UNPKG

@martinmilo/verve

Version:

TypeScript domain modeling library with field-level authorization, business rule validation, and context-aware access control

104 lines 3.67 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Context = void 0; const errors_1 = require("../../errors"); let adapter = null; let hasExplicitlySetAdapter = false; var Context; (function (Context) { function setAdapter(customAdapter) { adapter = customAdapter; hasExplicitlySetAdapter = true; } Context.setAdapter = setAdapter; function useAsyncLocalStorage() { // More robust Node.js detection const hasNodejsAsyncHooks = (() => { try { // Check if we can access async_hooks without actually requiring it yet return typeof require !== 'undefined' && typeof process !== 'undefined' && process.versions && process.versions.node && typeof require.resolve === 'function'; } catch (_a) { return false; } })(); if (!hasNodejsAsyncHooks) { throw new errors_1.VerveError(errors_1.ErrorCode.ASYNC_LOCAL_STORAGE_REQUIRES_NODEJS); } try { const { AsyncLocalStorage } = require('async_hooks'); const asyncLocalStorage = new AsyncLocalStorage(); setAdapter({ get: () => asyncLocalStorage.getStore(), set: () => { throw new errors_1.VerveError(errors_1.ErrorCode.CONTEXT_USE_RUN_METHOD); }, reset: () => { throw new errors_1.VerveError(errors_1.ErrorCode.CONTEXT_AUTO_RESET); }, run: (context, fn) => asyncLocalStorage.run(context, fn) }); } catch (error) { throw new errors_1.VerveError(errors_1.ErrorCode.ASYNC_LOCAL_STORAGE_SETUP_FAILED, error instanceof Error ? error.message : String(error)); } } Context.useAsyncLocalStorage = useAsyncLocalStorage; function useGlobalStorage() { setAdapter(createGlobalContextAdapter()); } Context.useGlobalStorage = useGlobalStorage; function ensureAdapter() { if (!adapter) { // More robust Node.js detection for the error check const looksLikeNodeJS = typeof process !== 'undefined' && process.versions && process.versions.node && typeof require !== 'undefined'; if (looksLikeNodeJS && !hasExplicitlySetAdapter) { throw new errors_1.VerveError(errors_1.ErrorCode.CONTEXT_ADAPTER_REQUIRED); } // Fallback to global adapter for browser environments adapter = createGlobalContextAdapter(); } return adapter; } function set(context) { ensureAdapter().set(context); } Context.set = set; function get() { return ensureAdapter().get(); } Context.get = get; function reset() { ensureAdapter().reset(); } Context.reset = reset; function run(context, fn) { return ensureAdapter().run(context, fn); } Context.run = run; })(Context || (exports.Context = Context = {})); function createGlobalContextAdapter() { let globalContext; return { get: () => globalContext, set: (context) => { globalContext = context; }, reset: () => { globalContext = undefined; }, run: (context, fn) => { globalContext = context; try { return fn(); } finally { globalContext = undefined; } }, }; } //# sourceMappingURL=Context.js.map