@terminus/ngx-tools
Version:
[![CircleCI][circle-badge]][circle-link] [![codecov][codecov-badge]][codecov-project] [![semantic-release][semantic-release-badge]][semantic-release] [![MIT License][license-image]][license-url] <br> [![NPM version][npm-version-image]][npm-url] [![Github
258 lines (251 loc) • 9.33 kB
JavaScript
import { __decorate, __param } from 'tslib';
import { isPlatformBrowser, DOCUMENT } from '@angular/common';
import { Inject, InjectionToken, PLATFORM_ID, ɵɵdefineInjectable, ɵɵinject, Injectable } from '@angular/core';
var MS_IN_SECONDS = 1000;
var SECONDS_IN_MINUTE = 60;
var MINUTES_IN_HOUR = 60;
var HOURS_IN_DAY = 24;
var MS_IN_DAY = MS_IN_SECONDS * SECONDS_IN_MINUTE * MINUTES_IN_HOUR * HOURS_IN_DAY;
/**
* A service to manage browser cookies
*/
var TsCookieService = /** @class */ (function () {
function TsCookieService(
// HACK: This `any` is required. See comment inside constructor.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
_document, platformId) {
this._document = _document;
this.platformId = platformId;
// HACK: The angular compiler doesn't understand the type `Document` when determining the metadata for injectable parameters.
// So we are using `any` for the injection signature (making Angular happy), but coercing to a TypeScript type within the class.
// See https://github.com/angular/angular/issues/20351
this.document = _document;
// The PLATFORM_ID allows us to check if we're in a browser
this.documentIsAccessible = isPlatformBrowser(platformId);
}
/**
* Set a cookie
*
* @param name - Cookie name
* @param value - Cookie value
* @param expires - Number of days until the cookies expires or an actual `Date`
* @param path - Cookie path
* @param domain - Cookie domain
* @param secure - Secure flag
* @param sameSite - OWASP samesite token `Lax` or `Strict`
*/
TsCookieService.prototype.set = function (name, value, expires, path, domain, secure, sameSite) {
if (!this.documentIsAccessible) {
return;
}
var cookieString = encodeURIComponent(name) + "=" + encodeURIComponent(value) + ";";
if (expires) {
if (typeof expires === 'number') {
var dateExpires = new Date(new Date().getTime() + (expires * MS_IN_DAY));
cookieString += "expires=" + dateExpires.toUTCString() + ";";
}
else {
cookieString += "expires=" + expires.toUTCString() + ";";
}
}
if (path) {
cookieString += "path=" + path + ";";
}
if (domain) {
cookieString += "domain=" + domain + ";";
}
if (secure) {
cookieString += 'secure;';
}
if (sameSite) {
cookieString += "sameSite=" + sameSite + ";";
}
this.document.cookie = cookieString;
};
/**
* Verify if a cookie exists
*
* @param name - Cookie name
* @returns boolean
*/
TsCookieService.prototype.check = function (name) {
if (!this.documentIsAccessible) {
return false;
}
var regExp = this.getCookieRegExp(encodeURIComponent(name));
return regExp.test(this.document.cookie);
};
/**
* @param name - Cookie name
* @returns any
*/
TsCookieService.prototype.get = function (name) {
if (this.documentIsAccessible && this.check(name)) {
var regExp = this.getCookieRegExp(encodeURIComponent(name));
var result = regExp.exec(this.document.cookie);
return result ? decodeURIComponent(result[1]) /* istanbul ignore next - Unreachable */ : '';
}
return '';
};
/**
* Get all cookies
*
* @returns Object containing all cookies
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
TsCookieService.prototype.getAll = function () {
if (!this.documentIsAccessible) {
return {};
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
var cookies = {};
var document = this.document;
// istanbul ignore else
if (document.cookie && document.cookie !== '') {
var split = document.cookie.split(';').filter(function (v) { return v !== ''; });
// eslint-disable-next-line @typescript-eslint/prefer-for-of
for (var i = 0; i < split.length; i += 1) {
var currentCookie = split[i].split('=');
currentCookie[0] = currentCookie[0].replace(/^ /, '');
cookies[decodeURIComponent(currentCookie[0])] = decodeURIComponent(currentCookie[1]);
}
}
return cookies;
};
/**
* Delete a cookie
*
* NOTE: This clears the value and sets the cookie as expired. The browser will delete the expired cookie the next time a request
* is made to the domain.
*
* @param name - Cookie name
* @param path - Cookie path
* @param domain - Cookie domain
*/
TsCookieService.prototype.delete = function (name, path, domain) {
if (!this.documentIsAccessible) {
return;
}
this.set(name, '', new Date('Thu, 01 Jan 1970 00:00:01 GMT'), path, domain);
};
/**
* Delete all cookies
*
* @param path - Cookie path
* @param domain - Cookie domain
*/
TsCookieService.prototype.deleteAll = function (path, domain) {
if (!this.documentIsAccessible) {
return;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
var cookies = this.getAll();
for (var cookieName in cookies) {
// istanbul ignore else
if (cookies.hasOwnProperty(cookieName)) {
this.delete(cookieName, path, domain);
}
}
};
/**
* Get a regular expression based on a cookie name
*
* @param name - Cookie name
* @returns RegExp
*/
TsCookieService.prototype.getCookieRegExp = function (name) {
var escapedName = name.replace(/([\[\]\{\}\(\)\|\=\;\+\?\,\.\*\^\$])/ig, '\\$1');
return new RegExp("(?:^" + escapedName + "|;\\s*" + escapedName + ")=(.*?)(?:;|$)", 'g');
};
TsCookieService.ctorParameters = function () { return [
{ type: undefined, decorators: [{ type: Inject, args: [DOCUMENT,] }] },
{ type: InjectionToken, decorators: [{ type: Inject, args: [PLATFORM_ID,] }] }
]; };
TsCookieService.ɵprov = ɵɵdefineInjectable({ factory: function TsCookieService_Factory() { return new TsCookieService(ɵɵinject(DOCUMENT), ɵɵinject(PLATFORM_ID)); }, token: TsCookieService, providedIn: "root" });
TsCookieService = __decorate([
Injectable({ providedIn: 'root' }),
__param(0, Inject(DOCUMENT)),
__param(1, Inject(PLATFORM_ID))
], TsCookieService);
return TsCookieService;
}());
/**
* Return the native document object
*
* @returns The native document object
*/
var originalDocument = function () { return document; };
/**
* Define a service that exposes the DOCUMENT object
*/
var TsDocumentService = /** @class */ (function () {
function TsDocumentService() {
}
Object.defineProperty(TsDocumentService.prototype, "document", {
/**
* Return a function that returns the native document object
*
* @returns The function that returns the native document object
*/
get: function () {
return originalDocument();
},
enumerable: true,
configurable: true
});
TsDocumentService.ɵprov = ɵɵdefineInjectable({ factory: function TsDocumentService_Factory() { return new TsDocumentService(); }, token: TsDocumentService, providedIn: "root" });
TsDocumentService = __decorate([
Injectable({ providedIn: 'root' })
], TsDocumentService);
return TsDocumentService;
}());
/**
* Helper function to retrieve desired DOM attribute's value
*
* @param el - HTMLElement
* @param attr - Desired attribute
* @returns attribute's value
*
* @example
* getDomAttribute(myElement, 'id'); // Returns: the element ID
*/
function getDomAttribute(el, attr) {
var item = el.attributes.getNamedItem(attr);
return item ? item.value : undefined;
}
/**
* Return the native window object
*
* @returns The native window object
*/
var realWindow = function () { return window; };
var ɵ0 = realWindow;
/**
* Define a service that exposes the native window object
*/
var TsWindowService = /** @class */ (function () {
function TsWindowService() {
}
Object.defineProperty(TsWindowService.prototype, "nativeWindow", {
/**
* Return a function that returns the native window object
*
* @returns The function that returns the native window object
*/
get: function () {
return realWindow();
},
enumerable: true,
configurable: true
});
TsWindowService.ɵprov = ɵɵdefineInjectable({ factory: function TsWindowService_Factory() { return new TsWindowService(); }, token: TsWindowService, providedIn: "root" });
TsWindowService = __decorate([
Injectable({ providedIn: 'root' })
], TsWindowService);
return TsWindowService;
}());
/**
* Generated bundle index. Do not edit.
*/
export { TsCookieService, TsDocumentService, TsWindowService, getDomAttribute, originalDocument, ɵ0 };
//# sourceMappingURL=terminus-ngx-tools-browser.js.map