@xnetjs/sqlite 0.0.2 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/dist/{adapter-I7yAV6iu.d.ts → adapter-imtxkmXZ.d.ts} +48 -1
  2. package/dist/adapters/electron.d.ts +70 -6
  3. package/dist/adapters/electron.js +662 -36
  4. package/dist/adapters/expo.d.ts +6 -2
  5. package/dist/adapters/expo.js +34 -6
  6. package/dist/adapters/memory.d.ts +6 -2
  7. package/dist/adapters/memory.js +8 -1
  8. package/dist/adapters/reader-thread.d.ts +78 -0
  9. package/dist/adapters/reader-thread.js +57 -0
  10. package/dist/adapters/web-proxy.d.ts +71 -3
  11. package/dist/adapters/web-proxy.js +554 -39
  12. package/dist/adapters/web-router-worker.d.ts +76 -0
  13. package/dist/adapters/web-router-worker.js +91 -0
  14. package/dist/adapters/web-worker.d.ts +56 -1
  15. package/dist/adapters/web-worker.js +253 -14
  16. package/dist/adapters/web.d.ts +90 -3
  17. package/dist/adapters/web.js +10 -4
  18. package/dist/browser-support.d.ts +65 -1
  19. package/dist/browser-support.js +15 -3
  20. package/dist/chunk-5HC5V73T.js +191 -0
  21. package/dist/chunk-BBZDKLA3.js +727 -0
  22. package/dist/chunk-CBU263LI.js +30 -0
  23. package/dist/chunk-CGI2YBZY.js +16 -0
  24. package/dist/chunk-S6MT6KCI.js +279 -0
  25. package/dist/chunk-SV475UL5.js +44 -0
  26. package/dist/chunk-W3L4FXU5.js +415 -0
  27. package/dist/index.d.ts +111 -8
  28. package/dist/index.js +219 -130
  29. package/dist/schema-C4gufY3B.d.ts +35 -0
  30. package/dist/types-BTabr_VP.d.ts +225 -0
  31. package/dist/worker-scheduler-D04DqMmR.d.ts +56 -0
  32. package/package.json +5 -1
  33. package/dist/chunk-BXYZU3OL.js +0 -245
  34. package/dist/chunk-HIREU5S5.js +0 -193
  35. package/dist/chunk-ZRR5D2OD.js +0 -140
  36. package/dist/schema-CjkXTqxn.d.ts +0 -35
  37. package/dist/types-C_aHfRDF.d.ts +0 -42
@@ -0,0 +1,56 @@
1
+ /**
2
+ * @xnetjs/sqlite - Priority scheduler for the single SQLite worker
3
+ *
4
+ * The web app funnels every storage operation — interactive reads, background
5
+ * writes, sync-apply batches — through ONE SQLite worker thread (exploration
6
+ * 0227). With no scheduling, the worker serves Comlink calls in arrival order,
7
+ * so an interactive read can be stuck behind a burst of queued writes. 0227
8
+ * fixed the one pathological 18s op; this scheduler generalises the fix so that
9
+ * *no* queued operation can starve an interactive read (exploration 0228).
10
+ *
11
+ * It does NOT add parallelism — a single OPFS connection is inherently serial
12
+ * (the `opfs-sahpool` VFS holds exclusive file handles, so multiple reader
13
+ * workers on the same DB are impossible). What it adds is **ordering**: queued
14
+ * work drains highest-priority-lane first, and identical concurrent reads are
15
+ * coalesced into a single execution.
16
+ *
17
+ * Safety: jobs run strictly one-at-a-time (no preemption of an in-flight op),
18
+ * which matches SQLite's single-connection serialization — operations on one
19
+ * connection are never truly concurrent anyway. A job already executing always
20
+ * completes before the next is dequeued.
21
+ */
22
+ /** Priority lanes, drained in this order: interactive → bulk → write. */
23
+ type SchedulerLane = 'interactive' | 'bulk' | 'write';
24
+ /** Point-in-time view of scheduler depth (for diagnostics / the perf panel). */
25
+ interface SchedulerSnapshot {
26
+ interactive: number;
27
+ bulk: number;
28
+ write: number;
29
+ /** Whether a job is currently executing. */
30
+ inFlight: boolean;
31
+ }
32
+ /** Aggregated per-lane op latency (exploration 0263). All ms values rounded. */
33
+ interface SchedulerLaneOpStats {
34
+ /** Ops executed on this lane since open/reset. */
35
+ ops: number;
36
+ queueP50Ms: number;
37
+ queueP95Ms: number;
38
+ execP50Ms: number;
39
+ execP95Ms: number;
40
+ /** Worst single execution — the head-of-line-blocking amplitude. */
41
+ maxExecMs: number;
42
+ }
43
+ /**
44
+ * Cumulative scheduler statistics: how many ops ran, how many duplicate reads
45
+ * were served without executing (coalesced), and per-lane latency percentiles.
46
+ * This is the "p50/p95 per-query worker time" measurement of exploration 0263 —
47
+ * the number that says whether the statement cache / batch RPC actually moved
48
+ * anything, without wading through per-op boot-log lines.
49
+ */
50
+ interface SchedulerOpStats {
51
+ ops: number;
52
+ coalescedHits: number;
53
+ lanes: Record<SchedulerLane, SchedulerLaneOpStats>;
54
+ }
55
+
56
+ export type { SchedulerSnapshot as S, SchedulerOpStats as a };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xnetjs/sqlite",
3
- "version": "0.0.2",
3
+ "version": "0.1.0",
4
4
  "description": "Unified SQLite adapter for xNet across all platforms",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -31,6 +31,10 @@
31
31
  "import": "./dist/adapters/web-worker.js",
32
32
  "types": "./dist/adapters/web-worker.d.ts"
33
33
  },
34
+ "./web-router-worker": {
35
+ "import": "./dist/adapters/web-router-worker.js",
36
+ "types": "./dist/adapters/web-router-worker.d.ts"
37
+ },
34
38
  "./browser-support": {
35
39
  "import": "./dist/browser-support.js",
36
40
  "types": "./dist/browser-support.d.ts"
@@ -1,245 +0,0 @@
1
- import {
2
- SCHEMA_DDL,
3
- SCHEMA_VERSION
4
- } from "./chunk-HIREU5S5.js";
5
-
6
- // src/adapters/web.ts
7
- function isDebugEnabled() {
8
- return typeof self !== "undefined" && typeof localStorage !== "undefined" && localStorage.getItem("xnet:sqlite:debug") === "true";
9
- }
10
- function log(...args) {
11
- if (isDebugEnabled()) {
12
- console.log(...args);
13
- }
14
- }
15
- var WebSQLiteAdapter = class {
16
- sqlite3 = null;
17
- db = null;
18
- poolUtil = null;
19
- _config = null;
20
- inTransaction = false;
21
- storageMode = "memory";
22
- async open(config) {
23
- if (this.db !== null) {
24
- throw new Error("Database already open. Call close() first.");
25
- }
26
- log("[WebSQLiteAdapter] Starting open()...");
27
- log("[WebSQLiteAdapter] Importing sqlite-wasm...");
28
- const sqlite3InitModule = (await import("@sqlite.org/sqlite-wasm")).default;
29
- log("[WebSQLiteAdapter] sqlite-wasm imported");
30
- log("[WebSQLiteAdapter] Initializing sqlite3 module...");
31
- this.sqlite3 = await sqlite3InitModule();
32
- log("[WebSQLiteAdapter] sqlite3 module initialized");
33
- try {
34
- log("[WebSQLiteAdapter] Installing OPFS-SAHPool VFS...");
35
- this.poolUtil = await this.sqlite3.installOpfsSAHPoolVfs({
36
- name: "opfs-sahpool",
37
- directory: ".xnet-sqlite",
38
- initialCapacity: 10,
39
- // Support ~3-4 databases with journals
40
- clearOnInit: false
41
- });
42
- log("[WebSQLiteAdapter] OPFS-SAHPool VFS installed");
43
- log("[WebSQLiteAdapter] Reserving capacity...");
44
- await this.poolUtil.reserveMinimumCapacity(10);
45
- log("[WebSQLiteAdapter] Capacity reserved");
46
- const dbPath = config.path.startsWith("/") ? config.path : `/${config.path}`;
47
- log("[WebSQLiteAdapter] Opening database at", dbPath);
48
- this.db = new this.poolUtil.OpfsSAHPoolDb(dbPath, "c");
49
- this.storageMode = "opfs";
50
- log("[WebSQLiteAdapter] Database opened with OPFS-SAHPool");
51
- } catch (err) {
52
- console.warn("[WebSQLiteAdapter] OPFS-SAHPool not available, trying OPFS direct mode:", err);
53
- const dbPath = config.path.startsWith("/") ? config.path : `/${config.path}`;
54
- const opfsDbCtor = this.sqlite3?.oo1?.OpfsDb;
55
- if (typeof opfsDbCtor === "function") {
56
- try {
57
- this.db = new opfsDbCtor(dbPath, "c");
58
- this.storageMode = "opfs";
59
- log("[WebSQLiteAdapter] Database opened with OPFS direct mode");
60
- } catch (opfsErr) {
61
- console.warn(
62
- "[WebSQLiteAdapter] OPFS direct mode not available, using in-memory database:",
63
- opfsErr
64
- );
65
- this.db = new this.sqlite3.oo1.DB(":memory:", "c");
66
- this.storageMode = "memory";
67
- log("[WebSQLiteAdapter] In-memory database opened");
68
- }
69
- } else {
70
- console.warn("[WebSQLiteAdapter] OPFS direct mode unavailable, using in-memory database");
71
- this.db = new this.sqlite3.oo1.DB(":memory:", "c");
72
- this.storageMode = "memory";
73
- log("[WebSQLiteAdapter] In-memory database opened");
74
- }
75
- }
76
- this._config = config;
77
- if (config.foreignKeys !== false) {
78
- this.execSync("PRAGMA foreign_keys = ON");
79
- }
80
- if (config.busyTimeout) {
81
- this.execSync(`PRAGMA busy_timeout = ${config.busyTimeout}`);
82
- } else {
83
- this.execSync("PRAGMA busy_timeout = 5000");
84
- }
85
- this.execSync("PRAGMA synchronous = NORMAL");
86
- this.execSync("PRAGMA cache_size = -64000");
87
- this.execSync("PRAGMA temp_store = MEMORY");
88
- }
89
- async close() {
90
- if (this.db) {
91
- this.db.close();
92
- this.db = null;
93
- }
94
- this.sqlite3 = null;
95
- this.poolUtil = null;
96
- this._config = null;
97
- }
98
- isOpen() {
99
- return this.db !== null;
100
- }
101
- getStorageMode() {
102
- return this.storageMode;
103
- }
104
- async query(sql, params) {
105
- this.ensureOpen();
106
- const rows = [];
107
- this.db.exec({
108
- sql,
109
- bind: params,
110
- rowMode: "object",
111
- callback: (row) => {
112
- rows.push(row);
113
- }
114
- });
115
- return rows;
116
- }
117
- async queryOne(sql, params) {
118
- const rows = await this.query(sql, params);
119
- return rows[0] ?? null;
120
- }
121
- async run(sql, params) {
122
- this.ensureOpen();
123
- this.db.exec({
124
- sql,
125
- bind: params
126
- });
127
- return {
128
- changes: this.sqlite3.capi.sqlite3_changes(this.db.pointer),
129
- lastInsertRowid: this.sqlite3.capi.sqlite3_last_insert_rowid(this.db.pointer)
130
- };
131
- }
132
- async exec(sql) {
133
- this.ensureOpen();
134
- this.execSync(sql);
135
- }
136
- execSync(sql) {
137
- this.db.exec({ sql });
138
- }
139
- async transaction(fn) {
140
- await this.beginTransaction();
141
- try {
142
- const result = await fn();
143
- await this.commit();
144
- return result;
145
- } catch (err) {
146
- await this.rollback();
147
- throw err;
148
- }
149
- }
150
- async beginTransaction() {
151
- if (this.inTransaction) {
152
- throw new Error("Transaction already in progress");
153
- }
154
- this.execSync("BEGIN IMMEDIATE");
155
- this.inTransaction = true;
156
- }
157
- async commit() {
158
- if (!this.inTransaction) {
159
- throw new Error("No transaction in progress");
160
- }
161
- this.execSync("COMMIT");
162
- this.inTransaction = false;
163
- }
164
- async rollback() {
165
- if (!this.inTransaction) {
166
- return;
167
- }
168
- this.execSync("ROLLBACK");
169
- this.inTransaction = false;
170
- }
171
- async prepare(sql) {
172
- return {
173
- query: async (params) => {
174
- return this.query(sql, params);
175
- },
176
- queryOne: async (params) => {
177
- return this.queryOne(sql, params);
178
- },
179
- run: async (params) => {
180
- return this.run(sql, params);
181
- },
182
- finalize: async () => {
183
- }
184
- };
185
- }
186
- async getSchemaVersion() {
187
- try {
188
- const row = await this.queryOne(
189
- "SELECT version FROM _schema_version ORDER BY version DESC LIMIT 1"
190
- );
191
- return row?.version ?? 0;
192
- } catch {
193
- return 0;
194
- }
195
- }
196
- async setSchemaVersion(version) {
197
- await this.run("INSERT INTO _schema_version (version, applied_at) VALUES (?, ?)", [
198
- version,
199
- Date.now()
200
- ]);
201
- }
202
- async applySchema(version, sql) {
203
- const currentVersion = await this.getSchemaVersion();
204
- if (currentVersion >= version) {
205
- return false;
206
- }
207
- await this.transaction(async () => {
208
- await this.exec(sql);
209
- await this.setSchemaVersion(version);
210
- });
211
- return true;
212
- }
213
- async getDatabaseSize() {
214
- try {
215
- const row = await this.queryOne(
216
- "SELECT page_count * page_size as size FROM pragma_page_count(), pragma_page_size()"
217
- );
218
- return row?.size ?? 0;
219
- } catch {
220
- return 0;
221
- }
222
- }
223
- async vacuum() {
224
- await this.exec("VACUUM");
225
- }
226
- async checkpoint() {
227
- return 0;
228
- }
229
- ensureOpen() {
230
- if (!this.db || !this.sqlite3) {
231
- throw new Error("Database not open. Call open() first.");
232
- }
233
- }
234
- };
235
- async function createWebSQLiteAdapter(config) {
236
- const adapter = new WebSQLiteAdapter();
237
- await adapter.open(config);
238
- await adapter.applySchema(SCHEMA_VERSION, SCHEMA_DDL);
239
- return adapter;
240
- }
241
-
242
- export {
243
- WebSQLiteAdapter,
244
- createWebSQLiteAdapter
245
- };
@@ -1,193 +0,0 @@
1
- // src/schema.ts
2
- var SCHEMA_VERSION = 1;
3
- var SCHEMA_DDL_CORE = `
4
- -- ============================================
5
- -- Schema Version Tracking
6
- -- ============================================
7
-
8
- CREATE TABLE IF NOT EXISTS _schema_version (
9
- version INTEGER PRIMARY KEY,
10
- applied_at INTEGER NOT NULL
11
- );
12
-
13
- -- ============================================
14
- -- Core Tables
15
- -- ============================================
16
-
17
- -- All nodes (Pages, Databases, Rows, Comments, etc.)
18
- CREATE TABLE IF NOT EXISTS nodes (
19
- id TEXT PRIMARY KEY,
20
- schema_id TEXT NOT NULL,
21
- created_at INTEGER NOT NULL,
22
- updated_at INTEGER NOT NULL,
23
- created_by TEXT NOT NULL,
24
- deleted_at INTEGER
25
- );
26
-
27
- -- Node properties (LWW per-property)
28
- CREATE TABLE IF NOT EXISTS node_properties (
29
- node_id TEXT NOT NULL,
30
- property_key TEXT NOT NULL,
31
- value BLOB,
32
- lamport_time INTEGER NOT NULL,
33
- updated_by TEXT NOT NULL,
34
- updated_at INTEGER NOT NULL,
35
-
36
- PRIMARY KEY (node_id, property_key),
37
- FOREIGN KEY (node_id) REFERENCES nodes(id) ON DELETE CASCADE
38
- );
39
-
40
- -- Change log (event sourcing)
41
- CREATE TABLE IF NOT EXISTS changes (
42
- hash TEXT PRIMARY KEY,
43
- node_id TEXT NOT NULL,
44
- payload BLOB NOT NULL,
45
- lamport_time INTEGER NOT NULL,
46
- lamport_peer TEXT NOT NULL,
47
- wall_time INTEGER NOT NULL,
48
- author TEXT NOT NULL,
49
- parent_hash TEXT,
50
- batch_id TEXT,
51
- signature BLOB NOT NULL,
52
-
53
- FOREIGN KEY (node_id) REFERENCES nodes(id) ON DELETE CASCADE
54
- );
55
-
56
- -- Y.Doc binary state (for nodes with collaborative content)
57
- CREATE TABLE IF NOT EXISTS yjs_state (
58
- node_id TEXT PRIMARY KEY,
59
- state BLOB NOT NULL,
60
- updated_at INTEGER NOT NULL,
61
-
62
- FOREIGN KEY (node_id) REFERENCES nodes(id) ON DELETE CASCADE
63
- );
64
-
65
- -- Y.Doc incremental updates (for sync)
66
- CREATE TABLE IF NOT EXISTS yjs_updates (
67
- id INTEGER PRIMARY KEY AUTOINCREMENT,
68
- node_id TEXT NOT NULL,
69
- update_data BLOB NOT NULL,
70
- timestamp INTEGER NOT NULL,
71
- origin TEXT,
72
-
73
- FOREIGN KEY (node_id) REFERENCES nodes(id) ON DELETE CASCADE
74
- );
75
-
76
- -- Yjs snapshots (for document time travel)
77
- CREATE TABLE IF NOT EXISTS yjs_snapshots (
78
- id INTEGER PRIMARY KEY AUTOINCREMENT,
79
- node_id TEXT NOT NULL,
80
- timestamp INTEGER NOT NULL,
81
- snapshot BLOB NOT NULL,
82
- doc_state BLOB NOT NULL,
83
- byte_size INTEGER NOT NULL,
84
-
85
- FOREIGN KEY (node_id) REFERENCES nodes(id) ON DELETE CASCADE
86
- );
87
-
88
- -- Blobs (content-addressed)
89
- CREATE TABLE IF NOT EXISTS blobs (
90
- cid TEXT PRIMARY KEY,
91
- data BLOB NOT NULL,
92
- mime_type TEXT,
93
- size INTEGER NOT NULL,
94
- created_at INTEGER NOT NULL,
95
- reference_count INTEGER DEFAULT 1
96
- );
97
-
98
- -- Documents (for @xnetjs/storage compatibility)
99
- CREATE TABLE IF NOT EXISTS documents (
100
- id TEXT PRIMARY KEY,
101
- content BLOB NOT NULL,
102
- metadata TEXT NOT NULL,
103
- version INTEGER NOT NULL DEFAULT 1
104
- );
105
-
106
- -- Signed updates (for @xnetjs/storage compatibility)
107
- CREATE TABLE IF NOT EXISTS updates (
108
- id INTEGER PRIMARY KEY AUTOINCREMENT,
109
- doc_id TEXT NOT NULL,
110
- update_hash TEXT NOT NULL,
111
- update_data TEXT NOT NULL,
112
- created_at INTEGER DEFAULT (strftime('%s', 'now') * 1000),
113
- UNIQUE(doc_id, update_hash)
114
- );
115
-
116
- -- Snapshots (for @xnetjs/storage compatibility)
117
- CREATE TABLE IF NOT EXISTS snapshots (
118
- doc_id TEXT PRIMARY KEY,
119
- snapshot_data TEXT NOT NULL,
120
- created_at INTEGER DEFAULT (strftime('%s', 'now') * 1000)
121
- );
122
-
123
- -- Sync metadata
124
- CREATE TABLE IF NOT EXISTS sync_state (
125
- key TEXT PRIMARY KEY,
126
- value TEXT NOT NULL
127
- );
128
-
129
- -- ============================================
130
- -- Indexes
131
- -- ============================================
132
-
133
- CREATE INDEX IF NOT EXISTS idx_nodes_schema ON nodes(schema_id);
134
- CREATE INDEX IF NOT EXISTS idx_nodes_updated ON nodes(updated_at);
135
- CREATE INDEX IF NOT EXISTS idx_nodes_created_by ON nodes(created_by);
136
- CREATE INDEX IF NOT EXISTS idx_nodes_deleted ON nodes(deleted_at);
137
-
138
- CREATE INDEX IF NOT EXISTS idx_properties_node ON node_properties(node_id);
139
- CREATE INDEX IF NOT EXISTS idx_properties_lamport ON node_properties(lamport_time);
140
-
141
- CREATE INDEX IF NOT EXISTS idx_changes_node ON changes(node_id);
142
- CREATE INDEX IF NOT EXISTS idx_changes_lamport ON changes(lamport_time);
143
- CREATE INDEX IF NOT EXISTS idx_changes_wall_time ON changes(wall_time);
144
- CREATE INDEX IF NOT EXISTS idx_changes_batch ON changes(batch_id);
145
-
146
- CREATE INDEX IF NOT EXISTS idx_yjs_state_updated ON yjs_state(updated_at);
147
- CREATE INDEX IF NOT EXISTS idx_yjs_updates_node ON yjs_updates(node_id);
148
- CREATE INDEX IF NOT EXISTS idx_yjs_snapshots_node ON yjs_snapshots(node_id);
149
- CREATE INDEX IF NOT EXISTS idx_yjs_snapshots_timestamp ON yjs_snapshots(node_id, timestamp);
150
-
151
- CREATE INDEX IF NOT EXISTS idx_updates_doc ON updates(doc_id);
152
- CREATE INDEX IF NOT EXISTS idx_updates_created ON updates(created_at);
153
- `;
154
- var SCHEMA_DDL_FTS = `
155
- -- ============================================
156
- -- Full-Text Search (FTS5)
157
- -- ============================================
158
-
159
- -- FTS index for searchable node content
160
- CREATE VIRTUAL TABLE IF NOT EXISTS nodes_fts USING fts5(
161
- node_id,
162
- title,
163
- content,
164
- tokenize='porter unicode61'
165
- );
166
-
167
- -- Triggers to keep FTS in sync will be managed by application layer
168
- -- since the searchable content is derived from node properties
169
- `;
170
- var SCHEMA_DDL = SCHEMA_DDL_CORE + SCHEMA_DDL_FTS;
171
- var SCHEMA_MIGRATIONS = {
172
- // Version 2 migrations would go here
173
- // 2: `ALTER TABLE nodes ADD COLUMN ...`
174
- };
175
- function getMigrationSQL(fromVersion, toVersion) {
176
- const statements = [];
177
- for (let v = fromVersion + 1; v <= toVersion; v++) {
178
- const migration = SCHEMA_MIGRATIONS[v];
179
- if (migration) {
180
- statements.push(migration);
181
- }
182
- }
183
- return statements.join("\n");
184
- }
185
-
186
- export {
187
- SCHEMA_VERSION,
188
- SCHEMA_DDL_CORE,
189
- SCHEMA_DDL_FTS,
190
- SCHEMA_DDL,
191
- SCHEMA_MIGRATIONS,
192
- getMigrationSQL
193
- };
@@ -1,140 +0,0 @@
1
- // src/browser-support.ts
2
- function withTimeout(promise, timeoutMs, errorMessage) {
3
- return Promise.race([
4
- promise,
5
- new Promise((_, reject) => setTimeout(() => reject(new Error(errorMessage)), timeoutMs))
6
- ]);
7
- }
8
- function isSafariPrivateBrowsing() {
9
- const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
10
- if (!isSafari) return false;
11
- try {
12
- localStorage.setItem("_test", "1");
13
- localStorage.removeItem("_test");
14
- return false;
15
- } catch {
16
- return true;
17
- }
18
- }
19
- async function checkBrowserSupport() {
20
- const result = {
21
- opfs: false,
22
- worker: true,
23
- supported: false
24
- };
25
- if (typeof Worker === "undefined") {
26
- result.worker = false;
27
- result.reason = "Web Workers not supported in this browser.";
28
- return result;
29
- }
30
- if (typeof navigator === "undefined" || !navigator.storage?.getDirectory) {
31
- result.reason = "Origin Private File System (OPFS) not supported. Please use a modern browser (Chrome 102+, Firefox 111+, Safari 16.4+).";
32
- return result;
33
- }
34
- try {
35
- const testOPFS = async () => {
36
- await navigator.storage.getDirectory();
37
- };
38
- await withTimeout(testOPFS(), 5e3, "OPFS access timeout");
39
- result.opfs = true;
40
- result.supported = true;
41
- } catch (err) {
42
- const errorMessage = err instanceof Error ? err.message : String(err);
43
- const normalized = errorMessage.toLowerCase();
44
- const safariStorageContextError = normalized.includes("object can not be found here") || normalized.includes("object cannot be found here") || normalized.includes("operation is insecure");
45
- if (isSafariPrivateBrowsing()) {
46
- result.warning = "Safari Private Browsing detected. Storage may be limited. For full functionality, switch to normal mode or use the xNet Desktop App.";
47
- result.supported = true;
48
- } else if (/^((?!chrome|android).)*safari/i.test(navigator.userAgent) && safariStorageContextError) {
49
- result.warning = "Safari storage APIs are restricted in this context. xNet will continue, but persistence may be limited between sessions.";
50
- result.supported = true;
51
- } else {
52
- result.warning = `Storage access limited (${errorMessage}). Data persistence may be limited between sessions. For full functionality, use the xNet Desktop App.`;
53
- result.supported = true;
54
- }
55
- }
56
- return result;
57
- }
58
- function showUnsupportedBrowserMessage(reason) {
59
- const container = document.getElementById("app") ?? document.body;
60
- container.innerHTML = `
61
- <div style="
62
- display: flex;
63
- flex-direction: column;
64
- align-items: center;
65
- justify-content: center;
66
- min-height: 100vh;
67
- padding: 2rem;
68
- text-align: center;
69
- font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
70
- background: #fafafa;
71
- color: #333;
72
- ">
73
- <div style="
74
- background: white;
75
- padding: 2rem 2.5rem;
76
- border-radius: 12px;
77
- box-shadow: 0 4px 12px rgba(0,0,0,0.08);
78
- max-width: 480px;
79
- width: 100%;
80
- ">
81
- <h1 style="
82
- font-size: 1.5rem;
83
- margin: 0 0 1rem 0;
84
- color: #111;
85
- font-weight: 600;
86
- ">
87
- Browser Not Supported
88
- </h1>
89
- <p style="
90
- color: #555;
91
- margin: 0 0 1.5rem 0;
92
- line-height: 1.6;
93
- font-size: 1rem;
94
- ">
95
- ${escapeHtml(reason)}
96
- </p>
97
- <div style="
98
- background: #f5f5f5;
99
- padding: 1rem;
100
- border-radius: 8px;
101
- text-align: left;
102
- font-size: 0.9rem;
103
- ">
104
- <p style="margin: 0 0 0.5rem 0; font-weight: 500;">Supported browsers:</p>
105
- <ul style="margin: 0; padding-left: 1.5rem; color: #666;">
106
- <li>Chrome 102+ (March 2022)</li>
107
- <li>Edge 102+ (March 2022)</li>
108
- <li>Firefox 111+ (March 2023)</li>
109
- <li>Safari 16.4+ (March 2023)</li>
110
- </ul>
111
- </div>
112
- <p style="
113
- color: #888;
114
- font-size: 0.875rem;
115
- margin: 1.5rem 0 0 0;
116
- ">
117
- For the best experience, please use the
118
- <a href="https://xnet.app/download" style="
119
- color: #0066cc;
120
- text-decoration: none;
121
- font-weight: 500;
122
- ">
123
- xNet Desktop App
124
- </a>
125
- or update your browser.
126
- </p>
127
- </div>
128
- </div>
129
- `;
130
- }
131
- function escapeHtml(text) {
132
- const div = document.createElement("div");
133
- div.textContent = text;
134
- return div.innerHTML;
135
- }
136
-
137
- export {
138
- checkBrowserSupport,
139
- showUnsupportedBrowserMessage
140
- };
@@ -1,35 +0,0 @@
1
- /**
2
- * @xnetjs/sqlite - Unified SQLite schema for xNet
3
- */
4
- /**
5
- * Current schema version.
6
- * Increment this when making schema changes.
7
- */
8
- declare const SCHEMA_VERSION = 1;
9
- /**
10
- * Core SQLite schema for xNet (without FTS5).
11
- * This schema works on all platforms including sql.js.
12
- */
13
- declare const SCHEMA_DDL_CORE = "\n-- ============================================\n-- Schema Version Tracking\n-- ============================================\n\nCREATE TABLE IF NOT EXISTS _schema_version (\n version INTEGER PRIMARY KEY,\n applied_at INTEGER NOT NULL\n);\n\n-- ============================================\n-- Core Tables\n-- ============================================\n\n-- All nodes (Pages, Databases, Rows, Comments, etc.)\nCREATE TABLE IF NOT EXISTS nodes (\n id TEXT PRIMARY KEY,\n schema_id TEXT NOT NULL,\n created_at INTEGER NOT NULL,\n updated_at INTEGER NOT NULL,\n created_by TEXT NOT NULL,\n deleted_at INTEGER\n);\n\n-- Node properties (LWW per-property)\nCREATE TABLE IF NOT EXISTS node_properties (\n node_id TEXT NOT NULL,\n property_key TEXT NOT NULL,\n value BLOB,\n lamport_time INTEGER NOT NULL,\n updated_by TEXT NOT NULL,\n updated_at INTEGER NOT NULL,\n\n PRIMARY KEY (node_id, property_key),\n FOREIGN KEY (node_id) REFERENCES nodes(id) ON DELETE CASCADE\n);\n\n-- Change log (event sourcing)\nCREATE TABLE IF NOT EXISTS changes (\n hash TEXT PRIMARY KEY,\n node_id TEXT NOT NULL,\n payload BLOB NOT NULL,\n lamport_time INTEGER NOT NULL,\n lamport_peer TEXT NOT NULL,\n wall_time INTEGER NOT NULL,\n author TEXT NOT NULL,\n parent_hash TEXT,\n batch_id TEXT,\n signature BLOB NOT NULL,\n\n FOREIGN KEY (node_id) REFERENCES nodes(id) ON DELETE CASCADE\n);\n\n-- Y.Doc binary state (for nodes with collaborative content)\nCREATE TABLE IF NOT EXISTS yjs_state (\n node_id TEXT PRIMARY KEY,\n state BLOB NOT NULL,\n updated_at INTEGER NOT NULL,\n\n FOREIGN KEY (node_id) REFERENCES nodes(id) ON DELETE CASCADE\n);\n\n-- Y.Doc incremental updates (for sync)\nCREATE TABLE IF NOT EXISTS yjs_updates (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n node_id TEXT NOT NULL,\n update_data BLOB NOT NULL,\n timestamp INTEGER NOT NULL,\n origin TEXT,\n\n FOREIGN KEY (node_id) REFERENCES nodes(id) ON DELETE CASCADE\n);\n\n-- Yjs snapshots (for document time travel)\nCREATE TABLE IF NOT EXISTS yjs_snapshots (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n node_id TEXT NOT NULL,\n timestamp INTEGER NOT NULL,\n snapshot BLOB NOT NULL,\n doc_state BLOB NOT NULL,\n byte_size INTEGER NOT NULL,\n\n FOREIGN KEY (node_id) REFERENCES nodes(id) ON DELETE CASCADE\n);\n\n-- Blobs (content-addressed)\nCREATE TABLE IF NOT EXISTS blobs (\n cid TEXT PRIMARY KEY,\n data BLOB NOT NULL,\n mime_type TEXT,\n size INTEGER NOT NULL,\n created_at INTEGER NOT NULL,\n reference_count INTEGER DEFAULT 1\n);\n\n-- Documents (for @xnetjs/storage compatibility)\nCREATE TABLE IF NOT EXISTS documents (\n id TEXT PRIMARY KEY,\n content BLOB NOT NULL,\n metadata TEXT NOT NULL,\n version INTEGER NOT NULL DEFAULT 1\n);\n\n-- Signed updates (for @xnetjs/storage compatibility)\nCREATE TABLE IF NOT EXISTS updates (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n doc_id TEXT NOT NULL,\n update_hash TEXT NOT NULL,\n update_data TEXT NOT NULL,\n created_at INTEGER DEFAULT (strftime('%s', 'now') * 1000),\n UNIQUE(doc_id, update_hash)\n);\n\n-- Snapshots (for @xnetjs/storage compatibility)\nCREATE TABLE IF NOT EXISTS snapshots (\n doc_id TEXT PRIMARY KEY,\n snapshot_data TEXT NOT NULL,\n created_at INTEGER DEFAULT (strftime('%s', 'now') * 1000)\n);\n\n-- Sync metadata\nCREATE TABLE IF NOT EXISTS sync_state (\n key TEXT PRIMARY KEY,\n value TEXT NOT NULL\n);\n\n-- ============================================\n-- Indexes\n-- ============================================\n\nCREATE INDEX IF NOT EXISTS idx_nodes_schema ON nodes(schema_id);\nCREATE INDEX IF NOT EXISTS idx_nodes_updated ON nodes(updated_at);\nCREATE INDEX IF NOT EXISTS idx_nodes_created_by ON nodes(created_by);\nCREATE INDEX IF NOT EXISTS idx_nodes_deleted ON nodes(deleted_at);\n\nCREATE INDEX IF NOT EXISTS idx_properties_node ON node_properties(node_id);\nCREATE INDEX IF NOT EXISTS idx_properties_lamport ON node_properties(lamport_time);\n\nCREATE INDEX IF NOT EXISTS idx_changes_node ON changes(node_id);\nCREATE INDEX IF NOT EXISTS idx_changes_lamport ON changes(lamport_time);\nCREATE INDEX IF NOT EXISTS idx_changes_wall_time ON changes(wall_time);\nCREATE INDEX IF NOT EXISTS idx_changes_batch ON changes(batch_id);\n\nCREATE INDEX IF NOT EXISTS idx_yjs_state_updated ON yjs_state(updated_at);\nCREATE INDEX IF NOT EXISTS idx_yjs_updates_node ON yjs_updates(node_id);\nCREATE INDEX IF NOT EXISTS idx_yjs_snapshots_node ON yjs_snapshots(node_id);\nCREATE INDEX IF NOT EXISTS idx_yjs_snapshots_timestamp ON yjs_snapshots(node_id, timestamp);\n\nCREATE INDEX IF NOT EXISTS idx_updates_doc ON updates(doc_id);\nCREATE INDEX IF NOT EXISTS idx_updates_created ON updates(created_at);\n";
14
- /**
15
- * FTS5 schema for full-text search.
16
- * This is applied separately because sql.js doesn't support FTS5.
17
- */
18
- declare const SCHEMA_DDL_FTS = "\n-- ============================================\n-- Full-Text Search (FTS5)\n-- ============================================\n\n-- FTS index for searchable node content\nCREATE VIRTUAL TABLE IF NOT EXISTS nodes_fts USING fts5(\n node_id,\n title,\n content,\n tokenize='porter unicode61'\n);\n\n-- Triggers to keep FTS in sync will be managed by application layer\n-- since the searchable content is derived from node properties\n";
19
- /**
20
- * Unified SQLite schema for xNet.
21
- * This schema is shared across all platforms (with FTS5).
22
- * Use SCHEMA_DDL_CORE for platforms without FTS5 support (sql.js).
23
- */
24
- declare const SCHEMA_DDL: string;
25
- /**
26
- * Schema for future versions (migrations).
27
- * Each key is the version number, value is the upgrade SQL.
28
- */
29
- declare const SCHEMA_MIGRATIONS: Record<number, string>;
30
- /**
31
- * Get the SQL to upgrade from one version to another.
32
- */
33
- declare function getMigrationSQL(fromVersion: number, toVersion: number): string;
34
-
35
- export { SCHEMA_VERSION as S, SCHEMA_DDL as a, SCHEMA_DDL_CORE as b, SCHEMA_DDL_FTS as c, SCHEMA_MIGRATIONS as d, getMigrationSQL as g };