@pingpolls/svelte-adapter-bun-isr 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 PingPolls
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 ADDED
@@ -0,0 +1,60 @@
1
+ # @pingpolls/svelte-adapter-bun-isr
2
+
3
+ A SvelteKit adapter designed for Bun environments that provides built-in Incremental Static Regeneration (ISR) support.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ bun add -D @pingpolls/svelte-adapter-bun-isr
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ Add the adapter to your `svelte.config.js`:
14
+
15
+ ```javascript
16
+ import adapter from '@pingpolls/svelte-adapter-bun-isr';
17
+
18
+ export default {
19
+ kit: {
20
+ adapter: adapter({
21
+ out: 'build',
22
+ revalidateToken: process.env.REVALIDATE_TOKEN, // Enables POST /__isr/revalidate
23
+ }),
24
+ },
25
+ };
26
+ ```
27
+
28
+ ## Features
29
+
30
+ * **Automatic ISR Support:** Define `export const revalidate = <seconds>` in your SvelteKit routes (`+page.server.ts`). The adapter automatically schedules proactive re-renders for these routes.
31
+ * **On-Demand Revalidation:** You can manually trigger a rebuild for a specific path using a POST request to `/__isr/revalidate?path=/your/route` (requires a valid `x-revalidate-token` header).
32
+ * **Warm-on-Boot:** All ISR-eligible paths are rendered and cached once when the Bun server starts.
33
+
34
+ ## Configuration Options
35
+
36
+ | Option | Type | Default | Description |
37
+ | :--- | :--- | :--- | :--- |
38
+ | `out` | `string` | `'build'` | The output directory for the generated SvelteKit files. |
39
+ | `revalidateToken` | `string` | `undefined` | A token required to authenticate on-demand revalidation requests. |
40
+ | `precompress` | `boolean` | `false` | Enables pre-compression of static assets. |
41
+
42
+ ## ISR Convention
43
+
44
+ To enable ISR on a route, export `revalidate` in your `+page.server.ts` or `+layout.server.ts` files:
45
+
46
+ ```ts
47
+ // src/routes/blog/[slug]/+page.server.ts
48
+ export const revalidate = 900; // Rebuild every 900 seconds (15 minutes)
49
+ ```
50
+
51
+ ## V1 Limitations
52
+
53
+ * **Single-Process Cache:** The current implementation uses an in-memory `Map` for caching. Cache coordination across multiple running processes or instances is not supported.
54
+ * **Path-Only Caching:** The cache keys are based solely on the pathname. Queries parameters in the URL are ignored for caching purposes.
55
+
56
+ ## Development
57
+
58
+ ```bash
59
+ bun run build && bun test
60
+ ```
@@ -0,0 +1,7 @@
1
+ import type { Adapter } from "@sveltejs/kit";
2
+ interface AdapterOptions {
3
+ out?: string;
4
+ port?: number;
5
+ }
6
+ export default function (options?: AdapterOptions): Adapter;
7
+ export {};
package/dist/index.js ADDED
@@ -0,0 +1,162 @@
1
+ // @bun
2
+ import{cpSync as Q,existsSync as L,mkdirSync as X,writeFileSync as g}from"fs";import{readdir as w}from"fs/promises";import{join as q}from"path";var M="svelte-adapter-bun-isr";function N(K={}){let{out:U="build",port:Z=3000}=K;return{name:M,async adapt(z){let H=q(process.cwd(),U),G=z.getBuildDirectory("adapter-bun");z.rimraf(H),z.rimraf(G),X(G,{recursive:!0}),z.log.minor("Copying client assets"),z.writeClient(q(H,"client")),z.log.minor("Copying prerendered pages"),z.writePrerendered(q(H,"prerendered")),z.log.minor("Building server"),z.writeServer(G);let F=JSON.stringify(z.prerendered.paths);g(q(G,"manifest.js"),[`export const manifest = ${z.generateManifest({relativePath:"./"})};`,`export const prerendered = new Set(${F});`,`export const base = ${JSON.stringify(z.config.kit.paths.base)};`].join(`
3
+
4
+ `));let J=q(H,"server");X(J,{recursive:!0}),Q(q(G,"manifest.js"),q(J,"manifest.js"));let B=q(G,"index.js");if(L(B))Q(B,q(J,"index.js"));let $=q(G,"chunks");if(L($)){let O=q(J,"chunks");X(O,{recursive:!0});let V=await w($);for(let R of V)Q(q($,R),q(O,R))}let T=q(G,"entries");if(L(T))await Y(T,q(J,"entries"));let W=q(G,"nodes");if(L(W))await Y(W,q(J,"nodes"));let I=["env.js","internal.js","remote-entry.js"];for(let O of I){let V=q(G,O);if(L(V))Q(V,q(J,O))}let _=q(G,".vite");if(L(_))await Y(_,q(J,".vite"));g(q(H,"index.js"),f(Z)),z.log.minor(`Adapter output written to ${H}`)},supports:{read:()=>!0}}}async function Y(K,U){X(U,{recursive:!0});let Z=await w(K,{withFileTypes:!0});for(let z of Z){let H=q(K,z.name),G=q(U,z.name);if(z.isDirectory())await Y(H,G);else Q(H,G)}}function f(K){return`
5
+ import { Server } from './server/index.js';
6
+ import { manifest, prerendered, base } from './server/manifest.js';
7
+ import { Glob } from 'bun';
8
+ import { join } from 'node:path';
9
+
10
+ const ADAPTER_NAME = 'svelte-adapter-bun-isr';
11
+ const ISR_CACHE = new Map();
12
+ const ASSET_DIR = join(import.meta.dir, 'client', base);
13
+ const PRERENDERED_DIR = join(import.meta.dir, 'prerendered');
14
+
15
+ const server = new Server(manifest);
16
+
17
+ await server.init({
18
+ env: Bun.env,
19
+ read: (file) => Bun.file(join(ASSET_DIR, file)).stream(),
20
+ });
21
+
22
+ // Pre-compute: build a Set of all client asset paths for O(1) lookups
23
+ // instead of calling existsSync on every request
24
+ const clientAssets = new Set();
25
+ const assetGlob = new Glob('**/*');
26
+ for await (const entry of assetGlob.scan({ cwd: ASSET_DIR, onlyFiles: true, absolute: false })) {
27
+ clientAssets.add('/' + base + '/' + entry);
28
+ }
29
+
30
+ // Pre-compute: build a Map of regex -> revalidate duration from manifest routes
31
+ // This eliminates per-request route pattern matching and dynamic imports
32
+ const revalidateMap = new Map();
33
+ const routes = manifest._?.routes || [];
34
+ for (const route of routes) {
35
+ if (!route.pattern) continue;
36
+ const page = route.page;
37
+ if (!page) continue;
38
+
39
+ let revalidate = null;
40
+
41
+ // Check layouts first
42
+ for (const leafIdx of page.layouts || []) {
43
+ try {
44
+ const mod = await manifest._.nodes[leafIdx]();
45
+ if (mod?.config && typeof mod.config.revalidate === 'number') {
46
+ revalidate = mod.config.revalidate;
47
+ break;
48
+ }
49
+ } catch {}
50
+ }
51
+
52
+ // Check leaf if no layout had revalidate
53
+ if (revalidate === null && typeof page.leaf === 'number') {
54
+ try {
55
+ const mod = await manifest._.nodes[page.leaf]();
56
+ if (mod?.config && typeof mod.config.revalidate === 'number') {
57
+ revalidate = mod.config.revalidate;
58
+ }
59
+ } catch {}
60
+ }
61
+
62
+ if (revalidate !== null) {
63
+ revalidateMap.set(route.pattern, revalidate);
64
+ }
65
+ }
66
+
67
+ function getRevalidateForPath(pathname) {
68
+ for (const [pattern, revalidate] of revalidateMap) {
69
+ if (pattern.test(pathname)) {
70
+ return revalidate;
71
+ }
72
+ }
73
+ return null;
74
+ }
75
+
76
+ function getCached(pathname) {
77
+ const entry = ISR_CACHE.get(pathname);
78
+ if (!entry) return null;
79
+ const age = (Date.now() - entry.timestamp) / 1000;
80
+ if (age < entry.revalidate) return entry.html;
81
+ ISR_CACHE.delete(pathname);
82
+ return null;
83
+ }
84
+
85
+ function setCache(pathname, html, revalidate) {
86
+ ISR_CACHE.set(pathname, { html, timestamp: Date.now(), revalidate });
87
+ }
88
+
89
+ // Pre-compute: build a Map of prerendered page -> pre-opened BunFile
90
+ // for zero-allocation, zero-syscall serving
91
+ const prerenderedFiles = new Map();
92
+ for (const p of prerendered) {
93
+ const candidates = [
94
+ join(PRERENDERED_DIR, p),
95
+ join(PRERENDERED_DIR, p + '.html'),
96
+ join(PRERENDERED_DIR, p, 'index.html'),
97
+ ];
98
+ for (const filePath of candidates) {
99
+ const f = Bun.file(filePath);
100
+ if (await f.exists()) {
101
+ prerenderedFiles.set(p, f);
102
+ break;
103
+ }
104
+ }
105
+ }
106
+
107
+ const bunServer = Bun.serve({
108
+ port: ${K},
109
+ idleTimeout: 0,
110
+ reusePort: true,
111
+ development: false,
112
+
113
+ async fetch(request) {
114
+ const url = new URL(request.url);
115
+ let pathname = url.pathname;
116
+
117
+ // 1. Serve static client assets (O(1) Set lookup)
118
+ if (clientAssets.has(pathname)) {
119
+ const filePath = join(ASSET_DIR, pathname.slice(base.length + 1) || pathname);
120
+ const file = Bun.file(filePath);
121
+ const headers = {};
122
+ if (pathname.includes('/immutable/')) {
123
+ headers['cache-control'] = 'public,max-age=31536000,immutable';
124
+ }
125
+ return new Response(file, { headers });
126
+ }
127
+
128
+ // 2. Serve prerendered pages (O(1) Map lookup, pre-opened BunFile)
129
+ const prerenderedFile = prerenderedFiles.get(pathname);
130
+ if (prerenderedFile) {
131
+ return new Response(prerenderedFile, {
132
+ headers: { 'Content-Type': 'text/html' },
133
+ });
134
+ }
135
+
136
+ // 3. Try ISR cache (O(1) Map lookup)
137
+ const cached = getCached(pathname);
138
+ if (cached) {
139
+ return new Response(cached, { status: 200, headers: { 'Content-Type': 'text/html' } });
140
+ }
141
+
142
+ // 4. Forward to SvelteKit
143
+ const response = await server.respond(request, {
144
+ platform: { server: bunServer, request },
145
+ });
146
+
147
+ // 5. Cache 200 responses with revalidate config (pre-computed map)
148
+ if (response.status === 200) {
149
+ const revalidate = getRevalidateForPath(pathname);
150
+ if (revalidate && revalidate > 0) {
151
+ const clone = response.clone();
152
+ const html = await clone.text();
153
+ setCache(pathname, html, revalidate);
154
+ }
155
+ }
156
+
157
+ return response;
158
+ },
159
+ });
160
+
161
+ console.log(\`\${ADAPTER_NAME} listening on http://localhost:\${bunServer.port}\`);
162
+ `}export{N as default};
package/package.json ADDED
@@ -0,0 +1,45 @@
1
+ {
2
+ "name": "@pingpolls/svelte-adapter-bun-isr",
3
+ "version": "0.1.0",
4
+ "description": "SvelteKit adapter for Bun with Incremental Static Regeneration (ISR) support",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/pingpolls/svelte-adapter-bun-isr.git"
9
+ },
10
+ "keywords": [
11
+ "sveltekit",
12
+ "adapter",
13
+ "bun",
14
+ "ssr",
15
+ "isr",
16
+ "static",
17
+ "svelte"
18
+ ],
19
+ "type": "module",
20
+ "main": "dist/index.js",
21
+ "module": "dist/index.js",
22
+ "types": "dist/index.d.ts",
23
+ "exports": {
24
+ ".": {
25
+ "types": "./dist/index.d.ts",
26
+ "import": "./dist/index.js"
27
+ }
28
+ },
29
+ "files": [
30
+ "dist"
31
+ ],
32
+ "scripts": {
33
+ "build": "rm -rf dist && bun build ./src/index.ts --outdir ./dist --target bun --minify && bun x tsc --project tsconfig.build.json",
34
+ "test": "bun test",
35
+ "release": "bun run build && bun test && bunx --bun npm publish --access public"
36
+ },
37
+ "peerDependencies": {
38
+ "@sveltejs/kit": ">=2.0.0"
39
+ },
40
+ "devDependencies": {
41
+ "@sveltejs/kit": "^2.70.1",
42
+ "@types/bun": "latest",
43
+ "typescript": "^5.0.0"
44
+ }
45
+ }