Skip to content
Merged
Show file tree
Hide file tree
Changes from 37 commits
Commits
Show all changes
42 commits
Select commit Hold shift + click to select a range
ef1740c
Add Node.js support
spinda Jan 12, 2025
3143158
Merge branch 'node' of github.com:spinda/powersync-js into node
simolus3 Mar 3, 2025
5923f6f
Override better-sqlite3 globally
simolus3 Mar 3, 2025
7c0c6c7
Load core extension in node demo
simolus3 Mar 3, 2025
afd62ab
Reformat example
simolus3 Mar 3, 2025
b287b4f
Test watching queries and uploads
simolus3 Mar 3, 2025
1064c65
Add tests to node package
simolus3 Mar 4, 2025
ed94f24
Add vitest workspace configuration
simolus3 Mar 4, 2025
3e1d9fd
Merge branch 'chore/vitest-workspace' into node
simolus3 Mar 4, 2025
1b334f9
Complete simple nodejs tests
simolus3 Mar 4, 2025
aedf8a9
Split implementation into more files
simolus3 Mar 5, 2025
7873694
Reduce API surface
simolus3 Mar 5, 2025
6cbc405
Ignore exceptions during rollback
simolus3 Mar 5, 2025
6c4b958
Remove better-sqlite dependency from demo
simolus3 Mar 5, 2025
073b28a
Node: Add readme
simolus3 Mar 5, 2025
30bec88
Update lockfile
simolus3 Mar 5, 2025
1e6b1d1
Remove toComlink with cast
simolus3 Mar 5, 2025
3f679b6
FIx worker URL
simolus3 Mar 5, 2025
23490e6
Rename demo script to start
simolus3 Mar 5, 2025
12c6649
Add changeset for node package
simolus3 Mar 5, 2025
a6e697b
Update readme in demo project
simolus3 Mar 5, 2025
d5a856a
Update other readmes
simolus3 Mar 5, 2025
02412a4
readme typo
simolus3 Mar 5, 2025
648202e
Disable tests for node package temporarily
simolus3 Mar 5, 2025
de0d0de
Use forked better-sqlite3
simolus3 Mar 7, 2025
1b1e805
Fix verdaccio config for better-sqlite3
simolus3 Mar 7, 2025
3b411f9
Merge remote-tracking branch 'origin/main' into node
simolus3 Mar 7, 2025
09768bb
Remove unused better-sqlite3 types
simolus3 Mar 7, 2025
447fcb8
Make things a bit clearer in the demo app Readme
benitav Mar 10, 2025
a03945a
More logs
simolus3 Mar 10, 2025
2dbda54
Apply throttle to node watch test
simolus3 Mar 10, 2025
d95a394
Skip watch test
simolus3 Mar 10, 2025
a5a5650
Merge remote-tracking branch 'origin/main' into node
simolus3 Mar 10, 2025
b941ac8
Use zero version for future changeset bump
simolus3 Mar 10, 2025
8de293f
Support uploads in node demo
simolus3 Mar 11, 2025
b247cb2
Use uuid for generated owner
simolus3 Mar 12, 2025
e5a57a5
Include node in docs build
simolus3 Mar 12, 2025
2b0f13a
NodeJS -> Node.js
benitav Mar 13, 2025
2d0e1ef
casing
benitav Mar 13, 2025
895983b
Also rename to Node.js in top-level readme
simolus3 Mar 12, 2025
3e3a287
Add thanks section to node readme
simolus3 Mar 13, 2025
87179ff
Merge remote-tracking branch 'origin/main' into node
simolus3 Mar 13, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/serious-rice-buy.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@powersync/node': minor
---

Initial version
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ _[PowerSync](https://www.powersync.com) is a sync engine for building local-firs

- JS Web SDK implementation (extension of `packages/common`)

- [packages/node](./packages/node/README.md)

- NodeJS client implementation (extension of `packages/common`)

- [packages/react](./packages/react/README.md)

- React integration for PowerSync.
Expand Down Expand Up @@ -80,6 +84,10 @@ Demo applications are located in the [`demos/`](./demos/) directory. Also see ou

- [demos/example-capacitor](./demos/example-capacitor/README.md) A Capacitor example app using the PowerSync Web SDK.

### Node

- [demos/example-node](./demos/example-node/README.md) A small CLI example built using the PowerSync SDK for NodeJS.

## Tools

- [tools/diagnostics-app](./tools/diagnostics-app): A standalone web app that presents stats about a user's local database (incl. tables and sync buckets).
Expand Down
2 changes: 2 additions & 0 deletions demos/example-node/.env
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
BACKEND=http://localhost:6060
SYNC_SERVICE=http://localhost:8080
16 changes: 16 additions & 0 deletions demos/example-node/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
## NodeJS Demo

This demonstrates a small NodeJS client opening a database and connecting PowerSync.

This demo is configured to talk to an example backend [you can host yourself](https://github.com/powersync-ja/self-host-demo). To get started:

1. Start one of the Node.js backend examples from [the self-host-demo repository](https://github.com/powersync-ja/self-host-demo).
2. If necessary, change `.env` to point to the started backend and sync service.
3. Run `pnpm install` and `pnpm build:packages` in the root of this repo.
4. In this directory, run `pnpm run start`.

This opens the local database, connects to PowerSync, waits for a first sync and then runs a simple query.
Results from the query are printed every time it changes. Try:

1. Updating a row in the backend database and see changes reflected in the running client.
2. Enter `add('my list')` and see the new list show up in the backend database.
20 changes: 20 additions & 0 deletions demos/example-node/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{
"name": "example-node",
"version": "1.0.0",
"description": "",
"type": "module",
"private": true,
"scripts": {
"build": "tsc -b",
"watch": "tsc -b -w",
"start": "node --loader ts-node/esm -r dotenv/config src/main.ts"
},
"dependencies": {
"@powersync/node": "workspace:*",
"dotenv": "^16.4.7"
},
"devDependencies": {
"ts-node": "^10.9.2",
"typescript": "^5.8.2"
}
}
65 changes: 65 additions & 0 deletions demos/example-node/src/main.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import repl_factory from 'node:repl';
import { once } from 'node:events';

import { PowerSyncDatabase, SyncStreamConnectionMethod } from '@powersync/node';
import Logger from 'js-logger';
import { AppSchema, DemoConnector } from './powersync.js';
import { exit } from 'node:process';

const main = async () => {
Logger.useDefaults({ defaultLevel: Logger.WARN });

if (!('BACKEND' in process.env) || !('SYNC_SERVICE' in process.env)) {
console.warn(
'Set the BACKEND and SYNC_SERVICE environment variables to point to a sync service and a running demo backend.'
);
return;
}

const db = new PowerSyncDatabase({
schema: AppSchema,
database: {
dbFilename: 'test.db'
},
logger: Logger
});
console.log(await db.get('SELECT powersync_rs_version();'));

await db.connect(new DemoConnector(), { connectionMethod: SyncStreamConnectionMethod.HTTP });
await db.waitForFirstSync();
console.log('First sync complete!');

let hasFirstRow: ((value: any) => void) | null = null;
const firstRow = new Promise((resolve) => (hasFirstRow = resolve));
const watchLists = async () => {
for await (const rows of db.watch('SELECT * FROM lists')) {
if (hasFirstRow) {
hasFirstRow(null);
hasFirstRow = null;
}
console.log('Has todo lists', rows.rows?._array);
}
};

watchLists();
await firstRow;

console.log('Connected to PowerSync. Try updating the lists in the database and see it reflected here.');
console.log("To upload a list here, enter `await add('name of new list');`");

const repl = repl_factory.start();
repl.context.add = async (name: string) => {
await db.execute(
"INSERT INTO lists (id, created_at, name, owner_id) VALUEs (uuid(), datetime('now'), ?, uuid());",
[name]
);
};

await once(repl, 'exit');
console.log('shutting down');
await db.disconnect();
await db.close();
exit(0);
};

await main();
77 changes: 77 additions & 0 deletions demos/example-node/src/powersync.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import { AbstractPowerSyncDatabase, column, PowerSyncBackendConnector, Schema, Table } from '@powersync/node';

export class DemoConnector implements PowerSyncBackendConnector {
async fetchCredentials() {
const response = await fetch(`${process.env.BACKEND}/api/auth/token`);
if (response.status != 200) {
throw 'Could not fetch token';
}

const { token } = await response.json();

return {
endpoint: process.env.SYNC_SERVICE!,
token: token
};
}

async uploadData(database: AbstractPowerSyncDatabase) {
const batch = await database.getCrudBatch();
if (batch == null) {
return;
}

const entries: any[] = [];
for (const op of batch.crud) {
entries.push({
table: op.table,
op: op.op,
id: op.id,
data: op.opData
});
}

const response = await fetch(`${process.env.BACKEND}/api/data/`, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({batch: entries}),
});
if (response.status !== 200) {
throw new Error(`Server returned HTTP ${response.status}: ${await response.text()}`);
}

await batch?.complete();
}
}

export const LIST_TABLE = 'lists';
export const TODO_TABLE = 'todos';

const todos = new Table(
{
list_id: column.text,
created_at: column.text,
completed_at: column.text,
description: column.text,
created_by: column.text,
completed_by: column.text,
completed: column.integer,
photo_id: column.text
},
{ indexes: { list: ['list_id'] } }
);

const lists = new Table({
created_at: column.text,
name: column.text,
owner_id: column.text
});

export const AppSchema = new Schema({
lists,
todos
});

export type Database = (typeof AppSchema)['types'];
export type TodoRecord = Database['todos'];
export type ListRecord = Database['lists'];
14 changes: 14 additions & 0 deletions demos/example-node/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"extends": "../../tsconfig.base",
"compilerOptions": {
"baseUrl": ".",
"rootDir": "src",
"outDir": "lib",
"strictNullChecks": true
},
"references": [
{
"path": "../../packages/node"
}
]
}
12 changes: 10 additions & 2 deletions docs/utils/packageMap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ enum Packages {
VueSdk = 'vue-sdk',
AttachmentsSdk = 'attachments-sdk',
WebSdk = 'web-sdk',
TanstackReactQuerySdk = 'tanstack-react-query-sdk'
TanstackReactQuerySdk = 'tanstack-react-query-sdk',
NodeSdk = 'node-sdk',
}

interface Package {
Expand Down Expand Up @@ -63,5 +64,12 @@ export const packageMap: PackageMap = {
entryPoints: ['../packages/attachments/src/index.ts'],
tsconfig: '../packages/attachments/tsconfig.json',
id: Packages.AttachmentsSdk
}
},
[Packages.NodeSdk]: {
name: 'Node SDK',
dirName: Packages.NodeSdk,
entryPoints: ['../packages/node/src/index.ts'],
tsconfig: '../packages/node/tsconfig.json',
id: Packages.NodeSdk
},
};
1 change: 1 addition & 0 deletions packages/node/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# @powersync/node
Loading