@framers/sql-storage-adapter 0.7.2 → 0.7.3

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 (184) hide show
  1. package/README.md +20 -0
  2. package/dist/adapters/electron/preload.cjs +289 -0
  3. package/dist/adapters/electron/renderer.d.ts +9 -0
  4. package/dist/adapters/electron/renderer.d.ts.map +1 -0
  5. package/dist/adapters/electron/renderer.js +8 -0
  6. package/dist/adapters/electron/renderer.js.map +1 -0
  7. package/dist/cjs/adapters/__tests__/indexedDbAdapter.spec.d.ts +2 -0
  8. package/dist/cjs/adapters/__tests__/indexedDbAdapter.spec.js +133 -0
  9. package/dist/cjs/adapters/baseStorageAdapter.d.ts +368 -0
  10. package/dist/cjs/adapters/baseStorageAdapter.js +744 -0
  11. package/dist/cjs/adapters/betterSqliteAdapter.d.ts +124 -0
  12. package/dist/cjs/adapters/betterSqliteAdapter.js +334 -0
  13. package/dist/cjs/adapters/capacitorSqliteAdapter.d.ts +83 -0
  14. package/dist/cjs/adapters/capacitorSqliteAdapter.js +250 -0
  15. package/dist/cjs/adapters/electron/electronMainAdapter.d.ts +251 -0
  16. package/dist/cjs/adapters/electron/electronMainAdapter.js +392 -0
  17. package/dist/cjs/adapters/electron/electronRendererAdapter.d.ts +177 -0
  18. package/dist/cjs/adapters/electron/electronRendererAdapter.js +283 -0
  19. package/dist/cjs/adapters/electron/index.d.ts +74 -0
  20. package/dist/cjs/adapters/electron/index.js +86 -0
  21. package/dist/cjs/adapters/electron/ipc/channels.d.ts +196 -0
  22. package/dist/cjs/adapters/electron/ipc/channels.js +127 -0
  23. package/dist/cjs/adapters/electron/ipc/index.d.ts +11 -0
  24. package/dist/cjs/adapters/electron/ipc/index.js +38 -0
  25. package/dist/cjs/adapters/electron/ipc/protocol.d.ts +78 -0
  26. package/dist/cjs/adapters/electron/ipc/protocol.js +341 -0
  27. package/dist/cjs/adapters/electron/ipc/types.d.ts +248 -0
  28. package/dist/cjs/adapters/electron/ipc/types.js +15 -0
  29. package/dist/cjs/adapters/electron/migration/autoMigrator.d.ts +184 -0
  30. package/dist/cjs/adapters/electron/migration/autoMigrator.js +441 -0
  31. package/dist/cjs/adapters/electron/migration/index.d.ts +9 -0
  32. package/dist/cjs/adapters/electron/migration/index.js +29 -0
  33. package/dist/cjs/adapters/electron/preload.d.ts +126 -0
  34. package/dist/cjs/adapters/electron/preload.js +233 -0
  35. package/dist/cjs/adapters/electron/recovery/corruptionDetector.d.ts +214 -0
  36. package/dist/cjs/adapters/electron/recovery/corruptionDetector.js +359 -0
  37. package/dist/cjs/adapters/electron/recovery/index.d.ts +11 -0
  38. package/dist/cjs/adapters/electron/recovery/index.js +34 -0
  39. package/dist/cjs/adapters/electron/recovery/walCheckpoint.d.ts +186 -0
  40. package/dist/cjs/adapters/electron/recovery/walCheckpoint.js +263 -0
  41. package/dist/cjs/adapters/electron/renderer.d.ts +9 -0
  42. package/dist/cjs/adapters/electron/renderer.js +33 -0
  43. package/dist/cjs/adapters/electron/window/index.d.ts +9 -0
  44. package/dist/cjs/adapters/electron/window/index.js +29 -0
  45. package/dist/cjs/adapters/electron/window/windowManager.d.ts +190 -0
  46. package/dist/cjs/adapters/electron/window/windowManager.js +321 -0
  47. package/dist/cjs/adapters/indexedDbAdapter.d.ts +490 -0
  48. package/dist/cjs/adapters/indexedDbAdapter.js +993 -0
  49. package/dist/cjs/adapters/postgresAdapter.d.ts +424 -0
  50. package/dist/cjs/adapters/postgresAdapter.js +889 -0
  51. package/dist/cjs/adapters/sqlJsAdapter.d.ts +64 -0
  52. package/dist/cjs/adapters/sqlJsAdapter.js +268 -0
  53. package/dist/cjs/adapters/supabase.d.ts +58 -0
  54. package/dist/cjs/adapters/supabase.js +401 -0
  55. package/dist/cjs/codecs/BrowserBlobCodec.d.ts +14 -0
  56. package/dist/cjs/codecs/BrowserBlobCodec.js +57 -0
  57. package/dist/cjs/codecs/NodeBlobCodec.d.ts +14 -0
  58. package/dist/cjs/codecs/NodeBlobCodec.js +59 -0
  59. package/dist/cjs/core/contracts/blobCodec.d.ts +15 -0
  60. package/dist/cjs/core/contracts/blobCodec.js +15 -0
  61. package/dist/cjs/core/contracts/context.d.ts +221 -0
  62. package/dist/cjs/core/contracts/context.js +15 -0
  63. package/dist/cjs/core/contracts/dialect.d.ts +154 -0
  64. package/dist/cjs/core/contracts/dialect.js +15 -0
  65. package/dist/cjs/core/contracts/events.d.ts +225 -0
  66. package/dist/cjs/core/contracts/events.js +15 -0
  67. package/dist/cjs/core/contracts/exporter.d.ts +13 -0
  68. package/dist/cjs/core/contracts/exporter.js +15 -0
  69. package/dist/cjs/core/contracts/extensions.d.ts +73 -0
  70. package/dist/cjs/core/contracts/extensions.js +15 -0
  71. package/dist/cjs/core/contracts/features.d.ts +25 -0
  72. package/dist/cjs/core/contracts/features.js +61 -0
  73. package/dist/cjs/core/contracts/fts.d.ts +66 -0
  74. package/dist/cjs/core/contracts/fts.js +15 -0
  75. package/dist/cjs/core/contracts/hooks.d.ts +481 -0
  76. package/dist/cjs/core/contracts/hooks.js +140 -0
  77. package/dist/cjs/core/contracts/index.d.ts +260 -0
  78. package/dist/cjs/core/contracts/index.js +41 -0
  79. package/dist/cjs/core/contracts/limitations.d.ts +46 -0
  80. package/dist/cjs/core/contracts/limitations.js +218 -0
  81. package/dist/cjs/core/contracts/performance.d.ts +308 -0
  82. package/dist/cjs/core/contracts/performance.js +144 -0
  83. package/dist/cjs/core/database.d.ts +220 -0
  84. package/dist/cjs/core/database.js +136 -0
  85. package/dist/cjs/core/portable.d.ts +23 -0
  86. package/dist/cjs/core/portable.js +66 -0
  87. package/dist/cjs/core/resolver.d.ts +77 -0
  88. package/dist/cjs/core/resolver.js +235 -0
  89. package/dist/cjs/dialects/PostgresDialect.d.ts +35 -0
  90. package/dist/cjs/dialects/PostgresDialect.js +143 -0
  91. package/dist/cjs/dialects/SqliteDialect.d.ts +35 -0
  92. package/dist/cjs/dialects/SqliteDialect.js +142 -0
  93. package/dist/cjs/dialects/shared.d.ts +17 -0
  94. package/dist/cjs/dialects/shared.js +90 -0
  95. package/dist/cjs/exporters/PostgresExporter.d.ts +14 -0
  96. package/dist/cjs/exporters/PostgresExporter.js +61 -0
  97. package/dist/cjs/exporters/SqliteFileExporter.d.ts +16 -0
  98. package/dist/cjs/exporters/SqliteFileExporter.js +43 -0
  99. package/dist/cjs/features/backup/cloudBackup.d.ts +219 -0
  100. package/dist/cjs/features/backup/cloudBackup.js +209 -0
  101. package/dist/cjs/features/kv/idb.d.ts +79 -0
  102. package/dist/cjs/features/kv/idb.js +32 -0
  103. package/dist/cjs/features/kv/index.d.ts +14 -0
  104. package/dist/cjs/features/kv/index.js +40 -0
  105. package/dist/cjs/features/kv/indexedDbKeyValueStore.d.ts +77 -0
  106. package/dist/cjs/features/kv/indexedDbKeyValueStore.js +116 -0
  107. package/dist/cjs/features/kv/keyValueStore.d.ts +48 -0
  108. package/dist/cjs/features/kv/keyValueStore.js +67 -0
  109. package/dist/cjs/features/kv/sqlKeyValueStore.d.ts +34 -0
  110. package/dist/cjs/features/kv/sqlKeyValueStore.js +81 -0
  111. package/dist/cjs/features/kv/valueCodec.d.ts +35 -0
  112. package/dist/cjs/features/kv/valueCodec.js +426 -0
  113. package/dist/cjs/features/migrations/dataExport.d.ts +77 -0
  114. package/dist/cjs/features/migrations/dataExport.js +194 -0
  115. package/dist/cjs/features/migrations/dataImport.d.ts +54 -0
  116. package/dist/cjs/features/migrations/dataImport.js +300 -0
  117. package/dist/cjs/features/migrations/migration.d.ts +89 -0
  118. package/dist/cjs/features/migrations/migration.js +187 -0
  119. package/dist/cjs/features/migrations/schemaMigrations.d.ts +93 -0
  120. package/dist/cjs/features/migrations/schemaMigrations.js +220 -0
  121. package/dist/cjs/features/sync/conflicts/conflictResolver.d.ts +222 -0
  122. package/dist/cjs/features/sync/conflicts/conflictResolver.js +366 -0
  123. package/dist/cjs/features/sync/conflicts/index.d.ts +9 -0
  124. package/dist/cjs/features/sync/conflicts/index.js +21 -0
  125. package/dist/cjs/features/sync/crossPlatformSync.d.ts +281 -0
  126. package/dist/cjs/features/sync/crossPlatformSync.js +551 -0
  127. package/dist/cjs/features/sync/devices/deviceManager.d.ts +243 -0
  128. package/dist/cjs/features/sync/devices/deviceManager.js +450 -0
  129. package/dist/cjs/features/sync/devices/index.d.ts +10 -0
  130. package/dist/cjs/features/sync/devices/index.js +21 -0
  131. package/dist/cjs/features/sync/index.d.ts +37 -0
  132. package/dist/cjs/features/sync/index.js +111 -0
  133. package/dist/cjs/features/sync/protocol/index.d.ts +11 -0
  134. package/dist/cjs/features/sync/protocol/index.js +23 -0
  135. package/dist/cjs/features/sync/protocol/messages.d.ts +348 -0
  136. package/dist/cjs/features/sync/protocol/messages.js +215 -0
  137. package/dist/cjs/features/sync/protocol/vectorClock.d.ts +164 -0
  138. package/dist/cjs/features/sync/protocol/vectorClock.js +256 -0
  139. package/dist/cjs/features/sync/syncManager.d.ts +348 -0
  140. package/dist/cjs/features/sync/syncManager.js +455 -0
  141. package/dist/cjs/features/sync/tables/index.d.ts +10 -0
  142. package/dist/cjs/features/sync/tables/index.js +21 -0
  143. package/dist/cjs/features/sync/tables/syncLogManager.d.ts +216 -0
  144. package/dist/cjs/features/sync/tables/syncLogManager.js +423 -0
  145. package/dist/cjs/features/sync/transport/httpTransport.d.ts +123 -0
  146. package/dist/cjs/features/sync/transport/httpTransport.js +346 -0
  147. package/dist/cjs/features/sync/transport/index.d.ts +12 -0
  148. package/dist/cjs/features/sync/transport/index.js +25 -0
  149. package/dist/cjs/features/sync/transport/transport.d.ts +259 -0
  150. package/dist/cjs/features/sync/transport/transport.js +163 -0
  151. package/dist/cjs/features/sync/transport/websocketTransport.d.ts +126 -0
  152. package/dist/cjs/features/sync/transport/websocketTransport.js +342 -0
  153. package/dist/cjs/fts/PostgresFts.d.ts +29 -0
  154. package/dist/cjs/fts/PostgresFts.js +77 -0
  155. package/dist/cjs/fts/SqliteFts5.d.ts +22 -0
  156. package/dist/cjs/fts/SqliteFts5.js +58 -0
  157. package/dist/cjs/index.d.ts +30 -0
  158. package/dist/cjs/index.js +101 -0
  159. package/dist/cjs/package.json +3 -0
  160. package/dist/cjs/shared/connectionGate.d.ts +94 -0
  161. package/dist/cjs/shared/connectionGate.js +77 -0
  162. package/dist/cjs/shared/errors.d.ts +23 -0
  163. package/dist/cjs/shared/errors.js +45 -0
  164. package/dist/cjs/shared/logger.d.ts +26 -0
  165. package/dist/cjs/shared/logger.js +40 -0
  166. package/dist/cjs/shared/parameterUtils.d.ts +16 -0
  167. package/dist/cjs/shared/parameterUtils.js +59 -0
  168. package/dist/cjs/shared/postgresTarget.d.ts +11 -0
  169. package/dist/cjs/shared/postgresTarget.js +30 -0
  170. package/dist/cjs/shared/segment.d.ts +43 -0
  171. package/dist/cjs/shared/segment.js +63 -0
  172. package/dist/cjs/shared/serializedTransaction.d.ts +14 -0
  173. package/dist/cjs/shared/serializedTransaction.js +74 -0
  174. package/dist/cjs/shared/splitSqlStatements.d.ts +27 -0
  175. package/dist/cjs/shared/splitSqlStatements.js +163 -0
  176. package/dist/cjs/shared/sqlPlaceholders.d.ts +48 -0
  177. package/dist/cjs/shared/sqlPlaceholders.js +263 -0
  178. package/dist/cjs/types/index.d.ts +29 -0
  179. package/dist/cjs/types/index.js +33 -0
  180. package/dist/core/portable.d.ts +23 -0
  181. package/dist/core/portable.d.ts.map +1 -0
  182. package/dist/core/portable.js +23 -0
  183. package/dist/core/portable.js.map +1 -0
  184. package/package.json +139 -24
@@ -0,0 +1,441 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
20
+ // If the importer is in node compatibility mode or this is not an ESM
21
+ // file that has been converted to a CommonJS file using a Babel-
22
+ // compatible transform (i.e. "__esModule" has not been set), then set
23
+ // "default" to the CommonJS "module.exports" for node compatibility.
24
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
25
+ mod
26
+ ));
27
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
28
+ var autoMigrator_exports = {};
29
+ __export(autoMigrator_exports, {
30
+ AutoMigrator: () => AutoMigrator,
31
+ createAutoMigrator: () => createAutoMigrator
32
+ });
33
+ module.exports = __toCommonJS(autoMigrator_exports);
34
+ var import_fs = __toESM(require("fs"));
35
+ var import_path = __toESM(require("path"));
36
+ const DEFAULT_CONFIG = {
37
+ runOnVersionChange: true,
38
+ tableName: "_migrations",
39
+ verbose: false
40
+ };
41
+ class AutoMigrator {
42
+ constructor(adapter, config) {
43
+ this.adapter = adapter;
44
+ this.migrations = [];
45
+ this.isInitialized = false;
46
+ this.lastMigrationResult = null;
47
+ this.config = {
48
+ ...DEFAULT_CONFIG,
49
+ ...config,
50
+ getAppVersion: config.getAppVersion ?? this.defaultGetAppVersion.bind(this)
51
+ };
52
+ }
53
+ // ============================================================================
54
+ // Initialization
55
+ // ============================================================================
56
+ /**
57
+ * Initialize the migration system.
58
+ */
59
+ async initialize() {
60
+ if (this.isInitialized)
61
+ return;
62
+ await this.createMigrationsTable();
63
+ this.migrations = await this.loadMigrations();
64
+ if (this.config.runOnVersionChange) {
65
+ const shouldRun = await this.shouldRunMigrations();
66
+ if (shouldRun) {
67
+ this.log("App version changed, running migrations...");
68
+ await this.runPending();
69
+ }
70
+ }
71
+ this.isInitialized = true;
72
+ this.log(`AutoMigrator initialized with ${this.migrations.length} migrations`);
73
+ }
74
+ /**
75
+ * Create the migrations tracking table.
76
+ */
77
+ async createMigrationsTable() {
78
+ await this.adapter.exec(`
79
+ CREATE TABLE IF NOT EXISTS ${this.config.tableName} (
80
+ version INTEGER PRIMARY KEY,
81
+ name TEXT NOT NULL,
82
+ applied_at INTEGER NOT NULL,
83
+ app_version TEXT NOT NULL,
84
+ checksum TEXT NOT NULL
85
+ )
86
+ `);
87
+ }
88
+ // ============================================================================
89
+ // Migration Discovery
90
+ // ============================================================================
91
+ /**
92
+ * Load all migration files from the migrations directory.
93
+ */
94
+ async loadMigrations() {
95
+ const migrationsPath = this.config.migrationsPath;
96
+ if (!import_fs.default.existsSync(migrationsPath)) {
97
+ this.log(`Migrations directory not found: ${migrationsPath}`);
98
+ return [];
99
+ }
100
+ const files = import_fs.default.readdirSync(migrationsPath).filter((f) => f.endsWith(".sql") || f.endsWith(".js") || f.endsWith(".ts")).sort();
101
+ const migrations = [];
102
+ for (const file of files) {
103
+ const filePath = import_path.default.join(migrationsPath, file);
104
+ const migration = await this.parseMigrationFile(filePath);
105
+ if (migration) {
106
+ migrations.push(migration);
107
+ }
108
+ }
109
+ migrations.sort((a, b) => a.version - b.version);
110
+ return migrations;
111
+ }
112
+ /**
113
+ * Parse a migration file.
114
+ */
115
+ async parseMigrationFile(filePath) {
116
+ const fileName = import_path.default.basename(filePath);
117
+ const ext = import_path.default.extname(filePath);
118
+ const match = fileName.match(/^(\d+)[_-](.+)\.(sql|js|ts)$/);
119
+ if (!match) {
120
+ this.log(`Skipping invalid migration filename: ${fileName}`);
121
+ return null;
122
+ }
123
+ const version = parseInt(match[1], 10);
124
+ const name = match[2];
125
+ if (ext === ".sql") {
126
+ return this.parseSqlMigration(filePath, version, name);
127
+ } else {
128
+ return this.parseJsMigration(filePath, version, name);
129
+ }
130
+ }
131
+ /**
132
+ * Parse a SQL migration file.
133
+ * Supports UP and DOWN sections separated by `-- DOWN`.
134
+ */
135
+ parseSqlMigration(filePath, version, name) {
136
+ const content = import_fs.default.readFileSync(filePath, "utf-8");
137
+ const parts = content.split(/^--\s*DOWN\s*$/im);
138
+ const up = parts[0].trim();
139
+ const down = parts[1]?.trim();
140
+ return { version, name, path: filePath, up, down };
141
+ }
142
+ /**
143
+ * Parse a JS/TS migration file.
144
+ * Expects exports: { up: string, down?: string }
145
+ */
146
+ async parseJsMigration(filePath, version, name) {
147
+ try {
148
+ const module2 = await Promise.resolve().then(() => __toESM(require(filePath)));
149
+ const exports2 = module2.default ?? module2;
150
+ if (!exports2.up) {
151
+ this.log(`Migration ${name} missing 'up' export`);
152
+ return null;
153
+ }
154
+ return {
155
+ version,
156
+ name,
157
+ path: filePath,
158
+ up: typeof exports2.up === "function" ? await exports2.up() : exports2.up,
159
+ down: typeof exports2.down === "function" ? await exports2.down() : exports2.down
160
+ };
161
+ } catch (error) {
162
+ this.log(`Failed to load migration ${name}: ${error}`);
163
+ return null;
164
+ }
165
+ }
166
+ // ============================================================================
167
+ // Migration Execution
168
+ // ============================================================================
169
+ /**
170
+ * Run all pending migrations.
171
+ */
172
+ async runPending() {
173
+ const startTime = Date.now();
174
+ const applied = await this.getAppliedMigrations();
175
+ const appliedVersions = new Set(applied.map((m) => m.version));
176
+ const pending = this.migrations.filter((m) => !appliedVersions.has(m.version));
177
+ if (pending.length === 0) {
178
+ this.log("No pending migrations");
179
+ return {
180
+ success: true,
181
+ migrationsRun: 0,
182
+ migrationsFailed: 0,
183
+ duration: Date.now() - startTime,
184
+ appliedMigrations: [],
185
+ errors: []
186
+ };
187
+ }
188
+ const result = {
189
+ success: true,
190
+ migrationsRun: 0,
191
+ migrationsFailed: 0,
192
+ duration: 0,
193
+ appliedMigrations: [],
194
+ errors: []
195
+ };
196
+ for (const migration of pending) {
197
+ try {
198
+ await this.applyMigration(migration);
199
+ result.migrationsRun++;
200
+ result.appliedMigrations.push(migration.name);
201
+ this.log(`Applied migration: ${migration.name}`);
202
+ } catch (error) {
203
+ result.migrationsFailed++;
204
+ result.success = false;
205
+ result.errors.push({
206
+ migration: migration.name,
207
+ error: error instanceof Error ? error.message : String(error)
208
+ });
209
+ this.log(`Failed migration: ${migration.name} - ${error}`);
210
+ break;
211
+ }
212
+ }
213
+ result.duration = Date.now() - startTime;
214
+ this.lastMigrationResult = result;
215
+ return result;
216
+ }
217
+ /**
218
+ * Run a single migration.
219
+ */
220
+ async applyMigration(migration) {
221
+ const appVersion = this.config.getAppVersion();
222
+ const checksum = this.calculateChecksum(migration.up);
223
+ await this.adapter.transaction(async (trx) => {
224
+ await trx.exec(migration.up);
225
+ await trx.run(`INSERT INTO ${this.config.tableName} (version, name, applied_at, app_version, checksum) VALUES (?, ?, ?, ?, ?)`, [migration.version, migration.name, Date.now(), appVersion, checksum]);
226
+ });
227
+ }
228
+ /**
229
+ * Run a specific migration by version.
230
+ */
231
+ async runMigrationByVersion(version) {
232
+ const migration = this.migrations.find((m) => m.version === version);
233
+ if (!migration) {
234
+ throw new Error(`Migration version ${version} not found`);
235
+ }
236
+ await this.applyMigration(migration);
237
+ }
238
+ // ============================================================================
239
+ // Rollback
240
+ // ============================================================================
241
+ /**
242
+ * Rollback the last applied migration.
243
+ */
244
+ async rollbackLast() {
245
+ const startTime = Date.now();
246
+ const applied = await this.getAppliedMigrations();
247
+ if (applied.length === 0) {
248
+ return {
249
+ success: true,
250
+ migrationsRun: 0,
251
+ migrationsFailed: 0,
252
+ duration: Date.now() - startTime,
253
+ appliedMigrations: [],
254
+ errors: []
255
+ };
256
+ }
257
+ const lastApplied = applied[applied.length - 1];
258
+ const migration = this.migrations.find((m) => m.version === lastApplied.version);
259
+ if (!migration) {
260
+ throw new Error(`Migration ${lastApplied.version} not found in migration files`);
261
+ }
262
+ if (!migration.down) {
263
+ throw new Error(`Migration ${migration.name} does not have a rollback script`);
264
+ }
265
+ try {
266
+ await this.adapter.transaction(async (trx) => {
267
+ await trx.exec(migration.down);
268
+ await trx.run(`DELETE FROM ${this.config.tableName} WHERE version = ?`, [migration.version]);
269
+ });
270
+ this.log(`Rolled back migration: ${migration.name}`);
271
+ return {
272
+ success: true,
273
+ migrationsRun: 1,
274
+ migrationsFailed: 0,
275
+ duration: Date.now() - startTime,
276
+ appliedMigrations: [migration.name],
277
+ errors: []
278
+ };
279
+ } catch (error) {
280
+ return {
281
+ success: false,
282
+ migrationsRun: 0,
283
+ migrationsFailed: 1,
284
+ duration: Date.now() - startTime,
285
+ appliedMigrations: [],
286
+ errors: [{
287
+ migration: migration.name,
288
+ error: error instanceof Error ? error.message : String(error)
289
+ }]
290
+ };
291
+ }
292
+ }
293
+ /**
294
+ * Rollback to a specific version.
295
+ */
296
+ async rollbackTo(targetVersion) {
297
+ const startTime = Date.now();
298
+ const applied = await this.getAppliedMigrations();
299
+ const toRollback = applied.filter((m) => m.version > targetVersion).reverse();
300
+ const result = {
301
+ success: true,
302
+ migrationsRun: 0,
303
+ migrationsFailed: 0,
304
+ duration: 0,
305
+ appliedMigrations: [],
306
+ errors: []
307
+ };
308
+ for (const migration of toRollback) {
309
+ const migrationFile = this.migrations.find((m) => m.version === migration.version);
310
+ if (!migrationFile?.down) {
311
+ result.migrationsFailed++;
312
+ result.success = false;
313
+ result.errors.push({
314
+ migration: migration.name,
315
+ error: "No rollback script available"
316
+ });
317
+ break;
318
+ }
319
+ try {
320
+ await this.adapter.transaction(async (trx) => {
321
+ await trx.exec(migrationFile.down);
322
+ await trx.run(`DELETE FROM ${this.config.tableName} WHERE version = ?`, [migration.version]);
323
+ });
324
+ result.migrationsRun++;
325
+ result.appliedMigrations.push(migration.name);
326
+ } catch (error) {
327
+ result.migrationsFailed++;
328
+ result.success = false;
329
+ result.errors.push({
330
+ migration: migration.name,
331
+ error: error instanceof Error ? error.message : String(error)
332
+ });
333
+ break;
334
+ }
335
+ }
336
+ result.duration = Date.now() - startTime;
337
+ return result;
338
+ }
339
+ // ============================================================================
340
+ // Status & Query
341
+ // ============================================================================
342
+ /**
343
+ * Get all applied migrations.
344
+ */
345
+ async getAppliedMigrations() {
346
+ const rows = await this.adapter.all(`SELECT * FROM ${this.config.tableName} ORDER BY version ASC`);
347
+ return rows.map((row) => ({
348
+ version: row.version,
349
+ name: row.name,
350
+ appliedAt: row.applied_at,
351
+ appVersion: row.app_version,
352
+ checksum: row.checksum
353
+ }));
354
+ }
355
+ /**
356
+ * Get pending migrations.
357
+ */
358
+ async getPendingMigrations() {
359
+ const applied = await this.getAppliedMigrations();
360
+ const appliedVersions = new Set(applied.map((m) => m.version));
361
+ return this.migrations.filter((m) => !appliedVersions.has(m.version));
362
+ }
363
+ /**
364
+ * Get migration status.
365
+ */
366
+ async getStatus() {
367
+ const applied = await this.getAppliedMigrations();
368
+ const pending = await this.getPendingMigrations();
369
+ return {
370
+ currentVersion: applied.length > 0 ? applied[applied.length - 1].version : 0,
371
+ latestVersion: this.migrations.length > 0 ? this.migrations[this.migrations.length - 1].version : 0,
372
+ pending: pending.map((m) => m.name),
373
+ applied: applied.map((m) => m.name)
374
+ };
375
+ }
376
+ /**
377
+ * Check if migrations should run based on version change.
378
+ */
379
+ async shouldRunMigrations() {
380
+ const pending = await this.getPendingMigrations();
381
+ return pending.length > 0;
382
+ }
383
+ // ============================================================================
384
+ // Utilities
385
+ // ============================================================================
386
+ /**
387
+ * Default app version getter.
388
+ */
389
+ defaultGetAppVersion() {
390
+ try {
391
+ const { app } = require("electron");
392
+ if (app?.getVersion) {
393
+ return app.getVersion();
394
+ }
395
+ } catch {
396
+ }
397
+ try {
398
+ const packagePath = import_path.default.join(process.cwd(), "package.json");
399
+ if (import_fs.default.existsSync(packagePath)) {
400
+ const pkg = JSON.parse(import_fs.default.readFileSync(packagePath, "utf-8"));
401
+ return pkg.version ?? "0.0.0";
402
+ }
403
+ } catch {
404
+ }
405
+ return "0.0.0";
406
+ }
407
+ /**
408
+ * Calculate checksum of migration content.
409
+ */
410
+ calculateChecksum(content) {
411
+ let hash = 0;
412
+ for (let i = 0; i < content.length; i++) {
413
+ const char = content.charCodeAt(i);
414
+ hash = (hash << 5) - hash + char;
415
+ hash = hash & hash;
416
+ }
417
+ return hash.toString(16);
418
+ }
419
+ /**
420
+ * Log a message if verbose mode is enabled.
421
+ */
422
+ log(message) {
423
+ if (this.config.verbose) {
424
+ console.log(`[AutoMigrator] ${message}`);
425
+ }
426
+ }
427
+ /**
428
+ * Get the last migration result.
429
+ */
430
+ getLastResult() {
431
+ return this.lastMigrationResult;
432
+ }
433
+ }
434
+ function createAutoMigrator(adapter, config) {
435
+ return new AutoMigrator(adapter, config);
436
+ }
437
+ // Annotate the CommonJS export names for ESM import in node:
438
+ 0 && (module.exports = {
439
+ AutoMigrator,
440
+ createAutoMigrator
441
+ });
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Migration Module for Electron SQL Storage Adapter.
3
+ *
4
+ * Provides automatic database migration management for Electron applications.
5
+ *
6
+ * @packageDocumentation
7
+ */
8
+ export { AutoMigrator, createAutoMigrator, type AutoMigratorConfig, type MigrationFile, type AppliedMigration, type MigrationResult, } from './autoMigrator.js';
9
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,29 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __export = (target, all) => {
6
+ for (var name in all)
7
+ __defProp(target, name, { get: all[name], enumerable: true });
8
+ };
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
18
+ var migration_exports = {};
19
+ __export(migration_exports, {
20
+ AutoMigrator: () => import_autoMigrator.AutoMigrator,
21
+ createAutoMigrator: () => import_autoMigrator.createAutoMigrator
22
+ });
23
+ module.exports = __toCommonJS(migration_exports);
24
+ var import_autoMigrator = require("./autoMigrator.js");
25
+ // Annotate the CommonJS export names for ESM import in node:
26
+ 0 && (module.exports = {
27
+ AutoMigrator,
28
+ createAutoMigrator
29
+ });
@@ -0,0 +1,126 @@
1
+ /**
2
+ * Preload Script for Electron SQL Storage Adapter.
3
+ *
4
+ * Exposes a secure API to renderer processes via contextBridge.
5
+ * This script runs in an isolated context with access to Node.js APIs
6
+ * and Electron's IPC modules.
7
+ *
8
+ * ## Security
9
+ * - Only exposes necessary functions via contextBridge
10
+ * - All IPC calls are wrapped with proper error handling
11
+ * - No direct access to Node.js modules from renderer
12
+ *
13
+ * ## Usage in main.js
14
+ * ```javascript
15
+ * new BrowserWindow({
16
+ * webPreferences: {
17
+ * preload: path.join(__dirname, 'preload.js'),
18
+ * contextIsolation: true,
19
+ * nodeIntegration: false,
20
+ * }
21
+ * });
22
+ * ```
23
+ */
24
+ import type { TransactionContext, SyncStatus, DbChangeEvent } from './ipc/types.js';
25
+ import type { StorageRunResult, StorageOpenOptions, StorageParameters, BatchOperation, BatchResult, StorageCapability } from '../../core/contracts/index.js';
26
+ /**
27
+ * SQL Storage API exposed to renderer processes.
28
+ */
29
+ declare const sqlStorageApi: {
30
+ /**
31
+ * Open the database connection.
32
+ */
33
+ open(options?: StorageOpenOptions): Promise<void>;
34
+ /**
35
+ * Close the database connection.
36
+ */
37
+ close(): Promise<void>;
38
+ /**
39
+ * Check if the database is open.
40
+ */
41
+ isOpen(): Promise<boolean>;
42
+ /**
43
+ * Get adapter capabilities.
44
+ */
45
+ getCapabilities(): Promise<StorageCapability[]>;
46
+ /**
47
+ * Execute a mutation statement (INSERT, UPDATE, DELETE).
48
+ */
49
+ run(statement: string, parameters?: StorageParameters): Promise<StorageRunResult>;
50
+ /**
51
+ * Get a single row.
52
+ */
53
+ get<T = unknown>(statement: string, parameters?: StorageParameters): Promise<T | null>;
54
+ /**
55
+ * Get all matching rows.
56
+ */
57
+ all<T = unknown>(statement: string, parameters?: StorageParameters): Promise<T[]>;
58
+ /**
59
+ * Execute a SQL script.
60
+ */
61
+ exec(script: string): Promise<void>;
62
+ /**
63
+ * Execute batch operations.
64
+ */
65
+ batch(operations: BatchOperation[]): Promise<BatchResult>;
66
+ /**
67
+ * Begin a transaction.
68
+ */
69
+ beginTransaction(): Promise<TransactionContext>;
70
+ /**
71
+ * Commit a transaction.
72
+ */
73
+ commitTransaction(transactionId: string): Promise<void>;
74
+ /**
75
+ * Rollback a transaction.
76
+ */
77
+ rollbackTransaction(transactionId: string): Promise<void>;
78
+ /**
79
+ * Execute an operation within a transaction.
80
+ */
81
+ executeInTransaction(transactionId: string, statement: string, parameters?: StorageParameters): Promise<StorageRunResult | unknown[]>;
82
+ /**
83
+ * Execute a callback within a transaction (convenience method).
84
+ * Automatically handles begin/commit/rollback.
85
+ */
86
+ transaction<T>(fn: (trx: {
87
+ run: (statement: string, parameters?: StorageParameters) => Promise<StorageRunResult>;
88
+ get: <R = unknown>(statement: string, parameters?: StorageParameters) => Promise<R | null>;
89
+ all: <R = unknown>(statement: string, parameters?: StorageParameters) => Promise<R[]>;
90
+ }) => Promise<T>): Promise<T>;
91
+ /**
92
+ * Get sync status.
93
+ */
94
+ getSyncStatus(): Promise<SyncStatus>;
95
+ /**
96
+ * Trigger manual sync.
97
+ */
98
+ triggerSync(): Promise<void>;
99
+ /**
100
+ * Subscribe to database change events.
101
+ */
102
+ onDatabaseChange(callback: (event: DbChangeEvent) => void): () => void;
103
+ /**
104
+ * Subscribe to sync progress events.
105
+ */
106
+ onSyncProgress(callback: (progress: number) => void): () => void;
107
+ /**
108
+ * Subscribe to sync complete events.
109
+ */
110
+ onSyncComplete(callback: () => void): () => void;
111
+ /**
112
+ * Subscribe to sync error events.
113
+ */
114
+ onSyncError(callback: (error: Error) => void): () => void;
115
+ };
116
+ /**
117
+ * Type declaration for window.sqlStorage.
118
+ */
119
+ export type SqlStorageApi = typeof sqlStorageApi;
120
+ export { sqlStorageApi };
121
+ declare global {
122
+ interface Window {
123
+ sqlStorage: SqlStorageApi;
124
+ }
125
+ }
126
+ //# sourceMappingURL=preload.d.ts.map