@powersync/diagnostics 0.0.2 → 0.1.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.
Files changed (54) hide show
  1. package/README.md +71 -4
  2. package/dist/devtools/assets/powersync-B1PBHXj2.js +184 -0
  3. package/dist/devtools/assets/powersync-CpTiA65L.css +1 -0
  4. package/dist/devtools/powersync.html +24 -0
  5. package/dist/rozenite.json +14 -0
  6. package/lib/src/agent-server.d.ts +21 -0
  7. package/lib/src/agent-server.js +51 -0
  8. package/lib/src/agent-server.js.map +1 -0
  9. package/lib/src/agent.d.ts +8 -19
  10. package/lib/src/agent.js +39 -59
  11. package/lib/src/agent.js.map +1 -1
  12. package/lib/src/client.js +5 -4
  13. package/lib/src/client.js.map +1 -1
  14. package/lib/src/definition.js +11 -17
  15. package/lib/src/definition.js.map +1 -1
  16. package/lib/src/js-agent.d.ts +6 -13
  17. package/lib/src/js-agent.js +18 -9
  18. package/lib/src/js-agent.js.map +1 -1
  19. package/lib/src/node.d.ts +1 -1
  20. package/lib/src/node.js +2 -2
  21. package/lib/src/node.js.map +1 -1
  22. package/lib/src/page.js +2 -3
  23. package/lib/src/page.js.map +1 -1
  24. package/lib/src/react-native/agent-tools.d.ts +3 -0
  25. package/lib/src/react-native/agent-tools.js +137 -0
  26. package/lib/src/react-native/agent-tools.js.map +1 -0
  27. package/lib/src/react-native/protocol.d.ts +22 -0
  28. package/lib/src/react-native/protocol.js +5 -0
  29. package/lib/src/react-native/protocol.js.map +1 -0
  30. package/lib/src/react-native/usePowerSyncDevTools.d.ts +7 -0
  31. package/lib/src/react-native/usePowerSyncDevTools.js +56 -0
  32. package/lib/src/react-native/usePowerSyncDevTools.js.map +1 -0
  33. package/lib/src/react-native.d.ts +7 -0
  34. package/lib/src/react-native.js +8 -0
  35. package/lib/src/react-native.js.map +1 -0
  36. package/lib/src/rpc-types.d.ts +1 -1
  37. package/lib/src/tools.d.ts +19 -0
  38. package/lib/src/tools.js +24 -0
  39. package/lib/src/tools.js.map +1 -0
  40. package/lib/tsconfig.tsbuildinfo +1 -1
  41. package/package.json +41 -13
  42. package/src/agent-server.ts +73 -0
  43. package/src/agent.ts +50 -82
  44. package/src/client.ts +5 -5
  45. package/src/definition.ts +11 -17
  46. package/src/js-agent.ts +28 -26
  47. package/src/node.ts +3 -3
  48. package/src/page.ts +2 -4
  49. package/src/react-native/agent-tools.ts +148 -0
  50. package/src/react-native/protocol.ts +33 -0
  51. package/src/react-native/usePowerSyncDevTools.ts +59 -0
  52. package/src/react-native.ts +14 -0
  53. package/src/rpc-types.ts +1 -1
  54. package/src/tools.ts +35 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@powersync/diagnostics",
3
- "version": "0.0.2",
3
+ "version": "0.1.0",
4
4
  "description": "PowerSync DevTools: a devframe definition that serves live PowerSync diagnostics as a Vite DevTools dock, a node dev server, and MCP tools.",
5
5
  "type": "module",
6
6
  "main": "lib/src/index.js",
@@ -29,11 +29,20 @@
29
29
  "./node": {
30
30
  "types": "./lib/src/node.d.ts",
31
31
  "default": "./lib/src/node.js"
32
+ },
33
+ "./agent": {
34
+ "types": "./lib/src/agent.d.ts",
35
+ "default": "./lib/src/agent.js"
36
+ },
37
+ "./react-native": {
38
+ "types": "./lib/src/react-native.d.ts",
39
+ "default": "./lib/src/react-native.js"
32
40
  }
33
41
  },
34
42
  "author": "PowerSync",
35
43
  "license": "Apache-2.0",
36
44
  "files": [
45
+ "dist",
37
46
  "lib",
38
47
  "src"
39
48
  ],
@@ -50,9 +59,12 @@
50
59
  },
51
60
  "homepage": "https://docs.powersync.com",
52
61
  "peerDependencies": {
53
- "@powersync/common": "^2.4.0",
54
- "@powersync/web": "^2.5.0",
62
+ "@powersync/common": "^2.5.0",
63
+ "@powersync/web": "^2.7.0",
64
+ "@rozenite/agent-bridge": "^2.5.0",
65
+ "@rozenite/plugin-bridge": "^2.5.0",
55
66
  "@vitejs/devtools-kit": ">=0.7.5",
67
+ "react": ">=18",
56
68
  "vite": ">=7.0.0"
57
69
  },
58
70
  "peerDependenciesMeta": {
@@ -62,6 +74,15 @@
62
74
  "@powersync/web": {
63
75
  "optional": true
64
76
  },
77
+ "@rozenite/agent-bridge": {
78
+ "optional": true
79
+ },
80
+ "@rozenite/plugin-bridge": {
81
+ "optional": true
82
+ },
83
+ "react": {
84
+ "optional": true
85
+ },
65
86
  "@vitejs/devtools-kit": {
66
87
  "optional": true
67
88
  },
@@ -70,25 +91,32 @@
70
91
  }
71
92
  },
72
93
  "dependencies": {
73
- "@devframes/agentic": "1.0.0",
74
- "devframe": "1.0.0",
94
+ "@devframes/agentic": "^1.2.6",
95
+ "devframe": "^1.2.6",
75
96
  "zod": "^4.6.5",
76
- "@powersync/diagnostics-ui": "0.0.2",
77
- "@powersync/diagnostics-core": "0.0.2"
97
+ "@powersync/diagnostics-core": "0.0.3",
98
+ "@powersync/diagnostics-ui": "0.0.4"
78
99
  },
79
100
  "devDependencies": {
80
- "@devframes/hub": "1.0.0",
101
+ "@devframes/hub": "^1.2.6",
102
+ "@rozenite/agent-bridge": "^2.5.0",
103
+ "@rozenite/plugin-bridge": "^2.5.0",
81
104
  "@types/node": "^24.0.0",
105
+ "@types/react": "19.2.14",
82
106
  "@vitejs/devtools-kit": "^0.7.5",
107
+ "react": "19.3.0",
83
108
  "typescript": "^6.0.3",
84
109
  "vite": "^7.3.6",
85
- "@powersync/common": "2.4.0",
86
- "@powersync/web": "2.5.0"
110
+ "vue": "3.5.43",
111
+ "@powersync/common": "2.5.0",
112
+ "@powersync/shared-internals": "1.6.0",
113
+ "@powersync/web": "2.7.0"
87
114
  },
88
115
  "scripts": {
89
- "build": "tsc -b",
90
- "build:prod": "tsc -b",
91
- "clean": "rm -rf lib tsconfig.tsbuildinfo",
116
+ "build": "tsc -b && pnpm build:rozenite",
117
+ "build:prod": "tsc -b && pnpm build:rozenite",
118
+ "build:rozenite": "tsc -p tsconfig.rozenite.json && vite build --config vite.rozenite.config.ts",
119
+ "clean": "rm -rf dist lib tsconfig.tsbuildinfo",
92
120
  "watch": "tsc --build -w"
93
121
  }
94
122
  }
@@ -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 CHANGED
@@ -1,31 +1,29 @@
1
1
  /**
2
- * Pieces shared by every JavaScript host: building the agent over a live database, and serving
3
- * agents to a devframe node side over an RPC client (a dock script in a web page, or a node process).
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.
4
5
  */
5
- import type { DevframeRpcClient } from 'devframe/client';
6
- import type { CommonPowerSyncDatabase, PowerSyncBackendConnector, SyncOptions } from '@powersync/common';
7
- import type {
6
+ import type { CommonPowerSyncDatabase } from '@powersync/common';
7
+ import type { CoreDiagnosticsEvent, SdkIntegration, Unsubscribe } from '@powersync/diagnostics-core';
8
+ import { JsAgent, type CoreEventSource } from './js-agent.js';
9
+ import type { BasePowerSyncDatabase } from '@powersync/shared-internals';
10
+
11
+ // The iframe hand-off and the protocol types an embedding host needs, so the host never imports the protocol package.
12
+ export { attachIframe } from '@powersync/diagnostics-core';
13
+ export type {
8
14
  ActionRequest,
9
- CoreDiagnosticsEvent,
15
+ AttachIframeOptions,
10
16
  DiagnosticsEvent,
11
- QueryParams,
12
17
  SdkIntegration,
13
- Unsubscribe
18
+ SyncState
14
19
  } from '@powersync/diagnostics-core';
15
- import { HEARTBEAT_MS } from './constants.js';
16
- import { JsAgent, type CoreEventSource } from './js-agent.js';
17
- import './rpc-types.js';
18
20
 
19
21
  /** The sync client broadcasts core diagnostics events on this channel (see `emitDiagnostics`). */
20
22
  const CORE_EVENTS_CHANNEL = 'powersync-diagnostics-events';
21
23
 
22
- /**
23
- * The connection accessors every SDK's database class has. They are not on the public
24
- * `CommonPowerSyncDatabase` interface, so the agent reads them through this internal view.
25
- */
26
- interface DiagnosableDatabase extends CommonPowerSyncDatabase {
27
- readonly connector: PowerSyncBackendConnector | null | undefined;
28
- readonly connectionOptions: SyncOptions | null | undefined;
24
+ /** The SDK label for the database, or `fallback` on SDK releases that do not report it. */
25
+ export function databaseSdk(database: CommonPowerSyncDatabase, fallback: string): string {
26
+ return (database as Partial<BasePowerSyncDatabase>).sdkName ?? fallback;
29
27
  }
30
28
 
31
29
  /** Consumes the core diagnostics events the sync client broadcasts (from a worker or in-process). */
@@ -43,74 +41,44 @@ class BroadcastCoreEvents implements CoreEventSource {
43
41
  }
44
42
  }
45
43
 
46
- /** Builds the JavaScript integration over a live database. */
47
- export function createIntegration(database: CommonPowerSyncDatabase, sdk: string): SdkIntegration {
48
- const db = database as DiagnosableDatabase;
49
- return new JsAgent(db, {
50
- sdk,
51
- coreEvents: typeof BroadcastChannel === 'function' ? new BroadcastCoreEvents() : undefined,
52
- connection: {
53
- getConnector: () => db.connector ?? null,
54
- getConnectionOptions: () => db.connectionOptions ?? null
55
- }
56
- });
44
+ /** A database that hands core diagnostics events to listeners directly (React Native). */
45
+ interface DiagnosticsListenerDatabase {
46
+ registerDiagnosticsListener(listener: (event: CoreDiagnosticsEvent) => void): () => void;
57
47
  }
58
48
 
59
- /** Serves integrations to the node side over one RPC client. */
60
- export interface AgentServer {
61
- /** Announces `integration` as `sourceId` and starts forwarding its events. */
62
- serve(sourceId: string, integration: SdkIntegration, sdk: string): Promise<void>;
63
- /** Withdraws a served integration. */
64
- release(sourceId: string): Promise<void>;
65
- /** Releases everything served through this client. */
66
- close(): Promise<void>;
49
+ function hasDiagnosticsListener(database: object): database is DiagnosticsListenerDatabase {
50
+ return typeof (database as Partial<DiagnosticsListenerDatabase>).registerDiagnosticsListener === 'function';
67
51
  }
68
52
 
69
- /**
70
- * Registers the page-side functions the node side calls (`powersync:page-*`) on `rpc`, and returns
71
- * a server that announces integrations to it. Call once per RPC client.
72
- */
73
- export function createAgentServer(rpc: DevframeRpcClient): AgentServer {
74
- const served = new Map<string, { integration: SdkIntegration; stop: Unsubscribe }>();
75
- // The node side only knows this client is alive while it hears from it.
76
- const heartbeat = setInterval(() => {
77
- for (const sourceId of served.keys()) void rpc.callEvent('powersync:page-heartbeat', sourceId);
78
- }, HEARTBEAT_MS);
79
- (heartbeat as { unref?: () => void }).unref?.();
53
+ /** Consumes the core diagnostics events a database hands to its listeners. */
54
+ class ListenerCoreEvents implements CoreEventSource {
55
+ private removers = new Set<Unsubscribe>();
56
+
57
+ constructor(private readonly database: DiagnosticsListenerDatabase) {}
80
58
 
81
- const integrationFor = (sourceId: string): SdkIntegration => {
82
- const entry = served.get(sourceId);
83
- if (!entry) throw new Error(`No database "${sourceId}" is served here.`);
84
- return entry.integration;
85
- };
86
- const register = (name: string, handler: (...args: any[]) => unknown) =>
87
- rpc.client.register({ name, type: 'action', jsonSerializable: true, handler }, true);
88
- register('powersync:page-query', (id: string, params: QueryParams) => integrationFor(id).runQuery(params));
89
- register('powersync:page-schema', (id: string) => integrationFor(id).getSchema());
90
- register('powersync:page-info', (id: string) => integrationFor(id).getInfo());
91
- register('powersync:page-action', (id: string, request: ActionRequest) => integrationFor(id).action(request));
59
+ onEvent(handler: (event: CoreDiagnosticsEvent) => void): Unsubscribe {
60
+ const remove = this.database.registerDiagnosticsListener(handler);
61
+ this.removers.add(remove);
62
+ return () => {
63
+ this.removers.delete(remove);
64
+ remove();
65
+ };
66
+ }
92
67
 
93
- return {
94
- async serve(sourceId, integration, sdk) {
95
- await rpc.call('powersync:page-register', sourceId, sdk);
96
- const stop = await integration.observeEvents((event: DiagnosticsEvent) => {
97
- void rpc.callEvent('powersync:page-event', sourceId, event);
98
- });
99
- served.set(sourceId, { integration, stop });
100
- },
101
- async release(sourceId) {
102
- const entry = served.get(sourceId);
103
- if (!entry) return;
104
- served.delete(sourceId);
105
- entry.stop();
106
- await entry.integration.close();
107
- await rpc.call('powersync:page-unregister', sourceId).catch(() => {});
108
- },
109
- async close() {
110
- clearInterval(heartbeat);
111
- for (const sourceId of [...served.keys()]) {
112
- await this.release(sourceId);
113
- }
114
- }
115
- };
68
+ dispose(): void {
69
+ for (const remove of this.removers) remove();
70
+ this.removers.clear();
71
+ }
72
+ }
73
+
74
+ function coreEventSource(database: object): CoreEventSource | undefined {
75
+ if (hasDiagnosticsListener(database)) return new ListenerCoreEvents(database);
76
+ if (typeof BroadcastChannel === 'function') return new BroadcastCoreEvents();
77
+ return undefined;
78
+ }
79
+
80
+ /** Builds the JavaScript integration over a live database. The agent reads the connection from the database itself. */
81
+ export function createIntegration(database: CommonPowerSyncDatabase, sdk: string): SdkIntegration {
82
+ const db = database as BasePowerSyncDatabase;
83
+ return new JsAgent(db, { sdk, coreEvents: coreEventSource(db) });
116
84
  }
package/src/client.ts CHANGED
@@ -5,9 +5,8 @@
5
5
  */
6
6
  import type { DockClientScriptContext } from '@devframes/hub/client';
7
7
  import { observeRegisteredDatabases } from '@powersync/web/devtools';
8
- import { createAgentServer, createIntegration } from './agent.js';
9
-
10
- const SDK = '@powersync/web';
8
+ import { createIntegration, databaseSdk } from './agent.js';
9
+ import { createAgentServer } from './agent-server.js';
11
10
 
12
11
  export default function setup(context: DockClientScriptContext): void {
13
12
  const server = createAgentServer(context.rpc);
@@ -30,7 +29,8 @@ export default function setup(context: DockClientScriptContext): void {
30
29
  return;
31
30
  }
32
31
  if (currentId) return;
33
- currentId = `web-${++counter}`;
34
- void server.serve(currentId, createIntegration(database, SDK), SDK);
32
+ const sdk = databaseSdk(database, '@powersync/web');
33
+ currentId = `${sdk.replace(/^@powersync\//, '')}-${++counter}`;
34
+ void server.serve(currentId, createIntegration(database, sdk), sdk);
35
35
  });
36
36
  }
package/src/definition.ts CHANGED
@@ -25,6 +25,7 @@ import type {
25
25
  } from '@powersync/diagnostics-core';
26
26
  import { DEVFRAME_ID, HEARTBEAT_MS, UI_ROUTE } from './constants.js';
27
27
  import type { SetupSdk, SourceInfo } from './rpc-types.js';
28
+ import { ACTION_NAMES, ARGUMENT_DESCRIPTIONS, TOOL_DESCRIPTIONS } from './tools.js';
28
29
 
29
30
  export type { SetupSdk, SourceInfo } from './rpc-types.js';
30
31
 
@@ -250,20 +251,13 @@ const sourceIdArg = z
250
251
  .describe('Id of the attached database, from powersync_sources. Null for the first one.');
251
252
  const queryParamsArg = z
252
253
  .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.')
254
+ sql: z.string().describe(ARGUMENT_DESCRIPTIONS.sql),
255
+ params: z.array(z.unknown()).optional().describe(ARGUMENT_DESCRIPTIONS.params)
255
256
  })
256
257
  .describe('The query.');
257
258
  const actionRequestArg = z
258
259
  .object({
259
- action: z.enum([
260
- 'reconnect',
261
- 'disconnect',
262
- 'clearData',
263
- 'requestCheckpoint',
264
- 'subscribeStream',
265
- 'unsubscribeStream'
266
- ]),
260
+ action: z.enum(ACTION_NAMES),
267
261
  args: z
268
262
  .object({
269
263
  name: z.string(),
@@ -272,7 +266,7 @@ const actionRequestArg = z
272
266
  priority: z.union([z.literal(0), z.literal(1), z.literal(2), z.literal(3)]).optional()
273
267
  })
274
268
  .optional()
275
- .describe('Stream name and options, for the stream actions only.')
269
+ .describe(ARGUMENT_DESCRIPTIONS.actionArgs)
276
270
  })
277
271
  .describe('The action to run.');
278
272
  const anyResult = z.unknown();
@@ -391,7 +385,7 @@ export const definition = defineDevframe({
391
385
  returns: anyResult,
392
386
  agent: {
393
387
  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.',
388
+ `${TOOL_DESCRIPTIONS.query} Arguments: arg0 = { sql, params? }, arg1 = database id or null for the first one.`,
395
389
  safety: 'action'
396
390
  },
397
391
  handler: (params, sourceId) => pickSource(sourceId).integration.runQuery(params as QueryParams)
@@ -406,7 +400,7 @@ export const definition = defineDevframe({
406
400
  returns: anyResult,
407
401
  agent: {
408
402
  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.'
403
+ `${TOOL_DESCRIPTIONS.schema} Argument: arg0 = database id or null for the first one.`
410
404
  },
411
405
  handler: (sourceId) => pickSource(sourceId).integration.getSchema()
412
406
  })
@@ -420,7 +414,7 @@ export const definition = defineDevframe({
420
414
  returns: anyResult,
421
415
  agent: {
422
416
  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.'
417
+ `${TOOL_DESCRIPTIONS.info} Argument: arg0 = database id or null for the first one.`
424
418
  },
425
419
  handler: (sourceId) => pickSource(sourceId).integration.getInfo()
426
420
  })
@@ -434,7 +428,7 @@ export const definition = defineDevframe({
434
428
  returns: anyResult,
435
429
  agent: {
436
430
  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.'
431
+ `${TOOL_DESCRIPTIONS.status} Argument: arg0 = database id or null for the first one.`
438
432
  },
439
433
  handler: async (sourceId) => latestSnapshot(sourceId, 'status')
440
434
  })
@@ -448,7 +442,7 @@ export const definition = defineDevframe({
448
442
  returns: anyResult,
449
443
  agent: {
450
444
  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.'
445
+ `${TOOL_DESCRIPTIONS['upload-queue']} Argument: arg0 = database id or null for the first one.`
452
446
  },
453
447
  handler: async (sourceId) => latestSnapshot(sourceId, 'uploadQueue')
454
448
  })
@@ -462,7 +456,7 @@ export const definition = defineDevframe({
462
456
  returns: anyResult,
463
457
  agent: {
464
458
  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.',
459
+ `${TOOL_DESCRIPTIONS.action} Arguments: arg0 = { action, args? }, arg1 = database id or null for the first one.`,
466
460
  safety: 'destructive'
467
461
  },
468
462
  handler: (request, sourceId) => pickSource(sourceId).integration.action(request as ActionRequest)
package/src/js-agent.ts CHANGED
@@ -1,8 +1,6 @@
1
1
  import type {
2
- CommonPowerSyncDatabase,
3
2
  LogLevels,
4
3
  LogRecord as SdkLogRecord,
5
- PowerSyncBackendConnector,
6
4
  SyncOptions,
7
5
  SyncStatus,
8
6
  SyncStreamSubscription
@@ -19,11 +17,14 @@ import type {
19
17
  SchemaPayload,
20
18
  SdkIntegration,
21
19
  StreamActionArgs,
22
- SyncState,
23
20
  Unsubscribe,
24
21
  UploadQueueState
25
22
  } from '@powersync/diagnostics-core';
26
23
  import { toStreamStates, toSyncState } from './sync-state.js';
24
+ import type { BasePowerSyncDatabase, InternalConnector } from '@powersync/shared-internals';
25
+
26
+ /** SQL that only reads, so it can run on a read connection. */
27
+ const READ_STATEMENT = /^\s*(select|explain)\b/i;
27
28
 
28
29
  /** Delivers the SQLite core's diagnostics events to the agent. How they arrive is runtime-specific. */
29
30
  export interface CoreEventSource {
@@ -31,24 +32,15 @@ export interface CoreEventSource {
31
32
  dispose(): void;
32
33
  }
33
34
 
34
- /**
35
- * Read access to the live connection. The connector and options are not on the database's public
36
- * interface, so the code that installs the agent (which can see the concrete database) hands them in.
37
- */
38
- export interface ConnectionAccess {
39
- getConnector(): PowerSyncBackendConnector | null;
40
- getConnectionOptions(): SyncOptions | null;
41
- }
42
-
43
35
  export interface JsAgentOptions {
44
36
  /** A label for the SDK behind this agent, e.g. `@powersync/web`. */
45
37
  sdk?: string;
38
+ /** If known, the path to the database */
39
+ databasePath?: string;
46
40
  /** Debounce for re-reading bucket stats after internal-table changes. */
47
41
  bucketThrottleMs?: number;
48
42
  /** Core diagnostics events (per-bucket `target_count`). Omit when core diagnostics are off. */
49
43
  coreEvents?: CoreEventSource;
50
- /** Read access to the live connection; omit if the runtime cannot expose it. */
51
- connection?: ConnectionAccess;
52
44
  }
53
45
 
54
46
  /**
@@ -63,36 +55,42 @@ export class JsAgent implements SdkIntegration {
63
55
  /** Debug subscriptions created through `action`, keyed by name + params, so they can be released. */
64
56
  private streamHandles = new Map<string, SyncStreamSubscription>();
65
57
  // Retained so reconnect / clear work after a disconnect, when the connection no longer exposes them.
66
- private lastConnector: PowerSyncBackendConnector | null = null;
58
+ private lastConnector: InternalConnector | null = null;
67
59
  private lastConnectionOptions: SyncOptions | null = null;
68
60
  // Per-bucket total operation counts from the core diagnostics stream (not stored in ps_buckets).
69
61
  private bucketTargets = new Map<string, number>();
70
62
 
71
63
  constructor(
72
- private db: CommonPowerSyncDatabase,
64
+ private readonly db: BasePowerSyncDatabase,
73
65
  private options: JsAgentOptions = {}
74
66
  ) {}
75
67
 
76
68
  // --- SdkIntegration ---
77
69
 
78
70
  async runQuery({ sql, params }: QueryParams): Promise<QueryResult> {
79
- const records = await this.db.getAll<Record<string, unknown>>(sql, params);
71
+ const records = await this.queryRecords(sql, params);
80
72
  const columns = records.length > 0 ? Object.keys(records[0]) : [];
81
73
  return { columns, rows: records.map((record) => columns.map((column) => record[column])) };
82
74
  }
83
75
 
76
+ // Node and React Native open their read connections read-only, so only plain reads go to one.
77
+ // Everything else (INSERT, UPDATE, DELETE, WITH, PRAGMA, …) runs on the write connection.
78
+ private async queryRecords(sql: string, params?: unknown[]): Promise<Record<string, unknown>[]> {
79
+ if (READ_STATEMENT.test(sql)) return this.db.getAll<Record<string, unknown>>(sql, params);
80
+ const result = await this.db.execute(sql, params);
81
+ return (result.rows?._array ?? []) as Record<string, unknown>[];
82
+ }
83
+
84
84
  async getSchema(): Promise<SchemaPayload> {
85
85
  // The core payload: what the client already sends to `powersync_replace_schema`.
86
86
  return this.db.schema.toJSON() as SchemaPayload;
87
87
  }
88
88
 
89
89
  async getInfo(): Promise<ProtocolInfo> {
90
- const connection = this.options.connection;
91
-
92
90
  let endpoint: string | null = null;
93
91
  let token: string | null = null;
94
92
  try {
95
- const credentials = await connection?.getConnector()?.fetchCredentials();
93
+ const credentials = await this.db.connector?.fetchCredentials?.();
96
94
  endpoint = credentials?.endpoint ?? null;
97
95
  token = credentials?.token ?? null;
98
96
  } catch {
@@ -114,7 +112,7 @@ export class JsAgent implements SdkIntegration {
114
112
  // Non-fatal.
115
113
  }
116
114
 
117
- const connectionOptions = connection?.getConnectionOptions() ?? null;
115
+ const connectionOptions = this.db.connectionOptions ?? null;
118
116
  return {
119
117
  endpoint,
120
118
  token,
@@ -123,7 +121,8 @@ export class JsAgent implements SdkIntegration {
123
121
  params: connectionOptions?.params ?? null,
124
122
  connected: this.db.currentStatus?.connected ?? false,
125
123
  sqliteCoreVersion,
126
- sdk: this.options.sdk ?? null
124
+ sdk: this.options.sdk ?? null,
125
+ databasePath: this.options.databasePath ?? null
127
126
  };
128
127
  }
129
128
 
@@ -345,17 +344,20 @@ export class JsAgent implements SdkIntegration {
345
344
  }
346
345
 
347
346
  private captureConnection(): void {
348
- const connection = this.options.connection;
349
- const connector = connection?.getConnector() ?? null;
347
+ const connector = this.db.connector ?? null;
350
348
  if (connector) {
351
349
  this.lastConnector = connector;
352
- this.lastConnectionOptions = connection?.getConnectionOptions() ?? null;
350
+ this.lastConnectionOptions = this.db.connectionOptions ?? null;
353
351
  }
354
352
  }
355
353
 
356
354
  private async reconnect(): Promise<void> {
357
355
  if (this.lastConnector) {
358
- await this.db.connect(this.lastConnector, this.lastConnectionOptions ?? undefined);
356
+ await this.db.connectionManager.connect(
357
+ this.lastConnector,
358
+ this.lastConnectionOptions ?? {},
359
+ this.db.schema.toJSON()
360
+ );
359
361
  }
360
362
  }
361
363
  }
package/src/node.ts CHANGED
@@ -6,7 +6,7 @@ import type { McpSetting } from 'devframe';
6
6
  import { createDevServer } from 'devframe/adapters/dev';
7
7
  import { buildOtpAuthUrl } from 'devframe/node/auth';
8
8
  import type { CommonPowerSyncDatabase } from '@powersync/common';
9
- import { createIntegration } from './agent.js';
9
+ import { createIntegration, databaseSdk } from './agent.js';
10
10
  import { definition, registerIntegration, setSetupSdks } from './definition.js';
11
11
 
12
12
  export interface EnableDiagnosticsOptions {
@@ -24,7 +24,7 @@ export interface EnableDiagnosticsOptions {
24
24
  auth?: boolean;
25
25
  /** Open the browser once the server is up. @default false */
26
26
  open?: boolean;
27
- /** A label for the SDK, shown in the UI. @default '@powersync/node' */
27
+ /** A label for the SDK, shown in the UI. @default the database's SDK name */
28
28
  sdk?: string;
29
29
  /** The source id shown in the UI. @default 'node-1' */
30
30
  id?: string;
@@ -67,7 +67,7 @@ export async function enablePowerSyncDiagnostics(
67
67
  db: CommonPowerSyncDatabase,
68
68
  options: EnableDiagnosticsOptions = {}
69
69
  ): Promise<DiagnosticsServer> {
70
- const sdk = options.sdk ?? '@powersync/node';
70
+ const sdk = options.sdk ?? databaseSdk(db, '@powersync/node');
71
71
  const detach = await registerIntegration(options.id ?? 'node-1', createIntegration(db, sdk), sdk);
72
72
  setSetupSdks(['node']);
73
73
  const auth = options.auth ?? true;
package/src/page.ts CHANGED
@@ -11,9 +11,7 @@ import {
11
11
  type SdkIntegration
12
12
  } from '@powersync/diagnostics-core';
13
13
  import { observeRegisteredDatabases } from '@powersync/web/devtools';
14
- import { createIntegration } from './agent.js';
15
-
16
- const SDK = '@powersync/web';
14
+ import { createIntegration, databaseSdk } from './agent.js';
17
15
 
18
16
  /**
19
17
  * Serves the app's first live database to any iframe that asks. Call once per page.
@@ -29,7 +27,7 @@ export function serveDiagnostics(): () => void {
29
27
  for (const stop of stops) stop();
30
28
  stops.clear();
31
29
  void integration?.close();
32
- integration = next ? createIntegration(next, SDK) : null;
30
+ integration = next ? createIntegration(next, databaseSdk(next, '@powersync/web')) : null;
33
31
  });
34
32
 
35
33
  const onMessage = (event: MessageEvent) => {