ngx-cookie-service
Version:
Angular cookie service
233 lines (232 loc) • 8.64 kB
JavaScript
import * as i0 from "@angular/core";
import { DOCUMENT, Injectable, InjectionToken, PLATFORM_ID, inject, makeEnvironmentProviders } from "@angular/core";
import { isPlatformBrowser } from "@angular/common";
const COOKIE_OPTIONS = new InjectionToken("ngx-cookie-service default cookie options");
function provideCookieOptions(options) {
return makeEnvironmentProviders([{
provide: COOKIE_OPTIONS,
useValue: { ...options }
}]);
}
const COOKIE_ENCODING = new InjectionToken("ngx-cookie-service cookie value encoding");
function provideCookieEncoding(encoding) {
return makeEnvironmentProviders([{
provide: COOKIE_ENCODING,
useValue: encoding
}]);
}
const SAME_SITE_VALUES = [
"Lax",
"Strict",
"None"
];
const COOKIE_OCTET_REGEXP = /^[!#$&'()*+\-./0-9:<=>?@A-Z[\]^_`a-z{|}~]*$/;
var CookieService = class CookieService {
constructor() {
this.document = inject(DOCUMENT);
this.platformId = inject(PLATFORM_ID);
this.defaultOptions = inject(COOKIE_OPTIONS, { optional: true }) ?? {};
this.codec = CookieService.toCodec(inject(COOKIE_ENCODING, { optional: true }));
this.documentIsAccessible = isPlatformBrowser(this.platformId);
}
static getCookieRegExp(name) {
const escapedName = name.replace(/([[\]{}()|=;+?,.*^$\\])/gi, "\\$1");
return new RegExp("(?:^" + escapedName + "|;\\s*" + escapedName + ")=(.*?)(?:;|$)");
}
static safeDecodeURIComponent(encodedURIComponent) {
try {
return decodeURIComponent(encodedURIComponent);
} catch {
return encodedURIComponent;
}
}
check(name) {
if (!this.documentIsAccessible) return false;
name = encodeURIComponent(name);
return CookieService.getCookieRegExp(name).test(this.document.cookie);
}
get(name) {
if (this.check(name)) {
const result = CookieService.getCookieRegExp(encodeURIComponent(name)).exec(this.document.cookie);
return result?.[1] ? this.decodeValue(result[1], name) : "";
} else return "";
}
getAll() {
if (!this.documentIsAccessible) return {};
const cookies = {};
const document = this.document;
if (document.cookie && document.cookie !== "") document.cookie.split(";").forEach((currentCookie) => {
const trimmedCookie = currentCookie.trim();
if (!trimmedCookie) return;
const equalIndex = trimmedCookie.indexOf("=");
if (equalIndex === -1) return;
const cookieName = CookieService.safeDecodeURIComponent(trimmedCookie.substring(0, equalIndex));
if (Object.hasOwn(cookies, cookieName)) return;
Object.defineProperty(cookies, cookieName, {
value: this.decodeValue(trimmedCookie.substring(equalIndex + 1), cookieName),
enumerable: true,
writable: true,
configurable: true
});
});
return cookies;
}
set(name, value, expiresOrOptions, path, domain, secure, sameSite, partitioned) {
if (!this.documentIsAccessible) return;
if (typeof expiresOrOptions !== "object" || expiresOrOptions === null || expiresOrOptions instanceof Date) {
const optionsBody = {
expires: expiresOrOptions,
path,
domain,
secure,
sameSite,
partitioned
};
this.set(name, value, optionsBody);
return;
}
const options = CookieService.validateOptions(name, CookieService.withDefaults(this.defaultOptions, expiresOrOptions));
if (!options) return;
const encodedValue = this.encodeValue(name, value);
if (encodedValue === void 0) return;
let cookieString = encodeURIComponent(name) + "=" + encodedValue + ";";
if (options.expires) cookieString += "Expires=" + options.expires.toUTCString() + ";";
if (options.path) cookieString += "Path=" + options.path + ";";
if (options.domain) cookieString += "Domain=" + options.domain + ";";
if (options.sameSite === "None" && !options.secure) {
options.secure = true;
console.warn(`[ngx-cookie-service] Cookie ${name} was forced with secure flag because sameSite=None.More details : https://github.com/stevermeister/ngx-cookie-service/issues/86#issuecomment-597720130`);
}
if (options.partitioned && !options.secure) {
options.secure = true;
console.warn(`[ngx-cookie-service] Cookie ${name} was forced with secure flag because Partitioned cookies must be Secure.`);
}
if (options.secure) cookieString += "Secure;";
if (!options.sameSite) options.sameSite = "Lax";
cookieString += "SameSite=" + options.sameSite + ";";
if (options.partitioned) cookieString += "Partitioned;";
this.document.cookie = cookieString;
}
delete(name, pathOrOptions, domain, secure, sameSite) {
if (!this.documentIsAccessible) return;
const options = CookieService.toDeleteOptions(pathOrOptions, domain, secure, sameSite);
this.set(name, "", {
...options,
expires: /* @__PURE__ */ new Date("Thu, 01 Jan 1970 00:00:01 GMT")
});
}
deleteAll(pathOrOptions, domain, secure, sameSite) {
if (!this.documentIsAccessible) return;
for (const cookieName of Object.keys(this.getAll())) if (typeof pathOrOptions === "object" && pathOrOptions !== null) this.delete(cookieName, pathOrOptions);
else this.delete(cookieName, pathOrOptions, domain, secure, sameSite);
}
static {
this.uriCodec = {
encode: (value) => encodeURIComponent(value),
decode: (value) => CookieService.safeDecodeURIComponent(value)
};
}
static {
this.minimalCodec = {
encode: (value) => COOKIE_OCTET_REGEXP.test(value) ? value : encodeURIComponent(value),
decode: (value) => CookieService.safeDecodeURIComponent(value)
};
}
static toCodec(encoding) {
if (encoding === "minimal") return CookieService.minimalCodec;
if (typeof encoding === "object" && encoding !== null) return encoding;
return CookieService.uriCodec;
}
encodeValue(name, value) {
const encodedValue = this.codec.encode(value, name);
if (typeof encodedValue !== "string" || CookieService.hasUnsafeCharacter(encodedValue)) {
console.warn(`[ngx-cookie-service] Cookie ${name} was skipped because its encoded value isn't a string without ";" or control characters.`);
return;
}
return encodedValue;
}
decodeValue(value, name) {
try {
return this.codec.decode(value, name);
} catch {
return value;
}
}
static withDefaults(defaults, options = {}) {
const merged = { ...defaults };
for (const [key, value] of Object.entries(options)) if (value !== void 0 && value !== null) merged[key] = value;
return merged;
}
static validateOptions(name, options = {}) {
const { expires, ...valid } = options;
const result = valid;
for (const attribute of ["path", "domain"]) {
const attributeValue = result[attribute];
if (typeof attributeValue === "string" && CookieService.hasUnsafeCharacter(attributeValue)) {
console.warn(`[ngx-cookie-service] Cookie ${name} was skipped because its ${attribute} contains ";" or a control character.`);
return;
}
}
if (expires) {
const date = typeof expires === "number" ? new Date(Date.now() + expires * 1e3 * 60 * 60 * 24) : expires;
if (date instanceof Date && Number.isFinite(date.getTime())) result.expires = date;
else console.warn(`[ngx-cookie-service] Cookie ${name}: ignoring invalid expires value "${String(expires)}".`);
}
if (result.sameSite !== void 0 && result.sameSite !== null) {
const sameSite = SAME_SITE_VALUES.find((value) => value.toLowerCase() === String(result.sameSite).toLowerCase());
if (sameSite) result.sameSite = sameSite;
else {
console.warn(`[ngx-cookie-service] Cookie ${name}: ignoring invalid sameSite value "${String(result.sameSite)}".`);
delete result.sameSite;
}
}
return result;
}
static hasUnsafeCharacter(value) {
return [...value].some((character) => {
const code = character.charCodeAt(0);
return character === ";" || code < 32 || code === 127;
});
}
static toDeleteOptions(pathOrOptions, domain, secure, sameSite) {
if (typeof pathOrOptions === "object" && pathOrOptions !== null) return { ...pathOrOptions };
return {
path: pathOrOptions,
domain,
secure,
sameSite
};
}
static {
this.ɵfac = i0.ɵɵngDeclareFactory({
minVersion: "12.0.0",
version: "22.2.2",
ngImport: i0,
type: CookieService,
deps: [],
target: i0.ɵɵFactoryTarget.Injectable
});
}
static {
this.ɵprov = i0.ɵɵngDeclareInjectable({
minVersion: "12.0.0",
version: "22.2.2",
ngImport: i0,
type: CookieService,
providedIn: "root"
});
}
};
i0.ɵɵngDeclareClassMetadata({
minVersion: "12.0.0",
version: "22.2.2",
ngImport: i0,
type: CookieService,
decorators: [{
type: Injectable,
args: [{ providedIn: "root" }]
}],
ctorParameters: () => []
});
export { COOKIE_ENCODING, COOKIE_OPTIONS, CookieService, provideCookieEncoding, provideCookieOptions };
//# sourceMappingURL=ngx-cookie-service.mjs.map