UNPKG

2.57 kBTypeScriptView Raw
1import type { Cookie } from './cookie';
2/**
3 * A comparison function that can be used with {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort | Array.sort()},
4 * which orders a list of cookies into the recommended order given in Step 2 of {@link https://www.rfc-editor.org/rfc/rfc6265.html#section-5.4 | RFC6265 - Section 5.4}.
5 *
6 * The sort algorithm is, in order of precedence:
7 *
8 * - Longest {@link Cookie.path}
9 *
10 * - Oldest {@link Cookie.creation} (which has a 1-ms precision, same as Date)
11 *
12 * - Lowest {@link Cookie.creationIndex} (to get beyond the 1-ms precision)
13 *
14 * @remarks
15 * ### RFC6265 - Section 5.4 - Step 2
16 *
17 * The user agent SHOULD sort the cookie-list in the following order:
18 *
19 * - Cookies with longer paths are listed before cookies with shorter paths.
20 *
21 * - Among cookies that have equal-length path fields, cookies with
22 * earlier creation-times are listed before cookies with later
23 * creation-times.
24 *
25 * NOTE: Not all user agents sort the cookie-list in this order, but
26 * this order reflects common practice when this document was
27 * written, and, historically, there have been servers that
28 * (erroneously) depended on this order.
29 *
30 * ### Custom Store Implementors
31 *
32 * Since the JavaScript Date is limited to a 1-ms precision, cookies within the same millisecond are entirely possible.
33 * This is especially true when using the `now` option to `CookieJar.setCookie(...)`. The {@link Cookie.creationIndex}
34 * property is a per-process global counter, assigned during construction with `new Cookie()`, which preserves the spirit
35 * of the RFC sorting: older cookies go first. This works great for {@link MemoryCookieStore} since `Set-Cookie` headers
36 * are parsed in order, but is not so great for distributed systems.
37 *
38 * Sophisticated Stores may wish to set this to some other
39 * logical clock so that if cookies `A` and `B` are created in the same millisecond, but cookie `A` is created before
40 * cookie `B`, then `A.creationIndex < B.creationIndex`.
41 *
42 * @example
43 * ```
44 * const cookies = [
45 * new Cookie({ key: 'a', value: '' }),
46 * new Cookie({ key: 'b', value: '' }),
47 * new Cookie({ key: 'c', value: '', path: '/path' }),
48 * new Cookie({ key: 'd', value: '', path: '/path' }),
49 * ]
50 * cookies.sort(cookieCompare)
51 * // cookie sort order would be ['c', 'd', 'a', 'b']
52 * ```
53 *
54 * @param a - the first Cookie for comparison
55 * @param b - the second Cookie for comparison
56 * @public
57 */
58export declare function cookieCompare(a: Cookie, b: Cookie): number;