Path: blob/main/corrosion/lib/cookie-parser.js
1223 views
// -------------------------------------------------------------1// WARNING: this file is used by both the client and the server.2// Do not use any browser or node-specific API!3// -------------------------------------------------------------4class CookieStore {5constructor(val = ''){6this.data = {};7val.split(';').map(cookie => {8var [ name, val = ''] = cookie.trimStart().split('=');9if (name) this.data[name] = val;10});11};12has(name){13if (!name || !this.data[name]) return false;14return true;15};16get(name){17return this.has(name) ? this.data[name] : null;18};19set(name, val){20if (!name || !val) return;21return this.data[name] = val;22};23delete(name){24if (!name) return;25return delete this.data[name];26};27forEach(action = (node, key) => null){28for (let prop in this.data) action(this.data[prop], prop);29};30serialize(){31var str = '';32for (let i in this.data) str += ` ${i}=${this.data[i]};`;33return str.substr(1);34};35};3637class SetCookie {38constructor(val = ''){3940var [ [ name, value = '' ], ...data ] = val.split(';').map(str => str.trimStart().split('='));4142this.name = name;43this.value = value;44this.expires = null;45this.maxAge = null;46this.domain = null;47this.secure = false;48this.httpOnly = false;49this.path = null;50this.sameSite = null;5152data.forEach(([name = null, value = null]) => {53if (typeof name == 'string') switch(name.toLowerCase()){54case 'domain':55this.domain = value;56break;57case 'secure':58this.secure = true;59break;60case 'httponly':61this.httpOnly = true;62break;63case 'samesite':64this.sameSite = value;65break;66case 'path':67this.path = value;68break;69case 'expires':70this.expires = value;71break;72case 'maxage':73this.maxAge = value;74break;75};76});77};78serialize(){79if (!this.name) return;80var str = `${this.name}=${this.value};`;81if (this.expires) str += ` Expires=${this.expires};`;82if (this.maxAge) str += ` Max-Age=${this.max_age};`;83if (this.domain) str += ` Domain=${this.domain};`;84if (this.secure) str += ` Secure;`;85if (this.httpOnly) str += ` HttpOnly;`;86if (this.path) str += ` Path=${this.path};`;87if (this.sameSite) str += ` SameSite=${this.sameSite};`;88return str;89};90};9192exports.CookieStore = CookieStore;93exports.SetCookie = SetCookie;949596