@powersync/diagnostics 0.0.0-dev-20261020125654
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 +201 -0
- package/README.md +138 -0
- package/lib/src/agent-server.d.ts +21 -0
- package/lib/src/agent-server.js +51 -0
- package/lib/src/agent-server.js.map +1 -0
- package/lib/src/agent.d.ts +11 -0
- package/lib/src/agent.js +30 -0
- package/lib/src/agent.js.map +1 -0
- package/lib/src/client.d.ts +7 -0
- package/lib/src/client.js +30 -0
- package/lib/src/client.js.map +1 -0
- package/lib/src/constants.d.ts +13 -0
- package/lib/src/constants.js +14 -0
- package/lib/src/constants.js.map +1 -0
- package/lib/src/definition.d.ts +16 -0
- package/lib/src/definition.js +421 -0
- package/lib/src/definition.js.map +1 -0
- package/lib/src/index.d.ts +4 -0
- package/lib/src/index.js +6 -0
- package/lib/src/index.js.map +1 -0
- package/lib/src/js-agent.d.ts +63 -0
- package/lib/src/js-agent.js +298 -0
- package/lib/src/js-agent.js.map +1 -0
- package/lib/src/node.d.ts +59 -0
- package/lib/src/node.js +40 -0
- package/lib/src/node.js.map +1 -0
- package/lib/src/page.d.ts +5 -0
- package/lib/src/page.js +50 -0
- package/lib/src/page.js.map +1 -0
- package/lib/src/rpc-types.d.ts +42 -0
- package/lib/src/rpc-types.js +2 -0
- package/lib/src/rpc-types.js.map +1 -0
- package/lib/src/sync-state.d.ts +4 -0
- package/lib/src/sync-state.js +53 -0
- package/lib/src/sync-state.js.map +1 -0
- package/lib/src/vite-static.d.ts +18 -0
- package/lib/src/vite-static.js +67 -0
- package/lib/src/vite-static.js.map +1 -0
- package/lib/src/vite.d.ts +27 -0
- package/lib/src/vite.js +43 -0
- package/lib/src/vite.js.map +1 -0
- package/lib/tsconfig.tsbuildinfo +1 -0
- package/package.json +98 -0
- package/src/agent-server.ts +73 -0
- package/src/agent.ts +58 -0
- package/src/client.ts +37 -0
- package/src/constants.ts +15 -0
- package/src/definition.ts +504 -0
- package/src/index.ts +7 -0
- package/src/js-agent.ts +378 -0
- package/src/node.ts +89 -0
- package/src/page.ts +61 -0
- package/src/rpc-types.ts +55 -0
- package/src/sync-state.ts +61 -0
- package/src/vite-static.ts +83 -0
- package/src/vite.ts +55 -0
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Serving agents to a devframe node side over an RPC client: a dock script in a web page, or a
|
|
3
|
+
* node process.
|
|
4
|
+
*/
|
|
5
|
+
import type { DevframeRpcClient } from 'devframe/client';
|
|
6
|
+
import type {
|
|
7
|
+
ActionRequest,
|
|
8
|
+
DiagnosticsEvent,
|
|
9
|
+
QueryParams,
|
|
10
|
+
SdkIntegration,
|
|
11
|
+
Unsubscribe
|
|
12
|
+
} from '@powersync/diagnostics-core';
|
|
13
|
+
import { HEARTBEAT_MS } from './constants.js';
|
|
14
|
+
import './rpc-types.js';
|
|
15
|
+
|
|
16
|
+
/** Serves integrations to the node side over one RPC client. */
|
|
17
|
+
export interface AgentServer {
|
|
18
|
+
/** Announces `integration` as `sourceId` and starts forwarding its events. */
|
|
19
|
+
serve(sourceId: string, integration: SdkIntegration, sdk: string): Promise<void>;
|
|
20
|
+
/** Withdraws a served integration. */
|
|
21
|
+
release(sourceId: string): Promise<void>;
|
|
22
|
+
/** Releases everything served through this client. */
|
|
23
|
+
close(): Promise<void>;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Registers the page-side functions the node side calls (`powersync:page-*`) on `rpc`, and returns
|
|
28
|
+
* a server that announces integrations to it. Call once per RPC client.
|
|
29
|
+
*/
|
|
30
|
+
export function createAgentServer(rpc: DevframeRpcClient): AgentServer {
|
|
31
|
+
const served = new Map<string, { integration: SdkIntegration; stop: Unsubscribe }>();
|
|
32
|
+
// The node side only knows this client is alive while it hears from it.
|
|
33
|
+
const heartbeat = setInterval(() => {
|
|
34
|
+
for (const sourceId of served.keys()) void rpc.callEvent('powersync:page-heartbeat', sourceId);
|
|
35
|
+
}, HEARTBEAT_MS);
|
|
36
|
+
(heartbeat as { unref?: () => void }).unref?.();
|
|
37
|
+
|
|
38
|
+
const integrationFor = (sourceId: string): SdkIntegration => {
|
|
39
|
+
const entry = served.get(sourceId);
|
|
40
|
+
if (!entry) throw new Error(`No database "${sourceId}" is served here.`);
|
|
41
|
+
return entry.integration;
|
|
42
|
+
};
|
|
43
|
+
const register = (name: string, handler: (...args: any[]) => unknown) =>
|
|
44
|
+
rpc.client.register({ name, type: 'action', jsonSerializable: true, handler }, true);
|
|
45
|
+
register('powersync:page-query', (id: string, params: QueryParams) => integrationFor(id).runQuery(params));
|
|
46
|
+
register('powersync:page-schema', (id: string) => integrationFor(id).getSchema());
|
|
47
|
+
register('powersync:page-info', (id: string) => integrationFor(id).getInfo());
|
|
48
|
+
register('powersync:page-action', (id: string, request: ActionRequest) => integrationFor(id).action(request));
|
|
49
|
+
|
|
50
|
+
return {
|
|
51
|
+
async serve(sourceId, integration, sdk) {
|
|
52
|
+
await rpc.call('powersync:page-register', sourceId, sdk);
|
|
53
|
+
const stop = await integration.observeEvents((event: DiagnosticsEvent) => {
|
|
54
|
+
void rpc.callEvent('powersync:page-event', sourceId, event);
|
|
55
|
+
});
|
|
56
|
+
served.set(sourceId, { integration, stop });
|
|
57
|
+
},
|
|
58
|
+
async release(sourceId) {
|
|
59
|
+
const entry = served.get(sourceId);
|
|
60
|
+
if (!entry) return;
|
|
61
|
+
served.delete(sourceId);
|
|
62
|
+
entry.stop();
|
|
63
|
+
await entry.integration.close();
|
|
64
|
+
await rpc.call('powersync:page-unregister', sourceId).catch(() => {});
|
|
65
|
+
},
|
|
66
|
+
async close() {
|
|
67
|
+
clearInterval(heartbeat);
|
|
68
|
+
for (const sourceId of [...served.keys()]) {
|
|
69
|
+
await this.release(sourceId);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
};
|
|
73
|
+
}
|
package/src/agent.ts
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The agent for a JavaScript host: the `SdkIntegration` built over a live database. This is the
|
|
3
|
+
* package's `./agent` entry, for a host that opens the database and embeds the DevTools page itself;
|
|
4
|
+
* the dock and node entries build their agents here too.
|
|
5
|
+
*/
|
|
6
|
+
import type { CommonPowerSyncDatabase, PowerSyncBackendConnector, SyncOptions } from '@powersync/common';
|
|
7
|
+
import type { CoreDiagnosticsEvent, SdkIntegration, Unsubscribe } from '@powersync/diagnostics-core';
|
|
8
|
+
import { JsAgent, type CoreEventSource } from './js-agent.js';
|
|
9
|
+
|
|
10
|
+
// The iframe hand-off and the protocol types an embedding host needs, so the host never imports the protocol package.
|
|
11
|
+
export { attachIframe } from '@powersync/diagnostics-core';
|
|
12
|
+
export type {
|
|
13
|
+
ActionRequest,
|
|
14
|
+
AttachIframeOptions,
|
|
15
|
+
DiagnosticsEvent,
|
|
16
|
+
SdkIntegration,
|
|
17
|
+
SyncState
|
|
18
|
+
} from '@powersync/diagnostics-core';
|
|
19
|
+
|
|
20
|
+
/** The sync client broadcasts core diagnostics events on this channel (see `emitDiagnostics`). */
|
|
21
|
+
const CORE_EVENTS_CHANNEL = 'powersync-diagnostics-events';
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* The connection accessors every SDK's database class has. They are not on the public
|
|
25
|
+
* `CommonPowerSyncDatabase` interface, so the agent reads them through this internal view.
|
|
26
|
+
*/
|
|
27
|
+
interface DiagnosableDatabase extends CommonPowerSyncDatabase {
|
|
28
|
+
readonly connector: PowerSyncBackendConnector | null | undefined;
|
|
29
|
+
readonly connectionOptions: SyncOptions | null | undefined;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Consumes the core diagnostics events the sync client broadcasts (from a worker or in-process). */
|
|
33
|
+
class BroadcastCoreEvents implements CoreEventSource {
|
|
34
|
+
private channel = new BroadcastChannel(CORE_EVENTS_CHANNEL);
|
|
35
|
+
|
|
36
|
+
onEvent(handler: (event: CoreDiagnosticsEvent) => void): Unsubscribe {
|
|
37
|
+
const listener = (event: MessageEvent) => handler(event.data as CoreDiagnosticsEvent);
|
|
38
|
+
this.channel.addEventListener('message', listener);
|
|
39
|
+
return () => this.channel.removeEventListener('message', listener);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
dispose(): void {
|
|
43
|
+
this.channel.close();
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Builds the JavaScript integration over a live database. The agent reads the connection from the database itself. */
|
|
48
|
+
export function createIntegration(database: CommonPowerSyncDatabase, sdk: string): SdkIntegration {
|
|
49
|
+
const db = database as DiagnosableDatabase;
|
|
50
|
+
return new JsAgent(db, {
|
|
51
|
+
sdk,
|
|
52
|
+
coreEvents: typeof BroadcastChannel === 'function' ? new BroadcastCoreEvents() : undefined,
|
|
53
|
+
connection: {
|
|
54
|
+
getConnector: () => db.connector ?? null,
|
|
55
|
+
getConnectionOptions: () => db.connectionOptions ?? null
|
|
56
|
+
}
|
|
57
|
+
});
|
|
58
|
+
}
|
package/src/client.ts
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The dock client script for `@powersync/web` apps. The devframe hub imports this module into the
|
|
3
|
+
* app page with an already trusted RPC client. It watches the app's open databases and serves each
|
|
4
|
+
* to the node side, which the diagnostics UI and MCP tools call.
|
|
5
|
+
*/
|
|
6
|
+
import type { DockClientScriptContext } from '@devframes/hub/client';
|
|
7
|
+
import { observeRegisteredDatabases } from '@powersync/web/devtools';
|
|
8
|
+
import { createIntegration } from './agent.js';
|
|
9
|
+
import { createAgentServer } from './agent-server.js';
|
|
10
|
+
|
|
11
|
+
const SDK = '@powersync/web';
|
|
12
|
+
|
|
13
|
+
export default function setup(context: DockClientScriptContext): void {
|
|
14
|
+
const server = createAgentServer(context.rpc);
|
|
15
|
+
let counter = 0;
|
|
16
|
+
let currentId: string | null = null;
|
|
17
|
+
|
|
18
|
+
// A closing tab cannot wait for the release to complete: withdraw first, the heartbeat is the backstop.
|
|
19
|
+
window.addEventListener('pagehide', () => {
|
|
20
|
+
if (currentId) void context.rpc.call('powersync:page-unregister', currentId);
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
observeRegisteredDatabases((databases) => {
|
|
24
|
+
const database = databases[0] ?? null;
|
|
25
|
+
if (!database) {
|
|
26
|
+
// The database closed: withdraw it.
|
|
27
|
+
if (currentId) {
|
|
28
|
+
void server.release(currentId);
|
|
29
|
+
currentId = null;
|
|
30
|
+
}
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
33
|
+
if (currentId) return;
|
|
34
|
+
currentId = `web-${++counter}`;
|
|
35
|
+
void server.serve(currentId, createIntegration(database, SDK), SDK);
|
|
36
|
+
});
|
|
37
|
+
}
|
package/src/constants.ts
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The route the diagnostics UI is served from. It is the devframe mount base of the `powersync`
|
|
3
|
+
* definition (`/__<id>/`), and the same path `./vite-static` serves for hosts without a devframe hub,
|
|
4
|
+
* so an embedding host can point an iframe at it either way.
|
|
5
|
+
*/
|
|
6
|
+
export const UI_ROUTE = '/__powersync/';
|
|
7
|
+
|
|
8
|
+
/** The devframe definition id. RPC functions live in this scope: `powersync:<name>`. */
|
|
9
|
+
export const DEVFRAME_ID = 'powersync';
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* How often a page or app that serves a database reports in to the node side. A closed tab cannot
|
|
13
|
+
* say it went, so a source silent for three beats counts as gone.
|
|
14
|
+
*/
|
|
15
|
+
export const HEARTBEAT_MS = 2000;
|
|
@@ -0,0 +1,504 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The PowerSync devframe definition: the node side every host mounts (a Vite DevTools dock, a node
|
|
3
|
+
* app's own dev server).
|
|
4
|
+
*
|
|
5
|
+
* It exposes `SdkIntegration` one RPC function per method. The databases it serves are *sources*:
|
|
6
|
+
* an integration living in this process (a node app), or a `RemoteIntegration` that forwards to a
|
|
7
|
+
* connected page or app which announced itself with `page-register`. UI clients subscribe with
|
|
8
|
+
* `observe` and receive pushed `DiagnosticsEvent`s; agents reach the same functions over MCP.
|
|
9
|
+
*/
|
|
10
|
+
import { createRequire } from 'node:module';
|
|
11
|
+
import { dirname, join } from 'node:path';
|
|
12
|
+
import { defineDevframe, defineRpcFunction, type DevframeNodeContext, type DevframeNodeRpcSession } from 'devframe';
|
|
13
|
+
import { z } from 'zod';
|
|
14
|
+
import type {
|
|
15
|
+
ActionRequest,
|
|
16
|
+
DiagnosticsEvent,
|
|
17
|
+
ProtocolInfo,
|
|
18
|
+
QueryParams,
|
|
19
|
+
QueryResult,
|
|
20
|
+
SchemaPayload,
|
|
21
|
+
SdkIntegration,
|
|
22
|
+
SyncState,
|
|
23
|
+
Unsubscribe,
|
|
24
|
+
UploadQueueState
|
|
25
|
+
} from '@powersync/diagnostics-core';
|
|
26
|
+
import { DEVFRAME_ID, HEARTBEAT_MS, UI_ROUTE } from './constants.js';
|
|
27
|
+
import type { SetupSdk, SourceInfo } from './rpc-types.js';
|
|
28
|
+
|
|
29
|
+
export type { SetupSdk, SourceInfo } from './rpc-types.js';
|
|
30
|
+
|
|
31
|
+
/** Event types replayed to a UI that subscribes late. `logs` and `core` are not replayed. */
|
|
32
|
+
const SNAPSHOT_TYPES = new Set<DiagnosticsEvent['type']>(['status', 'streams', 'buckets', 'uploadQueue']);
|
|
33
|
+
|
|
34
|
+
interface Source extends SourceInfo {
|
|
35
|
+
integration: SdkIntegration;
|
|
36
|
+
/** False once the page or app that served this database has gone. */
|
|
37
|
+
alive(): boolean;
|
|
38
|
+
/** When the serving page last reported in; `null` for a database in this process. */
|
|
39
|
+
lastSeen: number | null;
|
|
40
|
+
/** The latest snapshot per event type, for late subscribers. */
|
|
41
|
+
snapshots: Map<string, DiagnosticsEvent>;
|
|
42
|
+
stop?: Unsubscribe;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Calls into a page or app that serves a database over its own devframe connection. `sourceId` is
|
|
47
|
+
* the id the page serves it under, which differs from the id the node side lists when several pages
|
|
48
|
+
* announce the same one.
|
|
49
|
+
*/
|
|
50
|
+
class RemoteIntegration implements SdkIntegration {
|
|
51
|
+
constructor(
|
|
52
|
+
private session: DevframeNodeRpcSession,
|
|
53
|
+
private sourceId: string
|
|
54
|
+
) {}
|
|
55
|
+
|
|
56
|
+
get closed(): boolean {
|
|
57
|
+
return this.session.rpc.$closed;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
runQuery(params: QueryParams): Promise<QueryResult> {
|
|
61
|
+
return this.session.rpc.$call('powersync:page-query', this.sourceId, params);
|
|
62
|
+
}
|
|
63
|
+
getSchema(): Promise<SchemaPayload> {
|
|
64
|
+
return this.session.rpc.$call('powersync:page-schema', this.sourceId);
|
|
65
|
+
}
|
|
66
|
+
getInfo(): Promise<ProtocolInfo> {
|
|
67
|
+
return this.session.rpc.$call('powersync:page-info', this.sourceId);
|
|
68
|
+
}
|
|
69
|
+
action(request: ActionRequest): Promise<void> {
|
|
70
|
+
return this.session.rpc.$call('powersync:page-action', this.sourceId, request);
|
|
71
|
+
}
|
|
72
|
+
/** Events arrive as `page-event` pushes and are routed by the registry; nothing to subscribe here. */
|
|
73
|
+
async observeEvents(): Promise<Unsubscribe> {
|
|
74
|
+
return () => {};
|
|
75
|
+
}
|
|
76
|
+
async close(): Promise<void> {}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const sources = new Map<string, Source>();
|
|
80
|
+
/** The SDKs the entry point that mounted this definition can reach; `null` for all. */
|
|
81
|
+
let setupSdks: SetupSdk[] | null = null;
|
|
82
|
+
/** UI sessions that asked for events, keyed by session id. */
|
|
83
|
+
const observers = new Map<number, DevframeNodeRpcSession>();
|
|
84
|
+
/** The id a page serves a database under, per session, to the id it is listed under here. */
|
|
85
|
+
const pageSources = new Map<string, string>();
|
|
86
|
+
/** Runs while UIs observe, so a page that went away is dropped and announced without waiting for a call. */
|
|
87
|
+
let sweep: ReturnType<typeof setInterval> | undefined;
|
|
88
|
+
const SWEEP_INTERVAL_MS = 2000;
|
|
89
|
+
const STALE_AFTER_MS = HEARTBEAT_MS * 3;
|
|
90
|
+
|
|
91
|
+
function pageKey(session: DevframeNodeRpcSession, pageSourceId: string): string {
|
|
92
|
+
return `${session.meta.id}:${pageSourceId}`;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function pageAlive(remote: RemoteIntegration, source: () => Source | undefined): boolean {
|
|
96
|
+
if (remote.closed) return false;
|
|
97
|
+
const lastSeen = source()?.lastSeen;
|
|
98
|
+
return lastSeen == null || Date.now() - lastSeen < STALE_AFTER_MS;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Every page numbers its databases from 1, so a second page announcing `web-1` is listed as `web-2`. */
|
|
102
|
+
function allocateSourceId(pageSourceId: string): string {
|
|
103
|
+
const stem = pageSourceId.replace(/-\d+$/, '');
|
|
104
|
+
for (let number = 1; ; number++) {
|
|
105
|
+
const candidate = `${stem}-${number}`;
|
|
106
|
+
const taken = sources.get(candidate);
|
|
107
|
+
if (!taken || !taken.alive()) return candidate;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function sourceInfos(): SourceInfo[] {
|
|
112
|
+
return [...sources.values()].filter((source) => source.alive()).map((source) => ({ id: source.id, sdk: source.sdk }));
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function liveSources(): Source[] {
|
|
116
|
+
for (const [id, source] of sources) {
|
|
117
|
+
if (!source.alive()) {
|
|
118
|
+
removeSource(id);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
return [...sources.values()];
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function notifySources(): void {
|
|
125
|
+
const list = sourceInfos();
|
|
126
|
+
for (const [sessionId, session] of observers) {
|
|
127
|
+
if (session.rpc.$closed) {
|
|
128
|
+
observers.delete(sessionId);
|
|
129
|
+
continue;
|
|
130
|
+
}
|
|
131
|
+
void session.rpc.$callEvent('powersync:sources-changed', list);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function ensureSweep(): void {
|
|
136
|
+
if (sweep) return;
|
|
137
|
+
sweep = setInterval(() => {
|
|
138
|
+
liveSources();
|
|
139
|
+
if (observers.size === 0 && sweep) {
|
|
140
|
+
clearInterval(sweep);
|
|
141
|
+
sweep = undefined;
|
|
142
|
+
}
|
|
143
|
+
}, SWEEP_INTERVAL_MS);
|
|
144
|
+
sweep.unref?.();
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function pickSource(sourceId?: string | null): Source {
|
|
148
|
+
const live = liveSources();
|
|
149
|
+
const source = sourceId ? live.find((candidate) => candidate.id === sourceId) : live[0];
|
|
150
|
+
if (!source) {
|
|
151
|
+
throw new Error(
|
|
152
|
+
sourceId
|
|
153
|
+
? `No PowerSync database "${sourceId}" is attached.`
|
|
154
|
+
: 'No PowerSync database is attached. Open the app in a trusted browser tab, or call enablePowerSyncDiagnostics() in the node app.'
|
|
155
|
+
);
|
|
156
|
+
}
|
|
157
|
+
return source;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* The latest pushed snapshot of one event type, for the request-style tools (MCP). The protocol has
|
|
162
|
+
* no request for these; the source pushes them on subscribe and on every change, and they are kept
|
|
163
|
+
* here. `null` until the source has reported.
|
|
164
|
+
*/
|
|
165
|
+
function latestSnapshot(
|
|
166
|
+
sourceId: string | null | undefined,
|
|
167
|
+
type: DiagnosticsEvent['type']
|
|
168
|
+
): DiagnosticsEvent['payload'] | null {
|
|
169
|
+
return pickSource(sourceId).snapshots.get(type)?.payload ?? null;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function pushEvent(session: DevframeNodeRpcSession, sourceId: string, event: DiagnosticsEvent): void {
|
|
173
|
+
void session.rpc.$callEvent('powersync:event', sourceId, event);
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function fanOut(sourceId: string, event: DiagnosticsEvent): void {
|
|
177
|
+
const source = sources.get(sourceId);
|
|
178
|
+
if (!source) return;
|
|
179
|
+
if (SNAPSHOT_TYPES.has(event.type)) {
|
|
180
|
+
source.snapshots.set(event.type, event);
|
|
181
|
+
}
|
|
182
|
+
for (const [sessionId, session] of observers) {
|
|
183
|
+
if (session.rpc.$closed) {
|
|
184
|
+
observers.delete(sessionId);
|
|
185
|
+
continue;
|
|
186
|
+
}
|
|
187
|
+
pushEvent(session, sourceId, event);
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function addSource(source: Source): void {
|
|
192
|
+
sources.get(source.id)?.stop?.();
|
|
193
|
+
sources.set(source.id, source);
|
|
194
|
+
console.info(`[powersync-diagnostics] source attached: ${source.id} (${source.sdk ?? 'unknown sdk'})`);
|
|
195
|
+
notifySources();
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
function removeSource(sourceId: string): void {
|
|
199
|
+
const source = sources.get(sourceId);
|
|
200
|
+
if (!source) return;
|
|
201
|
+
source.stop?.();
|
|
202
|
+
sources.delete(sourceId);
|
|
203
|
+
for (const [key, id] of pageSources) {
|
|
204
|
+
if (id === sourceId) pageSources.delete(key);
|
|
205
|
+
}
|
|
206
|
+
console.info(`[powersync-diagnostics] source detached: ${sourceId}`);
|
|
207
|
+
notifySources();
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* Serves an integration that lives in this process (a node app's database). Events are pulled from
|
|
212
|
+
* it directly. Returns a function that detaches it.
|
|
213
|
+
*/
|
|
214
|
+
/**
|
|
215
|
+
* Names the SDKs this host can reach, so the UI's "no database" screens explain only those. Each entry
|
|
216
|
+
* point sets it: the Vite plugin, the node server, the Nuxt module.
|
|
217
|
+
*/
|
|
218
|
+
export function setSetupSdks(sdks: SetupSdk[] | null): void {
|
|
219
|
+
setupSdks = sdks?.length ? [...sdks] : null;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
export async function registerIntegration(
|
|
223
|
+
id: string,
|
|
224
|
+
integration: SdkIntegration,
|
|
225
|
+
sdk: string | null = null
|
|
226
|
+
): Promise<Unsubscribe> {
|
|
227
|
+
const source: Source = { id, sdk, integration, alive: () => true, lastSeen: null, snapshots: new Map() };
|
|
228
|
+
addSource(source);
|
|
229
|
+
source.stop = await integration.observeEvents((event) => fanOut(id, event));
|
|
230
|
+
return () => removeSource(id);
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/** The built diagnostics UI (`@powersync/diagnostics-ui/dist/standalone`), served as the dock page. */
|
|
234
|
+
export function uiDistDir(): string {
|
|
235
|
+
const require = createRequire(import.meta.url);
|
|
236
|
+
const pkg = require.resolve('@powersync/diagnostics-ui/package.json');
|
|
237
|
+
return join(dirname(pkg), 'dist', 'standalone');
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
const packageJson = createRequire(import.meta.url)('../../package.json') as { version: string; name: string };
|
|
241
|
+
|
|
242
|
+
// --- argument schemas (Standard Schema through zod): validated on the wire and shown to agents ---
|
|
243
|
+
// Agents see positional arguments as `arg0`, `arg1`, ... and every one is advertised as required, so
|
|
244
|
+
// each description spells out that convention and which values may be null.
|
|
245
|
+
|
|
246
|
+
const sourceIdArg = z
|
|
247
|
+
.string()
|
|
248
|
+
.nullable()
|
|
249
|
+
.optional()
|
|
250
|
+
.describe('Id of the attached database, from powersync_sources. Null for the first one.');
|
|
251
|
+
const queryParamsArg = z
|
|
252
|
+
.object({
|
|
253
|
+
sql: z.string().describe('SQL to run against the local SQLite database.'),
|
|
254
|
+
params: z.array(z.unknown()).optional().describe('Positional parameters for `?` placeholders.')
|
|
255
|
+
})
|
|
256
|
+
.describe('The query.');
|
|
257
|
+
const actionRequestArg = z
|
|
258
|
+
.object({
|
|
259
|
+
action: z.enum([
|
|
260
|
+
'reconnect',
|
|
261
|
+
'disconnect',
|
|
262
|
+
'clearData',
|
|
263
|
+
'requestCheckpoint',
|
|
264
|
+
'subscribeStream',
|
|
265
|
+
'unsubscribeStream'
|
|
266
|
+
]),
|
|
267
|
+
args: z
|
|
268
|
+
.object({
|
|
269
|
+
name: z.string(),
|
|
270
|
+
params: z.record(z.string(), z.unknown()).optional(),
|
|
271
|
+
ttl: z.number().optional(),
|
|
272
|
+
priority: z.union([z.literal(0), z.literal(1), z.literal(2), z.literal(3)]).optional()
|
|
273
|
+
})
|
|
274
|
+
.optional()
|
|
275
|
+
.describe('Stream name and options, for the stream actions only.')
|
|
276
|
+
})
|
|
277
|
+
.describe('The action to run.');
|
|
278
|
+
const anyResult = z.unknown();
|
|
279
|
+
|
|
280
|
+
export const definition = defineDevframe({
|
|
281
|
+
id: DEVFRAME_ID,
|
|
282
|
+
name: 'PowerSync',
|
|
283
|
+
version: packageJson.version,
|
|
284
|
+
packageName: packageJson.name,
|
|
285
|
+
importMetaUrl: import.meta.url,
|
|
286
|
+
homepage: 'https://docs.powersync.com',
|
|
287
|
+
description: 'Live diagnostics for the PowerSync client: sync status, buckets, streams, local data, schema and logs.',
|
|
288
|
+
// The PowerSync mark, shipped with the UI and served under the mount base.
|
|
289
|
+
icon: `${UI_ROUTE}powersync-icon.svg`,
|
|
290
|
+
clientAssets: uiDistDir(),
|
|
291
|
+
dock: {
|
|
292
|
+
category: 'app',
|
|
293
|
+
clientScript: {
|
|
294
|
+
// Runs in the app page: finds the live database and serves it to this node side.
|
|
295
|
+
importFrom: `${packageJson.name}/client`,
|
|
296
|
+
eager: true
|
|
297
|
+
}
|
|
298
|
+
},
|
|
299
|
+
setup(ctx: DevframeNodeContext) {
|
|
300
|
+
const ps = ctx.scope(DEVFRAME_ID);
|
|
301
|
+
const currentSession = () => {
|
|
302
|
+
const session = ctx.rpc.getCurrentRpcSession();
|
|
303
|
+
if (!session) throw new Error('No RPC session for this call.');
|
|
304
|
+
return session;
|
|
305
|
+
};
|
|
306
|
+
|
|
307
|
+
// --- page / app facing: a connected client serves a database ---
|
|
308
|
+
ps.rpc.register(
|
|
309
|
+
defineRpcFunction({
|
|
310
|
+
name: 'page-register',
|
|
311
|
+
type: 'action',
|
|
312
|
+
jsonSerializable: true,
|
|
313
|
+
handler: (pageSourceId: string, sdk: string | null) => {
|
|
314
|
+
const session = currentSession();
|
|
315
|
+
const id = allocateSourceId(pageSourceId);
|
|
316
|
+
pageSources.set(pageKey(session, pageSourceId), id);
|
|
317
|
+
const remote = new RemoteIntegration(session, pageSourceId);
|
|
318
|
+
addSource({
|
|
319
|
+
id,
|
|
320
|
+
sdk,
|
|
321
|
+
integration: remote,
|
|
322
|
+
alive: () => pageAlive(remote, () => sources.get(id)),
|
|
323
|
+
lastSeen: Date.now(),
|
|
324
|
+
snapshots: new Map()
|
|
325
|
+
});
|
|
326
|
+
}
|
|
327
|
+
})
|
|
328
|
+
);
|
|
329
|
+
ps.rpc.register(
|
|
330
|
+
defineRpcFunction({
|
|
331
|
+
name: 'page-heartbeat',
|
|
332
|
+
type: 'event',
|
|
333
|
+
jsonSerializable: true,
|
|
334
|
+
handler: (pageSourceId: string) => {
|
|
335
|
+
const id = pageSources.get(pageKey(currentSession(), pageSourceId));
|
|
336
|
+
const source = id ? sources.get(id) : undefined;
|
|
337
|
+
if (source) source.lastSeen = Date.now();
|
|
338
|
+
}
|
|
339
|
+
})
|
|
340
|
+
);
|
|
341
|
+
ps.rpc.register(
|
|
342
|
+
defineRpcFunction({
|
|
343
|
+
name: 'page-unregister',
|
|
344
|
+
type: 'action',
|
|
345
|
+
jsonSerializable: true,
|
|
346
|
+
handler: (pageSourceId: string) => {
|
|
347
|
+
const id = pageSources.get(pageKey(currentSession(), pageSourceId));
|
|
348
|
+
if (id) removeSource(id);
|
|
349
|
+
}
|
|
350
|
+
})
|
|
351
|
+
);
|
|
352
|
+
ps.rpc.register(
|
|
353
|
+
defineRpcFunction({
|
|
354
|
+
name: 'page-event',
|
|
355
|
+
type: 'event',
|
|
356
|
+
jsonSerializable: true,
|
|
357
|
+
handler: (pageSourceId: string, event: DiagnosticsEvent) => {
|
|
358
|
+
const id = pageSources.get(pageKey(currentSession(), pageSourceId));
|
|
359
|
+
if (id) fanOut(id, event);
|
|
360
|
+
}
|
|
361
|
+
})
|
|
362
|
+
);
|
|
363
|
+
|
|
364
|
+
// --- UI and agent facing: SdkIntegration, one function per method ---
|
|
365
|
+
ps.rpc.register(
|
|
366
|
+
defineRpcFunction({
|
|
367
|
+
name: 'sources',
|
|
368
|
+
type: 'query',
|
|
369
|
+
jsonSerializable: true,
|
|
370
|
+
agent: { description: 'List the PowerSync databases attached to this dev server, with their ids and SDKs.' },
|
|
371
|
+
handler: (): SourceInfo[] => {
|
|
372
|
+
liveSources();
|
|
373
|
+
return sourceInfos();
|
|
374
|
+
}
|
|
375
|
+
})
|
|
376
|
+
);
|
|
377
|
+
ps.rpc.register(
|
|
378
|
+
defineRpcFunction({
|
|
379
|
+
name: 'setup-sdks',
|
|
380
|
+
type: 'query',
|
|
381
|
+
jsonSerializable: true,
|
|
382
|
+
handler: (): SetupSdk[] | null => setupSdks
|
|
383
|
+
})
|
|
384
|
+
);
|
|
385
|
+
ps.rpc.register(
|
|
386
|
+
defineRpcFunction({
|
|
387
|
+
name: 'query',
|
|
388
|
+
type: 'action',
|
|
389
|
+
jsonSerializable: true,
|
|
390
|
+
args: [queryParamsArg, sourceIdArg],
|
|
391
|
+
returns: anyResult,
|
|
392
|
+
agent: {
|
|
393
|
+
description:
|
|
394
|
+
'Run SQL against the attached PowerSync SQLite database. App tables are views; the sync client state is in the ps_* tables (ps_buckets, ps_oplog, ps_crud, ps_stream_subscriptions). Returns columns and rows. Arguments: arg0 = { sql, params? }, arg1 = database id or null for the first one.',
|
|
395
|
+
safety: 'action'
|
|
396
|
+
},
|
|
397
|
+
handler: (params, sourceId) => pickSource(sourceId).integration.runQuery(params as QueryParams)
|
|
398
|
+
})
|
|
399
|
+
);
|
|
400
|
+
ps.rpc.register(
|
|
401
|
+
defineRpcFunction({
|
|
402
|
+
name: 'schema',
|
|
403
|
+
type: 'query',
|
|
404
|
+
jsonSerializable: true,
|
|
405
|
+
args: [sourceIdArg],
|
|
406
|
+
returns: anyResult,
|
|
407
|
+
agent: {
|
|
408
|
+
description:
|
|
409
|
+
'The client schema as the PowerSync SQLite core receives it: tables, columns, indexes. Argument: arg0 = database id or null for the first one.'
|
|
410
|
+
},
|
|
411
|
+
handler: (sourceId) => pickSource(sourceId).integration.getSchema()
|
|
412
|
+
})
|
|
413
|
+
);
|
|
414
|
+
ps.rpc.register(
|
|
415
|
+
defineRpcFunction({
|
|
416
|
+
name: 'info',
|
|
417
|
+
type: 'query',
|
|
418
|
+
jsonSerializable: true,
|
|
419
|
+
args: [sourceIdArg],
|
|
420
|
+
returns: anyResult,
|
|
421
|
+
agent: {
|
|
422
|
+
description:
|
|
423
|
+
'Connection info of the PowerSync client: endpoint, user id, client id, connection method, core version. Argument: arg0 = database id or null for the first one.'
|
|
424
|
+
},
|
|
425
|
+
handler: (sourceId) => pickSource(sourceId).integration.getInfo()
|
|
426
|
+
})
|
|
427
|
+
);
|
|
428
|
+
ps.rpc.register(
|
|
429
|
+
defineRpcFunction({
|
|
430
|
+
name: 'status',
|
|
431
|
+
type: 'query',
|
|
432
|
+
jsonSerializable: true,
|
|
433
|
+
args: [sourceIdArg],
|
|
434
|
+
returns: anyResult,
|
|
435
|
+
agent: {
|
|
436
|
+
description:
|
|
437
|
+
'The latest sync status the PowerSync client reported: connected, downloading, progress, last sync, errors. Null until it has reported. Argument: arg0 = database id or null for the first one.'
|
|
438
|
+
},
|
|
439
|
+
handler: async (sourceId) => latestSnapshot(sourceId, 'status')
|
|
440
|
+
})
|
|
441
|
+
);
|
|
442
|
+
ps.rpc.register(
|
|
443
|
+
defineRpcFunction({
|
|
444
|
+
name: 'upload-queue',
|
|
445
|
+
type: 'query',
|
|
446
|
+
jsonSerializable: true,
|
|
447
|
+
args: [sourceIdArg],
|
|
448
|
+
returns: anyResult,
|
|
449
|
+
agent: {
|
|
450
|
+
description:
|
|
451
|
+
'Pending local changes waiting to upload, as last reported: count and size. Null until reported. Argument: arg0 = database id or null for the first one.'
|
|
452
|
+
},
|
|
453
|
+
handler: async (sourceId) => latestSnapshot(sourceId, 'uploadQueue')
|
|
454
|
+
})
|
|
455
|
+
);
|
|
456
|
+
ps.rpc.register(
|
|
457
|
+
defineRpcFunction({
|
|
458
|
+
name: 'action',
|
|
459
|
+
type: 'action',
|
|
460
|
+
jsonSerializable: true,
|
|
461
|
+
args: [actionRequestArg, sourceIdArg],
|
|
462
|
+
returns: anyResult,
|
|
463
|
+
agent: {
|
|
464
|
+
description:
|
|
465
|
+
'Run a control action on the PowerSync client: reconnect, disconnect, clearData (wipes local data and re-syncs), requestCheckpoint, subscribeStream, unsubscribeStream. Arguments: arg0 = { action, args? }, arg1 = database id or null for the first one.',
|
|
466
|
+
safety: 'destructive'
|
|
467
|
+
},
|
|
468
|
+
handler: (request, sourceId) => pickSource(sourceId).integration.action(request as ActionRequest)
|
|
469
|
+
})
|
|
470
|
+
);
|
|
471
|
+
|
|
472
|
+
// --- UI facing: pushed events ---
|
|
473
|
+
ps.rpc.register(
|
|
474
|
+
defineRpcFunction({
|
|
475
|
+
name: 'observe',
|
|
476
|
+
type: 'action',
|
|
477
|
+
jsonSerializable: true,
|
|
478
|
+
handler: (sourceId?: string | null) => {
|
|
479
|
+
const session = currentSession();
|
|
480
|
+
observers.set(session.meta.id, session);
|
|
481
|
+
ensureSweep();
|
|
482
|
+
const live = liveSources();
|
|
483
|
+
// The list first, so the UI knows which database the snapshots that follow belong to.
|
|
484
|
+
void session.rpc.$callEvent('powersync:sources-changed', sourceInfos());
|
|
485
|
+
const source = sourceId ? live.find((candidate) => candidate.id === sourceId) : live[0];
|
|
486
|
+
if (!source) return;
|
|
487
|
+
for (const event of source.snapshots.values()) {
|
|
488
|
+
pushEvent(session, source.id, event);
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
})
|
|
492
|
+
);
|
|
493
|
+
ps.rpc.register(
|
|
494
|
+
defineRpcFunction({
|
|
495
|
+
name: 'unobserve',
|
|
496
|
+
type: 'action',
|
|
497
|
+
jsonSerializable: true,
|
|
498
|
+
handler: () => {
|
|
499
|
+
observers.delete(currentSession().meta.id);
|
|
500
|
+
}
|
|
501
|
+
})
|
|
502
|
+
);
|
|
503
|
+
}
|
|
504
|
+
});
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
// The PowerSync devframe definition and the node-side registry of served databases.
|
|
2
|
+
// Hosts mount it: `./vite` (Vite DevTools dock) and `./node` (a node app's dev server).
|
|
3
|
+
import './rpc-types.js';
|
|
4
|
+
|
|
5
|
+
export { definition, registerIntegration, setSetupSdks, uiDistDir } from './definition.js';
|
|
6
|
+
export type { SetupSdk, SourceInfo } from './rpc-types.js';
|
|
7
|
+
export { UI_ROUTE, DEVFRAME_ID } from './constants.js';
|