@powersync/web 0.0.0-dev-20260311103504 → 0.0.0-dev-20260503073249

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 (121) hide show
  1. package/dist/2075a31bb151adbb9767.wasm +0 -0
  2. package/dist/3322bc84de986b63c2cd.wasm +0 -0
  3. package/dist/8e97452e297be23b5e50.wasm +0 -0
  4. package/dist/fbc178b70d530e8ce02b.wasm +0 -0
  5. package/dist/index.umd.js +5341 -1279
  6. package/dist/index.umd.js.map +1 -1
  7. package/dist/worker/SharedSyncImplementation.umd.js +1113 -3526
  8. package/dist/worker/SharedSyncImplementation.umd.js.map +1 -1
  9. package/dist/worker/WASQLiteDB.umd.js +1397 -1332
  10. package/dist/worker/WASQLiteDB.umd.js.map +1 -1
  11. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_dist_mc-wa-s-9af0a7.umd.js +31 -0
  12. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_dist_mc-wa-s-9af0a7.umd.js.map +1 -0
  13. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_dist_mc-wa-s-bbf5a9.umd.js +31 -0
  14. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_dist_mc-wa-s-bbf5a9.umd.js.map +1 -0
  15. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_dist_wa-sqli-c26e0f.umd.js +31 -0
  16. package/dist/worker/{node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_dist_wa-sqli-cc5fcc.umd.js.map → node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_dist_wa-sqli-c26e0f.umd.js.map} +1 -1
  17. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_dist_wa-sqlite_mjs.umd.js +31 -0
  18. package/dist/worker/{node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_dist_wa-sqlite_mjs.umd.js.map → node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_dist_wa-sqlite_mjs.umd.js.map} +1 -1
  19. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_src_examples-2fb422.umd.js +3562 -0
  20. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_src_examples-2fb422.umd.js.map +1 -0
  21. package/dist/worker/{node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_src_examples-0df390.umd.js → node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_src_examples-96fb23.umd.js} +16 -16
  22. package/dist/worker/{node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_src_examples-0df390.umd.js.map → node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_src_examples-96fb23.umd.js.map} +1 -1
  23. package/dist/worker/{node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_src_examples-151024.umd.js → node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_src_examples-c89911.umd.js} +12 -12
  24. package/dist/worker/{node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_src_examples-151024.umd.js.map → node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_src_examples-c89911.umd.js.map} +1 -1
  25. package/dist/worker/{node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_src_examples-c01ef0.umd.js → node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_src_examples-ec4eb1.umd.js} +14 -14
  26. package/dist/worker/{node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_src_examples-c01ef0.umd.js.map → node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_src_examples-ec4eb1.umd.js.map} +1 -1
  27. package/lib/package.json +4 -5
  28. package/lib/src/db/PowerSyncDatabase.d.ts +2 -3
  29. package/lib/src/db/PowerSyncDatabase.js +3 -12
  30. package/lib/src/db/adapters/AsyncWebAdapter.d.ts +50 -0
  31. package/lib/src/db/adapters/AsyncWebAdapter.js +163 -0
  32. package/lib/src/db/adapters/SSRDBAdapter.d.ts +1 -2
  33. package/lib/src/db/adapters/SSRDBAdapter.js +5 -6
  34. package/lib/src/db/adapters/wa-sqlite/ConcurrentConnection.d.ts +56 -0
  35. package/lib/src/db/adapters/wa-sqlite/ConcurrentConnection.js +121 -0
  36. package/lib/src/db/adapters/wa-sqlite/DatabaseClient.d.ts +54 -0
  37. package/lib/src/db/adapters/wa-sqlite/DatabaseClient.js +227 -0
  38. package/lib/src/db/adapters/wa-sqlite/DatabaseServer.d.ts +47 -0
  39. package/lib/src/db/adapters/wa-sqlite/DatabaseServer.js +145 -0
  40. package/lib/src/db/adapters/wa-sqlite/RawSqliteConnection.d.ts +46 -0
  41. package/lib/src/db/adapters/wa-sqlite/RawSqliteConnection.js +147 -0
  42. package/lib/src/db/adapters/wa-sqlite/WASQLiteOpenFactory.d.ts +28 -6
  43. package/lib/src/db/adapters/wa-sqlite/WASQLiteOpenFactory.js +104 -55
  44. package/lib/src/db/adapters/wa-sqlite/vfs.d.ts +50 -0
  45. package/lib/src/db/adapters/wa-sqlite/vfs.js +76 -0
  46. package/lib/src/db/adapters/web-sql-flags.d.ts +5 -0
  47. package/lib/src/db/sync/SSRWebStreamingSyncImplementation.d.ts +5 -2
  48. package/lib/src/db/sync/SSRWebStreamingSyncImplementation.js +6 -3
  49. package/lib/src/db/sync/SharedWebStreamingSyncImplementation.js +4 -19
  50. package/lib/src/index.d.ts +1 -4
  51. package/lib/src/index.js +1 -4
  52. package/lib/src/shared/tab_close_signal.d.ts +11 -0
  53. package/lib/src/shared/tab_close_signal.js +26 -0
  54. package/lib/src/worker/db/MultiDatabaseServer.d.ts +17 -0
  55. package/lib/src/worker/db/MultiDatabaseServer.js +89 -0
  56. package/lib/src/worker/db/WASQLiteDB.worker.js +9 -48
  57. package/lib/src/worker/db/open-worker-database.d.ts +3 -3
  58. package/lib/src/worker/db/open-worker-database.js +2 -2
  59. package/lib/src/worker/sync/SharedSyncImplementation.d.ts +5 -6
  60. package/lib/src/worker/sync/SharedSyncImplementation.js +88 -54
  61. package/lib/tsconfig.tsbuildinfo +1 -1
  62. package/package.json +5 -6
  63. package/src/db/PowerSyncDatabase.ts +4 -12
  64. package/src/db/adapters/AsyncWebAdapter.ts +207 -0
  65. package/src/db/adapters/SSRDBAdapter.ts +7 -7
  66. package/src/db/adapters/wa-sqlite/ConcurrentConnection.ts +137 -0
  67. package/src/db/adapters/wa-sqlite/DatabaseClient.ts +325 -0
  68. package/src/db/adapters/wa-sqlite/DatabaseServer.ts +203 -0
  69. package/src/db/adapters/wa-sqlite/RawSqliteConnection.ts +194 -0
  70. package/src/db/adapters/wa-sqlite/WASQLiteOpenFactory.ts +152 -63
  71. package/src/db/adapters/wa-sqlite/vfs.ts +96 -0
  72. package/src/db/adapters/web-sql-flags.ts +6 -0
  73. package/src/db/sync/SSRWebStreamingSyncImplementation.ts +7 -3
  74. package/src/db/sync/SharedWebStreamingSyncImplementation.ts +4 -20
  75. package/src/index.ts +1 -4
  76. package/src/shared/tab_close_signal.ts +28 -0
  77. package/src/worker/db/MultiDatabaseServer.ts +107 -0
  78. package/src/worker/db/WASQLiteDB.worker.ts +10 -57
  79. package/src/worker/db/open-worker-database.ts +4 -4
  80. package/src/worker/sync/SharedSyncImplementation.ts +114 -58
  81. package/dist/26d61ca9f5694d064635.wasm +0 -0
  82. package/dist/_journeyapps_wa-sqlite-_journeyapps_wa-sqlite_src_examples_AccessHandlePoolVFS_js-_journeyapp-89f0ba.index.umd.js +0 -1878
  83. package/dist/_journeyapps_wa-sqlite-_journeyapps_wa-sqlite_src_examples_AccessHandlePoolVFS_js-_journeyapp-89f0ba.index.umd.js.map +0 -1
  84. package/dist/_journeyapps_wa-sqlite_src_examples_AccessHandlePoolVFS_js-_journeyapps_wa-sqlite_src_example-97ebe9.index.umd.js +0 -555
  85. package/dist/_journeyapps_wa-sqlite_src_examples_AccessHandlePoolVFS_js-_journeyapps_wa-sqlite_src_example-97ebe9.index.umd.js.map +0 -1
  86. package/dist/b4c6283dc473b6b3fd24.wasm +0 -0
  87. package/dist/c78985091a0b22aaef03.wasm +0 -0
  88. package/dist/ca59e199e1138b553fad.wasm +0 -0
  89. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_dist_mc-wa-s-b9c070.umd.js +0 -31
  90. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_dist_mc-wa-s-b9c070.umd.js.map +0 -1
  91. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_dist_mc-wa-s-c99c07.umd.js +0 -31
  92. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_dist_mc-wa-s-c99c07.umd.js.map +0 -1
  93. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_dist_wa-sqli-cc5fcc.umd.js +0 -31
  94. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_dist_wa-sqlite_mjs.umd.js +0 -31
  95. package/lib/src/db/adapters/AbstractWebSQLOpenFactory.d.ts +0 -17
  96. package/lib/src/db/adapters/AbstractWebSQLOpenFactory.js +0 -33
  97. package/lib/src/db/adapters/AsyncDatabaseConnection.d.ts +0 -49
  98. package/lib/src/db/adapters/AsyncDatabaseConnection.js +0 -1
  99. package/lib/src/db/adapters/LockedAsyncDatabaseAdapter.d.ts +0 -109
  100. package/lib/src/db/adapters/LockedAsyncDatabaseAdapter.js +0 -401
  101. package/lib/src/db/adapters/WorkerWrappedAsyncDatabaseConnection.d.ts +0 -59
  102. package/lib/src/db/adapters/WorkerWrappedAsyncDatabaseConnection.js +0 -147
  103. package/lib/src/db/adapters/wa-sqlite/InternalWASQLiteDBAdapter.d.ts +0 -12
  104. package/lib/src/db/adapters/wa-sqlite/InternalWASQLiteDBAdapter.js +0 -19
  105. package/lib/src/db/adapters/wa-sqlite/WASQLiteConnection.d.ts +0 -155
  106. package/lib/src/db/adapters/wa-sqlite/WASQLiteConnection.js +0 -401
  107. package/lib/src/db/adapters/wa-sqlite/WASQLiteDBAdapter.d.ts +0 -32
  108. package/lib/src/db/adapters/wa-sqlite/WASQLiteDBAdapter.js +0 -49
  109. package/lib/src/worker/db/SharedWASQLiteConnection.d.ts +0 -42
  110. package/lib/src/worker/db/SharedWASQLiteConnection.js +0 -90
  111. package/lib/src/worker/db/WorkerWASQLiteConnection.d.ts +0 -9
  112. package/lib/src/worker/db/WorkerWASQLiteConnection.js +0 -12
  113. package/src/db/adapters/AbstractWebSQLOpenFactory.ts +0 -48
  114. package/src/db/adapters/AsyncDatabaseConnection.ts +0 -55
  115. package/src/db/adapters/LockedAsyncDatabaseAdapter.ts +0 -490
  116. package/src/db/adapters/WorkerWrappedAsyncDatabaseConnection.ts +0 -201
  117. package/src/db/adapters/wa-sqlite/InternalWASQLiteDBAdapter.ts +0 -23
  118. package/src/db/adapters/wa-sqlite/WASQLiteConnection.ts +0 -497
  119. package/src/db/adapters/wa-sqlite/WASQLiteDBAdapter.ts +0 -86
  120. package/src/worker/db/SharedWASQLiteConnection.ts +0 -131
  121. package/src/worker/db/WorkerWASQLiteConnection.ts +0 -14
@@ -1,155 +0,0 @@
1
- import * as SQLite from '@journeyapps/wa-sqlite';
2
- import { BaseObserver, BatchedUpdateNotification } from '@powersync/common';
3
- import { Mutex } from 'async-mutex';
4
- import { AsyncDatabaseConnection, OnTableChangeCallback, ProxiedQueryResult } from '../AsyncDatabaseConnection.js';
5
- import { ResolvedWASQLiteOpenFactoryOptions } from './WASQLiteOpenFactory.js';
6
- /**
7
- * List of currently tested virtual filesystems
8
- */
9
- export declare enum WASQLiteVFS {
10
- IDBBatchAtomicVFS = "IDBBatchAtomicVFS",
11
- OPFSCoopSyncVFS = "OPFSCoopSyncVFS",
12
- AccessHandlePoolVFS = "AccessHandlePoolVFS"
13
- }
14
- /**
15
- * @internal
16
- */
17
- export type WASQLiteBroadCastTableUpdateEvent = {
18
- changedTables: Set<string>;
19
- connectionId: number;
20
- };
21
- /**
22
- * @internal
23
- */
24
- export type WASQLiteConnectionListener = {
25
- tablesUpdated: (event: BatchedUpdateNotification) => void;
26
- /**
27
- * Triggered when an active hold is overwritten by a new hold.
28
- * This is most likely to happen when a shared connection has been closed
29
- * without releasing the hold.
30
- * This listener can be used to cleanup any resources associated with the previous hold.
31
- * @param holdId - The id of the hold that has been overwritten.
32
- */
33
- holdOverwritten: (holdId: string) => Promise<void>;
34
- };
35
- /**
36
- * @internal
37
- */
38
- export type SQLiteModule = Parameters<typeof SQLite.Factory>[0];
39
- /**
40
- * @internal
41
- */
42
- export type WASQLiteModuleFactoryOptions = {
43
- dbFileName: string;
44
- encryptionKey?: string;
45
- };
46
- /**
47
- * @internal
48
- */
49
- export type WASQLiteModuleFactory = (options: WASQLiteModuleFactoryOptions) => Promise<{
50
- module: SQLiteModule;
51
- vfs: SQLiteVFS;
52
- }>;
53
- /**
54
- * @internal
55
- */
56
- export declare const AsyncWASQLiteModuleFactory: () => Promise<any>;
57
- /**
58
- * @internal
59
- */
60
- export declare const MultiCipherAsyncWASQLiteModuleFactory: () => Promise<any>;
61
- /**
62
- * @internal
63
- */
64
- export declare const SyncWASQLiteModuleFactory: () => Promise<any>;
65
- /**
66
- * @internal
67
- */
68
- export declare const MultiCipherSyncWASQLiteModuleFactory: () => Promise<any>;
69
- /**
70
- * @internal
71
- */
72
- export declare const DEFAULT_MODULE_FACTORIES: {
73
- IDBBatchAtomicVFS: (options: WASQLiteModuleFactoryOptions) => Promise<{
74
- module: any;
75
- vfs: any;
76
- }>;
77
- AccessHandlePoolVFS: (options: WASQLiteModuleFactoryOptions) => Promise<{
78
- module: any;
79
- vfs: any;
80
- }>;
81
- OPFSCoopSyncVFS: (options: WASQLiteModuleFactoryOptions) => Promise<{
82
- module: any;
83
- vfs: any;
84
- }>;
85
- };
86
- /**
87
- * @internal
88
- * WA-SQLite connection which directly interfaces with WA-SQLite.
89
- * This is usually instantiated inside a worker.
90
- */
91
- export declare class WASqliteConnection extends BaseObserver<WASQLiteConnectionListener> implements AsyncDatabaseConnection<ResolvedWASQLiteOpenFactoryOptions> {
92
- protected options: ResolvedWASQLiteOpenFactoryOptions;
93
- private _sqliteAPI;
94
- private _dbP;
95
- private _moduleFactory;
96
- protected updatedTables: Set<string>;
97
- protected updateTimer: ReturnType<typeof setTimeout> | null;
98
- protected statementMutex: Mutex;
99
- protected broadcastChannel: BroadcastChannel | null;
100
- /**
101
- * Unique id for this specific connection. This is used to prevent broadcast table change
102
- * notification loops.
103
- */
104
- protected connectionId: number;
105
- protected _holdCounter: number;
106
- protected _holdId: string | null;
107
- constructor(options: ResolvedWASQLiteOpenFactoryOptions);
108
- /**
109
- * Gets the id for the current hold.
110
- * This can be used to check for invalid states.
111
- */
112
- get currentHoldId(): string | null;
113
- protected get sqliteAPI(): SQLiteAPI;
114
- protected get dbP(): number;
115
- /**
116
- * Checks if the database connection is in autocommit mode.
117
- * @returns true if in autocommit mode, false if in a transaction
118
- */
119
- isAutoCommit(): Promise<boolean>;
120
- markHold(): Promise<string>;
121
- releaseHold(holdId: string): Promise<void>;
122
- protected openDB(): Promise<number>;
123
- protected executeEncryptionPragma(): Promise<void>;
124
- protected openSQLiteAPI(): Promise<SQLiteAPI>;
125
- protected registerBroadcastListeners(): void;
126
- protected queueTableUpdate(tableNames: Set<string>, shouldBroadcast?: boolean): void;
127
- init(): Promise<void>;
128
- getConfig(): Promise<ResolvedWASQLiteOpenFactoryOptions>;
129
- fireUpdates(shouldBroadcast?: boolean): void;
130
- /**
131
- * This executes SQL statements in a batch.
132
- */
133
- executeBatch(sql: string, bindings?: any[][]): Promise<ProxiedQueryResult>;
134
- /**
135
- * This executes single SQL statements inside a requested lock.
136
- */
137
- execute(sql: string | TemplateStringsArray, bindings?: any[]): Promise<ProxiedQueryResult>;
138
- executeRaw(sql: string | TemplateStringsArray, bindings?: any[]): Promise<any[][]>;
139
- close(): Promise<void>;
140
- registerOnTableChange(callback: OnTableChangeCallback): Promise<() => void>;
141
- /**
142
- * This requests a lock for executing statements.
143
- * Should only be used internally.
144
- */
145
- protected acquireExecuteLock: <T>(callback: () => Promise<T>) => Promise<T>;
146
- /**
147
- * This executes a single statement using SQLite3.
148
- */
149
- protected executeSingleStatement(sql: string | TemplateStringsArray, bindings?: any[]): Promise<ProxiedQueryResult>;
150
- /**
151
- * This executes a single statement using SQLite3 and returns the results as an array of arrays.
152
- */
153
- protected executeSingleStatementRaw(sql: string | TemplateStringsArray, bindings?: any[]): Promise<any[][]>;
154
- private _execute;
155
- }
@@ -1,401 +0,0 @@
1
- import * as SQLite from '@journeyapps/wa-sqlite';
2
- import { BaseObserver } from '@powersync/common';
3
- import { Mutex } from 'async-mutex';
4
- /**
5
- * List of currently tested virtual filesystems
6
- */
7
- export var WASQLiteVFS;
8
- (function (WASQLiteVFS) {
9
- WASQLiteVFS["IDBBatchAtomicVFS"] = "IDBBatchAtomicVFS";
10
- WASQLiteVFS["OPFSCoopSyncVFS"] = "OPFSCoopSyncVFS";
11
- WASQLiteVFS["AccessHandlePoolVFS"] = "AccessHandlePoolVFS";
12
- })(WASQLiteVFS || (WASQLiteVFS = {}));
13
- /**
14
- * @internal
15
- */
16
- export const AsyncWASQLiteModuleFactory = async () => {
17
- const { default: factory } = await import('@journeyapps/wa-sqlite/dist/wa-sqlite-async.mjs');
18
- return factory();
19
- };
20
- /**
21
- * @internal
22
- */
23
- export const MultiCipherAsyncWASQLiteModuleFactory = async () => {
24
- const { default: factory } = await import('@journeyapps/wa-sqlite/dist/mc-wa-sqlite-async.mjs');
25
- return factory();
26
- };
27
- /**
28
- * @internal
29
- */
30
- export const SyncWASQLiteModuleFactory = async () => {
31
- const { default: factory } = await import('@journeyapps/wa-sqlite/dist/wa-sqlite.mjs');
32
- return factory();
33
- };
34
- /**
35
- * @internal
36
- */
37
- export const MultiCipherSyncWASQLiteModuleFactory = async () => {
38
- const { default: factory } = await import('@journeyapps/wa-sqlite/dist/mc-wa-sqlite.mjs');
39
- return factory();
40
- };
41
- /**
42
- * @internal
43
- */
44
- export const DEFAULT_MODULE_FACTORIES = {
45
- [WASQLiteVFS.IDBBatchAtomicVFS]: async (options) => {
46
- let module;
47
- if (options.encryptionKey) {
48
- module = await MultiCipherAsyncWASQLiteModuleFactory();
49
- }
50
- else {
51
- module = await AsyncWASQLiteModuleFactory();
52
- }
53
- const { IDBBatchAtomicVFS } = await import('@journeyapps/wa-sqlite/src/examples/IDBBatchAtomicVFS.js');
54
- return {
55
- module,
56
- // @ts-expect-error The types for this static method are missing upstream
57
- vfs: await IDBBatchAtomicVFS.create(options.dbFileName, module, { lockPolicy: 'exclusive' })
58
- };
59
- },
60
- [WASQLiteVFS.AccessHandlePoolVFS]: async (options) => {
61
- let module;
62
- if (options.encryptionKey) {
63
- module = await MultiCipherSyncWASQLiteModuleFactory();
64
- }
65
- else {
66
- module = await SyncWASQLiteModuleFactory();
67
- }
68
- // @ts-expect-error The types for this static method are missing upstream
69
- const { AccessHandlePoolVFS } = await import('@journeyapps/wa-sqlite/src/examples/AccessHandlePoolVFS.js');
70
- return {
71
- module,
72
- vfs: await AccessHandlePoolVFS.create(options.dbFileName, module)
73
- };
74
- },
75
- [WASQLiteVFS.OPFSCoopSyncVFS]: async (options) => {
76
- let module;
77
- if (options.encryptionKey) {
78
- module = await MultiCipherSyncWASQLiteModuleFactory();
79
- }
80
- else {
81
- module = await SyncWASQLiteModuleFactory();
82
- }
83
- // @ts-expect-error The types for this static method are missing upstream
84
- const { OPFSCoopSyncVFS } = await import('@journeyapps/wa-sqlite/src/examples/OPFSCoopSyncVFS.js');
85
- const vfs = await OPFSCoopSyncVFS.create(options.dbFileName, module);
86
- return {
87
- module,
88
- vfs
89
- };
90
- }
91
- };
92
- /**
93
- * @internal
94
- * WA-SQLite connection which directly interfaces with WA-SQLite.
95
- * This is usually instantiated inside a worker.
96
- */
97
- export class WASqliteConnection extends BaseObserver {
98
- options;
99
- _sqliteAPI = null;
100
- _dbP = null;
101
- _moduleFactory;
102
- updatedTables;
103
- updateTimer;
104
- statementMutex;
105
- broadcastChannel;
106
- /**
107
- * Unique id for this specific connection. This is used to prevent broadcast table change
108
- * notification loops.
109
- */
110
- connectionId;
111
- _holdCounter;
112
- _holdId;
113
- constructor(options) {
114
- super();
115
- this.options = options;
116
- this.updatedTables = new Set();
117
- this.updateTimer = null;
118
- this.broadcastChannel = null;
119
- this.connectionId = new Date().valueOf() + Math.random();
120
- this.statementMutex = new Mutex();
121
- this._moduleFactory = DEFAULT_MODULE_FACTORIES[this.options.vfs];
122
- this._holdCounter = 0;
123
- this._holdId = null;
124
- }
125
- /**
126
- * Gets the id for the current hold.
127
- * This can be used to check for invalid states.
128
- */
129
- get currentHoldId() {
130
- return this._holdId;
131
- }
132
- get sqliteAPI() {
133
- if (!this._sqliteAPI) {
134
- throw new Error(`Initialization has not completed`);
135
- }
136
- return this._sqliteAPI;
137
- }
138
- get dbP() {
139
- if (!this._dbP) {
140
- throw new Error(`Initialization has not completed`);
141
- }
142
- return this._dbP;
143
- }
144
- /**
145
- * Checks if the database connection is in autocommit mode.
146
- * @returns true if in autocommit mode, false if in a transaction
147
- */
148
- async isAutoCommit() {
149
- return this.sqliteAPI.get_autocommit(this.dbP) != 0;
150
- }
151
- async markHold() {
152
- const previousHoldId = this._holdId;
153
- this._holdId = `${++this._holdCounter}`;
154
- if (previousHoldId) {
155
- await this.iterateAsyncListeners(async (cb) => cb.holdOverwritten?.(previousHoldId));
156
- }
157
- return this._holdId;
158
- }
159
- async releaseHold(holdId) {
160
- if (holdId != this._holdId) {
161
- throw new Error(`Invalid hold state, expected ${this._holdId} but got ${holdId}`);
162
- }
163
- this._holdId = null;
164
- }
165
- async openDB() {
166
- this._dbP = await this.sqliteAPI.open_v2(this.options.dbFilename);
167
- return this._dbP;
168
- }
169
- async executeEncryptionPragma() {
170
- if (this.options.encryptionKey) {
171
- await this.executeSingleStatement(`PRAGMA key = "${this.options.encryptionKey}"`);
172
- }
173
- return;
174
- }
175
- async openSQLiteAPI() {
176
- const { module, vfs } = await this._moduleFactory({
177
- dbFileName: this.options.dbFilename,
178
- encryptionKey: this.options.encryptionKey
179
- });
180
- const sqlite3 = SQLite.Factory(module);
181
- sqlite3.vfs_register(vfs, true);
182
- /**
183
- * Register the PowerSync core SQLite extension
184
- */
185
- module.ccall('powersync_init_static', 'int', []);
186
- /**
187
- * Create the multiple cipher vfs if an encryption key is provided
188
- */
189
- if (this.options.encryptionKey) {
190
- const createResult = module.ccall('sqlite3mc_vfs_create', 'int', ['string', 'int'], [this.options.dbFilename, 1]);
191
- if (createResult !== 0) {
192
- throw new Error('Failed to create multiple cipher vfs, Database encryption will not work');
193
- }
194
- }
195
- return sqlite3;
196
- }
197
- registerBroadcastListeners() {
198
- this.broadcastChannel = new BroadcastChannel(`${this.options.dbFilename}-table-updates`);
199
- this.broadcastChannel.addEventListener('message', (event) => {
200
- const data = event.data;
201
- if (this.connectionId == data.connectionId) {
202
- // Ignore messages from the same connection
203
- return;
204
- }
205
- // Ensuring that we don't rebroadcast the same message
206
- this.queueTableUpdate(data.changedTables, false);
207
- });
208
- }
209
- queueTableUpdate(tableNames, shouldBroadcast = true) {
210
- tableNames.forEach((tableName) => this.updatedTables.add(tableName));
211
- if (this.updateTimer == null) {
212
- this.updateTimer = setTimeout(() => this.fireUpdates(shouldBroadcast), 0);
213
- }
214
- }
215
- async init() {
216
- this._sqliteAPI = await this.openSQLiteAPI();
217
- await this.openDB();
218
- this.registerBroadcastListeners();
219
- await this.executeSingleStatement(`PRAGMA temp_store = ${this.options.temporaryStorage};`);
220
- await this.executeEncryptionPragma();
221
- await this.executeSingleStatement(`PRAGMA cache_size = -${this.options.cacheSizeKb};`);
222
- this.sqliteAPI.update_hook(this.dbP, (updateType, dbName, tableName) => {
223
- if (!tableName) {
224
- return;
225
- }
226
- const changedTables = new Set([tableName]);
227
- this.queueTableUpdate(changedTables);
228
- });
229
- }
230
- async getConfig() {
231
- return this.options;
232
- }
233
- fireUpdates(shouldBroadcast = true) {
234
- this.updateTimer = null;
235
- const event = { tables: [...this.updatedTables], groupedUpdates: {}, rawUpdates: [] };
236
- // Share to other connections
237
- if (shouldBroadcast) {
238
- this.broadcastChannel.postMessage({
239
- changedTables: this.updatedTables,
240
- connectionId: this.connectionId
241
- });
242
- }
243
- this.updatedTables.clear();
244
- this.iterateListeners((cb) => cb.tablesUpdated?.(event));
245
- }
246
- /**
247
- * This executes SQL statements in a batch.
248
- */
249
- async executeBatch(sql, bindings) {
250
- return this.acquireExecuteLock(async () => {
251
- let affectedRows = 0;
252
- try {
253
- await this.executeSingleStatement('BEGIN TRANSACTION');
254
- const wrappedBindings = bindings ? bindings : [];
255
- for await (const stmt of this.sqliteAPI.statements(this.dbP, sql)) {
256
- if (stmt === null) {
257
- return {
258
- rowsAffected: 0,
259
- rows: { _array: [], length: 0 }
260
- };
261
- }
262
- //Prepare statement once
263
- for (const binding of wrappedBindings) {
264
- // TODO not sure why this is needed currently, but booleans break
265
- for (let i = 0; i < binding.length; i++) {
266
- const b = binding[i];
267
- if (typeof b == 'boolean') {
268
- binding[i] = b ? 1 : 0;
269
- }
270
- }
271
- if (bindings) {
272
- this.sqliteAPI.bind_collection(stmt, binding);
273
- }
274
- const result = await this.sqliteAPI.step(stmt);
275
- if (result === SQLite.SQLITE_DONE) {
276
- //The value returned by sqlite3_changes() immediately after an INSERT, UPDATE or DELETE statement run on a view is always zero.
277
- affectedRows += this.sqliteAPI.changes(this.dbP);
278
- }
279
- this.sqliteAPI.reset(stmt);
280
- }
281
- }
282
- await this.executeSingleStatement('COMMIT');
283
- }
284
- catch (err) {
285
- await this.executeSingleStatement('ROLLBACK');
286
- return {
287
- rowsAffected: 0,
288
- rows: { _array: [], length: 0 }
289
- };
290
- }
291
- const result = {
292
- rowsAffected: affectedRows,
293
- rows: { _array: [], length: 0 }
294
- };
295
- return result;
296
- });
297
- }
298
- /**
299
- * This executes single SQL statements inside a requested lock.
300
- */
301
- async execute(sql, bindings) {
302
- // Running multiple statements on the same connection concurrently should not be allowed
303
- return this.acquireExecuteLock(async () => {
304
- return this.executeSingleStatement(sql, bindings);
305
- });
306
- }
307
- async executeRaw(sql, bindings) {
308
- return this.acquireExecuteLock(async () => {
309
- return this.executeSingleStatementRaw(sql, bindings);
310
- });
311
- }
312
- async close() {
313
- this.broadcastChannel?.close();
314
- await this.acquireExecuteLock(async () => {
315
- /**
316
- * Running the close operation inside the same execute mutex prevents errors like:
317
- * ```
318
- * unable to close due to unfinalized statements or unfinished backups
319
- * ```
320
- */
321
- await this.sqliteAPI.close(this.dbP);
322
- });
323
- }
324
- async registerOnTableChange(callback) {
325
- return this.registerListener({
326
- tablesUpdated: (event) => callback(event)
327
- });
328
- }
329
- /**
330
- * This requests a lock for executing statements.
331
- * Should only be used internally.
332
- */
333
- acquireExecuteLock = (callback) => {
334
- return this.statementMutex.runExclusive(callback);
335
- };
336
- /**
337
- * This executes a single statement using SQLite3.
338
- */
339
- async executeSingleStatement(sql, bindings) {
340
- const results = await this._execute(sql, bindings);
341
- const rows = [];
342
- for (const resultSet of results) {
343
- for (const row of resultSet.rows) {
344
- const outRow = {};
345
- resultSet.columns.forEach((key, index) => {
346
- outRow[key] = row[index];
347
- });
348
- rows.push(outRow);
349
- }
350
- }
351
- const result = {
352
- insertId: this.sqliteAPI.last_insert_id(this.dbP),
353
- rowsAffected: this.sqliteAPI.changes(this.dbP),
354
- rows: {
355
- _array: rows,
356
- length: rows.length
357
- }
358
- };
359
- return result;
360
- }
361
- /**
362
- * This executes a single statement using SQLite3 and returns the results as an array of arrays.
363
- */
364
- async executeSingleStatementRaw(sql, bindings) {
365
- const results = await this._execute(sql, bindings);
366
- return results.flatMap((resultset) => resultset.rows.map((row) => resultset.columns.map((_, index) => row[index])));
367
- }
368
- async _execute(sql, bindings) {
369
- const results = [];
370
- for await (const stmt of this.sqliteAPI.statements(this.dbP, sql)) {
371
- let columns;
372
- const wrappedBindings = bindings ? [bindings] : [[]];
373
- for (const binding of wrappedBindings) {
374
- // TODO not sure why this is needed currently, but booleans break
375
- binding.forEach((b, index, arr) => {
376
- if (typeof b == 'boolean') {
377
- arr[index] = b ? 1 : 0;
378
- }
379
- });
380
- this.sqliteAPI.reset(stmt);
381
- if (bindings) {
382
- this.sqliteAPI.bind_collection(stmt, binding);
383
- }
384
- const rows = [];
385
- while ((await this.sqliteAPI.step(stmt)) === SQLite.SQLITE_ROW) {
386
- const row = this.sqliteAPI.row(stmt);
387
- rows.push(row);
388
- }
389
- columns = columns ?? this.sqliteAPI.column_names(stmt);
390
- if (columns.length) {
391
- results.push({ columns, rows });
392
- }
393
- }
394
- // When binding parameters, only a single statement is executed.
395
- if (bindings) {
396
- break;
397
- }
398
- }
399
- return results;
400
- }
401
- }
@@ -1,32 +0,0 @@
1
- import { type PowerSyncOpenFactoryOptions } from '@powersync/common';
2
- import { ResolvedWebSQLOpenOptions, TemporaryStorageOption, WebSQLFlags } from '../web-sql-flags.js';
3
- import { InternalWASQLiteDBAdapter } from './InternalWASQLiteDBAdapter.js';
4
- import { WASQLiteVFS } from './WASQLiteConnection.js';
5
- /**
6
- * These flags are the same as {@link WebSQLFlags}.
7
- * This export is maintained only for API consistency
8
- */
9
- export type WASQLiteFlags = WebSQLFlags;
10
- export interface WASQLiteDBAdapterOptions extends Omit<PowerSyncOpenFactoryOptions, 'schema'> {
11
- flags?: WASQLiteFlags;
12
- /**
13
- * Use an existing port to an initialized worker.
14
- * A worker will be initialized if none is provided
15
- */
16
- workerPort?: MessagePort;
17
- worker?: string | URL | ((options: ResolvedWebSQLOpenOptions) => Worker | SharedWorker);
18
- vfs?: WASQLiteVFS;
19
- temporaryStorage?: TemporaryStorageOption;
20
- cacheSizeKb?: number;
21
- /**
22
- * Encryption key for the database.
23
- * If set, the database will be encrypted using multiple-ciphers.
24
- */
25
- encryptionKey?: string;
26
- }
27
- /**
28
- * Adapter for WA-SQLite SQLite connections.
29
- */
30
- export declare class WASQLiteDBAdapter extends InternalWASQLiteDBAdapter {
31
- constructor(options: WASQLiteDBAdapterOptions);
32
- }
@@ -1,49 +0,0 @@
1
- import * as Comlink from 'comlink';
2
- import { resolveWebPowerSyncFlags } from '../../PowerSyncDatabase.js';
3
- import { DEFAULT_CACHE_SIZE_KB, TemporaryStorageOption } from '../web-sql-flags.js';
4
- import { WorkerWrappedAsyncDatabaseConnection } from '../WorkerWrappedAsyncDatabaseConnection.js';
5
- import { InternalWASQLiteDBAdapter } from './InternalWASQLiteDBAdapter.js';
6
- import { WASQLiteOpenFactory } from './WASQLiteOpenFactory.js';
7
- /**
8
- * Adapter for WA-SQLite SQLite connections.
9
- */
10
- export class WASQLiteDBAdapter extends InternalWASQLiteDBAdapter {
11
- constructor(options) {
12
- super({
13
- name: options.dbFilename,
14
- openConnection: async () => {
15
- const { workerPort, temporaryStorage, cacheSizeKb } = options;
16
- if (workerPort) {
17
- const remote = Comlink.wrap(workerPort);
18
- return new WorkerWrappedAsyncDatabaseConnection({
19
- remote,
20
- remoteCanCloseUnexpectedly: false,
21
- identifier: options.dbFilename,
22
- baseConnection: await remote({
23
- ...options,
24
- temporaryStorage: temporaryStorage ?? TemporaryStorageOption.MEMORY,
25
- cacheSizeKb: cacheSizeKb ?? DEFAULT_CACHE_SIZE_KB,
26
- flags: resolveWebPowerSyncFlags(options.flags),
27
- encryptionKey: options.encryptionKey
28
- })
29
- });
30
- }
31
- const openFactory = new WASQLiteOpenFactory({
32
- dbFilename: options.dbFilename,
33
- dbLocation: options.dbLocation,
34
- debugMode: options.debugMode,
35
- flags: options.flags,
36
- temporaryStorage,
37
- cacheSizeKb,
38
- logger: options.logger,
39
- vfs: options.vfs,
40
- encryptionKey: options.encryptionKey,
41
- worker: options.worker
42
- });
43
- return openFactory.openConnection();
44
- },
45
- debugMode: options.debugMode,
46
- logger: options.logger
47
- });
48
- }
49
- }
@@ -1,42 +0,0 @@
1
- import { ILogger } from '@powersync/common';
2
- import { AsyncDatabaseConnection, OnTableChangeCallback, ProxiedQueryResult } from '../../db/adapters/AsyncDatabaseConnection.js';
3
- import { ResolvedWebSQLOpenOptions } from '../../db/adapters/web-sql-flags.js';
4
- /**
5
- * Keeps track of open DB connections and the clients which
6
- * are using it.
7
- */
8
- export type SharedDBWorkerConnection = {
9
- clientIds: Set<number>;
10
- db: AsyncDatabaseConnection;
11
- };
12
- export type SharedWASQLiteConnectionOptions = {
13
- dbMap: Map<string, SharedDBWorkerConnection>;
14
- dbFilename: string;
15
- clientId: number;
16
- logger: ILogger;
17
- };
18
- export declare class SharedWASQLiteConnection implements AsyncDatabaseConnection {
19
- protected options: SharedWASQLiteConnectionOptions;
20
- protected isClosing: boolean;
21
- protected activeHoldId: string | null;
22
- constructor(options: SharedWASQLiteConnectionOptions);
23
- protected get logger(): ILogger;
24
- protected get dbEntry(): SharedDBWorkerConnection;
25
- protected get connection(): AsyncDatabaseConnection<ResolvedWebSQLOpenOptions>;
26
- protected get clientIds(): Set<number>;
27
- init(): Promise<void>;
28
- markHold(): Promise<string>;
29
- releaseHold(id: string): Promise<void>;
30
- isAutoCommit(): Promise<boolean>;
31
- /**
32
- * Handles closing of a shared connection.
33
- * The connection is only closed if there are no active clients using it.
34
- */
35
- close(): Promise<void>;
36
- protected withClosing<T>(action: () => Promise<T>): Promise<T>;
37
- execute(sql: string, params?: any[]): Promise<ProxiedQueryResult>;
38
- executeRaw(sql: string, params?: any[]): Promise<any[][]>;
39
- executeBatch(sql: string, params?: any[] | undefined): Promise<ProxiedQueryResult>;
40
- registerOnTableChange(callback: OnTableChangeCallback): Promise<() => void>;
41
- getConfig(): Promise<ResolvedWebSQLOpenOptions>;
42
- }