@cldmv/slothlet 2.8.0 → 2.10.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.
Files changed (59) hide show
  1. package/AGENT-USAGE.md +1 -1
  2. package/README.md +300 -1557
  3. package/dist/lib/engine/slothlet_child.mjs +1 -1
  4. package/dist/lib/engine/slothlet_engine.mjs +1 -1
  5. package/dist/lib/engine/slothlet_esm.mjs +1 -1
  6. package/dist/lib/engine/slothlet_helpers.mjs +1 -1
  7. package/dist/lib/engine/slothlet_worker.mjs +1 -1
  8. package/dist/lib/helpers/als-eventemitter.mjs +5 -6
  9. package/dist/lib/helpers/api_builder/add_api.mjs +292 -0
  10. package/dist/lib/helpers/api_builder/analysis.mjs +532 -0
  11. package/dist/lib/helpers/api_builder/construction.mjs +457 -0
  12. package/dist/lib/helpers/api_builder/decisions.mjs +737 -0
  13. package/dist/lib/helpers/api_builder/metadata.mjs +248 -0
  14. package/dist/lib/helpers/api_builder.mjs +17 -1568
  15. package/dist/lib/helpers/auto-wrap.mjs +1 -1
  16. package/dist/lib/helpers/hooks.mjs +1 -1
  17. package/dist/lib/helpers/instance-manager.mjs +1 -1
  18. package/dist/lib/helpers/metadata-api.mjs +201 -0
  19. package/dist/lib/helpers/multidefault.mjs +12 -3
  20. package/dist/lib/helpers/resolve-from-caller.mjs +1 -1
  21. package/dist/lib/helpers/sanitize.mjs +1 -1
  22. package/dist/lib/helpers/utilities.mjs +121 -0
  23. package/dist/lib/modes/slothlet_eager.mjs +1 -1
  24. package/dist/lib/modes/slothlet_lazy.mjs +10 -1
  25. package/dist/lib/runtime/runtime-asynclocalstorage.mjs +49 -18
  26. package/dist/lib/runtime/runtime-livebindings.mjs +23 -4
  27. package/dist/lib/runtime/runtime.mjs +15 -4
  28. package/dist/slothlet.mjs +164 -748
  29. package/docs/API-RULES-CONDITIONS.md +508 -0
  30. package/{API-RULES.md → docs/API-RULES.md} +127 -72
  31. package/package.json +11 -9
  32. package/types/dist/lib/helpers/als-eventemitter.d.mts.map +1 -1
  33. package/types/dist/lib/helpers/api_builder/add_api.d.mts +76 -0
  34. package/types/dist/lib/helpers/api_builder/add_api.d.mts.map +1 -0
  35. package/types/dist/lib/helpers/api_builder/analysis.d.mts +189 -0
  36. package/types/dist/lib/helpers/api_builder/analysis.d.mts.map +1 -0
  37. package/types/dist/lib/helpers/api_builder/construction.d.mts +107 -0
  38. package/types/dist/lib/helpers/api_builder/construction.d.mts.map +1 -0
  39. package/types/dist/lib/helpers/api_builder/decisions.d.mts +213 -0
  40. package/types/dist/lib/helpers/api_builder/decisions.d.mts.map +1 -0
  41. package/types/dist/lib/helpers/api_builder/metadata.d.mts +99 -0
  42. package/types/dist/lib/helpers/api_builder/metadata.d.mts.map +1 -0
  43. package/types/dist/lib/helpers/api_builder.d.mts +5 -448
  44. package/types/dist/lib/helpers/api_builder.d.mts.map +1 -1
  45. package/types/dist/lib/helpers/metadata-api.d.mts +132 -0
  46. package/types/dist/lib/helpers/metadata-api.d.mts.map +1 -0
  47. package/types/dist/lib/helpers/multidefault.d.mts.map +1 -1
  48. package/types/dist/lib/helpers/utilities.d.mts +120 -0
  49. package/types/dist/lib/helpers/utilities.d.mts.map +1 -0
  50. package/types/dist/lib/runtime/runtime-asynclocalstorage.d.mts +9 -0
  51. package/types/dist/lib/runtime/runtime-asynclocalstorage.d.mts.map +1 -1
  52. package/types/dist/lib/runtime/runtime-livebindings.d.mts +10 -0
  53. package/types/dist/lib/runtime/runtime-livebindings.d.mts.map +1 -1
  54. package/types/dist/lib/runtime/runtime.d.mts +1 -0
  55. package/types/dist/lib/runtime/runtime.d.mts.map +1 -1
  56. package/types/dist/slothlet.d.mts +0 -11
  57. package/types/dist/slothlet.d.mts.map +1 -1
  58. package/types/index.d.mts +0 -1
  59. package/API-RULES-CONDITIONS.md +0 -367
@@ -0,0 +1,532 @@
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
+
18
+
19
+
20
+
21
+ import fs from "node:fs/promises";
22
+ import path from "node:path";
23
+ import { types as utilTypes } from "node:util";
24
+ import { pathToFileURL } from "node:url";
25
+ import { multidefault_analyzeModules } from "@cldmv/slothlet/helpers/multidefault";
26
+ import { setActiveInstance } from "@cldmv/slothlet/helpers/instance-manager";
27
+
28
+
29
+
30
+
31
+
32
+
33
+ export function isLikelySerializable(val) {
34
+ const type = typeof val;
35
+
36
+
37
+ if (type !== "object" || val === null) {
38
+ return type === "string" || type === "number" || type === "boolean" || type === "undefined";
39
+ }
40
+
41
+
42
+ return (
43
+ Array.isArray(val) || val instanceof Date || val instanceof RegExp || val?.constructor === Object || typeof val.toJSON === "function"
44
+ );
45
+ }
46
+
47
+
48
+
49
+
50
+
51
+
52
+ export async function analyzeModule(modulePath, options = {}) {
53
+ const { debug = false, instance = null } = options;
54
+
55
+ const moduleUrl = pathToFileURL(modulePath).href;
56
+
57
+
58
+
59
+ let importUrl = moduleUrl;
60
+ const separator = moduleUrl.includes("?") ? "&" : "?";
61
+
62
+
63
+ importUrl = `${moduleUrl}${separator}_t=${Date.now()}_${Math.random().toString(36).slice(2)}`;
64
+
65
+ if (instance && instance.instanceId) {
66
+ const runtimeType = instance.config?.runtime || "async";
67
+
68
+
69
+ if (runtimeType === "live") {
70
+ importUrl = `${importUrl}&slothlet_instance=${instance.instanceId}`;
71
+ importUrl = `${importUrl}&slothlet_runtime=${runtimeType}`;
72
+
73
+
74
+ setActiveInstance(instance.instanceId);
75
+ }
76
+
77
+
78
+ }
79
+
80
+ if (debug) {
81
+ console.log(`[DEBUG] analyzeModule: Importing ${path.basename(modulePath)}`);
82
+ console.log(`[DEBUG] URL: ${importUrl}`);
83
+ }
84
+
85
+ const rawModule = await import(importUrl);
86
+
87
+
88
+ let processedModule = rawModule;
89
+ const isCjs = modulePath.endsWith(".cjs") && "default" in rawModule;
90
+
91
+ if (isCjs) {
92
+ processedModule = rawModule.default;
93
+ }
94
+
95
+ const hasDefault = !!processedModule.default;
96
+ const isFunction = typeof processedModule.default === "function";
97
+ const exports = Object.entries(processedModule);
98
+ const namedExports = Object.entries(processedModule).filter(([k]) => k !== "default");
99
+
100
+
101
+ let defaultExportType = null;
102
+ if (hasDefault) {
103
+ defaultExportType = typeof processedModule.default === "function" ? "function" : "object";
104
+ }
105
+
106
+
107
+ let shouldWrapAsCallable = false;
108
+
109
+
110
+ if (
111
+ hasDefault &&
112
+ typeof processedModule.default === "object" &&
113
+ processedModule.default !== null &&
114
+ typeof processedModule.default.default === "function"
115
+ ) {
116
+ shouldWrapAsCallable = true;
117
+ }
118
+
119
+
120
+ if (!shouldWrapAsCallable) {
121
+ for (const [_, exportValue] of namedExports) {
122
+ if (typeof exportValue === "object" && exportValue !== null && typeof exportValue.default === "function") {
123
+ shouldWrapAsCallable = true;
124
+ break;
125
+ }
126
+ }
127
+ }
128
+
129
+ if (debug) {
130
+ console.log(`[DEBUG] analyzeModule(${path.basename(modulePath)}):`, {
131
+ isCjs,
132
+ hasDefault,
133
+ isFunction,
134
+ defaultExportType,
135
+ shouldWrapAsCallable,
136
+ namedExportsCount: namedExports.length
137
+ });
138
+ }
139
+
140
+ return {
141
+ rawModule,
142
+ processedModule,
143
+ isFunction,
144
+ hasDefault,
145
+ isCjs,
146
+ exports,
147
+ defaultExportType,
148
+ shouldWrapAsCallable,
149
+ namedExports,
150
+ metadata: { modulePath }
151
+ };
152
+ }
153
+
154
+
155
+ export function processModuleFromAnalysis(analysis, options = {}) {
156
+ const { instance, debug = false } = options;
157
+ const { processedModule, isFunction, hasDefault, shouldWrapAsCallable, namedExports } = analysis;
158
+
159
+ if (!instance) {
160
+ throw new Error("processModuleFromAnalysis requires instance parameter for _toapiPathKey access");
161
+ }
162
+
163
+
164
+ if (isFunction) {
165
+ let fn = processedModule.default;
166
+
167
+
168
+ if (hasDefault) {
169
+ try {
170
+ Object.defineProperty(fn, "__slothletDefault", {
171
+ value: true,
172
+ writable: false,
173
+ enumerable: false,
174
+ configurable: true
175
+ });
176
+ } catch {
177
+
178
+ }
179
+ }
180
+
181
+
182
+ for (const [exportName, exportValue] of Object.entries(processedModule)) {
183
+ if (exportName !== "default") {
184
+ fn[instance._toapiPathKey(exportName)] = exportValue;
185
+ }
186
+ }
187
+ return fn;
188
+ }
189
+
190
+
191
+ if (shouldWrapAsCallable) {
192
+ let callableObject = null;
193
+ let objectName = "callable";
194
+
195
+
196
+ if (
197
+ hasDefault &&
198
+ typeof processedModule.default === "object" &&
199
+ processedModule.default !== null &&
200
+ typeof processedModule.default.default === "function"
201
+ ) {
202
+ callableObject = processedModule.default;
203
+ objectName = processedModule.default.name || (namedExports[0] && namedExports[0][0] !== "default" ? namedExports[0][0] : "callable");
204
+ } else {
205
+
206
+ for (const [exportName, exportValue] of namedExports) {
207
+ if (typeof exportValue === "object" && exportValue !== null && typeof exportValue.default === "function") {
208
+ callableObject = exportValue;
209
+ objectName = exportName;
210
+ break;
211
+ }
212
+ }
213
+ }
214
+
215
+ if (callableObject) {
216
+ const callableApi = {
217
+ [objectName]: function (...args) {
218
+ return callableObject.default.apply(callableObject, args);
219
+ }
220
+ }[objectName];
221
+
222
+
223
+ for (const [methodName, method] of Object.entries(callableObject)) {
224
+ if (methodName === "default") continue;
225
+ callableApi[methodName] = method;
226
+ }
227
+
228
+ if (debug) {
229
+ console.log(`[DEBUG] Created callable wrapper for ${objectName}`);
230
+ }
231
+
232
+ return callableApi;
233
+ }
234
+ }
235
+
236
+
237
+ if (hasDefault && typeof processedModule.default === "object") {
238
+ const obj = processedModule.default;
239
+
240
+
241
+ const namedExportsToAdd = Object.entries(processedModule).filter(
242
+ ([exportName, exportValue]) => exportName !== "default" && exportValue !== obj
243
+ );
244
+
245
+ if (namedExportsToAdd.length > 0) {
246
+
247
+
248
+ const isCustomProxy = utilTypes?.isProxy?.(obj) ?? false;
249
+
250
+ if (isCustomProxy) {
251
+
252
+
253
+ for (const [exportName, exportValue] of namedExportsToAdd) {
254
+ const apiKey = instance._toapiPathKey(exportName);
255
+ obj[apiKey] = exportValue;
256
+ }
257
+
258
+
259
+
260
+ const proxyWithStructure = obj;
261
+
262
+
263
+
264
+
265
+
266
+
267
+
268
+
269
+
270
+
271
+
272
+
273
+
274
+
275
+
276
+
277
+
278
+
279
+
280
+
281
+ proxyWithStructure.default = obj;
282
+
283
+
284
+ if (!proxyWithStructure.toJSON) {
285
+ Object.defineProperty(proxyWithStructure, "toJSON", {
286
+ value: function () {
287
+
288
+ const serializable = {};
289
+
290
+
291
+ for (const key of Reflect.ownKeys(this)) {
292
+
293
+ if (typeof key !== "string") continue;
294
+
295
+ const descriptor = Reflect.getOwnPropertyDescriptor(this, key);
296
+ if (!descriptor || !descriptor.enumerable) continue;
297
+
298
+ if (key === "default") {
299
+
300
+ continue;
301
+ }
302
+
303
+ const value = this[key];
304
+ if (typeof value === "function") {
305
+ serializable[key] = "[Function]";
306
+ } else if (isLikelySerializable(value)) {
307
+
308
+ serializable[key] = value;
309
+ } else {
310
+
311
+ try {
312
+ JSON.stringify(value);
313
+ serializable[key] = value;
314
+ } catch {
315
+ serializable[key] = "[Non-serializable value]";
316
+ }
317
+ }
318
+ }
319
+
320
+
321
+ serializable._slothlet_proxy_info = {
322
+ type: "proxy",
323
+ circular_reference: "Property .default points to this object (excluded from serialization)",
324
+ warning: "This is a slothlet API proxy with circular .default reference"
325
+ };
326
+ return serializable;
327
+ },
328
+ writable: false,
329
+ enumerable: false,
330
+ configurable: true
331
+ });
332
+ }
333
+
334
+
335
+ for (const [exportName, exportValue] of namedExportsToAdd) {
336
+ const apiKey = instance._toapiPathKey(exportName);
337
+ if (!(apiKey in proxyWithStructure)) {
338
+ proxyWithStructure[apiKey] = exportValue;
339
+ }
340
+ }
341
+
342
+ return proxyWithStructure;
343
+ } else {
344
+
345
+ for (const [exportName, exportValue] of namedExportsToAdd) {
346
+ obj[instance._toapiPathKey(exportName)] = exportValue;
347
+ }
348
+
349
+ return obj;
350
+ }
351
+ }
352
+
353
+ return obj;
354
+ }
355
+
356
+
357
+ if (namedExports.length > 0) {
358
+ const apiExport = {};
359
+ for (const [exportName, exportValue] of namedExports) {
360
+ apiExport[instance._toapiPathKey(exportName)] = exportValue;
361
+ }
362
+ return apiExport;
363
+ }
364
+
365
+
366
+ throw new Error(`No valid exports found in processed module`);
367
+ }
368
+
369
+
370
+ export async function analyzeDirectoryStructure(categoryPath, options = {}) {
371
+ const { instance, currentDepth = 0, debug = false } = options;
372
+
373
+ if (!instance || typeof instance._toapiPathKey !== "function") {
374
+ throw new Error("analyzeDirectoryStructure requires a valid slothlet instance");
375
+ }
376
+
377
+ const files = await fs.readdir(categoryPath, { withFileTypes: true });
378
+ const moduleFiles = files.filter((f) => instance._shouldIncludeFile(f));
379
+ const categoryName = instance._toapiPathKey(path.basename(categoryPath));
380
+ const subDirs = files.filter((e) => e.isDirectory() && !e.name.startsWith("."));
381
+
382
+
383
+ let processingStrategy;
384
+ if (moduleFiles.length === 0) {
385
+ processingStrategy = "empty";
386
+ } else if (moduleFiles.length === 1 && subDirs.length === 0) {
387
+ processingStrategy = "single-file";
388
+ } else {
389
+ processingStrategy = "multi-file";
390
+ }
391
+
392
+
393
+ let multiDefaultAnalysis = null;
394
+ if (processingStrategy === "multi-file") {
395
+ multiDefaultAnalysis = await multidefault_analyzeModules(moduleFiles, categoryPath, { debug, instance });
396
+ }
397
+
398
+
399
+ const flatteningHints = {
400
+ shouldFlattenSingleFile: processingStrategy === "single-file",
401
+ shouldFlattenToParent: currentDepth > 0 && processingStrategy === "single-file",
402
+ hasMultipleDefaults: multiDefaultAnalysis?.hasMultipleDefaultExports || false,
403
+ selfReferentialFiles: multiDefaultAnalysis?.selfReferentialFiles || new Set()
404
+ };
405
+
406
+ if (debug) {
407
+ console.log(`[DEBUG] analyzeDirectoryStructure(${categoryName}):`, {
408
+ processingStrategy,
409
+ moduleCount: moduleFiles.length,
410
+ subDirCount: subDirs.length,
411
+ hasMultipleDefaults: flatteningHints.hasMultipleDefaults
412
+ });
413
+ }
414
+
415
+ return {
416
+ isSingleFile: processingStrategy === "single-file",
417
+ shouldAutoFlatten: flatteningHints.shouldFlattenSingleFile,
418
+ categoryName,
419
+ moduleFiles,
420
+ subDirs,
421
+ multiDefaultAnalysis,
422
+ processingStrategy,
423
+ flatteningHints
424
+ };
425
+ }
426
+
427
+
428
+ export async function getCategoryBuildingDecisions(categoryPath, options = {}) {
429
+ const { instance, currentDepth = 0, maxDepth = Infinity, debug = false } = options;
430
+
431
+ if (!instance) {
432
+ throw new Error("getCategoryBuildingDecisions requires a valid slothlet instance");
433
+ }
434
+
435
+ const analysis = await analyzeDirectoryStructure(categoryPath, { instance, currentDepth, maxDepth, debug });
436
+ const { processingStrategy, categoryName, moduleFiles, subDirs, multiDefaultAnalysis } = analysis;
437
+
438
+ const processedModules = [];
439
+ const subDirectories = [];
440
+
441
+
442
+ if (processingStrategy !== "empty") {
443
+ for (const file of moduleFiles) {
444
+ const moduleExt = path.extname(file.name);
445
+ const moduleName = instance._toapiPathKey(path.basename(file.name, moduleExt));
446
+ const modulePath = path.join(categoryPath, file.name);
447
+
448
+
449
+ const analysis = await analyzeModule(modulePath, {
450
+ debug,
451
+ instance
452
+ });
453
+ const processedModule = processModuleFromAnalysis(analysis, {
454
+ debug,
455
+ instance
456
+ });
457
+
458
+
459
+ const flatteningInfo = {
460
+ shouldFlatten: false,
461
+ apiPathKey: moduleName,
462
+ reason: "default"
463
+ };
464
+
465
+
466
+ if (processingStrategy === "single-file") {
467
+
468
+ const functionNameMatchesFolder =
469
+ typeof processedModule === "function" &&
470
+ processedModule.name &&
471
+ processedModule.name.toLowerCase() === categoryName.toLowerCase();
472
+
473
+ const moduleNameMatchesCategory = moduleName === categoryName && typeof processedModule === "function" && currentDepth > 0;
474
+
475
+ if (functionNameMatchesFolder && currentDepth > 0) {
476
+ flatteningInfo.shouldFlatten = true;
477
+ flatteningInfo.apiPathKey = processedModule.name;
478
+ flatteningInfo.reason = "function name matches folder";
479
+ } else if (moduleNameMatchesCategory) {
480
+ flatteningInfo.shouldFlatten = true;
481
+ flatteningInfo.apiPathKey = categoryName;
482
+ flatteningInfo.reason = "module name matches category";
483
+ }
484
+ }
485
+
486
+ processedModules.push({
487
+ file,
488
+ moduleName,
489
+ processedModule,
490
+ flattening: flatteningInfo
491
+ });
492
+ }
493
+ }
494
+
495
+
496
+ for (const subDirEntry of subDirs) {
497
+ if (currentDepth < maxDepth) {
498
+ const apiPathKey = instance._toapiPathKey(subDirEntry.name);
499
+ subDirectories.push({ dirEntry: subDirEntry, apiPathKey });
500
+ }
501
+ }
502
+
503
+
504
+ const upwardFlatteningCandidate = { shouldFlatten: false, apiPathKey: null };
505
+ if (processedModules.length === 1 && subDirectories.length === 0) {
506
+ const single = processedModules[0];
507
+ if (single.moduleName === categoryName) {
508
+ upwardFlatteningCandidate.shouldFlatten = true;
509
+ upwardFlatteningCandidate.apiPathKey = single.moduleName;
510
+ }
511
+ }
512
+
513
+ if (debug) {
514
+ console.log(`[DEBUG] getCategoryBuildingDecisions(${categoryName}):`, {
515
+ processingStrategy,
516
+ moduleCount: processedModules.length,
517
+ subDirCount: subDirectories.length,
518
+ upwardFlattening: upwardFlatteningCandidate.shouldFlatten
519
+ });
520
+ }
521
+
522
+ return {
523
+ processingStrategy,
524
+ categoryName,
525
+ shouldFlattenSingle: processingStrategy === "single-file",
526
+ processedModules,
527
+ subDirectories,
528
+ multiDefaultAnalysis,
529
+ flatteningDecisions: analysis.flatteningHints,
530
+ upwardFlatteningCandidate
531
+ };
532
+ }