Compare commits

...

7 Commits

Author SHA1 Message Date
Guido D'Orsi
74b984fbe6 Merge pull request #1230 from garden-co/changeset-release/main
Version Packages
2025-01-21 16:53:36 +01:00
github-actions[bot]
f8e00204b4 Version Packages 2025-01-21 15:49:31 +00:00
Guido D'Orsi
76543df765 Merge pull request #1229 from garden-co/revert-custom-logger
Revert custom logger
2025-01-21 16:48:17 +01:00
Guido D'Orsi
15d4b2a5f7 chore: changeset 2025-01-21 16:44:37 +01:00
Guido D'Orsi
2e67f91fe0 Revert "feat: make it possible to customize the logger in cojson"
This reverts commit 5863badbb0.
2025-01-21 16:42:54 +01:00
Benjamin S. Leveritt
0eb21a3471 Merge pull request #1216 from boorad/feat/demo-auth-theme
fix: phone theme drives light/dark mode in Demo Auth
2025-01-20 13:27:19 +00:00
Brad Anderson
aabe7bef34 fix: phone theme drives light/dark mode in Demo Auth 2025-01-17 23:07:38 -05:00
111 changed files with 641 additions and 450 deletions

View File

@@ -1,5 +1,14 @@
# chat-rn-clerk # chat-rn-clerk
## 1.0.53
### Patch Changes
- jazz-react-native@0.9.12
- jazz-react-native-auth-clerk@0.9.12
- jazz-tools@0.9.12
- jazz-react-native-media-images@0.9.12
## 1.0.52 ## 1.0.52
### Patch Changes ### Patch Changes

View File

@@ -1,7 +1,7 @@
{ {
"name": "chat-rn-clerk", "name": "chat-rn-clerk",
"main": "index.js", "main": "index.js",
"version": "1.0.52", "version": "1.0.53",
"scripts": { "scripts": {
"build": "expo export -p ios", "build": "expo export -p ios",
"start": "expo start", "start": "expo start",

View File

@@ -1,5 +1,12 @@
# chat-rn # chat-rn
## 1.0.50
### Patch Changes
- jazz-react-native@0.9.12
- jazz-tools@0.9.12
## 1.0.49 ## 1.0.49
### Patch Changes ### Patch Changes

View File

@@ -1,6 +1,6 @@
{ {
"name": "chat-rn", "name": "chat-rn",
"version": "1.0.49", "version": "1.0.50",
"main": "index.js", "main": "index.js",
"scripts": { "scripts": {
"build": "expo export -p ios", "build": "expo export -p ios",

View File

@@ -1,5 +1,13 @@
# chat-vue # chat-vue
## 0.0.37
### Patch Changes
- jazz-browser@0.9.12
- jazz-tools@0.9.12
- jazz-vue@0.9.12
## 0.0.36 ## 0.0.36
### Patch Changes ### Patch Changes

View File

@@ -1,6 +1,6 @@
{ {
"name": "chat-vue", "name": "chat-vue",
"version": "0.0.36", "version": "0.0.37",
"private": true, "private": true,
"type": "module", "type": "module",
"scripts": { "scripts": {

View File

@@ -1,5 +1,13 @@
# jazz-example-chat # jazz-example-chat
## 0.0.133
### Patch Changes
- jazz-react@0.9.12
- jazz-tools@0.9.12
- jazz-browser-media-images@0.9.12
## 0.0.132 ## 0.0.132
### Patch Changes ### Patch Changes

View File

@@ -1,7 +1,7 @@
{ {
"name": "jazz-example-chat", "name": "jazz-example-chat",
"private": true, "private": true,
"version": "0.0.132", "version": "0.0.133",
"type": "module", "type": "module",
"scripts": { "scripts": {
"dev": "vite", "dev": "vite",

View File

@@ -1,5 +1,13 @@
# minimal-auth-clerk # minimal-auth-clerk
## 0.0.32
### Patch Changes
- jazz-react@0.9.12
- jazz-react-auth-clerk@0.9.12
- jazz-tools@0.9.12
## 0.0.31 ## 0.0.31
### Patch Changes ### Patch Changes

View File

@@ -1,7 +1,7 @@
{ {
"name": "clerk", "name": "clerk",
"private": true, "private": true,
"version": "0.0.31", "version": "0.0.32",
"type": "module", "type": "module",
"scripts": { "scripts": {
"dev": "vite", "dev": "vite",
@@ -13,7 +13,7 @@
"dependencies": { "dependencies": {
"@clerk/clerk-react": "^5.4.1", "@clerk/clerk-react": "^5.4.1",
"jazz-react": "workspace:*", "jazz-react": "workspace:*",
"jazz-react-auth-clerk": "workspace:0.9.11", "jazz-react-auth-clerk": "workspace:0.9.12",
"jazz-tools": "workspace:*", "jazz-tools": "workspace:*",
"react": "^18.3.1", "react": "^18.3.1",
"react-dom": "^18.3.1" "react-dom": "^18.3.1"

View File

@@ -1,5 +1,12 @@
# file-share-svelte # file-share-svelte
## 0.0.17
### Patch Changes
- jazz-svelte@0.9.12
- jazz-tools@0.9.12
## 0.0.16 ## 0.0.16
### Patch Changes ### Patch Changes

View File

@@ -1,6 +1,6 @@
{ {
"name": "file-share-svelte", "name": "file-share-svelte",
"version": "0.0.16", "version": "0.0.17",
"private": true, "private": true,
"type": "module", "type": "module",
"scripts": { "scripts": {

View File

@@ -1,5 +1,13 @@
# form # form
## 0.0.28
### Patch Changes
- jazz-react@0.9.12
- jazz-tools@0.9.12
- jazz-browser-media-images@0.9.12
## 0.0.27 ## 0.0.27
### Patch Changes ### Patch Changes

View File

@@ -1,7 +1,7 @@
{ {
"name": "form", "name": "form",
"private": true, "private": true,
"version": "0.0.27", "version": "0.0.28",
"type": "module", "type": "module",
"scripts": { "scripts": {
"dev": "vite", "dev": "vite",

View File

@@ -1,5 +1,13 @@
# image-upload # image-upload
## 0.0.30
### Patch Changes
- jazz-react@0.9.12
- jazz-tools@0.9.12
- jazz-browser-media-images@0.9.12
## 0.0.29 ## 0.0.29
### Patch Changes ### Patch Changes

View File

@@ -1,7 +1,7 @@
{ {
"name": "image-upload", "name": "image-upload",
"private": true, "private": true,
"version": "0.0.29", "version": "0.0.30",
"type": "module", "type": "module",
"scripts": { "scripts": {
"dev": "vite", "dev": "vite",

View File

@@ -1,5 +1,13 @@
# jazz-example-inspector # jazz-example-inspector
## 0.0.97
### Patch Changes
- Updated dependencies [15d4b2a]
- cojson-transport-ws@0.9.12
- cojson@0.9.12
## 0.0.96 ## 0.0.96
### Patch Changes ### Patch Changes

View File

@@ -1,7 +1,7 @@
{ {
"name": "jazz-inspector-app", "name": "jazz-inspector-app",
"private": true, "private": true,
"version": "0.0.96", "version": "0.0.97",
"type": "module", "type": "module",
"scripts": { "scripts": {
"dev": "vite", "dev": "vite",
@@ -16,8 +16,8 @@
"@radix-ui/react-toast": "^1.1.4", "@radix-ui/react-toast": "^1.1.4",
"class-variance-authority": "^0.7.0", "class-variance-authority": "^0.7.0",
"clsx": "^2.0.0", "clsx": "^2.0.0",
"cojson": "workspace:0.9.11", "cojson": "workspace:0.9.12",
"cojson-transport-ws": "workspace:0.9.11", "cojson-transport-ws": "workspace:0.9.12",
"hash-slash": "workspace:0.2.1", "hash-slash": "workspace:0.2.1",
"lucide-react": "^0.274.0", "lucide-react": "^0.274.0",
"qrcode": "^1.5.3", "qrcode": "^1.5.3",

View File

@@ -1,5 +1,13 @@
# jazz-example-musicplayer # jazz-example-musicplayer
## 0.0.53
### Patch Changes
- jazz-inspector@0.9.12
- jazz-react@0.9.12
- jazz-tools@0.9.12
## 0.0.52 ## 0.0.52
### Patch Changes ### Patch Changes

View File

@@ -1,7 +1,7 @@
{ {
"name": "jazz-example-music-player", "name": "jazz-example-music-player",
"private": true, "private": true,
"version": "0.0.52", "version": "0.0.53",
"type": "module", "type": "module",
"scripts": { "scripts": {
"dev": "vite", "dev": "vite",
@@ -18,8 +18,8 @@
"@radix-ui/react-toast": "^1.1.4", "@radix-ui/react-toast": "^1.1.4",
"class-variance-authority": "^0.7.0", "class-variance-authority": "^0.7.0",
"clsx": "^2.0.0", "clsx": "^2.0.0",
"jazz-react": "workspace:0.9.11", "jazz-react": "workspace:0.9.12",
"jazz-tools": "workspace:0.9.11", "jazz-tools": "workspace:0.9.12",
"jazz-inspector": "workspace:*", "jazz-inspector": "workspace:*",
"lucide-react": "^0.274.0", "lucide-react": "^0.274.0",
"react": "^18.3.1", "react": "^18.3.1",

View File

@@ -1,5 +1,13 @@
# jazz-example-onboarding # jazz-example-onboarding
## 0.0.34
### Patch Changes
- jazz-react@0.9.12
- jazz-tools@0.9.12
- jazz-browser-media-images@0.9.12
## 0.0.33 ## 0.0.33
### Patch Changes ### Patch Changes

View File

@@ -1,7 +1,7 @@
{ {
"name": "jazz-example-onboarding", "name": "jazz-example-onboarding",
"private": true, "private": true,
"version": "0.0.33", "version": "0.0.34",
"type": "module", "type": "module",
"scripts": { "scripts": {
"dev": "vite", "dev": "vite",

View File

@@ -1,5 +1,12 @@
# organization # organization
## 0.0.26
### Patch Changes
- jazz-react@0.9.12
- jazz-tools@0.9.12
## 0.0.25 ## 0.0.25
### Patch Changes ### Patch Changes

View File

@@ -1,7 +1,7 @@
{ {
"name": "organization", "name": "organization",
"private": true, "private": true,
"version": "0.0.25", "version": "0.0.26",
"type": "module", "type": "module",
"scripts": { "scripts": {
"dev": "vite", "dev": "vite",

View File

@@ -1,5 +1,11 @@
# passkey-svelte # passkey-svelte
## 0.0.21
### Patch Changes
- jazz-svelte@0.9.12
## 0.0.20 ## 0.0.20
### Patch Changes ### Patch Changes

View File

@@ -1,6 +1,6 @@
{ {
"name": "passkey-svelte", "name": "passkey-svelte",
"version": "0.0.20", "version": "0.0.21",
"type": "module", "type": "module",
"private": true, "private": true,
"scripts": { "scripts": {

View File

@@ -1,5 +1,12 @@
# minimal-auth-passkey # minimal-auth-passkey
## 0.0.31
### Patch Changes
- jazz-react@0.9.12
- jazz-tools@0.9.12
## 0.0.30 ## 0.0.30
### Patch Changes ### Patch Changes

View File

@@ -1,7 +1,7 @@
{ {
"name": "passkey", "name": "passkey",
"private": true, "private": true,
"version": "0.0.30", "version": "0.0.31",
"type": "module", "type": "module",
"scripts": { "scripts": {
"dev": "vite", "dev": "vite",

View File

@@ -1,5 +1,12 @@
# jazz-password-manager # jazz-password-manager
## 0.0.52
### Patch Changes
- jazz-react@0.9.12
- jazz-tools@0.9.12
## 0.0.51 ## 0.0.51
### Patch Changes ### Patch Changes

View File

@@ -1,7 +1,7 @@
{ {
"name": "jazz-password-manager", "name": "jazz-password-manager",
"private": true, "private": true,
"version": "0.0.51", "version": "0.0.52",
"type": "module", "type": "module",
"scripts": { "scripts": {
"dev": "vite", "dev": "vite",
@@ -12,8 +12,8 @@
"clean-install": "rm -rf node_modules pnpm-lock.yaml && pnpm install" "clean-install": "rm -rf node_modules pnpm-lock.yaml && pnpm install"
}, },
"dependencies": { "dependencies": {
"jazz-react": "workspace:0.9.11", "jazz-react": "workspace:0.9.12",
"jazz-tools": "workspace:0.9.11", "jazz-tools": "workspace:0.9.12",
"react": "^18.3.1", "react": "^18.3.1",
"react-dom": "^18.3.1", "react-dom": "^18.3.1",
"react-hook-form": "^7.41.5", "react-hook-form": "^7.41.5",

View File

@@ -1,5 +1,13 @@
# jazz-example-pets # jazz-example-pets
## 0.0.150
### Patch Changes
- jazz-react@0.9.12
- jazz-tools@0.9.12
- jazz-browser-media-images@0.9.12
## 0.0.149 ## 0.0.149
### Patch Changes ### Patch Changes

View File

@@ -1,7 +1,7 @@
{ {
"name": "jazz-example-pets", "name": "jazz-example-pets",
"private": true, "private": true,
"version": "0.0.149", "version": "0.0.150",
"type": "module", "type": "module",
"scripts": { "scripts": {
"dev": "vite", "dev": "vite",
@@ -19,9 +19,9 @@
"@radix-ui/react-toast": "^1.1.4", "@radix-ui/react-toast": "^1.1.4",
"class-variance-authority": "^0.7.0", "class-variance-authority": "^0.7.0",
"clsx": "^2.0.0", "clsx": "^2.0.0",
"jazz-browser-media-images": "workspace:0.9.11", "jazz-browser-media-images": "workspace:0.9.12",
"jazz-react": "workspace:0.9.11", "jazz-react": "workspace:0.9.12",
"jazz-tools": "workspace:0.9.11", "jazz-tools": "workspace:0.9.12",
"lucide-react": "^0.274.0", "lucide-react": "^0.274.0",
"qrcode": "^1.5.3", "qrcode": "^1.5.3",
"react": "^18.3.1", "react": "^18.3.1",
@@ -41,7 +41,7 @@
"@vitejs/plugin-react-swc": "^3.3.2", "@vitejs/plugin-react-swc": "^3.3.2",
"autoprefixer": "^10.4.20", "autoprefixer": "^10.4.20",
"is-ci": "^3.0.1", "is-ci": "^3.0.1",
"jazz-run": "workspace:0.9.11", "jazz-run": "workspace:0.9.12",
"postcss": "^8.4.27", "postcss": "^8.4.27",
"tailwindcss": "^3.4.15", "tailwindcss": "^3.4.15",
"typescript": "~5.6.2", "typescript": "~5.6.2",

View File

@@ -1,5 +1,13 @@
# reactions # reactions
## 0.0.30
### Patch Changes
- jazz-react@0.9.12
- jazz-tools@0.9.12
- jazz-browser-media-images@0.9.12
## 0.0.29 ## 0.0.29
### Patch Changes ### Patch Changes

View File

@@ -1,7 +1,7 @@
{ {
"name": "reactions", "name": "reactions",
"private": true, "private": true,
"version": "0.0.29", "version": "0.0.30",
"type": "module", "type": "module",
"scripts": { "scripts": {
"dev": "vite", "dev": "vite",

View File

@@ -1,5 +1,13 @@
# todo-vue # todo-vue
## 0.0.35
### Patch Changes
- jazz-browser@0.9.12
- jazz-tools@0.9.12
- jazz-vue@0.9.12
## 0.0.34 ## 0.0.34
### Patch Changes ### Patch Changes

View File

@@ -1,6 +1,6 @@
{ {
"name": "todo-vue", "name": "todo-vue",
"version": "0.0.34", "version": "0.0.35",
"private": true, "private": true,
"type": "module", "type": "module",
"scripts": { "scripts": {

View File

@@ -1,5 +1,12 @@
# jazz-example-todo # jazz-example-todo
## 0.0.149
### Patch Changes
- jazz-react@0.9.12
- jazz-tools@0.9.12
## 0.0.148 ## 0.0.148
### Patch Changes ### Patch Changes

View File

@@ -1,7 +1,7 @@
{ {
"name": "jazz-example-todo", "name": "jazz-example-todo",
"private": true, "private": true,
"version": "0.0.148", "version": "0.0.149",
"type": "module", "type": "module",
"scripts": { "scripts": {
"dev": "vite", "dev": "vite",
@@ -16,8 +16,8 @@
"@radix-ui/react-toast": "^1.1.4", "@radix-ui/react-toast": "^1.1.4",
"class-variance-authority": "^0.7.0", "class-variance-authority": "^0.7.0",
"clsx": "^2.0.0", "clsx": "^2.0.0",
"jazz-react": "workspace:0.9.11", "jazz-react": "workspace:0.9.12",
"jazz-tools": "workspace:0.9.11", "jazz-tools": "workspace:0.9.12",
"lucide-react": "^0.274.0", "lucide-react": "^0.274.0",
"qrcode": "^1.5.3", "qrcode": "^1.5.3",
"react": "^18.3.1", "react": "^18.3.1",

View File

@@ -1,5 +1,12 @@
# version-history # version-history
## 0.0.27
### Patch Changes
- jazz-react@0.9.12
- jazz-tools@0.9.12
## 0.0.26 ## 0.0.26
### Patch Changes ### Patch Changes

View File

@@ -1,7 +1,7 @@
{ {
"name": "version-history", "name": "version-history",
"private": true, "private": true,
"version": "0.0.26", "version": "0.0.27",
"type": "module", "type": "module",
"scripts": { "scripts": {
"dev": "vite", "dev": "vite",

View File

@@ -1,5 +1,13 @@
# cojson-storage-indexeddb # cojson-storage-indexeddb
## 0.9.12
### Patch Changes
- Updated dependencies [15d4b2a]
- cojson-storage@0.9.12
- cojson@0.9.12
## 0.9.11 ## 0.9.11
### Patch Changes ### Patch Changes

View File

@@ -1,6 +1,6 @@
{ {
"name": "cojson-storage-indexeddb", "name": "cojson-storage-indexeddb",
"version": "0.9.11", "version": "0.9.12",
"main": "dist/index.js", "main": "dist/index.js",
"type": "module", "type": "module",
"types": "src/index.ts", "types": "src/index.ts",

View File

@@ -1,5 +1,13 @@
# cojson-storage-sqlite # cojson-storage-sqlite
## 0.8.55
### Patch Changes
- Updated dependencies [15d4b2a]
- cojson-storage@0.9.12
- cojson@0.9.12
## 0.8.54 ## 0.8.54
### Patch Changes ### Patch Changes

View File

@@ -1,7 +1,7 @@
{ {
"name": "cojson-storage-rn-sqlite", "name": "cojson-storage-rn-sqlite",
"type": "module", "type": "module",
"version": "0.8.54", "version": "0.8.55",
"main": "dist/index.js", "main": "dist/index.js",
"types": "src/index.ts", "types": "src/index.ts",
"license": "MIT", "license": "MIT",

View File

@@ -1,5 +1,14 @@
# cojson-storage-sqlite # cojson-storage-sqlite
## 0.9.12
### Patch Changes
- 15d4b2a: Revert the custom logger
- Updated dependencies [15d4b2a]
- cojson-storage@0.9.12
- cojson@0.9.12
## 0.9.11 ## 0.9.11
### Patch Changes ### Patch Changes

View File

@@ -1,13 +1,13 @@
{ {
"name": "cojson-storage-sqlite", "name": "cojson-storage-sqlite",
"type": "module", "type": "module",
"version": "0.9.11", "version": "0.9.12",
"main": "dist/index.js", "main": "dist/index.js",
"types": "src/index.ts", "types": "src/index.ts",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"better-sqlite3": "^11.7.0", "better-sqlite3": "^11.7.0",
"cojson": "workspace:0.9.11", "cojson": "workspace:0.9.12",
"cojson-storage": "workspace:*" "cojson-storage": "workspace:*"
}, },
"devDependencies": { "devDependencies": {

View File

@@ -1,10 +1,5 @@
import { Database as DatabaseT } from "better-sqlite3"; import { Database as DatabaseT } from "better-sqlite3";
import { import { CojsonInternalTypes, OutgoingSyncQueue, SessionID } from "cojson";
CojsonInternalTypes,
OutgoingSyncQueue,
SessionID,
logger,
} from "cojson";
import RawCoID = CojsonInternalTypes.RawCoID; import RawCoID = CojsonInternalTypes.RawCoID;
import Signature = CojsonInternalTypes.Signature; import Signature = CojsonInternalTypes.Signature;
import Transaction = CojsonInternalTypes.Transaction; import Transaction = CojsonInternalTypes.Transaction;
@@ -53,7 +48,7 @@ export class SQLiteClient implements DBClientInterface {
header: parsedHeader, header: parsedHeader,
}; };
} catch (e) { } catch (e) {
logger.warn(coValueId, "Invalid JSON in header", e, coValueRow?.header); console.warn(coValueId, "Invalid JSON in header", e, coValueRow?.header);
return; return;
} }
} }
@@ -80,7 +75,7 @@ export class SQLiteClient implements DBClientInterface {
tx: JSON.parse(transactionRow.tx) as Transaction, tx: JSON.parse(transactionRow.tx) as Transaction,
})); }));
} catch (e) { } catch (e) {
logger.warn("Invalid JSON in transaction", e); console.warn("Invalid JSON in transaction", e);
return []; return [];
} }
} }

View File

@@ -4,7 +4,6 @@ import {
OutgoingSyncQueue, OutgoingSyncQueue,
Peer, Peer,
cojsonInternals, cojsonInternals,
logger,
} from "cojson"; } from "cojson";
import { SyncManager, TransactionRow } from "cojson-storage"; import { SyncManager, TransactionRow } from "cojson-storage";
import { SQLiteClient } from "./sqliteClient.js"; import { SQLiteClient } from "./sqliteClient.js";
@@ -41,23 +40,25 @@ export class SQLiteNode {
await new Promise((resolve) => setTimeout(resolve, 0)); await new Promise((resolve) => setTimeout(resolve, 0));
} }
} catch (e) { } catch (e) {
logger.error( console.error(
`Error reading from localNode, handling msg\n\n${JSON.stringify( new Error(
msg, `Error reading from localNode, handling msg\n\n${JSON.stringify(
(k, v) => msg,
k === "changes" || k === "encryptedChanges" (k, v) =>
? v.slice(0, 20) + "..." k === "changes" || k === "encryptedChanges"
: v, ? v.slice(0, 20) + "..."
)}`, : v,
e, )}`,
{ cause: e },
),
); );
} }
} }
processMessages().catch((e) =>
logger.error("Error in processMessages in sqlite", e),
);
}; };
processMessages().catch((e) =>
console.error("Error in processMessages in sqlite", e),
);
} }
static async asPeer({ static async asPeer({
@@ -96,7 +97,10 @@ export class SQLiteNode {
db.pragma("user_version") as [{ user_version: number }] db.pragma("user_version") as [{ user_version: number }]
)[0].user_version as number; )[0].user_version as number;
console.log("DB version", oldVersion);
if (oldVersion === 0) { if (oldVersion === 0) {
console.log("Migration 0 -> 1: Basic schema");
db.prepare( db.prepare(
`CREATE TABLE IF NOT EXISTS transactions ( `CREATE TABLE IF NOT EXISTS transactions (
ses INTEGER, ses INTEGER,
@@ -134,10 +138,15 @@ export class SQLiteNode {
).run(); ).run();
db.pragma("user_version = 1"); db.pragma("user_version = 1");
console.log("Migration 0 -> 1: Basic schema - done");
} }
if (oldVersion <= 1) { if (oldVersion <= 1) {
// fix embarrassing off-by-one error for transaction indices // fix embarrassing off-by-one error for transaction indices
console.log(
"Migration 1 -> 2: Fix off-by-one error for transaction indices",
);
const txs = db const txs = db
.prepare(`SELECT * FROM transactions`) .prepare(`SELECT * FROM transactions`)
.all() as TransactionRow[]; .all() as TransactionRow[];
@@ -154,9 +163,14 @@ export class SQLiteNode {
} }
db.pragma("user_version = 2"); db.pragma("user_version = 2");
console.log(
"Migration 1 -> 2: Fix off-by-one error for transaction indices - done",
);
} }
if (oldVersion <= 2) { if (oldVersion <= 2) {
console.log("Migration 2 -> 3: Add signatureAfter");
db.prepare( db.prepare(
`CREATE TABLE IF NOT EXISTS signatureAfter ( `CREATE TABLE IF NOT EXISTS signatureAfter (
ses INTEGER, ses INTEGER,
@@ -171,6 +185,7 @@ export class SQLiteNode {
).run(); ).run();
db.pragma("user_version = 3"); db.pragma("user_version = 3");
console.log("Migration 2 -> 3: Add signatureAfter - done!!");
} }
return new SQLiteNode(db, fromLocalNode, toLocalNode); return new SQLiteNode(db, fromLocalNode, toLocalNode);

View File

@@ -1,5 +1,13 @@
# cojson-storage # cojson-storage
## 0.9.12
### Patch Changes
- 15d4b2a: Revert the custom logger
- Updated dependencies [15d4b2a]
- cojson@0.9.12
## 0.9.11 ## 0.9.11
### Patch Changes ### Patch Changes

View File

@@ -1,6 +1,6 @@
{ {
"name": "cojson-storage", "name": "cojson-storage",
"version": "0.9.11", "version": "0.9.12",
"main": "dist/index.js", "main": "dist/index.js",
"type": "module", "type": "module",
"types": "src/index.ts", "types": "src/index.ts",

View File

@@ -6,7 +6,6 @@ import {
SyncMessage, SyncMessage,
cojsonInternals, cojsonInternals,
emptyKnownState, emptyKnownState,
logger,
} from "cojson"; } from "cojson";
import { collectNewTxs, getDependedOnCoValues } from "./syncUtils.js"; import { collectNewTxs, getDependedOnCoValues } from "./syncUtils.js";
import { DBClientInterface, StoredSessionRow } from "./types.js"; import { DBClientInterface, StoredSessionRow } from "./types.js";
@@ -315,7 +314,7 @@ export class SyncManager {
return this.toLocalNode return this.toLocalNode
.push(msg) .push(msg)
.catch((e) => .catch((e) =>
logger.error(`Error sending ${msg.action} state, id ${msg.id}`, e), console.error(`Error sending ${msg.action} state, id ${msg.id}`, e),
); );
} }
} }

View File

@@ -1,5 +1,13 @@
# cojson-transport-nodejs-ws # cojson-transport-nodejs-ws
## 0.9.12
### Patch Changes
- 15d4b2a: Revert the custom logger
- Updated dependencies [15d4b2a]
- cojson@0.9.12
## 0.9.11 ## 0.9.11
### Patch Changes ### Patch Changes

View File

@@ -1,12 +1,12 @@
{ {
"name": "cojson-transport-ws", "name": "cojson-transport-ws",
"type": "module", "type": "module",
"version": "0.9.11", "version": "0.9.12",
"main": "dist/index.js", "main": "dist/index.js",
"types": "src/index.ts", "types": "src/index.ts",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"cojson": "workspace:0.9.11", "cojson": "workspace:0.9.12",
"typescript": "~5.6.2" "typescript": "~5.6.2"
}, },
"scripts": { "scripts": {

View File

@@ -4,7 +4,6 @@ import {
PingTimeoutError, PingTimeoutError,
SyncMessage, SyncMessage,
cojsonInternals, cojsonInternals,
logger,
} from "cojson"; } from "cojson";
import { BatchedOutgoingMessages } from "./BatchedOutgoingMessages.js"; import { BatchedOutgoingMessages } from "./BatchedOutgoingMessages.js";
import { deserializeMessages } from "./serialization.js"; import { deserializeMessages } from "./serialization.js";
@@ -137,7 +136,7 @@ export function createWebSocketPeer({
function handleClose() { function handleClose() {
incoming incoming
.push("Disconnected") .push("Disconnected")
.catch((e) => logger.error("Error while pushing disconnect msg", e)); .catch((e) => console.error("Error while pushing disconnect msg", e));
emitClosedEvent(); emitClosedEvent();
} }
@@ -146,7 +145,7 @@ export function createWebSocketPeer({
const pingTimeout = createPingTimeoutListener(expectPings, () => { const pingTimeout = createPingTimeoutListener(expectPings, () => {
incoming incoming
.push("PingTimeout") .push("PingTimeout")
.catch((e) => logger.error("Error while pushing ping timeout", e)); .catch((e) => console.error("Error while pushing ping timeout", e));
emitClosedEvent(); emitClosedEvent();
}); });
@@ -157,13 +156,14 @@ export function createWebSocketPeer({
function handleIncomingMsg(event: { data: unknown }) { function handleIncomingMsg(event: { data: unknown }) {
if (event.data === "") { if (event.data === "") {
console.log("client", id, "sent empty message");
return; return;
} }
const result = deserializeMessages(event.data); const result = deserializeMessages(event.data);
if (!result.ok) { if (!result.ok) {
logger.warn( console.error(
"Error while deserializing messages", "Error while deserializing messages",
event.data, event.data,
result.error, result.error,
@@ -184,7 +184,7 @@ export function createWebSocketPeer({
if (msg && "action" in msg) { if (msg && "action" in msg) {
incoming incoming
.push(msg) .push(msg)
.catch((e) => logger.error("Error while pushing incoming msg", e)); .catch((e) => console.error("Error while pushing incoming msg", e));
} }
} }
} }
@@ -197,6 +197,7 @@ export function createWebSocketPeer({
outgoing: { outgoing: {
push: outgoingMessages.sendMessage, push: outgoingMessages.sendMessage,
close() { close() {
console.log("Trying to close", id, websocket.readyState);
outgoingMessages.close(); outgoingMessages.close();
websocket.removeEventListener("message", handleIncomingMsg); websocket.removeEventListener("message", handleIncomingMsg);

View File

@@ -1,4 +1,4 @@
import { SyncMessage, logger } from "cojson"; import { SyncMessage } from "cojson";
import { PingMsg } from "./types.js"; import { PingMsg } from "./types.js";
export function addMessageToBacklog(backlog: string, message: SyncMessage) { export function addMessageToBacklog(backlog: string, message: SyncMessage) {
@@ -24,7 +24,7 @@ export function deserializeMessages(messages: unknown) {
| PingMsg[], | PingMsg[],
} as const; } as const;
} catch (e) { } catch (e) {
logger.error("Error while deserializing messages", e); console.error("Error while deserializing messages", e);
return { return {
ok: false, ok: false,
error: e, error: e,

View File

@@ -1,5 +1,11 @@
# cojson # cojson
## 0.9.12
### Patch Changes
- 15d4b2a: Revert the custom logger
## 0.9.11 ## 0.9.11
### Patch Changes ### Patch Changes

View File

@@ -24,7 +24,7 @@
}, },
"type": "module", "type": "module",
"license": "MIT", "license": "MIT",
"version": "0.9.11", "version": "0.9.12",
"devDependencies": { "devDependencies": {
"@opentelemetry/sdk-metrics": "^1.29.0", "@opentelemetry/sdk-metrics": "^1.29.0",
"@types/jest": "^29.5.3", "@types/jest": "^29.5.3",

View File

@@ -5,7 +5,6 @@ import {
} from "./PriorityBasedMessageQueue.js"; } from "./PriorityBasedMessageQueue.js";
import { TryAddTransactionsError } from "./coValueCore.js"; import { TryAddTransactionsError } from "./coValueCore.js";
import { RawCoID } from "./ids.js"; import { RawCoID } from "./ids.js";
import { logger } from "./logger.js";
import { CO_VALUE_PRIORITY } from "./priority.js"; import { CO_VALUE_PRIORITY } from "./priority.js";
import { Peer, SyncMessage } from "./sync.js"; import { Peer, SyncMessage } from "./sync.js";
@@ -138,7 +137,7 @@ export class PeerState {
} }
gracefulShutdown() { gracefulShutdown() {
logger.debug("Gracefully closing", this.id); console.debug("Gracefully closing", this.id);
this.closeQueue(); this.closeQueue();
this.peer.outgoing.close(); this.peer.outgoing.close();
this.closed = true; this.closed = true;

View File

@@ -43,7 +43,12 @@ export function bytesToBase64url(bytes: Uint8Array) {
let base64 = decoder.decode(new Uint8Array(encoded.buffer, 0, n)); let base64 = decoder.decode(new Uint8Array(encoded.buffer, 0, n));
if (k === 1) base64 += "=="; if (k === 1) base64 += "==";
if (k === 2) base64 += "="; if (k === 2) base64 += "=";
// const after = performance.now();
// console.log(
// "bytesToBase64url bandwidth in MB/s for length",
// (1000 * bytes.length / (after - before)) / (1024 * 1024),
// bytes.length
// );
return base64; return base64;
} }

View File

@@ -24,7 +24,6 @@ import {
import { Stringified, parseJSON, stableStringify } from "./jsonStringify.js"; import { Stringified, parseJSON, stableStringify } from "./jsonStringify.js";
import { JsonObject, JsonValue } from "./jsonValue.js"; import { JsonObject, JsonValue } from "./jsonValue.js";
import { LocalNode, ResolveAccountAgentError } from "./localNode.js"; import { LocalNode, ResolveAccountAgentError } from "./localNode.js";
import { logger } from "./logger.js";
import { import {
PermissionsDef as RulesetDef, PermissionsDef as RulesetDef,
determineValidTransactions, determineValidTransactions,
@@ -210,10 +209,16 @@ export class CoValueCore {
.andThen((agent) => { .andThen((agent) => {
const signerID = this.crypto.getAgentSignerID(agent); const signerID = this.crypto.getAgentSignerID(agent);
// const beforeHash = performance.now();
const { expectedNewHash, newStreamingHash } = this.expectedNewHashAfter( const { expectedNewHash, newStreamingHash } = this.expectedNewHashAfter(
sessionID, sessionID,
newTransactions, newTransactions,
); );
// const afterHash = performance.now();
// console.log(
// "Hashing took",
// afterHash - beforeHash
// );
if (givenExpectedNewHash && givenExpectedNewHash !== expectedNewHash) { if (givenExpectedNewHash && givenExpectedNewHash !== expectedNewHash) {
return err({ return err({
@@ -386,6 +391,7 @@ export class CoValueCore {
streamingHash.update(transaction); streamingHash.update(transaction);
const after = performance.now(); const after = performance.now();
if (after - before > 1) { if (after - before > 1) {
// console.log("Hashing blocked for", after - before);
await new Promise((resolve) => setTimeout(resolve, 0)); await new Promise((resolve) => setTimeout(resolve, 0));
before = performance.now(); before = performance.now();
} }
@@ -534,7 +540,7 @@ export class CoValueCore {
} }
if (!decryptedChanges) { if (!decryptedChanges) {
logger.error("Failed to decrypt transaction despite having key"); console.error("Failed to decrypt transaction despite having key");
continue; continue;
} }
@@ -679,7 +685,7 @@ export class CoValueCore {
if (secret) { if (secret) {
return secret as KeySecret; return secret as KeySecret;
} else { } else {
logger.warn( console.error(
`Encrypting ${encryptingKeyID} key didn't decrypt ${keyID}`, `Encrypting ${encryptingKeyID} key didn't decrypt ${keyID}`,
); );
} }
@@ -719,7 +725,7 @@ export class CoValueCore {
if (secret) { if (secret) {
return secret as KeySecret; return secret as KeySecret;
} else { } else {
logger.warn( console.error(
`Encrypting parent ${parentKey.id} key didn't decrypt ${keyID}`, `Encrypting parent ${parentKey.id} key didn't decrypt ${keyID}`,
); );
} }

View File

@@ -1,7 +1,6 @@
import { PeerState } from "./PeerState.js"; import { PeerState } from "./PeerState.js";
import { CoValueCore } from "./coValueCore.js"; import { CoValueCore } from "./coValueCore.js";
import { RawCoID } from "./ids.js"; import { RawCoID } from "./ids.js";
import { logger } from "./logger.js";
import { PeerID } from "./sync.js"; import { PeerID } from "./sync.js";
export const CO_VALUE_LOADING_MAX_RETRIES = 5; export const CO_VALUE_LOADING_MAX_RETRIES = 5;
@@ -283,7 +282,7 @@ async function loadCoValueFromPeers(
...coValueEntry.state.coValue.knownState(), ...coValueEntry.state.coValue.knownState(),
}) })
.catch((err) => { .catch((err) => {
logger.warn(`Failed to push load message to peer ${peer.id}`, err); console.error(`Failed to push load message to peer ${peer.id}`, err);
}); });
} else { } else {
/** /**
@@ -297,14 +296,14 @@ async function loadCoValueFromPeers(
sessions: {}, sessions: {},
}) })
.catch((err) => { .catch((err) => {
logger.warn(`Failed to push load message to peer ${peer.id}`, err); console.error(`Failed to push load message to peer ${peer.id}`, err);
}); });
} }
if (coValueEntry.state.type === "loading") { if (coValueEntry.state.type === "loading") {
const timeout = setTimeout(() => { const timeout = setTimeout(() => {
if (coValueEntry.state.type === "loading") { if (coValueEntry.state.type === "loading") {
logger.warn("Failed to load coValue from peer", peer.id); console.error("Failed to load coValue from peer", peer.id);
coValueEntry.dispatch({ coValueEntry.dispatch({
type: "not-found-in-peer", type: "not-found-in-peer",
peerId: peer.id, peerId: peer.id,
@@ -357,7 +356,7 @@ function sleep(ms: number) {
function getPeersWithoutErrors(peers: PeerState[], coValueId: RawCoID) { function getPeersWithoutErrors(peers: PeerState[], coValueId: RawCoID) {
return peers.filter((p) => { return peers.filter((p) => {
if (p.erroredCoValues.has(coValueId)) { if (p.erroredCoValues.has(coValueId)) {
logger.warn( console.error(
`Skipping load on errored coValue ${coValueId} from peer ${p.id}`, `Skipping load on errored coValue ${coValueId} from peer ${p.id}`,
); );
return false; return false;

View File

@@ -16,7 +16,6 @@ import {
import { AgentID } from "../ids.js"; import { AgentID } from "../ids.js";
import { JsonObject } from "../jsonValue.js"; import { JsonObject } from "../jsonValue.js";
import { LocalNode } from "../localNode.js"; import { LocalNode } from "../localNode.js";
import { logger } from "../logger.js";
import type { AccountRole } from "../permissions.js"; import type { AccountRole } from "../permissions.js";
import { RawCoMap } from "./coMap.js"; import { RawCoMap } from "./coMap.js";
import { InviteSecret, RawGroup } from "./group.js"; import { InviteSecret, RawGroup } from "./group.js";
@@ -60,7 +59,7 @@ export class RawAccount<
); );
if (agents.length !== 1) { if (agents.length !== 1) {
logger.warn("Account has " + agents.length + " agents", this.id); console.warn("Account has " + agents.length + " agents", this.id);
} }
this._cachedCurrentAgentID = agents[0]; this._cachedCurrentAgentID = agents[0];

View File

@@ -133,6 +133,10 @@ export class RawCoListView<
change.before.txIndex change.before.txIndex
]?.[change.before.changeIdx]; ]?.[change.before.changeIdx];
if (!beforeEntry) { if (!beforeEntry) {
// console.error(
// "Insertion before missing op " +
// change.before
// );
continue; continue;
} }
beforeEntry.predecessors.splice(0, 0, { beforeEntry.predecessors.splice(0, 0, {
@@ -152,6 +156,9 @@ export class RawCoListView<
change.after.txIndex change.after.txIndex
]?.[change.after.changeIdx]; ]?.[change.after.changeIdx];
if (!afterEntry) { if (!afterEntry) {
// console.error(
// "Insertion after missing op " + change.after
// );
continue; continue;
} }
afterEntry.successors.push({ afterEntry.successors.push({

View File

@@ -3,7 +3,6 @@ import { CoID, RawCoValue } from "../coValue.js";
import { CoValueCore } from "../coValueCore.js"; import { CoValueCore } from "../coValueCore.js";
import { AgentID, SessionID, TransactionID } from "../ids.js"; import { AgentID, SessionID, TransactionID } from "../ids.js";
import { JsonObject, JsonValue } from "../jsonValue.js"; import { JsonObject, JsonValue } from "../jsonValue.js";
import { logger } from "../logger.js";
import { CoValueKnownState } from "../sync.js"; import { CoValueKnownState } from "../sync.js";
import { accountOrAgentIDfromSessionID } from "../typeUtils/accountOrAgentIDfromSessionID.js"; import { accountOrAgentIDfromSessionID } from "../typeUtils/accountOrAgentIDfromSessionID.js";
import { isAccountID } from "../typeUtils/isAccountID.js"; import { isAccountID } from "../typeUtils/isAccountID.js";
@@ -310,7 +309,7 @@ export class RawBinaryCoStreamView<
const start = items[0]; const start = items[0];
if (start?.type !== "start") { if (start?.type !== "start") {
logger.error("Invalid binary stream start", start); console.error("Invalid binary stream start", start);
return; return;
} }
@@ -329,7 +328,7 @@ export class RawBinaryCoStreamView<
} }
if (item.type !== "chunk") { if (item.type !== "chunk") {
logger.error("Invalid binary stream chunk", item); console.error("Invalid binary stream chunk", item);
return undefined; return undefined;
} }
@@ -383,6 +382,7 @@ export class RawBinaryCoStream<
chunk: Uint8Array, chunk: Uint8Array,
privacy: "private" | "trusting" = "private", privacy: "private" | "trusting" = "private",
): void { ): void {
// const before = performance.now();
this.push( this.push(
{ {
type: "chunk", type: "chunk",
@@ -391,6 +391,11 @@ export class RawBinaryCoStream<
privacy, privacy,
false, false,
); );
// const after = performance.now();
// console.log(
// "pushBinaryStreamChunk bandwidth in MB/s",
// (1000 * chunk.length) / (after - before) / (1024 * 1024)
// );
} }
endBinaryStream(privacy: "private" | "trusting" = "private") { endBinaryStream(privacy: "private" | "trusting" = "private") {

View File

@@ -13,7 +13,6 @@ import {
isParentGroupReference, isParentGroupReference,
} from "../ids.js"; } from "../ids.js";
import { JsonObject } from "../jsonValue.js"; import { JsonObject } from "../jsonValue.js";
import { logger } from "../logger.js";
import { AccountRole, Role } from "../permissions.js"; import { AccountRole, Role } from "../permissions.js";
import { expectGroup } from "../typeUtils/expectGroup.js"; import { expectGroup } from "../typeUtils/expectGroup.js";
import { import {
@@ -154,7 +153,7 @@ export class RawGroup<
child.state.type === "unavailable" child.state.type === "unavailable"
) { ) {
child.loadFromPeers(peers).catch(() => { child.loadFromPeers(peers).catch(() => {
logger.error(`Failed to load child group ${id}`); console.error(`Failed to load child group ${id}`);
}); });
} }
@@ -322,7 +321,7 @@ export class RawGroup<
const secret = this.core.getReadKey(keyID); const secret = this.core.getReadKey(keyID);
if (!secret) { if (!secret) {
logger.error("Can't find key", keyID); console.error("Can't find key", keyID);
continue; continue;
} }

View File

@@ -7,7 +7,6 @@ import { base64URLtoBytes, bytesToBase64url } from "../base64url.js";
import { RawCoID, TransactionID } from "../ids.js"; import { RawCoID, TransactionID } from "../ids.js";
import { Stringified, stableStringify } from "../jsonStringify.js"; import { Stringified, stableStringify } from "../jsonStringify.js";
import { JsonValue } from "../jsonValue.js"; import { JsonValue } from "../jsonValue.js";
import { logger } from "../logger.js";
import { import {
CryptoProvider, CryptoProvider,
Encrypted, Encrypted,
@@ -193,7 +192,7 @@ export class PureJSCrypto extends CryptoProvider<Blake3State> {
try { try {
return JSON.parse(textDecoder.decode(plaintext)); return JSON.parse(textDecoder.decode(plaintext));
} catch (e) { } catch (e) {
logger.error("Failed to decrypt/parse sealed message", e); console.error("Failed to decrypt/parse sealed message", e);
return undefined; return undefined;
} }
} }

View File

@@ -15,7 +15,6 @@ import { base64URLtoBytes, bytesToBase64url } from "../base64url.js";
import { RawCoID, TransactionID } from "../ids.js"; import { RawCoID, TransactionID } from "../ids.js";
import { Stringified, stableStringify } from "../jsonStringify.js"; import { Stringified, stableStringify } from "../jsonStringify.js";
import { JsonValue } from "../jsonValue.js"; import { JsonValue } from "../jsonValue.js";
import { logger } from "../logger.js";
import { import {
CryptoProvider, CryptoProvider,
Encrypted, Encrypted,
@@ -241,7 +240,7 @@ export class WasmCrypto extends CryptoProvider<Uint8Array> {
try { try {
return JSON.parse(textDecoder.decode(plaintext)); return JSON.parse(textDecoder.decode(plaintext));
} catch (e) { } catch (e) {
logger.error("Failed to decrypt/parse sealed message", e); console.error("Failed to decrypt/parse sealed message", e);
return undefined; return undefined;
} }
} }

View File

@@ -4,7 +4,6 @@ import { AgentID, RawCoID, TransactionID } from "../ids.js";
import { SessionID } from "../ids.js"; import { SessionID } from "../ids.js";
import { Stringified, parseJSON, stableStringify } from "../jsonStringify.js"; import { Stringified, parseJSON, stableStringify } from "../jsonStringify.js";
import { JsonValue } from "../jsonValue.js"; import { JsonValue } from "../jsonValue.js";
import { logger } from "../logger.js";
export type SignerSecret = `signerSecret_z${string}`; export type SignerSecret = `signerSecret_z${string}`;
export type SignerID = `signer_z${string}`; export type SignerID = `signer_z${string}`;
@@ -160,7 +159,7 @@ export abstract class CryptoProvider<Blake3State = any> {
try { try {
return parseJSON(this.decryptRaw(encrypted, keySecret, nOnceMaterial)); return parseJSON(this.decryptRaw(encrypted, keySecret, nOnceMaterial));
} catch (e) { } catch (e) {
logger.error("Decryption error", e); console.error("Decryption error", e);
return undefined; return undefined;
} }
} }
@@ -306,7 +305,10 @@ export class StreamingHash {
update(value: JsonValue): Uint8Array { update(value: JsonValue): Uint8Array {
const encoded = textEncoder.encode(stableStringify(value)); const encoded = textEncoder.encode(stableStringify(value));
// const before = performance.now();
this.state = this.crypto.blake3IncrementalUpdate(this.state, encoded); this.state = this.crypto.blake3IncrementalUpdate(this.state, encoded);
// const after = performance.now();
// console.log(`Hashing throughput in MB/s`, 1000 * (encoded.length / (after - before)) / (1024 * 1024));
return encoded; return encoded;
} }

View File

@@ -74,7 +74,6 @@ import {
type Value = JsonValue | AnyRawCoValue; type Value = JsonValue | AnyRawCoValue;
import { logger } from "./logger.js";
import { getPriorityFromHeader } from "./priority.js"; import { getPriorityFromHeader } from "./priority.js";
import { FileSystem } from "./storage/FileSystem.js"; import { FileSystem } from "./storage/FileSystem.js";
import { BlockFilename, LSMStorage, WalFilename } from "./storage/index.js"; import { BlockFilename, LSMStorage, WalFilename } from "./storage/index.js";
@@ -142,7 +141,6 @@ export {
emptyKnownState, emptyKnownState,
RawCoPlainText, RawCoPlainText,
stringifyOpID, stringifyOpID,
logger,
}; };
export type { export type {

View File

@@ -27,7 +27,6 @@ import {
} from "./coValues/group.js"; } from "./coValues/group.js";
import { AgentSecret, CryptoProvider } from "./crypto/crypto.js"; import { AgentSecret, CryptoProvider } from "./crypto/crypto.js";
import { AgentID, RawCoID, SessionID, isAgentID } from "./ids.js"; import { AgentID, RawCoID, SessionID, isAgentID } from "./ids.js";
import { logger } from "./logger.js";
import { Peer, PeerID, SyncManager } from "./sync.js"; import { Peer, PeerID, SyncManager } from "./sync.js";
import { expectGroup } from "./typeUtils/expectGroup.js"; import { expectGroup } from "./typeUtils/expectGroup.js";
@@ -231,7 +230,7 @@ export class LocalNode {
return node; return node;
} catch (e) { } catch (e) {
logger.error("Error withLoadedAccount", e); console.error("Error withLoadedAccount", e);
throw e; throw e;
} }
} }
@@ -270,7 +269,7 @@ export class LocalNode {
this.syncManager.getServerAndStoragePeers(skipLoadingFromPeer); this.syncManager.getServerAndStoragePeers(skipLoadingFromPeer);
await entry.loadFromPeers(peers).catch((e) => { await entry.loadFromPeers(peers).catch((e) => {
logger.error("Error loading from peers", id, e); console.error("Error loading from peers", id, e);
}); });
} }
@@ -312,6 +311,8 @@ export class LocalNode {
let stopped = false; let stopped = false;
let unsubscribe!: () => void; let unsubscribe!: () => void;
// console.log("Subscribing to " + id);
this.load(id) this.load(id)
.then((coValue) => { .then((coValue) => {
if (stopped) { if (stopped) {
@@ -324,10 +325,11 @@ export class LocalNode {
unsubscribe = coValue.subscribe(callback); unsubscribe = coValue.subscribe(callback);
}) })
.catch((e) => { .catch((e) => {
logger.error("Error subscribing to ", id, e); console.error("Error subscribing to ", id, e);
}); });
return () => { return () => {
console.log("Unsubscribing from " + id);
stopped = true; stopped = true;
unsubscribe?.(); unsubscribe?.();
}; };
@@ -388,7 +390,9 @@ export class LocalNode {
(existingRole === "reader" && inviteRole === "readerInvite") || (existingRole === "reader" && inviteRole === "readerInvite") ||
(existingRole && inviteRole === "writeOnlyInvite") (existingRole && inviteRole === "writeOnlyInvite")
) { ) {
logger.debug("Not accepting invite that would replace or downgrade role"); console.debug(
"Not accepting invite that would replace or downgrade role",
);
return; return;
} }

View File

@@ -1,78 +0,0 @@
export enum LogLevel {
DEBUG = 0,
INFO = 1,
WARN = 2,
ERROR = 3,
NONE = 4,
}
export interface LogSystem {
debug(message: string, ...args: any[]): void;
info(message: string, ...args: any[]): void;
warn(message: string, ...args: any[]): void;
error(message: string, ...args: any[]): void;
}
// Default console-based logging system
export class ConsoleLogSystem implements LogSystem {
debug(message: string, ...args: any[]) {
console.debug(message, ...args);
}
info(message: string, ...args: any[]) {
console.info(message, ...args);
}
warn(message: string, ...args: any[]) {
console.warn(message, ...args);
}
error(message: string, ...args: any[]) {
console.error(message, ...args);
}
}
export class Logger {
private level: LogLevel;
private logSystem: LogSystem;
constructor(
level: LogLevel = LogLevel.INFO,
logSystem: LogSystem = new ConsoleLogSystem(),
) {
this.level = level;
this.logSystem = logSystem;
}
setLevel(level: LogLevel) {
this.level = level;
}
setLogSystem(logSystem: LogSystem) {
this.logSystem = logSystem;
}
debug(message: string, ...args: any[]) {
if (this.level <= LogLevel.DEBUG) {
this.logSystem.debug(message, ...args);
}
}
info(message: string, ...args: any[]) {
if (this.level <= LogLevel.INFO) {
this.logSystem.info(message, ...args);
}
}
warn(message: string, ...args: any[]) {
if (this.level <= LogLevel.WARN) {
this.logSystem.warn(message, ...args);
}
}
error(message: string, ...args: any[]) {
if (this.level <= LogLevel.ERROR) {
this.logSystem.error(message, ...args);
}
}
}
// Create default logger instance
export const logger = new Logger();

View File

@@ -14,7 +14,6 @@ import {
} from "./ids.js"; } from "./ids.js";
import { parseJSON } from "./jsonStringify.js"; import { parseJSON } from "./jsonStringify.js";
import { JsonValue } from "./jsonValue.js"; import { JsonValue } from "./jsonValue.js";
import { logger } from "./logger.js";
import { accountOrAgentIDfromSessionID } from "./typeUtils/accountOrAgentIDfromSessionID.js"; import { accountOrAgentIDfromSessionID } from "./typeUtils/accountOrAgentIDfromSessionID.js";
import { expectGroup } from "./typeUtils/expectGroup.js"; import { expectGroup } from "./typeUtils/expectGroup.js";
@@ -47,7 +46,7 @@ function logPermissionError(...args: unknown[]) {
return; return;
} }
logger.warn("Permission error", ...args); console.warn(...args);
} }
export function determineValidTransactions( export function determineValidTransactions(
@@ -205,6 +204,7 @@ function determineValidTransactionsForGroup(
const writeKeys = new Set<string>(); const writeKeys = new Set<string>();
for (const { sessionID, txIndex, tx } of allTransactionsSorted) { for (const { sessionID, txIndex, tx } of allTransactionsSorted) {
// console.log("before", { memberState, validTransactions });
const transactor = accountOrAgentIDfromSessionID(sessionID); const transactor = accountOrAgentIDfromSessionID(sessionID);
if (tx.privacy === "private") { if (tx.privacy === "private") {
@@ -458,6 +458,8 @@ function determineValidTransactionsForGroup(
memberState[affectedMember] = change.value; memberState[affectedMember] = change.value;
validTransactions.push({ txID: { sessionID, txIndex }, tx }); validTransactions.push({ txID: { sessionID, txIndex }, tx });
// console.log("after", { memberState, validTransactions });
} }
return { validTransactions, memberState }; return { validTransactions, memberState };
@@ -471,7 +473,7 @@ function agentInAccountOrMemberInGroup(
return groupAtTime.currentAgentID().match( return groupAtTime.currentAgentID().match(
(agentID) => agentID, (agentID) => agentID,
(e) => { (e) => {
logger.error( console.error(
"Error while determining current agent ID in valid transactions", "Error while determining current agent ID in valid transactions",
e, e,
); );

View File

@@ -87,15 +87,26 @@ export async function writeBlock<WH, RH, FS extends FileSystem<WH, RH>>(
const headerBytes = textEncoder.encode(JSON.stringify(blockHeader)); const headerBytes = textEncoder.encode(JSON.stringify(blockHeader));
await fs.append(file, headerBytes); await fs.append(file, headerBytes);
// console.log(
// "full file",
// yield* $(
// fs.read(file as unknown as RH, 0, offset + headerBytes.length),
// ),
// );
const filename: BlockFilename = `L${level}-${(blockNumber + "").padStart( const filename: BlockFilename = `L${level}-${(blockNumber + "").padStart(
3, 3,
"0", "0",
)}-${hash.digest().replace("hash_", "").slice(0, 15)}-H${ )}-${hash.digest().replace("hash_", "").slice(0, 15)}-H${
headerBytes.length headerBytes.length
}.jsonl`; }.jsonl`;
// console.log("renaming to" + filename);
await fs.closeAndRename(file, filename); await fs.closeAndRename(file, filename);
return filename; return filename;
// console.log("Wrote block", filename, blockHeader);
// console.log("IDs in block", blockHeader.map(e => e.id));
} }
export async function writeToWal<WH, RH, FS extends FileSystem<WH, RH>>( export async function writeToWal<WH, RH, FS extends FileSystem<WH, RH>>(
@@ -109,5 +120,6 @@ export async function writeToWal<WH, RH, FS extends FileSystem<WH, RH>>(
...chunk, ...chunk,
}; };
const bytes = textEncoder.encode(JSON.stringify(walEntry) + "\n"); const bytes = textEncoder.encode(JSON.stringify(walEntry) + "\n");
console.log("writing to WAL", handle, id, bytes.length);
return fs.append(handle, bytes); return fs.append(handle, bytes);
} }

View File

@@ -2,7 +2,6 @@ import { CoID, RawCoValue } from "../coValue.js";
import { CoValueHeader, Transaction } from "../coValueCore.js"; import { CoValueHeader, Transaction } from "../coValueCore.js";
import { Signature } from "../crypto/crypto.js"; import { Signature } from "../crypto/crypto.js";
import { RawCoID } from "../ids.js"; import { RawCoID } from "../ids.js";
import { logger } from "../logger.js";
import { connectedPeers } from "../streamUtils.js"; import { connectedPeers } from "../streamUtils.js";
import { import {
CoValueKnownState, CoValueKnownState,
@@ -69,6 +68,7 @@ export class LSMStorage<WH, RH, FS extends FileSystem<WH, RH>> {
const processMessages = async () => { const processMessages = async () => {
for await (const msg of fromLocalNode) { for await (const msg of fromLocalNode) {
console.log("Storage msg start", nMsg);
try { try {
if (msg === "Disconnected" || msg === "PingTimeout") { if (msg === "Disconnected" || msg === "PingTimeout") {
throw new Error("Unexpected Disconnected message"); throw new Error("Unexpected Disconnected message");
@@ -83,29 +83,32 @@ export class LSMStorage<WH, RH, FS extends FileSystem<WH, RH>> {
await this.sendNewContent(msg.id, msg, undefined); await this.sendNewContent(msg.id, msg, undefined);
} }
} catch (e) { } catch (e) {
logger.error( console.error(
`Error reading from localNode, handling msg\n\n${JSON.stringify( new Error(
msg, `Error reading from localNode, handling msg\n\n${JSON.stringify(
(k, v) => msg,
k === "changes" || k === "encryptedChanges" (k, v) =>
? v.slice(0, 20) + "..." k === "changes" || k === "encryptedChanges"
: v, ? v.slice(0, 20) + "..."
)}`, : v,
e, )}`,
{ cause: e },
),
); );
} }
console.log("Storage msg end", nMsg);
nMsg++; nMsg++;
} }
}; };
processMessages().catch((e) => processMessages().catch((e) =>
logger.error("Error in processMessages in storage", e), console.error("Error in processMessages in storage", e),
); );
setTimeout( setTimeout(
() => () =>
this.compact().catch((e) => { this.compact().catch((e) => {
logger.error("Error while compacting", e); console.error("Error while compacting", e);
}), }),
20000, 20000,
); );
@@ -131,7 +134,7 @@ export class LSMStorage<WH, RH, FS extends FileSystem<WH, RH>> {
sessions: {}, sessions: {},
asDependencyOf, asDependencyOf,
}) })
.catch((e) => logger.error("Error while pushing known", e)); .catch((e) => console.error("Error while pushing known", e));
return; return;
} }
@@ -187,13 +190,13 @@ export class LSMStorage<WH, RH, FS extends FileSystem<WH, RH>> {
...ourKnown, ...ourKnown,
asDependencyOf, asDependencyOf,
}) })
.catch((e) => logger.error("Error while pushing known", e)); .catch((e) => console.error("Error while pushing known", e));
for (const message of newContentMessages) { for (const message of newContentMessages) {
if (Object.keys(message.new).length === 0) continue; if (Object.keys(message.new).length === 0) continue;
this.toLocalNode this.toLocalNode
.push(message) .push(message)
.catch((e) => logger.error("Error while pushing new content", e)); .catch((e) => console.error("Error while pushing new content", e));
} }
this.coValues[id] = coValue; this.coValues[id] = coValue;
@@ -229,19 +232,20 @@ export class LSMStorage<WH, RH, FS extends FileSystem<WH, RH>> {
if (!coValue) { if (!coValue) {
if (newContent.header) { if (newContent.header) {
// console.log("Creating in WAL", newContent.id);
await this.withWAL((wal) => await this.withWAL((wal) =>
writeToWal(wal, this.fs, newContent.id, newContentAsChunk), writeToWal(wal, this.fs, newContent.id, newContentAsChunk),
); );
this.coValues[newContent.id] = newContentAsChunk; this.coValues[newContent.id] = newContentAsChunk;
} else { } else {
logger.warn("Incontiguous incoming update for " + newContent.id); console.warn("Incontiguous incoming update for " + newContent.id);
return; return;
} }
} else { } else {
const merged = mergeChunks(coValue, newContentAsChunk); const merged = mergeChunks(coValue, newContentAsChunk);
if (merged === "nonContigous") { if (merged === "nonContigous") {
logger.warn( console.warn(
"Non-contigous new content for " + newContent.id, "Non-contigous new content for " + newContent.id,
Object.entries(coValue.sessionEntries).map(([session, entries]) => Object.entries(coValue.sessionEntries).map(([session, entries]) =>
entries.map((entry) => ({ entries.map((entry) => ({
@@ -260,6 +264,7 @@ export class LSMStorage<WH, RH, FS extends FileSystem<WH, RH>> {
), ),
); );
} else { } else {
// console.log("Appending to WAL", newContent.id);
await this.withWAL((wal) => await this.withWAL((wal) =>
writeToWal(wal, this.fs, newContent.id, newContentAsChunk), writeToWal(wal, this.fs, newContent.id, newContentAsChunk),
); );
@@ -296,6 +301,8 @@ export class LSMStorage<WH, RH, FS extends FileSystem<WH, RH>> {
const { handle, size } = await this.getBlockHandle(blockFile, fs); const { handle, size } = await this.getBlockHandle(blockFile, fs);
// console.log("Attempting to load", id, blockFile);
if (!cachedHeader) { if (!cachedHeader) {
cachedHeader = {}; cachedHeader = {};
const header = await readHeader(blockFile, handle, size, fs); const header = await readHeader(blockFile, handle, size, fs);
@@ -310,13 +317,15 @@ export class LSMStorage<WH, RH, FS extends FileSystem<WH, RH>> {
} }
const headerEntry = cachedHeader[id]; const headerEntry = cachedHeader[id];
// console.log("Header entry", id, headerEntry);
if (headerEntry) { if (headerEntry) {
const nextChunk = await readChunk(handle, headerEntry, fs); const nextChunk = await readChunk(handle, headerEntry, fs);
if (result) { if (result) {
const merged = mergeChunks(result, nextChunk); const merged = mergeChunks(result, nextChunk);
if (merged === "nonContigous") { if (merged === "nonContigous") {
logger.warn( console.warn(
"Non-contigous chunks while loading " + id, "Non-contigous chunks while loading " + id,
result, result,
nextChunk, nextChunk,
@@ -345,6 +354,7 @@ export class LSMStorage<WH, RH, FS extends FileSystem<WH, RH>> {
const coValues = new Map<RawCoID, CoValueChunk>(); const coValues = new Map<RawCoID, CoValueChunk>();
console.log("Compacting WAL files", walFiles);
if (walFiles.length === 0) return; if (walFiles.length === 0) return;
const oldWal = this.currentWal; const oldWal = this.currentWal;
@@ -375,7 +385,7 @@ export class LSMStorage<WH, RH, FS extends FileSystem<WH, RH>> {
if (existingChunk) { if (existingChunk) {
const merged = mergeChunks(existingChunk, chunk); const merged = mergeChunks(existingChunk, chunk);
if (merged === "nonContigous") { if (merged === "nonContigous") {
logger.info( console.log(
"Non-contigous chunks in " + chunk.id + ", " + fileName, "Non-contigous chunks in " + chunk.id + ", " + fileName,
existingChunk, existingChunk,
chunk, chunk,
@@ -401,6 +411,8 @@ export class LSMStorage<WH, RH, FS extends FileSystem<WH, RH>> {
return acc; return acc;
}, 0); }, 0);
console.log([...coValues.keys()], fileNames, highestBlockNumber);
await writeBlock(coValues, MAX_N_LEVELS, highestBlockNumber + 1, this.fs); await writeBlock(coValues, MAX_N_LEVELS, highestBlockNumber + 1, this.fs);
for (const walFile of walFiles) { for (const walFile of walFiles) {
@@ -426,11 +438,15 @@ export class LSMStorage<WH, RH, FS extends FileSystem<WH, RH>> {
blockFilesByLevelInOrder[level]!.push(blockFile); blockFilesByLevelInOrder[level]!.push(blockFile);
} }
console.log(blockFilesByLevelInOrder);
for (let level = MAX_N_LEVELS; level > 0; level--) { for (let level = MAX_N_LEVELS; level > 0; level--) {
const nBlocksDesired = Math.pow(2, level); const nBlocksDesired = Math.pow(2, level);
const blocksInLevel = blockFilesByLevelInOrder[level]; const blocksInLevel = blockFilesByLevelInOrder[level];
if (blocksInLevel && blocksInLevel.length > nBlocksDesired) { if (blocksInLevel && blocksInLevel.length > nBlocksDesired) {
console.log("Compacting blocks in level", level, blocksInLevel);
const coValues = new Map<RawCoID, CoValueChunk>(); const coValues = new Map<RawCoID, CoValueChunk>();
for (const blockFile of blocksInLevel) { for (const blockFile of blocksInLevel) {
@@ -449,7 +465,7 @@ export class LSMStorage<WH, RH, FS extends FileSystem<WH, RH>> {
if (existingChunk) { if (existingChunk) {
const merged = mergeChunks(existingChunk, chunk); const merged = mergeChunks(existingChunk, chunk);
if (merged === "nonContigous") { if (merged === "nonContigous") {
logger.info( console.log(
"Non-contigous chunks in " + entry.id + ", " + blockFile, "Non-contigous chunks in " + entry.id + ", " + blockFile,
existingChunk, existingChunk,
chunk, chunk,
@@ -501,7 +517,7 @@ export class LSMStorage<WH, RH, FS extends FileSystem<WH, RH>> {
setTimeout( setTimeout(
() => () =>
this.compact().catch((e) => { this.compact().catch((e) => {
logger.error("Error while compacting", e); console.error("Error while compacting", e);
}), }),
5000, 5000,
); );

View File

@@ -6,7 +6,6 @@ import { CoValueCore } from "./coValueCore.js";
import { Signature } from "./crypto/crypto.js"; import { Signature } from "./crypto/crypto.js";
import { RawCoID, SessionID } from "./ids.js"; import { RawCoID, SessionID } from "./ids.js";
import { LocalNode } from "./localNode.js"; import { LocalNode } from "./localNode.js";
import { logger } from "./logger.js";
import { CoValuePriority } from "./priority.js"; import { CoValuePriority } from "./priority.js";
export type CoValueKnownState = { export type CoValueKnownState = {
@@ -151,7 +150,7 @@ export class SyncManager {
async handleSyncMessage(msg: SyncMessage, peer: PeerState) { async handleSyncMessage(msg: SyncMessage, peer: PeerState) {
if (peer.erroredCoValues.has(msg.id)) { if (peer.erroredCoValues.has(msg.id)) {
logger.warn( console.error(
`Skipping message ${msg.action} on errored coValue ${msg.id} from peer ${peer.id}`, `Skipping message ${msg.action} on errored coValue ${msg.id} from peer ${peer.id}`,
); );
return; return;
@@ -183,7 +182,7 @@ export class SyncManager {
if (entry.state.type !== "available") { if (entry.state.type !== "available") {
entry.loadFromPeers([peer]).catch((e: unknown) => { entry.loadFromPeers([peer]).catch((e: unknown) => {
logger.error("Error sending load", e); console.error("Error sending load", e);
}); });
return; return;
} }
@@ -200,7 +199,7 @@ export class SyncManager {
action: "load", action: "load",
...coValue.knownState(), ...coValue.knownState(),
}).catch((e: unknown) => { }).catch((e: unknown) => {
logger.error("Error sending load", e); console.error("Error sending load", e);
}); });
} }
} }
@@ -230,7 +229,7 @@ export class SyncManager {
asDependencyOf, asDependencyOf,
...coValue.knownState(), ...coValue.knownState(),
}).catch((e: unknown) => { }).catch((e: unknown) => {
logger.error("Error sending known state", e); console.error("Error sending known state", e);
}); });
peer.toldKnownState.add(id); peer.toldKnownState.add(id);
@@ -257,8 +256,15 @@ export class SyncManager {
const sendPieces = async () => { const sendPieces = async () => {
let lastYield = performance.now(); let lastYield = performance.now();
for (const [_i, piece] of newContentPieces.entries()) { for (const [_i, piece] of newContentPieces.entries()) {
// console.log(
// `${id} -> ${peer.id}: Sending content piece ${i + 1}/${
// newContentPieces.length
// } header: ${!!piece.header}`,
// // Object.values(piece.new).map((s) => s.newTransactions)
// );
this.trySendToPeer(peer, piece).catch((e: unknown) => { this.trySendToPeer(peer, piece).catch((e: unknown) => {
logger.error("Error sending content piece", e); console.error("Error sending content piece", e);
}); });
if (performance.now() - lastYield > 10) { if (performance.now() - lastYield > 10) {
@@ -271,7 +277,7 @@ export class SyncManager {
}; };
sendPieces().catch((e) => { sendPieces().catch((e) => {
logger.error("Error sending new content piece, retrying", e); console.error("Error sending new content piece, retrying", e);
peer.optimisticKnownStates.dispatch({ peer.optimisticKnownStates.dispatch({
type: "SET", type: "SET",
id, id,
@@ -331,7 +337,7 @@ export class SyncManager {
return; return;
} }
if (msg === "PingTimeout") { if (msg === "PingTimeout") {
logger.error("Ping timeout from peer", peer.id); console.error("Ping timeout from peer", peer.id);
return; return;
} }
try { try {
@@ -354,13 +360,13 @@ export class SyncManager {
processMessages() processMessages()
.then(() => { .then(() => {
if (peer.crashOnClose) { if (peer.crashOnClose) {
logger.warn("Unexepcted close from peer", peer.id); console.error("Unexepcted close from peer", peer.id);
this.local.crashed = new Error("Unexpected close from peer"); this.local.crashed = new Error("Unexpected close from peer");
throw new Error("Unexpected close from peer"); throw new Error("Unexpected close from peer");
} }
}) })
.catch((e) => { .catch((e) => {
logger.error("Error processing messages from peer", peer.id, e); console.error("Error processing messages from peer", peer.id, e);
if (peer.crashOnClose) { if (peer.crashOnClose) {
this.local.crashed = e; this.local.crashed = e;
throw new Error(e); throw new Error(e);
@@ -400,13 +406,13 @@ export class SyncManager {
// where we can get informations about the coValue // where we can get informations about the coValue
if (msg.header || Object.keys(msg.sessions).length > 0) { if (msg.header || Object.keys(msg.sessions).length > 0) {
entry.loadFromPeers([peer]).catch((e) => { entry.loadFromPeers([peer]).catch((e) => {
logger.error("Error loading coValue in handleLoad", e); console.error("Error loading coValue in handleLoad", e);
}); });
} }
return; return;
} else { } else {
this.local.loadCoValueCore(msg.id, peer.id).catch((e) => { this.local.loadCoValueCore(msg.id, peer.id).catch((e) => {
logger.error("Error loading coValue in handleLoad", e); console.error("Error loading coValue in handleLoad", e);
}); });
} }
} }
@@ -433,7 +439,7 @@ export class SyncManager {
header: false, header: false,
sessions: {}, sessions: {},
}).catch((e) => { }).catch((e) => {
logger.error("Error sending known state back", e); console.error("Error sending known state back", e);
}); });
return; return;
@@ -443,7 +449,7 @@ export class SyncManager {
await this.sendNewContentIncludingDependencies(msg.id, peer); await this.sendNewContentIncludingDependencies(msg.id, peer);
}) })
.catch((e) => { .catch((e) => {
logger.error("Error loading coValue in handleLoad loading state", e); console.error("Error loading coValue in handleLoad loading state", e);
}); });
} }
@@ -478,7 +484,7 @@ export class SyncManager {
peer.role === "storage" ? undefined : peer.id, peer.role === "storage" ? undefined : peer.id,
) )
.catch((e) => { .catch((e) => {
logger.error( console.error(
`Error loading coValue ${msg.id} to create loading state, as dependency of ${msg.asDependencyOf}`, `Error loading coValue ${msg.id} to create loading state, as dependency of ${msg.asDependencyOf}`,
e, e,
); );
@@ -515,7 +521,7 @@ export class SyncManager {
if (entry.state.type !== "available") { if (entry.state.type !== "available") {
if (!msg.header) { if (!msg.header) {
logger.error("Expected header to be sent in first message"); console.error("Expected header to be sent in first message");
return; return;
} }
@@ -578,7 +584,7 @@ export class SyncManager {
: t.changes.length, : t.changes.length,
) )
.reduce((a, b) => a + b, 0); .reduce((a, b) => a + b, 0);
logger.debug( console.log(
`Adding incoming transactions took ${(after - before).toFixed( `Adding incoming transactions took ${(after - before).toFixed(
2, 2,
)}ms for ${totalTxLength} bytes = bandwidth: ${( )}ms for ${totalTxLength} bytes = bandwidth: ${(
@@ -596,7 +602,7 @@ export class SyncManager {
// ); // );
if (result.isErr()) { if (result.isErr()) {
logger.error( console.error(
"Failed to add transactions from", "Failed to add transactions from",
peer.id, peer.id,
result.error, result.error,
@@ -627,7 +633,7 @@ export class SyncManager {
isCorrection: true, isCorrection: true,
...coValue.knownState(), ...coValue.knownState(),
}).catch((e) => { }).catch((e) => {
logger.error("Error sending known state correction", e); console.error("Error sending known state correction", e);
}); });
} else { } else {
/** /**
@@ -641,7 +647,7 @@ export class SyncManager {
action: "known", action: "known",
...coValue.knownState(), ...coValue.knownState(),
}).catch((e: unknown) => { }).catch((e: unknown) => {
logger.error("Error sending known state", e); console.error("Error sending known state", e);
}); });
} }
@@ -675,6 +681,9 @@ export class SyncManager {
const done = new Promise<void>((resolve) => { const done = new Promise<void>((resolve) => {
queueMicrotask(async () => { queueMicrotask(async () => {
delete this.requestedSyncs[coValue.id]; delete this.requestedSyncs[coValue.id];
// if (entry.nRequestsThisTick >= 2) {
// console.log("Syncing", coValue.id, "for", entry.nRequestsThisTick, "requests");
// }
await this.actuallySyncCoValue(coValue); await this.actuallySyncCoValue(coValue);
resolve(); resolve();
}); });

View File

@@ -49,9 +49,12 @@ describe("PeerState", () => {
test("should perform graceful shutdown", () => { test("should perform graceful shutdown", () => {
const { mockPeer, peerState } = setup(); const { mockPeer, peerState } = setup();
const consoleSpy = vi.spyOn(console, "debug").mockImplementation(() => {});
peerState.gracefulShutdown(); peerState.gracefulShutdown();
expect(mockPeer.outgoing.close).toHaveBeenCalled(); expect(mockPeer.outgoing.close).toHaveBeenCalled();
expect(peerState.closed).toBe(true); expect(peerState.closed).toBe(true);
expect(consoleSpy).toHaveBeenCalledWith("Gracefully closing", "test-peer");
consoleSpy.mockRestore();
}); });
test("should empty the queue when closing", async () => { test("should empty the queue when closing", async () => {

View File

@@ -1,145 +0,0 @@
import { describe, expect, test, vi } from "vitest";
import { LogLevel, Logger } from "../logger";
describe("Logger", () => {
describe("Log Level Filtering", () => {
test("should respect log level hierarchy", () => {
const mockLogSystem = {
debug: vi.fn(),
info: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
};
const logger = new Logger(LogLevel.WARN, mockLogSystem);
logger.debug("Debug message");
logger.info("Info message");
logger.warn("Warning message");
logger.error("Error message");
expect(mockLogSystem.debug).not.toHaveBeenCalled();
expect(mockLogSystem.info).not.toHaveBeenCalled();
expect(mockLogSystem.warn).toHaveBeenCalledWith("Warning message");
expect(mockLogSystem.error).toHaveBeenCalledWith("Error message");
});
test("should pass additional arguments to log system", () => {
const mockLogSystem = {
debug: vi.fn(),
info: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
};
const logger = new Logger(LogLevel.DEBUG, mockLogSystem);
const additionalArgs = [{ foo: "bar" }, 42, "extra"];
logger.debug("Debug message", ...additionalArgs);
expect(mockLogSystem.debug).toHaveBeenCalledWith(
"Debug message",
...additionalArgs,
);
});
});
describe("Log System Configuration", () => {
test("should allow changing log level at runtime", () => {
const mockLogSystem = {
debug: vi.fn(),
info: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
};
const logger = new Logger(LogLevel.ERROR, mockLogSystem);
logger.warn("Warning 1"); // Should not log
expect(mockLogSystem.warn).not.toHaveBeenCalled();
logger.setLevel(LogLevel.WARN);
logger.warn("Warning 2"); // Should log
expect(mockLogSystem.warn).toHaveBeenCalledWith("Warning 2");
});
test("should allow changing log system at runtime", () => {
const mockLogSystem1 = {
debug: vi.fn(),
info: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
};
const mockLogSystem2 = {
debug: vi.fn(),
info: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
};
const logger = new Logger(LogLevel.INFO, mockLogSystem1);
logger.info("Message 1");
expect(mockLogSystem1.info).toHaveBeenCalledWith("Message 1");
expect(mockLogSystem2.info).not.toHaveBeenCalled();
logger.setLogSystem(mockLogSystem2);
logger.info("Message 2");
expect(mockLogSystem2.info).toHaveBeenCalledWith("Message 2");
expect(mockLogSystem1.info).toHaveBeenCalledTimes(1);
});
});
describe("Default Console Log System", () => {
test("should use console methods by default", () => {
const consoleSpy = {
debug: vi.spyOn(console, "debug").mockImplementation(() => {}),
info: vi.spyOn(console, "info").mockImplementation(() => {}),
warn: vi.spyOn(console, "warn").mockImplementation(() => {}),
error: vi.spyOn(console, "error").mockImplementation(() => {}),
};
const logger = new Logger();
logger.setLevel(LogLevel.DEBUG);
const testMessage = "Test message";
const testArgs = [{ data: "test" }, 123];
logger.debug(testMessage, ...testArgs);
logger.info(testMessage, ...testArgs);
logger.warn(testMessage, ...testArgs);
logger.error(testMessage, ...testArgs);
expect(consoleSpy.debug).toHaveBeenCalledWith(testMessage, ...testArgs);
expect(consoleSpy.info).toHaveBeenCalledWith(testMessage, ...testArgs);
expect(consoleSpy.warn).toHaveBeenCalledWith(testMessage, ...testArgs);
expect(consoleSpy.error).toHaveBeenCalledWith(testMessage, ...testArgs);
// Cleanup
Object.values(consoleSpy).forEach((spy) => spy.mockRestore());
});
});
describe("Log Level NONE", () => {
test("should not log anything when level is NONE", () => {
const mockLogSystem = {
debug: vi.fn(),
info: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
};
const logger = new Logger(LogLevel.NONE, mockLogSystem);
logger.debug("Debug message");
logger.info("Info message");
logger.warn("Warning message");
logger.error("Error message");
expect(mockLogSystem.debug).not.toHaveBeenCalled();
expect(mockLogSystem.info).not.toHaveBeenCalled();
expect(mockLogSystem.warn).not.toHaveBeenCalled();
expect(mockLogSystem.error).not.toHaveBeenCalled();
});
});
});

View File

@@ -1,5 +1,14 @@
# jazz-browser-media-images # jazz-browser-media-images
## 0.9.12
### Patch Changes
- Updated dependencies [15d4b2a]
- cojson@0.9.12
- jazz-browser@0.9.12
- jazz-tools@0.9.12
## 0.9.11 ## 0.9.11
### Patch Changes ### Patch Changes

View File

@@ -1,14 +1,14 @@
{ {
"name": "jazz-browser-auth-clerk", "name": "jazz-browser-auth-clerk",
"version": "0.9.11", "version": "0.9.12",
"type": "module", "type": "module",
"main": "dist/index.js", "main": "dist/index.js",
"types": "src/index.ts", "types": "src/index.ts",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"cojson": "workspace:0.9.11", "cojson": "workspace:0.9.12",
"jazz-browser": "workspace:0.9.11", "jazz-browser": "workspace:0.9.12",
"jazz-tools": "workspace:0.9.11" "jazz-tools": "workspace:0.9.12"
}, },
"scripts": { "scripts": {
"format-and-lint": "biome check .", "format-and-lint": "biome check .",

View File

@@ -1,5 +1,12 @@
# jazz-browser-media-images # jazz-browser-media-images
## 0.9.12
### Patch Changes
- jazz-browser@0.9.12
- jazz-tools@0.9.12
## 0.9.11 ## 0.9.11
### Patch Changes ### Patch Changes

View File

@@ -1,6 +1,6 @@
{ {
"name": "jazz-browser-media-images", "name": "jazz-browser-media-images",
"version": "0.9.11", "version": "0.9.12",
"type": "module", "type": "module",
"main": "dist/index.js", "main": "dist/index.js",
"types": "src/index.ts", "types": "src/index.ts",
@@ -8,8 +8,8 @@
"dependencies": { "dependencies": {
"@types/image-blob-reduce": "^4.1.1", "@types/image-blob-reduce": "^4.1.1",
"image-blob-reduce": "^4.1.0", "image-blob-reduce": "^4.1.0",
"jazz-browser": "workspace:0.9.11", "jazz-browser": "workspace:0.9.12",
"jazz-tools": "workspace:0.9.11", "jazz-tools": "workspace:0.9.12",
"pica": "^9.0.1", "pica": "^9.0.1",
"typescript": "~5.6.2" "typescript": "~5.6.2"
}, },

View File

@@ -1,5 +1,15 @@
# jazz-browser # jazz-browser
## 0.9.12
### Patch Changes
- Updated dependencies [15d4b2a]
- cojson-transport-ws@0.9.12
- cojson@0.9.12
- cojson-storage-indexeddb@0.9.12
- jazz-tools@0.9.12
## 0.9.11 ## 0.9.11
### Patch Changes ### Patch Changes

View File

@@ -1,16 +1,16 @@
{ {
"name": "jazz-browser", "name": "jazz-browser",
"version": "0.9.11", "version": "0.9.12",
"type": "module", "type": "module",
"main": "dist/index.js", "main": "dist/index.js",
"types": "src/index.ts", "types": "src/index.ts",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@scure/bip39": "^1.3.0", "@scure/bip39": "^1.3.0",
"cojson": "workspace:0.9.11", "cojson": "workspace:0.9.12",
"cojson-storage-indexeddb": "workspace:0.9.11", "cojson-storage-indexeddb": "workspace:0.9.12",
"cojson-transport-ws": "workspace:0.9.11", "cojson-transport-ws": "workspace:0.9.12",
"jazz-tools": "workspace:0.9.11", "jazz-tools": "workspace:0.9.12",
"typescript": "~5.6.2" "typescript": "~5.6.2"
}, },
"scripts": { "scripts": {

View File

@@ -1,5 +1,14 @@
# jazz-inspector # jazz-inspector
## 0.9.12
### Patch Changes
- Updated dependencies [15d4b2a]
- cojson@0.9.12
- jazz-react-core@0.8.53
- jazz-tools@0.9.12
## 0.9.11 ## 0.9.11
### Patch Changes ### Patch Changes

View File

@@ -1,6 +1,6 @@
{ {
"name": "jazz-inspector", "name": "jazz-inspector",
"version": "0.9.11", "version": "0.9.12",
"type": "module", "type": "module",
"main": "./dist/jazz-inspector.js", "main": "./dist/jazz-inspector.js",
"types": "./src/app.tsx", "types": "./src/app.tsx",

View File

@@ -1,5 +1,14 @@
# jazz-autosub # jazz-autosub
## 0.9.12
### Patch Changes
- Updated dependencies [15d4b2a]
- cojson-transport-ws@0.9.12
- cojson@0.9.12
- jazz-tools@0.9.12
## 0.9.11 ## 0.9.11
### Patch Changes ### Patch Changes

View File

@@ -5,11 +5,11 @@
"types": "src/index.ts", "types": "src/index.ts",
"type": "module", "type": "module",
"license": "MIT", "license": "MIT",
"version": "0.9.11", "version": "0.9.12",
"dependencies": { "dependencies": {
"cojson": "workspace:0.9.11", "cojson": "workspace:0.9.12",
"cojson-transport-ws": "workspace:0.9.11", "cojson-transport-ws": "workspace:0.9.12",
"jazz-tools": "workspace:0.9.11", "jazz-tools": "workspace:0.9.12",
"ws": "^8.14.2" "ws": "^8.14.2"
}, },
"devDependencies": { "devDependencies": {

View File

@@ -1,5 +1,15 @@
# jazz-browser-media-images # jazz-browser-media-images
## 0.9.12
### Patch Changes
- Updated dependencies [15d4b2a]
- cojson@0.9.12
- jazz-browser-auth-clerk@0.9.12
- jazz-react@0.9.12
- jazz-tools@0.9.12
## 0.9.11 ## 0.9.11
### Patch Changes ### Patch Changes

View File

@@ -1,15 +1,15 @@
{ {
"name": "jazz-react-auth-clerk", "name": "jazz-react-auth-clerk",
"version": "0.9.11", "version": "0.9.12",
"type": "module", "type": "module",
"main": "dist/index.js", "main": "dist/index.js",
"types": "src/index.tsx", "types": "src/index.tsx",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"cojson": "workspace:0.9.11", "cojson": "workspace:0.9.12",
"jazz-browser-auth-clerk": "workspace:0.9.11", "jazz-browser-auth-clerk": "workspace:0.9.12",
"jazz-react": "workspace:0.9.11", "jazz-react": "workspace:0.9.12",
"jazz-tools": "workspace:0.9.11" "jazz-tools": "workspace:0.9.12"
}, },
"peerDependencies": { "peerDependencies": {
"react": "^18.2.0" "react": "^18.2.0"

View File

@@ -1,5 +1,13 @@
# jazz-react-core # jazz-react-core
## 0.8.53
### Patch Changes
- Updated dependencies [15d4b2a]
- cojson@0.9.12
- jazz-tools@0.9.12
## 0.8.52 ## 0.8.52
### Patch Changes ### Patch Changes

View File

@@ -1,6 +1,6 @@
{ {
"name": "jazz-react-core", "name": "jazz-react-core",
"version": "0.8.52", "version": "0.8.53",
"type": "module", "type": "module",
"main": "dist/index.js", "main": "dist/index.js",
"types": "src/index.ts", "types": "src/index.ts",

View File

@@ -1,5 +1,14 @@
# jazz-react-native-auth-clerk # jazz-react-native-auth-clerk
## 0.9.12
### Patch Changes
- Updated dependencies [15d4b2a]
- cojson@0.9.12
- jazz-react-native@0.9.12
- jazz-tools@0.9.12
## 0.9.11 ## 0.9.11
### Patch Changes ### Patch Changes

View File

@@ -1,6 +1,6 @@
{ {
"name": "jazz-react-native-auth-clerk", "name": "jazz-react-native-auth-clerk",
"version": "0.9.11", "version": "0.9.12",
"type": "module", "type": "module",
"main": "dist/index.js", "main": "dist/index.js",
"types": "src/index.ts", "types": "src/index.ts",

View File

@@ -1,5 +1,11 @@
# jazz-browser-media-images # jazz-browser-media-images
## 0.9.12
### Patch Changes
- jazz-tools@0.9.12
## 0.9.11 ## 0.9.11
### Patch Changes ### Patch Changes

View File

@@ -1,6 +1,6 @@
{ {
"name": "jazz-react-native-media-images", "name": "jazz-react-native-media-images",
"version": "0.9.11", "version": "0.9.12",
"type": "module", "type": "module",
"main": "dist/index.js", "main": "dist/index.js",
"types": "src/index.ts", "types": "src/index.ts",

View File

@@ -1,5 +1,16 @@
# jazz-browser # jazz-browser
## 0.9.12
### Patch Changes
- Updated dependencies [15d4b2a]
- cojson-transport-ws@0.9.12
- cojson@0.9.12
- cojson-storage-rn-sqlite@0.8.55
- jazz-react-core@0.8.53
- jazz-tools@0.9.12
## 0.9.11 ## 0.9.11
### Patch Changes ### Patch Changes

View File

@@ -1,6 +1,6 @@
{ {
"name": "jazz-react-native", "name": "jazz-react-native",
"version": "0.9.11", "version": "0.9.12",
"type": "module", "type": "module",
"main": "./dist/index.js", "main": "./dist/index.js",
"module": "./dist/index.js", "module": "./dist/index.js",

View File

@@ -7,6 +7,7 @@ import {
TextInput, TextInput,
TouchableOpacity, TouchableOpacity,
View, View,
useColorScheme,
} from "react-native"; } from "react-native";
import { KvStore } from "../storage/kv-store-context.js"; import { KvStore } from "../storage/kv-store-context.js";
import { RNDemoAuth } from "./DemoAuthMethod.js"; import { RNDemoAuth } from "./DemoAuthMethod.js";
@@ -104,7 +105,8 @@ export const DemoAuthBasicUI = ({
appName: string; appName: string;
state: DemoAuthState; state: DemoAuthState;
}) => { }) => {
const darkMode = false; const colorScheme = useColorScheme();
const darkMode = colorScheme === "dark";
const [username, setUsername] = useState<string>(""); const [username, setUsername] = useState<string>("");
const [errorMessage, setErrorMessage] = useState<string | null>(null); const [errorMessage, setErrorMessage] = useState<string | null>(null);

View File

@@ -1,5 +1,15 @@
# jazz-react # jazz-react
## 0.9.12
### Patch Changes
- Updated dependencies [15d4b2a]
- cojson@0.9.12
- jazz-browser@0.9.12
- jazz-react-core@0.8.53
- jazz-tools@0.9.12
## 0.9.11 ## 0.9.11
### Patch Changes ### Patch Changes

View File

@@ -1,6 +1,6 @@
{ {
"name": "jazz-react", "name": "jazz-react",
"version": "0.9.11", "version": "0.9.12",
"type": "module", "type": "module",
"main": "dist/index.js", "main": "dist/index.js",
"types": "src/index.ts", "types": "src/index.ts",
@@ -17,9 +17,9 @@
}, },
"dependencies": { "dependencies": {
"@scure/bip39": "^1.3.0", "@scure/bip39": "^1.3.0",
"cojson": "workspace:0.9.11", "cojson": "workspace:0.9.12",
"jazz-browser": "workspace:0.9.11", "jazz-browser": "workspace:0.9.12",
"jazz-tools": "workspace:0.9.11", "jazz-tools": "workspace:0.9.12",
"jazz-react-core": "workspace:*" "jazz-react-core": "workspace:*"
}, },
"devDependencies": { "devDependencies": {

Some files were not shown because too many files have changed in this diff Show More