http-vary 0.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.
package/README.md ADDED
@@ -0,0 +1,156 @@
1
+ <br />
2
+
3
+ [![Issues](https://img.shields.io/github/issues/arthurfiorette/tinylibs?logo=github&label=Issues)](https://github.com/arthurfiorette/tinylibs/issues)
4
+ [![Stars](https://img.shields.io/github/stars/arthurfiorette/tinylibs?logo=github&label=Stars)](https://github.com/arthurfiorette/tinylibs/stargazers)
5
+ [![License](https://img.shields.io/github/license/arthurfiorette/tinylibs?logo=githu&label=License)](https://github.com/arthurfiorette/tinylibs/blob/main/LICENSE)
6
+ [![Codecov](https://codecov.io/gh/arthurfiorette/tinylibs/branch/main/graph/badge.svg?token=ML0KGCU0VM)](https://codecov.io/gh/arthurfiorette/tinylibs)
7
+ [![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2Farthurfiorette%2Ftinylibs.svg?type=shield)](https://app.fossa.com/projects/git%2Bgithub.com%2Farthurfiorette%2Ftinylibs?ref=badge_shield)
8
+ [![Join the chat at https://gitter.im/tinylibs-js-org/community](https://badges.gitter.im/tinylibs-js-org/community.svg)](https://gitter.im/tinylibs-js-org/community?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
9
+ [![Speed Blazing](https://img.shields.io/badge/speed-blazing%20%F0%9F%94%A5-brightgreen.svg)](https://twitter.com/acdlite/status/974390255393505280)
10
+
11
+ [![Latest Version](https://img.shields.io/npm/v/http-vary)](https://www.npmjs.com/package/http-vary)
12
+ [![Downloads](https://img.shields.io/npm/dw/http-vary)](https://www.npmjs.com/package/http-vary)
13
+ [![JsDelivr](https://data.jsdelivr.com/v1/package/npm/http-vary/badge?style=rounded)](https://www.jsdelivr.com/package/npm/http-vary)
14
+ [![Bundlephobia](https://img.shields.io/bundlephobia/minzip/http-vary/latest?style=flat)](https://bundlephobia.com/package/http-vary@latest)
15
+ [![Packagephobia](https://packagephobia.com/badge?p=http-vary@latest)](https://packagephobia.com/result?p=http-vary@latest)
16
+
17
+ <br />
18
+
19
+ <div align="center">
20
+ <pre>
21
+ <h1>⌛<br />HTTP Vary</h1>
22
+ </pre>
23
+ <br />
24
+ </div>
25
+
26
+ <h3 align="center">
27
+ <code>HTTP Vary</code> is a minimal parser and utility for the <a href="https://www.rfc-editor.org/rfc/rfc9110.html#name-vary" target="_blank">Vary</a> header (RFC 9110).
28
+ <br />
29
+ <br />
30
+ </h3>
31
+
32
+ <br />
33
+
34
+ ## Table of Contents
35
+
36
+ - [Table of Contents](#table-of-contents)
37
+ - [Installing](#installing)
38
+ - [Node](#node)
39
+ - [Browser](#browser)
40
+ - [Url Import](#url-import)
41
+ - [Getting Started](#getting-started)
42
+ - [Usage](#usage)
43
+ - [Understanding Wildcard Behavior](#understanding-wildcard-behavior)
44
+ - [License](#license)
45
+
46
+ <br />
47
+
48
+ ## Installing
49
+
50
+ ### Node
51
+
52
+ ```sh
53
+ npm install http-vary # or yarn add http-vary
54
+ ```
55
+
56
+ ```js
57
+ const { parse, compare } = require('http-vary');
58
+ import { parse, compare } from 'http-vary';
59
+ ```
60
+
61
+ ### Browser
62
+
63
+ ```html
64
+ <script
65
+ crossorigin
66
+ src="https://cdn.jsdelivr.net/npm/http-vary@latest/dist/index.umd.js"
67
+ ></script>
68
+ ```
69
+
70
+ ```js
71
+ const { parse, compare } = window.httpVary;
72
+ ```
73
+
74
+ ### Url Import
75
+
76
+ ```ts
77
+ import { parse, compare } from 'https://cdn.skypack.dev/http-vary@latest';
78
+ ```
79
+
80
+ <br />
81
+
82
+ ## Getting Started
83
+
84
+ This package is a parser and utility for the HTTP Vary header as defined in
85
+ [RFC 9110 Section 12.5.5](https://www.rfc-editor.org/rfc/rfc9110.html#name-vary). The Vary
86
+ header indicates which request headers affect the response, enabling proper HTTP caching
87
+ behavior. You can parse a Vary header string with [`parse()`](./src/parse.ts) and compare
88
+ request headers for cache equivalence with [`compare()`](./src/compare.ts).
89
+
90
+ All needed documentation is available in form of `TSDoc` comments.
91
+
92
+ ### Usage
93
+
94
+ ```ts
95
+ import { parse, compare, VaryHeader } from 'http-vary';
96
+
97
+ // Parse a Vary header
98
+ const rawHeader = 'Accept-Encoding, User-Agent';
99
+
100
+ const vary = parse(rawHeader);
101
+ // => ['accept-encoding', 'user-agent']
102
+
103
+ // Parse wildcard
104
+ const wildcardVary = parse('*');
105
+ // => '*'
106
+
107
+ // Compare headers for cache equivalence
108
+ const headers1 = {
109
+ 'Accept-Encoding': 'gzip',
110
+ 'User-Agent': 'Chrome'
111
+ };
112
+
113
+ const headers2 = {
114
+ 'Accept-Encoding': 'gzip',
115
+ 'User-Agent': 'Chrome',
116
+ Cookie: 'session=abc' // This header is ignored
117
+ };
118
+
119
+ const isEquivalent = compare(vary, headers1, headers2);
120
+ // => true (headers match for the fields specified in Vary)
121
+
122
+ // Case-insensitive header matching (per RFC 9110)
123
+ const headers3 = {
124
+ 'accept-encoding': 'gzip', // lowercase
125
+ 'USER-AGENT': 'Chrome' // uppercase
126
+ };
127
+
128
+ const caseInsensitiveMatch = compare(vary, headers1, headers3);
129
+ // => true (header names are matched case-insensitively)
130
+
131
+ // Wildcard always returns false
132
+ const wildcardMatch = compare('*', headers1, headers2);
133
+ // => false (wildcard indicates response varies on aspects beyond headers)
134
+ ```
135
+
136
+ <br />
137
+
138
+ ## Understanding Wildcard Behavior
139
+
140
+ Per [RFC 9110](https://www.rfc-editor.org/rfc/rfc9110.html#name-vary), `Vary: *` signals
141
+ that the response can vary based on **anything** about the request, including factors
142
+ beyond headers (e.g., client IP, time, server load, A/B testing). Since we cannot
143
+ determine if two requests would receive the same response, `compare()` always returns
144
+ `false` for wildcard, preventing incorrect cache hits.
145
+
146
+ **TL;DR**: `Vary: *` means "don't cache" - always consult the origin server.
147
+
148
+ <br />
149
+
150
+ ## License
151
+
152
+ Licensed under the **MIT**. See [`LICENSE`](LICENSE) for more informations.
153
+
154
+ [![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2Farthurfiorette%2Ftinylibs.svg?type=small)](https://app.fossa.com/projects/git%2Bgithub.com%2Farthurfiorette%2Ftinylibs?ref=badge_small)
155
+
156
+ <br />
@@ -0,0 +1,37 @@
1
+ import type { CompareHeaders, VaryHeader } from './types';
2
+ /**
3
+ * Checks if {@linkcode source} and {@linkcode target} headers are equivalent for the given
4
+ * Vary header, as per
5
+ * {@link https://www.rfc-editor.org/rfc/rfc9110.html#name-vary RFC 9110 Section 12.5.5}.
6
+ *
7
+ * This function determines if two requests would receive the same cached response based
8
+ * on the Vary header requirements.
9
+ *
10
+ * @remarks
11
+ * - Returns `false` for wildcard vary (`'*'`) as responses always differ
12
+ * - Header name matching is case-insensitive (per RFC 9110)
13
+ * - Missing headers are treated as `undefined`
14
+ * - String values are trimmed before comparison
15
+ * - Array values are converted to strings via `.toString()`
16
+ * - Uses loose equality (!=) for comparison
17
+ * - Empty strings are distinct from missing headers
18
+ *
19
+ * @example
20
+ *
21
+ * ```ts
22
+ * const vary = ['accept-encoding', 'user-agent'];
23
+ * const headers1 = { 'Accept-Encoding': 'gzip', 'User-Agent': 'Chrome' };
24
+ * const headers2 = { 'Accept-Encoding': 'gzip', 'User-Agent': 'Chrome' };
25
+ *
26
+ * compare(vary, headers1, headers2);
27
+ * // => true
28
+ * ```
29
+ *
30
+ * @param {VaryHeader} vary - The Vary header specifying which fields to compare
31
+ * @param {CompareHeaders} source - The first set of request headers
32
+ * @param {CompareHeaders} target - The second set of request headers
33
+ * @returns {boolean} `true` if the headers are equivalent for the given Vary header,
34
+ * `false` otherwise
35
+ */
36
+ export declare function compare(vary: VaryHeader, source: CompareHeaders, target: CompareHeaders): boolean;
37
+ //# sourceMappingURL=compare.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"compare.d.ts","sourceRoot":"","sources":["../src/compare.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AAE1D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AACH,wBAAgB,OAAO,CACrB,IAAI,EAAE,UAAU,EAChB,MAAM,EAAE,cAAc,EACtB,MAAM,EAAE,cAAc,GACrB,OAAO,CAoCT"}
@@ -0,0 +1,4 @@
1
+ export * from './compare';
2
+ export * from './parse';
3
+ export * from './types';
4
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,WAAW,CAAC;AAC1B,cAAc,SAAS,CAAC;AACxB,cAAc,SAAS,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ function r(r,e){(null==e||e>r.length)&&(e=r.length);for(var t=0,n=Array(e);t<e;t++)n[t]=r[t];return n}function e(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(n)return(n=n.call(e)).next.bind(n);if(Array.isArray(e)||(n=function(e,t){if(e){if("string"==typeof e)return r(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?r(e,t):void 0}}(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var o=0;return function(){return o>=e.length?{done:!0}:{done:!1,value:e[o++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var t=/^[a-z0-9-]+$/i;exports.compare=function(r,t,n){if("*"===r)return!1;for(var o,a=Object.keys(t),i=Object.keys(n),l=e(r);!(o=l()).done;){for(var u,f=o.value,v=void 0,s=void 0,c=e(a);!(u=c()).done;){var d=u.value;if(d.toLowerCase()===f){var y;v=null==(y=t[d])||null==(y=y.toString())?void 0:y.trim();break}}for(var m,b=e(i);!(m=b()).done;){var g=m.value;if(g.toLowerCase()===f){var p;s=null==(p=n[g])||null==(p=p.toString())?void 0:p.trim();break}}if(v!=s)return!1}return!0},exports.parse=function(r,e){if(void 0===e&&(e=16),"string"!=typeof r)return null;if(r.includes("*"))return"*";for(var n=new Set,o=0;o<r.length;o++){var a=r[o];if(" "!==a&&"\t"!==a&&","!==a){for(var i=o;o<r.length&&","!==r[o];)o++;var l=r.slice(i,o).trim().toLowerCase();if(0!==l.length&&t.test(l)&&(n.add(l),n.size>=e))break}}return 0===n.size?null:Array.from(n)};
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sources":["../src/parse.ts","../src/compare.ts"],"sourcesContent":["import type { VaryHeader } from './types';\n\nconst VALID_HEADER_NAME_REGEX = /^[a-z0-9-]+$/i;\n\n/**\n * Parses the Vary header as defined in\n * {@link https://www.rfc-editor.org/rfc/rfc9110.html#name-vary RFC 9110 Section 12.5.5}.\n *\n * The Vary header indicates which request headers a server considers when selecting or\n * generating a response, enabling proper HTTP caching behavior.\n *\n * @remarks\n * - Header field names are normalized to lowercase\n * - Duplicate fields are automatically deduplicated\n * - Invalid header names (per RFC 9110) are silently skipped\n * - If the header contains `'*'`, the function returns `'*'` (wildcard)\n * - Returns `null` for invalid input or when no valid fields are found\n *\n * @example\n *\n * ```ts\n * parse('Accept-Encoding, User-Agent');\n * // => ['accept-encoding', 'user-agent']\n *\n * parse('*');\n * // => '*'\n *\n * parse('Invalid Header!');\n * // => null\n * ```\n *\n * @param {string} headerStr - The Vary header value to parse (e.g., \"Accept-Encoding,\n * User-Agent\")\n * @param {number} [maxLength=16] - Maximum number of header fields to parse for DoS\n * protection. Default is `16`\n * @returns {VaryHeader | null} The parsed Vary header as an array of lowercase field\n * names, `'*'` for wildcard, or `null` if invalid.\n */\nexport function parse(headerStr?: string, maxLength = 16): VaryHeader | null {\n // Invalid header name\n if (typeof headerStr !== 'string') {\n return null;\n }\n\n // RFC says only '*' is valid alone, but some servers may send invalid headers like '*, Accept-Encoding'\n if (headerStr.includes('*')) {\n return '*';\n }\n\n const values = new Set<string>();\n\n for (let i = 0; i < headerStr.length; i++) {\n const char = headerStr[i];\n\n if (char === ' ' || char === '\\t' || char === ',') {\n continue;\n }\n\n const start = i;\n\n while (i < headerStr.length) {\n const char = headerStr[i];\n\n if (char === ',') {\n break;\n }\n\n i++;\n }\n\n const headerName = headerStr.slice(start, i).trim().toLowerCase();\n\n // Skip invalid header names\n if (headerName.length === 0 || !VALID_HEADER_NAME_REGEX.test(headerName)) {\n continue;\n }\n\n values.add(headerName);\n\n // DOS protection to avoid overly large vary headers\n if (values.size >= maxLength) {\n break;\n }\n }\n\n // Ensures no empty set is returned\n if (values.size === 0) {\n return null;\n }\n\n return Array.from(values);\n}\n","import type { CompareHeaders, VaryHeader } from './types';\n\n/**\n * Checks if {@linkcode source} and {@linkcode target} headers are equivalent for the given\n * Vary header, as per\n * {@link https://www.rfc-editor.org/rfc/rfc9110.html#name-vary RFC 9110 Section 12.5.5}.\n *\n * This function determines if two requests would receive the same cached response based\n * on the Vary header requirements.\n *\n * @remarks\n * - Returns `false` for wildcard vary (`'*'`) as responses always differ\n * - Header name matching is case-insensitive (per RFC 9110)\n * - Missing headers are treated as `undefined`\n * - String values are trimmed before comparison\n * - Array values are converted to strings via `.toString()`\n * - Uses loose equality (!=) for comparison\n * - Empty strings are distinct from missing headers\n *\n * @example\n *\n * ```ts\n * const vary = ['accept-encoding', 'user-agent'];\n * const headers1 = { 'Accept-Encoding': 'gzip', 'User-Agent': 'Chrome' };\n * const headers2 = { 'Accept-Encoding': 'gzip', 'User-Agent': 'Chrome' };\n *\n * compare(vary, headers1, headers2);\n * // => true\n * ```\n *\n * @param {VaryHeader} vary - The Vary header specifying which fields to compare\n * @param {CompareHeaders} source - The first set of request headers\n * @param {CompareHeaders} target - The second set of request headers\n * @returns {boolean} `true` if the headers are equivalent for the given Vary header,\n * `false` otherwise\n */\nexport function compare(\n vary: VaryHeader,\n source: CompareHeaders,\n target: CompareHeaders\n): boolean {\n // Wildcard always differs\n if (vary === '*') {\n return false;\n }\n\n const sourceKeys = Object.keys(source);\n const targetKeys = Object.keys(target);\n\n for (const field of vary) {\n let sourceValue: string | undefined;\n let targetValue: string | undefined;\n\n // Case-insensitive header lookup in source\n for (const key of sourceKeys) {\n if (key.toLowerCase() === field) {\n sourceValue = source[key]?.toString()?.trim();\n break;\n }\n }\n\n // Case-insensitive header lookup in target\n for (const key of targetKeys) {\n if (key.toLowerCase() === field) {\n targetValue = target[key]?.toString()?.trim();\n break;\n }\n }\n\n // biome-ignore lint/suspicious/noDoubleEquals: Intentional loose comparison\n if (sourceValue != targetValue) {\n return false;\n }\n }\n\n return true;\n}\n"],"names":["VALID_HEADER_NAME_REGEX","vary","source","target","_step","sourceKeys","Object","keys","targetKeys","_iterator","_createForOfIteratorHelperLoose","done","_step2","field","value","sourceValue","targetValue","_iterator2","key","toLowerCase","_source$key","toString","trim","_step3","_iterator3","_target$_key","headerStr","maxLength","includes","values","Set","i","length","char","start","headerName","slice","test","add","size","Array","from"],"mappings":"oyBAEA,IAAMA,EAA0B,yCCmC9BC,EACAC,EACAC,GAGA,GAAa,MAATF,EACF,OACF,EAKA,IAHA,IAGwBG,EAHlBC,EAAaC,OAAOC,KAAKL,GACzBM,EAAaF,OAAOC,KAAKJ,GAE/BM,EAAAC,EAAoBT,KAAIG,EAAAK,KAAAE,MAAE,CAKxB,IALS,IAKmBC,EALnBC,EAAKT,EAAAU,MACVC,OAA+B,EAC/BC,OAGJ,EAAAC,EAAAP,EAAkBL,KAAUO,EAAAK,KAAAN,MAAE,CAAA,IAAnBO,EAAGN,EAAAE,MACZ,GAAII,EAAIC,gBAAkBN,EAAO,CAAA,IAAAO,EAC/BL,SAAWK,EAAGlB,EAAOgB,KAAgB,OAAZE,EAAXA,EAAaC,iBAAU,EAAvBD,EAAyBE,OACvC,KACF,CACF,CAGA,IAAA,IAA4BC,EAA5BC,EAAAd,EAAkBF,KAAUe,EAAAC,KAAAb,MAAE,CAAnB,IAAAO,EAAGK,EAAAT,MACZ,GAAII,EAAIC,gBAAkBN,EAAO,CAAAY,IAAAA,EAC/BT,EAAyBS,OAAdA,EAAGtB,EAAOe,KAAPO,OAAWA,EAAXA,EAAaJ,iBAAbI,EAAAA,EAAyBH,OACvC,KACF,CACF,CAGA,GAAIP,GAAeC,EACjB,OACF,CACF,CAEA,OACF,CAAA,yBDtCsBU,EAAoBC,GAExC,YAFwCA,IAAAA,EAAY,IAE3B,iBAAdD,EACT,OACF,KAGA,GAAIA,EAAUE,SAAS,KACrB,MAAO,IAKT,IAFA,IAAMC,EAAS,IAAIC,IAEVC,EAAI,EAAGA,EAAIL,EAAUM,OAAQD,IAAK,CACzC,IAAME,EAAOP,EAAUK,GAEvB,GAAa,MAATE,GAAyB,OAATA,GAA0B,MAATA,EAArC,CAMA,IAFA,IAAMC,EAAQH,EAEPA,EAAIL,EAAUM,QAGN,MAFAN,EAAUK,IAMvBA,IAGF,IAAMI,EAAaT,EAAUU,MAAMF,EAAOH,GAAGT,OAAOH,cAGpD,GAA0B,IAAtBgB,EAAWH,QAAiBhC,EAAwBqC,KAAKF,KAI7DN,EAAOS,IAAIH,GAGPN,EAAOU,MAAQZ,GACjB,KAzBF,CA2BF,CAGA,OAAoB,IAAhBE,EAAOU,KACF,KAGFC,MAAMC,KAAKZ,EACpB"}
package/dist/index.mjs ADDED
@@ -0,0 +1,2 @@
1
+ function r(r,e){(null==e||e>r.length)&&(e=r.length);for(var t=0,n=Array(e);t<e;t++)n[t]=r[t];return n}function e(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(n)return(n=n.call(e)).next.bind(n);if(Array.isArray(e)||(n=function(e,t){if(e){if("string"==typeof e)return r(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?r(e,t):void 0}}(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var o=0;return function(){return o>=e.length?{done:!0}:{done:!1,value:e[o++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function t(r,t,n){if("*"===r)return!1;for(var o,a=Object.keys(t),i=Object.keys(n),l=e(r);!(o=l()).done;){for(var u,f=o.value,v=void 0,d=void 0,s=e(a);!(u=s()).done;){var c=u.value;if(c.toLowerCase()===f){var y;v=null==(y=t[c])||null==(y=y.toString())?void 0:y.trim();break}}for(var b,m=e(i);!(b=m()).done;){var g=b.value;if(g.toLowerCase()===f){var h;d=null==(h=n[g])||null==(h=h.toString())?void 0:h.trim();break}}if(v!=d)return!1}return!0}var n=/^[a-z0-9-]+$/i;function o(r,e){if(void 0===e&&(e=16),"string"!=typeof r)return null;if(r.includes("*"))return"*";for(var t=new Set,o=0;o<r.length;o++){var a=r[o];if(" "!==a&&"\t"!==a&&","!==a){for(var i=o;o<r.length&&","!==r[o];)o++;var l=r.slice(i,o).trim().toLowerCase();if(0!==l.length&&n.test(l)&&(t.add(l),t.size>=e))break}}return 0===t.size?null:Array.from(t)}export{t as compare,o as parse};
2
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","sources":["../src/compare.ts","../src/parse.ts"],"sourcesContent":["import type { CompareHeaders, VaryHeader } from './types';\n\n/**\n * Checks if {@linkcode source} and {@linkcode target} headers are equivalent for the given\n * Vary header, as per\n * {@link https://www.rfc-editor.org/rfc/rfc9110.html#name-vary RFC 9110 Section 12.5.5}.\n *\n * This function determines if two requests would receive the same cached response based\n * on the Vary header requirements.\n *\n * @remarks\n * - Returns `false` for wildcard vary (`'*'`) as responses always differ\n * - Header name matching is case-insensitive (per RFC 9110)\n * - Missing headers are treated as `undefined`\n * - String values are trimmed before comparison\n * - Array values are converted to strings via `.toString()`\n * - Uses loose equality (!=) for comparison\n * - Empty strings are distinct from missing headers\n *\n * @example\n *\n * ```ts\n * const vary = ['accept-encoding', 'user-agent'];\n * const headers1 = { 'Accept-Encoding': 'gzip', 'User-Agent': 'Chrome' };\n * const headers2 = { 'Accept-Encoding': 'gzip', 'User-Agent': 'Chrome' };\n *\n * compare(vary, headers1, headers2);\n * // => true\n * ```\n *\n * @param {VaryHeader} vary - The Vary header specifying which fields to compare\n * @param {CompareHeaders} source - The first set of request headers\n * @param {CompareHeaders} target - The second set of request headers\n * @returns {boolean} `true` if the headers are equivalent for the given Vary header,\n * `false` otherwise\n */\nexport function compare(\n vary: VaryHeader,\n source: CompareHeaders,\n target: CompareHeaders\n): boolean {\n // Wildcard always differs\n if (vary === '*') {\n return false;\n }\n\n const sourceKeys = Object.keys(source);\n const targetKeys = Object.keys(target);\n\n for (const field of vary) {\n let sourceValue: string | undefined;\n let targetValue: string | undefined;\n\n // Case-insensitive header lookup in source\n for (const key of sourceKeys) {\n if (key.toLowerCase() === field) {\n sourceValue = source[key]?.toString()?.trim();\n break;\n }\n }\n\n // Case-insensitive header lookup in target\n for (const key of targetKeys) {\n if (key.toLowerCase() === field) {\n targetValue = target[key]?.toString()?.trim();\n break;\n }\n }\n\n // biome-ignore lint/suspicious/noDoubleEquals: Intentional loose comparison\n if (sourceValue != targetValue) {\n return false;\n }\n }\n\n return true;\n}\n","import type { VaryHeader } from './types';\n\nconst VALID_HEADER_NAME_REGEX = /^[a-z0-9-]+$/i;\n\n/**\n * Parses the Vary header as defined in\n * {@link https://www.rfc-editor.org/rfc/rfc9110.html#name-vary RFC 9110 Section 12.5.5}.\n *\n * The Vary header indicates which request headers a server considers when selecting or\n * generating a response, enabling proper HTTP caching behavior.\n *\n * @remarks\n * - Header field names are normalized to lowercase\n * - Duplicate fields are automatically deduplicated\n * - Invalid header names (per RFC 9110) are silently skipped\n * - If the header contains `'*'`, the function returns `'*'` (wildcard)\n * - Returns `null` for invalid input or when no valid fields are found\n *\n * @example\n *\n * ```ts\n * parse('Accept-Encoding, User-Agent');\n * // => ['accept-encoding', 'user-agent']\n *\n * parse('*');\n * // => '*'\n *\n * parse('Invalid Header!');\n * // => null\n * ```\n *\n * @param {string} headerStr - The Vary header value to parse (e.g., \"Accept-Encoding,\n * User-Agent\")\n * @param {number} [maxLength=16] - Maximum number of header fields to parse for DoS\n * protection. Default is `16`\n * @returns {VaryHeader | null} The parsed Vary header as an array of lowercase field\n * names, `'*'` for wildcard, or `null` if invalid.\n */\nexport function parse(headerStr?: string, maxLength = 16): VaryHeader | null {\n // Invalid header name\n if (typeof headerStr !== 'string') {\n return null;\n }\n\n // RFC says only '*' is valid alone, but some servers may send invalid headers like '*, Accept-Encoding'\n if (headerStr.includes('*')) {\n return '*';\n }\n\n const values = new Set<string>();\n\n for (let i = 0; i < headerStr.length; i++) {\n const char = headerStr[i];\n\n if (char === ' ' || char === '\\t' || char === ',') {\n continue;\n }\n\n const start = i;\n\n while (i < headerStr.length) {\n const char = headerStr[i];\n\n if (char === ',') {\n break;\n }\n\n i++;\n }\n\n const headerName = headerStr.slice(start, i).trim().toLowerCase();\n\n // Skip invalid header names\n if (headerName.length === 0 || !VALID_HEADER_NAME_REGEX.test(headerName)) {\n continue;\n }\n\n values.add(headerName);\n\n // DOS protection to avoid overly large vary headers\n if (values.size >= maxLength) {\n break;\n }\n }\n\n // Ensures no empty set is returned\n if (values.size === 0) {\n return null;\n }\n\n return Array.from(values);\n}\n"],"names":["compare","vary","source","target","_step","sourceKeys","Object","keys","targetKeys","_iterator","_createForOfIteratorHelperLoose","done","_step2","field","value","sourceValue","targetValue","_iterator2","key","toLowerCase","_source$key","toString","trim","_step3","_iterator3","_target$_key","VALID_HEADER_NAME_REGEX","parse","headerStr","maxLength","includes","values","Set","i","length","char","start","headerName","slice","test","add","size","Array","from"],"mappings":"6yBAoCgBA,EACdC,EACAC,EACAC,GAGA,GAAa,MAATF,EACF,OACF,EAKA,IAHA,IAGwBG,EAHlBC,EAAaC,OAAOC,KAAKL,GACzBM,EAAaF,OAAOC,KAAKJ,GAE/BM,EAAAC,EAAoBT,KAAIG,EAAAK,KAAAE,MAAE,CAKxB,IALS,IAKmBC,EALnBC,EAAKT,EAAAU,MACVC,OAA+B,EAC/BC,OAGJ,EAAAC,EAAAP,EAAkBL,KAAUO,EAAAK,KAAAN,MAAE,CAAA,IAAnBO,EAAGN,EAAAE,MACZ,GAAII,EAAIC,gBAAkBN,EAAO,CAAA,IAAAO,EAC/BL,SAAWK,EAAGlB,EAAOgB,KAAgB,OAAZE,EAAXA,EAAaC,iBAAU,EAAvBD,EAAyBE,OACvC,KACF,CACF,CAGA,IAAA,IAA4BC,EAA5BC,EAAAd,EAAkBF,KAAUe,EAAAC,KAAAb,MAAE,CAAnB,IAAAO,EAAGK,EAAAT,MACZ,GAAII,EAAIC,gBAAkBN,EAAO,CAAAY,IAAAA,EAC/BT,EAAyBS,OAAdA,EAAGtB,EAAOe,KAAPO,OAAWA,EAAXA,EAAaJ,iBAAbI,EAAAA,EAAyBH,OACvC,KACF,CACF,CAGA,GAAIP,GAAeC,EACjB,OACF,CACF,CAEA,OACF,CAAA,CC1EA,IAAMU,EAA0B,yBAoChBC,EAAMC,EAAoBC,GAExC,YAFwCA,IAAAA,EAAY,IAE3B,iBAAdD,EACT,OACF,KAGA,GAAIA,EAAUE,SAAS,KACrB,MAAO,IAKT,IAFA,IAAMC,EAAS,IAAIC,IAEVC,EAAI,EAAGA,EAAIL,EAAUM,OAAQD,IAAK,CACzC,IAAME,EAAOP,EAAUK,GAEvB,GAAa,MAATE,GAAyB,OAATA,GAA0B,MAATA,EAArC,CAMA,IAFA,IAAMC,EAAQH,EAEPA,EAAIL,EAAUM,QAGN,MAFAN,EAAUK,IAMvBA,IAGF,IAAMI,EAAaT,EAAUU,MAAMF,EAAOH,GAAGX,OAAOH,cAGpD,GAA0B,IAAtBkB,EAAWH,QAAiBR,EAAwBa,KAAKF,KAI7DN,EAAOS,IAAIH,GAGPN,EAAOU,MAAQZ,GACjB,KAzBF,CA2BF,CAGA,OAAoB,IAAhBE,EAAOU,KACF,KAGFC,MAAMC,KAAKZ,EACpB"}
@@ -0,0 +1,2 @@
1
+ function t(t,n,r){if("*"===t)return!1;const e=Object.keys(n),o=Object.keys(r);for(const s of t){let t,l;for(const r of e)if(r.toLowerCase()===s){var i;t=null==(i=n[r])||null==(i=i.toString())?void 0:i.trim();break}for(const t of o)if(t.toLowerCase()===s){var f;l=null==(f=r[t])||null==(f=f.toString())?void 0:f.trim();break}if(t!=l)return!1}return!0}const n=/^[a-z0-9-]+$/i;function r(t,r=16){if("string"!=typeof t)return null;if(t.includes("*"))return"*";const e=new Set;for(let o=0;o<t.length;o++){const i=t[o];if(" "===i||"\t"===i||","===i)continue;const f=o;for(;o<t.length&&","!==t[o];)o++;const s=t.slice(f,o).trim().toLowerCase();if(0!==s.length&&n.test(s)&&(e.add(s),e.size>=r))break}return 0===e.size?null:Array.from(e)}export{t as compare,r as parse};
2
+ //# sourceMappingURL=index.modern.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.modern.mjs","sources":["../src/compare.ts","../src/parse.ts"],"sourcesContent":["import type { CompareHeaders, VaryHeader } from './types';\n\n/**\n * Checks if {@linkcode source} and {@linkcode target} headers are equivalent for the given\n * Vary header, as per\n * {@link https://www.rfc-editor.org/rfc/rfc9110.html#name-vary RFC 9110 Section 12.5.5}.\n *\n * This function determines if two requests would receive the same cached response based\n * on the Vary header requirements.\n *\n * @remarks\n * - Returns `false` for wildcard vary (`'*'`) as responses always differ\n * - Header name matching is case-insensitive (per RFC 9110)\n * - Missing headers are treated as `undefined`\n * - String values are trimmed before comparison\n * - Array values are converted to strings via `.toString()`\n * - Uses loose equality (!=) for comparison\n * - Empty strings are distinct from missing headers\n *\n * @example\n *\n * ```ts\n * const vary = ['accept-encoding', 'user-agent'];\n * const headers1 = { 'Accept-Encoding': 'gzip', 'User-Agent': 'Chrome' };\n * const headers2 = { 'Accept-Encoding': 'gzip', 'User-Agent': 'Chrome' };\n *\n * compare(vary, headers1, headers2);\n * // => true\n * ```\n *\n * @param {VaryHeader} vary - The Vary header specifying which fields to compare\n * @param {CompareHeaders} source - The first set of request headers\n * @param {CompareHeaders} target - The second set of request headers\n * @returns {boolean} `true` if the headers are equivalent for the given Vary header,\n * `false` otherwise\n */\nexport function compare(\n vary: VaryHeader,\n source: CompareHeaders,\n target: CompareHeaders\n): boolean {\n // Wildcard always differs\n if (vary === '*') {\n return false;\n }\n\n const sourceKeys = Object.keys(source);\n const targetKeys = Object.keys(target);\n\n for (const field of vary) {\n let sourceValue: string | undefined;\n let targetValue: string | undefined;\n\n // Case-insensitive header lookup in source\n for (const key of sourceKeys) {\n if (key.toLowerCase() === field) {\n sourceValue = source[key]?.toString()?.trim();\n break;\n }\n }\n\n // Case-insensitive header lookup in target\n for (const key of targetKeys) {\n if (key.toLowerCase() === field) {\n targetValue = target[key]?.toString()?.trim();\n break;\n }\n }\n\n // biome-ignore lint/suspicious/noDoubleEquals: Intentional loose comparison\n if (sourceValue != targetValue) {\n return false;\n }\n }\n\n return true;\n}\n","import type { VaryHeader } from './types';\n\nconst VALID_HEADER_NAME_REGEX = /^[a-z0-9-]+$/i;\n\n/**\n * Parses the Vary header as defined in\n * {@link https://www.rfc-editor.org/rfc/rfc9110.html#name-vary RFC 9110 Section 12.5.5}.\n *\n * The Vary header indicates which request headers a server considers when selecting or\n * generating a response, enabling proper HTTP caching behavior.\n *\n * @remarks\n * - Header field names are normalized to lowercase\n * - Duplicate fields are automatically deduplicated\n * - Invalid header names (per RFC 9110) are silently skipped\n * - If the header contains `'*'`, the function returns `'*'` (wildcard)\n * - Returns `null` for invalid input or when no valid fields are found\n *\n * @example\n *\n * ```ts\n * parse('Accept-Encoding, User-Agent');\n * // => ['accept-encoding', 'user-agent']\n *\n * parse('*');\n * // => '*'\n *\n * parse('Invalid Header!');\n * // => null\n * ```\n *\n * @param {string} headerStr - The Vary header value to parse (e.g., \"Accept-Encoding,\n * User-Agent\")\n * @param {number} [maxLength=16] - Maximum number of header fields to parse for DoS\n * protection. Default is `16`\n * @returns {VaryHeader | null} The parsed Vary header as an array of lowercase field\n * names, `'*'` for wildcard, or `null` if invalid.\n */\nexport function parse(headerStr?: string, maxLength = 16): VaryHeader | null {\n // Invalid header name\n if (typeof headerStr !== 'string') {\n return null;\n }\n\n // RFC says only '*' is valid alone, but some servers may send invalid headers like '*, Accept-Encoding'\n if (headerStr.includes('*')) {\n return '*';\n }\n\n const values = new Set<string>();\n\n for (let i = 0; i < headerStr.length; i++) {\n const char = headerStr[i];\n\n if (char === ' ' || char === '\\t' || char === ',') {\n continue;\n }\n\n const start = i;\n\n while (i < headerStr.length) {\n const char = headerStr[i];\n\n if (char === ',') {\n break;\n }\n\n i++;\n }\n\n const headerName = headerStr.slice(start, i).trim().toLowerCase();\n\n // Skip invalid header names\n if (headerName.length === 0 || !VALID_HEADER_NAME_REGEX.test(headerName)) {\n continue;\n }\n\n values.add(headerName);\n\n // DOS protection to avoid overly large vary headers\n if (values.size >= maxLength) {\n break;\n }\n }\n\n // Ensures no empty set is returned\n if (values.size === 0) {\n return null;\n }\n\n return Array.from(values);\n}\n"],"names":["compare","vary","source","target","sourceKeys","Object","keys","targetKeys","field","sourceValue","targetValue","key","toLowerCase","_source$key","toString","trim","_target$key","VALID_HEADER_NAME_REGEX","parse","headerStr","maxLength","includes","values","Set","i","length","char","start","headerName","slice","test","add","size","Array","from"],"mappings":"SAoCgBA,EACdC,EACAC,EACAC,GAGA,GAAa,MAATF,EACF,OAAO,EAGT,MAAMG,EAAaC,OAAOC,KAAKJ,GACzBK,EAAaF,OAAOC,KAAKH,GAE/B,IAAK,MAAMK,KAASP,EAAM,CACxB,IAAIQ,EACAC,EAGJ,IAAK,MAAMC,KAAOP,EAChB,GAAIO,EAAIC,gBAAkBJ,EAAO,CAAAK,IAAAA,EAC/BJ,EAAyB,OAAdI,EAAGX,EAAOS,KAAgB,OAAZE,EAAXA,EAAaC,iBAAU,EAAvBD,EAAyBE,OACvC,KACF,CAIF,IAAK,MAAMJ,KAAOJ,EAChB,GAAII,EAAIC,gBAAkBJ,EAAO,CAAAQ,IAAAA,EAC/BN,EAAyB,OAAdM,EAAGb,EAAOQ,KAAPK,OAAWA,EAAXA,EAAaF,iBAAbE,EAAAA,EAAyBD,OACvC,KACF,CAIF,GAAIN,GAAeC,EACjB,QAEJ,CAEA,OACF,CAAA,CC1EA,MAAMO,EAA0B,yBAoChBC,EAAMC,EAAoBC,EAAY,IAEpD,GAAyB,iBAAdD,EACT,YAIF,GAAIA,EAAUE,SAAS,KACrB,MAAO,IAGT,MAAMC,EAAS,IAAIC,IAEnB,IAAK,IAAIC,EAAI,EAAGA,EAAIL,EAAUM,OAAQD,IAAK,CACzC,MAAME,EAAOP,EAAUK,GAEvB,GAAa,MAATE,GAAyB,OAATA,GAA0B,MAATA,EACnC,SAGF,MAAMC,EAAQH,EAEd,KAAOA,EAAIL,EAAUM,QAGN,MAFAN,EAAUK,IAMvBA,IAGF,MAAMI,EAAaT,EAAUU,MAAMF,EAAOH,GAAGT,OAAOH,cAGpD,GAA0B,IAAtBgB,EAAWH,QAAiBR,EAAwBa,KAAKF,KAI7DN,EAAOS,IAAIH,GAGPN,EAAOU,MAAQZ,GACjB,KAEJ,CAGA,OAAoB,IAAhBE,EAAOU,KACF,KAGFC,MAAMC,KAAKZ,EACpB"}
@@ -0,0 +1,2 @@
1
+ !function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports):"function"==typeof define&&define.amd?define(["exports"],r):r((e||self).httpVary={})}(this,function(e){function r(e,r){(null==r||r>e.length)&&(r=e.length);for(var t=0,n=Array(r);t<r;t++)n[t]=e[t];return n}function t(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(n)return(n=n.call(e)).next.bind(n);if(Array.isArray(e)||(n=function(e,t){if(e){if("string"==typeof e)return r(e,t);var n={}.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?r(e,t):void 0}}(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var o=0;return function(){return o>=e.length?{done:!0}:{done:!1,value:e[o++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var n=/^[a-z0-9-]+$/i;e.compare=function(e,r,n){if("*"===e)return!1;for(var o,i=Object.keys(r),a=Object.keys(n),l=t(e);!(o=l()).done;){for(var f,u=o.value,d=void 0,s=void 0,v=t(i);!(f=v()).done;){var c=f.value;if(c.toLowerCase()===u){var y;d=null==(y=r[c])||null==(y=y.toString())?void 0:y.trim();break}}for(var b,m=t(a);!(b=m()).done;){var p=b.value;if(p.toLowerCase()===u){var g;s=null==(g=n[p])||null==(g=g.toString())?void 0:g.trim();break}}if(d!=s)return!1}return!0},e.parse=function(e,r){if(void 0===r&&(r=16),"string"!=typeof e)return null;if(e.includes("*"))return"*";for(var t=new Set,o=0;o<e.length;o++){var i=e[o];if(" "!==i&&"\t"!==i&&","!==i){for(var a=o;o<e.length&&","!==e[o];)o++;var l=e.slice(a,o).trim().toLowerCase();if(0!==l.length&&n.test(l)&&(t.add(l),t.size>=r))break}}return 0===t.size?null:Array.from(t)}});
2
+ //# sourceMappingURL=index.umd.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.umd.js","sources":["../src/parse.ts","../src/compare.ts"],"sourcesContent":["import type { VaryHeader } from './types';\n\nconst VALID_HEADER_NAME_REGEX = /^[a-z0-9-]+$/i;\n\n/**\n * Parses the Vary header as defined in\n * {@link https://www.rfc-editor.org/rfc/rfc9110.html#name-vary RFC 9110 Section 12.5.5}.\n *\n * The Vary header indicates which request headers a server considers when selecting or\n * generating a response, enabling proper HTTP caching behavior.\n *\n * @remarks\n * - Header field names are normalized to lowercase\n * - Duplicate fields are automatically deduplicated\n * - Invalid header names (per RFC 9110) are silently skipped\n * - If the header contains `'*'`, the function returns `'*'` (wildcard)\n * - Returns `null` for invalid input or when no valid fields are found\n *\n * @example\n *\n * ```ts\n * parse('Accept-Encoding, User-Agent');\n * // => ['accept-encoding', 'user-agent']\n *\n * parse('*');\n * // => '*'\n *\n * parse('Invalid Header!');\n * // => null\n * ```\n *\n * @param {string} headerStr - The Vary header value to parse (e.g., \"Accept-Encoding,\n * User-Agent\")\n * @param {number} [maxLength=16] - Maximum number of header fields to parse for DoS\n * protection. Default is `16`\n * @returns {VaryHeader | null} The parsed Vary header as an array of lowercase field\n * names, `'*'` for wildcard, or `null` if invalid.\n */\nexport function parse(headerStr?: string, maxLength = 16): VaryHeader | null {\n // Invalid header name\n if (typeof headerStr !== 'string') {\n return null;\n }\n\n // RFC says only '*' is valid alone, but some servers may send invalid headers like '*, Accept-Encoding'\n if (headerStr.includes('*')) {\n return '*';\n }\n\n const values = new Set<string>();\n\n for (let i = 0; i < headerStr.length; i++) {\n const char = headerStr[i];\n\n if (char === ' ' || char === '\\t' || char === ',') {\n continue;\n }\n\n const start = i;\n\n while (i < headerStr.length) {\n const char = headerStr[i];\n\n if (char === ',') {\n break;\n }\n\n i++;\n }\n\n const headerName = headerStr.slice(start, i).trim().toLowerCase();\n\n // Skip invalid header names\n if (headerName.length === 0 || !VALID_HEADER_NAME_REGEX.test(headerName)) {\n continue;\n }\n\n values.add(headerName);\n\n // DOS protection to avoid overly large vary headers\n if (values.size >= maxLength) {\n break;\n }\n }\n\n // Ensures no empty set is returned\n if (values.size === 0) {\n return null;\n }\n\n return Array.from(values);\n}\n","import type { CompareHeaders, VaryHeader } from './types';\n\n/**\n * Checks if {@linkcode source} and {@linkcode target} headers are equivalent for the given\n * Vary header, as per\n * {@link https://www.rfc-editor.org/rfc/rfc9110.html#name-vary RFC 9110 Section 12.5.5}.\n *\n * This function determines if two requests would receive the same cached response based\n * on the Vary header requirements.\n *\n * @remarks\n * - Returns `false` for wildcard vary (`'*'`) as responses always differ\n * - Header name matching is case-insensitive (per RFC 9110)\n * - Missing headers are treated as `undefined`\n * - String values are trimmed before comparison\n * - Array values are converted to strings via `.toString()`\n * - Uses loose equality (!=) for comparison\n * - Empty strings are distinct from missing headers\n *\n * @example\n *\n * ```ts\n * const vary = ['accept-encoding', 'user-agent'];\n * const headers1 = { 'Accept-Encoding': 'gzip', 'User-Agent': 'Chrome' };\n * const headers2 = { 'Accept-Encoding': 'gzip', 'User-Agent': 'Chrome' };\n *\n * compare(vary, headers1, headers2);\n * // => true\n * ```\n *\n * @param {VaryHeader} vary - The Vary header specifying which fields to compare\n * @param {CompareHeaders} source - The first set of request headers\n * @param {CompareHeaders} target - The second set of request headers\n * @returns {boolean} `true` if the headers are equivalent for the given Vary header,\n * `false` otherwise\n */\nexport function compare(\n vary: VaryHeader,\n source: CompareHeaders,\n target: CompareHeaders\n): boolean {\n // Wildcard always differs\n if (vary === '*') {\n return false;\n }\n\n const sourceKeys = Object.keys(source);\n const targetKeys = Object.keys(target);\n\n for (const field of vary) {\n let sourceValue: string | undefined;\n let targetValue: string | undefined;\n\n // Case-insensitive header lookup in source\n for (const key of sourceKeys) {\n if (key.toLowerCase() === field) {\n sourceValue = source[key]?.toString()?.trim();\n break;\n }\n }\n\n // Case-insensitive header lookup in target\n for (const key of targetKeys) {\n if (key.toLowerCase() === field) {\n targetValue = target[key]?.toString()?.trim();\n break;\n }\n }\n\n // biome-ignore lint/suspicious/noDoubleEquals: Intentional loose comparison\n if (sourceValue != targetValue) {\n return false;\n }\n }\n\n return true;\n}\n"],"names":["VALID_HEADER_NAME_REGEX","vary","source","target","_step","sourceKeys","Object","keys","targetKeys","_iterator","_createForOfIteratorHelperLoose","done","_step2","field","value","sourceValue","targetValue","_iterator2","key","toLowerCase","_source$key","toString","trim","_step3","_iterator3","_target$_key","headerStr","maxLength","includes","values","Set","i","length","char","start","headerName","slice","test","add","size","Array","from"],"mappings":"sgCAEA,IAAMA,EAA0B,mCCmC9BC,EACAC,EACAC,GAGA,GAAa,MAATF,EACF,OACF,EAKA,IAHA,IAGwBG,EAHlBC,EAAaC,OAAOC,KAAKL,GACzBM,EAAaF,OAAOC,KAAKJ,GAE/BM,EAAAC,EAAoBT,KAAIG,EAAAK,KAAAE,MAAE,CAKxB,IALS,IAKmBC,EALnBC,EAAKT,EAAAU,MACVC,OAA+B,EAC/BC,OAGJ,EAAAC,EAAAP,EAAkBL,KAAUO,EAAAK,KAAAN,MAAE,CAAA,IAAnBO,EAAGN,EAAAE,MACZ,GAAII,EAAIC,gBAAkBN,EAAO,CAAA,IAAAO,EAC/BL,SAAWK,EAAGlB,EAAOgB,KAAgB,OAAZE,EAAXA,EAAaC,iBAAU,EAAvBD,EAAyBE,OACvC,KACF,CACF,CAGA,IAAA,IAA4BC,EAA5BC,EAAAd,EAAkBF,KAAUe,EAAAC,KAAAb,MAAE,CAAnB,IAAAO,EAAGK,EAAAT,MACZ,GAAII,EAAIC,gBAAkBN,EAAO,CAAAY,IAAAA,EAC/BT,EAAyBS,OAAdA,EAAGtB,EAAOe,KAAPO,OAAWA,EAAXA,EAAaJ,iBAAbI,EAAAA,EAAyBH,OACvC,KACF,CACF,CAGA,GAAIP,GAAeC,EACjB,OACF,CACF,CAEA,OACF,CAAA,mBDtCsBU,EAAoBC,GAExC,YAFwCA,IAAAA,EAAY,IAE3B,iBAAdD,EACT,OACF,KAGA,GAAIA,EAAUE,SAAS,KACrB,MAAO,IAKT,IAFA,IAAMC,EAAS,IAAIC,IAEVC,EAAI,EAAGA,EAAIL,EAAUM,OAAQD,IAAK,CACzC,IAAME,EAAOP,EAAUK,GAEvB,GAAa,MAATE,GAAyB,OAATA,GAA0B,MAATA,EAArC,CAMA,IAFA,IAAMC,EAAQH,EAEPA,EAAIL,EAAUM,QAGN,MAFAN,EAAUK,IAMvBA,IAGF,IAAMI,EAAaT,EAAUU,MAAMF,EAAOH,GAAGT,OAAOH,cAGpD,GAA0B,IAAtBgB,EAAWH,QAAiBhC,EAAwBqC,KAAKF,KAI7DN,EAAOS,IAAIH,GAGPN,EAAOU,MAAQZ,GACjB,KAzBF,CA2BF,CAGA,OAAoB,IAAhBE,EAAOU,KACF,KAGFC,MAAMC,KAAKZ,EACpB"}
@@ -0,0 +1,37 @@
1
+ import type { VaryHeader } from './types';
2
+ /**
3
+ * Parses the Vary header as defined in
4
+ * {@link https://www.rfc-editor.org/rfc/rfc9110.html#name-vary RFC 9110 Section 12.5.5}.
5
+ *
6
+ * The Vary header indicates which request headers a server considers when selecting or
7
+ * generating a response, enabling proper HTTP caching behavior.
8
+ *
9
+ * @remarks
10
+ * - Header field names are normalized to lowercase
11
+ * - Duplicate fields are automatically deduplicated
12
+ * - Invalid header names (per RFC 9110) are silently skipped
13
+ * - If the header contains `'*'`, the function returns `'*'` (wildcard)
14
+ * - Returns `null` for invalid input or when no valid fields are found
15
+ *
16
+ * @example
17
+ *
18
+ * ```ts
19
+ * parse('Accept-Encoding, User-Agent');
20
+ * // => ['accept-encoding', 'user-agent']
21
+ *
22
+ * parse('*');
23
+ * // => '*'
24
+ *
25
+ * parse('Invalid Header!');
26
+ * // => null
27
+ * ```
28
+ *
29
+ * @param {string} headerStr - The Vary header value to parse (e.g., "Accept-Encoding,
30
+ * User-Agent")
31
+ * @param {number} [maxLength=16] - Maximum number of header fields to parse for DoS
32
+ * protection. Default is `16`
33
+ * @returns {VaryHeader | null} The parsed Vary header as an array of lowercase field
34
+ * names, `'*'` for wildcard, or `null` if invalid.
35
+ */
36
+ export declare function parse(headerStr?: string, maxLength?: number): VaryHeader | null;
37
+ //# sourceMappingURL=parse.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"parse.d.ts","sourceRoot":"","sources":["../src/parse.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AAI1C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AACH,wBAAgB,KAAK,CAAC,SAAS,CAAC,EAAE,MAAM,EAAE,SAAS,SAAK,GAAG,UAAU,GAAG,IAAI,CAqD3E"}
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Type representing the Vary header as defined in
3
+ * {@link https://www.rfc-editor.org/rfc/rfc9110.html#name-vary RFC 9110 Section 12.5.5}.
4
+ *
5
+ * The Vary header field indicates which request headers affect the response, enabling
6
+ * proper cache key generation.
7
+ *
8
+ * - `'*'` - Wildcard indicating the response varies on aspects beyond headers
9
+ * - `string[]` - Array of lowercase header field names that affect the response
10
+ *
11
+ * @remarks
12
+ * The array is never empty and all header names are normalized to lowercase.
13
+ */
14
+ export type VaryHeader = string[] | '*';
15
+ /**
16
+ * Type representing HTTP headers. Header values can be strings, arrays of strings, or
17
+ * undefined.
18
+ */
19
+ export type HttpHeaders = Record<string, string | string[] | undefined>;
20
+ /**
21
+ * Type representing HTTP headers for comparison. Values must be strings or arrays (no
22
+ * undefined).
23
+ */
24
+ export type CompareHeaders = Record<string, string | string[]>;
25
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AACH,MAAM,MAAM,UAAU,GAAG,MAAM,EAAE,GAAG,GAAG,CAAC;AAExC;;;GAGG;AACH,MAAM,MAAM,WAAW,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,SAAS,CAAC,CAAC;AAExE;;;GAGG;AACH,MAAM,MAAM,cAAc,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC,CAAC"}
package/package.json ADDED
@@ -0,0 +1,48 @@
1
+ {
2
+ "name": "http-vary",
3
+ "version": "0.0.1",
4
+ "description": "A minimal parser and utility for the HTTP Vary header.",
5
+ "keywords": [
6
+ "vary",
7
+ "http",
8
+ "header",
9
+ "headers",
10
+ "cache",
11
+ "caching",
12
+ "http-cache",
13
+ "vary-header",
14
+ "rfc9110",
15
+ "rfc9111",
16
+ "cache-key",
17
+ "parser"
18
+ ],
19
+ "homepage": "https://tinylibs.js.org/packages/http-vary",
20
+ "bugs": "https://github.com/arthurfiorette/tinylibs/issues",
21
+ "repository": {
22
+ "type": "git",
23
+ "url": "git+https://github.com/arthurfiorette/tinylibs.git",
24
+ "directory": "packages/http-vary"
25
+ },
26
+ "license": "MIT",
27
+ "author": "Arthur Fiorette <npm@arthur.place>",
28
+ "sideEffects": false,
29
+ "main": "dist/index.js",
30
+ "umd:main": "dist/index.umd.js",
31
+ "unpkg": "dist/index.umd.js",
32
+ "module": "dist/index.mjs",
33
+ "source": "src/index.ts",
34
+ "types": "dist/index.d.ts",
35
+ "files": [
36
+ "dist",
37
+ "src",
38
+ "LICENSE",
39
+ "README.md"
40
+ ],
41
+ "scripts": {
42
+ "build": "microbundle --tsconfig tsconfig.build.json",
43
+ "test": "jest --coverage"
44
+ },
45
+ "devDependencies": {
46
+ "microbundle": "catalog:bundle"
47
+ }
48
+ }
package/src/compare.ts ADDED
@@ -0,0 +1,77 @@
1
+ import type { CompareHeaders, VaryHeader } from './types';
2
+
3
+ /**
4
+ * Checks if {@linkcode source} and {@linkcode target} headers are equivalent for the given
5
+ * Vary header, as per
6
+ * {@link https://www.rfc-editor.org/rfc/rfc9110.html#name-vary RFC 9110 Section 12.5.5}.
7
+ *
8
+ * This function determines if two requests would receive the same cached response based
9
+ * on the Vary header requirements.
10
+ *
11
+ * @remarks
12
+ * - Returns `false` for wildcard vary (`'*'`) as responses always differ
13
+ * - Header name matching is case-insensitive (per RFC 9110)
14
+ * - Missing headers are treated as `undefined`
15
+ * - String values are trimmed before comparison
16
+ * - Array values are converted to strings via `.toString()`
17
+ * - Uses loose equality (!=) for comparison
18
+ * - Empty strings are distinct from missing headers
19
+ *
20
+ * @example
21
+ *
22
+ * ```ts
23
+ * const vary = ['accept-encoding', 'user-agent'];
24
+ * const headers1 = { 'Accept-Encoding': 'gzip', 'User-Agent': 'Chrome' };
25
+ * const headers2 = { 'Accept-Encoding': 'gzip', 'User-Agent': 'Chrome' };
26
+ *
27
+ * compare(vary, headers1, headers2);
28
+ * // => true
29
+ * ```
30
+ *
31
+ * @param {VaryHeader} vary - The Vary header specifying which fields to compare
32
+ * @param {CompareHeaders} source - The first set of request headers
33
+ * @param {CompareHeaders} target - The second set of request headers
34
+ * @returns {boolean} `true` if the headers are equivalent for the given Vary header,
35
+ * `false` otherwise
36
+ */
37
+ export function compare(
38
+ vary: VaryHeader,
39
+ source: CompareHeaders,
40
+ target: CompareHeaders
41
+ ): boolean {
42
+ // Wildcard always differs
43
+ if (vary === '*') {
44
+ return false;
45
+ }
46
+
47
+ const sourceKeys = Object.keys(source);
48
+ const targetKeys = Object.keys(target);
49
+
50
+ for (const field of vary) {
51
+ let sourceValue: string | undefined;
52
+ let targetValue: string | undefined;
53
+
54
+ // Case-insensitive header lookup in source
55
+ for (const key of sourceKeys) {
56
+ if (key.toLowerCase() === field) {
57
+ sourceValue = source[key]?.toString()?.trim();
58
+ break;
59
+ }
60
+ }
61
+
62
+ // Case-insensitive header lookup in target
63
+ for (const key of targetKeys) {
64
+ if (key.toLowerCase() === field) {
65
+ targetValue = target[key]?.toString()?.trim();
66
+ break;
67
+ }
68
+ }
69
+
70
+ // biome-ignore lint/suspicious/noDoubleEquals: Intentional loose comparison
71
+ if (sourceValue != targetValue) {
72
+ return false;
73
+ }
74
+ }
75
+
76
+ return true;
77
+ }
package/src/index.ts ADDED
@@ -0,0 +1,3 @@
1
+ export * from './compare';
2
+ export * from './parse';
3
+ export * from './types';
package/src/parse.ts ADDED
@@ -0,0 +1,92 @@
1
+ import type { VaryHeader } from './types';
2
+
3
+ const VALID_HEADER_NAME_REGEX = /^[a-z0-9-]+$/i;
4
+
5
+ /**
6
+ * Parses the Vary header as defined in
7
+ * {@link https://www.rfc-editor.org/rfc/rfc9110.html#name-vary RFC 9110 Section 12.5.5}.
8
+ *
9
+ * The Vary header indicates which request headers a server considers when selecting or
10
+ * generating a response, enabling proper HTTP caching behavior.
11
+ *
12
+ * @remarks
13
+ * - Header field names are normalized to lowercase
14
+ * - Duplicate fields are automatically deduplicated
15
+ * - Invalid header names (per RFC 9110) are silently skipped
16
+ * - If the header contains `'*'`, the function returns `'*'` (wildcard)
17
+ * - Returns `null` for invalid input or when no valid fields are found
18
+ *
19
+ * @example
20
+ *
21
+ * ```ts
22
+ * parse('Accept-Encoding, User-Agent');
23
+ * // => ['accept-encoding', 'user-agent']
24
+ *
25
+ * parse('*');
26
+ * // => '*'
27
+ *
28
+ * parse('Invalid Header!');
29
+ * // => null
30
+ * ```
31
+ *
32
+ * @param {string} headerStr - The Vary header value to parse (e.g., "Accept-Encoding,
33
+ * User-Agent")
34
+ * @param {number} [maxLength=16] - Maximum number of header fields to parse for DoS
35
+ * protection. Default is `16`
36
+ * @returns {VaryHeader | null} The parsed Vary header as an array of lowercase field
37
+ * names, `'*'` for wildcard, or `null` if invalid.
38
+ */
39
+ export function parse(headerStr?: string, maxLength = 16): VaryHeader | null {
40
+ // Invalid header name
41
+ if (typeof headerStr !== 'string') {
42
+ return null;
43
+ }
44
+
45
+ // RFC says only '*' is valid alone, but some servers may send invalid headers like '*, Accept-Encoding'
46
+ if (headerStr.includes('*')) {
47
+ return '*';
48
+ }
49
+
50
+ const values = new Set<string>();
51
+
52
+ for (let i = 0; i < headerStr.length; i++) {
53
+ const char = headerStr[i];
54
+
55
+ if (char === ' ' || char === '\t' || char === ',') {
56
+ continue;
57
+ }
58
+
59
+ const start = i;
60
+
61
+ while (i < headerStr.length) {
62
+ const char = headerStr[i];
63
+
64
+ if (char === ',') {
65
+ break;
66
+ }
67
+
68
+ i++;
69
+ }
70
+
71
+ const headerName = headerStr.slice(start, i).trim().toLowerCase();
72
+
73
+ // Skip invalid header names
74
+ if (headerName.length === 0 || !VALID_HEADER_NAME_REGEX.test(headerName)) {
75
+ continue;
76
+ }
77
+
78
+ values.add(headerName);
79
+
80
+ // DOS protection to avoid overly large vary headers
81
+ if (values.size >= maxLength) {
82
+ break;
83
+ }
84
+ }
85
+
86
+ // Ensures no empty set is returned
87
+ if (values.size === 0) {
88
+ return null;
89
+ }
90
+
91
+ return Array.from(values);
92
+ }
package/src/types.ts ADDED
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Type representing the Vary header as defined in
3
+ * {@link https://www.rfc-editor.org/rfc/rfc9110.html#name-vary RFC 9110 Section 12.5.5}.
4
+ *
5
+ * The Vary header field indicates which request headers affect the response, enabling
6
+ * proper cache key generation.
7
+ *
8
+ * - `'*'` - Wildcard indicating the response varies on aspects beyond headers
9
+ * - `string[]` - Array of lowercase header field names that affect the response
10
+ *
11
+ * @remarks
12
+ * The array is never empty and all header names are normalized to lowercase.
13
+ */
14
+ export type VaryHeader = string[] | '*';
15
+
16
+ /**
17
+ * Type representing HTTP headers. Header values can be strings, arrays of strings, or
18
+ * undefined.
19
+ */
20
+ export type HttpHeaders = Record<string, string | string[] | undefined>;
21
+
22
+ /**
23
+ * Type representing HTTP headers for comparison. Values must be strings or arrays (no
24
+ * undefined).
25
+ */
26
+ export type CompareHeaders = Record<string, string | string[]>;