const inflightScopes = new Map() function resolveScopeId(scope) { if (scope && typeof scope === 'string') { return scope } if (scope && typeof scope.route === 'string' && scope.route) { return scope.route } const pages = typeof getCurrentPages === 'function' ? getCurrentPages() : [] const current = pages[pages.length - 1] if (current && current.route) { return current.route } return 'global' } function getScopeMap(scopeId) { if (!inflightScopes.has(scopeId)) { inflightScopes.set(scopeId, new Map()) } return inflightScopes.get(scopeId) } function createGuardError(message, scopeId, actionKey) { const error = new Error(message || '\u64cd\u4f5c\u8fdb\u884c\u4e2d\uff0c\u8bf7\u52ff\u91cd\u590d\u70b9\u51fb') error.isActionGuardError = true error.scopeId = scopeId error.actionKey = actionKey return error } async function run(scope, actionKey, task, options) { const scopeId = resolveScopeId(scope) const normalizedKey = String(actionKey || 'default') const scopeMap = getScopeMap(scopeId) if (scopeMap.get(normalizedKey)) { return Promise.reject(createGuardError((options && options.message) || '', scopeId, normalizedKey)) } scopeMap.set(normalizedKey, true) try { return await Promise.resolve().then(() => task()) } finally { scopeMap.delete(normalizedKey) if (!scopeMap.size) { inflightScopes.delete(scopeId) } } } function isRunning(scope, actionKey) { const scopeId = resolveScopeId(scope) const scopeMap = inflightScopes.get(scopeId) if (!scopeMap) { return false } return Boolean(scopeMap.get(String(actionKey || 'default'))) } function clearScope(scope) { inflightScopes.delete(resolveScopeId(scope)) } function isGuardError(error) { return Boolean(error && error.isActionGuardError) } module.exports = { run, isRunning, clearScope, isGuardError, createGuardError }