UNPKG

12.8 kBTypeScriptView Raw
1import type { SerializedCookie } from './constants';
2/**
3 * Optional configuration to be used when parsing cookies.
4 * @public
5 */
6export interface ParseCookieOptions {
7 /**
8 * If `true` then keyless cookies like `=abc` and `=` which are not RFC-compliant will be parsed.
9 */
10 loose?: boolean | undefined;
11}
12/**
13 * Configurable values that can be set when creating a {@link Cookie}.
14 * @public
15 */
16export interface CreateCookieOptions {
17 /** {@inheritDoc Cookie.key} */
18 key?: string;
19 /** {@inheritDoc Cookie.value} */
20 value?: string;
21 /** {@inheritDoc Cookie.expires} */
22 expires?: Date | 'Infinity' | null;
23 /** {@inheritDoc Cookie.maxAge} */
24 maxAge?: number | 'Infinity' | '-Infinity' | null;
25 /** {@inheritDoc Cookie.domain} */
26 domain?: string | null;
27 /** {@inheritDoc Cookie.path} */
28 path?: string | null;
29 /** {@inheritDoc Cookie.secure} */
30 secure?: boolean;
31 /** {@inheritDoc Cookie.httpOnly} */
32 httpOnly?: boolean;
33 /** {@inheritDoc Cookie.extensions} */
34 extensions?: string[] | null;
35 /** {@inheritDoc Cookie.creation} */
36 creation?: Date | 'Infinity' | null;
37 /** {@inheritDoc Cookie.hostOnly} */
38 hostOnly?: boolean | null;
39 /** {@inheritDoc Cookie.pathIsDefault} */
40 pathIsDefault?: boolean | null;
41 /** {@inheritDoc Cookie.lastAccessed} */
42 lastAccessed?: Date | 'Infinity' | null;
43 /** {@inheritDoc Cookie.sameSite} */
44 sameSite?: string | undefined;
45}
46/**
47 * An HTTP cookie (web cookie, browser cookie) is a small piece of data that a server sends to a user's web browser.
48 * It is defined in {@link https://www.rfc-editor.org/rfc/rfc6265.html | RFC6265}.
49 * @public
50 */
51export declare class Cookie {
52 /**
53 * The name or key of the cookie
54 */
55 key: string;
56 /**
57 * The value of the cookie
58 */
59 value: string;
60 /**
61 * The 'Expires' attribute of the cookie
62 * (See {@link https://www.rfc-editor.org/rfc/rfc6265.html#section-5.2.1 | RFC6265 Section 5.2.1}).
63 */
64 expires: Date | 'Infinity' | null;
65 /**
66 * The 'Max-Age' attribute of the cookie
67 * (See {@link https://www.rfc-editor.org/rfc/rfc6265.html#section-5.2.2 | RFC6265 Section 5.2.2}).
68 */
69 maxAge: number | 'Infinity' | '-Infinity' | null;
70 /**
71 * The 'Domain' attribute of the cookie represents the domain the cookie belongs to
72 * (See {@link https://www.rfc-editor.org/rfc/rfc6265.html#section-5.2.3 | RFC6265 Section 5.2.3}).
73 */
74 domain: string | null;
75 /**
76 * The 'Path' attribute of the cookie represents the path of the cookie
77 * (See {@link https://www.rfc-editor.org/rfc/rfc6265.html#section-5.2.4 | RFC6265 Section 5.2.4}).
78 */
79 path: string | null;
80 /**
81 * The 'Secure' flag of the cookie indicates if the scope of the cookie is
82 * limited to secure channels (e.g.; HTTPS) or not
83 * (See {@link https://www.rfc-editor.org/rfc/rfc6265.html#section-5.2.5 | RFC6265 Section 5.2.5}).
84 */
85 secure: boolean;
86 /**
87 * The 'HttpOnly' flag of the cookie indicates if the cookie is inaccessible to
88 * client scripts or not
89 * (See {@link https://www.rfc-editor.org/rfc/rfc6265.html#section-5.2.6 | RFC6265 Section 5.2.6}).
90 */
91 httpOnly: boolean;
92 /**
93 * Contains attributes which are not part of the defined spec but match the `extension-av` syntax
94 * defined in Section 4.1.1 of RFC6265
95 * (See {@link https://www.rfc-editor.org/rfc/rfc6265.html#section-4.1.1 | RFC6265 Section 4.1.1}).
96 */
97 extensions: string[] | null;
98 /**
99 * Set to the date and time when a Cookie is initially stored or a matching cookie is
100 * received that replaces an existing cookie
101 * (See {@link https://www.rfc-editor.org/rfc/rfc6265.html#section-5.3 | RFC6265 Section 5.3}).
102 *
103 * Also used to maintain ordering among cookies. Among cookies that have equal-length path fields,
104 * cookies with earlier creation-times are listed before cookies with later creation-times
105 * (See {@link https://www.rfc-editor.org/rfc/rfc6265.html#section-5.4 | RFC6265 Section 5.4}).
106 */
107 creation: Date | 'Infinity' | null;
108 /**
109 * A global counter used to break ordering ties between two cookies that have equal-length path fields
110 * and the same creation-time.
111 */
112 creationIndex: number;
113 /**
114 * A boolean flag indicating if a cookie is a host-only cookie (i.e.; when the request's host exactly
115 * matches the domain of the cookie) or not
116 * (See {@link https://www.rfc-editor.org/rfc/rfc6265.html#section-5.3 | RFC6265 Section 5.3}).
117 */
118 hostOnly: boolean | null;
119 /**
120 * A boolean flag indicating if a cookie had no 'Path' attribute and the default path
121 * was used
122 * (See {@link https://www.rfc-editor.org/rfc/rfc6265.html#section-5.2.4 | RFC6265 Section 5.2.4}).
123 */
124 pathIsDefault: boolean | null;
125 /**
126 * Set to the date and time when a cookie was initially stored ({@link https://www.rfc-editor.org/rfc/rfc6265.html#section-5.3 | RFC6265 Section 5.3}) and updated whenever
127 * the cookie is retrieved from the {@link CookieJar} ({@link https://www.rfc-editor.org/rfc/rfc6265.html#section-5.4 | RFC6265 Section 5.4}).
128 */
129 lastAccessed: Date | 'Infinity' | null;
130 /**
131 * The 'SameSite' attribute of a cookie as defined in RFC6265bis
132 * (See {@link https://www.ietf.org/archive/id/draft-ietf-httpbis-rfc6265bis-13.html#section-5.2 | RFC6265bis (v13) Section 5.2 }).
133 */
134 sameSite: string | undefined;
135 /**
136 * Create a new Cookie instance.
137 * @public
138 * @param options - The attributes to set on the cookie
139 */
140 constructor(options?: CreateCookieOptions);
141 /**
142 * For convenience in using `JSON.stringify(cookie)`. Returns a plain-old Object that can be JSON-serialized.
143 *
144 * @remarks
145 * - Any `Date` properties (such as {@link Cookie.expires}, {@link Cookie.creation}, and {@link Cookie.lastAccessed}) are exported in ISO format (`Date.toISOString()`).
146 *
147 * - Custom Cookie properties are discarded. In tough-cookie 1.x, since there was no {@link Cookie.toJSON} method explicitly defined, all enumerable properties were captured.
148 * If you want a property to be serialized, add the property name to {@link Cookie.serializableProperties}.
149 */
150 toJSON(): SerializedCookie;
151 /**
152 * Does a deep clone of this cookie, implemented exactly as `Cookie.fromJSON(cookie.toJSON())`.
153 * @public
154 */
155 clone(): Cookie | undefined;
156 /**
157 * Validates cookie attributes for semantic correctness. Useful for "lint" checking any `Set-Cookie` headers you generate.
158 * For now, it returns a boolean, but eventually could return a reason string.
159 *
160 * @remarks
161 * Works for a few things, but is by no means comprehensive.
162 *
163 * @beta
164 */
165 validate(): boolean;
166 /**
167 * Sets the 'Expires' attribute on a cookie.
168 *
169 * @remarks
170 * When given a `string` value it will be parsed with {@link parseDate}. If the value can't be parsed as a cookie date
171 * then the 'Expires' attribute will be set to `"Infinity"`.
172 *
173 * @param exp - the new value for the 'Expires' attribute of the cookie.
174 */
175 setExpires(exp: string | Date): void;
176 /**
177 * Sets the 'Max-Age' attribute (in seconds) on a cookie.
178 *
179 * @remarks
180 * Coerces `-Infinity` to `"-Infinity"` and `Infinity` to `"Infinity"` so it can be serialized to JSON.
181 *
182 * @param age - the new value for the 'Max-Age' attribute (in seconds).
183 */
184 setMaxAge(age: number): void;
185 /**
186 * Encodes to a `Cookie` header value (specifically, the {@link Cookie.key} and {@link Cookie.value} properties joined with "=").
187 * @public
188 */
189 cookieString(): string;
190 /**
191 * Encodes to a `Set-Cookie header` value.
192 * @public
193 */
194 toString(): string;
195 /**
196 * Computes the TTL relative to now (milliseconds).
197 *
198 * @remarks
199 * - `Infinity` is returned for cookies without an explicit expiry
200 *
201 * - `0` is returned if the cookie is expired.
202 *
203 * - Otherwise a time-to-live in milliseconds is returned.
204 *
205 * @param now - passing an explicit value is mostly used for testing purposes since this defaults to the `Date.now()`
206 * @public
207 */
208 TTL(now?: number): number;
209 /**
210 * Computes the absolute unix-epoch milliseconds that this cookie expires.
211 *
212 * The "Max-Age" attribute takes precedence over "Expires" (as per the RFC). The {@link Cookie.lastAccessed} attribute
213 * (or the `now` parameter if given) is used to offset the {@link Cookie.maxAge} attribute.
214 *
215 * If Expires ({@link Cookie.expires}) is set, that's returned.
216 *
217 * @param now - can be used to provide a time offset (instead of {@link Cookie.lastAccessed}) to use when calculating the "Max-Age" value
218 */
219 expiryTime(now?: Date): number | undefined;
220 /**
221 * Similar to {@link Cookie.expiryTime}, computes the absolute unix-epoch milliseconds that this cookie expires and returns it as a Date.
222 *
223 * The "Max-Age" attribute takes precedence over "Expires" (as per the RFC). The {@link Cookie.lastAccessed} attribute
224 * (or the `now` parameter if given) is used to offset the {@link Cookie.maxAge} attribute.
225 *
226 * If Expires ({@link Cookie.expires}) is set, that's returned.
227 *
228 * @param now - can be used to provide a time offset (instead of {@link Cookie.lastAccessed}) to use when calculating the "Max-Age" value
229 */
230 expiryDate(now?: Date): Date | undefined;
231 /**
232 * Indicates if the cookie has been persisted to a store or not.
233 * @public
234 */
235 isPersistent(): boolean;
236 /**
237 * Calls {@link canonicalDomain} with the {@link Cookie.domain} property.
238 * @public
239 */
240 canonicalizedDomain(): string | undefined;
241 /**
242 * Alias for {@link Cookie.canonicalizedDomain}
243 * @public
244 */
245 cdomain(): string | undefined;
246 /**
247 * Parses a string into a Cookie object.
248 *
249 * @remarks
250 * Note: when parsing a `Cookie` header it must be split by ';' before each Cookie string can be parsed.
251 *
252 * @example
253 * ```
254 * // parse a `Set-Cookie` header
255 * const setCookieHeader = 'a=bcd; Expires=Tue, 18 Oct 2011 07:05:03 GMT'
256 * const cookie = Cookie.parse(setCookieHeader)
257 * cookie.key === 'a'
258 * cookie.value === 'bcd'
259 * cookie.expires === new Date(Date.parse('Tue, 18 Oct 2011 07:05:03 GMT'))
260 * ```
261 *
262 * @example
263 * ```
264 * // parse a `Cookie` header
265 * const cookieHeader = 'name=value; name2=value2; name3=value3'
266 * const cookies = cookieHeader.split(';').map(Cookie.parse)
267 * cookies[0].name === 'name'
268 * cookies[0].value === 'value'
269 * cookies[1].name === 'name2'
270 * cookies[1].value === 'value2'
271 * cookies[2].name === 'name3'
272 * cookies[2].value === 'value3'
273 * ```
274 *
275 * @param str - The `Set-Cookie` header or a Cookie string to parse.
276 * @param options - Configures `strict` or `loose` mode for cookie parsing
277 */
278 static parse(str: string, options?: ParseCookieOptions): Cookie | undefined;
279 /**
280 * Does the reverse of {@link Cookie.toJSON}.
281 *
282 * @remarks
283 * Any Date properties (such as .expires, .creation, and .lastAccessed) are parsed via Date.parse, not tough-cookie's parseDate, since ISO timestamps are being handled at this layer.
284 *
285 * @example
286 * ```
287 * const json = JSON.stringify({
288 * key: 'alpha',
289 * value: 'beta',
290 * domain: 'example.com',
291 * path: '/foo',
292 * expires: '2038-01-19T03:14:07.000Z',
293 * })
294 * const cookie = Cookie.fromJSON(json)
295 * cookie.key === 'alpha'
296 * cookie.value === 'beta'
297 * cookie.domain === 'example.com'
298 * cookie.path === '/foo'
299 * cookie.expires === new Date(Date.parse('2038-01-19T03:14:07.000Z'))
300 * ```
301 *
302 * @param str - An unparsed JSON string or a value that has already been parsed as JSON
303 */
304 static fromJSON(str: unknown): Cookie | undefined;
305 private static cookiesCreated;
306 /**
307 * @internal
308 */
309 static sameSiteLevel: {
310 readonly strict: 3;
311 readonly lax: 2;
312 readonly none: 1;
313 };
314 /**
315 * @internal
316 */
317 static sameSiteCanonical: {
318 readonly strict: "Strict";
319 readonly lax: "Lax";
320 };
321 /**
322 * Cookie properties that will be serialized when using {@link Cookie.fromJSON} and {@link Cookie.toJSON}.
323 * @public
324 */
325 static serializableProperties: readonly ["key", "value", "expires", "maxAge", "domain", "path", "secure", "httpOnly", "extensions", "hostOnly", "pathIsDefault", "creation", "lastAccessed", "sameSite"];
326}