@ccheever/exact-ibex-runtime 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 (161) hide show
  1. package/package.json +63 -0
  2. package/src/abort/AbortController.ts +23 -0
  3. package/src/abort/AbortSignal.ts +152 -0
  4. package/src/abort/index.ts +2 -0
  5. package/src/accessibility.ts +12 -0
  6. package/src/arraybuffer-detach.ts +109 -0
  7. package/src/base64/base64.ts +168 -0
  8. package/src/base64/index.ts +1 -0
  9. package/src/blob/Blob.ts +259 -0
  10. package/src/blob/File.ts +59 -0
  11. package/src/blob/FormData.ts +323 -0
  12. package/src/blob/index.ts +3 -0
  13. package/src/bootstrap.ts +1946 -0
  14. package/src/broadcast/BroadcastChannel.ts +280 -0
  15. package/src/broadcast/index.ts +5 -0
  16. package/src/cache/Cache.ts +349 -0
  17. package/src/cache/CacheStorage.ts +89 -0
  18. package/src/cache/index.ts +27 -0
  19. package/src/camera/index.ts +6202 -0
  20. package/src/camera/processor.worker.ts +194 -0
  21. package/src/camera/scene.ts +195 -0
  22. package/src/clipboard/Clipboard.ts +129 -0
  23. package/src/clipboard/ClipboardItem.ts +97 -0
  24. package/src/clipboard/index.ts +6 -0
  25. package/src/clone/index.ts +1 -0
  26. package/src/clone/structuredClone.ts +389 -0
  27. package/src/clone/transferableSymbols.ts +2 -0
  28. package/src/compression/CompressionStream.ts +146 -0
  29. package/src/compression/DecompressionStream.ts +342 -0
  30. package/src/compression/index.ts +4 -0
  31. package/src/console/Console.ts +341 -0
  32. package/src/console/index.ts +2 -0
  33. package/src/core/accessibility-state.ts +263 -0
  34. package/src/core/accessibility.ts +184 -0
  35. package/src/core/agent-state.ts +37 -0
  36. package/src/core/diagnostics-logs.ts +144 -0
  37. package/src/core/host-call-bridge.ts +16 -0
  38. package/src/core/i18n-helpers.ts +189 -0
  39. package/src/core/locale-state.ts +253 -0
  40. package/src/core/locale.ts +95 -0
  41. package/src/crypto/Crypto.ts +2743 -0
  42. package/src/crypto/index.ts +1 -0
  43. package/src/diagnostics/logs.ts +7 -0
  44. package/src/encoding/TextDecoder.ts +1181 -0
  45. package/src/encoding/TextDecoderStream.ts +58 -0
  46. package/src/encoding/TextEncoder.ts +180 -0
  47. package/src/encoding/TextEncoderStream.ts +39 -0
  48. package/src/encoding/index.ts +8 -0
  49. package/src/events/CloseEvent.ts +91 -0
  50. package/src/events/DOMException.ts +409 -0
  51. package/src/events/ErrorEvent.ts +39 -0
  52. package/src/events/Event.ts +151 -0
  53. package/src/events/EventTarget.ts +280 -0
  54. package/src/events/FocusEvent.ts +27 -0
  55. package/src/events/KeyboardEvent.ts +46 -0
  56. package/src/events/MessageEvent.ts +61 -0
  57. package/src/events/ProgressEvent.ts +33 -0
  58. package/src/events/PromiseRejectionEvent.ts +31 -0
  59. package/src/events/index.ts +52 -0
  60. package/src/eventsource/EventSource.ts +371 -0
  61. package/src/eventsource/index.ts +2 -0
  62. package/src/fetch/Headers.ts +642 -0
  63. package/src/fetch/Request.ts +760 -0
  64. package/src/fetch/Response.ts +543 -0
  65. package/src/fetch/body.ts +1256 -0
  66. package/src/fetch/cookie-jar.ts +566 -0
  67. package/src/fetch/demo.ts +207 -0
  68. package/src/fetch/errors.ts +101 -0
  69. package/src/fetch/fetch.ts +2610 -0
  70. package/src/fetch/index.ts +101 -0
  71. package/src/fetch/native-bridge.ts +65 -0
  72. package/src/fetch/types.ts +258 -0
  73. package/src/filereader/FileReader.ts +236 -0
  74. package/src/filereader/index.ts +1 -0
  75. package/src/fs/Dirent.ts +39 -0
  76. package/src/fs/ExactFile.ts +450 -0
  77. package/src/fs/Stats.ts +80 -0
  78. package/src/fs/index.ts +944 -0
  79. package/src/fs/promises.ts +386 -0
  80. package/src/fs/shared.ts +328 -0
  81. package/src/http-server/index.js +697 -0
  82. package/src/http-server/index.ts +27 -0
  83. package/src/identity.generated.ts +14 -0
  84. package/src/index.ts +283 -0
  85. package/src/indexeddb/IDBCursor.ts +188 -0
  86. package/src/indexeddb/IDBDatabase.ts +343 -0
  87. package/src/indexeddb/IDBFactory.ts +269 -0
  88. package/src/indexeddb/IDBIndex.ts +194 -0
  89. package/src/indexeddb/IDBKeyRange.ts +109 -0
  90. package/src/indexeddb/IDBObjectStore.ts +468 -0
  91. package/src/indexeddb/IDBRequest.ts +163 -0
  92. package/src/indexeddb/IDBTransaction.ts +207 -0
  93. package/src/indexeddb/index.ts +34 -0
  94. package/src/indexeddb/utils.ts +52 -0
  95. package/src/inspect/index.ts +1 -0
  96. package/src/inspect/inspect.ts +465 -0
  97. package/src/internal/detect.ts +104 -0
  98. package/src/locale.ts +10 -0
  99. package/src/location/index.ts +1059 -0
  100. package/src/locks/LockManager.ts +460 -0
  101. package/src/locks/index.ts +12 -0
  102. package/src/media/VideoFrame.ts +58 -0
  103. package/src/messaging/MessageChannel.ts +31 -0
  104. package/src/messaging/MessagePort.ts +180 -0
  105. package/src/messaging/index.ts +2 -0
  106. package/src/messaging.ts +247 -0
  107. package/src/native/NativeModules.ts +354 -0
  108. package/src/native/index.ts +1 -0
  109. package/src/navigator/Navigator.ts +351 -0
  110. package/src/navigator/index.ts +1 -0
  111. package/src/node/Buffer.ts +1786 -0
  112. package/src/node/index.ts +4 -0
  113. package/src/node/path.ts +495 -0
  114. package/src/node/process.ts +2528 -0
  115. package/src/performance/Performance.ts +532 -0
  116. package/src/performance/index.ts +21 -0
  117. package/src/polyfills/array.ts +236 -0
  118. package/src/polyfills/arraybuffer.ts +172 -0
  119. package/src/polyfills/groupby.ts +85 -0
  120. package/src/polyfills/index.ts +85 -0
  121. package/src/polyfills/intl.ts +1956 -0
  122. package/src/polyfills/iterator.ts +479 -0
  123. package/src/polyfills/promise.ts +37 -0
  124. package/src/polyfills/set.ts +245 -0
  125. package/src/polyfills/string.ts +85 -0
  126. package/src/polyfills/typedarray.ts +110 -0
  127. package/src/promise-rejection-tracking.ts +464 -0
  128. package/src/react-native/index.ts +388 -0
  129. package/src/runtime-entry.ts +55 -0
  130. package/src/scheduling/AnimationFrame.ts +105 -0
  131. package/src/scheduling/IdleCallback.ts +167 -0
  132. package/src/scheduling/index.ts +13 -0
  133. package/src/security/Capabilities.ts +1146 -0
  134. package/src/security/Permissions.ts +392 -0
  135. package/src/security/capability-bits.generated.ts +63 -0
  136. package/src/security/index.ts +16 -0
  137. package/src/sqlite/Database.ts +456 -0
  138. package/src/sqlite/Statement.ts +206 -0
  139. package/src/sqlite/constants.ts +79 -0
  140. package/src/sqlite/errors.ts +25 -0
  141. package/src/sqlite/index.ts +34 -0
  142. package/src/sqlite/module.js +438 -0
  143. package/src/storage/Storage.ts +291 -0
  144. package/src/storage/StorageManager.ts +91 -0
  145. package/src/storage/index.ts +3 -0
  146. package/src/stream-compat.ts +47 -0
  147. package/src/streams/ReadableStream.ts +4131 -0
  148. package/src/streams/TransformStream.ts +375 -0
  149. package/src/streams/WritableStream.ts +866 -0
  150. package/src/streams/index.ts +41 -0
  151. package/src/timers/Timers.ts +296 -0
  152. package/src/timers/index.ts +11 -0
  153. package/src/url/URL.ts +656 -0
  154. package/src/url/URLPattern.ts +850 -0
  155. package/src/url/URLSearchParams.ts +244 -0
  156. package/src/url/index.ts +9 -0
  157. package/src/websocket/WebSocket.ts +770 -0
  158. package/src/websocket/WebSocketError.ts +52 -0
  159. package/src/websocket/WebSocketStream.ts +628 -0
  160. package/src/websocket/index.ts +7 -0
  161. package/src/window/index.ts +872 -0
@@ -0,0 +1,79 @@
1
+ /**
2
+ * SQLite constants for the Ibex runtime.
3
+ *
4
+ * Matches the constants exported by bun:sqlite.
5
+ */
6
+
7
+ export const constants = {
8
+ // Open flags
9
+ SQLITE_OPEN_READONLY: 0x00000001,
10
+ SQLITE_OPEN_READWRITE: 0x00000002,
11
+ SQLITE_OPEN_CREATE: 0x00000004,
12
+ SQLITE_OPEN_DELETEONCLOSE: 0x00000008,
13
+ SQLITE_OPEN_EXCLUSIVE: 0x00000010,
14
+ SQLITE_OPEN_AUTOPROXY: 0x00000020,
15
+ SQLITE_OPEN_URI: 0x00000040,
16
+ SQLITE_OPEN_MEMORY: 0x00000080,
17
+ SQLITE_OPEN_MAIN_DB: 0x00000100,
18
+ SQLITE_OPEN_TEMP_DB: 0x00000200,
19
+ SQLITE_OPEN_TRANSIENT_DB: 0x00000400,
20
+ SQLITE_OPEN_MAIN_JOURNAL: 0x00000800,
21
+ SQLITE_OPEN_TEMP_JOURNAL: 0x00001000,
22
+ SQLITE_OPEN_SUBJOURNAL: 0x00002000,
23
+ SQLITE_OPEN_SUPER_JOURNAL: 0x00004000,
24
+ SQLITE_OPEN_NOMUTEX: 0x00008000,
25
+ SQLITE_OPEN_FULLMUTEX: 0x00010000,
26
+ SQLITE_OPEN_SHAREDCACHE: 0x00020000,
27
+ SQLITE_OPEN_PRIVATECACHE: 0x00040000,
28
+ SQLITE_OPEN_WAL: 0x00080000,
29
+ SQLITE_OPEN_NOFOLLOW: 0x01000000,
30
+
31
+ // Prepare flags
32
+ SQLITE_PREPARE_PERSISTENT: 0x01,
33
+ SQLITE_PREPARE_NORMALIZE: 0x02,
34
+ SQLITE_PREPARE_NO_VTAB: 0x04,
35
+
36
+ // File control opcodes
37
+ SQLITE_FCNTL_LOCKSTATE: 1,
38
+ SQLITE_FCNTL_GET_LOCKPROXYFILE: 2,
39
+ SQLITE_FCNTL_SET_LOCKPROXYFILE: 3,
40
+ SQLITE_FCNTL_LAST_ERRNO: 4,
41
+ SQLITE_FCNTL_SIZE_HINT: 5,
42
+ SQLITE_FCNTL_CHUNK_SIZE: 6,
43
+ SQLITE_FCNTL_FILE_POINTER: 7,
44
+ SQLITE_FCNTL_SYNC_OMITTED: 8,
45
+ SQLITE_FCNTL_WIN32_AV_RETRY: 9,
46
+ SQLITE_FCNTL_PERSIST_WAL: 10,
47
+ SQLITE_FCNTL_OVERWRITE: 11,
48
+ SQLITE_FCNTL_VFSNAME: 12,
49
+ SQLITE_FCNTL_POWERSAFE_OVERWRITE: 13,
50
+ SQLITE_FCNTL_PRAGMA: 14,
51
+ SQLITE_FCNTL_BUSYHANDLER: 15,
52
+ SQLITE_FCNTL_TEMPFILENAME: 16,
53
+ SQLITE_FCNTL_MMAP_SIZE: 18,
54
+ SQLITE_FCNTL_TRACE: 19,
55
+ SQLITE_FCNTL_HAS_MOVED: 20,
56
+ SQLITE_FCNTL_SYNC: 21,
57
+ SQLITE_FCNTL_COMMIT_PHASETWO: 22,
58
+ SQLITE_FCNTL_WIN32_SET_HANDLE: 23,
59
+ SQLITE_FCNTL_WAL_BLOCK: 24,
60
+ SQLITE_FCNTL_ZIPVFS: 25,
61
+ SQLITE_FCNTL_RBU: 26,
62
+ SQLITE_FCNTL_VFS_POINTER: 27,
63
+ SQLITE_FCNTL_JOURNAL_POINTER: 28,
64
+ SQLITE_FCNTL_WIN32_GET_HANDLE: 29,
65
+ SQLITE_FCNTL_PDB: 30,
66
+ SQLITE_FCNTL_BEGIN_ATOMIC_WRITE: 31,
67
+ SQLITE_FCNTL_COMMIT_ATOMIC_WRITE: 32,
68
+ SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE: 33,
69
+ SQLITE_FCNTL_LOCK_TIMEOUT: 34,
70
+ SQLITE_FCNTL_DATA_VERSION: 35,
71
+ SQLITE_FCNTL_SIZE_LIMIT: 36,
72
+ SQLITE_FCNTL_CKPT_DONE: 37,
73
+ SQLITE_FCNTL_RESERVE_BYTES: 38,
74
+ SQLITE_FCNTL_CKPT_START: 39,
75
+ SQLITE_FCNTL_EXTERNAL_READER: 40,
76
+ SQLITE_FCNTL_CKSM_FILE: 41,
77
+ } as const;
78
+
79
+ export default constants;
@@ -0,0 +1,25 @@
1
+ /**
2
+ * SQLite error class for the Ibex runtime.
3
+ * Matches bun:sqlite's SQLiteError.
4
+ */
5
+
6
+ export class SQLiteError implements Error {
7
+ readonly name = 'SQLiteError';
8
+ readonly message: string;
9
+ stack?: string;
10
+ readonly errno: number;
11
+ readonly code?: string;
12
+ readonly byteOffset: number;
13
+
14
+ constructor(message: string, errno: number = 0, code?: string, byteOffset: number = 0) {
15
+ this.message = message;
16
+ this.stack = new Error(this.message).stack;
17
+ this.errno = errno;
18
+ this.code = code;
19
+ this.byteOffset = byteOffset;
20
+ }
21
+ }
22
+ Object.setPrototypeOf(SQLiteError.prototype, Error.prototype);
23
+ Object.setPrototypeOf(SQLiteError, Error);
24
+
25
+ export default SQLiteError;
@@ -0,0 +1,34 @@
1
+ /**
2
+ * exact:sqlite module
3
+ *
4
+ * SQLite database module for the Ibex runtime.
5
+ * API compatible with bun:sqlite, with built-in cr-sqlite CRDT support.
6
+ *
7
+ * @example
8
+ * ```typescript
9
+ * import { Database } from "exact:sqlite";
10
+ *
11
+ * const db = new Database(":memory:");
12
+ * db.run("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)");
13
+ * db.run("INSERT INTO users (name) VALUES (?)", "Alice");
14
+ *
15
+ * const users = db.query("SELECT * FROM users").all();
16
+ * console.log(users); // [{ id: 1, name: "Alice" }]
17
+ *
18
+ * // cr-sqlite support
19
+ * db.enableCrSqlite();
20
+ * db.markAsCrr("users");
21
+ * const changes = db.getChanges();
22
+ * ```
23
+ *
24
+ * @see https://bun.sh/docs/api/sqlite
25
+ * @see https://vlcn.io/docs/cr-sqlite/intro
26
+ */
27
+
28
+ export { Database, type DatabaseOptions } from './Database';
29
+ export { Statement, type Changes } from './Statement';
30
+ export { constants } from './constants';
31
+ export { SQLiteError } from './errors';
32
+
33
+ // Default export matches bun:sqlite
34
+ export { Database as default } from './Database';
@@ -0,0 +1,438 @@
1
+ /**
2
+ * exact:sqlite - CommonJS module entry point
3
+ *
4
+ * This file is included by the Rust module loader via include_str!().
5
+ * It provides the bun:sqlite-compatible API with cr-sqlite extension support.
6
+ */
7
+
8
+ var g = globalThis;
9
+
10
+ // ============================================================================
11
+ // SQLiteError
12
+ // ============================================================================
13
+
14
+ function SQLiteError(message, errno, code, byteOffset) {
15
+ var err = new Error(message);
16
+ err.name = 'SQLiteError';
17
+ err.errno = errno || 0;
18
+ err.code = code;
19
+ err.byteOffset = byteOffset || 0;
20
+ Object.setPrototypeOf(err, SQLiteError.prototype);
21
+ return err;
22
+ }
23
+ SQLiteError.prototype = Object.create(Error.prototype);
24
+ SQLiteError.prototype.constructor = SQLiteError;
25
+
26
+ // ============================================================================
27
+ // Constants
28
+ // ============================================================================
29
+
30
+ var constants = {
31
+ SQLITE_OPEN_READONLY: 0x00000001,
32
+ SQLITE_OPEN_READWRITE: 0x00000002,
33
+ SQLITE_OPEN_CREATE: 0x00000004,
34
+ SQLITE_OPEN_DELETEONCLOSE: 0x00000008,
35
+ SQLITE_OPEN_EXCLUSIVE: 0x00000010,
36
+ SQLITE_OPEN_URI: 0x00000040,
37
+ SQLITE_OPEN_MEMORY: 0x00000080,
38
+ SQLITE_OPEN_NOMUTEX: 0x00008000,
39
+ SQLITE_OPEN_FULLMUTEX: 0x00010000,
40
+ SQLITE_OPEN_SHAREDCACHE: 0x00020000,
41
+ SQLITE_OPEN_PRIVATECACHE: 0x00040000,
42
+ SQLITE_OPEN_WAL: 0x00080000,
43
+ SQLITE_PREPARE_PERSISTENT: 0x01,
44
+ SQLITE_PREPARE_NORMALIZE: 0x02,
45
+ SQLITE_PREPARE_NO_VTAB: 0x04,
46
+ SQLITE_FCNTL_LOCKSTATE: 1,
47
+ SQLITE_FCNTL_SIZE_HINT: 5,
48
+ SQLITE_FCNTL_CHUNK_SIZE: 6,
49
+ SQLITE_FCNTL_PERSIST_WAL: 10,
50
+ SQLITE_FCNTL_OVERWRITE: 11,
51
+ SQLITE_FCNTL_POWERSAFE_OVERWRITE: 13,
52
+ SQLITE_FCNTL_MMAP_SIZE: 18,
53
+ SQLITE_FCNTL_DATA_VERSION: 35,
54
+ };
55
+
56
+ // ============================================================================
57
+ // Statement
58
+ // ============================================================================
59
+
60
+ function Statement(dbHandle, sql) {
61
+ if (!g.__exactSqlitePrepare) {
62
+ throw new Error('exact:sqlite native bridge not available');
63
+ }
64
+ this._db = dbHandle;
65
+ this._sql = sql;
66
+ this._finalized = false;
67
+ this._columnTypes = [];
68
+ this._declaredTypes = [];
69
+ this._readOnly = true;
70
+ this._executed = false;
71
+
72
+ var result = g.__exactSqlitePrepare(dbHandle, sql);
73
+ this._handle = result.handle;
74
+ this.columnNames = result.columnNames || [];
75
+ this._declaredTypes = result.declaredTypes || [];
76
+ this.paramsCount = result.paramsCount || 0;
77
+ this._readOnly = result.readOnly !== false;
78
+ }
79
+
80
+ Statement.prototype._checkFinalized = function() {
81
+ if (this._finalized) throw new Error('Statement has been finalized and cannot be used');
82
+ };
83
+
84
+ Statement.prototype._normalizeParams = function(params) {
85
+ if (params.length === 0) return undefined;
86
+ if (params.length === 1 && typeof params[0] === 'object' && params[0] !== null && !(params[0] instanceof Uint8Array)) {
87
+ return params[0];
88
+ }
89
+ return params;
90
+ };
91
+
92
+ Object.defineProperty(Statement.prototype, 'native', {
93
+ get: function() {
94
+ return {
95
+ columns: this.columnNames.slice(),
96
+ columnsCount: this.columnNames.length,
97
+ };
98
+ },
99
+ configurable: true, enumerable: true,
100
+ });
101
+
102
+ Object.defineProperty(Statement.prototype, 'columnTypes', {
103
+ get: function() {
104
+ if (!this._readOnly) {
105
+ throw new Error('columnTypes is not available for non-read-only statements');
106
+ }
107
+ return this._columnTypes;
108
+ },
109
+ configurable: true, enumerable: true,
110
+ });
111
+
112
+ Object.defineProperty(Statement.prototype, 'declaredTypes', {
113
+ get: function() {
114
+ if (this._readOnly && !this._executed) {
115
+ throw new Error('Statement must be executed before accessing declaredTypes');
116
+ }
117
+ return this._declaredTypes;
118
+ },
119
+ configurable: true, enumerable: true,
120
+ });
121
+
122
+ Statement.prototype._recordExecution = function(result) {
123
+ this._executed = true;
124
+ this._columnTypes = Array.isArray(result && result.columnTypes) ? result.columnTypes : [];
125
+ };
126
+
127
+ Statement.prototype.all = function() {
128
+ this._checkFinalized();
129
+ var bindings = this._normalizeParams(Array.prototype.slice.call(arguments));
130
+ var result = g.__exactSqliteAll(this._handle, bindings);
131
+ this._recordExecution(result);
132
+ return result.rows;
133
+ };
134
+
135
+ Statement.prototype.get = function() {
136
+ this._checkFinalized();
137
+ var bindings = this._normalizeParams(Array.prototype.slice.call(arguments));
138
+ var result = g.__exactSqliteGet(this._handle, bindings);
139
+ this._recordExecution(result);
140
+ return result.row != null ? result.row : null;
141
+ };
142
+
143
+ Statement.prototype.run = function() {
144
+ this._checkFinalized();
145
+ var bindings = this._normalizeParams(Array.prototype.slice.call(arguments));
146
+ var result = g.__exactSqliteRun(this._handle, bindings);
147
+ this._executed = true;
148
+ return result;
149
+ };
150
+
151
+ Statement.prototype.values = function() {
152
+ this._checkFinalized();
153
+ var bindings = this._normalizeParams(Array.prototype.slice.call(arguments));
154
+ var result = g.__exactSqliteValues(this._handle, bindings);
155
+ this._recordExecution(result);
156
+ return result.rows;
157
+ };
158
+
159
+ Statement.prototype.finalize = function() {
160
+ if (this._finalized) return;
161
+ this._finalized = true;
162
+ if (g.__exactSqliteFinalize) g.__exactSqliteFinalize(this._handle);
163
+ };
164
+
165
+ Statement.prototype.toString = function() {
166
+ this._checkFinalized();
167
+ if (g.__exactSqliteExpandedSql) return g.__exactSqliteExpandedSql(this._handle);
168
+ return this._sql;
169
+ };
170
+
171
+ Statement.prototype.as = function(Class) {
172
+ var self = this;
173
+ var wrapped = Object.create(this);
174
+
175
+ wrapped.all = function() {
176
+ var rows = self.all.apply(self, arguments);
177
+ return rows.map(function(row) {
178
+ return Object.assign(Object.create(Class.prototype), row);
179
+ });
180
+ };
181
+
182
+ wrapped.get = function() {
183
+ var row = self.get.apply(self, arguments);
184
+ if (row === null) return null;
185
+ return Object.assign(Object.create(Class.prototype), row);
186
+ };
187
+
188
+ return wrapped;
189
+ };
190
+
191
+ // ============================================================================
192
+ // Database
193
+ // ============================================================================
194
+
195
+ function Database(filename, options) {
196
+ if (!(this instanceof Database)) return new Database(filename, options);
197
+
198
+ this.filename = filename || ':memory:';
199
+ this._closed = false;
200
+ this._queryCache = {};
201
+ this._crSqliteLoaded = false;
202
+
203
+ if (typeof options === 'number') {
204
+ this._options = {};
205
+ } else {
206
+ this._options = options || {};
207
+ }
208
+
209
+ if (!g.__exactSqliteOpen) {
210
+ throw new Error('exact:sqlite native bridge not available. The exact:sqlite module requires the Ibex runtime with SQLite support.');
211
+ }
212
+
213
+ var flags = typeof options === 'number' ? options : undefined;
214
+ this._handle = g.__exactSqliteOpen(this.filename, {
215
+ readonly: this._options.readonly || false,
216
+ create: this._options.create !== false,
217
+ readwrite: this._options.readwrite !== false,
218
+ safeIntegers: this._options.safeIntegers || false,
219
+ flags: flags,
220
+ });
221
+
222
+ // Enable WAL mode and foreign keys by default
223
+ this.run('PRAGMA journal_mode = WAL');
224
+ this.run('PRAGMA foreign_keys = ON');
225
+ }
226
+
227
+ Object.defineProperty(Database.prototype, 'handle', {
228
+ get: function() { return this._handle; },
229
+ configurable: true, enumerable: true,
230
+ });
231
+
232
+ Object.defineProperty(Database.prototype, 'inTransaction', {
233
+ get: function() {
234
+ this._checkClosed();
235
+ return g.__exactSqliteInTransaction ? g.__exactSqliteInTransaction(this._handle) : false;
236
+ },
237
+ configurable: true, enumerable: true,
238
+ });
239
+
240
+ Database.prototype._checkClosed = function() {
241
+ if (this._closed) throw new Error('Database is closed');
242
+ };
243
+
244
+ Database.prototype.query = function(sql) {
245
+ this._checkClosed();
246
+ if (!this._queryCache[sql]) {
247
+ this._queryCache[sql] = new Statement(this._handle, sql);
248
+ }
249
+ return this._queryCache[sql];
250
+ };
251
+
252
+ Database.prototype.prepare = function(sql) {
253
+ this._checkClosed();
254
+ return new Statement(this._handle, sql);
255
+ };
256
+
257
+ Database.prototype.run = function(sql) {
258
+ this._checkClosed();
259
+ var bindings = Array.prototype.slice.call(arguments, 1);
260
+ if (g.__exactSqliteExec) {
261
+ var params;
262
+ if (bindings.length === 1 && typeof bindings[0] === 'object' && bindings[0] !== null && !(bindings[0] instanceof Uint8Array)) {
263
+ params = bindings[0];
264
+ } else if (bindings.length > 0) {
265
+ params = bindings;
266
+ }
267
+ return g.__exactSqliteExec(this._handle, sql, params);
268
+ }
269
+ var stmt = this.prepare(sql);
270
+ try { return stmt.run.apply(stmt, bindings); }
271
+ finally { stmt.finalize(); }
272
+ };
273
+
274
+ Database.prototype.exec = Database.prototype.run;
275
+
276
+ Database.prototype.transaction = function(fn) {
277
+ var db = this;
278
+ db._checkClosed();
279
+
280
+ function wrapTransaction(beginStatement) {
281
+ return function() {
282
+ if (db.inTransaction) {
283
+ var sp = '_sp_' + Date.now() + '_' + Math.random().toString(36).slice(2);
284
+ db.run('SAVEPOINT "' + sp + '"');
285
+ try {
286
+ var result = fn.apply(this, arguments);
287
+ db.run('RELEASE "' + sp + '"');
288
+ return result;
289
+ } catch (e) {
290
+ db.run('ROLLBACK TO "' + sp + '"');
291
+ db.run('RELEASE "' + sp + '"');
292
+ throw e;
293
+ }
294
+ }
295
+ db.run(beginStatement);
296
+ try {
297
+ var result = fn.apply(this, arguments);
298
+ db.run('COMMIT');
299
+ return result;
300
+ } catch (e) {
301
+ db.run('ROLLBACK');
302
+ throw e;
303
+ }
304
+ };
305
+ }
306
+
307
+ var txnFn = wrapTransaction('BEGIN');
308
+ txnFn.deferred = wrapTransaction('BEGIN DEFERRED');
309
+ txnFn.immediate = wrapTransaction('BEGIN IMMEDIATE');
310
+ txnFn.exclusive = wrapTransaction('BEGIN EXCLUSIVE');
311
+ return txnFn;
312
+ };
313
+
314
+ Database.prototype.close = function(throwOnError) {
315
+ if (this._closed) return;
316
+ if (this._crSqliteLoaded) {
317
+ try { this.run('SELECT crsql_finalize()'); } catch (e) {}
318
+ }
319
+ this._closed = true;
320
+ for (var key in this._queryCache) {
321
+ this._queryCache[key].finalize();
322
+ }
323
+ this._queryCache = {};
324
+ if (g.__exactSqliteClose) {
325
+ try { g.__exactSqliteClose(this._handle); }
326
+ catch (e) { if (throwOnError) throw e; }
327
+ }
328
+ };
329
+
330
+ Database.prototype.serialize = function(name) {
331
+ this._checkClosed();
332
+ if (!g.__exactSqliteSerialize) throw new Error('Database serialization not supported');
333
+ return g.__exactSqliteSerialize(this._handle, name || 'main');
334
+ };
335
+
336
+ Database.prototype.loadExtension = function(path, entryPoint) {
337
+ this._checkClosed();
338
+ if (!g.__exactSqliteLoadExtension) throw new Error('Extension loading not supported');
339
+ g.__exactSqliteLoadExtension(this._handle, path, entryPoint);
340
+ };
341
+
342
+ Database.prototype.fileControl = function() {
343
+ this._checkClosed();
344
+ if (!g.__exactSqliteFileControl) throw new Error('fileControl not supported');
345
+ return g.__exactSqliteFileControl.apply(null, [this._handle].concat(Array.prototype.slice.call(arguments)));
346
+ };
347
+
348
+ // cr-sqlite methods
349
+ Database.prototype.enableCrSqlite = function() {
350
+ this._checkClosed();
351
+ if (this._crSqliteLoaded) return;
352
+ if (g.__exactCrSqlitePath) {
353
+ this.loadExtension(g.__exactCrSqlitePath());
354
+ } else if (g.__exactSqliteLoadCrSqlite) {
355
+ g.__exactSqliteLoadCrSqlite(this._handle);
356
+ } else {
357
+ throw new Error('cr-sqlite extension not available. The Ibex runtime must be built with cr-sqlite support.');
358
+ }
359
+ this._crSqliteLoaded = true;
360
+ };
361
+
362
+ Database.prototype.getSiteId = function() {
363
+ this._checkClosed();
364
+ if (!this._crSqliteLoaded) throw new Error('cr-sqlite is not loaded. Call db.enableCrSqlite() first.');
365
+ return this.query('SELECT crsql_site_id() as id').get().id;
366
+ };
367
+
368
+ Database.prototype.getDbVersion = function() {
369
+ this._checkClosed();
370
+ if (!this._crSqliteLoaded) throw new Error('cr-sqlite is not loaded. Call db.enableCrSqlite() first.');
371
+ return this.query('SELECT crsql_db_version() as version').get().version;
372
+ };
373
+
374
+ Database.prototype.markAsCrr = function(tableName) {
375
+ this._checkClosed();
376
+ if (!this._crSqliteLoaded) throw new Error('cr-sqlite is not loaded. Call db.enableCrSqlite() first.');
377
+ this.run("SELECT crsql_as_crr('" + tableName + "')");
378
+ };
379
+
380
+ Database.prototype.getChanges = function(sinceVersion, excludeSiteId) {
381
+ this._checkClosed();
382
+ if (!this._crSqliteLoaded) throw new Error('cr-sqlite is not loaded. Call db.enableCrSqlite() first.');
383
+ sinceVersion = sinceVersion || 0;
384
+ if (excludeSiteId) {
385
+ return this.query(
386
+ 'SELECT "table", "pk", "cid", "val", "col_version", "db_version", "site_id", "cl", "seq" FROM crsql_changes WHERE db_version > ? AND site_id IS NOT ?'
387
+ ).all(sinceVersion, excludeSiteId);
388
+ }
389
+ return this.query(
390
+ 'SELECT "table", "pk", "cid", "val", "col_version", "db_version", "site_id", "cl", "seq" FROM crsql_changes WHERE db_version > ?'
391
+ ).all(sinceVersion);
392
+ };
393
+
394
+ Database.prototype.applyChanges = function(changes) {
395
+ this._checkClosed();
396
+ if (!this._crSqliteLoaded) throw new Error('cr-sqlite is not loaded. Call db.enableCrSqlite() first.');
397
+ var insert = this.prepare(
398
+ 'INSERT INTO crsql_changes ("table", "pk", "cid", "val", "col_version", "db_version", "site_id", "cl", "seq") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)'
399
+ );
400
+ var applyAll = this.transaction(function(changes) {
401
+ for (var i = 0; i < changes.length; i++) {
402
+ var c = changes[i];
403
+ insert.run(c.table, c.pk, c.cid, c.val, c.col_version, c.db_version, c.site_id, c.cl, c.seq);
404
+ }
405
+ });
406
+ try { applyAll(changes); }
407
+ finally { insert.finalize(); }
408
+ };
409
+
410
+ // Static methods
411
+ Database.open = function(filename, options) {
412
+ return new Database(filename, options);
413
+ };
414
+
415
+ Database.deserialize = function(data, options) {
416
+ if (!g.__exactSqliteDeserialize) throw new Error('Database deserialization not supported');
417
+ var isReadOnly = typeof options === 'boolean' ? options : (options && options.readonly) || false;
418
+ var handle = g.__exactSqliteDeserialize(data, isReadOnly);
419
+ var db = Object.create(Database.prototype);
420
+ db._handle = handle;
421
+ db._closed = false;
422
+ db._queryCache = {};
423
+ db._options = typeof options === 'object' ? options : { readonly: isReadOnly };
424
+ db.filename = ':memory:';
425
+ db._crSqliteLoaded = false;
426
+ return db;
427
+ };
428
+
429
+ // ============================================================================
430
+ // Exports
431
+ // ============================================================================
432
+
433
+ module.exports = Database;
434
+ module.exports.Database = Database;
435
+ module.exports.Statement = Statement;
436
+ module.exports.constants = constants;
437
+ module.exports.SQLiteError = SQLiteError;
438
+ module.exports.default = Database;