@zerodensity/realityhub-api 1.19.0 → 1.21.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.
- package/.github/workflows/npm-publish-next.yml +1 -1
- package/.github/workflows/npm-publish.yml +9 -7
- package/custom-ui/backend.js +211 -0
- package/custom-ui/frontend.js +303 -0
- package/package.json +5 -11
- package/src/index.js +6 -4
- package/src/lib/BrokerBase.js +5 -5
- package/src/lib/BrokerClient.js +23 -11
- package/src/lib/BrokerError.js +2 -1
- package/src/lib/RawRequest.js +3 -1
- package/src/lib/consoleLogger.js +1 -1
- package/src/lib/onceMultiple.js +1 -1
- package/src/index.cjs +0 -17
|
@@ -7,15 +7,17 @@ on:
|
|
|
7
7
|
|
|
8
8
|
jobs:
|
|
9
9
|
publish-npm:
|
|
10
|
-
|
|
11
|
-
|
|
10
|
+
permissions:
|
|
11
|
+
contents: read
|
|
12
|
+
id-token: write
|
|
12
13
|
name: Publish Job
|
|
13
14
|
runs-on: ubuntu-latest
|
|
14
15
|
steps:
|
|
15
|
-
- uses: actions/checkout@
|
|
16
|
-
- uses: actions/setup-node@
|
|
16
|
+
- uses: actions/checkout@v6
|
|
17
|
+
- uses: actions/setup-node@v6
|
|
17
18
|
with:
|
|
18
|
-
node-version: '
|
|
19
|
+
node-version: '24'
|
|
19
20
|
registry-url: https://registry.npmjs.org/
|
|
20
|
-
|
|
21
|
-
- run: npm
|
|
21
|
+
package-manager-cache: false
|
|
22
|
+
- run: npm ci --ignore-scripts
|
|
23
|
+
- run: npm publish --tag stable
|
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
// Copyright (c) 2026 Zero Density Inc.
|
|
2
|
+
// SPDX-License-Identifier: GPL-2.0-only
|
|
3
|
+
const { EventEmitter } = require('node:events');
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* @typedef {Object} Snapshot
|
|
7
|
+
* @property {Object|null} state Auxiliary field state, persisted with the item.
|
|
8
|
+
* @property {*} value Controller/form output.
|
|
9
|
+
*
|
|
10
|
+
* @typedef {Object} DataSnapshot
|
|
11
|
+
* @property {boolean} hasValue
|
|
12
|
+
* @property {*} data
|
|
13
|
+
* @property {string|null} [error]
|
|
14
|
+
* @property {boolean} [stale]
|
|
15
|
+
*
|
|
16
|
+
* @typedef {Object} Subscription
|
|
17
|
+
* @property {function(): void} stop
|
|
18
|
+
*
|
|
19
|
+
* @typedef {Object} Watch
|
|
20
|
+
* @property {function(Object): void} setParameters Replace parameters and discard obsolete deliveries.
|
|
21
|
+
* @property {function(): void} stop
|
|
22
|
+
*
|
|
23
|
+
* @typedef {Object} BackendAPI Injected into the partner's exported start(api).
|
|
24
|
+
* @property {number} apiVersion
|
|
25
|
+
* @property {Object} context
|
|
26
|
+
* @property {function(string, Function): void} export Register a frontend-callable function.
|
|
27
|
+
* @property {function(string, *=): void} emit Send a custom event to attached frontends.
|
|
28
|
+
* @property {function(string, Function): Function} on Subscribe using legacy direct callback delivery.
|
|
29
|
+
* @property {function(function(Snapshot): *): Function} onStateChange Await external state changes in the handler queue.
|
|
30
|
+
* @property {function(): Snapshot} getState Read the latest committed snapshot.
|
|
31
|
+
* @property {function(Object): Promise<Snapshot>} update Replace each supplied snapshot property.
|
|
32
|
+
* @property {function(Object): Promise<Snapshot>} patch Shallow-merge state and optionally commit output atomically.
|
|
33
|
+
* @property {function(*): Promise<Snapshot>} setValue
|
|
34
|
+
* @property {function(Object|null): Promise<Snapshot>} setState
|
|
35
|
+
* @property {function(Function): void} schedule Queue background work after the current handler/startup.
|
|
36
|
+
* @property {Object} data Named query bindings configured on the field.
|
|
37
|
+
* @property {function(string, Object=): Promise<DataSnapshot>} data.request
|
|
38
|
+
* @property {function(string, Object, Function, Function=): Subscription} data.subscribe Legacy direct callbacks.
|
|
39
|
+
* @property {function(string, Object, Function, Function=): Watch} data.watch Await callbacks in the handler queue.
|
|
40
|
+
*/
|
|
41
|
+
|
|
42
|
+
// Transport and worker ownership belong to Hub. The same runtime supports memory-backed tests.
|
|
43
|
+
/**
|
|
44
|
+
* Create the API used by a Hub worker container or an isolated test harness.
|
|
45
|
+
* @param {Object} configuration
|
|
46
|
+
* @param {Snapshot} configuration.snapshot
|
|
47
|
+
* @param {Object} [configuration.context]
|
|
48
|
+
* @param {function(string, Object): Promise<*>} configuration.request Platform request transport.
|
|
49
|
+
* @param {function(string, *): void} configuration.emit Platform event transport.
|
|
50
|
+
*/
|
|
51
|
+
function createBackendRuntime({ snapshot: initial, context = {}, request, emit }) {
|
|
52
|
+
const methods = new Map();
|
|
53
|
+
const events = new EventEmitter();
|
|
54
|
+
const stateListeners = new Set();
|
|
55
|
+
let snapshot = structuredClone(initial);
|
|
56
|
+
let snapshotSequence = 0;
|
|
57
|
+
let subscriptionSequence = 0;
|
|
58
|
+
let tasks = Promise.resolve();
|
|
59
|
+
let writes = Promise.resolve();
|
|
60
|
+
|
|
61
|
+
function enqueue(operation) {
|
|
62
|
+
const run = tasks.then(operation);
|
|
63
|
+
tasks = run.catch(() => {});
|
|
64
|
+
return run;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function report(error) {
|
|
68
|
+
emit('backenderror', error.message || String(error));
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function commit(makePatch) {
|
|
72
|
+
const run = writes.then(async () => {
|
|
73
|
+
const saved = await request('update', makePatch());
|
|
74
|
+
if (saved.sequence >= snapshotSequence) {
|
|
75
|
+
snapshot = saved.snapshot;
|
|
76
|
+
snapshotSequence = saved.sequence;
|
|
77
|
+
}
|
|
78
|
+
return structuredClone(snapshot);
|
|
79
|
+
});
|
|
80
|
+
writes = run.catch(() => {});
|
|
81
|
+
return run;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function subscribe(query, parameters, onData, onError = () => {}) {
|
|
85
|
+
const id = String(++subscriptionSequence);
|
|
86
|
+
const listener = ({ snapshot: data, error }) => {
|
|
87
|
+
if (error) onError(new Error(error));
|
|
88
|
+
else onData(data);
|
|
89
|
+
};
|
|
90
|
+
events.on(`data:${id}`, listener);
|
|
91
|
+
request('data.subscribe', { id, query, parameters }).catch((error) => {
|
|
92
|
+
if (events.listeners(`data:${id}`).includes(listener)) onError(error);
|
|
93
|
+
});
|
|
94
|
+
return {
|
|
95
|
+
stop: () => {
|
|
96
|
+
events.off(`data:${id}`, listener);
|
|
97
|
+
request('data.unsubscribe', { id }).catch(() => {});
|
|
98
|
+
},
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function watch(query, parameters, onData, onError = report) {
|
|
103
|
+
let subscription;
|
|
104
|
+
let generation = 0;
|
|
105
|
+
let stopped = false;
|
|
106
|
+
const deliver = (mine, handler, value) => {
|
|
107
|
+
enqueue(() => {
|
|
108
|
+
if (!stopped && generation === mine) return handler(value);
|
|
109
|
+
return undefined;
|
|
110
|
+
}).catch(report);
|
|
111
|
+
};
|
|
112
|
+
const setParameters = (next) => {
|
|
113
|
+
if (stopped) return;
|
|
114
|
+
const mine = ++generation;
|
|
115
|
+
subscription?.stop();
|
|
116
|
+
subscription = subscribe(
|
|
117
|
+
query,
|
|
118
|
+
next,
|
|
119
|
+
(data) => deliver(mine, onData, data),
|
|
120
|
+
(error) => deliver(mine, onError, error)
|
|
121
|
+
);
|
|
122
|
+
};
|
|
123
|
+
setParameters(parameters);
|
|
124
|
+
return {
|
|
125
|
+
setParameters,
|
|
126
|
+
stop: () => {
|
|
127
|
+
if (stopped) return;
|
|
128
|
+
stopped = true;
|
|
129
|
+
generation += 1;
|
|
130
|
+
subscription.stop();
|
|
131
|
+
},
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** @type {BackendAPI} */
|
|
136
|
+
const api = {
|
|
137
|
+
apiVersion: 1,
|
|
138
|
+
context,
|
|
139
|
+
export: (name, handler) => {
|
|
140
|
+
if (typeof name !== 'string' || !name || typeof handler !== 'function' || name === 'getState') {
|
|
141
|
+
throw new Error('Invalid backend function.');
|
|
142
|
+
}
|
|
143
|
+
methods.set(name, handler);
|
|
144
|
+
},
|
|
145
|
+
emit: (name, payload = null) => emit(name, payload),
|
|
146
|
+
on: (name, handler) => {
|
|
147
|
+
events.on(name, handler);
|
|
148
|
+
return () => events.off(name, handler);
|
|
149
|
+
},
|
|
150
|
+
onStateChange: (handler) => {
|
|
151
|
+
stateListeners.add(handler);
|
|
152
|
+
return () => stateListeners.delete(handler);
|
|
153
|
+
},
|
|
154
|
+
getState: () => structuredClone(snapshot),
|
|
155
|
+
update: (patch) => {
|
|
156
|
+
const clean = structuredClone(patch);
|
|
157
|
+
return commit(() => clean);
|
|
158
|
+
},
|
|
159
|
+
patch: (patch) => {
|
|
160
|
+
const clean = structuredClone(patch);
|
|
161
|
+
if (Object.hasOwn(clean, 'state') && (!clean.state || Array.isArray(clean.state) || typeof clean.state !== 'object')) {
|
|
162
|
+
throw new Error('State patch must be an object. Use setState(null) to clear it.');
|
|
163
|
+
}
|
|
164
|
+
return commit(() => ({
|
|
165
|
+
...clean,
|
|
166
|
+
...(Object.hasOwn(clean, 'state') ? { state: { ...snapshot.state, ...clean.state } } : {}),
|
|
167
|
+
}));
|
|
168
|
+
},
|
|
169
|
+
setValue: (value) => api.update({ value }),
|
|
170
|
+
setState: (state) => api.update({ state }),
|
|
171
|
+
// Background tasks run after the current handler/initialization; failures are reported.
|
|
172
|
+
schedule: (operation) => {
|
|
173
|
+
enqueue(operation).catch(report);
|
|
174
|
+
},
|
|
175
|
+
data: {
|
|
176
|
+
request: (query, parameters = {}) => request('data.request', { query, parameters }),
|
|
177
|
+
subscribe,
|
|
178
|
+
watch,
|
|
179
|
+
},
|
|
180
|
+
};
|
|
181
|
+
|
|
182
|
+
return {
|
|
183
|
+
api,
|
|
184
|
+
initialize: (start) => enqueue(() => start(api)),
|
|
185
|
+
call: (name, args = []) =>
|
|
186
|
+
enqueue(async () => {
|
|
187
|
+
if (name === 'getState') {
|
|
188
|
+
await writes;
|
|
189
|
+
return api.getState();
|
|
190
|
+
}
|
|
191
|
+
const handler = methods.get(name);
|
|
192
|
+
if (!handler) throw new Error(`Unknown backend function: ${name}`);
|
|
193
|
+
return handler(...args);
|
|
194
|
+
}),
|
|
195
|
+
sync: (next, sequence) =>
|
|
196
|
+
enqueue(async () => {
|
|
197
|
+
if (sequence <= snapshotSequence) return;
|
|
198
|
+
snapshot = structuredClone(next);
|
|
199
|
+
snapshotSequence = sequence;
|
|
200
|
+
const changed = api.getState();
|
|
201
|
+
events.emit('stateupdate', structuredClone(changed));
|
|
202
|
+
for (const handler of stateListeners) {
|
|
203
|
+
// eslint-disable-next-line no-await-in-loop -- State observers participate in the same serial queue.
|
|
204
|
+
await handler(structuredClone(changed));
|
|
205
|
+
}
|
|
206
|
+
}),
|
|
207
|
+
deliverData: (message) => events.emit(`data:${message.id}`, message),
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
module.exports = { createBackendRuntime };
|
|
@@ -0,0 +1,303 @@
|
|
|
1
|
+
// Copyright (c) 2026 Zero Density Inc.
|
|
2
|
+
// SPDX-License-Identifier: GPL-2.0-only
|
|
3
|
+
const clients = new WeakMap();
|
|
4
|
+
const copy = (value) => JSON.parse(JSON.stringify(value));
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* @typedef {Object} ClientView
|
|
8
|
+
* @property {Object|null} state Latest authoritative field state.
|
|
9
|
+
* @property {*} value Latest controller/form output.
|
|
10
|
+
* @property {boolean} readOnly
|
|
11
|
+
* @property {Object} context
|
|
12
|
+
* @property {boolean} backend
|
|
13
|
+
* @property {boolean} paused
|
|
14
|
+
* @property {'connecting'|'connected'|'disconnected'|'closed'|'error'} connection
|
|
15
|
+
* @property {string|null} error
|
|
16
|
+
*
|
|
17
|
+
* @typedef {Object} Client
|
|
18
|
+
* @property {number} apiVersion
|
|
19
|
+
* @property {function(function(ClientView): void): Function} subscribe Replay the current view and observe changes.
|
|
20
|
+
* @property {function(): Promise<ClientView>} ready Wait for host initialization and backend readiness.
|
|
21
|
+
* @property {function(): Promise<{state: Object|null, value: *}>} getState Read on demand without replacing newer observed state.
|
|
22
|
+
* @property {function(string, ...*): Promise<*>} call Invoke a named backend function.
|
|
23
|
+
* @property {function(string, Function): Function} on Observe a custom backend event.
|
|
24
|
+
* @property {function(*): Promise<boolean>} setValue Update frontend-only output.
|
|
25
|
+
* @property {function(Object|null): Promise<Object|null>} setState Update frontend-only state.
|
|
26
|
+
* @property {Object} data Frontend query request/subscribe operations through the host.
|
|
27
|
+
* @property {function(string, Object=): Promise<import('./backend').DataSnapshot>} data.request
|
|
28
|
+
* @property {function(string, Object, Function, Function=): import('./backend').Subscription} data.subscribe
|
|
29
|
+
* @property {function(): void} destroy Release this client's resources; Hub retains worker ownership.
|
|
30
|
+
*/
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Join the iframe's existing Hub connection. Requests default to a 15-second deadline.
|
|
34
|
+
* @param {Object} [options]
|
|
35
|
+
* @param {Window} [options.window] The iframe window; injectable for tests.
|
|
36
|
+
* @param {number} [options.timeoutMs=15000]
|
|
37
|
+
* @returns {Client}
|
|
38
|
+
*/
|
|
39
|
+
function createClient({ window: target = window, timeoutMs = 15000 } = {}) {
|
|
40
|
+
if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) throw new Error('Request timeout must be positive.');
|
|
41
|
+
if (clients.has(target)) return clients.get(target);
|
|
42
|
+
const backend = target.hubBackend;
|
|
43
|
+
const observers = new Set();
|
|
44
|
+
const subscriptions = new Map();
|
|
45
|
+
const operations = new Set();
|
|
46
|
+
const pending = new Map();
|
|
47
|
+
const cleanup = new Set();
|
|
48
|
+
let port;
|
|
49
|
+
let initialized = false;
|
|
50
|
+
let destroyed = false;
|
|
51
|
+
let fatalError;
|
|
52
|
+
let sequence = 0;
|
|
53
|
+
let backendConnection = 'connecting';
|
|
54
|
+
let view = {
|
|
55
|
+
state: null,
|
|
56
|
+
value: null,
|
|
57
|
+
readOnly: true,
|
|
58
|
+
context: {},
|
|
59
|
+
backend: Boolean(backend),
|
|
60
|
+
paused: false,
|
|
61
|
+
connection: 'connecting',
|
|
62
|
+
error: null,
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
function update(changes) {
|
|
66
|
+
view = { ...view, ...changes };
|
|
67
|
+
for (const observer of observers) {
|
|
68
|
+
try {
|
|
69
|
+
observer(copy(view));
|
|
70
|
+
} catch (error) {
|
|
71
|
+
console.error(error);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
for (const operation of [...operations]) operation.begin();
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function perform(start, requireConnected = false, trackCancellation = null) {
|
|
78
|
+
return new Promise((resolve, reject) => {
|
|
79
|
+
let started = false;
|
|
80
|
+
let finished = false;
|
|
81
|
+
let cancel = () => {};
|
|
82
|
+
let requestId;
|
|
83
|
+
let timer;
|
|
84
|
+
let operation;
|
|
85
|
+
const deadlineAt = Date.now() + timeoutMs;
|
|
86
|
+
const finish = (error, result) => {
|
|
87
|
+
if (finished) return;
|
|
88
|
+
finished = true;
|
|
89
|
+
clearTimeout(timer);
|
|
90
|
+
operations.delete(operation);
|
|
91
|
+
if (trackCancellation) trackCancellation(null);
|
|
92
|
+
if (requestId) pending.delete(requestId);
|
|
93
|
+
if (error) {
|
|
94
|
+
cancel();
|
|
95
|
+
if (!destroyed) update({ error: error.message });
|
|
96
|
+
reject(error);
|
|
97
|
+
} else resolve(result);
|
|
98
|
+
};
|
|
99
|
+
operation = {
|
|
100
|
+
finish,
|
|
101
|
+
begin: () => {
|
|
102
|
+
if (finished || started) return;
|
|
103
|
+
if (destroyed || fatalError) {
|
|
104
|
+
finish(fatalError || new Error('Custom UI client closed.'));
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
if (view.connection === 'closed') {
|
|
108
|
+
finish(new Error('Backend closed.'));
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
if (!initialized || (requireConnected && view.connection !== 'connected')) return;
|
|
112
|
+
started = true;
|
|
113
|
+
try {
|
|
114
|
+
start({
|
|
115
|
+
finish,
|
|
116
|
+
remaining: Math.max(1, deadlineAt - Date.now()),
|
|
117
|
+
setCancel: (handler) => {
|
|
118
|
+
cancel = handler;
|
|
119
|
+
},
|
|
120
|
+
hostRequest: (type, payload = {}) => {
|
|
121
|
+
requestId = String(++sequence);
|
|
122
|
+
pending.set(requestId, finish);
|
|
123
|
+
port.postMessage({ protocol: 1, id: requestId, type, ...payload });
|
|
124
|
+
},
|
|
125
|
+
});
|
|
126
|
+
} catch (error) {
|
|
127
|
+
finish(error);
|
|
128
|
+
}
|
|
129
|
+
},
|
|
130
|
+
};
|
|
131
|
+
timer = setTimeout(() => finish(new Error('Custom UI request timed out.')), timeoutMs);
|
|
132
|
+
if (trackCancellation) trackCancellation(() => finish(null, true));
|
|
133
|
+
operations.add(operation);
|
|
134
|
+
operation.begin();
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function hostRequest(type, payload) {
|
|
139
|
+
return perform((operation) => operation.hostRequest(type, payload));
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function backendRequest(name, args) {
|
|
143
|
+
return perform((operation) => {
|
|
144
|
+
if (!backend) throw new Error('This custom UI has no backend.');
|
|
145
|
+
if (view.readOnly && name !== 'getState') throw new Error('This field is read-only.');
|
|
146
|
+
const request = backend.request(name, args, operation.remaining);
|
|
147
|
+
operation.setCancel(request.cancel);
|
|
148
|
+
request.promise.then(
|
|
149
|
+
(result) => operation.finish(null, result),
|
|
150
|
+
(error) => operation.finish(error)
|
|
151
|
+
);
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function unsubscribe(id) {
|
|
156
|
+
const subscription = subscriptions.get(id);
|
|
157
|
+
if (!subscription) return;
|
|
158
|
+
subscriptions.delete(id);
|
|
159
|
+
if (subscription.cancelRequest) subscription.cancelRequest();
|
|
160
|
+
if (port) port.postMessage({ protocol: 1, id: String(++sequence), type: 'unsubscribe', subscription: id });
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function receive({ data: message }) {
|
|
164
|
+
if (destroyed || message.protocol !== 1) return;
|
|
165
|
+
if (message.type === 'result') {
|
|
166
|
+
const finish = pending.get(message.id);
|
|
167
|
+
if (finish) finish(message.error ? new Error(message.error) : null, message.result);
|
|
168
|
+
} else if (message.type === 'init') {
|
|
169
|
+
if (message.apiVersion !== 1 || (message.backend && !backend)) {
|
|
170
|
+
fatalError = new Error('This SDK requires Reality Hub custom UI API version 1.');
|
|
171
|
+
update({ connection: 'error', error: fatalError.message });
|
|
172
|
+
return;
|
|
173
|
+
}
|
|
174
|
+
initialized = true;
|
|
175
|
+
update({
|
|
176
|
+
readOnly: Boolean(message.readOnly),
|
|
177
|
+
context: message.context || {},
|
|
178
|
+
paused: Boolean(message.paused),
|
|
179
|
+
connection: backend ? backendConnection : 'connected',
|
|
180
|
+
...(!backend ? { state: message.state || null, value: message.value === undefined ? null : message.value } : {}),
|
|
181
|
+
});
|
|
182
|
+
} else if (message.type === 'value') {
|
|
183
|
+
update({ readOnly: Boolean(message.readOnly), ...(!backend ? { value: message.value } : {}) });
|
|
184
|
+
} else if (message.type === 'paused') {
|
|
185
|
+
update({ paused: Boolean(message.paused) });
|
|
186
|
+
} else if (message.type === 'data' || message.type === 'queryError') {
|
|
187
|
+
const handle = subscriptions.get(message.subscription);
|
|
188
|
+
if (handle) {
|
|
189
|
+
try {
|
|
190
|
+
if (message.type === 'data') handle.onData(message.snapshot);
|
|
191
|
+
else handle.onError(new Error(message.error));
|
|
192
|
+
} catch (error) {
|
|
193
|
+
update({ error: error.message });
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
function connect(event) {
|
|
200
|
+
if (event.source !== target.parent || !event.data || event.data.type !== 'hub.xui.connect') return;
|
|
201
|
+
if (event.data.protocol !== 1 || !event.ports[0] || port || destroyed) return;
|
|
202
|
+
[port] = event.ports;
|
|
203
|
+
target.removeEventListener('message', connect);
|
|
204
|
+
port.onmessage = receive;
|
|
205
|
+
port.start();
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
function destroy() {
|
|
209
|
+
if (destroyed) return;
|
|
210
|
+
destroyed = true;
|
|
211
|
+
target.removeEventListener('message', connect);
|
|
212
|
+
target.removeEventListener('pagehide', destroy);
|
|
213
|
+
for (const id of [...subscriptions.keys()]) unsubscribe(id);
|
|
214
|
+
for (const operation of [...operations]) operation.finish(new Error('Custom UI client closed.'));
|
|
215
|
+
for (const off of cleanup) off();
|
|
216
|
+
cleanup.clear();
|
|
217
|
+
if (port) port.close();
|
|
218
|
+
update({ connection: 'closed' });
|
|
219
|
+
observers.clear();
|
|
220
|
+
clients.delete(target);
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
const client = {
|
|
224
|
+
apiVersion: 1,
|
|
225
|
+
subscribe: (observer) => {
|
|
226
|
+
if (destroyed) throw new Error('Custom UI client closed.');
|
|
227
|
+
observers.add(observer);
|
|
228
|
+
observer(copy(view));
|
|
229
|
+
return () => observers.delete(observer);
|
|
230
|
+
},
|
|
231
|
+
ready: () => perform((operation) => operation.finish(null, copy(view)), true),
|
|
232
|
+
getState: () =>
|
|
233
|
+
backend ? backendRequest('getState', []) : hostRequest('loadState').then((state) => ({ state, value: view.value })),
|
|
234
|
+
call: (name, ...args) => backendRequest(name, args),
|
|
235
|
+
on: (name, handler) => {
|
|
236
|
+
if (destroyed) throw new Error('Custom UI client closed.');
|
|
237
|
+
if (!backend) throw new Error('This custom UI has no backend.');
|
|
238
|
+
const off = backend.on(name, handler);
|
|
239
|
+
const stop = () => {
|
|
240
|
+
off();
|
|
241
|
+
cleanup.delete(stop);
|
|
242
|
+
};
|
|
243
|
+
cleanup.add(stop);
|
|
244
|
+
return stop;
|
|
245
|
+
},
|
|
246
|
+
setValue: (value) =>
|
|
247
|
+
hostRequest('setValue', { value }).then((result) => {
|
|
248
|
+
if (!destroyed) update({ value });
|
|
249
|
+
return result;
|
|
250
|
+
}),
|
|
251
|
+
setState: (state) =>
|
|
252
|
+
hostRequest('saveState', { state }).then((saved) => {
|
|
253
|
+
if (!destroyed) update({ state: saved });
|
|
254
|
+
return saved;
|
|
255
|
+
}),
|
|
256
|
+
data: {
|
|
257
|
+
request: (query, parameters = {}) => hostRequest('request', { query, parameters }),
|
|
258
|
+
subscribe: (query, parameters, onData, onError = (error) => update({ error: error.message })) => {
|
|
259
|
+
if (destroyed) throw new Error('Custom UI client closed.');
|
|
260
|
+
const id = `query_${++sequence}`;
|
|
261
|
+
const handle = { onData, onError };
|
|
262
|
+
subscriptions.set(id, handle);
|
|
263
|
+
perform(
|
|
264
|
+
(operation) => operation.hostRequest('subscribe', { query, parameters, subscription: id }),
|
|
265
|
+
false,
|
|
266
|
+
(cancel) => {
|
|
267
|
+
handle.cancelRequest = cancel;
|
|
268
|
+
}
|
|
269
|
+
).catch((error) => {
|
|
270
|
+
if (subscriptions.has(id)) {
|
|
271
|
+
unsubscribe(id);
|
|
272
|
+
onError(error);
|
|
273
|
+
}
|
|
274
|
+
});
|
|
275
|
+
return { stop: () => unsubscribe(id) };
|
|
276
|
+
},
|
|
277
|
+
},
|
|
278
|
+
destroy,
|
|
279
|
+
};
|
|
280
|
+
clients.set(target, client);
|
|
281
|
+
if (backend) {
|
|
282
|
+
if (backend.apiVersion !== 1 || typeof backend.subscribe !== 'function' || typeof backend.request !== 'function') {
|
|
283
|
+
fatalError = new Error('This SDK requires Reality Hub custom UI API version 1.');
|
|
284
|
+
update({ connection: 'error', error: fatalError.message });
|
|
285
|
+
} else {
|
|
286
|
+
cleanup.add(
|
|
287
|
+
backend.subscribe(({ snapshot, connection, error }) => {
|
|
288
|
+
backendConnection = connection;
|
|
289
|
+
update({
|
|
290
|
+
connection: initialized ? connection : 'connecting',
|
|
291
|
+
error,
|
|
292
|
+
...(snapshot ? { state: snapshot.state, value: snapshot.value } : {}),
|
|
293
|
+
});
|
|
294
|
+
})
|
|
295
|
+
);
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
target.addEventListener('message', connect);
|
|
299
|
+
target.addEventListener('pagehide', destroy);
|
|
300
|
+
return client;
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
exports.createClient = createClient;
|
package/package.json
CHANGED
|
@@ -1,22 +1,15 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zerodensity/realityhub-api",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.21.0",
|
|
4
4
|
"description": "RealityHub API Javascript Implementation",
|
|
5
|
-
"type": "module",
|
|
6
5
|
"main": "src/index.js",
|
|
7
|
-
"exports": {
|
|
8
|
-
"./package.json": "./package.json",
|
|
9
|
-
".": {
|
|
10
|
-
"import": "./src/index.js",
|
|
11
|
-
"require": "./src/index.cjs"
|
|
12
|
-
}
|
|
13
|
-
},
|
|
14
6
|
"repository": {
|
|
15
7
|
"type": "git",
|
|
16
8
|
"url": "git+ssh://git@github.com/zerodensity/realityhub-api.git"
|
|
17
9
|
},
|
|
18
10
|
"publishConfig": {
|
|
19
|
-
"access": "public"
|
|
11
|
+
"access": "public",
|
|
12
|
+
"tag": "stable"
|
|
20
13
|
},
|
|
21
14
|
"keywords": [
|
|
22
15
|
"realityhub",
|
|
@@ -38,6 +31,7 @@
|
|
|
38
31
|
},
|
|
39
32
|
"homepage": "https://github.com/zerodensity/realityhub-api#readme",
|
|
40
33
|
"dependencies": {
|
|
41
|
-
"uuid": "^11.0.3"
|
|
34
|
+
"uuid": "^11.0.3",
|
|
35
|
+
"ws": "^8.18.0"
|
|
42
36
|
}
|
|
43
37
|
}
|
package/src/index.js
CHANGED
|
@@ -14,7 +14,9 @@
|
|
|
14
14
|
// You should have received a copy of the GNU General Public License
|
|
15
15
|
// along with realityhub-api. If not, see <https://www.gnu.org/licenses/>.
|
|
16
16
|
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
17
|
+
module.exports = {
|
|
18
|
+
BrokerBase: require('./lib/BrokerBase'),
|
|
19
|
+
BrokerClient: require('./lib/BrokerClient'),
|
|
20
|
+
BrokerError: require('./lib/BrokerError'),
|
|
21
|
+
RawRequest: require('./lib/RawRequest'),
|
|
22
|
+
};
|
package/src/lib/BrokerBase.js
CHANGED
|
@@ -14,10 +14,10 @@
|
|
|
14
14
|
// You should have received a copy of the GNU General Public License
|
|
15
15
|
// along with realityhub-api. If not, see <https://www.gnu.org/licenses/>.
|
|
16
16
|
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
17
|
+
const { v4: uuid } = require('uuid');
|
|
18
|
+
const EventEmitter = require('events');
|
|
19
|
+
const BrokerError = require('./BrokerError.js');
|
|
20
|
+
const onceMultiple = require('./onceMultiple.js');
|
|
21
21
|
|
|
22
22
|
const DEFAULT_MAX_WS_PACKET_SIZE = 50 /*MB*/ * 1024 * 1024;
|
|
23
23
|
|
|
@@ -28,7 +28,7 @@ const DEFAULT_MAX_WS_PACKET_SIZE = 50 /*MB*/ * 1024 * 1024;
|
|
|
28
28
|
* @param {number} [params.maxPacketSize] Maximum websocket packet size
|
|
29
29
|
* @param {Logger} [params.logger] Logger instance
|
|
30
30
|
*/
|
|
31
|
-
|
|
31
|
+
module.exports = class BrokerBase extends EventEmitter {
|
|
32
32
|
constructor(params) {
|
|
33
33
|
super();
|
|
34
34
|
this.moduleName = params.moduleName;
|
package/src/lib/BrokerClient.js
CHANGED
|
@@ -14,14 +14,24 @@
|
|
|
14
14
|
// You should have received a copy of the GNU General Public License
|
|
15
15
|
// along with realityhub-api. If not, see <https://www.gnu.org/licenses/>.
|
|
16
16
|
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
17
|
+
const { v4: uuid } = require('uuid');
|
|
18
|
+
const BrokerBase = require('./BrokerBase.js');
|
|
19
|
+
const BrokerError = require('./BrokerError.js');
|
|
20
|
+
const RawRequest = require('./RawRequest.js');
|
|
21
|
+
const consoleLogger = require('./consoleLogger.js');
|
|
22
|
+
const onceMultiple = require('./onceMultiple.js');
|
|
23
|
+
|
|
24
|
+
let ws;
|
|
25
|
+
|
|
26
|
+
const runningInBrowser = typeof window !== 'undefined';
|
|
27
|
+
|
|
28
|
+
if (runningInBrowser) {
|
|
29
|
+
ws = WebSocket;
|
|
30
|
+
} else {
|
|
31
|
+
ws = require('ws');
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
module.exports = class BrokerClient extends BrokerBase {
|
|
25
35
|
/**
|
|
26
36
|
* BrokerClient constructor
|
|
27
37
|
* @param {object} params Parameters
|
|
@@ -127,10 +137,10 @@ export class BrokerClient extends BrokerBase {
|
|
|
127
137
|
if (typeof process !== "undefined" && process.versions != null && process.versions.node != null) {
|
|
128
138
|
const NODE_TLS_REJECT_UNAUTHORIZED = process.env.NODE_TLS_REJECT_UNAUTHORIZED;
|
|
129
139
|
process.env.NODE_TLS_REJECT_UNAUTHORIZED = 0;
|
|
130
|
-
this.socket = new
|
|
140
|
+
this.socket = new ws(`${webSocketURL}?module=true`);
|
|
131
141
|
process.env.NODE_TLS_REJECT_UNAUTHORIZED = NODE_TLS_REJECT_UNAUTHORIZED;
|
|
132
142
|
} else {
|
|
133
|
-
this.socket = new
|
|
143
|
+
this.socket = new ws(webSocketURL);
|
|
134
144
|
}
|
|
135
145
|
|
|
136
146
|
this.addSocketListeners();
|
|
@@ -431,7 +441,7 @@ export class BrokerClient extends BrokerBase {
|
|
|
431
441
|
},
|
|
432
442
|
);
|
|
433
443
|
|
|
434
|
-
if (socket.readyState !==
|
|
444
|
+
if (socket.readyState !== ws.OPEN) {
|
|
435
445
|
try {
|
|
436
446
|
await onceMultiple(this, ['connect'], webSocketMessage.timeout || this.messageTimeout);
|
|
437
447
|
} catch (ex) {
|
|
@@ -556,6 +566,8 @@ export class BrokerClient extends BrokerBase {
|
|
|
556
566
|
duplicate.onClose();
|
|
557
567
|
}
|
|
558
568
|
}
|
|
569
|
+
} else {
|
|
570
|
+
this.emit('reconnectfailure');
|
|
559
571
|
}
|
|
560
572
|
|
|
561
573
|
setTimeout(() => this.connect(this.connectOptions), 1000);
|
package/src/lib/BrokerError.js
CHANGED
|
@@ -14,4 +14,5 @@
|
|
|
14
14
|
// You should have received a copy of the GNU General Public License
|
|
15
15
|
// along with realityhub-api. If not, see <https://www.gnu.org/licenses/>.
|
|
16
16
|
|
|
17
|
-
|
|
17
|
+
class BrokerError extends Error { }
|
|
18
|
+
module.exports = BrokerError;
|
package/src/lib/RawRequest.js
CHANGED
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
// You should have received a copy of the GNU General Public License
|
|
15
15
|
// along with realityhub-api. If not, see <https://www.gnu.org/licenses/>.
|
|
16
16
|
|
|
17
|
-
|
|
17
|
+
class RawRequest {
|
|
18
18
|
setCallback(callback) {
|
|
19
19
|
if (typeof callback !== 'function') {
|
|
20
20
|
throw new Error('callback must be a function.');
|
|
@@ -37,3 +37,5 @@ export class RawRequest {
|
|
|
37
37
|
}
|
|
38
38
|
}
|
|
39
39
|
}
|
|
40
|
+
|
|
41
|
+
module.exports = RawRequest;
|
package/src/lib/consoleLogger.js
CHANGED
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
// You should have received a copy of the GNU General Public License
|
|
15
15
|
// along with realityhub-api. If not, see <https://www.gnu.org/licenses/>.
|
|
16
16
|
|
|
17
|
-
|
|
17
|
+
module.exports = function consoleLogger(moduleName, options = { silent: false }) {
|
|
18
18
|
const { silent } = options;
|
|
19
19
|
|
|
20
20
|
return ['log', 'info', 'warn', 'error', 'trace', 'debug'].reduce((o, item) => {
|
package/src/lib/onceMultiple.js
CHANGED
|
@@ -22,7 +22,7 @@ class TimeoutError extends Error {
|
|
|
22
22
|
}
|
|
23
23
|
}
|
|
24
24
|
|
|
25
|
-
|
|
25
|
+
module.exports = function onceMultiple(target, eventNames, timeout = null) {
|
|
26
26
|
return new Promise((resolve, reject) => {
|
|
27
27
|
let timer;
|
|
28
28
|
let handler;
|
package/src/index.cjs
DELETED
|
@@ -1,17 +0,0 @@
|
|
|
1
|
-
// Copyright (c) 2019-2025 Zero Density Inc.
|
|
2
|
-
//
|
|
3
|
-
// This file is part of realityhub-api.
|
|
4
|
-
//
|
|
5
|
-
// realityhub-api is free software: you can redistribute it and/or modify
|
|
6
|
-
// it under the terms of the GNU General Public License version 2, as published by
|
|
7
|
-
// the Free Software Foundation.
|
|
8
|
-
//
|
|
9
|
-
// realityhub-api is distributed in the hope that it will be useful,
|
|
10
|
-
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
11
|
-
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
12
|
-
// GNU General Public License for more details.
|
|
13
|
-
//
|
|
14
|
-
// You should have received a copy of the GNU General Public License
|
|
15
|
-
// along with realityhub-api. If not, see <https://www.gnu.org/licenses/>.
|
|
16
|
-
|
|
17
|
-
module.exports = require('./index.js');
|