node-bible-sync 0.0.0-stage → 0.3.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.
@@ -0,0 +1,433 @@
1
+ /* This file is part of node-bible-sync.
2
+
3
+ Copyright (C) 2026 Tobias Klein <contact@tklein.info>
4
+
5
+ node-bible-sync is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU General Public License as published by
7
+ the Free Software Foundation, either version 2 of the License, or
8
+ (at your option) any later version.
9
+
10
+ node-bible-sync is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13
+ See the GNU General Public License for more details.
14
+
15
+ You should have received a copy of the GNU General Public License
16
+ along with node-bible-sync. See the file COPYING.
17
+ If not, see <http://www.gnu.org/licenses/>. */
18
+
19
+ #include "biblesync_session.hpp"
20
+
21
+ #include <chrono>
22
+ #include <utility>
23
+ #include <biblesync.hh>
24
+ #undef min
25
+
26
+ std::mutex BibleSyncSession::activeMutex_;
27
+ BibleSyncSession *BibleSyncSession::active_ = nullptr;
28
+ thread_local BibleSyncSession *BibleSyncSession::current_ = nullptr;
29
+ thread_local int node_bible_sync_uuid_error = 0;
30
+
31
+ static bool packetFits(const std::string& application, const std::string& version,
32
+ const std::string& user, const std::string& passphrase, const std::string& device,
33
+ const std::string& bible, const std::string& reference,
34
+ const std::string& alternate, const std::string& group,
35
+ const std::string& domain)
36
+ {
37
+ const std::pair<std::string, std::string> fields[] = {
38
+ {BSP_APP_NAME, application}, {BSP_APP_VERSION, version},
39
+ {BSP_APP_INSTANCE_UUID, std::string(36, '0')}, {BSP_APP_OS, BSP_OS},
40
+ {BSP_APP_DEVICE, device}, {BSP_APP_USER, user}, {BSP_MSG_PASSPHRASE, passphrase},
41
+ {BSP_MSG_SYNC_BIBLEABBREV, bible}, {BSP_MSG_SYNC_DOMAIN, domain},
42
+ {BSP_MSG_SYNC_GROUP, group}, {BSP_MSG_SYNC_ALTVERSE, alternate},
43
+ {BSP_MSG_SYNC_VERSE, reference}
44
+ };
45
+ size_t size = 0;
46
+ for (const auto& field : fields) size += field.first.size() + field.second.size() + 2;
47
+ return size <= BSP_MAX_PAYLOAD;
48
+ }
49
+
50
+ Napi::Object BibleSyncSession::Init(Napi::Env env, Napi::Object exports)
51
+ {
52
+ Napi::Function constructor = DefineClass(env, "BibleSyncSession", {
53
+ InstanceMethod("start", &BibleSyncSession::Start),
54
+ InstanceMethod("enqueue", &BibleSyncSession::Enqueue)
55
+ });
56
+ exports.Set("BibleSyncSession", constructor);
57
+ return exports;
58
+ }
59
+
60
+ BibleSyncSession::BibleSyncSession(const Napi::CallbackInfo& info)
61
+ : Napi::ObjectWrap<BibleSyncSession>(info)
62
+ {
63
+ Napi::Env env = info.Env();
64
+ if (info.Length() != 2 || !info[0].IsObject() || !info[1].IsFunction()) {
65
+ Napi::TypeError::New(env, "BibleSyncSession requires options and a callback").ThrowAsJavaScriptException();
66
+ return;
67
+ }
68
+ Napi::Object options = info[0].As<Napi::Object>();
69
+ if (!options.Get("application").IsString() || !options.Get("version").IsString() ||
70
+ !options.Get("user").IsString() || !options.Get("passphrase").IsString()) {
71
+ Napi::TypeError::New(env, "BibleSync identification fields must be strings").ThrowAsJavaScriptException();
72
+ return;
73
+ }
74
+ application_ = options.Get("application").As<Napi::String>().Utf8Value();
75
+ version_ = options.Get("version").As<Napi::String>().Utf8Value();
76
+ user_ = options.Get("user").As<Napi::String>().Utf8Value();
77
+ passphrase_ = options.Get("passphrase").As<Napi::String>().Utf8Value();
78
+ callback_ = Napi::Persistent(info[1].As<Napi::Function>());
79
+ callback_.Unref();
80
+ if (napi_add_env_cleanup_hook(env, Cleanup, this) != napi_ok) {
81
+ Napi::Error::New(env, "Unable to register BibleSync environment cleanup").ThrowAsJavaScriptException();
82
+ return;
83
+ }
84
+ cleanupRegistered_ = true;
85
+ }
86
+
87
+ BibleSyncSession::~BibleSyncSession()
88
+ {
89
+ if (cleanupRegistered_ && !cleanupCalled_) napi_remove_env_cleanup_hook(Env(), Cleanup, this);
90
+ Shutdown();
91
+ }
92
+
93
+ void BibleSyncSession::Cleanup(void *data)
94
+ {
95
+ BibleSyncSession *session = static_cast<BibleSyncSession *>(data);
96
+ session->cleanupCalled_ = true;
97
+ session->Shutdown();
98
+ }
99
+
100
+ void BibleSyncSession::Shutdown()
101
+ {
102
+ {
103
+ std::lock_guard<std::mutex> lock(mutex_);
104
+ closing_ = true;
105
+ }
106
+ wake_.notify_one();
107
+ if (thread_.joinable()) thread_.join();
108
+ }
109
+
110
+ Napi::Value BibleSyncSession::Start(const Napi::CallbackInfo& info)
111
+ {
112
+ Napi::Env env = info.Env();
113
+ if (info.Length() != 2 || !info[0].IsString() || !info[1].IsString()) {
114
+ Napi::TypeError::New(env, "start requires a command ID and mode").ThrowAsJavaScriptException();
115
+ return env.Undefined();
116
+ }
117
+ const std::string mode = info[1].As<Napi::String>().Utf8Value();
118
+ if (mode != "personal" && mode != "speaker" && mode != "audience") {
119
+ Napi::TypeError::New(env, "Invalid BibleSync mode").ThrowAsJavaScriptException();
120
+ return env.Undefined();
121
+ }
122
+ {
123
+ std::lock_guard<std::mutex> lock(activeMutex_);
124
+ if (active_) {
125
+ Napi::Error::New(env, "A BibleSync session is already active").ThrowAsJavaScriptException();
126
+ return env.Undefined();
127
+ }
128
+ }
129
+ if (thread_.joinable()) thread_.join();
130
+ {
131
+ std::lock_guard<std::mutex> lock(activeMutex_);
132
+ if (active_) {
133
+ Napi::Error::New(env, "A BibleSync session is already active").ThrowAsJavaScriptException();
134
+ return env.Undefined();
135
+ }
136
+ active_ = this;
137
+ }
138
+ {
139
+ std::lock_guard<std::mutex> lock(mutex_);
140
+ closing_ = false;
141
+ commands_.clear();
142
+ }
143
+ overflow_ = false;
144
+ suppressEvents_ = false;
145
+ fatalError_.clear();
146
+ pending_.reset(new std::atomic<unsigned>(0));
147
+ tsfn_ = Napi::ThreadSafeFunction::New(env, callback_.Value(), "BibleSync events", 0, 1);
148
+ if (static_cast<napi_threadsafe_function>(tsfn_) == nullptr) {
149
+ std::lock_guard<std::mutex> lock(activeMutex_);
150
+ active_ = nullptr;
151
+ return env.Undefined();
152
+ }
153
+ thread_ = std::thread(&BibleSyncSession::Run, this,
154
+ info[0].As<Napi::String>().Utf8Value(), mode);
155
+ return env.Undefined();
156
+ }
157
+
158
+ Napi::Value BibleSyncSession::Enqueue(const Napi::CallbackInfo& info)
159
+ {
160
+ Napi::Env env = info.Env();
161
+ if (info.Length() != 3 || !info[0].IsString() || !info[1].IsString() || !info[2].IsObject()) {
162
+ Napi::TypeError::New(env, "enqueue requires an ID, command and arguments").ThrowAsJavaScriptException();
163
+ return env.Undefined();
164
+ }
165
+ Command command;
166
+ command.id = info[0].As<Napi::String>().Utf8Value();
167
+ command.type = info[1].As<Napi::String>().Utf8Value();
168
+ Napi::Object args = info[2].As<Napi::Object>();
169
+ if (command.type == "listen") {
170
+ if (!args.Get("speakerId").IsString() || !args.Get("listening").IsBoolean()) {
171
+ Napi::TypeError::New(env, "listen requires a speaker ID and boolean").ThrowAsJavaScriptException();
172
+ return env.Undefined();
173
+ }
174
+ command.speakerId = args.Get("speakerId").As<Napi::String>().Utf8Value();
175
+ command.listening = args.Get("listening").As<Napi::Boolean>().Value();
176
+ } else if (command.type == "send") {
177
+ if (!args.Get("bible").IsString() || !args.Get("reference").IsString() ||
178
+ !args.Get("alternateReference").IsString() || !args.Get("group").IsString() ||
179
+ !args.Get("domain").IsString()) {
180
+ Napi::TypeError::New(env, "send requires string navigation fields").ThrowAsJavaScriptException();
181
+ return env.Undefined();
182
+ }
183
+ command.bible = args.Get("bible").As<Napi::String>().Utf8Value();
184
+ command.reference = args.Get("reference").As<Napi::String>().Utf8Value();
185
+ command.alternateReference = args.Get("alternateReference").As<Napi::String>().Utf8Value();
186
+ command.group = args.Get("group").As<Napi::String>().Utf8Value();
187
+ command.domain = args.Get("domain").As<Napi::String>().Utf8Value();
188
+ } else if (command.type != "stop") {
189
+ Napi::Error::New(env, "Unknown BibleSync command").ThrowAsJavaScriptException();
190
+ return env.Undefined();
191
+ }
192
+ {
193
+ std::lock_guard<std::mutex> lock(activeMutex_);
194
+ if (active_ != this) {
195
+ Napi::Error::New(env, "BibleSync session is not running").ThrowAsJavaScriptException();
196
+ return env.Undefined();
197
+ }
198
+ }
199
+ {
200
+ std::lock_guard<std::mutex> lock(mutex_);
201
+ if (closing_ || (commands_.size() >= 128 && command.type != "stop")) {
202
+ Napi::Error::New(env, "BibleSync is stopping or its command queue is full").ThrowAsJavaScriptException();
203
+ return env.Undefined();
204
+ }
205
+ commands_.push_back(command);
206
+ if (command.type == "stop") closing_ = true;
207
+ }
208
+ wake_.notify_one();
209
+ return env.Undefined();
210
+ }
211
+
212
+ void BibleSyncSession::Emit(Message message, bool countEvent)
213
+ {
214
+ if (countEvent && pending_->fetch_add(1) >= 256) {
215
+ pending_->fetch_sub(1);
216
+ if (!overflow_) {
217
+ overflow_ = true;
218
+ fatalError_ = "BibleSync event queue overflow; session stopped";
219
+ }
220
+ return;
221
+ }
222
+ message.counted = countEvent;
223
+ message.pending = pending_;
224
+ Message *data = new Message(std::move(message));
225
+ napi_status status = tsfn_.NonBlockingCall(data, [](Napi::Env env, Napi::Function callback, Message *event) {
226
+ std::unique_ptr<Message> holder(event);
227
+ if (event->counted) event->pending->fetch_sub(1);
228
+ if (static_cast<napi_env>(env) == nullptr) return;
229
+ Napi::Object object = Napi::Object::New(env);
230
+ object.Set("type", event->type);
231
+ object.Set("id", event->id);
232
+ object.Set("error", event->error);
233
+ object.Set("speakerId", event->speakerId);
234
+ object.Set("bible", event->bible);
235
+ object.Set("reference", event->reference);
236
+ object.Set("alternateReference", event->alternateReference);
237
+ object.Set("group", event->group);
238
+ object.Set("domain", event->domain);
239
+ object.Set("user", event->user);
240
+ object.Set("address", event->address);
241
+ object.Set("application", event->application);
242
+ object.Set("device", event->device);
243
+ object.Set("listening", event->listening);
244
+ callback.Call({object});
245
+ });
246
+ if (status != napi_ok) {
247
+ if (data->counted) data->pending->fetch_sub(1);
248
+ delete data;
249
+ }
250
+ }
251
+
252
+ void BibleSyncSession::Callback(char cmd, std::string speakerId, std::string bible,
253
+ std::string ref, std::string alt, std::string group,
254
+ std::string domain, std::string info, std::string dump)
255
+ {
256
+ if (current_) current_->OnEvent(cmd, speakerId, bible, ref, alt, group, domain, info, dump);
257
+ }
258
+
259
+ void BibleSyncSession::OnEvent(char cmd, const std::string& speakerId, const std::string& bible,
260
+ const std::string& ref, const std::string& alt,
261
+ const std::string& group, const std::string& domain,
262
+ const std::string& info, const std::string& dump)
263
+ {
264
+ if (suppressEvents_) return;
265
+ if (cmd == 'E' && starting_) {
266
+ startupError_ = info + (dump.empty() ? "" : ": " + dump);
267
+ return;
268
+ }
269
+ Message event;
270
+ event.speakerId = speakerId;
271
+ if (cmd == 'S') {
272
+ sync_->listenToSpeaker(false, speakerId);
273
+ speakers_[speakerId] = false;
274
+ event.type = "speaker";
275
+ event.user = bible;
276
+ event.address = ref;
277
+ event.application = group;
278
+ event.device = domain;
279
+ } else if (cmd == 'D') {
280
+ speakers_.erase(speakerId);
281
+ event.type = "speakerRemoved";
282
+ } else if (cmd == 'N') {
283
+ event.type = "navigation";
284
+ event.bible = bible;
285
+ event.reference = ref;
286
+ event.alternateReference = alt;
287
+ event.group = group;
288
+ event.domain = domain;
289
+ } else if (cmd == 'A') {
290
+ event.type = "presence";
291
+ event.user = bible;
292
+ event.address = ref;
293
+ event.application = group;
294
+ event.device = domain;
295
+ } else if (cmd == 'E') {
296
+ event.type = "error";
297
+ event.error = info;
298
+ } else if (cmd == 'M') {
299
+ event.type = "diagnostic";
300
+ event.error = info;
301
+ } else {
302
+ return;
303
+ }
304
+ Emit(std::move(event));
305
+ }
306
+
307
+ void BibleSyncSession::Run(std::string id, std::string mode)
308
+ {
309
+ current_ = this;
310
+ BibleSync sync(application_, version_, user_);
311
+ sync_ = &sync;
312
+ starting_ = true;
313
+ startupError_.clear();
314
+ BibleSync_mode nativeMode = mode == "personal" ? BSP_MODE_PERSONAL
315
+ : mode == "speaker" ? BSP_MODE_SPEAKER : BSP_MODE_AUDIENCE;
316
+ if (node_bible_sync_uuid_error != 0) {
317
+ startupError_ = "BibleSync could not generate a secure UUID (error "
318
+ + std::to_string(node_bible_sync_uuid_error) + ")";
319
+ } else
320
+ if (!packetFits(application_, version_, user_, passphrase_, sync.getDevice(), "KJV", "Gen.1.1", "", "1", "BIBLE-VERSE")) {
321
+ startupError_ = "BibleSync identity exceeds the packet size limit";
322
+ } else {
323
+ sync.setMode(nativeMode, Callback, passphrase_);
324
+ }
325
+ starting_ = false;
326
+ Message result;
327
+ result.type = "result";
328
+ result.id = id;
329
+ result.error = startupError_;
330
+ if (result.error.empty() && sync.getMode() != nativeMode) result.error = "BibleSync failed to start";
331
+ bool started = result.error.empty();
332
+ if (!started) {
333
+ std::lock_guard<std::mutex> lock(activeMutex_);
334
+ active_ = nullptr;
335
+ }
336
+ Emit(std::move(result), false);
337
+
338
+ auto nextPoll = std::chrono::steady_clock::now() + std::chrono::seconds(1);
339
+ while (started && !overflow_) {
340
+ Command command;
341
+ bool haveCommand = false;
342
+ {
343
+ std::unique_lock<std::mutex> lock(mutex_);
344
+ wake_.wait_until(lock, nextPoll, [this] { return closing_ || !commands_.empty(); });
345
+ if (!commands_.empty()) {
346
+ command = std::move(commands_.front());
347
+ commands_.pop_front();
348
+ haveCommand = true;
349
+ } else if (closing_) {
350
+ break;
351
+ }
352
+ }
353
+ if (haveCommand) {
354
+ Message response;
355
+ response.type = "result";
356
+ response.id = command.id;
357
+ if (command.type == "stop") {
358
+ suppressEvents_ = true;
359
+ sync.setMode(BSP_MODE_DISABLE);
360
+ speakers_.clear();
361
+ {
362
+ std::lock_guard<std::mutex> lock(activeMutex_);
363
+ active_ = nullptr;
364
+ }
365
+ Emit(std::move(response), false);
366
+ started = false;
367
+ break;
368
+ } else if (command.type == "listen") {
369
+ auto speaker = speakers_.find(command.speakerId);
370
+ if (mode == "speaker") response.error = "Speaker mode cannot listen to navigation";
371
+ else if (speaker == speakers_.end()) response.error = "Unknown or expired BibleSync speaker";
372
+ else {
373
+ sync.listenToSpeaker(command.listening, command.speakerId);
374
+ speaker->second = command.listening;
375
+ }
376
+ } else if (command.type == "send") {
377
+ if (mode == "audience") response.error = "Audience mode cannot send navigation";
378
+ else if (!packetFits(application_, version_, user_, passphrase_, sync.getDevice(), command.bible,
379
+ command.reference, command.alternateReference,
380
+ command.group, command.domain)) {
381
+ response.error = "BibleSync navigation exceeds the packet size limit";
382
+ }
383
+ else {
384
+ BibleSync_xmit_status status = sync.Transmit(command.bible, command.reference,
385
+ command.alternateReference, command.group, command.domain);
386
+ if (status != BSP_XMIT_OK) response.error = "BibleSync transmission failed (status "
387
+ + std::to_string(static_cast<int>(status)) + ")";
388
+ if (sync.getMode() == BSP_MODE_DISABLE) {
389
+ fatalError_ = "BibleSync stopped after a network failure";
390
+ overflow_ = true;
391
+ }
392
+ }
393
+ }
394
+ Emit(std::move(response), false);
395
+ }
396
+ if (std::chrono::steady_clock::now() >= nextPoll) {
397
+ BibleSync::Receive(&sync);
398
+ if (sync.getMode() == BSP_MODE_DISABLE) {
399
+ fatalError_ = "BibleSync stopped after a network failure";
400
+ overflow_ = true;
401
+ }
402
+ nextPoll = std::chrono::steady_clock::now() + std::chrono::seconds(1);
403
+ }
404
+ }
405
+ {
406
+ std::lock_guard<std::mutex> lock(mutex_);
407
+ closing_ = true;
408
+ for (const Command& command : commands_) {
409
+ Message response;
410
+ response.type = "result";
411
+ response.id = command.id;
412
+ response.error = "BibleSync session stopped";
413
+ Emit(std::move(response), false);
414
+ }
415
+ commands_.clear();
416
+ }
417
+ suppressEvents_ = true;
418
+ sync.setMode(BSP_MODE_DISABLE);
419
+ speakers_.clear();
420
+ sync_ = nullptr;
421
+ {
422
+ std::lock_guard<std::mutex> lock(activeMutex_);
423
+ if (active_ == this) active_ = nullptr;
424
+ }
425
+ if (!fatalError_.empty()) {
426
+ Message fatal;
427
+ fatal.type = "fatal";
428
+ fatal.error = fatalError_;
429
+ Emit(std::move(fatal), false);
430
+ }
431
+ current_ = nullptr;
432
+ tsfn_.Release();
433
+ }
@@ -0,0 +1,90 @@
1
+ /* This file is part of node-bible-sync.
2
+
3
+ Copyright (C) 2026 Tobias Klein <contact@tklein.info>
4
+
5
+ node-bible-sync is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU General Public License as published by
7
+ the Free Software Foundation, either version 2 of the License, or
8
+ (at your option) any later version.
9
+
10
+ node-bible-sync is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13
+ See the GNU General Public License for more details.
14
+
15
+ You should have received a copy of the GNU General Public License
16
+ along with node-bible-sync. See the file COPYING.
17
+ If not, see <http://www.gnu.org/licenses/>. */
18
+
19
+ #ifndef NODE_BIBLE_SYNC_SESSION_HPP
20
+ #define NODE_BIBLE_SYNC_SESSION_HPP
21
+
22
+ #include <napi.h>
23
+ #include <atomic>
24
+ #include <condition_variable>
25
+ #include <deque>
26
+ #include <map>
27
+ #include <memory>
28
+ #include <mutex>
29
+ #include <string>
30
+ #include <thread>
31
+
32
+ class BibleSync;
33
+
34
+ class BibleSyncSession : public Napi::ObjectWrap<BibleSyncSession> {
35
+ public:
36
+ static Napi::Object Init(Napi::Env env, Napi::Object exports);
37
+ explicit BibleSyncSession(const Napi::CallbackInfo& info);
38
+ ~BibleSyncSession();
39
+
40
+ private:
41
+ struct Message {
42
+ std::string type, id, error, speakerId, bible, reference, alternateReference;
43
+ std::string group, domain, user, address, application, device;
44
+ bool listening = false;
45
+ bool counted = false;
46
+ std::shared_ptr<std::atomic<unsigned>> pending;
47
+ };
48
+ struct Command {
49
+ std::string type, id, speakerId, bible, reference, alternateReference, group, domain;
50
+ bool listening = false;
51
+ };
52
+
53
+ Napi::Value Start(const Napi::CallbackInfo& info);
54
+ Napi::Value Enqueue(const Napi::CallbackInfo& info);
55
+ void Run(std::string id, std::string mode);
56
+ void Emit(Message message, bool countEvent = true);
57
+ void OnEvent(char cmd, const std::string& speakerId, const std::string& bible,
58
+ const std::string& ref, const std::string& alt, const std::string& group,
59
+ const std::string& domain, const std::string& info, const std::string& dump);
60
+ static void Callback(char cmd, std::string speakerId, std::string bible,
61
+ std::string ref, std::string alt, std::string group,
62
+ std::string domain, std::string info, std::string dump);
63
+ static void Cleanup(void *data);
64
+ void Shutdown();
65
+
66
+ std::string application_, version_, user_, passphrase_;
67
+ Napi::FunctionReference callback_;
68
+ Napi::ThreadSafeFunction tsfn_;
69
+ std::shared_ptr<std::atomic<unsigned>> pending_{new std::atomic<unsigned>(0)};
70
+ std::thread thread_;
71
+ std::mutex mutex_;
72
+ std::condition_variable wake_;
73
+ std::deque<Command> commands_;
74
+ bool closing_ = false;
75
+ bool cleanupCalled_ = false;
76
+ bool cleanupRegistered_ = false;
77
+ bool starting_ = false;
78
+ bool overflow_ = false;
79
+ bool suppressEvents_ = false;
80
+ std::string startupError_;
81
+ std::string fatalError_;
82
+ BibleSync *sync_ = nullptr;
83
+ std::map<std::string, bool> speakers_;
84
+
85
+ static std::mutex activeMutex_;
86
+ static BibleSyncSession *active_;
87
+ static thread_local BibleSyncSession *current_;
88
+ };
89
+
90
+ #endif
@@ -0,0 +1,26 @@
1
+ /* This file is part of node-bible-sync.
2
+
3
+ Copyright (C) 2026 Tobias Klein <contact@tklein.info>
4
+
5
+ node-bible-sync is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU General Public License as published by
7
+ the Free Software Foundation, either version 2 of the License, or
8
+ (at your option) any later version.
9
+
10
+ node-bible-sync is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13
+ See the GNU General Public License for more details.
14
+
15
+ You should have received a copy of the GNU General Public License
16
+ along with node-bible-sync. See the file COPYING.
17
+ If not, see <http://www.gnu.org/licenses/>. */
18
+
19
+ #include <napi.h>
20
+ #include "biblesync_session.hpp"
21
+
22
+ Napi::Object InitAll(Napi::Env env, Napi::Object exports) {
23
+ return BibleSyncSession::Init(env, exports);
24
+ }
25
+
26
+ NODE_API_MODULE(NODE_GYP_MODULE_NAME, InitAll)
@@ -0,0 +1,142 @@
1
+ /* This file is part of node-bible-sync.
2
+
3
+ Copyright (C) 2026 Tobias Klein <contact@tklein.info>
4
+
5
+ node-bible-sync is free software: you can redistribute it and/or modify
6
+ it under the terms of the GNU General Public License as published by
7
+ the Free Software Foundation, either version 2 of the License, or
8
+ (at your option) any later version.
9
+
10
+ node-bible-sync is distributed in the hope that it will be useful,
11
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13
+ See the GNU General Public License for more details.
14
+
15
+ You should have received a copy of the GNU General Public License
16
+ along with node-bible-sync. See the file COPYING.
17
+ If not, see <http://www.gnu.org/licenses/>. */
18
+
19
+ const createBibleSyncClass = require('../biblesync');
20
+
21
+ let native;
22
+
23
+ class FakeNative {
24
+ constructor(options, callback) {
25
+ this.options = options;
26
+ this.callback = callback;
27
+ this.commands = [];
28
+ native = this;
29
+ }
30
+ start(id, mode) { this.commands.push({ id, type: 'start', mode }); }
31
+ enqueue(id, type, args) { this.commands.push({ id, type, args }); }
32
+ complete(error = '') {
33
+ const command = this.commands.shift();
34
+ this.callback({ type: 'result', id: command.id, error });
35
+ return command;
36
+ }
37
+ emit(type, data = {}) { this.callback({ type, ...data }); }
38
+ }
39
+
40
+ const BibleSync = createBibleSyncClass(FakeNative);
41
+ const options = { application: 'Test', version: '1', user: 'Alice' };
42
+
43
+ async function started(mode = 'personal') {
44
+ const session = new BibleSync(options);
45
+ const promise = session.start(mode);
46
+ native.complete();
47
+ await promise;
48
+ return session;
49
+ }
50
+
51
+ test('validates identity and does not start the network during construction', () => {
52
+ expect(() => new BibleSync({ ...options, user: 'bad\nuser' })).toThrow(/control/);
53
+ const session = new BibleSync(options);
54
+ expect(session.getSpeakers()).toEqual([]);
55
+ expect(native.options.passphrase).toBe('BibleSync');
56
+ expect(native.commands).toEqual([]);
57
+ });
58
+
59
+ test('handles lifecycle failures, retries, and concurrent start', async () => {
60
+ const session = new BibleSync(options);
61
+ await expect(session.start('bad')).rejects.toThrow('Invalid');
62
+ const start = session.start('audience');
63
+ await expect(session.start('speaker')).rejects.toThrow('already active');
64
+ native.complete('network unavailable');
65
+ await expect(start).rejects.toThrow('network unavailable');
66
+ const retry = session.start('speaker');
67
+ native.complete();
68
+ await retry;
69
+ const stop = session.stop();
70
+ const secondStop = session.stop();
71
+ native.complete();
72
+ await Promise.all([stop, secondStop]);
73
+ await session.stop();
74
+ });
75
+
76
+ test('discovers speakers as unselected and tracks explicit listening and expiry', async () => {
77
+ const session = await started();
78
+ const onSpeaker = jest.fn();
79
+ session.on('speaker', onSpeaker);
80
+ native.emit('speaker', { speakerId: 'id', user: 'Bob', address: '127.0.0.1', application: 'App', device: 'PC' });
81
+ expect(onSpeaker).toHaveBeenCalledWith(expect.objectContaining({ speakerId: 'id', listening: false }));
82
+ const snapshot = session.getSpeakers();
83
+ snapshot[0].listening = true;
84
+ expect(session.getSpeakers()[0].listening).toBe(false);
85
+ const listen = session.setSpeakerListening('id', true);
86
+ expect(native.complete().args).toEqual({ speakerId: 'id', listening: true });
87
+ await listen;
88
+ expect(session.getSpeakers()[0].listening).toBe(true);
89
+ native.emit('speakerRemoved', { speakerId: 'id' });
90
+ expect(session.getSpeakers()).toEqual([]);
91
+ const unknown = session.setSpeakerListening('id', true);
92
+ native.complete('Unknown or expired BibleSync speaker');
93
+ await expect(unknown).rejects.toThrow('Unknown or expired');
94
+ });
95
+
96
+ test('validates navigation and passes correct defaults to the native implementation', async () => {
97
+ const session = await started();
98
+ await expect(session.sendNavigation({ bible: 'KJV', reference: 'John.3.16\nbad' })).rejects.toThrow('control');
99
+ await expect(session.sendNavigation({ bible: 'KJV', reference: 'John.3.16', group: '0' })).rejects.toThrow('group');
100
+ await expect(session.sendNavigation({ bible: 'KJV', reference: 'John.3.16', domain: 'other' })).rejects.toThrow('domain');
101
+ const send = session.sendNavigation({ bible: 'KJV', reference: 'John.3.16' });
102
+ expect(native.complete().args).toEqual({
103
+ bible: 'KJV', reference: 'John.3.16', alternateReference: '', group: '1', domain: 'BIBLE-VERSE'
104
+ });
105
+ await send;
106
+ });
107
+
108
+ test('suppresses events during shutdown and rejects pending commands on fatal errors', async () => {
109
+ const session = await started();
110
+ const onNavigation = jest.fn();
111
+ const onError = jest.fn();
112
+ session.on('navigation', onNavigation);
113
+ session.on('error', onError);
114
+ const pending = session.sendNavigation({ bible: 'KJV', reference: 'John.3.16' });
115
+ native.emit('fatal', { error: 'overflow' });
116
+ await expect(pending).rejects.toThrow('overflow');
117
+ expect(onError).toHaveBeenCalledWith(expect.objectContaining({ message: 'overflow' }));
118
+ native.emit('navigation', { speakerId: 'id' });
119
+ expect(onNavigation).not.toHaveBeenCalled();
120
+ });
121
+
122
+ test('does not deliver events once stop has begun', async () => {
123
+ const session = await started();
124
+ const onSpeaker = jest.fn();
125
+ session.on('speaker', onSpeaker);
126
+ const stop = session.stop();
127
+ native.emit('speaker', { speakerId: 'id' });
128
+ native.complete();
129
+ await stop;
130
+ native.emit('speaker', { speakerId: 'id' });
131
+ expect(onSpeaker).not.toHaveBeenCalled();
132
+ });
133
+
134
+ test('a failed stop does not pretend the session has stopped', async () => {
135
+ const session = await started();
136
+ const stop = session.stop();
137
+ native.complete('queue error');
138
+ await expect(stop).rejects.toThrow('queue error');
139
+ const retry = session.stop();
140
+ native.complete();
141
+ await retry;
142
+ });