From fc22ad1feeebd26d2f4bf8be07a5ce5ef68609d3 Mon Sep 17 00:00:00 2001 From: RRFZ <247457381+Plastic-time@users.noreply.github.com> Date: Sat, 14 Nov 2026 23:14:56 -0500 Subject: [PATCH] Read .cts files as CommonJS and .mts files as ES modules (R3.12) (#1886) .cts and .mts got the same source type as .ts, where the parser decides between module and script from the syntax, so their reported source kind could be wrong. As in Node and TypeScript, .cts is now always CommonJS and .mts always an ES module. --- crates/js/src/lib.rs | 10 +++- crates/js/tests/regression_ts_module_kind.rs | 53 ++++++++++++++++++++ docs/ROADMAP.md | 2 + docs/STATUS.md | 1 + 4 files changed, 64 insertions(+), 2 deletions(-) create mode 100644 crates/js/tests/regression_ts_module_kind.rs diff --git a/crates/js/src/lib.rs b/crates/js/src/lib.rs index c89d2a79d..8b9bded19 100644 --- a/crates/js/src/lib.rs +++ b/crates/js/src/lib.rs @@ -77,12 +77,18 @@ pub(crate) fn guarded(f: impl FnOnce() -> T + Send + 'static) Ok(f()) } -/// Pick a source type from the file name. +/// Pick a source type from the file name. As in Node and TypeScript, `.cts` and `.cjs` are +/// CommonJS and `.mts` and `.mjs` are ES modules whatever their syntax; `.ts` and `.js` are +/// decided by the syntax. pub fn source_type_for(path: &str) -> SourceType { let lower = path.to_ascii_lowercase(); if lower.ends_with(".tsx") { SourceType::tsx() - } else if lower.ends_with(".ts") || lower.ends_with(".mts") || lower.ends_with(".cts") { + } else if lower.ends_with(".cts") { + SourceType::cjs().with_typescript(true) + } else if lower.ends_with(".mts") { + SourceType::mjs().with_typescript(true) + } else if lower.ends_with(".ts") { SourceType::ts() } else if lower.ends_with(".mjs") { SourceType::mjs().with_jsx(false) diff --git a/crates/js/tests/regression_ts_module_kind.rs b/crates/js/tests/regression_ts_module_kind.rs new file mode 100644 index 000000000..5a85435db --- /dev/null +++ b/crates/js/tests/regression_ts_module_kind.rs @@ -0,0 +1,53 @@ +//! Node and TypeScript fix the module system by extension: `.cts` is CommonJS and `.mts` is an +//! ES module whatever the file contains. Both used to be read like `.ts`, where the syntax decides, +//! so a `.cts` file that calls `require` was a script and a `.mts` file without `import` was too. + +use craft_anything_js::{Analysis, Limits, ParseMode, analyze}; + +/// Analyse `src` as `path` and check the syntax tree was used without errors. +fn parsed(path: &str, src: &str) -> Analysis { + let analysis = analyze(path, src, &Limits::default()); + assert_eq!(analysis.facts.mode, ParseMode::Parsed, "{path}: {:?}", analysis.facts.mode_reason); + analysis +} + +const REQUIRE: &str = "const fs = require('fs');\nmodule.exports = { read: (p: string) => fs.readFileSync(p) };\n"; + +#[test] +fn cts_is_commonjs_like_cjs() { + assert_eq!(parsed("lib/index.cts", REQUIRE).facts.source_kind, "commonjs"); + assert_eq!(parsed("LIB/INDEX.CTS", REQUIRE).facts.source_kind, "commonjs"); + // The JavaScript counterpart, for comparison. + assert_eq!(parsed("lib/index.cjs", "const fs = require('fs');\n").facts.source_kind, "commonjs"); +} + +/// TypeScript writes CommonJS imports with `import` syntax and compiles them to `require`, so a +/// `.cts` file with `import` and `export` stays CommonJS, parses cleanly and keeps its imports. +#[test] +fn cts_with_typescript_import_syntax() { + let src = "import fs from 'fs';\nimport path = require('path');\nexport const x: number = 1;\nexport = x;\n"; + let a = parsed("tool.cts", src); + assert_eq!(a.facts.source_kind, "commonjs"); + let specs: Vec<&str> = a.facts.imports.iter().map(|i| i.specifier.as_str()).collect(); + assert!(specs.contains(&"fs"), "{specs:?}"); + assert!(a.facts.exports.esm.contains(&"x".to_string()), "{:?}", a.facts.exports); + let plain = parsed("tool.cts", "import fs from 'fs';\nfs.readFileSync('a');\n"); + assert_eq!(plain.facts.source_kind, "commonjs"); +} + +#[test] +fn mts_is_a_module_without_import_syntax() { + assert_eq!(parsed("main.mts", "const x: number = 1;\nconsole.log(x);\n").facts.source_kind, "module"); + // Top-level await is valid only in a module. + assert_eq!(parsed("main.mts", "const r = await fetch('/api');\n").facts.source_kind, "module"); + assert_eq!(parsed("main.mts", "import fs from 'fs';\n").facts.source_kind, "module"); +} + +/// `.ts` and `.tsx` still let the syntax decide. +#[test] +fn ts_is_still_decided_by_syntax() { + assert_eq!(parsed("a.ts", REQUIRE).facts.source_kind, "script"); + assert_eq!(parsed("a.ts", "import fs from 'fs';\n").facts.source_kind, "module"); + assert_eq!(parsed("a.tsx", "export const A = () =>
;\n").facts.source_kind, "module"); + assert_eq!(parsed("a.d.ts", "declare const x: number;\n").facts.source_kind, "script"); +} diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 2f26e8065..a2763963c 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -1938,6 +1938,8 @@ Owner: open · Status: in progress — claimed: Plastic-time, branch rrfz/bugfix-r3.12-js-module-collisions - [x] Bound the text JavaScript facts build from constant strings, so repeated concatenation of a constant with itself cannot grow without limit. — claimed: Plastic-time, branch bugfix/r3.12-js-constant-text-budget +- [x] Read `.cts` files as CommonJS and `.mts` files as ES modules, as Node and TypeScript do, instead of guessing from the syntax. + — claimed: Plastic-time, branch bugfix/r3.12-js-cts-commonjs - [x] Refuse oversized GNU tar long names and link targets instead of silently truncating member identities. — claimed: Afloat16, branch bugfix/r3.12-tar-long-identities-20261109 Source [`de2c6390`](https://github.com/Afloat16/craft-anything/commit/de2c63908909cab675887103921ed2601b1bae9b) passed [formats tests, fmt and clippy](https://github.com/Afloat16/claude-mem/actions/runs/42640688213/job/129240669663) diff --git a/docs/STATUS.md b/docs/STATUS.md index 8d3a1d7bb..b812f9eb8 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -290,6 +290,7 @@ coverage and secrets passed. The companion CLI was built with locked dependencie | JavaScript chain nesting | A call, index read or template that follows another (`f()()`, `a[0][1]`, tagged-template chains) and a label that follows another (`a: b:`) each count one level in the nesting estimate, so a source nested deeper than the parser's stack takes the lexer fallback instead of stopping the process. Comments do not break a chain. A closed bracket that the expression goes on after (`((f)())()`, `f(g(x)())()`, `(a + b) + c`) keeps what was counted inside it; of siblings such as `(a) && (b)` only the deepest counts. The tokenizer skips JavaScript's non-ASCII spaces and the vertical tab, which it used to read as part of a name, so they can't break a chain either. An `else` chain counts one level per link at its own scope, so a `;` inside a block consequent does not reset the enclosing chain, and neither does a comma in an unbraced one; a class nested after `extends` counts a heritage level; prefix `++`/`--` count while postfix ones do not; `/` after an update operator or a member name (`.` or `?.`) divides. After `yield`, a regex is read when one closes on the same line; LF, CR, U+2028 and U+2029 end the lookahead (even after a backslash), its shared budget across the source keeps hostile input linear, and running out fails admission closed instead of guessing division, as do a quote or backtick inside the token, a closing `/` immediately followed by `*` or `/` (a comment in sloppy code), and a following `/`, `++` or `--` that the division reading would tokenize differently. Its brackets and every `!`, `+`, `-`, `~`, `*`, `%`, `?`, `&`, `\|` or `^` are counted and kept in the expression depth, so later nesting adds to them; the same text is division in sloppy code. | Regression tests: 5,000-link call, index, template and label chains are refused, also with a vertical tab, no-break space, byte-order mark or other space separator between links; chains split across 100 closing groups, call arguments, assignments, index brackets or function bodies count past 6,000 (about 160–260 before); two-million-link call, spaced call, grouped call and label chains, which overflowed the parser thread's stack and stopped the test process before this change, now report the lexer fallback; 5,000-link else-if, else-if with comma consequents, alternating block and unbraced consequents, `class extends`, prefix `++`, false-regex, yield-regex, yield-plus-prefix-operator and yield-plus-addition-chain sources are refused, and a 6,000-link analysis of each reaches the lexer fallback with a nesting reason; a unit test covers the bounded `yield` lookahead, an end-to-end test covers exhaustion with the 160-level limit, another checks a diverging follow and a quote inside the token (beside the compact-regex control), another checks a conditional chain and each bitwise chain at the 160-level limit, another checks a closing slash before a block comment, another checks that 100 operators plus 100 following brackets exceed 160, and another checks LF, CR, U+2028, U+2029 and an escaped line end; tokenizer controls keep `yield /a[0]/g`, `yield /a+b/` and `return /a[0]/g` as regexes (code after the closing delimiter still tokenized) while `yield / 2` divides; declarations, case clauses, object keys, conditionals and short chains stay below 16. Over 5,594 local JavaScript files, estimates rose by at most 46 and no file crossed the native (4096) or wasm (160) limit. The wasm stack itself was not measured. | | JavaScript lexer fallback list caps | The lexer fallback, used for huge, deeply nested or unparsable sources, bounds `endpoints` (fetch calls and URL literals) and `exposed` objects at `MAX_LIST`, as the syntax-tree pass does, and records `endpoints` in `truncated` when a fetch call is dropped. | A JS unit regression forces the lexer path with more than `MAX_LIST` fetch and `exposeInMainWorld` calls, checks both lists stop at the cap, that a URL literal adds nothing past it, and that `endpoints` says it was cut. | | JavaScript constant text budget | Text read through constants (`base + "/v1"`, `` `${base}/v1` ``) is at most 4 KiB per value, and all constants in a file share a budget of the source's size plus 1 MiB. Longer text reads as not literal, so `const a1 = a0 + a0; const a2 = a1 + a1; …` no longer doubles without end. A later `var` of the same name replaces the earlier value once its initializer has been read, even when the new value can't be read, so the old text is never reported in its place; the initializer itself (`var u = fetch(u)`) still sees the old value. | Regression tests: 26 doublings of an 8-byte constant (a 592-byte file that peaked at 1.5 GB before) and 64 doublings both finish with a non-literal endpoint of at most 4 KiB; 2,000 four-fold copies of a 1,000-byte constant stop at the shared budget; a redeclaration with a too-long or unknown value hides the earlier URL, and `var u = u + '/v1'` and `var u = fetch(u)` still read the earlier URL; ordinary concatenation and templates still give literal URLs. Facts from 5,594 local JavaScript files were identical before and after. | +| TypeScript module kind by extension | `.cts` reads as CommonJS and `.mts` as an ES module whatever the file contains, as in Node and TypeScript; `.ts`, `.tsx` and `.d.ts` are still decided by their syntax. A `.cts` file that calls `require` used to read as a script, one with `import` syntax as a module, and an `.mts` file without `import` or `export` as a script. | Regression tests: `.cts` with `require` (also in upper case) and with TypeScript `import`/`export =` syntax read as `commonjs` and parse without errors, keeping their imports and exports; `.mts` with plain code, top-level `await` or `import` reads as `module`; `.ts`, `.tsx` and `.d.ts` controls keep their syntax-based kind. Over 3,193 local `.cts`/`.mts` files (3,191 of them declaration files), 588 `.d.cts` files changed from `module` to `commonjs` and two `.d.mts` files from `script` to `module`; no file's parse mode or error count changed. | | JSONC registration comments | A bare carriage return ends a line comment, so registrations on the next line remain visible when settings are opened or edited. | Seven JSONC module tests on Linux, including a comment before the root and one inside it. | | First JSONC object | Creating the first object preserves the file's CRLF line endings and existing comments or BOM. Empty files keep LF. | Whitespace-only, comment-only, BOM and unterminated final-comment controls; parsed registration values stay intact. | | German UI | German (`de`, informal "du") in Settings → General → Language; System picks it for a German OS language. The catalog has the same keys as the Chinese ones. Drafted with an AI, not yet reviewed by a native speaker. Requests such as "Ein einfaches Snake-Spiel" or "Eine Website für …" keep their project kind. See [localisation](localization.md). | Catalog and locale tests, key-set comparison with the Chinese catalogs, the isolated language-switch test, a kind-detection test; fmt, clippy, layers, locks and secrets are clean. Not checked: how the German texts look in the running window (length, line breaks), and the `de.tsv` wording by a native speaker. |