@cldmv/slothlet 3.9.0 → 3.9.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.
Files changed (45) hide show
  1. package/README.md +20 -9
  2. package/dist/lib/builders/api_builder.mjs +1 -1
  3. package/dist/lib/handlers/api-manager.mjs +1 -1
  4. package/dist/lib/handlers/context-async.mjs +1 -1
  5. package/dist/lib/handlers/hook-manager.mjs +1 -1
  6. package/dist/lib/handlers/metadata.mjs +1 -1
  7. package/dist/lib/handlers/unified-wrapper.mjs +1 -1
  8. package/dist/lib/handlers/version-manager.mjs +1 -1
  9. package/dist/lib/helpers/class-instance-wrapper.mjs +1 -1
  10. package/dist/lib/helpers/config.mjs +1 -1
  11. package/dist/lib/helpers/eventemitter-context.mjs +1 -1
  12. package/dist/lib/helpers/generate-manifest.mjs +1 -1
  13. package/dist/lib/helpers/module-discovery.mjs +1 -1
  14. package/dist/lib/helpers/module-manifest-validator.mjs +1 -1
  15. package/dist/lib/helpers/platform.mjs +17 -0
  16. package/dist/lib/helpers/resolve-from-caller.mjs +1 -1
  17. package/dist/lib/i18n/translations.mjs +1 -1
  18. package/dist/lib/processors/loader.mjs +1 -1
  19. package/dist/slothlet.mjs +1 -1
  20. package/index.mjs +17 -10
  21. package/package.json +8 -2
  22. package/types/dist/lib/builders/api_builder.d.mts.map +1 -1
  23. package/types/dist/lib/handlers/api-manager.d.mts.map +1 -1
  24. package/types/dist/lib/handlers/context-async.d.mts.map +1 -1
  25. package/types/dist/lib/handlers/hook-manager.d.mts +6 -3
  26. package/types/dist/lib/handlers/hook-manager.d.mts.map +1 -1
  27. package/types/dist/lib/handlers/metadata.d.mts.map +1 -1
  28. package/types/dist/lib/handlers/unified-wrapper.d.mts.map +1 -1
  29. package/types/dist/lib/handlers/version-manager.d.mts.map +1 -1
  30. package/types/dist/lib/helpers/class-instance-wrapper.d.mts.map +1 -1
  31. package/types/dist/lib/helpers/config.d.mts +10 -0
  32. package/types/dist/lib/helpers/config.d.mts.map +1 -1
  33. package/types/dist/lib/helpers/eventemitter-context.d.mts.map +1 -1
  34. package/types/dist/lib/helpers/generate-manifest.d.mts +9 -0
  35. package/types/dist/lib/helpers/generate-manifest.d.mts.map +1 -1
  36. package/types/dist/lib/helpers/module-discovery.d.mts.map +1 -1
  37. package/types/dist/lib/helpers/module-manifest-validator.d.mts.map +1 -1
  38. package/types/dist/lib/helpers/platform.d.mts +12 -0
  39. package/types/dist/lib/helpers/platform.d.mts.map +1 -0
  40. package/types/dist/lib/helpers/resolve-from-caller.d.mts.map +1 -1
  41. package/types/dist/lib/i18n/translations.d.mts +1 -0
  42. package/types/dist/lib/i18n/translations.d.mts.map +1 -1
  43. package/types/dist/lib/processors/loader.d.mts.map +1 -1
  44. package/types/dist/slothlet.d.mts.map +1 -1
  45. package/types/index.d.mts.map +1 -1
@@ -14,4 +14,4 @@
14
14
  limitations under the License.
15
15
  */
16
16
 
17
- import{ComponentBase}from"@cldmv/slothlet/factories/component-base";import{compilePattern}from"@cldmv/slothlet/helpers/pattern-matcher";const ERROR_HOOK_PROCESSED=Symbol.for("@cldmv/slothlet/hook-error-processed");class HookManager extends ComponentBase{static slothletProperty="hookManager";#hooks={before:{before:{},primary:{},after:{}},after:{before:{},primary:{},after:{}},always:{before:{},primary:{},after:{}},error:{before:{},primary:{},after:{}}};#byId=new Map;#idCounter=0;#validTypes=new Set(["before","after","always","error"]);#validSubsets=new Set(["before","primary","after"]);constructor(slothlet){super(slothlet);const hookConfig=slothlet.config?.hook||{enabled:false,pattern:"**",suppressErrors:false};this.enabled=hookConfig.enabled;this.defaultPattern=hookConfig.pattern||"**";this.suppressErrors=hookConfig.suppressErrors||false;this.enabledPatterns=new Set;this.patternFilterActive=false;this.hooks=new Map;this.registrationOrder=0;this.reportedErrors=new WeakSet}on(typePattern,handler,options={}){let{type,pattern}=this.#parseTypePattern(typePattern);if(options.pattern!==void 0){pattern=options.pattern}if(!this.#validTypes.has(type)){throw new this.slothlet.SlothletError("INVALID_HOOK_TYPE",{type,validTypes:Array.from(this.#validTypes)})}if(typeof handler!=="function"){throw new this.slothlet.SlothletError("INVALID_HOOK_HANDLER",{receivedType:typeof handler,validationError:true})}const id=options.id||this.#generateId();if(this.#byId.has(id)){throw new this.slothlet.SlothletError("DUPLICATE_HOOK_ID",{id,validationError:true})}const subset=options.subset||"primary";if(!this.#validSubsets.has(subset)){throw new this.slothlet.SlothletError("INVALID_HOOK_SUBSET",{subset,validSubsets:Array.from(this.#validSubsets)})}this.#compilePattern(pattern);const lockCaller=options.lockCaller!==false;const effectiveHandler=lockCaller?this.#pinHandler(handler):handler;const hook={id,type,pattern,handler:effectiveHandler,lockCaller,priority:options.priority||0,subset,enabled:true,_compiled:null};const typeIndex=this.#hooks[type];const subsetIndex=typeIndex[subset];if(!subsetIndex[pattern]){subsetIndex[pattern]=[]}subsetIndex[pattern].push(hook);this.#byId.set(id,hook);return id}#pinHandler(handler){if(typeof handler._slothletOriginal==="function")return handler;const slothlet=this.slothlet;const capturedWrapper=slothlet.contextManager?.tryGetContext?.()?.currentWrapper??null;if(!capturedWrapper)return handler;const pinned=function slothlet_pinnedHook(...args){return slothlet.contextManager.runInContext(slothlet.instanceID,handler,this,args,capturedWrapper,true)};pinned._slothletOriginal=handler;return pinned}remove(filter={}){let removed=0;if(filter.id){const hook=this.#byId.get(filter.id);if(hook){this.#removeHook(hook);removed=1}return removed}const types=filter.type?[filter.type]:Array.from(this.#validTypes);for(const type of types){const typeIndex=this.#hooks[type];for(const subset of["before","primary","after"]){const subsetIndex=typeIndex[subset];if(filter.pattern){const patternHooks=subsetIndex[filter.pattern];if(patternHooks){removed+=patternHooks.length;patternHooks.forEach(hook=>this.#byId.delete(hook.id));delete subsetIndex[filter.pattern]}}else{for(const pattern in subsetIndex){const patternHooks=subsetIndex[pattern];removed+=patternHooks.length;patternHooks.forEach(hook=>this.#byId.delete(hook.id));delete subsetIndex[pattern]}}}}return removed}enable(filter={}){if(typeof filter==="string"){filter={pattern:filter}}this.enabled=true;return this.#setEnabledState(filter,true)}disable(filter={}){if(typeof filter==="string"){filter={pattern:filter}}if(Object.keys(filter).length===0){this.enabled=false}return this.#setEnabledState(filter,false)}list(filter={}){if(typeof filter==="string"){if(this.#validTypes.has(filter)){filter={type:filter}}else{filter={pattern:filter}}}const hooks=[];if(filter.id){const hook=this.#byId.get(filter.id);if(hook&&(filter.enabled===void 0||hook.enabled===filter.enabled)){hooks.push(this.#serializeHook(hook))}return{registeredHooks:hooks}}const types=filter.type?[filter.type]:Array.from(this.#validTypes);let patternMatcher=null;if(filter.pattern){patternMatcher=this.#compilePattern(filter.pattern)}for(const type of types){const typeIndex=this.#hooks[type];for(const subset of["before","primary","after"]){const subsetIndex=typeIndex[subset];for(const pattern in subsetIndex){const patternHooks=subsetIndex[pattern];for(const hook of patternHooks){if(filter.enabled!==void 0&&hook.enabled!==filter.enabled){continue}if(patternMatcher&&!patternMatcher(hook.pattern)){continue}hooks.push(this.#serializeHook(hook))}}}}return{registeredHooks:hooks}}getHooksForPath(type,apiPath){if(this.enabled===false){return[]}const typeIndex=this.#hooks[type];if(!typeIndex){return[]}const hooks=[];for(const subset of["before","primary","after"]){const subsetIndex=typeIndex[subset];const subsetHooks=[];for(const pattern in subsetIndex){const patternHooks=subsetIndex[pattern];if(pattern===apiPath){subsetHooks.push(...patternHooks.filter(h=>h.enabled));continue}for(const hook of patternHooks){if(!hook.enabled)continue;if(!hook._compiled){hook._compiled=this.#compilePattern(hook.pattern)}if(hook._compiled(apiPath)){subsetHooks.push(hook)}}}subsetHooks.sort((a,b)=>b.priority-a.priority);hooks.push(...subsetHooks)}return hooks}executeBeforeHooks(path,args,api,ctx){const hooks=this.getHooksForPath("before",path);for(const hook of hooks){try{const result=hook.handler({path,args,api,ctx});if(result&&typeof result==="object"&&typeof result.then==="function"){throw new this.SlothletError("HOOK_BEFORE_RETURNED_PROMISE",{id:hook.id,path},null,{validationError:true})}if(result!==void 0&&!Array.isArray(result)){return{args,shortCircuit:true,value:result}}if(Array.isArray(result)){args=result}}catch(error){const sourceInfo={type:"before",subset:hook.subset,hookTag:hook.id,hookId:hook.id,timestamp:Date.now(),stack:error.stack};this.executeErrorHooks(path,error,sourceInfo,args,api,ctx);if(!this.suppressErrors){throw error}return{args,shortCircuit:true,value:void 0}}}return{args,shortCircuit:false}}executeAfterHooks(path,result,args,api,ctx){const hooks=this.getHooksForPath("after",path);const originalResult=result;let currentResult=result;for(const hook of hooks){try{const hookContext={path,args,result:currentResult,api,ctx};const transformed=hook.handler(hookContext);if(transformed!==void 0){currentResult=transformed}}catch(error){const sourceInfo={type:"after",subset:hook.subset,hookTag:hook.id,hookId:hook.id,timestamp:Date.now(),stack:error.stack};this.executeErrorHooks(path,error,sourceInfo,args,api,ctx);if(!this.suppressErrors){throw error}}}if(currentResult===originalResult){return{modified:false}}else{return{modified:true,result:currentResult}}}executeAlwaysHooks(path,args,resultOrError,hasError=false,errors=[],api,ctx){const hooks=this.getHooksForPath("always",path);for(const hook of hooks){try{hook.handler({path,args,result:hasError?void 0:resultOrError,hasError,errors,api,ctx})}catch(error){const sourceInfo={type:"always",subset:hook.subset,hookTag:hook.id,hookId:hook.id,timestamp:Date.now(),stack:error.stack};this.executeErrorHooks(path,error,sourceInfo,args,api,ctx)}}}executeErrorHooks(path,error,source,args,api,ctx){if(error&&typeof error==="object"){error[ERROR_HOOK_PROCESSED]=true}const hooks=this.getHooksForPath("error",path);for(const hook of hooks){try{hook.handler({path,args,error,errorType:error?.constructor?.name||"Error",source,timestamp:new Date,api,ctx})}catch(hookError){this.slothlet.debug("hooks",`Error hook failed for ${path}:`,hookError)}}}#parseTypePattern(typePattern){if(typeof typePattern!=="string"){throw new this.slothlet.SlothletError("INVALID_TYPE_PATTERN",{typePattern,expected:"string in format 'type:pattern'"})}const colonIndex=typePattern.indexOf(":");if(colonIndex===-1){throw new this.slothlet.SlothletError("INVALID_TYPE_PATTERN",{typePattern,expected:"string in format 'type:pattern' with at least one colon"})}const type=typePattern.substring(0,colonIndex);const pattern=typePattern.substring(colonIndex+1);if(!type||!pattern){throw new this.slothlet.SlothletError("INVALID_TYPE_PATTERN",{typePattern,expected:"non-empty type and pattern"})}return{type,pattern}}#compilePattern(pattern){return compilePattern(pattern,{onMaxDepth:maxDepth=>{throw new this.SlothletError("HOOK_BRACE_EXPANSION_MAX_DEPTH",{maxDepth},null,{validationError:true})}})}getCompilePatternForDiagnostics(){return this.#compilePattern.bind(this)}#generateId(){return`hook-${++this.#idCounter}`}#removeHook(hook){const typeIndex=this.#hooks[hook.type];const subsetIndex=typeIndex[hook.subset];const patternHooks=subsetIndex[hook.pattern];if(!patternHooks){throw new this.slothlet.SlothletError("INTERNAL_HOOK_STATE_CORRUPT",{hookId:hook.id,type:hook.type,subset:hook.subset,pattern:hook.pattern,detail:"patternHooks array missing from subsetIndex \u2014 #byId and #hooks are desynced"})}const index=patternHooks.indexOf(hook);if(index===-1){throw new this.slothlet.SlothletError("INTERNAL_HOOK_STATE_CORRUPT",{hookId:hook.id,type:hook.type,subset:hook.subset,pattern:hook.pattern,detail:"hook object not found in patternHooks array \u2014 #byId and #hooks are desynced"})}patternHooks.splice(index,1);if(patternHooks.length===0){delete subsetIndex[hook.pattern]}this.#byId.delete(hook.id)}#setEnabledState(filter,enabled){let affected=0;if(filter.id){const hook=this.#byId.get(filter.id);if(hook){hook.enabled=enabled;affected=1}return affected}const types=filter.type?[filter.type]:Array.from(this.#validTypes);for(const type of types){const typeIndex=this.#hooks[type];for(const subset of["before","primary","after"]){const subsetIndex=typeIndex[subset];if(filter.pattern){const patternHooks=subsetIndex[filter.pattern]||[];for(const hook of patternHooks){hook.enabled=enabled;affected++}}else{for(const pattern in subsetIndex){const patternHooks=subsetIndex[pattern];for(const hook of patternHooks){hook.enabled=enabled;affected++}}}}}return affected}#serializeHook(hook){return{id:hook.id,type:hook.type,pattern:hook.pattern,priority:hook.priority,subset:hook.subset,enabled:hook.enabled,lockCaller:hook.lockCaller}}exportHooks(){const registrations=[];for(const hook of this.#byId.values()){registrations.push({typePattern:`${hook.type}:${hook.pattern}`,handler:hook.handler,options:{id:hook.id,priority:hook.priority,subset:hook.subset,lockCaller:hook.lockCaller},enabled:hook.enabled})}return registrations}importHooks(registrations){if(!Array.isArray(registrations))return;for(const reg of registrations){this.on(reg.typePattern,reg.handler,reg.options);if(!reg.enabled){this.disable({id:reg.options.id})}}}async shutdown(){this.#hooks={before:{before:{},primary:{},after:{}},after:{before:{},primary:{},after:{}},always:{before:{},primary:{},after:{}},error:{before:{},primary:{},after:{}}};this.#byId.clear();this.#idCounter=0}}export{HookManager};
17
+ import{ComponentBase}from"@cldmv/slothlet/factories/component-base";import{compilePattern}from"@cldmv/slothlet/helpers/pattern-matcher";import{normalizeHookConfig}from"@cldmv/slothlet/helpers/config";const ERROR_HOOK_PROCESSED=Symbol.for("@cldmv/slothlet/hook-error-processed");class HookManager extends ComponentBase{static slothletProperty="hookManager";#hooks={before:{before:{},primary:{},after:{}},after:{before:{},primary:{},after:{}},always:{before:{},primary:{},after:{}},error:{before:{},primary:{},after:{}}};#byId=new Map;#idCounter=0;#validTypes=new Set(["before","after","always","error"]);#validSubsets=new Set(["before","primary","after"]);constructor(slothlet){super(slothlet);const hookConfig=normalizeHookConfig(slothlet.config?.hook);this.enabled=hookConfig.enabled;this.defaultPattern=hookConfig.pattern||"**";this.suppressErrors=hookConfig.suppressErrors||false;this.enabledPatterns=new Set;this.patternFilterActive=false;if(this.defaultPattern!=="**"){this.enabledPatterns.add(this.defaultPattern);this.patternFilterActive=true}this.hooks=new Map;this.registrationOrder=0;this.reportedErrors=new WeakSet}#globalFilterCache=new Map;#pathMatchesGlobalFilter(apiPath){if(!this.patternFilterActive){return true}for(const pattern of this.enabledPatterns){let matcher=this.#globalFilterCache.get(pattern);if(!matcher){matcher=this.#compilePattern(pattern);this.#globalFilterCache.set(pattern,matcher)}if(matcher(apiPath)){return true}}return false}on(typePattern,handler,options={}){let{type,pattern}=this.#parseTypePattern(typePattern);if(options.pattern!==void 0){pattern=options.pattern}if(!this.#validTypes.has(type)){throw new this.slothlet.SlothletError("INVALID_HOOK_TYPE",{type,validTypes:Array.from(this.#validTypes)})}if(typeof handler!=="function"){throw new this.slothlet.SlothletError("INVALID_HOOK_HANDLER",{receivedType:typeof handler,validationError:true})}const id=options.id||this.#generateId();if(this.#byId.has(id)){throw new this.slothlet.SlothletError("DUPLICATE_HOOK_ID",{id,validationError:true})}const subset=options.subset||"primary";if(!this.#validSubsets.has(subset)){throw new this.slothlet.SlothletError("INVALID_HOOK_SUBSET",{subset,validSubsets:Array.from(this.#validSubsets)})}this.#compilePattern(pattern);const lockCaller=options.lockCaller!==false;const effectiveHandler=lockCaller?this.#pinHandler(handler):handler;const hook={id,type,pattern,handler:effectiveHandler,lockCaller,priority:options.priority||0,subset,enabled:true,_compiled:null};const typeIndex=this.#hooks[type];const subsetIndex=typeIndex[subset];if(!subsetIndex[pattern]){subsetIndex[pattern]=[]}subsetIndex[pattern].push(hook);this.#byId.set(id,hook);return id}#pinHandler(handler){if(typeof handler._slothletOriginal==="function")return handler;const slothlet=this.slothlet;const capturedWrapper=slothlet.contextManager?.tryGetContext?.()?.currentWrapper??null;if(!capturedWrapper)return handler;const pinned=function slothlet_pinnedHook(...args){return slothlet.contextManager.runInContext(slothlet.instanceID,handler,this,args,capturedWrapper,true)};pinned._slothletOriginal=handler;return pinned}remove(filter={}){let removed=0;if(filter.id){const hook=this.#byId.get(filter.id);if(hook){this.#removeHook(hook);removed=1}return removed}const types=filter.type?[filter.type]:Array.from(this.#validTypes);for(const type of types){const typeIndex=this.#hooks[type];for(const subset of["before","primary","after"]){const subsetIndex=typeIndex[subset];if(filter.pattern){const patternHooks=subsetIndex[filter.pattern];if(patternHooks){removed+=patternHooks.length;patternHooks.forEach(hook=>this.#byId.delete(hook.id));delete subsetIndex[filter.pattern]}}else{for(const pattern in subsetIndex){const patternHooks=subsetIndex[pattern];removed+=patternHooks.length;patternHooks.forEach(hook=>this.#byId.delete(hook.id));delete subsetIndex[pattern]}}}}return removed}enable(filter={}){if(typeof filter==="string"){filter={pattern:filter}}this.enabled=true;return this.#setEnabledState(filter,true)}disable(filter={}){if(typeof filter==="string"){filter={pattern:filter}}if(Object.keys(filter).length===0){this.enabled=false}return this.#setEnabledState(filter,false)}enablePattern(pattern){this.#compilePattern(pattern);this.enabledPatterns.add(pattern);this.patternFilterActive=true;return this.enabledPatterns.size}disablePattern(pattern){this.enabledPatterns.delete(pattern);this.#globalFilterCache.delete(pattern);if(this.enabledPatterns.size===0){this.patternFilterActive=false}return this.enabledPatterns.size}resetPatternFilter(){this.enabledPatterns.clear();this.#globalFilterCache.clear();this.patternFilterActive=false;if(this.defaultPattern!=="**"){this.enabledPatterns.add(this.defaultPattern);this.patternFilterActive=true}}list(filter={}){if(typeof filter==="string"){if(this.#validTypes.has(filter)){filter={type:filter}}else{filter={pattern:filter}}}const hooks=[];if(filter.id){const hook=this.#byId.get(filter.id);if(hook&&(filter.enabled===void 0||hook.enabled===filter.enabled)){hooks.push(this.#serializeHook(hook))}return{registeredHooks:hooks}}const types=filter.type?[filter.type]:Array.from(this.#validTypes);let patternMatcher=null;if(filter.pattern){patternMatcher=this.#compilePattern(filter.pattern)}for(const type of types){const typeIndex=this.#hooks[type];for(const subset of["before","primary","after"]){const subsetIndex=typeIndex[subset];for(const pattern in subsetIndex){const patternHooks=subsetIndex[pattern];for(const hook of patternHooks){if(filter.enabled!==void 0&&hook.enabled!==filter.enabled){continue}if(patternMatcher&&!patternMatcher(hook.pattern)){continue}hooks.push(this.#serializeHook(hook))}}}}return{registeredHooks:hooks}}getHooksForPath(type,apiPath){if(this.enabled===false){return[]}if(!this.#pathMatchesGlobalFilter(apiPath)){return[]}const typeIndex=this.#hooks[type];if(!typeIndex){return[]}const hooks=[];for(const subset of["before","primary","after"]){const subsetIndex=typeIndex[subset];const subsetHooks=[];for(const pattern in subsetIndex){const patternHooks=subsetIndex[pattern];if(pattern===apiPath){subsetHooks.push(...patternHooks.filter(h=>h.enabled));continue}for(const hook of patternHooks){if(!hook.enabled)continue;if(!hook._compiled){hook._compiled=this.#compilePattern(hook.pattern)}if(hook._compiled(apiPath)){subsetHooks.push(hook)}}}subsetHooks.sort((a,b)=>b.priority-a.priority);hooks.push(...subsetHooks)}return hooks}executeBeforeHooks(path,args,api,ctx){const hooks=this.getHooksForPath("before",path);for(const hook of hooks){try{const result=hook.handler({path,args,api,ctx});if(result&&typeof result==="object"&&typeof result.then==="function"){throw new this.SlothletError("HOOK_BEFORE_RETURNED_PROMISE",{id:hook.id,path},null,{validationError:true})}if(result!==void 0&&!Array.isArray(result)){return{args,shortCircuit:true,value:result}}if(Array.isArray(result)){args=result}}catch(error){const sourceInfo={type:"before",subset:hook.subset,hookTag:hook.id,hookId:hook.id,timestamp:Date.now(),stack:error.stack};this.executeErrorHooks(path,error,sourceInfo,args,api,ctx);if(!this.suppressErrors){throw error}return{args,shortCircuit:true,value:void 0}}}return{args,shortCircuit:false}}executeAfterHooks(path,result,args,api,ctx){const hooks=this.getHooksForPath("after",path);const originalResult=result;let currentResult=result;for(const hook of hooks){try{const hookContext={path,args,result:currentResult,api,ctx};const transformed=hook.handler(hookContext);if(transformed!==void 0){currentResult=transformed}}catch(error){const sourceInfo={type:"after",subset:hook.subset,hookTag:hook.id,hookId:hook.id,timestamp:Date.now(),stack:error.stack};this.executeErrorHooks(path,error,sourceInfo,args,api,ctx);if(!this.suppressErrors){throw error}}}if(currentResult===originalResult){return{modified:false}}else{return{modified:true,result:currentResult}}}executeAlwaysHooks(path,args,resultOrError,hasError=false,errors=[],api,ctx){const hooks=this.getHooksForPath("always",path);for(const hook of hooks){try{hook.handler({path,args,result:hasError?void 0:resultOrError,hasError,errors,api,ctx})}catch(error){const sourceInfo={type:"always",subset:hook.subset,hookTag:hook.id,hookId:hook.id,timestamp:Date.now(),stack:error.stack};this.executeErrorHooks(path,error,sourceInfo,args,api,ctx)}}}executeErrorHooks(path,error,source,args,api,ctx){if(error&&typeof error==="object"){error[ERROR_HOOK_PROCESSED]=true}const hooks=this.getHooksForPath("error",path);for(const hook of hooks){try{hook.handler({path,args,error,errorType:error?.constructor?.name||"Error",source,timestamp:new Date,api,ctx})}catch(hookError){this.slothlet.debug("hooks",`Error hook failed for ${path}:`,hookError)}}}#parseTypePattern(typePattern){if(typeof typePattern!=="string"){throw new this.slothlet.SlothletError("INVALID_TYPE_PATTERN",{typePattern,expected:"string in format 'type:pattern'"})}const colonIndex=typePattern.indexOf(":");if(colonIndex===-1){throw new this.slothlet.SlothletError("INVALID_TYPE_PATTERN",{typePattern,expected:"string in format 'type:pattern' with at least one colon"})}const type=typePattern.substring(0,colonIndex);const pattern=typePattern.substring(colonIndex+1);if(!type||!pattern){throw new this.slothlet.SlothletError("INVALID_TYPE_PATTERN",{typePattern,expected:"non-empty type and pattern"})}return{type,pattern}}#compilePattern(pattern){return compilePattern(pattern,{onMaxDepth:maxDepth=>{throw new this.SlothletError("HOOK_BRACE_EXPANSION_MAX_DEPTH",{maxDepth},null,{validationError:true})}})}getCompilePatternForDiagnostics(){return this.#compilePattern.bind(this)}#generateId(){return`hook-${++this.#idCounter}`}#removeHook(hook){const typeIndex=this.#hooks[hook.type];const subsetIndex=typeIndex[hook.subset];const patternHooks=subsetIndex[hook.pattern];if(!patternHooks){throw new this.slothlet.SlothletError("INTERNAL_HOOK_STATE_CORRUPT",{hookId:hook.id,type:hook.type,subset:hook.subset,pattern:hook.pattern,detail:"patternHooks array missing from subsetIndex \u2014 #byId and #hooks are desynced"})}const index=patternHooks.indexOf(hook);if(index===-1){throw new this.slothlet.SlothletError("INTERNAL_HOOK_STATE_CORRUPT",{hookId:hook.id,type:hook.type,subset:hook.subset,pattern:hook.pattern,detail:"hook object not found in patternHooks array \u2014 #byId and #hooks are desynced"})}patternHooks.splice(index,1);if(patternHooks.length===0){delete subsetIndex[hook.pattern]}this.#byId.delete(hook.id)}#setEnabledState(filter,enabled){let affected=0;if(filter.id){const hook=this.#byId.get(filter.id);if(hook){hook.enabled=enabled;affected=1}return affected}const types=filter.type?[filter.type]:Array.from(this.#validTypes);for(const type of types){const typeIndex=this.#hooks[type];for(const subset of["before","primary","after"]){const subsetIndex=typeIndex[subset];if(filter.pattern){const patternHooks=subsetIndex[filter.pattern]||[];for(const hook of patternHooks){hook.enabled=enabled;affected++}}else{for(const pattern in subsetIndex){const patternHooks=subsetIndex[pattern];for(const hook of patternHooks){hook.enabled=enabled;affected++}}}}}return affected}#serializeHook(hook){return{id:hook.id,type:hook.type,pattern:hook.pattern,priority:hook.priority,subset:hook.subset,enabled:hook.enabled,lockCaller:hook.lockCaller}}exportHooks(){const registrations=[];for(const hook of this.#byId.values()){registrations.push({typePattern:`${hook.type}:${hook.pattern}`,handler:hook.handler,options:{id:hook.id,priority:hook.priority,subset:hook.subset,lockCaller:hook.lockCaller},enabled:hook.enabled})}return registrations}importHooks(registrations){if(!Array.isArray(registrations))return;for(const reg of registrations){this.on(reg.typePattern,reg.handler,reg.options);if(!reg.enabled){this.disable({id:reg.options.id})}}}async shutdown(){this.#hooks={before:{before:{},primary:{},after:{}},after:{before:{},primary:{},after:{}},always:{before:{},primary:{},after:{}},error:{before:{},primary:{},after:{}}};this.#byId.clear();this.#idCounter=0}}export{HookManager};
@@ -14,4 +14,4 @@
14
14
  limitations under the License.
15
15
  */
16
16
 
17
- import{ComponentBase}from"@cldmv/slothlet/factories/component-base";import{resolveWrapper}from"@cldmv/slothlet/handlers/unified-wrapper";import{verifyToken}from"@cldmv/slothlet/handlers/lifecycle-token";class Metadata extends ComponentBase{static slothletProperty="metadata";_instanceId=null;constructor(slothlet){super(slothlet);this._instanceId=`metadata_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}#secureMetadata=new WeakMap;#userMetadataStore=new Map;#globalUserMetadata=Object.create(null);#mergeMetadataValue(currentValue,nextValue,argumentName="metadata",metadataKey=null){const utilities=this.slothlet.helpers?.utilities;if(metadataKey!=null){this.#assertSafeMetadataKeySegment(metadataKey)}if(utilities?.isPlainObject(currentValue)){this.#assertAcyclicPlainObject(currentValue,argumentName,metadataKey);this.#assertNoReservedMetadataKeys(currentValue,metadataKey)}if(utilities?.isPlainObject(nextValue)){this.#assertAcyclicPlainObject(nextValue,argumentName,metadataKey);this.#assertNoReservedMetadataKeys(nextValue,metadataKey)}if(utilities?.isPlainObject(currentValue)&&utilities?.isPlainObject(nextValue)){return utilities.deepMerge(currentValue,nextValue)}return nextValue}#assertAcyclicPlainObject(value,argumentName,metadataKey=null){const utilities=this.slothlet.helpers?.utilities;if(!utilities?.isPlainObject(value))return;const validate=(candidate,ancestors=new WeakSet)=>{if(ancestors.has(candidate)){throw new this.SlothletError("INVALID_ARGUMENT",{argument:metadataKey?`${argumentName}.${metadataKey}`:argumentName,expected:"acyclic object",received:"circular reference",validationError:true})}ancestors.add(candidate);try{for(const nestedValue of Object.values(candidate)){if(utilities.isPlainObject(nestedValue)){validate(nestedValue,ancestors)}}}finally{ancestors.delete(candidate)}};validate(value)}#assertSafeMetadataKeySegment(key){const blocked=new Set(["__proto__","prototype","constructor"]);if(typeof key!=="string"||key.length===0)return;for(const segment of key.split(".")){if(blocked.has(segment)){throw new this.SlothletError("INVALID_METADATA_KEY",{key,type:"string",expected:"safe dot-notation key without reserved segments"})}}}#assertNoReservedMetadataKeys(value,metadataKey=null){const blocked=new Set(["__proto__","prototype","constructor"]);const utilities=this.slothlet.helpers?.utilities;const walk=(candidate,path="")=>{for(const[key,nestedValue]of Object.entries(candidate)){if(blocked.has(key)){const fullPath=path?`${path}.${key}`:key;const keyPath=metadataKey?`${metadataKey}.${fullPath}`:fullPath;throw new this.SlothletError("INVALID_METADATA_KEY",{key:keyPath,type:"string",expected:"safe dot-notation key without reserved segments"})}if(utilities?.isPlainObject(nestedValue)){walk(nestedValue,path?`${path}.${key}`:key)}}};walk(value)}#deepFreeze(obj){if(Object.isFrozen(obj))return obj;Object.freeze(obj);Object.getOwnPropertyNames(obj).forEach(prop=>{if(obj[prop]!==null&&typeof obj[prop]==="object"){this.#deepFreeze(obj[prop])}});return obj}tagSystemMetadata(target,systemData,token){if(!verifyToken(this.slothlet,token)){throw new this.SlothletError("METADATA_LIFECYCLE_BYPASS",{},null,{validationError:true})}if(!target)return;if(typeof target!=="object"&&typeof target!=="function"){return}let fullModuleID=systemData.moduleID;if(systemData.apiPath&&systemData.moduleID){const apiPathSlashes=systemData.apiPath.replace(/\./g,"/");fullModuleID=`${systemData.moduleID}:${apiPathSlashes}`}let sourceFolder=systemData.sourceFolder;if(!sourceFolder&&systemData.filePath){const pathModule=this.slothlet.helpers.resolver.path;sourceFolder=pathModule.dirname(systemData.filePath)}const frozenSystem=Object.freeze({filePath:systemData.filePath,sourceFolder,apiPath:systemData.apiPath,moduleID:fullModuleID,taggedAt:Date.now()});this.#secureMetadata.set(target,frozenSystem)}getSystemMetadata(target){if(!target)return null;const actualTarget=resolveWrapper(target)??target;const systemData=this.#secureMetadata.get(actualTarget.____slothletInternal?.impl||actualTarget);return systemData||null}getMetadata(target){if(!target)return{};const actualTarget=resolveWrapper(target)??target;const systemData=this.#secureMetadata.get(actualTarget)||this.#secureMetadata.get(actualTarget.____slothletInternal?.impl)||{};const moduleID=systemData.moduleID||systemData.moduleID;const apiPath=systemData.apiPath;const collectMetadataFromParents=path=>{const parts=path.split(".");const collected={};for(let i=1;i<=parts.length;i++){const parentPath=parts.slice(0,i).join(".");const parentMeta=this.#userMetadataStore.get(parentPath);if(parentMeta?.metadata){Object.assign(collected,parentMeta.metadata)}}return collected};const userMetadataByModule=moduleID?this.#userMetadataStore.get(moduleID):null;const userMetadataByPath=apiPath?collectMetadataFromParents(apiPath):{};const userData={...userMetadataByPath,...userMetadataByModule?.metadata||{}};const combined={...this.#globalUserMetadata,...userData,...systemData};if(combined.metadata&&typeof combined.metadata==="object"){const{metadata,...rest}=combined;return this.#deepFreeze({...rest,...metadata})}return this.#deepFreeze(combined)}setGlobalMetadata(key,value){this.#globalUserMetadata[key]=this.#mergeMetadataValue(this.#globalUserMetadata[key],value,"metadata",key)}setUserMetadata(target,key,value){if(typeof target!=="function"&&typeof target!=="object"){throw new this.SlothletError("INVALID_METADATA_TARGET",{target:typeof target,expected:"function or object"})}const actualTarget=resolveWrapper(target)??target;const systemData=this.#secureMetadata.get(actualTarget)||this.#secureMetadata.get(actualTarget.____slothletInternal?.impl)||{};const moduleID=systemData.moduleID;if(!moduleID){throw new this.SlothletError("METADATA_NO_MODULE_ID",{},null,{validationError:true})}let entry=this.#userMetadataStore.get(moduleID);if(!entry){entry={metadata:{},apiPaths:new Set};this.#userMetadataStore.set(moduleID,entry)}entry.metadata[key]=this.#mergeMetadataValue(entry.metadata[key],value,"metadata",key);const apiPath=systemData.apiPath;if(apiPath){let pathEntry=this.#userMetadataStore.get(apiPath);if(!pathEntry){pathEntry={metadata:{},apiPaths:new Set};this.#userMetadataStore.set(apiPath,pathEntry)}pathEntry.metadata[key]=this.#mergeMetadataValue(pathEntry.metadata[key],value,"metadata",key);pathEntry.apiPaths.add(apiPath)}}removeUserMetadata(target,key){if(typeof target!=="function"&&typeof target!=="object"){throw new this.SlothletError("INVALID_METADATA_TARGET",{target:typeof target,expected:"function or object"})}const actualTarget=resolveWrapper(target)??target;const systemData=this.#secureMetadata.get(actualTarget)||this.#secureMetadata.get(actualTarget.____slothletInternal?.impl)||{};const moduleID=systemData.moduleID;const apiPath=systemData.apiPath;if(!moduleID)return;const applyRemoval=storeKey=>{const storeEntry=this.#userMetadataStore.get(storeKey);if(!storeEntry)return;if(key===void 0){this.#userMetadataStore.delete(storeKey)}else if(Array.isArray(key)){for(const k of key){if(typeof k!=="string"){throw new this.SlothletError("INVALID_METADATA_KEY",{key:k,type:typeof k,expected:"string"})}delete storeEntry.metadata[k]}}else if(typeof key==="object"&&key!==null){for(const[metadataKey,nestedKeys]of Object.entries(key)){if(!Array.isArray(nestedKeys)){throw new this.SlothletError("INVALID_METADATA_KEY",{key:metadataKey,type:typeof nestedKeys,expected:"array"})}const metadataValue=storeEntry.metadata[metadataKey];if(metadataValue&&typeof metadataValue==="object"){for(const nestedKey of nestedKeys){if(typeof nestedKey!=="string"){throw new this.SlothletError("INVALID_METADATA_KEY",{key:nestedKey,type:typeof nestedKey,expected:"string"})}delete metadataValue[nestedKey]}}}}else if(typeof key==="string"){delete storeEntry.metadata[key]}else{throw new this.SlothletError("INVALID_METADATA_KEY",{key,type:typeof key,expected:"string, string[], or object"})}};applyRemoval(moduleID);if(apiPath&&apiPath!==moduleID){applyRemoval(apiPath)}}registerUserMetadata(identifier,metadata){if(!identifier||typeof identifier!=="string"){throw new this.SlothletError("INVALID_ARGUMENT",{argument:"identifier",expected:"non-empty string",received:typeof identifier},null,{validationError:true})}let entry=this.#userMetadataStore.get(identifier);if(!entry){entry={metadata:{},apiPaths:new Set};this.#userMetadataStore.set(identifier,entry)}entry.metadata=this.#mergeMetadataValue(entry.metadata,metadata,"metadata");entry.apiPaths.add(identifier)}removeUserMetadataByApiPath(apiPath){if(!apiPath)return;this.#userMetadataStore.delete(apiPath)}setPathMetadata(apiPath,keyOrObj,value){if(typeof apiPath!=="string"||!apiPath){throw new this.SlothletError("INVALID_ARGUMENT",{argument:"apiPath",expected:"non-empty string",received:typeof apiPath},null,{validationError:true})}const metadataObj=typeof keyOrObj==="string"?{[keyOrObj]:value}:keyOrObj;if(!metadataObj||typeof metadataObj!=="object"||Array.isArray(metadataObj)){throw new this.SlothletError("INVALID_ARGUMENT",{argument:"keyOrObj",expected:"string key or plain object",received:typeof keyOrObj},null,{validationError:true})}this.registerUserMetadata(apiPath,metadataObj)}getPathMetadata(apiPath){if(!apiPath||typeof apiPath!=="string")return{};const parts=apiPath.split(".");const collected={};for(let i=1;i<=parts.length;i++){const parentPath=parts.slice(0,i).join(".");const parentMeta=this.#userMetadataStore.get(parentPath);if(parentMeta?.metadata){Object.assign(collected,parentMeta.metadata)}}return{...this.#globalUserMetadata,...collected}}removePathMetadata(apiPath,key){if(!apiPath||typeof apiPath!=="string")return;const entry=this.#userMetadataStore.get(apiPath);if(!entry)return;if(key===void 0){this.#userMetadataStore.delete(apiPath)}else if(Array.isArray(key)){for(const k of key){if(typeof k!=="string"){throw new this.SlothletError("INVALID_METADATA_KEY",{key:k,type:typeof k,expected:"string"})}delete entry.metadata[k]}}else if(typeof key==="string"){delete entry.metadata[key]}else{throw new this.SlothletError("INVALID_METADATA_KEY",{key,type:typeof key,expected:"string or string[]"})}}exportUserState(){const storeCopy=new Map;for(const[key,entry]of this.#userMetadataStore){storeCopy.set(key,{metadata:{...entry.metadata},apiPaths:new Set(entry.apiPaths)})}return{globalMetadata:{...this.#globalUserMetadata},userMetadataStore:storeCopy}}importUserState(state){if(!state)return;if(state.globalMetadata){for(const[k,v]of Object.entries(state.globalMetadata)){if(!(k in this.#globalUserMetadata)){this.#globalUserMetadata[k]=v}}}if(state.userMetadataStore){for(const[key,savedEntry]of state.userMetadataStore){const existing=this.#userMetadataStore.get(key);if(!existing){this.#userMetadataStore.set(key,{metadata:{...savedEntry.metadata},apiPaths:new Set(savedEntry.apiPaths)})}else{existing.metadata={...savedEntry.metadata,...existing.metadata};for(const p of savedEntry.apiPaths)existing.apiPaths.add(p)}}}}async get(path){if(typeof path!=="string"){throw new this.SlothletError("INVALID_ARGUMENT",{argument:"path",expected:"string",received:typeof path})}const apiRoot=this.slothlet.api;if(!apiRoot)return null;const parts=path.split(".");let target=apiRoot;for(const part of parts){if(!target||typeof target!=="object"&&typeof target!=="function"){return null}target=target[part]}if(target&&typeof target._materialize==="function"){await target._materialize()}if(typeof target==="function"||target&&resolveWrapper(target)?.____slothletInternal?.impl){return this.getMetadata(target)}return null}self(){const ctx=this.slothlet.contextManager?.tryGetContext();if(!ctx||!ctx.currentWrapper){throw new this.SlothletError("RUNTIME_NO_ACTIVE_CONTEXT",{},null,{validationError:true})}return this.getMetadata(ctx.currentWrapper)}caller(){const ctx=this.slothlet.contextManager?.tryGetContext();if(!ctx||!ctx.callerWrapper)return null;return this.getMetadata(ctx.callerWrapper)}}export{Metadata};
17
+ import{ComponentBase}from"@cldmv/slothlet/factories/component-base";import{resolveWrapper}from"@cldmv/slothlet/handlers/unified-wrapper";import{verifyToken}from"@cldmv/slothlet/handlers/lifecycle-token";class Metadata extends ComponentBase{static slothletProperty="metadata";_instanceId=null;constructor(slothlet){super(slothlet);this._instanceId=`metadata_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}#secureMetadata=new WeakMap;#userMetadataStore=new Map;#globalUserMetadata=Object.create(null);#mergeMetadataValue(currentValue,nextValue,argumentName="metadata",metadataKey=null){const utilities=this.slothlet.helpers?.utilities;if(metadataKey!=null){this.#assertSafeMetadataKeySegment(metadataKey)}if(utilities?.isPlainObject(currentValue)){this.#assertAcyclicPlainObject(currentValue,argumentName,metadataKey);this.#assertNoReservedMetadataKeys(currentValue,metadataKey)}if(utilities?.isPlainObject(nextValue)){this.#assertAcyclicPlainObject(nextValue,argumentName,metadataKey);this.#assertNoReservedMetadataKeys(nextValue,metadataKey)}if(utilities?.isPlainObject(currentValue)&&utilities?.isPlainObject(nextValue)){return utilities.deepMerge(currentValue,nextValue)}return nextValue}#assertAcyclicPlainObject(value,argumentName,metadataKey=null){const utilities=this.slothlet.helpers?.utilities;if(!utilities?.isPlainObject(value))return;const validate=(candidate,ancestors=new WeakSet)=>{if(ancestors.has(candidate)){throw new this.SlothletError("INVALID_ARGUMENT",{argument:metadataKey?`${argumentName}.${metadataKey}`:argumentName,expected:"acyclic object",received:"circular reference",validationError:true})}ancestors.add(candidate);try{for(const nestedValue of Object.values(candidate)){if(utilities.isPlainObject(nestedValue)){validate(nestedValue,ancestors)}}}finally{ancestors.delete(candidate)}};validate(value)}#assertSafeMetadataKeySegment(key){const blocked=new Set(["__proto__","prototype","constructor"]);if(typeof key!=="string"||key.length===0)return;for(const segment of key.split(".")){if(blocked.has(segment)){throw new this.SlothletError("INVALID_METADATA_KEY",{key,type:"string",expected:"safe dot-notation key without reserved segments"})}}}#assertNoReservedMetadataKeys(value,metadataKey=null){const blocked=new Set(["__proto__","prototype","constructor"]);const utilities=this.slothlet.helpers?.utilities;const walk=(candidate,path="")=>{for(const[key,nestedValue]of Object.entries(candidate)){if(blocked.has(key)){const fullPath=path?`${path}.${key}`:key;const keyPath=metadataKey?`${metadataKey}.${fullPath}`:fullPath;throw new this.SlothletError("INVALID_METADATA_KEY",{key:keyPath,type:"string",expected:"safe dot-notation key without reserved segments"})}if(utilities?.isPlainObject(nestedValue)){walk(nestedValue,path?`${path}.${key}`:key)}}};walk(value)}#deepFreeze(obj){if(Object.isFrozen(obj))return obj;Object.freeze(obj);Object.getOwnPropertyNames(obj).forEach(prop=>{if(obj[prop]!==null&&typeof obj[prop]==="object"){this.#deepFreeze(obj[prop])}});return obj}tagSystemMetadata(target,systemData,token){if(!verifyToken(this.slothlet,token)){throw new this.SlothletError("METADATA_LIFECYCLE_BYPASS",{},null,{validationError:true})}if(!target)return;if(typeof target!=="object"&&typeof target!=="function"){return}let fullModuleID=systemData.moduleID;if(systemData.apiPath&&systemData.moduleID){const apiPathSlashes=systemData.apiPath.replace(/\./g,"/");fullModuleID=`${systemData.moduleID}:${apiPathSlashes}`}let sourceFolder=systemData.sourceFolder;if(!sourceFolder&&systemData.filePath){const pathModule=this.slothlet.helpers.resolver.path;sourceFolder=pathModule.dirname(systemData.filePath)}const frozenSystem=Object.freeze({filePath:systemData.filePath,sourceFolder,apiPath:systemData.apiPath,moduleID:fullModuleID,taggedAt:Date.now()});this.#secureMetadata.set(target,frozenSystem)}getSystemMetadata(target){if(!target)return null;const actualTarget=resolveWrapper(target)??target;const systemData=this.#secureMetadata.get(actualTarget.____slothletInternal?.impl||actualTarget);return systemData||null}getMetadata(target){if(!target)return{};const actualTarget=resolveWrapper(target)??target;const systemData=this.#secureMetadata.get(actualTarget)||this.#secureMetadata.get(actualTarget.____slothletInternal?.impl)||{};const moduleID=systemData.moduleID;const apiPath=systemData.apiPath;const collectMetadataFromParents=path=>{const parts=path.split(".");const collected={};for(let i=1;i<=parts.length;i++){const parentPath=parts.slice(0,i).join(".");const parentMeta=this.#userMetadataStore.get(parentPath);if(parentMeta?.metadata){Object.assign(collected,parentMeta.metadata)}}return collected};const userMetadataByModule=moduleID?this.#userMetadataStore.get(moduleID):null;const userMetadataByPath=apiPath?collectMetadataFromParents(apiPath):{};const userData={...userMetadataByPath,...userMetadataByModule?.metadata||{}};const combined={...this.#globalUserMetadata,...userData,...systemData};if(combined.metadata&&typeof combined.metadata==="object"){const{metadata,...rest}=combined;return this.#deepFreeze({...rest,...metadata})}return this.#deepFreeze(combined)}setGlobalMetadata(key,value){this.#globalUserMetadata[key]=this.#mergeMetadataValue(this.#globalUserMetadata[key],value,"metadata",key)}setUserMetadata(target,key,value){if(typeof target!=="function"&&typeof target!=="object"){throw new this.SlothletError("INVALID_METADATA_TARGET",{target:typeof target,expected:"function or object"})}const actualTarget=resolveWrapper(target)??target;const systemData=this.#secureMetadata.get(actualTarget)||this.#secureMetadata.get(actualTarget.____slothletInternal?.impl)||{};const moduleID=systemData.moduleID;if(!moduleID){throw new this.SlothletError("METADATA_NO_MODULE_ID",{},null,{validationError:true})}let entry=this.#userMetadataStore.get(moduleID);if(!entry){entry={metadata:{},apiPaths:new Set};this.#userMetadataStore.set(moduleID,entry)}entry.metadata[key]=this.#mergeMetadataValue(entry.metadata[key],value,"metadata",key);const apiPath=systemData.apiPath;if(apiPath){let pathEntry=this.#userMetadataStore.get(apiPath);if(!pathEntry){pathEntry={metadata:{},apiPaths:new Set};this.#userMetadataStore.set(apiPath,pathEntry)}pathEntry.metadata[key]=this.#mergeMetadataValue(pathEntry.metadata[key],value,"metadata",key);pathEntry.apiPaths.add(apiPath)}}removeUserMetadata(target,key){if(typeof target!=="function"&&typeof target!=="object"){throw new this.SlothletError("INVALID_METADATA_TARGET",{target:typeof target,expected:"function or object"})}const actualTarget=resolveWrapper(target)??target;const systemData=this.#secureMetadata.get(actualTarget)||this.#secureMetadata.get(actualTarget.____slothletInternal?.impl)||{};const moduleID=systemData.moduleID;const apiPath=systemData.apiPath;if(!moduleID)return;const applyRemoval=storeKey=>{const storeEntry=this.#userMetadataStore.get(storeKey);if(!storeEntry)return;if(key===void 0){this.#userMetadataStore.delete(storeKey)}else if(Array.isArray(key)){for(const k of key){if(typeof k!=="string"){throw new this.SlothletError("INVALID_METADATA_KEY",{key:k,type:typeof k,expected:"string"})}delete storeEntry.metadata[k]}}else if(typeof key==="object"&&key!==null){for(const[metadataKey,nestedKeys]of Object.entries(key)){if(!Array.isArray(nestedKeys)){throw new this.SlothletError("INVALID_METADATA_KEY",{key:metadataKey,type:typeof nestedKeys,expected:"array"})}const metadataValue=storeEntry.metadata[metadataKey];if(metadataValue&&typeof metadataValue==="object"){for(const nestedKey of nestedKeys){if(typeof nestedKey!=="string"){throw new this.SlothletError("INVALID_METADATA_KEY",{key:nestedKey,type:typeof nestedKey,expected:"string"})}delete metadataValue[nestedKey]}}}}else if(typeof key==="string"){delete storeEntry.metadata[key]}else{throw new this.SlothletError("INVALID_METADATA_KEY",{key,type:typeof key,expected:"string, string[], or object"})}};applyRemoval(moduleID);if(apiPath&&apiPath!==moduleID){applyRemoval(apiPath)}}registerUserMetadata(identifier,metadata){if(!identifier||typeof identifier!=="string"){throw new this.SlothletError("INVALID_ARGUMENT",{argument:"identifier",expected:"non-empty string",received:typeof identifier},null,{validationError:true})}let entry=this.#userMetadataStore.get(identifier);if(!entry){entry={metadata:{},apiPaths:new Set};this.#userMetadataStore.set(identifier,entry)}entry.metadata=this.#mergeMetadataValue(entry.metadata,metadata,"metadata");entry.apiPaths.add(identifier)}removeUserMetadataByApiPath(apiPath){if(!apiPath)return;this.#userMetadataStore.delete(apiPath)}setPathMetadata(apiPath,keyOrObj,value){if(typeof apiPath!=="string"||!apiPath){throw new this.SlothletError("INVALID_ARGUMENT",{argument:"apiPath",expected:"non-empty string",received:typeof apiPath},null,{validationError:true})}const metadataObj=typeof keyOrObj==="string"?{[keyOrObj]:value}:keyOrObj;if(!metadataObj||typeof metadataObj!=="object"||Array.isArray(metadataObj)){throw new this.SlothletError("INVALID_ARGUMENT",{argument:"keyOrObj",expected:"string key or plain object",received:typeof keyOrObj},null,{validationError:true})}this.registerUserMetadata(apiPath,metadataObj)}getPathMetadata(apiPath){if(!apiPath||typeof apiPath!=="string")return{};const parts=apiPath.split(".");const collected={};for(let i=1;i<=parts.length;i++){const parentPath=parts.slice(0,i).join(".");const parentMeta=this.#userMetadataStore.get(parentPath);if(parentMeta?.metadata){Object.assign(collected,parentMeta.metadata)}}return{...this.#globalUserMetadata,...collected}}removePathMetadata(apiPath,key){if(!apiPath||typeof apiPath!=="string")return;const entry=this.#userMetadataStore.get(apiPath);if(!entry)return;if(key===void 0){this.#userMetadataStore.delete(apiPath)}else if(Array.isArray(key)){for(const k of key){if(typeof k!=="string"){throw new this.SlothletError("INVALID_METADATA_KEY",{key:k,type:typeof k,expected:"string"})}delete entry.metadata[k]}}else if(typeof key==="string"){delete entry.metadata[key]}else{throw new this.SlothletError("INVALID_METADATA_KEY",{key,type:typeof key,expected:"string or string[]"})}}exportUserState(){const storeCopy=new Map;for(const[key,entry]of this.#userMetadataStore){storeCopy.set(key,{metadata:{...entry.metadata},apiPaths:new Set(entry.apiPaths)})}return{globalMetadata:{...this.#globalUserMetadata},userMetadataStore:storeCopy}}importUserState(state){if(!state)return;if(state.globalMetadata){for(const[k,v]of Object.entries(state.globalMetadata)){if(!(k in this.#globalUserMetadata)){this.#globalUserMetadata[k]=v}}}if(state.userMetadataStore){for(const[key,savedEntry]of state.userMetadataStore){const existing=this.#userMetadataStore.get(key);if(!existing){this.#userMetadataStore.set(key,{metadata:{...savedEntry.metadata},apiPaths:new Set(savedEntry.apiPaths)})}else{existing.metadata={...savedEntry.metadata,...existing.metadata};for(const p of savedEntry.apiPaths)existing.apiPaths.add(p)}}}}async get(path){if(typeof path!=="string"){throw new this.SlothletError("INVALID_ARGUMENT",{argument:"path",expected:"string",received:typeof path})}const apiRoot=this.slothlet.api;if(!apiRoot)return null;const parts=path.split(".");let target=apiRoot;for(const part of parts){if(!target||typeof target!=="object"&&typeof target!=="function"){return null}target=target[part]}if(target&&typeof target._materialize==="function"){await target._materialize()}if(typeof target==="function"||target&&resolveWrapper(target)?.____slothletInternal?.impl){return this.getMetadata(target)}return null}self(){const ctx=this.slothlet.contextManager?.tryGetContext();if(!ctx||!ctx.currentWrapper){throw new this.SlothletError("RUNTIME_NO_ACTIVE_CONTEXT",{},null,{validationError:true})}return this.getMetadata(ctx.currentWrapper)}caller(){const ctx=this.slothlet.contextManager?.tryGetContext();if(!ctx||!ctx.callerWrapper)return null;return this.getMetadata(ctx.callerWrapper)}}export{Metadata};
@@ -14,4 +14,4 @@
14
14
  limitations under the License.
15
15
  */
16
16
 
17
- const ____COLLISION_MERGED_PROPERTY=Symbol("collisionMergedProperty");import util from"node:util";import{ComponentBase}from"@cldmv/slothlet/factories/component-base";const ERROR_HOOK_PROCESSED=Symbol.for("@cldmv/slothlet/hook-error-processed");const hasOwn=(obj,key)=>Object.prototype.hasOwnProperty.call(obj,key);function runtime_enforceReadGate(wrapper,prop,resolvedValue,callerOverride){const pm=wrapper.slothlet.handlers?.permissionManager;if(!pm||!pm.isEnabled()||!pm.isReadGatingEnabled())return;const isTerminal=resolvedValue!==Object(resolvedValue)||resolvedValue instanceof Map||resolvedValue instanceof Set||resolvedValue instanceof WeakMap||resolvedValue instanceof WeakSet||resolvedValue instanceof Date||resolvedValue instanceof RegExp||resolvedValue instanceof Promise||resolvedValue instanceof Error||ArrayBuffer.isView(resolvedValue)||resolvedValue instanceof ArrayBuffer;if(!isTerminal)return;const ctx=callerOverride!==void 0?callerOverride:wrapper.slothlet.contextManager?.tryGetContext?.();const callerWrapper=ctx?.currentWrapper;if(!callerWrapper)return;const callerPath=callerWrapper.____slothletInternal?.apiPath??"";const callerFilePath=callerWrapper.____slothletInternal?.filePath??null;const targetFilePath=wrapper.____slothletInternal.filePath??null;const targetPath=wrapper.____slothletInternal.apiPath+"."+String(prop);if(!pm.enforceAccess(callerPath,targetPath,callerFilePath,targetFilePath,ctx.context??null)){throw new wrapper.SlothletError("PERMISSION_DENIED",{caller:callerPath,target:targetPath})}}function unwrapError(error){if(error&&error.name==="SlothletError"&&error.originalError){return error.originalError}return error}const wrapperDebugEnabled=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 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;const extractFullImpl_result={};for(const key of Object.keys(impl)){if(key.startsWith("__"))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);let extractedModuleId=moduleID||(wrapperMetadata?.moduleID?wrapperMetadata.moduleID.split(":")[0]:null);if(extractedModuleId&&typeof extractedModuleId!=="string"){extractedModuleId=extractedModuleId.moduleID||extractedModuleId.__moduleID||String(extractedModuleId)}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;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;const builtinKeys=new Set(["slothlet","shutdown","destroy"]);for(const key of ownKeys){if(internalKeys.has(key)){continue}if(typeof key==="string"&&metadataKeys.has(key)){continue}if(typeof key==="string"&&builtinKeys.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.slothlet,this.____slothletInternal.moduleID,this.____slothletInternal.filePath)}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.slothlet,this.____slothletInternal.moduleID,this.____slothletInternal.filePath);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?.moduleID){const colonIndex=parentMetadata.moduleID.indexOf(":");childModuleId=colonIndex>0?parentMetadata.moduleID.substring(0,colonIndex):parentMetadata.moduleID}}else{if(childExistingMetadata?.moduleID){const colonIndex=childExistingMetadata.moduleID.indexOf(":");childModuleId=colonIndex>0?childExistingMetadata.moduleID.substring(0,colonIndex):childExistingMetadata.moduleID}}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:__readGateStore.currentWrapper,context:__readGateStore.context}: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;for(const chainProp of propChain){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;const idx=propChain.indexOf(chainProp);for(let i=idx;i<propChain.length;i++){result=result[propChain[i]]}return result}const isInternal2=typeof chainProp==="string"&&(chainProp.startsWith("_")||chainProp.startsWith("__"));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}runtime_enforceReadGate(current,chainProp,child,__readGateCaller);return child}if(current.____slothletInternal.impl&&current.____slothletInternal.impl[chainProp]!==void 0){const implValue=current.____slothletInternal.impl[chainProp];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)}return current.____slothletInternal.impl};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||current===null){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(current&&currentWrapper){const isInternal2=typeof chainProp==="string"&&(chainProp.startsWith("_")||chainProp.startsWith("__"));if(!isInternal2&&chainProp in currentWrapper){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=typeof chainProp==="string"&&(chainProp.startsWith("_")||chainProp.startsWith("__"));if(!isInternal2&&current&&chainProp in current){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=typeof prop==="string"&&(prop.startsWith("_")||prop.startsWith("__"));if(!isFinalInternal&&current&&prop in current){return current[prop]}return void 0}const isInternal=typeof prop==="string"&&(prop.startsWith("_")||prop.startsWith("__"));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=typeof prop==="string"&&(prop.startsWith("_")||prop.startsWith("__"));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 ___capturedCallerWrapper=wrapper.slothlet.contextManager?.tryGetContext?.()?.currentWrapper??null;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(current&&currentWrapper){lastWrapper=currentWrapper;const isInternal=typeof prop==="string"&&(prop.startsWith("_")||prop.startsWith("__"));if(!isInternal&&prop in currentWrapper){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(___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)}}return Reflect.apply(current,lastObject,args)}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{proxyTarget=wrapper}if(!(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=typeof prop==="string"&&UnifiedWrapper.INTERNAL_KEYS.has(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;if(prop==="then")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()=>void 0}if(wrapper.____slothletInternal.invalid){return void 0}if(wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.state.materialized&&!wrapper.____slothletInternal.state.inFlight){wrapper._materialize().catch(()=>{})}const isInternal=typeof prop==="string"&&(prop.startsWith("_")||prop.startsWith("__"));if(!isInternal&&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]}const isInternal2=typeof prop==="string"&&(prop.startsWith("_")||prop.startsWith("__"));if(!isInternal2&&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 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`)}const permissionManager=wrapper.slothlet.handlers?.permissionManager;if(permissionManager&&permissionManager.isEnabled()){const ctx2=wrapper.slothlet.contextManager?.tryGetContext?.();const callerWrapper=ctx2?.currentWrapper;if(callerWrapper){const callerPath=callerWrapper.____slothletInternal?.apiPath??"";const callerFilePath=callerWrapper.____slothletInternal?.filePath??null;const targetPath=wrapper.____slothletInternal.apiPath;const targetFilePath=wrapper.____slothletInternal.filePath??null;const runtimeContext=ctx2?.context??null;if(!permissionManager.enforceAccess(callerPath,targetPath,callerFilePath,targetFilePath,runtimeContext)){throw new wrapper.SlothletError("PERMISSION_DENIED",{caller:callerPath,target:targetPath})}}}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||{};let result;let finalResult;let isAsync=false;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))}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))}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)}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)}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){this.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=this.lastSyncError;this.lastSyncError=null;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=typeof prop==="string"&&(prop.startsWith("_")||prop.startsWith("__"));if(!isInternal&&hasOwn(wrapper,prop)){return true}if(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}}if(Object.prototype.hasOwnProperty.call(target,prop)){return Object.getOwnPropertyDescriptor(target,prop)}const isInternal=typeof prop==="string"&&(prop.startsWith("_")||prop.startsWith("__"));if(!isInternal&&hasOwn(wrapper,prop)){const desc=Object.getOwnPropertyDescriptor(wrapper,prop);if(desc){return desc}}if(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"){keys.add(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=typeof prop==="string"&&(prop.startsWith("_")||prop.startsWith("__"));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`)}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:getTrap,apply:applyTrap,construct:constructTrap,has:hasTrap,getOwnPropertyDescriptor:getOwnPropertyDescriptorTrap,ownKeys:ownKeysTrap,set:setTrap,deleteProperty:deletePropertyTrap,getPrototypeOf:()=>null});_proxyRegistry.set(wrapper.____slothletInternal.proxy,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{TYPE_STATES,UnifiedWrapper,resolveWrapper};
17
+ const ____COLLISION_MERGED_PROPERTY=Symbol("collisionMergedProperty");import{isNode,util}from"@cldmv/slothlet/helpers/platform";import{ComponentBase}from"@cldmv/slothlet/factories/component-base";const ERROR_HOOK_PROCESSED=Symbol.for("@cldmv/slothlet/hook-error-processed");const hasOwn=(obj,key)=>Object.prototype.hasOwnProperty.call(obj,key);function runtime_enforceReadGate(wrapper,prop,resolvedValue,callerOverride){const pm=wrapper.slothlet.handlers?.permissionManager;if(!pm||!pm.isEnabled()||!pm.isReadGatingEnabled())return;const isTerminal=resolvedValue!==Object(resolvedValue)||resolvedValue instanceof Map||resolvedValue instanceof Set||resolvedValue instanceof WeakMap||resolvedValue instanceof WeakSet||resolvedValue instanceof Date||resolvedValue instanceof RegExp||resolvedValue instanceof Promise||resolvedValue instanceof Error||ArrayBuffer.isView(resolvedValue)||resolvedValue instanceof ArrayBuffer;if(!isTerminal)return;const ctx=callerOverride!==void 0?callerOverride:wrapper.slothlet.contextManager?.tryGetContext?.();const callerWrapper=ctx?.currentWrapper;if(!callerWrapper)return;const callerPath=callerWrapper.____slothletInternal?.apiPath??"";const callerFilePath=callerWrapper.____slothletInternal?.filePath??null;const targetFilePath=wrapper.____slothletInternal.filePath??null;const targetPath=wrapper.____slothletInternal.apiPath+"."+String(prop);if(!pm.enforceAccess(callerPath,targetPath,callerFilePath,targetFilePath,ctx.context??null)){throw new wrapper.SlothletError("PERMISSION_DENIED",{caller:callerPath,target:targetPath})}}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 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;const extractFullImpl_result={};for(const key of Object.keys(impl)){if(key.startsWith("__"))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);let extractedModuleId=moduleID||(wrapperMetadata?.moduleID?wrapperMetadata.moduleID.split(":")[0]:null);if(extractedModuleId&&typeof extractedModuleId!=="string"){extractedModuleId=extractedModuleId.moduleID||extractedModuleId.__moduleID||String(extractedModuleId)}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;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;const builtinKeys=new Set(["slothlet","shutdown","destroy"]);for(const key of ownKeys){if(internalKeys.has(key)){continue}if(typeof key==="string"&&metadataKeys.has(key)){continue}if(typeof key==="string"&&builtinKeys.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.slothlet,this.____slothletInternal.moduleID,this.____slothletInternal.filePath)}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.slothlet,this.____slothletInternal.moduleID,this.____slothletInternal.filePath);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?.moduleID){const colonIndex=parentMetadata.moduleID.indexOf(":");childModuleId=colonIndex>0?parentMetadata.moduleID.substring(0,colonIndex):parentMetadata.moduleID}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:__readGateStore.currentWrapper,context:__readGateStore.context}: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;for(const chainProp of propChain){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;const idx=propChain.indexOf(chainProp);for(let i=idx;i<propChain.length;i++){result=result[propChain[i]]}return result}const isInternal2=typeof chainProp==="string"&&(chainProp.startsWith("_")||chainProp.startsWith("__"));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}runtime_enforceReadGate(current,chainProp,child,__readGateCaller);return child}if(current.____slothletInternal.impl&&current.____slothletInternal.impl[chainProp]!==void 0){const implValue=current.____slothletInternal.impl[chainProp];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)}return current.____slothletInternal.impl};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=typeof chainProp==="string"&&(chainProp.startsWith("_")||chainProp.startsWith("__"));if(!isInternal2&&chainProp in currentWrapper){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=typeof chainProp==="string"&&(chainProp.startsWith("_")||chainProp.startsWith("__"));if(!isInternal2&&current&&chainProp in current){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=typeof prop==="string"&&(prop.startsWith("_")||prop.startsWith("__"));if(!isFinalInternal&&current&&prop in current){return current[prop]}return void 0}const isInternal=typeof prop==="string"&&(prop.startsWith("_")||prop.startsWith("__"));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=typeof prop==="string"&&(prop.startsWith("_")||prop.startsWith("__"));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 ___capturedCallerWrapper=wrapper.slothlet.contextManager?.tryGetContext?.()?.currentWrapper??null;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=typeof prop==="string"&&(prop.startsWith("_")||prop.startsWith("__"));if(!isInternal&&prop in currentWrapper){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(___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)}}return Reflect.apply(current,lastObject,args)}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{proxyTarget=wrapper}if(!(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=typeof prop==="string"&&UnifiedWrapper.INTERNAL_KEYS.has(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;if(prop==="then")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()=>void 0}if(wrapper.____slothletInternal.invalid){return void 0}if(wrapper.____slothletInternal.mode==="lazy"&&!wrapper.____slothletInternal.state.materialized&&!wrapper.____slothletInternal.state.inFlight){wrapper._materialize().catch(()=>{})}const isInternal=typeof prop==="string"&&(prop.startsWith("_")||prop.startsWith("__"));if(!isInternal&&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]}const isInternal2=typeof prop==="string"&&(prop.startsWith("_")||prop.startsWith("__"));if(!isInternal2&&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 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`)}const permissionManager=wrapper.slothlet.handlers?.permissionManager;if(permissionManager&&permissionManager.isEnabled()){const ctx2=wrapper.slothlet.contextManager?.tryGetContext?.();const callerWrapper=ctx2?.currentWrapper;if(callerWrapper){const callerPath=callerWrapper.____slothletInternal?.apiPath??"";const callerFilePath=callerWrapper.____slothletInternal?.filePath??null;const targetPath=wrapper.____slothletInternal.apiPath;const targetFilePath=wrapper.____slothletInternal.filePath??null;const runtimeContext=ctx2?.context??null;if(!permissionManager.enforceAccess(callerPath,targetPath,callerFilePath,targetFilePath,runtimeContext)){throw new wrapper.SlothletError("PERMISSION_DENIED",{caller:callerPath,target:targetPath})}}}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||{};let result;let finalResult;let isAsync=false;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))}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))}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)}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)}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){this.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=this.lastSyncError;this.lastSyncError=null;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=typeof prop==="string"&&(prop.startsWith("_")||prop.startsWith("__"));if(!isInternal&&hasOwn(wrapper,prop)){return true}if(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}}if(Object.prototype.hasOwnProperty.call(target,prop)){return Object.getOwnPropertyDescriptor(target,prop)}const isInternal=typeof prop==="string"&&(prop.startsWith("_")||prop.startsWith("__"));if(!isInternal&&hasOwn(wrapper,prop)){const desc=Object.getOwnPropertyDescriptor(wrapper,prop);if(desc){return desc}}if(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"){keys.add(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=typeof prop==="string"&&(prop.startsWith("_")||prop.startsWith("__"));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`)}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:getTrap,apply:applyTrap,construct:constructTrap,has:hasTrap,getOwnPropertyDescriptor:getOwnPropertyDescriptorTrap,ownKeys:ownKeysTrap,set:setTrap,deleteProperty:deletePropertyTrap,getPrototypeOf:()=>null});_proxyRegistry.set(wrapper.____slothletInternal.proxy,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{TYPE_STATES,UnifiedWrapper,resolveWrapper};
@@ -14,4 +14,4 @@
14
14
  limitations under the License.
15
15
  */
16
16
 
17
- import{inspect}from"node:util";import{ComponentBase}from"@cldmv/slothlet/factories/component-base";function stripPrefix(tag){return tag.replace(/^[^0-9]+/,"")}function stripSuffix(s){return s.replace(/[-+].*$/,"")}function normaliseVersionTag(tag){const bare=stripSuffix(stripPrefix(tag));const parts=bare.split(".").map(p=>{const n=parseInt(p,10);return isNaN(n)?0:n});return[parts[0]??0,parts[1]??0,parts[2]??0]}function compareTuples(a,b){for(let i=0;i<3;i++){if(a[i]!==b[i])return b[i]-a[i]}return 0}const FORCE_VERSION_SYMBOL=Symbol.for("slothlet.versioning.force");class VersionManager extends ComponentBase{static slothletProperty="versionManager";#registry=new Map;#versionMetadataByModule=new Map;#moduleToVersionKey=new Map;#dispatchers=new Map;registerVersion(logicalPath,versionTag,moduleID,versionMeta,isDefault){if(!this.#registry.has(logicalPath)){this.#registry.set(logicalPath,{versions:new Map})}const entry=this.#registry.get(logicalPath);if(entry.versions.has(versionTag)){throw new this.SlothletError("VERSION_REGISTER_DUPLICATE",{version:versionTag,apiPath:logicalPath})}const versionEntry={moduleID,versionTag,versionedPath:`${versionTag}.${logicalPath}`,versionedParts:[versionTag,...logicalPath.split(".")],isDefault:isDefault??false,versionMeta:versionMeta??{},registeredAt:Date.now()};entry.versions.set(versionTag,versionEntry);this.#moduleToVersionKey.set(moduleID,{logicalPath,versionTag});this.#versionMetadataByModule.set(moduleID,{...versionMeta??{},version:versionTag,logicalPath});this.slothlet.debug("versioning",{key:"DEBUG_VERSION_REGISTERED",version:versionTag,logicalPath,moduleID});this.updateDispatcher(logicalPath)}unregisterVersion(logicalPath,versionTag){const entry=this.#registry.get(logicalPath);if(!entry)return false;const versionEntry=entry.versions.get(versionTag);if(!versionEntry)return false;this.#moduleToVersionKey.delete(versionEntry.moduleID);this.#versionMetadataByModule.delete(versionEntry.moduleID);entry.versions.delete(versionTag);this.slothlet.debug("versioning",{key:"DEBUG_VERSION_UNREGISTERED",version:versionTag,logicalPath});if(entry.versions.size===0){this.#registry.delete(logicalPath);this.teardownDispatcher(logicalPath)}else{this.updateDispatcher(logicalPath)}return true}getVersionKeyForModule(moduleID){return this.#moduleToVersionKey.get(moduleID)}hasDispatcher(logicalPath){return this.#dispatchers.has(logicalPath)}getVersionMetadata(moduleID){return this.#versionMetadataByModule.get(moduleID)}getVersionMetadataByPath(logicalPath,versionTag){const entry=this.#registry.get(logicalPath);if(!entry)return void 0;const ve=entry.versions.get(versionTag);if(!ve)return void 0;return this.#versionMetadataByModule.get(ve.moduleID)}setVersionMetadataByPath(logicalPath,versionTag,patch){const entry=this.#registry.get(logicalPath);if(!entry||!entry.versions.has(versionTag)){throw new this.SlothletError("VERSION_NOT_FOUND",{version:versionTag,apiPath:logicalPath})}const ve=entry.versions.get(versionTag);const existing=this.#versionMetadataByModule.get(ve.moduleID)??{};this.#versionMetadataByModule.set(ve.moduleID,{...existing,...patch&&typeof patch==="object"?patch:{},version:ve.versionTag,logicalPath})}list(logicalPath){const entry=this.#registry.get(logicalPath);if(!entry)return void 0;const versions={};for(const[tag,ve]of entry.versions){versions[tag]={...ve}}return{versions,default:this.getDefaultVersion(logicalPath)}}setDefault(logicalPath,versionTag){const entry=this.#registry.get(logicalPath);if(!entry){throw new this.SlothletError("VERSION_NOT_FOUND",{version:versionTag,apiPath:logicalPath})}if(!entry.versions.has(versionTag)){throw new this.SlothletError("VERSION_NOT_FOUND",{version:versionTag,apiPath:logicalPath})}for(const ve of entry.versions.values()){ve.isDefault=false}entry.versions.get(versionTag).isDefault=true}getDefaultVersion(logicalPath){const entry=this.#registry.get(logicalPath);if(!entry||entry.versions.size===0)return null;for(const[tag,ve]of entry.versions){if(ve.isDefault)return tag}const tags=Array.from(entry.versions.keys());if(tags.length===1)return tags[0];const sorted=tags.map(tag=>({tag,tuple:normaliseVersionTag(tag)})).sort((a,b)=>{const cmp=compareTuples(a.tuple,b.tuple);if(cmp!==0)return cmp;const aSuffix=a.tag.match(/[-+]/)?1:0;const bSuffix=b.tag.match(/[-+]/)?1:0;return aSuffix-bSuffix});return sorted[0].tag}resolveForPath(logicalPath,allVersions,caller){const discriminator=this.slothlet.config?.versionDispatcher??"version";let resolvedTag=null;if(typeof discriminator==="string"){resolvedTag=caller.versionMetadata?.[discriminator]??null}if(typeof discriminator==="function"){try{resolvedTag=discriminator(allVersions,caller)}catch{resolvedTag=null}}if(resolvedTag==null)return null;const entry=this.#registry.get(logicalPath);if(!entry||!entry.versions.has(resolvedTag)){this.slothlet.debug("versioning",{key:"DEBUG_VERSION_RESOLVED",version:null,apiPath:logicalPath,callerModule:caller?.metadata?.moduleID??null});return null}this.slothlet.debug("versioning",{key:"DEBUG_VERSION_RESOLVED",version:resolvedTag,apiPath:logicalPath,callerModule:caller?.metadata?.moduleID??null});return resolvedTag}buildAllVersionsArg(logicalPath){const entry=this.#registry.get(logicalPath);if(!entry)return{};const defaultTag=this.getDefaultVersion(logicalPath);const result={};for(const[tag,ve]of entry.versions){const mountedWrapper=this.#walkApiPath(ve.versionedParts);const regularMetadata=this.slothlet.handlers.metadata?.getMetadata?.(mountedWrapper)??{};const versionMetadata=this.#versionMetadataByModule.get(ve.moduleID)??{};result[tag]={version:tag,default:tag===defaultTag,metadata:regularMetadata,versionMetadata}}return result}buildCallerArg(callerWrapper){const callerModuleID=callerWrapper?.____slothletInternal?.moduleID??callerWrapper?.__moduleID;const callerVersionEntry=callerModuleID?this.#findVersionEntryForModule(callerModuleID):null;const regularMetadata=this.slothlet.handlers.metadata?.getMetadata?.(callerWrapper)??{};if(!callerVersionEntry){return{version:null,default:null,metadata:regularMetadata,versionMetadata:null}}const defaultTag=this.getDefaultVersion(callerVersionEntry.logicalPath);const versionMetadata=this.#versionMetadataByModule.get(callerModuleID)??{};return{version:callerVersionEntry.versionTag,default:callerVersionEntry.versionTag===defaultTag,metadata:regularMetadata,versionMetadata}}#findVersionEntryForModule(moduleID){const key=this.#moduleToVersionKey.get(moduleID);if(!key)return null;const entry=this.#registry.get(key.logicalPath);if(!entry)return null;return entry.versions.get(key.versionTag)??null}#walkApiPath(apiPath){if(!apiPath)return void 0;let node=this.slothlet.api;const segments=Array.isArray(apiPath)?apiPath:apiPath.split(".");for(const segment of segments){if(node==null)return void 0;node=node[segment]}return node}createDispatcher(logicalPath){const manager=this;const target={__isVersionDispatcher:true,__logicalPath:logicalPath};const displayName=logicalPath.split(".").pop();const resolveVersion=()=>{const ctx=manager.slothlet.contextManager?.tryGetContext?.();const forcedVersion=ctx?.context?.[FORCE_VERSION_SYMBOL];if(forcedVersion){const entry=manager.#registry.get(logicalPath);if(entry?.versions.has(forcedVersion))return forcedVersion}const callerWrapper=ctx?.currentWrapper??null;const allVersions=manager.buildAllVersionsArg(logicalPath);const caller=manager.buildCallerArg(callerWrapper);let tag=manager.resolveForPath(logicalPath,allVersions,caller);if(tag==null){tag=manager.getDefaultVersion(logicalPath);if(tag!=null){manager.slothlet.debug("versioning",{key:"DEBUG_VERSION_DEFAULT_USED",apiPath:logicalPath,version:tag})}}return tag};const resolveVersionedWrapper=()=>{const versionTag=resolveVersion();if(!versionTag)return null;return manager.#walkApiPath([versionTag,...logicalPath.split(".")])};target[Symbol.for("nodejs.util.inspect.custom")]=function(_depth,options,inspectFn){const vw=resolveVersionedWrapper();if(vw){try{return typeof inspectFn==="function"?inspectFn(vw,options):inspect(vw,options)}catch{}}const entry=manager.#registry.get(logicalPath);const versions=entry?Array.from(entry.versions.keys()):[];return{__versionDispatcher:logicalPath,versions}};const handlers={get(t,prop){if(typeof prop==="string"){if(prop==="____slothletInternal"||prop==="_impl"||prop==="__impl"||prop==="__state"||prop==="__invalid"){return void 0}}if(prop==="__isVersionDispatcher")return true;if(prop==="__mode")return"eager";if(prop==="__apiPath")return logicalPath;if(prop==="__slothletPath")return logicalPath;if(prop==="__isCallable")return false;if(prop==="__materializeOnCreate")return false;if(prop==="__materialized")return true;if(prop==="__inFlight")return false;if(prop==="__displayName")return displayName;if(prop==="__moduleID")return`versionDispatcher:${logicalPath}`;if(prop==="_materialize")return()=>{};if(prop==="length")return 0;if(prop==="name")return displayName;if(prop==="then")return void 0;if(prop==="constructor")return Object.prototype.constructor;if(prop===Symbol.toStringTag){const vw=resolveVersionedWrapper();if(!vw)return"Object";return vw[Symbol.toStringTag]}if(prop===inspect.custom){return(_depth,options,inspectFn)=>{const vw=resolveVersionedWrapper();if(vw){try{return typeof inspectFn==="function"?inspectFn(vw,options):inspect(vw,options)}catch{}}const entry=manager.#registry.get(logicalPath);const versions=entry?Array.from(entry.versions.keys()):[];return{__versionDispatcher:logicalPath,versions}}}if(prop==="toString")return()=>`[VersionDispatcher: ${logicalPath}]`;if(prop==="valueOf")return()=>dispatcherProxy;if(prop==="toJSON")return()=>void 0;if(typeof prop==="symbol")return void 0;if(prop==="__metadata"||prop==="__filePath"||prop==="__sourceFolder"||prop==="__type"){const vw=resolveVersionedWrapper();if(!vw)return void 0;return vw[prop]}const versionTag=resolveVersion();if(!versionTag){throw new manager.SlothletError("VERSION_NO_DEFAULT",{apiPath:logicalPath})}const versionedWrapper=manager.#walkApiPath([versionTag,...logicalPath.split(".")]);if(!versionedWrapper)return void 0;return versionedWrapper[prop]},apply(){throw new manager.SlothletError("VERSION_DISPATCH_NOT_CALLABLE",{apiPath:logicalPath})},has(t,key){if(Reflect.has(t,key))return true;const entry=manager.#registry.get(logicalPath);if(!entry)return false;for(const ve of entry.versions.values()){const vw=manager.#walkApiPath(ve.versionedParts);if(vw&&key in vw)return true}return false},ownKeys(t){const keySet=new Set(Reflect.ownKeys(t));const entry=manager.#registry.get(logicalPath);if(entry){for(const ve of entry.versions.values()){const vw=manager.#walkApiPath(ve.versionedParts);if(vw){for(const k of Reflect.ownKeys(Object(vw))){keySet.add(k)}}}}return Array.from(keySet)},getOwnPropertyDescriptor(t,prop){const targetDesc=Reflect.getOwnPropertyDescriptor(t,prop);if(targetDesc){if(!targetDesc.configurable){return targetDesc}return{configurable:true,enumerable:true,writable:false,value:t[prop]}}return{configurable:true,enumerable:true,writable:false,value:void 0}},defineProperty(t,prop,descriptor){const vw=resolveVersionedWrapper();if(!vw)return Reflect.defineProperty(t,prop,descriptor);if(descriptor.configurable===false){const shadow=Object.create(Reflect.getPrototypeOf(t));const currentDescriptor=Reflect.getOwnPropertyDescriptor(t,prop);if(currentDescriptor){Reflect.defineProperty(shadow,prop,currentDescriptor)}if(!Reflect.isExtensible(t)){Reflect.preventExtensions(shadow)}if(!Reflect.defineProperty(shadow,prop,descriptor))return false;if(!Reflect.defineProperty(vw,prop,descriptor))return false;return Reflect.defineProperty(t,prop,descriptor)}return Reflect.defineProperty(vw,prop,descriptor)},set(t,prop,value){if(typeof prop==="symbol")return true;if(prop==="____slothletInternal"||prop==="_impl"||prop==="__impl"||prop==="__state"||prop==="__invalid")return true;if(prop==="__isVersionDispatcher"||prop==="__mode"||prop==="__apiPath"||prop==="__slothletPath"||prop==="__isCallable"||prop==="__materializeOnCreate"||prop==="__materialized"||prop==="__inFlight"||prop==="__displayName"||prop==="__moduleID"||prop==="_materialize"||prop==="length"||prop==="name")return true;if(prop==="then"||prop==="constructor"||prop==="toString"||prop==="valueOf"||prop==="toJSON")return true;const vw=resolveVersionedWrapper();if(!vw)return true;return Reflect.set(vw,prop,value,vw)}};let dispatcherProxy;dispatcherProxy=new Proxy(target,handlers);return dispatcherProxy}updateDispatcher(logicalPath){if(this.#dispatchers.has(logicalPath)){return}const dispatcher=this.createDispatcher(logicalPath);this.#dispatchers.set(logicalPath,dispatcher);const parts=logicalPath.split(".");const mountOptions={collisionMode:"replace",moduleID:`versionDispatcher:${logicalPath}`,allowOverwrite:true,mutateExisting:false};if(this.slothlet.api){this.slothlet.handlers.apiManager.setValueAtPath(this.slothlet.api,parts,dispatcher,mountOptions)}if(this.slothlet.boundApi){this.slothlet.handlers.apiManager.setValueAtPath(this.slothlet.boundApi,parts,dispatcher,mountOptions)}}teardownDispatcher(logicalPath){this.#dispatchers.delete(logicalPath);const parts=logicalPath.split(".");if(this.slothlet.api){this.slothlet.handlers.apiManager.deletePath(this.slothlet.api,parts).catch(()=>{})}if(this.slothlet.boundApi){this.slothlet.handlers.apiManager.deletePath(this.slothlet.boundApi,parts).catch(()=>{})}}onVersionedModuleReload(moduleID){const key=this.#moduleToVersionKey.get(moduleID);if(!key)return;const{logicalPath}=key;this.updateDispatcher(logicalPath);this.slothlet.debug("versioning",{key:"DEBUG_VERSION_REGISTERED",version:key.versionTag,logicalPath,moduleID})}shutdown(){this.#registry.clear();this.#versionMetadataByModule.clear();this.#moduleToVersionKey.clear();this.#dispatchers.clear()}}export{VersionManager};
17
+ import{util}from"@cldmv/slothlet/helpers/platform";import{ComponentBase}from"@cldmv/slothlet/factories/component-base";const inspect=util.inspect;function stripPrefix(tag){return tag.replace(/^[^0-9]+/,"")}function stripSuffix(s){return s.replace(/[-+].*$/,"")}function normaliseVersionTag(tag){const bare=stripSuffix(stripPrefix(tag));const parts=bare.split(".").map(p=>{const n=parseInt(p,10);return isNaN(n)?0:n});return[parts[0]??0,parts[1]??0,parts[2]??0]}function compareTuples(a,b){for(let i=0;i<3;i++){if(a[i]!==b[i])return b[i]-a[i]}return 0}const FORCE_VERSION_SYMBOL=Symbol.for("slothlet.versioning.force");class VersionManager extends ComponentBase{static slothletProperty="versionManager";#registry=new Map;#versionMetadataByModule=new Map;#moduleToVersionKey=new Map;#dispatchers=new Map;registerVersion(logicalPath,versionTag,moduleID,versionMeta,isDefault){if(!this.#registry.has(logicalPath)){this.#registry.set(logicalPath,{versions:new Map})}const entry=this.#registry.get(logicalPath);if(entry.versions.has(versionTag)){throw new this.SlothletError("VERSION_REGISTER_DUPLICATE",{version:versionTag,apiPath:logicalPath})}const versionEntry={moduleID,versionTag,versionedPath:`${versionTag}.${logicalPath}`,versionedParts:[versionTag,...logicalPath.split(".")],isDefault:isDefault??false,versionMeta:versionMeta??{},registeredAt:Date.now()};entry.versions.set(versionTag,versionEntry);this.#moduleToVersionKey.set(moduleID,{logicalPath,versionTag});this.#versionMetadataByModule.set(moduleID,{...versionMeta??{},version:versionTag,logicalPath});this.slothlet.debug("versioning",{key:"DEBUG_VERSION_REGISTERED",version:versionTag,logicalPath,moduleID});this.updateDispatcher(logicalPath)}unregisterVersion(logicalPath,versionTag){const entry=this.#registry.get(logicalPath);if(!entry)return false;const versionEntry=entry.versions.get(versionTag);if(!versionEntry)return false;this.#moduleToVersionKey.delete(versionEntry.moduleID);this.#versionMetadataByModule.delete(versionEntry.moduleID);entry.versions.delete(versionTag);this.slothlet.debug("versioning",{key:"DEBUG_VERSION_UNREGISTERED",version:versionTag,logicalPath});if(entry.versions.size===0){this.#registry.delete(logicalPath);this.teardownDispatcher(logicalPath)}else{this.updateDispatcher(logicalPath)}return true}getVersionKeyForModule(moduleID){return this.#moduleToVersionKey.get(moduleID)}hasDispatcher(logicalPath){return this.#dispatchers.has(logicalPath)}getVersionMetadata(moduleID){return this.#versionMetadataByModule.get(moduleID)}getVersionMetadataByPath(logicalPath,versionTag){const entry=this.#registry.get(logicalPath);if(!entry)return void 0;const ve=entry.versions.get(versionTag);if(!ve)return void 0;return this.#versionMetadataByModule.get(ve.moduleID)}setVersionMetadataByPath(logicalPath,versionTag,patch){const entry=this.#registry.get(logicalPath);if(!entry||!entry.versions.has(versionTag)){throw new this.SlothletError("VERSION_NOT_FOUND",{version:versionTag,apiPath:logicalPath})}const ve=entry.versions.get(versionTag);const existing=this.#versionMetadataByModule.get(ve.moduleID)??{};this.#versionMetadataByModule.set(ve.moduleID,{...existing,...patch&&typeof patch==="object"?patch:{},version:ve.versionTag,logicalPath})}list(logicalPath){const entry=this.#registry.get(logicalPath);if(!entry)return void 0;const versions={};for(const[tag,ve]of entry.versions){versions[tag]={...ve}}return{versions,default:this.getDefaultVersion(logicalPath)}}setDefault(logicalPath,versionTag){const entry=this.#registry.get(logicalPath);if(!entry){throw new this.SlothletError("VERSION_NOT_FOUND",{version:versionTag,apiPath:logicalPath})}if(!entry.versions.has(versionTag)){throw new this.SlothletError("VERSION_NOT_FOUND",{version:versionTag,apiPath:logicalPath})}for(const ve of entry.versions.values()){ve.isDefault=false}entry.versions.get(versionTag).isDefault=true}getDefaultVersion(logicalPath){const entry=this.#registry.get(logicalPath);if(!entry||entry.versions.size===0)return null;for(const[tag,ve]of entry.versions){if(ve.isDefault)return tag}const tags=Array.from(entry.versions.keys());if(tags.length===1)return tags[0];const sorted=tags.map(tag=>({tag,tuple:normaliseVersionTag(tag)})).sort((a,b)=>{const cmp=compareTuples(a.tuple,b.tuple);if(cmp!==0)return cmp;const aSuffix=a.tag.match(/[-+]/)?1:0;const bSuffix=b.tag.match(/[-+]/)?1:0;return aSuffix-bSuffix});return sorted[0].tag}resolveForPath(logicalPath,allVersions,caller){const discriminator=this.slothlet.config?.versionDispatcher??"version";let resolvedTag=null;if(typeof discriminator==="string"){resolvedTag=caller.versionMetadata?.[discriminator]??null}if(typeof discriminator==="function"){try{resolvedTag=discriminator(allVersions,caller)}catch{resolvedTag=null}}if(resolvedTag==null)return null;const entry=this.#registry.get(logicalPath);if(!entry||!entry.versions.has(resolvedTag)){this.slothlet.debug("versioning",{key:"DEBUG_VERSION_RESOLVED",version:null,apiPath:logicalPath,callerModule:caller?.metadata?.moduleID??null});return null}this.slothlet.debug("versioning",{key:"DEBUG_VERSION_RESOLVED",version:resolvedTag,apiPath:logicalPath,callerModule:caller?.metadata?.moduleID??null});return resolvedTag}buildAllVersionsArg(logicalPath){const entry=this.#registry.get(logicalPath);if(!entry)return{};const defaultTag=this.getDefaultVersion(logicalPath);const result={};for(const[tag,ve]of entry.versions){const mountedWrapper=this.#walkApiPath(ve.versionedParts);const regularMetadata=this.slothlet.handlers.metadata?.getMetadata?.(mountedWrapper)??{};const versionMetadata=this.#versionMetadataByModule.get(ve.moduleID)??{};result[tag]={version:tag,default:tag===defaultTag,metadata:regularMetadata,versionMetadata}}return result}buildCallerArg(callerWrapper){const callerModuleID=callerWrapper?.____slothletInternal?.moduleID??callerWrapper?.__moduleID;const callerVersionEntry=callerModuleID?this.#findVersionEntryForModule(callerModuleID):null;const regularMetadata=this.slothlet.handlers.metadata?.getMetadata?.(callerWrapper)??{};if(!callerVersionEntry){return{version:null,default:null,metadata:regularMetadata,versionMetadata:null}}const defaultTag=this.getDefaultVersion(callerVersionEntry.logicalPath);const versionMetadata=this.#versionMetadataByModule.get(callerModuleID)??{};return{version:callerVersionEntry.versionTag,default:callerVersionEntry.versionTag===defaultTag,metadata:regularMetadata,versionMetadata}}#findVersionEntryForModule(moduleID){const key=this.#moduleToVersionKey.get(moduleID);if(!key)return null;const entry=this.#registry.get(key.logicalPath);if(!entry)return null;return entry.versions.get(key.versionTag)??null}#walkApiPath(apiPath){if(!apiPath)return void 0;let node=this.slothlet.api;const segments=Array.isArray(apiPath)?apiPath:apiPath.split(".");for(const segment of segments){if(node==null)return void 0;node=node[segment]}return node}createDispatcher(logicalPath){const manager=this;const target={__isVersionDispatcher:true,__logicalPath:logicalPath};const displayName=logicalPath.split(".").pop();const resolveVersion=()=>{const ctx=manager.slothlet.contextManager?.tryGetContext?.();const forcedVersion=ctx?.context?.[FORCE_VERSION_SYMBOL];if(forcedVersion){const entry=manager.#registry.get(logicalPath);if(entry?.versions.has(forcedVersion))return forcedVersion}const callerWrapper=ctx?.currentWrapper??null;const allVersions=manager.buildAllVersionsArg(logicalPath);const caller=manager.buildCallerArg(callerWrapper);let tag=manager.resolveForPath(logicalPath,allVersions,caller);if(tag==null){tag=manager.getDefaultVersion(logicalPath);if(tag!=null){manager.slothlet.debug("versioning",{key:"DEBUG_VERSION_DEFAULT_USED",apiPath:logicalPath,version:tag})}}return tag};const resolveVersionedWrapper=()=>{const versionTag=resolveVersion();if(!versionTag)return null;return manager.#walkApiPath([versionTag,...logicalPath.split(".")])};target[Symbol.for("nodejs.util.inspect.custom")]=function(_depth,options,inspectFn){const vw=resolveVersionedWrapper();if(vw){try{return typeof inspectFn==="function"?inspectFn(vw,options):inspect(vw,options)}catch{}}const entry=manager.#registry.get(logicalPath);const versions=entry?Array.from(entry.versions.keys()):[];return{__versionDispatcher:logicalPath,versions}};const handlers={get(t,prop){if(typeof prop==="string"){if(prop==="____slothletInternal"||prop==="_impl"||prop==="__impl"||prop==="__state"||prop==="__invalid"){return void 0}}if(prop==="__isVersionDispatcher")return true;if(prop==="__mode")return"eager";if(prop==="__apiPath")return logicalPath;if(prop==="__slothletPath")return logicalPath;if(prop==="__isCallable")return false;if(prop==="__materializeOnCreate")return false;if(prop==="__materialized")return true;if(prop==="__inFlight")return false;if(prop==="__displayName")return displayName;if(prop==="__moduleID")return`versionDispatcher:${logicalPath}`;if(prop==="_materialize")return()=>{};if(prop==="length")return 0;if(prop==="name")return displayName;if(prop==="then")return void 0;if(prop==="constructor")return Object.prototype.constructor;if(prop===Symbol.toStringTag){const vw=resolveVersionedWrapper();if(!vw)return"Object";return vw[Symbol.toStringTag]}if(prop===inspect.custom){return(_depth,options,inspectFn)=>{const vw=resolveVersionedWrapper();if(vw){try{return typeof inspectFn==="function"?inspectFn(vw,options):inspect(vw,options)}catch{}}const entry=manager.#registry.get(logicalPath);const versions=entry?Array.from(entry.versions.keys()):[];return{__versionDispatcher:logicalPath,versions}}}if(prop==="toString")return()=>`[VersionDispatcher: ${logicalPath}]`;if(prop==="valueOf")return()=>dispatcherProxy;if(prop==="toJSON")return()=>void 0;if(typeof prop==="symbol")return void 0;if(prop==="__metadata"||prop==="__filePath"||prop==="__sourceFolder"||prop==="__type"){const vw=resolveVersionedWrapper();if(!vw)return void 0;return vw[prop]}const versionTag=resolveVersion();if(!versionTag){throw new manager.SlothletError("VERSION_NO_DEFAULT",{apiPath:logicalPath})}const versionedWrapper=manager.#walkApiPath([versionTag,...logicalPath.split(".")]);if(!versionedWrapper)return void 0;return versionedWrapper[prop]},apply(){throw new manager.SlothletError("VERSION_DISPATCH_NOT_CALLABLE",{apiPath:logicalPath})},has(t,key){if(Reflect.has(t,key))return true;const entry=manager.#registry.get(logicalPath);if(!entry)return false;for(const ve of entry.versions.values()){const vw=manager.#walkApiPath(ve.versionedParts);if(vw&&key in vw)return true}return false},ownKeys(t){const keySet=new Set(Reflect.ownKeys(t));const entry=manager.#registry.get(logicalPath);if(entry){for(const ve of entry.versions.values()){const vw=manager.#walkApiPath(ve.versionedParts);if(vw){for(const k of Reflect.ownKeys(Object(vw))){keySet.add(k)}}}}return Array.from(keySet)},getOwnPropertyDescriptor(t,prop){const targetDesc=Reflect.getOwnPropertyDescriptor(t,prop);if(targetDesc){if(!targetDesc.configurable){return targetDesc}return{configurable:true,enumerable:true,writable:false,value:t[prop]}}return{configurable:true,enumerable:true,writable:false,value:void 0}},defineProperty(t,prop,descriptor){const vw=resolveVersionedWrapper();if(!vw)return Reflect.defineProperty(t,prop,descriptor);if(descriptor.configurable===false){const shadow=Object.create(Reflect.getPrototypeOf(t));const currentDescriptor=Reflect.getOwnPropertyDescriptor(t,prop);if(currentDescriptor){Reflect.defineProperty(shadow,prop,currentDescriptor)}if(!Reflect.isExtensible(t)){Reflect.preventExtensions(shadow)}if(!Reflect.defineProperty(shadow,prop,descriptor))return false;if(!Reflect.defineProperty(vw,prop,descriptor))return false;return Reflect.defineProperty(t,prop,descriptor)}return Reflect.defineProperty(vw,prop,descriptor)},set(t,prop,value){if(typeof prop==="symbol")return true;if(prop==="____slothletInternal"||prop==="_impl"||prop==="__impl"||prop==="__state"||prop==="__invalid")return true;if(prop==="__isVersionDispatcher"||prop==="__mode"||prop==="__apiPath"||prop==="__slothletPath"||prop==="__isCallable"||prop==="__materializeOnCreate"||prop==="__materialized"||prop==="__inFlight"||prop==="__displayName"||prop==="__moduleID"||prop==="_materialize"||prop==="length"||prop==="name")return true;if(prop==="then"||prop==="constructor"||prop==="toString"||prop==="valueOf"||prop==="toJSON")return true;const vw=resolveVersionedWrapper();if(!vw)return true;return Reflect.set(vw,prop,value,vw)}};let dispatcherProxy;dispatcherProxy=new Proxy(target,handlers);return dispatcherProxy}updateDispatcher(logicalPath){if(this.#dispatchers.has(logicalPath)){return}const dispatcher=this.createDispatcher(logicalPath);this.#dispatchers.set(logicalPath,dispatcher);const parts=logicalPath.split(".");const mountOptions={collisionMode:"replace",moduleID:`versionDispatcher:${logicalPath}`,allowOverwrite:true,mutateExisting:false};if(this.slothlet.api){this.slothlet.handlers.apiManager.setValueAtPath(this.slothlet.api,parts,dispatcher,mountOptions)}if(this.slothlet.boundApi){this.slothlet.handlers.apiManager.setValueAtPath(this.slothlet.boundApi,parts,dispatcher,mountOptions)}}teardownDispatcher(logicalPath){this.#dispatchers.delete(logicalPath);const parts=logicalPath.split(".");if(this.slothlet.api){this.slothlet.handlers.apiManager.deletePath(this.slothlet.api,parts).catch(()=>{})}if(this.slothlet.boundApi){this.slothlet.handlers.apiManager.deletePath(this.slothlet.boundApi,parts).catch(()=>{})}}onVersionedModuleReload(moduleID){const key=this.#moduleToVersionKey.get(moduleID);if(!key)return;const{logicalPath}=key;this.updateDispatcher(logicalPath);this.slothlet.debug("versioning",{key:"DEBUG_VERSION_REGISTERED",version:key.versionTag,logicalPath,moduleID})}shutdown(){this.#registry.clear();this.#versionMetadataByModule.clear();this.#moduleToVersionKey.clear();this.#dispatchers.clear()}}export{VersionManager};
@@ -14,4 +14,4 @@
14
14
  limitations under the License.
15
15
  */
16
16
 
17
- import{EventEmitter}from"node:events";const EXCLUDED_CONSTRUCTORS=new Set([Object,Array,Promise,Date,RegExp,Error]);const TypedArray=Object.getPrototypeOf(Uint8Array);const EXCLUDED_INSTANCEOF_CLASSES=[ArrayBuffer,TypedArray,DataView,Map,Set,WeakMap,WeakSet,EventEmitter];function runtime_shouldWrapMethod(value,prop){return typeof value==="function"&&typeof prop==="string"&&prop!=="constructor"&&!(prop in Object.prototype)&&!prop.startsWith("__")}function runtime_isClassInstance(val){if(val==null||typeof val!=="object"||!val.constructor||typeof val.constructor!=="function"||EXCLUDED_CONSTRUCTORS.has(val.constructor)){return false}for(const cls of EXCLUDED_INSTANCEOF_CLASSES){if(typeof cls==="function"&&val instanceof cls){return false}}return true}function runtime_wrapClassInstance(instance,contextManager,instanceID,instanceCache){if(instanceCache.has(instance)){return instanceCache.get(instance)}const methodCache=new Map;const wrappedInstance=new Proxy(instance,{get(target,prop,receiver){if(methodCache.has(prop)){return methodCache.get(prop)}const value=Reflect.get(target,prop,receiver);if(runtime_shouldWrapMethod(value,prop)){const runtime_contextPreservingMethod=function(...args){const result=contextManager.runInContext(instanceID,value,target,args);if(result!=null&&runtime_isClassInstance(result)){return runtime_wrapClassInstance(result,contextManager,instanceID,instanceCache)}return result};methodCache.set(prop,runtime_contextPreservingMethod);return runtime_contextPreservingMethod}if(value!=null&&runtime_isClassInstance(value)){return runtime_wrapClassInstance(value,contextManager,instanceID,instanceCache)}return value},set(target,prop,value,receiver){if(methodCache.has(prop)){methodCache.delete(prop)}return Reflect.set(target,prop,value,receiver)}});instanceCache.set(instance,wrappedInstance);return wrappedInstance}export{runtime_isClassInstance,runtime_shouldWrapMethod,runtime_wrapClassInstance};
17
+ import{EventEmitter}from"@cldmv/slothlet/helpers/platform";const EXCLUDED_CONSTRUCTORS=new Set([Object,Array,Promise,Date,RegExp,Error]);const SLOTHLET_CLASS_WRAPPED=Symbol("slothlet.classInstanceWrapped");const TypedArray=Object.getPrototypeOf(Uint8Array);const EXCLUDED_INSTANCEOF_CLASSES=[ArrayBuffer,TypedArray,DataView,Map,Set,WeakMap,WeakSet,EventEmitter].filter(Boolean);function runtime_shouldWrapMethod(value,prop){return typeof value==="function"&&typeof prop==="string"&&prop!=="constructor"&&!(prop in Object.prototype)&&!prop.startsWith("__")}function runtime_isClassInstance(val){if(val==null||typeof val!=="object"||!val.constructor||typeof val.constructor!=="function"||EXCLUDED_CONSTRUCTORS.has(val.constructor)){return false}for(const cls of EXCLUDED_INSTANCEOF_CLASSES){if(typeof cls==="function"&&val instanceof cls){return false}}return true}function runtime_wrapClassInstance(instance,contextManager,instanceID,instanceCache){if(instance!=null&&instance[SLOTHLET_CLASS_WRAPPED]){return instance}if(instanceCache.has(instance)){return instanceCache.get(instance)}const methodCache=new Map;const wrappedInstance=new Proxy(instance,{get(target,prop,receiver){if(prop===SLOTHLET_CLASS_WRAPPED){return true}if(methodCache.has(prop)){return methodCache.get(prop)}const value=Reflect.get(target,prop,receiver);if(runtime_shouldWrapMethod(value,prop)){const runtime_contextPreservingMethod=function(...args){const result=contextManager.runInContext(instanceID,value,target,args);if(result!=null&&runtime_isClassInstance(result)){return runtime_wrapClassInstance(result,contextManager,instanceID,instanceCache)}return result};methodCache.set(prop,runtime_contextPreservingMethod);return runtime_contextPreservingMethod}if(value!=null&&runtime_isClassInstance(value)){return runtime_wrapClassInstance(value,contextManager,instanceID,instanceCache)}return value},set(target,prop,value,receiver){if(methodCache.has(prop)){methodCache.delete(prop)}return Reflect.set(target,prop,value,receiver)}});instanceCache.set(instance,wrappedInstance);return wrappedInstance}export{runtime_isClassInstance,runtime_shouldWrapMethod,runtime_wrapClassInstance};