@ogygia/tsdown-plugin-svelte 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 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,59 @@
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
+ Ship Svelte components from a [tsdown](https://tsdown.dev) build, the way `svelte-package` does, without giving up tsdown for the rest of your library.
4
+
5
+ - Every `.svelte` file in `src` is copied to `dist` at the same path, **not compiled**. Your users' own Svelte compiles it, so your library never locks in a Svelte version.
6
+ - TypeScript is removed from the script **and the template**. Write `{x as Item}`, `{a!.b}` or `{#snippet row(item: Item)}` freely. What ships is plain JS, so users need no TypeScript setup.
7
+ - A `.svelte.d.ts` is generated next to each component, so users get typed props.
8
+ - Plain `.css` files in `src` are copied too.
9
+
10
+ ## Install
11
+
12
+ ```sh
13
+ pnpm add -D @ogygia/tsdown-plugin-svelte svelte2tsx typescript @sveltejs/vite-plugin-svelte
14
+ ```
15
+
16
+ `svelte2tsx` and `typescript` are only needed for types. `@sveltejs/vite-plugin-svelte` is only needed for the default preprocessor.
17
+
18
+ ## Use
19
+
20
+ ```ts
21
+ // tsdown.config.ts
22
+ import { defineConfig } from 'tsdown';
23
+ import { svelte } from '@ogygia/tsdown-plugin-svelte';
24
+
25
+ export default defineConfig({
26
+ entry: ['src/**/*.ts'],
27
+ unbundle: true,
28
+ dts: true,
29
+ plugins: [svelte()],
30
+ // keep the shipped components external
31
+ deps: { neverBundle: ['svelte', /\.svelte$/] }
32
+ });
33
+ ```
34
+
35
+ ## Options
36
+
37
+ | option | default | what it does |
38
+ | ------------ | --------------------------------- | ---------------------------------------------------- |
39
+ | `root` | `process.cwd()` | the package root the other paths start from |
40
+ | `src` | `'src'` | where the components live |
41
+ | `out` | `'dist'` | where they go (match tsdown's `outDir`) |
42
+ | `preprocess` | `vitePreprocess({ script: true })` | preprocessors for script and style |
43
+ | `dts` | `true` | write a `.svelte.d.ts` next to each component |
44
+
45
+ ## Just the TypeScript strip
46
+
47
+ ```ts
48
+ import { preprocess } from 'svelte/compiler';
49
+ import { strip_markup_ts } from '@ogygia/tsdown-plugin-svelte';
50
+
51
+ const { code } = await preprocess(source, preprocessors, { filename });
52
+ const plain_js = strip_markup_ts(code, filename);
53
+ ```
54
+
55
+ It uses Svelte's own parser, so it only ever removes type syntax, never a look-alike in a string or comment.
56
+
57
+ ## License
58
+
59
+ MIT
@@ -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": "0.1.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
  }