UNPKG

async-states

Version:

Core of async-states

77 lines (74 loc) 2.1 kB
import { freeze } from '../helpers/core.js'; import { __DEV__ } from '../utils.js'; import devtools from '../devtools/Devtools.js'; let contexts = new WeakMap(); let globalContextKey = freeze({}); let globalContext = createContext(globalContextKey); function createNewContext(arg) { let instances = new Map(); let createdContext = { ctx: arg, payload: {}, get(key) { return instances.get(key); }, remove(key) { return instances.delete(key); }, set(key, inst) { instances.set(key, inst); }, getAll() { return [...instances.values()]; }, terminate() { instances = new Map(); }, }; if (__DEV__) devtools.captureContext(createdContext); return createdContext; } function createContext(arg) { // null means the static global context if (arg === null) { return globalContext; } if (typeof arg !== "object") { throw new Error("createContext requires an object. Received " + String(typeof arg)); } let existingContext = contexts.get(arg); if (existingContext) { return existingContext; } let newContext = createNewContext(arg); contexts.set(arg, newContext); return newContext; } function requestContext(arg) { if (arg === null) { return globalContext; } let context = contexts.get(arg); if (!context) { throw new Error("Context not found. Please make sure to call createContext before " + "requestContext."); } return context; } function terminateContext(arg) { if (!arg) { return false; } let desiredContext = contexts.get(arg); if (!desiredContext) { return false; } // this will un-reference all instances from the context desiredContext.terminate(); if (__DEV__) devtools.releaseContext(desiredContext); return contexts.delete(arg); } export { createContext, requestContext, terminateContext }; //# sourceMappingURL=StateContext.js.map