svelte-bun 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Eric Liu
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,97 @@
1
- # Temporary Holding Version
1
+ # svelte-bun
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Svelte for Bun.build and Bun's dev server.
4
+
5
+ svelte-bun compiles Svelte 5 components and rune modules for Bun's dev
6
+ server and `Bun.build`, from one line of bunfig.
7
+ It reads `svelte.config.js`, so your preprocessors
8
+ and compiler options work as they do under Vite,
9
+ and it handles the cases where Bun's dev server breaks a Svelte app.
10
+ When Svelte rejects a file, the build fails with the file
11
+ and Svelte's message.
12
+
13
+ | On Bun 1.4.6, Svelte 5.59.1 | `bun-plugin-svelte` 0.0.6 | `svelte-bun` |
14
+ | :--- | :--- | :--- |
15
+ | `<svelte:head>` in the dev server | `undefined is not an object (evaluating '$.document.title = …')` | ✓ |
16
+ | a library's `svelte` export condition | `Could not resolve: "fake-lib"` | ✓ |
17
+ | `@import "./card.css"` in a component in a subdirectory | `Could not resolve: "./card.css"` | ✓ |
18
+ | preprocessors and `svelte.config.js` | ✗ | ✓ |
19
+ | a custom renderer, in `bun run` and `bun test` | ✗ can't pass `experimental.customRenderer` | ✓ |
20
+ | a minimal app, `minify: true`, production | 21.2 kB gzip | 18.7 kB gzip |
21
+
22
+ ## Quick start
23
+
24
+ ```sh
25
+ bun add -d svelte-bun svelte
26
+ ```
27
+
28
+ ```toml
29
+ # bunfig.toml
30
+ [serve.static]
31
+ plugins = ["svelte-bun"]
32
+ ```
33
+
34
+ ```sh
35
+ bun index.html
36
+ ```
37
+
38
+ Bun's dev server serves `index.html`,
39
+ compiling each `.svelte` file it reaches, with hot updates.
40
+ Options come from `svelte.config.js`, since bunfig can't pass any:
41
+
42
+ ```js
43
+ // svelte.config.js
44
+ import { optimizeImports } from "carbon-preprocess-svelte";
45
+
46
+ export default {
47
+ preprocess: [optimizeImports()],
48
+ compilerOptions: { runes: true },
49
+ };
50
+ ```
51
+
52
+ In `bun run` and `bun test`, a preload compiles the `.svelte` files
53
+ Bun's runtime imports, with the same config:
54
+
55
+ ```toml
56
+ # bunfig.toml
57
+ preload = ["svelte-bun/register"]
58
+ ```
59
+
60
+ ## From code
61
+
62
+ A production build, and a server build for prerendering:
63
+
64
+ ```ts
65
+ // build.ts
66
+ import { svelte } from "svelte-bun";
67
+
68
+ await Bun.build({
69
+ entrypoints: ["index.html"],
70
+ outdir: "dist",
71
+ minify: true,
72
+ plugins: [svelte({ production: true })],
73
+ });
74
+
75
+ await Bun.build({
76
+ entrypoints: ["src/ssr.ts"],
77
+ outdir: "dist/server",
78
+ target: "bun",
79
+ plugins: [svelte({ production: true, side: "server" })],
80
+ });
81
+ ```
82
+
83
+ `production` drops Svelte's development checks and the dev-only code in
84
+ its runtime; it defaults to `NODE_ENV === "production"`.
85
+ A host with its own bundler compiles files through `svelte-bun/compile`
86
+ instead.
87
+
88
+ ## Docs
89
+
90
+ - [Options](https://github.com/metonym/svelte-bun/blob/master/docs/options.md):
91
+ every option, `svelte.config.js`, custom renderers, and the preload
92
+ - [Compile API](https://github.com/metonym/svelte-bun/blob/master/docs/compile.md):
93
+ `compileFile()` and `scanImports()`, for another host
94
+ - [Compared](https://github.com/metonym/svelte-bun/blob/master/docs/compared.md):
95
+ what differs from `bun-plugin-svelte`, and how it was measured
96
+
97
+ These docs ship in the package, at `node_modules/svelte-bun/docs/`.
package/compile.d.ts ADDED
@@ -0,0 +1,91 @@
1
+ /** What `compileFile` returns. */
2
+ export type CompiledFile = {
3
+ js: string;
4
+ /** Svelte's warnings, each as `file:line:column message`. */
5
+ warnings: string[];
6
+ /** Set with `css: "external"` when the component has a `<style>`. */
7
+ css?: string;
8
+ };
9
+ /** Options for `compileFile`. */
10
+ export type CompileFileOptions = {
11
+ /** The name Svelte's warnings and scoped-CSS hashes use. */
12
+ filename: string;
13
+ side: Side;
14
+ /** Whether Svelte compiles in its development checks. */
15
+ dev?: boolean;
16
+ /**
17
+ * Whether to compile in Svelte's HMR, client side only; the host provides
18
+ * `import.meta.hot`.
19
+ */
20
+ hmr?: boolean;
21
+ /**
22
+ * `"external"` returns the CSS for the host to bundle; `"injected"`
23
+ * keeps it in the JS.
24
+ * @default "external"
25
+ */
26
+ css?: "external" | "injected";
27
+ /** Passed to Svelte's `compile()`; the options above win. */
28
+ compilerOptions?: Readonly<Record<string, unknown>>;
29
+ };
30
+ /** Which output Svelte generates. */
31
+ export type Side = "client" | "server";
32
+ /** The parts of `svelte/compiler` svelte-bun calls. */
33
+ export type SvelteCompiler = {
34
+ compile(source: string, options: Record<string, unknown>): {
35
+ js: {
36
+ code: string;
37
+ };
38
+ css: {
39
+ code: string;
40
+ } | null;
41
+ warnings: readonly SvelteWarning[];
42
+ };
43
+ compileModule(source: string, options: Record<string, unknown>): {
44
+ js: {
45
+ code: string;
46
+ };
47
+ warnings: readonly SvelteWarning[];
48
+ };
49
+ preprocess(source: string, preprocessors: unknown, options: {
50
+ filename: string;
51
+ }): Promise<{
52
+ code: string;
53
+ }>;
54
+ };
55
+ /** The parts of a Svelte warning svelte-bun reports. */
56
+ export type SvelteWarning = {
57
+ message: string;
58
+ start?: {
59
+ line: number;
60
+ column: number;
61
+ };
62
+ };
63
+ /** Compiles a component, or a `.svelte.ts` or `.svelte.js` rune module. */
64
+ export declare function compileFile(compiler: SvelteCompiler, source: string, options: CompileFileOptions): CompiledFile;
65
+ /** Which failure it is; a code never changes meaning. */
66
+ export type SvelteBunErrorCode =
67
+ /** `svelte` doesn't resolve from `root`. */
68
+ "SB_SVELTE_MISSING"
69
+ /** `svelte.config.js` threw while loading. */
70
+ | "SB_CONFIG_UNREADABLE"
71
+ /** A `svelte.config.js` value has the wrong type. */
72
+ | "SB_CONFIG_INVALID"
73
+ /** A preprocessor or Svelte's compiler threw on a file. */
74
+ | "SB_COMPILE_FAILED"
75
+ /** A bug in svelte-bun. */
76
+ | "SB_INTERNAL";
77
+ /** What to fix: the app's setup, a file, or, for `other`, svelte-bun. */
78
+ export type SvelteBunErrorKind = "setup" | "compile" | "other";
79
+ /** An error svelte-bun throws, with a stable `code`. */
80
+ export declare class SvelteBunError extends Error {
81
+ readonly code: SvelteBunErrorCode;
82
+ readonly kind: SvelteBunErrorKind;
83
+ constructor(code: SvelteBunErrorCode, message: string, options?: ErrorOptions);
84
+ }
85
+ /** Code a Svelte file's imports are in, and its loader. */
86
+ export type ScanPart = {
87
+ code: string;
88
+ loader: "js" | "ts";
89
+ };
90
+ /** Finds the code a Svelte file's imports are in, without compiling it. */
91
+ export declare function scanImports(source: string, path: string): ScanPart[];
@@ -0,0 +1,71 @@
1
+ # Compared with bun-plugin-svelte
2
+
3
+ `bun-plugin-svelte` is oven-sh's Svelte plugin for Bun;
4
+ this page lists where svelte-bun differs, each case reproduced.
5
+
6
+ | | `bun-plugin-svelte` 0.0.6 | `svelte-bun` |
7
+ | :--- | :--- | :--- |
8
+ | components, `<script lang="ts">` | ✓ | ✓ |
9
+ | `.svelte.ts` and `.svelte.js` rune modules | ✓ | ✓ |
10
+ | server output | ✓ | ✓ |
11
+ | HMR in Bun's dev server | ✓ | ✓ |
12
+ | `<svelte:head>` in the dev server | crashes | ✓ |
13
+ | a library's `svelte` export condition | doesn't resolve | ✓ |
14
+ | a relative `@import` in a nested component's `<style>` | doesn't resolve | ✓ |
15
+ | preprocessors, `svelte.config.js` | ✗ | ✓ |
16
+ | custom renderers (`experimental.customRenderer`) | ✗ | ✓ |
17
+ | export conditions in `bun run` without `--conditions` | ✗ | ✓ |
18
+ | a one-line preload for `bun run` and `bun test` | ✗ | `svelte-bun/register` |
19
+ | Svelte's warnings | ✗ dropped | reported, `file:line:column` |
20
+ | `compilerOptions` | 4 of them | all |
21
+ | Svelte's dev-only runtime code dropped in production | ✗ | ✓ |
22
+ | a hook to rewrite source before compiling | ✗ | `load` |
23
+ | a compile API for another host | ✗ | `svelte-bun/compile` |
24
+
25
+ ## The dev server
26
+
27
+ Each case ran in Bun 1.4.6's dev server, `bun index.html`,
28
+ with the plugin in bunfig, on a fixture app opened in WebKit.
29
+
30
+ - **`<svelte:head>`**: Bun's dev server re-exports Svelte's `document`
31
+ binding before `mount` assigns it, so a component that sets the title
32
+ throws
33
+ `undefined is not an object (evaluating '$.document.title = …')`.
34
+ svelte-bun reads the global in client code instead.
35
+ - **The `svelte` condition**: the dev server ignores a plugin's
36
+ `conditions`, so a library that ships its components under `svelte`,
37
+ as Carbon and svelte-highlight do, fails with
38
+ `Could not resolve: "fake-lib"`.
39
+ svelte-bun resolves that condition itself.
40
+ - **A relative `@import`**: `bun-plugin-svelte` bundles a component's
41
+ CSS from a virtual path, so `@import "./card.css"` in
42
+ `components/Card.svelte` fails with `Could not resolve: "./card.css"`,
43
+ in `Bun.build` too.
44
+ svelte-bun writes the CSS as `Card.svelte.css` beside the component.
45
+
46
+ ## From the source
47
+
48
+ `bun-plugin-svelte` forwards 4 of Svelte's `compilerOptions`:
49
+ `customElement`, `runes`, `modernAst` and `namespace`.
50
+ So `experimental.customRenderer` never reaches the compiler,
51
+ and it never reads a compile's `warnings`.
52
+
53
+ ## Size
54
+
55
+ A component with `$state` and `<svelte:head><title>`,
56
+ mounted from `index.html`, built with `minify: true`
57
+ and each plugin in production mode
58
+ (`development: false`, `production: true`), Svelte 5.59.1:
59
+
60
+ | Plugin | JavaScript | gzip |
61
+ | :--- | ---: | ---: |
62
+ | `bun-plugin-svelte` 0.0.6 | 56.7 kB | 21.2 kB |
63
+ | `svelte-bun` | 49.2 kB | 18.7 kB |
64
+
65
+ Bun doesn't fold constants imported from another module,
66
+ so Svelte's runtime keeps every `if (DEV)` branch
67
+ unless the plugin inlines `esm-env`'s values, as svelte-bun does.
68
+
69
+ ## Related
70
+
71
+ - [Options](options.md): what svelte-bun reads, and from where
@@ -0,0 +1,60 @@
1
+ # Compile API
2
+
3
+ `svelte-bun/compile` is svelte-bun without the Bun plugin:
4
+ the compile step and the import scanner,
5
+ for a host that bundles on its own.
6
+
7
+ ```ts
8
+ // integration.ts
9
+ import { compileFile, scanImports } from "svelte-bun/compile";
10
+ import * as compiler from "svelte/compiler";
11
+
12
+ const source = await Bun.file("src/App.svelte").text();
13
+ const { js, css } = compileFile(compiler, source, {
14
+ filename: "src/App.svelte",
15
+ side: "client",
16
+ dev: true,
17
+ hmr: true,
18
+ });
19
+ const parts = scanImports(source, "src/App.svelte");
20
+ ```
21
+
22
+ ## `compileFile`
23
+
24
+ `compileFile(compiler, source, options)` compiles one file
25
+ and returns `{ js, css, warnings }`,
26
+ each warning as `file:line:column message`.
27
+ A `.svelte` file compiles as a component;
28
+ a `.svelte.ts` or `.svelte.js` file compiles as a rune module,
29
+ with its TypeScript stripped first.
30
+
31
+ | Option | Sets |
32
+ | :--- | :--- |
33
+ | `filename` | the name Svelte's warnings and CSS hashes use |
34
+ | `side` | `"client"` or `"server"` |
35
+ | `dev` | Svelte's development checks |
36
+ | `hmr` | Svelte's HMR code, client side only; the host provides `import.meta.hot` |
37
+ | `css` | `"external"` returns the CSS as `css`; `"injected"` keeps it in `js` |
38
+ | `compilerOptions` | the rest of Svelte's `compile()` options |
39
+
40
+ `compiler` is the app's own `svelte/compiler`,
41
+ so the app's Svelte version compiles its files.
42
+
43
+ ## `scanImports`
44
+
45
+ `scanImports(source, path)` returns the code a file's imports are in,
46
+ without compiling it: each `<script>` block of a component,
47
+ with its loader, plus an import of Svelte's client runtime,
48
+ which every compiled component has.
49
+ A host that hashes a file's import graph, as an incremental build does,
50
+ scans these parts with `Bun.Transpiler`.
51
+
52
+ ## Not supported
53
+
54
+ - HMR transport: Bun's dev server provides `import.meta.hot`;
55
+ another host provides its own.
56
+ - Preprocessing: call `compiler.preprocess()` first, as the plugin does.
57
+
58
+ ## Related
59
+
60
+ - [Options](options.md): the plugin's options
@@ -0,0 +1,134 @@
1
+ # Options
2
+
3
+ The options `svelte()` takes set how svelte-bun compiles;
4
+ the bunfig entry takes none, and reads `svelte.config.js` instead.
5
+
6
+ ```ts
7
+ // build.ts
8
+ import { svelte } from "svelte-bun";
9
+
10
+ await Bun.build({
11
+ entrypoints: ["index.html"],
12
+ outdir: "dist",
13
+ plugins: [svelte({ production: true, css: "injected" })],
14
+ });
15
+ ```
16
+
17
+ | Option | Sets | Default |
18
+ | :--- | :--- | :--- |
19
+ | `root` | where `svelte.config.js` and `svelte` resolve from | the working directory |
20
+ | `production` | no development checks or HMR, and Svelte's dev-only runtime code dropped | `NODE_ENV === "production"` |
21
+ | `side` | `"client"` or `"server"` output | what the dev server asks for, else `"client"` |
22
+ | `preprocess` | Svelte preprocessors | `svelte.config.js`'s |
23
+ | `compilerOptions` | passed to Svelte's `compile()` | `svelte.config.js`'s |
24
+ | `css` | `"external"`: a stylesheet beside the component; `"injected"`: in the JS | `"external"` |
25
+ | `conditions` | export conditions packages resolve through, the first match winning | `["svelte"]` |
26
+ | `onwarn` | what to do with each Svelte warning, `file:line:column message` | print it, except under `node_modules` |
27
+ | `load` | the source to compile in place of a file's own | none |
28
+
29
+ ## `svelte.config.js`
30
+
31
+ svelte-bun reads the first of `svelte.config.js`,
32
+ `.mjs` and `.ts` in `root`, and takes its `preprocess`
33
+ and `compilerOptions`.
34
+ An option passed to `svelte()` wins over the file.
35
+ A config that fails to load fails the build with `SB_CONFIG_UNREADABLE`,
36
+ and a `compilerOptions` that isn't an object with `SB_CONFIG_INVALID`.
37
+
38
+ ## `conditions`
39
+
40
+ Bun's dev server ignores a plugin's export conditions,
41
+ and Bun's runtime takes them only from `--conditions`,
42
+ so svelte-bun resolves these itself:
43
+ a component library that ships its components under `svelte`,
44
+ as Carbon and svelte-highlight do, resolves to them, in a build,
45
+ the dev server, and `bun run`.
46
+
47
+ ## `css`
48
+
49
+ With `"external"`, a component's CSS becomes a stylesheet next to it,
50
+ `App.svelte.css`, which Bun bundles like any CSS file:
51
+ a relative `@import` in the component's `<style>` resolves from the
52
+ component's directory.
53
+ `"injected"` puts the CSS in the component's JavaScript instead.
54
+
55
+ ## `load`
56
+
57
+ `load(path)` returns the source to compile for a `.svelte` file,
58
+ or `undefined` to read the file.
59
+ It runs before preprocessing, for a source rewriter such as
60
+ carbon-preprocess-svelte's:
61
+
62
+ ```ts
63
+ // build.ts
64
+ import { optimizeCarbonBun } from "carbon-preprocess-svelte";
65
+ import { svelte } from "svelte-bun";
66
+
67
+ const carbon = optimizeCarbonBun();
68
+ const result = await Bun.build({
69
+ entrypoints: ["index.html"],
70
+ outdir: "dist",
71
+ metafile: true,
72
+ plugins: [
73
+ carbon,
74
+ svelte({ production: true, load: (path) => carbon.load(path) }),
75
+ ],
76
+ });
77
+ await carbon.pruneBuild(result);
78
+ ```
79
+
80
+ ## At runtime
81
+
82
+ `svelte-bun/register` compiles the `.svelte` files that `bun run`
83
+ and `bun test` import, with the options in `svelte.config.js`:
84
+
85
+ ```toml
86
+ # bunfig.toml
87
+ preload = ["svelte-bun/register"]
88
+ ```
89
+
90
+ It registers the same plugin with `Bun.plugin()`,
91
+ so `conditions` apply there too, with no `--conditions` flag.
92
+
93
+ ## Custom renderers
94
+
95
+ A custom renderer renders Svelte components to something other than the
96
+ DOM, such as a terminal.
97
+ Name its module in `svelte.config.js`:
98
+
99
+ ```js
100
+ // svelte.config.js
101
+ export default {
102
+ compilerOptions: {
103
+ experimental: { customRenderer: "./src/terminal-renderer.js" },
104
+ },
105
+ };
106
+ ```
107
+
108
+ A relative path is relative to `root`; Svelte itself refuses one,
109
+ since each component would resolve it from its own directory.
110
+ With a renderer set, svelte-bun puts `svelte-custom-renderer` first in
111
+ `conditions`, so `svelte` resolves to the runtime that output needs,
112
+ and emits no CSS, since there's no DOM to style.
113
+ Every `.svelte` file compiles with the renderer, library components too:
114
+ a component and the snippets it renders must share one.
115
+
116
+ ## Errors
117
+
118
+ Every error svelte-bun throws is a `SvelteBunError`,
119
+ with a `code` from `SvelteBunErrorCode` and a `kind`:
120
+ `setup` for something the app is missing,
121
+ `compile` for a file Svelte rejected.
122
+ `SB_SVELTE_MISSING` means `svelte` doesn't resolve from `root`.
123
+
124
+ ## Not supported
125
+
126
+ - Svelte 4 and earlier: svelte-bun compiles with Svelte 5's API.
127
+ - Node: the plugin uses Bun's plugin API and transpiler.
128
+ - A build pipeline: prerendering, hydration,
129
+ and inlining CSS are the app's, or an SSG's.
130
+
131
+ ## Related
132
+
133
+ - [Compile API](compile.md): the same compile, without the plugin
134
+ - [Compared](compared.md): what the dev server breaks, and how
package/index.d.ts ADDED
@@ -0,0 +1,47 @@
1
+ import type { BunPlugin } from "bun";
2
+ import type { Side } from "./compile.js";
3
+
4
+ /** Options for `svelte()`; the bunfig entries read `svelte.config.js`. */
5
+ export type SvelteBunOptions = {
6
+ /**
7
+ * Where `svelte.config.js` and `svelte` resolve from.
8
+ * @default the working directory
9
+ */
10
+ root?: string;
11
+ /**
12
+ * Whether to drop Svelte's dev checks, HMR, and dev-only runtime code.
13
+ * @default NODE_ENV === "production"
14
+ */
15
+ production?: boolean;
16
+ /** @default what the dev server asks for, else "client" */
17
+ side?: Side;
18
+ /** @default svelte.config.js's */
19
+ preprocess?: unknown;
20
+ /** @default svelte.config.js's */
21
+ compilerOptions?: Readonly<Record<string, unknown>>;
22
+ /**
23
+ * `"external"` writes the CSS beside the component, so its relative
24
+ * `@import`s resolve; `"injected"` keeps it in the JS.
25
+ * @default "external"
26
+ */
27
+ css?: "external" | "injected";
28
+ /**
29
+ * Export conditions, first match wins; a custom renderer puts
30
+ * `svelte-custom-renderer` first.
31
+ * @default ["svelte"]
32
+ */
33
+ conditions?: readonly string[];
34
+ /** @default prints each warning, except under node_modules */
35
+ onwarn?: (warning: string, path: string) => void;
36
+ /**
37
+ * Source to compile instead of the file's, before preprocessing, as
38
+ * carbon-preprocess-svelte's `optimizeCarbonBun()` provides.
39
+ */
40
+ load?: (path: string) => {
41
+ code: string;
42
+ } | string | undefined;
43
+ };
44
+ /** Svelte for `Bun.build`, Bun's dev server, and Bun's runtime. */
45
+ export declare function svelte(options?: SvelteBunOptions): BunPlugin;
46
+ declare const plugin: BunPlugin;
47
+ export { plugin as default };
package/package.json CHANGED
@@ -1,6 +1,34 @@
1
1
  {
2
2
  "name": "svelte-bun",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Svelte for Bun.build and Bun's dev server.",
5
+ "license": "MIT",
6
+ "author": "Eric Liu (https://github.com/metonym)",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/metonym/svelte-bun.git"
10
+ },
11
+ "homepage": "https://github.com/metonym/svelte-bun",
12
+ "bugs": "https://github.com/metonym/svelte-bun/issues",
13
+ "type": "module",
14
+ "exports": {
15
+ ".": {
16
+ "types": "./index.d.ts",
17
+ "default": "./src/index.ts"
18
+ },
19
+ "./compile": {
20
+ "types": "./compile.d.ts",
21
+ "default": "./src/compile.ts"
22
+ },
23
+ "./register": {
24
+ "default": "./src/register.ts"
25
+ },
26
+ "./package.json": "./package.json"
27
+ },
28
+ "peerDependencies": {
29
+ "svelte": "^5.0.0"
30
+ },
31
+ "engines": {
32
+ "bun": ">=1.4.0"
33
+ }
34
+ }
package/src/compile.ts ADDED
@@ -0,0 +1,12 @@
1
+ export type {
2
+ CompiledFile,
3
+ CompileFileOptions,
4
+ Side,
5
+ SvelteCompiler,
6
+ SvelteWarning,
7
+ } from "./component.ts";
8
+ export { compileFile } from "./component.ts";
9
+ export type { SvelteBunErrorCode, SvelteBunErrorKind } from "./errors.ts";
10
+ export { SvelteBunError } from "./errors.ts";
11
+ export type { ScanPart } from "./scan.ts";
12
+ export { scanImports } from "./scan.ts";
@@ -0,0 +1,105 @@
1
+ /** Which output Svelte generates. */
2
+ export type Side = "client" | "server";
3
+
4
+ /** The parts of `svelte/compiler` svelte-bun calls. */
5
+ export type SvelteCompiler = {
6
+ compile(
7
+ source: string,
8
+ options: Record<string, unknown>,
9
+ ): {
10
+ js: { code: string };
11
+ css: { code: string } | null;
12
+ warnings: readonly SvelteWarning[];
13
+ };
14
+ compileModule(
15
+ source: string,
16
+ options: Record<string, unknown>,
17
+ ): { js: { code: string }; warnings: readonly SvelteWarning[] };
18
+ preprocess(
19
+ source: string,
20
+ preprocessors: unknown,
21
+ options: { filename: string },
22
+ ): Promise<{ code: string }>;
23
+ };
24
+
25
+ /** Options for `compileFile`. */
26
+ export type CompileFileOptions = {
27
+ /** The name Svelte's warnings and scoped-CSS hashes use. */
28
+ filename: string;
29
+ side: Side;
30
+ /** Whether Svelte compiles in its development checks. */
31
+ dev?: boolean;
32
+ /**
33
+ * Whether to compile in Svelte's HMR, client side only; the host provides
34
+ * `import.meta.hot`.
35
+ */
36
+ hmr?: boolean;
37
+ /**
38
+ * `"external"` returns the CSS for the host to bundle; `"injected"`
39
+ * keeps it in the JS.
40
+ * @default "external"
41
+ */
42
+ css?: "external" | "injected";
43
+ /** Passed to Svelte's `compile()`; the options above win. */
44
+ compilerOptions?: Readonly<Record<string, unknown>>;
45
+ };
46
+
47
+ /** The parts of a Svelte warning svelte-bun reports. */
48
+ export type SvelteWarning = {
49
+ message: string;
50
+ start?: { line: number; column: number };
51
+ };
52
+
53
+ /** What `compileFile` returns. */
54
+ export type CompiledFile = {
55
+ js: string;
56
+ /** Svelte's warnings, each as `file:line:column message`. */
57
+ warnings: string[];
58
+ /** Set with `css: "external"` when the component has a `<style>`. */
59
+ css?: string;
60
+ };
61
+
62
+ const RUNE_MODULE = /\.svelte\.[jt]s$/;
63
+ const typescript = new Bun.Transpiler({ loader: "ts" });
64
+
65
+ function isRuneModule(path: string): boolean {
66
+ return RUNE_MODULE.test(path);
67
+ }
68
+
69
+ /** Compiles a component, or a `.svelte.ts` or `.svelte.js` rune module. */
70
+ export function compileFile(
71
+ compiler: SvelteCompiler,
72
+ source: string,
73
+ options: CompileFileOptions,
74
+ ): CompiledFile {
75
+ const { filename, side, dev = false, hmr = false } = options;
76
+ const shared = { ...options.compilerOptions, filename, generate: side, dev };
77
+ if (isRuneModule(filename)) {
78
+ // compileModule reads JavaScript only.
79
+ const js = filename.endsWith(".ts")
80
+ ? typescript.transformSync(source)
81
+ : source;
82
+ const result = compiler.compileModule(js, shared);
83
+ return {
84
+ js: result.js.code,
85
+ warnings: result.warnings.map((w) => formatWarning(w, filename)),
86
+ };
87
+ }
88
+ const result = compiler.compile(source, {
89
+ ...shared,
90
+ css: options.css ?? "external",
91
+ hmr: hmr && side === "client",
92
+ });
93
+ const warnings = result.warnings.map((w) => formatWarning(w, filename));
94
+ const css = result.css?.code;
95
+ return css
96
+ ? { js: result.js.code, css, warnings }
97
+ : { js: result.js.code, warnings };
98
+ }
99
+
100
+ function formatWarning(warning: SvelteWarning, filename: string): string {
101
+ const at = warning.start
102
+ ? `:${warning.start.line}:${warning.start.column}`
103
+ : "";
104
+ return `${filename}${at} ${warning.message}`;
105
+ }
package/src/env.ts ADDED
@@ -0,0 +1,13 @@
1
+ export function productionByEnv(): boolean {
2
+ // eslint-disable-next-line no-restricted-properties -- the one env reader
3
+ return process.env.NODE_ENV === "production";
4
+ }
5
+
6
+ export function warn(message: string): void {
7
+ // eslint-disable-next-line no-console -- a build's warnings are for the person running it
8
+ console.warn(message);
9
+ }
10
+
11
+ export function workingDirectory(): string {
12
+ return process.cwd();
13
+ }
package/src/errors.ts ADDED
@@ -0,0 +1,39 @@
1
+ /** What to fix: the app's setup, a file, or, for `other`, svelte-bun. */
2
+ export type SvelteBunErrorKind = "setup" | "compile" | "other";
3
+
4
+ /** Which failure it is; a code never changes meaning. */
5
+ export type SvelteBunErrorCode =
6
+ /** `svelte` doesn't resolve from `root`. */
7
+ | "SB_SVELTE_MISSING"
8
+ /** `svelte.config.js` threw while loading. */
9
+ | "SB_CONFIG_UNREADABLE"
10
+ /** A `svelte.config.js` value has the wrong type. */
11
+ | "SB_CONFIG_INVALID"
12
+ /** A preprocessor or Svelte's compiler threw on a file. */
13
+ | "SB_COMPILE_FAILED"
14
+ /** A bug in svelte-bun. */
15
+ | "SB_INTERNAL";
16
+
17
+ const KINDS: Record<SvelteBunErrorCode, SvelteBunErrorKind> = {
18
+ SB_SVELTE_MISSING: "setup",
19
+ SB_CONFIG_UNREADABLE: "setup",
20
+ SB_CONFIG_INVALID: "setup",
21
+ SB_COMPILE_FAILED: "compile",
22
+ SB_INTERNAL: "other",
23
+ };
24
+
25
+ /** An error svelte-bun throws, with a stable `code`. */
26
+ export class SvelteBunError extends Error {
27
+ readonly code: SvelteBunErrorCode;
28
+ readonly kind: SvelteBunErrorKind;
29
+ constructor(
30
+ code: SvelteBunErrorCode,
31
+ message: string,
32
+ options?: ErrorOptions,
33
+ ) {
34
+ super(message, options);
35
+ this.name = "SvelteBunError";
36
+ this.code = code;
37
+ this.kind = KINDS[code];
38
+ }
39
+ }
package/src/esm-env.ts ADDED
@@ -0,0 +1,29 @@
1
+ const ESM_ENV_IMPORT = /^import \{([^}]+)\} from ['"]esm-env['"];?$/gm;
2
+ const ALIAS = /\s+as\s+/;
3
+
4
+ /**
5
+ * Inlines `esm-env`'s `DEV`, `BROWSER` and `NODE` in a module that imports
6
+ * them. Bun doesn't fold constants imported from another module, so
7
+ * without this every `if (DEV)` branch of Svelte's runtime ships.
8
+ */
9
+ export function inlineEsmEnv(
10
+ source: string,
11
+ env: { dev: boolean; browser: boolean },
12
+ ): string {
13
+ const values = new Map([
14
+ ["DEV", env.dev],
15
+ ["BROWSER", env.browser],
16
+ ["NODE", !env.browser],
17
+ ]);
18
+ return source.replace(ESM_ENV_IMPORT, (statement, names: string) => {
19
+ const bindings = names
20
+ .split(",")
21
+ .map((name) => name.trim().split(ALIAS))
22
+ .map(([name = "", local = name]) => ({ name, local }));
23
+ if (bindings.some(({ name }) => !values.has(name))) return statement;
24
+ const consts = bindings.map(
25
+ ({ name, local }) => `${local} = ${String(values.get(name))}`,
26
+ );
27
+ return `const ${consts.join(", ")};`;
28
+ });
29
+ }
package/src/index.ts ADDED
@@ -0,0 +1,315 @@
1
+ import { existsSync } from "node:fs";
2
+ import { basename, dirname, join, resolve } from "node:path";
3
+
4
+ import type { BunPlugin, OnLoadArgs } from "bun";
5
+
6
+ import { compileFile, type Side, type SvelteCompiler } from "./component.ts";
7
+ import { productionByEnv, warn, workingDirectory } from "./env.ts";
8
+ import { SvelteBunError } from "./errors.ts";
9
+ import { inlineEsmEnv } from "./esm-env.ts";
10
+ import { type ExportsCache, resolveCondition } from "./resolve.ts";
11
+
12
+ /** Options for `svelte()`; the bunfig entries read `svelte.config.js`. */
13
+ export type SvelteBunOptions = {
14
+ /**
15
+ * Where `svelte.config.js` and `svelte` resolve from.
16
+ * @default the working directory
17
+ */
18
+ root?: string;
19
+ /**
20
+ * Whether to drop Svelte's dev checks, HMR, and dev-only runtime code.
21
+ * @default NODE_ENV === "production"
22
+ */
23
+ production?: boolean;
24
+ /** @default what the dev server asks for, else "client" */
25
+ side?: Side;
26
+ /** @default svelte.config.js's */
27
+ preprocess?: unknown;
28
+ /** @default svelte.config.js's */
29
+ compilerOptions?: Readonly<Record<string, unknown>>;
30
+ /**
31
+ * `"external"` writes the CSS beside the component, so its relative
32
+ * `@import`s resolve; `"injected"` keeps it in the JS.
33
+ * @default "external"
34
+ */
35
+ css?: "external" | "injected";
36
+ /**
37
+ * Export conditions, first match wins; a custom renderer puts
38
+ * `svelte-custom-renderer` first.
39
+ * @default ["svelte"]
40
+ */
41
+ conditions?: readonly string[];
42
+ /** @default prints each warning, except under node_modules */
43
+ onwarn?: (warning: string, path: string) => void;
44
+ /**
45
+ * Source to compile instead of the file's, before preprocessing, as
46
+ * carbon-preprocess-svelte's `optimizeCarbonBun()` provides.
47
+ */
48
+ load?: (path: string) => { code: string } | string | undefined;
49
+ };
50
+
51
+ type Config = {
52
+ preprocess?: unknown;
53
+ compilerOptions?: Readonly<Record<string, unknown>>;
54
+ };
55
+
56
+ type Setup = {
57
+ compiler: SvelteCompiler;
58
+ preprocess: unknown;
59
+ compilerOptions: Readonly<Record<string, unknown>> | undefined;
60
+ renderer: string | undefined;
61
+ conditions: readonly string[];
62
+ };
63
+
64
+ const SVELTE = /\.svelte(\.[jt]s)?$/;
65
+ const SVELTE_CSS = /\.svelte\.css$/;
66
+ const BARE = /^[@a-z]/;
67
+ const SVELTE_RUNTIME = /[\\/]node_modules[\\/]svelte[\\/]src[\\/].+\.js$/;
68
+ const LIVE_GLOBAL = /\$\.(document|window)\b/g;
69
+ const NODE_MODULES = /[\\/]node_modules[\\/]/;
70
+ const RELATIVE = /^\.\.?([\\/]|$)/;
71
+ const CONFIG_FILES = [
72
+ "svelte.config.js",
73
+ "svelte.config.mjs",
74
+ "svelte.config.ts",
75
+ ];
76
+
77
+ function parseConfig(module: unknown, file: string): Config {
78
+ const config =
79
+ typeof module === "object" && module !== null && "default" in module
80
+ ? module.default
81
+ : undefined;
82
+ if (typeof config !== "object" || config === null) return {};
83
+ const parsed: Config = {};
84
+ if ("preprocess" in config) parsed.preprocess = config.preprocess;
85
+ if ("compilerOptions" in config) {
86
+ const options = config.compilerOptions;
87
+ if (typeof options !== "object" || options === null) {
88
+ throw new SvelteBunError(
89
+ "SB_CONFIG_INVALID",
90
+ `svelte-bun config: ${basename(file)}: compilerOptions is ${String(options)}: make it an object`,
91
+ );
92
+ }
93
+ parsed.compilerOptions = Object.fromEntries(Object.entries(options));
94
+ }
95
+ return parsed;
96
+ }
97
+
98
+ // Synchronous, since onResolve is: Bun's require loads ESM too.
99
+ function loadConfig(root: string): Config {
100
+ const file = CONFIG_FILES.map((name) => join(root, name)).find((path) =>
101
+ existsSync(path),
102
+ );
103
+ if (!file) return {};
104
+ let module: unknown;
105
+ try {
106
+ module = import.meta.require(file);
107
+ } catch (cause) {
108
+ throw new SvelteBunError(
109
+ "SB_CONFIG_UNREADABLE",
110
+ `svelte-bun config: ${basename(file)} failed to load: fix the error it throws`,
111
+ { cause },
112
+ );
113
+ }
114
+ return parseConfig(module, file);
115
+ }
116
+
117
+ function isCompiler(module: unknown): module is SvelteCompiler {
118
+ return (
119
+ typeof module === "object" &&
120
+ module !== null &&
121
+ "compile" in module &&
122
+ typeof module.compile === "function" &&
123
+ "compileModule" in module &&
124
+ typeof module.compileModule === "function" &&
125
+ "preprocess" in module &&
126
+ typeof module.preprocess === "function"
127
+ );
128
+ }
129
+
130
+ function loadCompiler(root: string): SvelteCompiler {
131
+ let module: unknown;
132
+ try {
133
+ module = import.meta.require(Bun.resolveSync("svelte/compiler", root));
134
+ } catch (cause) {
135
+ throw new SvelteBunError(
136
+ "SB_SVELTE_MISSING",
137
+ `svelte-bun: svelte isn't installed in ${root}: run \`bun add -d svelte\``,
138
+ { cause },
139
+ );
140
+ }
141
+ if (!isCompiler(module)) {
142
+ throw new SvelteBunError(
143
+ "SB_SVELTE_MISSING",
144
+ `svelte-bun: the svelte in ${root} has no Svelte 5 compiler: run \`bun add -d svelte@5\``,
145
+ );
146
+ }
147
+ return module;
148
+ }
149
+
150
+ // Svelte refuses a relative customRenderer, which each component would
151
+ // resolve from its own directory; here it's relative to root.
152
+ function withRenderer(
153
+ compilerOptions: Readonly<Record<string, unknown>> | undefined,
154
+ root: string,
155
+ ): Pick<Setup, "compilerOptions" | "renderer"> {
156
+ const given = compilerOptions?.experimental;
157
+ const experimental: object =
158
+ typeof given === "object" && given !== null ? given : {};
159
+ const renderer =
160
+ "customRenderer" in experimental &&
161
+ typeof experimental.customRenderer === "string"
162
+ ? experimental.customRenderer
163
+ : undefined;
164
+ if (renderer === undefined || !RELATIVE.test(renderer)) {
165
+ return { compilerOptions, renderer };
166
+ }
167
+ const absolute = resolve(root, renderer);
168
+ return {
169
+ compilerOptions: {
170
+ ...compilerOptions,
171
+ experimental: { ...experimental, customRenderer: absolute },
172
+ },
173
+ renderer: absolute,
174
+ };
175
+ }
176
+
177
+ // Bun's dev server passes `side` and `hmr` to onLoad; Bun.build doesn't.
178
+ function devServerSide(args: OnLoadArgs): Side | undefined {
179
+ if (!("side" in args)) return undefined;
180
+ return args.side === "server" ? "server" : "client";
181
+ }
182
+
183
+ function devServerHmr(args: OnLoadArgs): boolean {
184
+ return "hmr" in args ? args.hmr !== false : true;
185
+ }
186
+
187
+ function printWarning(warning: string, path: string): void {
188
+ if (!NODE_MODULES.test(path)) warn(`svelte: ${warning}`);
189
+ }
190
+
191
+ /** Svelte for `Bun.build`, Bun's dev server, and Bun's runtime. */
192
+ export function svelte(options: SvelteBunOptions = {}): BunPlugin {
193
+ const root = options.root ?? workingDirectory();
194
+ const production = options.production ?? productionByEnv();
195
+ const onwarn = options.onwarn ?? printWarning;
196
+ const stylesheets = new Map<string, { css: string; from: string }>();
197
+ const exportsCache: ExportsCache = new Map();
198
+ // Read on first use, not when the module loads: importing `svelte` from
199
+ // svelte-bun creates the default export too.
200
+ let setup: Setup | undefined;
201
+ const ready = (): Setup => {
202
+ if (setup) return setup;
203
+ const config = loadConfig(root);
204
+ const { compilerOptions, renderer } = withRenderer(
205
+ options.compilerOptions ?? config.compilerOptions,
206
+ root,
207
+ );
208
+ const conditions = options.conditions ?? ["svelte"];
209
+ setup = {
210
+ compiler: loadCompiler(root),
211
+ preprocess: options.preprocess ?? config.preprocess,
212
+ compilerOptions,
213
+ renderer,
214
+ conditions: renderer
215
+ ? ["svelte-custom-renderer", ...conditions]
216
+ : conditions,
217
+ };
218
+ return setup;
219
+ };
220
+
221
+ return {
222
+ name: "svelte-bun",
223
+ setup(build) {
224
+ build.onResolve({ filter: BARE }, (args) => {
225
+ const path = resolveCondition(
226
+ args.path,
227
+ args.importer,
228
+ ready().conditions,
229
+ exportsCache,
230
+ );
231
+ return path === undefined ? undefined : { path };
232
+ });
233
+
234
+ build.onLoad({ filter: SVELTE }, async (args) => {
235
+ const { compiler, preprocess, compilerOptions, renderer } = ready();
236
+ const fromDevServer = devServerSide(args);
237
+ const side = options.side ?? fromDevServer ?? "client";
238
+ const loaded = options.load?.(args.path);
239
+ const replaced = typeof loaded === "string" ? loaded : loaded?.code;
240
+ let source = replaced ?? (await Bun.file(args.path).text());
241
+ let out;
242
+ try {
243
+ if (preprocess !== undefined && args.path.endsWith(".svelte")) {
244
+ const filename = args.path;
245
+ source = (
246
+ await compiler.preprocess(source, preprocess, { filename })
247
+ ).code;
248
+ }
249
+ out = compileFile(compiler, source, {
250
+ filename: args.path,
251
+ side,
252
+ dev: !production,
253
+ // Only the dev server provides `import.meta.hot`.
254
+ hmr:
255
+ !production && fromDevServer !== undefined && devServerHmr(args),
256
+ ...(options.css ? { css: options.css } : {}),
257
+ ...(compilerOptions ? { compilerOptions } : {}),
258
+ });
259
+ } catch (cause) {
260
+ throw new SvelteBunError(
261
+ "SB_COMPILE_FAILED",
262
+ `svelte-bun: ${args.path}: ${cause instanceof Error ? cause.message : String(cause)}`,
263
+ { cause },
264
+ );
265
+ }
266
+ for (const warning of out.warnings) onwarn(warning, args.path);
267
+ let js = out.js;
268
+ // compat: Bun's dev server re-exports Svelte's `$document` and
269
+ // `$window` by value, before `mount` assigns them, so the client
270
+ // reads the globals instead.
271
+ if (side === "client" && fromDevServer !== undefined) {
272
+ js = js.replace(LIVE_GLOBAL, "$1");
273
+ }
274
+ // A custom renderer has no DOM for CSS to style.
275
+ if (side === "client" && out.css !== undefined && !renderer) {
276
+ // Beside the component, so the CSS's relative `@import`s resolve.
277
+ const id = `${args.path}.css`;
278
+ stylesheets.set(id, { css: out.css, from: args.path });
279
+ js += `\nimport ${JSON.stringify(`./${basename(id)}`)};`;
280
+ }
281
+ return { contents: js, loader: "js" };
282
+ });
283
+
284
+ build.onResolve({ filter: SVELTE_CSS }, (args) => ({
285
+ path: join(dirname(args.importer), args.path),
286
+ }));
287
+ build.onLoad({ filter: SVELTE_CSS }, (args) => {
288
+ const entry = stylesheets.get(args.path);
289
+ if (!entry) {
290
+ throw new SvelteBunError(
291
+ "SB_INTERNAL",
292
+ `svelte-bun: no CSS was compiled for ${args.path}`,
293
+ );
294
+ }
295
+ return { contents: entry.css, loader: "css", watchFiles: [entry.from] };
296
+ });
297
+
298
+ if (production) {
299
+ const browser = (options.side ?? "client") === "client";
300
+ build.onLoad({ filter: SVELTE_RUNTIME }, async (args) => ({
301
+ contents: inlineEsmEnv(await Bun.file(args.path).text(), {
302
+ dev: false,
303
+ browser,
304
+ }),
305
+ loader: "js",
306
+ }));
307
+ }
308
+ },
309
+ };
310
+ }
311
+
312
+ const plugin: BunPlugin = svelte();
313
+
314
+ // eslint-disable-next-line import/no-default-export -- bunfig's [serve.static] plugins loads a module's default export, and passes no options
315
+ export { plugin as default };
@@ -0,0 +1,5 @@
1
+ // bunfig.toml: preload = ["svelte-bun/register"]
2
+
3
+ import { svelte } from "./index.ts";
4
+
5
+ await Bun.plugin(svelte());
package/src/resolve.ts ADDED
@@ -0,0 +1,56 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+
4
+ /** `undefined` where no package is installed. */
5
+ export type ExportsCache = Map<string, object | undefined>;
6
+
7
+ function readExports(root: string): object | undefined {
8
+ const manifest = join(root, "package.json");
9
+ if (!existsSync(manifest)) return undefined;
10
+ const parsed: unknown = JSON.parse(readFileSync(manifest, "utf8"));
11
+ if (typeof parsed !== "object" || parsed === null) return {};
12
+ const exports = "exports" in parsed ? parsed.exports : undefined;
13
+ return typeof exports === "object" && exports !== null ? exports : {};
14
+ }
15
+
16
+ function conditionEntry(
17
+ exports: object,
18
+ subpath: string,
19
+ conditions: readonly string[],
20
+ ): string | undefined {
21
+ const entry: unknown = Object.entries(exports).find(
22
+ ([key]) => key === subpath,
23
+ )?.[1];
24
+ if (typeof entry !== "object" || entry === null) return undefined;
25
+ const targets = new Map(Object.entries(entry));
26
+ for (const condition of conditions) {
27
+ const target: unknown = targets.get(condition);
28
+ if (typeof target === "string") return target;
29
+ }
30
+ return undefined;
31
+ }
32
+
33
+ // Bun's dev server ignores a plugin's conditions, and its runtime takes
34
+ // them only from --conditions, so the plugin resolves them itself.
35
+ export function resolveCondition(
36
+ specifier: string,
37
+ importer: string,
38
+ conditions: readonly string[],
39
+ cache: ExportsCache,
40
+ ): string | undefined {
41
+ const parts = specifier.split("/");
42
+ const name = specifier.startsWith("@")
43
+ ? parts.slice(0, 2).join("/")
44
+ : (parts[0] ?? specifier);
45
+ const subpath = `.${specifier.slice(name.length)}`;
46
+ for (let dir = dirname(importer); ; dir = dirname(dir)) {
47
+ const root = join(dir, "node_modules", name);
48
+ if (!cache.has(root)) cache.set(root, readExports(root));
49
+ const exports = cache.get(root);
50
+ if (exports !== undefined) {
51
+ const target = conditionEntry(exports, subpath, conditions);
52
+ return target === undefined ? undefined : join(root, target);
53
+ }
54
+ if (dir === dirname(dir)) return undefined;
55
+ }
56
+ }
package/src/scan.ts ADDED
@@ -0,0 +1,19 @@
1
+ /** Code a Svelte file's imports are in, and its loader. */
2
+ export type ScanPart = { code: string; loader: "js" | "ts" };
3
+
4
+ const SCRIPT = /<script\b([^>]*)>([\s\S]*?)<\/script>/g;
5
+ const TS_LANG = /\blang=["']ts["']/;
6
+
7
+ /** Finds the code a Svelte file's imports are in, without compiling it. */
8
+ export function scanImports(source: string, path: string): ScanPart[] {
9
+ if (!path.endsWith(".svelte")) {
10
+ return [{ code: source, loader: path.endsWith(".ts") ? "ts" : "js" }];
11
+ }
12
+ const parts: ScanPart[] = [...source.matchAll(SCRIPT)].map((match) => ({
13
+ code: match[2] ?? "",
14
+ loader: TS_LANG.test(match[1] ?? "") ? "ts" : "js",
15
+ }));
16
+ // A compiled component imports Svelte's runtime too.
17
+ parts.push({ code: 'import "svelte/internal/client";', loader: "js" });
18
+ return parts;
19
+ }