4 The author disclaims copyright to this source code. In place of a
5 legal notice, here is a blessing:
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.
11 ***********************************************************************
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
21 This script necessarily exposes one global symbol, but clients may
22 freely `delete` that symbol after calling it.
26 Configures an sqlite3 Worker API #1 Worker such that it can be
27 manipulated via a Promise-based interface and returns a factory
28 function which returns Promises for communicating with the worker.
29 This proxy has an _almost_ identical interface to the normal
30 worker API, with any exceptions documented below.
32 It requires a configuration object with the following properties:
34 - `worker` (required): a Worker instance which loads
35 `sqlite3-worker1.js` or a functional equivalent. Note that the
36 promiser factory replaces the worker.onmessage property. This
37 config option may alternately be a function, in which case this
38 function re-assigns this property with the result of calling that
39 function, enabling delayed instantiation of a Worker.
41 - `onready` (optional, but...): this callback is called with no
42 arguments when the worker fires its initial
43 'sqlite3-api'/'worker1-ready' message, which it does when
44 sqlite3.initWorker1API() completes its initialization. This is
45 the simplest way to tell the worker to kick off work at the
48 - `onunhandled` (optional): a callback which gets passed the
49 message event object for any worker.onmessage() events which
50 are not handled by this proxy. Ideally that "should" never
51 happen, as this proxy aims to handle all known message types.
53 - `generateMessageId` (optional): a function which, when passed an
54 about-to-be-posted message object, generates a _unique_ message ID
55 for the message, which this API then assigns as the messageId
56 property of the message. It _must_ generate unique IDs on each call
57 so that dispatching can work. If not defined, a default generator
58 is used (which should be sufficient for most or all cases).
60 - `debug` (optional): a console.debug()-style function for logging
61 information about messages.
63 This function returns a stateful factory function with the
66 - Promise function(messageType, messageArgs)
67 - Promise function({message object})
69 The first form expects the "type" and "args" values for a Worker
70 message. The second expects an object in the form {type:...,
71 args:...} plus any other properties the client cares to set. This
72 function will always set the `messageId` property on the object,
73 even if it's already set, and will set the `dbId` property to the
74 current database ID if it is _not_ set in the message object.
76 The function throws on error.
78 The function installs a temporary message listener, posts a
79 message to the configured Worker, and handles the message's
80 response via the temporary message listener. The then() callback
81 of the returned Promise is passed the `message.data` property from
82 the resulting message, i.e. the payload from the worker, stripped
83 of the lower-level event state which the onmessage() handler
90 const sq3Promiser = sqlite3Worker1Promiser(config);
91 sq3Promiser('open', {filename:"/foo.db"}).then(function(msg){
92 console.log("open response",msg); // => {type:'open', result: {filename:'/foo.db'}, ...}
94 sq3Promiser({type:'close'}).then((msg)=>{
95 console.log("close response",msg); // => {type:'close', result: {filename:'/foo.db'}, ...}
99 Differences from Worker API #1:
101 - exec's {callback: STRING} option does not work via this
102 interface (it triggers an exception), but {callback: function}
103 does and works exactly like the STRING form does in the Worker:
104 the callback is called one time for each row of the result set,
105 passed the same worker message format as the worker API emits:
112 Where `typeString` is an internally-synthesized message type string
113 used temporarily for worker message dispatching. It can be ignored
114 by all client code except that which tests this API. The `row`
115 property contains the row result in the form implied by the
116 `rowMode` option (defaulting to `'array'`). The `rowNumber` is a
117 1-based integer value incremented by 1 on each call into the
120 At the end of the result set, the same event is fired with
121 (row=undefined, rowNumber=null) to indicate that
122 the end of the result set has been reached. Note that the rows
123 arrive via worker-posted messages, with all the implications
126 Notable shortcomings:
128 - This API was not designed with ES6 modules in mind. Neither Firefox
129 nor Safari support, as of March 2023, the {type:"module"} flag to the
130 Worker constructor, so that particular usage is not something we're going
131 to target for the time being:
133 https://developer.mozilla.org/en-US/docs/Web/API/Worker/Worker
135 globalThis
.sqlite3Worker1Promiser
= function callee(config
= callee
.defaultConfig
){
136 // Inspired by: https://stackoverflow.com/a/52439530
137 if(1===arguments
.length
&& 'function'===typeof arguments
[0]){
139 config
= Object
.assign(Object
.create(null), callee
.defaultConfig
);
142 config
= Object
.assign(Object
.create(null), callee
.defaultConfig
, config
);
144 const handlerMap
= Object
.create(null);
145 const noop = function(){};
146 const err
= config
.onerror
147 || noop
/* config.onerror is intentionally undocumented
148 pending finding a less ambiguous name */;
149 const debug
= config
.debug
|| noop
;
150 const idTypeMap
= config
.generateMessageId
? undefined : Object
.create(null);
151 const genMsgId
= config
.generateMessageId
|| function(msg
){
152 return msg
.type
+'#'+(idTypeMap
[msg
.type
] = (idTypeMap
[msg
.type
]||0) + 1);
154 const toss
= (...args
)=>{throw new Error(args
.join(' '))};
155 if(!config
.worker
) config
.worker
= callee
.defaultConfig
.worker
;
156 if('function'===typeof config
.worker
) config
.worker
= config
.worker();
158 config
.worker
.onmessage = function(ev
){
160 debug('worker1.onmessage',ev
);
161 let msgHandler
= handlerMap
[ev
.messageId
];
163 if(ev
&& 'sqlite3-api'===ev
.type
&& 'worker1-ready'===ev
.result
) {
164 /*fired one time when the Worker1 API initializes*/
165 if(config
.onready
) config
.onready();
168 msgHandler
= handlerMap
[ev
.type
] /* check for exec per-row callback */;
169 if(msgHandler
&& msgHandler
.onrow
){
170 msgHandler
.onrow(ev
);
173 if(config
.onunhandled
) config
.onunhandled(arguments
[0]);
174 else err("sqlite3Worker1Promiser() unhandled worker message:",ev
);
177 delete handlerMap
[ev
.messageId
];
180 msgHandler
.reject(ev
);
183 if(!dbId
) dbId
= ev
.dbId
;
186 if(ev
.dbId
===dbId
) dbId
= undefined;
191 try {msgHandler
.resolve(ev
)}
192 catch(e
){msgHandler
.reject(e
)}
193 }/*worker.onmessage()*/;
194 return function(/*(msgType, msgArgs) || (msgEnvelope)*/){
196 if(1===arguments
.length
){
198 }else if(2===arguments
.length
){
204 toss("Invalid arugments for sqlite3Worker1Promiser()-created factory.");
206 if(!msg
.dbId
) msg
.dbId
= dbId
;
207 msg
.messageId
= genMsgId(msg
);
208 msg
.departureTime
= performance
.now();
209 const proxy
= Object
.create(null);
211 let rowCallbackId
/* message handler ID for exec on-row callback proxy */;
212 if('exec'===msg
.type
&& msg
.args
){
213 if('function'===typeof msg
.args
.callback
){
214 rowCallbackId
= msg
.messageId
+':row';
215 proxy
.onrow
= msg
.args
.callback
;
216 msg
.args
.callback
= rowCallbackId
;
217 handlerMap
[rowCallbackId
] = proxy
;
218 }else if('string' === typeof msg
.args
.callback
){
219 toss("exec callback may not be a string when using the Promise interface.");
221 Design note: the reason for this limitation is that this
222 API takes over worker.onmessage() and the client has no way
223 of adding their own message-type handlers to it. Per-row
224 callbacks are implemented as short-lived message.type
225 mappings for worker.onmessage().
227 We "could" work around this by providing a new
228 config.fallbackMessageHandler (or some such) which contains
229 a map of event type names to callbacks. Seems like overkill
230 for now, seeing as the client can pass callback functions
231 to this interface (whereas the string-form "callback" is
232 needed for the over-the-Worker interface).
236 //debug("requestWork", msg);
237 let p
= new Promise(function(resolve
, reject
){
238 proxy
.resolve
= resolve
;
239 proxy
.reject
= reject
;
240 handlerMap
[msg
.messageId
] = proxy
;
241 debug("Posting",msg
.type
,"message to Worker dbId="+(dbId
||'default')+':',msg
);
242 config
.worker
.postMessage(msg
);
244 if(rowCallbackId
) p
= p
.finally(()=>delete handlerMap
[rowCallbackId
]);
247 }/*sqlite3Worker1Promiser()*/;
248 globalThis
.sqlite3Worker1Promiser
.defaultConfig
= {
250 //#if target=es6-bundler-friendly
251 return new Worker("sqlite3-worker1-bundler-friendly.mjs",{
252 type
: 'module' /* Noting that neither Firefox nor Safari suppor this,
253 as of this writing. */
256 let theJs
= "sqlite3-worker1.js";
257 if(this.currentScript
){
258 const src
= this.currentScript
.src
.split('/');
260 theJs
= src
.join('/')+'/' + theJs
;
261 //sqlite3.config.warn("promiser currentScript, theJs =",this.currentScript,theJs);
262 }else if(globalThis
.location
){
263 //sqlite3.config.warn("promiser globalThis.location =",globalThis.location);
264 const urlParams
= new URL(globalThis
.location
.href
).searchParams
;
265 if(urlParams
.has('sqlite3.dir')){
266 theJs
= urlParams
.get('sqlite3.dir') + '/' + theJs
;
269 return new Worker(theJs
+ globalThis
.location
.search
);
272 currentScript
: globalThis
?.document
?.currentScript
274 onerror
: (...args
)=>console
.error('worker1 promiser error',...args
)