-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvite.config.ts
More file actions
188 lines (179 loc) · 6.65 KB
/
Copy pathvite.config.ts
File metadata and controls
188 lines (179 loc) · 6.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
import { defineConfig } from 'vitest/config';
import { fileURLToPath, URL } from 'node:url';
import { execSync } from 'node:child_process';
import path from 'node:path';
import fs from 'node:fs';
import type { Plugin } from 'vite';
import { VitePWA } from 'vite-plugin-pwa';
import { isWelcomePackSourceFile } from './src/fs/welcome-pack';
const root = fileURLToPath(new URL('.', import.meta.url));
const iconsDir = path.join(root, 'icons');
const welcomeDir = path.join(root, 'public', 'welcome');
const pkg = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8')) as { version: string };
/** Short SHA of main (CI / main / origin/main), else HEAD. Empty if git is unavailable. */
function gitCommitShort(): string {
const fromCi = process.env.GITHUB_SHA;
if (fromCi && /^[0-9a-f]{7,40}$/i.test(fromCi)) return fromCi.slice(0, 7);
for (const ref of ['main', 'origin/main', 'HEAD']) {
try {
const sha = execSync(`git rev-parse ${ref}`, {
cwd: root,
encoding: 'utf8',
stdio: ['ignore', 'pipe', 'ignore'],
}).trim();
if (/^[0-9a-f]{7,40}$/i.test(sha)) return sha.slice(0, 7);
} catch {
// try the next ref
}
}
return '';
}
/** Serve and copy ./icons → /icons for system Finder glyphs. */
function iconsStaticPlugin(): Plugin {
const copyIconsTree = (srcDir: string, destDir: string): void => {
if (!fs.existsSync(srcDir)) return;
fs.mkdirSync(destDir, { recursive: true });
for (const name of fs.readdirSync(srcDir)) {
if (name === '.DS_Store') continue;
const src = path.join(srcDir, name);
const dest = path.join(destDir, name);
const st = fs.statSync(src);
if (st.isDirectory()) copyIconsTree(src, dest);
else if (st.isFile()) fs.copyFileSync(src, dest);
}
};
return {
name: 'classicstack-icons-static',
configureServer(server) {
server.middlewares.use((req, res, next) => {
if (!req.url?.startsWith('/icons/')) return next();
const rel = decodeURIComponent(req.url.slice('/icons/'.length).split('?')[0] ?? '');
if (!rel || rel.includes('..') || path.isAbsolute(rel)) {
res.statusCode = 400;
res.end('bad path');
return;
}
const file = path.join(iconsDir, rel);
if (!file.startsWith(iconsDir) || !fs.existsSync(file) || !fs.statSync(file).isFile()) {
res.statusCode = 404;
res.end('not found');
return;
}
const ext = path.extname(file).toLowerCase();
const type =
ext === '.gif' ? 'image/gif' : ext === '.svg' ? 'image/svg+xml' : 'image/png';
res.setHeader('Content-Type', type);
res.setHeader('Cache-Control', 'public, max-age=86400');
fs.createReadStream(file).pipe(res);
});
},
closeBundle() {
copyIconsTree(iconsDir, path.join(root, 'dist', 'icons'));
},
};
}
/** List bundled welcome-pack files and serve /welcome/manifest.json. */
function welcomePackPlugin(): Plugin {
const listFiles = (): { path: string; bytes: number }[] => {
const walk = (dir: string, prefix: string): { path: string; bytes: number }[] => {
if (!fs.existsSync(dir)) return [];
const out: { path: string; bytes: number }[] = [];
for (const name of fs.readdirSync(dir).sort()) {
const full = path.join(dir, name);
const rel = prefix ? `${prefix}/${name}` : name;
const st = fs.statSync(full);
if (st.isDirectory()) out.push(...walk(full, rel));
else if (st.isFile() && isWelcomePackSourceFile(rel)) out.push({ path: rel, bytes: st.size });
}
return out;
};
return walk(welcomeDir, '');
};
const manifestJson = (): string => JSON.stringify({ files: listFiles() });
return {
name: 'classicstack-welcome-pack',
configureServer(server) {
server.middlewares.use((req, res, next) => {
const url = req.url?.split('?')[0];
if (url !== '/welcome/manifest.json') return next();
res.setHeader('Content-Type', 'application/json');
res.setHeader('Cache-Control', 'no-cache');
res.end(manifestJson());
});
},
closeBundle() {
const outDir = path.join(root, 'dist', 'welcome');
fs.mkdirSync(outDir, { recursive: true });
fs.writeFileSync(path.join(outDir, 'manifest.json'), manifestJson());
},
};
}
export default defineConfig({
plugins: [
iconsStaticPlugin(),
welcomePackPlugin(),
VitePWA({
registerType: 'prompt',
injectRegister: false,
includeAssets: ['favicon.png', 'apple-touch-icon.png', 'pwa-192.png', 'pwa-512.png'],
manifest: {
id: '/',
name: 'ClassicStack',
short_name: 'ClassicStack',
description: 'Browser AppleTalk / AFP stack over Web Serial and TashTalk.',
lang: 'en',
dir: 'ltr',
start_url: '/',
scope: '/',
display: 'standalone',
background_color: '#1a1d21',
theme_color: '#1a1d21',
icons: [
{ src: 'pwa-192.png', sizes: '192x192', type: 'image/png' },
{ src: 'pwa-512.png', sizes: '512x512', type: 'image/png' },
{ src: 'pwa-512.png', sizes: '512x512', type: 'image/png', purpose: 'maskable' },
],
},
workbox: {
globPatterns: ['**/*.{js,css,html,ico,png,svg,woff,woff2,json,bin,dsk,sit,txt,md}'],
globIgnores: ['**/CNAME'],
cleanupOutdatedCaches: true,
navigateFallback: 'index.html',
maximumFileSizeToCacheInBytes: 2 * 1024 * 1024,
runtimeCaching: [
{
urlPattern: /^https:\/\/fonts\.googleapis\.com\/.*/i,
handler: 'CacheFirst',
options: {
cacheName: 'google-fonts-stylesheets',
expiration: { maxEntries: 8, maxAgeSeconds: 60 * 60 * 24 * 365 },
cacheableResponse: { statuses: [0, 200] },
},
},
{
urlPattern: /^https:\/\/fonts\.gstatic\.com\/.*/i,
handler: 'CacheFirst',
options: {
cacheName: 'google-fonts-webfonts',
expiration: { maxEntries: 16, maxAgeSeconds: 60 * 60 * 24 * 365 },
cacheableResponse: { statuses: [0, 200] },
},
},
],
},
}),
],
define: {
__APP_VERSION__: JSON.stringify(pkg.version),
__GIT_COMMIT__: JSON.stringify(gitCommitShort()),
},
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url)),
},
},
test: {
globals: true,
environment: 'node',
},
});