@cldmv/slothlet 3.4.0 → 3.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +13 -9
- package/bin/slothlet.mjs +218 -0
- package/dist/lib/builders/api_builder.mjs +1 -1
- package/dist/lib/handlers/api-manager.mjs +1 -1
- package/dist/lib/handlers/metadata.mjs +1 -1
- package/dist/lib/handlers/ownership.mjs +1 -1
- package/dist/lib/handlers/permission-manager.mjs +1 -1
- package/dist/lib/handlers/unified-wrapper.mjs +1 -1
- package/dist/lib/i18n/languages/de-de.json +4 -1
- package/dist/lib/i18n/languages/en-gb.json +4 -1
- package/dist/lib/i18n/languages/en-us.json +4 -1
- package/dist/lib/i18n/languages/es-es.json +4 -1
- package/dist/lib/i18n/languages/es-mx.json +4 -1
- package/dist/lib/i18n/languages/fr-fr.json +4 -1
- package/dist/lib/i18n/languages/hi-in.json +4 -1
- package/dist/lib/i18n/languages/ja-jp.json +4 -1
- package/dist/lib/i18n/languages/ko-kr.json +4 -1
- package/dist/lib/i18n/languages/pt-br.json +4 -1
- package/dist/lib/i18n/languages/ru-ru.json +4 -1
- package/dist/lib/i18n/languages/zh-cn.json +4 -1
- package/dist/lib/processors/loader.mjs +1 -1
- package/dist/lib/processors/typescript.mjs +1 -1
- package/dist/lib/runtime/runtime-asynclocalstorage.mjs +1 -1
- package/dist/lib/runtime/runtime-livebindings.mjs +1 -1
- package/dist/lib/runtime/runtime.mjs +1 -1
- package/dist/lib/typegen/typegen.mjs +17 -0
- package/dist/slothlet.mjs +1 -1
- package/package.json +14 -2
- package/types/dist/lib/builders/api_builder.d.mts +1 -96
- package/types/dist/lib/builders/api_builder.d.mts.map +1 -1
- package/types/dist/lib/handlers/api-manager.d.mts +1 -0
- package/types/dist/lib/handlers/api-manager.d.mts.map +1 -1
- package/types/dist/lib/handlers/metadata.d.mts +2 -2
- package/types/dist/lib/handlers/metadata.d.mts.map +1 -1
- package/types/dist/lib/handlers/ownership.d.mts +3 -0
- package/types/dist/lib/handlers/ownership.d.mts.map +1 -1
- package/types/dist/lib/handlers/permission-manager.d.mts +3 -1
- package/types/dist/lib/handlers/permission-manager.d.mts.map +1 -1
- package/types/dist/lib/handlers/unified-wrapper.d.mts.map +1 -1
- package/types/dist/lib/processors/loader.d.mts.map +1 -1
- package/types/dist/lib/processors/typescript.d.mts +4 -0
- package/types/dist/lib/processors/typescript.d.mts.map +1 -1
- package/types/dist/lib/runtime/runtime-asynclocalstorage.d.mts.map +1 -1
- package/types/dist/lib/runtime/runtime-livebindings.d.mts.map +1 -1
- package/types/dist/lib/runtime/runtime.d.mts.map +1 -1
- package/types/dist/lib/typegen/typegen.d.mts +5 -0
- package/types/dist/lib/typegen/typegen.d.mts.map +1 -0
- package/types/dist/slothlet.d.mts.map +1 -1
|
@@ -35,6 +35,8 @@
|
|
|
35
35
|
"OWNERSHIP_INVALID_MODULE_ID": "유효하지 않은 소유권 등록: moduleID '{moduleID}'이(가) 유효하지 않습니다.",
|
|
36
36
|
"OWNERSHIP_INVALID_API_PATH": "유효하지 않은 소유권 등록: apiPath '{apiPath}'이(가) 유효하지 않습니다.",
|
|
37
37
|
"OWNERSHIP_CONFLICT": "소유권 충돌: 경로 '{apiPath}'은(는) 이미 모듈 '{existingModuleId}'이(가) 소유하고 있습니다. '{newModuleId}'에 할당할 수 없습니다. forceOverwrite: true를 사용하거나 먼저 removeApi를 호출하십시오.",
|
|
38
|
+
"LOOSE_SET_NOT_OWNED": "모듈 {callerApiPath}은(는) {apiPath}에 쓸 수 없습니다. 모듈은 자신의 apiPath 아래에서만 쓸 수 있습니다. 다른 경로에 등록하려면 api.slothlet.api.add()를 사용하세요.",
|
|
39
|
+
"LOOSE_SET_RESERVED_KEY": "apiPath '{apiPath}'의 예약된 키 세그먼트 '{segment}'에 할당할 수 없습니다. __proto__, prototype, constructor와 같은 이름은 API 트리의 프로토타입 오염을 방지하기 위해 차단됩니다.",
|
|
38
40
|
"INVALID_DIRECTORY": "유효하지 않은 디렉토리 '{dir}': {error}. 디렉토리가 존재하고 액세스 가능한지 확인하십시오.",
|
|
39
41
|
"WARN_DIRECTORY_EMPTY": "디렉토리 '{dir}'(확인된 경로: '{resolvedPath}')이(가) 비어 있거나 로드 가능한 모듈(.mjs, .cjs, .js 파일)이 없습니다. 이는 add-api 워크플로에서는 유효하지만 잘못 설정된 경로일 수 있습니다.",
|
|
40
42
|
"INTERNAL_HOOK_STATE_CORRUPT": "[내부 오류] HookManager 상태가 손상됨: 후크 \"{hookId}\" ({type}/{subset}/{pattern}) — {detail}. 이는 Slothlet의 버그입니다. 보고해 주십시오.",
|
|
@@ -270,6 +272,8 @@
|
|
|
270
272
|
"HINT_INVALID_CONFIG_LAZY_ASYNC_REQUIRED": "지연 모드에는 비동기 작업이 필요합니다. 즉시 모드를 사용하거나 적절한 비동기 패턴을 구현하십시오.",
|
|
271
273
|
"HINT_RUNTIME_NO_ACTIVE_CONTEXT_SELF": "Slothlet API 함수 컨텍스트 밖에서는 'self'에 액세스할 수 없습니다.",
|
|
272
274
|
"HINT_RUNTIME_NO_ACTIVE_CONTEXT_CONTEXT": "Slothlet API 함수 밖에서는 'context'에 액세스할 수 없습니다. 컨텍스트는 Slothlet API 호출 내에서만 수정할 수 있습니다.",
|
|
275
|
+
"HINT_LOOSE_SET_NOT_OWNED": "apiPath가 \"P\"인 모듈은 \"P.*\" 아래에만 쓸 수 있습니다. 다른 네임스페이스에 코드를 등록하려면 api.slothlet.api.add()를 호출하세요.",
|
|
276
|
+
"HINT_LOOSE_SET_RESERVED_KEY": "__proto__, prototype, constructor 세그먼트는 이들에 쓰면 JavaScript 프로토타입 체인이 변경되므로 apiPath 이름으로 사용할 수 없습니다. 다른 이름을 선택하세요.",
|
|
273
277
|
"HINT_INVALID_CONFIG_NOT_LOADED": "이 작업을 수행하기 전에 인스턴스를 로드해야 합니다. 먼저 load()를 호출하십시오.",
|
|
274
278
|
"HINT_INVALID_CONFIG_RELOAD_NOT_IMPL": "힌트: 재로드 기능은 아직 구현되지 않았습니다. 향후 버전에서 추가될 예정입니다.",
|
|
275
279
|
"HINT_WARNING_RESERVED_PROPERTY_CONFLICT": "'slothlet' 속성 이름은 내장 API 메서드를 위해 예약되어 있습니다. slothlet.shutdown(), slothlet.api.* 등과의 충돌을 피하기 위해 API 모듈이나 속성 이름을 바꾸십시오.",
|
|
@@ -382,7 +386,6 @@
|
|
|
382
386
|
"DEBUG_VERSION_DEFAULT_USED": "경로 {apiPath}에 대한 Discriminator 일치 없음; 기본 버전 {version}을(를) 사용합니다.",
|
|
383
387
|
"DEBUG_VERSION_REGISTERED": "버전 {version}이(가) {logicalPath}에 등록됨 (moduleID: {moduleID})",
|
|
384
388
|
"DEBUG_VERSION_UNREGISTERED": "버전 {version}이(가) {logicalPath}에서 등록 취소됨",
|
|
385
|
-
|
|
386
389
|
"PERMISSION_DENIED": "접근 거부: 호출자 '{caller}'은(는) '{target}'에 접근할 권한이 없습니다",
|
|
387
390
|
"HINT_PERMISSION_DENIED": "이 호출자/대상 쌍의 권한 규칙을 확인하세요. api.slothlet.permissions.global.rulesForPath('{target}')를 사용하여 활성 규칙을 검사할 수 있습니다.",
|
|
388
391
|
"PERMISSION_SELF_MODIFY": "모듈 '{moduleID}'은(는) 자신의 권한 규칙 '{ruleId}'을(를) 제거할 수 없습니다",
|
|
@@ -35,6 +35,8 @@
|
|
|
35
35
|
"OWNERSHIP_INVALID_MODULE_ID": "Registro de propriedade inválido: moduleID '{moduleID}' é inválido.",
|
|
36
36
|
"OWNERSHIP_INVALID_API_PATH": "Registro de propriedade inválido: apiPath '{apiPath}' é inválido.",
|
|
37
37
|
"OWNERSHIP_CONFLICT": "Conflito de propriedade: O caminho '{apiPath}' já pertence ao módulo '{existingModuleId}', não é possível atribuir a '{newModuleId}'. Use forceOverwrite: true ou removeApi primeiro.",
|
|
38
|
+
"LOOSE_SET_NOT_OWNED": "O módulo {callerApiPath} não pode escrever em {apiPath}. Um módulo só pode escrever sob seu próprio apiPath; use api.slothlet.api.add() para registrar em outro caminho.",
|
|
39
|
+
"LOOSE_SET_RESERVED_KEY": "Não é possível atribuir ao segmento de chave reservado '{segment}' no apiPath '{apiPath}'. Nomes como __proto__, prototype e constructor estão bloqueados para evitar a poluição do prototype da árvore da API.",
|
|
38
40
|
"INVALID_DIRECTORY": "Diretório inválido '{dir}': {error}. Certifique-se de que o diretório existe e está acessível.",
|
|
39
41
|
"WARN_DIRECTORY_EMPTY": "O diretório '{dir}' (resolvido: '{resolvedPath}') está vazio ou não contém módulos carregáveis (arquivos .mjs, .cjs, .js). Isso é válido para fluxos de trabalho add-api, mas pode indicar um caminho mal configurado.",
|
|
40
42
|
"INTERNAL_HOOK_STATE_CORRUPT": "[ERRO INTERNO] O estado do HookManager está corrompido: hook \"{hookId}\" ({type}/{subset}/{pattern}) — {detail}. Isso é um erro no Slothlet — por favor reporte-o.",
|
|
@@ -270,6 +272,8 @@
|
|
|
270
272
|
"HINT_INVALID_CONFIG_LAZY_ASYNC_REQUIRED": "O modo lazy requer operações assíncronas. Use o modo eager ou implemente padrões assíncronos adequados.",
|
|
271
273
|
"HINT_RUNTIME_NO_ACTIVE_CONTEXT_SELF": "Não é possível acessar 'self' fora do contexto de uma função da API slothlet.",
|
|
272
274
|
"HINT_RUNTIME_NO_ACTIVE_CONTEXT_CONTEXT": "Não é possível acessar 'context' fora de uma função da API slothlet. O contexto só pode ser modificado dentro de chamadas da API slothlet.",
|
|
275
|
+
"HINT_LOOSE_SET_NOT_OWNED": "Um módulo cujo apiPath é \"P\" só pode escrever sob \"P.*\". Para registrar código em outro namespace, chame api.slothlet.api.add().",
|
|
276
|
+
"HINT_LOOSE_SET_RESERVED_KEY": "Os segmentos __proto__, prototype e constructor não podem ser usados como nomes de apiPath porque escrever neles modificaria a cadeia de protótipos do JavaScript. Escolha outro nome.",
|
|
273
277
|
"HINT_INVALID_CONFIG_NOT_LOADED": "A instância deve ser carregada antes de realizar esta operação. Chame load() primeiro.",
|
|
274
278
|
"HINT_INVALID_CONFIG_RELOAD_NOT_IMPL": "A funcionalidade de recarregamento ainda não foi implementada. Isso será adicionado em uma iteração futura.",
|
|
275
279
|
"HINT_WARNING_RESERVED_PROPERTY_CONFLICT": "O nome de propriedade 'slothlet' é reservado para métodos integrados da API. Renomeie seu módulo ou propriedade da API para evitar conflitos com slothlet.shutdown(), slothlet.api.*, etc.",
|
|
@@ -382,7 +386,6 @@
|
|
|
382
386
|
"DEBUG_VERSION_DEFAULT_USED": "Nenhuma correspondência de discriminador para o caminho {apiPath}; usando versão padrão {version}.",
|
|
383
387
|
"DEBUG_VERSION_REGISTERED": "Versão {version} registrada em {logicalPath} (moduleID: {moduleID})",
|
|
384
388
|
"DEBUG_VERSION_UNREGISTERED": "Versão {version} removida de {logicalPath}",
|
|
385
|
-
|
|
386
389
|
"PERMISSION_DENIED": "Acesso negado: o chamador '{caller}' não tem permissão para acessar '{target}'",
|
|
387
390
|
"HINT_PERMISSION_DENIED": "Verifique as regras de permissão para este par chamador/alvo. Use api.slothlet.permissions.global.rulesForPath('{target}') para inspecionar as regras ativas.",
|
|
388
391
|
"PERMISSION_SELF_MODIFY": "O módulo '{moduleID}' não pode remover sua própria regra de permissão '{ruleId}'",
|
|
@@ -35,6 +35,8 @@
|
|
|
35
35
|
"OWNERSHIP_INVALID_MODULE_ID": "Недействительная регистрация владения: moduleID '{moduleID}' недействителен.",
|
|
36
36
|
"OWNERSHIP_INVALID_API_PATH": "Недействительная регистрация владения: apiPath '{apiPath}' недействителен.",
|
|
37
37
|
"OWNERSHIP_CONFLICT": "Конфликт владения: путь '{apiPath}' уже принадлежит модулю '{existingModuleId}', нельзя назначить '{newModuleId}'. Используйте forceOverwrite: true или предварительно вызовите removeApi.",
|
|
38
|
+
"LOOSE_SET_NOT_OWNED": "Модуль {callerApiPath} не может писать в {apiPath}. Модуль может писать только в пределах своего apiPath; используйте api.slothlet.api.add() для регистрации в другом пути.",
|
|
39
|
+
"LOOSE_SET_RESERVED_KEY": "Невозможно присвоить значение зарезервированному сегменту ключа '{segment}' в apiPath '{apiPath}'. Имена вроде __proto__, prototype и constructor заблокированы, чтобы предотвратить загрязнение прототипа дерева API.",
|
|
38
40
|
"INVALID_DIRECTORY": "Неверная директория '{dir}': {error}. Убедитесь, что директория существует и доступна.",
|
|
39
41
|
"WARN_DIRECTORY_EMPTY": "Директория '{dir}' (разрешено: '{resolvedPath}') пуста или не содержит загружаемых модулей (.mjs, .cjs, .js). Это допустимо для add-api, но может указывать на неверный путь.",
|
|
40
42
|
"INTERNAL_HOOK_STATE_CORRUPT": "[ВНУТРИ] Состояние HookManager повреждено: hook \"{hookId}\" ({type}/{subset}/{pattern}) — {detail}. Пожалуйста, сообщите.",
|
|
@@ -270,6 +272,8 @@
|
|
|
270
272
|
"HINT_INVALID_CONFIG_LAZY_ASYNC_REQUIRED": "Lazy-режим требует асинхронности — используйте eager или асинхронный паттерн.",
|
|
271
273
|
"HINT_RUNTIME_NO_ACTIVE_CONTEXT_SELF": "Нельзя использовать 'self' вне Slothlet API-функции.",
|
|
272
274
|
"HINT_RUNTIME_NO_ACTIVE_CONTEXT_CONTEXT": "Нельзя менять 'context' вне Slothlet API-вызовов.",
|
|
275
|
+
"HINT_LOOSE_SET_NOT_OWNED": "Модуль с apiPath \"P\" может писать только в \"P.*\". Чтобы зарегистрировать код в другом пространстве имён, вызовите api.slothlet.api.add().",
|
|
276
|
+
"HINT_LOOSE_SET_RESERVED_KEY": "Сегменты __proto__, prototype и constructor нельзя использовать как имена apiPath, поскольку запись в них изменит цепочку прототипов JavaScript. Выберите другое имя.",
|
|
273
277
|
"HINT_INVALID_CONFIG_NOT_LOADED": "Экземпляр должен быть загружен перед выполнением операции — вызовите load().",
|
|
274
278
|
"HINT_INVALID_CONFIG_RELOAD_NOT_IMPL": "Функция перезагрузки ещё не реализована.",
|
|
275
279
|
"HINT_WARNING_RESERVED_PROPERTY_CONFLICT": "Имя 'slothlet' зарезервировано — переименуйте модуль/свойство.",
|
|
@@ -382,7 +386,6 @@
|
|
|
382
386
|
"DEBUG_VERSION_DEFAULT_USED": "Нет совпадения дискриминатора для пути {apiPath}; используется версия по умолчанию {version}.",
|
|
383
387
|
"DEBUG_VERSION_REGISTERED": "Версия {version} зарегистрирована в {logicalPath} (moduleID: {moduleID})",
|
|
384
388
|
"DEBUG_VERSION_UNREGISTERED": "Версия {version} удалена из {logicalPath}",
|
|
385
|
-
|
|
386
389
|
"PERMISSION_DENIED": "Доступ запрещён: вызывающий '{caller}' не имеет права доступа к '{target}'",
|
|
387
390
|
"HINT_PERMISSION_DENIED": "Проверьте правила разрешений для этой пары вызывающий/цель. Используйте api.slothlet.permissions.global.rulesForPath('{target}') для просмотра активных правил.",
|
|
388
391
|
"PERMISSION_SELF_MODIFY": "Модуль '{moduleID}' не может удалить собственное правило разрешений '{ruleId}'",
|
|
@@ -35,6 +35,8 @@
|
|
|
35
35
|
"OWNERSHIP_INVALID_MODULE_ID": "无效的所有权注册:moduleID '{moduleID}' 无效。",
|
|
36
36
|
"OWNERSHIP_INVALID_API_PATH": "无效的所有权注册:apiPath '{apiPath}' 无效。",
|
|
37
37
|
"OWNERSHIP_CONFLICT": "所有权冲突:路径 '{apiPath}' 已被模块 '{existingModuleId}' 拥有,无法分配给 '{newModuleId}'。请使用 forceOverwrite: true 或先调用 removeApi。",
|
|
38
|
+
"LOOSE_SET_NOT_OWNED": "模块 {callerApiPath} 无法写入 {apiPath}。模块只能在自己的 apiPath 下写入;要在其他路径注册,请使用 api.slothlet.api.add()。",
|
|
39
|
+
"LOOSE_SET_RESERVED_KEY": "无法在 apiPath '{apiPath}' 中分配给保留键段 '{segment}'。__proto__、prototype 和 constructor 等名称已被阻止,以防止 API 树受到原型污染。",
|
|
38
40
|
"INVALID_DIRECTORY": "无效目录 '{dir}':{error}。请确保目录存在且可访问。",
|
|
39
41
|
"WARN_DIRECTORY_EMPTY": "目录 '{dir}'(解析路径:'{resolvedPath}')为空或不包含可加载模块(.mjs, .cjs, .js 文件)。这在 add-api 工作流程中是有效的,但可能表明路径配置有误。",
|
|
40
42
|
"INTERNAL_HOOK_STATE_CORRUPT": "[内部错误] HookManager 状态损坏:钩子 \"{hookId}\" ({type}/{subset}/{pattern}) — {detail}。这是一个 Slothlet 的 bug — 请报告它。",
|
|
@@ -270,6 +272,8 @@
|
|
|
270
272
|
"HINT_INVALID_CONFIG_LAZY_ASYNC_REQUIRED": "延迟模式需要异步操作。请使用立即(eager)模式或实现适当的异步模式。",
|
|
271
273
|
"HINT_RUNTIME_NO_ACTIVE_CONTEXT_SELF": "无法在 slothlet API 函数上下文之外访问 'self'。",
|
|
272
274
|
"HINT_RUNTIME_NO_ACTIVE_CONTEXT_CONTEXT": "无法在 slothlet API 函数外部访问 'context'。上下文只能在 slothlet API 调用内部修改。",
|
|
275
|
+
"HINT_LOOSE_SET_NOT_OWNED": "apiPath 为 \"P\" 的模块只能在 \"P.*\" 下写入。要在其他命名空间注册代码,请调用 api.slothlet.api.add()。",
|
|
276
|
+
"HINT_LOOSE_SET_RESERVED_KEY": "段 __proto__、prototype 和 constructor 不能用作 apiPath 名称,因为写入它们将更改 JavaScript 原型链。请选择其他名称。",
|
|
273
277
|
"HINT_INVALID_CONFIG_NOT_LOADED": "在执行此操作前必须加载实例。请先调用 load()。",
|
|
274
278
|
"HINT_INVALID_CONFIG_RELOAD_NOT_IMPL": "提示:重载功能尚未实现,计划在未来的版本中添加。",
|
|
275
279
|
"HINT_WARNING_RESERVED_PROPERTY_CONFLICT": "'slothlet' 属性名称已保留供内建 API 方法使用。请重命名您的 API 模块或属性,以避免与 slothlet.shutdown()、slothlet.api.* 等发生冲突。",
|
|
@@ -382,7 +386,6 @@
|
|
|
382
386
|
"DEBUG_VERSION_DEFAULT_USED": "路径 {apiPath} 无匹配判别器;使用默认版本 {version}。",
|
|
383
387
|
"DEBUG_VERSION_REGISTERED": "版本 {version} 已在 {logicalPath} 注册(moduleID:{moduleID})",
|
|
384
388
|
"DEBUG_VERSION_UNREGISTERED": "版本 {version} 已从 {logicalPath} 注销",
|
|
385
|
-
|
|
386
389
|
"PERMISSION_DENIED": "访问被拒绝:调用方 '{caller}' 无权访问 '{target}'",
|
|
387
390
|
"HINT_PERMISSION_DENIED": "请检查此调用方/目标对的权限规则。使用 api.slothlet.permissions.global.rulesForPath('{target}') 检查活动规则。",
|
|
388
391
|
"PERMISSION_SELF_MODIFY": "模块 '{moduleID}' 无法移除自身的权限规则 '{ruleId}'",
|
|
@@ -14,4 +14,4 @@
|
|
|
14
14
|
limitations under the License.
|
|
15
15
|
*/
|
|
16
16
|
|
|
17
|
-
import{readdir,stat}from"node:fs/promises";import{join,extname,basename,resolve}from"node:path";import{pathToFileURL}from"node:url";import{createRequire}from"node:module";import{ComponentBase}from"@cldmv/slothlet/factories/component-base";class Loader extends ComponentBase{static slothletProperty="loader";constructor(slothlet){super(slothlet)}async loadModule(filePath,instanceID,moduleID,cacheBust=null){try{if(filePath.endsWith(".cjs")){return this.#loadCJSIsolated(filePath)}const isTypeScript=filePath.endsWith(".ts")||filePath.endsWith(".mts");const typescriptConfig=this.slothlet.config?.typescript;let moduleUrl;if(isTypeScript&&typescriptConfig?.enabled){const mode=typescriptConfig.mode;if(mode==="strict"){if(!typescriptConfig.types?.output){throw new this.SlothletError("TS_STRICT_REQUIRES_OUTPUT",{},null,{validationError:true})}if(!typescriptConfig.types?.interfaceName){throw new this.SlothletError("TS_STRICT_REQUIRES_INTERFACE_NAME",{},null,{validationError:true})}if(!this.slothlet._typesGenerated){const{fork}=await import("child_process");const path=await import("path");const{fileURLToPath}=await import("url");const __dirname=path.dirname(fileURLToPath(import.meta.url));const scriptPath=path.resolve(__dirname,"../../../tools/build/generate-types-worker.mjs");const childConfig=JSON.stringify({dir:this.slothlet.config.root||this.slothlet.config.dir,mode:"eager",typescript:{enabled:true,mode:"fast"},types:typescriptConfig.types});await new Promise((resolve2,reject)=>{const child=fork(scriptPath,[],{stdio:["pipe","pipe","pipe","ipc"],env:{...process.env,SLOTHLET_CONFIG:childConfig}});let errorOutput="";child.stderr?.on("data",data=>{errorOutput+=data.toString()});child.on("message",msg=>{if(msg.type==="success"){this.slothlet._typesGenerated=true;resolve2()}else if(msg.type==="error"){reject(new this.SlothletError("TS_TYPE_GENERATION_FAILED",{},{message:msg.error}))}});child.on("error",error=>{reject(new this.SlothletError("TS_TYPE_GENERATION_FORK_FAILED",{},error))});child.on("exit",code=>{if(code!==0&&!this.slothlet._typesGenerated){reject(new this.SlothletError("TS_TYPE_GENERATION_PROCESS_EXITED",{code,output:errorOutput},null,{validationError:true}))}})})}const{transformTypeScriptStrict,
|
|
17
|
+
import{readdir,stat}from"node:fs/promises";import{join,extname,basename,resolve}from"node:path";import{pathToFileURL}from"node:url";import{createRequire}from"node:module";import{ComponentBase}from"@cldmv/slothlet/factories/component-base";class Loader extends ComponentBase{static slothletProperty="loader";constructor(slothlet){super(slothlet)}async loadModule(filePath,instanceID,moduleID,cacheBust=null){try{if(filePath.endsWith(".cjs")){return this.#loadCJSIsolated(filePath)}const isTypeScript=filePath.endsWith(".ts")||filePath.endsWith(".mts");const typescriptConfig=this.slothlet.config?.typescript;let moduleUrl;if(isTypeScript&&typescriptConfig?.enabled){const mode=typescriptConfig.mode;if(mode==="strict"){if(!typescriptConfig.types?.output){throw new this.SlothletError("TS_STRICT_REQUIRES_OUTPUT",{},null,{validationError:true})}if(!typescriptConfig.types?.interfaceName){throw new this.SlothletError("TS_STRICT_REQUIRES_INTERFACE_NAME",{},null,{validationError:true})}if(!this.slothlet._typesGenerated){const{fork}=await import("child_process");const path=await import("path");const{fileURLToPath}=await import("url");const __dirname=path.dirname(fileURLToPath(import.meta.url));const scriptPath=path.resolve(__dirname,"../../../tools/build/generate-types-worker.mjs");const childConfig=JSON.stringify({dir:this.slothlet.config.root||this.slothlet.config.dir,mode:"eager",typescript:{enabled:true,mode:"fast"},types:typescriptConfig.types});await new Promise((resolve2,reject)=>{const child=fork(scriptPath,[],{stdio:["pipe","pipe","pipe","ipc"],env:{...process.env,SLOTHLET_CONFIG:childConfig}});let errorOutput="";child.stderr?.on("data",data=>{errorOutput+=data.toString()});child.on("message",msg=>{if(msg.type==="success"){this.slothlet._typesGenerated=true;resolve2()}else if(msg.type==="error"){reject(new this.SlothletError("TS_TYPE_GENERATION_FAILED",{},{message:msg.error}))}});child.on("error",error=>{reject(new this.SlothletError("TS_TYPE_GENERATION_FORK_FAILED",{},error))});child.on("exit",code=>{if(code!==0&&!this.slothlet._typesGenerated){reject(new this.SlothletError("TS_TYPE_GENERATION_PROCESS_EXITED",{code,output:errorOutput},null,{validationError:true}))}})})}const{transformTypeScriptStrict,writeTransformedToCache,formatDiagnostics}=await import("@cldmv/slothlet/processors/typescript");const result=await transformTypeScriptStrict(filePath,{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,errors:errors.join("\n")},null,{validationError:true});error.diagnostics=result.diagnostics;throw error}moduleUrl=await this.#buildTypescriptModuleUrl(writeTransformedToCache,filePath,result.code,instanceID,moduleID,cacheBust)}else{const{transformTypeScript,writeTransformedToCache}=await import("@cldmv/slothlet/processors/typescript");const transformedCode=await transformTypeScript(filePath,{target:typescriptConfig.target,sourcemap:typescriptConfig.sourcemap});moduleUrl=await this.#buildTypescriptModuleUrl(writeTransformedToCache,filePath,transformedCode,instanceID,moduleID,cacheBust)}}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){const{url,cacheDir}=await writeTransformedToCache(filePath,code,instanceID);(this.slothlet._typescriptCacheDirs??=new Set).add(cacheDir);let moduleUrl=`${url}?slothlet_instance=${instanceID}`;if(moduleID){moduleUrl+=`&module=${moduleID}`}if(cacheBust){moduleUrl+=`&_reload=${cacheBust}`}return moduleUrl}async scanDirectory(dir,options={}){const typescriptConfig=this.slothlet.config?.typescript;const defaultExtensions=[".mjs",".cjs",".js"];const typescriptExtensions=typescriptConfig?.enabled?[".ts",".mts"]:[];const allExtensions=[...defaultExtensions,...typescriptExtensions];const{recursive=true,extensions=allExtensions,isRootScan=true,currentDepth=0,maxDepth=Infinity,fileFilter=null}=options;try{await stat(dir)}catch(error){throw new this.SlothletError("INVALID_DIRECTORY",{dir},error)}const structure={files:[],directories:[]};const entries=await readdir(dir,{withFileTypes:true});for(const entry of entries){const fullPath=join(dir,entry.name);if(entry.isDirectory()){if(fileFilter){continue}if(recursive&¤tDepth<maxDepth){const subStructure=await this.scanDirectory(fullPath,{...options,isRootScan:false,currentDepth:currentDepth+1});structure.directories.push({path:fullPath,name:entry.name,children:subStructure})}}else if(entry.isFile()){const ext=extname(entry.name);if(extensions.includes(ext)){if(entry.name.startsWith("__")){continue}if(fileFilter&&!fileFilter(entry.name)){continue}const nameWithoutExt=basename(entry.name,ext);structure.files.push({path:fullPath,name:nameWithoutExt,fullName:entry.name,moduleID:this.slothlet.helpers.sanitize.getModuleId(fullPath,dir)})}}}if(isRootScan&&structure.files.length===0&&structure.directories.length===0){new this.SlothletWarning("WARN_DIRECTORY_EMPTY",{dir,resolvedPath:resolve(dir)})}return structure}extractExports(module){const exports={};if(module.default!==void 0){exports.default=module.default}for(const key of Object.keys(module)){if(key!=="default"&&key!=="module.exports"&&typeof key==="string"){exports[key]=module[key]}}if(exports.default&&typeof exports.default==="object"&&exports.default!==null&&"default"in exports.default){const rootNamedKeys=Object.keys(exports).filter(k=>k!=="default"&&k!=="module.exports");const defaultKeys=Object.keys(exports.default).filter(k=>k!=="default");const isCJSPattern=rootNamedKeys.every(k=>k in exports.default);if(isCJSPattern&&defaultKeys.length>0){exports.default=exports.default.default}}return exports}}export{Loader};
|
|
@@ -14,4 +14,4 @@
|
|
|
14
14
|
limitations under the License.
|
|
15
15
|
*/
|
|
16
16
|
|
|
17
|
-
import fs from"fs";import path from"path";import{SlothletError}from"@cldmv/slothlet/errors";let esbuildInstance=null;let typescriptInstance=null;async function getEsbuild(){if(!esbuildInstance){try{esbuildInstance=await import("esbuild")}catch(error){throw new SlothletError("TYPESCRIPT_ESBUILD_NOT_INSTALLED",{mode:"fast"},error)}}return esbuildInstance}async function getTypeScript(){if(!typescriptInstance){try{typescriptInstance=await import("typescript")}catch(error){throw new SlothletError("TYPESCRIPT_TSC_NOT_INSTALLED",{mode:"strict"},error)}}return typescriptInstance}async function transformTypeScript(filePath,options={}){const esbuild=await getEsbuild();const code=fs.readFileSync(filePath,"utf8");const result=await esbuild.transform(code,{loader:"ts",format:options.format||"esm",target:options.target||"es2020",sourcemap:options.sourcemap||false,...options});return result.code}function createDataUrl(code){const encoded=encodeURIComponent(code);const timestamp=Date.now();return`data:text/javascript;charset=utf-8,${encoded}#t=${timestamp}`}async function transformTypeScriptStrict(filePath,options={}){const ts=await getTypeScript();const code=fs.readFileSync(filePath,"utf8");const targetMap={es3:ts.ScriptTarget.ES3,es5:ts.ScriptTarget.ES5,es6:ts.ScriptTarget.ES2015,es2015:ts.ScriptTarget.ES2015,es2016:ts.ScriptTarget.ES2016,es2017:ts.ScriptTarget.ES2017,es2018:ts.ScriptTarget.ES2018,es2019:ts.ScriptTarget.ES2019,es2020:ts.ScriptTarget.ES2020,es2021:ts.ScriptTarget.ES2021,es2022:ts.ScriptTarget.ES2022,esnext:ts.ScriptTarget.ESNext,latest:ts.ScriptTarget.Latest};const moduleMap={none:ts.ModuleKind.None,commonjs:ts.ModuleKind.CommonJS,amd:ts.ModuleKind.AMD,system:ts.ModuleKind.System,umd:ts.ModuleKind.UMD,es6:ts.ModuleKind.ES2015,es2015:ts.ModuleKind.ES2015,es2020:ts.ModuleKind.ES2020,es2022:ts.ModuleKind.ES2022,esnext:ts.ModuleKind.ESNext,node16:ts.ModuleKind.Node16,nodenext:ts.ModuleKind.NodeNext};const targetKey=(options.target||"es2020").toLowerCase();const moduleKey=(options.module||"esnext").toLowerCase();const compilerOptions={target:targetMap[targetKey]||ts.ScriptTarget.ES2020,module:moduleMap[moduleKey]||ts.ModuleKind.ESNext,strict:options.strict!==false,esModuleInterop:true,skipLibCheck:true,noEmit:false,...options.typeDefinitionPath&&{typeRoots:[path.dirname(options.typeDefinitionPath)],types:[path.basename(options.typeDefinitionPath,".d.ts")]},...options.compilerOptions};let diagnostics=[];if(!options.skipTypeCheck){const host=ts.createCompilerHost(compilerOptions);const originalReadFile=host.readFile;host.readFile=fileName=>{if(fileName===filePath){return code}return originalReadFile.call(host,fileName)};const program=ts.createProgram([filePath],compilerOptions,host);const allDiagnostics=[...program.getSemanticDiagnostics(),...program.getSyntacticDiagnostics()];diagnostics=allDiagnostics.filter(d=>d.file&&d.file.fileName===filePath)}const result=ts.transpileModule(code,{compilerOptions,fileName:filePath});return{code:result.outputText,diagnostics}}function formatDiagnostics(diagnostics,ts){return diagnostics.map(diagnostic=>{const message=ts.flattenDiagnosticMessageText(diagnostic.messageText,"\n");if(diagnostic.file&&diagnostic.start!==void 0){const{line,character}=diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start);const fileName=diagnostic.file.fileName;return`${fileName}:${line+1}:${character+1} - ${message}`}return message})}export{createDataUrl,formatDiagnostics,transformTypeScript,transformTypeScriptStrict};
|
|
17
|
+
import fs from"fs";import path from"path";import{writeFile,mkdir,readdir,rm}from"node:fs/promises";import{createHash}from"node:crypto";import{tmpdir}from"node:os";import{pathToFileURL}from"node:url";import{SlothletError}from"@cldmv/slothlet/errors";let esbuildInstance=null;let typescriptInstance=null;async function getEsbuild(){if(!esbuildInstance){try{esbuildInstance=await import("esbuild")}catch(error){throw new SlothletError("TYPESCRIPT_ESBUILD_NOT_INSTALLED",{mode:"fast"},error)}}return esbuildInstance}async function getTypeScript(){if(!typescriptInstance){try{typescriptInstance=await import("typescript")}catch(error){throw new SlothletError("TYPESCRIPT_TSC_NOT_INSTALLED",{mode:"strict"},error)}}return typescriptInstance}async function transformTypeScript(filePath,options={}){const esbuild=await getEsbuild();const code=fs.readFileSync(filePath,"utf8");const result=await esbuild.transform(code,{loader:"ts",format:options.format||"esm",target:options.target||"es2020",sourcemap:options.sourcemap||false,...options});return result.code}function createDataUrl(code){const encoded=encodeURIComponent(code);const timestamp=Date.now();return`data:text/javascript;charset=utf-8,${encoded}#t=${timestamp}`}function findPackageRoot(startPath){let dir;try{const resolved=path.resolve(startPath);dir=fs.statSync(resolved).isFile()?path.dirname(resolved):resolved}catch{return null}while(true){if(fs.existsSync(path.join(dir,"package.json")))return dir;const parent=path.dirname(dir);if(parent===dir)return null;dir=parent}}function isProcessAlive(pid){try{process.kill(pid,0);return true}catch(err){return err.code!=="ESRCH"}}const sweepPromises=new Map;function sweepStaleSlothletCache(projectRoot){if(sweepPromises.has(projectRoot))return sweepPromises.get(projectRoot);const promise=(async()=>{const cacheRoot=path.join(projectRoot,".slothlet-cache");let entries;try{entries=await readdir(cacheRoot,{withFileTypes:true})}catch{return}const currentPid=process.pid;await Promise.allSettled(entries.map(async entry=>{if(!entry.isDirectory())return;const match=entry.name.match(/^(\d+)-/);if(!match)return;const pid=Number(match[1]);if(pid===currentPid||isProcessAlive(pid))return;await rm(path.join(cacheRoot,entry.name),{recursive:true,force:true})}))})();sweepPromises.set(projectRoot,promise);return promise}async function writeTransformedToCache(originalPath,code,instanceID){const absolutePath=path.resolve(originalPath);const projectRoot=findPackageRoot(absolutePath)??tmpdir();await sweepStaleSlothletCache(projectRoot);const hash=createHash("sha256").update(absolutePath).update("\0").update(code).digest("hex").slice(0,16);const cacheDir=path.join(projectRoot,".slothlet-cache",`${process.pid}-${instanceID}`);const cachePath=path.join(cacheDir,`${hash}.mjs`);if(!fs.existsSync(cachePath)){await mkdir(cacheDir,{recursive:true});await writeFile(cachePath,code,"utf8")}return{url:pathToFileURL(cachePath).href,cacheDir}}async function transformTypeScriptStrict(filePath,options={}){const ts=await getTypeScript();const code=fs.readFileSync(filePath,"utf8");const targetMap={es3:ts.ScriptTarget.ES3,es5:ts.ScriptTarget.ES5,es6:ts.ScriptTarget.ES2015,es2015:ts.ScriptTarget.ES2015,es2016:ts.ScriptTarget.ES2016,es2017:ts.ScriptTarget.ES2017,es2018:ts.ScriptTarget.ES2018,es2019:ts.ScriptTarget.ES2019,es2020:ts.ScriptTarget.ES2020,es2021:ts.ScriptTarget.ES2021,es2022:ts.ScriptTarget.ES2022,esnext:ts.ScriptTarget.ESNext,latest:ts.ScriptTarget.Latest};const moduleMap={none:ts.ModuleKind.None,commonjs:ts.ModuleKind.CommonJS,amd:ts.ModuleKind.AMD,system:ts.ModuleKind.System,umd:ts.ModuleKind.UMD,es6:ts.ModuleKind.ES2015,es2015:ts.ModuleKind.ES2015,es2020:ts.ModuleKind.ES2020,es2022:ts.ModuleKind.ES2022,esnext:ts.ModuleKind.ESNext,node16:ts.ModuleKind.Node16,nodenext:ts.ModuleKind.NodeNext};const targetKey=(options.target||"es2020").toLowerCase();const moduleKey=(options.module||"esnext").toLowerCase();const compilerOptions={target:targetMap[targetKey]||ts.ScriptTarget.ES2020,module:moduleMap[moduleKey]||ts.ModuleKind.ESNext,strict:options.strict!==false,esModuleInterop:true,skipLibCheck:true,noEmit:false,...options.typeDefinitionPath&&{typeRoots:[path.dirname(options.typeDefinitionPath)],types:[path.basename(options.typeDefinitionPath,".d.ts")]},...options.compilerOptions};let diagnostics=[];if(!options.skipTypeCheck){const host=ts.createCompilerHost(compilerOptions);const originalReadFile=host.readFile;host.readFile=fileName=>{if(fileName===filePath){return code}return originalReadFile.call(host,fileName)};const program=ts.createProgram([filePath],compilerOptions,host);const allDiagnostics=[...program.getSemanticDiagnostics(),...program.getSyntacticDiagnostics()];diagnostics=allDiagnostics.filter(d=>d.file&&d.file.fileName===filePath)}const result=ts.transpileModule(code,{compilerOptions,fileName:filePath});return{code:result.outputText,diagnostics}}function formatDiagnostics(diagnostics,ts){return diagnostics.map(diagnostic=>{const message=ts.flattenDiagnosticMessageText(diagnostic.messageText,"\n");if(diagnostic.file&&diagnostic.start!==void 0){const{line,character}=diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start);const fileName=diagnostic.file.fileName;return`${fileName}:${line+1}:${character+1} - ${message}`}return message})}export{createDataUrl,formatDiagnostics,transformTypeScript,transformTypeScriptStrict,writeTransformedToCache};
|
|
@@ -14,4 +14,4 @@
|
|
|
14
14
|
limitations under the License.
|
|
15
15
|
*/
|
|
16
16
|
|
|
17
|
-
import{asyncRuntime}from"@cldmv/slothlet/factories/context";import{SlothletError}from"@cldmv/slothlet/errors";function safeGetContext(){try{return asyncRuntime.getContext()}catch{return null}}const self=new Proxy({},{get(_,prop){const ctx=safeGetContext();if(!ctx||!ctx.self){throw new SlothletError("RUNTIME_NO_ACTIVE_CONTEXT_SELF",{},null,{validationError:true})}return ctx.self[prop]},ownKeys(){const ctx=safeGetContext();if(!ctx||!ctx.self)return[];return Reflect.ownKeys(ctx.self)},has(_,prop){const ctx=safeGetContext();if(!ctx||!ctx.self)return false;return prop in ctx.self},getOwnPropertyDescriptor(_,prop){const ctx=safeGetContext();if(!ctx||!ctx.self)return void 0;const desc=Reflect.getOwnPropertyDescriptor(ctx.self,prop);if(desc){return{...desc,configurable:true}}return void 0}});const context=new Proxy({},{get(_,prop){const ctx=safeGetContext();if(!ctx||!ctx.context){return void 0}return ctx.context[prop]},set(_,prop,value){const ctx=safeGetContext();if(!ctx||!ctx.context){throw new SlothletError("RUNTIME_NO_ACTIVE_CONTEXT_CONTEXT",{},null,{validationError:true})}ctx.context[prop]=value;return true},ownKeys(){const ctx=safeGetContext();if(!ctx||!ctx.context)return[];return Reflect.ownKeys(ctx.context)},has(_,prop){const ctx=safeGetContext();if(!ctx||!ctx.context)return false;return prop in ctx.context},getOwnPropertyDescriptor(_,prop){const ctx=safeGetContext();if(!ctx||!ctx.context)return void 0;return Reflect.getOwnPropertyDescriptor(ctx.context,prop)}});const instanceID=new Proxy({},{get(_,prop){const ctx=safeGetContext();if(!ctx||!ctx.instanceID){return void 0}if(prop===Symbol.toPrimitive||prop==="toString"||prop==="valueOf"){return()=>ctx.instanceID}return ctx.instanceID[prop]},has(_,prop){const ctx=safeGetContext();if(!ctx||!ctx.instanceID)return false;return prop in Object(ctx.instanceID)}});export{context,instanceID,self};
|
|
17
|
+
import{asyncRuntime}from"@cldmv/slothlet/factories/context";import{SlothletError}from"@cldmv/slothlet/errors";function safeGetContext(){try{return asyncRuntime.getContext()}catch{return null}}const self=new Proxy({},{get(_,prop){const ctx=safeGetContext();if(!ctx||!ctx.self){throw new SlothletError("RUNTIME_NO_ACTIVE_CONTEXT_SELF",{},null,{validationError:true})}return ctx.self[prop]},ownKeys(){const ctx=safeGetContext();if(!ctx||!ctx.self)return[];return Reflect.ownKeys(ctx.self)},has(_,prop){const ctx=safeGetContext();if(!ctx||!ctx.self)return false;return prop in ctx.self},getOwnPropertyDescriptor(_,prop){const ctx=safeGetContext();if(!ctx||!ctx.self)return void 0;const desc=Reflect.getOwnPropertyDescriptor(ctx.self,prop);if(desc){return{...desc,configurable:true}}return void 0},set(_,prop,value){const ctx=safeGetContext();if(!ctx||!ctx.self){throw new SlothletError("RUNTIME_NO_ACTIVE_CONTEXT_SELF",{},null,{validationError:true})}if(typeof prop==="symbol"){ctx.self[prop]=value;return true}if(ctx.slothlet?.boundApi&&ctx.self!==ctx.slothlet.boundApi){ctx.self[prop]=value;return true}const apiManager=ctx.slothlet?.handlers?.apiManager;if(apiManager&&typeof apiManager.setOwnedProperty==="function"){apiManager.setOwnedProperty(String(prop),value,ctx.currentWrapper??null)}else{ctx.self[prop]=value}return true}});const context=new Proxy({},{get(_,prop){const ctx=safeGetContext();if(!ctx||!ctx.context){return void 0}return ctx.context[prop]},set(_,prop,value){const ctx=safeGetContext();if(!ctx||!ctx.context){throw new SlothletError("RUNTIME_NO_ACTIVE_CONTEXT_CONTEXT",{},null,{validationError:true})}ctx.context[prop]=value;return true},ownKeys(){const ctx=safeGetContext();if(!ctx||!ctx.context)return[];return Reflect.ownKeys(ctx.context)},has(_,prop){const ctx=safeGetContext();if(!ctx||!ctx.context)return false;return prop in ctx.context},getOwnPropertyDescriptor(_,prop){const ctx=safeGetContext();if(!ctx||!ctx.context)return void 0;return Reflect.getOwnPropertyDescriptor(ctx.context,prop)}});const instanceID=new Proxy({},{get(_,prop){const ctx=safeGetContext();if(!ctx||!ctx.instanceID){return void 0}if(prop===Symbol.toPrimitive||prop==="toString"||prop==="valueOf"){return()=>ctx.instanceID}return ctx.instanceID[prop]},has(_,prop){const ctx=safeGetContext();if(!ctx||!ctx.instanceID)return false;return prop in Object(ctx.instanceID)}});export{context,instanceID,self};
|
|
@@ -14,4 +14,4 @@
|
|
|
14
14
|
limitations under the License.
|
|
15
15
|
*/
|
|
16
16
|
|
|
17
|
-
import{liveRuntime}from"@cldmv/slothlet/factories/context";import{SlothletError}from"@cldmv/slothlet/errors";const self=new Proxy({},{get(_,prop){const ctx=liveRuntime.getContext();if(!ctx||!ctx.self){throw new SlothletError("RUNTIME_NO_ACTIVE_CONTEXT_SELF",{},null,{validationError:true})}return ctx.self[prop]},ownKeys(){const ctx=liveRuntime.getContext();if(!ctx||!ctx.self)return[];return Reflect.ownKeys(ctx.self)},has(_,prop){const ctx=liveRuntime.getContext();if(!ctx||!ctx.self)return false;return prop in ctx.self},getOwnPropertyDescriptor(_,prop){const ctx=liveRuntime.getContext();if(!ctx||!ctx.self)return void 0;const desc=Reflect.getOwnPropertyDescriptor(ctx.self,prop);if(desc){return{...desc,configurable:true}}return void 0}});const context=new Proxy({},{get(_,prop){const ctx=liveRuntime.getContext();if(!ctx||!ctx.context){return void 0}return ctx.context[prop]},set(_,prop,value){const ctx=liveRuntime.getContext();if(!ctx||!ctx.context){throw new SlothletError("RUNTIME_NO_ACTIVE_CONTEXT_CONTEXT",{},null,{validationError:true})}ctx.context[prop]=value;return true},ownKeys(){const ctx=liveRuntime.getContext();if(!ctx||!ctx.context)return[];return Reflect.ownKeys(ctx.context)},has(_,prop){const ctx=liveRuntime.getContext();if(!ctx||!ctx.context)return false;return prop in ctx.context},getOwnPropertyDescriptor(_,prop){const ctx=liveRuntime.getContext();if(!ctx||!ctx.context)return void 0;return Reflect.getOwnPropertyDescriptor(ctx.context,prop)}});export{context,self};
|
|
17
|
+
import{liveRuntime}from"@cldmv/slothlet/factories/context";import{SlothletError}from"@cldmv/slothlet/errors";const self=new Proxy({},{get(_,prop){const ctx=liveRuntime.getContext();if(!ctx||!ctx.self){throw new SlothletError("RUNTIME_NO_ACTIVE_CONTEXT_SELF",{},null,{validationError:true})}return ctx.self[prop]},ownKeys(){const ctx=liveRuntime.getContext();if(!ctx||!ctx.self)return[];return Reflect.ownKeys(ctx.self)},has(_,prop){const ctx=liveRuntime.getContext();if(!ctx||!ctx.self)return false;return prop in ctx.self},getOwnPropertyDescriptor(_,prop){const ctx=liveRuntime.getContext();if(!ctx||!ctx.self)return void 0;const desc=Reflect.getOwnPropertyDescriptor(ctx.self,prop);if(desc){return{...desc,configurable:true}}return void 0},set(_,prop,value){const ctx=liveRuntime.getContext();if(!ctx||!ctx.self){throw new SlothletError("RUNTIME_NO_ACTIVE_CONTEXT_SELF",{},null,{validationError:true})}if(typeof prop==="symbol"){ctx.self[prop]=value;return true}if(ctx.slothlet?.boundApi&&ctx.self!==ctx.slothlet.boundApi){ctx.self[prop]=value;return true}const apiManager=ctx.slothlet?.handlers?.apiManager;if(apiManager&&typeof apiManager.setOwnedProperty==="function"){apiManager.setOwnedProperty(String(prop),value,ctx.currentWrapper??null)}else{ctx.self[prop]=value}return true}});const context=new Proxy({},{get(_,prop){const ctx=liveRuntime.getContext();if(!ctx||!ctx.context){return void 0}return ctx.context[prop]},set(_,prop,value){const ctx=liveRuntime.getContext();if(!ctx||!ctx.context){throw new SlothletError("RUNTIME_NO_ACTIVE_CONTEXT_CONTEXT",{},null,{validationError:true})}ctx.context[prop]=value;return true},ownKeys(){const ctx=liveRuntime.getContext();if(!ctx||!ctx.context)return[];return Reflect.ownKeys(ctx.context)},has(_,prop){const ctx=liveRuntime.getContext();if(!ctx||!ctx.context)return false;return prop in ctx.context},getOwnPropertyDescriptor(_,prop){const ctx=liveRuntime.getContext();if(!ctx||!ctx.context)return void 0;return Reflect.getOwnPropertyDescriptor(ctx.context,prop)}});export{context,self};
|
|
@@ -14,4 +14,4 @@
|
|
|
14
14
|
limitations under the License.
|
|
15
15
|
*/
|
|
16
16
|
|
|
17
|
-
import{asyncRuntime,liveRuntime}from"@cldmv/slothlet/factories/context";const asyncRuntimeModule=await import("@cldmv/slothlet/runtime/async");const liveRuntimeModule=await import("@cldmv/slothlet/runtime/live");function getCurrentRuntime(){const asyncCtx=asyncRuntime.tryGetContext();if(asyncCtx){return asyncRuntimeModule}const liveCtx=liveRuntime.tryGetContext();if(liveCtx){return liveRuntimeModule}return asyncRuntimeModule}const self=new Proxy({},{get(_,prop){const runtime=getCurrentRuntime();return runtime.self[prop]},ownKeys(){const runtime=getCurrentRuntime();return Reflect.ownKeys(runtime.self)},has(_,prop){const runtime=getCurrentRuntime();return prop in runtime.self},getOwnPropertyDescriptor(_,prop){const runtime=getCurrentRuntime();const desc=Reflect.getOwnPropertyDescriptor(runtime.self,prop);if(desc){return{...desc,configurable:true}}return void 0}});const context=new Proxy({},{get(_,prop){const runtime=getCurrentRuntime();return runtime.context[prop]},ownKeys(){const runtime=getCurrentRuntime();return Reflect.ownKeys(runtime.context)},has(_,prop){const runtime=getCurrentRuntime();return prop in runtime.context},getOwnPropertyDescriptor(_,prop){const runtime=getCurrentRuntime();return Reflect.getOwnPropertyDescriptor(runtime.context,prop)},set(_,prop,value){const runtime=getCurrentRuntime();runtime.context[prop]=value;return true}});const instanceID=new Proxy({},{get(_,prop){const runtime=getCurrentRuntime();return runtime.instanceID?runtime.instanceID[prop]:void 0},has(_,prop){const runtime=getCurrentRuntime();return runtime.instanceID?prop in runtime.instanceID:false}});export{context,instanceID,self};
|
|
17
|
+
import{asyncRuntime,liveRuntime}from"@cldmv/slothlet/factories/context";const asyncRuntimeModule=await import("@cldmv/slothlet/runtime/async");const liveRuntimeModule=await import("@cldmv/slothlet/runtime/live");function getCurrentRuntime(){const asyncCtx=asyncRuntime.tryGetContext();if(asyncCtx){return asyncRuntimeModule}const liveCtx=liveRuntime.tryGetContext();if(liveCtx){return liveRuntimeModule}return asyncRuntimeModule}const self=new Proxy({},{get(_,prop){const runtime=getCurrentRuntime();return runtime.self[prop]},ownKeys(){const runtime=getCurrentRuntime();return Reflect.ownKeys(runtime.self)},has(_,prop){const runtime=getCurrentRuntime();return prop in runtime.self},getOwnPropertyDescriptor(_,prop){const runtime=getCurrentRuntime();const desc=Reflect.getOwnPropertyDescriptor(runtime.self,prop);if(desc){return{...desc,configurable:true}}return void 0},set(_,prop,value){const runtime=getCurrentRuntime();runtime.self[prop]=value;return true}});const context=new Proxy({},{get(_,prop){const runtime=getCurrentRuntime();return runtime.context[prop]},ownKeys(){const runtime=getCurrentRuntime();return Reflect.ownKeys(runtime.context)},has(_,prop){const runtime=getCurrentRuntime();return prop in runtime.context},getOwnPropertyDescriptor(_,prop){const runtime=getCurrentRuntime();return Reflect.getOwnPropertyDescriptor(runtime.context,prop)},set(_,prop,value){const runtime=getCurrentRuntime();runtime.context[prop]=value;return true}});const instanceID=new Proxy({},{get(_,prop){const runtime=getCurrentRuntime();return runtime.instanceID?runtime.instanceID[prop]:void 0},has(_,prop){const runtime=getCurrentRuntime();return runtime.instanceID?prop in runtime.instanceID:false}});export{context,instanceID,self};
|
|
@@ -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
|
+
import path from"node:path";import slothlet from"@cldmv/slothlet";import{generateTypes as writeDeclarationFile}from"@cldmv/slothlet/processors/type-generator";import{SlothletError}from"@cldmv/slothlet/errors";async function generateTypes(options={}){if(options===null||typeof options!=="object"||Array.isArray(options)){throw new SlothletError("INVALID_CONFIG",{option:"typegen.options",expected:"plain object",value:options,hint:"Call generateTypes({ dir, output, interfaceName }) with an options object.",validationError:true},null,{validationError:true})}assertOption(options.dir,"dir");assertOption(options.output,"output");assertOption(options.interfaceName,"interfaceName");const api=await slothlet({dir:path.resolve(options.dir),mode:"eager",typescript:options.typescript??{mode:"fast"}});try{const result=await writeDeclarationFile(api,{output:path.resolve(options.output),interfaceName:options.interfaceName,includeDocumentation:options.includeDocumentation??true});return{filePath:result.filePath,content:result.output}}finally{await api.slothlet.shutdown()}}function assertOption(value,name){if(typeof value!=="string"||value.length===0){throw new SlothletError("INVALID_CONFIG",{option:`typegen.${name}`,expected:"non-empty string",value,hint:`Provide options.${name} as a non-empty string when calling generateTypes(). For the CLI, use --${camelToKebab(name)} or the matching positional argument.`,validationError:true},null,{validationError:true})}}function camelToKebab(s){return s.replace(/[A-Z]/g,m=>`-${m.toLowerCase()}`)}export{generateTypes};
|
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.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(){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)}}}}_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;if(!this.envSnapshot){this.envSnapshot=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,"")}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||{};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()}`}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"){const{parts}=this.handlers.apiManager.normalizeApiPath(operation.apiPath);this.handlers.apiManager.deletePath(this.api,parts);if(this.handlers.metadata){const rootSegment=operation.apiPath.split(".")[0];this.handlers.metadata.removeUserMetadataByApiPath(rootSegment)}}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();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{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.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(){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)}}}}_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;if(!this.envSnapshot){this.envSnapshot=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};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cldmv/slothlet",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.5.0",
|
|
4
4
|
"moduleVersions": {
|
|
5
5
|
"lazy": "3.0.0",
|
|
6
6
|
"eager": "3.0.0",
|
|
@@ -10,12 +10,23 @@
|
|
|
10
10
|
"description": "Slothlet: Modular API Loader for Node.js. Lazy mode dynamically loads API modules and submodules only when accessed, supporting both lazy and eager loading.",
|
|
11
11
|
"main": "./index.cjs",
|
|
12
12
|
"module": "./index.mjs",
|
|
13
|
+
"bin": {
|
|
14
|
+
"slothlet": "./bin/slothlet.mjs"
|
|
15
|
+
},
|
|
13
16
|
"exports": {
|
|
14
17
|
".": {
|
|
15
18
|
"types": "./types/index.d.mts",
|
|
16
19
|
"import": "./index.mjs",
|
|
17
20
|
"require": "./index.cjs"
|
|
18
21
|
},
|
|
22
|
+
"./typegen": {
|
|
23
|
+
"slothlet-dev": {
|
|
24
|
+
"types": "./types/src/lib/typegen/typegen.d.mts",
|
|
25
|
+
"import": "./src/lib/typegen/typegen.mjs"
|
|
26
|
+
},
|
|
27
|
+
"types": "./types/dist/lib/typegen/typegen.d.mts",
|
|
28
|
+
"import": "./dist/lib/typegen/typegen.mjs"
|
|
29
|
+
},
|
|
19
30
|
"./devcheck": {
|
|
20
31
|
"types": "./types/devcheck.d.mts",
|
|
21
32
|
"import": "./devcheck.mjs"
|
|
@@ -319,7 +330,8 @@
|
|
|
319
330
|
"types/dist/",
|
|
320
331
|
"types/index.d.mts",
|
|
321
332
|
"types/index.d.mts.map",
|
|
322
|
-
"dist/"
|
|
333
|
+
"dist/",
|
|
334
|
+
"bin/"
|
|
323
335
|
],
|
|
324
336
|
"sideEffects": false
|
|
325
337
|
}
|
|
@@ -1,98 +1,7 @@
|
|
|
1
1
|
export class ApiBuilder extends ComponentBase {
|
|
2
2
|
static slothletProperty: string;
|
|
3
3
|
buildFinalAPI(userApi: any): Promise<any>;
|
|
4
|
-
createSlothletNamespace(userApi: any): Promise<
|
|
5
|
-
i18n: {
|
|
6
|
-
setLanguage: typeof setLanguage;
|
|
7
|
-
getLanguage: typeof getLanguage;
|
|
8
|
-
translate: typeof translate;
|
|
9
|
-
t: typeof translate;
|
|
10
|
-
initI18n: typeof initI18n;
|
|
11
|
-
};
|
|
12
|
-
version: string;
|
|
13
|
-
instanceID: any;
|
|
14
|
-
types: {
|
|
15
|
-
UNMATERIALIZED: symbol;
|
|
16
|
-
IN_FLIGHT: symbol;
|
|
17
|
-
};
|
|
18
|
-
api: {
|
|
19
|
-
add: (apiPath: any, folderPath: any, options?: {}, versionConfig?: null) => Promise<any>;
|
|
20
|
-
remove: (pathOrModuleId: any) => Promise<any>;
|
|
21
|
-
reload: (pathOrModuleId: any, options: any) => Promise<any>;
|
|
22
|
-
};
|
|
23
|
-
sanitize: (str: any) => any;
|
|
24
|
-
context: {
|
|
25
|
-
get: (key: any) => any;
|
|
26
|
-
diagnostics: () => {
|
|
27
|
-
instanceID: any;
|
|
28
|
-
managerType: any;
|
|
29
|
-
instancesMapSize: any;
|
|
30
|
-
instancesMapKeys: any[];
|
|
31
|
-
baseContext: any;
|
|
32
|
-
} | undefined;
|
|
33
|
-
run: (contextData: any, callback: any, ...args: any[]) => Promise<any>;
|
|
34
|
-
scope: (options: any) => Promise<any>;
|
|
35
|
-
};
|
|
36
|
-
hook: {
|
|
37
|
-
on: (typePattern: any, handler: any, options?: {}) => any;
|
|
38
|
-
remove: (filter?: {}) => any;
|
|
39
|
-
clear: (filter?: {}) => any;
|
|
40
|
-
off: (idOrFilter: any) => any;
|
|
41
|
-
enable: (filter?: {}) => any;
|
|
42
|
-
disable: (filter?: {}) => any;
|
|
43
|
-
list: (filter?: {}) => any;
|
|
44
|
-
};
|
|
45
|
-
metadata: {
|
|
46
|
-
setGlobal: (key: any, value: any) => any;
|
|
47
|
-
set: (fn: any, key: any, value: any) => any;
|
|
48
|
-
remove: (fn: any, key: any) => any;
|
|
49
|
-
setFor: (pathOrModuleId: any, keyOrObj: any, value: any) => any;
|
|
50
|
-
removeFor: (pathOrModuleId: any, key: any) => any;
|
|
51
|
-
setForVersion: (logicalPath: any, versionTag: any, keyOrObj: any, value: any) => any;
|
|
52
|
-
getForVersion: (logicalPath: any, versionTag: any) => any;
|
|
53
|
-
};
|
|
54
|
-
scope: (options: any) => Promise<any>;
|
|
55
|
-
run: (contextData: any, callback: any, ...args: any[]) => Promise<any>;
|
|
56
|
-
reload: (options?: {}) => Promise<any>;
|
|
57
|
-
shutdown: () => Promise<any>;
|
|
58
|
-
owner: {
|
|
59
|
-
get: (apiPath: any) => any;
|
|
60
|
-
};
|
|
61
|
-
materialize: Readonly<{
|
|
62
|
-
readonly materialized: any;
|
|
63
|
-
get: any;
|
|
64
|
-
wait: any;
|
|
65
|
-
}>;
|
|
66
|
-
lifecycle: {
|
|
67
|
-
on: any;
|
|
68
|
-
off: any;
|
|
69
|
-
};
|
|
70
|
-
env: any;
|
|
71
|
-
versioning: {
|
|
72
|
-
list: (logicalPath: any) => any;
|
|
73
|
-
setDefault: (logicalPath: any, versionTag: any) => any;
|
|
74
|
-
unregister: (logicalPath: any, versionTag: any) => Promise<boolean>;
|
|
75
|
-
getVersionMetadata: (logicalPath: any, versionTag: any) => any;
|
|
76
|
-
setVersionMetadata: (logicalPath: any, versionTag: any, patch: any) => any;
|
|
77
|
-
};
|
|
78
|
-
permissions: {
|
|
79
|
-
addRule: (rule: any) => any;
|
|
80
|
-
removeRule: (ruleId: any) => any;
|
|
81
|
-
self: {
|
|
82
|
-
access: (target: any) => any;
|
|
83
|
-
rules: () => any;
|
|
84
|
-
};
|
|
85
|
-
global: {
|
|
86
|
-
checkAccess: (caller: any, target: any) => any;
|
|
87
|
-
rulesForPath: (path: any) => any;
|
|
88
|
-
rulesByModule: (moduleID: any) => any;
|
|
89
|
-
};
|
|
90
|
-
control: {
|
|
91
|
-
enable: () => void;
|
|
92
|
-
disable: () => void;
|
|
93
|
-
};
|
|
94
|
-
};
|
|
95
|
-
}>;
|
|
4
|
+
createSlothletNamespace(userApi: any): Promise<any>;
|
|
96
5
|
createShutdownFunction(): () => Promise<any>;
|
|
97
6
|
createRunFunction(): (contextData: any, callback: any, ...args: any[]) => Promise<any>;
|
|
98
7
|
createScopeFunction(): (options: any) => Promise<any>;
|
|
@@ -100,8 +9,4 @@ export class ApiBuilder extends ComponentBase {
|
|
|
100
9
|
attachBuiltins(userApi: any, builtins: any): void;
|
|
101
10
|
}
|
|
102
11
|
import { ComponentBase } from "@cldmv/slothlet/factories/component-base";
|
|
103
|
-
import { setLanguage } from "@cldmv/slothlet/i18n";
|
|
104
|
-
import { getLanguage } from "@cldmv/slothlet/i18n";
|
|
105
|
-
import { translate } from "@cldmv/slothlet/i18n";
|
|
106
|
-
import { initI18n } from "@cldmv/slothlet/i18n";
|
|
107
12
|
//# sourceMappingURL=api_builder.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"api_builder.d.mts","sourceRoot":"","sources":["../../../../dist/lib/builders/api_builder.mjs"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"api_builder.d.mts","sourceRoot":"","sources":["../../../../dist/lib/builders/api_builder.mjs"],"names":[],"mappings":"AAAu8C;IAAuC,gCAAqC;IAAsC,0CAA66C;IAAA,oDAAopzB;IAAA,6CAAqR;IAAA,uFAA0vB;IAAA,sDAAsiJ;IAAA,qDAAmkB;IAAA,kDAA2Z;CAAC;8BAArnmC,0CAA0C"}
|
|
@@ -18,6 +18,7 @@ export class ApiManager extends ComponentBase {
|
|
|
18
18
|
buildDefaultModuleId(apiPath: any, ____resolvedFolderPath: any): string;
|
|
19
19
|
getValueAtPath(root: any, parts: any): any;
|
|
20
20
|
ensureParentPath(root: any, parts: any, options?: {}): any;
|
|
21
|
+
setOwnedProperty(apiPath: any, value: any, callerWrapper: any): void;
|
|
21
22
|
isWrapperProxy(value: any): boolean;
|
|
22
23
|
syncWrapper(existingProxy: any, nextProxy: any, config: any, collisionMode?: string, moduleID?: null): Promise<boolean>;
|
|
23
24
|
mutateApiValue(existingValue: any, nextValue: any, options: any, config: any): Promise<any>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"api-manager.d.mts","sourceRoot":"","sources":["../../../../dist/lib/handlers/api-manager.mjs"],"names":[],"mappings":"AAAiQ;IAAuC,gCAAqC;IAAsC;;;;MAAmF;IAAC;;;MAAwwD;IAAA;;;;OAAwhB;IAAA,iDAAwmB;IAAA,wEAAiL;IAAA,2CAA6L;IAAA,2DAAqxB;IAAA,oCAA0H;IAAA,wHAAsyI;IAAA,4FAA4vE;IAAA,kFAAivE;IAAA,oDAAsjE;IAAA,2DAA+zC;IAAgrB,
|
|
1
|
+
{"version":3,"file":"api-manager.d.mts","sourceRoot":"","sources":["../../../../dist/lib/handlers/api-manager.mjs"],"names":[],"mappings":"AAAiQ;IAAuC,gCAAqC;IAAsC;;;;MAAmF;IAAC;;;MAAwwD;IAAA;;;;OAAwhB;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;8BAAlsjD,0CAA0C"}
|
|
@@ -10,10 +10,10 @@ export class Metadata extends ComponentBase {
|
|
|
10
10
|
registerUserMetadata(identifier: any, metadata: any): void;
|
|
11
11
|
removeUserMetadataByApiPath(apiPath: any): void;
|
|
12
12
|
setPathMetadata(apiPath: any, keyOrObj: any, value: any): void;
|
|
13
|
-
getPathMetadata(apiPath: any):
|
|
13
|
+
getPathMetadata(apiPath: any): any;
|
|
14
14
|
removePathMetadata(apiPath: any, key: any): void;
|
|
15
15
|
exportUserState(): {
|
|
16
|
-
globalMetadata:
|
|
16
|
+
globalMetadata: any;
|
|
17
17
|
userMetadataStore: Map<any, any>;
|
|
18
18
|
};
|
|
19
19
|
importUserState(state: any): void;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"metadata.d.mts","sourceRoot":"","sources":["../../../../dist/lib/handlers/metadata.mjs"],"names":[],"mappings":"AAA2M;IAAqC,gCAAmC;
|
|
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"}
|
|
@@ -3,6 +3,9 @@ export class OwnershipManager extends ComponentBase {
|
|
|
3
3
|
moduleToPath: Map<any, any>;
|
|
4
4
|
pathToModule: Map<any, any>;
|
|
5
5
|
_unregisteredModules: Set<any>;
|
|
6
|
+
moduleEndpoints: Map<any, any>;
|
|
7
|
+
setModuleEndpoint(moduleID: any, endpoint: any): void;
|
|
8
|
+
getModuleEndpoint(moduleID: any): any;
|
|
6
9
|
register({ moduleID, apiPath, value, source, collisionMode, config, filePath }: {
|
|
7
10
|
moduleID: any;
|
|
8
11
|
apiPath: any;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ownership.d.mts","sourceRoot":"","sources":["../../../../dist/lib/handlers/ownership.mjs"],"names":[],"mappings":"AAAyI;IAA6C,gCAAoC;IAAsC,4BAAyB;IAAC,4BAAyB;IAAC,+BAAiC;IAAC;;;;;;;;YAAqlD;IAAA;;;;;;
|
|
1
|
+
{"version":3,"file":"ownership.d.mts","sourceRoot":"","sources":["../../../../dist/lib/handlers/ownership.mjs"],"names":[],"mappings":"AAAyI;IAA6C,gCAAoC;IAAsC,4BAAyB;IAAC,4BAAyB;IAAC,+BAAiC;IAAC,+BAA4B;IAAC,sDAA2H;IAAA,sCAAsE;IAAA;;;;;;;;YAAqlD;IAAA;;;;;;MAA6f;IAAA;;;;MAAszB;IAAA,mCAAyI;IAAA,mCAA+M;IAAA,qCAAgF;IAAA,kCAAkE;IAAA,2CAA6G;IAAA;;;;;;;;;;;MAA6W;IAAA,gDAA+J;IAAA,qFAAstB;IAAA,cAA2H;IAAA;;;MAA0K;IAAA,8BAAkM;CAAC;8BAApsL,0CAA0C"}
|
|
@@ -2,7 +2,9 @@ export class PermissionManager extends ComponentBase {
|
|
|
2
2
|
static slothletProperty: string;
|
|
3
3
|
addRule(rule: any, ownerModuleID?: null, ruleId?: null): string;
|
|
4
4
|
removeRule(ruleId: any, callerModuleID?: null): boolean;
|
|
5
|
-
checkAccess(callerPath: any, targetPath: any, callerFilePath?: null, targetFilePath?: null, runtimeContext?: null): any;
|
|
5
|
+
checkAccess(callerPath: any, targetPath: any, callerFilePath?: null, targetFilePath?: null, runtimeContext?: null, options?: null): any;
|
|
6
|
+
matchesCondition(condition: any, runtimeContext?: null): boolean;
|
|
7
|
+
enforceAccess(callerPath: any, targetPath: any, callerFilePath?: null, targetFilePath?: null, runtimeContext?: null): any;
|
|
6
8
|
getRulesForPath(targetPath: any): {
|
|
7
9
|
id: any;
|
|
8
10
|
caller: any;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"permission-manager.d.mts","sourceRoot":"","sources":["../../../../dist/lib/handlers/permission-manager.mjs"],"names":[],"mappings":"AAAwM;IAA8C,gCAA4C;IAAiiB,gEAAsc;IAAA,wDAAqc;IAAA,
|
|
1
|
+
{"version":3,"file":"permission-manager.d.mts","sourceRoot":"","sources":["../../../../dist/lib/handlers/permission-manager.mjs"],"names":[],"mappings":"AAAwM;IAA8C,gCAA4C;IAAiiB,gEAAsc;IAAA,wDAAqc;IAAA,wIAAqwB;IAAA,iEAAgN;IAA4Q,0HAAoS;IAAA;;;;;;;;QAA2O;IAAA;;;;;;;;QAAoL;IAAA;;;;;;;;QAA6O;IAAA,eAA+C;IAAA,gBAAiD;IAAA,qBAAiC;IAAA;;;;;;;QAAsM;IAAA,sCAA6I;IAAA,0BAAmK;IAAiwL,sCAAwD;;CAAC;8BAAvvU,0CAA0C"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"unified-wrapper.d.mts","sourceRoot":"","sources":["../../../../dist/lib/handlers/unified-wrapper.mjs"],"names":[],"mappings":";;;;AAA+vC;;IAA6jH,mCAAsc;IAAA,2CAAy/B;IAA32J;;;;;;;;;;OAAq1F;IAA56F,6CAAuF;IAAy3G,kBAAmD;IAA+7C,gEAAqyB;IAAA,8EAAgsC;IAAA,4CAA2kC;IAAA,+BAAs4D;IAAA,6BAA4C;IAAA,sBAA8T;IAAA,yDAAq6P;IAAA,iDAA2sG;IAAA,8CAA20Y;IAAA,
|
|
1
|
+
{"version":3,"file":"unified-wrapper.d.mts","sourceRoot":"","sources":["../../../../dist/lib/handlers/unified-wrapper.mjs"],"names":[],"mappings":";;;;AAA+vC;;IAA6jH,mCAAsc;IAAA,2CAAy/B;IAA32J;;;;;;;;;;OAAq1F;IAA56F,6CAAuF;IAAy3G,kBAAmD;IAA+7C,gEAAqyB;IAAA,8EAAgsC;IAAA,4CAA2kC;IAAA,+BAAs4D;IAAA,6BAA4C;IAAA,sBAA8T;IAAA,yDAAq6P;IAAA,iDAA2sG;IAAA,8CAA20Y;IAAA,mBAAs1wB;IAA3oO,uBAAwB;;CAAonO;AAAA,gDAA8N;8BAAh52D,0CAA0C"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"loader.d.mts","sourceRoot":"","sources":["../../../../dist/lib/processors/loader.mjs"],"names":[],"mappings":"AAA+O;IAAmC,gCAAiC;IAAsC,
|
|
1
|
+
{"version":3,"file":"loader.d.mts","sourceRoot":"","sources":["../../../../dist/lib/processors/loader.mjs"],"names":[],"mappings":"AAA+O;IAAmC,gCAAiC;IAAsC,0FAA2zG;IAAgyB;;;OAA+7C;IAAA,gCAAipB;;CAAC;8BAAj0M,0CAA0C"}
|
|
@@ -5,4 +5,8 @@ export function transformTypeScriptStrict(filePath: any, options?: {}): Promise<
|
|
|
5
5
|
code: any;
|
|
6
6
|
diagnostics: any[];
|
|
7
7
|
}>;
|
|
8
|
+
export function writeTransformedToCache(originalPath: any, code: any, instanceID: any): Promise<{
|
|
9
|
+
url: any;
|
|
10
|
+
cacheDir: any;
|
|
11
|
+
}>;
|
|
8
12
|
//# sourceMappingURL=typescript.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"typescript.d.mts","sourceRoot":"","sources":["../../../../dist/lib/processors/typescript.mjs"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"typescript.d.mts","sourceRoot":"","sources":["../../../../dist/lib/processors/typescript.mjs"],"names":[],"mappings":"AAA2hC,iDAAoK;AAA0lH,kEAAkZ;AAA58I,+EAA4T;AAA21D;;;GAAm6D;AAA5gF;;;GAAymB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtime-asynclocalstorage.d.mts","sourceRoot":"","sources":["../../../../dist/lib/runtime/runtime-asynclocalstorage.mjs"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"runtime-asynclocalstorage.d.mts","sourceRoot":"","sources":["../../../../dist/lib/runtime/runtime-asynclocalstorage.mjs"],"names":[],"mappings":"AAAmzC,yBAAmrB;AAAA,4BAA6V;AAAnoE,sBAAmnC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtime-livebindings.d.mts","sourceRoot":"","sources":["../../../../dist/lib/runtime/runtime-livebindings.mjs"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"runtime-livebindings.d.mts","sourceRoot":"","sources":["../../../../dist/lib/runtime/runtime-livebindings.mjs"],"names":[],"mappings":"AAAwwC,yBAA2tB;AAAt3D,sBAA2pC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runtime.d.mts","sourceRoot":"","sources":["../../../../dist/lib/runtime/runtime.mjs"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"runtime.d.mts","sourceRoot":"","sources":["../../../../dist/lib/runtime/runtime.mjs"],"names":[],"mappings":"AAAo8B,yBAA4e;AAAA,4BAAoP;AAAvvC,sBAAuhB"}
|