@akanjs/cli 3.0.0-alpha.7 → 3.0.0-alpha.9
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/.build-stamp +1 -1
- package/{agent.command-pggr92jj.js → agent.command-f0gqkfgz.js} +7 -6
- package/{application.command-692yap1d.js → application.command-x903m2qq.js} +5 -4
- package/buildBatch.proc.js +2 -1
- package/{capacitorApp-p0z5yab2.js → capacitorApp-9xswcgx7.js} +3 -2
- package/{cloud.command-wqfsyzv2.js → cloud.command-zs6kyf83.js} +8 -7
- package/{context.command-9bxtdn0w.js → context.command-fmepgjzg.js} +14 -13
- package/getDirname-m9s0cmhq.js +8 -0
- package/{guideline.command-nfqahxex.js → guideline.command-n6sw0a0c.js} +5 -4
- package/guidelines/conventions/conventions.generate.json +25 -0
- package/guidelines/conventions/conventions.instruction.md +668 -0
- package/guidelines/workspaceOnboarding/workspaceOnboarding.generate.json +24 -0
- package/guidelines/workspaceOnboarding/workspaceOnboarding.instruction.md +972 -0
- package/incrementalBuilder.proc.js +2 -1
- package/index-1577bej2.js +7 -0
- package/{index-bz2sfzzt.js → index-3vta1tqa.js} +4 -4
- package/{index-p3f4q532.js → index-4m0bphac.js} +3 -3
- package/{index-w6wbb612.js → index-5sn5w2mt.js} +13 -13
- package/{index-5dw57f0d.js → index-62955kn5.js} +6 -6
- package/{index-mssqn2sq.js → index-774gcx29.js} +43 -4
- package/{index-xhgtkekh.js → index-779ske1y.js} +1 -1
- package/{index-js368gk9.js → index-82jrh4hj.js} +5 -5
- package/{index-a1e0j63x.js → index-d43t8af2.js} +2 -2
- package/{index-gex7c8kd.js → index-eyyf2149.js} +34 -6
- package/{index-azv0xjb5.js → index-gcv8ncfh.js} +2 -2
- package/{index-7myvn0f0.js → index-j37qq1f2.js} +1 -1
- package/{index-ztpw544k.js → index-jf2ya7r2.js} +3 -3
- package/{index-vtj3zps1.js → index-jhpa13zj.js} +7 -7
- package/{index-6rhabeev.js → index-kdh76j26.js} +4 -2
- package/{index-5pmx7bkg.js → index-qzdjd4ct.js} +3 -3
- package/{index-2c3e2xh8.js → index-rxkpk7n4.js} +1 -1
- package/{index-4hek879p.js → index-xmmzf150.js} +1 -1
- package/{index-gmy45vz2.js → index-y4vkyhvv.js} +3 -3
- package/{index-vg0sj9nc.js → index-z8ptfkzv.js} +56 -18
- package/index.js +19 -18
- package/{library.command-md9715jz.js → library.command-cv9gdbmg.js} +4 -3
- package/{localRegistry.command-exkbamyj.js → localRegistry.command-d8fg36zc.js} +7 -6
- package/{module.command-w5aaddxk.js → module.command-qyr1s9cn.js} +7 -6
- package/{package.command-yfkrcy0z.js → package.command-wsjx0k47.js} +4 -3
- package/package.json +2 -2
- package/{page.command-echbavp4.js → page.command-rdzg65rm.js} +4 -3
- package/{primitive.command-9fbhspw2.js → primitive.command-89g38b53.js} +8 -7
- package/{quality.command-3pnt9yep.js → quality.command-0cs2z92d.js} +3 -2
- package/{repair.command-carj4vax.js → repair.command-6fphxfwj.js} +6 -5
- package/{scalar.command-51ryzypc.js → scalar.command-xfer69s6.js} +6 -5
- package/templates/app/page/styles.css.template +3 -3
- package/templates/crudPages/[__model__Id]/edit/page.tsx +1 -1
- package/templates/crudPages/new/page.tsx +1 -1
- package/templates/crudSinglePage/page.tsx +1 -1
- package/templates/module/__Model__.Util.tsx +1 -1
- package/templates/module/__Model__.Zone.tsx +3 -5
- package/templates/workspaceRoot/AGENTS.md.template +0 -972
- package/templates/workspaceRoot/biome.json.template +3 -244
- package/{workflow.command-91wmvm8k.js → workflow.command-2ygfqt4f.js} +13 -12
- package/{workspace.command-wa10mfd9.js → workspace.command-88m0zs64.js} +35 -33
- package/templates/workspaceRoot/.cursor/rules/akan-page-routing.mdc.template +0 -43
- package/templates/workspaceRoot/.cursor/rules/akan-sync-conventions.mdc.template +0 -34
- package/templates/workspaceRoot/.cursor/rules/application-test-commands.mdc.template +0 -16
- package/templates/workspaceRoot/.cursor/rules/change-scope.mdc.template +0 -12
- package/templates/workspaceRoot/.cursor/rules/client-server-boundaries.mdc.template +0 -18
- package/templates/workspaceRoot/.cursor/rules/coding-comments.mdc.template +0 -25
- package/templates/workspaceRoot/.cursor/rules/coding-style.mdc.template +0 -44
- package/templates/workspaceRoot/.cursor/rules/domain-module-conventions.mdc.template +0 -17
- package/templates/workspaceRoot/.cursor/rules/format-lint.mdc.template +0 -12
- package/templates/workspaceRoot/.cursor/rules/lint-enforced-rules.mdc.template +0 -19
- package/templates/workspaceRoot/.cursor/rules/module-file-playbook.mdc.template +0 -62
- package/templates/workspaceRoot/.cursor/rules/naming-conventions.mdc.template +0 -15
- package/templates/workspaceRoot/.cursor/rules/react-component-style.mdc.template +0 -21
- package/templates/workspaceRoot/.cursor/rules/repo-overview.mdc.template +0 -17
- package/templates/workspaceRoot/.cursor/rules/scalar-modeling.mdc.template +0 -99
- package/templates/workspaceRoot/.cursor/rules/secrets-and-env.mdc.template +0 -13
- package/templates/workspaceRoot/.cursor/rules/service-signal-conventions.mdc.template +0 -83
- package/templates/workspaceRoot/.cursor/rules/srvkit-adapters-and-guards.mdc.template +0 -50
- package/templates/workspaceRoot/.cursor/rules/ssr-first.mdc.template +0 -59
- package/templates/workspaceRoot/.cursor/rules/typescript-imports.mdc.template +0 -16
|
@@ -0,0 +1,972 @@
|
|
|
1
|
+
## Workspace Layout
|
|
2
|
+
|
|
3
|
+
- `apps/<app>` contains application pages, app UI, app domain modules, env files, and `akan.config.ts`.
|
|
4
|
+
- `libs/<lib>` contains shared domain and utility code reused by apps.
|
|
5
|
+
- `apps/<app>/page` contains server-side file-routed pages. Index pages use `_index.tsx`; nested layouts use `_layout.tsx`. routeName.tsx becomes /routeName and [modelId].tsx becomes /[modelId].
|
|
6
|
+
- `apps/<app>/lib/<model>` contains database-backed domain modules.
|
|
7
|
+
- `apps/<app>/lib/_<service>` contains service modules that are not database document models.
|
|
8
|
+
- `apps/<app>/lib/__scalar/<scalar>` contains reusable scalar/value types.
|
|
9
|
+
- Module abstracts live beside module code as `<model>.abstract.md`, `<service>.abstract.md`, or
|
|
10
|
+
`<scalar>.abstract.md`.
|
|
11
|
+
|
|
12
|
+
## Generated Files
|
|
13
|
+
|
|
14
|
+
Do not hand-edit generated Akan files. Regenerate them through Akan sync, lint, start, build, or the matching
|
|
15
|
+
CLI command instead.
|
|
16
|
+
|
|
17
|
+
Common generated files include:
|
|
18
|
+
- `apps/*/client.ts`
|
|
19
|
+
- `apps/*/server.ts`
|
|
20
|
+
- `*/lib/cnst.ts`
|
|
21
|
+
- `*/lib/db.ts`
|
|
22
|
+
- `*/lib/dict.ts`
|
|
23
|
+
- `*/lib/sig.ts`
|
|
24
|
+
- `*/lib/srv.ts`
|
|
25
|
+
- `*/lib/st.ts`
|
|
26
|
+
- `*/lib/useClient.ts`
|
|
27
|
+
- `*/lib/useServer.ts`
|
|
28
|
+
- `*/lib/**/index.ts`
|
|
29
|
+
- `*/ui/index.ts`
|
|
30
|
+
- `*/webkit/index.ts`
|
|
31
|
+
- `*/srvkit/index.ts`
|
|
32
|
+
- `*/common/index.ts`
|
|
33
|
+
|
|
34
|
+
Only **layer-root** barrels are generated. A nested `ui/<Folder>/index.tsx` that builds a namespace is
|
|
35
|
+
hand-written source and must be edited by hand. The distinguishing test: a generated barrel contains nothing
|
|
36
|
+
but `export * from "./X";` lines.
|
|
37
|
+
|
|
38
|
+
## Domain Module Responsibilities
|
|
39
|
+
|
|
40
|
+
Use the local module shape before adding a new abstraction.
|
|
41
|
+
|
|
42
|
+
- `<model>.constant.ts` defines model, enum, scalar, and schema intent.
|
|
43
|
+
- `<model>.abstract.md` defines business intent, domain rules, workflows, and agent notes that are not obvious
|
|
44
|
+
from code.
|
|
45
|
+
- `<model>.dictionary.ts` defines labels, descriptions, messages, and i18n metadata.
|
|
46
|
+
- `<model>.signal.ts` defines typed endpoint contracts.
|
|
47
|
+
- `<model>.document.ts` owns persistence and document queries.
|
|
48
|
+
- `<model>.service.ts` owns business logic.
|
|
49
|
+
- `<model>.store.ts` owns reusable workflow state and actions that span loading, selections, messages, or multi-step client actions. Consume stores through generated `st.use.*` state and `st.do.*` actions.
|
|
50
|
+
- `<Model>.Template.tsx` owns form-oriented UI, including local form inputs and submit/import interactions. Client components, with 'use client'.
|
|
51
|
+
- `<Model>.Unit.tsx` owns list/item UI. Server components, no 'use client'.
|
|
52
|
+
- `<Model>.View.tsx` owns detail UI. Server components, no 'use client'.
|
|
53
|
+
- `<Model>.Zone.tsx` owns page/container integration and interactive loading or action flows that need client state. Client components, with 'use client'.
|
|
54
|
+
- `<Model>.Util.tsx` owns small module UI helpers, including buttons, import actions, and client-side navigation such as `router.push`. Client components, with 'use client'.
|
|
55
|
+
|
|
56
|
+
## Agent Workflow
|
|
57
|
+
|
|
58
|
+
1. Read the nearby module and convention before creating files. If `*.abstract.md` exists, read it first.
|
|
59
|
+
2. Put new files in the established Akan location instead of adding parallel architecture.
|
|
60
|
+
3. Prefer Akan MCP workflows before direct source edits. Start with `akan mcp --mode plan` for `list_workflows`, `explain_workflow`, and `plan_workflow`.
|
|
61
|
+
4. If `plan_workflow` returns `planPath` or `next.tool=apply_workflow`, call `apply_workflow({ planPath })` before direct source edits.
|
|
62
|
+
5. Use `akan mcp --mode apply` only for allowlisted `apply_workflow`, `run_validation`, and repair tools.
|
|
63
|
+
6. After `apply_workflow`, run `run_validation` with `validationTarget` when present; otherwise use `applyReportPath`.
|
|
64
|
+
7. Direct source edits are denied when an allowlisted Akan workflow or repair tool can perform the change.
|
|
65
|
+
8. If no workflow exists, or apply reports unsupported/no-op/failed diagnostics that require manual action, edit only the owning source files and never patch generated files directly.
|
|
66
|
+
9. Keep page and layout files server-oriented: route-level `usePage`, headers, static layout, and `akanjs/ui` `Tab` composition belong there.
|
|
67
|
+
10. Put interactive loading, submit/import actions, local form state, and `router.push` in client `Util`, `Template`, or `Zone` components.
|
|
68
|
+
11. Prefer `Tab` for static mode selection instead of extra `useState`; render one focused client component inside each `Tab.Panel`.
|
|
69
|
+
12. Default to server rendering. Add `"use client"` only for a real client-only capability, and keep markup out of the component that carries it — see **SSR First** below.
|
|
70
|
+
13. Keep server-only logic out of client surfaces and client-only code out of server imports.
|
|
71
|
+
14. Treat `AKAN_PUBLIC_*` env vars as public. Never put secrets in them.
|
|
72
|
+
15. Add or update tests when behavior, contracts, or CLI output changes.
|
|
73
|
+
16. Update `*.abstract.md` when business invariants, workflows, or public behavior change.
|
|
74
|
+
17. Run the smallest relevant verification command after changes. After touching any `.tsx`, that includes `akan quality ssr`.
|
|
75
|
+
|
|
76
|
+
## Common Commands
|
|
77
|
+
|
|
78
|
+
Run commands from the workspace root unless a task says otherwise.
|
|
79
|
+
|
|
80
|
+
### Module Addition Workflow
|
|
81
|
+
|
|
82
|
+
When adding a new database-backed domain module (e.g., product, user):
|
|
83
|
+
|
|
84
|
+
```bash
|
|
85
|
+
# 1. Scaffold the module with Akan CLI (creates constant, service, signal, store, document files)
|
|
86
|
+
# The target app/lib is a POSITIONAL argument, not a --app flag.
|
|
87
|
+
akan create-module <module-name> <%= appName %>
|
|
88
|
+
|
|
89
|
+
# 2. Start dev server with HMR and type checking at http://localhost:8282
|
|
90
|
+
akan start <%= appName %>
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
### Change Verification Workflow
|
|
94
|
+
|
|
95
|
+
After any code change, run these in order:
|
|
96
|
+
|
|
97
|
+
```bash
|
|
98
|
+
# 1. Fast lint check — Akan.js conventions and Biome rules
|
|
99
|
+
akan lint <%= appName %>
|
|
100
|
+
|
|
101
|
+
# 2. Type-only check — catches server/client boundary violations and import errors
|
|
102
|
+
akan typecheck <%= appName %>
|
|
103
|
+
|
|
104
|
+
# 3. Test — Run the test code (lib/*/*.signal.test.ts or others)
|
|
105
|
+
akan test <%= appName %>
|
|
106
|
+
|
|
107
|
+
# 4. SSR balance — only after touching .tsx files. Reports the server render share
|
|
108
|
+
# per app/lib and flags client code that should render on the server.
|
|
109
|
+
akan quality ssr
|
|
110
|
+
|
|
111
|
+
# 5. Full production build — bundles the app, runs all type/lint checks combined
|
|
112
|
+
akan build <%= appName %>
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
**Verify endpoints with signal tests, not raw HTTP.** The canonical way to check a query/mutation/slice
|
|
116
|
+
contract is an in-memory signal test (`<model>.signal.test.ts`), using the test fetch harness
|
|
117
|
+
(`getOrSetupSignalTestFetch`) — it is fast, needs no running server, and exercises `fetch.*`, `view/edit/merge<Model>`,
|
|
118
|
+
and slice `init`/`list`/`insight` directly. Prefer it over `curl`: the dev gateway locale-prefixes routes (`/en/...`),
|
|
119
|
+
so hand-rolled HTTP calls against a raw path can redirect unexpectedly. See `akan test <%= appName %>`.
|
|
120
|
+
|
|
121
|
+
### Other Frequently Used Commands
|
|
122
|
+
|
|
123
|
+
```bash
|
|
124
|
+
akan create-scalar <scalar-name> <%= appName %> # Add a scalar module (lib/__scalar/<scalar-name>/)
|
|
125
|
+
akan create-service <service-name> <%= appName %> # Add a service module (lib/_<service-name>/)
|
|
126
|
+
akan test <%= appName %> # Run the test code (lib/*/*.signal.test.ts or others)
|
|
127
|
+
akan lint <%= appName %> # Lint only (no typecheck)
|
|
128
|
+
akan quality scan # All code-quality warnings + SSR balance
|
|
129
|
+
akan quality ssr # SSR balance and client-boundary warnings only
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
**CLI argument conventions.** Two argument styles, and mixing them up is a common mistake:
|
|
133
|
+
|
|
134
|
+
- Scaffolding and whole-app commands take the target app/lib as a **positional** argument, not a flag:
|
|
135
|
+
|
|
136
|
+
```bash
|
|
137
|
+
akan create-module photo <%= appName %>
|
|
138
|
+
akan create-scalar money <%= appName %>
|
|
139
|
+
akan create-service billing <%= appName %>
|
|
140
|
+
akan sync <%= appName %>
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
- Only the source-limited field commands use `--app`/`--module` flags:
|
|
144
|
+
|
|
145
|
+
```bash
|
|
146
|
+
akan add-field --app <%= appName %> --module photo --field width --type Int
|
|
147
|
+
akan add-enum-field --app <%= appName %> --module photo --field status --values draft,active
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
Passing `--app` to `create-module` is not recognized, and the target app will not resolve.
|
|
151
|
+
|
|
152
|
+
For the default generated app, start with:
|
|
153
|
+
|
|
154
|
+
```bash
|
|
155
|
+
akan start <%= appName %>
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
### The Essential Loop: Workflow -> Sync -> Check
|
|
159
|
+
|
|
160
|
+
Almost every Akan.js change follows this pattern. **Missing sync or repair is the #1 cause of agent confusion.**
|
|
161
|
+
|
|
162
|
+
> **If the Akan MCP tools are not connected in your agent, skip straight to the CLI-only fallback below.**
|
|
163
|
+
> `akan mcp --mode plan/apply` starts a stdio MCP server that only works when your agent is wired to it as an
|
|
164
|
+
> MCP client. When those `list_workflows` / `plan_workflow` / `apply_workflow` tools are not available, the CLI
|
|
165
|
+
> commands are a fully supported, first-class path — you are not losing any capability by using them.
|
|
166
|
+
|
|
167
|
+
1. **Plan** — Ask the Akan MCP server for the workflow first.
|
|
168
|
+
```
|
|
169
|
+
akan mcp --mode plan
|
|
170
|
+
# use list_workflows, explain_workflow, and plan_workflow
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
2. **Apply the plan** — If `plan_workflow` returns `planPath` or `next.tool=apply_workflow`, call
|
|
174
|
+
`apply_workflow({ planPath })`. Do not copy the workflow plan into direct source edits.
|
|
175
|
+
```
|
|
176
|
+
akan mcp --mode apply
|
|
177
|
+
# use apply_workflow, run_validation, repair_generated, repair_imports, or repair_module_shape
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
Direct edits are fallback only: use them after `list_workflows`/`explain_workflow` confirm no matching workflow, or
|
|
181
|
+
after apply reports unsupported/no-op/failed diagnostics that require manual action. Keep fallback edits to owning
|
|
182
|
+
source files such as `task.constant.ts`, `task.dictionary.ts`, `Task.Template.tsx`, or `Task.Unit.tsx`.
|
|
183
|
+
|
|
184
|
+
3. **Validate the apply report** — Use the apply report artifact, not the original raw plan, when it is available.
|
|
185
|
+
```
|
|
186
|
+
# run_validation with validationTarget first; otherwise use applyReportPath
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
4. **Sync or repair** — Regenerate barrel files so Akan discovers your change. This regenerates:
|
|
190
|
+
`cnst.ts`, `db.ts`, `srv.ts`, `sig.ts`, `st.ts`, `dict.ts`, `useClient.ts`, `useServer.ts`,
|
|
191
|
+
`ui/index.ts`, `webkit/index.ts`, `srvkit/index.ts`, `common/index.ts`, and all module `index.ts` files.
|
|
192
|
+
```
|
|
193
|
+
akan sync <%= appName %>
|
|
194
|
+
# or: akan repair generated --app <%= appName %>
|
|
195
|
+
```
|
|
196
|
+
**CRITICAL**: Sync after EVERY file add, delete, or rename. Without sync, other modules cannot
|
|
197
|
+
`import * as cnst from "../cnst"` and find your new model.
|
|
198
|
+
|
|
199
|
+
5. **Check** — Verify your change compiles and lints.
|
|
200
|
+
```
|
|
201
|
+
akan start <%= appName %> # dev server with live feedback (preferred)
|
|
202
|
+
akan lint <%= appName %> # quick lint-only check
|
|
203
|
+
akan doctor --strict # structured workspace diagnostics
|
|
204
|
+
```
|
|
205
|
+
|
|
206
|
+
If `akan sync` gives errors, try:
|
|
207
|
+
- `akan build <%= appName %>` — full rebuild catches type errors sync may miss
|
|
208
|
+
- Re-run `akan create-module <name> <%= appName %>` if the scaffold is corrupted
|
|
209
|
+
|
|
210
|
+
For compound natural-language requests, split the request into workflows and apply each artifact in order. For example,
|
|
211
|
+
"create a project module and add a budget field" should run `create-module` plan/apply first, then `add-field`
|
|
212
|
+
plan/apply, then validation/doctor on the returned `validationTarget`.
|
|
213
|
+
|
|
214
|
+
### CLI-Only Fallback (MCP Not Connected)
|
|
215
|
+
|
|
216
|
+
When the Akan MCP tools are not loaded, run the CLI commands directly. Each MCP tool maps 1:1 to a CLI command,
|
|
217
|
+
and the CLI emits the same structured report via `--format json`:
|
|
218
|
+
|
|
219
|
+
| MCP tool | CLI-only equivalent |
|
|
220
|
+
|----------|---------------------|
|
|
221
|
+
| `list_workflows` | `akan workflow list` |
|
|
222
|
+
| `explain_workflow <name>` | `akan workflow explain <name>` |
|
|
223
|
+
| `plan_workflow <name> ...` | `akan workflow plan <name> ... --format json --out <planPath>` |
|
|
224
|
+
| `apply_workflow { planPath }` | `akan workflow apply <planPath> --format json` (add `--dry-run` to preview) |
|
|
225
|
+
| `run_validation { validationTarget }` | `akan doctor --strict --format json` (or `akan typecheck <%= appName %>`) |
|
|
226
|
+
| `repair_generated` / `repair_imports` / `repair_module_shape` | `akan repair generated\|imports\|module-shape --app <%= appName %> --format json` |
|
|
227
|
+
|
|
228
|
+
The scaffolding primitives (`akan create-module`, `akan create-scalar`, `akan create-service`, `akan add-field`,
|
|
229
|
+
`akan add-enum-field`) are the same primitives the workflows call, so `create-module <name> <%= appName %>` followed
|
|
230
|
+
by `akan sync <%= appName %>` is equivalent to running the `create-module` workflow. Direct source edits remain the
|
|
231
|
+
final fallback when no CLI command covers the change.
|
|
232
|
+
|
|
233
|
+
## Quick Decision Matrix — "Where do I put this code?"
|
|
234
|
+
|
|
235
|
+
| You want to... | Create in... | Run after... |
|
|
236
|
+
|----------------|-------------|--------------|
|
|
237
|
+
| Define a new database-backed noun (e.g., User, Product) | `lib/<model>/` → constant, document, service, signal, store, dictionary, abstract | `akan sync <name>` |
|
|
238
|
+
| Add a pure workflow / integration (e.g., Payment, Email) | `lib/_<service>/` → service, signal, store, dictionary, abstract | `akan sync <name>` |
|
|
239
|
+
| Add a reusable value type (e.g., Address, WorkHistory) | `lib/__scalar/<type>/` → constant, dictionary, abstract | `akan sync <name>` |
|
|
240
|
+
| Create a new URL-visitable page | `page/` → `_index.tsx`, `_layout.tsx`, `[param]/_index.tsx` | Rebuild (akan start auto-detects) |
|
|
241
|
+
| Change the app color theme / design tokens | `apps/<app>/page/styles.css` → override the semantic token values under `:root, [data-theme="dark"]` and `[data-theme="light"]` (`--primary`, `--background`, `--foreground`, …) | akan start hot-reloads |
|
|
242
|
+
| Add a form or reusable UI component | `ui/` → PascalCase `.tsx`, **no** `"use client"` unless it uses a hook, event handler, store, or browser API | `akan sync <name>` |
|
|
243
|
+
| Add a React hook or browser helper | `webkit/` → camelCase `.ts` with `"use client"` | `akan sync <name>` |
|
|
244
|
+
| Add a server-only guard, middleware, or adaptor | `srvkit/` → PascalCase `.ts` | `akan sync <name>` |
|
|
245
|
+
| Add a pure helper (no DOM, no server API) | `common/` → camelCase `.ts` | `akan sync <name>` |
|
|
246
|
+
|
|
247
|
+
## Anti-patterns: Never Do These
|
|
248
|
+
|
|
249
|
+
| Don't | Why | Do Instead |
|
|
250
|
+
|-------|-----|------------|
|
|
251
|
+
| Edit `cnst.ts`, `db.ts`, `srv.ts`, `sig.ts`, `st.ts`, `dict.ts`, `useClient.ts`, `useServer.ts`, or any `index.ts` | These are **generated by `akan sync`**. Your changes will be overwritten. | Edit the source files in `lib/<model>/` directories and run `akan sync <name>` |
|
|
252
|
+
| Create a file without running sync | New files won't appear in barrel exports. Imports like `import * as cnst from "../cnst"` will fail. | Always run `akan sync <name>` after creating, renaming, or deleting any module file |
|
|
253
|
+
| Use JS `#private` in `*.constant.ts`, `*.document.ts`, `*.service.ts`, or `*.store.ts` | `no-js-private-class-method.grit` bans `#private` in exactly those four file suffixes. The rule is scoped by file path, not class shape — `#private` stays the house style under `srvkit/`, including `adapt()` classes. | `private _methodName()` in those four files; `#methodName()` in `srvkit/` |
|
|
254
|
+
| Use `console.log()` | Biome lint forbids `console.log`. Only `console.error`, `console.info`, `console.warn` are allowed. | Use one of the three allowed console methods, or `this.logger.*` / `new Logger("ClassName")` on the server |
|
|
255
|
+
| Write a `//!` marker in `ui/`, `webkit/`, `common/`, `page/**/*.tsx`, `*.constant.ts`, `*.store.ts`, or a module component file | `no-bang-comment-in-client.grit` bans it. Bun classifies `//!` and `/*!` as legal comments and keeps them through minification, so the note ships to every visitor. | `// FIXME:` in browser-reachable code; `//!` stays legal in server, `srvkit/`, and CLI files |
|
|
256
|
+
| `return` a value from a store action | `no-return-in-store-action.grit` bans it. Every method of a `store(...)` class dispatches through `st.do.<action>()`, which is typed `void` / `Promise<void>`, so the value never reaches the caller. | `this.set({ ... })` with the result; a bare `return;` guard, a `return` inside a nested callback, a getter, and a `static` helper all stay legal |
|
|
257
|
+
| `throw new Error("...")` | `no-throw-raw-error.grit` bans raw errors outside tests, `*.constant.ts`, `common/`, and `apps/akan/env/`. Raw errors carry no dictionary key, so they cannot be localized or toasted. | `throw new Err("task.error.<key>")` plus an `[en, ko]` entry in the module dictionary's `.error({})` |
|
|
258
|
+
| Hand-order Tailwind classes, or reorder them to "fix" a diff | `useSortedClasses` is an error and also sorts the string arguments to `cn()`. Sorter output like `font-bold text-2xl` looks wrong but is correct. | Write classes in any order and let `akan lint` sort them |
|
|
259
|
+
| A colour outside the semantic vocabulary — `bg-red-500`, `bg-[#3b82f6]`, `btn-primary`, `text-base-content`, `style={{ color: "#fff" }}` | The theme closes the vocabulary, so these produce **no CSS at all** — the element renders unstyled, and without the lint rules there is no error and no warning either. Raw-palette, arbitrary-colour, daisyUI-legacy and inline-colour rules all catch this. | Semantic tokens: `bg-primary`, `text-foreground/70`, `border-border`. A genuinely fixed colour takes a `// biome-ignore lint/plugin: <reason>` |
|
|
260
|
+
| `import` a third-party package inside a page, a barrel, or a module file | `no-import-external-library.grit` covers `page/**`, all barrels, and every `*.{constant,dictionary,document,service,signal,store}.ts` and `*.{Template,Unit,Util,View,Zone}.tsx`. | Re-export the symbol from a one-line shim in `base/`, `webkit/`, or `ui/` first, then import that |
|
|
261
|
+
| Import server APIs (`fs`, `Bun`, `process.env`) in `ui/`, `webkit/`, or `common/` | Server-only imports in client code cause build failures. | Keep server dependencies in `lib/`, `srvkit/`, or `private/` only |
|
|
262
|
+
| Import across the client/server boundary — a `*.service.ts` or `../db` from a `.tsx`, `@libs/<lib>/client` or `../st` from a `*.signal.ts` | `no-import-server-in-client.grit` and `no-import-client-in-server.grit` ban it in both directions, and hold `common/` and `*.constant.ts` to both at once. One value import drags the whole other-side graph into the bundle or the server process. | Client code goes through the package client entrypoint and `cnst`; server code goes through `cnst`, `db`, and `srv`. `import type` is erased and stays legal both ways |
|
|
263
|
+
| Skip running `akan sync` after deleting a file | Deleted files remain referenced in barrel exports, causing import errors everywhere. | Run `akan sync <name>` after every file add, remove, or rename |
|
|
264
|
+
| Use "use client" or `useState`/`useEffect` in pages/*.tsx, *.Unit.tsx, and *.View.tsx files | Server code cannot use React hooks. Wrap in a separate `"use client"` component. | Move hook logic to `webkit/` or a `"use client"` UI component |
|
|
265
|
+
| Use `<a>` tag for internal navigation between pages | Akan.js uses `<Link>` from `akanjs/ui` for client-side navigation — avoids full page reloads. | `import { Link } from "akanjs/ui"` and use `<Link href="/task">...</Link>` |
|
|
266
|
+
| Name a custom `Endpoint`/`Slice` like a generated CRUD op — `create<Model>`, `update<Model>`, `remove<Model>`, `view<Model>`, `edit<Model>`, `merge<Model>` | These names are already auto-generated. A collision can pass sync/typecheck/build and only fail at runtime. | Pick a distinct verb, e.g. `startTask`/`archiveTask`, never `createTask` for a custom endpoint |
|
|
267
|
+
| Add `"use client"` to a file that renders markup but uses no hook, event handler, store, or browser API | The directive is a cost, not a formality: everything behind it ships twice, as HTML and as JS that re-runs in the browser. | Delete the directive. `akan quality ssr` flags this as `akan.ssr.unnecessary-use-client` |
|
|
268
|
+
| Put a large static subtree inside a client component that only needs one `onClick` | The whole subtree lands in the bundle for the sake of one handler. | Keep the handler in a small client shell and pass the static markup in as `children`, or move it to a `Unit`/`View` |
|
|
269
|
+
| Load server data with `useEffect(() => { void st.do.initTaskInTodo(); }, [])` | The page renders an empty shell, hydrates, then round-trips for data the server already had. | `await fetch.initTaskInTodo()` in the page and pass `init` to the `Zone` |
|
|
270
|
+
|
|
271
|
+
## SSR First — Server Rendering Is The Default
|
|
272
|
+
|
|
273
|
+
Akan is SSR-first. Every JSX element that renders on the server ships as HTML and costs nothing to hydrate; every
|
|
274
|
+
element behind `"use client"` ships twice — as markup and as bundled JS that must re-run in the browser. The
|
|
275
|
+
boundary question is not which file *may* be client, it is **how little** ends up on the client side.
|
|
276
|
+
|
|
277
|
+
**The default is server. `"use client"` is a cost you justify per component, not a habit.** A component earns the
|
|
278
|
+
directive only by using a client-only capability: a React hook, a JSX event handler, the store (`st.use.*` /
|
|
279
|
+
`st.do.*`), a browser global, or a client-only third-party package. Rendering markup, mapping over data, reading a
|
|
280
|
+
route param, and calling `l()` are all server work — `usePage()` and `l()` are legal in server components and never
|
|
281
|
+
force a boundary.
|
|
282
|
+
|
|
283
|
+
The file role decides *where* the boundary sits (`Template`/`Zone`/`Util` are client, `Unit`/`View` are server); it
|
|
284
|
+
does not decide how much markup sits behind it. A `Zone` that hoards markup is still an SSR regression.
|
|
285
|
+
|
|
286
|
+
Measure with `akan quality ssr` (`--format json` for tooling). It reports the server render share per app and lib —
|
|
287
|
+
server-rendered JSX elements over total — plus the warnings below. Treat **50% server share as the floor** and a
|
|
288
|
+
falling share as a regression to justify or revert.
|
|
289
|
+
|
|
290
|
+
| Rule | Means |
|
|
291
|
+
|---|---|
|
|
292
|
+
| `akan.ssr.unnecessary-use-client` | The directive is there but nothing in the file needs it. Delete it. |
|
|
293
|
+
| `akan.ssr.client-static-component` | A component in a client file renders real markup with zero client-only capability — pure server work sitting in the bundle. |
|
|
294
|
+
| `akan.ssr.client-static-markup` | A large subtree wraps one or two interactive touches. Split it: interaction stays client, markup goes server. |
|
|
295
|
+
| `akan.ssr.client-mount-load` | A `useEffect(…, [])` loads server data. The page can fetch it before the first byte. |
|
|
296
|
+
| `akan.ssr.module-missing-server-view` | A module renders only from `Template`/`Zone`/`Util` and has no `Unit`/`View` at all. |
|
|
297
|
+
| `akan.ssr.template-client-state` | A `Template` holds form state in `useState` instead of the store. |
|
|
298
|
+
|
|
299
|
+
A third-party client package and the `ui/<Folder>/index_.tsx` + `lazy()` boundary both justify the directive and are
|
|
300
|
+
not flagged. Interaction-driven `fetch.*` inside an `onClick` is not flagged either — only mount-time loads are,
|
|
301
|
+
because those are the ones the server could have performed.
|
|
302
|
+
|
|
303
|
+
### Server-Side Implementation Playbook
|
|
304
|
+
|
|
305
|
+
**① Wrap the interaction, not the UI.** The smallest useful client component adds one behaviour and renders
|
|
306
|
+
`children` untouched, so the markup inside never reaches the bundle.
|
|
307
|
+
|
|
308
|
+
```tsx
|
|
309
|
+
// apps/<%= appName %>/ui/ClickWrapper.tsx
|
|
310
|
+
"use client";
|
|
311
|
+
export const ClickWrapper = ({ children, onPick }: ClickWrapperProps) => <div onClick={onPick}>{children}</div>;
|
|
312
|
+
|
|
313
|
+
// in a server page — Task.Unit.Card stays server-rendered
|
|
314
|
+
<ClickWrapper onPick={…}>
|
|
315
|
+
<Task.Unit.Card task={task} />
|
|
316
|
+
</ClickWrapper>
|
|
317
|
+
```
|
|
318
|
+
|
|
319
|
+
**② Split compound components so panels stay on the server.** A tab, accordion, or disclosure needs client state
|
|
320
|
+
only for *which* part is visible — never for what the parts contain. `Tab` / `Tab.Menus` / `Tab.Menu` / `Tab.Panel`
|
|
321
|
+
from `akanjs/ui` is the reference shape: only the provider and menu hold state, and `<Tab.Panel>` renders its
|
|
322
|
+
children as-is, so a server `Unit`/`View` passed in stays server-rendered.
|
|
323
|
+
|
|
324
|
+
```tsx
|
|
325
|
+
<Tab defaultMenu="detail">
|
|
326
|
+
<Tab.Menus>
|
|
327
|
+
<Tab.Menu menu="detail">{l("task.detail")}</Tab.Menu>
|
|
328
|
+
<Tab.Menu menu="history">{l("task.history")}</Tab.Menu>
|
|
329
|
+
</Tab.Menus>
|
|
330
|
+
<Tab.Panel menu="detail">
|
|
331
|
+
<Task.View.General task={task} />
|
|
332
|
+
</Tab.Panel>
|
|
333
|
+
</Tab>
|
|
334
|
+
```
|
|
335
|
+
|
|
336
|
+
Never collapse this into one `"use client"` file with a mode `useState` and every panel body inlined.
|
|
337
|
+
|
|
338
|
+
**③ Sync state instead of fetching it.** A server component cannot hold state, so render the initial data on the
|
|
339
|
+
server and hand it across the boundary as a serializable object. That is what `init` / `view` props are: the page
|
|
340
|
+
calls `fetch.initTaskInTodo()` / `fetch.viewTask(id)`, passes the result into a `Zone`, and `Load.Units` /
|
|
341
|
+
`Load.View` hydrate the store from it.
|
|
342
|
+
|
|
343
|
+
```tsx
|
|
344
|
+
export default async function Page() {
|
|
345
|
+
const [{ taskInitInTodo }] = await Promise.all([fetch.initTaskInTodo()]);
|
|
346
|
+
return <Task.Zone.Card init={taskInitInTodo} sliceName="taskInTodo" />;
|
|
347
|
+
}
|
|
348
|
+
```
|
|
349
|
+
|
|
350
|
+
**④ Push the boundary down to the leaf that needs it.** When a `Zone` reads the store, it should hold *zero* markup
|
|
351
|
+
and delegate to a server `View`, so the whole detail surface renders server-side wherever a page uses the `View`
|
|
352
|
+
directly.
|
|
353
|
+
|
|
354
|
+
```tsx
|
|
355
|
+
"use client";
|
|
356
|
+
export const Self = () => <Task.View.General task={st.use.task()} />;
|
|
357
|
+
```
|
|
358
|
+
|
|
359
|
+
**⑤ Hand the promise across, not the awaited value.** `ClientInit` / `ClientView` are `PromiseOrObject<T>`, so a
|
|
360
|
+
page may pass an unawaited `fetch.initTaskInTodo()` and `Load.*` resolves it behind a skeleton. `await` blocks the
|
|
361
|
+
shell for data the page needs immediately; passing the promise streams the rest. Independent fetches still go
|
|
362
|
+
through one `Promise.all`.
|
|
363
|
+
|
|
364
|
+
**⑥ Use named `ReactNode` slots, not just `children`.** A client shell can take several server-rendered subtrees:
|
|
365
|
+
`Layout.Navbar` accepts `title`, `back`, `left`, `right`, and `children`, so it composes server content in five
|
|
366
|
+
places instead of absorbing it.
|
|
367
|
+
|
|
368
|
+
**⑦ Let the server do the derived work.** Display and predicate logic belongs on `LightTask` (`isNew()`,
|
|
369
|
+
`canWrite(user?)`, `formatTimes()`), and enum→class lookups belong in a module-scope `as const` map. Both sides call
|
|
370
|
+
the same method, so a client component that exists only to compute a label is markup in the wrong place.
|
|
371
|
+
|
|
372
|
+
**⑧ Gate auth on the server.** Check the session in `_layout.tsx` and redirect there, before any HTML is sent. A
|
|
373
|
+
client-side auth check costs a hydration round-trip and flashes the wrong UI first.
|
|
374
|
+
|
|
375
|
+
**⑨ Prefer CSS over client state for pure visibility.** A `data-*` attribute plus `group-data-[…]` variants, or
|
|
376
|
+
`<details>`/`<summary>`, keeps both branches server-rendered. Reach for `useState` when the state is real, not when
|
|
377
|
+
a Tailwind variant would do.
|
|
378
|
+
|
|
379
|
+
**⑩ Keep the heavy island out of the first load.** A large client-only widget goes behind the
|
|
380
|
+
`ui/<Folder>/index_.tsx` + `lazy()` pair so the server renders the page around it.
|
|
381
|
+
|
|
382
|
+
## Code Style
|
|
383
|
+
|
|
384
|
+
House style for `apps/**` and `libs/**`. `akan lint` enforces the rules in the anti-pattern table above; the rest
|
|
385
|
+
is convention that keeps hand-written code reading like generated code.
|
|
386
|
+
|
|
387
|
+
### Files And Types
|
|
388
|
+
|
|
389
|
+
- Keep files small. Split a component before it reaches ~150 lines instead of adding section comments.
|
|
390
|
+
- Ship every scaffold file even when it is empty — `export class TaskInternal extends internal(srv.task, () => ({})) {}`,
|
|
391
|
+
empty dictionary stages, the `// state` / `// action` markers in an empty store. They mark where things go.
|
|
392
|
+
- Never add a sibling helper file inside `lib/<model>/`. Helpers go to `common/`, `webkit/`, `srvkit/`, or `ui/`.
|
|
393
|
+
- Prefer duplication to premature abstraction at the leaf: copy the near-identical file and change the literals.
|
|
394
|
+
- `interface` for object shapes, `type` only for unions and aliases.
|
|
395
|
+
- Never use a non-null assertion (`!`). Narrow with `?.`, an early return, or a type predicate.
|
|
396
|
+
- Escape with `as unknown as T`, never `as any`.
|
|
397
|
+
- `as const` on every `enumOf(...)` array, every Light field tuple, and every module-scope lookup map. Never the
|
|
398
|
+
TypeScript `enum` keyword.
|
|
399
|
+
- Never annotate a component's return type. Async functions carry no `Async` suffix.
|
|
400
|
+
|
|
401
|
+
### Components
|
|
402
|
+
|
|
403
|
+
- `export const X = ({ … }: XProps) => { return (…); };` — arrow const with a block body. `export default` is only
|
|
404
|
+
for pages, layouts, and `lazy()` targets.
|
|
405
|
+
- Declare `interface <ComponentName>Props` immediately above the component with no blank line, `className?: string`
|
|
406
|
+
first. Name it for the component (`CardProps`), never for the model.
|
|
407
|
+
- Never `React.FC`, never `defaultProps`, never `PropsWithChildren`. Defaults go in the destructuring; children are
|
|
408
|
+
typed `children: ReactNode`.
|
|
409
|
+
- `"use client"` on line 1 is mechanical by file role: every `.Zone.tsx`, `.Template.tsx`, and `.Util.tsx` has it;
|
|
410
|
+
no `.Unit.tsx` or `.View.tsx` ever does.
|
|
411
|
+
- Conditional render is `cond ? <X/> : null`, never `{cond && <X/>}` — in a `className` context the latter renders
|
|
412
|
+
the literal string `"false"`.
|
|
413
|
+
- Never hand-roll loading, empty, or list states. Use `Load.Units` / `Load.View` / `Load.Edit` with `renderItem`,
|
|
414
|
+
`renderList`, and `renderEmpty`, and `Model.New` / `Model.Edit` / `Model.SureToRemove` for CRUD modals.
|
|
415
|
+
- Avoid hooks. `useState` is for modal-open, tab, draft-input, and drag state only — never for server data.
|
|
416
|
+
`.Template.tsx` files contain zero `useState`: forms are store-driven with `Field.*`, `value={taskForm.x}`, and
|
|
417
|
+
`onChange={st.do.setXOnTask}` passed by reference.
|
|
418
|
+
- Read with `st.use.*` and write with `st.do.*`. Client components do not call `fetch.*`.
|
|
419
|
+
- Reach for a recipe before writing a look by hand: `buttonRecipe`, `badgeRecipe` and `inputRecipe` from
|
|
420
|
+
`akanjs/ui` carry the button, badge and field surfaces. Call them as `buttonRecipe(variants?, className?)` —
|
|
421
|
+
the second argument merges internally and takes an array, so never wrap it in `cn()`.
|
|
422
|
+
- Static class strings stay plain strings. Reach for `cn` only for a conditional or to merge an incoming
|
|
423
|
+
`className`, and merge the caller last: `cn("base", conditional, className)`. `cn` comes from `akanjs/client`
|
|
424
|
+
and is the only class-combining function — no `clsx`, no raw `twMerge`.
|
|
425
|
+
- Use semantic tokens with opacity modifiers (`text-foreground/60`, `bg-background/70`, `border-border`). Never
|
|
426
|
+
`dark:` — theming is the token block in `page/*/styles.css`, where each token has a `-foreground` pair.
|
|
427
|
+
- Hoist enum→class lookups to a module-scope `as const` map typed `{ [key in cnst.TaskStatus["value"]]: string }`,
|
|
428
|
+
not `Record<...>`.
|
|
429
|
+
|
|
430
|
+
### Naming
|
|
431
|
+
|
|
432
|
+
- Component exports are role names (`Card`, `General`, `Preview`, `Remove`). The model comes from the namespace, so
|
|
433
|
+
write `Card`, not `TaskCard`.
|
|
434
|
+
- Layer the verbs: the document chain method drops the model (`start()`) and the signal, store, and dictionary
|
|
435
|
+
re-add it (`startTask`). This keeps custom endpoints clear of generated CRUD and makes `st.do.X` read the same as
|
|
436
|
+
`fetch.X`.
|
|
437
|
+
- Slice and filter names are prepositional: `inTodo`, `byStatuses`, `ofProject`. Never `getXInY`, never `listX`.
|
|
438
|
+
- Handlers are `onX` props with inline arrows. Do not extract a `handleX`.
|
|
439
|
+
- Booleans are `is*` / `has*` / `can*` / `show*`. Counters are `*Num`, indices are `idx`, collections are `*List`.
|
|
440
|
+
- Identifiers, type names, endpoint names, and log messages are English. Everything a user reads goes through
|
|
441
|
+
`l("task.title")` or `l.trans({ … })` — never a hard-coded string in JSX, never `window.alert`.
|
|
442
|
+
|
|
443
|
+
### Backend
|
|
444
|
+
|
|
445
|
+
- **`constant.ts`** — five classes in order, `TaskInput → TaskObject → LightTask → Task → TaskInsight`, and write
|
|
446
|
+
`TaskInsight` even when empty. Put display and predicate logic on `LightTask` (`isNew()`, `canWrite(user?)`): it is
|
|
447
|
+
the class both server and client hold, so shared logic belongs there rather than in a util module. Collection
|
|
448
|
+
helpers go `static` on the full model.
|
|
449
|
+
- **`document.ts`** — `TaskFilter extends from(...)` → `Task extends by(...)` → `TaskModel extends into(...)`, with
|
|
450
|
+
`sort: {}` always present. Chain methods validate → mutate → `return this` and never `save()`; the caller saves, so
|
|
451
|
+
chains compose. Indexes and derived totals go in `static override _onSchema`.
|
|
452
|
+
- **`service.ts`** — keep methods to a few lines: load → chain → `return await ….save()`. Side effects go in
|
|
453
|
+
`override async _preUpdate` / `_postCreate`, not inline. Fire-and-forget is explicitly `void`-ed. Return `null` or
|
|
454
|
+
`false` for "not allowed" and let the signal decide whether that is an error.
|
|
455
|
+
- **`signal.ts`** — `TaskInternal` → `TaskSlice` → `TaskEndpoint`, all three declared even when empty, and `exec` is a
|
|
456
|
+
one-liner delegating to the service. Every `slice()` takes an explicit `{ guards: { root: Admin, … } }`, and every
|
|
457
|
+
custom mutation, query, and message names its own `guards: [...]`.
|
|
458
|
+
- **`store.ts`** — write a custom action only for a toast, an optimistic update, or a multi-field write; the rest is
|
|
459
|
+
generated. Never `import type { RootStore } from "../st"` — it crashes `akan build` with a Bun SSR segfault.
|
|
460
|
+
- **`dictionary.ts`** — fixed chain with empty stages still written:
|
|
461
|
+
`.of() → .model() → .insight() → .query() → .sort() → .enum() → .slice() → .endpoint() → .error() → .translate()`.
|
|
462
|
+
Every label is `t(["English", "한국어"])`, and nearly every one also carries `.desc([en, ko])`.
|
|
463
|
+
- **`srvkit/` adapters** — an injected singleton is an `adapt("name" as const, ({ use, env, plug, memory }) => ({…}))`
|
|
464
|
+
class, injected with `plug(TheClass)`. It self-registers, so do not add it to `lib/option.ts`. `this.logger` is
|
|
465
|
+
provided; lifecycle work goes in `override async onInit()`. A per-use value object stays a plain class you `new` at
|
|
466
|
+
the call site. Route remote calls through one private `#api<T>(path, init?)` with `AbortSignal.timeout(20_000)`, and
|
|
467
|
+
resolve secrets inside a function, never at module scope.
|
|
468
|
+
- **Errors** — state-machine preconditions throw in `document.ts`, cross-document rules in `service.ts`, and
|
|
469
|
+
request-level policy lives in signal guards. `try/catch` always converts an exception into a decision, never
|
|
470
|
+
swallows one. Store actions do not `try/catch`; let the framework toast the `Err`.
|
|
471
|
+
|
|
472
|
+
### Comments
|
|
473
|
+
|
|
474
|
+
Do not narrate code. Do document the thing the code cannot say. Both halves are the rule.
|
|
475
|
+
|
|
476
|
+
- Never add a comment that restates the identifier, the signature, or the control flow.
|
|
477
|
+
- Do not add JSDoc, section banners, or "why/how" comments for ordinary logic.
|
|
478
|
+
- Density tracks the layer: pages carry none, product code stays under 1 %, and `srvkit/` adapters and `guards.ts`
|
|
479
|
+
carry as much as the external constraints require.
|
|
480
|
+
- A comment is warranted for a vendor spec or protocol quirk, an infrastructure constraint, a third-party library
|
|
481
|
+
gotcha, security reasoning, a math derivation, a domain field's business meaning, a state transition above a
|
|
482
|
+
document chain method, or why an obvious alternative was rejected.
|
|
483
|
+
- Markers: `TODO` unfinished work · `FIXME` known broken behavior · `XXX` hazard a reader must not miss · `//!`
|
|
484
|
+
disabled or must-fix code · `//?` an explanatory aside · `//*` a design note · deletion caution, warning why
|
|
485
|
+
removing a line would break something non-obvious.
|
|
486
|
+
- `//!` is for server, `srvkit/`, and CLI files only. Bun's bundler treats `//!` and `/*!` as legal comments and
|
|
487
|
+
keeps them through minification, so in browser-reachable code the note ships verbatim to every visitor. Use
|
|
488
|
+
`// FIXME:` there — `no-bang-comment-in-client.grit` enforces it.
|
|
489
|
+
- Keep allowed comments to one short line, and give every suppression a reason:
|
|
490
|
+
`// biome-ignore lint/<rule>: <why>`. Never a bare disable block.
|
|
491
|
+
- Match nearby file style: if the surrounding code has few comments, keep it that way.
|
|
492
|
+
|
|
493
|
+
## Generated File Tracker (Quick Reference)
|
|
494
|
+
|
|
495
|
+
These files are regenerated by `akan sync` and overwritten on every sync. **Do not hand-edit them.**
|
|
496
|
+
|
|
497
|
+
| File | Generated From | Purpose |
|
|
498
|
+
|------|---------------|---------|
|
|
499
|
+
| `*/lib/cnst.ts` | All `*/lib/*/**.constant.ts` | Barrel for all constants |
|
|
500
|
+
| `*/lib/db.ts` | All `*/lib/<model>/*.document.ts` | Barrel for all document models |
|
|
501
|
+
| `*/lib/dict.ts` | All `*/lib/*/**.dictionary.ts` | Barrel for all dictionaries |
|
|
502
|
+
| `*/lib/sig.ts` | All `*/lib/**/**.signal.ts` | Barrel for all signals |
|
|
503
|
+
| `*/lib/srv.ts` | All `*/lib/**/**.service.ts` | Barrel for all services |
|
|
504
|
+
| `*/lib/st.ts` | All `*/lib/**/**.store.ts` | Barrel for all stores |
|
|
505
|
+
| `*/lib/useClient.ts` | Client-safe module re-exports | Client-side import entry |
|
|
506
|
+
| `*/lib/useServer.ts` | Server-only module re-exports | Server-side import entry |
|
|
507
|
+
| `apps/*/client.ts` | App-wide client barrel | The `fetch` and `st` instances |
|
|
508
|
+
| `apps/*/server.ts` | App-wide server barrel | Server-side service resolution |
|
|
509
|
+
| `*/lib/**/index.ts` | Per-module barrel | Module-level re-exports |
|
|
510
|
+
| `*/ui/index.ts` | All 1-depth UI files/folders | UI layer-root barrel (nested `ui/<Folder>/index.tsx` is **not** generated) |
|
|
511
|
+
| `*/webkit/index.ts` | All webkit files | Webkit barrel |
|
|
512
|
+
| `*/srvkit/index.ts` | All srvkit files | Srvkit barrel |
|
|
513
|
+
| `*/common/index.ts` | All common files | Common barrel |
|
|
514
|
+
|
|
515
|
+
## Workflow Recipes
|
|
516
|
+
|
|
517
|
+
Concrete step-by-step recipes for the most frequent Akan.js changes. Each recipe shows which files to edit
|
|
518
|
+
and in what order. The code examples reference the `task` module in `apps/<%= appName %>/lib/task/` as a
|
|
519
|
+
template; replace `task` with your model name and `Task` with your PascalCase model name.
|
|
520
|
+
|
|
521
|
+
When editing a file, always read the existing content first. Only change the relevant sections — do not
|
|
522
|
+
rewrite the entire file.
|
|
523
|
+
|
|
524
|
+
---
|
|
525
|
+
|
|
526
|
+
### Recipe 1: Adding a New Field to a Model
|
|
527
|
+
|
|
528
|
+
**Files to edit (in order):** `constant.ts` → `dictionary.ts` → `Template.tsx` → `Unit.tsx` → `akan sync`
|
|
529
|
+
|
|
530
|
+
```typescript
|
|
531
|
+
// 1. apps/<app>/lib/<model>/<model>.constant.ts
|
|
532
|
+
// Add field to the Input class. Use field() builder with optional defaults
|
|
533
|
+
export class TaskInput extends via((field) => ({
|
|
534
|
+
title: field(String),
|
|
535
|
+
priority: field(TaskPriority, { default: "medium" }), // NEW FIELD
|
|
536
|
+
})) {}
|
|
537
|
+
|
|
538
|
+
// If the new field should appear in list views, also add it to LightTask:
|
|
539
|
+
export class LightTask extends via(TaskObject, ["title", "priority", "status", "due"] as const, () => ({})) {}
|
|
540
|
+
|
|
541
|
+
// 2. apps/<app>/lib/<model>/<model>.dictionary.ts
|
|
542
|
+
// Add i18n labels for the new field (and its enum values if any).
|
|
543
|
+
// Labels are [en, ko] pairs, and nearly every one also carries a .desc([en, ko]).
|
|
544
|
+
.model<Task>((t) => ({
|
|
545
|
+
priority: t(["Priority", "우선순위"]).desc(["How urgent the task is", "할 일의 긴급도"]),
|
|
546
|
+
}))
|
|
547
|
+
.enum<TaskPriority>("taskPriority", (t) => ({
|
|
548
|
+
low: t(["Low", "낮음"]),
|
|
549
|
+
medium: t(["Medium", "보통"]),
|
|
550
|
+
high: t(["High", "높음"]),
|
|
551
|
+
}))
|
|
552
|
+
|
|
553
|
+
// 3. apps/<app>/lib/<model>/<Model>.Template.tsx
|
|
554
|
+
// Add a form field using st.do.setXxxOnYyy (auto-generated setter)
|
|
555
|
+
const form = st.use.taskForm();
|
|
556
|
+
<Field.ToggleSelect
|
|
557
|
+
label={l("task.priority")}
|
|
558
|
+
items={cnst.TaskPriority}
|
|
559
|
+
value={form.priority}
|
|
560
|
+
onChange={st.do.setPriorityOnTask}
|
|
561
|
+
/>
|
|
562
|
+
|
|
563
|
+
// 4. apps/<app>/lib/<model>/<Model>.Unit.tsx
|
|
564
|
+
// Display the new field in card/list views
|
|
565
|
+
<Badge variant={task.priority === "high" ? "error" : task.priority === "medium" ? "warning" : "default"}>
|
|
566
|
+
{task.priority}
|
|
567
|
+
</Badge>
|
|
568
|
+
|
|
569
|
+
// 5. Regenerate barrels
|
|
570
|
+
// akan sync <name>
|
|
571
|
+
```
|
|
572
|
+
|
|
573
|
+
---
|
|
574
|
+
|
|
575
|
+
### Recipe 2: Injecting a Dependency into a Service
|
|
576
|
+
|
|
577
|
+
Three patterns: injecting an **external adapter** (`use<>()`), another **module's service** (`service<>()`),
|
|
578
|
+
or a **predefined framework adapter** (`plug()`). A field named `<refName>Service` resolves to the service
|
|
579
|
+
registered under `<refName>` — the `Service`/`Signal` suffix is required and stripped to derive the lookup key.
|
|
580
|
+
|
|
581
|
+
> **For a new adapter you own, prefer the `adapt()` shape in pattern C over the `option.ts` registration in
|
|
582
|
+
> pattern A.** An `adapt()` class self-registers and is injected with `plug(TheClass)`, so it never touches
|
|
583
|
+
> `option.ts`. Pattern A is the legacy constructor-style shape: recognise it, keep it working, and migrate one
|
|
584
|
+
> only when you are already changing it.
|
|
585
|
+
|
|
586
|
+
> `apps/<app>/lib/option.ts` is a **user-owned** file scaffolded once — edit it to register adapters/DI. Unlike the
|
|
587
|
+
> barrels (`cnst.ts`, `db.ts`, `srv.ts`, …) it is **not** overwritten by `akan sync`, so your `.use(...)` registrations
|
|
588
|
+
> are safe.
|
|
589
|
+
|
|
590
|
+
**A. Adapter injection via `use<>()` (for external clients / global singletons)**
|
|
591
|
+
|
|
592
|
+
```typescript
|
|
593
|
+
// 1. Create the adapter class in apps/<app>/srvkit/
|
|
594
|
+
// apps/<app>/srvkit/EmailClient.ts
|
|
595
|
+
export class EmailClient {
|
|
596
|
+
constructor(readonly apiKey: string) {}
|
|
597
|
+
async send(opts: { to: string; subject: string; body: string }) { /* ... */ }
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
// 2. Register in apps/<app>/lib/option.ts
|
|
601
|
+
export const option = new AkanOption()
|
|
602
|
+
.use((options) => ({
|
|
603
|
+
emailClient: new EmailClient(options.mailerApiKey),
|
|
604
|
+
}));
|
|
605
|
+
|
|
606
|
+
// 3. Inject via use<>() in <model>.service.ts
|
|
607
|
+
export class TaskService extends serve(db.task, ({ use }) => ({
|
|
608
|
+
emailClient: use<EmailClient>(),
|
|
609
|
+
})) {
|
|
610
|
+
async _postCreate(task: cnst.Task) {
|
|
611
|
+
await this.emailClient.send({ to: "...", subject: "Task Created", body: `Task "${task.title}" created.` });
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
```
|
|
615
|
+
|
|
616
|
+
**B. Cross-module service injection via `service<>()` (for other Akan services)**
|
|
617
|
+
|
|
618
|
+
```typescript
|
|
619
|
+
// In <model>.service.ts — inject another module's service
|
|
620
|
+
import * as srv from "../srv";
|
|
621
|
+
|
|
622
|
+
export class TaskService extends serve(db.task, ({ service }) => ({
|
|
623
|
+
notiService: service<srv.NotiService>(),
|
|
624
|
+
})) {
|
|
625
|
+
async _postCreate(task: cnst.Task) {
|
|
626
|
+
await this.notiService.send("info", `Task "${task.title}" created`);
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
```
|
|
630
|
+
|
|
631
|
+
**C. Predefined framework adapter injection via `plug()` (storage, cache, queue, schedule, …)**
|
|
632
|
+
|
|
633
|
+
Akan ships predefined adapter roles from `akanjs/service`: `StorageAdaptorRole`, `CacheAdaptorRole`,
|
|
634
|
+
`QueueAdaptorRole`, `ScheduleAdaptorRole`, `DatabaseAdaptorRole`, `WebsocketAdaptorRole`,
|
|
635
|
+
`LoggingAdaptorRole`, `CompressAdaptorRole`. `plug()` injects the concrete adapter bound to that role (the
|
|
636
|
+
default `StorageAdaptor` binding is `BlobStorage`). `plug()` also accepts a concrete adapter class directly.
|
|
637
|
+
|
|
638
|
+
```typescript
|
|
639
|
+
// In <model>.service.ts — inject the framework storage adapter by role
|
|
640
|
+
import { plug, serve, StorageAdaptorRole } from "akanjs/service";
|
|
641
|
+
|
|
642
|
+
export class TaskService extends serve(db.task, ({ plug }) => ({
|
|
643
|
+
storage: plug(StorageAdaptorRole),
|
|
644
|
+
})) {
|
|
645
|
+
async attach(taskId: string, path: string, localPath: string) {
|
|
646
|
+
// BlobStorage returns a URL under blobStorage.urlPrefix (default "/api/localFile/getBlob").
|
|
647
|
+
return await this.storage.uploadDataFromLocal({ path, localPath });
|
|
648
|
+
}
|
|
649
|
+
}
|
|
650
|
+
```
|
|
651
|
+
|
|
652
|
+
For a custom adapter class (not a predefined role), pass the class itself, e.g. `ipfsApi: plug(IpfsApi)`
|
|
653
|
+
(see `libs/shared/lib/file/file.service.ts`). Injecting a file/image field is usually simpler than calling
|
|
654
|
+
storage directly: declare `image: field(File).optional()` (or `images: field([File])`) on the model and let the
|
|
655
|
+
store's generated `upload<Field>On<Model>(fileList)` action handle the upload. Add `{ cascade: "removeRef" }` to that
|
|
656
|
+
field when the file belongs to the model alone, and removing the model removes the file and its stored object.
|
|
657
|
+
|
|
658
|
+
---
|
|
659
|
+
|
|
660
|
+
### Recipe 3: Creating and Using a Slice
|
|
661
|
+
|
|
662
|
+
A Slice is a named, filtered data view. Add file entries and connect from a page.
|
|
663
|
+
|
|
664
|
+
> **Silent failure — a slice `exec` must return a query descriptor, never an executed list.**
|
|
665
|
+
> Return `this.taskService.queryByStatuses(...)` (the `query<Filter>` builder), **not**
|
|
666
|
+
> `this.taskService.listByStatuses(...)` / `listBy...(...)` (which returns a `Promise<Doc[]>`).
|
|
667
|
+
> Returning an array type-checks but throws at runtime during insight aggregation with the opaque
|
|
668
|
+
> `Error: Unknown document field path: 0`. If you see that error, your slice is returning a list, not a query.
|
|
669
|
+
|
|
670
|
+
```typescript
|
|
671
|
+
// 1. apps/<app>/lib/<model>/<model>.signal.ts — Define the slice
|
|
672
|
+
export class TaskSlice extends slice(srv.task, (init) => ({
|
|
673
|
+
inTodo: init()
|
|
674
|
+
.search("statuses", [cnst.TaskStatus])
|
|
675
|
+
.exec(function (statuses?) {
|
|
676
|
+
// ✅ query<Filter> — a query descriptor. ❌ listByStatuses(...) returns an array and fails at runtime.
|
|
677
|
+
return this.taskService.queryByStatuses(statuses ?? ["todo", "inProgress"]);
|
|
678
|
+
}),
|
|
679
|
+
})) {}
|
|
680
|
+
|
|
681
|
+
// 2. apps/<app>/lib/<model>/<model>.document.ts — Add query filter for slice
|
|
682
|
+
export class TaskFilter extends from(cnst.Task, (filter) => ({
|
|
683
|
+
query: {
|
|
684
|
+
byStatuses: filter()
|
|
685
|
+
.arg("statuses", [cnst.TaskStatus])
|
|
686
|
+
.query((statuses) => ({ status: { $in: statuses } })),
|
|
687
|
+
},
|
|
688
|
+
})) {}
|
|
689
|
+
|
|
690
|
+
// 3. apps/<app>/lib/<model>/<model>.dictionary.ts — Slice labels
|
|
691
|
+
.slice<TaskSlice>((fn) => ({
|
|
692
|
+
inTodo: fn(["Tasks In Todo", "할 일"]).arg((t) => ({
|
|
693
|
+
statuses: t(["Statuses", "상태"]),
|
|
694
|
+
})),
|
|
695
|
+
}))
|
|
696
|
+
|
|
697
|
+
// 4. In page — Init the slice in an async Page and hand the init to a Zone.
|
|
698
|
+
export default async function Page() {
|
|
699
|
+
const [{ taskInitInTodo }] = await Promise.all([fetch.initTaskInTodo()]);
|
|
700
|
+
return <Task.Zone.Card init={taskInitInTodo} sliceName="taskInTodo" />;
|
|
701
|
+
}
|
|
702
|
+
```
|
|
703
|
+
|
|
704
|
+
The slice name in code uses camelCase (`inTodo`). In dictionary and components it becomes `"taskInTodo"`.
|
|
705
|
+
|
|
706
|
+
---
|
|
707
|
+
|
|
708
|
+
### Recipe 4: Creating a Mutation Endpoint (with Status Workflow)
|
|
709
|
+
|
|
710
|
+
**Files to edit (in order):** `document.ts` → `service.ts` → `signal.ts` → `dictionary.ts` → `store.ts` → `Util.tsx`
|
|
711
|
+
|
|
712
|
+
```typescript
|
|
713
|
+
// 1. <model>.document.ts — Document chain method with state validation
|
|
714
|
+
export class TaskDocument extends by(cnst.Task) {
|
|
715
|
+
start() {
|
|
716
|
+
if (this.status !== "todo") throw new Err("task.error.cannotStartFromNonTodo");
|
|
717
|
+
this.status = "inProgress";
|
|
718
|
+
return this; // Return this for chaining: task.start().save()
|
|
719
|
+
}
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
// 2. <model>.service.ts — Service method wrapping document
|
|
723
|
+
async startTask(taskId: string) {
|
|
724
|
+
const task = await this.getTask(taskId);
|
|
725
|
+
return task.start().save();
|
|
726
|
+
}
|
|
727
|
+
|
|
728
|
+
// 3. <model>.signal.ts — Mutation endpoint
|
|
729
|
+
export class TaskEndpoint extends endpoint(srv.task, ({ mutation }) => ({
|
|
730
|
+
startTask: mutation(cnst.Task)
|
|
731
|
+
.param("taskId", String)
|
|
732
|
+
.exec(async function (taskId) {
|
|
733
|
+
return await this.taskService.startTask(taskId);
|
|
734
|
+
}),
|
|
735
|
+
})) {}
|
|
736
|
+
|
|
737
|
+
// 4. <model>.dictionary.ts — Endpoint + error labels
|
|
738
|
+
.endpoint<TaskEndpoint>((fn) => ({
|
|
739
|
+
startTask: fn(["Start Task", "작업시작"])
|
|
740
|
+
.arg((t) => ({ taskId: t(["Task ID", "할 일 ID"]) })),
|
|
741
|
+
}))
|
|
742
|
+
.error({
|
|
743
|
+
cannotStartFromNonTodo: ["Task can only start from todo status", "할 일 상태에서만 시작 가능"],
|
|
744
|
+
})
|
|
745
|
+
|
|
746
|
+
// 5. <model>.store.ts — Client-side action with toast feedback
|
|
747
|
+
async startTask(taskId: string) {
|
|
748
|
+
msg.loading("task.startTaskLoading", { key: "startTask" });
|
|
749
|
+
const task = await fetch.startTask(taskId);
|
|
750
|
+
this.setTask(task); // Auto-generated: updates task state in store
|
|
751
|
+
msg.success("task.startTaskSuccess", { key: "startTask" });
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
// 6. <Model>.Util.tsx — Reusable button component
|
|
755
|
+
export const Start = ({ taskId }: { taskId: string }) => (
|
|
756
|
+
<button className={buttonRecipe({ variant: "primary", size: "xs" })} onClick={() => st.do.startTask(taskId)}>
|
|
757
|
+
Start
|
|
758
|
+
</button>
|
|
759
|
+
);
|
|
760
|
+
```
|
|
761
|
+
|
|
762
|
+
---
|
|
763
|
+
|
|
764
|
+
### Recipe 5: Internal Triggers — Interval & Cron
|
|
765
|
+
|
|
766
|
+
Server-side background jobs. Defined in `internal()` signal, implemented in service.
|
|
767
|
+
|
|
768
|
+
```typescript
|
|
769
|
+
// 1. <model>.signal.ts — Define triggers
|
|
770
|
+
export class TaskInternal extends internal(srv.task, ({ interval, cron }) => ({
|
|
771
|
+
cleanupStaleTasks: interval(10000).exec(async function () {
|
|
772
|
+
await this.taskService.cleanupStaleTasks();
|
|
773
|
+
}),
|
|
774
|
+
|
|
775
|
+
dailyDigest: cron("0 0 * * *").exec(async function () {
|
|
776
|
+
await this.taskService.sendDailyDigest();
|
|
777
|
+
}),
|
|
778
|
+
})) {}
|
|
779
|
+
|
|
780
|
+
// 2. <model>.service.ts — Implement the logic
|
|
781
|
+
async cleanupStaleTasks() {
|
|
782
|
+
const weekAgo = dayjs().subtract(7, "day").toDate();
|
|
783
|
+
const stale = await this.taskModel.listDueBefore(weekAgo);
|
|
784
|
+
for (const task of stale) {
|
|
785
|
+
await task.remove();
|
|
786
|
+
}
|
|
787
|
+
}
|
|
788
|
+
```
|
|
789
|
+
|
|
790
|
+
**Available trigger types:**
|
|
791
|
+
- `interval(ms)` — runs repeatedly at the given interval
|
|
792
|
+
- `cron("min hour dom month dow")` — runs on a schedule
|
|
793
|
+
- `initialize()` — runs once on service startup
|
|
794
|
+
- `process(Return).msg(Type)` — message queue consumer
|
|
795
|
+
|
|
796
|
+
---
|
|
797
|
+
|
|
798
|
+
### Recipe 6: Creating an Insight (Aggregation / Dashboard Stats)
|
|
799
|
+
|
|
800
|
+
Insights display aggregated statistics across model data.
|
|
801
|
+
|
|
802
|
+
```typescript
|
|
803
|
+
// 1. <model>.constant.ts — Insight class with accumulate rules
|
|
804
|
+
export class TaskInsight extends via(Task, (field) => ({
|
|
805
|
+
totalCount: field(Int, { default: 0, accumulate: {} }),
|
|
806
|
+
completedCount: field(Int, { default: 0, accumulate: { status: "completed" } }),
|
|
807
|
+
})) {}
|
|
808
|
+
|
|
809
|
+
// 2. <model>.dictionary.ts — Insight field labels
|
|
810
|
+
.insight<TaskInsight>((t) => ({
|
|
811
|
+
totalCount: t(["Total Tasks", "전체 할 일"]),
|
|
812
|
+
completedCount: t(["Completed", "완료됨"]),
|
|
813
|
+
}))
|
|
814
|
+
|
|
815
|
+
// 3. <Model>.View.tsx — Display component consuming an Insight model
|
|
816
|
+
export const Stats = ({ taskInsight }: { taskInsight: cnst.TaskInsight }) => (
|
|
817
|
+
<div className="grid grid-cols-2 gap-4">
|
|
818
|
+
<div className="rounded-lg border border-border bg-card p-4">
|
|
819
|
+
<div className="text-muted-foreground text-sm">{l("task.totalCount")}</div>
|
|
820
|
+
<div className="font-bold text-2xl text-primary">{taskInsight.totalCount}</div>
|
|
821
|
+
</div>
|
|
822
|
+
<div className="rounded-lg border border-border bg-card p-4">
|
|
823
|
+
<div className="text-muted-foreground text-sm">{l("task.completedCount")}</div>
|
|
824
|
+
<div className="font-bold text-2xl text-success">{taskInsight.completedCount}</div>
|
|
825
|
+
</div>
|
|
826
|
+
</div>
|
|
827
|
+
);
|
|
828
|
+
|
|
829
|
+
// 4. <Model>.Zone.tsx — Mount in page via Load.Insight bound to a slice
|
|
830
|
+
export const Insight = ({ sliceName }: { sliceName: string }) => {
|
|
831
|
+
const insight = st.slice[sliceName].use.taskInsight();
|
|
832
|
+
if (!insight) return null;
|
|
833
|
+
return <Task.View.Stats taskInsight={insight} />;
|
|
834
|
+
};
|
|
835
|
+
```
|
|
836
|
+
|
|
837
|
+
---
|
|
838
|
+
|
|
839
|
+
### Data Flow Summary
|
|
840
|
+
|
|
841
|
+
For each business question, follow this chain:
|
|
842
|
+
|
|
843
|
+
| Question | File Pattern |
|
|
844
|
+
|----------|-------------|
|
|
845
|
+
| What fields does it have? | `constant.ts` — `via()` layers: Input → Object → Light → Model → Insight |
|
|
846
|
+
| How is it stored/searched? | `document.ts` — `from()` filters + `by()` document methods + `into()` model |
|
|
847
|
+
| What business rule should run? | `service.ts` — `serve()` with DI (`use`, `service`, `plug`, `env`, `memory`) |
|
|
848
|
+
| What should a page call? | `signal.ts` — `internal()` (jobs), `endpoint()` (APIs), `slice()` (data views) |
|
|
849
|
+
| What client state is shared? | `store.ts` — `store()` with auto-generated form/insight state + custom actions |
|
|
850
|
+
| What should users see? | `View.tsx` + `Zone.tsx` (detail/container), `Template.tsx` (forms), `Unit.tsx` (cards), `Util.tsx` (buttons) |
|
|
851
|
+
|
|
852
|
+
## Modeling & Query Gotchas
|
|
853
|
+
|
|
854
|
+
A short list of things the type system does not always catch:
|
|
855
|
+
|
|
856
|
+
- **Slices return a query, not a list.** A slice `exec` must return `this.<model>Service.query<Filter>(...)`, never
|
|
857
|
+
a `list<Filter>(...)` / `listBy...(...)` array. Returning an array type-checks but fails at runtime with
|
|
858
|
+
`Unknown document field path: 0`. (See Recipe 3.)
|
|
859
|
+
- **Custom endpoint names must not collide with generated CRUD.** `create/update/remove/view/edit/merge<Model>`
|
|
860
|
+
already exist. A collision can build green and fail only at runtime — pick a distinct verb.
|
|
861
|
+
- **Numbers are `Int` or `Float`, never `Number`.** `field(Number)` / `.body("x", Number)` fail to typecheck. Use
|
|
862
|
+
`Int` for counts, `Float` for decimals.
|
|
863
|
+
- **Array fields use `field([T])`.** e.g. `tags: field([String])`, `images: field([File])` — not `field(String)` with
|
|
864
|
+
a suffix.
|
|
865
|
+
- **Reading a secret field needs an explicit select.** `field(...).secret()` values (e.g. `passwordHash`) are stripped
|
|
866
|
+
from query results by default. Fetch them with `{ select: { <field>: true } }`, e.g.
|
|
867
|
+
`this.userModel.pickById(id, { select: { passwordHash: true } })`.
|
|
868
|
+
- **Text search fields use the `text` role.** Opt a field into the full-text index with
|
|
869
|
+
`field(String, { text: "title" })` (or `"desc"` / `"tag"` / `"thumb"` / `"filter"`). Nothing else opts a field in.
|
|
870
|
+
`secret` / `hidden` / `resolve()` fields with `text` throw at class-build time — the mirror is plaintext. Search
|
|
871
|
+
runs on sqlite/libsql only; `q.search()` against Postgres throws. `thumb` is mirrored for rendering and is not
|
|
872
|
+
indexed.
|
|
873
|
+
- **`cascade` names a direction, and the wrong one is a data loss.** Both actions can sit on the same field shape,
|
|
874
|
+
so the value has to say which end goes away. `cascade: "removeRef"` on the relation an owner holds
|
|
875
|
+
(`image: field(File, { cascade: "removeRef" })`, arrays included) removes the target when the owner is removed;
|
|
876
|
+
only a relation accepts it. `cascade: "removeWith"` on a child's own reference to its owner
|
|
877
|
+
(`field(ID, { ref: "agentSession", cascade: "removeWith" })`, or a relation, or `refPath` for a polymorphic
|
|
878
|
+
owner whose type field must be an `enumOf`) removes the child when the owner is — the owner never learns its
|
|
879
|
+
children exist. The removal runs through the **target's service** so its `_postRemove` runs too, unless the
|
|
880
|
+
target provably has no removal side effect, in which case the boot-time plan collapses it into one query. A
|
|
881
|
+
`removeWith` field gets its index automatically. Nothing checks for other references to the same target, so
|
|
882
|
+
`removeRef` asserts exclusive ownership. Removal is soft but a storage delete is not, and a query-level removal
|
|
883
|
+
fires no hooks and therefore no cascade.
|
|
884
|
+
- **Removal is always soft, and `delete` is reserved.** `remove(id)`, the facade's `removeMany(query)`, and the
|
|
885
|
+
store's `removeManyByQuery` all stamp `removedAt`; the framework has no hard delete for a model table.
|
|
886
|
+
- **The model facade spells out `Many`/`One` on its writes** — `updateOne`, `updateMany`, `removeOne`, `removeMany`
|
|
887
|
+
— because a bare `update`/`remove` would read like the document-path `update(id)` / `doc.remove()` while hitting
|
|
888
|
+
every match. Reads keep the short `find`/`findOne` pair, and counting is `count(query)` (`countDocuments` is
|
|
889
|
+
`@deprecated`).
|
|
890
|
+
- **`q.search()` is a filter node, not a slice requirement.** Prefer
|
|
891
|
+
`bySearch: filter().arg("text", String).query((text, q) => q.search(text, { prefix: true }))` — the generated
|
|
892
|
+
`listBySearch` / `countBySearch` / `queryBySearch` / `insightBySearch` come for free. Only add a search slice when
|
|
893
|
+
the model's data is safe to enumerate. It must sit at an AND position (not under `q.any()` / `q.not()`), blank
|
|
894
|
+
input matches nothing, and score order needs the built-in `relevance` sort key — a slice endpoint that leaves
|
|
895
|
+
`sort` off gets `latest`, not relevance.
|
|
896
|
+
|
|
897
|
+
## Current User, Guards & Auth-Gated Pages
|
|
898
|
+
|
|
899
|
+
Built-in user authentication (session / JWT / password hashing) ships as a separate Akan auth library, not in the
|
|
900
|
+
core framework. The core framework gives you the composition points below; wire the auth library through them.
|
|
901
|
+
|
|
902
|
+
- **Guards** attach at the signal declaration, not per-method:
|
|
903
|
+
`endpoint(srv.task, { guards: { root: SignedIn } }, ({ mutation }) => ({...}))` or
|
|
904
|
+
`slice(srv.task, { guards: { root: SignedIn, get: Public, cru: Public } }, ...)`. `Public` always allows; other
|
|
905
|
+
guards implement the `Guard` interface in `srvkit/` (server-only) and read the request context.
|
|
906
|
+
- **Read the current user inside a custom endpoint** by injecting an `InternalArg` with `.with(...)`:
|
|
907
|
+
`mutation(cnst.Task).with(CurrentUserId).exec(async function (currentUserId) { ... })`. The `Guard` /
|
|
908
|
+
`InternalArg` helpers live in `srvkit/` and read `context.getHttpContext().req.user`.
|
|
909
|
+
- **Auto-generated CRUD and `serve()` service methods / lifecycle hooks do not receive session context.** If an
|
|
910
|
+
operation needs the acting user, expose a custom endpoint that takes it via `.with(CurrentUserId)` — never trust a
|
|
911
|
+
client-supplied user id.
|
|
912
|
+
- **SSR auth-gated pages: guard at the layout.** Check the session in the `_layout.tsx` loader and redirect when it is
|
|
913
|
+
absent, so nested pages never render for signed-out users.
|
|
914
|
+
|
|
915
|
+
## Auto-Generated API Reference
|
|
916
|
+
|
|
917
|
+
akan sync automatically generates APIs across all layers. Only write custom logic — never hand-write what the framework generates.
|
|
918
|
+
|
|
919
|
+
### Signal — Endpoint Auto-Generation
|
|
920
|
+
|
|
921
|
+
| Auto-Generated | Signature | Description |
|
|
922
|
+
|---------------|-----------|-------------|
|
|
923
|
+
| `view[Model](id)` | `fetch.viewTask(id)` | Fetch single model for detail view |
|
|
924
|
+
| `edit[Model](id)` | `fetch.editTask(id)` | Fetch model for edit view |
|
|
925
|
+
| `merge[Model](id, data)` | `fetch.mergeTask(data)` | Create (no id) or update (with id) model |
|
|
926
|
+
| `[model]List[Suffix](args, skip, limit, sort)` | `fetch.taskListInTodo(args)` | Paginated list from slice filter |
|
|
927
|
+
| `[model]Insight[Suffix](args)` | `fetch.taskInsightInTodo(args)` | Aggregated insight from slice query |
|
|
928
|
+
| `init[Model][Suffix](args)` | `fetch.initTaskInTodo(args)` | Initialize slice with list + insight |
|
|
929
|
+
|
|
930
|
+
**Rule**: Only define `query()`, `mutation()`, `message()`, `pubsub()` endpoints manually when the endpoint needs custom business logic. Standard CRUD is already auto-generated.
|
|
931
|
+
|
|
932
|
+
### Service — CRUD & Query Auto-Generation
|
|
933
|
+
|
|
934
|
+
| Auto-Generated | Description |
|
|
935
|
+
|---------------|-------------|
|
|
936
|
+
| `this.<model>Model` | Auto-injected model adaptor |
|
|
937
|
+
| `get<Model>(id)`, `load<Model>(id)` | Single document lookup |
|
|
938
|
+
| `create<Model>(data)`, `update<Model>(id, data)`, `remove<Model>(id)` | CRUD operations — named after the model, e.g. `createTask`/`updateTask`/`removeTask` (there is no literal `createModel`) |
|
|
939
|
+
| `list<Query>(args)`, `find<Query>(args)`, `pick<Query>(args)` | Filter-based queries |
|
|
940
|
+
| `exists<Query>(args)`, `count<Query>(args)`, `insight<Query>(args)` | Filter-based helpers |
|
|
941
|
+
| `_preCreate`, `_postCreate`, `_preUpdate`, `_postUpdate`, `_preRemove`, `_postRemove` | Lifecycle hooks (override to add logic) |
|
|
942
|
+
|
|
943
|
+
**Rule**: Use `_preCreate`/`_postCreate` lifecycle hooks for side effects (e.g., push workHistory entries). Write custom service methods only for multi-model orchestration.
|
|
944
|
+
|
|
945
|
+
### Store — State & Action Auto-Generation
|
|
946
|
+
|
|
947
|
+
| Auto-Generated | Description |
|
|
948
|
+
|---------------|-------------|
|
|
949
|
+
| `[model]` (cached full model), `[model]Loading`, `[model]Form`, `[model]Modal` | Base model states |
|
|
950
|
+
| `create[Model](data)`, `update[Model](id, data)`, `remove[Model](id)` | CRUD actions |
|
|
951
|
+
| `new[Model](partial)`, `edit[Model](model)`, `view[Model](model)` | Form/view state actions |
|
|
952
|
+
| `[slice]List`, `[slice]InitList`, `[slice]Insight`, `[slice]Selection` | Slice states |
|
|
953
|
+
| `init[Slice](args)`, `refresh[Slice]()`, `setPageOf[Slice](page)` | Slice actions |
|
|
954
|
+
| `set[Field]On[Model](value)` | Auto-setters for each model field |
|
|
955
|
+
|
|
956
|
+
**Rule**: Write custom store actions only for toast messages (`msg.loading`/`msg.success`) or multi-step workflows. State fields and CRUD actions are already auto-generated.
|
|
957
|
+
|
|
958
|
+
### Document — Filter Query Auto-Generation
|
|
959
|
+
|
|
960
|
+
| Auto-Generated (from Filter definition) | Description |
|
|
961
|
+
|----------------------------------------|-------------|
|
|
962
|
+
| `list[Query](args)`, `listIds[Query](args)` | List documents matching filter |
|
|
963
|
+
| `find[Query](args)`, `findId[Query](args)` | Find one (null if not found) |
|
|
964
|
+
| `pick[Query](args)`, `pickId[Query](args)` | Find one (throw if not found) |
|
|
965
|
+
| `exists[Query](args)`, `count[Query](args)` | Existence check and count |
|
|
966
|
+
| `insight[Query](args)`, `query[Query](args)` | Insight and raw query |
|
|
967
|
+
| `remove[Query](args)`, `removeOne[Query](args)` | Query-level soft remove — all matches, or the newest one (`createdAt` desc, not caller-chosen) |
|
|
968
|
+
| `update[Query](args).set(patch)`, `updateOne[Query](args).set(patch)` | Query-level update — the patch lands on a terminal `.set()`, because a filter's trailing args may be optional |
|
|
969
|
+
|
|
970
|
+
**Rule**: Define `Filter` with `.query()` conditions in `document.ts`. akan sync auto-generates all 14 query helper methods per filter. Write `Document` chain methods only for state transitions with validation.
|
|
971
|
+
|
|
972
|
+
**The four query-level writes fire no hooks**, so no `_pre`/`_postRemove` and no cascade run — same as `updateManyByQuery`. Reach for them when the model carries no removal side effect; otherwise remove documents one at a time. A filter keyed after its own model (filter `chat` on model `chat`) is rejected at boot, because `removeChat`/`updateChat` would otherwise shadow the generated single-document CRUD.
|