Repository navigation
Expand file tree
/
Copy pathvite.config.js
More file actions
295 lines (262 loc) · 13.6 KB
/
Copy pathvite.config.js
File metadata and controls
295 lines (262 loc) · 13.6 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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
import { defineConfig } from 'vite';
import fs from 'fs';
import path from 'path';
// Parse query params splitting ONLY on ? (& is NOT a valid separator)
function parseParams(rawUrl) {
const q = rawUrl.indexOf('?');
if (q === -1) return {};
const qs = rawUrl.slice(q + 1).replace(/%3F/gi, '?').replace(/%3D/gi, '=').replace(/%26/gi, '&');
const p = {};
for (const pair of qs.split(/[?&]/)) { if (pair.startsWith('path=')) continue; const eq = pair.indexOf('='); if (eq !== -1) try { p[pair.slice(0, eq)] = decodeURIComponent(pair.slice(eq + 1)); } catch { p[pair.slice(0, eq)] = pair.slice(eq + 1); } }
return p;
}
function getPathname(rawUrl) {
const q = rawUrl.indexOf('?');
return q === -1 ? rawUrl : rawUrl.slice(0, q);
}
function apiDevPlugin() {
return {
name: 'api-dev',
configureServer(server) {
server.middlewares.use((req, res, next) => {
// --- Init API ---
if (req.url.startsWith('/api/init')) {
const params = parseParams(req.url);
const techs = params.t || '';
const guardrails = params.g || '';
const catFilter = params.c || '';
const format = (params.o || 'agents').toLowerCase();
const shell = (params.s || 'sh').toLowerCase();
const initFormatMap = {
cursor: { ignore: '.cursorignore', rules: '.cursorrules', ignoreSlug: 'cursorignore', rulesSlug: 'cursor' },
claude: { ignore: '.claudeignore', rules: 'CLAUDE.md', ignoreSlug: 'claudeignore', rulesSlug: 'claude' },
agents: { ignore: '.aiignore', rules: 'AGENTS.md', ignoreSlug: 'aiignore', rulesSlug: 'agents' },
windsurf: { ignore: '.codeiumignore', rules: '.windsurfrules', ignoreSlug: 'codeiumignore', rulesSlug: 'windsurf' },
copilot: { ignore: '.aiexclude', rules: '.github/copilot-instructions.md', ignoreSlug: 'aiexclude', rulesSlug: 'copilot' },
gemini: { ignore: '.geminiignore', rules: 'GEMINI.md', ignoreSlug: 'geminiignore', rulesSlug: 'gemini' },
};
const fmt = initFormatMap[format] || initFormatMap.agents;
res.setHeader('Content-Type', 'text/plain; charset=utf-8');
if (!techs && !guardrails) {
res.end(
'Usage: curl -sL "ainit.dev/api/init?t=react,node?g=react,node?o=cursor" | sh\n\n' +
'Parameters:\n t= .aiignore templates\n g= guardrails technologies\n c= guardrails categories (optional)\n o= tool: agents, cursor, claude, windsurf, copilot, gemini\n s= shell: sh (default), ps (PowerShell)\n\n' +
'See https://ainit.dev for available templates and technologies.\n'
);
return;
}
// Build ignore content
let ignoreContent = '';
if (techs) {
const templatesDir = path.resolve('public/templates');
const tIndex = JSON.parse(fs.readFileSync(path.join(templatesDir, 'index.json'), 'utf-8'));
const tValid = new Set(tIndex.map(t => t.slug));
const tSlugs = techs.split(',').map(s => s.trim().toLowerCase()).filter(Boolean);
const tBad = tSlugs.filter(s => !tValid.has(s));
if (tBad.length) {
res.statusCode = 404;
res.end(`Unknown template(s): ${tBad.join(', ')}\n\nAvailable: ${tIndex.map(t => t.slug).sort().join(', ')}\n`);
return;
}
const parts = tSlugs.map(s => fs.readFileSync(path.join(templatesDir, `${s}.txt`), 'utf-8'));
const header = `# === ${fmt.ignore} ===\n# Templates: ${tSlugs.join(', ')}\n# curl -L ainit.dev/api/${tSlugs.join(',')}?o=${fmt.ignoreSlug}\n`;
ignoreContent = header + '\n' + parts.join('\n');
}
// Build guardrails content
let rulesContent = '';
if (guardrails) {
const grDir = path.resolve('public/gr');
const gIndex = JSON.parse(fs.readFileSync(path.join(grDir, 'index.json'), 'utf-8'));
const gValid = new Set(gIndex.technologies.map(t => t.slug));
const gSlugs = guardrails.split(',').map(s => s.trim().toLowerCase()).filter(Boolean);
const gBad = gSlugs.filter(s => !gValid.has(s));
if (gBad.length) {
res.statusCode = 404;
res.end(`Unknown technology(ies): ${gBad.join(', ')}\n\nAvailable: ${gIndex.technologies.map(t => t.slug).sort().join(', ')}\n`);
return;
}
const validCats = new Set(gIndex.categories.map(c => c.slug));
let activeCats = gIndex.categories.map(c => c.slug);
if (catFilter) activeCats = catFilter.split(',').filter(c => validCats.has(c));
let output = `# === ${fmt.rules} ===\n`;
if (fmt.rules === 'AGENTS.md') output += `# AGENTS.md specification by https://agents.md\n`;
output += `# Generated by ainit.dev/guardrails\n# Technologies: ${gSlugs.join(', ')}\n# curl -L ainit.dev/api/guardrails/${gSlugs.join(',')}?o=${fmt.rulesSlug}\n\n`;
for (const catSlug of activeCats) {
const cat = gIndex.categories.find(c => c.slug === catSlug);
const catFile = path.join(grDir, 'categories', `${catSlug}.md`);
if (fs.existsSync(catFile)) output += fs.readFileSync(catFile, 'utf-8') + '\n';
for (const techSlug of gSlugs) {
const techFile = path.join(grDir, 'tech', `${techSlug}.md`);
if (fs.existsSync(techFile)) {
const section = extractSection(fs.readFileSync(techFile, 'utf-8'), cat.name);
if (section) {
const tech = gIndex.technologies.find(t => t.slug === techSlug);
output += `\n## ${tech.name}\n${section}\n`;
}
}
}
output += '\n';
}
rulesContent = output.trim() + '\n';
}
// Generate script
if (shell === 'ps') {
let script = '$u = [Text.UTF8Encoding]::new($false)\n';
if (ignoreContent) {
const escaped = ignoreContent.replace(/'/g, "''");
script += `[IO.File]::WriteAllText((Join-Path $PWD '${fmt.ignore}'), '${escaped}', $u)\n`;
script += `Write-Host "Created ${fmt.ignore}"\n`;
}
if (rulesContent) {
const dir = fmt.rules.includes('/') ? fmt.rules.slice(0, fmt.rules.lastIndexOf('/')) : '';
if (dir) script += `New-Item -ItemType Directory -Force -Path (Join-Path $PWD '${dir}') | Out-Null\n`;
const escaped = rulesContent.replace(/'/g, "''");
script += `[IO.File]::WriteAllText((Join-Path $PWD '${fmt.rules}'), '${escaped}', $u)\n`;
script += `Write-Host "Created ${fmt.rules}"\n`;
}
res.end(script);
} else {
let script = '#!/bin/sh\n';
if (ignoreContent) {
script += `cat > '${fmt.ignore}' << 'AINIT_IGNORE_EOF'\n`;
script += ignoreContent;
if (!ignoreContent.endsWith('\n')) script += '\n';
script += 'AINIT_IGNORE_EOF\n';
script += `echo "Created ${fmt.ignore}"\n`;
}
if (rulesContent) {
const dir = fmt.rules.includes('/') ? fmt.rules.slice(0, fmt.rules.lastIndexOf('/')) : '';
if (dir) script += `mkdir -p '${dir}'\n`;
script += `cat > '${fmt.rules}' << 'AINIT_RULES_EOF'\n`;
script += rulesContent;
if (!rulesContent.endsWith('\n')) script += '\n';
script += 'AINIT_RULES_EOF\n';
script += `echo "Created ${fmt.rules}"\n`;
}
res.end(script);
}
return;
}
// --- Guardrails API ---
if (req.url.startsWith('/api/guardrails/')) {
const grParams = parseParams(req.url);
const slugs = getPathname(req.url).replace('/api/guardrails/', '').split(',').map(s => s.trim().toLowerCase()).filter(Boolean);
const catFilter = grParams.c || null;
const formatParam = (grParams.o || '').toLowerCase();
const grFormatMap = {
agents: 'AGENTS.md', claude: 'CLAUDE.md', cursor: '.cursorrules',
windsurf: '.windsurfrules', copilot: 'copilot-instructions.md', gemini: 'GEMINI.md',
};
const grOutputFilename = grFormatMap[formatParam] || 'AGENTS.md';
const grDir = path.resolve('public/gr');
const index = JSON.parse(fs.readFileSync(path.join(grDir, 'index.json'), 'utf-8'));
const validTechs = new Set(index.technologies.map(t => t.slug));
const validCats = new Set(index.categories.map(c => c.slug));
res.setHeader('Content-Type', 'text/plain; charset=utf-8');
if (!slugs.length) {
res.end('Usage: curl -L ainit.dev/api/guardrails/react,python\n\nSee https://ainit.dev/guardrails for available technologies.\n');
return;
}
const bad = slugs.filter(s => !validTechs.has(s));
if (bad.length) {
res.statusCode = 404;
res.end(`Unknown technology(ies): ${bad.join(', ')}\n\nAvailable: ${index.technologies.map(t => t.slug).sort().join(', ')}\n`);
return;
}
// Determine active categories
let activeCats = index.categories.map(c => c.slug);
if (catFilter) {
activeCats = catFilter.split(',').filter(c => validCats.has(c));
}
// Build output — mirror the original query string with ? separators
const grCurlParts = [];
if (catFilter) grCurlParts.push(`c=${catFilter}`);
grCurlParts.push(`o=${formatParam || 'agents'}`);
let output = `# === ${grOutputFilename} ===\n`;
if (grOutputFilename === 'AGENTS.md') output += `# AGENTS.md specification by https://agents.md\n`;
output += `# Generated by ainit.dev/guardrails\n# Technologies: ${slugs.join(', ')}\n# curl -L ainit.dev/api/guardrails/${slugs.join(',')}?${grCurlParts.join('?')}\n\n`;
for (const catSlug of activeCats) {
const cat = index.categories.find(c => c.slug === catSlug);
const catFile = path.join(grDir, 'categories', `${catSlug}.md`);
if (fs.existsSync(catFile)) {
output += fs.readFileSync(catFile, 'utf-8') + '\n';
}
// Tech-specific sections
for (const techSlug of slugs) {
const techFile = path.join(grDir, 'tech', `${techSlug}.md`);
if (fs.existsSync(techFile)) {
const techContent = fs.readFileSync(techFile, 'utf-8');
const section = extractSection(techContent, cat.name);
if (section) {
const tech = index.technologies.find(t => t.slug === techSlug);
output += `\n## ${tech.name}\n${section}\n`;
}
}
}
output += '\n';
}
res.end(output.trim() + '\n');
return;
}
// --- Aiignore API ---
if (!req.url.startsWith('/api/')) return next();
const aiParams = parseParams(req.url);
const slugs = getPathname(req.url).replace('/api/', '').split(',').map(s => s.trim().toLowerCase()).filter(Boolean);
const aiFormatParam = (aiParams.o || '').toLowerCase();
const aiFormatMap = {
aiignore: '.aiignore', cursorignore: '.cursorignore', aiexclude: '.aiexclude',
codeiumignore: '.codeiumignore', geminiignore: '.geminiignore', claudeignore: '.claudeignore',
};
const aiOutputFilename = aiFormatMap[aiFormatParam] || '.aiignore';
const templatesDir = path.resolve('public/templates');
const index = JSON.parse(fs.readFileSync(path.join(templatesDir, 'index.json'), 'utf-8'));
const valid = new Set(index.map(t => t.slug));
res.setHeader('Content-Type', 'text/plain; charset=utf-8');
if (!slugs.length) {
res.end('Usage: curl -L ainit.dev/api/react,node,typescript\n\nSee https://ainit.dev for available templates.\n');
return;
}
const bad = slugs.filter(s => !valid.has(s));
if (bad.length) {
res.statusCode = 404;
res.end(`Unknown template(s): ${bad.join(', ')}\n\nAvailable: ${index.map(t => t.slug).sort().join(', ')}\n`);
return;
}
const parts = slugs.map(s => fs.readFileSync(path.join(templatesDir, `${s}.txt`), 'utf-8'));
const header = `# === ${aiOutputFilename} ===\n# Templates: ${slugs.join(', ')}\n# curl -L ainit.dev/api/${slugs.join(',')}?o=${aiFormatParam || 'aiignore'}\n`;
res.end(header + '\n' + parts.join('\n'));
});
// SPA fallback — serve index.html for client-side routes
server.middlewares.use((req, res, next) => {
if (req.url === '/guardrails' || req.url.startsWith('/guardrails?') ||
req.url === '/how-to-use' || req.url.startsWith('/how-to-use?')) {
req.url = '/index.html';
}
next();
});
},
};
}
function extractSection(markdown, categoryName) {
const lines = markdown.split('\n');
let capturing = false;
let buf = [];
for (const line of lines) {
const match = line.match(/^##\s+(.+)$/);
if (match) {
if (capturing) break;
if (match[1].trim() === categoryName) capturing = true;
} else if (capturing) {
buf.push(line);
}
}
const result = buf.join('\n').trim();
return result || null;
}
export default defineConfig({
plugins: [apiDevPlugin()],
publicDir: 'public',
build: {
outDir: 'dist',
},
});