@niwa-labs/cockpit-sdk 0.0.0-stage → 0.0.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 +54 -2
- package/package.json +26 -4
- package/src/boundary.tsx +85 -0
- package/src/catalogue.ts +40 -0
- package/src/commands.tsx +87 -0
- package/src/contract.ts +252 -0
- package/src/hooks.ts +103 -0
- package/src/host-client.ts +246 -0
- package/src/index.ts +108 -0
- package/src/loader.ts +94 -0
- package/src/paths.ts +104 -0
- package/src/record-stream.ts +242 -0
- package/src/records.ts +72 -0
- package/src/registry.ts +428 -0
- package/src/runtime.tsx +51 -0
- package/src/schema-form.tsx +417 -0
- package/src/slots.tsx +147 -0
- package/src/sse.ts +80 -0
- package/test/boundary.test.tsx +200 -0
- package/test/browser.test.ts +37 -0
- package/test/fixtures.ts +68 -0
- package/test/host-client.test.ts +185 -0
- package/test/loader.test.ts +101 -0
- package/test/paths.test.ts +48 -0
- package/test/record-stream.test.ts +190 -0
- package/test/registry.test.ts +344 -0
- package/test/schema-form.test.tsx +161 -0
- package/test/sse.test.ts +36 -0
- package/tsconfig.json +16 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Niwa Labs contributors
|
|
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,55 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @niwa-labs/cockpit-sdk
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The SDK for cockpit client modules. A plugin's module exports a plugin made with
|
|
4
|
+
`definePlugin`; the cockpit imports every module the host's catalogue lists, runs their
|
|
5
|
+
`setup` before it builds its routes, and renders what they registered.
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
import { definePlugin, entityTabSlot } from "@niwa-labs/cockpit-sdk";
|
|
9
|
+
|
|
10
|
+
export default definePlugin({
|
|
11
|
+
id: "rin",
|
|
12
|
+
setup(ctx) {
|
|
13
|
+
ctx.pages.add({ path: "/rin", title: "Rin", nav: { order: 10 }, component: RinPage });
|
|
14
|
+
ctx.slots.register(entityTabSlot("session"), { key: "rin-digest", title: "What Rin learned", component: DigestTab });
|
|
15
|
+
ctx.slots.register("home.tile", { key: "rin-attention", component: AttentionTile });
|
|
16
|
+
ctx.entities.register("commitment", { label: "Commitment", prefix: "com", href: (id) => `/rin/commitments/${id}` });
|
|
17
|
+
},
|
|
18
|
+
});
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
- **Contract**: `definePlugin`, `PluginContext` (viewer, host client, record stream, pages,
|
|
22
|
+
slots, entities), `SlotMap` (typed slots, extended by module augmentation), `PluginFault`.
|
|
23
|
+
- **Registry**: modules register into drafts; `loadPlugins` assembles them in load order and
|
|
24
|
+
leaves out a module whole when it cannot be imported, its setup throws, or what it registers
|
|
25
|
+
conflicts or targets an undeclared slot.
|
|
26
|
+
- **Catalogue**: `CockpitModuleSchema` and `parseCatalogue` for the list of modules the host
|
|
27
|
+
serves; `catalogueSources` imports them by their content-addressed entries. A module that
|
|
28
|
+
takes too long to import or set up is left out like one that fails.
|
|
29
|
+
- **Host**: `httpHostClient` calls actions and reads or follows records through the web server.
|
|
30
|
+
Action references are typed through their schemas; a result is what the host sent, as JSON
|
|
31
|
+
(`Wire<O>`), not decoded again. History and its live continuation take one `RecordQuery`.
|
|
32
|
+
- **Live records**: `createRecordStream` keeps one feed in a store; pages read projections
|
|
33
|
+
(`defineProjection`, `recordList`) with `useProjection`. A projection's fold is cached by the
|
|
34
|
+
projection object, so define projections at module scope. Modules see the stream read-only.
|
|
35
|
+
- **React**: `CockpitProvider`, `Slot`, `SlotItem`, `PageView`, `EntityLink`, `PageLink`,
|
|
36
|
+
`PluginBoundary`, `useCall` and `useAction` over TanStack Query.
|
|
37
|
+
|
|
38
|
+
All modules are trusted and share one document. React, React DOM and TanStack Query are peer
|
|
39
|
+
dependencies: the cockpit provides one copy of them, of this SDK and of the ui-kit, and every
|
|
40
|
+
module uses it.
|
|
41
|
+
|
|
42
|
+
## Pages and actions
|
|
43
|
+
|
|
44
|
+
A page can offer a named action with `commands: [{ action: "task.create",
|
|
45
|
+
label: "Create task" }]`. Commands can also be a function of the route
|
|
46
|
+
parameters, for example to prefill the id of the session being viewed. The
|
|
47
|
+
SDK checks the viewer's grants, reads the current action schema when the
|
|
48
|
+
form opens, and submits to the host. A module can still provide its own
|
|
49
|
+
form when a workflow needs a specialized interaction.
|
|
50
|
+
|
|
51
|
+
Set `panel: true` on a detail page to open it over the referring list and
|
|
52
|
+
return with Escape or Back. Its URL can also be opened directly. On the
|
|
53
|
+
desk, use `home.summary` for counts, `home.main` for work and `home.tile`
|
|
54
|
+
for the sidebar. Home contributions receive the selected project and may
|
|
55
|
+
report the project directories in their data.
|
package/package.json
CHANGED
|
@@ -1,6 +1,28 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@niwa-labs/cockpit-sdk",
|
|
3
|
-
"version": "0.0.0
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.0.0",
|
|
4
|
+
"license": "MIT",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"exports": {
|
|
7
|
+
".": "./src/index.ts"
|
|
8
|
+
},
|
|
9
|
+
"dependencies": {
|
|
10
|
+
"@niwa-labs/client": "0.0.0",
|
|
11
|
+
"@niwa-labs/ui-kit": "0.0.0",
|
|
12
|
+
"zod": "^4.6.7",
|
|
13
|
+
"zustand": "^5.1.0"
|
|
14
|
+
},
|
|
15
|
+
"peerDependencies": {
|
|
16
|
+
"@tanstack/react-query": "^5.108.2",
|
|
17
|
+
"react": "^19.3.1",
|
|
18
|
+
"react-dom": "^19.3.1"
|
|
19
|
+
},
|
|
20
|
+
"devDependencies": {
|
|
21
|
+
"@happy-dom/global-registrator": "^21.0.4",
|
|
22
|
+
"@tanstack/react-query": "^5.108.2",
|
|
23
|
+
"@types/react": "^19.3.0",
|
|
24
|
+
"@types/react-dom": "^19.3.0",
|
|
25
|
+
"react": "^19.3.1",
|
|
26
|
+
"react-dom": "^19.3.1"
|
|
27
|
+
}
|
|
28
|
+
}
|
package/src/boundary.tsx
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The boundary around everything a module renders. A component that throws is replaced by a
|
|
3
|
+
* small notice in its own place and reported as a fault; the frame and the other modules keep
|
|
4
|
+
* working. The notice offers to render the part again.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { cn } from "@niwa-labs/ui-kit";
|
|
8
|
+
import { Component, type ContextType, type ReactNode } from "react";
|
|
9
|
+
|
|
10
|
+
import { faultMessage, type PluginFault } from "./contract.ts";
|
|
11
|
+
import { CockpitContext } from "./runtime.tsx";
|
|
12
|
+
|
|
13
|
+
export type PluginBoundaryProps = {
|
|
14
|
+
plugin: string;
|
|
15
|
+
/** The slot, page or entity kind being rendered. */
|
|
16
|
+
place: string;
|
|
17
|
+
/** Rendering again with another key clears a failure, e.g. the address of the page shown. */
|
|
18
|
+
resetKey?: string | undefined;
|
|
19
|
+
/** What to show in place of the failed part; a compact notice by default. */
|
|
20
|
+
fallback?: ((fault: PluginFault, retry: () => void) => ReactNode) | undefined;
|
|
21
|
+
children?: ReactNode;
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
type Shown = { plugin: string; place: string; resetKey: string | undefined };
|
|
25
|
+
|
|
26
|
+
type BoundaryState = ({ failed: false } | { failed: true; error: unknown }) & { shown: Shown };
|
|
27
|
+
|
|
28
|
+
export function FaultNotice({ fault, retry, className }: { fault: PluginFault; retry?: (() => void) | undefined; className?: string }) {
|
|
29
|
+
return (
|
|
30
|
+
<div
|
|
31
|
+
role="alert"
|
|
32
|
+
data-slot="plugin-fault"
|
|
33
|
+
data-plugin={fault.plugin}
|
|
34
|
+
className={cn("flex min-w-0 items-center gap-2 rounded-md border border-dashed px-2 py-1 text-xs text-muted-foreground", className)}
|
|
35
|
+
>
|
|
36
|
+
<span className="min-w-0 truncate">
|
|
37
|
+
<span className="font-medium text-foreground">{fault.plugin}</span> failed here: {fault.message}
|
|
38
|
+
</span>
|
|
39
|
+
{retry === undefined ? null : (
|
|
40
|
+
<button type="button" className="ml-auto shrink-0 font-medium underline-offset-2 hover:underline" onClick={retry}>
|
|
41
|
+
Retry
|
|
42
|
+
</button>
|
|
43
|
+
)}
|
|
44
|
+
</div>
|
|
45
|
+
);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export class PluginBoundary extends Component<PluginBoundaryProps, BoundaryState> {
|
|
49
|
+
static override contextType = CockpitContext;
|
|
50
|
+
declare context: ContextType<typeof CockpitContext>;
|
|
51
|
+
override state: BoundaryState = {
|
|
52
|
+
failed: false,
|
|
53
|
+
shown: { plugin: this.props.plugin, place: this.props.place, resetKey: this.props.resetKey },
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
static getDerivedStateFromError(error: unknown): Partial<BoundaryState> {
|
|
57
|
+
return { failed: true, error };
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// A failure belongs to what was shown: another module, place or page starts clean, without
|
|
61
|
+
// showing the old failure once under the new place.
|
|
62
|
+
static getDerivedStateFromProps(props: PluginBoundaryProps, state: BoundaryState): Partial<BoundaryState> | null {
|
|
63
|
+
const { shown } = state;
|
|
64
|
+
if (shown.plugin === props.plugin && shown.place === props.place && shown.resetKey === props.resetKey) return null;
|
|
65
|
+
return { failed: false, shown: { plugin: props.plugin, place: props.place, resetKey: props.resetKey } };
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
private fault(error: unknown): PluginFault {
|
|
69
|
+
return { plugin: this.props.plugin, phase: "render", place: this.props.place, message: faultMessage(error), error };
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
override componentDidCatch(error: unknown): void {
|
|
73
|
+
const fault = this.fault(error);
|
|
74
|
+
if (this.context === null) console.error(`niwa cockpit: ${fault.plugin} failed in ${fault.place}`, error);
|
|
75
|
+
else this.context.reportFault(fault);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
private readonly retry = (): void => this.setState({ failed: false });
|
|
79
|
+
|
|
80
|
+
override render(): ReactNode {
|
|
81
|
+
if (!this.state.failed) return this.props.children;
|
|
82
|
+
const fault = this.fault(this.state.error);
|
|
83
|
+
return this.props.fallback === undefined ? <FaultNotice fault={fault} retry={this.retry} /> : this.props.fallback(fault, this.retry);
|
|
84
|
+
}
|
|
85
|
+
}
|
package/src/catalogue.ts
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The catalogue of cockpit modules, as the host serves it.
|
|
3
|
+
*
|
|
4
|
+
* A plugin on the host offers a client module; the host lists the modules it offers with a
|
|
5
|
+
* content hash, and the web server serves each module's code by id and hash. The cockpit
|
|
6
|
+
* imports the listed entries before it builds its routes.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { z } from "zod";
|
|
10
|
+
|
|
11
|
+
import { PLUGIN_ID } from "./contract.ts";
|
|
12
|
+
|
|
13
|
+
export const CockpitModuleSchema = z.object({
|
|
14
|
+
/** The module's id; the plugin it exports has the same id. */
|
|
15
|
+
id: z.string().regex(PLUGIN_ID),
|
|
16
|
+
/** The package that offers the module. */
|
|
17
|
+
package: z.string().min(1),
|
|
18
|
+
version: z.string().min(1),
|
|
19
|
+
/**
|
|
20
|
+
* The address of the module's code: an ES module that imports React and the SDK as shared
|
|
21
|
+
* modules. The address contains the hash as a path segment, so the module's own relative
|
|
22
|
+
* imports carry it too and no cache serves old code.
|
|
23
|
+
*/
|
|
24
|
+
entry: z.string().min(1),
|
|
25
|
+
/** The hash of the module's code. */
|
|
26
|
+
hash: z.string().min(1),
|
|
27
|
+
/** Stylesheets the module needs, if any. */
|
|
28
|
+
styles: z.array(z.string().min(1)).optional(),
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
export type CockpitModule = z.output<typeof CockpitModuleSchema>;
|
|
32
|
+
|
|
33
|
+
export const CockpitCatalogueSchema = z.object({ modules: z.array(CockpitModuleSchema) });
|
|
34
|
+
|
|
35
|
+
export type CockpitCatalogue = z.output<typeof CockpitCatalogueSchema>;
|
|
36
|
+
|
|
37
|
+
/** Read a catalogue the host answered with; a malformed one is an error, not an empty list. */
|
|
38
|
+
export function parseCatalogue(value: unknown): CockpitCatalogue {
|
|
39
|
+
return CockpitCatalogueSchema.parse(value);
|
|
40
|
+
}
|
package/src/commands.tsx
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { DataValue } from "@niwa-labs/ui-kit";
|
|
2
|
+
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
|
3
|
+
import { useState } from "react";
|
|
4
|
+
import { useHost, useViewer } from "./runtime.tsx";
|
|
5
|
+
import { SchemaFields, readFields, type FormSchema } from "./schema-form.tsx";
|
|
6
|
+
|
|
7
|
+
/** A plugin chooses the commands that belong on its page. Presets are initial form values. */
|
|
8
|
+
export interface PageCommand {
|
|
9
|
+
action: string;
|
|
10
|
+
label: string;
|
|
11
|
+
preset?: Record<string, unknown> | undefined;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function CommandForm({ command }: { command: PageCommand }) {
|
|
15
|
+
const host = useHost();
|
|
16
|
+
const client = useQueryClient();
|
|
17
|
+
const [error, setError] = useState("");
|
|
18
|
+
const schema = useQuery({
|
|
19
|
+
queryKey: ["niwa", "schema", command.action],
|
|
20
|
+
staleTime: Infinity,
|
|
21
|
+
queryFn: async ({ signal }) => {
|
|
22
|
+
const info = await host.info({ action: command.action, signal });
|
|
23
|
+
const action = info.action as { input?: FormSchema; name?: string; destructive?: boolean } | undefined;
|
|
24
|
+
if (action?.name !== command.action || !action.input) throw new Error("Хост не предоставил схему действия.");
|
|
25
|
+
return { input: action.input, destructive: action.destructive };
|
|
26
|
+
},
|
|
27
|
+
});
|
|
28
|
+
const call = useMutation({
|
|
29
|
+
mutationFn: (input: unknown) => host.call(command.action, input),
|
|
30
|
+
onSuccess: () => void client.invalidateQueries({ queryKey: ["niwa", "call"] }),
|
|
31
|
+
});
|
|
32
|
+
if (!schema.data) return <p role="status">{schema.error?.message ?? "Загружаю поля…"}</p>;
|
|
33
|
+
const { input, destructive } = schema.data;
|
|
34
|
+
return (
|
|
35
|
+
<form
|
|
36
|
+
className="desk-form"
|
|
37
|
+
onSubmit={(event) => {
|
|
38
|
+
event.preventDefault();
|
|
39
|
+
if (call.isPending) return;
|
|
40
|
+
try {
|
|
41
|
+
const value = readFields(input, new FormData(event.currentTarget)) ?? {};
|
|
42
|
+
if (destructive && !window.confirm(command.label + "?")) return;
|
|
43
|
+
setError("");
|
|
44
|
+
call.mutate(value);
|
|
45
|
+
} catch (e) {
|
|
46
|
+
setError(e instanceof Error ? e.message : String(e));
|
|
47
|
+
}
|
|
48
|
+
}}
|
|
49
|
+
>
|
|
50
|
+
<SchemaFields schema={input} initial={command.preset} />
|
|
51
|
+
<button className="desk-primary" disabled={call.isPending}>
|
|
52
|
+
{command.label}
|
|
53
|
+
</button>
|
|
54
|
+
{(error || call.error) && <p role="alert">{error || call.error?.message}</p>}
|
|
55
|
+
{call.isSuccess && (
|
|
56
|
+
<details open>
|
|
57
|
+
<summary>Результат</summary>
|
|
58
|
+
<DataValue value={call.data}/>
|
|
59
|
+
</details>
|
|
60
|
+
)}
|
|
61
|
+
</form>
|
|
62
|
+
);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function PageCommands({ commands }: { commands: readonly PageCommand[] }) {
|
|
66
|
+
const viewer = useViewer();
|
|
67
|
+
const [selected, setSelected] = useState("");
|
|
68
|
+
const visible = commands.filter((command) => viewer.can(command.action));
|
|
69
|
+
const command = visible.find((item) => item.action === selected);
|
|
70
|
+
if (!visible.length) return null;
|
|
71
|
+
return (
|
|
72
|
+
<section aria-label="Действия" className="desk-commands">
|
|
73
|
+
<div className="desk-tools">
|
|
74
|
+
{visible.map((c) => (
|
|
75
|
+
<button
|
|
76
|
+
key={c.action}
|
|
77
|
+
aria-expanded={command?.action === c.action}
|
|
78
|
+
onClick={() => setSelected(command?.action === c.action ? "" : c.action)}
|
|
79
|
+
>
|
|
80
|
+
{c.label}
|
|
81
|
+
</button>
|
|
82
|
+
))}
|
|
83
|
+
</div>
|
|
84
|
+
{command && <CommandForm key={command.action} command={command} />}
|
|
85
|
+
</section>
|
|
86
|
+
);
|
|
87
|
+
}
|
package/src/contract.ts
ADDED
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The contract between the cockpit and the modules it loads.
|
|
3
|
+
*
|
|
4
|
+
* A module's default export is a plugin made with `definePlugin`. Before the cockpit builds its
|
|
5
|
+
* routes it runs every plugin's `setup`, which adds pages, declares and fills slots, and
|
|
6
|
+
* registers entity kinds. Every module is trusted: it runs in the cockpit's own document with
|
|
7
|
+
* the same React, the same SDK and the same rights as the cockpit itself.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import type { ComponentType } from "react";
|
|
11
|
+
|
|
12
|
+
import type { HostClient } from "./host-client.ts";
|
|
13
|
+
import type { PathParams, SearchParams } from "./paths.ts";
|
|
14
|
+
import type { StoredRecord } from "./records.ts";
|
|
15
|
+
import type { RecordFeed } from "./record-stream.ts";
|
|
16
|
+
|
|
17
|
+
// ---------------------------------------------------------------------------------------------
|
|
18
|
+
// Who is looking
|
|
19
|
+
|
|
20
|
+
/** The person or client the cockpit acts for, and what it may call. */
|
|
21
|
+
export type Viewer = {
|
|
22
|
+
/** The id the host knows this client by. */
|
|
23
|
+
readonly id: string;
|
|
24
|
+
/** The viewer speaks for the owner. */
|
|
25
|
+
readonly owner: boolean;
|
|
26
|
+
/** The actions the viewer may call through the web server. */
|
|
27
|
+
readonly actions: ReadonlySet<string>;
|
|
28
|
+
/** Whether the viewer may call an action, by name or by reference. */
|
|
29
|
+
can(action: string | { readonly name: string }): boolean;
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
export function createViewer(spec: { id: string; owner: boolean; actions: Iterable<string> }): Viewer {
|
|
33
|
+
const actions: ReadonlySet<string> = new Set(spec.actions);
|
|
34
|
+
return {
|
|
35
|
+
id: spec.id,
|
|
36
|
+
owner: spec.owner,
|
|
37
|
+
actions,
|
|
38
|
+
can: (action) => actions.has(typeof action === "string" ? action : action.name),
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// ---------------------------------------------------------------------------------------------
|
|
43
|
+
// Pages
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* What a page receives. The query is given as strings, as written in the address; the cockpit
|
|
47
|
+
* does not turn `?n=1` into a number, the page parses what it needs.
|
|
48
|
+
*/
|
|
49
|
+
export type PageProps<P extends string = string> = {
|
|
50
|
+
params: PathParams<P>;
|
|
51
|
+
search: SearchParams;
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
export type NavEntry = {
|
|
55
|
+
/** The label in the navigation; the page title by default. */
|
|
56
|
+
label?: string | undefined;
|
|
57
|
+
/** Lower comes first. */
|
|
58
|
+
order?: number | undefined;
|
|
59
|
+
icon?: ComponentType<{ className?: string }> | undefined;
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
export type PageSpec<P extends string = string> = {
|
|
63
|
+
/** The path pattern, with `$name` parameters: `/runs/$runId`. */
|
|
64
|
+
path: P;
|
|
65
|
+
title: string;
|
|
66
|
+
component: ComponentType<PageProps<P>>;
|
|
67
|
+
/** Open above the referring list. A direct URL still opens as its own page. */
|
|
68
|
+
panel?: boolean;
|
|
69
|
+
/** Render the registered page title together with its available commands. */
|
|
70
|
+
commandHeading?: boolean;
|
|
71
|
+
commands?: readonly import("./commands.tsx").PageCommand[] | ((props: PageProps<P>) => readonly import("./commands.tsx").PageCommand[]);
|
|
72
|
+
/** Show the page in the navigation. Pages with parameters are reached by links instead. */
|
|
73
|
+
nav?: NavEntry | undefined;
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
// ---------------------------------------------------------------------------------------------
|
|
77
|
+
// Slots
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* How a slot holds its contributions.
|
|
81
|
+
*
|
|
82
|
+
* - `single`: one contribution at most; a second is a conflict.
|
|
83
|
+
* - `list`: any number, shown in `order`, then in load order.
|
|
84
|
+
* - `keyed`: looked up by key, e.g. the view of a record type; a repeated key is a conflict.
|
|
85
|
+
*/
|
|
86
|
+
export type SlotKind = "single" | "list" | "keyed";
|
|
87
|
+
|
|
88
|
+
/** What a slot is: its kind and the props its owner passes to every contribution. */
|
|
89
|
+
export type SlotSpec<K extends SlotKind = SlotKind, P extends object = object> = { kind: K; props: P };
|
|
90
|
+
|
|
91
|
+
export interface HomeTileProps {
|
|
92
|
+
project?: string | undefined;
|
|
93
|
+
reportProjects?: (directories: readonly string[]) => void;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* The slots and their props, by name. The cockpit's own slots are listed here; a module that
|
|
98
|
+
* owns a place declares its slot at setup and adds it to this interface:
|
|
99
|
+
*
|
|
100
|
+
* ```ts
|
|
101
|
+
* declare module "@niwa-labs/cockpit-sdk" {
|
|
102
|
+
* interface SlotMap {
|
|
103
|
+
* "rin.panel": SlotSpec<"list", { agent: string }>;
|
|
104
|
+
* }
|
|
105
|
+
* }
|
|
106
|
+
* ```
|
|
107
|
+
*/
|
|
108
|
+
export interface SlotMap {
|
|
109
|
+
/** Tiles on the home page. */
|
|
110
|
+
"home.tile": SlotSpec<"list", HomeTileProps>;
|
|
111
|
+
"home.main": SlotSpec<"list", HomeTileProps>;
|
|
112
|
+
"home.summary": SlotSpec<"list", HomeTileProps>;
|
|
113
|
+
/** Small items in the status bar of the frame. */
|
|
114
|
+
"shell.status": SlotSpec<"list", Record<never, never>>;
|
|
115
|
+
/** How a record is shown in the journal, keyed by record type name. */
|
|
116
|
+
"record.view": SlotSpec<"keyed", { record: StoredRecord }>;
|
|
117
|
+
/** Tabs on the page of an entity, e.g. `entity.session.tab`; declared with the entity kind. */
|
|
118
|
+
[tab: `entity.${string}.tab`]: SlotSpec<"list", { id: string }>;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export type SlotName = keyof SlotMap & string;
|
|
122
|
+
|
|
123
|
+
export type SlotPropsOf<K extends SlotName> = SlotMap[K]["props"];
|
|
124
|
+
|
|
125
|
+
export type SlotContribution<P extends object = object> = {
|
|
126
|
+
/** Unique within the slot. For a `keyed` slot it is the key the slot is looked up by. */
|
|
127
|
+
key: string;
|
|
128
|
+
component: ComponentType<P>;
|
|
129
|
+
/** A title, for slots shown as tabs or sections. */
|
|
130
|
+
title?: string | undefined;
|
|
131
|
+
/** Lower comes first in a `list` slot. */
|
|
132
|
+
order?: number | undefined;
|
|
133
|
+
};
|
|
134
|
+
|
|
135
|
+
/** The slots the cockpit itself owns. */
|
|
136
|
+
export const CORE_SLOTS: ReadonlyArray<{ name: SlotName; kind: SlotKind }> = [
|
|
137
|
+
{ name: "home.tile", kind: "list" },
|
|
138
|
+
{ name: "home.main", kind: "list" },
|
|
139
|
+
{ name: "home.summary", kind: "list" },
|
|
140
|
+
{ name: "shell.status", kind: "list" },
|
|
141
|
+
{ name: "record.view", kind: "keyed" },
|
|
142
|
+
];
|
|
143
|
+
|
|
144
|
+
/** The slot of tabs on the pages of an entity kind. */
|
|
145
|
+
export function entityTabSlot(kind: string): `entity.${string}.tab` {
|
|
146
|
+
return `entity.${kind}.tab`;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
// ---------------------------------------------------------------------------------------------
|
|
150
|
+
// Entities
|
|
151
|
+
|
|
152
|
+
/** A reference to an entity: a run, a session, a task, a request, or anything a module adds. */
|
|
153
|
+
export type EntityRef = { kind: string; id: string };
|
|
154
|
+
|
|
155
|
+
export type EntitySpec = {
|
|
156
|
+
/** The name of the kind for people: "Run", "Session". */
|
|
157
|
+
label: string;
|
|
158
|
+
/**
|
|
159
|
+
* The prefix of the kind's ids: ids written `<prefix>-<rest>` resolve to this kind. A kind
|
|
160
|
+
* whose ids have no such prefix (a pull request `owner/repo#12`) is referred to explicitly
|
|
161
|
+
* with an `EntityRef`.
|
|
162
|
+
*/
|
|
163
|
+
prefix?: string | undefined;
|
|
164
|
+
/** The address of an entity's page. */
|
|
165
|
+
href: (id: string) => string;
|
|
166
|
+
/** A chip of its own in place of the plain id chip. */
|
|
167
|
+
chip?: ComponentType<EntityChipProps> | undefined;
|
|
168
|
+
/** A short preview, for hover cards and lists. */
|
|
169
|
+
card?: ComponentType<{ id: string }> | undefined;
|
|
170
|
+
};
|
|
171
|
+
|
|
172
|
+
/** What a kind's own chip receives: the link is resolved and navigation handled by the cockpit. */
|
|
173
|
+
export type EntityChipProps = {
|
|
174
|
+
id: string;
|
|
175
|
+
href: string;
|
|
176
|
+
/** Navigate inside the cockpit; call it from a plain click instead of following the link. */
|
|
177
|
+
navigate: () => void;
|
|
178
|
+
label?: string | undefined;
|
|
179
|
+
short?: boolean | undefined;
|
|
180
|
+
className?: string | undefined;
|
|
181
|
+
};
|
|
182
|
+
|
|
183
|
+
// ---------------------------------------------------------------------------------------------
|
|
184
|
+
// The plugin
|
|
185
|
+
|
|
186
|
+
export interface PluginContext {
|
|
187
|
+
readonly plugin: { readonly id: string };
|
|
188
|
+
readonly viewer: Viewer;
|
|
189
|
+
readonly host: HostClient;
|
|
190
|
+
readonly records: RecordFeed;
|
|
191
|
+
readonly pages: {
|
|
192
|
+
add<P extends string>(page: PageSpec<P>): void;
|
|
193
|
+
};
|
|
194
|
+
readonly slots: {
|
|
195
|
+
/** Own a place: other modules may contribute to it. */
|
|
196
|
+
declare<K extends SlotName>(name: K, kind: SlotMap[K]["kind"]): void;
|
|
197
|
+
/** Contribute to a declared slot. A slot nobody declares fails the module at load. */
|
|
198
|
+
register<K extends SlotName>(name: K, contribution: SlotContribution<SlotPropsOf<K>>): void;
|
|
199
|
+
};
|
|
200
|
+
readonly entities: {
|
|
201
|
+
register(kind: string, spec: EntitySpec): void;
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
export type CockpitPlugin = {
|
|
206
|
+
/** The module's id; the catalogue serves the module under the same id. */
|
|
207
|
+
readonly id: string;
|
|
208
|
+
/** Registers what the module adds. Runs once, before the cockpit builds its routes. */
|
|
209
|
+
readonly setup: (ctx: PluginContext) => void | Promise<void>;
|
|
210
|
+
};
|
|
211
|
+
|
|
212
|
+
const PLUGIN = Symbol.for("niwa.cockpit.plugin");
|
|
213
|
+
|
|
214
|
+
/** Lowercase words joined by dashes or dots: `rin`, `sessions`, `git.forge`. */
|
|
215
|
+
export const PLUGIN_ID = /^[a-z][a-z0-9]*(?:[-.][a-z0-9]+)*$/;
|
|
216
|
+
|
|
217
|
+
export function definePlugin(plugin: CockpitPlugin): CockpitPlugin {
|
|
218
|
+
if (!PLUGIN_ID.test(plugin.id)) throw new TypeError(`a plugin id must be lowercase words joined by - or .: "${plugin.id}"`);
|
|
219
|
+
if (typeof plugin.setup !== "function") throw new TypeError(`the plugin ${plugin.id} has no setup function`);
|
|
220
|
+
const defined = { id: plugin.id, setup: plugin.setup };
|
|
221
|
+
Object.defineProperty(defined, PLUGIN, { value: true });
|
|
222
|
+
return Object.freeze(defined);
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
export function isCockpitPlugin(value: unknown): value is CockpitPlugin {
|
|
226
|
+
return value !== null && typeof value === "object" && (value as Record<symbol, unknown>)[PLUGIN] === true;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
// ---------------------------------------------------------------------------------------------
|
|
230
|
+
// Faults
|
|
231
|
+
|
|
232
|
+
/**
|
|
233
|
+
* Why a module, or one of its parts, is missing from the cockpit.
|
|
234
|
+
*
|
|
235
|
+
* - `load`: the module could not be imported or did not export a plugin.
|
|
236
|
+
* - `setup`: its setup threw, or registered something invalid.
|
|
237
|
+
* - `register`: what it registered conflicts with a module loaded before it, or contributes to
|
|
238
|
+
* a slot nobody declared. The module is left out whole.
|
|
239
|
+
* - `render`: one of its components threw while rendering; the rest of the cockpit stays up.
|
|
240
|
+
*/
|
|
241
|
+
export type PluginFault = {
|
|
242
|
+
plugin: string;
|
|
243
|
+
phase: "load" | "setup" | "register" | "render";
|
|
244
|
+
/** The slot, page or entity kind the fault is about. */
|
|
245
|
+
place?: string | undefined;
|
|
246
|
+
message: string;
|
|
247
|
+
error?: unknown;
|
|
248
|
+
};
|
|
249
|
+
|
|
250
|
+
export function faultMessage(error: unknown): string {
|
|
251
|
+
return error instanceof Error ? error.message : String(error);
|
|
252
|
+
}
|