@bitakit/cli 0.0.0-stage → 0.2.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 +21 -0
- package/README.md +153 -2
- package/package.json +44 -4
- package/src/add.mjs +190 -0
- package/src/agent-rules.mjs +52 -0
- package/src/build.mjs +203 -0
- package/src/cli.mjs +266 -0
- package/src/doctor.mjs +908 -0
- package/src/index.mjs +30 -0
- package/src/init.mjs +254 -0
- package/src/inventory.mjs +126 -0
- package/src/project.mjs +97 -0
- package/src/routes.mjs +124 -0
- package/src/templates.mjs +530 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Majid Vesal
|
|
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,154 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @bitakit/cli
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The `bitakit` command for BitaKit projects: wire an existing app, add plugins and their files
|
|
4
|
+
from templates, generate the wiring, migrate a 0.1 project, check a project for common problems,
|
|
5
|
+
and build plugin packages. New in 0.2.
|
|
6
|
+
|
|
7
|
+
Apps created with `@bitakit/create-app` 0.2 already include it as a dev dependency. Elsewhere:
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
npm install --save-dev @bitakit/cli
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Run it with `npx bitakit <command>` inside your app or plugin package.
|
|
14
|
+
|
|
15
|
+
## Wire an existing app
|
|
16
|
+
|
|
17
|
+
```sh
|
|
18
|
+
npx bitakit init
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
In an existing Next.js or TanStack Start app, `init` writes `bitakit.config.ts`, wraps
|
|
22
|
+
`next.config` with `withBitaKit` (or adds `bitakit()` to the Vite plugins), mounts
|
|
23
|
+
`<BitaKitProvider>` around `{children}` of the root layout, adds the catch-all route that renders
|
|
24
|
+
`<PluginPage />`, ignores `src/bitakit.gen.*` and appends the agent rules to `AGENTS.md`. It prints what it wrote (`+` new file, `~`
|
|
25
|
+
changed file) and what it skipped. Files that already carry the wiring are never touched, so it
|
|
26
|
+
is safe to run again; a shape it cannot edit (for example a CommonJS `next.config.js`) is
|
|
27
|
+
skipped with the line to add by hand. Packages are not installed: `init` lists the missing ones
|
|
28
|
+
(`@bitakit/core`, `@bitakit/discovery`, `@bitakit/ui` and the framework adapter). Then run `generate` and `doctor`.
|
|
29
|
+
`create-bitakit-app` writes the same wiring for new apps from the same templates.
|
|
30
|
+
|
|
31
|
+
## Add a feature
|
|
32
|
+
|
|
33
|
+
```sh
|
|
34
|
+
npx bitakit add plugin notes
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
This creates `src/plugins/notes/` with a page at `/notes` and, with Shell, its navigation
|
|
38
|
+
Action; discovery connects it, so there is nothing to register. `--example` writes a complete
|
|
39
|
+
feature (service, events, Actions, page); `--minimal` only a service, its events and one action.
|
|
40
|
+
|
|
41
|
+
Add single files to an existing plugin (inside a plugin package, give only the name):
|
|
42
|
+
|
|
43
|
+
```sh
|
|
44
|
+
npx bitakit add action notes/archive # actions/archive.ts → notes.archive
|
|
45
|
+
npx bitakit add service notes/search # services/search.ts → services.notes.search
|
|
46
|
+
npx bitakit add page notes/archive # ui/pages/archive.tsx → /notes/archive
|
|
47
|
+
npx bitakit add interceptor notes/audit # interceptors/audit.ts
|
|
48
|
+
npx bitakit add config notes/limits # configs/limits.ts → app.config.notes.limits
|
|
49
|
+
npx bitakit add events notes # events.ts
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
The file path decides the ID; nested names such as `notes/team/invite` create
|
|
53
|
+
`actions/team/invite.ts` with the ID `notes.team.invite`. Existing files are never overwritten.
|
|
54
|
+
|
|
55
|
+
## Generate and migrate
|
|
56
|
+
|
|
57
|
+
```sh
|
|
58
|
+
npx bitakit generate # write src/bitakit.gen.* from the plugin folders and installed packages
|
|
59
|
+
npx bitakit generate --watch # keep regenerating while files change
|
|
60
|
+
npx bitakit migrate --dry-run # list the changes from a 0.1 layout
|
|
61
|
+
npx bitakit migrate # apply them: bitakit.config.ts, folder-only files, ui/, generated imports,
|
|
62
|
+
# setup({ scope }), placement slot, slots.attach({ slot }), Foundation* →
|
|
63
|
+
# BitaKit* names and Core names moved from @bitakit/ui to @bitakit/core
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
The framework adapters run the generator themselves during `dev` and `build`; `generate` is for
|
|
67
|
+
scripts and type checks. After a migration, review the diff, then run `generate` and `doctor`.
|
|
68
|
+
The migrated `bitakit.config.ts` imports `defineBitaKit` from `@bitakit/discovery`; install it as a
|
|
69
|
+
dev dependency if the project does not list it yet.
|
|
70
|
+
|
|
71
|
+
## Check a project
|
|
72
|
+
|
|
73
|
+
```sh
|
|
74
|
+
npx bitakit doctor # human-readable report, exit code 1 on problems
|
|
75
|
+
npx bitakit doctor --json # for CI
|
|
76
|
+
npx bitakit info [--json] # the plugins, services, actions, events and pages discovery finds
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
Doctor checks package versions, duplicate copies of `@bitakit/core`, the config wrapper and
|
|
80
|
+
provider wiring, scripts that still force Webpack or `foundation-generate`, ignored generated
|
|
81
|
+
files, plugin pages and links no route reaches, colliding service names, `requires` entries that
|
|
82
|
+
name nothing, plugin dependency cycles, missing package styles and deprecated layouts, and prints
|
|
83
|
+
a fix for each problem.
|
|
84
|
+
|
|
85
|
+
The `requires` check reads the string literals of `requires` in services, actions, interceptors
|
|
86
|
+
and in `export const requires` of provider files. A name must be a service ID, an `exposeAs`
|
|
87
|
+
alias or the contract of a `provides` key of the app or a local plugin. Dotted names inside a
|
|
88
|
+
local plugin's namespace (`notes.items`) are checked exactly, including against plugins turned
|
|
89
|
+
off in `plugins.overrides`. Other names, such as the contract `auth`, can come from installed
|
|
90
|
+
plugin packages, from host `services` or from keys declared in other files, which doctor cannot
|
|
91
|
+
list, so they are only checked when none of those exist. The graph check reports a cycle in the `dependencies` of
|
|
92
|
+
`plugin.config.ts` as an error and enabled plugins that depend on disabled ones as a warning.
|
|
93
|
+
|
|
94
|
+
## Build a plugin package
|
|
95
|
+
|
|
96
|
+
Inside a package created with `npx @bitakit/create-app my-plugin --plugin`:
|
|
97
|
+
|
|
98
|
+
```sh
|
|
99
|
+
npx bitakit build # types, compiled sources and dist/plugin.js
|
|
100
|
+
npx bitakit build --check # type-check only
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
The package's `package.json` declares `bitakit: { plugin: './plugin' }`; apps that install the
|
|
104
|
+
built package discover the plugin automatically.
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
### Slot declaration or UI contribution
|
|
108
|
+
|
|
109
|
+
```sh
|
|
110
|
+
bitakit add slot-definition notes/header/tools # slots/header/tools.ts, owned by notes
|
|
111
|
+
bitakit add slot notes/app-bar/end # ui/slots/app-bar/end.tsx, contributes UI
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
In a plugin package, omit the plugin prefix. `bitakit build` compiles definitions and augments
|
|
115
|
+
`SlotMap`; the generated `dist/plugin.slots.json` is a derived static inventory for Doctor.
|
|
116
|
+
Keep it with the published entry. Doctor reports duplicate contracts, component/contract
|
|
117
|
+
mismatches and unresolved computed records without executing plugin source. It does not prove
|
|
118
|
+
that a UI outlet is mounted or that a plugin is ready.
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
`bitakit build` preserves `settings.ts` and `ui/settings/page.tsx` in the package factory and
|
|
122
|
+
emits SettingsMap augmentations. Custom/extra page descriptors, named page boundaries and
|
|
123
|
+
slot `when` exports pass through the same normalizers used for local app discovery.
|
|
124
|
+
|
|
125
|
+
## Inspection and explicit placement migration
|
|
126
|
+
|
|
127
|
+
`bitakit info` and `bitakit info --json` use the shared inventory schema:
|
|
128
|
+
|
|
129
|
+
```json
|
|
130
|
+
{ "version": 1, "static": { "plugins": [] }, "live": null }
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
This replaces the old raw discovery JSON. Files remain `resolution: "file"` with an unavailable
|
|
134
|
+
ID until resolved; installed package entrypoints can have `pluginId`/`declarations: null`.
|
|
135
|
+
The CLI does not execute plugins to invent live readiness. Config and Settings values are omitted.
|
|
136
|
+
|
|
137
|
+
```sh
|
|
138
|
+
bitakit add slot-definition notes/toolbar
|
|
139
|
+
bitakit add settings-page notes
|
|
140
|
+
bitakit migrate --navigation-slot shell.navigation --dry-run
|
|
141
|
+
# Review the diff before running the same explicit migration without --dry-run.
|
|
142
|
+
bitakit doctor
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
Doctor warns about literal `groups: ['navigation']` Actions without explicit placement when
|
|
146
|
+
Shell is installed. The opt-in migration adds the chosen `slots` target and retains logical
|
|
147
|
+
groups. It skips spread-based ambiguous objects; imported/computed declarations require manual
|
|
148
|
+
review. No group name is automatically reinterpreted as a slot. Migration scans the app source
|
|
149
|
+
root; externally included plugin directories require their own review. For a legacy 0.1 layout,
|
|
150
|
+
finish/review the layout migration before previewing placement changes.
|
|
151
|
+
|
|
152
|
+
`settings-page` writes `ui/settings/page.tsx` and uses the existing `renderField` callback;
|
|
153
|
+
`@bitakit/app-preferences` must be installed. It creates neither a value store nor navigation
|
|
154
|
+
Actions. Templates never overwrite existing files.
|
package/package.json
CHANGED
|
@@ -1,6 +1,46 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@bitakit/cli",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "BitaKit project commands: add plugins and contributions, check a project with doctor.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": {
|
|
7
|
+
"bitakit": "./src/cli.mjs"
|
|
8
|
+
},
|
|
9
|
+
"exports": {
|
|
10
|
+
".": "./src/index.mjs",
|
|
11
|
+
"./package.json": "./package.json"
|
|
12
|
+
},
|
|
13
|
+
"files": [
|
|
14
|
+
"src",
|
|
15
|
+
"README.md",
|
|
16
|
+
"LICENSE"
|
|
17
|
+
],
|
|
18
|
+
"engines": {
|
|
19
|
+
"node": ">=24"
|
|
20
|
+
},
|
|
21
|
+
"scripts": {
|
|
22
|
+
"test": "node --test tests/*.test.mjs"
|
|
23
|
+
},
|
|
24
|
+
"dependencies": {
|
|
25
|
+
"@bitakit/core": "^0.2.0",
|
|
26
|
+
"@bitakit/discovery": "^0.2.0",
|
|
27
|
+
"commander": "15.0.0",
|
|
28
|
+
"typescript": "^5.9.3"
|
|
29
|
+
},
|
|
30
|
+
"license": "MIT",
|
|
31
|
+
"repository": {
|
|
32
|
+
"type": "git",
|
|
33
|
+
"url": "git+https://github.com/mvavesal/bitakit.git",
|
|
34
|
+
"directory": "packages/cli"
|
|
35
|
+
},
|
|
36
|
+
"publishConfig": {
|
|
37
|
+
"access": "public"
|
|
38
|
+
},
|
|
39
|
+
"keywords": [
|
|
40
|
+
"bitakit",
|
|
41
|
+
"ai-agents",
|
|
42
|
+
"composition",
|
|
43
|
+
"cli",
|
|
44
|
+
"scaffolding"
|
|
45
|
+
]
|
|
46
|
+
}
|
package/src/add.mjs
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
import { mkdir, writeFile } from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { contributionSegments } from '@bitakit/discovery';
|
|
4
|
+
import { exists, findProject } from './project.mjs';
|
|
5
|
+
import {
|
|
6
|
+
actionFile,
|
|
7
|
+
configFile,
|
|
8
|
+
eventsFile,
|
|
9
|
+
interceptorFile,
|
|
10
|
+
layoutFile,
|
|
11
|
+
pageFile,
|
|
12
|
+
settingsFile,
|
|
13
|
+
settingsPageFile,
|
|
14
|
+
slotFile,
|
|
15
|
+
slotDefinitionFile,
|
|
16
|
+
dialogFile,
|
|
17
|
+
providerFile,
|
|
18
|
+
pluginFiles,
|
|
19
|
+
serviceFile,
|
|
20
|
+
starterFiles,
|
|
21
|
+
titleOf,
|
|
22
|
+
validateName,
|
|
23
|
+
} from './templates.mjs';
|
|
24
|
+
|
|
25
|
+
/** Paths that apps already own; a plugin page there would never be reached. */
|
|
26
|
+
const reserved = new Set(['settings', 'api', 'login', 'register']);
|
|
27
|
+
|
|
28
|
+
/** Writes files that do not exist yet; never overwrites anything. */
|
|
29
|
+
export async function writeNewFiles(root, files) {
|
|
30
|
+
const targets = Object.keys(files).map((file) => path.join(root, file));
|
|
31
|
+
for (const target of targets)
|
|
32
|
+
if (await exists(target)) throw new Error(`${target} already exists. Nothing was changed.`);
|
|
33
|
+
for (const [file, content] of Object.entries(files)) {
|
|
34
|
+
const target = path.join(root, file);
|
|
35
|
+
await mkdir(path.dirname(target), { recursive: true });
|
|
36
|
+
await writeFile(target, content);
|
|
37
|
+
}
|
|
38
|
+
return targets;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Templates are written relative to the plugin directory, so the configuration must be readable. */
|
|
42
|
+
async function configuredProject(cwd) {
|
|
43
|
+
const project = await findProject(cwd);
|
|
44
|
+
if (project.configError) throw project.configError;
|
|
45
|
+
return project;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** `bitakit add plugin <name>`: a new folder under the app's plugin directory. */
|
|
49
|
+
export async function addPlugin(name, { cwd, minimal = false, example = false } = {}) {
|
|
50
|
+
validateName(name, 'plugin name');
|
|
51
|
+
const project = await configuredProject(cwd);
|
|
52
|
+
if (project.kind !== 'app')
|
|
53
|
+
throw new Error('This is a plugin package. Run "bitakit add plugin" inside an app.');
|
|
54
|
+
if (!minimal && reserved.has(name))
|
|
55
|
+
throw new Error(`"${name}" is reserved for app routes. Choose another plugin name.`);
|
|
56
|
+
const root = path.join(project.pluginsDirectory, name);
|
|
57
|
+
if (await exists(root)) throw new Error(`${root} already exists. Nothing was changed.`);
|
|
58
|
+
const manifest = project.manifest;
|
|
59
|
+
const navigationSlot = { ...manifest.devDependencies, ...manifest.dependencies }['@bitakit/shell']
|
|
60
|
+
? 'shell.navigation'
|
|
61
|
+
: undefined;
|
|
62
|
+
// Default: the smallest feature (a page and its menu entry); --example writes a complete one.
|
|
63
|
+
const files = minimal
|
|
64
|
+
? pluginFiles(name, { minimal: true, navigationSlot })
|
|
65
|
+
: example
|
|
66
|
+
? pluginFiles(name, { navigationSlot })
|
|
67
|
+
: starterFiles(name, { navigationSlot });
|
|
68
|
+
const created = await writeNewFiles(root, files);
|
|
69
|
+
return {
|
|
70
|
+
project,
|
|
71
|
+
root,
|
|
72
|
+
created,
|
|
73
|
+
title: titleOf(name),
|
|
74
|
+
path: minimal ? undefined : `/${name}`,
|
|
75
|
+
// Only a placed open Action shows in a navigation; without Shell the page is reached by URL.
|
|
76
|
+
navigation: !minimal && Boolean(navigationSlot),
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export const contributionKinds = [
|
|
81
|
+
'action',
|
|
82
|
+
'service',
|
|
83
|
+
'page',
|
|
84
|
+
'interceptor',
|
|
85
|
+
'config',
|
|
86
|
+
'events',
|
|
87
|
+
'settings',
|
|
88
|
+
'settings-page',
|
|
89
|
+
'layout',
|
|
90
|
+
'slot',
|
|
91
|
+
'slot-definition',
|
|
92
|
+
'dialog',
|
|
93
|
+
'provider',
|
|
94
|
+
];
|
|
95
|
+
/** Declared once per plugin, in one root file. */
|
|
96
|
+
const singleFile = {
|
|
97
|
+
events: 'events.ts',
|
|
98
|
+
settings: 'settings.ts',
|
|
99
|
+
'settings-page': 'ui/settings/page.tsx',
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* `bitakit add <kind> <plugin>/<name>` in an app, or `<name>` in a plugin package. Nested names
|
|
104
|
+
* such as `notes/team/invite` create `actions/team/invite.ts` with the ID `notes.team.invite`.
|
|
105
|
+
* `events` takes only the plugin: a plugin declares its events once in `events.ts`.
|
|
106
|
+
*/
|
|
107
|
+
export async function addContribution(kind, target, { cwd } = {}) {
|
|
108
|
+
if (!contributionKinds.includes(kind))
|
|
109
|
+
throw new Error(`Unknown kind "${kind}". Use ${contributionKinds.join(', ')}.`);
|
|
110
|
+
const project = await configuredProject(cwd);
|
|
111
|
+
if (kind === 'layout') {
|
|
112
|
+
if (project.kind !== 'app')
|
|
113
|
+
throw new Error('Layouts belong to the app: run "bitakit add layout <name>" inside an app.');
|
|
114
|
+
if (!target) throw new Error('Name the layout, for example "bitakit add layout admin".');
|
|
115
|
+
validateName(target, 'layout name');
|
|
116
|
+
const created = await writeNewFiles(project.appDirectory, {
|
|
117
|
+
[`layouts/${target}.tsx`]: layoutFile(target),
|
|
118
|
+
});
|
|
119
|
+
return { project, created, id: target, path: undefined };
|
|
120
|
+
}
|
|
121
|
+
const single = Object.hasOwn(singleFile, kind);
|
|
122
|
+
const example = single
|
|
123
|
+
? `bitakit add ${kind} notes`
|
|
124
|
+
: `bitakit add ${kind} notes/${target || 'archive'}`;
|
|
125
|
+
let plugin;
|
|
126
|
+
let createdPlugin = false;
|
|
127
|
+
let name = target ?? '';
|
|
128
|
+
let moduleRoot;
|
|
129
|
+
if (project.kind === 'plugin') {
|
|
130
|
+
plugin = project.pluginId;
|
|
131
|
+
moduleRoot = project.moduleRoot;
|
|
132
|
+
// The package is the plugin; naming it is allowed but not needed.
|
|
133
|
+
if (single && name === plugin) name = '';
|
|
134
|
+
} else {
|
|
135
|
+
const slash = name.indexOf('/');
|
|
136
|
+
[plugin, name] =
|
|
137
|
+
slash >= 0
|
|
138
|
+
? [name.slice(0, slash), name.slice(slash + 1)]
|
|
139
|
+
: single
|
|
140
|
+
? [name, '']
|
|
141
|
+
: [undefined, name];
|
|
142
|
+
if (!plugin) throw new Error(`Name the plugin too, for example "${example}".`);
|
|
143
|
+
validateName(plugin, 'plugin name');
|
|
144
|
+
moduleRoot = path.join(project.pluginsDirectory, plugin);
|
|
145
|
+
// A plugin is just its folder: the first contribution creates it.
|
|
146
|
+
createdPlugin = !(await exists(moduleRoot));
|
|
147
|
+
}
|
|
148
|
+
if (single) {
|
|
149
|
+
if (name)
|
|
150
|
+
throw new Error(
|
|
151
|
+
`${kind === 'events' ? 'Events' : 'Settings'} are declared once per plugin in ${singleFile[kind]}: run "bitakit add ${kind}${project.kind === 'plugin' ? '' : ` ${plugin}`}" without a further name.`,
|
|
152
|
+
);
|
|
153
|
+
} else {
|
|
154
|
+
if (!name) throw new Error(`Name the ${kind}, for example "${example}".`);
|
|
155
|
+
// Dots and folders mean the same, as in discovery: notes/app-bar.end equals notes/app-bar/end.
|
|
156
|
+
name = contributionSegments(name).join('/');
|
|
157
|
+
name.split('/').forEach((segment) => validateName(segment, `${kind} name`));
|
|
158
|
+
}
|
|
159
|
+
const segments = name ? name.split('/') : [];
|
|
160
|
+
const dotted = segments.join('.');
|
|
161
|
+
// ui/pages/team/index.tsx serves /<plugin>/team, exactly as discovery derives it.
|
|
162
|
+
const pageSegments = segments.at(-1) === 'index' ? segments.slice(0, -1) : segments;
|
|
163
|
+
const pagePath = `/${plugin}${pageSegments.map((segment) => `/${segment}`).join('')}`;
|
|
164
|
+
const files = {
|
|
165
|
+
action: () => ({ [`actions/${name}.ts`]: actionFile(name) }),
|
|
166
|
+
service: () => ({ [`services/${name}.ts`]: serviceFile(name, plugin) }),
|
|
167
|
+
page: () => ({
|
|
168
|
+
[`ui/pages/${name}.tsx`]: pageFile(plugin, pagePath, titleOf(pageSegments.at(-1) ?? plugin)),
|
|
169
|
+
}),
|
|
170
|
+
interceptor: () => ({ [`interceptors/${name}.ts`]: interceptorFile(plugin, name) }),
|
|
171
|
+
config: () => ({ [`configs/${name}.ts`]: configFile(dotted) }),
|
|
172
|
+
events: () => ({ 'events.ts': eventsFile(plugin) }),
|
|
173
|
+
settings: () => ({ 'settings.ts': settingsFile(plugin) }),
|
|
174
|
+
'settings-page': () => ({ 'ui/settings/page.tsx': settingsPageFile() }),
|
|
175
|
+
slot: () => ({ [`ui/slots/${name}.tsx`]: slotFile(plugin, dotted) }),
|
|
176
|
+
'slot-definition': () => ({ [`slots/${name}.ts`]: slotDefinitionFile(`${plugin}.${dotted}`) }),
|
|
177
|
+
dialog: () => ({ [`ui/dialogs/${name}.tsx`]: dialogFile(plugin, dotted) }),
|
|
178
|
+
provider: () => ({ [`ui/providers/${name}.tsx`]: providerFile(plugin, dotted) }),
|
|
179
|
+
}[kind];
|
|
180
|
+
const created = await writeNewFiles(moduleRoot, files());
|
|
181
|
+
return {
|
|
182
|
+
project,
|
|
183
|
+
created,
|
|
184
|
+
createdPlugin,
|
|
185
|
+
// A ui/slots file fills the slot named by its path, which is not prefixed with this plugin.
|
|
186
|
+
id: single ? `${plugin}.*` : kind === 'slot' ? dotted : `${plugin}.${dotted}`,
|
|
187
|
+
plugin,
|
|
188
|
+
path: kind === 'page' ? pagePath : undefined,
|
|
189
|
+
};
|
|
190
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The one identity sentence. The root README, the docs introduction, generated READMEs and agent
|
|
3
|
+
* rules repeat it verbatim; a test keeps those surfaces from drifting apart.
|
|
4
|
+
*/
|
|
5
|
+
export const bitakitIdentity = 'BitaKit is a composition layer for building apps with AI agents.';
|
|
6
|
+
|
|
7
|
+
/** Markers around the BitaKit block, so a later run can find and leave it alone. */
|
|
8
|
+
export const agentRulesBegin = '<!-- BEGIN:bitakit-agent-rules -->';
|
|
9
|
+
export const agentRulesEnd = '<!-- END:bitakit-agent-rules -->';
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* The guidance block for coding assistants in an app's AGENTS.md, shared by create-app and
|
|
13
|
+
* `bitakit init`. Ordered by learning level: where each task goes first, then the rules, then
|
|
14
|
+
* the advanced kinds by name only. `routes` is the framework's own route folder; `shell` adds
|
|
15
|
+
* the Shell placement line. Tests hold it to one screen.
|
|
16
|
+
*/
|
|
17
|
+
export function agentRules({ routes, shell = false }) {
|
|
18
|
+
return `${agentRulesBegin}
|
|
19
|
+
|
|
20
|
+
# BitaKit
|
|
21
|
+
|
|
22
|
+
${bitakitIdentity} One feature = one folder in \`src/plugins/<name>/\`;
|
|
23
|
+
the file path is the ID. Discovery generates \`src/bitakit.gen.*\`; there is no registry to edit.
|
|
24
|
+
|
|
25
|
+
| Task | Where it goes |
|
|
26
|
+
| --- | --- |
|
|
27
|
+
| A page | \`ui/pages/<path>.tsx\`, served at \`/<name>/<path>\` |
|
|
28
|
+
| A button, link or menu entry | \`actions/<file>.ts\`: \`defineAction({ title, execute })\`, ID \`<name>.<file>\` |
|
|
29
|
+
| Shared state or logic | \`services/<file>.ts\`: \`defineService(({ store }) => ({ ... }))\`, \`services.<name>.<file>\` |
|
|
30
|
+
| A user setting | \`settings.ts\`: \`defineSettings({ size: setting({ default: 20 }) })\`, \`settings.<name>.size\` |
|
|
31
|
+
| Tell other features something happened | \`events.ts\`: \`defineEvents({ changed: event<T>() })\`, \`<name>.changed\` |
|
|
32
|
+
| Let other features add UI here | \`slots/<file>.ts\`: \`defineSlot(...)\`; others fill it from \`ui/slots/<slot>.tsx\` |
|
|
33
|
+
| Change a feature you do not own | Listen to its events, fill its slots or read its settings from your own plugin |
|
|
34
|
+
|
|
35
|
+
- Start with a page, then a service and an Action; add files only when needed. A small plugin
|
|
36
|
+
may keep one record file per kind (\`actions.ts\` exporting \`{ add, remove }\`, same IDs).
|
|
37
|
+
- Bind every control that runs an operation to its Action: \`<Action id="<name>.<file>" input={...}><Button /></Action>\`,
|
|
38
|
+
\`ActionButton\` or \`ActionLink\`. Label, disabled, pending and confirmation come from the Action, not from
|
|
39
|
+
hand-written \`disabled\`/\`onClick\` state.
|
|
40
|
+
- In React: \`useServiceState('<name>.<file>', (state) => ...)\`, \`useSetting('<name>.<key>')\`, \`useEvent('<name>.changed', fn)\`.
|
|
41
|
+
React only under \`ui/\`. Use \`@bitakit/ui/components\` and the app theme; do not restyle locally or
|
|
42
|
+
import package CSS from JavaScript (discovery writes \`src/bitakit.gen.css\`).
|
|
43
|
+
- Do not rebuild what BitaKit provides: no own registries, event buses, settings stores or button state.
|
|
44
|
+
${shell ? "- Shell: place an Action with `slots: ['shell.navigation']` or `['shell.toolbar']`; header content goes in `ui/slots/shell.header.end.tsx`.\n" : ''}- App-owned routes stay native framework routes in \`${routes}\`; layouts live in \`src/layouts/<name>.tsx\`.
|
|
45
|
+
- Create files with \`npx bitakit add plugin <name>\` and \`npx bitakit add <kind> <name>/<file>\`; list IDs with
|
|
46
|
+
\`npx bitakit info --json\`; check with \`npx bitakit doctor\` and \`npm run typecheck\`.
|
|
47
|
+
- Advanced, only when needed: interceptors, configs, providers, dialogs, \`setup.ts\`, \`plugin.config.ts\`.
|
|
48
|
+
- Never edit generated files: \`src/bitakit.gen.*\`.
|
|
49
|
+
|
|
50
|
+
${agentRulesEnd}
|
|
51
|
+
`;
|
|
52
|
+
}
|
package/src/build.mjs
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
import { execFileSync } from 'node:child_process';
|
|
2
|
+
import { cp, mkdir, realpath, rm, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { createRequire } from 'node:module';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { describeModule, describeDefinitions, validatePackageStyles } from '@bitakit/discovery';
|
|
6
|
+
import { findProject } from './project.mjs';
|
|
7
|
+
|
|
8
|
+
const quote = JSON.stringify;
|
|
9
|
+
const header = '// Generated by BitaKit. Do not edit.\n';
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Builds a plugin package from the same folders apps use. It generates the plugin's own types
|
|
13
|
+
* (`.bitakit/plugin.d.ts`), compiles `src` with the package's TypeScript config and writes
|
|
14
|
+
* `dist/plugin.js`, the entry apps discover. `check` stops after a type check.
|
|
15
|
+
*/
|
|
16
|
+
export async function buildPlugin({ cwd, check = false } = {}) {
|
|
17
|
+
const project = await findProject(cwd);
|
|
18
|
+
if (project.kind !== 'plugin')
|
|
19
|
+
throw new Error(
|
|
20
|
+
'Run "bitakit build" inside a plugin package (a package.json with a bitakit.plugin entry).',
|
|
21
|
+
);
|
|
22
|
+
const { root, pluginId: id, moduleRoot, manifest, metadata } = project;
|
|
23
|
+
const module = await describeModule(moduleRoot);
|
|
24
|
+
for (const warning of module.warnings) console.warn(`[bitakit] ${warning}`);
|
|
25
|
+
// Discovery resolves symlinks (macOS /var → /private/var); relate the files to the real root,
|
|
26
|
+
// or the generated imports would leave the package and the type augmentation would not apply.
|
|
27
|
+
const realRoot = await realpath(root);
|
|
28
|
+
await mkdir(path.join(root, '.bitakit'), { recursive: true });
|
|
29
|
+
await writeFile(
|
|
30
|
+
path.join(root, '.bitakit/plugin.d.ts'),
|
|
31
|
+
declarations(
|
|
32
|
+
id,
|
|
33
|
+
module,
|
|
34
|
+
(file) =>
|
|
35
|
+
`../${path
|
|
36
|
+
.relative(realRoot, file)
|
|
37
|
+
.split(path.sep)
|
|
38
|
+
.join('/')
|
|
39
|
+
.replace(/\.tsx?$/, '')}`,
|
|
40
|
+
),
|
|
41
|
+
);
|
|
42
|
+
const tsc = createRequire(path.join(root, 'package.json')).resolve('typescript/bin/tsc');
|
|
43
|
+
const compile = (args) => {
|
|
44
|
+
try {
|
|
45
|
+
execFileSync(process.execPath, [tsc, '-p', 'tsconfig.json', ...args], {
|
|
46
|
+
cwd: root,
|
|
47
|
+
stdio: 'pipe',
|
|
48
|
+
});
|
|
49
|
+
} catch (error) {
|
|
50
|
+
throw new Error(
|
|
51
|
+
`TypeScript found problems:\n${String(error.stdout || error.message).trim()}`,
|
|
52
|
+
);
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
if (check) {
|
|
56
|
+
compile(['--noEmit']);
|
|
57
|
+
return { id, module, checked: true };
|
|
58
|
+
}
|
|
59
|
+
const dist = path.join(root, 'dist');
|
|
60
|
+
await rm(dist, { recursive: true, force: true });
|
|
61
|
+
compile([]);
|
|
62
|
+
const local = (file) =>
|
|
63
|
+
`./${path
|
|
64
|
+
.relative(module.directory, file)
|
|
65
|
+
.split(path.sep)
|
|
66
|
+
.join('/')
|
|
67
|
+
.replace(/\.tsx?$/, '.js')}`;
|
|
68
|
+
await writeFile(path.join(dist, 'plugin.js'), entry(id, module, manifest, metadata, local));
|
|
69
|
+
// Derived tooling hints travel with the entry; the source declarations remain the authority.
|
|
70
|
+
const slotInfo = await describeDefinitions(module.slotDefinitions, {
|
|
71
|
+
helper: 'defineSlot', moduleId: id, properties: ['accepts', 'policy'],
|
|
72
|
+
});
|
|
73
|
+
const source = (file) => path.relative(module.directory, file).split(path.sep).join('/');
|
|
74
|
+
await writeFile(path.join(dist, 'plugin.slots.json'), JSON.stringify({
|
|
75
|
+
version: 1,
|
|
76
|
+
definitions: slotInfo.definitions.map((item) => ({ ...item, file: source(item.file), plugin: id, policy: item.policy ?? 'list' })),
|
|
77
|
+
unresolved: slotInfo.unresolved.map(source),
|
|
78
|
+
}, null, 2) + '\n');
|
|
79
|
+
await writeFile(
|
|
80
|
+
path.join(dist, 'plugin.d.ts'),
|
|
81
|
+
`${declarations(id, module, (file) => local(file))}import type { Plugin } from '@bitakit/core';
|
|
82
|
+
/** Creates the "${id}" plugin. Apps discover it through package.json bitakit.plugin. */
|
|
83
|
+
declare const plugin: () => Plugin & { readonly id: ${quote(id)} };
|
|
84
|
+
export default plugin;
|
|
85
|
+
`,
|
|
86
|
+
);
|
|
87
|
+
if (module.locales.length) {
|
|
88
|
+
await mkdir(path.join(dist, 'locales'), { recursive: true });
|
|
89
|
+
for (const file of module.locales)
|
|
90
|
+
await cp(file, path.join(dist, 'locales', path.basename(file)));
|
|
91
|
+
}
|
|
92
|
+
const styles = (value) => (value === undefined ? [] : Array.isArray(value) ? value : [value])
|
|
93
|
+
.map((entry) => `${manifest.name}/${entry.replace(/^\.\//, '')}`);
|
|
94
|
+
await validatePackageStyles([{
|
|
95
|
+
name: manifest.name,
|
|
96
|
+
manifestFile: path.join(root, 'package.json'),
|
|
97
|
+
manifest,
|
|
98
|
+
styles: styles(metadata.styles),
|
|
99
|
+
theme: styles(metadata.theme),
|
|
100
|
+
}]);
|
|
101
|
+
return { id, module, dist };
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Typed services, actions, events and config for TypeScript, through @bitakit/core augmentation. */
|
|
105
|
+
function declarations(id, module, specifier) {
|
|
106
|
+
const lines = [];
|
|
107
|
+
const files = (entries, kind) =>
|
|
108
|
+
entries.map((entry, index) => {
|
|
109
|
+
const name = `${kind}${index}`;
|
|
110
|
+
lines.push(`import type ${name}Entry from ${quote(specifier(entry.file))};`);
|
|
111
|
+
lines.push(`type ${name} = DiscoveredFile<typeof ${name}Entry, ${quote(entry.path)}>;`);
|
|
112
|
+
return name;
|
|
113
|
+
});
|
|
114
|
+
const services = files(module.services, 'Service');
|
|
115
|
+
const settings = files(module.settings, 'Settings');
|
|
116
|
+
const slots = files(module.slotDefinitions, 'Slot');
|
|
117
|
+
const actions = files(module.actions, 'Action');
|
|
118
|
+
const configs = files(module.configs, 'Config');
|
|
119
|
+
const events = files(module.events, 'Events');
|
|
120
|
+
const intersect = (items, map) => items.map(map).join(' & ') || '{}';
|
|
121
|
+
return `${header}import type { DiscoveredFile, DiscoveredSlotEntry, DiscoveredServiceEntry, DiscoveredActionEntry, DiscoveredConfigEntry, DiscoveredEventsEntry, DiscoveredCancelableEntry, DiscoveredSettingsEntry } from '@bitakit/core';
|
|
122
|
+
${lines.join('\n')}
|
|
123
|
+
type PluginSettings = ${intersect(settings, (name) => `DiscoveredSettingsEntry<${name}, ${quote(id)}>`)};
|
|
124
|
+
type PluginSlots = ${intersect(slots, (name) => `DiscoveredSlotEntry<${name}, ${quote(id)}>`)};
|
|
125
|
+
type PluginServices = ${intersect(services, (name) => `DiscoveredServiceEntry<${name}, ${quote(id)}>`)};
|
|
126
|
+
type PluginActions = ${intersect(actions, (name) => `DiscoveredActionEntry<${name}, ${quote(id)}>`)};
|
|
127
|
+
type PluginEvents = ${intersect(events, (name) => `DiscoveredEventsEntry<${name}, ${quote(id)}>`)};
|
|
128
|
+
type PluginCancelable = ${intersect(events, (name) => `DiscoveredCancelableEntry<${name}, ${quote(id)}>`)};
|
|
129
|
+
declare module '@bitakit/core' {
|
|
130
|
+
interface ServiceMap extends PluginServices {}
|
|
131
|
+
interface ActionMap extends PluginActions {}
|
|
132
|
+
interface EventMap extends PluginEvents {}
|
|
133
|
+
interface CancelableEventMap extends PluginCancelable {}
|
|
134
|
+
interface SlotMap extends PluginSlots {}
|
|
135
|
+
interface SettingsMap extends PluginSettings {}
|
|
136
|
+
interface ConfigMap { ${quote(id)}: ${intersect(configs, (name) => `DiscoveredConfigEntry<${name}>`)} }
|
|
137
|
+
}
|
|
138
|
+
`;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** The published plugin factory: the same normalizers apps use, with static imports only. */
|
|
142
|
+
function entry(id, module, manifest, metadata, local) {
|
|
143
|
+
const imports = [];
|
|
144
|
+
let serial = 0;
|
|
145
|
+
const load = (file, namespace = false) => {
|
|
146
|
+
const name = `${namespace ? 'module' : 'entry'}${serial++}`;
|
|
147
|
+
imports.push(
|
|
148
|
+
namespace
|
|
149
|
+
? `import * as ${name} from ${quote(local(file))};`
|
|
150
|
+
: `import ${name} from ${quote(local(file))};`,
|
|
151
|
+
);
|
|
152
|
+
return name;
|
|
153
|
+
};
|
|
154
|
+
const discovered = (entries) =>
|
|
155
|
+
entries.map((item) => {
|
|
156
|
+
const name = load(item.file);
|
|
157
|
+
return `discoveredFile(${name}, ${quote(item.path)}, ${quote(path.relative(module.directory, item.file).split(path.sep).join('/'))})`;
|
|
158
|
+
});
|
|
159
|
+
const info = {};
|
|
160
|
+
for (const key of ['name', 'version', 'description', 'author', 'homepage', 'bugs', 'license', 'coverImage', 'tags'])
|
|
161
|
+
if (manifest[key] !== undefined) info[key] = manifest[key];
|
|
162
|
+
const services = discovered(module.services);
|
|
163
|
+
const settings = discovered(module.settings);
|
|
164
|
+
const settingsPage = module.settingsPage ? `pluginSettingsPage(${load(module.settingsPage, true)})` : undefined;
|
|
165
|
+
const slotDefinitions = discovered(module.slotDefinitions);
|
|
166
|
+
const actions = discovered(module.actions);
|
|
167
|
+
const configs = discovered(module.configs);
|
|
168
|
+
const interceptors = discovered(module.interceptors);
|
|
169
|
+
const events = discovered(module.events);
|
|
170
|
+
const pages = module.pages.map(
|
|
171
|
+
(item) =>
|
|
172
|
+
`pluginPage(${load(item.file, true)}, ${quote(`/${id}${item.path ? `/${item.path.split('.').join('/')}` : ''}`)})`,
|
|
173
|
+
);
|
|
174
|
+
const slots = module.slots.map(
|
|
175
|
+
(item) => `pluginSlot(${load(item.file, true)}, ${quote(item.path)}, ${quote(path.relative(module.directory, item.file).split(path.sep).join('/'))})`,
|
|
176
|
+
);
|
|
177
|
+
const providers = module.providers.map(
|
|
178
|
+
(item) => `pluginProvider(${load(item.file, true)}, ${quote(`${id}.${item.path}`)})`,
|
|
179
|
+
);
|
|
180
|
+
const setup = module.setup ? load(module.setup) : 'undefined';
|
|
181
|
+
return `'use client';
|
|
182
|
+
${header}import { definePlugin, discoveredFile, discoverActions, discoverServices, discoverSlots, discoverConfig, discoverInterceptors, discoverEvents, discoverSettings, pluginSettingsPage, pluginPage, pluginSlot, pluginProvider } from '@bitakit/core';
|
|
183
|
+
${imports.join('\n')}
|
|
184
|
+
|
|
185
|
+
/** Creates the ${quote(id)} plugin; apps call this once per runtime. */
|
|
186
|
+
export default function plugin() {
|
|
187
|
+
return definePlugin({
|
|
188
|
+
id: ${quote(id)},
|
|
189
|
+
metadata: ${quote(info)},
|
|
190
|
+
dependencies: ${quote(metadata?.dependencies ?? [])},
|
|
191
|
+
events: discoverEvents([${events.join(', ')}]),
|
|
192
|
+
settings: discoverSettings([${settings.join(', ')}]),
|
|
193
|
+
slots: discoverSlots([${slotDefinitions.join(', ')}], ${quote(id)}),
|
|
194
|
+
services: discoverServices([${services.join(', ')}], ${quote(id)}),
|
|
195
|
+
actions: discoverActions([${actions.join(', ')}], ${quote(id)}),
|
|
196
|
+
config: discoverConfig([${configs.join(', ')}]),
|
|
197
|
+
interceptors: discoverInterceptors([${interceptors.join(', ')}]),
|
|
198
|
+
ui: { pages: [${pages.join(', ')}], slots: [${slots.join(', ')}], providers: [${providers.join(', ')}]${settingsPage ? `, settings: ${settingsPage}` : ''} },
|
|
199
|
+
setup: ${setup},
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
`;
|
|
203
|
+
}
|