cookie-es 2.0.0 → 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.
Files changed (4) hide show
  1. package/README.md +118 -10
  2. package/dist/index.d.mts +217 -195
  3. package/dist/index.mjs +395 -250
  4. package/package.json +24 -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,238 @@
1
+ //#region src/cookie/types.d.ts
1
2
  /**
2
- * Basic HTTP cookie parser and serializer for HTTP servers.
3
+ * Parse options.
3
4
  */
5
+ interface CookieParseOptions {
6
+ /**
7
+ * Specifies a function that will be used to decode a [cookie-value](https://datatracker.ietf.org/doc/html/rfc6265#section-4.1.1).
8
+ * Since the value of a cookie has a limited character set (and must be a simple string), this function can be used to decode
9
+ * a previously-encoded cookie value into a JavaScript string.
10
+ *
11
+ * The default function is the global `decodeURIComponent`, wrapped in a `try..catch`. If an error
12
+ * is thrown it will return the cookie's original value. If you provide your own encode/decode
13
+ * scheme you must ensure errors are appropriately handled.
14
+ *
15
+ * @default decode
16
+ */
17
+ decode?: (str: string) => string | undefined;
18
+ /**
19
+ * Custom function to filter parsing specific keys.
20
+ */
21
+ filter?(key: string): boolean;
22
+ /**
23
+ * When enabled, duplicate cookie names will return an array of values
24
+ * instead of only the first value.
25
+ */
26
+ allowMultiple?: boolean;
27
+ }
28
+ /**
29
+ * Cookies object.
30
+ */
31
+ type Cookies = Record<string, string | undefined>;
4
32
  /**
5
- * Additional serialization options
33
+ * Cookies object when `allowMultiple` is enabled.
6
34
  */
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;
35
+ type MultiCookies = Record<string, string | string[] | undefined>;
36
+ /**
37
+ * Stringify options.
38
+ */
39
+ interface CookieStringifyOptions {
40
+ /**
41
+ * Specifies a function that will be used to encode a [cookie-value](https://datatracker.ietf.org/doc/html/rfc6265#section-4.1.1).
42
+ * Since value of a cookie has a limited character set (and must be a simple string), this function can be used to encode
43
+ * a value into a string suited for a cookie's value, and should mirror `decode` when parsing.
44
+ *
45
+ * @default encodeURIComponent
46
+ */
47
+ encode?: (str: string) => string;
113
48
  }
114
49
  /**
115
- * Additional parsing options
50
+ * Set-Cookie object.
116
51
  */
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;
52
+ interface SetCookie {
53
+ /**
54
+ * Specifies the name of the cookie.
55
+ */
56
+ name: string;
57
+ /**
58
+ * Specifies the string to be the value for the cookie.
59
+ */
60
+ value: string | undefined;
61
+ /**
62
+ * 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).
63
+ *
64
+ * The [cookie storage model specification](https://tools.ietf.org/html/rfc6265#section-5.3) states that if both `expires` and
65
+ * `maxAge` are set, then `maxAge` takes precedence, but it is possible not all clients by obey this,
66
+ * so if both are set, they should point to the same date and time.
67
+ */
68
+ maxAge?: number;
69
+ /**
70
+ * Specifies the `Date` object to be the value for the [`Expires` `Set-Cookie` attribute](https://tools.ietf.org/html/rfc6265#section-5.2.1).
71
+ * When no expiration is set, clients consider this a "non-persistent cookie" and delete it when the current session is over.
72
+ *
73
+ * The [cookie storage model specification](https://tools.ietf.org/html/rfc6265#section-5.3) states that if both `expires` and
74
+ * `maxAge` are set, then `maxAge` takes precedence, but it is possible not all clients by obey this,
75
+ * so if both are set, they should point to the same date and time.
76
+ */
77
+ expires?: Date;
78
+ /**
79
+ * Specifies the value for the [`Domain` `Set-Cookie` attribute](https://tools.ietf.org/html/rfc6265#section-5.2.3).
80
+ * When no domain is set, clients consider the cookie to apply to the current domain only.
81
+ */
82
+ domain?: string;
83
+ /**
84
+ * Specifies the value for the [`Path` `Set-Cookie` attribute](https://tools.ietf.org/html/rfc6265#section-5.2.4).
85
+ * When no path is set, the path is considered the ["default path"](https://tools.ietf.org/html/rfc6265#section-5.1.4).
86
+ */
87
+ path?: string;
88
+ /**
89
+ * Enables the [`HttpOnly` `Set-Cookie` attribute](https://tools.ietf.org/html/rfc6265#section-5.2.6).
90
+ * When enabled, clients will not allow client-side JavaScript to see the cookie in `document.cookie`.
91
+ */
92
+ httpOnly?: boolean;
93
+ /**
94
+ * Enables the [`Secure` `Set-Cookie` attribute](https://tools.ietf.org/html/rfc6265#section-5.2.5).
95
+ * When enabled, clients will only send the cookie back if the browser has an HTTPS connection.
96
+ */
97
+ secure?: boolean;
98
+ /**
99
+ * Enables the [`Partitioned` `Set-Cookie` attribute](https://tools.ietf.org/html/draft-cutler-httpbis-partitioned-cookies/).
100
+ * When enabled, clients will only send the cookie back when the current domain _and_ top-level domain matches.
101
+ *
102
+ * This is an attribute that has not yet been fully standardized, and may change in the future.
103
+ * This also means clients may ignore this attribute until they understand it. More information
104
+ * about can be found in [the proposal](https://github.com/privacycg/CHIPS).
105
+ */
106
+ partitioned?: boolean;
107
+ /**
108
+ * Specifies the value for the [`Priority` `Set-Cookie` attribute](https://tools.ietf.org/html/draft-west-cookie-priority-00#section-4.1).
109
+ *
110
+ * - `'low'` will set the `Priority` attribute to `Low`.
111
+ * - `'medium'` will set the `Priority` attribute to `Medium`, the default priority when not set.
112
+ * - `'high'` will set the `Priority` attribute to `High`.
113
+ *
114
+ * More information about priority levels can be found in [the specification](https://tools.ietf.org/html/draft-west-cookie-priority-00#section-4.1).
115
+ */
116
+ priority?: "low" | "medium" | "high";
117
+ /**
118
+ * Specifies the value for the [`SameSite` `Set-Cookie` attribute](https://tools.ietf.org/html/draft-ietf-httpbis-rfc6265bis-09#section-5.4.7).
119
+ *
120
+ * - `true` will set the `SameSite` attribute to `Strict` for strict same site enforcement.
121
+ * - `'lax'` will set the `SameSite` attribute to `Lax` for lax same site enforcement.
122
+ * - `'none'` will set the `SameSite` attribute to `None` for an explicit cross-site cookie.
123
+ * - `'strict'` will set the `SameSite` attribute to `Strict` for strict same site enforcement.
124
+ *
125
+ * 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).
126
+ */
127
+ sameSite?: boolean | "lax" | "strict" | "none";
135
128
  }
136
-
137
129
  /**
138
- * Parse an HTTP Cookie header string and returning an object of all cookie
139
- * name-value pairs.
130
+ * Backward compatibility serialize options.
131
+ */
132
+ type CookieSerializeOptions = CookieStringifyOptions & Omit<SetCookie, "name" | "value">;
133
+ //#endregion
134
+ //#region src/cookie/parse.d.ts
135
+ /**
136
+ * Parse a `Cookie` header.
140
137
  *
141
- * @param str the string representing a `Cookie` header value
142
- * @param [options] object containing parsing options
138
+ * Parse the given cookie header string into an object
139
+ * The object has the various cookies as keys(names) => values
143
140
  */
144
- declare function parse(str: string, options?: CookieParseOptions): Record<string, string>;
145
-
141
+ declare function parse(str: string, options: CookieParseOptions & {
142
+ allowMultiple: true;
143
+ }): MultiCookies;
144
+ declare function parse(str: string, options?: CookieParseOptions): Cookies;
145
+ //#endregion
146
+ //#region src/cookie/serialize.d.ts
146
147
  /**
147
- * Serialize a cookie name-value pair into a `Set-Cookie` header string.
148
+ * Stringifies an object into an HTTP `Cookie` header.
149
+ */
150
+ declare function stringifyCookie(cookie: Cookies, options?: CookieStringifyOptions): string;
151
+ /**
152
+ * Serialize data into a cookie header.
153
+ *
154
+ * Serialize a name value pair into a cookie string suitable for
155
+ * http headers. An optional options object specifies cookie parameters.
148
156
  *
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
157
+ * serialize('foo', 'bar', { httpOnly: true })
158
+ * => "foo=bar; httpOnly"
153
159
  */
154
- declare function serialize(name: string, value: string, options?: CookieSerializeOptions): string;
155
-
160
+ declare function serialize(cookie: SetCookie, options?: CookieStringifyOptions): string;
161
+ declare function serialize(name: string, val: string, options?: CookieSerializeOptions): string;
162
+ //#endregion
163
+ //#region src/set-cookie/types.d.ts
156
164
  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);
165
+ /**
166
+ * Custom decode function to use on cookie values.
167
+ *
168
+ * By default, `decodeURIComponent` is used.
169
+ *
170
+ * **Note:** If decoding fails, the original (undecoded) value will be used
171
+ */
172
+ decode?: false | ((value: string) => string);
165
173
  }
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;
174
+ interface SetCookie$1 {
175
+ /**
176
+ * Cookie name
177
+ */
178
+ name: string;
179
+ /**
180
+ * Cookie value
181
+ */
182
+ value: string;
183
+ /**
184
+ * Cookie path
185
+ */
186
+ path?: string | undefined;
187
+ /**
188
+ * Absolute expiration date for the cookie
189
+ */
190
+ expires?: Date | undefined;
191
+ /**
192
+ * Relative max age of the cookie in seconds from when the client receives it (integer or undefined)
193
+ *
194
+ * Note: when using with express's res.cookie() method, multiply maxAge by 1000 to convert to milliseconds
195
+ */
196
+ maxAge?: number | undefined;
197
+ /**
198
+ * Domain for the cookie,
199
+ * May begin with "." to indicate the named domain or any subdomain of it
200
+ */
201
+ domain?: string | undefined;
202
+ /**
203
+ * Indicates that this cookie should only be sent over HTTPs
204
+ */
205
+ secure?: boolean | undefined;
206
+ /**
207
+ * Indicates that this cookie should not be accessible to client-side JavaScript
208
+ */
209
+ httpOnly?: boolean | undefined;
210
+ /**
211
+ * Indicates a cookie ought not to be sent along with cross-site requests
212
+ */
213
+ sameSite?: true | false | "lax" | "strict" | "none" | undefined;
214
+ /**
215
+ * Indicates that the cookie should be stored using partitioned storage
216
+ *
217
+ * See https://developer.mozilla.org/en-US/docs/Web/Privacy/Privacy_sandbox/Partitioned_cookies
218
+ */
219
+ partitioned?: boolean | undefined;
220
+ /**
221
+ * Indicates the priority of the cookie
222
+ *
223
+ * See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#prioritylow_medium_high
224
+ */
225
+ priority?: "low" | "medium" | "high" | undefined;
226
+ [key: string]: unknown;
207
227
  }
208
-
228
+ //#endregion
229
+ //#region src/set-cookie/parse.d.ts
209
230
  /**
210
231
  * Parse a [Set-Cookie](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie) header string into an object.
211
232
  */
212
- declare function parseSetCookie(setCookieValue: string, options?: SetCookieParseOptions): SetCookie;
213
-
233
+ declare function parseSetCookie(str: string, options?: SetCookieParseOptions): SetCookie$1 | undefined;
234
+ //#endregion
235
+ //#region src/set-cookie/split.d.ts
214
236
  /**
215
237
  * Set-Cookie header field-values are sometimes comma joined in one string. This splits them without choking on commas
216
238
  * that are within a single set-cookie field-value, such as in the Expires portion.
@@ -218,5 +240,5 @@ declare function parseSetCookie(setCookieValue: string, options?: SetCookieParse
218
240
  * See https://tools.ietf.org/html/rfc2616#section-4.2
219
241
  */
220
242
  declare function splitSetCookieString(cookiesString: string | string[]): string[];
221
-
222
- export { type CookieParseOptions, type CookieSerializeOptions, type SetCookie, type SetCookieParseOptions, parse, parseSetCookie, serialize, splitSetCookieString };
243
+ //#endregion
244
+ 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,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));
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 };
package/package.json CHANGED
@@ -1,37 +1,38 @@
1
1
  {
2
2
  "name": "cookie-es",
3
- "version": "2.0.0",
4
- "repository": "unjs/cookie-es",
3
+ "version": "3.0.0",
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
+ "mitata": "^1.0.34",
31
+ "obuild": "^0.4.32",
32
+ "oxfmt": "^0.41.0",
33
+ "oxlint": "^1.56.0",
34
+ "typescript": "^6.0.2",
35
+ "vitest": "^4.1.1"
35
36
  },
36
- "packageManager": "pnpm@10.5.2"
37
+ "packageManager": "pnpm@10.32.1"
37
38
  }