Uh oh!
There was an error while loading. Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork 79
fix(core): add .mjs extensions to unbundled client ESM imports#604
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
Open
BetterAndBetterII
wants to merge
1
commit into
ory:mainChoose a base branch
from
BetterAndBetterII:fix/esm-import-extensions
base:main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Uh oh!
There was an error while loading. Please reload this page.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Diff view
Diff view
There are no files selected for viewing
137 changes: 137 additions & 0 deletions
137 packages/elements-react/src/client/rewrite-esm-relative-imports.spec.ts
This file contains hidden or 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,137 @@ | ||
| // Copyright © 2024 Ory Corp | ||
| // SPDX-License-Identifier: Apache-2.0 | ||
| import { spawnSync } from "node:child_process" | ||
| import { | ||
| mkdtempSync, | ||
| readdirSync, | ||
| readFileSync, | ||
| rmSync, | ||
| writeFileSync, | ||
| } from "node:fs" | ||
| import { tmpdir } from "node:os" | ||
| import path from "node:path" | ||
| import { rewriteEsmRelativeImports } from "./rewrite-esm-relative-imports" | ||
| function nodeRun(file: string) { | ||
| return spawnSync(process.execPath, [file], { | ||
| encoding: "utf8", | ||
| timeout: 5000, | ||
| }) | ||
| } | ||
| describe("rewriteEsmRelativeImports", () => { | ||
| it("adds .mjs to the extensionless frontendClient import from issue #573", () => { | ||
| const input = `import { frontendClient } from "./frontendClient";\n` | ||
| expect(rewriteEsmRelativeImports(input)).toBe( | ||
| `import { frontendClient } from "./frontendClient.mjs";\n`, | ||
| ) | ||
| }) | ||
| it("adds .mjs to session-provider re-exports from the ESM client entry", () => { | ||
| const input = `import { | ||
| SessionProvider | ||
| } from "./session-provider"; | ||
| import { useSession } from "./useSession"; | ||
| ` | ||
| const output = rewriteEsmRelativeImports(input) | ||
| expect(output).toContain(`from "./session-provider.mjs"`) | ||
| expect(output).toContain(`from "./useSession.mjs"`) | ||
| }) | ||
| it("does not double-append extensions", () => { | ||
| const input = `import { frontendClient } from "./frontendClient.mjs";\n` | ||
| expect(rewriteEsmRelativeImports(input)).toBe(input) | ||
| }) | ||
| it("leaves package specifiers alone", () => { | ||
| const input = `import { Session } from "@ory/client-fetch";\n` | ||
| expect(rewriteEsmRelativeImports(input)).toBe(input) | ||
| }) | ||
| }) | ||
| describe("Node ESM resolution (issue #573)", () => { | ||
| let dir: string | ||
| beforeEach(() => { | ||
| dir = mkdtempSync(path.join(tmpdir(), "ory-elements-esm-")) | ||
| writeFileSync( | ||
| path.join(dir, "frontendClient.mjs"), | ||
| "export function frontendClient() { return 1 }\n", | ||
| ) | ||
| }) | ||
| afterEach(() => { | ||
| rmSync(dir, { recursive: true, force: true }) | ||
| }) | ||
| it("throws ERR_MODULE_NOT_FOUND for extensionless relative imports", () => { | ||
| writeFileSync( | ||
| path.join(dir, "index.mjs"), | ||
| `import { frontendClient } from "./frontendClient";\nconsole.log(frontendClient())\n`, | ||
| ) | ||
| const result = nodeRun(path.join(dir, "index.mjs")) | ||
| expect(result.status).not.toBe(0) | ||
| expect(result.stderr).toMatch(/ERR_MODULE_NOT_FOUND/) | ||
| expect(result.stderr).toMatch(/frontendClient/) | ||
| }) | ||
| it("resolves after rewriteEsmRelativeImports adds .mjs", () => { | ||
| const broken = `import { frontendClient } from "./frontendClient";\nconsole.log(frontendClient())\n` | ||
| writeFileSync( | ||
| path.join(dir, "index.mjs"), | ||
| rewriteEsmRelativeImports(broken), | ||
| ) | ||
| const result = nodeRun(path.join(dir, "index.mjs")) | ||
| expect(result.status).toBe(0) | ||
| expect(result.stderr).not.toMatch(/ERR_MODULE_NOT_FOUND/) | ||
| expect(result.stdout).toMatch(/1/) | ||
| }) | ||
| }) | ||
| describe("dist/client ESM build", () => { | ||
| const distClient = path.join(__dirname, "../../dist/client") | ||
| function relativeSpecifiers(source: string): string[] { | ||
| const specs: string[] = [] | ||
| const re = /\b(?:from\s+|import\s*\(\s*)(['"])(\.[^'"]+)\1/g | ||
| let match: RegExpExecArray | null | ||
| while ((match = re.exec(source))) { | ||
| specs.push(match[2]) | ||
| } | ||
| return specs | ||
| } | ||
| it("emits relative imports with .mjs extensions so Node ESM can resolve them", () => { | ||
| const files = readdirSync(distClient).filter( | ||
| (name) => name.endsWith(".mjs") && !name.endsWith(".map"), | ||
| ) | ||
| expect(files).toEqual( | ||
| expect.arrayContaining([ | ||
| "index.mjs", | ||
| "session-provider.mjs", | ||
| "frontendClient.mjs", | ||
| ]), | ||
| ) | ||
| const missingExtension: string[] = [] | ||
| const missingFile: string[] = [] | ||
| for (const file of files) { | ||
| const source = readFileSync(path.join(distClient, file), "utf8") | ||
| for (const spec of relativeSpecifiers(source)) { | ||
| if (!path.extname(spec)) { | ||
| missingExtension.push(`${file} imports ${spec}`) | ||
| continue | ||
| } | ||
| const resolved = path.resolve(distClient, spec) | ||
| if (!files.includes(path.basename(resolved))) { | ||
| missingFile.push(`${file} imports ${spec}`) | ||
| } | ||
| } | ||
| } | ||
| expect(missingExtension).toEqual([]) | ||
| expect(missingFile).toEqual([]) | ||
| }) | ||
| }) | ||
35 changes: 35 additions & 0 deletions
35 packages/elements-react/src/client/rewrite-esm-relative-imports.ts
This file contains hidden or 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,35 @@ | ||
| // Copyright © 2024 Ory Corp | ||
| // SPDX-License-Identifier: Apache-2.0 | ||
| import { readdirSync, readFileSync, writeFileSync } from "node:fs" | ||
| import path from "node:path" | ||
| /** | ||
| * Node ESM requires file extensions on relative specifiers. tsup's unbundled | ||
| * client build emits `from "./frontendClient"`; rewrite those to `.mjs`. | ||
| */ | ||
| export function rewriteEsmRelativeImports(source: string): string { | ||
| return source.replace( | ||
| /\b(from\s+|import\s*\(\s*)(['"])(\.[^'"]+)\2/g, | ||
| (full, prefix: string, quote: string, spec: string) => { | ||
| if (path.extname(spec)) { | ||
| return full | ||
| } | ||
| return `${prefix}${quote}${spec}.mjs${quote}` | ||
| }, | ||
| ) | ||
| } | ||
| export function rewriteEsmRelativeImportsInDir(dir: string): void { | ||
| for (const name of readdirSync(dir)) { | ||
| if (!name.endsWith(".mjs")) { | ||
| continue | ||
| } | ||
| const file = path.join(dir, name) | ||
| const source = readFileSync(file, "utf8") | ||
| const next = rewriteEsmRelativeImports(source) | ||
| if (next !== source) { | ||
| writeFileSync(file, next) | ||
| } | ||
| } | ||
| } |
This file contains hidden or 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
Oops, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
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.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Check the resolved pathname.
Line 128 discards directory components. For example,
./missing/frontendClient.mjspasses whendist/client/frontendClient.mjsexists. Checkresolveddirectly so this test rejects imports whose actual target is absent.Proposed fix
import { + existsSync, mkdtempSync, readdirSync, readFileSync, @@ - if (!files.includes(path.basename(resolved))) {+ if (!existsSync(resolved)) {📝 Committable suggestion
🤖 Prompt for AI Agents