create-addfox-app 0.1.1-beta.3

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.
Files changed (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +18 -0
  3. package/dist/cli.js +906 -0
  4. package/package.json +34 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 addfox
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,18 @@
1
+ <p align="center">
2
+ <img width="200" src="https://raw.githubusercontent.com/addfox/addfox/main/addfox.png" alt="Addfox">
3
+ </p>
4
+
5
+ # create-addfox-app
6
+
7
+ [中文](README-zh_CN.md) | English
8
+
9
+ ---
10
+
11
+ Interactive scaffolder: generates a addfox-based extension project from options (template, package manager, entries, skills).
12
+
13
+ - Commands: `create-addfox-app` or `pnpm create addfox-app` (and npm/yarn/bun equivalents)
14
+ - Flow: (1) select framework (vanilla / vue / react / preact / svelte / solid), (2) language (TypeScript / JavaScript), (3) package manager (pnpm / npm / yarn / bun), (4) entries to include (multi-select), (5) whether to install addfox skills (yes/no). Output to cwd or a given directory. Generated project uses **addfox.config.ts** or **addfox.config.js** with minimal manifest (entry discovery; no built-in entry paths in manifest).
15
+
16
+ ## Templates
17
+
18
+ Scaffold templates live at **repo root** in **`templates/`** (e.g. `template-vanilla-ts`, `template-react-ts`). The CLI downloads the chosen template from the GitHub repo tarball, so the repo must have `templates/` at root and committed. The npm package does not bundle templates; it fetches from GitHub at scaffold time.
package/dist/cli.js ADDED
@@ -0,0 +1,906 @@
1
+ #!/usr/bin/env node
2
+ import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
3
+ import { dirname, join, relative, resolve } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { createRequire } from "node:module";
6
+ import { execSync } from "node:child_process";
7
+ import prompts from "prompts";
8
+ import { blue, cyan, dim, gray, green, lightBlue, magenta, red, trueColor, yellow } from "kolorist";
9
+ import minimist from "minimist";
10
+ import { gunzipSync } from "node:zlib";
11
+ import { detectPackageManager, getExecCommand, getInstallCommand, getRunCommand } from "@addfox/pkg-manager";
12
+ const GITHUB_REPO = "gxy5202/addfox";
13
+ const TEMPLATE_BASE = "templates";
14
+ function getRepoRoot() {
15
+ const fromDist = resolve(dirname(fileURLToPath(import.meta.url)), "..", "..", "..");
16
+ return fromDist;
17
+ }
18
+ function tryLocalTemplates(templateName, destDir) {
19
+ const repoRoot = getRepoRoot();
20
+ const templatePath = join(repoRoot, TEMPLATE_BASE, templateName);
21
+ if (!existsSync(templatePath)) return false;
22
+ mkdirSync(destDir, {
23
+ recursive: true
24
+ });
25
+ cpSync(templatePath, destDir, {
26
+ recursive: true
27
+ });
28
+ return true;
29
+ }
30
+ function parseTarHeader(buf) {
31
+ if (buf.every((b)=>0 === b)) return null;
32
+ const rawName = buf.subarray(0, 100).toString("utf8").replace(/\0+$/, "");
33
+ const sizeStr = buf.subarray(124, 136).toString("utf8").replace(/\0+$/, "").trim();
34
+ const type = String.fromCharCode(buf[156]);
35
+ const prefix = buf.subarray(345, 500).toString("utf8").replace(/\0+$/, "");
36
+ return {
37
+ name: prefix ? `${prefix}/${rawName}` : rawName,
38
+ size: parseInt(sizeStr, 8) || 0,
39
+ type
40
+ };
41
+ }
42
+ function extractMatchingFiles(tarBuffer, templatePrefix, destDir) {
43
+ let offset = 0;
44
+ while(offset + 512 <= tarBuffer.length){
45
+ const header = parseTarHeader(tarBuffer.subarray(offset, offset + 512));
46
+ offset += 512;
47
+ if (!header) break;
48
+ const dataBlocks = 512 * Math.ceil(header.size / 512);
49
+ const idx = header.name.indexOf(templatePrefix);
50
+ if (-1 !== idx) {
51
+ const relativePath = header.name.substring(idx + templatePrefix.length).replace(/^\//, "");
52
+ if (relativePath) {
53
+ const destPath = join(destDir, relativePath);
54
+ const isDir = "5" === header.type || relativePath.endsWith("/");
55
+ if (isDir) mkdirSync(destPath, {
56
+ recursive: true
57
+ });
58
+ else if ("0" === header.type || "\0" === header.type) {
59
+ mkdirSync(dirname(destPath), {
60
+ recursive: true
61
+ });
62
+ writeFileSync(destPath, tarBuffer.subarray(offset, offset + header.size));
63
+ }
64
+ }
65
+ }
66
+ offset += dataBlocks;
67
+ }
68
+ }
69
+ async function downloadTemplate(templateName, destDir, branch = "main") {
70
+ const url = `https://codeload.github.com/${GITHUB_REPO}/tar.gz/${branch}`;
71
+ const templatePrefix = `${TEMPLATE_BASE}/${templateName}/`;
72
+ const response = await fetch(url);
73
+ if (!response.ok) throw new Error(`HTTP ${response.status}: ${response.statusText}`);
74
+ const compressed = Buffer.from(await response.arrayBuffer());
75
+ const tarBuffer = gunzipSync(compressed);
76
+ mkdirSync(destDir, {
77
+ recursive: true
78
+ });
79
+ extractMatchingFiles(tarBuffer, templatePrefix, destDir);
80
+ }
81
+ const STYLE_ENGINES = [
82
+ {
83
+ title: "无",
84
+ value: "none"
85
+ },
86
+ {
87
+ title: "Tailwind CSS",
88
+ value: "tailwindcss"
89
+ },
90
+ {
91
+ title: "UnoCSS",
92
+ value: "unocss"
93
+ },
94
+ {
95
+ title: "Less",
96
+ value: "less"
97
+ },
98
+ {
99
+ title: "Sass (SCSS)",
100
+ value: "sass"
101
+ }
102
+ ];
103
+ const FRAMEWORKS = [
104
+ {
105
+ title: "Vanilla",
106
+ value: "vanilla"
107
+ },
108
+ {
109
+ title: "Vue",
110
+ value: "vue"
111
+ },
112
+ {
113
+ title: "React",
114
+ value: "react"
115
+ },
116
+ {
117
+ title: "Preact",
118
+ value: "preact"
119
+ },
120
+ {
121
+ title: "Svelte",
122
+ value: "svelte"
123
+ },
124
+ {
125
+ title: "Solid",
126
+ value: "solid"
127
+ }
128
+ ];
129
+ function getTemplateName(framework, language) {
130
+ return `template-${framework}-${language}`;
131
+ }
132
+ const PACKAGE_MANAGER_CHOICES = [
133
+ {
134
+ title: "pnpm",
135
+ value: "pnpm"
136
+ },
137
+ {
138
+ title: "npm",
139
+ value: "npm"
140
+ },
141
+ {
142
+ title: "yarn",
143
+ value: "yarn"
144
+ },
145
+ {
146
+ title: "bun",
147
+ value: "bun"
148
+ }
149
+ ];
150
+ const ENTRY_NAMES = [
151
+ "popup",
152
+ "options",
153
+ "background",
154
+ "content",
155
+ "devtools",
156
+ "sidepanel",
157
+ "sandbox",
158
+ "newtab",
159
+ "bookmarks",
160
+ "history",
161
+ "offscreen"
162
+ ];
163
+ const ENTRY_APP_DIRS = ENTRY_NAMES;
164
+ const ENTRY_CHOICES = [
165
+ {
166
+ title: "All (popup, options, background, content, …)",
167
+ value: "__all__"
168
+ },
169
+ ...ENTRY_NAMES.map((name)=>({
170
+ title: name,
171
+ value: name
172
+ }))
173
+ ];
174
+ const APP_DIR = "app";
175
+ function filterAppEntries(destDir, selectedEntries) {
176
+ const useAll = selectedEntries.includes("__all__");
177
+ if (useAll) return;
178
+ const keepSet = new Set(selectedEntries);
179
+ const appPath = join(destDir, APP_DIR);
180
+ if (!existsSync(appPath)) return;
181
+ const dirs = readdirSync(appPath, {
182
+ withFileTypes: true
183
+ }).filter((d)=>d.isDirectory()).map((d)=>d.name);
184
+ for (const dir of dirs){
185
+ const isEntryDir = ENTRY_APP_DIRS.includes(dir);
186
+ if (isEntryDir && !keepSet.has(dir)) rmSync(join(appPath, dir), {
187
+ recursive: true
188
+ });
189
+ }
190
+ }
191
+ function getExistingAppEntryDirs(destDir) {
192
+ const appPath = join(destDir, APP_DIR);
193
+ if (!existsSync(appPath)) return [];
194
+ return readdirSync(appPath, {
195
+ withFileTypes: true
196
+ }).filter((d)=>d.isDirectory()).map((d)=>d.name).filter((name)=>ENTRY_APP_DIRS.includes(name));
197
+ }
198
+ function getFrameworkPluginImport(framework) {
199
+ switch(framework){
200
+ case "react":
201
+ return 'import { pluginReact } from "@rsbuild/plugin-react";';
202
+ case "preact":
203
+ return 'import { pluginPreact } from "@rsbuild/plugin-preact";';
204
+ case "vue":
205
+ return 'import { pluginVue } from "@rsbuild/plugin-vue";';
206
+ case "svelte":
207
+ return 'import { pluginSvelte } from "@rsbuild/plugin-svelte";';
208
+ case "solid":
209
+ return 'import { pluginSolid } from "@rsbuild/plugin-solid";';
210
+ default:
211
+ return "";
212
+ }
213
+ }
214
+ function getFrameworkPluginCall(framework) {
215
+ switch(framework){
216
+ case "react":
217
+ return "pluginReact()";
218
+ case "preact":
219
+ return "pluginPreact()";
220
+ case "vue":
221
+ return "pluginVue()";
222
+ case "svelte":
223
+ return "pluginSvelte()";
224
+ case "solid":
225
+ return "pluginSolid()";
226
+ default:
227
+ return null;
228
+ }
229
+ }
230
+ function getStylePlugin(engine) {
231
+ if ("none" === engine || void 0 === engine) return null;
232
+ if ("less" === engine) return {
233
+ importLine: 'import { pluginLess } from "@rsbuild/plugin-less";',
234
+ call: "pluginLess()"
235
+ };
236
+ if ("sass" === engine) return {
237
+ importLine: 'import { pluginSass } from "@rsbuild/plugin-sass";',
238
+ call: "pluginSass()"
239
+ };
240
+ return null;
241
+ }
242
+ const MINIMAL_MANIFEST = ' name: "My Extension",\n version: "1.0.0",\n manifest_version: 3,\n description: "Browser extension built with addfox",\n permissions: ["storage", "activeTab"],';
243
+ function generateAddfoxConfig(framework, _language, styleEngine) {
244
+ const importLines = [];
245
+ const fwImport = getFrameworkPluginImport(framework);
246
+ if (fwImport) importLines.push(fwImport);
247
+ const st = getStylePlugin(styleEngine);
248
+ if (st) importLines.push(st.importLine);
249
+ const pluginCalls = [];
250
+ const fwCall = getFrameworkPluginCall(framework);
251
+ if (fwCall) pluginCalls.push(fwCall);
252
+ if (st) pluginCalls.push(st.call);
253
+ const pluginsLine = pluginCalls.length > 0 ? ` plugins: [${pluginCalls.join(", ")}],` : "";
254
+ const parts = [
255
+ "import { defineConfig } from \"addfox\";",
256
+ importLines.length ? `\n${importLines.join("\n")}\n` : "",
257
+ "const manifest = {",
258
+ MINIMAL_MANIFEST,
259
+ "};",
260
+ "",
261
+ "export default defineConfig({",
262
+ " manifest: { chromium: manifest, firefox: { ...manifest } },",
263
+ ...pluginsLine ? [
264
+ pluginsLine
265
+ ] : [],
266
+ "});"
267
+ ];
268
+ return parts.filter(Boolean).join("\n");
269
+ }
270
+ const UTF8_BOM = "\uFEFF";
271
+ function stripUtf8Bom(text) {
272
+ return text.startsWith(UTF8_BOM) ? text.slice(UTF8_BOM.length) : text;
273
+ }
274
+ function readJsonFile(path) {
275
+ const raw = readFileSync(path, "utf8");
276
+ return JSON.parse(stripUtf8Bom(raw));
277
+ }
278
+ function writeJsonFile(path, data) {
279
+ writeFileSync(path, JSON.stringify(data, null, 2), "utf8");
280
+ }
281
+ const RSTEST_CORE = "^0.9.2";
282
+ const RSTEST_COVERAGE = "^0.3.0";
283
+ const RSTEST_BROWSER = "^0.9.2";
284
+ const PLAYWRIGHT = "^1.49.0";
285
+ const RSDOCTOR_RSPACK = "^1.5.3";
286
+ function getTestExt(language) {
287
+ return "ts" === language ? "ts" : "js";
288
+ }
289
+ function getTestGlob(language) {
290
+ return "ts" === language ? "__tests__/**/*.test.ts" : "__tests__/**/*.test.js";
291
+ }
292
+ function getE2eGlob(language) {
293
+ return "ts" === language ? "__tests__/e2e/**/*.test.ts" : "__tests__/e2e/**/*.test.js";
294
+ }
295
+ function generateRstestConfig(language, testKinds) {
296
+ const hasUnit = testKinds.includes("unit");
297
+ const hasE2e = testKinds.includes("e2e");
298
+ getTestExt(language);
299
+ if (!hasUnit && !hasE2e) return "";
300
+ const header = `import { defineConfig } from "@rstest/core";\n\n`;
301
+ if (hasUnit && !hasE2e) {
302
+ const glob = getTestGlob(language);
303
+ return `${header}export default defineConfig({
304
+ testEnvironment: "node",
305
+ include: ["${glob}"],
306
+ exclude: { patterns: ["**/node_modules/**", "**/dist/**"] },
307
+ root: process.cwd(),
308
+ });
309
+ `;
310
+ }
311
+ if (!hasUnit && hasE2e) {
312
+ const inc = getE2eGlob(language);
313
+ return `${header}export default defineConfig({
314
+ root: process.cwd(),
315
+ projects: [
316
+ {
317
+ name: "browser",
318
+ include: ["${inc}"],
319
+ browser: {
320
+ enabled: true,
321
+ provider: "playwright",
322
+ browser: "chromium",
323
+ },
324
+ },
325
+ ],
326
+ });
327
+ `;
328
+ }
329
+ const unitGlob = getTestGlob(language);
330
+ const e2eInc = getE2eGlob(language);
331
+ return `${header}export default defineConfig({
332
+ root: process.cwd(),
333
+ projects: [
334
+ {
335
+ name: "node",
336
+ testEnvironment: "node",
337
+ include: ["${unitGlob}"],
338
+ exclude: { patterns: ["**/node_modules/**", "**/dist/**", "__tests__/e2e/**"] },
339
+ },
340
+ {
341
+ name: "browser",
342
+ include: ["${e2eInc}"],
343
+ browser: {
344
+ enabled: true,
345
+ provider: "playwright",
346
+ browser: "chromium",
347
+ },
348
+ },
349
+ ],
350
+ });
351
+ `;
352
+ }
353
+ function writeUnitSample(root, language) {
354
+ const ext = getTestExt(language);
355
+ mkdirSync(resolve(root, "__tests__"), {
356
+ recursive: true
357
+ });
358
+ const path = resolve(root, "__tests__", `example.test.${ext}`);
359
+ const body = "ts" === language ? `import { describe, expect, it } from "@rstest/core";
360
+
361
+ describe("example unit tests", () => {
362
+ it("adds numbers", () => {
363
+ expect(1 + 2).toBe(3);
364
+ });
365
+ });
366
+ ` : `import { describe, expect, it } from "@rstest/core";
367
+
368
+ describe("example unit tests", () => {
369
+ it("adds numbers", () => {
370
+ expect(1 + 2).toBe(3);
371
+ });
372
+ });
373
+ `;
374
+ writeFileSync(path, body, "utf-8");
375
+ }
376
+ function writeE2eSample(root, language) {
377
+ const ext = getTestExt(language);
378
+ const dir = resolve(root, "__tests__", "e2e");
379
+ mkdirSync(dir, {
380
+ recursive: true
381
+ });
382
+ const path = resolve(dir, `example.browser.test.${ext}`);
383
+ const body = `import { describe, expect, it } from "@rstest/core";
384
+ import { page } from "@rstest/browser";
385
+
386
+ describe("E2E browser tests", () => {
387
+ it("asserts element in document", async () => {
388
+ document.body.innerHTML = \`<button id="btn">Click me</button>\`;
389
+ await expect
390
+ .element(page.getByRole("button", { name: "Click me" }))
391
+ .toBeVisible();
392
+ });
393
+ });
394
+ `;
395
+ writeFileSync(path, body, "utf-8");
396
+ }
397
+ function mergeDevDeps(pkg, testKinds, installRsdoctor) {
398
+ const dev = pkg.devDependencies ?? {};
399
+ pkg.devDependencies = dev;
400
+ if (testKinds.length > 0) dev["@rstest/core"] = RSTEST_CORE;
401
+ if (testKinds.includes("unit")) dev["@rstest/coverage-istanbul"] = RSTEST_COVERAGE;
402
+ if (testKinds.includes("e2e")) {
403
+ dev["@rstest/browser"] = RSTEST_BROWSER;
404
+ dev.playwright = PLAYWRIGHT;
405
+ }
406
+ if (installRsdoctor) dev["@rsdoctor/rspack-plugin"] = RSDOCTOR_RSPACK;
407
+ }
408
+ function mergeScripts(pkg, testKinds) {
409
+ const scripts = pkg.scripts ?? {};
410
+ pkg.scripts = scripts;
411
+ if (0 === testKinds.length) return;
412
+ scripts.test = "addfox test";
413
+ if (testKinds.includes("unit")) scripts["test:coverage"] = "addfox test --coverage";
414
+ if (testKinds.includes("e2e")) scripts.pretest = "addfox build";
415
+ }
416
+ function applyTestAndReportSetup(root, language, selection) {
417
+ const { testKinds, installRsdoctor } = selection;
418
+ if (0 === testKinds.length && !installRsdoctor) return;
419
+ const pkgPath = resolve(root, "package.json");
420
+ const pkg = readJsonFile(pkgPath);
421
+ mergeDevDeps(pkg, testKinds, installRsdoctor);
422
+ mergeScripts(pkg, testKinds);
423
+ writeJsonFile(pkgPath, pkg);
424
+ if (testKinds.length > 0) {
425
+ const configName = "ts" === language ? "rstest.config.ts" : "rstest.config.js";
426
+ const content = generateRstestConfig(language, testKinds);
427
+ writeFileSync(resolve(root, configName), content, "utf-8");
428
+ if (testKinds.includes("unit")) writeUnitSample(root, language);
429
+ if (testKinds.includes("e2e")) writeE2eSample(root, language);
430
+ }
431
+ }
432
+ const DASH_H = " - - - - - - - - - - - - - - - - - - - - - - - - - ";
433
+ const INNER_W = DASH_H.length;
434
+ function printAddfoxLogo(colorFn) {
435
+ const c = colorFn;
436
+ const top = " " + c("┌" + DASH_H + "┐");
437
+ const empty = " " + c("│") + " ".repeat(INNER_W) + c("│");
438
+ const text = "Addfox";
439
+ const pad = Math.max(0, Math.floor((INNER_W - text.length) / 2));
440
+ const textLine = " " + c("│") + " ".repeat(pad) + c(text) + " ".repeat(INNER_W - pad - text.length) + c("│");
441
+ const bottom = " " + c("└" + DASH_H + "┘");
442
+ const art = [
443
+ "",
444
+ top,
445
+ empty,
446
+ textLine,
447
+ empty,
448
+ bottom,
449
+ ""
450
+ ].join("\n");
451
+ console.log(art);
452
+ }
453
+ const SKIP_STYLE_ENTRIES = new Set([
454
+ "background",
455
+ "content"
456
+ ]);
457
+ const DEPS = {
458
+ tailwindcss: {
459
+ tailwindcss: "^4.1.18",
460
+ "@tailwindcss/postcss": "^4.1.18",
461
+ postcss: "^8.4.32",
462
+ autoprefixer: "^10.4.20"
463
+ },
464
+ unocss: {
465
+ unocss: "^0.62.4",
466
+ "@unocss/postcss": "^0.62.4",
467
+ postcss: "^8.4.32"
468
+ },
469
+ less: {
470
+ "@rsbuild/plugin-less": "^1.2.1",
471
+ less: "^4.2.0"
472
+ },
473
+ sass: {
474
+ "@rsbuild/plugin-sass": "^1.5.0",
475
+ sass: "^1.77.0"
476
+ }
477
+ };
478
+ function styleFileName(engine) {
479
+ if ("tailwindcss" === engine) return "global.css";
480
+ if ("unocss" === engine) return "uno.css";
481
+ if ("less" === engine) return "global.less";
482
+ return "global.scss";
483
+ }
484
+ function listUiEntryScripts(root, language) {
485
+ const appDir = join(root, "app");
486
+ if (!existsSync(appDir)) return [];
487
+ const extOrder = "ts" === language ? [
488
+ ".tsx",
489
+ ".ts",
490
+ ".vue",
491
+ ".svelte"
492
+ ] : [
493
+ ".jsx",
494
+ ".js",
495
+ ".vue",
496
+ ".svelte"
497
+ ];
498
+ const out = [];
499
+ for (const name of readdirSync(appDir)){
500
+ if (SKIP_STYLE_ENTRIES.has(name)) continue;
501
+ const sub = join(appDir, name);
502
+ if (statSync(sub).isDirectory()) for (const ext of extOrder){
503
+ const p = join(sub, `index${ext}`);
504
+ if (existsSync(p)) {
505
+ out.push(p);
506
+ break;
507
+ }
508
+ }
509
+ }
510
+ return out;
511
+ }
512
+ function buildStyleImportLine(entryFile, engine) {
513
+ const entryDir = join(entryFile, "..");
514
+ const stylePath = join(entryDir, "..", "styles", styleFileName(engine));
515
+ const rel = relative(entryDir, stylePath).replace(/\\/g, "/");
516
+ return `import "${rel}";`;
517
+ }
518
+ function prependImportIfMissing(filePath, line) {
519
+ const raw = readFileSync(filePath, "utf8");
520
+ if (raw.includes("/styles/global.") || raw.includes("/styles/uno.css")) return;
521
+ writeFileSync(filePath, `${line}\n${raw}`, "utf8");
522
+ }
523
+ function writeTailwindFiles(root) {
524
+ const dir = join(root, "app", "styles");
525
+ mkdirSync(dir, {
526
+ recursive: true
527
+ });
528
+ writeFileSync(join(dir, "global.css"), '@import "tailwindcss";\n', "utf8");
529
+ writeFileSync(join(root, "postcss.config.mjs"), `export default {
530
+ plugins: {
531
+ "@tailwindcss/postcss": {},
532
+ autoprefixer: {},
533
+ },
534
+ };
535
+ `, "utf8");
536
+ }
537
+ function writeUnoFiles(root) {
538
+ const dir = join(root, "app", "styles");
539
+ mkdirSync(dir, {
540
+ recursive: true
541
+ });
542
+ writeFileSync(join(dir, "uno.css"), `@unocss preflights;
543
+ @unocss default;
544
+ `, "utf8");
545
+ writeFileSync(join(root, "postcss.config.mjs"), `import UnoCSS from "@unocss/postcss";
546
+
547
+ export default {
548
+ plugins: [UnoCSS()],
549
+ };
550
+ `, "utf8");
551
+ writeFileSync(join(root, "uno.config.ts"), `import { defineConfig, presetUno } from "unocss";
552
+
553
+ export default defineConfig({
554
+ content: {
555
+ filesystem: ["./app/**/*.{html,js,ts,jsx,tsx,vue,svelte}"],
556
+ },
557
+ presets: [presetUno()],
558
+ });
559
+ `, "utf8");
560
+ }
561
+ function writeLessSassFiles(root, engine) {
562
+ const dir = join(root, "app", "styles");
563
+ mkdirSync(dir, {
564
+ recursive: true
565
+ });
566
+ "less" === engine ? writeFileSync(join(dir, "global.less"), "body {\n margin: 0;\n}\n", "utf8") : writeFileSync(join(dir, "global.scss"), "body {\n margin: 0;\n}\n", "utf8");
567
+ }
568
+ function mergeDevDependencies(pkg, engine) {
569
+ const dev = pkg.devDependencies ?? {};
570
+ pkg.devDependencies = dev;
571
+ Object.assign(dev, DEPS[engine]);
572
+ }
573
+ function writeEngineFiles(root, engine) {
574
+ if ("tailwindcss" === engine) return void writeTailwindFiles(root);
575
+ if ("unocss" === engine) return void writeUnoFiles(root);
576
+ writeLessSassFiles(root, engine);
577
+ }
578
+ function applyStyleEngine(root, _framework, language, engine) {
579
+ if ("none" === engine) return;
580
+ const pkgPath = join(root, "package.json");
581
+ const pkg = readJsonFile(pkgPath);
582
+ mergeDevDependencies(pkg, engine);
583
+ writeJsonFile(pkgPath, pkg);
584
+ writeEngineFiles(root, engine);
585
+ const entries = listUiEntryScripts(root, language);
586
+ for (const file of entries)prependImportIfMissing(file, buildStyleImportLine(file, engine));
587
+ }
588
+ const cli_require = createRequire(import.meta.url);
589
+ try {
590
+ const figures = cli_require("prompts/lib/util/figures");
591
+ figures.radioOn = "\u25CF";
592
+ figures.radioOff = "\u25CB";
593
+ } catch {}
594
+ const SKILLS_REPO = "addfox/skills";
595
+ const orange = trueColor(230, 138, 46);
596
+ function getFrameworkChoicesColored() {
597
+ const colors = {
598
+ vanilla: gray,
599
+ vue: green,
600
+ react: cyan,
601
+ preact: yellow,
602
+ svelte: red,
603
+ solid: lightBlue
604
+ };
605
+ return FRAMEWORKS.map((f)=>({
606
+ ...f,
607
+ title: colors[f.value](f.title)
608
+ }));
609
+ }
610
+ function getLanguageChoicesColored() {
611
+ return [
612
+ {
613
+ title: cyan("TypeScript"),
614
+ value: "ts"
615
+ },
616
+ {
617
+ title: yellow("JavaScript"),
618
+ value: "js"
619
+ }
620
+ ];
621
+ }
622
+ function getPackageManagerChoicesColored() {
623
+ const colors = {
624
+ pnpm: orange,
625
+ npm: red,
626
+ yarn: blue,
627
+ bun: green
628
+ };
629
+ return PACKAGE_MANAGER_CHOICES.map((c)=>({
630
+ ...c,
631
+ title: colors[c.value](c.title)
632
+ }));
633
+ }
634
+ function getStyleEngineChoicesColored() {
635
+ const colors = {
636
+ none: dim,
637
+ tailwindcss: cyan,
638
+ unocss: green,
639
+ less: yellow,
640
+ sass: magenta
641
+ };
642
+ return STYLE_ENGINES.map((c)=>({
643
+ ...c,
644
+ title: colors[c.value](c.title)
645
+ }));
646
+ }
647
+ function getVersion() {
648
+ try {
649
+ const pkgPath = resolve(dirname(fileURLToPath(import.meta.url)), "..", "package.json");
650
+ const pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
651
+ return pkg.version ?? "0.0.0";
652
+ } catch {
653
+ return "0.0.0";
654
+ }
655
+ }
656
+ function printHelp() {
657
+ const version = getVersion();
658
+ console.log(`
659
+ create-addfox-app v${version}
660
+
661
+ Create a new addfox extension project
662
+
663
+ Usage:
664
+ create-addfox-app [project-name] [options]
665
+
666
+ Options:
667
+ --framework <name> Skip prompt: vanilla | vue | react | preact | svelte | solid
668
+ --language <lang> Skip prompt: js | ts
669
+ --help Show this help message
670
+ --version Show version number
671
+
672
+ Steps: 1) framework 2) style engine 3) language 4) package manager 5) entries
673
+ 6) test setup (optional unit / e2e) 7) Rsdoctor (optional)
674
+ 8) install skills
675
+
676
+ Options (non-interactive / skip prompts when used with --framework + --language):
677
+ --style <name> none | tailwindcss | unocss | less | sass (default: tailwindcss)
678
+ --unit Add rstest unit setup (with --framework and --language)
679
+ --e2e Add rstest E2E (Playwright browser) setup
680
+ --rsdoctor Add @rsdoctor/rspack-plugin (use addfox dev/build --report)
681
+ `);
682
+ }
683
+ const VALID_STYLE_ENGINES = new Set([
684
+ "none",
685
+ "tailwindcss",
686
+ "unocss",
687
+ "less",
688
+ "sass"
689
+ ]);
690
+ function parseStyleEngineArg(raw) {
691
+ const s = "string" == typeof raw ? raw.toLowerCase() : "";
692
+ if (VALID_STYLE_ENGINES.has(s)) return s;
693
+ return "tailwindcss";
694
+ }
695
+ async function confirmOverwrite(dir) {
696
+ const { action } = await prompts({
697
+ type: "select",
698
+ name: "action",
699
+ message: `Directory "${dir}" already exists. What would you like to do?`,
700
+ choices: [
701
+ {
702
+ title: "Cancel",
703
+ value: "cancel"
704
+ },
705
+ {
706
+ title: "Overwrite (replace contents)",
707
+ value: "overwrite"
708
+ }
709
+ ],
710
+ initial: 0
711
+ });
712
+ if (void 0 === action) return false;
713
+ return "overwrite" === action;
714
+ }
715
+ async function promptOptions() {
716
+ const res = await prompts([
717
+ {
718
+ type: "select",
719
+ name: "framework",
720
+ message: "Select a framework",
721
+ choices: getFrameworkChoicesColored()
722
+ },
723
+ {
724
+ type: "select",
725
+ name: "styleEngine",
726
+ message: "Select a style engine",
727
+ choices: getStyleEngineChoicesColored()
728
+ },
729
+ {
730
+ type: "select",
731
+ name: "language",
732
+ message: "Select a language",
733
+ choices: getLanguageChoicesColored()
734
+ },
735
+ {
736
+ type: "select",
737
+ name: "packageManager",
738
+ message: "Select package manager",
739
+ choices: getPackageManagerChoicesColored()
740
+ },
741
+ {
742
+ type: "multiselect",
743
+ name: "entries",
744
+ message: "Select extension entries",
745
+ choices: ENTRY_CHOICES,
746
+ min: 1,
747
+ initial: 0,
748
+ hint: "Space to toggle, Enter to confirm (○ unselected, ● selected)"
749
+ }
750
+ ]);
751
+ if (!res.framework || !res.styleEngine || !res.language || !res.packageManager || !res.entries?.length) return null;
752
+ return {
753
+ framework: res.framework,
754
+ styleEngine: res.styleEngine,
755
+ language: res.language,
756
+ packageManager: res.packageManager,
757
+ entries: res.entries
758
+ };
759
+ }
760
+ const TEST_KIND_CHOICES = [
761
+ {
762
+ title: "Unit — rstest (Node)",
763
+ value: "unit"
764
+ },
765
+ {
766
+ title: "E2E — rstest + Playwright (browser)",
767
+ value: "e2e"
768
+ }
769
+ ];
770
+ async function promptTestAndReport() {
771
+ const testRes = await prompts({
772
+ type: "multiselect",
773
+ name: "testKinds",
774
+ message: "Initialize test config? (optional)",
775
+ choices: TEST_KIND_CHOICES,
776
+ min: 0,
777
+ hint: "Space toggles, Enter confirms — leave empty to skip"
778
+ });
779
+ if (void 0 === testRes.testKinds) return null;
780
+ const docRes = await prompts({
781
+ type: "select",
782
+ name: "installRsdoctor",
783
+ message: "Install Rsdoctor (@rsdoctor/rspack-plugin) for bundle analysis? After install, use addfox dev or addfox build with --report.",
784
+ choices: [
785
+ {
786
+ title: "Yes",
787
+ value: true
788
+ },
789
+ {
790
+ title: "No",
791
+ value: false
792
+ }
793
+ ],
794
+ initial: 0
795
+ });
796
+ if (void 0 === docRes.installRsdoctor) return null;
797
+ return {
798
+ testKinds: testRes.testKinds ?? [],
799
+ installRsdoctor: Boolean(docRes.installRsdoctor)
800
+ };
801
+ }
802
+ function resolveTestSelectionFromArgv(argv) {
803
+ const kinds = [];
804
+ if (argv.unit) kinds.push("unit");
805
+ if (argv.e2e) kinds.push("e2e");
806
+ return {
807
+ testKinds: kinds,
808
+ installRsdoctor: Boolean(argv.rsdoctor)
809
+ };
810
+ }
811
+ function updatePackageName(destDir, projectName) {
812
+ const pkgPath = resolve(destDir, "package.json");
813
+ if (!existsSync(pkgPath)) return;
814
+ const pkg = readJsonFile(pkgPath);
815
+ pkg.name = projectName.replace(/\s+/g, "-").toLowerCase();
816
+ writeJsonFile(pkgPath, pkg);
817
+ }
818
+ async function main() {
819
+ const argv = minimist(process.argv.slice(2));
820
+ if (argv.help || argv.h) return void printHelp();
821
+ if (argv.version || argv.v) return void console.log(getVersion());
822
+ const targetDir = argv._[0] ?? "my-extension";
823
+ const cliFramework = argv.framework;
824
+ const cliLanguage = argv.language;
825
+ printAddfoxLogo(orange);
826
+ console.log(blue("\n Create Addfox App\n"));
827
+ const root = resolve(process.cwd(), targetDir);
828
+ if (existsSync(root)) {
829
+ const confirmed = await confirmOverwrite(targetDir);
830
+ if (!confirmed) process.exit(0);
831
+ }
832
+ const options = cliFramework && cliLanguage ? {
833
+ framework: cliFramework,
834
+ styleEngine: parseStyleEngineArg(argv.style),
835
+ language: cliLanguage,
836
+ packageManager: detectPackageManager(),
837
+ entries: [
838
+ "__all__"
839
+ ]
840
+ } : await promptOptions();
841
+ if (!options) process.exit(0);
842
+ const testSelection = cliFramework && cliLanguage ? resolveTestSelectionFromArgv(argv) : await promptTestAndReport();
843
+ if (!testSelection) process.exit(0);
844
+ const pm = options.packageManager;
845
+ const templateName = getTemplateName(options.framework, options.language);
846
+ console.log(yellow("\n Downloading template...\n"));
847
+ try {
848
+ tryLocalTemplates(templateName, root) || await downloadTemplate(templateName, root);
849
+ } catch (err) {
850
+ console.error(red(`\n Failed to download template: ${err.message}\n`));
851
+ process.exit(1);
852
+ }
853
+ const useAllEntries = options.entries.includes("__all__");
854
+ const existingDirs = getExistingAppEntryDirs(root);
855
+ const effectiveEntries = useAllEntries ? [
856
+ "__all__"
857
+ ] : options.entries.filter((e)=>"__all__" !== e && existingDirs.includes(e));
858
+ if (!useAllEntries && effectiveEntries.length > 0) filterAppEntries(root, effectiveEntries);
859
+ const configExt = "ts" === options.language ? "ts" : "js";
860
+ const configPath = resolve(root, `addfox.config.${configExt}`);
861
+ const configContent = generateAddfoxConfig(options.framework, options.language, options.styleEngine);
862
+ writeFileSync(configPath, configContent, "utf-8");
863
+ updatePackageName(root, targetDir);
864
+ applyStyleEngine(root, options.framework, options.language, options.styleEngine);
865
+ applyTestAndReportSetup(root, options.language, testSelection);
866
+ const installCmd = getInstallCommand(pm);
867
+ const devCmd = getRunCommand(pm, "dev");
868
+ const { installSkills } = await prompts({
869
+ type: "select",
870
+ name: "installSkills",
871
+ message: "Install addfox skills?",
872
+ choices: [
873
+ {
874
+ title: "Yes",
875
+ value: true
876
+ },
877
+ {
878
+ title: "No",
879
+ value: false
880
+ }
881
+ ],
882
+ initial: 0
883
+ });
884
+ if (true === installSkills) {
885
+ const execCmd = getExecCommand(pm);
886
+ const fullCmd = `${execCmd} skills add ${SKILLS_REPO}`;
887
+ console.log(yellow("\n Running: " + fullCmd + "\n"));
888
+ try {
889
+ execSync(fullCmd, {
890
+ cwd: root,
891
+ stdio: "inherit"
892
+ });
893
+ } catch {
894
+ console.log(dim(" (Skills install skipped or failed; you can run it later.)\n"));
895
+ }
896
+ }
897
+ console.log(green("\n ✓ Project created successfully\n"));
898
+ console.log(dim(" Next steps:\n"));
899
+ console.log(` cd ${targetDir}`);
900
+ console.log(` ${installCmd}`);
901
+ console.log(` ${devCmd}\n`);
902
+ }
903
+ main().catch((e)=>{
904
+ console.error(e);
905
+ process.exit(1);
906
+ });
package/package.json ADDED
@@ -0,0 +1,34 @@
1
+ {
2
+ "name": "create-addfox-app",
3
+ "version": "0.1.1-beta.3",
4
+ "description": "Interactive scaffolder for addfox extension projects",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "bin": {
8
+ "create-addfox-app": "./dist/cli.js"
9
+ },
10
+ "files": [
11
+ "dist",
12
+ "LICENSE"
13
+ ],
14
+ "dependencies": {
15
+ "chalk": "^5.3.0",
16
+ "prompts": "^2.4.2",
17
+ "kolorist": "^1.8.0",
18
+ "minimist": "^1.2.8",
19
+ "@addfox/pkg-manager": "0.1.1-beta.3"
20
+ },
21
+ "devDependencies": {
22
+ "@rslib/core": "^0.20.0",
23
+ "@rstest/core": "^0.9.2",
24
+ "@rstest/coverage-istanbul": "^0.3.0",
25
+ "@types/node": "^20.0.0",
26
+ "typescript": "^5.0.0"
27
+ },
28
+ "scripts": {
29
+ "build": "rslib build",
30
+ "start": "node dist/cli.js",
31
+ "test": "rstest run",
32
+ "test:coverage": "rstest run --coverage"
33
+ }
34
+ }