@alecsibilia/ui-kit 0.0.0-stage → 0.1.0-alpha.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/CHANGELOG.md +7 -0
- package/LICENSE +201 -0
- package/README.md +233 -2
- package/bin/ui-kit.js +12 -0
- package/dist/alchemy/app.d.ts +34 -0
- package/dist/alchemy/app.js +88 -0
- package/dist/alchemy/index.d.ts +11 -0
- package/dist/alchemy/index.js +11 -0
- package/dist/alchemy/live-rooms.d.ts +21 -0
- package/dist/alchemy/live-rooms.js +31 -0
- package/dist/alchemy/migrations.d.ts +28 -0
- package/dist/alchemy/migrations.js +56 -0
- package/dist/alchemy/stage.d.ts +20 -0
- package/dist/alchemy/stage.js +20 -0
- package/dist/alchemy/wrangler-config.d.ts +76 -0
- package/dist/alchemy/wrangler-config.js +82 -0
- package/dist/build/app-modules.d.ts +11 -0
- package/dist/build/app-modules.js +40 -0
- package/dist/build/check.d.ts +4 -0
- package/dist/build/check.js +170 -0
- package/dist/build/cli.d.ts +1 -0
- package/dist/build/cli.js +79 -0
- package/dist/build/feature.d.ts +8 -0
- package/dist/build/feature.js +24 -0
- package/dist/build/index.d.ts +13 -0
- package/dist/build/index.js +13 -0
- package/dist/build/measure-cpu.d.ts +2 -0
- package/dist/build/measure-cpu.js +196 -0
- package/dist/build/prerender.d.ts +5 -0
- package/dist/build/prerender.js +109 -0
- package/dist/build/preview.d.ts +7 -0
- package/dist/build/preview.js +41 -0
- package/dist/build/seo-files.d.ts +27 -0
- package/dist/build/seo-files.js +24 -0
- package/dist/client/head-swap.d.ts +45 -0
- package/dist/client/head-swap.js +183 -0
- package/dist/client/hydration-pass.d.ts +56 -0
- package/dist/client/hydration-pass.js +186 -0
- package/dist/client/hydration-reset.d.ts +82 -0
- package/dist/client/hydration-reset.js +154 -0
- package/dist/client/index.d.ts +37 -0
- package/dist/client/index.js +65 -0
- package/dist/client/nav-client.d.ts +35 -0
- package/dist/client/nav-client.js +371 -0
- package/dist/live/collab/doc-provider.d.ts +74 -0
- package/dist/live/collab/doc-provider.js +412 -0
- package/dist/live/collab/index.d.ts +51 -0
- package/dist/live/collab/index.jsx +142 -0
- package/dist/live/collab-status.d.ts +25 -0
- package/dist/live/collab-status.js +17 -0
- package/dist/live/cursors/cursor-engine.d.ts +57 -0
- package/dist/live/cursors/cursor-engine.js +243 -0
- package/dist/live/cursors/index.d.ts +46 -0
- package/dist/live/cursors/index.jsx +110 -0
- package/dist/live/declaration.d.ts +113 -0
- package/dist/live/declaration.js +94 -0
- package/dist/live/index.d.ts +8 -0
- package/dist/live/index.js +8 -0
- package/dist/live/protocol.d.ts +224 -0
- package/dist/live/protocol.js +272 -0
- package/dist/live/server/doc-store.d.ts +68 -0
- package/dist/live/server/doc-store.js +187 -0
- package/dist/live/server/index.d.ts +60 -0
- package/dist/live/server/index.js +77 -0
- package/dist/live/server/room-presence.d.ts +24 -0
- package/dist/live/server/room-presence.js +123 -0
- package/dist/live/server/room-sockets.d.ts +65 -0
- package/dist/live/server/room-sockets.js +97 -0
- package/dist/live/server/room.d.ts +20 -0
- package/dist/live/server/room.js +348 -0
- package/dist/live/server/route.d.ts +56 -0
- package/dist/live/server/route.js +159 -0
- package/dist/live/server/types.d.ts +163 -0
- package/dist/live/server/types.js +2 -0
- package/dist/logic/agent-actions.d.ts +133 -0
- package/dist/logic/agent-actions.js +150 -0
- package/dist/logic/command-types.d.ts +53 -0
- package/dist/logic/command-types.js +0 -0
- package/dist/logic/dev.d.ts +9 -0
- package/dist/logic/dev.js +10 -0
- package/dist/logic/draft-rebase.d.ts +59 -0
- package/dist/logic/draft-rebase.js +71 -0
- package/dist/logic/form-state.d.ts +105 -0
- package/dist/logic/form-state.js +93 -0
- package/dist/logic/head.d.ts +145 -0
- package/dist/logic/head.js +140 -0
- package/dist/logic/index.d.ts +27 -0
- package/dist/logic/index.js +25 -0
- package/dist/logic/island-def.d.ts +89 -0
- package/dist/logic/island-def.js +59 -0
- package/dist/logic/kit-commands.d.ts +104 -0
- package/dist/logic/kit-commands.js +72 -0
- package/dist/logic/kit-errors.d.ts +25 -0
- package/dist/logic/kit-errors.js +6 -0
- package/dist/logic/listen.d.ts +99 -0
- package/dist/logic/listen.js +92 -0
- package/dist/logic/mutation-def.d.ts +65 -0
- package/dist/logic/mutation-def.js +43 -0
- package/dist/logic/navigation-data.d.ts +50 -0
- package/dist/logic/navigation-data.js +55 -0
- package/dist/logic/navigation-policy.d.ts +74 -0
- package/dist/logic/navigation-policy.js +127 -0
- package/dist/logic/page-model-def.d.ts +108 -0
- package/dist/logic/page-model-def.js +31 -0
- package/dist/logic/path.d.ts +31 -0
- package/dist/logic/path.js +48 -0
- package/dist/logic/query-def.d.ts +56 -0
- package/dist/logic/query-def.js +37 -0
- package/dist/logic/query-key.d.ts +24 -0
- package/dist/logic/query-key.js +35 -0
- package/dist/logic/query-types.d.ts +28 -0
- package/dist/logic/query-types.js +2 -0
- package/dist/logic/resources.d.ts +163 -0
- package/dist/logic/resources.js +62 -0
- package/dist/logic/result.d.ts +30 -0
- package/dist/logic/result.js +23 -0
- package/dist/logic/route-model.d.ts +139 -0
- package/dist/logic/route-model.js +207 -0
- package/dist/logic/route-params.d.ts +80 -0
- package/dist/logic/route-params.js +114 -0
- package/dist/logic/route-table.d.ts +308 -0
- package/dist/logic/route-table.js +206 -0
- package/dist/logic/seo.d.ts +61 -0
- package/dist/logic/seo.js +101 -0
- package/dist/logic/site.d.ts +12 -0
- package/dist/logic/site.js +0 -0
- package/dist/logic/subscriptions.d.ts +177 -0
- package/dist/logic/subscriptions.js +152 -0
- package/dist/render/index.d.ts +32 -0
- package/dist/render/index.js +52 -0
- package/dist/runtime/island-wake.d.ts +38 -0
- package/dist/runtime/island-wake.js +147 -0
- package/dist/runtime/query-scope.d.ts +224 -0
- package/dist/runtime/query-scope.js +222 -0
- package/dist/runtime/room-hub.d.ts +107 -0
- package/dist/runtime/room-hub.js +307 -0
- package/dist/runtime/subscription-runner.d.ts +71 -0
- package/dist/runtime/subscription-runner.js +240 -0
- package/dist/server/bindings.d.ts +41 -0
- package/dist/server/bindings.js +74 -0
- package/dist/server/browser.d.ts +9 -0
- package/dist/server/browser.js +9 -0
- package/dist/server/edge-cache.d.ts +28 -0
- package/dist/server/edge-cache.js +35 -0
- package/dist/server/errors.d.ts +45 -0
- package/dist/server/errors.js +36 -0
- package/dist/server/form-actions-setup.d.ts +1 -0
- package/dist/server/form-actions-setup.js +15 -0
- package/dist/server/form-actions.d.ts +121 -0
- package/dist/server/form-actions.js +211 -0
- package/dist/server/index.d.ts +36 -0
- package/dist/server/index.js +35 -0
- package/dist/server/inputs.d.ts +45 -0
- package/dist/server/inputs.js +77 -0
- package/dist/server/rate-limit.d.ts +29 -0
- package/dist/server/rate-limit.js +32 -0
- package/dist/server/read-cache.d.ts +74 -0
- package/dist/server/read-cache.js +58 -0
- package/dist/server/request-info.d.ts +17 -0
- package/dist/server/request-info.js +11 -0
- package/dist/server/request.d.ts +52 -0
- package/dist/server/request.js +73 -0
- package/dist/server/response-cookies.d.ts +23 -0
- package/dist/server/response-cookies.js +24 -0
- package/dist/server/run-effect.d.ts +42 -0
- package/dist/server/run-effect.js +92 -0
- package/dist/server/run.d.ts +63 -0
- package/dist/server/run.js +66 -0
- package/dist/server/session.d.ts +125 -0
- package/dist/server/session.js +247 -0
- package/dist/test/fake-bindings.d.ts +32 -0
- package/dist/test/fake-bindings.js +108 -0
- package/dist/test/fake-room.d.ts +66 -0
- package/dist/test/fake-room.js +216 -0
- package/dist/test/index.d.ts +19 -0
- package/dist/test/index.js +44 -0
- package/dist/test/probe.d.ts +11 -0
- package/dist/test/probe.js +11 -0
- package/dist/test/solid-jsx.d.ts +23 -0
- package/dist/test/solid-jsx.js +28 -0
- package/dist/test/solid-preload.d.ts +1 -0
- package/dist/test/solid-preload.js +29 -0
- package/dist/ui/code-editor/index.d.ts +21 -0
- package/dist/ui/code-editor/index.jsx +286 -0
- package/dist/ui/collab-text/index.d.ts +29 -0
- package/dist/ui/collab-text/index.jsx +96 -0
- package/dist/ui/components/controls.d.ts +69 -0
- package/dist/ui/components/controls.jsx +81 -0
- package/dist/ui/components/feedback.d.ts +26 -0
- package/dist/ui/components/feedback.jsx +80 -0
- package/dist/ui/components/layout.d.ts +74 -0
- package/dist/ui/components/layout.jsx +146 -0
- package/dist/ui/components/lists.d.ts +69 -0
- package/dist/ui/components/lists.jsx +133 -0
- package/dist/ui/components/navigation.d.ts +73 -0
- package/dist/ui/components/navigation.jsx +112 -0
- package/dist/ui/components/text.d.ts +34 -0
- package/dist/ui/components/text.jsx +163 -0
- package/dist/ui/index.d.ts +7 -0
- package/dist/ui/index.js +7 -0
- package/dist/ui/jsx-runtime.d.ts +19 -0
- package/dist/ui/jsx-runtime.js +0 -0
- package/dist/ui/list-keys.d.ts +31 -0
- package/dist/ui/list-keys.js +45 -0
- package/dist/ui/styles/base.css +38 -0
- package/dist/ui/styles/components.css +608 -0
- package/dist/ui/styles/tokens.css +27 -0
- package/dist/ui/styles/transitions.css +23 -0
- package/dist/ui/styles/workbench.css +428 -0
- package/dist/ui/styles.css +9 -0
- package/dist/view/agent-actions-view.d.ts +30 -0
- package/dist/view/agent-actions-view.js +27 -0
- package/dist/view/agent-surface.d.ts +42 -0
- package/dist/view/agent-surface.js +123 -0
- package/dist/view/app-scope.d.ts +51 -0
- package/dist/view/app-scope.js +75 -0
- package/dist/view/boundary.d.ts +18 -0
- package/dist/view/boundary.jsx +26 -0
- package/dist/view/command-runner.d.ts +16 -0
- package/dist/view/command-runner.js +245 -0
- package/dist/view/form.d.ts +82 -0
- package/dist/view/form.jsx +109 -0
- package/dist/view/head-view.d.ts +31 -0
- package/dist/view/head-view.js +46 -0
- package/dist/view/index.d.ts +41 -0
- package/dist/view/index.js +40 -0
- package/dist/view/island-root.d.ts +30 -0
- package/dist/view/island-root.js +36 -0
- package/dist/view/island.d.ts +102 -0
- package/dist/view/island.jsx +154 -0
- package/dist/view/match.d.ts +41 -0
- package/dist/view/match.js +111 -0
- package/dist/view/model.d.ts +92 -0
- package/dist/view/model.js +162 -0
- package/dist/view/navigation-head.d.ts +29 -0
- package/dist/view/navigation-head.jsx +38 -0
- package/dist/view/page-model.d.ts +46 -0
- package/dist/view/page-model.js +146 -0
- package/dist/view/query-effects.d.ts +87 -0
- package/dist/view/query-effects.js +147 -0
- package/dist/view/query-ok.d.ts +45 -0
- package/dist/view/query-ok.js +96 -0
- package/dist/view/query.d.ts +115 -0
- package/dist/view/query.jsx +179 -0
- package/dist/view/result-view.d.ts +14 -0
- package/dist/view/result-view.jsx +15 -0
- package/dist/view/route-pages.d.ts +43 -0
- package/dist/view/route-pages.js +59 -0
- package/dist/view/router.d.ts +44 -0
- package/dist/view/router.js +123 -0
- package/dist/vite/dev-middleware.d.ts +12 -0
- package/dist/vite/dev-middleware.js +39 -0
- package/dist/vite/dev-objects.d.ts +25 -0
- package/dist/vite/dev-objects.js +127 -0
- package/dist/vite/dev-platform.d.ts +19 -0
- package/dist/vite/dev-platform.js +77 -0
- package/dist/vite/dev-seo-files.d.ts +11 -0
- package/dist/vite/dev-seo-files.js +40 -0
- package/dist/vite/index.d.ts +53 -0
- package/dist/vite/index.js +148 -0
- package/dist/vite/local-config.d.ts +34 -0
- package/dist/vite/local-config.js +72 -0
- package/dist/vite/worker-build.d.ts +24 -0
- package/dist/vite/worker-build.js +84 -0
- package/dist/worker/create-worker.d.ts +52 -0
- package/dist/worker/create-worker.js +90 -0
- package/dist/worker/index.d.ts +12 -0
- package/dist/worker/index.js +12 -0
- package/dist/worker/page-routes.d.ts +88 -0
- package/dist/worker/page-routes.js +100 -0
- package/dist/worker/page-status.d.ts +41 -0
- package/dist/worker/page-status.js +23 -0
- package/dist/worker/request-prelude.d.ts +69 -0
- package/dist/worker/request-prelude.js +107 -0
- package/dist/worker/security.d.ts +76 -0
- package/dist/worker/security.js +137 -0
- package/dist/worker/server-app.d.ts +54 -0
- package/dist/worker/server-app.js +76 -0
- package/guards/browser-only.js +5 -0
- package/guards/node-only.js +6 -0
- package/guards/server-only.js +5 -0
- package/migrations/0001-sessions.sql +22 -0
- package/package.json +233 -5
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Types of the live rooms server: what an app supplies (hooks), what the
|
|
3
|
+
* Worker hands a room (identity), and the structural slices of the
|
|
4
|
+
* Cloudflare runtime the kit uses. Structural on purpose: the kit does not
|
|
5
|
+
* load `@cloudflare/workers-types` (it clashes with Bun's globals), and
|
|
6
|
+
* tests pass fakes.
|
|
7
|
+
*/
|
|
8
|
+
import type { AnyLiveRoomsDecl, DocNameOf, RoomTypeOf } from '../declaration.ts';
|
|
9
|
+
import type { RoomAccess, RoomRef } from '../protocol.ts';
|
|
10
|
+
/**
|
|
11
|
+
* Who is connecting, resolved by the Worker from the request (the app's
|
|
12
|
+
* session) before the upgrade. Never read from the client.
|
|
13
|
+
*/
|
|
14
|
+
export type LiveUser = {
|
|
15
|
+
readonly _tag: 'Member';
|
|
16
|
+
readonly userId: string;
|
|
17
|
+
readonly name: string;
|
|
18
|
+
/**
|
|
19
|
+
* An opaque handle for the session (e.g. its row id), so the room can
|
|
20
|
+
* re-check it later and close this session's sockets. Never the cookie.
|
|
21
|
+
*/
|
|
22
|
+
readonly session: string;
|
|
23
|
+
} | {
|
|
24
|
+
readonly _tag: 'Guest';
|
|
25
|
+
};
|
|
26
|
+
/** What `authorize` is asked. `join` gates the upgrade; `edit` gates doc writes. */
|
|
27
|
+
export type RoomAction = 'join' | 'edit';
|
|
28
|
+
/** What hooks get besides their arguments. */
|
|
29
|
+
export interface RoomHookContext<Env> {
|
|
30
|
+
/** The Worker's (or the room object's) bindings. */
|
|
31
|
+
readonly env: Env;
|
|
32
|
+
/** Epoch ms. */
|
|
33
|
+
readonly now: number;
|
|
34
|
+
}
|
|
35
|
+
/** The persisted state of a doc, handed to `persist`. */
|
|
36
|
+
export interface DocSnapshot {
|
|
37
|
+
readonly room: RoomRef;
|
|
38
|
+
readonly doc: string;
|
|
39
|
+
/** The text of the Y.Text named after the doc (the usual "one text field" case). */
|
|
40
|
+
readonly text: string;
|
|
41
|
+
/** The whole Yjs state (`Y.encodeStateAsUpdate`), for apps that store more than text. */
|
|
42
|
+
readonly state: Uint8Array;
|
|
43
|
+
}
|
|
44
|
+
/** Hooks for one collaborative doc. */
|
|
45
|
+
export interface DocHooks<Env> {
|
|
46
|
+
/** Largest stored size in bytes; writes past it are refused. Default 256 KiB. */
|
|
47
|
+
readonly maxBytes?: number;
|
|
48
|
+
/**
|
|
49
|
+
* Text for the doc's Y.Text on its very first load (no SQLite rows yet),
|
|
50
|
+
* e.g. the copy a previous `persist` wrote to D1. Runs at most once per room.
|
|
51
|
+
*/
|
|
52
|
+
readonly seed?: (room: RoomRef, ctx: RoomHookContext<Env>) => Promise<string | undefined>;
|
|
53
|
+
/**
|
|
54
|
+
* Copies the doc somewhere else (e.g. text to D1, so `<Query>` serves it to
|
|
55
|
+
* SSR, no-JS readers and agents), debounced after edits. Runs from the
|
|
56
|
+
* room's alarm, outside the mutation registry: the documented exception.
|
|
57
|
+
* A throw retries (alarm retry with backoff).
|
|
58
|
+
*/
|
|
59
|
+
readonly persist?: {
|
|
60
|
+
/** Default 2000 ms after the first unsaved edit. */
|
|
61
|
+
readonly debounceMs?: number;
|
|
62
|
+
readonly run: (snapshot: DocSnapshot, ctx: RoomHookContext<Env>) => Promise<void>;
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
/** Hooks for one room type. */
|
|
66
|
+
export interface RoomTypeHooks<Env, Doc extends string> {
|
|
67
|
+
/**
|
|
68
|
+
* The app's permission policy. `join`: may this user open the room at all
|
|
69
|
+
* (presence, cursors, reading docs)? `edit`: may they write its docs?
|
|
70
|
+
* Called by the Worker on every upgrade (`join`, then `edit` when the
|
|
71
|
+
* type has docs) and by the room when it re-checks an editor
|
|
72
|
+
* (`recheckEditMs`). Return `false` for a room that doesn't exist.
|
|
73
|
+
*/
|
|
74
|
+
readonly authorize: (user: LiveUser, room: RoomRef, action: RoomAction, ctx: RoomHookContext<Env>) => boolean | Promise<boolean>;
|
|
75
|
+
/** Extra key check beyond the shape (cheap, no I/O): a page room's allowlist. */
|
|
76
|
+
readonly key?: (key: string) => boolean;
|
|
77
|
+
/** Per-doc hooks (only declared docs typecheck). */
|
|
78
|
+
readonly docs?: {
|
|
79
|
+
readonly [N in Doc]?: DocHooks<Env>;
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
/** Everything an app supplies to `createLiveRooms`. */
|
|
83
|
+
export interface LiveRoomsHooks<D extends AnyLiveRoomsDecl, Env> {
|
|
84
|
+
/** Resolves who is connecting (one D1 read at most, only with a session cookie). */
|
|
85
|
+
readonly resolveUser: (request: Request, env: Env) => Promise<LiveUser>;
|
|
86
|
+
/** One entry per declared room type: a missing one is a type error and a startup error. */
|
|
87
|
+
readonly types: {
|
|
88
|
+
readonly [T in RoomTypeOf<D>]: RoomTypeHooks<Env, DocNameOf<D, T>>;
|
|
89
|
+
};
|
|
90
|
+
/** How often (at most) a room re-runs `authorize(…, "edit")` for a writing socket. Default 30 s. */
|
|
91
|
+
readonly recheckEditMs?: number;
|
|
92
|
+
}
|
|
93
|
+
/** What the Worker tells the room about a socket (header {@link IDENTITY_HEADER}). */
|
|
94
|
+
export interface LiveIdentity {
|
|
95
|
+
readonly peer: string;
|
|
96
|
+
readonly user: LiveUser;
|
|
97
|
+
readonly access: RoomAccess;
|
|
98
|
+
readonly socket: {
|
|
99
|
+
readonly _tag: 'Room';
|
|
100
|
+
} | {
|
|
101
|
+
readonly _tag: 'Doc';
|
|
102
|
+
readonly doc: string;
|
|
103
|
+
};
|
|
104
|
+
readonly room: {
|
|
105
|
+
readonly type: string;
|
|
106
|
+
readonly key: string;
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
/** The one header the Worker sets for the room (any client-sent copy is dropped). */
|
|
110
|
+
export declare const IDENTITY_HEADER = "x-live-identity";
|
|
111
|
+
/** A server-side hibernatable socket. */
|
|
112
|
+
export interface RoomSocket {
|
|
113
|
+
send(message: string | ArrayBuffer | Uint8Array): void;
|
|
114
|
+
close(code?: number, reason?: string): void;
|
|
115
|
+
serializeAttachment(value: unknown): void;
|
|
116
|
+
deserializeAttachment(): unknown;
|
|
117
|
+
}
|
|
118
|
+
/** `ctx.storage.sql.exec`'s cursor slice. */
|
|
119
|
+
export interface SqlCursor {
|
|
120
|
+
toArray(): Record<string, unknown>[];
|
|
121
|
+
}
|
|
122
|
+
/** The slice of `DurableObjectState` the room uses. */
|
|
123
|
+
export interface RoomState {
|
|
124
|
+
acceptWebSocket(socket: RoomSocket, tags?: string[]): void;
|
|
125
|
+
getWebSockets(tag?: string): RoomSocket[];
|
|
126
|
+
setWebSocketAutoResponse(pair: unknown): void;
|
|
127
|
+
readonly storage: {
|
|
128
|
+
readonly sql: {
|
|
129
|
+
exec(query: string, ...bindings: unknown[]): SqlCursor;
|
|
130
|
+
};
|
|
131
|
+
transactionSync<T>(fn: () => T): T;
|
|
132
|
+
getAlarm(): Promise<number | null>;
|
|
133
|
+
setAlarm(at: number): Promise<void>;
|
|
134
|
+
deleteAlarm(): Promise<void>;
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
/** What only workerd has (fakes in tests). */
|
|
138
|
+
export interface RoomRuntime {
|
|
139
|
+
newPair(): {
|
|
140
|
+
readonly client: RoomSocket;
|
|
141
|
+
readonly server: RoomSocket;
|
|
142
|
+
};
|
|
143
|
+
switchingProtocols(client: RoomSocket): Response;
|
|
144
|
+
autoResponse(request: string, response: string): unknown;
|
|
145
|
+
now(): number;
|
|
146
|
+
setTimeout(fn: () => void, ms: number): unknown;
|
|
147
|
+
randomId(): string;
|
|
148
|
+
}
|
|
149
|
+
/** The slice of a `DurableObjectNamespace` the route uses. */
|
|
150
|
+
export interface RoomNamespace {
|
|
151
|
+
idFromName(name: string): unknown;
|
|
152
|
+
get(id: unknown): {
|
|
153
|
+
fetch(request: Request): Promise<Response>;
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
/** The slice of a Rate Limiting binding the route uses. */
|
|
157
|
+
export interface ConnectLimiter {
|
|
158
|
+
limit(options: {
|
|
159
|
+
readonly key: string;
|
|
160
|
+
}): Promise<{
|
|
161
|
+
readonly success: boolean;
|
|
162
|
+
}>;
|
|
163
|
+
}
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Agent actions (draft, behind the site's `agents` flag): the Messages a
|
|
3
|
+
* page lets an in-browser agent send, declared as data next to the model,
|
|
4
|
+
* with an input schema the kit can both publish (JSON Schema) and check
|
|
5
|
+
* (a small validator, no Effect in the browser).
|
|
6
|
+
*
|
|
7
|
+
* An agent action is not a new endpoint. It builds an ordinary Message
|
|
8
|
+
* and the kit calls the panel's own `send`, so an agent acts with exactly
|
|
9
|
+
* the user's permissions, through `update`, Commands and mutations;
|
|
10
|
+
* mutations still decode their input on the server. Messages that report
|
|
11
|
+
* results (`SaveFinished`, query outcomes) can't be sent by an agent: only
|
|
12
|
+
* actions listed here exist.
|
|
13
|
+
*
|
|
14
|
+
* Pure and import-free (models may import it: `@alecsibilia/ui-kit/logic`).
|
|
15
|
+
*
|
|
16
|
+
* @example
|
|
17
|
+
* ```ts
|
|
18
|
+
* // planner.agent.ts
|
|
19
|
+
* export const plannerAgent = agentActions<PlanMessage, GearPlan>()({
|
|
20
|
+
* equipItem: {
|
|
21
|
+
* description: "Equip an item in one gear slot of the shown plan (autosaves).",
|
|
22
|
+
* effect: "write",
|
|
23
|
+
* input: { slot: agentField.oneOf(GEAR_SLOTS, "Gear slot"), itemId: agentField.oneOf(ITEM_IDS, "Item id") },
|
|
24
|
+
* toMessage: (input, plan) => ({ _tag: "SlotEquipped", slot: input.slot, itemId: input.itemId, base: planBase(plan) }),
|
|
25
|
+
* },
|
|
26
|
+
* });
|
|
27
|
+
* ```
|
|
28
|
+
*/
|
|
29
|
+
/** A string from a fixed set. */
|
|
30
|
+
export interface AgentOneOf<V extends string = string> {
|
|
31
|
+
readonly kind: 'oneOf';
|
|
32
|
+
readonly values: readonly V[];
|
|
33
|
+
readonly description: string;
|
|
34
|
+
}
|
|
35
|
+
/** Non-empty free text up to `maxLength`. */
|
|
36
|
+
export interface AgentText {
|
|
37
|
+
readonly kind: 'text';
|
|
38
|
+
readonly maxLength: number;
|
|
39
|
+
readonly description: string;
|
|
40
|
+
}
|
|
41
|
+
/** An integer in `[min, max]`. */
|
|
42
|
+
export interface AgentInt {
|
|
43
|
+
readonly kind: 'int';
|
|
44
|
+
readonly min: number;
|
|
45
|
+
readonly max: number;
|
|
46
|
+
readonly description: string;
|
|
47
|
+
}
|
|
48
|
+
export type AgentField = AgentOneOf | AgentText | AgentInt;
|
|
49
|
+
/** An action's input fields, by name (all required). */
|
|
50
|
+
export type AgentInputSpec = {
|
|
51
|
+
readonly [name: string]: AgentField;
|
|
52
|
+
};
|
|
53
|
+
/** The decoded input of a spec. */
|
|
54
|
+
export type AgentInputOf<S extends AgentInputSpec> = {
|
|
55
|
+
readonly [K in keyof S]: S[K] extends AgentOneOf<infer V> ? V : S[K] extends AgentText ? string : number;
|
|
56
|
+
};
|
|
57
|
+
/** Builders for action input fields (plain data). */
|
|
58
|
+
export declare const agentField: {
|
|
59
|
+
readonly oneOf: <const V extends string>(values: readonly V[], description: string) => AgentOneOf<V>;
|
|
60
|
+
readonly text: (description: string, maxLength?: number) => AgentText;
|
|
61
|
+
readonly int: (description: string, min?: number, max?: number) => AgentInt;
|
|
62
|
+
};
|
|
63
|
+
/**
|
|
64
|
+
* What an action does, for agents and browsers deciding whether to ask the
|
|
65
|
+
* user first (WebMCP `readOnlyHint` / `consequentialHint`):
|
|
66
|
+
* `read` changes nothing durable (refresh a panel), `ui` changes only what
|
|
67
|
+
* the page shows, `write` changes server data (through a mutation).
|
|
68
|
+
*/
|
|
69
|
+
export type AgentEffect = 'read' | 'ui' | 'write';
|
|
70
|
+
/** One action: a description for the model, its input, and the Message it sends. */
|
|
71
|
+
export interface AgentActionSpec<Msg, Ctx, S extends AgentInputSpec = AgentInputSpec> {
|
|
72
|
+
readonly description: string;
|
|
73
|
+
readonly effect: AgentEffect;
|
|
74
|
+
readonly input: S;
|
|
75
|
+
/** Builds the Message from the checked input and the panel's current context (its query value). */
|
|
76
|
+
readonly toMessage: (input: AgentInputOf<S>, context: Ctx) => Msg;
|
|
77
|
+
}
|
|
78
|
+
/** A panel's actions, by name. */
|
|
79
|
+
export type AgentActions<Msg, Ctx> = {
|
|
80
|
+
readonly [name: string]: AgentActionSpec<Msg, Ctx, any>;
|
|
81
|
+
};
|
|
82
|
+
/**
|
|
83
|
+
* Declares a panel's actions with their input types checked against
|
|
84
|
+
* `toMessage` (curried so `Msg` and `Ctx` are given and the specs inferred).
|
|
85
|
+
*/
|
|
86
|
+
export declare function agentActions<Msg, Ctx = undefined>(): <const S extends {
|
|
87
|
+
readonly [name: string]: AgentInputSpec;
|
|
88
|
+
}>(actions: { readonly [K in keyof S]: AgentActionSpec<Msg, Ctx, S[K]>; }) => { readonly [K in keyof S]: AgentActionSpec<Msg, Ctx, S[K]>; };
|
|
89
|
+
/** A JSON Schema object (draft 2020-12 subset). */
|
|
90
|
+
export type JsonSchema = {
|
|
91
|
+
readonly [key: string]: unknown;
|
|
92
|
+
};
|
|
93
|
+
/** JSON Schema for an action's input (what WebMCP `inputSchema` and the page manifest carry). */
|
|
94
|
+
export declare function inputJsonSchema(input: AgentInputSpec): JsonSchema;
|
|
95
|
+
/** The outcome of checking an agent's input. */
|
|
96
|
+
export type AgentInputCheck<T> = {
|
|
97
|
+
readonly _tag: 'Valid';
|
|
98
|
+
readonly input: T;
|
|
99
|
+
} | {
|
|
100
|
+
readonly _tag: 'Invalid';
|
|
101
|
+
readonly problems: readonly string[];
|
|
102
|
+
};
|
|
103
|
+
/**
|
|
104
|
+
* Checks untrusted input against a spec: an object with exactly the spec's
|
|
105
|
+
* fields, each of the right kind and range. Nothing is coerced.
|
|
106
|
+
*/
|
|
107
|
+
export declare function checkAgentInput<S extends AgentInputSpec>(spec: S, raw: unknown): AgentInputCheck<AgentInputOf<S>>;
|
|
108
|
+
/** One action as published to agents (page manifest and WebMCP tool). */
|
|
109
|
+
export interface AgentToolDescriptor {
|
|
110
|
+
/** `<panel>.<action>` (`planner.equipItem`). */
|
|
111
|
+
readonly name: string;
|
|
112
|
+
readonly description: string;
|
|
113
|
+
readonly effect: AgentEffect;
|
|
114
|
+
readonly inputSchema: JsonSchema;
|
|
115
|
+
}
|
|
116
|
+
/** The manifest of one panel's actions. */
|
|
117
|
+
export declare function agentToolDescriptors<Msg, Ctx>(panel: string, actions: AgentActions<Msg, Ctx>): AgentToolDescriptor[];
|
|
118
|
+
/** The `type` of the in-page manifest data block (`<script type=... data-agent-panel>`). */
|
|
119
|
+
export declare const AGENT_MANIFEST_TYPE = "application/vnd.our.agent-actions+json";
|
|
120
|
+
/** What calling an action returns to the agent. */
|
|
121
|
+
export type AgentCallResult = {
|
|
122
|
+
readonly _tag: 'Sent';
|
|
123
|
+
readonly message: string;
|
|
124
|
+
} | {
|
|
125
|
+
readonly _tag: 'Rejected';
|
|
126
|
+
readonly problems: readonly string[];
|
|
127
|
+
};
|
|
128
|
+
/**
|
|
129
|
+
* Runs one action for an agent: checks the input, builds the Message from
|
|
130
|
+
* the panel's current context and sends it. The kit's surface and tests
|
|
131
|
+
* share it.
|
|
132
|
+
*/
|
|
133
|
+
export declare function runAgentAction<Msg, Ctx, S extends AgentInputSpec>(spec: AgentActionSpec<Msg, Ctx, S>, raw: unknown, context: Ctx, send: (msg: Msg) => void): AgentCallResult;
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Agent actions (draft, behind the site's `agents` flag): the Messages a
|
|
3
|
+
* page lets an in-browser agent send, declared as data next to the model,
|
|
4
|
+
* with an input schema the kit can both publish (JSON Schema) and check
|
|
5
|
+
* (a small validator, no Effect in the browser).
|
|
6
|
+
*
|
|
7
|
+
* An agent action is not a new endpoint. It builds an ordinary Message
|
|
8
|
+
* and the kit calls the panel's own `send`, so an agent acts with exactly
|
|
9
|
+
* the user's permissions, through `update`, Commands and mutations;
|
|
10
|
+
* mutations still decode their input on the server. Messages that report
|
|
11
|
+
* results (`SaveFinished`, query outcomes) can't be sent by an agent: only
|
|
12
|
+
* actions listed here exist.
|
|
13
|
+
*
|
|
14
|
+
* Pure and import-free (models may import it: `@alecsibilia/ui-kit/logic`).
|
|
15
|
+
*
|
|
16
|
+
* @example
|
|
17
|
+
* ```ts
|
|
18
|
+
* // planner.agent.ts
|
|
19
|
+
* export const plannerAgent = agentActions<PlanMessage, GearPlan>()({
|
|
20
|
+
* equipItem: {
|
|
21
|
+
* description: "Equip an item in one gear slot of the shown plan (autosaves).",
|
|
22
|
+
* effect: "write",
|
|
23
|
+
* input: { slot: agentField.oneOf(GEAR_SLOTS, "Gear slot"), itemId: agentField.oneOf(ITEM_IDS, "Item id") },
|
|
24
|
+
* toMessage: (input, plan) => ({ _tag: "SlotEquipped", slot: input.slot, itemId: input.itemId, base: planBase(plan) }),
|
|
25
|
+
* },
|
|
26
|
+
* });
|
|
27
|
+
* ```
|
|
28
|
+
*/
|
|
29
|
+
/** Builders for action input fields (plain data). */
|
|
30
|
+
export const agentField = {
|
|
31
|
+
oneOf: (values, description) => ({
|
|
32
|
+
kind: 'oneOf',
|
|
33
|
+
values,
|
|
34
|
+
description,
|
|
35
|
+
}),
|
|
36
|
+
text: (description, maxLength = 200) => ({
|
|
37
|
+
kind: 'text',
|
|
38
|
+
maxLength,
|
|
39
|
+
description,
|
|
40
|
+
}),
|
|
41
|
+
int: (description, min = 0, max = Number.MAX_SAFE_INTEGER) => ({
|
|
42
|
+
kind: 'int',
|
|
43
|
+
min,
|
|
44
|
+
max,
|
|
45
|
+
description,
|
|
46
|
+
}),
|
|
47
|
+
};
|
|
48
|
+
/**
|
|
49
|
+
* Declares a panel's actions with their input types checked against
|
|
50
|
+
* `toMessage` (curried so `Msg` and `Ctx` are given and the specs inferred).
|
|
51
|
+
*/
|
|
52
|
+
export function agentActions() {
|
|
53
|
+
return (actions) => actions;
|
|
54
|
+
}
|
|
55
|
+
/** JSON Schema for an action's input (what WebMCP `inputSchema` and the page manifest carry). */
|
|
56
|
+
export function inputJsonSchema(input) {
|
|
57
|
+
const properties = {};
|
|
58
|
+
for (const [name, field] of Object.entries(input)) {
|
|
59
|
+
properties[name] =
|
|
60
|
+
field.kind === 'oneOf'
|
|
61
|
+
? {
|
|
62
|
+
type: 'string',
|
|
63
|
+
enum: field.values,
|
|
64
|
+
description: field.description,
|
|
65
|
+
}
|
|
66
|
+
: field.kind === 'text'
|
|
67
|
+
? {
|
|
68
|
+
type: 'string',
|
|
69
|
+
minLength: 1,
|
|
70
|
+
maxLength: field.maxLength,
|
|
71
|
+
description: field.description,
|
|
72
|
+
}
|
|
73
|
+
: {
|
|
74
|
+
type: 'integer',
|
|
75
|
+
minimum: field.min,
|
|
76
|
+
maximum: field.max,
|
|
77
|
+
description: field.description,
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
return {
|
|
81
|
+
type: 'object',
|
|
82
|
+
properties,
|
|
83
|
+
required: Object.keys(input),
|
|
84
|
+
additionalProperties: false,
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Checks untrusted input against a spec: an object with exactly the spec's
|
|
89
|
+
* fields, each of the right kind and range. Nothing is coerced.
|
|
90
|
+
*/
|
|
91
|
+
export function checkAgentInput(spec, raw) {
|
|
92
|
+
if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {
|
|
93
|
+
return { _tag: 'Invalid', problems: ['input must be an object'] };
|
|
94
|
+
}
|
|
95
|
+
const value = raw;
|
|
96
|
+
const problems = [];
|
|
97
|
+
for (const key of Object.keys(value))
|
|
98
|
+
if (!(key in spec))
|
|
99
|
+
problems.push(`unknown field \`${key}\``);
|
|
100
|
+
for (const [name, field] of Object.entries(spec)) {
|
|
101
|
+
const v = value[name];
|
|
102
|
+
if (field.kind === 'oneOf') {
|
|
103
|
+
if (typeof v !== 'string' ||
|
|
104
|
+
!field.values.includes(v)) {
|
|
105
|
+
problems.push(`\`${name}\` must be one of ${field.values.join(', ')}`);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
else if (field.kind === 'text') {
|
|
109
|
+
if (typeof v !== 'string' ||
|
|
110
|
+
v.length === 0 ||
|
|
111
|
+
v.length > field.maxLength) {
|
|
112
|
+
problems.push(`\`${name}\` must be text of 1 to ${field.maxLength} characters`);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
else if (typeof v !== 'number' ||
|
|
116
|
+
!Number.isSafeInteger(v) ||
|
|
117
|
+
v < field.min ||
|
|
118
|
+
v > field.max) {
|
|
119
|
+
problems.push(`\`${name}\` must be an integer in [${field.min}, ${field.max}]`);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
return problems.length > 0
|
|
123
|
+
? { _tag: 'Invalid', problems }
|
|
124
|
+
: { _tag: 'Valid', input: value };
|
|
125
|
+
}
|
|
126
|
+
/** The manifest of one panel's actions. */
|
|
127
|
+
export function agentToolDescriptors(panel, actions) {
|
|
128
|
+
return Object.entries(actions).map(([name, spec]) => ({
|
|
129
|
+
name: `${panel}.${name}`,
|
|
130
|
+
description: spec.description,
|
|
131
|
+
effect: spec.effect,
|
|
132
|
+
inputSchema: inputJsonSchema(spec.input),
|
|
133
|
+
}));
|
|
134
|
+
}
|
|
135
|
+
/** The `type` of the in-page manifest data block (`<script type=... data-agent-panel>`). */
|
|
136
|
+
export const AGENT_MANIFEST_TYPE = 'application/vnd.our.agent-actions+json';
|
|
137
|
+
/**
|
|
138
|
+
* Runs one action for an agent: checks the input, builds the Message from
|
|
139
|
+
* the panel's current context and sends it. The kit's surface and tests
|
|
140
|
+
* share it.
|
|
141
|
+
*/
|
|
142
|
+
export function runAgentAction(spec, raw, context, send) {
|
|
143
|
+
const checked = checkAgentInput(spec.input, raw);
|
|
144
|
+
if (checked._tag === 'Invalid')
|
|
145
|
+
return { _tag: 'Rejected', problems: checked.problems };
|
|
146
|
+
const msg = spec.toMessage(checked.input, context);
|
|
147
|
+
send(msg);
|
|
148
|
+
const tag = msg._tag;
|
|
149
|
+
return { _tag: 'Sent', message: typeof tag === 'string' ? tag : 'Message' };
|
|
150
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import type { KitCommand } from './kit-commands.ts';
|
|
2
|
+
import type { MutationDef } from './mutation-def.ts';
|
|
3
|
+
import type { UnexpectedQueryError } from './query-types.ts';
|
|
4
|
+
import type { Result as ResultValue, Tagged } from './result.ts';
|
|
5
|
+
/**
|
|
6
|
+
* The types an app's Command handlers (`commands/*.commands.ts`) and
|
|
7
|
+
* models are written against. The runtime that runs them is
|
|
8
|
+
* `createModel` (`@alecsibilia/ui-kit/view`); these are plain types, so
|
|
9
|
+
* the `commands/` layer imports only `@alecsibilia/ui-kit/logic`.
|
|
10
|
+
*/
|
|
11
|
+
export interface TraceEntry<Msg, Cmd> {
|
|
12
|
+
readonly message: Msg;
|
|
13
|
+
readonly commands: readonly Cmd[];
|
|
14
|
+
readonly at: number;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* What an app Command handler may do. Deliberately small: handlers run
|
|
18
|
+
* registered mutations and schedule Messages, nothing else. Reads are
|
|
19
|
+
* `<Query>` (+ the `Refetch` kit Command); browser effects the app needs
|
|
20
|
+
* (`StorageRead`, `StorageWrite`, `ScrollToTop`) are kit Commands returned
|
|
21
|
+
* from `update`. There is no general "run this promise" escape hatch, so a
|
|
22
|
+
* read or a write cannot bypass the query and mutation registries.
|
|
23
|
+
*/
|
|
24
|
+
export interface CommandContext<Msg> {
|
|
25
|
+
/** Sends a Message to this model (dropped after the model is disposed). */
|
|
26
|
+
readonly send: (msg: Msg) => void;
|
|
27
|
+
/**
|
|
28
|
+
* Runs a registered mutation (`createMutationRegistry`) and sends
|
|
29
|
+
* `toMessage(result)`. A thrown / network failure arrives as
|
|
30
|
+
* `{ _tag: "Err", error: { _tag: "Unexpected", message } }`. After `Ok`,
|
|
31
|
+
* the kit refetches every query in the mutation's `invalidates` in this
|
|
32
|
+
* page's `<AppScope>`, even if this model was disposed while the write
|
|
33
|
+
* was in flight (the write happened; other panels must not stay stale).
|
|
34
|
+
* Only the result Message is dropped after disposal. Keep `toMessage`
|
|
35
|
+
* a plain wrapper (`(result) => ({ _tag: "Saved", result })`): the
|
|
36
|
+
* decision belongs in `update`.
|
|
37
|
+
*/
|
|
38
|
+
readonly mutate: <Input, T, E extends Tagged>(mutation: MutationDef<Input, T, E>, input: Input, toMessage: (result: ResultValue<T, E | UnexpectedQueryError>) => Msg) => void;
|
|
39
|
+
/** Calls `fn` after `ms` unless the same key is scheduled again or cancelled. */
|
|
40
|
+
readonly debounce: (key: string, ms: number, fn: () => void) => void;
|
|
41
|
+
readonly cancel: (key: string) => void;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* One handler per app Command tag. Kit Commands (`Refetch`, `StorageRead`,
|
|
45
|
+
* `StorageWrite`, `ScrollToTop`) are run by the kit and need no handler.
|
|
46
|
+
*/
|
|
47
|
+
export type CommandHandlers<Cmd extends Tagged, Msg> = {
|
|
48
|
+
readonly [K in Exclude<Cmd, KitCommand>['_tag']]: (cmd: Extract<Cmd, {
|
|
49
|
+
readonly _tag: K;
|
|
50
|
+
}>, ctx: CommandContext<Msg>) => void;
|
|
51
|
+
};
|
|
52
|
+
/** What `init` returns: the model, or the model and its first Commands. */
|
|
53
|
+
export type InitResult<Model, Cmd> = Model | readonly [Model, readonly Cmd[]];
|
|
File without changes
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* True outside production builds. Vite replaces `import.meta.env.PROD`
|
|
3
|
+
* statically (`true` in `vite build`, `false` in `vite dev`); under Bun
|
|
4
|
+
* (`bun test`) `import.meta.env` is `process.env`, so `NODE_ENV` decides.
|
|
5
|
+
* Read as strings so the check typechecks under both Vite and Bun types.
|
|
6
|
+
* Plain Node (a Vite config loading the app's tables) has no
|
|
7
|
+
* `import.meta.env`: dev.
|
|
8
|
+
*/
|
|
9
|
+
export declare const IS_DEV: boolean;
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* True outside production builds. Vite replaces `import.meta.env.PROD`
|
|
3
|
+
* statically (`true` in `vite build`, `false` in `vite dev`); under Bun
|
|
4
|
+
* (`bun test`) `import.meta.env` is `process.env`, so `NODE_ENV` decides.
|
|
5
|
+
* Read as strings so the check typechecks under both Vite and Bun types.
|
|
6
|
+
* Plain Node (a Vite config loading the app's tables) has no
|
|
7
|
+
* `import.meta.env`: dev.
|
|
8
|
+
*/
|
|
9
|
+
export const IS_DEV = String(import.meta.env?.PROD) !== 'true' &&
|
|
10
|
+
String(import.meta.env?.NODE_ENV) !== 'production';
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Edit forms over server data: what to do when a save loses a race.
|
|
3
|
+
*
|
|
4
|
+
* The kit's pattern (an edit form is a draft over a `<Query>` value):
|
|
5
|
+
* 1. A save is a mutation with optimistic concurrency: the input carries the
|
|
6
|
+
* version the draft is based on, and the server fails with a typed
|
|
7
|
+
* `SaveConflict { expected_version, actual_version }` when it moved on.
|
|
8
|
+
* 2. On `SaveConflict`, `update` keeps the draft (never throws the user's
|
|
9
|
+
* edits away), shows a notice, and returns a kit `Refetch` of the query.
|
|
10
|
+
* 3. When the refetched value (version >= `actual_version`) arrives as a
|
|
11
|
+
* Message (`listen`), `update` calls `rebaseDraft(base, mine, theirs)`:
|
|
12
|
+
* a three-way merge per field. Fields the user changed keep the user's
|
|
13
|
+
* value (their edits on top); fields they didn't touch take the server's
|
|
14
|
+
* new value. The merged draft is based on the new version and is saved
|
|
15
|
+
* again (last writer wins per field the user touched).
|
|
16
|
+
*
|
|
17
|
+
* Pure and framework-free (`@alecsibilia/ui-kit/logic`), so a `.model.ts` uses it and
|
|
18
|
+
* `bun test` covers it.
|
|
19
|
+
*/
|
|
20
|
+
/** The typed failure a versioned save returns when the server moved on. */
|
|
21
|
+
export interface SaveConflictError {
|
|
22
|
+
readonly _tag: 'SaveConflict';
|
|
23
|
+
readonly expected_version: number;
|
|
24
|
+
readonly actual_version: number;
|
|
25
|
+
readonly message: string;
|
|
26
|
+
}
|
|
27
|
+
/** What `rebaseDraft` did, field by field (field names of the record). */
|
|
28
|
+
export interface Rebased<T> {
|
|
29
|
+
/** The user's edits on top of the server's new value. */
|
|
30
|
+
readonly merged: T;
|
|
31
|
+
/** Fields the user changed: their value wins. */
|
|
32
|
+
readonly kept: readonly (keyof T & string)[];
|
|
33
|
+
/** Fields the user changed that the server also changed (the user's value won). */
|
|
34
|
+
readonly overrode: readonly (keyof T & string)[];
|
|
35
|
+
/** Fields the user didn't touch that the server changed (the server's value taken). */
|
|
36
|
+
readonly took: readonly (keyof T & string)[];
|
|
37
|
+
/** Nothing left to save: the merge equals the server's value. */
|
|
38
|
+
readonly unchanged: boolean;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Three-way merge of a flat record: `base` is what the draft started from
|
|
42
|
+
* (the server's value at the draft's version), `mine` the draft, `theirs`
|
|
43
|
+
* the server's newer value. Fields compare by value (`===`, then JSON).
|
|
44
|
+
*
|
|
45
|
+
* @example
|
|
46
|
+
* ```ts
|
|
47
|
+
* const r = rebaseDraft({ head: "a", hands: "b" }, { head: "x", hands: "b" }, { head: "a", hands: "y" });
|
|
48
|
+
* r.merged; // { head: "x", hands: "y" }: my head edit on top, their hands change kept
|
|
49
|
+
* r.kept; // ["head"]
|
|
50
|
+
* r.took; // ["hands"]
|
|
51
|
+
* ```
|
|
52
|
+
*/
|
|
53
|
+
export declare function rebaseDraft<T extends Readonly<Record<string, unknown>>>(base: T, mine: T, theirs: T): Rebased<T>;
|
|
54
|
+
/** Whether a refetched server value is new enough to rebase a conflicted draft on. */
|
|
55
|
+
export declare function caughtUpWith(conflict: {
|
|
56
|
+
readonly actual_version: number;
|
|
57
|
+
}, server: {
|
|
58
|
+
readonly version: number;
|
|
59
|
+
}): boolean;
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Edit forms over server data: what to do when a save loses a race.
|
|
3
|
+
*
|
|
4
|
+
* The kit's pattern (an edit form is a draft over a `<Query>` value):
|
|
5
|
+
* 1. A save is a mutation with optimistic concurrency: the input carries the
|
|
6
|
+
* version the draft is based on, and the server fails with a typed
|
|
7
|
+
* `SaveConflict { expected_version, actual_version }` when it moved on.
|
|
8
|
+
* 2. On `SaveConflict`, `update` keeps the draft (never throws the user's
|
|
9
|
+
* edits away), shows a notice, and returns a kit `Refetch` of the query.
|
|
10
|
+
* 3. When the refetched value (version >= `actual_version`) arrives as a
|
|
11
|
+
* Message (`listen`), `update` calls `rebaseDraft(base, mine, theirs)`:
|
|
12
|
+
* a three-way merge per field. Fields the user changed keep the user's
|
|
13
|
+
* value (their edits on top); fields they didn't touch take the server's
|
|
14
|
+
* new value. The merged draft is based on the new version and is saved
|
|
15
|
+
* again (last writer wins per field the user touched).
|
|
16
|
+
*
|
|
17
|
+
* Pure and framework-free (`@alecsibilia/ui-kit/logic`), so a `.model.ts` uses it and
|
|
18
|
+
* `bun test` covers it.
|
|
19
|
+
*/
|
|
20
|
+
function same(a, b) {
|
|
21
|
+
return a === b || JSON.stringify(a) === JSON.stringify(b);
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Three-way merge of a flat record: `base` is what the draft started from
|
|
25
|
+
* (the server's value at the draft's version), `mine` the draft, `theirs`
|
|
26
|
+
* the server's newer value. Fields compare by value (`===`, then JSON).
|
|
27
|
+
*
|
|
28
|
+
* @example
|
|
29
|
+
* ```ts
|
|
30
|
+
* const r = rebaseDraft({ head: "a", hands: "b" }, { head: "x", hands: "b" }, { head: "a", hands: "y" });
|
|
31
|
+
* r.merged; // { head: "x", hands: "y" }: my head edit on top, their hands change kept
|
|
32
|
+
* r.kept; // ["head"]
|
|
33
|
+
* r.took; // ["hands"]
|
|
34
|
+
* ```
|
|
35
|
+
*/
|
|
36
|
+
export function rebaseDraft(base, mine, theirs) {
|
|
37
|
+
const merged = { ...theirs };
|
|
38
|
+
const kept = [];
|
|
39
|
+
const overrode = [];
|
|
40
|
+
const took = [];
|
|
41
|
+
const keys = new Set([
|
|
42
|
+
...Object.keys(base),
|
|
43
|
+
...Object.keys(mine),
|
|
44
|
+
...Object.keys(theirs),
|
|
45
|
+
]);
|
|
46
|
+
for (const key of keys) {
|
|
47
|
+
const mineChanged = !same(mine[key], base[key]);
|
|
48
|
+
const theirsChanged = !same(theirs[key], base[key]);
|
|
49
|
+
if (mineChanged) {
|
|
50
|
+
merged[key] = mine[key];
|
|
51
|
+
kept.push(key);
|
|
52
|
+
if (theirsChanged && !same(theirs[key], mine[key]))
|
|
53
|
+
overrode.push(key);
|
|
54
|
+
}
|
|
55
|
+
else if (theirsChanged) {
|
|
56
|
+
took.push(key);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
const unchanged = [...keys].every((key) => same(merged[key], theirs[key]));
|
|
60
|
+
return {
|
|
61
|
+
merged: merged,
|
|
62
|
+
kept: kept,
|
|
63
|
+
overrode: overrode,
|
|
64
|
+
took: took,
|
|
65
|
+
unchanged,
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
/** Whether a refetched server value is new enough to rebase a conflicted draft on. */
|
|
69
|
+
export function caughtUpWith(conflict, server) {
|
|
70
|
+
return server.version >= conflict.actual_version;
|
|
71
|
+
}
|