create-fsaa 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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Veaceslav Bezusco
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 CHANGED
@@ -1,3 +1,160 @@
1
- # Temporary Holding Version
1
+ <img width="814" height="243" alt="image" src="https://github.com/user-attachments/assets/047ea0c4-ae54-43f1-9dd9-2a8805839ed0" />
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
+ # FSAA — Feature-Sliced Atomic Architecture ⚡
4
+
5
+ > **FSD + Atomic Design with the missing decision rules: *where does UI go?***
6
+
7
+ [![templates](https://img.shields.io/badge/templates-fsaa--react%20·%20fsaa--vite-43e0bd)](https://aramex86.github.io/fsaa/)
8
+ [![docs](https://img.shields.io/badge/docs-aramex86.github.io%2Ffsaa-7ab8ff)](https://aramex86.github.io/fsaa/)
9
+ ![license](https://img.shields.io/badge/license-MIT-b79bff)
10
+ ![methodology](https://img.shields.io/badge/status-v0.3%20draft-ffcf6b)
11
+
12
+ * 💡 **Three decision rules** — graduation, boundary test, organisms eliminated
13
+ * 🔒 **ESLint-enforced boundaries** — wrong imports fail lint, not code review
14
+ * 🧩 **Two templates** — Next.js App Router · plain React (Vite + react-router)
15
+ * 🤖 **Agentic by default** — AGENTS.md contract with CI drift-check, step-by-step agent procedures, navigation skill for external agents
16
+ * 🚀 **Self-demonstrating** — the docs site is itself built on FSAA
17
+ * 🏭 **Production-proven** — internal financial tool, real daily users
18
+ * 📖 **Inspectable without NDA** — open code, open docs, open issues
19
+
20
+ <div align="center">
21
+
22
+ **[Read the docs →](https://aramex86.github.io/fsaa/)** · **[Next.js template →](https://github.com/Aramex86/fsaa-next)** · **[Plain React template →](https://github.com/Aramex86/fsaa-vite)**
23
+
24
+ </div>
25
+
26
+ FSAA is not a new architecture theory. It is a practical, opinionated assembly of two proven methods — Feature-Sliced Design and Atomic Design — with the missing decision rules added. We do not claim a revolution.
27
+
28
+ ## Status
29
+
30
+ > **Phase 0–2 (done):** methodology frozen, docs site live and indexed, starter templates shipped — [fsaa-next](https://github.com/Aramex86/fsaa-next) (Next.js App Router) and [fsaa-vite](https://github.com/Aramex86/fsaa-vite) (plain React) with **ESLint-enforced layer boundaries**: wrong imports fail lint, not code review. **Phase 3 (in progress):** the agentic machine — an [AGENTS.md contract](https://github.com/Aramex86/fsaa-next/blob/main/AGENTS.md) where every rule carries a CI check marker, a **drift-check** that fails the build when docs and code drift apart, `agents/` step-by-step procedures, and [`where-ui-goes`](https://github.com/Aramex86/fsaa-next/blob/main/agents/where-ui-goes.md) — a navigation skill for external agents ([how it works →](https://aramex86.github.io/fsaa/agentic/)).
31
+
32
+ Used in production (internal tool) with real daily users — and **self-demonstrating**: this documentation site is itself built on FSAA (features/entities/shared, thin routes), so the architecture is inspectable without NDA. Both templates clone the same structure with working Projects/Orders examples. Public example app — Phase 2.
33
+
34
+ ## The problem
35
+
36
+ Every frontend developer on a medium+ project hits the same wall: **"where do I put this component?"**
37
+
38
+ - Feature-Sliced Design (FSD) answers *where does code live and how does it access business logic* — but is silent on UI composition, and its `widgets` layer is controversial.
39
+ - Atomic Design answers *how does a component look and compose* (atoms → molecules → organisms) — but says nothing about business logic, and `organisms/` folders tend to become dumping grounds.
40
+ - Bulletproof React is a set of good advice, not an architecture — nothing enforces boundaries.
41
+
42
+ FSAA combines them additively and adds the three missing decision rules.
43
+
44
+ ## The layer stack
45
+
46
+ Imports flow **only downward**, with **no layer skipping** and **no circular dependencies**. Every module exposes a public API via `index.ts`.
47
+
48
+ | Layer | Responsibility | Can import from |
49
+ |---|---|---|
50
+ | `app` | Router, providers, global config, initialization | `shared` only |
51
+ | `pages` | Route-level compositions | `features`, `shared` |
52
+ | `features` | User scenarios **and** large page-level blocks | `entities`, `shared` |
53
+ | `entities` | Business models + data access | `shared` |
54
+ | `shared` | Design tokens, generic UI primitives, utilities | external libs only |
55
+
56
+ There is deliberately **no `widgets` layer** — features double as page-level blocks. One decision less per component.
57
+
58
+ ### FSAA & Next.js App Router
59
+
60
+ Next.js names collide with FSAA layers: its `app/` folder holds routes and `pages/` is the Pages Router. Renaming layers to `_app`/`_pages` (the standard FSD workaround) is not needed in FSAA. Instead, **the `pages` layer is replaced by the App Router itself** — route files are the page compositions:
61
+
62
+ ```
63
+ src/
64
+ features/ # user scenarios incl. large page-level blocks
65
+ entities/ # business models + data access
66
+ shared/ # tokens, atoms/molecules, utilities
67
+ app/
68
+ dashboard/page.tsx # thin: import DashboardOverview, render, wrap in <Suspense>
69
+ orders/page.tsx # thin: import OrdersOverview, render, wrap in <Suspense>
70
+ ```
71
+
72
+ A thin route file (import → render → Suspense) **is** the page composition — no `_app`/`_pages` prefixes, no lint conflict. Everything else works unchanged: the three decision rules and the layer stack above.
73
+
74
+ ## Three decision rules (the actual value)
75
+
76
+ ### 1. The Graduation pattern
77
+
78
+ Feature-local UI lives **flat** in `features/<name>/ui/` — 5–10 components, no Atomic Design inside a feature, the scope is already narrow. When a component proves reusable **in another feature**, it graduates: promoted to `shared/ui` and reorganized into atoms/molecules.
79
+
80
+ Features own their UI until it earns sharing.
81
+
82
+ **Mechanics.** The trigger is objective — a component is needed by a *second independent feature*. The first duplicate is legal: one copy is a signal, not a catastrophe. Promotion = **one PR**: the component moves to `shared/ui/molecules/`, both features import it from the shared public API (`index.ts`), and the feature-local copies are deleted inside that same changeset. Cross-feature imports are a lint error, so a copy-pasted component fails CI — drift cannot hide, the only legal cross-feature sources are entities (data) and shared (UI). (The starter templates ship this enforcement — see Phase 2 in the roadmap.)
83
+
84
+ ### 2. The boundary test for `shared`
85
+
86
+ > *If I removed this component from the app entirely, could it still be described without mentioning users, orders, or projects?*
87
+
88
+ Yes → `shared`. No → feature. A generic `DataTable` passes this test; `projectColumns` does not.
89
+
90
+ ### 3. Organisms are eliminated
91
+
92
+ A large composition — what Atomic Design would call an organism — **is a feature**. The Presentational/Container split happens at the export level (one file may export both `UserListContainer` and `UserList`), not the filesystem level.
93
+
94
+ ## Atomic Design placement
95
+
96
+ Atomic levels live **inside `shared/ui` only**:
97
+
98
+ | Level | Location | Examples |
99
+ |---|---|---|
100
+ | Atoms | `shared/ui/atoms` | `Button`, `Input`, `TableCell` |
101
+ | Molecules | `shared/ui/molecules` | `DataTable`, `FormRow`, `SearchField` |
102
+
103
+ ## Canonical example: one table, two entities
104
+
105
+ ```
106
+ src/
107
+ shared/ui/atoms/TableCell.tsx
108
+ shared/ui/atoms/TableHeaderCell.tsx
109
+ shared/ui/molecules/table/DataTable.tsx # generic: columns, data, isLoading
110
+ entities/project/ # project data access + types
111
+ entities/order/ # order data access + types
112
+ features/projects-overview/
113
+ config/projectColumns.tsx # columns from shared atoms + feature actions
114
+ ui/ProjectsOverview.tsx # wires useProjects + projectColumns + DataTable
115
+ features/orders-overview/
116
+ config/orderColumns.tsx
117
+ ui/OrdersOverview.tsx
118
+ pages/ProjectsPage.tsx # renders ProjectsOverview
119
+ pages/OrdersPage.tsx # renders OrdersOverview
120
+ ```
121
+
122
+ **The rule:** the table stays generic; business-specific columns live in their features. If two entities need the same visual pattern, extract the pattern into `shared` — keep the entity-specific configuration in `features`.
123
+
124
+ **Runnable code:** this exact structure ships in the starter templates — [fsaa-next (Next.js App Router)](https://github.com/Aramex86/fsaa-next) and [fsaa-vite (plain React SPA)](https://github.com/Aramex86/fsaa-vite), both with the Projects/Orders example working (`npm run dev` → `/projects`, `/orders`). A step-by-step trace lives in the [docs' worked example](https://aramex86.github.io/fsaa/example/).
125
+
126
+ ## Comparison
127
+
128
+ | Method | What it answers | What it misses |
129
+ |---|---|---|
130
+ | **FSAA** | Where UI goes + where code lives + how UI composes | — (this is the assembly) |
131
+ | FSD | Where code lives, import boundaries | Where UI goes; `widgets` is controversial; high entry threshold |
132
+ | Atomic Design | How components look and compose | Nothing about business logic; `organisms/` becomes a dumping ground |
133
+ | Bulletproof React | Good defaults per concern | No enforced boundaries — not an architecture |
134
+
135
+ **"Isn't this just FSD + Atomic Design?"** — Yes, deliberately. The value is not novelty; it is the three decision rules neither method provides: graduation, the boundary test, no organisms.
136
+
137
+ ## When to use it
138
+
139
+ **Good fit:** medium+ projects, teams of 3+, long-lived products, design-system-driven UI.
140
+
141
+ **Not a fit:** throwaway prototypes, MVPs with a 2-week lifespan, tiny apps where folder structure is not the bottleneck.
142
+
143
+ ## Roadmap
144
+
145
+ | Phase | Focus | Status |
146
+ |---|---|---|
147
+ | 0 | Repo, honest README, CONTRIBUTING | ✅ done (this repo) |
148
+ | 1 | Docs site (indexable: OG, sitemap, GSC) | ✅ [aramex86.github.io/fsaa](https://aramex86.github.io/fsaa/) |
149
+ | 2 | Boilerplate — two templates: [Next.js App Router](https://github.com/Aramex86/fsaa-next) + [plain React (Vite)](https://github.com/Aramex86/fsaa-vite), ESLint-enforced boundaries, Projects/Orders example | ✅ done |
150
+ | 3 | Agentic layer — AGENTS.md contract, CI drift-check, `agents/` procedures, external-agent skill | ✅ done ([docs](https://aramex86.github.io/fsaa/agentic/)) |
151
+ | 4 | CLI — `npm create fsaa@latest` (scaffolds next/vite) + `fsaa g <slice>` generator | 🟢 core shipped ([`fsaa` repo](https://github.com/Aramex86/fsaa)); npm registry package next |
152
+ | 5 | Promotion, adoption feedback loop | — |
153
+
154
+ ## Contributing
155
+
156
+ See [CONTRIBUTING.md](./CONTRIBUTING.md). Questions about a component's place in the structure are the most valuable contributions — open an issue with your case.
157
+
158
+ ## License
159
+
160
+ MIT © Veaceslav Bezusco
package/bin/fsaa.mjs ADDED
@@ -0,0 +1,12 @@
1
+ #!/usr/bin/env node
2
+ /* FSAA CLI — scaffold apps from the official starters and generate canonical slices. */
3
+ import { run } from "../lib/cli.mjs";
4
+ run(process.argv.slice(2)).then(
5
+ (code) => process.exit(code),
6
+ (err) => {
7
+ console.error("fsaa: unexpected error");
8
+ if (err && err.stack) console.error(err.stack.split("\n").slice(0, 3).join("\n"));
9
+ else console.error(String(err));
10
+ process.exit(1);
11
+ },
12
+ );
package/lib/cli.mjs ADDED
@@ -0,0 +1,85 @@
1
+ /* fsaa/lib/cli.mjs — command dispatch, flag parsing, interactive prompts (zero deps). */
2
+ import readline from "node:readline/promises";
3
+ import { stdin, stdout } from "node:process";
4
+ import { initCmd } from "./init.mjs";
5
+ import { generateCmd } from "./generate.mjs";
6
+
7
+ export function parseFlags(argv) {
8
+ const flags = {};
9
+ const rest = [];
10
+ for (let i = 0; i < argv.length; i++) {
11
+ const a = argv[i];
12
+ if (a.startsWith("--")) {
13
+ const k = a.slice(2);
14
+ const next = argv[i + 1];
15
+ if (next === undefined || next.startsWith("--")) {
16
+ flags[k] = true; // boolean flag
17
+ } else {
18
+ flags[k] = next;
19
+ i++;
20
+ }
21
+ } else {
22
+ rest.push(a);
23
+ }
24
+ }
25
+ return { flags, rest };
26
+ }
27
+
28
+ function isInteractive() {
29
+ return stdin.isTTY === true;
30
+ }
31
+
32
+ export async function prompt(question, fallback = "") {
33
+ const rl = readline.createInterface({ input: stdin, output: stdout });
34
+ try {
35
+ const answer = await rl.question(question);
36
+ return answer.trim() || fallback;
37
+ } finally {
38
+ rl.close();
39
+ }
40
+ }
41
+
42
+ const HELP = `FSAA CLI v0.1 — Feature-Sliced Atomic Architecture
43
+ (npm package: create-fsaa — run it as `npm create fsaa@latest`)
44
+
45
+ init Scaffold a new app from an official FSAA starter template
46
+ g Generate a canonical feature slice inside an existing FSAA app
47
+ help Show this help
48
+
49
+ init usage:
50
+ fsaa init # interactive (name, template, manager)
51
+ fsaa init --name my-app --template vite --manager npm # non-interactive
52
+
53
+ g usage (run inside a project scaffolded by fsaa init):
54
+ fsaa g <slice-name> # e.g. fsaa g checkout
55
+
56
+ Docs: https://aramex86.github.io/fsaa
57
+ `;
58
+
59
+ async function unknown(cmd) {
60
+ console.error(`fsaa: unknown command "${cmd}" — run "fsaa help" for usage.`);
61
+ return 1;
62
+ }
63
+
64
+ export async function run(argv) {
65
+ const [cmd, ...rest] = argv;
66
+ const { flags } = parseFlags(rest);
67
+ switch (cmd) {
68
+ case "init":
69
+ return initCmd({ flags, interactive: isInteractive(), prompt });
70
+ case "g":
71
+ case "generate":
72
+ return generateCmd({ args: rest, flags, interactive: isInteractive(), prompt });
73
+ case "help":
74
+ case "--help":
75
+ case "-h":
76
+ console.log(HELP);
77
+ return 0;
78
+ default:
79
+ if (!cmd) {
80
+ console.log(HELP);
81
+ return 0;
82
+ }
83
+ return unknown(cmd);
84
+ }
85
+ }
@@ -0,0 +1,64 @@
1
+ /* fsaa/lib/download.mjs — degit-style fetch of a template repo tarball (zero deps).
2
+ Downloads the codeload tar.gz, extracts with the system `tar` (ships with
3
+ Linux, macOS, Windows 10+), then moves the tarball's root folder to the target dir. */
4
+ import { mkdtempSync, mkdirSync, readdirSync, writeFileSync, rmSync, renameSync, cpSync, existsSync, readFileSync } from "node:fs";
5
+ import { tmpdir } from "node:os";
6
+ import { join } from "node:path";
7
+ import { spawnSync } from "node:child_process";
8
+ import { fetchFile } from "./net.mjs";
9
+
10
+ export const TEMPLATES = {
11
+ next: { repo: "Aramex86/fsaa-next", label: "Next.js App Router" },
12
+ vite: { repo: "Aramex86/fsaa-vite", label: "plain React (Vite + react-router)" },
13
+ };
14
+
15
+ export function templateLabel(template) {
16
+ return TEMPLATES[template]?.label ?? template;
17
+ }
18
+
19
+ /** Download template@main and unpack its root folder contents into targetDir. */
20
+ export async function fetchTemplate(template, targetDir) {
21
+ const t = TEMPLATES[template];
22
+ if (!t) throw new Error(`unknown template "${template}"`);
23
+ const tmp = mkdtempSync(join(tmpdir(), "fsaa-template-"));
24
+ try {
25
+ const tgz = join(tmp, "template.tar.gz");
26
+ writeFileSync(tgz, await fetchFile(TARBALL_URL(t.repo)));
27
+ const x = join(tmp, "x");
28
+ mkdirSync(x, { recursive: true });
29
+ const r = spawnSync("tar", ["-xzf", tgz, "-C", x], { stdio: "pipe" });
30
+ if (r.status !== 0) {
31
+ const msg = (r.stderr || "tar not found on PATH").toString().trim().slice(0, 160);
32
+ throw new Error(`tar extract failed: ${msg}`);
33
+ }
34
+ const entries = readdirSync(x);
35
+ if (entries.length !== 1) throw new Error("unexpected tarball layout");
36
+ moveDir(join(x, entries[0]), targetDir);
37
+ return t.repo;
38
+ } finally {
39
+ rmSync(tmp, { recursive: true, force: true });
40
+ }
41
+ }
42
+
43
+ const TARBALL_URL = (repo) => `https://codeload.github.com/${repo}/tar.gz/refs/heads/main`;
44
+
45
+ function moveDir(src, dest) {
46
+ // dest must not exist as a directory: rename would nest (same for `mv`, `move`, and cp fallback).
47
+ // Callers guarantee a non-existent dest (init/generate check first).
48
+ if (existsSync(dest)) {
49
+ throw new Error(
50
+ `destination already exists: ${dest}\n` +
51
+ ` (safeguard: refuse to overwrite; run fsaa in an empty or non-existent directory)`,
52
+ );
53
+ }
54
+ // fs-only move: rename first (same volume), cpSync fallback (cross-device).
55
+ // No shell on any platform — no cmd quoting traps, no /move cross-drive traps.
56
+ try {
57
+ renameSync(src, dest);
58
+ return;
59
+ } catch (err) {
60
+ if (err?.code !== "EXDEV") throw err;
61
+ }
62
+ cpSync(src, dest, { recursive: true });
63
+ rmSync(src, { recursive: true, force: true });
64
+ }
@@ -0,0 +1,162 @@
1
+ /* fsaa/lib/generate.mjs — fsaa g <slice>: generate a canonical slice pair
2
+ (entity + feature) inside an existing FSAA app, per agents/add-module.md:
3
+ entity = index/types/api/slice + tests (flat); feature = index/ui/config +
4
+ tests; thin route file; nothing else outside the layers. */
5
+ import { existsSync, readFileSync, writeFileSync, mkdirSync } from "node:fs";
6
+ import { join, resolve } from "node:path";
7
+ import { entityFiles, featureFiles, pascal } from "./snippets.mjs";
8
+
9
+ export async function generateCmd({ args }) {
10
+ const [raw] = args.filter((a) => !a.startsWith("--"));
11
+ if (!raw) {
12
+ console.error("fsaa g: missing slice name — usage: fsaa g <slice-name> (e.g. fsaa g checkout)");
13
+ return 1;
14
+ }
15
+ const name = raw.toLowerCase();
16
+ // no leading digit, no trailing dash, no double dash — each segment is a
17
+ // valid identifier fragment so pascal()/camel() can never crash
18
+ if (!/^[a-z][a-z0-9]*(-[a-z0-9]+)*$/.test(name)) {
19
+ console.error(`fsaa g: invalid slice name "${raw}" — lowercase words/digits joined by single dashes (e.g. invoices-overview)`);
20
+ return 1;
21
+ }
22
+ const Title = pascal(name);
23
+
24
+ const cwd = resolve(process.cwd());
25
+ const detected = detectTemplate(cwd);
26
+ if (!detected) {
27
+ console.error('fsaa g: run this inside an FSAA app (scaffolded by "fsaa init")');
28
+ return 1;
29
+ }
30
+ const { template } = detected;
31
+
32
+ const pagePath = template === "vite"
33
+ ? join(cwd, "src", "pages", `${Title}Page.tsx`)
34
+ : join(cwd, "app", name, "page.tsx");
35
+ if (existsSync(pagePath)) {
36
+ console.error(`fsaa g: page already exists: ${pagePath} — pick another slice name or remove the old page first`);
37
+ return 1;
38
+ }
39
+
40
+ const featureDir = join(cwd, "src", "features", name);
41
+ const entityDir = join(cwd, "src", "entities", name);
42
+ if (existsSync(featureDir) || existsSync(entityDir)) {
43
+ console.error(`fsaa g: slice already exists: src/features/${name} (and/or src/entities/${name})`);
44
+ return 1;
45
+ }
46
+
47
+ writeTree(join(entityDir), entityFiles(name));
48
+ writeTree(join(featureDir), featureFiles(name, template));
49
+
50
+ if (template === "vite") {
51
+ const routerPath = join(cwd, "src", "pages", "router.tsx");
52
+ let router;
53
+ try {
54
+ router = readFileSync(routerPath, "utf8");
55
+ } catch {
56
+ router = null;
57
+ }
58
+ write(pagePath, vitePage(name, Title));
59
+ if (router && !router.includes(`./${Title}Page`)) {
60
+ if (router.includes(`<Route path="/${name}"`)) {
61
+ console.log(` (route /${name} already registered — router.tsx untouched)`);
62
+ } else {
63
+ const withRoute = addRoute(router, `<Route path="/${name}" element={<${Title}Page />} />`);
64
+ if (withRoute) {
65
+ writeFileSync(routerPath, addImport(withRoute, `import { ${Title}Page } from './${Title}Page';`));
66
+ } else {
67
+ console.error(` (no </Routes> found in router.tsx — add the import+route by hand, see agents/add-module.md)`);
68
+ }
69
+ }
70
+ }
71
+ } else {
72
+ write(join(cwd, "app", name, "page.tsx"), nextPage(name, Title));
73
+ }
74
+
75
+ console.log(`
76
+ ✔ src/entities/${name}/ (index.ts, types.ts, api.ts, slice.ts, __tests__/)
77
+ ✔ src/features/${name}/ (index.ts, ui/, config/, __tests__/)
78
+ ✔ thin route registered${template === "next" ? " (app/" + name + "/page.tsx)" : " (src/pages/" + Title + "Page.tsx + router.tsx)"}
79
+
80
+ Verify (agents/add-module.md):
81
+ pnpm lint · pnpm typecheck · pnpm test
82
+ node scripts/check-agents-md.mjs`);
83
+ return 0;
84
+ }
85
+
86
+ export function detectTemplate(cwd) {
87
+ const marker = join(cwd, ".fsaa.json");
88
+ if (existsSync(marker)) {
89
+ try {
90
+ const m = JSON.parse(readFileSync(marker, "utf8"));
91
+ if (m.template === "vite" || m.template === "next") return { template: m.template };
92
+ } catch {
93
+ /* broken marker — fall through to file detection */
94
+ }
95
+ }
96
+ for (const cfg of ["next.config.mjs", "next.config.js", "next.config.ts"]) {
97
+ if (existsSync(join(cwd, cfg))) return { template: "next" };
98
+ }
99
+ if (existsSync(join(cwd, "vite.config.mjs")) || existsSync(join(cwd, "vite.config.ts"))) return { template: "vite" };
100
+ return null;
101
+ }
102
+
103
+ function addImport(src, importLine) {
104
+ const lines = src.split("\n");
105
+ // insert after the last COMPLETE single-line import; multiline imports
106
+ // ("import {", no "from") would break if we spliced inside them
107
+ const lastImport = lines.reduce(
108
+ (acc, l, i) => (l.trim().startsWith("import ") && l.includes("from") ? i : acc),
109
+ -1,
110
+ );
111
+ if (lastImport === -1) return importLine + "\n" + src;
112
+ lines.splice(lastImport + 1, 0, importLine);
113
+ return lines.join("\n");
114
+ }
115
+
116
+ function addRoute(src, routeLine) {
117
+ const lines = src.split("\n");
118
+ const closeIdx = lines.findIndex((l) => l.includes("</Routes>"));
119
+ if (closeIdx === -1) return null;
120
+ // indent matches the sibling <Route> lines, not the closing tag
121
+ const sibling = lines.find((l) => l.trim().startsWith("<Route "));
122
+ const routeIndent = sibling ? (sibling.match(/^\s*/) || [" "])[0] : " ";
123
+ lines.splice(closeIdx, 0, routeIndent + routeLine.trim());
124
+ return lines.join("\n");
125
+ }
126
+
127
+ function writeTree(dir, files) {
128
+ for (const [rel, content] of Object.entries(files)) {
129
+ const path = join(dir, rel);
130
+ mkdirSync(join(path, ".."), { recursive: true });
131
+ writeFileSync(path, content);
132
+ }
133
+ }
134
+
135
+ function write(path, content) {
136
+ mkdirSync(join(path, ".."), { recursive: true });
137
+ writeFileSync(path, content);
138
+ }
139
+
140
+ export { vitePage, nextPage };
141
+
142
+ function vitePage(name, Title) {
143
+ return `import { ${pascal(name)}Overview } from "@features/${name}";
144
+
145
+ /* Thin page composition (FSAA pages layer). */
146
+
147
+ export function ${Title}Page() {
148
+ return <${pascal(name)}Overview />;
149
+ }
150
+ `;
151
+ }
152
+
153
+ function nextPage(name, Title) {
154
+ return `import { ${pascal(name)}Overview } from '@features/${name}';
155
+
156
+ /* app/${name}/page.tsx — thin FSAA route. */
157
+
158
+ export default function ${Title}Page() {
159
+ return <${pascal(name)}Overview />;
160
+ }
161
+ `;
162
+ }
package/lib/init.mjs ADDED
@@ -0,0 +1,132 @@
1
+ /* fsaa/lib/init.mjs — fsaa init: scaffold an app from an official FSAA starter. */
2
+ import { existsSync, readFileSync, writeFileSync, rmSync, statSync, readdirSync } from "node:fs";
3
+ import { join, resolve } from "node:path";
4
+ import { spawnSync } from "node:child_process";
5
+ import { fetchTemplate, TEMPLATES, templateLabel } from "./download.mjs";
6
+ import { prompt } from "./cli.mjs";
7
+
8
+ export async function initCmd({ flags, interactive }) {
9
+ console.log("> FSAA init — Feature-Sliced Atomic Architecture\n");
10
+
11
+ let name = flags.name;
12
+ let template = flags.template;
13
+
14
+ if (!name) name = await prompt("App name [my-app]: ", "my-app");
15
+ if (!template) {
16
+ const answer = await prompt("Template — 1) next (Next.js App Router) 2) vite (plain React) [next]: ", "next");
17
+ template = answer.startsWith("2") ? "vite" : "next";
18
+ }
19
+
20
+ name = name || "my-app";
21
+ template = template || "next";
22
+ const manager = "pnpm"; // contract pin (single-lockfile rule lives on pnpm)
23
+
24
+ if (typeof flags.dir !== "undefined" && typeof flags.dir !== "string") {
25
+ throw new Error("--dir needs a value: fsaa init --dir ./somewhere");
26
+ }
27
+ validate(name, template);
28
+
29
+ const dest = resolve(flags.dir || ".", name);
30
+ if (existsSync(dest)) {
31
+ if (!flags.force) {
32
+ console.error(`fsaa: directory already exists: ${dest} (add --force to use an EMPTY directory; non-existing is preferred)`);
33
+ return 1;
34
+ }
35
+ if (!statSync(dest).isDirectory()) {
36
+ console.error(`fsaa: --force target is not a directory: ${dest}`);
37
+ return 1;
38
+ }
39
+ const left = readdirSync(dest).filter((e) => e !== ".git" && e !== ".gitignore");
40
+ if (left.length > 0) {
41
+ console.error(`fsaa: refusing --force: directory is not empty: ${dest} (${left.length} items) — move away or delete them yourself`);
42
+ return 1;
43
+ }
44
+ rmSync(dest, { recursive: true });
45
+ }
46
+
47
+ console.log(` template: ${templateLabel(template)}`);
48
+ console.log(` manager: pnpm (contract)`);
49
+ console.log(` target: ${dest}\n`);
50
+
51
+ console.log("> downloading template (codeload tarball)…");
52
+ await fetchTemplate(template, dest);
53
+ stamp(dest, { template });
54
+
55
+ console.log("> renaming project…");
56
+ const pkgPath = join(dest, "package.json");
57
+ const pkg = JSON.parse(readFileSync(pkgPath, "utf8"));
58
+ pkg.name = name;
59
+ writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + "\n");
60
+
61
+ // Windows: pnpm ships as pnpm.cmd; spawning a bare "pnpm" on win32 fails
62
+ // (Node ≥18.20 refuses .cmd/.bat without shell). Use the .cmd shim there.
63
+ const pnpmBin = process.platform === "win32" ? "pnpm.cmd" : "pnpm";
64
+ console.log("> installing dependencies (this may take a minute)…");
65
+ const r = spawnSync(pnpmBin, ["install"], { cwd: dest, stdio: "inherit" });
66
+ if (r.error) {
67
+ console.error('\nfsaa: pnpm not found on PATH — the FSAA contract pins pnpm.');
68
+ console.error(' enable it: corepack enable pnpm or: npm i -g pnpm');
69
+ return 1;
70
+ }
71
+ if (r.status !== 0) {
72
+ console.error("fsaa: dependency install failed — the template files are in place; fix your PATH or run install manually.");
73
+ return 1;
74
+ }
75
+ // single-lockfile contract: the template ships pnpm-lock.yaml — an npm install
76
+ // adds package-lock.json next to it, which makes drift-check red. Keep exactly one.
77
+ const otherLock = join(dest, "package-lock.json");
78
+ if (existsSync(otherLock)) rmSync(otherLock);
79
+
80
+ console.log("\n> running the contract drift-check as proof…");
81
+ const dc = spawnSync("node", ["scripts/check-agents-md.mjs"], { cwd: dest, stdio: "inherit" });
82
+ if (dc.status !== 0) {
83
+ console.error("fsaa: drift-check is red after init — report this: https://github.com/Aramex86/fsaa/issues");
84
+ return 1;
85
+ }
86
+
87
+ gitInit(dest, "feat/init", nameSafe(dest));
88
+
89
+ console.log(`\n${"=".repeat(52)}`);
90
+ console.log(` ✔ ${name} is ready (${templateLabel(template)})`);
91
+ console.log(` cd ${dest}`);
92
+ console.log(` ${manager} run dev`);
93
+ console.log(` agent contract: AGENTS.md · skills: agents/`);
94
+ console.log(` generate slices: ${manager === "pnpm" ? "pnpm exec" : "npx"} fsaa g <slice-name> (or: npx create-fsaa g <slice-name>)`);
95
+ console.log("=".repeat(52));
96
+ return 0;
97
+ }
98
+
99
+ function validate(name, template) {
100
+ if (!TEMPLATES[template]) {
101
+ throw new Error(`unknown template "${template}" — choose: ${Object.keys(TEMPLATES).join(" | ")}`);
102
+ }
103
+ // npm/pnpm require lowercase package names; a strict lowercase regex also
104
+ // keeps the project folder name predictable (no /i flag deliberately).
105
+ if (!/^[a-z0-9][a-z0-9._-]*$/.test(name)) {
106
+ throw new Error(`invalid app name "${name}" — lowercase letters, digits, dots, dashes, underscores only`);
107
+ }
108
+ // Windows: trailing dots/space vanish in paths; reserved device names break mkdir.
109
+ if (/[.\s-]$/.test(name) || /^(con|prn|aux|nul|com\d|lpt\d)$/i.test(name)) {
110
+ throw new Error(`invalid app name "${name}" — no trailing dot/space/dash, and no Windows reserved names (con, prn, aux, nul, com1..9, lpt1..9)`);
111
+ }
112
+ }
113
+
114
+ function stamp(dest, { template }) {
115
+ writeFileSync(join(dest, ".fsaa.json"), JSON.stringify({ fsaa: "0.1.0", template, generatedAt: new Date().toISOString() }, null, 2) + "\n");
116
+ }
117
+
118
+ function gitInit(dest, branch, appName) {
119
+ const state = (args) => spawnSync("git", args, { cwd: dest, stdio: "pipe" });
120
+ if (!existsSync(join(dest, ".git"))) {
121
+ state(["init", "-b", branch]);
122
+ state(["add", "-A"]);
123
+ const c = state(["commit", "-q", "-m", `feat/init — scaffold ${appName} from FSAA starter`]);
124
+ if (c.status !== 0) {
125
+ console.error(" (git repo initialized but the commit needs identity — set git config user.name/user.email and commit)");
126
+ }
127
+ }
128
+ }
129
+
130
+ function nameSafe(dest) {
131
+ return dest.split(/[/\\]/).filter(Boolean).pop() || "app";
132
+ }
package/lib/net.mjs ADDED
@@ -0,0 +1,13 @@
1
+ /* fsaa/lib/net.mjs — fetch binary over HTTPS (zero deps, no shell). */
2
+ export async function fetchFile(url) {
3
+ const resp = await fetch(url, {
4
+ headers: { "User-Agent": "fsaa-cli/0.1 (+https://github.com/Aramex86/fsaa)" },
5
+ redirect: "follow",
6
+ signal: AbortSignal.timeout(120_000), // no unbounded hangs on a stalled connection
7
+ });
8
+ if (!resp.ok) {
9
+ throw new Error(`download failed: HTTP ${resp.status} for ${url}`);
10
+ }
11
+ const buf = await resp.arrayBuffer();
12
+ return Buffer.from(buf);
13
+ }
@@ -0,0 +1,221 @@
1
+ /* fsaa/lib/snippets.mjs — canonical slice file templates.
2
+ These mirror agents/add-module.md and the seeded canon of both starter
3
+ templates: a generated slice = a full entity (index/types/api/slice with
4
+ mock data + a real test) + a thin feature (index/ui/config with a real
5
+ test) + a thin route file. Data access lives ONLY in the entity. */
6
+
7
+ export function entityFiles(name) {
8
+ const Noun = pascal(name);
9
+ return {
10
+ "index.ts": entityIndex(name),
11
+ "types.ts": entityTypes(Noun),
12
+ "api.ts": entityApi(name, Noun),
13
+ "slice.ts": entitySlice(name, Noun),
14
+ [`__tests__/${name}.test.ts`]: entityTest(name, Noun),
15
+ };
16
+ }
17
+
18
+ export function featureFiles(name, template) {
19
+ const Title = pascal(name);
20
+ return {
21
+ "index.ts": featureIndex(name),
22
+ [`ui/${Title}Overview.tsx`]: featureComponent(name, Title, template),
23
+ [`config/${camel(name)}Columns.tsx`]: featureColumns(name),
24
+ [`__tests__/${name}.test.tsx`]: featureTest(name, template),
25
+ };
26
+ }
27
+
28
+ /* ---------- entity ---------- */
29
+
30
+ function entityIndex(name) {
31
+ return `export type { ${pascal(name)}Record } from './types';
32
+ export { get${pascal(name)}s } from './api';
33
+ export { selectOpen${pascal(name)}s, select${pascal(name)}Total } from './slice';
34
+ `;
35
+ }
36
+
37
+ function entityTypes(Noun) {
38
+ return `export type ${Noun}Status = 'pending' | 'paid' | 'cancelled';
39
+
40
+ export type ${Noun}Record = {
41
+ id: string;
42
+ reference: string;
43
+ projectName: string;
44
+ amount: number;
45
+ status: ${Noun}Status;
46
+ };
47
+ `;
48
+ }
49
+
50
+ export function entityApi(name, Noun) {
51
+ return `/* entities/${name} — data access. Swap for a real API without touching features. */
52
+
53
+ import type { ${Noun}Record } from './types';
54
+
55
+ export const ${CONST(name)}_RECORDS: ${Noun}Record[] = [
56
+ { id: 'r1', reference: 'REF-2026-001', projectName: 'Core Banking Migration', amount: 18500, status: 'paid' },
57
+ { id: 'r2', reference: 'REF-2026-002', projectName: 'Mobile App v2', amount: 6200, status: 'pending' },
58
+ { id: 'r3', reference: 'REF-2026-003', projectName: 'Mobile App v2', amount: 12400, status: 'pending' },
59
+ { id: 'r4', reference: 'REF-2026-004', projectName: 'Legacy CRM Sunset', amount: 3100, status: 'cancelled' },
60
+ ];
61
+
62
+ export function get${Noun}s(): Promise<${Noun}Record[]> {
63
+ return Promise.resolve(${CONST(name)}_RECORDS);
64
+ }
65
+ `;
66
+ }
67
+
68
+ function entitySlice(name, Noun) {
69
+ return `/* entities/${name}/slice — business logic (no UI knowledge, fully testable). */
70
+
71
+ import type { ${Noun}Record } from './types';
72
+
73
+ export function selectOpen${Noun}s(records: ${Noun}Record[]) {
74
+ return records.filter((record) => record.status !== 'cancelled');
75
+ }
76
+
77
+ export function select${Noun}Total(records: ${Noun}Record[]) {
78
+ return records.reduce((sum, record) => sum + record.amount, 0);
79
+ }
80
+ `;
81
+ }
82
+
83
+ function entityTest(name, Noun) {
84
+ return `import { describe, expect, it } from 'vitest';
85
+ import { get${Noun}s, selectOpen${Noun}s, select${Noun}Total } from '../index';
86
+
87
+ describe('entities/${name}', () => {
88
+ it('returns records with valid ids, amounts and statuses', async () => {
89
+ const records = await get${Noun}s();
90
+ expect(records.length).toBeGreaterThan(0);
91
+ for (const record of records) {
92
+ expect(record.id).toBeTruthy();
93
+ expect(record.amount).toBeGreaterThan(0);
94
+ expect(['pending', 'paid', 'cancelled'] as const).toContain(record.status);
95
+ }
96
+ });
97
+
98
+ it('derives open records and total through the slice', async () => {
99
+ const records = await get${Noun}s();
100
+ expect(selectOpen${Noun}s(records).every((record) => record.status !== 'cancelled')).toBe(true);
101
+ expect(select${Noun}Total(records)).toBe(records.reduce((sum, record) => sum + record.amount, 0));
102
+ });
103
+ });
104
+ `;
105
+ }
106
+
107
+ /* ---------- feature ---------- */
108
+
109
+ function featureIndex(name) {
110
+ return `export { ${pascal(name)}Overview } from './ui/${pascal(name)}Overview';
111
+ `;
112
+ }
113
+
114
+ function featureComponent(name, Title, template) {
115
+ return `${template === "next" ? "'use client';\n\n" : ""}import { useEffect, useState } from 'react';
116
+ import { DataTable } from '@shared/ui/molecules/table/DataTable';
117
+ import { get${pascal(name)}s, type ${pascal(name)}Record } from '@entities/${name}';
118
+ import { ${camel(name)}Columns } from '../config/${camel(name)}Columns';
119
+
120
+ /* features/${name}/ui/${Title}Overview — thin composition: entity data + config. */
121
+
122
+ export function ${Title}Overview() {
123
+ const [records, setRecords] = useState<${pascal(name)}Record[] | null>(null);
124
+
125
+ useEffect(() => {
126
+ let alive = true;
127
+ get${pascal(name)}s().then((data) => {
128
+ if (alive) setRecords(data);
129
+ });
130
+ return () => {
131
+ alive = false;
132
+ };
133
+ }, []);
134
+
135
+ return (
136
+ <section>
137
+ <h2>${Title}</h2>
138
+ {records && <DataTable columns={${camel(name)}Columns} data={records} rowKey={(row) => row.id} />}
139
+ </section>
140
+ );
141
+ }
142
+ `;
143
+ }
144
+
145
+ function featureColumns(name) {
146
+ const Noun = pascal(name);
147
+ return `import type { Column } from '@shared/ui/molecules/table/DataTable';
148
+ import type { ${Noun}Record } from '@entities/${name}';
149
+
150
+ /* features/${name}/config — plain data of the scenario, no UI knowledge. */
151
+
152
+ export const ${camel(name)}Columns: Column<${Noun}Record>[] = [
153
+ {
154
+ header: 'Reference',
155
+ render: (row) => <strong>{row.reference}</strong>,
156
+ },
157
+ {
158
+ header: 'Project',
159
+ render: (row) => row.projectName,
160
+ },
161
+ {
162
+ header: 'Amount',
163
+ align: 'right',
164
+ render: (row) => \`$\${row.amount.toLocaleString('en-US')}\`,
165
+ },
166
+ {
167
+ header: 'Status',
168
+ render: (row) =>
169
+ row.status === 'paid' ? '✅ paid' : row.status === 'pending' ? '⏳ pending' : '❌ cancelled',
170
+ },
171
+ ];
172
+ `;
173
+ }
174
+
175
+ function featureTest(name, template) {
176
+ return `import { describe, it, expect } from 'vitest';
177
+ import { ${pascal(name)}Overview } from '../index';
178
+ import { ${camel(name)}Columns } from '../config/${camel(name)}Columns';
179
+ import type { ${pascal(name)}Record } from '@entities/${name}';
180
+
181
+ /* Scenario slice test: the component exists and the plain column config
182
+ renders a record. Pure logic — no jsdom needed. */
183
+
184
+ const record: ${pascal(name)}Record = {
185
+ id: 'r1',
186
+ reference: 'REF-2026-001',
187
+ projectName: 'Demo',
188
+ amount: 100,
189
+ status: 'pending',
190
+ };
191
+
192
+ describe('features/${name}', () => {
193
+ it('exports the scenario component', () => {
194
+ expect(typeof ${pascal(name)}Overview).toBe('function');
195
+ });
196
+
197
+ it('renders records through the plain column config', () => {
198
+ expect(${camel(name)}Columns.length).toBeGreaterThan(0);
199
+ for (const column of ${camel(name)}Columns) {
200
+ expect(column.render(record)).toBeTruthy();
201
+ }
202
+ expect(String(${camel(name)}Columns[1].render(record))).toBe(record.projectName);
203
+ });
204
+ });
205
+ `;
206
+ }
207
+
208
+ /* ---------- helpers ---------- */
209
+
210
+ export function pascal(name) {
211
+ return name.split("-").map((s) => s[0].toUpperCase() + s.slice(1)).join("");
212
+ }
213
+
214
+ /* camelCase, canon-style: invoices-overview -> 'invoicesOverviewColumns' (orderColumns style) */
215
+ export function camel(name) {
216
+ const [first, ...rest] = name.split("-");
217
+ return first + rest.map((s) => s[0].toUpperCase() + s.slice(1)).join("");
218
+ }
219
+
220
+
221
+ const CONST = (name) => name.split("-").join("_").toUpperCase();
package/package.json CHANGED
@@ -1,6 +1,32 @@
1
1
  {
2
2
  "name": "create-fsaa",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "FSAA — Feature-Sliced Atomic Architecture. Run `npm create fsaa` (this package) to scaffold an FSAA app from the official starter templates; `fsaa g <slice>` generates canonical slices.",
5
+ "license": "MIT",
6
+ "author": "Veaceslav Bezusco <Aramex86@users.noreply.github.com>",
7
+ "type": "module",
8
+ "bin": {
9
+ "fsaa": "bin/fsaa.mjs"
10
+ },
11
+ "files": [
12
+ "bin",
13
+ "lib"
14
+ ],
15
+ "engines": {
16
+ "node": ">=20"
17
+ },
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "git+https://github.com/Aramex86/fsaa.git"
21
+ },
22
+ "keywords": [
23
+ "fsaa",
24
+ "feature-sliced",
25
+ "atomic-design",
26
+ "architecture",
27
+ "scaffold"
28
+ ],
29
+ "scripts": {
30
+ "selfcheck": "node bin/fsaa.mjs --help"
31
+ }
6
32
  }