-
Notifications
You must be signed in to change notification settings - Fork 122
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
node imports #1156
Merged
Merged
node imports #1156
Changes from 23 commits
Commits
Show all changes
24 commits
Select commit
Hold shift + click to select a range
3e9a5ef
checkpoint import from node_modules
mbostock c17ec11
it works!
mbostock 8095c68
minify
Fil 34144a2
only resolve bare imports
mbostock e776e61
coalesce imports; ignore errors
mbostock ed6bb45
preload transitive dependencies
mbostock 02f5ad3
DRY parseImports
mbostock 589be7a
parseImports tests
mbostock 779e8fa
fix windows?
mbostock 9c696c9
add logging
mbostock c6bce08
test only windows
mbostock 9bc2ba1
don’t resolve input
mbostock 50c1255
restore tests
mbostock 10bded4
build _node
mbostock 0c19167
Merge branch 'main' into mbostock/node-modules
mbostock 396e16d
fix import order
mbostock 6173878
30s timeout
mbostock 6751721
Merge branch 'main' into mbostock/node-modules
mbostock 50a3e7d
adopt @rollup/plugin-node-resolve
mbostock 41925cf
more tests
mbostock e61a3d2
fix file path resolution
mbostock 95005f5
restore tests
mbostock 8f4746e
add missing dependency
mbostock add55fc
adopt pkg-dir
mbostock File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,115 @@ | ||
import {existsSync} from "node:fs"; | ||
import {copyFile, readFile, writeFile} from "node:fs/promises"; | ||
import {createRequire} from "node:module"; | ||
import op from "node:path"; | ||
import {extname, join} from "node:path/posix"; | ||
import {pathToFileURL} from "node:url"; | ||
import {nodeResolve} from "@rollup/plugin-node-resolve"; | ||
import type {AstNode, OutputChunk, Plugin, ResolveIdResult} from "rollup"; | ||
import {rollup} from "rollup"; | ||
import esbuild from "rollup-plugin-esbuild"; | ||
import {prepareOutput, toOsPath} from "./files.js"; | ||
import type {ImportReference} from "./javascript/imports.js"; | ||
import {isJavaScript, parseImports} from "./javascript/imports.js"; | ||
import {parseNpmSpecifier} from "./npm.js"; | ||
import {isPathImport} from "./path.js"; | ||
import {faint} from "./tty.js"; | ||
|
||
export async function resolveNodeImport(root: string, spec: string): Promise<string> { | ||
return resolveNodeImportInternal(op.join(root, ".observablehq", "cache", "_node"), root, spec); | ||
} | ||
|
||
const bundlePromises = new Map<string, Promise<void>>(); | ||
|
||
async function resolveNodeImportInternal(cacheRoot: string, packageRoot: string, spec: string): Promise<string> { | ||
const {name, path = "."} = parseNpmSpecifier(spec); | ||
const require = createRequire(pathToFileURL(op.join(packageRoot, "/"))); | ||
const pathResolution = require.resolve(spec); | ||
let packageResolution = pathResolution; | ||
do { | ||
const p = op.dirname(packageResolution); | ||
if (p === packageResolution) throw new Error(`unable to resolve package.json: ${spec}`); | ||
packageResolution = p; | ||
} while (!existsSync(op.join(packageResolution, "package.json"))); | ||
const {version} = JSON.parse(await readFile(op.join(packageResolution, "package.json"), "utf-8")); | ||
const resolution = `${name}@${version}/${extname(path) ? path : path === "." ? "index.js" : `${path}.js`}`; | ||
const outputPath = op.join(cacheRoot, toOsPath(resolution)); | ||
if (!existsSync(outputPath)) { | ||
let promise = bundlePromises.get(outputPath); | ||
if (!promise) { | ||
promise = (async () => { | ||
process.stdout.write(`${spec} ${faint("→")} ${resolution}\n`); | ||
await prepareOutput(outputPath); | ||
if (isJavaScript(pathResolution)) { | ||
await writeFile(outputPath, await bundle(spec, cacheRoot, packageResolution)); | ||
} else { | ||
await copyFile(pathResolution, outputPath); | ||
} | ||
})(); | ||
bundlePromises.set(outputPath, promise); | ||
promise.catch(() => {}).then(() => bundlePromises.delete(outputPath)); | ||
} | ||
await promise; | ||
} | ||
return `/_node/${resolution}`; | ||
} | ||
|
||
/** | ||
* Resolves the direct dependencies of the specified node import path, such as | ||
* "/_node/[email protected]/src/index.js", returning a set of node import paths. | ||
*/ | ||
export async function resolveNodeImports(root: string, path: string): Promise<ImportReference[]> { | ||
if (!path.startsWith("/_node/")) throw new Error(`invalid node path: ${path}`); | ||
return parseImports(join(root, ".observablehq", "cache"), path); | ||
} | ||
|
||
/** | ||
* Given a local npm path such as "/_node/[email protected]/src/index.js", returns | ||
* the corresponding npm specifier such as "[email protected]/src/index.js". | ||
*/ | ||
export function extractNodeSpecifier(path: string): string { | ||
if (!path.startsWith("/_node/")) throw new Error(`invalid node path: ${path}`); | ||
return path.replace(/^\/_node\//, ""); | ||
} | ||
|
||
async function bundle(input: string, cacheRoot: string, packageRoot: string): Promise<string> { | ||
const bundle = await rollup({ | ||
input, | ||
plugins: [ | ||
nodeResolve({browser: true, rootDir: packageRoot}), | ||
importResolve(input, cacheRoot, packageRoot), | ||
esbuild({ | ||
target: ["es2022", "chrome96", "firefox96", "safari16", "node18"], | ||
exclude: [], // don’t exclude node_modules | ||
minify: true | ||
}) | ||
], | ||
onwarn(message, warn) { | ||
if (message.code === "CIRCULAR_DEPENDENCY") return; | ||
warn(message); | ||
} | ||
}); | ||
try { | ||
const output = await bundle.generate({format: "es"}); | ||
const code = output.output.find((o): o is OutputChunk => o.type === "chunk")!.code; // TODO don’t assume one chunk? | ||
return code; | ||
} finally { | ||
await bundle.close(); | ||
} | ||
} | ||
|
||
function importResolve(input: string, cacheRoot: string, packageRoot: string): Plugin { | ||
async function resolve(specifier: string | AstNode): Promise<ResolveIdResult> { | ||
return typeof specifier !== "string" || // AST node? | ||
isPathImport(specifier) || // relative path, e.g., ./foo.js | ||
/^\w+:/.test(specifier) || // windows file path, https: URL, etc. | ||
specifier === input // entry point | ||
? null // don’t do any additional resolution | ||
: {id: await resolveNodeImportInternal(cacheRoot, packageRoot, specifier), external: true}; // resolve bare import | ||
} | ||
return { | ||
name: "resolve-import", | ||
resolveId: resolve, | ||
resolveDynamicImport: resolve | ||
}; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -6,7 +6,7 @@ import {simple} from "acorn-walk"; | |
import {rsort, satisfies} from "semver"; | ||
import {isEnoent} from "./error.js"; | ||
import type {ExportNode, ImportNode, ImportReference} from "./javascript/imports.js"; | ||
import {findImports, isImportMetaResolve} from "./javascript/imports.js"; | ||
import {isImportMetaResolve, parseImports} from "./javascript/imports.js"; | ||
import {parseProgram} from "./javascript/parse.js"; | ||
import type {StringLiteral} from "./javascript/source.js"; | ||
import {getStringLiteralValue, isStringLiteral} from "./javascript/source.js"; | ||
|
@@ -252,30 +252,14 @@ export async function resolveNpmImport(root: string, specifier: string): Promise | |
return `/_npm/${name}@${await resolveNpmVersion(root, {name, range})}/${path.replace(/\+esm$/, "_esm.js")}`; | ||
} | ||
|
||
const npmImportsCache = new Map<string, Promise<ImportReference[]>>(); | ||
|
||
/** | ||
* Resolves the direct dependencies of the specified npm path, such as | ||
* "/_npm/[email protected]/_esm.js", returning the corresponding set of npm paths. | ||
*/ | ||
export async function resolveNpmImports(root: string, path: string): Promise<ImportReference[]> { | ||
if (!path.startsWith("/_npm/")) throw new Error(`invalid npm path: ${path}`); | ||
let promise = npmImportsCache.get(path); | ||
if (promise) return promise; | ||
promise = (async function () { | ||
try { | ||
const filePath = await populateNpmCache(root, path); | ||
if (!/\.(m|c)?js$/i.test(path)) return []; // not JavaScript; TODO traverse CSS, too | ||
const source = await readFile(filePath, "utf-8"); | ||
const body = parseProgram(source); | ||
return findImports(body, path, source); | ||
} catch (error: any) { | ||
console.warn(`unable to fetch or parse ${path}: ${error.message}`); | ||
return []; | ||
} | ||
})(); | ||
npmImportsCache.set(path, promise); | ||
return promise; | ||
await populateNpmCache(root, path); | ||
return parseImports(join(root, ".observablehq", "cache"), path); | ||
} | ||
|
||
/** | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
1 change: 1 addition & 0 deletions
1
test/input/packages/node_modules/test-browser-condition/browser.js
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
1 change: 1 addition & 0 deletions
1
test/input/packages/node_modules/test-browser-condition/default.js
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
For posterity, here is an alternative approach to finding the
package.json
that I discovered:nodejs/node#33460 (comment)
I guess there are some cases of a “nested”
package.json
that our approach doesn’t handle; the linked approach is to trim the relative path to the entry point from the fully-resolved path. I think our approach is fine for now, though. There’s also this:https://github.com/sindresorhus/package-up
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I’ve switched this branch to use pkg-dir.