@cldmv/slothlet 3.15.1 → 3.15.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -43,17 +43,17 @@ Every feature has been hardened with a comprehensive test suite - over **5,300 t
43
43
 
44
44
  ## ✨ What's New
45
45
 
46
- ### Latest: v3.15.1 (August 2026)
46
+ ### Latest: v3.15.2 (September 2026)
47
47
 
48
- - **Maintenance & supply-chain hardening — no runtime changes** — The public API and loader behavior are identical to 3.15.0. This release scopes every GitHub Actions workflow token to least privilege (#319), clears two high-severity advisories in the dev-only test/lint toolchain (`brace-expansion`, `nanoid` — transitive, never shipped to consumers; #322), adds an OpenSSF Scorecard badge (#320), and fixes documentation links and CI plumbing (#316, #321, #314).
49
- - [View full v3.15.1 Changelog](https://github.com/CLDMV/slothlet/blob/master/docs/changelog/v3/v3.15.1.md)
48
+ - **Core context/composition bug-fix release** — Closes several gaps where documented behavior didn't actually hold: class-instance context propagation now fires for `async` factory leaves (#328), writable `self.X = <object>` wrap-on-set now gets the same context wrapping and permission read-gating as `api.slothlet.api.add()` (#329), and `api.slothlet.api.add()` no longer hangs when a mounted object carries a live `net.Socket` or other circular/native value (#330). Also fixes a process-wide memory leak in the global EventEmitter context patch that grew RSS unboundedly in long-lived services (#335). No breaking changes — a drop-in for 3.15.1; coverage restored to 100% (#334).
49
+ - [View full v3.15.2 Changelog](https://github.com/CLDMV/slothlet/blob/master/docs/changelog/v3/v3.15.2.md)
50
50
 
51
51
  ### Recent Releases
52
52
 
53
+ - **v3.15.1** (August 2026) — Maintenance & supply-chain hardening, no runtime changes: least-privilege GitHub Actions token permissions (#319), two high-severity dev-only toolchain advisories cleared (#322), and an OpenSSF Scorecard badge (#320) ([Changelog](https://github.com/CLDMV/slothlet/blob/master/docs/changelog/v3/v3.15.1.md))
53
54
  - **v3.15.0** (August 2026) — Character-safe `moduleID`s and scoped `remove(moduleID, apiPath)`: a `moduleID` may contain any character and round-trips through `add`/`leaves`/`remove`/`reload`; scoped removals and synthetic adds now survive `reload()`; plus a prototype-pollution guard on mount paths (#303, #302, #304) ([Changelog](https://github.com/CLDMV/slothlet/blob/master/docs/changelog/v3/v3.15.0.md))
54
55
  - **v3.14.0** (August 2026) — Browser importmap resolves consumer-graph package `exports` subpaths (not just slothlet's own surface), so a redirected dependency subpath no longer 404s in the browser and consumers can drop hand-maintained allowlists (#297) ([Changelog](https://github.com/CLDMV/slothlet/blob/master/docs/changelog/v3/v3.14.0.md))
55
56
  - **v3.13.3** (August 2026) — Completes the version-dispatcher permissions fix (a second framework read path probed the marker with a gated `__`-private read) by detecting a dispatcher by object identity, and fixes nested-instance permission isolation so a second `slothlet()` booted inside a permissioned leaf no longer throws during its own construction ([Changelog](https://github.com/CLDMV/slothlet/blob/master/docs/changelog/v3/v3.13.3.md))
56
- - **v3.13.2** (August 2026) — Restores composition of version-dispatched fields under a `permissions` configuration: slothlet's own version-dispatcher marker keys are exempted from the 3.13.0 module-private (`_`/`__`) rule by object identity, so a colliding version-dispatched field no longer fails at composition with `PERMISSION_DENIED` while a consumer's identically-named private member stays denied ([Changelog](https://github.com/CLDMV/slothlet/blob/master/docs/changelog/v3/v3.13.2.md))
57
57
 
58
58
  📚 **For complete version history and detailed release notes, see [docs/changelog/](https://github.com/CLDMV/slothlet/tree/master/docs/changelog/) folder.**
59
59
 
@@ -14,4 +14,4 @@
14
14
  limitations under the License.
15
15
  */
16
16
 
17
- import{isNode,AsyncResource,loadJson}from"@cldmv/slothlet/helpers/platform";import{ComponentBase}from"#factories/component-base";import{TYPE_STATES}from"#handlers/unified-wrapper";import{TRUSTED_ROOT,PROTECT_SENTINEL}from"#handlers/trusted-root";import{getLanguage,initI18n,setLanguage,setLanguageAsync,t,translate}from"@cldmv/slothlet/i18n";function _resolvePathOrModuleId(slothlet,pathOrModuleId){const history=slothlet.handlers?.apiManager?.state?.addHistory;if(history){let match=null;for(let i=history.length-1;i>=0;i--){const entry=history[i];if(entry?.moduleID===pathOrModuleId){match=entry;break}}if(match)return match.apiPath}return pathOrModuleId}function describeScopeReceived(value){if(Array.isArray(value)){const badIndex=value.findIndex(entry=>typeof entry!=="string");if(badIndex!==-1){return`array with non-string entry (${typeof value[badIndex]} at index ${badIndex})`}return"array"}return typeof value}function makeCopyOnWriteSelf(parentSelf){const overlay=new Map;const childViews=new Map;return new Proxy({},{get(_t,prop){if(overlay.has(prop))return overlay.get(prop);const real=parentSelf[prop];if(real!==null&&typeof real==="object"){let view=childViews.get(prop);if(view===void 0){view=makeCopyOnWriteSelf(real);childViews.set(prop,view)}return view}return real},set(_t,prop,value){overlay.set(prop,value);childViews.delete(prop);return true},has(_t,prop){return overlay.has(prop)||prop in parentSelf},deleteProperty(_t,prop){overlay.delete(prop);childViews.delete(prop);return true},ownKeys(){const keys=new Set(Reflect.ownKeys(parentSelf));for(const k of overlay.keys())keys.add(k);return[...keys]},getOwnPropertyDescriptor(_t,prop){if(overlay.has(prop)){return{value:overlay.get(prop),writable:true,enumerable:true,configurable:true}}const desc=Reflect.getOwnPropertyDescriptor(parentSelf,prop);return desc?{...desc,configurable:true}:void 0}})}class ApiBuilder extends ComponentBase{static slothletProperty="apiBuilder";constructor(slothlet){super(slothlet)}async buildFinalAPI(userApi){this.slothlet.debug("api",{key:"DEBUG_MODE_BUILD_FINAL_API_CALLED",diagnostics:this.____config.diagnostics,userApiKeys:Object.keys(userApi)});if(this.slothlet._ownBuiltins){for(const[key,ref]of Object.entries(this.slothlet._ownBuiltins)){if(ref&&Object.prototype.hasOwnProperty.call(userApi,key)&&userApi[key]===ref){try{delete userApi[key]}catch(_){}}}}this.slothlet.userHooks={shutdown:typeof userApi.shutdown==="function"?userApi.shutdown:null,destroy:typeof userApi.destroy==="function"?userApi.destroy:null};if(userApi.slothlet){if(!this.____config?.silent){new this.SlothletWarning("WARNING_RESERVED_PROPERTY_CONFLICT",{properties:"slothlet"})}await this.emitImplDiagnostic("warning",{apiPath:"slothlet",code:"WARNING_RESERVED_PROPERTY_CONFLICT",context:{properties:"slothlet"},source:"buildAPI"})}const slothletNamespace=await this.createSlothletNamespace(userApi);this.slothlet.debug("api",{key:"DEBUG_MODE_SLOTHLET_NAMESPACE_CREATED",namespaceKeys:Object.keys(slothletNamespace),hasDiag:!!slothletNamespace.diag});const shutdownFn=this.createShutdownFunction();this.attachBuiltins(userApi,{slothlet:slothletNamespace,shutdown:shutdownFn,destroy:null});this.slothlet.debug("api",{key:"DEBUG_MODE_BUILT_INS_ATTACHED",userApiKeys:Object.keys(userApi),hasSlothlet:!!userApi.slothlet,hasDiag:!!userApi.slothlet?.diag});const destroyWithApi=this.createDestroyFunction(userApi);Object.defineProperty(userApi,"destroy",{value:destroyWithApi,enumerable:true,writable:false,configurable:true});this.slothlet._ownBuiltins={shutdown:shutdownFn,slothlet:slothletNamespace,destroy:destroyWithApi};return userApi}async createSlothletNamespace(userApi){const slothlet=this.slothlet;const config=this.____config;const enforceInternalPermission=targetPath=>{const ctx=slothlet.contextManager?.tryGetContext?.(slothlet.instanceID);const identity=slothlet.contextManager?.getCallerIdentity?.(slothlet.instanceID);if(identity?.unresolved){throw new slothlet.SlothletError("PERMISSION_DENIED",{caller:null,target:targetPath})}const callerWrapper=identity?.currentWrapper;if(!callerWrapper)return;const permissionManager=slothlet.handlers?.permissionManager;if(!permissionManager?.enforceAccess){throw new slothlet.SlothletError("PERMISSION_MANAGER_NOT_AVAILABLE",{validationError:true})}const callerPath=callerWrapper.____slothletInternal?.apiPath??"";const callerFilePath=callerWrapper.____slothletInternal?.filePath??null;const runtimeContext=ctx?.context??null;if(!permissionManager.enforceAccess(callerPath,targetPath,callerFilePath,null,runtimeContext)){throw new slothlet.SlothletError("PERMISSION_DENIED",{caller:callerPath,target:targetPath})}};const canTraverseInternalNamespace=targetPath=>{const ctx=slothlet.contextManager?.tryGetContext?.(slothlet.instanceID);const identity=slothlet.contextManager?.getCallerIdentity?.(slothlet.instanceID);if(identity?.unresolved)return false;const callerWrapper=identity?.currentWrapper;if(!callerWrapper)return false;const permissionManager=slothlet.handlers?.permissionManager;if(!permissionManager?.getRulesForCaller||!permissionManager?.checkAccess){return false}const callerPath=callerWrapper.____slothletInternal?.apiPath??"";const callerFilePath=callerWrapper.____slothletInternal?.filePath??null;const runtimeContext=ctx?.context??null;const callerRules=permissionManager.getRulesForCaller(callerPath);const conditionMatches=condition=>typeof permissionManager.matchesCondition==="function"?permissionManager.matchesCondition(condition,runtimeContext):false;const prefix=`${targetPath}.`;for(const rule of callerRules){if(!rule||rule.effect!=="allow"||typeof rule.target!=="string")continue;const couldMatchDescendant=rule.target.startsWith(prefix)||rule.target==="**"||rule.target==="*";if(!couldMatchDescendant)continue;if(rule.target.startsWith(prefix)&&conditionMatches(rule.condition)){return true}const probePaths=[`${targetPath}.__probe__`];if(rule.target.startsWith(prefix)){const suffix=rule.target.slice(prefix.length);const firstSegment=suffix.split(".")[0];if(firstSegment&&!/[*!?{}]/u.test(firstSegment)){probePaths.unshift(`${targetPath}.${firstSegment}`);probePaths.push(`${targetPath}.${firstSegment}.__probe__`)}}for(const probePath of probePaths){if(permissionManager.checkAccess(callerPath,probePath,callerFilePath,null,runtimeContext,{useCache:false})){return true}}}return false};const createInternalRouteProxy=(value,routePath,seen=new WeakMap)=>{if(!value||typeof value!=="object"&&typeof value!=="function")return value;const isMetaProperty=prop=>prop==="__proto__"||prop==="prototype"||prop==="constructor"||prop==="caller"||prop==="arguments";let routeCache=seen.get(value);if(!routeCache){routeCache=new Map;seen.set(value,routeCache)}if(routeCache.has(routePath)){return routeCache.get(routePath)}const proxy=new Proxy(value,{get(target,prop,receiver){if(typeof prop!=="string"){const result2=Reflect.get(target,prop,receiver);return createInternalRouteProxy(result2,routePath,seen)}const childRoutePath=`${routePath}.${prop}`;let deniedError=null;try{enforceInternalPermission(childRoutePath)}catch(error){deniedError=error}if(deniedError){if(canTraverseInternalNamespace(childRoutePath)){const result2=Reflect.get(target,prop,receiver);if(result2&&(typeof result2==="object"||typeof result2==="function")){return createInternalRouteProxy(result2,childRoutePath,seen)}}throw deniedError}const result=Reflect.get(target,prop,receiver);if(isMetaProperty(prop)){return result}const descriptor=Object.getOwnPropertyDescriptor(target,prop);if(descriptor&&"value"in descriptor&&descriptor.configurable===false&&descriptor.writable===false){return descriptor.value}return createInternalRouteProxy(result,childRoutePath,seen)},getOwnPropertyDescriptor(target,prop){const descriptor=Reflect.getOwnPropertyDescriptor(target,prop);if(!descriptor)return void 0;if(typeof prop!=="string"){return descriptor}const childRoutePath=`${routePath}.${prop}`;if(isMetaProperty(prop)){enforceInternalPermission(childRoutePath);return descriptor}if("get"in descriptor||"set"in descriptor){enforceInternalPermission(childRoutePath);if(descriptor.configurable===true){return{...descriptor,get:typeof descriptor.get==="function"?function slothlet_internal_descriptor_getter(...args){enforceInternalPermission(childRoutePath);return Reflect.apply(descriptor.get,this,args)}:descriptor.get,set:typeof descriptor.set==="function"?function slothlet_internal_descriptor_setter(...args){enforceInternalPermission(childRoutePath);return Reflect.apply(descriptor.set,this,args)}:descriptor.set}}return descriptor}if(!("value"in descriptor)){return descriptor}const descriptorValue=descriptor.value;if(descriptor.configurable===false&&descriptor.writable===false){enforceInternalPermission(childRoutePath);return descriptor}if(!descriptorValue||typeof descriptorValue!=="object"&&typeof descriptorValue!=="function"||typeof descriptorValue==="function"){enforceInternalPermission(childRoutePath);if(typeof descriptorValue==="function"&&descriptor.configurable===true){return{...descriptor,value:createInternalRouteProxy(descriptorValue,childRoutePath,seen)}}return descriptor}return{...descriptor,value:createInternalRouteProxy(descriptorValue,childRoutePath,seen)}},set(target,prop,newValue,receiver){if(typeof prop!=="string"){return Reflect.set(target,prop,newValue,receiver)}const childRoutePath=`${routePath}.${prop}`;enforceInternalPermission(childRoutePath);return Reflect.set(target,prop,newValue,receiver)},defineProperty(target,prop,descriptor){if(typeof prop!=="string"){return Reflect.defineProperty(target,prop,descriptor)}const childRoutePath=`${routePath}.${prop}`;enforceInternalPermission(childRoutePath);return Reflect.defineProperty(target,prop,descriptor)},deleteProperty(target,prop){if(typeof prop!=="string"){return Reflect.deleteProperty(target,prop)}const childRoutePath=`${routePath}.${prop}`;enforceInternalPermission(childRoutePath);return Reflect.deleteProperty(target,prop)},ownKeys(target){return Reflect.ownKeys(target)},apply(target,thisArg,argArray){enforceInternalPermission(routePath);return Reflect.apply(target,thisArg,argArray)},construct(target,argArray,newTarget){enforceInternalPermission(routePath);return Reflect.construct(target,argArray,newTarget)}});routeCache.set(routePath,proxy);return proxy};let version="unknown";if(isNode){const pkg=loadJson(new URL("../../../package.json",import.meta.url));if(pkg?.version)version=pkg?.version}const namespace={i18n:{setLanguage,setLanguageAsync,getLanguage,translate,t,initI18n},version,instanceID:slothlet.instanceID,types:TYPE_STATES,api:{add:async function slothlet_api_add(apiPath,folderPath,options={},versionConfig=null){if(!config.api?.mutations?.add){throw new slothlet.SlothletError("INVALID_CONFIG_MUTATIONS_DISABLED",{operation:"api.add",validationError:true})}const{recordHistory:____recordHistory,collisionMode:____collisionMode,mutateExisting:____mutateExisting,...filteredOptions}=options;return slothlet.handlers.apiManager.addApiComponent({apiPath,folderPath,options:filteredOptions,versionConfig:versionConfig||null})},remove:async function slothlet_api_remove(pathOrModuleId,apiPath){if(!config.api?.mutations?.remove){throw new slothlet.SlothletError("INVALID_CONFIG_MUTATIONS_DISABLED",{operation:"api.remove",validationError:true})}if(typeof pathOrModuleId!=="string"){throw new slothlet.SlothletError("INVALID_ARGUMENT",{argument:"pathOrModuleId",expected:"string",received:typeof pathOrModuleId,validationError:true})}if(apiPath!==void 0&&typeof apiPath!=="string"){throw new slothlet.SlothletError("INVALID_ARGUMENT",{argument:"apiPath",expected:"string",received:typeof apiPath,validationError:true})}return slothlet.handlers.apiManager.removeApiComponent(pathOrModuleId,{scopedApiPath:apiPath})},leaves:async function slothlet_api_leaves(key,options={}){enforceInternalPermission("slothlet.api.leaves");if(typeof key!=="string"){throw new slothlet.SlothletError("INVALID_ARGUMENT",{argument:"key",expected:"string",received:typeof key,validationError:true})}const normalizedOptions=options==null?{}:options;if(typeof normalizedOptions!=="object"||Array.isArray(normalizedOptions)){throw new slothlet.SlothletError("INVALID_ARGUMENT",{argument:"options",expected:"object with optional boolean details/includePrivate",received:Array.isArray(normalizedOptions)?"array":typeof normalizedOptions,validationError:true})}const{details=false,includePrivate=false}=normalizedOptions;for(const[name,value]of[["details",details],["includePrivate",includePrivate]]){if(typeof value!=="boolean"){throw new slothlet.SlothletError("INVALID_ARGUMENT",{argument:`options.${name}`,expected:"boolean",received:typeof value,validationError:true})}}const ownership=slothlet.handlers.ownership;const leavesIdentity=slothlet.contextManager?.getCallerIdentity?.();const leavesCaller=leavesIdentity?.currentWrapper??null;if(includePrivate&&leavesCaller){throw new slothlet.SlothletError("PERMISSION_DENIED",{caller:leavesCaller.____slothletInternal?.apiPath??"",target:"slothlet.api.leaves:includePrivate"})}let moduleID=null;if(key==="."||key===""){moduleID=[...ownership.moduleEndpoints.entries()].find(([,endpoint2])=>endpoint2===".")?.[0]}else if(ownership.moduleToPath.has(key)){moduleID=key}else{moduleID=ownership.getCurrentOwner(key)?.moduleID??null;if(!moduleID){moduleID=[...ownership.moduleEndpoints.entries()].find(([,endpoint2])=>endpoint2===key)?.[0]??null}}if(!moduleID||!ownership.moduleToPath.has(moduleID)){throw new slothlet.SlothletError("API_LEAVES_UNKNOWN_MODULE",{key},null,{validationError:true})}const endpoint=ownership.moduleEndpoints.get(moduleID);const boundApi=slothlet.boundApi;if(config.mode==="lazy"&&boundApi){const seen=new WeakSet;let root=boundApi;if(endpoint!=="."){for(const segment of endpoint.split("."))root=root[segment]}const pending=[{node:root,path:endpoint==="."?"":endpoint}];while(pending.length>0){const{node,path}=pending.pop();if(node===null||typeof node!=="object"&&typeof node!=="function")continue;if(seen.has(node))continue;seen.add(node);if(typeof node._materialize==="function"&&node.__materialized===false){await node._materialize()}const childKeys=new Set(Object.keys(node));const records=ownership.moduleToPath.get(moduleID);if(path!==null&&records){const prefix=path===""?"":`${path}.`;for(const ownedPath of records){if(ownedPath===""||prefix!==""&&!ownedPath.startsWith(prefix))continue;const rest=ownedPath.slice(prefix.length);const segmentEnd=rest.indexOf(".");childKeys.add(segmentEnd===-1?rest:rest.slice(0,segmentEnd))}}for(const childKey of childKeys){if(path===""&&(childKey==="slothlet"||childKey==="shutdown"||childKey==="destroy"))continue;let child;try{child=node[childKey]}catch{continue}const childPath=path===null?null:path===""?childKey:`${path}.${childKey}`;pending.push({node:child,path:records?.has(childPath)?childPath:null})}}}if(!ownership.moduleToPath.has(moduleID)){throw new slothlet.SlothletError("API_LEAVES_UNKNOWN_MODULE",{key},null,{validationError:true})}const ownedPaths=[...ownership.moduleToPath.get(moduleID)].filter(path=>{if(path==="")return false;if(endpoint==="."&&(path==="slothlet"||path.startsWith("slothlet.")||path==="shutdown"||path==="destroy"))return false;const currentOwner=ownership.getCurrentOwner(path);return!currentOwner||currentOwner.moduleID===moduleID});ownedPaths.sort();const namespaces=new Set;for(const owned of ownedPaths){let cut=owned.lastIndexOf(".");while(cut>0){namespaces.add(owned.slice(0,cut));cut=owned.lastIndexOf(".",cut-1)}}const kindOf=path=>{if(namespaces.has(path))return"namespace";const entry=ownership.pathToModule.get(path)?.find(candidate=>candidate.moduleID===moduleID);return typeof entry?.value==="function"?"function":"data"};const permissionManager=slothlet.handlers?.permissionManager;let visiblePaths=ownedPaths;if(!includePrivate&&permissionManager?.isEnabled?.()){const callerPath=leavesCaller?.____slothletInternal?.apiPath??"";const callerFilePath=leavesCaller?.____slothletInternal?.filePath??null;const runtimeContext=slothlet.contextManager?.tryGetContext?.()?.context??null;visiblePaths=ownedPaths.filter(path=>{if(!permissionManager.isPrivateTarget(path))return true;const entry=ownership.pathToModule.get(path)?.find(candidate=>candidate.moduleID===moduleID);return permissionManager.checkAccess(callerPath,path,callerFilePath,entry?.filePath,runtimeContext)})}if(details){return visiblePaths.map(path=>({path,kind:kindOf(path)}))}return visiblePaths.filter(path=>kindOf(path)==="function")},reload:async function slothlet_api_reload(pathOrModuleId,options){if(!config.api?.mutations?.reload){throw new slothlet.SlothletError("INVALID_CONFIG_MUTATIONS_DISABLED",{operation:"api.reload",validationError:true})}if(pathOrModuleId==null||pathOrModuleId===""||pathOrModuleId==="."){return slothlet.handlers.apiManager.reloadApiComponent({apiPath:".",options})}if(typeof pathOrModuleId!=="string"){throw new slothlet.SlothletError("INVALID_ARGUMENT",{argument:"pathOrModuleId",expected:"string, null, undefined, or '.'",received:typeof pathOrModuleId,validationError:true})}const isModuleId=slothlet.handlers.apiManager.state.addHistory.some(entry=>entry.moduleID===pathOrModuleId);if(isModuleId){return slothlet.handlers.apiManager.reloadApiComponent({moduleID:pathOrModuleId,options})}const normalizedPath=slothlet.handlers.apiManager.normalizeApiPath(pathOrModuleId).apiPath;const pathParts=normalizedPath.split(".");let current=slothlet.api;for(const part of pathParts){if(!current||typeof current!=="object"&&typeof current!=="function"){throw new slothlet.SlothletError("INVALID_API_PATH",{apiPath:pathOrModuleId,validationError:true})}current=current[part]}if(current===void 0){throw new slothlet.SlothletError("INVALID_API_PATH",{apiPath:pathOrModuleId,validationError:true})}return slothlet.handlers.apiManager.reloadApiComponent({apiPath:normalizedPath,options})},modules:{discover:function slothlet_modules_discover(options){return slothlet.handlers.moduleManager.discover(options)},sort:function slothlet_modules_sort(results,comparator){return slothlet.handlers.moduleManager.sort(results,comparator)},addModule:async function slothlet_modules_addModule(nameOrResult,options){if(!config.api?.mutations?.add){throw new slothlet.SlothletError("INVALID_CONFIG_MUTATIONS_DISABLED",{operation:"api.modules.addModule",validationError:true})}return slothlet.handlers.moduleManager.addModule(nameOrResult,options)},addModules:async function slothlet_modules_addModules(items,options){if(!config.api?.mutations?.add){throw new slothlet.SlothletError("INVALID_CONFIG_MUTATIONS_DISABLED",{operation:"api.modules.addModules",validationError:true})}return slothlet.handlers.moduleManager.addModules(items,options)},removeModule:async function slothlet_modules_removeModule(name,opts){if(!config.api?.mutations?.remove){throw new slothlet.SlothletError("INVALID_CONFIG_MUTATIONS_DISABLED",{operation:"api.modules.removeModule",validationError:true})}return slothlet.handlers.moduleManager.removeModule(name,opts)},addDiscovered:async function slothlet_modules_addDiscovered(options={}){if(!config.api?.mutations?.add){throw new slothlet.SlothletError("INVALID_CONFIG_MUTATIONS_DISABLED",{operation:"api.modules.addDiscovered",validationError:true})}const{sort:comparator,collisionMode,onFailure,concurrency,...discoverOptions}=options;const found=await slothlet.handlers.moduleManager.discover(discoverOptions);const ordered=slothlet.handlers.moduleManager.sort(found,comparator);return slothlet.handlers.moduleManager.addModules(ordered,{collisionMode,onFailure,concurrency})},getDiscoveryCache:function slothlet_modules_getDiscoveryCache(){return slothlet.handlers.moduleManager.getDiscoveryCache()},clearDiscoveryCache:function slothlet_modules_clearDiscoveryCache(){return slothlet.handlers.moduleManager.clearDiscoveryCache()},getStaleMounts:function slothlet_modules_getStaleMounts(){return slothlet.handlers.moduleManager.getStaleMounts()}}},sanitize:function slothlet_sanitize(str){if(typeof str!=="string"){throw new slothlet.SlothletError("INVALID_ARGUMENT",{argument:"str",expected:"string",received:typeof str,validationError:true})}return slothlet.helpers.sanitize.sanitizePropertyName(str,slothlet.config.sanitize||{})},lockCaller:function slothlet_lockCaller(fn){if(typeof fn!=="function"){throw new slothlet.SlothletError("INVALID_ARGUMENT",{argument:"fn",expected:"function",received:typeof fn,validationError:true})}const capturedWrapper=slothlet.contextManager?.getCallerIdentity?.()?.currentWrapper??null;if(!capturedWrapper)return fn;const locked=function slothlet_lockedCaller(...args){return slothlet.contextManager.runInContext(slothlet.instanceID,fn,this,args,capturedWrapper,true)};locked._slothletOriginal=fn;return locked},bind:function slothlet_bind(fn){if(typeof fn!=="function"){throw new slothlet.SlothletError("INVALID_ARGUMENT",{argument:"fn",expected:"function",received:typeof fn,validationError:true})}return AsyncResource?AsyncResource.bind(fn,"slothlet-bound"):fn},context:{get:key=>{if(slothlet.contextManager.constructor.name==="LiveContextManager"){const currentID=slothlet.contextManager.currentInstanceID;if(currentID){const activeStore=slothlet.contextManager.instances.get(currentID);const isOurInstance=currentID===slothlet.instanceID||currentID?.startsWith(slothlet.instanceID+"__run_")||activeStore?.parentInstanceID===slothlet.instanceID;if(isOurInstance&&activeStore){return key?activeStore.context[key]:{...activeStore.context}}}const store=slothlet.contextManager.instances.get(slothlet.instanceID);if(!store){const baseContext2=slothlet.context||{};return key?baseContext2[key]:{...baseContext2}}return key?store.context[key]:{...store.context}}if(slothlet.contextManager.constructor.name==="AsyncContextManager"){let currentStore=slothlet.contextManager.tryGetContext();if(!currentStore){const baseStore2=slothlet.contextManager.instances.get(slothlet.instanceID);const baseContext3=baseStore2?.context||{};return key?baseContext3[key]:{...baseContext3}}const isOurInstance=currentStore.instanceID===slothlet.instanceID||currentStore.parentInstanceID===slothlet.instanceID||currentStore.instanceID.startsWith(slothlet.instanceID+"__run_");if(isOurInstance){return key?currentStore.context[key]:{...currentStore.context}}const baseStore=slothlet.contextManager.instances.get(slothlet.instanceID);const baseContext2=baseStore?.context||{};return key?baseContext2[key]:{...baseContext2}}const baseContext=slothlet.context||{};return key?baseContext[key]:{...baseContext}},diagnostics:()=>{if(!slothlet.config?.diagnostics)return void 0;const managerType=slothlet.contextManager.constructor.name;const result={instanceID:slothlet.instanceID,managerType,instancesMapSize:slothlet.contextManager.instances.size,instancesMapKeys:Array.from(slothlet.contextManager.instances.keys()),baseContext:slothlet.context};const store=slothlet.contextManager.instances.get(slothlet.instanceID);result.storeFromInstancesMap=store?{instanceID:store.instanceID,context:store.context,createdAt:store.createdAt}:null;if(managerType==="AsyncContextManager"){try{const currentCtx=slothlet.contextManager.tryGetContext();result.currentALSContext=currentCtx?{instanceID:currentCtx.instanceID,context:currentCtx.context,hasParent:!!currentCtx.parentContext,parentInstanceID:currentCtx.parentInstanceID}:null}catch(____error){result.currentALSContext=null}}if(managerType==="LiveContextManager"){result.currentInstanceID=slothlet.contextManager.currentInstanceID}return result},run:this.createRunFunction(),scope:this.createScopeFunction()},hook:{on:function slothlet_hook_on(typePattern,handler,options={}){if(!slothlet.handlers?.hookManager){throw new slothlet.SlothletError("HOOKS_NOT_INITIALIZED",{validationError:true})}return slothlet.handlers.hookManager.on(typePattern,handler,options)},remove:function slothlet_hook_remove(filter={}){if(!slothlet.handlers?.hookManager){throw new slothlet.SlothletError("HOOKS_NOT_INITIALIZED",{validationError:true})}return slothlet.handlers.hookManager.remove(filter)},clear:function slothlet_hook_clear(filter={}){return this.remove(filter)},off:function slothlet_hook_off(idOrFilter){if(!slothlet.handlers?.hookManager){throw new slothlet.SlothletError("HOOKS_NOT_INITIALIZED",{validationError:true})}const filter=typeof idOrFilter==="string"?{id:idOrFilter}:idOrFilter;return slothlet.handlers.hookManager.remove(filter)},enable:function slothlet_hook_enable(filter={}){if(!slothlet.handlers?.hookManager){throw new slothlet.SlothletError("HOOKS_NOT_INITIALIZED",{validationError:true})}return slothlet.handlers.hookManager.enable(filter)},disable:function slothlet_hook_disable(filter={}){if(!slothlet.handlers?.hookManager){throw new slothlet.SlothletError("HOOKS_NOT_INITIALIZED",{validationError:true})}return slothlet.handlers.hookManager.disable(filter)},enablePattern:function slothlet_hook_enablePattern(pattern){if(!slothlet.handlers?.hookManager){throw new slothlet.SlothletError("HOOKS_NOT_INITIALIZED",{validationError:true})}return slothlet.handlers.hookManager.enablePattern(pattern)},disablePattern:function slothlet_hook_disablePattern(pattern){if(!slothlet.handlers?.hookManager){throw new slothlet.SlothletError("HOOKS_NOT_INITIALIZED",{validationError:true})}return slothlet.handlers.hookManager.disablePattern(pattern)},resetPatternFilter:function slothlet_hook_resetPatternFilter(){if(!slothlet.handlers?.hookManager){throw new slothlet.SlothletError("HOOKS_NOT_INITIALIZED",{validationError:true})}return slothlet.handlers.hookManager.resetPatternFilter()},list:function slothlet_hook_list(filter={}){if(!slothlet.handlers?.hookManager){throw new slothlet.SlothletError("HOOKS_NOT_INITIALIZED",{validationError:true})}return slothlet.handlers.hookManager.list(filter)},pin:{get enabled(){if(!slothlet.handlers?.hookManager){throw new slothlet.SlothletError("HOOKS_NOT_INITIALIZED",{validationError:true})}return slothlet.handlers.hookManager.pinEnforced},enable:function slothlet_hook_pin_enable(){if(!slothlet.handlers?.hookManager){throw new slothlet.SlothletError("HOOKS_NOT_INITIALIZED",{validationError:true})}return slothlet.handlers.hookManager.setPinEnforced(true)},disable:function slothlet_hook_pin_disable(){if(!slothlet.handlers?.hookManager){throw new slothlet.SlothletError("HOOKS_NOT_INITIALIZED",{validationError:true})}return slothlet.handlers.hookManager.setPinEnforced(false)}}},metadata:{setGlobal:function slothlet_metadata_setGlobal(keyOrObj,value){if(!slothlet.handlers?.metadata){throw new slothlet.SlothletError("METADATA_NOT_AVAILABLE",{handlersKeys:slothlet.handlers?Object.keys(slothlet.handlers).join(", "):"undefined",validationError:true})}const validateGlobalMetadataKeyPath=keyPath=>{const blocked=new Set(["__proto__","prototype","constructor"]);if(typeof keyPath!=="string"||keyPath.length===0){throw new slothlet.SlothletError("INVALID_METADATA_KEY",{key:keyPath,type:typeof keyPath,expected:"non-empty string"})}const segments=keyPath.split(".");for(const segment of segments){if(!segment||blocked.has(segment)){throw new slothlet.SlothletError("INVALID_METADATA_KEY",{key:keyPath,type:typeof keyPath,expected:"safe dot-notation key without reserved segments"})}}};const normalizeGlobalMetadataObject=(source,prefix="",ancestors=new WeakSet)=>{if(ancestors.has(source)){throw new slothlet.SlothletError("INVALID_ARGUMENT",{argument:"keyOrObj",expected:"acyclic object",received:"circular reference",validationError:true})}ancestors.add(source);try{const normalized={};for(const[key,nestedValue]of Object.entries(source)){const fullKey=prefix?`${prefix}.${key}`:key;validateGlobalMetadataKeyPath(fullKey);const nestedProto=nestedValue&&typeof nestedValue==="object"?Object.getPrototypeOf(nestedValue):null;const isPlainNested=nestedProto===Object.prototype||nestedProto===null;if(nestedValue&&typeof nestedValue==="object"&&!Array.isArray(nestedValue)&&isPlainNested){normalized[key]=normalizeGlobalMetadataObject(nestedValue,fullKey,ancestors);continue}normalized[key]=nestedValue}return normalized}finally{ancestors.delete(source)}};if(keyOrObj&&typeof keyOrObj==="object"&&!Array.isArray(keyOrObj)){const normalizedMetadata=normalizeGlobalMetadataObject(keyOrObj);for(const[key,nestedValue]of Object.entries(normalizedMetadata)){slothlet.handlers.metadata.setGlobalMetadata(key,nestedValue)}return}if(typeof keyOrObj!=="string"){throw new slothlet.SlothletError("INVALID_ARGUMENT",{argument:"keyOrObj",expected:"string or object",received:typeof keyOrObj,validationError:true})}validateGlobalMetadataKeyPath(keyOrObj);return slothlet.handlers.metadata.setGlobalMetadata(keyOrObj,value)},set:function slothlet_metadata_set(fn,key,value){if(!slothlet.handlers?.metadata){throw new slothlet.SlothletError("METADATA_NOT_AVAILABLE",{handlersKeys:slothlet.handlers?Object.keys(slothlet.handlers).join(", "):"undefined",validationError:true})}return slothlet.handlers.metadata.setUserMetadata(fn,key,value)},remove:function slothlet_metadata_remove(fn,key){return slothlet.handlers.metadata.removeUserMetadata(fn,key)},setFor:function slothlet_metadata_setFor(pathOrModuleId,keyOrObj,value){if(!slothlet.handlers?.metadata){throw new slothlet.SlothletError("METADATA_NOT_AVAILABLE",{handlersKeys:slothlet.handlers?Object.keys(slothlet.handlers).join(", "):"undefined",validationError:true})}const resolvedPath=_resolvePathOrModuleId(slothlet,pathOrModuleId);return slothlet.handlers.metadata.setPathMetadata(resolvedPath,keyOrObj,value)},removeFor:function slothlet_metadata_removeFor(pathOrModuleId,key){if(!slothlet.handlers?.metadata)return;const resolvedPath=_resolvePathOrModuleId(slothlet,pathOrModuleId);return slothlet.handlers.metadata.removePathMetadata(resolvedPath,key)},getFor:function slothlet_metadata_getFor(pathOrModuleId){if(!slothlet.handlers?.metadata)return{};const resolvedPath=_resolvePathOrModuleId(slothlet,pathOrModuleId);return slothlet.handlers.metadata.getPathMetadata(resolvedPath)},setForVersion:function slothlet_metadata_setForVersion(logicalPath,versionTag,keyOrObj,value){if(!slothlet.handlers?.metadata){throw new slothlet.SlothletError("METADATA_NOT_AVAILABLE",{handlersKeys:slothlet.handlers?Object.keys(slothlet.handlers).join(", "):"undefined",validationError:true})}const info=slothlet.handlers?.versionManager?.list(logicalPath);if(!info||!info.versions?.[versionTag]){throw new slothlet.SlothletError("VERSION_NOT_FOUND",{version:versionTag,apiPath:logicalPath})}const{moduleID}=info.versions[versionTag];const resolvedPath=_resolvePathOrModuleId(slothlet,moduleID);return slothlet.handlers.metadata.setPathMetadata(resolvedPath,keyOrObj,value)},getForVersion:function slothlet_metadata_getForVersion(logicalPath,versionTag){if(!slothlet.handlers?.metadata)return{};const info=slothlet.handlers?.versionManager?.list(logicalPath);if(!info||!info.versions?.[versionTag])return{};const{moduleID}=info.versions[versionTag];const resolvedPath=_resolvePathOrModuleId(slothlet,moduleID);return slothlet.handlers.metadata.getPathMetadata(resolvedPath)}},scope:this.createScopeFunction(),run:this.createRunFunction(),reload:async(options={})=>{if(!config.api?.mutations?.reload){throw new slothlet.SlothletError("INVALID_CONFIG_MUTATIONS_DISABLED",{operation:"reload",validationError:true})}return slothlet.reload(options)},shutdown:async()=>{return slothlet.shutdown()},owner:{get:apiPath=>{if(slothlet.handlers?.ownership){return slothlet.handlers.ownership.getPathOwnership(apiPath)}return null}},materialize:(()=>{const mgr=slothlet.handlers?.materialize;const getMaterializedState=()=>{enforceInternalPermission("slothlet.materialize.materialized");return mgr?.materialized??false};const getMaterializeStats=()=>{enforceInternalPermission("slothlet.materialize.get");return mgr?mgr.get():{total:0,materialized:0,remaining:0,percentage:100}};const waitForMaterialization=async()=>{enforceInternalPermission("slothlet.materialize.wait");if(!mgr)return;return mgr.wait()};if(!mgr){return Object.freeze({get materialized(){return getMaterializedState()},get:getMaterializeStats,wait:waitForMaterialization})}return Object.freeze({get materialized(){return getMaterializedState()},get:getMaterializeStats,wait:waitForMaterialization})})(),lifecycle:(()=>{const handler=slothlet.handlers?.lifecycle;const noop=()=>{};if(!handler)return{on:noop,off:noop};return{on:handler.on.bind(handler),off:handler.off.bind(handler)}})(),env:slothlet.envSnapshot,versioning:{list:function slothlet_version_list(logicalPath){if(!slothlet.handlers?.versionManager)return void 0;return slothlet.handlers.versionManager.list(logicalPath)},setDefault:function slothlet_version_setDefault(logicalPath,versionTag){if(!slothlet.handlers?.versionManager)return;return slothlet.handlers.versionManager.setDefault(logicalPath,versionTag)},unregister:async function slothlet_version_unregister(logicalPath,versionTag){if(!slothlet.handlers?.versionManager)return false;const info=slothlet.handlers.versionManager.list(logicalPath);if(!info||!info.versions?.[versionTag])return false;const{moduleID:versionedModuleID}=info.versions[versionTag];await slothlet.handlers.apiManager.removeApiComponent(versionedModuleID);return true},getVersionMetadata:function slothlet_version_getVersionMetadata(logicalPath,versionTag){if(!slothlet.handlers?.versionManager)return void 0;return slothlet.handlers.versionManager.getVersionMetadataByPath(logicalPath,versionTag)},setVersionMetadata:function slothlet_version_setVersionMetadata(logicalPath,versionTag,patch){if(!slothlet.handlers?.versionManager)return;return slothlet.handlers.versionManager.setVersionMetadataByPath(logicalPath,versionTag,patch)}},permissions:{addRule:function slothlet_permissions_addRule(rule){if(!config.api?.mutations?.permissions){throw new slothlet.SlothletError("INVALID_CONFIG_MUTATIONS_DISABLED",{operation:"api.slothlet.permissions.addRule",validationError:true})}const permissionManager=slothlet.handlers?.permissionManager;if(!permissionManager?.addRule){throw new slothlet.SlothletError("PERMISSION_MANAGER_NOT_AVAILABLE",{validationError:true})}const ruleId=permissionManager.addRule(rule,null);if(slothlet.handlers?.apiManager?.state?.operationHistory){slothlet.handlers.apiManager.state.operationHistory.push({type:"addPermissionRule",rule,ownerModuleID:null,ruleId,timestamp:Date.now()})}return ruleId},removeRule:function slothlet_permissions_removeRule(ruleId){if(!config.api?.mutations?.permissions){throw new slothlet.SlothletError("INVALID_CONFIG_MUTATIONS_DISABLED",{operation:"api.slothlet.permissions.removeRule",validationError:true})}const permissionManager=slothlet.handlers?.permissionManager;if(!permissionManager?.removeRule){throw new slothlet.SlothletError("PERMISSION_MANAGER_NOT_AVAILABLE",{validationError:true})}const currentWrapper=slothlet.contextManager?.getCallerIdentity?.()?.currentWrapper;const callerModuleID=currentWrapper?.____slothletInternal?.moduleID??null;const result=slothlet.handlers.permissionManager.removeRule(ruleId,callerModuleID);if(result&&slothlet.handlers?.apiManager?.state?.operationHistory){slothlet.handlers.apiManager.state.operationHistory.push({type:"removePermissionRule",ruleId,callerModuleID,timestamp:Date.now()})}return result},self:{access:function slothlet_permissions_self_access(target){const permissionManager=slothlet.handlers?.permissionManager;if(!permissionManager?.checkAccess){throw new slothlet.SlothletError("PERMISSION_MANAGER_NOT_AVAILABLE",{validationError:true})}const ctx=slothlet.contextManager?.tryGetContext?.();const currentWrapper=slothlet.contextManager?.getCallerIdentity?.()?.currentWrapper;const callerPath=currentWrapper?.____slothletInternal?.apiPath??"";const callerFilePath=currentWrapper?.____slothletInternal?.filePath??null;const runtimeContext=ctx?.context??null;return slothlet.handlers.permissionManager.checkAccess(callerPath,target,callerFilePath,null,runtimeContext)},rules:function slothlet_permissions_self_rules(){const permissionManager=slothlet.handlers?.permissionManager;if(!permissionManager?.getRulesForCaller){throw new slothlet.SlothletError("PERMISSION_MANAGER_NOT_AVAILABLE",{validationError:true})}const currentWrapper=slothlet.contextManager?.getCallerIdentity?.()?.currentWrapper;const callerPath=currentWrapper?.____slothletInternal?.apiPath??"";return slothlet.handlers.permissionManager.getRulesForCaller(callerPath)}},global:{checkAccess:function slothlet_permissions_global_checkAccess(caller,target){const permissionManager=slothlet.handlers?.permissionManager;if(!permissionManager?.checkAccess){throw new slothlet.SlothletError("PERMISSION_MANAGER_NOT_AVAILABLE",{validationError:true})}const runtimeContext=slothlet.contextManager?.tryGetContext?.()?.context??null;return slothlet.handlers.permissionManager.checkAccess(caller,target,null,null,runtimeContext)},rulesForPath:function slothlet_permissions_global_rulesForPath(path){const permissionManager=slothlet.handlers?.permissionManager;if(!permissionManager?.getRulesForPath){throw new slothlet.SlothletError("PERMISSION_MANAGER_NOT_AVAILABLE",{validationError:true})}return slothlet.handlers.permissionManager.getRulesForPath(path)},rulesByModule:function slothlet_permissions_global_rulesByModule(moduleID){const permissionManager=slothlet.handlers?.permissionManager;if(!permissionManager?.getRulesByModule){throw new slothlet.SlothletError("PERMISSION_MANAGER_NOT_AVAILABLE",{validationError:true})}return slothlet.handlers.permissionManager.getRulesByModule(moduleID)}},control:{get enabled(){const permissionManager=slothlet.handlers?.permissionManager;if(!permissionManager?.isEnabled){throw new slothlet.SlothletError("PERMISSION_MANAGER_NOT_AVAILABLE",{validationError:true})}return permissionManager.isEnabled()},enable:function slothlet_permissions_control_enable(){const permissionManager=slothlet.handlers?.permissionManager;if(!permissionManager?.enable){throw new slothlet.SlothletError("PERMISSION_MANAGER_NOT_AVAILABLE",{validationError:true})}slothlet.handlers.permissionManager.enable()},disable:function slothlet_permissions_control_disable(){const permissionManager=slothlet.handlers?.permissionManager;if(!permissionManager?.disable){throw new slothlet.SlothletError("PERMISSION_MANAGER_NOT_AVAILABLE",{validationError:true})}slothlet.handlers.permissionManager.disable()},get readGatingEnabled(){const permissionManager=slothlet.handlers?.permissionManager;if(!permissionManager?.isReadGatingEnabled){throw new slothlet.SlothletError("PERMISSION_MANAGER_NOT_AVAILABLE",{validationError:true})}return permissionManager.isReadGatingEnabled()},readGating:function slothlet_permissions_control_readGating(value){const permissionManager=slothlet.handlers?.permissionManager;if(!permissionManager?.setReadGating){throw new slothlet.SlothletError("PERMISSION_MANAGER_NOT_AVAILABLE",{validationError:true})}slothlet.handlers.permissionManager.setReadGating(value)},seal:function slothlet_permissions_control_seal(){const permissionManager=slothlet.handlers?.permissionManager;if(!permissionManager?.seal){throw new slothlet.SlothletError("PERMISSION_MANAGER_NOT_AVAILABLE",{validationError:true})}slothlet.handlers.permissionManager.seal()},get sealed(){const permissionManager=slothlet.handlers?.permissionManager;if(!permissionManager?.isSealed){throw new slothlet.SlothletError("PERMISSION_MANAGER_NOT_AVAILABLE",{validationError:true})}return permissionManager.isSealed()}}}};if(!config.hook?.enabled&&config.diagnostics!==true){delete namespace.hooks}if(config.diagnostics===true){namespace.diag={describe:(showAll=false)=>{if(showAll){return{...userApi}}return Reflect.ownKeys(userApi)},reference:slothlet.reference||null,context:slothlet.context||{},inspect:()=>{return slothlet.getDiagnostics()},getAPI:()=>{return slothlet.getAPI()},getOwnership:()=>{return slothlet.getOwnership()},owner:{get:apiPath=>{if(slothlet.handlers?.ownership){return slothlet.handlers.ownership.getPathOwnership(apiPath)}return null}},caches:{get:()=>{if(slothlet.handlers?.apiCacheManager){return slothlet.handlers.apiCacheManager.getCacheDiagnostics()}return{totalCaches:0,caches:[]}},getAllModuleIDs:()=>{if(slothlet.handlers?.apiCacheManager){return slothlet.handlers.apiCacheManager.getAllModuleIDs()}return[]},has:moduleID=>{if(slothlet.handlers?.apiCacheManager){return slothlet.handlers.apiCacheManager.has(moduleID)}return false}},SlothletWarning:slothlet.SlothletWarning,hook:slothlet.handlers?.hookManager?{get enabled(){return slothlet.handlers.hookManager.enabled},compilePattern:pattern=>{return slothlet.handlers.hookManager.getCompilePatternForDiagnostics()(pattern)}}:void 0}}return createInternalRouteProxy(namespace,"slothlet")}createShutdownFunction(){const slothlet=this.slothlet;const shutdownFunction={shutdown:async()=>{if(slothlet.config.collectLifecycleHooks){const nestedHooks=(await slothlet._collectLifecycleHooks("shutdown")).reverse();for(const{fn,receiver}of nestedHooks){try{await Reflect.apply(fn,receiver,[])}catch{}}}if(slothlet.userHooks?.shutdown&&typeof slothlet.userHooks.shutdown==="function"){await slothlet.userHooks.shutdown()}return slothlet.shutdown()}}.shutdown;return shutdownFunction}createRunFunction(){const slothlet=this.slothlet;const scopeFunc=this.createScopeFunction();const runFunction={run:async(contextData,callback,...args)=>{if(slothlet.config.scope===false){throw new slothlet.SlothletError("SCOPE_DISABLED",{},null,{validationError:true})}if(!contextData||typeof contextData!=="object"){throw new slothlet.SlothletError("SCOPE_INVALID_CONTEXT",{received:typeof contextData},null,{validationError:true})}if(typeof callback!=="function"){throw new slothlet.SlothletError("SCOPE_INVALID_CALLBACK",{received:typeof callback},null,{validationError:true})}return scopeFunc({context:contextData,fn:callback,args,merge:slothlet.config.scope?.merge||"shallow",isolation:slothlet.config.scope?.isolation||"partial"})}}.run;return runFunction}createScopeFunction(){const slothlet=this.slothlet;const scopeFunction={scope:async options=>{if(slothlet.config.scope===false){throw new slothlet.SlothletError("SCOPE_DISABLED",{},null,{validationError:true})}if(!options||typeof options!=="object"){throw new slothlet.SlothletError("SCOPE_INVALID_OPTIONS",{received:typeof options},null,{validationError:true})}if(!options.fn||typeof options.fn!=="function"){throw new slothlet.SlothletError("SCOPE_INVALID_FN",{received:typeof options?.fn},null,{validationError:true})}if(!options.context||typeof options.context!=="object"){throw new slothlet.SlothletError("SCOPE_INVALID_CONTEXT_OBJECT",{received:typeof options?.context},null,{validationError:true})}const{context:contextData,fn,args=[],merge="shallow",isolation,protect,owners}=options;if(merge!=="shallow"&&merge!=="deep"){throw new slothlet.SlothletError("SCOPE_INVALID_MERGE_STRATEGY",{merge},null,{validationError:true})}const isolationMode=isolation||slothlet.config.scope?.isolation||"partial";if(isolationMode!=="partial"&&isolationMode!=="full"){throw new slothlet.SlothletError("SCOPE_INVALID_ISOLATION_MODE",{isolationMode},null,{validationError:true})}if(protect!==void 0&&(!Array.isArray(protect)||protect.some(k=>typeof k!=="string"))){throw new slothlet.SlothletError("SCOPE_INVALID_PROTECT",{received:describeScopeReceived(protect)},null,{validationError:true})}if(owners!==void 0){if(typeof owners!=="object"||owners===null||Array.isArray(owners)){throw new slothlet.SlothletError("SCOPE_INVALID_OWNERS",{received:describeScopeReceived(owners)},null,{validationError:true})}for(const[key,owner]of Object.entries(owners)){if(typeof owner!=="string"||owner.length===0){throw new slothlet.SlothletError("INVALID_ARGUMENT",{argument:`owners.${key}`,expected:"non-empty string",received:typeof owner==="string"?"empty string":typeof owner,validationError:true})}}}const buildContextOwners=parentOwners=>{const base=parentOwners??null;let child=base;const claim=(key,owner)=>{const existing=child&&Object.prototype.hasOwnProperty.call(child,key)?child[key]:void 0;if(existing!==void 0&&existing!==owner){throw new slothlet.SlothletError("CONTEXT_KEY_OWNED",{key:String(key)},null,{validationError:true})}if(child===base)child=base?Object.assign(Object.create(null),base):Object.create(null);child[key]=owner};if(Array.isArray(protect))for(const k of protect)claim(k,PROTECT_SENTINEL);if(owners&&typeof owners==="object")for(const[k,o]of Object.entries(owners))claim(k,o);return child};const contextManager=slothlet.contextManager;if(!contextManager){throw new slothlet.SlothletError("NO_CONTEXT_MANAGER",{validationError:true})}const{utilities}=slothlet.helpers;if(contextManager.constructor.name==="LiveContextManager"){let currentStore=null;const currentID=contextManager.currentInstanceID;if(currentID){const activeStore=contextManager.instances.get(currentID);const isOurContext=currentID===slothlet.instanceID||activeStore?.parentInstanceID===slothlet.instanceID||currentID.startsWith(slothlet.instanceID+"__run_");if(isOurContext){currentStore=activeStore}}if(!currentStore){currentStore=contextManager.instances.get(slothlet.instanceID)}if(!currentStore){throw new slothlet.SlothletError("CONTEXT_NOT_FOUND",{instanceID:slothlet.instanceID,availableInstances:[...contextManager.instances.keys()].join(", ")||"none",validationError:true})}let mergedContext;if(merge==="deep"){mergedContext=utilities.deepMerge(currentStore.context,contextData);mergedContext=structuredClone(mergedContext)}else{const clonedParent=structuredClone(currentStore.context);mergedContext={...clonedParent,...contextData}}const childInstanceID=`${slothlet.instanceID}__run_${Date.now()}_${Math.random().toString(36).slice(2,9)}`;const childStore={instanceID:childInstanceID,context:mergedContext,self:isolationMode==="full"?makeCopyOnWriteSelf(currentStore.self):currentStore.self,config:currentStore.config,createdAt:currentStore.createdAt,parentInstanceID:slothlet.instanceID,currentWrapper:currentStore.currentWrapper,callerWrapper:currentStore.callerWrapper,slothlet:currentStore.slothlet,__contextOwners:buildContextOwners(currentStore.__contextOwners)};if(currentStore[TRUSTED_ROOT]===true){Object.defineProperty(childStore,TRUSTED_ROOT,{value:true,configurable:true})}contextManager.instances.set(childInstanceID,childStore);const previousInstanceID=contextManager.currentInstanceID;try{contextManager.currentInstanceID=childInstanceID;return await fn(...args)}finally{contextManager.currentInstanceID=previousInstanceID;contextManager.instances.delete(childInstanceID)}}if(contextManager.constructor.name==="AsyncContextManager"){let currentStore=null;const activeStore=contextManager.tryGetContext();if(activeStore){const isOurContext=activeStore.instanceID===slothlet.instanceID||activeStore.parentInstanceID===slothlet.instanceID||activeStore.instanceID.startsWith(slothlet.instanceID+"__run_");if(isOurContext){currentStore=activeStore}}if(!currentStore){const baseStore=contextManager.instances.get(slothlet.instanceID);if(!baseStore){throw new slothlet.SlothletError("CONTEXT_NOT_FOUND",{instanceID:slothlet.instanceID,availableInstances:[...contextManager.instances.keys()].join(", ")||"none",validationError:true})}currentStore=baseStore}let mergedContext;if(merge==="deep"){mergedContext=utilities.deepMerge(currentStore.context,contextData);mergedContext=structuredClone(mergedContext)}else{const clonedParent=structuredClone(currentStore.context);mergedContext={...clonedParent,...contextData}}const childInstanceID=`${slothlet.instanceID}__run_${Date.now()}_${Math.random().toString(36).slice(2,9)}`;const childStore={instanceID:childInstanceID,context:mergedContext,self:isolationMode==="full"?makeCopyOnWriteSelf(currentStore.self):currentStore.self,config:currentStore.config,createdAt:currentStore.createdAt,parentInstanceID:slothlet.instanceID,currentWrapper:currentStore.currentWrapper,callerWrapper:currentStore.callerWrapper,slothlet:currentStore.slothlet,__contextOwners:buildContextOwners(currentStore.__contextOwners)};if(currentStore[TRUSTED_ROOT]===true){Object.defineProperty(childStore,TRUSTED_ROOT,{value:true,configurable:true})}contextManager.instances.set(childInstanceID,childStore);try{return await contextManager.als.run(childStore,async()=>{return await fn(...args)})}finally{contextManager.instances.delete(childInstanceID)}}throw new slothlet.SlothletError("UNSUPPORTED_CONTEXT_MANAGER",{manager:contextManager.constructor.name,validationError:true})}}.scope;return scopeFunction}createDestroyFunction(api){const slothlet=this.slothlet;const destroyFunction={destroy:async()=>{if(slothlet.config.collectLifecycleHooks){const nestedHooks=(await slothlet._collectLifecycleHooks("destroy")).reverse();for(const{fn,receiver}of nestedHooks){try{await Reflect.apply(fn,receiver,[])}catch{}}}if(slothlet.userHooks?.destroy&&typeof slothlet.userHooks.destroy==="function"){await slothlet.userHooks.destroy()}if(api&&typeof api.shutdown==="function"){await api.shutdown()}else{await slothlet.shutdown()}slothlet.isDestroyed=true;const objectsToClear=[api,slothlet.api].filter(obj=>obj&&typeof obj==="object");for(const obj of objectsToClear){const keys=Object.keys(obj);for(const key of keys){try{delete obj[key]}catch(_){}}}slothlet.api=null}}.destroy;return destroyFunction}attachBuiltins(userApi,builtins){Object.defineProperty(userApi,"slothlet",{value:builtins.slothlet,enumerable:true,writable:false,configurable:true});Object.defineProperty(userApi,"shutdown",{value:builtins.shutdown,enumerable:true,writable:false,configurable:true});if(builtins.destroy!==null){Object.defineProperty(userApi,"destroy",{value:builtins.destroy,enumerable:true,writable:false,configurable:true})}}}export{ApiBuilder};
17
+ import{isNode,AsyncResource,loadJson}from"@cldmv/slothlet/helpers/platform";import{ComponentBase}from"#factories/component-base";import{TYPE_STATES,resolveWrapper}from"#handlers/unified-wrapper";import{TRUSTED_ROOT,PROTECT_SENTINEL}from"#handlers/trusted-root";import{getLanguage,initI18n,setLanguage,setLanguageAsync,t,translate}from"@cldmv/slothlet/i18n";function _resolvePathOrModuleId(slothlet,pathOrModuleId){const history=slothlet.handlers?.apiManager?.state?.addHistory;if(history){let match=null;for(let i=history.length-1;i>=0;i--){const entry=history[i];if(entry?.moduleID===pathOrModuleId){match=entry;break}}if(match)return match.apiPath}return pathOrModuleId}function describeScopeReceived(value){if(Array.isArray(value)){const badIndex=value.findIndex(entry=>typeof entry!=="string");if(badIndex!==-1){return`array with non-string entry (${typeof value[badIndex]} at index ${badIndex})`}return"array"}return typeof value}function makeCopyOnWriteSelf(parentSelf){const overlay=new Map;const childViews=new Map;return new Proxy({},{get(_t,prop){if(overlay.has(prop))return overlay.get(prop);const real=parentSelf[prop];if(real!==null&&typeof real==="object"){let view=childViews.get(prop);if(view===void 0){view=makeCopyOnWriteSelf(real);childViews.set(prop,view)}return view}return real},set(_t,prop,value){overlay.set(prop,value);childViews.delete(prop);return true},has(_t,prop){return overlay.has(prop)||prop in parentSelf},deleteProperty(_t,prop){overlay.delete(prop);childViews.delete(prop);return true},ownKeys(){const keys=new Set(Reflect.ownKeys(parentSelf));for(const k of overlay.keys())keys.add(k);return[...keys]},getOwnPropertyDescriptor(_t,prop){if(overlay.has(prop)){return{value:overlay.get(prop),writable:true,enumerable:true,configurable:true}}const desc=Reflect.getOwnPropertyDescriptor(parentSelf,prop);return desc?{...desc,configurable:true}:void 0}})}class ApiBuilder extends ComponentBase{static slothletProperty="apiBuilder";constructor(slothlet){super(slothlet)}async buildFinalAPI(userApi){this.slothlet.debug("api",{key:"DEBUG_MODE_BUILD_FINAL_API_CALLED",diagnostics:this.____config.diagnostics,userApiKeys:Object.keys(userApi)});if(this.slothlet._ownBuiltins){for(const[key,ref]of Object.entries(this.slothlet._ownBuiltins)){if(ref&&Object.prototype.hasOwnProperty.call(userApi,key)&&userApi[key]===ref){try{delete userApi[key]}catch(_){}}}}this.slothlet.userHooks={shutdown:typeof userApi.shutdown==="function"?userApi.shutdown:null,destroy:typeof userApi.destroy==="function"?userApi.destroy:null};if(userApi.slothlet){if(!this.____config?.silent){new this.SlothletWarning("WARNING_RESERVED_PROPERTY_CONFLICT",{properties:"slothlet"})}await this.emitImplDiagnostic("warning",{apiPath:"slothlet",code:"WARNING_RESERVED_PROPERTY_CONFLICT",context:{properties:"slothlet"},source:"buildAPI"})}const slothletNamespace=await this.createSlothletNamespace(userApi);this.slothlet.debug("api",{key:"DEBUG_MODE_SLOTHLET_NAMESPACE_CREATED",namespaceKeys:Object.keys(slothletNamespace),hasDiag:!!slothletNamespace.diag});const shutdownFn=this.createShutdownFunction();this.attachBuiltins(userApi,{slothlet:slothletNamespace,shutdown:shutdownFn,destroy:null});this.slothlet.debug("api",{key:"DEBUG_MODE_BUILT_INS_ATTACHED",userApiKeys:Object.keys(userApi),hasSlothlet:!!userApi.slothlet,hasDiag:!!userApi.slothlet?.diag});const destroyWithApi=this.createDestroyFunction(userApi);Object.defineProperty(userApi,"destroy",{value:destroyWithApi,enumerable:true,writable:false,configurable:true});this.slothlet._ownBuiltins={shutdown:shutdownFn,slothlet:slothletNamespace,destroy:destroyWithApi};return userApi}async createSlothletNamespace(userApi){const slothlet=this.slothlet;const config=this.____config;const enforceInternalPermission=targetPath=>{const ctx=slothlet.contextManager?.tryGetContext?.(slothlet.instanceID);const identity=slothlet.contextManager?.getCallerIdentity?.(slothlet.instanceID);if(identity?.unresolved){throw new slothlet.SlothletError("PERMISSION_DENIED",{caller:null,target:targetPath})}const callerWrapper=identity?.currentWrapper;if(!callerWrapper)return;const permissionManager=slothlet.handlers?.permissionManager;if(!permissionManager?.enforceAccess){throw new slothlet.SlothletError("PERMISSION_MANAGER_NOT_AVAILABLE",{validationError:true})}const callerPath=callerWrapper.____slothletInternal?.apiPath??"";const callerFilePath=callerWrapper.____slothletInternal?.filePath??null;const runtimeContext=ctx?.context??null;if(!permissionManager.enforceAccess(callerPath,targetPath,callerFilePath,null,runtimeContext)){throw new slothlet.SlothletError("PERMISSION_DENIED",{caller:callerPath,target:targetPath})}};const canTraverseInternalNamespace=targetPath=>{const ctx=slothlet.contextManager?.tryGetContext?.(slothlet.instanceID);const identity=slothlet.contextManager?.getCallerIdentity?.(slothlet.instanceID);if(identity?.unresolved)return false;const callerWrapper=identity?.currentWrapper;if(!callerWrapper)return false;const permissionManager=slothlet.handlers?.permissionManager;if(!permissionManager?.getRulesForCaller||!permissionManager?.checkAccess){return false}const callerPath=callerWrapper.____slothletInternal?.apiPath??"";const callerFilePath=callerWrapper.____slothletInternal?.filePath??null;const runtimeContext=ctx?.context??null;const callerRules=permissionManager.getRulesForCaller(callerPath);const conditionMatches=condition=>typeof permissionManager.matchesCondition==="function"?permissionManager.matchesCondition(condition,runtimeContext):false;const prefix=`${targetPath}.`;for(const rule of callerRules){if(!rule||rule.effect!=="allow"||typeof rule.target!=="string")continue;const couldMatchDescendant=rule.target.startsWith(prefix)||rule.target==="**"||rule.target==="*";if(!couldMatchDescendant)continue;if(rule.target.startsWith(prefix)&&conditionMatches(rule.condition)){return true}const probePaths=[`${targetPath}.__probe__`];if(rule.target.startsWith(prefix)){const suffix=rule.target.slice(prefix.length);const firstSegment=suffix.split(".")[0];if(firstSegment&&!/[*!?{}]/u.test(firstSegment)){probePaths.unshift(`${targetPath}.${firstSegment}`);probePaths.push(`${targetPath}.${firstSegment}.__probe__`)}}for(const probePath of probePaths){if(permissionManager.checkAccess(callerPath,probePath,callerFilePath,null,runtimeContext,{useCache:false})){return true}}}return false};const createInternalRouteProxy=(value,routePath,seen=new WeakMap)=>{if(!value||typeof value!=="object"&&typeof value!=="function")return value;const isMetaProperty=prop=>prop==="__proto__"||prop==="prototype"||prop==="constructor"||prop==="caller"||prop==="arguments";let routeCache=seen.get(value);if(!routeCache){routeCache=new Map;seen.set(value,routeCache)}if(routeCache.has(routePath)){return routeCache.get(routePath)}const proxy=new Proxy(value,{get(target,prop,receiver){if(typeof prop!=="string"){const result2=Reflect.get(target,prop,receiver);return createInternalRouteProxy(result2,routePath,seen)}const childRoutePath=`${routePath}.${prop}`;let deniedError=null;try{enforceInternalPermission(childRoutePath)}catch(error){deniedError=error}if(deniedError){if(canTraverseInternalNamespace(childRoutePath)){const result2=Reflect.get(target,prop,receiver);if(result2&&(typeof result2==="object"||typeof result2==="function")){return createInternalRouteProxy(result2,childRoutePath,seen)}}throw deniedError}const result=Reflect.get(target,prop,receiver);if(isMetaProperty(prop)){return result}const descriptor=Object.getOwnPropertyDescriptor(target,prop);if(descriptor&&"value"in descriptor&&descriptor.configurable===false&&descriptor.writable===false){return descriptor.value}return createInternalRouteProxy(result,childRoutePath,seen)},getOwnPropertyDescriptor(target,prop){const descriptor=Reflect.getOwnPropertyDescriptor(target,prop);if(!descriptor)return void 0;if(typeof prop!=="string"){return descriptor}const childRoutePath=`${routePath}.${prop}`;if(isMetaProperty(prop)){enforceInternalPermission(childRoutePath);return descriptor}if("get"in descriptor||"set"in descriptor){enforceInternalPermission(childRoutePath);if(descriptor.configurable===true){return{...descriptor,get:typeof descriptor.get==="function"?function slothlet_internal_descriptor_getter(...args){enforceInternalPermission(childRoutePath);return Reflect.apply(descriptor.get,this,args)}:descriptor.get,set:typeof descriptor.set==="function"?function slothlet_internal_descriptor_setter(...args){enforceInternalPermission(childRoutePath);return Reflect.apply(descriptor.set,this,args)}:descriptor.set}}return descriptor}if(!("value"in descriptor)){return descriptor}const descriptorValue=descriptor.value;if(descriptor.configurable===false&&descriptor.writable===false){enforceInternalPermission(childRoutePath);return descriptor}if(!descriptorValue||typeof descriptorValue!=="object"&&typeof descriptorValue!=="function"||typeof descriptorValue==="function"){enforceInternalPermission(childRoutePath);if(typeof descriptorValue==="function"&&descriptor.configurable===true){return{...descriptor,value:createInternalRouteProxy(descriptorValue,childRoutePath,seen)}}return descriptor}return{...descriptor,value:createInternalRouteProxy(descriptorValue,childRoutePath,seen)}},set(target,prop,newValue,receiver){if(typeof prop!=="string"){return Reflect.set(target,prop,newValue,receiver)}const childRoutePath=`${routePath}.${prop}`;enforceInternalPermission(childRoutePath);return Reflect.set(target,prop,newValue,receiver)},defineProperty(target,prop,descriptor){if(typeof prop!=="string"){return Reflect.defineProperty(target,prop,descriptor)}const childRoutePath=`${routePath}.${prop}`;enforceInternalPermission(childRoutePath);return Reflect.defineProperty(target,prop,descriptor)},deleteProperty(target,prop){if(typeof prop!=="string"){return Reflect.deleteProperty(target,prop)}const childRoutePath=`${routePath}.${prop}`;enforceInternalPermission(childRoutePath);return Reflect.deleteProperty(target,prop)},ownKeys(target){return Reflect.ownKeys(target)},apply(target,thisArg,argArray){enforceInternalPermission(routePath);return Reflect.apply(target,thisArg,argArray)},construct(target,argArray,newTarget){enforceInternalPermission(routePath);return Reflect.construct(target,argArray,newTarget)}});routeCache.set(routePath,proxy);return proxy};let version="unknown";if(isNode){const pkg=loadJson(new URL("../../../package.json",import.meta.url));if(pkg?.version)version=pkg?.version}const namespace={i18n:{setLanguage,setLanguageAsync,getLanguage,translate,t,initI18n},version,instanceID:slothlet.instanceID,types:TYPE_STATES,api:{add:async function slothlet_api_add(apiPath,folderPath,options={},versionConfig=null){if(!config.api?.mutations?.add){throw new slothlet.SlothletError("INVALID_CONFIG_MUTATIONS_DISABLED",{operation:"api.add",validationError:true})}const{recordHistory:____recordHistory,collisionMode:____collisionMode,mutateExisting:____mutateExisting,...filteredOptions}=options;return slothlet.handlers.apiManager.addApiComponent({apiPath,folderPath,options:filteredOptions,versionConfig:versionConfig||null})},remove:async function slothlet_api_remove(pathOrModuleId,apiPath){if(!config.api?.mutations?.remove){throw new slothlet.SlothletError("INVALID_CONFIG_MUTATIONS_DISABLED",{operation:"api.remove",validationError:true})}if(typeof pathOrModuleId!=="string"){throw new slothlet.SlothletError("INVALID_ARGUMENT",{argument:"pathOrModuleId",expected:"string",received:typeof pathOrModuleId,validationError:true})}if(apiPath!==void 0&&typeof apiPath!=="string"){throw new slothlet.SlothletError("INVALID_ARGUMENT",{argument:"apiPath",expected:"string",received:typeof apiPath,validationError:true})}return slothlet.handlers.apiManager.removeApiComponent(pathOrModuleId,{scopedApiPath:apiPath})},leaves:async function slothlet_api_leaves(key,options={}){enforceInternalPermission("slothlet.api.leaves");if(typeof key!=="string"){throw new slothlet.SlothletError("INVALID_ARGUMENT",{argument:"key",expected:"string",received:typeof key,validationError:true})}const normalizedOptions=options==null?{}:options;if(typeof normalizedOptions!=="object"||Array.isArray(normalizedOptions)){throw new slothlet.SlothletError("INVALID_ARGUMENT",{argument:"options",expected:"object with optional boolean details/includePrivate",received:Array.isArray(normalizedOptions)?"array":typeof normalizedOptions,validationError:true})}const{details=false,includePrivate=false}=normalizedOptions;for(const[name,value]of[["details",details],["includePrivate",includePrivate]]){if(typeof value!=="boolean"){throw new slothlet.SlothletError("INVALID_ARGUMENT",{argument:`options.${name}`,expected:"boolean",received:typeof value,validationError:true})}}const ownership=slothlet.handlers.ownership;const leavesIdentity=slothlet.contextManager?.getCallerIdentity?.();const leavesCaller=leavesIdentity?.currentWrapper??null;if(includePrivate&&leavesCaller){throw new slothlet.SlothletError("PERMISSION_DENIED",{caller:leavesCaller.____slothletInternal?.apiPath??"",target:"slothlet.api.leaves:includePrivate"})}let moduleID=null;if(key==="."||key===""){moduleID=[...ownership.moduleEndpoints.entries()].find(([,endpoint2])=>endpoint2===".")?.[0]}else if(ownership.moduleToPath.has(key)){moduleID=key}else{moduleID=ownership.getCurrentOwner(key)?.moduleID??null;if(!moduleID){moduleID=[...ownership.moduleEndpoints.entries()].find(([,endpoint2])=>endpoint2===key)?.[0]??null}}if(!moduleID||!ownership.moduleToPath.has(moduleID)){throw new slothlet.SlothletError("API_LEAVES_UNKNOWN_MODULE",{key},null,{validationError:true})}const endpoint=ownership.moduleEndpoints.get(moduleID);const boundApi=slothlet.boundApi;if(config.mode==="lazy"&&boundApi){const seen=new WeakSet;let root=boundApi;if(endpoint!=="."){for(const segment of endpoint.split("."))root=root[segment]}const pending=[{node:root,path:endpoint==="."?"":endpoint}];while(pending.length>0){const{node,path}=pending.pop();if(node===null||typeof node!=="object"&&typeof node!=="function")continue;if(seen.has(node))continue;seen.add(node);if(typeof node._materialize==="function"&&node.__materialized===false){await node._materialize()}const childKeys=new Set(Object.keys(node));const records=ownership.moduleToPath.get(moduleID);if(path!==null&&records){const prefix=path===""?"":`${path}.`;for(const ownedPath of records){if(ownedPath===""||prefix!==""&&!ownedPath.startsWith(prefix))continue;const rest=ownedPath.slice(prefix.length);const segmentEnd=rest.indexOf(".");childKeys.add(segmentEnd===-1?rest:rest.slice(0,segmentEnd))}}for(const childKey of childKeys){if(path===""&&(childKey==="slothlet"||childKey==="shutdown"||childKey==="destroy"))continue;let child;try{child=node[childKey]}catch{continue}const childWrapper=child?resolveWrapper(child):null;if(childWrapper?.____slothletInternal?.userAssigned)continue;const childPath=path===null?null:path===""?childKey:`${path}.${childKey}`;pending.push({node:child,path:records?.has(childPath)?childPath:null})}}}if(!ownership.moduleToPath.has(moduleID)){throw new slothlet.SlothletError("API_LEAVES_UNKNOWN_MODULE",{key},null,{validationError:true})}const ownedPaths=[...ownership.moduleToPath.get(moduleID)].filter(path=>{if(path==="")return false;if(endpoint==="."&&(path==="slothlet"||path.startsWith("slothlet.")||path==="shutdown"||path==="destroy"))return false;const currentOwner=ownership.getCurrentOwner(path);return!currentOwner||currentOwner.moduleID===moduleID});ownedPaths.sort();const namespaces=new Set;for(const owned of ownedPaths){let cut=owned.lastIndexOf(".");while(cut>0){namespaces.add(owned.slice(0,cut));cut=owned.lastIndexOf(".",cut-1)}}const kindOf=path=>{if(namespaces.has(path))return"namespace";const entry=ownership.pathToModule.get(path)?.find(candidate=>candidate.moduleID===moduleID);return typeof entry?.value==="function"?"function":"data"};const permissionManager=slothlet.handlers?.permissionManager;let visiblePaths=ownedPaths;if(!includePrivate&&permissionManager?.isEnabled?.()){const callerPath=leavesCaller?.____slothletInternal?.apiPath??"";const callerFilePath=leavesCaller?.____slothletInternal?.filePath??null;const runtimeContext=slothlet.contextManager?.tryGetContext?.()?.context??null;visiblePaths=ownedPaths.filter(path=>{if(!permissionManager.isPrivateTarget(path))return true;const entry=ownership.pathToModule.get(path)?.find(candidate=>candidate.moduleID===moduleID);return permissionManager.checkAccess(callerPath,path,callerFilePath,entry?.filePath,runtimeContext)})}if(details){return visiblePaths.map(path=>({path,kind:kindOf(path)}))}return visiblePaths.filter(path=>kindOf(path)==="function")},reload:async function slothlet_api_reload(pathOrModuleId,options){if(!config.api?.mutations?.reload){throw new slothlet.SlothletError("INVALID_CONFIG_MUTATIONS_DISABLED",{operation:"api.reload",validationError:true})}if(pathOrModuleId==null||pathOrModuleId===""||pathOrModuleId==="."){return slothlet.handlers.apiManager.reloadApiComponent({apiPath:".",options})}if(typeof pathOrModuleId!=="string"){throw new slothlet.SlothletError("INVALID_ARGUMENT",{argument:"pathOrModuleId",expected:"string, null, undefined, or '.'",received:typeof pathOrModuleId,validationError:true})}const isModuleId=slothlet.handlers.apiManager.state.addHistory.some(entry=>entry.moduleID===pathOrModuleId);if(isModuleId){return slothlet.handlers.apiManager.reloadApiComponent({moduleID:pathOrModuleId,options})}const normalizedPath=slothlet.handlers.apiManager.normalizeApiPath(pathOrModuleId).apiPath;const pathParts=normalizedPath.split(".");let current=slothlet.api;for(const part of pathParts){if(!current||typeof current!=="object"&&typeof current!=="function"){throw new slothlet.SlothletError("INVALID_API_PATH",{apiPath:pathOrModuleId,validationError:true})}current=current[part]}if(current===void 0){throw new slothlet.SlothletError("INVALID_API_PATH",{apiPath:pathOrModuleId,validationError:true})}return slothlet.handlers.apiManager.reloadApiComponent({apiPath:normalizedPath,options})},modules:{discover:function slothlet_modules_discover(options){return slothlet.handlers.moduleManager.discover(options)},sort:function slothlet_modules_sort(results,comparator){return slothlet.handlers.moduleManager.sort(results,comparator)},addModule:async function slothlet_modules_addModule(nameOrResult,options){if(!config.api?.mutations?.add){throw new slothlet.SlothletError("INVALID_CONFIG_MUTATIONS_DISABLED",{operation:"api.modules.addModule",validationError:true})}return slothlet.handlers.moduleManager.addModule(nameOrResult,options)},addModules:async function slothlet_modules_addModules(items,options){if(!config.api?.mutations?.add){throw new slothlet.SlothletError("INVALID_CONFIG_MUTATIONS_DISABLED",{operation:"api.modules.addModules",validationError:true})}return slothlet.handlers.moduleManager.addModules(items,options)},removeModule:async function slothlet_modules_removeModule(name,opts){if(!config.api?.mutations?.remove){throw new slothlet.SlothletError("INVALID_CONFIG_MUTATIONS_DISABLED",{operation:"api.modules.removeModule",validationError:true})}return slothlet.handlers.moduleManager.removeModule(name,opts)},addDiscovered:async function slothlet_modules_addDiscovered(options={}){if(!config.api?.mutations?.add){throw new slothlet.SlothletError("INVALID_CONFIG_MUTATIONS_DISABLED",{operation:"api.modules.addDiscovered",validationError:true})}const{sort:comparator,collisionMode,onFailure,concurrency,...discoverOptions}=options;const found=await slothlet.handlers.moduleManager.discover(discoverOptions);const ordered=slothlet.handlers.moduleManager.sort(found,comparator);return slothlet.handlers.moduleManager.addModules(ordered,{collisionMode,onFailure,concurrency})},getDiscoveryCache:function slothlet_modules_getDiscoveryCache(){return slothlet.handlers.moduleManager.getDiscoveryCache()},clearDiscoveryCache:function slothlet_modules_clearDiscoveryCache(){return slothlet.handlers.moduleManager.clearDiscoveryCache()},getStaleMounts:function slothlet_modules_getStaleMounts(){return slothlet.handlers.moduleManager.getStaleMounts()}}},sanitize:function slothlet_sanitize(str){if(typeof str!=="string"){throw new slothlet.SlothletError("INVALID_ARGUMENT",{argument:"str",expected:"string",received:typeof str,validationError:true})}return slothlet.helpers.sanitize.sanitizePropertyName(str,slothlet.config.sanitize||{})},lockCaller:function slothlet_lockCaller(fn){if(typeof fn!=="function"){throw new slothlet.SlothletError("INVALID_ARGUMENT",{argument:"fn",expected:"function",received:typeof fn,validationError:true})}const capturedWrapper=slothlet.contextManager?.getCallerIdentity?.()?.currentWrapper??null;if(!capturedWrapper)return fn;const locked=function slothlet_lockedCaller(...args){return slothlet.contextManager.runInContext(slothlet.instanceID,fn,this,args,capturedWrapper,true)};locked._slothletOriginal=fn;return locked},bind:function slothlet_bind(fn){if(typeof fn!=="function"){throw new slothlet.SlothletError("INVALID_ARGUMENT",{argument:"fn",expected:"function",received:typeof fn,validationError:true})}return AsyncResource?AsyncResource.bind(fn,"slothlet-bound"):fn},context:{get:key=>{if(slothlet.contextManager.constructor.name==="LiveContextManager"){const currentID=slothlet.contextManager.currentInstanceID;if(currentID){const activeStore=slothlet.contextManager.instances.get(currentID);const isOurInstance=currentID===slothlet.instanceID||currentID?.startsWith(slothlet.instanceID+"__run_")||activeStore?.parentInstanceID===slothlet.instanceID;if(isOurInstance&&activeStore){return key?activeStore.context[key]:{...activeStore.context}}}const store=slothlet.contextManager.instances.get(slothlet.instanceID);if(!store){const baseContext2=slothlet.context||{};return key?baseContext2[key]:{...baseContext2}}return key?store.context[key]:{...store.context}}if(slothlet.contextManager.constructor.name==="AsyncContextManager"){let currentStore=slothlet.contextManager.tryGetContext();if(!currentStore){const baseStore2=slothlet.contextManager.instances.get(slothlet.instanceID);const baseContext3=baseStore2?.context||{};return key?baseContext3[key]:{...baseContext3}}const isOurInstance=currentStore.instanceID===slothlet.instanceID||currentStore.parentInstanceID===slothlet.instanceID||currentStore.instanceID.startsWith(slothlet.instanceID+"__run_");if(isOurInstance){return key?currentStore.context[key]:{...currentStore.context}}const baseStore=slothlet.contextManager.instances.get(slothlet.instanceID);const baseContext2=baseStore?.context||{};return key?baseContext2[key]:{...baseContext2}}const baseContext=slothlet.context||{};return key?baseContext[key]:{...baseContext}},diagnostics:()=>{if(!slothlet.config?.diagnostics)return void 0;const managerType=slothlet.contextManager.constructor.name;const result={instanceID:slothlet.instanceID,managerType,instancesMapSize:slothlet.contextManager.instances.size,instancesMapKeys:Array.from(slothlet.contextManager.instances.keys()),baseContext:slothlet.context};const store=slothlet.contextManager.instances.get(slothlet.instanceID);result.storeFromInstancesMap=store?{instanceID:store.instanceID,context:store.context,createdAt:store.createdAt}:null;if(managerType==="AsyncContextManager"){try{const currentCtx=slothlet.contextManager.tryGetContext();result.currentALSContext=currentCtx?{instanceID:currentCtx.instanceID,context:currentCtx.context,hasParent:!!currentCtx.parentContext,parentInstanceID:currentCtx.parentInstanceID}:null}catch(____error){result.currentALSContext=null}}if(managerType==="LiveContextManager"){result.currentInstanceID=slothlet.contextManager.currentInstanceID}return result},run:this.createRunFunction(),scope:this.createScopeFunction()},hook:{on:function slothlet_hook_on(typePattern,handler,options={}){if(!slothlet.handlers?.hookManager){throw new slothlet.SlothletError("HOOKS_NOT_INITIALIZED",{validationError:true})}return slothlet.handlers.hookManager.on(typePattern,handler,options)},remove:function slothlet_hook_remove(filter={}){if(!slothlet.handlers?.hookManager){throw new slothlet.SlothletError("HOOKS_NOT_INITIALIZED",{validationError:true})}return slothlet.handlers.hookManager.remove(filter)},clear:function slothlet_hook_clear(filter={}){return this.remove(filter)},off:function slothlet_hook_off(idOrFilter){if(!slothlet.handlers?.hookManager){throw new slothlet.SlothletError("HOOKS_NOT_INITIALIZED",{validationError:true})}const filter=typeof idOrFilter==="string"?{id:idOrFilter}:idOrFilter;return slothlet.handlers.hookManager.remove(filter)},enable:function slothlet_hook_enable(filter={}){if(!slothlet.handlers?.hookManager){throw new slothlet.SlothletError("HOOKS_NOT_INITIALIZED",{validationError:true})}return slothlet.handlers.hookManager.enable(filter)},disable:function slothlet_hook_disable(filter={}){if(!slothlet.handlers?.hookManager){throw new slothlet.SlothletError("HOOKS_NOT_INITIALIZED",{validationError:true})}return slothlet.handlers.hookManager.disable(filter)},enablePattern:function slothlet_hook_enablePattern(pattern){if(!slothlet.handlers?.hookManager){throw new slothlet.SlothletError("HOOKS_NOT_INITIALIZED",{validationError:true})}return slothlet.handlers.hookManager.enablePattern(pattern)},disablePattern:function slothlet_hook_disablePattern(pattern){if(!slothlet.handlers?.hookManager){throw new slothlet.SlothletError("HOOKS_NOT_INITIALIZED",{validationError:true})}return slothlet.handlers.hookManager.disablePattern(pattern)},resetPatternFilter:function slothlet_hook_resetPatternFilter(){if(!slothlet.handlers?.hookManager){throw new slothlet.SlothletError("HOOKS_NOT_INITIALIZED",{validationError:true})}return slothlet.handlers.hookManager.resetPatternFilter()},list:function slothlet_hook_list(filter={}){if(!slothlet.handlers?.hookManager){throw new slothlet.SlothletError("HOOKS_NOT_INITIALIZED",{validationError:true})}return slothlet.handlers.hookManager.list(filter)},pin:{get enabled(){if(!slothlet.handlers?.hookManager){throw new slothlet.SlothletError("HOOKS_NOT_INITIALIZED",{validationError:true})}return slothlet.handlers.hookManager.pinEnforced},enable:function slothlet_hook_pin_enable(){if(!slothlet.handlers?.hookManager){throw new slothlet.SlothletError("HOOKS_NOT_INITIALIZED",{validationError:true})}return slothlet.handlers.hookManager.setPinEnforced(true)},disable:function slothlet_hook_pin_disable(){if(!slothlet.handlers?.hookManager){throw new slothlet.SlothletError("HOOKS_NOT_INITIALIZED",{validationError:true})}return slothlet.handlers.hookManager.setPinEnforced(false)}}},metadata:{setGlobal:function slothlet_metadata_setGlobal(keyOrObj,value){if(!slothlet.handlers?.metadata){throw new slothlet.SlothletError("METADATA_NOT_AVAILABLE",{handlersKeys:slothlet.handlers?Object.keys(slothlet.handlers).join(", "):"undefined",validationError:true})}const validateGlobalMetadataKeyPath=keyPath=>{const blocked=new Set(["__proto__","prototype","constructor"]);if(typeof keyPath!=="string"||keyPath.length===0){throw new slothlet.SlothletError("INVALID_METADATA_KEY",{key:keyPath,type:typeof keyPath,expected:"non-empty string"})}const segments=keyPath.split(".");for(const segment of segments){if(!segment||blocked.has(segment)){throw new slothlet.SlothletError("INVALID_METADATA_KEY",{key:keyPath,type:typeof keyPath,expected:"safe dot-notation key without reserved segments"})}}};const normalizeGlobalMetadataObject=(source,prefix="",ancestors=new WeakSet)=>{if(ancestors.has(source)){throw new slothlet.SlothletError("INVALID_ARGUMENT",{argument:"keyOrObj",expected:"acyclic object",received:"circular reference",validationError:true})}ancestors.add(source);try{const normalized={};for(const[key,nestedValue]of Object.entries(source)){const fullKey=prefix?`${prefix}.${key}`:key;validateGlobalMetadataKeyPath(fullKey);const nestedProto=nestedValue&&typeof nestedValue==="object"?Object.getPrototypeOf(nestedValue):null;const isPlainNested=nestedProto===Object.prototype||nestedProto===null;if(nestedValue&&typeof nestedValue==="object"&&!Array.isArray(nestedValue)&&isPlainNested){normalized[key]=normalizeGlobalMetadataObject(nestedValue,fullKey,ancestors);continue}normalized[key]=nestedValue}return normalized}finally{ancestors.delete(source)}};if(keyOrObj&&typeof keyOrObj==="object"&&!Array.isArray(keyOrObj)){const normalizedMetadata=normalizeGlobalMetadataObject(keyOrObj);for(const[key,nestedValue]of Object.entries(normalizedMetadata)){slothlet.handlers.metadata.setGlobalMetadata(key,nestedValue)}return}if(typeof keyOrObj!=="string"){throw new slothlet.SlothletError("INVALID_ARGUMENT",{argument:"keyOrObj",expected:"string or object",received:typeof keyOrObj,validationError:true})}validateGlobalMetadataKeyPath(keyOrObj);return slothlet.handlers.metadata.setGlobalMetadata(keyOrObj,value)},set:function slothlet_metadata_set(fn,key,value){if(!slothlet.handlers?.metadata){throw new slothlet.SlothletError("METADATA_NOT_AVAILABLE",{handlersKeys:slothlet.handlers?Object.keys(slothlet.handlers).join(", "):"undefined",validationError:true})}return slothlet.handlers.metadata.setUserMetadata(fn,key,value)},remove:function slothlet_metadata_remove(fn,key){return slothlet.handlers.metadata.removeUserMetadata(fn,key)},setFor:function slothlet_metadata_setFor(pathOrModuleId,keyOrObj,value){if(!slothlet.handlers?.metadata){throw new slothlet.SlothletError("METADATA_NOT_AVAILABLE",{handlersKeys:slothlet.handlers?Object.keys(slothlet.handlers).join(", "):"undefined",validationError:true})}const resolvedPath=_resolvePathOrModuleId(slothlet,pathOrModuleId);return slothlet.handlers.metadata.setPathMetadata(resolvedPath,keyOrObj,value)},removeFor:function slothlet_metadata_removeFor(pathOrModuleId,key){if(!slothlet.handlers?.metadata)return;const resolvedPath=_resolvePathOrModuleId(slothlet,pathOrModuleId);return slothlet.handlers.metadata.removePathMetadata(resolvedPath,key)},getFor:function slothlet_metadata_getFor(pathOrModuleId){if(!slothlet.handlers?.metadata)return{};const resolvedPath=_resolvePathOrModuleId(slothlet,pathOrModuleId);return slothlet.handlers.metadata.getPathMetadata(resolvedPath)},setForVersion:function slothlet_metadata_setForVersion(logicalPath,versionTag,keyOrObj,value){if(!slothlet.handlers?.metadata){throw new slothlet.SlothletError("METADATA_NOT_AVAILABLE",{handlersKeys:slothlet.handlers?Object.keys(slothlet.handlers).join(", "):"undefined",validationError:true})}const info=slothlet.handlers?.versionManager?.list(logicalPath);if(!info||!info.versions?.[versionTag]){throw new slothlet.SlothletError("VERSION_NOT_FOUND",{version:versionTag,apiPath:logicalPath})}const{moduleID}=info.versions[versionTag];const resolvedPath=_resolvePathOrModuleId(slothlet,moduleID);return slothlet.handlers.metadata.setPathMetadata(resolvedPath,keyOrObj,value)},getForVersion:function slothlet_metadata_getForVersion(logicalPath,versionTag){if(!slothlet.handlers?.metadata)return{};const info=slothlet.handlers?.versionManager?.list(logicalPath);if(!info||!info.versions?.[versionTag])return{};const{moduleID}=info.versions[versionTag];const resolvedPath=_resolvePathOrModuleId(slothlet,moduleID);return slothlet.handlers.metadata.getPathMetadata(resolvedPath)}},scope:this.createScopeFunction(),run:this.createRunFunction(),reload:async(options={})=>{if(!config.api?.mutations?.reload){throw new slothlet.SlothletError("INVALID_CONFIG_MUTATIONS_DISABLED",{operation:"reload",validationError:true})}return slothlet.reload(options)},shutdown:async()=>{return slothlet.shutdown()},owner:{get:apiPath=>{if(slothlet.handlers?.ownership){return slothlet.handlers.ownership.getPathOwnership(apiPath)}return null}},materialize:(()=>{const mgr=slothlet.handlers?.materialize;const getMaterializedState=()=>{enforceInternalPermission("slothlet.materialize.materialized");return mgr?.materialized??false};const getMaterializeStats=()=>{enforceInternalPermission("slothlet.materialize.get");return mgr?mgr.get():{total:0,materialized:0,remaining:0,percentage:100}};const waitForMaterialization=async()=>{enforceInternalPermission("slothlet.materialize.wait");if(!mgr)return;return mgr.wait()};if(!mgr){return Object.freeze({get materialized(){return getMaterializedState()},get:getMaterializeStats,wait:waitForMaterialization})}return Object.freeze({get materialized(){return getMaterializedState()},get:getMaterializeStats,wait:waitForMaterialization})})(),lifecycle:(()=>{const handler=slothlet.handlers?.lifecycle;const noop=()=>{};if(!handler)return{on:noop,off:noop};return{on:handler.on.bind(handler),off:handler.off.bind(handler)}})(),env:slothlet.envSnapshot,versioning:{list:function slothlet_version_list(logicalPath){if(!slothlet.handlers?.versionManager)return void 0;return slothlet.handlers.versionManager.list(logicalPath)},setDefault:function slothlet_version_setDefault(logicalPath,versionTag){if(!slothlet.handlers?.versionManager)return;return slothlet.handlers.versionManager.setDefault(logicalPath,versionTag)},unregister:async function slothlet_version_unregister(logicalPath,versionTag){if(!slothlet.handlers?.versionManager)return false;const info=slothlet.handlers.versionManager.list(logicalPath);if(!info||!info.versions?.[versionTag])return false;const{moduleID:versionedModuleID}=info.versions[versionTag];await slothlet.handlers.apiManager.removeApiComponent(versionedModuleID);return true},getVersionMetadata:function slothlet_version_getVersionMetadata(logicalPath,versionTag){if(!slothlet.handlers?.versionManager)return void 0;return slothlet.handlers.versionManager.getVersionMetadataByPath(logicalPath,versionTag)},setVersionMetadata:function slothlet_version_setVersionMetadata(logicalPath,versionTag,patch){if(!slothlet.handlers?.versionManager)return;return slothlet.handlers.versionManager.setVersionMetadataByPath(logicalPath,versionTag,patch)}},permissions:{addRule:function slothlet_permissions_addRule(rule){if(!config.api?.mutations?.permissions){throw new slothlet.SlothletError("INVALID_CONFIG_MUTATIONS_DISABLED",{operation:"api.slothlet.permissions.addRule",validationError:true})}const permissionManager=slothlet.handlers?.permissionManager;if(!permissionManager?.addRule){throw new slothlet.SlothletError("PERMISSION_MANAGER_NOT_AVAILABLE",{validationError:true})}const ruleId=permissionManager.addRule(rule,null);if(slothlet.handlers?.apiManager?.state?.operationHistory){slothlet.handlers.apiManager.state.operationHistory.push({type:"addPermissionRule",rule,ownerModuleID:null,ruleId,timestamp:Date.now()})}return ruleId},removeRule:function slothlet_permissions_removeRule(ruleId){if(!config.api?.mutations?.permissions){throw new slothlet.SlothletError("INVALID_CONFIG_MUTATIONS_DISABLED",{operation:"api.slothlet.permissions.removeRule",validationError:true})}const permissionManager=slothlet.handlers?.permissionManager;if(!permissionManager?.removeRule){throw new slothlet.SlothletError("PERMISSION_MANAGER_NOT_AVAILABLE",{validationError:true})}const currentWrapper=slothlet.contextManager?.getCallerIdentity?.()?.currentWrapper;const callerModuleID=currentWrapper?.____slothletInternal?.moduleID??null;const result=slothlet.handlers.permissionManager.removeRule(ruleId,callerModuleID);if(result&&slothlet.handlers?.apiManager?.state?.operationHistory){slothlet.handlers.apiManager.state.operationHistory.push({type:"removePermissionRule",ruleId,callerModuleID,timestamp:Date.now()})}return result},self:{access:function slothlet_permissions_self_access(target){const permissionManager=slothlet.handlers?.permissionManager;if(!permissionManager?.checkAccess){throw new slothlet.SlothletError("PERMISSION_MANAGER_NOT_AVAILABLE",{validationError:true})}const ctx=slothlet.contextManager?.tryGetContext?.();const currentWrapper=slothlet.contextManager?.getCallerIdentity?.()?.currentWrapper;const callerPath=currentWrapper?.____slothletInternal?.apiPath??"";const callerFilePath=currentWrapper?.____slothletInternal?.filePath??null;const runtimeContext=ctx?.context??null;return slothlet.handlers.permissionManager.checkAccess(callerPath,target,callerFilePath,null,runtimeContext)},rules:function slothlet_permissions_self_rules(){const permissionManager=slothlet.handlers?.permissionManager;if(!permissionManager?.getRulesForCaller){throw new slothlet.SlothletError("PERMISSION_MANAGER_NOT_AVAILABLE",{validationError:true})}const currentWrapper=slothlet.contextManager?.getCallerIdentity?.()?.currentWrapper;const callerPath=currentWrapper?.____slothletInternal?.apiPath??"";return slothlet.handlers.permissionManager.getRulesForCaller(callerPath)}},global:{checkAccess:function slothlet_permissions_global_checkAccess(caller,target){const permissionManager=slothlet.handlers?.permissionManager;if(!permissionManager?.checkAccess){throw new slothlet.SlothletError("PERMISSION_MANAGER_NOT_AVAILABLE",{validationError:true})}const runtimeContext=slothlet.contextManager?.tryGetContext?.()?.context??null;return slothlet.handlers.permissionManager.checkAccess(caller,target,null,null,runtimeContext)},rulesForPath:function slothlet_permissions_global_rulesForPath(path){const permissionManager=slothlet.handlers?.permissionManager;if(!permissionManager?.getRulesForPath){throw new slothlet.SlothletError("PERMISSION_MANAGER_NOT_AVAILABLE",{validationError:true})}return slothlet.handlers.permissionManager.getRulesForPath(path)},rulesByModule:function slothlet_permissions_global_rulesByModule(moduleID){const permissionManager=slothlet.handlers?.permissionManager;if(!permissionManager?.getRulesByModule){throw new slothlet.SlothletError("PERMISSION_MANAGER_NOT_AVAILABLE",{validationError:true})}return slothlet.handlers.permissionManager.getRulesByModule(moduleID)}},control:{get enabled(){const permissionManager=slothlet.handlers?.permissionManager;if(!permissionManager?.isEnabled){throw new slothlet.SlothletError("PERMISSION_MANAGER_NOT_AVAILABLE",{validationError:true})}return permissionManager.isEnabled()},enable:function slothlet_permissions_control_enable(){const permissionManager=slothlet.handlers?.permissionManager;if(!permissionManager?.enable){throw new slothlet.SlothletError("PERMISSION_MANAGER_NOT_AVAILABLE",{validationError:true})}slothlet.handlers.permissionManager.enable()},disable:function slothlet_permissions_control_disable(){const permissionManager=slothlet.handlers?.permissionManager;if(!permissionManager?.disable){throw new slothlet.SlothletError("PERMISSION_MANAGER_NOT_AVAILABLE",{validationError:true})}slothlet.handlers.permissionManager.disable()},get readGatingEnabled(){const permissionManager=slothlet.handlers?.permissionManager;if(!permissionManager?.isReadGatingEnabled){throw new slothlet.SlothletError("PERMISSION_MANAGER_NOT_AVAILABLE",{validationError:true})}return permissionManager.isReadGatingEnabled()},readGating:function slothlet_permissions_control_readGating(value){const permissionManager=slothlet.handlers?.permissionManager;if(!permissionManager?.setReadGating){throw new slothlet.SlothletError("PERMISSION_MANAGER_NOT_AVAILABLE",{validationError:true})}slothlet.handlers.permissionManager.setReadGating(value)},seal:function slothlet_permissions_control_seal(){const permissionManager=slothlet.handlers?.permissionManager;if(!permissionManager?.seal){throw new slothlet.SlothletError("PERMISSION_MANAGER_NOT_AVAILABLE",{validationError:true})}slothlet.handlers.permissionManager.seal()},get sealed(){const permissionManager=slothlet.handlers?.permissionManager;if(!permissionManager?.isSealed){throw new slothlet.SlothletError("PERMISSION_MANAGER_NOT_AVAILABLE",{validationError:true})}return permissionManager.isSealed()}}}};if(!config.hook?.enabled&&config.diagnostics!==true){delete namespace.hooks}if(config.diagnostics===true){namespace.diag={describe:(showAll=false)=>{if(showAll){return{...userApi}}return Reflect.ownKeys(userApi)},reference:slothlet.reference||null,context:slothlet.context||{},inspect:()=>{return slothlet.getDiagnostics()},getAPI:()=>{return slothlet.getAPI()},getOwnership:()=>{return slothlet.getOwnership()},owner:{get:apiPath=>{if(slothlet.handlers?.ownership){return slothlet.handlers.ownership.getPathOwnership(apiPath)}return null}},caches:{get:()=>{if(slothlet.handlers?.apiCacheManager){return slothlet.handlers.apiCacheManager.getCacheDiagnostics()}return{totalCaches:0,caches:[]}},getAllModuleIDs:()=>{if(slothlet.handlers?.apiCacheManager){return slothlet.handlers.apiCacheManager.getAllModuleIDs()}return[]},has:moduleID=>{if(slothlet.handlers?.apiCacheManager){return slothlet.handlers.apiCacheManager.has(moduleID)}return false}},SlothletWarning:slothlet.SlothletWarning,hook:slothlet.handlers?.hookManager?{get enabled(){return slothlet.handlers.hookManager.enabled},compilePattern:pattern=>{return slothlet.handlers.hookManager.getCompilePatternForDiagnostics()(pattern)}}:void 0}}return createInternalRouteProxy(namespace,"slothlet")}createShutdownFunction(){const slothlet=this.slothlet;const shutdownFunction={shutdown:async()=>{if(slothlet.config.collectLifecycleHooks){const nestedHooks=(await slothlet._collectLifecycleHooks("shutdown")).reverse();for(const{fn,receiver}of nestedHooks){try{await Reflect.apply(fn,receiver,[])}catch{}}}if(slothlet.userHooks?.shutdown&&typeof slothlet.userHooks.shutdown==="function"){await slothlet.userHooks.shutdown()}return slothlet.shutdown()}}.shutdown;return shutdownFunction}createRunFunction(){const slothlet=this.slothlet;const scopeFunc=this.createScopeFunction();const runFunction={run:async(contextData,callback,...args)=>{if(slothlet.config.scope===false){throw new slothlet.SlothletError("SCOPE_DISABLED",{},null,{validationError:true})}if(!contextData||typeof contextData!=="object"){throw new slothlet.SlothletError("SCOPE_INVALID_CONTEXT",{received:typeof contextData},null,{validationError:true})}if(typeof callback!=="function"){throw new slothlet.SlothletError("SCOPE_INVALID_CALLBACK",{received:typeof callback},null,{validationError:true})}return scopeFunc({context:contextData,fn:callback,args,merge:slothlet.config.scope?.merge||"shallow",isolation:slothlet.config.scope?.isolation||"partial"})}}.run;return runFunction}createScopeFunction(){const slothlet=this.slothlet;const scopeFunction={scope:async options=>{if(slothlet.config.scope===false){throw new slothlet.SlothletError("SCOPE_DISABLED",{},null,{validationError:true})}if(!options||typeof options!=="object"){throw new slothlet.SlothletError("SCOPE_INVALID_OPTIONS",{received:typeof options},null,{validationError:true})}if(!options.fn||typeof options.fn!=="function"){throw new slothlet.SlothletError("SCOPE_INVALID_FN",{received:typeof options?.fn},null,{validationError:true})}if(!options.context||typeof options.context!=="object"){throw new slothlet.SlothletError("SCOPE_INVALID_CONTEXT_OBJECT",{received:typeof options?.context},null,{validationError:true})}const{context:contextData,fn,args=[],merge="shallow",isolation,protect,owners}=options;if(merge!=="shallow"&&merge!=="deep"){throw new slothlet.SlothletError("SCOPE_INVALID_MERGE_STRATEGY",{merge},null,{validationError:true})}const isolationMode=isolation||slothlet.config.scope?.isolation||"partial";if(isolationMode!=="partial"&&isolationMode!=="full"){throw new slothlet.SlothletError("SCOPE_INVALID_ISOLATION_MODE",{isolationMode},null,{validationError:true})}if(protect!==void 0&&(!Array.isArray(protect)||protect.some(k=>typeof k!=="string"))){throw new slothlet.SlothletError("SCOPE_INVALID_PROTECT",{received:describeScopeReceived(protect)},null,{validationError:true})}if(owners!==void 0){if(typeof owners!=="object"||owners===null||Array.isArray(owners)){throw new slothlet.SlothletError("SCOPE_INVALID_OWNERS",{received:describeScopeReceived(owners)},null,{validationError:true})}for(const[key,owner]of Object.entries(owners)){if(typeof owner!=="string"||owner.length===0){throw new slothlet.SlothletError("INVALID_ARGUMENT",{argument:`owners.${key}`,expected:"non-empty string",received:typeof owner==="string"?"empty string":typeof owner,validationError:true})}}}const buildContextOwners=parentOwners=>{const base=parentOwners??null;let child=base;const claim=(key,owner)=>{const existing=child&&Object.prototype.hasOwnProperty.call(child,key)?child[key]:void 0;if(existing!==void 0&&existing!==owner){throw new slothlet.SlothletError("CONTEXT_KEY_OWNED",{key:String(key)},null,{validationError:true})}if(child===base)child=base?Object.assign(Object.create(null),base):Object.create(null);child[key]=owner};if(Array.isArray(protect))for(const k of protect)claim(k,PROTECT_SENTINEL);if(owners&&typeof owners==="object")for(const[k,o]of Object.entries(owners))claim(k,o);return child};const contextManager=slothlet.contextManager;if(!contextManager){throw new slothlet.SlothletError("NO_CONTEXT_MANAGER",{validationError:true})}const{utilities}=slothlet.helpers;if(contextManager.constructor.name==="LiveContextManager"){let currentStore=null;const currentID=contextManager.currentInstanceID;if(currentID){const activeStore=contextManager.instances.get(currentID);const isOurContext=currentID===slothlet.instanceID||activeStore?.parentInstanceID===slothlet.instanceID||currentID.startsWith(slothlet.instanceID+"__run_");if(isOurContext){currentStore=activeStore}}if(!currentStore){currentStore=contextManager.instances.get(slothlet.instanceID)}if(!currentStore){throw new slothlet.SlothletError("CONTEXT_NOT_FOUND",{instanceID:slothlet.instanceID,availableInstances:[...contextManager.instances.keys()].join(", ")||"none",validationError:true})}let mergedContext;if(merge==="deep"){mergedContext=utilities.deepMerge(currentStore.context,contextData);mergedContext=structuredClone(mergedContext)}else{const clonedParent=structuredClone(currentStore.context);mergedContext={...clonedParent,...contextData}}const childInstanceID=`${slothlet.instanceID}__run_${Date.now()}_${Math.random().toString(36).slice(2,9)}`;const childStore={instanceID:childInstanceID,context:mergedContext,self:isolationMode==="full"?makeCopyOnWriteSelf(currentStore.self):currentStore.self,config:currentStore.config,createdAt:currentStore.createdAt,parentInstanceID:slothlet.instanceID,currentWrapper:currentStore.currentWrapper,callerWrapper:currentStore.callerWrapper,slothlet:currentStore.slothlet,__contextOwners:buildContextOwners(currentStore.__contextOwners)};if(currentStore[TRUSTED_ROOT]===true){Object.defineProperty(childStore,TRUSTED_ROOT,{value:true,configurable:true})}contextManager.instances.set(childInstanceID,childStore);const previousInstanceID=contextManager.currentInstanceID;try{contextManager.currentInstanceID=childInstanceID;return await fn(...args)}finally{contextManager.currentInstanceID=previousInstanceID;contextManager.instances.delete(childInstanceID)}}if(contextManager.constructor.name==="AsyncContextManager"){let currentStore=null;const activeStore=contextManager.tryGetContext();if(activeStore){const isOurContext=activeStore.instanceID===slothlet.instanceID||activeStore.parentInstanceID===slothlet.instanceID||activeStore.instanceID.startsWith(slothlet.instanceID+"__run_");if(isOurContext){currentStore=activeStore}}if(!currentStore){const baseStore=contextManager.instances.get(slothlet.instanceID);if(!baseStore){throw new slothlet.SlothletError("CONTEXT_NOT_FOUND",{instanceID:slothlet.instanceID,availableInstances:[...contextManager.instances.keys()].join(", ")||"none",validationError:true})}currentStore=baseStore}let mergedContext;if(merge==="deep"){mergedContext=utilities.deepMerge(currentStore.context,contextData);mergedContext=structuredClone(mergedContext)}else{const clonedParent=structuredClone(currentStore.context);mergedContext={...clonedParent,...contextData}}const childInstanceID=`${slothlet.instanceID}__run_${Date.now()}_${Math.random().toString(36).slice(2,9)}`;const childStore={instanceID:childInstanceID,context:mergedContext,self:isolationMode==="full"?makeCopyOnWriteSelf(currentStore.self):currentStore.self,config:currentStore.config,createdAt:currentStore.createdAt,parentInstanceID:slothlet.instanceID,currentWrapper:currentStore.currentWrapper,callerWrapper:currentStore.callerWrapper,slothlet:currentStore.slothlet,__contextOwners:buildContextOwners(currentStore.__contextOwners)};if(currentStore[TRUSTED_ROOT]===true){Object.defineProperty(childStore,TRUSTED_ROOT,{value:true,configurable:true})}contextManager.instances.set(childInstanceID,childStore);try{return await contextManager.als.run(childStore,async()=>{return await fn(...args)})}finally{contextManager.instances.delete(childInstanceID)}}throw new slothlet.SlothletError("UNSUPPORTED_CONTEXT_MANAGER",{manager:contextManager.constructor.name,validationError:true})}}.scope;return scopeFunction}createDestroyFunction(api){const slothlet=this.slothlet;const destroyFunction={destroy:async()=>{if(slothlet.config.collectLifecycleHooks){const nestedHooks=(await slothlet._collectLifecycleHooks("destroy")).reverse();for(const{fn,receiver}of nestedHooks){try{await Reflect.apply(fn,receiver,[])}catch{}}}if(slothlet.userHooks?.destroy&&typeof slothlet.userHooks.destroy==="function"){await slothlet.userHooks.destroy()}if(api&&typeof api.shutdown==="function"){await api.shutdown()}else{await slothlet.shutdown()}slothlet.isDestroyed=true;const objectsToClear=[api,slothlet.api].filter(obj=>obj&&typeof obj==="object");for(const obj of objectsToClear){const keys=Object.keys(obj);for(const key of keys){try{delete obj[key]}catch(_){}}}slothlet.api=null}}.destroy;return destroyFunction}attachBuiltins(userApi,builtins){Object.defineProperty(userApi,"slothlet",{value:builtins.slothlet,enumerable:true,writable:false,configurable:true});Object.defineProperty(userApi,"shutdown",{value:builtins.shutdown,enumerable:true,writable:false,configurable:true});if(builtins.destroy!==null){Object.defineProperty(userApi,"destroy",{value:builtins.destroy,enumerable:true,writable:false,configurable:true})}}}export{ApiBuilder};
@@ -14,4 +14,4 @@
14
14
  limitations under the License.
15
15
  */
16
16
 
17
- import{ComponentBase}from"#factories/component-base";class Builder extends ComponentBase{static slothletProperty="builder";constructor(slothlet){super(slothlet)}async buildAPI(options){const{dir,mode="eager",apiPathPrefix="",collisionContext="initial",moduleID,cacheBust=null,fileFilter=null,hidden=null,scanHiddenFolders=false,collisionMode=null,syntheticExports=null,syntheticName="synthetic",rootUnwrap=false}=options;let preloadedStructure=null;let effectiveDir=dir;if(syntheticExports!=null){const isPlainObject=value=>{if(value===null||typeof value!=="object")return false;const proto=Object.getPrototypeOf(value);return proto===Object.prototype||proto===null};if(!isPlainObject(syntheticExports)){throw new this.SlothletError("INVALID_CONFIG_SYNTHETIC_EXPORTS_SHAPE",{received:Array.isArray(syntheticExports)?"array":typeof syntheticExports==="object"?`${syntheticExports.constructor?.name??"non-plain object"} instance`:typeof syntheticExports,validationError:true})}if(typeof syntheticName!=="string"||!syntheticName){throw new this.SlothletError("INVALID_CONFIG_SYNTHETIC_NAME",{received:typeof syntheticName==="string"?"<empty>":typeof syntheticName,validationError:true})}const sentinel=`synthetic:${syntheticName}`;effectiveDir=sentinel;preloadedStructure={files:[{path:sentinel,name:syntheticName,fullName:`${syntheticName}.mjs`,moduleID,synthetic:true,exports:syntheticExports}],directories:[]}}else if(!dir||typeof dir!=="string"){throw new this.SlothletError("INVALID_CONFIG_DIR_INVALID",{dir},null,{validationError:true})}if(mode!=="eager"&&mode!=="lazy"){throw new this.SlothletError("INVALID_CONFIG_MODE_INVALID",{value:mode},null,{validationError:true})}let rawAPI;if(mode==="eager"){rawAPI=await this.slothlet.modes.eager.buildAPI({dir:effectiveDir,apiPathPrefix,collisionContext,moduleID,apiDepth:this.slothlet.config.apiDepth,cacheBust,fileFilter,hidden,scanHiddenFolders,preloadedStructure,rootUnwrap})}else{rawAPI=await this.slothlet.modes.lazy.buildAPI({dir:effectiveDir,apiPathPrefix,collisionContext,collisionMode,moduleID,apiDepth:this.slothlet.config.apiDepth,cacheBust,fileFilter,hidden,scanHiddenFolders,preloadedStructure,rootUnwrap})}return rawAPI}}export{Builder};
17
+ import{ComponentBase}from"#factories/component-base";class Builder extends ComponentBase{static slothletProperty="builder";constructor(slothlet){super(slothlet)}async buildAPI(options){const{dir,mode="eager",apiPathPrefix="",collisionContext="initial",moduleID,cacheBust=null,fileFilter=null,hidden=null,scanHiddenFolders=false,collisionMode=null,syntheticExports=null,syntheticName="synthetic",rootUnwrap=false}=options;let preloadedStructure=null;let effectiveDir=dir;if(syntheticExports!=null){const isPlainObject=value=>{if(value===null||typeof value!=="object")return false;const proto=Object.getPrototypeOf(value);return proto===Object.prototype||proto===null};if(!isPlainObject(syntheticExports)){throw new this.SlothletError("INVALID_CONFIG_SYNTHETIC_EXPORTS_SHAPE",{received:Array.isArray(syntheticExports)?"array":typeof syntheticExports==="object"?`${syntheticExports.constructor?.name??"non-plain object"} instance`:typeof syntheticExports,validationError:true})}if(typeof syntheticName!=="string"||!syntheticName){throw new this.SlothletError("INVALID_CONFIG_SYNTHETIC_NAME",{received:typeof syntheticName==="string"?"<empty>":typeof syntheticName,validationError:true})}const sentinel=`synthetic:${syntheticName}`;effectiveDir=sentinel;preloadedStructure={files:[{path:sentinel,name:syntheticName,fullName:`${syntheticName}.mjs`,moduleID,synthetic:true,exports:syntheticExports}],directories:[]}}else if(!dir||typeof dir!=="string"){throw new this.SlothletError("INVALID_CONFIG_DIR_INVALID",{dir},null,{validationError:true})}if(mode!=="eager"&&mode!=="lazy"){throw new this.SlothletError("INVALID_CONFIG_MODE_INVALID",{value:mode},null,{validationError:true})}let rawAPI;this.slothlet.____buildDepth=(this.slothlet.____buildDepth||0)+1;try{if(mode==="eager"){rawAPI=await this.slothlet.modes.eager.buildAPI({dir:effectiveDir,apiPathPrefix,collisionContext,moduleID,apiDepth:this.slothlet.config.apiDepth,cacheBust,fileFilter,hidden,scanHiddenFolders,preloadedStructure,rootUnwrap})}else{rawAPI=await this.slothlet.modes.lazy.buildAPI({dir:effectiveDir,apiPathPrefix,collisionContext,collisionMode,moduleID,apiDepth:this.slothlet.config.apiDepth,cacheBust,fileFilter,hidden,scanHiddenFolders,preloadedStructure,rootUnwrap})}}finally{this.slothlet.____buildDepth--}return rawAPI}}export{Builder};
@@ -14,4 +14,4 @@
14
14
  limitations under the License.
15
15
  */
16
16
 
17
- import{translate}from"@cldmv/slothlet/i18n";import{ComponentBase}from"#factories/component-base";import{UnifiedWrapper,resolveWrapper}from"#handlers/unified-wrapper";import{isFrameworkInternal}from"#handlers/framework-internals";import{MODULE_ID_SEPARATOR}from"#handlers/metadata";import{fsp,path}from"@cldmv/slothlet/helpers/platform";const UNSAFE_PATH_SEGMENTS=new Set(["__proto__","constructor","prototype"]);class ApiManager extends ComponentBase{static slothletProperty="apiManager";constructor(slothlet){super(slothlet);this.state={addHistory:[],initialConfig:slothlet?.config||null,operationHistory:[],replaceShadows:new Map}}normalizeApiPath(apiPath){if(apiPath===""||apiPath===null||apiPath===void 0){return{apiPath:"",parts:[]}}if(Array.isArray(apiPath)){if(apiPath.length===0){return{apiPath:"",parts:[]}}for(let i=0;i<apiPath.length;i++){if(typeof apiPath[i]!=="string"){throw new this.SlothletError("INVALID_CONFIG_API_PATH_INVALID",{apiPath,segment:apiPath[i],index:i,reason:translate("API_PATH_REASON_ARRAY_ELEMENTS"),validationError:true})}if(apiPath[i].trim()===""){throw new this.SlothletError("INVALID_CONFIG_API_PATH_INVALID",{apiPath,segment:apiPath[i],index:i,reason:translate("API_PATH_REASON_ARRAY_EMPTY_SEGMENTS"),validationError:true})}}if(apiPath[0]==="slothlet"||apiPath.length===1&&(apiPath[0]==="shutdown"||apiPath[0]==="destroy")){throw new this.SlothletError("INVALID_CONFIG_API_PATH_INVALID",{apiPath,reason:translate("API_PATH_REASON_RESERVED_NAME"),index:void 0,segment:void 0,validationError:true})}const unsafeArrayIndex=apiPath.findIndex(segment=>UNSAFE_PATH_SEGMENTS.has(segment));if(unsafeArrayIndex!==-1){throw new this.SlothletError("INVALID_CONFIG_API_PATH_INVALID",{apiPath,reason:translate("API_PATH_REASON_UNSAFE_SEGMENT"),index:unsafeArrayIndex,segment:apiPath[unsafeArrayIndex],validationError:true})}return{apiPath:apiPath.join("."),parts:apiPath}}if(typeof apiPath!=="string"){throw new this.SlothletError("INVALID_CONFIG_API_PATH_INVALID",{apiPath,reason:translate("API_PATH_REASON_INVALID_TYPE"),index:void 0,segment:void 0,validationError:true})}const normalized=apiPath.trim();if(normalized===""){return{apiPath:"",parts:[]}}const parts=normalized.split(".");if(parts.length===0||parts.some(part=>part.trim()==="")){throw new this.SlothletError("INVALID_CONFIG_API_PATH_INVALID",{apiPath:normalized,reason:translate("API_PATH_REASON_EMPTY_SEGMENTS"),index:void 0,segment:void 0,validationError:true})}if(parts[0]==="slothlet"||normalized==="shutdown"||normalized==="destroy"){throw new this.SlothletError("INVALID_CONFIG_API_PATH_INVALID",{apiPath:normalized,reason:translate("API_PATH_REASON_RESERVED_NAME"),index:void 0,segment:void 0,validationError:true})}const unsafeIndex=parts.findIndex(segment=>UNSAFE_PATH_SEGMENTS.has(segment));if(unsafeIndex!==-1){throw new this.SlothletError("INVALID_CONFIG_API_PATH_INVALID",{apiPath:normalized,reason:translate("API_PATH_REASON_UNSAFE_SEGMENT"),index:unsafeIndex,segment:parts[unsafeIndex],validationError:true})}return{apiPath:normalized,parts}}async resolvePath(inputPath){if(!inputPath||typeof inputPath!=="string"){throw new this.SlothletError("INVALID_CONFIG_DIR_INVALID",{dir:inputPath,validationError:true})}const resolvedPath=this.slothlet.helpers.resolver.resolvePathFromCaller(inputPath);if(this.slothlet.envTarget==="browser"){const lastSegment=resolvedPath.split("/").pop();const isFile=lastSegment.includes(".");return{resolvedPath,isDirectory:!isFile,isFile}}try{const stats=await fsp.stat(resolvedPath);return{resolvedPath,isDirectory:stats.isDirectory(),isFile:stats.isFile()}}catch(error){if(error instanceof this.SlothletError){throw error}throw new this.SlothletError("INVALID_CONFIG_DIR_INVALID",{dir:resolvedPath,validationError:true})}}async resolveFolderPath(folderPath){if(!folderPath||typeof folderPath!=="string"){throw new this.SlothletError("INVALID_CONFIG_DIR_INVALID",{dir:folderPath,validationError:true})}const resolvedPath=this.slothlet.helpers.resolver.resolvePathFromCaller(folderPath);try{const stats=await fsp.stat(resolvedPath);if(!stats.isDirectory()){throw new this.SlothletError("INVALID_CONFIG_DIR_INVALID",{dir:resolvedPath,validationError:true})}}catch(error){if(error instanceof this.SlothletError){throw error}throw new this.SlothletError("INVALID_CONFIG_DIR_INVALID",{dir:resolvedPath,validationError:true})}return resolvedPath}buildDefaultModuleId(apiPath,____resolvedFolderPath){const randomSuffix=Math.random().toString(36).substring(2,8);const prefix=apiPath||"auto";return`${prefix}_${randomSuffix}`}getValueAtPath(root,parts){let current=root;for(const part of parts){if(!current||typeof current!=="object"&&typeof current!=="function"){return void 0}current=current[part]}return current}ensureParentPath(root,parts,options={}){const{moduleID,sourceFolder}=options;let current=root;for(let i=0;i<parts.length-1;i+=1){const part=parts[i];const next=current[part];if(next===void 0){const containerPath=parts.slice(0,i+1).join(".");const containerWrapper=new UnifiedWrapper(this.slothlet,{mode:this.____config.mode,apiPath:containerPath,moduleID,sourceFolder});containerWrapper.___setImpl({},moduleID);current[part]=containerWrapper.createProxy();current=current[part];continue}if(next&&(typeof next==="object"||typeof next==="function")){current=next;continue}throw new this.SlothletError("INVALID_CONFIG_API_PATH_INVALID",{apiPath:parts.slice(0,i+1).join("."),reason:translate("API_PATH_REASON_NOT_TRAVERSABLE"),index:void 0,segment:void 0,validationError:true})}return current}setOwnedProperty(apiPath,value,callerWrapper){const coercedPath=String(apiPath);for(const segment of coercedPath.split(".")){if(UNSAFE_PATH_SEGMENTS.has(segment)){throw new this.SlothletError("LOOSE_SET_RESERVED_KEY",{apiPath:coercedPath,segment,validationError:true})}}const{parts}=this.normalizeApiPath(apiPath);if(parts.length===0){throw new this.SlothletError("INVALID_CONFIG_API_PATH_INVALID",{apiPath:String(apiPath??""),reason:translate("API_PATH_REASON_EMPTY_SEGMENTS"),index:void 0,segment:void 0,validationError:true})}const callerModuleID=callerWrapper?.____slothletInternal?.moduleID??null;const callerWrapperPath=callerWrapper?.____slothletInternal?.apiPath??null;let ownedRoot=null;if(callerModuleID&&this.slothlet.handlers?.ownership?.getModuleEndpoint){const endpoint=this.slothlet.handlers.ownership.getModuleEndpoint(callerModuleID);if(endpoint!=null){ownedRoot=endpoint}}if(ownedRoot===null)ownedRoot=".";if(ownedRoot&&ownedRoot!=="."&&ownedRoot!==""){const ownedParts=String(ownedRoot).split(".").filter(Boolean);const isUnderOwn=ownedParts.length<=parts.length&&ownedParts.every((seg,i)=>parts[i]===seg);if(!isUnderOwn){const callerApiPath=callerWrapperPath??ownedRoot;throw new this.SlothletError("LOOSE_SET_NOT_OWNED",{apiPath:parts.join("."),callerApiPath,validationError:true})}}const callerSourceFolder=callerWrapper?.____slothletInternal?.sourceFolder??null;const root=this.slothlet.boundApi;const parent=this.ensureParentPath(root,parts,{moduleID:callerModuleID,sourceFolder:callerSourceFolder});const finalKey=parts[parts.length-1];const isWrappable=typeof value==="function"||value!==null&&typeof value==="object";if(isWrappable){const wrapper=new UnifiedWrapper(this.slothlet,{mode:this.____config.mode,apiPath:parts.join("."),moduleID:callerModuleID,isCallable:typeof value==="function",sourceFolder:callerSourceFolder});wrapper.___setImpl(value,callerModuleID);parent[finalKey]=wrapper.createProxy()}else{parent[finalKey]=value}}isWrapperProxy(value){return!!(value&&(typeof value==="object"||typeof value==="function")&&resolveWrapper(value)!==null)}async syncWrapper(existingProxy,nextProxy,config,collisionMode="replace",moduleID=null){if(config?.debug?.api){this.slothlet.debug("api",{key:"DEBUG_MODE_SYNC_WRAPPER_ENTRY_EXISTING",apiPath:resolveWrapper(existingProxy)?.apiPath});this.slothlet.debug("api",{key:"DEBUG_MODE_SYNC_WRAPPER_ENTRY_NEXT",apiPath:resolveWrapper(nextProxy)?.apiPath})}if(!this.isWrapperProxy(existingProxy)||!this.isWrapperProxy(nextProxy)){return false}const existingWrapper=resolveWrapper(existingProxy)??existingProxy;const nextWrapper=resolveWrapper(nextProxy)??nextProxy;if(config?.debug?.api){this.slothlet.debug("api",{key:"DEBUG_MODE_SYNC_WRAPPER_EXISTING",apiPath:existingWrapper.apiPath});this.slothlet.debug("api",{key:"DEBUG_MODE_SYNC_WRAPPER_NEXT",apiPath:nextWrapper.apiPath})}if(nextWrapper.____slothletInternal.materializeFunc&&collisionMode!=="merge"){existingWrapper.____slothletInternal.materializeFunc=nextWrapper.____slothletInternal.materializeFunc}const existingChildKeys=Object.keys(existingWrapper).filter(k=>!k.startsWith("_")&&!k.startsWith("__"));const nextChildKeys=Object.keys(nextWrapper).filter(k=>!k.startsWith("_")&&!k.startsWith("__"));if(config?.debug?.api){this.slothlet.debug("api",{key:"DEBUG_MODE_SYNC_WRAPPER_BEFORE_MERGE",existingCacheSize:existingChildKeys.length,nextCacheSize:nextChildKeys.length});this.slothlet.debug("api",{key:"DEBUG_MODE_SYNC_WRAPPER_NEXT_IMPL_KEYS",implKeys:Object.keys(nextWrapper.____slothletInternal.impl||{})});this.slothlet.debug("api",{key:"DEBUG_MODE_SYNC_WRAPPER_NEXT_CHILDCACHE_KEYS",childCacheKeys:nextChildKeys})}if(collisionMode==="replace"){this._recordReplaceShadows(existingWrapper,existingChildKeys,nextChildKeys,moduleID);if(existingWrapper.___setImpl&&nextWrapper.____slothletInternal.impl!==void 0){existingWrapper.___setImpl(nextWrapper.____slothletInternal.impl,moduleID)}else if(nextWrapper.____slothletInternal.impl===void 0){existingWrapper.____slothletInternal.impl=null}else{if(nextWrapper.____slothletInternal.impl!==void 0){existingWrapper.____slothletInternal.impl=nextWrapper.____slothletInternal.impl;if(typeof nextWrapper.____slothletInternal.impl==="function"||nextWrapper.____slothletInternal.impl&&typeof nextWrapper.____slothletInternal.impl.default==="function"){existingWrapper.isCallable=true}}}for(const key of existingChildKeys){delete existingWrapper[key]}existingWrapper.___adoptImplChildren();for(const key of nextChildKeys){const childValue=nextWrapper[key];Object.defineProperty(existingWrapper,key,{value:childValue,writable:false,enumerable:true,configurable:true})}}else if(collisionMode==="merge"){for(const key of nextChildKeys){const isInternal=typeof key==="string"&&(key.startsWith("_")||key.startsWith("__"));if(!isInternal&&!Object.prototype.hasOwnProperty.call(existingWrapper,key)){const childValue=nextWrapper[key];Object.defineProperty(existingWrapper,key,{value:childValue,writable:false,enumerable:true,configurable:true})}else if(!isInternal){const existingChild=existingWrapper[key];const nextChild=nextWrapper[key];if(this.isWrapperProxy(existingChild)&&this.isWrapperProxy(nextChild)){const syncWrapper_nextChildWrapper=resolveWrapper(nextChild)??nextChild;const syncWrapper_hasGrandChildren=Object.keys(syncWrapper_nextChildWrapper).some(k=>!k.startsWith("_")&&!k.startsWith("__"));if(syncWrapper_hasGrandChildren){await this.syncWrapper(existingChild,nextChild,config,collisionMode,moduleID)}}}}}else{for(const key of nextChildKeys){const childValue=nextWrapper[key];if(Object.prototype.hasOwnProperty.call(existingWrapper,key)){const existingChild=existingWrapper[key];if(this.isWrapperProxy(existingChild)&&this.isWrapperProxy(childValue)){const nextChildWrapper=resolveWrapper(childValue)??childValue;const hasGrandChildren=Object.keys(nextChildWrapper).some(k=>!k.startsWith("_")&&!k.startsWith("__"));if(hasGrandChildren){await this.syncWrapper(existingChild,childValue,config,collisionMode,moduleID)}else{delete existingWrapper[key];Object.defineProperty(existingWrapper,key,{value:childValue,writable:false,enumerable:true,configurable:true})}}else{delete existingWrapper[key];Object.defineProperty(existingWrapper,key,{value:childValue,writable:false,enumerable:true,configurable:true})}}else{Object.defineProperty(existingWrapper,key,{value:childValue,writable:false,enumerable:true,configurable:true})}}}if(existingWrapper.____slothletInternal.state){const isActuallyMaterialized=existingWrapper.____slothletInternal.impl&&typeof existingWrapper.____slothletInternal.impl!=="function";existingWrapper.____slothletInternal.state.materialized=isActuallyMaterialized;existingWrapper.____slothletInternal.state.inFlight=false}return true}_recordReplaceShadows(existingWrapper,existingChildKeys,nextChildKeys,moduleID){const ownership=this.slothlet.handlers.ownership;if(!ownership||!moduleID)return;const moduleIDKey=String(moduleID);const containerPath=existingWrapper.____slothletInternal.apiPath;const nextSet=new Set(nextChildKeys);for(const key of existingChildKeys){if(nextSet.has(key))continue;const owner=ownership.getCurrentOwner(`${containerPath}.${key}`);if(!owner)continue;if(String(owner.moduleID)===moduleIDKey)continue;const child=existingWrapper[key];if(!this.isWrapperProxy(child))continue;let list=this.state.replaceShadows.get(moduleIDKey);if(!list){list=[];this.state.replaceShadows.set(moduleIDKey,list)}list.push({container:existingWrapper,key,child,ownerModuleID:String(owner.moduleID)})}}async mutateApiValue(existingValue,nextValue,options,config){if(config?.debug?.api){this.slothlet.debug("api",{key:"DEBUG_MODE_MUTATE_API_VALUE_CALLED",existingType:typeof existingValue,nextType:typeof nextValue});this.slothlet.debug("api",{key:"DEBUG_MODE_MUTATE_API_VALUE_WRAPPER_STATUS",existingIsWrapper:this.isWrapperProxy(existingValue),nextIsWrapper:this.isWrapperProxy(nextValue)});this.slothlet.debug("api",{key:"DEBUG_MODE_MUTATE_API_VALUE_NEXT_VALUE",nextValue});this.slothlet.debug("api",{key:"DEBUG_MODE_MUTATE_API_VALUE_NEXT_VALUE_KEYS",nextValueKeys:nextValue?Object.keys(nextValue):[]})}if(existingValue===nextValue){return}if(this.isWrapperProxy(existingValue)&&this.isWrapperProxy(nextValue)){if(config?.debug?.api){this.slothlet.debug("api",{key:"DEBUG_MODE_MUTATE_API_VALUE_SYNC_WRAPPERS"})}await this.syncWrapper(existingValue,nextValue,config,options.collisionMode,options.moduleID);return}if(this.isWrapperProxy(existingValue)&&!this.isWrapperProxy(nextValue)){const nextIsObjectLike=nextValue&&(typeof nextValue==="object"||typeof nextValue==="function");const nextHasKeys=nextIsObjectLike&&Object.keys(nextValue).length>0;if(nextHasKeys){if(config?.debug?.api){this.slothlet.debug("api",{key:"DEBUG_MODE_MUTATE_API_VALUE_MERGE_INTO_WRAPPER"});this.slothlet.debug("api",{key:"DEBUG_MODE_MUTATE_API_VALUE_MERGE_KEYS",keys:Object.keys(nextValue)})}await this.slothlet.builders.apiAssignment.mergeApiObjects(existingValue,nextValue,{removeMissing:options.removeMissing,mutateExisting:true,allowOverwrite:true,syncWrapper:this.syncWrapper.bind(this),collisionMode:options.collisionMode,moduleID:options.moduleID});return}const existingValueRaw=resolveWrapper(existingValue);if(existingValueRaw!==null){if(config?.debug?.api){this.slothlet.debug("api",{key:"DEBUG_MODE_MUTATE_API_VALUE_SETIMPL_FALLBACK"})}existingValueRaw.___setImpl(resolveWrapper(nextValue)?.__impl??nextValue);return}}if(existingValue&&typeof existingValue==="object"&&nextValue&&typeof nextValue==="object"){await this.slothlet.builders.apiAssignment.mergeApiObjects(existingValue,nextValue,{removeMissing:options.removeMissing,mutateExisting:true,allowOverwrite:true,syncWrapper:this.syncWrapper.bind(this),collisionMode:options.collisionMode,moduleID:options.moduleID});return existingValue}return nextValue}async setValueAtPath(root,parts,value,options){const parent=this.ensureParentPath(root,parts,{moduleID:options.moduleID,sourceFolder:options.sourceFolder});const finalKey=parts[parts.length-1];const parentWrapper=resolveWrapper(parent);if(parentWrapper&&parentWrapper.____slothletInternal.mode==="lazy"&&!parentWrapper.____slothletInternal.state.materialized){await parentWrapper._materialize()}const existing=parent?parent[finalKey]:void 0;const collisionMode=options.collisionMode||"merge";const moduleID=options.moduleID;this.slothlet.debug("api",{key:"DEBUG_MODE_SET_VALUE_AT_PATH",finalKey,existingType:typeof existing,valueType:typeof value,collisionMode,options});if(existing!==void 0){if(collisionMode==="error"){throw new this.SlothletError("INVALID_CONFIG_API_PATH_INVALID",{apiPath:parts.join("."),reason:translate("API_PATH_REASON_COLLISION_ERROR"),index:void 0,segment:void 0,validationError:true})}if(collisionMode==="skip"){this.slothlet.debug("api",{key:"DEBUG_MODE_SET_VALUE_AT_PATH_SKIP_COLLISION",path:parts.join("."),mode:"skip"});return false}if(collisionMode==="warn"){if(this.slothlet&&!this.____config?.silent){new this.SlothletWarning("WARNING_HOT_RELOAD_PATH_COLLISION",{apiPath:parts.join(".")})}return false}if(collisionMode==="replace"){const existingIsObject=typeof existing==="object"||typeof existing==="function";const valueIsObject=typeof value==="object"||typeof value==="function";if(existingIsObject&&valueIsObject){this.slothlet.debug("api",{key:"DEBUG_MODE_SET_VALUE_AT_PATH_REPLACE_MERGE",path:parts.join("."),mode:"replace"});await this.mutateApiValue(existing,value,{removeMissing:false,allowOverwrite:true,collisionMode:"replace",moduleID},this.____config);return true}else{parent[finalKey]=value;return true}}if(collisionMode==="merge"||collisionMode==="merge-replace"){const existingIsObject=typeof existing==="object"||typeof existing==="function";const valueIsObject=typeof value==="object"||typeof value==="function";if(existingIsObject&&valueIsObject){this.slothlet.debug("api",{key:"DEBUG_MODE_SET_VALUE_AT_PATH_MERGE_PROPS",mode:collisionMode});await this.mutateApiValue(existing,value,{removeMissing:false,allowOverwrite:true,collisionMode},this.____config);return true}else{const apiPath=parts.join(".");if(this.slothlet&&!this.____config?.silent){new this.SlothletWarning("WARNING_HOT_RELOAD_MERGE_PRIMITIVES",{apiPath})}await this.emitImplDiagnostic("error",{apiPath,code:"WARNING_HOT_RELOAD_MERGE_PRIMITIVES",context:{apiPath},source:"addApi",moduleID,error:new this.SlothletError("WARNING_HOT_RELOAD_MERGE_PRIMITIVES",{apiPath})});return false}}}this.slothlet.debug("api",{key:"DEBUG_MODE_SET_VALUE_AT_PATH_ASSIGN",finalKey});parent[finalKey]=value;return true}async deletePath(root,parts){let current=root;const stack=[];for(const part of parts.slice(0,-1)){if(!current||typeof current!=="object"&&typeof current!=="function"){return false}stack.push({parent:current,key:part});current=current[part]}const finalKey=parts[parts.length-1];if(!current||typeof current!=="object"&&typeof current!=="function"){return false}if(!Object.prototype.hasOwnProperty.call(current,finalKey)){return false}const removedImpl=current[finalKey];const apiPath=parts.join(".");if(removedImpl&&this.slothlet.handlers?.lifecycle){const metadata=this.slothlet.handlers.metadata?.getMetadata?.(removedImpl);await this.slothlet.handlers.lifecycle.emit("impl:removed",{apiPath,impl:removedImpl,source:"removal",moduleID:metadata?.moduleID,filePath:metadata?.filePath,sourceFolder:metadata?.sourceFolder})}if(resolveWrapper(current)){const wrapper=resolveWrapper(current);const isInternal=typeof finalKey==="string"&&(finalKey.startsWith("_")||finalKey.startsWith("__"));if(!isInternal&&finalKey in wrapper){delete wrapper[finalKey]}if(wrapper.____slothletInternal.impl&&typeof wrapper.____slothletInternal.impl==="object"){delete wrapper.____slothletInternal.impl[finalKey]}}delete current[finalKey];if(removedImpl&&(typeof removedImpl==="object"||typeof removedImpl==="function")){if(resolveWrapper(removedImpl)){const wrapper=resolveWrapper(removedImpl);if(wrapper.____slothletInternal.impl!==void 0){wrapper.____slothletInternal.impl=null}const childKeys=Object.keys(wrapper).filter(k=>!k.startsWith("_")&&!k.startsWith("__"));for(const key of childKeys){delete wrapper[key]}if(wrapper.____slothletInternal.state){wrapper.____slothletInternal.state.materialized=false;wrapper.____slothletInternal.state.inFlight=false}}}if(this.slothlet.handlers?.metadata){const rootSegment=apiPath.split(".")[0];this.slothlet.handlers.metadata.removeUserMetadataByApiPath(rootSegment)}for(let i=stack.length-1;i>=0;i-=1){const{parent,key}=stack[i];const value=parent[key];if(value&&(typeof value==="object"||typeof value==="function")&&Object.keys(value).length===0){delete parent[key]}}return true}async restoreApiPath(apiPath,moduleID){const normalizedModuleId=moduleID||null;const historyEntry=this.state.addHistory.slice().reverse().find(entry=>entry.apiPath===apiPath&&(normalizedModuleId?entry.moduleID===normalizedModuleId:true));if(historyEntry){await this.addApiComponent({apiPath:historyEntry.apiPath,folderPath:historyEntry.folderPath,options:{...historyEntry.options,metadata:historyEntry.metadata,mutateExisting:true,forceOverwrite:true,collisionMode:"replace",recordHistory:false}});return}if(normalizedModuleId==="base"||normalizedModuleId==="core"){const baseApi=await this.slothlet.builders.builder.buildAPI({dir:this.____config.dir,mode:this.____config.mode,moduleID:"base"});const{parts}=this.normalizeApiPath(apiPath);let baseValue=this.getValueAtPath(baseApi,parts);if(baseValue===void 0){await this.deletePath(this.slothlet.api,parts);await this.deletePath(this.slothlet.boundApi,parts);return}const baseValueRaw=resolveWrapper(baseValue);if(baseValue&&baseValueRaw!==null){baseValue=baseValueRaw.__impl}await this.setValueAtPath(this.slothlet.api,parts,baseValue,{mutateExisting:true,allowOverwrite:true,collisionMode:"replace",moduleID:normalizedModuleId});await this.setValueAtPath(this.slothlet.boundApi,parts,baseValue,{mutateExisting:true,allowOverwrite:true,collisionMode:"replace",moduleID:normalizedModuleId})}}#normalizePermissionShorthandEntry(entry){const getValueType=value=>{if(value===null)return"null";if(Array.isArray(value))return"array";return typeof value};if(typeof entry==="string"){return{target:entry,condition:void 0}}if(!entry||typeof entry!=="object"||Array.isArray(entry)){throw new this.SlothletError("INVALID_PERMISSION_RULE",{reason:translate("PERM_RULE_NOT_OBJECT"),received:getValueType(entry),validationError:true})}if(typeof entry.target!=="string"||!entry.target){throw new this.SlothletError("INVALID_PERMISSION_RULE",{reason:translate("PERM_RULE_TARGET_REQUIRED"),received:typeof entry.target,validationError:true})}return{target:entry.target,condition:entry.condition}}async addApiComponent(params){const{apiPath,folderPath,options={},versionConfig=null}=params||{};if(Array.isArray(folderPath)){const moduleIDs=[];for(const singlePath of folderPath){const moduleID2=await this.addApiComponent({apiPath,folderPath:singlePath,options,versionConfig});moduleIDs.push(moduleID2)}return moduleIDs}let effectiveOptions=options;if(folderPath&&typeof folderPath==="object"&&!Array.isArray(folderPath)&&Object.prototype.hasOwnProperty.call(folderPath,"exports")){const siblingOptions={...folderPath};delete siblingOptions.exports;if(Object.keys(siblingOptions).length>0)effectiveOptions={...siblingOptions,...options}}const{metadata={},...restOptions}=effectiveOptions;if(!this.slothlet||!this.slothlet.isLoaded){throw new this.SlothletError("INVALID_CONFIG_NOT_LOADED",{operation:"addApi",validationError:true})}if(restOptions.moduleID&&String(restOptions.moduleID).includes(MODULE_ID_SEPARATOR)){throw new this.SlothletError("MODULE_ID_RESERVED_SEPARATOR",{moduleID:String(restOptions.moduleID),separator:MODULE_ID_SEPARATOR,validationError:true})}const{apiPath:normalizedPath,parts}=this.normalizeApiPath(apiPath);if(restOptions.moduleID&&normalizedPath.includes(MODULE_ID_SEPARATOR)){const segIndex=parts.findIndex(p=>p.includes(MODULE_ID_SEPARATOR));throw new this.SlothletError("INVALID_CONFIG_API_PATH_INVALID",{apiPath:normalizedPath,segment:parts[segIndex],index:segIndex,reason:translate("API_PATH_REASON_RESERVED_SEPARATOR"),validationError:true})}let effectivePath=normalizedPath;let effectiveParts=parts;if(versionConfig?.version!==void 0&&versionConfig?.version!==null){if(normalizedPath===""){throw new this.SlothletError("INVALID_CONFIG_API_PATH_INVALID",{apiPath,reason:translate("API_PATH_REASON_VERSIONED_ROOT"),index:void 0,segment:void 0,validationError:true})}if(typeof versionConfig.version!=="string"||!String(versionConfig.version).trim()){throw new this.SlothletError("INVALID_CONFIG_VERSION_TAG",{received:versionConfig.version,validationError:true})}const versionTag=String(versionConfig.version).trim();effectiveParts=[versionTag,...parts];effectivePath=effectiveParts.join(".")}const isSynthetic=typeof folderPath==="function"||folderPath!==null&&typeof folderPath==="object"&&!Array.isArray(folderPath);let syntheticExports=null;let resolvedPath,isDirectory,isFile;if(isSynthetic){const isPlainObject=value=>{if(value===null||typeof value!=="object")return false;const proto=Object.getPrototypeOf(value);return proto===Object.prototype||proto===null};const describeNonPlain=value=>value===null?"null":Array.isArray(value)?"array":typeof value==="object"?`${value.constructor?.name??"non-plain object"} instance`:typeof value;if(typeof folderPath==="function"){syntheticExports={default:folderPath}}else if(Object.prototype.hasOwnProperty.call(folderPath,"exports")){const inner=folderPath.exports;if(!isPlainObject(inner)){throw new this.SlothletError("INVALID_CONFIG_SYNTHETIC_EXPORTS_SHAPE",{received:describeNonPlain(inner),validationError:true})}syntheticExports=inner}else if(isPlainObject(folderPath)){syntheticExports=folderPath}else{throw new this.SlothletError("INVALID_CONFIG_SYNTHETIC_INPUT",{received:describeNonPlain(folderPath),validationError:true})}if(parts.length===0&&typeof syntheticExports.default==="function"){const def=syntheticExports.default;const{default:___default,...named}=syntheticExports;if(!def.name||def.name==="default"){if(this.slothlet&&!this.____config?.silent){new this.SlothletWarning("WARN_SYNTHETIC_ROOT_UNNAMED",{})}await this.emitImplDiagnostic("warning",{apiPath:normalizedPath,code:"WARN_SYNTHETIC_ROOT_UNNAMED",context:{},source:"addApi",moduleID:restOptions.moduleID});syntheticExports=named}else{if(Object.prototype.hasOwnProperty.call(named,def.name)){if(this.slothlet&&!this.____config?.silent){new this.SlothletWarning("WARN_SYNTHETIC_ROOT_COLLISION",{name:def.name})}await this.emitImplDiagnostic("warning",{apiPath:normalizedPath,code:"WARN_SYNTHETIC_ROOT_COLLISION",context:{name:def.name},source:"addApi",moduleID:restOptions.moduleID})}syntheticExports={[def.name]:def,...named}}}isFile=false;resolvedPath=`synthetic:${normalizedPath||"root"}`}else{({resolvedPath,isDirectory,isFile}=await this.resolvePath(folderPath));if(!isDirectory&&!isFile){throw new this.SlothletError("INVALID_CONFIG_PATH_TYPE",{path:resolvedPath,validationError:true})}if(isFile){const ext=path.extname(resolvedPath);if(![".mjs",".cjs",".js"].includes(ext)){throw new this.SlothletError("INVALID_CONFIG_FILE_TYPE",{path:resolvedPath,extension:ext,validationError:true})}}}const resolvedFolderPath=resolvedPath;let collisionMode;if(restOptions.forceOverwrite){collisionMode="replace"}else{collisionMode=restOptions.collisionMode||this.____config.api?.collision?.api||"error"}const mutateExisting=!!(restOptions.mutateExisting||collisionMode==="merge");const scanHiddenFolders=(restOptions.scanHiddenFolders??this.____config.scanHiddenFolders)===true;if(restOptions.scanHiddenFolders!==void 0&&!this.____config?.silent){new this.SlothletWarning("CONFIG_SCAN_HIDDEN_FOLDERS_DEPRECATED",{option:"scanHiddenFolders"})}const moduleID=restOptions.moduleID?String(restOptions.moduleID):this.buildDefaultModuleId(normalizedPath,resolvedFolderPath);if(moduleID.includes(MODULE_ID_SEPARATOR)){throw new this.SlothletError("MODULE_ID_RESERVED_SEPARATOR",{moduleID,separator:MODULE_ID_SEPARATOR,validationError:true})}if(restOptions.forceOverwrite&&!moduleID){throw new this.SlothletError("INVALID_CONFIG_FORCE_OVERWRITE_REQUIRES_MODULE_ID",{apiPath:normalizedPath,validationError:true})}let dirForBuild=resolvedFolderPath;let fileFilter=null;if(isFile){dirForBuild=path.dirname(resolvedFolderPath);const fileName=path.basename(resolvedFolderPath);fileFilter=file=>file===fileName}const newApi=await this.slothlet.builders.builder.buildAPI({dir:dirForBuild,mode:this.____config.mode,apiPathPrefix:effectivePath,collisionContext:"addApi",moduleID,collisionMode,fileFilter,rootUnwrap:isFile||isSynthetic,hidden:restOptions.hidden??null,scanHiddenFolders,...isSynthetic?{syntheticExports,syntheticName:parts.length?parts[parts.length-1]:"synthetic"}:{}});if(this.slothlet.handlers.apiCacheManager){this.slothlet.handlers.apiCacheManager.set(moduleID,{endpoint:effectivePath,moduleID,api:newApi,folderPath:resolvedFolderPath,syntheticExports:isSynthetic?syntheticExports:null,mode:this.____config.mode,sanitizeOptions:this.____config.sanitize||{},hidden:restOptions.hidden??null,scanHiddenFolders,collisionMode,config:{...this.____config},timestamp:Date.now()})}this.slothlet.debug("api",{key:"DEBUG_MODE_ADD_API_COMPONENT_BUILD_RETURN",topLevelKeys:Object.keys(newApi),dottedKeys:Object.keys(newApi).filter(k=>k.includes(".")),wrappers:Object.keys(newApi).filter(k=>resolveWrapper(newApi[k])!==null).map(k=>{const _w=resolveWrapper(newApi[k]);return{key:k,apiPath:_w.apiPath,implKeys:Object.keys(_w.____slothletInternal.impl||{}),childCacheSize:Object.keys(_w).filter(k2=>!k2.startsWith("_")&&!k2.startsWith("__")).length,childCacheKeys:Object.keys(_w).filter(k2=>!k2.startsWith("_")&&!k2.startsWith("__"))}}),nonWrappers:Object.keys(newApi).filter(k=>resolveWrapper(newApi[k])===null).map(k=>({key:k,type:typeof newApi[k]}))});let apiToMerge=newApi;if((isFile||isSynthetic)&&Object.keys(newApi).length===1){const fileName=Object.keys(newApi)[0];apiToMerge=newApi[fileName]}if(!isFile&&normalizedPath){const lastPart=normalizedPath.includes(".")?normalizedPath.split(".").pop():normalizedPath;if(lastPart&&Object.prototype.hasOwnProperty.call(apiToMerge,lastPart)){const dupValue=apiToMerge[lastPart];const dupType=typeof dupValue;if(dupValue!==null&&(dupType==="object"||dupType==="function")){const dupWrapper=resolveWrapper(dupValue);const dupFilePath=dupWrapper?.____slothletInternal?.filePath;const dupFileDir=dupFilePath?dupFilePath.replace(/\\/g,"/").split("/").slice(0,-1).join("/"):null;const normalizedFolderPath=resolvedFolderPath.replace(/\\/g,"/").replace(/\/$/,"");const expectedDir=normalizedFolderPath+"/"+lastPart;const isDirectChild=dupFileDir===expectedDir||dupFileDir===normalizedFolderPath;if(isDirectChild){const hoisted={};for(const k of Object.keys(apiToMerge)){if(k!==lastPart)hoisted[k]=apiToMerge[k]}if(dupWrapper){for(const k of Object.keys(dupWrapper).filter(k2=>!k2.startsWith("_")&&!k2.startsWith("__"))){hoisted[k]=dupWrapper[k]}}else{for(const k of Object.keys(dupValue)){hoisted[k]=dupValue[k]}}apiToMerge=hoisted;this.slothlet.debug("api",{key:"DEBUG_MODE_RULE_13_DEDUP_HOISTED_KEY",lastPart,newKeys:Object.keys(apiToMerge)})}}}}if(this.____config.debug?.api){this.slothlet.debug("api",{key:"DEBUG_MODE_ADD_API_COMPONENT_MERGE_KEYS",keys:Object.keys(apiToMerge),isRootLevel:parts.length===0})}let anyAssignmentSucceeded=false;let rootKeys=[];if(parts.length===0){const rootSource=isSynthetic?apiToMerge:newApi;rootKeys=Object.keys(rootSource);if(rootKeys.length===0&&isSynthetic){if(this.slothlet&&!this.____config?.silent){new this.SlothletWarning("WARN_SYNTHETIC_ROOT_EMPTY",{apiPath:normalizedPath||"(root)"})}await this.emitImplDiagnostic("warning",{apiPath:normalizedPath,code:"WARN_SYNTHETIC_ROOT_EMPTY",context:{apiPath:normalizedPath||"(root)"},source:"addApi",moduleID})}for(const key of rootKeys){const result1=await this.setValueAtPath(this.slothlet.api,[key],rootSource[key],{mutateExisting,collisionMode,moduleID,sourceFolder:resolvedFolderPath});const result2=await this.setValueAtPath(this.slothlet.boundApi,[key],rootSource[key],{mutateExisting,collisionMode,moduleID,sourceFolder:resolvedFolderPath});if(result1||result2){anyAssignmentSucceeded=true}}}else{if(resolveWrapper(apiToMerge)===null){const isCallableNamespace=typeof apiToMerge==="function";const containerWrapper=new UnifiedWrapper(this.slothlet,{apiPath:effectivePath,mode:this.____config.mode,isCallable:isCallableNamespace,moduleID,filePath:resolvedFolderPath,sourceFolder:resolvedFolderPath});containerWrapper.___setImpl(apiToMerge,moduleID);apiToMerge=containerWrapper.createProxy()}const result1=await this.setValueAtPath(this.slothlet.api,effectiveParts,apiToMerge,{mutateExisting,collisionMode,moduleID,sourceFolder:resolvedFolderPath});const result2=await this.setValueAtPath(this.slothlet.boundApi,effectiveParts,apiToMerge,{mutateExisting,collisionMode,moduleID,sourceFolder:resolvedFolderPath});if(result1||result2){anyAssignmentSucceeded=true}}if(anyAssignmentSucceeded){const pendingMaterializations=[];const seenWrappers=new Set;const collectPendingMaterializations=(obj,depth=0)=>{const objType=typeof obj;if(!obj||objType!=="object"&&objType!=="function"||depth>10)return;if(isFrameworkInternal(obj))return;const wrapper=resolveWrapper(obj);if(wrapper){if(seenWrappers.has(wrapper))return;seenWrappers.add(wrapper);if(wrapper.____slothletInternal.materializationPromise){pendingMaterializations.push(wrapper.____slothletInternal.materializationPromise)}const childKeys=Object.keys(wrapper).filter(k=>!k.startsWith("_")&&!k.startsWith("__"));for(const key of childKeys){collectPendingMaterializations(wrapper[key],depth+1)}return}for(const key of Object.keys(obj)){if(key!=="____slothletInternal"){collectPendingMaterializations(obj[key],depth+1)}}};if(effectiveParts.length===0){for(const key of rootKeys){if(this.slothlet.api[key]){collectPendingMaterializations(this.slothlet.api[key])}}}else{let current=this.slothlet.api;for(const part of effectiveParts){if(current&&current[part]){current=current[part]}else{break}}if(current){collectPendingMaterializations(current)}}if(pendingMaterializations.length>0){if(this.____config.debug?.api){this.slothlet.debug("api",{key:"DEBUG_MODE_AWAITING_PENDING_MATERIALIZATIONS",count:pendingMaterializations.length,apiPath:normalizedPath})}await Promise.all(pendingMaterializations)}}if(anyAssignmentSucceeded&&metadata&&Object.keys(metadata).length>0&&this.slothlet.handlers.metadata){if(parts.length===0){for(const key of Object.keys(newApi)){this.slothlet.handlers.metadata.registerUserMetadata(key,metadata)}}else{const rootSegment=effectiveParts[0];this.slothlet.handlers.metadata.registerUserMetadata(rootSegment,metadata)}}if(this.slothlet.handlers.ownership&&moduleID){this.slothlet.handlers.ownership.registerSubtree(apiToMerge,moduleID,effectivePath);this.slothlet.handlers.ownership.setModuleEndpoint(moduleID,effectivePath)}if(this.slothlet.handlers.ownership){if(restOptions.recordHistory!==false){const historyFolderPath=isSynthetic?folderPath:resolvedFolderPath;this.state.addHistory.push({apiPath:normalizedPath,folderPath:historyFolderPath,options:{...restOptions,metadata,moduleID},moduleID,versionConfig:versionConfig||null});this.state.operationHistory.push({type:"add",apiPath:normalizedPath,folderPath:historyFolderPath,options:{...restOptions,metadata,moduleID},moduleID,versionConfig:versionConfig||null})}}if(versionConfig?.version&&this.slothlet.handlers.versionManager){const versionTag=String(versionConfig.version).trim();try{this.slothlet.handlers.versionManager.registerVersion(normalizedPath,versionTag,moduleID,versionConfig.metadata??{},versionConfig.default??false)}catch(error){await this._rollbackFailedVersionedAdd({moduleID,effectivePath,normalizedPath});throw error}}if(restOptions.permissions&&this.slothlet.handlers?.permissionManager){const perms=restOptions.permissions;const callerPattern=`${normalizedPath}.**`;if(Array.isArray(perms.deny)){for(const entry of perms.deny){const{target,condition}=this.#normalizePermissionShorthandEntry(entry);this.slothlet.handlers.permissionManager.addRule({caller:callerPattern,target,effect:"deny",condition},moduleID)}}if(Array.isArray(perms.allow)){for(const entry of perms.allow){const{target,condition}=this.#normalizePermissionShorthandEntry(entry);this.slothlet.handlers.permissionManager.addRule({caller:callerPattern,target,effect:"allow",condition},moduleID)}}}return moduleID}async _rollbackFailedVersionedAdd({moduleID,effectivePath,normalizedPath}){let addIndex=-1;for(let i=this.state.operationHistory.length-1;i>=0;i--){const entry=this.state.operationHistory[i];if(entry?.type==="add"&&entry?.apiPath===normalizedPath&&entry?.moduleID===moduleID){addIndex=i;break}}if(addIndex!==-1){this.state.operationHistory.splice(addIndex,1)}this.state.addHistory=this.state.addHistory.filter(entry=>entry?.moduleID!==moduleID);try{await this.removeApiComponent(moduleID||effectivePath,{recordHistory:false})}catch{}}#sweepOrphanedCaches(){const cacheManager=this.slothlet.handlers?.apiCacheManager;if(!cacheManager)return;const root=this.slothlet.boundApi;for(const moduleID of cacheManager.getAllModuleIDs()){const entry=cacheManager.get(moduleID);if(!entry||entry.endpoint==="."||entry.endpoint==="")continue;const parts=String(entry.endpoint).split(".").filter(Boolean);if(this.getValueAtPath(root,parts)===void 0){cacheManager.delete(moduleID)}}}_hasForeignOwnedDescendant(apiPath,moduleIDKey){const ownership=this.slothlet.handlers.ownership;if(!ownership||!apiPath)return false;const prefix=apiPath+".";for(const p of ownership.pathToModule.keys()){if(!p.startsWith(prefix))continue;const owner=ownership.getCurrentOwner(p);if(owner&&owner.moduleID!==moduleIDKey)return true}return false}async removeApiComponent(pathOrModuleId,options={}){const recordHistory=options.recordHistory!==false;if(typeof pathOrModuleId!=="string"||!pathOrModuleId){throw new this.SlothletError("INVALID_ARGUMENT",{argument:"pathOrModuleId",expected:"non-empty string",received:typeof pathOrModuleId,validationError:true})}const scopedApiPath=typeof options.scopedApiPath==="string"?options.scopedApiPath:null;let apiPath=null;let moduleID;if(this.slothlet.handlers.ownership){const registeredModules=Array.from(this.slothlet.handlers.ownership.moduleToPath.keys());let matchingModule=null;const candidateModuleID=pathOrModuleId.split(MODULE_ID_SEPARATOR)[0];for(let i=registeredModules.length-1;i>=0;i--){const candidate=registeredModules[i];if(candidate===candidateModuleID||candidate.startsWith(`${candidateModuleID}_`)){matchingModule=candidate;break}}if(matchingModule){moduleID=matchingModule}else if(scopedApiPath!==null){return false}else{const owner=this.slothlet.handlers.ownership.getCurrentOwner(pathOrModuleId);if(owner){apiPath=pathOrModuleId;moduleID=owner.moduleID}else{return false}}}else{const isModuleId=!pathOrModuleId.includes(".");apiPath=isModuleId?null:pathOrModuleId;moduleID=isModuleId?pathOrModuleId.split(MODULE_ID_SEPARATOR)[0]:null}if(!this.slothlet||!this.slothlet.isLoaded){throw new this.SlothletError("INVALID_CONFIG_NOT_LOADED",{operation:"removeApi",validationError:true})}if(scopedApiPath!==null){const ownership=this.slothlet.handlers.ownership;const normalizedScoped=this.normalizeApiPath(scopedApiPath).apiPath;const ownedPaths=ownership?.moduleToPath?.get(moduleID);if(!ownedPaths||!ownedPaths.has(normalizedScoped)){return false}const scopedModuleIDKey=String(moduleID);const scopedPrefix=`${normalizedScoped}.`;const targets=[...ownedPaths].filter(p=>p===normalizedScoped||p.startsWith(scopedPrefix)).sort((a,b)=>b.length-a.length);const isFullRemoval=[...ownedPaths].every(p=>p===normalizedScoped||p.startsWith(scopedPrefix));if(isFullRemoval){ownership?.markUnregistered?.(scopedModuleIDKey)}for(const target of targets){const targetParts=this.normalizeApiPath(target).parts;const scopedResult=ownership.removePath(target,scopedModuleIDKey);if(scopedResult.action==="restore"){const revertValue=ownership.getCurrentValue?.(target);const revertOwner=ownership.getCurrentOwner?.(target)?.moduleID;if(revertValue!==void 0&&revertOwner){const revertOptions={mutateExisting:true,allowOverwrite:true,collisionMode:"replace",moduleID:revertOwner};await this.setValueAtPath(this.slothlet.api,targetParts,revertValue,revertOptions);await this.setValueAtPath(this.slothlet.boundApi,targetParts,revertValue,revertOptions)}else{await this.restoreApiPath(target,scopedResult.restoreModuleId)}}else{const stillHasChild=[...ownership.moduleToPath.values()].some(set=>{for(const owned of set)if(owned.startsWith(`${target}.`))return true;return false});if(!stillHasChild){await this.deletePath(this.slothlet.api,targetParts);await this.deletePath(this.slothlet.boundApi,targetParts)}}}this.#sweepOrphanedCaches();if(recordHistory){this.state.operationHistory.push({type:"remove",apiPath:normalizedScoped,scopedModuleID:scopedModuleIDKey})}return true}if(apiPath&&moduleID){const normalizedPath2=this.normalizeApiPath(apiPath).apiPath;const moduleIDKey=String(moduleID);const history=this.slothlet.handlers.ownership?.getPathHistory?.(normalizedPath2)||[];const ownershipResult2=this.slothlet.handlers.ownership?.removePath?.(normalizedPath2,moduleIDKey)||{action:"none",removedModuleId:null,restoreModuleId:null};const pathParts=this.normalizeApiPath(apiPath).parts;if(ownershipResult2.action==="delete"){await this.deletePath(this.slothlet.api,pathParts);await this.deletePath(this.slothlet.boundApi,pathParts);if(this.slothlet.handlers.metadata){const rootSegment=normalizedPath2.split(".")[0];this.slothlet.handlers.metadata.removeUserMetadataByApiPath(rootSegment)}if(this.slothlet.handlers.versionManager){const versionKey=this.slothlet.handlers.versionManager.getVersionKeyForModule(moduleIDKey);if(versionKey){this.slothlet.handlers.versionManager.unregisterVersion(versionKey.logicalPath,versionKey.versionTag)}if(this.slothlet.handlers.versionManager.hasDispatcher(normalizedPath2)){this.slothlet.handlers.versionManager.teardownDispatcher(normalizedPath2)}}this.#sweepOrphanedCaches();this.state.operationHistory.push({type:"remove",apiPath:normalizedPath2});return true}if(ownershipResult2.action==="restore"){const restoredValue=this.slothlet.handlers.ownership?.getCurrentValue?.(normalizedPath2);const restoredModuleId=this.slothlet.handlers.ownership?.getCurrentOwner?.(normalizedPath2)?.moduleID;if(restoredValue!==void 0&&restoredModuleId){await this.setValueAtPath(this.slothlet.api,pathParts,restoredValue,{mutateExisting:true,allowOverwrite:true,collisionMode:"replace",moduleID:restoredModuleId});await this.setValueAtPath(this.slothlet.boundApi,pathParts,restoredValue,{mutateExisting:true,allowOverwrite:true,collisionMode:"replace",moduleID:restoredModuleId});this.state.operationHistory.push({type:"remove",apiPath:normalizedPath2});return true}else{await this.restoreApiPath(normalizedPath2,ownershipResult2.restoreModuleId);this.state.operationHistory.push({type:"remove",apiPath:normalizedPath2});return true}}if(ownershipResult2.action==="none"&&history.length===0){await this.deletePath(this.slothlet.api,pathParts);await this.deletePath(this.slothlet.boundApi,pathParts);return true}return false}if(moduleID){const moduleIDKey=String(moduleID);const mountEndpoint=this.slothlet.handlers.ownership?.getModuleEndpoint?.(moduleIDKey);const isRootMount=!mountEndpoint||mountEndpoint===".";let mountRoot=isRootMount?"":mountEndpoint;const result=this.slothlet.handlers.ownership?.unregister?.(moduleIDKey)||{removed:[],rolledBack:[]};if(this.slothlet.handlers.versionManager){const versionKey=this.slothlet.handlers.versionManager.getVersionKeyForModule(moduleIDKey);if(versionKey){this.slothlet.handlers.versionManager.unregisterVersion(versionKey.logicalPath,versionKey.versionTag)}}const allPaths=[...result.removed,...result.rolledBack.map(r=>r.apiPath)];const uniquePaths=[...new Set(allPaths)];const pathsToDelete=[];const pathsToRollback=[];for(const path2 of uniquePaths){const currentOwner=this.slothlet.handlers.ownership?.getCurrentOwner?.(path2);const hasChildrenWithOtherOwners=isRootMount?this._hasForeignOwnedDescendant(path2,moduleIDKey):uniquePaths.some(p=>{if(p===path2||!p.startsWith(path2+"."))return false;const childOwner=this.slothlet.handlers.ownership?.getCurrentOwner?.(p);return childOwner&&childOwner.moduleID!==moduleIDKey});if(currentOwner&&currentOwner.moduleID!==moduleIDKey){pathsToRollback.push({apiPath:path2,restoredTo:currentOwner.moduleID})}else if(!hasChildrenWithOtherOwners){pathsToDelete.push(path2)}}pathsToDelete.sort((a,b)=>{const depthA=(a.match(/\./g)||[]).length;const depthB=(b.match(/\./g)||[]).length;return depthB-depthA});for(const removedPath of pathsToDelete){const{parts:parts2}=this.normalizeApiPath(removedPath);await this.deletePath(this.slothlet.api,parts2);await this.deletePath(this.slothlet.boundApi,parts2);if(this.slothlet.handlers.metadata){const rootSegment=removedPath.split(".")[0];this.slothlet.handlers.metadata.removeUserMetadataByApiPath(rootSegment)}}if(pathsToDelete.length>0){if(isRootMount){const segs=pathsToDelete.map(p=>p.split("."));const minLen=Math.min(...segs.map(s=>s.length));const common=[];for(let i=0;i<minLen;i++){const seg=segs[0][i];if(segs.every(s=>s[i]===seg))common.push(seg);else break}mountRoot=common.join(".")}const rootParts=this.normalizeApiPath(mountRoot).parts;const mountRootDot=mountRoot===""?null:`${mountRoot}.`;const hasRollbackSurvivor=pathsToRollback.some(r=>r.apiPath===mountRoot||mountRootDot!==null&&r.apiPath.startsWith(mountRootDot));if(!hasRollbackSurvivor&&(!isRootMount||!this._hasForeignOwnedDescendant(mountRoot,moduleIDKey))){await this.deletePath(this.slothlet.api,rootParts);await this.deletePath(this.slothlet.boundApi,rootParts)}}for(const rollback of pathsToRollback){const{parts:parts2}=this.normalizeApiPath(rollback.apiPath);const previousImpl=this.slothlet.handlers.ownership?.getCurrentValue?.(rollback.apiPath);if(previousImpl!==void 0){const existingWrapper=this.getValueAtPath(this.slothlet.api,parts2);const existingWrapperRaw=resolveWrapper(existingWrapper);if(existingWrapperRaw){existingWrapperRaw.___setImpl(previousImpl,rollback.restoredTo)}const existingBoundWrapper=this.getValueAtPath(this.slothlet.boundApi,parts2);const existingBoundWrapperRaw=resolveWrapper(existingBoundWrapper);if(existingBoundWrapperRaw){existingBoundWrapperRaw.___setImpl(previousImpl,rollback.restoredTo)}}}const shadows=this.state.replaceShadows.get(moduleIDKey);if(shadows){for(const shadow of shadows){if(Object.prototype.hasOwnProperty.call(shadow.container,shadow.key))continue;Object.defineProperty(shadow.container,shadow.key,{value:shadow.child,writable:false,enumerable:true,configurable:true})}this.state.replaceShadows.delete(moduleIDKey)}this.state.addHistory=this.state.addHistory.filter(entry=>String(entry.moduleID)!==moduleIDKey);if(this.slothlet.handlers.apiCacheManager){const deleted=this.slothlet.handlers.apiCacheManager.delete(moduleIDKey);if(deleted){this.slothlet.debug("cache",{key:"DEBUG_MODE_CACHE_DELETED_MODULE_REMOVED",moduleID:moduleIDKey})}}this.#sweepOrphanedCaches();if(recordHistory&&pathsToDelete.length>0){this.state.operationHistory.push({type:"remove",apiPath:mountRoot||pathsToDelete[0].split(".")[0]})}return pathsToDelete.length>0||pathsToRollback.length>0}if(!apiPath){throw new this.SlothletError("INVALID_CONFIG_API_PATH_INVALID",{apiPath,reason:translate("API_PATH_REASON_REQUIRED"),index:void 0,segment:void 0,validationError:true})}const{apiPath:normalizedPath,parts}=this.normalizeApiPath(apiPath);const ownershipResult=this.slothlet.handlers.ownership?.removePath?.(normalizedPath,null)||{action:"none",removedModuleId:null,restoreModuleId:null};const pathExists=this.getValueAtPath(this.slothlet.api,parts)!==void 0;if(ownershipResult.action==="none"){if(pathExists){await this.deletePath(this.slothlet.api,parts);await this.deletePath(this.slothlet.boundApi,parts);if(this.slothlet.handlers.metadata){this.slothlet.handlers.metadata.removeUserMetadataByApiPath(normalizedPath)}if(recordHistory){this.state.operationHistory.push({type:"remove",apiPath:normalizedPath})}return true}return false}if(ownershipResult.action==="delete"){await this.deletePath(this.slothlet.api,parts);await this.deletePath(this.slothlet.boundApi,parts);if(this.slothlet.handlers.metadata){this.slothlet.handlers.metadata.removeUserMetadataByApiPath(normalizedPath)}if(recordHistory){this.state.operationHistory.push({type:"remove",apiPath:normalizedPath})}return true}if(ownershipResult.action==="restore"){const restoredValue=this.slothlet.handlers.ownership?.getCurrentValue?.(normalizedPath);const restoredModuleId=this.slothlet.handlers.ownership?.getCurrentOwner?.(normalizedPath)?.moduleID;if(restoredValue!==void 0&&restoredModuleId){await this.setValueAtPath(this.slothlet.api,parts,restoredValue,{mutateExisting:true,allowOverwrite:true,collisionMode:"replace",moduleID:restoredModuleId});await this.setValueAtPath(this.slothlet.boundApi,parts,restoredValue,{mutateExisting:true,allowOverwrite:true,collisionMode:"replace",moduleID:restoredModuleId});if(recordHistory){this.state.operationHistory.push({type:"remove",apiPath:normalizedPath})}return true}await this.restoreApiPath(normalizedPath,ownershipResult.restoreModuleId);if(recordHistory){this.state.operationHistory.push({type:"remove",apiPath:normalizedPath})}return true}return false}async reloadApiComponent(params){const{apiPath,moduleID,options}=params||{};if(!this.slothlet||!this.slothlet.isLoaded){throw new this.SlothletError("INVALID_CONFIG_NOT_LOADED",{operation:"reloadApi",validationError:true})}if(moduleID){await this._reloadByModuleID(moduleID);return}if(apiPath){await this._reloadByApiPath(apiPath,options);return}throw new this.SlothletError("INVALID_ARGUMENT",{argument:"params",expected:"{ moduleID } or { apiPath }",received:params,validationError:true})}async _reloadByModuleID(moduleID,{forceReplace=true}={}){const cacheManager=this.slothlet.handlers.apiCacheManager;if(!cacheManager){throw new this.SlothletError("CACHE_MANAGER_NOT_AVAILABLE",{operation:"reload",validationError:true})}if(!cacheManager.has(moduleID)){throw new this.SlothletError("CACHE_NOT_FOUND",{moduleID,operation:"reload",validationError:true})}const oldEntry=cacheManager.get(moduleID);this.slothlet.debug("reload",{key:"DEBUG_MODE_RELOADING_MODULE_BY_ID",moduleID,endpoint:oldEntry.endpoint,folderPath:oldEntry.folderPath});const freshApi=await cacheManager.rebuildCache(moduleID);cacheManager.set(moduleID,{...oldEntry,api:freshApi,timestamp:Date.now()});this.slothlet.debug("reload",{key:"DEBUG_MODE_FRESH_API_KEYS_BEFORE_RESTORE",moduleID,endpoint:oldEntry.endpoint,freshApiKeys:Object.keys(freshApi||{})});await this._restoreApiTree(freshApi,oldEntry.endpoint,moduleID,oldEntry.collisionMode,forceReplace);this.slothlet.debug("reload",{key:"DEBUG_MODE_FRESH_API_KEYS_AFTER_RESTORE",moduleID,endpoint:oldEntry.endpoint,freshApiKeys:Object.keys(freshApi||{})});this.slothlet.debug("reload",{key:"DEBUG_MODE_MODULE_RELOAD_COMPLETE",moduleID});if(this.slothlet.handlers.versionManager){this.slothlet.handlers.versionManager.onVersionedModuleReload(moduleID)}}async _reloadByApiPath(apiPath,options={}){this.slothlet.debug("reload",{key:"DEBUG_MODE_RELOADING_BY_API_PATH",apiPath});const moduleIDsToReload=this._findAffectedCaches(apiPath);if(moduleIDsToReload.length===0){this.slothlet.debug("reload",{key:"DEBUG_MODE_NO_CACHES_ATTEMPTING_RESTORE",apiPath});if(apiPath!=="."&&apiPath!==""){await this.restoreApiPath(apiPath,"base")}return}const cacheManager=this.slothlet.handlers.apiCacheManager;moduleIDsToReload.sort((a,b)=>{const entryA=cacheManager.get(a);const entryB=cacheManager.get(b);if(entryA?.endpoint==="."&&entryB?.endpoint!==".")return-1;if(entryB?.endpoint==="."&&entryA?.endpoint!==".")return 1;const indexA=this.state.addHistory.findIndex(h=>h.moduleID===a);const indexB=this.state.addHistory.findIndex(h=>h.moduleID===b);return indexA-indexB});const endpointOrder=new Map;for(const moduleID of moduleIDsToReload){const entry=cacheManager.get(moduleID);const ep=entry?.endpoint??".";if(!endpointOrder.has(ep))endpointOrder.set(ep,[]);endpointOrder.get(ep).push(moduleID)}for(const[,moduleIDs]of endpointOrder){for(let i=0;i<moduleIDs.length;i++){await this._reloadByModuleID(moduleIDs[i],{forceReplace:i===0})}}const reloadMetadata=options?.metadata;if(reloadMetadata&&typeof reloadMetadata==="object"&&Object.keys(reloadMetadata).length>0){if(this.slothlet.handlers.metadata){const targetPath=apiPath==="."?null:apiPath.split(".")[0];if(targetPath){this.slothlet.handlers.metadata.registerUserMetadata(targetPath,reloadMetadata)}}}this.slothlet.debug("reload",{key:"DEBUG_MODE_API_PATH_RELOAD_COMPLETE",apiPath,reloadedModules:moduleIDsToReload.length,loadOrder:moduleIDsToReload})}_findAffectedCaches(apiPath){const cacheManager=this.slothlet.handlers.apiCacheManager;if(!cacheManager)return[];const allModuleIDs=cacheManager.getAllModuleIDs();if(apiPath==="."||apiPath===""||apiPath==null){const baseModules=[];for(const moduleID of allModuleIDs){const entry=cacheManager.get(moduleID);if(entry&&entry.endpoint==="."){baseModules.push(moduleID)}}return baseModules}const exactMatches=[];for(const moduleID of allModuleIDs){const entry=cacheManager.get(moduleID);if(entry&&entry.endpoint===apiPath){exactMatches.push(moduleID)}}if(exactMatches.length>0)return exactMatches;const children=[];const pathPrefix=apiPath+".";for(const moduleID of allModuleIDs){const entry=cacheManager.get(moduleID);if(entry?.endpoint?.startsWith(pathPrefix)){children.push(moduleID)}}if(children.length>0)return children;const ownership=this.slothlet.handlers.ownership;const history=ownership?.getPathHistory?.(apiPath);if(history&&history.length>0){const owned=[];for(const{moduleID}of history){if(cacheManager.has(moduleID)){owned.push(moduleID)}}if(owned.length>0)return owned}let bestMatch=null;let bestLength=-1;for(const moduleID of allModuleIDs){const entry=cacheManager.get(moduleID);if(!entry?.endpoint)continue;const ep=entry.endpoint;if(ep==="."||apiPath.startsWith(ep+".")){if(ep.length>bestLength){bestLength=ep.length;bestMatch=moduleID}}}if(bestMatch)return[bestMatch];return[]}_collectCustomProperties(existingProxy,freshApi){const customProps={};if(!existingProxy||typeof existingProxy!=="object"&&typeof existingProxy!=="function"){return customProps}const wrapper=resolveWrapper(existingProxy);if(!wrapper){return customProps}const freshKeys=new Set(freshApi?Object.keys(freshApi):[]);const ownKeys=Object.keys(wrapper).filter(k=>!ComponentBase.INTERNAL_KEYS.has(k));for(const key of ownKeys){try{const val=wrapper[key];if(val&&(typeof val==="object"||typeof val==="function")&&resolveWrapper(val)){continue}if(!freshKeys.has(key)){customProps[key]=val}else{customProps[key]=val}}catch{}}return customProps}_restoreCustomProperties(proxy,customProps){if(!proxy||!customProps||typeof customProps!=="object"){return}for(const[key,value]of Object.entries(customProps)){try{proxy[key]=value}catch{}}}async _restoreApiTree(freshApi,endpoint,moduleID,collisionMode,forceReplace=true){if(!freshApi||typeof freshApi!=="object"&&typeof freshApi!=="function"){return}const parts=endpoint==="."?[]:endpoint.split(".");if(parts.length===0){for(const key of Object.keys(freshApi)){if(typeof key==="string"&&(key.startsWith("_")||key.startsWith("__")))continue;if(key==="slothlet"||key==="shutdown"||key==="destroy")continue;const existingAtKey=this.slothlet.api[key];const freshValue=freshApi[key];if(existingAtKey&&resolveWrapper(existingAtKey)!==null){const customProps=this._collectCustomProperties(existingAtKey,freshValue);const freshWrapper=resolveWrapper(freshValue);const isLazyFresh=freshWrapper&&freshWrapper.____slothletInternal.mode==="lazy"&&!freshWrapper.____slothletInternal.state.materialized&&typeof freshWrapper.____slothletInternal.materializeFunc==="function";this.slothlet.debug("reload",{key:"DEBUG_MODE_RESTORE_ROOT_KEY_INSPECT",rootKey:key,hasFreshWrapper:!!freshWrapper,freshMode:freshWrapper?.____slothletInternal.mode,freshMaterialized:freshWrapper?.____slothletInternal.state?.materialized,hasMaterializeFunc:typeof freshWrapper?.____slothletInternal.materializeFunc==="function",isLazyFresh,existingMaterialized:resolveWrapper(existingAtKey)?.____slothletInternal?.state?.materialized});if(isLazyFresh){resolveWrapper(existingAtKey).___resetLazy(freshWrapper.____slothletInternal.materializeFunc);this._restoreCustomProperties(existingAtKey,customProps);this.slothlet.debug("reload",{key:"DEBUG_MODE_ROOT_KEY_RESET_LAZY",rootKey:key,restoredCustomProps:Object.keys(customProps)})}else{let implForReload;if(freshValue&&resolveWrapper(freshValue)!==null){implForReload=freshWrapper?UnifiedWrapper._extractFullImpl(freshWrapper):freshValue}else{implForReload=freshValue}resolveWrapper(existingAtKey).___setImpl(implForReload,moduleID);this._restoreCustomProperties(existingAtKey,customProps);this.slothlet.debug("reload",{key:"DEBUG_MODE_ROOT_KEY_UPDATED_SETIMPL",rootKey:key,restoredCustomProps:Object.keys(customProps)})}}else if(existingAtKey===void 0){const cacheManager=this.slothlet.handlers.apiCacheManager;const cacheEntry=cacheManager.get(moduleID);const resolvedFolderPath=cacheEntry?.folderPath||"";await this.setValueAtPath(this.slothlet.api,[key],freshValue,{mutateExisting:true,collisionMode,moduleID,sourceFolder:resolvedFolderPath});if(this.slothlet.boundApi){await this.setValueAtPath(this.slothlet.boundApi,[key],freshValue,{mutateExisting:true,collisionMode,moduleID,sourceFolder:resolvedFolderPath})}}}}else{const existing=this.getValueAtPath(this.slothlet.api,parts);this.slothlet.debug("reload",{key:"DEBUG_MODE_RESTORE_NESTED_PATH",endpoint,moduleID,partsPath:parts.join("."),existingFound:!!existing,hasSetImpl:existing?resolveWrapper(existing)!==null:false,freshApiKeys:Object.keys(freshApi)});if(existing&&resolveWrapper(existing)!==null){const customProps=this._collectCustomProperties(existing,freshApi);const wrapper=resolveWrapper(existing);const originalCollisionMode=wrapper?wrapper.____slothletInternal.state.collisionMode:null;if(forceReplace&&wrapper){wrapper.____slothletInternal.state.collisionMode="replace";this.slothlet.debug("reload",{key:"DEBUG_MODE_RESTORE_FORCING_REPLACE",endpoint,originalCollisionMode,wrapperApiPath:wrapper.____slothletInternal.apiPath})}let implForReload;if(resolveWrapper(freshApi)!==null){const freshWrapper=resolveWrapper(freshApi);implForReload=freshWrapper?UnifiedWrapper._extractFullImpl(freshWrapper):freshApi}else{implForReload=freshApi}if(parts.length>0&&implForReload&&typeof implForReload==="object"){const lastEndpointPart=parts[parts.length-1];if(lastEndpointPart&&Object.prototype.hasOwnProperty.call(implForReload,lastEndpointPart)){const dupValue=implForReload[lastEndpointPart];const dupWrapperForDedup=resolveWrapper(dupValue);if(dupWrapperForDedup){const hoisted={};for(const k of Object.keys(implForReload)){if(k!==lastEndpointPart)hoisted[k]=implForReload[k]}for(const k of Object.keys(dupWrapperForDedup).filter(k2=>!k2.startsWith("_")&&!k2.startsWith("__"))){hoisted[k]=dupWrapperForDedup[k]}implForReload=hoisted}}}if(implForReload&&typeof implForReload==="object"){for(const key of Object.keys(implForReload)){const val=implForReload[key];if(resolveWrapper(val)!==null){const childWrapper=resolveWrapper(val);if(childWrapper.____slothletInternal.state.materialized){implForReload[key]=UnifiedWrapper._extractFullImpl(childWrapper)}}}}resolveWrapper(existing).___setImpl(implForReload,moduleID);if(wrapper&&originalCollisionMode!==null){wrapper.____slothletInternal.state.collisionMode=originalCollisionMode}this._restoreCustomProperties(existing,customProps);this.slothlet.debug("reload",{key:"DEBUG_MODE_UPDATED_WRAPPER_IMPL",endpoint,moduleID,forcedReplaceMode:true,restoredCustomProps:Object.keys(customProps)})}else{const cacheManager=this.slothlet.handlers.apiCacheManager;const cacheEntry=cacheManager.get(moduleID);const resolvedFolderPath=cacheEntry?.folderPath||"";let implForContainer=freshApi;if(typeof freshApi==="function"){implForContainer={};for(const key of Object.keys(freshApi)){implForContainer[key]=freshApi[key]}}const containerWrapper=new UnifiedWrapper(this.slothlet,{apiPath:endpoint,mode:this.____config.mode,moduleID,filePath:resolvedFolderPath,sourceFolder:resolvedFolderPath});containerWrapper.___setImpl(implForContainer,moduleID);const apiToSet=containerWrapper.createProxy();await this.setValueAtPath(this.slothlet.api,parts,apiToSet,{mutateExisting:true,collisionMode,moduleID,sourceFolder:resolvedFolderPath});if(this.slothlet.boundApi){await this.setValueAtPath(this.slothlet.boundApi,parts,apiToSet,{mutateExisting:true,collisionMode,moduleID,sourceFolder:resolvedFolderPath})}this.slothlet.debug("reload",{key:"DEBUG_MODE_CREATED_NEW_WRAPPER_UNEXPECTED",endpoint,moduleID})}}}}export{ApiManager};
17
+ import{translate}from"@cldmv/slothlet/i18n";import{ComponentBase}from"#factories/component-base";import{UnifiedWrapper,resolveWrapper}from"#handlers/unified-wrapper";import{isFrameworkInternal}from"#handlers/framework-internals";import{MODULE_ID_SEPARATOR}from"#handlers/metadata";import{fsp,path}from"@cldmv/slothlet/helpers/platform";const UNSAFE_PATH_SEGMENTS=new Set(["__proto__","constructor","prototype"]);class ApiManager extends ComponentBase{static slothletProperty="apiManager";constructor(slothlet){super(slothlet);this.state={addHistory:[],initialConfig:slothlet?.config||null,operationHistory:[],replaceShadows:new Map}}normalizeApiPath(apiPath){if(apiPath===""||apiPath===null||apiPath===void 0){return{apiPath:"",parts:[]}}if(Array.isArray(apiPath)){if(apiPath.length===0){return{apiPath:"",parts:[]}}for(let i=0;i<apiPath.length;i++){if(typeof apiPath[i]!=="string"){throw new this.SlothletError("INVALID_CONFIG_API_PATH_INVALID",{apiPath,segment:apiPath[i],index:i,reason:translate("API_PATH_REASON_ARRAY_ELEMENTS"),validationError:true})}if(apiPath[i].trim()===""){throw new this.SlothletError("INVALID_CONFIG_API_PATH_INVALID",{apiPath,segment:apiPath[i],index:i,reason:translate("API_PATH_REASON_ARRAY_EMPTY_SEGMENTS"),validationError:true})}}if(apiPath[0]==="slothlet"||apiPath.length===1&&(apiPath[0]==="shutdown"||apiPath[0]==="destroy")){throw new this.SlothletError("INVALID_CONFIG_API_PATH_INVALID",{apiPath,reason:translate("API_PATH_REASON_RESERVED_NAME"),index:void 0,segment:void 0,validationError:true})}const unsafeArrayIndex=apiPath.findIndex(segment=>UNSAFE_PATH_SEGMENTS.has(segment));if(unsafeArrayIndex!==-1){throw new this.SlothletError("INVALID_CONFIG_API_PATH_INVALID",{apiPath,reason:translate("API_PATH_REASON_UNSAFE_SEGMENT"),index:unsafeArrayIndex,segment:apiPath[unsafeArrayIndex],validationError:true})}return{apiPath:apiPath.join("."),parts:apiPath}}if(typeof apiPath!=="string"){throw new this.SlothletError("INVALID_CONFIG_API_PATH_INVALID",{apiPath,reason:translate("API_PATH_REASON_INVALID_TYPE"),index:void 0,segment:void 0,validationError:true})}const normalized=apiPath.trim();if(normalized===""){return{apiPath:"",parts:[]}}const parts=normalized.split(".");if(parts.length===0||parts.some(part=>part.trim()==="")){throw new this.SlothletError("INVALID_CONFIG_API_PATH_INVALID",{apiPath:normalized,reason:translate("API_PATH_REASON_EMPTY_SEGMENTS"),index:void 0,segment:void 0,validationError:true})}if(parts[0]==="slothlet"||normalized==="shutdown"||normalized==="destroy"){throw new this.SlothletError("INVALID_CONFIG_API_PATH_INVALID",{apiPath:normalized,reason:translate("API_PATH_REASON_RESERVED_NAME"),index:void 0,segment:void 0,validationError:true})}const unsafeIndex=parts.findIndex(segment=>UNSAFE_PATH_SEGMENTS.has(segment));if(unsafeIndex!==-1){throw new this.SlothletError("INVALID_CONFIG_API_PATH_INVALID",{apiPath:normalized,reason:translate("API_PATH_REASON_UNSAFE_SEGMENT"),index:unsafeIndex,segment:parts[unsafeIndex],validationError:true})}return{apiPath:normalized,parts}}async resolvePath(inputPath){if(!inputPath||typeof inputPath!=="string"){throw new this.SlothletError("INVALID_CONFIG_DIR_INVALID",{dir:inputPath,validationError:true})}const resolvedPath=this.slothlet.helpers.resolver.resolvePathFromCaller(inputPath);if(this.slothlet.envTarget==="browser"){const lastSegment=resolvedPath.split("/").pop();const isFile=lastSegment.includes(".");return{resolvedPath,isDirectory:!isFile,isFile}}try{const stats=await fsp.stat(resolvedPath);return{resolvedPath,isDirectory:stats.isDirectory(),isFile:stats.isFile()}}catch(error){if(error instanceof this.SlothletError){throw error}throw new this.SlothletError("INVALID_CONFIG_DIR_INVALID",{dir:resolvedPath,validationError:true})}}async resolveFolderPath(folderPath){if(!folderPath||typeof folderPath!=="string"){throw new this.SlothletError("INVALID_CONFIG_DIR_INVALID",{dir:folderPath,validationError:true})}const resolvedPath=this.slothlet.helpers.resolver.resolvePathFromCaller(folderPath);try{const stats=await fsp.stat(resolvedPath);if(!stats.isDirectory()){throw new this.SlothletError("INVALID_CONFIG_DIR_INVALID",{dir:resolvedPath,validationError:true})}}catch(error){if(error instanceof this.SlothletError){throw error}throw new this.SlothletError("INVALID_CONFIG_DIR_INVALID",{dir:resolvedPath,validationError:true})}return resolvedPath}buildDefaultModuleId(apiPath,____resolvedFolderPath){const randomSuffix=Math.random().toString(36).substring(2,8);const prefix=apiPath||"auto";return`${prefix}_${randomSuffix}`}getValueAtPath(root,parts){let current=root;for(const part of parts){if(!current||typeof current!=="object"&&typeof current!=="function"){return void 0}current=current[part]}return current}ensureParentPath(root,parts,options={}){const{moduleID,sourceFolder}=options;let current=root;for(let i=0;i<parts.length-1;i+=1){const part=parts[i];const next=current[part];if(next===void 0){const containerPath=parts.slice(0,i+1).join(".");const containerWrapper=new UnifiedWrapper(this.slothlet,{mode:this.____config.mode,apiPath:containerPath,moduleID,sourceFolder});containerWrapper.___setImpl({},moduleID);current[part]=containerWrapper.createProxy();current=current[part];continue}if(next&&(typeof next==="object"||typeof next==="function")){current=next;continue}throw new this.SlothletError("INVALID_CONFIG_API_PATH_INVALID",{apiPath:parts.slice(0,i+1).join("."),reason:translate("API_PATH_REASON_NOT_TRAVERSABLE"),index:void 0,segment:void 0,validationError:true})}return current}setOwnedProperty(apiPath,value,callerWrapper){const coercedPath=String(apiPath);for(const segment of coercedPath.split(".")){if(UNSAFE_PATH_SEGMENTS.has(segment)){throw new this.SlothletError("LOOSE_SET_RESERVED_KEY",{apiPath:coercedPath,segment,validationError:true})}}const{parts}=this.normalizeApiPath(apiPath);if(parts.length===0){throw new this.SlothletError("INVALID_CONFIG_API_PATH_INVALID",{apiPath:String(apiPath??""),reason:translate("API_PATH_REASON_EMPTY_SEGMENTS"),index:void 0,segment:void 0,validationError:true})}const callerModuleID=callerWrapper?.____slothletInternal?.moduleID??null;const callerWrapperPath=callerWrapper?.____slothletInternal?.apiPath??null;let ownedRoot=null;if(callerModuleID&&this.slothlet.handlers?.ownership?.getModuleEndpoint){const endpoint=this.slothlet.handlers.ownership.getModuleEndpoint(callerModuleID);if(endpoint!=null){ownedRoot=endpoint}}if(ownedRoot===null)ownedRoot=".";if(ownedRoot&&ownedRoot!=="."&&ownedRoot!==""){const ownedParts=String(ownedRoot).split(".").filter(Boolean);const isUnderOwn=ownedParts.length<=parts.length&&ownedParts.every((seg,i)=>parts[i]===seg);if(!isUnderOwn){const callerApiPath=callerWrapperPath??ownedRoot;throw new this.SlothletError("LOOSE_SET_NOT_OWNED",{apiPath:parts.join("."),callerApiPath,validationError:true})}}const callerSourceFolder=callerWrapper?.____slothletInternal?.sourceFolder??null;const root=this.slothlet.boundApi;const parent=this.ensureParentPath(root,parts,{moduleID:callerModuleID,sourceFolder:callerSourceFolder});const finalKey=parts[parts.length-1];const isWrappable=typeof value==="function"||value!==null&&typeof value==="object";if(isWrappable){const wrapper=new UnifiedWrapper(this.slothlet,{mode:this.____config.mode,apiPath:parts.join("."),moduleID:callerModuleID,isCallable:typeof value==="function",sourceFolder:callerSourceFolder});wrapper.___setImpl(value,callerModuleID);parent[finalKey]=wrapper.createProxy()}else{parent[finalKey]=value}}isWrapperProxy(value){return!!(value&&(typeof value==="object"||typeof value==="function")&&resolveWrapper(value)!==null)}async syncWrapper(existingProxy,nextProxy,config,collisionMode="replace",moduleID=null){if(config?.debug?.api){this.slothlet.debug("api",{key:"DEBUG_MODE_SYNC_WRAPPER_ENTRY_EXISTING",apiPath:resolveWrapper(existingProxy)?.apiPath});this.slothlet.debug("api",{key:"DEBUG_MODE_SYNC_WRAPPER_ENTRY_NEXT",apiPath:resolveWrapper(nextProxy)?.apiPath})}if(!this.isWrapperProxy(existingProxy)||!this.isWrapperProxy(nextProxy)){return false}const existingWrapper=resolveWrapper(existingProxy)??existingProxy;const nextWrapper=resolveWrapper(nextProxy)??nextProxy;if(config?.debug?.api){this.slothlet.debug("api",{key:"DEBUG_MODE_SYNC_WRAPPER_EXISTING",apiPath:existingWrapper.apiPath});this.slothlet.debug("api",{key:"DEBUG_MODE_SYNC_WRAPPER_NEXT",apiPath:nextWrapper.apiPath})}if(nextWrapper.____slothletInternal.materializeFunc&&collisionMode!=="merge"){existingWrapper.____slothletInternal.materializeFunc=nextWrapper.____slothletInternal.materializeFunc}const existingChildKeys=Object.keys(existingWrapper).filter(k=>!k.startsWith("_")&&!k.startsWith("__"));const nextChildKeys=Object.keys(nextWrapper).filter(k=>!k.startsWith("_")&&!k.startsWith("__"));const userAssignedKeys=new Set;for(const k of existingChildKeys){const w=resolveWrapper(existingWrapper[k]);if(w?.____slothletInternal?.userAssigned)userAssignedKeys.add(k)}if(config?.debug?.api){this.slothlet.debug("api",{key:"DEBUG_MODE_SYNC_WRAPPER_BEFORE_MERGE",existingCacheSize:existingChildKeys.length,nextCacheSize:nextChildKeys.length});this.slothlet.debug("api",{key:"DEBUG_MODE_SYNC_WRAPPER_NEXT_IMPL_KEYS",implKeys:Object.keys(nextWrapper.____slothletInternal.impl||{})});this.slothlet.debug("api",{key:"DEBUG_MODE_SYNC_WRAPPER_NEXT_CHILDCACHE_KEYS",childCacheKeys:nextChildKeys})}if(collisionMode==="replace"){this._recordReplaceShadows(existingWrapper,existingChildKeys,nextChildKeys,moduleID);if(existingWrapper.___setImpl&&nextWrapper.____slothletInternal.impl!==void 0){existingWrapper.___setImpl(nextWrapper.____slothletInternal.impl,moduleID)}else if(nextWrapper.____slothletInternal.impl===void 0){existingWrapper.____slothletInternal.impl=null}else{if(nextWrapper.____slothletInternal.impl!==void 0){existingWrapper.____slothletInternal.impl=nextWrapper.____slothletInternal.impl;if(typeof nextWrapper.____slothletInternal.impl==="function"||nextWrapper.____slothletInternal.impl&&typeof nextWrapper.____slothletInternal.impl.default==="function"){existingWrapper.isCallable=true}}}for(const key of existingChildKeys){if(userAssignedKeys.has(key))continue;delete existingWrapper[key]}existingWrapper.___adoptImplChildren();for(const key of nextChildKeys){if(userAssignedKeys.has(key))continue;const childValue=nextWrapper[key];Object.defineProperty(existingWrapper,key,{value:childValue,writable:false,enumerable:true,configurable:true})}}else if(collisionMode==="merge"){for(const key of nextChildKeys){const isInternal=typeof key==="string"&&(key.startsWith("_")||key.startsWith("__"));if(!isInternal&&!Object.prototype.hasOwnProperty.call(existingWrapper,key)){const childValue=nextWrapper[key];Object.defineProperty(existingWrapper,key,{value:childValue,writable:false,enumerable:true,configurable:true})}else if(!isInternal){const existingChild=existingWrapper[key];const nextChild=nextWrapper[key];if(this.isWrapperProxy(existingChild)&&this.isWrapperProxy(nextChild)){const syncWrapper_nextChildWrapper=resolveWrapper(nextChild)??nextChild;const syncWrapper_hasGrandChildren=Object.keys(syncWrapper_nextChildWrapper).some(k=>!k.startsWith("_")&&!k.startsWith("__"));if(syncWrapper_hasGrandChildren){await this.syncWrapper(existingChild,nextChild,config,collisionMode,moduleID)}}}}}else{for(const key of nextChildKeys){const childValue=nextWrapper[key];if(Object.prototype.hasOwnProperty.call(existingWrapper,key)){const existingChild=existingWrapper[key];if(this.isWrapperProxy(existingChild)&&this.isWrapperProxy(childValue)){const nextChildWrapper=resolveWrapper(childValue)??childValue;const hasGrandChildren=Object.keys(nextChildWrapper).some(k=>!k.startsWith("_")&&!k.startsWith("__"));if(hasGrandChildren){await this.syncWrapper(existingChild,childValue,config,collisionMode,moduleID)}else{delete existingWrapper[key];Object.defineProperty(existingWrapper,key,{value:childValue,writable:false,enumerable:true,configurable:true})}}else{delete existingWrapper[key];Object.defineProperty(existingWrapper,key,{value:childValue,writable:false,enumerable:true,configurable:true})}}else{Object.defineProperty(existingWrapper,key,{value:childValue,writable:false,enumerable:true,configurable:true})}}}if(existingWrapper.____slothletInternal.state){const isActuallyMaterialized=existingWrapper.____slothletInternal.impl&&typeof existingWrapper.____slothletInternal.impl!=="function";existingWrapper.____slothletInternal.state.materialized=isActuallyMaterialized;existingWrapper.____slothletInternal.state.inFlight=false}return true}_recordReplaceShadows(existingWrapper,existingChildKeys,nextChildKeys,moduleID){const ownership=this.slothlet.handlers.ownership;if(!ownership||!moduleID)return;const moduleIDKey=String(moduleID);const containerPath=existingWrapper.____slothletInternal.apiPath;const nextSet=new Set(nextChildKeys);for(const key of existingChildKeys){if(nextSet.has(key))continue;const owner=ownership.getCurrentOwner(`${containerPath}.${key}`);if(!owner)continue;if(String(owner.moduleID)===moduleIDKey)continue;const child=existingWrapper[key];if(!this.isWrapperProxy(child))continue;let list=this.state.replaceShadows.get(moduleIDKey);if(!list){list=[];this.state.replaceShadows.set(moduleIDKey,list)}list.push({container:existingWrapper,key,child,ownerModuleID:String(owner.moduleID)})}}async mutateApiValue(existingValue,nextValue,options,config){if(config?.debug?.api){this.slothlet.debug("api",{key:"DEBUG_MODE_MUTATE_API_VALUE_CALLED",existingType:typeof existingValue,nextType:typeof nextValue});this.slothlet.debug("api",{key:"DEBUG_MODE_MUTATE_API_VALUE_WRAPPER_STATUS",existingIsWrapper:this.isWrapperProxy(existingValue),nextIsWrapper:this.isWrapperProxy(nextValue)});this.slothlet.debug("api",{key:"DEBUG_MODE_MUTATE_API_VALUE_NEXT_VALUE",nextValue});this.slothlet.debug("api",{key:"DEBUG_MODE_MUTATE_API_VALUE_NEXT_VALUE_KEYS",nextValueKeys:nextValue?Object.keys(nextValue):[]})}if(existingValue===nextValue){return}if(this.isWrapperProxy(existingValue)&&this.isWrapperProxy(nextValue)){if(config?.debug?.api){this.slothlet.debug("api",{key:"DEBUG_MODE_MUTATE_API_VALUE_SYNC_WRAPPERS"})}await this.syncWrapper(existingValue,nextValue,config,options.collisionMode,options.moduleID);return}if(this.isWrapperProxy(existingValue)&&!this.isWrapperProxy(nextValue)){const nextIsObjectLike=nextValue&&(typeof nextValue==="object"||typeof nextValue==="function");const nextHasKeys=nextIsObjectLike&&Object.keys(nextValue).length>0;if(nextHasKeys){if(config?.debug?.api){this.slothlet.debug("api",{key:"DEBUG_MODE_MUTATE_API_VALUE_MERGE_INTO_WRAPPER"});this.slothlet.debug("api",{key:"DEBUG_MODE_MUTATE_API_VALUE_MERGE_KEYS",keys:Object.keys(nextValue)})}await this.slothlet.builders.apiAssignment.mergeApiObjects(existingValue,nextValue,{removeMissing:options.removeMissing,mutateExisting:true,allowOverwrite:true,syncWrapper:this.syncWrapper.bind(this),collisionMode:options.collisionMode,moduleID:options.moduleID});return}const existingValueRaw=resolveWrapper(existingValue);if(existingValueRaw!==null){if(config?.debug?.api){this.slothlet.debug("api",{key:"DEBUG_MODE_MUTATE_API_VALUE_SETIMPL_FALLBACK"})}existingValueRaw.___setImpl(resolveWrapper(nextValue)?.__impl??nextValue);return}}if(existingValue&&typeof existingValue==="object"&&nextValue&&typeof nextValue==="object"){await this.slothlet.builders.apiAssignment.mergeApiObjects(existingValue,nextValue,{removeMissing:options.removeMissing,mutateExisting:true,allowOverwrite:true,syncWrapper:this.syncWrapper.bind(this),collisionMode:options.collisionMode,moduleID:options.moduleID});return existingValue}return nextValue}async setValueAtPath(root,parts,value,options){const parent=this.ensureParentPath(root,parts,{moduleID:options.moduleID,sourceFolder:options.sourceFolder});const finalKey=parts[parts.length-1];const parentWrapper=resolveWrapper(parent);if(parentWrapper&&parentWrapper.____slothletInternal.mode==="lazy"&&!parentWrapper.____slothletInternal.state.materialized){await parentWrapper._materialize()}const existing=parent?parent[finalKey]:void 0;const collisionMode=options.collisionMode||"merge";const moduleID=options.moduleID;this.slothlet.debug("api",{key:"DEBUG_MODE_SET_VALUE_AT_PATH",finalKey,existingType:typeof existing,valueType:typeof value,collisionMode,options});if(existing!==void 0){if(collisionMode==="error"){throw new this.SlothletError("INVALID_CONFIG_API_PATH_INVALID",{apiPath:parts.join("."),reason:translate("API_PATH_REASON_COLLISION_ERROR"),index:void 0,segment:void 0,validationError:true})}if(collisionMode==="skip"){this.slothlet.debug("api",{key:"DEBUG_MODE_SET_VALUE_AT_PATH_SKIP_COLLISION",path:parts.join("."),mode:"skip"});return false}if(collisionMode==="warn"){if(this.slothlet&&!this.____config?.silent){new this.SlothletWarning("WARNING_HOT_RELOAD_PATH_COLLISION",{apiPath:parts.join(".")})}return false}if(collisionMode==="replace"){const existingIsObject=typeof existing==="object"||typeof existing==="function";const valueIsObject=typeof value==="object"||typeof value==="function";if(existingIsObject&&valueIsObject){this.slothlet.debug("api",{key:"DEBUG_MODE_SET_VALUE_AT_PATH_REPLACE_MERGE",path:parts.join("."),mode:"replace"});await this.mutateApiValue(existing,value,{removeMissing:false,allowOverwrite:true,collisionMode:"replace",moduleID},this.____config);return true}else{parent[finalKey]=value;return true}}if(collisionMode==="merge"||collisionMode==="merge-replace"){const existingIsObject=typeof existing==="object"||typeof existing==="function";const valueIsObject=typeof value==="object"||typeof value==="function";if(existingIsObject&&valueIsObject){this.slothlet.debug("api",{key:"DEBUG_MODE_SET_VALUE_AT_PATH_MERGE_PROPS",mode:collisionMode});await this.mutateApiValue(existing,value,{removeMissing:false,allowOverwrite:true,collisionMode},this.____config);return true}else{const apiPath=parts.join(".");if(this.slothlet&&!this.____config?.silent){new this.SlothletWarning("WARNING_HOT_RELOAD_MERGE_PRIMITIVES",{apiPath})}await this.emitImplDiagnostic("error",{apiPath,code:"WARNING_HOT_RELOAD_MERGE_PRIMITIVES",context:{apiPath},source:"addApi",moduleID,error:new this.SlothletError("WARNING_HOT_RELOAD_MERGE_PRIMITIVES",{apiPath})});return false}}}this.slothlet.debug("api",{key:"DEBUG_MODE_SET_VALUE_AT_PATH_ASSIGN",finalKey});parent[finalKey]=value;return true}async deletePath(root,parts){let current=root;const stack=[];for(const part of parts.slice(0,-1)){if(!current||typeof current!=="object"&&typeof current!=="function"){return false}stack.push({parent:current,key:part});current=current[part]}const finalKey=parts[parts.length-1];if(!current||typeof current!=="object"&&typeof current!=="function"){return false}if(!Object.prototype.hasOwnProperty.call(current,finalKey)){return false}const removedImpl=current[finalKey];const apiPath=parts.join(".");if(removedImpl&&this.slothlet.handlers?.lifecycle){const metadata=this.slothlet.handlers.metadata?.getMetadata?.(removedImpl);await this.slothlet.handlers.lifecycle.emit("impl:removed",{apiPath,impl:removedImpl,source:"removal",moduleID:metadata?.moduleID,filePath:metadata?.filePath,sourceFolder:metadata?.sourceFolder})}if(resolveWrapper(current)){const wrapper=resolveWrapper(current);const isInternal=typeof finalKey==="string"&&(finalKey.startsWith("_")||finalKey.startsWith("__"));if(!isInternal&&finalKey in wrapper){delete wrapper[finalKey]}if(wrapper.____slothletInternal.impl&&typeof wrapper.____slothletInternal.impl==="object"){delete wrapper.____slothletInternal.impl[finalKey]}}delete current[finalKey];if(removedImpl&&(typeof removedImpl==="object"||typeof removedImpl==="function")){if(resolveWrapper(removedImpl)){const wrapper=resolveWrapper(removedImpl);if(wrapper.____slothletInternal.impl!==void 0){wrapper.____slothletInternal.impl=null}const childKeys=Object.keys(wrapper).filter(k=>!k.startsWith("_")&&!k.startsWith("__"));for(const key of childKeys){delete wrapper[key]}if(wrapper.____slothletInternal.state){wrapper.____slothletInternal.state.materialized=false;wrapper.____slothletInternal.state.inFlight=false}}}if(this.slothlet.handlers?.metadata){const rootSegment=apiPath.split(".")[0];this.slothlet.handlers.metadata.removeUserMetadataByApiPath(rootSegment)}for(let i=stack.length-1;i>=0;i-=1){const{parent,key}=stack[i];const value=parent[key];if(value&&(typeof value==="object"||typeof value==="function")&&Object.keys(value).length===0){delete parent[key]}}return true}async restoreApiPath(apiPath,moduleID){const normalizedModuleId=moduleID||null;const historyEntry=this.state.addHistory.slice().reverse().find(entry=>entry.apiPath===apiPath&&(normalizedModuleId?entry.moduleID===normalizedModuleId:true));if(historyEntry){await this.addApiComponent({apiPath:historyEntry.apiPath,folderPath:historyEntry.folderPath,options:{...historyEntry.options,metadata:historyEntry.metadata,mutateExisting:true,forceOverwrite:true,collisionMode:"replace",recordHistory:false}});return}if(normalizedModuleId==="base"||normalizedModuleId==="core"){const baseApi=await this.slothlet.builders.builder.buildAPI({dir:this.____config.dir,mode:this.____config.mode,moduleID:"base"});const{parts}=this.normalizeApiPath(apiPath);let baseValue=this.getValueAtPath(baseApi,parts);if(baseValue===void 0){await this.deletePath(this.slothlet.api,parts);await this.deletePath(this.slothlet.boundApi,parts);return}const baseValueRaw=resolveWrapper(baseValue);if(baseValue&&baseValueRaw!==null){baseValue=baseValueRaw.__impl}await this.setValueAtPath(this.slothlet.api,parts,baseValue,{mutateExisting:true,allowOverwrite:true,collisionMode:"replace",moduleID:normalizedModuleId});await this.setValueAtPath(this.slothlet.boundApi,parts,baseValue,{mutateExisting:true,allowOverwrite:true,collisionMode:"replace",moduleID:normalizedModuleId})}}#normalizePermissionShorthandEntry(entry){const getValueType=value=>{if(value===null)return"null";if(Array.isArray(value))return"array";return typeof value};if(typeof entry==="string"){return{target:entry,condition:void 0}}if(!entry||typeof entry!=="object"||Array.isArray(entry)){throw new this.SlothletError("INVALID_PERMISSION_RULE",{reason:translate("PERM_RULE_NOT_OBJECT"),received:getValueType(entry),validationError:true})}if(typeof entry.target!=="string"||!entry.target){throw new this.SlothletError("INVALID_PERMISSION_RULE",{reason:translate("PERM_RULE_TARGET_REQUIRED"),received:typeof entry.target,validationError:true})}return{target:entry.target,condition:entry.condition}}async addApiComponent(params){const{apiPath,folderPath,options={},versionConfig=null}=params||{};if(Array.isArray(folderPath)){const moduleIDs=[];for(const singlePath of folderPath){const moduleID2=await this.addApiComponent({apiPath,folderPath:singlePath,options,versionConfig});moduleIDs.push(moduleID2)}return moduleIDs}let effectiveOptions=options;if(folderPath&&typeof folderPath==="object"&&!Array.isArray(folderPath)&&Object.prototype.hasOwnProperty.call(folderPath,"exports")){const siblingOptions={...folderPath};delete siblingOptions.exports;if(Object.keys(siblingOptions).length>0)effectiveOptions={...siblingOptions,...options}}const{metadata={},...restOptions}=effectiveOptions;if(!this.slothlet||!this.slothlet.isLoaded){throw new this.SlothletError("INVALID_CONFIG_NOT_LOADED",{operation:"addApi",validationError:true})}if(restOptions.moduleID&&String(restOptions.moduleID).includes(MODULE_ID_SEPARATOR)){throw new this.SlothletError("MODULE_ID_RESERVED_SEPARATOR",{moduleID:String(restOptions.moduleID),separator:MODULE_ID_SEPARATOR,validationError:true})}const{apiPath:normalizedPath,parts}=this.normalizeApiPath(apiPath);if(restOptions.moduleID&&normalizedPath.includes(MODULE_ID_SEPARATOR)){const segIndex=parts.findIndex(p=>p.includes(MODULE_ID_SEPARATOR));throw new this.SlothletError("INVALID_CONFIG_API_PATH_INVALID",{apiPath:normalizedPath,segment:parts[segIndex],index:segIndex,reason:translate("API_PATH_REASON_RESERVED_SEPARATOR"),validationError:true})}let effectivePath=normalizedPath;let effectiveParts=parts;if(versionConfig?.version!==void 0&&versionConfig?.version!==null){if(normalizedPath===""){throw new this.SlothletError("INVALID_CONFIG_API_PATH_INVALID",{apiPath,reason:translate("API_PATH_REASON_VERSIONED_ROOT"),index:void 0,segment:void 0,validationError:true})}if(typeof versionConfig.version!=="string"||!String(versionConfig.version).trim()){throw new this.SlothletError("INVALID_CONFIG_VERSION_TAG",{received:versionConfig.version,validationError:true})}const versionTag=String(versionConfig.version).trim();effectiveParts=[versionTag,...parts];effectivePath=effectiveParts.join(".")}const isSynthetic=typeof folderPath==="function"||folderPath!==null&&typeof folderPath==="object"&&!Array.isArray(folderPath);let syntheticExports=null;let resolvedPath,isDirectory,isFile;if(isSynthetic){const isPlainObject=value=>{if(value===null||typeof value!=="object")return false;const proto=Object.getPrototypeOf(value);return proto===Object.prototype||proto===null};const describeNonPlain=value=>value===null?"null":Array.isArray(value)?"array":typeof value==="object"?`${value.constructor?.name??"non-plain object"} instance`:typeof value;if(typeof folderPath==="function"){syntheticExports={default:folderPath}}else if(Object.prototype.hasOwnProperty.call(folderPath,"exports")){const inner=folderPath.exports;if(!isPlainObject(inner)){throw new this.SlothletError("INVALID_CONFIG_SYNTHETIC_EXPORTS_SHAPE",{received:describeNonPlain(inner),validationError:true})}syntheticExports=inner}else if(isPlainObject(folderPath)){syntheticExports=folderPath}else{throw new this.SlothletError("INVALID_CONFIG_SYNTHETIC_INPUT",{received:describeNonPlain(folderPath),validationError:true})}if(parts.length===0&&typeof syntheticExports.default==="function"){const def=syntheticExports.default;const{default:___default,...named}=syntheticExports;if(!def.name||def.name==="default"){if(this.slothlet&&!this.____config?.silent){new this.SlothletWarning("WARN_SYNTHETIC_ROOT_UNNAMED",{})}await this.emitImplDiagnostic("warning",{apiPath:normalizedPath,code:"WARN_SYNTHETIC_ROOT_UNNAMED",context:{},source:"addApi",moduleID:restOptions.moduleID});syntheticExports=named}else{if(Object.prototype.hasOwnProperty.call(named,def.name)){if(this.slothlet&&!this.____config?.silent){new this.SlothletWarning("WARN_SYNTHETIC_ROOT_COLLISION",{name:def.name})}await this.emitImplDiagnostic("warning",{apiPath:normalizedPath,code:"WARN_SYNTHETIC_ROOT_COLLISION",context:{name:def.name},source:"addApi",moduleID:restOptions.moduleID})}syntheticExports={[def.name]:def,...named}}}isFile=false;resolvedPath=`synthetic:${normalizedPath||"root"}`}else{({resolvedPath,isDirectory,isFile}=await this.resolvePath(folderPath));if(!isDirectory&&!isFile){throw new this.SlothletError("INVALID_CONFIG_PATH_TYPE",{path:resolvedPath,validationError:true})}if(isFile){const ext=path.extname(resolvedPath);if(![".mjs",".cjs",".js"].includes(ext)){throw new this.SlothletError("INVALID_CONFIG_FILE_TYPE",{path:resolvedPath,extension:ext,validationError:true})}}}const resolvedFolderPath=resolvedPath;let collisionMode;if(restOptions.forceOverwrite){collisionMode="replace"}else{collisionMode=restOptions.collisionMode||this.____config.api?.collision?.api||"error"}const mutateExisting=!!(restOptions.mutateExisting||collisionMode==="merge");const scanHiddenFolders=(restOptions.scanHiddenFolders??this.____config.scanHiddenFolders)===true;if(restOptions.scanHiddenFolders!==void 0&&!this.____config?.silent){new this.SlothletWarning("CONFIG_SCAN_HIDDEN_FOLDERS_DEPRECATED",{option:"scanHiddenFolders"})}const moduleID=restOptions.moduleID?String(restOptions.moduleID):this.buildDefaultModuleId(normalizedPath,resolvedFolderPath);if(moduleID.includes(MODULE_ID_SEPARATOR)){throw new this.SlothletError("MODULE_ID_RESERVED_SEPARATOR",{moduleID,separator:MODULE_ID_SEPARATOR,validationError:true})}if(restOptions.forceOverwrite&&!moduleID){throw new this.SlothletError("INVALID_CONFIG_FORCE_OVERWRITE_REQUIRES_MODULE_ID",{apiPath:normalizedPath,validationError:true})}let dirForBuild=resolvedFolderPath;let fileFilter=null;if(isFile){dirForBuild=path.dirname(resolvedFolderPath);const fileName=path.basename(resolvedFolderPath);fileFilter=file=>file===fileName}const newApi=await this.slothlet.builders.builder.buildAPI({dir:dirForBuild,mode:this.____config.mode,apiPathPrefix:effectivePath,collisionContext:"addApi",moduleID,collisionMode,fileFilter,rootUnwrap:isFile||isSynthetic,hidden:restOptions.hidden??null,scanHiddenFolders,...isSynthetic?{syntheticExports,syntheticName:parts.length?parts[parts.length-1]:"synthetic"}:{}});if(this.slothlet.handlers.apiCacheManager){this.slothlet.handlers.apiCacheManager.set(moduleID,{endpoint:effectivePath,moduleID,api:newApi,folderPath:resolvedFolderPath,syntheticExports:isSynthetic?syntheticExports:null,mode:this.____config.mode,sanitizeOptions:this.____config.sanitize||{},hidden:restOptions.hidden??null,scanHiddenFolders,collisionMode,config:{...this.____config},timestamp:Date.now()})}this.slothlet.debug("api",{key:"DEBUG_MODE_ADD_API_COMPONENT_BUILD_RETURN",topLevelKeys:Object.keys(newApi),dottedKeys:Object.keys(newApi).filter(k=>k.includes(".")),wrappers:Object.keys(newApi).filter(k=>resolveWrapper(newApi[k])!==null).map(k=>{const _w=resolveWrapper(newApi[k]);return{key:k,apiPath:_w.apiPath,implKeys:Object.keys(_w.____slothletInternal.impl||{}),childCacheSize:Object.keys(_w).filter(k2=>!k2.startsWith("_")&&!k2.startsWith("__")).length,childCacheKeys:Object.keys(_w).filter(k2=>!k2.startsWith("_")&&!k2.startsWith("__"))}}),nonWrappers:Object.keys(newApi).filter(k=>resolveWrapper(newApi[k])===null).map(k=>({key:k,type:typeof newApi[k]}))});let apiToMerge=newApi;if((isFile||isSynthetic)&&Object.keys(newApi).length===1){const fileName=Object.keys(newApi)[0];apiToMerge=newApi[fileName]}if(!isFile&&normalizedPath){const lastPart=normalizedPath.includes(".")?normalizedPath.split(".").pop():normalizedPath;if(lastPart&&Object.prototype.hasOwnProperty.call(apiToMerge,lastPart)){const dupValue=apiToMerge[lastPart];const dupType=typeof dupValue;if(dupValue!==null&&(dupType==="object"||dupType==="function")){const dupWrapper=resolveWrapper(dupValue);const dupFilePath=dupWrapper?.____slothletInternal?.filePath;const dupFileDir=dupFilePath?dupFilePath.replace(/\\/g,"/").split("/").slice(0,-1).join("/"):null;const normalizedFolderPath=resolvedFolderPath.replace(/\\/g,"/").replace(/\/$/,"");const expectedDir=normalizedFolderPath+"/"+lastPart;const isDirectChild=dupFileDir===expectedDir||dupFileDir===normalizedFolderPath;if(isDirectChild){const hoisted={};for(const k of Object.keys(apiToMerge)){if(k!==lastPart)hoisted[k]=apiToMerge[k]}if(dupWrapper){for(const k of Object.keys(dupWrapper).filter(k2=>!k2.startsWith("_")&&!k2.startsWith("__"))){hoisted[k]=dupWrapper[k]}}else{for(const k of Object.keys(dupValue)){hoisted[k]=dupValue[k]}}apiToMerge=hoisted;this.slothlet.debug("api",{key:"DEBUG_MODE_RULE_13_DEDUP_HOISTED_KEY",lastPart,newKeys:Object.keys(apiToMerge)})}}}}if(this.____config.debug?.api){this.slothlet.debug("api",{key:"DEBUG_MODE_ADD_API_COMPONENT_MERGE_KEYS",keys:Object.keys(apiToMerge),isRootLevel:parts.length===0})}let anyAssignmentSucceeded=false;let rootKeys=[];if(parts.length===0){const rootSource=isSynthetic?apiToMerge:newApi;rootKeys=Object.keys(rootSource);if(rootKeys.length===0&&isSynthetic){if(this.slothlet&&!this.____config?.silent){new this.SlothletWarning("WARN_SYNTHETIC_ROOT_EMPTY",{apiPath:normalizedPath||"(root)"})}await this.emitImplDiagnostic("warning",{apiPath:normalizedPath,code:"WARN_SYNTHETIC_ROOT_EMPTY",context:{apiPath:normalizedPath||"(root)"},source:"addApi",moduleID})}for(const key of rootKeys){const result1=await this.setValueAtPath(this.slothlet.api,[key],rootSource[key],{mutateExisting,collisionMode,moduleID,sourceFolder:resolvedFolderPath});const result2=await this.setValueAtPath(this.slothlet.boundApi,[key],rootSource[key],{mutateExisting,collisionMode,moduleID,sourceFolder:resolvedFolderPath});if(result1||result2){anyAssignmentSucceeded=true}}}else{if(resolveWrapper(apiToMerge)===null){const isCallableNamespace=typeof apiToMerge==="function";const containerWrapper=new UnifiedWrapper(this.slothlet,{apiPath:effectivePath,mode:this.____config.mode,isCallable:isCallableNamespace,moduleID,filePath:resolvedFolderPath,sourceFolder:resolvedFolderPath});containerWrapper.___setImpl(apiToMerge,moduleID);apiToMerge=containerWrapper.createProxy()}const result1=await this.setValueAtPath(this.slothlet.api,effectiveParts,apiToMerge,{mutateExisting,collisionMode,moduleID,sourceFolder:resolvedFolderPath});const result2=await this.setValueAtPath(this.slothlet.boundApi,effectiveParts,apiToMerge,{mutateExisting,collisionMode,moduleID,sourceFolder:resolvedFolderPath});if(result1||result2){anyAssignmentSucceeded=true}}if(anyAssignmentSucceeded){const pendingMaterializations=[];const seenWrappers=new Set;const collectPendingMaterializations=(obj,depth=0)=>{const objType=typeof obj;if(!obj||objType!=="object"&&objType!=="function"||depth>10)return;if(isFrameworkInternal(obj))return;const wrapper=resolveWrapper(obj);if(wrapper){if(seenWrappers.has(wrapper))return;seenWrappers.add(wrapper);if(wrapper.____slothletInternal.materializationPromise){pendingMaterializations.push(wrapper.____slothletInternal.materializationPromise)}const childKeys=Object.keys(wrapper).filter(k=>!k.startsWith("_")&&!k.startsWith("__"));for(const key of childKeys){collectPendingMaterializations(wrapper[key],depth+1)}return}for(const key of Object.keys(obj)){if(key!=="____slothletInternal"){collectPendingMaterializations(obj[key],depth+1)}}};if(effectiveParts.length===0){for(const key of rootKeys){if(this.slothlet.api[key]){collectPendingMaterializations(this.slothlet.api[key])}}}else{let current=this.slothlet.api;for(const part of effectiveParts){if(current&&current[part]){current=current[part]}else{break}}if(current){collectPendingMaterializations(current)}}if(pendingMaterializations.length>0){if(this.____config.debug?.api){this.slothlet.debug("api",{key:"DEBUG_MODE_AWAITING_PENDING_MATERIALIZATIONS",count:pendingMaterializations.length,apiPath:normalizedPath})}await Promise.all(pendingMaterializations)}}if(anyAssignmentSucceeded&&metadata&&Object.keys(metadata).length>0&&this.slothlet.handlers.metadata){if(parts.length===0){for(const key of Object.keys(newApi)){this.slothlet.handlers.metadata.registerUserMetadata(key,metadata)}}else{const rootSegment=effectiveParts[0];this.slothlet.handlers.metadata.registerUserMetadata(rootSegment,metadata)}}if(this.slothlet.handlers.ownership&&moduleID){this.slothlet.handlers.ownership.registerSubtree(apiToMerge,moduleID,effectivePath);this.slothlet.handlers.ownership.setModuleEndpoint(moduleID,effectivePath)}if(this.slothlet.handlers.ownership){if(restOptions.recordHistory!==false){const historyFolderPath=isSynthetic?folderPath:resolvedFolderPath;this.state.addHistory.push({apiPath:normalizedPath,folderPath:historyFolderPath,options:{...restOptions,metadata,moduleID},moduleID,versionConfig:versionConfig||null});this.state.operationHistory.push({type:"add",apiPath:normalizedPath,folderPath:historyFolderPath,options:{...restOptions,metadata,moduleID},moduleID,versionConfig:versionConfig||null})}}if(versionConfig?.version&&this.slothlet.handlers.versionManager){const versionTag=String(versionConfig.version).trim();try{this.slothlet.handlers.versionManager.registerVersion(normalizedPath,versionTag,moduleID,versionConfig.metadata??{},versionConfig.default??false)}catch(error){await this._rollbackFailedVersionedAdd({moduleID,effectivePath,normalizedPath});throw error}}if(restOptions.permissions&&this.slothlet.handlers?.permissionManager){const perms=restOptions.permissions;const callerPattern=`${normalizedPath}.**`;if(Array.isArray(perms.deny)){for(const entry of perms.deny){const{target,condition}=this.#normalizePermissionShorthandEntry(entry);this.slothlet.handlers.permissionManager.addRule({caller:callerPattern,target,effect:"deny",condition},moduleID)}}if(Array.isArray(perms.allow)){for(const entry of perms.allow){const{target,condition}=this.#normalizePermissionShorthandEntry(entry);this.slothlet.handlers.permissionManager.addRule({caller:callerPattern,target,effect:"allow",condition},moduleID)}}}return moduleID}async _rollbackFailedVersionedAdd({moduleID,effectivePath,normalizedPath}){let addIndex=-1;for(let i=this.state.operationHistory.length-1;i>=0;i--){const entry=this.state.operationHistory[i];if(entry?.type==="add"&&entry?.apiPath===normalizedPath&&entry?.moduleID===moduleID){addIndex=i;break}}if(addIndex!==-1){this.state.operationHistory.splice(addIndex,1)}this.state.addHistory=this.state.addHistory.filter(entry=>entry?.moduleID!==moduleID);try{await this.removeApiComponent(moduleID||effectivePath,{recordHistory:false})}catch{}}#sweepOrphanedCaches(){const cacheManager=this.slothlet.handlers?.apiCacheManager;if(!cacheManager)return;const root=this.slothlet.boundApi;for(const moduleID of cacheManager.getAllModuleIDs()){const entry=cacheManager.get(moduleID);if(!entry||entry.endpoint==="."||entry.endpoint==="")continue;const parts=String(entry.endpoint).split(".").filter(Boolean);if(this.getValueAtPath(root,parts)===void 0){cacheManager.delete(moduleID)}}}_hasForeignOwnedDescendant(apiPath,moduleIDKey){const ownership=this.slothlet.handlers.ownership;if(!ownership||!apiPath)return false;const prefix=apiPath+".";for(const p of ownership.pathToModule.keys()){if(!p.startsWith(prefix))continue;const owner=ownership.getCurrentOwner(p);if(owner&&owner.moduleID!==moduleIDKey)return true}return false}async removeApiComponent(pathOrModuleId,options={}){const recordHistory=options.recordHistory!==false;if(typeof pathOrModuleId!=="string"||!pathOrModuleId){throw new this.SlothletError("INVALID_ARGUMENT",{argument:"pathOrModuleId",expected:"non-empty string",received:typeof pathOrModuleId,validationError:true})}const scopedApiPath=typeof options.scopedApiPath==="string"?options.scopedApiPath:null;let apiPath=null;let moduleID;if(this.slothlet.handlers.ownership){const registeredModules=Array.from(this.slothlet.handlers.ownership.moduleToPath.keys());let matchingModule=null;const candidateModuleID=pathOrModuleId.split(MODULE_ID_SEPARATOR)[0];for(let i=registeredModules.length-1;i>=0;i--){const candidate=registeredModules[i];if(candidate===candidateModuleID||candidate.startsWith(`${candidateModuleID}_`)){matchingModule=candidate;break}}if(matchingModule){moduleID=matchingModule}else if(scopedApiPath!==null){return false}else{const owner=this.slothlet.handlers.ownership.getCurrentOwner(pathOrModuleId);if(owner){apiPath=pathOrModuleId;moduleID=owner.moduleID}else{return false}}}else{const isModuleId=!pathOrModuleId.includes(".");apiPath=isModuleId?null:pathOrModuleId;moduleID=isModuleId?pathOrModuleId.split(MODULE_ID_SEPARATOR)[0]:null}if(!this.slothlet||!this.slothlet.isLoaded){throw new this.SlothletError("INVALID_CONFIG_NOT_LOADED",{operation:"removeApi",validationError:true})}if(scopedApiPath!==null){const ownership=this.slothlet.handlers.ownership;const normalizedScoped=this.normalizeApiPath(scopedApiPath).apiPath;const ownedPaths=ownership?.moduleToPath?.get(moduleID);if(!ownedPaths||!ownedPaths.has(normalizedScoped)){return false}const scopedModuleIDKey=String(moduleID);const scopedPrefix=`${normalizedScoped}.`;const targets=[...ownedPaths].filter(p=>p===normalizedScoped||p.startsWith(scopedPrefix)).sort((a,b)=>b.length-a.length);const isFullRemoval=[...ownedPaths].every(p=>p===normalizedScoped||p.startsWith(scopedPrefix));if(isFullRemoval){ownership?.markUnregistered?.(scopedModuleIDKey)}for(const target of targets){const targetParts=this.normalizeApiPath(target).parts;const scopedResult=ownership.removePath(target,scopedModuleIDKey);if(scopedResult.action==="restore"){const revertValue=ownership.getCurrentValue?.(target);const revertOwner=ownership.getCurrentOwner?.(target)?.moduleID;if(revertValue!==void 0&&revertOwner){const revertOptions={mutateExisting:true,allowOverwrite:true,collisionMode:"replace",moduleID:revertOwner};await this.setValueAtPath(this.slothlet.api,targetParts,revertValue,revertOptions);await this.setValueAtPath(this.slothlet.boundApi,targetParts,revertValue,revertOptions)}else{await this.restoreApiPath(target,scopedResult.restoreModuleId)}}else{const stillHasChild=[...ownership.moduleToPath.values()].some(set=>{for(const owned of set)if(owned.startsWith(`${target}.`))return true;return false});if(!stillHasChild){await this.deletePath(this.slothlet.api,targetParts);await this.deletePath(this.slothlet.boundApi,targetParts)}}}this.#sweepOrphanedCaches();if(recordHistory){this.state.operationHistory.push({type:"remove",apiPath:normalizedScoped,scopedModuleID:scopedModuleIDKey})}return true}if(apiPath&&moduleID){const normalizedPath2=this.normalizeApiPath(apiPath).apiPath;const moduleIDKey=String(moduleID);const history=this.slothlet.handlers.ownership?.getPathHistory?.(normalizedPath2)||[];const ownershipResult2=this.slothlet.handlers.ownership?.removePath?.(normalizedPath2,moduleIDKey)||{action:"none",removedModuleId:null,restoreModuleId:null};const pathParts=this.normalizeApiPath(apiPath).parts;if(ownershipResult2.action==="delete"){await this.deletePath(this.slothlet.api,pathParts);await this.deletePath(this.slothlet.boundApi,pathParts);if(this.slothlet.handlers.metadata){const rootSegment=normalizedPath2.split(".")[0];this.slothlet.handlers.metadata.removeUserMetadataByApiPath(rootSegment)}if(this.slothlet.handlers.versionManager){const versionKey=this.slothlet.handlers.versionManager.getVersionKeyForModule(moduleIDKey);if(versionKey){this.slothlet.handlers.versionManager.unregisterVersion(versionKey.logicalPath,versionKey.versionTag)}if(this.slothlet.handlers.versionManager.hasDispatcher(normalizedPath2)){this.slothlet.handlers.versionManager.teardownDispatcher(normalizedPath2)}}this.#sweepOrphanedCaches();this.state.operationHistory.push({type:"remove",apiPath:normalizedPath2});return true}if(ownershipResult2.action==="restore"){const restoredValue=this.slothlet.handlers.ownership?.getCurrentValue?.(normalizedPath2);const restoredModuleId=this.slothlet.handlers.ownership?.getCurrentOwner?.(normalizedPath2)?.moduleID;if(restoredValue!==void 0&&restoredModuleId){await this.setValueAtPath(this.slothlet.api,pathParts,restoredValue,{mutateExisting:true,allowOverwrite:true,collisionMode:"replace",moduleID:restoredModuleId});await this.setValueAtPath(this.slothlet.boundApi,pathParts,restoredValue,{mutateExisting:true,allowOverwrite:true,collisionMode:"replace",moduleID:restoredModuleId});this.state.operationHistory.push({type:"remove",apiPath:normalizedPath2});return true}else{await this.restoreApiPath(normalizedPath2,ownershipResult2.restoreModuleId);this.state.operationHistory.push({type:"remove",apiPath:normalizedPath2});return true}}if(ownershipResult2.action==="none"&&history.length===0){await this.deletePath(this.slothlet.api,pathParts);await this.deletePath(this.slothlet.boundApi,pathParts);return true}return false}if(moduleID){const moduleIDKey=String(moduleID);const mountEndpoint=this.slothlet.handlers.ownership?.getModuleEndpoint?.(moduleIDKey);const isRootMount=!mountEndpoint||mountEndpoint===".";let mountRoot=isRootMount?"":mountEndpoint;const result=this.slothlet.handlers.ownership?.unregister?.(moduleIDKey)||{removed:[],rolledBack:[]};if(this.slothlet.handlers.versionManager){const versionKey=this.slothlet.handlers.versionManager.getVersionKeyForModule(moduleIDKey);if(versionKey){this.slothlet.handlers.versionManager.unregisterVersion(versionKey.logicalPath,versionKey.versionTag)}}const allPaths=[...result.removed,...result.rolledBack.map(r=>r.apiPath)];const uniquePaths=[...new Set(allPaths)];const pathsToDelete=[];const pathsToRollback=[];for(const path2 of uniquePaths){const currentOwner=this.slothlet.handlers.ownership?.getCurrentOwner?.(path2);const hasChildrenWithOtherOwners=isRootMount?this._hasForeignOwnedDescendant(path2,moduleIDKey):uniquePaths.some(p=>{if(p===path2||!p.startsWith(path2+"."))return false;const childOwner=this.slothlet.handlers.ownership?.getCurrentOwner?.(p);return childOwner&&childOwner.moduleID!==moduleIDKey});if(currentOwner&&currentOwner.moduleID!==moduleIDKey){pathsToRollback.push({apiPath:path2,restoredTo:currentOwner.moduleID})}else if(!hasChildrenWithOtherOwners){pathsToDelete.push(path2)}}pathsToDelete.sort((a,b)=>{const depthA=(a.match(/\./g)||[]).length;const depthB=(b.match(/\./g)||[]).length;return depthB-depthA});for(const removedPath of pathsToDelete){const{parts:parts2}=this.normalizeApiPath(removedPath);await this.deletePath(this.slothlet.api,parts2);await this.deletePath(this.slothlet.boundApi,parts2);if(this.slothlet.handlers.metadata){const rootSegment=removedPath.split(".")[0];this.slothlet.handlers.metadata.removeUserMetadataByApiPath(rootSegment)}}if(pathsToDelete.length>0){if(isRootMount){const segs=pathsToDelete.map(p=>p.split("."));const minLen=Math.min(...segs.map(s=>s.length));const common=[];for(let i=0;i<minLen;i++){const seg=segs[0][i];if(segs.every(s=>s[i]===seg))common.push(seg);else break}mountRoot=common.join(".")}const rootParts=this.normalizeApiPath(mountRoot).parts;const mountRootDot=mountRoot===""?null:`${mountRoot}.`;const hasRollbackSurvivor=pathsToRollback.some(r=>r.apiPath===mountRoot||mountRootDot!==null&&r.apiPath.startsWith(mountRootDot));if(!hasRollbackSurvivor&&(!isRootMount||!this._hasForeignOwnedDescendant(mountRoot,moduleIDKey))){await this.deletePath(this.slothlet.api,rootParts);await this.deletePath(this.slothlet.boundApi,rootParts)}}for(const rollback of pathsToRollback){const{parts:parts2}=this.normalizeApiPath(rollback.apiPath);const previousImpl=this.slothlet.handlers.ownership?.getCurrentValue?.(rollback.apiPath);if(previousImpl!==void 0){const existingWrapper=this.getValueAtPath(this.slothlet.api,parts2);const existingWrapperRaw=resolveWrapper(existingWrapper);if(existingWrapperRaw){existingWrapperRaw.___setImpl(previousImpl,rollback.restoredTo)}const existingBoundWrapper=this.getValueAtPath(this.slothlet.boundApi,parts2);const existingBoundWrapperRaw=resolveWrapper(existingBoundWrapper);if(existingBoundWrapperRaw){existingBoundWrapperRaw.___setImpl(previousImpl,rollback.restoredTo)}}}const shadows=this.state.replaceShadows.get(moduleIDKey);if(shadows){for(const shadow of shadows){if(Object.prototype.hasOwnProperty.call(shadow.container,shadow.key))continue;Object.defineProperty(shadow.container,shadow.key,{value:shadow.child,writable:false,enumerable:true,configurable:true})}this.state.replaceShadows.delete(moduleIDKey)}this.state.addHistory=this.state.addHistory.filter(entry=>String(entry.moduleID)!==moduleIDKey);if(this.slothlet.handlers.apiCacheManager){const deleted=this.slothlet.handlers.apiCacheManager.delete(moduleIDKey);if(deleted){this.slothlet.debug("cache",{key:"DEBUG_MODE_CACHE_DELETED_MODULE_REMOVED",moduleID:moduleIDKey})}}this.#sweepOrphanedCaches();if(recordHistory&&pathsToDelete.length>0){this.state.operationHistory.push({type:"remove",apiPath:mountRoot||pathsToDelete[0].split(".")[0]})}return pathsToDelete.length>0||pathsToRollback.length>0}if(!apiPath){throw new this.SlothletError("INVALID_CONFIG_API_PATH_INVALID",{apiPath,reason:translate("API_PATH_REASON_REQUIRED"),index:void 0,segment:void 0,validationError:true})}const{apiPath:normalizedPath,parts}=this.normalizeApiPath(apiPath);const ownershipResult=this.slothlet.handlers.ownership?.removePath?.(normalizedPath,null)||{action:"none",removedModuleId:null,restoreModuleId:null};const pathExists=this.getValueAtPath(this.slothlet.api,parts)!==void 0;if(ownershipResult.action==="none"){if(pathExists){await this.deletePath(this.slothlet.api,parts);await this.deletePath(this.slothlet.boundApi,parts);if(this.slothlet.handlers.metadata){this.slothlet.handlers.metadata.removeUserMetadataByApiPath(normalizedPath)}if(recordHistory){this.state.operationHistory.push({type:"remove",apiPath:normalizedPath})}return true}return false}if(ownershipResult.action==="delete"){await this.deletePath(this.slothlet.api,parts);await this.deletePath(this.slothlet.boundApi,parts);if(this.slothlet.handlers.metadata){this.slothlet.handlers.metadata.removeUserMetadataByApiPath(normalizedPath)}if(recordHistory){this.state.operationHistory.push({type:"remove",apiPath:normalizedPath})}return true}if(ownershipResult.action==="restore"){const restoredValue=this.slothlet.handlers.ownership?.getCurrentValue?.(normalizedPath);const restoredModuleId=this.slothlet.handlers.ownership?.getCurrentOwner?.(normalizedPath)?.moduleID;if(restoredValue!==void 0&&restoredModuleId){await this.setValueAtPath(this.slothlet.api,parts,restoredValue,{mutateExisting:true,allowOverwrite:true,collisionMode:"replace",moduleID:restoredModuleId});await this.setValueAtPath(this.slothlet.boundApi,parts,restoredValue,{mutateExisting:true,allowOverwrite:true,collisionMode:"replace",moduleID:restoredModuleId});if(recordHistory){this.state.operationHistory.push({type:"remove",apiPath:normalizedPath})}return true}await this.restoreApiPath(normalizedPath,ownershipResult.restoreModuleId);if(recordHistory){this.state.operationHistory.push({type:"remove",apiPath:normalizedPath})}return true}return false}async reloadApiComponent(params){const{apiPath,moduleID,options}=params||{};if(!this.slothlet||!this.slothlet.isLoaded){throw new this.SlothletError("INVALID_CONFIG_NOT_LOADED",{operation:"reloadApi",validationError:true})}if(moduleID){await this._reloadByModuleID(moduleID);return}if(apiPath){await this._reloadByApiPath(apiPath,options);return}throw new this.SlothletError("INVALID_ARGUMENT",{argument:"params",expected:"{ moduleID } or { apiPath }",received:params,validationError:true})}async _reloadByModuleID(moduleID,{forceReplace=true}={}){const cacheManager=this.slothlet.handlers.apiCacheManager;if(!cacheManager){throw new this.SlothletError("CACHE_MANAGER_NOT_AVAILABLE",{operation:"reload",validationError:true})}if(!cacheManager.has(moduleID)){throw new this.SlothletError("CACHE_NOT_FOUND",{moduleID,operation:"reload",validationError:true})}const oldEntry=cacheManager.get(moduleID);this.slothlet.debug("reload",{key:"DEBUG_MODE_RELOADING_MODULE_BY_ID",moduleID,endpoint:oldEntry.endpoint,folderPath:oldEntry.folderPath});const freshApi=await cacheManager.rebuildCache(moduleID);cacheManager.set(moduleID,{...oldEntry,api:freshApi,timestamp:Date.now()});this.slothlet.debug("reload",{key:"DEBUG_MODE_FRESH_API_KEYS_BEFORE_RESTORE",moduleID,endpoint:oldEntry.endpoint,freshApiKeys:Object.keys(freshApi||{})});await this._restoreApiTree(freshApi,oldEntry.endpoint,moduleID,oldEntry.collisionMode,forceReplace);this.slothlet.debug("reload",{key:"DEBUG_MODE_FRESH_API_KEYS_AFTER_RESTORE",moduleID,endpoint:oldEntry.endpoint,freshApiKeys:Object.keys(freshApi||{})});this.slothlet.debug("reload",{key:"DEBUG_MODE_MODULE_RELOAD_COMPLETE",moduleID});if(this.slothlet.handlers.versionManager){this.slothlet.handlers.versionManager.onVersionedModuleReload(moduleID)}}async _reloadByApiPath(apiPath,options={}){this.slothlet.debug("reload",{key:"DEBUG_MODE_RELOADING_BY_API_PATH",apiPath});const moduleIDsToReload=this._findAffectedCaches(apiPath);if(moduleIDsToReload.length===0){this.slothlet.debug("reload",{key:"DEBUG_MODE_NO_CACHES_ATTEMPTING_RESTORE",apiPath});if(apiPath!=="."&&apiPath!==""){await this.restoreApiPath(apiPath,"base")}return}const cacheManager=this.slothlet.handlers.apiCacheManager;moduleIDsToReload.sort((a,b)=>{const entryA=cacheManager.get(a);const entryB=cacheManager.get(b);if(entryA?.endpoint==="."&&entryB?.endpoint!==".")return-1;if(entryB?.endpoint==="."&&entryA?.endpoint!==".")return 1;const indexA=this.state.addHistory.findIndex(h=>h.moduleID===a);const indexB=this.state.addHistory.findIndex(h=>h.moduleID===b);return indexA-indexB});const endpointOrder=new Map;for(const moduleID of moduleIDsToReload){const entry=cacheManager.get(moduleID);const ep=entry?.endpoint??".";if(!endpointOrder.has(ep))endpointOrder.set(ep,[]);endpointOrder.get(ep).push(moduleID)}for(const[,moduleIDs]of endpointOrder){for(let i=0;i<moduleIDs.length;i++){await this._reloadByModuleID(moduleIDs[i],{forceReplace:i===0})}}const reloadMetadata=options?.metadata;if(reloadMetadata&&typeof reloadMetadata==="object"&&Object.keys(reloadMetadata).length>0){if(this.slothlet.handlers.metadata){const targetPath=apiPath==="."?null:apiPath.split(".")[0];if(targetPath){this.slothlet.handlers.metadata.registerUserMetadata(targetPath,reloadMetadata)}}}this.slothlet.debug("reload",{key:"DEBUG_MODE_API_PATH_RELOAD_COMPLETE",apiPath,reloadedModules:moduleIDsToReload.length,loadOrder:moduleIDsToReload})}_findAffectedCaches(apiPath){const cacheManager=this.slothlet.handlers.apiCacheManager;if(!cacheManager)return[];const allModuleIDs=cacheManager.getAllModuleIDs();if(apiPath==="."||apiPath===""||apiPath==null){const baseModules=[];for(const moduleID of allModuleIDs){const entry=cacheManager.get(moduleID);if(entry&&entry.endpoint==="."){baseModules.push(moduleID)}}return baseModules}const exactMatches=[];for(const moduleID of allModuleIDs){const entry=cacheManager.get(moduleID);if(entry&&entry.endpoint===apiPath){exactMatches.push(moduleID)}}if(exactMatches.length>0)return exactMatches;const children=[];const pathPrefix=apiPath+".";for(const moduleID of allModuleIDs){const entry=cacheManager.get(moduleID);if(entry?.endpoint?.startsWith(pathPrefix)){children.push(moduleID)}}if(children.length>0)return children;const ownership=this.slothlet.handlers.ownership;const history=ownership?.getPathHistory?.(apiPath);if(history&&history.length>0){const owned=[];for(const{moduleID}of history){if(cacheManager.has(moduleID)){owned.push(moduleID)}}if(owned.length>0)return owned}let bestMatch=null;let bestLength=-1;for(const moduleID of allModuleIDs){const entry=cacheManager.get(moduleID);if(!entry?.endpoint)continue;const ep=entry.endpoint;if(ep==="."||apiPath.startsWith(ep+".")){if(ep.length>bestLength){bestLength=ep.length;bestMatch=moduleID}}}if(bestMatch)return[bestMatch];return[]}_collectCustomProperties(existingProxy,freshApi){const customProps={};if(!existingProxy||typeof existingProxy!=="object"&&typeof existingProxy!=="function"){return customProps}const wrapper=resolveWrapper(existingProxy);if(!wrapper){return customProps}const freshKeys=new Set(freshApi?Object.keys(freshApi):[]);const ownKeys=Object.keys(wrapper).filter(k=>!ComponentBase.INTERNAL_KEYS.has(k));for(const key of ownKeys){try{const val=wrapper[key];if(val&&(typeof val==="object"||typeof val==="function")&&resolveWrapper(val)){if(!resolveWrapper(val).____slothletInternal?.userAssigned)continue}if(!freshKeys.has(key)){customProps[key]=val}else{customProps[key]=val}}catch{}}return customProps}_restoreCustomProperties(proxy,customProps){if(!proxy||!customProps||typeof customProps!=="object"){return}for(const[key,value]of Object.entries(customProps)){try{proxy[key]=value}catch{}}}async _restoreApiTree(freshApi,endpoint,moduleID,collisionMode,forceReplace=true){if(!freshApi||typeof freshApi!=="object"&&typeof freshApi!=="function"){return}const parts=endpoint==="."?[]:endpoint.split(".");if(parts.length===0){for(const key of Object.keys(freshApi)){if(typeof key==="string"&&(key.startsWith("_")||key.startsWith("__")))continue;if(key==="slothlet"||key==="shutdown"||key==="destroy")continue;const existingAtKey=this.slothlet.api[key];const freshValue=freshApi[key];if(existingAtKey&&resolveWrapper(existingAtKey)!==null){const customProps=this._collectCustomProperties(existingAtKey,freshValue);const freshWrapper=resolveWrapper(freshValue);const isLazyFresh=freshWrapper&&freshWrapper.____slothletInternal.mode==="lazy"&&!freshWrapper.____slothletInternal.state.materialized&&typeof freshWrapper.____slothletInternal.materializeFunc==="function";this.slothlet.debug("reload",{key:"DEBUG_MODE_RESTORE_ROOT_KEY_INSPECT",rootKey:key,hasFreshWrapper:!!freshWrapper,freshMode:freshWrapper?.____slothletInternal.mode,freshMaterialized:freshWrapper?.____slothletInternal.state?.materialized,hasMaterializeFunc:typeof freshWrapper?.____slothletInternal.materializeFunc==="function",isLazyFresh,existingMaterialized:resolveWrapper(existingAtKey)?.____slothletInternal?.state?.materialized});if(isLazyFresh){resolveWrapper(existingAtKey).___resetLazy(freshWrapper.____slothletInternal.materializeFunc);this._restoreCustomProperties(existingAtKey,customProps);this.slothlet.debug("reload",{key:"DEBUG_MODE_ROOT_KEY_RESET_LAZY",rootKey:key,restoredCustomProps:Object.keys(customProps)})}else{let implForReload;if(freshValue&&resolveWrapper(freshValue)!==null){implForReload=freshWrapper?UnifiedWrapper._extractFullImpl(freshWrapper):freshValue}else{implForReload=freshValue}resolveWrapper(existingAtKey).___setImpl(implForReload,moduleID);this._restoreCustomProperties(existingAtKey,customProps);this.slothlet.debug("reload",{key:"DEBUG_MODE_ROOT_KEY_UPDATED_SETIMPL",rootKey:key,restoredCustomProps:Object.keys(customProps)})}}else if(existingAtKey===void 0){const cacheManager=this.slothlet.handlers.apiCacheManager;const cacheEntry=cacheManager.get(moduleID);const resolvedFolderPath=cacheEntry?.folderPath||"";await this.setValueAtPath(this.slothlet.api,[key],freshValue,{mutateExisting:true,collisionMode,moduleID,sourceFolder:resolvedFolderPath});if(this.slothlet.boundApi){await this.setValueAtPath(this.slothlet.boundApi,[key],freshValue,{mutateExisting:true,collisionMode,moduleID,sourceFolder:resolvedFolderPath})}}}}else{const existing=this.getValueAtPath(this.slothlet.api,parts);this.slothlet.debug("reload",{key:"DEBUG_MODE_RESTORE_NESTED_PATH",endpoint,moduleID,partsPath:parts.join("."),existingFound:!!existing,hasSetImpl:existing?resolveWrapper(existing)!==null:false,freshApiKeys:Object.keys(freshApi)});if(existing&&resolveWrapper(existing)!==null){const customProps=this._collectCustomProperties(existing,freshApi);const wrapper=resolveWrapper(existing);const originalCollisionMode=wrapper?wrapper.____slothletInternal.state.collisionMode:null;if(forceReplace&&wrapper){wrapper.____slothletInternal.state.collisionMode="replace";this.slothlet.debug("reload",{key:"DEBUG_MODE_RESTORE_FORCING_REPLACE",endpoint,originalCollisionMode,wrapperApiPath:wrapper.____slothletInternal.apiPath})}let implForReload;if(resolveWrapper(freshApi)!==null){const freshWrapper=resolveWrapper(freshApi);implForReload=freshWrapper?UnifiedWrapper._extractFullImpl(freshWrapper):freshApi}else{implForReload=freshApi}if(parts.length>0&&implForReload&&typeof implForReload==="object"){const lastEndpointPart=parts[parts.length-1];if(lastEndpointPart&&Object.prototype.hasOwnProperty.call(implForReload,lastEndpointPart)){const dupValue=implForReload[lastEndpointPart];const dupWrapperForDedup=resolveWrapper(dupValue);if(dupWrapperForDedup){const hoisted={};for(const k of Object.keys(implForReload)){if(k!==lastEndpointPart)hoisted[k]=implForReload[k]}for(const k of Object.keys(dupWrapperForDedup).filter(k2=>!k2.startsWith("_")&&!k2.startsWith("__"))){hoisted[k]=dupWrapperForDedup[k]}implForReload=hoisted}}}if(implForReload&&typeof implForReload==="object"){for(const key of Object.keys(implForReload)){const val=implForReload[key];if(resolveWrapper(val)!==null){const childWrapper=resolveWrapper(val);if(childWrapper.____slothletInternal.state.materialized){implForReload[key]=UnifiedWrapper._extractFullImpl(childWrapper)}}}}resolveWrapper(existing).___setImpl(implForReload,moduleID);if(wrapper&&originalCollisionMode!==null){wrapper.____slothletInternal.state.collisionMode=originalCollisionMode}this._restoreCustomProperties(existing,customProps);this.slothlet.debug("reload",{key:"DEBUG_MODE_UPDATED_WRAPPER_IMPL",endpoint,moduleID,forcedReplaceMode:true,restoredCustomProps:Object.keys(customProps)})}else{const cacheManager=this.slothlet.handlers.apiCacheManager;const cacheEntry=cacheManager.get(moduleID);const resolvedFolderPath=cacheEntry?.folderPath||"";let implForContainer=freshApi;if(typeof freshApi==="function"){implForContainer={};for(const key of Object.keys(freshApi)){implForContainer[key]=freshApi[key]}}const containerWrapper=new UnifiedWrapper(this.slothlet,{apiPath:endpoint,mode:this.____config.mode,moduleID,filePath:resolvedFolderPath,sourceFolder:resolvedFolderPath});containerWrapper.___setImpl(implForContainer,moduleID);const apiToSet=containerWrapper.createProxy();await this.setValueAtPath(this.slothlet.api,parts,apiToSet,{mutateExisting:true,collisionMode,moduleID,sourceFolder:resolvedFolderPath});if(this.slothlet.boundApi){await this.setValueAtPath(this.slothlet.boundApi,parts,apiToSet,{mutateExisting:true,collisionMode,moduleID,sourceFolder:resolvedFolderPath})}this.slothlet.debug("reload",{key:"DEBUG_MODE_CREATED_NEW_WRAPPER_UNEXPECTED",endpoint,moduleID})}}}}export{ApiManager};
@@ -14,4 +14,4 @@
14
14
  limitations under the License.
15
15
  */
16
16
 
17
- import{AsyncLocalStorage}from"@cldmv/slothlet/helpers/platform";import{SlothletError}from"@cldmv/slothlet/errors";import{runtime_isClassInstance,runtime_wrapClassInstance}from"@cldmv/slothlet/helpers/class-instance-wrapper";import{setApiContextChecker}from"@cldmv/slothlet/helpers/eventemitter-context";class AsyncContextManager{constructor(){this.als=AsyncLocalStorage?new AsyncLocalStorage:null;this.instances=new Map}registerEventEmitterContextChecker(){setApiContextChecker(()=>{const store=this.als.getStore();return store&&store.instanceID?true:false})}initialize(instanceID,config={}){if(this.instances.has(instanceID)){throw new SlothletError("CONTEXT_ALREADY_EXISTS",{instanceID},null,{validationError:true})}const store={instanceID,self:{},context:{},config:{...config},createdAt:Date.now()};this.instances.set(instanceID,store);return store}runInContext(instanceID,fn,thisArg,args,currentWrapper,rawErrors=false){const activeStore=this.als.getStore();let baseStore;const isActiveOurInstance=activeStore&&(activeStore.instanceID===instanceID||activeStore.parentInstanceID===instanceID);if(isActiveOurInstance){baseStore=activeStore}else{baseStore=this.instances.get(instanceID);if(!baseStore){throw new SlothletError("CONTEXT_NOT_FOUND",{instanceID,availableInstances:Array.from(this.instances.keys())})}}const executionStore={...baseStore};if(currentWrapper){executionStore.callerWrapper=baseStore.currentWrapper;executionStore.currentWrapper=currentWrapper}if(isActiveOurInstance){return this.als.run(executionStore,()=>{try{const result=fn.apply(thisArg,args);if(runtime_isClassInstance(result)){const instanceCache=new WeakMap;return runtime_wrapClassInstance(result,this,instanceID,instanceCache,executionStore.currentWrapper)}return result}catch(error){if(rawErrors||error instanceof SlothletError)throw error;throw new SlothletError("CONTEXT_EXECUTION_FAILED",{instanceID},error)}})}return this.als.run(executionStore,()=>{try{const result=fn.apply(thisArg,args);if(runtime_isClassInstance(result)){const instanceCache=new WeakMap;return runtime_wrapClassInstance(result,this,instanceID,instanceCache,executionStore.currentWrapper)}return result}catch(error){if(rawErrors||error instanceof SlothletError)throw error;throw new SlothletError("CONTEXT_EXECUTION_FAILED",{instanceID},error)}})}getContext(){const store=this.als.getStore();if(!store){throw new SlothletError("NO_ACTIVE_CONTEXT_ASYNC",{},null,{validationError:true})}return store}tryGetContext(instanceID){if(!this.als)return void 0;const store=this.als.getStore();if(instanceID===void 0)return store;if(store&&(store.instanceID===instanceID||store.parentInstanceID===instanceID)){return store}return this.instances.get(instanceID)}getCallerIdentity(instanceID){const store=this.tryGetContext(instanceID);if(!store)return void 0;return{currentWrapper:store.currentWrapper,callerWrapper:store.callerWrapper}}cleanup(instanceID){const store=this.instances.get(instanceID);if(!store){throw new SlothletError("CONTEXT_NOT_FOUND",{instanceID,availableInstances:Array.from(this.instances.keys()).join(", ")||"none"},null,{validationError:true})}store.self={};store.context={};this.instances.delete(instanceID)}getDiagnostics(){return{type:"async",activeStore:this.als.getStore()?.instanceID||null,instances:Array.from(this.instances.entries()).map(([id,store])=>({id,createdAt:store.createdAt,contextKeys:Object.keys(store.context),selfKeys:Object.keys(store.self)}))}}}const asyncContextManager=new AsyncContextManager;export{AsyncContextManager,asyncContextManager};
17
+ import{AsyncLocalStorage}from"@cldmv/slothlet/helpers/platform";import{SlothletError}from"@cldmv/slothlet/errors";import{runtime_isClassInstance,runtime_wrapClassInstance}from"@cldmv/slothlet/helpers/class-instance-wrapper";import{setApiContextChecker}from"@cldmv/slothlet/helpers/eventemitter-context";class AsyncContextManager{constructor(){this.als=AsyncLocalStorage?new AsyncLocalStorage:null;this.instances=new Map}registerEventEmitterContextChecker(){setApiContextChecker(()=>{const store=this.als.getStore();return store&&store.instanceID?true:false})}initialize(instanceID,config={}){if(this.instances.has(instanceID)){throw new SlothletError("CONTEXT_ALREADY_EXISTS",{instanceID},null,{validationError:true})}const store={instanceID,self:{},context:{},config:{...config},createdAt:Date.now()};this.instances.set(instanceID,store);return store}runInContext(instanceID,fn,thisArg,args,currentWrapper,rawErrors=false){const activeStore=this.als.getStore();let baseStore;const isActiveOurInstance=activeStore&&(activeStore.instanceID===instanceID||activeStore.parentInstanceID===instanceID);if(isActiveOurInstance){baseStore=activeStore}else{baseStore=this.instances.get(instanceID);if(!baseStore){throw new SlothletError("CONTEXT_NOT_FOUND",{instanceID,availableInstances:Array.from(this.instances.keys())})}}const executionStore={...baseStore};if(currentWrapper){executionStore.callerWrapper=baseStore.currentWrapper;executionStore.currentWrapper=currentWrapper}if(isActiveOurInstance){return this.als.run(executionStore,()=>{try{const result=fn.apply(thisArg,args);if(result instanceof Promise){return result.then(value=>this.#wrapClassInstanceResult(value,instanceID,executionStore.currentWrapper))}return this.#wrapClassInstanceResult(result,instanceID,executionStore.currentWrapper)}catch(error){if(rawErrors||error instanceof SlothletError)throw error;throw new SlothletError("CONTEXT_EXECUTION_FAILED",{instanceID},error)}})}return this.als.run(executionStore,()=>{try{const result=fn.apply(thisArg,args);if(result instanceof Promise){return result.then(value=>this.#wrapClassInstanceResult(value,instanceID,executionStore.currentWrapper))}return this.#wrapClassInstanceResult(result,instanceID,executionStore.currentWrapper)}catch(error){if(rawErrors||error instanceof SlothletError)throw error;throw new SlothletError("CONTEXT_EXECUTION_FAILED",{instanceID},error)}})}#wrapClassInstanceResult(value,instanceID,currentWrapper){if(runtime_isClassInstance(value)){const instanceCache=new WeakMap;return runtime_wrapClassInstance(value,this,instanceID,instanceCache,currentWrapper)}return value}getContext(){const store=this.als.getStore();if(!store){throw new SlothletError("NO_ACTIVE_CONTEXT_ASYNC",{},null,{validationError:true})}return store}tryGetContext(instanceID){if(!this.als)return void 0;const store=this.als.getStore();if(instanceID===void 0)return store;if(store&&(store.instanceID===instanceID||store.parentInstanceID===instanceID)){return store}return this.instances.get(instanceID)}getCallerIdentity(instanceID){const store=this.tryGetContext(instanceID);if(!store)return void 0;return{currentWrapper:store.currentWrapper,callerWrapper:store.callerWrapper}}cleanup(instanceID){const store=this.instances.get(instanceID);if(!store){throw new SlothletError("CONTEXT_NOT_FOUND",{instanceID,availableInstances:Array.from(this.instances.keys()).join(", ")||"none"},null,{validationError:true})}store.self={};store.context={};this.instances.delete(instanceID)}getDiagnostics(){return{type:"async",activeStore:this.als.getStore()?.instanceID||null,instances:Array.from(this.instances.entries()).map(([id,store])=>({id,createdAt:store.createdAt,contextKeys:Object.keys(store.context),selfKeys:Object.keys(store.self)}))}}}const asyncContextManager=new AsyncContextManager;export{AsyncContextManager,asyncContextManager};
@@ -14,4 +14,4 @@
14
14
  limitations under the License.
15
15
  */
16
16
 
17
- const ____COLLISION_MERGED_PROPERTY=Symbol("collisionMergedProperty");import{isNode,util}from"@cldmv/slothlet/helpers/platform";import{ComponentBase}from"#factories/component-base";import{TRUSTED_ROOT,genuineWrappers}from"#handlers/trusted-root";import{isFrameworkInternal,isFrameworkMarkerKey}from"#handlers/framework-internals";const ERROR_HOOK_PROCESSED=Symbol.for("@cldmv/slothlet/hook-error-processed");const hasOwn=(obj,key)=>Object.prototype.hasOwnProperty.call(obj,key);function resolveEnforcedCaller(wrapper,ctxOverride){const ownInstanceID=wrapper.slothlet.instanceID;const ctx=ctxOverride!==void 0?ctxOverride:wrapper.slothlet.contextManager?.tryGetContext?.(ownInstanceID);const identity=ctxOverride!==void 0?ctxOverride:wrapper.slothlet.contextManager?.getCallerIdentity?.(ownInstanceID);if(identity?.unresolved)return{verdict:"deny"};const callerWrapper=identity?.currentWrapper;if(!callerWrapper){const store=ctx??wrapper.slothlet.contextManager?.instances?.get(wrapper.slothlet.instanceID);if(store&&store[TRUSTED_ROOT]===true)return{verdict:"allow"};if(wrapper.slothlet.config?.permissions?.failOpenOnAbsentCaller)return{verdict:"allow"};return{verdict:"deny"}}if(!genuineWrappers.has(callerWrapper))return{verdict:"deny"};return{verdict:"enforce",callerWrapper,ctx}}function runtime_enforceReadGate(wrapper,prop,resolvedValue,callerOverride){const pm=wrapper.slothlet.handlers?.permissionManager;if(!pm||!pm.isEnabled()||!pm.isReadGatingEnabled())return;if(!runtime_isTerminalData(resolvedValue))return;const targetPath=wrapper.____slothletInternal.apiPath+"."+String(prop);const decision=runtime_readGateDecision(wrapper,targetPath,callerOverride);if(decision.allowed)return;throw new wrapper.SlothletError("PERMISSION_DENIED",{caller:decision.caller,target:targetPath})}function runtime_isTerminalData(value){return value!==Object(value)||value instanceof Map||value instanceof Set||value instanceof WeakMap||value instanceof WeakSet||value instanceof Date||value instanceof RegExp||value instanceof Promise||value instanceof Error||ArrayBuffer.isView(value)||value instanceof ArrayBuffer}function runtime_readGateDecision(wrapper,targetPath,callerOverride){if(isFrameworkInternal(wrapper)){const leafKey=targetPath.slice(targetPath.lastIndexOf(".")+1);if(isFrameworkMarkerKey(leafKey))return{allowed:true,caller:null}}const decision=resolveEnforcedCaller(wrapper,callerOverride);if(decision.verdict==="allow"){const hostPm=wrapper.slothlet.handlers.permissionManager;if(hostPm.isPrivateTarget?.(targetPath)&&!hostPm.enforceAccess(null,targetPath,null,wrapper.____slothletInternal.filePath,null)){return{allowed:false,caller:null}}return{allowed:true,caller:null}}if(decision.verdict==="deny")return{allowed:false,caller:null};const{callerWrapper,ctx}=decision;const callerPath=callerWrapper.____slothletInternal?.apiPath??"";const callerFilePath=callerWrapper.____slothletInternal?.filePath??null;const targetFilePath=wrapper.____slothletInternal.filePath??null;const allowed=wrapper.slothlet.handlers.permissionManager.enforceAccess(callerPath,targetPath,callerFilePath,targetFilePath,ctx.context??null);return{allowed,caller:callerPath}}function runtime_isReadRedacted(wrapper,prop){const pm=wrapper.slothlet.handlers?.permissionManager;if(!pm||!pm.isEnabled()||!pm.isReadGatingEnabled())return false;const impl=wrapper.____slothletInternal?.impl;const desc=(impl&&(typeof impl==="object"||typeof impl==="function")?Object.getOwnPropertyDescriptor(impl,prop):void 0)??Object.getOwnPropertyDescriptor(wrapper,prop);if(!desc||!("value"in desc)||!runtime_isTerminalData(runtime_unwrapLeafValue(desc.value)))return false;const targetPath=wrapper.____slothletInternal.apiPath+"."+String(prop);return!runtime_readGateDecision(wrapper,targetPath).allowed}function runtime_unwrapLeafValue(value){let current=value;for(let depth=0;depth<8;depth++){if(!current||typeof current!=="object"&&typeof current!=="function")return current;const inner=_proxyRegistry.get(current)??(hasOwn(current,"____slothletInternal")?current:null);if(!inner)return current;current=inner.____slothletInternal?.impl}return current}function runtime_redactSerialized(wrapper,data,basePath,seen){if(!data||typeof data!=="object"||Array.isArray(data)||seen.has(data))return;seen.add(data);for(const key of Object.keys(data)){const value=data[key];const targetPath=`${basePath}.${key}`;if(runtime_isTerminalData(value)){if(!runtime_readGateDecision(wrapper,targetPath).allowed)delete data[key]}else{runtime_redactSerialized(wrapper,value,targetPath,seen)}}}function enforcePermission(wrapper){const permissionManager=wrapper.slothlet.handlers?.permissionManager;if(!permissionManager||!permissionManager.isEnabled())return;const targetPath=wrapper.____slothletInternal.apiPath;const decision=resolveEnforcedCaller(wrapper);if(decision.verdict==="allow"){if(permissionManager.isPrivateTarget?.(targetPath)&&!permissionManager.enforceAccess(null,targetPath,null,wrapper.____slothletInternal.filePath,null)){throw new wrapper.SlothletError("PERMISSION_DENIED",{caller:null,target:targetPath})}return}if(decision.verdict==="deny"){throw new wrapper.SlothletError("PERMISSION_DENIED",{caller:null,target:targetPath})}const{callerWrapper,ctx}=decision;const callerPath=callerWrapper.____slothletInternal?.apiPath??"";const callerFilePath=callerWrapper.____slothletInternal?.filePath??null;const targetFilePath=wrapper.____slothletInternal.filePath??null;const runtimeContext=ctx?.context??null;if(!permissionManager.enforceAccess(callerPath,targetPath,callerFilePath,targetFilePath,runtimeContext)){throw new wrapper.SlothletError("PERMISSION_DENIED",{caller:callerPath,target:targetPath})}}const capturedViews=new WeakMap;function runtime_enforceCapturedCaller(wrapper,capturedCaller,targetPathOverride){const permissionManager=wrapper.slothlet.handlers?.permissionManager;if(!permissionManager||!permissionManager.isEnabled())return;const targetPath=targetPathOverride??wrapper.____slothletInternal.apiPath;const callerPath=capturedCaller.____slothletInternal?.apiPath??"";const callerFilePath=capturedCaller.____slothletInternal?.filePath??null;const targetFilePath=wrapper.____slothletInternal.filePath??null;const runtimeContext=wrapper.slothlet.contextManager?.tryGetContext?.()?.context??null;if(!permissionManager.enforceAccess(callerPath,targetPath,callerFilePath,targetFilePath,runtimeContext)){throw new wrapper.SlothletError("PERMISSION_DENIED",{caller:callerPath,target:targetPath})}}function runtime_capturedView(child,capturedCaller){let byChild=capturedViews.get(capturedCaller);if(!byChild){byChild=new WeakMap;capturedViews.set(capturedCaller,byChild)}const existing=byChild.get(child);if(existing)return existing;const inner=resolveWrapper(child);const view=new Proxy(child,{apply(target,thisArg,args){runtime_enforceCapturedCaller(inner,capturedCaller);return Reflect.apply(target,thisArg,args)},construct(target,args,newTarget){runtime_enforceCapturedCaller(inner,capturedCaller);return Reflect.construct(target,args,newTarget===view?target:newTarget)},get(target,prop){const resolved=Reflect.get(target,prop);if(resolved!==void 0&&typeof prop==="string"&&runtime_isTerminalData(resolved)){const context=inner.slothlet.contextManager?.tryGetContext?.()?.context??null;runtime_enforceReadGate(inner,prop,resolved,{currentWrapper:capturedCaller,context});return resolved}if(resolveWrapper(resolved)===null)return resolved;return runtime_capturedView(resolved,capturedCaller)}});byChild.set(child,view);return view}function runtime_bindCapturedIdentity(wrapper,prop,value){if(typeof prop!=="string")return value;if(value===null||typeof value!=="object"&&typeof value!=="function")return value;const permissionManager=wrapper.slothlet.handlers?.permissionManager;if(!permissionManager||!permissionManager.isEnabled())return value;if(permissionManager.isCaptureEnabled?.()===false)return value;const inner=resolveWrapper(value);if(inner===null)return value;const innerPath=inner.____slothletInternal?.apiPath;if(!innerPath||innerPath.split(".").pop()!==prop)return value;const capturedCaller=wrapper.slothlet.contextManager?.getCallerIdentity?.()?.currentWrapper;if(!capturedCaller)return value;return runtime_capturedView(value,capturedCaller)}function runtime_guardPromotedResult(promise,path,SlothletErrorCtor){const refuse=()=>{throw new SlothletErrorCtor("HOOK_PROMOTED_RESULT_NOT_AWAITED",{path},null,{validationError:true})};return new Proxy(promise,{get(target,prop,receiver){if(prop===Symbol.toPrimitive||prop==="valueOf"||prop==="toString"||prop==="toJSON"){return refuse}const value=Reflect.get(target,prop,receiver);if(prop==="then"||prop==="catch"||prop==="finally")return value.bind(target);return value}})}function unwrapError(error){if(error&&error.name==="SlothletError"&&error.originalError){return error.originalError}return error}const wrapperDebugEnabled=isNode&&(process.env.SLOTHLET_DEBUG_WRAPPER==="1"||process.env.SLOTHLET_DEBUG_WRAPPER==="true"||process.env.SLOTHLET_DEBUG_SCRIPT_VERBOSE==="1"||process.env.SLOTHLET_DEBUG_SCRIPT_VERBOSE==="true");const IMPL_METADATA_KEYS=new Set(["__childFilePaths","__filePath","__childFilePathsPreMaterialize"]);function isFrameworkReservedKey(key){if(typeof key!=="string")return false;return UnifiedWrapper.INTERNAL_KEYS.has(key)||IMPL_METADATA_KEYS.has(key)}const TYPE_STATES={UNMATERIALIZED:Symbol("unmaterialized"),IN_FLIGHT:Symbol("inFlight")};function getSafeFunctionName(apiPath,fallback){const parts=String(apiPath||"").split(".").filter(part=>part&&part!=="null");const baseName=parts.length>0?parts[parts.length-1]:"";let safeName=String(baseName||"").replace(/[^A-Za-z0-9_$]/g,"_");if(!safeName||!/^[A-Za-z_$]/.test(safeName[0])){safeName=safeName?`_${safeName}`:""}return safeName||fallback}function createNamedProxyTarget(nameHint,fallback){const safeName=getSafeFunctionName(nameHint,fallback);return{[safeName]:function(){}}[safeName]}const _proxyRegistry=new WeakMap;class UnifiedWrapper extends ComponentBase{#internal=null;get ____slothletInternal(){if(!(#internal in this))return void 0;return this.#internal}constructor(slothlet,{mode,apiPath,initialImpl=null,materializeFunc=null,isCallable,materializeOnCreate=false,filePath=null,moduleID=null,sourceFolder=null}){super(slothlet);const isCallableExplicit=typeof isCallable==="boolean";const isCallableValue=isCallableExplicit?isCallable:typeof initialImpl==="function"||initialImpl&&typeof initialImpl.default==="function";const isCallableLocked=isCallableValue||isCallableExplicit;const internal=Object.create(null);internal.id=Math.random().toString(36).substr(2,9);internal.mode=mode;internal.apiPath=apiPath;internal.materializeOnCreate=materializeOnCreate;internal.isCallable=isCallableValue;internal.isCallableLocked=isCallableLocked;internal.moduleID=moduleID;internal.filePath=filePath;internal.sourceFolder=sourceFolder;internal.invalid=false;internal.state={materialized:initialImpl!==null,inFlight:false,collisionMode:"merge"};internal.displayName=apiPath?`${String(apiPath).replace(/\./g,"__")}__UnifiedWrapper`:"UnifiedWrapper";this.#internal=internal;const wrapper=this;Object.defineProperty(internal,"wrapper",{get(){return wrapper},enumerable:false,configurable:false});internal.callableImpl=null;internal.waitingProxyCache=new Map;internal.waitingProxyCacheByContext=new WeakMap;internal.proxy=null;internal.impl=UnifiedWrapper._cloneImpl(initialImpl);internal.materializeFunc=materializeFunc;if(filePath&&slothlet.handlers?.lifecycle){slothlet.handlers.lifecycle.emit("impl:created",{apiPath,impl:this,wrapper:Object.freeze({__impl:this.____slothletInternal.impl}),source:"initial",moduleID,filePath,sourceFolder:sourceFolder||slothlet.config?.dir})}if(initialImpl!==null&&filePath&&slothlet.handlers?.lifecycle){slothlet.handlers.lifecycle.emit("impl:created",{apiPath,impl:initialImpl,wrapper:Object.freeze({__impl:this.____slothletInternal.impl}),source:"initial",moduleID,filePath,sourceFolder:sourceFolder||slothlet.config?.dir})}if(initialImpl!==null){const implKeys=Object.keys(initialImpl||{});if((wrapperDebugEnabled||this.____config?.debug?.wrapper)&&apiPath&&(apiPath==="config"||apiPath.startsWith("config."))){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_WRAPPER_CONSTRUCTOR_IMPL_KEYS",apiPath,keyCount:implKeys.length,keySample:implKeys.slice(0,5)})}this.___adoptImplChildren();if((wrapperDebugEnabled||this.____config?.debug?.wrapper)&&apiPath&&(apiPath==="config"||apiPath.startsWith("config."))){const childKeys=Object.keys(this).filter(k=>!k.startsWith("_")&&!k.startsWith("__"));this.slothlet.debug("wrapper",{key:"DEBUG_MODE_WRAPPER_CONSTRUCTOR_AFTER_ADOPT",apiPath,childCount:childKeys.length,childKeySample:childKeys.slice(0,5)})}}if(mode==="lazy"){slothlet._registerLazyWrapper();if(slothlet.config.tracking?.materialization){setImmediate(()=>{this._materialize().catch(err=>{if(slothlet.config?.debug?.materialize){slothlet.debug("materialize",{key:"DEBUG_MODE_BACKGROUND_MATERIALIZE_ERROR",apiPath:this.____slothletInternal?.apiPath,error:err.message})}})})}}}____inspectCustom(____depth,____options,____inspect){const w=_proxyRegistry.get(this)??this;const childKeys=Object.keys(w).filter(k=>!k.startsWith("_")&&!k.startsWith("__"));if(childKeys.length>0&&!w.____slothletInternal?.isCallable){const inspectObj={};for(const key of childKeys){inspectObj[key]=w[key]}return inspectObj}if(w.____slothletInternal?.mode==="lazy"&&w.____slothletInternal?.state&&!w.____slothletInternal?.state.materialized&&w.____slothletInternal?.proxy){return w.____slothletInternal.proxy}return w.____slothletInternal?.impl}get __impl(){return this.____slothletInternal.impl}static _cloneImpl(value){if(value&&typeof value==="object"&&!Array.isArray(value)&&typeof value!=="function"){const isProxy=util.types.isProxy(value);if(isProxy){if(resolveWrapper(value)){const clone={};for(const key of Reflect.ownKeys(value)){try{clone[key]=value[key]}catch{}}return clone}return value}const uw_cloneDescriptors=Object.getOwnPropertyDescriptors(value);return Object.create(Object.getPrototypeOf(value),uw_cloneDescriptors)}return value}static _extractFullImpl(wrapper){if(!wrapper)return null;const impl=wrapper.____slothletInternal.impl;if(impl===null||impl===void 0)return impl;if(typeof impl!=="object"&&typeof impl!=="function")return impl;if(typeof impl==="function")return impl;if(Array.isArray(impl))return impl.slice();const extractFullImpl_result={};for(const key of Object.keys(impl)){if(isFrameworkReservedKey(key))continue;extractFullImpl_result[key]=impl[key]}if(impl.__childFilePaths){extractFullImpl_result.__childFilePaths=impl.__childFilePaths}if(impl.__childFilePathsPreMaterialize){extractFullImpl_result.__childFilePathsPreMaterialize=impl.__childFilePathsPreMaterialize}for(const key of Object.keys(wrapper)){if(UnifiedWrapper.INTERNAL_KEYS.has(key))continue;if(key in extractFullImpl_result)continue;const extractFullImpl_child=wrapper[key];const _extractChildW=resolveWrapper(extractFullImpl_child);if(_extractChildW){extractFullImpl_result[key]=UnifiedWrapper._extractFullImpl(_extractChildW)}else{extractFullImpl_result[key]=extractFullImpl_child}}return extractFullImpl_result}_applyNewImpl(newImpl,forceReuseChildren=false){this.____slothletInternal.impl=UnifiedWrapper._cloneImpl(newImpl);this.____slothletInternal.invalid=false;if(!this.____slothletInternal.isCallableLocked&&!this.____slothletInternal.isCallable&&(typeof newImpl==="function"||newImpl&&typeof newImpl.default==="function")){this.____slothletInternal.isCallable=true;this.____slothletInternal.isCallableLocked=true}if(!this.____slothletInternal.filePath&&this.____slothletInternal.impl&&this.____slothletInternal.impl.__filePath){this.____slothletInternal.filePath=this.____slothletInternal.impl.__filePath;this.slothlet.debug("wrapper",{key:"DEBUG_MODE_APPLY_IMPL_UPDATE_PATH",apiPath:this.____slothletInternal.apiPath,filePath:this.____slothletInternal.filePath})}this.___adoptImplChildren(forceReuseChildren)}___setImpl(newImpl,moduleID=null,forceReuseChildren=false){if((wrapperDebugEnabled||this.____config?.debug?.wrapper)&&this.____slothletInternal.apiPath==="string"){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_SETIMPL_CALLED",apiPath:this.____slothletInternal.apiPath,newImplKeys:Object.keys(newImpl||{})})}this._applyNewImpl(newImpl,forceReuseChildren);if(newImpl&&this.slothlet.handlers?.lifecycle){const wrapperMetadata=this.slothlet.handlers.metadata.getMetadata(this);const extractedModuleId=moduleID||wrapperMetadata?.baseModuleID||null;this.slothlet.handlers.lifecycle.emit("impl:changed",{apiPath:this.____slothletInternal.apiPath,impl:newImpl,wrapper:Object.freeze({__impl:this.____slothletInternal.impl}),source:"hot-reload",moduleID:extractedModuleId,filePath:wrapperMetadata?.filePath,sourceFolder:wrapperMetadata?.sourceFolder})}this.____slothletInternal.state.materialized=true;this.____slothletInternal.state.inFlight=false;if(this.slothlet._onWrapperMaterialized){this.slothlet._onWrapperMaterialized()}}___resetLazy(newMaterializeFunc){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_RESETLAZY_CALLED",apiPath:this.____slothletInternal.apiPath,hadImpl:this.____slothletInternal.impl!==null,hadChildren:Object.keys(this).filter(k=>!k.startsWith("_")&&!k.startsWith("__")).length});for(const key of Reflect.ownKeys(this)){if(typeof key==="string"&&(key.startsWith("_")||key.startsWith("__"))){continue}const child=this[key];const childRaw=resolveWrapper(child);if(childRaw){childRaw.___invalidate()}const descriptor=Object.getOwnPropertyDescriptor(this,key);if(descriptor?.configurable){delete this[key]}}this.____slothletInternal.impl=null;this.____slothletInternal.invalid=false;this.____slothletInternal.state.materialized=false;this.____slothletInternal.state.inFlight=false;this.____slothletInternal.materializationPromise=null;this.____slothletInternal.materializeFunc=newMaterializeFunc;if(this.____slothletInternal.waitingProxyCache){this.____slothletInternal.waitingProxyCache.clear()}this.____slothletInternal.waitingProxyCacheByContext=new WeakMap;this.slothlet.debug("wrapper",{key:"DEBUG_MODE_RESETLAZY_COMPLETE",apiPath:this.____slothletInternal.apiPath})}async ___materialize(){if(this.____slothletInternal.state.materialized){return}if(this.____slothletInternal.invalid){return}if(this.____slothletInternal.materializationPromise){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_MATERIALIZE_AWAIT",apiPath:this.____slothletInternal.apiPath});return this.____slothletInternal.materializationPromise}if((wrapperDebugEnabled||this.____config?.debug?.wrapper)&&this.apiPath==="string"){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_MATERIALIZE_START",apiPath:this.apiPath})}this.____slothletInternal.materializationPromise=(async()=>{this.____slothletInternal.state.inFlight=true;try{if(this.____slothletInternal.materializeFunc){if((wrapperDebugEnabled||this.____config?.debug?.wrapper)&&this.____slothletInternal.apiPath==="string"){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_MATERIALIZE_CALLING_FUNC",apiPath:this.____slothletInternal.apiPath})}const lazy_setImpl=value=>{this._applyNewImpl(value)};const result=await this.____slothletInternal.materializeFunc(lazy_setImpl);if(!this.____slothletInternal.impl){this._applyNewImpl(result)}this.____slothletInternal.state.materialized=true;if(this.slothlet._onWrapperMaterialized){this.slothlet._onWrapperMaterialized()}if((wrapperDebugEnabled||this.____config?.debug?.wrapper)&&this.____slothletInternal.apiPath==="string"){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_MATERIALIZE_COMPLETE",apiPath:this.____slothletInternal.apiPath,resultType:typeof result,resultKeys:Object.keys(result||{})})}}}catch(error){if((wrapperDebugEnabled||this.____config?.debug?.wrapper)&&this.____slothletInternal.apiPath==="string"){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_MATERIALIZE_ERROR",apiPath:this.____slothletInternal.apiPath,error:error.message})}throw error}finally{this.____slothletInternal.state.inFlight=false;this.____slothletInternal.materializationPromise=null}})();return this.____slothletInternal.materializationPromise}_materialize(){return this.___materialize()}___invalidate(){this.____slothletInternal.invalid=true;this.____slothletInternal.impl=null;for(const key of Reflect.ownKeys(this)){if(typeof key==="string"&&(key.startsWith("_")||key.startsWith("__"))){continue}const descriptor=Object.getOwnPropertyDescriptor(this,key);if(descriptor?.configurable){delete this[key]}}}___adoptImplChildren(forceReuseChildren=false){const preExistingKeys=Object.keys(this).filter(k=>!k.startsWith("_")&&!k.startsWith("__"));this.slothlet.debug("wrapper",{key:"DEBUG_MODE_ADOPT_START",apiPath:this.____slothletInternal.apiPath,wrapperId:this.____slothletInternal.id||"no-id",preExistingKeys:preExistingKeys.join(","),collisionMode:this.____slothletInternal.state.collisionMode});if(!this.____slothletInternal.impl||typeof this.____slothletInternal.impl!=="object"&&typeof this.____slothletInternal.impl!=="function"){return}if(util.types.isProxy(this.____slothletInternal.impl))return;if(Array.isArray(this.____slothletInternal.impl))return;const ownKeys=Reflect.ownKeys(this.____slothletInternal.impl);const internalKeys=new Set(["__impl","___setImpl","___resetLazy","_materialize","_impl","_state","_invalid","____slothlet","____slothletInternal"]);const keepImplProperties=typeof this.____slothletInternal.impl==="function"||this.____slothletInternal.impl&&typeof this.____slothletInternal.impl==="object"&&typeof this.____slothletInternal.impl.default==="function";if(keepImplProperties&&this.____slothletInternal.impl&&typeof this.____slothletInternal.impl==="object"&&typeof this.____slothletInternal.impl.default==="function"){internalKeys.add("default")}const observedKeys=new Set;const existingKeys=Object.keys(this).filter(k=>!k.startsWith("_")&&!k.startsWith("__"));const storedCollisionMode=this.____slothletInternal.state.collisionMode;const isMergeScenario=storedCollisionMode!=="replace"&&existingKeys.length>0;this.slothlet.debug("wrapper",{key:"DEBUG_MODE_ADOPT",apiPath:this.____slothletInternal.apiPath,mode:this.____slothletInternal.mode,storedCollisionMode,existingKeys:existingKeys.join(","),isMergeScenario});const savedChildren=new Map;if(storedCollisionMode==="replace"&&existingKeys.length>0){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_ADOPT_REPLACE_CLEARING",count:existingKeys.length});for(const key of existingKeys){const child=this[key];if(resolveWrapper(child)!==null){savedChildren.set(key,child)}const descriptor=Object.getOwnPropertyDescriptor(this,key);if(descriptor?.configurable){delete this[key]}}}else{for(const key of existingKeys){observedKeys.add(key)}}const metadataKeys=new Set(["__childFilePaths","__filePath","__childFilePathsPreMaterialize"]);const skipKeys=typeof this.____slothletInternal.impl==="function"?new Set(["length","name","prototype"]):null;for(const key of ownKeys){if(internalKeys.has(key)){continue}if(typeof key==="string"&&metadataKeys.has(key)){continue}if(skipKeys&&typeof key==="string"&&skipKeys.has(key)){continue}if(!this.____slothletInternal.impl||typeof this.____slothletInternal.impl!=="object"&&typeof this.____slothletInternal.impl!=="function"){break}const descriptor=Object.getOwnPropertyDescriptor(this.____slothletInternal.impl,key);if(!descriptor){continue}const value=this.____slothletInternal.impl[key];if(value===this.____slothletInternal.impl){continue}if(typeof key!=="symbol"){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_ADOPT_PROCESS",apiPath:this.____slothletInternal.apiPath,propKey:key,typeOf:typeof value,valueName:value?.name})}observedKeys.add(key);if(hasOwn(this,key)&&!key.toString().startsWith("_")){if(typeof key!=="symbol"){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_ADOPT_CHECK",apiPath:this.____slothletInternal.apiPath,propKey:key,has__collisionMergedKeys:!!this.____slothletInternal.collisionMergedKeys,inSet:this.____slothletInternal.collisionMergedKeys?.has(key)})}const isCollisionMerged=this.____slothletInternal.collisionMergedKeys&&this.____slothletInternal.collisionMergedKeys.has(key);if(isCollisionMerged&&!forceReuseChildren){if(typeof key!=="symbol"){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_ADOPT_SKIP_COLLISION_MERGED",apiPath:this.____slothletInternal.apiPath,propKey:key})}if(descriptor.configurable){delete this.____slothletInternal.impl[key]}continue}if(typeof key!=="symbol"){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_ADOPT_ALLOW_NOT_COLLISION_MERGED",apiPath:this.____slothletInternal.apiPath,propKey:key})}}const existingChild=savedChildren.get(key)||this[key];let wrapped;const skipChildReuse=!forceReuseChildren&&this.____slothletInternal.mode==="lazy"&&storedCollisionMode==="replace";if(!skipChildReuse&&existingChild&&resolveWrapper(existingChild)!==null){if(resolveWrapper(value)!==null){const newWrapper=resolveWrapper(value);let rawImpl=newWrapper?newWrapper.____slothletInternal.impl:null;if(rawImpl&&typeof rawImpl==="object"&&!Array.isArray(rawImpl)&&typeof rawImpl!=="function"&&Object.keys(rawImpl).filter(k=>!k.startsWith("__")).length===0){const wrapperOwnKeys=Object.keys(newWrapper).filter(k=>!k.startsWith("_")&&!k.startsWith("__"));if(wrapperOwnKeys.length>0){rawImpl=UnifiedWrapper._extractFullImpl(newWrapper)}}if(rawImpl!==null&&rawImpl!==void 0){resolveWrapper(existingChild).___setImpl(rawImpl,this.____slothletInternal.moduleID,true)}else if(newWrapper&&newWrapper.____slothletInternal.materializeFunc){const existingChildWrapper=resolveWrapper(existingChild);if(existingChildWrapper){existingChildWrapper.___resetLazy(newWrapper.____slothletInternal.materializeFunc)}}wrapped=existingChild}else{resolveWrapper(existingChild).___setImpl(value,this.____slothletInternal.moduleID,true);wrapped=existingChild}if(typeof key!=="symbol"){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_ADOPT_REUSE_CHILD_WRAPPER",apiPath:this.____slothletInternal.apiPath,propKey:key})}}else{wrapped=this.___createChildWrapper(key,value);if(typeof key!=="symbol"){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_ADOPT_WRAP",apiPath:this.____slothletInternal.apiPath,propKey:key,wrapped:wrapped?"YES":wrapped===null?"NULL":"NO"})}}if(wrapped){const existing=this[key];const existingDescriptor=Object.getOwnPropertyDescriptor(this,key);if(existing===wrapped||existingDescriptor&&!existingDescriptor.configurable){if(typeof key!=="symbol"){this.slothlet.debug("wrapper",{key:existingDescriptor&&!existingDescriptor.configurable?"DEBUG_MODE_ADOPT_SKIP_NON_CONFIGURABLE":"DEBUG_MODE_ADOPT_SKIP_SAME_WRAPPER",apiPath:this.____slothletInternal.apiPath,propKey:key})}}else{if(typeof key!=="symbol"){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_ADOPT_DEFINE",apiPath:this.____slothletInternal.apiPath,propKey:key})}Object.defineProperty(this,key,{value:wrapped,writable:false,enumerable:true,configurable:true});if(typeof key!=="symbol"){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_ADOPT_DEFINED",apiPath:this.____slothletInternal.apiPath,propKey:key})}}if(descriptor.configurable&&!keepImplProperties&&this.____slothletInternal.impl){delete this.____slothletInternal.impl[key]}}else if(wrapped===null){Object.defineProperty(this,key,{value,writable:false,enumerable:true,configurable:true});if(descriptor.configurable&&!keepImplProperties&&this.____slothletInternal.impl){delete this.____slothletInternal.impl[key]}}else{Object.defineProperty(this,key,{value,writable:false,enumerable:true,configurable:true});if(descriptor.configurable&&!keepImplProperties&&this.____slothletInternal.impl){delete this.____slothletInternal.impl[key]}}}if(!isMergeScenario){const currentKeys=Object.keys(this).filter(k=>!k.startsWith("_")&&!k.startsWith("__"));for(const key of currentKeys){if(!observedKeys.has(key)){const existing=this[key];const existingRaw=resolveWrapper(existing);if(existingRaw){existingRaw.___invalidate()}const descriptor=Object.getOwnPropertyDescriptor(this,key);if(descriptor?.configurable){delete this[key]}}}}if(this._mergeAfterMaterialize){const{existingWrapper,isMergeReplace:____isMergeReplace}=this._mergeAfterMaterialize;const existingKeys2=Object.keys(existingWrapper).filter(k=>!k.startsWith("_")&&!k.startsWith("__"));for(const key of existingKeys2){if(!(key in this)||key.startsWith("_")||key.startsWith("__")){const child=existingWrapper[key];Object.defineProperty(this,key,{value:child,writable:false,enumerable:true,configurable:true})}}delete this._mergeAfterMaterialize}}___createChildWrapper(key,value){if(value===void 0){return void 0}if(value===null){return null}if(value&&resolveWrapper(value)!==null){return value}if(value instanceof Map||value instanceof Set||value instanceof WeakMap||value instanceof WeakSet||value instanceof Date||value instanceof RegExp||value instanceof Promise||value instanceof Error||ArrayBuffer.isView(value)||value instanceof ArrayBuffer){return null}let childImpl=value;if(this.____slothletInternal.mode==="eager"&&childImpl&&typeof childImpl==="object"){if(Array.isArray(childImpl)){childImpl=childImpl.slice()}else{const descriptors=Object.getOwnPropertyDescriptors(childImpl);childImpl=Object.create(Object.getPrototypeOf(childImpl),descriptors)}}const parentMetadata=this.slothlet.handlers?.metadata?.getMetadata(this);const childExistingMetadata=this.slothlet.handlers?.metadata?.getMetadata(value);let childFilePath=childExistingMetadata?.filePath||null;let childModuleId=null;if(!childFilePath){const keyStr=typeof key==="symbol"?String(key):key;this.slothlet.debug("wrapper",{key:"DEBUG_MODE_WRAP_CHILD_PATH_CHECK",apiPath:this.apiPath,propKey:keyStr,has_impl:!!this.____slothletInternal.impl,has__childFilePaths:!!(this.____slothletInternal.impl&&this.____slothletInternal.impl.__childFilePaths),has__childFilePathsPreMaterialize:!!this.____slothletInternal.childFilePathsPreMaterialize,parentFilePath:parentMetadata?.filePath});if(this.____slothletInternal.impl&&this.____slothletInternal.impl.__childFilePaths){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_WRAP_CHILD_PATH_AVAILABLE",keys:Object.keys(this.____slothletInternal.impl.__childFilePaths).join(","),propKey:keyStr,found:!!this.____slothletInternal.impl.__childFilePaths[key]})}if(this.____slothletInternal.impl&&this.____slothletInternal.impl.__childFilePaths&&this.____slothletInternal.impl.__childFilePaths[key]){childFilePath=this.____slothletInternal.impl.__childFilePaths[key];this.slothlet.debug("wrapper",{key:"DEBUG_MODE_WRAP_CHILD_PATH_USING",childFilePath})}else if(this.____slothletInternal.childFilePathsPreMaterialize&&this.____slothletInternal.childFilePathsPreMaterialize[key]){childFilePath=this.____slothletInternal.childFilePathsPreMaterialize[key];this.slothlet.debug("wrapper",{key:"DEBUG_MODE_WRAP_CHILD_PATH_PRE_MAT",childFilePath})}else{childFilePath=parentMetadata?.filePath||null;this.slothlet.debug("wrapper",{key:"DEBUG_MODE_WRAP_CHILD_PATH_FALLBACK",childFilePath})}}if(parentMetadata?.baseModuleID){childModuleId=parentMetadata.baseModuleID}const childSourceFolder=childExistingMetadata?.sourceFolder||parentMetadata?.sourceFolder||null;const nestedWrapper=new UnifiedWrapper(this.slothlet,{mode:"eager",apiPath:this.____slothletInternal.apiPath?`${this.____slothletInternal.apiPath}.${typeof key==="symbol"?String(key):key}`:String(key),initialImpl:childImpl,isCallable:typeof childImpl==="function",filePath:childFilePath,moduleID:childModuleId,sourceFolder:childSourceFolder});return nestedWrapper.createProxy()}___createWaitingProxy(propChain=[]){const wrapper=this;const __readGateStore=wrapper.slothlet.contextManager?.tryGetContext?.();const __readGateCaller=__readGateStore?{currentWrapper:wrapper.slothlet.contextManager?.getCallerIdentity?.()?.currentWrapper??null,context:__readGateStore.context,[TRUSTED_ROOT]:__readGateStore[TRUSTED_ROOT]===true}:null;const __callerKey=__readGateCaller?.currentWrapper?.____slothletInternal?.apiPath??"";const cacheKey=`${__callerKey}::${propChain.join(".")}`;const __readGateContextRef=__readGateStore?.context??null;const useContextBucket=__readGateContextRef&&typeof __readGateContextRef==="object";let cache;if(useContextBucket){cache=wrapper.____slothletInternal.waitingProxyCacheByContext.get(__readGateContextRef);if(!cache){cache=new Map;wrapper.____slothletInternal.waitingProxyCacheByContext.set(__readGateContextRef,cache)}}else{cache=wrapper.____slothletInternal.waitingProxyCache}if(cache.has(cacheKey)){return cache.get(cacheKey)}const waitingTarget=createNamedProxyTarget(`${wrapper.____slothletInternal.apiPath}_waitingProxy`,"waitingProxyTarget");const waitingProxy=new Proxy(waitingTarget,{get(___target,prop){if(prop==="then"){return(onFulfilled,onRejected)=>{const waitingProxy_thenResolve=async()=>{if(!wrapper.____slothletInternal.state.materialized){await wrapper._materialize()}let current=wrapper;let __gateParent=null;let __gateProp=null;const __descendRest=(startValue,nextIndex)=>{let descended=startValue;for(let __di=nextIndex;__di<propChain.length;__di++){if(descended===null||descended===void 0)return void 0;descended=descended[propChain[__di]]}return descended};for(let __chainIndex=0;__chainIndex<propChain.length;__chainIndex++){const chainProp=propChain[__chainIndex];if(!current)return void 0;if(current.____slothletInternal.impl&&typeof current.____slothletInternal.impl==="object"&&util.types.isProxy(current.____slothletInternal.impl)){let result=current.____slothletInternal.impl;for(let i=__chainIndex;i<propChain.length;i++){result=result[propChain[i]]}return result}const isInternal2=isFrameworkReservedKey(chainProp);if(!isInternal2&&hasOwn(current,chainProp)){const child=current[chainProp];const _childW=resolveWrapper(child);if(_childW){__gateParent=current;__gateProp=chainProp;current=_childW;if(current.____slothletInternal.mode==="lazy"&&!current.____slothletInternal.state.materialized){await current._materialize()}continue}if(__chainIndex<propChain.length-1){const descendedChild=__descendRest(child,__chainIndex+1);if(descendedChild!==void 0){runtime_enforceReadGate(current,propChain.slice(__chainIndex).join("."),descendedChild,__readGateCaller)}return descendedChild}runtime_enforceReadGate(current,chainProp,child,__readGateCaller);return child}if(current.____slothletInternal.impl&&current.____slothletInternal.impl[chainProp]!==void 0){const implValue=current.____slothletInternal.impl[chainProp];if(__chainIndex<propChain.length-1){const descendedImpl=__descendRest(implValue,__chainIndex+1);if(descendedImpl!==void 0){runtime_enforceReadGate(current,propChain.slice(__chainIndex).join("."),descendedImpl,__readGateCaller)}return descendedImpl}runtime_enforceReadGate(current,chainProp,implValue,__readGateCaller);return implValue}return void 0}if(current.____slothletInternal.impl&&typeof current.____slothletInternal.impl==="object"&&util.types.isProxy(current.____slothletInternal.impl)){return current.____slothletInternal.impl}if(__gateParent){runtime_enforceReadGate(__gateParent,__gateProp,current.____slothletInternal.impl,__readGateCaller)}const finalImpl=current.____slothletInternal.impl;const callableCarriesWrapperMembers=typeof finalImpl==="function"&&Object.keys(current).some(key=>!isFrameworkReservedKey(key)&&!Object.prototype.hasOwnProperty.call(finalImpl,key));if(callableCarriesWrapperMembers||finalImpl!==null&&typeof finalImpl==="object"&&!Array.isArray(finalImpl)&&!runtime_isTerminalData(finalImpl)){const resolvedProxy=current.____slothletInternal.proxy;const __capturedReader=__readGateCaller?.currentWrapper??null;const __pm=wrapper.slothlet.handlers?.permissionManager;if(__capturedReader&&__pm&&__pm.isEnabled()&&__pm.isCaptureEnabled?.()!==false){return runtime_capturedView(resolvedProxy,__capturedReader)}return resolvedProxy}return finalImpl};waitingProxy_thenResolve().then(onFulfilled,onRejected)}}if(prop==="____slothletInternal")return void 0;if(prop==="_materialize")return wrapper._materialize.bind(wrapper);if(prop==="__mode")return wrapper.____slothletInternal.mode;if(prop==="__materialized")return wrapper.____slothletInternal.state.materialized;if(prop==="__inFlight")return wrapper.____slothletInternal.state.inFlight;if(wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.state.materialized&&!wrapper.____slothletInternal.state.inFlight){wrapper._materialize().catch(()=>{})}if(prop===util.inspect.custom){if(wrapper.____slothletInternal.state.inFlight){return waitingTarget}if(!wrapper.____slothletInternal.state.materialized){return waitingTarget}if(wrapper.____slothletInternal.impl){let current=wrapper.____slothletInternal.impl;for(const chainProp of propChain){if(!current){return void 0}current=current[chainProp]}return current}return waitingTarget}if(prop==="__type"){wrapper.slothlet.debug("wrapper",{key:"DEBUG_MODE_WAITING_TYPE",apiPath:wrapper.apiPath,propChain:propChain.join(","),materialized:wrapper.____slothletInternal.state.materialized,hasImpl:wrapper.____slothletInternal.impl!==null});if(wrapper.____slothletInternal.state.materialized||wrapper.____slothletInternal.impl!==null&&wrapper.____slothletInternal.impl!==void 0){let current=wrapper.createProxy();for(const chainProp of propChain){if(!current)break;const currentWrapper=resolveWrapper(current);if(currentWrapper){const isInternal2=isFrameworkReservedKey(chainProp);if(!isInternal2&&hasOwn(currentWrapper,chainProp)){current=currentWrapper[chainProp];wrapper.slothlet.debug("wrapper",{key:"DEBUG_MODE_WAITING_TYPE_WALK_WRAPPER",chainProp:String(chainProp),typeOf:typeof current});continue}if(currentWrapper.____slothletInternal.impl&&typeof currentWrapper.____slothletInternal.impl==="object"&&currentWrapper.____slothletInternal.impl!==null&&chainProp in currentWrapper.____slothletInternal.impl){current=currentWrapper.____slothletInternal.impl[chainProp];wrapper.slothlet.debug("wrapper",{key:"DEBUG_MODE_WAITING_TYPE_WALK_IMPL",chainProp:String(chainProp),typeOf:typeof current});continue}}wrapper.slothlet.debug("wrapper",{key:"DEBUG_MODE_WAITING_TYPE_WALK_DIRECT",chainProp:String(chainProp),typeOf:typeof current});current=current[chainProp]}const resolvedType=typeof current==="function"?"function":typeof current==="object"&&current!==null?"object":typeof current;wrapper.slothlet.debug("wrapper",{key:"DEBUG_MODE_WAITING_TYPE_RESOLVED",apiPath:wrapper.apiPath,propChain:propChain.join(","),resolvedType});return resolvedType}wrapper.slothlet.debug("wrapper",{key:"DEBUG_MODE_WAITING_TYPE_INFLIGHT",apiPath:wrapper.apiPath,propChain:propChain.join(",")});return TYPE_STATES.IN_FLIGHT}if(prop==="__metadata"){if(wrapper.slothlet.handlers?.metadata){return wrapper.slothlet.handlers.metadata.getMetadata(wrapper)}return{}}if(typeof prop==="symbol")return void 0;if(prop==="length"){return 0}if(prop==="name")return waitingTarget.name||"waitingProxyTarget";if(prop==="toString"){return Function.prototype.toString.bind(waitingTarget)}if(prop==="valueOf"){return Function.prototype.valueOf.bind(waitingTarget)}if(prop==="toJSON"){return()=>void 0}if(prop==="__slothletPath")return wrapper.____slothletInternal.apiPath;if(wrapper.____slothletInternal.impl!==null&&wrapper.____slothletInternal.impl!==void 0&&typeof wrapper.____slothletInternal.impl==="object"&&util.types.isProxy(wrapper.____slothletInternal.impl)){let result=wrapper.____slothletInternal.impl;for(const chainProp of propChain){result=result[chainProp]}return result[prop]}if(wrapper.____slothletInternal.impl!==null&&wrapper.____slothletInternal.impl!==void 0){let current=wrapper;let remainingChain=[...propChain];for(let i=0;i<propChain.length;i++){const chainProp=propChain[i];if(current.____slothletInternal.impl&&typeof current.____slothletInternal.impl==="object"&&util.types.isProxy(current.____slothletInternal.impl)){let proxyResult=current.____slothletInternal.impl;for(const remainingProp of remainingChain){proxyResult=proxyResult[remainingProp]}return proxyResult[prop]}const isInternal2=isFrameworkReservedKey(chainProp);if(!isInternal2&&current&&hasOwn(current,chainProp)){const cached=current[chainProp];const _cachedW2=resolveWrapper(cached);if(_cachedW2){current=_cachedW2;remainingChain.shift()}else{return void 0}}else{return void 0}}if(current&&current.____slothletInternal.impl&&typeof current.____slothletInternal.impl==="object"&&util.types.isProxy(current.____slothletInternal.impl)){return current.____slothletInternal.impl[prop]}const isFinalInternal=isFrameworkReservedKey(prop);if(!isFinalInternal&&hasOwn(current,prop)){return current[prop]}return void 0}const isInternal=isFrameworkReservedKey(prop);if(!isInternal&&hasOwn(wrapper,prop)){wrapper.slothlet.debug("wrapper",{key:"DEBUG_MODE_WAITING_GET_PREMATURE",apiPath:wrapper.____slothletInternal.apiPath,prop});return wrapper[prop]}if(wrapper.____slothletInternal.needsImmediateChildAdoption&&wrapper.____slothletInternal.materializeFunc&&!wrapper.____slothletInternal.state.materialized&&!wrapper.____slothletInternal.state.inFlight){wrapper.slothlet.debug("wrapper",{key:"DEBUG_MODE_WAITING_GET_IMMEDIATE_MAT",apiPath:wrapper.____slothletInternal.apiPath,prop});wrapper._materialize().catch(err=>{wrapper.slothlet.debug("wrapper",{key:"DEBUG_MODE_WAITING_GET_IMMEDIATE_MAT_ERROR",apiPath:wrapper.apiPath,error:err.message})});const isInternal2=isFrameworkReservedKey(prop);if(!isInternal2&&hasOwn(wrapper,prop)){wrapper.slothlet.debug("wrapper",{key:"DEBUG_MODE_WAITING_GET_IMMEDIATE_MAT_SUCCESS",apiPath:wrapper.____slothletInternal.apiPath,prop});return wrapper[prop]}}if(wrapper.____slothletInternal.state.inFlight){return wrapper.___createWaitingProxy([...propChain,prop])}return wrapper.___createWaitingProxy([...propChain,prop])},async apply(___target,___thisArg,args){const ___liveCallerWrapper=wrapper.slothlet.contextManager?.getCallerIdentity?.()?.currentWrapper??null;const ___capture=wrapper.slothlet.handlers?.permissionManager?.isCaptureEnabled()!==false;const ___creationCallerWrapper=___capture?__readGateCaller?.currentWrapper??null:null;const ___capturedCallerWrapper=___liveCallerWrapper??___creationCallerWrapper;wrapper.slothlet.debug("wrapper",{key:"DEBUG_MODE_WAITING_APPLY_ENTRY",apiPath:wrapper.____slothletInternal.apiPath,propChain:propChain.join(","),args:args.join(",")});const chainLabel=propChain.map(prop=>String(prop)).join(".");if(wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.state.materialized&&!wrapper.____slothletInternal.state.inFlight){wrapper.slothlet.debug("wrapper",{key:"DEBUG_MODE_WAITING_APPLY_MATERIALIZE",apiPath:wrapper.____slothletInternal.apiPath});await wrapper._materialize();wrapper.slothlet.debug("wrapper",{key:"DEBUG_MODE_WAITING_APPLY_MATERIALIZED",apiPath:wrapper.____slothletInternal.apiPath})}else if(wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.state.materialized&&wrapper.____slothletInternal.state.inFlight){if(wrapper.____slothletInternal.materializationPromise){await wrapper.____slothletInternal.materializationPromise}else{await wrapper._materialize()}}wrapper.slothlet.debug("wrapper",{key:"DEBUG_MODE_WAITING_APPLY_START_WALK",apiPath:wrapper.____slothletInternal.apiPath,propChain:propChain.join(",")});let current=wrapper.createProxy();let lastWrapper=wrapper;let lastObject=null;for(const prop of propChain){wrapper.slothlet.debug("wrapper",{key:"DEBUG_MODE_WAITING_APPLY_WALK",prop:String(prop),typeOf:typeof current,constructorName:current?.constructor?.name});if(!current){if(propChain.some(p=>typeof p==="symbol")){return void 0}if(wrapper.____slothletInternal.invalid||wrapper.____slothletInternal.impl===null||lastWrapper&&(lastWrapper.__invalid||lastWrapper._impl===null)){return void 0}const finalProp=propChain[propChain.length-1];if(finalProp==="hasAttribute"||finalProp==="toJSON"||finalProp===Symbol.toStringTag||finalProp==="constructor"||typeof finalProp==="symbol"||typeof prop==="symbol"){return void 0}throw new wrapper.slothlet.SlothletError("CHAIN_ACCESS_UNDEFINED",{apiPath:wrapper.____slothletInternal.apiPath,chainLabel,prop:String(prop)},null,{validationError:true})}const currentWrapper=resolveWrapper(current);if(currentWrapper){const state=currentWrapper.____slothletInternal.state;if(!state.materialized){if(!state.inFlight&&typeof current._materialize==="function"){await current._materialize()}while(!currentWrapper.____slothletInternal.state.materialized){const nextState=currentWrapper.____slothletInternal.state;if(!nextState.inFlight&&!nextState.materialized){throw new wrapper.slothlet.SlothletError("CHAIN_MATERIALIZE_FAILED",{apiPath:wrapper.____slothletInternal.apiPath,chainLabel,prop:String(prop)},null,{validationError:true})}await new Promise(resolve=>setImmediate(resolve))}}}if(currentWrapper){lastWrapper=currentWrapper;const isInternal=isFrameworkReservedKey(prop);if(!isInternal&&hasOwn(currentWrapper,prop)){lastObject=current;current=currentWrapper[prop];continue}if(currentWrapper.____slothletInternal.impl&&typeof currentWrapper.____slothletInternal.impl==="object"&&currentWrapper.____slothletInternal.impl!==null&&prop in currentWrapper.____slothletInternal.impl){lastObject=currentWrapper.____slothletInternal.impl;current=currentWrapper.____slothletInternal.impl[prop];continue}}lastObject=current;current=current[prop]}wrapper.slothlet.debug("wrapper",{key:"DEBUG_MODE_WAITING_APPLY",apiPath:wrapper.____slothletInternal.apiPath,propChain:propChain.join(","),typeOf:typeof current,currentName:current?.name,isFunction:typeof current==="function"});if(typeof current==="function"){if(___creationCallerWrapper&&___creationCallerWrapper!==___capturedCallerWrapper){const ___resolvedInner=resolveWrapper(current);const ___targetPath=___resolvedInner?.____slothletInternal?.apiPath??[wrapper.____slothletInternal.apiPath,...propChain].filter(Boolean).join(".");runtime_enforceCapturedCaller(wrapper,___creationCallerWrapper,___targetPath)}if(___capturedCallerWrapper&&wrapper.slothlet.contextManager){const ___instanceStore=wrapper.slothlet.contextManager.instances?.get?.(wrapper.instanceID);if(___instanceStore&&!___instanceStore.currentWrapper){return wrapper.slothlet.contextManager.runInContext(wrapper.instanceID,()=>Reflect.apply(current,lastObject,args),null,[],___capturedCallerWrapper,true)}}const ___identityStore=___capturedCallerWrapper?wrapper.slothlet.contextManager?.instances?.get?.(wrapper.instanceID):null;if(!___identityStore)return Reflect.apply(current,lastObject,args);const ___previousAuthoritative=___identityStore.__authoritativeWrapper;___identityStore.__authoritativeWrapper=___capturedCallerWrapper;try{return Reflect.apply(current,lastObject,args)}finally{___identityStore.__authoritativeWrapper=___previousAuthoritative}}const _finalChainProp=propChain[propChain.length-1];if(_finalChainProp==="hasAttribute"||_finalChainProp==="toJSON"){return void 0}if(current===void 0||current===null){throw new wrapper.slothlet.SlothletError("CHAIN_NOT_CALLABLE",{apiPath:wrapper.____slothletInternal.apiPath,chainLabel},null,{validationError:true})}throw new wrapper.slothlet.SlothletError("CHAIN_NOT_CALLABLE",{apiPath:wrapper.____slothletInternal.apiPath,chainLabel},null,{validationError:true})},getPrototypeOf:()=>null});_proxyRegistry.set(waitingProxy,wrapper);cache.set(cacheKey,waitingProxy);return waitingProxy}createProxy(){const wrapper=this;if(wrapper.____slothletInternal.proxy){return wrapper.____slothletInternal.proxy}if(wrapper.____slothletInternal.materializeOnCreate&&wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.state.materialized&&wrapper.____slothletInternal.materializeFunc){wrapper._materialize().catch(()=>{})}const mightBeCallable=wrapper.____slothletInternal.isCallable||wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.isCallableLocked;let proxyTarget;if(mightBeCallable){proxyTarget=createNamedProxyTarget(wrapper.____slothletInternal.apiPath,"callableProxy")}else if(Array.isArray(wrapper.____slothletInternal.impl)){proxyTarget=wrapper.____slothletInternal.impl}else{proxyTarget=wrapper}if(!Array.isArray(proxyTarget)&&!(util.inspect.custom in proxyTarget)){Object.defineProperty(proxyTarget,util.inspect.custom,{value:function(){const childKeys=Object.keys(wrapper).filter(k=>!k.startsWith("_")&&!k.startsWith("__"));if(childKeys.length>0&&!wrapper.____slothletInternal.isCallable){const obj={};for(const key of childKeys){const child=wrapper[key];if(child&&typeof child.createProxy==="function"){obj[key]=child.createProxy()}else{obj[key]=child}}return obj}if(wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.state.materialized&&(wrapper.____slothletInternal.impl===null||wrapper.____slothletInternal.impl===void 0)){return wrapper.____slothletInternal.proxy||wrapper}return wrapper.____slothletInternal.impl},writable:false,enumerable:false,configurable:true})}const getTrap=(target,prop,____receiver)=>{const enforceReadGate=resolvedValue=>runtime_enforceReadGate(wrapper,prop,resolvedValue);if(target!==wrapper&&prop in target){const desc=Object.getOwnPropertyDescriptor(target,prop);if(desc&&!desc.configurable){if(typeof prop==="string"&&prop.startsWith("__")){return wrapper[prop]}return target[prop]}}if(target===wrapper&&typeof prop==="string"){const desc=Object.getOwnPropertyDescriptor(target,prop);if(desc&&!desc.configurable){return target[prop]}}const isInternalProp=isFrameworkReservedKey(prop);const allowedInternals=new Set(["_materialize","__mode","__apiPath","__isCallable","__materializeOnCreate","__displayName","__type","__materialized","__inFlight","__slothletPath","__metadata","__filePath","__sourceFolder","__moduleID"]);if(isInternalProp&&!allowedInternals.has(prop)){return void 0}if(prop==="power"||prop==="add"){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_GET_START",apiPath:wrapper.____slothletInternal.apiPath,prop:String(prop),mode:wrapper.____slothletInternal.mode,collisionMode:wrapper.____slothletInternal.state.collisionMode||"none",materialized:wrapper.____slothletInternal.state.materialized,hasImpl:wrapper.____slothletInternal.impl!==null,inWrapper:!isInternalProp&&hasOwn(wrapper,prop)})}if(prop==="__mode")return wrapper.____slothletInternal.mode;if(prop==="__apiPath")return wrapper.____slothletInternal.apiPath;if(prop==="__isCallable")return wrapper.____slothletInternal.isCallable;if(prop==="__materializeOnCreate")return wrapper.____slothletInternal.materializeOnCreate;if(prop==="__materialized")return wrapper.____slothletInternal.state.materialized;if(prop==="__inFlight")return wrapper.____slothletInternal.state.inFlight;if(prop==="__displayName")return wrapper.____slothletInternal.displayName;if(prop==="__type"){if(wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.state.materialized&&!wrapper.____slothletInternal.state.inFlight){wrapper._materialize().catch(()=>{})}if(wrapper.____slothletInternal.mode==="lazy"&&wrapper.____slothletInternal.state.inFlight){return TYPE_STATES.IN_FLIGHT}if(wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.state.materialized){return TYPE_STATES.UNMATERIALIZED}const impl=wrapper.____slothletInternal.impl;if(typeof impl==="function"){return"function"}if(impl&&typeof impl==="object"&&typeof impl.default==="function"){return"function"}if(impl&&typeof impl==="object"){return"object"}if(typeof impl==="string"){return"string"}if(typeof impl==="number"){return"number"}if(typeof impl==="boolean"){return"boolean"}if(typeof impl==="symbol"){return"symbol"}if(typeof impl==="bigint"){return"bigint"}return"undefined"}if(prop==="_materialize")return wrapper._materialize.bind(wrapper);if(prop==="__slothletPath")return wrapper.____slothletInternal.apiPath;if(prop==="__metadata"){if(wrapper.slothlet.handlers?.metadata){return wrapper.slothlet.handlers.metadata.getMetadata(wrapper)}return{}}if(prop==="__filePath")return wrapper.____slothletInternal.filePath??void 0;if(prop==="__sourceFolder")return wrapper.____slothletInternal.sourceFolder??void 0;if(prop==="__moduleID")return wrapper.____slothletInternal.moduleID??void 0;if(prop==="__invalid")return wrapper.____slothletInternal.invalid;{const arrImpl=wrapper.____slothletInternal.impl;if(Array.isArray(arrImpl)){const isIndex=typeof prop==="string"&&/^(?:0|[1-9]\d*)$/.test(prop);if(!isIndex){const arrValue=Reflect.get(arrImpl,prop,arrImpl);enforceReadGate(arrValue);return arrValue}}}if(prop==="then"){if(wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.state.materialized){return(onFulfilled,onRejected)=>wrapper._materialize().then(()=>onFulfilled(wrapper.____slothletInternal.proxy)).catch(onRejected)}return void 0}if(prop==="constructor")return Object.prototype.constructor;if(prop===util.inspect.custom){return()=>{const childKeys=Object.keys(wrapper).filter(k=>!k.startsWith("_")&&!k.startsWith("__"));if(childKeys.length>0&&!wrapper.____slothletInternal.isCallable){const obj={};for(const key of childKeys){const child=wrapper[key];if(child&&typeof child.createProxy==="function"){obj[key]=child.createProxy()}else{obj[key]=child}}return obj}if(wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.state.materialized&&(wrapper.____slothletInternal.impl===null||wrapper.____slothletInternal.impl===void 0)){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_INSPECT_LAZY_UNMATERIALIZED",apiPath:wrapper.apiPath,wrapper,____proxy:wrapper.____slothletInternal.proxy});return wrapper||wrapper.____slothletInternal.proxy}return wrapper.____slothletInternal.impl}}if(prop===Symbol.toStringTag){const impl=wrapper.____slothletInternal.impl;if(typeof impl==="function"){return"Function"}if(impl&&typeof impl==="object"&&typeof impl.default==="function"){return"Function"}return"Object"}if(typeof prop==="symbol")return void 0;if(prop==="length"){const impl=wrapper.____slothletInternal.impl;if(typeof impl==="function"){return impl.length}if(impl&&typeof impl==="object"&&typeof impl.default==="function"){return impl.default.length}return 0}if(prop==="name"){if(wrapper.____slothletInternal.apiPath){const pathParts=wrapper.____slothletInternal.apiPath.split(".");const lastPart=pathParts[pathParts.length-1];if(lastPart){return lastPart}}return target.name||"unifiedWrapperProxy"}if(prop==="toString"){const impl=wrapper.____slothletInternal.impl;if(typeof impl==="function"){return impl.toString.bind(impl)}if(impl&&typeof impl==="object"&&typeof impl.default==="function"){return impl.default.toString.bind(impl.default)}if(typeof target==="function"){return Function.prototype.toString.bind(target)}return()=>`[UnifiedWrapper: ${wrapper.____slothletInternal.apiPath}]`}if(prop==="valueOf"){const impl=wrapper.____slothletInternal.impl;if(typeof impl==="function"){return impl.valueOf.bind(impl)}if(impl&&typeof impl==="object"&&typeof impl.default==="function"){return impl.default.valueOf.bind(impl.default)}return Function.prototype.valueOf.bind(target)}if(prop==="toJSON"){const impl=wrapper.____slothletInternal.impl;if(impl&&typeof impl.toJSON==="function"){return impl.toJSON.bind(impl)}return()=>{const data=UnifiedWrapper._extractFullImpl(wrapper);if(data&&typeof data==="object"){delete data.__childFilePaths;delete data.__childFilePathsPreMaterialize}const pm=wrapper.slothlet.handlers?.permissionManager;if(pm&&pm.isEnabled()&&pm.isReadGatingEnabled()){runtime_redactSerialized(wrapper,data,wrapper.____slothletInternal.apiPath,new WeakSet)}return data}}if(wrapper.____slothletInternal.invalid){return void 0}if(wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.state.materialized&&!wrapper.____slothletInternal.state.inFlight){wrapper._materialize().catch(()=>{})}if(hasOwn(wrapper,prop)){if(wrapper.____slothletInternal.state.collisionMode==="replace"&&(prop==="power"||prop==="add")){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_GET_CACHED_REPLACE",apiPath:wrapper.apiPath,prop:String(prop),collisionMode:wrapper.____slothletInternal.state.collisionMode,wrapperKeys:Object.keys(wrapper).filter(k=>!k.startsWith("_")&&!k.startsWith("__")).join(", ")})}this.slothlet.debug("wrapper",{key:"DEBUG_MODE_GET_CACHED",apiPath:wrapper.____slothletInternal.apiPath,prop:String(prop),materialized:wrapper.____slothletInternal.state.materialized,hasImpl:wrapper.____slothletInternal.impl!==null});const cached=wrapper[prop];const _cachedWrapper=resolveWrapper(cached);if(_cachedWrapper?.____slothletInternal?.impl!==null&&_cachedWrapper?.____slothletInternal?.impl!==void 0){const cachedImpl=_cachedWrapper.____slothletInternal.impl;const cachedType=typeof cachedImpl;if(cachedType==="string"||cachedType==="number"||cachedType==="boolean"||cachedType==="bigint"||cachedType==="symbol"){enforceReadGate(cachedImpl);return cachedImpl}}if(_cachedWrapper){const cachedWrapper=_cachedWrapper;if(cachedWrapper.____slothletInternal.mode==="lazy"&&!cachedWrapper.____slothletInternal.state.materialized&&!cachedWrapper.____slothletInternal.state.inFlight){cachedWrapper._materialize().catch(()=>{})}}enforceReadGate(cached);return cached}if(wrapper.____slothletInternal.impl!==null&&wrapper.____slothletInternal.impl!==void 0){if(typeof wrapper.____slothletInternal.impl==="object"&&util.types.isProxy(wrapper.____slothletInternal.impl)){return wrapper.____slothletInternal.impl[prop]}if(hasOwn(wrapper,prop)){if(prop==="power"||prop==="add"){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_GET_PROXYGET_ACCESSING",prop,wrapperId:wrapper.____slothletInternal.id,apiPath:wrapper.apiPath,collisionMode:wrapper.____slothletInternal.state.collisionMode||"none"});this.slothlet.debug("wrapper",{key:"DEBUG_MODE_GET_PROXYGET_FOUND",wrapperKeys:Object.keys(wrapper).filter(k=>!k.startsWith("_")&&!k.startsWith("__")).join(", ")})}const cached=wrapper[prop];const _cachedWrapper4=resolveWrapper(cached);if(_cachedWrapper4){const cachedWrapper=_cachedWrapper4;if(cachedWrapper.____slothletInternal.mode==="lazy"&&!cachedWrapper.____slothletInternal.state.materialized&&!cachedWrapper.____slothletInternal.state.inFlight){cachedWrapper._materialize().catch(()=>{})}}enforceReadGate(cached);return cached}}const isInternalProp2=typeof prop==="string"&&UnifiedWrapper.INTERNAL_KEYS.has(prop);if(wrapper.____slothletInternal.mode==="lazy"&&wrapper.____slothletInternal.state.materialized&&!isInternalProp2&&!hasOwn(wrapper,prop)&&wrapper.____slothletInternal.impl&&!(prop in wrapper.____slothletInternal.impl)){return void 0}if(wrapper.____slothletInternal.mode==="lazy"&&(wrapper.____slothletInternal.state.inFlight||!wrapper.____slothletInternal.impl)){if(!wrapper.____slothletInternal.state.materialized&&!wrapper.____slothletInternal.state.inFlight){wrapper._materialize().catch(()=>{})}this.slothlet.debug("wrapper",{key:"DEBUG_MODE_LAZY_GET_CREATE_WAITING_PROXY",prop:String(prop),collisionMode:wrapper.____slothletInternal.state.collisionMode||"none",apiPath:wrapper.____slothletInternal.apiPath});if(wrapper.____slothletInternal.impl&&typeof wrapper.____slothletInternal.impl==="object"&&util.types.isProxy(wrapper.____slothletInternal.impl)){const value2=wrapper.____slothletInternal.impl[prop];return value2}return wrapper.___createWaitingProxy([prop])}if(wrapper.____slothletInternal.impl&&typeof wrapper.____slothletInternal.impl==="object"&&util.types.isProxy(wrapper.____slothletInternal.impl)){const value2=wrapper.____slothletInternal.impl[prop];return value2}let value=wrapper.____slothletInternal.impl?wrapper.____slothletInternal.impl[prop]:void 0;if(value===void 0&&wrapper.____slothletInternal.impl){const descriptor=Object.getOwnPropertyDescriptor(wrapper.____slothletInternal.impl,prop);if(descriptor&&descriptor.get){value=descriptor.get.call(wrapper.____slothletInternal.impl)}}if(value===void 0&&Object.prototype.hasOwnProperty.call(target,prop)){value=target[prop]}if(value===void 0){return void 0}enforceReadGate(value);const valueType=typeof value;if(value===null||valueType==="string"||valueType==="number"||valueType==="boolean"||valueType==="bigint"||valueType==="symbol"){return value}if(value instanceof Map||value instanceof Set||value instanceof WeakMap||value instanceof WeakSet||value instanceof Date||value instanceof RegExp||value instanceof Promise||value instanceof Error||ArrayBuffer.isView(value)||value instanceof ArrayBuffer){return value}if(value&&typeof value==="object"&&util.types.isProxy(value)){return value}if(value&&(typeof value==="object"||typeof value==="function")&&resolveWrapper(value)!==null){return value}const currentImpl=wrapper.____slothletInternal.impl;if(typeof currentImpl==="function"&&!Object.prototype.propertyIsEnumerable.call(currentImpl,prop)){return value}const wrapped=wrapper.___createChildWrapper(prop,value);if(wrapped){Object.defineProperty(wrapper,prop,{value:wrapped,writable:false,enumerable:true,configurable:true});return wrapped}return value};const applyTrap=(target,thisArg,args)=>{if(wrapper.____slothletInternal.invalid){throw new TypeError(`${wrapper.____slothletInternal.apiPath||"api"} is invalidated`)}enforcePermission(wrapper);const hookManager=wrapper.slothlet.handlers?.hookManager;const hasHooks=hookManager&&hookManager.enabled&&!wrapper.____slothletInternal.apiPath.startsWith("slothlet.hook");const api=wrapper.slothlet.boundApi;const ctx=wrapper.slothlet.config?.context||{};if(hasHooks){const ___strategy=hookManager.getDispatchStrategy(wrapper.____slothletInternal.apiPath);if(___strategy.asyncBefore||___strategy.asyncAfter){const ___path=wrapper.____slothletInternal.apiPath;const ___leafIsAsync=util.types.isAsyncFunction(wrapper.____slothletInternal.impl)||util.types.isAsyncFunction(wrapper.____slothletInternal.impl?.default);const ___promotedRun=(async()=>{let beforeResult;try{beforeResult=await hookManager.executeBeforeHooksAsync(___path,args,api,ctx)}catch(error){hookManager.executeAlwaysHooks(___path,args,void 0,true,[unwrapError(error)],api,ctx);throw error}args=beforeResult.args;if(beforeResult.shortCircuit){hookManager.executeAlwaysHooks(___path,args,beforeResult.value,false,[],api,ctx);return beforeResult.value}if(wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.state.materialized){await wrapper._materialize()}const impl=wrapper.____slothletInternal.impl;let settled;try{let raw;if(typeof impl==="function"){raw=wrapper.slothlet.contextManager?wrapper.slothlet.contextManager.runInContext(wrapper.instanceID,impl,thisArg,args,wrapper):impl.apply(thisArg,args)}else if(impl&&typeof impl==="object"&&typeof impl.default==="function"){raw=wrapper.slothlet.contextManager?wrapper.slothlet.contextManager.runInContext(wrapper.instanceID,impl.default,impl,args,wrapper):impl.default.apply(impl,args)}else{throw new wrapper.SlothletError("INVALID_CONFIG_NOT_A_FUNCTION",{apiPath:___path,actualType:typeof impl},null,{validationError:true})}settled=raw&&typeof raw==="object"&&typeof raw.then==="function"?await raw:raw}catch(error){const originalError=unwrapError(error);if(!error[ERROR_HOOK_PROCESSED]){const sourceInfo={type:"function",timestamp:Date.now(),stack:originalError.stack};hookManager.executeErrorHooks(___path,originalError,sourceInfo,args,api,ctx)}hookManager.executeAlwaysHooks(___path,args,void 0,true,[originalError],api,ctx);if(wrapper.slothlet.config?.hook?.suppressErrors===true)return void 0;throw error}let promotedFinal;try{const afterResult=await hookManager.executeAfterHooksAsync(___path,settled,args,api,ctx);promotedFinal=afterResult.modified?afterResult.result:settled}catch(error){hookManager.executeAlwaysHooks(___path,args,void 0,true,[unwrapError(error)],api,ctx);throw error}hookManager.executeAlwaysHooks(___path,args,promotedFinal,false,[],api,ctx);return promotedFinal})();return ___leafIsAsync?___promotedRun:runtime_guardPromotedResult(___promotedRun,___path,wrapper.SlothletError)}}let result;let finalResult;let isAsync=false;let lastSyncError=null;try{if(hasHooks){const beforeResult=hookManager.executeBeforeHooks(wrapper.____slothletInternal.apiPath,args,api,ctx);args=beforeResult.args;if(beforeResult.shortCircuit){finalResult=beforeResult.value;return beforeResult.value}}if(wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.state.materialized&&!wrapper.____slothletInternal.state.inFlight){wrapper._materialize().catch(()=>{})}if(wrapper.____slothletInternal.mode==="lazy"&&wrapper.____slothletInternal.state.inFlight){return new Promise((resolve,reject)=>{const checkMaterialized=()=>{if(wrapper.____slothletInternal.state.materialized){const impl2=wrapper.____slothletInternal.impl;try{if(typeof impl2==="function"){if(wrapper.slothlet.contextManager){resolve(wrapper.slothlet.contextManager.runInContext(wrapper.instanceID,impl2,thisArg,args,wrapper,true))}else{resolve(impl2.apply(thisArg,args))}}else if(impl2&&typeof impl2==="object"&&typeof impl2.default==="function"){if(wrapper.contextManager){resolve(wrapper.contextManager.runInContext(wrapper.instanceID,impl2.default,impl2,args,wrapper,true))}else{resolve(impl2.default.apply(impl2,args))}}else{reject(new wrapper.slothlet.SlothletError("INVALID_CONFIG_NOT_A_FUNCTION",{apiPath:wrapper.____slothletInternal.apiPath,actualType:typeof impl2},null,{validationError:true}))}}catch(err){reject(err)}return}if(!wrapper.____slothletInternal.state.inFlight){reject(new wrapper.slothlet.SlothletError("INVALID_CONFIG_LAZY_MATERIALIZATION_FAILED",{apiPath:wrapper.____slothletInternal.apiPath},null,{validationError:true}));return}setImmediate(checkMaterialized)};checkMaterialized()})}const impl=wrapper.____slothletInternal.impl;if(typeof impl==="function"){if(wrapper.slothlet.contextManager){result=wrapper.slothlet.contextManager.runInContext(wrapper.instanceID,impl,thisArg,args,wrapper,true)}else{result=impl.apply(thisArg,args)}}else if(impl&&typeof impl==="object"&&typeof impl.default==="function"){if(wrapper.slothlet.contextManager){result=wrapper.slothlet.contextManager.runInContext(wrapper.instanceID,impl.default,impl,args,wrapper,true)}else{result=impl.default.apply(impl,args)}}else{throw new wrapper.SlothletError("INVALID_CONFIG_NOT_A_FUNCTION",{apiPath:wrapper.____slothletInternal.apiPath,actualType:typeof impl},null,{validationError:true})}if(result&&typeof result==="object"&&typeof result.then==="function"){isAsync=true;return result.then(resolvedResult=>{try{if(hasHooks){const afterResult=hookManager.executeAfterHooks(wrapper.____slothletInternal.apiPath,resolvedResult,args,api,ctx);const finalResult2=afterResult.modified?afterResult.result:resolvedResult;hookManager.executeAlwaysHooks(wrapper.____slothletInternal.apiPath,args,finalResult2,false,[],api,ctx);return finalResult2}return resolvedResult}catch(error){if(hasHooks){const originalError=unwrapError(error);const sourceInfo={type:"after",timestamp:Date.now(),stack:originalError.stack};hookManager.executeErrorHooks(wrapper.____slothletInternal.apiPath,originalError,sourceInfo,args,api,ctx);hookManager.executeAlwaysHooks(wrapper.____slothletInternal.apiPath,args,void 0,true,[originalError],api,ctx)}const suppressErrors=wrapper.slothlet.config?.hook?.suppressErrors===true;if(suppressErrors){return void 0}throw error}},error=>{if(hasHooks&&!error[ERROR_HOOK_PROCESSED]){const originalError=unwrapError(error);const sourceInfo={type:"function",timestamp:Date.now(),stack:originalError.stack};hookManager.executeErrorHooks(wrapper.____slothletInternal.apiPath,originalError,sourceInfo,args,api,ctx)}if(hasHooks){const originalError=unwrapError(error);hookManager.executeAlwaysHooks(wrapper.____slothletInternal.apiPath,args,void 0,true,[originalError],api,ctx)}const suppressErrors=wrapper.slothlet.config?.hook?.suppressErrors===true;if(suppressErrors){return void 0}throw error})}finalResult=result;if(hasHooks){const afterResult=hookManager.executeAfterHooks(wrapper.____slothletInternal.apiPath,result,args,api,ctx);if(afterResult.modified){finalResult=afterResult.result}}return finalResult}catch(error){lastSyncError=error;if(hasHooks&&!error[ERROR_HOOK_PROCESSED]){const originalError=unwrapError(error);const sourceInfo={type:"function",timestamp:Date.now(),stack:originalError.stack};hookManager.executeErrorHooks(wrapper.____slothletInternal.apiPath,originalError,sourceInfo,args,api,ctx)}const suppressErrors=wrapper.slothlet.config?.hook?.suppressErrors===true;if(suppressErrors){return void 0}throw error}finally{if(hasHooks&&!isAsync){const syncError=lastSyncError;const resultValue=syncError?void 0:typeof finalResult!=="undefined"?finalResult:result;const errors=syncError?[unwrapError(syncError)]:[];hookManager.executeAlwaysHooks(wrapper.____slothletInternal.apiPath,args,resultValue,!!syncError,errors,api,ctx)}}};const hasTrap=(target,prop)=>{if(prop==="_materialize"){return true}if(wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.state.materialized&&!wrapper.____slothletInternal.state.inFlight){wrapper._materialize().catch(()=>{})}const isInternal=isFrameworkReservedKey(prop);if(!isInternal&&hasOwn(wrapper,prop)){return true}if(!isInternal&&wrapper.____slothletInternal.impl&&(typeof wrapper.____slothletInternal.impl==="object"||typeof wrapper.____slothletInternal.impl==="function")&&prop in wrapper.____slothletInternal.impl){return true}return Object.prototype.hasOwnProperty.call(target,prop)};const getOwnPropertyDescriptorTrap=(target,prop)=>{if(wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.state.materialized&&!wrapper.____slothletInternal.state.inFlight){wrapper._materialize().catch(()=>{})}if(prop==="____slothletInternal")return void 0;if(prop==="prototype"&&typeof target==="function"){const desc=Object.getOwnPropertyDescriptor(target,"prototype");if(desc){return desc}}const ownDesc=Object.getOwnPropertyDescriptor(target,prop);if((!ownDesc||ownDesc.configurable)&&runtime_isReadRedacted(wrapper,prop)){return void 0}if(Object.prototype.hasOwnProperty.call(target,prop)){return Object.getOwnPropertyDescriptor(target,prop)}const isInternal=isFrameworkReservedKey(prop);if(!isInternal&&hasOwn(wrapper,prop)){const desc=Object.getOwnPropertyDescriptor(wrapper,prop);if(desc){return desc}}if(!isInternal&&wrapper.____slothletInternal.impl&&(typeof wrapper.____slothletInternal.impl==="object"||typeof wrapper.____slothletInternal.impl==="function")&&prop in wrapper.____slothletInternal.impl){return Object.getOwnPropertyDescriptor(wrapper.____slothletInternal.impl,prop)}return void 0};const ownKeysTrap=target=>{if(wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.state.materialized&&!wrapper.____slothletInternal.state.inFlight){wrapper._materialize().catch(()=>{})}const keys=new Set;if(typeof target==="function"||target&&target.__isCallable){keys.add("prototype");keys.add("length");keys.add("name")}for(const key of Reflect.ownKeys(target)){const descriptor=Object.getOwnPropertyDescriptor(target,key);if(!descriptor.configurable||descriptor.enumerable){keys.add(key)}}if(target!==wrapper){for(const key of Reflect.ownKeys(wrapper)){const descriptor=Object.getOwnPropertyDescriptor(wrapper,key);if(descriptor&&descriptor.enumerable){keys.add(key)}}}const implKeys=wrapper.____slothletInternal.impl&&(typeof wrapper.____slothletInternal.impl==="object"||typeof wrapper.____slothletInternal.impl==="function")?Reflect.ownKeys(wrapper.____slothletInternal.impl):[];for(const key of implKeys){if(key!=="prototype"&&!IMPL_METADATA_KEYS.has(key)){keys.add(key)}}for(const key of keys){const targetDesc=Object.getOwnPropertyDescriptor(target,key);if(targetDesc&&!targetDesc.configurable)continue;if(runtime_isReadRedacted(wrapper,key))keys.delete(key)}return Array.from(keys)};const setTrap=(target,prop,value)=>{if(wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.state.materialized&&!wrapper.____slothletInternal.state.inFlight){wrapper._materialize()}if(UnifiedWrapper.INTERNAL_KEYS.has(prop)&&prop!=="_materialize")return true;const internalKeys=new Set(["_materialize"]);if(!internalKeys.has(prop)){if(hasOwn(wrapper,prop)){delete wrapper[prop]}Object.defineProperty(wrapper,prop,{value,writable:false,enumerable:true,configurable:true})}else{target[prop]=value}return true};const deletePropertyTrap=(target,prop)=>{const internalKeys=new Set(["____slothletInternal","__impl","___setImpl","___resetLazy","_materialize","___invalidate","_impl","___getState","__state","__mode","__apiPath","__slothletPath","__isCallable","__materializeOnCreate","__displayName","__type","__metadata","__invalid","__filePath","__sourceFolder","__moduleID","__materialized","__inFlight"]);if(internalKeys.has(prop)){return true}const isInternal=isFrameworkReservedKey(prop);if(!isInternal&&hasOwn(wrapper,prop)){const childWrapper=wrapper[prop];const childWrapperRaw=resolveWrapper(childWrapper);if(childWrapperRaw){childWrapperRaw.___invalidate()}const descriptor=Object.getOwnPropertyDescriptor(wrapper,prop);if(descriptor?.configurable){delete wrapper[prop]}}if(wrapper.____slothletInternal.impl&&typeof wrapper.____slothletInternal.impl==="object"&&prop in wrapper.____slothletInternal.impl){delete wrapper.____slothletInternal.impl[prop]}delete target[prop];return true};const constructTrap=(target,args,newTarget)=>{if(wrapper.____slothletInternal.invalid){throw new TypeError(`${wrapper.____slothletInternal.apiPath||"api"} is invalidated`)}enforcePermission(wrapper);if(wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.state.materialized&&!wrapper.____slothletInternal.state.inFlight){wrapper._materialize().catch(()=>{})}if(wrapper.____slothletInternal.mode==="lazy"&&wrapper.____slothletInternal.state.inFlight){return Promise.resolve(wrapper.____slothletInternal.materializationPromise).then(()=>{if(!wrapper.____slothletInternal.state.materialized){throw new wrapper.slothlet.SlothletError("INVALID_CONFIG_LAZY_MATERIALIZATION_FAILED",{apiPath:wrapper.____slothletInternal.apiPath},null,{validationError:true})}const impl2=wrapper.____slothletInternal.impl;if(typeof impl2==="function"){const effectiveNewTarget=newTarget===wrapper.____slothletInternal.proxy?impl2:newTarget;return Reflect.construct(impl2,args,effectiveNewTarget)}if(impl2&&typeof impl2==="object"&&typeof impl2.default==="function"){const effectiveNewTarget=newTarget===wrapper.____slothletInternal.proxy?impl2.default:newTarget;return Reflect.construct(impl2.default,args,effectiveNewTarget)}throw new wrapper.slothlet.SlothletError("INVALID_CONFIG_NOT_A_FUNCTION",{apiPath:wrapper.____slothletInternal.apiPath,actualType:typeof impl2},null,{validationError:true})})}const impl=wrapper.____slothletInternal.impl;if(typeof impl==="function"){const effectiveNewTarget=newTarget===wrapper.____slothletInternal.proxy?impl:newTarget;return Reflect.construct(impl,args,effectiveNewTarget)}if(impl&&typeof impl==="object"&&typeof impl.default==="function"){const effectiveNewTarget=newTarget===wrapper.____slothletInternal.proxy?impl.default:newTarget;return Reflect.construct(impl.default,args,effectiveNewTarget)}throw new wrapper.SlothletError("INVALID_CONFIG_NOT_A_FUNCTION",{apiPath:wrapper.____slothletInternal.apiPath,actualType:typeof impl},null,{validationError:true})};wrapper.____slothletInternal.proxy=new Proxy(proxyTarget,{get:(target,prop,receiver)=>runtime_bindCapturedIdentity(wrapper,prop,getTrap(target,prop,receiver)),apply:applyTrap,construct:constructTrap,has:hasTrap,getOwnPropertyDescriptor:getOwnPropertyDescriptorTrap,ownKeys:ownKeysTrap,set:setTrap,deleteProperty:deletePropertyTrap,getPrototypeOf:()=>Array.isArray(wrapper.____slothletInternal.impl)?Array.prototype:null});_proxyRegistry.set(wrapper.____slothletInternal.proxy,wrapper);genuineWrappers.add(wrapper);return wrapper.____slothletInternal.proxy}}Object.defineProperty(UnifiedWrapper.prototype,util.inspect.custom,{value:UnifiedWrapper.prototype.____inspectCustom,writable:true,enumerable:false,configurable:true});function resolveWrapper(value){if(!value)return null;const registered=_proxyRegistry.get(value);if(registered)return registered;if(value instanceof UnifiedWrapper&&value.____slothletInternal!=null)return value;return null}export{IMPL_METADATA_KEYS,TYPE_STATES,UnifiedWrapper,isFrameworkReservedKey,resolveWrapper};
17
+ const ____COLLISION_MERGED_PROPERTY=Symbol("collisionMergedProperty");import{isNode,util,EventEmitter}from"@cldmv/slothlet/helpers/platform";import{ComponentBase}from"#factories/component-base";import{TRUSTED_ROOT,genuineWrappers}from"#handlers/trusted-root";import{isFrameworkInternal,isFrameworkMarkerKey}from"#handlers/framework-internals";const ERROR_HOOK_PROCESSED=Symbol.for("@cldmv/slothlet/hook-error-processed");const hasOwn=(obj,key)=>Object.prototype.hasOwnProperty.call(obj,key);function resolveEnforcedCaller(wrapper,ctxOverride){const ownInstanceID=wrapper.slothlet.instanceID;const ctx=ctxOverride!==void 0?ctxOverride:wrapper.slothlet.contextManager?.tryGetContext?.(ownInstanceID);const identity=ctxOverride!==void 0?ctxOverride:wrapper.slothlet.contextManager?.getCallerIdentity?.(ownInstanceID);if(identity?.unresolved)return{verdict:"deny"};const callerWrapper=identity?.currentWrapper;if(!callerWrapper){const store=ctx??wrapper.slothlet.contextManager?.instances?.get(wrapper.slothlet.instanceID);if(store&&store[TRUSTED_ROOT]===true)return{verdict:"allow"};if(wrapper.slothlet.config?.permissions?.failOpenOnAbsentCaller)return{verdict:"allow"};return{verdict:"deny"}}if(!genuineWrappers.has(callerWrapper))return{verdict:"deny"};return{verdict:"enforce",callerWrapper,ctx}}function runtime_enforceReadGate(wrapper,prop,resolvedValue,callerOverride){const pm=wrapper.slothlet.handlers?.permissionManager;if(!pm||!pm.isEnabled()||!pm.isReadGatingEnabled())return;if(!runtime_isTerminalData(resolvedValue))return;const targetPath=wrapper.____slothletInternal.apiPath+"."+String(prop);const decision=runtime_readGateDecision(wrapper,targetPath,callerOverride);if(decision.allowed)return;throw new wrapper.SlothletError("PERMISSION_DENIED",{caller:decision.caller,target:targetPath})}function runtime_isTerminalData(value){return value!==Object(value)||value instanceof Map||value instanceof Set||value instanceof WeakMap||value instanceof WeakSet||value instanceof Date||value instanceof RegExp||value instanceof Promise||value instanceof Error||ArrayBuffer.isView(value)||value instanceof ArrayBuffer}function runtime_readGateDecision(wrapper,targetPath,callerOverride){if(isFrameworkInternal(wrapper)){const leafKey=targetPath.slice(targetPath.lastIndexOf(".")+1);if(isFrameworkMarkerKey(leafKey))return{allowed:true,caller:null}}const decision=resolveEnforcedCaller(wrapper,callerOverride);if(decision.verdict==="allow"){const hostPm=wrapper.slothlet.handlers.permissionManager;if(hostPm.isPrivateTarget?.(targetPath)&&!hostPm.enforceAccess(null,targetPath,null,wrapper.____slothletInternal.filePath,null)){return{allowed:false,caller:null}}return{allowed:true,caller:null}}if(decision.verdict==="deny")return{allowed:false,caller:null};const{callerWrapper,ctx}=decision;const callerPath=callerWrapper.____slothletInternal?.apiPath??"";const callerFilePath=callerWrapper.____slothletInternal?.filePath??null;const targetFilePath=wrapper.____slothletInternal.filePath??null;const allowed=wrapper.slothlet.handlers.permissionManager.enforceAccess(callerPath,targetPath,callerFilePath,targetFilePath,ctx.context??null);return{allowed,caller:callerPath}}function runtime_isReadRedacted(wrapper,prop){const pm=wrapper.slothlet.handlers?.permissionManager;if(!pm||!pm.isEnabled()||!pm.isReadGatingEnabled())return false;const impl=wrapper.____slothletInternal?.impl;const desc=(impl&&(typeof impl==="object"||typeof impl==="function")?Object.getOwnPropertyDescriptor(impl,prop):void 0)??Object.getOwnPropertyDescriptor(wrapper,prop);if(!desc||!("value"in desc)||!runtime_isTerminalData(runtime_unwrapLeafValue(desc.value)))return false;const targetPath=wrapper.____slothletInternal.apiPath+"."+String(prop);return!runtime_readGateDecision(wrapper,targetPath).allowed}function runtime_unwrapLeafValue(value){let current=value;for(let depth=0;depth<8;depth++){if(!current||typeof current!=="object"&&typeof current!=="function")return current;const inner=_proxyRegistry.get(current)??(hasOwn(current,"____slothletInternal")?current:null);if(!inner)return current;current=inner.____slothletInternal?.impl}return current}function runtime_redactSerialized(wrapper,data,basePath,seen){if(!data||typeof data!=="object"||Array.isArray(data)||seen.has(data))return;seen.add(data);for(const key of Object.keys(data)){const value=data[key];const targetPath=`${basePath}.${key}`;if(runtime_isTerminalData(value)){if(!runtime_readGateDecision(wrapper,targetPath).allowed)delete data[key]}else{runtime_redactSerialized(wrapper,value,targetPath,seen)}}}function enforcePermission(wrapper){const permissionManager=wrapper.slothlet.handlers?.permissionManager;if(!permissionManager||!permissionManager.isEnabled())return;const targetPath=wrapper.____slothletInternal.apiPath;const decision=resolveEnforcedCaller(wrapper);if(decision.verdict==="allow"){if(permissionManager.isPrivateTarget?.(targetPath)&&!permissionManager.enforceAccess(null,targetPath,null,wrapper.____slothletInternal.filePath,null)){throw new wrapper.SlothletError("PERMISSION_DENIED",{caller:null,target:targetPath})}return}if(decision.verdict==="deny"){throw new wrapper.SlothletError("PERMISSION_DENIED",{caller:null,target:targetPath})}const{callerWrapper,ctx}=decision;const callerPath=callerWrapper.____slothletInternal?.apiPath??"";const callerFilePath=callerWrapper.____slothletInternal?.filePath??null;const targetFilePath=wrapper.____slothletInternal.filePath??null;const runtimeContext=ctx?.context??null;if(!permissionManager.enforceAccess(callerPath,targetPath,callerFilePath,targetFilePath,runtimeContext)){throw new wrapper.SlothletError("PERMISSION_DENIED",{caller:callerPath,target:targetPath})}}const capturedViews=new WeakMap;function runtime_enforceCapturedCaller(wrapper,capturedCaller,targetPathOverride){const permissionManager=wrapper.slothlet.handlers?.permissionManager;if(!permissionManager||!permissionManager.isEnabled())return;const targetPath=targetPathOverride??wrapper.____slothletInternal.apiPath;const callerPath=capturedCaller.____slothletInternal?.apiPath??"";const callerFilePath=capturedCaller.____slothletInternal?.filePath??null;const targetFilePath=wrapper.____slothletInternal.filePath??null;const runtimeContext=wrapper.slothlet.contextManager?.tryGetContext?.()?.context??null;if(!permissionManager.enforceAccess(callerPath,targetPath,callerFilePath,targetFilePath,runtimeContext)){throw new wrapper.SlothletError("PERMISSION_DENIED",{caller:callerPath,target:targetPath})}}function runtime_capturedView(child,capturedCaller){let byChild=capturedViews.get(capturedCaller);if(!byChild){byChild=new WeakMap;capturedViews.set(capturedCaller,byChild)}const existing=byChild.get(child);if(existing)return existing;const inner=resolveWrapper(child);const view=new Proxy(child,{apply(target,thisArg,args){runtime_enforceCapturedCaller(inner,capturedCaller);return Reflect.apply(target,thisArg,args)},construct(target,args,newTarget){runtime_enforceCapturedCaller(inner,capturedCaller);return Reflect.construct(target,args,newTarget===view?target:newTarget)},get(target,prop){const resolved=Reflect.get(target,prop);if(resolved!==void 0&&typeof prop==="string"&&runtime_isTerminalData(resolved)){const context=inner.slothlet.contextManager?.tryGetContext?.()?.context??null;runtime_enforceReadGate(inner,prop,resolved,{currentWrapper:capturedCaller,context});return resolved}if(resolveWrapper(resolved)===null)return resolved;return runtime_capturedView(resolved,capturedCaller)}});byChild.set(child,view);return view}function runtime_bindCapturedIdentity(wrapper,prop,value){if(typeof prop!=="string")return value;if(value===null||typeof value!=="object"&&typeof value!=="function")return value;const permissionManager=wrapper.slothlet.handlers?.permissionManager;if(!permissionManager||!permissionManager.isEnabled())return value;if(permissionManager.isCaptureEnabled?.()===false)return value;const inner=resolveWrapper(value);if(inner===null)return value;const innerPath=inner.____slothletInternal?.apiPath;if(!innerPath||innerPath.split(".").pop()!==prop)return value;const capturedCaller=wrapper.slothlet.contextManager?.getCallerIdentity?.()?.currentWrapper;if(!capturedCaller)return value;return runtime_capturedView(value,capturedCaller)}function runtime_guardPromotedResult(promise,path,SlothletErrorCtor){const refuse=()=>{throw new SlothletErrorCtor("HOOK_PROMOTED_RESULT_NOT_AWAITED",{path},null,{validationError:true})};return new Proxy(promise,{get(target,prop,receiver){if(prop===Symbol.toPrimitive||prop==="valueOf"||prop==="toString"||prop==="toJSON"){return refuse}const value=Reflect.get(target,prop,receiver);if(prop==="then"||prop==="catch"||prop==="finally")return value.bind(target);return value}})}function unwrapError(error){if(error&&error.name==="SlothletError"&&error.originalError){return error.originalError}return error}const wrapperDebugEnabled=isNode&&(process.env.SLOTHLET_DEBUG_WRAPPER==="1"||process.env.SLOTHLET_DEBUG_WRAPPER==="true"||process.env.SLOTHLET_DEBUG_SCRIPT_VERBOSE==="1"||process.env.SLOTHLET_DEBUG_SCRIPT_VERBOSE==="true");const IMPL_METADATA_KEYS=new Set(["__childFilePaths","__filePath","__childFilePathsPreMaterialize"]);function isFrameworkReservedKey(key){if(typeof key!=="string")return false;return UnifiedWrapper.INTERNAL_KEYS.has(key)||IMPL_METADATA_KEYS.has(key)}const TYPE_STATES={UNMATERIALIZED:Symbol("unmaterialized"),IN_FLIGHT:Symbol("inFlight")};function getSafeFunctionName(apiPath,fallback){const parts=String(apiPath||"").split(".").filter(part=>part&&part!=="null");const baseName=parts.length>0?parts[parts.length-1]:"";let safeName=String(baseName||"").replace(/[^A-Za-z0-9_$]/g,"_");if(!safeName||!/^[A-Za-z_$]/.test(safeName[0])){safeName=safeName?`_${safeName}`:""}return safeName||fallback}function createNamedProxyTarget(nameHint,fallback){const safeName=getSafeFunctionName(nameHint,fallback);return{[safeName]:function(){}}[safeName]}const _proxyRegistry=new WeakMap;class UnifiedWrapper extends ComponentBase{#internal=null;get ____slothletInternal(){if(!(#internal in this))return void 0;return this.#internal}constructor(slothlet,{mode,apiPath,initialImpl=null,materializeFunc=null,isCallable,materializeOnCreate=false,filePath=null,moduleID=null,sourceFolder=null,__adoptVisited=null,deferChildAdopt=false}){super(slothlet);const isCallableExplicit=typeof isCallable==="boolean";const isCallableValue=isCallableExplicit?isCallable:typeof initialImpl==="function"||initialImpl&&typeof initialImpl.default==="function";const isCallableLocked=isCallableValue||isCallableExplicit;const internal=Object.create(null);internal.id=Math.random().toString(36).substr(2,9);internal.mode=mode;internal.apiPath=apiPath;internal.materializeOnCreate=materializeOnCreate;internal.isCallable=isCallableValue;internal.isCallableLocked=isCallableLocked;internal.moduleID=moduleID;internal.filePath=filePath;internal.sourceFolder=sourceFolder;internal.adoptVisited=__adoptVisited;internal.deferChildAdopt=deferChildAdopt;internal.invalid=false;internal.state={materialized:initialImpl!==null,inFlight:false,collisionMode:"merge"};internal.displayName=apiPath?`${String(apiPath).replace(/\./g,"__")}__UnifiedWrapper`:"UnifiedWrapper";this.#internal=internal;const wrapper=this;Object.defineProperty(internal,"wrapper",{get(){return wrapper},enumerable:false,configurable:false});internal.callableImpl=null;internal.waitingProxyCache=new Map;internal.waitingProxyCacheByContext=new WeakMap;internal.proxy=null;internal.impl=UnifiedWrapper._cloneImpl(initialImpl);internal.materializeFunc=materializeFunc;if(filePath&&slothlet.handlers?.lifecycle){slothlet.handlers.lifecycle.emit("impl:created",{apiPath,impl:this,wrapper:Object.freeze({__impl:this.____slothletInternal.impl}),source:"initial",moduleID,filePath,sourceFolder:sourceFolder||slothlet.config?.dir})}if(initialImpl!==null&&filePath&&slothlet.handlers?.lifecycle){slothlet.handlers.lifecycle.emit("impl:created",{apiPath,impl:initialImpl,wrapper:Object.freeze({__impl:this.____slothletInternal.impl}),source:"initial",moduleID,filePath,sourceFolder:sourceFolder||slothlet.config?.dir})}if(initialImpl!==null&&!deferChildAdopt){const implKeys=Object.keys(initialImpl||{});if((wrapperDebugEnabled||this.____config?.debug?.wrapper)&&apiPath&&(apiPath==="config"||apiPath.startsWith("config."))){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_WRAPPER_CONSTRUCTOR_IMPL_KEYS",apiPath,keyCount:implKeys.length,keySample:implKeys.slice(0,5)})}this.___adoptImplChildren();if((wrapperDebugEnabled||this.____config?.debug?.wrapper)&&apiPath&&(apiPath==="config"||apiPath.startsWith("config."))){const childKeys=Object.keys(this).filter(k=>!k.startsWith("_")&&!k.startsWith("__"));this.slothlet.debug("wrapper",{key:"DEBUG_MODE_WRAPPER_CONSTRUCTOR_AFTER_ADOPT",apiPath,childCount:childKeys.length,childKeySample:childKeys.slice(0,5)})}}if(mode==="lazy"){slothlet._registerLazyWrapper();if(slothlet.config.tracking?.materialization){setImmediate(()=>{this._materialize().catch(err=>{if(slothlet.config?.debug?.materialize){slothlet.debug("materialize",{key:"DEBUG_MODE_BACKGROUND_MATERIALIZE_ERROR",apiPath:this.____slothletInternal?.apiPath,error:err.message})}})})}}}____inspectCustom(____depth,____options,____inspect){const w=_proxyRegistry.get(this)??this;const childKeys=Object.keys(w).filter(k=>!k.startsWith("_")&&!k.startsWith("__"));if(childKeys.length>0&&!w.____slothletInternal?.isCallable){const inspectObj={};for(const key of childKeys){inspectObj[key]=w[key]}return inspectObj}if(w.____slothletInternal?.mode==="lazy"&&w.____slothletInternal?.state&&!w.____slothletInternal?.state.materialized&&w.____slothletInternal?.proxy){return w.____slothletInternal.proxy}return w.____slothletInternal?.impl}get __impl(){return this.____slothletInternal.impl}static _cloneImpl(value){if(value&&typeof value==="object"&&!Array.isArray(value)&&typeof value!=="function"){const isProxy=util.types.isProxy(value);if(isProxy){if(resolveWrapper(value)){const clone={};for(const key of Reflect.ownKeys(value)){try{clone[key]=value[key]}catch{}}return clone}return value}const uw_cloneDescriptors=Object.getOwnPropertyDescriptors(value);return Object.create(Object.getPrototypeOf(value),uw_cloneDescriptors)}return value}static _extractFullImpl(wrapper){if(!wrapper)return null;const impl=wrapper.____slothletInternal.impl;if(impl===null||impl===void 0)return impl;if(typeof impl!=="object"&&typeof impl!=="function")return impl;if(typeof impl==="function")return impl;if(Array.isArray(impl))return impl.slice();const extractFullImpl_result={};for(const key of Object.keys(impl)){if(isFrameworkReservedKey(key))continue;extractFullImpl_result[key]=impl[key]}if(impl.__childFilePaths){extractFullImpl_result.__childFilePaths=impl.__childFilePaths}if(impl.__childFilePathsPreMaterialize){extractFullImpl_result.__childFilePathsPreMaterialize=impl.__childFilePathsPreMaterialize}for(const key of Object.keys(wrapper)){if(UnifiedWrapper.INTERNAL_KEYS.has(key))continue;if(key in extractFullImpl_result)continue;const extractFullImpl_child=wrapper[key];const _extractChildW=resolveWrapper(extractFullImpl_child);if(_extractChildW){extractFullImpl_result[key]=UnifiedWrapper._extractFullImpl(_extractChildW)}else{extractFullImpl_result[key]=extractFullImpl_child}}return extractFullImpl_result}_applyNewImpl(newImpl,forceReuseChildren=false){this.____slothletInternal.impl=UnifiedWrapper._cloneImpl(newImpl);this.____slothletInternal.invalid=false;if(!this.____slothletInternal.isCallableLocked&&!this.____slothletInternal.isCallable&&(typeof newImpl==="function"||newImpl&&typeof newImpl.default==="function")){this.____slothletInternal.isCallable=true;this.____slothletInternal.isCallableLocked=true}if(!this.____slothletInternal.filePath&&this.____slothletInternal.impl&&this.____slothletInternal.impl.__filePath){this.____slothletInternal.filePath=this.____slothletInternal.impl.__filePath;this.slothlet.debug("wrapper",{key:"DEBUG_MODE_APPLY_IMPL_UPDATE_PATH",apiPath:this.____slothletInternal.apiPath,filePath:this.____slothletInternal.filePath})}this.___adoptImplChildren(forceReuseChildren)}___setImpl(newImpl,moduleID=null,forceReuseChildren=false){if((wrapperDebugEnabled||this.____config?.debug?.wrapper)&&this.____slothletInternal.apiPath==="string"){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_SETIMPL_CALLED",apiPath:this.____slothletInternal.apiPath,newImplKeys:Object.keys(newImpl||{})})}this._applyNewImpl(newImpl,forceReuseChildren);if(newImpl&&this.slothlet.handlers?.lifecycle){const wrapperMetadata=this.slothlet.handlers.metadata.getMetadata(this);const extractedModuleId=moduleID||wrapperMetadata?.baseModuleID||null;this.slothlet.handlers.lifecycle.emit("impl:changed",{apiPath:this.____slothletInternal.apiPath,impl:newImpl,wrapper:Object.freeze({__impl:this.____slothletInternal.impl}),source:"hot-reload",moduleID:extractedModuleId,filePath:wrapperMetadata?.filePath,sourceFolder:wrapperMetadata?.sourceFolder})}this.____slothletInternal.state.materialized=true;this.____slothletInternal.state.inFlight=false;if(this.slothlet._onWrapperMaterialized){this.slothlet._onWrapperMaterialized()}}___resetLazy(newMaterializeFunc){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_RESETLAZY_CALLED",apiPath:this.____slothletInternal.apiPath,hadImpl:this.____slothletInternal.impl!==null,hadChildren:Object.keys(this).filter(k=>!k.startsWith("_")&&!k.startsWith("__")).length});for(const key of Reflect.ownKeys(this)){if(typeof key==="string"&&(key.startsWith("_")||key.startsWith("__"))){continue}const child=this[key];const childRaw=resolveWrapper(child);if(childRaw){childRaw.___invalidate()}const descriptor=Object.getOwnPropertyDescriptor(this,key);if(descriptor?.configurable){delete this[key]}}this.____slothletInternal.impl=null;this.____slothletInternal.invalid=false;this.____slothletInternal.state.materialized=false;this.____slothletInternal.state.inFlight=false;this.____slothletInternal.materializationPromise=null;this.____slothletInternal.materializeFunc=newMaterializeFunc;if(this.____slothletInternal.waitingProxyCache){this.____slothletInternal.waitingProxyCache.clear()}this.____slothletInternal.waitingProxyCacheByContext=new WeakMap;this.slothlet.debug("wrapper",{key:"DEBUG_MODE_RESETLAZY_COMPLETE",apiPath:this.____slothletInternal.apiPath})}async ___materialize(){if(this.____slothletInternal.state.materialized){return}if(this.____slothletInternal.invalid){return}if(this.____slothletInternal.materializationPromise){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_MATERIALIZE_AWAIT",apiPath:this.____slothletInternal.apiPath});return this.____slothletInternal.materializationPromise}if((wrapperDebugEnabled||this.____config?.debug?.wrapper)&&this.apiPath==="string"){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_MATERIALIZE_START",apiPath:this.apiPath})}this.____slothletInternal.materializationPromise=(async()=>{this.____slothletInternal.state.inFlight=true;try{if(this.____slothletInternal.materializeFunc){if((wrapperDebugEnabled||this.____config?.debug?.wrapper)&&this.____slothletInternal.apiPath==="string"){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_MATERIALIZE_CALLING_FUNC",apiPath:this.____slothletInternal.apiPath})}const lazy_setImpl=value=>{this._applyNewImpl(value)};const result=await this.____slothletInternal.materializeFunc(lazy_setImpl);if(!this.____slothletInternal.impl){this._applyNewImpl(result)}this.____slothletInternal.state.materialized=true;if(this.slothlet._onWrapperMaterialized){this.slothlet._onWrapperMaterialized()}if((wrapperDebugEnabled||this.____config?.debug?.wrapper)&&this.____slothletInternal.apiPath==="string"){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_MATERIALIZE_COMPLETE",apiPath:this.____slothletInternal.apiPath,resultType:typeof result,resultKeys:Object.keys(result||{})})}}}catch(error){if((wrapperDebugEnabled||this.____config?.debug?.wrapper)&&this.____slothletInternal.apiPath==="string"){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_MATERIALIZE_ERROR",apiPath:this.____slothletInternal.apiPath,error:error.message})}throw error}finally{this.____slothletInternal.state.inFlight=false;this.____slothletInternal.materializationPromise=null}})();return this.____slothletInternal.materializationPromise}_materialize(){return this.___materialize()}___invalidate(){this.____slothletInternal.invalid=true;this.____slothletInternal.impl=null;for(const key of Reflect.ownKeys(this)){if(typeof key==="string"&&(key.startsWith("_")||key.startsWith("__"))){continue}const descriptor=Object.getOwnPropertyDescriptor(this,key);if(descriptor?.configurable){delete this[key]}}}___adoptImplChildren(forceReuseChildren=false){const preExistingKeys=Object.keys(this).filter(k=>!k.startsWith("_")&&!k.startsWith("__"));this.slothlet.debug("wrapper",{key:"DEBUG_MODE_ADOPT_START",apiPath:this.____slothletInternal.apiPath,wrapperId:this.____slothletInternal.id||"no-id",preExistingKeys:preExistingKeys.join(","),collisionMode:this.____slothletInternal.state.collisionMode});const threadedVisited=this.____slothletInternal.adoptVisited;this.____slothletInternal.adoptVisited=null;if(!this.____slothletInternal.impl||typeof this.____slothletInternal.impl!=="object"&&typeof this.____slothletInternal.impl!=="function"){return}if(util.types.isProxy(this.____slothletInternal.impl))return;if(Array.isArray(this.____slothletInternal.impl))return;const adoptVisited=threadedVisited||new WeakSet;const ownKeys=Reflect.ownKeys(this.____slothletInternal.impl);const internalKeys=new Set(["__impl","___setImpl","___resetLazy","_materialize","_impl","_state","_invalid","____slothlet","____slothletInternal"]);const keepImplProperties=typeof this.____slothletInternal.impl==="function"||this.____slothletInternal.impl&&typeof this.____slothletInternal.impl==="object"&&typeof this.____slothletInternal.impl.default==="function";if(keepImplProperties&&this.____slothletInternal.impl&&typeof this.____slothletInternal.impl==="object"&&typeof this.____slothletInternal.impl.default==="function"){internalKeys.add("default")}const observedKeys=new Set;const existingKeys=Object.keys(this).filter(k=>!k.startsWith("_")&&!k.startsWith("__"));const storedCollisionMode=this.____slothletInternal.state.collisionMode;const isMergeScenario=storedCollisionMode!=="replace"&&existingKeys.length>0;this.slothlet.debug("wrapper",{key:"DEBUG_MODE_ADOPT",apiPath:this.____slothletInternal.apiPath,mode:this.____slothletInternal.mode,storedCollisionMode,existingKeys:existingKeys.join(","),isMergeScenario});const savedChildren=new Map;if(storedCollisionMode==="replace"&&existingKeys.length>0){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_ADOPT_REPLACE_CLEARING",count:existingKeys.length});for(const key of existingKeys){const child=this[key];if(resolveWrapper(child)!==null){savedChildren.set(key,child)}const descriptor=Object.getOwnPropertyDescriptor(this,key);if(descriptor?.configurable){delete this[key]}}}else{for(const key of existingKeys){observedKeys.add(key)}}const metadataKeys=new Set(["__childFilePaths","__filePath","__childFilePathsPreMaterialize"]);const skipKeys=typeof this.____slothletInternal.impl==="function"?new Set(["length","name","prototype"]):null;for(const key of ownKeys){if(internalKeys.has(key)){continue}if(typeof key==="string"&&metadataKeys.has(key)){continue}if(skipKeys&&typeof key==="string"&&skipKeys.has(key)){continue}if(!this.____slothletInternal.impl||typeof this.____slothletInternal.impl!=="object"&&typeof this.____slothletInternal.impl!=="function"){break}const descriptor=Object.getOwnPropertyDescriptor(this.____slothletInternal.impl,key);if(!descriptor){continue}const value=this.____slothletInternal.impl[key];if(value===this.____slothletInternal.impl){continue}if(typeof key!=="symbol"){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_ADOPT_PROCESS",apiPath:this.____slothletInternal.apiPath,propKey:key,typeOf:typeof value,valueName:value?.name})}observedKeys.add(key);if(hasOwn(this,key)&&!key.toString().startsWith("_")){if(typeof key!=="symbol"){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_ADOPT_CHECK",apiPath:this.____slothletInternal.apiPath,propKey:key,has__collisionMergedKeys:!!this.____slothletInternal.collisionMergedKeys,inSet:this.____slothletInternal.collisionMergedKeys?.has(key)})}const isCollisionMerged=this.____slothletInternal.collisionMergedKeys&&this.____slothletInternal.collisionMergedKeys.has(key);if(isCollisionMerged&&!forceReuseChildren){if(typeof key!=="symbol"){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_ADOPT_SKIP_COLLISION_MERGED",apiPath:this.____slothletInternal.apiPath,propKey:key})}if(descriptor.configurable){delete this.____slothletInternal.impl[key]}continue}if(typeof key!=="symbol"){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_ADOPT_ALLOW_NOT_COLLISION_MERGED",apiPath:this.____slothletInternal.apiPath,propKey:key})}}const existingChild=savedChildren.get(key)||this[key];let wrapped;const skipChildReuse=!forceReuseChildren&&this.____slothletInternal.mode==="lazy"&&storedCollisionMode==="replace";const existingChildUA=existingChild?resolveWrapper(existingChild):null;if(existingChildUA?.____slothletInternal?.userAssigned){wrapped=existingChild}else if(!skipChildReuse&&existingChild&&resolveWrapper(existingChild)!==null){if(resolveWrapper(value)!==null){const newWrapper=resolveWrapper(value);let rawImpl=newWrapper?newWrapper.____slothletInternal.impl:null;if(rawImpl&&typeof rawImpl==="object"&&!Array.isArray(rawImpl)&&typeof rawImpl!=="function"&&Object.keys(rawImpl).filter(k=>!k.startsWith("__")).length===0){const wrapperOwnKeys=Object.keys(newWrapper).filter(k=>!k.startsWith("_")&&!k.startsWith("__"));if(wrapperOwnKeys.length>0){rawImpl=UnifiedWrapper._extractFullImpl(newWrapper)}}if(rawImpl!==null&&rawImpl!==void 0){resolveWrapper(existingChild).___setImpl(rawImpl,this.____slothletInternal.moduleID,true)}else if(newWrapper&&newWrapper.____slothletInternal.materializeFunc){const existingChildWrapper=resolveWrapper(existingChild);if(existingChildWrapper){existingChildWrapper.___resetLazy(newWrapper.____slothletInternal.materializeFunc)}}wrapped=existingChild}else{resolveWrapper(existingChild).___setImpl(value,this.____slothletInternal.moduleID,true);wrapped=existingChild}if(typeof key!=="symbol"){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_ADOPT_REUSE_CHILD_WRAPPER",apiPath:this.____slothletInternal.apiPath,propKey:key})}}else{wrapped=this.___createChildWrapper(key,value,adoptVisited);if(typeof key!=="symbol"){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_ADOPT_WRAP",apiPath:this.____slothletInternal.apiPath,propKey:key,wrapped:wrapped?"YES":wrapped===null?"NULL":"NO"})}}if(wrapped){const existing=this[key];const existingDescriptor=Object.getOwnPropertyDescriptor(this,key);if(existing===wrapped||existingDescriptor&&!existingDescriptor.configurable){if(typeof key!=="symbol"){this.slothlet.debug("wrapper",{key:existingDescriptor&&!existingDescriptor.configurable?"DEBUG_MODE_ADOPT_SKIP_NON_CONFIGURABLE":"DEBUG_MODE_ADOPT_SKIP_SAME_WRAPPER",apiPath:this.____slothletInternal.apiPath,propKey:key})}}else{if(typeof key!=="symbol"){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_ADOPT_DEFINE",apiPath:this.____slothletInternal.apiPath,propKey:key})}Object.defineProperty(this,key,{value:wrapped,writable:false,enumerable:true,configurable:true});if(typeof key!=="symbol"){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_ADOPT_DEFINED",apiPath:this.____slothletInternal.apiPath,propKey:key})}}if(descriptor.configurable&&!keepImplProperties&&this.____slothletInternal.impl){delete this.____slothletInternal.impl[key]}}else if(wrapped===null){Object.defineProperty(this,key,{value,writable:false,enumerable:true,configurable:true});if(descriptor.configurable&&!keepImplProperties&&this.____slothletInternal.impl){delete this.____slothletInternal.impl[key]}}else{Object.defineProperty(this,key,{value,writable:false,enumerable:true,configurable:true});if(descriptor.configurable&&!keepImplProperties&&this.____slothletInternal.impl){delete this.____slothletInternal.impl[key]}}}if(!isMergeScenario){const currentKeys=Object.keys(this).filter(k=>!k.startsWith("_")&&!k.startsWith("__"));for(const key of currentKeys){if(!observedKeys.has(key)){const existing=this[key];const existingRaw=resolveWrapper(existing);if(existingRaw){existingRaw.___invalidate()}const descriptor=Object.getOwnPropertyDescriptor(this,key);if(descriptor?.configurable){delete this[key]}}}}if(this._mergeAfterMaterialize){const{existingWrapper,isMergeReplace:____isMergeReplace}=this._mergeAfterMaterialize;const existingKeys2=Object.keys(existingWrapper).filter(k=>!k.startsWith("_")&&!k.startsWith("__"));for(const key of existingKeys2){if(!(key in this)||key.startsWith("_")||key.startsWith("__")){const child=existingWrapper[key];Object.defineProperty(this,key,{value:child,writable:false,enumerable:true,configurable:true})}}delete this._mergeAfterMaterialize}}___createChildWrapper(key,value,visited=null,deferChildAdopt=false){if(value===void 0){return void 0}if(value===null){return null}if(value&&resolveWrapper(value)!==null){return value}if(value instanceof Map||value instanceof Set||value instanceof WeakMap||value instanceof WeakSet||value instanceof Date||value instanceof RegExp||value instanceof Promise||value instanceof Error||ArrayBuffer.isView(value)||value instanceof ArrayBuffer||EventEmitter&&value instanceof EventEmitter){return null}const trackCycle=typeof value==="object"||typeof value==="function";if(trackCycle){visited??=new WeakSet;if(visited.has(value)){return null}}let childImpl=value;if(this.____slothletInternal.mode==="eager"&&childImpl&&typeof childImpl==="object"){if(Array.isArray(childImpl)){childImpl=childImpl.slice()}else{const descriptors=Object.getOwnPropertyDescriptors(childImpl);childImpl=Object.create(Object.getPrototypeOf(childImpl),descriptors)}}const parentMetadata=this.slothlet.handlers?.metadata?.getMetadata(this);const childExistingMetadata=this.slothlet.handlers?.metadata?.getMetadata(value);let childFilePath=childExistingMetadata?.filePath||null;let childModuleId=null;if(!childFilePath){const keyStr=typeof key==="symbol"?String(key):key;this.slothlet.debug("wrapper",{key:"DEBUG_MODE_WRAP_CHILD_PATH_CHECK",apiPath:this.apiPath,propKey:keyStr,has_impl:!!this.____slothletInternal.impl,has__childFilePaths:!!(this.____slothletInternal.impl&&this.____slothletInternal.impl.__childFilePaths),has__childFilePathsPreMaterialize:!!this.____slothletInternal.childFilePathsPreMaterialize,parentFilePath:parentMetadata?.filePath});if(this.____slothletInternal.impl&&this.____slothletInternal.impl.__childFilePaths){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_WRAP_CHILD_PATH_AVAILABLE",keys:Object.keys(this.____slothletInternal.impl.__childFilePaths).join(","),propKey:keyStr,found:!!this.____slothletInternal.impl.__childFilePaths[key]})}if(this.____slothletInternal.impl&&this.____slothletInternal.impl.__childFilePaths&&this.____slothletInternal.impl.__childFilePaths[key]){childFilePath=this.____slothletInternal.impl.__childFilePaths[key];this.slothlet.debug("wrapper",{key:"DEBUG_MODE_WRAP_CHILD_PATH_USING",childFilePath})}else if(this.____slothletInternal.childFilePathsPreMaterialize&&this.____slothletInternal.childFilePathsPreMaterialize[key]){childFilePath=this.____slothletInternal.childFilePathsPreMaterialize[key];this.slothlet.debug("wrapper",{key:"DEBUG_MODE_WRAP_CHILD_PATH_PRE_MAT",childFilePath})}else{childFilePath=parentMetadata?.filePath||null;this.slothlet.debug("wrapper",{key:"DEBUG_MODE_WRAP_CHILD_PATH_FALLBACK",childFilePath})}}if(parentMetadata?.baseModuleID){childModuleId=parentMetadata.baseModuleID}const childSourceFolder=childExistingMetadata?.sourceFolder||parentMetadata?.sourceFolder||null;if(trackCycle){visited.add(value)}let nestedWrapper;try{nestedWrapper=new UnifiedWrapper(this.slothlet,{mode:"eager",apiPath:this.____slothletInternal.apiPath?`${this.____slothletInternal.apiPath}.${typeof key==="symbol"?String(key):key}`:String(key),initialImpl:childImpl,isCallable:typeof childImpl==="function",filePath:childFilePath,moduleID:childModuleId,sourceFolder:childSourceFolder,__adoptVisited:visited,deferChildAdopt})}finally{if(trackCycle){visited.delete(value)}}return nestedWrapper.createProxy()}___createWaitingProxy(propChain=[]){const wrapper=this;const __readGateStore=wrapper.slothlet.contextManager?.tryGetContext?.();const __readGateCaller=__readGateStore?{currentWrapper:wrapper.slothlet.contextManager?.getCallerIdentity?.()?.currentWrapper??null,context:__readGateStore.context,[TRUSTED_ROOT]:__readGateStore[TRUSTED_ROOT]===true}:null;const __callerKey=__readGateCaller?.currentWrapper?.____slothletInternal?.apiPath??"";const cacheKey=`${__callerKey}::${propChain.join(".")}`;const __readGateContextRef=__readGateStore?.context??null;const useContextBucket=__readGateContextRef&&typeof __readGateContextRef==="object";let cache;if(useContextBucket){cache=wrapper.____slothletInternal.waitingProxyCacheByContext.get(__readGateContextRef);if(!cache){cache=new Map;wrapper.____slothletInternal.waitingProxyCacheByContext.set(__readGateContextRef,cache)}}else{cache=wrapper.____slothletInternal.waitingProxyCache}if(cache.has(cacheKey)){return cache.get(cacheKey)}const waitingTarget=createNamedProxyTarget(`${wrapper.____slothletInternal.apiPath}_waitingProxy`,"waitingProxyTarget");const waitingProxy=new Proxy(waitingTarget,{get(___target,prop){if(prop==="then"){return(onFulfilled,onRejected)=>{const waitingProxy_thenResolve=async()=>{if(!wrapper.____slothletInternal.state.materialized){await wrapper._materialize()}let current=wrapper;let __gateParent=null;let __gateProp=null;const __descendRest=(startValue,nextIndex)=>{let descended=startValue;for(let __di=nextIndex;__di<propChain.length;__di++){if(descended===null||descended===void 0)return void 0;descended=descended[propChain[__di]]}return descended};for(let __chainIndex=0;__chainIndex<propChain.length;__chainIndex++){const chainProp=propChain[__chainIndex];if(!current)return void 0;if(current.____slothletInternal.impl&&typeof current.____slothletInternal.impl==="object"&&util.types.isProxy(current.____slothletInternal.impl)){let result=current.____slothletInternal.impl;for(let i=__chainIndex;i<propChain.length;i++){result=result[propChain[i]]}return result}const isInternal2=isFrameworkReservedKey(chainProp);if(!isInternal2&&hasOwn(current,chainProp)){const child=current[chainProp];const _childW=resolveWrapper(child);if(_childW){__gateParent=current;__gateProp=chainProp;current=_childW;if(current.____slothletInternal.mode==="lazy"&&!current.____slothletInternal.state.materialized){await current._materialize()}continue}if(__chainIndex<propChain.length-1){const descendedChild=__descendRest(child,__chainIndex+1);if(descendedChild!==void 0){runtime_enforceReadGate(current,propChain.slice(__chainIndex).join("."),descendedChild,__readGateCaller)}return descendedChild}runtime_enforceReadGate(current,chainProp,child,__readGateCaller);return child}if(current.____slothletInternal.impl&&current.____slothletInternal.impl[chainProp]!==void 0){const implValue=current.____slothletInternal.impl[chainProp];if(__chainIndex<propChain.length-1){const descendedImpl=__descendRest(implValue,__chainIndex+1);if(descendedImpl!==void 0){runtime_enforceReadGate(current,propChain.slice(__chainIndex).join("."),descendedImpl,__readGateCaller)}return descendedImpl}runtime_enforceReadGate(current,chainProp,implValue,__readGateCaller);return implValue}return void 0}if(current.____slothletInternal.impl&&typeof current.____slothletInternal.impl==="object"&&util.types.isProxy(current.____slothletInternal.impl)){return current.____slothletInternal.impl}if(__gateParent){runtime_enforceReadGate(__gateParent,__gateProp,current.____slothletInternal.impl,__readGateCaller)}const finalImpl=current.____slothletInternal.impl;const callableCarriesWrapperMembers=typeof finalImpl==="function"&&Object.keys(current).some(key=>!isFrameworkReservedKey(key)&&!Object.prototype.hasOwnProperty.call(finalImpl,key));if(callableCarriesWrapperMembers||finalImpl!==null&&typeof finalImpl==="object"&&!Array.isArray(finalImpl)&&!runtime_isTerminalData(finalImpl)){const resolvedProxy=current.____slothletInternal.proxy;const __capturedReader=__readGateCaller?.currentWrapper??null;const __pm=wrapper.slothlet.handlers?.permissionManager;if(__capturedReader&&__pm&&__pm.isEnabled()&&__pm.isCaptureEnabled?.()!==false){return runtime_capturedView(resolvedProxy,__capturedReader)}return resolvedProxy}return finalImpl};waitingProxy_thenResolve().then(onFulfilled,onRejected)}}if(prop==="____slothletInternal")return void 0;if(prop==="_materialize")return wrapper._materialize.bind(wrapper);if(prop==="__mode")return wrapper.____slothletInternal.mode;if(prop==="__materialized")return wrapper.____slothletInternal.state.materialized;if(prop==="__inFlight")return wrapper.____slothletInternal.state.inFlight;if(wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.state.materialized&&!wrapper.____slothletInternal.state.inFlight){wrapper._materialize().catch(()=>{})}if(prop===util.inspect.custom){if(wrapper.____slothletInternal.state.inFlight){return waitingTarget}if(!wrapper.____slothletInternal.state.materialized){return waitingTarget}if(wrapper.____slothletInternal.impl){let current=wrapper.____slothletInternal.impl;for(const chainProp of propChain){if(!current){return void 0}current=current[chainProp]}return current}return waitingTarget}if(prop==="__type"){wrapper.slothlet.debug("wrapper",{key:"DEBUG_MODE_WAITING_TYPE",apiPath:wrapper.apiPath,propChain:propChain.join(","),materialized:wrapper.____slothletInternal.state.materialized,hasImpl:wrapper.____slothletInternal.impl!==null});if(wrapper.____slothletInternal.state.materialized||wrapper.____slothletInternal.impl!==null&&wrapper.____slothletInternal.impl!==void 0){let current=wrapper.createProxy();for(const chainProp of propChain){if(!current)break;const currentWrapper=resolveWrapper(current);if(currentWrapper){const isInternal2=isFrameworkReservedKey(chainProp);if(!isInternal2&&hasOwn(currentWrapper,chainProp)){current=currentWrapper[chainProp];wrapper.slothlet.debug("wrapper",{key:"DEBUG_MODE_WAITING_TYPE_WALK_WRAPPER",chainProp:String(chainProp),typeOf:typeof current});continue}if(currentWrapper.____slothletInternal.impl&&typeof currentWrapper.____slothletInternal.impl==="object"&&currentWrapper.____slothletInternal.impl!==null&&chainProp in currentWrapper.____slothletInternal.impl){current=currentWrapper.____slothletInternal.impl[chainProp];wrapper.slothlet.debug("wrapper",{key:"DEBUG_MODE_WAITING_TYPE_WALK_IMPL",chainProp:String(chainProp),typeOf:typeof current});continue}}wrapper.slothlet.debug("wrapper",{key:"DEBUG_MODE_WAITING_TYPE_WALK_DIRECT",chainProp:String(chainProp),typeOf:typeof current});current=current[chainProp]}const resolvedType=typeof current==="function"?"function":typeof current==="object"&&current!==null?"object":typeof current;wrapper.slothlet.debug("wrapper",{key:"DEBUG_MODE_WAITING_TYPE_RESOLVED",apiPath:wrapper.apiPath,propChain:propChain.join(","),resolvedType});return resolvedType}wrapper.slothlet.debug("wrapper",{key:"DEBUG_MODE_WAITING_TYPE_INFLIGHT",apiPath:wrapper.apiPath,propChain:propChain.join(",")});return TYPE_STATES.IN_FLIGHT}if(prop==="__metadata"){if(wrapper.slothlet.handlers?.metadata){return wrapper.slothlet.handlers.metadata.getMetadata(wrapper)}return{}}if(typeof prop==="symbol")return void 0;if(prop==="length"){return 0}if(prop==="name")return waitingTarget.name||"waitingProxyTarget";if(prop==="toString"){return Function.prototype.toString.bind(waitingTarget)}if(prop==="valueOf"){return Function.prototype.valueOf.bind(waitingTarget)}if(prop==="toJSON"){return()=>void 0}if(prop==="__slothletPath")return wrapper.____slothletInternal.apiPath;if(wrapper.____slothletInternal.impl!==null&&wrapper.____slothletInternal.impl!==void 0&&typeof wrapper.____slothletInternal.impl==="object"&&util.types.isProxy(wrapper.____slothletInternal.impl)){let result=wrapper.____slothletInternal.impl;for(const chainProp of propChain){result=result[chainProp]}return result[prop]}if(wrapper.____slothletInternal.impl!==null&&wrapper.____slothletInternal.impl!==void 0){let current=wrapper;let remainingChain=[...propChain];for(let i=0;i<propChain.length;i++){const chainProp=propChain[i];if(current.____slothletInternal.impl&&typeof current.____slothletInternal.impl==="object"&&util.types.isProxy(current.____slothletInternal.impl)){let proxyResult=current.____slothletInternal.impl;for(const remainingProp of remainingChain){proxyResult=proxyResult[remainingProp]}return proxyResult[prop]}const isInternal2=isFrameworkReservedKey(chainProp);if(!isInternal2&&current&&hasOwn(current,chainProp)){const cached=current[chainProp];const _cachedW2=resolveWrapper(cached);if(_cachedW2){current=_cachedW2;remainingChain.shift()}else{return void 0}}else{return void 0}}if(current&&current.____slothletInternal.impl&&typeof current.____slothletInternal.impl==="object"&&util.types.isProxy(current.____slothletInternal.impl)){return current.____slothletInternal.impl[prop]}const isFinalInternal=isFrameworkReservedKey(prop);if(!isFinalInternal&&hasOwn(current,prop)){return current[prop]}return void 0}const isInternal=isFrameworkReservedKey(prop);if(!isInternal&&hasOwn(wrapper,prop)){wrapper.slothlet.debug("wrapper",{key:"DEBUG_MODE_WAITING_GET_PREMATURE",apiPath:wrapper.____slothletInternal.apiPath,prop});return wrapper[prop]}if(wrapper.____slothletInternal.needsImmediateChildAdoption&&wrapper.____slothletInternal.materializeFunc&&!wrapper.____slothletInternal.state.materialized&&!wrapper.____slothletInternal.state.inFlight){wrapper.slothlet.debug("wrapper",{key:"DEBUG_MODE_WAITING_GET_IMMEDIATE_MAT",apiPath:wrapper.____slothletInternal.apiPath,prop});wrapper._materialize().catch(err=>{wrapper.slothlet.debug("wrapper",{key:"DEBUG_MODE_WAITING_GET_IMMEDIATE_MAT_ERROR",apiPath:wrapper.apiPath,error:err.message})});const isInternal2=isFrameworkReservedKey(prop);if(!isInternal2&&hasOwn(wrapper,prop)){wrapper.slothlet.debug("wrapper",{key:"DEBUG_MODE_WAITING_GET_IMMEDIATE_MAT_SUCCESS",apiPath:wrapper.____slothletInternal.apiPath,prop});return wrapper[prop]}}if(wrapper.____slothletInternal.state.inFlight){return wrapper.___createWaitingProxy([...propChain,prop])}return wrapper.___createWaitingProxy([...propChain,prop])},async apply(___target,___thisArg,args){const ___liveCallerWrapper=wrapper.slothlet.contextManager?.getCallerIdentity?.()?.currentWrapper??null;const ___capture=wrapper.slothlet.handlers?.permissionManager?.isCaptureEnabled()!==false;const ___creationCallerWrapper=___capture?__readGateCaller?.currentWrapper??null:null;const ___capturedCallerWrapper=___liveCallerWrapper??___creationCallerWrapper;wrapper.slothlet.debug("wrapper",{key:"DEBUG_MODE_WAITING_APPLY_ENTRY",apiPath:wrapper.____slothletInternal.apiPath,propChain:propChain.join(","),args:args.join(",")});const chainLabel=propChain.map(prop=>String(prop)).join(".");if(wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.state.materialized&&!wrapper.____slothletInternal.state.inFlight){wrapper.slothlet.debug("wrapper",{key:"DEBUG_MODE_WAITING_APPLY_MATERIALIZE",apiPath:wrapper.____slothletInternal.apiPath});await wrapper._materialize();wrapper.slothlet.debug("wrapper",{key:"DEBUG_MODE_WAITING_APPLY_MATERIALIZED",apiPath:wrapper.____slothletInternal.apiPath})}else if(wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.state.materialized&&wrapper.____slothletInternal.state.inFlight){if(wrapper.____slothletInternal.materializationPromise){await wrapper.____slothletInternal.materializationPromise}else{await wrapper._materialize()}}wrapper.slothlet.debug("wrapper",{key:"DEBUG_MODE_WAITING_APPLY_START_WALK",apiPath:wrapper.____slothletInternal.apiPath,propChain:propChain.join(",")});let current=wrapper.createProxy();let lastWrapper=wrapper;let lastObject=null;for(const prop of propChain){wrapper.slothlet.debug("wrapper",{key:"DEBUG_MODE_WAITING_APPLY_WALK",prop:String(prop),typeOf:typeof current,constructorName:current?.constructor?.name});if(!current){if(propChain.some(p=>typeof p==="symbol")){return void 0}if(wrapper.____slothletInternal.invalid||wrapper.____slothletInternal.impl===null||lastWrapper&&(lastWrapper.__invalid||lastWrapper._impl===null)){return void 0}const finalProp=propChain[propChain.length-1];if(finalProp==="hasAttribute"||finalProp==="toJSON"||finalProp===Symbol.toStringTag||finalProp==="constructor"||typeof finalProp==="symbol"||typeof prop==="symbol"){return void 0}throw new wrapper.slothlet.SlothletError("CHAIN_ACCESS_UNDEFINED",{apiPath:wrapper.____slothletInternal.apiPath,chainLabel,prop:String(prop)},null,{validationError:true})}const currentWrapper=resolveWrapper(current);if(currentWrapper){const state=currentWrapper.____slothletInternal.state;if(!state.materialized){if(!state.inFlight&&typeof current._materialize==="function"){await current._materialize()}while(!currentWrapper.____slothletInternal.state.materialized){const nextState=currentWrapper.____slothletInternal.state;if(!nextState.inFlight&&!nextState.materialized){throw new wrapper.slothlet.SlothletError("CHAIN_MATERIALIZE_FAILED",{apiPath:wrapper.____slothletInternal.apiPath,chainLabel,prop:String(prop)},null,{validationError:true})}await new Promise(resolve=>setImmediate(resolve))}}}if(currentWrapper){lastWrapper=currentWrapper;const isInternal=isFrameworkReservedKey(prop);if(!isInternal&&hasOwn(currentWrapper,prop)){lastObject=current;current=currentWrapper[prop];continue}if(currentWrapper.____slothletInternal.impl&&typeof currentWrapper.____slothletInternal.impl==="object"&&currentWrapper.____slothletInternal.impl!==null&&prop in currentWrapper.____slothletInternal.impl){lastObject=currentWrapper.____slothletInternal.impl;current=currentWrapper.____slothletInternal.impl[prop];continue}}lastObject=current;current=current[prop]}wrapper.slothlet.debug("wrapper",{key:"DEBUG_MODE_WAITING_APPLY",apiPath:wrapper.____slothletInternal.apiPath,propChain:propChain.join(","),typeOf:typeof current,currentName:current?.name,isFunction:typeof current==="function"});if(typeof current==="function"){if(___creationCallerWrapper&&___creationCallerWrapper!==___capturedCallerWrapper){const ___resolvedInner=resolveWrapper(current);const ___targetPath=___resolvedInner?.____slothletInternal?.apiPath??[wrapper.____slothletInternal.apiPath,...propChain].filter(Boolean).join(".");runtime_enforceCapturedCaller(wrapper,___creationCallerWrapper,___targetPath)}if(___capturedCallerWrapper&&wrapper.slothlet.contextManager){const ___instanceStore=wrapper.slothlet.contextManager.instances?.get?.(wrapper.instanceID);if(___instanceStore&&!___instanceStore.currentWrapper){return wrapper.slothlet.contextManager.runInContext(wrapper.instanceID,()=>Reflect.apply(current,lastObject,args),null,[],___capturedCallerWrapper,true)}}const ___identityStore=___capturedCallerWrapper?wrapper.slothlet.contextManager?.instances?.get?.(wrapper.instanceID):null;if(!___identityStore)return Reflect.apply(current,lastObject,args);const ___previousAuthoritative=___identityStore.__authoritativeWrapper;___identityStore.__authoritativeWrapper=___capturedCallerWrapper;try{return Reflect.apply(current,lastObject,args)}finally{___identityStore.__authoritativeWrapper=___previousAuthoritative}}const _finalChainProp=propChain[propChain.length-1];if(_finalChainProp==="hasAttribute"||_finalChainProp==="toJSON"){return void 0}if(current===void 0||current===null){throw new wrapper.slothlet.SlothletError("CHAIN_NOT_CALLABLE",{apiPath:wrapper.____slothletInternal.apiPath,chainLabel},null,{validationError:true})}throw new wrapper.slothlet.SlothletError("CHAIN_NOT_CALLABLE",{apiPath:wrapper.____slothletInternal.apiPath,chainLabel},null,{validationError:true})},getPrototypeOf:()=>null});_proxyRegistry.set(waitingProxy,wrapper);cache.set(cacheKey,waitingProxy);return waitingProxy}createProxy(){const wrapper=this;if(wrapper.____slothletInternal.proxy){return wrapper.____slothletInternal.proxy}if(wrapper.____slothletInternal.materializeOnCreate&&wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.state.materialized&&wrapper.____slothletInternal.materializeFunc){wrapper._materialize().catch(()=>{})}const mightBeCallable=wrapper.____slothletInternal.isCallable||wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.isCallableLocked;let proxyTarget;if(mightBeCallable){proxyTarget=createNamedProxyTarget(wrapper.____slothletInternal.apiPath,"callableProxy")}else if(Array.isArray(wrapper.____slothletInternal.impl)){proxyTarget=wrapper.____slothletInternal.impl}else{proxyTarget=wrapper}if(!Array.isArray(proxyTarget)&&!(util.inspect.custom in proxyTarget)){Object.defineProperty(proxyTarget,util.inspect.custom,{value:function(){const childKeys=Object.keys(wrapper).filter(k=>!k.startsWith("_")&&!k.startsWith("__"));if(childKeys.length>0&&!wrapper.____slothletInternal.isCallable){const obj={};for(const key of childKeys){const child=wrapper[key];if(child&&typeof child.createProxy==="function"){obj[key]=child.createProxy()}else{obj[key]=child}}return obj}if(wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.state.materialized&&(wrapper.____slothletInternal.impl===null||wrapper.____slothletInternal.impl===void 0)){return wrapper.____slothletInternal.proxy||wrapper}return wrapper.____slothletInternal.impl},writable:false,enumerable:false,configurable:true})}const getTrap=(target,prop,____receiver)=>{const enforceReadGate=resolvedValue=>runtime_enforceReadGate(wrapper,prop,resolvedValue);if(target!==wrapper&&prop in target){const desc=Object.getOwnPropertyDescriptor(target,prop);if(desc&&!desc.configurable){if(typeof prop==="string"&&prop.startsWith("__")){return wrapper[prop]}return target[prop]}}if(target===wrapper&&typeof prop==="string"){const desc=Object.getOwnPropertyDescriptor(target,prop);if(desc&&!desc.configurable){return target[prop]}}const isInternalProp=isFrameworkReservedKey(prop);const allowedInternals=new Set(["_materialize","__mode","__apiPath","__isCallable","__materializeOnCreate","__displayName","__type","__materialized","__inFlight","__slothletPath","__metadata","__filePath","__sourceFolder","__moduleID"]);if(isInternalProp&&!allowedInternals.has(prop)){return void 0}if(prop==="power"||prop==="add"){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_GET_START",apiPath:wrapper.____slothletInternal.apiPath,prop:String(prop),mode:wrapper.____slothletInternal.mode,collisionMode:wrapper.____slothletInternal.state.collisionMode||"none",materialized:wrapper.____slothletInternal.state.materialized,hasImpl:wrapper.____slothletInternal.impl!==null,inWrapper:!isInternalProp&&hasOwn(wrapper,prop)})}if(prop==="__mode")return wrapper.____slothletInternal.mode;if(prop==="__apiPath")return wrapper.____slothletInternal.apiPath;if(prop==="__isCallable")return wrapper.____slothletInternal.isCallable;if(prop==="__materializeOnCreate")return wrapper.____slothletInternal.materializeOnCreate;if(prop==="__materialized")return wrapper.____slothletInternal.state.materialized;if(prop==="__inFlight")return wrapper.____slothletInternal.state.inFlight;if(prop==="__displayName")return wrapper.____slothletInternal.displayName;if(prop==="__type"){if(wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.state.materialized&&!wrapper.____slothletInternal.state.inFlight){wrapper._materialize().catch(()=>{})}if(wrapper.____slothletInternal.mode==="lazy"&&wrapper.____slothletInternal.state.inFlight){return TYPE_STATES.IN_FLIGHT}if(wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.state.materialized){return TYPE_STATES.UNMATERIALIZED}const impl=wrapper.____slothletInternal.impl;if(typeof impl==="function"){return"function"}if(impl&&typeof impl==="object"&&typeof impl.default==="function"){return"function"}if(impl&&typeof impl==="object"){return"object"}if(typeof impl==="string"){return"string"}if(typeof impl==="number"){return"number"}if(typeof impl==="boolean"){return"boolean"}if(typeof impl==="symbol"){return"symbol"}if(typeof impl==="bigint"){return"bigint"}return"undefined"}if(prop==="_materialize")return wrapper._materialize.bind(wrapper);if(prop==="__slothletPath")return wrapper.____slothletInternal.apiPath;if(prop==="__metadata"){if(wrapper.slothlet.handlers?.metadata){return wrapper.slothlet.handlers.metadata.getMetadata(wrapper)}return{}}if(prop==="__filePath")return wrapper.____slothletInternal.filePath??void 0;if(prop==="__sourceFolder")return wrapper.____slothletInternal.sourceFolder??void 0;if(prop==="__moduleID")return wrapper.____slothletInternal.moduleID??void 0;if(prop==="__invalid")return wrapper.____slothletInternal.invalid;{const arrImpl=wrapper.____slothletInternal.impl;if(Array.isArray(arrImpl)){const isIndex=typeof prop==="string"&&/^(?:0|[1-9]\d*)$/.test(prop);if(!isIndex){const arrValue=Reflect.get(arrImpl,prop,arrImpl);enforceReadGate(arrValue);return arrValue}}}if(prop==="then"){if(wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.state.materialized){return(onFulfilled,onRejected)=>wrapper._materialize().then(()=>onFulfilled(wrapper.____slothletInternal.proxy)).catch(onRejected)}return void 0}if(prop==="constructor")return Object.prototype.constructor;if(prop===util.inspect.custom){return()=>{const childKeys=Object.keys(wrapper).filter(k=>!k.startsWith("_")&&!k.startsWith("__"));if(childKeys.length>0&&!wrapper.____slothletInternal.isCallable){const obj={};for(const key of childKeys){const child=wrapper[key];if(child&&typeof child.createProxy==="function"){obj[key]=child.createProxy()}else{obj[key]=child}}return obj}if(wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.state.materialized&&(wrapper.____slothletInternal.impl===null||wrapper.____slothletInternal.impl===void 0)){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_INSPECT_LAZY_UNMATERIALIZED",apiPath:wrapper.apiPath,wrapper,____proxy:wrapper.____slothletInternal.proxy});return wrapper||wrapper.____slothletInternal.proxy}return wrapper.____slothletInternal.impl}}if(prop===Symbol.toStringTag){const impl=wrapper.____slothletInternal.impl;if(typeof impl==="function"){return"Function"}if(impl&&typeof impl==="object"&&typeof impl.default==="function"){return"Function"}return"Object"}if(typeof prop==="symbol")return void 0;if(prop==="length"){const impl=wrapper.____slothletInternal.impl;if(typeof impl==="function"){return impl.length}if(impl&&typeof impl==="object"&&typeof impl.default==="function"){return impl.default.length}return 0}if(prop==="name"){if(wrapper.____slothletInternal.apiPath){const pathParts=wrapper.____slothletInternal.apiPath.split(".");const lastPart=pathParts[pathParts.length-1];if(lastPart){return lastPart}}return target.name||"unifiedWrapperProxy"}if(prop==="toString"){const impl=wrapper.____slothletInternal.impl;if(typeof impl==="function"){return impl.toString.bind(impl)}if(impl&&typeof impl==="object"&&typeof impl.default==="function"){return impl.default.toString.bind(impl.default)}if(typeof target==="function"){return Function.prototype.toString.bind(target)}return()=>`[UnifiedWrapper: ${wrapper.____slothletInternal.apiPath}]`}if(prop==="valueOf"){const impl=wrapper.____slothletInternal.impl;if(typeof impl==="function"){return impl.valueOf.bind(impl)}if(impl&&typeof impl==="object"&&typeof impl.default==="function"){return impl.default.valueOf.bind(impl.default)}return Function.prototype.valueOf.bind(target)}if(prop==="toJSON"){const impl=wrapper.____slothletInternal.impl;if(impl&&typeof impl.toJSON==="function"){return impl.toJSON.bind(impl)}return()=>{const data=UnifiedWrapper._extractFullImpl(wrapper);if(data&&typeof data==="object"){delete data.__childFilePaths;delete data.__childFilePathsPreMaterialize}const pm=wrapper.slothlet.handlers?.permissionManager;if(pm&&pm.isEnabled()&&pm.isReadGatingEnabled()){runtime_redactSerialized(wrapper,data,wrapper.____slothletInternal.apiPath,new WeakSet)}return data}}if(wrapper.____slothletInternal.invalid){return void 0}if(wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.state.materialized&&!wrapper.____slothletInternal.state.inFlight){wrapper._materialize().catch(()=>{})}if(hasOwn(wrapper,prop)){if(wrapper.____slothletInternal.state.collisionMode==="replace"&&(prop==="power"||prop==="add")){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_GET_CACHED_REPLACE",apiPath:wrapper.apiPath,prop:String(prop),collisionMode:wrapper.____slothletInternal.state.collisionMode,wrapperKeys:Object.keys(wrapper).filter(k=>!k.startsWith("_")&&!k.startsWith("__")).join(", ")})}this.slothlet.debug("wrapper",{key:"DEBUG_MODE_GET_CACHED",apiPath:wrapper.____slothletInternal.apiPath,prop:String(prop),materialized:wrapper.____slothletInternal.state.materialized,hasImpl:wrapper.____slothletInternal.impl!==null});const cached=wrapper[prop];const _cachedWrapper=resolveWrapper(cached);if(_cachedWrapper?.____slothletInternal?.impl!==null&&_cachedWrapper?.____slothletInternal?.impl!==void 0){const cachedImpl=_cachedWrapper.____slothletInternal.impl;const cachedType=typeof cachedImpl;if(cachedType==="string"||cachedType==="number"||cachedType==="boolean"||cachedType==="bigint"||cachedType==="symbol"){enforceReadGate(cachedImpl);return cachedImpl}}if(_cachedWrapper){const cachedWrapper=_cachedWrapper;if(cachedWrapper.____slothletInternal.mode==="lazy"&&!cachedWrapper.____slothletInternal.state.materialized&&!cachedWrapper.____slothletInternal.state.inFlight){cachedWrapper._materialize().catch(()=>{})}}enforceReadGate(cached);return cached}if(wrapper.____slothletInternal.impl!==null&&wrapper.____slothletInternal.impl!==void 0){if(typeof wrapper.____slothletInternal.impl==="object"&&util.types.isProxy(wrapper.____slothletInternal.impl)){return wrapper.____slothletInternal.impl[prop]}if(hasOwn(wrapper,prop)){if(prop==="power"||prop==="add"){this.slothlet.debug("wrapper",{key:"DEBUG_MODE_GET_PROXYGET_ACCESSING",prop,wrapperId:wrapper.____slothletInternal.id,apiPath:wrapper.apiPath,collisionMode:wrapper.____slothletInternal.state.collisionMode||"none"});this.slothlet.debug("wrapper",{key:"DEBUG_MODE_GET_PROXYGET_FOUND",wrapperKeys:Object.keys(wrapper).filter(k=>!k.startsWith("_")&&!k.startsWith("__")).join(", ")})}const cached=wrapper[prop];const _cachedWrapper4=resolveWrapper(cached);if(_cachedWrapper4){const cachedWrapper=_cachedWrapper4;if(cachedWrapper.____slothletInternal.mode==="lazy"&&!cachedWrapper.____slothletInternal.state.materialized&&!cachedWrapper.____slothletInternal.state.inFlight){cachedWrapper._materialize().catch(()=>{})}}enforceReadGate(cached);return cached}}const isInternalProp2=typeof prop==="string"&&UnifiedWrapper.INTERNAL_KEYS.has(prop);if(wrapper.____slothletInternal.mode==="lazy"&&wrapper.____slothletInternal.state.materialized&&!isInternalProp2&&!hasOwn(wrapper,prop)&&wrapper.____slothletInternal.impl&&!(prop in wrapper.____slothletInternal.impl)){return void 0}if(wrapper.____slothletInternal.mode==="lazy"&&(wrapper.____slothletInternal.state.inFlight||!wrapper.____slothletInternal.impl)){if(!wrapper.____slothletInternal.state.materialized&&!wrapper.____slothletInternal.state.inFlight){wrapper._materialize().catch(()=>{})}this.slothlet.debug("wrapper",{key:"DEBUG_MODE_LAZY_GET_CREATE_WAITING_PROXY",prop:String(prop),collisionMode:wrapper.____slothletInternal.state.collisionMode||"none",apiPath:wrapper.____slothletInternal.apiPath});if(wrapper.____slothletInternal.impl&&typeof wrapper.____slothletInternal.impl==="object"&&util.types.isProxy(wrapper.____slothletInternal.impl)){const value2=wrapper.____slothletInternal.impl[prop];return value2}return wrapper.___createWaitingProxy([prop])}if(wrapper.____slothletInternal.impl&&typeof wrapper.____slothletInternal.impl==="object"&&util.types.isProxy(wrapper.____slothletInternal.impl)){const value2=wrapper.____slothletInternal.impl[prop];return value2}let value=wrapper.____slothletInternal.impl?wrapper.____slothletInternal.impl[prop]:void 0;if(value===void 0&&wrapper.____slothletInternal.impl){const descriptor=Object.getOwnPropertyDescriptor(wrapper.____slothletInternal.impl,prop);if(descriptor&&descriptor.get){value=descriptor.get.call(wrapper.____slothletInternal.impl)}}if(value===void 0&&Object.prototype.hasOwnProperty.call(target,prop)){value=target[prop]}if(value===void 0){return void 0}enforceReadGate(value);const valueType=typeof value;if(value===null||valueType==="string"||valueType==="number"||valueType==="boolean"||valueType==="bigint"||valueType==="symbol"){return value}if(value instanceof Map||value instanceof Set||value instanceof WeakMap||value instanceof WeakSet||value instanceof Date||value instanceof RegExp||value instanceof Promise||value instanceof Error||ArrayBuffer.isView(value)||value instanceof ArrayBuffer){return value}if(value&&typeof value==="object"&&util.types.isProxy(value)){return value}if(value&&(typeof value==="object"||typeof value==="function")&&resolveWrapper(value)!==null){return value}const currentImpl=wrapper.____slothletInternal.impl;if(typeof currentImpl==="function"&&!Object.prototype.propertyIsEnumerable.call(currentImpl,prop)){return value}const wrapped=wrapper.___createChildWrapper(prop,value,null,wrapper.____slothletInternal.deferChildAdopt);if(wrapped){Object.defineProperty(wrapper,prop,{value:wrapped,writable:false,enumerable:true,configurable:true});return wrapped}return value};const applyTrap=(target,thisArg,args)=>{if(wrapper.____slothletInternal.invalid){throw new TypeError(`${wrapper.____slothletInternal.apiPath||"api"} is invalidated`)}enforcePermission(wrapper);const hookManager=wrapper.slothlet.handlers?.hookManager;const hasHooks=hookManager&&hookManager.enabled&&!wrapper.____slothletInternal.apiPath.startsWith("slothlet.hook");const api=wrapper.slothlet.boundApi;const ctx=wrapper.slothlet.config?.context||{};if(hasHooks){const ___strategy=hookManager.getDispatchStrategy(wrapper.____slothletInternal.apiPath);if(___strategy.asyncBefore||___strategy.asyncAfter){const ___path=wrapper.____slothletInternal.apiPath;const ___leafIsAsync=util.types.isAsyncFunction(wrapper.____slothletInternal.impl)||util.types.isAsyncFunction(wrapper.____slothletInternal.impl?.default);const ___promotedRun=(async()=>{let beforeResult;try{beforeResult=await hookManager.executeBeforeHooksAsync(___path,args,api,ctx)}catch(error){hookManager.executeAlwaysHooks(___path,args,void 0,true,[unwrapError(error)],api,ctx);throw error}args=beforeResult.args;if(beforeResult.shortCircuit){hookManager.executeAlwaysHooks(___path,args,beforeResult.value,false,[],api,ctx);return beforeResult.value}if(wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.state.materialized){await wrapper._materialize()}const impl=wrapper.____slothletInternal.impl;let settled;try{let raw;if(typeof impl==="function"){raw=wrapper.slothlet.contextManager?wrapper.slothlet.contextManager.runInContext(wrapper.instanceID,impl,thisArg,args,wrapper):impl.apply(thisArg,args)}else if(impl&&typeof impl==="object"&&typeof impl.default==="function"){raw=wrapper.slothlet.contextManager?wrapper.slothlet.contextManager.runInContext(wrapper.instanceID,impl.default,impl,args,wrapper):impl.default.apply(impl,args)}else{throw new wrapper.SlothletError("INVALID_CONFIG_NOT_A_FUNCTION",{apiPath:___path,actualType:typeof impl},null,{validationError:true})}settled=raw&&typeof raw==="object"&&typeof raw.then==="function"?await raw:raw}catch(error){const originalError=unwrapError(error);if(!error[ERROR_HOOK_PROCESSED]){const sourceInfo={type:"function",timestamp:Date.now(),stack:originalError.stack};hookManager.executeErrorHooks(___path,originalError,sourceInfo,args,api,ctx)}hookManager.executeAlwaysHooks(___path,args,void 0,true,[originalError],api,ctx);if(wrapper.slothlet.config?.hook?.suppressErrors===true)return void 0;throw error}let promotedFinal;try{const afterResult=await hookManager.executeAfterHooksAsync(___path,settled,args,api,ctx);promotedFinal=afterResult.modified?afterResult.result:settled}catch(error){hookManager.executeAlwaysHooks(___path,args,void 0,true,[unwrapError(error)],api,ctx);throw error}hookManager.executeAlwaysHooks(___path,args,promotedFinal,false,[],api,ctx);return promotedFinal})();return ___leafIsAsync?___promotedRun:runtime_guardPromotedResult(___promotedRun,___path,wrapper.SlothletError)}}let result;let finalResult;let isAsync=false;let lastSyncError=null;try{if(hasHooks){const beforeResult=hookManager.executeBeforeHooks(wrapper.____slothletInternal.apiPath,args,api,ctx);args=beforeResult.args;if(beforeResult.shortCircuit){finalResult=beforeResult.value;return beforeResult.value}}if(wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.state.materialized&&!wrapper.____slothletInternal.state.inFlight){wrapper._materialize().catch(()=>{})}if(wrapper.____slothletInternal.mode==="lazy"&&wrapper.____slothletInternal.state.inFlight){return new Promise((resolve,reject)=>{const checkMaterialized=()=>{if(wrapper.____slothletInternal.state.materialized){const impl2=wrapper.____slothletInternal.impl;try{if(typeof impl2==="function"){if(wrapper.slothlet.contextManager){resolve(wrapper.slothlet.contextManager.runInContext(wrapper.instanceID,impl2,thisArg,args,wrapper,true))}else{resolve(impl2.apply(thisArg,args))}}else if(impl2&&typeof impl2==="object"&&typeof impl2.default==="function"){if(wrapper.contextManager){resolve(wrapper.contextManager.runInContext(wrapper.instanceID,impl2.default,impl2,args,wrapper,true))}else{resolve(impl2.default.apply(impl2,args))}}else{reject(new wrapper.slothlet.SlothletError("INVALID_CONFIG_NOT_A_FUNCTION",{apiPath:wrapper.____slothletInternal.apiPath,actualType:typeof impl2},null,{validationError:true}))}}catch(err){reject(err)}return}if(!wrapper.____slothletInternal.state.inFlight){reject(new wrapper.slothlet.SlothletError("INVALID_CONFIG_LAZY_MATERIALIZATION_FAILED",{apiPath:wrapper.____slothletInternal.apiPath},null,{validationError:true}));return}setImmediate(checkMaterialized)};checkMaterialized()})}const impl=wrapper.____slothletInternal.impl;if(typeof impl==="function"){if(wrapper.slothlet.contextManager){result=wrapper.slothlet.contextManager.runInContext(wrapper.instanceID,impl,thisArg,args,wrapper,true)}else{result=impl.apply(thisArg,args)}}else if(impl&&typeof impl==="object"&&typeof impl.default==="function"){if(wrapper.slothlet.contextManager){result=wrapper.slothlet.contextManager.runInContext(wrapper.instanceID,impl.default,impl,args,wrapper,true)}else{result=impl.default.apply(impl,args)}}else{throw new wrapper.SlothletError("INVALID_CONFIG_NOT_A_FUNCTION",{apiPath:wrapper.____slothletInternal.apiPath,actualType:typeof impl},null,{validationError:true})}if(result&&typeof result==="object"&&typeof result.then==="function"){isAsync=true;return result.then(resolvedResult=>{try{if(hasHooks){const afterResult=hookManager.executeAfterHooks(wrapper.____slothletInternal.apiPath,resolvedResult,args,api,ctx);const finalResult2=afterResult.modified?afterResult.result:resolvedResult;hookManager.executeAlwaysHooks(wrapper.____slothletInternal.apiPath,args,finalResult2,false,[],api,ctx);return finalResult2}return resolvedResult}catch(error){if(hasHooks){const originalError=unwrapError(error);const sourceInfo={type:"after",timestamp:Date.now(),stack:originalError.stack};hookManager.executeErrorHooks(wrapper.____slothletInternal.apiPath,originalError,sourceInfo,args,api,ctx);hookManager.executeAlwaysHooks(wrapper.____slothletInternal.apiPath,args,void 0,true,[originalError],api,ctx)}const suppressErrors=wrapper.slothlet.config?.hook?.suppressErrors===true;if(suppressErrors){return void 0}throw error}},error=>{if(hasHooks&&!error[ERROR_HOOK_PROCESSED]){const originalError=unwrapError(error);const sourceInfo={type:"function",timestamp:Date.now(),stack:originalError.stack};hookManager.executeErrorHooks(wrapper.____slothletInternal.apiPath,originalError,sourceInfo,args,api,ctx)}if(hasHooks){const originalError=unwrapError(error);hookManager.executeAlwaysHooks(wrapper.____slothletInternal.apiPath,args,void 0,true,[originalError],api,ctx)}const suppressErrors=wrapper.slothlet.config?.hook?.suppressErrors===true;if(suppressErrors){return void 0}throw error})}finalResult=result;if(hasHooks){const afterResult=hookManager.executeAfterHooks(wrapper.____slothletInternal.apiPath,result,args,api,ctx);if(afterResult.modified){finalResult=afterResult.result}}return finalResult}catch(error){lastSyncError=error;if(hasHooks&&!error[ERROR_HOOK_PROCESSED]){const originalError=unwrapError(error);const sourceInfo={type:"function",timestamp:Date.now(),stack:originalError.stack};hookManager.executeErrorHooks(wrapper.____slothletInternal.apiPath,originalError,sourceInfo,args,api,ctx)}const suppressErrors=wrapper.slothlet.config?.hook?.suppressErrors===true;if(suppressErrors){return void 0}throw error}finally{if(hasHooks&&!isAsync){const syncError=lastSyncError;const resultValue=syncError?void 0:typeof finalResult!=="undefined"?finalResult:result;const errors=syncError?[unwrapError(syncError)]:[];hookManager.executeAlwaysHooks(wrapper.____slothletInternal.apiPath,args,resultValue,!!syncError,errors,api,ctx)}}};const hasTrap=(target,prop)=>{if(prop==="_materialize"){return true}if(wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.state.materialized&&!wrapper.____slothletInternal.state.inFlight){wrapper._materialize().catch(()=>{})}const isInternal=isFrameworkReservedKey(prop);if(!isInternal&&hasOwn(wrapper,prop)){return true}if(!isInternal&&wrapper.____slothletInternal.impl&&(typeof wrapper.____slothletInternal.impl==="object"||typeof wrapper.____slothletInternal.impl==="function")&&prop in wrapper.____slothletInternal.impl){return true}return Object.prototype.hasOwnProperty.call(target,prop)};const getOwnPropertyDescriptorTrap=(target,prop)=>{if(wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.state.materialized&&!wrapper.____slothletInternal.state.inFlight){wrapper._materialize().catch(()=>{})}if(prop==="____slothletInternal")return void 0;if(prop==="prototype"&&typeof target==="function"){const desc=Object.getOwnPropertyDescriptor(target,"prototype");if(desc){return desc}}const ownDesc=Object.getOwnPropertyDescriptor(target,prop);if((!ownDesc||ownDesc.configurable)&&runtime_isReadRedacted(wrapper,prop)){return void 0}if(Object.prototype.hasOwnProperty.call(target,prop)){return Object.getOwnPropertyDescriptor(target,prop)}const isInternal=isFrameworkReservedKey(prop);if(!isInternal&&hasOwn(wrapper,prop)){const desc=Object.getOwnPropertyDescriptor(wrapper,prop);if(desc){return desc}}if(!isInternal&&wrapper.____slothletInternal.impl&&(typeof wrapper.____slothletInternal.impl==="object"||typeof wrapper.____slothletInternal.impl==="function")&&prop in wrapper.____slothletInternal.impl){return Object.getOwnPropertyDescriptor(wrapper.____slothletInternal.impl,prop)}return void 0};const ownKeysTrap=target=>{if(wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.state.materialized&&!wrapper.____slothletInternal.state.inFlight){wrapper._materialize().catch(()=>{})}const keys=new Set;if(typeof target==="function"||target&&target.__isCallable){keys.add("prototype");keys.add("length");keys.add("name")}for(const key of Reflect.ownKeys(target)){const descriptor=Object.getOwnPropertyDescriptor(target,key);if(!descriptor.configurable||descriptor.enumerable){keys.add(key)}}if(target!==wrapper){for(const key of Reflect.ownKeys(wrapper)){const descriptor=Object.getOwnPropertyDescriptor(wrapper,key);if(descriptor&&descriptor.enumerable){keys.add(key)}}}const implKeys=wrapper.____slothletInternal.impl&&(typeof wrapper.____slothletInternal.impl==="object"||typeof wrapper.____slothletInternal.impl==="function")?Reflect.ownKeys(wrapper.____slothletInternal.impl):[];for(const key of implKeys){if(key!=="prototype"&&!IMPL_METADATA_KEYS.has(key)){keys.add(key)}}for(const key of keys){const targetDesc=Object.getOwnPropertyDescriptor(target,key);if(targetDesc&&!targetDesc.configurable)continue;if(runtime_isReadRedacted(wrapper,key))keys.delete(key)}return Array.from(keys)};const setTrap=(target,prop,value)=>{if(wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.state.materialized&&!wrapper.____slothletInternal.state.inFlight){wrapper._materialize()}if(UnifiedWrapper.INTERNAL_KEYS.has(prop)&&prop!=="_materialize")return true;const internalKeys=new Set(["_materialize"]);if(!internalKeys.has(prop)){if(hasOwn(wrapper,prop)){delete wrapper[prop]}let stored=value;const inBuild=wrapper.slothlet.____buildDepth>0;if(!inBuild&&value!==null&&(typeof value==="object"||typeof value==="function")&&!util.types.isProxy(value)&&resolveWrapper(value)===null){const wrapped=wrapper.___createChildWrapper(prop,value,null,true);if(wrapped!==null&&wrapped!==void 0){const wrappedInternal=resolveWrapper(wrapped);if(wrappedInternal)wrappedInternal.____slothletInternal.userAssigned=true;stored=wrapped}}Object.defineProperty(wrapper,prop,{value:stored,writable:false,enumerable:true,configurable:true})}else{target[prop]=value}return true};const deletePropertyTrap=(target,prop)=>{const internalKeys=new Set(["____slothletInternal","__impl","___setImpl","___resetLazy","_materialize","___invalidate","_impl","___getState","__state","__mode","__apiPath","__slothletPath","__isCallable","__materializeOnCreate","__displayName","__type","__metadata","__invalid","__filePath","__sourceFolder","__moduleID","__materialized","__inFlight"]);if(internalKeys.has(prop)){return true}const isInternal=isFrameworkReservedKey(prop);if(!isInternal&&hasOwn(wrapper,prop)){const childWrapper=wrapper[prop];const childWrapperRaw=resolveWrapper(childWrapper);if(childWrapperRaw){childWrapperRaw.___invalidate()}const descriptor=Object.getOwnPropertyDescriptor(wrapper,prop);if(descriptor?.configurable){delete wrapper[prop]}}if(wrapper.____slothletInternal.impl&&typeof wrapper.____slothletInternal.impl==="object"&&prop in wrapper.____slothletInternal.impl){delete wrapper.____slothletInternal.impl[prop]}delete target[prop];return true};const constructTrap=(target,args,newTarget)=>{if(wrapper.____slothletInternal.invalid){throw new TypeError(`${wrapper.____slothletInternal.apiPath||"api"} is invalidated`)}enforcePermission(wrapper);if(wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.state.materialized&&!wrapper.____slothletInternal.state.inFlight){wrapper._materialize().catch(()=>{})}if(wrapper.____slothletInternal.mode==="lazy"&&wrapper.____slothletInternal.state.inFlight){return Promise.resolve(wrapper.____slothletInternal.materializationPromise).then(()=>{if(!wrapper.____slothletInternal.state.materialized){throw new wrapper.slothlet.SlothletError("INVALID_CONFIG_LAZY_MATERIALIZATION_FAILED",{apiPath:wrapper.____slothletInternal.apiPath},null,{validationError:true})}const impl2=wrapper.____slothletInternal.impl;if(typeof impl2==="function"){const effectiveNewTarget=newTarget===wrapper.____slothletInternal.proxy?impl2:newTarget;return Reflect.construct(impl2,args,effectiveNewTarget)}if(impl2&&typeof impl2==="object"&&typeof impl2.default==="function"){const effectiveNewTarget=newTarget===wrapper.____slothletInternal.proxy?impl2.default:newTarget;return Reflect.construct(impl2.default,args,effectiveNewTarget)}throw new wrapper.slothlet.SlothletError("INVALID_CONFIG_NOT_A_FUNCTION",{apiPath:wrapper.____slothletInternal.apiPath,actualType:typeof impl2},null,{validationError:true})})}const impl=wrapper.____slothletInternal.impl;if(typeof impl==="function"){const effectiveNewTarget=newTarget===wrapper.____slothletInternal.proxy?impl:newTarget;return Reflect.construct(impl,args,effectiveNewTarget)}if(impl&&typeof impl==="object"&&typeof impl.default==="function"){const effectiveNewTarget=newTarget===wrapper.____slothletInternal.proxy?impl.default:newTarget;return Reflect.construct(impl.default,args,effectiveNewTarget)}throw new wrapper.SlothletError("INVALID_CONFIG_NOT_A_FUNCTION",{apiPath:wrapper.____slothletInternal.apiPath,actualType:typeof impl},null,{validationError:true})};wrapper.____slothletInternal.proxy=new Proxy(proxyTarget,{get:(target,prop,receiver)=>runtime_bindCapturedIdentity(wrapper,prop,getTrap(target,prop,receiver)),apply:applyTrap,construct:constructTrap,has:hasTrap,getOwnPropertyDescriptor:getOwnPropertyDescriptorTrap,ownKeys:ownKeysTrap,set:setTrap,deleteProperty:deletePropertyTrap,getPrototypeOf:()=>Array.isArray(wrapper.____slothletInternal.impl)?Array.prototype:null});_proxyRegistry.set(wrapper.____slothletInternal.proxy,wrapper);genuineWrappers.add(wrapper);return wrapper.____slothletInternal.proxy}}Object.defineProperty(UnifiedWrapper.prototype,util.inspect.custom,{value:UnifiedWrapper.prototype.____inspectCustom,writable:true,enumerable:false,configurable:true});function resolveWrapper(value){if(!value)return null;const registered=_proxyRegistry.get(value);if(registered)return registered;if(value instanceof UnifiedWrapper&&value.____slothletInternal!=null)return value;return null}export{IMPL_METADATA_KEYS,TYPE_STATES,UnifiedWrapper,isFrameworkReservedKey,resolveWrapper};
@@ -14,4 +14,4 @@
14
14
  limitations under the License.
15
15
  */
16
16
 
17
- import{EventEmitter,AsyncResource}from"@cldmv/slothlet/helpers/platform";import{pinToCurrentCaller}from"@cldmv/slothlet/helpers/caller-pinning";let isInApiContext=null;function setApiContextChecker(checker){isInApiContext=checker}const originalMethods=new Map;const wrappedListeners=new Map;const trackedEmitters=new Set;let isPatchingEnabled=false;function runtime_wrapEventListener(listener){const resource=AsyncResource?new AsyncResource("slothlet-event-listener"):null;const bound=pinToCurrentCaller(listener);const runtime_wrappedListener=function(...args){if(!resource)return bound.apply(this,args);return resource.runInAsyncScope(()=>{return bound.apply(this,args)},this)};runtime_wrappedListener._slothletOriginal=listener;runtime_wrappedListener._slothletResource=resource;return runtime_wrappedListener}function runtime_getListenerTracking(emitter){let emitterTracking=wrappedListeners.get(emitter);if(!emitterTracking){emitterTracking=new Map;wrappedListeners.set(emitter,emitterTracking)}return emitterTracking}function runtime_trackListener(emitter,event,originalListener,wrappedListener){const emitterTracking=runtime_getListenerTracking(emitter);let eventTracking=emitterTracking.get(event);if(!eventTracking){eventTracking=new Map;emitterTracking.set(event,eventTracking)}let wrappers=eventTracking.get(originalListener);if(!wrappers){wrappers=[];eventTracking.set(originalListener,wrappers)}wrappers.push(wrappedListener)}function runtime_getWrappedListener(emitter,event,originalListener){const emitterTracking=wrappedListeners.get(emitter);if(!emitterTracking)return void 0;const eventTracking=emitterTracking.get(event);if(!eventTracking)return void 0;const wrappers=eventTracking.get(originalListener);if(!wrappers||wrappers.length===0)return void 0;return wrappers[wrappers.length-1]}function runtime_untrackListener(emitter,event,originalListener){const emitterTracking=wrappedListeners.get(emitter);if(!emitterTracking)return;const eventTracking=emitterTracking.get(event);if(!eventTracking)return;const wrappers=eventTracking.get(originalListener);if(!wrappers||wrappers.length===0)return;const wrappedListener=wrappers.pop();wrappedListener._slothletResource=null;if(wrappers.length===0){eventTracking.delete(originalListener)}if(eventTracking.size===0){emitterTracking.delete(event)}if(emitterTracking.size===0){wrappedListeners.delete(emitter)}}function runtime_untrackSpecificWrapper(emitter,event,originalListener,wrappedListener){const emitterTracking=wrappedListeners.get(emitter);if(!emitterTracking)return;const eventTracking=emitterTracking.get(event);if(!eventTracking)return;const wrappers=eventTracking.get(originalListener);if(!wrappers||wrappers.length===0)return;const idx=wrappers.indexOf(wrappedListener);if(idx===-1)return;wrappers.splice(idx,1);wrappedListener._slothletResource=null;if(wrappers.length===0){eventTracking.delete(originalListener)}if(eventTracking.size===0){emitterTracking.delete(event)}if(emitterTracking.size===0){wrappedListeners.delete(emitter)}}function runtime_shouldWrapListener(listener){if(typeof listener!=="function")return false;if(listener._slothletOriginal)return false;return true}function runtime_maybeTrackEmitter(emitter){if(isInApiContext&&isInApiContext()){trackedEmitters.add(emitter)}}function runtime_patchOn(){const original=EventEmitter.prototype.on;originalMethods.set("on",original);EventEmitter.prototype.on=function(event,listener){runtime_maybeTrackEmitter(this);if(!runtime_shouldWrapListener(listener)){return original.call(this,event,listener)}const wrapped=runtime_wrapEventListener(listener);runtime_trackListener(this,event,listener,wrapped);return original.call(this,event,wrapped)};EventEmitter.prototype.addListener=EventEmitter.prototype.on}function runtime_patchOnce(){const original=EventEmitter.prototype.once;originalMethods.set("once",original);const originalOn=originalMethods.get("on")??EventEmitter.prototype.on;const originalRemove=originalMethods.get("removeListener")??EventEmitter.prototype.removeListener;EventEmitter.prototype.once=function(event,listener){runtime_maybeTrackEmitter(this);if(!runtime_shouldWrapListener(listener)){return original.call(this,event,listener)}const wrapped=runtime_wrapEventListener(listener);const self=this;const runtime_onceWrapper=function(...args){originalRemove.call(self,event,runtime_onceWrapper);runtime_untrackSpecificWrapper(self,event,listener,runtime_onceWrapper);return wrapped.apply(this,args)};runtime_onceWrapper._slothletOriginal=listener;runtime_onceWrapper._slothletResource=wrapped._slothletResource;runtime_onceWrapper.listener=listener;runtime_trackListener(this,event,listener,runtime_onceWrapper);return originalOn.call(this,event,runtime_onceWrapper)}}function runtime_patchPrependListener(){const original=EventEmitter.prototype.prependListener;originalMethods.set("prependListener",original);EventEmitter.prototype.prependListener=function(event,listener){runtime_maybeTrackEmitter(this);if(!runtime_shouldWrapListener(listener)){return original.call(this,event,listener)}const wrapped=runtime_wrapEventListener(listener);runtime_trackListener(this,event,listener,wrapped);return original.call(this,event,wrapped)}}function runtime_patchPrependOnceListener(){const original=EventEmitter.prototype.prependOnceListener;originalMethods.set("prependOnceListener",original);const originalPrepend=originalMethods.get("prependListener")??EventEmitter.prototype.prependListener;const originalRemove=originalMethods.get("removeListener")??EventEmitter.prototype.removeListener;EventEmitter.prototype.prependOnceListener=function(event,listener){runtime_maybeTrackEmitter(this);if(!runtime_shouldWrapListener(listener)){return original.call(this,event,listener)}const wrapped=runtime_wrapEventListener(listener);const self=this;const runtime_onceWrapper=function(...args){originalRemove.call(self,event,runtime_onceWrapper);runtime_untrackSpecificWrapper(self,event,listener,runtime_onceWrapper);return wrapped.apply(this,args)};runtime_onceWrapper._slothletOriginal=listener;runtime_onceWrapper._slothletResource=wrapped._slothletResource;runtime_onceWrapper.listener=listener;runtime_trackListener(this,event,listener,runtime_onceWrapper);return originalPrepend.call(this,event,runtime_onceWrapper)}}function runtime_patchRemoveListener(){const original=EventEmitter.prototype.removeListener;originalMethods.set("removeListener",original);EventEmitter.prototype.removeListener=function(event,listener){const wrapped=runtime_getWrappedListener(this,event,listener);if(wrapped){const result=original.call(this,event,wrapped);runtime_untrackListener(this,event,listener);return result}return original.call(this,event,listener)};EventEmitter.prototype.off=EventEmitter.prototype.removeListener}function runtime_patchRemoveAllListeners(){const original=EventEmitter.prototype.removeAllListeners;originalMethods.set("removeAllListeners",original);EventEmitter.prototype.removeAllListeners=function(event){const removeEverything=arguments.length===0;const emitterTracking=wrappedListeners.get(this);if(emitterTracking){if(removeEverything){for(const[____evt,eventTracking]of emitterTracking.entries()){for(const wrappers of eventTracking.values()){for(const wrappedListener of wrappers){wrappedListener._slothletResource=null}}}wrappedListeners.delete(this)}else{const eventTracking=emitterTracking.get(event);if(eventTracking){for(const wrappers of eventTracking.values()){for(const wrappedListener of wrappers){wrappedListener._slothletResource=null}}emitterTracking.delete(event);if(emitterTracking.size===0){wrappedListeners.delete(this)}}}}return removeEverything?original.call(this):original.call(this,event)}}function enableEventEmitterPatching(){if(!EventEmitter)return;if(isPatchingEnabled){return}runtime_patchOn();runtime_patchOnce();runtime_patchPrependListener();runtime_patchPrependOnceListener();runtime_patchRemoveListener();runtime_patchRemoveAllListeners();isPatchingEnabled=true}function disableEventEmitterPatching(){if(!EventEmitter)return;if(!isPatchingEnabled){return}for(const[methodName,originalMethod]of originalMethods.entries()){EventEmitter.prototype[methodName]=originalMethod;if(methodName==="on"){EventEmitter.prototype.addListener=originalMethod}else if(methodName==="removeListener"){EventEmitter.prototype.off=originalMethod}}originalMethods.clear();isPatchingEnabled=false}function cleanupEventEmitterResources(){if(!EventEmitter)return;for(const emitter of trackedEmitters){try{emitter.removeAllListeners()}catch(____error){}}trackedEmitters.clear();wrappedListeners.clear()}export{cleanupEventEmitterResources,disableEventEmitterPatching,enableEventEmitterPatching,setApiContextChecker};
17
+ import{EventEmitter,AsyncResource}from"@cldmv/slothlet/helpers/platform";import{pinToCurrentCaller}from"@cldmv/slothlet/helpers/caller-pinning";let isInApiContext=null;function setApiContextChecker(checker){isInApiContext=checker}const originalMethods=new Map;const wrappedListeners=new WeakMap;const trackedEmitters=new Set;let isPatchingEnabled=false;function runtime_wrapEventListener(listener){const resource=AsyncResource?new AsyncResource("slothlet-event-listener"):null;const bound=pinToCurrentCaller(listener);const runtime_wrappedListener=function(...args){if(!resource)return bound.apply(this,args);return resource.runInAsyncScope(()=>{return bound.apply(this,args)},this)};runtime_wrappedListener._slothletOriginal=listener;runtime_wrappedListener._slothletResource=resource;return runtime_wrappedListener}function runtime_getListenerTracking(emitter){let emitterTracking=wrappedListeners.get(emitter);if(!emitterTracking){emitterTracking=new Map;wrappedListeners.set(emitter,emitterTracking)}return emitterTracking}function runtime_trackListener(emitter,event,originalListener,wrappedListener){const emitterTracking=runtime_getListenerTracking(emitter);let eventTracking=emitterTracking.get(event);if(!eventTracking){eventTracking=new Map;emitterTracking.set(event,eventTracking)}let wrappers=eventTracking.get(originalListener);if(!wrappers){wrappers=[];eventTracking.set(originalListener,wrappers)}wrappers.push(wrappedListener)}function runtime_getWrappedListener(emitter,event,originalListener){const emitterTracking=wrappedListeners.get(emitter);if(!emitterTracking)return void 0;const eventTracking=emitterTracking.get(event);if(!eventTracking)return void 0;const wrappers=eventTracking.get(originalListener);if(!wrappers||wrappers.length===0)return void 0;return wrappers[wrappers.length-1]}function runtime_untrackListener(emitter,event,originalListener){const emitterTracking=wrappedListeners.get(emitter);if(!emitterTracking)return;const eventTracking=emitterTracking.get(event);if(!eventTracking)return;const wrappers=eventTracking.get(originalListener);if(!wrappers||wrappers.length===0)return;const wrappedListener=wrappers.pop();wrappedListener._slothletResource=null;if(wrappers.length===0){eventTracking.delete(originalListener)}if(eventTracking.size===0){emitterTracking.delete(event)}if(emitterTracking.size===0){wrappedListeners.delete(emitter)}}function runtime_untrackSpecificWrapper(emitter,event,originalListener,wrappedListener){const emitterTracking=wrappedListeners.get(emitter);if(!emitterTracking)return;const eventTracking=emitterTracking.get(event);if(!eventTracking)return;const wrappers=eventTracking.get(originalListener);if(!wrappers||wrappers.length===0)return;const idx=wrappers.indexOf(wrappedListener);if(idx===-1)return;wrappers.splice(idx,1);wrappedListener._slothletResource=null;if(wrappers.length===0){eventTracking.delete(originalListener)}if(eventTracking.size===0){emitterTracking.delete(event)}if(emitterTracking.size===0){wrappedListeners.delete(emitter)}}function runtime_shouldWrapListener(listener){if(typeof listener!=="function")return false;if(listener._slothletOriginal)return false;return true}function runtime_maybeTrackEmitter(emitter){if(isInApiContext&&isInApiContext()){trackedEmitters.add(emitter)}}function runtime_patchOn(){const original=EventEmitter.prototype.on;originalMethods.set("on",original);EventEmitter.prototype.on=function(event,listener){runtime_maybeTrackEmitter(this);if(!runtime_shouldWrapListener(listener)){return original.call(this,event,listener)}const wrapped=runtime_wrapEventListener(listener);runtime_trackListener(this,event,listener,wrapped);return original.call(this,event,wrapped)};EventEmitter.prototype.addListener=EventEmitter.prototype.on}function runtime_patchOnce(){const original=EventEmitter.prototype.once;originalMethods.set("once",original);const originalOn=originalMethods.get("on")??EventEmitter.prototype.on;const originalRemove=originalMethods.get("removeListener")??EventEmitter.prototype.removeListener;EventEmitter.prototype.once=function(event,listener){runtime_maybeTrackEmitter(this);if(!runtime_shouldWrapListener(listener)){return original.call(this,event,listener)}const wrapped=runtime_wrapEventListener(listener);const self=this;const runtime_onceWrapper=function(...args){originalRemove.call(self,event,runtime_onceWrapper);runtime_untrackSpecificWrapper(self,event,listener,runtime_onceWrapper);return wrapped.apply(this,args)};runtime_onceWrapper._slothletOriginal=listener;runtime_onceWrapper._slothletResource=wrapped._slothletResource;runtime_onceWrapper.listener=listener;runtime_trackListener(this,event,listener,runtime_onceWrapper);return originalOn.call(this,event,runtime_onceWrapper)}}function runtime_patchPrependListener(){const original=EventEmitter.prototype.prependListener;originalMethods.set("prependListener",original);EventEmitter.prototype.prependListener=function(event,listener){runtime_maybeTrackEmitter(this);if(!runtime_shouldWrapListener(listener)){return original.call(this,event,listener)}const wrapped=runtime_wrapEventListener(listener);runtime_trackListener(this,event,listener,wrapped);return original.call(this,event,wrapped)}}function runtime_patchPrependOnceListener(){const original=EventEmitter.prototype.prependOnceListener;originalMethods.set("prependOnceListener",original);const originalPrepend=originalMethods.get("prependListener")??EventEmitter.prototype.prependListener;const originalRemove=originalMethods.get("removeListener")??EventEmitter.prototype.removeListener;EventEmitter.prototype.prependOnceListener=function(event,listener){runtime_maybeTrackEmitter(this);if(!runtime_shouldWrapListener(listener)){return original.call(this,event,listener)}const wrapped=runtime_wrapEventListener(listener);const self=this;const runtime_onceWrapper=function(...args){originalRemove.call(self,event,runtime_onceWrapper);runtime_untrackSpecificWrapper(self,event,listener,runtime_onceWrapper);return wrapped.apply(this,args)};runtime_onceWrapper._slothletOriginal=listener;runtime_onceWrapper._slothletResource=wrapped._slothletResource;runtime_onceWrapper.listener=listener;runtime_trackListener(this,event,listener,runtime_onceWrapper);return originalPrepend.call(this,event,runtime_onceWrapper)}}function runtime_patchRemoveListener(){const original=EventEmitter.prototype.removeListener;originalMethods.set("removeListener",original);EventEmitter.prototype.removeListener=function(event,listener){const wrapped=runtime_getWrappedListener(this,event,listener);if(wrapped){const result=original.call(this,event,wrapped);runtime_untrackListener(this,event,listener);return result}return original.call(this,event,listener)};EventEmitter.prototype.off=EventEmitter.prototype.removeListener}function runtime_patchRemoveAllListeners(){const original=EventEmitter.prototype.removeAllListeners;originalMethods.set("removeAllListeners",original);EventEmitter.prototype.removeAllListeners=function(event){const removeEverything=arguments.length===0;const emitterTracking=wrappedListeners.get(this);if(emitterTracking){if(removeEverything){for(const[____evt,eventTracking]of emitterTracking.entries()){for(const wrappers of eventTracking.values()){for(const wrappedListener of wrappers){wrappedListener._slothletResource=null}}}wrappedListeners.delete(this)}else{const eventTracking=emitterTracking.get(event);if(eventTracking){for(const wrappers of eventTracking.values()){for(const wrappedListener of wrappers){wrappedListener._slothletResource=null}}emitterTracking.delete(event);if(emitterTracking.size===0){wrappedListeners.delete(this)}}}}return removeEverything?original.call(this):original.call(this,event)}}function enableEventEmitterPatching(){if(!EventEmitter)return;if(isPatchingEnabled){return}runtime_patchOn();runtime_patchOnce();runtime_patchPrependListener();runtime_patchPrependOnceListener();runtime_patchRemoveListener();runtime_patchRemoveAllListeners();isPatchingEnabled=true}function disableEventEmitterPatching(){if(!EventEmitter)return;if(!isPatchingEnabled){return}for(const[methodName,originalMethod]of originalMethods.entries()){EventEmitter.prototype[methodName]=originalMethod;if(methodName==="on"){EventEmitter.prototype.addListener=originalMethod}else if(methodName==="removeListener"){EventEmitter.prototype.off=originalMethod}}originalMethods.clear();isPatchingEnabled=false}function cleanupEventEmitterResources(){if(!EventEmitter)return;for(const emitter of trackedEmitters){try{emitter.removeAllListeners()}catch(____error){}wrappedListeners.delete(emitter)}trackedEmitters.clear()}export{cleanupEventEmitterResources,disableEventEmitterPatching,enableEventEmitterPatching,setApiContextChecker};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cldmv/slothlet",
3
- "version": "3.15.1",
3
+ "version": "3.15.2",
4
4
  "moduleVersions": {
5
5
  "lazy": "3.0.0",
6
6
  "eager": "3.0.0",