@cldmv/slothlet 3.9.0 → 3.9.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/README.md +20 -9
  2. package/dist/lib/builders/api_builder.mjs +1 -1
  3. package/dist/lib/handlers/api-manager.mjs +1 -1
  4. package/dist/lib/handlers/context-async.mjs +1 -1
  5. package/dist/lib/handlers/hook-manager.mjs +1 -1
  6. package/dist/lib/handlers/metadata.mjs +1 -1
  7. package/dist/lib/handlers/unified-wrapper.mjs +1 -1
  8. package/dist/lib/handlers/version-manager.mjs +1 -1
  9. package/dist/lib/helpers/class-instance-wrapper.mjs +1 -1
  10. package/dist/lib/helpers/config.mjs +1 -1
  11. package/dist/lib/helpers/eventemitter-context.mjs +1 -1
  12. package/dist/lib/helpers/generate-manifest.mjs +1 -1
  13. package/dist/lib/helpers/module-discovery.mjs +1 -1
  14. package/dist/lib/helpers/module-manifest-validator.mjs +1 -1
  15. package/dist/lib/helpers/platform.mjs +17 -0
  16. package/dist/lib/helpers/resolve-from-caller.mjs +1 -1
  17. package/dist/lib/i18n/translations.mjs +1 -1
  18. package/dist/lib/processors/loader.mjs +1 -1
  19. package/dist/slothlet.mjs +1 -1
  20. package/index.mjs +17 -10
  21. package/package.json +8 -2
  22. package/types/dist/lib/builders/api_builder.d.mts.map +1 -1
  23. package/types/dist/lib/handlers/api-manager.d.mts.map +1 -1
  24. package/types/dist/lib/handlers/context-async.d.mts.map +1 -1
  25. package/types/dist/lib/handlers/hook-manager.d.mts +6 -3
  26. package/types/dist/lib/handlers/hook-manager.d.mts.map +1 -1
  27. package/types/dist/lib/handlers/metadata.d.mts.map +1 -1
  28. package/types/dist/lib/handlers/unified-wrapper.d.mts.map +1 -1
  29. package/types/dist/lib/handlers/version-manager.d.mts.map +1 -1
  30. package/types/dist/lib/helpers/class-instance-wrapper.d.mts.map +1 -1
  31. package/types/dist/lib/helpers/config.d.mts +10 -0
  32. package/types/dist/lib/helpers/config.d.mts.map +1 -1
  33. package/types/dist/lib/helpers/eventemitter-context.d.mts.map +1 -1
  34. package/types/dist/lib/helpers/generate-manifest.d.mts +9 -0
  35. package/types/dist/lib/helpers/generate-manifest.d.mts.map +1 -1
  36. package/types/dist/lib/helpers/module-discovery.d.mts.map +1 -1
  37. package/types/dist/lib/helpers/module-manifest-validator.d.mts.map +1 -1
  38. package/types/dist/lib/helpers/platform.d.mts +12 -0
  39. package/types/dist/lib/helpers/platform.d.mts.map +1 -0
  40. package/types/dist/lib/helpers/resolve-from-caller.d.mts.map +1 -1
  41. package/types/dist/lib/i18n/translations.d.mts +1 -0
  42. package/types/dist/lib/i18n/translations.d.mts.map +1 -1
  43. package/types/dist/lib/processors/loader.d.mts.map +1 -1
  44. package/types/dist/slothlet.d.mts.map +1 -1
  45. package/types/index.d.mts.map +1 -1
@@ -14,4 +14,4 @@
14
14
  limitations under the License.
15
15
  */
16
16
 
17
- import{ComponentBase}from"@cldmv/slothlet/factories/component-base";import{SlothletError}from"@cldmv/slothlet/errors";const IS_NODE=typeof process!=="undefined"&&typeof process.versions?.node==="string";class Config extends ComponentBase{static slothletProperty="config";normalizeCollision(collision){const validModes=["skip","warn","replace","merge","merge-replace","error"];const defaultMode="merge";if(typeof collision==="string"){const normalized=collision.toLowerCase();const mode=validModes.includes(normalized)?normalized:defaultMode;return{initial:mode,api:mode}}if(collision&&typeof collision==="object"){const validateMode=m=>{if(!m)return defaultMode;const normalized=String(m).toLowerCase();return validModes.includes(normalized)?normalized:defaultMode};return{initial:validateMode(collision.initial),api:validateMode(collision.api)}}return{initial:defaultMode,api:defaultMode}}normalizeRuntime(runtime){if(!runtime||typeof runtime!=="string"){return"async"}const normalized=runtime.toLowerCase().trim();if(normalized==="async"||normalized==="asynclocal"||normalized==="asynclocalstorage"){return"async"}if(normalized==="live"||normalized==="livebindings"||normalized==="experimental"){return"live"}return"async"}normalizeMode(mode){if(!mode||typeof mode!=="string"){return"eager"}const normalized=mode.toLowerCase().trim();if(normalized==="lazy"||normalized==="deferred"||normalized==="proxy"){return"lazy"}if(normalized==="eager"||normalized==="immediate"||normalized==="preload"){return"eager"}return"eager"}normalizeMutations(mutations){const defaults={add:true,remove:true,reload:true,permissions:true};if(!mutations||typeof mutations!=="object"){return defaults}return{add:mutations.add===false?false:true,remove:mutations.remove===false?false:true,reload:mutations.reload===false?false:true,permissions:mutations.permissions===false?false:true}}normalizeDebug(debug){if(!debug){return{builder:false,api:false,index:false,modes:false,wrapper:false,ownership:false,context:false,initialization:false,materialize:false,versioning:false,permissions:false}}if(debug===true){return{builder:true,api:true,index:true,modes:true,wrapper:true,ownership:true,context:true,initialization:true,materialize:true,versioning:true,permissions:true}}if(typeof debug==="object"){return{builder:debug.builder||false,api:debug.api||false,index:debug.index||false,modes:debug.modes||false,wrapper:debug.wrapper||false,ownership:debug.ownership||false,context:debug.context||false,initialization:debug.initialization||false,materialize:debug.materialize||false,versioning:debug.versioning||false,permissions:debug.permissions||false}}return{builder:false,api:false,index:false,modes:false,wrapper:false,ownership:false,context:false,initialization:false,materialize:false,versioning:false,permissions:false}}normalizeEnvTarget(platform,hasManifest=false){if(platform==="browser")return"browser";if(platform==="node")return"node";if(hasManifest)return"browser";return IS_NODE?"node":"browser"}transformConfig(config={}){const hasManifest=config.manifest!=null;const envTarget=this.normalizeEnvTarget(config.platform,hasManifest);const rawBase=config.base??config.dir;if(config.dir!==void 0&&config.base===void 0&&!config.silent){new this.SlothletWarning("V3_CONFIG_DEPRECATED",{option:"dir",replacement:"base"})}if(!rawBase){throw new this.SlothletError("INVALID_CONFIG_DIR_MISSING",{},null,{validationError:true})}if(envTarget==="browser"){if(!config.manifest||typeof config.manifest!=="object"||Array.isArray(config.manifest)){throw new this.SlothletError("INVALID_CONFIG_BROWSER_REQUIRES_MANIFEST",{},null,{validationError:true})}if(!Array.isArray(config.manifest.files)||!Array.isArray(config.manifest.directories)){throw new this.SlothletError("INVALID_CONFIG_BROWSER_MANIFEST_INVALID",{received:typeof config.manifest},null,{validationError:true})}if(config.resolveModuleSpecifier!==void 0&&typeof config.resolveModuleSpecifier!=="function"){throw new this.SlothletError("INVALID_CONFIG_BROWSER_RESOLVE_SPECIFIER_INVALID",{received:typeof config.resolveModuleSpecifier},null,{validationError:true})}}const resolvedDir=envTarget==="browser"?rawBase:this.slothlet.helpers.resolver.resolvePathFromCaller(rawBase);let mutations=null;if(config.allowMutation===false){mutations={add:false,remove:false,reload:false};if(!config.silent){new this.SlothletWarning("V2_CONFIG_UNSUPPORTED",{option:"allowMutation",replacement:"api.mutations: { add: false, remove: false, reload: false }",hint:"The allowMutation config option was part of v2. Use api.mutations for granular control in v3."})}}let collision=null;if(config.collision&&!config.api?.collision){collision=this.normalizeCollision(config.collision);if(!config.silent){new this.SlothletWarning("V2_CONFIG_UNSUPPORTED",{option:"collision",replacement:"api.collision",hint:"Root-level collision config was part of v2. Use api.collision in v3."})}}const apiConfig=config.api||{};const finalCollision=apiConfig.collision?this.normalizeCollision(apiConfig.collision):collision||this.normalizeCollision(null);const finalMutations=apiConfig.mutations?this.normalizeMutations(apiConfig.mutations):mutations||this.normalizeMutations(null);let scopeConfig=config.scope;if(scopeConfig&&typeof scopeConfig==="object"&&scopeConfig.merge){const validMergeStrategies=["shallow","deep"];if(!validMergeStrategies.includes(scopeConfig.merge)){throw new this.SlothletError("INVALID_CONFIG",{option:"scope.merge",value:scopeConfig.merge,expected:validMergeStrategies.join(" or "),hint:`Invalid merge strategy: "${scopeConfig.merge}". Must be "shallow" or "deep".`,validationError:true},null,{validationError:true})}}let hookConfig={enabled:false,pattern:"**",suppressErrors:false};if(config.hook===true||config.hook===false){hookConfig.enabled=config.hook;hookConfig.pattern=config.hook?"**":null}else if(typeof config.hook==="string"){hookConfig.enabled=true;hookConfig.pattern=config.hook}else if(config.hook&&typeof config.hook==="object"){hookConfig.enabled=config.hook.enabled!==false;hookConfig.pattern=config.hook.pattern||"**";hookConfig.suppressErrors=config.hook.suppressErrors||false}let trackingConfig={materialization:false};if(config.tracking===true||config.tracking===false){trackingConfig.materialization=config.tracking}else if(config.tracking&&typeof config.tracking==="object"){trackingConfig.materialization=config.tracking.materialization===true}if(config.backgroundMaterialize===true){trackingConfig.materialization=true}if(config.versionDispatcher!==void 0&&config.versionDispatcher!==null){if(typeof config.versionDispatcher!=="string"&&typeof config.versionDispatcher!=="function"){throw new this.SlothletError("INVALID_CONFIG_VERSION_DISPATCHER",{received:typeof config.versionDispatcher,validationError:true})}}const permissionsConfig=this.normalizePermissions(config.permissions);const suppressFixes=this.normalizeSuppressFixes(config.suppressFixes,config.silent);let i18nConfig=null;if(config.i18n&&typeof config.i18n==="object"){i18nConfig={language:typeof config.i18n.language==="string"?config.i18n.language:void 0}}return{...config,base:resolvedDir,dir:resolvedDir,manifest:config.manifest??null,resolveModuleSpecifier:config.resolveModuleSpecifier??null,envTarget,mode:this.normalizeMode(config.mode),runtime:this.normalizeRuntime(config.runtime),apiDepth:config.apiDepth!==void 0?config.apiDepth:Infinity,reference:config.reference||null,context:config.context||null,i18n:i18nConfig,debug:this.normalizeDebug(config.debug),diagnostics:config.diagnostics===true,hook:hookConfig,collision:finalCollision,api:{collision:finalCollision,mutations:finalMutations},scope:scopeConfig,tracking:trackingConfig,backgroundMaterialize:config.backgroundMaterialize===true,silent:config.silent===true,typescript:this.normalizeTypeScript(config.typescript),env:this.normalizeEnv(config.env),versionDispatcher:config.versionDispatcher??null,permissions:permissionsConfig,suppressFixes}}normalizeSuppressFixes(suppressFixes,silent){const KNOWN_FIX_IDS=new Set(["C03_116"]);const REPO_PR_BASE="https://github.com/CLDMV/slothlet/pull/";if(!Array.isArray(suppressFixes)||suppressFixes.length===0){return new Set}const result=new Set;for(const rule of suppressFixes){if(typeof rule!=="string"||!KNOWN_FIX_IDS.has(rule)){continue}result.add(rule);if(!silent){const prNumber=rule.split("_").pop();const url=`${REPO_PR_BASE}${prNumber}`;new this.SlothletWarning("WARN_SUPPRESS_FIX_ACTIVE",{rule,url})}}return result}normalizeTypeScript(typescript){if(!typescript){return null}if(typescript===true){return{enabled:true,mode:"fast"}}if(typeof typescript==="string"){const mode=typescript.toLowerCase();if(mode==="fast"||mode==="strict"){return{enabled:true,mode}}return{enabled:true,mode:"fast"}}if(typeof typescript==="object"){const mode=typescript.mode==="strict"?"strict":"fast";return{enabled:true,mode,types:typescript.types||null,target:typescript.target||"es2020",sourcemap:typescript.sourcemap||false}}return null}normalizeEnv(env){if(!env||typeof env!=="object"){return null}const include=Array.isArray(env.include)?env.include.filter(k=>typeof k==="string"):null;if(include&&include.length>0){return{include}}return null}normalizePermissions(permissions){if(!permissions||typeof permissions!=="object"){return null}let defaultPolicy;if(permissions.defaultPolicy==="deny"){defaultPolicy="deny"}else if(permissions.defaultPolicy==="allow"||permissions.defaultPolicy===void 0){defaultPolicy="allow"}else{throw new SlothletError("INVALID_CONFIG",{option:"permissions.defaultPolicy",value:permissions.defaultPolicy,expected:'"allow" or "deny"',hint:"HINT_INVALID_CONFIG"},null,{validationError:true})}const enabled=permissions.enabled!==false;let audit;if(permissions.audit==="verbose"){audit="verbose"}else if(permissions.audit==="default"||permissions.audit===void 0){audit="default"}else if(permissions.audit===true){audit="default"}else if(permissions.audit===false){audit="default"}else{throw new SlothletError("INVALID_CONFIG",{option:"permissions.audit",value:permissions.audit,expected:'"default" or "verbose"',hint:"HINT_INVALID_CONFIG"},null,{validationError:true})}let readGating;if(permissions.readGating===false){readGating=false}else if(permissions.readGating===true||permissions.readGating===void 0){readGating=true}else{throw new SlothletError("INVALID_CONFIG",{option:"permissions.readGating",value:permissions.readGating,expected:"boolean",hint:"HINT_INVALID_CONFIG"},null,{validationError:true})}if(permissions.rules!==void 0&&!Array.isArray(permissions.rules)){throw new SlothletError("INVALID_CONFIG",{option:"permissions.rules",value:permissions.rules,expected:"array",hint:"HINT_INVALID_CONFIG"},null,{validationError:true})}const rules=Array.isArray(permissions.rules)?permissions.rules:[];return{defaultPolicy,enabled,audit,readGating,rules}}}export{Config};
17
+ import{ComponentBase}from"@cldmv/slothlet/factories/component-base";import{SlothletError}from"@cldmv/slothlet/errors";import{isNode as IS_NODE}from"@cldmv/slothlet/helpers/platform";function normalizeHookConfig(hook){const hookConfig={enabled:false,pattern:"**",suppressErrors:false};if(hook===true||hook===false){hookConfig.enabled=hook;hookConfig.pattern=hook?"**":null}else if(typeof hook==="string"){hookConfig.enabled=true;hookConfig.pattern=hook}else if(hook&&typeof hook==="object"){hookConfig.enabled=hook.enabled!==false;hookConfig.pattern=hook.pattern||"**";hookConfig.suppressErrors=hook.suppressErrors||false}return hookConfig}class Config extends ComponentBase{static slothletProperty="config";normalizeCollision(collision){const validModes=["skip","warn","replace","merge","merge-replace","error"];const defaultMode="merge";if(typeof collision==="string"){const normalized=collision.toLowerCase();const mode=validModes.includes(normalized)?normalized:defaultMode;return{initial:mode,api:mode}}if(collision&&typeof collision==="object"){const validateMode=m=>{if(!m)return defaultMode;const normalized=String(m).toLowerCase();return validModes.includes(normalized)?normalized:defaultMode};return{initial:validateMode(collision.initial),api:validateMode(collision.api)}}return{initial:defaultMode,api:defaultMode}}normalizeRuntime(runtime){if(!runtime||typeof runtime!=="string"){return"async"}const normalized=runtime.toLowerCase().trim();if(normalized==="async"||normalized==="asynclocal"||normalized==="asynclocalstorage"){return"async"}if(normalized==="live"||normalized==="livebindings"||normalized==="experimental"){return"live"}return"async"}normalizeMode(mode){if(!mode||typeof mode!=="string"){return"eager"}const normalized=mode.toLowerCase().trim();if(normalized==="lazy"||normalized==="deferred"||normalized==="proxy"){return"lazy"}if(normalized==="eager"||normalized==="immediate"||normalized==="preload"){return"eager"}return"eager"}normalizeMutations(mutations){const defaults={add:true,remove:true,reload:true,permissions:true};if(!mutations||typeof mutations!=="object"){return defaults}return{add:mutations.add===false?false:true,remove:mutations.remove===false?false:true,reload:mutations.reload===false?false:true,permissions:mutations.permissions===false?false:true}}normalizeDebug(debug){if(!debug){return{builder:false,api:false,index:false,modes:false,wrapper:false,ownership:false,context:false,initialization:false,materialize:false,versioning:false,permissions:false}}if(debug===true){return{builder:true,api:true,index:true,modes:true,wrapper:true,ownership:true,context:true,initialization:true,materialize:true,versioning:true,permissions:true}}if(typeof debug==="object"){return{builder:debug.builder||false,api:debug.api||false,index:debug.index||false,modes:debug.modes||false,wrapper:debug.wrapper||false,ownership:debug.ownership||false,context:debug.context||false,initialization:debug.initialization||false,materialize:debug.materialize||false,versioning:debug.versioning||false,permissions:debug.permissions||false}}return{builder:false,api:false,index:false,modes:false,wrapper:false,ownership:false,context:false,initialization:false,materialize:false,versioning:false,permissions:false}}normalizeEnvTarget(platform,hasManifest=false){if(platform==="browser")return"browser";if(platform==="node")return"node";if(hasManifest)return"browser";return IS_NODE?"node":"browser"}normalizeHook(hook){return normalizeHookConfig(hook)}transformConfig(config={}){const hasManifest=config.manifest!=null;const envTarget=this.normalizeEnvTarget(config.platform,hasManifest);const rawBase=config.base??config.dir;if(config.dir!==void 0&&config.base===void 0&&!config.silent){new this.SlothletWarning("V3_CONFIG_DEPRECATED",{option:"dir",replacement:"base"})}if(!rawBase){throw new this.SlothletError("INVALID_CONFIG_DIR_MISSING",{},null,{validationError:true})}if(envTarget==="browser"){if(!config.manifest||typeof config.manifest!=="object"||Array.isArray(config.manifest)){throw new this.SlothletError("INVALID_CONFIG_BROWSER_REQUIRES_MANIFEST",{},null,{validationError:true})}if(!Array.isArray(config.manifest.files)||!Array.isArray(config.manifest.directories)){throw new this.SlothletError("INVALID_CONFIG_BROWSER_MANIFEST_INVALID",{received:typeof config.manifest},null,{validationError:true})}if(config.resolveModuleSpecifier!==void 0&&config.resolveModuleSpecifier!==null&&typeof config.resolveModuleSpecifier!=="function"){throw new this.SlothletError("INVALID_CONFIG_BROWSER_RESOLVE_SPECIFIER_INVALID",{received:typeof config.resolveModuleSpecifier},null,{validationError:true})}}const resolvedDir=envTarget==="browser"?rawBase:this.slothlet.helpers.resolver.resolvePathFromCaller(rawBase);let mutations=null;if(config.allowMutation===false){mutations={add:false,remove:false,reload:false};if(!config.silent){new this.SlothletWarning("V2_CONFIG_UNSUPPORTED",{option:"allowMutation",replacement:"api.mutations: { add: false, remove: false, reload: false }",hint:"The allowMutation config option was part of v2. Use api.mutations for granular control in v3."})}}let collision=null;if(config.collision&&!config.api?.collision){collision=this.normalizeCollision(config.collision);if(!config.silent){new this.SlothletWarning("V2_CONFIG_UNSUPPORTED",{option:"collision",replacement:"api.collision",hint:"Root-level collision config was part of v2. Use api.collision in v3."})}}const apiConfig=config.api||{};const finalCollision=apiConfig.collision?this.normalizeCollision(apiConfig.collision):collision||this.normalizeCollision(null);const finalMutations=apiConfig.mutations?this.normalizeMutations(apiConfig.mutations):mutations||this.normalizeMutations(null);let scopeConfig=config.scope;if(scopeConfig&&typeof scopeConfig==="object"&&scopeConfig.merge){const validMergeStrategies=["shallow","deep"];if(!validMergeStrategies.includes(scopeConfig.merge)){throw new this.SlothletError("INVALID_CONFIG",{option:"scope.merge",value:scopeConfig.merge,expected:validMergeStrategies.join(" or "),hint:`Invalid merge strategy: "${scopeConfig.merge}". Must be "shallow" or "deep".`,validationError:true},null,{validationError:true})}}const hookConfig=this.normalizeHook(config.hook);let trackingConfig={materialization:false};if(config.tracking===true||config.tracking===false){trackingConfig.materialization=config.tracking}else if(config.tracking&&typeof config.tracking==="object"){trackingConfig.materialization=config.tracking.materialization===true}if(config.backgroundMaterialize===true){trackingConfig.materialization=true}if(config.versionDispatcher!==void 0&&config.versionDispatcher!==null){if(typeof config.versionDispatcher!=="string"&&typeof config.versionDispatcher!=="function"){throw new this.SlothletError("INVALID_CONFIG_VERSION_DISPATCHER",{received:typeof config.versionDispatcher,validationError:true})}}const permissionsConfig=this.normalizePermissions(config.permissions);const suppressFixes=this.normalizeSuppressFixes(config.suppressFixes,config.silent);let i18nConfig=null;if(config.i18n&&typeof config.i18n==="object"){i18nConfig={language:typeof config.i18n.language==="string"?config.i18n.language:void 0}}return{...config,base:resolvedDir,dir:resolvedDir,manifest:config.manifest??null,resolveModuleSpecifier:config.resolveModuleSpecifier??null,envTarget,mode:this.normalizeMode(config.mode),runtime:this.normalizeRuntime(config.runtime),apiDepth:config.apiDepth!==void 0?config.apiDepth:Infinity,reference:config.reference||null,context:config.context||null,i18n:i18nConfig,debug:this.normalizeDebug(config.debug),diagnostics:config.diagnostics===true,hook:hookConfig,collision:finalCollision,api:{collision:finalCollision,mutations:finalMutations},scope:scopeConfig,tracking:trackingConfig,backgroundMaterialize:config.backgroundMaterialize===true,silent:config.silent===true,typescript:this.normalizeTypeScript(config.typescript),env:this.normalizeEnv(config.env),versionDispatcher:config.versionDispatcher??null,permissions:permissionsConfig,suppressFixes}}normalizeSuppressFixes(suppressFixes,silent){const KNOWN_FIX_IDS=new Set(["C03_116"]);const REPO_PR_BASE="https://github.com/CLDMV/slothlet/pull/";if(!Array.isArray(suppressFixes)||suppressFixes.length===0){return new Set}const result=new Set;for(const rule of suppressFixes){if(typeof rule!=="string"||!KNOWN_FIX_IDS.has(rule)){continue}result.add(rule);if(!silent){const prNumber=rule.split("_").pop();const url=`${REPO_PR_BASE}${prNumber}`;new this.SlothletWarning("WARN_SUPPRESS_FIX_ACTIVE",{rule,url})}}return result}normalizeTypeScript(typescript){if(!typescript){return null}if(typescript===true){return{enabled:true,mode:"fast"}}if(typeof typescript==="string"){const mode=typescript.toLowerCase();if(mode==="fast"||mode==="strict"){return{enabled:true,mode}}return{enabled:true,mode:"fast"}}if(typeof typescript==="object"){const mode=typescript.mode==="strict"?"strict":"fast";return{enabled:true,mode,types:typescript.types||null,target:typescript.target||"es2020",sourcemap:typescript.sourcemap||false}}return null}normalizeEnv(env){if(!env||typeof env!=="object"){return null}const include=Array.isArray(env.include)?env.include.filter(k=>typeof k==="string"):null;if(include&&include.length>0){return{include}}return null}normalizePermissions(permissions){if(!permissions||typeof permissions!=="object"){return null}let defaultPolicy;if(permissions.defaultPolicy==="deny"){defaultPolicy="deny"}else if(permissions.defaultPolicy==="allow"||permissions.defaultPolicy===void 0){defaultPolicy="allow"}else{throw new SlothletError("INVALID_CONFIG",{option:"permissions.defaultPolicy",value:permissions.defaultPolicy,expected:'"allow" or "deny"',hint:"HINT_INVALID_CONFIG"},null,{validationError:true})}const enabled=permissions.enabled!==false;let audit;if(permissions.audit==="verbose"){audit="verbose"}else if(permissions.audit==="default"||permissions.audit===void 0){audit="default"}else if(permissions.audit===true){audit="default"}else if(permissions.audit===false){audit="default"}else{throw new SlothletError("INVALID_CONFIG",{option:"permissions.audit",value:permissions.audit,expected:'"default" or "verbose"',hint:"HINT_INVALID_CONFIG"},null,{validationError:true})}let readGating;if(permissions.readGating===false){readGating=false}else if(permissions.readGating===true||permissions.readGating===void 0){readGating=true}else{throw new SlothletError("INVALID_CONFIG",{option:"permissions.readGating",value:permissions.readGating,expected:"boolean",hint:"HINT_INVALID_CONFIG"},null,{validationError:true})}if(permissions.rules!==void 0&&!Array.isArray(permissions.rules)){throw new SlothletError("INVALID_CONFIG",{option:"permissions.rules",value:permissions.rules,expected:"array",hint:"HINT_INVALID_CONFIG"},null,{validationError:true})}const rules=Array.isArray(permissions.rules)?permissions.rules:[];return{defaultPolicy,enabled,audit,readGating,rules}}}export{Config,normalizeHookConfig};
@@ -14,4 +14,4 @@
14
14
  limitations under the License.
15
15
  */
16
16
 
17
- import{EventEmitter}from"node:events";import{AsyncResource}from"node:async_hooks";let isInApiContext=null;function setApiContextChecker(checker){isInApiContext=checker}const originalMethods=new Map;const wrappedListeners=new Map;const trackedEmitters=new Set;let isPatchingEnabled=false;function runtime_wrapEventListener(listener){const resource=new AsyncResource("slothlet-event-listener");const runtime_wrappedListener=function(...args){return resource.runInAsyncScope(()=>{return listener.apply(this,args)},this)};runtime_wrappedListener._slothletOriginal=listener;runtime_wrappedListener._slothletResource=resource;return runtime_wrappedListener}function runtime_getListenerTracking(emitter){let emitterTracking=wrappedListeners.get(emitter);if(!emitterTracking){emitterTracking=new Map;wrappedListeners.set(emitter,emitterTracking)}return emitterTracking}function runtime_trackListener(emitter,event,originalListener,wrappedListener){const emitterTracking=runtime_getListenerTracking(emitter);let eventTracking=emitterTracking.get(event);if(!eventTracking){eventTracking=new Map;emitterTracking.set(event,eventTracking)}let wrappers=eventTracking.get(originalListener);if(!wrappers){wrappers=[];eventTracking.set(originalListener,wrappers)}wrappers.push(wrappedListener)}function runtime_getWrappedListener(emitter,event,originalListener){const emitterTracking=wrappedListeners.get(emitter);if(!emitterTracking)return void 0;const eventTracking=emitterTracking.get(event);if(!eventTracking)return void 0;const wrappers=eventTracking.get(originalListener);if(!wrappers||wrappers.length===0)return void 0;return wrappers[wrappers.length-1]}function runtime_untrackListener(emitter,event,originalListener){const emitterTracking=wrappedListeners.get(emitter);if(!emitterTracking)return;const eventTracking=emitterTracking.get(event);if(!eventTracking)return;const wrappers=eventTracking.get(originalListener);if(!wrappers||wrappers.length===0)return;const wrappedListener=wrappers.pop();wrappedListener._slothletResource=null;if(wrappers.length===0){eventTracking.delete(originalListener)}if(eventTracking.size===0){emitterTracking.delete(event)}if(emitterTracking.size===0){wrappedListeners.delete(emitter)}}function runtime_untrackSpecificWrapper(emitter,event,originalListener,wrappedListener){const emitterTracking=wrappedListeners.get(emitter);if(!emitterTracking)return;const eventTracking=emitterTracking.get(event);if(!eventTracking)return;const wrappers=eventTracking.get(originalListener);if(!wrappers||wrappers.length===0)return;const idx=wrappers.indexOf(wrappedListener);if(idx===-1)return;wrappers.splice(idx,1);wrappedListener._slothletResource=null;if(wrappers.length===0){eventTracking.delete(originalListener)}if(eventTracking.size===0){emitterTracking.delete(event)}if(emitterTracking.size===0){wrappedListeners.delete(emitter)}}function runtime_shouldWrapListener(listener){if(typeof listener!=="function")return false;if(listener._slothletOriginal)return false;return true}function runtime_maybeTrackEmitter(emitter){if(isInApiContext&&isInApiContext()){trackedEmitters.add(emitter)}}function runtime_patchOn(){const original=EventEmitter.prototype.on;originalMethods.set("on",original);EventEmitter.prototype.on=function(event,listener){runtime_maybeTrackEmitter(this);if(!runtime_shouldWrapListener(listener)){return original.call(this,event,listener)}const wrapped=runtime_wrapEventListener(listener);runtime_trackListener(this,event,listener,wrapped);return original.call(this,event,wrapped)};EventEmitter.prototype.addListener=EventEmitter.prototype.on}function runtime_patchOnce(){const original=EventEmitter.prototype.once;originalMethods.set("once",original);const originalOn=originalMethods.get("on")??EventEmitter.prototype.on;const originalRemove=originalMethods.get("removeListener")??EventEmitter.prototype.removeListener;EventEmitter.prototype.once=function(event,listener){runtime_maybeTrackEmitter(this);if(!runtime_shouldWrapListener(listener)){return original.call(this,event,listener)}const wrapped=runtime_wrapEventListener(listener);const self=this;const runtime_onceWrapper=function(...args){originalRemove.call(self,event,runtime_onceWrapper);runtime_untrackSpecificWrapper(self,event,listener,runtime_onceWrapper);return wrapped.apply(this,args)};runtime_onceWrapper._slothletOriginal=listener;runtime_onceWrapper._slothletResource=wrapped._slothletResource;runtime_onceWrapper.listener=listener;runtime_trackListener(this,event,listener,runtime_onceWrapper);return originalOn.call(this,event,runtime_onceWrapper)}}function runtime_patchPrependListener(){const original=EventEmitter.prototype.prependListener;originalMethods.set("prependListener",original);EventEmitter.prototype.prependListener=function(event,listener){runtime_maybeTrackEmitter(this);if(!runtime_shouldWrapListener(listener)){return original.call(this,event,listener)}const wrapped=runtime_wrapEventListener(listener);runtime_trackListener(this,event,listener,wrapped);return original.call(this,event,wrapped)}}function runtime_patchPrependOnceListener(){const original=EventEmitter.prototype.prependOnceListener;originalMethods.set("prependOnceListener",original);const originalPrepend=originalMethods.get("prependListener")??EventEmitter.prototype.prependListener;const originalRemove=originalMethods.get("removeListener")??EventEmitter.prototype.removeListener;EventEmitter.prototype.prependOnceListener=function(event,listener){runtime_maybeTrackEmitter(this);if(!runtime_shouldWrapListener(listener)){return original.call(this,event,listener)}const wrapped=runtime_wrapEventListener(listener);const self=this;const runtime_onceWrapper=function(...args){originalRemove.call(self,event,runtime_onceWrapper);runtime_untrackSpecificWrapper(self,event,listener,runtime_onceWrapper);return wrapped.apply(this,args)};runtime_onceWrapper._slothletOriginal=listener;runtime_onceWrapper._slothletResource=wrapped._slothletResource;runtime_onceWrapper.listener=listener;runtime_trackListener(this,event,listener,runtime_onceWrapper);return originalPrepend.call(this,event,runtime_onceWrapper)}}function runtime_patchRemoveListener(){const original=EventEmitter.prototype.removeListener;originalMethods.set("removeListener",original);EventEmitter.prototype.removeListener=function(event,listener){const wrapped=runtime_getWrappedListener(this,event,listener);if(wrapped){const result=original.call(this,event,wrapped);runtime_untrackListener(this,event,listener);return result}return original.call(this,event,listener)};EventEmitter.prototype.off=EventEmitter.prototype.removeListener}function runtime_patchRemoveAllListeners(){const original=EventEmitter.prototype.removeAllListeners;originalMethods.set("removeAllListeners",original);EventEmitter.prototype.removeAllListeners=function(event){const emitterTracking=wrappedListeners.get(this);if(emitterTracking){if(event===void 0){for(const[____evt,eventTracking]of emitterTracking.entries()){for(const wrappers of eventTracking.values()){for(const wrappedListener of wrappers){wrappedListener._slothletResource=null}}}wrappedListeners.delete(this)}else{const eventTracking=emitterTracking.get(event);if(eventTracking){for(const wrappers of eventTracking.values()){for(const wrappedListener of wrappers){wrappedListener._slothletResource=null}}emitterTracking.delete(event);if(emitterTracking.size===0){wrappedListeners.delete(this)}}}}return original.call(this,event)}}function enableEventEmitterPatching(){if(isPatchingEnabled){return}runtime_patchOn();runtime_patchOnce();runtime_patchPrependListener();runtime_patchPrependOnceListener();runtime_patchRemoveListener();runtime_patchRemoveAllListeners();isPatchingEnabled=true}function disableEventEmitterPatching(){if(!isPatchingEnabled){return}for(const[methodName,originalMethod]of originalMethods.entries()){EventEmitter.prototype[methodName]=originalMethod;if(methodName==="on"){EventEmitter.prototype.addListener=originalMethod}else if(methodName==="removeListener"){EventEmitter.prototype.off=originalMethod}}originalMethods.clear();isPatchingEnabled=false}function cleanupEventEmitterResources(){for(const emitter of trackedEmitters){try{emitter.removeAllListeners()}catch(____error){}}trackedEmitters.clear();wrappedListeners.clear()}export{cleanupEventEmitterResources,disableEventEmitterPatching,enableEventEmitterPatching,setApiContextChecker};
17
+ import{EventEmitter,AsyncResource}from"@cldmv/slothlet/helpers/platform";let isInApiContext=null;function setApiContextChecker(checker){isInApiContext=checker}const originalMethods=new Map;const wrappedListeners=new Map;const trackedEmitters=new Set;let isPatchingEnabled=false;function runtime_wrapEventListener(listener){const resource=new AsyncResource("slothlet-event-listener");const runtime_wrappedListener=function(...args){return resource.runInAsyncScope(()=>{return listener.apply(this,args)},this)};runtime_wrappedListener._slothletOriginal=listener;runtime_wrappedListener._slothletResource=resource;return runtime_wrappedListener}function runtime_getListenerTracking(emitter){let emitterTracking=wrappedListeners.get(emitter);if(!emitterTracking){emitterTracking=new Map;wrappedListeners.set(emitter,emitterTracking)}return emitterTracking}function runtime_trackListener(emitter,event,originalListener,wrappedListener){const emitterTracking=runtime_getListenerTracking(emitter);let eventTracking=emitterTracking.get(event);if(!eventTracking){eventTracking=new Map;emitterTracking.set(event,eventTracking)}let wrappers=eventTracking.get(originalListener);if(!wrappers){wrappers=[];eventTracking.set(originalListener,wrappers)}wrappers.push(wrappedListener)}function runtime_getWrappedListener(emitter,event,originalListener){const emitterTracking=wrappedListeners.get(emitter);if(!emitterTracking)return void 0;const eventTracking=emitterTracking.get(event);if(!eventTracking)return void 0;const wrappers=eventTracking.get(originalListener);if(!wrappers||wrappers.length===0)return void 0;return wrappers[wrappers.length-1]}function runtime_untrackListener(emitter,event,originalListener){const emitterTracking=wrappedListeners.get(emitter);if(!emitterTracking)return;const eventTracking=emitterTracking.get(event);if(!eventTracking)return;const wrappers=eventTracking.get(originalListener);if(!wrappers||wrappers.length===0)return;const wrappedListener=wrappers.pop();wrappedListener._slothletResource=null;if(wrappers.length===0){eventTracking.delete(originalListener)}if(eventTracking.size===0){emitterTracking.delete(event)}if(emitterTracking.size===0){wrappedListeners.delete(emitter)}}function runtime_untrackSpecificWrapper(emitter,event,originalListener,wrappedListener){const emitterTracking=wrappedListeners.get(emitter);if(!emitterTracking)return;const eventTracking=emitterTracking.get(event);if(!eventTracking)return;const wrappers=eventTracking.get(originalListener);if(!wrappers||wrappers.length===0)return;const idx=wrappers.indexOf(wrappedListener);if(idx===-1)return;wrappers.splice(idx,1);wrappedListener._slothletResource=null;if(wrappers.length===0){eventTracking.delete(originalListener)}if(eventTracking.size===0){emitterTracking.delete(event)}if(emitterTracking.size===0){wrappedListeners.delete(emitter)}}function runtime_shouldWrapListener(listener){if(typeof listener!=="function")return false;if(listener._slothletOriginal)return false;return true}function runtime_maybeTrackEmitter(emitter){if(isInApiContext&&isInApiContext()){trackedEmitters.add(emitter)}}function runtime_patchOn(){const original=EventEmitter.prototype.on;originalMethods.set("on",original);EventEmitter.prototype.on=function(event,listener){runtime_maybeTrackEmitter(this);if(!runtime_shouldWrapListener(listener)){return original.call(this,event,listener)}const wrapped=runtime_wrapEventListener(listener);runtime_trackListener(this,event,listener,wrapped);return original.call(this,event,wrapped)};EventEmitter.prototype.addListener=EventEmitter.prototype.on}function runtime_patchOnce(){const original=EventEmitter.prototype.once;originalMethods.set("once",original);const originalOn=originalMethods.get("on")??EventEmitter.prototype.on;const originalRemove=originalMethods.get("removeListener")??EventEmitter.prototype.removeListener;EventEmitter.prototype.once=function(event,listener){runtime_maybeTrackEmitter(this);if(!runtime_shouldWrapListener(listener)){return original.call(this,event,listener)}const wrapped=runtime_wrapEventListener(listener);const self=this;const runtime_onceWrapper=function(...args){originalRemove.call(self,event,runtime_onceWrapper);runtime_untrackSpecificWrapper(self,event,listener,runtime_onceWrapper);return wrapped.apply(this,args)};runtime_onceWrapper._slothletOriginal=listener;runtime_onceWrapper._slothletResource=wrapped._slothletResource;runtime_onceWrapper.listener=listener;runtime_trackListener(this,event,listener,runtime_onceWrapper);return originalOn.call(this,event,runtime_onceWrapper)}}function runtime_patchPrependListener(){const original=EventEmitter.prototype.prependListener;originalMethods.set("prependListener",original);EventEmitter.prototype.prependListener=function(event,listener){runtime_maybeTrackEmitter(this);if(!runtime_shouldWrapListener(listener)){return original.call(this,event,listener)}const wrapped=runtime_wrapEventListener(listener);runtime_trackListener(this,event,listener,wrapped);return original.call(this,event,wrapped)}}function runtime_patchPrependOnceListener(){const original=EventEmitter.prototype.prependOnceListener;originalMethods.set("prependOnceListener",original);const originalPrepend=originalMethods.get("prependListener")??EventEmitter.prototype.prependListener;const originalRemove=originalMethods.get("removeListener")??EventEmitter.prototype.removeListener;EventEmitter.prototype.prependOnceListener=function(event,listener){runtime_maybeTrackEmitter(this);if(!runtime_shouldWrapListener(listener)){return original.call(this,event,listener)}const wrapped=runtime_wrapEventListener(listener);const self=this;const runtime_onceWrapper=function(...args){originalRemove.call(self,event,runtime_onceWrapper);runtime_untrackSpecificWrapper(self,event,listener,runtime_onceWrapper);return wrapped.apply(this,args)};runtime_onceWrapper._slothletOriginal=listener;runtime_onceWrapper._slothletResource=wrapped._slothletResource;runtime_onceWrapper.listener=listener;runtime_trackListener(this,event,listener,runtime_onceWrapper);return originalPrepend.call(this,event,runtime_onceWrapper)}}function runtime_patchRemoveListener(){const original=EventEmitter.prototype.removeListener;originalMethods.set("removeListener",original);EventEmitter.prototype.removeListener=function(event,listener){const wrapped=runtime_getWrappedListener(this,event,listener);if(wrapped){const result=original.call(this,event,wrapped);runtime_untrackListener(this,event,listener);return result}return original.call(this,event,listener)};EventEmitter.prototype.off=EventEmitter.prototype.removeListener}function runtime_patchRemoveAllListeners(){const original=EventEmitter.prototype.removeAllListeners;originalMethods.set("removeAllListeners",original);EventEmitter.prototype.removeAllListeners=function(event){const emitterTracking=wrappedListeners.get(this);if(emitterTracking){if(event===void 0){for(const[____evt,eventTracking]of emitterTracking.entries()){for(const wrappers of eventTracking.values()){for(const wrappedListener of wrappers){wrappedListener._slothletResource=null}}}wrappedListeners.delete(this)}else{const eventTracking=emitterTracking.get(event);if(eventTracking){for(const wrappers of eventTracking.values()){for(const wrappedListener of wrappers){wrappedListener._slothletResource=null}}emitterTracking.delete(event);if(emitterTracking.size===0){wrappedListeners.delete(this)}}}}return original.call(this,event)}}function enableEventEmitterPatching(){if(!EventEmitter)return;if(isPatchingEnabled){return}runtime_patchOn();runtime_patchOnce();runtime_patchPrependListener();runtime_patchPrependOnceListener();runtime_patchRemoveListener();runtime_patchRemoveAllListeners();isPatchingEnabled=true}function disableEventEmitterPatching(){if(!EventEmitter)return;if(!isPatchingEnabled){return}for(const[methodName,originalMethod]of originalMethods.entries()){EventEmitter.prototype[methodName]=originalMethod;if(methodName==="on"){EventEmitter.prototype.addListener=originalMethod}else if(methodName==="removeListener"){EventEmitter.prototype.off=originalMethod}}originalMethods.clear();isPatchingEnabled=false}function cleanupEventEmitterResources(){if(!EventEmitter)return;for(const emitter of trackedEmitters){try{emitter.removeAllListeners()}catch(____error){}}trackedEmitters.clear();wrappedListeners.clear()}export{cleanupEventEmitterResources,disableEventEmitterPatching,enableEventEmitterPatching,setApiContextChecker};
@@ -14,4 +14,4 @@
14
14
  limitations under the License.
15
15
  */
16
16
 
17
- import fs from"node:fs/promises";import path from"node:path";const LOADABLE_EXTENSIONS=new Set([".mjs",".cjs",".js",".ts",".mts",".cts"]);const SKIP_PREFIXES=["__","."];function isApiFile(filename){const ext=path.extname(filename);return LOADABLE_EXTENSIONS.has(ext)}function makeFileEntry(relativePath){const fullName=path.basename(relativePath);const name=path.basename(relativePath,path.extname(relativePath));return{path:relativePath,name,fullName}}async function scanDir(absDir,rootDir){let entries;try{entries=await fs.readdir(absDir,{withFileTypes:true})}catch{return{files:[],directories:[]}}const files=[];const directories=[];for(const entry of entries){if(SKIP_PREFIXES.some(p=>entry.name.startsWith(p)))continue;if(entry.isFile()){if(isApiFile(entry.name)){const absPath=path.join(absDir,entry.name);const rel=path.relative(rootDir,absPath).replace(/\\/g,"/");files.push(makeFileEntry(rel))}}else if(entry.isDirectory()){const absSubDir=path.join(absDir,entry.name);const relDir=path.relative(rootDir,absSubDir).replace(/\\/g,"/");const children=await scanDir(absSubDir,rootDir);if(children.files.length>0||children.directories.length>0){directories.push({name:entry.name,path:relDir,children})}}}return{files,directories}}async function generateManifest(dir){if(!dir||typeof dir!=="string"){throw new Error(`generateManifest: dir must be a non-empty string, received ${typeof dir}`)}const absDir=path.resolve(dir);let stat;try{stat=await fs.stat(absDir)}catch(err){throw new Error(`generateManifest: cannot read directory "${absDir}": ${err.message}`)}if(!stat.isDirectory()){throw new Error(`generateManifest: "${absDir}" is not a directory`)}return scanDir(absDir,absDir)}export{generateManifest};
17
+ import fs from"node:fs/promises";import path from"node:path";import{fileURLToPath}from"node:url";const SLOTHLET_SPEC_RE=/["'](@cldmv\/slothlet(?:\/[^"']+)?)["']/g;const DEFAULT_SLOTHLET_BASE="/node_modules/@cldmv/slothlet/";const LOADABLE_EXTENSIONS=new Set([".mjs",".cjs",".js",".ts",".mts",".cts"]);const SKIP_PREFIXES=["__","."];function isApiFile(filename){const ext=path.extname(filename);return LOADABLE_EXTENSIONS.has(ext)}function makeFileEntry(relativePath){const fullName=path.basename(relativePath);const name=path.basename(relativePath,path.extname(relativePath));return{path:relativePath,name,fullName}}async function scanDir(absDir,rootDir){let entries;try{entries=await fs.readdir(absDir,{withFileTypes:true})}catch{return{files:[],directories:[]}}const files=[];const directories=[];for(const entry of entries){if(SKIP_PREFIXES.some(p=>entry.name.startsWith(p)))continue;if(entry.isFile()){if(isApiFile(entry.name)){const absPath=path.join(absDir,entry.name);const rel=path.relative(rootDir,absPath).replace(/\\/g,"/");files.push(makeFileEntry(rel))}}else if(entry.isDirectory()){const absSubDir=path.join(absDir,entry.name);const relDir=path.relative(rootDir,absSubDir).replace(/\\/g,"/");const children=await scanDir(absSubDir,rootDir);if(children.files.length>0||children.directories.length>0){directories.push({name:entry.name,path:relDir,children})}}}return{files,directories}}async function generateManifest(dir){if(!dir||typeof dir!=="string"){throw new Error(`generateManifest: dir must be a non-empty string, received ${typeof dir}`)}const absDir=path.resolve(dir);let stat;try{stat=await fs.stat(absDir)}catch(err){throw new Error(`generateManifest: cannot read directory "${absDir}": ${err.message}`,{cause:err})}if(!stat.isDirectory()){throw new Error(`generateManifest: "${absDir}" is not a directory`)}return scanDir(absDir,absDir)}function slothletPackageRoot(){return path.resolve(path.dirname(fileURLToPath(import.meta.url)),"../../..")}async function collectSlothletSpecifiers(root){const specifiers=new Set(["@cldmv/slothlet"]);const SKIP_DIRS=new Set(["node_modules","types","coverage","tmp","tests","api_tests",".git","docs"]);async function scan(dir){const entries=await fs.readdir(dir,{withFileTypes:true});for(const e of entries){if(e.isDirectory()){if(!SKIP_DIRS.has(e.name)&&!e.name.startsWith("."))await scan(path.join(dir,e.name))}else if(/\.(mjs|cjs|js)$/.test(e.name)){const src=await fs.readFile(path.join(dir,e.name),"utf8");let m;SLOTHLET_SPEC_RE.lastIndex=0;while(m=SLOTHLET_SPEC_RE.exec(src)){if(!m[1].startsWith("@cldmv/slothlet/i18n/language/"))specifiers.add(m[1])}}}}await scan(root);return specifiers}async function generateImportMap(slothletBase=DEFAULT_SLOTHLET_BASE){const base=String(slothletBase).endsWith("/")?String(slothletBase):`${slothletBase}/`;const root=slothletPackageRoot();const imports={};for(const spec of await collectSlothletSpecifiers(root)){let resolved;try{resolved=import.meta.resolve(spec)}catch{continue}const rel=path.relative(root,fileURLToPath(resolved)).replace(/\\/g,"/");imports[spec]=base+rel}try{const sampleDir=path.dirname(fileURLToPath(import.meta.resolve("@cldmv/slothlet/i18n/language/en-us.json")));for(const f of(await fs.readdir(sampleDir)).filter(n=>n.endsWith(".json"))){const rel=path.relative(root,path.join(sampleDir,f)).replace(/\\/g,"/");imports[`@cldmv/slothlet/i18n/language/${f}`]=base+rel}}catch{}return{imports}}async function generateBrowserAssets(apiDir,options={}){const{slothletBase=DEFAULT_SLOTHLET_BASE}=options;if(typeof slothletBase!=="string"){throw new Error(`generateBrowserAssets: options.slothletBase must be a string (where @cldmv/slothlet is served in the browser), received ${typeof slothletBase}`)}const[manifest,importmap]=await Promise.all([generateManifest(apiDir),generateImportMap(slothletBase)]);return{manifest,importmap}}export{generateBrowserAssets,generateImportMap,generateManifest};
@@ -14,4 +14,4 @@
14
14
  limitations under the License.
15
15
  */
16
16
 
17
- import{SlothletError}from"@cldmv/slothlet/errors";import{validateModuleManifest}from"@cldmv/slothlet/helpers/module-manifest-validator";const IS_NODE=typeof process!=="undefined"&&Boolean(process.versions?.node);const[fs,path]=IS_NODE?await Promise.all([import("node:fs").then(m=>m.promises),import("node:path").then(m=>m.default)]):[null,null];const DEFAULT_MANIFEST_FILE="slothlet.module.json";const UPWARD_WALK_CAP=20;async function discoverModules(options={}){const scanRoots=await resolveScanRoots(options.scanRoot);const manifestSource=parseManifestSource(options.manifest);const fieldSchema=options.schema??{};const filterFn=options.filter;const prefixes=normalizePrefixes(options.prefix);const candidates=[];for(const root of scanRoots){const mode=await detectScanMode(root);if(mode==="npm"){candidates.push(...await enumerateNpmPackages(root,prefixes))}else{candidates.push(...await enumerateFolderModules(root,prefixes))}}const results=[];const seenRealPaths=new Set;const realPathByNameVersion=new Map;for(const candidate of candidates){let realPath;try{realPath=await fs.realpath(candidate.path)}catch{continue}if(seenRealPaths.has(realPath))continue;seenRealPaths.add(realPath);const pkgJsonPath=path.join(realPath,"package.json");const pkg=await readJsonOrNull(pkgJsonPath);if(!pkg||typeof pkg.name!=="string"||typeof pkg.version!=="string"){continue}const manifestPath=path.join(realPath,manifestSource.file);const manifestRaw=await loadManifestRaw(manifestPath,manifestSource,pkg.name);if(manifestRaw===void 0)continue;const remapped=applySchemaRemap(manifestRaw,fieldSchema);if(manifestSource.isOverride&&remapped.schemaVersion===void 0){remapped.schemaVersion=1}const normalized=validateModuleManifest(remapped,{packageName:pkg.name,packageVersion:pkg.version,packageDescription:pkg.description,packageRoot:realPath,manifestPath});if(typeof filterFn==="function"&&!filterFn(normalized,pkg.name)){continue}const nameVersionKey=`${pkg.name}@${pkg.version}`;if(realPathByNameVersion.has(nameVersionKey)){const otherRealPath=realPathByNameVersion.get(nameVersionKey);if(otherRealPath!==realPath){throw new SlothletError("MODULE_DUPLICATE_NAME_VERSION_MISMATCH",{packageName:pkg.name,version:pkg.version,paths:[otherRealPath,realPath].join(", ")},null,{validationError:true})}}else{realPathByNameVersion.set(nameVersionKey,realPath)}const apiDirAbs=path.resolve(realPath,normalized.apiDir);results.push(Object.freeze({packageName:pkg.name,packageRoot:realPath,mountPath:Object.freeze([...normalized.mountPath]),apiDir:apiDirAbs,manifest:deepFreeze(normalized)}))}return results}async function resolveScanRoots(opt){if(opt===void 0){return[await defaultScanRoot()]}if(typeof opt==="string"){return[path.resolve(opt)]}if(Array.isArray(opt)){return opt.map(p=>path.resolve(p))}throw new SlothletError("INVALID_ARGUMENT",{argument:"scanRoot",expected:"string or string[]",received:typeof opt},null,{validationError:true})}async function defaultScanRoot(){let current=process.cwd();for(let i=0;i<UPWARD_WALK_CAP;i++){try{const stat=await fs.stat(path.join(current,"node_modules"));if(stat.isDirectory())return current}catch{}const parent=path.dirname(current);if(parent===current)break;current=parent}return process.cwd()}async function detectScanMode(root){try{const stat=await fs.stat(path.join(root,"node_modules"));if(stat.isDirectory())return"npm"}catch{}return"folder"}async function enumerateNpmPackages(root,prefixes){const nodeModules=path.join(root,"node_modules");const out=[];let entries;try{entries=await fs.readdir(nodeModules,{withFileTypes:true})}catch{return out}for(const entry of entries){if(!entry.isDirectory()&&!entry.isSymbolicLink())continue;if(entry.name.startsWith("."))continue;if(entry.name.startsWith("@")){const scopeDir=path.join(nodeModules,entry.name);let scopedEntries;try{scopedEntries=await fs.readdir(scopeDir,{withFileTypes:true})}catch{continue}for(const scoped of scopedEntries){if(!scoped.isDirectory()&&!scoped.isSymbolicLink())continue;const fullName=`${entry.name}/${scoped.name}`;if(!matchesPrefix(fullName,prefixes))continue;out.push({path:path.join(scopeDir,scoped.name),packageName:fullName})}}else{if(!matchesPrefix(entry.name,prefixes))continue;out.push({path:path.join(nodeModules,entry.name),packageName:entry.name})}}return out}async function enumerateFolderModules(root,prefixes){const out=[];let entries;try{entries=await fs.readdir(root,{withFileTypes:true})}catch{return out}for(const entry of entries){if(!entry.isDirectory()&&!entry.isSymbolicLink())continue;if(entry.name.startsWith("."))continue;if(!matchesPrefix(entry.name,prefixes))continue;out.push({path:path.join(root,entry.name),packageName:entry.name})}return out}function normalizePrefixes(opt){if(opt===void 0)return null;if(typeof opt==="string")return[opt];if(Array.isArray(opt)){if(opt.length===0)return null;return opt.slice()}throw new SlothletError("INVALID_ARGUMENT",{argument:"prefix",expected:"string or string[]",received:typeof opt},null,{validationError:true})}function matchesPrefix(name,prefixes){if(!prefixes)return true;for(const p of prefixes){if(name.startsWith(p))return true}return false}function parseManifestSource(opt){if(opt===void 0){return{file:DEFAULT_MANIFEST_FILE,subkey:null,isOverride:false}}if(typeof opt!=="string"||opt.length===0){throw new SlothletError("INVALID_ARGUMENT",{argument:"manifest",expected:"string",received:typeof opt},null,{validationError:true})}const hashIdx=opt.indexOf("#");if(hashIdx===-1){return{file:opt,subkey:null,isOverride:opt!==DEFAULT_MANIFEST_FILE}}const file=opt.slice(0,hashIdx);const subkey=opt.slice(hashIdx+1);if(file.length===0||subkey.length===0){throw new SlothletError("INVALID_ARGUMENT",{argument:"manifest",expected:"<file>#<dotted.key> with both parts non-empty",received:opt},null,{validationError:true})}return{file,subkey,isOverride:true}}async function readJsonOrNull(filePath){let content;try{content=await fs.readFile(filePath,"utf8")}catch{return null}try{return JSON.parse(content)}catch{return null}}async function loadManifestRaw(manifestPath,source,packageName){let content;try{content=await fs.readFile(manifestPath,"utf8")}catch{return void 0}let parsed;try{parsed=JSON.parse(content)}catch(err){throw new SlothletError("MODULE_MANIFEST_INVALID",{packageName,manifestPath,reason:`JSON parse error: ${err.message}`},err,{validationError:true})}if(source.subkey===null){return parsed}const parts=source.subkey.split(".");let cur=parsed;for(const part of parts){if(cur===null||typeof cur!=="object"||!(part in cur)){return void 0}cur=cur[part]}if(cur===null||typeof cur!=="object"||Array.isArray(cur)){return void 0}return cur}function applySchemaRemap(raw,schemaMap){if(!schemaMap||Object.keys(schemaMap).length===0){return raw}const out={...raw};for(const[canonical,legacy]of Object.entries(schemaMap)){if(legacy===canonical)continue;if(out[canonical]!==void 0)continue;if(legacy in out){out[canonical]=out[legacy];delete out[legacy]}}return out}function deepFreeze(obj){if(obj===null||typeof obj!=="object"||Object.isFrozen(obj))return obj;Object.freeze(obj);for(const key of Object.keys(obj)){const value=obj[key];if(value!==null&&typeof value==="object"){deepFreeze(value)}}return obj}export{discoverModules};
17
+ import{SlothletError}from"@cldmv/slothlet/errors";import{validateModuleManifest}from"@cldmv/slothlet/helpers/module-manifest-validator";import{fsp,path}from"@cldmv/slothlet/helpers/platform";const DEFAULT_MANIFEST_FILE="slothlet.module.json";const UPWARD_WALK_CAP=20;async function discoverModules(options={}){const scanRoots=await resolveScanRoots(options.scanRoot);const manifestSource=parseManifestSource(options.manifest);const fieldSchema=options.schema??{};const filterFn=options.filter;const prefixes=normalizePrefixes(options.prefix);const candidates=[];for(const root of scanRoots){const mode=await detectScanMode(root);if(mode==="npm"){candidates.push(...await enumerateNpmPackages(root,prefixes))}else{candidates.push(...await enumerateFolderModules(root,prefixes))}}const results=[];const seenRealPaths=new Set;const realPathByNameVersion=new Map;for(const candidate of candidates){let realPath;try{realPath=await fsp.realpath(candidate.path)}catch{continue}if(seenRealPaths.has(realPath))continue;seenRealPaths.add(realPath);const pkgJsonPath=path.join(realPath,"package.json");const pkg=await readJsonOrNull(pkgJsonPath);if(!pkg||typeof pkg.name!=="string"||typeof pkg.version!=="string"){continue}const manifestPath=path.join(realPath,manifestSource.file);const manifestRaw=await loadManifestRaw(manifestPath,manifestSource,pkg.name);if(manifestRaw===void 0)continue;const remapped=applySchemaRemap(manifestRaw,fieldSchema);if(manifestSource.isOverride&&remapped.schemaVersion===void 0){remapped.schemaVersion=1}const normalized=validateModuleManifest(remapped,{packageName:pkg.name,packageVersion:pkg.version,packageDescription:pkg.description,packageRoot:realPath,manifestPath});if(typeof filterFn==="function"&&!filterFn(normalized,pkg.name)){continue}const nameVersionKey=`${pkg.name}@${pkg.version}`;if(realPathByNameVersion.has(nameVersionKey)){const otherRealPath=realPathByNameVersion.get(nameVersionKey);if(otherRealPath!==realPath){throw new SlothletError("MODULE_DUPLICATE_NAME_VERSION_MISMATCH",{packageName:pkg.name,version:pkg.version,paths:[otherRealPath,realPath].join(", ")},null,{validationError:true})}}else{realPathByNameVersion.set(nameVersionKey,realPath)}const apiDirAbs=path.resolve(realPath,normalized.apiDir);results.push(Object.freeze({packageName:pkg.name,packageRoot:realPath,mountPath:Object.freeze([...normalized.mountPath]),apiDir:apiDirAbs,manifest:deepFreeze(normalized)}))}return results}async function resolveScanRoots(opt){if(opt===void 0){return[await defaultScanRoot()]}if(typeof opt==="string"){return[path.resolve(opt)]}if(Array.isArray(opt)){return opt.map(p=>path.resolve(p))}throw new SlothletError("INVALID_ARGUMENT",{argument:"scanRoot",expected:"string or string[]",received:typeof opt},null,{validationError:true})}async function defaultScanRoot(){let current=process.cwd();for(let i=0;i<UPWARD_WALK_CAP;i++){try{const stat=await fsp.stat(path.join(current,"node_modules"));if(stat.isDirectory())return current}catch{}const parent=path.dirname(current);if(parent===current)break;current=parent}return process.cwd()}async function detectScanMode(root){try{const stat=await fsp.stat(path.join(root,"node_modules"));if(stat.isDirectory())return"npm"}catch{}return"folder"}async function enumerateNpmPackages(root,prefixes){const nodeModules=path.join(root,"node_modules");const out=[];let entries;try{entries=await fsp.readdir(nodeModules,{withFileTypes:true})}catch{return out}for(const entry of entries){if(!entry.isDirectory()&&!entry.isSymbolicLink())continue;if(entry.name.startsWith("."))continue;if(entry.name.startsWith("@")){const scopeDir=path.join(nodeModules,entry.name);let scopedEntries;try{scopedEntries=await fsp.readdir(scopeDir,{withFileTypes:true})}catch{continue}for(const scoped of scopedEntries){if(!scoped.isDirectory()&&!scoped.isSymbolicLink())continue;const fullName=`${entry.name}/${scoped.name}`;if(!matchesPrefix(fullName,prefixes))continue;out.push({path:path.join(scopeDir,scoped.name),packageName:fullName})}}else{if(!matchesPrefix(entry.name,prefixes))continue;out.push({path:path.join(nodeModules,entry.name),packageName:entry.name})}}return out}async function enumerateFolderModules(root,prefixes){const out=[];let entries;try{entries=await fsp.readdir(root,{withFileTypes:true})}catch{return out}for(const entry of entries){if(!entry.isDirectory()&&!entry.isSymbolicLink())continue;if(entry.name.startsWith("."))continue;if(!matchesPrefix(entry.name,prefixes))continue;out.push({path:path.join(root,entry.name),packageName:entry.name})}return out}function normalizePrefixes(opt){if(opt===void 0)return null;if(typeof opt==="string")return[opt];if(Array.isArray(opt)){if(opt.length===0)return null;return opt.slice()}throw new SlothletError("INVALID_ARGUMENT",{argument:"prefix",expected:"string or string[]",received:typeof opt},null,{validationError:true})}function matchesPrefix(name,prefixes){if(!prefixes)return true;for(const p of prefixes){if(name.startsWith(p))return true}return false}function parseManifestSource(opt){if(opt===void 0){return{file:DEFAULT_MANIFEST_FILE,subkey:null,isOverride:false}}if(typeof opt!=="string"||opt.length===0){throw new SlothletError("INVALID_ARGUMENT",{argument:"manifest",expected:"string",received:typeof opt},null,{validationError:true})}const hashIdx=opt.indexOf("#");if(hashIdx===-1){return{file:opt,subkey:null,isOverride:opt!==DEFAULT_MANIFEST_FILE}}const file=opt.slice(0,hashIdx);const subkey=opt.slice(hashIdx+1);if(file.length===0||subkey.length===0){throw new SlothletError("INVALID_ARGUMENT",{argument:"manifest",expected:"<file>#<dotted.key> with both parts non-empty",received:opt},null,{validationError:true})}return{file,subkey,isOverride:true}}async function readJsonOrNull(filePath){let content;try{content=await fsp.readFile(filePath,"utf8")}catch{return null}try{return JSON.parse(content)}catch{return null}}async function loadManifestRaw(manifestPath,source,packageName){let content;try{content=await fsp.readFile(manifestPath,"utf8")}catch{return void 0}let parsed;try{parsed=JSON.parse(content)}catch(err){throw new SlothletError("MODULE_MANIFEST_INVALID",{packageName,manifestPath,reason:`JSON parse error: ${err.message}`},err,{validationError:true})}if(source.subkey===null){return parsed}const parts=source.subkey.split(".");let cur=parsed;for(const part of parts){if(cur===null||typeof cur!=="object"||!(part in cur)){return void 0}cur=cur[part]}if(cur===null||typeof cur!=="object"||Array.isArray(cur)){return void 0}return cur}function applySchemaRemap(raw,schemaMap){if(!schemaMap||Object.keys(schemaMap).length===0){return raw}const out={...raw};for(const[canonical,legacy]of Object.entries(schemaMap)){if(legacy===canonical)continue;if(out[canonical]!==void 0)continue;if(legacy in out){out[canonical]=out[legacy];delete out[legacy]}}return out}function deepFreeze(obj){if(obj===null||typeof obj!=="object"||Object.isFrozen(obj))return obj;Object.freeze(obj);for(const key of Object.keys(obj)){const value=obj[key];if(value!==null&&typeof value==="object"){deepFreeze(value)}}return obj}export{discoverModules};
@@ -14,4 +14,4 @@
14
14
  limitations under the License.
15
15
  */
16
16
 
17
- import{SlothletError}from"@cldmv/slothlet/errors";const IS_NODE=typeof process!=="undefined"&&Boolean(process.versions?.node);const path=IS_NODE?(await import("node:path")).default:null;const RESERVED_MOUNTPATH_ROOTS=Object.freeze(new Set(["slothlet","shutdown","destroy"]));const ALLOWED_TOP_LEVEL_FIELDS=Object.freeze(new Set(["schemaVersion","name","version","description","mountPath","apiDir","kind","priority","dependencies","permissions","metadata"]));const PERMISSION_EFFECT_VALUES=Object.freeze(new Set(["allow","deny"]));function validateModuleManifest(manifest,packageContext){if(!manifest||typeof manifest!=="object"||Array.isArray(manifest)){throw new SlothletError("MODULE_MANIFEST_INVALID",{packageName:packageContext?.packageName??"<unknown>",manifestPath:packageContext?.manifestPath??"<unknown>",reason:"manifest must be a JSON object"},null,{validationError:true})}const{packageName,packageVersion,packageDescription,packageRoot,manifestPath}=packageContext;for(const key of Object.keys(manifest)){if(!ALLOWED_TOP_LEVEL_FIELDS.has(key)){throw new SlothletError("MODULE_MANIFEST_UNKNOWN_FIELD",{packageName,manifestPath,field:key},null,{validationError:true})}}if(manifest.schemaVersion===void 0){throw new SlothletError("MODULE_MANIFEST_INVALID",{packageName,manifestPath,reason:"missing required field 'schemaVersion'"},null,{validationError:true})}if(manifest.schemaVersion!==1){throw new SlothletError("MODULE_VERSION_UNSUPPORTED",{packageName,schemaVersion:String(manifest.schemaVersion)},null,{validationError:true})}if(manifest.mountPath===void 0){throw new SlothletError("MODULE_MANIFEST_INVALID",{packageName,manifestPath,reason:"missing required field 'mountPath'"},null,{validationError:true})}const mountPathSegments=normalizeMountPath(manifest.mountPath,packageName,manifestPath);if(RESERVED_MOUNTPATH_ROOTS.has(mountPathSegments[0])){throw new SlothletError("MODULE_RESERVED_MOUNTPATH",{packageName,mountPathRoot:mountPathSegments[0],mountPath:mountPathSegments.join(".")},null,{validationError:true})}if(manifest.apiDir===void 0){throw new SlothletError("MODULE_MANIFEST_INVALID",{packageName,manifestPath,reason:"missing required field 'apiDir'"},null,{validationError:true})}if(typeof manifest.apiDir!=="string"||manifest.apiDir.length===0){throw new SlothletError("MODULE_MANIFEST_INVALID",{packageName,manifestPath,reason:"field 'apiDir' must be a non-empty string"},null,{validationError:true})}validateApiDirContainment(manifest.apiDir,packageRoot,packageName);if(manifest.name!==void 0){if(typeof manifest.name!=="string"){throw new SlothletError("MODULE_MANIFEST_INVALID",{packageName,manifestPath,reason:"field 'name' must be a string"},null,{validationError:true})}if(manifest.name!==packageName){throw new SlothletError("MODULE_MANIFEST_NAME_MISMATCH",{packageName,manifestName:manifest.name},null,{validationError:true})}}if(manifest.version!==void 0){if(typeof manifest.version!=="string"){throw new SlothletError("MODULE_MANIFEST_INVALID",{packageName,manifestPath,reason:"field 'version' must be a string"},null,{validationError:true})}if(manifest.version!==packageVersion){throw new SlothletError("MODULE_MANIFEST_VERSION_MISMATCH",{packageName,manifestVersion:manifest.version,packageVersion},null,{validationError:true})}}if(manifest.description!==void 0&&typeof manifest.description!=="string"){throw new SlothletError("MODULE_MANIFEST_INVALID",{packageName,manifestPath,reason:"field 'description' must be a string"},null,{validationError:true})}if(manifest.kind!==void 0&&typeof manifest.kind!=="string"){throw new SlothletError("MODULE_MANIFEST_INVALID",{packageName,manifestPath,reason:"field 'kind' must be a string"},null,{validationError:true})}if(manifest.priority!==void 0&&(typeof manifest.priority!=="number"||!Number.isFinite(manifest.priority))){throw new SlothletError("MODULE_MANIFEST_INVALID",{packageName,manifestPath,reason:"field 'priority' must be a finite number"},null,{validationError:true})}if(manifest.dependencies!==void 0){if(typeof manifest.dependencies!=="object"||manifest.dependencies===null||Array.isArray(manifest.dependencies)){throw new SlothletError("MODULE_MANIFEST_INVALID",{packageName,manifestPath,reason:"field 'dependencies' must be a plain object"},null,{validationError:true})}for(const[depName,depValue]of Object.entries(manifest.dependencies)){if(typeof depValue!=="string"){throw new SlothletError("MODULE_MANIFEST_INVALID",{packageName,manifestPath,reason:`dependency '${depName}' must be a string version range`},null,{validationError:true})}}}if(manifest.permissions!==void 0){validatePermissions(manifest.permissions,packageName,manifestPath)}if(manifest.metadata!==void 0){if(typeof manifest.metadata!=="object"||manifest.metadata===null||Array.isArray(manifest.metadata)){throw new SlothletError("MODULE_MANIFEST_INVALID",{packageName,manifestPath,reason:"field 'metadata' must be a plain object"},null,{validationError:true})}}return{schemaVersion:1,name:packageName,version:packageVersion,description:manifest.description??packageDescription,mountPath:mountPathSegments,apiDir:manifest.apiDir,kind:manifest.kind,priority:manifest.priority??0,dependencies:manifest.dependencies,permissions:manifest.permissions,metadata:manifest.metadata}}function normalizeMountPath(mountPath,packageName,manifestPath){if(typeof mountPath==="string"){if(mountPath.length===0){throw new SlothletError("MODULE_MANIFEST_INVALID",{packageName,manifestPath,reason:"field 'mountPath' must be a non-empty string or non-empty array of non-empty strings"},null,{validationError:true})}return mountPath.split(".")}if(Array.isArray(mountPath)){if(mountPath.length===0){throw new SlothletError("MODULE_MANIFEST_INVALID",{packageName,manifestPath,reason:"field 'mountPath' must be a non-empty string or non-empty array of non-empty strings"},null,{validationError:true})}for(const segment of mountPath){if(typeof segment!=="string"||segment.length===0){throw new SlothletError("MODULE_MANIFEST_INVALID",{packageName,manifestPath,reason:"field 'mountPath' array entries must all be non-empty strings"},null,{validationError:true})}}return mountPath.slice()}throw new SlothletError("MODULE_MANIFEST_INVALID",{packageName,manifestPath,reason:"field 'mountPath' must be a non-empty string or non-empty array of non-empty strings"},null,{validationError:true})}function validateApiDirContainment(apiDir,packageRoot,packageName){const resolved=path.resolve(packageRoot,apiDir);const rootWithSep=packageRoot.endsWith(path.sep)?packageRoot:packageRoot+path.sep;if(resolved!==packageRoot&&!resolved.startsWith(rootWithSep)){throw new SlothletError("MODULE_PATH_TRAVERSAL",{packageName,apiDir,resolvedPath:resolved,packageRoot},null,{validationError:true})}}function validatePermissions(permissions,packageName,manifestPath){if(!Array.isArray(permissions)){throw new SlothletError("MODULE_MANIFEST_INVALID",{packageName,manifestPath,reason:"field 'permissions' must be an array of rule objects"},null,{validationError:true})}for(let i=0;i<permissions.length;i++){const rule=permissions[i];if(!rule||typeof rule!=="object"||Array.isArray(rule)){throw new SlothletError("MODULE_MANIFEST_INVALID",{packageName,manifestPath,reason:`permissions[${i}] must be a rule object`},null,{validationError:true})}if(typeof rule.caller!=="string"||rule.caller.length===0){throw new SlothletError("MODULE_MANIFEST_INVALID",{packageName,manifestPath,reason:`permissions[${i}].caller must be a non-empty string`},null,{validationError:true})}if(typeof rule.target!=="string"||rule.target.length===0){throw new SlothletError("MODULE_MANIFEST_INVALID",{packageName,manifestPath,reason:`permissions[${i}].target must be a non-empty string`},null,{validationError:true})}if(!PERMISSION_EFFECT_VALUES.has(rule.effect)){throw new SlothletError("MODULE_MANIFEST_INVALID",{packageName,manifestPath,reason:`permissions[${i}].effect must be "allow" or "deny"`},null,{validationError:true})}}}export{validateModuleManifest};
17
+ import{SlothletError}from"@cldmv/slothlet/errors";import{path}from"@cldmv/slothlet/helpers/platform";const RESERVED_MOUNTPATH_ROOTS=Object.freeze(new Set(["slothlet","shutdown","destroy"]));const ALLOWED_TOP_LEVEL_FIELDS=Object.freeze(new Set(["schemaVersion","name","version","description","mountPath","apiDir","kind","priority","dependencies","permissions","metadata"]));const PERMISSION_EFFECT_VALUES=Object.freeze(new Set(["allow","deny"]));function validateModuleManifest(manifest,packageContext){if(!manifest||typeof manifest!=="object"||Array.isArray(manifest)){throw new SlothletError("MODULE_MANIFEST_INVALID",{packageName:packageContext?.packageName??"<unknown>",manifestPath:packageContext?.manifestPath??"<unknown>",reason:"manifest must be a JSON object"},null,{validationError:true})}const{packageName,packageVersion,packageDescription,packageRoot,manifestPath}=packageContext;for(const key of Object.keys(manifest)){if(!ALLOWED_TOP_LEVEL_FIELDS.has(key)){throw new SlothletError("MODULE_MANIFEST_UNKNOWN_FIELD",{packageName,manifestPath,field:key},null,{validationError:true})}}if(manifest.schemaVersion===void 0){throw new SlothletError("MODULE_MANIFEST_INVALID",{packageName,manifestPath,reason:"missing required field 'schemaVersion'"},null,{validationError:true})}if(manifest.schemaVersion!==1){throw new SlothletError("MODULE_VERSION_UNSUPPORTED",{packageName,schemaVersion:String(manifest.schemaVersion)},null,{validationError:true})}if(manifest.mountPath===void 0){throw new SlothletError("MODULE_MANIFEST_INVALID",{packageName,manifestPath,reason:"missing required field 'mountPath'"},null,{validationError:true})}const mountPathSegments=normalizeMountPath(manifest.mountPath,packageName,manifestPath);if(RESERVED_MOUNTPATH_ROOTS.has(mountPathSegments[0])){throw new SlothletError("MODULE_RESERVED_MOUNTPATH",{packageName,mountPathRoot:mountPathSegments[0],mountPath:mountPathSegments.join(".")},null,{validationError:true})}if(manifest.apiDir===void 0){throw new SlothletError("MODULE_MANIFEST_INVALID",{packageName,manifestPath,reason:"missing required field 'apiDir'"},null,{validationError:true})}if(typeof manifest.apiDir!=="string"||manifest.apiDir.length===0){throw new SlothletError("MODULE_MANIFEST_INVALID",{packageName,manifestPath,reason:"field 'apiDir' must be a non-empty string"},null,{validationError:true})}validateApiDirContainment(manifest.apiDir,packageRoot,packageName);if(manifest.name!==void 0){if(typeof manifest.name!=="string"){throw new SlothletError("MODULE_MANIFEST_INVALID",{packageName,manifestPath,reason:"field 'name' must be a string"},null,{validationError:true})}if(manifest.name!==packageName){throw new SlothletError("MODULE_MANIFEST_NAME_MISMATCH",{packageName,manifestName:manifest.name},null,{validationError:true})}}if(manifest.version!==void 0){if(typeof manifest.version!=="string"){throw new SlothletError("MODULE_MANIFEST_INVALID",{packageName,manifestPath,reason:"field 'version' must be a string"},null,{validationError:true})}if(manifest.version!==packageVersion){throw new SlothletError("MODULE_MANIFEST_VERSION_MISMATCH",{packageName,manifestVersion:manifest.version,packageVersion},null,{validationError:true})}}if(manifest.description!==void 0&&typeof manifest.description!=="string"){throw new SlothletError("MODULE_MANIFEST_INVALID",{packageName,manifestPath,reason:"field 'description' must be a string"},null,{validationError:true})}if(manifest.kind!==void 0&&typeof manifest.kind!=="string"){throw new SlothletError("MODULE_MANIFEST_INVALID",{packageName,manifestPath,reason:"field 'kind' must be a string"},null,{validationError:true})}if(manifest.priority!==void 0&&(typeof manifest.priority!=="number"||!Number.isFinite(manifest.priority))){throw new SlothletError("MODULE_MANIFEST_INVALID",{packageName,manifestPath,reason:"field 'priority' must be a finite number"},null,{validationError:true})}if(manifest.dependencies!==void 0){if(typeof manifest.dependencies!=="object"||manifest.dependencies===null||Array.isArray(manifest.dependencies)){throw new SlothletError("MODULE_MANIFEST_INVALID",{packageName,manifestPath,reason:"field 'dependencies' must be a plain object"},null,{validationError:true})}for(const[depName,depValue]of Object.entries(manifest.dependencies)){if(typeof depValue!=="string"){throw new SlothletError("MODULE_MANIFEST_INVALID",{packageName,manifestPath,reason:`dependency '${depName}' must be a string version range`},null,{validationError:true})}}}if(manifest.permissions!==void 0){validatePermissions(manifest.permissions,packageName,manifestPath)}if(manifest.metadata!==void 0){if(typeof manifest.metadata!=="object"||manifest.metadata===null||Array.isArray(manifest.metadata)){throw new SlothletError("MODULE_MANIFEST_INVALID",{packageName,manifestPath,reason:"field 'metadata' must be a plain object"},null,{validationError:true})}}return{schemaVersion:1,name:packageName,version:packageVersion,description:manifest.description??packageDescription,mountPath:mountPathSegments,apiDir:manifest.apiDir,kind:manifest.kind,priority:manifest.priority??0,dependencies:manifest.dependencies,permissions:manifest.permissions,metadata:manifest.metadata}}function normalizeMountPath(mountPath,packageName,manifestPath){if(typeof mountPath==="string"){if(mountPath.length===0){throw new SlothletError("MODULE_MANIFEST_INVALID",{packageName,manifestPath,reason:"field 'mountPath' must be a non-empty string or non-empty array of non-empty strings"},null,{validationError:true})}return mountPath.split(".")}if(Array.isArray(mountPath)){if(mountPath.length===0){throw new SlothletError("MODULE_MANIFEST_INVALID",{packageName,manifestPath,reason:"field 'mountPath' must be a non-empty string or non-empty array of non-empty strings"},null,{validationError:true})}for(const segment of mountPath){if(typeof segment!=="string"||segment.length===0){throw new SlothletError("MODULE_MANIFEST_INVALID",{packageName,manifestPath,reason:"field 'mountPath' array entries must all be non-empty strings"},null,{validationError:true})}}return mountPath.slice()}throw new SlothletError("MODULE_MANIFEST_INVALID",{packageName,manifestPath,reason:"field 'mountPath' must be a non-empty string or non-empty array of non-empty strings"},null,{validationError:true})}function validateApiDirContainment(apiDir,packageRoot,packageName){const resolved=path.resolve(packageRoot,apiDir);const rootWithSep=packageRoot.endsWith(path.sep)?packageRoot:packageRoot+path.sep;if(resolved!==packageRoot&&!resolved.startsWith(rootWithSep)){throw new SlothletError("MODULE_PATH_TRAVERSAL",{packageName,apiDir,resolvedPath:resolved,packageRoot},null,{validationError:true})}}function validatePermissions(permissions,packageName,manifestPath){if(!Array.isArray(permissions)){throw new SlothletError("MODULE_MANIFEST_INVALID",{packageName,manifestPath,reason:"field 'permissions' must be an array of rule objects"},null,{validationError:true})}for(let i=0;i<permissions.length;i++){const rule=permissions[i];if(!rule||typeof rule!=="object"||Array.isArray(rule)){throw new SlothletError("MODULE_MANIFEST_INVALID",{packageName,manifestPath,reason:`permissions[${i}] must be a rule object`},null,{validationError:true})}if(typeof rule.caller!=="string"||rule.caller.length===0){throw new SlothletError("MODULE_MANIFEST_INVALID",{packageName,manifestPath,reason:`permissions[${i}].caller must be a non-empty string`},null,{validationError:true})}if(typeof rule.target!=="string"||rule.target.length===0){throw new SlothletError("MODULE_MANIFEST_INVALID",{packageName,manifestPath,reason:`permissions[${i}].target must be a non-empty string`},null,{validationError:true})}if(!PERMISSION_EFFECT_VALUES.has(rule.effect)){throw new SlothletError("MODULE_MANIFEST_INVALID",{packageName,manifestPath,reason:`permissions[${i}].effect must be "allow" or "deny"`},null,{validationError:true})}}}export{validateModuleManifest};
@@ -0,0 +1,17 @@
1
+ /*
2
+ Copyright 2026 CLDMV/Shinrai
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+ */
16
+
17
+ const isNode=typeof process!=="undefined"&&Boolean(process?.versions?.node);let fs=null;let fsp=null;let path=null;let url=null;let util=null;let EventEmitter=null;let AsyncLocalStorage=null;let AsyncResource=null;let createRequire=null;if(isNode){const[fsMod,fspMod,pathMod,urlMod,utilMod,eventsMod,asyncHooksMod,moduleMod]=await Promise.all([import("node:fs"),import("node:fs/promises"),import("node:path"),import("node:url"),import("node:util"),import("node:events"),import("node:async_hooks"),import("node:module")]);fs=fsMod;fsp=fspMod;path=pathMod;url=urlMod;util=utilMod;({EventEmitter}=eventsMod);({AsyncLocalStorage,AsyncResource}=asyncHooksMod);({createRequire}=moduleMod)}else{util={inspect:Object.assign(value=>value,{custom:Symbol.for("nodejs.util.inspect.custom")}),types:{isProxy:()=>false}}}function loadJson(ref){if(!isNode){return import(ref,{with:{type:"json"}}).then(mod=>mod.default??null).catch(()=>null)}try{return JSON.parse(fs.readFileSync(ref,"utf-8"))}catch{return null}}export{AsyncLocalStorage,AsyncResource,EventEmitter,createRequire,fs,fsp,isNode,loadJson,path,url,util};
@@ -14,4 +14,4 @@
14
14
  limitations under the License.
15
15
  */
16
16
 
17
- import{ComponentBase}from"@cldmv/slothlet/factories/component-base";const IS_NODE=typeof process!=="undefined"&&Boolean(process.versions?.node);const{fs,path,fileURLToPath}=IS_NODE?await(async()=>{const[fsMod,pathMod,urlMod]=await Promise.all([import("node:fs"),import("node:path"),import("node:url")]);return{fs:fsMod.default,path:pathMod.default,fileURLToPath:urlMod.fileURLToPath}})():{fs:null,path:null,fileURLToPath:null};let SLOTHLET_LIB_ROOT=null;let SLOTHLET_PKG_ROOT=null;try{const __filename=fileURLToPath(import.meta.url);const __dirname=path.dirname(__filename);SLOTHLET_LIB_ROOT=path.resolve(__dirname,"../..");SLOTHLET_PKG_ROOT=path.normalize(path.resolve(__dirname,"../../.."))}catch{}class Resolver extends ComponentBase{static slothletProperty="resolver";getStack(skipFn){const orig=Error.prepareStackTrace;try{Error.prepareStackTrace=(_,s)=>s;const e=new Error("Stack trace");if(skipFn)Error.captureStackTrace(e,skipFn);return e.stack}finally{Error.prepareStackTrace=orig}}#getStack(){const originalPrepare=Error.prepareStackTrace;Error.prepareStackTrace=(___,stack2)=>stack2;const stack=new Error().stack;Error.prepareStackTrace=originalPrepare;return stack}toFsPath(v){if(!v)return null;const str=String(v);return str.startsWith("file://")?fileURLToPath(str):str}#isSlothletInternal(filePath){if(!SLOTHLET_LIB_ROOT)return false;const normalized=path.normalize(filePath);const normalizedLibRoot=path.normalize(SLOTHLET_LIB_ROOT);if(normalized.startsWith(normalizedLibRoot)){return true}const basename=path.basename(normalized);if(basename==="index.mjs"||basename==="index.cjs"){if(path.dirname(normalized)===SLOTHLET_PKG_ROOT)return true}return false}#findCallerBase(){const stack=this.#getStack();const files=stack.map(s=>this.toFsPath(s.getFileName())).filter(Boolean);const slothletIndex=files.findIndex(f=>path.basename(f).toLowerCase()==="slothlet.mjs");if(slothletIndex===-1){for(const file of files){if(!this.#isSlothletInternal(file)){return file}}return null}for(let i=slothletIndex+1;i<files.length;i++){const file=files[i];if(file.startsWith?.("node:"))continue;if(this.#isSlothletInternal(file))continue;return file}for(const file of files){if(!this.#isSlothletInternal(file)){return file}}return null}resolvePathFromCaller(rel){if(this.slothlet?.envTarget==="browser"){return rel||""}if(rel.startsWith?.("file://"))return fileURLToPath(rel);if(path.isAbsolute(rel))return rel;const callerFile=this.#findCallerBase();if(!callerFile){return path.resolve(process.cwd(),rel)}const callerDir=path.dirname(callerFile);const resolved=path.resolve(callerDir,rel);if(fs.existsSync(resolved)){return resolved}const cwdResolved=path.resolve(process.cwd(),rel);if(fs.existsSync(cwdResolved)){return cwdResolved}return resolved}}export{Resolver};
17
+ import{ComponentBase}from"@cldmv/slothlet/factories/component-base";import{fs,path,url}from"@cldmv/slothlet/helpers/platform";let SLOTHLET_LIB_ROOT=null;let SLOTHLET_PKG_ROOT=null;try{const __filename=url.fileURLToPath(import.meta.url);const __dirname=path.dirname(__filename);SLOTHLET_LIB_ROOT=path.resolve(__dirname,"../..");SLOTHLET_PKG_ROOT=path.normalize(path.resolve(__dirname,"../../.."))}catch{}class Resolver extends ComponentBase{static slothletProperty="resolver";getStack(skipFn){const orig=Error.prepareStackTrace;try{Error.prepareStackTrace=(_,s)=>s;const e=new Error("Stack trace");if(skipFn)Error.captureStackTrace(e,skipFn);return e.stack}finally{Error.prepareStackTrace=orig}}#getStack(){const originalPrepare=Error.prepareStackTrace;Error.prepareStackTrace=(___,stack2)=>stack2;const stack=new Error().stack;Error.prepareStackTrace=originalPrepare;return stack}toFsPath(v){if(!v)return null;const str=String(v);return str.startsWith("file://")?url.fileURLToPath(str):str}#isSlothletInternal(filePath){if(!SLOTHLET_LIB_ROOT)return false;const normalized=path.normalize(filePath);const normalizedLibRoot=path.normalize(SLOTHLET_LIB_ROOT);if(normalized.startsWith(normalizedLibRoot)){return true}const basename=path.basename(normalized);if(basename==="index.mjs"||basename==="index.cjs"){if(path.dirname(normalized)===SLOTHLET_PKG_ROOT)return true}return false}#findCallerBase(){const stack=this.#getStack();const files=stack.map(s=>this.toFsPath(s.getFileName())).filter(Boolean);const slothletIndex=files.findIndex(f=>path.basename(f).toLowerCase()==="slothlet.mjs");if(slothletIndex===-1){for(const file of files){if(!this.#isSlothletInternal(file)){return file}}return null}for(let i=slothletIndex+1;i<files.length;i++){const file=files[i];if(file.startsWith?.("node:"))continue;if(this.#isSlothletInternal(file))continue;return file}for(const file of files){if(!this.#isSlothletInternal(file)){return file}}return null}resolvePathFromCaller(rel){if(this.slothlet?.envTarget==="browser"){return rel||""}if(rel.startsWith?.("file://"))return url.fileURLToPath(rel);if(path.isAbsolute(rel))return rel;const callerFile=this.#findCallerBase();if(!callerFile){return path.resolve(process.cwd(),rel)}const callerDir=path.dirname(callerFile);const resolved=path.resolve(callerDir,rel);if(fs.existsSync(resolved)){return resolved}const cwdResolved=path.resolve(process.cwd(),rel);if(fs.existsSync(cwdResolved)){return cwdResolved}return resolved}}export{Resolver};
@@ -14,4 +14,4 @@
14
14
  limitations under the License.
15
15
  */
16
16
 
17
- import{existsSync,readFileSync}from"fs";import{fileURLToPath}from"url";import{dirname,join}from"path";const translations_dirname=dirname(fileURLToPath(import.meta.url));const defaultTranslations=JSON.parse(readFileSync(join(translations_dirname,"languages","en-us.json"),"utf-8"));let currentTranslations=defaultTranslations.translations;let currentLanguage="en-us";const i18n_languageFallbacks={en:"en-us",es:"es-mx",de:"de-de",fr:"fr-fr",hi:"hi-in",ja:"ja-jp",ko:"ko-kr",pt:"pt-br",ru:"ru-ru",zh:"zh-cn"};function i18n_languageFileExists(lang){const langFilePath=join(translations_dirname,"languages",`${lang}.json`);return existsSync(langFilePath)}function i18n_normalizeEnvLanguage(envLang){const normalized=String(envLang).split(".")[0].split("@")[0].replace(/_/g,"-").toLowerCase();if(normalized==="c"||normalized==="posix")return"en-us";if(i18n_languageFileExists(normalized))return normalized;const base=normalized.split("-")[0];if(!base)return"en-us";if(i18n_languageFileExists(base))return base;return i18n_languageFallbacks[base]||base}function i18n_detectLanguage(){const envLang=process.env.LANG||process.env.LANGUAGE||process.env.LC_ALL;if(envLang){return i18n_normalizeEnvLanguage(envLang)}return"en-us"}function i18n_loadLanguageSync(lang){try{const langFilePath=join(translations_dirname,"languages",`${lang}.json`);const langData=JSON.parse(readFileSync(langFilePath,"utf-8"));return langData.translations}catch(___error){return null}}function setLanguage(lang){currentTranslations={...defaultTranslations.translations};if(lang!=="en-us"){const langTranslations=i18n_loadLanguageSync(lang);if(langTranslations){currentTranslations={...currentTranslations,...langTranslations};currentLanguage=lang}else{console.warn(`Failed to load language '${lang}', falling back to English.`);currentLanguage="en-us"}}else{currentLanguage="en-us"}}function getLanguage(){return currentLanguage}function translate(errorCode,params={}){let template=currentTranslations[errorCode];if(!template&&errorCode.startsWith("INVALID_CONFIG_")){template=currentTranslations.INVALID_CONFIG_generic}let message=template||`Error: ${errorCode}`;for(const[key,value]of Object.entries(params)){message=message.replace(new RegExp(`\\{${key}\\}`,"g"),value!==void 0?String(value):"")}message=message.replace(/\{\w+\}/g,"").replace(/\s+/g," ").trim();return message}function initI18n(options={}){try{if(options.language){setLanguage(options.language)}else{const detected=i18n_detectLanguage();setLanguage(detected)}}catch(___error){console.warn("i18n initialization failed, using English:",___error.message);currentLanguage="en-us";currentTranslations=defaultTranslations.translations}}initI18n();const t=translate;export{getLanguage,initI18n,setLanguage,t,translate};
17
+ import defaultTranslations from"./languages/en-us.json"with{type:"json"};import{isNode,fs,path,url,loadJson}from"@cldmv/slothlet/helpers/platform";const translations_dirname=isNode?path.dirname(url.fileURLToPath(import.meta.url)):null;let currentTranslations=defaultTranslations.translations;let currentLanguage="en-us";const i18n_languageFallbacks={en:"en-us",es:"es-mx",de:"de-de",fr:"fr-fr",hi:"hi-in",ja:"ja-jp",ko:"ko-kr",pt:"pt-br",ru:"ru-ru",zh:"zh-cn"};const KNOWN_LOCALES=new Set(["de-de","en-gb","en-us","es-es","es-mx","fr-fr","hi-in","ja-jp","ko-kr","pt-br","ru-ru","zh-cn"]);function i18n_localeRef(lang){return isNode?path.join(translations_dirname,"languages",`${lang}.json`):`@cldmv/slothlet/i18n/language/${lang}.json`}function i18n_languageFileExists(lang){if(!isNode)return KNOWN_LOCALES.has(lang);const langFilePath=path.join(translations_dirname,"languages",`${lang}.json`);return fs.existsSync(langFilePath)}function i18n_normalizeEnvLanguage(envLang){const normalized=String(envLang).split(".")[0].split("@")[0].replace(/_/g,"-").toLowerCase();if(normalized==="c"||normalized==="posix")return"en-us";if(i18n_languageFileExists(normalized))return normalized;const base=normalized.split("-")[0];if(!base)return"en-us";if(i18n_languageFileExists(base))return base;return i18n_languageFallbacks[base]||base}function i18n_detectLanguage(){if(!isNode){const navLang=typeof navigator!=="undefined"?navigator.languages?.[0]||navigator.language:null;return navLang?i18n_normalizeEnvLanguage(navLang):"en-us"}const envLang=process.env.LANG||process.env.LANGUAGE||process.env.LC_ALL;if(envLang){return i18n_normalizeEnvLanguage(envLang)}return"en-us"}function i18n_loadLanguageSync(lang){if(!isNode)return null;const langData=loadJson(i18n_localeRef(lang));return langData?langData.translations:null}function setLanguage(lang){currentTranslations={...defaultTranslations.translations};if(lang==="en-us"){currentLanguage="en-us";return}if(!isNode){void setLanguageAsync(lang);return}const langTranslations=i18n_loadLanguageSync(lang);if(langTranslations){currentTranslations={...currentTranslations,...langTranslations};currentLanguage=lang}else{console.warn(`Failed to load language '${lang}', falling back to English.`);currentLanguage="en-us"}}async function setLanguageAsync(lang){currentTranslations={...defaultTranslations.translations};if(lang==="en-us"){currentLanguage="en-us";return}currentLanguage="en-us";const langData=await loadJson(i18n_localeRef(lang));if(langData?.translations){currentTranslations={...currentTranslations,...langData.translations};currentLanguage=lang}else{console.warn(`Failed to load language '${lang}', falling back to English.`);currentLanguage="en-us"}}function getLanguage(){return currentLanguage}function translate(errorCode,params={}){let template=currentTranslations[errorCode];if(!template&&errorCode.startsWith("INVALID_CONFIG_")){template=currentTranslations.INVALID_CONFIG_generic}let message=template||`Error: ${errorCode}`;for(const[key,value]of Object.entries(params)){message=message.replace(new RegExp(`\\{${key}\\}`,"g"),value!==void 0?String(value):"")}message=message.replace(/\{\w+\}/g,"").replace(/\s+/g," ").trim();return message}function initI18n(options={}){try{const lang=options.language||i18n_detectLanguage();if(!isNode){currentLanguage="en-us";if(lang&&lang!=="en-us")void setLanguageAsync(lang);return}setLanguage(lang)}catch(___error){console.warn("i18n initialization failed, using English:",___error.message);currentLanguage="en-us";currentTranslations=defaultTranslations.translations}}initI18n();const t=translate;export{getLanguage,initI18n,setLanguage,setLanguageAsync,t,translate};
@@ -14,4 +14,4 @@
14
14
  limitations under the License.
15
15
  */
16
16
 
17
- import{ComponentBase}from"@cldmv/slothlet/factories/component-base";const IS_NODE=typeof process!=="undefined"&&Boolean(process.versions?.node);const{readdir,stat,join,extname,basename,resolve,pathToFileURL,createRequire}=IS_NODE?await(async()=>{const[fsMod,pathMod,urlMod,moduleMod]=await Promise.all([import("node:fs/promises"),import("node:path"),import("node:url"),import("node:module")]);return{readdir:fsMod.readdir,stat:fsMod.stat,join:pathMod.join,extname:pathMod.extname,basename:pathMod.basename,resolve:pathMod.resolve,pathToFileURL:urlMod.pathToFileURL,createRequire:moduleMod.createRequire}})():{readdir:null,stat:null,join:null,extname:null,basename:null,resolve:null,pathToFileURL:null,createRequire:null};class Loader extends ComponentBase{static slothletProperty="loader";constructor(slothlet){super(slothlet)}async loadModule(filePath,instanceID,moduleID,cacheBust=null){try{if(this.slothlet.envTarget==="browser"){return this.#loadModuleBrowser(filePath)}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={}){if(this.slothlet.envTarget==="browser"){return this.#scanDirectoryBrowser(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&&currentDepth<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}#scanDirectoryBrowser(dir,options={}){const manifest=this.slothlet.config?.manifest;if(!manifest){throw new this.SlothletError("INVALID_CONFIG_BROWSER_REQUIRES_MANIFEST",{},null,{validationError:true})}const configBase=(this.slothlet.config?.dir||"").replace(/\/$/,"");let relativePath=(dir||"").replace(/\/$/,"");if(configBase&&relativePath.startsWith(configBase)){relativePath=relativePath.slice(configBase.length).replace(/^\/|\/$/g,"")}const isRoot=!relativePath||relativePath==="/"||relativePath===".";const node=isRoot?manifest:this.#findManifestNode(manifest,relativePath);if(!node){throw new this.SlothletError("INVALID_DIRECTORY",{dir},null)}return this.#manifestNodeToStructure(node,dir,options)}#findManifestNode(node,targetPath){const normalised=targetPath.replace(/\\/g,"/").replace(/^\/|\/$/g,"");for(const dir of node.directories||[]){const dirPath=(dir.path||dir.name||"").replace(/\\/g,"/").replace(/^\/|\/$/g,"");if(dirPath===normalised)return dir.children||dir;const found=this.#findManifestNode(dir.children||dir,normalised);if(found)return found}return null}#manifestNodeToStructure(node,rootPath,options={}){const{fileFilter=null}=options;const ALLOWED_EXTS=[".mjs",".cjs",".js"];const structure={files:[],directories:[]};for(const file of node.files||[]){const filePath=file.path||file.relativePath||"";const fullName=file.fullName||filePath.split("/").pop();const lastDot=fullName.lastIndexOf(".");const ext=lastDot>=0?fullName.slice(lastDot):"";if(!ALLOWED_EXTS.includes(ext))continue;if(fullName.startsWith("__"))continue;if(fileFilter&&!fileFilter(fullName))continue;const name=file.name||(lastDot>=0?fullName.slice(0,lastDot):fullName);structure.files.push({path:filePath,name,fullName,moduleID:this.slothlet.helpers.sanitize.getModuleId(filePath,rootPath)})}if(!fileFilter){for(const dir of node.directories||[]){const dirPath=dir.path||dir.name||"";structure.directories.push({path:dirPath,name:dir.name||dirPath.split("/").pop(),children:this.#manifestNodeToStructure(dir.children||dir,dirPath,options)})}}return structure}async#loadModuleBrowser(filePath){const resolveModuleSpecifier=this.slothlet.config?.resolveModuleSpecifier??(({path:p})=>{const base=this.slothlet.config?.base??this.slothlet.config?.dir??"";const leadingSlash=base.startsWith("/")?"":"/";const baseUrl=/^[a-zA-Z][\w+\-.]*:\/\//.test(base)?base.endsWith("/")?base:base+"/":"file://"+leadingSlash+base.replace(/\/?$/,"/");return new URL(p,baseUrl).href});const fullName=filePath.split("/").pop();const lastDot=fullName.lastIndexOf(".");const name=lastDot>=0?fullName.slice(0,lastDot):fullName;const specifier=resolveModuleSpecifier({path:filePath,name,fullName});const module=await import(specifier);return module}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};
17
+ import{ComponentBase}from"@cldmv/slothlet/factories/component-base";import{fsp,path,url,createRequire}from"@cldmv/slothlet/helpers/platform";class Loader extends ComponentBase{static slothletProperty="loader";constructor(slothlet){super(slothlet)}async loadModule(filePath,instanceID,moduleID,cacheBust=null){try{if(this.slothlet.envTarget==="browser"){return this.#loadModuleBrowser(filePath)}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 path2=await import("path");const{fileURLToPath}=await import("url");const __dirname=path2.dirname(fileURLToPath(import.meta.url));const scriptPath=path2.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((resolve,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;resolve()}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=url.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:url2,cacheDir}=await writeTransformedToCache(filePath,code,instanceID,transform);(this.slothlet._typescriptCacheDirs??=new Set).add(cacheDir);let moduleUrl=`${url2}?slothlet_instance=${instanceID}`;if(moduleID){moduleUrl+=`&module=${moduleID}`}if(cacheBust){moduleUrl+=`&_reload=${cacheBust}`}return moduleUrl}async scanDirectory(dir,options={}){if(this.slothlet.envTarget==="browser"){return this.#scanDirectoryBrowser(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 fsp.stat(dir)}catch(error){throw new this.SlothletError("INVALID_DIRECTORY",{dir},error)}const structure={files:[],directories:[]};const entries=await fsp.readdir(dir,{withFileTypes:true});for(const entry of entries){const fullPath=path.join(dir,entry.name);if(entry.isDirectory()){if(fileFilter){continue}if(recursive&&currentDepth<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=path.extname(entry.name);if(extensions.includes(ext)){if(entry.name.startsWith("__")){continue}if(fileFilter&&!fileFilter(entry.name)){continue}const nameWithoutExt=path.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:path.resolve(dir)})}return structure}#scanDirectoryBrowser(dir,options={}){const manifest=this.slothlet.config?.manifest;if(!manifest){throw new this.SlothletError("INVALID_CONFIG_BROWSER_REQUIRES_MANIFEST",{},null,{validationError:true})}const configBase=(this.slothlet.config?.dir||"").replace(/\/$/,"");let relativePath=(dir||"").replace(/\/$/,"");if(configBase&&relativePath.startsWith(configBase)){relativePath=relativePath.slice(configBase.length).replace(/^\/|\/$/g,"")}const isRoot=!relativePath||relativePath==="/"||relativePath===".";const node=isRoot?manifest:this.#findManifestNode(manifest,relativePath);if(!node){throw new this.SlothletError("INVALID_DIRECTORY",{dir},null)}return this.#manifestNodeToStructure(node,dir,options)}#findManifestNode(node,targetPath){const normalised=targetPath.replace(/\\/g,"/").replace(/^\/|\/$/g,"");for(const dir of node.directories||[]){const dirPath=(dir.path||dir.name||"").replace(/\\/g,"/").replace(/^\/|\/$/g,"");if(dirPath===normalised)return dir.children||dir;const found=this.#findManifestNode(dir.children||dir,normalised);if(found)return found}return null}#manifestNodeToStructure(node,rootPath,options={}){const{fileFilter=null}=options;const ALLOWED_EXTS=[".mjs",".cjs",".js"];const structure={files:[],directories:[]};for(const file of node.files||[]){const filePath=file.path||file.relativePath||"";const fullName=file.fullName||filePath.split("/").pop();const lastDot=fullName.lastIndexOf(".");const ext=lastDot>=0?fullName.slice(lastDot):"";if(!ALLOWED_EXTS.includes(ext))continue;if(fullName.startsWith("__"))continue;if(fileFilter&&!fileFilter(fullName))continue;const name=file.name||(lastDot>=0?fullName.slice(0,lastDot):fullName);structure.files.push({path:filePath,name,fullName,moduleID:this.slothlet.helpers.sanitize.getModuleId(filePath,rootPath)})}if(!fileFilter){for(const dir of node.directories||[]){const dirPath=dir.path||dir.name||"";structure.directories.push({path:dirPath,name:dir.name||dirPath.split("/").pop(),children:this.#manifestNodeToStructure(dir.children||dir,dirPath,options)})}}return structure}async#loadModuleBrowser(filePath){const resolveModuleSpecifier=this.slothlet.config?.resolveModuleSpecifier??(({path:p})=>{const base=this.slothlet.config?.base??this.slothlet.config?.dir??"";const leadingSlash=base.startsWith("/")?"":"/";const baseUrl=/^[a-zA-Z][\w+\-.]*:\/\//.test(base)?base.endsWith("/")?base:base+"/":"file://"+leadingSlash+base.replace(/\/?$/,"/");return new URL(p,baseUrl).href});const fullName=filePath.split("/").pop();const lastDot=fullName.lastIndexOf(".");const name=lastDot>=0?fullName.slice(0,lastDot):fullName;const specifier=resolveModuleSpecifier({path:filePath,name,fullName});const module=await import(specifier);return module}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};
package/dist/slothlet.mjs CHANGED
@@ -14,4 +14,4 @@
14
14
  limitations under the License.
15
15
  */
16
16
 
17
- import{readdirSync}from"node:fs";import{dirname,join}from"node:path";import{fileURLToPath,pathToFileURL}from"node:url";import{getContextManager}from"@cldmv/slothlet/factories/context";import{SlothletError,SlothletWarning,SlothletDebug}from"@cldmv/slothlet/errors";import{registerInstance}from"@cldmv/slothlet/handlers/lifecycle-token";import{resolveWrapper}from"@cldmv/slothlet/handlers/unified-wrapper";import{initI18n}from"@cldmv/slothlet/i18n";import{enableEventEmitterPatching,disableEventEmitterPatching,cleanupEventEmitterResources,setApiContextChecker}from"@cldmv/slothlet/helpers/eventemitter-context";class Slothlet{static RESERVED_ROOT_KEYS=["slothlet","shutdown","destroy"];static SKIP_PROPS=["__metadata","__type","_materialize","_impl","____slothletInternal"];constructor(){this.SlothletError=SlothletError;this.SlothletWarning=SlothletWarning;this.debugLogger=null;this.instanceID=null;this.config=null;this.envTarget="node";this.api=null;this.boundApi=null;this.contextManager=null;this.isLoaded=false;this.reference=null;this.context=null;this.envSnapshot=null;this._totalLazyCount=0;this._unmaterializedLazyCount=0;this._materializationComplete=false;this._materializationWaiters=[];this._materializationCompleteEmitted=false;this.componentCategories=["helpers","handlers","builders","processors","modes"];for(const category of this.componentCategories){this[category]={}}}async _initializeComponents(){if(this.envTarget==="browser"){await this._initializeComponentsBrowser();return}const baseDir=join(dirname(fileURLToPath(import.meta.url)),"lib");for(const category of this.componentCategories){const categoryDir=join(baseDir,category);const files=readdirSync(categoryDir).filter(f=>f.endsWith(".mjs"));for(const file of files){const filePath=join(categoryDir,file);try{const module=await import(pathToFileURL(filePath).href);const classExports=Object.values(module).filter(exp=>typeof exp==="function"&&exp.slothletProperty);for(const ClassExport of classExports){const propName=ClassExport.slothletProperty;this[category][propName]=new ClassExport(this);if(this.config?.debug?.initialization){this.debug("initialization",{key:"DEBUG_MODE_COMPONENT_INITIALIZED",component:ClassExport.name,category,propertyName:propName})}}}catch(error){throw new this.SlothletError("MODULE_IMPORT_FAILED",{modulePath:filePath},error)}}}}async _initializeComponentsBrowser(){const BROWSER_COMPONENT_SPECIFIERS=["@cldmv/slothlet/builders/api-assignment","@cldmv/slothlet/builders/api_builder","@cldmv/slothlet/builders/builder","@cldmv/slothlet/builders/modes-processor","@cldmv/slothlet/handlers/api-cache-manager","@cldmv/slothlet/handlers/api-manager","@cldmv/slothlet/handlers/hook-manager","@cldmv/slothlet/handlers/lifecycle","@cldmv/slothlet/handlers/materialize-manager","@cldmv/slothlet/handlers/metadata","@cldmv/slothlet/handlers/module-manager","@cldmv/slothlet/handlers/ownership","@cldmv/slothlet/handlers/permission-manager","@cldmv/slothlet/handlers/version-manager","@cldmv/slothlet/helpers/config","@cldmv/slothlet/helpers/hint-detector","@cldmv/slothlet/helpers/modes-utils","@cldmv/slothlet/helpers/resolve-from-caller","@cldmv/slothlet/helpers/sanitize","@cldmv/slothlet/helpers/utilities","@cldmv/slothlet/modes/eager","@cldmv/slothlet/modes/lazy","@cldmv/slothlet/processors/flatten","@cldmv/slothlet/processors/loader"];for(const specifier of BROWSER_COMPONENT_SPECIFIERS){const parts=specifier.split("/");const category=parts[2];const module=await import(specifier);const classExports=Object.values(module).filter(exp=>typeof exp==="function"&&exp.slothletProperty);for(const ClassExport of classExports){const propName=ClassExport.slothletProperty;this[category][propName]=new ClassExport(this)}}}_setupLifecycleSubscribers(){if(!this.handlers.lifecycle){return}if(this.handlers.metadata){this.handlers.lifecycle.subscribe("impl:created",(data,token)=>{this.handlers.metadata.tagSystemMetadata(data.impl,{filePath:data.filePath,apiPath:data.apiPath,moduleID:data.moduleID,sourceFolder:data.sourceFolder},token)});this.handlers.lifecycle.subscribe("impl:changed",(data,token)=>{this.handlers.metadata.tagSystemMetadata(data.impl,{filePath:data.filePath,apiPath:data.apiPath,moduleID:data.moduleID,sourceFolder:data.sourceFolder},token)});this.handlers.lifecycle.subscribe("impl:removed",data=>{if(data.apiPath){const rootSegment=data.apiPath.split(".")[0];this.handlers.metadata.removeUserMetadataByApiPath(rootSegment)}})}if(this.handlers.ownership){this.handlers.lifecycle.subscribe("impl:created",data=>{const collisionMode=this.config?.collision?.api||"merge";const implValue=data.wrapper?.__impl??data.impl;this.handlers.ownership.register({moduleID:data.moduleID,apiPath:data.apiPath,value:implValue,source:data.source,filePath:data.filePath,collisionMode})});this.handlers.lifecycle.subscribe("impl:changed",data=>{const collisionMode=this.config?.collision?.api||"merge";const implValue=data.wrapper?.__impl??data.impl;const currentOwner=this.handlers.ownership.getCurrentOwner(data.apiPath);if(currentOwner?.moduleID!==data.moduleID){this.handlers.ownership.register({moduleID:data.moduleID,apiPath:data.apiPath,value:implValue,source:data.source,filePath:data.filePath,collisionMode})}})}}_registerLazyWrapper(){this._totalLazyCount++;this._unmaterializedLazyCount++;if(this.config?.debug?.materialize){this.debug("materialize",{key:"DEBUG_MODE_LAZY_WRAPPER_REGISTERED",total:this._totalLazyCount,unmaterialized:this._unmaterializedLazyCount})}}_onWrapperMaterialized(){this._unmaterializedLazyCount--;if(this.config?.debug?.materialize){this.debug("materialize",{key:"DEBUG_MODE_LAZY_WRAPPER_MATERIALIZED",total:this._totalLazyCount,unmaterialized:this._unmaterializedLazyCount,percentage:this._totalLazyCount>0?(this._totalLazyCount-this._unmaterializedLazyCount)/this._totalLazyCount*100:100})}if(this._unmaterializedLazyCount===0&&!this._materializationComplete){this._materializationComplete=true;if(this.config?.debug?.materialize){this.debug("materialize",{key:"DEBUG_MODE_ALL_LAZY_WRAPPERS_MATERIALIZED",total:this._totalLazyCount})}const waiters=this._materializationWaiters.splice(0);for(const resolve of waiters){resolve()}if(this.config?.tracking?.materialization&&!this._materializationCompleteEmitted){this._materializationCompleteEmitted=true;if(this.handlers?.lifecycle){this.handlers.lifecycle.emit("materialized:complete",{total:this._totalLazyCount,timestamp:Date.now()})}}}}_captureEnvSnapshot(envConfig){const rawInclude=envConfig?.include;const include=Array.isArray(rawInclude)?rawInclude.filter(key=>typeof key==="string"):null;const useAllowlist=include!==null&&include.length>0;const raw=useAllowlist?include.reduce((acc,key)=>{if(Object.prototype.hasOwnProperty.call(process.env,key)){acc[key]=process.env[key]}return acc},Object.create(null)):{...process.env};return Object.freeze(raw)}async load(config={},preservedInstanceID=null){this.config=config;this.envTarget=config.platform==="browser"||config.platform!=="node"&&config.manifest!=null?"browser":"node";if(!this.envSnapshot){this.envSnapshot=this.envTarget==="browser"?Object.freeze(Object.create(null)):this._captureEnvSnapshot(config.env)}this.debugLogger=new SlothletDebug(config);await this._initializeComponents();registerInstance(this);this._setupLifecycleSubscribers();this.config=this.helpers.config.transformConfig(config);if(this.config?.i18n?.language){initI18n({language:this.config.i18n.language})}this.debugLogger=new SlothletDebug(this.config);this.instanceID=preservedInstanceID||this.helpers.utilities.generateId();this.reference=this.config.reference;this.context=this.config.context;this.contextManager=getContextManager(this.config.runtime);setApiContextChecker(()=>{const ctx=this.contextManager.tryGetContext();return!!(ctx&&ctx.self)});let store;if(preservedInstanceID&&this.contextManager.instances.has(preservedInstanceID)){this.contextManager.cleanup(preservedInstanceID);store=this.contextManager.initialize(this.instanceID,this.config)}else{store=this.contextManager.initialize(this.instanceID,this.config)}enableEventEmitterPatching();if(typeof this.contextManager.registerEventEmitterContextChecker==="function"){this.contextManager.registerEventEmitterContextChecker()}const baseModuleId=`base_${this.helpers.utilities.generateId().substring(0,8)}`;const baseApi=await this.builders.builder.buildAPI({dir:this.config.dir,mode:this.config.mode,moduleID:baseModuleId});this.api=baseApi;const apiWithBuiltins=await this.buildFinalAPI(this.api);if(this.handlers.apiCacheManager){this.handlers.apiCacheManager.set(baseModuleId,{endpoint:".",moduleID:baseModuleId,api:this.api,folderPath:this.config.dir,mode:this.config.mode,sanitizeOptions:this.config.sanitize||{},collisionMode:this.config.collision?.api||"merge",config:{...this.config},timestamp:Date.now()})}this.injectRuntimeMetadataFunctions(apiWithBuiltins);if(this.config.metadata&&typeof this.config.metadata==="object"){for(const[key,value]of Object.entries(this.config.metadata)){this.handlers.metadata.setGlobalMetadata(key,value)}this.handlers.metadata.registerUserMetadata(baseModuleId,this.config.metadata)}if(this.handlers.ownership){this.handlers.ownership.registerSubtree(apiWithBuiltins,baseModuleId,"");this.handlers.ownership.setModuleEndpoint(baseModuleId,".")}if(!this.boundApi){const isCallable=typeof this.api==="function"||this.api&&typeof this.api.default==="function";const proxyTarget=isCallable?function(){}:{};this.boundApi=new Proxy(proxyTarget,{get:(target,prop)=>this.api?this.api[prop]:void 0,set:(target,prop,value)=>{if(this.api){this.api[prop]=value}return true},has:(target,prop)=>this.api?prop in this.api:false,ownKeys:____target=>this.api?Reflect.ownKeys(this.api):[],deleteProperty:(target,prop)=>this.api?delete this.api[prop]:true,apply:(target,thisArg,args)=>this.api?Reflect.apply(this.api,thisArg,args):void 0,construct:(target,args)=>this.api?Reflect.construct(this.api,args):{},getOwnPropertyDescriptor:(target,prop)=>{if(isCallable&&prop==="prototype"){return Object.getOwnPropertyDescriptor(target,prop)}if(this.api&&prop in this.api){const desc=Object.getOwnPropertyDescriptor(this.api,prop);if(desc){return{...desc,configurable:true}}}return void 0}})}store.self=this.boundApi;store.context=this.context||{};store.slothlet=this;if(this.reference&&typeof this.reference==="object"){Object.assign(this.boundApi,this.reference)}this.isLoaded=true;return this.boundApi}async reload(options={}){const{keepInstanceID=false}=options;if(!this.config?.dir){throw new SlothletError("INVALID_CONFIG_NOT_LOADED",{operation:"reload",validationError:true})}const operationHistory=this.handlers.apiManager?.state?.operationHistory?[...this.handlers.apiManager.state.operationHistory]:[];await this._clearModuleCaches();const oldInstanceID=this.instanceID;if(!keepInstanceID){this.instanceID=`${oldInstanceID}_reload_${Date.now()}`;if(this._typescriptCacheDirs?.size){const{rm}=await import("node:fs/promises");await Promise.allSettled([...this._typescriptCacheDirs].map(dir=>rm(dir,{recursive:true,force:true})));this._typescriptCacheDirs.clear()}}const savedMetadataState=this.handlers.metadata?.exportUserState?.();const savedHooks=this.handlers.hookManager?.exportHooks?.();await this.load(this.config,this.instanceID);if(savedMetadataState&&this.handlers.metadata){this.handlers.metadata.importUserState(savedMetadataState)}if(savedHooks?.length&&this.handlers.hookManager){this.handlers.hookManager.importHooks(savedHooks)}for(const[,store]of this.contextManager.instances){if(store.parentInstanceID===oldInstanceID){store.parentInstanceID=this.instanceID}}if(oldInstanceID&&oldInstanceID!==this.instanceID&&this.contextManager.instances?.has(oldInstanceID)){this.contextManager.cleanup(oldInstanceID)}for(const operation of operationHistory){if(operation.type==="add"){await this.handlers.apiManager.addApiComponent({apiPath:operation.apiPath,folderPath:operation.folderPath,options:{...operation.options||{},recordHistory:false},moduleID:`replay_${this.helpers.utilities.generateId().substring(0,8)}`,versionConfig:operation.versionConfig||null})}else if(operation.type==="remove"){await this.handlers.apiManager.removeApiComponent(operation.apiPath,{recordHistory:false})}else if(operation.type==="addPermissionRule"){if(this.handlers.permissionManager){this.handlers.permissionManager.addRule(operation.rule,operation.ownerModuleID,operation.ruleId)}}else if(operation.type==="removePermissionRule"){if(this.handlers.permissionManager){this.handlers.permissionManager.removeRule(operation.ruleId,operation.callerModuleID)}}}return this.boundApi}async _clearModuleCaches(){const targetDir=this.config.dir;const{resolve}=await import("node:path");const{createRequire}=await import("node:module");const require2=createRequire(import.meta.url);const absoluteTargetDir=resolve(targetDir);for(const key of Object.keys(require2.cache)){if(key.startsWith(absoluteTargetDir)){delete require2.cache[key]}}}injectRuntimeMetadataFunctions(api){if(!api.slothlet?.metadata){return}const metadataHandler=this.handlers.metadata;api.slothlet.metadata.get=async function slothlet_metadata_get_runtime(path){return metadataHandler.get(path)};api.slothlet.metadata.self=function slothlet_metadata_self_runtime(){return metadataHandler.self()};api.slothlet.metadata.caller=function slothlet_metadata_caller_runtime(){return metadataHandler.caller()}}async _drainInFlightLoads(){if(!this.api)return;const pending=[];const seen=new Set;const collect=(obj,depth=0)=>{const objType=typeof obj;if(!obj||objType!=="object"&&objType!=="function"||depth>15||seen.has(obj))return;seen.add(obj);try{if(obj.__isVersionDispatcher===true)return;const wrapper=resolveWrapper(obj);if(wrapper){const mat=wrapper.____slothletInternal.materializationPromise;if(mat)pending.push(mat);for(const key of Object.keys(wrapper)){if(!key.startsWith("____"))collect(wrapper[key],depth+1)}return}for(const key of Object.keys(obj)){collect(obj[key],depth+1)}}catch{}};for(const key of Object.keys(this.api)){collect(this.api[key])}if(pending.length>0){await Promise.allSettled(pending)}}async shutdown(){if(!this.isLoaded){return}await this._drainInFlightLoads();disableEventEmitterPatching();cleanupEventEmitterResources();if(this.instanceID&&this.contextManager){this.contextManager.cleanup(this.instanceID)}if(this.handlers.ownership){this.handlers.ownership.clear()}this.handlers.versionManager?.shutdown();await this.handlers.permissionManager?.shutdown();if(this._typescriptCacheDirs?.size){const{rm}=await import("node:fs/promises");await Promise.allSettled([...this._typescriptCacheDirs].map(dir=>rm(dir,{recursive:true,force:true})));this._typescriptCacheDirs.clear()}this.isLoaded=false}debug(code,context={}){if(this.debugLogger){this.debugLogger.log(code,context)}}getAPI(){if(!this.isLoaded){throw new SlothletError("INVALID_CONFIG_NOT_LOADED",{operation:"getAPI"},null,{validationError:true})}return this.boundApi}getDiagnostics(){return{instanceID:this.instanceID,isLoaded:this.isLoaded,config:this.config,context:this.contextManager?.getDiagnostics()||null,ownership:this.handlers.ownership?.getDiagnostics()||null}}getOwnership(){if(!this.handlers.ownership){return null}return this.handlers.ownership.getDiagnostics()}buildFinalAPI(userApi){return this.builders.apiBuilder.buildFinalAPI(userApi)}}async function slothlet(config){const instance=new Slothlet;const api=await instance.load(config);return api}var stdin_default=slothlet;export{stdin_default as default,slothlet};
17
+ import{isNode,fs,fsp,path,url,createRequire}from"@cldmv/slothlet/helpers/platform";import{getContextManager}from"@cldmv/slothlet/factories/context";import{SlothletError,SlothletWarning,SlothletDebug}from"@cldmv/slothlet/errors";import{registerInstance}from"@cldmv/slothlet/handlers/lifecycle-token";import{resolveWrapper}from"@cldmv/slothlet/handlers/unified-wrapper";import{initI18n}from"@cldmv/slothlet/i18n";import{enableEventEmitterPatching,disableEventEmitterPatching,cleanupEventEmitterResources,setApiContextChecker}from"@cldmv/slothlet/helpers/eventemitter-context";class Slothlet{static RESERVED_ROOT_KEYS=["slothlet","shutdown","destroy"];static SKIP_PROPS=["__metadata","__type","_materialize","_impl","____slothletInternal"];constructor(){this.SlothletError=SlothletError;this.SlothletWarning=SlothletWarning;this.debugLogger=null;this.instanceID=null;this.config=null;this.envTarget="node";this.api=null;this.boundApi=null;this.contextManager=null;this.isLoaded=false;this.reference=null;this.context=null;this.envSnapshot=null;this._totalLazyCount=0;this._unmaterializedLazyCount=0;this._materializationComplete=false;this._materializationWaiters=[];this._materializationCompleteEmitted=false;this.componentCategories=["helpers","handlers","builders","processors","modes"];for(const category of this.componentCategories){this[category]={}}}async _initializeComponents(){if(this.envTarget==="browser"){await this._initializeComponentsBrowser();return}const baseDir=path.join(path.dirname(url.fileURLToPath(import.meta.url)),"lib");for(const category of this.componentCategories){const categoryDir=path.join(baseDir,category);const files=fs.readdirSync(categoryDir).filter(f=>f.endsWith(".mjs"));for(const file of files){const filePath=path.join(categoryDir,file);try{const module=await import(url.pathToFileURL(filePath).href);const classExports=Object.values(module).filter(exp=>typeof exp==="function"&&exp.slothletProperty);for(const ClassExport of classExports){const propName=ClassExport.slothletProperty;this[category][propName]=new ClassExport(this);if(this.config?.debug?.initialization){this.debug("initialization",{key:"DEBUG_MODE_COMPONENT_INITIALIZED",component:ClassExport.name,category,propertyName:propName})}}}catch(error){throw new this.SlothletError("MODULE_IMPORT_FAILED",{modulePath:filePath},error)}}}}async _initializeComponentsBrowser(){const BROWSER_COMPONENT_SPECIFIERS=["@cldmv/slothlet/builders/api-assignment","@cldmv/slothlet/builders/api_builder","@cldmv/slothlet/builders/builder","@cldmv/slothlet/builders/modes-processor","@cldmv/slothlet/handlers/api-cache-manager","@cldmv/slothlet/handlers/api-manager","@cldmv/slothlet/handlers/hook-manager","@cldmv/slothlet/handlers/lifecycle","@cldmv/slothlet/handlers/materialize-manager","@cldmv/slothlet/handlers/metadata","@cldmv/slothlet/handlers/module-manager","@cldmv/slothlet/handlers/ownership","@cldmv/slothlet/handlers/permission-manager","@cldmv/slothlet/handlers/version-manager","@cldmv/slothlet/helpers/config","@cldmv/slothlet/helpers/hint-detector","@cldmv/slothlet/helpers/modes-utils","@cldmv/slothlet/helpers/resolve-from-caller","@cldmv/slothlet/helpers/sanitize","@cldmv/slothlet/helpers/utilities","@cldmv/slothlet/modes/eager","@cldmv/slothlet/modes/lazy","@cldmv/slothlet/processors/flatten","@cldmv/slothlet/processors/loader"];for(const specifier of BROWSER_COMPONENT_SPECIFIERS){const parts=specifier.split("/");const category=parts[2];const module=await import(specifier);const classExports=Object.values(module).filter(exp=>typeof exp==="function"&&exp.slothletProperty);for(const ClassExport of classExports){const propName=ClassExport.slothletProperty;this[category][propName]=new ClassExport(this)}}}_setupLifecycleSubscribers(){if(!this.handlers.lifecycle){return}if(this.handlers.metadata){this.handlers.lifecycle.subscribe("impl:created",(data,token)=>{this.handlers.metadata.tagSystemMetadata(data.impl,{filePath:data.filePath,apiPath:data.apiPath,moduleID:data.moduleID,sourceFolder:data.sourceFolder},token)});this.handlers.lifecycle.subscribe("impl:changed",(data,token)=>{this.handlers.metadata.tagSystemMetadata(data.impl,{filePath:data.filePath,apiPath:data.apiPath,moduleID:data.moduleID,sourceFolder:data.sourceFolder},token)});this.handlers.lifecycle.subscribe("impl:removed",data=>{if(data.apiPath){const rootSegment=data.apiPath.split(".")[0];this.handlers.metadata.removeUserMetadataByApiPath(rootSegment)}})}if(this.handlers.ownership){this.handlers.lifecycle.subscribe("impl:created",data=>{const collisionMode=this.config?.collision?.api||"merge";const implValue=data.wrapper?.__impl??data.impl;this.handlers.ownership.register({moduleID:data.moduleID,apiPath:data.apiPath,value:implValue,source:data.source,filePath:data.filePath,collisionMode})});this.handlers.lifecycle.subscribe("impl:changed",data=>{const collisionMode=this.config?.collision?.api||"merge";const implValue=data.wrapper?.__impl??data.impl;const currentOwner=this.handlers.ownership.getCurrentOwner(data.apiPath);if(currentOwner?.moduleID!==data.moduleID){this.handlers.ownership.register({moduleID:data.moduleID,apiPath:data.apiPath,value:implValue,source:data.source,filePath:data.filePath,collisionMode})}})}}_registerLazyWrapper(){this._totalLazyCount++;this._unmaterializedLazyCount++;if(this.config?.debug?.materialize){this.debug("materialize",{key:"DEBUG_MODE_LAZY_WRAPPER_REGISTERED",total:this._totalLazyCount,unmaterialized:this._unmaterializedLazyCount})}}_onWrapperMaterialized(){this._unmaterializedLazyCount--;if(this.config?.debug?.materialize){this.debug("materialize",{key:"DEBUG_MODE_LAZY_WRAPPER_MATERIALIZED",total:this._totalLazyCount,unmaterialized:this._unmaterializedLazyCount,percentage:this._totalLazyCount>0?(this._totalLazyCount-this._unmaterializedLazyCount)/this._totalLazyCount*100:100})}if(this._unmaterializedLazyCount===0&&!this._materializationComplete){this._materializationComplete=true;if(this.config?.debug?.materialize){this.debug("materialize",{key:"DEBUG_MODE_ALL_LAZY_WRAPPERS_MATERIALIZED",total:this._totalLazyCount})}const waiters=this._materializationWaiters.splice(0);for(const resolve of waiters){resolve()}if(this.config?.tracking?.materialization&&!this._materializationCompleteEmitted){this._materializationCompleteEmitted=true;if(this.handlers?.lifecycle){this.handlers.lifecycle.emit("materialized:complete",{total:this._totalLazyCount,timestamp:Date.now()})}}}}_captureEnvSnapshot(envConfig){const rawInclude=envConfig?.include;const include=Array.isArray(rawInclude)?rawInclude.filter(key=>typeof key==="string"):null;const useAllowlist=include!==null&&include.length>0;const raw=useAllowlist?include.reduce((acc,key)=>{if(Object.prototype.hasOwnProperty.call(process.env,key)){acc[key]=process.env[key]}return acc},Object.create(null)):{...process.env};return Object.freeze(raw)}async load(config={},preservedInstanceID=null){this.config=config;this.envTarget=config.platform==="browser"||config.platform!=="node"&&config.manifest!=null?"browser":"node";if(!this.envSnapshot){this.envSnapshot=this.envTarget==="browser"?Object.freeze(Object.create(null)):this._captureEnvSnapshot(config.env)}this.debugLogger=new SlothletDebug(config);await this._initializeComponents();registerInstance(this);this._setupLifecycleSubscribers();this.config=this.helpers.config.transformConfig(config);if(this.config?.i18n?.language){initI18n({language:this.config.i18n.language})}this.debugLogger=new SlothletDebug(this.config);this.instanceID=preservedInstanceID||this.helpers.utilities.generateId();this.reference=this.config.reference;this.context=this.config.context;this.contextManager=getContextManager(this.envTarget==="browser"?"live":this.config.runtime);setApiContextChecker(()=>{const ctx=this.contextManager.tryGetContext();return!!(ctx&&ctx.self)});let store;if(preservedInstanceID&&this.contextManager.instances.has(preservedInstanceID)){this.contextManager.cleanup(preservedInstanceID);store=this.contextManager.initialize(this.instanceID,this.config)}else{store=this.contextManager.initialize(this.instanceID,this.config)}enableEventEmitterPatching();if(typeof this.contextManager.registerEventEmitterContextChecker==="function"){this.contextManager.registerEventEmitterContextChecker()}const baseModuleId=`base_${this.helpers.utilities.generateId().substring(0,8)}`;const baseApi=await this.builders.builder.buildAPI({dir:this.config.dir,mode:this.config.mode,moduleID:baseModuleId});this.api=baseApi;const apiWithBuiltins=await this.buildFinalAPI(this.api);if(this.handlers.apiCacheManager){this.handlers.apiCacheManager.set(baseModuleId,{endpoint:".",moduleID:baseModuleId,api:this.api,folderPath:this.config.dir,mode:this.config.mode,sanitizeOptions:this.config.sanitize||{},collisionMode:this.config.collision?.api||"merge",config:{...this.config},timestamp:Date.now()})}this.injectRuntimeMetadataFunctions(apiWithBuiltins);if(this.config.metadata&&typeof this.config.metadata==="object"){for(const[key,value]of Object.entries(this.config.metadata)){this.handlers.metadata.setGlobalMetadata(key,value)}this.handlers.metadata.registerUserMetadata(baseModuleId,this.config.metadata)}if(this.handlers.ownership){this.handlers.ownership.registerSubtree(apiWithBuiltins,baseModuleId,"");this.handlers.ownership.setModuleEndpoint(baseModuleId,".")}if(!this.boundApi){const isCallable=typeof this.api==="function"||this.api&&typeof this.api.default==="function";const proxyTarget=isCallable?function(){}:{};this.boundApi=new Proxy(proxyTarget,{get:(target,prop)=>this.api?this.api[prop]:void 0,set:(target,prop,value)=>{if(this.api){this.api[prop]=value}return true},has:(target,prop)=>this.api?prop in this.api:false,ownKeys:____target=>this.api?Reflect.ownKeys(this.api):[],deleteProperty:(target,prop)=>this.api?delete this.api[prop]:true,apply:(target,thisArg,args)=>this.api?Reflect.apply(this.api,thisArg,args):void 0,construct:(target,args)=>this.api?Reflect.construct(this.api,args):{},getOwnPropertyDescriptor:(target,prop)=>{if(isCallable&&prop==="prototype"){return Object.getOwnPropertyDescriptor(target,prop)}if(this.api&&prop in this.api){const desc=Object.getOwnPropertyDescriptor(this.api,prop);if(desc){return{...desc,configurable:true}}}return void 0}})}store.self=this.boundApi;store.context=this.context||{};store.slothlet=this;if(this.reference&&typeof this.reference==="object"){Object.assign(this.boundApi,this.reference)}this.isLoaded=true;return this.boundApi}async reload(options={}){const{keepInstanceID=false}=options;if(!this.config?.dir){throw new SlothletError("INVALID_CONFIG_NOT_LOADED",{operation:"reload",validationError:true})}const operationHistory=this.handlers.apiManager?.state?.operationHistory?[...this.handlers.apiManager.state.operationHistory]:[];await this._clearModuleCaches();const oldInstanceID=this.instanceID;if(!keepInstanceID){this.instanceID=`${oldInstanceID}_reload_${Date.now()}`;if(isNode&&this._typescriptCacheDirs?.size){await Promise.allSettled([...this._typescriptCacheDirs].map(dir=>fsp.rm(dir,{recursive:true,force:true})));this._typescriptCacheDirs.clear()}}const savedMetadataState=this.handlers.metadata?.exportUserState?.();const savedHooks=this.handlers.hookManager?.exportHooks?.();await this.load(this.config,this.instanceID);if(savedMetadataState&&this.handlers.metadata){this.handlers.metadata.importUserState(savedMetadataState)}if(savedHooks?.length&&this.handlers.hookManager){this.handlers.hookManager.importHooks(savedHooks)}for(const[,store]of this.contextManager.instances){if(store.parentInstanceID===oldInstanceID){store.parentInstanceID=this.instanceID}}if(oldInstanceID&&oldInstanceID!==this.instanceID&&this.contextManager.instances?.has(oldInstanceID)){this.contextManager.cleanup(oldInstanceID)}for(const operation of operationHistory){if(operation.type==="add"){await this.handlers.apiManager.addApiComponent({apiPath:operation.apiPath,folderPath:operation.folderPath,options:{...operation.options||{},recordHistory:false},moduleID:`replay_${this.helpers.utilities.generateId().substring(0,8)}`,versionConfig:operation.versionConfig||null})}else if(operation.type==="remove"){await this.handlers.apiManager.removeApiComponent(operation.apiPath,{recordHistory:false})}else if(operation.type==="addPermissionRule"){if(this.handlers.permissionManager){this.handlers.permissionManager.addRule(operation.rule,operation.ownerModuleID,operation.ruleId)}}else if(operation.type==="removePermissionRule"){if(this.handlers.permissionManager){this.handlers.permissionManager.removeRule(operation.ruleId,operation.callerModuleID)}}}return this.boundApi}async _clearModuleCaches(){if(!isNode)return;const targetDir=this.config.dir;const require2=createRequire(import.meta.url);const absoluteTargetDir=path.resolve(targetDir);for(const key of Object.keys(require2.cache)){if(key.startsWith(absoluteTargetDir)){delete require2.cache[key]}}}injectRuntimeMetadataFunctions(api){if(!api.slothlet?.metadata){return}const metadataHandler=this.handlers.metadata;api.slothlet.metadata.get=async function slothlet_metadata_get_runtime(path2){return metadataHandler.get(path2)};api.slothlet.metadata.self=function slothlet_metadata_self_runtime(){return metadataHandler.self()};api.slothlet.metadata.caller=function slothlet_metadata_caller_runtime(){return metadataHandler.caller()}}async _drainInFlightLoads(){if(!this.api)return;const pending=[];const seen=new Set;const collect=(obj,depth=0)=>{const objType=typeof obj;if(!obj||objType!=="object"&&objType!=="function"||depth>15||seen.has(obj))return;seen.add(obj);try{if(obj.__isVersionDispatcher===true)return;const wrapper=resolveWrapper(obj);if(wrapper){const mat=wrapper.____slothletInternal.materializationPromise;if(mat)pending.push(mat);for(const key of Object.keys(wrapper)){if(!key.startsWith("____"))collect(wrapper[key],depth+1)}return}for(const key of Object.keys(obj)){collect(obj[key],depth+1)}}catch{}};for(const key of Object.keys(this.api)){collect(this.api[key])}if(pending.length>0){await Promise.allSettled(pending)}}async shutdown(){if(!this.isLoaded){return}await this._drainInFlightLoads();disableEventEmitterPatching();cleanupEventEmitterResources();if(this.instanceID&&this.contextManager){this.contextManager.cleanup(this.instanceID)}if(this.handlers.ownership){this.handlers.ownership.clear()}this.handlers.versionManager?.shutdown();await this.handlers.permissionManager?.shutdown();if(isNode&&this._typescriptCacheDirs?.size){await Promise.allSettled([...this._typescriptCacheDirs].map(dir=>fsp.rm(dir,{recursive:true,force:true})));this._typescriptCacheDirs.clear()}this.isLoaded=false}debug(code,context={}){if(this.debugLogger){this.debugLogger.log(code,context)}}getAPI(){if(!this.isLoaded){throw new SlothletError("INVALID_CONFIG_NOT_LOADED",{operation:"getAPI"},null,{validationError:true})}return this.boundApi}getDiagnostics(){return{instanceID:this.instanceID,isLoaded:this.isLoaded,config:this.config,context:this.contextManager?.getDiagnostics()||null,ownership:this.handlers.ownership?.getDiagnostics()||null}}getOwnership(){if(!this.handlers.ownership){return null}return this.handlers.ownership.getDiagnostics()}buildFinalAPI(userApi){return this.builders.apiBuilder.buildFinalAPI(userApi)}}async function slothlet(config){const instance=new Slothlet;const api=await instance.load(config);return api}var stdin_default=slothlet;export{stdin_default as default,slothlet};
package/index.mjs CHANGED
@@ -17,7 +17,10 @@
17
17
  */
18
18
 
19
19
  // Custom uncaught exception handler for SlothletError
20
- process.on("uncaughtException", (error) => {
20
+ // `process` is undefined in a browser, so define the handler unconditionally but
21
+ // only register it under Node — keeps this entry module loadable in a browser (#123).
22
+ const __isNode = typeof process !== "undefined" && Boolean(process?.versions?.node);
23
+ const __slothletUncaughtHandler = (error) => {
21
24
  if (error.name === "SlothletError") {
22
25
  console.error("\n================================================================================");
23
26
  console.error(`ERROR [${error.code}]: ${error.message}`);
@@ -81,17 +84,21 @@ process.on("uncaughtException", (error) => {
81
84
 
82
85
  // Re-throw other errors to let Node.js handle them
83
86
  throw error;
84
- });
87
+ };
88
+ if (__isNode) process.on("uncaughtException", __slothletUncaughtHandler);
85
89
 
86
90
  // Development environment check (must happen before slothlet imports)
87
- const devcheckPromise = (async () => {
88
- try {
89
- await import("@cldmv/slothlet/devcheck");
90
- } catch {
91
- // Ignore errors (e.g., devcheck.mjs not found in production)
92
- // devcheck.mjs uses process.exit() for environment errors
93
- }
94
- })();
91
+ // devcheck is a Node-only dev-environment check; skip it entirely in a browser.
92
+ const devcheckPromise = __isNode
93
+ ? (async () => {
94
+ try {
95
+ await import("@cldmv/slothlet/devcheck");
96
+ } catch {
97
+ // Ignore errors (e.g., devcheck.mjs not found in production)
98
+ // devcheck.mjs uses process.exit() for environment errors
99
+ }
100
+ })()
101
+ : Promise.resolve();
95
102
 
96
103
  /**
97
104
  * Creates a slothlet API instance with live-binding context and AsyncLocalStorage support.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cldmv/slothlet",
3
- "version": "3.9.0",
3
+ "version": "3.9.2",
4
4
  "moduleVersions": {
5
5
  "lazy": "3.0.0",
6
6
  "eager": "3.0.0",
@@ -127,6 +127,10 @@
127
127
  "types": "./types/dist/lib/i18n/translations.d.mts",
128
128
  "import": "./dist/lib/i18n/translations.mjs"
129
129
  },
130
+ "./i18n/language/*": {
131
+ "slothlet-dev": "./src/lib/i18n/languages/*",
132
+ "default": "./dist/lib/i18n/languages/*"
133
+ },
130
134
  "./schemas/slothlet.module.schema.json": "./schemas/slothlet.module.schema.json"
131
135
  },
132
136
  "types": "./types/index.d.mts",
@@ -149,6 +153,7 @@
149
153
  "ci:test:types": "npm run build:dist && npm run build:types && npm run test:types",
150
154
  "test:performance": "node tests/performance/performance-benchmark-aggregated.mjs",
151
155
  "test:performance-simple": "node tests/performance/performance-benchmark.mjs",
156
+ "test:browser": "node --conditions=slothlet-dev tests/browser/playwright-smoke.mjs",
152
157
  "lint": "eslint --config .configs/eslint.config.mjs .",
153
158
  "inspect": "node tools/dev/inspect-api-structure.mjs",
154
159
  "check:node-versions": "node tools/dev/check-node-versions.mjs",
@@ -243,7 +248,7 @@
243
248
  "zero-dependencies"
244
249
  ],
245
250
  "engines": {
246
- "node": ">=20.19.0"
251
+ "node": ">=22.0.0"
247
252
  },
248
253
  "author": {
249
254
  "name": "Shinrai",
@@ -296,6 +301,7 @@
296
301
  "jsdoc-to-markdown": "^9.1.3",
297
302
  "jsdoc2md": "^1.0.0",
298
303
  "jsonc-parser": "^3.3.1",
304
+ "playwright": "^1.60.0",
299
305
  "prettier": "^3.8.3",
300
306
  "shx": "^0.4.0",
301
307
  "typescript": "^6.0.3",
@@ -1 +1 @@
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,oDAAys6B;IAAA,6CAAqR;IAAA,uFAA0vB;IAAA,sDAA8sJ;IAAA,qDAAmkB;IAAA,kDAA2Z;CAAC;8BAAl1tC,0CAA0C"}
1
+ {"version":3,"file":"api_builder.d.mts","sourceRoot":"","sources":["../../../../dist/lib/builders/api_builder.mjs"],"names":[],"mappings":"AAAoiD;IAAuC,gCAAqC;IAAsC,0CAA66C;IAAA,oDAAk07B;IAAA,6CAAqR;IAAA,uFAA0vB;IAAA,sDAA8sJ;IAAA,qDAAmkB;IAAA,kDAA2Z;CAAC;8BAA59uC,0CAA0C"}
@@ -1 +1 @@
1
- {"version":3,"file":"api-manager.d.mts","sourceRoot":"","sources":["../../../../dist/lib/handlers/api-manager.mjs"],"names":[],"mappings":"AAA6Z;IAAuC,gCAAqC;IAAsC;;;;MAAmF;IAAC;;;MAAwwD;IAAA;;;;OAAusB;IAAA,iDAAwmB;IAAA,wEAAiL;IAAA,2CAA6L;IAAA,2DAAqxB;IAAA,qEAA+6D;IAAA,oCAA0H;IAAA,wHAAsyI;IAAA,4FAA4vE;IAAA,kFAAivE;IAAA,oDAAsjE;IAAA,2DAA+zC;IAAgrB,kCAA85S;IAAA;;;;sBAAshB;IAAkb,wEAAu8Q;IAAA,+CAA2e;IAAA;;sBAAkwC;IAAA,4DAA0mD;IAAA,yCAAi3C;IAAA,gEAAynB;IAAA,6DAA6L;IAAA,wHAAquM;;CAAC;8BAA1kkD,0CAA0C"}
1
+ {"version":3,"file":"api-manager.d.mts","sourceRoot":"","sources":["../../../../dist/lib/handlers/api-manager.mjs"],"names":[],"mappings":"AAA2P;IAAuC,gCAAqC;IAAsC;;;;MAAmF;IAAC;;;MAAwwD;IAAA;;;;OAAwsB;IAAA,iDAAymB;IAAA,wEAAiL;IAAA,2CAA6L;IAAA,2DAAqxB;IAAA,qEAA+6D;IAAA,oCAA0H;IAAA,wHAAsyI;IAAA,4FAA4vE;IAAA,kFAAivE;IAAA,oDAAsjE;IAAA,2DAA+zC;IAAgrB,kCAA85S;IAAA;;;;sBAAshB;IAAkb,wEAAu8Q;IAAA,+CAA2e;IAAA;;sBAAkwC;IAAA,4DAA0mD;IAAA,yCAAi3C;IAAA,gEAAynB;IAAA,6DAA6L;IAAA,wHAAiuM;;CAAC;8BAAt6jD,0CAA0C"}
@@ -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,+GAAm3C;IAAA,kBAAuJ;IAAA,qBAA2C;IAAA,+BAAyS;IAAA;;;;;;;;;MAAmQ;CAAC;AAAA,sDAAkD"}
1
+ {"version":3,"file":"context-async.d.mts","sourceRoot":"","sources":["../../../../dist/lib/handlers/context-async.mjs"],"names":[],"mappings":"AAA+S;IAAwC,SAAqD;IAAC,yBAAsB;IAAC,2CAA2I;IAAA;;;;;;MAAqS;IAAA,+GAAm3C;IAAA,kBAAuJ;IAAA,qBAAsE;IAAA,+BAAyS;IAAA;;;;;;;;;MAAmQ;CAAC;AAAA,sDAAkD"}
@@ -1,8 +1,8 @@
1
1
  export class HookManager extends ComponentBase {
2
2
  static slothletProperty: string;
3
- enabled: any;
4
- defaultPattern: any;
5
- suppressErrors: any;
3
+ enabled: boolean;
4
+ defaultPattern: string;
5
+ suppressErrors: boolean;
6
6
  enabledPatterns: Set<any>;
7
7
  patternFilterActive: boolean;
8
8
  hooks: Map<any, any>;
@@ -12,6 +12,9 @@ export class HookManager extends ComponentBase {
12
12
  remove(filter?: {}): number;
13
13
  enable(filter?: {}): number;
14
14
  disable(filter?: {}): number;
15
+ enablePattern(pattern: any): number;
16
+ disablePattern(pattern: any): number;
17
+ resetPatternFilter(): void;
15
18
  list(filter?: {}): {
16
19
  registeredHooks: {
17
20
  id: any;
@@ -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,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"}
1
+ {"version":3,"file":"hook-manager.d.mts","sourceRoot":"","sources":["../../../../dist/lib/handlers/hook-manager.mjs"],"names":[],"mappings":"AAAsR;IAAwC,gCAAsC;IAA6Y,iBAA+B;IAAC,uBAA4C;IAAC,wBAAoD;IAAC,0BAA4B;IAAC,6BAA8B;IAA4G,qBAAkB;IAAC,0BAAwB;IAAC,gCAA+B;IAAmV,sDAAmsC;IAAub,4BAA2vB;IAAA,4BAAmI;IAAA,6BAAyK;IAAA,oCAAsJ;IAAA,qCAAuM;IAAA,2BAA6N;IAAA;;;;;;;;;;MAA46B;IAAA,gDAAotB;IAAA;;;;;;;;MAAswB;IAAA;;;;;;MAA2pB;IAAA,iJAAqb;IAAA,2FAA2Y;IAAwzB,yDAAyE;IAAyoD;;;;;;;;;;QAAsS;IAAA,sCAAyM;IAAA,0BAA8N;;CAAC;8BAAnrX,0CAA0C"}
@@ -1 +1 @@
1
- {"version":3,"file":"metadata.d.mts","sourceRoot":"","sources":["../../../../dist/lib/handlers/metadata.mjs"],"names":[],"mappings":"AAA2M;IAAqC,gCAAmC;IAAA,kBAAiB;IAAiqF,kEAA2zB;IAAA,oCAA4N;IAAA,8BAAgkC;IAAA,8CAAwI;IAAA,yDAAyiC;IAAA,gDAA0mD;IAAA,2DAA+e;IAAA,gDAAgG;IAAA,+DAA4kB;IAAA,mCAAyX;IAAA,iDAAijB;IAAA;;;MAA8P;IAAA,kCAA2jB;IAAA,6BAA8kB;IAAA,YAAkO;IAAA,cAAoJ;;CAAC;8BAAjmX,0CAA0C"}
1
+ {"version":3,"file":"metadata.d.mts","sourceRoot":"","sources":["../../../../dist/lib/handlers/metadata.mjs"],"names":[],"mappings":"AAA2M;IAAqC,gCAAmC;IAAA,kBAAiB;IAAiqF,kEAA2zB;IAAA,oCAA4N;IAAA,8BAA2iC;IAAA,8CAAwI;IAAA,yDAAyiC;IAAA,gDAA0mD;IAAA,2DAA+e;IAAA,gDAAgG;IAAA,+DAA4kB;IAAA,mCAAyX;IAAA,iDAAijB;IAAA;;;MAA8P;IAAA,kCAA2jB;IAAA,6BAA8kB;IAAA,YAAkO;IAAA,cAAoJ;;CAAC;8BAA5kX,0CAA0C"}
@@ -1 +1 @@
1
- {"version":3,"file":"unified-wrapper.d.mts","sourceRoot":"","sources":["../../../../dist/lib/handlers/unified-wrapper.mjs"],"names":[],"mappings":";;;;AAAk8E;IAAymH,mCAAsc;IAAA,2CAAy/B;IAAv5J;;;;;;;;;;OAAq4F;IAA59F,6CAAuF;IAAq4F,2EAAgiB;IAAA,kBAAmD;IAA+7C,gEAAqyB;IAAA,8EAAgsC;IAAA,4CAA4oC;IAAA,+BAAs4D;IAAA,6BAA4C;IAAA,sBAA8T;IAAA,yDAAq6P;IAAA,iDAAwuG;IAAA,8CAAira;IAAA,mBAAkhxB;IAA3oO,uBAAwB;;CAAonO;AAAwK,gDAA8N;8BAAv67D,0CAA0C"}
1
+ {"version":3,"file":"unified-wrapper.d.mts","sourceRoot":"","sources":["../../../../dist/lib/handlers/unified-wrapper.mjs"],"names":[],"mappings":";;;;AAA0+E;IAAymH,mCAAsc;IAAA,2CAAy/B;IAAv5J;;;;;;;;;;OAAq4F;IAA59F,6CAAuF;IAAq4F,2EAAgiB;IAAA,kBAAmD;IAA+7C,gEAAqyB;IAAA,8EAAgsC;IAAA,4CAA4oC;IAAA,+BAAs4D;IAAA,6BAA4C;IAAA,sBAA8T;IAAA,yDAAq6P;IAAA,iDAAghG;IAAA,8CAA+oa;IAAA,mBAAkhxB;IAA3oO,uBAAwB;;CAAonO;AAAwK,gDAA8N;8BAAvr7D,0CAA0C"}
@@ -1 +1 @@
1
- {"version":3,"file":"version-manager.d.mts","sourceRoot":"","sources":["../../../../dist/lib/handlers/version-manager.mjs"],"names":[],"mappings":"AAA2jB;IAA2C,gCAAyC;IAAoG,0GAAu4B;IAAA,8DAA8kB;IAAA,2CAA+E;IAAA,yCAAqE;IAAA,uCAAgF;IAAA,iEAAwO;IAAA,8EAA8d;IAAA;;;kBAA+N;IAAA,oDAA8Z;IAAA,yCAAihB;IAAA,qEAAyxB;IAAA,0CAA+gB;IAAA;;;;;;;;;;MAAurB;IAAsc,wCAA4+K;IAAA,yCAA8kB;IAAA,2CAAwU;IAAA,6CAA2Q;IAAA,iBAAmI;;CAAC;8BAA93a,0CAA0C"}
1
+ {"version":3,"file":"version-manager.d.mts","sourceRoot":"","sources":["../../../../dist/lib/handlers/version-manager.mjs"],"names":[],"mappings":"AAA0mB;IAA2C,gCAAyC;IAAoG,0GAAu4B;IAAA,8DAA8kB;IAAA,2CAA+E;IAAA,yCAAqE;IAAA,uCAAgF;IAAA,iEAAwO;IAAA,8EAA8d;IAAA;;;kBAA+N;IAAA,oDAA8Z;IAAA,yCAAihB;IAAA,qEAAyxB;IAAA,0CAA+gB;IAAA;;;;;;;;;;MAAurB;IAAsc,wCAA4+K;IAAA,yCAA8kB;IAAA,2CAAwU;IAAA,6CAA2Q;IAAA,iBAAmI;;CAAC;8BAAz5a,0CAA0C"}
@@ -1 +1 @@
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
+ {"version":3,"file":"class-instance-wrapper.d.mts","sourceRoot":"","sources":["../../../../dist/lib/helpers/class-instance-wrapper.mjs"],"names":[],"mappings":"AAA4iB,2DAAmT;AAAre,yEAAkL;AAAmT,wHAA2rC"}