reload personal config when imported .js files change (#1856)

* reload personal config when imported .js files change

* watch and load the same config file kinds

the watcher skipped foo.d.js, foo.d.mjs, and foo.d.json because it treated
every .d stem as a declaration file, while the loader ran any file imported
by its exact name as javascript even though edits to it never reloaded.

both now use one predicate: ts, js, mjs, mts, and json in any case, excluding
only .d.ts and .d.mts declarations. the loader refuses other extensions when
a config imports them.
This commit is contained in:
Dax
2026-11-15 10:46:47 -05:00
committed by GitHub
parent 0932d092fd
commit 82ca73f945
6 changed files with 125 additions and 19 deletions
+3
View File
@@ -1385,6 +1385,9 @@ their host's refresh. `host_startup_discovers_a_config_without_selecting_a_trans
in [personal_commands.rs](../../src/personal_commands.rs) covers the shared
decision, policy denial, built-ins, and custom selection in global and other
modes. This is a pure decision check, not a live Set up walkthrough.
`workspace_fingerprint_tracks_every_loaded_file_kind` in
[personal_commands.rs](../../src/personal_commands.rs) covers which file edits
trigger the reload watcher; it is not a live filesystem notification.
```ts
Transform host APIs // personal_commands/{io,fetch,process,trust}.rs
+6 -6
View File
@@ -152,12 +152,12 @@ avoids Effect and npm packages; their `package.json`, `bun.lock`,
`node_modules`, `.hex-sdk`, and `.agents` can be deleted.
Hex reloads the config about a third of a second after any `.ts`, `.js`,
`.mjs`, or `.json` file in the folder changes (not `.d.ts`, dot folders,
`node_modules`, or symlink targets), activates valid changes, and reports the
last load error with its file, line, and column in Modes' Transformations
section. `hex commands check` (macOS) loads the config as Hex would and prints
what it registers or why it fails. Type checking is optional:
`npx -y -p typescript tsc` in the folder.
`.mjs`, `.mts`, or `.json` file in the folder changes, in any case, but not
declaration files (`.d.ts`, `.d.mts`), `node_modules`, `.git`, or symlink
targets. It activates valid changes and reports the last load error with its
file, line, and column in Modes' Transformations section. `hex commands check`
(macOS) loads the config as Hex would and prints what it registers or why it
fails. Type checking is optional: `npx -y -p typescript tsc` in the folder.
## Runtime Boundary
+2 -1
View File
@@ -48,7 +48,8 @@ transformations were already native.
- **No ambient authority:** the context has standard JavaScript only, plus a
`console` that writes to Hex's log. No filesystem, network, process,
environment, or timers. Imports resolve to `@hex/commands` or files inside
the config folder (`.ts`, `.js`, `.mjs`, `.json`); anything else is refused.
the config folder (`.ts`, `.js`, `.mjs`, `.mts`, `.json`, in any case, never
`.d.ts` or `.d.mts` declarations); anything else is refused.
- **Commands return actions.** A handler returns an action, a list, or
nothing; `hex.*` still exists and queues actions (resolving at once), so
most existing handlers keep working. Hex validates every action, then runs
+98 -6
View File
@@ -982,6 +982,45 @@ fn invocation_context(
}
}
/// Extensions the script host loads, in any case, shared with the loader so
/// every file it can import is one the watcher reloads.
const SCRIPT_EXTENSIONS: [&str; 5] = ["ts", "js", "mjs", "mts", "json"];
/// Extensions the script host erases types from, and the ones a TypeScript
/// declaration file can have.
const TYPESCRIPT_EXTENSIONS: [&str; 2] = ["ts", "mts"];
/// `.ts, .js, .mjs, .mts, .json` for messages about what can be imported.
fn script_extension_list() -> String {
SCRIPT_EXTENSIONS
.iter()
.map(|extension| format!(".{extension}"))
.collect::<Vec<_>>()
.join(", ")
}
/// The last component's stem and lowercased extension, or None when it has no
/// extension.
fn script_name_parts(path: &Path) -> Option<(&str, String)> {
let name = path.file_name()?.to_str()?;
let (stem, extension) = name.rsplit_once('.')?;
Some((stem, extension.to_ascii_lowercase()))
}
/// Whether `path` names a file the script host loads, and so one the reload
/// watcher tracks. Declaration files only describe the API, so editing one
/// never needs a reload.
fn is_script_file(path: &Path) -> bool {
let Some((stem, extension)) = script_name_parts(path) else {
return false;
};
if !SCRIPT_EXTENSIONS.contains(&extension.as_str()) {
return false;
}
let declaration = (stem.ends_with(".d") || stem.ends_with(".D"))
&& TYPESCRIPT_EXTENSIONS.contains(&extension.as_str());
!declaration
}
fn workspace_fingerprint(root: &Path) -> u64 {
let mut hash = 1469598103934665603;
let mut queue = VecDeque::from([(root.to_path_buf(), 0_usize)]);
@@ -1015,12 +1054,7 @@ fn workspace_fingerprint(root: &Path) -> u64 {
}
if metadata.is_dir() {
queue.push_back((path, depth + 1));
} else if metadata.is_file()
&& matches!(
path.extension().and_then(|value| value.to_str()),
Some("ts" | "json")
)
{
} else if metadata.is_file() && is_script_file(&path) {
for byte in path.as_os_str().as_encoded_bytes() {
hash = hash
.wrapping_mul(1099511628211)
@@ -1330,6 +1364,46 @@ mod tests {
assert_eq!(status.transformations[2].name, "No trailing punctuation");
}
#[test]
fn workspace_fingerprint_tracks_every_loaded_file_kind() {
let root = unique_temp_dir("hex-watch-kinds");
fs::create_dir_all(root.join("lib")).unwrap();
let watched = [
"hex.config.ts",
"spelling.js",
"lib/words.mjs",
"lib/types.mts",
"data.json",
"lib/upper.JS",
"lib/foo.d.js",
];
for name in watched {
fs::write(root.join(name), "first").unwrap();
}
fs::write(root.join("notes.md"), "first").unwrap();
fs::write(root.join("hex.d.ts"), "first").unwrap();
fs::write(root.join("lib/x.d.mts"), "first").unwrap();
let mut fingerprint = workspace_fingerprint(&root);
for name in watched {
fs::write(root.join(name), "second").unwrap();
let next = workspace_fingerprint(&root);
assert_ne!(next, fingerprint, "editing {name} should reload");
fingerprint = next;
}
fs::write(root.join("lib/new.js"), "first").unwrap();
assert_ne!(
workspace_fingerprint(&root),
fingerprint,
"a new .js file should reload"
);
fingerprint = workspace_fingerprint(&root);
fs::write(root.join("notes.md"), "changed").unwrap();
fs::write(root.join("hex.d.ts"), "changed").unwrap();
fs::write(root.join("lib/x.d.mts"), "changed").unwrap();
assert_eq!(workspace_fingerprint(&root), fingerprint);
fs::remove_dir_all(root).unwrap();
}
#[cfg(unix)]
#[test]
fn workspace_fingerprint_does_not_follow_symlinks_or_excessive_depth() {
@@ -1702,6 +1776,24 @@ export default defineHexConfig({
);
assert_eq!(harness.transform(&["shout"], "hi").unwrap(), "HI!");
fs::write(
workspace.join("lib/plain.js"),
"export const yell = (text) => text.toUpperCase()\n",
)
.unwrap();
harness.write(
"import { yell } from \"./lib/plain.js\"\nexport default { transformations: { yell: { name: \"Yell\", transform: yell } } }\n",
);
assert_eq!(harness.transform(&["yell"], "hi").unwrap(), "HI");
fs::write(workspace.join("notes.txt"), "export const x = 1\n").unwrap();
harness.write("import { x } from \"./notes.txt\"\nexport default {}\n");
assert!(
harness.error().contains("./notes.txt"),
"a .txt import loaded as JavaScript: {}",
harness.error()
);
for import in [
"node:fs",
"effect",
+5 -4
View File
@@ -7,10 +7,11 @@ This folder configures custom text transformations for Hex. Edit
`@hex/commands` module; Hex owns it, so do not edit it.
Hex runs the config itself in an embedded JavaScript engine (QuickJS) and
reloads it about a third of a second after any `.ts`, `.js`, or `.json` file
here changes. A config that fails to load keeps the previous one active; the
error, with its file, line, and column, shows in the Modes pane's
Transformations section. No install step and no Node, Bun, or npm are involved.
reloads it about a third of a second after any `.ts`, `.js`, `.mjs`, `.mts`,
or `.json` file here changes. A config that fails to load keeps the previous
one active; the error, with its file, line, and column, shows in the Modes
pane's Transformations section. No install step and no Node, Bun, or npm are
involved.
## What a script can do
+11 -2
View File
@@ -359,6 +359,12 @@ impl WorkspaceLoader {
.into_iter()
.find(|candidate| self.root.join(candidate).is_file())
.ok_or_else(|| "file not found".to_string())?;
if !super::is_script_file(&found) {
return Err(format!(
"only {} files can be imported",
super::script_extension_list()
));
}
let real = self
.root
.join(&found)
@@ -387,12 +393,15 @@ impl WorkspaceLoader {
.borrow_mut()
.sources
.push((name.to_owned(), source.clone()));
if name.ends_with(".json") {
let extension = super::script_name_parts(Path::new(name))
.map(|(_, extension)| extension)
.unwrap_or_default();
if extension == "json" {
serde_json::from_str::<serde_json::Value>(&source).map_err(|error| {
SourceError::Syntax(format!("{}:{}: {error}", error.line(), error.column()))
})?;
Ok(format!("export default {source}"))
} else if name.ends_with(".ts") || name.ends_with(".mts") {
} else if super::TYPESCRIPT_EXTENSIONS.contains(&extension.as_str()) {
super::typescript::strip(&source).map_err(SourceError::Syntax)
} else {
Ok(source)