Add optional hash and searchParams arguments to resolve()
#14750
hash and searchParams arguments to resolve()Development PRs
Please go easy on me as this is the first PR I'm making to this repository, I am more than open to any suggested changes. I've been trying to get some help with this PR from the official Discord server, but discussion was pretty stale. So I'm hoping by opening this PR we can get this change going. Or, if the conclusion is 'we shouldnt do this at all', that's fine too!
Adds optional arguments for URL params hash and searchParams to resolve(). Appends these to the returned URL after resolving the path.
Resolves #14750 and helps address sveltejs/eslint-plugin-svelte#1353
- Additionally updates the example docstring to show new usage:
import { resolve } from '$app/paths';
// using a pathname
const resolved = resolve(`/blog/hello-world`);
// using a route ID plus route parameters
const resolved = resolve('/blog/[slug]', {
slug: 'hello-world'
});
// using a route ID plus URL parameters
const resolved = resolve('/blog/search',
{ hash: 'results', searchParams: { author: 'John Doe', year: '2025' } }
});
// using a route ID plus route parameters and URL parameters
const resolved = resolve('/blog/[slug]',
{ slug: 'hello-world' },
{ hash: 'introduction' }
});
Please don't delete this checklist! Before submitting the PR, please make sure you do the following:
- It's really useful if your PR references an issue where it is discussed ahead of time. In many cases, features are absent for a reason. For large changes, please create an RFC: https://github.com/sveltejs/rfcs
- PR references an issue, but no discussion as of yet.
- This message body should clearly illustrate what problems it solves.
- Ideally, include a test that fails without this PR but passes with it.
- I tried writing some tests in
kit/packages/kit/test/apps/basics/test/client.test.js, but was met withReferenceError: __SVELTEKIT_PAYLOAD__ is not defined at ../../../../src/runtime/app/paths/internal/client.js:1. This makes sense, becauseresolveRouteis used inresolve, which usesbase, which needs__SVELTEKIT_PAYLOAD__. I wasn't able to find any existing tests forresolveorresolveRoute, other than atpackages/kit/test/apps/options/test/test.jsat line97, which seems to be more of an integration test than actually testingresolveRouteitself. This is my first PR for this repo, so I'm not sure where below tests should go. Willing to add these if I get some pointers in the right direction.
import { resolve } from '../../../../src/runtime/app/paths/client.js'; describe('resolve function', () => { it('resolves a simple pathname', () => { const result = resolve('/blog/hello-world'); expect(result).toBe('/blog/hello-world'); }); it('resolves a route ID with dynamic parameters', () => { const result = resolve('/blog/[slug]', { slug: 'hello-world' }); expect(result).toBe('/blog/hello-world'); }); it('resolves a route ID with URL parameters', () => { const result = resolve('/blog/search', { hash: 'results', searchParams: { author: 'John Doe', year: '2025' } }); expect(result).toBe('/blog/search?author=John%20Doe&year=2025#results'); }); it('resolves a route ID with both dynamic and URL parameters', () => { const result = resolve('/blog/[slug]', { slug: 'hello-world' }, { hash: 'introduction' }); expect(result).toBe('/blog/hello-world#introduction'); }); it('handles empty parameters gracefully', () => { const result = resolve('/blog/[slug]', {}); expect(result).toBe('/blog/[slug]'); }); }); - I tried writing some tests in
Tests
- Run the tests with
pnpm testand lint the project withpnpm lintandpnpm check
Changesets
- If your PR makes a change that should be noted in one or more packages' changelogs, generate a changeset by running
pnpm changesetand following the prompts. Changesets that add features should beminorand those that fix bugs should bepatch. Please prefix changeset messages withfeat:,fix:, orchore:.- added a changeset as requested, but also somewhat unfamiliar with the 'correct' process for these, so a review is required.
Edits
- Please ensure that 'Allow edits from maintainers' is checked. PRs without this option may be closed.
Summary by CodeRabbit
-
New Features
- Full custom quiz/test mode: builder, runner (timed/offline-capable), submission, and detailed results/review UI.
- Feature announcements/spotlight with per-user seen state.
- Recent module activity and progress summaries surfaced in UI.
-
Documentation
- Added comprehensive design and implementation plan for test mode v1.
-
Chores
- Updated many project dependencies.
- Expanded backend schema to support quiz attempts and items.
-
Style
- Large UI refresh: rounded/pill styling across admin, improved class/module card visuals, and an animated changelog timeline.
Summary
Adds a ResolvablePath type that extends Pathname with optional ?${string} and #${string} suffixes, allowing resolve() to accept pathnames with query strings and hash fragments.
- No runtime changes —
resolve_route()already passes through?and#correctly Pathnametype is unchanged (still used forpage.url.pathname)- Existing
resolve()behavior with route IDs and params is unaffected
Motivation
Currently there is no way to use goto() with query strings or hash fragments without either disabling the lint rule or bypassing resolve():
resolve('/products?page=2')fails type-checking (Pathnamedoesn't include?)goto(resolve('/products') + '?page=2')fails thesvelte/no-navigation-without-resolvelint rule (argument isn't aresolve()call)
Per @teemingc's suggestion in #14750:
"It should be possible to add a union type with a template string such as
/my-route#${string}and/my-route?${string}. This would continue to keep the function type-safe."
This is a minimal type-only fix that doesn't conflict with #14756 (which adds richer { hash, searchParams } options).
What this enables
// All of these now type-check AND satisfy the lint rule:
goto(resolve('/products?page=2'));
goto(resolve(`/search?${params}`));
goto(resolve('/docs/intro#getting-started'));
Test plan
-
pnpm checkpasses -
pnpm lintpasses - Existing tests pass (no runtime changes, only type widening)
Closes #14750
Summary by CodeRabbit
-
Refactor
- Improved navigation path handling for more reliable routing across the app.
- Made "Play Again" visibility more consistent after finishing a game and improved leaderboard navigation.
- Enhanced list rendering stability for smoother updates and better performance.
-
Chores
- Removed unused imports to tidy the codebase.
Summary by CodeRabbit
-
New Features
- Full Clerk authentication: sign-in, sign-up, password reset, Google SSO, and session handling with automatic sign-out.
- Workspace access flow: authenticated users must join/create workspaces; redirects guide users accordingly.
- Client/server session bridging for secure API calls.
-
Documentation
- Added a SvelteKit + Clerk integration reference.
-
UI / Styling
- New auth page layouts and improved dark-mode selection styling.
fixes :- #515
Summary by CodeRabbit
- Bug Fixes
- Improved step navigation to reliably preserve template selections and clean up query parameters when returning to the primary screen.
- Refined “Next” navigation during template conversion so the updated template selection is reflected immediately while maintaining scroll and focus.
- Improved form population by copying available configuration fields from loaded test/template data.
- UI Improvements
- Made the stepper and question list headings conditional during template conversion (“Review Questions” vs “Select Questions”).
- Updated the questions view to match the conversion state consistently.
This adds a contextual person details panel when a person page/chat window is opened. On this PR I also added end to end tests for this feature but discovered some other things I needed to fix before I could run and test them so they are fixed in this PR as well.
https://www.loom.com/share/ed1289e43267414ab9a3efeb084b074a
Summary by CodeRabbit
- New Features
- Added a person context panel with profile details, communication status, contact info, teams/tags, notes, and last active activity.
- Included desktop sidebar and mobile drawer experiences with expand/collapse, close, and “view full profile” navigation.
- Added loading, error, permission, and not-found states.
- Added support to toggle person data loading when needed.
- Improvements
- Notes now show the latest (and ignore deleted entries) and support adding notes from the panel.
- Added localized strings for the new person context UI.
- Tests
- Expanded end-to-end coverage for the person context panel and notes flows.
Free AP Practice 1.7.10
User-facing release notes
- Reworked graded and shared quizzes into a focused full-screen experience with progress navigation, review, and score summaries.
- Added answer elimination and text highlighting for passages and prompts.
- Improved keyboard navigation, focus handling, screen-reader support, quiz loading, retry, and leave-quiz flows.
- Synchronized live version metadata and changelog entries for 1.7.10.
Quality gates
bun run lintbun run test:unit- 115 files, 423 tests passedbun run check- 0 errors, 0 warningsbun run build- passed
git diff --check and the pinned Svelte MCP autofixer also passed with no issues. The build emitted existing non-fatal dependency-resolution, large-chunk, and Sentry upload-permission warnings.
Continuation of #1482 (originally #1444), rebased onto current main, with the review feedback from #1482 addressed.
What this does
svelte/no-navigation-without-resolve no longer reports:
- Resolved URLs followed by a query string or a fragment, e.g.
resolve('/foo') + '?page=2',`${resolve('/foo')}#section`,resolve('/') + (searchParams.size ? `?${searchParams}` : ''), or<a href="{resolve('/foo')}?page=2">. A URL counts as resolved if it starts withresolve()/asset()or aResolvedPathnamevalue. - Query-only and fragment-only URLs, e.g.
goto('?page=2'),<a href="?{searchParams}">orreplaceState('#top', {}), as they keep the current path. Fragment-only URLs were previously only allowed in links.
A resolved value followed by anything other than a query or a fragment (e.g. resolve('/foo') + '/bar') is still reported, since it bypasses the route type-checking of resolve(). This follows the discussion in sveltejs/kit#14750.
URLs may be built with + concatenation, template literals, multi-part href attributes, variables, array elements, object properties, {#each} items and ternaries, in any combination.
Behaviour change for href attributes
Previously, only the first part of a multi-part href attribute was checked, so <a href="{resolve('/foo')}/bar"> was not reported. All parts are now checked, so it is reported. To fix such links, pass the whole path to resolve() (e.g. resolve('/blog/[slug]', { slug })) and start a query or fragment with a literal ? or # (e.g. href="{resolve('/search')}?{params}").
Leading and trailing whitespace in an href is ignored, as browsers strip it, so <a href=" {resolve('/foo')} "> is not reported. Whitespace between the parts is kept, as it stays in the URL.
Review feedback from #1482
- Fixed a crash on template literals containing only
resolve()(or nothing). - Concatenation is only recognised for the
+operator. - Replaced the separate
BinaryExpression/TemplateLiteralhandling with a single check over the URL's parts. Variables, member accesses and{#each}items are expanded along the way. Cyclic definitions are guarded by a set of the variables expanded on the current path, rather than aFindVariableContext, because a shared one would make the branches of a ternary interfere with each other, and a fresh one per branch loops forever on cyclic definitions. - Documented queries, fragments and
ResolvedPathnamein the rule docs.
Related: #1381 adds suffix support behind an option; this PR enables it by default.
Issue
Describe the problem
For internal navigation, I tend to use goto().
The lint rule triggers when calling goto() without wrapping the path in resolve().
However, since resolve() currently only accepts plain /route or /route/[slug] URLs, it's not possible to use goto() with URLs that include a hash or search parameters. Or at least, not without triggering that linting rule.
e.g. this throw the linting rule for both the a tag and the button
<script lang="ts">
import { goto } from "$app/navigation";
import { resolve } from "$app/paths";
const myURL = resolve('/my-page') + '#some-hash';
</script>
<a href={myURL}>My A Tag</a>
<button onclick={() => { goto(myURL) }}>My Button</button>
If we try to apply the tag inside the resolve() function:
<script lang="ts">
import { goto } from "$app/navigation";
import { resolve } from "$app/paths";
</script>
<a href={resolve('/my-page#some-hash')}>My A Tag</a>
<button onclick={() => { goto(resolve('/my-page#some-hash')) }}>My Button</button>
We get a type mismatch, which is pretty much the point of the resolve() function:
error| Argument of type '["/my-page#some-hash"]' is not assignable to parameter of type '[route: "/"] | [route: "/my-page"] | [route: "/my-page/"]'. Type '["/my-page#some-hash"]' is not assignable to type '[route: "/my-page/"]'. Type '"/my-page#some-hash"' is not assignable to type '"/my-page/"'.
I've tried several workarounds, including string interpolation and concatenation, but these approaches also trigger the lint rule.
Note: The playground doesn’t actually run SvelteKit, so resolve() doesn’t throw typing errors there as it would locally. There's no /routes/my-page/+page.svelte, but <a href={resolve(hashedSvelteURL)}>my svelte link</a> is still accepted as “valid”.
Currently, the only way to navigate to unresolved or partially resolved paths is via window.location.href, which makes sense since it's .
However, since linking to fragments like /projects#project-slug is common (and even used throughout the Svelte docs), it seems odd that resolve() doesn’t support searchParams or hash values.
So unless I’m missing something, the only two options at the moment are:
- ignore the lint rule, or
- use
window.location.hreffor internal navigation.
Alternatives considered
I searched for documentation or existing discussions on how to handle this within the current linting constraints but couldn’t find any.
If a workaround already exists, perhaps the could be updated to include guidance or examples.
Would you like me to make it sound slightly more “formal” (to match typical framework issue tone), or keep this slightly conversational GitHub style?
Describe the proposed solution
.
It would be helpful if it also accepted optional arguments like:
resolve(path, { hash?: string, searchParams?: Record<string, string> })
These additions wouldn’t break existing functionality and would make internal navigation with anchors or query parameters lint-compliant.
Implementation-wise, resolve() could run its existing logic first and then append the hash and/or serialized searchParams', similar to how SvelteURL` appends these.
Alternatives considered
I searched for documentation or existing discussions on how to handle this within the current linting constraints but couldn’t find any.
If a workaround already exists, perhaps the could be updated to include a pointer to this workaround.
Alternative solutions would be:
-
Relax the linting rule to allow strings that append hashes or search parameters. However, this feels undesirable, since it’s much cleaner to define hash and searchParams programmatically—similar to how SvelteURL handles them—rather than relying on string interpolation.
-
Add built-in
resolve()support for SvelteURL, so that we could call something likegoto(mySvelteURL.resolve()). -
Allow
resolve()to take inSvelteURL, and resolve it from there. This might even be the 'prettiest' option. This would probably need extra work soSvelteURLcan be expanded with a.slugattribute.
Importance
would make my life easier
Additional Information
No response
This issue in sveltejs/eslint-plugin-svelte seems to be at least somewhat related, should we go for the 'this is the linting rules job' route.
I've implemented this feat in the above commit ( codevogel@5853cb9 )
For anyone who's interested, I'll have to do some investigating on what tests I need to write before I can open up a PR to close this issue. If, in the meanwhile, someone can take a look at my work and review it, it'd be much appreciated, as this would be my first PR in this repo.
Would absolutely love to see support or solution for that
Sounds like this is a 2 part problem: the type mismatch and the linting rule error. I think we can avoid the linting rule error if we just resolve the type mismatch first. It should be possible to add a union type with a template string such as /my-route#${string} and /my-route?${string}. This would continue to keep the function type-safe.
Sounds like this is a 2 part problem: the type mismatch and the linting rule error. I think we can avoid the linting rule error if we just resolve the type mismatch first. It should be possible to add a union type with a template string such as
/my-route#${string}and/my-route?${string}. This would continue to keep the function type-safe.
I am kind of wondering if we should even include this functionality in to resolve at all.
It doesn't really have to do anything with resolving a path -- the hash and search params should have no influence on the routing of said function. So maybe this is really just lint related.
I am kind of wondering if we should even include this functionality in to
resolveat all. It doesn't really have to do anything with resolving a path -- the hash and search params should have no influence on the routing of said function. So maybe this is really just lint related.
How would it look like to create a path with searchParams, e.g. /card?brand=1&model=2&color=blue
How would it look like to create a path with
searchParams, e.g./card?brand=1&model=2&color=blue
See #14756 for example usage.
@codevogel that's the question, same example from your PR:
// using a route ID plus URL parameters
const resolved = resolve('/blog/search',
{ hash: 'results', searchParams: { author: 'John Doe', year: '2025' } }
});
It looks great and I'd love to use it that way. The question is for:
I am kind of wondering if we should even include this functionality in to
resolveat all.
How do you see it without adding such functionality to resolve?
This response got longer and longer as I started typing it, so I'll section it off...
To answer your question
How do you see it without adding such functionality to
resolve?
Two One option I think would suffice:
-
Relax the linting rule so that the original workarounds from the OP (like moustache interpolation) wouldn't report an
unresolved pathlinting error.
For example, simply concatenating the hash or search params to the resolved path should be fine:<script> import { resolve } from '$app/paths' // fine const href = resolve('/my-route/[slug]', { slug: 'foo' }) + '#my-hash' </script> <a {href}>My link</a>It should also be relatively trivial to perform this linting check, since
hashandsearchParamshave a very well-defined signature. So it should still be easy to detect when the resolved path has actually been altered:<script> import { resolve } from '$app/paths' // Still throws the error: the extra 'bogus' makes it an invalid path const href = resolve('/my-route/[slug]', { slug: 'foo' }) + 'bogus' + '#my-hash' // Still throws the error: extra 'bogus' before the query string const hrefSearchParam = resolve('/my-route/[slug]', { slug: 'foo' }) + 'bogus' + '?query=bar' </script>
Actually, this wouldn't work becauseresolvecould optionally take a(Svelte)URLrather than just a string for the path.new SvelteURL('/path')is not allowed, only full valid URLs are, e.g.https://example.com/path.
Relaxing the linting rule might be the best solution, but has its own downsides.
The more I think about it, the more I'm leaning towards relaxing the linting rule being the correct decision here.
The only downside is that manual interpolation of hash and searchParams can easily break URL syntax.
That, I guess, is the main benefit of including it in resolve. It would guarantee the correct order and encoding.
Here are some examples of how you can mess it up manually:
import { resolve } from '$app/paths'
// Hash before query params (order is wrong)
const href1 = resolve('/my-route') + '#hash' + '?query=foo' // -> /my-route#hash?query=foo
// Missing '?' before query params
const href2 = resolve('/my-route') + 'query=foo' // -> /my-routequery=foo
// Forgot to encode query params
const href3 = resolve('/my-route') + '?redirect=/my route' // -> /my-route?redirect=/my route (invalid space)
And here are some safer ways to do it:
import { resolve } from '$app/paths'
// Use URL/URLSearchParams to handle ordering and encoding correctly
const url = new URL(resolve('/my-route', { slug: 'foo' }), 'https://example.com')
url.searchParams.set('query', 'bar baz')
url.hash = 'section-2'
const href = url.pathname + url.search + url.hash
// results in: "/my-route/foo?query=bar+baz#section-2"
But even that is susceptible to messing up the search / hash order
Why this might not be the best fit for resolve
An argument as to why this shouldn't be added to resolve:
The resolve function's responsibility is to ensure a valid route path, not necessarily a valid full URL.
hash and searchParams don't affect routing unless you explicitly write logic that uses them for redirection, which is generally a design smell, and a problem for the user to solve, not for resolve to notice. To illustrate my point: say you have a path that's something like /my-route?redirect=foo, then technically, the path does resolve to /my-route, you just redirect after correctly arriving at /my-route).
So... while adding hash/search param support to resolve has its benefits, relaxing the lint rule might just be the better solution, given that there's another solution to the entire 'manual interpolation' side of things.
naaaah man, just compare this:
const url = new URL(resolve('/my-route', { slug: 'foo' }), 'https://example.com')
url.searchParams.set('query', 'bar baz')
url.hash = 'section-2'
const href = url.pathname + url.search + url.hash
to this:
// using a route ID plus URL parameters
const resolved = resolve('/blog/search',
{ hash: 'results', searchParams: { author: 'John Doe', year: '2025' } }
});
Don't doubt yourself, your PR version is superior and provides a lightning years better DX 😉
Don't doubt yourself, your PR version is superior and provides a lightning years better DX 😉
I mean, I do agree, the lower syntax would provide much better DX. Part of the reason why I opened the PR 🐦
But let's be honest, the hash and searchParams there have nothing to do with actually resolving the path 😛, so I could definitely see some opposition towards it, as it kind of breaks the SRP.
Maybe an additional idea would be some wrapper utility that does both: resolves a path, then safely appends the hash and searchParams. That way, resolve() stays focused, but we still get the DX benefits.
Something like resolveWithParams() or something of the likes.
Then the linting rule can just be relaxed to accept both resolve and resolveWithParams
But then again maybe that's bloating the API so my PR could just be the best solution afterall ¯\_(ツ)_/¯
Anyway, @vladshcherbin I could use some help getting the PR ready for approval in the meanwhile. I am not sure why the tests are failing. If you could be of help, it'd be much appreciated 👍
@teemingc - This is a bug, since there are NO workarounds.
const next = new URLSearchParams({ next: page.url.pathname });
const url = resolve('/login') + `?${next.toString()}`;
goto(url, {
replaceState: true
});
Currently, there is no way to satisfy the lint error without disabling it... (please correct me if I'm wrong).
J
I think the linting is overzealous in this case and we should fix it in the eslint plugin. Adding search param options to resolve wouldn’t fix the overzealousness in the cases where search params aren’t involved. For example, components which simply pass the value of a prop to the anchor tag still trigger this error.
Thanks for the reminder. I do think the core issue is solved but the ability to pass in an object to set the search params is quite nice. I’m not sure if we need this issue for that
We've decided that if we do want to do this we'd want it to enable typed search params at the very least. Some prior arts worth considering are:
Hmm, sorry just found this - I am the author of the svelte/no-navigation-without-resolve lint rule. We are currently working on a PR (sveltejs/eslint-plugin-svelte#1482) that should allow all of these to pass the lint:
<script>
import { resolve } from '$app/paths';
import { goto } from '$app/navigation';
const resolved = resolve('/foo/');
const empty = '';
const keyValue = 'bar=baz';
const queryValue = '?foo=bar';
const section = 'section';
const fragment = '#section';
const query1 = resolve('/foo') + '?';
const query2 = resolve('/foo') + '?foo=bar';
const query3 = resolve('/foo') + '?' + 'foo=bar';
const query4 = resolve('/foo') + '?' + keyValue;
const query5 = resolve('/foo') + `?${keyValue}`;
const query6 = resolve('/foo') + queryValue;
const fragment1 = resolve('/foo') + '#';
const fragment2 = resolve('/foo') + '#section';
const fragment3 = resolve('/foo') + '#' + 'section';
const fragment4 = resolve('/foo') + '#' + section;
const fragment5 = resolve('/foo') + `#${section}`;
const fragment6 = resolve('/foo') + fragment;
goto(resolve('/foo') + '');
goto(resolve('/foo') + empty);
goto(resolve('/foo') + '?');
goto(resolve('/foo') + '?foo=bar');
goto(resolve('/foo') + '?' + 'foo=bar');
goto(resolve('/foo') + '?' + keyValue);
goto(resolve('/foo') + `?${keyValue}`);
goto(resolve('/foo') + queryValue);
goto(`${resolve('/foo')}?`);
goto(`${resolve('/foo')}?foo=bar`);
goto(`${resolve('/foo')}${'?' + 'foo=bar'}`);
goto(`${resolve('/foo')}${'?' + keyValue}`);
goto(`${resolve('/foo')}?${keyValue}`);
goto(`${resolve('/foo')}${queryValue}`);
goto(resolved + '?');
goto(resolved + '?foo=bar');
goto(resolved + '?' + 'foo=bar');
goto(resolved + '?' + keyValue);
goto(resolved + `?${keyValue}`);
goto(resolved + queryValue);
goto(`${resolved}?`);
goto(`${resolved}?foo=bar`);
goto(`${resolved}${'?' + 'foo=bar'}`);
goto(`${resolved}${'?' + keyValue}`);
goto(`${resolved}?${keyValue}`);
goto(`${resolved}${queryValue}`);
goto(query1);
goto(query2);
goto(query3);
goto(query4);
goto(query5);
goto(query6);
goto(resolve('/foo') + '#');
goto(resolve('/foo') + '#section');
goto(resolve('/foo') + '#' + 'section');
goto(resolve('/foo') + '#' + section);
goto(resolve('/foo') + `#${section}`);
goto(resolve('/foo') + fragment);
goto(`${resolve('/foo')}#`);
goto(`${resolve('/foo')}#section`);
goto(`${resolve('/foo')}${'#' + 'section'}`);
goto(`${resolve('/foo')}${'#' + section}`);
goto(`${resolve('/foo')}#${section}`);
goto(`${resolve('/foo')}${fragment}`);
goto(resolved + '#');
goto(resolved + '#section');
goto(resolved + '#' + 'section');
goto(resolved + '#' + section);
goto(resolved + `#${section}`);
goto(resolved + fragment);
goto(`${resolved}#`);
goto(`${resolved}#section`);
goto(`${resolved}${'#' + 'section'}`);
goto(`${resolved}${'#' + section}`);
goto(`${resolved}#${section}`);
goto(`${resolved}${fragment}`);
goto(fragment1);
goto(fragment2);
goto(fragment3);
goto(fragment4);
goto(fragment5);
goto(fragment6);
</script>
...and the same for pushState, replaceState, and <a href="..."></a>.
Question for the Svelte team: Should we do that? Or do you prefer to push the queries and fragments into resolve?
I think it’s probably better to move forward with your current PR
I didn't want to wait until it's fixed so I added a workaround I'm sharing with anyone else.
Create new file src/lib/utils/resolve.ts
import { resolve as kitResolve } from '$app/paths';
import type { Pathname, ResolvedPathname, RouteId, RouteParams } from '$app/types';
export type AdditionalRouteParams = {
searchParams?: ConstructorParameters<typeof URLSearchParams>[0];
hash?: string;
};
// TODO patch-resolve | Temporary workaround until {@link https://github.com/sveltejs/kit/issues/14750} is fixed
export function resolve<T extends RouteId | Pathname>(
path: T,
params: T extends RouteId
? RouteParams<T> extends Record<string, never>
? AdditionalRouteParams | undefined
: RouteParams<T> & AdditionalRouteParams
: AdditionalRouteParams | undefined
): ResolvedPathname {
let resolved = kitResolve(path, params);
if (params?.searchParams) resolved += '?' + new URLSearchParams(params.searchParams);
if (params?.hash) resolved += '#' + params.hash;
return resolved as ResolvedPathname;
}
Update add following vite.config.ts Plugin
// TODO patch-resolve | Temporary workaround until {@link https://github.com/sveltejs/kit/issues/14750} is fixed
const patchResolve = () =>
({
name: 'patch-sveltekit-resolve',
enforce: 'pre',
transform(code: string, id: string) {
// Don't transform our wrapper function's imports
if (id.endsWith('src/lib/utils/resolve.ts')) return;
// Ignore any files which don't import paths
if (!code.includes('$app/paths')) return;
// Replace only the resolve import
return code.replace(
/import\s*{\s*([^}]*)\bresolve\b([^}]*)}\s*from\s*['"]\$app\/paths['"]/g,
(_, before, after) => {
const remaining = `${before}${after}`.replace(/^[\s,]+|[\s,]+$/g, '').trim();
const pathsImport = remaining ? `import { ${remaining} } from '$app/paths';\n` : '';
return `${pathsImport}import { resolve } from '$lib/utils/resolve.ts';`;
}
);
}
}) as const;
export default defineConfig({
plugins: [patchResolve(), sveltekit()],
});
And finally update src/app.d.ts to override the type
// TODO patch-resolve | Temporary workaround until {@link https://github.com/sveltejs/kit/issues/14750} is fixed
import type { Pathname, ResolvedPathname, RouteId, RouteParams } from '$app/types';
import type { AdditionalRouteParams } from '$lib/utils/resolve.ts';
declare module '$app/paths' {
/**
* Resolve a pathname by prefixing it with the base path, if any, or resolve a route ID by populating dynamic segments with parameters.
*
* During server rendering, the base path is relative and depends on the page currently being rendered.
*
* @example
* ```js
* import { resolve } from '$app/paths';
*
* // using a pathname
* const resolved = resolve(`/blog/hello-world`);
*
* // using a route ID plus parameters
* const resolved = resolve('/blog/[slug]', {
* slug: 'hello-world'
* });
*
* // using with fragment and search parameters
* const resolved = resolve('/blog/', {
* hash: 'focused',
* searchParams: { id: 'hello-world' }
* });
* ```
* @since 2.26
*/
export function resolve<T extends RouteId | Pathname>(
path: T,
params: T extends RouteId
? RouteParams<T> extends Record<string, never>
? AdditionalRouteParams | undefined
: RouteParams<T> & AdditionalRouteParams
: AdditionalRouteParams | undefined
): ResolvedPathname;
}I think it’s probably better to move forward with your current PR
Please! There are multiple issues and fixing linting as @marekdedic described is absolutely one of them regardless of the rest imo. I put a comment there (sveltejs/eslint-plugin-svelte#1482)
Cool stuff. Let me know if I can do anything to move #14756 forward, if still wanted.