@cldmv/slothlet 3.9.0 → 3.9.1

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 (38) hide show
  1. package/README.md +6 -7
  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/metadata.mjs +1 -1
  6. package/dist/lib/handlers/unified-wrapper.mjs +1 -1
  7. package/dist/lib/handlers/version-manager.mjs +1 -1
  8. package/dist/lib/helpers/class-instance-wrapper.mjs +1 -1
  9. package/dist/lib/helpers/config.mjs +1 -1
  10. package/dist/lib/helpers/eventemitter-context.mjs +1 -1
  11. package/dist/lib/helpers/module-discovery.mjs +1 -1
  12. package/dist/lib/helpers/module-manifest-validator.mjs +1 -1
  13. package/dist/lib/helpers/platform.mjs +17 -0
  14. package/dist/lib/helpers/resolve-from-caller.mjs +1 -1
  15. package/dist/lib/i18n/translations.mjs +1 -1
  16. package/dist/lib/processors/loader.mjs +1 -1
  17. package/dist/slothlet.mjs +1 -1
  18. package/index.mjs +17 -10
  19. package/package.json +8 -2
  20. package/types/dist/lib/builders/api_builder.d.mts.map +1 -1
  21. package/types/dist/lib/handlers/api-manager.d.mts.map +1 -1
  22. package/types/dist/lib/handlers/context-async.d.mts.map +1 -1
  23. package/types/dist/lib/handlers/metadata.d.mts.map +1 -1
  24. package/types/dist/lib/handlers/unified-wrapper.d.mts.map +1 -1
  25. package/types/dist/lib/handlers/version-manager.d.mts.map +1 -1
  26. package/types/dist/lib/helpers/class-instance-wrapper.d.mts.map +1 -1
  27. package/types/dist/lib/helpers/config.d.mts.map +1 -1
  28. package/types/dist/lib/helpers/eventemitter-context.d.mts.map +1 -1
  29. package/types/dist/lib/helpers/module-discovery.d.mts.map +1 -1
  30. package/types/dist/lib/helpers/module-manifest-validator.d.mts.map +1 -1
  31. package/types/dist/lib/helpers/platform.d.mts +12 -0
  32. package/types/dist/lib/helpers/platform.d.mts.map +1 -0
  33. package/types/dist/lib/helpers/resolve-from-caller.d.mts.map +1 -1
  34. package/types/dist/lib/i18n/translations.d.mts +1 -0
  35. package/types/dist/lib/i18n/translations.d.mts.map +1 -1
  36. package/types/dist/lib/processors/loader.d.mts.map +1 -1
  37. package/types/dist/slothlet.d.mts.map +1 -1
  38. package/types/index.d.mts.map +1 -1
@@ -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.1",
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,oDAAon6B;IAAA,6CAAqR;IAAA,uFAA0vB;IAAA,sDAA8sJ;IAAA,qDAAmkB;IAAA,kDAA2Z;CAAC;8BAA9wtC,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 +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":"AAAue,2DAAmT;AAAre,yEAAkL;AAAmT,wHAAwkC"}
@@ -1 +1 @@
1
- {"version":3,"file":"config.d.mts","sourceRoot":"","sources":["../../../../dist/lib/helpers/config.mjs"],"names":[],"mappings":"AAA2M;IAAmC,gCAAiC;IAAA;;;MAA2mB;IAAA,iDAA+U;IAAA,2CAA0S;IAAA;;;;;MAAqV;IAAA;;;;;;;;;;;;MAA46B;IAAA,6EAAwL;IAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;MAA+0J;IAAA,kEAA0gB;IAAA;;;;;;;;;;;;aAAyf;IAAA;;aAAiN;IAAA;;;;;;aAAymD;CAAC;8BAAhiV,0CAA0C"}
1
+ {"version":3,"file":"config.d.mts","sourceRoot":"","sources":["../../../../dist/lib/helpers/config.mjs"],"names":[],"mappings":"AAAsL;IAAmC,gCAAiC;IAAA;;;MAA2mB;IAAA,iDAA+U;IAAA,2CAA0S;IAAA;;;;;MAAqV;IAAA;;;;;;;;;;;;MAA46B;IAAA,6EAAwL;IAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;MAAq3J;IAAA,kEAA0gB;IAAA;;;;;;;;;;;;aAAyf;IAAA;;aAAiN;IAAA;;;;;;aAAymD;CAAC;8BAAjjV,0CAA0C"}
@@ -1 +1 @@
1
- {"version":3,"file":"eventemitter-context.d.mts","sourceRoot":"","sources":["../../../../dist/lib/helpers/eventemitter-context.mjs"],"names":[],"mappings":"AAA24P,qDAAmL;AAAtjB,oDAAmY;AAAroB,mDAAkQ;AAA95O,yDAA8D"}
1
+ {"version":3,"file":"eventemitter-context.d.mts","sourceRoot":"","sources":["../../../../dist/lib/helpers/eventemitter-context.mjs"],"names":[],"mappings":"AAAk7P,qDAA2M;AAAtmB,oDAA2Z;AAArrB,mDAA0R;AAAt7O,yDAA8D"}
@@ -1 +1 @@
1
- {"version":3,"file":"module-discovery.d.mts","sourceRoot":"","sources":["../../../../dist/lib/helpers/module-discovery.mjs"],"names":[],"mappings":"AAAqa;;;;;;MAA0nE"}
1
+ {"version":3,"file":"module-discovery.d.mts","sourceRoot":"","sources":["../../../../dist/lib/helpers/module-discovery.mjs"],"names":[],"mappings":"AAA2Q;;;;;;MAA2nE"}
@@ -1 +1 @@
1
- {"version":3,"file":"module-manifest-validator.d.mts","sourceRoot":"","sources":["../../../../dist/lib/helpers/module-manifest-validator.mjs"],"names":[],"mappings":"AAAkhB;;;;;;;;;;;;EAA0mJ"}
1
+ {"version":3,"file":"module-manifest-validator.d.mts","sourceRoot":"","sources":["../../../../dist/lib/helpers/module-manifest-validator.mjs"],"names":[],"mappings":"AAA6b;;;;;;;;;;;;EAA0mJ"}
@@ -0,0 +1,12 @@
1
+ export let AsyncLocalStorage: null;
2
+ export let AsyncResource: null;
3
+ export let EventEmitter: null;
4
+ export let createRequire: null;
5
+ export let fs: null;
6
+ export let fsp: null;
7
+ export const isNode: boolean;
8
+ export function loadJson(ref: any): any;
9
+ export let path: null;
10
+ export let url: null;
11
+ export let util: null;
12
+ //# sourceMappingURL=platform.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"platform.d.mts","sourceRoot":"","sources":["../../../../dist/lib/helpers/platform.mjs"],"names":[],"mappings":"AAAoK,mCAA2B;AAAA,+BAAuB;AAAxE,8BAAsB;AAAkD,+BAAuB;AAAjK,oBAAY;AAAA,qBAAa;AAArG,6BAA4E;AAA2tB,wCAA+L;AAAj4B,sBAAc;AAAA,qBAAa;AAAA,sBAAc"}
@@ -1 +1 @@
1
- {"version":3,"file":"resolve-from-caller.d.mts","sourceRoot":"","sources":["../../../../dist/lib/helpers/resolve-from-caller.mjs"],"names":[],"mappings":"AAA4rB;IAAqC,gCAAmC;IAAA,0CAA2N;IAA0L,sBAA0G;IAAs7B,qCAAkgB;;CAAC;8BAAnqF,0CAA0C"}
1
+ {"version":3,"file":"resolve-from-caller.d.mts","sourceRoot":"","sources":["../../../../dist/lib/helpers/resolve-from-caller.mjs"],"names":[],"mappings":"AAAmZ;IAAqC,gCAAmC;IAAA,0CAA2N;IAA0L,sBAA8G;IAAs7B,qCAAsgB;;CAAC;8BAAl4E,0CAA0C"}
@@ -1,6 +1,7 @@
1
1
  export function getLanguage(): string;
2
2
  export function initI18n(options?: {}): void;
3
3
  export function setLanguage(lang: any): void;
4
+ export function setLanguageAsync(lang: any): Promise<void>;
4
5
  export function t(errorCode: any, params?: {}): any;
5
6
  export function translate(errorCode: any, params?: {}): any;
6
7
  //# sourceMappingURL=translations.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"translations.d.mts","sourceRoot":"","sources":["../../../../dist/lib/i18n/translations.mjs"],"names":[],"mappings":"AAA2zD,sCAA8C;AAAmc,6CAAgU;AAA/rC,6CAA8Y;AAA8C,oDAAmc;AAAnc,4DAAmc"}
1
+ {"version":3,"file":"translations.d.mts","sourceRoot":"","sources":["../../../../dist/lib/i18n/translations.mjs"],"names":[],"mappings":"AAAgpF,sCAA8C;AAAmc,6CAAgX;AAA7tD,6CAA8b;AAAA,2DAA8b;AAA8C,oDAAmc;AAAnc,4DAAmc"}
@@ -1 +1 @@
1
- {"version":3,"file":"loader.d.mts","sourceRoot":"","sources":["../../../../dist/lib/processors/loader.mjs"],"names":[],"mappings":"AAAitB;IAAmC,gCAAiC;IAAsC,0FAA+nH;IAAozB;;;OAAshD;IAA6pF,gCAAipB;;CAAC;8BAA1hU,0CAA0C"}
1
+ {"version":3,"file":"loader.d.mts","sourceRoot":"","sources":["../../../../dist/lib/processors/loader.mjs"],"names":[],"mappings":"AAA6I;IAAmC,gCAAiC;IAAsC,0FAAooH;IAA0zB;;;OAAkjD;IAA6pF,gCAAipB;;CAAC;8BAA7/S,0CAA0C"}
@@ -1 +1 @@
1
- {"version":3,"file":"slothlet.d.mts","sourceRoot":"","sources":["../../dist/slothlet.mjs"],"names":[],"mappings":"AAAi9d,yDAA6G;AAA7G,mDAA6G"}
1
+ {"version":3,"file":"slothlet.d.mts","sourceRoot":"","sources":["../../dist/slothlet.mjs"],"names":[],"mappings":"AAA+2d,yDAA6G;AAA7G,mDAA6G"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","sourceRoot":"","sources":["../index.mjs"],"names":[],"mappings":";AA+FA;;;;;;;;;;;;;;GAcG;AACH,mCATW,OAAO,oBAAoB,EAAE,eAAe,GAC1C,OAAO,CAAC,OAAO,oBAAoB,EAAE,WAAW,CAAC,CAkB7D"}
1
+ {"version":3,"file":"index.d.mts","sourceRoot":"","sources":["../index.mjs"],"names":[],"mappings":";AAsGA;;;;;;;;;;;;;;GAcG;AACH,mCATW,OAAO,oBAAoB,EAAE,eAAe,GAC1C,OAAO,CAAC,OAAO,oBAAoB,EAAE,WAAW,CAAC,CAkB7D"}