Skip to content

Open-source and local-first Slack and Notion alternative that puts you in control of your data

Consolidate entries and messages into 'nodes'

Hakan Shehuc82fbedefad7
diff --git a/apps/desktop/src/main/databases/workspace/migrations/00001-create-users-table.ts b/apps/desktop/src/main/databases/workspace/migrations/00001-create-users-table.ts
index 156579dd..2b485cae 100644
--- a/apps/desktop/src/main/databases/workspace/migrations/00001-create-users-table.ts
+++ b/apps/desktop/src/main/databases/workspace/migrations/00001-create-users-table.ts
@@ -5,6 +5,7 @@ export const createUsersTable: Migration = {
await db.schema
.createTable('users')
.addColumn('id', 'text', (col) => col.primaryKey().notNull())
+ .addColumn('revision', 'integer', (col) => col.notNull())
.addColumn('email', 'text', (col) => col.notNull())
.addColumn('name', 'text', (col) => col.notNull())
.addColumn('avatar', 'text')
@@ -14,7 +15,6 @@ export const createUsersTable: Migration = {
.addColumn('status', 'integer', (col) => col.notNull())
.addColumn('created_at', 'text', (col) => col.notNull())
.addColumn('updated_at', 'text')
- .addColumn('version', 'integer')
.execute();
},
down: async (db) => {
diff --git a/apps/desktop/src/main/databases/workspace/migrations/00002-create-entries-table.ts b/apps/desktop/src/main/databases/workspace/migrations/00002-create-nodes-table.ts
similarity index 74%
rename from apps/desktop/src/main/databases/workspace/migrations/00002-create-entries-table.ts
rename to apps/desktop/src/main/databases/workspace/migrations/00002-create-nodes-table.ts
index d9dd1943..1f10d375 100644
--- a/apps/desktop/src/main/databases/workspace/migrations/00002-create-entries-table.ts
+++ b/apps/desktop/src/main/databases/workspace/migrations/00002-create-nodes-table.ts
@@ -1,9 +1,9 @@
import { Migration, sql } from 'kysely';
-export const createEntriesTable: Migration = {
+export const createNodesTable: Migration = {
up: async (db) => {
await db.schema
- .createTable('entries')
+ .createTable('nodes')
.addColumn('id', 'text', (col) => col.primaryKey().notNull())
.addColumn('type', 'text', (col) =>
col
@@ -17,21 +17,22 @@ export const createEntriesTable: Migration = {
.stored()
)
.addColumn('root_id', 'text', (col) => col.notNull())
+ .addColumn('local_revision', 'integer', (col) => col.notNull())
+ .addColumn('server_revision', 'integer', (col) => col.notNull())
.addColumn('attributes', 'text', (col) => col.notNull())
.addColumn('created_at', 'text', (col) => col.notNull())
.addColumn('updated_at', 'text')
.addColumn('created_by', 'text', (col) => col.notNull())
.addColumn('updated_by', 'text')
- .addColumn('transaction_id', 'text', (col) => col.notNull())
.execute();
await db.schema
- .createIndex('entries_parent_id_type_index')
- .on('entries')
+ .createIndex('nodes_parent_id_type_index')
+ .on('nodes')
.columns(['parent_id', 'type'])
.execute();
},
down: async (db) => {
- await db.schema.dropTable('entries').execute();
+ await db.schema.dropTable('nodes').execute();
},
};
diff --git a/apps/desktop/src/main/databases/workspace/migrations/00003-create-entry-transactions-table.ts b/apps/desktop/src/main/databases/workspace/migrations/00003-create-entry-transactions-table.ts
deleted file mode 100644
index 4058cbea..00000000
--- a/apps/desktop/src/main/databases/workspace/migrations/00003-create-entry-transactions-table.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-import { Migration } from 'kysely';
-
-export const createEntryTransactionsTable: Migration = {
- up: async (db) => {
- await db.schema
- .createTable('entry_transactions')
- .addColumn('id', 'text', (col) => col.notNull().primaryKey())
- .addColumn('entry_id', 'text', (col) => col.notNull())
- .addColumn('root_id', 'text', (col) => col.notNull())
- .addColumn('operation', 'integer', (col) => col.notNull())
- .addColumn('data', 'blob')
- .addColumn('created_at', 'text', (col) => col.notNull())
- .addColumn('created_by', 'text', (col) => col.notNull())
- .addColumn('server_created_at', 'text')
- .addColumn('version', 'integer', (col) => col.notNull())
- .execute();
- },
- down: async (db) => {
- await db.schema.dropTable('entry_transactions').execute();
- },
-};
diff --git a/apps/desktop/src/main/databases/workspace/migrations/00003-create-node-states-table.ts b/apps/desktop/src/main/databases/workspace/migrations/00003-create-node-states-table.ts
new file mode 100644
index 00000000..4694c44d
--- /dev/null
+++ b/apps/desktop/src/main/databases/workspace/migrations/00003-create-node-states-table.ts
@@ -0,0 +1,17 @@
+import { Migration } from 'kysely';
+
+export const createNodeStatesTable: Migration = {
+ up: async (db) => {
+ await db.schema
+ .createTable('node_states')
+ .addColumn('id', 'text', (col) =>
+ col.notNull().primaryKey().references('nodes.id').onDelete('cascade')
+ )
+ .addColumn('state', 'blob', (col) => col.notNull())
+ .addColumn('revision', 'integer', (col) => col.notNull())
+ .execute();
+ },
+ down: async (db) => {
+ await db.schema.dropTable('node_states').execute();
+ },
+};
diff --git a/apps/desktop/src/main/databases/workspace/migrations/00004-create-node-transactions-table.ts b/apps/desktop/src/main/databases/workspace/migrations/00004-create-node-transactions-table.ts
new file mode 100644
index 00000000..14ace5df
--- /dev/null
+++ b/apps/desktop/src/main/databases/workspace/migrations/00004-create-node-transactions-table.ts
@@ -0,0 +1,19 @@
+import { Migration } from 'kysely';
+
+export const createNodeTransactionsTable: Migration = {
+ up: async (db) => {
+ await db.schema
+ .createTable('node_transactions')
+ .addColumn('id', 'text', (col) => col.notNull().primaryKey())
+ .addColumn('node_id', 'text', (col) =>
+ col.notNull().references('nodes.id').onDelete('cascade')
+ )
+ .addColumn('operation', 'integer', (col) => col.notNull())
+ .addColumn('data', 'blob', (col) => col.notNull())
+ .addColumn('created_at', 'text', (col) => col.notNull())
+ .execute();
+ },
+ down: async (db) => {
+ await db.schema.dropTable('node_transactions').execute();
+ },
+};
diff --git a/apps/desktop/src/main/databases/workspace/migrations/00004-create-entry-interactions-table.ts b/apps/desktop/src/main/databases/workspace/migrations/00005-create-node-interactions-table.ts
similarity index 63%
rename from apps/desktop/src/main/databases/workspace/migrations/00004-create-entry-interactions-table.ts
rename to apps/desktop/src/main/databases/workspace/migrations/00005-create-node-interactions-table.ts
index 0781ae5d..13ff76cc 100644
--- a/apps/desktop/src/main/databases/workspace/migrations/00004-create-entry-interactions-table.ts
+++ b/apps/desktop/src/main/databases/workspace/migrations/00005-create-node-interactions-table.ts
@@ -1,21 +1,21 @@
import { Migration } from 'kysely';
-export const createEntryInteractionsTable: Migration = {
+export const createNodeInteractionsTable: Migration = {
up: async (db) => {
await db.schema
- .createTable('entry_interactions')
- .addColumn('entry_id', 'text', (col) => col.notNull())
+ .createTable('node_interactions')
+ .addColumn('node_id', 'text', (col) => col.notNull())
.addColumn('collaborator_id', 'text', (col) => col.notNull())
.addColumn('root_id', 'text', (col) => col.notNull())
+ .addColumn('revision', 'integer', (col) => col.notNull())
+ .addPrimaryKeyConstraint('node_interactions_pkey', [
+ 'node_id',
+ 'collaborator_id',
+ ])
.addColumn('first_seen_at', 'text')
.addColumn('last_seen_at', 'text')
.addColumn('first_opened_at', 'text')
.addColumn('last_opened_at', 'text')
- .addColumn('version', 'integer', (col) => col.notNull())
- .addPrimaryKeyConstraint('entry_interactions_pkey', [
- 'entry_id',
- 'collaborator_id',
- ])
.execute();
},
down: async (db) => {
diff --git a/apps/desktop/src/main/databases/workspace/migrations/00006-create-messages-table.ts b/apps/desktop/src/main/databases/workspace/migrations/00006-create-messages-table.ts
deleted file mode 100644
index 87798b82..00000000
--- a/apps/desktop/src/main/databases/workspace/migrations/00006-create-messages-table.ts
+++ /dev/null
@@ -1,35 +0,0 @@
-import { Migration, sql } from 'kysely';
-
-export const createMessagesTable: Migration = {
- up: async (db) => {
- await db.schema
- .createTable('messages')
- .addColumn('id', 'text', (col) => col.notNull().primaryKey())
- .addColumn('type', 'integer', (col) =>
- col
- .notNull()
- .generatedAlwaysAs(sql`json_extract(attributes, '$.type')`)
- .stored()
- )
- .addColumn('parent_id', 'text', (col) => col.notNull())
- .addColumn('entry_id', 'text', (col) => col.notNull())
- .addColumn('root_id', 'text', (col) => col.notNull())
- .addColumn('attributes', 'text', (col) => col.notNull())
- .addColumn('created_at', 'text', (col) => col.notNull())
- .addColumn('created_by', 'text', (col) => col.notNull())
- .addColumn('updated_at', 'text')
- .addColumn('updated_by', 'text')
- .addColumn('deleted_at', 'text')
- .addColumn('version', 'integer')
- .execute();
-
- await db.schema
- .createIndex('messages_parent_id_index')
- .on('messages')
- .columns(['parent_id'])
- .execute();
- },
- down: async (db) => {
- await db.schema.dropTable('messages').execute();
- },
-};
diff --git a/apps/desktop/src/main/databases/workspace/migrations/00007-create-message-reactions-table.ts b/apps/desktop/src/main/databases/workspace/migrations/00006-create-node-reactions-table.ts
similarity index 52%
rename from apps/desktop/src/main/databases/workspace/migrations/00007-create-message-reactions-table.ts
rename to apps/desktop/src/main/databases/workspace/migrations/00006-create-node-reactions-table.ts
index dd9f9e7a..b7f6f12b 100644
--- a/apps/desktop/src/main/databases/workspace/migrations/00007-create-message-reactions-table.ts
+++ b/apps/desktop/src/main/databases/workspace/migrations/00006-create-node-reactions-table.ts
@@ -1,24 +1,23 @@
import { Migration } from 'kysely';
-export const createMessageReactionsTable: Migration = {
+export const createNodeReactionsTable: Migration = {
up: async (db) => {
await db.schema
- .createTable('message_reactions')
- .addColumn('message_id', 'text', (col) => col.notNull())
+ .createTable('node_reactions')
+ .addColumn('node_id', 'text', (col) => col.notNull())
.addColumn('collaborator_id', 'text', (col) => col.notNull())
.addColumn('reaction', 'text', (col) => col.notNull())
.addColumn('root_id', 'text', (col) => col.notNull())
+ .addColumn('revision', 'integer', (col) => col.notNull())
.addColumn('created_at', 'text', (col) => col.notNull())
- .addColumn('deleted_at', 'text')
- .addColumn('version', 'integer', (col) => col.notNull())
- .addPrimaryKeyConstraint('message_reactions_pkey', [
- 'message_id',
+ .addPrimaryKeyConstraint('node_reactions_pkey', [
+ 'node_id',
'collaborator_id',
'reaction',
])
.execute();
},
down: async (db) => {
- await db.schema.dropTable('message_reactions').execute();
+ await db.schema.dropTable('node_reactions').execute();
},
};
diff --git a/apps/desktop/src/main/databases/workspace/migrations/00005-create-collaborations-table.ts b/apps/desktop/src/main/databases/workspace/migrations/00007-create-collaborations-table.ts
similarity index 76%
rename from apps/desktop/src/main/databases/workspace/migrations/00005-create-collaborations-table.ts
rename to apps/desktop/src/main/databases/workspace/migrations/00007-create-collaborations-table.ts
index 73d42f1d..5870889d 100644
--- a/apps/desktop/src/main/databases/workspace/migrations/00005-create-collaborations-table.ts
+++ b/apps/desktop/src/main/databases/workspace/migrations/00007-create-collaborations-table.ts
@@ -4,12 +4,12 @@ export const createCollaborationsTable: Migration = {
up: async (db) => {
await db.schema
.createTable('collaborations')
- .addColumn('entry_id', 'text', (col) => col.notNull().primaryKey())
+ .addColumn('node_id', 'text', (col) => col.notNull().primaryKey())
.addColumn('role', 'text')
+ .addColumn('revision', 'integer', (col) => col.notNull())
.addColumn('created_at', 'text', (col) => col.notNull())
.addColumn('updated_at', 'text')
.addColumn('deleted_at', 'text')
- .addColumn('version', 'integer')
.execute();
},
down: async (db) => {
diff --git a/apps/desktop/src/main/databases/workspace/migrations/00009-create-files-table.ts b/apps/desktop/src/main/databases/workspace/migrations/00008-create-files-table.ts
similarity index 71%
rename from apps/desktop/src/main/databases/workspace/migrations/00009-create-files-table.ts
rename to apps/desktop/src/main/databases/workspace/migrations/00008-create-files-table.ts
index cfaa1355..34607268 100644
--- a/apps/desktop/src/main/databases/workspace/migrations/00009-create-files-table.ts
+++ b/apps/desktop/src/main/databases/workspace/migrations/00008-create-files-table.ts
@@ -7,8 +7,8 @@ export const createFilesTable: Migration = {
.addColumn('id', 'text', (col) => col.notNull().primaryKey())
.addColumn('type', 'text', (col) => col.notNull())
.addColumn('parent_id', 'text', (col) => col.notNull())
- .addColumn('entry_id', 'text', (col) => col.notNull())
.addColumn('root_id', 'text', (col) => col.notNull())
+ .addColumn('revision', 'integer', (col) => col.notNull())
.addColumn('name', 'text', (col) => col.notNull())
.addColumn('original_name', 'text', (col) => col.notNull())
.addColumn('mime_type', 'text', (col) => col.notNull())
@@ -18,9 +18,13 @@ export const createFilesTable: Migration = {
.addColumn('created_by', 'text', (col) => col.notNull())
.addColumn('updated_at', 'text')
.addColumn('updated_by', 'text')
- .addColumn('deleted_at', 'text')
+ .addColumn('download_status', 'integer', (col) => col.notNull())
+ .addColumn('download_progress', 'integer', (col) => col.notNull())
+ .addColumn('download_retries', 'integer', (col) => col.notNull())
+ .addColumn('upload_status', 'integer', (col) => col.notNull())
+ .addColumn('upload_progress', 'integer', (col) => col.notNull())
+ .addColumn('upload_retries', 'integer', (col) => col.notNull())
.addColumn('status', 'integer', (col) => col.notNull())
- .addColumn('version', 'integer')
.execute();
await db.schema
diff --git a/apps/desktop/src/main/databases/workspace/migrations/00008-create-message-interactions-table.ts b/apps/desktop/src/main/databases/workspace/migrations/00008-create-message-interactions-table.ts
deleted file mode 100644
index 78f709cc..00000000
--- a/apps/desktop/src/main/databases/workspace/migrations/00008-create-message-interactions-table.ts
+++ /dev/null
@@ -1,24 +0,0 @@
-import { Migration } from 'kysely';
-
-export const createMessageInteractionsTable: Migration = {
- up: async (db) => {
- await db.schema
- .createTable('message_interactions')
- .addColumn('message_id', 'text', (col) => col.notNull())
- .addColumn('collaborator_id', 'text', (col) => col.notNull())
- .addColumn('root_id', 'text', (col) => col.notNull())
- .addColumn('first_seen_at', 'text')
- .addColumn('last_seen_at', 'text')
- .addColumn('first_opened_at', 'text')
- .addColumn('last_opened_at', 'text')
- .addColumn('version', 'integer', (col) => col.notNull())
- .addPrimaryKeyConstraint('message_interactions_pkey', [
- 'message_id',
- 'collaborator_id',
- ])
- .execute();
- },
- down: async (db) => {
- await db.schema.dropTable('message_interactions').execute();
- },
-};
diff --git a/apps/desktop/src/main/databases/workspace/migrations/00012-create-mutations-table.ts b/apps/desktop/src/main/databases/workspace/migrations/00009-create-mutations-table.ts
similarity index 100%
rename from apps/desktop/src/main/databases/workspace/migrations/00012-create-mutations-table.ts
rename to apps/desktop/src/main/databases/workspace/migrations/00009-create-mutations-table.ts
diff --git a/apps/desktop/src/main/databases/workspace/migrations/00010-create-file-states-table.ts b/apps/desktop/src/main/databases/workspace/migrations/00010-create-file-states-table.ts
deleted file mode 100644
index 7420c7c1..00000000
--- a/apps/desktop/src/main/databases/workspace/migrations/00010-create-file-states-table.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-import { Migration } from 'kysely';
-
-export const createFileStatesTable: Migration = {
- up: async (db) => {
- await db.schema
- .createTable('file_states')
- .addColumn('file_id', 'text', (col) => col.notNull().primaryKey())
- .addColumn('download_status', 'integer', (col) => col.notNull())
- .addColumn('download_progress', 'integer', (col) => col.notNull())
- .addColumn('download_retries', 'integer', (col) => col.notNull())
- .addColumn('upload_status', 'integer', (col) => col.notNull())
- .addColumn('upload_progress', 'integer', (col) => col.notNull())
- .addColumn('upload_retries', 'integer', (col) => col.notNull())
- .addColumn('created_at', 'text', (col) => col.notNull())
- .addColumn('updated_at', 'text')
- .execute();
- },
- down: async (db) => {
- await db.schema.dropTable('file_states').execute();
- },
-};
diff --git a/apps/desktop/src/main/databases/workspace/migrations/00010-create-tombstones-table.ts b/apps/desktop/src/main/databases/workspace/migrations/00010-create-tombstones-table.ts
new file mode 100644
index 00000000..553a75e8
--- /dev/null
+++ b/apps/desktop/src/main/databases/workspace/migrations/00010-create-tombstones-table.ts
@@ -0,0 +1,15 @@
+import { Migration } from 'kysely';
+
+export const createTombstonesTable: Migration = {
+ up: async (db) => {
+ await db.schema
+ .createTable('tombstones')
+ .addColumn('id', 'text', (col) => col.notNull().primaryKey())
+ .addColumn('data', 'text', (col) => col.notNull())
+ .addColumn('deleted_at', 'text', (col) => col.notNull())
+ .execute();
+ },
+ down: async (db) => {
+ await db.schema.dropTable('tombstones').execute();
+ },
+};
diff --git a/apps/desktop/src/main/databases/workspace/migrations/00011-create-file-interactions-table.ts b/apps/desktop/src/main/databases/workspace/migrations/00011-create-file-interactions-table.ts
deleted file mode 100644
index 3ba5cff4..00000000
--- a/apps/desktop/src/main/databases/workspace/migrations/00011-create-file-interactions-table.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-import { Migration } from 'kysely';
-
-export const createFileInteractionsTable: Migration = {
- up: async (db) => {
- await db.schema
- .createTable('file_interactions')
- .addColumn('file_id', 'text', (col) => col.notNull())
- .addColumn('collaborator_id', 'text', (col) => col.notNull())
- .addColumn('root_id', 'text', (col) => col.notNull())
- .addColumn('seen_at', 'text')
- .addColumn('first_opened_at', 'text')
- .addColumn('last_opened_at', 'text')
- .addColumn('version', 'integer', (col) => col.notNull())
- .addPrimaryKeyConstraint('file_interactions_pkey', [
- 'file_id',
- 'collaborator_id',
- ])
- .execute();
- },
- down: async (db) => {
- await db.schema.dropTable('file_interactions').execute();
- },
-};
diff --git a/apps/desktop/src/main/databases/workspace/migrations/00014-create-texts-table.ts b/apps/desktop/src/main/databases/workspace/migrations/00011-create-texts-table.ts
similarity index 100%
rename from apps/desktop/src/main/databases/workspace/migrations/00014-create-texts-table.ts
rename to apps/desktop/src/main/databases/workspace/migrations/00011-create-texts-table.ts
diff --git a/apps/desktop/src/main/databases/workspace/migrations/00015-create-cursors-table.ts b/apps/desktop/src/main/databases/workspace/migrations/00012-create-cursors-table.ts
similarity index 100%
rename from apps/desktop/src/main/databases/workspace/migrations/00015-create-cursors-table.ts
rename to apps/desktop/src/main/databases/workspace/migrations/00012-create-cursors-table.ts
diff --git a/apps/desktop/src/main/databases/workspace/migrations/00013-create-entry-paths-table.ts b/apps/desktop/src/main/databases/workspace/migrations/00013-create-entry-paths-table.ts
deleted file mode 100644
index 6a9e72a1..00000000
--- a/apps/desktop/src/main/databases/workspace/migrations/00013-create-entry-paths-table.ts
+++ /dev/null
@@ -1,63 +0,0 @@
-import { Migration, sql } from 'kysely';
-
-export const createEntryPathsTable: Migration = {
- up: async (db) => {
- await db.schema
- .createTable('entry_paths')
- .addColumn('ancestor_id', 'varchar(30)', (col) =>
- col.notNull().references('entries.id').onDelete('cascade')
- )
- .addColumn('descendant_id', 'varchar(30)', (col) =>
- col.notNull().references('entries.id').onDelete('cascade')
- )
- .addColumn('level', 'integer', (col) => col.notNull())
- .addPrimaryKeyConstraint('entry_paths_pkey', [
- 'ancestor_id',
- 'descendant_id',
- ])
- .execute();
-
- await sql`
- CREATE TRIGGER trg_insert_entry_path
- AFTER INSERT ON entries
- FOR EACH ROW
- BEGIN
- -- Insert direct path from the new entry to itself
- INSERT INTO entry_paths (ancestor_id, descendant_id, level)
- VALUES (NEW.id, NEW.id, 0);
-
- -- Insert paths from ancestors to the new entry
- INSERT INTO entry_paths (ancestor_id, descendant_id, level)
- SELECT ancestor_id, NEW.id, level + 1
- FROM entry_paths
- WHERE descendant_id = NEW.parent_id AND ancestor_id <> NEW.id;
- END;
- `.execute(db);
-
- await sql`
- CREATE TRIGGER trg_update_entry_path
- AFTER UPDATE ON entries
- FOR EACH ROW
- WHEN OLD.parent_id <> NEW.parent_id
- BEGIN
- -- Delete old paths involving the updated entry
- DELETE FROM entry_paths
- WHERE descendant_id = NEW.id AND ancestor_id <> NEW.id;
-
- -- Insert new paths from ancestors to the updated entry
- INSERT INTO entry_paths (ancestor_id, descendant_id, level)
- SELECT ancestor_id, NEW.id, level + 1
- FROM entry_paths
- WHERE descendant_id = NEW.parent_id AND ancestor_id <> NEW.id;
- END;
- `.execute(db);
- },
- down: async (db) => {
- await sql`
- DROP TRIGGER IF EXISTS trg_insert_entry_path;
- DROP TRIGGER IF EXISTS trg_update_entry_path;
- `.execute(db);
-
- await db.schema.dropTable('entry_paths').execute();
- },
-};
diff --git a/apps/desktop/src/main/databases/workspace/migrations/00016-create-metadata-table.tsx b/apps/desktop/src/main/databases/workspace/migrations/00013-create-metadata-table.tsx
similarity index 100%
rename from apps/desktop/src/main/databases/workspace/migrations/00016-create-metadata-table.tsx
rename to apps/desktop/src/main/databases/workspace/migrations/00013-create-metadata-table.tsx
diff --git a/apps/desktop/src/main/databases/workspace/migrations/index.ts b/apps/desktop/src/main/databases/workspace/migrations/index.ts
index 87fb43e9..456d5541 100644
--- a/apps/desktop/src/main/databases/workspace/migrations/index.ts
+++ b/apps/desktop/src/main/databases/workspace/migrations/index.ts
@@ -1,37 +1,31 @@
import { Migration } from 'kysely';
import { createUsersTable } from './00001-create-users-table';
-import { createEntriesTable } from './00002-create-entries-table';
-import { createEntryInteractionsTable } from './00004-create-entry-interactions-table';
-import { createEntryTransactionsTable } from './00003-create-entry-transactions-table';
-import { createCollaborationsTable } from './00005-create-collaborations-table';
-import { createMessagesTable } from './00006-create-messages-table';
-import { createMessageReactionsTable } from './00007-create-message-reactions-table';
-import { createMessageInteractionsTable } from './00008-create-message-interactions-table';
-import { createFilesTable } from './00009-create-files-table';
-import { createFileStatesTable } from './00010-create-file-states-table';
-import { createFileInteractionsTable } from './00011-create-file-interactions-table';
-import { createMutationsTable } from './00012-create-mutations-table';
-import { createEntryPathsTable } from './00013-create-entry-paths-table';
-import { createTextsTable } from './00014-create-texts-table';
-import { createCursorsTable } from './00015-create-cursors-table';
-import { createMetadataTable } from './00016-create-metadata-table';
+import { createNodesTable } from './00002-create-nodes-table';
+import { createNodeStatesTable } from './00003-create-node-states-table';
+import { createNodeTransactionsTable } from './00004-create-node-transactions-table';
+import { createNodeInteractionsTable } from './00005-create-node-interactions-table';
+import { createNodeReactionsTable } from './00006-create-node-reactions-table';
+import { createCollaborationsTable } from './00007-create-collaborations-table';
+import { createFilesTable } from './00008-create-files-table';
+import { createMutationsTable } from './00009-create-mutations-table';
+import { createTombstonesTable } from './00010-create-tombstones-table';
+import { createTextsTable } from './00011-create-texts-table';
+import { createCursorsTable } from './00012-create-cursors-table';
+import { createMetadataTable } from './00013-create-metadata-table';
export const workspaceDatabaseMigrations: Record<string, Migration> = {
'00001-create-users-table': createUsersTable,
- '00002-create-entries-table': createEntriesTable,
- '00003-create-entry-transactions-table': createEntryTransactionsTable,
- '00004-create-entry-interactions-table': createEntryInteractionsTable,
- '00005-create-collaborations-table': createCollaborationsTable,
- '00006-create-messages-table': createMessagesTable,
- '00007-create-message-reactions-table': createMessageReactionsTable,
- '00008-create-message-interactions-table': createMessageInteractionsTable,
- '00009-create-files-table': createFilesTable,
- '00010-create-file-states-table': createFileStatesTable,
- '00011-create-file-interactions-table': createFileInteractionsTable,
- '00012-create-mutations-table': createMutationsTable,
- '00013-create-entry-paths-table': createEntryPathsTable,
- '00014-create-texts-table': createTextsTable,
- '00015-create-cursors-table': createCursorsTable,
- '00016-create-metadata-table': createMetadataTable,
+ '00002-create-nodes-table': createNodesTable,
+ '00003-create-node-states-table': createNodeStatesTable,
+ '00004-create-node-transactions-table': createNodeTransactionsTable,
+ '00005-create-node-interactions-table': createNodeInteractionsTable,
+ '00006-create-node-reactions-table': createNodeReactionsTable,
+ '00007-create-collaborations-table': createCollaborationsTable,
+ '00008-create-files-table': createFilesTable,
+ '00009-create-mutations-table': createMutationsTable,
+ '00010-create-tombstones-table': createTombstonesTable,
+ '00011-create-texts-table': createTextsTable,
+ '00012-create-cursors-table': createCursorsTable,
+ '00013-create-metadata-table': createMetadataTable,
};
diff --git a/apps/desktop/src/main/databases/workspace/schema.ts b/apps/desktop/src/main/databases/workspace/schema.ts
index 268f6c4a..99a00204 100644
--- a/apps/desktop/src/main/databases/workspace/schema.ts
+++ b/apps/desktop/src/main/databases/workspace/schema.ts
@@ -2,9 +2,8 @@ import {
FileStatus,
FileType,
MutationType,
- EntryType,
+ NodeType,
WorkspaceRole,
- MessageType,
TransactionOperation,
UserStatus,
} from '@colanode/core';
@@ -23,156 +22,108 @@ interface UserTable {
status: ColumnType<UserStatus, UserStatus, UserStatus>;
created_at: ColumnType<string, string, never>;
updated_at: ColumnType<string | null, string | null, string | null>;
- version: ColumnType<bigint, bigint, bigint>;
+ revision: ColumnType<bigint, bigint, bigint>;
}
export type SelectUser = Selectable<UserTable>;
export type CreateUser = Insertable<UserTable>;
export type UpdateUser = Updateable<UserTable>;
-interface EntryTable {
+interface NodeTable {
id: ColumnType<string, string, never>;
- type: ColumnType<EntryType, never, never>;
+ type: ColumnType<NodeType, never, never>;
parent_id: ColumnType<string | null, never, never>;
root_id: ColumnType<string, string, never>;
attributes: ColumnType<string, string, string>;
+ local_revision: ColumnType<bigint, bigint, bigint>;
+ server_revision: ColumnType<bigint, bigint, bigint>;
created_at: ColumnType<string, string, never>;
updated_at: ColumnType<string | null, string | null, string | null>;
created_by: ColumnType<string, string, never>;
updated_by: ColumnType<string | null, string | null, string | null>;
- transaction_id: ColumnType<string, string, string>;
}
-export type SelectEntry = Selectable<EntryTable>;
-export type CreateEntry = Insertable<EntryTable>;
-export type UpdateEntry = Updateable<EntryTable>;
+export type SelectNode = Selectable<NodeTable>;
+export type CreateNode = Insertable<NodeTable>;
+export type UpdateNode = Updateable<NodeTable>;
-interface EntryPathTable {
- ancestor_id: ColumnType<string, string, never>;
- descendant_id: ColumnType<string, string, never>;
- level: ColumnType<number, number, number>;
+interface NodeStateTable {
+ id: ColumnType<string, string, never>;
+ state: ColumnType<Uint8Array, Uint8Array, Uint8Array>;
+ revision: ColumnType<bigint, bigint, bigint>;
}
-export type SelectEntryPath = Selectable<EntryPathTable>;
+export type SelectNodeState = Selectable<NodeStateTable>;
+export type CreateNodeState = Insertable<NodeStateTable>;
+export type UpdateNodeState = Updateable<NodeStateTable>;
-interface EntryTransactionTable {
+interface NodeTransactionTable {
id: ColumnType<string, string, never>;
- entry_id: ColumnType<string, string, never>;
- root_id: ColumnType<string, string, never>;
+ node_id: ColumnType<string, string, never>;
operation: ColumnType<TransactionOperation, TransactionOperation, never>;
- data: ColumnType<Uint8Array | null, Uint8Array | null, never>;
+ data: ColumnType<Uint8Array, Uint8Array, never>;
created_at: ColumnType<string, string, never>;
- created_by: ColumnType<string, string, never>;
- server_created_at: ColumnType<string | null, string | null, string | null>;
- version: ColumnType<bigint, bigint, bigint>;
}
-export type SelectEntryTransaction = Selectable<EntryTransactionTable>;
-export type CreateEntryTransaction = Insertable<EntryTransactionTable>;
-export type UpdateEntryTransaction = Updateable<EntryTransactionTable>;
+export type SelectNodeTransaction = Selectable<NodeTransactionTable>;
+export type CreateNodeTransaction = Insertable<NodeTransactionTable>;
+export type UpdateNodeTransaction = Updateable<NodeTransactionTable>;
-interface EntryInteractionTable {
- entry_id: ColumnType<string, string, never>;
+interface NodeInteractionTable {
+ node_id: ColumnType<string, string, never>;
collaborator_id: ColumnType<string, string, never>;
root_id: ColumnType<string, string, never>;
+ revision: ColumnType<bigint, bigint, bigint>;
first_seen_at: ColumnType<string | null, string | null, string | null>;
last_seen_at: ColumnType<string | null, string | null, string | null>;
first_opened_at: ColumnType<string | null, string | null, string | null>;
last_opened_at: ColumnType<string | null, string | null, string | null>;
- version: ColumnType<bigint, bigint, bigint>;
}
-export type SelectEntryInteraction = Selectable<EntryInteractionTable>;
-export type CreateEntryInteraction = Insertable<EntryInteractionTable>;
-export type UpdateEntryInteraction = Updateable<EntryInteractionTable>;
+export type SelectNodeInteraction = Selectable<NodeInteractionTable>;
+export type CreateNodeInteraction = Insertable<NodeInteractionTable>;
+export type UpdateNodeInteraction = Updateable<NodeInteractionTable>;
+
+interface NodeReactionTable {
+ node_id: ColumnType<string, string, never>;
+ collaborator_id: ColumnType<string, string, never>;
+ reaction: ColumnType<string, string, string>;
+ root_id: ColumnType<string, string, string>;
+ revision: ColumnType<bigint, bigint, bigint>;
+ created_at: ColumnType<string, string, never>;
+}
+
+export type SelectNodeReaction = Selectable<NodeReactionTable>;
+export type CreateNodeReaction = Insertable<NodeReactionTable>;
+export type UpdateNodeReaction = Updateable<NodeReactionTable>;
interface CollaborationTable {
- entry_id: ColumnType<string, string, never>;
+ node_id: ColumnType<string, string, never>;
role: ColumnType<string, string, string>;
+ revision: ColumnType<bigint, bigint, bigint>;
created_at: ColumnType<string, string, never>;
updated_at: ColumnType<string | null, string | null, string | null>;
deleted_at: ColumnType<string | null, string | null, string | null>;
- version: ColumnType<bigint, bigint, bigint>;
}
export type SelectCollaboration = Selectable<CollaborationTable>;
export type CreateCollaboration = Insertable<CollaborationTable>;
export type UpdateCollaboration = Updateable<CollaborationTable>;
-interface MessageTable {
- id: ColumnType<string, string, never>;
- type: ColumnType<MessageType, never, never>;
- parent_id: ColumnType<string, string, string>;
- entry_id: ColumnType<string, string, string>;
- root_id: ColumnType<string, string, string>;
- attributes: ColumnType<string, string, string>;
- created_at: ColumnType<string, string, never>;
- created_by: ColumnType<string, string, never>;
- updated_at: ColumnType<string | null, string | null, string | null>;
- updated_by: ColumnType<string | null, string | null, string | null>;
- deleted_at: ColumnType<string | null, never, string | null>;
- version: ColumnType<bigint, bigint, bigint>;
-}
-
-export type SelectMessage = Selectable<MessageTable>;
-export type CreateMessage = Insertable<MessageTable>;
-export type UpdateMessage = Updateable<MessageTable>;
-
-interface MessageReactionTable {
- message_id: ColumnType<string, string, never>;
- collaborator_id: ColumnType<string, string, never>;
- reaction: ColumnType<string, string, string>;
- root_id: ColumnType<string, string, string>;
- created_at: ColumnType<string, string, never>;
- deleted_at: ColumnType<string | null, never, string | null>;
- version: ColumnType<bigint, bigint, bigint>;
-}
-
-export type SelectMessageReaction = Selectable<MessageReactionTable>;
-export type CreateMessageReaction = Insertable<MessageReactionTable>;
-export type UpdateMessageReaction = Updateable<MessageReactionTable>;
-
-interface MessageInteractionTable {
- message_id: ColumnType<string, string, never>;
- collaborator_id: ColumnType<string, string, never>;
- root_id: ColumnType<string, string, string>;
- first_seen_at: ColumnType<string | null, string | null, string | null>;
- last_seen_at: ColumnType<string | null, string | null, string | null>;
- first_opened_at: ColumnType<string | null, string | null, string | null>;
- last_opened_at: ColumnType<string | null, string | null, string | null>;
- version: ColumnType<bigint, bigint, bigint>;
-}
-
-export type SelectMessageInteraction = Selectable<MessageInteractionTable>;
-export type CreateMessageInteraction = Insertable<MessageInteractionTable>;
-export type UpdateMessageInteraction = Updateable<MessageInteractionTable>;
-
interface FileTable {
id: ColumnType<string, string, never>;
type: ColumnType<FileType, FileType, FileType>;
parent_id: ColumnType<string, string, string>;
- entry_id: ColumnType<string, string, string>;
root_id: ColumnType<string, string, string>;
+ revision: ColumnType<bigint, bigint, bigint>;
name: ColumnType<string, string, string>;
original_name: ColumnType<string, string, string>;
mime_type: ColumnType<string, string, string>;
extension: ColumnType<string, string, string>;
size: ColumnType<number, number, number>;
- created_at: ColumnType<string, string, never>;
created_by: ColumnType<string, string, never>;
- updated_at: ColumnType<string | null, string | null, string | null>;
updated_by: ColumnType<string | null, string | null, string | null>;
deleted_at: ColumnType<string | null, never, string | null>;
- status: ColumnType<FileStatus, FileStatus, FileStatus>;
- version: ColumnType<bigint, bigint, bigint>;
-}
-
-export type SelectFile = Selectable<FileTable>;
-export type CreateFile = Insertable<FileTable>;
-export type UpdateFile = Updateable<FileTable>;
-
-interface FileStateTable {
- file_id: ColumnType<string, string, never>;
download_status: ColumnType<DownloadStatus, DownloadStatus, DownloadStatus>;
download_progress: ColumnType<number, number, number>;
download_retries: ColumnType<number, number, number>;
@@ -181,26 +132,12 @@ interface FileStateTable {
upload_retries: ColumnType<number, number, number>;
created_at: ColumnType<string, string, never>;
updated_at: ColumnType<string | null, string | null, string>;
+ status: ColumnType<FileStatus, FileStatus, FileStatus>;
}
-export type SelectFileState = Selectable<FileStateTable>;
-export type CreateFileState = Insertable<FileStateTable>;
-export type UpdateFileState = Updateable<FileStateTable>;
-
-interface FileInteractionTable {
- file_id: ColumnType<string, string, never>;
- collaborator_id: ColumnType<string, string, never>;
- root_id: ColumnType<string, string, string>;
- first_seen_at: ColumnType<string | null, string | null, string | null>;
- last_seen_at: ColumnType<string | null, string | null, string | null>;
- first_opened_at: ColumnType<string | null, string | null, string | null>;
- last_opened_at: ColumnType<string | null, string | null, string | null>;
- version: ColumnType<bigint, bigint, bigint>;
-}
-
-export type SelectFileInteraction = Selectable<FileInteractionTable>;
-export type CreateFileInteraction = Insertable<FileInteractionTable>;
-export type UpdateFileInteraction = Updateable<FileInteractionTable>;
+export type SelectFile = Selectable<FileTable>;
+export type CreateFile = Insertable<FileTable>;
+export type UpdateFile = Updateable<FileTable>;
interface MutationTable {
id: ColumnType<string, string, never>;
@@ -214,6 +151,16 @@ export type SelectMutation = Selectable<MutationTable>;
export type CreateMutation = Insertable<MutationTable>;
export type UpdateMutation = Updateable<MutationTable>;
+interface TombstoneTable {
+ id: ColumnType<string, string, never>;
+ data: ColumnType<string, string, never>;
+ created_at: ColumnType<string, string, never>;
+}
+
+export type SelectTombsonte = Selectable<TombstoneTable>;
+export type CreateTombstone = Insertable<TombstoneTable>;
+export type UpdateTombstone = Updateable<TombstoneTable>;
+
interface TextTable {
id: ColumnType<string, string, never>;
name: ColumnType<string | null, string | null, string | null>;
@@ -248,18 +195,15 @@ export type UpdateWorkspaceMetadata = Updateable<MetadataTable>;
export interface WorkspaceDatabaseSchema {
users: UserTable;
- entries: EntryTable;
- entry_interactions: EntryInteractionTable;
- entry_transactions: EntryTransactionTable;
- entry_paths: EntryPathTable;
+ nodes: NodeTable;
+ node_states: NodeStateTable;
+ node_interactions: NodeInteractionTable;
+ node_transactions: NodeTransactionTable;
+ node_reactions: NodeReactionTable;
collaborations: CollaborationTable;
- messages: MessageTable;
- message_reactions: MessageReactionTable;
- message_interactions: MessageInteractionTable;
files: FileTable;
- file_states: FileStateTable;
- file_interactions: FileInteractionTable;
mutations: MutationTable;
+ tombstones: TombstoneTable;
texts: TextTable;
cursors: CursorTable;
metadata: MetadataTable;
diff --git a/apps/desktop/src/main/lib/mappers.ts b/apps/desktop/src/main/lib/mappers.ts
index 3f5791ab..e71e9593 100644
--- a/apps/desktop/src/main/lib/mappers.ts
+++ b/apps/desktop/src/main/lib/mappers.ts
@@ -1,9 +1,4 @@
-import {
- LocalTransaction,
- Mutation,
- Entry,
- TransactionOperation,
-} from '@colanode/core';
+import { LocalNodeTransaction, Mutation } from '@colanode/core';
import { encodeState } from '@colanode/crdt';
import {
@@ -16,33 +11,24 @@ import { SelectIcon } from '@/main/databases/icons';
import { SelectWorkspace } from '@/main/databases/account';
import {
SelectFile,
- SelectFileState,
- SelectMessage,
- SelectMessageReaction,
SelectMutation,
- SelectEntry,
- SelectEntryTransaction,
+ SelectNode,
+ SelectNodeTransaction,
SelectUser,
- SelectMessageInteraction,
- SelectFileInteraction,
- SelectEntryInteraction,
+ SelectNodeInteraction,
+ SelectNodeReaction,
SelectWorkspaceMetadata,
} from '@/main/databases/workspace';
import { Account } from '@/shared/types/accounts';
import { Server } from '@/shared/types/servers';
import { User } from '@/shared/types/users';
-import { File, FileInteraction, FileState } from '@/shared/types/files';
+import { File } from '@/shared/types/files';
import {
Workspace,
WorkspaceMetadata,
WorkspaceMetadataKey,
} from '@/shared/types/workspaces';
-import {
- MessageInteraction,
- MessageNode,
- MessageReaction,
-} from '@/shared/types/messages';
-import { EntryInteraction } from '@/shared/types/entries';
+import { LocalNode, NodeInteraction, NodeReaction } from '@/shared/types/nodes';
import { Emoji } from '@/shared/types/emojis';
import { Icon } from '@/shared/types/icons';
import { AppMetadata, AppMetadataKey } from '@/shared/types/apps';
@@ -61,7 +47,7 @@ export const mapUser = (row: SelectUser): User => {
};
};
-export const mapEntry = (row: SelectEntry): Entry => {
+export const mapNode = (row: SelectNode): LocalNode => {
return {
id: row.id,
type: row.type,
@@ -72,8 +58,9 @@ export const mapEntry = (row: SelectEntry): Entry => {
createdBy: row.created_by,
updatedAt: row.updated_at,
updatedBy: row.updated_by,
- transactionId: row.transaction_id,
- };
+ localRevision: row.local_revision,
+ serverRevision: row.server_revision,
+ } as LocalNode;
};
export const mapAccount = (row: SelectAccount): Account => {
@@ -105,45 +92,16 @@ export const mapWorkspace = (row: SelectWorkspace): Workspace => {
};
};
-export const mapEntryTransaction = (
- row: SelectEntryTransaction
-): LocalTransaction => {
- if (row.operation === TransactionOperation.Create && row.data) {
- return {
- id: row.id,
- entryId: row.entry_id,
- rootId: row.root_id,
- operation: TransactionOperation.Create,
- data: encodeState(row.data),
- createdAt: row.created_at,
- createdBy: row.created_by,
- };
- }
-
- if (row.operation === TransactionOperation.Update && row.data) {
- return {
- id: row.id,
- entryId: row.entry_id,
- rootId: row.root_id,
- operation: TransactionOperation.Update,
- data: encodeState(row.data),
- createdAt: row.created_at,
- createdBy: row.created_by,
- };
- }
-
- if (row.operation === TransactionOperation.Delete) {
- return {
- id: row.id,
- entryId: row.entry_id,
- rootId: row.root_id,
- operation: TransactionOperation.Delete,
- createdAt: row.created_at,
- createdBy: row.created_by,
- };
- }
-
- throw new Error('Invalid transaction type');
+export const mapNodeTransaction = (
+ row: SelectNodeTransaction
+): LocalNodeTransaction => {
+ return {
+ id: row.id,
+ nodeId: row.node_id,
+ operation: row.operation,
+ data: encodeState(row.data),
+ createdAt: row.created_at,
+ };
};
export const mapMutation = (row: SelectMutation): Mutation => {
@@ -167,26 +125,9 @@ export const mapServer = (row: SelectServer): Server => {
};
};
-export const mapMessage = (row: SelectMessage): MessageNode => {
+export const mapNodeReaction = (row: SelectNodeReaction): NodeReaction => {
return {
- id: row.id,
- type: row.type,
- parentId: row.parent_id,
- rootId: row.root_id,
- attributes: JSON.parse(row.attributes),
- createdAt: row.created_at,
- createdBy: row.created_by,
- updatedAt: row.updated_at,
- updatedBy: row.updated_by,
- version: row.version,
- };
-};
-
-export const mapMessageReaction = (
- row: SelectMessageReaction
-): MessageReaction => {
- return {
- messageId: row.message_id,
+ nodeId: row.node_id,
collaboratorId: row.collaborator_id,
reaction: row.reaction,
rootId: row.root_id,
@@ -194,18 +135,18 @@ export const mapMessageReaction = (
};
};
-export const mapMessageInteraction = (
- row: SelectMessageInteraction
-): MessageInteraction => {
+export const mapNodeInteraction = (
+ row: SelectNodeInteraction
+): NodeInteraction => {
return {
- messageId: row.message_id,
+ nodeId: row.node_id,
collaboratorId: row.collaborator_id,
rootId: row.root_id,
+ revision: row.revision,
firstSeenAt: row.first_seen_at,
lastSeenAt: row.last_seen_at,
firstOpenedAt: row.first_opened_at,
lastOpenedAt: row.last_opened_at,
- version: row.version,
};
};
@@ -214,8 +155,8 @@ export const mapFile = (row: SelectFile): File => {
id: row.id,
type: row.type,
parentId: row.parent_id,
- entryId: row.entry_id,
rootId: row.root_id,
+ revision: row.revision,
name: row.name,
originalName: row.original_name,
extension: row.extension,
@@ -226,51 +167,12 @@ export const mapFile = (row: SelectFile): File => {
updatedAt: row.updated_at,
updatedBy: row.updated_by,
status: row.status,
- version: row.version,
- };
-};
-
-export const mapFileState = (row: SelectFileState): FileState => {
- return {
- fileId: row.file_id,
- downloadProgress: row.download_progress,
downloadStatus: row.download_status,
+ downloadProgress: row.download_progress,
downloadRetries: row.download_retries,
- uploadProgress: row.upload_progress,
uploadStatus: row.upload_status,
+ uploadProgress: row.upload_progress,
uploadRetries: row.upload_retries,
- createdAt: row.created_at,
- updatedAt: row.updated_at,
- };
-};
-
-export const mapFileInteraction = (
- row: SelectFileInteraction
-): FileInteraction => {
- return {
- fileId: row.file_id,
- collaboratorId: row.collaborator_id,
- rootId: row.root_id,
- lastSeenAt: row.last_seen_at,
- firstSeenAt: row.first_seen_at,
- lastOpenedAt: row.last_opened_at,
- firstOpenedAt: row.first_opened_at,
- version: row.version,
- };
-};
-
-export const mapEntryInteraction = (
- row: SelectEntryInteraction
-): EntryInteraction => {
- return {
- entryId: row.entry_id,
- collaboratorId: row.collaborator_id,
- rootId: row.root_id,
- lastSeenAt: row.last_seen_at,
- firstSeenAt: row.first_seen_at,
- lastOpenedAt: row.last_opened_at,
- firstOpenedAt: row.first_opened_at,
- version: row.version,
};
};
diff --git a/apps/desktop/src/main/lib/utils.ts b/apps/desktop/src/main/lib/utils.ts
index 2d36fdd6..5c0464dc 100644
--- a/apps/desktop/src/main/lib/utils.ts
+++ b/apps/desktop/src/main/lib/utils.ts
@@ -1,4 +1,4 @@
-import { extractFileType, getIdType, IdType } from '@colanode/core';
+import { extractFileType } from '@colanode/core';
import {
DeleteResult,
InsertResult,
@@ -13,7 +13,7 @@ import path from 'path';
import fs from 'fs';
import {
- SelectEntry,
+ SelectNode,
WorkspaceDatabaseSchema,
} from '@/main/databases/workspace';
import { FileMetadata } from '@/shared/types/files';
@@ -112,34 +112,42 @@ export const getFileMetadata = (filePath: string): FileMetadata | null => {
};
};
-export const fetchEntryAncestors = (
+export const fetchNodeAncestors = async (
database:
| Kysely<WorkspaceDatabaseSchema>
| Transaction<WorkspaceDatabaseSchema>,
- entryId: string
-): Promise<SelectEntry[]> => {
+ nodeId: string
+): Promise<SelectNode[]> => {
return database
- .selectFrom('entries')
- .selectAll()
- .where(
- 'id',
- 'in',
- database
- .selectFrom('entry_paths')
- .select('ancestor_id')
- .where('descendant_id', '=', entryId)
+ .withRecursive('ancestor_nodes', (cte) =>
+ cte
+ .selectFrom('nodes')
+ .selectAll('nodes')
+ .where('id', '=', nodeId)
+ .unionAll(
+ cte
+ .selectFrom('nodes as parent')
+ .selectAll('parent')
+ .innerJoin(
+ 'ancestor_nodes as child',
+ 'parent.id',
+ 'child.parent_id'
+ )
+ )
)
+ .selectFrom('ancestor_nodes')
+ .selectAll()
.execute();
};
-export const fetchEntry = (
+export const fetchNode = (
database:
| Kysely<WorkspaceDatabaseSchema>
| Transaction<WorkspaceDatabaseSchema>,
entryId: string
-): Promise<SelectEntry | undefined> => {
+): Promise<SelectNode | undefined> => {
return database
- .selectFrom('entries')
+ .selectFrom('nodes')
.selectAll()
.where('id', '=', entryId)
.executeTakeFirst();
@@ -159,76 +167,3 @@ export const fetchUserStorageUsed = async (
return BigInt(storageUsedRow?.storage_used ?? 0);
};
-
-export const fetchEntryBreadcrumb = async (
- database: Kysely<WorkspaceDatabaseSchema>,
- entryId: string
-): Promise<string[]> => {
- const rows = await database
- .selectFrom('entry_paths')
- .select('ancestor_id')
- .where('descendant_id', '=', entryId)
- .orderBy('level', 'desc')
- .execute();
-
- return rows.map((row) => row.ancestor_id);
-};
-
-export const fetchMessageBreadcrumb = async (
- database: Kysely<WorkspaceDatabaseSchema>,
- messageId: string
-): Promise<string[]> => {
- const message = await database
- .selectFrom('messages')
- .select('parent_id')
- .where('id', '=', messageId)
- .executeTakeFirst();
-
- if (!message) {
- return [];
- }
-
- const parentIdType = getIdType(message.parent_id);
- if (parentIdType === IdType.Message) {
- const messageBreadcrumb = await fetchMessageBreadcrumb(
- database,
- message.parent_id
- );
-
- return [...messageBreadcrumb, messageId];
- }
-
- const entryBreadcrumb = await fetchEntryBreadcrumb(
- database,
- message.parent_id
- );
- return [...entryBreadcrumb, messageId];
-};
-
-export const fetchFileBreadcrumb = async (
- database: Kysely<WorkspaceDatabaseSchema>,
- fileId: string
-): Promise<string[]> => {
- const file = await database
- .selectFrom('files')
- .select('parent_id')
- .where('id', '=', fileId)
- .executeTakeFirst();
-
- if (!file) {
- return [];
- }
-
- const parentIdType = getIdType(file.parent_id);
- if (parentIdType === IdType.Message) {
- const messageBreadcrumb = await fetchMessageBreadcrumb(
- database,
- file.parent_id
- );
-
- return [...messageBreadcrumb, fileId];
- }
-
- const entryBreadcrumb = await fetchEntryBreadcrumb(database, file.parent_id);
- return [...entryBreadcrumb, fileId];
-};
diff --git a/apps/desktop/src/main/mutations/channels/channel-create.ts b/apps/desktop/src/main/mutations/channels/channel-create.ts
index 4e0d65be..bd852dc7 100644
--- a/apps/desktop/src/main/mutations/channels/channel-create.ts
+++ b/apps/desktop/src/main/mutations/channels/channel-create.ts
@@ -18,7 +18,7 @@ export class ChannelCreateMutationHandler
const workspace = this.getWorkspace(input.accountId, input.workspaceId);
const space = await workspace.database
- .selectFrom('entries')
+ .selectFrom('nodes')
.selectAll()
.where('id', '=', input.spaceId)
.executeTakeFirst();
@@ -38,7 +38,7 @@ export class ChannelCreateMutationHandler
parentId: input.spaceId,
};
- await workspace.entries.createEntry({
+ await workspace.nodes.createNode({
id,
attributes,
parentId: input.spaceId,
diff --git a/apps/desktop/src/main/mutations/channels/channel-delete.ts b/apps/desktop/src/main/mutations/channels/channel-delete.ts
index f679d940..67e01dc0 100644
--- a/apps/desktop/src/main/mutations/channels/channel-delete.ts
+++ b/apps/desktop/src/main/mutations/channels/channel-delete.ts
@@ -13,7 +13,7 @@ export class ChannelDeleteMutationHandler
input: ChannelDeleteMutationInput
): Promise<ChannelDeleteMutationOutput> {
const workspace = this.getWorkspace(input.accountId, input.workspaceId);
- await workspace.entries.deleteEntry(input.channelId);
+ await workspace.nodes.deleteNode(input.channelId);
return {
success: true,
diff --git a/apps/desktop/src/main/mutations/channels/channel-update.ts b/apps/desktop/src/main/mutations/channels/channel-update.ts
index 74d1b4d8..6177b816 100644
--- a/apps/desktop/src/main/mutations/channels/channel-update.ts
+++ b/apps/desktop/src/main/mutations/channels/channel-update.ts
@@ -17,7 +17,7 @@ export class ChannelUpdateMutationHandler
): Promise<ChannelUpdateMutationOutput> {
const workspace = this.getWorkspace(input.accountId, input.workspaceId);
- const result = await workspace.entries.updateEntry<ChannelAttributes>(
+ const result = await workspace.nodes.updateNode<ChannelAttributes>(
input.channelId,
(attributes) => {
attributes.name = input.name;
diff --git a/apps/desktop/src/main/mutations/chats/chat-create.ts b/apps/desktop/src/main/mutations/chats/chat-create.ts
index 3700804b..830fa1a6 100644
--- a/apps/desktop/src/main/mutations/chats/chat-create.ts
+++ b/apps/desktop/src/main/mutations/chats/chat-create.ts
@@ -23,7 +23,7 @@ export class ChatCreateMutationHandler
const query = sql<ChatRow>`
SELECT id
- FROM entries
+ FROM nodes
WHERE type = 'chat'
AND json_extract(attributes, '$.collaborators.${sql.raw(input.userId)}') is not null
AND json_extract(attributes, '$.collaborators.${sql.raw(workspace.userId)}') is not null
@@ -46,7 +46,7 @@ export class ChatCreateMutationHandler
},
};
- await workspace.entries.createEntry({
+ await workspace.nodes.createNode({
id,
attributes,
parentId: null,
diff --git a/apps/desktop/src/main/mutations/databases/database-create.ts b/apps/desktop/src/main/mutations/databases/database-create.ts
index 7a507103..e90a99b9 100644
--- a/apps/desktop/src/main/mutations/databases/database-create.ts
+++ b/apps/desktop/src/main/mutations/databases/database-create.ts
@@ -4,6 +4,7 @@ import {
generateNodeIndex,
IdType,
} from '@colanode/core';
+import { DatabaseViewAttributes } from '@colanode/core/src/registry/database-view';
import { MutationHandler } from '@/main/lib/types';
import {
@@ -22,10 +23,10 @@ export class DatabaseCreateMutationHandler
const workspace = this.getWorkspace(input.accountId, input.workspaceId);
const databaseId = generateId(IdType.Database);
- const viewId = generateId(IdType.View);
+ const viewId = generateId(IdType.DatabaseView);
const fieldId = generateId(IdType.Field);
- const attributes: DatabaseAttributes = {
+ const databaseAttributes: DatabaseAttributes = {
type: 'database',
name: input.name,
avatar: input.avatar,
@@ -38,22 +39,28 @@ export class DatabaseCreateMutationHandler
name: 'Comment',
},
},
- views: {
- [viewId]: {
- id: viewId,
- type: 'table',
- name: 'Default',
- index: generateNodeIndex(null, null),
- },
- },
};
- await workspace.entries.createEntry({
+ const viewAttributes: DatabaseViewAttributes = {
+ type: 'database_view',
+ name: 'Default',
+ index: generateNodeIndex(null, null),
+ layout: 'table',
+ parentId: databaseId,
+ };
+
+ await workspace.nodes.createNode({
id: databaseId,
- attributes,
+ attributes: databaseAttributes,
parentId: input.parentId,
});
+ await workspace.nodes.createNode({
+ id: viewId,
+ attributes: viewAttributes,
+ parentId: databaseId,
+ });
+
return {
id: databaseId,
};
diff --git a/apps/desktop/src/main/mutations/databases/database-delete.ts b/apps/desktop/src/main/mutations/databases/database-delete.ts
index 10bf120b..afceafb0 100644
--- a/apps/desktop/src/main/mutations/databases/database-delete.ts
+++ b/apps/desktop/src/main/mutations/databases/database-delete.ts
@@ -13,7 +13,7 @@ export class DatabaseDeleteMutationHandler
input: DatabaseDeleteMutationInput
): Promise<DatabaseDeleteMutationOutput> {
const workspace = this.getWorkspace(input.accountId, input.workspaceId);
- await workspace.entries.deleteEntry(input.databaseId);
+ await workspace.nodes.deleteNode(input.databaseId);
return {
success: true,
diff --git a/apps/desktop/src/main/mutations/databases/database-update.ts b/apps/desktop/src/main/mutations/databases/database-update.ts
index bac79f29..039c7350 100644
--- a/apps/desktop/src/main/mutations/databases/database-update.ts
+++ b/apps/desktop/src/main/mutations/databases/database-update.ts
@@ -16,7 +16,7 @@ export class DatabaseUpdateMutationHandler
input: DatabaseUpdateMutationInput
): Promise<DatabaseUpdateMutationOutput> {
const workspace = this.getWorkspace(input.accountId, input.workspaceId);
- const result = await workspace.entries.updateEntry<DatabaseAttributes>(
+ const result = await workspace.nodes.updateNode<DatabaseAttributes>(
input.databaseId,
(attributes) => {
attributes.name = input.name;
diff --git a/apps/desktop/src/main/mutations/databases/field-create.ts b/apps/desktop/src/main/mutations/databases/field-create.ts
index 0fcba563..c3bd7069 100644
--- a/apps/desktop/src/main/mutations/databases/field-create.ts
+++ b/apps/desktop/src/main/mutations/databases/field-create.ts
@@ -1,5 +1,6 @@
import {
compareString,
+ DatabaseAttributes,
FieldAttributes,
FieldType,
generateId,
@@ -13,7 +14,7 @@ import {
FieldCreateMutationOutput,
} from '@/shared/mutations/databases/field-create';
import { MutationError, MutationErrorCode } from '@/shared/mutations';
-import { fetchEntry } from '@/main/lib/utils';
+import { fetchNode } from '@/main/lib/utils';
import { WorkspaceMutationHandlerBase } from '@/main/mutations/workspace-mutation-handler-base';
export class FieldCreateMutationHandler
@@ -33,7 +34,7 @@ export class FieldCreateMutationHandler
);
}
- const relationDatabase = await fetchEntry(
+ const relationDatabase = await fetchNode(
workspace.database,
input.relationDatabaseId
);
@@ -47,13 +48,9 @@ export class FieldCreateMutationHandler
}
const fieldId = generateId(IdType.Field);
- const result = await workspace.entries.updateEntry(
+ const result = await workspace.nodes.updateNode<DatabaseAttributes>(
input.databaseId,
(attributes) => {
- if (attributes.type !== 'database') {
- throw new Error('Invalid node type');
- }
-
const maxIndex = Object.values(attributes.fields)
.map((field) => field.index)
.sort((a, b) => -compareString(a, b))[0];
diff --git a/apps/desktop/src/main/mutations/databases/field-delete.ts b/apps/desktop/src/main/mutations/databases/field-delete.ts
index 0f74e98b..9c957f83 100644
--- a/apps/desktop/src/main/mutations/databases/field-delete.ts
+++ b/apps/desktop/src/main/mutations/databases/field-delete.ts
@@ -17,7 +17,7 @@ export class FieldDeleteMutationHandler
): Promise<FieldDeleteMutationOutput> {
const workspace = this.getWorkspace(input.accountId, input.workspaceId);
- const result = await workspace.entries.updateEntry<DatabaseAttributes>(
+ const result = await workspace.nodes.updateNode<DatabaseAttributes>(
input.databaseId,
(attributes) => {
delete attributes.fields[input.fieldId];
diff --git a/apps/desktop/src/main/mutations/databases/field-name-update.ts b/apps/desktop/src/main/mutations/databases/field-name-update.ts
index 174a4b3b..9f8baac5 100644
--- a/apps/desktop/src/main/mutations/databases/field-name-update.ts
+++ b/apps/desktop/src/main/mutations/databases/field-name-update.ts
@@ -17,7 +17,7 @@ export class FieldNameUpdateMutationHandler
): Promise<FieldNameUpdateMutationOutput> {
const workspace = this.getWorkspace(input.accountId, input.workspaceId);
- const result = await workspace.entries.updateEntry<DatabaseAttributes>(
+ const result = await workspace.nodes.updateNode<DatabaseAttributes>(
input.databaseId,
(attributes) => {
const field = attributes.fields[input.fieldId];
diff --git a/apps/desktop/src/main/mutations/databases/select-option-create.ts b/apps/desktop/src/main/mutations/databases/select-option-create.ts
index 10d60fb8..18173610 100644
--- a/apps/desktop/src/main/mutations/databases/select-option-create.ts
+++ b/apps/desktop/src/main/mutations/databases/select-option-create.ts
@@ -24,7 +24,7 @@ export class SelectOptionCreateMutationHandler
const workspace = this.getWorkspace(input.accountId, input.workspaceId);
const id = generateId(IdType.SelectOption);
- const result = await workspace.entries.updateEntry<DatabaseAttributes>(
+ const result = await workspace.nodes.updateNode<DatabaseAttributes>(
input.databaseId,
(attributes) => {
const field = attributes.fields[input.fieldId];
@@ -35,7 +35,7 @@ export class SelectOptionCreateMutationHandler
);
}
- if (field.type !== 'select' && field.type !== 'multiSelect') {
+ if (field.type !== 'multi_select' && field.type !== 'select') {
throw new MutationError(
MutationErrorCode.FieldTypeInvalid,
'The field you are trying to create a select option in is not a "Select" or "Multi-Select" field.'
diff --git a/apps/desktop/src/main/mutations/databases/select-option-delete.ts b/apps/desktop/src/main/mutations/databases/select-option-delete.ts
index 55bb2199..da1e56f3 100644
--- a/apps/desktop/src/main/mutations/databases/select-option-delete.ts
+++ b/apps/desktop/src/main/mutations/databases/select-option-delete.ts
@@ -17,7 +17,7 @@ export class SelectOptionDeleteMutationHandler
): Promise<SelectOptionDeleteMutationOutput> {
const workspace = this.getWorkspace(input.accountId, input.workspaceId);
- const result = await workspace.entries.updateEntry<DatabaseAttributes>(
+ const result = await workspace.nodes.updateNode<DatabaseAttributes>(
input.databaseId,
(attributes) => {
const field = attributes.fields[input.fieldId];
@@ -28,7 +28,7 @@ export class SelectOptionDeleteMutationHandler
);
}
- if (field.type !== 'select' && field.type !== 'multiSelect') {
+ if (field.type !== 'multi_select' && field.type !== 'select') {
throw new MutationError(
MutationErrorCode.FieldTypeInvalid,
'The field you are trying to delete a select option from is not a "Select" or "Multi-Select" field.'
diff --git a/apps/desktop/src/main/mutations/databases/select-option-update.ts b/apps/desktop/src/main/mutations/databases/select-option-update.ts
index cef7399e..94f060d0 100644
--- a/apps/desktop/src/main/mutations/databases/select-option-update.ts
+++ b/apps/desktop/src/main/mutations/databases/select-option-update.ts
@@ -17,7 +17,7 @@ export class SelectOptionUpdateMutationHandler
): Promise<SelectOptionUpdateMutationOutput> {
const workspace = this.getWorkspace(input.accountId, input.workspaceId);
- const result = await workspace.entries.updateEntry<DatabaseAttributes>(
+ const result = await workspace.nodes.updateNode<DatabaseAttributes>(
input.databaseId,
(attributes) => {
const field = attributes.fields[input.fieldId];
@@ -28,7 +28,7 @@ export class SelectOptionUpdateMutationHandler
);
}
- if (field.type !== 'select' && field.type !== 'multiSelect') {
+ if (field.type !== 'multi_select' && field.type !== 'select') {
throw new MutationError(
MutationErrorCode.FieldTypeInvalid,
'The field you are trying to update a select option in is not a "Select" or "Multi-Select" field.'
diff --git a/apps/desktop/src/main/mutations/databases/view-create.ts b/apps/desktop/src/main/mutations/databases/view-create.ts
index 5fa3433a..65bda6be 100644
--- a/apps/desktop/src/main/mutations/databases/view-create.ts
+++ b/apps/desktop/src/main/mutations/databases/view-create.ts
@@ -1,9 +1,8 @@
import {
- compareString,
- DatabaseAttributes,
generateId,
generateNodeIndex,
IdType,
+ DatabaseViewAttributes,
} from '@colanode/core';
import { MutationHandler } from '@/main/lib/types';
@@ -11,8 +10,8 @@ import {
ViewCreateMutationInput,
ViewCreateMutationOutput,
} from '@/shared/mutations/databases/view-create';
-import { MutationError, MutationErrorCode } from '@/shared/mutations';
import { WorkspaceMutationHandlerBase } from '@/main/mutations/workspace-mutation-handler-base';
+import { mapNode } from '@/main/lib/mappers';
export class ViewCreateMutationHandler
extends WorkspaceMutationHandlerBase
@@ -23,39 +22,40 @@ export class ViewCreateMutationHandler
): Promise<ViewCreateMutationOutput> {
const workspace = this.getWorkspace(input.accountId, input.workspaceId);
- const id = generateId(IdType.View);
- const result = await workspace.entries.updateEntry<DatabaseAttributes>(
- input.databaseId,
- (attributes) => {
- const maxIndex = Object.values(attributes.views)
- .map((view) => view.index)
- .sort((a, b) => -compareString(a, b))[0];
+ const id = generateId(IdType.DatabaseView);
+ const otherViews = await workspace.database
+ .selectFrom('nodes')
+ .selectAll()
+ .where('parent_id', '=', input.databaseId)
+ .where('type', '=', 'database_view')
+ .execute();
- attributes.views[id] = {
- id: id,
- type: input.viewType,
- name: input.name,
- groupBy: input.groupBy,
- index: generateNodeIndex(maxIndex, null),
- };
-
- return attributes;
+ let maxIndex: string | null = null;
+ for (const otherView of otherViews) {
+ const view = mapNode(otherView);
+ if (view.attributes.type !== 'database_view') {
+ continue;
}
- );
- if (result === 'unauthorized') {
- throw new MutationError(
- MutationErrorCode.ViewCreateForbidden,
- "You don't have permission to create a view in this database."
- );
+ const index = view.attributes.index;
+ if (maxIndex === null || index > maxIndex) {
+ maxIndex = index;
+ }
}
- if (result !== 'success') {
- throw new MutationError(
- MutationErrorCode.ViewCreateFailed,
- 'Something went wrong while creating the view.'
- );
- }
+ const attributes: DatabaseViewAttributes = {
+ type: 'database_view',
+ name: input.name,
+ index: generateNodeIndex(maxIndex, null),
+ layout: input.viewType,
+ parentId: input.databaseId,
+ };
+
+ await workspace.nodes.createNode({
+ id: id,
+ attributes: attributes,
+ parentId: input.databaseId,
+ });
return {
id: id,
diff --git a/apps/desktop/src/main/mutations/databases/view-delete.ts b/apps/desktop/src/main/mutations/databases/view-delete.ts
index 76c6d0be..3a5a8e67 100644
--- a/apps/desktop/src/main/mutations/databases/view-delete.ts
+++ b/apps/desktop/src/main/mutations/databases/view-delete.ts
@@ -1,7 +1,4 @@
-import { DatabaseAttributes } from '@colanode/core';
-
import { MutationHandler } from '@/main/lib/types';
-import { MutationError, MutationErrorCode } from '@/shared/mutations';
import {
ViewDeleteMutationInput,
ViewDeleteMutationOutput,
@@ -16,35 +13,7 @@ export class ViewDeleteMutationHandler
input: ViewDeleteMutationInput
): Promise<ViewDeleteMutationOutput> {
const workspace = this.getWorkspace(input.accountId, input.workspaceId);
-
- const result = await workspace.entries.updateEntry<DatabaseAttributes>(
- input.databaseId,
- (attributes) => {
- if (!attributes.views[input.viewId]) {
- throw new MutationError(
- MutationErrorCode.ViewNotFound,
- 'The view you are trying to delete does not exist.'
- );
- }
-
- delete attributes.views[input.viewId];
- return attributes;
- }
- );
-
- if (result === 'unauthorized') {
- throw new MutationError(
- MutationErrorCode.ViewDeleteForbidden,
- "You don't have permission to delete this view."
- );
- }
-
- if (result !== 'success') {
- throw new MutationError(
- MutationErrorCode.ViewDeleteFailed,
- 'Something went wrong while deleting the view.'
- );
- }
+ await workspace.nodes.deleteNode(input.viewId);
return {
id: input.viewId,
diff --git a/apps/desktop/src/main/mutations/databases/view-name-update.ts b/apps/desktop/src/main/mutations/databases/view-name-update.ts
index 81d3312b..8f4b730e 100644
--- a/apps/desktop/src/main/mutations/databases/view-name-update.ts
+++ b/apps/desktop/src/main/mutations/databases/view-name-update.ts
@@ -1,12 +1,12 @@
-import { DatabaseAttributes } from '@colanode/core';
+import { DatabaseViewAttributes } from '@colanode/core';
import { MutationHandler } from '@/main/lib/types';
-import { MutationError, MutationErrorCode } from '@/shared/mutations';
import {
ViewNameUpdateMutationInput,
ViewNameUpdateMutationOutput,
} from '@/shared/mutations/databases/view-name-update';
import { WorkspaceMutationHandlerBase } from '@/main/mutations/workspace-mutation-handler-base';
+import { MutationErrorCode, MutationError } from '@/shared/mutations';
export class ViewNameUpdateMutationHandler
extends WorkspaceMutationHandlerBase
@@ -17,18 +17,10 @@ export class ViewNameUpdateMutationHandler
): Promise<ViewNameUpdateMutationOutput> {
const workspace = this.getWorkspace(input.accountId, input.workspaceId);
- const result = await workspace.entries.updateEntry<DatabaseAttributes>(
- input.databaseId,
+ const result = await workspace.nodes.updateNode<DatabaseViewAttributes>(
+ input.viewId,
(attributes) => {
- const view = attributes.views[input.viewId];
- if (!view) {
- throw new MutationError(
- MutationErrorCode.ViewNotFound,
- 'The view you are trying to update the name of does not exist.'
- );
- }
-
- view.name = input.name;
+ attributes.name = input.name;
return attributes;
}
);
diff --git a/apps/desktop/src/main/mutations/databases/view-update.ts b/apps/desktop/src/main/mutations/databases/view-update.ts
index 1b1b63ff..4661ea96 100644
--- a/apps/desktop/src/main/mutations/databases/view-update.ts
+++ b/apps/desktop/src/main/mutations/databases/view-update.ts
@@ -1,4 +1,4 @@
-import { DatabaseAttributes } from '@colanode/core';
+import { DatabaseViewAttributes } from '@colanode/core';
import { MutationHandler } from '@/main/lib/types';
import { MutationError, MutationErrorCode } from '@/shared/mutations';
@@ -17,18 +17,10 @@ export class ViewUpdateMutationHandler
): Promise<ViewUpdateMutationOutput> {
const workspace = this.getWorkspace(input.accountId, input.workspaceId);
- const result = await workspace.entries.updateEntry<DatabaseAttributes>(
- input.databaseId,
- (attributes) => {
- if (!attributes.views[input.view.id]) {
- throw new MutationError(
- MutationErrorCode.ViewNotFound,
- 'The view you are trying to update does not exist.'
- );
- }
-
- attributes.views[input.view.id] = input.view;
- return attributes;
+ const result = await workspace.nodes.updateNode<DatabaseViewAttributes>(
+ input.viewId,
+ () => {
+ return input.view;
}
);
@@ -47,7 +39,7 @@ export class ViewUpdateMutationHandler
}
return {
- id: input.view.id,
+ id: input.viewId,
};
}
}
diff --git a/apps/desktop/src/main/mutations/files/file-create.ts b/apps/desktop/src/main/mutations/files/file-create.ts
index b673e50c..1d171c51 100644
--- a/apps/desktop/src/main/mutations/files/file-create.ts
+++ b/apps/desktop/src/main/mutations/files/file-create.ts
@@ -1,9 +1,8 @@
import {
- canCreateFile,
- CreateFileMutationData,
- FileStatus,
+ canCreateNode,
generateId,
IdType,
+ FileAttributes,
} from '@colanode/core';
import { MutationHandler } from '@/main/lib/types';
@@ -12,15 +11,8 @@ import {
FileCreateMutationOutput,
} from '@/shared/mutations/files/file-create';
import { MutationError, MutationErrorCode } from '@/shared/mutations';
-import { eventBus } from '@/shared/lib/event-bus';
-import {
- fetchEntry,
- fetchUserStorageUsed,
- getFileMetadata,
-} from '@/main/lib/utils';
-import { mapEntry, mapFile } from '@/main/lib/mappers';
-import { formatBytes } from '@/shared/lib/files';
-import { DownloadStatus, UploadStatus } from '@/shared/types/files';
+import { fetchNode } from '@/main/lib/utils';
+import { mapNode } from '@/main/lib/mappers';
import { WorkspaceMutationHandlerBase } from '@/main/mutations/workspace-mutation-handler-base';
export class FileCreateMutationHandler
@@ -30,50 +22,16 @@ export class FileCreateMutationHandler
async handleMutation(
input: FileCreateMutationInput
): Promise<FileCreateMutationOutput> {
- const metadata = getFileMetadata(input.filePath);
- if (!metadata) {
- throw new MutationError(
- MutationErrorCode.FileInvalid,
- 'File is invalid or could not be read.'
- );
- }
-
const workspace = this.getWorkspace(input.accountId, input.workspaceId);
-
- if (metadata.size > workspace.maxFileSize) {
+ const node = await fetchNode(workspace.database, input.parentId);
+ if (!node) {
throw new MutationError(
- MutationErrorCode.FileTooLarge,
- 'The file you are trying to upload is too large. The maximum file size is ' +
- formatBytes(workspace.maxFileSize)
+ MutationErrorCode.NodeNotFound,
+ 'There was an error while fetching the node. Please make sure you have access to this node.'
);
}
- const storageUsed = await fetchUserStorageUsed(
- workspace.database,
- workspace.userId
- );
-
- if (storageUsed + BigInt(metadata.size) > workspace.storageLimit) {
- throw new MutationError(
- MutationErrorCode.StorageLimitExceeded,
- 'You have reached your storage limit. You have used ' +
- formatBytes(storageUsed) +
- ' and you are trying to upload a file of size ' +
- formatBytes(metadata.size) +
- '. Your storage limit is ' +
- formatBytes(workspace.storageLimit)
- );
- }
-
- const entry = await fetchEntry(workspace.database, input.entryId);
- if (!entry) {
- throw new MutationError(
- MutationErrorCode.EntryNotFound,
- 'There was an error while fetching the entry. Please make sure you have access to this entry.'
- );
- }
-
- const root = await fetchEntry(workspace.database, input.rootId);
+ const root = await fetchNode(workspace.database, node.root_id);
if (!root) {
throw new MutationError(
MutationErrorCode.RootNotFound,
@@ -81,131 +39,35 @@ export class FileCreateMutationHandler
);
}
- const fileId = generateId(IdType.File);
+ const attributes: FileAttributes = {
+ type: 'file',
+ parentId: node.id,
+ };
+
if (
- !canCreateFile({
- user: {
- userId: workspace.userId,
- role: workspace.role,
- },
- root: mapEntry(root),
- entry: mapEntry(entry),
- file: {
- id: fileId,
- parentId: input.parentId,
+ !canCreateNode(
+ {
+ user: {
+ userId: workspace.userId,
+ role: workspace.role,
+ },
+ root: mapNode(root),
},
- })
+ 'file'
+ )
) {
throw new MutationError(
MutationErrorCode.FileCreateForbidden,
- 'You are not allowed to upload a file in this entry.'
+ 'You are not allowed to upload a file in this node.'
);
}
- workspace.files.copyFileToWorkspace(
- input.filePath,
- fileId,
- metadata.extension
- );
-
- const mutationData: CreateFileMutationData = {
+ const fileId = generateId(IdType.File);
+ await workspace.files.createFile(input.filePath, fileId, node.id, root);
+ await workspace.nodes.createNode({
id: fileId,
- type: metadata.type,
- parentId: input.parentId,
- entryId: input.entryId,
- rootId: input.rootId,
- name: metadata.name,
- originalName: metadata.name,
- extension: metadata.extension,
- mimeType: metadata.mimeType,
- size: metadata.size,
- createdAt: new Date().toISOString(),
- };
-
- const createdFile = await workspace.database
- .transaction()
- .execute(async (tx) => {
- const createdFile = await tx
- .insertInto('files')
- .returningAll()
- .values({
- id: fileId,
- type: metadata.type,
- parent_id: input.parentId,
- entry_id: input.entryId,
- root_id: input.rootId,
- name: metadata.name,
- original_name: metadata.name,
- mime_type: metadata.mimeType,
- size: metadata.size,
- extension: metadata.extension,
- created_at: new Date().toISOString(),
- created_by: workspace.userId,
- status: FileStatus.Pending,
- version: 0n,
- })
- .executeTakeFirst();
-
- if (!createdFile) {
- throw new Error('Failed to create file.');
- }
-
- await tx
- .insertInto('file_states')
- .values({
- file_id: fileId,
- created_at: new Date().toISOString(),
- download_progress: 100,
- download_status: DownloadStatus.Completed,
- download_retries: 0,
- upload_progress: 0,
- upload_status: UploadStatus.Pending,
- upload_retries: 0,
- })
- .execute();
-
- await tx
- .insertInto('mutations')
- .values({
- id: generateId(IdType.Mutation),
- type: 'create_file',
- data: JSON.stringify(mutationData),
- created_at: new Date().toISOString(),
- retries: 0,
- })
- .execute();
-
- return createdFile;
- });
-
- if (!createdFile) {
- throw new Error('Failed to create file.');
- }
-
- workspace.mutations.triggerSync();
-
- eventBus.publish({
- type: 'file_created',
- accountId: workspace.accountId,
- workspaceId: workspace.id,
- file: mapFile(createdFile),
- });
-
- eventBus.publish({
- type: 'file_state_created',
- accountId: workspace.accountId,
- workspaceId: workspace.id,
- fileState: {
- fileId: fileId,
- downloadProgress: 100,
- downloadStatus: DownloadStatus.Completed,
- downloadRetries: 0,
- uploadProgress: 10,
- uploadStatus: UploadStatus.Pending,
- uploadRetries: 0,
- createdAt: new Date().toISOString(),
- updatedAt: null,
- },
+ attributes,
+ parentId: node.id,
});
return {
diff --git a/apps/desktop/src/main/mutations/files/file-delete.ts b/apps/desktop/src/main/mutations/files/file-delete.ts
index cbbefd52..53b1be09 100644
--- a/apps/desktop/src/main/mutations/files/file-delete.ts
+++ b/apps/desktop/src/main/mutations/files/file-delete.ts
@@ -1,19 +1,8 @@
-import {
- canDeleteFile,
- DeleteFileMutationData,
- generateId,
- IdType,
-} from '@colanode/core';
-
import { MutationHandler } from '@/main/lib/types';
import {
FileDeleteMutationInput,
FileDeleteMutationOutput,
} from '@/shared/mutations/files/file-delete';
-import { eventBus } from '@/shared/lib/event-bus';
-import { fetchEntry } from '@/main/lib/utils';
-import { mapEntry, mapFile } from '@/main/lib/mappers';
-import { MutationError, MutationErrorCode } from '@/shared/mutations';
import { WorkspaceMutationHandlerBase } from '@/main/mutations/workspace-mutation-handler-base';
export class FileDeleteMutationHandler
@@ -24,93 +13,7 @@ export class FileDeleteMutationHandler
input: FileDeleteMutationInput
): Promise<FileDeleteMutationOutput> {
const workspace = this.getWorkspace(input.accountId, input.workspaceId);
-
- const file = await workspace.database
- .selectFrom('files')
- .selectAll()
- .where('id', '=', input.fileId)
- .executeTakeFirst();
-
- if (!file) {
- throw new MutationError(
- MutationErrorCode.FileNotFound,
- 'File could not be found or has been already deleted.'
- );
- }
-
- const entry = await fetchEntry(workspace.database, file.root_id);
- if (!entry) {
- throw new MutationError(
- MutationErrorCode.EntryNotFound,
- 'There was an error while fetching the entry. Please make sure you have access to this entry.'
- );
- }
-
- const root = await fetchEntry(workspace.database, entry.root_id);
- if (!root) {
- throw new MutationError(
- MutationErrorCode.RootNotFound,
- 'There was an error while fetching the root. Please make sure you have access to this root.'
- );
- }
-
- if (
- !canDeleteFile({
- user: {
- userId: workspace.userId,
- role: workspace.role,
- },
- root: mapEntry(root),
- entry: mapEntry(entry),
- file: {
- id: input.fileId,
- parentId: file.parent_id,
- createdBy: file.created_by,
- },
- })
- ) {
- throw new MutationError(
- MutationErrorCode.FileDeleteForbidden,
- 'You are not allowed to delete this file.'
- );
- }
-
- const deletedAt = new Date().toISOString();
- const deleteFileMutationData: DeleteFileMutationData = {
- id: input.fileId,
- rootId: file.root_id,
- deletedAt,
- };
-
- await workspace.database.transaction().execute(async (tx) => {
- await tx
- .updateTable('files')
- .set({
- deleted_at: deletedAt,
- })
- .where('id', '=', input.fileId)
- .execute();
-
- await tx
- .insertInto('mutations')
- .values({
- id: generateId(IdType.Mutation),
- type: 'delete_file',
- data: JSON.stringify(deleteFileMutationData),
- created_at: deletedAt,
- retries: 0,
- })
- .execute();
- });
-
- workspace.mutations.triggerSync();
-
- eventBus.publish({
- type: 'file_deleted',
- accountId: workspace.accountId,
- workspaceId: workspace.id,
- file: mapFile(file),
- });
+ await workspace.nodes.deleteNode(input.fileId);
return {
success: true,
diff --git a/apps/desktop/src/main/mutations/files/file-download.ts b/apps/desktop/src/main/mutations/files/file-download.ts
index 6f98f0da..e81b4f1a 100644
--- a/apps/desktop/src/main/mutations/files/file-download.ts
+++ b/apps/desktop/src/main/mutations/files/file-download.ts
@@ -1,14 +1,14 @@
import { FileStatus } from '@colanode/core';
import { MutationHandler } from '@/main/lib/types';
-import { mapFileState } from '@/main/lib/mappers';
+import { mapFile } from '@/main/lib/mappers';
import { eventBus } from '@/shared/lib/event-bus';
import { MutationError, MutationErrorCode } from '@/shared/mutations';
import {
FileDownloadMutationInput,
FileDownloadMutationOutput,
} from '@/shared/mutations/files/file-download';
-import { DownloadStatus, UploadStatus } from '@/shared/types/files';
+import { DownloadStatus } from '@/shared/types/files';
import { WorkspaceMutationHandlerBase } from '@/main/mutations/workspace-mutation-handler-base';
export class FileDownloadMutationHandler
@@ -40,55 +40,41 @@ export class FileDownloadMutationHandler
);
}
- const existingFileState = await workspace.database
- .selectFrom('file_states')
- .selectAll()
- .where('file_id', '=', input.fileId)
- .executeTakeFirst();
-
if (
- existingFileState &&
- existingFileState.download_status === DownloadStatus.Completed
+ file.download_status === DownloadStatus.Completed ||
+ file.download_status === DownloadStatus.Pending
) {
return {
success: true,
};
}
- const fileState = await workspace.database
- .insertInto('file_states')
+ const updatedFile = await workspace.database
+ .updateTable('files')
.returningAll()
- .values({
- file_id: input.fileId,
+ .set({
download_status: DownloadStatus.Pending,
download_progress: 0,
download_retries: 0,
- upload_status: UploadStatus.None,
- upload_progress: 0,
- upload_retries: 0,
- created_at: new Date().toISOString(),
+ updated_at: new Date().toISOString(),
})
- .onConflict((oc) =>
- oc.doUpdateSet(() => ({
- download_status: DownloadStatus.Pending,
- download_progress: 0,
- download_retries: 0,
- updated_at: new Date().toISOString(),
- }))
- )
+ .where('id', '=', input.fileId)
.executeTakeFirst();
- if (!fileState) {
- throw new Error('Failed to create file state.');
+ if (!updatedFile) {
+ throw new MutationError(
+ MutationErrorCode.FileNotFound,
+ 'The file you are trying to download does not exist.'
+ );
}
workspace.files.triggerDownloads();
eventBus.publish({
- type: 'file_state_created',
+ type: 'file_updated',
accountId: workspace.accountId,
workspaceId: workspace.id,
- fileState: mapFileState(fileState),
+ file: mapFile(updatedFile),
});
return {
diff --git a/apps/desktop/src/main/mutations/files/file-mark-opened.ts b/apps/desktop/src/main/mutations/files/file-mark-opened.ts
deleted file mode 100644
index 85905b1a..00000000
--- a/apps/desktop/src/main/mutations/files/file-mark-opened.ts
+++ /dev/null
@@ -1,129 +0,0 @@
-import { MarkFileOpenedMutation, generateId, IdType } from '@colanode/core';
-
-import { MutationHandler } from '@/main/lib/types';
-import {
- FileMarkOpenedMutationInput,
- FileMarkOpenedMutationOutput,
-} from '@/shared/mutations/files/file-mark-opened';
-import { eventBus } from '@/shared/lib/event-bus';
-import { mapFileInteraction } from '@/main/lib/mappers';
-import { WorkspaceMutationHandlerBase } from '@/main/mutations/workspace-mutation-handler-base';
-
-export class FileMarkOpenedMutationHandler
- extends WorkspaceMutationHandlerBase
- implements MutationHandler<FileMarkOpenedMutationInput>
-{
- async handleMutation(
- input: FileMarkOpenedMutationInput
- ): Promise<FileMarkOpenedMutationOutput> {
- const workspace = this.getWorkspace(input.accountId, input.workspaceId);
-
- const file = await workspace.database
- .selectFrom('files')
- .selectAll()
- .where('id', '=', input.fileId)
- .executeTakeFirst();
-
- if (!file) {
- return {
- success: false,
- };
- }
-
- const existingInteraction = await workspace.database
- .selectFrom('file_interactions')
- .selectAll()
- .where('file_id', '=', input.fileId)
- .where('collaborator_id', '=', workspace.userId)
- .executeTakeFirst();
-
- if (existingInteraction) {
- const lastOpenedAt = existingInteraction.last_opened_at;
- if (
- lastOpenedAt &&
- lastOpenedAt > new Date(Date.now() - 5 * 60 * 1000).toISOString()
- ) {
- return {
- success: true,
- };
- }
- }
-
- const lastOpenedAt = new Date().toISOString();
- const firstOpenedAt = existingInteraction
- ? existingInteraction.first_opened_at
- : lastOpenedAt;
-
- const { createdInteraction, createdMutation } = await workspace.database
- .transaction()
- .execute(async (trx) => {
- const createdInteraction = await trx
- .insertInto('file_interactions')
- .returningAll()
- .values({
- file_id: input.fileId,
- collaborator_id: workspace.userId,
- last_opened_at: lastOpenedAt,
- first_opened_at: firstOpenedAt,
- version: 0n,
- root_id: file.root_id,
- })
- .onConflict((b) =>
- b.columns(['file_id', 'collaborator_id']).doUpdateSet({
- last_opened_at: lastOpenedAt,
- first_opened_at: firstOpenedAt,
- })
- )
- .executeTakeFirst();
-
- if (!createdInteraction) {
- throw new Error('Failed to create file interaction');
- }
-
- const mutation: MarkFileOpenedMutation = {
- id: generateId(IdType.Mutation),
- createdAt: new Date().toISOString(),
- type: 'mark_file_opened',
- data: {
- fileId: input.fileId,
- collaboratorId: workspace.userId,
- openedAt: new Date().toISOString(),
- },
- };
-
- const createdMutation = await trx
- .insertInto('mutations')
- .returningAll()
- .values({
- id: mutation.id,
- type: mutation.type,
- data: JSON.stringify(mutation.data),
- created_at: mutation.createdAt,
- retries: 0,
- })
- .executeTakeFirst();
-
- return {
- createdInteraction,
- createdMutation,
- };
- });
-
- if (!createdInteraction || !createdMutation) {
- throw new Error('Failed to create file interaction');
- }
-
- workspace.mutations.triggerSync();
-
- eventBus.publish({
- type: 'file_interaction_updated',
- accountId: workspace.accountId,
- workspaceId: workspace.id,
- fileInteraction: mapFileInteraction(createdInteraction),
- });
-
- return {
- success: true,
- };
- }
-}
diff --git a/apps/desktop/src/main/mutations/files/file-mark-seen.ts b/apps/desktop/src/main/mutations/files/file-mark-seen.ts
deleted file mode 100644
index 2f1317a1..00000000
--- a/apps/desktop/src/main/mutations/files/file-mark-seen.ts
+++ /dev/null
@@ -1,129 +0,0 @@
-import { MarkFileSeenMutation, generateId, IdType } from '@colanode/core';
-
-import { MutationHandler } from '@/main/lib/types';
-import {
- FileMarkSeenMutationInput,
- FileMarkSeenMutationOutput,
-} from '@/shared/mutations/files/file-mark-seen';
-import { eventBus } from '@/shared/lib/event-bus';
-import { mapFileInteraction } from '@/main/lib/mappers';
-import { WorkspaceMutationHandlerBase } from '@/main/mutations/workspace-mutation-handler-base';
-
-export class FileMarkSeenMutationHandler
- extends WorkspaceMutationHandlerBase
- implements MutationHandler<FileMarkSeenMutationInput>
-{
- async handleMutation(
- input: FileMarkSeenMutationInput
- ): Promise<FileMarkSeenMutationOutput> {
- const workspace = this.getWorkspace(input.accountId, input.workspaceId);
-
- const file = await workspace.database
- .selectFrom('files')
- .selectAll()
- .where('id', '=', input.fileId)
- .executeTakeFirst();
-
- if (!file) {
- return {
- success: false,
- };
- }
-
- const existingInteraction = await workspace.database
- .selectFrom('file_interactions')
- .selectAll()
- .where('file_id', '=', input.fileId)
- .where('collaborator_id', '=', workspace.userId)
- .executeTakeFirst();
-
- if (existingInteraction) {
- const lastSeenAt = existingInteraction.last_seen_at;
- if (
- lastSeenAt &&
- lastSeenAt > new Date(Date.now() - 5 * 60 * 1000).toISOString()
- ) {
- return {
- success: true,
- };
- }
- }
-
- const lastSeenAt = new Date().toISOString();
- const firstSeenAt = existingInteraction
- ? existingInteraction.first_seen_at
- : lastSeenAt;
-
- const { createdInteraction, createdMutation } = await workspace.database
- .transaction()
- .execute(async (trx) => {
- const createdInteraction = await trx
- .insertInto('file_interactions')
- .returningAll()
- .values({
- file_id: input.fileId,
- collaborator_id: workspace.userId,
- last_seen_at: lastSeenAt,
- first_seen_at: firstSeenAt,
- version: 0n,
- root_id: file.root_id,
- })
- .onConflict((b) =>
- b.columns(['file_id', 'collaborator_id']).doUpdateSet({
- last_seen_at: lastSeenAt,
- first_seen_at: firstSeenAt,
- })
- )
- .executeTakeFirst();
-
- if (!createdInteraction) {
- throw new Error('Failed to create file interaction');
- }
-
- const mutation: MarkFileSeenMutation = {
- id: generateId(IdType.Mutation),
- createdAt: new Date().toISOString(),
- type: 'mark_file_seen',
- data: {
- fileId: input.fileId,
- collaboratorId: workspace.userId,
- seenAt: new Date().toISOString(),
- },
- };
-
- const createdMutation = await trx
- .insertInto('mutations')
- .returningAll()
- .values({
- id: mutation.id,
- type: mutation.type,
- data: JSON.stringify(mutation.data),
- created_at: mutation.createdAt,
- retries: 0,
- })
- .executeTakeFirst();
-
- return {
- createdInteraction,
- createdMutation,
- };
- });
-
- if (!createdInteraction || !createdMutation) {
- throw new Error('Failed to create file interaction');
- }
-
- workspace.mutations.triggerSync();
-
- eventBus.publish({
- type: 'file_interaction_updated',
- accountId: workspace.accountId,
- workspaceId: workspace.id,
- fileInteraction: mapFileInteraction(createdInteraction),
- });
-
- return {
- success: true,
- };
- }
-}
diff --git a/apps/desktop/src/main/mutations/folders/folder-create.ts b/apps/desktop/src/main/mutations/folders/folder-create.ts
index 368cc121..e0412b54 100644
--- a/apps/desktop/src/main/mutations/folders/folder-create.ts
+++ b/apps/desktop/src/main/mutations/folders/folder-create.ts
@@ -24,7 +24,7 @@ export class FolderCreateMutationHandler
avatar: input.avatar,
};
- await workspace.entries.createEntry({
+ await workspace.nodes.createNode({
id,
attributes,
parentId: input.parentId,
diff --git a/apps/desktop/src/main/mutations/folders/folder-delete.ts b/apps/desktop/src/main/mutations/folders/folder-delete.ts
index 73c75b2b..4a1a28cd 100644
--- a/apps/desktop/src/main/mutations/folders/folder-delete.ts
+++ b/apps/desktop/src/main/mutations/folders/folder-delete.ts
@@ -14,7 +14,7 @@ export class FolderDeleteMutationHandler
): Promise<FolderDeleteMutationOutput> {
const workspace = this.getWorkspace(input.accountId, input.workspaceId);
- await workspace.entries.deleteEntry(input.folderId);
+ await workspace.nodes.deleteNode(input.folderId);
return {
success: true,
diff --git a/apps/desktop/src/main/mutations/folders/folder-update.ts b/apps/desktop/src/main/mutations/folders/folder-update.ts
index 38e32ff3..7acaedfb 100644
--- a/apps/desktop/src/main/mutations/folders/folder-update.ts
+++ b/apps/desktop/src/main/mutations/folders/folder-update.ts
@@ -17,7 +17,7 @@ export class FolderUpdateMutationHandler
): Promise<FolderUpdateMutationOutput> {
const workspace = this.getWorkspace(input.accountId, input.workspaceId);
- const result = await workspace.entries.updateEntry<FolderAttributes>(
+ const result = await workspace.nodes.updateNode<FolderAttributes>(
input.folderId,
(attributes) => {
attributes.name = input.name;
diff --git a/apps/desktop/src/main/mutations/index.ts b/apps/desktop/src/main/mutations/index.ts
index 1d26e5a1..81e63127 100644
--- a/apps/desktop/src/main/mutations/index.ts
+++ b/apps/desktop/src/main/mutations/index.ts
@@ -19,22 +19,19 @@ import { FieldNameUpdateMutationHandler } from '@/main/mutations/databases/field
import { FileCreateMutationHandler } from '@/main/mutations/files/file-create';
import { FileDeleteMutationHandler } from '@/main/mutations/files/file-delete';
import { FileDownloadMutationHandler } from '@/main/mutations/files/file-download';
-import { FileMarkOpenedMutationHandler } from '@/main/mutations/files/file-mark-opened';
-import { FileMarkSeenMutationHandler } from '@/main/mutations/files/file-mark-seen';
import { FileSaveTempMutationHandler } from '@/main/mutations/files/file-save-temp';
import { FolderCreateMutationHandler } from '@/main/mutations/folders/folder-create';
import { FolderUpdateMutationHandler } from '@/main/mutations/folders/folder-update';
import { FolderDeleteMutationHandler } from '@/main/mutations/folders/folder-delete';
import { MessageCreateMutationHandler } from '@/main/mutations/messages/message-create';
import { MessageDeleteMutationHandler } from '@/main/mutations/messages/message-delete';
-import { EntryCollaboratorCreateMutationHandler } from '@/main/mutations/entries/entry-collaborator-create';
-import { EntryCollaboratorDeleteMutationHandler } from '@/main/mutations/entries/entry-collaborator-delete';
-import { EntryCollaboratorUpdateMutationHandler } from '@/main/mutations/entries/entry-collaborator-update';
-import { EntryMarkOpenedMutationHandler } from '@/main/mutations/entries/entry-mark-opened';
-import { EntryMarkSeenMutationHandler } from '@/main/mutations/entries/entry-mark-seen';
-import { MessageReactionCreateMutationHandler } from '@/main/mutations/messages/message-reaction-create';
-import { MessageReactionDeleteMutationHandler } from '@/main/mutations/messages/message-reaction-delete';
-import { MessageMarkSeenMutationHandler } from '@/main/mutations/messages/message-mark-seen';
+import { NodeCollaboratorCreateMutationHandler } from '@/main/mutations/nodes/node-collaborator-create';
+import { NodeCollaboratorDeleteMutationHandler } from '@/main/mutations/nodes/node-collaborator-delete';
+import { NodeCollaboratorUpdateMutationHandler } from '@/main/mutations/nodes/node-collaborator-update';
+import { NodeMarkOpenedMutationHandler } from '@/main/mutations/nodes/node-mark-opened';
+import { NodeMarkSeenMutationHandler } from '@/main/mutations/nodes/node-mark-seen';
+import { NodeReactionCreateMutationHandler } from '@/main/mutations/nodes/node-reaction-create';
+import { NodeReactionDeleteMutationHandler } from '@/main/mutations/nodes/node-reaction-delete';
import { PageCreateMutationHandler } from '@/main/mutations/pages/page-create';
import { PageUpdateMutationHandler } from '@/main/mutations/pages/page-update';
import { PageDeleteMutationHandler } from '@/main/mutations/pages/page-delete';
@@ -86,17 +83,16 @@ export const mutationHandlerMap: MutationHandlerMap = {
message_create: new MessageCreateMutationHandler(),
file_delete: new FileDeleteMutationHandler(),
folder_delete: new FolderDeleteMutationHandler(),
- entry_collaborator_create: new EntryCollaboratorCreateMutationHandler(),
- entry_collaborator_delete: new EntryCollaboratorDeleteMutationHandler(),
- entry_collaborator_update: new EntryCollaboratorUpdateMutationHandler(),
- entry_mark_opened: new EntryMarkOpenedMutationHandler(),
- entry_mark_seen: new EntryMarkSeenMutationHandler(),
+ node_collaborator_create: new NodeCollaboratorCreateMutationHandler(),
+ node_collaborator_delete: new NodeCollaboratorDeleteMutationHandler(),
+ node_collaborator_update: new NodeCollaboratorUpdateMutationHandler(),
+ node_mark_opened: new NodeMarkOpenedMutationHandler(),
+ node_mark_seen: new NodeMarkSeenMutationHandler(),
page_create: new PageCreateMutationHandler(),
page_delete: new PageDeleteMutationHandler(),
page_content_update: new PageContentUpdateMutationHandler(),
- message_reaction_create: new MessageReactionCreateMutationHandler(),
- message_reaction_delete: new MessageReactionDeleteMutationHandler(),
- message_mark_seen: new MessageMarkSeenMutationHandler(),
+ node_reaction_create: new NodeReactionCreateMutationHandler(),
+ node_reaction_delete: new NodeReactionDeleteMutationHandler(),
message_delete: new MessageDeleteMutationHandler(),
record_create: new RecordCreateMutationHandler(),
record_delete: new RecordDeleteMutationHandler(),
@@ -120,8 +116,6 @@ export const mutationHandlerMap: MutationHandlerMap = {
folder_create: new FolderCreateMutationHandler(),
file_create: new FileCreateMutationHandler(),
file_download: new FileDownloadMutationHandler(),
- file_mark_opened: new FileMarkOpenedMutationHandler(),
- file_mark_seen: new FileMarkSeenMutationHandler(),
file_save_temp: new FileSaveTempMutationHandler(),
space_avatar_update: new SpaceAvatarUpdateMutationHandler(),
space_description_update: new SpaceDescriptionUpdateMutationHandler(),
diff --git a/apps/desktop/src/main/mutations/messages/message-create.ts b/apps/desktop/src/main/mutations/messages/message-create.ts
index 5a300f9a..971d65b0 100644
--- a/apps/desktop/src/main/mutations/messages/message-create.ts
+++ b/apps/desktop/src/main/mutations/messages/message-create.ts
@@ -1,14 +1,10 @@
import {
Block,
- canCreateMessage,
- CreateFileMutationData,
- CreateMessageMutationData,
+ canCreateNode,
EditorNodeTypes,
- FileStatus,
generateId,
IdType,
MessageAttributes,
- MessageType,
} from '@colanode/core';
import { MutationHandler } from '@/main/lib/types';
@@ -18,26 +14,9 @@ import {
MessageCreateMutationOutput,
} from '@/shared/mutations/messages/message-create';
import { MutationError, MutationErrorCode } from '@/shared/mutations';
-import {
- CreateFile,
- CreateFileState,
- CreateMutation,
-} from '@/main/databases/workspace';
-import { eventBus } from '@/shared/lib/event-bus';
-import {
- fetchEntry,
- fetchUserStorageUsed,
- getFileMetadata,
-} from '@/main/lib/utils';
-import {
- mapEntry,
- mapFile,
- mapFileState,
- mapMessage,
-} from '@/main/lib/mappers';
-import { formatBytes } from '@/shared/lib/files';
-import { DownloadStatus, UploadStatus } from '@/shared/types/files';
+import { fetchNode } from '@/main/lib/utils';
import { WorkspaceMutationHandlerBase } from '@/main/mutations/workspace-mutation-handler-base';
+import { mapNode } from '@/main/lib/mappers';
export class MessageCreateMutationHandler
extends WorkspaceMutationHandlerBase
@@ -48,15 +27,15 @@ export class MessageCreateMutationHandler
): Promise<MessageCreateMutationOutput> {
const workspace = this.getWorkspace(input.accountId, input.workspaceId);
- const entry = await fetchEntry(workspace.database, input.conversationId);
- if (!entry) {
+ const node = await fetchNode(workspace.database, input.parentId);
+ if (!node) {
throw new MutationError(
- MutationErrorCode.EntryNotFound,
+ MutationErrorCode.NodeNotFound,
'There was an error while fetching the conversation. Please make sure you have access to this conversation.'
);
}
- const root = await fetchEntry(workspace.database, input.rootId);
+ const root = await fetchNode(workspace.database, node.root_id);
if (!root) {
throw new MutationError(
MutationErrorCode.RootNotFound,
@@ -65,14 +44,16 @@ export class MessageCreateMutationHandler
}
if (
- !canCreateMessage({
- user: {
- userId: workspace.userId,
- role: workspace.role,
+ !canCreateNode(
+ {
+ user: {
+ userId: workspace.userId,
+ role: workspace.role,
+ },
+ root: mapNode(root),
},
- root: mapEntry(root),
- entry: mapEntry(entry),
- })
+ 'message'
+ )
) {
throw new MutationError(
MutationErrorCode.MessageCreateForbidden,
@@ -80,118 +61,21 @@ export class MessageCreateMutationHandler
);
}
- const editorContent = input.content.content ?? [];
const messageId = generateId(IdType.Message);
- const createdAt = new Date().toISOString();
+ const editorContent = input.content.content ?? [];
const blocks = mapContentsToBlocks(messageId, editorContent, new Map());
- const files: CreateFile[] = [];
- const fileStates: CreateFileState[] = [];
- const fileMutations: CreateMutation[] = [];
-
// check if there are nested nodes (files, pages, folders etc.)
for (const block of blocks) {
if (block.type === EditorNodeTypes.FilePlaceholder) {
const path = block.attrs?.path;
- const metadata = getFileMetadata(path);
- if (!metadata) {
- throw new MutationError(
- MutationErrorCode.FileInvalid,
- 'The file attachment is invalid or could not be read.'
- );
- }
+ const fileId = generateId(IdType.File);
- if (metadata.size > workspace.maxFileSize) {
- throw new MutationError(
- MutationErrorCode.FileTooLarge,
- 'The file you are trying to upload is too large. The maximum file size is ' +
- formatBytes(workspace.maxFileSize)
- );
- }
+ await workspace.files.createFile(path, fileId, messageId, root);
- const fileId = generateId(IdType.File);
block.id = fileId;
block.type = 'file';
block.attrs = null;
-
- workspace.files.copyFileToWorkspace(path, fileId, metadata.extension);
-
- files.push({
- id: fileId,
- type: metadata.type,
- status: FileStatus.Pending,
- parent_id: messageId,
- entry_id: input.conversationId,
- root_id: input.rootId,
- name: metadata.name,
- original_name: metadata.name,
- mime_type: metadata.mimeType,
- extension: metadata.extension,
- size: metadata.size,
- created_at: createdAt,
- created_by: workspace.userId,
- version: 0n,
- });
-
- const mutationData: CreateFileMutationData = {
- id: fileId,
- type: metadata.type,
- parentId: messageId,
- entryId: input.conversationId,
- rootId: input.rootId,
- name: metadata.name,
- originalName: metadata.name,
- extension: metadata.extension,
- mimeType: metadata.mimeType,
- size: metadata.size,
- createdAt: createdAt,
- };
-
- fileMutations.push({
- id: generateId(IdType.Mutation),
- type: 'create_file',
- data: JSON.stringify(mutationData),
- created_at: createdAt,
- retries: 0,
- });
-
- fileStates.push({
- file_id: fileId,
- upload_status: UploadStatus.Pending,
- upload_progress: 0,
- upload_retries: 0,
- download_status: DownloadStatus.Completed,
- download_progress: 100,
- download_retries: 0,
- created_at: createdAt,
- });
- }
- }
-
- if (files.length > 0) {
- const storageUsed = await fetchUserStorageUsed(
- workspace.database,
- workspace.userId
- );
-
- const fileSizeSum = BigInt(
- files.reduce((sum, file) => sum + file.size, 0)
- );
-
- if (storageUsed + fileSizeSum > workspace.storageLimit) {
- for (const file of files) {
- workspace.files.deleteFile(file.id, file.extension);
- }
-
- throw new MutationError(
- MutationErrorCode.StorageLimitExceeded,
- 'You have reached your storage limit. You have used ' +
- formatBytes(storageUsed) +
- ' and you are trying to upload files of size ' +
- formatBytes(fileSizeSum) +
- '. Your storage limit is ' +
- formatBytes(workspace.storageLimit)
- );
}
}
@@ -204,119 +88,18 @@ export class MessageCreateMutationHandler
);
const messageAttributes: MessageAttributes = {
- type: MessageType.Standard,
- blocks: blocksRecord,
+ type: 'message',
+ subtype: 'standard',
+ parentId: input.parentId,
+ content: blocksRecord,
referenceId: input.referenceId,
};
- const { createdMessage, createdFiles, createdFileStates } =
- await workspace.database.transaction().execute(async (tx) => {
- const createdMessage = await tx
- .insertInto('messages')
- .returningAll()
- .values({
- id: messageId,
- entry_id: input.conversationId,
- parent_id: input.conversationId,
- root_id: input.rootId,
- attributes: JSON.stringify(messageAttributes),
- created_at: createdAt,
- created_by: workspace.userId,
- version: 0n,
- })
- .executeTakeFirst();
-
- if (!createdMessage) {
- throw new Error('Failed to create message.');
- }
-
- const createMessageMutationData: CreateMessageMutationData = {
- id: messageId,
- entryId: input.conversationId,
- parentId: input.conversationId,
- rootId: input.rootId,
- attributes: messageAttributes,
- createdAt: createdAt,
- };
-
- await tx
- .insertInto('mutations')
- .values({
- id: generateId(IdType.Mutation),
- type: 'create_message',
- data: JSON.stringify(createMessageMutationData),
- created_at: createdAt,
- retries: 0,
- })
- .execute();
-
- if (files.length > 0) {
- const createdFiles = await tx
- .insertInto('files')
- .returningAll()
- .values(files)
- .execute();
-
- if (createdFiles.length !== files.length) {
- throw new Error('Failed to create files.');
- }
-
- await tx.insertInto('mutations').values(fileMutations).execute();
-
- const createdFileStates = await tx
- .insertInto('file_states')
- .returningAll()
- .values(fileStates)
- .execute();
-
- if (createdFileStates.length !== fileStates.length) {
- throw new Error('Failed to create file states.');
- }
-
- return {
- createdFiles,
- createdFileStates,
- createdMessage,
- };
- }
-
- return {
- createdMessage,
- };
- });
-
- workspace.mutations.triggerSync();
-
- if (createdMessage) {
- eventBus.publish({
- type: 'message_created',
- accountId: workspace.accountId,
- workspaceId: workspace.id,
- message: mapMessage(createdMessage),
- });
- }
-
- if (createdFiles) {
- for (const file of createdFiles) {
- eventBus.publish({
- type: 'file_created',
- accountId: workspace.accountId,
- workspaceId: workspace.id,
- file: mapFile(file),
- });
- }
- }
-
- if (createdFileStates) {
- for (const fileState of createdFileStates) {
- eventBus.publish({
- type: 'file_state_created',
- accountId: workspace.accountId,
- workspaceId: workspace.id,
- fileState: mapFileState(fileState),
- });
- }
- }
+ await workspace.nodes.createNode({
+ id: messageId,
+ attributes: messageAttributes,
+ parentId: input.parentId,
+ });
return {
id: messageId,
diff --git a/apps/desktop/src/main/mutations/messages/message-delete.ts b/apps/desktop/src/main/mutations/messages/message-delete.ts
index 0d5a42f7..c499767f 100644
--- a/apps/desktop/src/main/mutations/messages/message-delete.ts
+++ b/apps/desktop/src/main/mutations/messages/message-delete.ts
@@ -1,19 +1,8 @@
-import {
- canDeleteMessage,
- DeleteMessageMutationData,
- generateId,
- IdType,
-} from '@colanode/core';
-
import { MutationHandler } from '@/main/lib/types';
import {
MessageDeleteMutationInput,
MessageDeleteMutationOutput,
} from '@/shared/mutations/messages/message-delete';
-import { eventBus } from '@/shared/lib/event-bus';
-import { fetchEntry } from '@/main/lib/utils';
-import { mapEntry, mapMessage } from '@/main/lib/mappers';
-import { MutationError, MutationErrorCode } from '@/shared/mutations';
import { WorkspaceMutationHandlerBase } from '@/main/mutations/workspace-mutation-handler-base';
export class MessageDeleteMutationHandler
extends WorkspaceMutationHandlerBase
@@ -23,91 +12,7 @@ export class MessageDeleteMutationHandler
input: MessageDeleteMutationInput
): Promise<MessageDeleteMutationOutput> {
const workspace = this.getWorkspace(input.accountId, input.workspaceId);
-
- const message = await workspace.database
- .selectFrom('messages')
- .selectAll()
- .where('id', '=', input.messageId)
- .executeTakeFirst();
-
- if (!message) {
- return {
- success: true,
- };
- }
-
- const entry = await fetchEntry(workspace.database, message.entry_id);
- if (!entry) {
- throw new MutationError(
- MutationErrorCode.EntryNotFound,
- 'There was an error while fetching the conversation. Please make sure you have access to this conversation.'
- );
- }
-
- const root = await fetchEntry(workspace.database, message.root_id);
- if (!root) {
- throw new MutationError(
- MutationErrorCode.RootNotFound,
- 'There was an error while fetching the root. Please make sure you have access to this root.'
- );
- }
-
- if (
- !canDeleteMessage({
- user: {
- userId: workspace.userId,
- role: workspace.role,
- },
- root: mapEntry(root),
- entry: mapEntry(entry),
- message: {
- id: message.id,
- createdBy: message.created_by,
- },
- })
- ) {
- throw new MutationError(
- MutationErrorCode.MessageDeleteForbidden,
- 'You are not allowed to delete this message.'
- );
- }
-
- const deletedAt = new Date().toISOString();
- const deleteMessageMutationData: DeleteMessageMutationData = {
- id: input.messageId,
- rootId: message.root_id,
- deletedAt,
- };
-
- await workspace.database.transaction().execute(async (tx) => {
- await tx
- .updateTable('messages')
- .set({
- deleted_at: deletedAt,
- })
- .where('id', '=', input.messageId)
- .execute();
-
- await tx
- .insertInto('mutations')
- .values({
- id: generateId(IdType.Mutation),
- type: 'delete_message',
- data: JSON.stringify(deleteMessageMutationData),
- created_at: deletedAt,
- retries: 0,
- })
- .execute();
- });
-
- workspace.mutations.triggerSync();
-
- eventBus.publish({
- type: 'message_deleted',
- accountId: workspace.accountId,
- workspaceId: workspace.id,
- message: mapMessage(message),
- });
+ await workspace.nodes.deleteNode(input.messageId);
return {
success: true,
diff --git a/apps/desktop/src/main/mutations/messages/message-mark-seen.ts b/apps/desktop/src/main/mutations/messages/message-mark-seen.ts
deleted file mode 100644
index d4590ce0..00000000
--- a/apps/desktop/src/main/mutations/messages/message-mark-seen.ts
+++ /dev/null
@@ -1,129 +0,0 @@
-import { MarkMessageSeenMutation, generateId, IdType } from '@colanode/core';
-
-import { MutationHandler } from '@/main/lib/types';
-import {
- MessageMarkSeenMutationInput,
- MessageMarkSeenMutationOutput,
-} from '@/shared/mutations/messages/message-mark-seen';
-import { eventBus } from '@/shared/lib/event-bus';
-import { mapMessageInteraction } from '@/main/lib/mappers';
-import { WorkspaceMutationHandlerBase } from '@/main/mutations/workspace-mutation-handler-base';
-
-export class MessageMarkSeenMutationHandler
- extends WorkspaceMutationHandlerBase
- implements MutationHandler<MessageMarkSeenMutationInput>
-{
- async handleMutation(
- input: MessageMarkSeenMutationInput
- ): Promise<MessageMarkSeenMutationOutput> {
- const workspace = this.getWorkspace(input.accountId, input.workspaceId);
-
- const message = await workspace.database
- .selectFrom('messages')
- .selectAll()
- .where('id', '=', input.messageId)
- .executeTakeFirst();
-
- if (!message) {
- return {
- success: false,
- };
- }
-
- const existingInteraction = await workspace.database
- .selectFrom('message_interactions')
- .selectAll()
- .where('message_id', '=', input.messageId)
- .where('collaborator_id', '=', workspace.userId)
- .executeTakeFirst();
-
- if (existingInteraction) {
- const lastSeenAt = existingInteraction.last_seen_at;
- if (
- lastSeenAt &&
- lastSeenAt > new Date(Date.now() - 5 * 1000).toISOString()
- ) {
- return {
- success: true,
- };
- }
- }
-
- const lastSeenAt = new Date().toISOString();
- const firstSeenAt = existingInteraction
- ? existingInteraction.first_seen_at
- : lastSeenAt;
-
- const { createdInteraction, createdMutation } = await workspace.database
- .transaction()
- .execute(async (trx) => {
- const createdInteraction = await trx
- .insertInto('message_interactions')
- .returningAll()
- .values({
- message_id: input.messageId,
- collaborator_id: workspace.userId,
- first_seen_at: firstSeenAt,
- last_seen_at: lastSeenAt,
- version: 0n,
- root_id: message.root_id,
- })
- .onConflict((b) =>
- b.columns(['message_id', 'collaborator_id']).doUpdateSet({
- first_seen_at: firstSeenAt,
- last_seen_at: lastSeenAt,
- })
- )
- .executeTakeFirst();
-
- if (!createdInteraction) {
- throw new Error('Failed to create message interaction');
- }
-
- const mutation: MarkMessageSeenMutation = {
- id: generateId(IdType.Mutation),
- createdAt: new Date().toISOString(),
- type: 'mark_message_seen',
- data: {
- messageId: input.messageId,
- collaboratorId: workspace.userId,
- seenAt: new Date().toISOString(),
- },
- };
-
- const createdMutation = await trx
- .insertInto('mutations')
- .returningAll()
- .values({
- id: mutation.id,
- type: mutation.type,
- data: JSON.stringify(mutation.data),
- created_at: mutation.createdAt,
- retries: 0,
- })
- .executeTakeFirst();
-
- return {
- createdInteraction,
- createdMutation,
- };
- });
-
- if (!createdInteraction || !createdMutation) {
- throw new Error('Failed to create message interaction');
- }
-
- workspace.mutations.triggerSync();
-
- eventBus.publish({
- type: 'message_interaction_updated',
- accountId: workspace.accountId,
- workspaceId: workspace.id,
- messageInteraction: mapMessageInteraction(createdInteraction),
- });
-
- return {
- success: true,
- };
- }
-}
diff --git a/apps/desktop/src/main/mutations/messages/message-reaction-create.ts b/apps/desktop/src/main/mutations/messages/message-reaction-create.ts
deleted file mode 100644
index 5da291ac..00000000
--- a/apps/desktop/src/main/mutations/messages/message-reaction-create.ts
+++ /dev/null
@@ -1,156 +0,0 @@
-import {
- canCreateMessageReaction,
- CreateMessageReactionMutation,
- generateId,
- IdType,
-} from '@colanode/core';
-
-import { MutationHandler } from '@/main/lib/types';
-import {
- MessageReactionCreateMutationInput,
- MessageReactionCreateMutationOutput,
-} from '@/shared/mutations/messages/message-reaction-create';
-import { eventBus } from '@/shared/lib/event-bus';
-import { fetchEntry } from '@/main/lib/utils';
-import { mapEntry, mapMessageReaction } from '@/main/lib/mappers';
-import { MutationError, MutationErrorCode } from '@/shared/mutations';
-import { WorkspaceMutationHandlerBase } from '@/main/mutations/workspace-mutation-handler-base';
-
-export class MessageReactionCreateMutationHandler
- extends WorkspaceMutationHandlerBase
- implements MutationHandler<MessageReactionCreateMutationInput>
-{
- async handleMutation(
- input: MessageReactionCreateMutationInput
- ): Promise<MessageReactionCreateMutationOutput> {
- const workspace = this.getWorkspace(input.accountId, input.workspaceId);
-
- const message = await workspace.database
- .selectFrom('messages')
- .selectAll()
- .where('id', '=', input.messageId)
- .executeTakeFirst();
-
- if (!message) {
- throw new MutationError(
- MutationErrorCode.MessageNotFound,
- 'Message not found or has been deleted.'
- );
- }
-
- const existingMessageReaction = await workspace.database
- .selectFrom('message_reactions')
- .selectAll()
- .where('message_id', '=', input.messageId)
- .where('collaborator_id', '=', workspace.userId)
- .where('reaction', '=', input.reaction)
- .executeTakeFirst();
-
- if (existingMessageReaction) {
- return {
- success: true,
- };
- }
-
- const root = await fetchEntry(workspace.database, input.rootId);
- if (!root) {
- throw new MutationError(
- MutationErrorCode.RootNotFound,
- 'There was an error while fetching the root. Please make sure you have access to this root.'
- );
- }
-
- if (
- !canCreateMessageReaction({
- user: {
- userId: workspace.userId,
- role: workspace.role,
- },
- root: mapEntry(root),
- message: {
- id: message.id,
- createdBy: message.created_by,
- },
- })
- ) {
- throw new MutationError(
- MutationErrorCode.MessageReactionCreateForbidden,
- "You don't have permission to react to this message."
- );
- }
-
- const { createdMessageReaction, createdMutation } = await workspace.database
- .transaction()
- .execute(async (trx) => {
- const createdMessageReaction = await trx
- .insertInto('message_reactions')
- .returningAll()
- .values({
- message_id: input.messageId,
- collaborator_id: workspace.userId,
- reaction: input.reaction,
- root_id: input.rootId,
- version: 0n,
- created_at: new Date().toISOString(),
- })
- .onConflict((cb) =>
- cb
- .columns(['message_id', 'collaborator_id', 'reaction'])
- .doUpdateSet({
- deleted_at: null,
- })
- )
- .executeTakeFirst();
-
- if (!createdMessageReaction) {
- throw new Error('Failed to create message reaction');
- }
-
- const mutation: CreateMessageReactionMutation = {
- id: generateId(IdType.Mutation),
- createdAt: new Date().toISOString(),
- type: 'create_message_reaction',
- data: {
- messageId: input.messageId,
- reaction: input.reaction,
- rootId: input.rootId,
- createdAt: new Date().toISOString(),
- },
- };
-
- const createdMutation = await trx
- .insertInto('mutations')
- .returningAll()
- .values({
- id: mutation.id,
- type: mutation.type,
- data: JSON.stringify(mutation.data),
- created_at: mutation.createdAt,
- retries: 0,
- })
- .executeTakeFirst();
-
- return {
- createdMessageReaction,
- createdMutation,
- };
- });
-
- if (!createdMessageReaction || !createdMutation) {
- throw new Error('Failed to create message reaction');
- }
-
- workspace.mutations.triggerSync();
-
- eventBus.publish({
- type: 'message_reaction_created',
- accountId: workspace.accountId,
- workspaceId: workspace.id,
- messageReaction: mapMessageReaction(createdMessageReaction),
- });
-
- return {
- success: true,
- };
- }
-}
diff --git a/apps/desktop/src/main/mutations/messages/message-reaction-delete.ts b/apps/desktop/src/main/mutations/messages/message-reaction-delete.ts
deleted file mode 100644
index a73d17d0..00000000
--- a/apps/desktop/src/main/mutations/messages/message-reaction-delete.ts
+++ /dev/null
@@ -1,104 +0,0 @@
-import {
- DeleteMessageReactionMutation,
- generateId,
- IdType,
-} from '@colanode/core';
-
-import { MutationHandler } from '@/main/lib/types';
-import {
- MessageReactionDeleteMutationInput,
- MessageReactionDeleteMutationOutput,
-} from '@/shared/mutations/messages/message-reaction-delete';
-import { mapMessageReaction } from '@/main/lib/mappers';
-import { eventBus } from '@/shared/lib/event-bus';
-import { WorkspaceMutationHandlerBase } from '@/main/mutations/workspace-mutation-handler-base';
-
-export class MessageReactionDeleteMutationHandler
- extends WorkspaceMutationHandlerBase
- implements MutationHandler<MessageReactionDeleteMutationInput>
-{
- async handleMutation(
- input: MessageReactionDeleteMutationInput
- ): Promise<MessageReactionDeleteMutationOutput> {
- const workspace = this.getWorkspace(input.accountId, input.workspaceId);
-
- const existingMessageReaction = await workspace.database
- .selectFrom('message_reactions')
- .selectAll()
- .where('message_id', '=', input.messageId)
- .where('collaborator_id', '=', workspace.userId)
- .where('reaction', '=', input.reaction)
- .executeTakeFirst();
-
- if (!existingMessageReaction) {
- return {
- success: true,
- };
- }
-
- const { deletedMessageReaction, createdMutation } = await workspace.database
- .transaction()
- .execute(async (trx) => {
- const deletedMessageReaction = await trx
- .updateTable('message_reactions')
- .returningAll()
- .set({
- deleted_at: new Date().toISOString(),
- })
- .where('message_id', '=', input.messageId)
- .where('collaborator_id', '=', workspace.userId)
- .where('reaction', '=', input.reaction)
- .executeTakeFirst();
-
- if (!deletedMessageReaction) {
- throw new Error('Failed to delete message reaction');
- }
-
- const mutation: DeleteMessageReactionMutation = {
- id: generateId(IdType.Mutation),
- createdAt: new Date().toISOString(),
- type: 'delete_message_reaction',
- data: {
- messageId: input.messageId,
- reaction: deletedMessageReaction.reaction,
- rootId: input.rootId,
- deletedAt: new Date().toISOString(),
- },
- };
-
- const createdMutation = await trx
- .insertInto('mutations')
- .returningAll()
- .values({
- id: mutation.id,
- type: mutation.type,
- data: JSON.stringify(mutation.data),
- created_at: mutation.createdAt,
- retries: 0,
- })
- .executeTakeFirst();
-
- return {
- deletedMessageReaction,
- createdMutation,
- };
- });
-
- if (!deletedMessageReaction || !createdMutation) {
- throw new Error('Failed to delete message reaction');
- }
-
- workspace.mutations.triggerSync();
-
- eventBus.publish({
- type: 'message_reaction_deleted',
- accountId: workspace.accountId,
- workspaceId: workspace.id,
- messageReaction: mapMessageReaction(deletedMessageReaction),
- });
-
- return {
- success: true,
- };
- }
-}
diff --git a/apps/desktop/src/main/mutations/entries/entry-collaborator-create.ts b/apps/desktop/src/main/mutations/nodes/node-collaborator-create.ts
similarity index 62%
rename from apps/desktop/src/main/mutations/entries/entry-collaborator-create.ts
rename to apps/desktop/src/main/mutations/nodes/node-collaborator-create.ts
index 8f3a7e64..36808593 100644
--- a/apps/desktop/src/main/mutations/entries/entry-collaborator-create.ts
+++ b/apps/desktop/src/main/mutations/nodes/node-collaborator-create.ts
@@ -2,23 +2,23 @@ import { set } from 'lodash-es';
import { MutationHandler } from '@/main/lib/types';
import {
- EntryCollaboratorCreateMutationInput,
- EntryCollaboratorCreateMutationOutput,
-} from '@/shared/mutations/entries/entry-collaborator-create';
+ NodeCollaboratorCreateMutationInput,
+ NodeCollaboratorCreateMutationOutput,
+} from '@/shared/mutations/nodes/node-collaborator-create';
import { MutationError, MutationErrorCode } from '@/shared/mutations';
import { WorkspaceMutationHandlerBase } from '@/main/mutations/workspace-mutation-handler-base';
-export class EntryCollaboratorCreateMutationHandler
+export class NodeCollaboratorCreateMutationHandler
extends WorkspaceMutationHandlerBase
- implements MutationHandler<EntryCollaboratorCreateMutationInput>
+ implements MutationHandler<NodeCollaboratorCreateMutationInput>
{
async handleMutation(
- input: EntryCollaboratorCreateMutationInput
- ): Promise<EntryCollaboratorCreateMutationOutput> {
+ input: NodeCollaboratorCreateMutationInput
+ ): Promise<NodeCollaboratorCreateMutationOutput> {
const workspace = this.getWorkspace(input.accountId, input.workspaceId);
- const result = await workspace.entries.updateEntry(
- input.entryId,
+ const result = await workspace.nodes.updateNode(
+ input.nodeId,
(attributes) => {
for (const collaboratorId of input.collaboratorIds) {
set(attributes, `collaborators.${collaboratorId}`, input.role);
@@ -29,15 +29,15 @@ export class EntryCollaboratorCreateMutationHandler
if (result === 'unauthorized') {
throw new MutationError(
- MutationErrorCode.EntryCollaboratorCreateForbidden,
- "You don't have permission to add collaborators to this entry."
+ MutationErrorCode.NodeCollaboratorCreateForbidden,
+ "You don't have permission to add collaborators to this node."
);
}
if (result !== 'success') {
throw new MutationError(
- MutationErrorCode.EntryCollaboratorCreateFailed,
- 'Something went wrong while adding collaborators to the entry.'
+ MutationErrorCode.NodeCollaboratorCreateFailed,
+ 'Something went wrong while adding collaborators to the node.'
);
}
diff --git a/apps/desktop/src/main/mutations/entries/entry-collaborator-delete.ts b/apps/desktop/src/main/mutations/nodes/node-collaborator-delete.ts
similarity index 61%
rename from apps/desktop/src/main/mutations/entries/entry-collaborator-delete.ts
rename to apps/desktop/src/main/mutations/nodes/node-collaborator-delete.ts
index 2e03b6c8..9046857a 100644
--- a/apps/desktop/src/main/mutations/entries/entry-collaborator-delete.ts
+++ b/apps/desktop/src/main/mutations/nodes/node-collaborator-delete.ts
@@ -2,23 +2,23 @@ import { unset } from 'lodash-es';
import { MutationHandler } from '@/main/lib/types';
import {
- EntryCollaboratorDeleteMutationInput,
- EntryCollaboratorDeleteMutationOutput,
-} from '@/shared/mutations/entries/entry-collaborator-delete';
+ NodeCollaboratorDeleteMutationInput,
+ NodeCollaboratorDeleteMutationOutput,
+} from '@/shared/mutations/nodes/node-collaborator-delete';
import { MutationError, MutationErrorCode } from '@/shared/mutations';
import { WorkspaceMutationHandlerBase } from '@/main/mutations/workspace-mutation-handler-base';
-export class EntryCollaboratorDeleteMutationHandler
+export class NodeCollaboratorDeleteMutationHandler
extends WorkspaceMutationHandlerBase
- implements MutationHandler<EntryCollaboratorDeleteMutationInput>
+ implements MutationHandler<NodeCollaboratorDeleteMutationInput>
{
async handleMutation(
- input: EntryCollaboratorDeleteMutationInput
- ): Promise<EntryCollaboratorDeleteMutationOutput> {
+ input: NodeCollaboratorDeleteMutationInput
+ ): Promise<NodeCollaboratorDeleteMutationOutput> {
const workspace = this.getWorkspace(input.accountId, input.workspaceId);
- const result = await workspace.entries.updateEntry(
- input.entryId,
+ const result = await workspace.nodes.updateNode(
+ input.nodeId,
(attributes) => {
unset(attributes, `collaborators.${input.collaboratorId}`);
return attributes;
@@ -27,14 +27,14 @@ export class EntryCollaboratorDeleteMutationHandler
if (result === 'unauthorized') {
throw new MutationError(
- MutationErrorCode.EntryCollaboratorDeleteForbidden,
+ MutationErrorCode.NodeCollaboratorDeleteForbidden,
"You don't have permission to remove collaborators from this node."
);
}
if (result !== 'success') {
throw new MutationError(
- MutationErrorCode.EntryCollaboratorDeleteFailed,
+ MutationErrorCode.NodeCollaboratorDeleteFailed,
'Something went wrong while removing collaborators from the node.'
);
}
diff --git a/apps/desktop/src/main/mutations/entries/entry-collaborator-update.ts b/apps/desktop/src/main/mutations/nodes/node-collaborator-update.ts
similarity index 62%
rename from apps/desktop/src/main/mutations/entries/entry-collaborator-update.ts
rename to apps/desktop/src/main/mutations/nodes/node-collaborator-update.ts
index b273efec..b5df1549 100644
--- a/apps/desktop/src/main/mutations/entries/entry-collaborator-update.ts
+++ b/apps/desktop/src/main/mutations/nodes/node-collaborator-update.ts
@@ -2,23 +2,23 @@ import { set } from 'lodash-es';
import { MutationHandler } from '@/main/lib/types';
import {
- EntryCollaboratorUpdateMutationInput,
- EntryCollaboratorUpdateMutationOutput,
-} from '@/shared/mutations/entries/entry-collaborator-update';
+ NodeCollaboratorUpdateMutationInput,
+ NodeCollaboratorUpdateMutationOutput,
+} from '@/shared/mutations/nodes/node-collaborator-update';
import { MutationError, MutationErrorCode } from '@/shared/mutations';
import { WorkspaceMutationHandlerBase } from '@/main/mutations/workspace-mutation-handler-base';
-export class EntryCollaboratorUpdateMutationHandler
+export class NodeCollaboratorUpdateMutationHandler
extends WorkspaceMutationHandlerBase
- implements MutationHandler<EntryCollaboratorUpdateMutationInput>
+ implements MutationHandler<NodeCollaboratorUpdateMutationInput>
{
async handleMutation(
- input: EntryCollaboratorUpdateMutationInput
- ): Promise<EntryCollaboratorUpdateMutationOutput> {
+ input: NodeCollaboratorUpdateMutationInput
+ ): Promise<NodeCollaboratorUpdateMutationOutput> {
const workspace = this.getWorkspace(input.accountId, input.workspaceId);
- const result = await workspace.entries.updateEntry(
- input.entryId,
+ const result = await workspace.nodes.updateNode(
+ input.nodeId,
(attributes) => {
set(attributes, `collaborators.${input.collaboratorId}`, input.role);
return attributes;
@@ -27,14 +27,14 @@ export class EntryCollaboratorUpdateMutationHandler
if (result === 'unauthorized') {
throw new MutationError(
- MutationErrorCode.EntryCollaboratorUpdateForbidden,
+ MutationErrorCode.NodeCollaboratorUpdateForbidden,
"You don't have permission to update collaborators for this entry."
);
}
if (result !== 'success') {
throw new MutationError(
- MutationErrorCode.EntryCollaboratorUpdateFailed,
+ MutationErrorCode.NodeCollaboratorUpdateFailed,
'Something went wrong while updating collaborators for the entry.'
);
}
diff --git a/apps/desktop/src/main/mutations/entries/entry-mark-opened.ts b/apps/desktop/src/main/mutations/nodes/node-mark-opened.ts
similarity index 68%
rename from apps/desktop/src/main/mutations/entries/entry-mark-opened.ts
rename to apps/desktop/src/main/mutations/nodes/node-mark-opened.ts
index 9a90d370..b7f286dd 100644
--- a/apps/desktop/src/main/mutations/entries/entry-mark-opened.ts
+++ b/apps/desktop/src/main/mutations/nodes/node-mark-opened.ts
@@ -1,36 +1,36 @@
-import { MarkEntryOpenedMutation, generateId, IdType } from '@colanode/core';
+import { MarkNodeOpenedMutation, generateId, IdType } from '@colanode/core';
import { MutationHandler } from '@/main/lib/types';
import {
- EntryMarkOpenedMutationInput,
- EntryMarkOpenedMutationOutput,
-} from '@/shared/mutations/entries/entry-mark-opened';
+ NodeMarkOpenedMutationInput,
+ NodeMarkOpenedMutationOutput,
+} from '@/shared/mutations/nodes/node-mark-opened';
import { eventBus } from '@/shared/lib/event-bus';
-import { mapEntryInteraction } from '@/main/lib/mappers';
-import { fetchEntry } from '@/main/lib/utils';
+import { mapNodeInteraction } from '@/main/lib/mappers';
+import { fetchNode } from '@/main/lib/utils';
import { WorkspaceMutationHandlerBase } from '@/main/mutations/workspace-mutation-handler-base';
-export class EntryMarkOpenedMutationHandler
+export class NodeMarkOpenedMutationHandler
extends WorkspaceMutationHandlerBase
- implements MutationHandler<EntryMarkOpenedMutationInput>
+ implements MutationHandler<NodeMarkOpenedMutationInput>
{
async handleMutation(
- input: EntryMarkOpenedMutationInput
- ): Promise<EntryMarkOpenedMutationOutput> {
+ input: NodeMarkOpenedMutationInput
+ ): Promise<NodeMarkOpenedMutationOutput> {
const workspace = this.getWorkspace(input.accountId, input.workspaceId);
- const entry = await fetchEntry(workspace.database, input.entryId);
+ const node = await fetchNode(workspace.database, input.nodeId);
- if (!entry) {
+ if (!node) {
return {
success: false,
};
}
const existingInteraction = await workspace.database
- .selectFrom('entry_interactions')
+ .selectFrom('node_interactions')
.selectAll()
- .where('entry_id', '=', input.entryId)
+ .where('node_id', '=', input.nodeId)
.where('collaborator_id', '=', workspace.userId)
.executeTakeFirst();
@@ -55,18 +55,18 @@ export class EntryMarkOpenedMutationHandler
.transaction()
.execute(async (trx) => {
const createdInteraction = await trx
- .insertInto('entry_interactions')
+ .insertInto('node_interactions')
.returningAll()
.values({
- entry_id: input.entryId,
+ node_id: input.nodeId,
collaborator_id: workspace.userId,
last_opened_at: lastOpenedAt,
first_opened_at: firstOpenedAt,
- version: 0n,
- root_id: entry.root_id,
+ revision: 0n,
+ root_id: node.root_id,
})
.onConflict((b) =>
- b.columns(['entry_id', 'collaborator_id']).doUpdateSet({
+ b.columns(['node_id', 'collaborator_id']).doUpdateSet({
last_opened_at: lastOpenedAt,
first_opened_at: firstOpenedAt,
})
@@ -74,15 +74,15 @@ export class EntryMarkOpenedMutationHandler
.executeTakeFirst();
if (!createdInteraction) {
- throw new Error('Failed to create file interaction');
+ throw new Error('Failed to create node interaction');
}
- const mutation: MarkEntryOpenedMutation = {
+ const mutation: MarkNodeOpenedMutation = {
id: generateId(IdType.Mutation),
createdAt: new Date().toISOString(),
- type: 'mark_entry_opened',
+ type: 'mark_node_opened',
data: {
- entryId: input.entryId,
+ nodeId: input.nodeId,
collaboratorId: workspace.userId,
openedAt: new Date().toISOString(),
},
@@ -113,10 +113,10 @@ export class EntryMarkOpenedMutationHandler
workspace.mutations.triggerSync();
eventBus.publish({
- type: 'entry_interaction_updated',
+ type: 'node_interaction_updated',
accountId: workspace.accountId,
workspaceId: workspace.id,
- entryInteraction: mapEntryInteraction(createdInteraction),
+ nodeInteraction: mapNodeInteraction(createdInteraction),
});
return {
diff --git a/apps/desktop/src/main/mutations/entries/entry-mark-seen.ts b/apps/desktop/src/main/mutations/nodes/node-mark-seen.ts
similarity index 68%
rename from apps/desktop/src/main/mutations/entries/entry-mark-seen.ts
rename to apps/desktop/src/main/mutations/nodes/node-mark-seen.ts
index 975c792c..5ad231b8 100644
--- a/apps/desktop/src/main/mutations/entries/entry-mark-seen.ts
+++ b/apps/desktop/src/main/mutations/nodes/node-mark-seen.ts
@@ -1,36 +1,36 @@
-import { MarkEntrySeenMutation, generateId, IdType } from '@colanode/core';
+import { MarkNodeSeenMutation, generateId, IdType } from '@colanode/core';
import { MutationHandler } from '@/main/lib/types';
import {
- EntryMarkSeenMutationInput,
- EntryMarkSeenMutationOutput,
-} from '@/shared/mutations/entries/entry-mark-seen';
+ NodeMarkSeenMutationInput,
+ NodeMarkSeenMutationOutput,
+} from '@/shared/mutations/nodes/node-mark-seen';
import { eventBus } from '@/shared/lib/event-bus';
-import { fetchEntry } from '@/main/lib/utils';
-import { mapEntryInteraction } from '@/main/lib/mappers';
+import { fetchNode } from '@/main/lib/utils';
+import { mapNodeInteraction } from '@/main/lib/mappers';
import { WorkspaceMutationHandlerBase } from '@/main/mutations/workspace-mutation-handler-base';
-export class EntryMarkSeenMutationHandler
+export class NodeMarkSeenMutationHandler
extends WorkspaceMutationHandlerBase
- implements MutationHandler<EntryMarkSeenMutationInput>
+ implements MutationHandler<NodeMarkSeenMutationInput>
{
async handleMutation(
- input: EntryMarkSeenMutationInput
- ): Promise<EntryMarkSeenMutationOutput> {
+ input: NodeMarkSeenMutationInput
+ ): Promise<NodeMarkSeenMutationOutput> {
const workspace = this.getWorkspace(input.accountId, input.workspaceId);
- const entry = await fetchEntry(workspace.database, input.entryId);
+ const node = await fetchNode(workspace.database, input.nodeId);
- if (!entry) {
+ if (!node) {
return {
success: false,
};
}
const existingInteraction = await workspace.database
- .selectFrom('entry_interactions')
+ .selectFrom('node_interactions')
.selectAll()
- .where('entry_id', '=', input.entryId)
+ .where('node_id', '=', input.nodeId)
.where('collaborator_id', '=', workspace.userId)
.executeTakeFirst();
@@ -55,18 +55,18 @@ export class EntryMarkSeenMutationHandler
.transaction()
.execute(async (trx) => {
const createdInteraction = await trx
- .insertInto('entry_interactions')
+ .insertInto('node_interactions')
.returningAll()
.values({
- entry_id: input.entryId,
+ node_id: input.nodeId,
collaborator_id: workspace.userId,
last_seen_at: lastSeenAt,
first_seen_at: firstSeenAt,
- version: 0n,
- root_id: entry.root_id,
+ revision: 0n,
+ root_id: node.root_id,
})
.onConflict((b) =>
- b.columns(['entry_id', 'collaborator_id']).doUpdateSet({
+ b.columns(['node_id', 'collaborator_id']).doUpdateSet({
last_seen_at: lastSeenAt,
first_seen_at: firstSeenAt,
})
@@ -74,15 +74,15 @@ export class EntryMarkSeenMutationHandler
.executeTakeFirst();
if (!createdInteraction) {
- throw new Error('Failed to create entry interaction');
+ throw new Error('Failed to create node interaction');
}
- const mutation: MarkEntrySeenMutation = {
+ const mutation: MarkNodeSeenMutation = {
id: generateId(IdType.Mutation),
createdAt: new Date().toISOString(),
- type: 'mark_entry_seen',
+ type: 'mark_node_seen',
data: {
- entryId: input.entryId,
+ nodeId: input.nodeId,
collaboratorId: workspace.userId,
seenAt: new Date().toISOString(),
},
@@ -113,10 +113,10 @@ export class EntryMarkSeenMutationHandler
workspace.mutations.triggerSync();
eventBus.publish({
- type: 'entry_interaction_updated',
+ type: 'node_interaction_updated',
accountId: workspace.accountId,
workspaceId: workspace.id,
- entryInteraction: mapEntryInteraction(createdInteraction),
+ nodeInteraction: mapNodeInteraction(createdInteraction),
});
return {
diff --git a/apps/desktop/src/main/mutations/nodes/node-reaction-create.ts b/apps/desktop/src/main/mutations/nodes/node-reaction-create.ts
new file mode 100644
index 00000000..3c99a5e4
--- /dev/null
+++ b/apps/desktop/src/main/mutations/nodes/node-reaction-create.ts
@@ -0,0 +1,25 @@
+import { MutationHandler } from '@/main/lib/types';
+import {
+ NodeReactionCreateMutationInput,
+ NodeReactionCreateMutationOutput,
+} from '@/shared/mutations/nodes/node-reaction-create';
+import { WorkspaceMutationHandlerBase } from '@/main/mutations/workspace-mutation-handler-base';
+
+export class NodeReactionCreateMutationHandler
+ extends WorkspaceMutationHandlerBase
+ implements MutationHandler<NodeReactionCreateMutationInput>
+{
+ async handleMutation(
+ input: NodeReactionCreateMutationInput
+ ): Promise<NodeReactionCreateMutationOutput> {
+ const workspace = this.getWorkspace(input.accountId, input.workspaceId);
+ await workspace.nodeReactions.createNodeReaction(
+ input.nodeId,
+ input.reaction
+ );
+
+ return {
+ success: true,
+ };
+ }
+}
diff --git a/apps/desktop/src/main/mutations/nodes/node-reaction-delete.ts b/apps/desktop/src/main/mutations/nodes/node-reaction-delete.ts
new file mode 100644
index 00000000..8fcfedc3
--- /dev/null
+++ b/apps/desktop/src/main/mutations/nodes/node-reaction-delete.ts
@@ -0,0 +1,25 @@
+import { MutationHandler } from '@/main/lib/types';
+import {
+ NodeReactionDeleteMutationInput,
+ NodeReactionDeleteMutationOutput,
+} from '@/shared/mutations/nodes/node-reaction-delete';
+import { WorkspaceMutationHandlerBase } from '@/main/mutations/workspace-mutation-handler-base';
+
+export class NodeReactionDeleteMutationHandler
+ extends WorkspaceMutationHandlerBase
+ implements MutationHandler<NodeReactionDeleteMutationInput>
+{
+ async handleMutation(
+ input: NodeReactionDeleteMutationInput
+ ): Promise<NodeReactionDeleteMutationOutput> {
+ const workspace = this.getWorkspace(input.accountId, input.workspaceId);
+ await workspace.nodeReactions.deleteNodeReaction(
+ input.nodeId,
+ input.reaction
+ );
+
+ return {
+ success: true,
+ };
+ }
+}
diff --git a/apps/desktop/src/main/mutations/pages/page-content-update.ts b/apps/desktop/src/main/mutations/pages/page-content-update.ts
index ecfca9c6..55a51d82 100644
--- a/apps/desktop/src/main/mutations/pages/page-content-update.ts
+++ b/apps/desktop/src/main/mutations/pages/page-content-update.ts
@@ -25,7 +25,7 @@ export class PageContentUpdateMutationHandler
};
}
- const result = await workspace.entries.updateEntry<PageAttributes>(
+ const result = await workspace.nodes.updateNode<PageAttributes>(
input.pageId,
(attributes) => {
const indexMap = new Map<string, string>();
diff --git a/apps/desktop/src/main/mutations/pages/page-create.ts b/apps/desktop/src/main/mutations/pages/page-create.ts
index 08e4f6e1..ebd11a9b 100644
--- a/apps/desktop/src/main/mutations/pages/page-create.ts
+++ b/apps/desktop/src/main/mutations/pages/page-create.ts
@@ -24,7 +24,7 @@ export class PageCreateMutationHandler
name: input.name,
};
- await workspace.entries.createEntry({
+ await workspace.nodes.createNode({
id,
attributes,
parentId: input.parentId,
diff --git a/apps/desktop/src/main/mutations/pages/page-delete.ts b/apps/desktop/src/main/mutations/pages/page-delete.ts
index d0e7284b..8927669f 100644
--- a/apps/desktop/src/main/mutations/pages/page-delete.ts
+++ b/apps/desktop/src/main/mutations/pages/page-delete.ts
@@ -13,8 +13,7 @@ export class PageDeleteMutationHandler
input: PageDeleteMutationInput
): Promise<PageDeleteMutationOutput> {
const workspace = this.getWorkspace(input.accountId, input.workspaceId);
-
- await workspace.entries.deleteEntry(input.pageId);
+ await workspace.nodes.deleteNode(input.pageId);
return {
success: true,
diff --git a/apps/desktop/src/main/mutations/pages/page-update.ts b/apps/desktop/src/main/mutations/pages/page-update.ts
index 42ce7f24..018ad78b 100644
--- a/apps/desktop/src/main/mutations/pages/page-update.ts
+++ b/apps/desktop/src/main/mutations/pages/page-update.ts
@@ -17,7 +17,7 @@ export class PageUpdateMutationHandler
): Promise<PageUpdateMutationOutput> {
const workspace = this.getWorkspace(input.accountId, input.workspaceId);
- const result = await workspace.entries.updateEntry<PageAttributes>(
+ const result = await workspace.nodes.updateNode<PageAttributes>(
input.pageId,
(attributes) => {
attributes.name = input.name;
diff --git a/apps/desktop/src/main/mutations/records/record-avatar-update.ts b/apps/desktop/src/main/mutations/records/record-avatar-update.ts
index bc8b9b88..c15a8838 100644
--- a/apps/desktop/src/main/mutations/records/record-avatar-update.ts
+++ b/apps/desktop/src/main/mutations/records/record-avatar-update.ts
@@ -17,7 +17,7 @@ export class RecordAvatarUpdateMutationHandler
): Promise<RecordAvatarUpdateMutationOutput> {
const workspace = this.getWorkspace(input.accountId, input.workspaceId);
- const result = await workspace.entries.updateEntry<RecordAttributes>(
+ const result = await workspace.nodes.updateNode<RecordAttributes>(
input.recordId,
(attributes) => {
attributes.avatar = input.avatar;
diff --git a/apps/desktop/src/main/mutations/records/record-content-update.ts b/apps/desktop/src/main/mutations/records/record-content-update.ts
index 2812332d..094db37c 100644
--- a/apps/desktop/src/main/mutations/records/record-content-update.ts
+++ b/apps/desktop/src/main/mutations/records/record-content-update.ts
@@ -25,7 +25,7 @@ export class RecordContentUpdateMutationHandler
};
}
- const result = await workspace.entries.updateEntry<RecordAttributes>(
+ const result = await workspace.nodes.updateNode<RecordAttributes>(
input.recordId,
(attributes) => {
const indexMap = new Map<string, string>();
diff --git a/apps/desktop/src/main/mutations/records/record-create.ts b/apps/desktop/src/main/mutations/records/record-create.ts
index bb68ee65..e3cdea53 100644
--- a/apps/desktop/src/main/mutations/records/record-create.ts
+++ b/apps/desktop/src/main/mutations/records/record-create.ts
@@ -25,7 +25,7 @@ export class RecordCreateMutationHandler
fields: input.fields ?? {},
};
- await workspace.entries.createEntry({
+ await workspace.nodes.createNode({
id,
attributes,
parentId: input.databaseId,
diff --git a/apps/desktop/src/main/mutations/records/record-delete.ts b/apps/desktop/src/main/mutations/records/record-delete.ts
index 11a7639b..b3e0e795 100644
--- a/apps/desktop/src/main/mutations/records/record-delete.ts
+++ b/apps/desktop/src/main/mutations/records/record-delete.ts
@@ -13,8 +13,7 @@ export class RecordDeleteMutationHandler
input: RecordDeleteMutationInput
): Promise<RecordDeleteMutationOutput> {
const workspace = this.getWorkspace(input.accountId, input.workspaceId);
-
- await workspace.entries.deleteEntry(input.recordId);
+ await workspace.nodes.deleteNode(input.recordId);
return {
success: true,
diff --git a/apps/desktop/src/main/mutations/records/record-field-value-delete.ts b/apps/desktop/src/main/mutations/records/record-field-value-delete.ts
index a7625fdb..27b6be7c 100644
--- a/apps/desktop/src/main/mutations/records/record-field-value-delete.ts
+++ b/apps/desktop/src/main/mutations/records/record-field-value-delete.ts
@@ -17,7 +17,7 @@ export class RecordFieldValueDeleteMutationHandler
): Promise<RecordFieldValueDeleteMutationOutput> {
const workspace = this.getWorkspace(input.accountId, input.workspaceId);
- const result = await workspace.entries.updateEntry<RecordAttributes>(
+ const result = await workspace.nodes.updateNode<RecordAttributes>(
input.recordId,
(attributes) => {
delete attributes.fields[input.fieldId];
diff --git a/apps/desktop/src/main/mutations/records/record-field-value-set.ts b/apps/desktop/src/main/mutations/records/record-field-value-set.ts
index 55b603ab..26f900cc 100644
--- a/apps/desktop/src/main/mutations/records/record-field-value-set.ts
+++ b/apps/desktop/src/main/mutations/records/record-field-value-set.ts
@@ -17,7 +17,7 @@ export class RecordFieldValueSetMutationHandler
): Promise<RecordFieldValueSetMutationOutput> {
const workspace = this.getWorkspace(input.accountId, input.workspaceId);
- const result = await workspace.entries.updateEntry<RecordAttributes>(
+ const result = await workspace.nodes.updateNode<RecordAttributes>(
input.recordId,
(attributes) => {
attributes.fields[input.fieldId] = input.value;
diff --git a/apps/desktop/src/main/mutations/records/record-name-update.ts b/apps/desktop/src/main/mutations/records/record-name-update.ts
index 01cd0bad..8d2d69a2 100644
--- a/apps/desktop/src/main/mutations/records/record-name-update.ts
+++ b/apps/desktop/src/main/mutations/records/record-name-update.ts
@@ -17,7 +17,7 @@ export class RecordNameUpdateMutationHandler
): Promise<RecordNameUpdateMutationOutput> {
const workspace = this.getWorkspace(input.accountId, input.workspaceId);
- const result = await workspace.entries.updateEntry<RecordAttributes>(
+ const result = await workspace.nodes.updateNode<RecordAttributes>(
input.recordId,
(attributes) => {
attributes.name = input.name;
diff --git a/apps/desktop/src/main/mutations/spaces/space-avatar-update.ts b/apps/desktop/src/main/mutations/spaces/space-avatar-update.ts
index edcfa1cc..a9e45437 100644
--- a/apps/desktop/src/main/mutations/spaces/space-avatar-update.ts
+++ b/apps/desktop/src/main/mutations/spaces/space-avatar-update.ts
@@ -17,7 +17,7 @@ export class SpaceAvatarUpdateMutationHandler
): Promise<SpaceAvatarUpdateMutationOutput> {
const workspace = this.getWorkspace(input.accountId, input.workspaceId);
- const result = await workspace.entries.updateEntry<SpaceAttributes>(
+ const result = await workspace.nodes.updateNode<SpaceAttributes>(
input.spaceId,
(attributes) => {
attributes.avatar = input.avatar;
diff --git a/apps/desktop/src/main/mutations/spaces/space-create.ts b/apps/desktop/src/main/mutations/spaces/space-create.ts
index 9f247a07..52e677eb 100644
--- a/apps/desktop/src/main/mutations/spaces/space-create.ts
+++ b/apps/desktop/src/main/mutations/spaces/space-create.ts
@@ -48,7 +48,7 @@ export class SpaceCreateMutationHandler
description: input.description,
};
- await workspace.entries.createEntry({
+ await workspace.nodes.createNode({
id: spaceId,
attributes: spaceAttributes,
parentId: null,
@@ -61,7 +61,7 @@ export class SpaceCreateMutationHandler
parentId: spaceId,
};
- await workspace.entries.createEntry({
+ await workspace.nodes.createNode({
id: pageId,
attributes: pageAttributes,
parentId: spaceId,
@@ -74,7 +74,7 @@ export class SpaceCreateMutationHandler
parentId: spaceId,
};
- await workspace.entries.createEntry({
+ await workspace.nodes.createNode({
id: channelId,
attributes: channelAttributes,
parentId: spaceId,
diff --git a/apps/desktop/src/main/mutations/spaces/space-delete.ts b/apps/desktop/src/main/mutations/spaces/space-delete.ts
index 0f08f522..23b69380 100644
--- a/apps/desktop/src/main/mutations/spaces/space-delete.ts
+++ b/apps/desktop/src/main/mutations/spaces/space-delete.ts
@@ -13,7 +13,7 @@ export class SpaceDeleteMutationHandler
input: SpaceDeleteMutationInput
): Promise<SpaceDeleteMutationOutput> {
const workspace = this.getWorkspace(input.accountId, input.workspaceId);
- await workspace.entries.deleteEntry(input.spaceId);
+ await workspace.nodes.deleteNode(input.spaceId);
return {
success: true,
diff --git a/apps/desktop/src/main/mutations/spaces/space-description-update.ts b/apps/desktop/src/main/mutations/spaces/space-description-update.ts
index 542d2239..1cf6e5dc 100644
--- a/apps/desktop/src/main/mutations/spaces/space-description-update.ts
+++ b/apps/desktop/src/main/mutations/spaces/space-description-update.ts
@@ -17,7 +17,7 @@ export class SpaceDescriptionUpdateMutationHandler
): Promise<SpaceDescriptionUpdateMutationOutput> {
const workspace = this.getWorkspace(input.accountId, input.workspaceId);
- const result = await workspace.entries.updateEntry<SpaceAttributes>(
+ const result = await workspace.nodes.updateNode<SpaceAttributes>(
input.spaceId,
(attributes) => {
attributes.description = input.description;
diff --git a/apps/desktop/src/main/mutations/spaces/space-name-update.ts b/apps/desktop/src/main/mutations/spaces/space-name-update.ts
index ecdb534d..562bb523 100644
--- a/apps/desktop/src/main/mutations/spaces/space-name-update.ts
+++ b/apps/desktop/src/main/mutations/spaces/space-name-update.ts
@@ -17,7 +17,7 @@ export class SpaceNameUpdateMutationHandler
): Promise<SpaceNameUpdateMutationOutput> {
const workspace = this.getWorkspace(input.accountId, input.workspaceId);
- const result = await workspace.entries.updateEntry<SpaceAttributes>(
+ const result = await workspace.nodes.updateNode<SpaceAttributes>(
input.spaceId,
(attributes) => {
attributes.name = input.name;
diff --git a/apps/desktop/src/main/mutations/users/user-role-update.ts b/apps/desktop/src/main/mutations/users/user-role-update.ts
index 4f293601..1b13f835 100644
--- a/apps/desktop/src/main/mutations/users/user-role-update.ts
+++ b/apps/desktop/src/main/mutations/users/user-role-update.ts
@@ -1,5 +1,3 @@
-import { UserRoleUpdateOutput } from '@colanode/core';
-
import { MutationHandler } from '@/main/lib/types';
import {
UserRoleUpdateMutationInput,
@@ -19,7 +17,7 @@ export class UserRoleUpdateMutationHandler
const workspace = this.getWorkspace(input.accountId, input.workspaceId);
try {
- await workspace.account.client.put<UserRoleUpdateOutput>(
+ await workspace.account.client.put(
`/v1/workspaces/${workspace.id}/users/${input.userId}`,
{
role: input.role,
diff --git a/apps/desktop/src/main/queries/chats/chat-list.ts b/apps/desktop/src/main/queries/chats/chat-list.ts
index 4fceec6c..573edc4a 100644
--- a/apps/desktop/src/main/queries/chats/chat-list.ts
+++ b/apps/desktop/src/main/queries/chats/chat-list.ts
@@ -1,25 +1,26 @@
-import { ChatEntry } from '@colanode/core';
-
-import { SelectEntry } from '@/main/databases/workspace';
+import { SelectNode } from '@/main/databases/workspace';
import { ChangeCheckResult, QueryHandler } from '@/main/lib/types';
-import { mapEntry } from '@/main/lib/mappers';
+import { mapNode } from '@/main/lib/mappers';
import { ChatListQueryInput } from '@/shared/queries/chats/chat-list';
import { Event } from '@/shared/types/events';
import { WorkspaceQueryHandlerBase } from '@/main/queries/workspace-query-handler-base';
+import { LocalChatNode } from '@/shared/types/nodes';
export class ChatListQueryHandler
extends WorkspaceQueryHandlerBase
implements QueryHandler<ChatListQueryInput>
{
- public async handleQuery(input: ChatListQueryInput): Promise<ChatEntry[]> {
+ public async handleQuery(
+ input: ChatListQueryInput
+ ): Promise<LocalChatNode[]> {
const rows = await this.fetchChildren(input);
- return rows.map(mapEntry) as ChatEntry[];
+ return rows.map(mapNode) as LocalChatNode[];
}
public async checkForChanges(
event: Event,
input: ChatListQueryInput,
- output: ChatEntry[]
+ output: LocalChatNode[]
): Promise<ChangeCheckResult<ChatListQueryInput>> {
if (
event.type === 'workspace_deleted' &&
@@ -33,12 +34,12 @@ export class ChatListQueryHandler
}
if (
- event.type === 'entry_created' &&
+ event.type === 'node_created' &&
event.accountId === input.accountId &&
event.workspaceId === input.workspaceId &&
- event.entry.type === 'chat'
+ event.node.type === 'chat'
) {
- const newChildren = [...output, event.entry];
+ const newChildren = [...output, event.node];
return {
hasChanges: true,
result: newChildren,
@@ -46,15 +47,15 @@ export class ChatListQueryHandler
}
if (
- event.type === 'entry_updated' &&
+ event.type === 'node_updated' &&
event.accountId === input.accountId &&
event.workspaceId === input.workspaceId &&
- event.entry.type === 'chat'
+ event.node.type === 'chat'
) {
- const entry = output.find((entry) => entry.id === event.entry.id);
- if (entry) {
- const newChildren = output.map((entry) =>
- entry.id === event.entry.id ? (event.entry as ChatEntry) : entry
+ const node = output.find((node) => node.id === event.node.id);
+ if (node) {
+ const newChildren = output.map((node) =>
+ node.id === event.node.id ? (event.node as LocalChatNode) : node
);
return {
@@ -65,16 +66,14 @@ export class ChatListQueryHandler
}
if (
- event.type === 'entry_deleted' &&
+ event.type === 'node_deleted' &&
event.accountId === input.accountId &&
event.workspaceId === input.workspaceId &&
- event.entry.type === 'chat'
+ event.node.type === 'chat'
) {
- const entry = output.find((entry) => entry.id === event.entry.id);
- if (entry) {
- const newChildren = output.filter(
- (entry) => entry.id !== event.entry.id
- );
+ const node = output.find((node) => node.id === event.node.id);
+ if (node) {
+ const newChildren = output.filter((node) => node.id !== event.node.id);
return {
hasChanges: true,
result: newChildren,
@@ -89,11 +88,11 @@ export class ChatListQueryHandler
private async fetchChildren(
input: ChatListQueryInput
- ): Promise<SelectEntry[]> {
+ ): Promise<SelectNode[]> {
const workspace = this.getWorkspace(input.accountId, input.workspaceId);
const rows = await workspace.database
- .selectFrom('entries')
+ .selectFrom('nodes')
.selectAll()
.where('parent_id', 'is', null)
.where('type', '=', 'chat')
diff --git a/apps/desktop/src/main/queries/databases/database-list.ts b/apps/desktop/src/main/queries/databases/database-list.ts
index f7e95370..fb7ba95b 100644
--- a/apps/desktop/src/main/queries/databases/database-list.ts
+++ b/apps/desktop/src/main/queries/databases/database-list.ts
@@ -1,11 +1,12 @@
-import { compareString, DatabaseEntry } from '@colanode/core';
+import { compareString } from '@colanode/core';
-import { SelectEntry } from '@/main/databases/workspace';
+import { SelectNode } from '@/main/databases/workspace';
import { ChangeCheckResult, QueryHandler } from '@/main/lib/types';
-import { mapEntry } from '@/main/lib/mappers';
+import { mapNode } from '@/main/lib/mappers';
import { DatabaseListQueryInput } from '@/shared/queries/databases/database-list';
import { Event } from '@/shared/types/events';
import { WorkspaceQueryHandlerBase } from '@/main/queries/workspace-query-handler-base';
+import { LocalDatabaseNode } from '@/shared/types/nodes';
export class DatabaseListQueryHandler
extends WorkspaceQueryHandlerBase
@@ -13,15 +14,16 @@ export class DatabaseListQueryHandler
{
public async handleQuery(
input: DatabaseListQueryInput
- ): Promise<DatabaseEntry[]> {
+ ): Promise<LocalDatabaseNode[]> {
const databases = await this.fetchDatabases(input);
- return this.buildDatabases(databases);
+ const databaseNodes = databases.map(mapNode) as LocalDatabaseNode[];
+ return databaseNodes.sort((a, b) => compareString(a.id, b.id));
}
public async checkForChanges(
event: Event,
input: DatabaseListQueryInput,
- output: DatabaseEntry[]
+ output: LocalDatabaseNode[]
): Promise<ChangeCheckResult<DatabaseListQueryInput>> {
if (
event.type === 'workspace_deleted' &&
@@ -35,10 +37,10 @@ export class DatabaseListQueryHandler
}
if (
- event.type === 'entry_created' &&
+ event.type === 'node_created' &&
event.accountId === input.accountId &&
event.workspaceId === input.workspaceId &&
- event.entry.type === 'database'
+ event.node.type === 'database'
) {
const newResult = await this.handleQuery(input);
@@ -49,20 +51,18 @@ export class DatabaseListQueryHandler
}
if (
- event.type === 'entry_updated' &&
+ event.type === 'node_updated' &&
event.accountId === input.accountId &&
event.workspaceId === input.workspaceId &&
- event.entry.type === 'database'
+ event.node.type === 'database'
) {
- const database = output.find(
- (database) => database.id === event.entry.id
- );
+ const database = output.find((database) => database.id === event.node.id);
if (database) {
- const newResult = output.map((database) => {
- if (database.id === event.entry.id) {
- return event.entry as DatabaseEntry;
+ const newResult = output.map((node) => {
+ if (node.id === event.node.id) {
+ return event.node as LocalDatabaseNode;
}
- return database;
+ return node;
});
return {
@@ -73,14 +73,12 @@ export class DatabaseListQueryHandler
}
if (
- event.type === 'entry_deleted' &&
+ event.type === 'node_deleted' &&
event.accountId === input.accountId &&
event.workspaceId === input.workspaceId &&
- event.entry.type === 'database'
+ event.node.type === 'database'
) {
- const database = output.find(
- (database) => database.id === event.entry.id
- );
+ const database = output.find((node) => node.id === event.node.id);
if (database) {
const newOutput = await this.handleQuery(input);
@@ -98,30 +96,15 @@ export class DatabaseListQueryHandler
private async fetchDatabases(
input: DatabaseListQueryInput
- ): Promise<SelectEntry[]> {
+ ): Promise<SelectNode[]> {
const workspace = this.getWorkspace(input.accountId, input.workspaceId);
const databases = await workspace.database
- .selectFrom('entries')
+ .selectFrom('nodes')
.where('type', '=', 'database')
.selectAll()
.execute();
return databases;
}
-
- private buildDatabases = (rows: SelectEntry[]): DatabaseEntry[] => {
- const entries = rows.map(mapEntry);
- const databaseEntries: DatabaseEntry[] = [];
-
- for (const entry of entries) {
- if (entry.type !== 'database') {
- continue;
- }
-
- databaseEntries.push(entry);
- }
-
- return databaseEntries.sort((a, b) => compareString(a.id, b.id));
- };
}
diff --git a/apps/desktop/src/main/queries/databases/database-view-list.ts b/apps/desktop/src/main/queries/databases/database-view-list.ts
new file mode 100644
index 00000000..f2bbb7fc
--- /dev/null
+++ b/apps/desktop/src/main/queries/databases/database-view-list.ts
@@ -0,0 +1,117 @@
+import { compareString } from '@colanode/core';
+
+import { SelectNode } from '@/main/databases/workspace';
+import { ChangeCheckResult, QueryHandler } from '@/main/lib/types';
+import { mapNode } from '@/main/lib/mappers';
+import { DatabaseViewListQueryInput } from '@/shared/queries/databases/database-view-list';
+import { Event } from '@/shared/types/events';
+import { WorkspaceQueryHandlerBase } from '@/main/queries/workspace-query-handler-base';
+import { LocalDatabaseViewNode } from '@/shared/types/nodes';
+
+export class DatabaseViewListQueryHandler
+ extends WorkspaceQueryHandlerBase
+ implements QueryHandler<DatabaseViewListQueryInput>
+{
+ public async handleQuery(
+ input: DatabaseViewListQueryInput
+ ): Promise<LocalDatabaseViewNode[]> {
+ const databaseViews = await this.fetchDatabaseViews(input);
+ const databaseViewNodes = databaseViews.map(
+ mapNode
+ ) as LocalDatabaseViewNode[];
+ return databaseViewNodes.sort((a, b) => compareString(a.id, b.id));
+ }
+
+ public async checkForChanges(
+ event: Event,
+ input: DatabaseViewListQueryInput,
+ output: LocalDatabaseViewNode[]
+ ): Promise<ChangeCheckResult<DatabaseViewListQueryInput>> {
+ if (
+ event.type === 'workspace_deleted' &&
+ event.workspace.accountId === input.accountId &&
+ event.workspace.id === input.workspaceId
+ ) {
+ return {
+ hasChanges: true,
+ result: [],
+ };
+ }
+
+ if (
+ event.type === 'node_created' &&
+ event.accountId === input.accountId &&
+ event.workspaceId === input.workspaceId &&
+ event.node.type === 'database_view' &&
+ event.node.parentId === input.databaseId
+ ) {
+ const newResult = await this.handleQuery(input);
+
+ return {
+ hasChanges: true,
+ result: newResult,
+ };
+ }
+
+ if (
+ event.type === 'node_updated' &&
+ event.accountId === input.accountId &&
+ event.workspaceId === input.workspaceId &&
+ event.node.type === 'database_view' &&
+ event.node.parentId === input.databaseId
+ ) {
+ const databaseView = output.find((dv) => dv.id === event.node.id);
+
+ if (databaseView) {
+ const newResult = output.map((node) => {
+ if (node.id === event.node.id) {
+ return event.node as LocalDatabaseViewNode;
+ }
+ return node;
+ });
+
+ return {
+ hasChanges: true,
+ result: newResult,
+ };
+ }
+ }
+
+ if (
+ event.type === 'node_deleted' &&
+ event.accountId === input.accountId &&
+ event.workspaceId === input.workspaceId &&
+ event.node.type === 'database_view' &&
+ event.node.parentId === input.databaseId
+ ) {
+ const databaseView = output.find((node) => node.id === event.node.id);
+
+ if (databaseView) {
+ const newOutput = await this.handleQuery(input);
+ return {
+ hasChanges: true,
+ result: newOutput,
+ };
+ }
+ }
+
+ return {
+ hasChanges: false,
+ };
+ }
+
+ private async fetchDatabaseViews(
+ input: DatabaseViewListQueryInput
+ ): Promise<SelectNode[]> {
+ const workspace = this.getWorkspace(input.accountId, input.workspaceId);
+
+ const databaseViews = await workspace.database
+ .selectFrom('nodes')
+ .where('parent_id', '=', input.databaseId)
+ .where('type', '=', 'database_view')
+ .selectAll()
+ .execute();
+
+ return databaseViews;
+ }
+}
diff --git a/apps/desktop/src/main/queries/entries/entry-children-get.ts b/apps/desktop/src/main/queries/entries/entry-children-get.ts
deleted file mode 100644
index 2013fec0..00000000
--- a/apps/desktop/src/main/queries/entries/entry-children-get.ts
+++ /dev/null
@@ -1,109 +0,0 @@
-import { Entry } from '@colanode/core';
-
-import { SelectEntry } from '@/main/databases/workspace';
-import { ChangeCheckResult, QueryHandler } from '@/main/lib/types';
-import { mapEntry } from '@/main/lib/mappers';
-import { Event } from '@/shared/types/events';
-import { EntryChildrenGetQueryInput } from '@/shared/queries/entries/entry-children-get';
-import { WorkspaceQueryHandlerBase } from '@/main/queries/workspace-query-handler-base';
-
-export class EntryChildrenGetQueryHandler
- extends WorkspaceQueryHandlerBase
- implements QueryHandler<EntryChildrenGetQueryInput>
-{
- public async handleQuery(
- input: EntryChildrenGetQueryInput
- ): Promise<Entry[]> {
- const rows = await this.fetchChildren(input);
- return rows.map(mapEntry);
- }
-
- public async checkForChanges(
- event: Event,
- input: EntryChildrenGetQueryInput,
- output: Entry[]
- ): Promise<ChangeCheckResult<EntryChildrenGetQueryInput>> {
- if (
- event.type === 'workspace_deleted' &&
- event.workspace.accountId === input.accountId &&
- event.workspace.id === input.workspaceId
- ) {
- return {
- hasChanges: true,
- result: [],
- };
- }
-
- if (
- event.type === 'entry_created' &&
- event.accountId === input.accountId &&
- event.workspaceId === input.workspaceId &&
- event.entry.parentId === input.entryId &&
- (input.types === undefined || input.types.includes(event.entry.type))
- ) {
- const newChildren = [...output, event.entry];
- return {
- hasChanges: true,
- result: newChildren,
- };
- }
-
- if (
- event.type === 'entry_updated' &&
- event.accountId === input.accountId &&
- event.workspaceId === input.workspaceId &&
- event.entry.parentId === input.entryId &&
- (input.types === undefined || input.types.includes(event.entry.type))
- ) {
- const entry = output.find((entry) => entry.id === event.entry.id);
- if (entry) {
- const newChildren = output.map((entry) =>
- entry.id === event.entry.id ? event.entry : entry
- );
-
- return {
- hasChanges: true,
- result: newChildren,
- };
- }
- }
-
- if (
- event.type === 'entry_deleted' &&
- event.accountId === input.accountId &&
- event.workspaceId === input.workspaceId &&
- event.entry.parentId === input.entryId &&
- (input.types === undefined || input.types.includes(event.entry.type))
- ) {
- const entry = output.find((entry) => entry.id === event.entry.id);
- if (entry) {
- const newChildren = output.filter(
- (entry) => entry.id !== event.entry.id
- );
- return {
- hasChanges: true,
- result: newChildren,
- };
- }
- }
-
- return {
- hasChanges: false,
- };
- }
-
- private async fetchChildren(
- input: EntryChildrenGetQueryInput
- ): Promise<SelectEntry[]> {
- const workspace = this.getWorkspace(input.accountId, input.workspaceId);
-
- const rows = await workspace.database
- .selectFrom('entries')
- .selectAll()
- .where('parent_id', '=', input.entryId)
- .where('type', 'in', input.types ?? [])
- .execute();
-
- return rows;
- }
-}
diff --git a/apps/desktop/src/main/queries/files/file-breadcrumb-get.ts b/apps/desktop/src/main/queries/files/file-breadcrumb-get.ts
deleted file mode 100644
index 7b68be35..00000000
--- a/apps/desktop/src/main/queries/files/file-breadcrumb-get.ts
+++ /dev/null
@@ -1,67 +0,0 @@
-import { ChangeCheckResult, QueryHandler } from '@/main/lib/types';
-import { FileBreadcrumbGetQueryInput } from '@/shared/queries/files/file-breadcrumb-get';
-import { Event } from '@/shared/types/events';
-import { WorkspaceQueryHandlerBase } from '@/main/queries/workspace-query-handler-base';
-import { fetchFileBreadcrumb } from '@/main/lib/utils';
-
-export class FileBreadcrumbGetQueryHandler
- extends WorkspaceQueryHandlerBase
- implements QueryHandler<FileBreadcrumbGetQueryInput>
-{
- public async handleQuery(
- input: FileBreadcrumbGetQueryInput
- ): Promise<string[]> {
- const workspace = this.getWorkspace(input.accountId, input.workspaceId);
- return fetchFileBreadcrumb(workspace.database, input.fileId);
- }
-
- public async checkForChanges(
- event: Event,
- input: FileBreadcrumbGetQueryInput,
- output: string[]
- ): Promise<ChangeCheckResult<FileBreadcrumbGetQueryInput>> {
- if (
- event.type === 'workspace_deleted' &&
- event.workspace.accountId === input.accountId &&
- event.workspace.id === input.workspaceId
- ) {
- return {
- hasChanges: true,
- result: [],
- };
- }
-
- if (
- event.type === 'file_created' &&
- event.accountId === input.accountId &&
- event.workspaceId === input.workspaceId &&
- event.file.id === input.fileId
- ) {
- const newOutput = await this.handleQuery(input);
- return {
- hasChanges: true,
- result: newOutput,
- };
- }
-
- if (
- event.type === 'file_deleted' &&
- event.accountId === input.accountId &&
- event.workspaceId === input.workspaceId &&
- event.file.id === input.fileId
- ) {
- const fileId = output.find((id) => id === event.file.id);
- if (fileId) {
- const newOutput = await this.handleQuery(input);
- return {
- hasChanges: true,
- result: newOutput,
- };
- }
- }
-
- return {
- hasChanges: false,
- };
- }
-}
diff --git a/apps/desktop/src/main/queries/files/file-get.ts b/apps/desktop/src/main/queries/files/file-get.ts
index d164f14e..8516519a 100644
--- a/apps/desktop/src/main/queries/files/file-get.ts
+++ b/apps/desktop/src/main/queries/files/file-get.ts
@@ -2,27 +2,21 @@ import { ChangeCheckResult, QueryHandler } from '@/main/lib/types';
import { mapFile } from '@/main/lib/mappers';
import { FileGetQueryInput } from '@/shared/queries/files/file-get';
import { Event } from '@/shared/types/events';
-import {
- DownloadStatus,
- FileWithState,
- UploadStatus,
-} from '@/shared/types/files';
+import { File } from '@/shared/types/files';
import { WorkspaceQueryHandlerBase } from '@/main/queries/workspace-query-handler-base';
export class FileGetQueryHandler
extends WorkspaceQueryHandlerBase
implements QueryHandler<FileGetQueryInput>
{
- public async handleQuery(
- input: FileGetQueryInput
- ): Promise<FileWithState | null> {
+ public async handleQuery(input: FileGetQueryInput): Promise<File | null> {
return await this.fetchFile(input);
}
public async checkForChanges(
event: Event,
input: FileGetQueryInput,
- output: FileWithState | null
+ _: File | null
): Promise<ChangeCheckResult<FileGetQueryInput>> {
if (
event.type === 'workspace_deleted' &&
@@ -56,13 +50,7 @@ export class FileGetQueryHandler
) {
return {
hasChanges: true,
- result: {
- ...event.file,
- downloadProgress: output?.downloadProgress ?? 0,
- downloadStatus: output?.downloadStatus ?? DownloadStatus.None,
- uploadProgress: output?.uploadProgress ?? 0,
- uploadStatus: output?.uploadStatus ?? UploadStatus.None,
- },
+ result: event.file,
};
}
@@ -78,104 +66,24 @@ export class FileGetQueryHandler
};
}
- if (
- event.type === 'file_state_created' &&
- event.accountId === input.accountId &&
- event.workspaceId === input.workspaceId &&
- event.fileState.fileId === input.id
- ) {
- if (output === null) {
- const newResult = await this.fetchFile(input);
- return {
- hasChanges: true,
- result: newResult,
- };
- }
-
- return {
- hasChanges: true,
- result: {
- ...output,
- ...event.fileState,
- },
- };
- }
-
- if (
- event.type === 'file_state_updated' &&
- event.accountId === input.accountId &&
- event.workspaceId === input.workspaceId &&
- event.fileState.fileId === input.id
- ) {
- if (output === null) {
- const newResult = await this.fetchFile(input);
- return {
- hasChanges: true,
- result: newResult,
- };
- }
-
- return {
- hasChanges: true,
- result: {
- ...output,
- ...event.fileState,
- },
- };
- }
-
return {
hasChanges: false,
};
}
- private async fetchFile(
- input: FileGetQueryInput
- ): Promise<FileWithState | null> {
+ private async fetchFile(input: FileGetQueryInput): Promise<File | null> {
const workspace = this.getWorkspace(input.accountId, input.workspaceId);
const file = await workspace.database
- .selectFrom('files as f')
- .leftJoin('file_states as fs', 'f.id', 'fs.file_id')
- .select([
- 'f.id',
- 'f.type',
- 'f.parent_id',
- 'f.entry_id',
- 'f.root_id',
- 'f.name',
- 'f.original_name',
- 'f.mime_type',
- 'f.extension',
- 'f.size',
- 'f.created_at',
- 'f.created_by',
- 'f.updated_at',
- 'f.updated_by',
- 'f.deleted_at',
- 'f.status',
- 'f.version',
- 'fs.download_status',
- 'fs.download_progress',
- 'fs.upload_status',
- 'fs.upload_progress',
- ])
- .where('f.id', '=', input.id)
- .where('f.deleted_at', 'is', null)
+ .selectFrom('files')
+ .selectAll()
+ .where('id', '=', input.id)
.executeTakeFirst();
if (!file || file.deleted_at) {
return null;
}
- const fileWithState: FileWithState = {
- ...mapFile(file),
- downloadProgress: file.download_progress ?? 0,
- downloadStatus: file.download_status ?? DownloadStatus.None,
- uploadProgress: file.upload_progress ?? 0,
- uploadStatus: file.upload_status ?? UploadStatus.None,
- };
-
- return fileWithState;
+ return mapFile(file);
}
}
diff --git a/apps/desktop/src/main/queries/files/file-list.ts b/apps/desktop/src/main/queries/files/file-list.ts
index 5656de7e..0281bcec 100644
--- a/apps/desktop/src/main/queries/files/file-list.ts
+++ b/apps/desktop/src/main/queries/files/file-list.ts
@@ -2,27 +2,21 @@ import { ChangeCheckResult, QueryHandler } from '@/main/lib/types';
import { mapFile } from '@/main/lib/mappers';
import { FileListQueryInput } from '@/shared/queries/files/file-list';
import { Event } from '@/shared/types/events';
-import {
- DownloadStatus,
- FileWithState,
- UploadStatus,
-} from '@/shared/types/files';
+import { File } from '@/shared/types/files';
import { WorkspaceQueryHandlerBase } from '@/main/queries/workspace-query-handler-base';
export class FileListQueryHandler
extends WorkspaceQueryHandlerBase
implements QueryHandler<FileListQueryInput>
{
- public async handleQuery(
- input: FileListQueryInput
- ): Promise<FileWithState[]> {
+ public async handleQuery(input: FileListQueryInput): Promise<File[]> {
return await this.fetchFiles(input);
}
public async checkForChanges(
event: Event,
input: FileListQueryInput,
- output: FileWithState[]
+ output: File[]
): Promise<ChangeCheckResult<FileListQueryInput>> {
if (
event.type === 'workspace_deleted' &&
@@ -58,13 +52,7 @@ export class FileListQueryHandler
if (file) {
const newResult = output.map((file) => {
if (file.id === event.file.id) {
- return {
- ...event.file,
- downloadProgress: file.downloadProgress,
- downloadStatus: file.downloadStatus,
- uploadProgress: file.uploadProgress,
- uploadStatus: file.uploadStatus,
- };
+ return event.file;
}
return file;
@@ -93,106 +81,25 @@ export class FileListQueryHandler
}
}
- if (
- event.type === 'file_state_created' &&
- event.accountId === input.accountId &&
- event.workspaceId === input.workspaceId
- ) {
- const file = output.find((file) => file.id === event.fileState.fileId);
- if (file) {
- const newResult = output.map((file) => {
- if (file.id === event.fileState.fileId) {
- return {
- ...file,
- ...event.fileState,
- };
- }
- return file;
- });
-
- return {
- hasChanges: true,
- result: newResult,
- };
- }
- }
-
- if (
- event.type === 'file_state_updated' &&
- event.accountId === input.accountId &&
- event.workspaceId === input.workspaceId
- ) {
- const file = output.find((file) => file.id === event.fileState.fileId);
- if (file) {
- const newResult = output.map((file) => {
- if (file.id === event.fileState.fileId) {
- return {
- ...file,
- ...event.fileState,
- };
- }
- return file;
- });
-
- return {
- hasChanges: true,
- result: newResult,
- };
- }
- }
-
return {
hasChanges: false,
};
}
- private async fetchFiles(
- input: FileListQueryInput
- ): Promise<FileWithState[]> {
+ private async fetchFiles(input: FileListQueryInput): Promise<File[]> {
const workspace = this.getWorkspace(input.accountId, input.workspaceId);
const offset = (input.page - 1) * input.count;
const files = await workspace.database
- .selectFrom('files as f')
- .leftJoin('file_states as fs', 'f.id', 'fs.file_id')
- .select([
- 'f.id',
- 'f.type',
- 'f.parent_id',
- 'f.root_id',
- 'f.entry_id',
- 'f.name',
- 'f.original_name',
- 'f.mime_type',
- 'f.extension',
- 'f.size',
- 'f.created_at',
- 'f.created_by',
- 'f.updated_at',
- 'f.updated_by',
- 'f.deleted_at',
- 'f.status',
- 'f.version',
- 'fs.download_status',
- 'fs.download_progress',
- 'fs.upload_status',
- 'fs.upload_progress',
- ])
- .where('f.parent_id', '=', input.parentId)
- .where('f.deleted_at', 'is', null)
- .orderBy('f.id', 'asc')
+ .selectFrom('files')
+ .selectAll()
+ .where('parent_id', '=', input.parentId)
+ .where('deleted_at', 'is', null)
+ .orderBy('id', 'asc')
.limit(input.count)
.offset(offset)
.execute();
- const filesWithState: FileWithState[] = files.map((file) => ({
- ...mapFile(file),
- downloadProgress: file.download_progress ?? 0,
- downloadStatus: file.download_status ?? DownloadStatus.None,
- uploadProgress: file.upload_progress ?? 0,
- uploadStatus: file.upload_status ?? UploadStatus.None,
- }));
-
- return filesWithState;
+ return files.map(mapFile);
}
}
diff --git a/apps/desktop/src/main/queries/index.ts b/apps/desktop/src/main/queries/index.ts
index 942b3351..8a217fbf 100644
--- a/apps/desktop/src/main/queries/index.ts
+++ b/apps/desktop/src/main/queries/index.ts
@@ -9,18 +9,15 @@ import { EmojiGetBySkinIdQueryHandler } from '@/main/queries/emojis/emoji-get-by
import { FileListQueryHandler } from '@/main/queries/files/file-list';
import { FileGetQueryHandler } from '@/main/queries/files/file-get';
import { FileMetadataGetQueryHandler } from '@/main/queries/files/file-metadata-get';
-import { FileBreadcrumbGetQueryHandler } from '@/main/queries/files/file-breadcrumb-get';
import { IconListQueryHandler } from '@/main/queries/icons/icon-list';
import { IconSearchQueryHandler } from '@/main/queries/icons/icon-search';
import { IconCategoryListQueryHandler } from '@/main/queries/icons/icon-category-list';
-import { MessageGetQueryHandler } from '@/main/queries/messages/message-get';
import { MessageListQueryHandler } from '@/main/queries/messages/message-list';
-import { MessageReactionsListQueryHandler } from '@/main/queries/messages/message-reaction-list';
-import { MessageReactionsAggregateQueryHandler } from '@/main/queries/messages/message-reactions-aggregate';
-import { MessageBreadcrumbGetQueryHandler } from '@/main/queries/messages/message-breadcrumb-get';
-import { EntryChildrenGetQueryHandler } from '@/main/queries/entries/entry-children-get';
-import { EntryGetQueryHandler } from '@/main/queries/entries/entry-get';
-import { EntryBreadcrumbGetQueryHandler } from '@/main/queries/entries/entry-breadcrumb-get';
+import { NodeReactionsListQueryHandler } from '@/main/queries/nodes/node-reaction-list';
+import { NodeReactionsAggregateQueryHandler } from '@/main/queries/nodes/node-reactions-aggregate';
+import { NodeChildrenGetQueryHandler } from '@/main/queries/nodes/node-children-get';
+import { NodeGetQueryHandler } from '@/main/queries/nodes/node-get';
+import { NodeTreeGetQueryHandler } from '@/main/queries/nodes/node-tree-get';
import { RadarDataGetQueryHandler } from '@/main/queries/interactions/radar-data-get';
import { RecordListQueryHandler } from '@/main/queries/records/record-list';
import { ServerListQueryHandler } from '@/main/queries/servers/server-list';
@@ -29,6 +26,7 @@ import { WorkspaceGetQueryHandler } from '@/main/queries/workspaces/workspace-ge
import { WorkspaceListQueryHandler } from '@/main/queries/workspaces/workspace-list';
import { UserListQueryHandler } from '@/main/queries/users/user-list';
import { DatabaseListQueryHandler } from '@/main/queries/databases/database-list';
+import { DatabaseViewListQueryHandler } from '@/main/queries/databases/database-view-list';
import { RecordSearchQueryHandler } from '@/main/queries/records/record-search';
import { UserGetQueryHandler } from '@/main/queries/users/user-get';
import { SpaceListQueryHandler } from '@/main/queries/spaces/space-list';
@@ -45,12 +43,10 @@ export const queryHandlerMap: QueryHandlerMap = {
app_metadata_list: new AppMetadataListQueryHandler(),
account_list: new AccountListQueryHandler(),
message_list: new MessageListQueryHandler(),
- message_reaction_list: new MessageReactionsListQueryHandler(),
- message_reactions_aggregate: new MessageReactionsAggregateQueryHandler(),
- message_get: new MessageGetQueryHandler(),
- message_breadcrumb_get: new MessageBreadcrumbGetQueryHandler(),
- entry_get: new EntryGetQueryHandler(),
- entry_breadcrumb_get: new EntryBreadcrumbGetQueryHandler(),
+ node_reaction_list: new NodeReactionsListQueryHandler(),
+ node_reactions_aggregate: new NodeReactionsAggregateQueryHandler(),
+ node_get: new NodeGetQueryHandler(),
+ node_tree_get: new NodeTreeGetQueryHandler(),
record_list: new RecordListQueryHandler(),
server_list: new ServerListQueryHandler(),
user_search: new UserSearchQueryHandler(),
@@ -65,13 +61,13 @@ export const queryHandlerMap: QueryHandlerMap = {
icon_list: new IconListQueryHandler(),
icon_search: new IconSearchQueryHandler(),
icon_category_list: new IconCategoryListQueryHandler(),
- entry_children_get: new EntryChildrenGetQueryHandler(),
+ node_children_get: new NodeChildrenGetQueryHandler(),
radar_data_get: new RadarDataGetQueryHandler(),
file_metadata_get: new FileMetadataGetQueryHandler(),
- file_breadcrumb_get: new FileBreadcrumbGetQueryHandler(),
account_get: new AccountGetQueryHandler(),
workspace_get: new WorkspaceGetQueryHandler(),
database_list: new DatabaseListQueryHandler(),
+ database_view_list: new DatabaseViewListQueryHandler(),
record_search: new RecordSearchQueryHandler(),
user_get: new UserGetQueryHandler(),
file_get: new FileGetQueryHandler(),
diff --git a/apps/desktop/src/main/queries/messages/message-breadcrumb-get.ts b/apps/desktop/src/main/queries/messages/message-breadcrumb-get.ts
deleted file mode 100644
index aa431917..00000000
--- a/apps/desktop/src/main/queries/messages/message-breadcrumb-get.ts
+++ /dev/null
@@ -1,67 +0,0 @@
-import { ChangeCheckResult, QueryHandler } from '@/main/lib/types';
-import { MessageBreadcrumbGetQueryInput } from '@/shared/queries/messages/message-breadcrumb-get';
-import { Event } from '@/shared/types/events';
-import { WorkspaceQueryHandlerBase } from '@/main/queries/workspace-query-handler-base';
-import { fetchMessageBreadcrumb } from '@/main/lib/utils';
-
-export class MessageBreadcrumbGetQueryHandler
- extends WorkspaceQueryHandlerBase
- implements QueryHandler<MessageBreadcrumbGetQueryInput>
-{
- public async handleQuery(
- input: MessageBreadcrumbGetQueryInput
- ): Promise<string[]> {
- const workspace = this.getWorkspace(input.accountId, input.workspaceId);
- return fetchMessageBreadcrumb(workspace.database, input.messageId);
- }
-
- public async checkForChanges(
- event: Event,
- input: MessageBreadcrumbGetQueryInput,
- output: string[]
- ): Promise<ChangeCheckResult<MessageBreadcrumbGetQueryInput>> {
- if (
- event.type === 'workspace_deleted' &&
- event.workspace.accountId === input.accountId &&
- event.workspace.id === input.workspaceId
- ) {
- return {
- hasChanges: true,
- result: [],
- };
- }
-
- if (
- event.type === 'message_created' &&
- event.accountId === input.accountId &&
- event.workspaceId === input.workspaceId &&
- event.message.id === input.messageId
- ) {
- const newOutput = await this.handleQuery(input);
- return {
- hasChanges: true,
- result: newOutput,
- };
- }
-
- if (
- event.type === 'message_deleted' &&
- event.accountId === input.accountId &&
- event.workspaceId === input.workspaceId &&
- event.message.id === input.messageId
- ) {
- const messageId = output.find((id) => id === event.message.id);
- if (messageId) {
- const newOutput = await this.handleQuery(input);
- return {
- hasChanges: true,
- result: newOutput,
- };
- }
- }
-
- return {
- hasChanges: false,
- };
- }
-}
diff --git a/apps/desktop/src/main/queries/messages/message-get.ts b/apps/desktop/src/main/queries/messages/message-get.ts
deleted file mode 100644
index 88dc2c24..00000000
--- a/apps/desktop/src/main/queries/messages/message-get.ts
+++ /dev/null
@@ -1,90 +0,0 @@
-import { SelectMessage } from '@/main/databases/workspace';
-import { WorkspaceQueryHandlerBase } from '@/main/queries/workspace-query-handler-base';
-import { ChangeCheckResult, QueryHandler } from '@/main/lib/types';
-import { mapMessage } from '@/main/lib/mappers';
-import { MessageGetQueryInput } from '@/shared/queries/messages/message-get';
-import { Event } from '@/shared/types/events';
-import { MessageNode } from '@/shared/types/messages';
-
-export class MessageGetQueryHandler
- extends WorkspaceQueryHandlerBase
- implements QueryHandler<MessageGetQueryInput>
-{
- public async handleQuery(
- input: MessageGetQueryInput
- ): Promise<MessageNode | null> {
- const row = await this.fetchMessage(input);
- return row ? mapMessage(row) : null;
- }
-
- public async checkForChanges(
- event: Event,
- input: MessageGetQueryInput,
- _: MessageNode | null
- ): Promise<ChangeCheckResult<MessageGetQueryInput>> {
- if (
- event.type === 'workspace_deleted' &&
- event.workspace.accountId === input.accountId &&
- event.workspace.id === input.workspaceId
- ) {
- return {
- hasChanges: true,
- result: null,
- };
- }
-
- if (
- event.type === 'message_created' &&
- event.accountId === input.accountId &&
- event.workspaceId === input.workspaceId &&
- event.message.id === input.messageId
- ) {
- return {
- hasChanges: true,
- result: event.message,
- };
- }
-
- if (
- event.type === 'message_updated' &&
- event.accountId === input.accountId &&
- event.workspaceId === input.workspaceId &&
- event.message.id === input.messageId
- ) {
- return {
- hasChanges: true,
- result: event.message,
- };
- }
-
- if (
- event.type === 'message_deleted' &&
- event.accountId === input.accountId &&
- event.workspaceId === input.workspaceId &&
- event.message.id === input.messageId
- ) {
- return {
- hasChanges: true,
- result: null,
- };
- }
-
- return {
- hasChanges: false,
- };
- }
-
- private async fetchMessage(
- input: MessageGetQueryInput
- ): Promise<SelectMessage | undefined> {
- const workspace = this.getWorkspace(input.accountId, input.workspaceId);
-
- const row = await workspace.database
- .selectFrom('messages')
- .selectAll()
- .where('id', '=', input.messageId)
- .executeTakeFirst();
-
- return row;
- }
-}
diff --git a/apps/desktop/src/main/queries/messages/message-list.ts b/apps/desktop/src/main/queries/messages/message-list.ts
index d005ac66..893c6b36 100644
--- a/apps/desktop/src/main/queries/messages/message-list.ts
+++ b/apps/desktop/src/main/queries/messages/message-list.ts
@@ -2,11 +2,11 @@ import { compareString } from '@colanode/core';
import { WorkspaceQueryHandlerBase } from '@/main/queries/workspace-query-handler-base';
import { ChangeCheckResult, QueryHandler } from '@/main/lib/types';
-import { mapMessage } from '@/main/lib/mappers';
+import { mapNode } from '@/main/lib/mappers';
import { MessageListQueryInput } from '@/shared/queries/messages/message-list';
import { Event } from '@/shared/types/events';
-import { MessageNode } from '@/shared/types/messages';
-import { SelectMessage } from '@/main/databases/workspace';
+import { SelectNode } from '@/main/databases/workspace';
+import { LocalMessageNode } from '@/shared/types/nodes';
export class MessageListQueryHandler
extends WorkspaceQueryHandlerBase
@@ -14,15 +14,16 @@ export class MessageListQueryHandler
{
public async handleQuery(
input: MessageListQueryInput
- ): Promise<MessageNode[]> {
+ ): Promise<LocalMessageNode[]> {
const messages = await this.fetchMesssages(input);
- return this.buildMessages(messages);
+ const messageNodes = messages.map(mapNode) as LocalMessageNode[];
+ return messageNodes.sort((a, b) => compareString(a.id, b.id));
}
public async checkForChanges(
event: Event,
input: MessageListQueryInput,
- output: MessageNode[]
+ output: LocalMessageNode[]
): Promise<ChangeCheckResult<MessageListQueryInput>> {
if (
event.type === 'workspace_deleted' &&
@@ -36,10 +37,11 @@ export class MessageListQueryHandler
}
if (
- event.type === 'message_created' &&
+ event.type === 'node_created' &&
+ event.node.type === 'message' &&
event.accountId === input.accountId &&
event.workspaceId === input.workspaceId &&
- event.message.parentId === input.conversationId
+ event.node.parentId === input.conversationId
) {
const newResult = await this.handleQuery(input);
@@ -50,16 +52,17 @@ export class MessageListQueryHandler
}
if (
- event.type === 'message_updated' &&
+ event.type === 'node_updated' &&
+ event.node.type === 'message' &&
event.accountId === input.accountId &&
event.workspaceId === input.workspaceId &&
- event.message.parentId === input.conversationId
+ event.node.parentId === input.conversationId
) {
- const message = output.find((message) => message.id === event.message.id);
+ const message = output.find((message) => message.id === event.node.id);
if (message) {
const newResult = output.map((message) => {
- if (message.id === event.message.id) {
- return event.message;
+ if (message.id === event.node.id) {
+ return event.node as LocalMessageNode;
}
return message;
});
@@ -72,12 +75,13 @@ export class MessageListQueryHandler
}
if (
- event.type === 'message_deleted' &&
+ event.type === 'node_deleted' &&
+ event.node.type === 'message' &&
event.accountId === input.accountId &&
event.workspaceId === input.workspaceId &&
- event.message.parentId === input.conversationId
+ event.node.parentId === input.conversationId
) {
- const message = output.find((message) => message.id === event.message.id);
+ const message = output.find((message) => message.id === event.node.id);
if (message) {
const newOutput = await this.handleQuery(input);
@@ -95,15 +99,15 @@ export class MessageListQueryHandler
private async fetchMesssages(
input: MessageListQueryInput
- ): Promise<SelectMessage[]> {
+ ): Promise<SelectNode[]> {
const workspace = this.getWorkspace(input.accountId, input.workspaceId);
const offset = (input.page - 1) * input.count;
const messages = await workspace.database
- .selectFrom('messages')
+ .selectFrom('nodes')
.selectAll()
.where('parent_id', '=', input.conversationId)
- .where('deleted_at', 'is', null)
+ .where('type', '=', 'message')
.orderBy('id', 'desc')
.limit(input.count)
.offset(offset)
@@ -111,9 +115,4 @@ export class MessageListQueryHandler
return messages;
}
-
- private buildMessages = (rows: SelectMessage[]): MessageNode[] => {
- const messages = rows.map(mapMessage);
- return messages.sort((a, b) => compareString(a.id, b.id));
- };
}
diff --git a/apps/desktop/src/main/queries/nodes/node-children-get.ts b/apps/desktop/src/main/queries/nodes/node-children-get.ts
new file mode 100644
index 00000000..50cc9519
--- /dev/null
+++ b/apps/desktop/src/main/queries/nodes/node-children-get.ts
@@ -0,0 +1,106 @@
+import { SelectNode } from '@/main/databases/workspace';
+import { ChangeCheckResult, QueryHandler } from '@/main/lib/types';
+import { mapNode } from '@/main/lib/mappers';
+import { Event } from '@/shared/types/events';
+import { NodeChildrenGetQueryInput } from '@/shared/queries/nodes/node-children-get';
+import { WorkspaceQueryHandlerBase } from '@/main/queries/workspace-query-handler-base';
+import { LocalNode } from '@/shared/types/nodes';
+
+export class NodeChildrenGetQueryHandler
+ extends WorkspaceQueryHandlerBase
+ implements QueryHandler<NodeChildrenGetQueryInput>
+{
+ public async handleQuery(
+ input: NodeChildrenGetQueryInput
+ ): Promise<LocalNode[]> {
+ const rows = await this.fetchChildren(input);
+ return rows.map(mapNode) as LocalNode[];
+ }
+
+ public async checkForChanges(
+ event: Event,
+ input: NodeChildrenGetQueryInput,
+ output: LocalNode[]
+ ): Promise<ChangeCheckResult<NodeChildrenGetQueryInput>> {
+ if (
+ event.type === 'workspace_deleted' &&
+ event.workspace.accountId === input.accountId &&
+ event.workspace.id === input.workspaceId
+ ) {
+ return {
+ hasChanges: true,
+ result: [],
+ };
+ }
+
+ if (
+ event.type === 'node_created' &&
+ event.accountId === input.accountId &&
+ event.workspaceId === input.workspaceId &&
+ event.node.parentId === input.nodeId &&
+ (input.types === undefined || input.types.includes(event.node.type))
+ ) {
+ const newChildren = [...output, event.node];
+ return {
+ hasChanges: true,
+ result: newChildren,
+ };
+ }
+
+ if (
+ event.type === 'node_updated' &&
+ event.accountId === input.accountId &&
+ event.workspaceId === input.workspaceId &&
+ event.node.parentId === input.nodeId &&
+ (input.types === undefined || input.types.includes(event.node.type))
+ ) {
+ const node = output.find((n) => n.id === event.node.id);
+ if (node) {
+ const newChildren = output.map((node) =>
+ node.id === event.node.id ? event.node : node
+ );
+
+ return {
+ hasChanges: true,
+ result: newChildren,
+ };
+ }
+ }
+
+ if (
+ event.type === 'node_deleted' &&
+ event.accountId === input.accountId &&
+ event.workspaceId === input.workspaceId &&
+ event.node.parentId === input.nodeId &&
+ (input.types === undefined || input.types.includes(event.node.type))
+ ) {
+ const node = output.find((n) => n.id === event.node.id);
+ if (node) {
+ const newChildren = output.filter((n) => n.id !== event.node.id);
+ return {
+ hasChanges: true,
+ result: newChildren,
+ };
+ }
+ }
+
+ return {
+ hasChanges: false,
+ };
+ }
+
+ private async fetchChildren(
+ input: NodeChildrenGetQueryInput
+ ): Promise<SelectNode[]> {
+ const workspace = this.getWorkspace(input.accountId, input.workspaceId);
+
+ const rows = await workspace.database
+ .selectFrom('nodes')
+ .selectAll()
+ .where('parent_id', '=', input.nodeId)
+ .where('type', 'in', input.types ?? [])
+ .execute();
+
+ return rows;
+ }
+}
diff --git a/apps/desktop/src/main/queries/entries/entry-get.ts b/apps/desktop/src/main/queries/nodes/node-get.ts
similarity index 55%
rename from apps/desktop/src/main/queries/entries/entry-get.ts
rename to apps/desktop/src/main/queries/nodes/node-get.ts
index ef88ebb3..a800c10f 100644
--- a/apps/desktop/src/main/queries/entries/entry-get.ts
+++ b/apps/desktop/src/main/queries/nodes/node-get.ts
@@ -1,26 +1,27 @@
-import { Entry } from '@colanode/core';
-
-import { SelectEntry } from '@/main/databases/workspace';
+import { SelectNode } from '@/main/databases/workspace';
import { ChangeCheckResult, QueryHandler } from '@/main/lib/types';
-import { mapEntry } from '@/main/lib/mappers';
-import { EntryGetQueryInput } from '@/shared/queries/entries/entry-get';
+import { mapNode } from '@/main/lib/mappers';
+import { NodeGetQueryInput } from '@/shared/queries/nodes/node-get';
import { Event } from '@/shared/types/events';
import { WorkspaceQueryHandlerBase } from '@/main/queries/workspace-query-handler-base';
+import { LocalNode } from '@/shared/types/nodes';
-export class EntryGetQueryHandler
+export class NodeGetQueryHandler
extends WorkspaceQueryHandlerBase
- implements QueryHandler<EntryGetQueryInput>
+ implements QueryHandler<NodeGetQueryInput>
{
- public async handleQuery(input: EntryGetQueryInput): Promise<Entry | null> {
- const row = await this.fetchEntry(input);
- return row ? mapEntry(row) : null;
+ public async handleQuery(
+ input: NodeGetQueryInput
+ ): Promise<LocalNode | null> {
+ const row = await this.fetchNode(input);
+ return row ? mapNode(row) : null;
}
public async checkForChanges(
event: Event,
- input: EntryGetQueryInput,
- _: Entry | null
- ): Promise<ChangeCheckResult<EntryGetQueryInput>> {
+ input: NodeGetQueryInput,
+ _: LocalNode | null
+ ): Promise<ChangeCheckResult<NodeGetQueryInput>> {
if (
event.type === 'workspace_deleted' &&
event.workspace.accountId === input.accountId &&
@@ -33,34 +34,34 @@ export class EntryGetQueryHandler
}
if (
- event.type === 'entry_created' &&
+ event.type === 'node_created' &&
event.accountId === input.accountId &&
event.workspaceId === input.workspaceId &&
- event.entry.id === input.entryId
+ event.node.id === input.nodeId
) {
return {
hasChanges: true,
- result: event.entry,
+ result: event.node,
};
}
if (
- event.type === 'entry_updated' &&
+ event.type === 'node_updated' &&
event.accountId === input.accountId &&
event.workspaceId === input.workspaceId &&
- event.entry.id === input.entryId
+ event.node.id === input.nodeId
) {
return {
hasChanges: true,
- result: event.entry,
+ result: event.node,
};
}
if (
- event.type === 'entry_deleted' &&
+ event.type === 'node_deleted' &&
event.accountId === input.accountId &&
event.workspaceId === input.workspaceId &&
- event.entry.id === input.entryId
+ event.node.id === input.nodeId
) {
return {
hasChanges: true,
@@ -73,15 +74,15 @@ export class EntryGetQueryHandler
};
}
- private async fetchEntry(
- input: EntryGetQueryInput
- ): Promise<SelectEntry | undefined> {
+ private async fetchNode(
+ input: NodeGetQueryInput
+ ): Promise<SelectNode | undefined> {
const workspace = this.getWorkspace(input.accountId, input.workspaceId);
const row = await workspace.database
- .selectFrom('entries')
+ .selectFrom('nodes')
.selectAll()
- .where('id', '=', input.entryId)
+ .where('id', '=', input.nodeId)
.executeTakeFirst();
return row;
diff --git a/apps/desktop/src/main/queries/messages/message-reaction-list.ts b/apps/desktop/src/main/queries/nodes/node-reaction-list.ts
similarity index 62%
rename from apps/desktop/src/main/queries/messages/message-reaction-list.ts
rename to apps/desktop/src/main/queries/nodes/node-reaction-list.ts
index b112f69f..9e68094d 100644
--- a/apps/desktop/src/main/queries/messages/message-reaction-list.ts
+++ b/apps/desktop/src/main/queries/nodes/node-reaction-list.ts
@@ -1,24 +1,24 @@
import { ChangeCheckResult, QueryHandler } from '@/main/lib/types';
-import { MessageReactionListQueryInput } from '@/shared/queries/messages/message-reaction-list';
+import { NodeReactionListQueryInput } from '@/shared/queries/nodes/node-reaction-list';
import { Event } from '@/shared/types/events';
-import { MessageReaction } from '@/shared/types/messages';
+import { NodeReaction } from '@/shared/types/nodes';
import { WorkspaceQueryHandlerBase } from '@/main/queries/workspace-query-handler-base';
-export class MessageReactionsListQueryHandler
+export class NodeReactionsListQueryHandler
extends WorkspaceQueryHandlerBase
- implements QueryHandler<MessageReactionListQueryInput>
+ implements QueryHandler<NodeReactionListQueryInput>
{
public async handleQuery(
- input: MessageReactionListQueryInput
- ): Promise<MessageReaction[]> {
- return this.fetchMessageReactions(input);
+ input: NodeReactionListQueryInput
+ ): Promise<NodeReaction[]> {
+ return this.fetchNodeReactions(input);
}
public async checkForChanges(
event: Event,
- input: MessageReactionListQueryInput,
- _: MessageReaction[]
- ): Promise<ChangeCheckResult<MessageReactionListQueryInput>> {
+ input: NodeReactionListQueryInput,
+ _: NodeReaction[]
+ ): Promise<ChangeCheckResult<NodeReactionListQueryInput>> {
if (
event.type === 'workspace_deleted' &&
event.workspace.accountId === input.accountId &&
@@ -31,10 +31,10 @@ export class MessageReactionsListQueryHandler
}
if (
- event.type === 'message_reaction_created' &&
+ event.type === 'node_reaction_created' &&
event.accountId === input.accountId &&
event.workspaceId === input.workspaceId &&
- event.messageReaction.messageId === input.messageId
+ event.nodeReaction.nodeId === input.nodeId
) {
const newResult = await this.handleQuery(input);
@@ -45,10 +45,10 @@ export class MessageReactionsListQueryHandler
}
if (
- event.type === 'message_reaction_deleted' &&
+ event.type === 'node_reaction_deleted' &&
event.accountId === input.accountId &&
event.workspaceId === input.workspaceId &&
- event.messageReaction.messageId === input.messageId
+ event.nodeReaction.nodeId === input.nodeId
) {
const newResult = await this.handleQuery(input);
@@ -63,18 +63,17 @@ export class MessageReactionsListQueryHandler
};
}
- private async fetchMessageReactions(
- input: MessageReactionListQueryInput
- ): Promise<MessageReaction[]> {
+ private async fetchNodeReactions(
+ input: NodeReactionListQueryInput
+ ): Promise<NodeReaction[]> {
const workspace = this.getWorkspace(input.accountId, input.workspaceId);
const offset = (input.page - 1) * input.count;
const reactions = await workspace.database
- .selectFrom('message_reactions')
+ .selectFrom('node_reactions')
.selectAll()
- .where('message_id', '=', input.messageId)
+ .where('node_id', '=', input.nodeId)
.where('reaction', '=', input.reaction)
- .where('deleted_at', 'is', null)
.orderBy('created_at', 'desc')
.limit(input.count)
.offset(offset)
@@ -82,7 +81,7 @@ export class MessageReactionsListQueryHandler
return reactions.map((row) => {
return {
- messageId: row.message_id,
+ nodeId: row.node_id,
collaboratorId: row.collaborator_id,
rootId: row.root_id,
reaction: row.reaction,
diff --git a/apps/desktop/src/main/queries/messages/message-reactions-aggregate.ts b/apps/desktop/src/main/queries/nodes/node-reactions-aggregate.ts
similarity index 61%
rename from apps/desktop/src/main/queries/messages/message-reactions-aggregate.ts
rename to apps/desktop/src/main/queries/nodes/node-reactions-aggregate.ts
index 1a033cbe..95708e1d 100644
--- a/apps/desktop/src/main/queries/messages/message-reactions-aggregate.ts
+++ b/apps/desktop/src/main/queries/nodes/node-reactions-aggregate.ts
@@ -1,32 +1,32 @@
import { sql } from 'kysely';
import { ChangeCheckResult, QueryHandler } from '@/main/lib/types';
-import { MessageReactionsAggregateQueryInput } from '@/shared/queries/messages/message-reactions-aggregate';
+import { NodeReactionsAggregateQueryInput } from '@/shared/queries/nodes/node-reactions-aggregate';
import { Event } from '@/shared/types/events';
-import { MessageReactionCount } from '@/shared/types/messages';
+import { NodeReactionCount } from '@/shared/types/nodes';
import { WorkspaceQueryHandlerBase } from '@/main/queries/workspace-query-handler-base';
-interface MessageReactionsAggregateRow {
+interface NodeReactionsAggregateRow {
reaction: string;
count: number;
reacted: number;
}
-export class MessageReactionsAggregateQueryHandler
+export class NodeReactionsAggregateQueryHandler
extends WorkspaceQueryHandlerBase
- implements QueryHandler<MessageReactionsAggregateQueryInput>
+ implements QueryHandler<NodeReactionsAggregateQueryInput>
{
public async handleQuery(
- input: MessageReactionsAggregateQueryInput
- ): Promise<MessageReactionCount[]> {
- return this.fetchMessageReactions(input);
+ input: NodeReactionsAggregateQueryInput
+ ): Promise<NodeReactionCount[]> {
+ return this.fetchNodeReactions(input);
}
public async checkForChanges(
event: Event,
- input: MessageReactionsAggregateQueryInput,
- _: MessageReactionCount[]
- ): Promise<ChangeCheckResult<MessageReactionsAggregateQueryInput>> {
+ input: NodeReactionsAggregateQueryInput,
+ _: NodeReactionCount[]
+ ): Promise<ChangeCheckResult<NodeReactionsAggregateQueryInput>> {
if (
event.type === 'workspace_deleted' &&
event.workspace.accountId === input.accountId &&
@@ -39,10 +39,10 @@ export class MessageReactionsAggregateQueryHandler
}
if (
- event.type === 'message_reaction_created' &&
+ event.type === 'node_reaction_created' &&
event.accountId === input.accountId &&
event.workspaceId === input.workspaceId &&
- event.messageReaction.messageId === input.messageId
+ event.nodeReaction.nodeId === input.nodeId
) {
const newResult = await this.handleQuery(input);
@@ -53,10 +53,10 @@ export class MessageReactionsAggregateQueryHandler
}
if (
- event.type === 'message_reaction_deleted' &&
+ event.type === 'node_reaction_deleted' &&
event.accountId === input.accountId &&
event.workspaceId === input.workspaceId &&
- event.messageReaction.messageId === input.messageId
+ event.nodeReaction.nodeId === input.nodeId
) {
const newResult = await this.handleQuery(input);
@@ -71,12 +71,12 @@ export class MessageReactionsAggregateQueryHandler
};
}
- private async fetchMessageReactions(
- input: MessageReactionsAggregateQueryInput
- ): Promise<MessageReactionCount[]> {
+ private async fetchNodeReactions(
+ input: NodeReactionsAggregateQueryInput
+ ): Promise<NodeReactionCount[]> {
const workspace = this.getWorkspace(input.accountId, input.workspaceId);
- const result = await sql<MessageReactionsAggregateRow>`
+ const result = await sql<NodeReactionsAggregateRow>`
SELECT
reaction,
COUNT(reaction) as count,
@@ -84,8 +84,8 @@ export class MessageReactionsAggregateQueryHandler
WHEN collaborator_id = ${workspace.userId} THEN 1
ELSE 0
END) as reacted
- FROM message_reactions
- WHERE message_id = ${input.messageId} AND deleted_at IS NULL
+ FROM node_reactions
+ WHERE node_id = ${input.nodeId}
GROUP BY reaction
`.execute(workspace.database);
diff --git a/apps/desktop/src/main/queries/entries/entry-breadcrumb-get.ts b/apps/desktop/src/main/queries/nodes/node-tree-get.ts
similarity index 59%
rename from apps/desktop/src/main/queries/entries/entry-breadcrumb-get.ts
rename to apps/desktop/src/main/queries/nodes/node-tree-get.ts
index 2ca8ec67..c5188e78 100644
--- a/apps/desktop/src/main/queries/entries/entry-breadcrumb-get.ts
+++ b/apps/desktop/src/main/queries/nodes/node-tree-get.ts
@@ -1,25 +1,26 @@
import { ChangeCheckResult, QueryHandler } from '@/main/lib/types';
-import { fetchEntryBreadcrumb } from '@/main/lib/utils';
-import { EntryBreadcrumbGetQueryInput } from '@/shared/queries/entries/entry-breadcrumb-get';
+import { NodeTreeGetQueryInput } from '@/shared/queries/nodes/node-tree-get';
import { Event } from '@/shared/types/events';
import { WorkspaceQueryHandlerBase } from '@/main/queries/workspace-query-handler-base';
+import { fetchNodeAncestors } from '@/main/lib/utils';
+import { mapNode } from '@/main/lib/mappers';
+import { LocalNode } from '@/shared/types/nodes';
-export class EntryBreadcrumbGetQueryHandler
+export class NodeTreeGetQueryHandler
extends WorkspaceQueryHandlerBase
- implements QueryHandler<EntryBreadcrumbGetQueryInput>
+ implements QueryHandler<NodeTreeGetQueryInput>
{
- public async handleQuery(
- input: EntryBreadcrumbGetQueryInput
- ): Promise<string[]> {
+ public async handleQuery(input: NodeTreeGetQueryInput): Promise<LocalNode[]> {
const workspace = this.getWorkspace(input.accountId, input.workspaceId);
- return fetchEntryBreadcrumb(workspace.database, input.entryId);
+ const rows = await fetchNodeAncestors(workspace.database, input.nodeId);
+ return rows.map(mapNode);
}
public async checkForChanges(
event: Event,
- input: EntryBreadcrumbGetQueryInput,
- output: string[]
- ): Promise<ChangeCheckResult<EntryBreadcrumbGetQueryInput>> {
+ input: NodeTreeGetQueryInput,
+ output: LocalNode[]
+ ): Promise<ChangeCheckResult<NodeTreeGetQueryInput>> {
if (
event.type === 'workspace_deleted' &&
event.workspace.accountId === input.accountId &&
@@ -32,10 +33,10 @@ export class EntryBreadcrumbGetQueryHandler
}
if (
- event.type === 'entry_created' &&
+ event.type === 'node_created' &&
event.accountId === input.accountId &&
event.workspaceId === input.workspaceId &&
- event.entry.id === input.entryId
+ event.node.id === input.nodeId
) {
const newResult = await this.handleQuery(input);
return {
@@ -45,12 +46,12 @@ export class EntryBreadcrumbGetQueryHandler
}
if (
- event.type === 'entry_deleted' &&
+ event.type === 'node_deleted' &&
event.accountId === input.accountId &&
event.workspaceId === input.workspaceId
) {
- const entryId = output.find((id) => id === event.entry.id);
- if (entryId) {
+ const node = output.find((n) => n.id === event.node.id);
+ if (node) {
const newResult = await this.handleQuery(input);
return {
hasChanges: true,
diff --git a/apps/desktop/src/main/queries/records/record-list.ts b/apps/desktop/src/main/queries/records/record-list.ts
index 479230fc..9af48ffb 100644
--- a/apps/desktop/src/main/queries/records/record-list.ts
+++ b/apps/desktop/src/main/queries/records/record-list.ts
@@ -1,30 +1,30 @@
import {
BooleanFieldAttributes,
CreatedAtFieldAttributes,
- DatabaseEntry,
+ DatabaseNode,
DateFieldAttributes,
EmailFieldAttributes,
FieldAttributes,
isStringArray,
- MultiSelectFieldAttributes,
NumberFieldAttributes,
PhoneFieldAttributes,
- RecordEntry,
SelectFieldAttributes,
TextFieldAttributes,
UrlFieldAttributes,
- ViewFieldFilterAttributes,
- ViewFilterAttributes,
- ViewSortAttributes,
+ DatabaseViewFieldFilterAttributes,
+ DatabaseViewFilterAttributes,
+ DatabaseViewSortAttributes,
+ MultiSelectFieldAttributes,
} from '@colanode/core';
import { sql } from 'kysely';
import { WorkspaceQueryHandlerBase } from '@/main/queries/workspace-query-handler-base';
import { ChangeCheckResult, QueryHandler } from '@/main/lib/types';
-import { mapEntry } from '@/main/lib/mappers';
+import { mapNode } from '@/main/lib/mappers';
import { RecordListQueryInput } from '@/shared/queries/records/record-list';
import { Event } from '@/shared/types/events';
-import { SelectEntry } from '@/main/databases/workspace';
+import { SelectNode } from '@/main/databases/workspace';
+import { LocalRecordNode } from '@/shared/types/nodes';
export class RecordListQueryHandler
extends WorkspaceQueryHandlerBase
@@ -32,15 +32,15 @@ export class RecordListQueryHandler
{
public async handleQuery(
input: RecordListQueryInput
- ): Promise<RecordEntry[]> {
+ ): Promise<LocalRecordNode[]> {
const rows = await this.fetchRecords(input);
- return this.buildRecords(rows);
+ return rows.map(mapNode) as LocalRecordNode[];
}
public async checkForChanges(
event: Event,
input: RecordListQueryInput,
- output: RecordEntry[]
+ output: LocalRecordNode[]
): Promise<ChangeCheckResult<RecordListQueryInput>> {
if (
event.type === 'workspace_deleted' &&
@@ -54,10 +54,10 @@ export class RecordListQueryHandler
}
if (
- event.type === 'entry_created' &&
+ event.type === 'node_created' &&
event.accountId === input.accountId &&
event.workspaceId === input.workspaceId &&
- event.entry.type === 'record'
+ event.node.type === 'record'
) {
const newResult = await this.handleQuery(input);
return {
@@ -67,13 +67,13 @@ export class RecordListQueryHandler
}
if (
- event.type === 'entry_updated' &&
+ event.type === 'node_updated' &&
event.accountId === input.accountId &&
event.workspaceId === input.workspaceId
) {
if (
- event.entry.type === 'record' &&
- event.entry.attributes.databaseId === input.databaseId
+ event.node.type === 'record' &&
+ event.node.attributes.databaseId === input.databaseId
) {
if (input.filters.length > 0 || input.sorts.length > 0) {
const newResult = await this.handleQuery(input);
@@ -83,11 +83,11 @@ export class RecordListQueryHandler
};
}
- const record = output.find((record) => record.id === event.entry.id);
+ const record = output.find((record) => record.id === event.node.id);
if (record) {
const newResult = output.map((record) => {
- if (record.id === event.entry.id) {
- return event.entry as RecordEntry;
+ if (record.id === event.node.id) {
+ return event.node as LocalRecordNode;
}
return record;
});
@@ -100,8 +100,8 @@ export class RecordListQueryHandler
}
if (
- event.entry.type === 'database' &&
- event.entry.id === input.databaseId
+ event.node.type === 'database' &&
+ event.node.id === input.databaseId
) {
const newResult = await this.handleQuery(input);
return {
@@ -112,13 +112,13 @@ export class RecordListQueryHandler
}
if (
- event.type === 'entry_deleted' &&
+ event.type === 'node_deleted' &&
event.accountId === input.accountId &&
event.workspaceId === input.workspaceId
) {
if (
- event.entry.type === 'record' &&
- event.entry.attributes.databaseId === input.databaseId
+ event.node.type === 'record' &&
+ event.node.attributes.databaseId === input.databaseId
) {
const newResult = await this.handleQuery(input);
return {
@@ -128,8 +128,8 @@ export class RecordListQueryHandler
}
if (
- event.entry.type === 'database' &&
- event.entry.id === input.databaseId
+ event.node.type === 'database' &&
+ event.node.id === input.databaseId
) {
return {
hasChanges: true,
@@ -145,7 +145,7 @@ export class RecordListQueryHandler
private async fetchRecords(
input: RecordListQueryInput
- ): Promise<SelectEntry[]> {
+ ): Promise<SelectNode[]> {
const database = await this.fetchDatabase(input);
const filterQuery = this.buildFiltersQuery(
input.filters,
@@ -153,12 +153,12 @@ export class RecordListQueryHandler
);
const workspace = this.getWorkspace(input.accountId, input.workspaceId);
- const orderByQuery = `ORDER BY ${input.sorts.length > 0 ? this.buildSortOrdersQuery(input.sorts, database.attributes.fields) : 'e."id" ASC'}`;
+ const orderByQuery = `ORDER BY ${input.sorts.length > 0 ? this.buildSortOrdersQuery(input.sorts, database.attributes.fields) : 'n."id" ASC'}`;
const offset = (input.page - 1) * input.count;
- const query = sql<SelectEntry>`
- SELECT e.*
- FROM entries e
- WHERE e.parent_id = ${input.databaseId} AND e.type = 'record' ${sql.raw(filterQuery)}
+ const query = sql<SelectNode>`
+ SELECT n.*
+ FROM nodes n
+ WHERE n.parent_id = ${input.databaseId} AND n.type = 'record' ${sql.raw(filterQuery)}
${sql.raw(orderByQuery)}
LIMIT ${sql.lit(input.count)}
OFFSET ${sql.lit(offset)}
@@ -168,28 +168,13 @@ export class RecordListQueryHandler
return result.rows;
}
- private buildRecords = (rows: SelectEntry[]): RecordEntry[] => {
- const entries = rows.map(mapEntry);
- const recordEntries: RecordEntry[] = [];
-
- for (const entry of entries) {
- if (entry.type !== 'record') {
- continue;
- }
-
- recordEntries.push(entry);
- }
-
- return recordEntries;
- };
-
private async fetchDatabase(
input: RecordListQueryInput
- ): Promise<DatabaseEntry> {
+ ): Promise<DatabaseNode> {
const workspace = this.getWorkspace(input.accountId, input.workspaceId);
const row = await workspace.database
- .selectFrom('entries')
+ .selectFrom('nodes')
.where('id', '=', input.databaseId)
.selectAll()
.executeTakeFirst();
@@ -198,12 +183,12 @@ export class RecordListQueryHandler
throw new Error('Database not found');
}
- const database = mapEntry(row) as DatabaseEntry;
+ const database = mapNode(row) as DatabaseNode;
return database;
}
private buildFiltersQuery = (
- filters: ViewFilterAttributes[],
+ filters: DatabaseViewFilterAttributes[],
fields: Record<string, FieldAttributes>
): string => {
if (filters.length === 0) {
@@ -222,7 +207,7 @@ export class RecordListQueryHandler
};
private buildFilterQuery = (
- filter: ViewFilterAttributes,
+ filter: DatabaseViewFilterAttributes,
fields: Record<string, FieldAttributes>
): string | null => {
if (filter.type === 'group') {
@@ -239,9 +224,9 @@ export class RecordListQueryHandler
return this.buildBooleanFilterQuery(filter, field);
case 'collaborator':
return null;
- case 'createdAt':
+ case 'created_at':
return this.buildCreatedAtFilterQuery(filter, field);
- case 'createdBy':
+ case 'created_by':
return null;
case 'date':
return this.buildDateFilterQuery(filter, field);
@@ -249,7 +234,7 @@ export class RecordListQueryHandler
return this.buildEmailFilterQuery(filter, field);
case 'file':
return null;
- case 'multiSelect':
+ case 'multi_select':
return this.buildMultiSelectFilterQuery(filter, field);
case 'number':
return this.buildNumberFilterQuery(filter, field);
@@ -267,22 +252,22 @@ export class RecordListQueryHandler
};
private buildBooleanFilterQuery = (
- filter: ViewFieldFilterAttributes,
+ filter: DatabaseViewFieldFilterAttributes,
field: BooleanFieldAttributes
): string | null => {
if (filter.operator === 'is_true') {
- return `json_extract(e.attributes, '$.fields.${field.id}.value') = true`;
+ return `json_extract(n.attributes, '$.fields.${field.id}.value') = true`;
}
if (filter.operator === 'is_false') {
- return `(json_extract(e.attributes, '$.fields.${field.id}.value') = false OR json_extract(e.attributes, '$.fields.${field.id}.value') IS NULL)`;
+ return `(json_extract(n.attributes, '$.fields.${field.id}.value') = false OR json_extract(n.attributes, '$.fields.${field.id}.value') IS NULL)`;
}
return null;
};
private buildNumberFilterQuery = (
- filter: ViewFieldFilterAttributes,
+ filter: DatabaseViewFieldFilterAttributes,
field: NumberFieldAttributes
): string | null => {
if (filter.operator === 'is_empty') {
@@ -331,11 +316,11 @@ export class RecordListQueryHandler
return null;
}
- return `json_extract(e.attributes, '$.fields.${field.id}.value') ${operator} ${value}`;
+ return `json_extract(n.attributes, '$.fields.${field.id}.value') ${operator} ${value}`;
};
private buildTextFilterQuery = (
- filter: ViewFieldFilterAttributes,
+ filter: DatabaseViewFieldFilterAttributes,
field: TextFieldAttributes
): string | null => {
if (filter.operator === 'is_empty') {
@@ -389,11 +374,11 @@ export class RecordListQueryHandler
return null;
}
- return `json_extract(e.attributes, '$.fields.${field.id}.value') ${operator} '${formattedValue}'`;
+ return `json_extract(n.attributes, '$.fields.${field.id}.value') ${operator} '${formattedValue}'`;
};
private buildEmailFilterQuery = (
- filter: ViewFieldFilterAttributes,
+ filter: DatabaseViewFieldFilterAttributes,
field: EmailFieldAttributes
): string | null => {
if (filter.operator === 'is_empty') {
@@ -447,11 +432,11 @@ export class RecordListQueryHandler
return null;
}
- return `json_extract(e.attributes, '$.fields.${field.id}.value') ${operator} '${formattedValue}'`;
+ return `json_extract(n.attributes, '$.fields.${field.id}.value') ${operator} '${formattedValue}'`;
};
private buildPhoneFilterQuery = (
- filter: ViewFieldFilterAttributes,
+ filter: DatabaseViewFieldFilterAttributes,
field: PhoneFieldAttributes
): string | null => {
if (filter.operator === 'is_empty') {
@@ -505,11 +490,11 @@ export class RecordListQueryHandler
return null;
}
- return `json_extract(e.attributes, '$.fields.${field.id}.value') ${operator} '${formattedValue}'`;
+ return `json_extract(n.attributes, '$.fields.${field.id}.value') ${operator} '${formattedValue}'`;
};
private buildUrlFilterQuery = (
- filter: ViewFieldFilterAttributes,
+ filter: DatabaseViewFieldFilterAttributes,
field: UrlFieldAttributes
): string | null => {
if (filter.operator === 'is_empty') {
@@ -563,11 +548,11 @@ export class RecordListQueryHandler
return null;
}
- return `json_extract(e.attributes, '$.fields.${field.id}.value') ${operator} '${formattedValue}'`;
+ return `json_extract(n.attributes, '$.fields.${field.id}.value') ${operator} '${formattedValue}'`;
};
private buildSelectFilterQuery = (
- filter: ViewFieldFilterAttributes,
+ filter: DatabaseViewFieldFilterAttributes,
field: SelectFieldAttributes
): string | null => {
if (filter.operator === 'is_empty') {
@@ -589,24 +574,24 @@ export class RecordListQueryHandler
const values = this.joinIds(filter.value);
switch (filter.operator) {
case 'is_in':
- return `json_extract(e.attributes, '$.fields.${field.id}.value') IN (${values})`;
+ return `json_extract(n.attributes, '$.fields.${field.id}.value') IN (${values})`;
case 'is_not_in':
- return `json_extract(e.attributes, '$.fields.${field.id}.value') NOT IN (${values})`;
+ return `json_extract(n.attributes, '$.fields.${field.id}.value') NOT IN (${values})`;
default:
return null;
}
};
private buildMultiSelectFilterQuery = (
- filter: ViewFieldFilterAttributes,
+ filter: DatabaseViewFieldFilterAttributes,
field: MultiSelectFieldAttributes
): string | null => {
if (filter.operator === 'is_empty') {
- return `json_extract(e.attributes, '$.fields.${field.id}.value') IS NULL OR json_array_length(json_extract(e.attributes, '$.fields.${field.id}.value')) = 0`;
+ return `json_extract(n.attributes, '$.fields.${field.id}.value') IS NULL OR json_array_length(json_extract(n.attributes, '$.fields.${field.id}.value')) = 0`;
}
if (filter.operator === 'is_not_empty') {
- return `json_extract(e.attributes, '$.fields.${field.id}.value') IS NOT NULL AND json_array_length(json_extract(e.attributes, '$.fields.${field.id}.value')) > 0`;
+ return `json_extract(n.attributes, '$.fields.${field.id}.value') IS NOT NULL AND json_array_length(json_extract(n.attributes, '$.fields.${field.id}.value')) > 0`;
}
if (!isStringArray(filter.value)) {
@@ -620,16 +605,16 @@ export class RecordListQueryHandler
const values = this.joinIds(filter.value);
switch (filter.operator) {
case 'is_in':
- return `EXISTS (SELECT 1 FROM json_each(json_extract(e.attributes, '$.fields.${field.id}.value')) WHERE json_each.value IN (${values}))`;
+ return `EXISTS (SELECT 1 FROM json_each(json_extract(n.attributes, '$.fields.${field.id}.value')) WHERE json_each.value IN (${values}))`;
case 'is_not_in':
- return `NOT EXISTS (SELECT 1 FROM json_each(json_extract(e.attributes, '$.fields.${field.id}.value')) WHERE json_each.value IN (${values}))`;
+ return `NOT EXISTS (SELECT 1 FROM json_each(json_extract(n.attributes, '$.fields.${field.id}.value')) WHERE json_each.value IN (${values}))`;
default:
return null;
}
};
private buildDateFilterQuery = (
- filter: ViewFieldFilterAttributes,
+ filter: DatabaseViewFieldFilterAttributes,
field: DateFieldAttributes
): string | null => {
if (filter.operator === 'is_empty') {
@@ -683,19 +668,19 @@ export class RecordListQueryHandler
return null;
}
- return `DATE(json_extract(e.attributes, '$.fields.${field.id}.value')) ${operator} '${dateString}'`;
+ return `DATE(json_extract(n.attributes, '$.fields.${field.id}.value')) ${operator} '${dateString}'`;
};
private buildCreatedAtFilterQuery = (
- filter: ViewFieldFilterAttributes,
+ filter: DatabaseViewFieldFilterAttributes,
_: CreatedAtFieldAttributes
): string | null => {
if (filter.operator === 'is_empty') {
- return `e.created_at IS NULL`;
+ return `n.created_at IS NULL`;
}
if (filter.operator === 'is_not_empty') {
- return `e.created_at IS NOT NULL`;
+ return `n.created_at IS NOT NULL`;
}
if (filter.value === null) {
@@ -741,15 +726,15 @@ export class RecordListQueryHandler
return null;
}
- return `DATE(e.created_at) ${operator} '${dateString}'`;
+ return `DATE(n.created_at) ${operator} '${dateString}'`;
};
private buildIsEmptyFilterQuery = (fieldId: string): string => {
- return `json_extract(e.attributes, '$.fields.${fieldId}.value') IS NULL`;
+ return `json_extract(n.attributes, '$.fields.${fieldId}.value') IS NULL`;
};
private buildIsNotEmptyFilterQuery = (fieldId: string): string => {
- return `json_extract(e.attributes, '$.fields.${fieldId}.value') IS NOT NULL`;
+ return `json_extract(n.attributes, '$.fields.${fieldId}.value') IS NOT NULL`;
};
private joinIds = (ids: string[]): string => {
@@ -757,7 +742,7 @@ export class RecordListQueryHandler
};
private buildSortOrdersQuery = (
- sorts: ViewSortAttributes[],
+ sorts: DatabaseViewSortAttributes[],
fields: Record<string, FieldAttributes>
): string => {
return sorts
@@ -767,7 +752,7 @@ export class RecordListQueryHandler
};
private buildSortOrderQuery = (
- sort: ViewSortAttributes,
+ sort: DatabaseViewSortAttributes,
fields: Record<string, FieldAttributes>
): string | null => {
const field = fields[sort.fieldId];
@@ -775,14 +760,14 @@ export class RecordListQueryHandler
return null;
}
- if (field.type === 'createdAt') {
- return `e.created_at ${sort.direction}`;
+ if (field.type === 'created_at') {
+ return `n.created_at ${sort.direction}`;
}
- if (field.type === 'createdBy') {
- return `e.created_by_id ${sort.direction}`;
+ if (field.type === 'created_by') {
+ return `n.created_by_id ${sort.direction}`;
}
- return `json_extract(e.attributes, '$.fields.${field.id}.value') ${sort.direction}`;
+ return `json_extract(n.attributes, '$.fields.${field.id}.value') ${sort.direction}`;
};
}
diff --git a/apps/desktop/src/main/queries/records/record-search.ts b/apps/desktop/src/main/queries/records/record-search.ts
index cfb79cf2..d883edf0 100644
--- a/apps/desktop/src/main/queries/records/record-search.ts
+++ b/apps/desktop/src/main/queries/records/record-search.ts
@@ -1,12 +1,12 @@
-import { RecordEntry } from '@colanode/core';
import { sql } from 'kysely';
import { ChangeCheckResult, QueryHandler } from '@/main/lib/types';
-import { mapEntry } from '@/main/lib/mappers';
+import { mapNode } from '@/main/lib/mappers';
import { RecordSearchQueryInput } from '@/shared/queries/records/record-search';
import { Event } from '@/shared/types/events';
-import { SelectEntry } from '@/main/databases/workspace';
+import { SelectNode } from '@/main/databases/workspace';
import { WorkspaceQueryHandlerBase } from '@/main/queries/workspace-query-handler-base';
+import { LocalRecordNode } from '@/shared/types/nodes';
export class RecordSearchQueryHandler
extends WorkspaceQueryHandlerBase
@@ -14,19 +14,19 @@ export class RecordSearchQueryHandler
{
public async handleQuery(
input: RecordSearchQueryInput
- ): Promise<RecordEntry[]> {
+ ): Promise<LocalRecordNode[]> {
const rows =
input.searchQuery.length > 0
? await this.searchRecords(input)
: await this.fetchRecords(input);
- return this.buildRecordEntries(rows);
+ return rows.map((row) => mapNode(row) as LocalRecordNode);
}
public async checkForChanges(
event: Event,
input: RecordSearchQueryInput,
- _: RecordEntry[]
+ _: LocalRecordNode[]
): Promise<ChangeCheckResult<RecordSearchQueryInput>> {
if (
event.type === 'workspace_deleted' &&
@@ -40,11 +40,11 @@ export class RecordSearchQueryHandler
}
if (
- event.type === 'entry_created' &&
+ event.type === 'node_created' &&
event.accountId === input.accountId &&
event.workspaceId === input.workspaceId &&
- event.entry.type === 'record' &&
- event.entry.attributes.databaseId === input.databaseId
+ event.node.type === 'record' &&
+ event.node.attributes.databaseId === input.databaseId
) {
const newResult = await this.handleQuery(input);
return {
@@ -54,11 +54,11 @@ export class RecordSearchQueryHandler
}
if (
- event.type === 'entry_updated' &&
+ event.type === 'node_updated' &&
event.accountId === input.accountId &&
event.workspaceId === input.workspaceId &&
- event.entry.type === 'record' &&
- event.entry.attributes.databaseId === input.databaseId
+ event.node.type === 'record' &&
+ event.node.attributes.databaseId === input.databaseId
) {
const newResult = await this.handleQuery(input);
return {
@@ -68,11 +68,11 @@ export class RecordSearchQueryHandler
}
if (
- event.type === 'entry_deleted' &&
+ event.type === 'node_deleted' &&
event.accountId === input.accountId &&
event.workspaceId === input.workspaceId &&
- event.entry.type === 'record' &&
- event.entry.attributes.databaseId === input.databaseId
+ event.node.type === 'record' &&
+ event.node.attributes.databaseId === input.databaseId
) {
const newResult = await this.handleQuery(input);
return {
@@ -88,20 +88,20 @@ export class RecordSearchQueryHandler
private async searchRecords(
input: RecordSearchQueryInput
- ): Promise<SelectEntry[]> {
+ ): Promise<SelectNode[]> {
const workspace = this.getWorkspace(input.accountId, input.workspaceId);
const exclude = input.exclude ?? [];
- const query = sql<SelectEntry>`
- SELECT e.*
- FROM entries e
- JOIN entry_names en ON e.id = en.id
- WHERE e.type = 'record'
- AND e.parent_id = ${input.databaseId}
+ const query = sql<SelectNode>`
+ SELECT n.*
+ FROM nodes n
+ JOIN node_names nn ON n.id = nn.id
+ WHERE n.type = 'record'
+ AND n.parent_id = ${input.databaseId}
AND en.name MATCH ${input.searchQuery + '*'}
${
exclude.length > 0
- ? sql`AND e.id NOT IN (${sql.join(
+ ? sql`AND n.id NOT IN (${sql.join(
exclude.map((id) => sql`${id}`),
sql`, `
)})`
@@ -115,20 +115,16 @@ export class RecordSearchQueryHandler
private async fetchRecords(
input: RecordSearchQueryInput
- ): Promise<SelectEntry[]> {
+ ): Promise<SelectNode[]> {
const workspace = this.getWorkspace(input.accountId, input.workspaceId);
const exclude = input.exclude ?? [];
return workspace.database
- .selectFrom('entries')
+ .selectFrom('nodes')
.where('type', '=', 'record')
.where('parent_id', '=', input.databaseId)
.where('id', 'not in', exclude)
.selectAll()
.execute();
}
-
- private buildRecordEntries = (rows: SelectEntry[]): RecordEntry[] => {
- return rows.map((row) => mapEntry(row) as RecordEntry);
- };
}
diff --git a/apps/desktop/src/main/queries/spaces/space-list.ts b/apps/desktop/src/main/queries/spaces/space-list.ts
index d1e5352f..5829a5cb 100644
--- a/apps/desktop/src/main/queries/spaces/space-list.ts
+++ b/apps/desktop/src/main/queries/spaces/space-list.ts
@@ -1,25 +1,26 @@
-import { SpaceEntry } from '@colanode/core';
-
import { WorkspaceQueryHandlerBase } from '@/main/queries/workspace-query-handler-base';
import { ChangeCheckResult, QueryHandler } from '@/main/lib/types';
-import { mapEntry } from '@/main/lib/mappers';
+import { mapNode } from '@/main/lib/mappers';
import { SpaceListQueryInput } from '@/shared/queries/spaces/space-list';
import { Event } from '@/shared/types/events';
-import { SelectEntry } from '@/main/databases/workspace';
+import { SelectNode } from '@/main/databases/workspace';
+import { LocalSpaceNode } from '@/shared/types/nodes';
export class SpaceListQueryHandler
extends WorkspaceQueryHandlerBase
implements QueryHandler<SpaceListQueryInput>
{
- public async handleQuery(input: SpaceListQueryInput): Promise<SpaceEntry[]> {
+ public async handleQuery(
+ input: SpaceListQueryInput
+ ): Promise<LocalSpaceNode[]> {
const rows = await this.fetchChildren(input);
- return rows.map(mapEntry) as SpaceEntry[];
+ return rows.map(mapNode) as LocalSpaceNode[];
}
public async checkForChanges(
event: Event,
input: SpaceListQueryInput,
- output: SpaceEntry[]
+ output: LocalSpaceNode[]
): Promise<ChangeCheckResult<SpaceListQueryInput>> {
if (
event.type === 'workspace_deleted' &&
@@ -33,12 +34,12 @@ export class SpaceListQueryHandler
}
if (
- event.type === 'entry_created' &&
+ event.type === 'node_created' &&
event.accountId === input.accountId &&
event.workspaceId === input.workspaceId &&
- event.entry.type === 'space'
+ event.node.type === 'space'
) {
- const newChildren = [...output, event.entry];
+ const newChildren = [...output, event.node];
return {
hasChanges: true,
result: newChildren,
@@ -46,15 +47,15 @@ export class SpaceListQueryHandler
}
if (
- event.type === 'entry_updated' &&
+ event.type === 'node_updated' &&
event.accountId === input.accountId &&
event.workspaceId === input.workspaceId &&
- event.entry.type === 'space'
+ event.node.type === 'space'
) {
- const entry = output.find((entry) => entry.id === event.entry.id);
- if (entry) {
- const newChildren = output.map((entry) =>
- entry.id === event.entry.id ? (event.entry as SpaceEntry) : entry
+ const node = output.find((n) => n.id === event.node.id);
+ if (node) {
+ const newChildren = output.map((n) =>
+ n.id === event.node.id ? (event.node as LocalSpaceNode) : n
);
return {
@@ -65,16 +66,14 @@ export class SpaceListQueryHandler
}
if (
- event.type === 'entry_deleted' &&
+ event.type === 'node_deleted' &&
event.accountId === input.accountId &&
event.workspaceId === input.workspaceId &&
- event.entry.type === 'space'
+ event.node.type === 'space'
) {
- const entry = output.find((entry) => entry.id === event.entry.id);
- if (entry) {
- const newChildren = output.filter(
- (entry) => entry.id !== event.entry.id
- );
+ const node = output.find((n) => n.id === event.node.id);
+ if (node) {
+ const newChildren = output.filter((n) => n.id !== event.node.id);
return {
hasChanges: true,
result: newChildren,
@@ -89,13 +88,12 @@ export class SpaceListQueryHandler
private async fetchChildren(
input: SpaceListQueryInput
- ): Promise<SelectEntry[]> {
+ ): Promise<SelectNode[]> {
const workspace = this.getWorkspace(input.accountId, input.workspaceId);
const rows = await workspace.database
- .selectFrom('entries')
+ .selectFrom('nodes')
.selectAll()
- .where('parent_id', 'is', null)
.where('type', '=', 'space')
.execute();
diff --git a/apps/desktop/src/main/services/workspaces/collaboration-service.ts b/apps/desktop/src/main/services/workspaces/collaboration-service.ts
index 2d0030d1..3748d1ac 100644
--- a/apps/desktop/src/main/services/workspaces/collaboration-service.ts
+++ b/apps/desktop/src/main/services/workspaces/collaboration-service.ts
@@ -13,83 +13,63 @@ export class CollaborationService {
public async syncServerCollaboration(collaboration: SyncCollaborationData) {
this.debug(
- `Applying server collaboration: ${collaboration.entryId} for workspace ${this.workspace.id}`
+ `Applying server collaboration: ${collaboration.nodeId} for workspace ${this.workspace.id}`
);
await this.workspace.database
.insertInto('collaborations')
.values({
- entry_id: collaboration.entryId,
+ node_id: collaboration.nodeId,
role: collaboration.role,
created_at: collaboration.createdAt,
updated_at: collaboration.updatedAt,
deleted_at: collaboration.deletedAt,
- version: BigInt(collaboration.version),
+ revision: BigInt(collaboration.revision),
})
.onConflict((oc) =>
oc
- .columns(['entry_id'])
+ .columns(['node_id'])
.doUpdateSet({
role: collaboration.role,
- version: BigInt(collaboration.version),
+ revision: BigInt(collaboration.revision),
updated_at: collaboration.updatedAt,
deleted_at: collaboration.deletedAt,
})
- .where('version', '<', BigInt(collaboration.version))
+ .where('revision', '<', BigInt(collaboration.revision))
)
.execute();
if (collaboration.deletedAt) {
await this.workspace.database
- .deleteFrom('entries')
- .where('root_id', '=', collaboration.entryId)
+ .deleteFrom('nodes')
+ .where('root_id', '=', collaboration.nodeId)
.execute();
await this.workspace.database
- .deleteFrom('entry_transactions')
- .where('root_id', '=', collaboration.entryId)
- .execute();
-
- await this.workspace.database
- .deleteFrom('entry_interactions')
- .where('root_id', '=', collaboration.entryId)
- .execute();
-
- await this.workspace.database
- .deleteFrom('messages')
- .where('root_id', '=', collaboration.entryId)
- .execute();
-
- await this.workspace.database
- .deleteFrom('message_reactions')
- .where('root_id', '=', collaboration.entryId)
- .execute();
-
- await this.workspace.database
- .deleteFrom('message_interactions')
- .where('root_id', '=', collaboration.entryId)
+ .deleteFrom('node_interactions')
+ .where('root_id', '=', collaboration.nodeId)
.execute();
await this.workspace.database
.deleteFrom('files')
- .where('root_id', '=', collaboration.entryId)
+ .where('root_id', '=', collaboration.nodeId)
.execute();
await this.workspace.database
- .deleteFrom('file_interactions')
- .where('root_id', '=', collaboration.entryId)
+ .deleteFrom('node_interactions')
+ .where('root_id', '=', collaboration.nodeId)
.execute();
eventBus.publish({
type: 'collaboration_deleted',
accountId: this.workspace.accountId,
workspaceId: this.workspace.id,
- entryId: collaboration.entryId,
+ nodeId: collaboration.nodeId,
});
} else {
eventBus.publish({
type: 'collaboration_created',
- entryId: collaboration.entryId,
+ nodeId: collaboration.nodeId,
accountId: this.workspace.accountId,
workspaceId: this.workspace.id,
});
diff --git a/apps/desktop/src/main/services/workspaces/entry-service.ts b/apps/desktop/src/main/services/workspaces/entry-service.ts
deleted file mode 100644
index fc33c5b4..00000000
--- a/apps/desktop/src/main/services/workspaces/entry-service.ts
+++ /dev/null
@@ -1,1145 +0,0 @@
-import {
- generateId,
- IdType,
- LocalCreateTransaction,
- LocalDeleteTransaction,
- LocalUpdateTransaction,
- EntryAttributes,
- SyncCreateEntryTransactionData,
- SyncDeleteEntryTransactionData,
- SyncEntryInteractionData,
- SyncEntryTransactionData,
- SyncUpdateEntryTransactionData,
- extractEntryText,
- canDeleteEntry,
- canUpdateEntry,
- entryAttributesSchema,
- Entry,
- canCreateEntry,
- TransactionOperation,
- createDebugger,
-} from '@colanode/core';
-import { decodeState, YDoc } from '@colanode/crdt';
-
-import { SelectEntryTransaction } from '@/main/databases/workspace';
-import { fetchEntry } from '@/main/lib/utils';
-import {
- mapEntry,
- mapEntryInteraction,
- mapEntryTransaction,
-} from '@/main/lib/mappers';
-import { eventBus } from '@/shared/lib/event-bus';
-import { WorkspaceService } from '@/main/services/workspaces/workspace-service';
-
-const UPDATE_RETRIES_LIMIT = 20;
-
-export type CreateEntryInput = {
- id: string;
- attributes: EntryAttributes;
- parentId: string | null;
-};
-
-export type UpdateEntryResult =
- | 'success'
- | 'not_found'
- | 'unauthorized'
- | 'failed'
- | 'invalid_attributes';
-
-export class EntryService {
- private readonly debug = createDebugger('desktop:service:entry');
- private readonly workspace: WorkspaceService;
-
- constructor(workspaceService: WorkspaceService) {
- this.workspace = workspaceService;
- }
-
- public async createEntry(input: CreateEntryInput) {
- this.debug(`Creating ${Array.isArray(input) ? 'entries' : 'entry'}`);
-
- let root: Entry | null = null;
-
- if (input.parentId) {
- const parent = await fetchEntry(this.workspace.database, input.parentId);
-
- if (parent) {
- if (parent.id === parent.root_id) {
- root = mapEntry(parent);
- } else {
- const rootRow = await fetchEntry(
- this.workspace.database,
- parent.root_id
- );
- if (rootRow) {
- root = mapEntry(rootRow);
- }
- }
- }
- }
-
- if (
- !canCreateEntry(
- {
- user: {
- userId: this.workspace.userId,
- role: this.workspace.role,
- },
- root: root,
- },
- input.attributes
- )
- ) {
- throw new Error('Insufficient permissions');
- }
-
- const ydoc = new YDoc();
- const update = ydoc.updateAttributes(
- entryAttributesSchema,
- input.attributes
- );
-
- if (!update) {
- return;
- }
-
- const createdAt = new Date().toISOString();
- const transactionId = generateId(IdType.Transaction);
- const text = extractEntryText(input.id, input.attributes);
-
- const { createdEntry, createdMutation } = await this.workspace.database
- .transaction()
- .execute(async (trx) => {
- const createdEntry = await trx
- .insertInto('entries')
- .returningAll()
- .values({
- id: input.id,
- root_id: root?.id ?? input.id,
- attributes: JSON.stringify(input.attributes),
- created_at: createdAt,
- created_by: this.workspace.userId,
- transaction_id: transactionId,
- })
- .executeTakeFirst();
-
- if (!createdEntry) {
- throw new Error('Failed to create entry');
- }
-
- const createdTransaction = await trx
- .insertInto('entry_transactions')
- .returningAll()
- .values({
- id: transactionId,
- entry_id: input.id,
- root_id: root?.id ?? input.id,
- operation: TransactionOperation.Create,
- data: update,
- created_at: createdAt,
- created_by: this.workspace.userId,
- version: 0n,
- })
- .executeTakeFirst();
-
- if (!createdTransaction) {
- throw new Error('Failed to create transaction');
- }
-
- const createdMutation = await trx
- .insertInto('mutations')
- .returningAll()
- .values({
- id: generateId(IdType.Mutation),
- type: 'apply_create_transaction',
- data: JSON.stringify(mapEntryTransaction(createdTransaction)),
- created_at: createdAt,
- retries: 0,
- })
- .executeTakeFirst();
-
- if (!createdMutation) {
- throw new Error('Failed to create mutation');
- }
-
- if (text) {
- await trx
- .insertInto('texts')
- .values({ id: input.id, name: text.name, text: text.text })
- .execute();
- }
-
- return {
- createdEntry,
- createdMutation,
- };
- });
-
- if (!createdEntry) {
- throw new Error('Failed to create entry');
- }
-
- this.debug(
- `Created entry ${createdEntry.id} with type ${createdEntry.type}`
- );
-
- eventBus.publish({
- type: 'entry_created',
- accountId: this.workspace.accountId,
- workspaceId: this.workspace.id,
- entry: mapEntry(createdEntry),
- });
-
- if (!createdMutation) {
- throw new Error('Failed to create mutation');
- }
-
- this.workspace.mutations.triggerSync();
- }
-
- public async updateEntry<T extends EntryAttributes>(
- entryId: string,
- updater: (attributes: T) => T
- ): Promise<UpdateEntryResult> {
- for (let count = 0; count < UPDATE_RETRIES_LIMIT; count++) {
- const result = await this.tryUpdateEntry(entryId, updater);
- if (result) {
- return result;
- }
- }
-
- return 'failed';
- }
-
- private async tryUpdateEntry<T extends EntryAttributes>(
- entryId: string,
- updater: (attributes: T) => T
- ): Promise<UpdateEntryResult | null> {
- this.debug(`Updating entry ${entryId}`);
-
- const entryRow = await fetchEntry(this.workspace.database, entryId);
- if (!entryRow) {
- return 'not_found';
- }
-
- const root = await fetchEntry(this.workspace.database, entryRow.root_id);
- if (!root) {
- return 'not_found';
- }
-
- const entry = mapEntry(entryRow);
- const transactionId = generateId(IdType.Transaction);
- const updatedAt = new Date().toISOString();
- const updatedAttributes = updater(entry.attributes as T);
-
- const ydoc = new YDoc();
- const previousTransactions = await this.workspace.database
- .selectFrom('entry_transactions')
- .where('entry_id', '=', entryId)
- .selectAll()
- .execute();
-
- for (const previousTransaction of previousTransactions) {
- if (previousTransaction.data === null) {
- return 'not_found';
- }
-
- ydoc.applyUpdate(previousTransaction.data);
- }
-
- const update = ydoc.updateAttributes(
- entryAttributesSchema,
- updatedAttributes
- );
-
- if (
- !canUpdateEntry(
- {
- user: {
- userId: this.workspace.userId,
- role: this.workspace.role,
- },
- root: mapEntry(root),
- entry: entry,
- },
- updatedAttributes
- )
- ) {
- return 'unauthorized';
- }
-
- if (!update) {
- return 'success';
- }
-
- const text = extractEntryText(entryId, updatedAttributes);
-
- const { updatedEntry, createdMutation } = await this.workspace.database
- .transaction()
- .execute(async (trx) => {
- const updatedEntry = await trx
- .updateTable('entries')
- .returningAll()
- .set({
- attributes: JSON.stringify(ydoc.getAttributes()),
- updated_at: updatedAt,
- updated_by: this.workspace.userId,
- transaction_id: transactionId,
- })
- .where('id', '=', entryId)
- .where('transaction_id', '=', entry.transactionId)
- .executeTakeFirst();
-
- if (!updatedEntry) {
- return { updatedEntry: undefined };
- }
-
- const createdTransaction = await trx
- .insertInto('entry_transactions')
- .returningAll()
- .values({
- id: transactionId,
- entry_id: entryId,
- root_id: entry.rootId,
- operation: TransactionOperation.Update,
- data: update,
- created_at: updatedAt,
- created_by: this.workspace.userId,
- version: 0n,
- })
- .executeTakeFirst();
-
- if (!createdTransaction) {
- throw new Error('Failed to create transaction');
- }
-
- const createdMutation = await trx
- .insertInto('mutations')
- .returningAll()
- .values({
- id: generateId(IdType.Mutation),
- type: 'apply_update_transaction',
- data: JSON.stringify(mapEntryTransaction(createdTransaction)),
- created_at: updatedAt,
- retries: 0,
- })
- .executeTakeFirst();
-
- if (!createdMutation) {
- throw new Error('Failed to create mutation');
- }
-
- if (text !== undefined) {
- await trx.deleteFrom('texts').where('id', '=', entryId).execute();
- }
-
- if (text) {
- await trx
- .insertInto('texts')
- .values({ id: entryId, name: text.name, text: text.text })
- .execute();
- }
-
- return {
- updatedEntry,
- createdMutation,
- };
- });
-
- if (updatedEntry) {
- this.debug(
- `Updated entry ${updatedEntry.id} with type ${updatedEntry.type}`
- );
-
- eventBus.publish({
- type: 'entry_updated',
- accountId: this.workspace.accountId,
- workspaceId: this.workspace.id,
- entry: mapEntry(updatedEntry),
- });
- } else {
- this.debug(`Failed to update entry ${entryId}`);
- }
-
- if (createdMutation) {
- this.workspace.mutations.triggerSync();
- }
-
- if (updatedEntry) {
- return 'success';
- }
-
- return null;
- }
-
- public async deleteEntry(entryId: string) {
- const entry = await fetchEntry(this.workspace.database, entryId);
- if (!entry) {
- throw new Error('Entry not found');
- }
-
- const root = await fetchEntry(this.workspace.database, entry.root_id);
- if (!root) {
- throw new Error('Root not found');
- }
-
- if (
- !canDeleteEntry({
- user: {
- userId: this.workspace.userId,
- role: this.workspace.role,
- },
- root: mapEntry(root),
- entry: mapEntry(entry),
- })
- ) {
- throw new Error('Insufficient permissions');
- }
-
- const { deletedEntry, createdMutation } = await this.workspace.database
- .transaction()
- .execute(async (trx) => {
- const deletedEntry = await trx
- .deleteFrom('entries')
- .returningAll()
- .where('id', '=', entryId)
- .executeTakeFirst();
-
- if (!deletedEntry) {
- return { deletedEntry: undefined };
- }
-
- await trx.deleteFrom('texts').where('id', '=', entryId).execute();
-
- const createdTransaction = await trx
- .insertInto('entry_transactions')
- .returningAll()
- .values({
- id: generateId(IdType.Transaction),
- entry_id: entryId,
- root_id: root.root_id,
- operation: TransactionOperation.Delete,
- data: null,
- created_at: new Date().toISOString(),
- created_by: this.workspace.userId,
- version: 0n,
- })
- .executeTakeFirst();
-
- if (!createdTransaction) {
- throw new Error('Failed to create transaction');
- }
-
- const createdMutation = await trx
- .insertInto('mutations')
- .returningAll()
- .values({
- id: generateId(IdType.Mutation),
- type: 'apply_delete_transaction',
- data: JSON.stringify(mapEntryTransaction(createdTransaction)),
- created_at: new Date().toISOString(),
- retries: 0,
- })
- .executeTakeFirst();
-
- return { deletedEntry, createdMutation };
- });
-
- if (deletedEntry) {
- this.debug(
- `Deleted entry ${deletedEntry.id} with type ${deletedEntry.type}`
- );
-
- eventBus.publish({
- type: 'entry_deleted',
- accountId: this.workspace.accountId,
- workspaceId: this.workspace.id,
- entry: mapEntry(deletedEntry),
- });
- } else {
- this.debug(`Failed to delete entry ${entryId}`);
- }
-
- if (createdMutation) {
- this.workspace.mutations.triggerSync();
- }
- }
-
- public async applyServerTransaction(transaction: SyncEntryTransactionData) {
- if (transaction.operation === TransactionOperation.Create) {
- await this.applyServerCreateTransaction(transaction);
- } else if (transaction.operation === TransactionOperation.Update) {
- await this.applyServerUpdateTransaction(transaction);
- } else if (transaction.operation === TransactionOperation.Delete) {
- await this.applyServerDeleteTransaction(transaction);
- }
- }
-
- private async applyServerCreateTransaction(
- transaction: SyncCreateEntryTransactionData
- ) {
- this.debug(
- `Applying server create transaction ${transaction.id} for entry ${transaction.entryId}`
- );
-
- const version = BigInt(transaction.version);
- const existingTransaction = await this.workspace.database
- .selectFrom('entry_transactions')
- .select(['id', 'version', 'server_created_at'])
- .where('id', '=', transaction.id)
- .executeTakeFirst();
-
- if (existingTransaction) {
- if (
- existingTransaction.version === version &&
- existingTransaction.server_created_at === transaction.serverCreatedAt
- ) {
- this.debug(
- `Server create transaction ${transaction.id} for entry ${transaction.entryId} is already synced`
- );
- return;
- }
-
- await this.workspace.database
- .updateTable('entry_transactions')
- .set({
- version,
- server_created_at: transaction.serverCreatedAt,
- })
- .where('id', '=', transaction.id)
- .execute();
-
- this.debug(
- `Server create transaction ${transaction.id} for entry ${transaction.entryId} has been synced`
- );
- return;
- }
-
- const ydoc = new YDoc();
- ydoc.applyUpdate(transaction.data);
- const attributes = ydoc.getAttributes<EntryAttributes>();
- const text = extractEntryText(transaction.entryId, attributes);
-
- const { createdEntry } = await this.workspace.database
- .transaction()
- .execute(async (trx) => {
- const createdEntry = await trx
- .insertInto('entries')
- .returningAll()
- .values({
- id: transaction.entryId,
- root_id: transaction.rootId,
- attributes: JSON.stringify(attributes),
- created_at: transaction.createdAt,
- created_by: transaction.createdBy,
- transaction_id: transaction.id,
- })
- .executeTakeFirst();
-
- await trx
- .insertInto('entry_transactions')
- .values({
- id: transaction.id,
- entry_id: transaction.entryId,
- root_id: transaction.rootId,
- operation: TransactionOperation.Create,
- data: decodeState(transaction.data),
- created_at: transaction.createdAt,
- created_by: transaction.createdBy,
- version,
- server_created_at: transaction.serverCreatedAt,
- })
- .execute();
-
- if (text) {
- await trx
- .insertInto('texts')
- .values({
- id: transaction.entryId,
- name: text.name,
- text: text.text,
- })
- .execute();
- }
-
- return { createdEntry };
- });
-
- if (!createdEntry) {
- this.debug(
- `Server create transaction ${transaction.id} for entry ${transaction.entryId} is incomplete`
- );
- return;
- }
-
- this.debug(
- `Created entry ${createdEntry.id} with type ${createdEntry.type} with transaction ${transaction.id}`
- );
-
- eventBus.publish({
- type: 'entry_created',
- accountId: this.workspace.accountId,
- workspaceId: this.workspace.id,
- entry: mapEntry(createdEntry),
- });
- }
-
- private async applyServerUpdateTransaction(
- transaction: SyncUpdateEntryTransactionData
- ) {
- for (let count = 0; count < UPDATE_RETRIES_LIMIT; count++) {
- const result = await this.tryApplyServerUpdateTransaction(transaction);
-
- if (result) {
- return;
- }
- }
- }
-
- private async tryApplyServerUpdateTransaction(
- transaction: SyncUpdateEntryTransactionData
- ): Promise<boolean> {
- const version = BigInt(transaction.version);
- const existingTransaction = await this.workspace.database
- .selectFrom('entry_transactions')
- .select(['id', 'version', 'server_created_at'])
- .where('id', '=', transaction.id)
- .executeTakeFirst();
-
- if (existingTransaction) {
- if (
- existingTransaction.version === version &&
- existingTransaction.server_created_at === transaction.serverCreatedAt
- ) {
- this.debug(
- `Server update transaction ${transaction.id} for entry ${transaction.entryId} is already synced`
- );
- return true;
- }
-
- await this.workspace.database
- .updateTable('entry_transactions')
- .set({
- version,
- server_created_at: transaction.serverCreatedAt,
- })
- .where('id', '=', transaction.id)
- .execute();
-
- this.debug(
- `Server update transaction ${transaction.id} for entry ${transaction.entryId} has been synced`
- );
- return true;
- }
-
- const entry = await this.workspace.database
- .selectFrom('entries')
- .selectAll()
- .where('id', '=', transaction.entryId)
- .executeTakeFirst();
-
- if (!entry) {
- return false;
- }
-
- const previousTransactions = await this.workspace.database
- .selectFrom('entry_transactions')
- .selectAll()
- .where('entry_id', '=', transaction.entryId)
- .orderBy('id', 'asc')
- .execute();
-
- const ydoc = new YDoc();
-
- for (const previousTransaction of previousTransactions) {
- if (previousTransaction.data) {
- ydoc.applyUpdate(previousTransaction.data);
- }
- }
-
- ydoc.applyUpdate(transaction.data);
- const attributes = ydoc.getAttributes<EntryAttributes>();
- const text = extractEntryText(transaction.entryId, attributes);
-
- const { updatedEntry } = await this.workspace.database
- .transaction()
- .execute(async (trx) => {
- const updatedEntry = await trx
- .updateTable('entries')
- .returningAll()
- .set({
- attributes: JSON.stringify(attributes),
- updated_at: transaction.createdAt,
- updated_by: transaction.createdBy,
- transaction_id: transaction.id,
- })
- .where('id', '=', transaction.entryId)
- .where('transaction_id', '=', entry.transaction_id)
- .executeTakeFirst();
-
- if (!updatedEntry) {
- return { updatedEntry: undefined };
- }
-
- await trx
- .insertInto('entry_transactions')
- .values({
- id: transaction.id,
- entry_id: transaction.entryId,
- root_id: transaction.rootId,
- operation: TransactionOperation.Update,
- data: decodeState(transaction.data),
- created_at: transaction.createdAt,
- created_by: transaction.createdBy,
- version,
- server_created_at: transaction.serverCreatedAt,
- })
- .execute();
-
- if (text !== undefined) {
- await trx
- .deleteFrom('texts')
- .where('id', '=', transaction.entryId)
- .execute();
- }
-
- if (text) {
- await trx
- .insertInto('texts')
- .values({
- id: transaction.entryId,
- name: text.name,
- text: text.text,
- })
- .execute();
- }
-
- return { updatedEntry };
- });
-
- if (!updatedEntry) {
- this.debug(
- `Server update transaction ${transaction.id} for entry ${transaction.entryId} is incomplete`
- );
- return false;
- }
-
- this.debug(
- `Updated entry ${updatedEntry.id} with type ${updatedEntry.type} with transaction ${transaction.id}`
- );
-
- eventBus.publish({
- type: 'entry_updated',
- accountId: this.workspace.accountId,
- workspaceId: this.workspace.id,
- entry: mapEntry(updatedEntry),
- });
-
- return true;
- }
-
- private async applyServerDeleteTransaction(
- transaction: SyncDeleteEntryTransactionData
- ) {
- this.debug(
- `Applying server delete transaction ${transaction.id} for entry ${transaction.entryId}`
- );
-
- const { deletedEntry } = await this.workspace.database
- .transaction()
- .execute(async (trx) => {
- const deletedEntry = await trx
- .deleteFrom('entries')
- .returningAll()
- .where('id', '=', transaction.entryId)
- .executeTakeFirst();
-
- await trx
- .deleteFrom('entry_transactions')
- .where('entry_id', '=', transaction.entryId)
- .execute();
-
- await trx
- .deleteFrom('entry_interactions')
- .where('entry_id', '=', transaction.entryId)
- .execute();
-
- await trx
- .deleteFrom('texts')
- .where('id', '=', transaction.entryId)
- .execute();
-
- return { deletedEntry };
- });
-
- this.debug(
- `Deleted entry ${transaction.entryId} with transaction ${transaction.id}`
- );
-
- if (!deletedEntry) {
- return;
- }
-
- eventBus.publish({
- type: 'entry_deleted',
- accountId: this.workspace.accountId,
- workspaceId: this.workspace.id,
- entry: mapEntry(deletedEntry),
- });
- }
-
- public async revertCreateTransaction(transaction: LocalCreateTransaction) {
- const entry = await this.workspace.database
- .selectFrom('entries')
- .selectAll()
- .where('id', '=', transaction.entryId)
- .executeTakeFirst();
-
- if (!entry) {
- return;
- }
-
- const transactionRow = await this.workspace.database
- .selectFrom('entry_transactions')
- .selectAll()
- .where('id', '=', transaction.id)
- .executeTakeFirst();
-
- if (!transactionRow) {
- return;
- }
-
- await this.workspace.database.transaction().execute(async (tx) => {
- await tx
- .deleteFrom('entries')
- .where('id', '=', transaction.entryId)
- .execute();
-
- await tx
- .deleteFrom('entry_transactions')
- .where('id', '=', transaction.id)
- .execute();
-
- await tx
- .deleteFrom('entry_interactions')
- .where('entry_id', '=', transaction.entryId)
- .execute();
-
- await tx
- .deleteFrom('texts')
- .where('id', '=', transaction.entryId)
- .execute();
- });
-
- eventBus.publish({
- type: 'entry_deleted',
- accountId: this.workspace.accountId,
- workspaceId: this.workspace.id,
- entry: mapEntry(entry),
- });
- }
-
- public async revertUpdateTransaction(transaction: LocalUpdateTransaction) {
- for (let count = 0; count < UPDATE_RETRIES_LIMIT; count++) {
- const result = await this.tryRevertUpdateTransaction(transaction);
-
- if (result) {
- return;
- }
- }
- }
-
- private async tryRevertUpdateTransaction(
- transaction: LocalUpdateTransaction
- ): Promise<boolean> {
- const entry = await this.workspace.database
- .selectFrom('entries')
- .selectAll()
- .where('id', '=', transaction.entryId)
- .executeTakeFirst();
-
- if (!entry) {
- // Make sure we don't have any data left behind
- await this.workspace.database
- .deleteFrom('entry_transactions')
- .where('id', '=', transaction.id)
- .execute();
-
- await this.workspace.database
- .deleteFrom('entry_interactions')
- .where('entry_id', '=', transaction.entryId)
- .execute();
-
- await this.workspace.database
- .deleteFrom('texts')
- .where('id', '=', transaction.entryId)
- .execute();
-
- return true;
- }
-
- const transactionRow = await this.workspace.database
- .selectFrom('entry_transactions')
- .selectAll()
- .where('id', '=', transaction.id)
- .executeTakeFirst();
-
- if (!transactionRow) {
- return true;
- }
-
- const previousTransactions = await this.workspace.database
- .selectFrom('entry_transactions')
- .selectAll()
- .where('entry_id', '=', transaction.entryId)
- .orderBy('id', 'asc')
- .execute();
-
- const ydoc = new YDoc();
- let lastTransaction: SelectEntryTransaction | undefined;
- for (const previousTransaction of previousTransactions) {
- if (previousTransaction.id === transaction.id) {
- continue;
- }
-
- if (previousTransaction.data) {
- ydoc.applyUpdate(previousTransaction.data);
- }
-
- lastTransaction = previousTransaction;
- }
-
- if (!lastTransaction) {
- return true;
- }
-
- const attributes = ydoc.getAttributes<EntryAttributes>();
- const text = extractEntryText(transaction.entryId, attributes);
-
- const updatedEntry = await this.workspace.database
- .transaction()
- .execute(async (trx) => {
- const updatedEntry = await trx
- .updateTable('entries')
- .returningAll()
- .set({
- attributes: JSON.stringify(ydoc.getAttributes()),
- updated_at: lastTransaction.created_at,
- updated_by: lastTransaction.created_by,
- transaction_id: lastTransaction.id,
- })
- .where('id', '=', transaction.entryId)
- .where('transaction_id', '=', entry.transaction_id)
- .executeTakeFirst();
-
- if (!updatedEntry) {
- return undefined;
- }
-
- if (text !== undefined) {
- await trx
- .deleteFrom('texts')
- .where('id', '=', transaction.entryId)
- .execute();
- }
-
- if (text) {
- await trx
- .insertInto('texts')
- .values({
- id: transaction.entryId,
- name: text.name,
- text: text.text,
- })
- .execute();
- }
-
- await trx
- .deleteFrom('entry_transactions')
- .where('id', '=', transaction.id)
- .execute();
- });
-
- if (updatedEntry) {
- eventBus.publish({
- type: 'entry_updated',
- accountId: this.workspace.accountId,
- workspaceId: this.workspace.id,
- entry: mapEntry(updatedEntry),
- });
-
- return true;
- }
-
- return false;
- }
-
- public async revertDeleteTransaction(transaction: LocalDeleteTransaction) {
- const transactionRow = await this.workspace.database
- .selectFrom('entry_transactions')
- .selectAll()
- .where('id', '=', transaction.id)
- .executeTakeFirst();
-
- if (!transactionRow) {
- return;
- }
-
- const previousTransactions = await this.workspace.database
- .selectFrom('entry_transactions')
- .selectAll()
- .where('entry_id', '=', transaction.entryId)
- .orderBy('id', 'asc')
- .execute();
-
- const ydoc = new YDoc();
-
- let lastTransaction: SelectEntryTransaction | undefined;
- for (const previousTransaction of previousTransactions) {
- if (previousTransaction.id === transaction.id) {
- continue;
- }
-
- if (previousTransaction.data) {
- ydoc.applyUpdate(previousTransaction.data);
- }
-
- lastTransaction = previousTransaction;
- }
-
- if (!lastTransaction) {
- return true;
- }
-
- const attributes = ydoc.getAttributes<EntryAttributes>();
- const text = extractEntryText(transaction.entryId, attributes);
-
- const createdEntry = await this.workspace.database
- .transaction()
- .execute(async (trx) => {
- const createdEntry = await trx
- .insertInto('entries')
- .returningAll()
- .values({
- id: transaction.entryId,
- root_id: transaction.rootId,
- created_at: lastTransaction.created_at,
- created_by: lastTransaction.created_by,
- attributes: JSON.stringify(attributes),
- updated_at: lastTransaction.created_at,
- updated_by: lastTransaction.created_by,
- transaction_id: lastTransaction.id,
- })
- .onConflict((b) =>
- b
- .columns(['id'])
- .doUpdateSet({
- attributes: JSON.stringify(attributes),
- updated_at: lastTransaction.created_at,
- updated_by: lastTransaction.created_by,
- transaction_id: lastTransaction.id,
- })
- .where('transaction_id', '=', transaction.id)
- )
- .executeTakeFirst();
-
- if (!createdEntry) {
- return undefined;
- }
-
- await trx
- .deleteFrom('entry_transactions')
- .where('id', '=', transaction.id)
- .execute();
-
- if (text !== undefined) {
- await trx
- .deleteFrom('texts')
- .where('id', '=', transaction.entryId)
- .execute();
- }
-
- if (text) {
- await trx
- .insertInto('texts')
- .values({
- id: transaction.entryId,
- name: text.name,
- text: text.text,
- })
- .execute();
- }
- });
-
- if (createdEntry) {
- eventBus.publish({
- type: 'entry_created',
- accountId: this.workspace.accountId,
- workspaceId: this.workspace.id,
- entry: mapEntry(createdEntry),
- });
-
- return true;
- }
-
- return false;
- }
-
- public async syncServerEntryInteraction(
- entryInteraction: SyncEntryInteractionData
- ) {
- const existingEntryInteraction = await this.workspace.database
- .selectFrom('entry_interactions')
- .selectAll()
- .where('entry_id', '=', entryInteraction.entryId)
- .executeTakeFirst();
-
- const version = BigInt(entryInteraction.version);
- if (existingEntryInteraction) {
- if (existingEntryInteraction.version === version) {
- this.debug(
- `Server entry interaction for entry ${entryInteraction.entryId} is already synced`
- );
- return;
- }
- }
-
- const createdEntryInteraction = await this.workspace.database
- .insertInto('entry_interactions')
- .returningAll()
- .values({
- entry_id: entryInteraction.entryId,
- root_id: entryInteraction.rootId,
- collaborator_id: entryInteraction.collaboratorId,
- first_seen_at: entryInteraction.firstSeenAt,
- last_seen_at: entryInteraction.lastSeenAt,
- last_opened_at: entryInteraction.lastOpenedAt,
- first_opened_at: entryInteraction.firstOpenedAt,
- version,
- })
- .onConflict((b) =>
- b.columns(['entry_id', 'collaborator_id']).doUpdateSet({
- last_seen_at: entryInteraction.lastSeenAt,
- first_seen_at: entryInteraction.firstSeenAt,
- last_opened_at: entryInteraction.lastOpenedAt,
- first_opened_at: entryInteraction.firstOpenedAt,
- version,
- })
- )
- .executeTakeFirst();
-
- if (!createdEntryInteraction) {
- return;
- }
-
- eventBus.publish({
- type: 'entry_interaction_updated',
- accountId: this.workspace.accountId,
- workspaceId: this.workspace.id,
- entryInteraction: mapEntryInteraction(createdEntryInteraction),
- });
-
- this.debug(
- `Server entry interaction for entry ${entryInteraction.entryId} has been synced`
- );
- }
-}
diff --git a/apps/desktop/src/main/services/workspaces/file-service.ts b/apps/desktop/src/main/services/workspaces/file-service.ts
index 03e34888..8989fdb7 100644
--- a/apps/desktop/src/main/services/workspaces/file-service.ts
+++ b/apps/desktop/src/main/services/workspaces/file-service.ts
@@ -1,12 +1,13 @@
import {
CompleteUploadOutput,
CreateDownloadOutput,
+ CreateFileMutationData,
CreateUploadOutput,
FileStatus,
+ IdType,
SyncFileData,
- SyncFileInteractionData,
- SyncFileTombstoneData,
createDebugger,
+ generateId,
} from '@colanode/core';
import axios from 'axios';
import ms from 'ms';
@@ -15,15 +16,19 @@ import fs from 'fs';
import path from 'path';
import {
+ fetchUserStorageUsed,
+ getFileMetadata,
getWorkspaceFilesDirectoryPath,
getWorkspaceTempFilesDirectoryPath,
} from '@/main/lib/utils';
-import { mapFile, mapFileInteraction, mapFileState } from '@/main/lib/mappers';
+import { mapFile, mapNode } from '@/main/lib/mappers';
import { eventBus } from '@/shared/lib/event-bus';
import { DownloadStatus, UploadStatus } from '@/shared/types/files';
import { WorkspaceService } from '@/main/services/workspaces/workspace-service';
import { EventLoop } from '@/main/lib/event-loop';
-import { SelectFileState } from '@/main/databases/workspace';
+import { SelectFile, SelectNode } from '@/main/databases/workspace';
+import { MutationError, MutationErrorCode } from '@/shared/mutations';
+import { formatBytes } from '@/shared/lib/files';
const UPLOAD_RETRIES_LIMIT = 10;
const DOWNLOAD_RETRIES_LIMIT = 10;
@@ -88,6 +93,119 @@ export class FileService {
this.cleanupEventLoop.start();
}
+ public async createFile(
+ path: string,
+ id: string,
+ parentId: string,
+ root: SelectNode
+ ): Promise<void> {
+ const metadata = getFileMetadata(path);
+ if (!metadata) {
+ throw new MutationError(
+ MutationErrorCode.FileInvalid,
+ 'File is invalid or could not be read.'
+ );
+ }
+
+ if (metadata.size > this.workspace.maxFileSize) {
+ throw new MutationError(
+ MutationErrorCode.FileTooLarge,
+ 'The file you are trying to upload is too large. The maximum file size is ' +
+ formatBytes(this.workspace.maxFileSize)
+ );
+ }
+
+ const storageUsed = await fetchUserStorageUsed(
+ this.workspace.database,
+ this.workspace.userId
+ );
+
+ if (storageUsed + BigInt(metadata.size) > this.workspace.storageLimit) {
+ throw new MutationError(
+ MutationErrorCode.StorageLimitExceeded,
+ 'You have reached your storage limit. You have used ' +
+ formatBytes(storageUsed) +
+ ' and you are trying to upload a file of size ' +
+ formatBytes(metadata.size) +
+ '. Your storage limit is ' +
+ formatBytes(this.workspace.storageLimit)
+ );
+ }
+
+ this.copyFileToWorkspace(path, id, metadata.extension);
+
+ const mutationData: CreateFileMutationData = {
+ id,
+ type: metadata.type,
+ parentId: parentId,
+ rootId: root.id,
+ name: metadata.name,
+ originalName: metadata.name,
+ extension: metadata.extension,
+ mimeType: metadata.mimeType,
+ size: metadata.size,
+ createdAt: new Date().toISOString(),
+ };
+
+ const createdFile = await this.workspace.database
+ .transaction()
+ .execute(async (tx) => {
+ const createdFile = await tx
+ .insertInto('files')
+ .returningAll()
+ .values({
+ id,
+ type: metadata.type,
+ parent_id: parentId,
+ root_id: root.id,
+ name: metadata.name,
+ original_name: metadata.name,
+ mime_type: metadata.mimeType,
+ size: metadata.size,
+ extension: metadata.extension,
+ created_at: new Date().toISOString(),
+ created_by: this.workspace.userId,
+ status: FileStatus.Pending,
+ revision: 0n,
+ download_status: DownloadStatus.Completed,
+ download_progress: 100,
+ download_retries: 0,
+ upload_status: UploadStatus.Pending,
+ upload_progress: 0,
+ upload_retries: 0,
+ })
+ .executeTakeFirst();
+
+ if (!createdFile) {
+ throw new Error('Failed to create file.');
+ }
+
+ await tx
+ .insertInto('mutations')
+ .values({
+ id: generateId(IdType.Mutation),
+ type: 'create_file',
+ data: JSON.stringify(mutationData),
+ created_at: new Date().toISOString(),
+ retries: 0,
+ })
+ .execute();
+
+ return createdFile;
+ });
+
+ if (createdFile) {
+ this.workspace.mutations.triggerSync();
+
+ eventBus.publish({
+ type: 'file_created',
+ accountId: this.workspace.accountId,
+ workspaceId: this.workspace.id,
+ file: mapFile(createdFile),
+ });
+ }
+ }
+
public copyFileToWorkspace(
filePath: string,
fileId: string,
@@ -140,7 +258,7 @@ export class FileService {
this.debug(`Uploading files for workspace ${this.workspace.id}`);
const uploads = await this.workspace.database
- .selectFrom('file_states')
+ .selectFrom('files')
.selectAll()
.where('upload_status', '=', UploadStatus.Pending)
.execute();
@@ -154,92 +272,72 @@ export class FileService {
}
}
- private async uploadFile(state: SelectFileState): Promise<void> {
- if (state.upload_retries >= UPLOAD_RETRIES_LIMIT) {
+ private async uploadFile(file: SelectFile): Promise<void> {
+ if (file.upload_retries >= UPLOAD_RETRIES_LIMIT) {
this.debug(
- `File ${state.file_id} upload retries limit reached, marking as failed`
+ `File ${file.id} upload retries limit reached, marking as failed`
);
- const updatedFileState = await this.workspace.database
- .updateTable('file_states')
+ const updatedFile = await this.workspace.database
+ .updateTable('files')
.returningAll()
.set({
upload_status: UploadStatus.Failed,
updated_at: new Date().toISOString(),
})
- .where('file_id', '=', state.file_id)
+ .where('id', '=', file.id)
.executeTakeFirst();
- if (updatedFileState) {
+ if (updatedFile) {
eventBus.publish({
- type: 'file_state_updated',
+ type: 'file_updated',
accountId: this.workspace.accountId,
workspaceId: this.workspace.id,
- fileState: mapFileState(updatedFileState),
+ file: mapFile(updatedFile),
});
}
return;
}
- const file = await this.workspace.database
- .selectFrom('files')
- .selectAll()
- .where('id', '=', state.file_id)
- .executeTakeFirst();
-
- if (!file) {
- await this.workspace.database
- .deleteFrom('file_states')
- .where('file_id', '=', state.file_id)
- .execute();
-
- this.debug(
- `File ${state.file_id} not found, deleting state from database`
- );
- return;
- }
-
- if (file.version === BigInt(0)) {
+ if (file.revision === BigInt(0)) {
// file is not synced with the server, we need to wait for the sync to complete
return;
}
if (file.status === FileStatus.Ready) {
- const updatedFileState = await this.workspace.database
- .updateTable('file_states')
+ const updatedFile = await this.workspace.database
+ .updateTable('files')
.returningAll()
.set({
upload_status: UploadStatus.Completed,
upload_progress: 100,
updated_at: new Date().toISOString(),
})
- .where('file_id', '=', state.file_id)
+ .where('id', '=', file.id)
.executeTakeFirst();
- if (updatedFileState) {
+ if (updatedFile) {
eventBus.publish({
- type: 'file_state_updated',
+ type: 'file_updated',
accountId: this.workspace.accountId,
workspaceId: this.workspace.id,
- fileState: mapFileState(updatedFileState),
+ file: mapFile(updatedFile),
});
}
return;
}
- const filePath = this.buildFilePath(state.file_id, file.extension);
+ const filePath = this.buildFilePath(file.id, file.extension);
if (!fs.existsSync(filePath)) {
await this.workspace.database
- .deleteFrom('file_states')
- .where('file_id', '=', file.id)
+ .deleteFrom('files')
+ .where('id', '=', file.id)
.execute();
- this.debug(
- `File ${state.file_id} not found, deleting state from database`
- );
+ this.debug(`File ${file.id} not found, deleting from database`);
return;
}
@@ -270,25 +368,25 @@ export class FileService {
lastProgress = progress;
- const updatedFileState = await this.workspace.database
- .updateTable('file_states')
+ const updatedFile = await this.workspace.database
+ .updateTable('files')
.returningAll()
.set({
upload_progress: progress,
updated_at: new Date().toISOString(),
})
- .where('file_id', '=', file.id)
+ .where('id', '=', file.id)
.executeTakeFirst();
- if (!updatedFileState) {
+ if (!updatedFile) {
return;
}
eventBus.publish({
- type: 'file_state_updated',
+ type: 'file_updated',
accountId: this.workspace.accountId,
workspaceId: this.workspace.id,
- fileState: mapFileState(updatedFileState),
+ file: mapFile(updatedFile),
});
},
});
@@ -298,41 +396,41 @@ export class FileService {
{}
);
- const finalFileState = await this.workspace.database
- .updateTable('file_states')
+ const finalFile = await this.workspace.database
+ .updateTable('files')
.returningAll()
.set({
upload_status: UploadStatus.Completed,
upload_progress: 100,
updated_at: new Date().toISOString(),
})
- .where('file_id', '=', file.id)
+ .where('id', '=', file.id)
.executeTakeFirst();
- if (finalFileState) {
+ if (finalFile) {
eventBus.publish({
- type: 'file_state_updated',
+ type: 'file_updated',
accountId: this.workspace.accountId,
workspaceId: this.workspace.id,
- fileState: mapFileState(finalFileState),
+ file: mapFile(finalFile),
});
}
this.debug(`File ${file.id} uploaded successfully`);
} catch {
- const updatedFileState = await this.workspace.database
- .updateTable('file_states')
+ const updatedFile = await this.workspace.database
+ .updateTable('files')
.returningAll()
.set((eb) => ({ upload_retries: eb('upload_retries', '+', 1) }))
- .where('file_id', '=', file.id)
+ .where('id', '=', file.id)
.executeTakeFirst();
- if (updatedFileState) {
+ if (updatedFile) {
eventBus.publish({
- type: 'file_state_updated',
+ type: 'file_updated',
accountId: this.workspace.accountId,
workspaceId: this.workspace.id,
- fileState: mapFileState(updatedFileState),
+ file: mapFile(updatedFile),
});
}
}
@@ -346,7 +444,7 @@ export class FileService {
this.debug(`Downloading files for workspace ${this.workspace.id}`);
const downloads = await this.workspace.database
- .selectFrom('file_states')
+ .selectFrom('files')
.selectAll()
.where('download_status', '=', DownloadStatus.Pending)
.execute();
@@ -360,71 +458,41 @@ export class FileService {
}
}
- private async downloadFile(state: SelectFileState): Promise<void> {
- if (state.download_retries >= DOWNLOAD_RETRIES_LIMIT) {
+ private async downloadFile(file: SelectFile): Promise<void> {
+ if (file.download_retries >= DOWNLOAD_RETRIES_LIMIT) {
this.debug(
- `File ${state.file_id} download retries limit reached, marking as failed`
+ `File ${file.id} download retries limit reached, marking as failed`
);
await this.workspace.database
- .updateTable('file_states')
+ .updateTable('files')
.set({
download_status: DownloadStatus.Failed,
updated_at: new Date().toISOString(),
})
- .where('file_id', '=', state.file_id)
+ .where('id', '=', file.id)
.execute();
}
- const file = await this.workspace.database
- .selectFrom('files')
- .selectAll()
- .where('id', '=', state.file_id)
- .executeTakeFirst();
-
- if (!file) {
- this.debug(
- `File ${state.file_id} not found, deleting state from database`
- );
-
- const deletedFileState = await this.workspace.database
- .deleteFrom('file_states')
- .returningAll()
- .where('file_id', '=', state.file_id)
- .executeTakeFirst();
-
- if (deletedFileState) {
- eventBus.publish({
- type: 'file_state_deleted',
- accountId: this.workspace.accountId,
- workspaceId: this.workspace.id,
- fileState: mapFileState(deletedFileState),
- });
- }
-
- return;
- }
-
- const filePath = this.buildFilePath(state.file_id, file.extension);
-
+ const filePath = this.buildFilePath(file.id, file.extension);
if (fs.existsSync(filePath)) {
- const updatedFileState = await this.workspace.database
- .updateTable('file_states')
+ const updatedFile = await this.workspace.database
+ .updateTable('files')
.returningAll()
.set({
download_status: DownloadStatus.Completed,
download_progress: 100,
updated_at: new Date().toISOString(),
})
- .where('file_id', '=', file.id)
+ .where('id', '=', file.id)
.executeTakeFirst();
- if (updatedFileState) {
+ if (updatedFile) {
eventBus.publish({
- type: 'file_state_updated',
+ type: 'file_updated',
accountId: this.workspace.accountId,
workspaceId: this.workspace.id,
- fileState: mapFileState(updatedFileState),
+ file: mapFile(updatedFile),
});
}
@@ -456,22 +524,22 @@ export class FileService {
lastProgress = progress;
- const updatedFileState = await this.workspace.database
- .updateTable('file_states')
+ const updatedFile = await this.workspace.database
+ .updateTable('files')
.returningAll()
.set({
download_progress: progress,
updated_at: new Date().toISOString(),
})
- .where('file_id', '=', file.id)
+ .where('id', '=', file.id)
.executeTakeFirst();
- if (updatedFileState) {
+ if (updatedFile) {
eventBus.publish({
- type: 'file_state_updated',
+ type: 'file_updated',
accountId: this.workspace.accountId,
workspaceId: this.workspace.id,
- fileState: mapFileState(updatedFileState),
+ file: mapFile(updatedFile),
});
}
},
@@ -480,39 +548,39 @@ export class FileService {
response.data.pipe(fileStream);
});
- const updatedFileState = await this.workspace.database
- .updateTable('file_states')
+ const updatedFile = await this.workspace.database
+ .updateTable('files')
.returningAll()
.set({
download_status: DownloadStatus.Completed,
download_progress: 100,
updated_at: new Date().toISOString(),
})
- .where('file_id', '=', file.id)
+ .where('id', '=', file.id)
.executeTakeFirst();
- if (updatedFileState) {
+ if (updatedFile) {
eventBus.publish({
- type: 'file_state_updated',
+ type: 'file_updated',
accountId: this.workspace.accountId,
workspaceId: this.workspace.id,
- fileState: mapFileState(updatedFileState),
+ file: mapFile(updatedFile),
});
}
} catch {
- const updatedFileState = await this.workspace.database
- .updateTable('file_states')
+ const updatedFile = await this.workspace.database
+ .updateTable('files')
.returningAll()
.set((eb) => ({ download_retries: eb('download_retries', '+', 1) }))
- .where('file_id', '=', file.id)
+ .where('id', '=', file.id)
.executeTakeFirst();
- if (updatedFileState) {
+ if (updatedFile) {
eventBus.publish({
- type: 'file_state_updated',
+ type: 'file_updated',
accountId: this.workspace.accountId,
workspaceId: this.workspace.id,
- fileState: mapFileState(updatedFileState),
+ file: mapFile(updatedFile),
});
}
}
@@ -521,9 +589,9 @@ export class FileService {
public async cleanDeletedFiles(): Promise<void> {
this.debug(`Checking deleted files for workspace ${this.workspace.id}`);
- const files = fs.readdirSync(this.filesDir);
- while (files.length > 0) {
- const batch = files.splice(0, 100);
+ const fsFiles = fs.readdirSync(this.filesDir);
+ while (fsFiles.length > 0) {
+ const batch = fsFiles.splice(0, 100);
const fileIdMap: Record<string, string> = {};
for (const file of batch) {
@@ -532,15 +600,15 @@ export class FileService {
}
const fileIds = Object.keys(fileIdMap);
- const fileStates = await this.workspace.database
- .selectFrom('file_states')
- .select(['file_id'])
- .where('file_id', 'in', fileIds)
+ const files = await this.workspace.database
+ .selectFrom('files')
+ .select(['id'])
+ .where('id', 'in', fileIds)
.execute();
for (const fileId of fileIds) {
- const fileState = fileStates.find((f) => f.file_id === fileId);
- if (fileState) {
+ const file = files.find((f) => f.id === fileId);
+ if (!file) {
continue;
}
@@ -582,9 +650,9 @@ export class FileService {
.where('id', '=', file.id)
.executeTakeFirst();
- const version = BigInt(file.version);
+ const revision = BigInt(file.revision);
if (existingFile) {
- if (existingFile.version === version) {
+ if (existingFile.revision === revision) {
this.debug(`Server file ${file.id} is already synced`);
return;
}
@@ -602,9 +670,9 @@ export class FileService {
root_id: file.rootId,
status: file.status,
type: file.type,
- updated_at: file.updatedAt,
- updated_by: file.updatedBy,
- version,
+ updated_at: file.updatedAt ?? undefined,
+ updated_by: file.updatedBy ?? undefined,
+ revision,
})
.where('id', '=', file.id)
.executeTakeFirst();
@@ -632,10 +700,9 @@ export class FileService {
.returningAll()
.values({
id: file.id,
- version,
+ revision,
type: file.type,
parent_id: file.parentId,
- entry_id: file.entryId,
root_id: file.rootId,
name: file.name,
original_name: file.originalName,
@@ -647,6 +714,12 @@ export class FileService {
updated_at: file.updatedAt,
updated_by: file.updatedBy,
status: file.status,
+ download_progress: 0,
+ download_retries: 0,
+ upload_progress: 0,
+ upload_retries: 0,
+ download_status: DownloadStatus.None,
+ upload_status: UploadStatus.None,
})
.executeTakeFirst();
@@ -664,124 +737,40 @@ export class FileService {
this.debug(`Server file ${file.id} has been synced`);
}
- public async syncServerFileTombstone(fileTombstone: SyncFileTombstoneData) {
+ public async revertFileCreation(fileId: string) {
const deletedFile = await this.workspace.database
.deleteFrom('files')
.returningAll()
- .where('id', '=', fileTombstone.id)
- .executeTakeFirst();
-
- await this.workspace.database
- .deleteFrom('file_interactions')
- .where('file_id', '=', fileTombstone.id)
- .execute();
-
- await this.workspace.database
- .deleteFrom('file_states')
- .where('file_id', '=', fileTombstone.id)
- .execute();
-
- if (deletedFile) {
- // if the file exists in the workspace, we need to delete it
- const filePath = this.buildFilePath(
- fileTombstone.id,
- deletedFile.extension
- );
-
- if (fs.existsSync(filePath)) {
- fs.rmSync(filePath, { force: true });
- }
-
- eventBus.publish({
- type: 'file_deleted',
- accountId: this.workspace.accountId,
- workspaceId: this.workspace.id,
- file: mapFile(deletedFile),
- });
- }
-
- this.debug(`Server file tombstone ${fileTombstone.id} has been synced`);
- }
-
- public async syncServerFileInteraction(
- fileInteraction: SyncFileInteractionData
- ) {
- const existingFileInteraction = await this.workspace.database
- .selectFrom('file_interactions')
- .selectAll()
- .where('file_id', '=', fileInteraction.fileId)
- .executeTakeFirst();
-
- const version = BigInt(fileInteraction.version);
- if (existingFileInteraction) {
- if (existingFileInteraction.version === version) {
- this.debug(
- `Server file interaction for file ${fileInteraction.fileId} is already synced`
- );
- return;
- }
- }
-
- const createdFileInteraction = await this.workspace.database
- .insertInto('file_interactions')
- .returningAll()
- .values({
- file_id: fileInteraction.fileId,
- root_id: fileInteraction.rootId,
- collaborator_id: fileInteraction.collaboratorId,
- first_seen_at: fileInteraction.firstSeenAt,
- last_seen_at: fileInteraction.lastSeenAt,
- last_opened_at: fileInteraction.lastOpenedAt,
- first_opened_at: fileInteraction.firstOpenedAt,
- version,
- })
- .onConflict((b) =>
- b.columns(['file_id', 'collaborator_id']).doUpdateSet({
- last_seen_at: fileInteraction.lastSeenAt,
- first_seen_at: fileInteraction.firstSeenAt,
- last_opened_at: fileInteraction.lastOpenedAt,
- first_opened_at: fileInteraction.firstOpenedAt,
- version,
- })
- )
+ .where('id', '=', fileId)
.executeTakeFirst();
- if (!createdFileInteraction) {
+ if (!deletedFile) {
return;
}
- eventBus.publish({
- type: 'file_interaction_updated',
- accountId: this.workspace.accountId,
- workspaceId: this.workspace.id,
- fileInteraction: mapFileInteraction(createdFileInteraction),
- });
-
- this.debug(
- `Server file interaction for file ${fileInteraction.fileId} has been synced`
- );
- }
-
- public async revertFileCreation(fileId: string) {
- const deletedFile = await this.workspace.database
- .deleteFrom('files')
+ const deletedNode = await this.workspace.database
+ .deleteFrom('nodes')
.returningAll()
- .where('id', '=', fileId)
+ .where('id', '=', deletedFile.parent_id)
.executeTakeFirst();
- if (!deletedFile) {
+ if (!deletedNode) {
return;
}
await this.workspace.database
- .deleteFrom('file_states')
- .returningAll()
- .where('file_id', '=', fileId)
- .executeTakeFirst();
+ .deleteFrom('node_states')
+ .where('id', '=', deletedNode.id)
+ .execute();
+
+ await this.workspace.database
+ .deleteFrom('node_interactions')
+ .where('node_id', '=', deletedNode.id)
+ .execute();
await this.workspace.database
- .deleteFrom('file_interactions')
- .where('file_id', '=', fileId)
+ .deleteFrom('node_reactions')
+ .where('node_id', '=', deletedNode.id)
.execute();
const filePath = path.join(
@@ -799,27 +788,12 @@ export class FileService {
workspaceId: this.workspace.id,
file: mapFile(deletedFile),
});
- }
-
- public async revertFileDeletion(fileId: string) {
- const deletedFile = await this.workspace.database
- .updateTable('files')
- .returningAll()
- .set({
- deleted_at: null,
- })
- .where('id', '=', fileId)
- .executeTakeFirst();
-
- if (!deletedFile) {
- return;
- }
eventBus.publish({
- type: 'file_created',
+ type: 'node_deleted',
accountId: this.workspace.accountId,
workspaceId: this.workspace.id,
- file: mapFile(deletedFile),
+ node: mapNode(deletedNode),
});
}
diff --git a/apps/desktop/src/main/services/workspaces/message-service.ts b/apps/desktop/src/main/services/workspaces/message-service.ts
deleted file mode 100644
index 73550a4b..00000000
--- a/apps/desktop/src/main/services/workspaces/message-service.ts
+++ /dev/null
@@ -1,436 +0,0 @@
-import {
- CreateMessageReactionMutationData,
- DeleteMessageReactionMutationData,
- extractMessageText,
- SyncMessageData,
- SyncMessageInteractionData,
- SyncMessageReactionData,
- SyncMessageTombstoneData,
- createDebugger,
-} from '@colanode/core';
-
-import {
- mapMessage,
- mapMessageInteraction,
- mapMessageReaction,
-} from '@/main/lib/mappers';
-import { eventBus } from '@/shared/lib/event-bus';
-import { WorkspaceService } from '@/main/services/workspaces/workspace-service';
-
-export class MessageService {
- private readonly debug = createDebugger('desktop:service:message');
- private readonly workspace: WorkspaceService;
-
- constructor(workspace: WorkspaceService) {
- this.workspace = workspace;
- }
-
- public async syncServerMessage(message: SyncMessageData) {
- const existingMessage = await this.workspace.database
- .selectFrom('messages')
- .selectAll()
- .where('id', '=', message.id)
- .executeTakeFirst();
-
- const version = BigInt(message.version);
- if (existingMessage) {
- if (existingMessage.version === version) {
- this.debug(`Server message ${message.id} is already synced`);
- return;
- }
-
- const updatedMessage = await this.workspace.database
- .updateTable('messages')
- .returningAll()
- .set({
- attributes: JSON.stringify(message.attributes),
- updated_at: message.updatedAt,
- updated_by: message.updatedBy,
- root_id: message.rootId,
- version,
- })
- .where('id', '=', message.id)
- .executeTakeFirst();
-
- if (!updatedMessage) {
- return;
- }
-
- await this.workspace.database
- .deleteFrom('texts')
- .where('id', '=', message.id)
- .execute();
-
- const text = extractMessageText(message.id, message.attributes);
- if (text) {
- await this.workspace.database
- .insertInto('texts')
- .values({
- id: message.id,
- name: null,
- text: text.text,
- })
- .execute();
- }
-
- eventBus.publish({
- type: 'message_updated',
- accountId: this.workspace.accountId,
- workspaceId: this.workspace.id,
- message: mapMessage(updatedMessage),
- });
-
- this.debug(`Server message ${message.id} has been synced`);
- return;
- }
-
- const createdMessage = await this.workspace.database
- .insertInto('messages')
- .returningAll()
- .values({
- id: message.id,
- version,
- parent_id: message.entryId,
- entry_id: message.entryId,
- root_id: message.rootId,
- attributes: JSON.stringify(message.attributes),
- created_at: message.createdAt,
- created_by: message.createdBy,
- updated_at: message.updatedAt,
- updated_by: message.updatedBy,
- })
- .executeTakeFirst();
-
- if (!createdMessage) {
- return;
- }
-
- const text = extractMessageText(message.id, message.attributes);
- if (text) {
- await this.workspace.database
- .insertInto('texts')
- .values({
- id: message.id,
- name: null,
- text: text.text,
- })
- .execute();
- }
-
- eventBus.publish({
- type: 'message_created',
- accountId: this.workspace.accountId,
- workspaceId: this.workspace.id,
- message: mapMessage(createdMessage),
- });
-
- this.debug(`Server message ${message.id} has been synced`);
- }
-
- public async syncServerMessageTombstone(
- messageTombstone: SyncMessageTombstoneData
- ) {
- const deletedMessage = await this.workspace.database
- .deleteFrom('messages')
- .returningAll()
- .where('id', '=', messageTombstone.id)
- .executeTakeFirst();
-
- await this.workspace.database
- .deleteFrom('message_reactions')
- .where('message_id', '=', messageTombstone.id)
- .execute();
-
- await this.workspace.database
- .deleteFrom('message_interactions')
- .where('message_id', '=', messageTombstone.id)
- .execute();
-
- await this.workspace.database
- .deleteFrom('texts')
- .where('id', '=', messageTombstone.id)
- .execute();
-
- if (deletedMessage) {
- eventBus.publish({
- type: 'message_deleted',
- accountId: this.workspace.accountId,
- workspaceId: this.workspace.id,
- message: mapMessage(deletedMessage),
- });
- }
-
- this.debug(
- `Server message tombstone ${messageTombstone.id} has been synced`
- );
- }
-
- public async syncServerMessageReaction(
- messageReaction: SyncMessageReactionData
- ) {
- if (messageReaction.deletedAt) {
- const deletedMessageReaction = await this.workspace.database
- .deleteFrom('message_reactions')
- .returningAll()
- .where('message_id', '=', messageReaction.messageId)
- .where('collaborator_id', '=', messageReaction.collaboratorId)
- .where('reaction', '=', messageReaction.reaction)
- .executeTakeFirst();
-
- if (deletedMessageReaction) {
- eventBus.publish({
- type: 'message_reaction_deleted',
- accountId: this.workspace.accountId,
- workspaceId: this.workspace.id,
- messageReaction: mapMessageReaction(deletedMessageReaction),
- });
- }
-
- this.debug(
- `Server message reaction for message ${messageReaction.messageId} has been synced`
- );
- return;
- }
-
- const existingMessageReaction = await this.workspace.database
- .selectFrom('message_reactions')
- .selectAll()
- .where('message_id', '=', messageReaction.messageId)
- .where('collaborator_id', '=', messageReaction.collaboratorId)
- .where('reaction', '=', messageReaction.reaction)
- .executeTakeFirst();
-
- const version = BigInt(messageReaction.version);
- if (existingMessageReaction) {
- if (existingMessageReaction.version === version) {
- this.debug(
- `Server message reaction for message ${messageReaction.messageId} is already synced`
- );
- return;
- }
-
- const updatedMessageReaction = await this.workspace.database
- .updateTable('message_reactions')
- .returningAll()
- .set({
- version,
- })
- .where('message_id', '=', messageReaction.messageId)
- .where('collaborator_id', '=', messageReaction.collaboratorId)
- .where('reaction', '=', messageReaction.reaction)
- .executeTakeFirst();
-
- if (!updatedMessageReaction) {
- return;
- }
-
- this.debug(
- `Server message reaction for message ${messageReaction.messageId} has been synced`
- );
- return;
- }
-
- const createdMessageReaction = await this.workspace.database
- .insertInto('message_reactions')
- .returningAll()
- .values({
- message_id: messageReaction.messageId,
- collaborator_id: messageReaction.collaboratorId,
- reaction: messageReaction.reaction,
- root_id: messageReaction.rootId,
- created_at: messageReaction.createdAt,
- version,
- })
- .onConflict((b) =>
- b.columns(['message_id', 'collaborator_id', 'reaction']).doUpdateSet({
- version,
- deleted_at: null,
- })
- )
- .executeTakeFirst();
-
- if (!createdMessageReaction) {
- return;
- }
-
- eventBus.publish({
- type: 'message_reaction_created',
- accountId: this.workspace.accountId,
- workspaceId: this.workspace.id,
- messageReaction: mapMessageReaction(createdMessageReaction),
- });
-
- this.debug(
- `Server message reaction for message ${messageReaction.messageId} has been synced`
- );
- }
-
- public async syncServerMessageInteraction(
- messageInteraction: SyncMessageInteractionData
- ) {
- const existingMessageInteraction = await this.workspace.database
- .selectFrom('message_interactions')
- .selectAll()
- .where('message_id', '=', messageInteraction.messageId)
- .executeTakeFirst();
-
- const version = BigInt(messageInteraction.version);
- if (existingMessageInteraction) {
- if (existingMessageInteraction.version === version) {
- this.debug(
- `Server message interaction for message ${messageInteraction.messageId} is already synced`
- );
- return;
- }
- }
-
- const createdMessageInteraction = await this.workspace.database
- .insertInto('message_interactions')
- .returningAll()
- .values({
- message_id: messageInteraction.messageId,
- collaborator_id: messageInteraction.collaboratorId,
- root_id: messageInteraction.rootId,
- first_seen_at: messageInteraction.firstSeenAt,
- last_seen_at: messageInteraction.lastSeenAt,
- first_opened_at: messageInteraction.firstOpenedAt,
- last_opened_at: messageInteraction.lastOpenedAt,
- version,
- })
- .onConflict((b) =>
- b.columns(['message_id', 'collaborator_id']).doUpdateSet({
- first_seen_at: messageInteraction.firstSeenAt,
- last_seen_at: messageInteraction.lastSeenAt,
- first_opened_at: messageInteraction.firstOpenedAt,
- last_opened_at: messageInteraction.lastOpenedAt,
- version,
- })
- )
- .executeTakeFirst();
-
- if (!createdMessageInteraction) {
- return;
- }
-
- eventBus.publish({
- type: 'message_interaction_updated',
- accountId: this.workspace.accountId,
- workspaceId: this.workspace.id,
- messageInteraction: mapMessageInteraction(createdMessageInteraction),
- });
-
- this.debug(
- `Server message interaction for message ${messageInteraction.messageId} has been synced`
- );
- }
-
- public async revertMessageCreation(messageId: string) {
- const deletedMessage = await this.workspace.database
- .deleteFrom('messages')
- .returningAll()
- .where('id', '=', messageId)
- .executeTakeFirst();
-
- if (!deletedMessage) {
- return;
- }
-
- await this.workspace.database
- .deleteFrom('message_reactions')
- .where('message_id', '=', messageId)
- .execute();
-
- await this.workspace.database
- .deleteFrom('message_interactions')
- .where('message_id', '=', messageId)
- .execute();
-
- eventBus.publish({
- type: 'message_deleted',
- accountId: this.workspace.accountId,
- workspaceId: this.workspace.id,
- message: mapMessage(deletedMessage),
- });
-
- const files = await this.workspace.database
- .selectFrom('files')
- .selectAll()
- .where('parent_id', '=', messageId)
- .execute();
-
- for (const file of files) {
- await this.workspace.files.revertFileCreation(file.id);
- }
- }
-
- public async revertMessageDeletion(messageId: string) {
- const deletedMessage = await this.workspace.database
- .updateTable('messages')
- .returningAll()
- .set({
- deleted_at: null,
- })
- .where('id', '=', messageId)
- .executeTakeFirst();
-
- if (!deletedMessage) {
- return;
- }
-
- eventBus.publish({
- type: 'message_created',
- accountId: this.workspace.accountId,
- workspaceId: this.workspace.id,
- message: mapMessage(deletedMessage),
- });
- }
-
- public async revertMessageReactionCreation(
- messageReaction: CreateMessageReactionMutationData
- ) {
- const deletedMessageReaction = await this.workspace.database
- .deleteFrom('message_reactions')
- .returningAll()
- .where('message_id', '=', messageReaction.messageId)
- .where('collaborator_id', '=', this.workspace.userId)
- .where('reaction', '=', messageReaction.reaction)
- .executeTakeFirst();
-
- if (!deletedMessageReaction) {
- return;
- }
-
- eventBus.publish({
- type: 'message_reaction_deleted',
- accountId: this.workspace.accountId,
- workspaceId: this.workspace.id,
- messageReaction: mapMessageReaction(deletedMessageReaction),
- });
- }
-
- public async revertMessageReactionDeletion(
- messageReaction: DeleteMessageReactionMutationData
- ) {
- const createdMessageReaction = await this.workspace.database
- .updateTable('message_reactions')
- .returningAll()
- .set({
- deleted_at: null,
- })
- .where('message_id', '=', messageReaction.messageId)
- .where('collaborator_id', '=', this.workspace.userId)
- .where('reaction', '=', messageReaction.reaction)
- .executeTakeFirst();
-
- if (!createdMessageReaction) {
- return;
- }
-
- eventBus.publish({
- type: 'message_reaction_created',
- accountId: this.workspace.accountId,
- workspaceId: this.workspace.id,
- messageReaction: mapMessageReaction(createdMessageReaction),
- });
- }
-}
diff --git a/apps/desktop/src/main/services/workspaces/mutation-service.ts b/apps/desktop/src/main/services/workspaces/mutation-service.ts
index 5c382b2f..fba3c728 100644
--- a/apps/desktop/src/main/services/workspaces/mutation-service.ts
+++ b/apps/desktop/src/main/services/workspaces/mutation-service.ts
@@ -145,24 +145,16 @@ export class MutationService {
if (mutation.type === 'create_file') {
await this.workspace.files.revertFileCreation(mutation.id);
- } else if (mutation.type === 'delete_file') {
- await this.workspace.files.revertFileDeletion(mutation.id);
- } else if (mutation.type === 'apply_create_transaction') {
- await this.workspace.entries.revertCreateTransaction(mutation.data);
- } else if (mutation.type === 'apply_update_transaction') {
- await this.workspace.entries.revertUpdateTransaction(mutation.data);
- } else if (mutation.type === 'apply_delete_transaction') {
- await this.workspace.entries.revertDeleteTransaction(mutation.data);
- } else if (mutation.type === 'create_message') {
- await this.workspace.messages.revertMessageCreation(mutation.data.id);
- } else if (mutation.type === 'delete_message') {
- await this.workspace.messages.revertMessageDeletion(mutation.data.id);
- } else if (mutation.type === 'create_message_reaction') {
- await this.workspace.messages.revertMessageReactionCreation(
+ } else if (mutation.type === 'apply_node_transaction') {
+ await this.workspace.nodes.revertNodeTransaction(mutation.data);
+ } else if (mutation.type === 'delete_node') {
+ await this.workspace.nodes.revertNodeDelete(mutation.data);
+ } else if (mutation.type === 'create_node_reaction') {
+ await this.workspace.nodeReactions.revertNodeReactionCreation(
mutation.data
);
- } else if (mutation.type === 'delete_message_reaction') {
- await this.workspace.messages.revertMessageReactionDeletion(
+ } else if (mutation.type === 'delete_node_reaction') {
+ await this.workspace.nodeReactions.revertNodeReactionDeletion(
mutation.data
);
}
@@ -212,7 +204,7 @@ export class MutationService {
continue;
}
- if (mutation.type === 'apply_delete_transaction') {
+ if (mutation.type === 'delete_node') {
for (let j = i - 1; j >= 0; j--) {
const previousMutation = mutations[j];
if (!previousMutation) {
@@ -220,84 +212,39 @@ export class MutationService {
}
if (
- previousMutation.type === 'apply_create_transaction' &&
+ previousMutation.type === 'apply_node_transaction' &&
previousMutation.data.id === mutation.data.id
) {
deletedMutationIds.add(mutation.id);
deletedMutationIds.add(previousMutation.id);
} else if (
- previousMutation.type === 'apply_update_transaction' &&
- previousMutation.data.id === mutation.data.id
+ previousMutation.type === 'mark_node_seen' &&
+ previousMutation.data.nodeId === mutation.data.id
) {
deletedMutationIds.add(previousMutation.id);
} else if (
- previousMutation.type === 'mark_entry_opened' &&
- previousMutation.data.entryId === mutation.data.id
+ previousMutation.type === 'mark_node_opened' &&
+ previousMutation.data.nodeId === mutation.data.id
) {
deletedMutationIds.add(previousMutation.id);
} else if (
- previousMutation.type === 'mark_entry_seen' &&
- previousMutation.data.entryId === mutation.data.id
- ) {
- deletedMutationIds.add(previousMutation.id);
- }
- }
- } else if (mutation.type === 'delete_file') {
- for (let j = i - 1; j >= 0; j--) {
- const previousMutation = mutations[j];
- if (!previousMutation) {
- continue;
- }
-
- if (
- previousMutation.type === 'create_file' &&
- previousMutation.data.id === mutation.data.id
+ previousMutation.type === 'create_node_reaction' &&
+ previousMutation.data.nodeId === mutation.data.id
) {
- deletedMutationIds.add(mutation.id);
deletedMutationIds.add(previousMutation.id);
} else if (
- previousMutation.type === 'mark_file_seen' &&
- previousMutation.data.fileId === mutation.data.id
+ previousMutation.type === 'delete_node_reaction' &&
+ previousMutation.data.nodeId === mutation.data.id
) {
deletedMutationIds.add(previousMutation.id);
} else if (
- previousMutation.type === 'mark_file_opened' &&
- previousMutation.data.fileId === mutation.data.id
- ) {
- deletedMutationIds.add(previousMutation.id);
- }
- }
- } else if (mutation.type === 'delete_message') {
- for (let j = i - 1; j >= 0; j--) {
- const previousMutation = mutations[j];
- if (!previousMutation) {
- continue;
- }
-
- if (
- previousMutation.type === 'create_message' &&
+ previousMutation.type === 'create_file' &&
previousMutation.data.id === mutation.data.id
- ) {
- deletedMutationIds.add(mutation.id);
- deletedMutationIds.add(previousMutation.id);
- } else if (
- previousMutation.type === 'mark_message_seen' &&
- previousMutation.data.messageId === mutation.data.id
- ) {
- deletedMutationIds.add(previousMutation.id);
- } else if (
- previousMutation.type === 'create_message_reaction' &&
- previousMutation.data.messageId === mutation.data.id
- ) {
- deletedMutationIds.add(previousMutation.id);
- } else if (
- previousMutation.type === 'delete_message_reaction' &&
- previousMutation.data.messageId === mutation.data.id
) {
deletedMutationIds.add(previousMutation.id);
}
}
- } else if (mutation.type === 'delete_message_reaction') {
+ } else if (mutation.type === 'delete_node_reaction') {
for (let j = i - 1; j >= 0; j--) {
const previousMutation = mutations[j];
if (!previousMutation) {
@@ -305,63 +252,21 @@ export class MutationService {
}
if (
- previousMutation.type === 'create_message_reaction' &&
- previousMutation.data.messageId === mutation.data.messageId &&
+ previousMutation.type === 'create_node_reaction' &&
+ previousMutation.data.nodeId === mutation.data.nodeId &&
previousMutation.data.reaction === mutation.data.reaction
) {
deletedMutationIds.add(mutation.id);
deletedMutationIds.add(previousMutation.id);
} else if (
- previousMutation.type === 'delete_message_reaction' &&
- previousMutation.data.messageId === mutation.data.messageId &&
+ previousMutation.type === 'delete_node_reaction' &&
+ previousMutation.data.nodeId === mutation.data.nodeId &&
previousMutation.data.reaction === mutation.data.reaction
) {
deletedMutationIds.add(previousMutation.id);
}
}
- } else if (mutation.type === 'mark_entry_seen') {
- for (let j = i - 1; j >= 0; j--) {
- const previousMutation = mutations[j];
- if (!previousMutation) {
- continue;
- }
-
- if (
- previousMutation.type === 'mark_entry_seen' &&
- previousMutation.data.entryId === mutation.data.entryId
- ) {
- deletedMutationIds.add(previousMutation.id);
- }
- }
- } else if (mutation.type === 'mark_entry_opened') {
- for (let j = i - 1; j >= 0; j--) {
- const previousMutation = mutations[j];
- if (!previousMutation) {
- continue;
- }
-
- if (
- previousMutation.type === 'mark_entry_opened' &&
- previousMutation.data.entryId === mutation.data.entryId
- ) {
- deletedMutationIds.add(previousMutation.id);
- }
- }
- } else if (mutation.type === 'mark_file_seen') {
- for (let j = i - 1; j >= 0; j--) {
- const previousMutation = mutations[j];
- if (!previousMutation) {
- continue;
- }
-
- if (
- previousMutation.type === 'mark_file_seen' &&
- previousMutation.data.fileId === mutation.data.fileId
- ) {
- deletedMutationIds.add(previousMutation.id);
- }
- }
- } else if (mutation.type === 'mark_file_opened') {
+ } else if (mutation.type === 'mark_node_seen') {
for (let j = i - 1; j >= 0; j--) {
const previousMutation = mutations[j];
if (!previousMutation) {
@@ -369,13 +274,13 @@ export class MutationService {
}
if (
- previousMutation.type === 'mark_file_opened' &&
- previousMutation.data.fileId === mutation.data.fileId
+ previousMutation.type === 'mark_node_seen' &&
+ previousMutation.data.nodeId === mutation.data.nodeId
) {
deletedMutationIds.add(previousMutation.id);
}
}
- } else if (mutation.type === 'mark_message_seen') {
+ } else if (mutation.type === 'mark_node_opened') {
for (let j = i - 1; j >= 0; j--) {
const previousMutation = mutations[j];
if (!previousMutation) {
@@ -383,8 +288,8 @@ export class MutationService {
}
if (
- previousMutation.type === 'mark_message_seen' &&
- previousMutation.data.messageId === mutation.data.messageId
+ previousMutation.type === 'mark_node_opened' &&
+ previousMutation.data.nodeId === mutation.data.nodeId
) {
deletedMutationIds.add(previousMutation.id);
}
diff --git a/apps/desktop/src/main/services/workspaces/node-interaction-service.ts b/apps/desktop/src/main/services/workspaces/node-interaction-service.ts
new file mode 100644
index 00000000..469197fb
--- /dev/null
+++ b/apps/desktop/src/main/services/workspaces/node-interaction-service.ts
@@ -0,0 +1,74 @@
+import { createDebugger, SyncNodeInteractionData } from '@colanode/core';
+
+import { WorkspaceService } from '@/main/services/workspaces/workspace-service';
+import { eventBus } from '@/shared/lib/event-bus';
+import { mapNodeInteraction } from '@/main/lib/mappers';
+
+export class NodeInteractionService {
+ private readonly debug = createDebugger('desktop:service:node-interaction');
+ private readonly workspace: WorkspaceService;
+
+ constructor(workspaceService: WorkspaceService) {
+ this.workspace = workspaceService;
+ }
+
+ public async syncServerNodeInteraction(
+ nodeInteraction: SyncNodeInteractionData
+ ) {
+ const existingNodeInteraction = await this.workspace.database
+ .selectFrom('node_interactions')
+ .selectAll()
+ .where('node_id', '=', nodeInteraction.nodeId)
+ .where('collaborator_id', '=', nodeInteraction.collaboratorId)
+ .executeTakeFirst();
+
+ const revision = BigInt(nodeInteraction.revision);
+ if (existingNodeInteraction) {
+ if (existingNodeInteraction.revision === revision) {
+ this.debug(
+ `Server node interaction for node ${nodeInteraction.nodeId} is already synced`
+ );
+ return;
+ }
+ }
+
+ const createdNodeInteraction = await this.workspace.database
+ .insertInto('node_interactions')
+ .returningAll()
+ .values({
+ node_id: nodeInteraction.nodeId,
+ root_id: nodeInteraction.rootId,
+ collaborator_id: nodeInteraction.collaboratorId,
+ first_seen_at: nodeInteraction.firstSeenAt,
+ last_seen_at: nodeInteraction.lastSeenAt,
+ last_opened_at: nodeInteraction.lastOpenedAt,
+ first_opened_at: nodeInteraction.firstOpenedAt,
+ revision,
+ })
+ .onConflict((b) =>
+ b.columns(['node_id', 'collaborator_id']).doUpdateSet({
+ last_seen_at: nodeInteraction.lastSeenAt,
+ first_seen_at: nodeInteraction.firstSeenAt,
+ last_opened_at: nodeInteraction.lastOpenedAt,
+ first_opened_at: nodeInteraction.firstOpenedAt,
+ revision,
+ })
+ )
+ .executeTakeFirst();
+
+ if (!createdNodeInteraction) {
+ return;
+ }
+
+ eventBus.publish({
+ type: 'node_interaction_updated',
+ accountId: this.workspace.accountId,
+ workspaceId: this.workspace.id,
+ nodeInteraction: mapNodeInteraction(createdNodeInteraction),
+ });
+
+ this.debug(
+ `Server node interaction for node ${nodeInteraction.nodeId} has been synced`
+ );
+ }
+}
diff --git a/apps/desktop/src/main/services/workspaces/node-reaction-service.ts b/apps/desktop/src/main/services/workspaces/node-reaction-service.ts
new file mode 100644
index 00000000..1205a23f
--- /dev/null
+++ b/apps/desktop/src/main/services/workspaces/node-reaction-service.ts
@@ -0,0 +1,408 @@
+import {
+ canCreateNodeReaction,
+ createDebugger,
+ CreateNodeReactionMutation,
+ CreateNodeReactionMutationData,
+ DeleteNodeReactionMutation,
+ DeleteNodeReactionMutationData,
+ generateId,
+ IdType,
+ SyncNodeReactionData,
+} from '@colanode/core';
+
+import { WorkspaceService } from '@/main/services/workspaces/workspace-service';
+import { eventBus } from '@/shared/lib/event-bus';
+import { mapNode, mapNodeReaction } from '@/main/lib/mappers';
+import { SelectNodeReaction } from '@/main/databases/workspace';
+import { MutationErrorCode, MutationError } from '@/shared/mutations';
+import { fetchNode } from '@/main/lib/utils';
+
+export class NodeReactionService {
+ private readonly debug = createDebugger('desktop:service:node-reaction');
+ private readonly workspace: WorkspaceService;
+
+ constructor(workspaceService: WorkspaceService) {
+ this.workspace = workspaceService;
+ }
+
+ public async createNodeReaction(nodeId: string, reaction: string) {
+ const node = await this.workspace.database
+ .selectFrom('nodes')
+ .selectAll()
+ .where('id', '=', nodeId)
+ .executeTakeFirst();
+
+ if (!node) {
+ throw new MutationError(
+ MutationErrorCode.NodeNotFound,
+ 'Node not found or has been deleted.'
+ );
+ }
+
+ const existingNodeReaction = await this.workspace.database
+ .selectFrom('node_reactions')
+ .selectAll()
+ .where('node_id', '=', nodeId)
+ .where('collaborator_id', '=', this.workspace.userId)
+ .where('reaction', '=', reaction)
+ .executeTakeFirst();
+
+ if (existingNodeReaction) {
+ return {
+ success: true,
+ };
+ }
+
+ const root = await fetchNode(this.workspace.database, node.root_id);
+ if (!root) {
+ throw new MutationError(
+ MutationErrorCode.RootNotFound,
+ 'There was an error while fetching the root. Please make sure you have access to this root.'
+ );
+ }
+
+ if (
+ !canCreateNodeReaction({
+ user: {
+ userId: this.workspace.userId,
+ role: this.workspace.role,
+ },
+ node: mapNode(node),
+ root: mapNode(root),
+ })
+ ) {
+ throw new MutationError(
+ MutationErrorCode.NodeReactionCreateForbidden,
+ "You don't have permission to react to this node."
+ );
+ }
+
+ const tombstoneId = this.generateTombstoneId(nodeId, reaction);
+ const { createdNodeReaction, createdMutation } =
+ await this.workspace.database.transaction().execute(async (trx) => {
+ const createdNodeReaction = await trx
+ .insertInto('node_reactions')
+ .returningAll()
+ .values({
+ node_id: nodeId,
+ collaborator_id: this.workspace.userId,
+ reaction,
+ root_id: node.root_id,
+ revision: 0n,
+ created_at: new Date().toISOString(),
+ })
+ .onConflict((cb) => cb.doNothing())
+ .executeTakeFirst();
+
+ if (!createdNodeReaction) {
+ throw new Error('Failed to create node reaction');
+ }
+
+ const mutation: CreateNodeReactionMutation = {
+ id: generateId(IdType.Mutation),
+ createdAt: new Date().toISOString(),
+ type: 'create_node_reaction',
+ data: {
+ nodeId,
+ reaction,
+ rootId: node.root_id,
+ createdAt: new Date().toISOString(),
+ },
+ };
+
+ const createdMutation = await trx
+ .insertInto('mutations')
+ .returningAll()
+ .values({
+ id: mutation.id,
+ type: mutation.type,
+ data: JSON.stringify(mutation.data),
+ created_at: mutation.createdAt,
+ retries: 0,
+ })
+ .executeTakeFirst();
+
+ await trx
+ .deleteFrom('tombstones')
+ .where('id', '=', tombstoneId)
+ .execute();
+
+ return {
+ createdNodeReaction,
+ createdMutation,
+ };
+ });
+
+ if (!createdNodeReaction || !createdMutation) {
+ throw new Error('Failed to create node reaction');
+ }
+
+ this.workspace.mutations.triggerSync();
+
+ eventBus.publish({
+ type: 'node_reaction_created',
+ accountId: this.workspace.accountId,
+ workspaceId: this.workspace.id,
+ nodeReaction: mapNodeReaction(createdNodeReaction),
+ });
+ }
+
+ public async deleteNodeReaction(nodeId: string, reaction: string) {
+ const existingNodeReaction = await this.workspace.database
+ .selectFrom('node_reactions')
+ .selectAll()
+ .where('node_id', '=', nodeId)
+ .where('collaborator_id', '=', this.workspace.userId)
+ .where('reaction', '=', reaction)
+ .executeTakeFirst();
+
+ if (!existingNodeReaction) {
+ return {
+ success: true,
+ };
+ }
+
+ const tombstoneId = this.generateTombstoneId(nodeId, reaction);
+ const { deletedNodeReaction, createdMutation } =
+ await this.workspace.database.transaction().execute(async (trx) => {
+ const deletedNodeReaction = await trx
+ .deleteFrom('node_reactions')
+ .returningAll()
+ .where('node_id', '=', nodeId)
+ .where('collaborator_id', '=', this.workspace.userId)
+ .where('reaction', '=', reaction)
+ .executeTakeFirst();
+
+ if (!deletedNodeReaction) {
+ throw new Error('Failed to delete node reaction');
+ }
+
+ const mutation: DeleteNodeReactionMutation = {
+ id: generateId(IdType.Mutation),
+ createdAt: new Date().toISOString(),
+ type: 'delete_node_reaction',
+ data: {
+ nodeId,
+ reaction,
+ rootId: existingNodeReaction.root_id,
+ deletedAt: new Date().toISOString(),
+ },
+ };
+
+ const createdMutation = await trx
+ .insertInto('mutations')
+ .returningAll()
+ .values({
+ id: mutation.id,
+ type: mutation.type,
+ data: JSON.stringify(mutation.data),
+ created_at: mutation.createdAt,
+ retries: 0,
+ })
+ .executeTakeFirst();
+
+ if (!createdMutation) {
+ throw new Error('Failed to create node reaction mutation');
+ }
+
+ await trx
+ .insertInto('tombstones')
+ .values({
+ id: tombstoneId,
+ data: JSON.stringify(deletedNodeReaction),
+ created_at: new Date().toISOString(),
+ })
+ .executeTakeFirst();
+
+ return {
+ deletedNodeReaction,
+ createdMutation,
+ };
+ });
+
+ if (!deletedNodeReaction || !createdMutation) {
+ throw new Error('Failed to delete node reaction');
+ }
+
+ this.workspace.mutations.triggerSync();
+
+ eventBus.publish({
+ type: 'node_reaction_deleted',
+ accountId: this.workspace.accountId,
+ workspaceId: this.workspace.id,
+ nodeReaction: mapNodeReaction(deletedNodeReaction),
+ });
+ }
+
+ public async syncServerNodeReaction(nodeReaction: SyncNodeReactionData) {
+ if (nodeReaction.deletedAt) {
+ const deletedNodeReaction = await this.workspace.database
+ .deleteFrom('node_reactions')
+ .returningAll()
+ .where('node_id', '=', nodeReaction.nodeId)
+ .where('collaborator_id', '=', nodeReaction.collaboratorId)
+ .where('reaction', '=', nodeReaction.reaction)
+ .executeTakeFirst();
+
+ if (deletedNodeReaction) {
+ eventBus.publish({
+ type: 'node_reaction_deleted',
+ accountId: this.workspace.accountId,
+ workspaceId: this.workspace.id,
+ nodeReaction: mapNodeReaction(deletedNodeReaction),
+ });
+ }
+
+ this.debug(
+ `Server node reaction for node ${nodeReaction.nodeId} has been synced`
+ );
+ return;
+ }
+
+ const existingNodeReaction = await this.workspace.database
+ .selectFrom('node_reactions')
+ .selectAll()
+ .where('node_id', '=', nodeReaction.nodeId)
+ .where('collaborator_id', '=', nodeReaction.collaboratorId)
+ .where('reaction', '=', nodeReaction.reaction)
+ .executeTakeFirst();
+
+ const revision = BigInt(nodeReaction.revision);
+ if (existingNodeReaction) {
+ if (existingNodeReaction.revision === revision) {
+ this.debug(
+ `Server node reaction for node ${nodeReaction.nodeId} is already synced`
+ );
+ return;
+ }
+
+ const updatedNodeReaction = await this.workspace.database
+ .updateTable('node_reactions')
+ .returningAll()
+ .set({
+ revision,
+ })
+ .where('node_id', '=', nodeReaction.nodeId)
+ .where('collaborator_id', '=', nodeReaction.collaboratorId)
+ .where('reaction', '=', nodeReaction.reaction)
+ .executeTakeFirst();
+
+ if (!updatedNodeReaction) {
+ return;
+ }
+
+ this.debug(
+ `Server node reaction for node ${nodeReaction.nodeId} has been synced`
+ );
+ return;
+ }
+
+ const createdNodeReaction = await this.workspace.database
+ .insertInto('node_reactions')
+ .returningAll()
+ .values({
+ node_id: nodeReaction.nodeId,
+ collaborator_id: nodeReaction.collaboratorId,
+ reaction: nodeReaction.reaction,
+ root_id: nodeReaction.rootId,
+ created_at: nodeReaction.createdAt,
+ revision,
+ })
+ .onConflict((b) =>
+ b.columns(['node_id', 'collaborator_id', 'reaction']).doUpdateSet({
+ revision,
+ })
+ )
+ .executeTakeFirst();
+
+ if (!createdNodeReaction) {
+ return;
+ }
+
+ eventBus.publish({
+ type: 'node_reaction_created',
+ accountId: this.workspace.accountId,
+ workspaceId: this.workspace.id,
+ nodeReaction: mapNodeReaction(createdNodeReaction),
+ });
+
+ this.debug(
+ `Server node reaction for node ${nodeReaction.nodeId} has been synced`
+ );
+ }
+
+ public async revertNodeReactionCreation(
+ nodeReaction: CreateNodeReactionMutationData
+ ) {
+ const deletedNodeReaction = await this.workspace.database
+ .deleteFrom('node_reactions')
+ .returningAll()
+ .where('node_id', '=', nodeReaction.nodeId)
+ .where('collaborator_id', '=', this.workspace.userId)
+ .where('reaction', '=', nodeReaction.reaction)
+ .executeTakeFirst();
+
+ if (!deletedNodeReaction) {
+ return;
+ }
+
+ eventBus.publish({
+ type: 'node_reaction_deleted',
+ accountId: this.workspace.accountId,
+ workspaceId: this.workspace.id,
+ nodeReaction: mapNodeReaction(deletedNodeReaction),
+ });
+ }
+
+ public async revertNodeReactionDeletion(
+ nodeReaction: DeleteNodeReactionMutationData
+ ) {
+ const tombstoneId = this.generateTombstoneId(
+ nodeReaction.nodeId,
+ nodeReaction.reaction
+ );
+ const tombstone = await this.workspace.database
+ .selectFrom('tombstones')
+ .selectAll()
+ .where('id', '=', tombstoneId)
+ .executeTakeFirst();
+
+ if (!tombstone) {
+ return;
+ }
+
+ const data = JSON.parse(tombstone.data) as SelectNodeReaction;
+ const createdNodeReaction = await this.workspace.database
+ .insertInto('node_reactions')
+ .returningAll()
+ .values({
+ node_id: data.node_id,
+ collaborator_id: data.collaborator_id,
+ reaction: data.reaction,
+ root_id: data.root_id,
+ created_at: data.created_at,
+ revision: data.revision,
+ })
+ .onConflict((b) =>
+ b.columns(['node_id', 'collaborator_id', 'reaction']).doUpdateSet({
+ revision: data.revision,
+ })
+ )
+ .executeTakeFirst();
+
+ if (!createdNodeReaction) {
+ return;
+ }
+
+ eventBus.publish({
+ type: 'node_reaction_created',
+ accountId: this.workspace.accountId,
+ workspaceId: this.workspace.id,
+ nodeReaction: mapNodeReaction(createdNodeReaction),
+ });
+ }
+
+ private generateTombstoneId(nodeId: string, reaction: string) {
+ return `${nodeId}-${reaction}`;
+ }
+}
diff --git a/apps/desktop/src/main/services/workspaces/node-service.ts b/apps/desktop/src/main/services/workspaces/node-service.ts
new file mode 100644
index 00000000..df0a9b61
--- /dev/null
+++ b/apps/desktop/src/main/services/workspaces/node-service.ts
@@ -0,0 +1,1024 @@
+import {
+ generateId,
+ IdType,
+ TransactionOperation,
+ createDebugger,
+ NodeAttributes,
+ Node,
+ canCreateNode,
+ nodeAttributesSchema,
+ extractNodeText,
+ canUpdateNode,
+ canDeleteNode,
+ DeleteNodeMutationData,
+ SyncNodeData,
+ SyncNodeTombstoneData,
+ LocalNodeTransaction,
+} from '@colanode/core';
+import { decodeState, YDoc } from '@colanode/crdt';
+
+import { fetchNode } from '@/main/lib/utils';
+import { mapFile, mapNode, mapNodeTransaction } from '@/main/lib/mappers';
+import { eventBus } from '@/shared/lib/event-bus';
+import { WorkspaceService } from '@/main/services/workspaces/workspace-service';
+import { SelectNode } from '@/main/databases/workspace';
+
+const UPDATE_RETRIES_LIMIT = 20;
+
+export type CreateNodeInput = {
+ id: string;
+ attributes: NodeAttributes;
+ parentId: string | null;
+};
+
+export type UpdateNodeResult =
+ | 'success'
+ | 'not_found'
+ | 'unauthorized'
+ | 'failed'
+ | 'invalid_attributes';
+
+export class NodeService {
+ private readonly debug = createDebugger('desktop:service:node');
+ private readonly workspace: WorkspaceService;
+
+ constructor(workspaceService: WorkspaceService) {
+ this.workspace = workspaceService;
+ }
+
+ public async createNode(input: CreateNodeInput): Promise<SelectNode> {
+ this.debug(`Creating ${Array.isArray(input) ? 'nodes' : 'node'}`);
+
+ let root: Node | null = null;
+
+ if (input.parentId) {
+ const parent = await fetchNode(this.workspace.database, input.parentId);
+
+ if (parent) {
+ if (parent.id === parent.root_id) {
+ root = mapNode(parent);
+ } else {
+ const rootRow = await fetchNode(
+ this.workspace.database,
+ parent.root_id
+ );
+ if (rootRow) {
+ root = mapNode(rootRow);
+ }
+ }
+ }
+ }
+
+ if (
+ !canCreateNode(
+ {
+ user: {
+ userId: this.workspace.userId,
+ role: this.workspace.role,
+ },
+ root: root,
+ },
+ input.attributes.type
+ )
+ ) {
+ throw new Error('Insufficient permissions');
+ }
+
+ const ydoc = new YDoc();
+ const update = ydoc.updateAttributes(
+ nodeAttributesSchema,
+ input.attributes
+ );
+
+ if (!update) {
+ throw new Error('Invalid attributes');
+ }
+
+ const createdAt = new Date().toISOString();
+ const transactionId = generateId(IdType.Transaction);
+ const text = extractNodeText(input.id, input.attributes);
+
+ const { createdNode, createdMutation } = await this.workspace.database
+ .transaction()
+ .execute(async (trx) => {
+ const createdNode = await trx
+ .insertInto('nodes')
+ .returningAll()
+ .values({
+ id: input.id,
+ root_id: root?.id ?? input.id,
+ attributes: JSON.stringify(input.attributes),
+ created_at: createdAt,
+ created_by: this.workspace.userId,
+ local_revision: BigInt(0),
+ server_revision: BigInt(0),
+ })
+ .executeTakeFirst();
+
+ if (!createdNode) {
+ throw new Error('Failed to create entry');
+ }
+
+ const createdTransaction = await trx
+ .insertInto('node_transactions')
+ .returningAll()
+ .values({
+ id: transactionId,
+ node_id: input.id,
+ operation: TransactionOperation.Create,
+ data: update,
+ created_at: createdAt,
+ })
+ .executeTakeFirst();
+
+ if (!createdTransaction) {
+ throw new Error('Failed to create transaction');
+ }
+
+ const createdMutation = await trx
+ .insertInto('mutations')
+ .returningAll()
+ .values({
+ id: generateId(IdType.Mutation),
+ type: 'apply_node_transaction',
+ data: JSON.stringify(mapNodeTransaction(createdTransaction)),
+ created_at: createdAt,
+ retries: 0,
+ })
+ .executeTakeFirst();
+
+ if (!createdMutation) {
+ throw new Error('Failed to create mutation');
+ }
+
+ if (text) {
+ await trx
+ .insertInto('texts')
+ .values({ id: input.id, name: text.name, text: text.text })
+ .execute();
+ }
+
+ return {
+ createdNode,
+ createdMutation,
+ };
+ });
+
+ if (!createdNode) {
+ throw new Error('Failed to create entry');
+ }
+
+ this.debug(`Created node ${createdNode.id} with type ${createdNode.type}`);
+
+ eventBus.publish({
+ type: 'node_created',
+ accountId: this.workspace.accountId,
+ workspaceId: this.workspace.id,
+ node: mapNode(createdNode),
+ });
+
+ if (!createdMutation) {
+ throw new Error('Failed to create mutation');
+ }
+
+ this.workspace.mutations.triggerSync();
+ return createdNode;
+ }
+
+ public async updateNode<T extends NodeAttributes>(
+ nodeId: string,
+ updater: (attributes: T) => T
+ ): Promise<UpdateNodeResult> {
+ for (let count = 0; count < UPDATE_RETRIES_LIMIT; count++) {
+ const result = await this.tryUpdateNode(nodeId, updater);
+ if (result) {
+ return result;
+ }
+ }
+
+ return 'failed';
+ }
+
+ private async tryUpdateNode<T extends NodeAttributes>(
+ nodeId: string,
+ updater: (attributes: T) => T
+ ): Promise<UpdateNodeResult | null> {
+ this.debug(`Updating node ${nodeId}`);
+
+ const nodeRow = await fetchNode(this.workspace.database, nodeId);
+ if (!nodeRow) {
+ return 'not_found';
+ }
+
+ const root = await fetchNode(this.workspace.database, nodeRow.root_id);
+ if (!root) {
+ return 'not_found';
+ }
+
+ const node = mapNode(nodeRow);
+ const transactionId = generateId(IdType.Transaction);
+ const updatedAt = new Date().toISOString();
+ const updatedAttributes = updater(node.attributes as T);
+
+ const ydoc = new YDoc();
+
+ const state = await this.workspace.database
+ .selectFrom('node_states')
+ .where('id', '=', nodeId)
+ .selectAll()
+ .executeTakeFirst();
+
+ if (state) {
+ ydoc.applyUpdate(state.state);
+ }
+
+ const transactions = await this.workspace.database
+ .selectFrom('node_transactions')
+ .where('node_id', '=', nodeId)
+ .selectAll()
+ .execute();
+
+ for (const transaction of transactions) {
+ ydoc.applyUpdate(transaction.data);
+ }
+
+ const update = ydoc.updateAttributes(
+ nodeAttributesSchema,
+ updatedAttributes
+ );
+
+ if (
+ !canUpdateNode(
+ {
+ user: {
+ userId: this.workspace.userId,
+ role: this.workspace.role,
+ },
+ root: mapNode(root),
+ node: node,
+ },
+ updatedAttributes
+ )
+ ) {
+ return 'unauthorized';
+ }
+
+ if (!update) {
+ return 'success';
+ }
+
+ const attributes = ydoc.getAttributes<NodeAttributes>();
+ const text = extractNodeText(nodeId, updatedAttributes);
+
+ const localRevision = BigInt(node.localRevision) + BigInt(1);
+ const { updatedNode, createdMutation } = await this.workspace.database
+ .transaction()
+ .execute(async (trx) => {
+ const updatedNode = await trx
+ .updateTable('nodes')
+ .returningAll()
+ .set({
+ attributes: JSON.stringify(attributes),
+ updated_at: updatedAt,
+ updated_by: this.workspace.userId,
+ local_revision: localRevision,
+ })
+ .where('id', '=', nodeId)
+ .where('local_revision', '=', node.localRevision)
+ .executeTakeFirst();
+
+ if (!updatedNode) {
+ return { updatedNode: undefined };
+ }
+
+ const createdTransaction = await trx
+ .insertInto('node_transactions')
+ .returningAll()
+ .values({
+ id: transactionId,
+ node_id: nodeId,
+ operation: TransactionOperation.Update,
+ data: update,
+ created_at: updatedAt,
+ })
+ .executeTakeFirst();
+
+ if (!createdTransaction) {
+ throw new Error('Failed to create transaction');
+ }
+
+ const createdMutation = await trx
+ .insertInto('mutations')
+ .returningAll()
+ .values({
+ id: generateId(IdType.Mutation),
+ type: 'apply_node_transaction',
+ data: JSON.stringify(mapNodeTransaction(createdTransaction)),
+ created_at: updatedAt,
+ retries: 0,
+ })
+ .executeTakeFirst();
+
+ if (!createdMutation) {
+ throw new Error('Failed to create mutation');
+ }
+
+ if (text !== undefined) {
+ await trx.deleteFrom('texts').where('id', '=', nodeId).execute();
+ }
+
+ if (text) {
+ await trx
+ .insertInto('texts')
+ .values({ id: nodeId, name: text.name, text: text.text })
+ .execute();
+ }
+
+ return {
+ updatedNode,
+ createdMutation,
+ };
+ });
+
+ if (updatedNode) {
+ this.debug(
+ `Updated node ${updatedNode.id} with type ${updatedNode.type}`
+ );
+
+ eventBus.publish({
+ type: 'node_updated',
+ accountId: this.workspace.accountId,
+ workspaceId: this.workspace.id,
+ node: mapNode(updatedNode),
+ });
+ } else {
+ this.debug(`Failed to update node ${nodeId}`);
+ }
+
+ if (createdMutation) {
+ this.workspace.mutations.triggerSync();
+ }
+
+ if (updatedNode) {
+ return 'success';
+ }
+
+ return null;
+ }
+
+ public async deleteNode(nodeId: string) {
+ const node = await fetchNode(this.workspace.database, nodeId);
+ if (!node) {
+ throw new Error('Node not found');
+ }
+
+ const root = await fetchNode(this.workspace.database, node.root_id);
+ if (!root) {
+ throw new Error('Root not found');
+ }
+
+ if (
+ !canDeleteNode({
+ user: {
+ userId: this.workspace.userId,
+ role: this.workspace.role,
+ },
+ root: mapNode(root),
+ node: mapNode(node),
+ })
+ ) {
+ throw new Error('Insufficient permissions');
+ }
+
+ const { deletedNode, createdMutation } = await this.workspace.database
+ .transaction()
+ .execute(async (trx) => {
+ const deletedNode = await trx
+ .deleteFrom('nodes')
+ .returningAll()
+ .where('id', '=', nodeId)
+ .executeTakeFirst();
+
+ if (!deletedNode) {
+ return { deletedNode: undefined };
+ }
+
+ await trx
+ .insertInto('tombstones')
+ .values({
+ id: deletedNode.id,
+ data: JSON.stringify(deletedNode),
+ created_at: new Date().toISOString(),
+ })
+ .execute();
+
+ const deleteMutationData: DeleteNodeMutationData = {
+ id: nodeId,
+ rootId: root.root_id,
+ deletedAt: new Date().toISOString(),
+ };
+
+ const createdMutation = await trx
+ .insertInto('mutations')
+ .returningAll()
+ .values({
+ id: generateId(IdType.Mutation),
+ type: 'delete_node',
+ data: JSON.stringify(deleteMutationData),
+ created_at: new Date().toISOString(),
+ retries: 0,
+ })
+ .executeTakeFirst();
+
+ return { deletedNode, createdMutation };
+ });
+
+ if (deletedNode) {
+ this.debug(
+ `Deleted node ${deletedNode.id} with type ${deletedNode.type}`
+ );
+
+ eventBus.publish({
+ type: 'node_deleted',
+ accountId: this.workspace.accountId,
+ workspaceId: this.workspace.id,
+ node: mapNode(deletedNode),
+ });
+ } else {
+ this.debug(`Failed to delete node ${nodeId}`);
+ }
+
+ if (createdMutation) {
+ this.workspace.mutations.triggerSync();
+ }
+ }
+
+ public async syncServerNode(node: SyncNodeData) {
+ const existingNode = await this.workspace.database
+ .selectFrom('nodes')
+ .where('id', '=', node.id)
+ .selectAll()
+ .executeTakeFirst();
+
+ if (!existingNode) {
+ return this.createServerNode(node);
+ } else {
+ return this.updateServerNode(node);
+ }
+ }
+
+ private async createServerNode(node: SyncNodeData): Promise<void> {
+ const serverRevision = BigInt(node.revision);
+
+ const ydoc = new YDoc(node.state);
+ const transactions = await this.workspace.database
+ .selectFrom('node_transactions')
+ .selectAll()
+ .where('node_id', '=', node.id)
+ .orderBy('id', 'asc')
+ .execute();
+
+ for (const transaction of transactions) {
+ ydoc.applyUpdate(transaction.data);
+ }
+
+ const attributes = ydoc.getAttributes<NodeAttributes>();
+ const text = extractNodeText(node.id, attributes);
+
+ const { createdNode } = await this.workspace.database
+ .transaction()
+ .execute(async (trx) => {
+ const createdNode = await trx
+ .insertInto('nodes')
+ .returningAll()
+ .values({
+ id: node.id,
+ root_id: node.rootId,
+ attributes: JSON.stringify(attributes),
+ created_at: node.createdAt,
+ created_by: node.createdBy,
+ local_revision: 0n,
+ server_revision: serverRevision,
+ })
+ .executeTakeFirst();
+
+ if (!createdNode) {
+ return { createdNode: undefined };
+ }
+
+ if (text) {
+ await trx
+ .insertInto('texts')
+ .values({ id: node.id, name: text.name, text: text.text })
+ .execute();
+ }
+
+ await trx
+ .insertInto('node_states')
+ .returningAll()
+ .values({
+ id: node.id,
+ revision: serverRevision,
+ state: decodeState(node.state),
+ })
+ .executeTakeFirst();
+
+ return { createdNode };
+ });
+
+ if (!createdNode) {
+ this.debug(`Failed to create node ${node.id}`);
+ return;
+ }
+
+ this.debug(`Created node ${createdNode.id} with type ${createdNode.type}`);
+
+ eventBus.publish({
+ type: 'node_created',
+ accountId: this.workspace.accountId,
+ workspaceId: this.workspace.id,
+ node: mapNode(createdNode),
+ });
+ }
+
+ public async updateServerNode(node: SyncNodeData): Promise<void> {
+ for (let count = 0; count < UPDATE_RETRIES_LIMIT; count++) {
+ const result = await this.tryUpdateServerNode(node);
+
+ if (result) {
+ return;
+ }
+ }
+ }
+
+ private async tryUpdateServerNode(node: SyncNodeData): Promise<boolean> {
+ const serverRevision = BigInt(node.revision);
+
+ const existingNode = await this.workspace.database
+ .selectFrom('nodes')
+ .where('id', '=', node.id)
+ .selectAll()
+ .executeTakeFirst();
+
+ if (!existingNode) {
+ await this.createServerNode(node);
+ return true;
+ }
+
+ const ydoc = new YDoc(node.state);
+ const transactions = await this.workspace.database
+ .selectFrom('node_transactions')
+ .selectAll()
+ .where('node_id', '=', node.id)
+ .orderBy('id', 'asc')
+ .execute();
+
+ for (const transaction of transactions) {
+ ydoc.applyUpdate(transaction.data);
+ }
+
+ const attributes = ydoc.getAttributes<NodeAttributes>();
+ const text = extractNodeText(node.id, attributes);
+ const localRevision = BigInt(existingNode.local_revision) + BigInt(1);
+
+ const { updatedNode } = await this.workspace.database
+ .transaction()
+ .execute(async (trx) => {
+ const updatedNode = await trx
+ .updateTable('nodes')
+ .returningAll()
+ .set({
+ attributes: JSON.stringify(attributes),
+ updated_at: node.updatedAt,
+ updated_by: node.updatedBy,
+ local_revision: localRevision,
+ server_revision: serverRevision,
+ })
+ .where('id', '=', node.id)
+ .where('local_revision', '=', existingNode.local_revision)
+ .executeTakeFirst();
+
+ if (!updatedNode) {
+ return { updatedNode: undefined };
+ }
+
+ await trx
+ .updateTable('node_states')
+ .set({
+ revision: serverRevision,
+ state: decodeState(node.state),
+ })
+ .where('id', '=', node.id)
+ .executeTakeFirst();
+
+ if (text !== undefined) {
+ await trx.deleteFrom('texts').where('id', '=', node.id).execute();
+ }
+
+ if (text) {
+ await trx
+ .insertInto('texts')
+ .values({ id: node.id, name: text.name, text: text.text })
+ .execute();
+ }
+
+ return { updatedNode };
+ });
+
+ if (!updatedNode) {
+ this.debug(`Failed to update node ${node.id}`);
+ return false;
+ }
+
+ this.debug(`Updated node ${updatedNode.id} with type ${updatedNode.type}`);
+
+ eventBus.publish({
+ type: 'node_updated',
+ accountId: this.workspace.accountId,
+ workspaceId: this.workspace.id,
+ node: mapNode(updatedNode),
+ });
+
+ return true;
+ }
+
+ public async syncServerNodeDelete(tombstone: SyncNodeTombstoneData) {
+ this.debug(
+ `Applying server delete transaction ${tombstone.id} for node ${tombstone.id}`
+ );
+
+ const { deletedNode, deletedFile } = await this.workspace.database
+ .transaction()
+ .execute(async (trx) => {
+ const deletedNode = await trx
+ .deleteFrom('nodes')
+ .returningAll()
+ .where('id', '=', tombstone.id)
+ .executeTakeFirst();
+
+ await trx
+ .deleteFrom('node_transactions')
+ .where('node_id', '=', tombstone.id)
+ .execute();
+
+ await trx
+ .deleteFrom('node_states')
+ .where('id', '=', tombstone.id)
+ .execute();
+
+ await trx.deleteFrom('texts').where('id', '=', tombstone.id).execute();
+
+ await trx
+ .deleteFrom('node_reactions')
+ .where('node_id', '=', tombstone.id)
+ .execute();
+
+ await trx
+ .deleteFrom('node_interactions')
+ .where('node_id', '=', tombstone.id)
+ .execute();
+
+ const deletedFile = await trx
+ .deleteFrom('files')
+ .returningAll()
+ .where('id', '=', tombstone.id)
+ .executeTakeFirst();
+
+ await trx
+ .deleteFrom('tombstones')
+ .where('id', '=', tombstone.id)
+ .execute();
+
+ return { deletedNode, deletedFile };
+ });
+
+ if (deletedFile) {
+ this.workspace.files.deleteFile(deletedFile.id, deletedFile.extension);
+ eventBus.publish({
+ type: 'file_deleted',
+ accountId: this.workspace.accountId,
+ workspaceId: this.workspace.id,
+ file: mapFile(deletedFile),
+ });
+ }
+
+ if (deletedNode) {
+ eventBus.publish({
+ type: 'node_deleted',
+ accountId: this.workspace.accountId,
+ workspaceId: this.workspace.id,
+ node: mapNode(deletedNode),
+ });
+ }
+ }
+
+ public async revertNodeTransaction(transaction: LocalNodeTransaction) {
+ if (transaction.operation === TransactionOperation.Create) {
+ return this.revertCreateTransaction(transaction);
+ } else if (transaction.operation === TransactionOperation.Update) {
+ return this.revertUpdateTransaction(transaction);
+ }
+ }
+
+ public async revertCreateTransaction(transaction: LocalNodeTransaction) {
+ const node = await this.workspace.database
+ .selectFrom('nodes')
+ .selectAll()
+ .where('id', '=', transaction.nodeId)
+ .executeTakeFirst();
+
+ if (!node) {
+ return;
+ }
+
+ const transactionRow = await this.workspace.database
+ .selectFrom('node_transactions')
+ .selectAll()
+ .where('id', '=', transaction.id)
+ .executeTakeFirst();
+
+ if (!transactionRow) {
+ return;
+ }
+
+ await this.workspace.database.transaction().execute(async (tx) => {
+ await tx
+ .deleteFrom('nodes')
+ .where('id', '=', transaction.nodeId)
+ .execute();
+
+ await tx
+ .deleteFrom('node_transactions')
+ .where('node_id', '=', transaction.nodeId)
+ .execute();
+
+ await tx
+ .deleteFrom('node_interactions')
+ .where('node_id', '=', transaction.nodeId)
+ .execute();
+
+ await tx
+ .deleteFrom('texts')
+ .where('id', '=', transaction.nodeId)
+ .execute();
+
+ await tx
+ .deleteFrom('node_reactions')
+ .where('node_id', '=', transaction.nodeId)
+ .execute();
+
+ await tx
+ .deleteFrom('node_states')
+ .where('id', '=', transaction.nodeId)
+ .execute();
+ });
+
+ eventBus.publish({
+ type: 'node_deleted',
+ accountId: this.workspace.accountId,
+ workspaceId: this.workspace.id,
+ node: mapNode(node),
+ });
+ }
+
+ public async revertUpdateTransaction(transaction: LocalNodeTransaction) {
+ for (let count = 0; count < UPDATE_RETRIES_LIMIT; count++) {
+ const result = await this.tryRevertUpdateTransaction(transaction);
+
+ if (result) {
+ return;
+ }
+ }
+ }
+
+ private async tryRevertUpdateTransaction(
+ transaction: LocalNodeTransaction
+ ): Promise<boolean> {
+ const node = await this.workspace.database
+ .selectFrom('nodes')
+ .selectAll()
+ .where('id', '=', transaction.nodeId)
+ .executeTakeFirst();
+
+ if (!node) {
+ // Make sure we don't have any data left behind
+ await this.workspace.database
+ .deleteFrom('node_transactions')
+ .where('id', '=', transaction.id)
+ .execute();
+
+ await this.workspace.database
+ .deleteFrom('node_interactions')
+ .where('node_id', '=', transaction.nodeId)
+ .execute();
+
+ await this.workspace.database
+ .deleteFrom('texts')
+ .where('id', '=', transaction.nodeId)
+ .execute();
+
+ await this.workspace.database
+ .deleteFrom('node_reactions')
+ .where('node_id', '=', transaction.nodeId)
+ .execute();
+
+ await this.workspace.database
+ .deleteFrom('node_states')
+ .where('id', '=', transaction.nodeId)
+ .execute();
+
+ return true;
+ }
+
+ const transactionRow = await this.workspace.database
+ .selectFrom('node_transactions')
+ .selectAll()
+ .where('id', '=', transaction.id)
+ .executeTakeFirst();
+
+ if (!transactionRow) {
+ return true;
+ }
+
+ const nodeTransactions = await this.workspace.database
+ .selectFrom('node_transactions')
+ .selectAll()
+ .where('node_id', '=', transaction.nodeId)
+ .orderBy('id', 'asc')
+ .execute();
+
+ const state = await this.workspace.database
+ .selectFrom('node_states')
+ .selectAll()
+ .where('id', '=', transaction.nodeId)
+ .executeTakeFirst();
+
+ if (!state) {
+ return true;
+ }
+
+ const ydoc = new YDoc(state.state);
+ for (const nodeTransaction of nodeTransactions) {
+ if (nodeTransaction.id === transaction.id) {
+ continue;
+ }
+
+ if (nodeTransaction.data) {
+ ydoc.applyUpdate(nodeTransaction.data);
+ }
+ }
+
+ const attributes = ydoc.getAttributes<NodeAttributes>();
+ const text = extractNodeText(transaction.nodeId, attributes);
+
+ const updatedNode = await this.workspace.database
+ .transaction()
+ .execute(async (trx) => {
+ const updatedNode = await trx
+ .updateTable('nodes')
+ .returningAll()
+ .set({
+ attributes: JSON.stringify(attributes),
+ })
+ .where('id', '=', transaction.nodeId)
+ .where('local_revision', '=', node.local_revision)
+ .executeTakeFirst();
+
+ if (!updatedNode) {
+ return undefined;
+ }
+
+ if (text !== undefined) {
+ await trx
+ .deleteFrom('texts')
+ .where('id', '=', transaction.nodeId)
+ .execute();
+ }
+
+ if (text) {
+ await trx
+ .insertInto('texts')
+ .values({
+ id: transaction.nodeId,
+ name: text.name,
+ text: text.text,
+ })
+ .execute();
+ }
+
+ await trx
+ .deleteFrom('node_transactions')
+ .where('id', '=', transaction.id)
+ .execute();
+ });
+
+ if (updatedNode) {
+ eventBus.publish({
+ type: 'node_updated',
+ accountId: this.workspace.accountId,
+ workspaceId: this.workspace.id,
+ node: mapNode(updatedNode),
+ });
+
+ return true;
+ }
+
+ return false;
+ }
+
+ public async revertNodeDelete(mutation: DeleteNodeMutationData) {
+ const tombstone = await this.workspace.database
+ .selectFrom('tombstones')
+ .selectAll()
+ .where('id', '=', mutation.id)
+ .executeTakeFirst();
+
+ if (!tombstone) {
+ return;
+ }
+
+ const state = await this.workspace.database
+ .selectFrom('node_states')
+ .selectAll()
+ .where('id', '=', mutation.id)
+ .executeTakeFirst();
+
+ if (!state) {
+ return;
+ }
+
+ const nodeTransactions = await this.workspace.database
+ .selectFrom('node_transactions')
+ .selectAll()
+ .where('node_id', '=', mutation.id)
+ .orderBy('id', 'asc')
+ .execute();
+
+ const ydoc = new YDoc(state.state);
+ for (const nodeTransaction of nodeTransactions) {
+ ydoc.applyUpdate(nodeTransaction.data);
+ }
+
+ const attributes = ydoc.getAttributes<NodeAttributes>();
+ const text = extractNodeText(mutation.id, attributes);
+
+ const deletedNode = JSON.parse(tombstone.data) as SelectNode;
+ const createdNode = await this.workspace.database
+ .transaction()
+ .execute(async (trx) => {
+ const createdNode = await trx
+ .insertInto('nodes')
+ .returningAll()
+ .values({
+ id: deletedNode.id,
+ root_id: deletedNode.root_id,
+ created_at: deletedNode.created_at,
+ created_by: deletedNode.created_by,
+ attributes: JSON.stringify(attributes),
+ updated_at: deletedNode.updated_at,
+ updated_by: deletedNode.updated_by,
+ local_revision: deletedNode.local_revision,
+ server_revision: deletedNode.server_revision,
+ })
+ .onConflict((b) => b.doNothing())
+ .executeTakeFirst();
+
+ if (!createdNode) {
+ return undefined;
+ }
+
+ await trx
+ .deleteFrom('tombstones')
+ .where('id', '=', mutation.id)
+ .execute();
+
+ if (text !== undefined) {
+ await trx.deleteFrom('texts').where('id', '=', mutation.id).execute();
+ }
+
+ if (text) {
+ await trx
+ .insertInto('texts')
+ .values({
+ id: mutation.id,
+ name: text.name,
+ text: text.text,
+ })
+ .execute();
+ }
+ });
+
+ if (createdNode) {
+ eventBus.publish({
+ type: 'node_created',
+ accountId: this.workspace.accountId,
+ workspaceId: this.workspace.id,
+ node: mapNode(createdNode),
+ });
+
+ return true;
+ }
+
+ return false;
+ }
+}
diff --git a/apps/desktop/src/main/services/workspaces/radar-service.ts b/apps/desktop/src/main/services/workspaces/radar-service.ts
index 92fd94d2..42a62990 100644
--- a/apps/desktop/src/main/services/workspaces/radar-service.ts
+++ b/apps/desktop/src/main/services/workspaces/radar-service.ts
@@ -10,9 +10,9 @@ import {
import {
CollaborationCreatedEvent,
CollaborationDeletedEvent,
- MessageCreatedEvent,
- MessageDeletedEvent,
- MessageInteractionUpdatedEvent,
+ NodeCreatedEvent,
+ NodeDeletedEvent,
+ NodeInteractionUpdatedEvent,
Event,
} from '@/shared/types/events';
import { eventBus } from '@/shared/lib/event-bus';
@@ -90,7 +90,7 @@ export class RadarService {
.execute();
for (const collaboration of collaborations) {
- this.collaborations.set(collaboration.entry_id, collaboration);
+ this.collaborations.set(collaboration.node_id, collaboration);
}
if (this.collaborations.size === 0) {
@@ -98,33 +98,33 @@ export class RadarService {
}
const unreadMessagesRows = await this.workspace.database
- .selectFrom('messages as message')
- .leftJoin('message_interactions as message_interactions', (join) =>
+ .selectFrom('nodes as node')
+ .leftJoin('node_interactions as node_interactions', (join) =>
join
- .onRef('message.id', '=', 'message_interactions.message_id')
- .on(
- 'message_interactions.collaborator_id',
- '=',
- this.workspace.userId
- )
+ .onRef('node.id', '=', 'node_interactions.node_id')
+ .on('node_interactions.collaborator_id', '=', this.workspace.userId)
)
- .innerJoin('entry_interactions as entry_interactions', (join) =>
+ .innerJoin('node_interactions as parent_interactions', (join) =>
join
- .onRef('message.entry_id', '=', 'entry_interactions.entry_id')
- .on('entry_interactions.collaborator_id', '=', this.workspace.userId)
+ .onRef('node.parent_id', '=', 'parent_interactions.node_id')
+ .on('parent_interactions.collaborator_id', '=', this.workspace.userId)
)
- .select(['message.id as message_id', 'message.entry_id as entry_id'])
- .where('message.created_by', '!=', this.workspace.userId)
- .where('message_interactions.last_seen_at', 'is', null)
- .where('entry_interactions.last_seen_at', 'is not', null)
- .whereRef('message.created_at', '>=', 'entry_interactions.first_seen_at')
+ .select(['node.id as node_id', 'node.parent_id as parent_id'])
+ .where('node.created_by', '!=', this.workspace.userId)
+ .where('node_interactions.last_seen_at', 'is', null)
+ .where('parent_interactions.last_seen_at', 'is not', null)
+ .whereRef('node.created_at', '>=', 'parent_interactions.first_seen_at')
.execute();
for (const unreadMessageRow of unreadMessagesRows) {
- this.unreadMessages.set(unreadMessageRow.message_id, {
- messageId: unreadMessageRow.message_id,
- parentId: unreadMessageRow.entry_id,
- parentIdType: getIdType(unreadMessageRow.entry_id),
+ if (!unreadMessageRow.parent_id) {
+ continue;
+ }
+
+ this.unreadMessages.set(unreadMessageRow.node_id, {
+ messageId: unreadMessageRow.node_id,
+ parentId: unreadMessageRow.parent_id,
+ parentIdType: getIdType(unreadMessageRow.parent_id),
});
}
}
@@ -134,12 +134,12 @@ export class RadarService {
}
private async handleEvent(event: Event) {
- if (event.type === 'message_interaction_updated') {
- await this.handleMessageInteractionUpdated(event);
- } else if (event.type === 'message_created') {
- await this.handleMessageCreated(event);
- } else if (event.type === 'message_deleted') {
- await this.handleMessageDeleted(event);
+ if (event.type === 'node_interaction_updated') {
+ await this.handleNodeInteractionUpdated(event);
+ } else if (event.type === 'node_created') {
+ await this.handleNodeCreated(event);
+ } else if (event.type === 'node_deleted') {
+ await this.handleNodeDeleted(event);
} else if (event.type === 'collaboration_created') {
await this.handleCollaborationCreated(event);
} else if (event.type === 'collaboration_deleted') {
@@ -147,10 +147,10 @@ export class RadarService {
}
}
- private async handleMessageInteractionUpdated(
- event: MessageInteractionUpdatedEvent
+ private async handleNodeInteractionUpdated(
+ event: NodeInteractionUpdatedEvent
): Promise<void> {
- const interaction = event.messageInteraction;
+ const interaction = event.nodeInteraction;
if (
event.accountId !== this.workspace.accountId ||
event.workspaceId !== this.workspace.id ||
@@ -160,9 +160,9 @@ export class RadarService {
}
if (interaction.lastSeenAt) {
- const unreadMessage = this.unreadMessages.get(interaction.messageId);
+ const unreadMessage = this.unreadMessages.get(interaction.nodeId);
if (unreadMessage) {
- this.unreadMessages.delete(interaction.messageId);
+ this.unreadMessages.delete(interaction.nodeId);
eventBus.publish({
type: 'radar_data_updated',
});
@@ -171,10 +171,12 @@ export class RadarService {
}
}
- private async handleMessageCreated(
- event: MessageCreatedEvent
- ): Promise<void> {
- const message = event.message;
+ private async handleNodeCreated(event: NodeCreatedEvent): Promise<void> {
+ if (event.node.type !== 'message') {
+ return;
+ }
+
+ const message = event.node;
if (message.createdBy === this.workspace.userId) {
return;
}
@@ -193,9 +195,9 @@ export class RadarService {
}
const messageInteraction = await this.workspace.database
- .selectFrom('message_interactions')
+ .selectFrom('node_interactions')
.selectAll()
- .where('message_id', '=', message.id)
+ .where('node_id', '=', message.id)
.where('collaborator_id', '=', this.workspace.userId)
.executeTakeFirst();
@@ -214,10 +216,8 @@ export class RadarService {
});
}
- private async handleMessageDeleted(
- event: MessageDeletedEvent
- ): Promise<void> {
- const message = event.message;
+ private async handleNodeDeleted(event: NodeDeletedEvent): Promise<void> {
+ const message = event.node;
if (message.createdBy === this.workspace.userId) {
return;
}
@@ -238,19 +238,19 @@ export class RadarService {
const collaboration = await this.workspace.database
.selectFrom('collaborations')
.selectAll()
- .where('entry_id', '=', event.entryId)
+ .where('node_id', '=', event.nodeId)
.executeTakeFirst();
if (!collaboration) {
return;
}
- this.collaborations.set(event.entryId, collaboration);
+ this.collaborations.set(event.nodeId, collaboration);
}
private async handleCollaborationDeleted(
event: CollaborationDeletedEvent
): Promise<void> {
- this.collaborations.delete(event.entryId);
+ this.collaborations.delete(event.nodeId);
}
}
diff --git a/apps/desktop/src/main/services/workspaces/sync-service.ts b/apps/desktop/src/main/services/workspaces/sync-service.ts
index 0791950d..9d161e5d 100644
--- a/apps/desktop/src/main/services/workspaces/sync-service.ts
+++ b/apps/desktop/src/main/services/workspaces/sync-service.ts
@@ -2,26 +2,18 @@ import {
createDebugger,
SyncCollaborationsInput,
SyncUsersInput,
- SyncEntryTransactionsInput,
- SyncEntryInteractionsInput,
- SyncMessagesInput,
- SyncMessageInteractionsInput,
- SyncMessageReactionsInput,
+ SyncNodesInput,
+ SyncNodeInteractionsInput,
+ SyncNodeReactionsInput,
SyncFilesInput,
- SyncFileInteractionsInput,
- SyncFileTombstonesInput,
- SyncMessageTombstonesInput,
- SyncEntryTransactionData,
- SyncMessageTombstoneData,
- SyncMessageInteractionData,
- SyncEntryInteractionData,
- SyncMessageData,
- SyncMessageReactionData,
- SyncFileInteractionData,
- SyncFileTombstoneData,
- SyncFileData,
+ SyncNodeTombstonesInput,
+ SyncNodeInteractionData,
+ SyncNodeReactionData,
+ SyncNodeTombstoneData,
+ SyncNodeData,
SyncUserData,
SyncCollaborationData,
+ SyncFileData,
} from '@colanode/core';
import { Event } from '@/shared/types/events';
@@ -30,29 +22,21 @@ import { Synchronizer } from '@/main/services/workspaces/synchronizer';
import { eventBus } from '@/shared/lib/event-bus';
interface RootSynchronizers {
- entryTransactions: Synchronizer<SyncEntryTransactionsInput>;
- entryInteractions: Synchronizer<SyncEntryInteractionsInput>;
- messages: Synchronizer<SyncMessagesInput>;
- messageInteractions: Synchronizer<SyncMessageInteractionsInput>;
- messageReactions: Synchronizer<SyncMessageReactionsInput>;
- messageTombstones: Synchronizer<SyncMessageTombstonesInput>;
+ nodes: Synchronizer<SyncNodesInput>;
+ nodeInteractions: Synchronizer<SyncNodeInteractionsInput>;
+ nodeReactions: Synchronizer<SyncNodeReactionsInput>;
+ nodeTombstones: Synchronizer<SyncNodeTombstonesInput>;
files: Synchronizer<SyncFilesInput>;
- fileInteractions: Synchronizer<SyncFileInteractionsInput>;
- fileTombstones: Synchronizer<SyncFileTombstonesInput>;
}
type SyncHandlers = {
users: (data: SyncUserData) => Promise<void>;
collaborations: (data: SyncCollaborationData) => Promise<void>;
- entry_transactions: (data: SyncEntryTransactionData) => Promise<void>;
- entry_interactions: (data: SyncEntryInteractionData) => Promise<void>;
- messages: (data: SyncMessageData) => Promise<void>;
- message_interactions: (data: SyncMessageInteractionData) => Promise<void>;
- message_reactions: (data: SyncMessageReactionData) => Promise<void>;
- message_tombstones: (data: SyncMessageTombstoneData) => Promise<void>;
+ nodes: (data: SyncNodeData) => Promise<void>;
+ nodeInteractions: (data: SyncNodeInteractionData) => Promise<void>;
+ nodeReactions: (data: SyncNodeReactionData) => Promise<void>;
+ nodeTombstones: (data: SyncNodeTombstoneData) => Promise<void>;
files: (data: SyncFileData) => Promise<void>;
- file_interactions: (data: SyncFileInteractionData) => Promise<void>;
- file_tombstones: (data: SyncFileTombstoneData) => Promise<void>;
};
export class SyncService {
@@ -77,34 +61,18 @@ export class SyncService {
this.workspace.collaborations.syncServerCollaboration.bind(
this.workspace.collaborations
),
- entry_transactions: this.workspace.entries.applyServerTransaction.bind(
- this.workspace.entries
- ),
- entry_interactions:
- this.workspace.entries.syncServerEntryInteraction.bind(
- this.workspace.entries
+ nodes: this.workspace.nodes.syncServerNode.bind(this.workspace.nodes),
+ nodeInteractions:
+ this.workspace.nodeInteractions.syncServerNodeInteraction.bind(
+ this.workspace.nodes
),
- messages: this.workspace.messages.syncServerMessage.bind(
- this.workspace.messages
+ nodeReactions: this.workspace.nodeReactions.syncServerNodeReaction.bind(
+ this.workspace.nodes
),
- message_interactions:
- this.workspace.messages.syncServerMessageInteraction.bind(
- this.workspace.messages
- ),
- message_reactions: this.workspace.messages.syncServerMessageReaction.bind(
- this.workspace.messages
+ nodeTombstones: this.workspace.nodes.syncServerNodeDelete.bind(
+ this.workspace.nodes
),
- message_tombstones:
- this.workspace.messages.syncServerMessageTombstone.bind(
- this.workspace.messages
- ),
files: this.workspace.files.syncServerFile.bind(this.workspace.files),
- file_interactions: this.workspace.files.syncServerFileInteraction.bind(
- this.workspace.files
- ),
- file_tombstones: this.workspace.files.syncServerFileTombstone.bind(
- this.workspace.files
- ),
};
eventBus.subscribe(this.handleEvent.bind(this));
}
@@ -115,13 +83,13 @@ export class SyncService {
event.accountId === this.workspace.accountId &&
event.workspaceId === this.workspace.id
) {
- this.initRootSynchronizers(event.entryId);
+ this.initRootSynchronizers(event.nodeId);
} else if (
event.type === 'collaboration_deleted' &&
event.accountId === this.workspace.accountId &&
event.workspaceId === this.workspace.id
) {
- this.removeRootSynchronizers(event.entryId);
+ this.removeRootSynchronizers(event.nodeId);
}
}
@@ -156,7 +124,7 @@ export class SyncService {
.execute();
for (const collaboration of collaborations) {
- await this.initRootSynchronizers(collaboration.entry_id);
+ await this.initRootSynchronizers(collaboration.node_id);
}
}
@@ -170,15 +138,11 @@ export class SyncService {
}
private destroyRootSynchronizers(rootSynchronizers: RootSynchronizers): void {
- rootSynchronizers.entryTransactions.destroy();
- rootSynchronizers.entryInteractions.destroy();
- rootSynchronizers.messages.destroy();
- rootSynchronizers.messageInteractions.destroy();
- rootSynchronizers.messageReactions.destroy();
- rootSynchronizers.messageTombstones.destroy();
+ rootSynchronizers.nodes.destroy();
+ rootSynchronizers.nodeInteractions.destroy();
+ rootSynchronizers.nodeReactions.destroy();
+ rootSynchronizers.nodeTombstones.destroy();
rootSynchronizers.files.destroy();
- rootSynchronizers.fileInteractions.destroy();
- rootSynchronizers.fileTombstones.destroy();
}
private async initRootSynchronizers(rootId: string): Promise<void> {
@@ -191,41 +155,29 @@ export class SyncService {
);
const rootSynchronizers = {
- entryTransactions: new Synchronizer(
+ nodes: new Synchronizer(
this.workspace,
- { type: 'entry_transactions', rootId },
- `${rootId}_entry_transactions`,
- this.syncHandlers.entry_transactions
+ { type: 'nodes', rootId },
+ `${rootId}_nodes`,
+ this.syncHandlers.nodes
),
- entryInteractions: new Synchronizer(
+ nodeInteractions: new Synchronizer(
this.workspace,
- { type: 'entry_interactions', rootId },
- `${rootId}_entry_interactions`,
- this.syncHandlers.entry_interactions
+ { type: 'node_interactions', rootId },
+ `${rootId}_node_interactions`,
+ this.syncHandlers.nodeInteractions
),
- messages: new Synchronizer(
+ nodeReactions: new Synchronizer(
this.workspace,
- { type: 'messages', rootId },
- `${rootId}_messages`,
- this.syncHandlers.messages
+ { type: 'node_reactions', rootId },
+ `${rootId}_node_reactions`,
+ this.syncHandlers.nodeReactions
),
- messageInteractions: new Synchronizer(
+ nodeTombstones: new Synchronizer(
this.workspace,
- { type: 'message_interactions', rootId },
- `${rootId}_message_interactions`,
- this.syncHandlers.message_interactions
- ),
- messageReactions: new Synchronizer(
- this.workspace,
- { type: 'message_reactions', rootId },
- `${rootId}_message_reactions`,
- this.syncHandlers.message_reactions
- ),
- messageTombstones: new Synchronizer(
- this.workspace,
- { type: 'message_tombstones', rootId },
- `${rootId}_message_tombstones`,
- this.syncHandlers.message_tombstones
+ { type: 'node_tombstones', rootId },
+ `${rootId}_node_tombstones`,
+ this.syncHandlers.nodeTombstones
),
files: new Synchronizer(
this.workspace,
@@ -233,18 +185,6 @@ export class SyncService {
`${rootId}_files`,
this.syncHandlers.files
),
- fileInteractions: new Synchronizer(
- this.workspace,
- { type: 'file_interactions', rootId },
- `${rootId}_file_interactions`,
- this.syncHandlers.file_interactions
- ),
- fileTombstones: new Synchronizer(
- this.workspace,
- { type: 'file_tombstones', rootId },
- `${rootId}_file_tombstones`,
- this.syncHandlers.file_tombstones
- ),
};
this.rootSynchronizers.set(rootId, rootSynchronizers);
diff --git a/apps/desktop/src/main/services/workspaces/user-service.ts b/apps/desktop/src/main/services/workspaces/user-service.ts
index ca907600..67b9ab29 100644
--- a/apps/desktop/src/main/services/workspaces/user-service.ts
+++ b/apps/desktop/src/main/services/workspaces/user-service.ts
@@ -1,4 +1,4 @@
-import { createDebugger, SyncUserData, UserStatus } from '@colanode/core';
+import { createDebugger, SyncUserData } from '@colanode/core';
import { mapUser } from '@/main/lib/mappers';
import { eventBus } from '@/shared/lib/event-bus';
@@ -26,7 +26,7 @@ export class UserService {
name: user.name,
avatar: user.avatar,
role: user.role,
- version: BigInt(user.version),
+ revision: BigInt(user.revision),
created_at: user.createdAt,
updated_at: user.updatedAt,
status: user.status,
@@ -43,10 +43,10 @@ export class UserService {
custom_avatar: user.customAvatar,
role: user.role,
status: user.status,
- version: BigInt(user.version),
+ revision: BigInt(user.revision),
updated_at: user.updatedAt,
})
- .where('version', '<', BigInt(user.version))
+ .where('revision', '<', BigInt(user.revision))
)
.executeTakeFirst();
diff --git a/apps/desktop/src/main/services/workspaces/workspace-service.ts b/apps/desktop/src/main/services/workspaces/workspace-service.ts
index 0735a968..199ff092 100644
--- a/apps/desktop/src/main/services/workspaces/workspace-service.ts
+++ b/apps/desktop/src/main/services/workspaces/workspace-service.ts
@@ -11,8 +11,9 @@ import {
} from '@/main/databases/workspace';
import { getWorkspaceDirectoryPath } from '@/main/lib/utils';
import { AccountService } from '@/main/services/accounts/account-service';
-import { EntryService } from '@/main/services/workspaces/entry-service';
-import { MessageService } from '@/main/services/workspaces/message-service';
+import { NodeService } from '@/main/services/workspaces/node-service';
+import { NodeInteractionService } from '@/main/services/workspaces/node-interaction-service';
+import { NodeReactionService } from '@/main/services/workspaces/node-reaction-service';
import { FileService } from '@/main/services/workspaces/file-service';
import { Workspace } from '@/shared/types/workspaces';
import { MutationService } from '@/main/services/workspaces/mutation-service';
@@ -28,8 +29,9 @@ export class WorkspaceService {
public readonly database: Kysely<WorkspaceDatabaseSchema>;
public readonly account: AccountService;
- public readonly entries: EntryService;
- public readonly messages: MessageService;
+ public readonly nodes: NodeService;
+ public readonly nodeInteractions: NodeInteractionService;
+ public readonly nodeReactions: NodeReactionService;
public readonly files: FileService;
public readonly mutations: MutationService;
public readonly users: UserService;
@@ -62,8 +64,9 @@ export class WorkspaceService {
}),
});
- this.entries = new EntryService(this);
- this.messages = new MessageService(this);
+ this.nodes = new NodeService(this);
+ this.nodeInteractions = new NodeInteractionService(this);
+ this.nodeReactions = new NodeReactionService(this);
this.files = new FileService(this);
this.mutations = new MutationService(this);
this.users = new UserService(this);
diff --git a/apps/desktop/src/renderer/components/channels/channel-breadcrumb-item.tsx b/apps/desktop/src/renderer/components/channels/channel-breadcrumb-item.tsx
index 97887fec..c9589ec3 100644
--- a/apps/desktop/src/renderer/components/channels/channel-breadcrumb-item.tsx
+++ b/apps/desktop/src/renderer/components/channels/channel-breadcrumb-item.tsx
@@ -1,28 +1,13 @@
-import { ChannelEntry } from '@colanode/core';
-
import { Avatar } from '@/renderer/components/avatars/avatar';
-import { useQuery } from '@/renderer/hooks/use-query';
-import { useWorkspace } from '@/renderer/contexts/workspace';
+import { LocalChannelNode } from '@/shared/types/nodes';
interface ChannelBreadcrumbItemProps {
- id: string;
+ channel: LocalChannelNode;
}
-export const ChannelBreadcrumbItem = ({ id }: ChannelBreadcrumbItemProps) => {
- const workspace = useWorkspace();
- const { data } = useQuery({
- type: 'entry_get',
- entryId: id,
- accountId: workspace.accountId,
- workspaceId: workspace.id,
- });
-
- if (!data) {
- return null;
- }
-
- const channel = data as ChannelEntry;
-
+export const ChannelBreadcrumbItem = ({
+ channel,
+}: ChannelBreadcrumbItemProps) => {
return (
<div className="flex items-center space-x-2">
<Avatar
diff --git a/apps/desktop/src/renderer/components/channels/channel-container-tab.tsx b/apps/desktop/src/renderer/components/channels/channel-container-tab.tsx
index 26e936b6..00c3afcd 100644
--- a/apps/desktop/src/renderer/components/channels/channel-container-tab.tsx
+++ b/apps/desktop/src/renderer/components/channels/channel-container-tab.tsx
@@ -1,10 +1,9 @@
-import { ChannelEntry } from '@colanode/core';
-
import { Avatar } from '@/renderer/components/avatars/avatar';
import { useWorkspace } from '@/renderer/contexts/workspace';
import { useQuery } from '@/renderer/hooks/use-query';
import { useRadar } from '@/renderer/contexts/radar';
import { NotificationBadge } from '@/renderer/components/ui/notification-badge';
+import { LocalChannelNode } from '@/shared/types/nodes';
interface ChannelContainerTabProps {
channelId: string;
@@ -19,8 +18,8 @@ export const ChannelContainerTab = ({
const radar = useRadar();
const { data, isPending } = useQuery({
- type: 'entry_get',
- entryId: channelId,
+ type: 'node_get',
+ nodeId: channelId,
accountId: workspace.accountId,
workspaceId: workspace.id,
});
@@ -29,7 +28,7 @@ export const ChannelContainerTab = ({
return <p className="text-sm text-muted-foreground">Loading...</p>;
}
- const channel = data as ChannelEntry;
+ const channel = data as LocalChannelNode;
if (!channel) {
return <p className="text-sm text-muted-foreground">Not found</p>;
}
diff --git a/apps/desktop/src/renderer/components/channels/channel-container.tsx b/apps/desktop/src/renderer/components/channels/channel-container.tsx
index 29b070e0..7a140447 100644
--- a/apps/desktop/src/renderer/components/channels/channel-container.tsx
+++ b/apps/desktop/src/renderer/components/channels/channel-container.tsx
@@ -1,5 +1,4 @@
-import { ChannelEntry } from '@colanode/core';
-
+import { LocalChannelNode } from '@/shared/types/nodes';
import { ChannelNotFound } from '@/renderer/components/channels/channel-not-found';
import {
Container,
@@ -8,29 +7,29 @@ import {
ContainerSettings,
} from '@/renderer/components/ui/container';
import { ContainerBreadcrumb } from '@/renderer/components/layouts/containers/container-breadrumb';
-import { useEntryContainer } from '@/renderer/hooks/use-entry-container';
+import { useNodeContainer } from '@/renderer/hooks/use-node-container';
import { ChannelSettings } from '@/renderer/components/channels/channel-settings';
import { Conversation } from '@/renderer/components/messages/conversation';
-import { useEntryRadar } from '@/renderer/hooks/use-entry-radar';
+import { useNodeRadar } from '@/renderer/hooks/use-node-radar';
interface ChannelContainerProps {
channelId: string;
}
export const ChannelContainer = ({ channelId }: ChannelContainerProps) => {
- const data = useEntryContainer<ChannelEntry>(channelId);
+ const data = useNodeContainer<LocalChannelNode>(channelId);
- useEntryRadar(data.entry);
+ useNodeRadar(data.node);
if (data.isPending) {
return null;
}
- if (!data.entry) {
+ if (!data.node) {
return <ChannelNotFound />;
}
- const { entry: channel, role } = data;
+ const { node: channel, role } = data;
return (
<Container>
diff --git a/apps/desktop/src/renderer/components/channels/channel-settings.tsx b/apps/desktop/src/renderer/components/channels/channel-settings.tsx
index c9fea397..b93e5c1f 100644
--- a/apps/desktop/src/renderer/components/channels/channel-settings.tsx
+++ b/apps/desktop/src/renderer/components/channels/channel-settings.tsx
@@ -1,10 +1,10 @@
-import { ChannelEntry, EntryRole, hasEntryRole } from '@colanode/core';
+import { NodeRole, hasNodeRole } from '@colanode/core';
import { Copy, Image, LetterText, Settings, Trash2 } from 'lucide-react';
import React from 'react';
import { ChannelDeleteDialog } from '@/renderer/components/channels/channel-delete-dialog';
import { ChannelUpdateDialog } from '@/renderer/components/channels/channel-update-dialog';
-import { EntryCollaboratorAudit } from '@/renderer/components/collaborators/entry-collaborator-audit';
+import { NodeCollaboratorAudit } from '@/renderer/components/collaborators/node-collaborator-audit';
import {
DropdownMenu,
DropdownMenuContent,
@@ -13,18 +13,19 @@ import {
DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@/renderer/components/ui/dropdown-menu';
+import { LocalChannelNode } from '@/shared/types/nodes';
interface ChannelSettingsProps {
- channel: ChannelEntry;
- role: EntryRole;
+ channel: LocalChannelNode;
+ role: NodeRole;
}
export const ChannelSettings = ({ channel, role }: ChannelSettingsProps) => {
const [showUpdateDialog, setShowUpdateDialog] = React.useState(false);
const [showDeleteDialog, setShowDeleteModal] = React.useState(false);
- const canEdit = hasEntryRole(role, 'editor');
- const canDelete = hasEntryRole(role, 'editor');
+ const canEdit = hasNodeRole(role, 'editor');
+ const canDelete = hasNodeRole(role, 'editor');
return (
<React.Fragment>
@@ -84,7 +85,7 @@ export const ChannelSettings = ({ channel, role }: ChannelSettingsProps) => {
<DropdownMenuSeparator />
<DropdownMenuLabel>Created by</DropdownMenuLabel>
<DropdownMenuItem>
- <EntryCollaboratorAudit
+ <NodeCollaboratorAudit
collaboratorId={channel.createdBy}
date={channel.createdAt}
/>
@@ -94,7 +95,7 @@ export const ChannelSettings = ({ channel, role }: ChannelSettingsProps) => {
<DropdownMenuSeparator />
<DropdownMenuLabel>Last updated by</DropdownMenuLabel>
<DropdownMenuItem>
- <EntryCollaboratorAudit
+ <NodeCollaboratorAudit
collaboratorId={channel.updatedBy}
date={channel.updatedAt}
/>
diff --git a/apps/desktop/src/renderer/components/channels/channel-sidebar-item.tsx b/apps/desktop/src/renderer/components/channels/channel-sidebar-item.tsx
index d854b845..f968b4ab 100644
--- a/apps/desktop/src/renderer/components/channels/channel-sidebar-item.tsx
+++ b/apps/desktop/src/renderer/components/channels/channel-sidebar-item.tsx
@@ -1,4 +1,3 @@
-import { ChannelEntry } from '@colanode/core';
import { InView } from 'react-intersection-observer';
import { Avatar } from '@/renderer/components/avatars/avatar';
@@ -7,9 +6,10 @@ import { useRadar } from '@/renderer/contexts/radar';
import { useWorkspace } from '@/renderer/contexts/workspace';
import { useLayout } from '@/renderer/contexts/layout';
import { cn } from '@/shared/lib/utils';
+import { LocalChannelNode } from '@/shared/types/nodes';
interface ChannelSidebarItemProps {
- channel: ChannelEntry;
+ channel: LocalChannelNode;
}
export const ChannelSidebarItem = ({ channel }: ChannelSidebarItemProps) => {
@@ -31,7 +31,7 @@ export const ChannelSidebarItem = ({ channel }: ChannelSidebarItemProps) => {
rootMargin="20px"
onChange={(inView) => {
if (inView) {
- radar.markEntryAsSeen(workspace.accountId, workspace.id, channel.id);
+ radar.markNodeAsSeen(workspace.accountId, workspace.id, channel.id);
}
}}
className={cn(
diff --git a/apps/desktop/src/renderer/components/channels/channel-update-dialog.tsx b/apps/desktop/src/renderer/components/channels/channel-update-dialog.tsx
index d033a1f1..935b1a4b 100644
--- a/apps/desktop/src/renderer/components/channels/channel-update-dialog.tsx
+++ b/apps/desktop/src/renderer/components/channels/channel-update-dialog.tsx
@@ -1,5 +1,6 @@
-import { ChannelEntry, EntryRole, hasEntryRole } from '@colanode/core';
+import { NodeRole, hasNodeRole } from '@colanode/core';
+import { LocalChannelNode } from '@/shared/types/nodes';
import { ChannelForm } from '@/renderer/components/channels/channel-form';
import {
Dialog,
@@ -13,8 +14,8 @@ import { useMutation } from '@/renderer/hooks/use-mutation';
import { toast } from '@/renderer/hooks/use-toast';
interface ChannelUpdateDialogProps {
- channel: ChannelEntry;
- role: EntryRole;
+ channel: LocalChannelNode;
+ role: NodeRole;
open: boolean;
onOpenChange: (open: boolean) => void;
}
@@ -27,7 +28,7 @@ export const ChannelUpdateDialog = ({
}: ChannelUpdateDialogProps) => {
const workspace = useWorkspace();
const { mutate, isPending } = useMutation();
- const canEdit = hasEntryRole(role, 'editor');
+ const canEdit = hasNodeRole(role, 'editor');
return (
<Dialog open={open} onOpenChange={onOpenChange}>
diff --git a/apps/desktop/src/renderer/components/chats/chat-breadcrumb-item.tsx b/apps/desktop/src/renderer/components/chats/chat-breadcrumb-item.tsx
index 672d1e01..d606c284 100644
--- a/apps/desktop/src/renderer/components/chats/chat-breadcrumb-item.tsx
+++ b/apps/desktop/src/renderer/components/chats/chat-breadcrumb-item.tsx
@@ -1,21 +1,15 @@
import { Avatar } from '@/renderer/components/avatars/avatar';
import { useWorkspace } from '@/renderer/contexts/workspace';
import { useQuery } from '@/renderer/hooks/use-query';
+import { LocalChatNode } from '@/shared/types/nodes';
interface ChatBreadcrumbItemProps {
- id: string;
+ chat: LocalChatNode;
}
-export const ChatBreadcrumbItem = ({ id }: ChatBreadcrumbItemProps) => {
+export const ChatBreadcrumbItem = ({ chat }: ChatBreadcrumbItemProps) => {
const workspace = useWorkspace();
- const { data: chat } = useQuery({
- type: 'entry_get',
- entryId: id,
- accountId: workspace.accountId,
- workspaceId: workspace.id,
- });
-
const userId =
chat && chat.type === 'chat'
? (Object.keys(chat.attributes.collaborators).find(
@@ -30,7 +24,7 @@ export const ChatBreadcrumbItem = ({ id }: ChatBreadcrumbItemProps) => {
userId,
});
- if (!chat || !user) {
+ if (!user) {
return null;
}
diff --git a/apps/desktop/src/renderer/components/chats/chat-container-tab.tsx b/apps/desktop/src/renderer/components/chats/chat-container-tab.tsx
index 11084d86..ab6f36eb 100644
--- a/apps/desktop/src/renderer/components/chats/chat-container-tab.tsx
+++ b/apps/desktop/src/renderer/components/chats/chat-container-tab.tsx
@@ -17,8 +17,8 @@ export const ChatContainerTab = ({
const radar = useRadar();
const { data: chat, isPending: isChatPending } = useQuery({
- type: 'entry_get',
- entryId: chatId,
+ type: 'node_get',
+ nodeId: chatId,
accountId: workspace.accountId,
workspaceId: workspace.id,
});
diff --git a/apps/desktop/src/renderer/components/chats/chat-container.tsx b/apps/desktop/src/renderer/components/chats/chat-container.tsx
index 9462c4ce..d26dc4d7 100644
--- a/apps/desktop/src/renderer/components/chats/chat-container.tsx
+++ b/apps/desktop/src/renderer/components/chats/chat-container.tsx
@@ -1,5 +1,3 @@
-import { ChatEntry } from '@colanode/core';
-
import {
Container,
ContainerBody,
@@ -8,46 +6,43 @@ import {
} from '@/renderer/components/ui/container';
import { ContainerBreadcrumb } from '@/renderer/components/layouts/containers/container-breadrumb';
import { ChatNotFound } from '@/renderer/components/chats/chat-not-found';
-import { EntryCollaboratorsPopover } from '@/renderer/components/collaborators/entry-collaborators-popover';
+import { NodeCollaboratorsPopover } from '@/renderer/components/collaborators/node-collaborators-popover';
import { Conversation } from '@/renderer/components/messages/conversation';
-import { useEntryRadar } from '@/renderer/hooks/use-entry-radar';
-import { useEntryContainer } from '@/renderer/hooks/use-entry-container';
+import { useNodeRadar } from '@/renderer/hooks/use-node-radar';
+import { useNodeContainer } from '@/renderer/hooks/use-node-container';
+import { LocalChatNode } from '@/shared/types/nodes';
interface ChatContainerProps {
chatId: string;
}
export const ChatContainer = ({ chatId }: ChatContainerProps) => {
- const data = useEntryContainer<ChatEntry>(chatId);
+ const data = useNodeContainer<LocalChatNode>(chatId);
- useEntryRadar(data.entry);
+ useNodeRadar(data.node);
if (data.isPending) {
return null;
}
- if (!data.entry) {
+ if (!data.node) {
return <ChatNotFound />;
}
- const { entry, role } = data;
+ const { node, role } = data;
return (
<Container>
<ContainerHeader>
<ContainerBreadcrumb breadcrumb={data.breadcrumb} />
<ContainerSettings>
- <EntryCollaboratorsPopover
- entry={entry}
- entries={[entry]}
- role={role}
- />
+ <NodeCollaboratorsPopover node={node} nodes={[node]} role={role} />
</ContainerSettings>
</ContainerHeader>
<ContainerBody>
<Conversation
- conversationId={entry.id}
- rootId={entry.rootId}
+ conversationId={node.id}
+ rootId={node.rootId}
role={role}
/>
</ContainerBody>
diff --git a/apps/desktop/src/renderer/components/chats/chat-sidebar-item.tsx b/apps/desktop/src/renderer/components/chats/chat-sidebar-item.tsx
index 74f6a5eb..bc3e4ab6 100644
--- a/apps/desktop/src/renderer/components/chats/chat-sidebar-item.tsx
+++ b/apps/desktop/src/renderer/components/chats/chat-sidebar-item.tsx
@@ -1,6 +1,6 @@
-import { ChatEntry } from '@colanode/core';
import { InView } from 'react-intersection-observer';
+import { LocalChatNode } from '@/shared/types/nodes';
import { Avatar } from '@/renderer/components/avatars/avatar';
import { NotificationBadge } from '@/renderer/components/ui/notification-badge';
import { useRadar } from '@/renderer/contexts/radar';
@@ -10,7 +10,7 @@ import { useLayout } from '@/renderer/contexts/layout';
import { cn } from '@/shared/lib/utils';
interface ChatSidebarItemProps {
- chat: ChatEntry;
+ chat: LocalChatNode;
}
export const ChatSidebarItem = ({ chat }: ChatSidebarItemProps) => {
@@ -48,7 +48,7 @@ export const ChatSidebarItem = ({ chat }: ChatSidebarItemProps) => {
rootMargin="20px"
onChange={(inView) => {
if (inView) {
- radar.markEntryAsSeen(workspace.accountId, workspace.id, chat.id);
+ radar.markNodeAsSeen(workspace.accountId, workspace.id, chat.id);
}
}}
className={cn(
diff --git a/apps/desktop/src/renderer/components/collaborators/entry-collaborator-audit.tsx b/apps/desktop/src/renderer/components/collaborators/node-collaborator-audit.tsx
similarity index 88%
rename from apps/desktop/src/renderer/components/collaborators/entry-collaborator-audit.tsx
rename to apps/desktop/src/renderer/components/collaborators/node-collaborator-audit.tsx
index 45107e12..d1843b91 100644
--- a/apps/desktop/src/renderer/components/collaborators/entry-collaborator-audit.tsx
+++ b/apps/desktop/src/renderer/components/collaborators/node-collaborator-audit.tsx
@@ -4,15 +4,15 @@ import { Avatar } from '@/renderer/components/avatars/avatar';
import { useWorkspace } from '@/renderer/contexts/workspace';
import { useQuery } from '@/renderer/hooks/use-query';
-interface EntryCollaboratorAuditProps {
+interface NodeCollaboratorAuditProps {
collaboratorId: string;
date: string;
}
-export const EntryCollaboratorAudit = ({
+export const NodeCollaboratorAudit = ({
collaboratorId,
date,
-}: EntryCollaboratorAuditProps) => {
+}: NodeCollaboratorAuditProps) => {
const workspace = useWorkspace();
const { data, isPending } = useQuery({
type: 'user_get',
diff --git a/apps/desktop/src/renderer/components/collaborators/entry-collaborator-create.tsx b/apps/desktop/src/renderer/components/collaborators/node-collaborator-create.tsx
similarity index 74%
rename from apps/desktop/src/renderer/components/collaborators/entry-collaborator-create.tsx
rename to apps/desktop/src/renderer/components/collaborators/node-collaborator-create.tsx
index 82d14f1f..8bf6a4db 100644
--- a/apps/desktop/src/renderer/components/collaborators/entry-collaborator-create.tsx
+++ b/apps/desktop/src/renderer/components/collaborators/node-collaborator-create.tsx
@@ -1,39 +1,39 @@
import React from 'react';
-import { EntryRole } from '@colanode/core';
+import { NodeRole } from '@colanode/core';
import { User } from '@/shared/types/users';
-import { EntryCollaboratorRoleDropdown } from '@/renderer/components/collaborators/entry-collaborator-role-dropdown';
-import { EntryCollaboratorSearch } from '@/renderer/components/collaborators/entry-collaborator-search';
+import { NodeCollaboratorRoleDropdown } from '@/renderer/components/collaborators/node-collaborator-role-dropdown';
+import { NodeCollaboratorSearch } from '@/renderer/components/collaborators/node-collaborator-search';
import { Button } from '@/renderer/components/ui/button';
import { Spinner } from '@/renderer/components/ui/spinner';
import { useWorkspace } from '@/renderer/contexts/workspace';
import { useMutation } from '@/renderer/hooks/use-mutation';
import { toast } from '@/renderer/hooks/use-toast';
-interface EntryCollaboratorCreateProps {
- entryId: string;
+interface NodeCollaboratorCreateProps {
+ nodeId: string;
existingCollaborators: string[];
}
-export const EntryCollaboratorCreate = ({
- entryId,
+export const NodeCollaboratorCreate = ({
+ nodeId,
existingCollaborators,
-}: EntryCollaboratorCreateProps) => {
+}: NodeCollaboratorCreateProps) => {
const workspace = useWorkspace();
const { mutate, isPending } = useMutation();
const [users, setUsers] = React.useState<User[]>([]);
- const [role, setRole] = React.useState<EntryRole>('editor');
+ const [role, setRole] = React.useState<NodeRole>('editor');
return (
<div className="flex flex-col gap-2">
- <EntryCollaboratorSearch
+ <NodeCollaboratorSearch
value={users}
onChange={setUsers}
excluded={existingCollaborators}
/>
<div className="flex justify-end space-x-2">
- <EntryCollaboratorRoleDropdown
+ <NodeCollaboratorRoleDropdown
value={role}
onChange={setRole}
canEdit={true}
@@ -50,8 +50,8 @@ export const EntryCollaboratorCreate = ({
mutate({
input: {
- type: 'entry_collaborator_create',
- entryId,
+ type: 'node_collaborator_create',
+ nodeId,
collaboratorIds: users.map((user) => user.id),
role: role,
accountId: workspace.accountId,
diff --git a/apps/desktop/src/renderer/components/collaborators/entry-collaborator-role-dropdown.tsx b/apps/desktop/src/renderer/components/collaborators/node-collaborator-role-dropdown.tsx
similarity index 85%
rename from apps/desktop/src/renderer/components/collaborators/entry-collaborator-role-dropdown.tsx
rename to apps/desktop/src/renderer/components/collaborators/node-collaborator-role-dropdown.tsx
index 939cefe7..7e67847c 100644
--- a/apps/desktop/src/renderer/components/collaborators/entry-collaborator-role-dropdown.tsx
+++ b/apps/desktop/src/renderer/components/collaborators/node-collaborator-role-dropdown.tsx
@@ -1,5 +1,5 @@
import { Check, ChevronDown } from 'lucide-react';
-import { EntryRole } from '@colanode/core';
+import { NodeRole } from '@colanode/core';
import {
DropdownMenu,
@@ -8,14 +8,14 @@ import {
DropdownMenuTrigger,
} from '@/renderer/components/ui/dropdown-menu';
-interface EntryCollaboratorRole {
+interface NodeCollaboratorRole {
name: string;
- value: EntryRole;
+ value: NodeRole;
description: string;
enabled: boolean;
}
-const roles: EntryCollaboratorRole[] = [
+const roles: NodeCollaboratorRole[] = [
{
name: 'Admin',
value: 'admin',
@@ -42,17 +42,17 @@ const roles: EntryCollaboratorRole[] = [
},
];
-interface EntryCollaboratorRoleDropdownProps {
- value: EntryRole;
- onChange: (value: EntryRole) => void;
+interface NodeCollaboratorRoleDropdownProps {
+ value: NodeRole;
+ onChange: (value: NodeRole) => void;
canEdit: boolean;
}
-export const EntryCollaboratorRoleDropdown = ({
+export const NodeCollaboratorRoleDropdown = ({
value,
onChange,
canEdit,
-}: EntryCollaboratorRoleDropdownProps) => {
+}: NodeCollaboratorRoleDropdownProps) => {
const currentRole = roles.find((role) => role.value === value);
if (!canEdit) {
diff --git a/apps/desktop/src/renderer/components/collaborators/entry-collaborator-search.tsx b/apps/desktop/src/renderer/components/collaborators/node-collaborator-search.tsx
similarity index 96%
rename from apps/desktop/src/renderer/components/collaborators/entry-collaborator-search.tsx
rename to apps/desktop/src/renderer/components/collaborators/node-collaborator-search.tsx
index ec19d608..6f70bb0d 100644
--- a/apps/desktop/src/renderer/components/collaborators/entry-collaborator-search.tsx
+++ b/apps/desktop/src/renderer/components/collaborators/node-collaborator-search.tsx
@@ -21,17 +21,17 @@ import {
import { useWorkspace } from '@/renderer/contexts/workspace';
import { useQuery } from '@/renderer/hooks/use-query';
-interface EntryCollaboratorSearchProps {
+interface NodeCollaboratorSearchProps {
excluded: string[];
value: User[];
onChange: (value: User[]) => void;
}
-export const EntryCollaboratorSearch = ({
+export const NodeCollaboratorSearch = ({
excluded,
value,
onChange,
-}: EntryCollaboratorSearchProps) => {
+}: NodeCollaboratorSearchProps) => {
const workspace = useWorkspace();
const [query, setQuery] = React.useState('');
diff --git a/apps/desktop/src/renderer/components/collaborators/entry-collaborator.tsx b/apps/desktop/src/renderer/components/collaborators/node-collaborator.tsx
similarity index 80%
rename from apps/desktop/src/renderer/components/collaborators/entry-collaborator.tsx
rename to apps/desktop/src/renderer/components/collaborators/node-collaborator.tsx
index 1fd25496..4687ea44 100644
--- a/apps/desktop/src/renderer/components/collaborators/entry-collaborator.tsx
+++ b/apps/desktop/src/renderer/components/collaborators/node-collaborator.tsx
@@ -1,28 +1,28 @@
-import { EntryRole } from '@colanode/core';
+import { NodeRole } from '@colanode/core';
import { Trash2 } from 'lucide-react';
import { Avatar } from '@/renderer/components/avatars/avatar';
-import { EntryCollaboratorRoleDropdown } from '@/renderer/components/collaborators/entry-collaborator-role-dropdown';
+import { NodeCollaboratorRoleDropdown } from '@/renderer/components/collaborators/node-collaborator-role-dropdown';
import { useWorkspace } from '@/renderer/contexts/workspace';
import { useMutation } from '@/renderer/hooks/use-mutation';
import { useQuery } from '@/renderer/hooks/use-query';
import { toast } from '@/renderer/hooks/use-toast';
-interface EntryCollaboratorProps {
- entryId: string;
+interface NodeCollaboratorProps {
+ nodeId: string;
collaboratorId: string;
- role: EntryRole;
+ role: NodeRole;
canEdit: boolean;
canRemove: boolean;
}
-export const EntryCollaborator = ({
- entryId,
+export const NodeCollaborator = ({
+ nodeId,
collaboratorId,
role,
canEdit,
canRemove,
-}: EntryCollaboratorProps) => {
+}: NodeCollaboratorProps) => {
const workspace = useWorkspace();
const { mutate } = useMutation();
@@ -47,14 +47,14 @@ export const EntryCollaborator = ({
</div>
</div>
<div className="flex flex-row items-center gap-1">
- <EntryCollaboratorRoleDropdown
+ <NodeCollaboratorRoleDropdown
value={role}
canEdit={canEdit}
onChange={(newRole) => {
mutate({
input: {
- type: 'entry_collaborator_update',
- entryId: entryId,
+ type: 'node_collaborator_update',
+ nodeId: nodeId,
collaboratorId: collaboratorId,
role: newRole,
accountId: workspace.accountId,
@@ -76,8 +76,8 @@ export const EntryCollaborator = ({
onClick={() => {
mutate({
input: {
- type: 'entry_collaborator_delete',
- entryId: entryId,
+ type: 'node_collaborator_delete',
+ nodeId: nodeId,
collaboratorId: collaboratorId,
accountId: workspace.accountId,
workspaceId: workspace.id,
diff --git a/apps/desktop/src/renderer/components/collaborators/entry-collaborators-popover.tsx b/apps/desktop/src/renderer/components/collaborators/node-collaborators-popover.tsx
similarity index 52%
rename from apps/desktop/src/renderer/components/collaborators/entry-collaborators-popover.tsx
rename to apps/desktop/src/renderer/components/collaborators/node-collaborators-popover.tsx
index 0b75cef3..2d66792b 100644
--- a/apps/desktop/src/renderer/components/collaborators/entry-collaborators-popover.tsx
+++ b/apps/desktop/src/renderer/components/collaborators/node-collaborators-popover.tsx
@@ -1,31 +1,31 @@
-import { Entry, EntryRole } from '@colanode/core';
+import { Node, NodeRole } from '@colanode/core';
import { UserRoundPlus } from 'lucide-react';
-import { EntryCollaborators } from '@/renderer/components/collaborators/entry-collaborators';
+import { NodeCollaborators } from '@/renderer/components/collaborators/node-collaborators';
import {
Popover,
PopoverContent,
PopoverTrigger,
} from '@/renderer/components/ui/popover';
-interface EntryCollaboratorsPopoverProps {
- entry: Entry;
- entries: Entry[];
- role: EntryRole;
+interface NodeCollaboratorsPopoverProps {
+ node: Node;
+ nodes: Node[];
+ role: NodeRole;
}
-export const EntryCollaboratorsPopover = ({
- entry,
- entries,
+export const NodeCollaboratorsPopover = ({
+ node,
+ nodes,
role,
-}: EntryCollaboratorsPopoverProps) => {
+}: NodeCollaboratorsPopoverProps) => {
return (
<Popover>
<PopoverTrigger asChild>
<UserRoundPlus className="size-5 cursor-pointer text-muted-foreground hover:text-foreground" />
</PopoverTrigger>
<PopoverContent className="mr-2 max-h-128 w-128 overflow-auto">
- <EntryCollaborators entry={entry} entries={entries} role={role} />
+ <NodeCollaborators node={node} nodes={nodes} role={role} />
</PopoverContent>
</Popover>
);
diff --git a/apps/desktop/src/renderer/components/collaborators/entry-collaborators.tsx b/apps/desktop/src/renderer/components/collaborators/node-collaborators.tsx
similarity index 70%
rename from apps/desktop/src/renderer/components/collaborators/entry-collaborators.tsx
rename to apps/desktop/src/renderer/components/collaborators/node-collaborators.tsx
index 6309350e..6af4c420 100644
--- a/apps/desktop/src/renderer/components/collaborators/entry-collaborators.tsx
+++ b/apps/desktop/src/renderer/components/collaborators/node-collaborators.tsx
@@ -1,45 +1,40 @@
-import {
- Entry,
- EntryRole,
- extractEntryName,
- hasEntryRole,
-} from '@colanode/core';
+import { Node, NodeRole, extractNodeName, hasNodeRole } from '@colanode/core';
import React from 'react';
-import { EntryCollaborator } from '@/renderer/components/collaborators/entry-collaborator';
-import { EntryCollaboratorCreate } from '@/renderer/components/collaborators/entry-collaborator-create';
+import { NodeCollaborator } from '@/renderer/components/collaborators/node-collaborator';
+import { NodeCollaboratorCreate } from '@/renderer/components/collaborators/node-collaborator-create';
import { Separator } from '@/renderer/components/ui/separator';
-import { buildEntryCollaborators } from '@/shared/lib/entries';
+import { buildNodeCollaborators } from '@/shared/lib/nodes';
-interface EntryCollaboratorsProps {
- entry: Entry;
- entries: Entry[];
- role: EntryRole;
+interface NodeCollaboratorsProps {
+ node: Node;
+ nodes: Node[];
+ role: NodeRole;
}
-export const EntryCollaborators = ({
- entry,
- entries,
+export const NodeCollaborators = ({
+ node,
+ nodes,
role,
-}: EntryCollaboratorsProps) => {
- const collaborators = buildEntryCollaborators(entries);
+}: NodeCollaboratorsProps) => {
+ const collaborators = buildNodeCollaborators(nodes);
const directCollaborators = collaborators.filter(
- (collaborator) => collaborator.entryId === entry.id
+ (collaborator) => collaborator.nodeId === node.id
);
const directCollaboratorIds = directCollaborators.map(
(collaborator) => collaborator.collaboratorId
);
- const isAdmin = hasEntryRole(role, 'admin');
- const canAddCollaborator = isAdmin && entry.type === 'space';
- const ancestors = entries.filter((entry) => entry.id !== entry.id);
+ const isAdmin = hasNodeRole(role, 'admin');
+ const canAddCollaborator = isAdmin && node.type === 'space';
+ const ancestors = nodes.filter((node) => node.id !== node.id);
return (
<div className="flex flex-col gap-2">
{canAddCollaborator && (
<React.Fragment>
- <EntryCollaboratorCreate
- entryId={entry.id}
+ <NodeCollaboratorCreate
+ nodeId={node.id}
existingCollaborators={directCollaboratorIds}
/>
<Separator />
@@ -66,9 +61,9 @@ export const EntryCollaborators = ({
}
return (
- <EntryCollaborator
+ <NodeCollaborator
key={collaborator.collaboratorId}
- entryId={entry.id}
+ nodeId={node.id}
collaboratorId={collaborator.collaboratorId}
role={collaborator.role}
canEdit={canEdit}
@@ -86,14 +81,14 @@ export const EntryCollaborators = ({
</div>
{ancestors.map((node) => {
const inheritCollaborators = collaborators.filter(
- (collaborator) => collaborator.entryId === node.id
+ (collaborator) => collaborator.nodeId === node.id
);
if (inheritCollaborators.length === 0) {
return null;
}
- const name = extractEntryName(node.attributes) ?? 'Unknown';
+ const name = extractNodeName(node.attributes) ?? 'Unknown';
return (
<div key={node.id}>
<Separator className="my-3" />
@@ -104,9 +99,9 @@ export const EntryCollaborators = ({
const canEdit = isAdmin && collaborator.role !== 'admin';
return (
- <EntryCollaborator
+ <NodeCollaborator
key={collaborator.collaboratorId}
- entryId={node.id}
+ nodeId={node.id}
collaboratorId={collaborator.collaboratorId}
role={collaborator.role}
canEdit={canEdit}
diff --git a/apps/desktop/src/renderer/components/databases/boards/board-view-column-records.tsx b/apps/desktop/src/renderer/components/databases/boards/board-view-column-records.tsx
index 3d12cb7b..6019dd4e 100644
--- a/apps/desktop/src/renderer/components/databases/boards/board-view-column-records.tsx
+++ b/apps/desktop/src/renderer/components/databases/boards/board-view-column-records.tsx
@@ -1,17 +1,17 @@
import {
- extractEntryRole,
+ extractNodeRole,
SelectFieldAttributes,
SelectOptionAttributes,
- ViewFilterAttributes,
+ DatabaseViewFilterAttributes,
} from '@colanode/core';
import { BoardViewRecordCard } from '@/renderer/components/databases/boards/board-view-record-card';
import { BoardViewRecordCreateCard } from '@/renderer/components/databases/boards/board-view-record-create-card';
import { RecordProvider } from '@/renderer/components/records/record-provider';
import { useDatabase } from '@/renderer/contexts/database';
-import { useView } from '@/renderer/contexts/view';
+import { useDatabaseView } from '@/renderer/contexts/database-view';
import { useWorkspace } from '@/renderer/contexts/workspace';
-import { useRecordsQuery } from '@/renderer/hooks/user-records-query';
+import { useRecordsQuery } from '@/renderer/hooks/use-records-query';
interface BoardViewColumnRecordsProps {
field: SelectFieldAttributes;
@@ -24,9 +24,9 @@ export const BoardViewColumnRecords = ({
}: BoardViewColumnRecordsProps) => {
const workspace = useWorkspace();
const database = useDatabase();
- const view = useView();
+ const view = useDatabaseView();
- const filter: ViewFilterAttributes = {
+ const filter: DatabaseViewFilterAttributes = {
id: '1',
type: 'field',
fieldId: field.id,
@@ -34,14 +34,13 @@ export const BoardViewColumnRecords = ({
value: [option.id],
};
- const filters: ViewFilterAttributes[] = [...view.filters, filter];
+ const filters: DatabaseViewFilterAttributes[] = [...view.filters, filter];
const { records } = useRecordsQuery(filters, view.sorts);
return (
<div className="mt-3 flex flex-col gap-2">
{records.map((record) => {
- const role =
- extractEntryRole(record, workspace.userId) ?? database.role;
+ const role = extractNodeRole(record, workspace.userId) ?? database.role;
return (
<RecordProvider key={record.id} record={record} role={role}>
diff --git a/apps/desktop/src/renderer/components/databases/boards/board-view-record-card.tsx b/apps/desktop/src/renderer/components/databases/boards/board-view-record-card.tsx
index 30991e6a..805c5d0f 100644
--- a/apps/desktop/src/renderer/components/databases/boards/board-view-record-card.tsx
+++ b/apps/desktop/src/renderer/components/databases/boards/board-view-record-card.tsx
@@ -4,7 +4,7 @@ import { useDrag } from 'react-dnd';
import { RecordFieldValue } from '@/renderer/components/records/record-field-value';
import { useRecord } from '@/renderer/contexts/record';
-import { useView } from '@/renderer/contexts/view';
+import { useDatabaseView } from '@/renderer/contexts/database-view';
import { useLayout } from '@/renderer/contexts/layout';
interface DragResult {
@@ -14,7 +14,7 @@ interface DragResult {
export const BoardViewRecordCard = () => {
const layout = useLayout();
- const view = useView();
+ const view = useDatabaseView();
const record = useRecord();
const [, drag] = useDrag({
@@ -34,7 +34,7 @@ export const BoardViewRecordCard = () => {
}
record.updateFieldValue(dropResult.field, {
- type: 'select',
+ type: 'string',
value: optionId,
});
}
diff --git a/apps/desktop/src/renderer/components/databases/boards/board-view-record-create-card.tsx b/apps/desktop/src/renderer/components/databases/boards/board-view-record-create-card.tsx
index 3315a758..e4173411 100644
--- a/apps/desktop/src/renderer/components/databases/boards/board-view-record-create-card.tsx
+++ b/apps/desktop/src/renderer/components/databases/boards/board-view-record-create-card.tsx
@@ -1,18 +1,18 @@
-import { ViewFilterAttributes } from '@colanode/core';
+import { DatabaseViewFilterAttributes } from '@colanode/core';
import { Plus } from 'lucide-react';
import { useDatabase } from '@/renderer/contexts/database';
-import { useView } from '@/renderer/contexts/view';
+import { useDatabaseView } from '@/renderer/contexts/database-view';
interface BoardViewRecordCreateCardProps {
- filters: ViewFilterAttributes[];
+ filters: DatabaseViewFilterAttributes[];
}
export const BoardViewRecordCreateCard = ({
filters,
}: BoardViewRecordCreateCardProps) => {
const database = useDatabase();
- const view = useView();
+ const view = useDatabaseView();
if (!database.canCreateRecord) {
return null;
diff --git a/apps/desktop/src/renderer/components/databases/boards/board-view-settings.tsx b/apps/desktop/src/renderer/components/databases/boards/board-view-settings.tsx
index f9fb3955..083cc39c 100644
--- a/apps/desktop/src/renderer/components/databases/boards/board-view-settings.tsx
+++ b/apps/desktop/src/renderer/components/databases/boards/board-view-settings.tsx
@@ -21,12 +21,12 @@ import {
TooltipTrigger,
} from '@/renderer/components/ui/tooltip';
import { useDatabase } from '@/renderer/contexts/database';
-import { useView } from '@/renderer/contexts/view';
+import { useDatabaseView } from '@/renderer/contexts/database-view';
import { cn } from '@/shared/lib/utils';
export const BoardViewSettings = () => {
const database = useDatabase();
- const view = useView();
+ const view = useDatabaseView();
const [open, setOpen] = React.useState(false);
const [openDelete, setOpenDelete] = React.useState(false);
@@ -51,7 +51,7 @@ export const BoardViewSettings = () => {
id={view.id}
name={view.name}
avatar={view.avatar}
- type={view.type}
+ layout={view.layout}
className="size-4"
/>
</Button>
@@ -62,7 +62,7 @@ export const BoardViewSettings = () => {
id={view.id}
name={view.name}
avatar={view.avatar}
- type={view.type}
+ layout={view.layout}
className="size-4"
/>
</Button>
diff --git a/apps/desktop/src/renderer/components/databases/boards/board-view.tsx b/apps/desktop/src/renderer/components/databases/boards/board-view.tsx
index f453dcee..00ac97a3 100644
--- a/apps/desktop/src/renderer/components/databases/boards/board-view.tsx
+++ b/apps/desktop/src/renderer/components/databases/boards/board-view.tsx
@@ -7,11 +7,11 @@ import { ViewSearchBar } from '@/renderer/components/databases/search/view-searc
import { ViewSortButton } from '@/renderer/components/databases/search/view-sort-button';
import { ViewTabs } from '@/renderer/components/databases/view-tabs';
import { useDatabase } from '@/renderer/contexts/database';
-import { useView } from '@/renderer/contexts/view';
+import { useDatabaseView } from '@/renderer/contexts/database-view';
export const BoardView = () => {
const database = useDatabase();
- const view = useView();
+ const view = useDatabaseView();
const groupByField = database.fields.find(
(field) => field.id === view.groupBy
diff --git a/apps/desktop/src/renderer/components/databases/calendars/calendar-view-day.tsx b/apps/desktop/src/renderer/components/databases/calendars/calendar-view-day.tsx
index 4568b5e8..66d368b8 100644
--- a/apps/desktop/src/renderer/components/databases/calendars/calendar-view-day.tsx
+++ b/apps/desktop/src/renderer/components/databases/calendars/calendar-view-day.tsx
@@ -1,4 +1,4 @@
-import { extractEntryRole, isSameDay, RecordEntry } from '@colanode/core';
+import { extractNodeRole, isSameDay } from '@colanode/core';
import { Plus } from 'lucide-react';
import { CalendarViewRecordCard } from '@/renderer/components/databases/calendars/calendar-view-record-card';
@@ -6,11 +6,12 @@ import { RecordProvider } from '@/renderer/components/records/record-provider';
import { useDatabase } from '@/renderer/contexts/database';
import { useWorkspace } from '@/renderer/contexts/workspace';
import { cn } from '@/shared/lib/utils';
+import { LocalRecordNode } from '@/shared/types/nodes';
interface CalendarViewDayProps {
date: Date;
month: Date;
- records: RecordEntry[];
+ records: LocalRecordNode[];
onCreate?: () => void;
}
@@ -49,8 +50,7 @@ export const CalendarViewDay = ({
</p>
</div>
{records.map((record) => {
- const role =
- extractEntryRole(record, workspace.userId) ?? database.role;
+ const role = extractNodeRole(record, workspace.userId) ?? database.role;
return (
<RecordProvider key={record.id} record={record} role={role}>
diff --git a/apps/desktop/src/renderer/components/databases/calendars/calendar-view-grid.tsx b/apps/desktop/src/renderer/components/databases/calendars/calendar-view-grid.tsx
index 0d18edb7..b514f8dc 100644
--- a/apps/desktop/src/renderer/components/databases/calendars/calendar-view-grid.tsx
+++ b/apps/desktop/src/renderer/components/databases/calendars/calendar-view-grid.tsx
@@ -2,7 +2,7 @@ import {
FieldAttributes,
isSameDay,
toUTCDate,
- ViewFilterAttributes,
+ DatabaseViewFilterAttributes,
} from '@colanode/core';
import { ChevronLeft, ChevronRight } from 'lucide-react';
import React from 'react';
@@ -11,9 +11,9 @@ import { DayPicker, DayProps } from 'react-day-picker';
import { CalendarViewDay } from '@/renderer/components/databases/calendars/calendar-view-day';
import { buttonVariants } from '@/renderer/components/ui/button';
import { useDatabase } from '@/renderer/contexts/database';
-import { useView } from '@/renderer/contexts/view';
+import { useDatabaseView } from '@/renderer/contexts/database-view';
import { useWorkspace } from '@/renderer/contexts/workspace';
-import { useRecordsQuery } from '@/renderer/hooks/user-records-query';
+import { useRecordsQuery } from '@/renderer/hooks/use-records-query';
import { filterRecords } from '@/shared/lib/databases';
import { cn, getDisplayedDates } from '@/shared/lib/utils';
@@ -24,12 +24,12 @@ interface CalendarViewGridProps {
export const CalendarViewGrid = ({ field }: CalendarViewGridProps) => {
const workspace = useWorkspace();
const database = useDatabase();
- const view = useView();
+ const view = useDatabaseView();
const [month, setMonth] = React.useState(new Date());
const { first, last } = getDisplayedDates(month);
- const filters: ViewFilterAttributes[] = [
+ const filters: DatabaseViewFilterAttributes[] = [
...view.filters,
{
id: 'start_date',
@@ -89,7 +89,7 @@ export const CalendarViewGrid = ({ field }: CalendarViewGridProps) => {
<ChevronRight className="size-4" {...props} />
),
Day: (props: DayProps) => {
- const filter: ViewFilterAttributes = {
+ const filter: DatabaseViewFilterAttributes = {
id: 'calendar_filter',
type: 'field',
fieldId: field.id,
@@ -105,7 +105,8 @@ export const CalendarViewGrid = ({ field }: CalendarViewGridProps) => {
);
const canCreate =
- (field.type === 'createdAt' && isSameDay(props.date, new Date())) ||
+ (field.type === 'created_at' &&
+ isSameDay(props.date, new Date())) ||
field.type === 'date';
const onCreate =
diff --git a/apps/desktop/src/renderer/components/databases/calendars/calendar-view-record-card.tsx b/apps/desktop/src/renderer/components/databases/calendars/calendar-view-record-card.tsx
index 7bb50f07..83282db4 100644
--- a/apps/desktop/src/renderer/components/databases/calendars/calendar-view-record-card.tsx
+++ b/apps/desktop/src/renderer/components/databases/calendars/calendar-view-record-card.tsx
@@ -1,11 +1,11 @@
import { RecordFieldValue } from '@/renderer/components/records/record-field-value';
import { useRecord } from '@/renderer/contexts/record';
-import { useView } from '@/renderer/contexts/view';
+import { useDatabaseView } from '@/renderer/contexts/database-view';
import { useLayout } from '@/renderer/contexts/layout';
export const CalendarViewRecordCard = () => {
const layout = useLayout();
- const view = useView();
+ const view = useDatabaseView();
const record = useRecord();
const name = record.name;
diff --git a/apps/desktop/src/renderer/components/databases/calendars/calendar-view-settings.tsx b/apps/desktop/src/renderer/components/databases/calendars/calendar-view-settings.tsx
index 909870a4..c90aae25 100644
--- a/apps/desktop/src/renderer/components/databases/calendars/calendar-view-settings.tsx
+++ b/apps/desktop/src/renderer/components/databases/calendars/calendar-view-settings.tsx
@@ -21,12 +21,12 @@ import {
TooltipTrigger,
} from '@/renderer/components/ui/tooltip';
import { useDatabase } from '@/renderer/contexts/database';
-import { useView } from '@/renderer/contexts/view';
+import { useDatabaseView } from '@/renderer/contexts/database-view';
import { cn } from '@/shared/lib/utils';
export const CalendarViewSettings = () => {
const database = useDatabase();
- const view = useView();
+ const view = useDatabaseView();
const [open, setOpen] = React.useState(false);
const [openDelete, setOpenDelete] = React.useState(false);
@@ -51,7 +51,7 @@ export const CalendarViewSettings = () => {
id={view.id}
name={view.name}
avatar={view.avatar}
- type={view.type}
+ layout={view.layout}
className="size-4"
/>
</Button>
@@ -62,7 +62,7 @@ export const CalendarViewSettings = () => {
id={view.id}
name={view.name}
avatar={view.avatar}
- type={view.type}
+ layout={view.layout}
className="size-4"
/>
</Button>
diff --git a/apps/desktop/src/renderer/components/databases/calendars/calendar-view.tsx b/apps/desktop/src/renderer/components/databases/calendars/calendar-view.tsx
index 56bd4305..52bc2735 100644
--- a/apps/desktop/src/renderer/components/databases/calendars/calendar-view.tsx
+++ b/apps/desktop/src/renderer/components/databases/calendars/calendar-view.tsx
@@ -7,11 +7,11 @@ import { ViewSearchBar } from '@/renderer/components/databases/search/view-searc
import { ViewSortButton } from '@/renderer/components/databases/search/view-sort-button';
import { ViewTabs } from '@/renderer/components/databases/view-tabs';
import { useDatabase } from '@/renderer/contexts/database';
-import { useView } from '@/renderer/contexts/view';
+import { useDatabaseView } from '@/renderer/contexts/database-view';
export const CalendarView = () => {
const database = useDatabase();
- const view = useView();
+ const view = useDatabaseView();
const groupByField = database.fields.find(
(field) => field.id === view.groupBy
diff --git a/apps/desktop/src/renderer/components/databases/database-breadcrumb-item.tsx b/apps/desktop/src/renderer/components/databases/database-breadcrumb-item.tsx
index 687ab9cc..e1a81f25 100644
--- a/apps/desktop/src/renderer/components/databases/database-breadcrumb-item.tsx
+++ b/apps/desktop/src/renderer/components/databases/database-breadcrumb-item.tsx
@@ -1,25 +1,13 @@
-import { DatabaseEntry } from '@colanode/core';
-
import { Avatar } from '@/renderer/components/avatars/avatar';
-import { useQuery } from '@/renderer/hooks/use-query';
-import { useWorkspace } from '@/renderer/contexts/workspace';
+import { LocalDatabaseNode } from '@/shared/types/nodes';
interface DatabaseBreadcrumbItemProps {
- id: string;
+ database: LocalDatabaseNode;
}
-export const DatabaseBreadcrumbItem = ({ id }: DatabaseBreadcrumbItemProps) => {
- const workspace = useWorkspace();
- const { data } = useQuery({
- type: 'entry_get',
- entryId: id,
- accountId: workspace.accountId,
- workspaceId: workspace.id,
- });
- if (!data) {
- return null;
- }
- const database = data as DatabaseEntry;
+export const DatabaseBreadcrumbItem = ({
+ database,
+}: DatabaseBreadcrumbItemProps) => {
return (
<div className="flex items-center space-x-2">
<Avatar
diff --git a/apps/desktop/src/renderer/components/databases/database-container-tab.tsx b/apps/desktop/src/renderer/components/databases/database-container-tab.tsx
index 7f728e67..d874f44c 100644
--- a/apps/desktop/src/renderer/components/databases/database-container-tab.tsx
+++ b/apps/desktop/src/renderer/components/databases/database-container-tab.tsx
@@ -1,8 +1,7 @@
-import { DatabaseEntry } from '@colanode/core';
-
import { Avatar } from '@/renderer/components/avatars/avatar';
import { useWorkspace } from '@/renderer/contexts/workspace';
import { useQuery } from '@/renderer/hooks/use-query';
+import { LocalDatabaseNode } from '@/shared/types/nodes';
interface DatabaseContainerTabProps {
databaseId: string;
@@ -14,8 +13,8 @@ export const DatabaseContainerTab = ({
const workspace = useWorkspace();
const { data, isPending } = useQuery({
- type: 'entry_get',
- entryId: databaseId,
+ type: 'node_get',
+ nodeId: databaseId,
accountId: workspace.accountId,
workspaceId: workspace.id,
});
@@ -24,7 +23,7 @@ export const DatabaseContainerTab = ({
return <p className="text-sm text-muted-foreground">Loading...</p>;
}
- const database = data as DatabaseEntry;
+ const database = data as LocalDatabaseNode;
if (!database) {
return <p className="text-sm text-muted-foreground">Not found</p>;
}
diff --git a/apps/desktop/src/renderer/components/databases/database-container.tsx b/apps/desktop/src/renderer/components/databases/database-container.tsx
index 3304c933..ef8e3417 100644
--- a/apps/desktop/src/renderer/components/databases/database-container.tsx
+++ b/apps/desktop/src/renderer/components/databases/database-container.tsx
@@ -1,5 +1,3 @@
-import { DatabaseEntry } from '@colanode/core';
-
import { DatabaseNotFound } from '@/renderer/components/databases/database-not-found';
import {
Container,
@@ -8,30 +6,31 @@ import {
ContainerSettings,
} from '@/renderer/components/ui/container';
import { ContainerBreadcrumb } from '@/renderer/components/layouts/containers/container-breadrumb';
-import { useEntryContainer } from '@/renderer/hooks/use-entry-container';
-import { useEntryRadar } from '@/renderer/hooks/use-entry-radar';
+import { useNodeContainer } from '@/renderer/hooks/use-node-container';
+import { useNodeRadar } from '@/renderer/hooks/use-node-radar';
import { DatabaseSettings } from '@/renderer/components/databases/database-settings';
import { Database } from '@/renderer/components/databases/database';
import { DatabaseViews } from '@/renderer/components/databases/database-views';
+import { LocalDatabaseNode } from '@/shared/types/nodes';
interface DatabaseContainerProps {
databaseId: string;
}
export const DatabaseContainer = ({ databaseId }: DatabaseContainerProps) => {
- const data = useEntryContainer<DatabaseEntry>(databaseId);
+ const data = useNodeContainer<LocalDatabaseNode>(databaseId);
- useEntryRadar(data.entry);
+ useNodeRadar(data.node);
if (data.isPending) {
return null;
}
- if (!data.entry) {
+ if (!data.node) {
return <DatabaseNotFound />;
}
- const { entry: database, role } = data;
+ const { node: database, role } = data;
return (
<Container>
diff --git a/apps/desktop/src/renderer/components/databases/database-settings.tsx b/apps/desktop/src/renderer/components/databases/database-settings.tsx
index ebdcf053..24d18618 100644
--- a/apps/desktop/src/renderer/components/databases/database-settings.tsx
+++ b/apps/desktop/src/renderer/components/databases/database-settings.tsx
@@ -1,8 +1,9 @@
-import { DatabaseEntry, EntryRole, hasEntryRole } from '@colanode/core';
+import { NodeRole, hasNodeRole } from '@colanode/core';
import { Copy, Image, LetterText, Settings, Trash2 } from 'lucide-react';
import React from 'react';
-import { EntryCollaboratorAudit } from '@/renderer/components/collaborators/entry-collaborator-audit';
+import { LocalDatabaseNode } from '@/shared/types/nodes';
+import { NodeCollaboratorAudit } from '@/renderer/components/collaborators/node-collaborator-audit';
import { DatabaseDeleteDialog } from '@/renderer/components/databases/database-delete-dialog';
import { DatabaseUpdateDialog } from '@/renderer/components/databases/database-update-dialog';
import {
@@ -15,16 +16,16 @@ import {
} from '@/renderer/components/ui/dropdown-menu';
interface DatabaseSettingsProps {
- database: DatabaseEntry;
- role: EntryRole;
+ database: LocalDatabaseNode;
+ role: NodeRole;
}
export const DatabaseSettings = ({ database, role }: DatabaseSettingsProps) => {
const [showUpdateDialog, setShowUpdateDialog] = React.useState(false);
const [showDeleteDialog, setShowDeleteModal] = React.useState(false);
- const canEdit = hasEntryRole(role, 'editor');
- const canDelete = hasEntryRole(role, 'admin');
+ const canEdit = hasNodeRole(role, 'editor');
+ const canDelete = hasNodeRole(role, 'admin');
return (
<React.Fragment>
@@ -84,7 +85,7 @@ export const DatabaseSettings = ({ database, role }: DatabaseSettingsProps) => {
<DropdownMenuSeparator />
<DropdownMenuLabel>Created by</DropdownMenuLabel>
<DropdownMenuItem>
- <EntryCollaboratorAudit
+ <NodeCollaboratorAudit
collaboratorId={database.createdBy}
date={database.createdAt}
/>
@@ -94,7 +95,7 @@ export const DatabaseSettings = ({ database, role }: DatabaseSettingsProps) => {
<DropdownMenuSeparator />
<DropdownMenuLabel>Last updated by</DropdownMenuLabel>
<DropdownMenuItem>
- <EntryCollaboratorAudit
+ <NodeCollaboratorAudit
collaboratorId={database.updatedBy}
date={database.updatedAt}
/>
diff --git a/apps/desktop/src/renderer/components/databases/database-sidiebar-item.tsx b/apps/desktop/src/renderer/components/databases/database-sidiebar-item.tsx
index 727eea61..b53f6a06 100644
--- a/apps/desktop/src/renderer/components/databases/database-sidiebar-item.tsx
+++ b/apps/desktop/src/renderer/components/databases/database-sidiebar-item.tsx
@@ -1,11 +1,10 @@
-import { DatabaseEntry } from '@colanode/core';
-
import { Avatar } from '@/renderer/components/avatars/avatar';
import { useLayout } from '@/renderer/contexts/layout';
import { cn } from '@/shared/lib/utils';
+import { LocalDatabaseNode } from '@/shared/types/nodes';
interface DatabaseSidebarItemProps {
- database: DatabaseEntry;
+ database: LocalDatabaseNode;
}
export const DatabaseSidebarItem = ({ database }: DatabaseSidebarItemProps) => {
diff --git a/apps/desktop/src/renderer/components/databases/database-update-dialog.tsx b/apps/desktop/src/renderer/components/databases/database-update-dialog.tsx
index dc499720..537ec753 100644
--- a/apps/desktop/src/renderer/components/databases/database-update-dialog.tsx
+++ b/apps/desktop/src/renderer/components/databases/database-update-dialog.tsx
@@ -1,5 +1,6 @@
-import { DatabaseEntry, EntryRole, hasEntryRole } from '@colanode/core';
+import { NodeRole, hasNodeRole } from '@colanode/core';
+import { LocalDatabaseNode } from '@/shared/types/nodes';
import { DatabaseForm } from '@/renderer/components/databases/database-form';
import {
Dialog,
@@ -13,8 +14,8 @@ import { useMutation } from '@/renderer/hooks/use-mutation';
import { toast } from '@/renderer/hooks/use-toast';
interface DatabaseUpdateDialogProps {
- database: DatabaseEntry;
- role: EntryRole;
+ database: LocalDatabaseNode;
+ role: NodeRole;
open: boolean;
onOpenChange: (open: boolean) => void;
}
@@ -27,7 +28,7 @@ export const DatabaseUpdateDialog = ({
}: DatabaseUpdateDialogProps) => {
const workspace = useWorkspace();
const { mutate, isPending } = useMutation();
- const canEdit = hasEntryRole(role, 'editor');
+ const canEdit = hasNodeRole(role, 'editor');
return (
<Dialog open={open} onOpenChange={onOpenChange}>
diff --git a/apps/desktop/src/renderer/components/databases/database-views.tsx b/apps/desktop/src/renderer/components/databases/database-views.tsx
index 02e78594..5b647999 100644
--- a/apps/desktop/src/renderer/components/databases/database-views.tsx
+++ b/apps/desktop/src/renderer/components/databases/database-views.tsx
@@ -5,23 +5,32 @@ import { View } from '@/renderer/components/databases/view';
import { ScrollBar } from '@/renderer/components/ui/scroll-area';
import { useDatabase } from '@/renderer/contexts/database';
import { DatabaseViewsContext } from '@/renderer/contexts/database-views';
+import { useQuery } from '@/renderer/hooks/use-query';
+import { useWorkspace } from '@/renderer/contexts/workspace';
export const DatabaseViews = () => {
+ const workspace = useWorkspace();
const database = useDatabase();
- const [activeViewId, setActiveViewId] = React.useState<string>(
- database.views[0]?.id ?? ''
- );
- const activeView = database.views.find((view) => view.id === activeViewId);
+ const [activeViewId, setActiveViewId] = React.useState<string | null>(null);
+
+ const { data } = useQuery({
+ type: 'database_view_list',
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
+ databaseId: database.id,
+ });
React.useEffect(() => {
- if (!activeView) {
- setActiveViewId(database.views[0]?.id ?? '');
+ if (!activeViewId) {
+ setActiveViewId(data?.[0]?.id ?? null);
}
- }, [database.views, activeViewId]);
+ }, [data, activeViewId]);
+ const views = data ?? [];
+ const activeView = views.find((view) => view.id === activeViewId);
return (
<DatabaseViewsContext.Provider
- value={{ views: database.views, activeViewId, setActiveViewId }}
+ value={{ views, activeViewId: activeViewId ?? '', setActiveViewId }}
>
<div className="h-full w-full overflow-y-auto">
<ScrollAreaPrimitive.Root className="relative overflow-hidden">
diff --git a/apps/desktop/src/renderer/components/databases/database.tsx b/apps/desktop/src/renderer/components/databases/database.tsx
index 7006c25e..d7d97e79 100644
--- a/apps/desktop/src/renderer/components/databases/database.tsx
+++ b/apps/desktop/src/renderer/components/databases/database.tsx
@@ -1,20 +1,21 @@
-import { DatabaseEntry, EntryRole, hasEntryRole } from '@colanode/core';
+import { NodeRole, hasNodeRole } from '@colanode/core';
import React from 'react';
+import { LocalDatabaseNode } from '@/shared/types/nodes';
import { DatabaseContext } from '@/renderer/contexts/database';
import { useWorkspace } from '@/renderer/contexts/workspace';
import { toast } from '@/renderer/hooks/use-toast';
interface DatabaseProps {
- database: DatabaseEntry;
- role: EntryRole;
+ database: LocalDatabaseNode;
+ role: NodeRole;
children: React.ReactNode;
}
export const Database = ({ database, role, children }: DatabaseProps) => {
const workspace = useWorkspace();
- const canEdit = hasEntryRole(role, 'editor');
- const canCreateRecord = hasEntryRole(role, 'editor');
+ const canEdit = hasNodeRole(role, 'editor');
+ const canCreateRecord = hasNodeRole(role, 'editor');
return (
<DatabaseContext.Provider
@@ -23,7 +24,6 @@ export const Database = ({ database, role, children }: DatabaseProps) => {
name: database.attributes.name,
role,
fields: Object.values(database.attributes.fields),
- views: Object.values(database.attributes.views),
canEdit,
canCreateRecord,
createField: async (type, name) => {
diff --git a/apps/desktop/src/renderer/components/databases/fields/field-create-popover.tsx b/apps/desktop/src/renderer/components/databases/fields/field-create-popover.tsx
index 8f246fd5..b7a21a8b 100644
--- a/apps/desktop/src/renderer/components/databases/fields/field-create-popover.tsx
+++ b/apps/desktop/src/renderer/components/databases/fields/field-create-popover.tsx
@@ -32,19 +32,19 @@ const formSchema = z.object({
type: z.union([
z.literal('boolean'),
z.literal('collaborator'),
- z.literal('createdAt'),
- z.literal('createdBy'),
+ z.literal('created_at'),
+ z.literal('created_by'),
z.literal('date'),
z.literal('email'),
z.literal('file'),
- z.literal('multiSelect'),
+ z.literal('multi_select'),
z.literal('number'),
z.literal('phone'),
z.literal('select'),
z.literal('text'),
z.literal('relation'),
- z.literal('updatedAt'),
- z.literal('updatedBy'),
+ z.literal('updated_at'),
+ z.literal('updated_by'),
z.literal('url'),
]),
relationDatabaseId: z.string().optional().nullable(),
diff --git a/apps/desktop/src/renderer/components/databases/fields/field-icon.tsx b/apps/desktop/src/renderer/components/databases/fields/field-icon.tsx
index 2c717470..29e57af0 100644
--- a/apps/desktop/src/renderer/components/databases/fields/field-icon.tsx
+++ b/apps/desktop/src/renderer/components/databases/fields/field-icon.tsx
@@ -26,9 +26,9 @@ export const FieldIcon = ({ type, className }: FieldIconProps) => {
return <SquareCheck className={className} />;
case 'collaborator':
return <User className={className} />;
- case 'createdAt':
+ case 'created_at':
return <Calendar className={className} />;
- case 'createdBy':
+ case 'created_by':
return <User className={className} />;
case 'date':
return <Calendar className={className} />;
@@ -36,7 +36,7 @@ export const FieldIcon = ({ type, className }: FieldIconProps) => {
return <Mail className={className} />;
case 'file':
return <File className={className} />;
- case 'multiSelect':
+ case 'multi_select':
return <ListChecks className={className} />;
case 'number':
return <Hash className={className} />;
@@ -50,9 +50,9 @@ export const FieldIcon = ({ type, className }: FieldIconProps) => {
return <Text className={className} />;
case 'url':
return <Link className={className} />;
- case 'updatedAt':
+ case 'updated_at':
return <Calendar className={className} />;
- case 'updatedBy':
+ case 'updated_by':
return <User className={className} />;
default:
return <ShieldQuestion className={className} />;
diff --git a/apps/desktop/src/renderer/components/databases/fields/field-type-select.tsx b/apps/desktop/src/renderer/components/databases/fields/field-type-select.tsx
index c82ffa48..e9140a71 100644
--- a/apps/desktop/src/renderer/components/databases/fields/field-type-select.tsx
+++ b/apps/desktop/src/renderer/components/databases/fields/field-type-select.tsx
@@ -35,11 +35,11 @@ const fieldTypes: FieldTypeOption[] = [
},
{
name: 'Created Date & Time',
- type: 'createdAt',
+ type: 'created_at',
},
{
name: 'Created by user',
- type: 'createdBy',
+ type: 'created_by',
},
{
name: 'Date',
@@ -51,7 +51,7 @@ const fieldTypes: FieldTypeOption[] = [
},
{
name: 'Multi Select',
- type: 'multiSelect',
+ type: 'multi_select',
},
{
name: 'Number',
@@ -79,11 +79,11 @@ const fieldTypes: FieldTypeOption[] = [
},
{
name: 'Last Updated Date & Time',
- type: 'updatedAt',
+ type: 'updated_at',
},
{
name: 'Last Updated By',
- type: 'updatedBy',
+ type: 'updated_by',
},
];
diff --git a/apps/desktop/src/renderer/components/databases/search/view-boolean-field-filter.tsx b/apps/desktop/src/renderer/components/databases/search/view-boolean-field-filter.tsx
index 978a89c0..08529501 100644
--- a/apps/desktop/src/renderer/components/databases/search/view-boolean-field-filter.tsx
+++ b/apps/desktop/src/renderer/components/databases/search/view-boolean-field-filter.tsx
@@ -1,6 +1,6 @@
import {
BooleanFieldAttributes,
- ViewFieldFilterAttributes,
+ DatabaseViewFieldFilterAttributes,
} from '@colanode/core';
import { ChevronDown, Trash2 } from 'lucide-react';
@@ -17,19 +17,19 @@ import {
PopoverContent,
PopoverTrigger,
} from '@/renderer/components/ui/popover';
-import { useView } from '@/renderer/contexts/view';
+import { useDatabaseView } from '@/renderer/contexts/database-view';
import { booleanFieldFilterOperators } from '@/shared/lib/databases';
interface ViewBooleanFieldFilterProps {
field: BooleanFieldAttributes;
- filter: ViewFieldFilterAttributes;
+ filter: DatabaseViewFieldFilterAttributes;
}
export const ViewBooleanFieldFilter = ({
field,
filter,
}: ViewBooleanFieldFilterProps) => {
- const view = useView();
+ const view = useDatabaseView();
const operator =
booleanFieldFilterOperators.find(
diff --git a/apps/desktop/src/renderer/components/databases/search/view-created-at-field-fitler.tsx b/apps/desktop/src/renderer/components/databases/search/view-created-at-field-fitler.tsx
index 490c0a43..13a0d8c9 100644
--- a/apps/desktop/src/renderer/components/databases/search/view-created-at-field-fitler.tsx
+++ b/apps/desktop/src/renderer/components/databases/search/view-created-at-field-fitler.tsx
@@ -1,6 +1,6 @@
import {
CreatedAtFieldAttributes,
- ViewFieldFilterAttributes,
+ DatabaseViewFieldFilterAttributes,
} from '@colanode/core';
import { ChevronDown, Trash2 } from 'lucide-react';
@@ -18,19 +18,19 @@ import {
PopoverContent,
PopoverTrigger,
} from '@/renderer/components/ui/popover';
-import { useView } from '@/renderer/contexts/view';
+import { useDatabaseView } from '@/renderer/contexts/database-view';
import { dateFieldFilterOperators } from '@/shared/lib/databases';
interface ViewCreatedAtFieldFilterProps {
field: CreatedAtFieldAttributes;
- filter: ViewFieldFilterAttributes;
+ filter: DatabaseViewFieldFilterAttributes;
}
export const ViewCreatedAtFieldFilter = ({
field,
filter,
}: ViewCreatedAtFieldFilterProps) => {
- const view = useView();
+ const view = useDatabaseView();
const operator =
dateFieldFilterOperators.find(
diff --git a/apps/desktop/src/renderer/components/databases/search/view-date-field-filter.tsx b/apps/desktop/src/renderer/components/databases/search/view-date-field-filter.tsx
index e24c4e13..c7e76966 100644
--- a/apps/desktop/src/renderer/components/databases/search/view-date-field-filter.tsx
+++ b/apps/desktop/src/renderer/components/databases/search/view-date-field-filter.tsx
@@ -1,4 +1,7 @@
-import { DateFieldAttributes, ViewFieldFilterAttributes } from '@colanode/core';
+import {
+ DateFieldAttributes,
+ DatabaseViewFieldFilterAttributes,
+} from '@colanode/core';
import { ChevronDown, Trash2 } from 'lucide-react';
import { FieldIcon } from '@/renderer/components/databases/fields/field-icon';
@@ -15,19 +18,19 @@ import {
PopoverContent,
PopoverTrigger,
} from '@/renderer/components/ui/popover';
-import { useView } from '@/renderer/contexts/view';
+import { useDatabaseView } from '@/renderer/contexts/database-view';
import { dateFieldFilterOperators } from '@/shared/lib/databases';
interface ViewDateFieldFilterProps {
field: DateFieldAttributes;
- filter: ViewFieldFilterAttributes;
+ filter: DatabaseViewFieldFilterAttributes;
}
export const ViewDateFieldFilter = ({
field,
filter,
}: ViewDateFieldFilterProps) => {
- const view = useView();
+ const view = useDatabaseView();
const operator =
dateFieldFilterOperators.find(
diff --git a/apps/desktop/src/renderer/components/databases/search/view-email-field-filter.tsx b/apps/desktop/src/renderer/components/databases/search/view-email-field-filter.tsx
index c31ec8d6..d7724985 100644
--- a/apps/desktop/src/renderer/components/databases/search/view-email-field-filter.tsx
+++ b/apps/desktop/src/renderer/components/databases/search/view-email-field-filter.tsx
@@ -1,6 +1,6 @@
import {
EmailFieldAttributes,
- ViewFieldFilterAttributes,
+ DatabaseViewFieldFilterAttributes,
} from '@colanode/core';
import { ChevronDown, Trash2 } from 'lucide-react';
@@ -18,19 +18,19 @@ import {
PopoverTrigger,
} from '@/renderer/components/ui/popover';
import { SmartTextInput } from '@/renderer/components/ui/smart-text-input';
-import { useView } from '@/renderer/contexts/view';
+import { useDatabaseView } from '@/renderer/contexts/database-view';
import { emailFieldFilterOperators } from '@/shared/lib/databases';
interface ViewEmailFieldFilterProps {
field: EmailFieldAttributes;
- filter: ViewFieldFilterAttributes;
+ filter: DatabaseViewFieldFilterAttributes;
}
export const ViewEmailFieldFilter = ({
field,
filter,
}: ViewEmailFieldFilterProps) => {
- const view = useView();
+ const view = useDatabaseView();
const operator =
emailFieldFilterOperators.find(
diff --git a/apps/desktop/src/renderer/components/databases/search/view-filter-add-popover.tsx b/apps/desktop/src/renderer/components/databases/search/view-filter-add-popover.tsx
index 9c521d32..5d284c97 100644
--- a/apps/desktop/src/renderer/components/databases/search/view-filter-add-popover.tsx
+++ b/apps/desktop/src/renderer/components/databases/search/view-filter-add-popover.tsx
@@ -15,7 +15,7 @@ import {
PopoverTrigger,
} from '@/renderer/components/ui/popover';
import { useDatabase } from '@/renderer/contexts/database';
-import { useView } from '@/renderer/contexts/view';
+import { useDatabaseView } from '@/renderer/contexts/database-view';
interface ViewFilterAddPopoverProps {
children: React.ReactNode;
@@ -25,7 +25,7 @@ export const ViewFilterAddPopover = ({
children,
}: ViewFilterAddPopoverProps) => {
const database = useDatabase();
- const view = useView();
+ const view = useDatabaseView();
const [open, setOpen] = React.useState(false);
const fieldsWithoutFilters = database.fields.filter(
diff --git a/apps/desktop/src/renderer/components/databases/search/view-filter-button.tsx b/apps/desktop/src/renderer/components/databases/search/view-filter-button.tsx
index eb5aac11..0cff4eae 100644
--- a/apps/desktop/src/renderer/components/databases/search/view-filter-button.tsx
+++ b/apps/desktop/src/renderer/components/databases/search/view-filter-button.tsx
@@ -1,10 +1,10 @@
import { Filter } from 'lucide-react';
import { ViewFilterAddPopover } from '@/renderer/components/databases/search/view-filter-add-popover';
-import { useView } from '@/renderer/contexts/view';
+import { useDatabaseView } from '@/renderer/contexts/database-view';
export const ViewFilterButton = () => {
- const view = useView();
+ const view = useDatabaseView();
if (view.filters.length > 0) {
return (
diff --git a/apps/desktop/src/renderer/components/databases/search/view-filters.tsx b/apps/desktop/src/renderer/components/databases/search/view-filters.tsx
index 0930f953..0ea803bf 100644
--- a/apps/desktop/src/renderer/components/databases/search/view-filters.tsx
+++ b/apps/desktop/src/renderer/components/databases/search/view-filters.tsx
@@ -12,11 +12,11 @@ import { ViewSelectFieldFilter } from '@/renderer/components/databases/search/vi
import { ViewTextFieldFilter } from '@/renderer/components/databases/search/view-text-field-filter';
import { ViewUrlFieldFilter } from '@/renderer/components/databases/search/view-url-field-filter';
import { useDatabase } from '@/renderer/contexts/database';
-import { useView } from '@/renderer/contexts/view';
+import { useDatabaseView } from '@/renderer/contexts/database-view';
export const ViewFilters = () => {
const database = useDatabase();
- const view = useView();
+ const view = useDatabaseView();
return (
<div className="flex flex-row items-center gap-2">
@@ -45,7 +45,7 @@ export const ViewFilters = () => {
);
case 'collaborator':
return null;
- case 'createdAt':
+ case 'created_at':
return (
<ViewCreatedAtFieldFilter
key={filter.id}
@@ -53,7 +53,7 @@ export const ViewFilters = () => {
filter={filter}
/>
);
- case 'createdBy':
+ case 'created_by':
return null;
case 'date':
return (
@@ -73,7 +73,7 @@ export const ViewFilters = () => {
);
case 'file':
return null;
- case 'multiSelect':
+ case 'multi_select':
return (
<ViewMultiSelectFieldFilter
key={filter.id}
diff --git a/apps/desktop/src/renderer/components/databases/search/view-multi-select-field-filter.tsx b/apps/desktop/src/renderer/components/databases/search/view-multi-select-field-filter.tsx
index 32f1892c..eb56add5 100644
--- a/apps/desktop/src/renderer/components/databases/search/view-multi-select-field-filter.tsx
+++ b/apps/desktop/src/renderer/components/databases/search/view-multi-select-field-filter.tsx
@@ -1,6 +1,6 @@
import {
MultiSelectFieldAttributes,
- ViewFieldFilterAttributes,
+ DatabaseViewFieldFilterAttributes,
} from '@colanode/core';
import { ChevronDown, Trash2 } from 'lucide-react';
@@ -19,19 +19,19 @@ import {
PopoverContent,
PopoverTrigger,
} from '@/renderer/components/ui/popover';
-import { useView } from '@/renderer/contexts/view';
+import { useDatabaseView } from '@/renderer/contexts/database-view';
import { selectFieldFilterOperators } from '@/shared/lib/databases';
interface ViewMultiSelectFieldFilterProps {
field: MultiSelectFieldAttributes;
- filter: ViewFieldFilterAttributes;
+ filter: DatabaseViewFieldFilterAttributes;
}
export const ViewMultiSelectFieldFilter = ({
field,
filter,
}: ViewMultiSelectFieldFilterProps) => {
- const view = useView();
+ const view = useDatabaseView();
const selectOptions = Object.values(field.options ?? {});
const operator =
selectFieldFilterOperators.find(
diff --git a/apps/desktop/src/renderer/components/databases/search/view-number-field-filter.tsx b/apps/desktop/src/renderer/components/databases/search/view-number-field-filter.tsx
index 97123ea8..47fc562e 100644
--- a/apps/desktop/src/renderer/components/databases/search/view-number-field-filter.tsx
+++ b/apps/desktop/src/renderer/components/databases/search/view-number-field-filter.tsx
@@ -1,6 +1,6 @@
import {
NumberFieldAttributes,
- ViewFieldFilterAttributes,
+ DatabaseViewFieldFilterAttributes,
} from '@colanode/core';
import { ChevronDown, Trash2 } from 'lucide-react';
@@ -18,19 +18,19 @@ import {
PopoverTrigger,
} from '@/renderer/components/ui/popover';
import { SmartNumberInput } from '@/renderer/components/ui/smart-number-input';
-import { useView } from '@/renderer/contexts/view';
+import { useDatabaseView } from '@/renderer/contexts/database-view';
import { numberFieldFilterOperators } from '@/shared/lib/databases';
interface ViewNumberFieldFilterProps {
field: NumberFieldAttributes;
- filter: ViewFieldFilterAttributes;
+ filter: DatabaseViewFieldFilterAttributes;
}
export const ViewNumberFieldFilter = ({
field,
filter,
}: ViewNumberFieldFilterProps) => {
- const view = useView();
+ const view = useDatabaseView();
const operator =
numberFieldFilterOperators.find(
diff --git a/apps/desktop/src/renderer/components/databases/search/view-phone-field-filter.tsx b/apps/desktop/src/renderer/components/databases/search/view-phone-field-filter.tsx
index 9f13cedf..14071bb2 100644
--- a/apps/desktop/src/renderer/components/databases/search/view-phone-field-filter.tsx
+++ b/apps/desktop/src/renderer/components/databases/search/view-phone-field-filter.tsx
@@ -1,6 +1,6 @@
import {
PhoneFieldAttributes,
- ViewFieldFilterAttributes,
+ DatabaseViewFieldFilterAttributes,
} from '@colanode/core';
import { ChevronDown, Trash2 } from 'lucide-react';
@@ -18,19 +18,19 @@ import {
PopoverTrigger,
} from '@/renderer/components/ui/popover';
import { SmartTextInput } from '@/renderer/components/ui/smart-text-input';
-import { useView } from '@/renderer/contexts/view';
+import { useDatabaseView } from '@/renderer/contexts/database-view';
import { phoneFieldFilterOperators } from '@/shared/lib/databases';
interface ViewPhoneFieldFilterProps {
field: PhoneFieldAttributes;
- filter: ViewFieldFilterAttributes;
+ filter: DatabaseViewFieldFilterAttributes;
}
export const ViewPhoneFieldFilter = ({
field,
filter,
}: ViewPhoneFieldFilterProps) => {
- const view = useView();
+ const view = useDatabaseView();
const operator =
phoneFieldFilterOperators.find(
diff --git a/apps/desktop/src/renderer/components/databases/search/view-search-bar.tsx b/apps/desktop/src/renderer/components/databases/search/view-search-bar.tsx
index a2f8f11f..fd730d8f 100644
--- a/apps/desktop/src/renderer/components/databases/search/view-search-bar.tsx
+++ b/apps/desktop/src/renderer/components/databases/search/view-search-bar.tsx
@@ -3,10 +3,10 @@ import React from 'react';
import { ViewFilters } from '@/renderer/components/databases/search/view-filters';
import { ViewSorts } from '@/renderer/components/databases/search/view-sorts';
import { Separator } from '@/renderer/components/ui/separator';
-import { useView } from '@/renderer/contexts/view';
+import { useDatabaseView } from '@/renderer/contexts/database-view';
export const ViewSearchBar = () => {
- const view = useView();
+ const view = useDatabaseView();
if (!view.isSearchBarOpened) {
return null;
diff --git a/apps/desktop/src/renderer/components/databases/search/view-select-field-filter.tsx b/apps/desktop/src/renderer/components/databases/search/view-select-field-filter.tsx
index fea0746a..34e56cb8 100644
--- a/apps/desktop/src/renderer/components/databases/search/view-select-field-filter.tsx
+++ b/apps/desktop/src/renderer/components/databases/search/view-select-field-filter.tsx
@@ -1,6 +1,6 @@
import {
SelectFieldAttributes,
- ViewFieldFilterAttributes,
+ DatabaseViewFieldFilterAttributes,
} from '@colanode/core';
import { ChevronDown, Trash2 } from 'lucide-react';
@@ -19,19 +19,19 @@ import {
PopoverContent,
PopoverTrigger,
} from '@/renderer/components/ui/popover';
-import { useView } from '@/renderer/contexts/view';
+import { useDatabaseView } from '@/renderer/contexts/database-view';
import { selectFieldFilterOperators } from '@/shared/lib/databases';
interface ViewSelectFieldFilterProps {
field: SelectFieldAttributes;
- filter: ViewFieldFilterAttributes;
+ filter: DatabaseViewFieldFilterAttributes;
}
export const ViewSelectFieldFilter = ({
field,
filter,
}: ViewSelectFieldFilterProps) => {
- const view = useView();
+ const view = useDatabaseView();
const selectOptions = Object.values(field.options ?? {});
const operator =
selectFieldFilterOperators.find(
diff --git a/apps/desktop/src/renderer/components/databases/search/view-sort-add-popover.tsx b/apps/desktop/src/renderer/components/databases/search/view-sort-add-popover.tsx
index f92396c3..5b5041bd 100644
--- a/apps/desktop/src/renderer/components/databases/search/view-sort-add-popover.tsx
+++ b/apps/desktop/src/renderer/components/databases/search/view-sort-add-popover.tsx
@@ -15,7 +15,7 @@ import {
PopoverTrigger,
} from '@/renderer/components/ui/popover';
import { useDatabase } from '@/renderer/contexts/database';
-import { useView } from '@/renderer/contexts/view';
+import { useDatabaseView } from '@/renderer/contexts/database-view';
import { isSortableField } from '@/shared/lib/databases';
interface ViewSortAddPopoverProps {
@@ -24,7 +24,7 @@ interface ViewSortAddPopoverProps {
export const ViewSortAddPopover = ({ children }: ViewSortAddPopoverProps) => {
const database = useDatabase();
- const view = useView();
+ const view = useDatabaseView();
const [open, setOpen] = React.useState(false);
const sortableFields = database.fields.filter(
diff --git a/apps/desktop/src/renderer/components/databases/search/view-sort-button.tsx b/apps/desktop/src/renderer/components/databases/search/view-sort-button.tsx
index f5d5050b..1770c952 100644
--- a/apps/desktop/src/renderer/components/databases/search/view-sort-button.tsx
+++ b/apps/desktop/src/renderer/components/databases/search/view-sort-button.tsx
@@ -1,10 +1,10 @@
import { ArrowDownAz } from 'lucide-react';
import { ViewSortAddPopover } from '@/renderer/components/databases/search/view-sort-add-popover';
-import { useView } from '@/renderer/contexts/view';
+import { useDatabaseView } from '@/renderer/contexts/database-view';
export const ViewSortButton = () => {
- const view = useView();
+ const view = useDatabaseView();
if (view.sorts.length > 0) {
return (
diff --git a/apps/desktop/src/renderer/components/databases/search/view-sort-row.tsx b/apps/desktop/src/renderer/components/databases/search/view-sort-row.tsx
index a6bc0ca0..84539476 100644
--- a/apps/desktop/src/renderer/components/databases/search/view-sort-row.tsx
+++ b/apps/desktop/src/renderer/components/databases/search/view-sort-row.tsx
@@ -1,4 +1,4 @@
-import { FieldAttributes, ViewSortAttributes } from '@colanode/core';
+import { FieldAttributes, DatabaseViewSortAttributes } from '@colanode/core';
import { ChevronDown, Trash2 } from 'lucide-react';
import { FieldIcon } from '@/renderer/components/databases/fields/field-icon';
@@ -9,15 +9,15 @@ import {
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/renderer/components/ui/dropdown-menu';
-import { useView } from '@/renderer/contexts/view';
+import { useDatabaseView } from '@/renderer/contexts/database-view';
interface ViewSortProps {
- sort: ViewSortAttributes;
+ sort: DatabaseViewSortAttributes;
field: FieldAttributes;
}
export const ViewSortRow = ({ sort, field }: ViewSortProps) => {
- const view = useView();
+ const view = useDatabaseView();
return (
<div className="flex flex-row items-center gap-3 text-sm">
diff --git a/apps/desktop/src/renderer/components/databases/search/view-sorts.tsx b/apps/desktop/src/renderer/components/databases/search/view-sorts.tsx
index 2df01ebd..073406bc 100644
--- a/apps/desktop/src/renderer/components/databases/search/view-sorts.tsx
+++ b/apps/desktop/src/renderer/components/databases/search/view-sorts.tsx
@@ -9,11 +9,11 @@ import {
PopoverTrigger,
} from '@/renderer/components/ui/popover';
import { useDatabase } from '@/renderer/contexts/database';
-import { useView } from '@/renderer/contexts/view';
+import { useDatabaseView } from '@/renderer/contexts/database-view';
export const ViewSorts = () => {
const database = useDatabase();
- const view = useView();
+ const view = useDatabaseView();
return (
<Popover
diff --git a/apps/desktop/src/renderer/components/databases/search/view-text-field-filter.tsx b/apps/desktop/src/renderer/components/databases/search/view-text-field-filter.tsx
index 3eb27a5b..97055691 100644
--- a/apps/desktop/src/renderer/components/databases/search/view-text-field-filter.tsx
+++ b/apps/desktop/src/renderer/components/databases/search/view-text-field-filter.tsx
@@ -1,5 +1,8 @@
-import { TextFieldAttributes, ViewFieldFilterAttributes } from '@colanode/core';
-import { ChevronDown,Trash2 } from 'lucide-react';
+import {
+ TextFieldAttributes,
+ DatabaseViewFieldFilterAttributes,
+} from '@colanode/core';
+import { ChevronDown, Trash2 } from 'lucide-react';
import { FieldIcon } from '@/renderer/components/databases/fields/field-icon';
import { Button } from '@/renderer/components/ui/button';
@@ -15,19 +18,19 @@ import {
PopoverTrigger,
} from '@/renderer/components/ui/popover';
import { SmartTextInput } from '@/renderer/components/ui/smart-text-input';
-import { useView } from '@/renderer/contexts/view';
+import { useDatabaseView } from '@/renderer/contexts/database-view';
import { textFieldFilterOperators } from '@/shared/lib/databases';
interface ViewTextFieldFilterProps {
field: TextFieldAttributes;
- filter: ViewFieldFilterAttributes;
+ filter: DatabaseViewFieldFilterAttributes;
}
export const ViewTextFieldFilter = ({
field,
filter,
}: ViewTextFieldFilterProps) => {
- const view = useView();
+ const view = useDatabaseView();
const operator =
textFieldFilterOperators.find(
diff --git a/apps/desktop/src/renderer/components/databases/search/view-url-field-filter.tsx b/apps/desktop/src/renderer/components/databases/search/view-url-field-filter.tsx
index 09ca82ff..75cb17a0 100644
--- a/apps/desktop/src/renderer/components/databases/search/view-url-field-filter.tsx
+++ b/apps/desktop/src/renderer/components/databases/search/view-url-field-filter.tsx
@@ -1,4 +1,7 @@
-import { UrlFieldAttributes, ViewFieldFilterAttributes } from '@colanode/core';
+import {
+ UrlFieldAttributes,
+ DatabaseViewFieldFilterAttributes,
+} from '@colanode/core';
import { ChevronDown, Trash2 } from 'lucide-react';
import { FieldIcon } from '@/renderer/components/databases/fields/field-icon';
@@ -15,19 +18,19 @@ import {
PopoverTrigger,
} from '@/renderer/components/ui/popover';
import { SmartTextInput } from '@/renderer/components/ui/smart-text-input';
-import { useView } from '@/renderer/contexts/view';
+import { useDatabaseView } from '@/renderer/contexts/database-view';
import { urlFieldFilterOperators } from '@/shared/lib/databases';
interface ViewUrlFieldFilterProps {
field: UrlFieldAttributes;
- filter: ViewFieldFilterAttributes;
+ filter: DatabaseViewFieldFilterAttributes;
}
export const ViewUrlFieldFilter = ({
field,
filter,
}: ViewUrlFieldFilterProps) => {
- const view = useView();
+ const view = useDatabaseView();
const operator =
urlFieldFilterOperators.find(
diff --git a/apps/desktop/src/renderer/components/databases/tables/table-view-body.tsx b/apps/desktop/src/renderer/components/databases/tables/table-view-body.tsx
index 7f72b1da..892c15d3 100644
--- a/apps/desktop/src/renderer/components/databases/tables/table-view-body.tsx
+++ b/apps/desktop/src/renderer/components/databases/tables/table-view-body.tsx
@@ -1,11 +1,11 @@
import { TableViewEmptyPlaceholder } from '@/renderer/components/databases/tables/table-view-empty-placeholder';
import { TableViewLoadMoreRow } from '@/renderer/components/databases/tables/table-view-load-more-row';
import { TableViewRow } from '@/renderer/components/databases/tables/table-view-row';
-import { useView } from '@/renderer/contexts/view';
-import { useRecordsQuery } from '@/renderer/hooks/user-records-query';
+import { useDatabaseView } from '@/renderer/contexts/database-view';
+import { useRecordsQuery } from '@/renderer/hooks/use-records-query';
export const TableViewBody = () => {
- const view = useView();
+ const view = useDatabaseView();
const { records, hasMore, loadMore, isPending } = useRecordsQuery(
view.filters,
view.sorts
diff --git a/apps/desktop/src/renderer/components/databases/tables/table-view-field-header.tsx b/apps/desktop/src/renderer/components/databases/tables/table-view-field-header.tsx
index 8eecbec2..a58cfea3 100644
--- a/apps/desktop/src/renderer/components/databases/tables/table-view-field-header.tsx
+++ b/apps/desktop/src/renderer/components/databases/tables/table-view-field-header.tsx
@@ -13,7 +13,7 @@ import {
} from '@/renderer/components/ui/popover';
import { Separator } from '@/renderer/components/ui/separator';
import { useDatabase } from '@/renderer/contexts/database';
-import { useView } from '@/renderer/contexts/view';
+import { useDatabaseView } from '@/renderer/contexts/database-view';
import { isFilterableField, isSortableField } from '@/shared/lib/databases';
import { cn } from '@/shared/lib/utils';
import { ViewField } from '@/shared/types/databases';
@@ -26,7 +26,7 @@ export const TableViewFieldHeader = ({
viewField,
}: TableViewFieldHeaderProps) => {
const database = useDatabase();
- const view = useView();
+ const view = useDatabaseView();
const [openPopover, setOpenPopover] = React.useState(false);
const [showDeleteDialog, setShowDeleteDialog] = React.useState(false);
diff --git a/apps/desktop/src/renderer/components/databases/tables/table-view-header.tsx b/apps/desktop/src/renderer/components/databases/tables/table-view-header.tsx
index c81984a2..f282f614 100644
--- a/apps/desktop/src/renderer/components/databases/tables/table-view-header.tsx
+++ b/apps/desktop/src/renderer/components/databases/tables/table-view-header.tsx
@@ -2,11 +2,11 @@ import { FieldCreatePopover } from '@/renderer/components/databases/fields/field
import { TableViewFieldHeader } from '@/renderer/components/databases/tables/table-view-field-header';
import { TableViewNameHeader } from '@/renderer/components/databases/tables/table-view-name-header';
import { useDatabase } from '@/renderer/contexts/database';
-import { useView } from '@/renderer/contexts/view';
+import { useDatabaseView } from '@/renderer/contexts/database-view';
export const TableViewHeader = () => {
const database = useDatabase();
- const view = useView();
+ const view = useDatabaseView();
return (
<div className="flex flex-row items-center gap-0.5">
diff --git a/apps/desktop/src/renderer/components/databases/tables/table-view-name-cell.tsx b/apps/desktop/src/renderer/components/databases/tables/table-view-name-cell.tsx
index 8a1f0ade..d7703ccf 100644
--- a/apps/desktop/src/renderer/components/databases/tables/table-view-name-cell.tsx
+++ b/apps/desktop/src/renderer/components/databases/tables/table-view-name-cell.tsx
@@ -1,4 +1,4 @@
-import { RecordEntry } from '@colanode/core';
+import { RecordNode } from '@colanode/core';
import isHotkey from 'is-hotkey';
import { SquareArrowOutUpRight } from 'lucide-react';
import React, { Fragment } from 'react';
@@ -54,7 +54,7 @@ const NameEditor = ({ initialValue, onSave, onCancel }: NameEditorProps) => {
};
interface TableViewNameCellProps {
- record: RecordEntry;
+ record: RecordNode;
}
export const TableViewNameCell = ({ record }: TableViewNameCellProps) => {
diff --git a/apps/desktop/src/renderer/components/databases/tables/table-view-name-header.tsx b/apps/desktop/src/renderer/components/databases/tables/table-view-name-header.tsx
index 6e18244f..8cddf43c 100644
--- a/apps/desktop/src/renderer/components/databases/tables/table-view-name-header.tsx
+++ b/apps/desktop/src/renderer/components/databases/tables/table-view-name-header.tsx
@@ -11,12 +11,12 @@ import {
} from '@/renderer/components/ui/popover';
import { Separator } from '@/renderer/components/ui/separator';
import { useDatabase } from '@/renderer/contexts/database';
-import { useView } from '@/renderer/contexts/view';
+import { useDatabaseView } from '@/renderer/contexts/database-view';
import { cn } from '@/shared/lib/utils';
export const TableViewNameHeader = () => {
const database = useDatabase();
- const view = useView();
+ const view = useDatabaseView();
const [dropMonitor, dropRef] = useDrop({
accept: 'table-field-header',
diff --git a/apps/desktop/src/renderer/components/databases/tables/table-view-record-create-row.tsx b/apps/desktop/src/renderer/components/databases/tables/table-view-record-create-row.tsx
index d003a1e3..2597d957 100644
--- a/apps/desktop/src/renderer/components/databases/tables/table-view-record-create-row.tsx
+++ b/apps/desktop/src/renderer/components/databases/tables/table-view-record-create-row.tsx
@@ -1,11 +1,11 @@
import { Plus } from 'lucide-react';
import { useDatabase } from '@/renderer/contexts/database';
-import { useView } from '@/renderer/contexts/view';
+import { useDatabaseView } from '@/renderer/contexts/database-view';
export const TableViewRecordCreateRow = () => {
const database = useDatabase();
- const view = useView();
+ const view = useDatabaseView();
if (!database.canCreateRecord) {
return null;
diff --git a/apps/desktop/src/renderer/components/databases/tables/table-view-row.tsx b/apps/desktop/src/renderer/components/databases/tables/table-view-row.tsx
index b902d473..4d5ab20b 100644
--- a/apps/desktop/src/renderer/components/databases/tables/table-view-row.tsx
+++ b/apps/desktop/src/renderer/components/databases/tables/table-view-row.tsx
@@ -1,22 +1,23 @@
-import { extractEntryRole, RecordEntry } from '@colanode/core';
+import { extractNodeRole } from '@colanode/core';
import { TableViewNameCell } from '@/renderer/components/databases/tables/table-view-name-cell';
import { RecordFieldValue } from '@/renderer/components/records/record-field-value';
import { RecordProvider } from '@/renderer/components/records/record-provider';
import { useDatabase } from '@/renderer/contexts/database';
-import { useView } from '@/renderer/contexts/view';
+import { useDatabaseView } from '@/renderer/contexts/database-view';
import { useWorkspace } from '@/renderer/contexts/workspace';
+import { LocalRecordNode } from '@/shared/types/nodes';
interface TableViewRowProps {
index: number;
- record: RecordEntry;
+ record: LocalRecordNode;
}
export const TableViewRow = ({ index, record }: TableViewRowProps) => {
const workspace = useWorkspace();
const database = useDatabase();
- const view = useView();
- const role = extractEntryRole(record, workspace.userId) ?? database.role;
+ const view = useDatabaseView();
+ const role = extractNodeRole(record, workspace.userId) ?? database.role;
return (
<RecordProvider record={record} role={role}>
diff --git a/apps/desktop/src/renderer/components/databases/tables/table-view-settings.tsx b/apps/desktop/src/renderer/components/databases/tables/table-view-settings.tsx
index bc11da7f..bb78eca0 100644
--- a/apps/desktop/src/renderer/components/databases/tables/table-view-settings.tsx
+++ b/apps/desktop/src/renderer/components/databases/tables/table-view-settings.tsx
@@ -21,12 +21,12 @@ import {
TooltipTrigger,
} from '@/renderer/components/ui/tooltip';
import { useDatabase } from '@/renderer/contexts/database';
-import { useView } from '@/renderer/contexts/view';
+import { useDatabaseView } from '@/renderer/contexts/database-view';
import { cn } from '@/shared/lib/utils';
export const TableViewSettings = () => {
const database = useDatabase();
- const view = useView();
+ const view = useDatabaseView();
const [open, setOpen] = React.useState(false);
const [openDelete, setOpenDelete] = React.useState(false);
@@ -51,7 +51,7 @@ export const TableViewSettings = () => {
id={view.id}
name={view.name}
avatar={view.avatar}
- type={view.type}
+ layout={view.layout}
className="size-4"
/>
</Button>
@@ -62,7 +62,7 @@ export const TableViewSettings = () => {
id={view.id}
name={view.name}
avatar={view.avatar}
- type={view.type}
+ layout={view.layout}
className="size-4"
/>
</Button>
diff --git a/apps/desktop/src/renderer/components/databases/view-create-dialog.tsx b/apps/desktop/src/renderer/components/databases/view-create-dialog.tsx
index 8f55c64b..c09908b4 100644
--- a/apps/desktop/src/renderer/components/databases/view-create-dialog.tsx
+++ b/apps/desktop/src/renderer/components/databases/view-create-dialog.tsx
@@ -62,7 +62,7 @@ const viewTypes: ViewTypeOption[] = [
];
const boardGroupFields: FieldType[] = ['select'];
-const calendarGroupFields: FieldType[] = ['date', 'createdAt'];
+const calendarGroupFields: FieldType[] = ['date', 'created_at'];
interface ViewCreateDialogProps {
open: boolean;
diff --git a/apps/desktop/src/renderer/components/databases/view-icon.tsx b/apps/desktop/src/renderer/components/databases/view-icon.tsx
index e541e23a..f37ccfd4 100644
--- a/apps/desktop/src/renderer/components/databases/view-icon.tsx
+++ b/apps/desktop/src/renderer/components/databases/view-icon.tsx
@@ -6,7 +6,7 @@ interface ViewIconProps {
id: string;
name: string;
avatar: string | null | undefined;
- type: 'table' | 'board' | 'calendar';
+ layout: 'table' | 'board' | 'calendar';
className?: string;
}
@@ -14,22 +14,22 @@ export const ViewIcon = ({
id,
name,
avatar,
- type,
+ layout,
className,
}: ViewIconProps) => {
if (avatar) {
return <Avatar id={id} name={name} avatar={avatar} className={className} />;
}
- if (type === 'table') {
+ if (layout === 'table') {
return <Table className={className} />;
}
- if (type === 'calendar') {
+ if (layout === 'calendar') {
return <Calendar className={className} />;
}
- if (type === 'board') {
+ if (layout === 'board') {
return <SquareKanban className={className} />;
}
diff --git a/apps/desktop/src/renderer/components/databases/view-tab.tsx b/apps/desktop/src/renderer/components/databases/view-tab.tsx
index 6cb20e13..1c8f716e 100644
--- a/apps/desktop/src/renderer/components/databases/view-tab.tsx
+++ b/apps/desktop/src/renderer/components/databases/view-tab.tsx
@@ -1,10 +1,9 @@
-import { ViewAttributes } from '@colanode/core';
-
+import { LocalDatabaseViewNode } from '@/shared/types/nodes';
import { ViewIcon } from '@/renderer/components/databases/view-icon';
import { cn } from '@/shared/lib/utils';
interface ViewTabProps {
- view: ViewAttributes;
+ view: LocalDatabaseViewNode;
isActive: boolean;
onClick: () => void;
}
@@ -22,12 +21,12 @@ export const ViewTab = ({ view, isActive, onClick }: ViewTabProps) => {
>
<ViewIcon
id={view.id}
- name={view.name}
- avatar={view.avatar}
- type={view.type}
+ name={view.attributes.name}
+ avatar={view.attributes.avatar}
+ layout={view.attributes.layout}
className="size-4"
/>
- {view.name}
+ {view.attributes.name}
</div>
);
};
diff --git a/apps/desktop/src/renderer/components/databases/view.tsx b/apps/desktop/src/renderer/components/databases/view.tsx
index 107db67f..d4d04346 100644
--- a/apps/desktop/src/renderer/components/databases/view.tsx
+++ b/apps/desktop/src/renderer/components/databases/view.tsx
@@ -1,10 +1,9 @@
import {
compareString,
SortDirection,
- ViewAttributes,
- ViewFieldFilterAttributes,
- ViewFilterAttributes,
- ViewSortAttributes,
+ DatabaseViewFieldFilterAttributes,
+ DatabaseViewFilterAttributes,
+ DatabaseViewSortAttributes,
} from '@colanode/core';
import React from 'react';
import { match } from 'ts-pattern';
@@ -13,7 +12,7 @@ import { BoardView } from '@/renderer/components/databases/boards/board-view';
import { CalendarView } from '@/renderer/components/databases/calendars/calendar-view';
import { TableView } from '@/renderer/components/databases/tables/table-view';
import { useDatabase } from '@/renderer/contexts/database';
-import { ViewContext } from '@/renderer/contexts/view';
+import { DatabaseViewContext } from '@/renderer/contexts/database-view';
import { useWorkspace } from '@/renderer/contexts/workspace';
import { useLayout } from '@/renderer/contexts/layout';
import {
@@ -26,9 +25,10 @@ import {
} from '@/shared/lib/databases';
import { ViewField } from '@/shared/types/databases';
import { toast } from '@/renderer/hooks/use-toast';
+import { LocalDatabaseViewNode } from '@/shared/types/nodes';
interface ViewProps {
- view: ViewAttributes;
+ view: LocalDatabaseViewNode;
}
export const View = ({ view }: ViewProps) => {
@@ -39,18 +39,20 @@ export const View = ({ view }: ViewProps) => {
const fields: ViewField[] = React.useMemo(() => {
return database.fields
.map((field) => {
- const viewField = view.fields?.[field.id];
+ const viewField = view.attributes.fields?.[field.id];
return {
field,
- display: viewField?.display ?? getDefaultViewFieldDisplay(view.type),
+ display:
+ viewField?.display ??
+ getDefaultViewFieldDisplay(view.attributes.layout),
index: viewField?.index ?? field.index,
width: viewField?.width ?? getDefaultFieldWidth(field.type),
};
})
.filter((field) => field.display)
.sort((a, b) => compareString(a.index, b.index));
- }, [view.id, database.fields, view.fields]);
+ }, [view.id, database.fields, view.attributes.fields]);
const [isSearchBarOpened, setIsSearchBarOpened] = React.useState(false);
const [isSortsOpened, setIsSortsOpened] = React.useState(false);
@@ -59,31 +61,31 @@ export const View = ({ view }: ViewProps) => {
);
return (
- <ViewContext.Provider
+ <DatabaseViewContext.Provider
value={{
id: view.id,
- name: view.name,
- avatar: view.avatar,
- type: view.type,
+ name: view.attributes.name,
+ avatar: view.attributes.avatar,
+ layout: view.attributes.layout,
fields,
- filters: Object.values(view.filters ?? {}),
- sorts: Object.values(view.sorts ?? {}),
- groupBy: view.groupBy,
- nameWidth: view.nameWidth ?? getDefaultNameWidth(),
+ filters: Object.values(view.attributes.filters ?? {}),
+ sorts: Object.values(view.attributes.sorts ?? {}),
+ groupBy: view.attributes.groupBy,
+ nameWidth: view.attributes.nameWidth ?? getDefaultNameWidth(),
isSearchBarOpened,
isSortsOpened,
rename: async (name: string) => {
if (!database.canEdit) return;
- const viewCopy = { ...view };
- viewCopy.name = name;
+ const viewAttributes = { ...view.attributes };
+ viewAttributes.name = name;
const result = await window.colanode.executeMutation({
type: 'view_update',
accountId: workspace.accountId,
workspaceId: workspace.id,
- databaseId: database.id,
- view: viewCopy,
+ viewId: view.id,
+ view: viewAttributes,
});
if (!result.success) {
@@ -97,15 +99,15 @@ export const View = ({ view }: ViewProps) => {
updateAvatar: async (avatar: string) => {
if (!database.canEdit) return;
- const viewCopy = { ...view };
- viewCopy.avatar = avatar;
+ const viewAttributes = { ...view.attributes };
+ viewAttributes.avatar = avatar;
const result = await window.colanode.executeMutation({
type: 'view_update',
accountId: workspace.accountId,
workspaceId: workspace.id,
- databaseId: database.id,
- view: viewCopy,
+ viewId: view.id,
+ view: viewAttributes,
});
if (!result.success) {
@@ -119,26 +121,26 @@ export const View = ({ view }: ViewProps) => {
setFieldDisplay: async (id: string, display: boolean) => {
if (!database.canEdit) return;
- const viewField = view.fields?.[id];
+ const viewField = view.attributes.fields?.[id];
if (viewField && viewField.display === display) return;
- const viewCopy = { ...view };
- viewCopy.fields = viewCopy.fields ?? {};
- if (!viewCopy.fields[id]) {
- viewCopy.fields[id] = {
+ const viewAttributes = { ...view.attributes };
+ viewAttributes.fields = viewAttributes.fields ?? {};
+ if (!viewAttributes.fields[id]) {
+ viewAttributes.fields[id] = {
id: id,
display: display,
};
} else {
- viewCopy.fields[id].display = display;
+ viewAttributes.fields[id].display = display;
}
const result = await window.colanode.executeMutation({
type: 'view_update',
accountId: workspace.accountId,
workspaceId: workspace.id,
- databaseId: database.id,
- view: viewCopy,
+ viewId: view.id,
+ view: viewAttributes,
});
if (!result.success) {
@@ -154,28 +156,28 @@ export const View = ({ view }: ViewProps) => {
return;
}
- const viewField = view.fields?.[id];
+ const viewField = view.attributes.fields?.[id];
if (viewField && viewField.width === width) {
return;
}
- const viewCopy = { ...view };
- viewCopy.fields = viewCopy.fields ?? {};
- if (!viewCopy.fields[id]) {
- viewCopy.fields[id] = {
+ const viewAttributes = { ...view.attributes };
+ viewAttributes.fields = viewAttributes.fields ?? {};
+ if (!viewAttributes.fields[id]) {
+ viewAttributes.fields[id] = {
id: id,
width: width,
};
} else {
- viewCopy.fields[id].width = width;
+ viewAttributes.fields[id].width = width;
}
const result = await window.colanode.executeMutation({
type: 'view_update',
accountId: workspace.accountId,
workspaceId: workspace.id,
- databaseId: database.id,
- view: viewCopy,
+ viewId: view.id,
+ view: viewAttributes,
});
if (!result.success) {
@@ -191,19 +193,19 @@ export const View = ({ view }: ViewProps) => {
return;
}
- if (view.nameWidth === width) {
+ if (view.attributes.nameWidth === width) {
return;
}
- const viewCopy = { ...view };
- viewCopy.nameWidth = width;
+ const viewAttributes = { ...view.attributes };
+ viewAttributes.nameWidth = width;
const result = await window.colanode.executeMutation({
type: 'view_update',
accountId: workspace.accountId,
workspaceId: workspace.id,
- databaseId: database.id,
- view: viewCopy,
+ viewId: view.id,
+ view: viewAttributes,
});
if (!result.success) {
@@ -221,7 +223,7 @@ export const View = ({ view }: ViewProps) => {
const newIndex = generateViewFieldIndex(
database.fields,
- Object.values(view.fields ?? {}),
+ Object.values(view.attributes.fields ?? {}),
id,
after
);
@@ -229,23 +231,23 @@ export const View = ({ view }: ViewProps) => {
return;
}
- const viewCopy = { ...view };
- viewCopy.fields = viewCopy.fields ?? {};
- if (!viewCopy.fields[id]) {
- viewCopy.fields[id] = {
+ const viewAttributes = { ...view.attributes };
+ viewAttributes.fields = viewAttributes.fields ?? {};
+ if (!viewAttributes.fields[id]) {
+ viewAttributes.fields[id] = {
id: id,
index: newIndex,
};
} else {
- viewCopy.fields[id].index = newIndex;
+ viewAttributes.fields[id].index = newIndex;
}
const result = await window.colanode.executeMutation({
type: 'view_update',
accountId: workspace.accountId,
workspaceId: workspace.id,
- databaseId: database.id,
- view: viewCopy,
+ viewId: view.id,
+ view: viewAttributes,
});
if (!result.success) {
@@ -263,7 +265,7 @@ export const View = ({ view }: ViewProps) => {
return;
}
- if (view.filters?.[fieldId]) {
+ if (view.attributes.filters?.[fieldId]) {
setOpenedFieldFilters((prev) => [...prev, fieldId]);
return;
}
@@ -274,23 +276,23 @@ export const View = ({ view }: ViewProps) => {
}
const operators = getFieldFilterOperators(field.type);
- const filter: ViewFieldFilterAttributes = {
+ const filter: DatabaseViewFieldFilterAttributes = {
type: 'field',
id: fieldId,
fieldId,
operator: operators[0]?.value ?? '',
};
- const viewCopy = { ...view };
- viewCopy.filters = viewCopy.filters ?? {};
- viewCopy.filters[fieldId] = filter;
+ const viewAttributes = { ...view.attributes };
+ viewAttributes.filters = viewAttributes.filters ?? {};
+ viewAttributes.filters[fieldId] = filter;
const result = await window.colanode.executeMutation({
type: 'view_update',
accountId: workspace.accountId,
workspaceId: workspace.id,
- databaseId: database.id,
- view: viewCopy,
+ viewId: view.id,
+ view: viewAttributes,
});
if (!result.success) {
@@ -303,25 +305,28 @@ export const View = ({ view }: ViewProps) => {
setOpenedFieldFilters((prev) => [...prev, fieldId]);
}
},
- updateFilter: async (id: string, filter: ViewFilterAttributes) => {
+ updateFilter: async (
+ id: string,
+ filter: DatabaseViewFilterAttributes
+ ) => {
if (!database.canEdit) {
return;
}
- if (!view.filters?.[id]) {
+ if (!view.attributes.filters?.[id]) {
return;
}
- const viewCopy = { ...view };
- viewCopy.filters = viewCopy.filters ?? {};
- viewCopy.filters[id] = filter;
+ const viewAttributes = { ...view.attributes };
+ viewAttributes.filters = viewAttributes.filters ?? {};
+ viewAttributes.filters[id] = filter;
const result = await window.colanode.executeMutation({
type: 'view_update',
accountId: workspace.accountId,
workspaceId: workspace.id,
- databaseId: database.id,
- view: viewCopy,
+ viewId: view.id,
+ view: viewAttributes,
});
if (!result.success) {
@@ -339,20 +344,20 @@ export const View = ({ view }: ViewProps) => {
return;
}
- if (!view.filters?.[id]) {
+ if (!view.attributes.filters?.[id]) {
return;
}
- const viewCopy = { ...view };
- viewCopy.filters = viewCopy.filters ?? {};
- delete viewCopy.filters[id];
+ const viewAttributes = { ...view.attributes };
+ viewAttributes.filters = viewAttributes.filters ?? {};
+ delete viewAttributes.filters[id];
const result = await window.colanode.executeMutation({
type: 'view_update',
accountId: workspace.accountId,
workspaceId: workspace.id,
- databaseId: database.id,
- view: viewCopy,
+ viewId: view.id,
+ view: viewAttributes,
});
if (!result.success) {
@@ -370,7 +375,7 @@ export const View = ({ view }: ViewProps) => {
return;
}
- const existingSort = view.sorts?.[fieldId];
+ const existingSort = view.attributes.sorts?.[fieldId];
if (existingSort && existingSort.direction === direction) {
return;
}
@@ -380,22 +385,22 @@ export const View = ({ view }: ViewProps) => {
return;
}
- const sort: ViewSortAttributes = {
+ const sort: DatabaseViewSortAttributes = {
id: fieldId,
fieldId,
direction,
};
- const viewCopy = { ...view };
- viewCopy.sorts = viewCopy.sorts ?? {};
- viewCopy.sorts[fieldId] = sort;
+ const viewAttributes = { ...view.attributes };
+ viewAttributes.sorts = viewAttributes.sorts ?? {};
+ viewAttributes.sorts[fieldId] = sort;
const result = await window.colanode.executeMutation({
type: 'view_update',
accountId: workspace.accountId,
workspaceId: workspace.id,
- databaseId: database.id,
- view: viewCopy,
+ viewId: view.id,
+ view: viewAttributes,
});
if (!result.success) {
@@ -409,25 +414,25 @@ export const View = ({ view }: ViewProps) => {
setIsSortsOpened(true);
}
},
- updateSort: async (id: string, sort: ViewSortAttributes) => {
+ updateSort: async (id: string, sort: DatabaseViewSortAttributes) => {
if (!database.canEdit) {
return;
}
- if (!view.sorts?.[id]) {
+ if (!view.attributes.sorts?.[id]) {
return;
}
- const viewCopy = { ...view };
- viewCopy.sorts = viewCopy.sorts ?? {};
- viewCopy.sorts[id] = sort;
+ const viewAttributes = { ...view.attributes };
+ viewAttributes.sorts = viewAttributes.sorts ?? {};
+ viewAttributes.sorts[id] = sort;
const result = await window.colanode.executeMutation({
type: 'view_update',
accountId: workspace.accountId,
workspaceId: workspace.id,
- databaseId: database.id,
- view: viewCopy,
+ viewId: view.id,
+ view: viewAttributes,
});
if (!result.success) {
@@ -446,20 +451,20 @@ export const View = ({ view }: ViewProps) => {
return;
}
- if (!view.sorts?.[id]) {
+ if (!view.attributes.sorts?.[id]) {
return;
}
- const viewCopy = { ...view };
- viewCopy.sorts = viewCopy.sorts ?? {};
- delete viewCopy.sorts[id];
+ const viewAttributes = { ...view.attributes };
+ viewAttributes.sorts = viewAttributes.sorts ?? {};
+ delete viewAttributes.sorts[id];
const result = await window.colanode.executeMutation({
type: 'view_update',
accountId: workspace.accountId,
workspaceId: workspace.id,
- databaseId: database.id,
- view: viewCopy,
+ viewId: view.id,
+ view: viewAttributes,
});
if (!result.success) {
@@ -491,8 +496,9 @@ export const View = ({ view }: ViewProps) => {
closeFieldFilter: (fieldId: string) => {
setOpenedFieldFilters((prev) => prev.filter((id) => id !== fieldId));
},
- createRecord: async (filters?: ViewFilterAttributes[]) => {
- const viewFilters = Object.values(view.filters ?? {}) ?? [];
+ createRecord: async (filters?: DatabaseViewFilterAttributes[]) => {
+ const viewFilters =
+ Object.values(view.attributes.filters ?? {}) ?? [];
const extraFilters = filters ?? [];
const allFilters = [...viewFilters, ...extraFilters];
@@ -522,11 +528,11 @@ export const View = ({ view }: ViewProps) => {
},
}}
>
- {match(view.type)
+ {match(view.attributes.layout)
.with('table', () => <TableView />)
.with('board', () => <BoardView />)
.with('calendar', () => <CalendarView />)
.exhaustive()}
- </ViewContext.Provider>
+ </DatabaseViewContext.Provider>
);
};
diff --git a/apps/desktop/src/renderer/components/documents/document-editor.tsx b/apps/desktop/src/renderer/components/documents/document-editor.tsx
index 1dc1b2ff..6cfff18a 100644
--- a/apps/desktop/src/renderer/components/documents/document-editor.tsx
+++ b/apps/desktop/src/renderer/components/documents/document-editor.tsx
@@ -73,7 +73,7 @@ interface DocumentEditorProps {
documentId: string;
rootId: string;
content: JSONContent;
- transactionId: string;
+ revision: bigint;
canEdit: boolean;
onUpdate: (before: JSONContent, after: JSONContent) => void;
autoFocus?: FocusPosition;
@@ -83,7 +83,7 @@ export const DocumentEditor = ({
documentId,
rootId,
content,
- transactionId,
+ revision,
canEdit,
onUpdate,
autoFocus,
@@ -91,7 +91,7 @@ export const DocumentEditor = ({
const workspace = useWorkspace();
const hasPendingChanges = React.useRef(false);
- const transactionIdRef = React.useRef(transactionId);
+ const revisionRef = React.useRef(revision);
const contentRef = React.useRef(content);
const debouncedSave = React.useMemo(
@@ -209,7 +209,7 @@ export const DocumentEditor = ({
return;
}
- if (transactionIdRef.current === transactionId) {
+ if (revisionRef.current === revision) {
return;
}
@@ -217,7 +217,7 @@ export const DocumentEditor = ({
return;
}
- transactionIdRef.current = transactionId;
+ revisionRef.current = revision;
contentRef.current = content;
const relativeSelection = getRelativeSelection(editor);
@@ -226,7 +226,7 @@ export const DocumentEditor = ({
if (relativeSelection != null) {
restoreRelativeSelection(editor, relativeSelection);
}
- }, [content, transactionId]);
+ }, [content, revision]);
return (
<div className="min-h-[500px]">
diff --git a/apps/desktop/src/renderer/components/documents/document.tsx b/apps/desktop/src/renderer/components/documents/document.tsx
index 08636384..fb34dd15 100644
--- a/apps/desktop/src/renderer/components/documents/document.tsx
+++ b/apps/desktop/src/renderer/components/documents/document.tsx
@@ -8,7 +8,7 @@ interface DocumentProps {
entryId: string;
rootId: string;
content?: Record<string, Block> | null;
- transactionId: string;
+ revision: bigint;
canEdit: boolean;
onUpdate: (before: JSONContent, after: JSONContent) => void;
autoFocus?: FocusPosition;
@@ -18,7 +18,7 @@ export const Document = ({
entryId,
rootId,
content,
- transactionId,
+ revision,
canEdit,
onUpdate,
autoFocus,
@@ -43,7 +43,7 @@ export const Document = ({
documentId={entryId}
rootId={rootId}
content={tiptapContent}
- transactionId={transactionId}
+ revision={revision}
canEdit={canEdit}
onUpdate={onUpdate}
autoFocus={autoFocus}
diff --git a/apps/desktop/src/renderer/components/files/file-body.tsx b/apps/desktop/src/renderer/components/files/file-body.tsx
index 57dd82c8..9c657b54 100644
--- a/apps/desktop/src/renderer/components/files/file-body.tsx
+++ b/apps/desktop/src/renderer/components/files/file-body.tsx
@@ -4,14 +4,29 @@ import { FilePreview } from '@/renderer/components/files/file-preview';
import { FileSidebar } from '@/renderer/components/files/file-sidebar';
import { Button } from '@/renderer/components/ui/button';
import { useWorkspace } from '@/renderer/contexts/workspace';
-import { FileWithState } from '@/shared/types/files';
+import { useQuery } from '@/renderer/hooks/use-query';
+import { LocalFileNode } from '@/shared/types/nodes';
interface FileBodyProps {
- file: FileWithState;
+ file: LocalFileNode;
}
export const FileBody = ({ file }: FileBodyProps) => {
const workspace = useWorkspace();
+ const { data, isPending } = useQuery({
+ type: 'file_get',
+ id: file.id,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
+ });
+
+ if (isPending) {
+ return <p className="text-sm text-muted-foreground">Loading...</p>;
+ }
+
+ if (!data) {
+ return <p className="text-sm text-muted-foreground">Not found</p>;
+ }
return (
<div className="flex h-full max-h-full w-full flex-row items-center gap-2">
@@ -25,8 +40,8 @@ export const FileBody = ({ file }: FileBodyProps) => {
type: 'file_open',
accountId: workspace.accountId,
workspaceId: workspace.id,
- fileId: file.id,
- extension: file.extension,
+ fileId: data.id,
+ extension: data.extension,
})
}
>
@@ -34,11 +49,11 @@ export const FileBody = ({ file }: FileBodyProps) => {
</Button>
</div>
<div className="flex w-full max-w-full flex-grow items-center justify-center overflow-hidden p-10">
- <FilePreview file={file} />
+ <FilePreview file={data} />
</div>
</div>
<div className="h-full w-72 min-w-72 overflow-hidden border-l border-gray-100 p-2 pl-3">
- <FileSidebar file={file} />
+ <FileSidebar file={data} />
</div>
</div>
);
diff --git a/apps/desktop/src/renderer/components/files/file-breadcrumb-item.tsx b/apps/desktop/src/renderer/components/files/file-breadcrumb-item.tsx
index 0225c90c..95fa43d8 100644
--- a/apps/desktop/src/renderer/components/files/file-breadcrumb-item.tsx
+++ b/apps/desktop/src/renderer/components/files/file-breadcrumb-item.tsx
@@ -1,32 +1,33 @@
import { FileThumbnail } from '@/renderer/components/files/file-thumbnail';
import { useQuery } from '@/renderer/hooks/use-query';
import { useWorkspace } from '@/renderer/contexts/workspace';
+import { LocalFileNode } from '@/shared/types/nodes';
interface FileBreadcrumbItemProps {
- id: string;
+ file: LocalFileNode;
}
-export const FileBreadcrumbItem = ({ id }: FileBreadcrumbItemProps) => {
+export const FileBreadcrumbItem = ({ file }: FileBreadcrumbItemProps) => {
const workspace = useWorkspace();
- const { data: file } = useQuery({
+ const { data } = useQuery({
type: 'file_get',
- id,
+ id: file.id,
accountId: workspace.accountId,
workspaceId: workspace.id,
});
- if (!file) {
+ if (!data) {
return null;
}
return (
<div className="flex items-center space-x-2">
<FileThumbnail
- file={file}
+ file={data}
className="size-4 overflow-hidden rounded object-contain"
/>
- <span>{file.name}</span>
+ <span>{data.name}</span>
</div>
);
};
diff --git a/apps/desktop/src/renderer/components/files/file-container.tsx b/apps/desktop/src/renderer/components/files/file-container.tsx
index 51d97a64..4154d091 100644
--- a/apps/desktop/src/renderer/components/files/file-container.tsx
+++ b/apps/desktop/src/renderer/components/files/file-container.tsx
@@ -7,21 +7,22 @@ import {
} from '@/renderer/components/ui/container';
import { ContainerBreadcrumb } from '@/renderer/components/layouts/containers/container-breadrumb';
import { FileNotFound } from '@/renderer/components/files/file-not-found';
-import { useFileContainer } from '@/renderer/hooks/use-file-container';
+import { useNodeContainer } from '@/renderer/hooks/use-node-container';
import { FileSettings } from '@/renderer/components/files/file-settings';
+import { LocalFileNode } from '@/shared/types/nodes';
interface FileContainerProps {
fileId: string;
}
export const FileContainer = ({ fileId }: FileContainerProps) => {
- const data = useFileContainer(fileId);
+ const data = useNodeContainer<LocalFileNode>(fileId);
if (data.isPending) {
return null;
}
- if (!data.file) {
+ if (!data.node) {
return <FileNotFound />;
}
@@ -30,11 +31,11 @@ export const FileContainer = ({ fileId }: FileContainerProps) => {
<ContainerHeader>
<ContainerBreadcrumb breadcrumb={data.breadcrumb} />
<ContainerSettings>
- <FileSettings file={data.file} role={data.role} />
+ <FileSettings file={data.node} role={data.role} />
</ContainerSettings>
</ContainerHeader>
<ContainerBody>
- <FileBody file={data.file} />
+ <FileBody file={data.node} />
</ContainerBody>
</Container>
);
diff --git a/apps/desktop/src/renderer/components/files/file-download.tsx b/apps/desktop/src/renderer/components/files/file-download.tsx
index f9a6acc2..95ebcaad 100644
--- a/apps/desktop/src/renderer/components/files/file-download.tsx
+++ b/apps/desktop/src/renderer/components/files/file-download.tsx
@@ -3,11 +3,11 @@ import { Download } from 'lucide-react';
import { Spinner } from '@/renderer/components/ui/spinner';
import { useWorkspace } from '@/renderer/contexts/workspace';
import { toast } from '@/renderer/hooks/use-toast';
-import { DownloadStatus, FileWithState } from '@/shared/types/files';
+import { DownloadStatus, File } from '@/shared/types/files';
import { formatBytes } from '@/shared/lib/files';
interface FileDownloadProps {
- file: FileWithState;
+ file: File;
}
export const FileDownload = ({ file }: FileDownloadProps) => {
diff --git a/apps/desktop/src/renderer/components/files/file-preview.tsx b/apps/desktop/src/renderer/components/files/file-preview.tsx
index 5800f2a2..9052d508 100644
--- a/apps/desktop/src/renderer/components/files/file-preview.tsx
+++ b/apps/desktop/src/renderer/components/files/file-preview.tsx
@@ -6,10 +6,10 @@ import { FilePreviewOther } from '@/renderer/components/files/previews/file-prev
import { FilePreviewVideo } from '@/renderer/components/files/previews/file-preview-video';
import { useWorkspace } from '@/renderer/contexts/workspace';
import { getFileUrl } from '@/shared/lib/files';
-import { FileWithState } from '@/shared/types/files';
+import { File } from '@/shared/types/files';
interface FilePreviewProps {
- file: FileWithState;
+ file: File;
}
export const FilePreview = ({ file }: FilePreviewProps) => {
diff --git a/apps/desktop/src/renderer/components/files/file-settings.tsx b/apps/desktop/src/renderer/components/files/file-settings.tsx
index e7e57fa4..3aeaa315 100644
--- a/apps/desktop/src/renderer/components/files/file-settings.tsx
+++ b/apps/desktop/src/renderer/components/files/file-settings.tsx
@@ -1,6 +1,6 @@
import { Copy, Settings, Trash2 } from 'lucide-react';
import React from 'react';
-import { EntryRole, hasEntryRole } from '@colanode/core';
+import { NodeRole, hasNodeRole } from '@colanode/core';
import { FileDeleteDialog } from '@/renderer/components/files/file-delete-dialog';
import {
@@ -9,20 +9,20 @@ import {
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/renderer/components/ui/dropdown-menu';
-import { FileWithState } from '@/shared/types/files';
import { useWorkspace } from '@/renderer/contexts/workspace';
+import { LocalFileNode } from '@/shared/types/nodes';
interface FileSettingsProps {
- file: FileWithState;
- role: EntryRole;
+ file: LocalFileNode;
+ role: NodeRole;
}
export const FileSettings = ({ file, role }: FileSettingsProps) => {
const workspace = useWorkspace();
const [showDeleteModal, setShowDeleteModal] = React.useState(false);
const canDelete =
- file.parentId === file.entryId &&
- (file.createdBy === workspace.userId || hasEntryRole(role, 'editor'));
+ file.parentId === file.parentId &&
+ (file.createdBy === workspace.userId || hasNodeRole(role, 'editor'));
return (
<React.Fragment>
diff --git a/apps/desktop/src/renderer/components/files/file-sidebar.tsx b/apps/desktop/src/renderer/components/files/file-sidebar.tsx
index 97f834b3..7ad61699 100644
--- a/apps/desktop/src/renderer/components/files/file-sidebar.tsx
+++ b/apps/desktop/src/renderer/components/files/file-sidebar.tsx
@@ -6,10 +6,10 @@ import { FileThumbnail } from '@/renderer/components/files/file-thumbnail';
import { useWorkspace } from '@/renderer/contexts/workspace';
import { useQuery } from '@/renderer/hooks/use-query';
import { formatBytes } from '@/shared/lib/files';
-import { FileWithState } from '@/shared/types/files';
+import { File } from '@/shared/types/files';
interface FileSidebarProps {
- file: FileWithState;
+ file: File;
}
const FileMeta = ({ title, value }: { title: string; value: string }) => {
diff --git a/apps/desktop/src/renderer/components/files/file-thumbnail.tsx b/apps/desktop/src/renderer/components/files/file-thumbnail.tsx
index f7d203b3..182528bc 100644
--- a/apps/desktop/src/renderer/components/files/file-thumbnail.tsx
+++ b/apps/desktop/src/renderer/components/files/file-thumbnail.tsx
@@ -2,10 +2,10 @@ import { FileIcon } from '@/renderer/components/files/file-icon';
import { useWorkspace } from '@/renderer/contexts/workspace';
import { getFileUrl } from '@/shared/lib/files';
import { cn } from '@/shared/lib/utils';
-import { FileWithState } from '@/shared/types/files';
+import { File } from '@/shared/types/files';
interface FileThumbnailProps {
- file: FileWithState;
+ file: File;
className?: string;
}
diff --git a/apps/desktop/src/renderer/components/folders/folder-body.tsx b/apps/desktop/src/renderer/components/folders/folder-body.tsx
index f08ad4eb..59675927 100644
--- a/apps/desktop/src/renderer/components/folders/folder-body.tsx
+++ b/apps/desktop/src/renderer/components/folders/folder-body.tsx
@@ -1,4 +1,4 @@
-import { EntryRole, FolderEntry } from '@colanode/core';
+import { NodeRole } from '@colanode/core';
import {
Check,
Filter,
@@ -24,6 +24,7 @@ import { ScrollArea } from '@/renderer/components/ui/scroll-area';
import { useWorkspace } from '@/renderer/contexts/workspace';
import { FolderLayoutType } from '@/shared/types/folders';
import { toast } from '@/renderer/hooks/use-toast';
+import { LocalFolderNode } from '@/shared/types/nodes';
export type FolderLayoutOption = {
value: FolderLayoutType;
@@ -54,8 +55,8 @@ export const folderLayouts: FolderLayoutOption[] = [
];
interface FolderBodyProps {
- folder: FolderEntry;
- role: EntryRole;
+ folder: LocalFolderNode;
+ role: NodeRole;
}
export const FolderBody = ({ folder }: FolderBodyProps) => {
diff --git a/apps/desktop/src/renderer/components/folders/folder-breadcrumb-item.tsx b/apps/desktop/src/renderer/components/folders/folder-breadcrumb-item.tsx
index e640cbe0..39922f23 100644
--- a/apps/desktop/src/renderer/components/folders/folder-breadcrumb-item.tsx
+++ b/apps/desktop/src/renderer/components/folders/folder-breadcrumb-item.tsx
@@ -1,26 +1,11 @@
-import { FolderEntry } from '@colanode/core';
-
import { Avatar } from '@/renderer/components/avatars/avatar';
-import { useQuery } from '@/renderer/hooks/use-query';
-import { useWorkspace } from '@/renderer/contexts/workspace';
+import { LocalFolderNode } from '@/shared/types/nodes';
interface FolderBreadcrumbItemProps {
- id: string;
+ folder: LocalFolderNode;
}
-export const FolderBreadcrumbItem = ({ id }: FolderBreadcrumbItemProps) => {
- const workspace = useWorkspace();
- const { data } = useQuery({
- type: 'entry_get',
- entryId: id,
- accountId: workspace.accountId,
- workspaceId: workspace.id,
- });
- if (!data) {
- return null;
- }
- const folder = data as FolderEntry;
-
+export const FolderBreadcrumbItem = ({ folder }: FolderBreadcrumbItemProps) => {
return (
<div className="flex items-center space-x-2">
<Avatar
diff --git a/apps/desktop/src/renderer/components/folders/folder-container-tab.tsx b/apps/desktop/src/renderer/components/folders/folder-container-tab.tsx
index 5f76ddd5..a97acc19 100644
--- a/apps/desktop/src/renderer/components/folders/folder-container-tab.tsx
+++ b/apps/desktop/src/renderer/components/folders/folder-container-tab.tsx
@@ -1,8 +1,7 @@
-import { FolderEntry } from '@colanode/core';
-
import { Avatar } from '@/renderer/components/avatars/avatar';
import { useWorkspace } from '@/renderer/contexts/workspace';
import { useQuery } from '@/renderer/hooks/use-query';
+import { LocalFolderNode } from '@/shared/types/nodes';
interface FolderContainerTabProps {
folderId: string;
@@ -12,8 +11,8 @@ export const FolderContainerTab = ({ folderId }: FolderContainerTabProps) => {
const workspace = useWorkspace();
const { data, isPending } = useQuery({
- type: 'entry_get',
- entryId: folderId,
+ type: 'node_get',
+ nodeId: folderId,
accountId: workspace.accountId,
workspaceId: workspace.id,
});
@@ -22,7 +21,7 @@ export const FolderContainerTab = ({ folderId }: FolderContainerTabProps) => {
return <p className="text-sm text-muted-foreground">Loading...</p>;
}
- const folder = data as FolderEntry;
+ const folder = data as LocalFolderNode;
if (!folder) {
return <p className="text-sm text-muted-foreground">Not found</p>;
}
diff --git a/apps/desktop/src/renderer/components/folders/folder-container.tsx b/apps/desktop/src/renderer/components/folders/folder-container.tsx
index 6dd33950..b1266da7 100644
--- a/apps/desktop/src/renderer/components/folders/folder-container.tsx
+++ b/apps/desktop/src/renderer/components/folders/folder-container.tsx
@@ -1,5 +1,3 @@
-import { FolderEntry } from '@colanode/core';
-
import { FolderNotFound } from '@/renderer/components/folders/folder-not-found';
import {
Container,
@@ -8,29 +6,30 @@ import {
ContainerSettings,
} from '@/renderer/components/ui/container';
import { ContainerBreadcrumb } from '@/renderer/components/layouts/containers/container-breadrumb';
-import { useEntryContainer } from '@/renderer/hooks/use-entry-container';
-import { useEntryRadar } from '@/renderer/hooks/use-entry-radar';
+import { useNodeContainer } from '@/renderer/hooks/use-node-container';
+import { useNodeRadar } from '@/renderer/hooks/use-node-radar';
import { FolderSettings } from '@/renderer/components/folders/folder-settings';
import { FolderBody } from '@/renderer/components/folders/folder-body';
+import { LocalFolderNode } from '@/shared/types/nodes';
interface FolderContainerProps {
folderId: string;
}
export const FolderContainer = ({ folderId }: FolderContainerProps) => {
- const data = useEntryContainer<FolderEntry>(folderId);
+ const data = useNodeContainer<LocalFolderNode>(folderId);
- useEntryRadar(data.entry);
+ useNodeRadar(data.node);
if (data.isPending) {
return null;
}
- if (!data.entry) {
+ if (!data.node) {
return <FolderNotFound />;
}
- const { entry: folder, role } = data;
+ const { node: folder, role } = data;
return (
<Container>
diff --git a/apps/desktop/src/renderer/components/folders/folder-settings.tsx b/apps/desktop/src/renderer/components/folders/folder-settings.tsx
index e3640d02..1acca423 100644
--- a/apps/desktop/src/renderer/components/folders/folder-settings.tsx
+++ b/apps/desktop/src/renderer/components/folders/folder-settings.tsx
@@ -1,8 +1,8 @@
-import { EntryRole, FolderEntry, hasEntryRole } from '@colanode/core';
+import { NodeRole, hasNodeRole } from '@colanode/core';
import { Copy, Image, LetterText, Settings, Trash2 } from 'lucide-react';
import React from 'react';
-import { EntryCollaboratorAudit } from '@/renderer/components/collaborators/entry-collaborator-audit';
+import { NodeCollaboratorAudit } from '@/renderer/components/collaborators/node-collaborator-audit';
import { FolderDeleteDialog } from '@/renderer/components/folders/folder-delete-dialog';
import { FolderUpdateDialog } from '@/renderer/components/folders/folder-update-dialog';
import {
@@ -13,18 +13,19 @@ import {
DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@/renderer/components/ui/dropdown-menu';
+import { LocalFolderNode } from '@/shared/types/nodes';
interface FolderSettingsProps {
- folder: FolderEntry;
- role: EntryRole;
+ folder: LocalFolderNode;
+ role: NodeRole;
}
export const FolderSettings = ({ folder, role }: FolderSettingsProps) => {
const [showUpdateDialog, setShowUpdateDialog] = React.useState(false);
const [showDeleteDialog, setShowDeleteModal] = React.useState(false);
- const canEdit = hasEntryRole(role, 'editor');
- const canDelete = hasEntryRole(role, 'editor');
+ const canEdit = hasNodeRole(role, 'editor');
+ const canDelete = hasNodeRole(role, 'editor');
return (
<React.Fragment>
@@ -84,7 +85,7 @@ export const FolderSettings = ({ folder, role }: FolderSettingsProps) => {
<DropdownMenuSeparator />
<DropdownMenuLabel>Created by</DropdownMenuLabel>
<DropdownMenuItem>
- <EntryCollaboratorAudit
+ <NodeCollaboratorAudit
collaboratorId={folder.createdBy}
date={folder.createdAt}
/>
@@ -94,7 +95,7 @@ export const FolderSettings = ({ folder, role }: FolderSettingsProps) => {
<DropdownMenuSeparator />
<DropdownMenuLabel>Last updated by</DropdownMenuLabel>
<DropdownMenuItem>
- <EntryCollaboratorAudit
+ <NodeCollaboratorAudit
collaboratorId={folder.updatedBy}
date={folder.updatedAt}
/>
diff --git a/apps/desktop/src/renderer/components/folders/folder-sidebar-item.tsx b/apps/desktop/src/renderer/components/folders/folder-sidebar-item.tsx
index 88741cea..4b3bf627 100644
--- a/apps/desktop/src/renderer/components/folders/folder-sidebar-item.tsx
+++ b/apps/desktop/src/renderer/components/folders/folder-sidebar-item.tsx
@@ -1,11 +1,10 @@
-import { FolderEntry } from '@colanode/core';
-
import { Avatar } from '@/renderer/components/avatars/avatar';
import { useLayout } from '@/renderer/contexts/layout';
import { cn } from '@/shared/lib/utils';
+import { LocalFolderNode } from '@/shared/types/nodes';
interface FolderSidebarItemProps {
- folder: FolderEntry;
+ folder: LocalFolderNode;
}
export const FolderSidebarItem = ({ folder }: FolderSidebarItemProps) => {
diff --git a/apps/desktop/src/renderer/components/folders/folder-update-dialog.tsx b/apps/desktop/src/renderer/components/folders/folder-update-dialog.tsx
index c744f8c7..5936419e 100644
--- a/apps/desktop/src/renderer/components/folders/folder-update-dialog.tsx
+++ b/apps/desktop/src/renderer/components/folders/folder-update-dialog.tsx
@@ -1,4 +1,4 @@
-import { EntryRole, FolderEntry, hasEntryRole } from '@colanode/core';
+import { NodeRole, hasNodeRole } from '@colanode/core';
import { FolderForm } from '@/renderer/components/folders/folder-form';
import {
@@ -11,10 +11,11 @@ import {
import { useWorkspace } from '@/renderer/contexts/workspace';
import { useMutation } from '@/renderer/hooks/use-mutation';
import { toast } from '@/renderer/hooks/use-toast';
+import { LocalFolderNode } from '@/shared/types/nodes';
interface FolderUpdateDialogProps {
- folder: FolderEntry;
- role: EntryRole;
+ folder: LocalFolderNode;
+ role: NodeRole;
open: boolean;
onOpenChange: (open: boolean) => void;
}
@@ -27,7 +28,7 @@ export const FolderUpdateDialog = ({
}: FolderUpdateDialogProps) => {
const workspace = useWorkspace();
const { mutate, isPending } = useMutation();
- const canEdit = hasEntryRole(role, 'editor');
+ const canEdit = hasNodeRole(role, 'editor');
return (
<Dialog open={open} onOpenChange={onOpenChange}>
diff --git a/apps/desktop/src/renderer/components/folders/grids/grid-file.tsx b/apps/desktop/src/renderer/components/folders/grids/grid-file.tsx
index 4315a6e9..7e82b9d4 100644
--- a/apps/desktop/src/renderer/components/folders/grids/grid-file.tsx
+++ b/apps/desktop/src/renderer/components/folders/grids/grid-file.tsx
@@ -1,10 +1,10 @@
-import { FileWithState } from '@/shared/types/files';
+import { File } from '@/shared/types/files';
import { FileContextMenu } from '@/renderer/components/files/file-context-menu';
import { FileThumbnail } from '@/renderer/components/files/file-thumbnail';
import { GridItem } from '@/renderer/components/folders/grids/grid-item';
interface GridFileProps {
- file: FileWithState;
+ file: File;
}
export const GridFile = ({ file }: GridFileProps) => {
diff --git a/apps/desktop/src/renderer/components/layouts/containers/container-breadcrumb-item.tsx b/apps/desktop/src/renderer/components/layouts/containers/container-breadcrumb-item.tsx
index 86cffb66..6de75866 100644
--- a/apps/desktop/src/renderer/components/layouts/containers/container-breadcrumb-item.tsx
+++ b/apps/desktop/src/renderer/components/layouts/containers/container-breadcrumb-item.tsx
@@ -1,5 +1,3 @@
-import { getIdType, IdType } from '@colanode/core';
-
import { ChannelBreadcrumbItem } from '@/renderer/components/channels/channel-breadcrumb-item';
import { ChatBreadcrumbItem } from '@/renderer/components/chats/chat-breadcrumb-item';
import { DatabaseBreadcrumbItem } from '@/renderer/components/databases/database-breadcrumb-item';
@@ -9,35 +7,34 @@ import { RecordBreadcrumbItem } from '@/renderer/components/records/record-bread
import { SpaceBreadcrumbItem } from '@/renderer/components/spaces/space-breadcrumb-item';
import { FileBreadcrumbItem } from '@/renderer/components/files/file-breadcrumb-item';
import { MessageBreadcrumbItem } from '@/renderer/components/messages/message-breadcrumb-item';
+import { LocalNode } from '@/shared/types/nodes';
interface ContainerBreadcrumbItemProps {
- id: string;
+ node: LocalNode;
}
export const ContainerBreadcrumbItem = ({
- id,
+ node,
}: ContainerBreadcrumbItemProps) => {
- const idType = getIdType(id);
-
- switch (idType) {
- case IdType.Space:
- return <SpaceBreadcrumbItem id={id} />;
- case IdType.Channel:
- return <ChannelBreadcrumbItem id={id} />;
- case IdType.Chat:
- return <ChatBreadcrumbItem id={id} />;
- case IdType.Page:
- return <PageBreadcrumbItem id={id} />;
- case IdType.Database:
- return <DatabaseBreadcrumbItem id={id} />;
- case IdType.Record:
- return <RecordBreadcrumbItem id={id} />;
- case IdType.Folder:
- return <FolderBreadcrumbItem id={id} />;
- case IdType.File:
- return <FileBreadcrumbItem id={id} />;
- case IdType.Message:
- return <MessageBreadcrumbItem id={id} />;
+ switch (node.type) {
+ case 'space':
+ return <SpaceBreadcrumbItem space={node} />;
+ case 'channel':
+ return <ChannelBreadcrumbItem channel={node} />;
+ case 'chat':
+ return <ChatBreadcrumbItem chat={node} />;
+ case 'page':
+ return <PageBreadcrumbItem page={node} />;
+ case 'database':
+ return <DatabaseBreadcrumbItem database={node} />;
+ case 'record':
+ return <RecordBreadcrumbItem record={node} />;
+ case 'folder':
+ return <FolderBreadcrumbItem folder={node} />;
+ case 'file':
+ return <FileBreadcrumbItem file={node} />;
+ case 'message':
+ return <MessageBreadcrumbItem message={node} />;
default:
return null;
}
diff --git a/apps/desktop/src/renderer/components/layouts/containers/container-breadrumb.tsx b/apps/desktop/src/renderer/components/layouts/containers/container-breadrumb.tsx
index 9c893fa4..30d73a29 100644
--- a/apps/desktop/src/renderer/components/layouts/containers/container-breadrumb.tsx
+++ b/apps/desktop/src/renderer/components/layouts/containers/container-breadrumb.tsx
@@ -15,9 +15,10 @@ import {
} from '@/renderer/components/ui/dropdown-menu';
import { useLayout } from '@/renderer/contexts/layout';
import { ContainerBreadcrumbItem } from '@/renderer/components/layouts/containers/container-breadcrumb-item';
+import { LocalNode } from '@/shared/types/nodes';
interface ContainerBreadcrumbProps {
- breadcrumb: string[];
+ breadcrumb: LocalNode[];
}
export const ContainerBreadcrumb = ({
@@ -47,15 +48,15 @@ export const ContainerBreadcrumb = ({
const isFirst = index === 0;
return (
- <React.Fragment key={item}>
+ <React.Fragment key={item.id}>
{!isFirst && <BreadcrumbSeparator />}
<BreadcrumbItem
className="hover:cursor-pointer hover:text-foreground"
onClick={() => {
- layout.openLeft(item);
+ layout.openLeft(item.id);
}}
>
- <ContainerBreadcrumbItem id={item} />
+ <ContainerBreadcrumbItem node={item} />
</BreadcrumbItem>
{showEllipsis && isFirst && (
<React.Fragment>
@@ -69,13 +70,13 @@ export const ContainerBreadcrumb = ({
{ellipsisItems.map((ellipsisItem) => {
return (
<DropdownMenuItem
- key={ellipsisItem}
+ key={ellipsisItem.id}
onClick={() => {
- layout.openLeft(ellipsisItem);
+ layout.openLeft(ellipsisItem.id);
}}
>
<BreadcrumbItem className="hover:cursor-pointer hover:text-foreground">
- <ContainerBreadcrumbItem id={ellipsisItem} />
+ <ContainerBreadcrumbItem node={ellipsisItem} />
</BreadcrumbItem>
</DropdownMenuItem>
);
diff --git a/apps/desktop/src/renderer/components/layouts/layout.tsx b/apps/desktop/src/renderer/components/layouts/layout.tsx
index 9a0d784e..81500803 100644
--- a/apps/desktop/src/renderer/components/layouts/layout.tsx
+++ b/apps/desktop/src/renderer/components/layouts/layout.tsx
@@ -4,7 +4,7 @@ import { ContainerTabs } from '@/renderer/components/layouts/containers/containe
import { ContainerBlank } from '@/renderer/components/layouts/containers/container-blank';
import { Sidebar } from '@/renderer/components/layouts/sidebars/sidebar';
import { LayoutContext } from '@/renderer/contexts/layout';
-import { useLayoutState } from '@/renderer/hooks/user-layout-state';
+import { useLayoutState } from '@/renderer/hooks/use-layout-state';
import { useWindowSize } from '@/renderer/hooks/use-window-size';
import { percentToNumber } from '@/shared/lib/utils';
diff --git a/apps/desktop/src/renderer/components/layouts/sidebars/sidebar-item.tsx b/apps/desktop/src/renderer/components/layouts/sidebars/sidebar-item.tsx
index effbc4dc..e6b8ba44 100644
--- a/apps/desktop/src/renderer/components/layouts/sidebars/sidebar-item.tsx
+++ b/apps/desktop/src/renderer/components/layouts/sidebars/sidebar-item.tsx
@@ -1,4 +1,3 @@
-import { Entry } from '@colanode/core';
import React from 'react';
import { ChannelSidebarItem } from '@/renderer/components/channels/channel-sidebar-item';
@@ -7,25 +6,26 @@ import { DatabaseSidebarItem } from '@/renderer/components/databases/database-si
import { FolderSidebarItem } from '@/renderer/components/folders/folder-sidebar-item';
import { PageSidebarItem } from '@/renderer/components/pages/page-sidebar-item';
import { SpaceSidebarItem } from '@/renderer/components/spaces/space-sidebar-item';
+import { LocalNode } from '@/shared/types/nodes';
interface SidebarItemProps {
- entry: Entry;
+ node: LocalNode;
}
-export const SidebarItem = ({ entry }: SidebarItemProps): React.ReactNode => {
- switch (entry.type) {
+export const SidebarItem = ({ node }: SidebarItemProps): React.ReactNode => {
+ switch (node.type) {
case 'space':
- return <SpaceSidebarItem space={entry} />;
+ return <SpaceSidebarItem space={node} />;
case 'channel':
- return <ChannelSidebarItem channel={entry} />;
+ return <ChannelSidebarItem channel={node} />;
case 'chat':
- return <ChatSidebarItem chat={entry} />;
+ return <ChatSidebarItem chat={node} />;
case 'page':
- return <PageSidebarItem page={entry} />;
+ return <PageSidebarItem page={node} />;
case 'database':
- return <DatabaseSidebarItem database={entry} />;
+ return <DatabaseSidebarItem database={node} />;
case 'folder':
- return <FolderSidebarItem folder={entry} />;
+ return <FolderSidebarItem folder={node} />;
default:
return null;
}
diff --git a/apps/desktop/src/renderer/components/messages/conversation.tsx b/apps/desktop/src/renderer/components/messages/conversation.tsx
index 4b3fcbb7..b08a20a4 100644
--- a/apps/desktop/src/renderer/components/messages/conversation.tsx
+++ b/apps/desktop/src/renderer/components/messages/conversation.tsx
@@ -1,4 +1,4 @@
-import { EntryRole, hasEntryRole } from '@colanode/core';
+import { NodeRole, hasNodeRole } from '@colanode/core';
import React from 'react';
import { InView } from 'react-intersection-observer';
@@ -14,7 +14,7 @@ import { useWorkspace } from '@/renderer/contexts/workspace';
interface ConversationProps {
conversationId: string;
rootId: string;
- role: EntryRole;
+ role: NodeRole;
}
export const Conversation = ({
@@ -72,8 +72,8 @@ export const Conversation = ({
}
};
- const isAdmin = hasEntryRole(role, 'admin');
- const canCreateMessage = hasEntryRole(role, 'commenter');
+ const isAdmin = hasNodeRole(role, 'admin');
+ const canCreateMessage = hasNodeRole(role, 'commenter');
return (
<ConversationContext.Provider
diff --git a/apps/desktop/src/renderer/components/messages/message-actions.tsx b/apps/desktop/src/renderer/components/messages/message-actions.tsx
index d04d6739..e7ed56d4 100644
--- a/apps/desktop/src/renderer/components/messages/message-actions.tsx
+++ b/apps/desktop/src/renderer/components/messages/message-actions.tsx
@@ -9,8 +9,8 @@ import { useConversation } from '@/renderer/contexts/conversation';
import { useWorkspace } from '@/renderer/contexts/workspace';
import { useMutation } from '@/renderer/hooks/use-mutation';
import { toast } from '@/renderer/hooks/use-toast';
-import { MessageNode } from '@/shared/types/messages';
import { defaultEmojis } from '@/shared/lib/assets';
+import { LocalMessageNode } from '@/shared/types/nodes';
const MessageAction = ({ children }: { children: React.ReactNode }) => {
return (
@@ -21,7 +21,7 @@ const MessageAction = ({ children }: { children: React.ReactNode }) => {
};
interface MessageActionsProps {
- message: MessageNode;
+ message: LocalMessageNode;
}
export const MessageActions = ({ message }: MessageActionsProps) => {
@@ -40,8 +40,8 @@ export const MessageActions = ({ message }: MessageActionsProps) => {
mutate({
input: {
- type: 'message_reaction_create',
- messageId: message.id,
+ type: 'node_reaction_create',
+ nodeId: message.id,
accountId: workspace.accountId,
workspaceId: workspace.id,
reaction,
@@ -94,8 +94,8 @@ export const MessageActions = ({ message }: MessageActionsProps) => {
mutate({
input: {
- type: 'message_reaction_create',
- messageId: message.id,
+ type: 'node_reaction_create',
+ nodeId: message.id,
accountId: workspace.accountId,
workspaceId: workspace.id,
reaction,
diff --git a/apps/desktop/src/renderer/components/messages/message-author-avatar.tsx b/apps/desktop/src/renderer/components/messages/message-author-avatar.tsx
index 3aa5a2de..1bea926a 100644
--- a/apps/desktop/src/renderer/components/messages/message-author-avatar.tsx
+++ b/apps/desktop/src/renderer/components/messages/message-author-avatar.tsx
@@ -1,10 +1,10 @@
import { Avatar } from '@/renderer/components/avatars/avatar';
import { useWorkspace } from '@/renderer/contexts/workspace';
import { useQuery } from '@/renderer/hooks/use-query';
-import { MessageNode } from '@/shared/types/messages';
+import { LocalMessageNode } from '@/shared/types/nodes';
interface MessageAuthorAvatarProps {
- message: MessageNode;
+ message: LocalMessageNode;
className?: string;
}
diff --git a/apps/desktop/src/renderer/components/messages/message-author-name.tsx b/apps/desktop/src/renderer/components/messages/message-author-name.tsx
index 1c70e921..04d21ed6 100644
--- a/apps/desktop/src/renderer/components/messages/message-author-name.tsx
+++ b/apps/desktop/src/renderer/components/messages/message-author-name.tsx
@@ -1,10 +1,10 @@
-import { MessageNode } from '@/shared/types/messages';
import { useWorkspace } from '@/renderer/contexts/workspace';
import { useQuery } from '@/renderer/hooks/use-query';
import { cn } from '@/shared/lib/utils';
+import { LocalMessageNode } from '@/shared/types/nodes';
interface MessageAuthorNameProps {
- message: MessageNode;
+ message: LocalMessageNode;
className?: string;
}
diff --git a/apps/desktop/src/renderer/components/messages/message-breadcrumb-item.tsx b/apps/desktop/src/renderer/components/messages/message-breadcrumb-item.tsx
index c8137449..a7eefa36 100644
--- a/apps/desktop/src/renderer/components/messages/message-breadcrumb-item.tsx
+++ b/apps/desktop/src/renderer/components/messages/message-breadcrumb-item.tsx
@@ -1,12 +1,16 @@
import { MessageCircle } from 'lucide-react';
+import { LocalMessageNode } from '@/shared/types/nodes';
+
interface MessageBreadcrumbItemProps {
- id: string;
+ message: LocalMessageNode;
}
-export const MessageBreadcrumbItem = ({ id }: MessageBreadcrumbItemProps) => {
+export const MessageBreadcrumbItem = ({
+ message,
+}: MessageBreadcrumbItemProps) => {
return (
- <div className="flex items-center space-x-2" id={id}>
+ <div className="flex items-center space-x-2" id={message.id}>
<MessageCircle className="size-4" />
<span>Message</span>
</div>
diff --git a/apps/desktop/src/renderer/components/messages/message-content.tsx b/apps/desktop/src/renderer/components/messages/message-content.tsx
index 1bfd6bec..2cd5cabe 100644
--- a/apps/desktop/src/renderer/components/messages/message-content.tsx
+++ b/apps/desktop/src/renderer/components/messages/message-content.tsx
@@ -1,13 +1,13 @@
-import { MessageNode } from '@/shared/types/messages';
import { NodeRenderer } from '@/renderer/editor/renderers/node';
import { mapBlocksToContents } from '@/shared/lib/editor';
+import { LocalMessageNode } from '@/shared/types/nodes';
interface MessageContentProps {
- message: MessageNode;
+ message: LocalMessageNode;
}
export const MessageContent = ({ message }: MessageContentProps) => {
- const nodeBlocks = Object.values(message.attributes.blocks ?? {});
+ const nodeBlocks = Object.values(message.attributes.content ?? {});
const contents = mapBlocksToContents(message.id, nodeBlocks);
return (
diff --git a/apps/desktop/src/renderer/components/messages/message-create.tsx b/apps/desktop/src/renderer/components/messages/message-create.tsx
index 80f3a2ca..61943d7b 100644
--- a/apps/desktop/src/renderer/components/messages/message-create.tsx
+++ b/apps/desktop/src/renderer/components/messages/message-create.tsx
@@ -19,9 +19,10 @@ import { useWorkspace } from '@/renderer/contexts/workspace';
import { useMutation } from '@/renderer/hooks/use-mutation';
import { toast } from '@/renderer/hooks/use-toast';
import { editorHasContent } from '@/shared/lib/editor';
-import { MessageNode } from '@/shared/types/messages';
+import { LocalMessageNode } from '@/shared/types/nodes';
+
export interface MessageCreateRefProps {
- setReplyTo: (replyTo: MessageNode) => void;
+ setReplyTo: (replyTo: LocalMessageNode) => void;
}
export const MessageCreate = React.forwardRef<MessageCreateRefProps>(
@@ -33,7 +34,7 @@ export const MessageCreate = React.forwardRef<MessageCreateRefProps>(
const messageEditorRef = React.useRef<MessageEditorRefProps>(null);
const [content, setContent] = React.useState<JSONContent | null>(null);
- const [replyTo, setReplyTo] = React.useState<MessageNode | null>(null);
+ const [replyTo, setReplyTo] = React.useState<LocalMessageNode | null>(null);
const hasContent = content != null && editorHasContent(content);
@@ -66,7 +67,7 @@ export const MessageCreate = React.forwardRef<MessageCreateRefProps>(
mutate({
input: {
type: 'message_create',
- conversationId: conversation.id,
+ parentId: conversation.id,
content: content,
accountId: workspace.accountId,
workspaceId: workspace.id,
diff --git a/apps/desktop/src/renderer/components/messages/message-reaction-count-tooltip-content.tsx b/apps/desktop/src/renderer/components/messages/message-reaction-count-tooltip-content.tsx
index bc212bab..3aa6c8f9 100644
--- a/apps/desktop/src/renderer/components/messages/message-reaction-count-tooltip-content.tsx
+++ b/apps/desktop/src/renderer/components/messages/message-reaction-count-tooltip-content.tsx
@@ -1,12 +1,12 @@
-import { MessageNode, MessageReactionCount } from '@/shared/types/messages';
import { useWorkspace } from '@/renderer/contexts/workspace';
import { useQuery } from '@/renderer/hooks/use-query';
import { useQueries } from '@/renderer/hooks/use-queries';
import { EmojiElement } from '@/renderer/components/emojis/emoji-element';
+import { NodeReactionCount, LocalMessageNode } from '@/shared/types/nodes';
interface MessageReactionCountTooltipContentProps {
- message: MessageNode;
- reactionCount: MessageReactionCount;
+ message: LocalMessageNode;
+ reactionCount: NodeReactionCount;
}
export const MessageReactionCountTooltipContent = ({
@@ -21,8 +21,8 @@ export const MessageReactionCountTooltipContent = ({
});
const { data: reactions } = useQuery({
- type: 'message_reaction_list',
- messageId: message.id,
+ type: 'node_reaction_list',
+ nodeId: message.id,
reaction: reactionCount.reaction,
accountId: workspace.accountId,
workspaceId: workspace.id,
diff --git a/apps/desktop/src/renderer/components/messages/message-reaction-count-tooltip.tsx b/apps/desktop/src/renderer/components/messages/message-reaction-count-tooltip.tsx
index 8698bc11..cb4ee02b 100644
--- a/apps/desktop/src/renderer/components/messages/message-reaction-count-tooltip.tsx
+++ b/apps/desktop/src/renderer/components/messages/message-reaction-count-tooltip.tsx
@@ -1,14 +1,14 @@
-import { MessageNode, MessageReactionCount } from '@/shared/types/messages';
import {
Tooltip,
TooltipContent,
TooltipTrigger,
} from '@/renderer/components/ui/tooltip';
import { MessageReactionCountTooltipContent } from '@/renderer/components/messages/message-reaction-count-tooltip-content';
+import { NodeReactionCount, LocalMessageNode } from '@/shared/types/nodes';
interface MessageReactionCountTooltipProps {
- message: MessageNode;
- reactionCount: MessageReactionCount;
+ message: LocalMessageNode;
+ reactionCount: NodeReactionCount;
children: React.ReactNode;
onOpen: () => void;
}
diff --git a/apps/desktop/src/renderer/components/messages/message-reaction-counts-dialog-list.tsx b/apps/desktop/src/renderer/components/messages/message-reaction-counts-dialog-list.tsx
index fb6238c7..f1fb52f3 100644
--- a/apps/desktop/src/renderer/components/messages/message-reaction-counts-dialog-list.tsx
+++ b/apps/desktop/src/renderer/components/messages/message-reaction-counts-dialog-list.tsx
@@ -1,17 +1,17 @@
import React from 'react';
import { InView } from 'react-intersection-observer';
-import { MessageNode, MessageReactionCount } from '@/shared/types/messages';
import { Avatar } from '@/renderer/components/avatars/avatar';
import { useWorkspace } from '@/renderer/contexts/workspace';
import { useQueries } from '@/renderer/hooks/use-queries';
-import { MessageReactionListQueryInput } from '@/shared/queries/messages/message-reaction-list';
+import { NodeReactionCount, LocalMessageNode } from '@/shared/types/nodes';
+import { NodeReactionListQueryInput } from '@/shared/queries/nodes/node-reaction-list';
const REACTIONS_PER_PAGE = 20;
interface MessageReactionCountsDialogListProps {
- message: MessageNode;
- reactionCount: MessageReactionCount;
+ message: LocalMessageNode;
+ reactionCount: NodeReactionCount;
}
export const MessageReactionCountsDialogList = ({
@@ -21,11 +21,11 @@ export const MessageReactionCountsDialogList = ({
const workspace = useWorkspace();
const [lastPage, setLastPage] = React.useState<number>(1);
- const inputs: MessageReactionListQueryInput[] = Array.from({
+ const inputs: NodeReactionListQueryInput[] = Array.from({
length: lastPage,
}).map((_, i) => ({
- type: 'message_reaction_list',
- messageId: message.id,
+ type: 'node_reaction_list',
+ nodeId: message.id,
reaction: reactionCount.reaction,
accountId: workspace.accountId,
workspaceId: workspace.id,
diff --git a/apps/desktop/src/renderer/components/messages/message-reaction-counts-dialog.tsx b/apps/desktop/src/renderer/components/messages/message-reaction-counts-dialog.tsx
index 78ef81d1..f50bc5e8 100644
--- a/apps/desktop/src/renderer/components/messages/message-reaction-counts-dialog.tsx
+++ b/apps/desktop/src/renderer/components/messages/message-reaction-counts-dialog.tsx
@@ -11,13 +11,13 @@ import {
TabsList,
TabsTrigger,
} from '@/renderer/components/ui/tabs';
-import { MessageNode, MessageReactionCount } from '@/shared/types/messages';
import { EmojiElement } from '@/renderer/components/emojis/emoji-element';
import { MessageReactionCountsDialogList } from '@/renderer/components/messages/message-reaction-counts-dialog-list';
+import { NodeReactionCount, LocalMessageNode } from '@/shared/types/nodes';
interface MessageReactionCountsDialogProps {
- message: MessageNode;
- reactionCounts: MessageReactionCount[];
+ message: LocalMessageNode;
+ reactionCounts: NodeReactionCount[];
open: boolean;
onOpenChange: (open: boolean) => void;
}
diff --git a/apps/desktop/src/renderer/components/messages/message-reaction-counts.tsx b/apps/desktop/src/renderer/components/messages/message-reaction-counts.tsx
index 945ba5cb..68fcbbe9 100644
--- a/apps/desktop/src/renderer/components/messages/message-reaction-counts.tsx
+++ b/apps/desktop/src/renderer/components/messages/message-reaction-counts.tsx
@@ -1,6 +1,5 @@
import React from 'react';
-import { MessageNode } from '@/shared/types/messages';
import { EmojiElement } from '@/renderer/components/emojis/emoji-element';
import { useWorkspace } from '@/renderer/contexts/workspace';
import { useMutation } from '@/renderer/hooks/use-mutation';
@@ -9,9 +8,10 @@ import { toast } from '@/renderer/hooks/use-toast';
import { useQuery } from '@/renderer/hooks/use-query';
import { MessageReactionCountTooltip } from '@/renderer/components/messages/message-reaction-count-tooltip';
import { MessageReactionCountsDialog } from '@/renderer/components/messages/message-reaction-counts-dialog';
+import { LocalMessageNode } from '@/shared/types/nodes';
interface MessageReactionCountsProps {
- message: MessageNode;
+ message: LocalMessageNode;
}
export const MessageReactionCounts = ({
@@ -23,8 +23,8 @@ export const MessageReactionCounts = ({
const { mutate, isPending } = useMutation();
const { data } = useQuery({
- type: 'message_reactions_aggregate',
- messageId: message.id,
+ type: 'node_reactions_aggregate',
+ nodeId: message.id,
accountId: workspace.accountId,
workspaceId: workspace.id,
});
@@ -66,8 +66,8 @@ export const MessageReactionCounts = ({
if (hasReacted) {
mutate({
input: {
- type: 'message_reaction_delete',
- messageId: message.id,
+ type: 'node_reaction_delete',
+ nodeId: message.id,
accountId: workspace.accountId,
workspaceId: workspace.id,
rootId: message.rootId,
@@ -84,8 +84,8 @@ export const MessageReactionCounts = ({
} else {
mutate({
input: {
- type: 'message_reaction_create',
- messageId: message.id,
+ type: 'node_reaction_create',
+ nodeId: message.id,
accountId: workspace.accountId,
workspaceId: workspace.id,
rootId: message.rootId,
diff --git a/apps/desktop/src/renderer/components/messages/message-reference.tsx b/apps/desktop/src/renderer/components/messages/message-reference.tsx
index d2d2db60..5b9f34b2 100644
--- a/apps/desktop/src/renderer/components/messages/message-reference.tsx
+++ b/apps/desktop/src/renderer/components/messages/message-reference.tsx
@@ -3,6 +3,7 @@ import { MessageAuthorName } from '@/renderer/components/messages/message-author
import { MessageContent } from '@/renderer/components/messages/message-content';
import { useWorkspace } from '@/renderer/contexts/workspace';
import { useQuery } from '@/renderer/hooks/use-query';
+import { LocalMessageNode } from '@/shared/types/nodes';
interface MessageReferenceProps {
messageId: string;
@@ -11,8 +12,8 @@ interface MessageReferenceProps {
export const MessageReference = ({ messageId }: MessageReferenceProps) => {
const workspace = useWorkspace();
const { data, isPending } = useQuery({
- type: 'message_get',
- messageId,
+ type: 'node_get',
+ nodeId: messageId,
accountId: workspace.accountId,
workspaceId: workspace.id,
});
@@ -21,6 +22,8 @@ export const MessageReference = ({ messageId }: MessageReferenceProps) => {
return null;
}
+ const message = data as LocalMessageNode;
+
if (!data) {
return (
<div className="flex flex-row gap-2 border-l-4 p-2">
@@ -33,10 +36,10 @@ export const MessageReference = ({ messageId }: MessageReferenceProps) => {
return (
<div className="flex flex-row gap-2 border-l-4 p-2">
- <MessageAuthorAvatar message={data} className="size-5 mt-1" />
+ <MessageAuthorAvatar message={message} className="size-5 mt-1" />
<div className='"flex-grow flex-col gap-1'>
- <MessageAuthorName message={data} />
- <MessageContent message={data} />
+ <MessageAuthorName message={message} />
+ <MessageContent message={message} />
</div>
</div>
);
diff --git a/apps/desktop/src/renderer/components/messages/message-reply-banner.tsx b/apps/desktop/src/renderer/components/messages/message-reply-banner.tsx
index 31e2111c..c5dcc36d 100644
--- a/apps/desktop/src/renderer/components/messages/message-reply-banner.tsx
+++ b/apps/desktop/src/renderer/components/messages/message-reply-banner.tsx
@@ -1,11 +1,11 @@
import { CircleX } from 'lucide-react';
-import { MessageNode } from '@/shared/types/messages';
import { useWorkspace } from '@/renderer/contexts/workspace';
import { useQuery } from '@/renderer/hooks/use-query';
+import { LocalMessageNode } from '@/shared/types/nodes';
interface MessageReplyBannerProps {
- message: MessageNode;
+ message: LocalMessageNode;
onCancel: () => void;
}
diff --git a/apps/desktop/src/renderer/components/messages/message-time.tsx b/apps/desktop/src/renderer/components/messages/message-time.tsx
index 5e14a57f..9088c64d 100644
--- a/apps/desktop/src/renderer/components/messages/message-time.tsx
+++ b/apps/desktop/src/renderer/components/messages/message-time.tsx
@@ -5,9 +5,10 @@ import {
TooltipContent,
TooltipTrigger,
} from '@/renderer/components/ui/tooltip';
-import { MessageNode } from '@/shared/types/messages';
+import { LocalMessageNode } from '@/shared/types/nodes';
+
interface MessageTimeProps {
- message: MessageNode;
+ message: LocalMessageNode;
}
export const MessageTime = ({ message }: MessageTimeProps) => {
diff --git a/apps/desktop/src/renderer/components/messages/message.tsx b/apps/desktop/src/renderer/components/messages/message.tsx
index 7e21a7b9..115ac0bc 100644
--- a/apps/desktop/src/renderer/components/messages/message.tsx
+++ b/apps/desktop/src/renderer/components/messages/message.tsx
@@ -9,15 +9,16 @@ import { MessageTime } from '@/renderer/components/messages/message-time';
import { MessageReference } from '@/renderer/components/messages/message-reference';
import { useRadar } from '@/renderer/contexts/radar';
import { useWorkspace } from '@/renderer/contexts/workspace';
-import { MessageNode } from '@/shared/types/messages';
+import { LocalMessageNode } from '@/shared/types/nodes';
+
interface MessageProps {
- message: MessageNode;
- previousMessage?: MessageNode | null;
+ message: LocalMessageNode;
+ previousMessage?: LocalMessageNode | null;
}
const shouldDisplayAuthor = (
- message: MessageNode,
- previousMessage?: MessageNode | null
+ message: LocalMessageNode,
+ previousMessage?: LocalMessageNode | null
) => {
if (!previousMessage) {
return true;
@@ -61,7 +62,7 @@ export const Message = ({ message, previousMessage }: MessageProps) => {
rootMargin="50px"
onChange={(inView) => {
if (inView) {
- radar.markMessageAsSeen(
+ radar.markNodeAsSeen(
workspace.accountId,
workspace.id,
message.id
diff --git a/apps/desktop/src/renderer/components/pages/page-body.tsx b/apps/desktop/src/renderer/components/pages/page-body.tsx
index b03aa3c2..b39f7494 100644
--- a/apps/desktop/src/renderer/components/pages/page-body.tsx
+++ b/apps/desktop/src/renderer/components/pages/page-body.tsx
@@ -1,20 +1,21 @@
import { useCallback } from 'react';
-import { EntryRole, PageEntry, hasEntryRole } from '@colanode/core';
+import { NodeRole, hasNodeRole } from '@colanode/core';
import { JSONContent } from '@tiptap/core';
import { Document } from '@/renderer/components/documents/document';
import { ScrollArea } from '@/renderer/components/ui/scroll-area';
import { useWorkspace } from '@/renderer/contexts/workspace';
import { toast } from '@/renderer/hooks/use-toast';
+import { LocalPageNode } from '@/shared/types/nodes';
interface PageBodyProps {
- page: PageEntry;
- role: EntryRole;
+ page: LocalPageNode;
+ role: NodeRole;
}
export const PageBody = ({ page, role }: PageBodyProps) => {
const workspace = useWorkspace();
- const canEdit = hasEntryRole(role, 'editor');
+ const canEdit = hasNodeRole(role, 'editor');
const handleUpdate = useCallback(
async (before: JSONContent, after: JSONContent) => {
@@ -44,7 +45,7 @@ export const PageBody = ({ page, role }: PageBodyProps) => {
entryId={page.id}
rootId={page.rootId}
content={page.attributes.content}
- transactionId={page.transactionId}
+ revision={page.localRevision}
canEdit={canEdit}
onUpdate={handleUpdate}
autoFocus="start"
diff --git a/apps/desktop/src/renderer/components/pages/page-breadcrumb-item.tsx b/apps/desktop/src/renderer/components/pages/page-breadcrumb-item.tsx
index adacfe66..0e46fb37 100644
--- a/apps/desktop/src/renderer/components/pages/page-breadcrumb-item.tsx
+++ b/apps/desktop/src/renderer/components/pages/page-breadcrumb-item.tsx
@@ -1,28 +1,11 @@
-import { PageEntry } from '@colanode/core';
-
import { Avatar } from '@/renderer/components/avatars/avatar';
-import { useQuery } from '@/renderer/hooks/use-query';
-import { useWorkspace } from '@/renderer/contexts/workspace';
+import { LocalPageNode } from '@/shared/types/nodes';
interface PageBreadcrumbItemProps {
- id: string;
+ page: LocalPageNode;
}
-export const PageBreadcrumbItem = ({ id }: PageBreadcrumbItemProps) => {
- const workspace = useWorkspace();
- const { data } = useQuery({
- type: 'entry_get',
- entryId: id,
- accountId: workspace.accountId,
- workspaceId: workspace.id,
- });
-
- if (!data) {
- return null;
- }
-
- const page = data as PageEntry;
-
+export const PageBreadcrumbItem = ({ page }: PageBreadcrumbItemProps) => {
return (
<div className="flex items-center space-x-2">
<Avatar
diff --git a/apps/desktop/src/renderer/components/pages/page-container-tab.tsx b/apps/desktop/src/renderer/components/pages/page-container-tab.tsx
index 605d1cfe..cd05284a 100644
--- a/apps/desktop/src/renderer/components/pages/page-container-tab.tsx
+++ b/apps/desktop/src/renderer/components/pages/page-container-tab.tsx
@@ -1,8 +1,7 @@
-import { PageEntry } from '@colanode/core';
-
import { Avatar } from '@/renderer/components/avatars/avatar';
import { useWorkspace } from '@/renderer/contexts/workspace';
import { useQuery } from '@/renderer/hooks/use-query';
+import { LocalPageNode } from '@/shared/types/nodes';
interface PageContainerTabProps {
pageId: string;
@@ -12,8 +11,8 @@ export const PageContainerTab = ({ pageId }: PageContainerTabProps) => {
const workspace = useWorkspace();
const { data, isPending } = useQuery({
- type: 'entry_get',
- entryId: pageId,
+ type: 'node_get',
+ nodeId: pageId,
accountId: workspace.accountId,
workspaceId: workspace.id,
});
@@ -22,7 +21,7 @@ export const PageContainerTab = ({ pageId }: PageContainerTabProps) => {
return <p className="text-sm text-muted-foreground">Loading...</p>;
}
- const page = data as PageEntry;
+ const page = data as LocalPageNode;
if (!page) {
return <p className="text-sm text-muted-foreground">Not found</p>;
}
diff --git a/apps/desktop/src/renderer/components/pages/page-container.tsx b/apps/desktop/src/renderer/components/pages/page-container.tsx
index 82038e47..c38b8f02 100644
--- a/apps/desktop/src/renderer/components/pages/page-container.tsx
+++ b/apps/desktop/src/renderer/components/pages/page-container.tsx
@@ -1,8 +1,6 @@
-import { PageEntry } from '@colanode/core';
-
import { PageNotFound } from '@/renderer/components/pages/page-not-found';
-import { useEntryContainer } from '@/renderer/hooks/use-entry-container';
-import { useEntryRadar } from '@/renderer/hooks/use-entry-radar';
+import { useNodeContainer } from '@/renderer/hooks/use-node-container';
+import { useNodeRadar } from '@/renderer/hooks/use-node-radar';
import { PageSettings } from '@/renderer/components/pages/page-settings';
import {
Container,
@@ -12,25 +10,26 @@ import {
} from '@/renderer/components/ui/container';
import { ContainerBreadcrumb } from '@/renderer/components/layouts/containers/container-breadrumb';
import { PageBody } from '@/renderer/components/pages/page-body';
+import { LocalPageNode } from '@/shared/types/nodes';
interface PageContainerProps {
pageId: string;
}
export const PageContainer = ({ pageId }: PageContainerProps) => {
- const data = useEntryContainer<PageEntry>(pageId);
+ const data = useNodeContainer<LocalPageNode>(pageId);
- useEntryRadar(data.entry);
+ useNodeRadar(data.node);
if (data.isPending) {
return null;
}
- if (!data.entry) {
+ if (!data.node) {
return <PageNotFound />;
}
- const { entry: page, role } = data;
+ const { node: page, role } = data;
return (
<Container>
diff --git a/apps/desktop/src/renderer/components/pages/page-settings.tsx b/apps/desktop/src/renderer/components/pages/page-settings.tsx
index 73b23507..f6b9ba44 100644
--- a/apps/desktop/src/renderer/components/pages/page-settings.tsx
+++ b/apps/desktop/src/renderer/components/pages/page-settings.tsx
@@ -1,8 +1,8 @@
-import { EntryRole, PageEntry, hasEntryRole } from '@colanode/core';
+import { NodeRole, hasNodeRole } from '@colanode/core';
import { Copy, Image, LetterText, Settings, Trash2 } from 'lucide-react';
import React from 'react';
-import { EntryCollaboratorAudit } from '@/renderer/components/collaborators/entry-collaborator-audit';
+import { NodeCollaboratorAudit } from '@/renderer/components/collaborators/node-collaborator-audit';
import { PageDeleteDialog } from '@/renderer/components/pages/page-delete-dialog';
import { PageUpdateDialog } from '@/renderer/components/pages/page-update-dialog';
import {
@@ -13,18 +13,19 @@ import {
DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@/renderer/components/ui/dropdown-menu';
+import { LocalPageNode } from '@/shared/types/nodes';
interface PageSettingsProps {
- page: PageEntry;
- role: EntryRole;
+ page: LocalPageNode;
+ role: NodeRole;
}
export const PageSettings = ({ page, role }: PageSettingsProps) => {
const [showUpdateDialog, setShowUpdateDialog] = React.useState(false);
const [showDeleteDialog, setShowDeleteModal] = React.useState(false);
- const canEdit = hasEntryRole(role, 'editor');
- const canDelete = hasEntryRole(role, 'editor');
+ const canEdit = hasNodeRole(role, 'editor');
+ const canDelete = hasNodeRole(role, 'editor');
return (
<React.Fragment>
@@ -84,7 +85,7 @@ export const PageSettings = ({ page, role }: PageSettingsProps) => {
<DropdownMenuSeparator />
<DropdownMenuLabel>Created by</DropdownMenuLabel>
<DropdownMenuItem>
- <EntryCollaboratorAudit
+ <NodeCollaboratorAudit
collaboratorId={page.createdBy}
date={page.createdAt}
/>
@@ -94,7 +95,7 @@ export const PageSettings = ({ page, role }: PageSettingsProps) => {
<DropdownMenuSeparator />
<DropdownMenuLabel>Last updated by</DropdownMenuLabel>
<DropdownMenuItem>
- <EntryCollaboratorAudit
+ <NodeCollaboratorAudit
collaboratorId={page.updatedBy}
date={page.updatedAt}
/>
diff --git a/apps/desktop/src/renderer/components/pages/page-sidebar-item.tsx b/apps/desktop/src/renderer/components/pages/page-sidebar-item.tsx
index affbf484..f38d16c8 100644
--- a/apps/desktop/src/renderer/components/pages/page-sidebar-item.tsx
+++ b/apps/desktop/src/renderer/components/pages/page-sidebar-item.tsx
@@ -1,11 +1,10 @@
-import { PageEntry } from '@colanode/core';
-
import { Avatar } from '@/renderer/components/avatars/avatar';
import { useLayout } from '@/renderer/contexts/layout';
import { cn } from '@/shared/lib/utils';
+import { LocalPageNode } from '@/shared/types/nodes';
interface PageSidebarItemProps {
- page: PageEntry;
+ page: LocalPageNode;
}
export const PageSidebarItem = ({ page }: PageSidebarItemProps) => {
diff --git a/apps/desktop/src/renderer/components/pages/page-update-dialog.tsx b/apps/desktop/src/renderer/components/pages/page-update-dialog.tsx
index 5c4199dd..377a0269 100644
--- a/apps/desktop/src/renderer/components/pages/page-update-dialog.tsx
+++ b/apps/desktop/src/renderer/components/pages/page-update-dialog.tsx
@@ -1,4 +1,4 @@
-import { EntryRole, PageEntry, hasEntryRole } from '@colanode/core';
+import { NodeRole, hasNodeRole } from '@colanode/core';
import { PageForm } from '@/renderer/components/pages/page-form';
import {
@@ -11,10 +11,11 @@ import {
import { useWorkspace } from '@/renderer/contexts/workspace';
import { useMutation } from '@/renderer/hooks/use-mutation';
import { toast } from '@/renderer/hooks/use-toast';
+import { LocalPageNode } from '@/shared/types/nodes';
interface PageUpdateDialogProps {
- page: PageEntry;
- role: EntryRole;
+ page: LocalPageNode;
+ role: NodeRole;
open: boolean;
onOpenChange: (open: boolean) => void;
}
@@ -27,7 +28,7 @@ export const PageUpdateDialog = ({
}: PageUpdateDialogProps) => {
const workspace = useWorkspace();
const { mutate, isPending } = useMutation();
- const canEdit = hasEntryRole(role, 'editor');
+ const canEdit = hasNodeRole(role, 'editor');
return (
<Dialog open={open} onOpenChange={onOpenChange}>
diff --git a/apps/desktop/src/renderer/components/records/record-body.tsx b/apps/desktop/src/renderer/components/records/record-body.tsx
index 8e1fa0cd..f99303f1 100644
--- a/apps/desktop/src/renderer/components/records/record-body.tsx
+++ b/apps/desktop/src/renderer/components/records/record-body.tsx
@@ -1,4 +1,4 @@
-import { EntryRole, hasEntryRole, RecordEntry } from '@colanode/core';
+import { NodeRole, hasNodeRole } from '@colanode/core';
import { JSONContent } from '@tiptap/core';
import { useCallback } from 'react';
@@ -10,17 +10,18 @@ import { Separator } from '@/renderer/components/ui/separator';
import { useWorkspace } from '@/renderer/contexts/workspace';
import { toast } from '@/renderer/hooks/use-toast';
import { RecordDatabase } from '@/renderer/components/records/record-database';
+import { LocalRecordNode } from '@/shared/types/nodes';
interface RecordBodyProps {
- record: RecordEntry;
- role: EntryRole;
+ record: LocalRecordNode;
+ role: NodeRole;
}
export const RecordBody = ({ record, role }: RecordBodyProps) => {
const workspace = useWorkspace();
const canEdit =
- record.createdBy === workspace.userId || hasEntryRole(role, 'editor');
+ record.createdBy === workspace.userId || hasNodeRole(role, 'editor');
const handleUpdate = useCallback(
async (before: JSONContent, after: JSONContent) => {
@@ -55,7 +56,7 @@ export const RecordBody = ({ record, role }: RecordBodyProps) => {
entryId={record.id}
rootId={record.rootId}
content={record.attributes.content}
- transactionId={record.transactionId}
+ revision={record.localRevision}
canEdit={canEdit}
onUpdate={handleUpdate}
autoFocus={false}
diff --git a/apps/desktop/src/renderer/components/records/record-breadcrumb-item.tsx b/apps/desktop/src/renderer/components/records/record-breadcrumb-item.tsx
index 9d6c84fc..de7b139a 100644
--- a/apps/desktop/src/renderer/components/records/record-breadcrumb-item.tsx
+++ b/apps/desktop/src/renderer/components/records/record-breadcrumb-item.tsx
@@ -1,25 +1,11 @@
-import { RecordEntry } from '@colanode/core';
-
import { Avatar } from '@/renderer/components/avatars/avatar';
-import { useQuery } from '@/renderer/hooks/use-query';
-import { useWorkspace } from '@/renderer/contexts/workspace';
+import { LocalRecordNode } from '@/shared/types/nodes';
interface RecordBreadcrumbItemProps {
- id: string;
+ record: LocalRecordNode;
}
-export const RecordBreadcrumbItem = ({ id }: RecordBreadcrumbItemProps) => {
- const workspace = useWorkspace();
- const { data } = useQuery({
- type: 'entry_get',
- entryId: id,
- accountId: workspace.accountId,
- workspaceId: workspace.id,
- });
- if (!data) {
- return null;
- }
- const record = data as RecordEntry;
+export const RecordBreadcrumbItem = ({ record }: RecordBreadcrumbItemProps) => {
return (
<div className="flex items-center space-x-2">
<Avatar
diff --git a/apps/desktop/src/renderer/components/records/record-container-tab.tsx b/apps/desktop/src/renderer/components/records/record-container-tab.tsx
index 4195b9b6..0cec0a2c 100644
--- a/apps/desktop/src/renderer/components/records/record-container-tab.tsx
+++ b/apps/desktop/src/renderer/components/records/record-container-tab.tsx
@@ -1,8 +1,7 @@
-import { RecordEntry } from '@colanode/core';
-
import { Avatar } from '@/renderer/components/avatars/avatar';
import { useWorkspace } from '@/renderer/contexts/workspace';
import { useQuery } from '@/renderer/hooks/use-query';
+import { LocalRecordNode } from '@/shared/types/nodes';
interface RecordContainerTabProps {
recordId: string;
@@ -11,14 +10,14 @@ interface RecordContainerTabProps {
export const RecordContainerTab = ({ recordId }: RecordContainerTabProps) => {
const workspace = useWorkspace();
- const { data: entry } = useQuery({
- type: 'entry_get',
- entryId: recordId,
+ const { data: node } = useQuery({
+ type: 'node_get',
+ nodeId: recordId,
accountId: workspace.accountId,
workspaceId: workspace.id,
});
- const record = entry as RecordEntry;
+ const record = node as LocalRecordNode;
if (!record) {
return <p>Not found</p>;
}
diff --git a/apps/desktop/src/renderer/components/records/record-container.tsx b/apps/desktop/src/renderer/components/records/record-container.tsx
index 8f063b49..fe22d4dc 100644
--- a/apps/desktop/src/renderer/components/records/record-container.tsx
+++ b/apps/desktop/src/renderer/components/records/record-container.tsx
@@ -1,8 +1,6 @@
-import { RecordEntry } from '@colanode/core';
-
import { RecordNotFound } from '@/renderer/components/records/record-not-found';
-import { useEntryContainer } from '@/renderer/hooks/use-entry-container';
-import { useEntryRadar } from '@/renderer/hooks/use-entry-radar';
+import { useNodeContainer } from '@/renderer/hooks/use-node-container';
+import { useNodeRadar } from '@/renderer/hooks/use-node-radar';
import {
Container,
ContainerBody,
@@ -12,25 +10,26 @@ import {
import { ContainerBreadcrumb } from '@/renderer/components/layouts/containers/container-breadrumb';
import { RecordBody } from '@/renderer/components/records/record-body';
import { RecordSettings } from '@/renderer/components/records/record-settings';
+import { LocalRecordNode } from '@/shared/types/nodes';
interface RecordContainerProps {
recordId: string;
}
export const RecordContainer = ({ recordId }: RecordContainerProps) => {
- const data = useEntryContainer<RecordEntry>(recordId);
+ const data = useNodeContainer<LocalRecordNode>(recordId);
- useEntryRadar(data.entry);
+ useNodeRadar(data.node);
if (data.isPending) {
return null;
}
- if (!data.entry) {
+ if (!data.node) {
return <RecordNotFound />;
}
- const { entry: record, role } = data;
+ const { node: record, role } = data;
return (
<Container>
diff --git a/apps/desktop/src/renderer/components/records/record-database.tsx b/apps/desktop/src/renderer/components/records/record-database.tsx
index f43dee2b..4f628134 100644
--- a/apps/desktop/src/renderer/components/records/record-database.tsx
+++ b/apps/desktop/src/renderer/components/records/record-database.tsx
@@ -1,12 +1,13 @@
-import { DatabaseEntry, EntryRole } from '@colanode/core';
+import { NodeRole } from '@colanode/core';
import { Database } from '@/renderer/components/databases/database';
import { useQuery } from '@/renderer/hooks/use-query';
import { useWorkspace } from '@/renderer/contexts/workspace';
+import { LocalDatabaseNode } from '@/shared/types/nodes';
interface RecordDatabaseProps {
id: string;
- role: EntryRole;
+ role: NodeRole;
children: React.ReactNode;
}
@@ -14,10 +15,10 @@ export const RecordDatabase = ({ id, role, children }: RecordDatabaseProps) => {
const workspace = useWorkspace();
const { data, isPending } = useQuery({
- type: 'entry_get',
+ type: 'node_get',
accountId: workspace.accountId,
workspaceId: workspace.id,
- entryId: id,
+ nodeId: id,
});
if (isPending) {
@@ -29,7 +30,7 @@ export const RecordDatabase = ({ id, role, children }: RecordDatabaseProps) => {
}
return (
- <Database database={data as DatabaseEntry} role={role}>
+ <Database database={data as LocalDatabaseNode} role={role}>
{children}
</Database>
);
diff --git a/apps/desktop/src/renderer/components/records/record-field-value.tsx b/apps/desktop/src/renderer/components/records/record-field-value.tsx
index 202c1eaf..ab16e4fc 100644
--- a/apps/desktop/src/renderer/components/records/record-field-value.tsx
+++ b/apps/desktop/src/renderer/components/records/record-field-value.tsx
@@ -28,9 +28,9 @@ export const RecordFieldValue = ({
switch (field.type) {
case 'boolean':
return <RecordBooleanValue field={field} readOnly={readOnly} />;
- case 'createdAt':
+ case 'created_at':
return <RecordCreatedAtValue field={field} />;
- case 'createdBy':
+ case 'created_by':
return <RecordCreatedByValue field={field} />;
case 'collaborator':
return <RecordCollaboratorValue field={field} readOnly={readOnly} />;
@@ -38,7 +38,7 @@ export const RecordFieldValue = ({
return <RecordDateValue field={field} readOnly={readOnly} />;
case 'email':
return <RecordEmailValue field={field} readOnly={readOnly} />;
- case 'multiSelect':
+ case 'multi_select':
return <RecordMultiSelectValue field={field} readOnly={readOnly} />;
case 'number':
return <RecordNumberValue field={field} readOnly={readOnly} />;
@@ -52,9 +52,9 @@ export const RecordFieldValue = ({
return <RecordTextValue field={field} readOnly={readOnly} />;
case 'url':
return <RecordUrlValue field={field} readOnly={readOnly} />;
- case 'updatedAt':
+ case 'updated_at':
return <RecordUpdatedAtValue field={field} />;
- case 'updatedBy':
+ case 'updated_by':
return <RecordUpdatedByValue field={field} />;
default:
return null;
diff --git a/apps/desktop/src/renderer/components/records/record-provider.tsx b/apps/desktop/src/renderer/components/records/record-provider.tsx
index 225d23e9..82ce4167 100644
--- a/apps/desktop/src/renderer/components/records/record-provider.tsx
+++ b/apps/desktop/src/renderer/components/records/record-provider.tsx
@@ -1,23 +1,24 @@
-import { EntryRole, RecordEntry, hasEntryRole } from '@colanode/core';
+import { NodeRole, hasNodeRole } from '@colanode/core';
import React from 'react';
import { RecordContext } from '@/renderer/contexts/record';
import { useWorkspace } from '@/renderer/contexts/workspace';
import { toast } from '@/renderer/hooks/use-toast';
+import { LocalRecordNode } from '@/shared/types/nodes';
export const RecordProvider = ({
record,
role,
children,
}: {
- record: RecordEntry;
- role: EntryRole;
+ record: LocalRecordNode;
+ role: NodeRole;
children: React.ReactNode;
}) => {
const workspace = useWorkspace();
const canEdit =
- record.createdBy === workspace.userId || hasEntryRole(role, 'editor');
+ record.createdBy === workspace.userId || hasNodeRole(role, 'editor');
return (
<RecordContext.Provider
@@ -31,6 +32,7 @@ export const RecordProvider = ({
updatedBy: record.updatedBy,
updatedAt: record.updatedAt,
databaseId: record.attributes.databaseId,
+ localRevision: record.localRevision,
canEdit,
updateFieldValue: async (field, value) => {
const result = await window.colanode.executeMutation({
@@ -77,7 +79,7 @@ export const RecordProvider = ({
},
getCollaboratorValue: (field) => {
const fieldValue = record.attributes.fields[field.id];
- if (fieldValue?.type === 'collaborator') {
+ if (fieldValue?.type === 'string_array') {
return fieldValue.value;
}
@@ -85,7 +87,7 @@ export const RecordProvider = ({
},
getDateValue: (field) => {
const fieldValue = record.attributes.fields[field.id];
- if (fieldValue?.type === 'date') {
+ if (fieldValue?.type === 'string') {
return new Date(fieldValue.value);
}
@@ -93,7 +95,7 @@ export const RecordProvider = ({
},
getEmailValue: (field) => {
const fieldValue = record.attributes.fields[field.id];
- if (fieldValue?.type === 'email') {
+ if (fieldValue?.type === 'string') {
return fieldValue.value;
}
@@ -101,7 +103,7 @@ export const RecordProvider = ({
},
getFileValue: (field) => {
const fieldValue = record.attributes.fields[field.id];
- if (fieldValue?.type === 'file') {
+ if (fieldValue?.type === 'string_array') {
return fieldValue.value;
}
@@ -109,7 +111,7 @@ export const RecordProvider = ({
},
getMultiSelectValue: (field) => {
const fieldValue = record.attributes.fields[field.id];
- if (fieldValue?.type === 'multiSelect') {
+ if (fieldValue?.type === 'string_array') {
return fieldValue.value;
}
@@ -125,7 +127,7 @@ export const RecordProvider = ({
},
getPhoneValue: (field) => {
const fieldValue = record.attributes.fields[field.id];
- if (fieldValue?.type === 'phone') {
+ if (fieldValue?.type === 'string') {
return fieldValue.value;
}
@@ -133,7 +135,7 @@ export const RecordProvider = ({
},
getRelationValue: (field) => {
const fieldValue = record.attributes.fields[field.id];
- if (fieldValue?.type === 'relation') {
+ if (fieldValue?.type === 'string_array') {
return fieldValue.value;
}
@@ -141,7 +143,7 @@ export const RecordProvider = ({
},
getRollupValue: (field) => {
const fieldValue = record.attributes.fields[field.id];
- if (fieldValue?.type === 'rollup') {
+ if (fieldValue?.type === 'string') {
return fieldValue.value;
}
@@ -149,7 +151,7 @@ export const RecordProvider = ({
},
getSelectValue: (field) => {
const fieldValue = record.attributes.fields[field.id];
- if (fieldValue?.type === 'select') {
+ if (fieldValue?.type === 'string') {
return fieldValue.value;
}
@@ -165,13 +167,12 @@ export const RecordProvider = ({
},
getUrlValue: (field) => {
const fieldValue = record.attributes.fields[field.id];
- if (fieldValue?.type === 'url') {
+ if (fieldValue?.type === 'string') {
return fieldValue.value;
}
return null;
},
- transactionId: record.transactionId,
}}
>
{children}
diff --git a/apps/desktop/src/renderer/components/records/record-search.tsx b/apps/desktop/src/renderer/components/records/record-search.tsx
index 84342597..d5b08eb7 100644
--- a/apps/desktop/src/renderer/components/records/record-search.tsx
+++ b/apps/desktop/src/renderer/components/records/record-search.tsx
@@ -1,4 +1,3 @@
-import { RecordEntry } from '@colanode/core';
import React from 'react';
import { Avatar } from '@/renderer/components/avatars/avatar';
@@ -12,10 +11,11 @@ import {
} from '@/renderer/components/ui/command';
import { useWorkspace } from '@/renderer/contexts/workspace';
import { useQuery } from '@/renderer/hooks/use-query';
+import { LocalRecordNode } from '@/shared/types/nodes';
interface RecordSearchProps {
exclude?: string[];
- onSelect: (record: RecordEntry) => void;
+ onSelect: (record: LocalRecordNode) => void;
databaseId: string;
}
diff --git a/apps/desktop/src/renderer/components/records/record-settings.tsx b/apps/desktop/src/renderer/components/records/record-settings.tsx
index 1c2ae977..8a3175b8 100644
--- a/apps/desktop/src/renderer/components/records/record-settings.tsx
+++ b/apps/desktop/src/renderer/components/records/record-settings.tsx
@@ -1,8 +1,8 @@
-import { EntryRole, RecordEntry, hasEntryRole } from '@colanode/core';
+import { NodeRole, hasNodeRole } from '@colanode/core';
import { Copy, Settings, Trash2 } from 'lucide-react';
import React from 'react';
-import { EntryCollaboratorAudit } from '@/renderer/components/collaborators/entry-collaborator-audit';
+import { NodeCollaboratorAudit } from '@/renderer/components/collaborators/node-collaborator-audit';
import { RecordDeleteDialog } from '@/renderer/components/records/record-delete-dialog';
import {
DropdownMenu,
@@ -13,17 +13,18 @@ import {
DropdownMenuTrigger,
} from '@/renderer/components/ui/dropdown-menu';
import { useWorkspace } from '@/renderer/contexts/workspace';
+import { LocalRecordNode } from '@/shared/types/nodes';
interface RecordSettingsProps {
- record: RecordEntry;
- role: EntryRole;
+ record: LocalRecordNode;
+ role: NodeRole;
}
export const RecordSettings = ({ record, role }: RecordSettingsProps) => {
const workspace = useWorkspace();
const [showDeleteDialog, setShowDeleteModal] = React.useState(false);
const canDelete =
- record.createdBy === workspace.userId || hasEntryRole(role, 'editor');
+ record.createdBy === workspace.userId || hasNodeRole(role, 'editor');
return (
<React.Fragment>
@@ -55,7 +56,7 @@ export const RecordSettings = ({ record, role }: RecordSettingsProps) => {
<DropdownMenuSeparator />
<DropdownMenuLabel>Created by</DropdownMenuLabel>
<DropdownMenuItem>
- <EntryCollaboratorAudit
+ <NodeCollaboratorAudit
collaboratorId={record.createdBy}
date={record.createdAt}
/>
@@ -65,7 +66,7 @@ export const RecordSettings = ({ record, role }: RecordSettingsProps) => {
<DropdownMenuSeparator />
<DropdownMenuLabel>Last updated by</DropdownMenuLabel>
<DropdownMenuItem>
- <EntryCollaboratorAudit
+ <NodeCollaboratorAudit
collaboratorId={record.updatedBy}
date={record.updatedAt}
/>
diff --git a/apps/desktop/src/renderer/components/records/values/record-boolean-value.tsx b/apps/desktop/src/renderer/components/records/values/record-boolean-value.tsx
index 0f8a9335..85d91ba8 100644
--- a/apps/desktop/src/renderer/components/records/values/record-boolean-value.tsx
+++ b/apps/desktop/src/renderer/components/records/values/record-boolean-value.tsx
@@ -21,7 +21,7 @@ export const RecordBooleanValue = ({
React.useEffect(() => {
setInput(record.getBooleanValue(field));
- }, [record.transactionId]);
+ }, [record.localRevision]);
return (
<div className="flex h-full w-full flex-row items-center justify-start p-0">
diff --git a/apps/desktop/src/renderer/components/records/values/record-collaborator-value.tsx b/apps/desktop/src/renderer/components/records/values/record-collaborator-value.tsx
index 60b7098a..e7b6175c 100644
--- a/apps/desktop/src/renderer/components/records/values/record-collaborator-value.tsx
+++ b/apps/desktop/src/renderer/components/records/values/record-collaborator-value.tsx
@@ -117,7 +117,7 @@ export const RecordCollaboratorValue = ({
record.removeFieldValue(field);
} else {
record.updateFieldValue(field, {
- type: 'collaborator',
+ type: 'string_array',
value: newCollaborators,
});
}
@@ -146,7 +146,7 @@ export const RecordCollaboratorValue = ({
record.removeFieldValue(field);
} else {
record.updateFieldValue(field, {
- type: 'collaborator',
+ type: 'string_array',
value: newCollaborators,
});
}
diff --git a/apps/desktop/src/renderer/components/records/values/record-date-value.tsx b/apps/desktop/src/renderer/components/records/values/record-date-value.tsx
index 54213625..419a482f 100644
--- a/apps/desktop/src/renderer/components/records/values/record-date-value.tsx
+++ b/apps/desktop/src/renderer/components/records/values/record-date-value.tsx
@@ -22,7 +22,7 @@ export const RecordDateValue = ({ field, readOnly }: RecordDateValueProps) => {
record.removeFieldValue(field);
} else {
record.updateFieldValue(field, {
- type: 'date',
+ type: 'string',
value: newValue.toISOString(),
});
}
diff --git a/apps/desktop/src/renderer/components/records/values/record-email-value.tsx b/apps/desktop/src/renderer/components/records/values/record-email-value.tsx
index 9bdc8cb6..58074d06 100644
--- a/apps/desktop/src/renderer/components/records/values/record-email-value.tsx
+++ b/apps/desktop/src/renderer/components/records/values/record-email-value.tsx
@@ -25,7 +25,7 @@ export const RecordEmailValue = ({
record.removeFieldValue(field);
} else {
record.updateFieldValue(field, {
- type: 'email',
+ type: 'string',
value: newValue,
});
}
diff --git a/apps/desktop/src/renderer/components/records/values/record-multi-select-value.tsx b/apps/desktop/src/renderer/components/records/values/record-multi-select-value.tsx
index 98c9a63a..7b6e2a24 100644
--- a/apps/desktop/src/renderer/components/records/values/record-multi-select-value.tsx
+++ b/apps/desktop/src/renderer/components/records/values/record-multi-select-value.tsx
@@ -28,7 +28,7 @@ export const RecordMultiSelectValue = ({
React.useEffect(() => {
setSelectedValues(record.getMultiSelectValue(field));
- }, [record.transactionId]);
+ }, [record.localRevision]);
const selectOptions = Object.values(field.options ?? {});
const selectedOptions = selectOptions.filter((option) =>
@@ -81,7 +81,7 @@ export const RecordMultiSelectValue = ({
record.removeFieldValue(field);
} else {
record.updateFieldValue(field, {
- type: 'multiSelect',
+ type: 'string_array',
value: newValues,
});
}
diff --git a/apps/desktop/src/renderer/components/records/values/record-phone-value.tsx b/apps/desktop/src/renderer/components/records/values/record-phone-value.tsx
index 2b3b2819..eb1cb4c6 100644
--- a/apps/desktop/src/renderer/components/records/values/record-phone-value.tsx
+++ b/apps/desktop/src/renderer/components/records/values/record-phone-value.tsx
@@ -29,7 +29,7 @@ export const RecordPhoneValue = ({
record.removeFieldValue(field);
} else {
record.updateFieldValue(field, {
- type: 'phone',
+ type: 'string',
value: newValue,
});
}
diff --git a/apps/desktop/src/renderer/components/records/values/record-relation-value.tsx b/apps/desktop/src/renderer/components/records/values/record-relation-value.tsx
index 6bcdfb08..60e54125 100644
--- a/apps/desktop/src/renderer/components/records/values/record-relation-value.tsx
+++ b/apps/desktop/src/renderer/components/records/values/record-relation-value.tsx
@@ -1,4 +1,4 @@
-import { RecordEntry, RelationFieldAttributes } from '@colanode/core';
+import { RecordNode, RelationFieldAttributes } from '@colanode/core';
import { X } from 'lucide-react';
import React from 'react';
@@ -21,7 +21,7 @@ interface RecordRelationValueProps {
readOnly?: boolean;
}
-const RelationBadge = ({ record }: { record: RecordEntry }) => {
+const RelationBadge = ({ record }: { record: RecordNode }) => {
const name = record.attributes.name ?? 'Unnamed';
return (
<div className="flex flex-row items-center gap-1">
@@ -48,14 +48,14 @@ export const RecordRelationValue = ({
const relationIds = record.getRelationValue(field) ?? [];
const results = useQueries(
relationIds.map((id) => ({
- type: 'entry_get',
- entryId: id,
+ type: 'node_get',
+ nodeId: id,
accountId: workspace.accountId,
workspaceId: workspace.id,
}))
);
- const relations: RecordEntry[] = [];
+ const relations: RecordNode[] = [];
for (const result of results) {
if (result.data && result.data.type === 'record') {
relations.push(result.data);
@@ -108,7 +108,7 @@ export const RecordRelationValue = ({
record.removeFieldValue(field);
} else {
record.updateFieldValue(field, {
- type: 'relation',
+ type: 'string_array',
value: newRelations,
});
}
@@ -138,7 +138,7 @@ export const RecordRelationValue = ({
record.removeFieldValue(field);
} else {
record.updateFieldValue(field, {
- type: 'relation',
+ type: 'string_array',
value: newRelations,
});
}
diff --git a/apps/desktop/src/renderer/components/records/values/record-select-value.tsx b/apps/desktop/src/renderer/components/records/values/record-select-value.tsx
index 844bd64b..9f0e5b7e 100644
--- a/apps/desktop/src/renderer/components/records/values/record-select-value.tsx
+++ b/apps/desktop/src/renderer/components/records/values/record-select-value.tsx
@@ -28,7 +28,7 @@ export const RecordSelectValue = ({
React.useEffect(() => {
setSelectedValue(record.getSelectValue(field));
- }, [record.transactionId]);
+ }, [record.localRevision]);
const selectedOption = field.options?.[selectedValue ?? ''];
@@ -75,7 +75,7 @@ export const RecordSelectValue = ({
record.removeFieldValue(field);
} else {
record.updateFieldValue(field, {
- type: 'select',
+ type: 'string',
value: id,
});
}
diff --git a/apps/desktop/src/renderer/components/records/values/record-url-value.tsx b/apps/desktop/src/renderer/components/records/values/record-url-value.tsx
index fdee6caa..57df6922 100644
--- a/apps/desktop/src/renderer/components/records/values/record-url-value.tsx
+++ b/apps/desktop/src/renderer/components/records/values/record-url-value.tsx
@@ -38,7 +38,7 @@ export const RecordUrlValue = ({ field, readOnly }: RecordUrlValueProps) => {
record.removeFieldValue(field);
} else {
record.updateFieldValue(field, {
- type: 'url',
+ type: 'string',
value: newValue,
});
}
diff --git a/apps/desktop/src/renderer/components/spaces/space-avatar.tsx b/apps/desktop/src/renderer/components/spaces/space-avatar.tsx
index 7188c8a3..23149220 100644
--- a/apps/desktop/src/renderer/components/spaces/space-avatar.tsx
+++ b/apps/desktop/src/renderer/components/spaces/space-avatar.tsx
@@ -1,11 +1,10 @@
-import { SpaceEntry } from '@colanode/core';
-
import { Avatar } from '@/renderer/components/avatars/avatar';
import { AvatarPopover } from '@/renderer/components/avatars/avatar-popover';
import { Button } from '@/renderer/components/ui/button';
+import { LocalSpaceNode } from '@/shared/types/nodes';
interface SpaceAvatarProps {
- space: SpaceEntry;
+ space: LocalSpaceNode;
readonly: boolean;
onUpdate: (avatar: string) => void;
}
diff --git a/apps/desktop/src/renderer/components/spaces/space-body.tsx b/apps/desktop/src/renderer/components/spaces/space-body.tsx
index d25293b2..f8814a1c 100644
--- a/apps/desktop/src/renderer/components/spaces/space-body.tsx
+++ b/apps/desktop/src/renderer/components/spaces/space-body.tsx
@@ -1,7 +1,7 @@
-import { EntryRole, hasEntryRole, SpaceEntry } from '@colanode/core';
+import { NodeRole, hasNodeRole } from '@colanode/core';
import { Info, Trash2, Users } from 'lucide-react';
-import { EntryCollaborators } from '@/renderer/components/collaborators/entry-collaborators';
+import { NodeCollaborators } from '@/renderer/components/collaborators/node-collaborators';
import { SpaceDeleteForm } from '@/renderer/components/spaces/space-delete-form';
import {
Tabs,
@@ -11,16 +11,17 @@ import {
} from '@/renderer/components/ui/tabs';
import { useLayout } from '@/renderer/contexts/layout';
import { SpaceGeneralTab } from '@/renderer/components/spaces/space-general-tab';
+import { LocalSpaceNode } from '@/shared/types/nodes';
interface SpaceBodyProps {
- space: SpaceEntry;
- role: EntryRole;
+ space: LocalSpaceNode;
+ role: NodeRole;
}
export const SpaceBody = ({ space, role }: SpaceBodyProps) => {
const layout = useLayout();
- const canEdit = hasEntryRole(role, 'admin');
- const canDelete = hasEntryRole(role, 'admin');
+ const canEdit = hasNodeRole(role, 'admin');
+ const canDelete = hasNodeRole(role, 'admin');
return (
<Tabs
@@ -68,7 +69,7 @@ export const SpaceBody = ({ space, role }: SpaceBodyProps) => {
className="focus-visible:ring-0 focus-visible:ring-offset-0"
value="collaborators"
>
- <EntryCollaborators entry={space} entries={[space]} role={role} />
+ <NodeCollaborators node={space} nodes={[space]} role={role} />
</TabsContent>
{canDelete && (
<TabsContent
diff --git a/apps/desktop/src/renderer/components/spaces/space-breadcrumb-item.tsx b/apps/desktop/src/renderer/components/spaces/space-breadcrumb-item.tsx
index a4ba4e8c..57b51da0 100644
--- a/apps/desktop/src/renderer/components/spaces/space-breadcrumb-item.tsx
+++ b/apps/desktop/src/renderer/components/spaces/space-breadcrumb-item.tsx
@@ -1,27 +1,11 @@
-import { SpaceEntry } from '@colanode/core';
-
import { Avatar } from '@/renderer/components/avatars/avatar';
-import { useQuery } from '@/renderer/hooks/use-query';
-import { useWorkspace } from '@/renderer/contexts/workspace';
+import { LocalSpaceNode } from '@/shared/types/nodes';
interface SpaceBreadcrumbItemProps {
- id: string;
+ space: LocalSpaceNode;
}
-export const SpaceBreadcrumbItem = ({ id }: SpaceBreadcrumbItemProps) => {
- const workspace = useWorkspace();
- const { data } = useQuery({
- type: 'entry_get',
- entryId: id,
- accountId: workspace.accountId,
- workspaceId: workspace.id,
- });
-
- if (!data) {
- return null;
- }
-
- const space = data as SpaceEntry;
+export const SpaceBreadcrumbItem = ({ space }: SpaceBreadcrumbItemProps) => {
return (
<div className="flex items-center space-x-2">
<Avatar
diff --git a/apps/desktop/src/renderer/components/spaces/space-container-tab.tsx b/apps/desktop/src/renderer/components/spaces/space-container-tab.tsx
index 217598cb..775aca1f 100644
--- a/apps/desktop/src/renderer/components/spaces/space-container-tab.tsx
+++ b/apps/desktop/src/renderer/components/spaces/space-container-tab.tsx
@@ -1,8 +1,7 @@
-import { SpaceEntry } from '@colanode/core';
-
import { Avatar } from '@/renderer/components/avatars/avatar';
import { useWorkspace } from '@/renderer/contexts/workspace';
import { useQuery } from '@/renderer/hooks/use-query';
+import { LocalSpaceNode } from '@/shared/types/nodes';
interface SpaceContainerTabProps {
spaceId: string;
@@ -12,8 +11,8 @@ export const SpaceContainerTab = ({ spaceId }: SpaceContainerTabProps) => {
const workspace = useWorkspace();
const { data, isPending } = useQuery({
- type: 'entry_get',
- entryId: spaceId,
+ type: 'node_get',
+ nodeId: spaceId,
accountId: workspace.accountId,
workspaceId: workspace.id,
});
@@ -22,7 +21,7 @@ export const SpaceContainerTab = ({ spaceId }: SpaceContainerTabProps) => {
return <p className="text-sm text-muted-foreground">Loading...</p>;
}
- const space = data as SpaceEntry;
+ const space = data as LocalSpaceNode;
if (!space) {
return <p className="text-sm text-muted-foreground">Not found</p>;
}
diff --git a/apps/desktop/src/renderer/components/spaces/space-container.tsx b/apps/desktop/src/renderer/components/spaces/space-container.tsx
index 652091fe..4c5fc3ad 100644
--- a/apps/desktop/src/renderer/components/spaces/space-container.tsx
+++ b/apps/desktop/src/renderer/components/spaces/space-container.tsx
@@ -1,5 +1,3 @@
-import { SpaceEntry } from '@colanode/core';
-
import {
Container,
ContainerBody,
@@ -7,28 +5,29 @@ import {
} from '@/renderer/components/ui/container';
import { ContainerBreadcrumb } from '@/renderer/components/layouts/containers/container-breadrumb';
import { SpaceNotFound } from '@/renderer/components/spaces/space-not-found';
-import { useEntryRadar } from '@/renderer/hooks/use-entry-radar';
-import { useEntryContainer } from '@/renderer/hooks/use-entry-container';
+import { useNodeRadar } from '@/renderer/hooks/use-node-radar';
+import { useNodeContainer } from '@/renderer/hooks/use-node-container';
import { SpaceBody } from '@/renderer/components/spaces/space-body';
+import { LocalSpaceNode } from '@/shared/types/nodes';
interface SpaceContainerProps {
spaceId: string;
}
export const SpaceContainer = ({ spaceId }: SpaceContainerProps) => {
- const data = useEntryContainer<SpaceEntry>(spaceId);
+ const data = useNodeContainer<LocalSpaceNode>(spaceId);
- useEntryRadar(data.entry);
+ useNodeRadar(data.node);
if (data.isPending) {
return null;
}
- if (!data.entry) {
+ if (!data.node) {
return <SpaceNotFound />;
}
- const { entry, role } = data;
+ const { node, role } = data;
return (
<Container>
@@ -36,7 +35,7 @@ export const SpaceContainer = ({ spaceId }: SpaceContainerProps) => {
<ContainerBreadcrumb breadcrumb={data.breadcrumb} />
</ContainerHeader>
<ContainerBody>
- <SpaceBody space={entry} role={role} />
+ <SpaceBody space={node} role={role} />
</ContainerBody>
</Container>
);
diff --git a/apps/desktop/src/renderer/components/spaces/space-description.tsx b/apps/desktop/src/renderer/components/spaces/space-description.tsx
index 5b6395ae..d06cac88 100644
--- a/apps/desktop/src/renderer/components/spaces/space-description.tsx
+++ b/apps/desktop/src/renderer/components/spaces/space-description.tsx
@@ -1,10 +1,10 @@
-import { SpaceEntry } from '@colanode/core';
import { useEffect, useRef } from 'react';
import { SmartTextarea } from '@/renderer/components/ui/smart-textarea';
+import { LocalSpaceNode } from '@/shared/types/nodes';
interface SpaceDescriptionProps {
- space: SpaceEntry;
+ space: LocalSpaceNode;
readonly: boolean;
onUpdate: (description: string) => void;
}
diff --git a/apps/desktop/src/renderer/components/spaces/space-general-tab.tsx b/apps/desktop/src/renderer/components/spaces/space-general-tab.tsx
index b5777785..db63fdd2 100644
--- a/apps/desktop/src/renderer/components/spaces/space-general-tab.tsx
+++ b/apps/desktop/src/renderer/components/spaces/space-general-tab.tsx
@@ -1,14 +1,13 @@
-import { SpaceEntry } from '@colanode/core';
-
import { SpaceAvatar } from '@/renderer/components/spaces/space-avatar';
import { SpaceDescription } from '@/renderer/components/spaces/space-description';
import { SpaceName } from '@/renderer/components/spaces/space-name';
import { useWorkspace } from '@/renderer/contexts/workspace';
import { useMutation } from '@/renderer/hooks/use-mutation';
import { toast } from '@/renderer/hooks/use-toast';
+import { LocalSpaceNode } from '@/shared/types/nodes';
interface SpaceGeneralTabProps {
- space: SpaceEntry;
+ space: LocalSpaceNode;
readonly: boolean;
}
diff --git a/apps/desktop/src/renderer/components/spaces/space-name.tsx b/apps/desktop/src/renderer/components/spaces/space-name.tsx
index 6fc871bc..28629826 100644
--- a/apps/desktop/src/renderer/components/spaces/space-name.tsx
+++ b/apps/desktop/src/renderer/components/spaces/space-name.tsx
@@ -1,10 +1,10 @@
-import { SpaceEntry } from '@colanode/core';
import { useEffect, useRef } from 'react';
import { SmartTextInput } from '@/renderer/components/ui/smart-text-input';
+import { LocalSpaceNode } from '@/shared/types/nodes';
interface SpaceNameProps {
- space: SpaceEntry;
+ space: LocalSpaceNode;
readonly: boolean;
onUpdate: (name: string) => void;
}
diff --git a/apps/desktop/src/renderer/components/spaces/space-sidebar-item.tsx b/apps/desktop/src/renderer/components/spaces/space-sidebar-item.tsx
index f60277a4..2873c7d7 100644
--- a/apps/desktop/src/renderer/components/spaces/space-sidebar-item.tsx
+++ b/apps/desktop/src/renderer/components/spaces/space-sidebar-item.tsx
@@ -1,4 +1,4 @@
-import { compareString, SpaceEntry } from '@colanode/core';
+import { compareString } from '@colanode/core';
import {
ChevronRight,
Database,
@@ -34,9 +34,10 @@ import { useWorkspace } from '@/renderer/contexts/workspace';
import { useQuery } from '@/renderer/hooks/use-query';
import { cn } from '@/shared/lib/utils';
import { useLayout } from '@/renderer/contexts/layout';
+import { LocalSpaceNode } from '@/shared/types/nodes';
interface SpaceSidebarItemProps {
- space: SpaceEntry;
+ space: LocalSpaceNode;
}
export const SpaceSidebarItem = ({ space }: SpaceSidebarItemProps) => {
@@ -44,8 +45,8 @@ export const SpaceSidebarItem = ({ space }: SpaceSidebarItemProps) => {
const layout = useLayout();
const { data } = useQuery({
- type: 'entry_children_get',
- entryId: space.id,
+ type: 'node_children_get',
+ nodeId: space.id,
accountId: workspace.accountId,
workspaceId: workspace.id,
types: ['page', 'channel', 'database', 'folder'],
@@ -151,7 +152,7 @@ export const SpaceSidebarItem = ({ space }: SpaceSidebarItemProps) => {
'bg-sidebar-accent text-sidebar-accent-foreground font-medium'
)}
>
- <SidebarItem entry={child} />
+ <SidebarItem node={child} />
</div>
</li>
))}
diff --git a/apps/desktop/src/renderer/contexts/conversation.ts b/apps/desktop/src/renderer/contexts/conversation.ts
index 326717c8..7994173e 100644
--- a/apps/desktop/src/renderer/contexts/conversation.ts
+++ b/apps/desktop/src/renderer/contexts/conversation.ts
@@ -1,16 +1,16 @@
-import { EntryRole } from '@colanode/core';
+import { NodeRole } from '@colanode/core';
import { createContext, useContext } from 'react';
-import { MessageNode } from '@/shared/types/messages';
+import { LocalMessageNode } from '@/shared/types/nodes';
interface ConversationContext {
id: string;
rootId: string;
- role: EntryRole;
+ role: NodeRole;
canCreateMessage: boolean;
- onReply: (message: MessageNode) => void;
+ onReply: (message: LocalMessageNode) => void;
onLastMessageIdChange: (id: string) => void;
- canDeleteMessage: (message: MessageNode) => boolean;
+ canDeleteMessage: (message: LocalMessageNode) => boolean;
}
export const ConversationContext = createContext<ConversationContext>(
diff --git a/apps/desktop/src/renderer/contexts/view.ts b/apps/desktop/src/renderer/contexts/database-view.ts
similarity index 64%
rename from apps/desktop/src/renderer/contexts/view.ts
rename to apps/desktop/src/renderer/contexts/database-view.ts
index 02939741..f4d7264e 100644
--- a/apps/desktop/src/renderer/contexts/view.ts
+++ b/apps/desktop/src/renderer/contexts/database-view.ts
@@ -1,21 +1,21 @@
import {
SortDirection,
- ViewFilterAttributes,
- ViewSortAttributes,
- ViewType,
+ DatabaseViewFilterAttributes,
+ DatabaseViewSortAttributes,
+ DatabaseViewLayout,
} from '@colanode/core';
import { createContext, useContext } from 'react';
import { ViewField } from '@/shared/types/databases';
-interface ViewContext {
+interface DatabaseViewContext {
id: string;
name: string;
avatar: string | null | undefined;
- type: ViewType;
+ layout: DatabaseViewLayout;
fields: ViewField[];
- filters: ViewFilterAttributes[];
- sorts: ViewSortAttributes[];
+ filters: DatabaseViewFilterAttributes[];
+ sorts: DatabaseViewSortAttributes[];
groupBy: string | null | undefined;
nameWidth: number;
isSearchBarOpened: boolean;
@@ -28,10 +28,10 @@ interface ViewContext {
moveField: (id: string, after: string) => void;
isFieldFilterOpened: (fieldId: string) => boolean;
initFieldFilter: (fieldId: string) => void;
- updateFilter: (id: string, filter: ViewFilterAttributes) => void;
+ updateFilter: (id: string, filter: DatabaseViewFilterAttributes) => void;
removeFilter: (id: string) => void;
initFieldSort: (fieldId: string, direction: SortDirection) => void;
- updateSort: (id: string, sort: ViewSortAttributes) => void;
+ updateSort: (id: string, sort: DatabaseViewSortAttributes) => void;
removeSort: (id: string) => void;
openSearchBar: () => void;
closeSearchBar: () => void;
@@ -39,9 +39,11 @@ interface ViewContext {
closeSorts: () => void;
openFieldFilter: (fieldId: string) => void;
closeFieldFilter: (fieldId: string) => void;
- createRecord: (filters?: ViewFilterAttributes[]) => void;
+ createRecord: (filters?: DatabaseViewFilterAttributes[]) => void;
}
-export const ViewContext = createContext<ViewContext>({} as ViewContext);
+export const DatabaseViewContext = createContext<DatabaseViewContext>(
+ {} as DatabaseViewContext
+);
-export const useView = () => useContext(ViewContext);
+export const useDatabaseView = () => useContext(DatabaseViewContext);
diff --git a/apps/desktop/src/renderer/contexts/database-views.ts b/apps/desktop/src/renderer/contexts/database-views.ts
index be572008..3653f8b1 100644
--- a/apps/desktop/src/renderer/contexts/database-views.ts
+++ b/apps/desktop/src/renderer/contexts/database-views.ts
@@ -1,8 +1,9 @@
-import { ViewAttributes } from '@colanode/core';
import { createContext, useContext } from 'react';
+import { LocalDatabaseViewNode } from '@/shared/types/nodes';
+
interface DatabaseViewsContext {
- views: ViewAttributes[];
+ views: LocalDatabaseViewNode[];
activeViewId: string;
setActiveViewId: (viewId: string) => void;
}
diff --git a/apps/desktop/src/renderer/contexts/database.ts b/apps/desktop/src/renderer/contexts/database.ts
index 4ddde445..bb6f91c9 100644
--- a/apps/desktop/src/renderer/contexts/database.ts
+++ b/apps/desktop/src/renderer/contexts/database.ts
@@ -1,9 +1,8 @@
import {
FieldAttributes,
FieldType,
- EntryRole,
+ NodeRole,
SelectOptionAttributes,
- ViewAttributes,
} from '@colanode/core';
import { createContext, useContext } from 'react';
@@ -11,10 +10,9 @@ interface DatabaseContext {
id: string;
name: string;
fields: FieldAttributes[];
- views: ViewAttributes[];
canEdit: boolean;
canCreateRecord: boolean;
- role: EntryRole;
+ role: NodeRole;
createField: (type: FieldType, name: string) => void;
renameField: (id: string, name: string) => void;
deleteField: (id: string) => void;
diff --git a/apps/desktop/src/renderer/contexts/folder.ts b/apps/desktop/src/renderer/contexts/folder.ts
index ca1aaa92..1105826a 100644
--- a/apps/desktop/src/renderer/contexts/folder.ts
+++ b/apps/desktop/src/renderer/contexts/folder.ts
@@ -1,11 +1,11 @@
import { createContext, useContext } from 'react';
-import { FileWithState } from '@/shared/types/files';
+import { File } from '@/shared/types/files';
interface FolderContext {
id: string;
name: string;
- files: FileWithState[];
+ files: File[];
onClick: (event: React.MouseEvent<HTMLElement>, id: string) => void;
onDoubleClick: (event: React.MouseEvent<HTMLElement>, id: string) => void;
onMove: (entryId: string, targetId: string) => void;
diff --git a/apps/desktop/src/renderer/contexts/radar.ts b/apps/desktop/src/renderer/contexts/radar.ts
index bc5c11e3..3aa50859 100644
--- a/apps/desktop/src/renderer/contexts/radar.ts
+++ b/apps/desktop/src/renderer/contexts/radar.ts
@@ -23,30 +23,15 @@ interface RadarContext {
workspaceId: string,
entryId: string
) => ChannelReadState;
- markMessageAsSeen: (
+ markNodeAsSeen: (
accountId: string,
workspaceId: string,
- messageId: string
+ nodeId: string
) => void;
- markFileAsSeen: (
+ markNodeAsOpened: (
accountId: string,
workspaceId: string,
- fileId: string
- ) => void;
- markFileAsOpened: (
- accountId: string,
- workspaceId: string,
- fileId: string
- ) => void;
- markEntryAsSeen: (
- accountId: string,
- workspaceId: string,
- entryId: string
- ) => void;
- markEntryAsOpened: (
- accountId: string,
- workspaceId: string,
- entryId: string
+ nodeId: string
) => void;
}
diff --git a/apps/desktop/src/renderer/contexts/record.ts b/apps/desktop/src/renderer/contexts/record.ts
index 94d334d2..078c06a6 100644
--- a/apps/desktop/src/renderer/contexts/record.ts
+++ b/apps/desktop/src/renderer/contexts/record.ts
@@ -26,9 +26,9 @@ interface RecordContext {
createdAt: string;
updatedBy?: string | null;
updatedAt?: string | null;
- transactionId: string;
databaseId: string;
canEdit: boolean;
+ localRevision: bigint;
updateFieldValue: (field: FieldAttributes, value: FieldValue) => void;
removeFieldValue: (field: FieldAttributes) => void;
getBooleanValue: (field: BooleanFieldAttributes) => boolean;
diff --git a/apps/desktop/src/renderer/editor/views/database.tsx b/apps/desktop/src/renderer/editor/views/database.tsx
index cb4a462e..ff79d4d7 100644
--- a/apps/desktop/src/renderer/editor/views/database.tsx
+++ b/apps/desktop/src/renderer/editor/views/database.tsx
@@ -12,8 +12,8 @@ export const DatabaseNodeView = ({ node }: NodeViewProps) => {
const id = node.attrs.id;
const { data } = useQuery({
- type: 'entry_get',
- entryId: id,
+ type: 'node_get',
+ nodeId: id,
accountId: workspace.accountId,
workspaceId: workspace.id,
});
diff --git a/apps/desktop/src/renderer/editor/views/folder.tsx b/apps/desktop/src/renderer/editor/views/folder.tsx
index 5b37e35f..efbf87f3 100644
--- a/apps/desktop/src/renderer/editor/views/folder.tsx
+++ b/apps/desktop/src/renderer/editor/views/folder.tsx
@@ -12,8 +12,8 @@ export const FolderNodeView = ({ node }: NodeViewProps) => {
const id = node.attrs.id;
const { data } = useQuery({
- type: 'entry_get',
- entryId: id,
+ type: 'node_get',
+ nodeId: id,
accountId: workspace.accountId,
workspaceId: workspace.id,
});
diff --git a/apps/desktop/src/renderer/editor/views/page.tsx b/apps/desktop/src/renderer/editor/views/page.tsx
index fb5a39d4..1c0e18d2 100644
--- a/apps/desktop/src/renderer/editor/views/page.tsx
+++ b/apps/desktop/src/renderer/editor/views/page.tsx
@@ -12,8 +12,8 @@ export const PageNodeView = ({ node }: NodeViewProps) => {
const id = node.attrs.id;
const { data } = useQuery({
- type: 'entry_get',
- entryId: id,
+ type: 'node_get',
+ nodeId: id,
accountId: workspace.accountId,
workspaceId: workspace.id,
});
diff --git a/apps/desktop/src/renderer/hooks/use-entry-container.tsx b/apps/desktop/src/renderer/hooks/use-entry-container.tsx
deleted file mode 100644
index eeb67d66..00000000
--- a/apps/desktop/src/renderer/hooks/use-entry-container.tsx
+++ /dev/null
@@ -1,109 +0,0 @@
-import { Entry, EntryRole, extractEntryRole } from '@colanode/core';
-
-import { useWorkspace } from '@/renderer/contexts/workspace';
-import { useQuery } from '@/renderer/hooks/use-query';
-
-type UseEntryContainerResult<T extends Entry> =
- | {
- isPending: true;
- entry: null;
- }
- | {
- isPending: false;
- entry: null;
- }
- | {
- isPending: false;
- entry: T;
- breadcrumb: string[];
- root: Entry;
- role: EntryRole;
- };
-
-export const useEntryContainer = <T extends Entry>(
- id: string
-): UseEntryContainerResult<T> => {
- const workspace = useWorkspace();
-
- const { data: entryData, isPending: isPendingEntry } = useQuery({
- type: 'entry_get',
- entryId: id,
- accountId: workspace.accountId,
- workspaceId: workspace.id,
- });
-
- const entryExists = !!entryData;
- const isRoot = entryData?.rootId === id;
-
- const { data: rootData, isPending: isPendingRoot } = useQuery(
- {
- type: 'entry_get',
- entryId: entryData?.rootId ?? '',
- accountId: workspace.accountId,
- workspaceId: workspace.id,
- },
- {
- enabled: entryExists && !isRoot,
- }
- );
-
- const { data: breadcrumbData, isPending: isPendingBreadcrumb } = useQuery(
- {
- type: 'entry_breadcrumb_get',
- entryId: id,
- accountId: workspace.accountId,
- workspaceId: workspace.id,
- },
- {
- enabled: entryExists && !isRoot,
- }
- );
-
- const isPending =
- isPendingEntry ||
- (entryExists && !isRoot && (isPendingRoot || isPendingBreadcrumb));
-
- if (isPending) {
- return { isPending: true, entry: null };
- }
-
- if (!entryExists) {
- return { isPending: false, entry: null };
- }
-
- if (isRoot) {
- const role = extractEntryRole(entryData, workspace.userId);
- if (!role) {
- return { isPending: false, entry: null };
- }
-
- return {
- isPending: false,
- entry: entryData as T,
- root: entryData,
- breadcrumb: [entryData.id],
- role,
- };
- }
-
- if (!rootData) {
- return { isPending: false, entry: null };
- }
-
- if (!breadcrumbData || breadcrumbData.length === 0) {
- return { isPending: false, entry: null };
- }
-
- const role = extractEntryRole(rootData, workspace.userId);
- if (!role) {
- return { isPending: false, entry: null };
- }
-
- return {
- isPending: false,
- entry: entryData as T,
- root: rootData,
- breadcrumb: breadcrumbData,
- role,
- };
-};
diff --git a/apps/desktop/src/renderer/hooks/use-file-container.tsx b/apps/desktop/src/renderer/hooks/use-file-container.tsx
deleted file mode 100644
index ba3d1675..00000000
--- a/apps/desktop/src/renderer/hooks/use-file-container.tsx
+++ /dev/null
@@ -1,91 +0,0 @@
-import { Entry, EntryRole, extractEntryRole } from '@colanode/core';
-
-import { useWorkspace } from '@/renderer/contexts/workspace';
-import { useQuery } from '@/renderer/hooks/use-query';
-import { FileWithState } from '@/shared/types/files';
-
-type UseFileContainerResult =
- | {
- isPending: true;
- file: null;
- }
- | {
- isPending: false;
- file: null;
- }
- | {
- isPending: false;
- file: FileWithState;
- breadcrumb: string[];
- root: Entry;
- role: EntryRole;
- };
-
-export const useFileContainer = (id: string): UseFileContainerResult => {
- const workspace = useWorkspace();
-
- const { data: fileData, isPending: isPendingFile } = useQuery({
- type: 'file_get',
- id: id,
- accountId: workspace.accountId,
- workspaceId: workspace.id,
- });
-
- const fileExists = !!fileData;
-
- const { data: rootData, isPending: isPendingRoot } = useQuery(
- {
- type: 'entry_get',
- entryId: fileData?.rootId ?? '',
- accountId: workspace.accountId,
- workspaceId: workspace.id,
- },
- {
- enabled: fileExists,
- }
- );
-
- const { data: breadcrumbData, isPending: isPendingBreadcrumb } = useQuery(
- {
- type: 'file_breadcrumb_get',
- fileId: id,
- accountId: workspace.accountId,
- workspaceId: workspace.id,
- },
- {
- enabled: fileExists,
- }
- );
-
- const isPending =
- isPendingFile || (fileExists && (isPendingRoot || isPendingBreadcrumb));
-
- if (isPending) {
- return { isPending: true, file: null };
- }
-
- if (!fileExists) {
- return { isPending: false, file: null };
- }
-
- if (!rootData) {
- return { isPending: false, file: null };
- }
-
- if (!breadcrumbData || breadcrumbData.length === 0) {
- return { isPending: false, file: null };
- }
-
- const role = extractEntryRole(rootData, workspace.userId);
- if (!role) {
- return { isPending: false, file: null };
- }
-
- return {
- isPending: false,
- file: fileData,
- root: rootData,
- breadcrumb: breadcrumbData,
- role,
- };
-};
diff --git a/apps/desktop/src/renderer/hooks/user-layout-state.tsx b/apps/desktop/src/renderer/hooks/use-layout-state.tsx
similarity index 100%
rename from apps/desktop/src/renderer/hooks/user-layout-state.tsx
rename to apps/desktop/src/renderer/hooks/use-layout-state.tsx
diff --git a/apps/desktop/src/renderer/hooks/use-node-container.tsx b/apps/desktop/src/renderer/hooks/use-node-container.tsx
new file mode 100644
index 00000000..944576de
--- /dev/null
+++ b/apps/desktop/src/renderer/hooks/use-node-container.tsx
@@ -0,0 +1,66 @@
+import { NodeRole, extractNodeRole } from '@colanode/core';
+
+import { useWorkspace } from '@/renderer/contexts/workspace';
+import { useQuery } from '@/renderer/hooks/use-query';
+import { LocalNode } from '@/shared/types/nodes';
+
+type UseNodeContainerResult<T extends LocalNode> =
+ | {
+ isPending: true;
+ node: null;
+ }
+ | {
+ isPending: false;
+ node: null;
+ }
+ | {
+ isPending: false;
+ node: T;
+ breadcrumb: LocalNode[];
+ root: LocalNode;
+ role: NodeRole;
+ };
+
+export const useNodeContainer = <T extends LocalNode>(
+ id: string
+): UseNodeContainerResult<T> => {
+ const workspace = useWorkspace();
+
+ const { data, isPending } = useQuery({
+ type: 'node_tree_get',
+ nodeId: id,
+ accountId: workspace.accountId,
+ workspaceId: workspace.id,
+ });
+
+ if (isPending) {
+ return { isPending: true, node: null };
+ }
+
+ const nodes = data ?? [];
+ const node = nodes.find((node) => node.id === id);
+
+ if (!node) {
+ return { isPending: false, node: null };
+ }
+
+ const root = nodes.find((node) => node.id === node.rootId);
+
+ if (!root) {
+ return { isPending: false, node: null };
+ }
+
+ const role = extractNodeRole(root, workspace.userId);
+
+ if (!role) {
+ return { isPending: false, node: null };
+ }
+
+ return {
+ isPending: false,
+ node: node as T,
+ root: root,
+ breadcrumb: nodes,
+ role,
+ };
+};
diff --git a/apps/desktop/src/renderer/hooks/use-entry-radar.tsx b/apps/desktop/src/renderer/hooks/use-node-radar.tsx
similarity index 56%
rename from apps/desktop/src/renderer/hooks/use-entry-radar.tsx
rename to apps/desktop/src/renderer/hooks/use-node-radar.tsx
index 6ca518a6..3e3e4536 100644
--- a/apps/desktop/src/renderer/hooks/use-entry-radar.tsx
+++ b/apps/desktop/src/renderer/hooks/use-node-radar.tsx
@@ -1,24 +1,24 @@
-import { Entry } from '@colanode/core';
+import { Node } from '@colanode/core';
import { useEffect } from 'react';
import { useRadar } from '@/renderer/contexts/radar';
import { useWorkspace } from '@/renderer/contexts/workspace';
-export const useEntryRadar = (entry: Entry | null) => {
+export const useNodeRadar = (node: Node | null) => {
const workspace = useWorkspace();
const radar = useRadar();
useEffect(() => {
- if (!entry) {
+ if (!node) {
return;
}
- radar.markEntryAsOpened(workspace.accountId, workspace.id, entry.id);
+ radar.markNodeAsOpened(workspace.accountId, workspace.id, node.id);
const interval = setInterval(() => {
- radar.markEntryAsOpened(workspace.accountId, workspace.id, entry.id);
+ radar.markNodeAsOpened(workspace.accountId, workspace.id, node.id);
}, 60000);
return () => clearInterval(interval);
- }, [entry?.id]);
+ }, [node?.id]);
};
diff --git a/apps/desktop/src/renderer/hooks/user-records-query.tsx b/apps/desktop/src/renderer/hooks/use-records-query.tsx
similarity index 88%
rename from apps/desktop/src/renderer/hooks/user-records-query.tsx
rename to apps/desktop/src/renderer/hooks/use-records-query.tsx
index fa9a92f3..c9de4dfc 100644
--- a/apps/desktop/src/renderer/hooks/user-records-query.tsx
+++ b/apps/desktop/src/renderer/hooks/use-records-query.tsx
@@ -1,4 +1,7 @@
-import { ViewFilterAttributes, ViewSortAttributes } from '@colanode/core';
+import {
+ DatabaseViewFilterAttributes,
+ DatabaseViewSortAttributes,
+} from '@colanode/core';
import React from 'react';
import { useDatabase } from '@/renderer/contexts/database';
@@ -9,8 +12,8 @@ import { RecordListQueryInput } from '@/shared/queries/records/record-list';
const RECORDS_PER_PAGE = 50;
export const useRecordsQuery = (
- filters: ViewFilterAttributes[],
- sorts: ViewSortAttributes[],
+ filters: DatabaseViewFilterAttributes[],
+ sorts: DatabaseViewSortAttributes[],
count?: number
) => {
const workspace = useWorkspace();
diff --git a/apps/desktop/src/renderer/radar-provider.tsx b/apps/desktop/src/renderer/radar-provider.tsx
index 5ce6fdc7..1e0f23d3 100644
--- a/apps/desktop/src/renderer/radar-provider.tsx
+++ b/apps/desktop/src/renderer/radar-provider.tsx
@@ -84,42 +84,18 @@ export const RadarProvider = ({ children }: RadarProviderProps) => {
mentionsCount: 0,
};
},
- markMessageAsSeen: (accountId, workspaceId, messageId) => {
+ markNodeAsSeen: (accountId, workspaceId, nodeId) => {
window.colanode.executeMutation({
- type: 'message_mark_seen',
- messageId,
+ type: 'node_mark_seen',
+ nodeId,
accountId,
workspaceId,
});
},
- markFileAsSeen: (accountId, workspaceId, fileId) => {
+ markNodeAsOpened: (accountId, workspaceId, nodeId) => {
window.colanode.executeMutation({
- type: 'file_mark_seen',
- fileId,
- accountId,
- workspaceId,
- });
- },
- markFileAsOpened: (accountId, workspaceId, fileId) => {
- window.colanode.executeMutation({
- type: 'file_mark_opened',
- fileId,
- accountId,
- workspaceId,
- });
- },
- markEntryAsSeen: (accountId, workspaceId, entryId) => {
- window.colanode.executeMutation({
- type: 'entry_mark_seen',
- entryId,
- accountId,
- workspaceId,
- });
- },
- markEntryAsOpened: (accountId, workspaceId, entryId) => {
- window.colanode.executeMutation({
- type: 'entry_mark_opened',
- entryId,
+ type: 'node_mark_opened',
+ nodeId,
accountId,
workspaceId,
});
diff --git a/apps/desktop/src/shared/lib/databases.ts b/apps/desktop/src/shared/lib/databases.ts
index a5cbd1c7..8d96515f 100644
--- a/apps/desktop/src/shared/lib/databases.ts
+++ b/apps/desktop/src/shared/lib/databases.ts
@@ -6,14 +6,15 @@ import {
generateNodeIndex,
isStringArray,
MultiSelectFieldAttributes,
- RecordEntry,
SelectFieldAttributes,
- ViewFieldAttributes,
- ViewFieldFilterAttributes,
- ViewFilterAttributes,
- ViewType,
+ DatabaseViewFieldAttributes,
+ DatabaseViewFilterAttributes,
+ DatabaseViewLayout,
+ DatabaseViewFieldFilterAttributes,
} from '@colanode/core';
+import { LocalRecordNode } from '@/shared/types/nodes';
+
export const getDefaultFieldWidth = (type: FieldType): number => {
if (!type) return 0;
@@ -69,8 +70,10 @@ export const getDefaultNameWidth = (): number => {
return 300;
};
-export const getDefaultViewFieldDisplay = (viewType: ViewType): boolean => {
- return viewType === 'table';
+export const getDefaultViewFieldDisplay = (
+ layout: DatabaseViewLayout
+): boolean => {
+ return layout === 'table';
};
interface SelectOptionColor {
@@ -481,9 +484,9 @@ export const getFieldFilterOperators = (
return booleanFieldFilterOperators;
case 'collaborator':
return collaboratorFieldFilterOperators;
- case 'createdAt':
+ case 'created_at':
return createdAtFieldFilterOperators;
- case 'createdBy':
+ case 'created_by':
return createdByFieldFilterOperators;
case 'date':
return dateFieldFilterOperators;
@@ -491,7 +494,7 @@ export const getFieldFilterOperators = (
return emailFieldFilterOperators;
case 'file':
return fileFieldFilterOperators;
- case 'multiSelect':
+ case 'multi_select':
return multiSelectFieldFilterOperators;
case 'number':
return numberFieldFilterOperators;
@@ -509,19 +512,19 @@ export const getFieldFilterOperators = (
};
export const filterRecords = (
- records: RecordEntry[],
- filter: ViewFilterAttributes,
+ records: LocalRecordNode[],
+ filter: DatabaseViewFilterAttributes,
field: FieldAttributes,
currentUserId: string
-): RecordEntry[] => {
+): LocalRecordNode[] => {
return records.filter((record) =>
recordMatchesFilter(record, filter, field, currentUserId)
);
};
const recordMatchesFilter = (
- record: RecordEntry,
- filter: ViewFilterAttributes,
+ record: LocalRecordNode,
+ filter: DatabaseViewFilterAttributes,
field: FieldAttributes,
currentUserId: string
) => {
@@ -534,9 +537,9 @@ const recordMatchesFilter = (
return recordMatchesBooleanFilter(record, filter, field);
case 'collaborator':
return recordMatchesCollaboratorFilter(record, filter, field);
- case 'createdAt':
+ case 'created_at':
return recordMatchesCreatedAtFilter(record, filter);
- case 'createdBy':
+ case 'created_by':
return recordMatchesCreatedByFilter(record, filter, currentUserId);
case 'date':
return recordMatchesDateFilter(record, filter, field);
@@ -544,7 +547,7 @@ const recordMatchesFilter = (
return recordMatchesEmailFilter(record, filter, field);
case 'file':
return recordMatchesFileFilter(record, filter, field);
- case 'multiSelect':
+ case 'multi_select':
return recordMatchesMultiSelectFilter(record, filter, field);
case 'number':
return recordMatchesNumberFilter(record, filter, field);
@@ -562,8 +565,8 @@ const recordMatchesFilter = (
};
const recordMatchesBooleanFilter = (
- record: RecordEntry,
- filter: ViewFieldFilterAttributes,
+ record: LocalRecordNode,
+ filter: DatabaseViewFieldFilterAttributes,
field: FieldAttributes
) => {
const fieldValue = record.attributes.fields[field.id];
@@ -586,16 +589,16 @@ const recordMatchesBooleanFilter = (
};
const recordMatchesCollaboratorFilter = (
- _: RecordEntry,
- __: ViewFieldFilterAttributes,
+ _: LocalRecordNode,
+ __: DatabaseViewFilterAttributes,
___: FieldAttributes
) => {
return false;
};
const recordMatchesCreatedAtFilter = (
- record: RecordEntry,
- filter: ViewFieldFilterAttributes
+ record: LocalRecordNode,
+ filter: DatabaseViewFieldFilterAttributes
) => {
if (!filter.value) return false;
@@ -628,8 +631,8 @@ const recordMatchesCreatedAtFilter = (
};
const recordMatchesCreatedByFilter = (
- record: RecordEntry,
- filter: ViewFieldFilterAttributes,
+ record: LocalRecordNode,
+ filter: DatabaseViewFieldFilterAttributes,
currentUserId: string
) => {
const createdBy = record.createdBy;
@@ -661,8 +664,8 @@ const recordMatchesCreatedByFilter = (
};
const recordMatchesDateFilter = (
- record: RecordEntry,
- filter: ViewFieldFilterAttributes,
+ record: LocalRecordNode,
+ filter: DatabaseViewFieldFilterAttributes,
field: FieldAttributes
) => {
const fieldValue = record.attributes.fields[field.id];
@@ -674,7 +677,7 @@ const recordMatchesDateFilter = (
return !!fieldValue;
}
- if (!fieldValue || fieldValue.type !== 'date') {
+ if (!fieldValue || fieldValue.type !== 'string') {
return false;
}
@@ -707,8 +710,8 @@ const recordMatchesDateFilter = (
};
const recordMatchesEmailFilter = (
- record: RecordEntry,
- filter: ViewFieldFilterAttributes,
+ record: LocalRecordNode,
+ filter: DatabaseViewFieldFilterAttributes,
field: FieldAttributes
) => {
const fieldValue = record.attributes.fields[field.id];
@@ -721,7 +724,7 @@ const recordMatchesEmailFilter = (
return !!fieldValue;
}
- if (!fieldValue || fieldValue.type !== 'email') {
+ if (!fieldValue || fieldValue.type !== 'string') {
return false;
}
@@ -749,21 +752,21 @@ const recordMatchesEmailFilter = (
};
const recordMatchesFileFilter = (
- _: RecordEntry,
- __: ViewFieldFilterAttributes,
+ _: LocalRecordNode,
+ __: DatabaseViewFilterAttributes,
___: FieldAttributes
) => {
return false;
};
const recordMatchesMultiSelectFilter = (
- record: RecordEntry,
- filter: ViewFieldFilterAttributes,
+ record: LocalRecordNode,
+ filter: DatabaseViewFieldFilterAttributes,
field: FieldAttributes
) => {
const fieldValue = record.attributes.fields[field.id];
const selectValues =
- fieldValue?.type === 'multiSelect' ? fieldValue.value : [];
+ fieldValue?.type === 'string_array' ? fieldValue.value : [];
if (filter.operator === 'is_empty') {
return selectValues.length === 0;
@@ -788,8 +791,8 @@ const recordMatchesMultiSelectFilter = (
};
const recordMatchesNumberFilter = (
- record: RecordEntry,
- filter: ViewFieldFilterAttributes,
+ record: LocalRecordNode,
+ filter: DatabaseViewFieldFilterAttributes,
field: FieldAttributes
) => {
const fieldValue = record.attributes.fields[field.id];
@@ -834,8 +837,8 @@ const recordMatchesNumberFilter = (
};
const recordMatchesPhoneFilter = (
- record: RecordEntry,
- filter: ViewFieldFilterAttributes,
+ record: LocalRecordNode,
+ filter: DatabaseViewFieldFilterAttributes,
field: FieldAttributes
) => {
const fieldValue = record.attributes.fields[field.id];
@@ -848,7 +851,7 @@ const recordMatchesPhoneFilter = (
return !!fieldValue;
}
- if (!fieldValue || fieldValue.type !== 'phone') {
+ if (!fieldValue || fieldValue.type !== 'string') {
return false;
}
@@ -876,8 +879,8 @@ const recordMatchesPhoneFilter = (
};
const recordMatchesSelectFilter = (
- record: RecordEntry,
- filter: ViewFieldFilterAttributes,
+ record: LocalRecordNode,
+ filter: DatabaseViewFieldFilterAttributes,
field: FieldAttributes
) => {
const fieldValue = record.attributes.fields[field.id];
@@ -890,7 +893,7 @@ const recordMatchesSelectFilter = (
return !!fieldValue;
}
- if (!fieldValue || fieldValue.type !== 'select') {
+ if (!fieldValue || fieldValue.type !== 'string') {
return false;
}
@@ -911,8 +914,8 @@ const recordMatchesSelectFilter = (
};
const recordMatchesTextFilter = (
- record: RecordEntry,
- filter: ViewFieldFilterAttributes,
+ record: LocalRecordNode,
+ filter: DatabaseViewFieldFilterAttributes,
field: FieldAttributes
) => {
const fieldValue = record.attributes.fields[field.id];
@@ -953,8 +956,8 @@ const recordMatchesTextFilter = (
};
const recordMatchesUrlFilter = (
- record: RecordEntry,
- filter: ViewFieldFilterAttributes,
+ record: LocalRecordNode,
+ filter: DatabaseViewFieldFilterAttributes,
field: FieldAttributes
) => {
const fieldValue = record.attributes.fields[field.id];
@@ -967,7 +970,7 @@ const recordMatchesUrlFilter = (
return !!fieldValue;
}
- if (!fieldValue || fieldValue.type !== 'url') {
+ if (!fieldValue || fieldValue.type !== 'string') {
return false;
}
@@ -1004,7 +1007,7 @@ export const isSortableField = (field: FieldAttributes) => {
field.type === 'text' ||
field.type === 'number' ||
field.type === 'date' ||
- field.type === 'createdAt' ||
+ field.type === 'created_at' ||
field.type === 'email' ||
field.type === 'phone' ||
field.type === 'select' ||
@@ -1014,7 +1017,7 @@ export const isSortableField = (field: FieldAttributes) => {
export const generateViewFieldIndex = (
databaseFields: FieldAttributes[],
- viewFields: ViewFieldAttributes[],
+ viewFields: DatabaseViewFieldAttributes[],
fieldId: string,
after: string
): string | null => {
@@ -1089,7 +1092,7 @@ export const generateViewFieldIndex = (
export const generateFieldValuesFromFilters = (
fields: FieldAttributes[],
- filters: ViewFilterAttributes[],
+ filters: DatabaseViewFilterAttributes[],
userId: string
): Record<string, FieldValue> => {
if (fields.length === 0 || filters.length === 0) {
@@ -1115,7 +1118,7 @@ export const generateFieldValuesFromFilters = (
const generateValueFromFilter = (
field: FieldAttributes,
- filter: ViewFieldFilterAttributes,
+ filter: DatabaseViewFieldFilterAttributes,
userId: string
): FieldValue | null => {
switch (field.type) {
@@ -1134,7 +1137,7 @@ const generateValueFromFilter = (
case 'file': {
return generateFileValue(filter);
}
- case 'multiSelect': {
+ case 'multi_select': {
return generateMultiSelectValue(field, filter);
}
case 'number': {
@@ -1158,7 +1161,7 @@ const generateValueFromFilter = (
};
const generateBooleanValue = (
- filter: ViewFieldFilterAttributes
+ filter: DatabaseViewFieldFilterAttributes
): FieldValue | null => {
if (filter.operator === 'is_true') {
return { type: 'boolean', value: true };
@@ -1172,11 +1175,11 @@ const generateBooleanValue = (
};
const generateCollaboratorValue = (
- filter: ViewFieldFilterAttributes,
+ filter: DatabaseViewFieldFilterAttributes,
userId: string
): FieldValue | null => {
if (filter.operator === 'is_me') {
- return { type: 'collaborator', value: [userId] };
+ return { type: 'string_array', value: [userId] };
}
if (filter.operator === 'is_in' && Array.isArray(filter.value)) {
@@ -1185,78 +1188,78 @@ const generateCollaboratorValue = (
return null;
}
- return { type: 'collaborator', value: [firstValue] };
+ return { type: 'string_array', value: [firstValue] };
}
if (filter.operator === 'is_not_empty') {
- return { type: 'collaborator', value: [userId] };
+ return { type: 'string_array', value: [userId] };
}
return null;
};
const generateDateValue = (
- filter: ViewFieldFilterAttributes
+ filter: DatabaseViewFieldFilterAttributes
): FieldValue | null => {
if (typeof filter.value !== 'string') {
return null;
}
if (filter.operator === 'is_equal_to') {
- return { type: 'date', value: filter.value };
+ return { type: 'string', value: filter.value };
}
if (filter.operator === 'is_on_or_after') {
- return { type: 'date', value: filter.value };
+ return { type: 'string', value: filter.value };
}
if (filter.operator === 'is_on_or_before') {
- return { type: 'date', value: filter.value };
+ return { type: 'string', value: filter.value };
}
if (filter.operator === 'is_after') {
const date = new Date(filter.value);
date.setDate(date.getDate() + 1);
- return { type: 'date', value: date.toISOString() };
+ return { type: 'string', value: date.toISOString() };
}
if (filter.operator === 'is_before') {
const date = new Date(filter.value);
date.setDate(date.getDate() - 1);
- return { type: 'date', value: date.toISOString() };
+ return { type: 'string', value: date.toISOString() };
}
if (filter.operator === 'is_not_empty') {
- return { type: 'date', value: new Date().toISOString() };
+ return { type: 'string', value: new Date().toISOString() };
}
return null;
};
const generateEmailValue = (
- filter: ViewFieldFilterAttributes
+ filter: DatabaseViewFieldFilterAttributes
): FieldValue | null => {
if (typeof filter.value !== 'string') {
return null;
}
if (filter.operator === 'is_equal_to') {
- return { type: 'email', value: filter.value };
+ return { type: 'string', value: filter.value };
}
if (filter.operator === 'contains') {
- return { type: 'email', value: filter.value };
+ return { type: 'string', value: filter.value };
}
if (filter.operator === 'is_not_empty') {
- return { type: 'email', value: '#' };
+ return { type: 'string', value: '#' };
}
return null;
};
const generateFileValue = (
- filter: ViewFieldFilterAttributes
+ filter: DatabaseViewFieldFilterAttributes
): FieldValue | null => {
if (filter.operator === 'is_in' && Array.isArray(filter.value)) {
const firstValue = filter.value[0];
@@ -1264,7 +1267,7 @@ const generateFileValue = (
return null;
}
- return { type: 'file', value: [firstValue] };
+ return { type: 'string_array', value: [firstValue] };
}
return null;
@@ -1272,7 +1275,7 @@ const generateFileValue = (
const generateMultiSelectValue = (
field: MultiSelectFieldAttributes,
- filter: ViewFieldFilterAttributes
+ filter: DatabaseViewFieldFilterAttributes
): FieldValue | null => {
if (filter.operator === 'is_in' && Array.isArray(filter.value)) {
const firstValue = filter.value[0];
@@ -1280,7 +1283,7 @@ const generateMultiSelectValue = (
return null;
}
- return { type: 'multiSelect', value: [firstValue] };
+ return { type: 'string_array', value: [firstValue] };
}
if (
@@ -1293,14 +1296,14 @@ const generateMultiSelectValue = (
return null;
}
- return { type: 'multiSelect', value: [firstOption.id] };
+ return { type: 'string_array', value: [firstOption.id] };
}
return null;
};
const generateNumberValue = (
- filter: ViewFieldFilterAttributes
+ filter: DatabaseViewFieldFilterAttributes
): FieldValue | null => {
if (typeof filter.value !== 'number') {
return null;
@@ -1334,22 +1337,22 @@ const generateNumberValue = (
};
const generatePhoneValue = (
- filter: ViewFieldFilterAttributes
+ filter: DatabaseViewFieldFilterAttributes
): FieldValue | null => {
if (typeof filter.value !== 'string') {
return null;
}
if (filter.operator === 'is_equal_to') {
- return { type: 'phone', value: filter.value };
+ return { type: 'string', value: filter.value };
}
if (filter.operator === 'contains') {
- return { type: 'phone', value: filter.value };
+ return { type: 'string', value: filter.value };
}
if (filter.operator === 'is_not_empty') {
- return { type: 'phone', value: '#' };
+ return { type: 'string', value: '#' };
}
return null;
@@ -1357,7 +1360,7 @@ const generatePhoneValue = (
const generateSelectValue = (
field: SelectFieldAttributes,
- filter: ViewFieldFilterAttributes
+ filter: DatabaseViewFieldFilterAttributes
): FieldValue | null => {
if (filter.operator === 'is_in' && Array.isArray(filter.value)) {
const firstValue = filter.value[0];
@@ -1365,7 +1368,7 @@ const generateSelectValue = (
return null;
}
- return { type: 'select', value: firstValue };
+ return { type: 'string', value: firstValue };
}
if (
@@ -1378,14 +1381,14 @@ const generateSelectValue = (
return null;
}
- return { type: 'select', value: firstOption.id };
+ return { type: 'string', value: firstOption.id };
}
return null;
};
const generateTextValue = (
- filter: ViewFieldFilterAttributes
+ filter: DatabaseViewFieldFilterAttributes
): FieldValue | null => {
if (typeof filter.value !== 'string') {
return null;
@@ -1407,22 +1410,22 @@ const generateTextValue = (
};
const generateUrlValue = (
- filter: ViewFieldFilterAttributes
+ filter: DatabaseViewFieldFilterAttributes
): FieldValue | null => {
if (typeof filter.value !== 'string') {
return null;
}
if (filter.operator === 'is_equal_to') {
- return { type: 'url', value: filter.value };
+ return { type: 'string', value: filter.value };
}
if (filter.operator === 'contains') {
- return { type: 'url', value: filter.value };
+ return { type: 'string', value: filter.value };
}
if (filter.operator === 'is_not_empty') {
- return { type: 'url', value: '#' };
+ return { type: 'string', value: '#' };
}
return null;
diff --git a/apps/desktop/src/shared/lib/entries.ts b/apps/desktop/src/shared/lib/entries.ts
deleted file mode 100644
index 25c75020..00000000
--- a/apps/desktop/src/shared/lib/entries.ts
+++ /dev/null
@@ -1,42 +0,0 @@
-import { extractEntryCollaborators, Entry, EntryType } from '@colanode/core';
-
-import { EntryCollaborator } from '@/shared/types/entries';
-
-export const getDefaultEntryIcon = (type: EntryType) => {
- switch (type) {
- case 'channel':
- return 'discuss-line';
- case 'page':
- return 'book-line';
- case 'database':
- return 'database-2-line';
- case 'record':
- return 'article-line';
- case 'folder':
- return 'folder-open-line';
- case 'space':
- return 'team-line';
- default:
- return 'file-unknown-line';
- }
-};
-
-export const buildEntryCollaborators = (
- entries: Entry[]
-): EntryCollaborator[] => {
- const collaborators: Record<string, EntryCollaborator> = {};
-
- for (const entry of entries) {
- const entryCollaborators = extractEntryCollaborators(entry.attributes);
-
- for (const [collaboratorId, role] of Object.entries(entryCollaborators)) {
- collaborators[collaboratorId] = {
- entryId: entry.id,
- collaboratorId,
- role,
- };
- }
- }
-
- return Object.values(collaborators);
-};
diff --git a/apps/desktop/src/shared/lib/nodes.ts b/apps/desktop/src/shared/lib/nodes.ts
new file mode 100644
index 00000000..a3f75eb3
--- /dev/null
+++ b/apps/desktop/src/shared/lib/nodes.ts
@@ -0,0 +1,40 @@
+import { extractNodeCollaborators, Node, NodeType } from '@colanode/core';
+
+import { NodeCollaborator } from '@/shared/types/nodes';
+
+export const getDefaultNodeIcon = (type: NodeType) => {
+ switch (type) {
+ case 'channel':
+ return 'discuss-line';
+ case 'page':
+ return 'book-line';
+ case 'database':
+ return 'database-2-line';
+ case 'record':
+ return 'article-line';
+ case 'folder':
+ return 'folder-open-line';
+ case 'space':
+ return 'team-line';
+ default:
+ return 'file-unknown-line';
+ }
+};
+
+export const buildNodeCollaborators = (nodes: Node[]): NodeCollaborator[] => {
+ const collaborators: Record<string, NodeCollaborator> = {};
+
+ for (const node of nodes) {
+ const nodeCollaborators = extractNodeCollaborators(node.attributes);
+
+ for (const [collaboratorId, role] of Object.entries(nodeCollaborators)) {
+ collaborators[collaboratorId] = {
+ nodeId: node.id,
+ collaboratorId,
+ role,
+ };
+ }
+ }
+
+ return Object.values(collaborators);
+};
diff --git a/apps/desktop/src/shared/mutations/databases/view-delete.ts b/apps/desktop/src/shared/mutations/databases/view-delete.ts
index 542700fa..fef7c0c2 100644
--- a/apps/desktop/src/shared/mutations/databases/view-delete.ts
+++ b/apps/desktop/src/shared/mutations/databases/view-delete.ts
@@ -2,7 +2,6 @@ export type ViewDeleteMutationInput = {
type: 'view_delete';
accountId: string;
workspaceId: string;
- databaseId: string;
viewId: string;
};
diff --git a/apps/desktop/src/shared/mutations/databases/view-update.ts b/apps/desktop/src/shared/mutations/databases/view-update.ts
index 15e391f8..08e3d8d0 100644
--- a/apps/desktop/src/shared/mutations/databases/view-update.ts
+++ b/apps/desktop/src/shared/mutations/databases/view-update.ts
@@ -1,11 +1,11 @@
-import { ViewAttributes } from '@colanode/core';
+import { DatabaseViewAttributes } from '@colanode/core';
export type ViewUpdateMutationInput = {
type: 'view_update';
accountId: string;
workspaceId: string;
- databaseId: string;
- view: ViewAttributes;
+ viewId: string;
+ view: DatabaseViewAttributes;
};
export type ViewUpdateMutationOutput = {
diff --git a/apps/desktop/src/shared/mutations/entries/entry-collaborator-create.ts b/apps/desktop/src/shared/mutations/entries/entry-collaborator-create.ts
deleted file mode 100644
index 05282a3c..00000000
--- a/apps/desktop/src/shared/mutations/entries/entry-collaborator-create.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-export type EntryCollaboratorCreateMutationInput = {
- type: 'entry_collaborator_create';
- accountId: string;
- workspaceId: string;
- entryId: string;
- collaboratorIds: string[];
- role: string;
-};
-
-export type EntryCollaboratorCreateMutationOutput = {
- success: boolean;
-};
-
-declare module '@/shared/mutations' {
- interface MutationMap {
- entry_collaborator_create: {
- input: EntryCollaboratorCreateMutationInput;
- output: EntryCollaboratorCreateMutationOutput;
- };
- }
-}
diff --git a/apps/desktop/src/shared/mutations/entries/entry-collaborator-delete.ts b/apps/desktop/src/shared/mutations/entries/entry-collaborator-delete.ts
deleted file mode 100644
index 92cd1cbc..00000000
--- a/apps/desktop/src/shared/mutations/entries/entry-collaborator-delete.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-export type EntryCollaboratorDeleteMutationInput = {
- type: 'entry_collaborator_delete';
- accountId: string;
- workspaceId: string;
- entryId: string;
- collaboratorId: string;
-};
-
-export type EntryCollaboratorDeleteMutationOutput = {
- success: boolean;
-};
-
-declare module '@/shared/mutations' {
- interface MutationMap {
- entry_collaborator_delete: {
- input: EntryCollaboratorDeleteMutationInput;
- output: EntryCollaboratorDeleteMutationOutput;
- };
- }
-}
diff --git a/apps/desktop/src/shared/mutations/entries/entry-collaborator-update.ts b/apps/desktop/src/shared/mutations/entries/entry-collaborator-update.ts
deleted file mode 100644
index 6cb6caa1..00000000
--- a/apps/desktop/src/shared/mutations/entries/entry-collaborator-update.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-export type EntryCollaboratorUpdateMutationInput = {
- type: 'entry_collaborator_update';
- accountId: string;
- workspaceId: string;
- entryId: string;
- collaboratorId: string;
- role: string;
-};
-
-export type EntryCollaboratorUpdateMutationOutput = {
- success: boolean;
-};
-
-declare module '@/shared/mutations' {
- interface MutationMap {
- entry_collaborator_update: {
- input: EntryCollaboratorUpdateMutationInput;
- output: EntryCollaboratorUpdateMutationOutput;
- };
- }
-}
diff --git a/apps/desktop/src/shared/mutations/entries/entry-mark-opened.ts b/apps/desktop/src/shared/mutations/entries/entry-mark-opened.ts
deleted file mode 100644
index 13991542..00000000
--- a/apps/desktop/src/shared/mutations/entries/entry-mark-opened.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-export type EntryMarkOpenedMutationInput = {
- type: 'entry_mark_opened';
- accountId: string;
- workspaceId: string;
- entryId: string;
-};
-
-export type EntryMarkOpenedMutationOutput = {
- success: boolean;
-};
-
-declare module '@/shared/mutations' {
- interface MutationMap {
- entry_mark_opened: {
- input: EntryMarkOpenedMutationInput;
- output: EntryMarkOpenedMutationOutput;
- };
- }
-}
diff --git a/apps/desktop/src/shared/mutations/entries/entry-mark-seen.ts b/apps/desktop/src/shared/mutations/entries/entry-mark-seen.ts
deleted file mode 100644
index 60a467b0..00000000
--- a/apps/desktop/src/shared/mutations/entries/entry-mark-seen.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-export type EntryMarkSeenMutationInput = {
- type: 'entry_mark_seen';
- accountId: string;
- workspaceId: string;
- entryId: string;
-};
-
-export type EntryMarkSeenMutationOutput = {
- success: boolean;
-};
-
-declare module '@/shared/mutations' {
- interface MutationMap {
- entry_mark_seen: {
- input: EntryMarkSeenMutationInput;
- output: EntryMarkSeenMutationOutput;
- };
- }
-}
diff --git a/apps/desktop/src/shared/mutations/files/file-mark-opened.ts b/apps/desktop/src/shared/mutations/files/file-mark-opened.ts
deleted file mode 100644
index 57e6e25d..00000000
--- a/apps/desktop/src/shared/mutations/files/file-mark-opened.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-export type FileMarkOpenedMutationInput = {
- type: 'file_mark_opened';
- accountId: string;
- workspaceId: string;
- fileId: string;
-};
-
-export type FileMarkOpenedMutationOutput = {
- success: boolean;
-};
-
-declare module '@/shared/mutations' {
- interface MutationMap {
- file_mark_opened: {
- input: FileMarkOpenedMutationInput;
- output: FileMarkOpenedMutationOutput;
- };
- }
-}
diff --git a/apps/desktop/src/shared/mutations/files/file-mark-seen.ts b/apps/desktop/src/shared/mutations/files/file-mark-seen.ts
deleted file mode 100644
index 530b4288..00000000
--- a/apps/desktop/src/shared/mutations/files/file-mark-seen.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-export type FileMarkSeenMutationInput = {
- type: 'file_mark_seen';
- accountId: string;
- workspaceId: string;
- fileId: string;
-};
-
-export type FileMarkSeenMutationOutput = {
- success: boolean;
-};
-
-declare module '@/shared/mutations' {
- interface MutationMap {
- file_mark_seen: {
- input: FileMarkSeenMutationInput;
- output: FileMarkSeenMutationOutput;
- };
- }
-}
diff --git a/apps/desktop/src/shared/mutations/index.ts b/apps/desktop/src/shared/mutations/index.ts
index 3858ea13..718dab32 100644
--- a/apps/desktop/src/shared/mutations/index.ts
+++ b/apps/desktop/src/shared/mutations/index.ts
@@ -84,14 +84,14 @@ export enum MutationErrorCode {
RecordUpdateFailed = 'record_update_failed',
PageUpdateForbidden = 'page_update_forbidden',
PageUpdateFailed = 'page_update_failed',
- EntryCollaboratorCreateForbidden = 'entry_collaborator_create_forbidden',
- EntryCollaboratorCreateFailed = 'entry_collaborator_create_failed',
- EntryCollaboratorDeleteForbidden = 'entry_collaborator_delete_forbidden',
- EntryCollaboratorDeleteFailed = 'entry_collaborator_delete_failed',
- EntryCollaboratorUpdateForbidden = 'entry_collaborator_update_forbidden',
- EntryCollaboratorUpdateFailed = 'entry_collaborator_update_failed',
+ NodeCollaboratorCreateForbidden = 'node_collaborator_create_forbidden',
+ NodeCollaboratorCreateFailed = 'node_collaborator_create_failed',
+ NodeCollaboratorDeleteForbidden = 'node_collaborator_delete_forbidden',
+ NodeCollaboratorDeleteFailed = 'node_collaborator_delete_failed',
+ NodeCollaboratorUpdateForbidden = 'node_collaborator_update_forbidden',
+ NodeCollaboratorUpdateFailed = 'node_collaborator_update_failed',
UserNotFound = 'user_not_found',
- EntryNotFound = 'entry_not_found',
+ NodeNotFound = 'node_not_found',
RootNotFound = 'root_not_found',
FileCreateForbidden = 'file_create_forbidden',
FileCreateFailed = 'file_create_failed',
@@ -108,5 +108,5 @@ export enum MutationErrorCode {
MessageDeleteForbidden = 'message_delete_forbidden',
MessageDeleteFailed = 'message_delete_failed',
MessageNotFound = 'message_not_found',
- MessageReactionCreateForbidden = 'message_reaction_create_forbidden',
+ NodeReactionCreateForbidden = 'node_reaction_create_forbidden',
}
diff --git a/apps/desktop/src/shared/mutations/messages/message-create.ts b/apps/desktop/src/shared/mutations/messages/message-create.ts
index d822da3d..fe9ea32e 100644
--- a/apps/desktop/src/shared/mutations/messages/message-create.ts
+++ b/apps/desktop/src/shared/mutations/messages/message-create.ts
@@ -4,8 +4,7 @@ export type MessageCreateMutationInput = {
type: 'message_create';
accountId: string;
workspaceId: string;
- conversationId: string;
- rootId: string;
+ parentId: string;
content: JSONContent;
referenceId?: string;
};
diff --git a/apps/desktop/src/shared/mutations/messages/message-mark-seen.ts b/apps/desktop/src/shared/mutations/messages/message-mark-seen.ts
deleted file mode 100644
index 35394992..00000000
--- a/apps/desktop/src/shared/mutations/messages/message-mark-seen.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-export type MessageMarkSeenMutationInput = {
- type: 'message_mark_seen';
- accountId: string;
- workspaceId: string;
- messageId: string;
-};
-
-export type MessageMarkSeenMutationOutput = {
- success: boolean;
-};
-
-declare module '@/shared/mutations' {
- interface MutationMap {
- message_mark_seen: {
- input: MessageMarkSeenMutationInput;
- output: MessageMarkSeenMutationOutput;
- };
- }
-}
diff --git a/apps/desktop/src/shared/mutations/messages/message-reaction-create.ts b/apps/desktop/src/shared/mutations/messages/message-reaction-create.ts
deleted file mode 100644
index aac06ffc..00000000
--- a/apps/desktop/src/shared/mutations/messages/message-reaction-create.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-export type MessageReactionCreateMutationInput = {
- type: 'message_reaction_create';
- accountId: string;
- workspaceId: string;
- messageId: string;
- rootId: string;
- reaction: string;
-};
-
-export type MessageReactionCreateMutationOutput = {
- success: boolean;
-};
-
-declare module '@/shared/mutations' {
- interface MutationMap {
- message_reaction_create: {
- input: MessageReactionCreateMutationInput;
- output: MessageReactionCreateMutationOutput;
- };
- }
-}
diff --git a/apps/desktop/src/shared/mutations/messages/message-reaction-delete.ts b/apps/desktop/src/shared/mutations/messages/message-reaction-delete.ts
deleted file mode 100644
index 9b40b336..00000000
--- a/apps/desktop/src/shared/mutations/messages/message-reaction-delete.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-export type MessageReactionDeleteMutationInput = {
- type: 'message_reaction_delete';
- accountId: string;
- workspaceId: string;
- messageId: string;
- rootId: string;
- reaction: string;
-};
-
-export type MessageReactionDeleteMutationOutput = {
- success: boolean;
-};
-
-declare module '@/shared/mutations' {
- interface MutationMap {
- message_reaction_delete: {
- input: MessageReactionDeleteMutationInput;
- output: MessageReactionDeleteMutationOutput;
- };
- }
-}
diff --git a/apps/desktop/src/shared/mutations/nodes/node-collaborator-create.ts b/apps/desktop/src/shared/mutations/nodes/node-collaborator-create.ts
new file mode 100644
index 00000000..737beaf7
--- /dev/null
+++ b/apps/desktop/src/shared/mutations/nodes/node-collaborator-create.ts
@@ -0,0 +1,21 @@
+export type NodeCollaboratorCreateMutationInput = {
+ type: 'node_collaborator_create';
+ accountId: string;
+ workspaceId: string;
+ nodeId: string;
+ collaboratorIds: string[];
+ role: string;
+};
+
+export type NodeCollaboratorCreateMutationOutput = {
+ success: boolean;
+};
+
+declare module '@/shared/mutations' {
+ interface MutationMap {
+ node_collaborator_create: {
+ input: NodeCollaboratorCreateMutationInput;
+ output: NodeCollaboratorCreateMutationOutput;
+ };
+ }
+}
diff --git a/apps/desktop/src/shared/mutations/nodes/node-collaborator-delete.ts b/apps/desktop/src/shared/mutations/nodes/node-collaborator-delete.ts
new file mode 100644
index 00000000..b0b9212e
--- /dev/null
+++ b/apps/desktop/src/shared/mutations/nodes/node-collaborator-delete.ts
@@ -0,0 +1,20 @@
+export type NodeCollaboratorDeleteMutationInput = {
+ type: 'node_collaborator_delete';
+ accountId: string;
+ workspaceId: string;
+ nodeId: string;
+ collaboratorId: string;
+};
+
+export type NodeCollaboratorDeleteMutationOutput = {
+ success: boolean;
+};
+
+declare module '@/shared/mutations' {
+ interface MutationMap {
+ node_collaborator_delete: {
+ input: NodeCollaboratorDeleteMutationInput;
+ output: NodeCollaboratorDeleteMutationOutput;
+ };
+ }
+}
diff --git a/apps/desktop/src/shared/mutations/nodes/node-collaborator-update.ts b/apps/desktop/src/shared/mutations/nodes/node-collaborator-update.ts
new file mode 100644
index 00000000..d792bd6c
--- /dev/null
+++ b/apps/desktop/src/shared/mutations/nodes/node-collaborator-update.ts
@@ -0,0 +1,21 @@
+export type NodeCollaboratorUpdateMutationInput = {
+ type: 'node_collaborator_update';
+ accountId: string;
+ workspaceId: string;
+ nodeId: string;
+ collaboratorId: string;
+ role: string;
+};
+
+export type NodeCollaboratorUpdateMutationOutput = {
+ success: boolean;
+};
+
+declare module '@/shared/mutations' {
+ interface MutationMap {
+ node_collaborator_update: {
+ input: NodeCollaboratorUpdateMutationInput;
+ output: NodeCollaboratorUpdateMutationOutput;
+ };
+ }
+}
diff --git a/apps/desktop/src/shared/mutations/nodes/node-mark-opened.ts b/apps/desktop/src/shared/mutations/nodes/node-mark-opened.ts
new file mode 100644
index 00000000..5ee8ac21
--- /dev/null
+++ b/apps/desktop/src/shared/mutations/nodes/node-mark-opened.ts
@@ -0,0 +1,19 @@
+export type NodeMarkOpenedMutationInput = {
+ type: 'node_mark_opened';
+ accountId: string;
+ workspaceId: string;
+ nodeId: string;
+};
+
+export type NodeMarkOpenedMutationOutput = {
+ success: boolean;
+};
+
+declare module '@/shared/mutations' {
+ interface MutationMap {
+ node_mark_opened: {
+ input: NodeMarkOpenedMutationInput;
+ output: NodeMarkOpenedMutationOutput;
+ };
+ }
+}
diff --git a/apps/desktop/src/shared/mutations/nodes/node-mark-seen.ts b/apps/desktop/src/shared/mutations/nodes/node-mark-seen.ts
new file mode 100644
index 00000000..b9bf8a3c
--- /dev/null
+++ b/apps/desktop/src/shared/mutations/nodes/node-mark-seen.ts
@@ -0,0 +1,19 @@
+export type NodeMarkSeenMutationInput = {
+ type: 'node_mark_seen';
+ accountId: string;
+ workspaceId: string;
+ nodeId: string;
+};
+
+export type NodeMarkSeenMutationOutput = {
+ success: boolean;
+};
+
+declare module '@/shared/mutations' {
+ interface MutationMap {
+ node_mark_seen: {
+ input: NodeMarkSeenMutationInput;
+ output: NodeMarkSeenMutationOutput;
+ };
+ }
+}
diff --git a/apps/desktop/src/shared/mutations/nodes/node-reaction-create.ts b/apps/desktop/src/shared/mutations/nodes/node-reaction-create.ts
new file mode 100644
index 00000000..ea0be2c9
--- /dev/null
+++ b/apps/desktop/src/shared/mutations/nodes/node-reaction-create.ts
@@ -0,0 +1,20 @@
+export type NodeReactionCreateMutationInput = {
+ type: 'node_reaction_create';
+ accountId: string;
+ workspaceId: string;
+ nodeId: string;
+ reaction: string;
+};
+
+export type NodeReactionCreateMutationOutput = {
+ success: boolean;
+};
+
+declare module '@/shared/mutations' {
+ interface MutationMap {
+ node_reaction_create: {
+ input: NodeReactionCreateMutationInput;
+ output: NodeReactionCreateMutationOutput;
+ };
+ }
+}
diff --git a/apps/desktop/src/shared/mutations/nodes/node-reaction-delete.ts b/apps/desktop/src/shared/mutations/nodes/node-reaction-delete.ts
new file mode 100644
index 00000000..85ed11e1
--- /dev/null
+++ b/apps/desktop/src/shared/mutations/nodes/node-reaction-delete.ts
@@ -0,0 +1,20 @@
+export type NodeReactionDeleteMutationInput = {
+ type: 'node_reaction_delete';
+ accountId: string;
+ workspaceId: string;
+ nodeId: string;
+ reaction: string;
+};
+
+export type NodeReactionDeleteMutationOutput = {
+ success: boolean;
+};
+
+declare module '@/shared/mutations' {
+ interface MutationMap {
+ node_reaction_delete: {
+ input: NodeReactionDeleteMutationInput;
+ output: NodeReactionDeleteMutationOutput;
+ };
+ }
+}
diff --git a/apps/desktop/src/shared/queries/chats/chat-list.ts b/apps/desktop/src/shared/queries/chats/chat-list.ts
index a9030076..5aaf1592 100644
--- a/apps/desktop/src/shared/queries/chats/chat-list.ts
+++ b/apps/desktop/src/shared/queries/chats/chat-list.ts
@@ -1,4 +1,4 @@
-import { ChatEntry } from '@colanode/core';
+import { LocalChatNode } from '@/shared/types/nodes';
export type ChatListQueryInput = {
type: 'chat_list';
@@ -12,7 +12,7 @@ declare module '@/shared/queries' {
interface QueryMap {
chat_list: {
input: ChatListQueryInput;
- output: ChatEntry[];
+ output: LocalChatNode[];
};
}
}
diff --git a/apps/desktop/src/shared/queries/databases/database-list.ts b/apps/desktop/src/shared/queries/databases/database-list.ts
index a88346a1..92aa3259 100644
--- a/apps/desktop/src/shared/queries/databases/database-list.ts
+++ b/apps/desktop/src/shared/queries/databases/database-list.ts
@@ -1,4 +1,4 @@
-import { DatabaseEntry } from '@colanode/core';
+import { LocalDatabaseNode } from '@/shared/types/nodes';
export type DatabaseListQueryInput = {
type: 'database_list';
@@ -10,7 +10,7 @@ declare module '@/shared/queries' {
interface QueryMap {
database_list: {
input: DatabaseListQueryInput;
- output: DatabaseEntry[];
+ output: LocalDatabaseNode[];
};
}
}
diff --git a/apps/desktop/src/shared/queries/databases/database-view-list.ts b/apps/desktop/src/shared/queries/databases/database-view-list.ts
new file mode 100644
index 00000000..039d7505
--- /dev/null
+++ b/apps/desktop/src/shared/queries/databases/database-view-list.ts
@@ -0,0 +1,17 @@
+import { LocalDatabaseViewNode } from '@/shared/types/nodes';
+
+export type DatabaseViewListQueryInput = {
+ type: 'database_view_list';
+ accountId: string;
+ workspaceId: string;
+ databaseId: string;
+};
+
+declare module '@/shared/queries' {
+ interface QueryMap {
+ database_view_list: {
+ input: DatabaseViewListQueryInput;
+ output: LocalDatabaseViewNode[];
+ };
+ }
+}
diff --git a/apps/desktop/src/shared/queries/entries/entry-breadcrumb-get.ts b/apps/desktop/src/shared/queries/entries/entry-breadcrumb-get.ts
deleted file mode 100644
index af79adbc..00000000
--- a/apps/desktop/src/shared/queries/entries/entry-breadcrumb-get.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-export type EntryBreadcrumbGetQueryInput = {
- type: 'entry_breadcrumb_get';
- entryId: string;
- accountId: string;
- workspaceId: string;
-};
-
-declare module '@/shared/queries' {
- interface QueryMap {
- entry_breadcrumb_get: {
- input: EntryBreadcrumbGetQueryInput;
- output: string[];
- };
- }
-}
diff --git a/apps/desktop/src/shared/queries/entries/entry-children-get.ts b/apps/desktop/src/shared/queries/entries/entry-children-get.ts
deleted file mode 100644
index 34549459..00000000
--- a/apps/desktop/src/shared/queries/entries/entry-children-get.ts
+++ /dev/null
@@ -1,18 +0,0 @@
-import { Entry, EntryType } from '@colanode/core';
-
-export type EntryChildrenGetQueryInput = {
- type: 'entry_children_get';
- entryId: string;
- accountId: string;
- workspaceId: string;
- types?: EntryType[];
-};
-
-declare module '@/shared/queries' {
- interface QueryMap {
- entry_children_get: {
- input: EntryChildrenGetQueryInput;
- output: Entry[];
- };
- }
-}
diff --git a/apps/desktop/src/shared/queries/entries/entry-get.ts b/apps/desktop/src/shared/queries/entries/entry-get.ts
deleted file mode 100644
index 933a880f..00000000
--- a/apps/desktop/src/shared/queries/entries/entry-get.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-import { Entry } from '@colanode/core';
-
-export type EntryGetQueryInput = {
- type: 'entry_get';
- entryId: string;
- accountId: string;
- workspaceId: string;
-};
-
-declare module '@/shared/queries' {
- interface QueryMap {
- entry_get: {
- input: EntryGetQueryInput;
- output: Entry | null;
- };
- }
-}
diff --git a/apps/desktop/src/shared/queries/files/file-breadcrumb-get.ts b/apps/desktop/src/shared/queries/files/file-breadcrumb-get.ts
deleted file mode 100644
index 4ce9fff0..00000000
--- a/apps/desktop/src/shared/queries/files/file-breadcrumb-get.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-export type FileBreadcrumbGetQueryInput = {
- type: 'file_breadcrumb_get';
- fileId: string;
- accountId: string;
- workspaceId: string;
-};
-
-declare module '@/shared/queries' {
- interface QueryMap {
- file_breadcrumb_get: {
- input: FileBreadcrumbGetQueryInput;
- output: string[];
- };
- }
-}
diff --git a/apps/desktop/src/shared/queries/files/file-get.ts b/apps/desktop/src/shared/queries/files/file-get.ts
index 46220bb2..1ac2440a 100644
--- a/apps/desktop/src/shared/queries/files/file-get.ts
+++ b/apps/desktop/src/shared/queries/files/file-get.ts
@@ -1,4 +1,4 @@
-import { FileWithState } from '@/shared/types/files';
+import { File } from '@/shared/types/files';
export type FileGetQueryInput = {
type: 'file_get';
@@ -11,7 +11,7 @@ declare module '@/shared/queries' {
interface QueryMap {
file_get: {
input: FileGetQueryInput;
- output: FileWithState | null;
+ output: File | null;
};
}
}
diff --git a/apps/desktop/src/shared/queries/files/file-list.ts b/apps/desktop/src/shared/queries/files/file-list.ts
index b33533bc..fe07d88b 100644
--- a/apps/desktop/src/shared/queries/files/file-list.ts
+++ b/apps/desktop/src/shared/queries/files/file-list.ts
@@ -1,4 +1,4 @@
-import { FileWithState } from '@/shared/types/files';
+import { File } from '@/shared/types/files';
export type FileListQueryInput = {
type: 'file_list';
@@ -13,7 +13,7 @@ declare module '@/shared/queries' {
interface QueryMap {
file_list: {
input: FileListQueryInput;
- output: FileWithState[];
+ output: File[];
};
}
}
diff --git a/apps/desktop/src/shared/queries/messages/message-breadcrumb-get.ts b/apps/desktop/src/shared/queries/messages/message-breadcrumb-get.ts
deleted file mode 100644
index 3aceac3e..00000000
--- a/apps/desktop/src/shared/queries/messages/message-breadcrumb-get.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-export type MessageBreadcrumbGetQueryInput = {
- type: 'message_breadcrumb_get';
- messageId: string;
- accountId: string;
- workspaceId: string;
-};
-
-declare module '@/shared/queries' {
- interface QueryMap {
- message_breadcrumb_get: {
- input: MessageBreadcrumbGetQueryInput;
- output: string[];
- };
- }
-}
diff --git a/apps/desktop/src/shared/queries/messages/message-get.ts b/apps/desktop/src/shared/queries/messages/message-get.ts
deleted file mode 100644
index 6f1907c7..00000000
--- a/apps/desktop/src/shared/queries/messages/message-get.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-import { MessageNode } from '@/shared/types/messages';
-
-export type MessageGetQueryInput = {
- type: 'message_get';
- messageId: string;
- accountId: string;
- workspaceId: string;
-};
-
-declare module '@/shared/queries' {
- interface QueryMap {
- message_get: {
- input: MessageGetQueryInput;
- output: MessageNode | null;
- };
- }
-}
diff --git a/apps/desktop/src/shared/queries/messages/message-list.ts b/apps/desktop/src/shared/queries/messages/message-list.ts
index 901ad758..846ea72d 100644
--- a/apps/desktop/src/shared/queries/messages/message-list.ts
+++ b/apps/desktop/src/shared/queries/messages/message-list.ts
@@ -1,4 +1,4 @@
-import { MessageNode } from '@/shared/types/messages';
+import { LocalMessageNode } from '@/shared/types/nodes';
export type MessageListQueryInput = {
type: 'message_list';
@@ -13,7 +13,7 @@ declare module '@/shared/queries' {
interface QueryMap {
message_list: {
input: MessageListQueryInput;
- output: MessageNode[];
+ output: LocalMessageNode[];
};
}
}
diff --git a/apps/desktop/src/shared/queries/messages/message-reaction-list.ts b/apps/desktop/src/shared/queries/messages/message-reaction-list.ts
deleted file mode 100644
index 3c6a4d85..00000000
--- a/apps/desktop/src/shared/queries/messages/message-reaction-list.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-import { MessageReaction } from '@/shared/types/messages';
-
-export type MessageReactionListQueryInput = {
- type: 'message_reaction_list';
- messageId: string;
- reaction: string;
- accountId: string;
- workspaceId: string;
- page: number;
- count: number;
-};
-
-declare module '@/shared/queries' {
- interface QueryMap {
- message_reaction_list: {
- input: MessageReactionListQueryInput;
- output: MessageReaction[];
- };
- }
-}
diff --git a/apps/desktop/src/shared/queries/messages/message-reactions-aggregate.ts b/apps/desktop/src/shared/queries/messages/message-reactions-aggregate.ts
deleted file mode 100644
index 88ef2552..00000000
--- a/apps/desktop/src/shared/queries/messages/message-reactions-aggregate.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-import { MessageReactionCount } from '@/shared/types/messages';
-
-export type MessageReactionsAggregateQueryInput = {
- type: 'message_reactions_aggregate';
- messageId: string;
- accountId: string;
- workspaceId: string;
-};
-
-declare module '@/shared/queries' {
- interface QueryMap {
- message_reactions_aggregate: {
- input: MessageReactionsAggregateQueryInput;
- output: MessageReactionCount[];
- };
- }
-}
diff --git a/apps/desktop/src/shared/queries/nodes/node-children-get.ts b/apps/desktop/src/shared/queries/nodes/node-children-get.ts
new file mode 100644
index 00000000..a8b35062
--- /dev/null
+++ b/apps/desktop/src/shared/queries/nodes/node-children-get.ts
@@ -0,0 +1,20 @@
+import { NodeType } from '@colanode/core';
+
+import { LocalNode } from '@/shared/types/nodes';
+
+export type NodeChildrenGetQueryInput = {
+ type: 'node_children_get';
+ nodeId: string;
+ accountId: string;
+ workspaceId: string;
+ types?: NodeType[];
+};
+
+declare module '@/shared/queries' {
+ interface QueryMap {
+ node_children_get: {
+ input: NodeChildrenGetQueryInput;
+ output: LocalNode[];
+ };
+ }
+}
diff --git a/apps/desktop/src/shared/queries/nodes/node-get.ts b/apps/desktop/src/shared/queries/nodes/node-get.ts
new file mode 100644
index 00000000..930355f7
--- /dev/null
+++ b/apps/desktop/src/shared/queries/nodes/node-get.ts
@@ -0,0 +1,17 @@
+import { LocalNode } from '@/shared/types/nodes';
+
+export type NodeGetQueryInput = {
+ type: 'node_get';
+ nodeId: string;
+ accountId: string;
+ workspaceId: string;
+};
+
+declare module '@/shared/queries' {
+ interface QueryMap {
+ node_get: {
+ input: NodeGetQueryInput;
+ output: LocalNode | null;
+ };
+ }
+}
diff --git a/apps/desktop/src/shared/queries/nodes/node-reaction-list.ts b/apps/desktop/src/shared/queries/nodes/node-reaction-list.ts
new file mode 100644
index 00000000..d8eccd21
--- /dev/null
+++ b/apps/desktop/src/shared/queries/nodes/node-reaction-list.ts
@@ -0,0 +1,20 @@
+import { NodeReaction } from '@/shared/types/nodes';
+
+export type NodeReactionListQueryInput = {
+ type: 'node_reaction_list';
+ nodeId: string;
+ reaction: string;
+ accountId: string;
+ workspaceId: string;
+ page: number;
+ count: number;
+};
+
+declare module '@/shared/queries' {
+ interface QueryMap {
+ node_reaction_list: {
+ input: NodeReactionListQueryInput;
+ output: NodeReaction[];
+ };
+ }
+}
diff --git a/apps/desktop/src/shared/queries/nodes/node-reactions-aggregate.ts b/apps/desktop/src/shared/queries/nodes/node-reactions-aggregate.ts
new file mode 100644
index 00000000..ae9a27a0
--- /dev/null
+++ b/apps/desktop/src/shared/queries/nodes/node-reactions-aggregate.ts
@@ -0,0 +1,17 @@
+import { NodeReactionCount } from '@/shared/types/nodes';
+
+export type NodeReactionsAggregateQueryInput = {
+ type: 'node_reactions_aggregate';
+ nodeId: string;
+ accountId: string;
+ workspaceId: string;
+};
+
+declare module '@/shared/queries' {
+ interface QueryMap {
+ node_reactions_aggregate: {
+ input: NodeReactionsAggregateQueryInput;
+ output: NodeReactionCount[];
+ };
+ }
+}
diff --git a/apps/desktop/src/shared/queries/nodes/node-tree-get.ts b/apps/desktop/src/shared/queries/nodes/node-tree-get.ts
new file mode 100644
index 00000000..c73bfada
--- /dev/null
+++ b/apps/desktop/src/shared/queries/nodes/node-tree-get.ts
@@ -0,0 +1,17 @@
+import { LocalNode } from '@/shared/types/nodes';
+
+export type NodeTreeGetQueryInput = {
+ type: 'node_tree_get';
+ nodeId: string;
+ accountId: string;
+ workspaceId: string;
+};
+
+declare module '@/shared/queries' {
+ interface QueryMap {
+ node_tree_get: {
+ input: NodeTreeGetQueryInput;
+ output: LocalNode[];
+ };
+ }
+}
diff --git a/apps/desktop/src/shared/queries/records/record-list.ts b/apps/desktop/src/shared/queries/records/record-list.ts
index f854ff1a..4fe2e02c 100644
--- a/apps/desktop/src/shared/queries/records/record-list.ts
+++ b/apps/desktop/src/shared/queries/records/record-list.ts
@@ -1,14 +1,15 @@
import {
- RecordEntry,
- ViewFilterAttributes,
- ViewSortAttributes,
+ DatabaseViewFilterAttributes,
+ DatabaseViewSortAttributes,
} from '@colanode/core';
+import { LocalRecordNode } from '@/shared/types/nodes';
+
export type RecordListQueryInput = {
type: 'record_list';
databaseId: string;
- filters: ViewFilterAttributes[];
- sorts: ViewSortAttributes[];
+ filters: DatabaseViewFilterAttributes[];
+ sorts: DatabaseViewSortAttributes[];
page: number;
count: number;
accountId: string;
@@ -19,7 +20,7 @@ declare module '@/shared/queries' {
interface QueryMap {
record_list: {
input: RecordListQueryInput;
- output: RecordEntry[];
+ output: LocalRecordNode[];
};
}
}
diff --git a/apps/desktop/src/shared/queries/records/record-search.ts b/apps/desktop/src/shared/queries/records/record-search.ts
index d660bef4..dc491fca 100644
--- a/apps/desktop/src/shared/queries/records/record-search.ts
+++ b/apps/desktop/src/shared/queries/records/record-search.ts
@@ -1,4 +1,4 @@
-import { RecordEntry } from '@colanode/core';
+import { LocalRecordNode } from '@/shared/types/nodes';
export type RecordSearchQueryInput = {
type: 'record_search';
@@ -13,7 +13,7 @@ declare module '@/shared/queries' {
interface QueryMap {
record_search: {
input: RecordSearchQueryInput;
- output: RecordEntry[];
+ output: LocalRecordNode[];
};
}
}
diff --git a/apps/desktop/src/shared/queries/spaces/space-list.ts b/apps/desktop/src/shared/queries/spaces/space-list.ts
index c00d1406..6e9f580e 100644
--- a/apps/desktop/src/shared/queries/spaces/space-list.ts
+++ b/apps/desktop/src/shared/queries/spaces/space-list.ts
@@ -1,4 +1,4 @@
-import { SpaceEntry } from '@colanode/core';
+import { LocalSpaceNode } from '@/shared/types/nodes';
export type SpaceListQueryInput = {
type: 'space_list';
@@ -12,7 +12,7 @@ declare module '@/shared/queries' {
interface QueryMap {
space_list: {
input: SpaceListQueryInput;
- output: SpaceEntry[];
+ output: LocalSpaceNode[];
};
}
}
diff --git a/apps/desktop/src/shared/types/entries.ts b/apps/desktop/src/shared/types/entries.ts
deleted file mode 100644
index ec888b61..00000000
--- a/apps/desktop/src/shared/types/entries.ts
+++ /dev/null
@@ -1,18 +0,0 @@
-import { EntryRole } from '@colanode/core';
-
-export type EntryCollaborator = {
- entryId: string;
- collaboratorId: string;
- role: EntryRole;
-};
-
-export type EntryInteraction = {
- entryId: string;
- collaboratorId: string;
- rootId: string;
- lastSeenAt: string | null;
- firstSeenAt: string | null;
- lastOpenedAt: string | null;
- firstOpenedAt: string | null;
- version: bigint;
-};
diff --git a/apps/desktop/src/shared/types/events.ts b/apps/desktop/src/shared/types/events.ts
index 46da9206..3cb9bd62 100644
--- a/apps/desktop/src/shared/types/events.ts
+++ b/apps/desktop/src/shared/types/events.ts
@@ -1,17 +1,12 @@
-import { Entry, Message } from '@colanode/core';
+import { Message } from '@colanode/core';
import { AppMetadata } from '@/shared/types/apps';
-import { EntryInteraction } from '@/shared/types/entries';
-import {
- MessageInteraction,
- MessageNode,
- MessageReaction,
-} from '@/shared/types/messages';
import { Account } from '@/shared/types/accounts';
import { Server } from '@/shared/types/servers';
import { Workspace, WorkspaceMetadata } from '@/shared/types/workspaces';
import { User } from '@/shared/types/users';
-import { File, FileInteraction, FileState } from '@/shared/types/files';
+import { File } from '@/shared/types/files';
+import { LocalNode, NodeInteraction, NodeReaction } from '@/shared/types/nodes';
export type UserCreatedEvent = {
type: 'user_created';
@@ -34,74 +29,46 @@ export type UserDeletedEvent = {
user: User;
};
-export type EntryCreatedEvent = {
- type: 'entry_created';
+export type NodeCreatedEvent = {
+ type: 'node_created';
accountId: string;
workspaceId: string;
- entry: Entry;
+ node: LocalNode;
};
-export type EntryUpdatedEvent = {
- type: 'entry_updated';
+export type NodeUpdatedEvent = {
+ type: 'node_updated';
accountId: string;
workspaceId: string;
- entry: Entry;
+ node: LocalNode;
};
-export type EntryDeletedEvent = {
- type: 'entry_deleted';
+export type NodeDeletedEvent = {
+ type: 'node_deleted';
accountId: string;
workspaceId: string;
- entry: Entry;
+ node: LocalNode;
};
-export type EntryInteractionUpdatedEvent = {
- type: 'entry_interaction_updated';
+export type NodeInteractionUpdatedEvent = {
+ type: 'node_interaction_updated';
accountId: string;
workspaceId: string;
- entryInteraction: EntryInteraction;
+ nodeInteraction: NodeInteraction;
};
-export type MessageCreatedEvent = {
- type: 'message_created';
+export type NodeReactionCreatedEvent = {
+ type: 'node_reaction_created';
accountId: string;
workspaceId: string;
- message: MessageNode;
+ nodeReaction: NodeReaction;
};
-export type MessageUpdatedEvent = {
- type: 'message_updated';
+export type NodeReactionDeletedEvent = {
+ type: 'node_reaction_deleted';
accountId: string;
workspaceId: string;
- message: MessageNode;
-};
-
-export type MessageDeletedEvent = {
- type: 'message_deleted';
- accountId: string;
- workspaceId: string;
- message: MessageNode;
-};
-
-export type MessageReactionCreatedEvent = {
- type: 'message_reaction_created';
- accountId: string;
- workspaceId: string;
- messageReaction: MessageReaction;
-};
-
-export type MessageReactionDeletedEvent = {
- type: 'message_reaction_deleted';
- accountId: string;
- workspaceId: string;
- messageReaction: MessageReaction;
-};
-
-export type MessageInteractionUpdatedEvent = {
- type: 'message_interaction_updated';
- accountId: string;
- workspaceId: string;
- messageInteraction: MessageInteraction;
+ nodeReaction: NodeReaction;
};
export type FileCreatedEvent = {
@@ -125,34 +92,6 @@ export type FileDeletedEvent = {
file: File;
};
-export type FileStateCreatedEvent = {
- type: 'file_state_created';
- accountId: string;
- workspaceId: string;
- fileState: FileState;
-};
-
-export type FileStateUpdatedEvent = {
- type: 'file_state_updated';
- accountId: string;
- workspaceId: string;
- fileState: FileState;
-};
-
-export type FileStateDeletedEvent = {
- type: 'file_state_deleted';
- accountId: string;
- workspaceId: string;
- fileState: FileState;
-};
-
-export type FileInteractionUpdatedEvent = {
- type: 'file_interaction_updated';
- accountId: string;
- workspaceId: string;
- fileInteraction: FileInteraction;
-};
-
export type AccountCreatedEvent = {
type: 'account_created';
account: Account;
@@ -207,14 +146,14 @@ export type CollaborationCreatedEvent = {
type: 'collaboration_created';
accountId: string;
workspaceId: string;
- entryId: string;
+ nodeId: string;
};
export type CollaborationDeletedEvent = {
type: 'collaboration_deleted';
accountId: string;
workspaceId: string;
- entryId: string;
+ nodeId: string;
};
export type ServerAvailabilityChangedEvent = {
@@ -267,16 +206,12 @@ export type Event =
| UserCreatedEvent
| UserUpdatedEvent
| UserDeletedEvent
- | EntryCreatedEvent
- | EntryUpdatedEvent
- | EntryDeletedEvent
- | EntryInteractionUpdatedEvent
- | MessageCreatedEvent
- | MessageUpdatedEvent
- | MessageDeletedEvent
- | MessageReactionCreatedEvent
- | MessageReactionDeletedEvent
- | MessageInteractionUpdatedEvent
+ | NodeCreatedEvent
+ | NodeUpdatedEvent
+ | NodeDeletedEvent
+ | NodeInteractionUpdatedEvent
+ | NodeReactionCreatedEvent
+ | NodeReactionDeletedEvent
| AccountCreatedEvent
| AccountUpdatedEvent
| AccountDeletedEvent
@@ -288,10 +223,6 @@ export type Event =
| FileCreatedEvent
| FileUpdatedEvent
| FileDeletedEvent
- | FileStateCreatedEvent
- | FileStateUpdatedEvent
- | FileStateDeletedEvent
- | FileInteractionUpdatedEvent
| QueryResultUpdatedEvent
| RadarDataUpdatedEvent
| ServerAvailabilityChangedEvent
diff --git a/apps/desktop/src/shared/types/files.ts b/apps/desktop/src/shared/types/files.ts
index a31a0fac..57bf2970 100644
--- a/apps/desktop/src/shared/types/files.ts
+++ b/apps/desktop/src/shared/types/files.ts
@@ -13,8 +13,8 @@ export type File = {
id: string;
type: FileType;
parentId: string;
- entryId: string;
rootId: string;
+ revision: bigint;
name: string;
originalName: string;
extension: string;
@@ -24,8 +24,13 @@ export type File = {
createdBy: string;
updatedAt: string | null;
updatedBy: string | null;
+ downloadStatus: DownloadStatus;
+ downloadProgress: number;
+ downloadRetries: number;
+ uploadStatus: UploadStatus;
+ uploadProgress: number;
+ uploadRetries: number;
status: FileStatus;
- version: bigint;
};
export enum DownloadStatus {
@@ -41,33 +46,3 @@ export enum UploadStatus {
Completed = 2,
Failed = 3,
}
-
-export type FileState = {
- fileId: string;
- downloadProgress: number;
- downloadStatus: DownloadStatus;
- downloadRetries: number;
- uploadProgress: number;
- uploadStatus: UploadStatus;
- uploadRetries: number;
- createdAt: string;
- updatedAt: string | null;
-};
-
-export type FileWithState = File & {
- downloadProgress: number;
- downloadStatus: DownloadStatus;
- uploadProgress: number;
- uploadStatus: UploadStatus;
-};
-
-export type FileInteraction = {
- fileId: string;
- collaboratorId: string;
- rootId: string;
- lastSeenAt: string | null;
- firstSeenAt: string | null;
- lastOpenedAt: string | null;
- firstOpenedAt: string | null;
- version: bigint;
-};
diff --git a/apps/desktop/src/shared/types/messages.ts b/apps/desktop/src/shared/types/messages.ts
deleted file mode 100644
index 8f5fded1..00000000
--- a/apps/desktop/src/shared/types/messages.ts
+++ /dev/null
@@ -1,39 +0,0 @@
-import { MessageAttributes, MessageType } from '@colanode/core';
-
-export type MessageNode = {
- id: string;
- type: MessageType;
- parentId: string;
- rootId: string;
- attributes: MessageAttributes;
- createdAt: string;
- createdBy: string;
- updatedAt: string | null;
- updatedBy: string | null;
- version: bigint;
-};
-
-export type MessageReaction = {
- messageId: string;
- collaboratorId: string;
- rootId: string;
- reaction: string;
- createdAt: string;
-};
-
-export type MessageReactionCount = {
- reaction: string;
- count: number;
- reacted: boolean;
-};
-
-export type MessageInteraction = {
- messageId: string;
- collaboratorId: string;
- rootId: string;
- firstSeenAt: string | null;
- lastSeenAt: string | null;
- firstOpenedAt: string | null;
- lastOpenedAt: string | null;
- version: bigint;
-};
diff --git a/apps/desktop/src/shared/types/nodes.ts b/apps/desktop/src/shared/types/nodes.ts
new file mode 100644
index 00000000..a0febd27
--- /dev/null
+++ b/apps/desktop/src/shared/types/nodes.ts
@@ -0,0 +1,81 @@
+import {
+ NodeRole,
+ ChannelNode,
+ FolderNode,
+ FileNode,
+ DatabaseViewNode,
+ DatabaseNode,
+ ChatNode,
+ PageNode,
+ SpaceNode,
+ MessageNode,
+ RecordNode,
+} from '@colanode/core';
+
+export type NodeCollaborator = {
+ nodeId: string;
+ collaboratorId: string;
+ role: NodeRole;
+};
+
+export type NodeInteraction = {
+ nodeId: string;
+ collaboratorId: string;
+ rootId: string;
+ revision: bigint;
+ lastSeenAt: string | null;
+ firstSeenAt: string | null;
+ lastOpenedAt: string | null;
+ firstOpenedAt: string | null;
+};
+
+export type NodeReaction = {
+ nodeId: string;
+ collaboratorId: string;
+ rootId: string;
+ reaction: string;
+ createdAt: string;
+};
+
+export type NodeReactionCount = {
+ reaction: string;
+ count: number;
+ reacted: boolean;
+};
+
+export type LocalNodeBase = {
+ localRevision: bigint;
+ serverRevision: bigint;
+};
+
+export type LocalChannelNode = ChannelNode & LocalNodeBase;
+
+export type LocalChatNode = ChatNode & LocalNodeBase;
+
+export type LocalPageNode = PageNode & LocalNodeBase;
+
+export type LocalDatabaseNode = DatabaseNode & LocalNodeBase;
+
+export type LocalDatabaseViewNode = DatabaseViewNode & LocalNodeBase;
+
+export type LocalFileNode = FileNode & LocalNodeBase;
+
+export type LocalFolderNode = FolderNode & LocalNodeBase;
+
+export type LocalRecordNode = RecordNode & LocalNodeBase;
+
+export type LocalMessageNode = MessageNode & LocalNodeBase;
+
+export type LocalSpaceNode = SpaceNode & LocalNodeBase;
+
+export type LocalNode =
+ | LocalChannelNode
+ | LocalChatNode
+ | LocalDatabaseNode
+ | LocalDatabaseViewNode
+ | LocalFileNode
+ | LocalFolderNode
+ | LocalPageNode
+ | LocalRecordNode
+ | LocalMessageNode
+ | LocalSpaceNode;
diff --git a/apps/server/src/api/client/controllers/accounts/email-login.ts b/apps/server/src/api/client/controllers/accounts/email-login.ts
index 932a8b85..5bbc1c8d 100644
--- a/apps/server/src/api/client/controllers/accounts/email-login.ts
+++ b/apps/server/src/api/client/controllers/accounts/email-login.ts
@@ -3,10 +3,13 @@ import { AccountStatus, EmailLoginInput, ApiErrorCode } from '@colanode/core';
import argon2 from '@node-rs/argon2';
import { database } from '@/data/database';
-import { accountService } from '@/services/account-service';
import { ResponseBuilder } from '@/lib/response-builder';
import { rateLimitService } from '@/services/rate-limit-service';
import { configuration } from '@/lib/configuration';
+import {
+ buildLoginSuccessOutput,
+ buildLoginVerifyOutput,
+} from '@/lib/accounts';
export const emailLoginHandler = async (
req: Request,
@@ -48,7 +51,7 @@ export const emailLoginHandler = async (
if (account.status === AccountStatus.Unverified) {
if (configuration.account.verificationType === 'email') {
- const output = await accountService.buildLoginVerifyOutput(account);
+ const output = await buildLoginVerifyOutput(account);
return ResponseBuilder.success(res, output);
}
@@ -68,7 +71,7 @@ export const emailLoginHandler = async (
});
}
- const output = await accountService.buildLoginSuccessOutput(account, {
+ const output = await buildLoginSuccessOutput(account, {
ip: res.locals.ip,
platform: input.platform,
version: input.version,
diff --git a/apps/server/src/api/client/controllers/accounts/email-register.ts b/apps/server/src/api/client/controllers/accounts/email-register.ts
index e4c0c7cc..894447bd 100644
--- a/apps/server/src/api/client/controllers/accounts/email-register.ts
+++ b/apps/server/src/api/client/controllers/accounts/email-register.ts
@@ -10,10 +10,13 @@ import argon2 from '@node-rs/argon2';
import { database } from '@/data/database';
import { SelectAccount } from '@/data/schema';
-import { accountService } from '@/services/account-service';
import { ResponseBuilder } from '@/lib/response-builder';
import { rateLimitService } from '@/services/rate-limit-service';
import { configuration } from '@/lib/configuration';
+import {
+ buildLoginSuccessOutput,
+ buildLoginVerifyOutput,
+} from '@/lib/accounts';
export const emailRegisterHandler = async (
req: Request,
@@ -102,7 +105,7 @@ export const emailRegisterHandler = async (
if (account.status === AccountStatus.Unverified) {
if (configuration.account.verificationType === 'email') {
- const output = await accountService.buildLoginVerifyOutput(account);
+ const output = await buildLoginVerifyOutput(account);
return ResponseBuilder.success(res, output);
}
@@ -113,7 +116,7 @@ export const emailRegisterHandler = async (
});
}
- const output = await accountService.buildLoginSuccessOutput(account, {
+ const output = await buildLoginSuccessOutput(account, {
ip: res.locals.ip,
platform: input.platform,
version: input.version,
diff --git a/apps/server/src/api/client/controllers/accounts/email-verify.ts b/apps/server/src/api/client/controllers/accounts/email-verify.ts
index f0acb13d..5b711ff8 100644
--- a/apps/server/src/api/client/controllers/accounts/email-verify.ts
+++ b/apps/server/src/api/client/controllers/accounts/email-verify.ts
@@ -3,11 +3,11 @@ import { Request, Response } from 'express';
import { database } from '@/data/database';
import { ResponseBuilder } from '@/lib/response-builder';
-import { accountService } from '@/services/account-service';
+import { buildLoginSuccessOutput, verifyOtpCode } from '@/lib/accounts';
export const emailVerifyHandler = async (req: Request, res: Response) => {
const input: EmailVerifyInput = req.body;
- const accountId = await accountService.verifyOtpCode(input.id, input.otp);
+ const accountId = await verifyOtpCode(input.id, input.otp);
if (!accountId) {
return ResponseBuilder.badRequest(res, {
@@ -32,7 +32,7 @@ export const emailVerifyHandler = async (req: Request, res: Response) => {
});
}
- const output = await accountService.buildLoginSuccessOutput(account, {
+ const output = await buildLoginSuccessOutput(account, {
ip: res.locals.ip,
platform: input.platform,
version: input.version,
diff --git a/apps/server/src/api/client/controllers/accounts/login-google.ts b/apps/server/src/api/client/controllers/accounts/login-google.ts
index 44b70110..eaab8718 100644
--- a/apps/server/src/api/client/controllers/accounts/login-google.ts
+++ b/apps/server/src/api/client/controllers/accounts/login-google.ts
@@ -10,10 +10,10 @@ import {
import axios from 'axios';
import { database } from '@/data/database';
-import { accountService } from '@/services/account-service';
import { ResponseBuilder } from '@/lib/response-builder';
import { rateLimitService } from '@/services/rate-limit-service';
import { configuration } from '@/lib/configuration';
+import { buildLoginSuccessOutput } from '@/lib/accounts';
const GoogleUserInfoUrl = 'https://www.googleapis.com/oauth2/v1/userinfo';
@@ -76,14 +76,11 @@ export const loginWithGoogleHandler = async (
.execute();
}
- const output = await accountService.buildLoginSuccessOutput(
- existingAccount,
- {
- ip: res.locals.ip,
- platform: input.platform,
- version: input.version,
- }
- );
+ const output = await buildLoginSuccessOutput(existingAccount, {
+ ip: res.locals.ip,
+ platform: input.platform,
+ version: input.version,
+ });
return ResponseBuilder.success(res, output);
}
@@ -108,7 +105,7 @@ export const loginWithGoogleHandler = async (
});
}
- const output = await accountService.buildLoginSuccessOutput(newAccount, {
+ const output = await buildLoginSuccessOutput(newAccount, {
ip: res.locals.ip,
platform: input.platform,
version: input.version,
diff --git a/apps/server/src/api/client/controllers/workspaces/files/file-download-get.ts b/apps/server/src/api/client/controllers/workspaces/files/file-download-get.ts
index a30f0628..a243add2 100644
--- a/apps/server/src/api/client/controllers/workspaces/files/file-download-get.ts
+++ b/apps/server/src/api/client/controllers/workspaces/files/file-download-get.ts
@@ -1,16 +1,16 @@
import { Request, Response } from 'express';
import {
CreateDownloadOutput,
- hasEntryRole,
+ hasNodeRole,
ApiErrorCode,
- extractEntryRole,
+ extractNodeRole,
FileStatus,
} from '@colanode/core';
import { GetObjectCommand } from '@aws-sdk/client-s3';
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
import { database } from '@/data/database';
-import { fetchEntry, mapEntry } from '@/lib/entries';
+import { fetchNode, mapNode } from '@/lib/nodes';
import { fileS3 } from '@/data/storage';
import { ResponseBuilder } from '@/lib/response-builder';
import { configuration } from '@/lib/configuration';
@@ -41,7 +41,7 @@ export const fileDownloadGetHandler = async (
});
}
- const root = await fetchEntry(file.root_id);
+ const root = await fetchNode(file.root_id);
if (!root) {
return ResponseBuilder.badRequest(res, {
code: ApiErrorCode.RootNotFound,
@@ -49,8 +49,8 @@ export const fileDownloadGetHandler = async (
});
}
- const role = extractEntryRole(mapEntry(root), res.locals.user.id);
- if (role === null || !hasEntryRole(role, 'viewer')) {
+ const role = extractNodeRole(mapNode(root), res.locals.user.id);
+ if (role === null || !hasNodeRole(role, 'viewer')) {
return ResponseBuilder.forbidden(res, {
code: ApiErrorCode.FileNoAccess,
message: 'You do not have access to this file.',
diff --git a/apps/server/src/api/client/controllers/workspaces/mutations/mutations-sync.ts b/apps/server/src/api/client/controllers/workspaces/mutations/mutations-sync.ts
index 12397491..0a599915 100644
--- a/apps/server/src/api/client/controllers/workspaces/mutations/mutations-sync.ts
+++ b/apps/server/src/api/client/controllers/workspaces/mutations/mutations-sync.ts
@@ -4,27 +4,19 @@ import {
SyncMutationResult,
SyncMutationStatus,
Mutation,
- ApplyCreateTransactionMutation,
- ApplyUpdateTransactionMutation,
- ApplyDeleteTransactionMutation,
- CreateFileMutation,
- CreateMessageMutation,
- CreateMessageReactionMutation,
- DeleteMessageReactionMutation,
- MarkEntrySeenMutation,
- MarkEntryOpenedMutation,
- MarkMessageSeenMutation,
- MarkFileSeenMutation,
- MarkFileOpenedMutation,
- DeleteFileMutation,
- DeleteMessageMutation,
+ ApplyNodeTransactionMutation,
+ CreateNodeReactionMutation,
+ DeleteNodeReactionMutation,
+ MarkNodeSeenMutation,
+ MarkNodeOpenedMutation,
+ DeleteNodeMutation,
} from '@colanode/core';
import { SelectUser } from '@/data/schema';
-import { entryService } from '@/services/entry-service';
-import { fileService } from '@/services/file-service';
-import { messageService } from '@/services/message-service';
import { ResponseBuilder } from '@/lib/response-builder';
+import { applyNodeTransaction, deleteNode } from '@/lib/nodes';
+import { createNodeReaction, deleteNodeReaction } from '@/lib/node-reactions';
+import { markNodeAsOpened, markNodeAsSeen } from '@/lib/node-interactions';
export const mutationsSyncHandler = async (
req: Request,
@@ -56,69 +48,33 @@ const handleMutation = async (
user: SelectUser,
mutation: Mutation
): Promise<SyncMutationStatus> => {
- if (mutation.type === 'apply_create_transaction') {
- return await handleCreateTransaction(user, mutation);
- } else if (mutation.type === 'apply_update_transaction') {
- return await handleUpdateTransaction(user, mutation);
- } else if (mutation.type === 'apply_delete_transaction') {
- return await handleDeleteTransaction(user, mutation);
- } else if (mutation.type === 'create_file') {
- return await handleCreateFile(user, mutation);
- } else if (mutation.type === 'delete_file') {
- return await handleDeleteFile(user, mutation);
- } else if (mutation.type === 'create_message') {
- return await handleCreateMessage(user, mutation);
- } else if (mutation.type === 'delete_message') {
- return await handleDeleteMessage(user, mutation);
- } else if (mutation.type === 'create_message_reaction') {
- return await handleCreateMessageReaction(user, mutation);
- } else if (mutation.type === 'delete_message_reaction') {
- return await handleDeleteMessageReaction(user, mutation);
- } else if (mutation.type === 'mark_entry_seen') {
- return await handleMarkEntrySeenMutation(user, mutation);
- } else if (mutation.type === 'mark_entry_opened') {
- return await handleMarkEntryOpenedMutation(user, mutation);
- } else if (mutation.type === 'mark_message_seen') {
- return await handleMarkMessageSeenMutation(user, mutation);
- } else if (mutation.type === 'mark_file_seen') {
- return await handleMarkFileSeenMutation(user, mutation);
- } else if (mutation.type === 'mark_file_opened') {
- return await markFileOpenedMutation(user, mutation);
+ if (mutation.type === 'apply_node_transaction') {
+ return await handleApplyNodeTransaction(user, mutation);
+ } else if (mutation.type === 'delete_node') {
+ return await handleDeleteNode(user, mutation);
+ } else if (mutation.type === 'create_node_reaction') {
+ return await handleCreateNodeReaction(user, mutation);
+ } else if (mutation.type === 'delete_node_reaction') {
+ return await handleDeleteNodeReaction(user, mutation);
+ } else if (mutation.type === 'mark_node_seen') {
+ return await handleMarkNodeSeen(user, mutation);
+ } else if (mutation.type === 'mark_node_opened') {
+ return await handleMarkNodeOpened(user, mutation);
} else {
return 'error';
}
};
-const handleCreateTransaction = async (
+const handleApplyNodeTransaction = async (
user: SelectUser,
- mutation: ApplyCreateTransactionMutation
+ mutation: ApplyNodeTransactionMutation
): Promise<SyncMutationStatus> => {
- const output = await entryService.applyCreateTransaction(user, {
+ const output = await applyNodeTransaction(user, {
id: mutation.data.id,
- entryId: mutation.data.entryId,
- rootId: mutation.data.rootId,
- data: mutation.data.data,
- createdAt: new Date(mutation.data.createdAt),
- });
-
- if (!output) {
- return 'error';
- }
-
- return 'success';
-};
-
-const handleUpdateTransaction = async (
- user: SelectUser,
- mutation: ApplyUpdateTransactionMutation
-): Promise<SyncMutationStatus> => {
- const output = await entryService.applyUpdateTransaction(user, {
- id: mutation.data.id,
- entryId: mutation.data.entryId,
- rootId: mutation.data.rootId,
- userId: mutation.data.createdBy,
+ nodeId: mutation.data.nodeId,
data: mutation.data.data,
createdAt: new Date(mutation.data.createdAt),
+ operation: mutation.data.operation,
});
if (!output) {
@@ -128,15 +84,14 @@ const handleUpdateTransaction = async (
return 'success';
};
-const handleDeleteTransaction = async (
+const handleDeleteNode = async (
user: SelectUser,
- mutation: ApplyDeleteTransactionMutation
+ mutation: DeleteNodeMutation
): Promise<SyncMutationStatus> => {
- const output = await entryService.applyDeleteTransaction(user, {
+ const output = await deleteNode(user, {
id: mutation.data.id,
- entryId: mutation.data.entryId,
rootId: mutation.data.rootId,
- createdAt: new Date(mutation.data.createdAt),
+ deletedAt: mutation.data.deletedAt,
});
if (!output) {
@@ -146,90 +101,34 @@ const handleDeleteTransaction = async (
return 'success';
};
-const handleCreateFile = async (
- user: SelectUser,
- mutation: CreateFileMutation
-): Promise<SyncMutationStatus> => {
- const output = await fileService.createFile(user, mutation);
- return output ? 'success' : 'error';
-};
-
-const handleDeleteFile = async (
- user: SelectUser,
- mutation: DeleteFileMutation
-): Promise<SyncMutationStatus> => {
- const output = await fileService.deleteFile(user, mutation);
- return output ? 'success' : 'error';
-};
-
-const handleCreateMessage = async (
- user: SelectUser,
- mutation: CreateMessageMutation
-): Promise<SyncMutationStatus> => {
- const output = await messageService.createMessage(user, mutation);
- return output ? 'success' : 'error';
-};
-
-const handleDeleteMessage = async (
- user: SelectUser,
- mutation: DeleteMessageMutation
-): Promise<SyncMutationStatus> => {
- const output = await messageService.deleteMessage(user, mutation);
- return output ? 'success' : 'error';
-};
-
-const handleCreateMessageReaction = async (
- user: SelectUser,
- mutation: CreateMessageReactionMutation
-): Promise<SyncMutationStatus> => {
- const output = await messageService.createMessageReaction(user, mutation);
- return output ? 'success' : 'error';
-};
-
-const handleDeleteMessageReaction = async (
- user: SelectUser,
- mutation: DeleteMessageReactionMutation
-): Promise<SyncMutationStatus> => {
- const output = await messageService.deleteMessageReaction(user, mutation);
- return output ? 'success' : 'error';
-};
-
-const handleMarkEntrySeenMutation = async (
- user: SelectUser,
- mutation: MarkEntrySeenMutation
-): Promise<SyncMutationStatus> => {
- const output = await entryService.markEntryAsSeen(user, mutation);
- return output ? 'success' : 'error';
-};
-
-const handleMarkEntryOpenedMutation = async (
+const handleCreateNodeReaction = async (
user: SelectUser,
- mutation: MarkEntryOpenedMutation
+ mutation: CreateNodeReactionMutation
): Promise<SyncMutationStatus> => {
- const output = await entryService.markEntryAsOpened(user, mutation);
+ const output = await createNodeReaction(user, mutation);
return output ? 'success' : 'error';
};
-const handleMarkMessageSeenMutation = async (
+const handleDeleteNodeReaction = async (
user: SelectUser,
- mutation: MarkMessageSeenMutation
+ mutation: DeleteNodeReactionMutation
): Promise<SyncMutationStatus> => {
- const output = await messageService.markMessageAsSeen(user, mutation);
+ const output = await deleteNodeReaction(user, mutation);
return output ? 'success' : 'error';
};
-const handleMarkFileSeenMutation = async (
+const handleMarkNodeSeen = async (
user: SelectUser,
- mutation: MarkFileSeenMutation
+ mutation: MarkNodeSeenMutation
): Promise<SyncMutationStatus> => {
- const output = await fileService.markFileAsSeen(user, mutation);
+ const output = await markNodeAsSeen(user, mutation);
return output ? 'success' : 'error';
};
-const markFileOpenedMutation = async (
+const handleMarkNodeOpened = async (
user: SelectUser,
- mutation: MarkFileOpenedMutation
+ mutation: MarkNodeOpenedMutation
): Promise<SyncMutationStatus> => {
- const output = await fileService.markFileAsOpened(user, mutation);
+ const output = await markNodeAsOpened(user, mutation);
return output ? 'success' : 'error';
};
diff --git a/apps/server/src/api/client/controllers/workspaces/workspace-create.ts b/apps/server/src/api/client/controllers/workspaces/workspace-create.ts
index 0aea5d52..281f2d64 100644
--- a/apps/server/src/api/client/controllers/workspaces/workspace-create.ts
+++ b/apps/server/src/api/client/controllers/workspaces/workspace-create.ts
@@ -1,9 +1,9 @@
import { WorkspaceCreateInput, ApiErrorCode } from '@colanode/core';
import { Request, Response } from 'express';
-import { workspaceService } from '@/services/workspace-service';
import { database } from '@/data/database';
import { ResponseBuilder } from '@/lib/response-builder';
+import { createWorkspace } from '@/lib/workspaces';
export const workspaceCreateHandler = async (
req: Request,
@@ -31,6 +31,6 @@ export const workspaceCreateHandler = async (
});
}
- const output = await workspaceService.createWorkspace(account, input);
+ const output = await createWorkspace(account, input);
return ResponseBuilder.success(res, output);
};
diff --git a/apps/server/src/data/migrations.ts b/apps/server/src/data/migrations.ts
deleted file mode 100644
index a4872075..00000000
--- a/apps/server/src/data/migrations.ts
+++ /dev/null
@@ -1,987 +0,0 @@
-import { Migration, sql } from 'kysely';
-
-const createAccountsTable: Migration = {
- up: async (db) => {
- await db.schema
- .createTable('accounts')
- .addColumn('id', 'varchar(30)', (col) => col.notNull().primaryKey())
- .addColumn('name', 'varchar(256)', (col) => col.notNull())
- .addColumn('email', 'varchar(256)', (col) => col.notNull().unique())
- .addColumn('avatar', 'varchar(256)')
- .addColumn('password', 'varchar(256)')
- .addColumn('attrs', 'jsonb')
- .addColumn('created_at', 'timestamptz', (col) => col.notNull())
- .addColumn('updated_at', 'timestamptz')
- .addColumn('status', 'integer', (col) => col.notNull())
- .execute();
- },
- down: async (db) => {
- await db.schema.dropTable('accounts').execute();
- },
-};
-
-const createDevicesTable: Migration = {
- up: async (db) => {
- await db.schema
- .createTable('devices')
- .addColumn('id', 'varchar(30)', (col) => col.notNull().primaryKey())
- .addColumn('account_id', 'varchar(30)', (col) => col.notNull())
- .addColumn('token_hash', 'varchar(100)', (col) => col.notNull())
- .addColumn('token_salt', 'varchar(100)', (col) => col.notNull())
- .addColumn('token_generated_at', 'timestamptz', (col) => col.notNull())
- .addColumn('previous_token_hash', 'varchar(100)')
- .addColumn('previous_token_salt', 'varchar(100)')
- .addColumn('type', 'integer', (col) => col.notNull())
- .addColumn('version', 'varchar(30)', (col) => col.notNull())
- .addColumn('platform', 'varchar(30)')
- .addColumn('ip', 'varchar(45)')
- .addColumn('created_at', 'timestamptz', (col) => col.notNull())
- .addColumn('synced_at', 'timestamptz')
- .execute();
-
- await db.schema
- .createIndex('devices_account_id_idx')
- .on('devices')
- .column('account_id')
- .execute();
- },
- down: async (db) => {
- await db.schema.dropIndex('devices_account_id_idx').execute();
- await db.schema.dropTable('devices').execute();
- },
-};
-
-const createWorkspacesTable: Migration = {
- up: async (db) => {
- await db.schema
- .createTable('workspaces')
- .addColumn('id', 'varchar(30)', (col) => col.notNull().primaryKey())
- .addColumn('name', 'varchar(256)', (col) => col.notNull())
- .addColumn('description', 'varchar(256)')
- .addColumn('avatar', 'varchar(256)')
- .addColumn('attrs', 'jsonb')
- .addColumn('created_at', 'timestamptz', (col) => col.notNull())
- .addColumn('created_by', 'varchar(30)', (col) => col.notNull())
- .addColumn('updated_at', 'timestamptz')
- .addColumn('updated_by', 'varchar(30)')
- .addColumn('status', 'integer', (col) => col.notNull())
- .execute();
- },
- down: async (db) => {
- await db.schema.dropTable('workspaces').execute();
- },
-};
-
-const createUsersTable: Migration = {
- up: async (db) => {
- await sql`
- CREATE SEQUENCE IF NOT EXISTS users_version_sequence
- START WITH 1000000000
- INCREMENT BY 1
- NO MINVALUE
- NO MAXVALUE
- CACHE 1;
- `.execute(db);
-
- await db.schema
- .createTable('users')
- .addColumn('id', 'varchar(30)', (col) => col.notNull().primaryKey())
- .addColumn('workspace_id', 'varchar(30)', (col) => col.notNull())
- .addColumn('account_id', 'varchar(30)', (col) => col.notNull())
- .addColumn('email', 'varchar(256)', (col) => col.notNull())
- .addColumn('name', 'varchar(256)', (col) => col.notNull())
- .addColumn('avatar', 'varchar(256)')
- .addColumn('custom_name', 'varchar(256)')
- .addColumn('custom_avatar', 'varchar(256)')
- .addColumn('role', 'varchar(30)', (col) => col.notNull())
- .addColumn('storage_limit', 'bigint', (col) => col.notNull())
- .addColumn('max_file_size', 'bigint', (col) => col.notNull())
- .addColumn('created_at', 'timestamptz', (col) => col.notNull())
- .addColumn('created_by', 'varchar(30)', (col) => col.notNull())
- .addColumn('updated_at', 'timestamptz')
- .addColumn('updated_by', 'varchar(30)')
- .addColumn('status', 'integer', (col) => col.notNull())
- .addColumn('version', 'bigint', (col) =>
- col.notNull().defaultTo(sql`nextval('users_version_sequence')`)
- )
- .addUniqueConstraint('unique_workspace_account_combination', [
- 'workspace_id',
- 'account_id',
- ])
- .execute();
-
- await db.schema
- .createIndex('users_workspace_id_version_idx')
- .on('users')
- .columns(['workspace_id', 'version'])
- .execute();
-
- await sql`
- CREATE OR REPLACE FUNCTION update_user_version() RETURNS TRIGGER AS $$
- BEGIN
- NEW.version = nextval('users_version_sequence');
- RETURN NEW;
- END;
- $$ LANGUAGE plpgsql;
-
- CREATE TRIGGER trg_update_user_version
- BEFORE UPDATE ON users
- FOR EACH ROW
- EXECUTE FUNCTION update_user_version();
- `.execute(db);
- },
- down: async (db) => {
- await sql`
- DROP TRIGGER IF EXISTS trg_update_user_version ON users;
- DROP FUNCTION IF EXISTS update_user_version();
- `.execute(db);
-
- await db.schema.dropIndex('users_workspace_id_version_idx').execute();
- await db.schema.dropTable('users').execute();
- await sql`DROP SEQUENCE IF EXISTS users_version_sequence`.execute(db);
- },
-};
-
-const createEntriesTable: Migration = {
- up: async (db) => {
- await db.schema
- .createTable('entries')
- .addColumn('id', 'varchar(30)', (col) => col.notNull().primaryKey())
- .addColumn('type', 'varchar(30)', (col) =>
- col.generatedAlwaysAs(sql`(attributes->>'type')::VARCHAR(30)`).stored()
- )
- .addColumn('parent_id', 'varchar(30)', (col) =>
- col
- .generatedAlwaysAs(sql`(attributes->>'parentId')::VARCHAR(30)`)
- .stored()
- )
- .addColumn('root_id', 'varchar(30)', (col) => col.notNull())
- .addColumn('workspace_id', 'varchar(30)', (col) => col.notNull())
- .addColumn('attributes', 'jsonb', (col) => col.notNull())
- .addColumn('created_at', 'timestamptz', (col) => col.notNull())
- .addColumn('updated_at', 'timestamptz')
- .addColumn('created_by', 'varchar(30)', (col) => col.notNull())
- .addColumn('updated_by', 'varchar(30)')
- .addColumn('transaction_id', 'varchar(30)', (col) => col.notNull())
- .execute();
- },
- down: async (db) => {
- await db.schema.dropTable('entries').execute();
- },
-};
-
-const createEntryTransactionsTable: Migration = {
- up: async (db) => {
- await sql`
- CREATE SEQUENCE IF NOT EXISTS entry_transactions_version_sequence
- START WITH 1000000000
- INCREMENT BY 1
- NO MINVALUE
- NO MAXVALUE
- CACHE 1;
- `.execute(db);
-
- await db.schema
- .createTable('entry_transactions')
- .addColumn('id', 'varchar(30)', (col) => col.notNull().primaryKey())
- .addColumn('entry_id', 'varchar(30)', (col) => col.notNull())
- .addColumn('root_id', 'varchar(30)', (col) => col.notNull())
- .addColumn('workspace_id', 'varchar(30)', (col) => col.notNull())
- .addColumn('operation', 'integer', (col) => col.notNull())
- .addColumn('data', 'bytea')
- .addColumn('created_at', 'timestamptz', (col) => col.notNull())
- .addColumn('created_by', 'varchar(30)', (col) => col.notNull())
- .addColumn('server_created_at', 'timestamptz', (col) => col.notNull())
- .addColumn('version', 'bigint', (col) =>
- col
- .notNull()
- .defaultTo(sql`nextval('entry_transactions_version_sequence')`)
- )
- .execute();
-
- await db.schema
- .createIndex('entry_transactions_entry_id_idx')
- .on('entry_transactions')
- .column('entry_id')
- .execute();
-
- await db.schema
- .createIndex('entry_transactions_root_id_version_idx')
- .on('entry_transactions')
- .columns(['root_id', 'version'])
- .execute();
-
- await sql`
- CREATE OR REPLACE FUNCTION update_entry_transaction_version() RETURNS TRIGGER AS $$
- BEGIN
- NEW.version = nextval('entry_transactions_version_sequence');
- RETURN NEW;
- END;
- $$ LANGUAGE plpgsql;
-
- CREATE TRIGGER trg_update_entry_transaction_version
- BEFORE UPDATE ON entry_transactions
- FOR EACH ROW
- EXECUTE FUNCTION update_entry_transaction_version();
- `.execute(db);
- },
- down: async (db) => {
- await sql`
- DROP TRIGGER IF EXISTS trg_update_entry_transaction_version ON entry_transactions;
- DROP FUNCTION IF EXISTS update_entry_transaction_version();
- `.execute(db);
-
- await db.schema.dropIndex('entry_transactions_entry_id_idx').execute();
- await db.schema
- .dropIndex('entry_transactions_root_id_version_idx')
- .execute();
-
- await db.schema.dropTable('entry_transactions').execute();
- await sql`DROP SEQUENCE IF EXISTS entry_transactions_version_sequence`.execute(
- db
- );
- },
-};
-
-const createCollaborationsTable: Migration = {
- up: async (db) => {
- await sql`
- CREATE SEQUENCE IF NOT EXISTS collaborations_version_sequence
- START WITH 1000000000
- INCREMENT BY 1
- NO MINVALUE
- NO MAXVALUE
- CACHE 1;
- `.execute(db);
-
- await db.schema
- .createTable('collaborations')
- .addColumn('entry_id', 'varchar(30)', (col) => col.notNull())
- .addColumn('collaborator_id', 'varchar(30)', (col) => col.notNull())
- .addColumn('workspace_id', 'varchar(30)', (col) => col.notNull())
- .addColumn('role', 'varchar(30)', (col) => col.notNull())
- .addColumn('created_at', 'timestamptz', (col) => col.notNull())
- .addColumn('created_by', 'varchar(30)', (col) => col.notNull())
- .addColumn('updated_at', 'timestamptz')
- .addColumn('updated_by', 'varchar(30)')
- .addColumn('deleted_at', 'timestamptz')
- .addColumn('deleted_by', 'varchar(30)')
- .addColumn('version', 'bigint', (col) =>
- col.notNull().defaultTo(sql`nextval('collaborations_version_sequence')`)
- )
- .addPrimaryKeyConstraint('collaborations_pkey', [
- 'entry_id',
- 'collaborator_id',
- ])
- .execute();
-
- await db.schema
- .createIndex('collaborations_collaborator_version_idx')
- .on('collaborations')
- .columns(['collaborator_id', 'version'])
- .execute();
-
- await sql`
- CREATE OR REPLACE FUNCTION update_collaboration_version() RETURNS TRIGGER AS $$
- BEGIN
- NEW.version = nextval('collaborations_version_sequence');
- RETURN NEW;
- END;
- $$ LANGUAGE plpgsql;
-
- CREATE TRIGGER trg_update_collaboration_version
- BEFORE UPDATE ON collaborations
- FOR EACH ROW
- EXECUTE FUNCTION update_collaboration_version();
- `.execute(db);
- },
- down: async (db) => {
- await sql`
- DROP TRIGGER IF EXISTS trg_update_collaboration_version ON collaborations;
- DROP FUNCTION IF EXISTS update_collaboration_version();
- `.execute(db);
-
- await db.schema
- .dropIndex('collaborations_collaborator_version_idx')
- .execute();
-
- await db.schema.dropTable('collaborations').execute();
- await sql`DROP SEQUENCE IF EXISTS collaborations_version_sequence`.execute(
- db
- );
- },
-};
-
-const createEntryInteractionsTable: Migration = {
- up: async (db) => {
- await sql`
- CREATE SEQUENCE IF NOT EXISTS entry_interactions_version_sequence
- START WITH 1000000000
- INCREMENT BY 1
- NO MINVALUE
- NO MAXVALUE
- CACHE 1;
- `.execute(db);
-
- await db.schema
- .createTable('entry_interactions')
- .addColumn('entry_id', 'varchar(30)', (col) => col.notNull())
- .addColumn('collaborator_id', 'varchar(30)', (col) => col.notNull())
- .addColumn('root_id', 'varchar(30)', (col) => col.notNull())
- .addColumn('workspace_id', 'varchar(30)', (col) => col.notNull())
- .addColumn('first_seen_at', 'timestamptz')
- .addColumn('last_seen_at', 'timestamptz')
- .addColumn('first_opened_at', 'timestamptz')
- .addColumn('last_opened_at', 'timestamptz')
- .addColumn('version', 'bigint', (col) =>
- col
- .notNull()
- .defaultTo(sql`nextval('entry_interactions_version_sequence')`)
- )
- .addPrimaryKeyConstraint('entry_interactions_pkey', [
- 'entry_id',
- 'collaborator_id',
- ])
- .execute();
-
- await sql`
- CREATE OR REPLACE FUNCTION update_entry_interaction_version() RETURNS TRIGGER AS $$
- BEGIN
- NEW.version = nextval('entry_interactions_version_sequence');
- RETURN NEW;
- END;
- $$ LANGUAGE plpgsql;
-
- CREATE TRIGGER trg_update_entry_interaction_version
- BEFORE UPDATE ON entry_interactions
- FOR EACH ROW
- EXECUTE FUNCTION update_entry_interaction_version();
- `.execute(db);
-
- await db.schema
- .createIndex('entry_interactions_root_id_version_idx')
- .on('entry_interactions')
- .columns(['root_id', 'version'])
- .execute();
- },
- down: async (db) => {
- await sql`
- DROP TRIGGER IF EXISTS trg_update_entry_interaction_version ON entry_interactions;
- DROP FUNCTION IF EXISTS update_entry_interaction_version();
- `.execute(db);
-
- await db.schema
- .dropIndex('entry_interactions_root_id_version_idx')
- .execute();
-
- await db.schema.dropTable('entry_interactions').execute();
- await sql`DROP SEQUENCE IF EXISTS entry_interactions_version_sequence`.execute(
- db
- );
- },
-};
-
-const createMessagesTable: Migration = {
- up: async (db) => {
- await sql`
- CREATE SEQUENCE IF NOT EXISTS messages_version_sequence
- START WITH 1000000000
- INCREMENT BY 1
- NO MINVALUE
- NO MAXVALUE
- CACHE 1;
- `.execute(db);
-
- await db.schema
- .createTable('messages')
- .addColumn('id', 'varchar(30)', (col) => col.notNull().primaryKey())
- .addColumn('type', 'integer', (col) =>
- col.generatedAlwaysAs(sql`(attributes->>'type')::INTEGER`).stored()
- )
- .addColumn('parent_id', 'varchar(30)', (col) => col.notNull())
- .addColumn('entry_id', 'varchar(30)', (col) => col.notNull())
- .addColumn('root_id', 'varchar(30)', (col) => col.notNull())
- .addColumn('workspace_id', 'varchar(30)', (col) => col.notNull())
- .addColumn('attributes', 'jsonb', (col) => col.notNull())
- .addColumn('created_at', 'timestamptz', (col) => col.notNull())
- .addColumn('created_by', 'varchar(30)', (col) => col.notNull())
- .addColumn('updated_at', 'timestamptz')
- .addColumn('updated_by', 'varchar(30)')
- .addColumn('version', 'bigint', (col) =>
- col.notNull().defaultTo(sql`nextval('messages_version_sequence')`)
- )
- .execute();
-
- await db.schema
- .createIndex('messages_root_id_version_idx')
- .on('messages')
- .columns(['root_id', 'version'])
- .execute();
-
- await sql`
- CREATE OR REPLACE FUNCTION update_message_version() RETURNS TRIGGER AS $$
- BEGIN
- NEW.version = nextval('messages_version_sequence');
- RETURN NEW;
- END;
- $$ LANGUAGE plpgsql;
-
- CREATE TRIGGER trg_update_message_version
- BEFORE UPDATE ON messages
- FOR EACH ROW
- EXECUTE FUNCTION update_message_version();
- `.execute(db);
- },
- down: async (db) => {
- await sql`
- DROP TRIGGER IF EXISTS trg_update_message_version ON messages;
- DROP FUNCTION IF EXISTS update_message_version();
- `.execute(db);
-
- await db.schema.dropIndex('messages_root_id_version_idx').execute();
- await db.schema.dropTable('messages').execute();
- await sql`DROP SEQUENCE IF EXISTS messages_version_sequence`.execute(db);
- },
-};
-
-const createMessageReactionsTable: Migration = {
- up: async (db) => {
- await sql`
- CREATE SEQUENCE IF NOT EXISTS message_reactions_version_sequence
- START WITH 1000000000
- INCREMENT BY 1
- NO MINVALUE
- NO MAXVALUE
- CACHE 1;
- `.execute(db);
-
- await db.schema
- .createTable('message_reactions')
- .addColumn('message_id', 'varchar(30)', (col) => col.notNull())
- .addColumn('collaborator_id', 'varchar(30)', (col) => col.notNull())
- .addColumn('reaction', 'varchar(30)', (col) => col.notNull())
- .addColumn('root_id', 'varchar(30)', (col) => col.notNull())
- .addColumn('workspace_id', 'varchar(30)', (col) => col.notNull())
- .addColumn('created_at', 'timestamptz', (col) => col.notNull())
- .addColumn('deleted_at', 'timestamptz')
- .addColumn('version', 'bigint', (col) =>
- col
- .notNull()
- .defaultTo(sql`nextval('message_reactions_version_sequence')`)
- )
- .addPrimaryKeyConstraint('message_reactions_pkey', [
- 'message_id',
- 'collaborator_id',
- 'reaction',
- ])
- .execute();
-
- await db.schema
- .createIndex('message_reactions_root_id_version_idx')
- .on('message_reactions')
- .columns(['root_id', 'version'])
- .execute();
-
- await sql`
- CREATE OR REPLACE FUNCTION update_message_reaction_version() RETURNS TRIGGER AS $$
- BEGIN
- NEW.version = nextval('message_reactions_version_sequence');
- RETURN NEW;
- END;
- $$ LANGUAGE plpgsql;
-
- CREATE TRIGGER trg_update_message_reaction_version
- BEFORE UPDATE ON message_reactions
- FOR EACH ROW
- EXECUTE FUNCTION update_message_reaction_version();
- `.execute(db);
- },
- down: async (db) => {
- await sql`
- DROP TRIGGER IF EXISTS trg_update_message_reaction_version ON message_reactions;
- DROP FUNCTION IF EXISTS update_message_reaction_version();
- `.execute(db);
-
- await db.schema
- .dropIndex('message_reactions_root_id_version_idx')
- .execute();
-
- await db.schema.dropTable('message_reactions').execute();
- await sql`DROP SEQUENCE IF EXISTS message_reactions_version_sequence`.execute(
- db
- );
- },
-};
-
-const createMessageInteractionsTable: Migration = {
- up: async (db) => {
- await sql`
- CREATE SEQUENCE IF NOT EXISTS message_interactions_version_sequence
- START WITH 1000000000
- INCREMENT BY 1
- NO MINVALUE
- NO MAXVALUE
- CACHE 1;
- `.execute(db);
-
- await db.schema
- .createTable('message_interactions')
- .addColumn('message_id', 'varchar(30)', (col) => col.notNull())
- .addColumn('collaborator_id', 'varchar(30)', (col) => col.notNull())
- .addColumn('root_id', 'varchar(30)', (col) => col.notNull())
- .addColumn('workspace_id', 'varchar(30)', (col) => col.notNull())
- .addColumn('first_seen_at', 'timestamptz')
- .addColumn('last_seen_at', 'timestamptz')
- .addColumn('first_opened_at', 'timestamptz')
- .addColumn('last_opened_at', 'timestamptz')
- .addColumn('version', 'bigint', (col) =>
- col
- .notNull()
- .defaultTo(sql`nextval('message_interactions_version_sequence')`)
- )
- .addPrimaryKeyConstraint('message_interactions_pkey', [
- 'message_id',
- 'collaborator_id',
- ])
- .execute();
-
- await db.schema
- .createIndex('message_interactions_root_id_version_idx')
- .on('message_interactions')
- .columns(['root_id', 'version'])
- .execute();
-
- await sql`
- CREATE OR REPLACE FUNCTION update_message_interaction_version() RETURNS TRIGGER AS $$
- BEGIN
- NEW.version = nextval('message_interactions_version_sequence');
- RETURN NEW;
- END;
- $$ LANGUAGE plpgsql;
-
- CREATE TRIGGER trg_update_message_interaction_version
- BEFORE UPDATE ON message_interactions
- FOR EACH ROW
- EXECUTE FUNCTION update_message_interaction_version();
- `.execute(db);
- },
- down: async (db) => {
- await sql`
- DROP TRIGGER IF EXISTS trg_update_message_interaction_version ON message_interactions;
- DROP FUNCTION IF EXISTS update_message_interaction_version();
- `.execute(db);
-
- await db.schema
- .dropIndex('message_interactions_root_id_version_idx')
- .execute();
-
- await db.schema.dropTable('message_interactions').execute();
- await sql`DROP SEQUENCE IF EXISTS message_interactions_version_sequence`.execute(
- db
- );
- },
-};
-
-const createMessageTombstonesTable: Migration = {
- up: async (db) => {
- await sql`
- CREATE SEQUENCE IF NOT EXISTS message_tombstones_version_sequence
- START WITH 1000000000
- INCREMENT BY 1
- NO MINVALUE
- NO MAXVALUE
- CACHE 1;
- `.execute(db);
-
- await db.schema
- .createTable('message_tombstones')
- .addColumn('id', 'varchar(30)', (col) => col.notNull().primaryKey())
- .addColumn('root_id', 'varchar(30)', (col) => col.notNull())
- .addColumn('workspace_id', 'varchar(30)', (col) => col.notNull())
- .addColumn('deleted_at', 'timestamptz', (col) => col.notNull())
- .addColumn('deleted_by', 'varchar(30)', (col) => col.notNull())
- .addColumn('version', 'bigint', (col) =>
- col
- .notNull()
- .defaultTo(sql`nextval('message_tombstones_version_sequence')`)
- )
- .execute();
-
- await db.schema
- .createIndex('message_tombstones_root_id_version_idx')
- .on('message_tombstones')
- .columns(['root_id', 'version'])
- .execute();
- },
- down: async (db) => {
- await db.schema
- .dropIndex('message_tombstones_root_id_version_idx')
- .execute();
-
- await db.schema.dropTable('message_tombstones').execute();
- await sql`DROP SEQUENCE IF EXISTS message_tombstones_version_sequence`.execute(
- db
- );
- },
-};
-
-const createFilesTable: Migration = {
- up: async (db) => {
- await sql`
- CREATE SEQUENCE IF NOT EXISTS files_version_sequence
- START WITH 1000000000
- INCREMENT BY 1
- NO MINVALUE
- NO MAXVALUE
- CACHE 1;
- `.execute(db);
-
- await db.schema
- .createTable('files')
- .addColumn('id', 'varchar(30)', (col) => col.notNull().primaryKey())
- .addColumn('type', 'varchar(30)', (col) => col.notNull())
- .addColumn('parent_id', 'varchar(30)', (col) => col.notNull())
- .addColumn('entry_id', 'varchar(30)', (col) => col.notNull())
- .addColumn('root_id', 'varchar(30)', (col) => col.notNull())
- .addColumn('workspace_id', 'varchar(30)', (col) => col.notNull())
- .addColumn('name', 'varchar(256)', (col) => col.notNull())
- .addColumn('original_name', 'varchar(256)', (col) => col.notNull())
- .addColumn('mime_type', 'varchar(256)', (col) => col.notNull())
- .addColumn('extension', 'varchar(256)', (col) => col.notNull())
- .addColumn('size', 'integer', (col) => col.notNull())
- .addColumn('created_at', 'timestamptz', (col) => col.notNull())
- .addColumn('created_by', 'varchar(30)', (col) => col.notNull())
- .addColumn('updated_at', 'timestamptz')
- .addColumn('updated_by', 'varchar(30)')
- .addColumn('status', 'integer', (col) => col.notNull())
- .addColumn('version', 'bigint', (col) =>
- col.notNull().defaultTo(sql`nextval('files_version_sequence')`)
- )
- .execute();
-
- await db.schema
- .createIndex('files_root_id_version_idx')
- .on('files')
- .columns(['root_id', 'version'])
- .execute();
-
- await sql`
- CREATE OR REPLACE FUNCTION update_file_version() RETURNS TRIGGER AS $$
- BEGIN
- NEW.version = nextval('files_version_sequence');
- RETURN NEW;
- END;
- $$ LANGUAGE plpgsql;
-
- CREATE TRIGGER trg_update_file_version
- BEFORE UPDATE ON files
- FOR EACH ROW
- EXECUTE FUNCTION update_file_version();
- `.execute(db);
- },
- down: async (db) => {
- await sql`
- DROP TRIGGER IF EXISTS trg_update_file_version ON files;
- DROP FUNCTION IF EXISTS update_file_version();
- `.execute(db);
-
- await db.schema.dropIndex('files_root_id_version_idx').execute();
- await db.schema.dropTable('files').execute();
- await sql`DROP SEQUENCE IF EXISTS files_version_sequence`.execute(db);
- },
-};
-
-const createFileInteractionsTable: Migration = {
- up: async (db) => {
- await sql`
- CREATE SEQUENCE IF NOT EXISTS file_interactions_version_sequence
- START WITH 1000000000
- INCREMENT BY 1
- NO MINVALUE
- NO MAXVALUE
- CACHE 1;
- `.execute(db);
-
- await db.schema
- .createTable('file_interactions')
- .addColumn('file_id', 'varchar(30)', (col) => col.notNull())
- .addColumn('collaborator_id', 'varchar(30)', (col) => col.notNull())
- .addColumn('root_id', 'varchar(30)', (col) => col.notNull())
- .addColumn('workspace_id', 'varchar(30)', (col) => col.notNull())
- .addColumn('first_seen_at', 'timestamptz')
- .addColumn('last_seen_at', 'timestamptz')
- .addColumn('first_opened_at', 'timestamptz')
- .addColumn('last_opened_at', 'timestamptz')
- .addColumn('version', 'bigint', (col) =>
- col
- .notNull()
- .defaultTo(sql`nextval('file_interactions_version_sequence')`)
- )
- .addPrimaryKeyConstraint('file_interactions_pkey', [
- 'file_id',
- 'collaborator_id',
- ])
- .execute();
-
- await db.schema
- .createIndex('file_interactions_root_id_version_idx')
- .on('file_interactions')
- .columns(['root_id', 'version'])
- .execute();
-
- await sql`
- CREATE OR REPLACE FUNCTION update_file_interaction_version() RETURNS TRIGGER AS $$
- BEGIN
- NEW.version = nextval('file_interactions_version_sequence');
- RETURN NEW;
- END;
- $$ LANGUAGE plpgsql;
-
- CREATE TRIGGER trg_update_file_interaction_version
- BEFORE UPDATE ON file_interactions
- FOR EACH ROW
- EXECUTE FUNCTION update_file_interaction_version();
- `.execute(db);
- },
- down: async (db) => {
- await sql`
- DROP TRIGGER IF EXISTS trg_update_file_interaction_version ON file_interactions;
- DROP FUNCTION IF EXISTS update_file_interaction_version();
- `.execute(db);
-
- await db.schema
- .dropIndex('file_interactions_root_id_version_idx')
- .execute();
-
- await db.schema.dropTable('file_interactions').execute();
- await sql`DROP SEQUENCE IF EXISTS file_interactions_version_sequence`.execute(
- db
- );
- },
-};
-
-const createFileTombstonesTable: Migration = {
- up: async (db) => {
- await sql`
- CREATE SEQUENCE IF NOT EXISTS file_tombstones_version_sequence
- START WITH 1000000000
- INCREMENT BY 1
- NO MINVALUE
- NO MAXVALUE
- CACHE 1;
- `.execute(db);
-
- await db.schema
- .createTable('file_tombstones')
- .addColumn('id', 'varchar(30)', (col) => col.notNull().primaryKey())
- .addColumn('root_id', 'varchar(30)', (col) => col.notNull())
- .addColumn('workspace_id', 'varchar(30)', (col) => col.notNull())
- .addColumn('deleted_at', 'timestamptz', (col) => col.notNull())
- .addColumn('deleted_by', 'varchar(30)', (col) => col.notNull())
- .addColumn('version', 'bigint', (col) =>
- col
- .notNull()
- .defaultTo(sql`nextval('file_tombstones_version_sequence')`)
- )
- .execute();
-
- await db.schema
- .createIndex('file_tombstones_root_id_version_idx')
- .on('file_tombstones')
- .columns(['root_id', 'version'])
- .execute();
- },
- down: async (db) => {
- await db.schema.dropIndex('file_tombstones_root_id_version_idx').execute();
- await db.schema.dropTable('file_tombstones').execute();
- await sql`DROP SEQUENCE IF EXISTS file_tombstones_version_sequence`.execute(
- db
- );
- },
-};
-
-const createEntryPathsTable: Migration = {
- up: async (db) => {
- await db.schema
- .createTable('entry_paths')
- .addColumn('ancestor_id', 'varchar(30)', (col) =>
- col.notNull().references('entries.id').onDelete('cascade')
- )
- .addColumn('descendant_id', 'varchar(30)', (col) =>
- col.notNull().references('entries.id').onDelete('cascade')
- )
- .addColumn('workspace_id', 'varchar(30)', (col) => col.notNull())
- .addColumn('level', 'integer', (col) => col.notNull())
- .addPrimaryKeyConstraint('entry_paths_pkey', [
- 'ancestor_id',
- 'descendant_id',
- ])
- .execute();
-
- await sql`
- CREATE OR REPLACE FUNCTION fn_insert_entry_path() RETURNS TRIGGER AS $$
- BEGIN
- -- Insert direct path from the new entry to itself
- INSERT INTO entry_paths (ancestor_id, descendant_id, workspace_id, level)
- VALUES (NEW.id, NEW.id, NEW.workspace_id, 0);
-
- -- Insert paths from ancestors to the new entry
- INSERT INTO entry_paths (ancestor_id, descendant_id, workspace_id, level)
- SELECT ancestor_id, NEW.id, NEW.workspace_id, level + 1
- FROM entry_paths
- WHERE descendant_id = NEW.parent_id AND ancestor_id <> NEW.id;
-
- RETURN NEW;
- END;
- $$ LANGUAGE plpgsql;
-
- CREATE TRIGGER trg_insert_entry_path
- AFTER INSERT ON entries
- FOR EACH ROW
- EXECUTE FUNCTION fn_insert_entry_path();
-
- CREATE OR REPLACE FUNCTION fn_update_entry_path() RETURNS TRIGGER AS $$
- BEGIN
- IF OLD.parent_id IS DISTINCT FROM NEW.parent_id THEN
- -- Delete old paths involving the updated entry
- DELETE FROM entry_paths
- WHERE descendant_id = NEW.id AND ancestor_id <> NEW.id;
-
- INSERT INTO entry_paths (ancestor_id, descendant_id, workspace_id, level)
- SELECT ancestor_id, NEW.id, NEW.workspace_id, level + 1
- FROM entry_paths
- WHERE descendant_id = NEW.parent_id AND ancestor_id <> NEW.id;
- END IF;
-
- RETURN NEW;
- END;
- $$ LANGUAGE plpgsql;
-
- CREATE TRIGGER trg_update_entry_path
- AFTER UPDATE ON entries
- EXECUTE FUNCTION fn_update_entry_path();
- `.execute(db);
- },
- down: async (db) => {
- await sql`
- DROP TRIGGER IF EXISTS trg_insert_entry_path ON entries;
- DROP TRIGGER IF EXISTS trg_update_entry_path ON entries;
- DROP FUNCTION IF EXISTS fn_insert_entry_path();
- DROP FUNCTION IF EXISTS fn_update_entry_path();
- `.execute(db);
-
- await db.schema.dropTable('entry_paths').execute();
- },
-};
-
-const createVectorExtension: Migration = {
- up: async (db) => {
- await sql`CREATE EXTENSION IF NOT EXISTS vector`.execute(db);
- },
- down: async (db) => {
- await sql`DROP EXTENSION IF EXISTS vector`.execute(db);
- },
-};
-
-const createMessageEmbeddingsTable: Migration = {
- up: async (db) => {
- await db.schema
- .createTable('message_embeddings')
- .addColumn('message_id', 'varchar(30)', (col) => col.notNull())
- .addColumn('chunk', 'integer', (col) => col.notNull())
- .addColumn('parent_id', 'varchar(30)', (col) => col.notNull())
- .addColumn('entry_id', 'varchar(30)', (col) => col.notNull())
- .addColumn('root_id', 'varchar(30)', (col) => col.notNull())
- .addColumn('workspace_id', 'varchar(30)', (col) => col.notNull())
- .addColumn('text', 'text', (col) => col.notNull())
- .addColumn('embedding_vector', sql`vector(2000)`, (col) => col.notNull())
- .addColumn(
- 'search_vector',
- sql`tsvector GENERATED ALWAYS AS (to_tsvector('english', text)) STORED`
- )
- .addColumn('created_at', 'timestamptz', (col) => col.notNull())
- .addColumn('updated_at', 'timestamptz')
- .execute();
-
- await sql`
- CREATE INDEX message_embeddings_embedding_vector_idx
- ON message_embeddings
- USING hnsw(embedding_vector vector_cosine_ops)
- WITH (
- m = 16,
- ef_construction = 64
- );
- `.execute(db);
-
- await sql`
- CREATE INDEX message_embeddings_search_vector_idx
- ON message_embeddings
- USING GIN (search_vector);
- `.execute(db);
- },
- down: async (db) => {
- await db.schema.dropTable('message_embeddings').execute();
- },
-};
-
-const createEntryEmbeddingsTable: Migration = {
- up: async (db) => {
- await db.schema
- .createTable('entry_embeddings')
- .addColumn('entry_id', 'varchar(30)', (col) => col.notNull())
- .addColumn('chunk', 'integer', (col) => col.notNull())
- .addColumn('parent_id', 'varchar(30)')
- .addColumn('root_id', 'varchar(30)', (col) => col.notNull())
- .addColumn('workspace_id', 'varchar(30)', (col) => col.notNull())
- .addColumn('text', 'text', (col) => col.notNull())
- .addColumn('embedding_vector', sql`vector(2000)`, (col) => col.notNull())
- .addColumn(
- 'search_vector',
- sql`tsvector GENERATED ALWAYS AS (to_tsvector('english', text)) STORED`
- )
- .addColumn('created_at', 'timestamptz', (col) => col.notNull())
- .addColumn('updated_at', 'timestamptz')
- .execute();
-
- await sql`
- CREATE INDEX entry_embeddings_embedding_vector_idx
- ON entry_embeddings
- USING hnsw(embedding_vector vector_cosine_ops)
- WITH (
- m = 16,
- ef_construction = 64
- );
- `.execute(db);
-
- await sql`
- CREATE INDEX entry_embeddings_search_vector_idx
- ON entry_embeddings
- USING GIN (search_vector);
- `.execute(db);
- },
- down: async (db) => {
- await db.schema.dropTable('entry_embeddings').execute();
- },
-};
-
-export const databaseMigrations: Record<string, Migration> = {
- '00001_create_accounts_table': createAccountsTable,
- '00002_create_devices_table': createDevicesTable,
- '00003_create_workspaces_table': createWorkspacesTable,
- '00004_create_users_table': createUsersTable,
- '00005_create_entries_table': createEntriesTable,
- '00006_create_entry_transactions_table': createEntryTransactionsTable,
- '00007_create_entry_interactions_table': createEntryInteractionsTable,
- '00008_create_entry_paths_table': createEntryPathsTable,
- '00009_create_messages_table': createMessagesTable,
- '00010_create_message_reactions_table': createMessageReactionsTable,
- '00011_create_message_interactions_table': createMessageInteractionsTable,
- '00012_create_message_tombstones_table': createMessageTombstonesTable,
- '00013_create_files_table': createFilesTable,
- '00014_create_file_interactions_table': createFileInteractionsTable,
- '00015_create_file_tombstones_table': createFileTombstonesTable,
- '00016_create_collaborations_table': createCollaborationsTable,
- '00017_create_vector_extension': createVectorExtension,
- '00018_create_entry_embeddings_table': createEntryEmbeddingsTable,
- '00019_create_message_embeddings_table': createMessageEmbeddingsTable,
-};
diff --git a/apps/server/src/data/migrations/00001-create-accounts-table.ts b/apps/server/src/data/migrations/00001-create-accounts-table.ts
new file mode 100644
index 00000000..87d0226d
--- /dev/null
+++ b/apps/server/src/data/migrations/00001-create-accounts-table.ts
@@ -0,0 +1,21 @@
+import { Migration } from 'kysely';
+
+export const createAccountsTable: Migration = {
+ up: async (db) => {
+ await db.schema
+ .createTable('accounts')
+ .addColumn('id', 'varchar(30)', (col) => col.notNull().primaryKey())
+ .addColumn('name', 'varchar(256)', (col) => col.notNull())
+ .addColumn('email', 'varchar(256)', (col) => col.notNull().unique())
+ .addColumn('avatar', 'varchar(256)')
+ .addColumn('password', 'varchar(256)')
+ .addColumn('attrs', 'jsonb')
+ .addColumn('created_at', 'timestamptz', (col) => col.notNull())
+ .addColumn('updated_at', 'timestamptz')
+ .addColumn('status', 'integer', (col) => col.notNull())
+ .execute();
+ },
+ down: async (db) => {
+ await db.schema.dropTable('accounts').execute();
+ },
+};
diff --git a/apps/server/src/data/migrations/00002-create-devices-table.ts b/apps/server/src/data/migrations/00002-create-devices-table.ts
new file mode 100644
index 00000000..7ba753b9
--- /dev/null
+++ b/apps/server/src/data/migrations/00002-create-devices-table.ts
@@ -0,0 +1,32 @@
+import { Migration } from 'kysely';
+
+export const createDevicesTable: Migration = {
+ up: async (db) => {
+ await db.schema
+ .createTable('devices')
+ .addColumn('id', 'varchar(30)', (col) => col.notNull().primaryKey())
+ .addColumn('account_id', 'varchar(30)', (col) => col.notNull())
+ .addColumn('token_hash', 'varchar(100)', (col) => col.notNull())
+ .addColumn('token_salt', 'varchar(100)', (col) => col.notNull())
+ .addColumn('token_generated_at', 'timestamptz', (col) => col.notNull())
+ .addColumn('previous_token_hash', 'varchar(100)')
+ .addColumn('previous_token_salt', 'varchar(100)')
+ .addColumn('type', 'integer', (col) => col.notNull())
+ .addColumn('version', 'varchar(30)', (col) => col.notNull())
+ .addColumn('platform', 'varchar(30)')
+ .addColumn('ip', 'varchar(45)')
+ .addColumn('created_at', 'timestamptz', (col) => col.notNull())
+ .addColumn('synced_at', 'timestamptz')
+ .execute();
+
+ await db.schema
+ .createIndex('devices_account_id_idx')
+ .on('devices')
+ .column('account_id')
+ .execute();
+ },
+ down: async (db) => {
+ await db.schema.dropIndex('devices_account_id_idx').execute();
+ await db.schema.dropTable('devices').execute();
+ },
+};
diff --git a/apps/server/src/data/migrations/00003-create-workspaces-table.ts b/apps/server/src/data/migrations/00003-create-workspaces-table.ts
new file mode 100644
index 00000000..eba6dfb4
--- /dev/null
+++ b/apps/server/src/data/migrations/00003-create-workspaces-table.ts
@@ -0,0 +1,22 @@
+import { Migration } from 'kysely';
+
+export const createWorkspacesTable: Migration = {
+ up: async (db) => {
+ await db.schema
+ .createTable('workspaces')
+ .addColumn('id', 'varchar(30)', (col) => col.notNull().primaryKey())
+ .addColumn('name', 'varchar(256)', (col) => col.notNull())
+ .addColumn('description', 'varchar(256)')
+ .addColumn('avatar', 'varchar(256)')
+ .addColumn('attrs', 'jsonb')
+ .addColumn('created_at', 'timestamptz', (col) => col.notNull())
+ .addColumn('created_by', 'varchar(30)', (col) => col.notNull())
+ .addColumn('updated_at', 'timestamptz')
+ .addColumn('updated_by', 'varchar(30)')
+ .addColumn('status', 'integer', (col) => col.notNull())
+ .execute();
+ },
+ down: async (db) => {
+ await db.schema.dropTable('workspaces').execute();
+ },
+};
diff --git a/apps/server/src/data/migrations/00004-create-users-table.ts b/apps/server/src/data/migrations/00004-create-users-table.ts
new file mode 100644
index 00000000..3fd52fa5
--- /dev/null
+++ b/apps/server/src/data/migrations/00004-create-users-table.ts
@@ -0,0 +1,71 @@
+import { Migration, sql } from 'kysely';
+
+export const createUsersTable: Migration = {
+ up: async (db) => {
+ await sql`
+ CREATE SEQUENCE IF NOT EXISTS users_revision_sequence
+ START WITH 1000000000
+ INCREMENT BY 1
+ NO MINVALUE
+ NO MAXVALUE
+ CACHE 1;
+ `.execute(db);
+
+ await db.schema
+ .createTable('users')
+ .addColumn('id', 'varchar(30)', (col) => col.notNull().primaryKey())
+ .addColumn('workspace_id', 'varchar(30)', (col) => col.notNull())
+ .addColumn('account_id', 'varchar(30)', (col) => col.notNull())
+ .addColumn('revision', 'bigint', (col) =>
+ col.notNull().defaultTo(sql`nextval('users_revision_sequence')`)
+ )
+ .addColumn('email', 'varchar(256)', (col) => col.notNull())
+ .addColumn('name', 'varchar(256)', (col) => col.notNull())
+ .addColumn('avatar', 'varchar(256)')
+ .addColumn('custom_name', 'varchar(256)')
+ .addColumn('custom_avatar', 'varchar(256)')
+ .addColumn('role', 'varchar(30)', (col) => col.notNull())
+ .addColumn('storage_limit', 'bigint', (col) => col.notNull())
+ .addColumn('max_file_size', 'bigint', (col) => col.notNull())
+ .addColumn('created_at', 'timestamptz', (col) => col.notNull())
+ .addColumn('created_by', 'varchar(30)', (col) => col.notNull())
+ .addColumn('updated_at', 'timestamptz')
+ .addColumn('updated_by', 'varchar(30)')
+ .addColumn('status', 'integer', (col) => col.notNull())
+ .addUniqueConstraint('unique_workspace_account_combination', [
+ 'workspace_id',
+ 'account_id',
+ ])
+ .execute();
+
+ await db.schema
+ .createIndex('users_workspace_id_revision_idx')
+ .on('users')
+ .columns(['workspace_id', 'revision'])
+ .execute();
+
+ await sql`
+ CREATE OR REPLACE FUNCTION update_user_revision() RETURNS TRIGGER AS $$
+ BEGIN
+ NEW.revision = nextval('users_revision_sequence');
+ RETURN NEW;
+ END;
+ $$ LANGUAGE plpgsql;
+
+ CREATE TRIGGER trg_update_user_revision
+ BEFORE UPDATE ON users
+ FOR EACH ROW
+ EXECUTE FUNCTION update_user_revision();
+ `.execute(db);
+ },
+ down: async (db) => {
+ await sql`
+ DROP TRIGGER IF EXISTS trg_update_user_revision ON users;
+ DROP FUNCTION IF EXISTS update_user_revision();
+ `.execute(db);
+
+ await db.schema.dropIndex('users_workspace_id_revision_idx').execute();
+ await db.schema.dropTable('users').execute();
+ await sql`DROP SEQUENCE IF EXISTS users_revision_sequence`.execute(db);
+ },
+};
diff --git a/apps/server/src/data/migrations/00005-create-nodes-table.ts b/apps/server/src/data/migrations/00005-create-nodes-table.ts
new file mode 100644
index 00000000..d34ffa15
--- /dev/null
+++ b/apps/server/src/data/migrations/00005-create-nodes-table.ts
@@ -0,0 +1,66 @@
+import { Migration, sql } from 'kysely';
+
+export const createNodesTable: Migration = {
+ up: async (db) => {
+ await sql`
+ CREATE SEQUENCE IF NOT EXISTS nodes_revision_sequence
+ START WITH 1000000000
+ INCREMENT BY 1
+ NO MINVALUE
+ NO MAXVALUE
+ CACHE 1;
+ `.execute(db);
+
+ await db.schema
+ .createTable('nodes')
+ .addColumn('id', 'varchar(30)', (col) => col.notNull().primaryKey())
+ .addColumn('type', 'varchar(30)', (col) =>
+ col.generatedAlwaysAs(sql`(attributes->>'type')::VARCHAR(30)`).stored()
+ )
+ .addColumn('parent_id', 'varchar(30)', (col) =>
+ col
+ .generatedAlwaysAs(sql`(attributes->>'parentId')::VARCHAR(30)`)
+ .stored()
+ )
+ .addColumn('root_id', 'varchar(30)', (col) => col.notNull())
+ .addColumn('workspace_id', 'varchar(30)', (col) => col.notNull())
+ .addColumn('revision', 'bigint', (col) =>
+ col.notNull().defaultTo(sql`nextval('nodes_revision_sequence')`)
+ )
+ .addColumn('attributes', 'jsonb', (col) => col.notNull())
+ .addColumn('state', 'bytea', (col) => col.notNull())
+ .addColumn('created_at', 'timestamptz', (col) => col.notNull())
+ .addColumn('created_by', 'varchar(30)', (col) => col.notNull())
+ .addColumn('updated_at', 'timestamptz')
+ .addColumn('updated_by', 'varchar(30)')
+ .execute();
+
+ await db.schema
+ .createIndex('nodes_root_id_revision_idx')
+ .on('nodes')
+ .columns(['root_id', 'revision'])
+ .execute();
+
+ await sql`
+ CREATE OR REPLACE FUNCTION update_node_revision() RETURNS TRIGGER AS $$
+ BEGIN
+ NEW.revision = nextval('nodes_revision_sequence');
+ RETURN NEW;
+ END;
+ $$ LANGUAGE plpgsql;
+
+ CREATE TRIGGER trg_update_node_revision
+ BEFORE UPDATE ON nodes
+ FOR EACH ROW
+ EXECUTE FUNCTION update_node_revision();
+ `.execute(db);
+ },
+ down: async (db) => {
+ await sql`
+ DROP TRIGGER IF EXISTS trg_update_node_revision ON nodes;
+ DROP FUNCTION IF EXISTS update_node_revision();
+ `.execute(db);
+
+ await db.schema.dropTable('nodes').execute();
+ },
+};
diff --git a/apps/server/src/data/migrations/00006-create-node-reactions-table.ts b/apps/server/src/data/migrations/00006-create-node-reactions-table.ts
new file mode 100644
index 00000000..7dbf92f1
--- /dev/null
+++ b/apps/server/src/data/migrations/00006-create-node-reactions-table.ts
@@ -0,0 +1,66 @@
+import { sql, Migration } from 'kysely';
+
+export const createNodeReactionsTable: Migration = {
+ up: async (db) => {
+ await sql`
+ CREATE SEQUENCE IF NOT EXISTS node_reactions_revision_sequence
+ START WITH 1000000000
+ INCREMENT BY 1
+ NO MINVALUE
+ NO MAXVALUE
+ CACHE 1;
+ `.execute(db);
+
+ await db.schema
+ .createTable('node_reactions')
+ .addColumn('node_id', 'varchar(30)', (col) => col.notNull())
+ .addColumn('collaborator_id', 'varchar(30)', (col) => col.notNull())
+ .addColumn('reaction', 'varchar(30)', (col) => col.notNull())
+ .addColumn('root_id', 'varchar(30)', (col) => col.notNull())
+ .addColumn('workspace_id', 'varchar(30)', (col) => col.notNull())
+ .addColumn('revision', 'bigint', (col) =>
+ col
+ .notNull()
+ .defaultTo(sql`nextval('node_reactions_revision_sequence')`)
+ )
+ .addColumn('created_at', 'timestamptz', (col) => col.notNull())
+ .addColumn('deleted_at', 'timestamptz')
+ .addPrimaryKeyConstraint('node_reactions_pkey', [
+ 'node_id',
+ 'collaborator_id',
+ 'reaction',
+ ])
+ .execute();
+
+ await db.schema
+ .createIndex('node_reactions_root_id_revision_idx')
+ .on('node_reactions')
+ .columns(['root_id', 'revision'])
+ .execute();
+
+ await sql`
+ CREATE OR REPLACE FUNCTION update_node_reaction_revision() RETURNS TRIGGER AS $$
+ BEGIN
+ NEW.revision = nextval('node_reactions_revision_sequence');
+ RETURN NEW;
+ END;
+ $$ LANGUAGE plpgsql;
+
+ CREATE TRIGGER trg_update_node_reaction_revision
+ BEFORE UPDATE ON node_reactions
+ FOR EACH ROW
+ EXECUTE FUNCTION update_node_reaction_revision();
+ `.execute(db);
+ },
+ down: async (db) => {
+ await sql`
+ DROP TRIGGER IF EXISTS trg_update_node_reaction_revision ON node_reactions;
+ DROP FUNCTION IF EXISTS update_node_reaction_revision();
+ `.execute(db);
+
+ await db.schema.dropTable('node_reactions').execute();
+ await sql`DROP SEQUENCE IF EXISTS node_reactions_revision_sequence`.execute(
+ db
+ );
+ },
+};
diff --git a/apps/server/src/data/migrations/00007-create-node-interactions-table.ts b/apps/server/src/data/migrations/00007-create-node-interactions-table.ts
new file mode 100644
index 00000000..723b0660
--- /dev/null
+++ b/apps/server/src/data/migrations/00007-create-node-interactions-table.ts
@@ -0,0 +1,66 @@
+import { sql, Migration } from 'kysely';
+
+export const createNodeInteractionsTable: Migration = {
+ up: async (db) => {
+ await sql`
+ CREATE SEQUENCE IF NOT EXISTS node_interactions_revision_sequence
+ START WITH 1000000000
+ INCREMENT BY 1
+ NO MINVALUE
+ NO MAXVALUE
+ CACHE 1;
+ `.execute(db);
+
+ await db.schema
+ .createTable('node_interactions')
+ .addColumn('node_id', 'varchar(30)', (col) => col.notNull())
+ .addColumn('collaborator_id', 'varchar(30)', (col) => col.notNull())
+ .addColumn('root_id', 'varchar(30)', (col) => col.notNull())
+ .addColumn('workspace_id', 'varchar(30)', (col) => col.notNull())
+ .addColumn('revision', 'bigint', (col) =>
+ col
+ .notNull()
+ .defaultTo(sql`nextval('node_interactions_revision_sequence')`)
+ )
+ .addColumn('first_seen_at', 'timestamptz')
+ .addColumn('last_seen_at', 'timestamptz')
+ .addColumn('first_opened_at', 'timestamptz')
+ .addColumn('last_opened_at', 'timestamptz')
+ .addPrimaryKeyConstraint('node_interactions_pkey', [
+ 'node_id',
+ 'collaborator_id',
+ ])
+ .execute();
+
+ await sql`
+ CREATE OR REPLACE FUNCTION update_node_interaction_revision() RETURNS TRIGGER AS $$
+ BEGIN
+ NEW.revision = nextval('node_interactions_revision_sequence');
+ RETURN NEW;
+ END;
+ $$ LANGUAGE plpgsql;
+
+ CREATE TRIGGER trg_update_node_interaction_revision
+ BEFORE UPDATE ON node_interactions
+ FOR EACH ROW
+ EXECUTE FUNCTION update_node_interaction_revision();
+ `.execute(db);
+
+ await db.schema
+ .createIndex('node_interactions_root_id_revision_idx')
+ .on('node_interactions')
+ .columns(['root_id', 'revision'])
+ .execute();
+ },
+ down: async (db) => {
+ await sql`
+ DROP TRIGGER IF EXISTS trg_update_node_interaction_revision ON node_interactions;
+ DROP FUNCTION IF EXISTS update_node_interaction_revision();
+ `.execute(db);
+
+ await db.schema.dropTable('node_interactions').execute();
+ await sql`DROP SEQUENCE IF EXISTS node_interactions_revision_sequence`.execute(
+ db
+ );
+ },
+};
diff --git a/apps/server/src/data/migrations/00009-create-node-tombstones-table.ts b/apps/server/src/data/migrations/00009-create-node-tombstones-table.ts
new file mode 100644
index 00000000..41487ae0
--- /dev/null
+++ b/apps/server/src/data/migrations/00009-create-node-tombstones-table.ts
@@ -0,0 +1,42 @@
+import { sql, Migration } from 'kysely';
+
+export const createNodeTombstonesTable: Migration = {
+ up: async (db) => {
+ await sql`
+ CREATE SEQUENCE IF NOT EXISTS node_tombstones_revision_sequence
+ START WITH 1000000000
+ INCREMENT BY 1
+ NO MINVALUE
+ NO MAXVALUE
+ CACHE 1;
+ `.execute(db);
+
+ await db.schema
+ .createTable('node_tombstones')
+ .addColumn('id', 'varchar(30)', (col) => col.notNull().primaryKey())
+ .addColumn('root_id', 'varchar(30)', (col) => col.notNull())
+ .addColumn('workspace_id', 'varchar(30)', (col) => col.notNull())
+ .addColumn('revision', 'bigint', (col) =>
+ col
+ .notNull()
+ .defaultTo(sql`nextval('node_tombstones_revision_sequence')`)
+ )
+ .addColumn('deleted_at', 'timestamptz', (col) => col.notNull())
+ .addColumn('deleted_by', 'varchar(30)', (col) => col.notNull())
+ .execute();
+
+ await db.schema
+ .createIndex('node_tombstones_root_id_revision_idx')
+ .on('node_tombstones')
+ .columns(['root_id', 'revision'])
+ .execute();
+ },
+ down: async (db) => {
+ await db.schema.dropIndex('node_tombstones_root_id_revision_idx').execute();
+
+ await db.schema.dropTable('node_tombstones').execute();
+ await sql`DROP SEQUENCE IF EXISTS node_tombstones_revision_sequence`.execute(
+ db
+ );
+ },
+};
diff --git a/apps/server/src/data/migrations/00010-create-node-paths-table.ts b/apps/server/src/data/migrations/00010-create-node-paths-table.ts
new file mode 100644
index 00000000..9235cb4d
--- /dev/null
+++ b/apps/server/src/data/migrations/00010-create-node-paths-table.ts
@@ -0,0 +1,75 @@
+import { Migration, sql } from 'kysely';
+
+export const createNodePathsTable: Migration = {
+ up: async (db) => {
+ await db.schema
+ .createTable('node_paths')
+ .addColumn('ancestor_id', 'varchar(30)', (col) =>
+ col.notNull().references('nodes.id').onDelete('cascade')
+ )
+ .addColumn('descendant_id', 'varchar(30)', (col) =>
+ col.notNull().references('nodes.id').onDelete('cascade')
+ )
+ .addColumn('workspace_id', 'varchar(30)', (col) => col.notNull())
+ .addColumn('level', 'integer', (col) => col.notNull())
+ .addPrimaryKeyConstraint('node_paths_pkey', [
+ 'ancestor_id',
+ 'descendant_id',
+ ])
+ .execute();
+
+ await sql`
+ CREATE OR REPLACE FUNCTION fn_insert_node_path() RETURNS TRIGGER AS $$
+ BEGIN
+ -- Insert direct path from the new node to itself
+ INSERT INTO node_paths (ancestor_id, descendant_id, workspace_id, level)
+ VALUES (NEW.id, NEW.id, NEW.workspace_id, 0);
+
+ -- Insert paths from ancestors to the new node
+ INSERT INTO node_paths (ancestor_id, descendant_id, workspace_id, level)
+ SELECT ancestor_id, NEW.id, NEW.workspace_id, level + 1
+ FROM node_paths
+ WHERE descendant_id = NEW.parent_id AND ancestor_id <> NEW.id;
+
+ RETURN NEW;
+ END;
+ $$ LANGUAGE plpgsql;
+
+ CREATE TRIGGER trg_insert_node_path
+ AFTER INSERT ON nodes
+ FOR EACH ROW
+ EXECUTE FUNCTION fn_insert_node_path();
+
+ CREATE OR REPLACE FUNCTION fn_update_node_path() RETURNS TRIGGER AS $$
+ BEGIN
+ IF OLD.parent_id IS DISTINCT FROM NEW.parent_id THEN
+ -- Delete old paths involving the updated node
+ DELETE FROM node_paths
+ WHERE descendant_id = NEW.id AND ancestor_id <> NEW.id;
+
+ INSERT INTO node_paths (ancestor_id, descendant_id, workspace_id, level)
+ SELECT ancestor_id, NEW.id, NEW.workspace_id, level + 1
+ FROM node_paths
+ WHERE descendant_id = NEW.parent_id AND ancestor_id <> NEW.id;
+ END IF;
+
+ RETURN NEW;
+ END;
+ $$ LANGUAGE plpgsql;
+
+ CREATE TRIGGER trg_update_node_path
+ AFTER UPDATE ON nodes
+ EXECUTE FUNCTION fn_update_node_path();
+ `.execute(db);
+ },
+ down: async (db) => {
+ await sql`
+ DROP TRIGGER IF EXISTS trg_insert_node_path ON nodes;
+ DROP TRIGGER IF EXISTS trg_update_node_path ON nodes;
+ DROP FUNCTION IF EXISTS fn_insert_node_path();
+ DROP FUNCTION IF EXISTS fn_update_node_path();
+ `.execute(db);
+
+ await db.schema.dropTable('node_paths').execute();
+ },
+};
diff --git a/apps/server/src/data/migrations/00011-create-collaborations-table.ts b/apps/server/src/data/migrations/00011-create-collaborations-table.ts
new file mode 100644
index 00000000..31adcd7f
--- /dev/null
+++ b/apps/server/src/data/migrations/00011-create-collaborations-table.ts
@@ -0,0 +1,68 @@
+import { sql, Migration } from 'kysely';
+
+export const createCollaborationsTable: Migration = {
+ up: async (db) => {
+ await sql`
+ CREATE SEQUENCE IF NOT EXISTS collaborations_revision_sequence
+ START WITH 1000000000
+ INCREMENT BY 1
+ NO MINVALUE
+ NO MAXVALUE
+ CACHE 1;
+ `.execute(db);
+
+ await db.schema
+ .createTable('collaborations')
+ .addColumn('node_id', 'varchar(30)', (col) => col.notNull())
+ .addColumn('collaborator_id', 'varchar(30)', (col) => col.notNull())
+ .addColumn('workspace_id', 'varchar(30)', (col) => col.notNull())
+ .addColumn('revision', 'bigint', (col) =>
+ col
+ .notNull()
+ .defaultTo(sql`nextval('collaborations_revision_sequence')`)
+ )
+ .addColumn('role', 'varchar(30)', (col) => col.notNull())
+ .addColumn('created_at', 'timestamptz', (col) => col.notNull())
+ .addColumn('created_by', 'varchar(30)', (col) => col.notNull())
+ .addColumn('updated_at', 'timestamptz')
+ .addColumn('updated_by', 'varchar(30)')
+ .addColumn('deleted_at', 'timestamptz')
+ .addColumn('deleted_by', 'varchar(30)')
+ .addPrimaryKeyConstraint('collaborations_pkey', [
+ 'node_id',
+ 'collaborator_id',
+ ])
+ .execute();
+
+ await db.schema
+ .createIndex('collaborations_collaborator_revision_idx')
+ .on('collaborations')
+ .columns(['collaborator_id', 'revision'])
+ .execute();
+
+ await sql`
+ CREATE OR REPLACE FUNCTION update_collaboration_revision() RETURNS TRIGGER AS $$
+ BEGIN
+ NEW.revision = nextval('collaborations_revision_sequence');
+ RETURN NEW;
+ END;
+ $$ LANGUAGE plpgsql;
+
+ CREATE TRIGGER trg_update_collaboration_revision
+ BEFORE UPDATE ON collaborations
+ FOR EACH ROW
+ EXECUTE FUNCTION update_collaboration_revision();
+ `.execute(db);
+ },
+ down: async (db) => {
+ await sql`
+ DROP TRIGGER IF EXISTS trg_update_collaboration_revision ON collaborations;
+ DROP FUNCTION IF EXISTS update_collaboration_revision();
+ `.execute(db);
+
+ await db.schema.dropTable('collaborations').execute();
+ await sql`DROP SEQUENCE IF EXISTS collaborations_revision_sequence`.execute(
+ db
+ );
+ },
+};
diff --git a/apps/server/src/data/migrations/00012-create-files-table.ts b/apps/server/src/data/migrations/00012-create-files-table.ts
new file mode 100644
index 00000000..a62eb751
--- /dev/null
+++ b/apps/server/src/data/migrations/00012-create-files-table.ts
@@ -0,0 +1,66 @@
+import { sql, Migration } from 'kysely';
+
+export const createFilesTable: Migration = {
+ up: async (db) => {
+ await sql`
+ CREATE SEQUENCE IF NOT EXISTS files_revision_sequence
+ START WITH 1000000000
+ INCREMENT BY 1
+ NO MINVALUE
+ NO MAXVALUE
+ CACHE 1;
+ `.execute(db);
+
+ await db.schema
+ .createTable('files')
+ .addColumn('id', 'varchar(30)', (col) => col.notNull().primaryKey())
+ .addColumn('type', 'varchar(30)', (col) => col.notNull())
+ .addColumn('parent_id', 'varchar(30)', (col) => col.notNull())
+ .addColumn('entry_id', 'varchar(30)', (col) => col.notNull())
+ .addColumn('root_id', 'varchar(30)', (col) => col.notNull())
+ .addColumn('workspace_id', 'varchar(30)', (col) => col.notNull())
+ .addColumn('name', 'varchar(256)', (col) => col.notNull())
+ .addColumn('original_name', 'varchar(256)', (col) => col.notNull())
+ .addColumn('mime_type', 'varchar(256)', (col) => col.notNull())
+ .addColumn('extension', 'varchar(256)', (col) => col.notNull())
+ .addColumn('size', 'integer', (col) => col.notNull())
+ .addColumn('created_at', 'timestamptz', (col) => col.notNull())
+ .addColumn('created_by', 'varchar(30)', (col) => col.notNull())
+ .addColumn('updated_at', 'timestamptz')
+ .addColumn('updated_by', 'varchar(30)')
+ .addColumn('status', 'integer', (col) => col.notNull())
+ .addColumn('revision', 'bigint', (col) =>
+ col.notNull().defaultTo(sql`nextval('files_revision_sequence')`)
+ )
+ .execute();
+
+ await db.schema
+ .createIndex('files_root_id_revision_idx')
+ .on('files')
+ .columns(['root_id', 'revision'])
+ .execute();
+
+ await sql`
+ CREATE OR REPLACE FUNCTION update_file_revision() RETURNS TRIGGER AS $$
+ BEGIN
+ NEW.revision = nextval('files_revision_sequence');
+ RETURN NEW;
+ END;
+ $$ LANGUAGE plpgsql;
+
+ CREATE TRIGGER trg_update_file_revision
+ BEFORE UPDATE ON files
+ FOR EACH ROW
+ EXECUTE FUNCTION update_file_revision();
+ `.execute(db);
+ },
+ down: async (db) => {
+ await sql`
+ DROP TRIGGER IF EXISTS trg_update_file_revision ON files;
+ DROP FUNCTION IF EXISTS update_file_revision();
+ `.execute(db);
+
+ await db.schema.dropTable('files').execute();
+ await sql`DROP SEQUENCE IF EXISTS files_revision_sequence`.execute(db);
+ },
+};
diff --git a/apps/server/src/data/migrations/index.ts b/apps/server/src/data/migrations/index.ts
new file mode 100644
index 00000000..16144070
--- /dev/null
+++ b/apps/server/src/data/migrations/index.ts
@@ -0,0 +1,27 @@
+import { Migration } from 'kysely';
+
+import { createAccountsTable } from './00001-create-accounts-table';
+import { createDevicesTable } from './00002-create-devices-table';
+import { createWorkspacesTable } from './00003-create-workspaces-table';
+import { createUsersTable } from './00004-create-users-table';
+import { createNodesTable } from './00005-create-nodes-table';
+import { createNodeReactionsTable } from './00006-create-node-reactions-table';
+import { createNodeInteractionsTable } from './00007-create-node-interactions-table';
+import { createNodeTombstonesTable } from './00009-create-node-tombstones-table';
+import { createNodePathsTable } from './00010-create-node-paths-table';
+import { createCollaborationsTable } from './00011-create-collaborations-table';
+import { createFilesTable } from './00012-create-files-table';
+
+export const databaseMigrations: Record<string, Migration> = {
+ '00001_create_accounts_table': createAccountsTable,
+ '00002_create_devices_table': createDevicesTable,
+ '00003_create_workspaces_table': createWorkspacesTable,
+ '00004_create_users_table': createUsersTable,
+ '00005_create_nodes_table': createNodesTable,
+ '00006_create_node_interactions_table': createNodeInteractionsTable,
+ '00007_create_node_reactions_table': createNodeReactionsTable,
+ '00008_create_node_tombstones_table': createNodeTombstonesTable,
+ '00009_create_node_paths_table': createNodePathsTable,
+ '00010_create_collaborations_table': createCollaborationsTable,
+ '00011_create_files_table': createFilesTable,
+};
diff --git a/apps/server/src/data/schema.ts b/apps/server/src/data/schema.ts
index aec109f6..67e50cdd 100644
--- a/apps/server/src/data/schema.ts
+++ b/apps/server/src/data/schema.ts
@@ -1,13 +1,10 @@
import {
FileStatus,
FileType,
- EntryAttributes,
- EntryRole,
- EntryType,
+ NodeAttributes,
+ NodeRole,
+ NodeType,
WorkspaceRole,
- MessageType,
- MessageAttributes,
- TransactionOperation,
UserStatus,
} from '@colanode/core';
import {
@@ -75,6 +72,7 @@ interface UserTable {
id: ColumnType<string, string, never>;
workspace_id: ColumnType<string, string, never>;
account_id: ColumnType<string, string, never>;
+ revision: ColumnType<bigint, never, never>;
email: ColumnType<string, string, string>;
role: ColumnType<WorkspaceRole, WorkspaceRole, WorkspaceRole>;
name: ColumnType<string, string, string>;
@@ -88,163 +86,111 @@ interface UserTable {
updated_at: ColumnType<Date | null, Date | null, Date>;
updated_by: ColumnType<string | null, string | null, string>;
status: ColumnType<UserStatus, UserStatus, UserStatus>;
- version: ColumnType<bigint, never, never>;
}
export type SelectUser = Selectable<UserTable>;
export type CreateUser = Insertable<UserTable>;
export type UpdateUser = Updateable<UserTable>;
-interface EntryTable {
+interface NodeTable {
id: ColumnType<string, string, never>;
- type: ColumnType<EntryType, never, never>;
+ type: ColumnType<NodeType, never, never>;
parent_id: ColumnType<string | null, never, never>;
root_id: ColumnType<string, string, never>;
workspace_id: ColumnType<string, string, never>;
- attributes: JSONColumnType<EntryAttributes, string | null, string | null>;
+ revision: ColumnType<bigint, never, never>;
+ attributes: JSONColumnType<NodeAttributes, string | null, string | null>;
+ state: ColumnType<Uint8Array, Uint8Array, Uint8Array>;
created_at: ColumnType<Date, Date, never>;
- updated_at: ColumnType<Date | null, Date | null, Date>;
created_by: ColumnType<string, string, never>;
+ updated_at: ColumnType<Date | null, Date | null, Date>;
updated_by: ColumnType<string | null, string | null, string>;
- transaction_id: ColumnType<string, string, string>;
}
-export type SelectEntry = Selectable<EntryTable>;
-export type CreateEntry = Insertable<EntryTable>;
-export type UpdateEntry = Updateable<EntryTable>;
+export type SelectNode = Selectable<NodeTable>;
+export type CreateNode = Insertable<NodeTable>;
+export type UpdateNode = Updateable<NodeTable>;
-interface CollaborationTable {
- entry_id: ColumnType<string, string, never>;
- collaborator_id: ColumnType<string, string, never>;
- workspace_id: ColumnType<string, string, never>;
- role: ColumnType<EntryRole, EntryRole, EntryRole>;
- created_at: ColumnType<Date, Date, never>;
- created_by: ColumnType<string, string, never>;
- updated_at: ColumnType<Date | null, Date | null, Date | null>;
- updated_by: ColumnType<string | null, string | null, string | null>;
- deleted_at: ColumnType<Date | null, Date | null, Date | null>;
- deleted_by: ColumnType<string | null, string | null, string | null>;
- version: ColumnType<bigint, never, never>;
-}
-
-export type SelectCollaboration = Selectable<CollaborationTable>;
-export type CreateCollaboration = Insertable<CollaborationTable>;
-export type UpdateCollaboration = Updateable<CollaborationTable>;
-
-interface EntryTransactionTable {
- id: ColumnType<string, string, never>;
- entry_id: ColumnType<string, string, never>;
- root_id: ColumnType<string, string, never>;
- workspace_id: ColumnType<string, string, never>;
- operation: ColumnType<TransactionOperation, TransactionOperation, never>;
- data: ColumnType<Uint8Array | null, Uint8Array | null, Uint8Array | null>;
- created_at: ColumnType<Date, Date, never>;
- created_by: ColumnType<string, string, never>;
- server_created_at: ColumnType<Date, Date, never>;
- version: ColumnType<bigint, never, never>;
-}
-
-export type SelectEntryTransaction = Selectable<EntryTransactionTable>;
-export type CreateEntryTransaction = Insertable<EntryTransactionTable>;
-export type UpdateEntryTransaction = Updateable<EntryTransactionTable>;
-
-interface EntryInteractionTable {
- entry_id: ColumnType<string, string, never>;
+interface NodeInteractionTable {
+ node_id: ColumnType<string, string, never>;
collaborator_id: ColumnType<string, string, never>;
root_id: ColumnType<string, string, never>;
workspace_id: ColumnType<string, string, never>;
+ revision: ColumnType<bigint, never, never>;
first_seen_at: ColumnType<Date | null, Date | null, Date | null>;
last_seen_at: ColumnType<Date | null, Date | null, Date | null>;
first_opened_at: ColumnType<Date | null, Date | null, Date | null>;
last_opened_at: ColumnType<Date | null, Date | null, Date | null>;
- version: ColumnType<bigint, never, never>;
}
-export type SelectEntryInteraction = Selectable<EntryInteractionTable>;
-export type CreateEntryInteraction = Insertable<EntryInteractionTable>;
-export type UpdateEntryInteraction = Updateable<EntryInteractionTable>;
+export type SelectNodeInteraction = Selectable<NodeInteractionTable>;
+export type CreateNodeInteraction = Insertable<NodeInteractionTable>;
+export type UpdateNodeInteraction = Updateable<NodeInteractionTable>;
-interface EntryPathTable {
- ancestor_id: ColumnType<string, string, never>;
- descendant_id: ColumnType<string, string, never>;
+interface NodeReactionTable {
+ node_id: ColumnType<string, string, never>;
+ collaborator_id: ColumnType<string, string, never>;
+ root_id: ColumnType<string, string, never>;
workspace_id: ColumnType<string, string, never>;
- level: ColumnType<number, number, number>;
+ revision: ColumnType<bigint, never, never>;
+ reaction: ColumnType<string, string, string>;
+ created_at: ColumnType<Date, Date, Date>;
+ deleted_at: ColumnType<Date | null, Date | null, Date | null>;
}
-export type SelectEntryPath = Selectable<EntryPathTable>;
-export type CreateEntryPath = Insertable<EntryPathTable>;
-export type UpdateEntryPath = Updateable<EntryPathTable>;
+export type SelectNodeReaction = Selectable<NodeReactionTable>;
+export type CreateNodeReaction = Insertable<NodeReactionTable>;
+export type UpdateNodeReaction = Updateable<NodeReactionTable>;
-interface MessageTable {
+interface NodeTombstoneTable {
id: ColumnType<string, string, never>;
- type: ColumnType<MessageType, never, never>;
- parent_id: ColumnType<string, string, never>;
- entry_id: ColumnType<string, string, never>;
root_id: ColumnType<string, string, never>;
workspace_id: ColumnType<string, string, never>;
- attributes: JSONColumnType<MessageAttributes, string, string>;
- created_at: ColumnType<Date, Date, never>;
- created_by: ColumnType<string, string, never>;
- updated_at: ColumnType<Date | null, Date | null, Date>;
- updated_by: ColumnType<string | null, string | null, string>;
- version: ColumnType<bigint, never, never>;
+ revision: ColumnType<bigint, never, never>;
+ deleted_at: ColumnType<Date, Date, Date>;
+ deleted_by: ColumnType<string, string, never>;
}
-export type SelectMessage = Selectable<MessageTable>;
-export type CreateMessage = Insertable<MessageTable>;
-export type UpdateMessage = Updateable<MessageTable>;
+export type SelectNodeTombstone = Selectable<NodeTombstoneTable>;
+export type CreateNodeTombstone = Insertable<NodeTombstoneTable>;
+export type UpdateNodeTombstone = Updateable<NodeTombstoneTable>;
-interface MessageReactionTable {
- message_id: ColumnType<string, string, never>;
- collaborator_id: ColumnType<string, string, never>;
- root_id: ColumnType<string, string, never>;
+interface NodePathTable {
+ ancestor_id: ColumnType<string, string, never>;
+ descendant_id: ColumnType<string, string, never>;
workspace_id: ColumnType<string, string, never>;
- reaction: ColumnType<string, string, string>;
- created_at: ColumnType<Date, Date, Date>;
- deleted_at: ColumnType<Date | null, Date | null, Date | null>;
- version: ColumnType<bigint, never, never>;
+ level: ColumnType<number, number, number>;
}
-export type SelectMessageReaction = Selectable<MessageReactionTable>;
-export type CreateMessageReaction = Insertable<MessageReactionTable>;
-export type UpdateMessageReaction = Updateable<MessageReactionTable>;
+export type SelectNodePath = Selectable<NodePathTable>;
+export type CreateNodePath = Insertable<NodePathTable>;
+export type UpdateNodePath = Updateable<NodePathTable>;
-interface MessageInteractionTable {
- message_id: ColumnType<string, string, never>;
+interface CollaborationTable {
+ node_id: ColumnType<string, string, never>;
collaborator_id: ColumnType<string, string, never>;
- root_id: ColumnType<string, string, never>;
- workspace_id: ColumnType<string, string, never>;
- first_seen_at: ColumnType<Date | null, Date | null, Date | null>;
- last_seen_at: ColumnType<Date | null, Date | null, Date | null>;
- first_opened_at: ColumnType<Date | null, Date | null, Date | null>;
- last_opened_at: ColumnType<Date | null, Date | null, Date | null>;
- version: ColumnType<bigint, never, never>;
-}
-
-export type SelectMessageInteraction = Selectable<MessageInteractionTable>;
-export type CreateMessageInteraction = Insertable<MessageInteractionTable>;
-export type UpdateMessageInteraction = Updateable<MessageInteractionTable>;
-
-interface MessageTombstoneTable {
- id: ColumnType<string, string, never>;
- root_id: ColumnType<string, string, never>;
workspace_id: ColumnType<string, string, never>;
- deleted_at: ColumnType<Date, Date, Date>;
- deleted_by: ColumnType<string, string, never>;
- version: ColumnType<bigint, never, never>;
+ revision: ColumnType<bigint, never, never>;
+ role: ColumnType<NodeRole, NodeRole, NodeRole>;
+ created_at: ColumnType<Date, Date, never>;
+ created_by: ColumnType<string, string, never>;
+ updated_at: ColumnType<Date | null, Date | null, Date | null>;
+ updated_by: ColumnType<string | null, string | null, string | null>;
+ deleted_at: ColumnType<Date | null, Date | null, Date | null>;
+ deleted_by: ColumnType<string | null, string | null, string | null>;
}
-export type SelectMessageTombstone = Selectable<MessageTombstoneTable>;
-export type CreateMessageTombstone = Insertable<MessageTombstoneTable>;
-export type UpdateMessageTombstone = Updateable<MessageTombstoneTable>;
+export type SelectCollaboration = Selectable<CollaborationTable>;
+export type CreateCollaboration = Insertable<CollaborationTable>;
+export type UpdateCollaboration = Updateable<CollaborationTable>;
interface FileTable {
id: ColumnType<string, string, never>;
type: ColumnType<FileType, FileType, FileType>;
parent_id: ColumnType<string, string, never>;
- entry_id: ColumnType<string, string, never>;
root_id: ColumnType<string, string, never>;
workspace_id: ColumnType<string, string, never>;
+ revision: ColumnType<bigint, never, never>;
name: ColumnType<string, string, never>;
original_name: ColumnType<string, string, never>;
mime_type: ColumnType<string, string, never>;
@@ -255,94 +201,22 @@ interface FileTable {
updated_at: ColumnType<Date | null, Date | null, Date | null>;
updated_by: ColumnType<string | null, string | null, string | null>;
status: ColumnType<FileStatus, FileStatus, FileStatus>;
- version: ColumnType<bigint, never, never>;
}
export type SelectFile = Selectable<FileTable>;
export type CreateFile = Insertable<FileTable>;
export type UpdateFile = Updateable<FileTable>;
-interface FileInteractionTable {
- file_id: ColumnType<string, string, never>;
- collaborator_id: ColumnType<string, string, never>;
- root_id: ColumnType<string, string, never>;
- workspace_id: ColumnType<string, string, never>;
- first_seen_at: ColumnType<Date | null, Date | null, Date | null>;
- last_seen_at: ColumnType<Date | null, Date | null, Date | null>;
- first_opened_at: ColumnType<Date | null, Date | null, Date | null>;
- last_opened_at: ColumnType<Date | null, Date | null, Date | null>;
- version: ColumnType<bigint, never, never>;
-}
-
-export type SelectFileInteraction = Selectable<FileInteractionTable>;
-export type CreateFileInteraction = Insertable<FileInteractionTable>;
-export type UpdateFileInteraction = Updateable<FileInteractionTable>;
-
-interface FileTombstoneTable {
- id: ColumnType<string, string, never>;
- root_id: ColumnType<string, string, never>;
- workspace_id: ColumnType<string, string, never>;
- deleted_at: ColumnType<Date, Date, Date>;
- deleted_by: ColumnType<string, string, never>;
- version: ColumnType<bigint, never, never>;
-}
-
-export type SelectFileTombstone = Selectable<FileTombstoneTable>;
-export type CreateFileTombstone = Insertable<FileTombstoneTable>;
-export type UpdateFileTombstone = Updateable<FileTombstoneTable>;
-
-interface EntryEmbeddingTable {
- entry_id: ColumnType<string, string, never>;
- chunk: ColumnType<number, number, number>;
- parent_id: ColumnType<string | null, string | null, never>;
- root_id: ColumnType<string, string, never>;
- workspace_id: ColumnType<string, string, never>;
- text: ColumnType<string, string, string>;
- embedding_vector: ColumnType<number[], number[], number[]>;
- search_vector: ColumnType<never, never, never>;
- created_at: ColumnType<Date, Date, never>;
- updated_at: ColumnType<Date | null, Date | null, Date | null>;
-}
-
-export type SelectEntryEmbedding = Selectable<EntryEmbeddingTable>;
-export type CreateEntryEmbedding = Insertable<EntryEmbeddingTable>;
-export type UpdateEntryEmbedding = Updateable<EntryEmbeddingTable>;
-
-interface MessageEmbeddingTable {
- message_id: ColumnType<string, string, never>;
- chunk: ColumnType<number, number, number>;
- parent_id: ColumnType<string, string, never>;
- entry_id: ColumnType<string, string, never>;
- root_id: ColumnType<string, string, never>;
- workspace_id: ColumnType<string, string, never>;
- text: ColumnType<string, string, string>;
- embedding_vector: ColumnType<number[], number[], number[]>;
- search_vector: ColumnType<never, never, never>;
- created_at: ColumnType<Date, Date, never>;
- updated_at: ColumnType<Date | null, Date | null, Date | null>;
-}
-
-export type SelectMessageEmbedding = Selectable<MessageEmbeddingTable>;
-export type CreateMessageEmbedding = Insertable<MessageEmbeddingTable>;
-export type UpdateMessageEmbedding = Updateable<MessageEmbeddingTable>;
-
export interface DatabaseSchema {
accounts: AccountTable;
devices: DeviceTable;
workspaces: WorkspaceTable;
users: UserTable;
- entries: EntryTable;
- entry_transactions: EntryTransactionTable;
- entry_interactions: EntryInteractionTable;
- entry_paths: EntryPathTable;
- messages: MessageTable;
- message_reactions: MessageReactionTable;
- message_interactions: MessageInteractionTable;
- message_tombstones: MessageTombstoneTable;
- files: FileTable;
- file_interactions: FileInteractionTable;
- file_tombstones: FileTombstoneTable;
+ nodes: NodeTable;
+ node_interactions: NodeInteractionTable;
+ node_reactions: NodeReactionTable;
+ node_paths: NodePathTable;
+ node_tombstones: NodeTombstoneTable;
collaborations: CollaborationTable;
- entry_embeddings: EntryEmbeddingTable;
- message_embeddings: MessageEmbeddingTable;
+ files: FileTable;
}
diff --git a/apps/server/src/jobs/clean-entry-data.ts b/apps/server/src/jobs/clean-entry-data.ts
deleted file mode 100644
index 37018bc1..00000000
--- a/apps/server/src/jobs/clean-entry-data.ts
+++ /dev/null
@@ -1,307 +0,0 @@
-import { DeleteObjectCommand } from '@aws-sdk/client-s3';
-import {
- createDebugger,
- generateId,
- IdType,
- TransactionOperation,
-} from '@colanode/core';
-
-import { database } from '@/data/database';
-import {
- CreateEntryTransaction,
- CreateFileTombstone,
- CreateMessageTombstone,
-} from '@/data/schema';
-import { JobHandler } from '@/types/jobs';
-import { eventBus } from '@/lib/event-bus';
-import { fileS3 } from '@/data/storage';
-import { configuration } from '@/lib/configuration';
-
-const BATCH_SIZE = 100;
-
-const debug = createDebugger('server:job:clean-entry-data');
-
-export type CleanEntryDataInput = {
- type: 'clean_entry_data';
- entryId: string;
- workspaceId: string;
-};
-
-declare module '@/types/jobs' {
- interface JobMap {
- clean_entry_data: {
- input: CleanEntryDataInput;
- };
- }
-}
-
-export const cleanEntryDataHandler: JobHandler<CleanEntryDataInput> = async (
- input
-) => {
- debug(`Cleaning entry data for ${input.entryId}`);
-
- const deleteTransactions = await database
- .selectFrom('entry_transactions')
- .selectAll()
- .where('entry_id', '=', input.entryId)
- .execute();
-
- if (deleteTransactions.length !== 1) {
- debug(`Expected 1 delete transaction for ${input.entryId}`);
- return;
- }
-
- const deleteTransaction = deleteTransactions[0];
- if (
- !deleteTransaction?.operation ||
- deleteTransaction.operation !== TransactionOperation.Delete
- ) {
- debug(`Expected delete transaction for ${input.entryId}`);
- return;
- }
-
- const userId = deleteTransaction.created_by;
-
- const parentIds = [input.entryId];
- while (parentIds.length > 0) {
- const tempParentIds = parentIds.splice(0, BATCH_SIZE);
- const deletedEntryIds = await deleteChildren(tempParentIds, userId);
-
- await deleteMessages(tempParentIds, userId);
- await deleteFiles(tempParentIds, userId);
-
- parentIds.push(...deletedEntryIds);
- }
-};
-
-const deleteChildren = async (parentIds: string[], userId: string) => {
- const deletedEntryIds: string[] = [];
- let hasMore = true;
- while (hasMore) {
- try {
- const descendants = await database
- .selectFrom('entries')
- .selectAll()
- .where('parent_id', 'in', parentIds)
- .orderBy('id', 'asc')
- .limit(BATCH_SIZE)
- .execute();
-
- if (descendants.length === 0) {
- debug(`No descendants found for ${parentIds}`);
- hasMore = false;
- break;
- }
-
- const entryIds: string[] = descendants.map((d) => d.id);
- const transactionsToCreate: CreateEntryTransaction[] = descendants.map(
- (descendant) => ({
- id: generateId(IdType.Transaction),
- entry_id: descendant.id,
- root_id: descendant.root_id,
- workspace_id: descendant.workspace_id,
- operation: TransactionOperation.Delete,
- created_at: new Date(),
- created_by: userId,
- server_created_at: new Date(),
- })
- );
-
- await database.transaction().execute(async (trx) => {
- await trx
- .deleteFrom('entry_transactions')
- .where('entry_id', 'in', entryIds)
- .execute();
-
- const createdTransactions = await trx
- .insertInto('entry_transactions')
- .returningAll()
- .values(transactionsToCreate)
- .execute();
-
- if (createdTransactions.length !== transactionsToCreate.length) {
- throw new Error('Failed to create transactions');
- }
-
- await trx.deleteFrom('entries').where('id', 'in', entryIds).execute();
-
- await trx
- .deleteFrom('entry_interactions')
- .where('entry_id', 'in', entryIds)
- .execute();
-
- await trx
- .deleteFrom('entry_embeddings')
- .where('entry_id', 'in', entryIds)
- .execute();
-
- await trx
- .updateTable('collaborations')
- .set({
- deleted_at: new Date(),
- deleted_by: userId,
- })
- .where('entry_id', 'in', entryIds)
- .execute();
- });
-
- for (const entry of descendants) {
- eventBus.publish({
- type: 'entry_deleted',
- entryId: entry.id,
- entryType: entry.type,
- rootId: entry.root_id,
- workspaceId: entry.workspace_id,
- });
-
- deletedEntryIds.push(entry.id);
- }
-
- hasMore = descendants.length === BATCH_SIZE;
- } catch (error) {
- debug(`Error cleaning entry data for ${parentIds}: ${error}`);
- hasMore = false;
- }
- }
-
- return deletedEntryIds;
-};
-
-const deleteMessages = async (entryIds: string[], userId: string) => {
- let hasMore = true;
- while (hasMore) {
- try {
- const messages = await database
- .selectFrom('messages')
- .selectAll()
- .where('entry_id', 'in', entryIds)
- .orderBy('id', 'asc')
- .limit(BATCH_SIZE)
- .execute();
-
- if (messages.length === 0) {
- hasMore = false;
- break;
- }
-
- const messageIds: string[] = messages.map((m) => m.id);
- const messageTombstonesToCreate: CreateMessageTombstone[] = messages.map(
- (message) => ({
- id: message.id,
- root_id: message.root_id,
- workspace_id: message.workspace_id,
- deleted_at: new Date(),
- deleted_by: userId,
- })
- );
-
- await database.transaction().execute(async (trx) => {
- await trx
- .deleteFrom('messages')
- .where('id', 'in', messageIds)
- .execute();
-
- await trx
- .deleteFrom('message_reactions')
- .where('message_id', 'in', messageIds)
- .execute();
-
- await trx
- .deleteFrom('message_interactions')
- .where('message_id', 'in', messageIds)
- .execute();
-
- await trx
- .deleteFrom('message_embeddings')
- .where('message_id', 'in', messageIds)
- .execute();
-
- await trx
- .insertInto('message_tombstones')
- .values(messageTombstonesToCreate)
- .execute();
- });
-
- for (const message of messages) {
- eventBus.publish({
- type: 'message_deleted',
- messageId: message.id,
- rootId: message.root_id,
- workspaceId: message.workspace_id,
- });
- }
-
- hasMore = messages.length === BATCH_SIZE;
- } catch (error) {
- debug(`Error deleting messages for ${entryIds}: ${error}`);
- hasMore = false;
- }
- }
-};
-
-const deleteFiles = async (entryIds: string[], userId: string) => {
- let hasMore = true;
- while (hasMore) {
- try {
- const files = await database
- .selectFrom('files')
- .selectAll()
- .where('entry_id', 'in', entryIds)
- .orderBy('id', 'asc')
- .limit(BATCH_SIZE)
- .execute();
-
- if (files.length === 0) {
- hasMore = false;
- break;
- }
-
- const fileIds: string[] = files.map((m) => m.id);
- const fileTombstonesToCreate: CreateFileTombstone[] = files.map(
- (file) => ({
- id: file.id,
- root_id: file.root_id,
- workspace_id: file.workspace_id,
- deleted_at: new Date(),
- deleted_by: userId,
- })
- );
-
- await database.transaction().execute(async (trx) => {
- await trx.deleteFrom('files').where('id', 'in', fileIds).execute();
-
- await trx
- .deleteFrom('file_interactions')
- .where('file_id', 'in', fileIds)
- .execute();
-
- await trx
- .insertInto('file_tombstones')
- .values(fileTombstonesToCreate)
- .execute();
- });
-
- for (const file of files) {
- eventBus.publish({
- type: 'file_deleted',
- fileId: file.id,
- rootId: file.root_id,
- workspaceId: file.workspace_id,
- });
-
- const path = `files/${file.workspace_id}/${file.id}${file.extension}`;
- const command = new DeleteObjectCommand({
- Bucket: configuration.fileS3.bucketName,
- Key: path,
- });
-
- await fileS3.send(command);
- }
-
- hasMore = files.length === BATCH_SIZE;
- } catch (error) {
- debug(`Error deleting files for ${entryIds}: ${error}`);
- hasMore = false;
- }
- }
-};
diff --git a/apps/server/src/jobs/clean-node-data.ts b/apps/server/src/jobs/clean-node-data.ts
new file mode 100644
index 00000000..2138bdf6
--- /dev/null
+++ b/apps/server/src/jobs/clean-node-data.ts
@@ -0,0 +1,183 @@
+import { createDebugger } from '@colanode/core';
+
+import { database } from '@/data/database';
+import { JobHandler } from '@/types/jobs';
+import { eventBus } from '@/lib/event-bus';
+import { CreateNodeTombstone } from '@/data/schema';
+
+const BATCH_SIZE = 100;
+
+const debug = createDebugger('server:job:clean-node-data');
+
+export type CleanNodeDataInput = {
+ type: 'clean_node_data';
+ nodeId: string;
+ workspaceId: string;
+ userId: string;
+};
+
+declare module '@/types/jobs' {
+ interface JobMap {
+ clean_node_data: {
+ input: CleanNodeDataInput;
+ };
+ }
+}
+
+export const cleanNodeDataHandler: JobHandler<CleanNodeDataInput> = async (
+ input
+) => {
+ debug(`Cleaning node data for ${input.nodeId}`);
+ const parentIds = [input.nodeId];
+ while (parentIds.length > 0) {
+ const tempParentIds = parentIds.splice(0, BATCH_SIZE);
+ const deletedNodeIds = await deleteChildren(tempParentIds, input.userId);
+ parentIds.push(...deletedNodeIds);
+ }
+};
+
+const deleteChildren = async (parentIds: string[], userId: string) => {
+ const deletedNodeIds: string[] = [];
+ let hasMore = true;
+ while (hasMore) {
+ try {
+ const descendants = await database
+ .selectFrom('nodes')
+ .selectAll()
+ .where('parent_id', 'in', parentIds)
+ .orderBy('id', 'asc')
+ .limit(BATCH_SIZE)
+ .execute();
+
+ if (descendants.length === 0) {
+ debug(`No descendants found for ${parentIds}`);
+ hasMore = false;
+ break;
+ }
+
+ const nodeIds: string[] = descendants.map((d) => d.id);
+ const nodeTombstonesToCreate: CreateNodeTombstone[] = descendants.map(
+ (node) => ({
+ id: node.id,
+ root_id: node.root_id,
+ workspace_id: node.workspace_id,
+ deleted_at: new Date(),
+ deleted_by: userId,
+ })
+ );
+
+ await database.transaction().execute(async (trx) => {
+ await trx.deleteFrom('nodes').where('id', 'in', nodeIds).execute();
+
+ await trx
+ .deleteFrom('node_interactions')
+ .where('node_id', 'in', nodeIds)
+ .execute();
+
+ await trx
+ .deleteFrom('node_reactions')
+ .where('node_id', 'in', nodeIds)
+ .execute();
+
+ await trx
+ .updateTable('collaborations')
+ .set({
+ deleted_at: new Date(),
+ deleted_by: userId,
+ })
+ .where('node_id', 'in', nodeIds)
+ .execute();
+
+ await trx
+ .insertInto('node_tombstones')
+ .values(nodeTombstonesToCreate)
+ .execute();
+ });
+
+ for (const node of descendants) {
+ eventBus.publish({
+ type: 'node_deleted',
+ nodeId: node.id,
+ rootId: node.root_id,
+ workspaceId: node.workspace_id,
+ });
+
+ deletedNodeIds.push(node.id);
+ }
+
+ hasMore = descendants.length === BATCH_SIZE;
+ } catch (error) {
+ debug(`Error cleaning node data for ${parentIds}: ${error}`);
+ hasMore = false;
+ }
+ }
+
+ return deletedNodeIds;
+};
+
+// const deleteFiles = async (entryIds: string[], userId: string) => {
+// let hasMore = true;
+// while (hasMore) {
+// try {
+// const files = await database
+// .selectFrom('files')
+// .selectAll()
+// .where('entry_id', 'in', entryIds)
+// .orderBy('id', 'asc')
+// .limit(BATCH_SIZE)
+// .execute();
+
+// if (files.length === 0) {
+// hasMore = false;
+// break;
+// }
+
+// const fileIds: string[] = files.map((m) => m.id);
+// const fileTombstonesToCreate: CreateFileTombstone[] = files.map(
+// (file) => ({
+// id: file.id,
+// root_id: file.root_id,
+// workspace_id: file.workspace_id,
+// deleted_at: new Date(),
+// deleted_by: userId,
+// })
+// );
+
+// await database.transaction().execute(async (trx) => {
+// await trx.deleteFrom('files').where('id', 'in', fileIds).execute();
+
+// await trx
+// .deleteFrom('file_interactions')
+// .where('file_id', 'in', fileIds)
+// .execute();
+
+// await trx
+// .insertInto('file_tombstones')
+// .values(fileTombstonesToCreate)
+// .execute();
+// });
+
+// for (const file of files) {
+// eventBus.publish({
+// type: 'file_deleted',
+// fileId: file.id,
+// rootId: file.root_id,
+// workspaceId: file.workspace_id,
+// });
+
+// const path = `files/${file.workspace_id}/${file.id}${file.extension}`;
+// const command = new DeleteObjectCommand({
+// Bucket: configuration.fileS3.bucketName,
+// Key: path,
+// });
+
+// await fileS3.send(command);
+// }
+
+// hasMore = files.length === BATCH_SIZE;
+// } catch (error) {
+// debug(`Error deleting files for ${entryIds}: ${error}`);
+// hasMore = false;
+// }
+// }
+// };
diff --git a/apps/server/src/jobs/embed-entry.ts b/apps/server/src/jobs/embed-entry.ts
deleted file mode 100644
index f7614f99..00000000
--- a/apps/server/src/jobs/embed-entry.ts
+++ /dev/null
@@ -1,125 +0,0 @@
-import { OpenAIEmbeddings } from '@langchain/openai';
-import { extractEntryText } from '@colanode/core';
-
-import { JobHandler } from '@/types/jobs';
-import { ChunkingService } from '@/services/chunking-service';
-import { database } from '@/data/database';
-import { configuration } from '@/lib/configuration';
-import { CreateEntryEmbedding } from '@/data/schema';
-
-export type EmbedEntryInput = {
- type: 'embed_entry';
- entryId: string;
-};
-
-declare module '@/types/jobs' {
- interface JobMap {
- embed_entry: {
- input: EmbedEntryInput;
- };
- }
-}
-
-export const embedEntryHandler: JobHandler<EmbedEntryInput> = async (input) => {
- if (!configuration.ai.enabled) {
- return;
- }
-
- const { entryId } = input;
-
- const entry = await database
- .selectFrom('entries')
- .select(['id', 'attributes', 'parent_id', 'root_id', 'workspace_id'])
- .where('id', '=', entryId)
- .executeTakeFirst();
-
- if (!entry) {
- return;
- }
-
- const textResult = extractEntryText(entryId, entry.attributes);
- if (textResult === undefined) {
- return;
- }
-
- if (textResult.text === null || textResult.text === '') {
- await database
- .deleteFrom('entry_embeddings')
- .where('entry_id', '=', entryId)
- .execute();
-
- return;
- }
-
- const chunkingService = new ChunkingService();
- const chunks = await chunkingService.chunkText(textResult.text);
-
- const embeddings = new OpenAIEmbeddings({
- apiKey: configuration.ai.openai.apiKey,
- modelName: configuration.ai.openai.embeddingModel,
- dimensions: configuration.ai.openai.embeddingDimensions,
- });
-
- const existingEmbeddings = await database
- .selectFrom('entry_embeddings')
- .select(['chunk', 'text'])
- .where('entry_id', '=', entryId)
- .execute();
-
- const embeddingsToCreateOrUpdate: CreateEntryEmbedding[] = [];
-
- for (let i = 0; i < chunks.length; i++) {
- const chunk = chunks[i];
- if (!chunk) {
- continue;
- }
-
- const existingEmbedding = existingEmbeddings.find((e) => e.chunk === i);
-
- if (existingEmbedding && existingEmbedding.text === chunk) {
- continue;
- }
-
- embeddingsToCreateOrUpdate.push({
- entry_id: entryId,
- chunk: i,
- parent_id: entry.parent_id,
- root_id: entry.root_id,
- workspace_id: entry.workspace_id,
- text: chunk,
- embedding_vector: [],
- created_at: new Date(),
- });
- }
-
- const batchSize = configuration.ai.openai.embeddingBatchSize;
- for (let i = 0; i < embeddingsToCreateOrUpdate.length; i += batchSize) {
- const batch = embeddingsToCreateOrUpdate.slice(i, i + batchSize);
- const textsToEmbed = batch.map((item) => item.text);
- const embeddingVectors = await embeddings.embedDocuments(textsToEmbed);
-
- for (let j = 0; j < batch.length; j++) {
- const vector = embeddingVectors[j];
- const batchItem = batch[j];
- if (vector && batchItem) {
- batchItem.embedding_vector = vector;
- }
- }
- }
-
- if (embeddingsToCreateOrUpdate.length == 0) {
- return;
- }
-
- await database
- .insertInto('entry_embeddings')
- .values(embeddingsToCreateOrUpdate)
- .onConflict((oc) =>
- oc.columns(['entry_id', 'chunk']).doUpdateSet((eb) => ({
- text: eb.ref('excluded.text'),
- embedding_vector: eb.ref('excluded.embedding_vector'),
- updated_at: new Date(),
- }))
- )
- .execute();
-};
diff --git a/apps/server/src/jobs/embed-message.ts b/apps/server/src/jobs/embed-message.ts
deleted file mode 100644
index 9b234d3e..00000000
--- a/apps/server/src/jobs/embed-message.ts
+++ /dev/null
@@ -1,119 +0,0 @@
-import { OpenAIEmbeddings } from '@langchain/openai';
-import { extractMessageText } from '@colanode/core';
-
-import { JobHandler } from '@/types/jobs';
-import { ChunkingService } from '@/services/chunking-service';
-import { database } from '@/data/database';
-import { configuration } from '@/lib/configuration';
-import { CreateMessageEmbedding } from '@/data/schema';
-
-export type EmbedMessageInput = {
- type: 'embed_message';
- messageId: string;
-};
-
-declare module '@/types/jobs' {
- interface JobMap {
- embed_message: {
- input: EmbedMessageInput;
- };
- }
-}
-
-export const embedMessageHandler: JobHandler<EmbedMessageInput> = async (
- input
-) => {
- if (!configuration.ai.enabled) {
- return;
- }
-
- const { messageId } = input;
-
- const message = await database
- .selectFrom('messages')
- .selectAll()
- .where('id', '=', messageId)
- .executeTakeFirst();
-
- if (!message) {
- return;
- }
-
- const chunkingService = new ChunkingService();
- const text = extractMessageText(message.id, message.attributes);
-
- if (!text || !text.text) {
- return;
- }
-
- const chunks = await chunkingService.chunkText(text.text);
- const embeddings = new OpenAIEmbeddings({
- apiKey: configuration.ai.openai.apiKey,
- modelName: configuration.ai.openai.embeddingModel,
- dimensions: configuration.ai.openai.embeddingDimensions,
- });
-
- const existingEmbeddings = await database
- .selectFrom('message_embeddings')
- .select(['chunk', 'text'])
- .where('message_id', '=', messageId)
- .execute();
-
- const embeddingsToCreateOrUpdate: CreateMessageEmbedding[] = [];
-
- for (let i = 0; i < chunks.length; i++) {
- const chunk = chunks[i];
- if (!chunk) {
- continue;
- }
-
- const existingEmbedding = existingEmbeddings.find((e) => e.chunk === i);
-
- if (existingEmbedding && existingEmbedding.text === chunk) {
- continue;
- }
-
- embeddingsToCreateOrUpdate.push({
- message_id: messageId,
- chunk: i,
- parent_id: message.parent_id,
- entry_id: message.entry_id,
- root_id: message.root_id,
- workspace_id: message.workspace_id,
- text: chunk,
- embedding_vector: [],
- created_at: new Date(),
- });
- }
-
- const batchSize = configuration.ai.openai.embeddingBatchSize;
- for (let i = 0; i < embeddingsToCreateOrUpdate.length; i += batchSize) {
- const batch = embeddingsToCreateOrUpdate.slice(i, i + batchSize);
- const textsToEmbed = batch.map((item) => item.text);
- const embeddingVectors = await embeddings.embedDocuments(textsToEmbed);
-
- for (let j = 0; j < batch.length; j++) {
- const vector = embeddingVectors[j];
- const batchItem = batch[j];
- if (vector && batchItem) {
- batchItem.embedding_vector = vector;
- }
- }
- }
-
- if (embeddingsToCreateOrUpdate.length == 0) {
- return;
- }
-
- await database
- .insertInto('message_embeddings')
- .values(embeddingsToCreateOrUpdate)
- .onConflict((oc) =>
- oc.columns(['message_id', 'chunk']).doUpdateSet((eb) => ({
- text: eb.ref('excluded.text'),
- embedding_vector: eb.ref('excluded.embedding_vector'),
- updated_at: new Date(),
- }))
- )
- .execute();
-};
diff --git a/apps/server/src/jobs/index.ts b/apps/server/src/jobs/index.ts
index 8a84e8f5..70ab60ec 100644
--- a/apps/server/src/jobs/index.ts
+++ b/apps/server/src/jobs/index.ts
@@ -1,8 +1,6 @@
-import { cleanEntryDataHandler } from '@/jobs/clean-entry-data';
+import { cleanNodeDataHandler } from '@/jobs/clean-node-data';
import { cleanWorkspaceDataHandler } from '@/jobs/clean-workspace-data';
import { JobHandler, JobMap } from '@/types/jobs';
-import { embedMessageHandler } from '@/jobs/embed-message';
-import { embedEntryHandler } from '@/jobs/embed-entry';
import { sendEmailVerifyEmailHandler } from '@/jobs/send-email-verify-email';
type JobHandlerMap = {
@@ -12,7 +10,5 @@ type JobHandlerMap = {
export const jobHandlerMap: JobHandlerMap = {
send_email_verify_email: sendEmailVerifyEmailHandler,
clean_workspace_data: cleanWorkspaceDataHandler,
- clean_entry_data: cleanEntryDataHandler,
- embed_message: embedMessageHandler,
- embed_entry: embedEntryHandler,
+ clean_node_data: cleanNodeDataHandler,
};
diff --git a/apps/server/src/jobs/send-email-verify-email.ts b/apps/server/src/jobs/send-email-verify-email.ts
index d9b0093f..f1a91bd2 100644
--- a/apps/server/src/jobs/send-email-verify-email.ts
+++ b/apps/server/src/jobs/send-email-verify-email.ts
@@ -1,4 +1,4 @@
-import { accountService } from '@/services/account-service';
+import { sendEmailVerifyEmail } from '@/lib/accounts';
import { JobHandler } from '@/types/jobs';
export type SendEmailVerifyEmailInput = {
@@ -18,5 +18,5 @@ export const sendEmailVerifyEmailHandler: JobHandler<
SendEmailVerifyEmailInput
> = async (input) => {
const { otpId } = input;
- await accountService.sendEmailVerifyEmail(otpId);
+ await sendEmailVerifyEmail(otpId);
};
diff --git a/apps/server/src/lib/accounts.ts b/apps/server/src/lib/accounts.ts
new file mode 100644
index 00000000..dadc934e
--- /dev/null
+++ b/apps/server/src/lib/accounts.ts
@@ -0,0 +1,202 @@
+import {
+ IdType,
+ UserStatus,
+ WorkspaceRole,
+ WorkspaceOutput,
+ LoginSuccessOutput,
+ generateId,
+ LoginVerifyOutput,
+} from '@colanode/core';
+
+import { configuration } from '@/lib/configuration';
+import { database } from '@/data/database';
+import { SelectAccount } from '@/data/schema';
+import { generateToken } from '@/lib/tokens';
+import { createDefaultWorkspace } from '@/lib/workspaces';
+import { jobService } from '@/services/job-service';
+import { emailVerifyTemplate } from '@/templates';
+import { emailService } from '@/services/email-service';
+import { deleteOtp, fetchOtp, generateOtpCode, saveOtp } from '@/lib/otps';
+import { Otp, AccountVerifyOtpAttributes } from '@/types/otps';
+
+interface DeviceMetadata {
+ ip: string | undefined;
+ platform: string;
+ version: string;
+}
+
+export const buildLoginSuccessOutput = async (
+ account: SelectAccount,
+ metadata: DeviceMetadata
+): Promise<LoginSuccessOutput> => {
+ const users = await database
+ .selectFrom('users')
+ .where('account_id', '=', account.id)
+ .where('status', '=', UserStatus.Active)
+ .where('role', '!=', 'none')
+ .selectAll()
+ .execute();
+
+ const workspaceOutputs: WorkspaceOutput[] = [];
+ if (users.length > 0) {
+ const workspaceIds = users.map((u) => u.workspace_id);
+ const workspaces = await database
+ .selectFrom('workspaces')
+ .where('id', 'in', workspaceIds)
+ .selectAll()
+ .execute();
+
+ for (const user of users) {
+ const workspace = workspaces.find((w) => w.id === user.workspace_id);
+
+ if (!workspace) {
+ continue;
+ }
+
+ workspaceOutputs.push({
+ id: workspace.id,
+ name: workspace.name,
+ avatar: workspace.avatar,
+ description: workspace.description,
+ user: {
+ id: user.id,
+ accountId: user.account_id,
+ role: user.role as WorkspaceRole,
+ storageLimit: user.storage_limit,
+ maxFileSize: user.max_file_size,
+ },
+ });
+ }
+ }
+
+ if (workspaceOutputs.length === 0) {
+ const workspace = await createDefaultWorkspace(account);
+ workspaceOutputs.push(workspace);
+ }
+
+ const deviceId = generateId(IdType.Device);
+ const { token, salt, hash } = generateToken(deviceId);
+
+ const device = await database
+ .insertInto('devices')
+ .values({
+ id: deviceId,
+ account_id: account.id,
+ token_hash: hash,
+ token_salt: salt,
+ token_generated_at: new Date(),
+ type: 1,
+ ip: metadata.ip,
+ platform: metadata.platform,
+ version: metadata.version,
+ created_at: new Date(),
+ })
+ .returningAll()
+ .executeTakeFirst();
+
+ if (!device) {
+ throw new Error('Failed to create device.');
+ }
+
+ return {
+ type: 'success',
+ account: {
+ id: account.id,
+ name: account.name,
+ email: account.email,
+ avatar: account.avatar,
+ },
+ workspaces: workspaceOutputs,
+ deviceId: device.id,
+ token,
+ };
+};
+
+export const buildLoginVerifyOutput = async (
+ account: SelectAccount
+): Promise<LoginVerifyOutput> => {
+ const id = generateId(IdType.OtpCode);
+ const expiresAt = new Date(
+ Date.now() + configuration.account.otpTimeout * 1000
+ );
+ const otpCode = await generateOtpCode();
+
+ const otp: Otp<AccountVerifyOtpAttributes> = {
+ id,
+ expiresAt,
+ otp: otpCode,
+ attributes: {
+ accountId: account.id,
+ attempts: 0,
+ },
+ };
+
+ await saveOtp(id, otp);
+ await jobService.addJob({
+ type: 'send_email_verify_email',
+ otpId: id,
+ });
+
+ return {
+ type: 'verify',
+ id,
+ expiresAt,
+ };
+};
+
+export const verifyOtpCode = async (
+ id: string,
+ otpCode: string
+): Promise<string | null> => {
+ const otp = await fetchOtp<AccountVerifyOtpAttributes>(id);
+ if (!otp) {
+ return null;
+ }
+
+ if (otp.otp !== otpCode) {
+ if (otp.attributes.attempts >= 3) {
+ await deleteOtp(id);
+ return null;
+ }
+
+ otp.attributes.attempts++;
+
+ await saveOtp(id, otp);
+ return null;
+ }
+
+ await deleteOtp(id);
+ return otp.attributes.accountId;
+};
+
+export const sendEmailVerifyEmail = async (otpId: string): Promise<void> => {
+ const otp = await fetchOtp<AccountVerifyOtpAttributes>(otpId);
+ if (!otp) {
+ return;
+ }
+
+ const account = await database
+ .selectFrom('accounts')
+ .where('id', '=', otp.attributes.accountId)
+ .selectAll()
+ .executeTakeFirst();
+
+ if (!account) {
+ return;
+ }
+
+ const email = account.email;
+ const name = account.name;
+ const otpCode = otp.otp;
+
+ const html = emailVerifyTemplate({
+ name,
+ otp: otpCode,
+ });
+
+ await emailService.sendEmail({
+ subject: 'Your Colanode email verification code',
+ to: email,
+ html,
+ });
+};
diff --git a/apps/server/src/lib/collaborations.ts b/apps/server/src/lib/collaborations.ts
new file mode 100644
index 00000000..756d0827
--- /dev/null
+++ b/apps/server/src/lib/collaborations.ts
@@ -0,0 +1,138 @@
+import {
+ extractNodeCollaborators,
+ NodeAttributes,
+ NodeRole,
+} from '@colanode/core';
+import { Transaction } from 'kysely';
+
+import { DatabaseSchema, SelectCollaboration } from '@/data/schema';
+
+type CollaboratorChangeResult = {
+ addedCollaborators: Record<string, NodeRole>;
+ updatedCollaborators: Record<string, NodeRole>;
+ removedCollaborators: Record<string, NodeRole>;
+};
+
+export const checkCollaboratorChanges = (
+ beforeAttributes: NodeAttributes,
+ afterAttributes: NodeAttributes
+): CollaboratorChangeResult => {
+ const beforeCollaborators = extractNodeCollaborators(beforeAttributes);
+ const afterCollaborators = extractNodeCollaborators(afterAttributes);
+
+ const addedCollaborators: Record<string, NodeRole> = {};
+ const updatedCollaborators: Record<string, NodeRole> = {};
+ const removedCollaborators: Record<string, NodeRole> = {};
+
+ // Check for added and updated collaborators
+ for (const [userId, newRole] of Object.entries(afterCollaborators)) {
+ if (!(userId in beforeCollaborators)) {
+ addedCollaborators[userId] = newRole;
+ } else if (beforeCollaborators[userId] !== newRole) {
+ updatedCollaborators[userId] = newRole;
+ }
+ }
+
+ // Check for removed collaborators
+ for (const [userId, oldRole] of Object.entries(beforeCollaborators)) {
+ if (!(userId in afterCollaborators)) {
+ removedCollaborators[userId] = oldRole;
+ }
+ }
+
+ return {
+ addedCollaborators,
+ updatedCollaborators,
+ removedCollaborators,
+ };
+};
+
+export const applyCollaboratorUpdates = async (
+ transaction: Transaction<DatabaseSchema>,
+ nodeId: string,
+ userId: string,
+ workspaceId: string,
+ updateResult: CollaboratorChangeResult
+) => {
+ const createdCollaborations: SelectCollaboration[] = [];
+ const updatedCollaborations: SelectCollaboration[] = [];
+
+ for (const [collaboratorId, role] of Object.entries(
+ updateResult.addedCollaborators
+ )) {
+ const createdCollaboration = await transaction
+ .insertInto('collaborations')
+ .returningAll()
+ .values({
+ collaborator_id: collaboratorId,
+ node_id: nodeId,
+ workspace_id: workspaceId,
+ role,
+ created_at: new Date(),
+ created_by: userId,
+ })
+ .onConflict((oc) =>
+ oc.columns(['collaborator_id', 'node_id']).doUpdateSet({
+ role,
+ updated_at: new Date(),
+ updated_by: userId,
+ deleted_at: null,
+ deleted_by: null,
+ })
+ )
+ .executeTakeFirst();
+
+ if (!createdCollaboration) {
+ throw new Error('Failed to create collaboration');
+ }
+
+ createdCollaborations.push(createdCollaboration);
+ }
+
+ for (const [collaboratorId, role] of Object.entries(
+ updateResult.updatedCollaborators
+ )) {
+ const updatedCollaboration = await transaction
+ .updateTable('collaborations')
+ .returningAll()
+ .set({
+ role,
+ updated_at: new Date(),
+ updated_by: userId,
+ deleted_at: null,
+ deleted_by: null,
+ })
+ .where('collaborator_id', '=', collaboratorId)
+ .where('node_id', '=', nodeId)
+ .executeTakeFirst();
+
+ if (!updatedCollaboration) {
+ throw new Error('Failed to update collaboration');
+ }
+
+ updatedCollaborations.push(updatedCollaboration);
+ }
+
+ const removedCollaboratorIds = Object.keys(updateResult.removedCollaborators);
+
+ if (removedCollaboratorIds.length > 0) {
+ const removedCollaborations = await transaction
+ .updateTable('collaborations')
+ .returningAll()
+ .set({
+ deleted_at: new Date(),
+ deleted_by: userId,
+ })
+ .where('collaborator_id', 'in', removedCollaboratorIds)
+ .where('node_id', '=', nodeId)
+ .execute();
+
+ if (removedCollaborations.length !== removedCollaboratorIds.length) {
+ throw new Error('Failed to remove collaborations');
+ }
+
+ updatedCollaborations.push(...removedCollaborations);
+ }
+
+ return { createdCollaborations, updatedCollaborations };
+};
diff --git a/apps/server/src/lib/entries.ts b/apps/server/src/lib/entries.ts
deleted file mode 100644
index cbaa5954..00000000
--- a/apps/server/src/lib/entries.ts
+++ /dev/null
@@ -1,74 +0,0 @@
-import { Entry, EntryOutput, EntryType } from '@colanode/core';
-
-import { database } from '@/data/database';
-import { SelectEntry } from '@/data/schema';
-
-export const mapEntryOutput = (entry: SelectEntry): EntryOutput => {
- return {
- id: entry.id,
- parentId: entry.parent_id,
- workspaceId: entry.workspace_id,
- type: entry.type,
- attributes: entry.attributes,
- state: '',
- createdAt: entry.created_at.toISOString(),
- createdBy: entry.created_by,
- transactionId: entry.transaction_id,
- updatedAt: entry.updated_at?.toISOString() ?? null,
- updatedBy: entry.updated_by ?? null,
- };
-};
-
-export const mapEntry = (entry: SelectEntry): Entry => {
- return {
- id: entry.id,
- parentId: entry.parent_id,
- rootId: entry.root_id,
- type: entry.type as EntryType,
- attributes: entry.attributes,
- createdAt: entry.created_at.toISOString(),
- createdBy: entry.created_by,
- updatedAt: entry.updated_at?.toISOString() ?? null,
- updatedBy: entry.updated_by ?? null,
- transactionId: entry.transaction_id,
- } as Entry;
-};
-
-export const fetchEntry = async (
- entryId: string
-): Promise<SelectEntry | null> => {
- const result = await database
- .selectFrom('entries')
- .selectAll()
- .where('id', '=', entryId)
- .executeTakeFirst();
-
- return result ?? null;
-};
-
-export const fetchEntryAncestors = async (
- entryId: string
-): Promise<SelectEntry[]> => {
- const result = await database
- .selectFrom('entries')
- .selectAll()
- .innerJoin('entry_paths', 'entries.id', 'entry_paths.ancestor_id')
- .where('entry_paths.descendant_id', '=', entryId)
- .orderBy('entry_paths.level', 'desc')
- .execute();
-
- return result;
-};
-
-export const fetchEntryDescendants = async (
- entryId: string
-): Promise<string[]> => {
- const result = await database
- .selectFrom('entry_paths')
- .select('descendant_id')
- .where('ancestor_id', '=', entryId)
- .orderBy('level', 'asc')
- .execute();
-
- return result.map((row) => row.descendant_id);
-};
diff --git a/apps/server/src/lib/node-interactions.ts b/apps/server/src/lib/node-interactions.ts
new file mode 100644
index 00000000..53271aae
--- /dev/null
+++ b/apps/server/src/lib/node-interactions.ts
@@ -0,0 +1,173 @@
+import {
+ extractNodeRole,
+ hasNodeRole,
+ MarkNodeOpenedMutation,
+ MarkNodeSeenMutation,
+} from '@colanode/core';
+
+import { database } from '@/data/database';
+import { SelectUser } from '@/data/schema';
+import { mapNode } from '@/lib/nodes';
+import { eventBus } from '@/lib/event-bus';
+
+export const markNodeAsSeen = async (
+ user: SelectUser,
+ mutation: MarkNodeSeenMutation
+): Promise<boolean> => {
+ const node = await database
+ .selectFrom('nodes')
+ .select(['id', 'root_id', 'workspace_id'])
+ .where('id', '=', mutation.data.nodeId)
+ .executeTakeFirst();
+
+ if (!node) {
+ return false;
+ }
+
+ const root = await database
+ .selectFrom('nodes')
+ .selectAll()
+ .where('id', '=', node.root_id)
+ .executeTakeFirst();
+
+ if (!root) {
+ return false;
+ }
+
+ const rootNode = mapNode(root);
+ const role = extractNodeRole(rootNode, user.id);
+ if (!role || !hasNodeRole(role, 'viewer')) {
+ return false;
+ }
+
+ const existingInteraction = await database
+ .selectFrom('node_interactions')
+ .selectAll()
+ .where('node_id', '=', mutation.data.nodeId)
+ .where('collaborator_id', '=', user.id)
+ .executeTakeFirst();
+
+ if (
+ existingInteraction &&
+ existingInteraction.last_seen_at !== null &&
+ existingInteraction.last_seen_at <= new Date(mutation.data.seenAt)
+ ) {
+ return true;
+ }
+
+ const lastSeenAt = new Date(mutation.data.seenAt);
+ const firstSeenAt = existingInteraction?.first_seen_at ?? lastSeenAt;
+ const createdInteraction = await database
+ .insertInto('node_interactions')
+ .returningAll()
+ .values({
+ node_id: mutation.data.nodeId,
+ collaborator_id: user.id,
+ first_seen_at: firstSeenAt,
+ last_seen_at: lastSeenAt,
+ root_id: root.id,
+ workspace_id: root.workspace_id,
+ })
+ .onConflict((b) =>
+ b.columns(['node_id', 'collaborator_id']).doUpdateSet({
+ last_seen_at: lastSeenAt,
+ first_seen_at: firstSeenAt,
+ })
+ )
+ .executeTakeFirst();
+
+ if (!createdInteraction) {
+ return false;
+ }
+
+ eventBus.publish({
+ type: 'node_interaction_updated',
+ nodeId: createdInteraction.node_id,
+ collaboratorId: createdInteraction.collaborator_id,
+ rootId: createdInteraction.root_id,
+ workspaceId: createdInteraction.workspace_id,
+ });
+
+ return true;
+};
+
+export const markNodeAsOpened = async (
+ user: SelectUser,
+ mutation: MarkNodeOpenedMutation
+): Promise<boolean> => {
+ const node = await database
+ .selectFrom('nodes')
+ .select(['id', 'root_id', 'workspace_id'])
+ .where('id', '=', mutation.data.nodeId)
+ .executeTakeFirst();
+
+ if (!node) {
+ return false;
+ }
+
+ const root = await database
+ .selectFrom('nodes')
+ .selectAll()
+ .where('id', '=', node.root_id)
+ .executeTakeFirst();
+
+ if (!root) {
+ return false;
+ }
+
+ const rootNode = mapNode(root);
+ const role = extractNodeRole(rootNode, user.id);
+ if (!role || !hasNodeRole(role, 'viewer')) {
+ return false;
+ }
+
+ const existingInteraction = await database
+ .selectFrom('node_interactions')
+ .selectAll()
+ .where('node_id', '=', mutation.data.nodeId)
+ .where('collaborator_id', '=', user.id)
+ .executeTakeFirst();
+
+ if (
+ existingInteraction &&
+ existingInteraction.last_opened_at !== null &&
+ existingInteraction.last_opened_at <= new Date(mutation.data.openedAt)
+ ) {
+ return true;
+ }
+
+ const lastOpenedAt = new Date(mutation.data.openedAt);
+ const firstOpenedAt = existingInteraction?.first_opened_at ?? lastOpenedAt;
+ const createdInteraction = await database
+ .insertInto('node_interactions')
+ .returningAll()
+ .values({
+ node_id: mutation.data.nodeId,
+ collaborator_id: user.id,
+ first_opened_at: firstOpenedAt,
+ last_opened_at: lastOpenedAt,
+ root_id: root.id,
+ workspace_id: root.workspace_id,
+ })
+ .onConflict((b) =>
+ b.columns(['node_id', 'collaborator_id']).doUpdateSet({
+ last_opened_at: lastOpenedAt,
+ first_opened_at: firstOpenedAt,
+ })
+ )
+ .executeTakeFirst();
+
+ if (!createdInteraction) {
+ return false;
+ }
+
+ eventBus.publish({
+ type: 'node_interaction_updated',
+ nodeId: createdInteraction.node_id,
+ collaboratorId: createdInteraction.collaborator_id,
+ rootId: createdInteraction.root_id,
+ workspaceId: createdInteraction.workspace_id,
+ });
+
+ return true;
+};
diff --git a/apps/server/src/lib/node-reactions.ts b/apps/server/src/lib/node-reactions.ts
new file mode 100644
index 00000000..a2187a65
--- /dev/null
+++ b/apps/server/src/lib/node-reactions.ts
@@ -0,0 +1,144 @@
+import {
+ canCreateNodeReaction,
+ canDeleteNodeReaction,
+ CreateNodeReactionMutation,
+ DeleteNodeReactionMutation,
+} from '@colanode/core';
+
+import { eventBus } from '@/lib/event-bus';
+import { database } from '@/data/database';
+import { SelectUser } from '@/data/schema';
+import { mapNode } from '@/lib/nodes';
+
+export const createNodeReaction = async (
+ user: SelectUser,
+ mutation: CreateNodeReactionMutation
+): Promise<boolean> => {
+ const node = await database
+ .selectFrom('nodes')
+ .selectAll()
+ .where('id', '=', mutation.data.nodeId)
+ .executeTakeFirst();
+
+ if (!node) {
+ return false;
+ }
+
+ const root = await database
+ .selectFrom('nodes')
+ .selectAll()
+ .where('id', '=', node.root_id)
+ .executeTakeFirst();
+
+ if (!root) {
+ return false;
+ }
+
+ if (
+ !canCreateNodeReaction({
+ user: {
+ userId: user.id,
+ role: user.role,
+ },
+ root: mapNode(root),
+ node: mapNode(node),
+ })
+ ) {
+ return false;
+ }
+
+ const createdNodeReaction = await database
+ .insertInto('node_reactions')
+ .returningAll()
+ .values({
+ node_id: mutation.data.nodeId,
+ collaborator_id: user.id,
+ reaction: mutation.data.reaction,
+ workspace_id: root.workspace_id,
+ root_id: root.id,
+ created_at: new Date(mutation.data.createdAt),
+ })
+ .onConflict((b) =>
+ b.columns(['node_id', 'collaborator_id', 'reaction']).doUpdateSet({
+ created_at: new Date(mutation.data.createdAt),
+ deleted_at: null,
+ })
+ )
+ .executeTakeFirst();
+
+ if (!createdNodeReaction) {
+ return false;
+ }
+
+ eventBus.publish({
+ type: 'node_reaction_created',
+ nodeId: createdNodeReaction.node_id,
+ collaboratorId: createdNodeReaction.collaborator_id,
+ rootId: createdNodeReaction.root_id,
+ workspaceId: createdNodeReaction.workspace_id,
+ });
+
+ return true;
+};
+
+export const deleteNodeReaction = async (
+ user: SelectUser,
+ mutation: DeleteNodeReactionMutation
+): Promise<boolean> => {
+ const node = await database
+ .selectFrom('nodes')
+ .selectAll()
+ .where('id', '=', mutation.data.nodeId)
+ .executeTakeFirst();
+
+ if (!node) {
+ return false;
+ }
+
+ const root = await database
+ .selectFrom('nodes')
+ .selectAll()
+ .where('id', '=', node.root_id)
+ .executeTakeFirst();
+
+ if (!root) {
+ return false;
+ }
+
+ if (
+ !canDeleteNodeReaction({
+ user: {
+ userId: user.id,
+ role: user.role,
+ },
+ root: mapNode(root),
+ node: mapNode(node),
+ })
+ ) {
+ return false;
+ }
+
+ const deletedNodeReaction = await database
+ .updateTable('node_reactions')
+ .set({
+ deleted_at: new Date(mutation.data.deletedAt),
+ })
+ .where('node_id', '=', mutation.data.nodeId)
+ .where('collaborator_id', '=', user.id)
+ .where('reaction', '=', mutation.data.reaction)
+ .executeTakeFirst();
+
+ if (!deletedNodeReaction) {
+ return false;
+ }
+
+ eventBus.publish({
+ type: 'node_reaction_deleted',
+ nodeId: mutation.data.nodeId,
+ collaboratorId: user.id,
+ rootId: node.root_id,
+ workspaceId: node.workspace_id,
+ });
+
+ return true;
+};
diff --git a/apps/server/src/lib/nodes.ts b/apps/server/src/lib/nodes.ts
new file mode 100644
index 00000000..6b3ba80f
--- /dev/null
+++ b/apps/server/src/lib/nodes.ts
@@ -0,0 +1,671 @@
+import {
+ canCreateNode,
+ canDeleteNode,
+ canUpdateNode,
+ createDebugger,
+ extractNodeCollaborators,
+ Node,
+ NodeAttributes,
+ nodeAttributesSchema,
+ TransactionOperation,
+} from '@colanode/core';
+import { YDoc } from '@colanode/crdt';
+import { cloneDeep } from 'lodash-es';
+
+import { database } from '@/data/database';
+import {
+ CreateCollaboration,
+ CreateNode,
+ SelectNode,
+ SelectUser,
+} from '@/data/schema';
+import {
+ ApplyNodeTransactionInput,
+ ApplyNodeTransactionOutput,
+ CreateNodeInput,
+ CreateNodeOutput,
+ DeleteNodeInput,
+ DeleteNodeOutput,
+ UpdateNodeInput,
+ UpdateNodeOutput,
+} from '@/types/nodes';
+import { eventBus } from '@/lib/event-bus';
+import {
+ applyCollaboratorUpdates,
+ checkCollaboratorChanges,
+} from '@/lib/collaborations';
+import { jobService } from '@/services/job-service';
+
+const debug = createDebugger('server:lib:nodes');
+
+const UPDATE_RETRIES_LIMIT = 10;
+
+type UpdateResult<T> = {
+ type: 'success' | 'error' | 'retry';
+ output: T | null;
+};
+
+export const mapNode = (node: SelectNode): Node => {
+ return {
+ id: node.id,
+ parentId: node.parent_id,
+ rootId: node.root_id,
+ type: node.type,
+ attributes: node.attributes,
+ createdAt: node.created_at.toISOString(),
+ createdBy: node.created_by,
+ updatedAt: node.updated_at?.toISOString() ?? null,
+ updatedBy: node.updated_by ?? null,
+ } as Node;
+};
+
+export const fetchNode = async (nodeId: string): Promise<SelectNode | null> => {
+ const result = await database
+ .selectFrom('nodes')
+ .selectAll()
+ .where('id', '=', nodeId)
+ .executeTakeFirst();
+
+ return result ?? null;
+};
+
+export const fetchNodeAncestors = async (
+ nodeId: string
+): Promise<SelectNode[]> => {
+ const result = await database
+ .selectFrom('nodes')
+ .selectAll()
+ .innerJoin('node_paths', 'nodes.id', 'node_paths.ancestor_id')
+ .where('node_paths.descendant_id', '=', nodeId)
+ .orderBy('node_paths.level', 'desc')
+ .execute();
+
+ return result;
+};
+
+export const fetchNodeDescendants = async (
+ nodeId: string
+): Promise<string[]> => {
+ const result = await database
+ .selectFrom('node_paths')
+ .select('descendant_id')
+ .where('ancestor_id', '=', nodeId)
+ .orderBy('level', 'asc')
+ .execute();
+
+ return result.map((row) => row.descendant_id);
+};
+
+export const createNode = async (
+ input: CreateNodeInput
+): Promise<CreateNodeOutput | null> => {
+ const ydoc = new YDoc();
+ const update = ydoc.updateAttributes(nodeAttributesSchema, input.attributes);
+
+ if (!update) {
+ return null;
+ }
+
+ const attributes = ydoc.getAttributes<NodeAttributes>();
+ const attributesJson = JSON.stringify(attributes);
+ const state = ydoc.getState();
+ const date = new Date();
+
+ const createNode: CreateNode = {
+ id: input.nodeId,
+ root_id: input.rootId,
+ workspace_id: input.workspaceId,
+ attributes: attributesJson,
+ created_at: date,
+ created_by: input.userId,
+ state: state,
+ };
+
+ const collaborationsToCreate: CreateCollaboration[] = Object.entries(
+ extractNodeCollaborators(attributes)
+ ).map(([userId, role]) => ({
+ collaborator_id: userId,
+ node_id: input.nodeId,
+ workspace_id: input.workspaceId,
+ role,
+ created_at: new Date(),
+ created_by: input.userId,
+ }));
+
+ try {
+ const { createdNode, createdCollaborations } = await database
+ .transaction()
+ .execute(async (trx) => {
+ const createdNode = await trx
+ .insertInto('nodes')
+ .returningAll()
+ .values(createNode)
+ .executeTakeFirst();
+
+ if (!createdNode) {
+ throw new Error('Failed to create node');
+ }
+
+ if (collaborationsToCreate.length > 0) {
+ const createdCollaborations = await trx
+ .insertInto('collaborations')
+ .returningAll()
+ .values(collaborationsToCreate)
+ .execute();
+
+ return { createdNode, createdCollaborations };
+ }
+
+ return { createdNode, createdCollaborations: [] };
+ });
+
+ eventBus.publish({
+ type: 'node_created',
+ nodeId: input.nodeId,
+ rootId: input.rootId,
+ workspaceId: input.workspaceId,
+ });
+
+ for (const createdCollaboration of createdCollaborations) {
+ eventBus.publish({
+ type: 'collaboration_created',
+ collaboratorId: createdCollaboration.collaborator_id,
+ nodeId: input.nodeId,
+ workspaceId: input.workspaceId,
+ });
+ }
+
+ return {
+ node: createdNode,
+ };
+ } catch (error) {
+ debug(`Failed to create node transaction: ${error}`);
+ return null;
+ }
+};
+
+export const updateNode = async (
+ input: UpdateNodeInput
+): Promise<UpdateNodeOutput | null> => {
+ for (let count = 0; count < UPDATE_RETRIES_LIMIT; count++) {
+ const result = await tryUpdateNode(input);
+
+ if (result.type === 'success') {
+ return result.output;
+ }
+
+ if (result.type === 'error') {
+ return null;
+ }
+ }
+
+ return null;
+};
+
+export const tryUpdateNode = async (
+ input: UpdateNodeInput
+): Promise<UpdateResult<UpdateNodeOutput>> => {
+ const node = await fetchNode(input.nodeId);
+ if (!node) {
+ return { type: 'error', output: null };
+ }
+
+ const ydoc = new YDoc(node.state);
+ const currentAttributes = ydoc.getAttributes<NodeAttributes>();
+ const updatedAttributes = input.updater(cloneDeep(currentAttributes));
+ if (!updatedAttributes) {
+ return { type: 'error', output: null };
+ }
+
+ const update = ydoc.updateAttributes(nodeAttributesSchema, updatedAttributes);
+
+ if (!update) {
+ return { type: 'success', output: null };
+ }
+
+ const attributes = ydoc.getAttributes<NodeAttributes>();
+ const attributesJson = JSON.stringify(attributes);
+
+ const date = new Date();
+ const state = ydoc.getState();
+
+ const collaboratorChanges = checkCollaboratorChanges(
+ node.attributes,
+ attributes
+ );
+
+ try {
+ const { updatedNode, createdCollaborations, updatedCollaborations } =
+ await database.transaction().execute(async (trx) => {
+ const updatedNode = await trx
+ .updateTable('nodes')
+ .returningAll()
+ .set({
+ attributes: attributesJson,
+ updated_at: date,
+ updated_by: input.userId,
+ state: state,
+ })
+ .where('id', '=', input.nodeId)
+ .where('revision', '=', node.revision)
+ .executeTakeFirst();
+
+ if (!updatedNode) {
+ throw new Error('Failed to update node');
+ }
+
+ const { createdCollaborations, updatedCollaborations } =
+ await applyCollaboratorUpdates(
+ trx,
+ input.nodeId,
+ input.userId,
+ input.workspaceId,
+ collaboratorChanges
+ );
+
+ return {
+ updatedNode,
+ createdCollaborations,
+ updatedCollaborations,
+ };
+ });
+
+ eventBus.publish({
+ type: 'node_updated',
+ nodeId: input.nodeId,
+ rootId: node.root_id,
+ workspaceId: input.workspaceId,
+ });
+
+ for (const createdCollaboration of createdCollaborations) {
+ eventBus.publish({
+ type: 'collaboration_created',
+ collaboratorId: createdCollaboration.collaborator_id,
+ nodeId: input.nodeId,
+ workspaceId: input.workspaceId,
+ });
+ }
+
+ for (const updatedCollaboration of updatedCollaborations) {
+ eventBus.publish({
+ type: 'collaboration_updated',
+ collaboratorId: updatedCollaboration.collaborator_id,
+ nodeId: input.nodeId,
+ workspaceId: input.workspaceId,
+ });
+ }
+
+ return {
+ type: 'success',
+ output: {
+ node: updatedNode,
+ },
+ };
+ } catch {
+ return { type: 'retry', output: null };
+ }
+};
+
+export const applyNodeTransaction = async (
+ user: SelectUser,
+ input: ApplyNodeTransactionInput
+): Promise<ApplyNodeTransactionOutput | null> => {
+ if (input.operation === TransactionOperation.Create) {
+ return applyNodeCreateTransaction(user, input);
+ }
+
+ if (input.operation === TransactionOperation.Update) {
+ return applyNodeUpdateTransaction(user, input);
+ }
+
+ return null;
+};
+
+const applyNodeCreateTransaction = async (
+ user: SelectUser,
+ input: ApplyNodeTransactionInput
+): Promise<ApplyNodeTransactionOutput | null> => {
+ const ydoc = new YDoc();
+ ydoc.applyUpdate(input.data);
+
+ const attributes = ydoc.getAttributes<NodeAttributes>();
+ let root: SelectNode | null = null;
+
+ if (attributes.type !== 'space' && attributes.type !== 'chat') {
+ const parent = await fetchNode(attributes.parentId);
+ if (!parent) {
+ return null;
+ }
+
+ root = await fetchNode(parent.root_id);
+ }
+
+ if (
+ !canCreateNode(
+ {
+ user: {
+ userId: user.id,
+ role: user.role,
+ },
+ root: root ? mapNode(root) : null,
+ },
+ attributes.type
+ )
+ ) {
+ return null;
+ }
+
+ const createNode: CreateNode = {
+ id: input.nodeId,
+ root_id: root?.id ?? input.nodeId,
+ attributes: JSON.stringify(attributes),
+ workspace_id: user.workspace_id,
+ created_at: input.createdAt,
+ created_by: user.id,
+ state: ydoc.getState(),
+ };
+
+ const collaborationsToCreate: CreateCollaboration[] = Object.entries(
+ extractNodeCollaborators(attributes)
+ ).map(([userId, role]) => ({
+ collaborator_id: userId,
+ node_id: input.nodeId,
+ workspace_id: user.workspace_id,
+ role,
+ created_at: new Date(),
+ created_by: user.id,
+ }));
+
+ try {
+ const { createdNode, createdCollaborations } = await database
+ .transaction()
+ .execute(async (trx) => {
+ const createdNode = await trx
+ .insertInto('nodes')
+ .returningAll()
+ .values(createNode)
+ .executeTakeFirst();
+
+ if (!createdNode) {
+ throw new Error('Failed to create node');
+ }
+
+ if (collaborationsToCreate.length > 0) {
+ const createdCollaborations = await trx
+ .insertInto('collaborations')
+ .returningAll()
+ .values(collaborationsToCreate)
+ .execute();
+
+ return { createdNode, createdCollaborations };
+ }
+
+ return { createdNode, createdCollaborations: [] };
+ });
+
+ eventBus.publish({
+ type: 'node_created',
+ nodeId: input.nodeId,
+ rootId: root?.id ?? input.nodeId,
+ workspaceId: user.workspace_id,
+ });
+
+ for (const createdCollaboration of createdCollaborations) {
+ eventBus.publish({
+ type: 'collaboration_created',
+ collaboratorId: createdCollaboration.collaborator_id,
+ nodeId: input.nodeId,
+ workspaceId: user.workspace_id,
+ });
+ }
+
+ return {
+ node: createdNode,
+ };
+ } catch (error) {
+ debug(`Failed to create node transaction: ${error}`);
+ return null;
+ }
+};
+
+const applyNodeUpdateTransaction = async (
+ user: SelectUser,
+ input: ApplyNodeTransactionInput
+): Promise<ApplyNodeTransactionOutput | null> => {
+ for (let count = 0; count < UPDATE_RETRIES_LIMIT; count++) {
+ const result = await tryApplyNodeUpdateTransaction(user, input);
+
+ if (result.type === 'success') {
+ return result.output;
+ }
+
+ if (result.type === 'error') {
+ return null;
+ }
+ }
+
+ return null;
+};
+
+const tryApplyNodeUpdateTransaction = async (
+ user: SelectUser,
+ input: ApplyNodeTransactionInput
+): Promise<UpdateResult<ApplyNodeTransactionOutput>> => {
+ const node = await fetchNode(input.nodeId);
+ if (!node) {
+ return { type: 'error', output: null };
+ }
+
+ const root = await fetchNode(node.root_id);
+ if (!root) {
+ return { type: 'error', output: null };
+ }
+
+ const ydoc = new YDoc(node.state);
+ ydoc.applyUpdate(input.data);
+
+ const attributes = ydoc.getAttributes<NodeAttributes>();
+ const attributesJson = JSON.stringify(attributes);
+
+ if (
+ !canUpdateNode(
+ {
+ user: {
+ userId: user.id,
+ role: user.role,
+ },
+ root: mapNode(root),
+ node: mapNode(node),
+ },
+ attributes
+ )
+ ) {
+ return { type: 'error', output: null };
+ }
+
+ const collaboratorChanges = checkCollaboratorChanges(
+ node.attributes,
+ attributes
+ );
+
+ try {
+ const { updatedNode, createdCollaborations, updatedCollaborations } =
+ await database.transaction().execute(async (trx) => {
+ const updatedNode = await trx
+ .updateTable('nodes')
+ .returningAll()
+ .set({
+ attributes: attributesJson,
+ updated_at: input.createdAt,
+ updated_by: user.id,
+ state: ydoc.getState(),
+ })
+ .where('id', '=', input.nodeId)
+ .where('revision', '=', node.revision)
+ .executeTakeFirst();
+
+ if (!updatedNode) {
+ throw new Error('Failed to update node');
+ }
+
+ const { createdCollaborations, updatedCollaborations } =
+ await applyCollaboratorUpdates(
+ trx,
+ input.nodeId,
+ user.id,
+ user.workspace_id,
+ collaboratorChanges
+ );
+
+ return {
+ updatedNode,
+ createdCollaborations,
+ updatedCollaborations,
+ };
+ });
+
+ eventBus.publish({
+ type: 'node_updated',
+ nodeId: input.nodeId,
+ rootId: root.id,
+ workspaceId: user.workspace_id,
+ });
+
+ for (const createdCollaboration of createdCollaborations) {
+ eventBus.publish({
+ type: 'collaboration_created',
+ collaboratorId: createdCollaboration.collaborator_id,
+ nodeId: input.nodeId,
+ workspaceId: user.workspace_id,
+ });
+ }
+
+ for (const updatedCollaboration of updatedCollaborations) {
+ eventBus.publish({
+ type: 'collaboration_updated',
+ collaboratorId: updatedCollaboration.collaborator_id,
+ nodeId: input.nodeId,
+ workspaceId: user.workspace_id,
+ });
+ }
+
+ return {
+ type: 'success',
+ output: {
+ node: updatedNode,
+ },
+ };
+ } catch {
+ return { type: 'retry', output: null };
+ }
+};
+
+export const deleteNode = async (
+ user: SelectUser,
+ input: DeleteNodeInput
+): Promise<DeleteNodeOutput | null> => {
+ const node = await fetchNode(input.id);
+ if (!node) {
+ return null;
+ }
+
+ const root = await fetchNode(node.root_id);
+ if (!root) {
+ return null;
+ }
+
+ if (
+ !canDeleteNode({
+ user: {
+ userId: user.id,
+ role: user.role,
+ },
+ root: mapNode(root),
+ node: mapNode(node),
+ })
+ ) {
+ return null;
+ }
+
+ const { deletedNode, updatedCollaborations } = await database
+ .transaction()
+ .execute(async (trx) => {
+ const deletedNode = await trx
+ .deleteFrom('nodes')
+ .returningAll()
+ .where('id', '=', input.id)
+ .executeTakeFirst();
+
+ if (!deletedNode) {
+ throw new Error('Failed to delete node');
+ }
+
+ const createdTombstone = await trx
+ .insertInto('node_tombstones')
+ .returningAll()
+ .values({
+ id: node.id,
+ root_id: node.root_id,
+ workspace_id: node.workspace_id,
+ deleted_at: new Date(input.deletedAt),
+ deleted_by: user.id,
+ })
+ .executeTakeFirst();
+
+ if (!createdTombstone) {
+ throw new Error('Failed to create tombstone');
+ }
+
+ await trx
+ .deleteFrom('node_reactions')
+ .where('node_id', '=', input.id)
+ .execute();
+
+ await trx
+ .deleteFrom('node_interactions')
+ .where('node_id', '=', input.id)
+ .execute();
+
+ const updatedCollaborations = await trx
+ .updateTable('collaborations')
+ .set({
+ deleted_at: new Date(),
+ deleted_by: user.id,
+ })
+ .returningAll()
+ .where('node_id', '=', input.id)
+ .execute();
+
+ return {
+ deletedNode,
+ updatedCollaborations,
+ };
+ });
+
+ eventBus.publish({
+ type: 'node_deleted',
+ nodeId: input.id,
+ rootId: node.root_id,
+ workspaceId: user.workspace_id,
+ });
+
+ for (const updatedCollaboration of updatedCollaborations) {
+ eventBus.publish({
+ type: 'collaboration_updated',
+ collaboratorId: updatedCollaboration.collaborator_id,
+ nodeId: input.id,
+ workspaceId: user.workspace_id,
+ });
+ }
+
+ await jobService.addJob({
+ type: 'clean_node_data',
+ nodeId: input.id,
+ workspaceId: user.workspace_id,
+ userId: user.id,
+ });
+
+ return {
+ node: deletedNode,
+ };
+};
diff --git a/apps/server/src/lib/otps.ts b/apps/server/src/lib/otps.ts
new file mode 100644
index 00000000..8503d4a6
--- /dev/null
+++ b/apps/server/src/lib/otps.ts
@@ -0,0 +1,48 @@
+import crypto from 'crypto';
+
+import { redis } from '@/data/redis';
+import { Otp } from '@/types/otps';
+
+const OTP_DIGITS = '0123456789';
+const OTP_LENGTH = 6;
+
+export const fetchOtp = async <T>(id: string): Promise<Otp<T> | null> => {
+ const redisKey = getOtpRedisKey(id);
+ const otpJson = await redis.get(redisKey);
+ if (!otpJson) {
+ return null;
+ }
+
+ return JSON.parse(otpJson);
+};
+
+export const saveOtp = async <T>(id: string, otp: Otp<T>): Promise<void> => {
+ const redisKey = getOtpRedisKey(id);
+ const expireSeconds = Math.max(
+ Math.floor((otp.expiresAt.getTime() - Date.now()) / 1000),
+ 1
+ );
+ await redis.set(redisKey, JSON.stringify(otp), {
+ EX: expireSeconds,
+ });
+};
+
+export const deleteOtp = async (id: string): Promise<void> => {
+ const redisKey = getOtpRedisKey(id);
+ await redis.del(redisKey);
+};
+
+export const getOtpRedisKey = (id: string): string => {
+ return `otp:${id}`;
+};
+
+export const generateOtpCode = async (): Promise<string> => {
+ let otp = '';
+
+ for (let i = 0; i < OTP_LENGTH; i++) {
+ const randomIndex = crypto.randomInt(0, OTP_DIGITS.length);
+ otp += OTP_DIGITS[randomIndex];
+ }
+
+ return otp;
+};
diff --git a/apps/server/src/lib/workspaces.ts b/apps/server/src/lib/workspaces.ts
new file mode 100644
index 00000000..21e858de
--- /dev/null
+++ b/apps/server/src/lib/workspaces.ts
@@ -0,0 +1,166 @@
+import {
+ IdType,
+ generateId,
+ WorkspaceCreateInput,
+ WorkspaceOutput,
+ WorkspaceStatus,
+ UserStatus,
+} from '@colanode/core';
+
+import { SelectAccount } from '@/data/schema';
+import { database } from '@/data/database';
+import { configuration } from '@/lib/configuration';
+import { eventBus } from '@/lib/event-bus';
+import {
+ generateWelcomePageBlocks,
+ generateInitialMessageBlocks,
+} from '@/lib/blocks';
+import { createNode } from '@/lib/nodes';
+
+export const createWorkspace = async (
+ account: SelectAccount,
+ input: WorkspaceCreateInput
+): Promise<WorkspaceOutput> => {
+ const date = new Date();
+ const workspaceId = generateId(IdType.Workspace);
+ const userId = generateId(IdType.User);
+ const spaceId = generateId(IdType.Space);
+
+ const workspace = await database
+ .insertInto('workspaces')
+ .values({
+ id: workspaceId,
+ name: input.name,
+ description: input.description,
+ avatar: input.avatar,
+ created_at: date,
+ created_by: account.id,
+ status: WorkspaceStatus.Active,
+ })
+ .returningAll()
+ .executeTakeFirst();
+
+ if (!workspace) {
+ throw new Error('Failed to create workspace.');
+ }
+
+ const user = await database
+ .insertInto('users')
+ .values({
+ id: userId,
+ account_id: account.id,
+ workspace_id: workspaceId,
+ role: 'owner',
+ name: account.name,
+ email: account.email,
+ avatar: account.avatar,
+ storage_limit: configuration.user.storageLimit,
+ max_file_size: configuration.user.maxFileSize,
+ created_at: date,
+ created_by: account.id,
+ status: UserStatus.Active,
+ })
+ .returningAll()
+ .executeTakeFirst();
+
+ if (!user) {
+ throw new Error('Failed to create workspace user.');
+ }
+
+ const createSpaceOutput = await createNode({
+ nodeId: spaceId,
+ rootId: spaceId,
+ attributes: {
+ type: 'space',
+ name: 'Home',
+ description: 'This is your home space.',
+ visibility: 'private',
+ collaborators: {
+ [userId]: 'admin',
+ },
+ },
+ userId: userId,
+ workspaceId: workspaceId,
+ });
+
+ if (createSpaceOutput) {
+ const pageId = generateId(IdType.Page);
+ await createNode({
+ nodeId: pageId,
+ rootId: spaceId,
+ attributes: {
+ type: 'page',
+ name: 'Welcome',
+ parentId: spaceId,
+ content: generateWelcomePageBlocks(pageId),
+ },
+ userId: userId,
+ workspaceId: workspaceId,
+ });
+
+ const channelId = generateId(IdType.Channel);
+ await createNode({
+ nodeId: channelId,
+ rootId: spaceId,
+ attributes: {
+ type: 'channel',
+ name: 'Discussions',
+ parentId: spaceId,
+ },
+ userId: userId,
+ workspaceId: workspaceId,
+ });
+
+ const messageId = generateId(IdType.Message);
+ await createNode({
+ nodeId: messageId,
+ rootId: spaceId,
+ attributes: {
+ type: 'message',
+ parentId: channelId,
+ subtype: 'standard',
+ content: generateInitialMessageBlocks(messageId),
+ },
+ userId: userId,
+ workspaceId: workspaceId,
+ });
+ }
+
+ eventBus.publish({
+ type: 'workspace_created',
+ workspaceId: workspaceId,
+ });
+
+ eventBus.publish({
+ type: 'user_created',
+ userId: userId,
+ workspaceId: workspaceId,
+ accountId: account.id,
+ });
+
+ return {
+ id: workspace.id,
+ name: workspace.name,
+ description: workspace.description,
+ avatar: workspace.avatar,
+ user: {
+ id: user.id,
+ accountId: user.account_id,
+ role: user.role,
+ storageLimit: user.storage_limit,
+ maxFileSize: user.max_file_size,
+ },
+ };
+};
+
+export const createDefaultWorkspace = async (
+ account: SelectAccount
+): Promise<WorkspaceOutput> => {
+ const input: WorkspaceCreateInput = {
+ name: `${account.name}'s Workspace`,
+ description: 'This is your personal workspace.',
+ avatar: '',
+ };
+
+ return createWorkspace(account, input);
+};
diff --git a/apps/server/src/services/account-service.ts b/apps/server/src/services/account-service.ts
deleted file mode 100644
index cc81b53e..00000000
--- a/apps/server/src/services/account-service.ts
+++ /dev/null
@@ -1,250 +0,0 @@
-import {
- generateId,
- IdType,
- LoginSuccessOutput,
- LoginVerifyOutput,
- UserStatus,
- WorkspaceOutput,
- WorkspaceRole,
-} from '@colanode/core';
-
-import crypto from 'crypto';
-
-import { SelectAccount } from '@/data/schema';
-import { database } from '@/data/database';
-import { workspaceService } from '@/services/workspace-service';
-import { generateToken } from '@/lib/tokens';
-import { configuration } from '@/lib/configuration';
-import { OtpCodeData } from '@/types/api';
-import { redis } from '@/data/redis';
-import { jobService } from '@/services/job-service';
-import { emailVerifyTemplate } from '@/templates';
-import { emailService } from '@/services/email-service';
-
-const OTP_DIGITS = '0123456789';
-const OTP_LENGTH = 6;
-
-interface DeviceMetadata {
- ip: string | undefined;
- platform: string;
- version: string;
-}
-
-class AccountService {
- public async buildLoginSuccessOutput(
- account: SelectAccount,
- metadata: DeviceMetadata
- ): Promise<LoginSuccessOutput> {
- const users = await database
- .selectFrom('users')
- .where('account_id', '=', account.id)
- .where('status', '=', UserStatus.Active)
- .where('role', '!=', 'none')
- .selectAll()
- .execute();
-
- const workspaceOutputs: WorkspaceOutput[] = [];
- if (users.length > 0) {
- const workspaceIds = users.map((u) => u.workspace_id);
- const workspaces = await database
- .selectFrom('workspaces')
- .where('id', 'in', workspaceIds)
- .selectAll()
- .execute();
-
- for (const user of users) {
- const workspace = workspaces.find((w) => w.id === user.workspace_id);
-
- if (!workspace) {
- continue;
- }
-
- workspaceOutputs.push({
- id: workspace.id,
- name: workspace.name,
- avatar: workspace.avatar,
- description: workspace.description,
- user: {
- id: user.id,
- accountId: user.account_id,
- role: user.role as WorkspaceRole,
- storageLimit: user.storage_limit,
- maxFileSize: user.max_file_size,
- },
- });
- }
- }
-
- if (workspaceOutputs.length === 0) {
- const workspace = await workspaceService.createDefaultWorkspace(account);
- workspaceOutputs.push(workspace);
- }
-
- const deviceId = generateId(IdType.Device);
- const { token, salt, hash } = generateToken(deviceId);
-
- const device = await database
- .insertInto('devices')
- .values({
- id: deviceId,
- account_id: account.id,
- token_hash: hash,
- token_salt: salt,
- token_generated_at: new Date(),
- type: 1,
- ip: metadata.ip,
- platform: metadata.platform,
- version: metadata.version,
- created_at: new Date(),
- })
- .returningAll()
- .executeTakeFirst();
-
- if (!device) {
- throw new Error('Failed to create device.');
- }
-
- return {
- type: 'success',
- account: {
- id: account.id,
- name: account.name,
- email: account.email,
- avatar: account.avatar,
- },
- workspaces: workspaceOutputs,
- deviceId: device.id,
- token,
- };
- }
-
- public async buildLoginVerifyOutput(
- account: SelectAccount
- ): Promise<LoginVerifyOutput> {
- const id = generateId(IdType.OtpCode);
- const expiresAt = new Date(
- Date.now() + configuration.account.otpTimeout * 1000
- );
- const otp = await this.generateOtpCode();
-
- const otpData: OtpCodeData = {
- id,
- expiresAt,
- accountId: account.id,
- otp,
- attempts: 0,
- };
-
- await this.saveOtpData(id, otpData);
- await jobService.addJob({
- type: 'send_email_verify_email',
- otpId: id,
- });
-
- return {
- type: 'verify',
- id,
- expiresAt,
- };
- }
-
- public async verifyOtpCode(id: string, otp: string): Promise<string | null> {
- const otpData = await this.fetchOtpData(id);
- if (!otpData) {
- return null;
- }
-
- if (otpData.otp !== otp) {
- if (otpData.attempts >= 3) {
- await this.deleteOtpData(id);
- return null;
- }
-
- otpData.attempts++;
-
- await this.saveOtpData(id, otpData);
- return null;
- }
-
- await this.deleteOtpData(id);
- return otpData.accountId;
- }
-
- public async sendEmailVerifyEmail(otpId: string): Promise<void> {
- const otpData = await this.fetchOtpData(otpId);
- if (!otpData) {
- return;
- }
-
- const account = await database
- .selectFrom('accounts')
- .where('id', '=', otpData.accountId)
- .selectAll()
- .executeTakeFirst();
-
- if (!account) {
- return;
- }
-
- const email = account.email;
- const name = account.name;
- const otp = otpData.otp;
-
- const html = emailVerifyTemplate({
- name,
- otp,
- });
-
- await emailService.sendEmail({
- subject: 'Your Colanode email verification code',
- to: email,
- html,
- });
- }
-
- private async fetchOtpData(otpId: string): Promise<OtpCodeData | null> {
- const redisKey = this.getOtpDataRedisKey(otpId);
- const otpDataJson = await redis.get(redisKey);
- if (!otpDataJson) {
- return null;
- }
-
- return JSON.parse(otpDataJson);
- }
-
- private async saveOtpData(
- otpId: string,
- otpData: OtpCodeData
- ): Promise<void> {
- const redisKey = this.getOtpDataRedisKey(otpId);
- const expireSeconds = Math.max(
- Math.floor((otpData.expiresAt.getTime() - Date.now()) / 1000),
- 1
- );
- await redis.set(redisKey, JSON.stringify(otpData), {
- EX: expireSeconds,
- });
- }
-
- private async deleteOtpData(otpId: string): Promise<void> {
- const redisKey = this.getOtpDataRedisKey(otpId);
- await redis.del(redisKey);
- }
-
- private getOtpDataRedisKey(otpId: string): string {
- return `otp:${otpId}`;
- }
-
- private async generateOtpCode(): Promise<string> {
- let otp = '';
-
- for (let i = 0; i < OTP_LENGTH; i++) {
- const randomIndex = crypto.randomInt(0, OTP_DIGITS.length);
- otp += OTP_DIGITS[randomIndex];
- }
-
- return otp;
- }
-}
-
-export const accountService = new AccountService();
diff --git a/apps/server/src/services/entry-service.ts b/apps/server/src/services/entry-service.ts
deleted file mode 100644
index 8ded3f94..00000000
--- a/apps/server/src/services/entry-service.ts
+++ /dev/null
@@ -1,1041 +0,0 @@
-import {
- extractEntryCollaborators,
- generateId,
- IdType,
- EntryAttributes,
- EntryRole,
- MarkEntrySeenMutation,
- MarkEntryOpenedMutation,
- extractEntryRole,
- hasEntryRole,
- entryAttributesSchema,
- canCreateEntry,
- canUpdateEntry,
- canDeleteEntry,
- TransactionOperation,
- createDebugger,
-} from '@colanode/core';
-import { decodeState, YDoc } from '@colanode/crdt';
-import { Transaction } from 'kysely';
-import { cloneDeep } from 'lodash-es';
-
-import { jobService } from '@/services/job-service';
-import { database } from '@/data/database';
-import {
- CreateEntry,
- CreateCollaboration,
- CreateEntryTransaction,
- DatabaseSchema,
- SelectUser,
- SelectCollaboration,
-} from '@/data/schema';
-import { eventBus } from '@/lib/event-bus';
-import { fetchEntry, mapEntry } from '@/lib/entries';
-import {
- ApplyCreateTransactionInput,
- ApplyCreateTransactionOutput,
- ApplyDeleteTransactionInput,
- ApplyDeleteTransactionOutput,
- ApplyUpdateTransactionInput,
- ApplyUpdateTransactionOutput,
- CreateEntryInput,
- CreateEntryOutput,
- UpdateEntryInput,
- UpdateEntryOutput,
-} from '@/types/entries';
-import { configuration } from '@/lib/configuration';
-
-const UPDATE_RETRIES_LIMIT = 10;
-
-type UpdateResult<T> = {
- type: 'success' | 'error' | 'retry';
- output: T | null;
-};
-
-type CollaboratorChangeResult = {
- addedCollaborators: Record<string, EntryRole>;
- updatedCollaborators: Record<string, EntryRole>;
- removedCollaborators: Record<string, EntryRole>;
-};
-
-class EntryService {
- private readonly debug = createDebugger('server:service:entry');
-
- public async createEntry(
- input: CreateEntryInput
- ): Promise<CreateEntryOutput | null> {
- const ydoc = new YDoc();
- const update = ydoc.updateAttributes(
- entryAttributesSchema,
- input.attributes
- );
-
- if (!update) {
- return null;
- }
-
- const attributes = ydoc.getAttributes<EntryAttributes>();
- const attributesJson = JSON.stringify(attributes);
-
- const date = new Date();
- const transactionId = generateId(IdType.Transaction);
-
- const createEntry: CreateEntry = {
- id: input.entryId,
- root_id: input.rootId,
- workspace_id: input.workspaceId,
- attributes: attributesJson,
- created_at: date,
- created_by: input.userId,
- transaction_id: transactionId,
- };
-
- const createTransaction: CreateEntryTransaction = {
- id: transactionId,
- root_id: input.rootId,
- entry_id: input.entryId,
- workspace_id: input.workspaceId,
- operation: TransactionOperation.Create,
- data: update,
- created_at: date,
- created_by: input.userId,
- server_created_at: date,
- };
-
- try {
- const { createdEntry, createdTransaction, createdCollaborations } =
- await this.applyDatabaseCreateTransaction(
- attributes,
- createEntry,
- createTransaction
- );
-
- eventBus.publish({
- type: 'entry_created',
- entryId: input.entryId,
- entryType: input.attributes.type,
- rootId: input.rootId,
- workspaceId: input.workspaceId,
- });
-
- for (const createdCollaboration of createdCollaborations) {
- eventBus.publish({
- type: 'collaboration_created',
- collaboratorId: createdCollaboration.collaborator_id,
- entryId: input.entryId,
- workspaceId: input.workspaceId,
- });
- }
-
- await this.scheduleEntryEmbedding(input.entryId);
-
- return {
- entry: createdEntry,
- transaction: createdTransaction,
- };
- } catch (error) {
- this.debug(`Failed to create node transaction: ${error}`);
- return null;
- }
- }
-
- public async updateEntry(
- input: UpdateEntryInput
- ): Promise<UpdateEntryOutput | null> {
- for (let count = 0; count < UPDATE_RETRIES_LIMIT; count++) {
- const result = await this.tryUpdateEntry(input);
-
- if (result.type === 'success') {
- return result.output;
- }
-
- if (result.type === 'error') {
- return null;
- }
- }
-
- return null;
- }
-
- private async tryUpdateEntry(
- input: UpdateEntryInput
- ): Promise<UpdateResult<UpdateEntryOutput>> {
- const entryRow = await fetchEntry(input.entryId);
- if (!entryRow) {
- return { type: 'error', output: null };
- }
-
- const entry = mapEntry(entryRow);
- const previousTransactions = await database
- .selectFrom('entry_transactions')
- .selectAll()
- .where('entry_id', '=', input.entryId)
- .orderBy('id', 'asc')
- .execute();
-
- const ydoc = new YDoc();
- for (const transaction of previousTransactions) {
- if (transaction.data === null) {
- return { type: 'error', output: null };
- }
-
- ydoc.applyUpdate(transaction.data);
- }
-
- const currentAttributes = ydoc.getAttributes<EntryAttributes>();
- const updatedAttributes = input.updater(cloneDeep(currentAttributes));
- if (!updatedAttributes) {
- return { type: 'error', output: null };
- }
-
- const update = ydoc.updateAttributes(
- entryAttributesSchema,
- updatedAttributes
- );
-
- if (!update) {
- return { type: 'success', output: null };
- }
-
- const attributes = ydoc.getAttributes<EntryAttributes>();
- const attributesJson = JSON.stringify(attributes);
-
- const date = new Date();
- const transactionId = generateId(IdType.Transaction);
-
- const collaboratorChanges = this.checkCollaboratorChanges(
- entry.attributes,
- attributes
- );
-
- try {
- const {
- updatedEntry,
- createdTransaction,
- createdCollaborations,
- updatedCollaborations,
- } = await database.transaction().execute(async (trx) => {
- const updatedEntry = await trx
- .updateTable('entries')
- .returningAll()
- .set({
- attributes: attributesJson,
- updated_at: date,
- updated_by: input.userId,
- transaction_id: transactionId,
- })
- .where('id', '=', input.entryId)
- .where('transaction_id', '=', entry.transactionId)
- .executeTakeFirst();
-
- if (!updatedEntry) {
- throw new Error('Failed to update entry');
- }
-
- const createdTransaction = await trx
- .insertInto('entry_transactions')
- .returningAll()
- .values({
- id: transactionId,
- entry_id: input.entryId,
- root_id: entry.rootId,
- workspace_id: input.workspaceId,
- operation: TransactionOperation.Update,
- data: update,
- created_at: date,
- created_by: input.userId,
- server_created_at: date,
- })
- .executeTakeFirst();
-
- if (!createdTransaction) {
- throw new Error('Failed to create transaction');
- }
-
- const { createdCollaborations, updatedCollaborations } =
- await this.applyCollaboratorUpdates(
- trx,
- input.entryId,
- input.userId,
- input.workspaceId,
- collaboratorChanges
- );
-
- return {
- updatedEntry,
- createdTransaction,
- createdCollaborations,
- updatedCollaborations,
- };
- });
-
- eventBus.publish({
- type: 'entry_updated',
- entryId: input.entryId,
- entryType: entry.type,
- rootId: entry.rootId,
- workspaceId: input.workspaceId,
- });
-
- for (const createdCollaboration of createdCollaborations) {
- eventBus.publish({
- type: 'collaboration_created',
- collaboratorId: createdCollaboration.collaborator_id,
- entryId: input.entryId,
- workspaceId: input.workspaceId,
- });
- }
-
- for (const updatedCollaboration of updatedCollaborations) {
- eventBus.publish({
- type: 'collaboration_updated',
- collaboratorId: updatedCollaboration.collaborator_id,
- entryId: input.entryId,
- workspaceId: input.workspaceId,
- });
- }
-
- await this.scheduleEntryEmbedding(input.entryId);
-
- return {
- type: 'success',
- output: {
- entry: updatedEntry,
- transaction: createdTransaction,
- },
- };
- } catch {
- return { type: 'retry', output: null };
- }
- }
-
- public async applyCreateTransaction(
- user: SelectUser,
- input: ApplyCreateTransactionInput
- ): Promise<ApplyCreateTransactionOutput | null> {
- const root = await fetchEntry(input.rootId);
- const ydoc = new YDoc();
- ydoc.applyUpdate(input.data);
- const attributes = ydoc.getAttributes<EntryAttributes>();
-
- if (
- !canCreateEntry(
- {
- user: {
- userId: user.id,
- role: user.role,
- },
- root: root ? mapEntry(root) : null,
- },
- attributes
- )
- ) {
- return null;
- }
-
- const createEntry: CreateEntry = {
- id: input.entryId,
- root_id: input.rootId,
- attributes: JSON.stringify(attributes),
- workspace_id: user.workspace_id,
- created_at: input.createdAt,
- created_by: user.id,
- transaction_id: input.id,
- };
-
- const createTransaction: CreateEntryTransaction = {
- id: input.id,
- entry_id: input.entryId,
- root_id: input.rootId,
- workspace_id: user.workspace_id,
- operation: TransactionOperation.Create,
- data:
- typeof input.data === 'string' ? decodeState(input.data) : input.data,
- created_at: input.createdAt,
- created_by: user.id,
- server_created_at: new Date(),
- };
-
- try {
- const { createdEntry, createdTransaction, createdCollaborations } =
- await this.applyDatabaseCreateTransaction(
- attributes,
- createEntry,
- createTransaction
- );
-
- eventBus.publish({
- type: 'entry_created',
- entryId: input.entryId,
- entryType: attributes.type,
- rootId: input.rootId,
- workspaceId: user.workspace_id,
- });
-
- for (const createdCollaboration of createdCollaborations) {
- eventBus.publish({
- type: 'collaboration_created',
- collaboratorId: createdCollaboration.collaborator_id,
- entryId: input.entryId,
- workspaceId: user.workspace_id,
- });
- }
-
- await this.scheduleEntryEmbedding(input.entryId);
-
- return {
- entry: createdEntry,
- transaction: createdTransaction,
- };
- } catch (error) {
- this.debug(`Failed to apply node create transaction: ${error}`);
- return null;
- }
- }
-
- public async applyUpdateTransaction(
- user: SelectUser,
- input: ApplyUpdateTransactionInput
- ): Promise<ApplyUpdateTransactionOutput | null> {
- for (let count = 0; count < UPDATE_RETRIES_LIMIT; count++) {
- const result = await this.tryApplyUpdateTransaction(user, input);
-
- if (result.type === 'success') {
- return result.output;
- }
-
- if (result.type === 'error') {
- return null;
- }
- }
-
- return null;
- }
-
- private async tryApplyUpdateTransaction(
- user: SelectUser,
- input: ApplyUpdateTransactionInput
- ): Promise<UpdateResult<ApplyUpdateTransactionOutput>> {
- const root = await fetchEntry(input.rootId);
- if (!root) {
- return { type: 'error', output: null };
- }
-
- const entry = await fetchEntry(input.entryId);
- if (!entry) {
- return { type: 'error', output: null };
- }
-
- const previousTransactions = await database
- .selectFrom('entry_transactions')
- .selectAll()
- .where('entry_id', '=', input.entryId)
- .orderBy('version', 'asc')
- .execute();
-
- const ydoc = new YDoc();
- for (const previousTransaction of previousTransactions) {
- if (previousTransaction.data === null) {
- return { type: 'error', output: null };
- }
-
- ydoc.applyUpdate(previousTransaction.data);
- }
-
- ydoc.applyUpdate(input.data);
-
- const attributes = ydoc.getAttributes<EntryAttributes>();
- const attributesJson = JSON.stringify(attributes);
-
- if (
- !canUpdateEntry(
- {
- user: {
- userId: user.id,
- role: user.role,
- },
- root: mapEntry(root),
- entry: mapEntry(entry),
- },
- attributes
- )
- ) {
- return { type: 'error', output: null };
- }
-
- const collaboratorChanges = this.checkCollaboratorChanges(
- entry.attributes,
- attributes
- );
-
- try {
- const {
- updatedEntry,
- createdTransaction,
- createdCollaborations,
- updatedCollaborations,
- } = await database.transaction().execute(async (trx) => {
- const updatedEntry = await trx
- .updateTable('entries')
- .returningAll()
- .set({
- attributes: attributesJson,
- updated_at: input.createdAt,
- updated_by: input.userId,
- transaction_id: input.id,
- })
- .where('id', '=', input.entryId)
- .where('transaction_id', '=', entry.transaction_id)
- .executeTakeFirst();
-
- if (!updatedEntry) {
- throw new Error('Failed to update entry');
- }
-
- const createdTransaction = await trx
- .insertInto('entry_transactions')
- .returningAll()
- .values({
- id: input.id,
- entry_id: input.entryId,
- root_id: input.rootId,
- workspace_id: user.workspace_id,
- operation: TransactionOperation.Update,
- data:
- typeof input.data === 'string'
- ? decodeState(input.data)
- : input.data,
- created_at: input.createdAt,
- created_by: input.userId,
- server_created_at: new Date(),
- })
- .executeTakeFirst();
-
- if (!createdTransaction) {
- throw new Error('Failed to create transaction');
- }
-
- const { createdCollaborations, updatedCollaborations } =
- await this.applyCollaboratorUpdates(
- trx,
- input.entryId,
- input.userId,
- user.workspace_id,
- collaboratorChanges
- );
-
- return {
- updatedEntry,
- createdTransaction,
- createdCollaborations,
- updatedCollaborations,
- };
- });
-
- eventBus.publish({
- type: 'entry_updated',
- entryId: input.entryId,
- entryType: entry.type,
- rootId: entry.root_id,
- workspaceId: user.workspace_id,
- });
-
- for (const createdCollaboration of createdCollaborations) {
- eventBus.publish({
- type: 'collaboration_created',
- collaboratorId: createdCollaboration.collaborator_id,
- entryId: input.entryId,
- workspaceId: user.workspace_id,
- });
- }
-
- for (const updatedCollaboration of updatedCollaborations) {
- eventBus.publish({
- type: 'collaboration_updated',
- collaboratorId: updatedCollaboration.collaborator_id,
- entryId: input.entryId,
- workspaceId: user.workspace_id,
- });
- }
-
- await this.scheduleEntryEmbedding(input.entryId);
-
- return {
- type: 'success',
- output: {
- entry: updatedEntry,
- transaction: createdTransaction,
- },
- };
- } catch {
- return { type: 'retry', output: null };
- }
- }
-
- public async applyDeleteTransaction(
- user: SelectUser,
- input: ApplyDeleteTransactionInput
- ): Promise<ApplyDeleteTransactionOutput | null> {
- const entry = await fetchEntry(input.entryId);
- if (!entry) {
- return null;
- }
-
- const root = await fetchEntry(entry.root_id);
- if (!root) {
- return null;
- }
-
- if (
- !canDeleteEntry({
- user: {
- userId: user.id,
- role: user.role,
- },
- root: mapEntry(root),
- entry: mapEntry(entry),
- })
- ) {
- return null;
- }
-
- const { deletedEntry, createdTransaction, updatedCollaborations } =
- await database.transaction().execute(async (trx) => {
- const deletedEntry = await trx
- .deleteFrom('entries')
- .returningAll()
- .where('id', '=', input.entryId)
- .executeTakeFirst();
-
- if (!deletedEntry) {
- throw new Error('Failed to delete entry');
- }
-
- await trx
- .deleteFrom('entry_transactions')
- .where('entry_id', '=', input.entryId)
- .execute();
-
- const createdTransaction = await trx
- .insertInto('entry_transactions')
- .returningAll()
- .values({
- id: input.id,
- entry_id: input.entryId,
- root_id: input.rootId,
- workspace_id: user.workspace_id,
- operation: TransactionOperation.Delete,
- created_at: input.createdAt,
- created_by: user.id,
- server_created_at: new Date(),
- })
- .executeTakeFirst();
-
- if (!createdTransaction) {
- throw new Error('Failed to create transaction');
- }
-
- const updatedCollaborations = await trx
- .updateTable('collaborations')
- .set({
- deleted_at: new Date(),
- deleted_by: user.id,
- })
- .returningAll()
- .where('entry_id', '=', input.entryId)
- .execute();
-
- return {
- deletedEntry,
- createdTransaction,
- updatedCollaborations,
- };
- });
-
- eventBus.publish({
- type: 'entry_deleted',
- entryId: input.entryId,
- entryType: entry.type,
- rootId: entry.root_id,
- workspaceId: user.workspace_id,
- });
-
- for (const updatedCollaboration of updatedCollaborations) {
- eventBus.publish({
- type: 'collaboration_updated',
- collaboratorId: updatedCollaboration.collaborator_id,
- entryId: input.entryId,
- workspaceId: user.workspace_id,
- });
- }
-
- await jobService.addJob({
- type: 'clean_entry_data',
- entryId: input.entryId,
- workspaceId: user.workspace_id,
- });
-
- return {
- entry: deletedEntry,
- transaction: createdTransaction,
- };
- }
-
- public async markEntryAsSeen(
- user: SelectUser,
- mutation: MarkEntrySeenMutation
- ): Promise<boolean> {
- const entry = await database
- .selectFrom('entries')
- .select(['id', 'root_id', 'workspace_id'])
- .where('id', '=', mutation.data.entryId)
- .executeTakeFirst();
-
- if (!entry) {
- return false;
- }
-
- const root = await database
- .selectFrom('entries')
- .selectAll()
- .where('id', '=', entry.root_id)
- .executeTakeFirst();
-
- if (!root) {
- return false;
- }
-
- const rootEntry = mapEntry(root);
- const role = extractEntryRole(rootEntry, user.id);
- if (!role || !hasEntryRole(role, 'viewer')) {
- return false;
- }
-
- const existingInteraction = await database
- .selectFrom('entry_interactions')
- .selectAll()
- .where('entry_id', '=', mutation.data.entryId)
- .where('collaborator_id', '=', user.id)
- .executeTakeFirst();
-
- if (
- existingInteraction &&
- existingInteraction.last_seen_at !== null &&
- existingInteraction.last_seen_at <= new Date(mutation.data.seenAt)
- ) {
- return true;
- }
-
- const lastSeenAt = new Date(mutation.data.seenAt);
- const firstSeenAt = existingInteraction?.first_seen_at ?? lastSeenAt;
- const createdInteraction = await database
- .insertInto('entry_interactions')
- .returningAll()
- .values({
- entry_id: mutation.data.entryId,
- collaborator_id: user.id,
- first_seen_at: firstSeenAt,
- last_seen_at: lastSeenAt,
- root_id: root.id,
- workspace_id: root.workspace_id,
- })
- .onConflict((b) =>
- b.columns(['entry_id', 'collaborator_id']).doUpdateSet({
- last_seen_at: lastSeenAt,
- first_seen_at: firstSeenAt,
- })
- )
- .executeTakeFirst();
-
- if (!createdInteraction) {
- return false;
- }
-
- eventBus.publish({
- type: 'entry_interaction_updated',
- entryId: createdInteraction.entry_id,
- collaboratorId: createdInteraction.collaborator_id,
- rootId: createdInteraction.root_id,
- workspaceId: createdInteraction.workspace_id,
- });
-
- return true;
- }
-
- public async markEntryAsOpened(
- user: SelectUser,
- mutation: MarkEntryOpenedMutation
- ): Promise<boolean> {
- const entry = await database
- .selectFrom('entries')
- .select(['id', 'root_id', 'workspace_id'])
- .where('id', '=', mutation.data.entryId)
- .executeTakeFirst();
-
- if (!entry) {
- return false;
- }
-
- const root = await database
- .selectFrom('entries')
- .selectAll()
- .where('id', '=', entry.root_id)
- .executeTakeFirst();
-
- if (!root) {
- return false;
- }
-
- const rootEntry = mapEntry(root);
- const role = extractEntryRole(rootEntry, user.id);
- if (!role || !hasEntryRole(role, 'viewer')) {
- return false;
- }
-
- const existingInteraction = await database
- .selectFrom('entry_interactions')
- .selectAll()
- .where('entry_id', '=', mutation.data.entryId)
- .where('collaborator_id', '=', user.id)
- .executeTakeFirst();
-
- if (
- existingInteraction &&
- existingInteraction.last_opened_at !== null &&
- existingInteraction.last_opened_at <= new Date(mutation.data.openedAt)
- ) {
- return true;
- }
-
- const lastOpenedAt = new Date(mutation.data.openedAt);
- const firstOpenedAt = existingInteraction?.first_opened_at ?? lastOpenedAt;
- const createdInteraction = await database
- .insertInto('entry_interactions')
- .returningAll()
- .values({
- entry_id: mutation.data.entryId,
- collaborator_id: user.id,
- first_opened_at: firstOpenedAt,
- last_opened_at: lastOpenedAt,
- root_id: root.id,
- workspace_id: root.workspace_id,
- })
- .onConflict((b) =>
- b.columns(['entry_id', 'collaborator_id']).doUpdateSet({
- last_opened_at: lastOpenedAt,
- first_opened_at: firstOpenedAt,
- })
- )
- .executeTakeFirst();
-
- if (!createdInteraction) {
- return false;
- }
-
- eventBus.publish({
- type: 'entry_interaction_updated',
- entryId: createdInteraction.entry_id,
- collaboratorId: createdInteraction.collaborator_id,
- rootId: createdInteraction.root_id,
- workspaceId: createdInteraction.workspace_id,
- });
-
- return true;
- }
-
- private async applyDatabaseCreateTransaction(
- attributes: EntryAttributes,
- entry: CreateEntry,
- transaction: CreateEntryTransaction
- ) {
- const collaborationsToCreate: CreateCollaboration[] = Object.entries(
- extractEntryCollaborators(attributes)
- ).map(([userId, role]) => ({
- collaborator_id: userId,
- entry_id: entry.id,
- workspace_id: entry.workspace_id,
- role,
- created_at: new Date(),
- created_by: transaction.created_by,
- }));
-
- return await database.transaction().execute(async (trx) => {
- const createdEntry = await trx
- .insertInto('entries')
- .returningAll()
- .values(entry)
- .executeTakeFirst();
-
- if (!createdEntry) {
- throw new Error('Failed to create entry');
- }
-
- const createdTransaction = await trx
- .insertInto('entry_transactions')
- .returningAll()
- .values(transaction)
- .executeTakeFirst();
-
- if (!createdTransaction) {
- throw new Error('Failed to create transaction');
- }
-
- if (collaborationsToCreate.length > 0) {
- const createdCollaborations = await trx
- .insertInto('collaborations')
- .returningAll()
- .values(collaborationsToCreate)
- .execute();
-
- if (createdCollaborations.length !== collaborationsToCreate.length) {
- throw new Error('Failed to create collaborations');
- }
-
- return { createdEntry, createdTransaction, createdCollaborations };
- }
-
- return { createdEntry, createdTransaction, createdCollaborations: [] };
- });
- }
-
- private async applyCollaboratorUpdates(
- transaction: Transaction<DatabaseSchema>,
- entryId: string,
- userId: string,
- workspaceId: string,
- updateResult: CollaboratorChangeResult
- ) {
- const createdCollaborations: SelectCollaboration[] = [];
- const updatedCollaborations: SelectCollaboration[] = [];
-
- for (const [collaboratorId, role] of Object.entries(
- updateResult.addedCollaborators
- )) {
- const createdCollaboration = await transaction
- .insertInto('collaborations')
- .returningAll()
- .values({
- collaborator_id: collaboratorId,
- entry_id: entryId,
- workspace_id: workspaceId,
- role,
- created_at: new Date(),
- created_by: userId,
- })
- .onConflict((oc) =>
- oc.columns(['collaborator_id', 'entry_id']).doUpdateSet({
- role,
- updated_at: new Date(),
- updated_by: userId,
- deleted_at: null,
- deleted_by: null,
- })
- )
- .executeTakeFirst();
-
- if (!createdCollaboration) {
- throw new Error('Failed to create collaboration');
- }
-
- createdCollaborations.push(createdCollaboration);
- }
-
- for (const [collaboratorId, role] of Object.entries(
- updateResult.updatedCollaborators
- )) {
- const updatedCollaboration = await transaction
- .updateTable('collaborations')
- .returningAll()
- .set({
- role,
- updated_at: new Date(),
- updated_by: userId,
- deleted_at: null,
- deleted_by: null,
- })
- .where('collaborator_id', '=', collaboratorId)
- .where('entry_id', '=', entryId)
- .executeTakeFirst();
-
- if (!updatedCollaboration) {
- throw new Error('Failed to update collaboration');
- }
-
- updatedCollaborations.push(updatedCollaboration);
- }
-
- const removedCollaboratorIds = Object.keys(
- updateResult.removedCollaborators
- );
-
- if (removedCollaboratorIds.length > 0) {
- const removedCollaborations = await transaction
- .updateTable('collaborations')
- .returningAll()
- .set({
- deleted_at: new Date(),
- deleted_by: userId,
- })
- .where('collaborator_id', 'in', removedCollaboratorIds)
- .where('entry_id', '=', entryId)
- .execute();
-
- if (removedCollaborations.length !== removedCollaboratorIds.length) {
- throw new Error('Failed to remove collaborations');
- }
-
- updatedCollaborations.push(...removedCollaborations);
- }
-
- return { createdCollaborations, updatedCollaborations };
- }
-
- private checkCollaboratorChanges(
- beforeAttributes: EntryAttributes,
- afterAttributes: EntryAttributes
- ): CollaboratorChangeResult {
- const beforeCollaborators = extractEntryCollaborators(beforeAttributes);
- const afterCollaborators = extractEntryCollaborators(afterAttributes);
-
- const addedCollaborators: Record<string, EntryRole> = {};
- const updatedCollaborators: Record<string, EntryRole> = {};
- const removedCollaborators: Record<string, EntryRole> = {};
-
- // Check for added and updated collaborators
- for (const [userId, newRole] of Object.entries(afterCollaborators)) {
- if (!(userId in beforeCollaborators)) {
- addedCollaborators[userId] = newRole;
- } else if (beforeCollaborators[userId] !== newRole) {
- updatedCollaborators[userId] = newRole;
- }
- }
-
- // Check for removed collaborators
- for (const [userId, oldRole] of Object.entries(beforeCollaborators)) {
- if (!(userId in afterCollaborators)) {
- removedCollaborators[userId] = oldRole;
- }
- }
-
- return {
- addedCollaborators,
- updatedCollaborators,
- removedCollaborators,
- };
- }
-
- private async scheduleEntryEmbedding(entryId: string) {
- await jobService.addJob(
- {
- type: 'embed_entry',
- entryId,
- },
- {
- jobId: `embed_entry:${entryId}`,
- delay: configuration.ai.entryEmbedDelay,
- }
- );
- }
-}
-
-export const entryService = new EntryService();
diff --git a/apps/server/src/services/file-service.ts b/apps/server/src/services/file-service.ts
deleted file mode 100644
index 7f55836c..00000000
--- a/apps/server/src/services/file-service.ts
+++ /dev/null
@@ -1,360 +0,0 @@
-import {
- canCreateFile,
- canDeleteFile,
- CreateFileMutation,
- DeleteFileMutation,
- extractEntryRole,
- FileStatus,
- hasEntryRole,
- MarkFileOpenedMutation,
- MarkFileSeenMutation,
-} from '@colanode/core';
-import { DeleteObjectCommand } from '@aws-sdk/client-s3';
-
-import { database } from '@/data/database';
-import { SelectUser } from '@/data/schema';
-import { fetchEntry, mapEntry } from '@/lib/entries';
-import { eventBus } from '@/lib/event-bus';
-import { fileS3 } from '@/data/storage';
-import { configuration } from '@/lib/configuration';
-
-class FileService {
- public async createFile(
- user: SelectUser,
- mutation: CreateFileMutation
- ): Promise<boolean> {
- const existingFile = await database
- .selectFrom('files')
- .where('id', '=', mutation.data.id)
- .executeTakeFirst();
-
- if (existingFile) {
- return true;
- }
-
- const entry = await fetchEntry(mutation.data.entryId);
- if (!entry) {
- return false;
- }
-
- const root = await fetchEntry(mutation.data.rootId);
- if (!root) {
- return false;
- }
-
- if (
- !canCreateFile({
- user: {
- userId: user.id,
- role: user.role,
- },
- root: mapEntry(root),
- entry: mapEntry(entry),
- file: {
- id: mutation.data.id,
- parentId: mutation.data.parentId,
- },
- })
- ) {
- return false;
- }
-
- if (mutation.data.size > user.max_file_size) {
- return false;
- }
-
- const storageUsedRow = await database
- .selectFrom('files')
- .select(({ fn }) => [fn.sum('size').as('storage_used')])
- .where('created_by', '=', user.id)
- .executeTakeFirst();
-
- const storageUsed = BigInt(storageUsedRow?.storage_used ?? 0);
-
- if (storageUsed + BigInt(mutation.data.size) > user.storage_limit) {
- return false;
- }
-
- const createdFile = await database
- .insertInto('files')
- .returningAll()
- .values({
- id: mutation.data.id,
- type: mutation.data.type,
- parent_id: mutation.data.parentId,
- entry_id: mutation.data.entryId,
- root_id: mutation.data.rootId,
- workspace_id: root.workspace_id,
- name: mutation.data.name,
- original_name: mutation.data.originalName,
- extension: mutation.data.extension,
- mime_type: mutation.data.mimeType,
- size: mutation.data.size,
- created_by: user.id,
- created_at: new Date(mutation.data.createdAt),
- status: FileStatus.Pending,
- })
- .executeTakeFirst();
-
- if (!createdFile) {
- return false;
- }
-
- eventBus.publish({
- type: 'file_created',
- fileId: createdFile.id,
- rootId: createdFile.root_id,
- workspaceId: createdFile.workspace_id,
- });
-
- return true;
- }
-
- public async deleteFile(
- user: SelectUser,
- mutation: DeleteFileMutation
- ): Promise<boolean> {
- const file = await database
- .selectFrom('files')
- .selectAll()
- .where('id', '=', mutation.data.id)
- .executeTakeFirst();
-
- if (!file) {
- return true;
- }
-
- const entry = await fetchEntry(file.entry_id);
- if (!entry) {
- return false;
- }
-
- const root = await fetchEntry(file.root_id);
- if (!root) {
- return false;
- }
-
- if (
- !canDeleteFile({
- user: {
- userId: user.id,
- role: user.role,
- },
- root: mapEntry(root),
- entry: mapEntry(entry),
- file: {
- id: mutation.data.id,
- parentId: file.parent_id,
- createdBy: file.created_by,
- },
- })
- ) {
- return false;
- }
-
- const deletedFile = await database.transaction().execute(async (tx) => {
- const deletedFile = await tx
- .deleteFrom('files')
- .returningAll()
- .where('id', '=', mutation.data.id)
- .executeTakeFirst();
-
- if (!deletedFile) {
- return null;
- }
-
- await tx
- .deleteFrom('file_interactions')
- .where('file_id', '=', deletedFile.id)
- .execute();
-
- await tx
- .insertInto('file_tombstones')
- .values({
- id: deletedFile.id,
- root_id: deletedFile.root_id,
- workspace_id: deletedFile.workspace_id,
- deleted_at: new Date(mutation.data.deletedAt),
- deleted_by: user.id,
- })
- .executeTakeFirst();
-
- return deletedFile;
- });
-
- if (!deletedFile) {
- return false;
- }
-
- const path = `files/${deletedFile.workspace_id}/${deletedFile.id}${deletedFile.extension}`;
- const command = new DeleteObjectCommand({
- Bucket: configuration.fileS3.bucketName,
- Key: path,
- });
-
- await fileS3.send(command);
-
- eventBus.publish({
- type: 'file_deleted',
- fileId: deletedFile.id,
- rootId: deletedFile.root_id,
- workspaceId: deletedFile.workspace_id,
- });
-
- return true;
- }
-
- public async markFileAsSeen(
- user: SelectUser,
- mutation: MarkFileSeenMutation
- ): Promise<boolean> {
- const file = await database
- .selectFrom('files')
- .select(['id', 'root_id', 'workspace_id'])
- .where('id', '=', mutation.data.fileId)
- .executeTakeFirst();
-
- if (!file) {
- return false;
- }
-
- const root = await fetchEntry(file.root_id);
- if (!root) {
- return false;
- }
-
- const rootEntry = mapEntry(root);
- const role = extractEntryRole(rootEntry, user.id);
- if (!role || !hasEntryRole(role, 'viewer')) {
- return false;
- }
-
- const existingInteraction = await database
- .selectFrom('file_interactions')
- .selectAll()
- .where('file_id', '=', mutation.data.fileId)
- .where('collaborator_id', '=', user.id)
- .executeTakeFirst();
-
- if (
- existingInteraction &&
- existingInteraction.last_seen_at !== null &&
- existingInteraction.last_seen_at <= new Date(mutation.data.seenAt)
- ) {
- return true;
- }
-
- const lastSeenAt = new Date(mutation.data.seenAt);
- const firstSeenAt = existingInteraction?.first_seen_at ?? lastSeenAt;
- const createdInteraction = await database
- .insertInto('file_interactions')
- .returningAll()
- .values({
- file_id: mutation.data.fileId,
- collaborator_id: user.id,
- first_seen_at: firstSeenAt,
- last_seen_at: lastSeenAt,
- root_id: root.id,
- workspace_id: root.workspace_id,
- })
- .onConflict((b) =>
- b.columns(['file_id', 'collaborator_id']).doUpdateSet({
- last_seen_at: lastSeenAt,
- first_seen_at: firstSeenAt,
- })
- )
- .executeTakeFirst();
-
- if (!createdInteraction) {
- return false;
- }
-
- eventBus.publish({
- type: 'file_interaction_updated',
- fileId: createdInteraction.file_id,
- collaboratorId: createdInteraction.collaborator_id,
- rootId: createdInteraction.root_id,
- workspaceId: createdInteraction.workspace_id,
- });
-
- return true;
- }
-
- public async markFileAsOpened(
- user: SelectUser,
- mutation: MarkFileOpenedMutation
- ): Promise<boolean> {
- const file = await database
- .selectFrom('files')
- .select(['id', 'entry_id', 'root_id', 'workspace_id'])
- .where('id', '=', mutation.data.fileId)
- .executeTakeFirst();
-
- if (!file) {
- return false;
- }
-
- const root = await fetchEntry(file.root_id);
- if (!root) {
- return false;
- }
-
- const rootEntry = mapEntry(root);
- const role = extractEntryRole(rootEntry, user.id);
- if (!role || !hasEntryRole(role, 'viewer')) {
- return false;
- }
-
- const existingInteraction = await database
- .selectFrom('file_interactions')
- .selectAll()
- .where('file_id', '=', mutation.data.fileId)
- .where('collaborator_id', '=', user.id)
- .executeTakeFirst();
-
- if (
- existingInteraction &&
- existingInteraction.last_opened_at !== null &&
- existingInteraction.last_opened_at <= new Date(mutation.data.openedAt)
- ) {
- return true;
- }
-
- const lastOpenedAt = new Date(mutation.data.openedAt);
- const firstOpenedAt = existingInteraction?.first_opened_at ?? lastOpenedAt;
- const createdInteraction = await database
- .insertInto('file_interactions')
- .returningAll()
- .values({
- file_id: mutation.data.fileId,
- collaborator_id: user.id,
- first_opened_at: firstOpenedAt,
- last_opened_at: lastOpenedAt,
- root_id: root.id,
- workspace_id: root.workspace_id,
- })
- .onConflict((b) =>
- b.columns(['file_id', 'collaborator_id']).doUpdateSet({
- last_opened_at: lastOpenedAt,
- first_opened_at: firstOpenedAt,
- })
- )
- .executeTakeFirst();
-
- if (!createdInteraction) {
- return false;
- }
-
- eventBus.publish({
- type: 'file_interaction_updated',
- fileId: createdInteraction.file_id,
- collaboratorId: createdInteraction.collaborator_id,
- rootId: createdInteraction.root_id,
- workspaceId: createdInteraction.workspace_id,
- });
-
- return true;
- }
-}
-
-export const fileService = new FileService();
diff --git a/apps/server/src/services/message-service.ts b/apps/server/src/services/message-service.ts
deleted file mode 100644
index 53a6345b..00000000
--- a/apps/server/src/services/message-service.ts
+++ /dev/null
@@ -1,391 +0,0 @@
-import {
- canCreateMessage,
- canCreateMessageReaction,
- canDeleteMessage,
- CreateMessageMutation,
- CreateMessageReactionMutation,
- DeleteMessageMutation,
- DeleteMessageReactionMutation,
- extractEntryRole,
- hasEntryRole,
- MarkMessageSeenMutation,
-} from '@colanode/core';
-
-import { database } from '@/data/database';
-import { SelectUser } from '@/data/schema';
-import { fetchEntry, mapEntry } from '@/lib/entries';
-import { eventBus } from '@/lib/event-bus';
-import { jobService } from '@/services/job-service';
-
-class MessageService {
- public async createMessage(
- user: SelectUser,
- mutation: CreateMessageMutation
- ): Promise<boolean> {
- const existingMessage = await database
- .selectFrom('messages')
- .where('id', '=', mutation.data.id)
- .executeTakeFirst();
-
- if (existingMessage) {
- return true;
- }
-
- const root = await fetchEntry(mutation.data.rootId);
- const entry = await fetchEntry(mutation.data.entryId);
-
- if (!root || !entry) {
- return false;
- }
-
- if (
- !canCreateMessage({
- user: {
- userId: user.id,
- role: user.role,
- },
- root: mapEntry(root),
- entry: mapEntry(entry),
- })
- ) {
- return false;
- }
-
- const createdMessage = await database
- .insertInto('messages')
- .returningAll()
- .values({
- id: mutation.data.id,
- entry_id: mutation.data.entryId,
- parent_id: mutation.data.parentId,
- root_id: mutation.data.rootId,
- workspace_id: root.workspace_id,
- attributes: JSON.stringify(mutation.data.attributes),
- created_by: user.id,
- created_at: new Date(mutation.data.createdAt),
- })
- .executeTakeFirst();
-
- if (!createdMessage) {
- return false;
- }
-
- await jobService.addJob({
- type: 'embed_message',
- messageId: createdMessage.id,
- });
-
- eventBus.publish({
- type: 'message_created',
- messageId: createdMessage.id,
- rootId: createdMessage.root_id,
- workspaceId: createdMessage.workspace_id,
- });
-
- return true;
- }
-
- public async deleteMessage(
- user: SelectUser,
- mutation: DeleteMessageMutation
- ): Promise<boolean> {
- const message = await database
- .selectFrom('messages')
- .select(['id', 'entry_id', 'root_id', 'workspace_id', 'created_by'])
- .where('id', '=', mutation.data.id)
- .executeTakeFirst();
-
- if (!message) {
- return true;
- }
-
- const root = await fetchEntry(message.root_id);
- const entry = await fetchEntry(message.entry_id);
-
- if (!root || !entry) {
- return false;
- }
-
- if (
- !canDeleteMessage({
- user: {
- userId: user.id,
- role: user.role,
- },
- root: mapEntry(root),
- entry: mapEntry(entry),
- message: {
- id: message.id,
- createdBy: message.created_by,
- },
- })
- ) {
- return false;
- }
-
- const deletedMessage = await database.transaction().execute(async (tx) => {
- const deletedMessage = await tx
- .deleteFrom('messages')
- .returningAll()
- .where('id', '=', mutation.data.id)
- .executeTakeFirst();
-
- if (!deletedMessage) {
- return null;
- }
-
- await tx
- .deleteFrom('message_interactions')
- .where('message_id', '=', deletedMessage.id)
- .execute();
-
- await tx
- .deleteFrom('message_reactions')
- .where('message_id', '=', deletedMessage.id)
- .execute();
-
- await tx
- .deleteFrom('message_embeddings')
- .where('message_id', '=', deletedMessage.id)
- .execute();
-
- await tx
- .insertInto('message_tombstones')
- .values({
- id: deletedMessage.id,
- root_id: deletedMessage.root_id,
- workspace_id: deletedMessage.workspace_id,
- deleted_at: new Date(mutation.data.deletedAt),
- deleted_by: user.id,
- })
- .executeTakeFirst();
-
- return deletedMessage;
- });
-
- if (!deletedMessage) {
- return false;
- }
-
- eventBus.publish({
- type: 'message_deleted',
- messageId: deletedMessage.id,
- rootId: deletedMessage.root_id,
- workspaceId: deletedMessage.workspace_id,
- });
-
- return true;
- }
-
- public async createMessageReaction(
- user: SelectUser,
- mutation: CreateMessageReactionMutation
- ): Promise<boolean> {
- const message = await database
- .selectFrom('messages')
- .select(['id', 'root_id', 'workspace_id', 'created_by'])
- .where('id', '=', mutation.data.messageId)
- .executeTakeFirst();
-
- if (!message) {
- return false;
- }
-
- const root = await database
- .selectFrom('entries')
- .selectAll()
- .where('id', '=', message.root_id)
- .executeTakeFirst();
-
- if (!root) {
- return false;
- }
-
- if (
- !canCreateMessageReaction({
- user: {
- userId: user.id,
- role: user.role,
- },
- root: mapEntry(root),
- message: {
- id: message.id,
- createdBy: message.created_by,
- },
- })
- ) {
- return false;
- }
-
- const createdMessageReaction = await database
- .insertInto('message_reactions')
- .returningAll()
- .values({
- message_id: mutation.data.messageId,
- collaborator_id: user.id,
- reaction: mutation.data.reaction,
- workspace_id: root.workspace_id,
- root_id: root.id,
- created_at: new Date(mutation.data.createdAt),
- })
- .onConflict((b) =>
- b.columns(['message_id', 'collaborator_id', 'reaction']).doUpdateSet({
- created_at: new Date(mutation.data.createdAt),
- deleted_at: null,
- })
- )
- .executeTakeFirst();
-
- if (!createdMessageReaction) {
- return false;
- }
-
- eventBus.publish({
- type: 'message_reaction_created',
- messageId: createdMessageReaction.message_id,
- collaboratorId: createdMessageReaction.collaborator_id,
- rootId: createdMessageReaction.root_id,
- workspaceId: createdMessageReaction.workspace_id,
- });
-
- return true;
- }
-
- public async deleteMessageReaction(
- user: SelectUser,
- mutation: DeleteMessageReactionMutation
- ): Promise<boolean> {
- const message = await database
- .selectFrom('messages')
- .select(['id', 'root_id', 'workspace_id'])
- .where('id', '=', mutation.data.messageId)
- .executeTakeFirst();
-
- if (!message) {
- return false;
- }
-
- const root = await database
- .selectFrom('entries')
- .selectAll()
- .where('id', '=', message.root_id)
- .executeTakeFirst();
-
- if (!root) {
- return false;
- }
-
- const rootEntry = mapEntry(root);
- const role = extractEntryRole(rootEntry, user.id);
- if (!role || !hasEntryRole(role, 'commenter')) {
- return false;
- }
-
- const deletedMessageReaction = await database
- .updateTable('message_reactions')
- .set({
- deleted_at: new Date(mutation.data.deletedAt),
- })
- .where('message_id', '=', mutation.data.messageId)
- .where('collaborator_id', '=', user.id)
- .where('reaction', '=', mutation.data.reaction)
- .executeTakeFirst();
-
- if (!deletedMessageReaction) {
- return false;
- }
-
- eventBus.publish({
- type: 'message_reaction_deleted',
- messageId: mutation.data.messageId,
- collaboratorId: user.id,
- rootId: root.id,
- workspaceId: root.workspace_id,
- });
-
- return true;
- }
-
- public async markMessageAsSeen(
- user: SelectUser,
- mutation: MarkMessageSeenMutation
- ): Promise<boolean> {
- const message = await database
- .selectFrom('messages')
- .select(['id', 'root_id', 'workspace_id'])
- .where('id', '=', mutation.data.messageId)
- .executeTakeFirst();
-
- if (!message) {
- return false;
- }
-
- const root = await database
- .selectFrom('entries')
- .selectAll()
- .where('id', '=', message.root_id)
- .executeTakeFirst();
-
- if (!root) {
- return false;
- }
-
- const rootEntry = mapEntry(root);
- const role = extractEntryRole(rootEntry, user.id);
- if (!role || !hasEntryRole(role, 'viewer')) {
- return false;
- }
-
- const existingInteraction = await database
- .selectFrom('message_interactions')
- .selectAll()
- .where('message_id', '=', mutation.data.messageId)
- .where('collaborator_id', '=', user.id)
- .executeTakeFirst();
-
- if (
- existingInteraction &&
- existingInteraction.last_seen_at !== null &&
- existingInteraction.last_seen_at >= new Date(mutation.data.seenAt)
- ) {
- return true;
- }
-
- const lastSeenAt = new Date(mutation.data.seenAt);
- const firstSeenAt = existingInteraction?.first_seen_at ?? lastSeenAt;
- const createdInteraction = await database
- .insertInto('message_interactions')
- .returningAll()
- .values({
- message_id: mutation.data.messageId,
- collaborator_id: user.id,
- first_seen_at: firstSeenAt,
- last_seen_at: lastSeenAt,
- root_id: root.id,
- workspace_id: root.workspace_id,
- })
- .onConflict((b) =>
- b.columns(['message_id', 'collaborator_id']).doUpdateSet({
- last_seen_at: lastSeenAt,
- first_seen_at: firstSeenAt,
- })
- )
- .executeTakeFirst();
-
- if (!createdInteraction) {
- return false;
- }
-
- eventBus.publish({
- type: 'message_interaction_updated',
- messageId: createdInteraction.message_id,
- collaboratorId: createdInteraction.collaborator_id,
- rootId: createdInteraction.root_id,
- workspaceId: createdInteraction.workspace_id,
- });
-
- return true;
- }
-}
-
-export const messageService = new MessageService();
diff --git a/apps/server/src/services/socket-connection.ts b/apps/server/src/services/socket-connection.ts
index f5f94bf9..c69a7c7b 100644
--- a/apps/server/src/services/socket-connection.ts
+++ b/apps/server/src/services/socket-connection.ts
@@ -23,15 +23,11 @@ import { ConnectedUser } from '@/types/users';
import { BaseSynchronizer } from '@/synchronizers/base';
import { UserSynchronizer } from '@/synchronizers/users';
import { CollaborationSynchronizer } from '@/synchronizers/collaborations';
+import { NodeSynchronizer } from '@/synchronizers/nodes';
+import { NodeReactionSynchronizer } from '@/synchronizers/node-reactions';
+import { NodeTombstoneSynchronizer } from '@/synchronizers/node-tombstones';
+import { NodeInteractionSynchronizer } from '@/synchronizers/node-interactions';
import { FileSynchronizer } from '@/synchronizers/files';
-import { MessageSynchronizer } from '@/synchronizers/messages';
-import { MessageReactionSynchronizer } from '@/synchronizers/message-reactions';
-import { EntryTransactionSynchronizer } from '@/synchronizers/entry-transactions';
-import { MessageInteractionSynchronizer } from '@/synchronizers/message-interactions';
-import { EntryInteractionSynchronizer } from '@/synchronizers/entry-interactions';
-import { FileInteractionSynchronizer } from '@/synchronizers/file-interactions';
-import { FileTombstoneSynchronizer } from '@/synchronizers/file-tombstones';
-import { MessageTombstoneSynchronizer } from '@/synchronizers/message-tombstones';
type SocketUser = {
user: ConnectedUser;
@@ -156,73 +152,32 @@ export class SocketConnection {
}
return new FileSynchronizer(message.id, user.user, message.input, cursor);
- } else if (message.input.type === 'messages') {
+ } else if (message.input.type === 'nodes') {
if (!user.rootIds.has(message.input.rootId)) {
return null;
}
- return new MessageSynchronizer(
+ return new NodeSynchronizer(message.id, user.user, message.input, cursor);
+ } else if (message.input.type === 'node_reactions') {
+ return new NodeReactionSynchronizer(
message.id,
user.user,
message.input,
cursor
);
- } else if (message.input.type === 'message_reactions') {
- return new MessageReactionSynchronizer(
+ } else if (message.input.type === 'node_interactions') {
+ return new NodeInteractionSynchronizer(
message.id,
user.user,
message.input,
cursor
);
- } else if (message.input.type === 'entry_transactions') {
- return new EntryTransactionSynchronizer(
- message.id,
- user.user,
- message.input,
- cursor
- );
- } else if (message.input.type === 'message_interactions') {
+ } else if (message.input.type === 'node_tombstones') {
if (!user.rootIds.has(message.input.rootId)) {
return null;
}
- return new MessageInteractionSynchronizer(
- message.id,
- user.user,
- message.input,
- cursor
- );
- } else if (message.input.type === 'entry_interactions') {
- if (!user.rootIds.has(message.input.rootId)) {
- return null;
- }
-
- return new EntryInteractionSynchronizer(
- message.id,
- user.user,
- message.input,
- cursor
- );
- } else if (message.input.type === 'file_interactions') {
- if (!user.rootIds.has(message.input.rootId)) {
- return null;
- }
-
- return new FileInteractionSynchronizer(
- message.id,
- user.user,
- message.input,
- cursor
- );
- } else if (message.input.type === 'file_tombstones') {
- return new FileTombstoneSynchronizer(
- message.id,
- user.user,
- message.input,
- cursor
- );
- } else if (message.input.type === 'message_tombstones') {
- return new MessageTombstoneSynchronizer(
+ return new NodeTombstoneSynchronizer(
message.id,
user.user,
message.input,
@@ -297,7 +252,7 @@ export class SocketConnection {
continue;
}
- rootIds.add(collaboration.entry_id);
+ rootIds.add(collaboration.node_id);
}
const socketUser: SocketUser = {
@@ -357,7 +312,7 @@ export class SocketConnection {
return;
}
- user.rootIds.add(event.entryId);
+ user.rootIds.add(event.nodeId);
}
private async handleCollaborationUpdatedEvent(
@@ -372,13 +327,13 @@ export class SocketConnection {
.selectFrom('collaborations')
.selectAll()
.where('collaborator_id', '=', event.collaboratorId)
- .where('entry_id', '=', event.entryId)
+ .where('node_id', '=', event.nodeId)
.executeTakeFirst();
if (!collaboration || collaboration.deleted_at) {
- user.rootIds.delete(event.entryId);
+ user.rootIds.delete(event.nodeId);
} else {
- user.rootIds.add(event.entryId);
+ user.rootIds.add(event.nodeId);
}
}
diff --git a/apps/server/src/services/workspace-service.ts b/apps/server/src/services/workspace-service.ts
deleted file mode 100644
index cc9d8ac4..00000000
--- a/apps/server/src/services/workspace-service.ts
+++ /dev/null
@@ -1,180 +0,0 @@
-import {
- generateId,
- IdType,
- WorkspaceCreateInput,
- WorkspaceOutput,
- WorkspaceStatus,
- UserStatus,
- MessageType,
-} from '@colanode/core';
-
-import { database } from '@/data/database';
-import { SelectAccount } from '@/data/schema';
-import { mapEntry } from '@/lib/entries';
-import { entryService } from '@/services/entry-service';
-import { eventBus } from '@/lib/event-bus';
-import { configuration } from '@/lib/configuration';
-import { messageService } from '@/services/message-service';
-import {
- generateWelcomePageBlocks,
- generateInitialMessageBlocks,
-} from '@/lib/blocks';
-
-class WorkspaceService {
- public async createWorkspace(
- account: SelectAccount,
- input: WorkspaceCreateInput
- ): Promise<WorkspaceOutput> {
- const date = new Date();
- const workspaceId = generateId(IdType.Workspace);
- const userId = generateId(IdType.User);
- const spaceId = generateId(IdType.Space);
-
- const workspace = await database
- .insertInto('workspaces')
- .values({
- id: workspaceId,
- name: input.name,
- description: input.description,
- avatar: input.avatar,
- created_at: date,
- created_by: account.id,
- status: WorkspaceStatus.Active,
- })
- .returningAll()
- .executeTakeFirst();
-
- if (!workspace) {
- throw new Error('Failed to create workspace.');
- }
-
- const user = await database
- .insertInto('users')
- .values({
- id: userId,
- account_id: account.id,
- workspace_id: workspaceId,
- role: 'owner',
- name: account.name,
- email: account.email,
- avatar: account.avatar,
- storage_limit: configuration.user.storageLimit,
- max_file_size: configuration.user.maxFileSize,
- created_at: date,
- created_by: account.id,
- status: UserStatus.Active,
- })
- .returningAll()
- .executeTakeFirst();
-
- if (!user) {
- throw new Error('Failed to create workspace user.');
- }
-
- const createSpaceEntryOutput = await entryService.createEntry({
- entryId: spaceId,
- rootId: spaceId,
- attributes: {
- type: 'space',
- name: 'Home',
- description: 'This is your home space.',
- visibility: 'private',
- collaborators: {
- [userId]: 'admin',
- },
- },
- userId: userId,
- workspaceId: workspaceId,
- ancestors: [],
- });
-
- if (createSpaceEntryOutput) {
- const spaceEntry = mapEntry(createSpaceEntryOutput.entry);
-
- const pageId = generateId(IdType.Page);
- await entryService.createEntry({
- entryId: pageId,
- rootId: spaceId,
- attributes: {
- type: 'page',
- name: 'Welcome',
- parentId: spaceId,
- content: generateWelcomePageBlocks(pageId),
- },
- userId: userId,
- workspaceId: workspaceId,
- ancestors: [spaceEntry],
- });
-
- const channelId = generateId(IdType.Channel);
- await entryService.createEntry({
- entryId: channelId,
- rootId: spaceId,
- attributes: {
- type: 'channel',
- name: 'Discussions',
- parentId: spaceId,
- },
- userId: userId,
- workspaceId: workspaceId,
- ancestors: [spaceEntry],
- });
-
- const messageId = generateId(IdType.Message);
- await messageService.createMessage(user, {
- id: messageId,
- type: 'create_message',
- data: {
- id: messageId,
- entryId: channelId,
- parentId: channelId,
- attributes: {
- type: MessageType.Standard,
- blocks: generateInitialMessageBlocks(messageId),
- },
- rootId: spaceId,
- createdAt: date.toISOString(),
- },
- createdAt: date.toISOString(),
- });
- }
-
- eventBus.publish({
- type: 'workspace_created',
- workspaceId: workspaceId,
- });
-
- eventBus.publish({
- type: 'user_created',
- userId: userId,
- workspaceId: workspaceId,
- accountId: account.id,
- });
-
- return {
- id: workspace.id,
- name: workspace.name,
- description: workspace.description,
- avatar: workspace.avatar,
- user: {
- id: user.id,
- accountId: user.account_id,
- role: user.role,
- storageLimit: user.storage_limit,
- maxFileSize: user.max_file_size,
- },
- };
- }
-
- public async createDefaultWorkspace(account: SelectAccount) {
- const input: WorkspaceCreateInput = {
- name: `${account.name}'s Workspace`,
- description: 'This is your personal workspace.',
- avatar: '',
- };
-
- return this.createWorkspace(account, input);
- }
-}
-
-export const workspaceService = new WorkspaceService();
diff --git a/apps/server/src/synchronizers/collaborations.ts b/apps/server/src/synchronizers/collaborations.ts
index ce187db9..3e0abf28 100644
--- a/apps/server/src/synchronizers/collaborations.ts
+++ b/apps/server/src/synchronizers/collaborations.ts
@@ -44,8 +44,8 @@ export class CollaborationSynchronizer extends BaseSynchronizer<SyncCollaboratio
.selectFrom('collaborations')
.selectAll()
.where('collaborator_id', '=', this.user.userId)
- .where('version', '>', this.cursor)
- .orderBy('version', 'asc')
+ .where('revision', '>', this.cursor)
+ .orderBy('revision', 'asc')
.limit(50)
.execute();
@@ -58,7 +58,7 @@ export class CollaborationSynchronizer extends BaseSynchronizer<SyncCollaboratio
): SynchronizerOutputMessage<SyncCollaborationsInput> {
const items: SyncCollaborationData[] = unsyncedCollaborations.map(
(collaboration) => ({
- entryId: collaboration.entry_id,
+ nodeId: collaboration.node_id,
workspaceId: collaboration.workspace_id,
collaboratorId: collaboration.collaborator_id,
role: collaboration.role,
@@ -68,7 +68,7 @@ export class CollaborationSynchronizer extends BaseSynchronizer<SyncCollaboratio
updatedAt: collaboration.updated_at?.toISOString() ?? null,
deletedAt: collaboration.deleted_at?.toISOString() ?? null,
deletedBy: collaboration.deleted_by ?? null,
- version: collaboration.version.toString(),
+ revision: collaboration.revision.toString(),
})
);
@@ -77,7 +77,7 @@ export class CollaborationSynchronizer extends BaseSynchronizer<SyncCollaboratio
userId: this.user.userId,
id: this.id,
items: items.map((item) => ({
- cursor: item.version,
+ cursor: item.revision,
data: item,
})),
};
diff --git a/apps/server/src/synchronizers/entry-interactions.ts b/apps/server/src/synchronizers/entry-interactions.ts
deleted file mode 100644
index 4001d3f7..00000000
--- a/apps/server/src/synchronizers/entry-interactions.ts
+++ /dev/null
@@ -1,94 +0,0 @@
-import {
- SynchronizerOutputMessage,
- SyncEntryInteractionsInput,
- SyncEntryInteractionData,
-} from '@colanode/core';
-
-import { BaseSynchronizer } from '@/synchronizers/base';
-import { Event } from '@/types/events';
-import { database } from '@/data/database';
-import { SelectEntryInteraction } from '@/data/schema';
-
-export class EntryInteractionSynchronizer extends BaseSynchronizer<SyncEntryInteractionsInput> {
- public async fetchData(): Promise<SynchronizerOutputMessage<SyncEntryInteractionsInput> | null> {
- const entryInteractions = await this.fetchEntryInteractions();
- if (entryInteractions.length === 0) {
- return null;
- }
-
- return this.buildMessage(entryInteractions);
- }
-
- public async fetchDataFromEvent(
- event: Event
- ): Promise<SynchronizerOutputMessage<SyncEntryInteractionsInput> | null> {
- if (!this.shouldFetch(event)) {
- return null;
- }
-
- const entryInteractions = await this.fetchEntryInteractions();
- if (entryInteractions.length === 0) {
- return null;
- }
-
- return this.buildMessage(entryInteractions);
- }
-
- private async fetchEntryInteractions() {
- if (this.status === 'fetching') {
- return [];
- }
-
- this.status = 'fetching';
- const entryInteractions = await database
- .selectFrom('entry_interactions')
- .selectAll()
- .where('root_id', '=', this.input.rootId)
- .where('version', '>', this.cursor)
- .orderBy('version', 'asc')
- .limit(20)
- .execute();
-
- this.status = 'pending';
- return entryInteractions;
- }
-
- private buildMessage(
- unsyncedEntryInteractions: SelectEntryInteraction[]
- ): SynchronizerOutputMessage<SyncEntryInteractionsInput> {
- const items: SyncEntryInteractionData[] = unsyncedEntryInteractions.map(
- (entryInteraction) => ({
- entryId: entryInteraction.entry_id,
- collaboratorId: entryInteraction.collaborator_id,
- firstSeenAt: entryInteraction.first_seen_at?.toISOString() ?? null,
- lastSeenAt: entryInteraction.last_seen_at?.toISOString() ?? null,
- firstOpenedAt: entryInteraction.first_opened_at?.toISOString() ?? null,
- lastOpenedAt: entryInteraction.last_opened_at?.toISOString() ?? null,
- rootId: entryInteraction.root_id,
- workspaceId: entryInteraction.workspace_id,
- version: entryInteraction.version.toString(),
- })
- );
-
- return {
- type: 'synchronizer_output',
- userId: this.user.userId,
- id: this.id,
- items: items.map((item) => ({
- cursor: item.version,
- data: item,
- })),
- };
- }
-
- private shouldFetch(event: Event) {
- if (
- event.type === 'entry_interaction_updated' &&
- event.rootId === this.input.rootId
- ) {
- return true;
- }
-
- return false;
- }
-}
diff --git a/apps/server/src/synchronizers/entry-transactions.ts b/apps/server/src/synchronizers/entry-transactions.ts
deleted file mode 100644
index b624f5be..00000000
--- a/apps/server/src/synchronizers/entry-transactions.ts
+++ /dev/null
@@ -1,143 +0,0 @@
-import {
- SynchronizerOutputMessage,
- SyncEntryTransactionsInput,
- SyncEntryTransactionData,
- TransactionOperation,
-} from '@colanode/core';
-import { encodeState } from '@colanode/crdt';
-
-import { BaseSynchronizer } from '@/synchronizers/base';
-import { Event } from '@/types/events';
-import { database } from '@/data/database';
-import { SelectEntryTransaction } from '@/data/schema';
-
-export class EntryTransactionSynchronizer extends BaseSynchronizer<SyncEntryTransactionsInput> {
- public async fetchData(): Promise<SynchronizerOutputMessage<SyncEntryTransactionsInput> | null> {
- const transactions = await this.fetchTransactions();
- if (transactions.length === 0) {
- return null;
- }
-
- return this.buildMessage(transactions);
- }
-
- public async fetchDataFromEvent(
- event: Event
- ): Promise<SynchronizerOutputMessage<SyncEntryTransactionsInput> | null> {
- if (!this.shouldFetch(event)) {
- return null;
- }
-
- const transactions = await this.fetchTransactions();
- if (transactions.length === 0) {
- return null;
- }
-
- return this.buildMessage(transactions);
- }
-
- private async fetchTransactions() {
- if (this.status === 'fetching') {
- return [];
- }
-
- this.status = 'fetching';
- const transactions = await database
- .selectFrom('entry_transactions')
- .selectAll()
- .where('root_id', '=', this.input.rootId)
- .where('version', '>', this.cursor)
- .orderBy('version', 'asc')
- .limit(20)
- .execute();
-
- this.status = 'pending';
- return transactions;
- }
-
- private buildMessage(
- unsyncedTransactions: SelectEntryTransaction[]
- ): SynchronizerOutputMessage<SyncEntryTransactionsInput> {
- const items: SyncEntryTransactionData[] = unsyncedTransactions.map(
- (transaction) => {
- if (
- transaction.operation === TransactionOperation.Create &&
- transaction.data
- ) {
- return {
- id: transaction.id,
- operation: TransactionOperation.Create,
- entryId: transaction.entry_id,
- rootId: transaction.root_id,
- workspaceId: transaction.workspace_id,
- data: encodeState(transaction.data),
- createdAt: transaction.created_at.toISOString(),
- createdBy: transaction.created_by,
- serverCreatedAt: transaction.server_created_at.toISOString(),
- version: transaction.version.toString(),
- };
- }
-
- if (
- transaction.operation === TransactionOperation.Update &&
- transaction.data
- ) {
- return {
- id: transaction.id,
- operation: TransactionOperation.Update,
- entryId: transaction.entry_id,
- rootId: transaction.root_id,
- workspaceId: transaction.workspace_id,
- data: encodeState(transaction.data),
- createdAt: transaction.created_at.toISOString(),
- createdBy: transaction.created_by,
- serverCreatedAt: transaction.server_created_at.toISOString(),
- version: transaction.version.toString(),
- };
- }
-
- if (transaction.operation === TransactionOperation.Delete) {
- return {
- id: transaction.id,
- operation: TransactionOperation.Delete,
- entryId: transaction.entry_id,
- rootId: transaction.root_id,
- workspaceId: transaction.workspace_id,
- createdAt: transaction.created_at.toISOString(),
- createdBy: transaction.created_by,
- serverCreatedAt: transaction.server_created_at.toISOString(),
- version: transaction.version.toString(),
- };
- }
-
- throw new Error('Unknown transaction type');
- }
- );
-
- return {
- type: 'synchronizer_output',
- userId: this.user.userId,
- id: this.id,
- items: items.map((item) => ({
- cursor: item.version,
- data: item,
- })),
- };
- }
-
- private shouldFetch(event: Event) {
- if (event.type === 'entry_created' && event.rootId === this.input.rootId) {
- return true;
- }
-
- if (event.type === 'entry_updated' && event.rootId === this.input.rootId) {
- return true;
- }
-
- if (event.type === 'entry_deleted' && event.rootId === this.input.rootId) {
- return true;
- }
-
- return false;
- }
-}
diff --git a/apps/server/src/synchronizers/file-interactions.ts b/apps/server/src/synchronizers/file-interactions.ts
deleted file mode 100644
index 031d865d..00000000
--- a/apps/server/src/synchronizers/file-interactions.ts
+++ /dev/null
@@ -1,94 +0,0 @@
-import {
- SynchronizerOutputMessage,
- SyncFileInteractionsInput,
- SyncFileInteractionData,
-} from '@colanode/core';
-
-import { BaseSynchronizer } from '@/synchronizers/base';
-import { Event } from '@/types/events';
-import { database } from '@/data/database';
-import { SelectFileInteraction } from '@/data/schema';
-
-export class FileInteractionSynchronizer extends BaseSynchronizer<SyncFileInteractionsInput> {
- public async fetchData(): Promise<SynchronizerOutputMessage<SyncFileInteractionsInput> | null> {
- const fileInteractions = await this.fetchFileInteractions();
- if (fileInteractions.length === 0) {
- return null;
- }
-
- return this.buildMessage(fileInteractions);
- }
-
- public async fetchDataFromEvent(
- event: Event
- ): Promise<SynchronizerOutputMessage<SyncFileInteractionsInput> | null> {
- if (!this.shouldFetch(event)) {
- return null;
- }
-
- const fileInteractions = await this.fetchFileInteractions();
- if (fileInteractions.length === 0) {
- return null;
- }
-
- return this.buildMessage(fileInteractions);
- }
-
- private async fetchFileInteractions() {
- if (this.status === 'fetching') {
- return [];
- }
-
- this.status = 'fetching';
- const fileInteractions = await database
- .selectFrom('file_interactions')
- .selectAll()
- .where('root_id', '=', this.input.rootId)
- .where('version', '>', this.cursor)
- .orderBy('version', 'asc')
- .limit(20)
- .execute();
-
- this.status = 'pending';
- return fileInteractions;
- }
-
- private buildMessage(
- unsyncedFileInteractions: SelectFileInteraction[]
- ): SynchronizerOutputMessage<SyncFileInteractionsInput> {
- const items: SyncFileInteractionData[] = unsyncedFileInteractions.map(
- (fileInteraction) => ({
- fileId: fileInteraction.file_id,
- collaboratorId: fileInteraction.collaborator_id,
- firstSeenAt: fileInteraction.first_seen_at?.toISOString() ?? null,
- lastSeenAt: fileInteraction.last_seen_at?.toISOString() ?? null,
- firstOpenedAt: fileInteraction.first_opened_at?.toISOString() ?? null,
- lastOpenedAt: fileInteraction.last_opened_at?.toISOString() ?? null,
- rootId: fileInteraction.root_id,
- workspaceId: fileInteraction.workspace_id,
- version: fileInteraction.version.toString(),
- })
- );
-
- return {
- type: 'synchronizer_output',
- userId: this.user.userId,
- id: this.id,
- items: items.map((item) => ({
- cursor: item.version,
- data: item,
- })),
- };
- }
-
- private shouldFetch(event: Event) {
- if (
- event.type === 'file_interaction_updated' &&
- event.rootId === this.input.rootId
- ) {
- return true;
- }
-
- return false;
- }
-}
diff --git a/apps/server/src/synchronizers/file-tombstones.ts b/apps/server/src/synchronizers/file-tombstones.ts
deleted file mode 100644
index 8426c151..00000000
--- a/apps/server/src/synchronizers/file-tombstones.ts
+++ /dev/null
@@ -1,88 +0,0 @@
-import {
- SynchronizerOutputMessage,
- SyncFileTombstonesInput,
- SyncFileTombstoneData,
-} from '@colanode/core';
-
-import { BaseSynchronizer } from '@/synchronizers/base';
-import { Event } from '@/types/events';
-import { database } from '@/data/database';
-import { SelectFileTombstone } from '@/data/schema';
-
-export class FileTombstoneSynchronizer extends BaseSynchronizer<SyncFileTombstonesInput> {
- public async fetchData(): Promise<SynchronizerOutputMessage<SyncFileTombstonesInput> | null> {
- const fileTombstones = await this.fetchFileTombstones();
- if (fileTombstones.length === 0) {
- return null;
- }
-
- return this.buildMessage(fileTombstones);
- }
-
- public async fetchDataFromEvent(
- event: Event
- ): Promise<SynchronizerOutputMessage<SyncFileTombstonesInput> | null> {
- if (!this.shouldFetch(event)) {
- return null;
- }
-
- const fileTombstones = await this.fetchFileTombstones();
- if (fileTombstones.length === 0) {
- return null;
- }
-
- return this.buildMessage(fileTombstones);
- }
-
- private async fetchFileTombstones() {
- if (this.status === 'fetching') {
- return [];
- }
-
- this.status = 'fetching';
- const fileTombstones = await database
- .selectFrom('file_tombstones')
- .selectAll()
- .where('root_id', '=', this.input.rootId)
- .where('version', '>', this.cursor)
- .orderBy('version', 'asc')
- .limit(20)
- .execute();
-
- this.status = 'pending';
- return fileTombstones;
- }
-
- private buildMessage(
- unsyncedFileTombstones: SelectFileTombstone[]
- ): SynchronizerOutputMessage<SyncFileTombstonesInput> {
- const items: SyncFileTombstoneData[] = unsyncedFileTombstones.map(
- (fileTombstone) => ({
- id: fileTombstone.id,
- rootId: fileTombstone.root_id,
- workspaceId: fileTombstone.workspace_id,
- deletedAt: fileTombstone.deleted_at.toISOString(),
- deletedBy: fileTombstone.deleted_by,
- version: fileTombstone.version.toString(),
- })
- );
-
- return {
- type: 'synchronizer_output',
- userId: this.user.userId,
- id: this.id,
- items: items.map((item) => ({
- cursor: item.version,
- data: item,
- })),
- };
- }
-
- private shouldFetch(event: Event) {
- if (event.type === 'file_deleted' && event.rootId === this.input.rootId) {
- return true;
- }
-
- return false;
- }
-}
diff --git a/apps/server/src/synchronizers/files.ts b/apps/server/src/synchronizers/files.ts
index b48158db..e14b3025 100644
--- a/apps/server/src/synchronizers/files.ts
+++ b/apps/server/src/synchronizers/files.ts
@@ -44,8 +44,8 @@ export class FileSynchronizer extends BaseSynchronizer<SyncFilesInput> {
.selectFrom('files')
.selectAll()
.where('root_id', '=', this.input.rootId)
- .where('version', '>', this.cursor)
- .orderBy('version', 'asc')
+ .where('revision', '>', this.cursor)
+ .orderBy('revision', 'asc')
.limit(20)
.execute();
@@ -60,7 +60,6 @@ export class FileSynchronizer extends BaseSynchronizer<SyncFilesInput> {
id: file.id,
type: file.type,
parentId: file.parent_id,
- entryId: file.entry_id,
rootId: file.root_id,
workspaceId: file.workspace_id,
name: file.name,
@@ -72,7 +71,7 @@ export class FileSynchronizer extends BaseSynchronizer<SyncFilesInput> {
createdBy: file.created_by,
updatedAt: file.updated_at?.toISOString() ?? null,
updatedBy: file.updated_by ?? null,
- version: file.version.toString(),
+ revision: file.revision.toString(),
status: file.status,
}));
@@ -81,7 +80,7 @@ export class FileSynchronizer extends BaseSynchronizer<SyncFilesInput> {
userId: this.user.userId,
id: this.id,
items: items.map((item) => ({
- cursor: item.version,
+ cursor: item.revision,
data: item,
})),
};
diff --git a/apps/server/src/synchronizers/message-interactions.ts b/apps/server/src/synchronizers/message-interactions.ts
deleted file mode 100644
index ef843458..00000000
--- a/apps/server/src/synchronizers/message-interactions.ts
+++ /dev/null
@@ -1,95 +0,0 @@
-import {
- SynchronizerOutputMessage,
- SyncMessageInteractionsInput,
- SyncMessageInteractionData,
-} from '@colanode/core';
-
-import { BaseSynchronizer } from '@/synchronizers/base';
-import { Event } from '@/types/events';
-import { database } from '@/data/database';
-import { SelectMessageInteraction } from '@/data/schema';
-
-export class MessageInteractionSynchronizer extends BaseSynchronizer<SyncMessageInteractionsInput> {
- public async fetchData(): Promise<SynchronizerOutputMessage<SyncMessageInteractionsInput> | null> {
- const messageInteractions = await this.fetchMessageInteractions();
- if (messageInteractions.length === 0) {
- return null;
- }
-
- return this.buildMessage(messageInteractions);
- }
-
- public async fetchDataFromEvent(
- event: Event
- ): Promise<SynchronizerOutputMessage<SyncMessageInteractionsInput> | null> {
- if (!this.shouldFetch(event)) {
- return null;
- }
-
- const messageInteractions = await this.fetchMessageInteractions();
- if (messageInteractions.length === 0) {
- return null;
- }
-
- return this.buildMessage(messageInteractions);
- }
-
- private async fetchMessageInteractions() {
- if (this.status === 'fetching') {
- return [];
- }
-
- this.status = 'fetching';
- const messageInteractions = await database
- .selectFrom('message_interactions')
- .selectAll()
- .where('root_id', '=', this.input.rootId)
- .where('version', '>', this.cursor)
- .orderBy('version', 'asc')
- .limit(20)
- .execute();
-
- this.status = 'pending';
- return messageInteractions;
- }
-
- private buildMessage(
- unsyncedMessageInteractions: SelectMessageInteraction[]
- ): SynchronizerOutputMessage<SyncMessageInteractionsInput> {
- const items: SyncMessageInteractionData[] = unsyncedMessageInteractions.map(
- (messageInteraction) => ({
- messageId: messageInteraction.message_id,
- collaboratorId: messageInteraction.collaborator_id,
- firstSeenAt: messageInteraction.first_seen_at?.toISOString() ?? null,
- lastSeenAt: messageInteraction.last_seen_at?.toISOString() ?? null,
- firstOpenedAt:
- messageInteraction.first_opened_at?.toISOString() ?? null,
- lastOpenedAt: messageInteraction.last_opened_at?.toISOString() ?? null,
- rootId: messageInteraction.root_id,
- workspaceId: messageInteraction.workspace_id,
- version: messageInteraction.version.toString(),
- })
- );
-
- return {
- type: 'synchronizer_output',
- userId: this.user.userId,
- id: this.id,
- items: items.map((item) => ({
- cursor: item.version,
- data: item,
- })),
- };
- }
-
- private shouldFetch(event: Event) {
- if (
- event.type === 'message_interaction_updated' &&
- event.rootId === this.input.rootId
- ) {
- return true;
- }
-
- return false;
- }
-}
diff --git a/apps/server/src/synchronizers/message-reactions.ts b/apps/server/src/synchronizers/message-reactions.ts
deleted file mode 100644
index db9e2237..00000000
--- a/apps/server/src/synchronizers/message-reactions.ts
+++ /dev/null
@@ -1,100 +0,0 @@
-import {
- SynchronizerOutputMessage,
- SyncMessageReactionsInput,
- SyncMessageReactionData,
-} from '@colanode/core';
-
-import { BaseSynchronizer } from '@/synchronizers/base';
-import { Event } from '@/types/events';
-import { database } from '@/data/database';
-import { SelectMessageReaction } from '@/data/schema';
-
-export class MessageReactionSynchronizer extends BaseSynchronizer<SyncMessageReactionsInput> {
- public async fetchData(): Promise<SynchronizerOutputMessage<SyncMessageReactionsInput> | null> {
- const messageReactions = await this.fetchMessageReactions();
- if (messageReactions.length === 0) {
- return null;
- }
-
- return this.buildMessage(messageReactions);
- }
-
- public async fetchDataFromEvent(
- event: Event
- ): Promise<SynchronizerOutputMessage<SyncMessageReactionsInput> | null> {
- if (!this.shouldFetch(event)) {
- return null;
- }
-
- const messageReactions = await this.fetchMessageReactions();
- if (messageReactions.length === 0) {
- return null;
- }
-
- return this.buildMessage(messageReactions);
- }
-
- private async fetchMessageReactions() {
- if (this.status === 'fetching') {
- return [];
- }
-
- this.status = 'fetching';
- const messageReactions = await database
- .selectFrom('message_reactions')
- .selectAll()
- .where('root_id', '=', this.input.rootId)
- .where('version', '>', this.cursor)
- .orderBy('version', 'asc')
- .limit(20)
- .execute();
-
- this.status = 'pending';
- return messageReactions;
- }
-
- private buildMessage(
- unsyncedMessageReactions: SelectMessageReaction[]
- ): SynchronizerOutputMessage<SyncMessageReactionsInput> {
- const items: SyncMessageReactionData[] = unsyncedMessageReactions.map(
- (messageReaction) => ({
- messageId: messageReaction.message_id,
- collaboratorId: messageReaction.collaborator_id,
- reaction: messageReaction.reaction,
- rootId: messageReaction.root_id,
- workspaceId: messageReaction.workspace_id,
- createdAt: messageReaction.created_at.toISOString(),
- deletedAt: messageReaction.deleted_at?.toISOString() ?? null,
- version: messageReaction.version.toString(),
- })
- );
-
- return {
- type: 'synchronizer_output',
- userId: this.user.userId,
- id: this.id,
- items: items.map((item) => ({
- cursor: item.version,
- data: item,
- })),
- };
- }
-
- private shouldFetch(event: Event) {
- if (
- event.type === 'message_reaction_created' &&
- event.rootId === this.input.rootId
- ) {
- return true;
- }
-
- if (
- event.type === 'message_reaction_deleted' &&
- event.rootId === this.input.rootId
- ) {
- return true;
- }
-
- return false;
- }
-}
diff --git a/apps/server/src/synchronizers/message-tombstones.ts b/apps/server/src/synchronizers/message-tombstones.ts
deleted file mode 100644
index 7a0938ea..00000000
--- a/apps/server/src/synchronizers/message-tombstones.ts
+++ /dev/null
@@ -1,91 +0,0 @@
-import {
- SynchronizerOutputMessage,
- SyncMessageTombstonesInput,
- SyncMessageTombstoneData,
-} from '@colanode/core';
-
-import { BaseSynchronizer } from '@/synchronizers/base';
-import { Event } from '@/types/events';
-import { database } from '@/data/database';
-import { SelectMessageTombstone } from '@/data/schema';
-
-export class MessageTombstoneSynchronizer extends BaseSynchronizer<SyncMessageTombstonesInput> {
- public async fetchData(): Promise<SynchronizerOutputMessage<SyncMessageTombstonesInput> | null> {
- const messageTombstones = await this.fetchMessageTombstones();
- if (messageTombstones.length === 0) {
- return null;
- }
-
- return this.buildMessage(messageTombstones);
- }
-
- public async fetchDataFromEvent(
- event: Event
- ): Promise<SynchronizerOutputMessage<SyncMessageTombstonesInput> | null> {
- if (!this.shouldFetch(event)) {
- return null;
- }
-
- const messageTombstones = await this.fetchMessageTombstones();
- if (messageTombstones.length === 0) {
- return null;
- }
-
- return this.buildMessage(messageTombstones);
- }
-
- private async fetchMessageTombstones() {
- if (this.status === 'fetching') {
- return [];
- }
-
- this.status = 'fetching';
- const messageTombstones = await database
- .selectFrom('message_tombstones')
- .selectAll()
- .where('root_id', '=', this.input.rootId)
- .where('version', '>', this.cursor)
- .orderBy('version', 'asc')
- .limit(20)
- .execute();
-
- this.status = 'pending';
- return messageTombstones;
- }
-
- private buildMessage(
- unsyncedMessageTombstones: SelectMessageTombstone[]
- ): SynchronizerOutputMessage<SyncMessageTombstonesInput> {
- const items: SyncMessageTombstoneData[] = unsyncedMessageTombstones.map(
- (messageTombstone) => ({
- id: messageTombstone.id,
- rootId: messageTombstone.root_id,
- workspaceId: messageTombstone.workspace_id,
- deletedAt: messageTombstone.deleted_at.toISOString(),
- deletedBy: messageTombstone.deleted_by,
- version: messageTombstone.version.toString(),
- })
- );
-
- return {
- type: 'synchronizer_output',
- userId: this.user.userId,
- id: this.id,
- items: items.map((item) => ({
- cursor: item.version,
- data: item,
- })),
- };
- }
-
- private shouldFetch(event: Event) {
- if (
- event.type === 'message_deleted' &&
- event.rootId === this.input.rootId
- ) {
- return true;
- }
-
- return false;
- }
-}
diff --git a/apps/server/src/synchronizers/messages.ts b/apps/server/src/synchronizers/messages.ts
deleted file mode 100644
index 0e5b1bdf..00000000
--- a/apps/server/src/synchronizers/messages.ts
+++ /dev/null
@@ -1,108 +0,0 @@
-import {
- SynchronizerOutputMessage,
- SyncMessagesInput,
- SyncMessageData,
-} from '@colanode/core';
-
-import { BaseSynchronizer } from '@/synchronizers/base';
-import { Event } from '@/types/events';
-import { database } from '@/data/database';
-import { SelectMessage } from '@/data/schema';
-
-export class MessageSynchronizer extends BaseSynchronizer<SyncMessagesInput> {
- public async fetchData(): Promise<SynchronizerOutputMessage<SyncMessagesInput> | null> {
- const messages = await this.fetchMessages();
- if (messages.length === 0) {
- return null;
- }
-
- return this.buildMessage(messages);
- }
-
- public async fetchDataFromEvent(
- event: Event
- ): Promise<SynchronizerOutputMessage<SyncMessagesInput> | null> {
- if (!this.shouldFetch(event)) {
- return null;
- }
-
- const messages = await this.fetchMessages();
- if (messages.length === 0) {
- return null;
- }
-
- return this.buildMessage(messages);
- }
-
- private async fetchMessages() {
- if (this.status === 'fetching') {
- return [];
- }
-
- this.status = 'fetching';
- const messages = await database
- .selectFrom('messages')
- .selectAll()
- .where('root_id', '=', this.input.rootId)
- .where('version', '>', this.cursor)
- .orderBy('version', 'asc')
- .limit(20)
- .execute();
-
- this.status = 'pending';
- return messages;
- }
-
- private buildMessage(
- unsyncedMessages: SelectMessage[]
- ): SynchronizerOutputMessage<SyncMessagesInput> {
- const items: SyncMessageData[] = unsyncedMessages.map((message) => ({
- id: message.id,
- entryId: message.entry_id,
- parentId: message.parent_id,
- rootId: message.root_id,
- workspaceId: message.workspace_id,
- attributes: message.attributes,
- createdAt: message.created_at.toISOString(),
- createdBy: message.created_by,
- updatedAt: message.updated_at?.toISOString() ?? null,
- updatedBy: message.updated_by ?? null,
- version: message.version.toString(),
- }));
-
- return {
- type: 'synchronizer_output',
- userId: this.user.userId,
- id: this.id,
- items: items.map((item) => ({
- cursor: item.version,
- data: item,
- })),
- };
- }
-
- private shouldFetch(event: Event) {
- if (
- event.type === 'message_created' &&
- event.rootId === this.input.rootId
- ) {
- return true;
- }
-
- if (
- event.type === 'message_updated' &&
- event.rootId === this.input.rootId
- ) {
- return true;
- }
-
- if (
- event.type === 'message_deleted' &&
- event.rootId === this.input.rootId
- ) {
- return true;
- }
-
- return false;
- }
-}
diff --git a/apps/server/src/synchronizers/node-interactions.ts b/apps/server/src/synchronizers/node-interactions.ts
new file mode 100644
index 00000000..e9c439da
--- /dev/null
+++ b/apps/server/src/synchronizers/node-interactions.ts
@@ -0,0 +1,94 @@
+import {
+ SynchronizerOutputMessage,
+ SyncNodeInteractionsInput,
+ SyncNodeInteractionData,
+} from '@colanode/core';
+
+import { BaseSynchronizer } from '@/synchronizers/base';
+import { Event } from '@/types/events';
+import { database } from '@/data/database';
+import { SelectNodeInteraction } from '@/data/schema';
+
+export class NodeInteractionSynchronizer extends BaseSynchronizer<SyncNodeInteractionsInput> {
+ public async fetchData(): Promise<SynchronizerOutputMessage<SyncNodeInteractionsInput> | null> {
+ const nodeInteractions = await this.fetchNodeInteractions();
+ if (nodeInteractions.length === 0) {
+ return null;
+ }
+
+ return this.buildMessage(nodeInteractions);
+ }
+
+ public async fetchDataFromEvent(
+ event: Event
+ ): Promise<SynchronizerOutputMessage<SyncNodeInteractionsInput> | null> {
+ if (!this.shouldFetch(event)) {
+ return null;
+ }
+
+ const nodeInteractions = await this.fetchNodeInteractions();
+ if (nodeInteractions.length === 0) {
+ return null;
+ }
+
+ return this.buildMessage(nodeInteractions);
+ }
+
+ private async fetchNodeInteractions() {
+ if (this.status === 'fetching') {
+ return [];
+ }
+
+ this.status = 'fetching';
+ const nodeInteractions = await database
+ .selectFrom('node_interactions')
+ .selectAll()
+ .where('root_id', '=', this.input.rootId)
+ .where('revision', '>', this.cursor)
+ .orderBy('revision', 'asc')
+ .limit(20)
+ .execute();
+
+ this.status = 'pending';
+ return nodeInteractions;
+ }
+
+ private buildMessage(
+ unsyncedNodeInteractions: SelectNodeInteraction[]
+ ): SynchronizerOutputMessage<SyncNodeInteractionsInput> {
+ const items: SyncNodeInteractionData[] = unsyncedNodeInteractions.map(
+ (nodeInteraction) => ({
+ nodeId: nodeInteraction.node_id,
+ collaboratorId: nodeInteraction.collaborator_id,
+ firstSeenAt: nodeInteraction.first_seen_at?.toISOString() ?? null,
+ lastSeenAt: nodeInteraction.last_seen_at?.toISOString() ?? null,
+ firstOpenedAt: nodeInteraction.first_opened_at?.toISOString() ?? null,
+ lastOpenedAt: nodeInteraction.last_opened_at?.toISOString() ?? null,
+ rootId: nodeInteraction.root_id,
+ workspaceId: nodeInteraction.workspace_id,
+ revision: nodeInteraction.revision.toString(),
+ })
+ );
+
+ return {
+ type: 'synchronizer_output',
+ userId: this.user.userId,
+ id: this.id,
+ items: items.map((item) => ({
+ cursor: item.revision,
+ data: item,
+ })),
+ };
+ }
+
+ private shouldFetch(event: Event) {
+ if (
+ event.type === 'node_interaction_updated' &&
+ event.rootId === this.input.rootId
+ ) {
+ return true;
+ }
+
+ return false;
+ }
+}
diff --git a/apps/server/src/synchronizers/node-reactions.ts b/apps/server/src/synchronizers/node-reactions.ts
new file mode 100644
index 00000000..0268267e
--- /dev/null
+++ b/apps/server/src/synchronizers/node-reactions.ts
@@ -0,0 +1,100 @@
+import {
+ SynchronizerOutputMessage,
+ SyncNodeReactionsInput,
+ SyncNodeReactionData,
+} from '@colanode/core';
+
+import { BaseSynchronizer } from '@/synchronizers/base';
+import { Event } from '@/types/events';
+import { database } from '@/data/database';
+import { SelectNodeReaction } from '@/data/schema';
+
+export class NodeReactionSynchronizer extends BaseSynchronizer<SyncNodeReactionsInput> {
+ public async fetchData(): Promise<SynchronizerOutputMessage<SyncNodeReactionsInput> | null> {
+ const nodeReactions = await this.fetchNodeReactions();
+ if (nodeReactions.length === 0) {
+ return null;
+ }
+
+ return this.buildMessage(nodeReactions);
+ }
+
+ public async fetchDataFromEvent(
+ event: Event
+ ): Promise<SynchronizerOutputMessage<SyncNodeReactionsInput> | null> {
+ if (!this.shouldFetch(event)) {
+ return null;
+ }
+
+ const nodeReactions = await this.fetchNodeReactions();
+ if (nodeReactions.length === 0) {
+ return null;
+ }
+
+ return this.buildMessage(nodeReactions);
+ }
+
+ private async fetchNodeReactions() {
+ if (this.status === 'fetching') {
+ return [];
+ }
+
+ this.status = 'fetching';
+ const nodeReactions = await database
+ .selectFrom('node_reactions')
+ .selectAll()
+ .where('root_id', '=', this.input.rootId)
+ .where('revision', '>', this.cursor)
+ .orderBy('revision', 'asc')
+ .limit(20)
+ .execute();
+
+ this.status = 'pending';
+ return nodeReactions;
+ }
+
+ private buildMessage(
+ unsyncedNodeReactions: SelectNodeReaction[]
+ ): SynchronizerOutputMessage<SyncNodeReactionsInput> {
+ const items: SyncNodeReactionData[] = unsyncedNodeReactions.map(
+ (nodeReaction) => ({
+ nodeId: nodeReaction.node_id,
+ collaboratorId: nodeReaction.collaborator_id,
+ reaction: nodeReaction.reaction,
+ rootId: nodeReaction.root_id,
+ workspaceId: nodeReaction.workspace_id,
+ createdAt: nodeReaction.created_at.toISOString(),
+ deletedAt: nodeReaction.deleted_at?.toISOString() ?? null,
+ revision: nodeReaction.revision.toString(),
+ })
+ );
+
+ return {
+ type: 'synchronizer_output',
+ userId: this.user.userId,
+ id: this.id,
+ items: items.map((item) => ({
+ cursor: item.revision,
+ data: item,
+ })),
+ };
+ }
+
+ private shouldFetch(event: Event) {
+ if (
+ event.type === 'node_reaction_created' &&
+ event.rootId === this.input.rootId
+ ) {
+ return true;
+ }
+
+ if (
+ event.type === 'node_reaction_deleted' &&
+ event.rootId === this.input.rootId
+ ) {
+ return true;
+ }
+
+ return false;
+ }
+}
diff --git a/apps/server/src/synchronizers/node-tombstones.ts b/apps/server/src/synchronizers/node-tombstones.ts
new file mode 100644
index 00000000..be1b96d5
--- /dev/null
+++ b/apps/server/src/synchronizers/node-tombstones.ts
@@ -0,0 +1,88 @@
+import {
+ SynchronizerOutputMessage,
+ SyncNodeTombstonesInput,
+ SyncNodeTombstoneData,
+} from '@colanode/core';
+
+import { BaseSynchronizer } from '@/synchronizers/base';
+import { Event } from '@/types/events';
+import { database } from '@/data/database';
+import { SelectNodeTombstone } from '@/data/schema';
+
+export class NodeTombstoneSynchronizer extends BaseSynchronizer<SyncNodeTombstonesInput> {
+ public async fetchData(): Promise<SynchronizerOutputMessage<SyncNodeTombstonesInput> | null> {
+ const nodeTombstones = await this.fetchNodeTombstones();
+ if (nodeTombstones.length === 0) {
+ return null;
+ }
+
+ return this.buildMessage(nodeTombstones);
+ }
+
+ public async fetchDataFromEvent(
+ event: Event
+ ): Promise<SynchronizerOutputMessage<SyncNodeTombstonesInput> | null> {
+ if (!this.shouldFetch(event)) {
+ return null;
+ }
+
+ const nodeTombstones = await this.fetchNodeTombstones();
+ if (nodeTombstones.length === 0) {
+ return null;
+ }
+
+ return this.buildMessage(nodeTombstones);
+ }
+
+ private async fetchNodeTombstones() {
+ if (this.status === 'fetching') {
+ return [];
+ }
+
+ this.status = 'fetching';
+ const nodeTombstones = await database
+ .selectFrom('node_tombstones')
+ .selectAll()
+ .where('root_id', '=', this.input.rootId)
+ .where('revision', '>', this.cursor)
+ .orderBy('revision', 'asc')
+ .limit(20)
+ .execute();
+
+ this.status = 'pending';
+ return nodeTombstones;
+ }
+
+ private buildMessage(
+ unsyncedNodeTombstones: SelectNodeTombstone[]
+ ): SynchronizerOutputMessage<SyncNodeTombstonesInput> {
+ const items: SyncNodeTombstoneData[] = unsyncedNodeTombstones.map(
+ (nodeTombstone) => ({
+ id: nodeTombstone.id,
+ rootId: nodeTombstone.root_id,
+ workspaceId: nodeTombstone.workspace_id,
+ deletedAt: nodeTombstone.deleted_at.toISOString(),
+ deletedBy: nodeTombstone.deleted_by,
+ revision: nodeTombstone.revision.toString(),
+ })
+ );
+
+ return {
+ type: 'synchronizer_output',
+ userId: this.user.userId,
+ id: this.id,
+ items: items.map((item) => ({
+ cursor: item.revision,
+ data: item,
+ })),
+ };
+ }
+
+ private shouldFetch(event: Event) {
+ if (event.type === 'node_deleted' && event.rootId === this.input.rootId) {
+ return true;
+ }
+
+ return false;
+ }
+}
diff --git a/apps/server/src/synchronizers/nodes.ts b/apps/server/src/synchronizers/nodes.ts
new file mode 100644
index 00000000..7a2b87ea
--- /dev/null
+++ b/apps/server/src/synchronizers/nodes.ts
@@ -0,0 +1,100 @@
+import {
+ SynchronizerOutputMessage,
+ SyncNodesInput,
+ SyncNodeData,
+} from '@colanode/core';
+import { encodeState } from '@colanode/crdt';
+
+import { BaseSynchronizer } from '@/synchronizers/base';
+import { Event } from '@/types/events';
+import { database } from '@/data/database';
+import { SelectNode } from '@/data/schema';
+
+export class NodeSynchronizer extends BaseSynchronizer<SyncNodesInput> {
+ public async fetchData(): Promise<SynchronizerOutputMessage<SyncNodesInput> | null> {
+ const nodes = await this.fetchNodes();
+ if (nodes.length === 0) {
+ return null;
+ }
+
+ return this.buildMessage(nodes);
+ }
+
+ public async fetchDataFromEvent(
+ event: Event
+ ): Promise<SynchronizerOutputMessage<SyncNodesInput> | null> {
+ if (!this.shouldFetch(event)) {
+ return null;
+ }
+
+ const nodes = await this.fetchNodes();
+ if (nodes.length === 0) {
+ return null;
+ }
+
+ return this.buildMessage(nodes);
+ }
+
+ private async fetchNodes() {
+ if (this.status === 'fetching') {
+ return [];
+ }
+
+ this.status = 'fetching';
+ const nodes = await database
+ .selectFrom('nodes')
+ .selectAll()
+ .where('root_id', '=', this.input.rootId)
+ .where('revision', '>', this.cursor)
+ .orderBy('revision', 'asc')
+ .limit(20)
+ .execute();
+
+ this.status = 'pending';
+ return nodes;
+ }
+
+ private buildMessage(
+ unsyncedNodes: SelectNode[]
+ ): SynchronizerOutputMessage<SyncNodesInput> {
+ const items: SyncNodeData[] = unsyncedNodes.map((node) => {
+ return {
+ id: node.id,
+ rootId: node.root_id,
+ workspaceId: node.workspace_id,
+ revision: node.revision.toString(),
+ state: encodeState(node.state),
+ createdAt: node.created_at.toISOString(),
+ createdBy: node.created_by,
+ updatedAt: node.updated_at?.toISOString() ?? null,
+ updatedBy: node.updated_by,
+ };
+ });
+
+ return {
+ type: 'synchronizer_output',
+ userId: this.user.userId,
+ id: this.id,
+ items: items.map((item) => ({
+ cursor: item.revision,
+ data: item,
+ })),
+ };
+ }
+
+ private shouldFetch(event: Event) {
+ if (event.type === 'node_created' && event.rootId === this.input.rootId) {
+ return true;
+ }
+
+ if (event.type === 'node_updated' && event.rootId === this.input.rootId) {
+ return true;
+ }
+
+ if (event.type === 'node_deleted' && event.rootId === this.input.rootId) {
+ return true;
+ }
+
+ return false;
+ }
+}
diff --git a/apps/server/src/synchronizers/users.ts b/apps/server/src/synchronizers/users.ts
index 5a172cf3..612e488a 100644
--- a/apps/server/src/synchronizers/users.ts
+++ b/apps/server/src/synchronizers/users.ts
@@ -44,8 +44,8 @@ export class UserSynchronizer extends BaseSynchronizer<SyncUsersInput> {
.selectFrom('users')
.selectAll()
.where('workspace_id', '=', this.user.workspaceId)
- .where('version', '>', this.cursor)
- .orderBy('version', 'asc')
+ .where('revision', '>', this.cursor)
+ .orderBy('revision', 'asc')
.limit(50)
.execute();
@@ -67,7 +67,7 @@ export class UserSynchronizer extends BaseSynchronizer<SyncUsersInput> {
customAvatar: user.custom_avatar,
createdAt: user.created_at.toISOString(),
updatedAt: user.updated_at?.toISOString() ?? null,
- version: user.version.toString(),
+ revision: user.revision.toString(),
status: user.status,
}));
@@ -76,7 +76,7 @@ export class UserSynchronizer extends BaseSynchronizer<SyncUsersInput> {
userId: this.user.userId,
id: this.id,
items: items.map((item) => ({
- cursor: item.version,
+ cursor: item.revision,
data: item,
})),
};
diff --git a/apps/server/src/types/api.ts b/apps/server/src/types/api.ts
index cdca5680..688cf25b 100644
--- a/apps/server/src/types/api.ts
+++ b/apps/server/src/types/api.ts
@@ -2,11 +2,3 @@ export type RequestAccount = {
id: string;
deviceId: string;
};
-
-export type OtpCodeData = {
- id: string;
- expiresAt: Date;
- accountId: string;
- otp: string;
- attempts: number;
-};
diff --git a/apps/server/src/types/entries.ts b/apps/server/src/types/entries.ts
deleted file mode 100644
index db132d17..00000000
--- a/apps/server/src/types/entries.ts
+++ /dev/null
@@ -1,74 +0,0 @@
-import { Entry, EntryAttributes } from '@colanode/core';
-
-import { SelectEntry, SelectEntryTransaction } from '@/data/schema';
-
-export type EntryCollaborator = {
- entryId: string;
- collaboratorId: string;
- role: string;
-};
-
-export type CreateEntryInput = {
- entryId: string;
- rootId: string;
- attributes: EntryAttributes;
- userId: string;
- workspaceId: string;
- ancestors: Entry[];
-};
-
-export type CreateEntryOutput = {
- entry: SelectEntry;
- transaction: SelectEntryTransaction;
-};
-
-export type UpdateEntryInput = {
- entryId: string;
- userId: string;
- workspaceId: string;
- updater: (attributes: EntryAttributes) => EntryAttributes | null;
-};
-
-export type UpdateEntryOutput = {
- entry: SelectEntry;
- transaction: SelectEntryTransaction;
-};
-
-export type ApplyCreateTransactionInput = {
- id: string;
- entryId: string;
- rootId: string;
- data: string | Uint8Array;
- createdAt: Date;
-};
-
-export type ApplyCreateTransactionOutput = {
- entry: SelectEntry;
- transaction: SelectEntryTransaction;
-};
-
-export type ApplyUpdateTransactionInput = {
- id: string;
- entryId: string;
- rootId: string;
- userId: string;
- data: string | Uint8Array;
- createdAt: Date;
-};
-
-export type ApplyUpdateTransactionOutput = {
- entry: SelectEntry;
- transaction: SelectEntryTransaction;
-};
-
-export type ApplyDeleteTransactionInput = {
- id: string;
- entryId: string;
- rootId: string;
- createdAt: Date;
-};
-
-export type ApplyDeleteTransactionOutput = {
- entry: SelectEntry;
- transaction: SelectEntryTransaction;
-};
diff --git a/apps/server/src/types/events.ts b/apps/server/src/types/events.ts
index a7b33a60..f6be2dc9 100644
--- a/apps/server/src/types/events.ts
+++ b/apps/server/src/types/events.ts
@@ -1,77 +1,43 @@
-import { EntryType } from '@colanode/core';
-
-export type EntryCreatedEvent = {
- type: 'entry_created';
- entryId: string;
- entryType: EntryType;
- rootId: string;
- workspaceId: string;
-};
-
-export type EntryUpdatedEvent = {
- type: 'entry_updated';
- entryId: string;
- entryType: EntryType;
- rootId: string;
- workspaceId: string;
-};
-
-export type EntryDeletedEvent = {
- type: 'entry_deleted';
- entryId: string;
- entryType: EntryType;
- rootId: string;
- workspaceId: string;
-};
-
-export type EntryInteractionUpdatedEvent = {
- type: 'entry_interaction_updated';
- entryId: string;
- collaboratorId: string;
- rootId: string;
- workspaceId: string;
-};
-
-export type MessageCreatedEvent = {
- type: 'message_created';
- messageId: string;
+export type NodeCreatedEvent = {
+ type: 'node_created';
+ nodeId: string;
rootId: string;
workspaceId: string;
};
-export type MessageUpdatedEvent = {
- type: 'message_updated';
- messageId: string;
+export type NodeUpdatedEvent = {
+ type: 'node_updated';
+ nodeId: string;
rootId: string;
workspaceId: string;
};
-export type MessageDeletedEvent = {
- type: 'message_deleted';
- messageId: string;
+export type NodeDeletedEvent = {
+ type: 'node_deleted';
+ nodeId: string;
rootId: string;
workspaceId: string;
};
-export type MessageReactionCreatedEvent = {
- type: 'message_reaction_created';
- messageId: string;
+export type NodeInteractionUpdatedEvent = {
+ type: 'node_interaction_updated';
+ nodeId: string;
collaboratorId: string;
rootId: string;
workspaceId: string;
};
-export type MessageReactionDeletedEvent = {
- type: 'message_reaction_deleted';
- messageId: string;
+export type NodeReactionCreatedEvent = {
+ type: 'node_reaction_created';
+ nodeId: string;
collaboratorId: string;
rootId: string;
workspaceId: string;
};
-export type MessageInteractionUpdatedEvent = {
- type: 'message_interaction_updated';
- messageId: string;
+export type NodeReactionDeletedEvent = {
+ type: 'node_reaction_deleted';
+ nodeId: string;
collaboratorId: string;
rootId: string;
workspaceId: string;
@@ -80,14 +46,14 @@ export type MessageInteractionUpdatedEvent = {
export type CollaborationCreatedEvent = {
type: 'collaboration_created';
collaboratorId: string;
- entryId: string;
+ nodeId: string;
workspaceId: string;
};
export type CollaborationUpdatedEvent = {
type: 'collaboration_updated';
collaboratorId: string;
- entryId: string;
+ nodeId: string;
workspaceId: string;
};
@@ -161,12 +127,14 @@ export type DeviceDeletedEvent = {
};
export type Event =
- | EntryCreatedEvent
- | EntryUpdatedEvent
- | EntryDeletedEvent
+ | NodeCreatedEvent
+ | NodeUpdatedEvent
+ | NodeDeletedEvent
| CollaborationCreatedEvent
| CollaborationUpdatedEvent
- | EntryInteractionUpdatedEvent
+ | NodeInteractionUpdatedEvent
+ | NodeReactionCreatedEvent
+ | NodeReactionDeletedEvent
| UserCreatedEvent
| UserUpdatedEvent
| AccountUpdatedEvent
@@ -177,10 +145,4 @@ export type Event =
| FileCreatedEvent
| FileUpdatedEvent
| FileDeletedEvent
- | FileInteractionUpdatedEvent
- | MessageCreatedEvent
- | MessageUpdatedEvent
- | MessageDeletedEvent
- | MessageReactionCreatedEvent
- | MessageReactionDeletedEvent
- | MessageInteractionUpdatedEvent;
+ | FileInteractionUpdatedEvent;
diff --git a/apps/server/src/types/nodes.ts b/apps/server/src/types/nodes.ts
new file mode 100644
index 00000000..8d32f03e
--- /dev/null
+++ b/apps/server/src/types/nodes.ts
@@ -0,0 +1,54 @@
+import { NodeAttributes, TransactionOperation } from '@colanode/core';
+
+import { SelectNode } from '@/data/schema';
+
+export type NodeCollaborator = {
+ nodeId: string;
+ collaboratorId: string;
+ role: string;
+};
+
+export type CreateNodeInput = {
+ nodeId: string;
+ rootId: string;
+ attributes: NodeAttributes;
+ userId: string;
+ workspaceId: string;
+};
+
+export type CreateNodeOutput = {
+ node: SelectNode;
+};
+
+export type UpdateNodeInput = {
+ nodeId: string;
+ userId: string;
+ workspaceId: string;
+ updater: (attributes: NodeAttributes) => NodeAttributes | null;
+};
+
+export type UpdateNodeOutput = {
+ node: SelectNode;
+};
+
+export type ApplyNodeTransactionInput = {
+ id: string;
+ nodeId: string;
+ operation: TransactionOperation;
+ data: string | Uint8Array;
+ createdAt: Date;
+};
+
+export type ApplyNodeTransactionOutput = {
+ node: SelectNode;
+};
+
+export type DeleteNodeInput = {
+ id: string;
+ rootId: string;
+ deletedAt: string;
+};
+
+export type DeleteNodeOutput = {
+ node: SelectNode;
+};
diff --git a/apps/server/src/types/otps.ts b/apps/server/src/types/otps.ts
new file mode 100644
index 00000000..8ea3a3cf
--- /dev/null
+++ b/apps/server/src/types/otps.ts
@@ -0,0 +1,11 @@
+export type AccountVerifyOtpAttributes = {
+ accountId: string;
+ attempts: number;
+};
+
+export type Otp<T> = {
+ id: string;
+ expiresAt: Date;
+ otp: string;
+ attributes: T;
+};
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 42e53f74..517305a6 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -8,25 +8,27 @@ export * from './registry/channel';
export * from './registry/chat';
export * from './registry/core';
export * from './registry/database';
-export * from './registry/fields';
+export * from './registry/database-view';
+export * from './registry/field';
+export * from './registry/field-value';
export * from './registry/folder';
export * from './registry/index';
+export * from './registry/message';
export * from './registry/page';
export * from './registry/record';
export * from './registry/space';
+export * from './registry/file';
export * from './registry/zod';
export * from './types/accounts';
export * from './types/files';
export * from './types/interactions';
export * from './types/sockets';
-export * from './types/entries';
export * from './types/servers';
export * from './types/transactions';
export * from './types/workspaces';
export * from './types/mutations';
-export * from './types/messages';
export * from './synchronizers';
-export * from './lib/entries';
+export * from './lib/nodes';
export * from './lib/texts';
export * from './lib/permissions';
export * from './types/api';
diff --git a/packages/core/src/lib/id.ts b/packages/core/src/lib/id.ts
index e03c8d65..27428173 100644
--- a/packages/core/src/lib/id.ts
+++ b/packages/core/src/lib/id.ts
@@ -18,7 +18,7 @@ export enum IdType {
DatabaseReplica = 'dr',
Record = 'rc',
Folder = 'fl',
- View = 'vw',
+ DatabaseView = 'dv',
Field = 'fd',
SelectOption = 'so',
ViewFilter = 'vf',
@@ -30,7 +30,7 @@ export enum IdType {
Icon = 'ic',
File = 'fi',
FilePlaceholder = 'fp',
- Device = 'dv',
+ Device = 'de',
Upload = 'up',
Transaction = 'tx',
Event = 'ev',
diff --git a/packages/core/src/lib/entries.ts b/packages/core/src/lib/nodes.ts
similarity index 57%
rename from packages/core/src/lib/entries.ts
rename to packages/core/src/lib/nodes.ts
index 22125faa..defea0d1 100644
--- a/packages/core/src/lib/entries.ts
+++ b/packages/core/src/lib/nodes.ts
@@ -1,17 +1,17 @@
import { generateKeyBetween } from 'fractional-indexing-jittered';
-import { Entry, EntryAttributes, EntryRole } from '../index';
+import { Node, NodeAttributes, NodeRole } from '../index';
-export const extractEntryCollaborators = (
- attributes: EntryAttributes | EntryAttributes[]
-): Record<string, EntryRole> => {
+export const extractNodeCollaborators = (
+ attributes: NodeAttributes | NodeAttributes[]
+): Record<string, NodeRole> => {
const items = Array.isArray(attributes) ? attributes : [attributes];
- const collaborators: Record<string, EntryRole> = {};
+ const collaborators: Record<string, NodeRole> = {};
for (const item of items) {
if ('collaborators' in item && item.collaborators) {
for (const [collaboratorId, role] of Object.entries(item.collaborators)) {
- collaborators[collaboratorId] = role as EntryRole;
+ collaborators[collaboratorId] = role as NodeRole;
}
}
}
@@ -19,9 +19,7 @@ export const extractEntryCollaborators = (
return collaborators;
};
-export const extractEntryName = (
- attributes: EntryAttributes
-): string | null => {
+export const extractNodeName = (attributes: NodeAttributes): string | null => {
if ('name' in attributes && attributes.name) {
return attributes.name as string;
}
@@ -29,14 +27,14 @@ export const extractEntryName = (
return null;
};
-export const extractEntryRole = (
- tree: Entry | Entry[],
+export const extractNodeRole = (
+ tree: Node | Node[],
collaboratorId: string
-): EntryRole | null => {
- const entries = Array.isArray(tree) ? tree : [tree];
- let role: EntryRole | null = null;
- for (const entry of entries) {
- const collaborators = extractEntryCollaborators(entry.attributes);
+): NodeRole | null => {
+ const nodes = Array.isArray(tree) ? tree : [tree];
+ let role: NodeRole | null = null;
+ for (const node of nodes) {
+ const collaborators = extractNodeCollaborators(node.attributes);
const collaboratorRole = collaborators[collaboratorId];
if (collaboratorRole) {
role = collaboratorRole;
diff --git a/packages/core/src/lib/permissions.ts b/packages/core/src/lib/permissions.ts
index 38c0f117..4fcd0e79 100644
--- a/packages/core/src/lib/permissions.ts
+++ b/packages/core/src/lib/permissions.ts
@@ -1,35 +1,37 @@
import { isEqual } from 'lodash-es';
-import { extractEntryRole } from './entries';
-
-import { Entry, EntryAttributes } from '../registry';
-import { WorkspaceRole } from '../types/workspaces';
-
-import { EntryRole } from '~/registry/core';
+import {
+ extractNodeRole,
+ Node,
+ NodeAttributes,
+ WorkspaceRole,
+ NodeRole,
+ NodeType,
+} from '../index';
export type UserInput = {
userId: string;
role: WorkspaceRole;
};
-export type CanCreateEntryInput = {
+export type CanCreateNodeInput = {
user: UserInput;
- root: Entry | null;
+ root: Node | null;
};
-export const canCreateEntry = (
- input: CanCreateEntryInput,
- attributes: EntryAttributes
+export const canCreateNode = (
+ input: CanCreateNodeInput,
+ type: NodeType
): boolean => {
if (input.user.role === 'none') {
return false;
}
- if (attributes.type === 'chat') {
+ if (type === 'chat') {
return true;
}
- if (attributes.type === 'space') {
+ if (type === 'space') {
return hasWorkspaceRole(input.user.role, 'collaborator');
}
@@ -38,23 +40,23 @@ export const canCreateEntry = (
return false;
}
- const rootRole = extractEntryRole(root, input.user.userId);
+ const rootRole = extractNodeRole(root, input.user.userId);
if (!rootRole) {
return false;
}
- return hasEntryRole(rootRole, 'editor');
+ return hasNodeRole(rootRole, 'editor');
};
-export type CanUpdateEntryInput = {
+export type CanUpdateNodeInput = {
user: UserInput;
- root: Entry;
- entry: Entry;
+ root: Node;
+ node: Node;
};
-export const canUpdateEntry = (
- input: CanUpdateEntryInput,
- attributes: EntryAttributes
+export const canUpdateNode = (
+ input: CanUpdateNodeInput,
+ attributes: NodeAttributes
): boolean => {
if (input.user.role === 'none') {
return false;
@@ -64,57 +66,57 @@ export const canUpdateEntry = (
return false;
}
- const rootRole = extractEntryRole(input.root, input.user.userId);
+ const rootRole = extractNodeRole(input.root, input.user.userId);
if (!rootRole) {
return false;
}
if (attributes.type === 'space') {
- if (input.entry.type !== 'space') {
+ if (input.node.type !== 'space') {
return false;
}
const afterCollaborators = attributes.collaborators;
- const beforeCollaborators = input.entry.attributes.collaborators;
+ const beforeCollaborators = input.node.attributes.collaborators;
if (!isEqual(afterCollaborators, beforeCollaborators)) {
- return hasEntryRole(rootRole, 'admin');
+ return hasNodeRole(rootRole, 'admin');
}
}
- return hasEntryRole(rootRole, 'editor');
+ return hasNodeRole(rootRole, 'editor');
};
-export type CanDeleteEntryInput = {
+export type CanDeleteNodeInput = {
user: UserInput;
- root: Entry;
- entry: Entry;
+ root: Node;
+ node: Node;
};
-export const canDeleteEntry = (input: CanDeleteEntryInput): boolean => {
+export const canDeleteNode = (input: CanDeleteNodeInput): boolean => {
if (input.user.role === 'none') {
return false;
}
- const entry = input.entry;
- if (entry.attributes.type === 'chat') {
+ const node = input.node;
+ if (node.attributes.type === 'chat') {
return false;
}
- const rootRole = extractEntryRole(input.root, input.user.userId);
+ const rootRole = extractNodeRole(input.root, input.user.userId);
if (!rootRole) {
return false;
}
- if (entry.attributes.type === 'record') {
- return input.entry.createdBy === input.user.userId;
+ if (node.attributes.type === 'record') {
+ return node.createdBy === input.user.userId;
}
- if (entry.attributes.type === 'space') {
- return hasEntryRole(rootRole, 'admin');
+ if (node.attributes.type === 'space') {
+ return hasNodeRole(rootRole, 'admin');
}
- return hasEntryRole(rootRole, 'editor');
+ return hasNodeRole(rootRole, 'editor');
};
export const hasWorkspaceRole = (
@@ -149,7 +151,7 @@ export const hasWorkspaceRole = (
return false;
};
-export const hasEntryRole = (currentRole: EntryRole, targetRole: EntryRole) => {
+export const hasNodeRole = (currentRole: NodeRole, targetRole: NodeRole) => {
if (targetRole === 'admin') {
return currentRole === 'admin';
}
@@ -178,107 +180,36 @@ export const hasEntryRole = (currentRole: EntryRole, targetRole: EntryRole) => {
return false;
};
-export type CreateMessageInput = {
- user: UserInput;
- root: Entry;
- entry: Entry;
-};
-
-export const canCreateMessage = (input: CreateMessageInput): boolean => {
- const rootRole = extractEntryRole(input.root, input.user.userId);
- if (!rootRole) {
- return false;
- }
-
- return hasEntryRole(rootRole, 'commenter');
-};
-
-export type DeleteMessageInput = {
- user: UserInput;
- root: Entry;
- entry: Entry;
- message: {
- id: string;
- createdBy: string;
- };
-};
-
-export const canDeleteMessage = (input: DeleteMessageInput): boolean => {
- const rootRole = extractEntryRole(input.root, input.user.userId);
- if (!rootRole) {
- return false;
- }
-
- if (input.message.createdBy === input.user.userId) {
- return true;
- }
-
- return hasEntryRole(rootRole, 'admin');
-};
-
-export type CanCreateMessageReactionInput = {
+export type CanCreateNodeReactionInput = {
user: UserInput;
- root: Entry;
- message: {
- id: string;
- createdBy: string;
- };
+ root: Node;
+ node: Node;
};
-export const canCreateMessageReaction = (
- input: CanCreateMessageReactionInput
+export const canCreateNodeReaction = (
+ input: CanCreateNodeReactionInput
): boolean => {
- const rootRole = extractEntryRole(input.root, input.user.userId);
- if (!rootRole) {
- return false;
- }
-
- return hasEntryRole(rootRole, 'viewer');
-};
-
-export type CreateFileInput = {
- user: UserInput;
- root: Entry;
- entry: Entry;
- file: {
- id: string;
- parentId: string;
- };
-};
-
-export const canCreateFile = (input: CreateFileInput): boolean => {
- const rootRole = extractEntryRole(input.root, input.user.userId);
+ const rootRole = extractNodeRole(input.root, input.user.userId);
if (!rootRole) {
return false;
}
- if (input.file.parentId === input.entry.id) {
- return hasEntryRole(rootRole, 'editor');
- }
-
- return hasEntryRole(rootRole, 'commenter');
+ return hasNodeRole(rootRole, 'viewer');
};
-export type DeleteFileInput = {
+export type CanDeleteNodeReactionInput = {
user: UserInput;
- root: Entry;
- entry: Entry;
- file: {
- id: string;
- parentId: string;
- createdBy: string;
- };
+ root: Node;
+ node: Node;
};
-export const canDeleteFile = (input: DeleteFileInput): boolean => {
- const rootRole = extractEntryRole(input.root, input.user.userId);
+export const canDeleteNodeReaction = (
+ input: CanDeleteNodeReactionInput
+): boolean => {
+ const rootRole = extractNodeRole(input.root, input.user.userId);
if (!rootRole) {
return false;
}
- if (input.file.createdBy === input.user.userId) {
- return true;
- }
-
- return hasEntryRole(rootRole, 'admin');
+ return hasNodeRole(rootRole, 'viewer');
};
diff --git a/packages/core/src/lib/texts.ts b/packages/core/src/lib/texts.ts
index c2935e76..868efbd6 100644
--- a/packages/core/src/lib/texts.ts
+++ b/packages/core/src/lib/texts.ts
@@ -1,6 +1,5 @@
import { Block } from '../registry/block';
-import { EntryAttributes } from '../registry';
-import { MessageAttributes, MessageType } from '../types/messages';
+import { NodeAttributes } from '../registry';
export type TextResult = {
id: string;
@@ -8,9 +7,9 @@ export type TextResult = {
text: string | null;
};
-export const extractEntryText = (
+export const extractNodeText = (
id: string,
- attributes: EntryAttributes
+ attributes: NodeAttributes
): TextResult | undefined => {
if (attributes.type === 'page') {
return {
@@ -31,21 +30,6 @@ export const extractEntryText = (
return undefined;
};
-export const extractMessageText = (
- id: string,
- attributes: MessageAttributes
-): TextResult | undefined => {
- if (attributes.type === MessageType.Standard) {
- return {
- id,
- name: null,
- text: extractBlockTexts(id, attributes.blocks),
- };
- }
-
- return undefined;
-};
-
const extractBlockTexts = (
entryId: string,
blocks: Record<string, Block> | undefined | null
diff --git a/packages/core/src/registry/chat.ts b/packages/core/src/registry/chat.ts
index c5650be0..99c07d0e 100644
--- a/packages/core/src/registry/chat.ts
+++ b/packages/core/src/registry/chat.ts
@@ -1,10 +1,10 @@
import { z } from 'zod';
-import { entryRoleEnum } from './core';
+import { nodeRoleEnum } from './core';
export const chatAttributesSchema = z.object({
type: z.literal('chat'),
- collaborators: z.record(z.string(), entryRoleEnum),
+ collaborators: z.record(z.string(), nodeRoleEnum),
});
export type ChatAttributes = z.infer<typeof chatAttributesSchema>;
diff --git a/packages/core/src/registry/core.ts b/packages/core/src/registry/core.ts
index 275bfd8f..f2fc747c 100644
--- a/packages/core/src/registry/core.ts
+++ b/packages/core/src/registry/core.ts
@@ -1,4 +1,4 @@
import { z } from 'zod';
-export type EntryRole = 'admin' | 'editor' | 'commenter' | 'viewer';
-export const entryRoleEnum = z.enum(['admin', 'editor', 'commenter', 'viewer']);
+export type NodeRole = 'admin' | 'editor' | 'commenter' | 'viewer';
+export const nodeRoleEnum = z.enum(['admin', 'editor', 'commenter', 'viewer']);
diff --git a/packages/core/src/registry/database-view.ts b/packages/core/src/registry/database-view.ts
new file mode 100644
index 00000000..64da6e13
--- /dev/null
+++ b/packages/core/src/registry/database-view.ts
@@ -0,0 +1,85 @@
+import { z } from 'zod';
+
+export const databaseViewFieldAttributesSchema = z.object({
+ id: z.string(),
+ width: z.number().nullable().optional(),
+ display: z.boolean().nullable().optional(),
+ index: z.string().nullable().optional(),
+});
+
+export type DatabaseViewFieldAttributes = z.infer<
+ typeof databaseViewFieldAttributesSchema
+>;
+
+export const databaseViewFieldFilterAttributesSchema = z.object({
+ id: z.string(),
+ fieldId: z.string(),
+ type: z.literal('field'),
+ operator: z.string(),
+ value: z
+ .union([z.string(), z.number(), z.boolean(), z.array(z.string())])
+ .nullable()
+ .optional(),
+});
+
+export type DatabaseViewFieldFilterAttributes = z.infer<
+ typeof databaseViewFieldFilterAttributesSchema
+>;
+
+export const databaseViewGroupFilterAttributesSchema = z.object({
+ id: z.string(),
+ type: z.literal('group'),
+ operator: z.enum(['and', 'or']),
+ filters: z.array(databaseViewFieldFilterAttributesSchema),
+});
+
+export type DatabaseViewGroupFilterAttributes = z.infer<
+ typeof databaseViewGroupFilterAttributesSchema
+>;
+
+export const databaseViewSortAttributesSchema = z.object({
+ id: z.string(),
+ fieldId: z.string(),
+ direction: z.enum(['asc', 'desc']),
+});
+
+export type DatabaseViewSortAttributes = z.infer<
+ typeof databaseViewSortAttributesSchema
+>;
+
+export const databaseViewFilterAttributesSchema = z.discriminatedUnion('type', [
+ databaseViewFieldFilterAttributesSchema,
+ databaseViewGroupFilterAttributesSchema,
+]);
+
+export type DatabaseViewFilterAttributes = z.infer<
+ typeof databaseViewFilterAttributesSchema
+>;
+
+export const databaseViewAttributesSchema = z.object({
+ type: z.literal('database_view'),
+ parentId: z.string(),
+ layout: z.enum(['table', 'board', 'calendar']),
+ name: z.string(),
+ avatar: z.string().nullable().optional(),
+ index: z.string(),
+ fields: z
+ .record(z.string(), databaseViewFieldAttributesSchema)
+ .optional()
+ .nullable(),
+ filters: z
+ .record(z.string(), databaseViewFilterAttributesSchema)
+ .optional()
+ .nullable(),
+ sorts: z
+ .record(z.string(), databaseViewSortAttributesSchema)
+ .optional()
+ .nullable(),
+ groupBy: z.string().nullable().optional(),
+ nameWidth: z.number().nullable().optional(),
+});
+
+export type DatabaseViewAttributes = z.infer<
+ typeof databaseViewAttributesSchema
+>;
+export type DatabaseViewLayout = 'table' | 'board' | 'calendar';
diff --git a/packages/core/src/registry/database.ts b/packages/core/src/registry/database.ts
index 9430ae1c..795236eb 100644
--- a/packages/core/src/registry/database.ts
+++ b/packages/core/src/registry/database.ts
@@ -1,74 +1,6 @@
import { z } from 'zod';
-import { fieldAttributesSchema } from './fields';
-
-export const viewFieldAttributesSchema = z.object({
- id: z.string(),
- width: z.number().nullable().optional(),
- display: z.boolean().nullable().optional(),
- index: z.string().nullable().optional(),
-});
-
-export type ViewFieldAttributes = z.infer<typeof viewFieldAttributesSchema>;
-
-export const viewFieldFilterAttributesSchema = z.object({
- id: z.string(),
- fieldId: z.string(),
- type: z.literal('field'),
- operator: z.string(),
- value: z
- .union([z.string(), z.number(), z.boolean(), z.array(z.string())])
- .nullable()
- .optional(),
-});
-
-export type ViewFieldFilterAttributes = z.infer<
- typeof viewFieldFilterAttributesSchema
->;
-
-export const viewGroupFilterAttributesSchema = z.object({
- id: z.string(),
- type: z.literal('group'),
- operator: z.enum(['and', 'or']),
- filters: z.array(viewFieldFilterAttributesSchema),
-});
-
-export type ViewGroupFilterAttributes = z.infer<
- typeof viewGroupFilterAttributesSchema
->;
-
-export const viewSortAttributesSchema = z.object({
- id: z.string(),
- fieldId: z.string(),
- direction: z.enum(['asc', 'desc']),
-});
-
-export type ViewSortAttributes = z.infer<typeof viewSortAttributesSchema>;
-
-export const viewFilterAttributesSchema = z.discriminatedUnion('type', [
- viewFieldFilterAttributesSchema,
- viewGroupFilterAttributesSchema,
-]);
-
-export type ViewFilterAttributes = z.infer<typeof viewFilterAttributesSchema>;
-
-export const viewAttributesSchema = z.object({
- id: z.string(),
- type: z.enum(['table', 'board', 'calendar']),
- name: z.string(),
- avatar: z.string().nullable().optional(),
- index: z.string(),
- fields: z.record(z.string(), viewFieldAttributesSchema).optional().nullable(),
- filters: z
- .record(z.string(), viewFilterAttributesSchema)
- .optional()
- .nullable(),
- sorts: z.record(z.string(), viewSortAttributesSchema).optional().nullable(),
- groupBy: z.string().nullable().optional(),
- nameWidth: z.number().nullable().optional(),
-});
-
-export type ViewAttributes = z.infer<typeof viewAttributesSchema>;
+import { fieldAttributesSchema } from './field';
export const databaseAttributesSchema = z.object({
type: z.literal('database'),
@@ -76,8 +8,6 @@ export const databaseAttributesSchema = z.object({
avatar: z.string().nullable().optional(),
parentId: z.string(),
fields: z.record(z.string(), fieldAttributesSchema),
- views: z.record(z.string(), viewAttributesSchema),
});
export type DatabaseAttributes = z.infer<typeof databaseAttributesSchema>;
-export type ViewType = 'table' | 'board' | 'calendar';
diff --git a/packages/core/src/registry/field-value.ts b/packages/core/src/registry/field-value.ts
new file mode 100644
index 00000000..005c9b79
--- /dev/null
+++ b/packages/core/src/registry/field-value.ts
@@ -0,0 +1,48 @@
+import { ZodText } from '@colanode/core';
+import { z } from 'zod';
+
+export const booleanFieldValueSchema = z.object({
+ type: z.literal('boolean'),
+ value: z.boolean(),
+});
+
+export type BooleanFieldValue = z.infer<typeof booleanFieldValueSchema>;
+
+export const stringFieldValueSchema = z.object({
+ type: z.literal('string'),
+ value: z.string(),
+});
+
+export type StringFieldValue = z.infer<typeof stringFieldValueSchema>;
+
+export const stringArrayFieldValueSchema = z.object({
+ type: z.literal('string_array'),
+ value: z.array(z.string()),
+});
+
+export type StringArrayFieldValue = z.infer<typeof stringArrayFieldValueSchema>;
+
+export const numberFieldValueSchema = z.object({
+ type: z.literal('number'),
+ value: z.number(),
+});
+
+export type NumberFieldValue = z.infer<typeof numberFieldValueSchema>;
+
+export const textFieldValueSchema = z.object({
+ type: z.literal('text'),
+ value: ZodText.create(),
+});
+
+export type TextFieldValue = z.infer<typeof textFieldValueSchema>;
+
+export const fieldValueSchema = z.discriminatedUnion('type', [
+ booleanFieldValueSchema,
+ stringFieldValueSchema,
+ stringArrayFieldValueSchema,
+ numberFieldValueSchema,
+ textFieldValueSchema,
+]);
+
+export type FieldValue = z.infer<typeof fieldValueSchema>;
+export type FieldValueType = FieldValue['type'];
diff --git a/packages/core/src/registry/fields.ts b/packages/core/src/registry/field.ts
similarity index 57%
rename from packages/core/src/registry/fields.ts
rename to packages/core/src/registry/field.ts
index ef367561..1b60f277 100644
--- a/packages/core/src/registry/fields.ts
+++ b/packages/core/src/registry/field.ts
@@ -1,7 +1,5 @@
import { z } from 'zod';
-import { ZodText } from './zod';
-
export const selectOptionAttributesSchema = z.object({
id: z.string(),
name: z.string(),
@@ -24,13 +22,6 @@ export type BooleanFieldAttributes = z.infer<
typeof booleanFieldAttributesSchema
>;
-export const booleanFieldValueSchema = z.object({
- type: z.literal('boolean'),
- value: z.boolean(),
-});
-
-export type BooleanFieldValue = z.infer<typeof booleanFieldValueSchema>;
-
export const collaboratorFieldAttributesSchema = z.object({
id: z.string(),
type: z.literal('collaborator'),
@@ -42,18 +33,9 @@ export type CollaboratorFieldAttributes = z.infer<
typeof collaboratorFieldAttributesSchema
>;
-export const collaboratorFieldValueSchema = z.object({
- type: z.literal('collaborator'),
- value: z.array(z.string()),
-});
-
-export type CollaboratorFieldValue = z.infer<
- typeof collaboratorFieldValueSchema
->;
-
export const createdAtFieldAttributesSchema = z.object({
id: z.string(),
- type: z.literal('createdAt'),
+ type: z.literal('created_at'),
name: z.string(),
index: z.string(),
});
@@ -62,16 +44,9 @@ export type CreatedAtFieldAttributes = z.infer<
typeof createdAtFieldAttributesSchema
>;
-export const createdAtFieldValueSchema = z.object({
- type: z.literal('createdAt'),
- value: z.string(),
-});
-
-export type CreatedAtFieldValue = z.infer<typeof createdAtFieldValueSchema>;
-
export const createdByFieldAttributesSchema = z.object({
id: z.string(),
- type: z.literal('createdBy'),
+ type: z.literal('created_by'),
name: z.string(),
index: z.string(),
});
@@ -80,13 +55,6 @@ export type CreatedByFieldAttributes = z.infer<
typeof createdByFieldAttributesSchema
>;
-export const createdByFieldValueSchema = z.object({
- type: z.literal('createdBy'),
- value: z.string(),
-});
-
-export type CreatedByFieldValue = z.infer<typeof createdByFieldValueSchema>;
-
export const dateFieldAttributesSchema = z.object({
id: z.string(),
type: z.literal('date'),
@@ -96,13 +64,6 @@ export const dateFieldAttributesSchema = z.object({
export type DateFieldAttributes = z.infer<typeof dateFieldAttributesSchema>;
-export const dateFieldValueSchema = z.object({
- type: z.literal('date'),
- value: z.string(),
-});
-
-export type DateFieldValue = z.infer<typeof dateFieldValueSchema>;
-
export const emailFieldAttributesSchema = z.object({
id: z.string(),
type: z.literal('email'),
@@ -112,13 +73,6 @@ export const emailFieldAttributesSchema = z.object({
export type EmailFieldAttributes = z.infer<typeof emailFieldAttributesSchema>;
-export const emailFieldValueSchema = z.object({
- type: z.literal('email'),
- value: z.string(),
-});
-
-export type EmailFieldValue = z.infer<typeof emailFieldValueSchema>;
-
export const fileFieldAttributesSchema = z.object({
id: z.string(),
type: z.literal('file'),
@@ -128,16 +82,9 @@ export const fileFieldAttributesSchema = z.object({
export type FileFieldAttributes = z.infer<typeof fileFieldAttributesSchema>;
-export const fileFieldValueSchema = z.object({
- type: z.literal('file'),
- value: z.array(z.string()),
-});
-
-export type FileFieldValue = z.infer<typeof fileFieldValueSchema>;
-
export const multiSelectFieldAttributesSchema = z.object({
id: z.string(),
- type: z.literal('multiSelect'),
+ type: z.literal('multi_select'),
name: z.string(),
index: z.string(),
options: z.record(z.string(), selectOptionAttributesSchema).optional(),
@@ -147,13 +94,6 @@ export type MultiSelectFieldAttributes = z.infer<
typeof multiSelectFieldAttributesSchema
>;
-export const multiSelectFieldValueSchema = z.object({
- type: z.literal('multiSelect'),
- value: z.array(z.string()),
-});
-
-export type MultiSelectFieldValue = z.infer<typeof multiSelectFieldValueSchema>;
-
export const numberFieldAttributesSchema = z.object({
id: z.string(),
type: z.literal('number'),
@@ -163,13 +103,6 @@ export const numberFieldAttributesSchema = z.object({
export type NumberFieldAttributes = z.infer<typeof numberFieldAttributesSchema>;
-export const numberFieldValueSchema = z.object({
- type: z.literal('number'),
- value: z.number(),
-});
-
-export type NumberFieldValue = z.infer<typeof numberFieldValueSchema>;
-
export const phoneFieldAttributesSchema = z.object({
id: z.string(),
type: z.literal('phone'),
@@ -179,13 +112,6 @@ export const phoneFieldAttributesSchema = z.object({
export type PhoneFieldAttributes = z.infer<typeof phoneFieldAttributesSchema>;
-export const phoneFieldValueSchema = z.object({
- type: z.literal('phone'),
- value: z.string(),
-});
-
-export type PhoneFieldValue = z.infer<typeof phoneFieldValueSchema>;
-
export const relationFieldAttributesSchema = z.object({
id: z.string(),
type: z.literal('relation'),
@@ -198,13 +124,6 @@ export type RelationFieldAttributes = z.infer<
typeof relationFieldAttributesSchema
>;
-export const relationFieldValueSchema = z.object({
- type: z.literal('relation'),
- value: z.array(z.string()),
-});
-
-export type RelationFieldValue = z.infer<typeof relationFieldValueSchema>;
-
export const rollupFieldAttributesSchema = z.object({
id: z.string(),
type: z.literal('rollup'),
@@ -214,13 +133,6 @@ export const rollupFieldAttributesSchema = z.object({
export type RollupFieldAttributes = z.infer<typeof rollupFieldAttributesSchema>;
-export const rollupFieldValueSchema = z.object({
- type: z.literal('rollup'),
- value: z.string(),
-});
-
-export type RollupFieldValue = z.infer<typeof rollupFieldValueSchema>;
-
export const selectFieldAttributesSchema = z.object({
id: z.string(),
type: z.literal('select'),
@@ -231,13 +143,6 @@ export const selectFieldAttributesSchema = z.object({
export type SelectFieldAttributes = z.infer<typeof selectFieldAttributesSchema>;
-export const selectFieldValueSchema = z.object({
- type: z.literal('select'),
- value: z.string(),
-});
-
-export type SelectFieldValue = z.infer<typeof selectFieldValueSchema>;
-
export const textFieldAttributesSchema = z.object({
id: z.string(),
type: z.literal('text'),
@@ -247,13 +152,6 @@ export const textFieldAttributesSchema = z.object({
export type TextFieldAttributes = z.infer<typeof textFieldAttributesSchema>;
-export const textFieldValueSchema = z.object({
- type: z.literal('text'),
- value: ZodText.create(),
-});
-
-export type TextFieldValue = z.infer<typeof textFieldValueSchema>;
-
export const urlFieldAttributesSchema = z.object({
id: z.string(),
type: z.literal('url'),
@@ -263,14 +161,9 @@ export const urlFieldAttributesSchema = z.object({
export type UrlFieldAttributes = z.infer<typeof urlFieldAttributesSchema>;
-export const urlFieldValueSchema = z.object({
- type: z.literal('url'),
- value: z.string(),
-});
-
export const updatedAtFieldAttributesSchema = z.object({
id: z.string(),
- type: z.literal('updatedAt'),
+ type: z.literal('updated_at'),
name: z.string(),
index: z.string(),
});
@@ -279,16 +172,9 @@ export type UpdatedAtFieldAttributes = z.infer<
typeof updatedAtFieldAttributesSchema
>;
-export const updatedAtFieldValueSchema = z.object({
- type: z.literal('updatedAt'),
- value: z.string(),
-});
-
-export type UpdatedAtFieldValue = z.infer<typeof updatedAtFieldValueSchema>;
-
export const updatedByFieldAttributesSchema = z.object({
id: z.string(),
- type: z.literal('updatedBy'),
+ type: z.literal('updated_by'),
name: z.string(),
index: z.string(),
});
@@ -297,11 +183,6 @@ export type UpdatedByFieldAttributes = z.infer<
typeof updatedByFieldAttributesSchema
>;
-export const updatedByFieldValueSchema = z.object({
- type: z.literal('updatedBy'),
- value: z.string(),
-});
-
export const fieldAttributesSchema = z.discriminatedUnion('type', [
booleanFieldAttributesSchema,
collaboratorFieldAttributesSchema,
@@ -324,26 +205,4 @@ export const fieldAttributesSchema = z.discriminatedUnion('type', [
export type FieldAttributes = z.infer<typeof fieldAttributesSchema>;
-export const fieldValueSchema = z.discriminatedUnion('type', [
- booleanFieldValueSchema,
- collaboratorFieldValueSchema,
- createdAtFieldValueSchema,
- createdByFieldValueSchema,
- dateFieldValueSchema,
- emailFieldValueSchema,
- fileFieldValueSchema,
- multiSelectFieldValueSchema,
- numberFieldValueSchema,
- phoneFieldValueSchema,
- relationFieldValueSchema,
- rollupFieldValueSchema,
- selectFieldValueSchema,
- textFieldValueSchema,
- urlFieldValueSchema,
- updatedAtFieldValueSchema,
- updatedByFieldValueSchema,
-]);
-
-export type FieldValue = z.infer<typeof fieldValueSchema>;
-
export type FieldType = Extract<FieldAttributes['type'], string>;
diff --git a/packages/core/src/registry/file.ts b/packages/core/src/registry/file.ts
new file mode 100644
index 00000000..4862273c
--- /dev/null
+++ b/packages/core/src/registry/file.ts
@@ -0,0 +1,10 @@
+import { z } from 'zod';
+
+export const fileAttributesSchema = z.object({
+ type: z.literal('file'),
+ name: z.string().optional(),
+ parentId: z.string(),
+ index: z.string().optional(),
+});
+
+export type FileAttributes = z.infer<typeof fileAttributesSchema>;
diff --git a/packages/core/src/registry/index.ts b/packages/core/src/registry/index.ts
index 7213ec10..783210e9 100644
--- a/packages/core/src/registry/index.ts
+++ b/packages/core/src/registry/index.ts
@@ -7,78 +7,107 @@ import { FolderAttributes, folderAttributesSchema } from './folder';
import { PageAttributes, pageAttributesSchema } from './page';
import { RecordAttributes, recordAttributesSchema } from './record';
import { SpaceAttributes, spaceAttributesSchema } from './space';
+import { MessageAttributes, messageAttributesSchema } from './message';
+import {
+ DatabaseViewAttributes,
+ databaseViewAttributesSchema,
+} from './database-view';
+import { FileAttributes, fileAttributesSchema } from './file';
-type EntryBase = {
+type NodeBase = {
id: string;
- parentId: string | null;
+ parentId: string;
rootId: string;
createdAt: string;
createdBy: string;
updatedAt: string | null;
updatedBy: string | null;
- transactionId: string;
};
-export type ChannelEntry = EntryBase & {
+export type ChannelNode = NodeBase & {
type: 'channel';
attributes: ChannelAttributes;
};
-export type ChatEntry = EntryBase & {
+export type ChatNode = NodeBase & {
type: 'chat';
attributes: ChatAttributes;
};
-export type DatabaseEntry = EntryBase & {
+export type DatabaseNode = NodeBase & {
type: 'database';
attributes: DatabaseAttributes;
};
-export type FolderEntry = EntryBase & {
+export type DatabaseViewNode = NodeBase & {
+ type: 'database_view';
+ attributes: DatabaseViewAttributes;
+};
+
+export type FolderNode = NodeBase & {
type: 'folder';
attributes: FolderAttributes;
};
-export type PageEntry = EntryBase & {
+export type PageNode = NodeBase & {
type: 'page';
attributes: PageAttributes;
};
-export type RecordEntry = EntryBase & {
+export type RecordNode = NodeBase & {
type: 'record';
attributes: RecordAttributes;
};
-export type SpaceEntry = EntryBase & {
+export type SpaceNode = NodeBase & {
type: 'space';
attributes: SpaceAttributes;
};
-export type EntryType = EntryAttributes['type'];
+export type MessageNode = NodeBase & {
+ type: 'message';
+ attributes: MessageAttributes;
+};
+
+export type FileNode = NodeBase & {
+ type: 'file';
+ attributes: FileAttributes;
+};
+
+export type NodeType = NodeAttributes['type'];
-export type EntryAttributes =
+export type NodeAttributes =
| SpaceAttributes
| DatabaseAttributes
| ChannelAttributes
| ChatAttributes
| FolderAttributes
| PageAttributes
- | RecordAttributes;
-
-export type Entry =
- | ChannelEntry
- | ChatEntry
- | DatabaseEntry
- | FolderEntry
- | PageEntry
- | RecordEntry
- | SpaceEntry;
-
-export const entryAttributesSchema = z.discriminatedUnion('type', [
+ | RecordAttributes
+ | MessageAttributes
+ | FileAttributes
+ | DatabaseViewAttributes;
+
+export type Node =
+ | SpaceNode
+ | DatabaseNode
+ | DatabaseViewNode
+ | ChannelNode
+ | ChatNode
+ | FolderNode
+ | PageNode
+ | RecordNode
+ | MessageNode
+ | FileNode;
+
+export const nodeAttributesSchema = z.discriminatedUnion('type', [
channelAttributesSchema,
chatAttributesSchema,
databaseAttributesSchema,
+ databaseViewAttributesSchema,
+ fileAttributesSchema,
folderAttributesSchema,
+ messageAttributesSchema,
pageAttributesSchema,
recordAttributesSchema,
spaceAttributesSchema,
diff --git a/packages/core/src/registry/message.ts b/packages/core/src/registry/message.ts
new file mode 100644
index 00000000..32b004d0
--- /dev/null
+++ b/packages/core/src/registry/message.ts
@@ -0,0 +1,14 @@
+import { z } from 'zod';
+
+import { blockSchema } from './block';
+
+export const messageAttributesSchema = z.object({
+ type: z.literal('message'),
+ subtype: z.enum(['standard']),
+ name: z.string().optional(),
+ parentId: z.string(),
+ referenceId: z.string().nullable().optional(),
+ content: z.record(blockSchema).optional().nullable(),
+});
+
+export type MessageAttributes = z.infer<typeof messageAttributesSchema>;
diff --git a/packages/core/src/registry/record.ts b/packages/core/src/registry/record.ts
index eb43d01c..bccd3908 100644
--- a/packages/core/src/registry/record.ts
+++ b/packages/core/src/registry/record.ts
@@ -1,7 +1,7 @@
import { z } from 'zod';
import { blockSchema } from './block';
-import { fieldValueSchema } from './fields';
+import { fieldValueSchema } from './field-value';
export const recordAttributesSchema = z.object({
type: z.literal('record'),
diff --git a/packages/core/src/registry/space.ts b/packages/core/src/registry/space.ts
index 2c18d09a..4c81f7d2 100644
--- a/packages/core/src/registry/space.ts
+++ b/packages/core/src/registry/space.ts
@@ -1,13 +1,13 @@
import { z } from 'zod';
-import { entryRoleEnum } from './core';
+import { nodeRoleEnum } from './core';
export const spaceAttributesSchema = z.object({
type: z.literal('space'),
name: z.string(),
description: z.string().nullable().optional(),
avatar: z.string().nullable().optional(),
- collaborators: z.record(z.string(), entryRoleEnum),
+ collaborators: z.record(z.string(), nodeRoleEnum),
visibility: z.enum(['public', 'private']).default('private'),
});
diff --git a/packages/core/src/synchronizers/collaborations.ts b/packages/core/src/synchronizers/collaborations.ts
index b214d4ff..4a41169d 100644
--- a/packages/core/src/synchronizers/collaborations.ts
+++ b/packages/core/src/synchronizers/collaborations.ts
@@ -1,4 +1,4 @@
-import { EntryRole } from '../registry/core';
+import { NodeRole } from '../registry/core';
export type SyncCollaborationsInput = {
type: 'collaborations';
@@ -6,16 +6,16 @@ export type SyncCollaborationsInput = {
export type SyncCollaborationData = {
collaboratorId: string;
- entryId: string;
+ nodeId: string;
workspaceId: string;
- role: EntryRole;
+ role: NodeRole;
createdAt: string;
createdBy: string;
updatedAt: string | null;
updatedBy: string | null;
deletedAt: string | null;
deletedBy: string | null;
- version: string;
+ revision: string;
};
declare module '@colanode/core' {
diff --git a/packages/core/src/synchronizers/entry-interactions.ts b/packages/core/src/synchronizers/entry-interactions.ts
deleted file mode 100644
index 37de7b44..00000000
--- a/packages/core/src/synchronizers/entry-interactions.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-export type SyncEntryInteractionsInput = {
- type: 'entry_interactions';
- rootId: string;
-};
-
-export type SyncEntryInteractionData = {
- entryId: string;
- collaboratorId: string;
- firstSeenAt: string | null;
- lastSeenAt: string | null;
- firstOpenedAt: string | null;
- lastOpenedAt: string | null;
- rootId: string;
- workspaceId: string;
- version: string;
-};
-
-declare module '@colanode/core' {
- interface SynchronizerMap {
- entry_interactions: {
- input: SyncEntryInteractionsInput;
- data: SyncEntryInteractionData;
- };
- }
-}
diff --git a/packages/core/src/synchronizers/entry-transactions.ts b/packages/core/src/synchronizers/entry-transactions.ts
deleted file mode 100644
index 1478debe..00000000
--- a/packages/core/src/synchronizers/entry-transactions.ts
+++ /dev/null
@@ -1,58 +0,0 @@
-import { TransactionOperation } from '../types/transactions';
-
-export type SyncEntryTransactionsInput = {
- type: 'entry_transactions';
- rootId: string;
-};
-
-export type SyncCreateEntryTransactionData = {
- id: string;
- operation: TransactionOperation.Create;
- entryId: string;
- rootId: string;
- workspaceId: string;
- data: string;
- createdAt: string;
- createdBy: string;
- serverCreatedAt: string;
- version: string;
-};
-
-export type SyncUpdateEntryTransactionData = {
- id: string;
- operation: TransactionOperation.Update;
- entryId: string;
- rootId: string;
- workspaceId: string;
- data: string;
- createdAt: string;
- createdBy: string;
- serverCreatedAt: string;
- version: string;
-};
-
-export type SyncDeleteEntryTransactionData = {
- id: string;
- operation: TransactionOperation.Delete;
- entryId: string;
- rootId: string;
- workspaceId: string;
- createdAt: string;
- createdBy: string;
- serverCreatedAt: string;
- version: string;
-};
-
-export type SyncEntryTransactionData =
- | SyncCreateEntryTransactionData
- | SyncUpdateEntryTransactionData
- | SyncDeleteEntryTransactionData;
-
-declare module '@colanode/core' {
- interface SynchronizerMap {
- entry_transactions: {
- input: SyncEntryTransactionsInput;
- data: SyncEntryTransactionData;
- };
- }
-}
diff --git a/packages/core/src/synchronizers/file-tombstones.ts b/packages/core/src/synchronizers/file-tombstones.ts
deleted file mode 100644
index c9d4c453..00000000
--- a/packages/core/src/synchronizers/file-tombstones.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-export type SyncFileTombstonesInput = {
- type: 'file_tombstones';
- rootId: string;
-};
-
-export type SyncFileTombstoneData = {
- id: string;
- rootId: string;
- workspaceId: string;
- deletedBy: string;
- deletedAt: string;
- version: string;
-};
-
-declare module '@colanode/core' {
- interface SynchronizerMap {
- file_tombstones: {
- input: SyncFileTombstonesInput;
- data: SyncFileTombstoneData;
- };
- }
-}
diff --git a/packages/core/src/synchronizers/files.ts b/packages/core/src/synchronizers/files.ts
index 4518ea44..e81b7ff0 100644
--- a/packages/core/src/synchronizers/files.ts
+++ b/packages/core/src/synchronizers/files.ts
@@ -9,9 +9,9 @@ export type SyncFileData = {
id: string;
type: FileType;
parentId: string;
- entryId: string;
rootId: string;
workspaceId: string;
+ revision: string;
name: string;
originalName: string;
mimeType: string;
@@ -22,7 +22,6 @@ export type SyncFileData = {
createdBy: string;
updatedAt: string | null;
updatedBy: string | null;
- version: string;
};
declare module '@colanode/core' {
diff --git a/packages/core/src/synchronizers/index.ts b/packages/core/src/synchronizers/index.ts
index f162bedc..c8d525a9 100644
--- a/packages/core/src/synchronizers/index.ts
+++ b/packages/core/src/synchronizers/index.ts
@@ -1,14 +1,10 @@
-export * from './messages';
-export * from './entry-transactions';
+export * from './nodes';
export * from './users';
export * from './files';
-export * from './message-reactions';
-export * from './message-interactions';
-export * from './file-interactions';
-export * from './entry-interactions';
+export * from './node-reactions';
+export * from './node-interactions';
+export * from './node-tombstones';
export * from './collaborations';
-export * from './message-tombstones';
-export * from './file-tombstones';
// eslint-disable-next-line @typescript-eslint/no-empty-object-type
export interface SynchronizerMap {}
diff --git a/packages/core/src/synchronizers/message-interactions.ts b/packages/core/src/synchronizers/message-interactions.ts
deleted file mode 100644
index c843992f..00000000
--- a/packages/core/src/synchronizers/message-interactions.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-export type SyncMessageInteractionsInput = {
- type: 'message_interactions';
- rootId: string;
-};
-
-export type SyncMessageInteractionData = {
- messageId: string;
- collaboratorId: string;
- firstSeenAt: string | null;
- lastSeenAt: string | null;
- firstOpenedAt: string | null;
- lastOpenedAt: string | null;
- rootId: string;
- workspaceId: string;
- version: string;
-};
-
-declare module '@colanode/core' {
- interface SynchronizerMap {
- message_interactions: {
- input: SyncMessageInteractionsInput;
- data: SyncMessageInteractionData;
- };
- }
-}
diff --git a/packages/core/src/synchronizers/message-reactions.ts b/packages/core/src/synchronizers/message-reactions.ts
deleted file mode 100644
index d6aa3f3d..00000000
--- a/packages/core/src/synchronizers/message-reactions.ts
+++ /dev/null
@@ -1,24 +0,0 @@
-export type SyncMessageReactionsInput = {
- type: 'message_reactions';
- rootId: string;
-};
-
-export type SyncMessageReactionData = {
- messageId: string;
- collaboratorId: string;
- reaction: string;
- rootId: string;
- workspaceId: string;
- createdAt: string;
- deletedAt: string | null;
- version: string;
-};
-
-declare module '@colanode/core' {
- interface SynchronizerMap {
- message_reactions: {
- input: SyncMessageReactionsInput;
- data: SyncMessageReactionData;
- };
- }
-}
diff --git a/packages/core/src/synchronizers/message-tombstones.ts b/packages/core/src/synchronizers/message-tombstones.ts
deleted file mode 100644
index c4e074f5..00000000
--- a/packages/core/src/synchronizers/message-tombstones.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-export type SyncMessageTombstonesInput = {
- type: 'message_tombstones';
- rootId: string;
-};
-
-export type SyncMessageTombstoneData = {
- id: string;
- rootId: string;
- workspaceId: string;
- deletedAt: string;
- deletedBy: string;
- version: string;
-};
-
-declare module '@colanode/core' {
- interface SynchronizerMap {
- message_tombstones: {
- input: SyncMessageTombstonesInput;
- data: SyncMessageTombstoneData;
- };
- }
-}
diff --git a/packages/core/src/synchronizers/messages.ts b/packages/core/src/synchronizers/messages.ts
deleted file mode 100644
index 42ffe68d..00000000
--- a/packages/core/src/synchronizers/messages.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-import { MessageAttributes } from '../types/messages';
-
-export type SyncMessagesInput = {
- type: 'messages';
- rootId: string;
-};
-
-export type SyncMessageData = {
- id: string;
- parentId: string;
- entryId: string;
- rootId: string;
- workspaceId: string;
- attributes: MessageAttributes;
- createdAt: string;
- createdBy: string;
- updatedAt: string | null;
- updatedBy: string | null;
- version: string;
-};
-
-declare module '@colanode/core' {
- interface SynchronizerMap {
- messages: {
- input: SyncMessagesInput;
- data: SyncMessageData;
- };
- }
-}
diff --git a/packages/core/src/synchronizers/file-interactions.ts b/packages/core/src/synchronizers/node-interactions.ts
similarity index 53%
rename from packages/core/src/synchronizers/file-interactions.ts
rename to packages/core/src/synchronizers/node-interactions.ts
index 4bb69cc4..4f289a30 100644
--- a/packages/core/src/synchronizers/file-interactions.ts
+++ b/packages/core/src/synchronizers/node-interactions.ts
@@ -1,25 +1,25 @@
-export type SyncFileInteractionsInput = {
- type: 'file_interactions';
+export type SyncNodeInteractionsInput = {
+ type: 'node_interactions';
rootId: string;
};
-export type SyncFileInteractionData = {
- fileId: string;
+export type SyncNodeInteractionData = {
+ nodeId: string;
collaboratorId: string;
+ rootId: string;
+ workspaceId: string;
+ revision: string;
firstSeenAt: string | null;
lastSeenAt: string | null;
firstOpenedAt: string | null;
lastOpenedAt: string | null;
- rootId: string;
- workspaceId: string;
- version: string;
};
declare module '@colanode/core' {
interface SynchronizerMap {
- file_interactions: {
- input: SyncFileInteractionsInput;
- data: SyncFileInteractionData;
+ node_interactions: {
+ input: SyncNodeInteractionsInput;
+ data: SyncNodeInteractionData;
};
}
}
diff --git a/packages/core/src/synchronizers/node-reactions.ts b/packages/core/src/synchronizers/node-reactions.ts
new file mode 100644
index 00000000..f3782020
--- /dev/null
+++ b/packages/core/src/synchronizers/node-reactions.ts
@@ -0,0 +1,24 @@
+export type SyncNodeReactionsInput = {
+ type: 'node_reactions';
+ rootId: string;
+};
+
+export type SyncNodeReactionData = {
+ nodeId: string;
+ collaboratorId: string;
+ reaction: string;
+ rootId: string;
+ workspaceId: string;
+ revision: string;
+ createdAt: string;
+ deletedAt: string | null;
+};
+
+declare module '@colanode/core' {
+ interface SynchronizerMap {
+ node_reactions: {
+ input: SyncNodeReactionsInput;
+ data: SyncNodeReactionData;
+ };
+ }
+}
diff --git a/packages/core/src/synchronizers/node-tombstones.ts b/packages/core/src/synchronizers/node-tombstones.ts
new file mode 100644
index 00000000..0edd529d
--- /dev/null
+++ b/packages/core/src/synchronizers/node-tombstones.ts
@@ -0,0 +1,22 @@
+export type SyncNodeTombstonesInput = {
+ type: 'node_tombstones';
+ rootId: string;
+};
+
+export type SyncNodeTombstoneData = {
+ id: string;
+ rootId: string;
+ workspaceId: string;
+ deletedBy: string;
+ deletedAt: string;
+ revision: string;
+};
+
+declare module '@colanode/core' {
+ interface SynchronizerMap {
+ node_tombstones: {
+ input: SyncNodeTombstonesInput;
+ data: SyncNodeTombstoneData;
+ };
+ }
+}
diff --git a/packages/core/src/synchronizers/nodes.ts b/packages/core/src/synchronizers/nodes.ts
new file mode 100644
index 00000000..d0069e8f
--- /dev/null
+++ b/packages/core/src/synchronizers/nodes.ts
@@ -0,0 +1,25 @@
+export type SyncNodesInput = {
+ type: 'nodes';
+ rootId: string;
+};
+
+export type SyncNodeData = {
+ id: string;
+ rootId: string;
+ workspaceId: string;
+ revision: string;
+ state: string;
+ createdAt: string;
+ createdBy: string;
+ updatedAt: string | null;
+ updatedBy: string | null;
+};
+
+declare module '@colanode/core' {
+ interface SynchronizerMap {
+ nodes: {
+ input: SyncNodesInput;
+ data: SyncNodeData;
+ };
+ }
+}
diff --git a/packages/core/src/synchronizers/users.ts b/packages/core/src/synchronizers/users.ts
index e0d2ec52..26c04ab0 100644
--- a/packages/core/src/synchronizers/users.ts
+++ b/packages/core/src/synchronizers/users.ts
@@ -15,7 +15,7 @@ export type SyncUserData = {
customAvatar: string | null;
createdAt: string;
updatedAt: string | null;
- version: string;
+ revision: string;
status: UserStatus;
};
diff --git a/packages/core/src/types/entries.ts b/packages/core/src/types/entries.ts
deleted file mode 100644
index d4f09a08..00000000
--- a/packages/core/src/types/entries.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-import { EntryAttributes } from '../registry';
-
-export type EntryOutput = {
- id: string;
- workspaceId: string;
- parentId: string | null;
- type: string;
- attributes: EntryAttributes;
- state: string;
- createdAt: string;
- createdBy: string;
- updatedAt?: string | null;
- updatedBy?: string | null;
- transactionId: string;
-};
diff --git a/packages/core/src/types/messages.ts b/packages/core/src/types/messages.ts
deleted file mode 100644
index c59f2b06..00000000
--- a/packages/core/src/types/messages.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-import { Block } from '../registry/block';
-
-export enum MessageType {
- Standard = 1,
-}
-
-export type StandardMessageAttributes = {
- type: MessageType.Standard;
- blocks: Record<string, Block>;
- referenceId?: string | null;
-};
-
-export type MessageAttributes = StandardMessageAttributes;
diff --git a/packages/core/src/types/mutations.ts b/packages/core/src/types/mutations.ts
index 0f5734f5..6ba4bf3f 100644
--- a/packages/core/src/types/mutations.ts
+++ b/packages/core/src/types/mutations.ts
@@ -1,10 +1,5 @@
import { FileType } from './files';
-import { MessageAttributes } from './messages';
-import {
- LocalCreateTransaction,
- LocalDeleteTransaction,
- LocalUpdateTransaction,
-} from './transactions';
+import { LocalNodeTransaction } from './transactions';
export type SyncMutationsInput = {
mutations: Mutation[];
@@ -30,7 +25,6 @@ export type CreateFileMutationData = {
id: string;
type: FileType;
parentId: string;
- entryId: string;
rootId: string;
name: string;
originalName: string;
@@ -45,150 +39,75 @@ export type CreateFileMutation = MutationBase & {
data: CreateFileMutationData;
};
-export type DeleteFileMutationData = {
- id: string;
- rootId: string;
- deletedAt: string;
-};
-
-export type DeleteFileMutation = MutationBase & {
- type: 'delete_file';
- data: DeleteFileMutationData;
-};
-
-export type ApplyCreateTransactionMutation = MutationBase & {
- type: 'apply_create_transaction';
- data: LocalCreateTransaction;
-};
-
-export type ApplyUpdateTransactionMutation = MutationBase & {
- type: 'apply_update_transaction';
- data: LocalUpdateTransaction;
-};
-
-export type ApplyDeleteTransactionMutation = MutationBase & {
- type: 'apply_delete_transaction';
- data: LocalDeleteTransaction;
-};
-
-export type CreateMessageMutationData = {
- id: string;
- entryId: string;
- parentId: string;
- attributes: MessageAttributes;
- rootId: string;
- createdAt: string;
-};
-
-export type CreateMessageMutation = MutationBase & {
- type: 'create_message';
- data: CreateMessageMutationData;
+export type ApplyNodeTransactionMutation = MutationBase & {
+ type: 'apply_node_transaction';
+ data: LocalNodeTransaction;
};
-export type DeleteMessageMutationData = {
+export type DeleteNodeMutationData = {
id: string;
rootId: string;
deletedAt: string;
};
-export type DeleteMessageMutation = MutationBase & {
- type: 'delete_message';
- data: DeleteMessageMutationData;
+export type DeleteNodeMutation = MutationBase & {
+ type: 'delete_node';
+ data: DeleteNodeMutationData;
};
-export type CreateMessageReactionMutationData = {
- messageId: string;
+export type CreateNodeReactionMutationData = {
+ nodeId: string;
reaction: string;
rootId: string;
createdAt: string;
};
-export type CreateMessageReactionMutation = MutationBase & {
- type: 'create_message_reaction';
- data: CreateMessageReactionMutationData;
+export type CreateNodeReactionMutation = MutationBase & {
+ type: 'create_node_reaction';
+ data: CreateNodeReactionMutationData;
};
-export type MarkMessageSeenMutationData = {
- messageId: string;
- collaboratorId: string;
- seenAt: string;
-};
-
-export type MarkMessageSeenMutation = MutationBase & {
- type: 'mark_message_seen';
- data: MarkMessageSeenMutationData;
-};
-
-export type DeleteMessageReactionMutationData = {
- messageId: string;
+export type DeleteNodeReactionMutationData = {
+ nodeId: string;
reaction: string;
rootId: string;
deletedAt: string;
};
-export type DeleteMessageReactionMutation = MutationBase & {
- type: 'delete_message_reaction';
- data: DeleteMessageReactionMutationData;
-};
-
-export type MarkFileSeenMutationData = {
- fileId: string;
- collaboratorId: string;
- seenAt: string;
-};
-
-export type MarkFileSeenMutation = MutationBase & {
- type: 'mark_file_seen';
- data: MarkFileSeenMutationData;
-};
-
-export type MarkFileOpenedMutationData = {
- fileId: string;
- collaboratorId: string;
- openedAt: string;
-};
-
-export type MarkFileOpenedMutation = MutationBase & {
- type: 'mark_file_opened';
- data: MarkFileOpenedMutationData;
+export type DeleteNodeReactionMutation = MutationBase & {
+ type: 'delete_node_reaction';
+ data: DeleteNodeReactionMutationData;
};
-export type MarkEntrySeenMutationData = {
- entryId: string;
+export type MarkNodeSeenMutationData = {
+ nodeId: string;
collaboratorId: string;
seenAt: string;
};
-export type MarkEntrySeenMutation = MutationBase & {
- type: 'mark_entry_seen';
- data: MarkEntrySeenMutationData;
+export type MarkNodeSeenMutation = MutationBase & {
+ type: 'mark_node_seen';
+ data: MarkNodeSeenMutationData;
};
-export type MarkEntryOpenedMutationData = {
- entryId: string;
+export type MarkNodeOpenedMutationData = {
+ nodeId: string;
collaboratorId: string;
openedAt: string;
};
-export type MarkEntryOpenedMutation = MutationBase & {
- type: 'mark_entry_opened';
- data: MarkEntryOpenedMutationData;
+export type MarkNodeOpenedMutation = MutationBase & {
+ type: 'mark_node_opened';
+ data: MarkNodeOpenedMutationData;
};
export type Mutation =
| CreateFileMutation
- | DeleteFileMutation
- | ApplyCreateTransactionMutation
- | ApplyUpdateTransactionMutation
- | ApplyDeleteTransactionMutation
- | CreateMessageMutation
- | DeleteMessageMutation
- | CreateMessageReactionMutation
- | DeleteMessageReactionMutation
- | MarkMessageSeenMutation
- | MarkFileSeenMutation
- | MarkFileOpenedMutation
- | MarkEntrySeenMutation
- | MarkEntryOpenedMutation;
+ | ApplyNodeTransactionMutation
+ | DeleteNodeMutation
+ | CreateNodeReactionMutation
+ | DeleteNodeReactionMutation
+ | MarkNodeSeenMutation
+ | MarkNodeOpenedMutation;
export type MutationType = Mutation['type'];
diff --git a/packages/core/src/types/transactions.ts b/packages/core/src/types/transactions.ts
index d2c3c787..0fed71c5 100644
--- a/packages/core/src/types/transactions.ts
+++ b/packages/core/src/types/transactions.ts
@@ -1,39 +1,12 @@
export enum TransactionOperation {
Create = 1,
Update = 2,
- Delete = 3,
}
-export type LocalTransaction =
- | LocalCreateTransaction
- | LocalUpdateTransaction
- | LocalDeleteTransaction;
-
-export type LocalCreateTransaction = {
- id: string;
- entryId: string;
- rootId: string;
- operation: TransactionOperation.Create;
- data: string;
- createdAt: string;
- createdBy: string;
-};
-
-export type LocalUpdateTransaction = {
+export type LocalNodeTransaction = {
id: string;
- entryId: string;
- rootId: string;
- operation: TransactionOperation.Update;
+ nodeId: string;
+ operation: TransactionOperation;
data: string;
createdAt: string;
- createdBy: string;
-};
-
-export type LocalDeleteTransaction = {
- id: string;
- entryId: string;
- rootId: string;
- operation: TransactionOperation.Delete;
- createdAt: string;
- createdBy: string;
};
diff --git a/packages/core/src/types/workspaces.ts b/packages/core/src/types/workspaces.ts
index c05780db..aa7e9f31 100644
--- a/packages/core/src/types/workspaces.ts
+++ b/packages/core/src/types/workspaces.ts
@@ -1,5 +1,3 @@
-import { EntryOutput } from './entries.js';
-
export type WorkspaceRole =
| 'owner'
| 'admin'
@@ -62,7 +60,3 @@ export type UsersInviteOutput = {
export type UserRoleUpdateInput = {
role: WorkspaceRole;
};
-
-export type UserRoleUpdateOutput = {
- user: EntryOutput;
-};