@cldmv/slothlet 3.5.0 → 3.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -7
- package/dist/lib/builders/api_builder.mjs +1 -1
- package/dist/lib/handlers/context-async.mjs +1 -1
- package/dist/lib/handlers/context-live.mjs +1 -1
- package/dist/lib/handlers/hook-manager.mjs +1 -1
- package/dist/lib/handlers/unified-wrapper.mjs +1 -1
- package/dist/lib/helpers/class-instance-wrapper.mjs +1 -1
- package/dist/lib/processors/loader.mjs +1 -1
- package/dist/lib/processors/typescript.mjs +1 -1
- package/index.mjs +8 -5
- package/package.json +1 -1
- package/types/dist/lib/builders/api_builder.d.mts.map +1 -1
- package/types/dist/lib/handlers/context-async.d.mts +1 -1
- package/types/dist/lib/handlers/context-async.d.mts.map +1 -1
- package/types/dist/lib/handlers/context-live.d.mts +1 -1
- package/types/dist/lib/handlers/context-live.d.mts.map +1 -1
- package/types/dist/lib/handlers/hook-manager.d.mts +2 -0
- package/types/dist/lib/handlers/hook-manager.d.mts.map +1 -1
- package/types/dist/lib/handlers/unified-wrapper.d.mts +1 -1
- package/types/dist/lib/handlers/unified-wrapper.d.mts.map +1 -1
- package/types/dist/lib/helpers/class-instance-wrapper.d.mts.map +1 -1
- package/types/dist/lib/processors/loader.d.mts.map +1 -1
- package/types/dist/lib/processors/typescript.d.mts +7 -1
- package/types/dist/lib/processors/typescript.d.mts.map +1 -1
- package/types/index.d.mts +2 -2
- package/types/index.d.mts.map +1 -1
package/README.md
CHANGED
|
@@ -55,19 +55,19 @@ Every feature has been hardened with a comprehensive test suite - over **5,300 t
|
|
|
55
55
|
|
|
56
56
|
## ✨ What's New
|
|
57
57
|
|
|
58
|
-
### Latest: v3.
|
|
58
|
+
### Latest: v3.6.0 (May 2026)
|
|
59
59
|
|
|
60
|
-
-
|
|
61
|
-
- **`slothlet
|
|
62
|
-
-
|
|
63
|
-
- [View full v3.
|
|
60
|
+
- **`self.slothlet.lockCaller(fn)`** — pins the registering module's caller identity onto a callback. Callbacks stored in plain arrays — a web framework's `addHook` handler, a third-party event registry — never pass through slothlet's `EventEmitter` patch, so they run with whatever module's async context is ambient when they fire. `lockCaller` overrides only the caller identity (request-scoped context stays live), so `self.*` calls and permission rules inside the callback are always attributed to the module that registered it.
|
|
61
|
+
- **`self.slothlet.bind(fn)`** — a convenience re-export of Node's `AsyncResource.bind` that freezes the entire async context captured at registration time. Reach for `lockCaller` when you want the caller pinned but request context live, and `bind` when you want the whole context snapshot frozen.
|
|
62
|
+
- **Caller identity is now correct for hooks and `run`/`scope` too** — `api.slothlet.hook.on()` auto-pins the registering module's caller identity onto hook handlers by default (opt out with `{ lockCaller: false }`), and `api.slothlet.run()` / `.scope()` callbacks now carry the caller identity through instead of dropping it. A `self.*` call inside a hook or a `run`/`scope` callback is attributed to the module that owns the code.
|
|
63
|
+
- [View full v3.6.0 Changelog](./docs/changelog/v3/v3.6.0.md)
|
|
64
64
|
|
|
65
65
|
### Recent Releases
|
|
66
66
|
|
|
67
|
+
- **v3.5.1** (May 2026) — Binary buffers (`Buffer` / `TypedArray` / `DataView`) cross `self` unwrapped; relative imports work from `.ts` / `.mts` modules ([Changelog](./docs/changelog/v3/v3.5.1.md))
|
|
68
|
+
- **v3.5.0** (May 2026) — TypeScript runtime imports (`self` / `context` / `instanceID`) work from `.ts` / `.mts`; `slothlet typegen` CLI + programmatic API; runtime `self.X = …` assignment now persists ([Changelog](./docs/changelog/v3/v3.5.0.md))
|
|
67
69
|
- **v3.4.1** (May 2026) — Permission gating for all `api.slothlet.*` routes; metadata hardening against prototype-pollution and circular payloads ([Changelog](./docs/changelog/v3/v3.4.1.md))
|
|
68
70
|
- **v3.4.0** (May 2026) — Context-conditional permission rules: optional `condition` field (plain object, function, or array) on rules evaluated against per-request ALS context ([Changelog](./docs/changelog/v3/v3.4.0.md))
|
|
69
|
-
- **v3.3.2** (April 2026) — Workflow maintenance: Node.js minimum raised to `20.19.0`; `lts_only_matrix` input added to CI/release workflows ([Changelog](./docs/changelog/v3/v3.3.2.md))
|
|
70
|
-
- **v3.3.1** (April 2026) — `construct` trap for proxied classes; Node.js engine requirement raised to ≥ 20.19.0; type declaration fixes ([Changelog](./docs/changelog/v3/v3.3.1.md))
|
|
71
71
|
|
|
72
72
|
|
|
73
73
|
📚 **For complete version history and detailed release notes, see [docs/changelog/](./docs/changelog/) folder.**
|
|
@@ -14,4 +14,4 @@
|
|
|
14
14
|
limitations under the License.
|
|
15
15
|
*/
|
|
16
16
|
|
|
17
|
-
import{ComponentBase}from"@cldmv/slothlet/factories/component-base";import{TYPE_STATES}from"@cldmv/slothlet/handlers/unified-wrapper";import{getLanguage,initI18n,setLanguage,t,translate}from"@cldmv/slothlet/i18n";function _resolvePathOrModuleId(slothlet,pathOrModuleId){const history=slothlet.handlers?.apiManager?.state?.addHistory;if(history){let match=null;for(let i=history.length-1;i>=0;i--){const entry=history[i];if(entry?.moduleID===pathOrModuleId){match=entry;break}}if(match)return match.apiPath}return pathOrModuleId}function makeCopyOnWriteSelf(parentSelf){const overlay=new Map;const childViews=new Map;return new Proxy({},{get(_t,prop){if(overlay.has(prop))return overlay.get(prop);const real=parentSelf[prop];if(real!==null&&typeof real==="object"){let view=childViews.get(prop);if(view===void 0){view=makeCopyOnWriteSelf(real);childViews.set(prop,view)}return view}return real},set(_t,prop,value){overlay.set(prop,value);childViews.delete(prop);return true},has(_t,prop){return overlay.has(prop)||prop in parentSelf},deleteProperty(_t,prop){overlay.delete(prop);childViews.delete(prop);return true},ownKeys(){const keys=new Set(Reflect.ownKeys(parentSelf));for(const k of overlay.keys())keys.add(k);return[...keys]},getOwnPropertyDescriptor(_t,prop){if(overlay.has(prop)){return{value:overlay.get(prop),writable:true,enumerable:true,configurable:true}}const desc=Reflect.getOwnPropertyDescriptor(parentSelf,prop);return desc?{...desc,configurable:true}:void 0}})}class ApiBuilder extends ComponentBase{static slothletProperty="apiBuilder";constructor(slothlet){super(slothlet)}async buildFinalAPI(userApi){this.slothlet.debug("api",{key:"DEBUG_MODE_BUILD_FINAL_API_CALLED",diagnostics:this.____config.diagnostics,userApiKeys:Object.keys(userApi)});if(this.slothlet._ownBuiltins){for(const[key,ref]of Object.entries(this.slothlet._ownBuiltins)){if(ref&&Object.prototype.hasOwnProperty.call(userApi,key)&&userApi[key]===ref){try{delete userApi[key]}catch(_){}}}}this.slothlet.userHooks={shutdown:typeof userApi.shutdown==="function"?userApi.shutdown:null,destroy:typeof userApi.destroy==="function"?userApi.destroy:null};if(userApi.slothlet){new this.SlothletWarning("WARNING_RESERVED_PROPERTY_CONFLICT",{properties:"slothlet"})}const slothletNamespace=await this.createSlothletNamespace(userApi);this.slothlet.debug("api",{key:"DEBUG_MODE_SLOTHLET_NAMESPACE_CREATED",namespaceKeys:Object.keys(slothletNamespace),hasDiag:!!slothletNamespace.diag});const shutdownFn=this.createShutdownFunction();this.attachBuiltins(userApi,{slothlet:slothletNamespace,shutdown:shutdownFn,destroy:null});this.slothlet.debug("api",{key:"DEBUG_MODE_BUILT_INS_ATTACHED",userApiKeys:Object.keys(userApi),hasSlothlet:!!userApi.slothlet,hasDiag:!!userApi.slothlet?.diag});const destroyWithApi=this.createDestroyFunction(userApi);Object.defineProperty(userApi,"destroy",{value:destroyWithApi,enumerable:true,writable:false,configurable:true});this.slothlet._ownBuiltins={shutdown:shutdownFn,slothlet:slothletNamespace,destroy:destroyWithApi};return userApi}async createSlothletNamespace(userApi){const slothlet=this.slothlet;const config=this.____config;const enforceInternalPermission=targetPath=>{const ctx=slothlet.contextManager?.tryGetContext?.();const callerWrapper=ctx?.currentWrapper;if(!callerWrapper)return;const permissionManager=slothlet.handlers?.permissionManager;if(!permissionManager?.enforceAccess){throw new slothlet.SlothletError("PERMISSION_MANAGER_NOT_AVAILABLE",{validationError:true})}const callerPath=callerWrapper.____slothletInternal?.apiPath??"";const callerFilePath=callerWrapper.____slothletInternal?.filePath??null;const runtimeContext=ctx?.context??null;if(!permissionManager.enforceAccess(callerPath,targetPath,callerFilePath,null,runtimeContext)){throw new slothlet.SlothletError("PERMISSION_DENIED",{caller:callerPath,target:targetPath})}};const canTraverseInternalNamespace=targetPath=>{const ctx=slothlet.contextManager?.tryGetContext?.();const callerWrapper=ctx?.currentWrapper;if(!callerWrapper)return false;const permissionManager=slothlet.handlers?.permissionManager;if(!permissionManager?.getRulesForCaller||!permissionManager?.checkAccess){return false}const callerPath=callerWrapper.____slothletInternal?.apiPath??"";const callerFilePath=callerWrapper.____slothletInternal?.filePath??null;const runtimeContext=ctx?.context??null;const callerRules=permissionManager.getRulesForCaller(callerPath);const conditionMatches=condition=>typeof permissionManager.matchesCondition==="function"?permissionManager.matchesCondition(condition,runtimeContext):false;const prefix=`${targetPath}.`;for(const rule of callerRules){if(!rule||rule.effect!=="allow"||typeof rule.target!=="string")continue;const couldMatchDescendant=rule.target.startsWith(prefix)||rule.target==="**"||rule.target==="*";if(!couldMatchDescendant)continue;if(rule.target.startsWith(prefix)&&conditionMatches(rule.condition)){return true}const probePaths=[`${targetPath}.__probe__`];if(rule.target.startsWith(prefix)){const suffix=rule.target.slice(prefix.length);const firstSegment=suffix.split(".")[0];if(firstSegment&&!/[*!?{}]/u.test(firstSegment)){probePaths.unshift(`${targetPath}.${firstSegment}`);probePaths.push(`${targetPath}.${firstSegment}.__probe__`)}}for(const probePath of probePaths){if(permissionManager.checkAccess(callerPath,probePath,callerFilePath,null,runtimeContext,{useCache:false})){return true}}}return false};const createInternalRouteProxy=(value,routePath,seen=new WeakMap)=>{if(!value||typeof value!=="object"&&typeof value!=="function")return value;const isMetaProperty=prop=>prop==="__proto__"||prop==="prototype"||prop==="constructor"||prop==="caller"||prop==="arguments";let routeCache=seen.get(value);if(!routeCache){routeCache=new Map;seen.set(value,routeCache)}if(routeCache.has(routePath)){return routeCache.get(routePath)}const proxy=new Proxy(value,{get(target,prop,receiver){if(typeof prop!=="string"){const result2=Reflect.get(target,prop,receiver);return createInternalRouteProxy(result2,routePath,seen)}const childRoutePath=`${routePath}.${prop}`;let deniedError=null;try{enforceInternalPermission(childRoutePath)}catch(error){deniedError=error}if(deniedError){if(canTraverseInternalNamespace(childRoutePath)){const result2=Reflect.get(target,prop,receiver);if(result2&&(typeof result2==="object"||typeof result2==="function")){return createInternalRouteProxy(result2,childRoutePath,seen)}}throw deniedError}const result=Reflect.get(target,prop,receiver);if(isMetaProperty(prop)){return result}const descriptor=Object.getOwnPropertyDescriptor(target,prop);if(descriptor&&"value"in descriptor&&descriptor.configurable===false&&descriptor.writable===false){return descriptor.value}return createInternalRouteProxy(result,childRoutePath,seen)},getOwnPropertyDescriptor(target,prop){const descriptor=Reflect.getOwnPropertyDescriptor(target,prop);if(!descriptor)return void 0;if(typeof prop!=="string"){return descriptor}const childRoutePath=`${routePath}.${prop}`;if(isMetaProperty(prop)){enforceInternalPermission(childRoutePath);return descriptor}if("get"in descriptor||"set"in descriptor){enforceInternalPermission(childRoutePath);if(descriptor.configurable===true){return{...descriptor,get:typeof descriptor.get==="function"?function slothlet_internal_descriptor_getter(...args){enforceInternalPermission(childRoutePath);return Reflect.apply(descriptor.get,this,args)}:descriptor.get,set:typeof descriptor.set==="function"?function slothlet_internal_descriptor_setter(...args){enforceInternalPermission(childRoutePath);return Reflect.apply(descriptor.set,this,args)}:descriptor.set}}return descriptor}if(!("value"in descriptor)){return descriptor}const descriptorValue=descriptor.value;if(descriptor.configurable===false&&descriptor.writable===false){enforceInternalPermission(childRoutePath);return descriptor}if(!descriptorValue||typeof descriptorValue!=="object"&&typeof descriptorValue!=="function"||typeof descriptorValue==="function"){enforceInternalPermission(childRoutePath);if(typeof descriptorValue==="function"&&descriptor.configurable===true){return{...descriptor,value:createInternalRouteProxy(descriptorValue,childRoutePath,seen)}}return descriptor}return{...descriptor,value:createInternalRouteProxy(descriptorValue,childRoutePath,seen)}},set(target,prop,newValue,receiver){if(typeof prop!=="string"){return Reflect.set(target,prop,newValue,receiver)}const childRoutePath=`${routePath}.${prop}`;enforceInternalPermission(childRoutePath);return Reflect.set(target,prop,newValue,receiver)},defineProperty(target,prop,descriptor){if(typeof prop!=="string"){return Reflect.defineProperty(target,prop,descriptor)}const childRoutePath=`${routePath}.${prop}`;enforceInternalPermission(childRoutePath);return Reflect.defineProperty(target,prop,descriptor)},deleteProperty(target,prop){if(typeof prop!=="string"){return Reflect.deleteProperty(target,prop)}const childRoutePath=`${routePath}.${prop}`;enforceInternalPermission(childRoutePath);return Reflect.deleteProperty(target,prop)},ownKeys(target){return Reflect.ownKeys(target)},apply(target,thisArg,argArray){enforceInternalPermission(routePath);return Reflect.apply(target,thisArg,argArray)},construct(target,argArray,newTarget){enforceInternalPermission(routePath);return Reflect.construct(target,argArray,newTarget)}});routeCache.set(routePath,proxy);return proxy};let version="unknown";try{const pkgPath=new URL("../../../package.json",import.meta.url);const{readFile}=await import("node:fs/promises");const pkgContent=await readFile(pkgPath,"utf-8");const pkg=JSON.parse(pkgContent);version=pkg.version||"unknown"}catch{}const namespace={i18n:{setLanguage,getLanguage,translate,t,initI18n},version,instanceID:slothlet.instanceID,types:TYPE_STATES,api:{add:async function slothlet_api_add(apiPath,folderPath,options={},versionConfig=null){if(!config.api?.mutations?.add){throw new slothlet.SlothletError("INVALID_CONFIG_MUTATIONS_DISABLED",{operation:"api.add",validationError:true})}const{recordHistory:____recordHistory,collisionMode:____collisionMode,mutateExisting:____mutateExisting,...filteredOptions}=options;return slothlet.handlers.apiManager.addApiComponent({apiPath,folderPath,options:filteredOptions,versionConfig:versionConfig||null})},remove:async function slothlet_api_remove(pathOrModuleId){if(!config.api?.mutations?.remove){throw new slothlet.SlothletError("INVALID_CONFIG_MUTATIONS_DISABLED",{operation:"api.remove",validationError:true})}if(typeof pathOrModuleId!=="string"){throw new slothlet.SlothletError("INVALID_ARGUMENT",{argument:"pathOrModuleId",expected:"string",received:typeof pathOrModuleId,validationError:true})}return slothlet.handlers.apiManager.removeApiComponent(pathOrModuleId)},reload:async function slothlet_api_reload(pathOrModuleId,options){if(!config.api?.mutations?.reload){throw new slothlet.SlothletError("INVALID_CONFIG_MUTATIONS_DISABLED",{operation:"api.reload",validationError:true})}if(pathOrModuleId==null||pathOrModuleId===""||pathOrModuleId==="."){return slothlet.handlers.apiManager.reloadApiComponent({apiPath:".",options})}if(typeof pathOrModuleId!=="string"){throw new slothlet.SlothletError("INVALID_ARGUMENT",{argument:"pathOrModuleId",expected:"string, null, undefined, or '.'",received:typeof pathOrModuleId,validationError:true})}const isModuleId=slothlet.handlers.apiManager.state.addHistory.some(entry=>entry.moduleID===pathOrModuleId);if(isModuleId){return slothlet.handlers.apiManager.reloadApiComponent({moduleID:pathOrModuleId,options})}const normalizedPath=slothlet.handlers.apiManager.normalizeApiPath(pathOrModuleId).apiPath;const pathParts=normalizedPath.split(".");let current=slothlet.api;for(const part of pathParts){if(!current||typeof current!=="object"&&typeof current!=="function"){throw new slothlet.SlothletError("INVALID_API_PATH",{apiPath:pathOrModuleId,validationError:true})}current=current[part]}if(current===void 0){throw new slothlet.SlothletError("INVALID_API_PATH",{apiPath:pathOrModuleId,validationError:true})}return slothlet.handlers.apiManager.reloadApiComponent({apiPath:normalizedPath,options})}},sanitize:function slothlet_sanitize(str){if(typeof str!=="string"){throw new slothlet.SlothletError("INVALID_ARGUMENT",{argument:"str",expected:"string",received:typeof str,validationError:true})}return slothlet.helpers.sanitize.sanitizePropertyName(str,slothlet.config.sanitize||{})},context:{get:key=>{if(slothlet.contextManager.constructor.name==="LiveContextManager"){const currentID=slothlet.contextManager.currentInstanceID;if(currentID){const activeStore=slothlet.contextManager.instances.get(currentID);const isOurInstance=currentID===slothlet.instanceID||currentID?.startsWith(slothlet.instanceID+"__run_")||activeStore?.parentInstanceID===slothlet.instanceID;if(isOurInstance&&activeStore){return key?activeStore.context[key]:{...activeStore.context}}}const store=slothlet.contextManager.instances.get(slothlet.instanceID);if(!store){const baseContext2=slothlet.context||{};return key?baseContext2[key]:{...baseContext2}}return key?store.context[key]:{...store.context}}if(slothlet.contextManager.constructor.name==="AsyncContextManager"){let currentStore=slothlet.contextManager.tryGetContext();if(!currentStore){const baseStore2=slothlet.contextManager.instances.get(slothlet.instanceID);const baseContext3=baseStore2?.context||{};return key?baseContext3[key]:{...baseContext3}}const isOurInstance=currentStore.instanceID===slothlet.instanceID||currentStore.parentInstanceID===slothlet.instanceID||currentStore.instanceID.startsWith(slothlet.instanceID+"__run_");if(isOurInstance){return key?currentStore.context[key]:{...currentStore.context}}const baseStore=slothlet.contextManager.instances.get(slothlet.instanceID);const baseContext2=baseStore?.context||{};return key?baseContext2[key]:{...baseContext2}}const baseContext=slothlet.context||{};return key?baseContext[key]:{...baseContext}},diagnostics:()=>{if(!slothlet.config?.diagnostics)return void 0;const managerType=slothlet.contextManager.constructor.name;const result={instanceID:slothlet.instanceID,managerType,instancesMapSize:slothlet.contextManager.instances.size,instancesMapKeys:Array.from(slothlet.contextManager.instances.keys()),baseContext:slothlet.context};const store=slothlet.contextManager.instances.get(slothlet.instanceID);result.storeFromInstancesMap=store?{instanceID:store.instanceID,context:store.context,createdAt:store.createdAt}:null;if(managerType==="AsyncContextManager"){try{const currentCtx=slothlet.contextManager.tryGetContext();result.currentALSContext=currentCtx?{instanceID:currentCtx.instanceID,context:currentCtx.context,hasParent:!!currentCtx.parentContext,parentInstanceID:currentCtx.parentInstanceID}:null}catch(____error){result.currentALSContext=null}}if(managerType==="LiveContextManager"){result.currentInstanceID=slothlet.contextManager.currentInstanceID}return result},run:this.createRunFunction(),scope:this.createScopeFunction()},hook:{on:function slothlet_hook_on(typePattern,handler,options={}){if(!slothlet.handlers?.hookManager){throw new slothlet.SlothletError("HOOKS_NOT_INITIALIZED",{validationError:true})}return slothlet.handlers.hookManager.on(typePattern,handler,options)},remove:function slothlet_hook_remove(filter={}){if(!slothlet.handlers?.hookManager){throw new slothlet.SlothletError("HOOKS_NOT_INITIALIZED",{validationError:true})}return slothlet.handlers.hookManager.remove(filter)},clear:function slothlet_hook_clear(filter={}){return this.remove(filter)},off:function slothlet_hook_off(idOrFilter){if(!slothlet.handlers?.hookManager){throw new slothlet.SlothletError("HOOKS_NOT_INITIALIZED",{validationError:true})}const filter=typeof idOrFilter==="string"?{id:idOrFilter}:idOrFilter;return slothlet.handlers.hookManager.remove(filter)},enable:function slothlet_hook_enable(filter={}){if(!slothlet.handlers?.hookManager){throw new slothlet.SlothletError("HOOKS_NOT_INITIALIZED",{validationError:true})}return slothlet.handlers.hookManager.enable(filter)},disable:function slothlet_hook_disable(filter={}){if(!slothlet.handlers?.hookManager){throw new slothlet.SlothletError("HOOKS_NOT_INITIALIZED",{validationError:true})}return slothlet.handlers.hookManager.disable(filter)},list:function slothlet_hook_list(filter={}){if(!slothlet.handlers?.hookManager){throw new slothlet.SlothletError("HOOKS_NOT_INITIALIZED",{validationError:true})}return slothlet.handlers.hookManager.list(filter)}},metadata:{setGlobal:function slothlet_metadata_setGlobal(keyOrObj,value){if(!slothlet.handlers?.metadata){throw new slothlet.SlothletError("METADATA_NOT_AVAILABLE",{handlersKeys:slothlet.handlers?Object.keys(slothlet.handlers).join(", "):"undefined",validationError:true})}const validateGlobalMetadataKeyPath=keyPath=>{const blocked=new Set(["__proto__","prototype","constructor"]);if(typeof keyPath!=="string"||keyPath.length===0){throw new slothlet.SlothletError("INVALID_METADATA_KEY",{key:keyPath,type:typeof keyPath,expected:"non-empty string"})}const segments=keyPath.split(".");for(const segment of segments){if(!segment||blocked.has(segment)){throw new slothlet.SlothletError("INVALID_METADATA_KEY",{key:keyPath,type:typeof keyPath,expected:"safe dot-notation key without reserved segments"})}}};const normalizeGlobalMetadataObject=(source,prefix="",ancestors=new WeakSet)=>{if(ancestors.has(source)){throw new slothlet.SlothletError("INVALID_ARGUMENT",{argument:"keyOrObj",expected:"acyclic object",received:"circular reference",validationError:true})}ancestors.add(source);try{const normalized={};for(const[key,nestedValue]of Object.entries(source)){const fullKey=prefix?`${prefix}.${key}`:key;validateGlobalMetadataKeyPath(fullKey);const nestedProto=nestedValue&&typeof nestedValue==="object"?Object.getPrototypeOf(nestedValue):null;const isPlainNested=nestedProto===Object.prototype||nestedProto===null;if(nestedValue&&typeof nestedValue==="object"&&!Array.isArray(nestedValue)&&isPlainNested){normalized[key]=normalizeGlobalMetadataObject(nestedValue,fullKey,ancestors);continue}normalized[key]=nestedValue}return normalized}finally{ancestors.delete(source)}};if(keyOrObj&&typeof keyOrObj==="object"&&!Array.isArray(keyOrObj)){const normalizedMetadata=normalizeGlobalMetadataObject(keyOrObj);for(const[key,nestedValue]of Object.entries(normalizedMetadata)){slothlet.handlers.metadata.setGlobalMetadata(key,nestedValue)}return}if(typeof keyOrObj!=="string"){throw new slothlet.SlothletError("INVALID_ARGUMENT",{argument:"keyOrObj",expected:"string or object",received:typeof keyOrObj,validationError:true})}validateGlobalMetadataKeyPath(keyOrObj);return slothlet.handlers.metadata.setGlobalMetadata(keyOrObj,value)},set:function slothlet_metadata_set(fn,key,value){if(!slothlet.handlers?.metadata){throw new slothlet.SlothletError("METADATA_NOT_AVAILABLE",{handlersKeys:slothlet.handlers?Object.keys(slothlet.handlers).join(", "):"undefined",validationError:true})}return slothlet.handlers.metadata.setUserMetadata(fn,key,value)},remove:function slothlet_metadata_remove(fn,key){return slothlet.handlers.metadata.removeUserMetadata(fn,key)},setFor:function slothlet_metadata_setFor(pathOrModuleId,keyOrObj,value){if(!slothlet.handlers?.metadata){throw new slothlet.SlothletError("METADATA_NOT_AVAILABLE",{handlersKeys:slothlet.handlers?Object.keys(slothlet.handlers).join(", "):"undefined",validationError:true})}const resolvedPath=_resolvePathOrModuleId(slothlet,pathOrModuleId);return slothlet.handlers.metadata.setPathMetadata(resolvedPath,keyOrObj,value)},removeFor:function slothlet_metadata_removeFor(pathOrModuleId,key){if(!slothlet.handlers?.metadata)return;const resolvedPath=_resolvePathOrModuleId(slothlet,pathOrModuleId);return slothlet.handlers.metadata.removePathMetadata(resolvedPath,key)},setForVersion:function slothlet_metadata_setForVersion(logicalPath,versionTag,keyOrObj,value){if(!slothlet.handlers?.metadata){throw new slothlet.SlothletError("METADATA_NOT_AVAILABLE",{handlersKeys:slothlet.handlers?Object.keys(slothlet.handlers).join(", "):"undefined",validationError:true})}const info=slothlet.handlers?.versionManager?.list(logicalPath);if(!info||!info.versions?.[versionTag]){throw new slothlet.SlothletError("VERSION_NOT_FOUND",{version:versionTag,apiPath:logicalPath})}const{moduleID}=info.versions[versionTag];const resolvedPath=_resolvePathOrModuleId(slothlet,moduleID);return slothlet.handlers.metadata.setPathMetadata(resolvedPath,keyOrObj,value)},getForVersion:function slothlet_metadata_getForVersion(logicalPath,versionTag){if(!slothlet.handlers?.metadata)return{};const info=slothlet.handlers?.versionManager?.list(logicalPath);if(!info||!info.versions?.[versionTag])return{};const{moduleID}=info.versions[versionTag];const resolvedPath=_resolvePathOrModuleId(slothlet,moduleID);return slothlet.handlers.metadata.getPathMetadata(resolvedPath)}},scope:this.createScopeFunction(),run:this.createRunFunction(),reload:async(options={})=>{if(!config.api?.mutations?.reload){throw new slothlet.SlothletError("INVALID_CONFIG_MUTATIONS_DISABLED",{operation:"reload",validationError:true})}return slothlet.reload(options)},shutdown:async()=>{return slothlet.shutdown()},owner:{get:apiPath=>{if(slothlet.handlers?.ownership){return slothlet.handlers.ownership.getPathOwnership(apiPath)}return null}},materialize:(()=>{const mgr=slothlet.handlers?.materialize;const getMaterializedState=()=>{enforceInternalPermission("slothlet.materialize.materialized");return mgr?.materialized??false};const getMaterializeStats=()=>{enforceInternalPermission("slothlet.materialize.get");return mgr?mgr.get():{total:0,materialized:0,remaining:0,percentage:100}};const waitForMaterialization=async()=>{enforceInternalPermission("slothlet.materialize.wait");if(!mgr)return;return mgr.wait()};if(!mgr){return Object.freeze({get materialized(){return getMaterializedState()},get:getMaterializeStats,wait:waitForMaterialization})}return Object.freeze({get materialized(){return getMaterializedState()},get:getMaterializeStats,wait:waitForMaterialization})})(),lifecycle:(()=>{const handler=slothlet.handlers?.lifecycle;const noop=()=>{};if(!handler)return{on:noop,off:noop};return{on:handler.on.bind(handler),off:handler.off.bind(handler)}})(),env:slothlet.envSnapshot,versioning:{list:function slothlet_version_list(logicalPath){if(!slothlet.handlers?.versionManager)return void 0;return slothlet.handlers.versionManager.list(logicalPath)},setDefault:function slothlet_version_setDefault(logicalPath,versionTag){if(!slothlet.handlers?.versionManager)return;return slothlet.handlers.versionManager.setDefault(logicalPath,versionTag)},unregister:async function slothlet_version_unregister(logicalPath,versionTag){if(!slothlet.handlers?.versionManager)return false;const info=slothlet.handlers.versionManager.list(logicalPath);if(!info||!info.versions?.[versionTag])return false;const{moduleID:versionedModuleID}=info.versions[versionTag];await slothlet.handlers.apiManager.removeApiComponent(versionedModuleID);return true},getVersionMetadata:function slothlet_version_getVersionMetadata(logicalPath,versionTag){if(!slothlet.handlers?.versionManager)return void 0;return slothlet.handlers.versionManager.getVersionMetadataByPath(logicalPath,versionTag)},setVersionMetadata:function slothlet_version_setVersionMetadata(logicalPath,versionTag,patch){if(!slothlet.handlers?.versionManager)return;return slothlet.handlers.versionManager.setVersionMetadataByPath(logicalPath,versionTag,patch)}},permissions:{addRule:function slothlet_permissions_addRule(rule){if(!config.api?.mutations?.permissions){throw new slothlet.SlothletError("INVALID_CONFIG_MUTATIONS_DISABLED",{operation:"api.slothlet.permissions.addRule",validationError:true})}const permissionManager=slothlet.handlers?.permissionManager;if(!permissionManager?.addRule){throw new slothlet.SlothletError("PERMISSION_MANAGER_NOT_AVAILABLE",{validationError:true})}const ruleId=permissionManager.addRule(rule,null);if(slothlet.handlers?.apiManager?.state?.operationHistory){slothlet.handlers.apiManager.state.operationHistory.push({type:"addPermissionRule",rule,ownerModuleID:null,ruleId,timestamp:Date.now()})}return ruleId},removeRule:function slothlet_permissions_removeRule(ruleId){if(!config.api?.mutations?.permissions){throw new slothlet.SlothletError("INVALID_CONFIG_MUTATIONS_DISABLED",{operation:"api.slothlet.permissions.removeRule",validationError:true})}const permissionManager=slothlet.handlers?.permissionManager;if(!permissionManager?.removeRule){throw new slothlet.SlothletError("PERMISSION_MANAGER_NOT_AVAILABLE",{validationError:true})}const ctx=slothlet.contextManager?.tryGetContext?.();const currentWrapper=ctx?.currentWrapper;const callerModuleID=currentWrapper?.____slothletInternal?.moduleID??null;const result=slothlet.handlers.permissionManager.removeRule(ruleId,callerModuleID);if(result&&slothlet.handlers?.apiManager?.state?.operationHistory){slothlet.handlers.apiManager.state.operationHistory.push({type:"removePermissionRule",ruleId,callerModuleID,timestamp:Date.now()})}return result},self:{access:function slothlet_permissions_self_access(target){const permissionManager=slothlet.handlers?.permissionManager;if(!permissionManager?.checkAccess){throw new slothlet.SlothletError("PERMISSION_MANAGER_NOT_AVAILABLE",{validationError:true})}const ctx=slothlet.contextManager?.tryGetContext?.();const currentWrapper=ctx?.currentWrapper;const callerPath=currentWrapper?.____slothletInternal?.apiPath??"";const callerFilePath=currentWrapper?.____slothletInternal?.filePath??null;const runtimeContext=ctx?.context??null;return slothlet.handlers.permissionManager.checkAccess(callerPath,target,callerFilePath,null,runtimeContext)},rules:function slothlet_permissions_self_rules(){const permissionManager=slothlet.handlers?.permissionManager;if(!permissionManager?.getRulesForCaller){throw new slothlet.SlothletError("PERMISSION_MANAGER_NOT_AVAILABLE",{validationError:true})}const currentWrapper=slothlet.contextManager?.tryGetContext?.()?.currentWrapper;const callerPath=currentWrapper?.____slothletInternal?.apiPath??"";return slothlet.handlers.permissionManager.getRulesForCaller(callerPath)}},global:{checkAccess:function slothlet_permissions_global_checkAccess(caller,target){const permissionManager=slothlet.handlers?.permissionManager;if(!permissionManager?.checkAccess){throw new slothlet.SlothletError("PERMISSION_MANAGER_NOT_AVAILABLE",{validationError:true})}const runtimeContext=slothlet.contextManager?.tryGetContext?.()?.context??null;return slothlet.handlers.permissionManager.checkAccess(caller,target,null,null,runtimeContext)},rulesForPath:function slothlet_permissions_global_rulesForPath(path){const permissionManager=slothlet.handlers?.permissionManager;if(!permissionManager?.getRulesForPath){throw new slothlet.SlothletError("PERMISSION_MANAGER_NOT_AVAILABLE",{validationError:true})}return slothlet.handlers.permissionManager.getRulesForPath(path)},rulesByModule:function slothlet_permissions_global_rulesByModule(moduleID){const permissionManager=slothlet.handlers?.permissionManager;if(!permissionManager?.getRulesByModule){throw new slothlet.SlothletError("PERMISSION_MANAGER_NOT_AVAILABLE",{validationError:true})}return slothlet.handlers.permissionManager.getRulesByModule(moduleID)}},control:{get enabled(){const permissionManager=slothlet.handlers?.permissionManager;if(!permissionManager?.isEnabled){throw new slothlet.SlothletError("PERMISSION_MANAGER_NOT_AVAILABLE",{validationError:true})}return permissionManager.isEnabled()},enable:function slothlet_permissions_control_enable(){const permissionManager=slothlet.handlers?.permissionManager;if(!permissionManager?.enable){throw new slothlet.SlothletError("PERMISSION_MANAGER_NOT_AVAILABLE",{validationError:true})}slothlet.handlers.permissionManager.enable()},disable:function slothlet_permissions_control_disable(){const permissionManager=slothlet.handlers?.permissionManager;if(!permissionManager?.disable){throw new slothlet.SlothletError("PERMISSION_MANAGER_NOT_AVAILABLE",{validationError:true})}slothlet.handlers.permissionManager.disable()}}}};if(!config.hook?.enabled&&config.diagnostics!==true){delete namespace.hooks}if(config.diagnostics===true){namespace.diag={describe:(showAll=false)=>{if(showAll){return{...userApi}}return Reflect.ownKeys(userApi)},reference:slothlet.reference||null,context:slothlet.context||{},inspect:()=>{return slothlet.getDiagnostics()},getAPI:()=>{return slothlet.getAPI()},getOwnership:()=>{return slothlet.getOwnership()},owner:{get:apiPath=>{if(slothlet.handlers?.ownership){return slothlet.handlers.ownership.getPathOwnership(apiPath)}return null}},caches:{get:()=>{if(slothlet.handlers?.apiCacheManager){return slothlet.handlers.apiCacheManager.getCacheDiagnostics()}return{totalCaches:0,caches:[]}},getAllModuleIDs:()=>{if(slothlet.handlers?.apiCacheManager){return slothlet.handlers.apiCacheManager.getAllModuleIDs()}return[]},has:moduleID=>{if(slothlet.handlers?.apiCacheManager){return slothlet.handlers.apiCacheManager.has(moduleID)}return false}},SlothletWarning:slothlet.SlothletWarning,hook:slothlet.handlers?.hookManager?{get enabled(){return slothlet.handlers.hookManager.enabled},compilePattern:pattern=>{return slothlet.handlers.hookManager.getCompilePatternForDiagnostics()(pattern)}}:void 0}}return createInternalRouteProxy(namespace,"slothlet")}createShutdownFunction(){const slothlet=this.slothlet;const shutdownFunction={shutdown:async()=>{if(slothlet.userHooks?.shutdown&&typeof slothlet.userHooks.shutdown==="function"){await slothlet.userHooks.shutdown()}return slothlet.shutdown()}}.shutdown;return shutdownFunction}createRunFunction(){const slothlet=this.slothlet;const scopeFunc=this.createScopeFunction();const runFunction={run:async(contextData,callback,...args)=>{if(slothlet.config.scope===false){throw new slothlet.SlothletError("SCOPE_DISABLED",{},null,{validationError:true})}if(!contextData||typeof contextData!=="object"){throw new slothlet.SlothletError("SCOPE_INVALID_CONTEXT",{received:typeof contextData},null,{validationError:true})}if(typeof callback!=="function"){throw new slothlet.SlothletError("SCOPE_INVALID_CALLBACK",{received:typeof callback},null,{validationError:true})}return scopeFunc({context:contextData,fn:callback,args,merge:slothlet.config.scope?.merge||"shallow",isolation:slothlet.config.scope?.isolation||"partial"})}}.run;return runFunction}createScopeFunction(){const slothlet=this.slothlet;const scopeFunction={scope:async options=>{if(slothlet.config.scope===false){throw new slothlet.SlothletError("SCOPE_DISABLED",{},null,{validationError:true})}if(!options||typeof options!=="object"){throw new slothlet.SlothletError("SCOPE_INVALID_OPTIONS",{received:typeof options},null,{validationError:true})}if(!options.fn||typeof options.fn!=="function"){throw new slothlet.SlothletError("SCOPE_INVALID_FN",{received:typeof options?.fn},null,{validationError:true})}if(!options.context||typeof options.context!=="object"){throw new slothlet.SlothletError("SCOPE_INVALID_CONTEXT_OBJECT",{received:typeof options?.context},null,{validationError:true})}const{context:contextData,fn,args=[],merge="shallow",isolation}=options;if(merge!=="shallow"&&merge!=="deep"){throw new slothlet.SlothletError("SCOPE_INVALID_MERGE_STRATEGY",{merge},null,{validationError:true})}const isolationMode=isolation||slothlet.config.scope?.isolation||"partial";if(isolationMode!=="partial"&&isolationMode!=="full"){throw new slothlet.SlothletError("SCOPE_INVALID_ISOLATION_MODE",{isolationMode},null,{validationError:true})}const contextManager=slothlet.contextManager;if(!contextManager){throw new slothlet.SlothletError("NO_CONTEXT_MANAGER",{validationError:true})}const{utilities}=slothlet.helpers;if(contextManager.constructor.name==="LiveContextManager"){let currentStore=null;const currentID=contextManager.currentInstanceID;if(currentID){const activeStore=contextManager.instances.get(currentID);const isOurContext=currentID===slothlet.instanceID||activeStore?.parentInstanceID===slothlet.instanceID||currentID.startsWith(slothlet.instanceID+"__run_");if(isOurContext){currentStore=activeStore}}if(!currentStore){currentStore=contextManager.instances.get(slothlet.instanceID)}if(!currentStore){throw new slothlet.SlothletError("CONTEXT_NOT_FOUND",{instanceID:slothlet.instanceID,availableInstances:[...contextManager.instances.keys()].join(", ")||"none",validationError:true})}let mergedContext;if(merge==="deep"){mergedContext=utilities.deepMerge(currentStore.context,contextData);mergedContext=structuredClone(mergedContext)}else{const clonedParent=structuredClone(currentStore.context);mergedContext={...clonedParent,...contextData}}const childInstanceID=`${slothlet.instanceID}__run_${Date.now()}_${Math.random().toString(36).slice(2,9)}`;const childStore={instanceID:childInstanceID,context:mergedContext,self:isolationMode==="full"?makeCopyOnWriteSelf(currentStore.self):currentStore.self,config:currentStore.config,createdAt:currentStore.createdAt,parentInstanceID:slothlet.instanceID,slothlet:currentStore.slothlet};contextManager.instances.set(childInstanceID,childStore);const previousInstanceID=contextManager.currentInstanceID;try{contextManager.currentInstanceID=childInstanceID;return await fn(...args)}finally{contextManager.currentInstanceID=previousInstanceID;contextManager.instances.delete(childInstanceID)}}if(contextManager.constructor.name==="AsyncContextManager"){let currentStore=null;const activeStore=contextManager.tryGetContext();if(activeStore){const isOurContext=activeStore.instanceID===slothlet.instanceID||activeStore.parentInstanceID===slothlet.instanceID||activeStore.instanceID.startsWith(slothlet.instanceID+"__run_");if(isOurContext){currentStore=activeStore}}if(!currentStore){const baseStore=contextManager.instances.get(slothlet.instanceID);if(!baseStore){throw new slothlet.SlothletError("CONTEXT_NOT_FOUND",{instanceID:slothlet.instanceID,availableInstances:[...contextManager.instances.keys()].join(", ")||"none",validationError:true})}currentStore=baseStore}let mergedContext;if(merge==="deep"){mergedContext=utilities.deepMerge(currentStore.context,contextData);mergedContext=structuredClone(mergedContext)}else{const clonedParent=structuredClone(currentStore.context);mergedContext={...clonedParent,...contextData}}const childInstanceID=`${slothlet.instanceID}__run_${Date.now()}_${Math.random().toString(36).slice(2,9)}`;const childStore={instanceID:childInstanceID,context:mergedContext,self:isolationMode==="full"?makeCopyOnWriteSelf(currentStore.self):currentStore.self,config:currentStore.config,createdAt:currentStore.createdAt,parentInstanceID:slothlet.instanceID,slothlet:currentStore.slothlet};contextManager.instances.set(childInstanceID,childStore);try{return await contextManager.als.run(childStore,async()=>{return await fn(...args)})}finally{contextManager.instances.delete(childInstanceID)}}throw new slothlet.SlothletError("UNSUPPORTED_CONTEXT_MANAGER",{manager:contextManager.constructor.name,validationError:true})}}.scope;return scopeFunction}createDestroyFunction(api){const slothlet=this.slothlet;const destroyFunction={destroy:async()=>{if(slothlet.userHooks?.destroy&&typeof slothlet.userHooks.destroy==="function"){await slothlet.userHooks.destroy()}if(api&&typeof api.shutdown==="function"){await api.shutdown()}else{await slothlet.shutdown()}slothlet.isDestroyed=true;const objectsToClear=[api,slothlet.api].filter(obj=>obj&&typeof obj==="object");for(const obj of objectsToClear){const keys=Object.keys(obj);for(const key of keys){try{delete obj[key]}catch(_){}}}slothlet.api=null}}.destroy;return destroyFunction}attachBuiltins(userApi,builtins){Object.defineProperty(userApi,"slothlet",{value:builtins.slothlet,enumerable:true,writable:false,configurable:true});Object.defineProperty(userApi,"shutdown",{value:builtins.shutdown,enumerable:true,writable:false,configurable:true});if(builtins.destroy!==null){Object.defineProperty(userApi,"destroy",{value:builtins.destroy,enumerable:true,writable:false,configurable:true})}}}export{ApiBuilder};
|
|
17
|
+
import{AsyncResource}from"node:async_hooks";import{ComponentBase}from"@cldmv/slothlet/factories/component-base";import{TYPE_STATES}from"@cldmv/slothlet/handlers/unified-wrapper";import{getLanguage,initI18n,setLanguage,t,translate}from"@cldmv/slothlet/i18n";function _resolvePathOrModuleId(slothlet,pathOrModuleId){const history=slothlet.handlers?.apiManager?.state?.addHistory;if(history){let match=null;for(let i=history.length-1;i>=0;i--){const entry=history[i];if(entry?.moduleID===pathOrModuleId){match=entry;break}}if(match)return match.apiPath}return pathOrModuleId}function makeCopyOnWriteSelf(parentSelf){const overlay=new Map;const childViews=new Map;return new Proxy({},{get(_t,prop){if(overlay.has(prop))return overlay.get(prop);const real=parentSelf[prop];if(real!==null&&typeof real==="object"){let view=childViews.get(prop);if(view===void 0){view=makeCopyOnWriteSelf(real);childViews.set(prop,view)}return view}return real},set(_t,prop,value){overlay.set(prop,value);childViews.delete(prop);return true},has(_t,prop){return overlay.has(prop)||prop in parentSelf},deleteProperty(_t,prop){overlay.delete(prop);childViews.delete(prop);return true},ownKeys(){const keys=new Set(Reflect.ownKeys(parentSelf));for(const k of overlay.keys())keys.add(k);return[...keys]},getOwnPropertyDescriptor(_t,prop){if(overlay.has(prop)){return{value:overlay.get(prop),writable:true,enumerable:true,configurable:true}}const desc=Reflect.getOwnPropertyDescriptor(parentSelf,prop);return desc?{...desc,configurable:true}:void 0}})}class ApiBuilder extends ComponentBase{static slothletProperty="apiBuilder";constructor(slothlet){super(slothlet)}async buildFinalAPI(userApi){this.slothlet.debug("api",{key:"DEBUG_MODE_BUILD_FINAL_API_CALLED",diagnostics:this.____config.diagnostics,userApiKeys:Object.keys(userApi)});if(this.slothlet._ownBuiltins){for(const[key,ref]of Object.entries(this.slothlet._ownBuiltins)){if(ref&&Object.prototype.hasOwnProperty.call(userApi,key)&&userApi[key]===ref){try{delete userApi[key]}catch(_){}}}}this.slothlet.userHooks={shutdown:typeof userApi.shutdown==="function"?userApi.shutdown:null,destroy:typeof userApi.destroy==="function"?userApi.destroy:null};if(userApi.slothlet){new this.SlothletWarning("WARNING_RESERVED_PROPERTY_CONFLICT",{properties:"slothlet"})}const slothletNamespace=await this.createSlothletNamespace(userApi);this.slothlet.debug("api",{key:"DEBUG_MODE_SLOTHLET_NAMESPACE_CREATED",namespaceKeys:Object.keys(slothletNamespace),hasDiag:!!slothletNamespace.diag});const shutdownFn=this.createShutdownFunction();this.attachBuiltins(userApi,{slothlet:slothletNamespace,shutdown:shutdownFn,destroy:null});this.slothlet.debug("api",{key:"DEBUG_MODE_BUILT_INS_ATTACHED",userApiKeys:Object.keys(userApi),hasSlothlet:!!userApi.slothlet,hasDiag:!!userApi.slothlet?.diag});const destroyWithApi=this.createDestroyFunction(userApi);Object.defineProperty(userApi,"destroy",{value:destroyWithApi,enumerable:true,writable:false,configurable:true});this.slothlet._ownBuiltins={shutdown:shutdownFn,slothlet:slothletNamespace,destroy:destroyWithApi};return userApi}async createSlothletNamespace(userApi){const slothlet=this.slothlet;const config=this.____config;const enforceInternalPermission=targetPath=>{const ctx=slothlet.contextManager?.tryGetContext?.();const callerWrapper=ctx?.currentWrapper;if(!callerWrapper)return;const permissionManager=slothlet.handlers?.permissionManager;if(!permissionManager?.enforceAccess){throw new slothlet.SlothletError("PERMISSION_MANAGER_NOT_AVAILABLE",{validationError:true})}const callerPath=callerWrapper.____slothletInternal?.apiPath??"";const callerFilePath=callerWrapper.____slothletInternal?.filePath??null;const runtimeContext=ctx?.context??null;if(!permissionManager.enforceAccess(callerPath,targetPath,callerFilePath,null,runtimeContext)){throw new slothlet.SlothletError("PERMISSION_DENIED",{caller:callerPath,target:targetPath})}};const canTraverseInternalNamespace=targetPath=>{const ctx=slothlet.contextManager?.tryGetContext?.();const callerWrapper=ctx?.currentWrapper;if(!callerWrapper)return false;const permissionManager=slothlet.handlers?.permissionManager;if(!permissionManager?.getRulesForCaller||!permissionManager?.checkAccess){return false}const callerPath=callerWrapper.____slothletInternal?.apiPath??"";const callerFilePath=callerWrapper.____slothletInternal?.filePath??null;const runtimeContext=ctx?.context??null;const callerRules=permissionManager.getRulesForCaller(callerPath);const conditionMatches=condition=>typeof permissionManager.matchesCondition==="function"?permissionManager.matchesCondition(condition,runtimeContext):false;const prefix=`${targetPath}.`;for(const rule of callerRules){if(!rule||rule.effect!=="allow"||typeof rule.target!=="string")continue;const couldMatchDescendant=rule.target.startsWith(prefix)||rule.target==="**"||rule.target==="*";if(!couldMatchDescendant)continue;if(rule.target.startsWith(prefix)&&conditionMatches(rule.condition)){return true}const probePaths=[`${targetPath}.__probe__`];if(rule.target.startsWith(prefix)){const suffix=rule.target.slice(prefix.length);const firstSegment=suffix.split(".")[0];if(firstSegment&&!/[*!?{}]/u.test(firstSegment)){probePaths.unshift(`${targetPath}.${firstSegment}`);probePaths.push(`${targetPath}.${firstSegment}.__probe__`)}}for(const probePath of probePaths){if(permissionManager.checkAccess(callerPath,probePath,callerFilePath,null,runtimeContext,{useCache:false})){return true}}}return false};const createInternalRouteProxy=(value,routePath,seen=new WeakMap)=>{if(!value||typeof value!=="object"&&typeof value!=="function")return value;const isMetaProperty=prop=>prop==="__proto__"||prop==="prototype"||prop==="constructor"||prop==="caller"||prop==="arguments";let routeCache=seen.get(value);if(!routeCache){routeCache=new Map;seen.set(value,routeCache)}if(routeCache.has(routePath)){return routeCache.get(routePath)}const proxy=new Proxy(value,{get(target,prop,receiver){if(typeof prop!=="string"){const result2=Reflect.get(target,prop,receiver);return createInternalRouteProxy(result2,routePath,seen)}const childRoutePath=`${routePath}.${prop}`;let deniedError=null;try{enforceInternalPermission(childRoutePath)}catch(error){deniedError=error}if(deniedError){if(canTraverseInternalNamespace(childRoutePath)){const result2=Reflect.get(target,prop,receiver);if(result2&&(typeof result2==="object"||typeof result2==="function")){return createInternalRouteProxy(result2,childRoutePath,seen)}}throw deniedError}const result=Reflect.get(target,prop,receiver);if(isMetaProperty(prop)){return result}const descriptor=Object.getOwnPropertyDescriptor(target,prop);if(descriptor&&"value"in descriptor&&descriptor.configurable===false&&descriptor.writable===false){return descriptor.value}return createInternalRouteProxy(result,childRoutePath,seen)},getOwnPropertyDescriptor(target,prop){const descriptor=Reflect.getOwnPropertyDescriptor(target,prop);if(!descriptor)return void 0;if(typeof prop!=="string"){return descriptor}const childRoutePath=`${routePath}.${prop}`;if(isMetaProperty(prop)){enforceInternalPermission(childRoutePath);return descriptor}if("get"in descriptor||"set"in descriptor){enforceInternalPermission(childRoutePath);if(descriptor.configurable===true){return{...descriptor,get:typeof descriptor.get==="function"?function slothlet_internal_descriptor_getter(...args){enforceInternalPermission(childRoutePath);return Reflect.apply(descriptor.get,this,args)}:descriptor.get,set:typeof descriptor.set==="function"?function slothlet_internal_descriptor_setter(...args){enforceInternalPermission(childRoutePath);return Reflect.apply(descriptor.set,this,args)}:descriptor.set}}return descriptor}if(!("value"in descriptor)){return descriptor}const descriptorValue=descriptor.value;if(descriptor.configurable===false&&descriptor.writable===false){enforceInternalPermission(childRoutePath);return descriptor}if(!descriptorValue||typeof descriptorValue!=="object"&&typeof descriptorValue!=="function"||typeof descriptorValue==="function"){enforceInternalPermission(childRoutePath);if(typeof descriptorValue==="function"&&descriptor.configurable===true){return{...descriptor,value:createInternalRouteProxy(descriptorValue,childRoutePath,seen)}}return descriptor}return{...descriptor,value:createInternalRouteProxy(descriptorValue,childRoutePath,seen)}},set(target,prop,newValue,receiver){if(typeof prop!=="string"){return Reflect.set(target,prop,newValue,receiver)}const childRoutePath=`${routePath}.${prop}`;enforceInternalPermission(childRoutePath);return Reflect.set(target,prop,newValue,receiver)},defineProperty(target,prop,descriptor){if(typeof prop!=="string"){return Reflect.defineProperty(target,prop,descriptor)}const childRoutePath=`${routePath}.${prop}`;enforceInternalPermission(childRoutePath);return Reflect.defineProperty(target,prop,descriptor)},deleteProperty(target,prop){if(typeof prop!=="string"){return Reflect.deleteProperty(target,prop)}const childRoutePath=`${routePath}.${prop}`;enforceInternalPermission(childRoutePath);return Reflect.deleteProperty(target,prop)},ownKeys(target){return Reflect.ownKeys(target)},apply(target,thisArg,argArray){enforceInternalPermission(routePath);return Reflect.apply(target,thisArg,argArray)},construct(target,argArray,newTarget){enforceInternalPermission(routePath);return Reflect.construct(target,argArray,newTarget)}});routeCache.set(routePath,proxy);return proxy};let version="unknown";try{const pkgPath=new URL("../../../package.json",import.meta.url);const{readFile}=await import("node:fs/promises");const pkgContent=await readFile(pkgPath,"utf-8");const pkg=JSON.parse(pkgContent);version=pkg.version||"unknown"}catch{}const namespace={i18n:{setLanguage,getLanguage,translate,t,initI18n},version,instanceID:slothlet.instanceID,types:TYPE_STATES,api:{add:async function slothlet_api_add(apiPath,folderPath,options={},versionConfig=null){if(!config.api?.mutations?.add){throw new slothlet.SlothletError("INVALID_CONFIG_MUTATIONS_DISABLED",{operation:"api.add",validationError:true})}const{recordHistory:____recordHistory,collisionMode:____collisionMode,mutateExisting:____mutateExisting,...filteredOptions}=options;return slothlet.handlers.apiManager.addApiComponent({apiPath,folderPath,options:filteredOptions,versionConfig:versionConfig||null})},remove:async function slothlet_api_remove(pathOrModuleId){if(!config.api?.mutations?.remove){throw new slothlet.SlothletError("INVALID_CONFIG_MUTATIONS_DISABLED",{operation:"api.remove",validationError:true})}if(typeof pathOrModuleId!=="string"){throw new slothlet.SlothletError("INVALID_ARGUMENT",{argument:"pathOrModuleId",expected:"string",received:typeof pathOrModuleId,validationError:true})}return slothlet.handlers.apiManager.removeApiComponent(pathOrModuleId)},reload:async function slothlet_api_reload(pathOrModuleId,options){if(!config.api?.mutations?.reload){throw new slothlet.SlothletError("INVALID_CONFIG_MUTATIONS_DISABLED",{operation:"api.reload",validationError:true})}if(pathOrModuleId==null||pathOrModuleId===""||pathOrModuleId==="."){return slothlet.handlers.apiManager.reloadApiComponent({apiPath:".",options})}if(typeof pathOrModuleId!=="string"){throw new slothlet.SlothletError("INVALID_ARGUMENT",{argument:"pathOrModuleId",expected:"string, null, undefined, or '.'",received:typeof pathOrModuleId,validationError:true})}const isModuleId=slothlet.handlers.apiManager.state.addHistory.some(entry=>entry.moduleID===pathOrModuleId);if(isModuleId){return slothlet.handlers.apiManager.reloadApiComponent({moduleID:pathOrModuleId,options})}const normalizedPath=slothlet.handlers.apiManager.normalizeApiPath(pathOrModuleId).apiPath;const pathParts=normalizedPath.split(".");let current=slothlet.api;for(const part of pathParts){if(!current||typeof current!=="object"&&typeof current!=="function"){throw new slothlet.SlothletError("INVALID_API_PATH",{apiPath:pathOrModuleId,validationError:true})}current=current[part]}if(current===void 0){throw new slothlet.SlothletError("INVALID_API_PATH",{apiPath:pathOrModuleId,validationError:true})}return slothlet.handlers.apiManager.reloadApiComponent({apiPath:normalizedPath,options})}},sanitize:function slothlet_sanitize(str){if(typeof str!=="string"){throw new slothlet.SlothletError("INVALID_ARGUMENT",{argument:"str",expected:"string",received:typeof str,validationError:true})}return slothlet.helpers.sanitize.sanitizePropertyName(str,slothlet.config.sanitize||{})},lockCaller:function slothlet_lockCaller(fn){if(typeof fn!=="function"){throw new slothlet.SlothletError("INVALID_ARGUMENT",{argument:"fn",expected:"function",received:typeof fn,validationError:true})}const capturedWrapper=slothlet.contextManager?.tryGetContext?.()?.currentWrapper??null;if(!capturedWrapper)return fn;const locked=function slothlet_lockedCaller(...args){return slothlet.contextManager.runInContext(slothlet.instanceID,fn,this,args,capturedWrapper,true)};locked._slothletOriginal=fn;return locked},bind:function slothlet_bind(fn){if(typeof fn!=="function"){throw new slothlet.SlothletError("INVALID_ARGUMENT",{argument:"fn",expected:"function",received:typeof fn,validationError:true})}return AsyncResource.bind(fn,"slothlet-bound")},context:{get:key=>{if(slothlet.contextManager.constructor.name==="LiveContextManager"){const currentID=slothlet.contextManager.currentInstanceID;if(currentID){const activeStore=slothlet.contextManager.instances.get(currentID);const isOurInstance=currentID===slothlet.instanceID||currentID?.startsWith(slothlet.instanceID+"__run_")||activeStore?.parentInstanceID===slothlet.instanceID;if(isOurInstance&&activeStore){return key?activeStore.context[key]:{...activeStore.context}}}const store=slothlet.contextManager.instances.get(slothlet.instanceID);if(!store){const baseContext2=slothlet.context||{};return key?baseContext2[key]:{...baseContext2}}return key?store.context[key]:{...store.context}}if(slothlet.contextManager.constructor.name==="AsyncContextManager"){let currentStore=slothlet.contextManager.tryGetContext();if(!currentStore){const baseStore2=slothlet.contextManager.instances.get(slothlet.instanceID);const baseContext3=baseStore2?.context||{};return key?baseContext3[key]:{...baseContext3}}const isOurInstance=currentStore.instanceID===slothlet.instanceID||currentStore.parentInstanceID===slothlet.instanceID||currentStore.instanceID.startsWith(slothlet.instanceID+"__run_");if(isOurInstance){return key?currentStore.context[key]:{...currentStore.context}}const baseStore=slothlet.contextManager.instances.get(slothlet.instanceID);const baseContext2=baseStore?.context||{};return key?baseContext2[key]:{...baseContext2}}const baseContext=slothlet.context||{};return key?baseContext[key]:{...baseContext}},diagnostics:()=>{if(!slothlet.config?.diagnostics)return void 0;const managerType=slothlet.contextManager.constructor.name;const result={instanceID:slothlet.instanceID,managerType,instancesMapSize:slothlet.contextManager.instances.size,instancesMapKeys:Array.from(slothlet.contextManager.instances.keys()),baseContext:slothlet.context};const store=slothlet.contextManager.instances.get(slothlet.instanceID);result.storeFromInstancesMap=store?{instanceID:store.instanceID,context:store.context,createdAt:store.createdAt}:null;if(managerType==="AsyncContextManager"){try{const currentCtx=slothlet.contextManager.tryGetContext();result.currentALSContext=currentCtx?{instanceID:currentCtx.instanceID,context:currentCtx.context,hasParent:!!currentCtx.parentContext,parentInstanceID:currentCtx.parentInstanceID}:null}catch(____error){result.currentALSContext=null}}if(managerType==="LiveContextManager"){result.currentInstanceID=slothlet.contextManager.currentInstanceID}return result},run:this.createRunFunction(),scope:this.createScopeFunction()},hook:{on:function slothlet_hook_on(typePattern,handler,options={}){if(!slothlet.handlers?.hookManager){throw new slothlet.SlothletError("HOOKS_NOT_INITIALIZED",{validationError:true})}return slothlet.handlers.hookManager.on(typePattern,handler,options)},remove:function slothlet_hook_remove(filter={}){if(!slothlet.handlers?.hookManager){throw new slothlet.SlothletError("HOOKS_NOT_INITIALIZED",{validationError:true})}return slothlet.handlers.hookManager.remove(filter)},clear:function slothlet_hook_clear(filter={}){return this.remove(filter)},off:function slothlet_hook_off(idOrFilter){if(!slothlet.handlers?.hookManager){throw new slothlet.SlothletError("HOOKS_NOT_INITIALIZED",{validationError:true})}const filter=typeof idOrFilter==="string"?{id:idOrFilter}:idOrFilter;return slothlet.handlers.hookManager.remove(filter)},enable:function slothlet_hook_enable(filter={}){if(!slothlet.handlers?.hookManager){throw new slothlet.SlothletError("HOOKS_NOT_INITIALIZED",{validationError:true})}return slothlet.handlers.hookManager.enable(filter)},disable:function slothlet_hook_disable(filter={}){if(!slothlet.handlers?.hookManager){throw new slothlet.SlothletError("HOOKS_NOT_INITIALIZED",{validationError:true})}return slothlet.handlers.hookManager.disable(filter)},list:function slothlet_hook_list(filter={}){if(!slothlet.handlers?.hookManager){throw new slothlet.SlothletError("HOOKS_NOT_INITIALIZED",{validationError:true})}return slothlet.handlers.hookManager.list(filter)}},metadata:{setGlobal:function slothlet_metadata_setGlobal(keyOrObj,value){if(!slothlet.handlers?.metadata){throw new slothlet.SlothletError("METADATA_NOT_AVAILABLE",{handlersKeys:slothlet.handlers?Object.keys(slothlet.handlers).join(", "):"undefined",validationError:true})}const validateGlobalMetadataKeyPath=keyPath=>{const blocked=new Set(["__proto__","prototype","constructor"]);if(typeof keyPath!=="string"||keyPath.length===0){throw new slothlet.SlothletError("INVALID_METADATA_KEY",{key:keyPath,type:typeof keyPath,expected:"non-empty string"})}const segments=keyPath.split(".");for(const segment of segments){if(!segment||blocked.has(segment)){throw new slothlet.SlothletError("INVALID_METADATA_KEY",{key:keyPath,type:typeof keyPath,expected:"safe dot-notation key without reserved segments"})}}};const normalizeGlobalMetadataObject=(source,prefix="",ancestors=new WeakSet)=>{if(ancestors.has(source)){throw new slothlet.SlothletError("INVALID_ARGUMENT",{argument:"keyOrObj",expected:"acyclic object",received:"circular reference",validationError:true})}ancestors.add(source);try{const normalized={};for(const[key,nestedValue]of Object.entries(source)){const fullKey=prefix?`${prefix}.${key}`:key;validateGlobalMetadataKeyPath(fullKey);const nestedProto=nestedValue&&typeof nestedValue==="object"?Object.getPrototypeOf(nestedValue):null;const isPlainNested=nestedProto===Object.prototype||nestedProto===null;if(nestedValue&&typeof nestedValue==="object"&&!Array.isArray(nestedValue)&&isPlainNested){normalized[key]=normalizeGlobalMetadataObject(nestedValue,fullKey,ancestors);continue}normalized[key]=nestedValue}return normalized}finally{ancestors.delete(source)}};if(keyOrObj&&typeof keyOrObj==="object"&&!Array.isArray(keyOrObj)){const normalizedMetadata=normalizeGlobalMetadataObject(keyOrObj);for(const[key,nestedValue]of Object.entries(normalizedMetadata)){slothlet.handlers.metadata.setGlobalMetadata(key,nestedValue)}return}if(typeof keyOrObj!=="string"){throw new slothlet.SlothletError("INVALID_ARGUMENT",{argument:"keyOrObj",expected:"string or object",received:typeof keyOrObj,validationError:true})}validateGlobalMetadataKeyPath(keyOrObj);return slothlet.handlers.metadata.setGlobalMetadata(keyOrObj,value)},set:function slothlet_metadata_set(fn,key,value){if(!slothlet.handlers?.metadata){throw new slothlet.SlothletError("METADATA_NOT_AVAILABLE",{handlersKeys:slothlet.handlers?Object.keys(slothlet.handlers).join(", "):"undefined",validationError:true})}return slothlet.handlers.metadata.setUserMetadata(fn,key,value)},remove:function slothlet_metadata_remove(fn,key){return slothlet.handlers.metadata.removeUserMetadata(fn,key)},setFor:function slothlet_metadata_setFor(pathOrModuleId,keyOrObj,value){if(!slothlet.handlers?.metadata){throw new slothlet.SlothletError("METADATA_NOT_AVAILABLE",{handlersKeys:slothlet.handlers?Object.keys(slothlet.handlers).join(", "):"undefined",validationError:true})}const resolvedPath=_resolvePathOrModuleId(slothlet,pathOrModuleId);return slothlet.handlers.metadata.setPathMetadata(resolvedPath,keyOrObj,value)},removeFor:function slothlet_metadata_removeFor(pathOrModuleId,key){if(!slothlet.handlers?.metadata)return;const resolvedPath=_resolvePathOrModuleId(slothlet,pathOrModuleId);return slothlet.handlers.metadata.removePathMetadata(resolvedPath,key)},setForVersion:function slothlet_metadata_setForVersion(logicalPath,versionTag,keyOrObj,value){if(!slothlet.handlers?.metadata){throw new slothlet.SlothletError("METADATA_NOT_AVAILABLE",{handlersKeys:slothlet.handlers?Object.keys(slothlet.handlers).join(", "):"undefined",validationError:true})}const info=slothlet.handlers?.versionManager?.list(logicalPath);if(!info||!info.versions?.[versionTag]){throw new slothlet.SlothletError("VERSION_NOT_FOUND",{version:versionTag,apiPath:logicalPath})}const{moduleID}=info.versions[versionTag];const resolvedPath=_resolvePathOrModuleId(slothlet,moduleID);return slothlet.handlers.metadata.setPathMetadata(resolvedPath,keyOrObj,value)},getForVersion:function slothlet_metadata_getForVersion(logicalPath,versionTag){if(!slothlet.handlers?.metadata)return{};const info=slothlet.handlers?.versionManager?.list(logicalPath);if(!info||!info.versions?.[versionTag])return{};const{moduleID}=info.versions[versionTag];const resolvedPath=_resolvePathOrModuleId(slothlet,moduleID);return slothlet.handlers.metadata.getPathMetadata(resolvedPath)}},scope:this.createScopeFunction(),run:this.createRunFunction(),reload:async(options={})=>{if(!config.api?.mutations?.reload){throw new slothlet.SlothletError("INVALID_CONFIG_MUTATIONS_DISABLED",{operation:"reload",validationError:true})}return slothlet.reload(options)},shutdown:async()=>{return slothlet.shutdown()},owner:{get:apiPath=>{if(slothlet.handlers?.ownership){return slothlet.handlers.ownership.getPathOwnership(apiPath)}return null}},materialize:(()=>{const mgr=slothlet.handlers?.materialize;const getMaterializedState=()=>{enforceInternalPermission("slothlet.materialize.materialized");return mgr?.materialized??false};const getMaterializeStats=()=>{enforceInternalPermission("slothlet.materialize.get");return mgr?mgr.get():{total:0,materialized:0,remaining:0,percentage:100}};const waitForMaterialization=async()=>{enforceInternalPermission("slothlet.materialize.wait");if(!mgr)return;return mgr.wait()};if(!mgr){return Object.freeze({get materialized(){return getMaterializedState()},get:getMaterializeStats,wait:waitForMaterialization})}return Object.freeze({get materialized(){return getMaterializedState()},get:getMaterializeStats,wait:waitForMaterialization})})(),lifecycle:(()=>{const handler=slothlet.handlers?.lifecycle;const noop=()=>{};if(!handler)return{on:noop,off:noop};return{on:handler.on.bind(handler),off:handler.off.bind(handler)}})(),env:slothlet.envSnapshot,versioning:{list:function slothlet_version_list(logicalPath){if(!slothlet.handlers?.versionManager)return void 0;return slothlet.handlers.versionManager.list(logicalPath)},setDefault:function slothlet_version_setDefault(logicalPath,versionTag){if(!slothlet.handlers?.versionManager)return;return slothlet.handlers.versionManager.setDefault(logicalPath,versionTag)},unregister:async function slothlet_version_unregister(logicalPath,versionTag){if(!slothlet.handlers?.versionManager)return false;const info=slothlet.handlers.versionManager.list(logicalPath);if(!info||!info.versions?.[versionTag])return false;const{moduleID:versionedModuleID}=info.versions[versionTag];await slothlet.handlers.apiManager.removeApiComponent(versionedModuleID);return true},getVersionMetadata:function slothlet_version_getVersionMetadata(logicalPath,versionTag){if(!slothlet.handlers?.versionManager)return void 0;return slothlet.handlers.versionManager.getVersionMetadataByPath(logicalPath,versionTag)},setVersionMetadata:function slothlet_version_setVersionMetadata(logicalPath,versionTag,patch){if(!slothlet.handlers?.versionManager)return;return slothlet.handlers.versionManager.setVersionMetadataByPath(logicalPath,versionTag,patch)}},permissions:{addRule:function slothlet_permissions_addRule(rule){if(!config.api?.mutations?.permissions){throw new slothlet.SlothletError("INVALID_CONFIG_MUTATIONS_DISABLED",{operation:"api.slothlet.permissions.addRule",validationError:true})}const permissionManager=slothlet.handlers?.permissionManager;if(!permissionManager?.addRule){throw new slothlet.SlothletError("PERMISSION_MANAGER_NOT_AVAILABLE",{validationError:true})}const ruleId=permissionManager.addRule(rule,null);if(slothlet.handlers?.apiManager?.state?.operationHistory){slothlet.handlers.apiManager.state.operationHistory.push({type:"addPermissionRule",rule,ownerModuleID:null,ruleId,timestamp:Date.now()})}return ruleId},removeRule:function slothlet_permissions_removeRule(ruleId){if(!config.api?.mutations?.permissions){throw new slothlet.SlothletError("INVALID_CONFIG_MUTATIONS_DISABLED",{operation:"api.slothlet.permissions.removeRule",validationError:true})}const permissionManager=slothlet.handlers?.permissionManager;if(!permissionManager?.removeRule){throw new slothlet.SlothletError("PERMISSION_MANAGER_NOT_AVAILABLE",{validationError:true})}const ctx=slothlet.contextManager?.tryGetContext?.();const currentWrapper=ctx?.currentWrapper;const callerModuleID=currentWrapper?.____slothletInternal?.moduleID??null;const result=slothlet.handlers.permissionManager.removeRule(ruleId,callerModuleID);if(result&&slothlet.handlers?.apiManager?.state?.operationHistory){slothlet.handlers.apiManager.state.operationHistory.push({type:"removePermissionRule",ruleId,callerModuleID,timestamp:Date.now()})}return result},self:{access:function slothlet_permissions_self_access(target){const permissionManager=slothlet.handlers?.permissionManager;if(!permissionManager?.checkAccess){throw new slothlet.SlothletError("PERMISSION_MANAGER_NOT_AVAILABLE",{validationError:true})}const ctx=slothlet.contextManager?.tryGetContext?.();const currentWrapper=ctx?.currentWrapper;const callerPath=currentWrapper?.____slothletInternal?.apiPath??"";const callerFilePath=currentWrapper?.____slothletInternal?.filePath??null;const runtimeContext=ctx?.context??null;return slothlet.handlers.permissionManager.checkAccess(callerPath,target,callerFilePath,null,runtimeContext)},rules:function slothlet_permissions_self_rules(){const permissionManager=slothlet.handlers?.permissionManager;if(!permissionManager?.getRulesForCaller){throw new slothlet.SlothletError("PERMISSION_MANAGER_NOT_AVAILABLE",{validationError:true})}const currentWrapper=slothlet.contextManager?.tryGetContext?.()?.currentWrapper;const callerPath=currentWrapper?.____slothletInternal?.apiPath??"";return slothlet.handlers.permissionManager.getRulesForCaller(callerPath)}},global:{checkAccess:function slothlet_permissions_global_checkAccess(caller,target){const permissionManager=slothlet.handlers?.permissionManager;if(!permissionManager?.checkAccess){throw new slothlet.SlothletError("PERMISSION_MANAGER_NOT_AVAILABLE",{validationError:true})}const runtimeContext=slothlet.contextManager?.tryGetContext?.()?.context??null;return slothlet.handlers.permissionManager.checkAccess(caller,target,null,null,runtimeContext)},rulesForPath:function slothlet_permissions_global_rulesForPath(path){const permissionManager=slothlet.handlers?.permissionManager;if(!permissionManager?.getRulesForPath){throw new slothlet.SlothletError("PERMISSION_MANAGER_NOT_AVAILABLE",{validationError:true})}return slothlet.handlers.permissionManager.getRulesForPath(path)},rulesByModule:function slothlet_permissions_global_rulesByModule(moduleID){const permissionManager=slothlet.handlers?.permissionManager;if(!permissionManager?.getRulesByModule){throw new slothlet.SlothletError("PERMISSION_MANAGER_NOT_AVAILABLE",{validationError:true})}return slothlet.handlers.permissionManager.getRulesByModule(moduleID)}},control:{get enabled(){const permissionManager=slothlet.handlers?.permissionManager;if(!permissionManager?.isEnabled){throw new slothlet.SlothletError("PERMISSION_MANAGER_NOT_AVAILABLE",{validationError:true})}return permissionManager.isEnabled()},enable:function slothlet_permissions_control_enable(){const permissionManager=slothlet.handlers?.permissionManager;if(!permissionManager?.enable){throw new slothlet.SlothletError("PERMISSION_MANAGER_NOT_AVAILABLE",{validationError:true})}slothlet.handlers.permissionManager.enable()},disable:function slothlet_permissions_control_disable(){const permissionManager=slothlet.handlers?.permissionManager;if(!permissionManager?.disable){throw new slothlet.SlothletError("PERMISSION_MANAGER_NOT_AVAILABLE",{validationError:true})}slothlet.handlers.permissionManager.disable()}}}};if(!config.hook?.enabled&&config.diagnostics!==true){delete namespace.hooks}if(config.diagnostics===true){namespace.diag={describe:(showAll=false)=>{if(showAll){return{...userApi}}return Reflect.ownKeys(userApi)},reference:slothlet.reference||null,context:slothlet.context||{},inspect:()=>{return slothlet.getDiagnostics()},getAPI:()=>{return slothlet.getAPI()},getOwnership:()=>{return slothlet.getOwnership()},owner:{get:apiPath=>{if(slothlet.handlers?.ownership){return slothlet.handlers.ownership.getPathOwnership(apiPath)}return null}},caches:{get:()=>{if(slothlet.handlers?.apiCacheManager){return slothlet.handlers.apiCacheManager.getCacheDiagnostics()}return{totalCaches:0,caches:[]}},getAllModuleIDs:()=>{if(slothlet.handlers?.apiCacheManager){return slothlet.handlers.apiCacheManager.getAllModuleIDs()}return[]},has:moduleID=>{if(slothlet.handlers?.apiCacheManager){return slothlet.handlers.apiCacheManager.has(moduleID)}return false}},SlothletWarning:slothlet.SlothletWarning,hook:slothlet.handlers?.hookManager?{get enabled(){return slothlet.handlers.hookManager.enabled},compilePattern:pattern=>{return slothlet.handlers.hookManager.getCompilePatternForDiagnostics()(pattern)}}:void 0}}return createInternalRouteProxy(namespace,"slothlet")}createShutdownFunction(){const slothlet=this.slothlet;const shutdownFunction={shutdown:async()=>{if(slothlet.userHooks?.shutdown&&typeof slothlet.userHooks.shutdown==="function"){await slothlet.userHooks.shutdown()}return slothlet.shutdown()}}.shutdown;return shutdownFunction}createRunFunction(){const slothlet=this.slothlet;const scopeFunc=this.createScopeFunction();const runFunction={run:async(contextData,callback,...args)=>{if(slothlet.config.scope===false){throw new slothlet.SlothletError("SCOPE_DISABLED",{},null,{validationError:true})}if(!contextData||typeof contextData!=="object"){throw new slothlet.SlothletError("SCOPE_INVALID_CONTEXT",{received:typeof contextData},null,{validationError:true})}if(typeof callback!=="function"){throw new slothlet.SlothletError("SCOPE_INVALID_CALLBACK",{received:typeof callback},null,{validationError:true})}return scopeFunc({context:contextData,fn:callback,args,merge:slothlet.config.scope?.merge||"shallow",isolation:slothlet.config.scope?.isolation||"partial"})}}.run;return runFunction}createScopeFunction(){const slothlet=this.slothlet;const scopeFunction={scope:async options=>{if(slothlet.config.scope===false){throw new slothlet.SlothletError("SCOPE_DISABLED",{},null,{validationError:true})}if(!options||typeof options!=="object"){throw new slothlet.SlothletError("SCOPE_INVALID_OPTIONS",{received:typeof options},null,{validationError:true})}if(!options.fn||typeof options.fn!=="function"){throw new slothlet.SlothletError("SCOPE_INVALID_FN",{received:typeof options?.fn},null,{validationError:true})}if(!options.context||typeof options.context!=="object"){throw new slothlet.SlothletError("SCOPE_INVALID_CONTEXT_OBJECT",{received:typeof options?.context},null,{validationError:true})}const{context:contextData,fn,args=[],merge="shallow",isolation}=options;if(merge!=="shallow"&&merge!=="deep"){throw new slothlet.SlothletError("SCOPE_INVALID_MERGE_STRATEGY",{merge},null,{validationError:true})}const isolationMode=isolation||slothlet.config.scope?.isolation||"partial";if(isolationMode!=="partial"&&isolationMode!=="full"){throw new slothlet.SlothletError("SCOPE_INVALID_ISOLATION_MODE",{isolationMode},null,{validationError:true})}const contextManager=slothlet.contextManager;if(!contextManager){throw new slothlet.SlothletError("NO_CONTEXT_MANAGER",{validationError:true})}const{utilities}=slothlet.helpers;if(contextManager.constructor.name==="LiveContextManager"){let currentStore=null;const currentID=contextManager.currentInstanceID;if(currentID){const activeStore=contextManager.instances.get(currentID);const isOurContext=currentID===slothlet.instanceID||activeStore?.parentInstanceID===slothlet.instanceID||currentID.startsWith(slothlet.instanceID+"__run_");if(isOurContext){currentStore=activeStore}}if(!currentStore){currentStore=contextManager.instances.get(slothlet.instanceID)}if(!currentStore){throw new slothlet.SlothletError("CONTEXT_NOT_FOUND",{instanceID:slothlet.instanceID,availableInstances:[...contextManager.instances.keys()].join(", ")||"none",validationError:true})}let mergedContext;if(merge==="deep"){mergedContext=utilities.deepMerge(currentStore.context,contextData);mergedContext=structuredClone(mergedContext)}else{const clonedParent=structuredClone(currentStore.context);mergedContext={...clonedParent,...contextData}}const childInstanceID=`${slothlet.instanceID}__run_${Date.now()}_${Math.random().toString(36).slice(2,9)}`;const childStore={instanceID:childInstanceID,context:mergedContext,self:isolationMode==="full"?makeCopyOnWriteSelf(currentStore.self):currentStore.self,config:currentStore.config,createdAt:currentStore.createdAt,parentInstanceID:slothlet.instanceID,currentWrapper:currentStore.currentWrapper,callerWrapper:currentStore.callerWrapper,slothlet:currentStore.slothlet};contextManager.instances.set(childInstanceID,childStore);const previousInstanceID=contextManager.currentInstanceID;try{contextManager.currentInstanceID=childInstanceID;return await fn(...args)}finally{contextManager.currentInstanceID=previousInstanceID;contextManager.instances.delete(childInstanceID)}}if(contextManager.constructor.name==="AsyncContextManager"){let currentStore=null;const activeStore=contextManager.tryGetContext();if(activeStore){const isOurContext=activeStore.instanceID===slothlet.instanceID||activeStore.parentInstanceID===slothlet.instanceID||activeStore.instanceID.startsWith(slothlet.instanceID+"__run_");if(isOurContext){currentStore=activeStore}}if(!currentStore){const baseStore=contextManager.instances.get(slothlet.instanceID);if(!baseStore){throw new slothlet.SlothletError("CONTEXT_NOT_FOUND",{instanceID:slothlet.instanceID,availableInstances:[...contextManager.instances.keys()].join(", ")||"none",validationError:true})}currentStore=baseStore}let mergedContext;if(merge==="deep"){mergedContext=utilities.deepMerge(currentStore.context,contextData);mergedContext=structuredClone(mergedContext)}else{const clonedParent=structuredClone(currentStore.context);mergedContext={...clonedParent,...contextData}}const childInstanceID=`${slothlet.instanceID}__run_${Date.now()}_${Math.random().toString(36).slice(2,9)}`;const childStore={instanceID:childInstanceID,context:mergedContext,self:isolationMode==="full"?makeCopyOnWriteSelf(currentStore.self):currentStore.self,config:currentStore.config,createdAt:currentStore.createdAt,parentInstanceID:slothlet.instanceID,currentWrapper:currentStore.currentWrapper,callerWrapper:currentStore.callerWrapper,slothlet:currentStore.slothlet};contextManager.instances.set(childInstanceID,childStore);try{return await contextManager.als.run(childStore,async()=>{return await fn(...args)})}finally{contextManager.instances.delete(childInstanceID)}}throw new slothlet.SlothletError("UNSUPPORTED_CONTEXT_MANAGER",{manager:contextManager.constructor.name,validationError:true})}}.scope;return scopeFunction}createDestroyFunction(api){const slothlet=this.slothlet;const destroyFunction={destroy:async()=>{if(slothlet.userHooks?.destroy&&typeof slothlet.userHooks.destroy==="function"){await slothlet.userHooks.destroy()}if(api&&typeof api.shutdown==="function"){await api.shutdown()}else{await slothlet.shutdown()}slothlet.isDestroyed=true;const objectsToClear=[api,slothlet.api].filter(obj=>obj&&typeof obj==="object");for(const obj of objectsToClear){const keys=Object.keys(obj);for(const key of keys){try{delete obj[key]}catch(_){}}}slothlet.api=null}}.destroy;return destroyFunction}attachBuiltins(userApi,builtins){Object.defineProperty(userApi,"slothlet",{value:builtins.slothlet,enumerable:true,writable:false,configurable:true});Object.defineProperty(userApi,"shutdown",{value:builtins.shutdown,enumerable:true,writable:false,configurable:true});if(builtins.destroy!==null){Object.defineProperty(userApi,"destroy",{value:builtins.destroy,enumerable:true,writable:false,configurable:true})}}}export{ApiBuilder};
|
|
@@ -14,4 +14,4 @@
|
|
|
14
14
|
limitations under the License.
|
|
15
15
|
*/
|
|
16
16
|
|
|
17
|
-
import{AsyncLocalStorage}from"node:async_hooks";import{SlothletError}from"@cldmv/slothlet/errors";import{runtime_isClassInstance,runtime_wrapClassInstance}from"@cldmv/slothlet/helpers/class-instance-wrapper";import{setApiContextChecker}from"@cldmv/slothlet/helpers/eventemitter-context";class AsyncContextManager{constructor(){this.als=new AsyncLocalStorage;this.instances=new Map}registerEventEmitterContextChecker(){setApiContextChecker(()=>{const store=this.als.getStore();return store&&store.instanceID?true:false})}initialize(instanceID,config={}){if(this.instances.has(instanceID)){throw new SlothletError("CONTEXT_ALREADY_EXISTS",{instanceID},null,{validationError:true})}const store={instanceID,self:{},context:{},config:{...config},createdAt:Date.now()};this.instances.set(instanceID,store);return store}runInContext(instanceID,fn,thisArg,args,currentWrapper){const activeStore=this.als.getStore();let baseStore;const isActiveOurInstance=activeStore&&(activeStore.instanceID===instanceID||activeStore.parentInstanceID===instanceID);if(isActiveOurInstance){baseStore=activeStore}else{baseStore=this.instances.get(instanceID);if(!baseStore){throw new SlothletError("CONTEXT_NOT_FOUND",{instanceID,availableInstances:Array.from(this.instances.keys())})}}const executionStore={...baseStore};if(currentWrapper){executionStore.callerWrapper=baseStore.currentWrapper;executionStore.currentWrapper=currentWrapper}if(isActiveOurInstance){return this.als.run(executionStore,()=>{try{const result=fn.apply(thisArg,args);if(runtime_isClassInstance(result)){const instanceCache=new WeakMap;return runtime_wrapClassInstance(result,this,instanceID,instanceCache)}return result}catch(error){if(error instanceof SlothletError)throw error;throw new SlothletError("CONTEXT_EXECUTION_FAILED",{instanceID},error)}})}return this.als.run(executionStore,()=>{try{const result=fn.apply(thisArg,args);if(runtime_isClassInstance(result)){const instanceCache=new WeakMap;return runtime_wrapClassInstance(result,this,instanceID,instanceCache)}return result}catch(error){if(error instanceof SlothletError)throw error;throw new SlothletError("CONTEXT_EXECUTION_FAILED",{instanceID},error)}})}getContext(){const store=this.als.getStore();if(!store){throw new SlothletError("NO_ACTIVE_CONTEXT_ASYNC",{},null,{validationError:true})}return store}tryGetContext(){return this.als.getStore()}cleanup(instanceID){const store=this.instances.get(instanceID);if(!store){throw new SlothletError("CONTEXT_NOT_FOUND",{instanceID,availableInstances:Array.from(this.instances.keys()).join(", ")||"none"},null,{validationError:true})}store.self={};store.context={};this.instances.delete(instanceID)}getDiagnostics(){return{type:"async",activeStore:this.als.getStore()?.instanceID||null,instances:Array.from(this.instances.entries()).map(([id,store])=>({id,createdAt:store.createdAt,contextKeys:Object.keys(store.context),selfKeys:Object.keys(store.self)}))}}}const asyncContextManager=new AsyncContextManager;export{AsyncContextManager,asyncContextManager};
|
|
17
|
+
import{AsyncLocalStorage}from"node:async_hooks";import{SlothletError}from"@cldmv/slothlet/errors";import{runtime_isClassInstance,runtime_wrapClassInstance}from"@cldmv/slothlet/helpers/class-instance-wrapper";import{setApiContextChecker}from"@cldmv/slothlet/helpers/eventemitter-context";class AsyncContextManager{constructor(){this.als=new AsyncLocalStorage;this.instances=new Map}registerEventEmitterContextChecker(){setApiContextChecker(()=>{const store=this.als.getStore();return store&&store.instanceID?true:false})}initialize(instanceID,config={}){if(this.instances.has(instanceID)){throw new SlothletError("CONTEXT_ALREADY_EXISTS",{instanceID},null,{validationError:true})}const store={instanceID,self:{},context:{},config:{...config},createdAt:Date.now()};this.instances.set(instanceID,store);return store}runInContext(instanceID,fn,thisArg,args,currentWrapper,rawErrors=false){const activeStore=this.als.getStore();let baseStore;const isActiveOurInstance=activeStore&&(activeStore.instanceID===instanceID||activeStore.parentInstanceID===instanceID);if(isActiveOurInstance){baseStore=activeStore}else{baseStore=this.instances.get(instanceID);if(!baseStore){throw new SlothletError("CONTEXT_NOT_FOUND",{instanceID,availableInstances:Array.from(this.instances.keys())})}}const executionStore={...baseStore};if(currentWrapper){executionStore.callerWrapper=baseStore.currentWrapper;executionStore.currentWrapper=currentWrapper}if(isActiveOurInstance){return this.als.run(executionStore,()=>{try{const result=fn.apply(thisArg,args);if(runtime_isClassInstance(result)){const instanceCache=new WeakMap;return runtime_wrapClassInstance(result,this,instanceID,instanceCache)}return result}catch(error){if(rawErrors||error instanceof SlothletError)throw error;throw new SlothletError("CONTEXT_EXECUTION_FAILED",{instanceID},error)}})}return this.als.run(executionStore,()=>{try{const result=fn.apply(thisArg,args);if(runtime_isClassInstance(result)){const instanceCache=new WeakMap;return runtime_wrapClassInstance(result,this,instanceID,instanceCache)}return result}catch(error){if(rawErrors||error instanceof SlothletError)throw error;throw new SlothletError("CONTEXT_EXECUTION_FAILED",{instanceID},error)}})}getContext(){const store=this.als.getStore();if(!store){throw new SlothletError("NO_ACTIVE_CONTEXT_ASYNC",{},null,{validationError:true})}return store}tryGetContext(){return this.als.getStore()}cleanup(instanceID){const store=this.instances.get(instanceID);if(!store){throw new SlothletError("CONTEXT_NOT_FOUND",{instanceID,availableInstances:Array.from(this.instances.keys()).join(", ")||"none"},null,{validationError:true})}store.self={};store.context={};this.instances.delete(instanceID)}getDiagnostics(){return{type:"async",activeStore:this.als.getStore()?.instanceID||null,instances:Array.from(this.instances.entries()).map(([id,store])=>({id,createdAt:store.createdAt,contextKeys:Object.keys(store.context),selfKeys:Object.keys(store.self)}))}}}const asyncContextManager=new AsyncContextManager;export{AsyncContextManager,asyncContextManager};
|
|
@@ -14,4 +14,4 @@
|
|
|
14
14
|
limitations under the License.
|
|
15
15
|
*/
|
|
16
16
|
|
|
17
|
-
import{SlothletError}from"@cldmv/slothlet/errors";import{setApiContextChecker}from"@cldmv/slothlet/helpers/eventemitter-context";class LiveContextManager{constructor(){this.instances=new Map;this.currentInstanceID=null}registerEventEmitterContextChecker(){setApiContextChecker(()=>{return this.currentInstanceID!==null})}initialize(instanceID,config={}){if(this.instances.has(instanceID)){throw new SlothletError("CONTEXT_ALREADY_EXISTS",{instanceID},null,{validationError:true})}const store={instanceID,self:{},context:{},config:{...config},createdAt:Date.now()};this.instances.set(instanceID,store);if(!this.currentInstanceID){this.currentInstanceID=instanceID}return store}runInContext(instanceID,fn,thisArg,args,currentWrapper){const currentID=this.currentInstanceID;let isAlreadyInContext=false;if(currentID){const currentStore=this.instances.get(currentID);isAlreadyInContext=currentID===instanceID||currentStore?.parentInstanceID===instanceID||currentID.startsWith(instanceID+"__run_")}const targetInstanceID=isAlreadyInContext?currentID:instanceID;const store=this.instances.get(targetInstanceID);if(!store){throw new SlothletError("CONTEXT_NOT_FOUND",{instanceID:targetInstanceID,availableInstances:Array.from(this.instances.keys())})}const previousInstanceID=this.currentInstanceID;const previousWrapper=store.currentWrapper;const previousCallerWrapper=store.callerWrapper;this.currentInstanceID=targetInstanceID;if(currentWrapper){store.callerWrapper=previousWrapper;store.currentWrapper=currentWrapper}try{return fn.apply(thisArg,args)}catch(error){if(error instanceof SlothletError)throw error;throw new SlothletError("CONTEXT_EXECUTION_FAILED",{instanceID},error)}finally{this.currentInstanceID=previousInstanceID;store.currentWrapper=previousWrapper;store.callerWrapper=previousCallerWrapper}}getContext(){if(!this.currentInstanceID){throw new SlothletError("NO_ACTIVE_CONTEXT_LIVE",{},null,{validationError:true})}const store=this.instances.get(this.currentInstanceID);if(!store){throw new SlothletError("CONTEXT_NOT_FOUND",{instanceID:this.currentInstanceID,availableInstances:Array.from(this.instances.keys()).join(", ")||"none"},null,{validationError:true})}return store}tryGetContext(){if(!this.currentInstanceID){return void 0}return this.instances.get(this.currentInstanceID)}cleanup(instanceID){const store=this.instances.get(instanceID);if(!store){throw new SlothletError("CONTEXT_NOT_FOUND",{instanceID,availableInstances:Array.from(this.instances.keys()).join(", ")||"none"},null,{validationError:true})}store.self={};store.context={};this.instances.delete(instanceID);if(this.currentInstanceID===instanceID){this.currentInstanceID=null}}getDiagnostics(){return{type:"live",currentInstanceID:this.currentInstanceID,instances:Array.from(this.instances.entries()).map(([id,store])=>({id,createdAt:store.createdAt,contextKeys:Object.keys(store.context),selfKeys:Object.keys(store.self)}))}}}const liveContextManager=new LiveContextManager;export{LiveContextManager,liveContextManager};
|
|
17
|
+
import{SlothletError}from"@cldmv/slothlet/errors";import{setApiContextChecker}from"@cldmv/slothlet/helpers/eventemitter-context";class LiveContextManager{constructor(){this.instances=new Map;this.currentInstanceID=null}registerEventEmitterContextChecker(){setApiContextChecker(()=>{return this.currentInstanceID!==null})}initialize(instanceID,config={}){if(this.instances.has(instanceID)){throw new SlothletError("CONTEXT_ALREADY_EXISTS",{instanceID},null,{validationError:true})}const store={instanceID,self:{},context:{},config:{...config},createdAt:Date.now()};this.instances.set(instanceID,store);if(!this.currentInstanceID){this.currentInstanceID=instanceID}return store}runInContext(instanceID,fn,thisArg,args,currentWrapper,rawErrors=false){const currentID=this.currentInstanceID;let isAlreadyInContext=false;if(currentID){const currentStore=this.instances.get(currentID);isAlreadyInContext=currentID===instanceID||currentStore?.parentInstanceID===instanceID||currentID.startsWith(instanceID+"__run_")}const targetInstanceID=isAlreadyInContext?currentID:instanceID;const store=this.instances.get(targetInstanceID);if(!store){throw new SlothletError("CONTEXT_NOT_FOUND",{instanceID:targetInstanceID,availableInstances:Array.from(this.instances.keys())})}const previousInstanceID=this.currentInstanceID;const previousWrapper=store.currentWrapper;const previousCallerWrapper=store.callerWrapper;this.currentInstanceID=targetInstanceID;if(currentWrapper){store.callerWrapper=previousWrapper;store.currentWrapper=currentWrapper}try{return fn.apply(thisArg,args)}catch(error){if(rawErrors||error instanceof SlothletError)throw error;throw new SlothletError("CONTEXT_EXECUTION_FAILED",{instanceID},error)}finally{this.currentInstanceID=previousInstanceID;store.currentWrapper=previousWrapper;store.callerWrapper=previousCallerWrapper}}getContext(){if(!this.currentInstanceID){throw new SlothletError("NO_ACTIVE_CONTEXT_LIVE",{},null,{validationError:true})}const store=this.instances.get(this.currentInstanceID);if(!store){throw new SlothletError("CONTEXT_NOT_FOUND",{instanceID:this.currentInstanceID,availableInstances:Array.from(this.instances.keys()).join(", ")||"none"},null,{validationError:true})}return store}tryGetContext(){if(!this.currentInstanceID){return void 0}return this.instances.get(this.currentInstanceID)}cleanup(instanceID){const store=this.instances.get(instanceID);if(!store){throw new SlothletError("CONTEXT_NOT_FOUND",{instanceID,availableInstances:Array.from(this.instances.keys()).join(", ")||"none"},null,{validationError:true})}store.self={};store.context={};this.instances.delete(instanceID);if(this.currentInstanceID===instanceID){this.currentInstanceID=null}}getDiagnostics(){return{type:"live",currentInstanceID:this.currentInstanceID,instances:Array.from(this.instances.entries()).map(([id,store])=>({id,createdAt:store.createdAt,contextKeys:Object.keys(store.context),selfKeys:Object.keys(store.self)}))}}}const liveContextManager=new LiveContextManager;export{LiveContextManager,liveContextManager};
|
|
@@ -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 hook={id,type,pattern,handler,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}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}}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},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";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};
|
|
@@ -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 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.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})}})})}}}[util.inspect.custom](____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.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&&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 cacheKey=propChain.join(".");if(!wrapper.____slothletInternal.waitingProxyCache){wrapper.____slothletInternal.waitingProxyCache=new Map}if(wrapper.____slothletInternal.waitingProxyCache.has(cacheKey)){return wrapper.____slothletInternal.waitingProxyCache.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;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){current=_childW;if(current.____slothletInternal.mode==="lazy"&&!current.____slothletInternal.state.materialized){await current._materialize()}continue}return child}if(current.____slothletInternal.impl&¤t.____slothletInternal.impl[chainProp]!==void 0){return current.____slothletInternal.impl[chainProp]}return void 0}if(current.____slothletInternal.impl&&typeof current.____slothletInternal.impl==="object"&&util.types.isProxy(current.____slothletInternal.impl)){return current.____slothletInternal.impl}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&¤tWrapper){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"&¤tWrapper.____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"&¤t!==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&¤t&&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&¤t.____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&¤t&&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&¤tWrapper){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"&¤tWrapper.____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);wrapper.____slothletInternal.waitingProxyCache.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)=>{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"){return cachedImpl}}if(_cachedWrapper){const cachedWrapper=_cachedWrapper;if(cachedWrapper.____slothletInternal.mode==="lazy"&&!cachedWrapper.____slothletInternal.state.materialized&&!cachedWrapper.____slothletInternal.state.inFlight){cachedWrapper._materialize().catch(()=>{})}}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(()=>{})}}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}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}}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 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 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.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.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&&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 cacheKey=propChain.join(".");if(!wrapper.____slothletInternal.waitingProxyCache){wrapper.____slothletInternal.waitingProxyCache=new Map}if(wrapper.____slothletInternal.waitingProxyCache.has(cacheKey)){return wrapper.____slothletInternal.waitingProxyCache.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;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){current=_childW;if(current.____slothletInternal.mode==="lazy"&&!current.____slothletInternal.state.materialized){await current._materialize()}continue}return child}if(current.____slothletInternal.impl&¤t.____slothletInternal.impl[chainProp]!==void 0){return current.____slothletInternal.impl[chainProp]}return void 0}if(current.____slothletInternal.impl&&typeof current.____slothletInternal.impl==="object"&&util.types.isProxy(current.____slothletInternal.impl)){return current.____slothletInternal.impl}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&¤tWrapper){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"&¤tWrapper.____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"&¤t!==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&¤t&&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&¤t.____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&¤t&&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&¤tWrapper){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"&¤tWrapper.____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);wrapper.____slothletInternal.waitingProxyCache.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)=>{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"){return cachedImpl}}if(_cachedWrapper){const cachedWrapper=_cachedWrapper;if(cachedWrapper.____slothletInternal.mode==="lazy"&&!cachedWrapper.____slothletInternal.state.materialized&&!cachedWrapper.____slothletInternal.state.inFlight){cachedWrapper._materialize().catch(()=>{})}}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(()=>{})}}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}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{EventEmitter}from"node:events";const EXCLUDED_CONSTRUCTORS=new Set([Object,Array,Promise,Date,RegExp,Error]);const EXCLUDED_INSTANCEOF_CLASSES=[ArrayBuffer,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"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};
|
|
@@ -14,4 +14,4 @@
|
|
|
14
14
|
limitations under the License.
|
|
15
15
|
*/
|
|
16
16
|
|
|
17
|
-
import{readdir,stat}from"node:fs/promises";import{join,extname,basename,resolve}from"node:path";import{pathToFileURL}from"node:url";import{createRequire}from"node:module";import{ComponentBase}from"@cldmv/slothlet/factories/component-base";class Loader extends ComponentBase{static slothletProperty="loader";constructor(slothlet){super(slothlet)}async loadModule(filePath,instanceID,moduleID,cacheBust=null){try{if(filePath.endsWith(".cjs")){return this.#loadCJSIsolated(filePath)}const isTypeScript=filePath.endsWith(".ts")||filePath.endsWith(".mts");const typescriptConfig=this.slothlet.config?.typescript;let moduleUrl;if(isTypeScript&&typescriptConfig?.enabled){const mode=typescriptConfig.mode;if(mode==="strict"){if(!typescriptConfig.types?.output){throw new this.SlothletError("TS_STRICT_REQUIRES_OUTPUT",{},null,{validationError:true})}if(!typescriptConfig.types?.interfaceName){throw new this.SlothletError("TS_STRICT_REQUIRES_INTERFACE_NAME",{},null,{validationError:true})}if(!this.slothlet._typesGenerated){const{fork}=await import("child_process");const path=await import("path");const{fileURLToPath}=await import("url");const __dirname=path.dirname(fileURLToPath(import.meta.url));const scriptPath=path.resolve(__dirname,"../../../tools/build/generate-types-worker.mjs");const childConfig=JSON.stringify({dir:this.slothlet.config.root||this.slothlet.config.dir,mode:"eager",typescript:{enabled:true,mode:"fast"},types:typescriptConfig.types});await new Promise((resolve2,reject)=>{const child=fork(scriptPath,[],{stdio:["pipe","pipe","pipe","ipc"],env:{...process.env,SLOTHLET_CONFIG:childConfig}});let errorOutput="";child.stderr?.on("data",data=>{errorOutput+=data.toString()});child.on("message",msg=>{if(msg.type==="success"){this.slothlet._typesGenerated=true;resolve2()}else if(msg.type==="error"){reject(new this.SlothletError("TS_TYPE_GENERATION_FAILED",{},{message:msg.error}))}});child.on("error",error=>{reject(new this.SlothletError("TS_TYPE_GENERATION_FORK_FAILED",{},error))});child.on("exit",code=>{if(code!==0&&!this.slothlet._typesGenerated){reject(new this.SlothletError("TS_TYPE_GENERATION_PROCESS_EXITED",{code,output:errorOutput},null,{validationError:true}))}})})}const{transformTypeScriptStrict,writeTransformedToCache,formatDiagnostics}=await import("@cldmv/slothlet/processors/typescript");const result=await transformTypeScriptStrict(
|
|
17
|
+
import{readdir,stat}from"node:fs/promises";import{join,extname,basename,resolve}from"node:path";import{pathToFileURL}from"node:url";import{createRequire}from"node:module";import{ComponentBase}from"@cldmv/slothlet/factories/component-base";class Loader extends ComponentBase{static slothletProperty="loader";constructor(slothlet){super(slothlet)}async loadModule(filePath,instanceID,moduleID,cacheBust=null){try{if(filePath.endsWith(".cjs")){return this.#loadCJSIsolated(filePath)}const isTypeScript=filePath.endsWith(".ts")||filePath.endsWith(".mts");const typescriptConfig=this.slothlet.config?.typescript;let moduleUrl;if(isTypeScript&&typescriptConfig?.enabled){const mode=typescriptConfig.mode;if(mode==="strict"){if(!typescriptConfig.types?.output){throw new this.SlothletError("TS_STRICT_REQUIRES_OUTPUT",{},null,{validationError:true})}if(!typescriptConfig.types?.interfaceName){throw new this.SlothletError("TS_STRICT_REQUIRES_INTERFACE_NAME",{},null,{validationError:true})}if(!this.slothlet._typesGenerated){const{fork}=await import("child_process");const path=await import("path");const{fileURLToPath}=await import("url");const __dirname=path.dirname(fileURLToPath(import.meta.url));const scriptPath=path.resolve(__dirname,"../../../tools/build/generate-types-worker.mjs");const childConfig=JSON.stringify({dir:this.slothlet.config.root||this.slothlet.config.dir,mode:"eager",typescript:{enabled:true,mode:"fast"},types:typescriptConfig.types});await new Promise((resolve2,reject)=>{const child=fork(scriptPath,[],{stdio:["pipe","pipe","pipe","ipc"],env:{...process.env,SLOTHLET_CONFIG:childConfig}});let errorOutput="";child.stderr?.on("data",data=>{errorOutput+=data.toString()});child.on("message",msg=>{if(msg.type==="success"){this.slothlet._typesGenerated=true;resolve2()}else if(msg.type==="error"){reject(new this.SlothletError("TS_TYPE_GENERATION_FAILED",{},{message:msg.error}))}});child.on("error",error=>{reject(new this.SlothletError("TS_TYPE_GENERATION_FORK_FAILED",{},error))});child.on("exit",code=>{if(code!==0&&!this.slothlet._typesGenerated){reject(new this.SlothletError("TS_TYPE_GENERATION_PROCESS_EXITED",{code,output:errorOutput},null,{validationError:true}))}})})}const{transformTypeScriptStrict,writeTransformedToCache,formatDiagnostics}=await import("@cldmv/slothlet/processors/typescript");const strictTransform=async tsPath=>{const result=await transformTypeScriptStrict(tsPath,{target:typescriptConfig.target,module:typescriptConfig.module,strict:typescriptConfig.strict,typeDefinitionPath:typescriptConfig.types.output,compilerOptions:typescriptConfig.compilerOptions});if(result.diagnostics&&result.diagnostics.length>0){const ts=await import("typescript");const errors=formatDiagnostics(result.diagnostics,ts.default);const error=new this.SlothletError("TS_TYPE_CHECK_ERRORS",{filePath:tsPath,errors:errors.join("\n")},null,{validationError:true});error.diagnostics=result.diagnostics;throw error}return result.code};const entryCode=await strictTransform(filePath);moduleUrl=await this.#buildTypescriptModuleUrl(writeTransformedToCache,filePath,entryCode,instanceID,moduleID,cacheBust,strictTransform)}else{const{transformTypeScript,writeTransformedToCache}=await import("@cldmv/slothlet/processors/typescript");const transformOptions={target:typescriptConfig.target,sourcemap:typescriptConfig.sourcemap};const transformedCode=await transformTypeScript(filePath,transformOptions);const transform=tsPath=>transformTypeScript(tsPath,transformOptions);moduleUrl=await this.#buildTypescriptModuleUrl(writeTransformedToCache,filePath,transformedCode,instanceID,moduleID,cacheBust,transform)}}else{const fileUrl=pathToFileURL(filePath).href;moduleUrl=`${fileUrl}?slothlet_instance=${instanceID}`;if(moduleID){moduleUrl+=`&module=${moduleID}`}if(cacheBust){moduleUrl+=`&_reload=${cacheBust}`}}const module=await import(moduleUrl);return module}catch(error){throw new this.SlothletError("MODULE_IMPORT_FAILED",{modulePath:filePath},error)}}#loadCJSIsolated(filePath){const requireFn=createRequire(filePath);const resolved=requireFn.resolve(filePath);delete requireFn.cache[resolved];const exports=requireFn(resolved);delete requireFn.cache[resolved];const namespace={default:exports};if(exports!==null&&typeof exports==="object"){for(const key of Object.keys(exports)){if(key!=="default"){namespace[key]=exports[key]}}}return namespace}async#buildTypescriptModuleUrl(writeTransformedToCache,filePath,code,instanceID,moduleID,cacheBust,transform){const{url,cacheDir}=await writeTransformedToCache(filePath,code,instanceID,transform);(this.slothlet._typescriptCacheDirs??=new Set).add(cacheDir);let moduleUrl=`${url}?slothlet_instance=${instanceID}`;if(moduleID){moduleUrl+=`&module=${moduleID}`}if(cacheBust){moduleUrl+=`&_reload=${cacheBust}`}return moduleUrl}async scanDirectory(dir,options={}){const typescriptConfig=this.slothlet.config?.typescript;const defaultExtensions=[".mjs",".cjs",".js"];const typescriptExtensions=typescriptConfig?.enabled?[".ts",".mts"]:[];const allExtensions=[...defaultExtensions,...typescriptExtensions];const{recursive=true,extensions=allExtensions,isRootScan=true,currentDepth=0,maxDepth=Infinity,fileFilter=null}=options;try{await stat(dir)}catch(error){throw new this.SlothletError("INVALID_DIRECTORY",{dir},error)}const structure={files:[],directories:[]};const entries=await readdir(dir,{withFileTypes:true});for(const entry of entries){const fullPath=join(dir,entry.name);if(entry.isDirectory()){if(fileFilter){continue}if(recursive&¤tDepth<maxDepth){const subStructure=await this.scanDirectory(fullPath,{...options,isRootScan:false,currentDepth:currentDepth+1});structure.directories.push({path:fullPath,name:entry.name,children:subStructure})}}else if(entry.isFile()){const ext=extname(entry.name);if(extensions.includes(ext)){if(entry.name.startsWith("__")){continue}if(fileFilter&&!fileFilter(entry.name)){continue}const nameWithoutExt=basename(entry.name,ext);structure.files.push({path:fullPath,name:nameWithoutExt,fullName:entry.name,moduleID:this.slothlet.helpers.sanitize.getModuleId(fullPath,dir)})}}}if(isRootScan&&structure.files.length===0&&structure.directories.length===0){new this.SlothletWarning("WARN_DIRECTORY_EMPTY",{dir,resolvedPath:resolve(dir)})}return structure}extractExports(module){const exports={};if(module.default!==void 0){exports.default=module.default}for(const key of Object.keys(module)){if(key!=="default"&&key!=="module.exports"&&typeof key==="string"){exports[key]=module[key]}}if(exports.default&&typeof exports.default==="object"&&exports.default!==null&&"default"in exports.default){const rootNamedKeys=Object.keys(exports).filter(k=>k!=="default"&&k!=="module.exports");const defaultKeys=Object.keys(exports.default).filter(k=>k!=="default");const isCJSPattern=rootNamedKeys.every(k=>k in exports.default);if(isCJSPattern&&defaultKeys.length>0){exports.default=exports.default.default}}return exports}}export{Loader};
|
|
@@ -14,4 +14,4 @@
|
|
|
14
14
|
limitations under the License.
|
|
15
15
|
*/
|
|
16
16
|
|
|
17
|
-
import fs from"fs";import path from"path";import{writeFile,mkdir,readdir,rm}from"node:fs/promises";import{createHash}from"node:crypto";import{tmpdir}from"node:os";import{pathToFileURL}from"node:url";import{SlothletError}from"@cldmv/slothlet/errors";let esbuildInstance=null;let typescriptInstance=null;async function getEsbuild(){if(!esbuildInstance){try{esbuildInstance=await import("esbuild")}catch(error){throw new SlothletError("TYPESCRIPT_ESBUILD_NOT_INSTALLED",{mode:"fast"},error)}}return esbuildInstance}async function getTypeScript(){if(!typescriptInstance){try{typescriptInstance=await import("typescript")}catch(error){throw new SlothletError("TYPESCRIPT_TSC_NOT_INSTALLED",{mode:"strict"},error)}}return typescriptInstance}async function transformTypeScript(filePath,options={}){const esbuild=await getEsbuild();const code=fs.readFileSync(filePath,"utf8");const result=await esbuild.transform(code,{loader:"ts",format:options.format||"esm",target:options.target||"es2020",sourcemap:options.sourcemap||false,...options});return result.code}function createDataUrl(code){const encoded=encodeURIComponent(code);const timestamp=Date.now();return`data:text/javascript;charset=utf-8,${encoded}#t=${timestamp}`}function findPackageRoot(startPath){let dir;try{const resolved=path.resolve(startPath);dir=fs.statSync(resolved).isFile()?path.dirname(resolved):resolved}catch{return null}while(true){if(fs.existsSync(path.join(dir,"package.json")))return dir;const parent=path.dirname(dir);if(parent===dir)return null;dir=parent}}function isProcessAlive(pid){try{process.kill(pid,0);return true}catch(err){return err.code!=="ESRCH"}}const sweepPromises=new Map;function sweepStaleSlothletCache(projectRoot){if(sweepPromises.has(projectRoot))return sweepPromises.get(projectRoot);const promise=(async()=>{const cacheRoot=path.join(projectRoot,".slothlet-cache");let entries;try{entries=await readdir(cacheRoot,{withFileTypes:true})}catch{return}const currentPid=process.pid;await Promise.allSettled(entries.map(async entry=>{if(!entry.isDirectory())return;const match=entry.name.match(/^(\d+)-/);if(!match)return;const pid=Number(match[1]);if(pid===currentPid||isProcessAlive(pid))return;await rm(path.join(cacheRoot,entry.name),{recursive:true,force:true})}))})();sweepPromises.set(projectRoot,promise);return promise}async function writeTransformedToCache(originalPath,code,instanceID){const absolutePath=path.resolve(originalPath);const projectRoot=findPackageRoot(absolutePath)??tmpdir();await sweepStaleSlothletCache(projectRoot);const hash=createHash("sha256").update(absolutePath).update("\0").update(code).digest("hex").slice(0,16);const cacheDir=path.join(projectRoot,".slothlet-cache",`${process.pid}-${instanceID}`);const cachePath=path.join(cacheDir,`${hash}.mjs`);if(!fs.existsSync(cachePath)){await mkdir(cacheDir,{recursive:true});await writeFile(cachePath,code,"utf8")}return{url:pathToFileURL(cachePath).href,cacheDir}}async function transformTypeScriptStrict(filePath,options={}){const ts=await getTypeScript();const code=fs.readFileSync(filePath,"utf8");const targetMap={es3:ts.ScriptTarget.ES3,es5:ts.ScriptTarget.ES5,es6:ts.ScriptTarget.ES2015,es2015:ts.ScriptTarget.ES2015,es2016:ts.ScriptTarget.ES2016,es2017:ts.ScriptTarget.ES2017,es2018:ts.ScriptTarget.ES2018,es2019:ts.ScriptTarget.ES2019,es2020:ts.ScriptTarget.ES2020,es2021:ts.ScriptTarget.ES2021,es2022:ts.ScriptTarget.ES2022,esnext:ts.ScriptTarget.ESNext,latest:ts.ScriptTarget.Latest};const moduleMap={none:ts.ModuleKind.None,commonjs:ts.ModuleKind.CommonJS,amd:ts.ModuleKind.AMD,system:ts.ModuleKind.System,umd:ts.ModuleKind.UMD,es6:ts.ModuleKind.ES2015,es2015:ts.ModuleKind.ES2015,es2020:ts.ModuleKind.ES2020,es2022:ts.ModuleKind.ES2022,esnext:ts.ModuleKind.ESNext,node16:ts.ModuleKind.Node16,nodenext:ts.ModuleKind.NodeNext};const targetKey=(options.target||"es2020").toLowerCase();const moduleKey=(options.module||"esnext").toLowerCase();const compilerOptions={target:targetMap[targetKey]||ts.ScriptTarget.ES2020,module:moduleMap[moduleKey]||ts.ModuleKind.ESNext,strict:options.strict!==false,esModuleInterop:true,skipLibCheck:true,noEmit:false,...options.typeDefinitionPath&&{typeRoots:[path.dirname(options.typeDefinitionPath)],types:[path.basename(options.typeDefinitionPath,".d.ts")]},...options.compilerOptions};let diagnostics=[];if(!options.skipTypeCheck){const host=ts.createCompilerHost(compilerOptions);const originalReadFile=host.readFile;host.readFile=fileName=>{if(fileName===filePath){return code}return originalReadFile.call(host,fileName)};const program=ts.createProgram([filePath],compilerOptions,host);const allDiagnostics=[...program.getSemanticDiagnostics(),...program.getSyntacticDiagnostics()];diagnostics=allDiagnostics.filter(d=>d.file&&d.file.fileName===filePath)}const result=ts.transpileModule(code,{compilerOptions,fileName:filePath});return{code:result.outputText,diagnostics}}function formatDiagnostics(diagnostics,ts){return diagnostics.map(diagnostic=>{const message=ts.flattenDiagnosticMessageText(diagnostic.messageText,"\n");if(diagnostic.file&&diagnostic.start!==void 0){const{line,character}=diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start);const fileName=diagnostic.file.fileName;return`${fileName}:${line+1}:${character+1} - ${message}`}return message})}export{createDataUrl,formatDiagnostics,transformTypeScript,transformTypeScriptStrict,writeTransformedToCache};
|
|
17
|
+
import fs from"fs";import path from"path";import{writeFile,mkdir,readdir,rm}from"node:fs/promises";import{createHash}from"node:crypto";import{tmpdir}from"node:os";import{pathToFileURL}from"node:url";import{SlothletError}from"@cldmv/slothlet/errors";let esbuildInstance=null;let typescriptInstance=null;async function getEsbuild(){if(!esbuildInstance){try{esbuildInstance=await import("esbuild")}catch(error){throw new SlothletError("TYPESCRIPT_ESBUILD_NOT_INSTALLED",{mode:"fast"},error)}}return esbuildInstance}async function getTypeScript(){if(!typescriptInstance){try{typescriptInstance=await import("typescript")}catch(error){throw new SlothletError("TYPESCRIPT_TSC_NOT_INSTALLED",{mode:"strict"},error)}}return typescriptInstance}async function transformTypeScript(filePath,options={}){const esbuild=await getEsbuild();const code=fs.readFileSync(filePath,"utf8");const result=await esbuild.transform(code,{loader:"ts",format:options.format||"esm",target:options.target||"es2020",sourcemap:options.sourcemap||false,...options});return result.code}function createDataUrl(code){const encoded=encodeURIComponent(code);const timestamp=Date.now();return`data:text/javascript;charset=utf-8,${encoded}#t=${timestamp}`}function findPackageRoot(startPath){let dir;try{const resolved=path.resolve(startPath);dir=fs.statSync(resolved).isFile()?path.dirname(resolved):resolved}catch{return null}while(true){if(fs.existsSync(path.join(dir,"package.json")))return dir;const parent=path.dirname(dir);if(parent===dir)return null;dir=parent}}function isProcessAlive(pid){try{process.kill(pid,0);return true}catch(err){return err.code!=="ESRCH"}}const sweepPromises=new Map;function sweepStaleSlothletCache(projectRoot){if(sweepPromises.has(projectRoot))return sweepPromises.get(projectRoot);const promise=(async()=>{const cacheRoot=path.join(projectRoot,".slothlet-cache");let entries;try{entries=await readdir(cacheRoot,{withFileTypes:true})}catch{return}const currentPid=process.pid;await Promise.allSettled(entries.map(async entry=>{if(!entry.isDirectory())return;const match=entry.name.match(/^(\d+)-/);if(!match)return;const pid=Number(match[1]);if(pid===currentPid||isProcessAlive(pid))return;await rm(path.join(cacheRoot,entry.name),{recursive:true,force:true})}))})();sweepPromises.set(projectRoot,promise);return promise}const TS_SOURCE_EXT=/\.m?ts$/;function resolveModuleFile(absoluteTarget){const isFile=candidate=>{try{return fs.statSync(candidate).isFile()}catch{return false}};if(isFile(absoluteTarget)){return{path:absoluteTarget,isTS:TS_SOURCE_EXT.test(absoluteTarget)}}const ext=path.extname(absoluteTarget);const base=ext?absoluteTarget.slice(0,-ext.length):absoluteTarget;const candidates=ext===".mjs"?[".mts"]:ext===".js"?[".ts"]:ext===""?[".mts",".ts"]:[];for(const candidate of candidates){if(isFile(base+candidate)){return{path:base+candidate,isTS:true}}}return{path:absoluteTarget,isTS:false}}const REGEX_PRECEDING_KEYWORDS=new Set(["return","typeof","instanceof","in","of","new","delete","void","throw","else","yield","await","case","do"]);function isIdentifierChar(ch){const cc=ch.charCodeAt(0);return cc>=97&&cc<=122||cc>=65&&cc<=90||cc>=48&&cc<=57||ch==="_"||ch==="$"||cc>127}function maskStringsAndComments(code){const n=code.length;const mask=new Uint8Array(n);let regexAllowed=true;let i=0;while(i<n){const c=code[i];const c2=code[i+1];if(c==="/"&&c2==="/"){while(i<n&&code[i]!=="\n")mask[i++]=1}else if(c==="/"&&c2==="*"){mask[i++]=1;mask[i++]=1;while(i<n&&!(code[i]==="*"&&code[i+1]==="/"))mask[i++]=1;if(i<n){mask[i++]=1;mask[i++]=1}}else if(c==="/"&®exAllowed){mask[i++]=1;let inClass=false;while(i<n&&code[i]!=="\n"){const ch=code[i];if(ch==="\\"&&i+1<n){mask[i++]=1;mask[i++]=1;continue}if(ch==="[")inClass=true;else if(ch==="]")inClass=false;mask[i++]=1;if(ch==="/"&&!inClass)break}regexAllowed=false}else if(c==='"'||c==="'"||c==="`"){mask[i++]=1;while(i<n&&code[i]!==c){if(code[i]==="\\"&&i+1<n)mask[i++]=1;mask[i++]=1}if(i<n)mask[i++]=1;regexAllowed=false}else if(c===" "||c===" "||c==="\n"||c==="\r"||c==="\f"||c==="\v"){i++}else if(isIdentifierChar(c)&&!(c>="0"&&c<="9")){const start=i;while(i<n&&isIdentifierChar(code[i]))i++;regexAllowed=REGEX_PRECEDING_KEYWORDS.has(code.slice(start,i))}else{regexAllowed=c!==")"&&c!=="]"&&!(c>="0"&&c<="9");i++}}return mask}const TOKEN_GAP="(?:\\s|/\\*[\\s\\S]*?\\*/|//[^\\n]*)*";const STATIC_FROM_RE=new RegExp(`^([ \\t]*(?:import|export)\\b[^"'\`;]*?\\bfrom${TOKEN_GAP})(["'])(\\.\\.?/[^"']*)\\2`,"gm");const BARE_IMPORT_RE=new RegExp(`^([ \\t]*import${TOKEN_GAP})(["'])(\\.\\.?/[^"']*)\\2`,"gm");const DYNAMIC_IMPORT_RE=new RegExp(`(?<![.\\w$])import(${TOKEN_GAP}\\(${TOKEN_GAP})(["'])(\\.\\.?/[^"']*)\\2(${TOKEN_GAP}\\))`,"g");function rewriteRelativeSpecifiers(code,sourcePath,resolve){const sourceDir=path.dirname(sourcePath);const resolveSpecifier=resolve??((absoluteTarget,suffix)=>pathToFileURL(absoluteTarget).href+suffix);const handle=specifier=>{const suffixIdx=specifier.search(/[?#]/);const pathPart=suffixIdx===-1?specifier:specifier.slice(0,suffixIdx);const suffix=suffixIdx===-1?"":specifier.slice(suffixIdx);return resolveSpecifier(path.resolve(sourceDir,pathPart),suffix,specifier)};const rewriteWith=(text,regex,replacer)=>{const mask=maskStringsAndComments(text);return text.replace(regex,(...args)=>{const offset=args[args.length-2];return mask[offset]?args[0]:replacer(...args)})};let out=code;out=rewriteWith(out,STATIC_FROM_RE,(_m,pre,q,spec)=>`${pre}${q}${handle(spec)}${q}`);out=rewriteWith(out,BARE_IMPORT_RE,(_m,pre,q,spec)=>`${pre}${q}${handle(spec)}${q}`);out=rewriteWith(out,DYNAMIC_IMPORT_RE,(_m,pre,q,spec,post)=>`import${pre}${q}${handle(spec)}${q}${post}`);return out}async function writeTransformedToCache(originalPath,code,instanceID,transform){const absolutePath=path.resolve(originalPath);const projectRoot=findPackageRoot(absolutePath)??tmpdir();await sweepStaleSlothletCache(projectRoot);const cacheDir=path.join(projectRoot,".slothlet-cache",`${process.pid}-${instanceID}`);const transformed=new Map([[absolutePath,code]]);const deps=new Map;if(transform){const pending=[absolutePath];while(pending.length>0){const file=pending.pop();const fileDeps=new Set;deps.set(file,fileDeps);rewriteRelativeSpecifiers(transformed.get(file),file,(absoluteTarget,_suffix,specifier)=>{const resolved=resolveModuleFile(absoluteTarget);if(resolved.isTS)fileDeps.add(resolved.path);return specifier});for(const dep of fileDeps){if(!transformed.has(dep)){transformed.set(dep,await transform(dep));pending.push(dep)}}}}const closureCache=new Map;const closureOf=file=>{if(closureCache.has(file))return closureCache.get(file);const seen=new Set;const walk=node=>{if(seen.has(node))return;seen.add(node);for(const next of deps.get(node)??[])walk(next)};walk(file);closureCache.set(file,seen);return seen};const cacheName=file=>{const hash=createHash("sha256");for(const member of[...closureOf(file)].sort()){hash.update(member).update("\0").update(transformed.get(member)).update("\0")}hash.update("entry\0").update(file);return`${hash.digest("hex").slice(0,16)}.mjs`};await mkdir(cacheDir,{recursive:true});for(const[file,fileCode]of transformed){const rewritten=rewriteRelativeSpecifiers(fileCode,file,(absoluteTarget,suffix)=>{const resolved=resolveModuleFile(absoluteTarget);if(resolved.isTS&&transformed.has(resolved.path)){return pathToFileURL(path.join(cacheDir,cacheName(resolved.path))).href+suffix}return pathToFileURL(resolved.path).href+suffix});const cachePath=path.join(cacheDir,cacheName(file));if(!fs.existsSync(cachePath)){await writeFile(cachePath,rewritten,"utf8")}}return{url:pathToFileURL(path.join(cacheDir,cacheName(absolutePath))).href,cacheDir}}async function transformTypeScriptStrict(filePath,options={}){const ts=await getTypeScript();const code=fs.readFileSync(filePath,"utf8");const targetMap={es3:ts.ScriptTarget.ES3,es5:ts.ScriptTarget.ES5,es6:ts.ScriptTarget.ES2015,es2015:ts.ScriptTarget.ES2015,es2016:ts.ScriptTarget.ES2016,es2017:ts.ScriptTarget.ES2017,es2018:ts.ScriptTarget.ES2018,es2019:ts.ScriptTarget.ES2019,es2020:ts.ScriptTarget.ES2020,es2021:ts.ScriptTarget.ES2021,es2022:ts.ScriptTarget.ES2022,esnext:ts.ScriptTarget.ESNext,latest:ts.ScriptTarget.Latest};const moduleMap={none:ts.ModuleKind.None,commonjs:ts.ModuleKind.CommonJS,amd:ts.ModuleKind.AMD,system:ts.ModuleKind.System,umd:ts.ModuleKind.UMD,es6:ts.ModuleKind.ES2015,es2015:ts.ModuleKind.ES2015,es2020:ts.ModuleKind.ES2020,es2022:ts.ModuleKind.ES2022,esnext:ts.ModuleKind.ESNext,node16:ts.ModuleKind.Node16,nodenext:ts.ModuleKind.NodeNext};const targetKey=(options.target||"es2020").toLowerCase();const moduleKey=(options.module||"esnext").toLowerCase();const compilerOptions={target:targetMap[targetKey]||ts.ScriptTarget.ES2020,module:moduleMap[moduleKey]||ts.ModuleKind.ESNext,strict:options.strict!==false,esModuleInterop:true,skipLibCheck:true,noEmit:false,...options.typeDefinitionPath&&{typeRoots:[path.dirname(options.typeDefinitionPath)],types:[path.basename(options.typeDefinitionPath,".d.ts")]},...options.compilerOptions};let diagnostics=[];if(!options.skipTypeCheck){const host=ts.createCompilerHost(compilerOptions);const originalReadFile=host.readFile;host.readFile=fileName=>{if(fileName===filePath){return code}return originalReadFile.call(host,fileName)};const program=ts.createProgram([filePath],compilerOptions,host);const allDiagnostics=[...program.getSemanticDiagnostics(),...program.getSyntacticDiagnostics()];diagnostics=allDiagnostics.filter(d=>d.file&&d.file.fileName===filePath)}const result=ts.transpileModule(code,{compilerOptions,fileName:filePath});return{code:result.outputText,diagnostics}}function formatDiagnostics(diagnostics,ts){return diagnostics.map(diagnostic=>{const message=ts.flattenDiagnosticMessageText(diagnostic.messageText,"\n");if(diagnostic.file&&diagnostic.start!==void 0){const{line,character}=diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start);const fileName=diagnostic.file.fileName;return`${fileName}:${line+1}:${character+1} - ${message}`}return message})}export{createDataUrl,formatDiagnostics,maskStringsAndComments,resolveModuleFile,rewriteRelativeSpecifiers,transformTypeScript,transformTypeScriptStrict,writeTransformedToCache};
|
package/index.mjs
CHANGED
|
@@ -118,17 +118,17 @@ const devcheckPromise = (async () => {
|
|
|
118
118
|
* const result = await api.math.add(2, 3); // 5
|
|
119
119
|
*
|
|
120
120
|
*/
|
|
121
|
-
|
|
121
|
+
const slothlet = async (options = {}) => {
|
|
122
122
|
// Wait for devcheck to complete before proceeding
|
|
123
123
|
await devcheckPromise;
|
|
124
124
|
|
|
125
125
|
// Dynamic imports after environment check
|
|
126
126
|
const mod = await import("@cldmv/slothlet/slothlet");
|
|
127
127
|
|
|
128
|
-
const
|
|
128
|
+
const slothletImpl = mod.slothlet ?? mod.default;
|
|
129
129
|
|
|
130
|
-
return
|
|
131
|
-
}
|
|
130
|
+
return slothletImpl(options);
|
|
131
|
+
};
|
|
132
132
|
|
|
133
133
|
/**
|
|
134
134
|
* Named export alias for the default slothlet function.
|
|
@@ -140,5 +140,8 @@ export default async function slothlet(options = {}) {
|
|
|
140
140
|
* import { slothlet } from "@cldmv/slothlet";
|
|
141
141
|
* const api = await slothlet({ dir: './api' });
|
|
142
142
|
*/
|
|
143
|
-
//
|
|
143
|
+
// Default export and named alias — both bind the same function. `slothlet` is a
|
|
144
|
+
// `const` (not `export default function`) so the generated `.d.mts` reliably
|
|
145
|
+
// emits the named `export { slothlet }` alongside the default export.
|
|
146
|
+
export default slothlet;
|
|
144
147
|
export { slothlet };
|
package/package.json
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"api_builder.d.mts","sourceRoot":"","sources":["../../../../dist/lib/builders/api_builder.mjs"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"api_builder.d.mts","sourceRoot":"","sources":["../../../../dist/lib/builders/api_builder.mjs"],"names":[],"mappings":"AAAm/C;IAAuC,gCAAqC;IAAsC,0CAA66C;IAAA,oDAAi40B;IAAA,6CAAqR;IAAA,uFAA0vB;IAAA,sDAA8sJ;IAAA,qDAAmkB;IAAA,kDAA2Z;CAAC;8BAA1goC,0CAA0C"}
|
|
@@ -9,7 +9,7 @@ export class AsyncContextManager {
|
|
|
9
9
|
config: {};
|
|
10
10
|
createdAt: number;
|
|
11
11
|
};
|
|
12
|
-
runInContext(instanceID: any, fn: any, thisArg: any, args: any, currentWrapper: any): any;
|
|
12
|
+
runInContext(instanceID: any, fn: any, thisArg: any, args: any, currentWrapper: any, rawErrors?: boolean): any;
|
|
13
13
|
getContext(): any;
|
|
14
14
|
tryGetContext(): any;
|
|
15
15
|
cleanup(instanceID: any): void;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"context-async.d.mts","sourceRoot":"","sources":["../../../../dist/lib/handlers/context-async.mjs"],"names":[],"mappings":"AAA+R;IAAwC,SAA8B;IAAC,yBAAsB;IAAC,2CAA2I;IAAA;;;;;;MAAqS;IAAA
|
|
1
|
+
{"version":3,"file":"context-async.d.mts","sourceRoot":"","sources":["../../../../dist/lib/handlers/context-async.mjs"],"names":[],"mappings":"AAA+R;IAAwC,SAA8B;IAAC,yBAAsB;IAAC,2CAA2I;IAAA;;;;;;MAAqS;IAAA,+GAAm3C;IAAA,kBAAuJ;IAAA,qBAA2C;IAAA,+BAAyS;IAAA;;;;;;;;;MAAmQ;CAAC;AAAA,sDAAkD"}
|
|
@@ -9,7 +9,7 @@ export class LiveContextManager {
|
|
|
9
9
|
config: {};
|
|
10
10
|
createdAt: number;
|
|
11
11
|
};
|
|
12
|
-
runInContext(instanceID: any, fn: any, thisArg: any, args: any, currentWrapper: any): any;
|
|
12
|
+
runInContext(instanceID: any, fn: any, thisArg: any, args: any, currentWrapper: any, rawErrors?: boolean): any;
|
|
13
13
|
getContext(): any;
|
|
14
14
|
tryGetContext(): any;
|
|
15
15
|
cleanup(instanceID: any): void;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"context-live.d.mts","sourceRoot":"","sources":["../../../../dist/lib/handlers/context-live.mjs"],"names":[],"mappings":"AAAiI;IAAuC,yBAAsB;IAAC,uBAA2B;IAAC,2CAAsG;IAAA;;;;;;MAAmW;IAAA
|
|
1
|
+
{"version":3,"file":"context-live.d.mts","sourceRoot":"","sources":["../../../../dist/lib/handlers/context-live.mjs"],"names":[],"mappings":"AAAiI;IAAuC,yBAAsB;IAAC,uBAA2B;IAAC,2CAAsG;IAAA;;;;;;MAAmW;IAAA,+GAAuoC;IAAA,kBAA8X;IAAA,qBAA4G;IAAA,+BAA8W;IAAA;;;;;;;;;MAAyP;CAAC;AAAA,oDAAgD"}
|
|
@@ -20,6 +20,7 @@ export class HookManager extends ComponentBase {
|
|
|
20
20
|
priority: any;
|
|
21
21
|
subset: any;
|
|
22
22
|
enabled: any;
|
|
23
|
+
lockCaller: any;
|
|
23
24
|
}[];
|
|
24
25
|
};
|
|
25
26
|
getHooksForPath(type: any, apiPath: any): any[];
|
|
@@ -49,6 +50,7 @@ export class HookManager extends ComponentBase {
|
|
|
49
50
|
id: any;
|
|
50
51
|
priority: any;
|
|
51
52
|
subset: any;
|
|
53
|
+
lockCaller: any;
|
|
52
54
|
};
|
|
53
55
|
enabled: any;
|
|
54
56
|
}[];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hook-manager.d.mts","sourceRoot":"","sources":["../../../../dist/lib/handlers/hook-manager.mjs"],"names":[],"mappings":"AAAsN;IAAwC,gCAAsC;IAA2a,aAA+B;IAAC,oBAA4C;IAAC,oBAAoD;IAAC,0BAA4B;IAAC,6BAA8B;IAAC,qBAAkB;IAAC,0BAAwB;IAAC,gCAA+B;IAAC,
|
|
1
|
+
{"version":3,"file":"hook-manager.d.mts","sourceRoot":"","sources":["../../../../dist/lib/handlers/hook-manager.mjs"],"names":[],"mappings":"AAAsN;IAAwC,gCAAsC;IAA2a,aAA+B;IAAC,oBAA4C;IAAC,oBAAoD;IAAC,0BAA4B;IAAC,6BAA8B;IAAC,qBAAkB;IAAC,0BAAwB;IAAC,gCAA+B;IAAC,sDAAmsC;IAAub,4BAA2vB;IAAA,4BAAmI;IAAA,6BAAyK;IAAA;;;;;;;;;;MAA46B;IAAA,gDAA+pB;IAAA;;;;;;;;MAAswB;IAAA;;;;;;MAA2pB;IAAA,iJAAqb;IAAA,2FAA2Y;IAAwzB,yDAAyE;IAAyoD;;;;;;;;;;QAAsS;IAAA,sCAAyM;IAAA,0BAA8N;;CAAC;8BAArmV,0CAA0C"}
|
|
@@ -3,7 +3,6 @@ export namespace TYPE_STATES {
|
|
|
3
3
|
let IN_FLIGHT: symbol;
|
|
4
4
|
}
|
|
5
5
|
export class UnifiedWrapper extends ComponentBase {
|
|
6
|
-
[x: number]: (____depth: any, ____options: any, ____inspect: any) => any;
|
|
7
6
|
static _cloneImpl(value: any): any;
|
|
8
7
|
static _extractFullImpl(wrapper: any): any;
|
|
9
8
|
constructor(slothlet: any, { mode, apiPath, initialImpl, materializeFunc, isCallable, materializeOnCreate, filePath, moduleID, sourceFolder }: {
|
|
@@ -18,6 +17,7 @@ export class UnifiedWrapper extends ComponentBase {
|
|
|
18
17
|
sourceFolder?: null | undefined;
|
|
19
18
|
});
|
|
20
19
|
get ____slothletInternal(): null | undefined;
|
|
20
|
+
____inspectCustom(____depth: any, ____options: any, ____inspect: any): any;
|
|
21
21
|
get __impl(): any;
|
|
22
22
|
_applyNewImpl(newImpl: any, forceReuseChildren?: boolean): void;
|
|
23
23
|
___setImpl(newImpl: any, moduleID?: null, forceReuseChildren?: boolean): void;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"unified-wrapper.d.mts","sourceRoot":"","sources":["../../../../dist/lib/handlers/unified-wrapper.mjs"],"names":[],"mappings":";;;;AAA+vC
|
|
1
|
+
{"version":3,"file":"unified-wrapper.d.mts","sourceRoot":"","sources":["../../../../dist/lib/handlers/unified-wrapper.mjs"],"names":[],"mappings":";;;;AAA+vC;IAAyjH,mCAAsc;IAAA,2CAAy/B;IAAv2J;;;;;;;;;;OAAq1F;IAA56F,6CAAuF;IAAq1F,2EAAgiB;IAAA,kBAAmD;IAA+7C,gEAAqyB;IAAA,8EAAgsC;IAAA,4CAA2kC;IAAA,+BAAs4D;IAAA,6BAA4C;IAAA,sBAA8T;IAAA,yDAAq6P;IAAA,iDAA2sG;IAAA,8CAA20Y;IAAA,mBAAs1wB;IAA3oO,uBAAwB;;CAAonO;AAAwK,gDAA8N;8BAApj3D,0CAA0C"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"class-instance-wrapper.d.mts","sourceRoot":"","sources":["../../../../dist/lib/helpers/class-instance-wrapper.mjs"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"class-instance-wrapper.d.mts","sourceRoot":"","sources":["../../../../dist/lib/helpers/class-instance-wrapper.mjs"],"names":[],"mappings":"AAAkc,2DAAmT;AAAre,yEAAkL;AAAmT,wHAAwkC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"loader.d.mts","sourceRoot":"","sources":["../../../../dist/lib/processors/loader.mjs"],"names":[],"mappings":"AAA+O;IAAmC,gCAAiC;IAAsC,
|
|
1
|
+
{"version":3,"file":"loader.d.mts","sourceRoot":"","sources":["../../../../dist/lib/processors/loader.mjs"],"names":[],"mappings":"AAA+O;IAAmC,gCAAiC;IAAsC,0FAA8iH;IAAozB;;;OAA+7C;IAAA,gCAAipB;;CAAC;8BAAxkN,0CAA0C"}
|
|
@@ -1,11 +1,17 @@
|
|
|
1
1
|
export function createDataUrl(code: any): string;
|
|
2
2
|
export function formatDiagnostics(diagnostics: any, ts: any): any;
|
|
3
|
+
export function maskStringsAndComments(code: any): Uint8Array<any>;
|
|
4
|
+
export function resolveModuleFile(absoluteTarget: any): {
|
|
5
|
+
path: any;
|
|
6
|
+
isTS: boolean;
|
|
7
|
+
};
|
|
8
|
+
export function rewriteRelativeSpecifiers(code: any, sourcePath: any, resolve: any): any;
|
|
3
9
|
export function transformTypeScript(filePath: any, options?: {}): Promise<any>;
|
|
4
10
|
export function transformTypeScriptStrict(filePath: any, options?: {}): Promise<{
|
|
5
11
|
code: any;
|
|
6
12
|
diagnostics: any[];
|
|
7
13
|
}>;
|
|
8
|
-
export function writeTransformedToCache(originalPath: any, code: any, instanceID: any): Promise<{
|
|
14
|
+
export function writeTransformedToCache(originalPath: any, code: any, instanceID: any, transform: any): Promise<{
|
|
9
15
|
url: any;
|
|
10
16
|
cacheDir: any;
|
|
11
17
|
}>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"typescript.d.mts","sourceRoot":"","sources":["../../../../dist/lib/processors/typescript.mjs"],"names":[],"mappings":"AAA2hC,iDAAoK;
|
|
1
|
+
{"version":3,"file":"typescript.d.mts","sourceRoot":"","sources":["../../../../dist/lib/processors/typescript.mjs"],"names":[],"mappings":"AAA2hC,iDAAoK;AAAmtQ,kEAAkZ;AAA5qN,mEAA+kC;AAA55D;;;EAA8iB;AAAqwD,yFAA68B;AAA50J,+EAA4T;AAAo9M;;;GAAm6D;AAAv2H;;;GAAo8D"}
|
package/types/index.d.mts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
export default slothlet;
|
|
1
2
|
/**
|
|
2
3
|
* Creates a slothlet API instance with live-binding context and AsyncLocalStorage support.
|
|
3
4
|
* Automatically wraps all API functions with context isolation for multi-instance support.
|
|
@@ -23,7 +24,7 @@
|
|
|
23
24
|
* const result = await api.math.add(2, 3); // 5
|
|
24
25
|
*
|
|
25
26
|
*/
|
|
26
|
-
export
|
|
27
|
+
export function slothlet(options?: {
|
|
27
28
|
dir?: string | undefined;
|
|
28
29
|
lazy?: boolean | undefined;
|
|
29
30
|
mode?: string | undefined;
|
|
@@ -35,5 +36,4 @@ export default function slothlet(options?: {
|
|
|
35
36
|
context?: object | undefined;
|
|
36
37
|
reference?: object | undefined;
|
|
37
38
|
}): Promise<import("./src/slothlet.mjs").SlothletAPI>;
|
|
38
|
-
export { slothlet };
|
|
39
39
|
//# sourceMappingURL=index.d.mts.map
|
package/types/index.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","sourceRoot":"","sources":["../index.mjs"],"names":[],"mappings":"AA+FA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,
|
|
1
|
+
{"version":3,"file":"index.d.mts","sourceRoot":"","sources":["../index.mjs"],"names":[],"mappings":";AA+FA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,mCAlBG;IAAyB,GAAG;IACF,IAAI;IACL,IAAI;IACJ,MAAM;IACN,QAAQ;IACP,KAAK;IACN,QAAQ;IACP,iBAAiB;IAClB,OAAO;IACP,SAAS;CAClC,GAAU,OAAO,CAAC,OAAO,oBAAoB,EAAE,WAAW,CAAC,CAkB7D"}
|