UNPKG

@comunica/core

Version:

Lightweight, semantic and modular actor framework

106 lines • 3.4 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ActionContextKey = exports.ActionContext = void 0; /** * Implementation of {@link IActionContext} backed by a native Map, which is never modified after construction. * Modifications copy the map. */ class ActionContext { map; constructor(data = {}) { // Maps are only passed internally, by contexts that do not modify them anymore this.map = data instanceof Map ? data : new Map(Object.entries(data)); } /** * Will only set the value if the key is not already set. */ setDefault(key, value) { return this.has(key) ? this : this.set(key, value); } set(key, value) { return this.setRaw(key.name, value); } setRaw(key, value) { const map = new Map(this.map); map.set(key, value); return new ActionContext(map); } delete(key) { if (!this.map.has(key.name)) { return new ActionContext(this.map); } const map = new Map(this.map); map.delete(key.name); return new ActionContext(map); } get(key) { return this.getRaw(key.name); } getRaw(key) { return this.map.get(key); } getSafe(key) { if (!this.has(key)) { throw new Error(`Context entry ${key.name} is required but not available`); } return this.get(key); } has(key) { return this.hasRaw(key.name); } hasRaw(key) { return this.map.has(key); } merge(...contexts) { // The entries are only copied once, when the first entry is merged let map; for (const source of contexts) { for (const key of source.keys()) { map ??= new Map(this.map); map.set(key.name, source.get(key)); } } return map ? new ActionContext(map) : this; } keys() { return [...this.map.keys()].map(keyName => new ActionContextKey(keyName)); } toJS() { return Object.fromEntries(this.map); } toString() { return `ActionContext(${JSON.stringify(this.toJS())})`; } [Symbol.for('nodejs.util.inspect.custom')]() { return `ActionContext(${JSON.stringify(this.toJS(), null, ' ')})`; } /** * Convert the given object to an action context object if it is not an action context object yet. * If it already is an action context object, return the object as-is. * @param maybeActionContext An action context or record. * @return {ActionContext} An action context object. */ static ensureActionContext(maybeActionContext) { // This should only be an instanceof, but can fail when this package is loaded multiple times, // with multiple ActionContexts existing in parallel. return maybeActionContext instanceof ActionContext || (maybeActionContext && 'map' in maybeActionContext) ? maybeActionContext : new ActionContext(maybeActionContext); } } exports.ActionContext = ActionContext; /** * Simple implementation of {@link IActionContextKey}. */ class ActionContextKey { /** * A unique context key name. */ name; dummy; constructor(name) { this.name = name; } } exports.ActionContextKey = ActionContextKey; //# sourceMappingURL=ActionContext.js.map