This commit is contained in:
nucther committed 2025-12-01 23:23:05 +07:00
commit d282e2bcae
3481 files changed
+568488

No files matched your search

+50
View File
@@ -0,0 +1,50 @@
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased]
## [1.3.2] - 2020-01-21
### Added
- `CookieAttributes` is now exported from main module for easier usage.
## [1.3.1] - 2020-01-10
### Changed
- Use type system to enforce secure SameSite=None cookies (thanks [@rkrasiuk](https://github.com/rkrasiuk/)).
## [1.3.0] - 2019-10-17
### Added
- Support for the `none` SameSite cookie value.
- Support for case insensitive URL encoding.
## [1.2.0] - 2018-05-13
### Added
- Support for the `SameSite` cookie attribute.
## [1.1.1] - 2017-02-07
### Removed
- `Object.assign` dependency.
## [1.1.0] - 2017-02-05
### Added
- New `encode` and `parse` functions.
- Expanded documentation and tests.
## [1.0.1] - 2017-02-05
### Fixed
- Homepage/issues links in package.json.
## [1.0.0] - 2017-02-05
- Initial release
[Unreleased]: https://github.com/theodorejb/es-cookie/compare/v1.3.2...HEAD
[1.3.2]: https://github.com/theodorejb/es-cookie/compare/v1.3.1...v1.3.2
[1.3.1]: https://github.com/theodorejb/es-cookie/compare/v1.3.0...v1.3.1
[1.3.0]: https://github.com/theodorejb/es-cookie/compare/v1.2.0...v1.3.0
[1.2.0]: https://github.com/theodorejb/es-cookie/compare/v1.1.1...v1.2.0
[1.1.1]: https://github.com/theodorejb/es-cookie/compare/v1.1.0...v1.1.1
[1.1.0]: https://github.com/theodorejb/es-cookie/compare/v1.0.1...v1.1.0
[1.0.1]: https://github.com/theodorejb/es-cookie/compare/v1.0.0...v1.0.1
[1.0.0]: https://github.com/theodorejb/es-cookie/tree/v1.0.0
+20
View File
@@ -0,0 +1,20 @@
Copyright 2017 Theodore Brown
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+217
View File
@@ -0,0 +1,217 @@
# es-cookie
[![NPM version](https://img.shields.io/npm/v/es-cookie.svg)](https://www.npmjs.org/package/es-cookie)
A simple, lightweight module for handling cookies
* Includes TypeScript definitions
* Works with Webpack, Rollup, and Browserify module bundlers
* Fully compliant with [RFC 6265](https://tools.ietf.org/html/rfc6265)
* No dependencies
* Originally based on js-cookie, but rewritten as a TypeScript module with a lean, type-safe API
## Installation
`npm install es-cookie --save`
## Usage
Import entire module:
```javascript
import * as Cookies from 'es-cookie';
Cookies.set('name', 'value');
Cookies.get('name'); // => 'value'
```
Alternatively, just import the functions you need:
```javascript
import {set as setCookie, get as getCookie} from 'es-cookie';
setCookie('name', 'value');
getCookie('name'); // => 'value'
```
Create a cookie that expires 7 days from now, valid across the entire site:
```javascript
Cookies.set('name', 'value', { expires: 7 });
```
## Functions
### set
Creates a new cookie. The first parameter is for the name, and the second
for the value. The third parameter is optional and allows you to modify
attributes for the new cookie (see the [Attributes section](#attributes) below).
```javascript
// Create an expiring cookie, valid to the path of the current page:
Cookies.set('name', 'value', { expires: 7, path: '' });
```
### get
Returns a single cookie with the specified name, or `undefined` if the cookie doesn't exist.
```javascript
Cookies.get('name'); // => 'value'
Cookies.get('nothing'); // => undefined
```
### getAll
Returns an object containing all visible cookies.
```javascript
Cookies.getAll(); // => { name: 'value' }
```
### remove
Deletes a single cookie by name.
```javascript
Cookies.remove('name');
```
*IMPORTANT! When removing a cookie, you must pass the exact same path and
domain attributes that were used to set the cookie, unless you're using
the default attributes.*
```javascript
Cookies.set('name', 'value', { path: '' });
Cookies.remove('name'); // fail!
Cookies.remove('name', { path: '' }); // removed!
```
*Note: Removing a nonexistant cookie does not raise an exception or return a value.*
### parse
Parses a cookie string (e.g. `document.cookie`) and returns the names/values as an object.
```javascript
Cookies.parse('c=v; name=value'); // => {c: 'v', name: 'value'}
```
### encode
Takes a name, value, and attributes object and returns an encoded string
which can be used to create a new cookie.
```javascript
Cookies.encode('c', 'v', {secure: true}); // => 'c=v; Secure'
```
## Attributes
### expires
Define when the cookie will be removed. Value can be a number which
will be interpreted as days from time of creation or a `Date` instance.
If omitted, the cookie becomes a session cookie.
To create a cookie that expires in less than a day, use a `Date` object.
**Default:** Cookie is removed when the user closes the browser.
**Examples:**
```javascript
Cookies.set('name', 'value', { expires: 365 });
Cookies.get('name'); // => 'value'
Cookies.remove('name');
let twoHoursFromNow = new Date();
twoHoursFromNow.setHours(twoHoursFromNow.getHours() + 2);
Cookies.set('name', 'value', { expires: twoHoursFromNow });
```
### path
A string indicating the path where the cookie is visible.
**Default:** `/`
**Examples:**
```javascript
Cookies.set('name', 'value', { path: '' });
Cookies.get('name'); // => 'value'
Cookies.remove('name', { path: '' });
```
### domain
A string indicating a valid domain where the cookie should be visible.
The cookie will also be visible to all subdomains.
**Default:** Cookie is visible only to the domain or subdomain of the page where the cookie was created.
**Examples:**
Assuming a cookie that is being created on `site.com`:
```javascript
Cookies.set('name', 'value', { domain: 'subdomain.site.com' });
Cookies.get('name'); // => undefined (need to read at 'subdomain.site.com')
```
### secure
Either `true` or `false`, indicating if the cookie transmission requires a secure protocol (https).
**Default:** No secure protocol requirement.
**Examples:**
```javascript
Cookies.set('name', 'value', { secure: true });
Cookies.get('name'); // => 'value'
Cookies.remove('name');
```
### sameSite
A string with a value of either `strict`, `lax`, or `none`. When enabled,
supporting browsers will only send the cookie if the request originates
from the same website the cookie is from. This provides some protection
against cross-site request forgery attacks (CSRF).
The strict mode witholds the cookie from any kind of cross-site usage
(including inbound links from external sites). The lax mode witholds the
cookie on cross-domain subrequests (e.g. images or frames), but sends it
whenever a user navigates safely from an external site (e.g. by following
a link).
**Default:** No same-site requirement is set - the browser default will be used.
**Examples:**
```javascript
Cookies.set('name', 'value', { sameSite: 'strict' });
Cookies.set('other', 'value', { sameSite: 'lax' });
```
## Encoding
This project is [RFC 6265](http://tools.ietf.org/html/rfc6265#section-4.1.1)
compliant. Special characters that are not allowed in the cookie name or
value are encoded with their UTF-8 Hex equivalent using
[percent-encoding](http://en.wikipedia.org/wiki/Percent-encoding).
The only character allowed in cookie names or values that is still encoded
is the percent (`%`) character. It is escaped in order to interpret
percent input as literal.
## Author
Theodore Brown
<https://theodorejb.me>
## License
MIT
+46
View File
@@ -0,0 +1,46 @@
{
"name": "es-cookie",
"version": "1.3.2",
"description": "A JavaScript module for handling cookies",
"files": [
"src/*.js",
"src/*.d.ts"
],
"main": "src/es-cookie.js",
"types": "./src/es-cookie.d.ts",
"keywords": [
"cookies",
"typescript",
"module",
"commonjs",
"rollup",
"browserify",
"webpack"
],
"scripts": {
"prepublish": "tsc && browserify test/tests.js -o test/browser/testbundle.js",
"start": "http-server"
},
"author": {
"name": "Theodore Brown",
"email": "theodorejb@outlook.com",
"url": "http://theodorejb.me/"
},
"license": "MIT",
"homepage": "https://github.com/theodorejb/es-cookie",
"bugs": {
"url": "https://github.com/theodorejb/es-cookie/issues"
},
"repository": {
"type": "git",
"url": "git://github.com/theodorejb/es-cookie.git"
},
"devDependencies": {
"@types/mocha": "^5.2.0",
"@types/node": "^12.12.24",
"browserify": "^16.2.2",
"http-server": "^0.12.1",
"mocha": "^7.0.0",
"typescript": "^3.7.4"
}
}
+44
View File
@@ -0,0 +1,44 @@
export declare type CookieAttributes = BaseCookieAttributes & SameSiteCookieAttributes;
interface BaseCookieAttributes {
/**
* A number will be interpreted as days from time of creation
*/
expires?: Date | number;
/**
* Hosts to which the cookie will be sent
*/
domain?: string;
/**
* The cookie will only be included in an HTTP request if the request
* path matches (or is a subdirectory of) the cookie's path attribute.
*/
path?: string;
/**
* If enabled, the cookie will only be included in an HTTP request
* if it is transmitted over a secure channel (typically HTTP over TLS).
*/
secure?: boolean;
}
declare type SameSiteCookieAttributes = LaxStrictSameSiteCookieAttributes | NoneSameSiteCookieAttributes;
interface LaxStrictSameSiteCookieAttributes {
/**
* Only send the cookie if the request originates from the same website the
* cookie is from. This provides some protection against cross-site request
* forgery attacks (CSRF).
*
* The strict mode witholds the cookie from any kind of cross-site usage
* (including inbound links from external sites). The lax mode witholds
* the cookie on cross-domain subrequests (e.g. images or frames), but
* sends it whenever a user navigates safely from an external site (e.g.
* by following a link).
*/
sameSite?: 'strict' | 'lax';
}
/**
* Cookies with `SameSite=None` must also specify 'Secure'
*/
interface NoneSameSiteCookieAttributes {
sameSite: 'none';
secure: true;
}
export {};
+2
View File
@@ -0,0 +1,2 @@
"use strict";
exports.__esModule = true;
+12
View File
@@ -0,0 +1,12 @@
import { CookieAttributes } from './CookieAttributes';
export { CookieAttributes };
export declare function encode(name: string, value: string, attributes: CookieAttributes): string;
export declare function parse(cookieString: string): {
[name: string]: string;
};
export declare function getAll(): {
[name: string]: string;
};
export declare function get(name: string): string | undefined;
export declare function set(name: string, value: string, attributes?: CookieAttributes): void;
export declare function remove(name: string, attributes?: CookieAttributes): void;
+82
View File
@@ -0,0 +1,82 @@
"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
exports.__esModule = true;
function stringifyAttribute(name, value) {
if (!value) {
return '';
}
var stringified = '; ' + name;
if (value === true) {
return stringified; // boolean attributes shouldn't have a value
}
return stringified + '=' + value;
}
function stringifyAttributes(attributes) {
if (typeof attributes.expires === 'number') {
var expires = new Date();
expires.setMilliseconds(expires.getMilliseconds() + attributes.expires * 864e+5);
attributes.expires = expires;
}
return stringifyAttribute('Expires', attributes.expires ? attributes.expires.toUTCString() : '')
+ stringifyAttribute('Domain', attributes.domain)
+ stringifyAttribute('Path', attributes.path)
+ stringifyAttribute('Secure', attributes.secure)
+ stringifyAttribute('SameSite', attributes.sameSite);
}
function encode(name, value, attributes) {
return encodeURIComponent(name)
.replace(/%(23|24|26|2B|5E|60|7C)/g, decodeURIComponent) // allowed special characters
.replace(/\(/g, '%28').replace(/\)/g, '%29') // replace opening and closing parens
+ '=' + encodeURIComponent(value)
// allowed special characters
.replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g, decodeURIComponent)
+ stringifyAttributes(attributes);
}
exports.encode = encode;
function parse(cookieString) {
var result = {};
var cookies = cookieString ? cookieString.split('; ') : [];
var rdecode = /(%[\dA-F]{2})+/gi;
for (var i = 0; i < cookies.length; i++) {
var parts = cookies[i].split('=');
var cookie = parts.slice(1).join('=');
if (cookie.charAt(0) === '"') {
cookie = cookie.slice(1, -1);
}
try {
var name_1 = parts[0].replace(rdecode, decodeURIComponent);
result[name_1] = cookie.replace(rdecode, decodeURIComponent);
}
catch (e) {
// ignore cookies with invalid name/value encoding
}
}
return result;
}
exports.parse = parse;
function getAll() {
return parse(document.cookie);
}
exports.getAll = getAll;
function get(name) {
return getAll()[name];
}
exports.get = get;
function set(name, value, attributes) {
document.cookie = encode(name, value, __assign({ path: '/' }, attributes));
}
exports.set = set;
function remove(name, attributes) {
set(name, '', __assign(__assign({}, attributes), { expires: -1 }));
}
exports.remove = remove;