@wervt/client 0.0.0 → 0.0.2

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/README.md CHANGED
@@ -1,3 +1,24 @@
1
1
  # @wervt/client
2
2
 
3
- Placeholder. Released from https://github.com/wervt-app/wervt.
3
+ The browser side of an app on [wervt](https://wervt.app), for any framework. `@wervt/nuxt` wires
4
+ it up on its own; other apps call it directly.
5
+
6
+ ```ts
7
+ import {
8
+ feedback,
9
+ fetchUser,
10
+ loadFeedback,
11
+ loginUrl,
12
+ registerTools,
13
+ track,
14
+ trackPageView,
15
+ } from '@wervt/client'
16
+ import { applyMessages, loadSnapshot } from '@wervt/client/shape'
17
+ ```
18
+
19
+ - `fetchUser()`, `loginUrl()`, `logoutUrl()`: who is signed in, and where to sign in or out.
20
+ - `trackPageView(path)` on client-side navigations, `track(name, label)` for custom events.
21
+ - `loadFeedback({ key, url })` and `feedback.open()` / `feedback.setContext()`: kontor's widget.
22
+ - `registerTools()`: the app's tools for the browser's agent (WebMCP).
23
+ - `loadSnapshot(url)`, `applyMessages(rows, messages)` (`@wervt/client/shape`): rows from a shape
24
+ route, and keeping them current (needs `@electric-sql/client`).
@@ -0,0 +1,38 @@
1
+ interface KontorWidget {
2
+ open(): void;
3
+ close(): void;
4
+ setContext(values: Record<string, unknown>): void;
5
+ }
6
+ declare global {
7
+ interface Window {
8
+ kontor?: KontorWidget;
9
+ }
10
+ }
11
+ export interface FeedbackOptions {
12
+ /** The kontor intake key. */
13
+ key: string;
14
+ /** kontor's URL, e.g. `https://kontor.wervt.app`. */
15
+ url: string;
16
+ /** Sent with every report, so it's clear which app and release it is about. */
17
+ context?: Record<string, unknown>;
18
+ lang?: string;
19
+ position?: string;
20
+ label?: string;
21
+ color?: string;
22
+ }
23
+ /**
24
+ * Loads the widget script. Call it once the page is interactive, so it never delays the app.
25
+ */
26
+ export declare function loadFeedback(options: FeedbackOptions): void;
27
+ /**
28
+ * Controls the feedback widget: open it from your own button, or add context to every report,
29
+ * e.g. what the user was looking at. Works before the widget has loaded.
30
+ *
31
+ * @example feedback.setContext({ room: room.id })
32
+ */
33
+ export declare const feedback: {
34
+ open: () => void | undefined;
35
+ close: () => void | undefined;
36
+ setContext(values: Record<string, unknown>): void;
37
+ };
38
+ export {};
@@ -0,0 +1,40 @@
1
+ // src/feedback.ts
2
+ const pendingContext = {};
3
+ const widget = () => typeof window === "undefined" ? void 0 : window.kontor;
4
+ /**
5
+ * Loads the widget script. Call it once the page is interactive, so it never delays the app.
6
+ */
7
+ function loadFeedback(options) {
8
+ if (typeof document === "undefined") return;
9
+ const script = document.createElement("script");
10
+ script.src = `${options.url.replace(/\/$/, "")}/widget.js`;
11
+ script.async = true;
12
+ script.dataset.key = options.key;
13
+ for (const name of [
14
+ "lang",
15
+ "position",
16
+ "label",
17
+ "color"
18
+ ]) if (options[name]) script.dataset[name] = options[name];
19
+ script.dataset.context = JSON.stringify({
20
+ ...options.context,
21
+ ...pendingContext
22
+ });
23
+ script.addEventListener("load", () => widget()?.setContext(pendingContext));
24
+ document.head.appendChild(script);
25
+ }
26
+ /**
27
+ * Controls the feedback widget: open it from your own button, or add context to every report,
28
+ * e.g. what the user was looking at. Works before the widget has loaded.
29
+ *
30
+ * @example feedback.setContext({ room: room.id })
31
+ */
32
+ const feedback = {
33
+ open: () => widget()?.open(),
34
+ close: () => widget()?.close(),
35
+ setContext(values) {
36
+ Object.assign(pendingContext, values);
37
+ widget()?.setContext(values);
38
+ }
39
+ };
40
+ export { feedback, loadFeedback };
@@ -0,0 +1,6 @@
1
+ import { FeedbackOptions, feedback, loadFeedback } from "./feedback.js";
2
+ import { track, trackPageView } from "./track.js";
3
+ import { fetchUser, loginUrl, logoutUrl } from "./user.js";
4
+ import { ToolInfo, callTool, hasWebMcp, registerTools } from "./webmcp.js";
5
+ import { WervtRole, WervtUser } from "@wervt/core";
6
+ export { type FeedbackOptions, type ToolInfo, type WervtRole, type WervtUser, callTool, feedback, fetchUser, hasWebMcp, loadFeedback, loginUrl, logoutUrl, registerTools, track, trackPageView };
package/dist/index.js ADDED
@@ -0,0 +1,5 @@
1
+ import { feedback, loadFeedback } from "./feedback.js";
2
+ import { fetchUser, loginUrl, logoutUrl } from "./user.js";
3
+ import { track, trackPageView } from "./track.js";
4
+ import { callTool, hasWebMcp, registerTools } from "./webmcp.js";
5
+ export { callTool, feedback, fetchUser, hasWebMcp, loadFeedback, loginUrl, logoutUrl, registerTools, track, trackPageView };
@@ -0,0 +1,15 @@
1
+ import { Message, Offset, Row } from "@electric-sql/client";
2
+ export interface ShapeSnapshot<T> {
3
+ rows: [string, T][];
4
+ offset: Offset;
5
+ handle?: string;
6
+ /**
7
+ * The route answered 401: the shape needs a signed-in user and there is none, e.g. an anonymous
8
+ * visitor of a public app, or the deploy's page check. No rows, and nothing to stream.
9
+ */
10
+ unauthorized?: true;
11
+ }
12
+ /** The rows of the shape at `url` (absolute) as of now, without subscribing. */
13
+ export declare function loadSnapshot<T extends Row<unknown>>(url: string, fetchClient?: typeof fetch): Promise<ShapeSnapshot<T>>;
14
+ /** Applies Electric change messages to `rows`. Returns whether anything changed. */
15
+ export declare function applyMessages<T extends Row<unknown>>(rows: Map<string, T>, messages: Message<T>[]): boolean;
package/dist/shape.js ADDED
@@ -0,0 +1,63 @@
1
+ import { ShapeStream, isChangeMessage, isControlMessage } from "@electric-sql/client";
2
+ import { shapeParser } from "@wervt/core";
3
+ // src/shape.ts
4
+ /** The rows of the shape at `url` (absolute) as of now, without subscribing. */
5
+ async function loadSnapshot(url, fetchClient) {
6
+ const rows = /* @__PURE__ */ new Map();
7
+ let fail = () => {};
8
+ const stream = new ShapeStream({
9
+ url,
10
+ subscribe: false,
11
+ fetchClient,
12
+ parser: shapeParser,
13
+ onError: (e) => fail(e)
14
+ });
15
+ try {
16
+ await new Promise((resolve, reject) => {
17
+ fail = reject;
18
+ stream.subscribe((messages) => {
19
+ applyMessages(rows, messages);
20
+ if (stream.isUpToDate) resolve();
21
+ }, (e) => reject(e));
22
+ });
23
+ } catch (e) {
24
+ if (e?.status === 401) return {
25
+ rows: [],
26
+ offset: "-1",
27
+ unauthorized: true
28
+ };
29
+ throw e;
30
+ } finally {
31
+ stream.unsubscribeAll();
32
+ }
33
+ return {
34
+ rows: [...rows],
35
+ offset: stream.lastOffset,
36
+ handle: stream.shapeHandle
37
+ };
38
+ }
39
+ /** Applies Electric change messages to `rows`. Returns whether anything changed. */
40
+ function applyMessages(rows, messages) {
41
+ let changed = false;
42
+ for (const message of messages) if (isChangeMessage(message)) {
43
+ const { key, value } = message;
44
+ switch (message.headers.operation) {
45
+ case "insert":
46
+ rows.set(key, value);
47
+ break;
48
+ case "update":
49
+ rows.set(key, {
50
+ ...rows.get(key),
51
+ ...value
52
+ });
53
+ break;
54
+ case "delete": rows.delete(key);
55
+ }
56
+ changed = true;
57
+ } else if (isControlMessage(message) && message.headers.control === "must-refetch") {
58
+ rows.clear();
59
+ changed = true;
60
+ }
61
+ return changed;
62
+ }
63
+ export { applyMessages, loadSnapshot };
@@ -0,0 +1,12 @@
1
+ /** Counts a page view for a client-side navigation to `path` (with the app's base path). */
2
+ export declare function trackPageView(path: string, options?: {
3
+ base?: string;
4
+ }): void;
5
+ /**
6
+ * A custom event for wervt's analytics, e.g. `track('signup')` or `track('click', url)`. It shows
7
+ * up with its count and visitors in the dashboard and `wervt stats`. Cookieless like page views:
8
+ * only the event, its label and the current path are sent.
9
+ */
10
+ export declare function track(name: string, label?: string, options?: {
11
+ base?: string;
12
+ }): void;
package/dist/track.js ADDED
@@ -0,0 +1,24 @@
1
+ import { trimBase } from "./user.js";
2
+ // src/track.ts
3
+ function beacon(base, body) {
4
+ if (typeof navigator === "undefined") return;
5
+ navigator.sendBeacon?.(`${trimBase(base)}/_wervt/view`, new Blob([JSON.stringify(body)], { type: "application/json" }));
6
+ }
7
+ /** Counts a page view for a client-side navigation to `path` (with the app's base path). */
8
+ function trackPageView(path, options = {}) {
9
+ beacon(options.base, { path });
10
+ }
11
+ /**
12
+ * A custom event for wervt's analytics, e.g. `track('signup')` or `track('click', url)`. It shows
13
+ * up with its count and visitors in the dashboard and `wervt stats`. Cookieless like page views:
14
+ * only the event, its label and the current path are sent.
15
+ */
16
+ function track(name, label, options = {}) {
17
+ if (typeof location === "undefined") return;
18
+ beacon(options.base, {
19
+ path: location.pathname,
20
+ name,
21
+ label
22
+ });
23
+ }
24
+ export { track, trackPageView };
package/dist/user.d.ts ADDED
@@ -0,0 +1,12 @@
1
+ import { WervtUser } from "@wervt/core";
2
+ /** Sign in with wervt, then come back to `redirect` (a path in this app). */
3
+ export declare const loginUrl: (redirect?: string) => string;
4
+ /** Sign out of wervt (all apps), then come back to `redirect`. */
5
+ export declare const logoutUrl: (redirect?: string) => string;
6
+ /**
7
+ * The signed-in user from the app's `/_wervt/user` route, `null` when nobody is signed in or the
8
+ * route can't be reached. For pages the server didn't render with the user in them.
9
+ */
10
+ export declare function fetchUser(options?: {
11
+ base?: string;
12
+ }): Promise<WervtUser | null>;
package/dist/user.js ADDED
@@ -0,0 +1,22 @@
1
+ // src/user.ts
2
+ /** Sign in with wervt, then come back to `redirect` (a path in this app). */
3
+ const loginUrl = (redirect = "/") => `/_wervt/login?redirect=${encodeURIComponent(redirect)}`;
4
+ /** Sign out of wervt (all apps), then come back to `redirect`. */
5
+ const logoutUrl = (redirect = "/") => `/_wervt/logout?redirect=${encodeURIComponent(redirect)}`;
6
+ /**
7
+ * The signed-in user from the app's `/_wervt/user` route, `null` when nobody is signed in or the
8
+ * route can't be reached. For pages the server didn't render with the user in them.
9
+ */
10
+ async function fetchUser(options = {}) {
11
+ try {
12
+ const res = await fetch(`${trimBase(options.base)}/_wervt/user`);
13
+ return res.ok ? (await res.json()).user : null;
14
+ } catch {
15
+ return null;
16
+ }
17
+ }
18
+ /** The app's base path without its trailing slash, `''` at the root. */
19
+ function trimBase(base = "") {
20
+ return base.replace(/\/$/, "");
21
+ }
22
+ export { fetchUser, loginUrl, logoutUrl, trimBase };
@@ -0,0 +1,19 @@
1
+ export interface ToolInfo {
2
+ name: string;
3
+ description: string;
4
+ inputSchema: object;
5
+ readOnly: boolean;
6
+ }
7
+ /** Whether the browser has WebMCP, so apps can skip loading tools when it doesn't. */
8
+ export declare const hasWebMcp: () => boolean;
9
+ /** Calls one of the app's tools, with the error the agent needs to correct its call. */
10
+ export declare function callTool(name: string, input: unknown, options?: {
11
+ base?: string;
12
+ }): Promise<{} | null>;
13
+ /**
14
+ * Registers the app's tools with the browser's agent. Does nothing in browsers without WebMCP,
15
+ * so they don't pay for the extra request.
16
+ */
17
+ export declare function registerTools(options?: {
18
+ base?: string;
19
+ }): Promise<void>;
package/dist/webmcp.js ADDED
@@ -0,0 +1,51 @@
1
+ import { trimBase } from "./user.js";
2
+ // src/webmcp.ts
3
+ function pageModelContext() {
4
+ if (typeof document === "undefined") return void 0;
5
+ const context = document.modelContext ?? navigator.modelContext;
6
+ return typeof context?.registerTool === "function" ? context : void 0;
7
+ }
8
+ /** Whether the browser has WebMCP, so apps can skip loading tools when it doesn't. */
9
+ const hasWebMcp = () => pageModelContext() !== void 0;
10
+ /** Calls one of the app's tools, with the error the agent needs to correct its call. */
11
+ async function callTool(name, input, options = {}) {
12
+ const res = await fetch(`${trimBase(options.base)}/_wervt/tools/${encodeURIComponent(name)}`, {
13
+ method: "POST",
14
+ headers: { "content-type": "application/json" },
15
+ body: JSON.stringify(input ?? {})
16
+ });
17
+ const body = await res.json().catch(() => void 0);
18
+ if (res.ok) return body?.result ?? null;
19
+ const issues = body?.issues ?? body?.data;
20
+ const message = (typeof body?.error === "string" ? body.error : body?.message) ?? `${res.status} ${res.statusText}`;
21
+ throw new Error(issues ? `${message} ${JSON.stringify(issues)}` : message);
22
+ }
23
+ /**
24
+ * Registers the app's tools with the browser's agent. Does nothing in browsers without WebMCP,
25
+ * so they don't pay for the extra request.
26
+ */
27
+ async function registerTools(options = {}) {
28
+ const context = pageModelContext();
29
+ if (!context) return;
30
+ let tools;
31
+ try {
32
+ const res = await fetch(`${trimBase(options.base)}/_wervt/tools`);
33
+ if (!res.ok) return;
34
+ tools = await res.json();
35
+ } catch {
36
+ return;
37
+ }
38
+ for (const tool of tools) try {
39
+ const result = context.registerTool({
40
+ name: tool.name,
41
+ description: tool.description,
42
+ inputSchema: tool.inputSchema,
43
+ ...tool.readOnly ? { annotations: { readOnlyHint: true } } : {},
44
+ execute: (input) => callTool(tool.name, input, options)
45
+ });
46
+ if (result instanceof Promise) result.catch((e) => console.warn(`wervt: could not register tool ${tool.name}`, e));
47
+ } catch (e) {
48
+ console.warn(`wervt: could not register tool ${tool.name}`, e);
49
+ }
50
+ }
51
+ export { callTool, hasWebMcp, registerTools };
package/package.json CHANGED
@@ -1 +1,50 @@
1
- {"name":"@wervt/client","version":"0.0.0","description":"Placeholder, the first release follows from CI.","license":"MIT","repository":{"type":"git","url":"git+https://github.com/wervt-app/wervt.git","directory":"packages/client"}}
1
+ {
2
+ "name": "@wervt/client",
3
+ "version": "0.0.2",
4
+ "description": "Browser SDK for apps on wervt, for any framework: the signed-in user, live data from shapes, analytics events, the feedback widget and WebMCP tools.",
5
+ "keywords": [
6
+ "electric",
7
+ "webmcp",
8
+ "wervt"
9
+ ],
10
+ "homepage": "https://wervt.app",
11
+ "license": "MIT",
12
+ "author": "Niki2k1",
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "git+https://github.com/wervt-app/wervt.git",
16
+ "directory": "packages/client"
17
+ },
18
+ "files": [
19
+ "dist",
20
+ "README.md"
21
+ ],
22
+ "type": "module",
23
+ "exports": {
24
+ ".": {
25
+ "types": "./dist/index.d.ts",
26
+ "default": "./dist/index.js"
27
+ },
28
+ "./shape": {
29
+ "types": "./dist/shape.d.ts",
30
+ "default": "./dist/shape.js"
31
+ }
32
+ },
33
+ "dependencies": {
34
+ "@wervt/core": "^0.0.2"
35
+ },
36
+ "devDependencies": {
37
+ "@electric-sql/client": "^1.5.28"
38
+ },
39
+ "peerDependencies": {
40
+ "@electric-sql/client": "^1.5.28"
41
+ },
42
+ "peerDependenciesMeta": {
43
+ "@electric-sql/client": {
44
+ "optional": true
45
+ }
46
+ },
47
+ "scripts": {
48
+ "build": "vp pack"
49
+ }
50
+ }