@ultrst-armada/krnl 1.0.1 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1146 @@
1
+ // ../validate/dist/index.js
2
+ import * as fs2 from "fs";
3
+ import * as path4 from "path";
4
+ import { Project } from "ts-morph";
5
+ import * as path from "path";
6
+ import { SyntaxKind } from "ts-morph";
7
+ import * as path2 from "path";
8
+ import { SyntaxKind as SyntaxKind2, Node } from "ts-morph";
9
+ import * as fs from "fs";
10
+ import * as path3 from "path";
11
+ import { SyntaxKind as SyntaxKind3 } from "ts-morph";
12
+ function checkFileLimits(sf, options) {
13
+ const errors = [];
14
+ const warnings = [];
15
+ const filePath = sf.getFilePath();
16
+ const sourceText = sf.getText();
17
+ const lines = sourceText.split("\n");
18
+ if (lines.length > options.maxFileLineLimit) {
19
+ errors.push({
20
+ ruleId: "krnl/file-line-limit",
21
+ filePath,
22
+ message: `File exceeds maximum length of ${options.maxFileLineLimit} lines (currently ${lines.length} lines). Decompose into sub-components, custom hooks, quad-units, or concept libraries.`,
23
+ severity: "error"
24
+ });
25
+ }
26
+ for (const decl of sf.getImportDeclarations()) {
27
+ const moduleSpec = decl.getModuleSpecifierValue();
28
+ if (moduleSpec.startsWith(".") && !moduleSpec.endsWith(".js") && !moduleSpec.endsWith(".json") && !moduleSpec.endsWith(".css") && !moduleSpec.endsWith(".svg") && !moduleSpec.endsWith(".png")) {
29
+ errors.push({
30
+ ruleId: "krnl/import-suffix",
31
+ filePath,
32
+ line: decl.getStartLineNumber(),
33
+ message: `Relative import '${moduleSpec}' must end with '.js' for NodeNext module resolution.`,
34
+ severity: "error"
35
+ });
36
+ }
37
+ }
38
+ const isHelper = filePath.includes("helper_functions") || filePath.includes("/helpers/") || filePath.includes("\\helpers\\");
39
+ if (isHelper) {
40
+ for (const fn of sf.getFunctions()) {
41
+ const fnLines = fn.getText().split("\n").length;
42
+ if (fnLines > options.maxHelperLineLimit && !sourceText.includes("Concepts.")) {
43
+ errors.push({
44
+ ruleId: "krnl/helper-line-limit",
45
+ filePath,
46
+ line: fn.getStartLineNumber(),
47
+ message: `Helper function '${fn.getName() || "anonymous"}' exceeds ${options.maxHelperLineLimit} lines (${fnLines} lines). Must delegate to a root libraries/{Domain}Concepts.ts library.`,
48
+ severity: "error"
49
+ });
50
+ }
51
+ }
52
+ }
53
+ const isMainLogic = filePath.endsWith("logic.ts") || filePath.endsWith("logic.js");
54
+ if (isMainLogic) {
55
+ const substantiveLines = lines.filter((l) => {
56
+ const trimmed = l.trim();
57
+ return trimmed.length > 0 && !trimmed.startsWith("//") && !trimmed.startsWith("/*") && !trimmed.startsWith("*");
58
+ });
59
+ if (substantiveLines.length > options.maxMainLogicLimit && !sourceText.includes("helpers") && !sourceText.includes("Concepts") && !sourceText.includes("state")) {
60
+ errors.push({
61
+ ruleId: "krnl/main-delegation",
62
+ filePath,
63
+ message: `Main logic function has ${substantiveLines.length} substantive lines without delegating to Layer 1 helper functions or Layer 0 libraries.`,
64
+ severity: "error"
65
+ });
66
+ }
67
+ }
68
+ return { errors, warnings };
69
+ }
70
+ function checkComponentRules(sf) {
71
+ const errors = [];
72
+ const warnings = [];
73
+ const filePath = sf.getFilePath();
74
+ const baseName = path.basename(filePath);
75
+ if (filePath.endsWith(".tsx") || filePath.endsWith(".jsx")) {
76
+ const componentNames = [];
77
+ for (const fn of sf.getFunctions()) {
78
+ const name = fn.getName();
79
+ if (name && /^[A-Z]/.test(name)) {
80
+ const hasJsx = fn.getDescendantsOfKind(SyntaxKind.JsxElement).length > 0 || fn.getDescendantsOfKind(SyntaxKind.JsxSelfClosingElement).length > 0 || fn.getDescendantsOfKind(SyntaxKind.JsxFragment).length > 0;
81
+ if (hasJsx) componentNames.push(name);
82
+ }
83
+ }
84
+ for (const stmt of sf.getVariableStatements()) {
85
+ for (const decl of stmt.getDeclarations()) {
86
+ const name = decl.getName();
87
+ if (/^[A-Z]/.test(name)) {
88
+ const typeText = decl.getTypeNode()?.getText() || "";
89
+ const isFcType = typeText.includes("FC") || typeText.includes("FunctionComponent") || typeText.includes("ComponentType");
90
+ const init = decl.getInitializer();
91
+ if (init) {
92
+ const hasJsx = init.getDescendantsOfKind(SyntaxKind.JsxElement).length > 0 || init.getDescendantsOfKind(SyntaxKind.JsxSelfClosingElement).length > 0 || init.getDescendantsOfKind(SyntaxKind.JsxFragment).length > 0;
93
+ if (isFcType || hasJsx) {
94
+ if (!componentNames.includes(name)) componentNames.push(name);
95
+ }
96
+ }
97
+ }
98
+ }
99
+ }
100
+ for (const cls of sf.getClasses()) {
101
+ const name = cls.getName();
102
+ const ext = cls.getExtends()?.getText() || "";
103
+ if (name && (ext.includes("Component") || ext.includes("PureComponent"))) {
104
+ if (!componentNames.includes(name)) componentNames.push(name);
105
+ }
106
+ }
107
+ if (componentNames.length > 1) {
108
+ errors.push({
109
+ ruleId: "krnl/one-component-per-file",
110
+ filePath,
111
+ message: `File '${baseName}' defines multiple React components (${componentNames.join(
112
+ ", "
113
+ )}). Krnl strictly enforces ONE component per file. Decompose into sub-component files.`,
114
+ severity: "error"
115
+ });
116
+ }
117
+ }
118
+ const isHelper = filePath.includes("helper_functions") || filePath.includes("/helpers/") || filePath.includes("\\helpers\\");
119
+ if (isHelper) {
120
+ for (const decl of sf.getImportDeclarations()) {
121
+ const spec = decl.getModuleSpecifierValue();
122
+ if (["fs", "node:fs", "http", "node:http", "ws"].includes(spec)) {
123
+ errors.push({
124
+ ruleId: "krnl/helper-purity",
125
+ filePath,
126
+ line: decl.getStartLineNumber(),
127
+ message: `Helper functions (Layer 1) cannot directly import I/O modules ('${spec}'). Delegate to Layer 0 libraries or Entity context.`,
128
+ severity: "error"
129
+ });
130
+ }
131
+ }
132
+ }
133
+ return { errors, warnings };
134
+ }
135
+ function checkEntityRules(sf) {
136
+ const errors = [];
137
+ const warnings = [];
138
+ const filePath = sf.getFilePath();
139
+ const sourceText = sf.getText();
140
+ const baseName = path2.basename(filePath);
141
+ const calls = sf.getDescendantsOfKind(SyntaxKind2.CallExpression);
142
+ for (const call of calls) {
143
+ const exprText = call.getExpression().getText();
144
+ if (exprText === "setInterval" || exprText === "window.setInterval") {
145
+ errors.push({
146
+ ruleId: "krnl/no-polling",
147
+ filePath,
148
+ line: call.getStartLineNumber(),
149
+ message: `Prohibited use of 'setInterval'. Krnl applications must use reactive event streams (entity.emitEvent / entity.on).`,
150
+ severity: "error"
151
+ });
152
+ }
153
+ }
154
+ if (sourceText.includes("main = async") || sourceText.includes("export const main = async")) {
155
+ const match = sourceText.match(/main\s*=\s*async\s*\([^,]+,\s*\{([^}]*)\}\s*\)/);
156
+ if (match) {
157
+ const destructured = match[1];
158
+ if (/\bsystem\b/.test(destructured) && !/\bentity\b/.test(destructured)) {
159
+ errors.push({
160
+ ruleId: "krnl/context-destructuring",
161
+ filePath,
162
+ message: `Functionality context parameter destructures 'system'. Functionality passes { state, entity }. Always destructure 'entity'.`,
163
+ severity: "error"
164
+ });
165
+ }
166
+ }
167
+ }
168
+ const isEntityClass = sf.getClasses().some((c) => {
169
+ const ext = c.getExtends();
170
+ return ext && (ext.getText().includes("Entity") || ext.getText().includes("krnlEntityBase"));
171
+ });
172
+ if (isEntityClass) {
173
+ for (const decl of sf.getImportDeclarations()) {
174
+ const spec = decl.getModuleSpecifierValue();
175
+ if (spec.includes("libraries/") || spec.includes("Concepts")) {
176
+ errors.push({
177
+ ruleId: "krnl/entity-no-libraries",
178
+ filePath,
179
+ line: decl.getStartLineNumber(),
180
+ message: `Entity class violates Library Calling Invariant. Entities must not call or import libraries directly ('${spec}'). Only functionalities in 'src/functionalities/' are permitted to call shared libraries.`,
181
+ severity: "error"
182
+ });
183
+ }
184
+ }
185
+ let loadAllLine = -1;
186
+ const addLocalLines = [];
187
+ for (const call of calls) {
188
+ const txt = call.getText();
189
+ if (txt.includes("MagneticLoader.loadAll") || txt.includes("KrnlMagneticLoader.loadAll")) {
190
+ loadAllLine = call.getStartLineNumber();
191
+ } else if (txt.startsWith("this.addLocal(")) {
192
+ const hasUiSpec = txt.includes("uiSpec");
193
+ const idMatch = txt.match(/id\s*:\s*["']([^"']+)["']/);
194
+ addLocalLines.push({
195
+ line: call.getStartLineNumber(),
196
+ hasUiSpec,
197
+ id: idMatch ? idMatch[1] : "unknown"
198
+ });
199
+ }
200
+ }
201
+ if (loadAllLine !== -1) {
202
+ for (const al of addLocalLines) {
203
+ if (al.hasUiSpec && al.line > loadAllLine) {
204
+ errors.push({
205
+ ruleId: "krnl/boot-order",
206
+ filePath,
207
+ line: al.line,
208
+ message: `addLocal('${al.id}') with uiSpec at line ${al.line} appears AFTER loadAll() at line ${loadAllLine}. All addLocal() with UI must precede loadAll().`,
209
+ severity: "error"
210
+ });
211
+ }
212
+ }
213
+ }
214
+ for (const cls of sf.getClasses()) {
215
+ const ext = cls.getExtends();
216
+ if (ext && (ext.getText().includes("Entity") || ext.getText().includes("krnlEntityBase"))) {
217
+ const loops = [
218
+ ...cls.getDescendantsOfKind(SyntaxKind2.ForStatement),
219
+ ...cls.getDescendantsOfKind(SyntaxKind2.ForOfStatement),
220
+ ...cls.getDescendantsOfKind(SyntaxKind2.ForInStatement),
221
+ ...cls.getDescendantsOfKind(SyntaxKind2.WhileStatement),
222
+ ...cls.getDescendantsOfKind(SyntaxKind2.DoStatement)
223
+ ];
224
+ for (const loop of loops) {
225
+ errors.push({
226
+ ruleId: "krnl/entity-purity",
227
+ filePath,
228
+ line: loop.getStartLineNumber(),
229
+ message: `Entity '${cls.getName() || "Anonymous"}' violates Entity Purity Law. Loops and procedural algorithms are prohibited inside entities. Move logic to a functionality or a global library function.`,
230
+ severity: "error"
231
+ });
232
+ }
233
+ for (const method of cls.getMethods()) {
234
+ const methodName = method.getName();
235
+ if (!["boot", "init", "dispose"].includes(methodName)) {
236
+ errors.push({
237
+ ruleId: "krnl/entity-purity",
238
+ filePath,
239
+ line: method.getStartLineNumber(),
240
+ message: `Entity '${cls.getName() || "Anonymous"}' defines custom method '${methodName}'. Entities are purely declarative compositors/orchestrators. Define capabilities as functionalities or global library functions.`,
241
+ severity: "error"
242
+ });
243
+ }
244
+ }
245
+ }
246
+ }
247
+ for (const call of calls) {
248
+ const callText = call.getText();
249
+ if (callText.startsWith("this.orchestration(") || callText.startsWith("this.flow(")) {
250
+ let currentExpr = call;
251
+ const chainCalls = [];
252
+ while (currentExpr && Node.isCallExpression(currentExpr)) {
253
+ const propAccess = currentExpr.getExpression();
254
+ if (Node.isPropertyAccessExpression(propAccess)) {
255
+ const methodName = propAccess.getName();
256
+ const args = currentExpr.getArguments();
257
+ const argText = args.length > 0 ? args[0].getText() : void 0;
258
+ chainCalls.unshift({ name: methodName, node: currentExpr, argText });
259
+ currentExpr = propAccess.getExpression();
260
+ } else {
261
+ break;
262
+ }
263
+ }
264
+ let chainId = "orchestration";
265
+ for (const step of chainCalls) {
266
+ if (step.name === "orchestration" || step.name === "flow") {
267
+ chainId = step.argText ? step.argText.replace(/['"]/g, "") : "orchestration";
268
+ } else if (step.name === "thenFunction") {
269
+ errors.push({
270
+ ruleId: "krnl/entity-no-direct-library-calls",
271
+ filePath,
272
+ line: step.node.getStartLineNumber(),
273
+ message: `Orchestration chain '${chainId}' violates Entity Purity Law. Entities cannot chain direct library functions via thenFunction(). Entities must only orchestrate functionalities (thenFunctionality) and orchestrations from other entities (thenEntityOrchestration).`,
274
+ severity: "error"
275
+ });
276
+ }
277
+ }
278
+ }
279
+ }
280
+ }
281
+ return { errors, warnings };
282
+ }
283
+ function checkTopLevelPurity(sf) {
284
+ const errors = [];
285
+ const warnings = [];
286
+ const filePath = sf.getFilePath();
287
+ const baseName = path3.basename(filePath);
288
+ const isUiTopLevel = /^(App|main|index|_app|root)\.(tsx|jsx)$/i.test(baseName);
289
+ const isBackendTopLevel = /^(server|app)\.(ts|js)$/i.test(baseName) && !filePath.includes("/components/") && !filePath.includes("/entities/") && !filePath.includes("/libraries/");
290
+ if (isUiTopLevel) {
291
+ const jsxElements = sf.getDescendantsOfKind(SyntaxKind3.JsxOpeningElement);
292
+ const jsxSelfClosing = sf.getDescendantsOfKind(SyntaxKind3.JsxSelfClosingElement);
293
+ const allJsxTags = [...jsxElements, ...jsxSelfClosing];
294
+ for (const jsx of allJsxTags) {
295
+ const tagName = jsx.getTagNameNode().getText();
296
+ if (/^[a-z]/.test(tagName)) {
297
+ errors.push({
298
+ ruleId: "krnl/top-level-purity",
299
+ filePath,
300
+ line: jsx.getStartLineNumber(),
301
+ message: `Top-level file '${baseName}' violates Top-Level Purity Law. Raw JSX/HTML element '<${tagName}>' is strictly forbidden. Top-level files must ONLY import and compose React components.`,
302
+ severity: "error"
303
+ });
304
+ }
305
+ }
306
+ const calls = sf.getDescendantsOfKind(SyntaxKind3.CallExpression);
307
+ for (const call of calls) {
308
+ const exprText = call.getExpression().getText();
309
+ if ([
310
+ "useState",
311
+ "useEffect",
312
+ "useRef",
313
+ "useMemo",
314
+ "useCallback",
315
+ "useReducer",
316
+ "useContext",
317
+ "useLayoutEffect"
318
+ ].includes(exprText) || /^use[A-Z]/.test(exprText) && exprText !== "use") {
319
+ errors.push({
320
+ ruleId: "krnl/top-level-purity",
321
+ filePath,
322
+ line: call.getStartLineNumber(),
323
+ message: `Top-level file '${baseName}' violates Top-Level Purity Law. React hook '${exprText}' is forbidden in top-level files. Encapsulate state and effects inside dedicated component files.`,
324
+ severity: "error"
325
+ });
326
+ }
327
+ }
328
+ }
329
+ if (isBackendTopLevel) {
330
+ const calls = sf.getDescendantsOfKind(SyntaxKind3.CallExpression);
331
+ for (const call of calls) {
332
+ const exprText = call.getExpression().getText();
333
+ if (/^(app|router|server)\.(get|post|put|delete|patch|options|head)$/.test(exprText)) {
334
+ errors.push({
335
+ ruleId: "krnl/top-level-purity",
336
+ filePath,
337
+ line: call.getStartLineNumber(),
338
+ message: `Backend entry file '${baseName}' violates Entry Purity Law. Inline route definition '${exprText}' is forbidden. Delegate to dedicated route/controller modules.`,
339
+ severity: "error"
340
+ });
341
+ }
342
+ }
343
+ }
344
+ return { errors, warnings };
345
+ }
346
+ function checkWorkspaceLayout(projectRoot, errors) {
347
+ const krnlDir = path3.join(projectRoot, "krnl");
348
+ const srcDir = path3.join(projectRoot, "src");
349
+ const targetDir = fs.existsSync(krnlDir) ? krnlDir : fs.existsSync(srcDir) ? srcDir : null;
350
+ if (!targetDir) return;
351
+ const backendDir = path3.join(targetDir, "backend");
352
+ const frontendDir = path3.join(targetDir, "frontend");
353
+ if (fs.existsSync(backendDir)) {
354
+ const bLibs = path3.join(backendDir, "libraries");
355
+ if (fs.existsSync(bLibs)) {
356
+ for (const entry of fs.readdirSync(bLibs, { withFileTypes: true })) {
357
+ if (!entry.isDirectory()) continue;
358
+ const libPath = path3.join(bLibs, entry.name);
359
+ if (!fs.existsSync(path3.join(libPath, "manifest.json"))) {
360
+ errors.push({
361
+ ruleId: "krnl/concept-manifest-required",
362
+ filePath: libPath,
363
+ message: `Backend concept library "${entry.name}" is missing a manifest.json file.`,
364
+ severity: "error"
365
+ });
366
+ }
367
+ }
368
+ }
369
+ const bFuncs = path3.join(backendDir, "functionalities");
370
+ if (fs.existsSync(bFuncs)) {
371
+ for (const entry of fs.readdirSync(bFuncs, { withFileTypes: true })) {
372
+ if (!entry.isDirectory()) continue;
373
+ const funcPath = path3.join(bFuncs, entry.name);
374
+ if (!fs.existsSync(path3.join(funcPath, "manifest.json"))) {
375
+ errors.push({
376
+ ruleId: "krnl/functionality-manifest-required",
377
+ filePath: funcPath,
378
+ message: `Backend functionality "${entry.name}" is missing a manifest.json file.`,
379
+ severity: "error"
380
+ });
381
+ }
382
+ }
383
+ }
384
+ }
385
+ if (fs.existsSync(frontendDir)) {
386
+ const fLibs = path3.join(frontendDir, "libraries");
387
+ if (fs.existsSync(fLibs)) {
388
+ for (const entry of fs.readdirSync(fLibs, { withFileTypes: true })) {
389
+ if (!entry.isDirectory()) continue;
390
+ const libPath = path3.join(fLibs, entry.name);
391
+ if (!fs.existsSync(path3.join(libPath, "manifest.json"))) {
392
+ errors.push({
393
+ ruleId: "krnl/frontend-concept-manifest-required",
394
+ filePath: libPath,
395
+ message: `Frontend concept library "${entry.name}" is missing a manifest.json file.`,
396
+ severity: "error"
397
+ });
398
+ }
399
+ }
400
+ }
401
+ const fFuncs = path3.join(frontendDir, "functionalities");
402
+ if (fs.existsSync(fFuncs)) {
403
+ for (const entry of fs.readdirSync(fFuncs, { withFileTypes: true })) {
404
+ if (!entry.isDirectory()) continue;
405
+ const funcPath = path3.join(fFuncs, entry.name);
406
+ if (!fs.existsSync(path3.join(funcPath, "manifest.json"))) {
407
+ errors.push({
408
+ ruleId: "krnl/frontend-functionality-manifest-required",
409
+ filePath: funcPath,
410
+ message: `Frontend functionality "${entry.name}" is missing a manifest.json file.`,
411
+ severity: "error"
412
+ });
413
+ }
414
+ }
415
+ }
416
+ }
417
+ }
418
+ var KrnlValidatorEngine = class {
419
+ project;
420
+ projectRoot;
421
+ limitOptions;
422
+ constructor(optionsOrRoot) {
423
+ const options = typeof optionsOrRoot === "string" ? { projectRoot: optionsOrRoot } : optionsOrRoot;
424
+ this.projectRoot = path4.resolve(options.projectRoot || process.cwd());
425
+ this.limitOptions = {
426
+ maxFileLineLimit: options.maxFileLineLimit ?? 200,
427
+ maxMainLogicLimit: options.maxMainLogicLimit ?? 20,
428
+ maxHelperLineLimit: options.maxHelperLineLimit ?? 30
429
+ };
430
+ const tsConfigPath = path4.join(this.projectRoot, "tsconfig.json");
431
+ if (fs2.existsSync(tsConfigPath)) {
432
+ this.project = new Project({ tsConfigFilePath: tsConfigPath, skipAddingFilesFromTsConfig: true });
433
+ } else {
434
+ this.project = new Project({ compilerOptions: {
435
+ target: 99
436
+ /* ESNext */
437
+ } });
438
+ }
439
+ }
440
+ validateAll() {
441
+ const files = this.collectSourceFiles(this.projectRoot);
442
+ const errors = [];
443
+ const warnings = [];
444
+ checkWorkspaceLayout(this.projectRoot, errors);
445
+ for (const f of files) {
446
+ const sf = this.project.addSourceFileAtPath(f);
447
+ const fileReport = this.validateSourceFile(sf);
448
+ errors.push(...fileReport.errors);
449
+ warnings.push(...fileReport.warnings);
450
+ }
451
+ return {
452
+ valid: errors.length === 0,
453
+ totalFiles: files.length,
454
+ errors,
455
+ warnings
456
+ };
457
+ }
458
+ validateSourceFile(sf) {
459
+ const filePath = sf.getFilePath();
460
+ const baseName = path4.basename(filePath);
461
+ if (baseName.includes("_pb.") || baseName.endsWith(".d.ts")) {
462
+ return { errors: [], warnings: [] };
463
+ }
464
+ const limits = checkFileLimits(sf, this.limitOptions);
465
+ const purity = checkTopLevelPurity(sf);
466
+ const components = checkComponentRules(sf);
467
+ const entity = checkEntityRules(sf);
468
+ return {
469
+ errors: [...limits.errors, ...purity.errors, ...components.errors, ...entity.errors],
470
+ warnings: [...limits.warnings, ...purity.warnings, ...components.warnings, ...entity.warnings]
471
+ };
472
+ }
473
+ collectSourceFiles(dir, collected = []) {
474
+ if (!fs2.existsSync(dir)) return collected;
475
+ const entries = fs2.readdirSync(dir, { withFileTypes: true });
476
+ for (const entry of entries) {
477
+ if (entry.name === "node_modules" || entry.name === "dist" || entry.name === ".git") continue;
478
+ const full = path4.join(dir, entry.name);
479
+ if (entry.isDirectory()) {
480
+ this.collectSourceFiles(full, collected);
481
+ } else if (entry.isFile() && (entry.name.endsWith(".ts") || entry.name.endsWith(".js") || entry.name.endsWith(".tsx") || entry.name.endsWith(".jsx"))) {
482
+ collected.push(full);
483
+ }
484
+ }
485
+ return collected;
486
+ }
487
+ };
488
+
489
+ // src/commands/validate.ts
490
+ async function runValidate(projectRoot = process.cwd()) {
491
+ console.log(`
492
+ \u{1F50D} [Krnl Validate] Scanning project at: ${projectRoot}
493
+ `);
494
+ const validator = new KrnlValidatorEngine({ projectRoot });
495
+ const report = validator.validateAll();
496
+ if (report.warnings.length > 0) {
497
+ console.warn(`\u26A0\uFE0F [WARNINGS] Found ${report.warnings.length} warning(s):`);
498
+ for (const w of report.warnings) {
499
+ console.warn(` - [${w.ruleId}] ${w.filePath}${w.line ? `:${w.line}` : ""}: ${w.message}`);
500
+ }
501
+ }
502
+ if (!report.valid) {
503
+ console.error(`
504
+ \u274C [VALIDATION FAILED] Found ${report.errors.length} error(s):
505
+ `);
506
+ for (const err of report.errors) {
507
+ console.error(` \u274C [${err.ruleId}] ${err.filePath}${err.line ? `:${err.line}` : ""}`);
508
+ console.error(` ${err.message}
509
+ `);
510
+ }
511
+ return false;
512
+ }
513
+ console.log(`\u2705 [VALIDATION PASSED] ${report.totalFiles} source files verified clean against Krnl paradigms.
514
+ `);
515
+ return true;
516
+ }
517
+
518
+ // ../core/dist/index.js
519
+ import * as fs3 from "fs";
520
+ import * as path5 from "path";
521
+ var KrnlPackageReconciler = class {
522
+ /**
523
+ * Scans all manifest.json files across backend and frontend and reconciles root package.json.
524
+ */
525
+ static reconcile(projectRoot = process.cwd(), writeChanges = true) {
526
+ const manifests = this.findManifests(projectRoot);
527
+ const aggregatedDeps = {};
528
+ const aggregatedDevDeps = {};
529
+ for (const mPath of manifests) {
530
+ try {
531
+ const raw = fs3.readFileSync(mPath, "utf8");
532
+ const json = JSON.parse(raw);
533
+ if (json.dependencies && typeof json.dependencies === "object") {
534
+ for (const [pkg, ver] of Object.entries(json.dependencies)) {
535
+ if (!aggregatedDeps[pkg]) aggregatedDeps[pkg] = [];
536
+ if (!aggregatedDeps[pkg].includes(String(ver))) {
537
+ aggregatedDeps[pkg].push(String(ver));
538
+ }
539
+ }
540
+ }
541
+ if (json.devDependencies && typeof json.devDependencies === "object") {
542
+ for (const [pkg, ver] of Object.entries(json.devDependencies)) {
543
+ if (!aggregatedDevDeps[pkg]) aggregatedDevDeps[pkg] = [];
544
+ if (!aggregatedDevDeps[pkg].includes(String(ver))) {
545
+ aggregatedDevDeps[pkg].push(String(ver));
546
+ }
547
+ }
548
+ }
549
+ } catch (err) {
550
+ console.warn(`[KrnlPackageReconciler] Warning: Could not parse ${mPath}:`, err);
551
+ }
552
+ }
553
+ const conflicts = [];
554
+ const resolvedDeps = {};
555
+ const resolvedDevDeps = {};
556
+ for (const [pkg, versions] of Object.entries(aggregatedDeps)) {
557
+ if (versions.length > 1) {
558
+ conflicts.push({ package: pkg, versions });
559
+ }
560
+ resolvedDeps[pkg] = versions[versions.length - 1];
561
+ }
562
+ for (const [pkg, versions] of Object.entries(aggregatedDevDeps)) {
563
+ if (versions.length > 1 && !conflicts.some((c) => c.package === pkg)) {
564
+ conflicts.push({ package: pkg, versions });
565
+ }
566
+ resolvedDevDeps[pkg] = versions[versions.length - 1];
567
+ }
568
+ const pkgJsonPath = path5.join(projectRoot, "package.json");
569
+ let updated = false;
570
+ if (fs3.existsSync(pkgJsonPath)) {
571
+ const pkgContent = JSON.parse(fs3.readFileSync(pkgJsonPath, "utf8"));
572
+ pkgContent.dependencies = pkgContent.dependencies || {};
573
+ pkgContent.devDependencies = pkgContent.devDependencies || {};
574
+ let hasChanges = false;
575
+ for (const [pkg, ver] of Object.entries(resolvedDeps)) {
576
+ if (pkgContent.dependencies[pkg] !== ver) {
577
+ pkgContent.dependencies[pkg] = ver;
578
+ hasChanges = true;
579
+ }
580
+ }
581
+ for (const [pkg, ver] of Object.entries(resolvedDevDeps)) {
582
+ if (!pkgContent.dependencies[pkg] && pkgContent.devDependencies[pkg] !== ver) {
583
+ pkgContent.devDependencies[pkg] = ver;
584
+ hasChanges = true;
585
+ }
586
+ }
587
+ if (hasChanges && writeChanges) {
588
+ fs3.writeFileSync(pkgJsonPath, JSON.stringify(pkgContent, null, 2) + "\n");
589
+ updated = true;
590
+ console.log(`[KrnlPackageReconciler] Reconciled package.json from ${manifests.length} manifest(s).`);
591
+ }
592
+ }
593
+ return {
594
+ updated,
595
+ totalManifests: manifests.length,
596
+ addedDependencies: resolvedDeps,
597
+ addedDevDependencies: resolvedDevDeps,
598
+ conflicts
599
+ };
600
+ }
601
+ /**
602
+ * Discovers all manifest.json files in krnl/ (or src/)
603
+ */
604
+ static findManifests(projectRoot) {
605
+ const searchDirs = [
606
+ path5.join(projectRoot, "krnl", "backend", "libraries"),
607
+ path5.join(projectRoot, "krnl", "backend", "functionalities"),
608
+ path5.join(projectRoot, "krnl", "frontend", "libraries"),
609
+ path5.join(projectRoot, "krnl", "frontend", "functionalities"),
610
+ path5.join(projectRoot, "src", "functionalities"),
611
+ path5.join(projectRoot, "src", "libraries")
612
+ ];
613
+ const found = [];
614
+ for (const dir of searchDirs) {
615
+ if (fs3.existsSync(dir)) {
616
+ this.scanRecursive(dir, found);
617
+ }
618
+ }
619
+ return found;
620
+ }
621
+ static scanRecursive(dir, found) {
622
+ try {
623
+ const entries = fs3.readdirSync(dir, { withFileTypes: true });
624
+ for (const entry of entries) {
625
+ if (entry.name === "node_modules" || entry.name === "dist" || entry.name === ".git") continue;
626
+ const full = path5.join(dir, entry.name);
627
+ if (entry.isDirectory()) {
628
+ this.scanRecursive(full, found);
629
+ } else if (entry.isFile() && entry.name === "manifest.json") {
630
+ found.push(full);
631
+ }
632
+ }
633
+ } catch {
634
+ }
635
+ }
636
+ };
637
+
638
+ // src/commands/generators/entityGenerator.ts
639
+ import * as fs5 from "fs";
640
+ import * as path7 from "path";
641
+
642
+ // src/commands/generators/common.ts
643
+ import * as fs4 from "fs";
644
+ import * as path6 from "path";
645
+ function getPlaneRoots(projectRoot) {
646
+ const krnlRoot = path6.join(projectRoot, "krnl");
647
+ if (fs4.existsSync(krnlRoot)) {
648
+ return {
649
+ backend: path6.join(krnlRoot, "backend"),
650
+ frontend: path6.join(krnlRoot, "frontend"),
651
+ isKrnlDir: true
652
+ };
653
+ }
654
+ return {
655
+ backend: path6.join(projectRoot, "src"),
656
+ frontend: path6.join(projectRoot, "src"),
657
+ isKrnlDir: false
658
+ };
659
+ }
660
+
661
+ // src/commands/generators/entityGenerator.ts
662
+ function generateEntity(name, projectRoot) {
663
+ const { backend, frontend } = getPlaneRoots(projectRoot);
664
+ const bEntityDir = path7.join(backend, "entities", name);
665
+ fs5.mkdirSync(path7.join(bEntityDir, "orchestrations"), { recursive: true });
666
+ fs5.mkdirSync(path7.join(bEntityDir, "tests"), { recursive: true });
667
+ fs5.writeFileSync(
668
+ path7.join(bEntityDir, `${name}.ts`),
669
+ `import { Entity, KrnlMagneticLoader } from "@dinilmusick/krnl-core";
670
+
671
+ /**
672
+ * @role skeleton
673
+ */
674
+ export class ${name} extends Entity {
675
+ constructor() {
676
+ super({
677
+ id: "${name}",
678
+ version: "1.0.0",
679
+ description: "${name} entity"
680
+ });
681
+ }
682
+
683
+ async boot(): Promise<void> {
684
+ await KrnlMagneticLoader.loadAll(this, import.meta.url);
685
+ }
686
+ }
687
+
688
+ export default ${name};
689
+ `
690
+ );
691
+ fs5.writeFileSync(
692
+ path7.join(bEntityDir, "orchestrations", "DefaultFlow.ts"),
693
+ `export function configureDefaultFlow(entity: any) {
694
+ return entity.flow("defaultFlow")
695
+ .register({ visibility: "public" });
696
+ }
697
+ `
698
+ );
699
+ fs5.writeFileSync(
700
+ path7.join(bEntityDir, "tests", `${name}.test.ts`),
701
+ `import { describe, it, expect } from "vitest";
702
+ import { ${name} } from "../${name}.js";
703
+
704
+ describe("${name} Entity", () => {
705
+ it("instantiates correctly", () => {
706
+ const instance = new ${name}();
707
+ expect(instance.id).toBe("${name}");
708
+ });
709
+ });
710
+ `
711
+ );
712
+ const fEntityDir = path7.join(frontend, "entities", name);
713
+ fs5.mkdirSync(path7.join(fEntityDir, "tests"), { recursive: true });
714
+ fs5.writeFileSync(
715
+ path7.join(fEntityDir, `${name}0.tsx`),
716
+ `import React from "react";
717
+
718
+ export const ${name}0: React.FC = () => {
719
+ return (
720
+ <div className="krnl-entity-${name.toLowerCase()}">
721
+ <h2>${name} (Variant 0)</h2>
722
+ </div>
723
+ );
724
+ };
725
+
726
+ export default ${name}0;
727
+ `
728
+ );
729
+ fs5.writeFileSync(
730
+ path7.join(fEntityDir, "tests", `${name}0.test.tsx`),
731
+ `import { describe, it, expect } from "vitest";
732
+
733
+ describe("${name}0 Component", () => {
734
+ it("renders variant 0", () => {
735
+ expect(true).toBe(true);
736
+ });
737
+ });
738
+ `
739
+ );
740
+ console.log(`\u2705 Created Backend Entity Folder: krnl/backend/entities/${name}/`);
741
+ console.log(`\u2705 Created Frontend Entity Folder: krnl/frontend/entities/${name}/`);
742
+ }
743
+
744
+ // src/commands/generators/functionalityGenerator.ts
745
+ import * as fs6 from "fs";
746
+ import * as path8 from "path";
747
+ function generateFunctionality(name, projectRoot) {
748
+ const { backend, frontend } = getPlaneRoots(projectRoot);
749
+ const bFuncDir = path8.join(backend, "functionalities", name);
750
+ fs6.mkdirSync(path8.join(bFuncDir, "main_function"), { recursive: true });
751
+ fs6.mkdirSync(path8.join(bFuncDir, "state_data"), { recursive: true });
752
+ fs6.mkdirSync(path8.join(bFuncDir, "helper_functions"), { recursive: true });
753
+ fs6.mkdirSync(path8.join(bFuncDir, "events"), { recursive: true });
754
+ fs6.mkdirSync(path8.join(bFuncDir, "tests"), { recursive: true });
755
+ fs6.writeFileSync(
756
+ path8.join(bFuncDir, `${name}Atom.ts`),
757
+ `export interface ${name}Input {
758
+ payload?: string;
759
+ }
760
+
761
+ export interface ${name}Output {
762
+ success: boolean;
763
+ timestamp: number;
764
+ }
765
+ `
766
+ );
767
+ fs6.writeFileSync(
768
+ path8.join(bFuncDir, "manifest.json"),
769
+ JSON.stringify(
770
+ {
771
+ name,
772
+ description: `${name} quad-unit functionality`,
773
+ dependencies: {}
774
+ },
775
+ null,
776
+ 2
777
+ )
778
+ );
779
+ fs6.writeFileSync(
780
+ path8.join(bFuncDir, "main_function", "logic.ts"),
781
+ `import type { ${name}Input, ${name}Output } from "../${name}Atom.js";
782
+
783
+ export const main = async (input: ${name}Input, { state }: any): Promise<${name}Output> => {
784
+ return {
785
+ success: true,
786
+ timestamp: Date.now()
787
+ };
788
+ };
789
+ `
790
+ );
791
+ fs6.writeFileSync(
792
+ path8.join(bFuncDir, "main_function", "lifecycle.ts"),
793
+ `export async function onMount() {}
794
+ export async function onTeardown() {}
795
+ `
796
+ );
797
+ fs6.writeFileSync(
798
+ path8.join(bFuncDir, "state_data", "state.ts"),
799
+ `export interface ${name}State {
800
+ executionCount: number;
801
+ }
802
+
803
+ export const initialState: ${name}State = {
804
+ executionCount: 0
805
+ };
806
+ `
807
+ );
808
+ fs6.writeFileSync(
809
+ path8.join(bFuncDir, "helper_functions", "helper.ts"),
810
+ `/**
811
+ * @role component
812
+ */
813
+ export function exampleHelper(): boolean {
814
+ return true;
815
+ }
816
+ `
817
+ );
818
+ fs6.writeFileSync(
819
+ path8.join(bFuncDir, "events", "events.ts"),
820
+ `/**
821
+ * @role component
822
+ */
823
+ export interface ${name}CompletedEvent {
824
+ timestamp: number;
825
+ }
826
+ `
827
+ );
828
+ fs6.writeFileSync(
829
+ path8.join(bFuncDir, "tests", `${name}.test.ts`),
830
+ `import { describe, it, expect } from "vitest";
831
+
832
+ describe("${name} functionality", () => {
833
+ it("passes basic test", () => {
834
+ expect(true).toBe(true);
835
+ });
836
+ });
837
+ `
838
+ );
839
+ const fFuncDir = path8.join(frontend, "functionalities", name);
840
+ fs6.mkdirSync(path8.join(fFuncDir, "tests"), { recursive: true });
841
+ fs6.writeFileSync(
842
+ path8.join(fFuncDir, `${name}0.tsx`),
843
+ `import React from "react";
844
+
845
+ export const ${name}0: React.FC = () => {
846
+ return (
847
+ <div className="krnl-func-${name.toLowerCase()}">
848
+ <h3>${name} (Variant 0)</h3>
849
+ </div>
850
+ );
851
+ };
852
+
853
+ export default ${name}0;
854
+ `
855
+ );
856
+ fs6.writeFileSync(
857
+ path8.join(fFuncDir, "manifest.json"),
858
+ JSON.stringify({ name: `${name}UI`, dependencies: {} }, null, 2)
859
+ );
860
+ fs6.writeFileSync(
861
+ path8.join(fFuncDir, "tests", `${name}0.test.tsx`),
862
+ `import { describe, it, expect } from "vitest";
863
+
864
+ describe("${name}0 Component", () => {
865
+ it("renders correctly", () => {
866
+ expect(true).toBe(true);
867
+ });
868
+ });
869
+ `
870
+ );
871
+ KrnlPackageReconciler.reconcile(projectRoot, true);
872
+ console.log(`\u2705 Created Backend Functionality Quad-Unit: krnl/backend/functionalities/${name}/`);
873
+ console.log(`\u2705 Created Frontend Functionality: krnl/frontend/functionalities/${name}/`);
874
+ }
875
+
876
+ // src/commands/generators/libraryGenerator.ts
877
+ import * as fs7 from "fs";
878
+ import * as path9 from "path";
879
+ function generateLibrary(name, projectRoot) {
880
+ const { backend, frontend } = getPlaneRoots(projectRoot);
881
+ const conceptName = name.endsWith("Concepts") ? name : `${name}Concepts`;
882
+ const bLibDir = path9.join(backend, "libraries", conceptName);
883
+ fs7.mkdirSync(path9.join(bLibDir, "tests"), { recursive: true });
884
+ fs7.writeFileSync(
885
+ path9.join(bLibDir, "definitions.ts"),
886
+ `/**
887
+ * @file definitions.ts
888
+ * @role component
889
+ */
890
+ export interface ${conceptName}Options {
891
+ enabled?: boolean;
892
+ }
893
+ `
894
+ );
895
+ fs7.writeFileSync(
896
+ path9.join(bLibDir, "functions.ts"),
897
+ `/**
898
+ * @file functions.ts
899
+ * @role component
900
+ */
901
+ import type { ${conceptName}Options } from "./definitions.js";
902
+
903
+ export function ${name.toLowerCase()}Transform<T>(data: T, _opts?: ${conceptName}Options): T {
904
+ return data;
905
+ }
906
+ `
907
+ );
908
+ fs7.writeFileSync(
909
+ path9.join(bLibDir, "manifest.json"),
910
+ JSON.stringify({ name: conceptName, dependencies: {} }, null, 2)
911
+ );
912
+ fs7.writeFileSync(
913
+ path9.join(bLibDir, "tests", `${conceptName}.test.ts`),
914
+ `import { describe, it, expect } from "vitest";
915
+
916
+ describe("${conceptName}", () => {
917
+ it("runs correctly", () => {
918
+ expect(true).toBe(true);
919
+ });
920
+ });
921
+ `
922
+ );
923
+ const fLibDir = path9.join(frontend, "libraries", conceptName);
924
+ fs7.mkdirSync(path9.join(fLibDir, "tests"), { recursive: true });
925
+ fs7.writeFileSync(
926
+ path9.join(fLibDir, "definitions.ts"),
927
+ `export interface ${name}Props {
928
+ label?: string;
929
+ }
930
+ `
931
+ );
932
+ fs7.writeFileSync(
933
+ path9.join(fLibDir, "components.tsx"),
934
+ `import React from "react";
935
+ import type { ${name}Props } from "./definitions.js";
936
+ import "./styles.css";
937
+
938
+ export const ${name}: React.FC<${name}Props> = ({ label = "${name}" }) => {
939
+ return <div className="krnl-${name.toLowerCase()}">{label}</div>;
940
+ };
941
+ `
942
+ );
943
+ fs7.writeFileSync(
944
+ path9.join(fLibDir, "styles.css"),
945
+ `.krnl-${name.toLowerCase()} {
946
+ font-family: inherit;
947
+ }
948
+ `
949
+ );
950
+ fs7.writeFileSync(
951
+ path9.join(fLibDir, "manifest.json"),
952
+ JSON.stringify({ name: `${conceptName}UI`, dependencies: {} }, null, 2)
953
+ );
954
+ fs7.writeFileSync(
955
+ path9.join(fLibDir, "tests", `${name}.test.tsx`),
956
+ `import { describe, it, expect } from "vitest";
957
+
958
+ describe("${name} UI Concept", () => {
959
+ it("renders correctly", () => {
960
+ expect(true).toBe(true);
961
+ });
962
+ });
963
+ `
964
+ );
965
+ KrnlPackageReconciler.reconcile(projectRoot, true);
966
+ console.log(`\u2705 Created Backend Concept Library: krnl/backend/libraries/${conceptName}/`);
967
+ console.log(`\u2705 Created Frontend Concept Library: krnl/frontend/libraries/${conceptName}/`);
968
+ }
969
+ function generateSubApp(name, projectRoot) {
970
+ const { backend } = getPlaneRoots(projectRoot);
971
+ const subappDir = path9.join(backend, "subapps", name);
972
+ fs7.mkdirSync(subappDir, { recursive: true });
973
+ fs7.writeFileSync(
974
+ path9.join(subappDir, "subapp.json"),
975
+ JSON.stringify(
976
+ {
977
+ name,
978
+ version: "1.0.0",
979
+ description: `${name} self-contained sub-app`,
980
+ registrationEntry: "./register.js"
981
+ },
982
+ null,
983
+ 2
984
+ )
985
+ );
986
+ fs7.writeFileSync(
987
+ path9.join(subappDir, "register.ts"),
988
+ `export function register(context: any) {
989
+ context.logger.log("Registering ${name} sub-app");
990
+ return {
991
+ name: "${name}",
992
+ operations: []
993
+ };
994
+ }
995
+ export default register;
996
+ `
997
+ );
998
+ console.log(`\u2705 Created Sub-App: krnl/backend/subapps/${name}/`);
999
+ }
1000
+
1001
+ // src/commands/generate.ts
1002
+ async function runGenerate(type, name, _parentEntity, projectRoot = process.cwd()) {
1003
+ if (!name) {
1004
+ console.error("\u274C Error: Resource name is required. Usage: krnl generate <entity|functionality|library|subapp> <Name>");
1005
+ process.exit(1);
1006
+ }
1007
+ switch (type.toLowerCase()) {
1008
+ case "entity":
1009
+ generateEntity(name, projectRoot);
1010
+ break;
1011
+ case "functionality":
1012
+ generateFunctionality(name, projectRoot);
1013
+ break;
1014
+ case "library":
1015
+ generateLibrary(name, projectRoot);
1016
+ break;
1017
+ case "subapp":
1018
+ generateSubApp(name, projectRoot);
1019
+ break;
1020
+ default:
1021
+ console.error(`\u274C Unknown resource type "${type}". Valid types: entity, functionality, library, subapp`);
1022
+ process.exit(1);
1023
+ }
1024
+ }
1025
+
1026
+ // src/commands/watch.ts
1027
+ import * as fs8 from "fs";
1028
+ import * as path10 from "path";
1029
+ function generateMagneticDeclarations(projectRoot = process.cwd()) {
1030
+ const { results: functionalities, libDirs } = scanDirectory(projectRoot);
1031
+ let dtsContent = `// Automatically generated by Krnl Magnetic Watcher. Do not edit manually.
1032
+
1033
+ `;
1034
+ dtsContent += `import { Entity } from '@dinilmusick/krnl-core';
1035
+
1036
+ `;
1037
+ const globalDeclarations = [];
1038
+ for (const func of functionalities) {
1039
+ const helpersDir = path10.join(func.funcPath, "helper_functions");
1040
+ if (fs8.existsSync(helpersDir)) {
1041
+ const files = fs8.readdirSync(helpersDir);
1042
+ for (const file of files) {
1043
+ if (file.endsWith(".js") || file.endsWith(".ts")) {
1044
+ const filePath = path10.join(helpersDir, file);
1045
+ const baseName = path10.basename(file, path10.extname(file));
1046
+ const importPath = `./${path10.relative(projectRoot, filePath).replace(/\\/g, "/")}`;
1047
+ const { named, hasDefault } = parseExports(filePath, baseName);
1048
+ if (hasDefault) {
1049
+ globalDeclarations.push(` const ${baseName}: typeof import('${importPath}')['default'];`);
1050
+ }
1051
+ for (const name of named) {
1052
+ globalDeclarations.push(` const ${name}: typeof import('${importPath}')['${name}'];`);
1053
+ }
1054
+ }
1055
+ }
1056
+ }
1057
+ const eventsDir = path10.join(func.funcPath, "events");
1058
+ if (fs8.existsSync(eventsDir)) {
1059
+ const files = fs8.readdirSync(eventsDir);
1060
+ for (const file of files) {
1061
+ if (file.endsWith(".js") || file.endsWith(".ts")) {
1062
+ const filePath = path10.join(eventsDir, file);
1063
+ const baseName = path10.basename(file, path10.extname(file));
1064
+ const importPath = `./${path10.relative(projectRoot, filePath).replace(/\\/g, "/")}`;
1065
+ const { named, hasDefault } = parseExports(filePath, baseName);
1066
+ if (hasDefault) {
1067
+ globalDeclarations.push(` const ${baseName}: typeof import('${importPath}')['default'];`);
1068
+ }
1069
+ for (const name of named) {
1070
+ globalDeclarations.push(` const ${name}: typeof import('${importPath}')['${name}'];`);
1071
+ }
1072
+ }
1073
+ }
1074
+ }
1075
+ }
1076
+ for (const libPath of libDirs) {
1077
+ scanLibFiles(libPath, projectRoot, globalDeclarations);
1078
+ }
1079
+ if (globalDeclarations.length > 0) {
1080
+ dtsContent += `declare global {
1081
+ ${Array.from(new Set(globalDeclarations)).join("\n")}
1082
+ }
1083
+ `;
1084
+ }
1085
+ const outPath = path10.join(projectRoot, "krnl-magnetic.d.ts");
1086
+ fs8.writeFileSync(outPath, dtsContent);
1087
+ console.log(`[Krnl Watch] Updated ambient declarations: ${outPath}`);
1088
+ }
1089
+ function scanLibFiles(dir, projectRoot, decls) {
1090
+ if (!fs8.existsSync(dir)) return;
1091
+ for (const entry of fs8.readdirSync(dir, { withFileTypes: true })) {
1092
+ if (entry.name.startsWith(".") || entry.name === "node_modules") continue;
1093
+ const full = path10.join(dir, entry.name);
1094
+ if (entry.isDirectory()) {
1095
+ scanLibFiles(full, projectRoot, decls);
1096
+ } else if ((entry.name.endsWith(".ts") || entry.name.endsWith(".js")) && !entry.name.endsWith(".d.ts")) {
1097
+ const baseName = path10.basename(entry.name, path10.extname(entry.name));
1098
+ const importPath = `./${path10.relative(projectRoot, full).replace(/\\/g, "/")}`;
1099
+ const { named, hasDefault } = parseExports(full, baseName);
1100
+ if (hasDefault) decls.push(` const ${baseName}: typeof import('${importPath}')['default'];`);
1101
+ for (const n of named) decls.push(` const ${n}: typeof import('${importPath}')['${n}'];`);
1102
+ }
1103
+ }
1104
+ }
1105
+ function scanDirectory(dir, results = [], libDirs = []) {
1106
+ if (!fs8.existsSync(dir)) return { results, libDirs };
1107
+ const list = fs8.readdirSync(dir, { withFileTypes: true });
1108
+ for (const entry of list) {
1109
+ if (entry.isDirectory()) {
1110
+ if (entry.name === "node_modules" || entry.name === "dist" || entry.name === ".git") continue;
1111
+ const fullPath = path10.join(dir, entry.name);
1112
+ if (entry.name === "functionalities") {
1113
+ const funcs = fs8.readdirSync(fullPath, { withFileTypes: true });
1114
+ for (const f of funcs) {
1115
+ if (f.isDirectory()) results.push({ funcPath: path10.join(fullPath, f.name), funcName: f.name });
1116
+ }
1117
+ } else if (entry.name === "libraries" || entry.name === "library") {
1118
+ libDirs.push(fullPath);
1119
+ } else {
1120
+ scanDirectory(fullPath, results, libDirs);
1121
+ }
1122
+ }
1123
+ }
1124
+ return { results, libDirs };
1125
+ }
1126
+ function parseExports(filePath, defaultName) {
1127
+ const content = fs8.readFileSync(filePath, "utf8");
1128
+ const named = [];
1129
+ let hasDefault = false;
1130
+ const namedRegex = /export\s+(?:const|let|var|function|class|async\s+function)\s+([a-zA-Z0-9_$]+)/g;
1131
+ let match;
1132
+ while ((match = namedRegex.exec(content)) !== null) {
1133
+ if (match[1]) named.push(match[1]);
1134
+ }
1135
+ if (content.includes("export default")) {
1136
+ hasDefault = true;
1137
+ }
1138
+ return { named, hasDefault };
1139
+ }
1140
+
1141
+ export {
1142
+ runValidate,
1143
+ KrnlPackageReconciler,
1144
+ runGenerate,
1145
+ generateMagneticDeclarations
1146
+ };