@classic-homes/maps-core 0.1.1

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,387 @@
1
+ // src/workers/SpatialWorkerClient.ts
2
+ var SpatialWorkerClient = class _SpatialWorkerClient {
3
+ constructor(options = {}) {
4
+ this.worker = null;
5
+ this.pendingRequests = /* @__PURE__ */ new Map();
6
+ this.requestCounter = 0;
7
+ this.initialized = false;
8
+ this.ready = false;
9
+ this.readyResolve = null;
10
+ this.options = {
11
+ requestTimeout: options.requestTimeout ?? 3e4,
12
+ useRTree: options.useRTree ?? true,
13
+ gridTargetCells: options.gridTargetCells ?? 1024,
14
+ rtreeMaxEntries: options.rtreeMaxEntries ?? 9,
15
+ workerFactory: options.workerFactory,
16
+ workerUrl: options.workerUrl
17
+ };
18
+ this.readyPromise = new Promise((resolve) => {
19
+ this.readyResolve = resolve;
20
+ });
21
+ this.createWorker();
22
+ }
23
+ /**
24
+ * Check if Web Workers are supported
25
+ */
26
+ static isSupported() {
27
+ return typeof Worker !== "undefined";
28
+ }
29
+ /**
30
+ * Create the worker instance
31
+ */
32
+ createWorker() {
33
+ if (!_SpatialWorkerClient.isSupported()) {
34
+ console.warn("[maps-core] Web Workers not supported. SpatialWorkerClient will not function.");
35
+ return;
36
+ }
37
+ if (!this.options.workerFactory && !this.options.workerUrl) {
38
+ console.warn(
39
+ "[maps-core] SpatialWorkerClient: No workerFactory or workerUrl provided. Worker will not be created until setWorker() is called."
40
+ );
41
+ return;
42
+ }
43
+ try {
44
+ if (this.options.workerFactory) {
45
+ this.worker = this.options.workerFactory();
46
+ } else if (this.options.workerUrl) {
47
+ this.worker = new Worker(this.options.workerUrl, { type: "module" });
48
+ }
49
+ if (this.worker) {
50
+ this.worker.onmessage = this.handleMessage.bind(this);
51
+ this.worker.onerror = this.handleError.bind(this);
52
+ }
53
+ } catch (error) {
54
+ console.error("[maps-core] Failed to create spatial worker:", error);
55
+ }
56
+ }
57
+ /**
58
+ * Set the worker instance manually
59
+ *
60
+ * Use this when you need to create the worker yourself,
61
+ * or when using a bundler-specific worker import.
62
+ *
63
+ * @example
64
+ * ```ts
65
+ * import SpatialWorker from './spatial.worker?worker';
66
+ * const client = new SpatialWorkerClient();
67
+ * client.setWorker(new SpatialWorker());
68
+ * ```
69
+ */
70
+ setWorker(worker) {
71
+ if (this.worker) {
72
+ this.worker.terminate();
73
+ }
74
+ this.worker = worker;
75
+ this.worker.onmessage = this.handleMessage.bind(this);
76
+ this.worker.onerror = this.handleError.bind(this);
77
+ this.ready = false;
78
+ this.readyPromise = new Promise((resolve) => {
79
+ this.readyResolve = resolve;
80
+ });
81
+ }
82
+ /**
83
+ * Handle messages from the worker
84
+ */
85
+ handleMessage(event) {
86
+ const message = event.data;
87
+ if (message.type === "ready") {
88
+ this.ready = true;
89
+ this.readyResolve?.();
90
+ return;
91
+ }
92
+ const response = message;
93
+ const pending = this.pendingRequests.get(response.requestId);
94
+ if (pending) {
95
+ clearTimeout(pending.timeout);
96
+ this.pendingRequests.delete(response.requestId);
97
+ if (response.success) {
98
+ pending.resolve(response);
99
+ } else {
100
+ pending.reject(new Error(response.error || "Unknown worker error"));
101
+ }
102
+ }
103
+ }
104
+ /**
105
+ * Handle worker errors
106
+ */
107
+ handleError(error) {
108
+ console.error("[maps-core] Spatial worker error:", error);
109
+ for (const [requestId, pending] of this.pendingRequests) {
110
+ clearTimeout(pending.timeout);
111
+ pending.reject(new Error(`Worker error: ${error.message}`));
112
+ this.pendingRequests.delete(requestId);
113
+ }
114
+ }
115
+ /**
116
+ * Generate a unique request ID
117
+ */
118
+ generateRequestId() {
119
+ return `req_${++this.requestCounter}_${Date.now()}`;
120
+ }
121
+ /**
122
+ * Send a request to the worker and wait for response
123
+ */
124
+ async sendRequest(request) {
125
+ if (!this.worker) {
126
+ throw new Error("Worker not available");
127
+ }
128
+ await this.readyPromise;
129
+ return new Promise((resolve, reject) => {
130
+ const timeout = setTimeout(() => {
131
+ this.pendingRequests.delete(request.requestId);
132
+ reject(new Error(`Request timeout: ${request.type}`));
133
+ }, this.options.requestTimeout);
134
+ this.pendingRequests.set(request.requestId, {
135
+ resolve,
136
+ reject,
137
+ timeout
138
+ });
139
+ this.worker.postMessage(request);
140
+ });
141
+ }
142
+ /**
143
+ * Initialize the worker with GeoJSON data
144
+ *
145
+ * @param data The GeoJSON FeatureCollection to index
146
+ * @returns Initialization result with build statistics
147
+ */
148
+ async initialize(data) {
149
+ const startTime = performance.now();
150
+ const request = {
151
+ type: "initialize",
152
+ requestId: this.generateRequestId(),
153
+ data,
154
+ options: {
155
+ useRTree: this.options.useRTree,
156
+ gridTargetCells: this.options.gridTargetCells,
157
+ rtreeMaxEntries: this.options.rtreeMaxEntries
158
+ }
159
+ };
160
+ try {
161
+ const response = await this.sendRequest(request);
162
+ this.initialized = response.success;
163
+ return {
164
+ success: response.success,
165
+ featureCount: response.stats?.featureCount ?? 0,
166
+ indexType: response.stats?.indexType ?? "rtree",
167
+ buildTimeMs: response.stats?.buildTimeMs ?? performance.now() - startTime,
168
+ error: response.error
169
+ };
170
+ } catch (error) {
171
+ return {
172
+ success: false,
173
+ featureCount: 0,
174
+ indexType: "rtree",
175
+ buildTimeMs: performance.now() - startTime,
176
+ error: error instanceof Error ? error.message : "Unknown error"
177
+ };
178
+ }
179
+ }
180
+ /**
181
+ * Query features within the given bounds
182
+ *
183
+ * @param bounds Viewport bounds [[swLng, swLat], [neLng, neLat]]
184
+ * @param options Query options
185
+ * @returns Query result with features and statistics
186
+ */
187
+ async query(bounds, options = {}) {
188
+ if (!this.initialized) {
189
+ return {
190
+ success: false,
191
+ data: { type: "FeatureCollection", features: [] },
192
+ stats: {
193
+ totalFeatures: 0,
194
+ visibleFeatures: 0,
195
+ culledPercent: 0,
196
+ cellsChecked: 0,
197
+ totalCells: 0
198
+ },
199
+ queryTimeMs: 0,
200
+ error: "Worker not initialized"
201
+ };
202
+ }
203
+ const startTime = performance.now();
204
+ const request = {
205
+ type: "query",
206
+ requestId: this.generateRequestId(),
207
+ bounds,
208
+ options
209
+ };
210
+ try {
211
+ const response = await this.sendRequest(request);
212
+ const queryTimeMs = performance.now() - startTime;
213
+ const rawStats = response.stats;
214
+ const stats = rawStats ? {
215
+ totalFeatures: rawStats.totalFeatures,
216
+ visibleFeatures: rawStats.visibleFeatures,
217
+ culledPercent: rawStats.culledPercent,
218
+ cellsChecked: "cellsChecked" in rawStats ? rawStats.cellsChecked : 0,
219
+ totalCells: "totalCells" in rawStats ? rawStats.totalCells : 0
220
+ } : {
221
+ totalFeatures: 0,
222
+ visibleFeatures: 0,
223
+ culledPercent: 0,
224
+ cellsChecked: 0,
225
+ totalCells: 0
226
+ };
227
+ return {
228
+ success: response.success,
229
+ data: response.data ?? { type: "FeatureCollection", features: [] },
230
+ stats,
231
+ queryTimeMs,
232
+ error: response.error
233
+ };
234
+ } catch (error) {
235
+ return {
236
+ success: false,
237
+ data: { type: "FeatureCollection", features: [] },
238
+ stats: {
239
+ totalFeatures: 0,
240
+ visibleFeatures: 0,
241
+ culledPercent: 0,
242
+ cellsChecked: 0,
243
+ totalCells: 0
244
+ },
245
+ queryTimeMs: performance.now() - startTime,
246
+ error: error instanceof Error ? error.message : "Unknown error"
247
+ };
248
+ }
249
+ }
250
+ /**
251
+ * Query with predictive pan loading
252
+ *
253
+ * Tracks viewport movement and expands buffer in the predicted
254
+ * direction of panning to eliminate pop-in.
255
+ *
256
+ * @param bounds Current viewport bounds
257
+ * @param options Predictive query options
258
+ * @returns Query result with velocity info
259
+ */
260
+ async queryPredictive(bounds, options = {}) {
261
+ if (!this.initialized) {
262
+ return {
263
+ success: false,
264
+ data: { type: "FeatureCollection", features: [] },
265
+ stats: {
266
+ totalFeatures: 0,
267
+ visibleFeatures: 0,
268
+ culledPercent: 0,
269
+ cellsChecked: 0,
270
+ totalCells: 0
271
+ },
272
+ queryTimeMs: 0,
273
+ velocity: { lngPerSec: 0, latPerSec: 0, magnitude: 0 },
274
+ updated: false,
275
+ error: "Worker not initialized"
276
+ };
277
+ }
278
+ const startTime = performance.now();
279
+ const request = {
280
+ type: "predictive-query",
281
+ requestId: this.generateRequestId(),
282
+ bounds,
283
+ timestamp: performance.now(),
284
+ options
285
+ };
286
+ try {
287
+ const response = await this.sendRequest(request);
288
+ const queryTimeMs = performance.now() - startTime;
289
+ return {
290
+ success: response.success,
291
+ data: response.data ?? { type: "FeatureCollection", features: [] },
292
+ stats: response.stats ?? {
293
+ totalFeatures: 0,
294
+ visibleFeatures: 0,
295
+ culledPercent: 0,
296
+ cellsChecked: 0,
297
+ totalCells: 0
298
+ },
299
+ queryTimeMs,
300
+ velocity: response.velocity ?? { lngPerSec: 0, latPerSec: 0, magnitude: 0 },
301
+ updated: response.updated,
302
+ error: response.error
303
+ };
304
+ } catch (error) {
305
+ return {
306
+ success: false,
307
+ data: { type: "FeatureCollection", features: [] },
308
+ stats: {
309
+ totalFeatures: 0,
310
+ visibleFeatures: 0,
311
+ culledPercent: 0,
312
+ cellsChecked: 0,
313
+ totalCells: 0
314
+ },
315
+ queryTimeMs: performance.now() - startTime,
316
+ velocity: { lngPerSec: 0, latPerSec: 0, magnitude: 0 },
317
+ updated: false,
318
+ error: error instanceof Error ? error.message : "Unknown error"
319
+ };
320
+ }
321
+ }
322
+ /**
323
+ * Reset predictive pan state
324
+ *
325
+ * Call this when the user stops panning or when you want
326
+ * to clear the velocity tracking.
327
+ */
328
+ async resetPredictive() {
329
+ if (!this.worker) return;
330
+ const request = {
331
+ type: "reset-predictive",
332
+ requestId: this.generateRequestId()
333
+ };
334
+ await this.sendRequest(request);
335
+ }
336
+ /**
337
+ * Get current index statistics
338
+ */
339
+ async getStats() {
340
+ if (!this.initialized || !this.worker) {
341
+ return null;
342
+ }
343
+ const request = {
344
+ type: "get-stats",
345
+ requestId: this.generateRequestId()
346
+ };
347
+ try {
348
+ const response = await this.sendRequest(request);
349
+ return response.stats ?? null;
350
+ } catch {
351
+ return null;
352
+ }
353
+ }
354
+ /**
355
+ * Check if the client is initialized
356
+ */
357
+ isInitialized() {
358
+ return this.initialized;
359
+ }
360
+ /**
361
+ * Check if the worker is ready
362
+ */
363
+ isReady() {
364
+ return this.ready;
365
+ }
366
+ /**
367
+ * Terminate the worker and clean up resources
368
+ */
369
+ terminate() {
370
+ for (const [requestId, pending] of this.pendingRequests) {
371
+ clearTimeout(pending.timeout);
372
+ pending.reject(new Error("Worker terminated"));
373
+ this.pendingRequests.delete(requestId);
374
+ }
375
+ if (this.worker) {
376
+ this.worker.terminate();
377
+ this.worker = null;
378
+ }
379
+ this.initialized = false;
380
+ this.ready = false;
381
+ }
382
+ };
383
+ function createSpatialWorkerClient(options) {
384
+ return new SpatialWorkerClient(options);
385
+ }
386
+
387
+ export { SpatialWorkerClient, createSpatialWorkerClient };