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
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
// One validation pass, two consumers.
|
|
2
|
+
//
|
|
3
|
+
// `slice build` blocks the bundle on it; `slice doctor` reports it. They used to
|
|
4
|
+
// disagree because each one picked different fields out of the same result:
|
|
5
|
+
// build blocked on source errors and prop errors, doctor showed only props and
|
|
6
|
+
// demoted everything to a warning. The rules live in `validateComponentProps`,
|
|
7
|
+
// `validateRoutes` and `validateConfigRules`; this module owns the composition
|
|
8
|
+
// and the classification, so callers only decide how to print it and which exit
|
|
9
|
+
// code to use.
|
|
10
|
+
|
|
11
|
+
import fs from 'fs-extra';
|
|
12
|
+
import path from 'node:path';
|
|
13
|
+
import { parse } from '@babel/parser';
|
|
14
|
+
import traverse from '@babel/traverse';
|
|
15
|
+
import { validateComponentProps, parseComponentsRegistry } from '../types/types.js';
|
|
16
|
+
import { describeSyntaxError, findUnresolvedRelativeImports } from './SourceDiagnostics.js';
|
|
17
|
+
import { getComponentsJsPath, getConfigPath } from './PathHelper.js';
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Config combinations that build fine and misbehave at runtime. Pure function:
|
|
21
|
+
* both commands feed it the same object, so the rule exists once.
|
|
22
|
+
*/
|
|
23
|
+
export function validateConfigRules(config) {
|
|
24
|
+
const problems = [];
|
|
25
|
+
|
|
26
|
+
if (config?.context?.enabled && !config?.events?.enabled) {
|
|
27
|
+
problems.push({
|
|
28
|
+
path: 'context.enabled',
|
|
29
|
+
message:
|
|
30
|
+
'requires events.enabled: ContextManager reactivity (setState → watch/bind) runs through '
|
|
31
|
+
+ 'EventManager, and EventManager is only bundled when events are enabled.'
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
return problems;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Static checks for `src/routes.js`.
|
|
40
|
+
*
|
|
41
|
+
* The router fetches this file at runtime instead of bundling it, so neither
|
|
42
|
+
* the bundler nor a component-only check ever looks at it. That let `slice
|
|
43
|
+
* build` ship `dist/routes.js` with an import of a file that does not exist.
|
|
44
|
+
*/
|
|
45
|
+
export async function validateRoutes({ projectRoot, registeredNames = new Set() }) {
|
|
46
|
+
const file = path.join(projectRoot, 'src', 'routes.js');
|
|
47
|
+
const routeErrors = [];
|
|
48
|
+
const routeWarnings = [];
|
|
49
|
+
let routeCount = 0;
|
|
50
|
+
|
|
51
|
+
let source;
|
|
52
|
+
try {
|
|
53
|
+
source = await fs.readFile(file, 'utf8');
|
|
54
|
+
} catch {
|
|
55
|
+
return { routeErrors, routeWarnings, routeCount }; // no routes file: nothing to check
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const syntax = describeSyntaxError(source, file);
|
|
59
|
+
if (!syntax.ok) {
|
|
60
|
+
routeErrors.push({ component: 'routes.js', message: `Syntax error at ${syntax.message}` });
|
|
61
|
+
return { routeErrors, routeWarnings, routeCount };
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const unresolved = findUnresolvedRelativeImports(source, path.dirname(file));
|
|
65
|
+
if (unresolved.length > 0) {
|
|
66
|
+
routeErrors.push({
|
|
67
|
+
component: 'routes.js',
|
|
68
|
+
message:
|
|
69
|
+
`cannot resolve ${unresolved.map((spec) => `"${spec}"`).join(', ')}. routes.js is served as-is and `
|
|
70
|
+
+ 'loaded by the browser, so an unresolved import breaks the router module and nothing navigates.'
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// `{ path, component: 'Name' }`. A name that is not registered does not break
|
|
75
|
+
// startup: `slice.build(name)` throws when the user navigates to that route.
|
|
76
|
+
// Advisory, so an app with a stale route still builds.
|
|
77
|
+
const reported = new Set();
|
|
78
|
+
try {
|
|
79
|
+
const ast = parse(source, { sourceType: 'module', plugins: ['jsx'] });
|
|
80
|
+
traverse.default(ast, {
|
|
81
|
+
ObjectExpression({ node }) {
|
|
82
|
+
for (const property of node.properties) {
|
|
83
|
+
if (property.type !== 'ObjectProperty' || property.computed) continue;
|
|
84
|
+
const key = property.name ?? property.key?.name ?? property.key?.value;
|
|
85
|
+
if (property.value?.type !== 'StringLiteral') continue;
|
|
86
|
+
|
|
87
|
+
// `:id` looks like a parameter and is never matched: the router only
|
|
88
|
+
// compiles patterns containing `${`.
|
|
89
|
+
if (key === 'path') {
|
|
90
|
+
const routePath = property.value.value;
|
|
91
|
+
const colon = routePath.match(/(?:^|\/):([A-Za-z_]\w*)/);
|
|
92
|
+
if (colon) {
|
|
93
|
+
routeWarnings.push({
|
|
94
|
+
component: 'routes.js',
|
|
95
|
+
message:
|
|
96
|
+
`route "${routePath}" uses ":${colon[1]}", which Slice never matches. `
|
|
97
|
+
+ `It only compiles "\${${colon[1]}}" patterns, so this path is treated as a literal.`
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
continue;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
if (key !== 'component') continue;
|
|
104
|
+
|
|
105
|
+
routeCount += 1;
|
|
106
|
+
const name = property.value.value;
|
|
107
|
+
if (registeredNames.has(name) || reported.has(name)) continue;
|
|
108
|
+
|
|
109
|
+
reported.add(name);
|
|
110
|
+
routeWarnings.push({
|
|
111
|
+
component: 'routes.js',
|
|
112
|
+
message:
|
|
113
|
+
`a route uses component "${name}", which is not registered in components.js. `
|
|
114
|
+
+ `slice.build("${name}") throws when that route is visited.`
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
});
|
|
119
|
+
} catch { /* the syntax check above already reported it */ }
|
|
120
|
+
|
|
121
|
+
return { routeErrors, routeWarnings, routeCount };
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* `api/index.js` is the deployment entrypoint. `slice build` bundles `src/` and
|
|
126
|
+
* never executes it, so a syntax error there survived every check and surfaced
|
|
127
|
+
* as a 500 in production.
|
|
128
|
+
*/
|
|
129
|
+
export async function validateServerEntry({ projectRoot }) {
|
|
130
|
+
const file = path.join(projectRoot, 'api', 'index.js');
|
|
131
|
+
|
|
132
|
+
let source;
|
|
133
|
+
try {
|
|
134
|
+
source = await fs.readFile(file, 'utf8');
|
|
135
|
+
} catch {
|
|
136
|
+
return { serverErrors: [], serverWarnings: [], hasServer: false }; // static app
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
const syntax = describeSyntaxError(source, file);
|
|
140
|
+
if (!syntax.ok) {
|
|
141
|
+
return {
|
|
142
|
+
serverErrors: [{ component: 'api/index.js', message: `Syntax error at ${syntax.message}` }],
|
|
143
|
+
serverWarnings: [],
|
|
144
|
+
hasServer: true
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
return { serverErrors: [], serverWarnings: [], hasServer: true };
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** Config, components and routes in one result. Both commands start here. */
|
|
152
|
+
export async function validateProject({ projectRoot, skipComponents = false, includeCss = true }) {
|
|
153
|
+
const config = readConfig(projectRoot);
|
|
154
|
+
const registry = readRegistry(projectRoot);
|
|
155
|
+
|
|
156
|
+
let components;
|
|
157
|
+
if (skipComponents) {
|
|
158
|
+
components = {
|
|
159
|
+
errors: [], warnings: [], sourceErrors: [], sourceWarnings: [], checkedCount: 0, registeredCount: registry.names.size
|
|
160
|
+
};
|
|
161
|
+
} else {
|
|
162
|
+
try {
|
|
163
|
+
components = await validateComponentProps({ projectRoot, includeCss });
|
|
164
|
+
} catch (error) {
|
|
165
|
+
// A registry that does not parse used to escape as a stack trace from
|
|
166
|
+
// build and as a vague warning from doctor. It is a blocking finding.
|
|
167
|
+
components = {
|
|
168
|
+
errors: [],
|
|
169
|
+
warnings: [],
|
|
170
|
+
sourceErrors: [{ component: 'components.js', message: error.message }],
|
|
171
|
+
sourceWarnings: [],
|
|
172
|
+
checkedCount: 0,
|
|
173
|
+
registeredCount: 0
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
if (registry.error && !components.sourceErrors.some((issue) => issue.component === 'components.js')) {
|
|
179
|
+
components.sourceErrors.push({ component: 'components.js', message: registry.error });
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
const routes = await validateRoutes({ projectRoot, registeredNames: registry.names });
|
|
183
|
+
|
|
184
|
+
return {
|
|
185
|
+
configErrors: validateConfigRules(config),
|
|
186
|
+
...components,
|
|
187
|
+
routeErrors: routes.routeErrors,
|
|
188
|
+
routeWarnings: routes.routeWarnings,
|
|
189
|
+
routeCount: routes.routeCount
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
function readConfig(projectRoot) {
|
|
194
|
+
try {
|
|
195
|
+
return JSON.parse(fs.readFileSync(getConfigPath(import.meta.url, projectRoot), 'utf8'));
|
|
196
|
+
} catch {
|
|
197
|
+
// A missing or invalid config is the Configuration row's finding, not a
|
|
198
|
+
// silent "no rules to apply".
|
|
199
|
+
return null;
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
function readRegistry(projectRoot) {
|
|
204
|
+
const file = getComponentsJsPath(import.meta.url, projectRoot);
|
|
205
|
+
try {
|
|
206
|
+
const map = parseComponentsRegistry(fs.readFileSync(file, 'utf8'), file);
|
|
207
|
+
return { names: new Set(Object.keys(map)), error: null };
|
|
208
|
+
} catch (error) {
|
|
209
|
+
// No registry at all is not an error: a project may have no components yet.
|
|
210
|
+
return { names: new Set(), error: fs.existsSync(file) ? error.message : null };
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/**
|
|
215
|
+
* Split a component validation result into what blocks a build and what is only
|
|
216
|
+
* advice. A single place, so `slice doctor` and `slice build` cannot classify
|
|
217
|
+
* the same problem differently.
|
|
218
|
+
*/
|
|
219
|
+
export function classifyValidation(result = {}) {
|
|
220
|
+
const blocking = [
|
|
221
|
+
...(result.serverErrors || []).map((issue) => ({
|
|
222
|
+
kind: 'server',
|
|
223
|
+
component: issue.component,
|
|
224
|
+
message: issue.message
|
|
225
|
+
})),
|
|
226
|
+
...(result.sourceErrors || []).map((issue) => ({
|
|
227
|
+
kind: 'source',
|
|
228
|
+
component: issue.component,
|
|
229
|
+
message: issue.message
|
|
230
|
+
})),
|
|
231
|
+
...(result.routeErrors || []).map((issue) => ({
|
|
232
|
+
kind: 'route',
|
|
233
|
+
component: issue.component,
|
|
234
|
+
message: issue.message
|
|
235
|
+
})),
|
|
236
|
+
...(result.errors || []).map((issue) => ({
|
|
237
|
+
kind: 'prop',
|
|
238
|
+
component: issue.component,
|
|
239
|
+
prop: issue.prop,
|
|
240
|
+
message: issue.message
|
|
241
|
+
}))
|
|
242
|
+
];
|
|
243
|
+
|
|
244
|
+
const advisory = [
|
|
245
|
+
...(result.serverWarnings || []).map((issue) => ({
|
|
246
|
+
kind: 'server-warning',
|
|
247
|
+
component: issue.component,
|
|
248
|
+
message: issue.message
|
|
249
|
+
})),
|
|
250
|
+
...(result.sourceWarnings || []).map((issue) => ({
|
|
251
|
+
kind: 'source-warning',
|
|
252
|
+
component: issue.component,
|
|
253
|
+
message: issue.message
|
|
254
|
+
})),
|
|
255
|
+
...(result.routeWarnings || []).map((issue) => ({
|
|
256
|
+
kind: 'route-warning',
|
|
257
|
+
component: issue.component,
|
|
258
|
+
message: issue.message
|
|
259
|
+
})),
|
|
260
|
+
...(result.warnings || []).map((issue) => ({
|
|
261
|
+
kind: 'prop-warning',
|
|
262
|
+
component: issue.component,
|
|
263
|
+
prop: issue.prop,
|
|
264
|
+
message: issue.message
|
|
265
|
+
}))
|
|
266
|
+
];
|
|
267
|
+
|
|
268
|
+
return { blocking, advisory };
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/** `Component.prop — message`, or `Component — message` for source findings. */
|
|
272
|
+
export function describeIssue(issue) {
|
|
273
|
+
return issue.prop ? `${issue.component}.${issue.prop} — ${issue.message}` : `${issue.component} — ${issue.message}`;
|
|
274
|
+
}
|
|
@@ -1,201 +1,201 @@
|
|
|
1
|
-
// Shared reporting for "this source file does not parse".
|
|
2
|
-
//
|
|
3
|
-
// Two places hit it — buildProduction minifying a file src/ -> dist/, and
|
|
4
|
-
// BundleGenerator preparing a component for a bundle — and each used to report
|
|
5
|
-
// it in its own way: Terser's `Unexpected token punc «(», expected punc «,»`
|
|
6
|
-
// with no location, or a position inside the *generated* bundle. Neither told
|
|
7
|
-
// the developer which line of their own file to look at.
|
|
8
|
-
import fs from 'fs-extra';
|
|
9
|
-
import path from 'path';
|
|
10
|
-
import { parse } from '@babel/parser';
|
|
11
|
-
|
|
12
|
-
/** Extensions a relative specifier is resolved against. */
|
|
13
|
-
export const RESOLVABLE_MODULE_EXTENSIONS = ['.js', '.json', '.mjs'];
|
|
14
|
-
|
|
15
|
-
/**
|
|
16
|
-
* Renders a few lines of source around a position, with a caret under it.
|
|
17
|
-
* Deliberately hand-rolled: @babel/code-frame is not a dependency, and this is
|
|
18
|
-
* all it needs to do.
|
|
19
|
-
*
|
|
20
|
-
* @param {string} code
|
|
21
|
-
* @param {number} line 1-based
|
|
22
|
-
* @param {number} column 0-based
|
|
23
|
-
* @returns {string}
|
|
24
|
-
*/
|
|
25
|
-
export function formatSourceFrame(code, line, column) {
|
|
26
|
-
const lines = String(code).split('\n');
|
|
27
|
-
const first = Math.max(1, line - 2);
|
|
28
|
-
const last = Math.min(lines.length, line + 2);
|
|
29
|
-
const gutter = String(last).length;
|
|
30
|
-
const out = [];
|
|
31
|
-
|
|
32
|
-
for (let current = first; current <= last; current += 1) {
|
|
33
|
-
const marker = current === line ? '>' : ' ';
|
|
34
|
-
out.push(` ${marker} ${String(current).padStart(gutter)} | ${lines[current - 1]}`);
|
|
35
|
-
if (current === line) {
|
|
36
|
-
out.push(` ${' '.repeat(gutter)} | ${' '.repeat(Math.max(0, column))}^`);
|
|
37
|
-
}
|
|
38
|
-
}
|
|
39
|
-
return out.join('\n');
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
/**
|
|
43
|
-
* Parses `code`, returning a readable diagnostic when it fails.
|
|
44
|
-
*
|
|
45
|
-
* @param {string} code
|
|
46
|
-
* @param {string} filePath shown in the message
|
|
47
|
-
* @returns {{ok: true} | {ok: false, message: string, line: number|null, column: number|null}}
|
|
48
|
-
*/
|
|
49
|
-
export function describeSyntaxError(code, filePath) {
|
|
50
|
-
try {
|
|
51
|
-
parse(code, { sourceType: 'module', plugins: ['jsx'] });
|
|
52
|
-
return { ok: true };
|
|
53
|
-
} catch (error) {
|
|
54
|
-
const line = error.loc?.line ?? null;
|
|
55
|
-
const column = error.loc?.column ?? 0;
|
|
56
|
-
const where = line ? `${filePath}:${line}:${column + 1}` : filePath;
|
|
57
|
-
// Babel appends its own "(line:col)"; drop it, the location is already
|
|
58
|
-
// stated above in a form editors can jump to.
|
|
59
|
-
const detail = String(error.message).replace(/\s*\(\d+:\d+\)\s*$/, '');
|
|
60
|
-
const frame = line ? `\n\n${formatSourceFrame(code, line, column)}\n` : '';
|
|
61
|
-
|
|
62
|
-
return {
|
|
63
|
-
ok: false,
|
|
64
|
-
line,
|
|
65
|
-
column,
|
|
66
|
-
message: `${where}: ${detail}.${frame}`
|
|
67
|
-
};
|
|
68
|
-
}
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
/**
|
|
72
|
-
* Resolves a relative specifier the way the bundler does.
|
|
73
|
-
* @param {string} specifier
|
|
74
|
-
* @param {string} fromDir
|
|
75
|
-
* @returns {string|null} absolute path, or null when nothing matches
|
|
76
|
-
*/
|
|
77
|
-
export function resolveRelativeSpecifier(specifier, fromDir) {
|
|
78
|
-
const resolved = path.resolve(fromDir, specifier);
|
|
79
|
-
if (!path.extname(resolved)) {
|
|
80
|
-
for (const extension of RESOLVABLE_MODULE_EXTENSIONS) {
|
|
81
|
-
if (fs.existsSync(resolved + extension)) return resolved + extension;
|
|
82
|
-
}
|
|
83
|
-
}
|
|
84
|
-
return fs.existsSync(resolved) ? resolved : null;
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
/**
|
|
88
|
-
* Relative imports that name a JavaScript module and resolve to nothing.
|
|
89
|
-
*
|
|
90
|
-
* Only module-like specifiers are reported — extensionless, or one of
|
|
91
|
-
* RESOLVABLE_MODULE_EXTENSIONS. A relative asset import has its own delivery
|
|
92
|
-
* story and is not the bundler's business.
|
|
93
|
-
*
|
|
94
|
-
* @param {string} code
|
|
95
|
-
* @param {string} fromDir directory the specifiers resolve against
|
|
96
|
-
* @returns {string[]} unresolved specifiers, in source order
|
|
97
|
-
*/
|
|
98
|
-
export function findUnresolvedRelativeImports(code, fromDir) {
|
|
99
|
-
let ast;
|
|
100
|
-
try {
|
|
101
|
-
ast = parse(code, { sourceType: 'module', plugins: ['jsx'] });
|
|
102
|
-
} catch {
|
|
103
|
-
return []; // unparseable: describeSyntaxError reports that instead
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
const unresolved = [];
|
|
107
|
-
for (const node of ast.program.body) {
|
|
108
|
-
const isImportLike = node.type === 'ImportDeclaration'
|
|
109
|
-
|| node.type === 'ExportNamedDeclaration'
|
|
110
|
-
|| node.type === 'ExportAllDeclaration';
|
|
111
|
-
const specifier = isImportLike ? node.source?.value : null;
|
|
112
|
-
if (typeof specifier !== 'string') continue;
|
|
113
|
-
if (!specifier.startsWith('./') && !specifier.startsWith('../')) continue;
|
|
114
|
-
|
|
115
|
-
const ext = path.extname(specifier);
|
|
116
|
-
const moduleLike = ext === '' || RESOLVABLE_MODULE_EXTENSIONS.includes(ext);
|
|
117
|
-
if (!moduleLike) continue;
|
|
118
|
-
|
|
119
|
-
if (!resolveRelativeSpecifier(specifier, fromDir)) unresolved.push(specifier);
|
|
120
|
-
}
|
|
121
|
-
return unresolved;
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
/**
|
|
125
|
-
* True when the module has a default export.
|
|
126
|
-
*
|
|
127
|
-
* Slice loads a component with `const { default: myClass } = await import(...)`
|
|
128
|
-
* (Slice.getClass), so a component without one can never be built.
|
|
129
|
-
*
|
|
130
|
-
* @param {string} code
|
|
131
|
-
* @returns {boolean|null} null when the source does not parse
|
|
132
|
-
*/
|
|
133
|
-
export function hasDefaultExport(code) {
|
|
134
|
-
try {
|
|
135
|
-
const ast = parse(code, { sourceType: 'module', plugins: ['jsx'] });
|
|
136
|
-
return ast.program.body.some((node) => node.type === 'ExportDefaultDeclaration');
|
|
137
|
-
} catch {
|
|
138
|
-
return null;
|
|
139
|
-
}
|
|
140
|
-
}
|
|
141
|
-
|
|
142
|
-
/**
|
|
143
|
-
* `slice.build('Name')` calls whose component is not in the registry.
|
|
144
|
-
*
|
|
145
|
-
* `slice.build` resolves a component by its registered name, so a typo returns
|
|
146
|
-
* null and the component simply never renders — the framework logs
|
|
147
|
-
* "Component X not found in components.js file" and carries on. Catching it at
|
|
148
|
-
* build time is the closest thing to a "module not found".
|
|
149
|
-
*
|
|
150
|
-
* Deliberately narrow:
|
|
151
|
-
* - only a `slice.build(...)` receiver (not an arbitrary `.build()` method),
|
|
152
|
-
* - only a string-literal first argument (a computed name cannot be checked),
|
|
153
|
-
* - `getComponent` is NOT checked: it takes a sliceId, which is arbitrary
|
|
154
|
-
* (`slice.getComponent('appTopbar')`), not a component name.
|
|
155
|
-
*
|
|
156
|
-
* @param {string} code
|
|
157
|
-
* @param {Set<string>} registeredNames
|
|
158
|
-
* @returns {string[]} unknown component names, deduped, in source order
|
|
159
|
-
*/
|
|
160
|
-
export function findUnknownComponentBuilds(code, registeredNames) {
|
|
161
|
-
let ast;
|
|
162
|
-
try {
|
|
163
|
-
ast = parse(code, { sourceType: 'module', plugins: ['jsx', 'classProperties'] });
|
|
164
|
-
} catch {
|
|
165
|
-
return [];
|
|
166
|
-
}
|
|
167
|
-
|
|
168
|
-
const unknown = [];
|
|
169
|
-
const seen = new Set();
|
|
170
|
-
|
|
171
|
-
const isSliceBuildCallee = (callee) => {
|
|
172
|
-
if (!callee || callee.type !== 'MemberExpression') return false;
|
|
173
|
-
if (callee.property?.name !== 'build') return false;
|
|
174
|
-
const object = callee.object;
|
|
175
|
-
if (object?.type === 'Identifier') return object.name === 'slice';
|
|
176
|
-
// window.slice.build(...)
|
|
177
|
-
return object?.type === 'MemberExpression' && object.property?.name === 'slice';
|
|
178
|
-
};
|
|
179
|
-
|
|
180
|
-
const walk = (node) => {
|
|
181
|
-
if (!node || typeof node !== 'object') return;
|
|
182
|
-
if (Array.isArray(node)) {
|
|
183
|
-
for (const child of node) walk(child);
|
|
184
|
-
return;
|
|
185
|
-
}
|
|
186
|
-
if (node.type === 'CallExpression' && isSliceBuildCallee(node.callee)) {
|
|
187
|
-
const first = node.arguments?.[0];
|
|
188
|
-
if (first?.type === 'StringLiteral' && !registeredNames.has(first.value) && !seen.has(first.value)) {
|
|
189
|
-
seen.add(first.value);
|
|
190
|
-
unknown.push(first.value);
|
|
191
|
-
}
|
|
192
|
-
}
|
|
193
|
-
for (const key of Object.keys(node)) {
|
|
194
|
-
if (key === 'loc' || key === 'start' || key === 'end') continue;
|
|
195
|
-
walk(node[key]);
|
|
196
|
-
}
|
|
197
|
-
};
|
|
198
|
-
|
|
199
|
-
walk(ast.program.body);
|
|
200
|
-
return unknown;
|
|
201
|
-
}
|
|
1
|
+
// Shared reporting for "this source file does not parse".
|
|
2
|
+
//
|
|
3
|
+
// Two places hit it — buildProduction minifying a file src/ -> dist/, and
|
|
4
|
+
// BundleGenerator preparing a component for a bundle — and each used to report
|
|
5
|
+
// it in its own way: Terser's `Unexpected token punc «(», expected punc «,»`
|
|
6
|
+
// with no location, or a position inside the *generated* bundle. Neither told
|
|
7
|
+
// the developer which line of their own file to look at.
|
|
8
|
+
import fs from 'fs-extra';
|
|
9
|
+
import path from 'path';
|
|
10
|
+
import { parse } from '@babel/parser';
|
|
11
|
+
|
|
12
|
+
/** Extensions a relative specifier is resolved against. */
|
|
13
|
+
export const RESOLVABLE_MODULE_EXTENSIONS = ['.js', '.json', '.mjs'];
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Renders a few lines of source around a position, with a caret under it.
|
|
17
|
+
* Deliberately hand-rolled: @babel/code-frame is not a dependency, and this is
|
|
18
|
+
* all it needs to do.
|
|
19
|
+
*
|
|
20
|
+
* @param {string} code
|
|
21
|
+
* @param {number} line 1-based
|
|
22
|
+
* @param {number} column 0-based
|
|
23
|
+
* @returns {string}
|
|
24
|
+
*/
|
|
25
|
+
export function formatSourceFrame(code, line, column) {
|
|
26
|
+
const lines = String(code).split('\n');
|
|
27
|
+
const first = Math.max(1, line - 2);
|
|
28
|
+
const last = Math.min(lines.length, line + 2);
|
|
29
|
+
const gutter = String(last).length;
|
|
30
|
+
const out = [];
|
|
31
|
+
|
|
32
|
+
for (let current = first; current <= last; current += 1) {
|
|
33
|
+
const marker = current === line ? '>' : ' ';
|
|
34
|
+
out.push(` ${marker} ${String(current).padStart(gutter)} | ${lines[current - 1]}`);
|
|
35
|
+
if (current === line) {
|
|
36
|
+
out.push(` ${' '.repeat(gutter)} | ${' '.repeat(Math.max(0, column))}^`);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
return out.join('\n');
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Parses `code`, returning a readable diagnostic when it fails.
|
|
44
|
+
*
|
|
45
|
+
* @param {string} code
|
|
46
|
+
* @param {string} filePath shown in the message
|
|
47
|
+
* @returns {{ok: true} | {ok: false, message: string, line: number|null, column: number|null}}
|
|
48
|
+
*/
|
|
49
|
+
export function describeSyntaxError(code, filePath) {
|
|
50
|
+
try {
|
|
51
|
+
parse(code, { sourceType: 'module', plugins: ['jsx'] });
|
|
52
|
+
return { ok: true };
|
|
53
|
+
} catch (error) {
|
|
54
|
+
const line = error.loc?.line ?? null;
|
|
55
|
+
const column = error.loc?.column ?? 0;
|
|
56
|
+
const where = line ? `${filePath}:${line}:${column + 1}` : filePath;
|
|
57
|
+
// Babel appends its own "(line:col)"; drop it, the location is already
|
|
58
|
+
// stated above in a form editors can jump to.
|
|
59
|
+
const detail = String(error.message).replace(/\s*\(\d+:\d+\)\s*$/, '');
|
|
60
|
+
const frame = line ? `\n\n${formatSourceFrame(code, line, column)}\n` : '';
|
|
61
|
+
|
|
62
|
+
return {
|
|
63
|
+
ok: false,
|
|
64
|
+
line,
|
|
65
|
+
column,
|
|
66
|
+
message: `${where}: ${detail}.${frame}`
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Resolves a relative specifier the way the bundler does.
|
|
73
|
+
* @param {string} specifier
|
|
74
|
+
* @param {string} fromDir
|
|
75
|
+
* @returns {string|null} absolute path, or null when nothing matches
|
|
76
|
+
*/
|
|
77
|
+
export function resolveRelativeSpecifier(specifier, fromDir) {
|
|
78
|
+
const resolved = path.resolve(fromDir, specifier);
|
|
79
|
+
if (!path.extname(resolved)) {
|
|
80
|
+
for (const extension of RESOLVABLE_MODULE_EXTENSIONS) {
|
|
81
|
+
if (fs.existsSync(resolved + extension)) return resolved + extension;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
return fs.existsSync(resolved) ? resolved : null;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Relative imports that name a JavaScript module and resolve to nothing.
|
|
89
|
+
*
|
|
90
|
+
* Only module-like specifiers are reported — extensionless, or one of
|
|
91
|
+
* RESOLVABLE_MODULE_EXTENSIONS. A relative asset import has its own delivery
|
|
92
|
+
* story and is not the bundler's business.
|
|
93
|
+
*
|
|
94
|
+
* @param {string} code
|
|
95
|
+
* @param {string} fromDir directory the specifiers resolve against
|
|
96
|
+
* @returns {string[]} unresolved specifiers, in source order
|
|
97
|
+
*/
|
|
98
|
+
export function findUnresolvedRelativeImports(code, fromDir) {
|
|
99
|
+
let ast;
|
|
100
|
+
try {
|
|
101
|
+
ast = parse(code, { sourceType: 'module', plugins: ['jsx'] });
|
|
102
|
+
} catch {
|
|
103
|
+
return []; // unparseable: describeSyntaxError reports that instead
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
const unresolved = [];
|
|
107
|
+
for (const node of ast.program.body) {
|
|
108
|
+
const isImportLike = node.type === 'ImportDeclaration'
|
|
109
|
+
|| node.type === 'ExportNamedDeclaration'
|
|
110
|
+
|| node.type === 'ExportAllDeclaration';
|
|
111
|
+
const specifier = isImportLike ? node.source?.value : null;
|
|
112
|
+
if (typeof specifier !== 'string') continue;
|
|
113
|
+
if (!specifier.startsWith('./') && !specifier.startsWith('../')) continue;
|
|
114
|
+
|
|
115
|
+
const ext = path.extname(specifier);
|
|
116
|
+
const moduleLike = ext === '' || RESOLVABLE_MODULE_EXTENSIONS.includes(ext);
|
|
117
|
+
if (!moduleLike) continue;
|
|
118
|
+
|
|
119
|
+
if (!resolveRelativeSpecifier(specifier, fromDir)) unresolved.push(specifier);
|
|
120
|
+
}
|
|
121
|
+
return unresolved;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* True when the module has a default export.
|
|
126
|
+
*
|
|
127
|
+
* Slice loads a component with `const { default: myClass } = await import(...)`
|
|
128
|
+
* (Slice.getClass), so a component without one can never be built.
|
|
129
|
+
*
|
|
130
|
+
* @param {string} code
|
|
131
|
+
* @returns {boolean|null} null when the source does not parse
|
|
132
|
+
*/
|
|
133
|
+
export function hasDefaultExport(code) {
|
|
134
|
+
try {
|
|
135
|
+
const ast = parse(code, { sourceType: 'module', plugins: ['jsx'] });
|
|
136
|
+
return ast.program.body.some((node) => node.type === 'ExportDefaultDeclaration');
|
|
137
|
+
} catch {
|
|
138
|
+
return null;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* `slice.build('Name')` calls whose component is not in the registry.
|
|
144
|
+
*
|
|
145
|
+
* `slice.build` resolves a component by its registered name, so a typo returns
|
|
146
|
+
* null and the component simply never renders — the framework logs
|
|
147
|
+
* "Component X not found in components.js file" and carries on. Catching it at
|
|
148
|
+
* build time is the closest thing to a "module not found".
|
|
149
|
+
*
|
|
150
|
+
* Deliberately narrow:
|
|
151
|
+
* - only a `slice.build(...)` receiver (not an arbitrary `.build()` method),
|
|
152
|
+
* - only a string-literal first argument (a computed name cannot be checked),
|
|
153
|
+
* - `getComponent` is NOT checked: it takes a sliceId, which is arbitrary
|
|
154
|
+
* (`slice.getComponent('appTopbar')`), not a component name.
|
|
155
|
+
*
|
|
156
|
+
* @param {string} code
|
|
157
|
+
* @param {Set<string>} registeredNames
|
|
158
|
+
* @returns {string[]} unknown component names, deduped, in source order
|
|
159
|
+
*/
|
|
160
|
+
export function findUnknownComponentBuilds(code, registeredNames) {
|
|
161
|
+
let ast;
|
|
162
|
+
try {
|
|
163
|
+
ast = parse(code, { sourceType: 'module', plugins: ['jsx', 'classProperties'] });
|
|
164
|
+
} catch {
|
|
165
|
+
return [];
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
const unknown = [];
|
|
169
|
+
const seen = new Set();
|
|
170
|
+
|
|
171
|
+
const isSliceBuildCallee = (callee) => {
|
|
172
|
+
if (!callee || callee.type !== 'MemberExpression') return false;
|
|
173
|
+
if (callee.property?.name !== 'build') return false;
|
|
174
|
+
const object = callee.object;
|
|
175
|
+
if (object?.type === 'Identifier') return object.name === 'slice';
|
|
176
|
+
// window.slice.build(...)
|
|
177
|
+
return object?.type === 'MemberExpression' && object.property?.name === 'slice';
|
|
178
|
+
};
|
|
179
|
+
|
|
180
|
+
const walk = (node) => {
|
|
181
|
+
if (!node || typeof node !== 'object') return;
|
|
182
|
+
if (Array.isArray(node)) {
|
|
183
|
+
for (const child of node) walk(child);
|
|
184
|
+
return;
|
|
185
|
+
}
|
|
186
|
+
if (node.type === 'CallExpression' && isSliceBuildCallee(node.callee)) {
|
|
187
|
+
const first = node.arguments?.[0];
|
|
188
|
+
if (first?.type === 'StringLiteral' && !registeredNames.has(first.value) && !seen.has(first.value)) {
|
|
189
|
+
seen.add(first.value);
|
|
190
|
+
unknown.push(first.value);
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
for (const key of Object.keys(node)) {
|
|
194
|
+
if (key === 'loc' || key === 'start' || key === 'end') continue;
|
|
195
|
+
walk(node[key]);
|
|
196
|
+
}
|
|
197
|
+
};
|
|
198
|
+
|
|
199
|
+
walk(ast.program.body);
|
|
200
|
+
return unknown;
|
|
201
|
+
}
|