@widgetic/dev-tools 0.3.8 → 0.3.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,609 @@
1
+ /**
2
+ * Comments out the debugging `console` calls of a source file and keeps every one of them in the code. The CLI in
3
+ * `bin/comment-console-logs.mjs` reads files, prints and exits; this module decides what is commented out, what is
4
+ * kept, and why.
5
+ *
6
+ * It reads the code as code (the TypeScript parser for `.ts` / `.js` / `.mjs` and friends, the Svelte compiler's
7
+ * parser for `.svelte`), so a call inside a string, a comment or a template literal is never mistaken for a call,
8
+ * and a statement is only commented out where that cannot change what the program does:
9
+ *
10
+ * commented out a statement of its own in a block, a file or a `case`; a standalone `{console.log(...)}` tag in
11
+ * the markup of a Svelte file.
12
+ * kept, reported the body of a braceless `if` / `for` / `while` (commenting it would hand the next statement to
13
+ * the `if`); a call that is a value (`() => console.log(x)`, `ok && console.log(x)`,
14
+ * `.catch(console.log)`, a tag inside an attribute); a statement behind an `if (DEBUG...)` switch
15
+ * (the switch is how it is turned on, and commenting the call would leave a switch that does
16
+ * nothing); a statement that shares its line with other code and holds a `*` followed by a `/`.
17
+ *
18
+ * Only `console.log`, `console.info`, `console.debug` and `console.trace` are commented out. `console.warn` and
19
+ * `console.error` are never touched: they report things a partner or a developer has to see.
20
+ *
21
+ * How a statement is commented out: one that begins its line and ends its line gets `// ` in front of each of its
22
+ * lines, after the indentation, so taking the `// ` away gives the original back (a blank line inside it gets `//`).
23
+ * One that shares its line with other code goes between `/* ... *\/`. A standalone tag in a Svelte template goes
24
+ * between `<!-- ... -->`. A result is only handed back when the file reads as code the same way after the change:
25
+ * no parse error, and every statement that was meant to stay is still there.
26
+ *
27
+ * Neither parser is a dependency of this package. The caller hands over the loaded modules, and `loadParsers`
28
+ * resolves them from the checkout that is being edited, so the rules here run against the TypeScript and the
29
+ * Svelte the code is built with. Plain ESM with hand-written JSDoc types, same rules as `check-links.mjs`.
30
+ */
31
+
32
+ import { existsSync, readdirSync, statSync } from 'node:fs';
33
+ import { createRequire } from 'node:module';
34
+ import { extname, join, resolve } from 'node:path';
35
+ import { pathToFileURL } from 'node:url';
36
+
37
+ /** The console methods that are commented out. Every other method (`warn`, `error`, `table`, ...) is left alone. */
38
+ export const COMMENTED_CONSOLE_METHODS = Object.freeze(['log', 'info', 'debug', 'trace']);
39
+ const commentedConsoleMethodNames = new Set(COMMENTED_CONSOLE_METHODS);
40
+
41
+ /**
42
+ * The names a debug switch goes by (`DEBUG`, `DEBUG_PANEL`, `isDebugEnabled`, `debugMode`). A call behind an `if`
43
+ * whose condition names one of them is kept: the switch is how the call is turned on.
44
+ */
45
+ export const DEBUG_SWITCH_PATTERN = /\bDEBUG[A-Z0-9_]*\b|\bisDebug\w*\b|\bdebugMode\b/;
46
+
47
+ /** The files a directory walk picks up. A file named on the command line is read whatever its extension is, as long as it is one of these. */
48
+ export const SOURCE_FILE_EXTENSIONS = Object.freeze(['.ts', '.mts', '.cts', '.tsx', '.js', '.mjs', '.cjs', '.jsx', '.svelte']);
49
+
50
+ /** Directories a walk does not enter (a directory named on the command line is always entered). */
51
+ export const SKIPPED_DIRECTORY_NAMES = Object.freeze(['node_modules', '.git', '.svelte-kit', 'dist', 'build', '.output', 'coverage']);
52
+
53
+ // Why a call is kept. One string per reason, so the report groups them and the tests can name them.
54
+ export const KEPT_REASONS = Object.freeze({
55
+ debugSwitch: 'behind an if (DEBUG...) switch: the switch is how it is turned on',
56
+ bracelessBody: 'the body of a braceless control statement: commenting it would change which statement the control owns',
57
+ usedAsValue: 'a call used as a value (arrow body, `&&`, argument, ...)',
58
+ handedOver: 'console.<method> handed over as a function (`.catch(console.log)`)',
59
+ insideAttribute: 'a tag inside an attribute: a comment cannot go there',
60
+ wrongPosition: 'the parser gave a position that is not the statement',
61
+ holdsCommentEnd: 'it shares its line with other code and holds `*/`',
62
+ holdsLineSeparator: 'it holds a line separator character, which would end a `//` comment early',
63
+ holdsHtmlCommentEnd: 'the tag holds `-->`, which would end an HTML comment'
64
+ });
65
+
66
+ /**
67
+ * @typedef {object} Parsers
68
+ * @property {any} [typescript] The loaded `typescript` module (needed for every file that is not `.svelte`).
69
+ * @property {any} [svelteCompiler] The loaded `svelte/compiler` module (needed for `.svelte` files).
70
+ */
71
+
72
+ /**
73
+ * One place where the code calls `console.log` (or `info`, `debug`, `trace`) and what is done about it.
74
+ * @typedef {object} ConsoleFinding
75
+ * @property {number} start Offset of the first character of the call or statement.
76
+ * @property {number} end Offset after its last character.
77
+ * @property {number} line One-based line of `start`.
78
+ * @property {'statement' | 'value' | 'template tag'} shape How the call sits in the code.
79
+ * @property {'comment' | 'keep'} action What the rules say to do with it.
80
+ * @property {string} [reason] Why it is kept (one of `KEPT_REASONS`).
81
+ * @property {string} text The call, on one line, cut at 110 characters.
82
+ */
83
+
84
+ /**
85
+ * @typedef {object} CommentOutResult
86
+ * @property {'commented' | 'unchanged' | 'left alone'} status `commented`: there is a new text. `unchanged`: nothing to comment out. `left alone`: the file could not be read as code, or the change did not check out.
87
+ * @property {string} [reason] Why the file was left alone.
88
+ * @property {string} updatedText The text with the statements commented out (the original text unless `status` is `commented`).
89
+ * @property {ConsoleFinding[]} commented The statements and tags that are commented out.
90
+ * @property {ConsoleFinding[]} kept The calls that stay as they are, each with its `reason`.
91
+ * @property {number} commentedAlong How many more calls sat inside a commented statement (they are commented with it, and not listed).
92
+ */
93
+
94
+ // ---- Parsers -----------------------------------------------------------------------------------------------------
95
+
96
+ /** Is this the kind of file the Svelte compiler reads? */
97
+ function isSvelteFile(filePath) {
98
+ return extname(filePath).toLowerCase() === '.svelte';
99
+ }
100
+
101
+ /**
102
+ * Does the tool read this file by its extension?
103
+ * @param {string} filePath
104
+ * @returns {boolean}
105
+ */
106
+ export function isSourceFile(filePath) {
107
+ return SOURCE_FILE_EXTENSIONS.includes(extname(filePath).toLowerCase());
108
+ }
109
+
110
+ /**
111
+ * Which parsers the given files need: TypeScript for every script, the Svelte compiler for `.svelte`.
112
+ * @param {string[]} filePaths
113
+ * @returns {{ typescript: boolean, svelte: boolean }}
114
+ */
115
+ export function parsersNeededFor(filePaths) {
116
+ return {
117
+ typescript: filePaths.some((filePath) => !isSvelteFile(filePath)),
118
+ svelte: filePaths.some((filePath) => isSvelteFile(filePath))
119
+ };
120
+ }
121
+
122
+ /**
123
+ * Loads `typescript` and `svelte/compiler` the way a file in `resolveFromDirectory` would: from its
124
+ * `node_modules`, or the ones above it. Only what is asked for is loaded, so a run over scripts needs no Svelte.
125
+ * @param {string} resolveFromDirectory A checkout (or any directory below one) that has the packages installed.
126
+ * @param {{ typescript?: boolean, svelte?: boolean }} [needs]
127
+ * @returns {Parsers}
128
+ * @throws {Error} Naming the packages that could not be loaded and the directory they were looked for from.
129
+ */
130
+ export function loadParsers(resolveFromDirectory, needs = { typescript: true, svelte: true }) {
131
+ const directory = resolve(resolveFromDirectory);
132
+ const requireFromTarget = createRequire(pathToFileURL(join(directory, 'package.json')));
133
+ /** @type {Parsers} */
134
+ const parsers = {};
135
+ const missingPackages = [];
136
+ if (needs.typescript) {
137
+ try {
138
+ parsers.typescript = requireFromTarget('typescript');
139
+ } catch {
140
+ missingPackages.push('typescript');
141
+ }
142
+ }
143
+ if (needs.svelte) {
144
+ try {
145
+ parsers.svelteCompiler = requireFromTarget('svelte/compiler');
146
+ } catch {
147
+ missingPackages.push('svelte');
148
+ }
149
+ }
150
+ if (missingPackages.length > 0) {
151
+ throw new Error(
152
+ `could not load ${missingPackages.join(' and ')} from ${directory} (install it there, or point --resolve-from at a checkout that has it)`
153
+ );
154
+ }
155
+ return parsers;
156
+ }
157
+
158
+ // ---- Finding the calls -------------------------------------------------------------------------------------------
159
+
160
+ /**
161
+ * A function that says which line an offset is on, with the line starts worked out once for the whole text.
162
+ * @param {string} sourceText
163
+ * @returns {(offset: number) => number}
164
+ */
165
+ function createLineLocator(sourceText) {
166
+ const lineStartOffsets = [0];
167
+ for (let index = 0; index < sourceText.length; index += 1) {
168
+ if (sourceText.charCodeAt(index) === 10) lineStartOffsets.push(index + 1);
169
+ }
170
+ return (offset) => {
171
+ let low = 0;
172
+ let high = lineStartOffsets.length - 1;
173
+ while (low < high) {
174
+ const middle = Math.ceil((low + high) / 2);
175
+ if (lineStartOffsets[middle] <= offset) low = middle;
176
+ else high = middle - 1;
177
+ }
178
+ return low + 1;
179
+ };
180
+ }
181
+
182
+ /**
183
+ * @param {string} sourceText
184
+ * @param {(offset: number) => number} locateLine
185
+ * @param {number} start
186
+ * @param {number} end
187
+ * @param {ConsoleFinding['shape']} shape
188
+ * @param {ConsoleFinding['action']} action
189
+ * @param {string} [reason]
190
+ * @returns {ConsoleFinding}
191
+ */
192
+ function describeFinding(sourceText, locateLine, start, end, shape, action, reason) {
193
+ return {
194
+ start,
195
+ end,
196
+ line: locateLine(start),
197
+ shape,
198
+ action,
199
+ reason,
200
+ text: sourceText.slice(start, end).replace(/\s+/g, ' ').slice(0, 110)
201
+ };
202
+ }
203
+
204
+ /** The error a missing parser raises, so a run that cannot read a file at all is told apart from a file that is not code. */
205
+ function parserNotLoadedError(packageName, filePath) {
206
+ const error = new Error(`${packageName} was not loaded, and ${filePath} needs it`);
207
+ /** @type {any} */ (error).code = 'PARSER_NOT_LOADED';
208
+ return error;
209
+ }
210
+
211
+ function scriptKindOf(typescript, filePath) {
212
+ const extension = extname(filePath).toLowerCase();
213
+ if (extension === '.ts' || extension === '.mts' || extension === '.cts') return typescript.ScriptKind.TS;
214
+ if (extension === '.tsx') return typescript.ScriptKind.TSX;
215
+ if (extension === '.jsx') return typescript.ScriptKind.JSX;
216
+ return typescript.ScriptKind.JS;
217
+ }
218
+
219
+ /**
220
+ * The calls in a script (`.ts`, `.js`, `.mjs`, ...), by the TypeScript parser.
221
+ * @param {string} sourceText
222
+ * @param {string} filePath
223
+ * @param {any} typescript
224
+ * @returns {{ findings: ConsoleFinding[], parseErrors: number }}
225
+ */
226
+ function findInScript(sourceText, filePath, typescript) {
227
+ const sourceFile = typescript.createSourceFile(filePath, sourceText, typescript.ScriptTarget.Latest, true, scriptKindOf(typescript, filePath));
228
+ const locateLine = createLineLocator(sourceText);
229
+ /** @type {ConsoleFinding[]} */
230
+ const findings = [];
231
+
232
+ // `console.<method>` where the method is one that is commented out.
233
+ const isConsoleMethodAccess = (node) =>
234
+ typescript.isPropertyAccessExpression(node) &&
235
+ typescript.isIdentifier(node.expression) &&
236
+ node.expression.text === 'console' &&
237
+ commentedConsoleMethodNames.has(node.name.text);
238
+
239
+ // A statement list is somewhere a statement can be taken out of without changing what its neighbours belong to.
240
+ const isStatementList = (node) =>
241
+ typescript.isBlock(node) ||
242
+ typescript.isSourceFile(node) ||
243
+ typescript.isModuleBlock(node) ||
244
+ typescript.isCaseClause(node) ||
245
+ typescript.isDefaultClause(node);
246
+
247
+ // Is the statement in the "then" part of an `if` whose condition names a debug switch? A function between them ends the search.
248
+ const isBehindDebugSwitch = (statement) => {
249
+ let child = statement;
250
+ for (let ancestor = statement.parent; ancestor && !typescript.isSourceFile(ancestor); ancestor = ancestor.parent) {
251
+ if (typescript.isFunctionLike(ancestor)) return false;
252
+ if (typescript.isIfStatement(ancestor) && ancestor.thenStatement === child && DEBUG_SWITCH_PATTERN.test(ancestor.expression.getText(sourceFile))) return true;
253
+ child = ancestor;
254
+ }
255
+ return false;
256
+ };
257
+
258
+ const visit = (node) => {
259
+ if (typescript.isCallExpression(node) && isConsoleMethodAccess(node.expression)) {
260
+ const parent = node.parent;
261
+ if (typescript.isExpressionStatement(parent) && parent.expression === node) {
262
+ const start = parent.getStart(sourceFile);
263
+ const end = parent.end;
264
+ if (isBehindDebugSwitch(parent)) {
265
+ findings.push(describeFinding(sourceText, locateLine, start, end, 'statement', 'keep', KEPT_REASONS.debugSwitch));
266
+ } else if (isStatementList(parent.parent)) {
267
+ findings.push(describeFinding(sourceText, locateLine, start, end, 'statement', 'comment'));
268
+ } else {
269
+ findings.push(describeFinding(sourceText, locateLine, start, end, 'statement', 'keep', KEPT_REASONS.bracelessBody));
270
+ }
271
+ } else {
272
+ findings.push(describeFinding(sourceText, locateLine, node.getStart(sourceFile), node.end, 'value', 'keep', KEPT_REASONS.usedAsValue));
273
+ }
274
+ } else if (isConsoleMethodAccess(node) && !(typescript.isCallExpression(node.parent) && node.parent.expression === node)) {
275
+ findings.push(describeFinding(sourceText, locateLine, node.getStart(sourceFile), node.end, 'value', 'keep', KEPT_REASONS.handedOver));
276
+ }
277
+ typescript.forEachChild(node, visit);
278
+ };
279
+ visit(sourceFile);
280
+ return { findings, parseErrors: sourceFile.parseDiagnostics.length };
281
+ }
282
+
283
+ /**
284
+ * Walks a Svelte modern AST (ESTree nodes inside Svelte nodes), calling `visit(node, parents)` for every node.
285
+ * @param {any} root
286
+ * @param {(node: any, parents: any[]) => void} visit
287
+ */
288
+ function walkSvelteAst(root, visit) {
289
+ const seen = new WeakSet();
290
+ const step = (node, parents) => {
291
+ if (!node || typeof node !== 'object' || seen.has(node)) return;
292
+ seen.add(node);
293
+ if (Array.isArray(node)) {
294
+ for (const item of node) step(item, parents);
295
+ return;
296
+ }
297
+ if (typeof node.type === 'string') visit(node, parents);
298
+ const nextParents = typeof node.type === 'string' ? [...parents, node] : parents;
299
+ for (const [key, value] of Object.entries(node)) {
300
+ if (key === 'metadata' || key === 'parent' || key === 'loc') continue;
301
+ step(value, nextParents);
302
+ }
303
+ };
304
+ step(root, []);
305
+ }
306
+
307
+ function isEstreeConsoleMember(node) {
308
+ return (
309
+ node?.type === 'MemberExpression' &&
310
+ !node.computed &&
311
+ node.object?.type === 'Identifier' &&
312
+ node.object.name === 'console' &&
313
+ node.property?.type === 'Identifier' &&
314
+ commentedConsoleMethodNames.has(node.property.name)
315
+ );
316
+ }
317
+
318
+ function isEstreeConsoleCall(node) {
319
+ return node?.type === 'CallExpression' && isEstreeConsoleMember(node.callee);
320
+ }
321
+
322
+ /**
323
+ * The calls in a Svelte file: its scripts and its markup, by the Svelte compiler's parser.
324
+ * @param {string} sourceText
325
+ * @param {string} filePath
326
+ * @param {any} svelteCompiler
327
+ * @returns {{ findings: ConsoleFinding[], parseErrors: number }}
328
+ */
329
+ function findInSvelte(sourceText, filePath, svelteCompiler) {
330
+ const abstractSyntaxTree = svelteCompiler.parse(sourceText, { modern: true, filename: filePath });
331
+ const locateLine = createLineLocator(sourceText);
332
+ /** @type {ConsoleFinding[]} */
333
+ const findings = [];
334
+
335
+ // Is the node on the "then" side of an `if` (a statement in a script, a block in the markup) whose condition names a
336
+ // debug switch? A function, or a snippet, between them ends the search: it runs when it is called.
337
+ const isBehindDebugSwitch = (node, parents) => {
338
+ let child = node;
339
+ for (let index = parents.length - 1; index >= 0; index -= 1) {
340
+ const ancestor = parents[index];
341
+ if (/Function/.test(ancestor.type) || ancestor.type === 'SnippetBlock') return false;
342
+ const isIfOfSomeKind = ancestor.type === 'IfStatement' || ancestor.type === 'IfBlock';
343
+ if (isIfOfSomeKind && ancestor.consequent === child && ancestor.test && DEBUG_SWITCH_PATTERN.test(sourceText.slice(ancestor.test.start, ancestor.test.end))) return true;
344
+ child = ancestor;
345
+ }
346
+ return false;
347
+ };
348
+
349
+ walkSvelteAst(abstractSyntaxTree, (node, parents) => {
350
+ const parent = parents[parents.length - 1];
351
+ if (node.type === 'ExpressionStatement' && isEstreeConsoleCall(node.expression)) {
352
+ const listParent = parent && ['BlockStatement', 'Program', 'SwitchCase', 'StaticBlock'].includes(parent.type);
353
+ if (!sourceText.slice(node.start, node.end).startsWith('console.')) {
354
+ findings.push(describeFinding(sourceText, locateLine, node.start, node.end, 'statement', 'keep', KEPT_REASONS.wrongPosition));
355
+ } else if (isBehindDebugSwitch(node, parents)) {
356
+ findings.push(describeFinding(sourceText, locateLine, node.start, node.end, 'statement', 'keep', KEPT_REASONS.debugSwitch));
357
+ } else if (listParent) {
358
+ findings.push(describeFinding(sourceText, locateLine, node.start, node.end, 'statement', 'comment'));
359
+ } else {
360
+ findings.push(describeFinding(sourceText, locateLine, node.start, node.end, 'statement', 'keep', KEPT_REASONS.bracelessBody));
361
+ }
362
+ } else if (node.type === 'ExpressionTag' && isEstreeConsoleCall(node.expression)) {
363
+ // A tag of its own in the markup can become an HTML comment. One inside an attribute cannot.
364
+ if (parent?.type !== 'Fragment') {
365
+ findings.push(describeFinding(sourceText, locateLine, node.start, node.end, 'value', 'keep', KEPT_REASONS.insideAttribute));
366
+ } else if (isBehindDebugSwitch(node, parents)) {
367
+ findings.push(describeFinding(sourceText, locateLine, node.start, node.end, 'template tag', 'keep', KEPT_REASONS.debugSwitch));
368
+ } else {
369
+ findings.push(describeFinding(sourceText, locateLine, node.start, node.end, 'template tag', 'comment'));
370
+ }
371
+ } else if (isEstreeConsoleCall(node)) {
372
+ // A call that is a statement or a tag was described above.
373
+ if (parent?.type !== 'ExpressionStatement' && parent?.type !== 'ExpressionTag') {
374
+ findings.push(describeFinding(sourceText, locateLine, node.start, node.end, 'value', 'keep', KEPT_REASONS.usedAsValue));
375
+ }
376
+ } else if (isEstreeConsoleMember(node) && !(parent?.type === 'CallExpression' && parent.callee === node)) {
377
+ findings.push(describeFinding(sourceText, locateLine, node.start, node.end, 'value', 'keep', KEPT_REASONS.handedOver));
378
+ }
379
+ });
380
+ return { findings, parseErrors: 0 };
381
+ }
382
+
383
+ /**
384
+ * Every `console.log` / `info` / `debug` / `trace` in the text, with what the rules say to do about each.
385
+ * @param {string} sourceText
386
+ * @param {string} filePath Its extension says which parser reads it.
387
+ * @param {Parsers} parsers
388
+ * @returns {{ findings: ConsoleFinding[], parseErrors: number }}
389
+ * @throws The Svelte compiler's error when a `.svelte` file is not valid, and a `PARSER_NOT_LOADED` error when the parser the file needs was not handed over.
390
+ */
391
+ export function findConsoleCalls(sourceText, filePath, parsers) {
392
+ let analysis;
393
+ if (isSvelteFile(filePath)) {
394
+ if (!parsers.svelteCompiler) throw parserNotLoadedError('svelte/compiler', filePath);
395
+ analysis = findInSvelte(sourceText, filePath, parsers.svelteCompiler);
396
+ } else {
397
+ if (!parsers.typescript) throw parserNotLoadedError('typescript', filePath);
398
+ analysis = findInScript(sourceText, filePath, parsers.typescript);
399
+ }
400
+ // In the order they stand in the file (the Svelte walk meets the markup before the scripts).
401
+ analysis.findings.sort((first, second) => first.start - second.start || first.end - second.end);
402
+ return analysis;
403
+ }
404
+
405
+ // ---- Commenting a finding out ------------------------------------------------------------------------------------
406
+
407
+ /**
408
+ * `// ` in front of one line of a statement, after the indentation of the statement's first line. A blank line gets
409
+ * `//` only. Taking the added characters away gives the line back, trailing blanks included.
410
+ * @param {string} line
411
+ * @param {string} indentation
412
+ * @returns {string}
413
+ */
414
+ function commentOutLine(line, indentation) {
415
+ // A carriage return at the end of a line (CRLF) is whitespace that stays where it is: it is neither read as content
416
+ // (`trim` takes it away for the blank test) nor moved, because only the start of the line is touched.
417
+ const marker = line.trim() === '' ? '//' : '// ';
418
+ return line.startsWith(indentation) ? `${indentation}${marker}${line.slice(indentation.length)}` : `${marker}${line}`;
419
+ }
420
+
421
+ /**
422
+ * The edit that comments one finding out, or a `skip` (with the reason) when it cannot be done without touching
423
+ * other code.
424
+ * @param {string} sourceText
425
+ * @param {ConsoleFinding} finding
426
+ * @returns {{ start: number, end: number, replacement: string } | { skip: string }}
427
+ */
428
+ export function planEdit(sourceText, finding) {
429
+ const original = sourceText.slice(finding.start, finding.end);
430
+
431
+ if (finding.shape === 'template tag') {
432
+ if (original.includes('-->')) return { skip: KEPT_REASONS.holdsHtmlCommentEnd };
433
+ return { start: finding.start, end: finding.end, replacement: `<!-- ${original} -->` };
434
+ }
435
+
436
+ const lineStart = sourceText.lastIndexOf('\n', finding.start - 1) + 1;
437
+ const lineEndIndex = sourceText.indexOf('\n', finding.end);
438
+ const lineEnd = lineEndIndex === -1 ? sourceText.length : lineEndIndex;
439
+ const textBefore = sourceText.slice(lineStart, finding.start);
440
+ const textAfter = sourceText.slice(finding.end, lineEnd);
441
+ // Alone on its lines: nothing but blanks before it, and after it blanks or a line comment (which stays after the `// `).
442
+ const isAloneOnItsLines = /^[ \t]*$/.test(textBefore) && /^[ \t]*(\/\/[^\r\n]*)?\r?$/.test(textAfter);
443
+
444
+ if (isAloneOnItsLines) {
445
+ if (/[\u2028\u2029]/.test(original)) return { skip: KEPT_REASONS.holdsLineSeparator };
446
+ const indentation = textBefore;
447
+ const block = sourceText.slice(lineStart, finding.end);
448
+ const commentedBlock = block
449
+ .split('\n')
450
+ .map((line) => commentOutLine(line, indentation))
451
+ .join('\n');
452
+ return { start: lineStart, end: finding.end, replacement: commentedBlock };
453
+ }
454
+
455
+ if (original.includes('*/')) return { skip: KEPT_REASONS.holdsCommentEnd };
456
+ return { start: finding.start, end: finding.end, replacement: `/* ${original} */` };
457
+ }
458
+
459
+ /**
460
+ * Applies edits that do not overlap, last one first so the offsets of the others stay right.
461
+ * @param {string} sourceText
462
+ * @param {{ start: number, end: number, replacement: string }[]} edits
463
+ * @returns {string}
464
+ */
465
+ export function applyEdits(sourceText, edits) {
466
+ let resultText = sourceText;
467
+ for (const edit of [...edits].sort((first, second) => second.start - first.start)) {
468
+ resultText = resultText.slice(0, edit.start) + edit.replacement + resultText.slice(edit.end);
469
+ }
470
+ return resultText;
471
+ }
472
+
473
+ /**
474
+ * Does the changed text read as code the same way? No parse error, no statement left that should have been commented
475
+ * out (apart from the ones that were skipped), and as many calls kept as before.
476
+ * @param {string} updatedText
477
+ * @param {string} filePath
478
+ * @param {Parsers} parsers
479
+ * @param {{ skippedCount: number, keptCount: number }} expected
480
+ * @returns {{ ok: true } | { ok: false, reason: string }}
481
+ */
482
+ export function checkCommentedText(updatedText, filePath, parsers, expected) {
483
+ let analysis;
484
+ try {
485
+ analysis = findConsoleCalls(updatedText, filePath, parsers);
486
+ } catch (error) {
487
+ if (/** @type {any} */ (error)?.code === 'PARSER_NOT_LOADED') throw error;
488
+ return { ok: false, reason: `the result no longer reads as code (${firstLineOf(error)})` };
489
+ }
490
+ if (analysis.parseErrors > 0) return { ok: false, reason: `the result has ${analysis.parseErrors} parse error(s)` };
491
+ const stillToComment = analysis.findings.filter((finding) => finding.action === 'comment').length;
492
+ const stillKept = analysis.findings.filter((finding) => finding.action === 'keep').length;
493
+ if (stillToComment !== expected.skippedCount) {
494
+ return { ok: false, reason: `${stillToComment} statement(s) are still to comment out in the result, ${expected.skippedCount} were expected` };
495
+ }
496
+ if (stillKept !== expected.keptCount) {
497
+ return { ok: false, reason: `${stillKept} call(s) are kept in the result, ${expected.keptCount} were expected` };
498
+ }
499
+ return { ok: true };
500
+ }
501
+
502
+ /** The first line of an error's message: the Svelte compiler's errors carry a code frame after it. */
503
+ function firstLineOf(error) {
504
+ return String(/** @type {any} */ (error)?.message ?? error).split('\n')[0];
505
+ }
506
+
507
+ /**
508
+ * Comments out what can be commented out in one file's text, and says what it kept and why. Nothing is read or
509
+ * written here: the text goes in, the new text comes out.
510
+ * @param {string} sourceText
511
+ * @param {string} filePath Its extension says which parser reads it.
512
+ * @param {Parsers} parsers
513
+ * @returns {CommentOutResult}
514
+ * @throws A `PARSER_NOT_LOADED` error when the parser the file needs was not handed over.
515
+ */
516
+ export function commentOutConsoleLogs(sourceText, filePath, parsers) {
517
+ /** @param {string} reason */
518
+ const leftAlone = (reason) => ({ status: /** @type {const} */ ('left alone'), reason, updatedText: sourceText, commented: [], kept: [], commentedAlong: 0 });
519
+
520
+ let analysis;
521
+ try {
522
+ analysis = findConsoleCalls(sourceText, filePath, parsers);
523
+ } catch (error) {
524
+ if (/** @type {any} */ (error)?.code === 'PARSER_NOT_LOADED') throw error;
525
+ return leftAlone(`could not read it as code (${firstLineOf(error)})`);
526
+ }
527
+ if (analysis.parseErrors > 0) return leftAlone(`${analysis.parseErrors} parse error(s) before any change`);
528
+
529
+ // What can be done with each statement the rules say to comment out.
530
+ const plannedFindings = analysis.findings.map((finding) => ({ finding, plan: finding.action === 'comment' ? planEdit(sourceText, finding) : null }));
531
+ const appliedRanges = plannedFindings.filter(({ plan }) => plan && !('skip' in plan)).map(({ finding }) => finding);
532
+
533
+ // A call inside a statement that is commented out goes with it: it has no edit of its own, and no line in the report.
534
+ const isCoveredByAnother = (finding) => appliedRanges.some((outer) => outer !== finding && outer.start <= finding.start && finding.end <= outer.end);
535
+
536
+ /** @type {ConsoleFinding[]} */
537
+ const commented = [];
538
+ /** @type {ConsoleFinding[]} */
539
+ const kept = [];
540
+ /** @type {{ start: number, end: number, replacement: string }[]} */
541
+ const edits = [];
542
+ let commentedAlong = 0;
543
+ let skippedCount = 0;
544
+ for (const { finding, plan } of plannedFindings) {
545
+ if (isCoveredByAnother(finding)) {
546
+ commentedAlong += 1;
547
+ } else if (plan && !('skip' in plan)) {
548
+ edits.push(plan);
549
+ commented.push(finding);
550
+ } else {
551
+ if (plan) skippedCount += 1;
552
+ kept.push({ ...finding, reason: plan && 'skip' in plan ? plan.skip : finding.reason });
553
+ }
554
+ }
555
+
556
+ if (edits.length === 0) return { status: 'unchanged', updatedText: sourceText, commented, kept, commentedAlong };
557
+
558
+ const updatedText = applyEdits(sourceText, edits);
559
+ const verdict = checkCommentedText(updatedText, filePath, parsers, { skippedCount, keptCount: kept.length - skippedCount });
560
+ if (!verdict.ok) return leftAlone(verdict.reason);
561
+ return { status: 'commented', updatedText, commented, kept, commentedAlong };
562
+ }
563
+
564
+ // ---- Finding the files -------------------------------------------------------------------------------------------
565
+
566
+ /**
567
+ * Walks a directory for source files, in name order, without entering the directories a checkout keeps its output
568
+ * and its packages in. A link is not followed.
569
+ * @param {string} directory
570
+ * @param {string[]} foundFiles Receives the paths.
571
+ */
572
+ function walkDirectory(directory, foundFiles) {
573
+ const entries = readdirSync(directory, { withFileTypes: true }).sort((first, second) => (first.name < second.name ? -1 : first.name > second.name ? 1 : 0));
574
+ for (const entry of entries) {
575
+ const entryPath = join(directory, entry.name);
576
+ if (entry.isDirectory()) {
577
+ if (!SKIPPED_DIRECTORY_NAMES.includes(entry.name)) walkDirectory(entryPath, foundFiles);
578
+ } else if (entry.isFile() && isSourceFile(entry.name)) {
579
+ foundFiles.push(entryPath);
580
+ }
581
+ }
582
+ }
583
+
584
+ /**
585
+ * The files to read for the paths given on the command line: a file is itself (when it is a kind of file the tool
586
+ * reads), a directory is every source file below it.
587
+ * @param {string[]} paths
588
+ * @returns {{ files: string[], problems: { path: string, reason: string }[] }}
589
+ */
590
+ export function collectSourceFiles(paths) {
591
+ /** @type {string[]} */
592
+ const files = [];
593
+ /** @type {{ path: string, reason: string }[]} */
594
+ const problems = [];
595
+ for (const inputPath of paths) {
596
+ if (!existsSync(inputPath)) {
597
+ problems.push({ path: inputPath, reason: 'not found' });
598
+ continue;
599
+ }
600
+ if (statSync(inputPath).isDirectory()) {
601
+ walkDirectory(inputPath, files);
602
+ } else if (isSourceFile(inputPath)) {
603
+ files.push(inputPath);
604
+ } else {
605
+ problems.push({ path: inputPath, reason: `not a kind of file this tool reads (${SOURCE_FILE_EXTENSIONS.join(', ')})` });
606
+ }
607
+ }
608
+ return { files: [...new Set(files)], problems };
609
+ }
@@ -82,7 +82,9 @@ export const SIBLING_PACKAGES = {
82
82
  // `dir` was `props-editor` (see older configs — and dangling symlinks).
83
83
  editor: { dir: 'editor', lib: 'src/lib' },
84
84
  'file-browser': { dir: 'file-browser', lib: 'src/lib' },
85
- workflows: { dir: 'workflows', lib: 'src/lib' }
85
+ workflows: { dir: 'workflows', lib: 'src/lib' },
86
+ // The graph model and state machine of workflows: no dependencies, read by the Embed SDK, the editor and the gateway.
87
+ 'workflows-engine': { dir: 'workflows-engine', entry: 'src/index.ts' }
86
88
  };
87
89
 
88
90
  /**
@@ -19,6 +19,7 @@ export const PUBLISHABLE_PACKAGES = [
19
19
  { dir: 'editor', script: 'publish-to-npm' },
20
20
  { dir: 'file-browser', script: 'publish-to-npm' },
21
21
  { dir: 'widget-creator', script: 'publish-to-npm' },
22
+ { dir: 'workflows-engine', script: 'publish-to-npm' },
22
23
  { dir: 'workflows', script: 'publish-to-npm' },
23
24
  { dir: 'embed-sdk', script: 'publish-to-npm' },
24
25
  { dir: 'ui-sdk', script: 'publish-to-npm' }
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@widgetic/dev-tools",
3
- "version": "0.3.8",
3
+ "version": "0.3.9",
4
4
  "type": "module",
5
- "description": "Build-time checks and dev tooling shared by the published @widgetic packages, released once so the repositories that consume them cannot drift apart. Currently: check-runtime-deps (with the fixture suite that proves it fails), the Vite sibling-$lib remap, the canonical Frontend sibling layout that builds every consumer's dev-alias tables, and check-links — the link-doctor that fails when a sibling symlink dangles, a promised dist/ file is missing, or a dead checkout name lingers, and check-design-system-peers — which fails when the two design-system peers' lockfiles drift apart.",
5
+ "description": "Build-time checks and dev tooling shared by the published @widgetic packages, released once so the repositories that consume them cannot drift apart. Currently: check-runtime-deps (with the fixture suite that proves it fails), the Vite sibling-$lib remap, the canonical Frontend sibling layout that builds every consumer's dev-alias tables, and check-links — the link-doctor that fails when a sibling symlink dangles, a promised dist/ file is missing, or a dead checkout name lingers, check-design-system-peers — which fails when the two design-system peers' lockfiles drift apart, and comment-console-logs — which comments out the debugging console calls of a codebase and keeps every one of them in the code.",
6
6
  "repository": {
7
7
  "type": "git",
8
8
  "url": "git+https://gitlab.com/widgeticai/Frontend/dev-tools.git"
@@ -23,6 +23,7 @@
23
23
  "check-readme-contracts-fixtures": "bin/check-readme-contracts-fixtures.mjs",
24
24
  "check-layout-fixtures": "bin/check-layout-fixtures.mjs",
25
25
  "check-design-system-peers": "bin/check-design-system-peers.mjs",
26
+ "comment-console-logs": "bin/comment-console-logs.mjs",
26
27
  "publish-all-to-npm": "bin/publish-all-to-npm.mjs"
27
28
  },
28
29
  "files": [
@@ -45,7 +46,8 @@
45
46
  "test:peers": "node --test test/lockfile-peers.test.mjs",
46
47
  "test:publish": "node --test test/publish-to-npm.test.mjs",
47
48
  "test:lists": "node --test test/package-lists.test.mjs",
48
- "test": "npm run check:deps && npm run test:deps && npm run test:vite && npm run test:layout && npm run test:links && npm run test:readme && npm run test:peers && npm run test:publish && npm run test:lists",
49
+ "test:comment-logs": "node --test test/comment-console-logs.test.mjs",
50
+ "test": "npm run check:deps && npm run test:deps && npm run test:vite && npm run test:layout && npm run test:links && npm run test:readme && npm run test:peers && npm run test:publish && npm run test:lists && npm run test:comment-logs",
49
51
  "publish-to-npm": "node bin/publish-package.mjs",
50
52
  "publish-all-to-npm": "node bin/publish-all-to-npm.mjs",
51
53
  "prepublishOnly": "npm test"