Files
raea/engine/native/src/cjs.rs
shane d873402ac5 raea goal is the loop, raea make the asset tools (#269)
One loop, raea goal: every rule in TypeScript, held at edit, render, publish and done (goal check, tasks, judge, seen, gates, next); the brief's contract is goal: (one goal or a list, a workflow inline), and its plan is plan:. raea make is making a finished asset: character, clothes, motion, solid, wear, splat, physics, bake, sounds, component, the kit pipeline and shots. Instruments (check, judge, ask, world, scene faults, light check) stay top-level. With it: the montage pack (MK48-MK51), JavaScriptCore fixes raea goal needs (CommonJS named exports, reserved words too, dynamic import of file URLs, process.exit from a promise, stdin for -), raea-cli-goal and raea-cli-refused split out of raea-cli, and skills at raea-skills 105aede.
2026-11-29 18:43:09 -08:00

108 lines
4.7 KiB
Rust

//! A CommonJS file's export names, read from its text the way Node's cjs-module-lexer does, so the ES module node.rs
//! wraps it in can give each as a named export: `import { jsx } from "react/jsx-runtime"` (what the automatic JSX
//! runtime writes in every .tsx) and `import { useEffect } from "react"` bind, where a default export alone left them
//! unbound ("Importing binding name 'jsx' is not found"). It reads `exports.NAME =`, `Object.defineProperty(exports,
//! "NAME"`, and follows `module.exports = require("./FILE")` (both of a NODE_ENV branch), four files deep. A name the
//! file turns out not to set is undefined, as Node's interop gives it.
use std::collections::BTreeSet;
use std::path::{Path, PathBuf};
/// The export names of the CommonJS file at `path`: identifiers (reserved words too: node.rs exports each by alias),
/// never `default` (the module's default export is module.exports itself) or `__esModule`
pub fn names(path: &Path) -> Vec<String> {
let mut out = BTreeSet::new();
walk(path, 0, &mut out);
out.into_iter().filter(|n| is_binding(n)).collect()
}
fn walk(path: &Path, depth: usize, out: &mut BTreeSet<String>) {
let Ok(text) = std::fs::read_to_string(path) else { return };
out.extend(assigned(&text));
if depth >= 4 {
return;
}
for rel in reexports(&text) {
if let Some(p) = resolve(path.parent().unwrap_or(Path::new("/")), &rel) {
walk(&p, depth + 1, out);
}
}
}
/// `exports.NAME = ...` (not `==`) and `Object.defineProperty(exports, "NAME"`
fn assigned(text: &str) -> Vec<String> {
let mut names = Vec::new();
for (i, _) in text.match_indices("exports.") {
if text[..i].chars().next_back().is_some_and(ident) && !text[..i].ends_with("module.") {
continue;
}
let rest = &text[i + "exports.".len()..];
let name: String = rest.chars().take_while(|c| ident(*c)).collect();
let after = rest[name.len()..].trim_start();
if !name.is_empty() && after.starts_with('=') && !after.starts_with("==") {
names.push(name);
}
}
for (i, _) in text.match_indices("Object.defineProperty(exports,") {
let rest = text[i + "Object.defineProperty(exports,".len()..].trim_start();
if let Some(name) = quoted(rest) {
names.push(name.to_string());
}
}
names
}
/// The relative files `module.exports = require("./FILE")` hands on
fn reexports(text: &str) -> Vec<String> {
let mut out = Vec::new();
for (i, _) in text.match_indices("module.exports") {
let rest = text[i + "module.exports".len()..].trim_start();
let Some(rest) = rest.strip_prefix('=').filter(|r| !r.starts_with('=')) else { continue };
let Some(rest) = rest.trim_start().strip_prefix("require(") else { continue };
let rest = rest.trim_start();
if let Some(spec) = quoted(rest).filter(|s| s.starts_with('.')) {
out.push(spec.to_string());
}
}
out
}
/// The string a quote at the start of `s` opens, to its closing quote
fn quoted(s: &str) -> Option<&str> {
let q = s.chars().next().filter(|c| matches!(c, '"' | '\''))?;
s[1..].find(q).map(|end| &s[1..1 + end])
}
fn ident(c: char) -> bool {
c.is_alphanumeric() || matches!(c, '_' | '$')
}
/// `rel` as Node's require finds it from `dir`: the file, or with .js or .cjs, or the folder's index.js
fn resolve(dir: &Path, rel: &str) -> Option<PathBuf> {
let base = dir.join(rel);
["", ".js", ".cjs", "/index.js"].iter().map(|e| {
let mut p = base.clone().into_os_string();
p.push(e);
PathBuf::from(p)
}).find(|p| p.is_file())
}
fn is_binding(n: &str) -> bool {
n.chars().next().is_some_and(|c| c.is_alphabetic() || c == '_' || c == '$') && n != "default" && n != "__esModule"
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn reads_assigned_names_and_follows_a_node_env_reexport() {
let d = std::env::temp_dir().join(format!("raea-cjs-{}", std::process::id()));
std::fs::create_dir_all(d.join("cjs")).unwrap();
std::fs::write(d.join("index.js"), "'use strict';\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./cjs/a.production.js');\n} else {\n module.exports = require('./cjs/a.development.js');\n}\n").unwrap();
std::fs::write(d.join("cjs/a.production.js"), "exports.Fragment = REACT_FRAGMENT_TYPE;\nexports.jsx = jsxProd;\nexports.jsxs = jsxProd;\nif (exports.jsx == null) {}\n").unwrap();
std::fs::write(d.join("cjs/a.development.js"), "Object.defineProperty(exports, \"jsxDEV\", { value: 1 });\nexports.default = 1;\nmyexports.nope = 2;\n").unwrap();
assert_eq!(names(&d.join("index.js")), vec!["Fragment", "jsx", "jsxDEV", "jsxs"]);
}
}