slicejs-cli 4.3.0 → 4.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/LICENSE +21 -21
- package/README.md +260 -257
- package/client.js +958 -823
- package/commands/Print.js +163 -163
- package/commands/Validations.js +92 -92
- package/commands/build/build.js +97 -107
- package/commands/buildProduction/buildProduction.js +613 -613
- package/commands/bundle/bundle.js +251 -239
- package/commands/createComponent/VisualComponentTemplate.js +55 -55
- package/commands/createComponent/createComponent.js +128 -128
- package/commands/deleteComponent/deleteComponent.js +81 -81
- package/commands/docs/docs.js +365 -365
- package/commands/doctor/doctor.js +730 -563
- package/commands/getComponent/getComponent.js +841 -842
- package/commands/init/init.js +526 -475
- package/commands/lint/lint.js +75 -0
- package/commands/lint/types.js +85 -0
- package/commands/listComponents/listComponents.js +172 -172
- package/commands/seo/check.js +94 -0
- package/commands/seo/images.js +641 -0
- package/commands/seo/sitemap.js +109 -0
- package/commands/seo/support.js +192 -0
- package/commands/setup/lint.js +151 -0
- package/commands/skill/skill.js +236 -236
- package/commands/startServer/startServer.js +240 -240
- package/commands/startServer/watchServer.js +66 -66
- package/commands/translator/check.js +32 -0
- package/commands/translator/init.js +125 -0
- package/commands/translator/scan.js +444 -0
- package/commands/typecheck/typecheck.js +83 -0
- package/commands/types/types.js +1378 -1097
- package/commands/utils/JsMinifier.js +230 -230
- package/commands/utils/LocalCliDelegation.js +78 -53
- package/commands/utils/PackageManager.js +148 -148
- package/commands/utils/PathHelper.js +87 -75
- package/commands/utils/ProjectValidation.js +274 -0
- package/commands/utils/SourceDiagnostics.js +201 -201
- package/commands/utils/VersionChecker.js +169 -169
- package/commands/utils/analyzeSource.js +77 -77
- package/commands/utils/bundling/BundleGenerator.js +3748 -3776
- package/commands/utils/bundling/DependencyAnalyzer.js +12 -2
- package/commands/utils/bundling/ExternalModuleBundler.js +298 -298
- package/commands/utils/componentAudit.js +74 -0
- package/commands/utils/compressAssets.js +103 -103
- package/commands/utils/cssScope.js +83 -0
- package/commands/utils/loadConfig.js +31 -31
- package/commands/utils/semver.js +66 -0
- package/commands/utils/sliceConfigSchema.js +106 -0
- package/commands/utils/sliceScripts.js +48 -48
- package/commands/utils/updateManager.js +471 -471
- package/eslint-config.js +128 -0
- package/package.json +19 -13
package/commands/types/types.js
CHANGED
|
@@ -1,1147 +1,1428 @@
|
|
|
1
|
-
import fs from 'fs-extra';
|
|
2
|
-
import path from 'path';
|
|
3
|
-
import { parse } from '@babel/parser';
|
|
4
|
-
import traverse from '@babel/traverse';
|
|
5
|
-
|
|
1
|
+
import fs from 'fs-extra';
|
|
2
|
+
import path from 'path';
|
|
3
|
+
import { parse } from '@babel/parser';
|
|
4
|
+
import traverse from '@babel/traverse';
|
|
5
|
+
|
|
6
6
|
import Print from '../Print.js';
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
if (keyNode
|
|
40
|
-
return
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
if (
|
|
63
|
-
const
|
|
64
|
-
if (
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
7
|
+
import { componentTagFromSource, findUnscopedSelectors } from '../utils/cssScope.js';
|
|
8
|
+
import { auditComponentLifecycle } from '../utils/componentAudit.js';
|
|
9
|
+
import { getConfigPath, getComponentsJsPath, joinRoot } from '../utils/PathHelper.js';
|
|
10
|
+
import {
|
|
11
|
+
describeSyntaxError,
|
|
12
|
+
findUnresolvedRelativeImports,
|
|
13
|
+
hasDefaultExport,
|
|
14
|
+
findUnknownComponentBuilds
|
|
15
|
+
} from '../utils/SourceDiagnostics.js';
|
|
16
|
+
|
|
17
|
+
const TYPE_MAP = {
|
|
18
|
+
string: 'string',
|
|
19
|
+
number: 'number',
|
|
20
|
+
boolean: 'boolean',
|
|
21
|
+
object: 'Record<string, unknown>',
|
|
22
|
+
array: 'unknown[]',
|
|
23
|
+
function: '(...args: unknown[]) => unknown',
|
|
24
|
+
any: 'unknown'
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
const literalValueFromAst = (node) => {
|
|
28
|
+
if (!node) return undefined;
|
|
29
|
+
if (node.type === 'StringLiteral' || node.type === 'NumericLiteral' || node.type === 'BooleanLiteral') {
|
|
30
|
+
return node.value;
|
|
31
|
+
}
|
|
32
|
+
if (node.type === 'NullLiteral') {
|
|
33
|
+
return null;
|
|
34
|
+
}
|
|
35
|
+
return undefined;
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
const keyNameFromAst = (keyNode) => {
|
|
39
|
+
if (!keyNode) return null;
|
|
40
|
+
if (keyNode.type === 'Identifier') return keyNode.name;
|
|
41
|
+
if (keyNode.type === 'StringLiteral') return keyNode.value;
|
|
42
|
+
return null;
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
const astNodeToValue = (node) => {
|
|
46
|
+
if (!node) return undefined;
|
|
47
|
+
|
|
48
|
+
const literal = literalValueFromAst(node);
|
|
49
|
+
if (literal !== undefined || (node && node.type === 'NullLiteral')) {
|
|
50
|
+
return literal;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
if (node.type === 'ArrayExpression') {
|
|
54
|
+
return (node.elements || [])
|
|
55
|
+
.map((element) => astNodeToValue(element))
|
|
56
|
+
.filter((value) => value !== undefined);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
if (node.type === 'ObjectExpression') {
|
|
60
|
+
const out = {};
|
|
61
|
+
for (const property of node.properties || []) {
|
|
62
|
+
if (property.type !== 'ObjectProperty') continue;
|
|
63
|
+
const key = keyNameFromAst(property.key);
|
|
64
|
+
if (!key) continue;
|
|
65
|
+
const value = astNodeToValue(property.value);
|
|
66
|
+
if (value !== undefined) {
|
|
67
|
+
out[key] = value;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
return out;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
return undefined;
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
const normalizePropConfig = (rawConfig) => {
|
|
77
|
+
if (!rawConfig || typeof rawConfig !== 'object' || Array.isArray(rawConfig)) {
|
|
78
|
+
return { type: 'any', required: false };
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const config = {
|
|
82
|
+
type: typeof rawConfig.type === 'string' ? rawConfig.type.toLowerCase() : 'any',
|
|
83
|
+
required: rawConfig.required === true
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
if (Array.isArray(rawConfig.allowedValues) && rawConfig.allowedValues.length > 0) {
|
|
87
|
+
config.allowedValues = rawConfig.allowedValues;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
if (rawConfig.schema && typeof rawConfig.schema === 'object' && !Array.isArray(rawConfig.schema)) {
|
|
91
|
+
const schema = {};
|
|
92
|
+
for (const [name, nestedRaw] of Object.entries(rawConfig.schema)) {
|
|
93
|
+
schema[name] = normalizePropConfig(nestedRaw);
|
|
94
|
+
}
|
|
95
|
+
config.schema = schema;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
if (rawConfig.items && typeof rawConfig.items === 'object' && !Array.isArray(rawConfig.items)) {
|
|
99
|
+
config.items = normalizePropConfig(rawConfig.items);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
return config;
|
|
103
|
+
};
|
|
104
|
+
|
|
105
|
+
const extractStaticPropsFromObjectExpression = (objectExpressionNode) => {
|
|
106
|
+
const raw = astNodeToValue(objectExpressionNode);
|
|
107
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
|
|
108
|
+
|
|
109
|
+
const props = {};
|
|
110
|
+
for (const [propName, rawConfig] of Object.entries(raw)) {
|
|
111
|
+
props[propName] = normalizePropConfig(rawConfig);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
return Object.keys(props).length > 0 ? props : null;
|
|
115
|
+
};
|
|
116
|
+
|
|
117
|
+
// ============================================================
|
|
118
|
+
// Event registry scanning (slice.events.register(...) call sites)
|
|
119
|
+
// ============================================================
|
|
120
|
+
|
|
121
|
+
const PAYLOAD_TYPE_MAP = {
|
|
122
|
+
string: 'string',
|
|
123
|
+
number: 'number',
|
|
124
|
+
boolean: 'boolean',
|
|
125
|
+
object: 'Record<string, unknown>',
|
|
126
|
+
array: 'unknown[]',
|
|
127
|
+
function: '(...args: unknown[]) => unknown',
|
|
128
|
+
any: 'unknown'
|
|
129
|
+
};
|
|
130
|
+
|
|
131
|
+
// Translate a payload mini-schema into a TS type.
|
|
132
|
+
// - null/undefined => 'void'
|
|
133
|
+
// - 'string' (a scalar) => 'string'
|
|
134
|
+
// - { id: 'number', ... } => '{ id: number; ... }'
|
|
135
|
+
// - field value may also be { type: 'number' } (long form)
|
|
136
|
+
const payloadToTs = (payload) => {
|
|
137
|
+
if (payload === null || payload === undefined) return 'void';
|
|
138
|
+
if (typeof payload === 'string') return PAYLOAD_TYPE_MAP[payload.toLowerCase()] || 'unknown';
|
|
139
|
+
if (typeof payload === 'object' && !Array.isArray(payload)) {
|
|
140
|
+
const inner = Object.entries(payload)
|
|
141
|
+
.map(([key, value]) => {
|
|
142
|
+
let tsType = 'unknown';
|
|
143
|
+
if (typeof value === 'string') {
|
|
144
|
+
tsType = PAYLOAD_TYPE_MAP[value.toLowerCase()] || 'unknown';
|
|
145
|
+
} else if (value && typeof value === 'object' && typeof value.type === 'string') {
|
|
146
|
+
tsType = PAYLOAD_TYPE_MAP[value.type.toLowerCase()] || 'unknown';
|
|
147
|
+
}
|
|
148
|
+
return `${tsPropertyKey(key)}?: ${tsType}`;
|
|
149
|
+
})
|
|
150
|
+
.join('; ');
|
|
151
|
+
return inner.length > 0 ? `{ ${inner} }` : 'Record<string, unknown>';
|
|
152
|
+
}
|
|
153
|
+
return 'unknown';
|
|
154
|
+
};
|
|
155
|
+
|
|
156
|
+
const parseModule = (source, filePath) => {
|
|
157
|
+
try {
|
|
158
|
+
return parse(source, { sourceType: 'module', plugins: ['classProperties'] });
|
|
159
|
+
} catch (parseError) {
|
|
160
|
+
const loc = parseError.loc ? ` at line ${parseError.loc.line}, column ${parseError.loc.column}` : '';
|
|
161
|
+
Print.warning(`Parse error in ${filePath || 'unknown file'}${loc}: ${parseError.message}`);
|
|
162
|
+
return null;
|
|
163
|
+
}
|
|
164
|
+
};
|
|
165
|
+
|
|
166
|
+
// Matches `<x>.events.register(...)` — covers slice.events, this.events (bind), window.slice.events.
|
|
167
|
+
const isEventsRegisterCallee = (callee) => {
|
|
168
|
+
return (
|
|
169
|
+
callee &&
|
|
170
|
+
callee.type === 'MemberExpression' &&
|
|
171
|
+
keyNameFromAst(callee.property) === 'register' &&
|
|
172
|
+
callee.object &&
|
|
173
|
+
callee.object.type === 'MemberExpression' &&
|
|
174
|
+
keyNameFromAst(callee.object.property) === 'events'
|
|
175
|
+
);
|
|
176
|
+
};
|
|
177
|
+
|
|
178
|
+
// Resolve an exported object literal from a module file (export const NAME = {...} / export default {...}).
|
|
179
|
+
const resolveExportedObject = async (modulePath, exportName) => {
|
|
180
|
+
if (!(await fs.pathExists(modulePath))) return null;
|
|
181
|
+
let source;
|
|
182
|
+
try {
|
|
183
|
+
source = await fs.readFile(modulePath, 'utf8');
|
|
184
|
+
} catch {
|
|
185
|
+
return null;
|
|
186
|
+
}
|
|
187
|
+
const ast = parseModule(source, modulePath);
|
|
188
|
+
if (!ast) return null;
|
|
189
|
+
|
|
190
|
+
let found = null;
|
|
191
|
+
traverse.default(ast, {
|
|
192
|
+
ExportDefaultDeclaration(pathRef) {
|
|
193
|
+
if (exportName !== 'default') return;
|
|
194
|
+
const decl = pathRef.node.declaration;
|
|
195
|
+
if (decl && decl.type === 'ObjectExpression') found = decl;
|
|
196
|
+
},
|
|
197
|
+
ExportNamedDeclaration(pathRef) {
|
|
198
|
+
const decl = pathRef.node.declaration;
|
|
199
|
+
if (decl && decl.type === 'VariableDeclaration') {
|
|
200
|
+
for (const d of decl.declarations) {
|
|
201
|
+
if (keyNameFromAst(d.id) === exportName && d.init && d.init.type === 'ObjectExpression') {
|
|
202
|
+
found = d.init;
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
});
|
|
208
|
+
|
|
209
|
+
return found ? astNodeToValue(found) : null;
|
|
210
|
+
};
|
|
211
|
+
|
|
212
|
+
// Resolve a relative import specifier to an absolute .js file path.
|
|
213
|
+
const resolveRelativeModule = async (fromFile, specifier) => {
|
|
214
|
+
if (!specifier.startsWith('.')) return null; // bare imports are not followed
|
|
215
|
+
const base = path.resolve(path.dirname(fromFile), specifier);
|
|
216
|
+
const candidates = [base, `${base}.js`, path.join(base, 'index.js')];
|
|
217
|
+
for (const candidate of candidates) {
|
|
218
|
+
if (await fs.pathExists(candidate) && (await fs.stat(candidate)).isFile()) return candidate;
|
|
219
|
+
}
|
|
220
|
+
return null;
|
|
221
|
+
};
|
|
222
|
+
|
|
223
|
+
const mergeCatalog = (registry, catalog, prefix = '') => {
|
|
224
|
+
if (!catalog || typeof catalog !== 'object' || Array.isArray(catalog)) return;
|
|
225
|
+
for (const [key, definition] of Object.entries(catalog)) {
|
|
226
|
+
const eventName = `${prefix}${key}`;
|
|
227
|
+
const payload =
|
|
228
|
+
definition && typeof definition === 'object' && !Array.isArray(definition)
|
|
229
|
+
? definition.payload ?? null
|
|
230
|
+
: null;
|
|
231
|
+
registry[eventName] = { payload };
|
|
232
|
+
}
|
|
233
|
+
};
|
|
234
|
+
|
|
235
|
+
// Scan src/**/*.js for slice.events.register(<catalog>) calls and build the event registry.
|
|
236
|
+
const collectEventRegistry = async ({ projectRoot }) => {
|
|
237
|
+
const srcDir = joinRoot(projectRoot, 'src');
|
|
238
|
+
const files = await collectJavaScriptFiles(srcDir);
|
|
239
|
+
const registry = {};
|
|
240
|
+
|
|
241
|
+
for (const file of files) {
|
|
242
|
+
let source;
|
|
243
|
+
try {
|
|
244
|
+
source = await fs.readFile(file, 'utf8');
|
|
245
|
+
} catch {
|
|
246
|
+
continue;
|
|
247
|
+
}
|
|
248
|
+
if (!source.includes('.events.register(')) continue; // cheap prefilter
|
|
249
|
+
|
|
250
|
+
const ast = parseModule(source, file);
|
|
251
|
+
if (!ast) continue;
|
|
252
|
+
|
|
253
|
+
// Collect local object-literal consts and import bindings up front.
|
|
254
|
+
const localObjects = new Map(); // name -> ObjectExpression node
|
|
255
|
+
const imports = new Map(); // localName -> { source, imported }
|
|
256
|
+
traverse.default(ast, {
|
|
257
|
+
VariableDeclarator(pathRef) {
|
|
258
|
+
const node = pathRef.node;
|
|
259
|
+
if (node.id?.type === 'Identifier' && node.init?.type === 'ObjectExpression') {
|
|
260
|
+
localObjects.set(node.id.name, node.init);
|
|
261
|
+
}
|
|
262
|
+
},
|
|
263
|
+
ImportDeclaration(pathRef) {
|
|
264
|
+
const src = pathRef.node.source?.value;
|
|
265
|
+
for (const spec of pathRef.node.specifiers || []) {
|
|
266
|
+
if (spec.type === 'ImportDefaultSpecifier') {
|
|
267
|
+
imports.set(spec.local.name, { source: src, imported: 'default' });
|
|
268
|
+
} else if (spec.type === 'ImportSpecifier') {
|
|
269
|
+
imports.set(spec.local.name, { source: src, imported: keyNameFromAst(spec.imported) });
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
});
|
|
274
|
+
|
|
275
|
+
// Find the register() call sites and capture their arguments. Supports both
|
|
276
|
+
// register(catalog) and register('namespace', catalog).
|
|
277
|
+
const pendingCalls = [];
|
|
278
|
+
traverse.default(ast, {
|
|
279
|
+
CallExpression(pathRef) {
|
|
280
|
+
if (!isEventsRegisterCallee(pathRef.node.callee)) return;
|
|
281
|
+
pendingCalls.push(pathRef.node.arguments);
|
|
282
|
+
}
|
|
283
|
+
});
|
|
284
|
+
|
|
285
|
+
// Resolve a catalog arg node to a plain object (inline literal, local const, or import).
|
|
286
|
+
const resolveCatalogArg = async (arg) => {
|
|
287
|
+
if (!arg) return null;
|
|
288
|
+
if (arg.type === 'ObjectExpression') return astNodeToValue(arg);
|
|
289
|
+
if (arg.type === 'Identifier') {
|
|
290
|
+
if (localObjects.has(arg.name)) return astNodeToValue(localObjects.get(arg.name));
|
|
291
|
+
if (imports.has(arg.name)) {
|
|
292
|
+
const { source: importSource, imported } = imports.get(arg.name);
|
|
293
|
+
const modulePath = await resolveRelativeModule(file, importSource);
|
|
294
|
+
if (modulePath) return resolveExportedObject(modulePath, imported);
|
|
295
|
+
Print.warning(`Could not resolve event catalog import "${arg.name}" from "${importSource}" in ${file}`);
|
|
296
|
+
return null;
|
|
297
|
+
}
|
|
298
|
+
Print.warning(`slice.events.register(${arg.name}) in ${file}: argument is not a literal/imported object — skipped for typing.`);
|
|
299
|
+
return null;
|
|
300
|
+
}
|
|
301
|
+
Print.warning(`slice.events.register(...) in ${file}: argument is not an object literal — skipped for typing.`);
|
|
302
|
+
return null;
|
|
303
|
+
};
|
|
304
|
+
|
|
305
|
+
for (const args of pendingCalls) {
|
|
306
|
+
let prefix = '';
|
|
307
|
+
let catalogArg = args[0];
|
|
308
|
+
// register('namespace', catalog) — first arg is a string literal.
|
|
309
|
+
if (args[0] && args[0].type === 'StringLiteral') {
|
|
310
|
+
const ns = String(args[0].value).trim();
|
|
311
|
+
prefix = ns.endsWith(':') ? ns : `${ns}:`;
|
|
312
|
+
catalogArg = args[1];
|
|
313
|
+
}
|
|
314
|
+
const catalog = await resolveCatalogArg(catalogArg);
|
|
315
|
+
mergeCatalog(registry, catalog, prefix);
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
return registry;
|
|
320
|
+
};
|
|
321
|
+
|
|
322
|
+
// Matches `<x>.events.<method>(...)` — covers slice.events / this.events (bind) / window.slice.events.
|
|
323
|
+
const isEventsMethodCallee = (callee, methods) => {
|
|
324
|
+
return (
|
|
325
|
+
callee &&
|
|
326
|
+
callee.type === 'MemberExpression' &&
|
|
327
|
+
methods.includes(keyNameFromAst(callee.property)) &&
|
|
328
|
+
callee.object &&
|
|
329
|
+
callee.object.type === 'MemberExpression' &&
|
|
330
|
+
keyNameFromAst(callee.object.property) === 'events'
|
|
331
|
+
);
|
|
332
|
+
};
|
|
333
|
+
|
|
334
|
+
// Nearest enclosing class name for a call site (the component/service that emits/listens).
|
|
335
|
+
const enclosingClassName = (pathRef) => {
|
|
336
|
+
const classPath = pathRef.findParent((p) => p.isClassDeclaration() || p.isClassExpression());
|
|
337
|
+
return classPath?.node?.id?.name || null;
|
|
338
|
+
};
|
|
339
|
+
|
|
340
|
+
// Static pub/sub graph: scan emit()/subscribe() call sites so emitters/listeners are
|
|
341
|
+
// documented WITHOUT executing the code (complements the observational runtime tracing).
|
|
342
|
+
// Returns { events: { name: { emitters:[], listeners:[] } }, dynamic: { emitters:[], listeners:[] } }.
|
|
343
|
+
const collectEventGraph = async ({ projectRoot }) => {
|
|
344
|
+
const srcDir = joinRoot(projectRoot, 'src');
|
|
345
|
+
const files = await collectJavaScriptFiles(srcDir);
|
|
346
|
+
const events = {};
|
|
347
|
+
const dynamic = { emitters: [], listeners: [] };
|
|
348
|
+
|
|
349
|
+
const bucketFor = (eventName, kind) => {
|
|
350
|
+
if (!events[eventName]) events[eventName] = { emitters: [], listeners: [] };
|
|
351
|
+
return events[eventName][kind];
|
|
352
|
+
};
|
|
353
|
+
|
|
354
|
+
for (const file of files) {
|
|
355
|
+
let source;
|
|
356
|
+
try {
|
|
357
|
+
source = await fs.readFile(file, 'utf8');
|
|
358
|
+
} catch {
|
|
359
|
+
continue;
|
|
360
|
+
}
|
|
361
|
+
if (!source.includes('.events.emit(') && !source.includes('.events.subscribe(') && !source.includes('.events.subscribeOnce(')) {
|
|
362
|
+
continue; // cheap prefilter
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
const ast = parseModule(source, file);
|
|
366
|
+
if (!ast) continue;
|
|
367
|
+
|
|
368
|
+
const relFile = path.relative(projectRoot, file).replace(/\\/g, '/');
|
|
369
|
+
|
|
370
|
+
traverse.default(ast, {
|
|
371
|
+
CallExpression(pathRef) {
|
|
372
|
+
const callee = pathRef.node.callee;
|
|
373
|
+
let kind = null;
|
|
374
|
+
if (isEventsMethodCallee(callee, ['emit'])) kind = 'emitters';
|
|
375
|
+
else if (isEventsMethodCallee(callee, ['subscribe', 'subscribeOnce'])) kind = 'listeners';
|
|
376
|
+
if (!kind) return;
|
|
377
|
+
|
|
378
|
+
const site = {
|
|
379
|
+
file: relFile,
|
|
380
|
+
line: pathRef.node.loc?.start?.line || 0,
|
|
381
|
+
component: enclosingClassName(pathRef)
|
|
382
|
+
};
|
|
383
|
+
|
|
384
|
+
const nameArg = pathRef.node.arguments[0];
|
|
385
|
+
if (nameArg && nameArg.type === 'StringLiteral') {
|
|
386
|
+
bucketFor(nameArg.value, kind).push(site);
|
|
387
|
+
} else {
|
|
388
|
+
dynamic[kind].push(site); // computed event name — can't be resolved statically
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
});
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
return { events, dynamic };
|
|
395
|
+
};
|
|
396
|
+
|
|
397
|
+
const sortKeys = (obj) => {
|
|
398
|
+
return Object.keys(obj)
|
|
399
|
+
.sort((a, b) => a.localeCompare(b))
|
|
400
|
+
.reduce((acc, key) => {
|
|
401
|
+
acc[key] = obj[key];
|
|
402
|
+
return acc;
|
|
403
|
+
}, {});
|
|
404
|
+
};
|
|
405
|
+
|
|
406
|
+
const parseComponentsRegistry = (content, filePath) => {
|
|
407
|
+
const match = content.match(/const components = ({[\s\S]*?});/);
|
|
408
|
+
if (!match) {
|
|
409
|
+
throw new Error(`Invalid format in ${filePath}. Expected: const components = { ... };`);
|
|
410
|
+
}
|
|
411
|
+
try {
|
|
412
|
+
return JSON.parse(match[1]);
|
|
413
|
+
} catch (parseError) {
|
|
414
|
+
throw new Error(`Failed to parse components registry in ${filePath}: ${parseError.message}`, { cause: parseError });
|
|
415
|
+
}
|
|
416
|
+
};
|
|
417
|
+
|
|
418
|
+
// The prop metadata the type generator has to read from the AST. Anything
|
|
419
|
+
// computed (a constant, a function call) is invisible to it: the prop silently
|
|
420
|
+
// degrades to `any` and loses autocomplete, with no error anywhere.
|
|
421
|
+
const TYPE_METADATA_FIELDS = new Set(['type', 'allowedValues', 'schema', 'items']);
|
|
102
422
|
|
|
103
|
-
const extractStaticPropsFromObjectExpression = (objectExpressionNode) => {
|
|
104
|
-
const raw = astNodeToValue(objectExpressionNode);
|
|
105
|
-
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
|
|
106
423
|
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
};
|
|
114
|
-
|
|
115
|
-
// ============================================================
|
|
116
|
-
// Event registry scanning (slice.events.register(...) call sites)
|
|
117
|
-
// ============================================================
|
|
118
|
-
|
|
119
|
-
const PAYLOAD_TYPE_MAP = {
|
|
120
|
-
string: 'string',
|
|
121
|
-
number: 'number',
|
|
122
|
-
boolean: 'boolean',
|
|
123
|
-
object: 'Record<string, unknown>',
|
|
124
|
-
array: 'unknown[]',
|
|
125
|
-
function: '(...args: unknown[]) => unknown',
|
|
126
|
-
any: 'unknown'
|
|
127
|
-
};
|
|
128
|
-
|
|
129
|
-
// Translate a payload mini-schema into a TS type.
|
|
130
|
-
// - null/undefined => 'void'
|
|
131
|
-
// - 'string' (a scalar) => 'string'
|
|
132
|
-
// - { id: 'number', ... } => '{ id: number; ... }'
|
|
133
|
-
// - field value may also be { type: 'number' } (long form)
|
|
134
|
-
const payloadToTs = (payload) => {
|
|
135
|
-
if (payload === null || payload === undefined) return 'void';
|
|
136
|
-
if (typeof payload === 'string') return PAYLOAD_TYPE_MAP[payload.toLowerCase()] || 'unknown';
|
|
137
|
-
if (typeof payload === 'object' && !Array.isArray(payload)) {
|
|
138
|
-
const inner = Object.entries(payload)
|
|
139
|
-
.map(([key, value]) => {
|
|
140
|
-
let tsType = 'unknown';
|
|
141
|
-
if (typeof value === 'string') {
|
|
142
|
-
tsType = PAYLOAD_TYPE_MAP[value.toLowerCase()] || 'unknown';
|
|
143
|
-
} else if (value && typeof value === 'object' && typeof value.type === 'string') {
|
|
144
|
-
tsType = PAYLOAD_TYPE_MAP[value.type.toLowerCase()] || 'unknown';
|
|
145
|
-
}
|
|
146
|
-
return `${tsPropertyKey(key)}: ${tsType}`;
|
|
147
|
-
})
|
|
148
|
-
.join('; ');
|
|
149
|
-
return inner.length > 0 ? `{ ${inner} }` : 'Record<string, unknown>';
|
|
150
|
-
}
|
|
151
|
-
return 'unknown';
|
|
152
|
-
};
|
|
153
|
-
|
|
154
|
-
const parseModule = (source, filePath) => {
|
|
155
|
-
try {
|
|
156
|
-
return parse(source, { sourceType: 'module', plugins: ['classProperties'] });
|
|
157
|
-
} catch (parseError) {
|
|
158
|
-
const loc = parseError.loc ? ` at line ${parseError.loc.line}, column ${parseError.loc.column}` : '';
|
|
159
|
-
Print.warning(`Parse error in ${filePath || 'unknown file'}${loc}: ${parseError.message}`);
|
|
160
|
-
return null;
|
|
161
|
-
}
|
|
162
|
-
};
|
|
163
|
-
|
|
164
|
-
// Matches `<x>.events.register(...)` — covers slice.events, this.events (bind), window.slice.events.
|
|
165
|
-
const isEventsRegisterCallee = (callee) => {
|
|
166
|
-
return (
|
|
167
|
-
callee &&
|
|
168
|
-
callee.type === 'MemberExpression' &&
|
|
169
|
-
keyNameFromAst(callee.property) === 'register' &&
|
|
170
|
-
callee.object &&
|
|
171
|
-
callee.object.type === 'MemberExpression' &&
|
|
172
|
-
keyNameFromAst(callee.object.property) === 'events'
|
|
173
|
-
);
|
|
174
|
-
};
|
|
175
|
-
|
|
176
|
-
// Resolve an exported object literal from a module file (export const NAME = {...} / export default {...}).
|
|
177
|
-
const resolveExportedObject = async (modulePath, exportName) => {
|
|
178
|
-
if (!(await fs.pathExists(modulePath))) return null;
|
|
179
|
-
let source;
|
|
424
|
+
/**
|
|
425
|
+
* Prop metadata written as an expression instead of a literal.
|
|
426
|
+
* @returns {{prop: string, field: string}[]}
|
|
427
|
+
*/
|
|
428
|
+
export const findComputedPropFields = (source) => {
|
|
429
|
+
let ast;
|
|
180
430
|
try {
|
|
181
|
-
|
|
431
|
+
ast = parse(source, { sourceType: 'module', plugins: ['classProperties'] });
|
|
182
432
|
} catch {
|
|
183
|
-
return
|
|
433
|
+
return []; // the syntax error is reported elsewhere
|
|
184
434
|
}
|
|
185
|
-
const ast = parseModule(source, modulePath);
|
|
186
|
-
if (!ast) return null;
|
|
187
435
|
|
|
188
|
-
let
|
|
436
|
+
let propsObject = null;
|
|
437
|
+
const issues = [];
|
|
189
438
|
traverse.default(ast, {
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
if (
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
for (const d of decl.declarations) {
|
|
199
|
-
if (keyNameFromAst(d.id) === exportName && d.init && d.init.type === 'ObjectExpression') {
|
|
200
|
-
found = d.init;
|
|
201
|
-
}
|
|
202
|
-
}
|
|
439
|
+
ClassProperty(pathRef) {
|
|
440
|
+
const node = pathRef.node;
|
|
441
|
+
if (!node.static || keyNameFromAst(node.key) !== "props") return;
|
|
442
|
+
if (node.value?.type === "ObjectExpression") {
|
|
443
|
+
propsObject = node.value;
|
|
444
|
+
} else if (node.value) {
|
|
445
|
+
// `static props = SHARED`: nothing to read at all.
|
|
446
|
+
issues.push({ prop: "props", field: "metadata" });
|
|
203
447
|
}
|
|
204
448
|
}
|
|
205
449
|
});
|
|
450
|
+
if (!propsObject) return issues;
|
|
451
|
+
const isLiteral = (node) => literalValueFromAst(node) !== undefined || node?.type === 'NullLiteral';
|
|
206
452
|
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
const resolveRelativeModule = async (fromFile, specifier) => {
|
|
212
|
-
if (!specifier.startsWith('.')) return null; // bare imports are not followed
|
|
213
|
-
const base = path.resolve(path.dirname(fromFile), specifier);
|
|
214
|
-
const candidates = [base, `${base}.js`, path.join(base, 'index.js')];
|
|
215
|
-
for (const candidate of candidates) {
|
|
216
|
-
if (await fs.pathExists(candidate) && (await fs.stat(candidate)).isFile()) return candidate;
|
|
217
|
-
}
|
|
218
|
-
return null;
|
|
219
|
-
};
|
|
220
|
-
|
|
221
|
-
const mergeCatalog = (registry, catalog, prefix = '') => {
|
|
222
|
-
if (!catalog || typeof catalog !== 'object' || Array.isArray(catalog)) return;
|
|
223
|
-
for (const [key, definition] of Object.entries(catalog)) {
|
|
224
|
-
const eventName = `${prefix}${key}`;
|
|
225
|
-
const payload =
|
|
226
|
-
definition && typeof definition === 'object' && !Array.isArray(definition)
|
|
227
|
-
? definition.payload ?? null
|
|
228
|
-
: null;
|
|
229
|
-
registry[eventName] = { payload };
|
|
230
|
-
}
|
|
231
|
-
};
|
|
232
|
-
|
|
233
|
-
// Scan src/**/*.js for slice.events.register(<catalog>) calls and build the event registry.
|
|
234
|
-
const collectEventRegistry = async ({ projectRoot }) => {
|
|
235
|
-
const srcDir = joinRoot(projectRoot, 'src');
|
|
236
|
-
const files = await collectJavaScriptFiles(srcDir);
|
|
237
|
-
const registry = {};
|
|
238
|
-
|
|
239
|
-
for (const file of files) {
|
|
240
|
-
let source;
|
|
241
|
-
try {
|
|
242
|
-
source = await fs.readFile(file, 'utf8');
|
|
243
|
-
} catch {
|
|
244
|
-
continue;
|
|
453
|
+
const inspectConfig = (propPath, configNode) => {
|
|
454
|
+
if (configNode?.type !== 'ObjectExpression') {
|
|
455
|
+
issues.push({ prop: propPath, field: 'metadata' });
|
|
456
|
+
return;
|
|
245
457
|
}
|
|
246
|
-
if (!source.includes('.events.register(')) continue; // cheap prefilter
|
|
247
458
|
|
|
248
|
-
const
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
const localObjects = new Map(); // name -> ObjectExpression node
|
|
253
|
-
const imports = new Map(); // localName -> { source, imported }
|
|
254
|
-
traverse.default(ast, {
|
|
255
|
-
VariableDeclarator(pathRef) {
|
|
256
|
-
const node = pathRef.node;
|
|
257
|
-
if (node.id?.type === 'Identifier' && node.init?.type === 'ObjectExpression') {
|
|
258
|
-
localObjects.set(node.id.name, node.init);
|
|
259
|
-
}
|
|
260
|
-
},
|
|
261
|
-
ImportDeclaration(pathRef) {
|
|
262
|
-
const src = pathRef.node.source?.value;
|
|
263
|
-
for (const spec of pathRef.node.specifiers || []) {
|
|
264
|
-
if (spec.type === 'ImportDefaultSpecifier') {
|
|
265
|
-
imports.set(spec.local.name, { source: src, imported: 'default' });
|
|
266
|
-
} else if (spec.type === 'ImportSpecifier') {
|
|
267
|
-
imports.set(spec.local.name, { source: src, imported: keyNameFromAst(spec.imported) });
|
|
268
|
-
}
|
|
269
|
-
}
|
|
270
|
-
}
|
|
271
|
-
});
|
|
459
|
+
for (const property of configNode.properties || []) {
|
|
460
|
+
if (property.type !== 'ObjectProperty') continue;
|
|
461
|
+
const field = keyNameFromAst(property.key);
|
|
462
|
+
if (!TYPE_METADATA_FIELDS.has(field)) continue;
|
|
272
463
|
|
|
273
|
-
|
|
274
|
-
// register(catalog) and register('namespace', catalog).
|
|
275
|
-
const pendingCalls = [];
|
|
276
|
-
traverse.default(ast, {
|
|
277
|
-
CallExpression(pathRef) {
|
|
278
|
-
if (!isEventsRegisterCallee(pathRef.node.callee)) return;
|
|
279
|
-
pendingCalls.push(pathRef.node.arguments);
|
|
280
|
-
}
|
|
281
|
-
});
|
|
464
|
+
const value = property.value;
|
|
282
465
|
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
if (arg.type === 'ObjectExpression') return astNodeToValue(arg);
|
|
287
|
-
if (arg.type === 'Identifier') {
|
|
288
|
-
if (localObjects.has(arg.name)) return astNodeToValue(localObjects.get(arg.name));
|
|
289
|
-
if (imports.has(arg.name)) {
|
|
290
|
-
const { source: importSource, imported } = imports.get(arg.name);
|
|
291
|
-
const modulePath = await resolveRelativeModule(file, importSource);
|
|
292
|
-
if (modulePath) return resolveExportedObject(modulePath, imported);
|
|
293
|
-
Print.warning(`Could not resolve event catalog import "${arg.name}" from "${importSource}" in ${file}`);
|
|
294
|
-
return null;
|
|
295
|
-
}
|
|
296
|
-
Print.warning(`slice.events.register(${arg.name}) in ${file}: argument is not a literal/imported object — skipped for typing.`);
|
|
297
|
-
return null;
|
|
466
|
+
if (field === 'type' && !isLiteral(value)) {
|
|
467
|
+
issues.push({ prop: propPath, field });
|
|
468
|
+
continue;
|
|
298
469
|
}
|
|
299
|
-
Print.warning(`slice.events.register(...) in ${file}: argument is not an object literal — skipped for typing.`);
|
|
300
|
-
return null;
|
|
301
|
-
};
|
|
302
470
|
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
if (args[0] && args[0].type === 'StringLiteral') {
|
|
308
|
-
const ns = String(args[0].value).trim();
|
|
309
|
-
prefix = ns.endsWith(':') ? ns : `${ns}:`;
|
|
310
|
-
catalogArg = args[1];
|
|
471
|
+
if (field === 'allowedValues' && !(value.type === 'ArrayExpression'
|
|
472
|
+
&& (value.elements || []).every((element) => !element || isLiteral(element)))) {
|
|
473
|
+
issues.push({ prop: propPath, field });
|
|
474
|
+
continue;
|
|
311
475
|
}
|
|
312
|
-
const catalog = await resolveCatalogArg(catalogArg);
|
|
313
|
-
mergeCatalog(registry, catalog, prefix);
|
|
314
|
-
}
|
|
315
|
-
}
|
|
316
|
-
|
|
317
|
-
return registry;
|
|
318
|
-
};
|
|
319
|
-
|
|
320
|
-
// Matches `<x>.events.<method>(...)` — covers slice.events / this.events (bind) / window.slice.events.
|
|
321
|
-
const isEventsMethodCallee = (callee, methods) => {
|
|
322
|
-
return (
|
|
323
|
-
callee &&
|
|
324
|
-
callee.type === 'MemberExpression' &&
|
|
325
|
-
methods.includes(keyNameFromAst(callee.property)) &&
|
|
326
|
-
callee.object &&
|
|
327
|
-
callee.object.type === 'MemberExpression' &&
|
|
328
|
-
keyNameFromAst(callee.object.property) === 'events'
|
|
329
|
-
);
|
|
330
|
-
};
|
|
331
|
-
|
|
332
|
-
// Nearest enclosing class name for a call site (the component/service that emits/listens).
|
|
333
|
-
const enclosingClassName = (pathRef) => {
|
|
334
|
-
const classPath = pathRef.findParent((p) => p.isClassDeclaration() || p.isClassExpression());
|
|
335
|
-
return classPath?.node?.id?.name || null;
|
|
336
|
-
};
|
|
337
|
-
|
|
338
|
-
// Static pub/sub graph: scan emit()/subscribe() call sites so emitters/listeners are
|
|
339
|
-
// documented WITHOUT executing the code (complements the observational runtime tracing).
|
|
340
|
-
// Returns { events: { name: { emitters:[], listeners:[] } }, dynamic: { emitters:[], listeners:[] } }.
|
|
341
|
-
const collectEventGraph = async ({ projectRoot }) => {
|
|
342
|
-
const srcDir = joinRoot(projectRoot, 'src');
|
|
343
|
-
const files = await collectJavaScriptFiles(srcDir);
|
|
344
|
-
const events = {};
|
|
345
|
-
const dynamic = { emitters: [], listeners: [] };
|
|
346
|
-
|
|
347
|
-
const bucketFor = (eventName, kind) => {
|
|
348
|
-
if (!events[eventName]) events[eventName] = { emitters: [], listeners: [] };
|
|
349
|
-
return events[eventName][kind];
|
|
350
|
-
};
|
|
351
|
-
|
|
352
|
-
for (const file of files) {
|
|
353
|
-
let source;
|
|
354
|
-
try {
|
|
355
|
-
source = await fs.readFile(file, 'utf8');
|
|
356
|
-
} catch {
|
|
357
|
-
continue;
|
|
358
|
-
}
|
|
359
|
-
if (!source.includes('.events.emit(') && !source.includes('.events.subscribe(') && !source.includes('.events.subscribeOnce(')) {
|
|
360
|
-
continue; // cheap prefilter
|
|
361
|
-
}
|
|
362
|
-
|
|
363
|
-
const ast = parseModule(source, file);
|
|
364
|
-
if (!ast) continue;
|
|
365
476
|
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
let kind = null;
|
|
372
|
-
if (isEventsMethodCallee(callee, ['emit'])) kind = 'emitters';
|
|
373
|
-
else if (isEventsMethodCallee(callee, ['subscribe', 'subscribeOnce'])) kind = 'listeners';
|
|
374
|
-
if (!kind) return;
|
|
375
|
-
|
|
376
|
-
const site = {
|
|
377
|
-
file: relFile,
|
|
378
|
-
line: pathRef.node.loc?.start?.line || 0,
|
|
379
|
-
component: enclosingClassName(pathRef)
|
|
380
|
-
};
|
|
381
|
-
|
|
382
|
-
const nameArg = pathRef.node.arguments[0];
|
|
383
|
-
if (nameArg && nameArg.type === 'StringLiteral') {
|
|
384
|
-
bucketFor(nameArg.value, kind).push(site);
|
|
385
|
-
} else {
|
|
386
|
-
dynamic[kind].push(site); // computed event name — can't be resolved statically
|
|
477
|
+
if (field === 'schema' || field === 'items') {
|
|
478
|
+
if (value.type !== 'ObjectExpression') {
|
|
479
|
+
// A computed map (`schema: SHARED`, `items: FIELD`): say which path.
|
|
480
|
+
issues.push({ prop: `${propPath}.${field}`, field: 'metadata' });
|
|
481
|
+
continue;
|
|
387
482
|
}
|
|
388
|
-
}
|
|
389
|
-
});
|
|
390
|
-
}
|
|
391
|
-
|
|
392
|
-
return { events, dynamic };
|
|
393
|
-
};
|
|
394
|
-
|
|
395
|
-
const sortKeys = (obj) => {
|
|
396
|
-
return Object.keys(obj)
|
|
397
|
-
.sort((a, b) => a.localeCompare(b))
|
|
398
|
-
.reduce((acc, key) => {
|
|
399
|
-
acc[key] = obj[key];
|
|
400
|
-
return acc;
|
|
401
|
-
}, {});
|
|
402
|
-
};
|
|
403
|
-
|
|
404
|
-
const parseComponentsRegistry = (content, filePath) => {
|
|
405
|
-
const match = content.match(/const components = ({[\s\S]*?});/);
|
|
406
|
-
if (!match) {
|
|
407
|
-
throw new Error(`Invalid format in ${filePath}. Expected: const components = { ... };`);
|
|
408
|
-
}
|
|
409
|
-
try {
|
|
410
|
-
return JSON.parse(match[1]);
|
|
411
|
-
} catch (parseError) {
|
|
412
|
-
throw new Error(`Failed to parse components registry in ${filePath}: ${parseError.message}`);
|
|
413
|
-
}
|
|
414
|
-
};
|
|
415
483
|
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
plugins: ['classProperties']
|
|
422
|
-
});
|
|
423
|
-
} catch (parseError) {
|
|
424
|
-
const sourceDesc = filePath || 'unknown file';
|
|
425
|
-
const loc = parseError.loc ? ` at line ${parseError.loc.line}, column ${parseError.loc.column}` : '';
|
|
426
|
-
Print.warning(`Parse error in ${sourceDesc}${loc}: ${parseError.message}`);
|
|
427
|
-
return null;
|
|
428
|
-
}
|
|
484
|
+
if (field === 'items') {
|
|
485
|
+
// `items` is a single prop config, not a map of them.
|
|
486
|
+
inspectConfig(`${propPath}.items`, value);
|
|
487
|
+
continue;
|
|
488
|
+
}
|
|
429
489
|
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
if (!node.static || !node.key || keyNameFromAst(node.key) !== 'props') return;
|
|
435
|
-
if (node.value && node.value.type === 'ObjectExpression') {
|
|
436
|
-
staticPropsObject = node.value;
|
|
490
|
+
for (const nested of value.properties || []) {
|
|
491
|
+
if (nested.type !== 'ObjectProperty') continue;
|
|
492
|
+
inspectConfig(`${propPath}.${keyNameFromAst(nested.key)}`, nested.value);
|
|
493
|
+
}
|
|
437
494
|
}
|
|
438
495
|
}
|
|
439
|
-
}
|
|
440
|
-
|
|
441
|
-
if (!staticPropsObject) return null;
|
|
442
|
-
return extractStaticPropsFromObjectExpression(staticPropsObject);
|
|
443
|
-
};
|
|
444
|
-
|
|
445
|
-
const typeFromProp = (propMeta) => {
|
|
446
|
-
if (propMeta.type === 'object' && propMeta.schema && typeof propMeta.schema === 'object') {
|
|
447
|
-
const schemaEntries = Object.entries(sortKeys(propMeta.schema));
|
|
448
|
-
const inner = schemaEntries
|
|
449
|
-
.map(([name, meta]) => {
|
|
450
|
-
const optionalMark = meta.required ? '' : '?';
|
|
451
|
-
return `${name}${optionalMark}: ${typeFromProp(meta)};`;
|
|
452
|
-
})
|
|
453
|
-
.join(' ');
|
|
454
|
-
return `{ ${inner} }`;
|
|
455
|
-
}
|
|
456
|
-
|
|
457
|
-
if (propMeta.type === 'array' && propMeta.items && typeof propMeta.items === 'object') {
|
|
458
|
-
return `${typeFromProp(propMeta.items)}[]`;
|
|
459
|
-
}
|
|
460
|
-
|
|
461
|
-
const allowedValues = Array.isArray(propMeta.allowedValues) ? propMeta.allowedValues : [];
|
|
462
|
-
|
|
463
|
-
if (allowedValues.length > 0 && propMeta.type === 'string' && allowedValues.every((value) => typeof value === 'string')) {
|
|
464
|
-
return allowedValues.map((value) => `'${String(value).replace(/'/g, "\\'")}'`).join(' | ');
|
|
465
|
-
}
|
|
496
|
+
};
|
|
466
497
|
|
|
467
|
-
|
|
468
|
-
|
|
498
|
+
for (const property of propsObject.properties || []) {
|
|
499
|
+
if (property.type !== 'ObjectProperty') continue;
|
|
500
|
+
inspectConfig(keyNameFromAst(property.key), property.value);
|
|
469
501
|
}
|
|
470
502
|
|
|
471
|
-
return
|
|
503
|
+
return issues;
|
|
472
504
|
};
|
|
473
505
|
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
}
|
|
511
|
-
|
|
512
|
-
|
|
506
|
+
const extractStaticPropsFromSource = (source, filePath) => {
|
|
507
|
+
let ast;
|
|
508
|
+
try {
|
|
509
|
+
ast = parse(source, {
|
|
510
|
+
sourceType: 'module',
|
|
511
|
+
plugins: ['classProperties']
|
|
512
|
+
});
|
|
513
|
+
} catch (parseError) {
|
|
514
|
+
const sourceDesc = filePath || 'unknown file';
|
|
515
|
+
const loc = parseError.loc ? ` at line ${parseError.loc.line}, column ${parseError.loc.column}` : '';
|
|
516
|
+
Print.warning(`Parse error in ${sourceDesc}${loc}: ${parseError.message}`);
|
|
517
|
+
return null;
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
let staticPropsObject = null;
|
|
521
|
+
traverse.default(ast, {
|
|
522
|
+
ClassProperty(pathRef) {
|
|
523
|
+
const node = pathRef.node;
|
|
524
|
+
if (!node.static || !node.key || keyNameFromAst(node.key) !== 'props') return;
|
|
525
|
+
if (node.value && node.value.type === 'ObjectExpression') {
|
|
526
|
+
staticPropsObject = node.value;
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
});
|
|
530
|
+
|
|
531
|
+
if (!staticPropsObject) return null;
|
|
532
|
+
return extractStaticPropsFromObjectExpression(staticPropsObject);
|
|
533
|
+
};
|
|
534
|
+
|
|
535
|
+
const typeFromProp = (propMeta) => {
|
|
536
|
+
if (propMeta.type === 'object' && propMeta.schema && typeof propMeta.schema === 'object') {
|
|
537
|
+
const schemaEntries = Object.entries(sortKeys(propMeta.schema));
|
|
538
|
+
const inner = schemaEntries
|
|
539
|
+
.map(([name, meta]) => {
|
|
540
|
+
const optionalMark = meta.required ? '' : '?';
|
|
541
|
+
return `${name}${optionalMark}: ${typeFromProp(meta)};`;
|
|
542
|
+
})
|
|
543
|
+
.join(' ');
|
|
544
|
+
return `{ ${inner} }`;
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
if (propMeta.type === 'array' && propMeta.items && typeof propMeta.items === 'object') {
|
|
548
|
+
return `${typeFromProp(propMeta.items)}[]`;
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
const allowedValues = Array.isArray(propMeta.allowedValues) ? propMeta.allowedValues : [];
|
|
552
|
+
|
|
553
|
+
if (allowedValues.length > 0 && propMeta.type === 'string' && allowedValues.every((value) => typeof value === 'string')) {
|
|
554
|
+
return allowedValues.map((value) => `'${String(value).replace(/'/g, "\\'")}'`).join(' | ');
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
if (allowedValues.length > 0 && propMeta.type === 'number' && allowedValues.every((value) => typeof value === 'number' && Number.isFinite(value))) {
|
|
558
|
+
return allowedValues.join(' | ');
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
return TYPE_MAP[propMeta.type] || 'unknown';
|
|
562
|
+
};
|
|
563
|
+
|
|
564
|
+
/**
|
|
565
|
+
* True when `name` can be written as a bare TypeScript property key or
|
|
566
|
+
* identifier. Anything else has to be quoted (or escaped, for a type name).
|
|
567
|
+
* @param {string} name
|
|
568
|
+
* @returns {boolean}
|
|
569
|
+
*/
|
|
570
|
+
const isSafeTsIdentifier = (name) => /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(String(name));
|
|
571
|
+
|
|
572
|
+
/**
|
|
573
|
+
* Property key for a declaration line: bare when it can be, quoted otherwise.
|
|
574
|
+
* `data-id` and `my-btn` are legal keys but only in quoted form; emitting them
|
|
575
|
+
* bare produced a .d.ts that does not parse, which silently took out editor
|
|
576
|
+
* tooling for the whole project (jsconfig includes the generated file).
|
|
577
|
+
* @param {string} name
|
|
578
|
+
* @returns {string}
|
|
579
|
+
*/
|
|
580
|
+
const tsPropertyKey = (name) => (isSafeTsIdentifier(name) ? String(name) : JSON.stringify(String(name)));
|
|
581
|
+
|
|
582
|
+
/**
|
|
583
|
+
* Interface name for a component.
|
|
584
|
+
*
|
|
585
|
+
* A component's registered name need not be a valid identifier — `my-btn` used
|
|
586
|
+
* to yield `export interface my-btnProps`, which is a syntax error. Characters
|
|
587
|
+
* outside [A-Za-z0-9_$] are hex-escaped rather than dropped, so two distinct
|
|
588
|
+
* component names can never collapse onto the same interface (the same reason
|
|
589
|
+
* BundleGenerator.toSafeIdentifier escapes instead of replacing).
|
|
590
|
+
*
|
|
591
|
+
* @param {string} componentName
|
|
592
|
+
* @returns {string}
|
|
593
|
+
*/
|
|
594
|
+
const interfaceNameFor = (componentName) => {
|
|
595
|
+
const raw = String(componentName);
|
|
596
|
+
if (isSafeTsIdentifier(raw)) return `${raw}Props`;
|
|
597
|
+
const encoded = raw.replace(/[^A-Za-z0-9_$]/g, (char) => `_${char.charCodeAt(0).toString(16)}_`);
|
|
598
|
+
// Prefixed so a name starting with a digit still yields a valid identifier.
|
|
599
|
+
return `SliceComponent_${encoded}Props`;
|
|
600
|
+
};
|
|
601
|
+
const DYNAMIC_FALLBACK_PROP = '__dynamicPropsFallback';
|
|
602
|
+
|
|
513
603
|
const DEFAULT_EDITOR_COMPILER_OPTIONS = {
|
|
514
604
|
allowJs: true,
|
|
515
605
|
checkJs: true,
|
|
606
|
+
noEmit: true,
|
|
607
|
+
target: 'ES2022',
|
|
608
|
+
lib: ['ES2022', 'DOM', 'DOM.Iterable'],
|
|
609
|
+
module: 'ESNext',
|
|
610
|
+
moduleResolution: 'Bundler',
|
|
516
611
|
strict: false,
|
|
517
612
|
noImplicitAny: false,
|
|
518
613
|
strictNullChecks: false,
|
|
519
|
-
|
|
520
|
-
};
|
|
521
|
-
|
|
522
|
-
const DEFAULT_EDITOR_INCLUDE = [
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
const
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
await fs.
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
lines.push('
|
|
608
|
-
lines.push('
|
|
609
|
-
lines.push('
|
|
610
|
-
lines.push('
|
|
611
|
-
|
|
612
|
-
lines.push('
|
|
613
|
-
lines.push('
|
|
614
|
-
lines.push('');
|
|
615
|
-
lines.push('
|
|
616
|
-
lines.push('
|
|
617
|
-
lines.push('
|
|
618
|
-
lines.push('
|
|
619
|
-
lines.push('
|
|
620
|
-
lines.push('
|
|
621
|
-
lines.push('
|
|
622
|
-
lines.push('');
|
|
623
|
-
lines.push('
|
|
624
|
-
lines.push('
|
|
625
|
-
lines.push('
|
|
626
|
-
lines.push('
|
|
627
|
-
lines.push('
|
|
628
|
-
lines.push('
|
|
629
|
-
lines.push('
|
|
630
|
-
lines.push('
|
|
631
|
-
lines.push('
|
|
632
|
-
lines.push('
|
|
633
|
-
lines.push('
|
|
634
|
-
lines.push('
|
|
635
|
-
lines.push('
|
|
636
|
-
lines.push('
|
|
637
|
-
lines.push('
|
|
638
|
-
lines.push('
|
|
639
|
-
lines.push('');
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
}
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
lines.push(
|
|
669
|
-
}
|
|
670
|
-
|
|
671
|
-
lines.push('');
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
lines.push('
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
lines.push(
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
lines.push('
|
|
689
|
-
lines.push('
|
|
690
|
-
lines.push('
|
|
691
|
-
lines.push('
|
|
692
|
-
lines.push('
|
|
693
|
-
lines.push('
|
|
694
|
-
lines.push('');
|
|
695
|
-
lines.push('
|
|
696
|
-
|
|
697
|
-
lines.push('
|
|
698
|
-
lines.push(' }');
|
|
699
|
-
lines.push('
|
|
700
|
-
lines.push('
|
|
701
|
-
|
|
702
|
-
lines.push('
|
|
703
|
-
lines.push('
|
|
704
|
-
lines.push('
|
|
705
|
-
lines.push('');
|
|
706
|
-
lines.push('
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
}
|
|
710
|
-
lines.push('
|
|
711
|
-
lines.push('
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
lines.push('
|
|
718
|
-
lines.push('
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
lines.push('
|
|
723
|
-
lines.push('
|
|
724
|
-
lines.push('
|
|
725
|
-
lines.push(
|
|
726
|
-
lines.push('
|
|
727
|
-
lines.push('
|
|
728
|
-
lines.push('
|
|
729
|
-
lines.push('
|
|
730
|
-
lines.push('
|
|
731
|
-
lines.push('
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
lines.push('
|
|
736
|
-
lines.push('
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
const
|
|
755
|
-
const
|
|
756
|
-
|
|
757
|
-
const
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
614
|
+
skipLibCheck: true
|
|
615
|
+
};
|
|
616
|
+
|
|
617
|
+
const DEFAULT_EDITOR_INCLUDE = [
|
|
618
|
+
'src/Components/**/*.js',
|
|
619
|
+
'src/App/**/*.js',
|
|
620
|
+
'src/routes.js',
|
|
621
|
+
'src/**/*.d.ts'
|
|
622
|
+
];
|
|
623
|
+
const DEFAULT_EDITOR_EXCLUDE = ['node_modules', 'dist', 'src/libs/**', 'tests/**', '**/*.spec.js'];
|
|
624
|
+
const NOISY_INCLUDE_PATTERNS = new Set(['src/**/*.js', 'api/**/*.js', 'tests/**/*.js']);
|
|
625
|
+
|
|
626
|
+
// Vendored static assets live under src/public/. Exclude them from type-check
|
|
627
|
+
// coverage (they aren't app source).
|
|
628
|
+
const readPublicFolderExcludes = async (projectRoot) => {
|
|
629
|
+
if (await fs.pathExists(joinRoot(projectRoot, 'src', 'public'))) {
|
|
630
|
+
return ['src/public/**'];
|
|
631
|
+
}
|
|
632
|
+
return [];
|
|
633
|
+
};
|
|
634
|
+
|
|
635
|
+
const collectJavaScriptFiles = async (dirPath) => {
|
|
636
|
+
if (!(await fs.pathExists(dirPath))) return [];
|
|
637
|
+
const entries = await fs.readdir(dirPath, { withFileTypes: true });
|
|
638
|
+
const files = [];
|
|
639
|
+
|
|
640
|
+
for (const entry of entries) {
|
|
641
|
+
const fullPath = path.join(dirPath, entry.name);
|
|
642
|
+
if (entry.isDirectory()) {
|
|
643
|
+
const nested = await collectJavaScriptFiles(fullPath);
|
|
644
|
+
files.push(...nested);
|
|
645
|
+
} else if (entry.isFile() && entry.name.toLowerCase().endsWith('.js')) {
|
|
646
|
+
files.push(fullPath);
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
return files;
|
|
651
|
+
};
|
|
652
|
+
|
|
653
|
+
const ensureNoCheckInPublicVendorFiles = async (projectRoot) => {
|
|
654
|
+
const configPath = getConfigPath(import.meta.url, projectRoot);
|
|
655
|
+
if (!(await fs.pathExists(configPath))) return { updatedFiles: 0, scannedFiles: 0 };
|
|
656
|
+
|
|
657
|
+
let parsed;
|
|
658
|
+
try {
|
|
659
|
+
parsed = JSON.parse(await fs.readFile(configPath, 'utf8'));
|
|
660
|
+
} catch {
|
|
661
|
+
return { updatedFiles: 0, scannedFiles: 0 };
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
// Vendored JS under src/public/ gets // @ts-nocheck so it isn't type-checked.
|
|
665
|
+
const candidateDirs = [];
|
|
666
|
+
const publicDir = joinRoot(projectRoot, 'src', 'public');
|
|
667
|
+
if (await fs.pathExists(publicDir)) candidateDirs.push(publicDir);
|
|
668
|
+
|
|
669
|
+
const uniqueDirs = Array.from(new Set(candidateDirs));
|
|
670
|
+
let scannedFiles = 0;
|
|
671
|
+
let updatedFiles = 0;
|
|
672
|
+
|
|
673
|
+
for (const dirPath of uniqueDirs) {
|
|
674
|
+
const jsFiles = await collectJavaScriptFiles(dirPath);
|
|
675
|
+
for (const filePath of jsFiles) {
|
|
676
|
+
scannedFiles += 1;
|
|
677
|
+
const raw = await fs.readFile(filePath, 'utf8');
|
|
678
|
+
if (raw.startsWith('// @ts-nocheck')) {
|
|
679
|
+
continue;
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
await fs.writeFile(filePath, `// @ts-nocheck\n${raw}`, 'utf8');
|
|
683
|
+
updatedFiles += 1;
|
|
684
|
+
}
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
return { updatedFiles, scannedFiles };
|
|
688
|
+
};
|
|
689
|
+
|
|
690
|
+
const generateEventRegistryLines = (eventRegistry) => {
|
|
691
|
+
const events = sortKeys(eventRegistry || {});
|
|
692
|
+
const names = Object.keys(events);
|
|
693
|
+
if (names.length === 0) return [];
|
|
694
|
+
|
|
695
|
+
const lines = [];
|
|
696
|
+
lines.push('export interface SliceEventRegistry {');
|
|
697
|
+
for (const name of names) {
|
|
698
|
+
// JSON.stringify, not a hand-rolled quote: an event name containing a quote
|
|
699
|
+
// would otherwise terminate the string early.
|
|
700
|
+
lines.push(` ${JSON.stringify(name)}: ${payloadToTs(events[name].payload)};`);
|
|
701
|
+
}
|
|
702
|
+
lines.push('}');
|
|
703
|
+
lines.push('');
|
|
704
|
+
lines.push('type SliceEventCatalog = Record<string, { description?: string; payload?: unknown }>;');
|
|
705
|
+
lines.push('');
|
|
706
|
+
// Single conditional-type signatures (not overload pairs): for a KNOWN event');
|
|
707
|
+
lines.push('// name the payload is enforced; for any other (unknown / framework / dynamic');
|
|
708
|
+
lines.push('// context:* events) it stays permissive. A plain string-fallback overload');
|
|
709
|
+
lines.push('// would swallow wrong-payload calls and defeat the whole point.');
|
|
710
|
+
lines.push('type SliceEventData<K extends string> = K extends keyof SliceEventRegistry ? SliceEventRegistry[K] : unknown;');
|
|
711
|
+
lines.push('type SliceEventArgs<K extends string> = K extends keyof SliceEventRegistry');
|
|
712
|
+
lines.push(' ? (SliceEventRegistry[K] extends void ? [] : [SliceEventRegistry[K]])');
|
|
713
|
+
lines.push(' : unknown[];');
|
|
714
|
+
lines.push('');
|
|
715
|
+
lines.push('export interface SliceTypedEventBinding {');
|
|
716
|
+
lines.push(' subscribe<K extends string>(eventName: K, callback: (data: SliceEventData<K>) => void): string | null;');
|
|
717
|
+
lines.push(' subscribeOnce<K extends string>(eventName: K, callback: (data: SliceEventData<K>) => void): string | null;');
|
|
718
|
+
lines.push(' emit<K extends string>(eventName: K, ...data: SliceEventArgs<K>): void;');
|
|
719
|
+
lines.push(' register(namespace: string, catalog: SliceEventCatalog): unknown;');
|
|
720
|
+
lines.push(' register(catalog: SliceEventCatalog): unknown;');
|
|
721
|
+
lines.push('}');
|
|
722
|
+
lines.push('');
|
|
723
|
+
lines.push('export interface SliceTypedEventManager {');
|
|
724
|
+
lines.push(' init(): boolean;');
|
|
725
|
+
lines.push(' subscribe<K extends string>(eventName: K, callback: (data: SliceEventData<K>) => void, options?: { component?: HTMLElement }): string | null;');
|
|
726
|
+
lines.push(' subscribeOnce<K extends string>(eventName: K, callback: (data: SliceEventData<K>) => void, options?: { component?: HTMLElement }): string | null;');
|
|
727
|
+
lines.push(' unsubscribe(eventName: string, subscriptionId: string): boolean;');
|
|
728
|
+
lines.push(' emit<K extends string>(eventName: K, ...data: SliceEventArgs<K>): void;');
|
|
729
|
+
lines.push(' bind(component: HTMLElement): SliceTypedEventBinding | null;');
|
|
730
|
+
lines.push(' cleanupComponent(sliceId: string): number;');
|
|
731
|
+
lines.push(' hasSubscribers(eventName: string): boolean;');
|
|
732
|
+
lines.push(' subscriberCount(eventName: string): number;');
|
|
733
|
+
lines.push(' isDeclared(eventName: string): boolean;');
|
|
734
|
+
lines.push(' namespaceOf(eventName: string): string | null;');
|
|
735
|
+
lines.push(' register(namespace: string, catalog: SliceEventCatalog): SliceTypedEventManager;');
|
|
736
|
+
lines.push(' register(catalog: SliceEventCatalog): SliceTypedEventManager;');
|
|
737
|
+
lines.push(' clear(): void;');
|
|
738
|
+
lines.push('}');
|
|
739
|
+
lines.push('');
|
|
740
|
+
return lines;
|
|
741
|
+
};
|
|
742
|
+
|
|
743
|
+
const generateDeclarationContent = (componentPropsMap, eventRegistry = {}) => {
|
|
744
|
+
const componentsSorted = sortKeys(componentPropsMap);
|
|
745
|
+
const hasEvents = Object.keys(eventRegistry || {}).length > 0;
|
|
746
|
+
const lines = [];
|
|
747
|
+
|
|
748
|
+
lines.push('/* Auto-generated by slice types generate. Do not edit manually. */');
|
|
749
|
+
lines.push('');
|
|
750
|
+
|
|
751
|
+
for (const [componentName, props] of Object.entries(componentsSorted)) {
|
|
752
|
+
lines.push(`export interface ${interfaceNameFor(componentName)} {`);
|
|
753
|
+
lines.push(' [key: string]: unknown;');
|
|
754
|
+
const sortedProps = sortKeys(props);
|
|
755
|
+
const isDynamicFallback = Object.keys(sortedProps).length === 1 && sortedProps[DYNAMIC_FALLBACK_PROP];
|
|
756
|
+
if (!isDynamicFallback) {
|
|
757
|
+
for (const [propName, propMeta] of Object.entries(sortedProps)) {
|
|
758
|
+
const optionalMark = propMeta.required ? '' : '?';
|
|
759
|
+
lines.push(` ${tsPropertyKey(propName)}${optionalMark}: ${typeFromProp(propMeta)};`);
|
|
760
|
+
}
|
|
761
|
+
}
|
|
762
|
+
lines.push('}');
|
|
763
|
+
lines.push('');
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
lines.push('export interface SliceComponentPropsMap {');
|
|
767
|
+
for (const componentName of Object.keys(componentsSorted)) {
|
|
768
|
+
lines.push(` ${tsPropertyKey(componentName)}: ${interfaceNameFor(componentName)};`);
|
|
769
|
+
}
|
|
770
|
+
lines.push('}');
|
|
771
|
+
lines.push('');
|
|
772
|
+
lines.push('export type SliceComponentName = keyof SliceComponentPropsMap;');
|
|
773
|
+
lines.push('export type SliceDynamicElement = HTMLElement & Record<string, any>;');
|
|
774
|
+
lines.push('');
|
|
775
|
+
if (hasEvents) {
|
|
776
|
+
lines.push(...generateEventRegistryLines(eventRegistry));
|
|
777
|
+
}
|
|
778
|
+
lines.push('declare global {');
|
|
779
|
+
// When typed events exist we declare slice with an index-signature interface so
|
|
780
|
+
// that explicit members (build, events) keep their precise type while dynamic
|
|
781
|
+
// access (slice.anything) stays `any` — `& Record<string, any>` would otherwise
|
|
782
|
+
// collapse slice.events to `any`.
|
|
783
|
+
lines.push(` const slice: SliceBuildApi${hasEvents ? '' : ' & Record<string, any>'};`);
|
|
784
|
+
lines.push('');
|
|
785
|
+
lines.push(' interface Event {');
|
|
786
|
+
lines.push(' detail: any;');
|
|
787
|
+
lines.push(' key: any;');
|
|
788
|
+
lines.push(' request: any;');
|
|
789
|
+
lines.push(' waitUntil: any;');
|
|
790
|
+
lines.push(' respondWith: any;');
|
|
791
|
+
lines.push(' target: any;');
|
|
792
|
+
lines.push(' currentTarget: any;');
|
|
793
|
+
lines.push(' }');
|
|
794
|
+
lines.push('');
|
|
795
|
+
lines.push(' interface Element {');
|
|
796
|
+
lines.push(' querySelector<E extends Element = HTMLElement>(selectors: string): E | null;');
|
|
797
|
+
lines.push(' querySelectorAll<E extends Element = HTMLElement>(selectors: string): NodeListOf<E>;');
|
|
798
|
+
lines.push(' }');
|
|
799
|
+
lines.push(' interface HTMLElement {');
|
|
800
|
+
lines.push(' [key: string]: any;');
|
|
801
|
+
lines.push(' }');
|
|
802
|
+
lines.push(' interface EventTarget {');
|
|
803
|
+
lines.push(' [key: string]: any;');
|
|
804
|
+
lines.push(' }');
|
|
805
|
+
lines.push('');
|
|
806
|
+
lines.push(' interface SliceBuildApi {');
|
|
807
|
+
if (hasEvents) {
|
|
808
|
+
lines.push(' [key: string]: any;');
|
|
809
|
+
}
|
|
810
|
+
lines.push(' build<K extends SliceComponentName>(');
|
|
811
|
+
lines.push(' name: K,');
|
|
812
|
+
lines.push(' props?: SliceComponentPropsMap[K]');
|
|
813
|
+
lines.push(' ): Promise<SliceDynamicElement | null>;');
|
|
814
|
+
if (hasEvents) {
|
|
815
|
+
lines.push(' events: SliceTypedEventManager;');
|
|
816
|
+
}
|
|
817
|
+
lines.push(' }');
|
|
818
|
+
lines.push('}');
|
|
819
|
+
lines.push('');
|
|
820
|
+
lines.push("declare module 'slicejs-web-framework' {");
|
|
821
|
+
lines.push(' interface SliceApi {');
|
|
822
|
+
lines.push(' build<K extends SliceComponentName>(');
|
|
823
|
+
lines.push(' name: K,');
|
|
824
|
+
lines.push(' props?: SliceComponentPropsMap[K]');
|
|
825
|
+
lines.push(' ): Promise<SliceDynamicElement | null>;');
|
|
826
|
+
lines.push(' getComponent<K extends SliceComponentName>(');
|
|
827
|
+
lines.push(' componentSliceId: K | `${K}-${string}`');
|
|
828
|
+
lines.push(' ): SliceDynamicElement | undefined;');
|
|
829
|
+
lines.push(' getComponent<T extends SliceDynamicElement = SliceDynamicElement>(');
|
|
830
|
+
lines.push(' componentSliceId: string');
|
|
831
|
+
lines.push(' ): T | undefined;');
|
|
832
|
+
if (hasEvents) {
|
|
833
|
+
lines.push(' events: SliceTypedEventManager;');
|
|
834
|
+
}
|
|
835
|
+
lines.push(' }');
|
|
836
|
+
lines.push('}');
|
|
837
|
+
lines.push('');
|
|
838
|
+
lines.push('export {};');
|
|
839
|
+
lines.push('');
|
|
840
|
+
|
|
841
|
+
return lines.join('\n');
|
|
842
|
+
};
|
|
843
|
+
|
|
844
|
+
/**
|
|
845
|
+
* Component folders that exist under a configured category but have no
|
|
846
|
+
* `<Name>/<Name>.js`. The registry is generated from the folders, so these are
|
|
847
|
+
* broken registrations even though nothing imports them yet.
|
|
848
|
+
*/
|
|
849
|
+
const findComponentFoldersWithoutFile = async ({ projectRoot, componentPaths }) => {
|
|
850
|
+
const missing = [];
|
|
851
|
+
|
|
852
|
+
for (const [category, entry] of Object.entries(componentPaths || {})) {
|
|
853
|
+
if (!entry?.path) continue;
|
|
854
|
+
const categoryDir = joinRoot(projectRoot, 'src', String(entry.path).replace(/^[/\\]+/, ''));
|
|
855
|
+
|
|
856
|
+
let items;
|
|
857
|
+
try {
|
|
858
|
+
items = await fs.readdir(categoryDir, { withFileTypes: true });
|
|
859
|
+
} catch {
|
|
860
|
+
continue; // a missing category folder is a config problem, not this one
|
|
861
|
+
}
|
|
862
|
+
|
|
863
|
+
for (const item of items) {
|
|
864
|
+
if (!item.isDirectory()) continue;
|
|
865
|
+
const componentFile = path.join(categoryDir, item.name, `${item.name}.js`);
|
|
866
|
+
if (!(await fs.pathExists(componentFile))) {
|
|
867
|
+
missing.push({ category, component: item.name, file: componentFile });
|
|
868
|
+
}
|
|
869
|
+
}
|
|
870
|
+
}
|
|
871
|
+
|
|
872
|
+
return missing;
|
|
873
|
+
};
|
|
874
|
+
|
|
875
|
+
const readCategoryPathFromConfig = async (configPath, category) => {
|
|
876
|
+
const raw = await fs.readFile(configPath, 'utf8');
|
|
877
|
+
const config = JSON.parse(raw);
|
|
878
|
+
const categoryEntry = config?.paths?.components?.[category];
|
|
879
|
+
if (!categoryEntry || !categoryEntry.path) {
|
|
880
|
+
return null;
|
|
881
|
+
}
|
|
882
|
+
return categoryEntry.path.replace(/^[/\\]+/, '');
|
|
883
|
+
};
|
|
884
|
+
|
|
885
|
+
const loadComponentStaticProps = async ({ projectRoot, registryMap }) => {
|
|
886
|
+
const configPath = getConfigPath(import.meta.url, projectRoot);
|
|
887
|
+
const categoryPathCache = new Map();
|
|
888
|
+
const componentPropsMap = {};
|
|
889
|
+
let skippedCount = 0;
|
|
890
|
+
let processedCount = 0;
|
|
891
|
+
|
|
892
|
+
for (const [componentName, category] of Object.entries(sortKeys(registryMap))) {
|
|
893
|
+
if (!categoryPathCache.has(category)) {
|
|
894
|
+
const categoryPath = await readCategoryPathFromConfig(configPath, category);
|
|
895
|
+
categoryPathCache.set(category, categoryPath);
|
|
896
|
+
}
|
|
897
|
+
|
|
898
|
+
const categoryPath = categoryPathCache.get(category);
|
|
899
|
+
if (!categoryPath) {
|
|
900
|
+
skippedCount++;
|
|
901
|
+
continue;
|
|
902
|
+
}
|
|
903
|
+
|
|
904
|
+
const componentFile = joinRoot(projectRoot, 'src', categoryPath, componentName, `${componentName}.js`);
|
|
905
|
+
if (!(await fs.pathExists(componentFile))) {
|
|
906
|
+
skippedCount++;
|
|
907
|
+
continue;
|
|
908
|
+
}
|
|
909
|
+
|
|
910
|
+
let source;
|
|
911
|
+
try {
|
|
912
|
+
source = await fs.readFile(componentFile, 'utf8');
|
|
913
|
+
} catch (readError) {
|
|
914
|
+
Print.warning(`Cannot read ${componentFile}: ${readError.message}`);
|
|
915
|
+
skippedCount++;
|
|
916
|
+
continue;
|
|
917
|
+
}
|
|
918
|
+
|
|
919
|
+
const props = extractStaticPropsFromSource(source, componentFile);
|
|
920
|
+
if (props) {
|
|
921
|
+
componentPropsMap[componentName] = props;
|
|
922
|
+
processedCount++;
|
|
923
|
+
} else {
|
|
924
|
+
componentPropsMap[componentName] = { [DYNAMIC_FALLBACK_PROP]: { type: 'any', required: false } };
|
|
925
|
+
}
|
|
926
|
+
|
|
927
|
+
// Anything computed in the metadata is invisible to this generator: warn
|
|
928
|
+
// instead of silently emitting `any`.
|
|
929
|
+
for (const issue of findComputedPropFields(source)) {
|
|
930
|
+
const field = issue.field === 'metadata' ? 'definition' : issue.field;
|
|
931
|
+
Print.warning(`${componentName}.${issue.prop}: ${field} is computed, not a literal — the generated type falls back to any`);
|
|
932
|
+
}
|
|
933
|
+
}
|
|
934
|
+
|
|
935
|
+
if (skippedCount > 0) {
|
|
936
|
+
Print.info(`Skipped ${skippedCount} component(s) with missing or unreadable files`);
|
|
937
|
+
}
|
|
938
|
+
|
|
939
|
+
return componentPropsMap;
|
|
940
|
+
};
|
|
941
|
+
|
|
804
942
|
const PROP_VALID_TYPES = new Set(['string', 'number', 'boolean', 'object', 'array', 'function', 'any']);
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
*
|
|
812
|
-
*
|
|
813
|
-
*
|
|
814
|
-
*
|
|
815
|
-
*
|
|
816
|
-
*
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
*
|
|
820
|
-
*
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
*
|
|
824
|
-
*
|
|
825
|
-
*
|
|
826
|
-
*
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
const
|
|
835
|
-
//
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
const
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
if (
|
|
882
|
-
|
|
943
|
+
// Build directives, stripped from props before setters run. Declaring one as a
|
|
944
|
+
// prop is a silent no-op: the value never reaches the component. Found by the
|
|
945
|
+
// Conclave lint audit (0 uses in 338 components, so it guards future mistakes).
|
|
946
|
+
const RESERVED_PROP_NAMES = new Set(['id', 'sliceId', 'singleton']);
|
|
947
|
+
|
|
948
|
+
/**
|
|
949
|
+
* Validates every registered component's static props. Shared by `slice doctor`
|
|
950
|
+
* and `slice build`.
|
|
951
|
+
*
|
|
952
|
+
* Returns issues split by severity:
|
|
953
|
+
* - errors: the definition is wrong and will misbehave at runtime
|
|
954
|
+
* (unknown type, schema/items/allowedValues type mismatch).
|
|
955
|
+
* - warnings: style / best-practice (type "any", required-without-default).
|
|
956
|
+
*
|
|
957
|
+
* @param {{ projectRoot: string }} options
|
|
958
|
+
* @returns {Promise<{ errors: Array, warnings: Array, checkedCount: number }>}
|
|
959
|
+
*/
|
|
960
|
+
/**
|
|
961
|
+
* Walks every component registered in components.js.
|
|
962
|
+
*
|
|
963
|
+
* Note this covers MORE than the bundler does: the bundler only ever sees
|
|
964
|
+
* components reachable from a route, so a registered-but-unused component with a
|
|
965
|
+
* syntax error, a missing default export or a broken import was never checked
|
|
966
|
+
* anywhere — it failed the first time somebody navigated to it.
|
|
967
|
+
*
|
|
968
|
+
* @returns {Promise<{errors: object[], warnings: object[], sourceErrors: object[], checkedCount: number}>}
|
|
969
|
+
*/
|
|
970
|
+
const validateComponentProps = async ({ projectRoot, includeCss = true }) => {
|
|
971
|
+
const errors = [];
|
|
972
|
+
const warnings = [];
|
|
973
|
+
// Problems with the file itself rather than with a prop definition. Kept
|
|
974
|
+
// separate because they are reported differently (they carry a file and a
|
|
975
|
+
// position, not a prop name).
|
|
976
|
+
const sourceErrors = [];
|
|
977
|
+
// Reported but not blocking — see findUnknownComponentBuilds below.
|
|
978
|
+
const sourceWarnings = [];
|
|
979
|
+
let checkedCount = 0;
|
|
980
|
+
|
|
981
|
+
const registryPath = getComponentsJsPath(import.meta.url, projectRoot);
|
|
982
|
+
let registryContent;
|
|
983
|
+
try {
|
|
984
|
+
registryContent = await fs.readFile(registryPath, 'utf8');
|
|
985
|
+
} catch {
|
|
986
|
+
return { errors, warnings, sourceErrors, sourceWarnings, checkedCount, registeredCount: 0 }; // no registry → nothing to validate
|
|
987
|
+
}
|
|
988
|
+
|
|
989
|
+
const registryMap = parseComponentsRegistry(registryContent, registryPath);
|
|
990
|
+
const registeredNames = new Set(Object.keys(registryMap));
|
|
991
|
+
const registeredCount = registeredNames.size;
|
|
992
|
+
const configPath = getConfigPath(import.meta.url, projectRoot);
|
|
993
|
+
|
|
994
|
+
// One read for the whole pass: the prop loop needs a category path and the
|
|
995
|
+
// folder scan below needs every category. Config problems themselves are
|
|
996
|
+
// reported by the doctor's Configuration row, not here.
|
|
997
|
+
let componentPaths = null;
|
|
998
|
+
try {
|
|
999
|
+
const config = JSON.parse(await fs.readFile(configPath, 'utf8'));
|
|
1000
|
+
componentPaths = config?.paths?.components || null;
|
|
1001
|
+
} catch { /* reported elsewhere */ }
|
|
1002
|
+
|
|
1003
|
+
const categoryPath = (category) => {
|
|
1004
|
+
const entry = componentPaths?.[category];
|
|
1005
|
+
return entry?.path ? String(entry.path).replace(/^[/\\]+/, '') : null;
|
|
1006
|
+
};
|
|
1007
|
+
|
|
1008
|
+
// A configured category whose folder is missing. Reported once per category
|
|
1009
|
+
// (per-component errors would bury the cause), and only when something is
|
|
1010
|
+
// registered under it: an empty category in sliceConfig is harmless, but a
|
|
1011
|
+
// registered component in a missing folder can never load.
|
|
1012
|
+
const registeredByCategory = new Map();
|
|
1013
|
+
for (const category of Object.values(registryMap)) {
|
|
1014
|
+
registeredByCategory.set(category, (registeredByCategory.get(category) || 0) + 1);
|
|
1015
|
+
}
|
|
1016
|
+
|
|
1017
|
+
const missingCategories = new Map();
|
|
1018
|
+
for (const [category, entry] of Object.entries(componentPaths || {})) {
|
|
1019
|
+
if (!entry?.path) continue;
|
|
1020
|
+
if (!registeredByCategory.has(category)) continue;
|
|
1021
|
+
const dir = joinRoot(projectRoot, 'src', String(entry.path).replace(/^[/\\]+/, ''));
|
|
1022
|
+
if (!(await fs.pathExists(dir))) {
|
|
1023
|
+
missingCategories.set(category, dir);
|
|
1024
|
+
sourceErrors.push({
|
|
1025
|
+
component: `paths.components.${category}`,
|
|
1026
|
+
message: `${path.relative(projectRoot, dir)} does not exist. ${registeredByCategory.get(category)} component(s) are registered under "${category}" and cannot resolve until it is created.`
|
|
1027
|
+
});
|
|
1028
|
+
}
|
|
1029
|
+
}
|
|
1030
|
+
|
|
1031
|
+
for (const [componentName, category] of Object.entries(registryMap)) {
|
|
1032
|
+
const categoryPathValue = categoryPath(category);
|
|
1033
|
+
if (!categoryPathValue) {
|
|
1034
|
+
// Registered under a category the config does not know: the path cannot be
|
|
1035
|
+
// built, so slice.build(name) can never resolve it.
|
|
1036
|
+
sourceErrors.push({
|
|
1037
|
+
component: componentName,
|
|
1038
|
+
message: `is registered under category "${category}", which has no path in sliceConfig.paths.components. slice.build("${componentName}") cannot resolve it.`
|
|
1039
|
+
});
|
|
1040
|
+
continue;
|
|
1041
|
+
}
|
|
1042
|
+
if (missingCategories.has(category)) continue; // one warning for the whole folder
|
|
1043
|
+
|
|
1044
|
+
const componentFile = joinRoot(projectRoot, 'src', categoryPathValue, componentName, `${componentName}.js`);
|
|
1045
|
+
if (!(await fs.pathExists(componentFile))) {
|
|
1046
|
+
// Registered but not on disk: the router and slice.build() resolve the
|
|
1047
|
+
// same path, so the name can never load. It used to be skipped silently.
|
|
1048
|
+
sourceErrors.push({
|
|
1049
|
+
component: componentName,
|
|
1050
|
+
message: `registered in components.js but ${path.relative(projectRoot, componentFile)} does not exist. slice.build("${componentName}") cannot load it.`
|
|
1051
|
+
});
|
|
1052
|
+
continue;
|
|
1053
|
+
}
|
|
1054
|
+
|
|
1055
|
+
let source;
|
|
1056
|
+
try { source = await fs.readFile(componentFile, 'utf8'); } catch { continue; }
|
|
1057
|
+
|
|
1058
|
+
const syntax = describeSyntaxError(source, componentFile);
|
|
1059
|
+
if (!syntax.ok) {
|
|
1060
|
+
sourceErrors.push({ component: componentName, message: `Syntax error at ${syntax.message}` });
|
|
1061
|
+
continue; // nothing further can be said about a file that does not parse
|
|
1062
|
+
}
|
|
1063
|
+
|
|
1064
|
+
// Being in components.js means "this is a component", and the runtime loads
|
|
1065
|
+
// one with `const { default: myClass } = await import(...)` (Slice.getClass).
|
|
1066
|
+
// Without a default export that entry can never resolve, so it is a broken
|
|
1067
|
+
// registration, not a style issue.
|
|
1068
|
+
//
|
|
1069
|
+
// components.js is auto-generated by scanning directories, so a plain module
|
|
1070
|
+
// parked at <Category>/<Name>/<Name>.js gets registered by accident. The fix
|
|
1071
|
+
// is to move it out of the components tree — it is a module, not a component.
|
|
1072
|
+
if (hasDefaultExport(source) === false) {
|
|
1073
|
+
sourceErrors.push({
|
|
1074
|
+
component: componentName,
|
|
1075
|
+
message: `${componentFile}: no default export, but it is registered as a component. `
|
|
1076
|
+
+ `Slice loads components with \`const { default: myClass } = await import(...)\`, so `
|
|
1077
|
+
+ `slice.build('${componentName}') can never resolve. Add a default export, or — if this `
|
|
1078
|
+
+ 'is a plain module of constants/helpers — move it out of the components tree so it '
|
|
1079
|
+
+ 'stops being auto-registered.'
|
|
1080
|
+
});
|
|
1081
|
+
}
|
|
1082
|
+
|
|
1083
|
+
const unresolved = findUnresolvedRelativeImports(source, path.dirname(componentFile));
|
|
1084
|
+
if (unresolved.length > 0) {
|
|
1085
|
+
sourceErrors.push({
|
|
1086
|
+
component: componentName,
|
|
1087
|
+
message: `${componentFile}: cannot resolve ${unresolved.map((s2) => `"${s2}"`).join(', ')}. `
|
|
1088
|
+
+ 'An unresolved relative import silently becomes `undefined` at runtime.'
|
|
1089
|
+
});
|
|
1090
|
+
}
|
|
1091
|
+
|
|
1092
|
+
// A warning, not an error: components legitimately build OPTIONAL ones. The
|
|
1093
|
+
// framework's own Button does `if (this.icon) slice.build('Icon', ...)`, and
|
|
1094
|
+
// a project that never passes an icon has no reason to install Icon. So an
|
|
1095
|
+
// unregistered name is a likely typo, not a certain one.
|
|
1096
|
+
const unknownBuilds = findUnknownComponentBuilds(source, registeredNames);
|
|
1097
|
+
if (unknownBuilds.length > 0) {
|
|
1098
|
+
sourceWarnings.push({
|
|
1099
|
+
component: componentName,
|
|
1100
|
+
message: `builds ${unknownBuilds.map((n) => `"${n}"`).join(', ')}, not registered in `
|
|
1101
|
+
+ 'components.js. If that is a typo it will silently render nothing; if the component '
|
|
1102
|
+
+ 'is optional, ignore this.'
|
|
1103
|
+
});
|
|
1104
|
+
}
|
|
1105
|
+
|
|
1106
|
+
// Lifecycle conventions that are statically visible. Advisories: the app runs,
|
|
1107
|
+
// but the cleanup is not what the author thinks it is.
|
|
1108
|
+
const lifecycle = auditComponentLifecycle(source);
|
|
1109
|
+
if (lifecycle.asyncBeforeDestroy) {
|
|
1110
|
+
warnings.push({
|
|
883
1111
|
component: componentName,
|
|
884
|
-
message:
|
|
885
|
-
+ `Slice loads components with \`const { default: myClass } = await import(...)\`, so `
|
|
886
|
-
+ `slice.build('${componentName}') can never resolve. Add a default export, or — if this `
|
|
887
|
-
+ 'is a plain module of constants/helpers — move it out of the components tree so it '
|
|
888
|
-
+ 'stops being auto-registered.'
|
|
1112
|
+
message: 'beforeDestroy is async: the framework does not await it, so the cleanup runs after the component is removed. Keep it synchronous, or fire-and-forget the promise.'
|
|
889
1113
|
});
|
|
890
1114
|
}
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
if (unresolved.length > 0) {
|
|
894
|
-
sourceErrors.push({
|
|
1115
|
+
if (lifecycle.deadTeardown) {
|
|
1116
|
+
warnings.push({
|
|
895
1117
|
component: componentName,
|
|
896
|
-
message: `${
|
|
897
|
-
+ 'An unresolved relative import silently becomes `undefined` at runtime.'
|
|
1118
|
+
message: `${lifecycle.deadTeardown}() is never called: the framework only invokes beforeDestroy(). Move the cleanup there.`
|
|
898
1119
|
});
|
|
899
1120
|
}
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
// framework's own Button does `if (this.icon) slice.build('Icon', ...)`, and
|
|
903
|
-
// a project that never passes an icon has no reason to install Icon. So an
|
|
904
|
-
// unregistered name is a likely typo, not a certain one.
|
|
905
|
-
const unknownBuilds = findUnknownComponentBuilds(source, registeredNames);
|
|
906
|
-
if (unknownBuilds.length > 0) {
|
|
907
|
-
sourceWarnings.push({
|
|
1121
|
+
if (lifecycle.globalListener) {
|
|
1122
|
+
warnings.push({
|
|
908
1123
|
component: componentName,
|
|
909
|
-
message:
|
|
910
|
-
+ 'components.js. If that is a typo it will silently render nothing; if the component '
|
|
911
|
-
+ 'is optional, ignore this.'
|
|
1124
|
+
message: `${lifecycle.globalListener} global listener(s) added on window/document with no removeEventListener in this file: they outlive the component. Remove them in beforeDestroy() (or pass { once: true } / { signal }).`
|
|
912
1125
|
});
|
|
913
1126
|
}
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
const
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
if (Array.isArray(meta.allowedValues) && meta.allowedValues.length > 0 && meta.type !== 'any') {
|
|
927
|
-
if (meta.allowedValues.some((v) => typeof v !== meta.type)) {
|
|
928
|
-
err(`allowedValues type mismatch (expected all ${meta.type})`);
|
|
929
|
-
}
|
|
1127
|
+
// Component CSS is loaded globally: a selector that does not start with the
|
|
1128
|
+
// component's tag leaks into every page. Advisory - most are harmless class
|
|
1129
|
+
// names, and portaled widgets opt out with the slice:unscoped marker.
|
|
1130
|
+
const componentTag = componentTagFromSource(source);
|
|
1131
|
+
const cssFile = path.join(path.dirname(componentFile), `${componentName}.css`);
|
|
1132
|
+
if (includeCss && componentTag && await fs.pathExists(cssFile)) {
|
|
1133
|
+
const unscoped = findUnscopedSelectors(await fs.readFile(cssFile, 'utf8'), componentTag);
|
|
1134
|
+
if (unscoped.length > 0) {
|
|
1135
|
+
warnings.push({
|
|
1136
|
+
component: componentName,
|
|
1137
|
+
message: `${unscoped.length} CSS selector(s) are not scoped under <${componentTag}>: ${unscoped.slice(0, 2).join(', ')}${unscoped.length > 2 ? ', ...' : ''}. Component CSS is global: prefix them with the tag or :host.`
|
|
1138
|
+
});
|
|
930
1139
|
}
|
|
931
|
-
|
|
932
|
-
if (meta.type === 'any') warn('uses type "any" — specify a concrete type');
|
|
933
|
-
if (meta.required && meta.type !== 'boolean') warn('is required but has no default value');
|
|
934
1140
|
}
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
const eventGraph = await collectEventGraph({ projectRoot });
|
|
959
|
-
const manifest = buildEventManifest(eventRegistry, eventGraph);
|
|
960
|
-
const manifestPath = path.join(path.dirname(outputPath), 'slice-events.generated.js');
|
|
961
|
-
await fs.writeFile(manifestPath, generateEventManifestContent(manifest), 'utf8');
|
|
962
|
-
|
|
963
|
-
const siteCount = Object.values(eventGraph.events).reduce(
|
|
964
|
-
(sum, e) => sum + e.emitters.length + e.listeners.length,
|
|
965
|
-
0
|
|
966
|
-
);
|
|
967
|
-
|
|
968
|
-
return {
|
|
969
|
-
outputPath,
|
|
970
|
-
manifestPath,
|
|
971
|
-
componentsProcessed: Object.keys(componentPropsMap).length,
|
|
972
|
-
eventsProcessed: Object.keys(eventRegistry).length,
|
|
973
|
-
graphSites: siteCount
|
|
974
|
-
};
|
|
975
|
-
};
|
|
976
|
-
|
|
977
|
-
// Merge the declared registry (payloads) with the static graph (call sites) into one manifest.
|
|
978
|
-
const buildEventManifest = (registry, graph) => {
|
|
979
|
-
const names = new Set([...Object.keys(registry), ...Object.keys(graph.events)]);
|
|
980
|
-
const events = {};
|
|
981
|
-
for (const name of Array.from(names).sort((a, b) => a.localeCompare(b))) {
|
|
982
|
-
events[name] = {
|
|
983
|
-
payload: registry[name]?.payload ?? null,
|
|
984
|
-
emitters: graph.events[name]?.emitters || [],
|
|
985
|
-
listeners: graph.events[name]?.listeners || []
|
|
986
|
-
};
|
|
987
|
-
}
|
|
988
|
-
return { events, dynamic: graph.dynamic };
|
|
989
|
-
};
|
|
990
|
-
|
|
991
|
-
const generateEventManifestContent = (manifest) => {
|
|
992
|
-
return `/* Auto-generated by slice types generate. Do not edit manually. */\nexport default ${JSON.stringify(manifest, null, 2)};\n`;
|
|
993
|
-
};
|
|
994
|
-
|
|
995
|
-
const toPosixRelative = (projectRoot, targetPath) => {
|
|
996
|
-
const relative = path.relative(projectRoot, targetPath).replace(/\\/g, '/');
|
|
997
|
-
return relative;
|
|
998
|
-
};
|
|
999
|
-
|
|
1000
|
-
const ensureEditorConfigForTypes = async ({ projectRoot, outputPath }) => {
|
|
1001
|
-
try {
|
|
1002
|
-
const tsconfigPath = joinRoot(projectRoot, 'tsconfig.json');
|
|
1003
|
-
if (await fs.pathExists(tsconfigPath)) {
|
|
1004
|
-
return { mode: 'tsconfig_exists', filePath: tsconfigPath, includeAdded: false };
|
|
1005
|
-
}
|
|
1006
|
-
|
|
1007
|
-
const jsconfigPath = joinRoot(projectRoot, 'jsconfig.json');
|
|
1008
|
-
const declarationGlob = (() => {
|
|
1009
|
-
const relative = toPosixRelative(projectRoot, outputPath);
|
|
1010
|
-
if (!relative) return 'src/**/*.d.ts';
|
|
1011
|
-
const idx = relative.lastIndexOf('/');
|
|
1012
|
-
if (idx === -1) return relative;
|
|
1013
|
-
const dir = relative.slice(0, idx);
|
|
1014
|
-
return `${dir}/**/*.d.ts`;
|
|
1015
|
-
})();
|
|
1016
|
-
|
|
1017
|
-
const writeDefaultJsconfig = async () => {
|
|
1018
|
-
// Include the public/ excludes up front so a freshly written jsconfig is
|
|
1019
|
-
// already in its desired state (the next run reports it as unchanged).
|
|
1020
|
-
const publicExcludes = await readPublicFolderExcludes(projectRoot);
|
|
1021
|
-
const jsconfig = {
|
|
1022
|
-
compilerOptions: { ...DEFAULT_EDITOR_COMPILER_OPTIONS },
|
|
1023
|
-
include: [...DEFAULT_EDITOR_INCLUDE, declarationGlob],
|
|
1024
|
-
exclude: Array.from(new Set([...DEFAULT_EDITOR_EXCLUDE, ...publicExcludes]))
|
|
1025
|
-
};
|
|
1026
|
-
await fs.writeFile(jsconfigPath, `${JSON.stringify(jsconfig, null, 2)}\n`, 'utf8');
|
|
1027
|
-
};
|
|
1028
|
-
|
|
1029
|
-
if (!(await fs.pathExists(jsconfigPath))) {
|
|
1030
|
-
await writeDefaultJsconfig();
|
|
1031
|
-
return { mode: 'created_jsconfig', filePath: jsconfigPath, includeAdded: true };
|
|
1032
|
-
}
|
|
1033
|
-
|
|
1034
|
-
let jsconfigRaw;
|
|
1035
|
-
try {
|
|
1036
|
-
jsconfigRaw = await fs.readFile(jsconfigPath, 'utf8');
|
|
1037
|
-
} catch {
|
|
1038
|
-
// Don't fail — fall back to writing the default options.
|
|
1039
|
-
await writeDefaultJsconfig();
|
|
1040
|
-
return { mode: 'reset_jsconfig', reason: 'unreadable', filePath: jsconfigPath, includeAdded: true };
|
|
1041
|
-
}
|
|
1042
|
-
|
|
1043
|
-
let parsed;
|
|
1044
|
-
try {
|
|
1045
|
-
parsed = JSON.parse(jsconfigRaw);
|
|
1046
|
-
} catch {
|
|
1047
|
-
// The jsconfig was edited into invalid JSON (a typo, comments, trailing commas...).
|
|
1048
|
-
// Don't fail — just write the default options so editor IntelliSense keeps working.
|
|
1049
|
-
await writeDefaultJsconfig();
|
|
1050
|
-
return { mode: 'reset_jsconfig', reason: 'invalid_json', filePath: jsconfigPath, includeAdded: true };
|
|
1051
|
-
}
|
|
1052
|
-
|
|
1053
|
-
const include = Array.isArray(parsed.include) ? parsed.include : [];
|
|
1054
|
-
const needsInclude = !include.includes(declarationGlob);
|
|
1055
|
-
const hasAllDefaultInclude = DEFAULT_EDITOR_INCLUDE.every((entry) => include.includes(entry));
|
|
1056
|
-
const hasNoisyInclude = include.some((entry) => NOISY_INCLUDE_PATTERNS.has(entry));
|
|
1057
|
-
const exclude = Array.isArray(parsed.exclude) ? parsed.exclude : [];
|
|
1058
|
-
const publicFolderExcludes = await readPublicFolderExcludes(projectRoot);
|
|
1059
|
-
const desiredExcludes = Array.from(new Set([...DEFAULT_EDITOR_EXCLUDE, ...publicFolderExcludes]));
|
|
1060
|
-
const hasAllDefaultExclude = desiredExcludes.every((entry) => exclude.includes(entry));
|
|
1061
|
-
|
|
1062
|
-
const compilerOptions = parsed && typeof parsed.compilerOptions === 'object' && parsed.compilerOptions !== null
|
|
1063
|
-
? { ...parsed.compilerOptions }
|
|
1064
|
-
: {};
|
|
1065
|
-
|
|
1066
|
-
let compilerOptionsChanged = false;
|
|
1067
|
-
for (const [key, value] of Object.entries(DEFAULT_EDITOR_COMPILER_OPTIONS)) {
|
|
1068
|
-
if (compilerOptions[key] === undefined) {
|
|
1069
|
-
compilerOptions[key] = value;
|
|
1070
|
-
compilerOptionsChanged = true;
|
|
1141
|
+
const props = extractStaticPropsFromSource(source, componentFile);
|
|
1142
|
+
if (!props) continue;
|
|
1143
|
+
checkedCount++;
|
|
1144
|
+
|
|
1145
|
+
// A computed value (`type: TYPE`, `allowedValues: SIZES`) is invisible to the
|
|
1146
|
+
// extractor: the prop silently becomes `any`. Say why, instead of the
|
|
1147
|
+
// generic "uses type any".
|
|
1148
|
+
const computedFields = findComputedPropFields(source);
|
|
1149
|
+
for (const issue of computedFields) {
|
|
1150
|
+
const field = issue.field === 'metadata' ? 'definition' : issue.field;
|
|
1151
|
+
warnings.push({
|
|
1152
|
+
component: componentName,
|
|
1153
|
+
prop: issue.prop,
|
|
1154
|
+
message: `${field} is computed, not a literal. slice types generate reads the AST and cannot resolve it, so the prop degrades to any. Inline the value.`
|
|
1155
|
+
});
|
|
1156
|
+
}
|
|
1157
|
+
|
|
1158
|
+
for (const [prop, meta] of Object.entries(props)) {
|
|
1159
|
+
const err = (message) => errors.push({ component: componentName, prop, message });
|
|
1160
|
+
const warn = (message) => warnings.push({ component: componentName, prop, message });
|
|
1161
|
+
|
|
1162
|
+
if (RESERVED_PROP_NAMES.has(prop)) {
|
|
1163
|
+
err(`is a reserved build directive and is stripped before setters run. Pass it to slice.build("${componentName}", { ${prop}: ... }) instead of declaring it as a prop.`);
|
|
1071
1164
|
}
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
};
|
|
1098
|
-
}
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
}
|
|
1120
|
-
|
|
1121
|
-
}
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1165
|
+
if (!PROP_VALID_TYPES.has(meta.type)) err(`unknown type "${meta.type}"`);
|
|
1166
|
+
if (meta.schema && meta.type !== 'object') err(`has "schema" but type is "${meta.type}" (should be "object")`);
|
|
1167
|
+
if (meta.items && meta.type !== 'array') err(`has "items" but type is "${meta.type}" (should be "array")`);
|
|
1168
|
+
if (Array.isArray(meta.allowedValues) && meta.allowedValues.length > 0 && meta.type !== 'any') {
|
|
1169
|
+
if (meta.allowedValues.some((v) => typeof v !== meta.type)) {
|
|
1170
|
+
err(`allowedValues type mismatch (expected all ${meta.type})`);
|
|
1171
|
+
}
|
|
1172
|
+
}
|
|
1173
|
+
|
|
1174
|
+
const typeIsComputed = computedFields.some((issue) => issue.prop === prop && issue.field === 'type');
|
|
1175
|
+
if (meta.type === 'any' && !typeIsComputed) warn('uses type "any" — specify a concrete type');
|
|
1176
|
+
if (meta.required && meta.type !== 'boolean') warn('is required but has no default value');
|
|
1177
|
+
}
|
|
1178
|
+
}
|
|
1179
|
+
|
|
1180
|
+
// components.js is generated by scanning folders, so a folder without
|
|
1181
|
+
// <Name>/<Name>.js registers a component that can never resolve. Advisory on
|
|
1182
|
+
// purpose: the bundler only trips over it when something reaches the name, and
|
|
1183
|
+
// helper folders are common. The doctor reports the same finding because it now
|
|
1184
|
+
// comes from this pass instead of its own scan.
|
|
1185
|
+
for (const finding of await findComponentFoldersWithoutFile({ projectRoot, componentPaths })) {
|
|
1186
|
+
sourceWarnings.push({
|
|
1187
|
+
component: finding.component,
|
|
1188
|
+
kind: 'missing-file',
|
|
1189
|
+
message: `${path.relative(projectRoot, finding.file)}: folder has no ${finding.component}.js. components.js is generated by scanning folders, so this registers a component that cannot resolve. Add the file or remove the folder.`
|
|
1190
|
+
});
|
|
1191
|
+
}
|
|
1192
|
+
|
|
1193
|
+
return { errors, warnings, sourceErrors, sourceWarnings, checkedCount, registeredCount };
|
|
1194
|
+
};
|
|
1195
|
+
|
|
1196
|
+
const RUNTIME_MODULE_SHIM = `/* Auto-generated by slice types generate. Do not edit manually. */
|
|
1197
|
+
// The app entry imports the runtime by its browser-absolute URL; the app server
|
|
1198
|
+
// serves it. TypeScript cannot match a leading-slash specifier with an exact
|
|
1199
|
+
// ambient declaration (it rejects the name as relative), so the wildcard is the
|
|
1200
|
+
// form that resolves it without following the framework's untyped JS source.
|
|
1201
|
+
declare module '*/Slice/Slice.js' {
|
|
1202
|
+
const Slice: any;
|
|
1203
|
+
export default Slice;
|
|
1204
|
+
}
|
|
1205
|
+
`;
|
|
1206
|
+
|
|
1207
|
+
const generateTypesFile = async ({ projectRoot, outputPath }) => {
|
|
1208
|
+
const registryPath = getComponentsJsPath(import.meta.url, projectRoot);
|
|
1209
|
+
let registryContent;
|
|
1210
|
+
try {
|
|
1211
|
+
registryContent = await fs.readFile(registryPath, 'utf8');
|
|
1212
|
+
} catch (readError) {
|
|
1213
|
+
throw new Error(`Cannot read components registry at ${registryPath}: ${readError.message}`, { cause: readError });
|
|
1214
|
+
}
|
|
1215
|
+
const registryMap = parseComponentsRegistry(registryContent, registryPath);
|
|
1216
|
+
|
|
1217
|
+
const componentPropsMap = await loadComponentStaticProps({ projectRoot, registryMap });
|
|
1218
|
+
const eventRegistry = await collectEventRegistry({ projectRoot });
|
|
1219
|
+
|
|
1220
|
+
const declaration = generateDeclarationContent(componentPropsMap, eventRegistry);
|
|
1221
|
+
await fs.ensureDir(path.dirname(outputPath));
|
|
1222
|
+
await fs.writeFile(outputPath, declaration, 'utf8');
|
|
1223
|
+
|
|
1224
|
+
// `src/App/index.js` is now in the type-check include, and it starts with
|
|
1225
|
+
// `import Slice from '/Slice/Slice.js'`. Without this declaration every
|
|
1226
|
+
// project fails on that import before anything else is checked.
|
|
1227
|
+
const runtimeShimPath = path.join(path.dirname(outputPath), 'slice-runtime.generated.d.ts');
|
|
1228
|
+
await fs.writeFile(runtimeShimPath, RUNTIME_MODULE_SHIM, 'utf8');
|
|
1229
|
+
|
|
1230
|
+
// Static pub/sub graph manifest (documentation): emitters/listeners by call site.
|
|
1231
|
+
const eventGraph = await collectEventGraph({ projectRoot });
|
|
1232
|
+
const manifest = buildEventManifest(eventRegistry, eventGraph);
|
|
1233
|
+
const manifestPath = path.join(path.dirname(outputPath), 'slice-events.generated.js');
|
|
1234
|
+
await fs.writeFile(manifestPath, generateEventManifestContent(manifest), 'utf8');
|
|
1235
|
+
|
|
1236
|
+
const siteCount = Object.values(eventGraph.events).reduce(
|
|
1237
|
+
(sum, e) => sum + e.emitters.length + e.listeners.length,
|
|
1238
|
+
0
|
|
1239
|
+
);
|
|
1240
|
+
|
|
1241
|
+
return {
|
|
1242
|
+
outputPath,
|
|
1243
|
+
manifestPath,
|
|
1244
|
+
runtimeShimPath,
|
|
1245
|
+
componentsProcessed: Object.keys(componentPropsMap).length,
|
|
1246
|
+
eventsProcessed: Object.keys(eventRegistry).length,
|
|
1247
|
+
graphSites: siteCount
|
|
1248
|
+
};
|
|
1249
|
+
};
|
|
1250
|
+
|
|
1251
|
+
// Merge the declared registry (payloads) with the static graph (call sites) into one manifest.
|
|
1252
|
+
const buildEventManifest = (registry, graph) => {
|
|
1253
|
+
const names = new Set([...Object.keys(registry), ...Object.keys(graph.events)]);
|
|
1254
|
+
const events = {};
|
|
1255
|
+
for (const name of Array.from(names).sort((a, b) => a.localeCompare(b))) {
|
|
1256
|
+
events[name] = {
|
|
1257
|
+
payload: registry[name]?.payload ?? null,
|
|
1258
|
+
emitters: graph.events[name]?.emitters || [],
|
|
1259
|
+
listeners: graph.events[name]?.listeners || []
|
|
1260
|
+
};
|
|
1261
|
+
}
|
|
1262
|
+
return { events, dynamic: graph.dynamic };
|
|
1263
|
+
};
|
|
1264
|
+
|
|
1265
|
+
const generateEventManifestContent = (manifest) => {
|
|
1266
|
+
return `/* Auto-generated by slice types generate. Do not edit manually. */\nexport default ${JSON.stringify(manifest, null, 2)};\n`;
|
|
1267
|
+
};
|
|
1268
|
+
|
|
1269
|
+
const toPosixRelative = (projectRoot, targetPath) => {
|
|
1270
|
+
const relative = path.relative(projectRoot, targetPath).replace(/\\/g, '/');
|
|
1271
|
+
return relative;
|
|
1272
|
+
};
|
|
1273
|
+
|
|
1274
|
+
const ensureEditorConfigForTypes = async ({ projectRoot, outputPath }) => {
|
|
1275
|
+
try {
|
|
1276
|
+
const tsconfigPath = joinRoot(projectRoot, 'tsconfig.json');
|
|
1277
|
+
if (await fs.pathExists(tsconfigPath)) {
|
|
1278
|
+
return { mode: 'tsconfig_exists', filePath: tsconfigPath, includeAdded: false };
|
|
1279
|
+
}
|
|
1280
|
+
|
|
1281
|
+
const jsconfigPath = joinRoot(projectRoot, 'jsconfig.json');
|
|
1282
|
+
const declarationGlob = (() => {
|
|
1283
|
+
const relative = toPosixRelative(projectRoot, outputPath);
|
|
1284
|
+
if (!relative) return 'src/**/*.d.ts';
|
|
1285
|
+
const idx = relative.lastIndexOf('/');
|
|
1286
|
+
if (idx === -1) return relative;
|
|
1287
|
+
const dir = relative.slice(0, idx);
|
|
1288
|
+
return `${dir}/**/*.d.ts`;
|
|
1289
|
+
})();
|
|
1290
|
+
|
|
1291
|
+
const writeDefaultJsconfig = async () => {
|
|
1292
|
+
// Include the public/ excludes up front so a freshly written jsconfig is
|
|
1293
|
+
// already in its desired state (the next run reports it as unchanged).
|
|
1294
|
+
const publicExcludes = await readPublicFolderExcludes(projectRoot);
|
|
1295
|
+
const jsconfig = {
|
|
1296
|
+
compilerOptions: { ...DEFAULT_EDITOR_COMPILER_OPTIONS },
|
|
1297
|
+
include: [...DEFAULT_EDITOR_INCLUDE, declarationGlob],
|
|
1298
|
+
exclude: Array.from(new Set([...DEFAULT_EDITOR_EXCLUDE, ...publicExcludes]))
|
|
1299
|
+
};
|
|
1300
|
+
await fs.writeFile(jsconfigPath, `${JSON.stringify(jsconfig, null, 2)}\n`, 'utf8');
|
|
1301
|
+
};
|
|
1302
|
+
|
|
1303
|
+
if (!(await fs.pathExists(jsconfigPath))) {
|
|
1304
|
+
await writeDefaultJsconfig();
|
|
1305
|
+
return { mode: 'created_jsconfig', filePath: jsconfigPath, includeAdded: true };
|
|
1306
|
+
}
|
|
1307
|
+
|
|
1308
|
+
let jsconfigRaw;
|
|
1309
|
+
try {
|
|
1310
|
+
jsconfigRaw = await fs.readFile(jsconfigPath, 'utf8');
|
|
1311
|
+
} catch {
|
|
1312
|
+
// Don't fail — fall back to writing the default options.
|
|
1313
|
+
await writeDefaultJsconfig();
|
|
1314
|
+
return { mode: 'reset_jsconfig', reason: 'unreadable', filePath: jsconfigPath, includeAdded: true };
|
|
1315
|
+
}
|
|
1316
|
+
|
|
1317
|
+
let parsed;
|
|
1318
|
+
try {
|
|
1319
|
+
parsed = JSON.parse(jsconfigRaw);
|
|
1320
|
+
} catch {
|
|
1321
|
+
// The jsconfig was edited into invalid JSON (a typo, comments, trailing commas...).
|
|
1322
|
+
// Don't fail — just write the default options so editor IntelliSense keeps working.
|
|
1323
|
+
await writeDefaultJsconfig();
|
|
1324
|
+
return { mode: 'reset_jsconfig', reason: 'invalid_json', filePath: jsconfigPath, includeAdded: true };
|
|
1325
|
+
}
|
|
1326
|
+
|
|
1327
|
+
const include = Array.isArray(parsed.include) ? parsed.include : [];
|
|
1328
|
+
const needsInclude = !include.includes(declarationGlob);
|
|
1329
|
+
const hasAllDefaultInclude = DEFAULT_EDITOR_INCLUDE.every((entry) => include.includes(entry));
|
|
1330
|
+
const hasNoisyInclude = include.some((entry) => NOISY_INCLUDE_PATTERNS.has(entry));
|
|
1331
|
+
const exclude = Array.isArray(parsed.exclude) ? parsed.exclude : [];
|
|
1332
|
+
const publicFolderExcludes = await readPublicFolderExcludes(projectRoot);
|
|
1333
|
+
const desiredExcludes = Array.from(new Set([...DEFAULT_EDITOR_EXCLUDE, ...publicFolderExcludes]));
|
|
1334
|
+
const hasAllDefaultExclude = desiredExcludes.every((entry) => exclude.includes(entry));
|
|
1335
|
+
|
|
1336
|
+
const compilerOptions = parsed && typeof parsed.compilerOptions === 'object' && parsed.compilerOptions !== null
|
|
1337
|
+
? { ...parsed.compilerOptions }
|
|
1338
|
+
: {};
|
|
1339
|
+
|
|
1340
|
+
let compilerOptionsChanged = false;
|
|
1133
1341
|
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1342
|
+
// Our old default made tsc check inside node_modules; drop it when it is
|
|
1343
|
+
// still the generated value, so typecheck stays fast.
|
|
1344
|
+
if (compilerOptions.maxNodeModuleJsDepth === 2) {
|
|
1345
|
+
delete compilerOptions.maxNodeModuleJsDepth;
|
|
1346
|
+
compilerOptionsChanged = true;
|
|
1347
|
+
}
|
|
1348
|
+
for (const [key, value] of Object.entries(DEFAULT_EDITOR_COMPILER_OPTIONS)) {
|
|
1349
|
+
if (compilerOptions[key] === undefined) {
|
|
1350
|
+
compilerOptions[key] = value;
|
|
1351
|
+
compilerOptionsChanged = true;
|
|
1352
|
+
}
|
|
1353
|
+
}
|
|
1354
|
+
|
|
1355
|
+
if (!needsInclude && !compilerOptionsChanged && hasAllDefaultInclude && hasAllDefaultExclude && !hasNoisyInclude) {
|
|
1356
|
+
return { mode: 'jsconfig_already_has_include', filePath: jsconfigPath, includeAdded: false };
|
|
1357
|
+
}
|
|
1358
|
+
|
|
1359
|
+
parsed.compilerOptions = compilerOptions;
|
|
1360
|
+
parsed.include = needsInclude ? [...include, declarationGlob] : include;
|
|
1361
|
+
const includeSet = new Set(
|
|
1362
|
+
(Array.isArray(parsed.include) ? parsed.include : []).filter((entry) => !NOISY_INCLUDE_PATTERNS.has(entry))
|
|
1363
|
+
);
|
|
1364
|
+
DEFAULT_EDITOR_INCLUDE.forEach((entry) => includeSet.add(entry));
|
|
1365
|
+
parsed.include = Array.from(includeSet);
|
|
1366
|
+
|
|
1367
|
+
const excludeSet = new Set(Array.isArray(parsed.exclude) ? parsed.exclude : []);
|
|
1368
|
+
desiredExcludes.forEach((entry) => excludeSet.add(entry));
|
|
1369
|
+
parsed.exclude = Array.from(excludeSet);
|
|
1370
|
+
await fs.writeFile(jsconfigPath, `${JSON.stringify(parsed, null, 2)}\n`, 'utf8');
|
|
1371
|
+
return { mode: 'updated_jsconfig', filePath: jsconfigPath, includeAdded: needsInclude };
|
|
1372
|
+
} catch (error) {
|
|
1373
|
+
return {
|
|
1374
|
+
mode: 'editor_config_error',
|
|
1375
|
+
filePath: projectRoot,
|
|
1376
|
+
includeAdded: false,
|
|
1377
|
+
errorMessage: error?.message || 'Unknown editor config setup error'
|
|
1378
|
+
};
|
|
1379
|
+
}
|
|
1380
|
+
};
|
|
1381
|
+
|
|
1382
|
+
const runGenerateTypes = async ({ projectRoot, outputPath }) => {
|
|
1383
|
+
const result = await generateTypesFile({ projectRoot, outputPath });
|
|
1384
|
+
const editorConfig = await ensureEditorConfigForTypes({ projectRoot, outputPath });
|
|
1385
|
+
const publicVendorSuppression = await ensureNoCheckInPublicVendorFiles(projectRoot);
|
|
1386
|
+
Print.success(`Generated TypeScript declarations at ${result.outputPath}`);
|
|
1387
|
+
Print.info(`Components with static props: ${result.componentsProcessed}`);
|
|
1388
|
+
if (typeof result.eventsProcessed === 'number') {
|
|
1389
|
+
Print.info(`Registered events typed: ${result.eventsProcessed}`);
|
|
1390
|
+
}
|
|
1391
|
+
if (result.manifestPath) {
|
|
1392
|
+
Print.info(`Event graph manifest: ${toPosixRelative(projectRoot, result.manifestPath)} (${result.graphSites} call site(s))`);
|
|
1393
|
+
}
|
|
1394
|
+
if (editorConfig.mode === 'created_jsconfig') {
|
|
1395
|
+
Print.info(`Created jsconfig.json and included declaration glob for editor IntelliSense.`);
|
|
1396
|
+
} else if (editorConfig.mode === 'updated_jsconfig') {
|
|
1397
|
+
Print.info(`Updated jsconfig.json include list for declaration IntelliSense.`);
|
|
1398
|
+
} else if (editorConfig.mode === 'jsconfig_already_has_include') {
|
|
1399
|
+
Print.info(`jsconfig.json already includes declaration glob. Editor IntelliSense should pick generated types.`);
|
|
1400
|
+
} else if (editorConfig.mode === 'tsconfig_exists') {
|
|
1401
|
+
Print.info(`tsconfig.json detected. Types declaration is generated; ensure include covers ${toPosixRelative(projectRoot, outputPath)}.`);
|
|
1402
|
+
} else if (editorConfig.mode === 'reset_jsconfig') {
|
|
1403
|
+
const why = editorConfig.reason === 'invalid_json' ? 'contained invalid JSON' : 'could not be read';
|
|
1404
|
+
Print.warning(`jsconfig.json ${why}; wrote the default options so editor IntelliSense keeps working.`);
|
|
1405
|
+
Print.info(`Review ${editorConfig.filePath} if you had custom settings there.`);
|
|
1406
|
+
} else if (editorConfig.mode === 'editor_config_error') {
|
|
1407
|
+
Print.warning(`Unexpected editor config setup error: ${editorConfig.errorMessage}`);
|
|
1408
|
+
}
|
|
1409
|
+
if (publicVendorSuppression.updatedFiles > 0) {
|
|
1410
|
+
Print.info(`Added // @ts-nocheck to ${publicVendorSuppression.updatedFiles} vendor JS files under src/public/.`);
|
|
1411
|
+
}
|
|
1412
|
+
return result;
|
|
1413
|
+
};
|
|
1414
|
+
|
|
1415
|
+
export {
|
|
1416
|
+
ensureNoCheckInPublicVendorFiles,
|
|
1417
|
+
ensureEditorConfigForTypes,
|
|
1418
|
+
extractStaticPropsFromSource,
|
|
1419
|
+
generateDeclarationContent,
|
|
1420
|
+
generateTypesFile,
|
|
1421
|
+
parseComponentsRegistry,
|
|
1422
|
+
validateComponentProps,
|
|
1423
|
+
collectEventRegistry,
|
|
1424
|
+
collectEventGraph,
|
|
1425
|
+
buildEventManifest,
|
|
1426
|
+
payloadToTs,
|
|
1427
|
+
runGenerateTypes
|
|
1428
|
+
};
|