Skip to content

fix: relative path resolution for the assets directory#76

Open
yuriiShmal wants to merge 6 commits into
elysiajs:mainfrom
yuriiShmal:main
Open

fix: relative path resolution for the assets directory#76
yuriiShmal wants to merge 6 commits into
elysiajs:mainfrom
yuriiShmal:main

Conversation

@yuriiShmal
Copy link
Copy Markdown
Contributor

@yuriiShmal yuriiShmal commented Apr 28, 2026

Attempts to resolve #58.

Main issue

Relative assets paths were previously resolved from process.cwd().

That worked when the server was started from the project root, but failed when the same entrypoint was started from another working directory, for example:

cd ..
bun run project/src/index.ts

In that case, assets: public was resolved as ../public instead of project/public, causing static asset requests to fail with ENOENT.

Changes

  • Resolve relative assets paths from the Bun entrypoint’s project root when available.
  • Preserve support for absolute assets paths.
  • Use the resolved assetsDir consistently across:
    • eager static asset registration
    • HTML asset discovery
    • dynamic wildcard static serving
  • Add project-root discovery by walking upward from the Bun entrypoint until package.json is found.
  • Fall back to the entrypoint directory when no package.json can be found.
  • Fall back to process.cwd() when Bun entrypoint metadata is unavailable.
  • Update shouldIgnore so ignore string patterns continue to work after asset paths are resolved to absolute paths.

Additional test coverage added by JoshuaNam

  • Added regression coverage for relative assets path resolution:

    • default relative assets path serves files
    • relative assets path still works when cwd differs from the project root
    • absolute assets path continues to serve files correctly
  • Added unit coverage for findProjectRoot:

    • finds package.json from a deep entrypoint
    • finds package.json from a flat-layout entrypoint at the project root
    • finds package.json from a deeper app-style layout
    • returns null when no package.json exists above the entrypoint
  • Added ignore-pattern regression coverage:

    • partial string ignore patterns still match file paths after internal path resolution changes

Notes

Notes on project-root resolution

The fix now prefers the nearest package.json above the Bun entrypoint, which is more robust than assuming a fixed directory depth from bun.main.

This avoids resolving assets relative to the wrong cwd while still supporting different project layouts, including flat entrypoints and deeper src/app structures.

Notes on shouldIgnore

The shouldIgnore update is required because assetsDir may now be absolute internally. Without adjusting the ignore matching behavior, existing string ignore patterns could stop matching user-provided relative-style patterns.

Testing

  • Existing and newly added tests pass with:

bun test

  • Current coverage includes:
    • relative assets path behavior
    • cwd mismatch behavior
    • absolute assets path behavior
    • project root discovery
    • partial-string ignore pattern matching

Manual verification

I also manually tested the startup path behavior by temporarily adding:

new Elysia()
    .use(staticPlugin())
    .listen(3000)

at the end of src/index.ts, then starting the server from different current working directories.

With the current changes, relative assets paths no longer produced ENOENT when the entrypoint was launched from outside the project root.

Compatibility

This preserves the existing public API:

staticPlugin({
    assets: "public"
})

No user configuration changes should be required.

Summary by CodeRabbit

  • Bug Fixes

    • Fixed assets directory resolution when using relative asset paths (improves serving under alternate runtimes and when cwd differs from project root)
    • Improved ignore-pattern matching with path normalization so ignored files are consistently filtered
    • Standardized static file enumeration and path handling to reduce incorrect 404s
  • Tests

    • Added tests covering asset resolution and ignore-pattern behavior across configurations

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 28, 2026

Walkthrough

The static plugin now computes assetsDir using a new findProjectRoot helper when running under Bun (falling back to process.cwd() otherwise). Ignore-pattern matching and all filesystem operations now normalize and test both absolute and assets-relative paths, and directory/HTML enumeration uses the computed assetsDir.

Changes

Cohort / File(s) Summary
Path Resolution Utilities
src/utils.ts
Added export const findProjectRoot(entrypoint: string): Promise<string | null> which walks upward from the Bun entrypoint to locate the nearest ancestor containing package.json, returning that directory or null.
Plugin Core Logic
src/index.ts
Compute assetsDir by using findProjectRoot for Bun entrypoints (fallback to process.cwd()), normalize ignore patterns and test them against both normalized absolute file paths and paths relative to assetsDir, and update all filesystem enumeration/construction to use assetsDir consistently.
Tests
test/index.test.ts
Added tests for ignore-pattern substring matching, regression tests for relative assets resolution under altered process.cwd() and absolute assets paths, and unit tests for findProjectRoot behavior across multiple synthetic entrypoints.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

Assets once wandered, lost and so baka~ (¬‿¬)♡
We taught the plugin to look for package.json~ (^▽^)♡
Now paths behave, no more drama~ (`・ω・´)♡
Serve your files, and stop crying, silly~ (¬‿¬)♡

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'fix: relative path resolution for the assets directory' accurately describes the main change—resolving relative assets paths from the Bun entrypoint's project root instead of process.cwd().
Linked Issues check ✅ Passed All objectives from issue #58 are met: relative assets are resolved from project root via findProjectRoot [#58], absolute paths preserved [#58], graceful fallbacks implemented [#58], and ignore patterns work correctly [#58].
Out of Scope Changes check ✅ Passed All changes directly address issue #58: findProjectRoot helper, assetsDir resolution logic, ignore pattern normalization, and comprehensive regression tests—no unrelated modifications detected.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
Review rate limit: 0/1 reviews remaining, refill in 60 minutes.

Comment @coderabbitai help to get the list of available commands and usage tips.

@yuriiShmal yuriiShmal marked this pull request as ready for review April 29, 2026 21:40
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
test/index.test.ts (1)

488-503: Mark this test with .serial() to future-proof against concurrent execution.

Bun runs tests sequentially by default, so the try/finally cleanup handles cwd restoration just fine~ But if someone runs tests with --concurrent flag, this test will flake without explicitly marking it as .serial(). Your cleanup is solid, but add it.serial(...) to make the intent clear and prevent accidents when the runner configuration changes~ (^▽^)

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@test/index.test.ts` around lines 488 - 503, Update the test named "serves
files when cwd differs from project root" to be run serially to avoid flakiness
under concurrent test runs: change the test declaration from it(...) to
it.serial(...) so the try/finally cwd swap (process.chdir(originalCwd)) cannot
race with other tests; locate the test by its description string and adjust the
test invocation accordingly (the rest of the test body, including uses of
process.chdir, Elysia, staticPlugin, and req('/public/takodachi.png'), should
remain unchanged).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@test/index.test.ts`:
- Around line 488-503: Update the test named "serves files when cwd differs from
project root" to be run serially to avoid flakiness under concurrent test runs:
change the test declaration from it(...) to it.serial(...) so the try/finally
cwd swap (process.chdir(originalCwd)) cannot race with other tests; locate the
test by its description string and adjust the test invocation accordingly (the
rest of the test body, including uses of process.chdir, Elysia, staticPlugin,
and req('/public/takodachi.png'), should remain unchanged).

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 2a866fe0-bd91-4792-9699-3c3df17e7267

📥 Commits

Reviewing files that changed from the base of the PR and between 62aea0c and 4b6c9ce.

📒 Files selected for processing (3)
  • src/index.ts
  • src/utils.ts
  • test/index.test.ts

@yuriiShmal
Copy link
Copy Markdown
Contributor Author

@coderabbitai help

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 1, 2026

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

CodeRabbit commands

These commands are invoked using PR/Issue comments.

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai rate limit to show your current review rate limit status.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai evaluate custom pre-merge check --instructions <custom-checks-instructions> --name <custom-checks-title> [--mode <error|warning>] to validate the custom pre-merge checks instructions. Defaults to error when --mode is omitted.
  • @coderabbitai ignore pre-merge checks to override pre-merge checks and get an approval on PR.
  • @coderabbitai run pre-merge checks to run pre-merge checks on the pull request.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve merge conflict to automatically resolve merge conflicts.
  • @coderabbitai autofix to automatically fix issues identified in unresolved review comments.
  • @coderabbitai resolve to resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai generate configuration to create a PR that adds the current resolved configuration as .coderabbit.yaml (or show it if already present).
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit configuration file (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • You can also validate your configuration using the online YAML validator.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, support, documentation and community

  • Visit our status page to check the current availability of CodeRabbit.
  • Create a ticket on our support page for assistance with any issues or questions.
  • Visit our documentation site for detailed information on how to use CodeRabbit.
  • Join our Discord community to connect with other users and get help from the community.
  • Follow us on X/Twitter for updates and announcements.

@yuriiShmal
Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 1, 2026

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/index.ts (1)

342-349: ⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

Block .. escapes before touching the filesystem, baka~ (¬‿¬ )♡

This still lets a request like /public/../package.json resolve outside assetsDir in dynamic mode, so arbitrary files can be served. Resolve the candidate path first, then reject anything whose relative path escapes the assets root.

♨️ Tight fix
-                const pathName = normalizePath(
-                    path.join(
-                        assetsDir,
-                        decodeURI
-                            ? (fastDecodeURI(params['*']) ?? params['*'])
-                            : params['*']
-                    )
-                )
+                const requestedPath = decodeURI
+                    ? (fastDecodeURI(params['*']) ?? params['*'])
+                    : params['*']
+                const resolvedPath = path.resolve(assetsDir, requestedPath)
+                const relativeToAssets = path.relative(assetsDir, resolvedPath)
+
+                if (
+                    relativeToAssets.startsWith('..') ||
+                    path.isAbsolute(relativeToAssets)
+                )
+                    throw new NotFoundError()
+
+                const pathName = normalizePath(resolvedPath)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/index.ts` around lines 342 - 349, The current construct builds pathName
before resolving and allows `/public/../package.json` to escape assetsDir;
change the logic in the block around normalizePath/path.join so you first
compute the candidate string (using the existing decodeURI ?
fastDecodeURI(params['*']) ?? params['*'] : params['*']), then call
path.resolve(assetsDir, candidate) to get an absoluteCandidate, then compute
path.relative(assetsDir, absoluteCandidate) and reject/return a 403 if that
relative path starts with '..' or is equal to '..' (i.e., escapes the root);
only after that safe-check call normalizePath on absoluteCandidate and
continue—this involves the same symbols: assetsDir, params['*'], fastDecodeURI,
path.resolve, path.relative, normalizePath.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@test/index.test.ts`:
- Around line 540-542: The test hard-codes "/tmp" which is OS-dependent and may
accidentally contain a package.json; change the spec to create an isolated
temporary directory (e.g., using fs.mkdtemp or fs.promises.mkdtemp with
os.tmpdir()), build a path like path.join(tmpDir, 'index.ts') (optionally create
the file), call findProjectRoot(tmpIndexPath) and assert null, then remove the
temp directory; update the test case around findProjectRoot to use the temporary
directory helper instead of "/tmp/no-such-project/index.ts".
- Around line 505-507: The test "serves files when assets is an absolute path"
constructs absoluteAssets using process.cwd(), making the test cwd-dependent;
change the resolution to use the test file directory (e.g., import.meta.dir or
__dirname) instead of process.cwd() so absoluteAssets is stable across
environments—update the path.resolve call that assigns absoluteAssets (used when
creating new Elysia().use(staticPlugin({ assets: absoluteAssets }))) to base off
import.meta.dir/__dirname.

---

Outside diff comments:
In `@src/index.ts`:
- Around line 342-349: The current construct builds pathName before resolving
and allows `/public/../package.json` to escape assetsDir; change the logic in
the block around normalizePath/path.join so you first compute the candidate
string (using the existing decodeURI ? fastDecodeURI(params['*']) ?? params['*']
: params['*']), then call path.resolve(assetsDir, candidate) to get an
absoluteCandidate, then compute path.relative(assetsDir, absoluteCandidate) and
reject/return a 403 if that relative path starts with '..' or is equal to '..'
(i.e., escapes the root); only after that safe-check call normalizePath on
absoluteCandidate and continue—this involves the same symbols: assetsDir,
params['*'], fastDecodeURI, path.resolve, path.relative, normalizePath.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: fd2c11d3-f289-4d1e-bfb0-e895583c9509

📥 Commits

Reviewing files that changed from the base of the PR and between 4b6c9ce and 436efb4.

📒 Files selected for processing (3)
  • src/index.ts
  • src/utils.ts
  • test/index.test.ts

Comment thread test/index.test.ts
Comment on lines +505 to +507
it('serves files when assets is an absolute path', async () => {
const absoluteAssets = path.resolve(process.cwd(), 'public')
const app = new Elysia().use(staticPlugin({ assets: absoluteAssets }))
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Use the fixture location, not process.cwd(), dummy~ ( ̄^ ̄)ゞ

This “absolute path” regression still derives the path from the current working directory, so it can fail before it even exercises the behavior under test. Resolve from import.meta.dir / __dirname instead so the test stays invariant to cwd.

♻️ Small cleanup
-        const absoluteAssets = path.resolve(process.cwd(), 'public')
+        const absoluteAssets = path.resolve(__dirname, '../public')
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
it('serves files when assets is an absolute path', async () => {
const absoluteAssets = path.resolve(process.cwd(), 'public')
const app = new Elysia().use(staticPlugin({ assets: absoluteAssets }))
it('serves files when assets is an absolute path', async () => {
const absoluteAssets = path.resolve(__dirname, '../public')
const app = new Elysia().use(staticPlugin({ assets: absoluteAssets }))
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@test/index.test.ts` around lines 505 - 507, The test "serves files when
assets is an absolute path" constructs absoluteAssets using process.cwd(),
making the test cwd-dependent; change the resolution to use the test file
directory (e.g., import.meta.dir or __dirname) instead of process.cwd() so
absoluteAssets is stable across environments—update the path.resolve call that
assigns absoluteAssets (used when creating new Elysia().use(staticPlugin({
assets: absoluteAssets }))) to base off import.meta.dir/__dirname.

Comment thread test/index.test.ts
Comment on lines +540 to +542
it('returns null when no package.json is found above the entrypoint', async () => {
const result = await findProjectRoot('/tmp/no-such-project/index.ts')
expect(result).toBeNull()
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Don’t hard-code /tmp for the “no project root” case, brat~ (◕‿◕✿)♡

This assumes a POSIX-ish host and also assumes no ancestor like /tmp/package.json exists. That makes the test environment-dependent. A fresh temp directory created during the test would keep this deterministic.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@test/index.test.ts` around lines 540 - 542, The test hard-codes "/tmp" which
is OS-dependent and may accidentally contain a package.json; change the spec to
create an isolated temporary directory (e.g., using fs.mkdtemp or
fs.promises.mkdtemp with os.tmpdir()), build a path like path.join(tmpDir,
'index.ts') (optionally create the file), call findProjectRoot(tmpIndexPath) and
assert null, then remove the temp directory; update the test case around
findProjectRoot to use the temporary directory helper instead of
"/tmp/no-such-project/index.ts".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

process.cwd() for assets path (unexpected breakage in production)

2 participants