@cldmv/slothlet 2.4.2 → 2.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.
@@ -0,0 +1,197 @@
1
+ /*
2
+ Copyright 2025 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
+ import path from "path";
20
+
21
+
22
+ async function multidefault_analyzeModules(moduleFiles, baseDir, debug = false) {
23
+ const selfReferentialFiles = new Set();
24
+ const rawModuleCache = new Map();
25
+ const defaultExportFiles = [];
26
+ let totalDefaultExports = 0;
27
+
28
+ if (debug) {
29
+ console.log(`[DEBUG] multidefault_analyzeModules: Processing ${moduleFiles.length} files in ${baseDir}`);
30
+ }
31
+
32
+
33
+ for (const file of moduleFiles) {
34
+ const moduleExt = path.extname(file.name);
35
+ const fileName = path.basename(file.name, moduleExt);
36
+ const moduleFilePath = path.resolve(baseDir, file.name);
37
+
38
+
39
+ const rawImport = await import(`file://${moduleFilePath.replace(/\\/g, "/")}`);
40
+
41
+
42
+ const isCjsFile = moduleExt === ".cjs";
43
+ const rawMod = isCjsFile ? rawImport.default : rawImport;
44
+ rawModuleCache.set(file.name, rawMod);
45
+
46
+
47
+ const hasRealDefault = rawMod && "default" in rawMod;
48
+ if (hasRealDefault) {
49
+ totalDefaultExports++;
50
+
51
+
52
+ const isSelfReferential = multidefault_isSelfReferential(rawMod);
53
+
54
+ if (debug) {
55
+ console.log(`[DEBUG] multidefault_analyzeModules: Checking ${file.name}`);
56
+ console.log(`[DEBUG] - fileName: ${fileName}`);
57
+ console.log(`[DEBUG] - has default: ${hasRealDefault}`);
58
+ console.log(`[DEBUG] - isSelfReferential: ${isSelfReferential}`);
59
+ }
60
+
61
+ if (!isSelfReferential) {
62
+
63
+ defaultExportFiles.push({ fileName, rawModule: rawMod });
64
+ if (debug) {
65
+ console.log(`[DEBUG] Found default export in ${file.name} (non-self-referential)`);
66
+ }
67
+ } else {
68
+ selfReferentialFiles.add(fileName);
69
+ if (debug) {
70
+ console.log(`[DEBUG] Skipped ${file.name} - self-referential default export`);
71
+ }
72
+ }
73
+ } else if (debug) {
74
+ console.log(`[DEBUG] multidefault_analyzeModules: Checking ${file.name}`);
75
+ console.log(`[DEBUG] - fileName: ${fileName}`);
76
+ console.log(`[DEBUG] - has default: ${hasRealDefault}`);
77
+ if (isCjsFile) {
78
+ console.log(`[DEBUG] - CJS file unwrapped from Node.js wrapper`);
79
+ }
80
+ }
81
+ }
82
+
83
+
84
+ const hasMultipleDefaultExports = totalDefaultExports > 1;
85
+
86
+ if (debug) {
87
+ console.log(`[DEBUG] multidefault_analyzeModules results:`);
88
+ console.log(`[DEBUG] - selfReferentialFiles:`, Array.from(selfReferentialFiles));
89
+ console.log(`[DEBUG] - totalDefaultExports:`, totalDefaultExports);
90
+ console.log(`[DEBUG] - hasMultipleDefaultExports:`, hasMultipleDefaultExports);
91
+ console.log(`[DEBUG] - defaultExportFiles count:`, defaultExportFiles.length);
92
+ }
93
+
94
+ return {
95
+ totalDefaultExports,
96
+ hasMultipleDefaultExports,
97
+ selfReferentialFiles,
98
+ rawModuleCache,
99
+ defaultExportFiles
100
+ };
101
+ }
102
+
103
+
104
+ function multidefault_isSelfReferential(rawModule) {
105
+ if (!rawModule || !("default" in rawModule)) {
106
+ return false;
107
+ }
108
+
109
+
110
+ return Object.entries(rawModule).some(([key, value]) => key !== "default" && value === rawModule.default);
111
+ }
112
+
113
+
114
+ function multidefault_getFlatteningDecision(options) {
115
+ const {
116
+ hasMultipleDefaultExports,
117
+ moduleHasDefault,
118
+ isSelfReferential,
119
+ moduleKeys,
120
+ apiPathKey,
121
+ totalModuleCount,
122
+ debug = false
123
+ } = options;
124
+
125
+ if (debug) {
126
+ console.log(`[DEBUG] multidefault_getFlatteningDecision: Analyzing flattening for ${apiPathKey}`);
127
+ console.log(`[DEBUG] - hasMultipleDefaultExports: ${hasMultipleDefaultExports}`);
128
+ console.log(`[DEBUG] - moduleHasDefault: ${moduleHasDefault}`);
129
+ console.log(`[DEBUG] - isSelfReferential: ${isSelfReferential}`);
130
+ console.log(`[DEBUG] - moduleKeys: [${moduleKeys.join(", ")}]`);
131
+ console.log(`[DEBUG] - totalModuleCount: ${totalModuleCount}`);
132
+ }
133
+
134
+
135
+ if (isSelfReferential) {
136
+ return {
137
+ shouldFlatten: false,
138
+ flattenToRoot: false,
139
+ preserveAsNamespace: true,
140
+ reason: "self-referential default export"
141
+ };
142
+ }
143
+
144
+
145
+ if (hasMultipleDefaultExports) {
146
+ if (moduleHasDefault) {
147
+
148
+ return {
149
+ shouldFlatten: false,
150
+ flattenToRoot: false,
151
+ preserveAsNamespace: true,
152
+ reason: "multi-default context with default export"
153
+ };
154
+ } else {
155
+
156
+ return {
157
+ shouldFlatten: true,
158
+ flattenToRoot: true,
159
+ preserveAsNamespace: false,
160
+ reason: "multi-default context without default export"
161
+ };
162
+ }
163
+ }
164
+
165
+
166
+
167
+ if (moduleKeys.length === 1 && moduleKeys[0] === apiPathKey) {
168
+ return {
169
+ shouldFlatten: true,
170
+ flattenToRoot: false,
171
+ preserveAsNamespace: false,
172
+ reason: "single named export matching filename"
173
+ };
174
+ }
175
+
176
+
177
+
178
+
179
+
180
+
181
+
182
+
183
+
184
+
185
+
186
+
187
+
188
+
189
+ return {
190
+ shouldFlatten: false,
191
+ flattenToRoot: false,
192
+ preserveAsNamespace: true,
193
+ reason: "default namespace preservation"
194
+ };
195
+ }
196
+
197
+ export { multidefault_analyzeModules, multidefault_isSelfReferential, multidefault_getFlatteningDecision };
@@ -27,128 +27,76 @@ import path from "node:path";
27
27
 
28
28
 
29
29
 
30
-
31
- export async function create(dir, rootLevel = true, maxDepth = Infinity, currentDepth = 0) {
30
+ export async function create(dir, maxDepth = Infinity, currentDepth = 0) {
32
31
 
32
+ const { processModuleForAPI } = await import("@cldmv/slothlet/helpers/api_builder");
33
33
  const entries = await fs.readdir(dir, { withFileTypes: true });
34
34
  const api = {};
35
-
36
- const rootNamedExports = {};
37
-
38
35
  let rootDefaultFunction = null;
39
36
 
40
- if (rootLevel) {
41
-
42
- const moduleFiles = entries.filter((e) => this._shouldIncludeFile(e));
43
- const defaultExportFiles = [];
44
-
45
-
46
- for (const entry of moduleFiles) {
47
- const ext = path.extname(entry.name);
48
- const fileName = path.basename(entry.name, ext);
49
- const mod = await this._loadSingleModule(path.join(dir, entry.name), true);
37
+
38
+ const moduleFiles = entries.filter((e) => this._shouldIncludeFile(e));
39
+ const defaultExportFiles = [];
40
+
41
+ const { multidefault_analyzeModules } = await import("@cldmv/slothlet/helpers/multidefault");
42
+ const analysis = await multidefault_analyzeModules(moduleFiles, dir, this.config.debug);
50
43
 
51
- if (this.config.debug) {
52
- console.log(`[DEBUG] First pass - ${fileName}: hasDefault=${mod && "default" in mod}`);
53
- }
44
+ const { totalDefaultExports, hasMultipleDefaultExports, selfReferentialFiles, defaultExportFiles: analysisDefaults } = analysis;
54
45
 
55
- if (mod && "default" in mod) {
56
- defaultExportFiles.push({ entry, fileName, mod });
57
- if (this.config.debug) {
58
- console.log(`[DEBUG] Added ${fileName} to defaultExportFiles`);
59
- }
60
- }
46
+
47
+ defaultExportFiles.length = 0;
48
+ for (const { fileName } of analysisDefaults) {
49
+ const entry = moduleFiles.find((f) => path.basename(f.name, path.extname(f.name)) === fileName);
50
+ if (entry) {
51
+ const mod = await this._loadSingleModule(path.join(dir, entry.name));
52
+ defaultExportFiles.push({ entry, fileName, mod });
61
53
  }
62
- const hasMultipleDefaultExports = defaultExportFiles.length > 1;
54
+ }
63
55
 
64
- if (this.config.debug) {
65
- console.log(
66
- `[DEBUG] Detection result: ${defaultExportFiles.length} default exports found, hasMultipleDefaultExports=${hasMultipleDefaultExports}`
67
- );
68
- console.log(
69
- `[DEBUG] Default export files:`,
70
- defaultExportFiles.map((f) => f.fileName)
71
- );
72
- }
56
+ if (this.config.debug) {
57
+ console.log(`[DEBUG] Eager mode: Using shared multidefault utility results`);
58
+ console.log(
59
+ `[DEBUG] Detection result: ${totalDefaultExports} total defaults (${defaultExportFiles.length} non-self-referential + ${selfReferentialFiles.size} self-referential), hasMultipleDefaultExports=${hasMultipleDefaultExports}`
60
+ );
61
+ console.log(
62
+ `[DEBUG] Default export files:`,
63
+ defaultExportFiles.map((f) => f.fileName)
64
+ );
65
+ }
66
+
67
+
68
+ for (const entry of moduleFiles) {
69
+ const ext = path.extname(entry.name);
70
+ const fileName = path.basename(entry.name, ext);
71
+ const apiPathKey = this._toapiPathKey(fileName);
72
+ const mod = await this._loadSingleModule(path.join(dir, entry.name));
73
73
 
74
74
 
75
- for (const entry of moduleFiles) {
76
- const ext = path.extname(entry.name);
77
- const fileName = path.basename(entry.name, ext);
78
- const apiKey = this._toApiKey(fileName);
79
- const mod = await this._loadSingleModule(path.join(dir, entry.name), true);
80
-
81
- if (mod && typeof mod.default === "function") {
82
- if (hasMultipleDefaultExports) {
83
-
84
- api[apiKey] = mod.default;
85
-
86
-
87
- for (const [key, value] of Object.entries(mod)) {
88
- if (key !== "default") {
89
- api[apiKey][key] = value;
90
- }
91
- }
92
-
93
- if (this.config.debug) {
94
- console.log(`[DEBUG] Multi-default in eager mode: using filename '${apiKey}' for default export`);
95
- }
96
- } else {
97
-
98
-
99
- if (this.config.debug) {
100
- console.log(
101
- `[DEBUG] Processing traditional default: hasMultipleDefaultExports=${hasMultipleDefaultExports}, rootDefaultFunction=${!!rootDefaultFunction}`
102
- );
103
- }
104
- if (!hasMultipleDefaultExports && !rootDefaultFunction) {
105
- rootDefaultFunction = mod.default;
106
- if (this.config.debug) {
107
- console.log(`[DEBUG] Set rootDefaultFunction to:`, mod.default.name);
108
- }
109
- } else {
110
- if (this.config.debug) {
111
- console.log(`[DEBUG] Skipped setting rootDefaultFunction due to multi-default scenario`);
112
- }
113
- }
114
- for (const [key, value] of Object.entries(mod)) {
115
- if (key !== "default") api[key] = value;
116
- }
117
- }
118
- } else {
119
-
120
-
121
- if (this.config.debug) {
122
- console.log(`[DEBUG] Processing non-default exports for ${fileName}`);
123
- }
124
-
125
- if (hasMultipleDefaultExports) {
126
-
127
- if (this.config.debug) {
128
- console.log(`[DEBUG] Multi-default context: flattening ${fileName} exports to root`);
129
- }
130
- for (const [key, value] of Object.entries(mod)) {
131
- api[key] = value;
132
- rootNamedExports[key] = value;
133
- }
134
- } else {
135
-
136
- if (this.config.debug) {
137
- console.log(`[DEBUG] Traditional context: preserving ${fileName} as namespace`);
138
- }
139
- api[apiKey] = mod;
140
- for (const [key, value] of Object.entries(mod)) {
141
- rootNamedExports[key] = value;
142
- }
143
- }
75
+ const isSelfReferential = selfReferentialFiles.has(fileName);
76
+
77
+ processModuleForAPI({
78
+ mod,
79
+ fileName,
80
+ apiPathKey,
81
+ hasMultipleDefaultExports,
82
+ isSelfReferential,
83
+ api,
84
+ getRootDefault: () => rootDefaultFunction,
85
+ setRootDefault: (fn) => {
86
+ rootDefaultFunction = fn;
87
+ },
88
+ context: {
89
+ debug: this.config.debug,
90
+ mode: "root",
91
+ totalModules: moduleFiles.length
144
92
  }
145
- }
93
+ });
146
94
  }
147
95
 
148
96
  for (const entry of entries) {
149
97
  if (entry.isDirectory() && !entry.name.startsWith(".") && currentDepth < maxDepth) {
150
98
  const categoryPath = path.join(dir, entry.name);
151
- api[this._toApiKey(entry.name)] = await this._loadCategory(categoryPath, currentDepth + 1, maxDepth);
99
+ api[this._toapiPathKey(entry.name)] = await this._loadCategory(categoryPath, currentDepth + 1, maxDepth);
152
100
  }
153
101
  }
154
102
 
@@ -170,9 +118,5 @@ export async function create(dir, rootLevel = true, maxDepth = Infinity, current
170
118
  }
171
119
  }
172
120
 
173
-
174
-
175
-
176
-
177
121
  return finalApi;
178
122
  }
@@ -18,91 +18,86 @@
18
18
 
19
19
 
20
20
  import fs from "node:fs/promises";
21
+ import { readdirSync } from "node:fs";
21
22
  import path from "node:path";
22
23
  import { runWithCtx } from "@cldmv/slothlet/runtime";
24
+ import { processModuleForAPI } from "@cldmv/slothlet/helpers/api_builder";
23
25
 
24
26
 
25
- export async function create(dir, rootLevel = true, maxDepth = Infinity, currentDepth = 0) {
27
+ export async function create(dir, maxDepth = Infinity, currentDepth = 0) {
26
28
  const instance = this;
27
29
  const entries = await fs.readdir(dir, { withFileTypes: true });
28
30
  let api = {};
29
31
  let rootDefaultFn = null;
30
32
 
31
33
 
32
- if (rootLevel) {
33
-
34
- const moduleFiles = entries.filter((e) => instance._shouldIncludeFile(e));
35
- const defaultExportFiles = [];
34
+
35
+ const moduleFiles = entries.filter((e) => instance._shouldIncludeFile(e));
36
+ const defaultExportFiles = [];
36
37
 
37
-
38
- for (const entry of moduleFiles) {
39
- const ext = path.extname(entry.name);
40
- const fileName = path.basename(entry.name, ext);
41
- const mod = await instance._loadSingleModule(path.join(dir, entry.name), true);
38
+
39
+ const { multidefault_analyzeModules } = await import("@cldmv/slothlet/helpers/multidefault");
40
+ const analysis = await multidefault_analyzeModules(moduleFiles, dir, instance.config.debug);
42
41
 
43
- if (mod && "default" in mod) {
44
- defaultExportFiles.push({ entry, fileName, mod });
45
- }
42
+ const { totalDefaultExports, hasMultipleDefaultExports, selfReferentialFiles, defaultExportFiles: analysisDefaults } = analysis;
43
+
44
+
45
+ defaultExportFiles.length = 0;
46
+ for (const { fileName } of analysisDefaults) {
47
+ const entry = moduleFiles.find((f) => path.basename(f.name, path.extname(f.name)) === fileName);
48
+ if (entry) {
49
+ const mod = await instance._loadSingleModule(path.join(dir, entry.name));
50
+ defaultExportFiles.push({ entry, fileName, mod });
46
51
  }
52
+ }
47
53
 
48
- const hasMultipleDefaultExports = defaultExportFiles.length > 1;
54
+ if (instance.config.debug) {
55
+ console.log(`[DEBUG] Lazy mode: Using shared multidefault utility results`);
56
+ console.log(`[DEBUG] - totalDefaultExports: ${totalDefaultExports}`);
57
+ console.log(`[DEBUG] - hasMultipleDefaultExports: ${hasMultipleDefaultExports}`);
58
+ console.log(`[DEBUG] - selfReferentialFiles: ${Array.from(selfReferentialFiles)}`);
59
+ }
49
60
 
50
-
51
- for (const entry of moduleFiles) {
52
- const ext = path.extname(entry.name);
53
- const fileName = path.basename(entry.name, ext);
54
- const apiKey = instance._toApiKey(fileName);
55
- const mod = await instance._loadSingleModule(path.join(dir, entry.name), true);
56
-
57
- if (mod && typeof mod.default === "function") {
58
- if (hasMultipleDefaultExports) {
59
-
60
- api[apiKey] = mod.default;
61
+
62
+ const processedModuleCache = new Map();
61
63
 
62
-
63
- for (const [key, value] of Object.entries(mod)) {
64
- if (key !== "default") {
65
- api[apiKey][key] = value;
66
- }
67
- }
64
+ for (const entry of moduleFiles) {
65
+ const ext = path.extname(entry.name);
66
+ const fileName = path.basename(entry.name, ext);
67
+ const apiPathKey = instance._toapiPathKey(fileName);
68
68
 
69
- if (instance.config.debug) {
70
- console.log(`[DEBUG] Multi-default in lazy mode: using filename '${apiKey}' for default export`);
71
- }
72
- } else {
73
-
74
-
75
- if (!hasMultipleDefaultExports && !rootDefaultFn) {
76
- rootDefaultFn = mod.default;
77
- }
78
- for (const [k, v] of Object.entries(mod)) {
79
- if (k !== "default") api[k] = v;
80
- }
81
- }
82
- } else {
83
-
84
-
85
- if (instance.config.debug) {
86
- console.log(`[DEBUG] Processing non-default exports for ${fileName}`);
87
- }
69
+
70
+ let mod = null;
71
+ const existingDefault = defaultExportFiles.find((def) => def.fileName === fileName);
72
+ if (existingDefault) {
73
+ mod = existingDefault.mod;
74
+ } else {
75
+
76
+ mod = await instance._loadSingleModule(path.join(dir, entry.name));
77
+ processedModuleCache.set(entry.name, mod);
78
+ }
88
79
 
89
- if (hasMultipleDefaultExports) {
90
-
91
- if (instance.config.debug) {
92
- console.log(`[DEBUG] Multi-default context: flattening ${fileName} exports to root`);
93
- }
94
- for (const [k, v] of Object.entries(mod)) {
95
- api[k] = v;
96
- }
97
- } else {
98
-
99
- if (instance.config.debug) {
100
- console.log(`[DEBUG] Traditional context: preserving ${fileName} as namespace`);
101
- }
102
- api[apiKey] = mod;
103
- }
80
+
81
+ const isSelfReferential = selfReferentialFiles.has(fileName);
82
+
83
+
84
+ processModuleForAPI({
85
+ mod,
86
+ fileName,
87
+ apiPathKey,
88
+ hasMultipleDefaultExports,
89
+ isSelfReferential,
90
+ api,
91
+ getRootDefault: () => rootDefaultFn,
92
+ setRootDefault: (fn) => {
93
+ rootDefaultFn = fn;
94
+ },
95
+ context: {
96
+ debug: instance.config.debug,
97
+ mode: "root",
98
+ totalModules: moduleFiles.length
104
99
  }
105
- }
100
+ });
106
101
  }
107
102
 
108
103
 
@@ -114,10 +109,37 @@ export async function create(dir, rootLevel = true, maxDepth = Infinity, current
114
109
 
115
110
  for (const entry of entries) {
116
111
  if (entry.isDirectory() && !entry.name.startsWith(".") && currentDepth < maxDepth) {
117
- const key = instance._toApiKey(entry.name);
112
+ const key = instance._toapiPathKey(entry.name);
118
113
  const subDirPath = path.join(dir, entry.name);
119
114
  const parent = api;
120
115
  const depth = 1;
116
+
117
+
118
+ try {
119
+ const subEntries = readdirSync(subDirPath, { withFileTypes: true });
120
+ const hasFiles = subEntries.some(
121
+ (subEntry) =>
122
+ subEntry.isFile() &&
123
+ !subEntry.name.startsWith(".") &&
124
+ (subEntry.name.endsWith(".mjs") || subEntry.name.endsWith(".cjs") || subEntry.name.endsWith(".js"))
125
+ );
126
+ const hasSubdirs = subEntries.some((subEntry) => subEntry.isDirectory() && !subEntry.name.startsWith("."));
127
+
128
+
129
+ if (!hasFiles && !hasSubdirs) {
130
+ if (instance?.config?.debug) {
131
+ console.log(`[lazy][debug] empty folder detected during traversal: ${subDirPath} -> adding {}`);
132
+ }
133
+ parent[key] = {};
134
+ continue;
135
+ }
136
+ } catch (error) {
137
+
138
+ if (instance?.config?.debug) {
139
+ console.log(`[lazy][debug] error reading directory ${subDirPath}: ${error.message}, creating lazy proxy`);
140
+ }
141
+ }
142
+
121
143
  const proxy = createFolderProxy({
122
144
  subDirPath,
123
145
  key,