svelte-sharp 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/README.md CHANGED
@@ -1,3 +1,214 @@
1
- # Temporary Holding Version
1
+ # SvelteSharp
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
+ **Write C#. Build with Svelte.**
4
+
5
+ SvelteSharp is an experimental C# component authoring toolkit for SvelteKit and Svelte 5.
6
+
7
+ It allows developers to write component logic in familiar C# syntax while using Svelte for rendering, reactivity and DOM updates.
8
+
9
+ The goal is to bring the C# and Blazor developer experience into the Svelte ecosystem without requiring developers to write their component logic in JavaScript or TypeScript.
10
+
11
+ ## Features
12
+
13
+ - Write component logic in C#.
14
+ - Keep markup in native `.svelte` files.
15
+ - Automatic reactive state generation using Svelte 5 `$state`.
16
+ - Computed properties using `$derived`.
17
+ - C# methods translated into JavaScript functions.
18
+ - Native Svelte two-way binding.
19
+ - Component parameters.
20
+ - Independent state for multiple component instances.
21
+ - Vite development integration.
22
+ - Local C# compiler execution.
23
+
24
+ ## Requirements
25
+
26
+ - Node.js
27
+ - npm
28
+ - Svelte 5
29
+ - SvelteKit
30
+ - Vite 6 or newer
31
+ - Windows x64 (current compiler distribution)
32
+
33
+ **Note:** The current compiler is distributed as a self-contained executable, so users do not need to install .NET separately.
34
+
35
+ ## Installation
36
+
37
+ Install SvelteSharp in your SvelteKit project:
38
+
39
+ ```bash
40
+ npm install svelte-sharp
41
+ ```
42
+
43
+ ## Configuration
44
+
45
+ Add SvelteSharp to your `vite.config.ts`:
46
+
47
+ ```typescript
48
+ import adapter from '@sveltejs/adapter-auto';
49
+ import { sveltekit } from '@sveltejs/kit/vite';
50
+ import { defineConfig } from 'vite';
51
+
52
+ import {
53
+ svelteSharp,
54
+ svelteSharpPreprocessor
55
+ } from 'svelte-sharp';
56
+
57
+ export default defineConfig({
58
+ plugins: [
59
+ svelteSharp(),
60
+
61
+ sveltekit({
62
+ adapter: adapter(),
63
+ preprocess: [
64
+ svelteSharpPreprocessor()
65
+ ]
66
+ })
67
+ ]
68
+ });
69
+ ```
70
+
71
+ ## Your First C# Component
72
+
73
+ Create two files next to each other.
74
+
75
+ ### 1. Counter.svelte.cs
76
+
77
+ Write your component logic in C#:
78
+
79
+ ```csharp
80
+ public partial class Counter
81
+ {
82
+ private int count = 0;
83
+
84
+ private string Message =>
85
+ $"You clicked {count} times";
86
+
87
+ private void Increment()
88
+ {
89
+ count++;
90
+ }
91
+
92
+ private void Decrement()
93
+ {
94
+ count--;
95
+ }
96
+ }
97
+ ```
98
+
99
+ ### 2. Counter.svelte
100
+
101
+ Write your component markup using native Svelte syntax:
102
+
103
+ ```svelte
104
+ <div class="counter">
105
+ <h2>My C# Counter</h2>
106
+
107
+ <h3>Count: {count}</h3>
108
+
109
+ <p>{Message}</p>
110
+
111
+ <button onclick={Increment}>+</button>
112
+ <button onclick={Decrement}>-</button>
113
+ </div>
114
+ ```
115
+
116
+ ### 3. Use Your Component
117
+
118
+ Import it into your SvelteKit page:
119
+
120
+ ```svelte
121
+ <script lang="ts">
122
+ import Counter from '$lib/Counter.svelte';
123
+ </script>
124
+
125
+ <h1>Welcome to SvelteSharp</h1>
126
+
127
+ <Counter />
128
+ ```
129
+
130
+ ### 4. Run the Application
131
+
132
+ ```bash
133
+ npm run dev
134
+ ```
135
+
136
+ Your C# component logic is translated into Svelte-compatible JavaScript during compilation.
137
+
138
+ ## Two-Way Binding
139
+
140
+ SvelteSharp uses Svelte's native binding system.
141
+
142
+ **Counter.svelte.cs**
143
+
144
+ ```csharp
145
+ public partial class Counter
146
+ {
147
+ private string Name = "Ahsan";
148
+ }
149
+ ```
150
+
151
+ **Counter.svelte**
152
+
153
+ ```svelte
154
+ <input bind:value={Name} />
155
+
156
+ <p>Hello {Name}</p>
157
+ ```
158
+
159
+ You don't need to write a separate input event handler. Svelte handles the binding and reactive updates.
160
+
161
+ ## How It Works
162
+
163
+ ```text
164
+ .svelte.cs
165
+ |
166
+ v
167
+ SvelteSharp C# Compiler
168
+ |
169
+ v
170
+ Generated Svelte-compatible JavaScript
171
+ |
172
+ v
173
+ Svelte 5 Compiler
174
+ |
175
+ v
176
+ Browser
177
+ ```
178
+
179
+ SvelteSharp translates C# component logic, while Svelte handles rendering, reactivity and DOM updates.
180
+
181
+ ## Current Limitations
182
+
183
+ SvelteSharp is an experimental project and does not support the complete C# language or the entire .NET platform.
184
+
185
+ Current limitations include:
186
+
187
+ - Limited C# language support.
188
+ - Windows x64 compiler distribution only.
189
+ - Not a replacement for the .NET runtime.
190
+ - Not a drop-in replacement for Blazor.
191
+ - Some advanced C# and Blazor features are not implemented.
192
+
193
+ ## Roadmap
194
+
195
+ - [ ] Simplified project initialization.
196
+ - [ ] Better compiler diagnostics.
197
+ - [ ] Improved compilation caching.
198
+ - [ ] More C# language features.
199
+ - [ ] Component lifecycle integration.
200
+ - [ ] Dependency injection.
201
+ - [ ] Component communication.
202
+ - [ ] Improved Blazor and Razor compatibility.
203
+ - [ ] Blazor migration tooling.
204
+ - [ ] Linux and macOS support.
205
+
206
+ ## Source Code
207
+
208
+ GitHub: https://github.com/theahsanbuilds/svelte-sharp
209
+
210
+ Bug reports, suggestions and contributions are welcome.
211
+
212
+ ## License
213
+
214
+ MIT License (subject to the license included with the package).
@@ -0,0 +1,4 @@
1
+ [diffend] Oversized file quarantined before diffing.
2
+ name: package/compiler/win-x64/SvelteSharp.Compiler.exe
3
+ size: 87556616 bytes
4
+ sha256: 3b025de7d57f1129e675b5f15ef31b613186de1639420c754d3320c796afa9fb
@@ -0,0 +1,2 @@
1
+ import type { SvelteSharpOptions } from './types.js';
2
+ export declare function compileComponent(filename: string, options?: SvelteSharpOptions): Promise<string>;
@@ -0,0 +1,87 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { createHash } from 'node:crypto';
3
+ import { mkdir, readFile, stat, writeFile } from 'node:fs/promises';
4
+ import { dirname, resolve } from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+ const packageDirectory = resolve(dirname(fileURLToPath(import.meta.url)), '..');
7
+ function getCompilerPath(options) {
8
+ if (options.compilerPath) {
9
+ return resolve(options.compilerPath);
10
+ }
11
+ if (process.platform !== 'win32' || process.arch !== 'x64') {
12
+ throw new Error(`SvelteSharp currently supports Windows x64 only. ` +
13
+ `Your platform is ${process.platform}-${process.arch}.`);
14
+ }
15
+ return resolve(packageDirectory, 'compiler', 'win-x64', 'SvelteSharp.Compiler.exe');
16
+ }
17
+ function createCacheKey(filename, componentCode, csharpCode, compilerModified, compilerSize) {
18
+ return createHash('sha256')
19
+ .update(filename)
20
+ .update(componentCode)
21
+ .update(csharpCode)
22
+ .update(String(compilerModified))
23
+ .update(String(compilerSize))
24
+ .digest('hex');
25
+ }
26
+ export async function compileComponent(filename, options = {}) {
27
+ const absoluteFilename = resolve(filename);
28
+ const csharpFilename = `${absoluteFilename}.cs`;
29
+ const compilerPath = getCompilerPath(options);
30
+ // Read both component files.
31
+ const componentCode = await readFile(absoluteFilename, 'utf8');
32
+ const csharpCode = await readFile(csharpFilename, 'utf8');
33
+ // Check compiler information.
34
+ let compilerInfo;
35
+ try {
36
+ compilerInfo = await stat(compilerPath);
37
+ }
38
+ catch {
39
+ throw new Error(`SvelteSharp compiler was not found: ${compilerPath}\n` +
40
+ `Build the compiler using: npm run compiler:build`);
41
+ }
42
+ // Generate a cache key.
43
+ const cacheKey = createCacheKey(absoluteFilename, componentCode, csharpCode, compilerInfo.mtimeMs, compilerInfo.size);
44
+ // Store cache inside the consuming project's node_modules.
45
+ const cacheDirectory = resolve(process.cwd(), 'node_modules', '.cache', 'svelte-sharp');
46
+ const cacheFile = resolve(cacheDirectory, `${cacheKey}.svelte`);
47
+ // Return cached output if it exists.
48
+ try {
49
+ return await readFile(cacheFile, 'utf8');
50
+ }
51
+ catch {
52
+ // Cache does not exist. Compile the component.
53
+ }
54
+ // Execute the compiler only when necessary.
55
+ const generatedCode = await new Promise((resolvePromise, reject) => {
56
+ const child = spawn(compilerPath, [absoluteFilename], {
57
+ cwd: process.cwd(),
58
+ stdio: ['ignore', 'pipe', 'pipe']
59
+ });
60
+ let stdout = '';
61
+ let stderr = '';
62
+ child.stdout.setEncoding('utf8');
63
+ child.stderr.setEncoding('utf8');
64
+ child.stdout.on('data', chunk => {
65
+ stdout += chunk;
66
+ });
67
+ child.stderr.on('data', chunk => {
68
+ stderr += chunk;
69
+ });
70
+ child.on('error', error => {
71
+ reject(new Error(`Could not start SvelteSharp compiler: ${error.message}`));
72
+ });
73
+ child.on('close', code => {
74
+ if (code === 0) {
75
+ resolvePromise(stdout);
76
+ }
77
+ else {
78
+ reject(new Error(stderr.trim() ||
79
+ `SvelteSharp compiler exited with code ${code}`));
80
+ }
81
+ });
82
+ });
83
+ // Save successful output in the cache.
84
+ await mkdir(cacheDirectory, { recursive: true });
85
+ await writeFile(cacheFile, generatedCode, 'utf8');
86
+ return generatedCode;
87
+ }
@@ -0,0 +1,3 @@
1
+ export { svelteSharp } from './vite-plugin.js';
2
+ export { svelteSharpPreprocessor } from './preprocessor.js';
3
+ export type { SvelteSharpOptions } from './types.js';
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export { svelteSharp } from './vite-plugin.js';
2
+ export { svelteSharpPreprocessor } from './preprocessor.js';
@@ -0,0 +1,3 @@
1
+ import type { PreprocessorGroup } from 'svelte/compiler';
2
+ import type { SvelteSharpOptions } from './types.js';
3
+ export declare function svelteSharpPreprocessor(options?: SvelteSharpOptions): PreprocessorGroup;
@@ -0,0 +1,35 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { compileComponent } from './compiler-runner.js';
3
+ import { registerCsharpDependency } from './watcher.js';
4
+ export function svelteSharpPreprocessor(options = {}) {
5
+ return {
6
+ name: 'svelte-sharp-preprocessor',
7
+ async markup({ filename }) {
8
+ if (!filename?.endsWith('.svelte')) {
9
+ return;
10
+ }
11
+ if (filename.includes('/.svelte-kit/') ||
12
+ filename.includes('\\.svelte-kit\\')) {
13
+ return;
14
+ }
15
+ const csharpFile = `${filename}.cs`;
16
+ if (!existsSync(csharpFile)) {
17
+ return;
18
+ }
19
+ registerCsharpDependency(csharpFile);
20
+ try {
21
+ const code = await compileComponent(filename, options);
22
+ return {
23
+ code,
24
+ dependencies: [csharpFile]
25
+ };
26
+ }
27
+ catch (error) {
28
+ const message = error instanceof Error
29
+ ? error.message
30
+ : String(error);
31
+ throw new Error(`SvelteSharp failed in ${filename}:\n${message}`);
32
+ }
33
+ }
34
+ };
35
+ }
@@ -0,0 +1,4 @@
1
+ export interface SvelteSharpOptions {
2
+ compilerPath?: string;
3
+ dotnetCommand?: string;
4
+ }
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,3 @@
1
+ import type { Plugin } from 'vite';
2
+ import type { SvelteSharpOptions } from './types.js';
3
+ export declare function svelteSharp(_options?: SvelteSharpOptions): Plugin;
@@ -0,0 +1,26 @@
1
+ import { resolve } from 'node:path';
2
+ import { normalizePath } from 'vite';
3
+ import { setViteServer } from './watcher.js';
4
+ export function svelteSharp(_options = {}) {
5
+ return {
6
+ name: 'svelte-sharp',
7
+ enforce: 'pre',
8
+ configureServer(server) {
9
+ setViteServer(server);
10
+ },
11
+ handleHotUpdate({ file, server }) {
12
+ if (!file.endsWith('.svelte.cs')) {
13
+ return;
14
+ }
15
+ const svelteFile = normalizePath(resolve(file.slice(0, -3)));
16
+ const modules = server.moduleGraph.getModulesByFile(svelteFile);
17
+ if (!modules || modules.size === 0) {
18
+ return;
19
+ }
20
+ for (const module of modules) {
21
+ server.moduleGraph.invalidateModule(module);
22
+ }
23
+ return [...modules];
24
+ }
25
+ };
26
+ }
@@ -0,0 +1,3 @@
1
+ import type { ViteDevServer } from 'vite';
2
+ export declare function setViteServer(server: ViteDevServer): void;
3
+ export declare function registerCsharpDependency(filename: string): void;
@@ -0,0 +1,12 @@
1
+ let viteServer;
2
+ const dependencies = new Set();
3
+ export function setViteServer(server) {
4
+ viteServer = server;
5
+ for (const file of dependencies) {
6
+ viteServer.watcher.add(file);
7
+ }
8
+ }
9
+ export function registerCsharpDependency(filename) {
10
+ dependencies.add(filename);
11
+ viteServer?.watcher.add(filename);
12
+ }
package/package.json CHANGED
@@ -1,6 +1,33 @@
1
+
1
2
  {
2
3
  "name": "svelte-sharp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
4
+ "version": "0.1.0",
5
+ "description": "C# component authoring for SvelteKit",
6
+ "type": "module",
7
+ "license": "MIT",
8
+ "files": [
9
+ "dist",
10
+ "compiler",
11
+ "README.md",
12
+ "LICENSE"
13
+ ],
14
+ "exports": {
15
+ ".": {
16
+ "types": "./dist/index.d.ts",
17
+ "import": "./dist/index.js"
18
+ }
19
+ },
20
+ "scripts": {
21
+ "build": "tsc -p tsconfig.json"
22
+ },
23
+ "peerDependencies": {
24
+ "svelte": "^5.0.0",
25
+ "vite": "^6.0.0 || ^7.0.0 || ^8.0.0"
26
+ },
27
+ "devDependencies": {
28
+ "@types/node": "^22.0.0",
29
+ "svelte": "^5.0.0",
30
+ "typescript": "^5.0.0",
31
+ "vite": "^6.0.0"
32
+ }
33
+ }