@dolthub/doltlite-wasm 0.11.16

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.
@@ -0,0 +1,35 @@
1
+ /*
2
+ 2022-05-23
3
+
4
+ The author disclaims copyright to this source code. In place of a
5
+ legal notice, here is a blessing:
6
+
7
+ * May you do good and not evil.
8
+ * May you find forgiveness for yourself and forgive others.
9
+ * May you share freely, never taking more than you give.
10
+
11
+ ***********************************************************************
12
+
13
+ This is a JS Worker file for the main sqlite3 api. It loads
14
+ sqlite3.js, initializes the module, and postMessage()'s a message
15
+ after the module is initialized:
16
+
17
+ {type: 'sqlite3-api', result: 'worker1-ready'}
18
+
19
+ This seemingly superfluous level of indirection is necessary when
20
+ loading sqlite3.js via a Worker. Instantiating a worker with new
21
+ Worker("sqlite.js") will not (cannot) call sqlite3InitModule() to
22
+ initialize the module due to a timing/order-of-operations conflict
23
+ (and that symbol is not exported in a way that a Worker loading it
24
+ that way can see it). Thus JS code wanting to load the sqlite3
25
+ Worker-specific API needs to pass _this_ file (or equivalent) to the
26
+ Worker constructor and then listen for an event in the form shown
27
+ above in order to know when the module has completed initialization.
28
+
29
+ This file accepts a URL arguments to adjust how it loads sqlite3.js:
30
+
31
+ - `sqlite3.dir`, if set, treats the given directory name as the
32
+ directory from which `sqlite3.js` will be loaded.
33
+ */
34
+ import sqlite3InitModule from './sqlite3-bundler-friendly.mjs';
35
+ sqlite3InitModule().then(sqlite3 => sqlite3.initWorker1API());
@@ -0,0 +1,320 @@
1
+ /*
2
+ 2022-08-24
3
+
4
+ The author disclaims copyright to this source code. In place of a
5
+ legal notice, here is a blessing:
6
+
7
+ * May you do good and not evil.
8
+ * May you find forgiveness for yourself and forgive others.
9
+ * May you share freely, never taking more than you give.
10
+
11
+ ***********************************************************************
12
+
13
+ This file implements a Promise-based proxy for the sqlite3 Worker
14
+ API #1. It is intended to be included either from the main thread or
15
+ a Worker, but only if (A) the environment supports nested Workers
16
+ and (B) it's _not_ a Worker which loads the sqlite3 WASM/JS
17
+ module. This file's features will load that module and provide a
18
+ slightly simpler client-side interface than the slightly-lower-level
19
+ Worker API does.
20
+
21
+ In non-ESM builds this file necessarily exposes one global symbol,
22
+ but clients may freely `delete` that symbol after calling it.
23
+ */
24
+ /**
25
+ Configures an sqlite3 Worker API #1 Worker such that it can be
26
+ manipulated via a Promise-based interface and returns a factory
27
+ function which returns Promises for communicating with the worker.
28
+ This proxy has an _almost_ identical interface to the normal
29
+ worker API, with any exceptions documented below.
30
+
31
+ It requires a configuration object with the following properties:
32
+
33
+ - `worker` (required): a Worker instance which loads
34
+ `sqlite3-worker1.js` or a functional equivalent. Note that the
35
+ promiser factory replaces the worker.onmessage property. This
36
+ config option may alternately be a function, in which case this
37
+ function re-assigns this property with the result of calling that
38
+ function, enabling delayed instantiation of a Worker.
39
+
40
+ - `onready` (optional, but...): this callback is called with no
41
+ arguments when the worker fires its initial
42
+ 'sqlite3-api'/'worker1-ready' message, which it does when
43
+ sqlite3.initWorker1API() completes its initialization. This is the
44
+ simplest way to tell the worker to kick off work at the earliest
45
+ opportunity, and the only way to know when the worker module has
46
+ completed loading. The irony of using a callback for this, instead
47
+ of returning a promise from sqlite3Worker1Promiser() is not lost on
48
+ the developers: see sqlite3Worker1Promiser.v2() which uses a
49
+ Promise instead.
50
+
51
+ - `onunhandled` (optional): a callback which gets passed the
52
+ message event object for any worker.onmessage() events which
53
+ are not handled by this proxy. Ideally that "should" never
54
+ happen, as this proxy aims to handle all known message types.
55
+
56
+ - `generateMessageId` (optional): a function which, when passed an
57
+ about-to-be-posted message object, generates a _unique_ message ID
58
+ for the message, which this API then assigns as the messageId
59
+ property of the message. It _must_ generate unique IDs on each call
60
+ so that dispatching can work. If not defined, a default generator
61
+ is used (which should be sufficient for most or all cases).
62
+
63
+ - `debug` (optional): a console.debug()-style function for logging
64
+ information about messages.
65
+
66
+ This function returns a stateful factory function with the
67
+ following interfaces:
68
+
69
+ - Promise function(messageType, messageArgs)
70
+ - Promise function({message object})
71
+
72
+ The first form expects the "type" and "args" values for a Worker
73
+ message. The second expects an object in the form {type:...,
74
+ args:...} plus any other properties the client cares to set. This
75
+ function will always set the `messageId` property on the object,
76
+ even if it's already set, and will set the `dbId` property to the
77
+ current database ID if it is _not_ set in the message object.
78
+
79
+ The function throws on error.
80
+
81
+ The function installs a temporary message listener, posts a
82
+ message to the configured Worker, and handles the message's
83
+ response via the temporary message listener. The then() callback
84
+ of the returned Promise is passed the `message.data` property from
85
+ the resulting message, i.e. the payload from the worker, stripped
86
+ of the lower-level event state which the onmessage() handler
87
+ receives.
88
+
89
+ Example usage:
90
+
91
+ ```
92
+ const config = {...};
93
+ const sq3Promiser = sqlite3Worker1Promiser(config);
94
+ sq3Promiser('open', {filename:"/foo.db"}).then(function(msg){
95
+ console.log("open response",msg); // => {type:'open', result: {filename:'/foo.db'}, ...}
96
+ });
97
+ sq3Promiser({type:'close'}).then((msg)=>{
98
+ console.log("close response",msg); // => {type:'close', result: {filename:'/foo.db'}, ...}
99
+ });
100
+ ```
101
+
102
+ Differences from Worker API #1:
103
+
104
+ - exec's {callback: STRING} option does not work via this
105
+ interface (it triggers an exception), but {callback: function}
106
+ does and works exactly like the STRING form does in the Worker:
107
+ the callback is called one time for each row of the result set,
108
+ passed the same worker message format as the worker API emits:
109
+
110
+ {
111
+ type:typeString,
112
+ row:VALUE,
113
+ rowNumber:1-based-#,
114
+ columnNames: array
115
+ }
116
+
117
+ Where `typeString` is an internally-synthesized message type string
118
+ used temporarily for worker message dispatching. It can be ignored
119
+ by all client code except that which tests this API. The `row`
120
+ property contains the row result in the form implied by the
121
+ `rowMode` option (defaulting to `'array'`). The `rowNumber` is a
122
+ 1-based integer value incremented by 1 on each call into the
123
+ callback.
124
+
125
+ At the end of the result set, the same event is fired with
126
+ (row=undefined, rowNumber=null) to indicate that the end of the
127
+ result set has been reached. The rows arrive via worker-posted
128
+ messages, with all the implications of that.
129
+
130
+ Notable shortcomings:
131
+
132
+ - "v1" of this this API is not suitable for use as an ESM module
133
+ because ESM worker modules were not widely supported when it was
134
+ developed. For use as an ESM module, see the "v2" interface later
135
+ on in this file.
136
+ */
137
+ globalThis.sqlite3Worker1Promiser = function callee(config = callee.defaultConfig){
138
+ // Inspired by: https://stackoverflow.com/a/52439530
139
+ if(1===arguments.length && 'function'===typeof arguments[0]){
140
+ const f = config;
141
+ config = Object.assign(Object.create(null), callee.defaultConfig);
142
+ config.onready = f;
143
+ }else{
144
+ config = Object.assign(Object.create(null), callee.defaultConfig, config);
145
+ }
146
+ const handlerMap = Object.create(null);
147
+ const noop = function(){};
148
+ const err = config.onerror
149
+ || noop /* config.onerror is intentionally undocumented
150
+ pending finding a less ambiguous name */;
151
+ const debug = config.debug || noop;
152
+ const idTypeMap = config.generateMessageId ? undefined : Object.create(null);
153
+ const genMsgId = config.generateMessageId || function(msg){
154
+ return msg.type+'#'+(idTypeMap[msg.type] = (idTypeMap[msg.type]||0) + 1);
155
+ };
156
+ const toss = (...args)=>{throw new Error(args.join(' '))};
157
+ if(!config.worker) config.worker = callee.defaultConfig.worker;
158
+ if('function'===typeof config.worker) config.worker = config.worker();
159
+ let dbId;
160
+ let promiserFunc;
161
+ config.worker.onmessage = function(ev){
162
+ ev = ev.data;
163
+ debug('worker1.onmessage',ev);
164
+ let msgHandler = handlerMap[ev.messageId];
165
+ if(!msgHandler){
166
+ if(ev && 'sqlite3-api'===ev.type && 'worker1-ready'===ev.result) {
167
+ /*fired one time when the Worker1 API initializes*/
168
+ if(config.onready) config.onready(promiserFunc);
169
+ return;
170
+ }
171
+ msgHandler = handlerMap[ev.type] /* check for exec per-row callback */;
172
+ if(msgHandler && msgHandler.onrow){
173
+ msgHandler.onrow(ev);
174
+ return;
175
+ }
176
+ if(config.onunhandled) config.onunhandled(arguments[0]);
177
+ else err("sqlite3Worker1Promiser() unhandled worker message:",ev);
178
+ return;
179
+ }
180
+ delete handlerMap[ev.messageId];
181
+ switch(ev.type){
182
+ case 'error':
183
+ msgHandler.reject(ev);
184
+ return;
185
+ case 'open':
186
+ if(!dbId) dbId = ev.dbId;
187
+ break;
188
+ case 'close':
189
+ if(ev.dbId===dbId) dbId = undefined;
190
+ break;
191
+ default:
192
+ break;
193
+ }
194
+ try {msgHandler.resolve(ev)}
195
+ catch(e){msgHandler.reject(e)}
196
+ }/*worker.onmessage()*/;
197
+ return promiserFunc = function(/*(msgType, msgArgs) || (msgEnvelope)*/){
198
+ let msg;
199
+ if(1===arguments.length){
200
+ msg = arguments[0];
201
+ }else if(2===arguments.length){
202
+ msg = Object.create(null);
203
+ msg.type = arguments[0];
204
+ msg.args = arguments[1];
205
+ msg.dbId = msg.args.dbId;
206
+ }else{
207
+ toss("Invalid arguments for sqlite3Worker1Promiser()-created factory.");
208
+ }
209
+ if(!msg.dbId && msg.type!=='open') msg.dbId = dbId;
210
+ msg.messageId = genMsgId(msg);
211
+ msg.departureTime = performance.now();
212
+ const proxy = Object.create(null);
213
+ proxy.message = msg;
214
+ let rowCallbackId /* message handler ID for exec on-row callback proxy */;
215
+ if('exec'===msg.type && msg.args){
216
+ if('function'===typeof msg.args.callback){
217
+ rowCallbackId = msg.messageId+':row';
218
+ proxy.onrow = msg.args.callback;
219
+ msg.args.callback = rowCallbackId;
220
+ handlerMap[rowCallbackId] = proxy;
221
+ }else if('string' === typeof msg.args.callback){
222
+ toss("exec callback may not be a string when using the Promise interface.");
223
+ /**
224
+ Design note: the reason for this limitation is that this
225
+ API takes over worker.onmessage() and the client has no way
226
+ of adding their own message-type handlers to it. Per-row
227
+ callbacks are implemented as short-lived message.type
228
+ mappings for worker.onmessage().
229
+
230
+ We "could" work around this by providing a new
231
+ config.fallbackMessageHandler (or some such) which contains
232
+ a map of event type names to callbacks. Seems like overkill
233
+ for now, seeing as the client can pass callback functions
234
+ to this interface (whereas the string-form "callback" is
235
+ needed for the over-the-Worker interface).
236
+ */
237
+ }
238
+ }
239
+ //debug("requestWork", msg);
240
+ let p = new Promise(function(resolve, reject){
241
+ proxy.resolve = resolve;
242
+ proxy.reject = reject;
243
+ handlerMap[msg.messageId] = proxy;
244
+ debug("Posting",msg.type,"message to Worker dbId="+(dbId||'default')+':',msg);
245
+ config.worker.postMessage(msg);
246
+ });
247
+ if(rowCallbackId) p = p.finally(()=>delete handlerMap[rowCallbackId]);
248
+ return p;
249
+ };
250
+ }/*sqlite3Worker1Promiser()*/;
251
+
252
+ globalThis.sqlite3Worker1Promiser.defaultConfig = {
253
+ worker: function(){
254
+ return new Worker(new URL("sqlite3-worker1.mjs", import.meta.url),{
255
+ type: 'module'
256
+ });
257
+ }
258
+ ,
259
+ onerror: (...args)=>console.error('sqlite3Worker1Promiser():',...args)
260
+ }/*defaultConfig*/;
261
+
262
+ /**
263
+ sqlite3Worker1Promiser.v2(), added in 3.46, works identically to
264
+ sqlite3Worker1Promiser() except that it returns a Promise instead
265
+ of relying an an onready callback in the config object. The Promise
266
+ resolves to the same factory function which
267
+ sqlite3Worker1Promiser() returns.
268
+
269
+ If config is-a function or is an object which contains an onready
270
+ function, that function is replaced by a proxy which will resolve
271
+ after calling the original function and will reject if that
272
+ function throws.
273
+ */
274
+ globalThis.sqlite3Worker1Promiser.v2 = function callee(config = callee.defaultConfig){
275
+ let oldFunc;
276
+ if( 'function' == typeof config ){
277
+ oldFunc = config;
278
+ config = {};
279
+ }else if('function'===typeof config?.onready){
280
+ oldFunc = config.onready;
281
+ delete config.onready;
282
+ }
283
+ const promiseProxy = Object.create(null);
284
+ config = Object.assign((config || Object.create(null)),{
285
+ onready: async function(func){
286
+ try {
287
+ if( oldFunc ) await oldFunc(func);
288
+ promiseProxy.resolve(func);
289
+ }
290
+ catch(e){promiseProxy.reject(e)}
291
+ }
292
+ });
293
+ const p = new Promise(function(resolve,reject){
294
+ promiseProxy.resolve = resolve;
295
+ promiseProxy.reject = reject;
296
+ });
297
+ try{
298
+ this.original(config);
299
+ }catch(e){
300
+ promiseProxy.reject(e);
301
+ }
302
+ return p;
303
+ }.bind({
304
+ /* We do this because clients are recommended to delete
305
+ globalThis.sqlite3Worker1Promiser. */
306
+ original: sqlite3Worker1Promiser
307
+ });
308
+
309
+ globalThis.sqlite3Worker1Promiser.v2.defaultConfig =
310
+ globalThis.sqlite3Worker1Promiser.defaultConfig;
311
+
312
+ /**
313
+ When built as a module, we export sqlite3Worker1Promiser.v2()
314
+ instead of sqlite3Worker1Promise() because (A) its interface is more
315
+ conventional for ESM usage and (B) the ESM export option for this
316
+ API did not exist until v2 was created, so there's no backwards
317
+ incompatibility.
318
+ */
319
+ export default sqlite3Worker1Promiser.v2;
320
+ delete globalThis.sqlite3Worker1Promiser;
@@ -0,0 +1,35 @@
1
+ /*
2
+ 2022-05-23
3
+
4
+ The author disclaims copyright to this source code. In place of a
5
+ legal notice, here is a blessing:
6
+
7
+ * May you do good and not evil.
8
+ * May you find forgiveness for yourself and forgive others.
9
+ * May you share freely, never taking more than you give.
10
+
11
+ ***********************************************************************
12
+
13
+ This is a JS Worker file for the main sqlite3 api. It loads
14
+ sqlite3.js, initializes the module, and postMessage()'s a message
15
+ after the module is initialized:
16
+
17
+ {type: 'sqlite3-api', result: 'worker1-ready'}
18
+
19
+ This seemingly superfluous level of indirection is necessary when
20
+ loading sqlite3.js via a Worker. Instantiating a worker with new
21
+ Worker("sqlite.js") will not (cannot) call sqlite3InitModule() to
22
+ initialize the module due to a timing/order-of-operations conflict
23
+ (and that symbol is not exported in a way that a Worker loading it
24
+ that way can see it). Thus JS code wanting to load the sqlite3
25
+ Worker-specific API needs to pass _this_ file (or equivalent) to the
26
+ Worker constructor and then listen for an event in the form shown
27
+ above in order to know when the module has completed initialization.
28
+
29
+ This file accepts a URL arguments to adjust how it loads sqlite3.js:
30
+
31
+ - `sqlite3.dir`, if set, treats the given directory name as the
32
+ directory from which `sqlite3.js` will be loaded.
33
+ */
34
+ import sqlite3InitModule from './sqlite3.mjs';
35
+ sqlite3InitModule().then(sqlite3 => sqlite3.initWorker1API());