@ogygia/tsdown-plugin-svelte 0.0.0-stage → 1.0.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 Puru Vijayvargia
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,128 @@
1
- # Temporary Holding Version
1
+ # @ogygia/tsdown-plugin-svelte
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
+ [![npm](https://img.shields.io/npm/v/@ogygia/tsdown-plugin-svelte)](https://www.npmjs.com/package/@ogygia/tsdown-plugin-svelte)
4
+ [![license](https://img.shields.io/npm/l/@ogygia/tsdown-plugin-svelte)](./LICENSE)
5
+
6
+ Ship Svelte components from a [tsdown](https://tsdown.dev) build.
7
+
8
+ Keep one build for your whole library. Your `.ts` goes through tsdown as usual, and your `.svelte` components ship next to it, the way `svelte-package` ships them, with no second build step.
9
+
10
+ ```
11
+ src/ dist/
12
+ ├─ index.ts → ├─ index.mjs + index.d.mts (tsdown)
13
+ ├─ Button.svelte → ├─ Button.svelte (plain JS, uncompiled)
14
+ │ ├─ Button.svelte.d.ts (typed props)
15
+ └─ theme.css → └─ theme.css (copied)
16
+ ```
17
+
18
+ ## Why
19
+
20
+ - **Components ship uncompiled.** Each `.svelte` file lands in `dist` at the same path, as source. Your users' own Svelte compiles it, so your library never pins them to the Svelte version you built with.
21
+ - **Write TypeScript everywhere, ship plain JS.** TypeScript is removed from the `<script>` and from the template: `{item as Row}`, `{user!.name}` and `{#snippet row(item: Row)}` are all fine. What ships needs no TypeScript setup on the user's side.
22
+ - **Typed props.** A `.svelte.d.ts` is generated beside every component, with svelte2tsx, the same engine `svelte-package` uses.
23
+ - **Safe stripping.** Types are found with Svelte's own parser, not with patterns, so a string or comment that merely looks like a type is never touched.
24
+ - **Styles come along.** Plain `.css` files under `src` are copied as they are.
25
+
26
+ ## Install
27
+
28
+ ```sh
29
+ pnpm add -D @ogygia/tsdown-plugin-svelte
30
+ ```
31
+
32
+ It needs `tsdown` (0.15 or newer) and `svelte` 5. For the defaults, also install:
33
+
34
+ ```sh
35
+ pnpm add -D svelte2tsx typescript @sveltejs/vite-plugin-svelte
36
+ ```
37
+
38
+ - `svelte2tsx` and `typescript` generate the `.svelte.d.ts` types. Skip them with `dts: false`.
39
+ - `@sveltejs/vite-plugin-svelte` provides the default preprocessor. Skip it by passing your own `preprocess`.
40
+
41
+ ## Usage
42
+
43
+ ```ts
44
+ // tsdown.config.ts
45
+ import { defineConfig } from 'tsdown';
46
+ import { svelte } from '@ogygia/tsdown-plugin-svelte';
47
+
48
+ export default defineConfig({
49
+ entry: ['src/**/*.ts'],
50
+ unbundle: true,
51
+ dts: true,
52
+ plugins: [svelte()],
53
+ // the shipped components stay as files: never bundle them, or Svelte, into your JS
54
+ deps: { neverBundle: ['svelte', /\.svelte$/] }
55
+ });
56
+ ```
57
+
58
+ `unbundle: true` keeps one output file per source file, so `import Button from './Button.svelte'` in your `.ts` still points at the shipped component.
59
+
60
+ Then expose the components to Svelte-aware tools with the `svelte` export condition:
61
+
62
+ ```jsonc
63
+ // package.json
64
+ {
65
+ "type": "module",
66
+ "exports": {
67
+ ".": {
68
+ "types": "./dist/index.d.mts",
69
+ "svelte": "./dist/index.mjs",
70
+ "default": "./dist/index.mjs"
71
+ },
72
+ "./Button.svelte": {
73
+ "types": "./dist/Button.svelte.d.ts",
74
+ "svelte": "./dist/Button.svelte"
75
+ }
76
+ },
77
+ "files": ["dist"]
78
+ }
79
+ ```
80
+
81
+ ## Options
82
+
83
+ ```ts
84
+ svelte({
85
+ root: process.cwd(),
86
+ src: 'src',
87
+ out: 'dist',
88
+ preprocess: vitePreprocess({ script: true }),
89
+ dts: true
90
+ });
91
+ ```
92
+
93
+ | Option | Default | What it does |
94
+ | ------------ | ---------------------------------- | --------------------------------------------------------------- |
95
+ | `root` | `process.cwd()` | The package root that `src` and `out` are relative to. |
96
+ | `src` | `'src'` | Where your components and `.css` files live. |
97
+ | `out` | `'dist'` | Where they are written. Match tsdown's `outDir`. |
98
+ | `preprocess` | `vitePreprocess({ script: true })` | Svelte preprocessors for the script and styles (one or a list). |
99
+ | `dts` | `true` | Write a `.svelte.d.ts` beside each component. |
100
+
101
+ In a monorepo, set `root` to the package's own folder when tsdown runs from somewhere else:
102
+
103
+ ```ts
104
+ svelte({ root: fileURLToPath(new URL('.', import.meta.url)) });
105
+ ```
106
+
107
+ ## How it works
108
+
109
+ 1. At the start of the build, every `.svelte` under `src` is run through your preprocessors, which turns its `<script lang="ts">` into JS.
110
+ 2. Svelte's parser then reads the file once more, still as TypeScript, and every type-only span in the template is cut out: `as` and `satisfies` casts, `!` assertions, annotations and generic arguments. `lang="ts"` is removed from each script.
111
+ 3. The result is emitted as a build asset at the same path in `out`. Emitting assets, rather than writing files, means tsdown's `clean` never wipes them.
112
+ 4. After the bundle is written, svelte2tsx generates declarations into a scratch folder, and only the `*.svelte.d.ts` files are copied next to the components. tsdown keeps owning the declarations for your `.ts` files.
113
+
114
+ ## Using the TypeScript strip on its own
115
+
116
+ `strip_markup_ts` is exported for tools that ship Svelte source another way. Run it on the output of `preprocess()`, when the script is JS but the template still has types:
117
+
118
+ ```ts
119
+ import { preprocess } from 'svelte/compiler';
120
+ import { strip_markup_ts } from '@ogygia/tsdown-plugin-svelte';
121
+
122
+ const { code } = await preprocess(source, preprocessors, { filename });
123
+ const plain_js = strip_markup_ts(code, filename);
124
+ ```
125
+
126
+ ## License
127
+
128
+ [MIT](./LICENSE)
@@ -0,0 +1,31 @@
1
+ import { PreprocessorGroup } from "svelte/compiler";
2
+ //#region src/strip-ts.d.ts
3
+ declare function strip_markup_ts(source: string, filename?: string): string;
4
+ //#endregion
5
+ //#region src/index.d.ts
6
+ interface SvelteOptions {
7
+ /** the package root the other paths are relative to (default: the working directory) */
8
+ root?: string;
9
+ /** the source dir holding the components (default: `src`) */
10
+ src?: string;
11
+ /** the output dir, tsdown's `outDir` (default: `dist`) */
12
+ out?: string;
13
+ /** preprocessors for the script and style (default: vite-plugin-svelte's `vitePreprocess({ script: true })`) */
14
+ preprocess?: PreprocessorGroup | PreprocessorGroup[];
15
+ /** generate `.svelte.d.ts` beside each component (default: true; needs `svelte2tsx` and `typescript`) */
16
+ dts?: boolean;
17
+ }
18
+ interface EmitContext {
19
+ emitFile(file: {
20
+ type: 'asset';
21
+ fileName: string;
22
+ source: string | Uint8Array;
23
+ }): string;
24
+ }
25
+ declare function svelte(options?: SvelteOptions): {
26
+ name: string;
27
+ buildStart(this: EmitContext): Promise<void>;
28
+ writeBundle(): Promise<void>;
29
+ };
30
+ //#endregion
31
+ export { SvelteOptions, svelte as default, svelte, strip_markup_ts };
package/dist/index.mjs ADDED
@@ -0,0 +1,166 @@
1
+ import { cpSync, existsSync, globSync, mkdirSync, readFileSync, rmSync } from "node:fs";
2
+ import { dirname, join, relative, resolve } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import { parse, preprocess } from "svelte/compiler";
5
+ import MagicString from "magic-string";
6
+ //#region src/strip-ts.ts
7
+ /**
8
+ * Turn a TypeScript Svelte component into a plain-JS one, for shipping raw.
9
+ *
10
+ * `preprocess()` transpiles the `<script>`, but never the template: a `{x as Y}`, `{a!.b}` or
11
+ * `{#snippet row(l: Line)}` survives it, and once `lang="ts"` is gone the consumer's compiler reads
12
+ * it as broken JS. `strip_markup_ts` takes Svelte's own parse of the file (which reads the template
13
+ * as TS while `lang="ts"` is still on the script) and cuts every type-only span out of the
14
+ * template's expressions: `as` / `satisfies` casts, `!` assertions, annotations, generic
15
+ * arguments. Only type-only syntax exists in a Svelte template, so the cuts leave exactly the JS.
16
+ * It also drops the `lang="ts"` attribute from each script, by the parse, not by pattern.
17
+ *
18
+ * Run it on the output of `preprocess()`: the script is JS by then and the markup still TS.
19
+ */
20
+ const is_node = (v) => !!v && typeof v === "object" && typeof v.start === "number" && typeof v.end === "number";
21
+ /** keys that hold a type, never a value: cut the whole span and do not look inside */
22
+ const TYPE_KEYS = /* @__PURE__ */ new Set([
23
+ "typeAnnotation",
24
+ "typeArguments",
25
+ "typeParameters",
26
+ "returnType"
27
+ ]);
28
+ /** the static text of an attribute value (`lang="ts"` → `ts`), or undefined */
29
+ function attr_text(a) {
30
+ const v = a.value;
31
+ if (!Array.isArray(v) || v.length !== 1) return void 0;
32
+ const t = v[0];
33
+ return t.type === "Text" ? t.data : void 0;
34
+ }
35
+ /** true when the source has a `<script lang="ts">`: a cheap check before paying for a parse */
36
+ const has_ts_script = (source) => source.includes("lang=\"ts\"") || source.includes("lang='ts'");
37
+ function strip_markup_ts(source, filename) {
38
+ if (!has_ts_script(source)) return source;
39
+ const ast = parse(source, {
40
+ modern: true,
41
+ filename
42
+ });
43
+ const s = new MagicString(source);
44
+ const seen = /* @__PURE__ */ new Set();
45
+ const visit = (v) => {
46
+ if (!v || typeof v !== "object" || seen.has(v)) return;
47
+ seen.add(v);
48
+ if (Array.isArray(v)) {
49
+ for (const x of v) visit(x);
50
+ return;
51
+ }
52
+ const n = v;
53
+ if (n.type === "TSAsExpression" || n.type === "TSSatisfiesExpression" || n.type === "TSNonNullExpression") {
54
+ const inner = n.expression;
55
+ if (inner.end < n.end) s.remove(inner.end, n.end);
56
+ visit(inner);
57
+ return;
58
+ }
59
+ if (n.type === "TSTypeAssertion") {
60
+ const inner = n.expression;
61
+ if (n.start < inner.start) s.remove(n.start, inner.start);
62
+ visit(inner);
63
+ return;
64
+ }
65
+ for (const k in n) {
66
+ if (k === "parent" || k === "metadata") continue;
67
+ const c = n[k];
68
+ if (TYPE_KEYS.has(k)) {
69
+ if (is_node(c) && c.start < c.end) s.remove(c.start, c.end);
70
+ continue;
71
+ }
72
+ visit(c);
73
+ }
74
+ };
75
+ visit(ast.fragment);
76
+ for (const script of [ast.instance, ast.module]) for (const a of script?.attributes ?? []) {
77
+ if (a.name !== "lang" || attr_text(a) !== "ts") continue;
78
+ let from = a.start;
79
+ while (from > 0 && (source[from - 1] === " " || source[from - 1] === " " || source[from - 1] === "\n")) from--;
80
+ s.remove(from, a.end);
81
+ }
82
+ return s.hasChanged() ? s.toString() : source;
83
+ }
84
+ //#endregion
85
+ //#region src/index.ts
86
+ /**
87
+ * A tsdown plugin that ships a library's Svelte components the way svelte-package does, inside a
88
+ * normal tsdown build:
89
+ *
90
+ * - every `.svelte` under `src` is preprocessed (its script's TS transpiled), its markup's TS cut
91
+ * (`strip_markup_ts`) and `lang="ts"` dropped, then emitted into the output dir at the same
92
+ * path as a raw, plain-JS component. It is NOT compiled: the consumer's own Svelte compiles it,
93
+ * so the library never bakes in a Svelte version. Templates may use TypeScript freely.
94
+ * - standalone `.css` files are copied as they are.
95
+ * - `.svelte.d.ts` types are generated beside each component with svelte2tsx (the engine
96
+ * svelte-package uses). tsdown stays in charge of the `.ts` declarations.
97
+ *
98
+ * Assets are emitted in `buildStart` and types copied in `writeBundle`, so tsdown's `clean` never
99
+ * wipes them.
100
+ */
101
+ /** the path of `abs` inside `dir`, with forward slashes */
102
+ const rel_to = (dir, abs) => relative(dir, abs).split("\\").join("/");
103
+ async function default_preprocess() {
104
+ try {
105
+ const { vitePreprocess } = await import("@sveltejs/vite-plugin-svelte");
106
+ return vitePreprocess({ script: true });
107
+ } catch {
108
+ throw new Error("@ogygia/tsdown-plugin-svelte: pass `preprocess`, or install @sveltejs/vite-plugin-svelte for the default");
109
+ }
110
+ }
111
+ function svelte(options = {}) {
112
+ const root = resolve(options.root ?? process.cwd());
113
+ const src = resolve(root, options.src ?? "src");
114
+ const out = resolve(root, options.out ?? "dist");
115
+ return {
116
+ name: "@ogygia/tsdown-plugin-svelte",
117
+ async buildStart() {
118
+ const pre = options.preprocess ?? await default_preprocess();
119
+ for (const file of globSync("**/*.{svelte,css}", { cwd: src })) {
120
+ const abs = join(src, file);
121
+ const fileName = rel_to(src, abs);
122
+ let source = readFileSync(abs, "utf8");
123
+ if (abs.endsWith(".svelte")) {
124
+ ({code: source} = await preprocess(source, pre, { filename: abs }));
125
+ source = strip_markup_ts(source, abs);
126
+ }
127
+ this.emitFile({
128
+ type: "asset",
129
+ fileName,
130
+ source
131
+ });
132
+ }
133
+ },
134
+ async writeBundle() {
135
+ if (options.dts === false) return;
136
+ const { emitDts } = await import("svelte2tsx");
137
+ const tmp = join(root, ".svelte-dts");
138
+ rmSync(tmp, {
139
+ recursive: true,
140
+ force: true
141
+ });
142
+ try {
143
+ await emitDts({
144
+ libRoot: src,
145
+ declarationDir: tmp,
146
+ svelteShimsPath: fileURLToPath(import.meta.resolve("svelte2tsx/svelte-shims-v4.d.ts"))
147
+ });
148
+ for (const file of globSync("**/*.svelte", { cwd: src })) {
149
+ const rel = rel_to(src, join(src, file)) + ".d.ts";
150
+ const from = join(tmp, rel);
151
+ if (!existsSync(from)) continue;
152
+ const to = join(out, rel);
153
+ mkdirSync(dirname(to), { recursive: true });
154
+ cpSync(from, to);
155
+ }
156
+ } finally {
157
+ rmSync(tmp, {
158
+ recursive: true,
159
+ force: true
160
+ });
161
+ }
162
+ }
163
+ };
164
+ }
165
+ //#endregion
166
+ export { svelte as default, svelte, strip_markup_ts };
package/package.json CHANGED
@@ -1,6 +1,68 @@
1
1
  {
2
2
  "name": "@ogygia/tsdown-plugin-svelte",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "1.0.0",
4
+ "description": "Ship Svelte components from a tsdown build: preprocessed, TypeScript-free markup, with .svelte.d.ts types",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "author": "Puru Vijayvargia <devpuruvj@gmail.com>",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/PuruVJ/ogygia.git",
11
+ "directory": "packages/tsdown-plugin-svelte"
12
+ },
13
+ "keywords": [
14
+ "tsdown",
15
+ "rolldown",
16
+ "svelte",
17
+ "plugin",
18
+ "library"
19
+ ],
20
+ "exports": {
21
+ ".": {
22
+ "types": "./dist/index.d.mts",
23
+ "default": "./dist/index.mjs"
24
+ }
25
+ },
26
+ "files": [
27
+ "dist",
28
+ "README.md",
29
+ "LICENSE"
30
+ ],
31
+ "dependencies": {
32
+ "magic-string": "^1.1.0"
33
+ },
34
+ "peerDependencies": {
35
+ "@sveltejs/vite-plugin-svelte": ">=5.0.0",
36
+ "svelte": "^5.40.0",
37
+ "svelte2tsx": ">=0.7.0",
38
+ "tsdown": ">=0.15.0",
39
+ "typescript": ">=5.0.0"
40
+ },
41
+ "peerDependenciesMeta": {
42
+ "@sveltejs/vite-plugin-svelte": {
43
+ "optional": true
44
+ },
45
+ "svelte2tsx": {
46
+ "optional": true
47
+ },
48
+ "typescript": {
49
+ "optional": true
50
+ }
51
+ },
52
+ "devDependencies": {
53
+ "@sveltejs/vite-plugin-svelte": "^7.2.0",
54
+ "@types/node": "^26.1.2",
55
+ "svelte": "^5.40.0",
56
+ "svelte2tsx": "^0.7.60",
57
+ "tsdown": "^0.22.14",
58
+ "typescript": "^6.0.3",
59
+ "vitest": "^4.1.10"
60
+ },
61
+ "publishConfig": {
62
+ "access": "public"
63
+ },
64
+ "scripts": {
65
+ "build": "tsdown",
66
+ "test": "vitest run"
67
+ }
6
68
  }