@ml2drender/wasm 0.0.0-stage → 0.1.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/dist/index.js ADDED
@@ -0,0 +1,522 @@
1
+ const encoder = new TextEncoder();
2
+ const decoder = new TextDecoder();
3
+ const DEFAULT_TTL_MS = 5 * 60 * 1000;
4
+ const SUPPORTED_LAYERS = new Set([
5
+ 'background', 'fill', 'line', 'circle', 'raster', 'symbol', 'hillshade', 'color-relief', 'heatmap',
6
+ ]);
7
+ async function fetchResource(url) {
8
+ const response = await fetch(url);
9
+ if (!response.ok) {
10
+ await response.body?.cancel();
11
+ if (response.status === 404)
12
+ return null;
13
+ throw new Error(`Resource fetch failed: HTTP ${response.status} ${url}`);
14
+ }
15
+ return new Uint8Array(await response.arrayBuffer());
16
+ }
17
+ /** The bundled module, compiled once. */
18
+ let bundled;
19
+ async function loadWasm(module) {
20
+ if (!module) {
21
+ // Vite bundles this asset for browsers. Workers supply their imported module and
22
+ // never fetch or compile WASM at runtime. Fetched directly: `loadResource` serves the style.
23
+ if (!bundled) {
24
+ const url = new URL('../wasm/ml2drender_wasm.wasm', import.meta.url).href;
25
+ bundled = fetchResource(url).then((bytes) => {
26
+ if (bytes === null)
27
+ throw new Error(`WASM not found: ${url}`);
28
+ return WebAssembly.compile(bytes);
29
+ });
30
+ // A failed load is retried by the next call.
31
+ bundled.catch(() => { bundled = undefined; });
32
+ }
33
+ module = await bundled;
34
+ }
35
+ const instance = await WebAssembly.instantiate(module);
36
+ return instance.exports;
37
+ }
38
+ /** Copied output buffer of the last call. */
39
+ function output(w) {
40
+ return new Uint8Array(w.memory.buffer, w.out_ptr(), w.out_len()).slice();
41
+ }
42
+ function withBytes(w, bytes, call) {
43
+ const ptr = w.alloc(bytes.length);
44
+ new Uint8Array(w.memory.buffer, ptr, bytes.length).set(bytes);
45
+ try {
46
+ return call(ptr, bytes.length);
47
+ }
48
+ finally {
49
+ w.dealloc(ptr, bytes.length);
50
+ }
51
+ }
52
+ /**
53
+ * One WASM instance per module (the bundled one under `undefined`), shared by projections and by
54
+ * renderers that keep nothing between renders (`ttlMs` 0): memory freed by one render is reused by
55
+ * the next. (WASM memory never shrinks, and an instance per renderer holds its own until collected;
56
+ * on Cloudflare Workers all of it counts towards the isolate's 128 MB.) A renderer that keeps
57
+ * resources gets its own instance, which goes with it.
58
+ */
59
+ const instances = new Map();
60
+ /** Instances a trap (Rust panic or out of memory) left in an unknown state. */
61
+ const brokenInstances = new WeakSet();
62
+ function sharedWasm(module) {
63
+ let instance = instances.get(module);
64
+ if (!instance) {
65
+ const loading = loadWasm(module);
66
+ instances.set(module, loading);
67
+ // A failed load is retried by the next call.
68
+ loading.catch(() => { if (instances.get(module) === loading)
69
+ instances.delete(module); });
70
+ instance = loading;
71
+ }
72
+ return instance;
73
+ }
74
+ /** Later loads get a new instance. */
75
+ function discardInstance(module, instance, w) {
76
+ brokenInstances.add(w);
77
+ if (instances.get(module) === instance)
78
+ instances.delete(module);
79
+ }
80
+ const freeProjection = new FinalizationRegistry(({ w, handle }) => w.projection_free(handle));
81
+ /**
82
+ * Load a PROJJSON CRS the way `MapRenderer.projected` reads `Crs.projjson`, e.g. to compute
83
+ * tile bounds or to register the CRS with MapLibre's `addProjection`, so both agree on the CRS.
84
+ * Throws for a CRS the renderer does not support.
85
+ */
86
+ export async function loadProjection(projjson, options = {}) {
87
+ return (await loadProjectionFactory(options))(projjson);
88
+ }
89
+ /**
90
+ * Load the WASM once and return a synchronous `loadProjection`, for hosts that must build a
91
+ * projection without awaiting, such as MapLibre's worker `setProjectionHandler`.
92
+ */
93
+ export async function loadProjectionFactory(options = {}) {
94
+ const w = await sharedWasm(options.wasm);
95
+ return (projjson) => {
96
+ if (!projjson || typeof projjson !== 'object')
97
+ throw new TypeError('projjson must be a PROJJSON object');
98
+ const handle = withBytes(w, encoder.encode(JSON.stringify(projjson)), (ptr, len) => w.projection_new(ptr, len));
99
+ if (!handle)
100
+ throw new Error(decoder.decode(output(w)));
101
+ // A fresh view per call: memory growth detaches earlier ones.
102
+ const xy = () => [...new Float64Array(w.memory.buffer, w.xy_ptr(), 2)];
103
+ // The methods hold `owner`, which frees the handle once collected: callers may keep only them.
104
+ const owner = { handle };
105
+ const projection = {
106
+ forward: ([lng, lat]) => {
107
+ w.projection_forward(owner.handle, lng, lat);
108
+ return xy();
109
+ },
110
+ inverse: ([x, y]) => {
111
+ w.projection_inverse(owner.handle, x, y);
112
+ return xy();
113
+ },
114
+ };
115
+ freeProjection.register(owner, { w, handle });
116
+ return projection;
117
+ };
118
+ }
119
+ function viewArgs(view) {
120
+ const [lng, lat] = view.center;
121
+ for (const [name, value] of Object.entries({ lng, lat, zoom: view.zoom, bearing: view.bearing ?? 0 })) {
122
+ if (!Number.isFinite(value))
123
+ throw new RangeError(`${name} must be finite`);
124
+ }
125
+ return [lng, lat, view.zoom, view.bearing ?? 0, ...sizeArgs(view), marginArg(view.margin)];
126
+ }
127
+ /** Width and height (positive uint32 integers) and a finite, positive pixel ratio. */
128
+ function sizeArgs({ width, height, pixelRatio = 1 }) {
129
+ for (const [name, value] of [['width', width], ['height', height]]) {
130
+ if (!Number.isInteger(value) || value < 1 || value > 0xffffffff)
131
+ throw new RangeError(`${name} must be a positive uint32 integer`);
132
+ }
133
+ if (!Number.isFinite(pixelRatio) || pixelRatio <= 0)
134
+ throw new RangeError('pixelRatio must be finite and positive');
135
+ return [width, height, pixelRatio];
136
+ }
137
+ function tileView({ z, x, y, tileSize = 256, pixelRatio, margin }) {
138
+ const n = 2 ** z;
139
+ if (!Number.isInteger(z) || z < 0 || z > 30)
140
+ throw new RangeError('z must be an integer in 0..=30');
141
+ if (!Number.isInteger(x) || !Number.isInteger(y) || x < 0 || y < 0 || x >= n || y >= n)
142
+ throw new RangeError('x and y must be integers in 0..2^z');
143
+ if (!Number.isInteger(tileSize) || tileSize < 1)
144
+ throw new RangeError('tileSize must be a positive integer');
145
+ return {
146
+ center: [((x + 0.5) / n) * 360 - 180, Math.atan(Math.sinh(Math.PI * (1 - (2 * (y + 0.5)) / n))) * 180 / Math.PI],
147
+ // MapLibre's zoom puts the world in 512 CSS pixels at zoom 0.
148
+ zoom: z + Math.log2(tileSize / 512),
149
+ width: tileSize,
150
+ height: tileSize,
151
+ pixelRatio,
152
+ margin,
153
+ };
154
+ }
155
+ const MAX_LAT = 85.0511287798066;
156
+ function fitLngLat({ bbox: [west, south, east, north], size, pixelRatio, margin }) {
157
+ if (!Number.isInteger(size) || size < 1 || size > 0xffffffff)
158
+ throw new RangeError('size must be a positive uint32 integer');
159
+ if (east < west)
160
+ east += 360;
161
+ [south, north] = [south, north].map((lat) => Math.max(-MAX_LAT, Math.min(MAX_LAT, lat)));
162
+ if (!(east > west && north > south))
163
+ throw new RangeError('bbox must be [west, south, east, north] with a non-empty area');
164
+ // Web Mercator y in world units (0 at the north edge, 1 at the south edge).
165
+ const my = (lat) => (1 - Math.log(Math.tan(Math.PI / 4 + (lat * Math.PI) / 360)) / Math.PI) / 2;
166
+ const [y0, y1] = [my(north), my(south)];
167
+ const [dx, dy] = [(east - west) / 360, y1 - y0];
168
+ // CSS pixels per world: the long side spans `size`.
169
+ const scale = size / Math.max(dx, dy);
170
+ const lng = (west + east) / 2;
171
+ return {
172
+ center: [lng > 180 ? lng - 360 : lng, Math.atan(Math.sinh(Math.PI * (1 - (y0 + y1)))) * 180 / Math.PI],
173
+ zoom: Math.log2(scale / 512),
174
+ width: Math.max(1, Math.round(dx * scale)),
175
+ height: Math.max(1, Math.round(dy * scale)),
176
+ pixelRatio,
177
+ margin,
178
+ };
179
+ }
180
+ function marginArg(value = 0) {
181
+ const margin = nonnegative(value, 'margin');
182
+ if (!Number.isInteger(margin) || margin > 0xffffffff)
183
+ throw new RangeError('margin must be a uint32 integer');
184
+ return margin;
185
+ }
186
+ function nonnegative(value, name) {
187
+ if (!Number.isFinite(value) || value < 0)
188
+ throw new RangeError(`${name} must be a finite, non-negative number`);
189
+ return value;
190
+ }
191
+ function flattenFillExtrusion(layer) {
192
+ const { type, paint, layout, ...base } = layer;
193
+ // Shared paint properties have the same defaults; leaving absent values unset
194
+ // preserves them without duplicating Style Spec defaults. Expressions stay intact.
195
+ return {
196
+ ...base,
197
+ type: 'fill',
198
+ layout: { visibility: layout?.visibility },
199
+ paint: {
200
+ 'fill-color': paint?.['fill-extrusion-color'],
201
+ 'fill-opacity': paint?.['fill-extrusion-opacity'],
202
+ 'fill-pattern': paint?.['fill-extrusion-pattern'],
203
+ 'fill-translate': paint?.['fill-extrusion-translate'],
204
+ 'fill-translate-anchor': paint?.['fill-extrusion-translate-anchor'],
205
+ 'fill-color-transition': paint?.['fill-extrusion-color-transition'],
206
+ 'fill-opacity-transition': paint?.['fill-extrusion-opacity-transition'],
207
+ 'fill-pattern-transition': paint?.['fill-extrusion-pattern-transition'],
208
+ 'fill-translate-transition': paint?.['fill-extrusion-translate-transition'],
209
+ },
210
+ };
211
+ }
212
+ function prepareStyle(style, transform = flattenFillExtrusion) {
213
+ if (!style || typeof style !== 'object' || !Array.isArray(style.layers)) {
214
+ throw new Error('Style must contain a layers array');
215
+ }
216
+ const layers = style.layers.map((layer) => {
217
+ if (!layer || typeof layer !== 'object' || !('type' in layer) || layer.type !== 'fill-extrusion')
218
+ return layer;
219
+ const replacement = transform(layer);
220
+ if (!replacement || typeof replacement.id !== 'string' || !SUPPORTED_LAYERS.has(replacement.type)) {
221
+ throw new Error(`Invalid replacement for fill-extrusion layer ${'id' in layer ? String(layer.id) : ''}`);
222
+ }
223
+ return replacement;
224
+ });
225
+ return encoder.encode(JSON.stringify({ ...style, layers }));
226
+ }
227
+ /**
228
+ * Render a MapLibre Style as a static 2D RGBA image.
229
+ *
230
+ * @example
231
+ * ```ts
232
+ * const renderer = await MapRenderer.init(style);
233
+ * const image = await renderer.renderTile({ z: 5, x: 28, y: 12 });
234
+ * const png = image.toPng();
235
+ * ```
236
+ */
237
+ export class MapRenderer {
238
+ /** The reused core (none with a TTL of 0). */
239
+ core;
240
+ /** A trap (Rust panic or out of memory) left the WASM instance in an unknown state. */
241
+ broken;
242
+ /** Fetches in flight, shared by overlapping renders, with the newest ticket that awaits each. */
243
+ pending = new Map();
244
+ /** Tickets of the renders in progress: WASM keeps the tiles they need (`renderer_set_ticket`). */
245
+ tickets = new Set();
246
+ lastTicket = 0;
247
+ module;
248
+ instance;
249
+ wasm;
250
+ style;
251
+ /** The style as given, for `toStyle`. */
252
+ original;
253
+ loadResource;
254
+ ttlMs;
255
+ constructor(module, instance, wasm, style, original, loadResource, ttlMs) {
256
+ this.module = module;
257
+ this.instance = instance;
258
+ this.wasm = wasm;
259
+ this.style = style;
260
+ this.original = original;
261
+ this.loadResource = loadResource;
262
+ this.ttlMs = ttlMs;
263
+ }
264
+ /** Snapshot a style object and load the renderer. Resource URLs are passed to `loadResource` as written. */
265
+ static async init(style, options = {}) {
266
+ const ttlMs = options.cache?.ttlMs ?? DEFAULT_TTL_MS;
267
+ if (ttlMs !== Infinity)
268
+ nonnegative(ttlMs, 'cache.ttlMs');
269
+ const loadResource = options.loadResource ?? fetchResource;
270
+ const prepared = prepareStyle(style, options.transformFillExtrusion);
271
+ const instance = ttlMs === 0 ? sharedWasm(options.wasm) : loadWasm(options.wasm);
272
+ return new MapRenderer(options.wasm, instance, await instance, prepared, structuredClone(style), loadResource, ttlMs);
273
+ }
274
+ /** Fetch required resources and return a new RGBA image of a Web Mercator camera. */
275
+ async renderView(view) {
276
+ const args = viewArgs(view);
277
+ return this.draw(view, args, (handle) => this.wasm.renderer_set_view(handle, ...args));
278
+ }
279
+ /** `renderView` of an XYZ tile of the Web Mercator grid. */
280
+ async renderTile(tile) {
281
+ return this.renderView(tileView(tile));
282
+ }
283
+ /** `renderView` of a longitude/latitude box, `box.size` CSS pixels on the long side. */
284
+ async render(box) {
285
+ return this.renderView(fitLngLat(box));
286
+ }
287
+ /** This renderer drawing in `crs`, on its tile grid. Resources fetched for one CRS serve the others too. */
288
+ projected(crs) {
289
+ if (typeof crs.name !== 'string' || !crs.name)
290
+ throw new TypeError('crs.name must be a name');
291
+ if (!crs.projjson || typeof crs.projjson !== 'object')
292
+ throw new TypeError('crs.projjson must be a PROJJSON object');
293
+ const { origin, extentAtZoom0 } = crs.tileMatrixSet;
294
+ if (!origin.every(Number.isFinite) || !(extentAtZoom0 > 0 && Number.isFinite(extentAtZoom0))) {
295
+ throw new RangeError('crs.tileMatrixSet must have a finite origin and a finite, positive extentAtZoom0');
296
+ }
297
+ const projjson = encoder.encode(JSON.stringify(crs.projjson));
298
+ // The box of tile z/x/y of the grid.
299
+ const box = ({ z, x, y }) => {
300
+ const n = 2 ** z;
301
+ if (!Number.isInteger(z) || z < 0 || z > 30)
302
+ throw new RangeError('z must be an integer in 0..=30');
303
+ if (!Number.isInteger(x) || !Number.isInteger(y) || x < 0 || y < 0 || x >= n || y >= n)
304
+ throw new RangeError('x and y must be integers in 0..2^z');
305
+ const s = extentAtZoom0 / n;
306
+ const [minX, maxY] = [origin[0] + x * s, origin[1] - y * s];
307
+ return [minX, maxY - s, minX + s, maxY];
308
+ };
309
+ const render = (view, bearing) => this.draw(view, ...this.projectedArgs(projjson, view, bearing));
310
+ return {
311
+ crs,
312
+ render: (view) => render(view),
313
+ renderTile: ({ tileSize = 256, pixelRatio, margin, ...tile }) => {
314
+ if (!Number.isInteger(tileSize) || tileSize < 1)
315
+ throw new RangeError('tileSize must be a positive integer');
316
+ return render({ bbox: box(tile), width: tileSize, height: tileSize, pixelRatio, margin });
317
+ },
318
+ renderView: async ({ center: [lng, lat], zoom, bearing = 0, width, height, pixelRatio, margin }) => {
319
+ if (![lng, lat, zoom, bearing].every(Number.isFinite))
320
+ throw new RangeError('center, zoom and bearing must be finite');
321
+ const [x, y] = this.forward(projjson, lng, lat);
322
+ if (!Number.isFinite(x) || !Number.isFinite(y))
323
+ throw new RangeError('center is outside the CRS');
324
+ // CRS units per CSS pixel.
325
+ const unit = extentAtZoom0 / (512 * 2 ** zoom);
326
+ const [w, h] = [(width / 2) * unit, (height / 2) * unit];
327
+ // The box at bearing 0, which the core turns around its center.
328
+ return render({ bbox: [x - w, y - h, x + w, y + h], width, height, pixelRatio, margin }, bearing);
329
+ },
330
+ getTile: (tile) => {
331
+ if (typeof tile.source !== 'string' || !tile.source)
332
+ throw new TypeError('source must be a source id');
333
+ const view = { bbox: box(tile), width: 512, height: 512 };
334
+ return this.run(...this.projectedArgs(projjson, view), encoder.encode(tile.source), this.wasm.renderer_export_tile);
335
+ },
336
+ toStyle: ({ tiles }) => {
337
+ const style = this.original;
338
+ const sources = {};
339
+ for (const [id, source] of Object.entries(style.sources)) {
340
+ const common = { tiles: [tiles(id)], ...('attribution' in source && source.attribution ? { attribution: source.attribution } : {}) };
341
+ if (source.type === 'vector' || source.type === 'geojson')
342
+ sources[id] = { type: 'vector', ...common };
343
+ else if (source.type === 'raster' || source.type === 'image')
344
+ sources[id] = { type: 'raster', tileSize: 512, ...common };
345
+ else if (source.type === 'raster-dem')
346
+ sources[id] = { type: 'raster-dem', tileSize: 512, encoding: 'terrarium', ...common };
347
+ }
348
+ const layers = style.layers.flatMap((layer) => {
349
+ if (!('source' in layer) || typeof layer.source !== 'string')
350
+ return [layer];
351
+ if (!sources[layer.source])
352
+ return [];
353
+ return [style.sources[layer.source].type === 'geojson' ? { ...layer, 'source-layer': layer.source } : layer];
354
+ });
355
+ return structuredClone({ ...style, projection: { type: crs.name }, sources, layers });
356
+ },
357
+ };
358
+ }
359
+ /** `[lng, lat]` in the CRS `projjson` (encoded); NaN where the CRS has no point. */
360
+ forward(projjson, lng, lat) {
361
+ this.assertUsable();
362
+ const w = this.wasm;
363
+ const handle = this.withBytes(projjson, (ptr, len) => w.projection_new(ptr, len));
364
+ if (!handle)
365
+ throw new Error(decoder.decode(this.output()));
366
+ w.projection_forward(handle, lng, lat);
367
+ const xy = [...new Float64Array(w.memory.buffer, w.xy_ptr(), 2)];
368
+ w.projection_free(handle);
369
+ return xy;
370
+ }
371
+ assertUsable() {
372
+ if (this.broken || brokenInstances.has(this.wasm)) {
373
+ throw new Error('The renderer crashed earlier; create a new one', { cause: this.broken });
374
+ }
375
+ }
376
+ /** The core arguments and `setView` of a view of the CRS `projjson` (encoded), turned around its center by `bearing`. */
377
+ projectedArgs(projjson, view, bearing = 0) {
378
+ const margin = marginArg(view.margin);
379
+ const size = sizeArgs(view);
380
+ if (!view.bbox.every(Number.isFinite))
381
+ throw new RangeError('bbox must be finite');
382
+ // The initial camera is replaced before the first `needs`.
383
+ return [[0, 0, 0, 0, ...size, 0], (handle) => {
384
+ const ok = this.withBytes(projjson, (ptr, len) => this.wasm.renderer_set_projected_view(handle, ptr, len, ...view.bbox, bearing, ...size, margin));
385
+ if (!ok)
386
+ throw new Error(decoder.decode(this.output()));
387
+ }];
388
+ }
389
+ /** The fetch-and-render loop of images; `setView` points a core at the view. */
390
+ async draw(view, args, setView) {
391
+ const w = this.wasm;
392
+ const bytes = await this.run(args, setView, new Uint8Array(), w.renderer_render);
393
+ const width = Math.round(view.width * (view.pixelRatio ?? 1));
394
+ const height = Math.round(view.height * (view.pixelRatio ?? 1));
395
+ const data = new Uint8ClampedArray(bytes.buffer, bytes.byteOffset, bytes.byteLength);
396
+ const encode = (format) => () => {
397
+ if (!this.withBytes(bytes, (ptr, len) => format(ptr, len, width, height))) {
398
+ throw new Error(decoder.decode(this.output()));
399
+ }
400
+ return this.output();
401
+ };
402
+ return {
403
+ width, height, data, toPng: encode(w.encode_png), toWebp: encode(w.encode_webp),
404
+ toJpeg: (quality) => {
405
+ if (!Number.isFinite(quality))
406
+ throw new RangeError('quality must be finite');
407
+ const q = Math.min(100, Math.max(1, Math.round(quality)));
408
+ return encode((ptr, len, width, height) => w.encode_jpeg(ptr, len, width, height, q))();
409
+ },
410
+ };
411
+ }
412
+ /**
413
+ * The fetch loop of the view `setView` points a core at, for the export source `source` (empty: none), then
414
+ * `finish(handle, oldest)`'s output.
415
+ */
416
+ async run(args, setView, source, finish) {
417
+ try {
418
+ return await this.runOnce(args, setView, source, finish);
419
+ }
420
+ catch (error) {
421
+ if (error instanceof WebAssembly.RuntimeError) {
422
+ this.broken = error;
423
+ discardInstance(this.module, this.instance, this.wasm);
424
+ }
425
+ throw error;
426
+ }
427
+ }
428
+ async runOnce(args, setView, source, finish) {
429
+ const w = this.wasm;
430
+ const core = this.acquire(args);
431
+ const ticket = ++this.lastTicket;
432
+ this.tickets.add(ticket);
433
+ try {
434
+ // Other renders may move the camera while this one awaits resources.
435
+ for (let round = 0;; round++) {
436
+ setView(core.handle);
437
+ if (!this.withBytes(source, (ptr, len) => w.renderer_set_export_source(core.handle, ptr, len))) {
438
+ throw new Error(decoder.decode(this.output()));
439
+ }
440
+ w.renderer_set_ticket(core.handle, ticket);
441
+ const count = w.renderer_needs(core.handle);
442
+ if (count === 0)
443
+ break;
444
+ if (round >= 32)
445
+ throw new Error('Resource requests did not settle');
446
+ const urls = decoder.decode(this.output()).split('\n');
447
+ await Promise.all(urls.map((url) => this.fetch(core, url, ticket)));
448
+ }
449
+ // Tickets increase, so the first in the set is the oldest in progress.
450
+ const oldest = this.tickets.values().next().value;
451
+ if (!finish(core.handle, oldest))
452
+ throw new Error(decoder.decode(this.output()));
453
+ // Own the bytes before another render can overwrite or grow WASM memory.
454
+ return this.output();
455
+ }
456
+ finally {
457
+ this.tickets.delete(ticket);
458
+ this.release(core);
459
+ }
460
+ }
461
+ /**
462
+ * Fetch `url` once and provide it to `core`, which requested it, before it leaves `pending`. It is
463
+ * kept for the newest render awaiting it: while any of them is in progress, the oldest ticket in
464
+ * progress is at most that one.
465
+ */
466
+ fetch(core, url, ticket) {
467
+ const shared = this.pending.get(url);
468
+ if (shared) {
469
+ shared.ticket = Math.max(shared.ticket, ticket);
470
+ return shared.request;
471
+ }
472
+ const entry = { ticket, request: Promise.resolve() };
473
+ entry.request = this.loadResource(url).then((bytes) => {
474
+ // A freed core was retired by the TTL; its successor fetches again.
475
+ if (core.retired && core.active === 0)
476
+ return;
477
+ this.wasm.renderer_set_ticket(core.handle, entry.ticket);
478
+ this.withBytes(encoder.encode(url), (urlPtr, urlLen) => this.withBytes(bytes ?? new Uint8Array(), (dataPtr, dataLen) => this.wasm.renderer_provide(core.handle, urlPtr, urlLen, dataPtr, dataLen, bytes === null ? 0 : 1)));
479
+ }).finally(() => this.pending.delete(url));
480
+ this.pending.set(url, entry);
481
+ return entry.request;
482
+ }
483
+ /**
484
+ * The current WASM renderer, replaced once older than the cache TTL. With a TTL of 0, each
485
+ * render gets its own, freed when the render ends.
486
+ */
487
+ acquire(args) {
488
+ this.assertUsable();
489
+ const now = performance.now();
490
+ if (this.core && now - this.core.createdAt >= this.ttlMs) {
491
+ this.core.retired = true;
492
+ if (this.core.active === 0)
493
+ this.wasm.renderer_free(this.core.handle);
494
+ this.core = undefined;
495
+ }
496
+ let core = this.core;
497
+ if (!core) {
498
+ const handle = this.withBytes(this.style, (ptr, len) => this.wasm.renderer_new(ptr, len, ...args));
499
+ if (!handle)
500
+ throw new Error(decoder.decode(this.output()));
501
+ // A core that is not reused drops buckets as soon as they are drawn.
502
+ if (this.ttlMs === 0)
503
+ this.wasm.renderer_set_keep_buckets(handle, 0);
504
+ core = { handle, createdAt: now, active: 0, retired: this.ttlMs === 0 };
505
+ if (!core.retired)
506
+ this.core = core;
507
+ }
508
+ core.active++;
509
+ return core;
510
+ }
511
+ release(core) {
512
+ core.active--;
513
+ if (core.retired && core.active === 0)
514
+ this.wasm.renderer_free(core.handle);
515
+ }
516
+ output() {
517
+ return output(this.wasm);
518
+ }
519
+ withBytes(bytes, call) {
520
+ return withBytes(this.wasm, bytes, call);
521
+ }
522
+ }
package/package.json CHANGED
@@ -1,6 +1,45 @@
1
1
  {
2
2
  "name": "@ml2drender/wasm",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "MapLibre style 2D renderer in pure Rust / WebAssembly, no GPU",
5
+ "license": "BSD-3-Clause",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/Kanahiro/ml2drender.git",
9
+ "directory": "packages/ml2drender"
10
+ },
11
+ "homepage": "https://kanahiro.github.io/ml2drender/",
12
+ "type": "module",
13
+ "engines": {
14
+ "node": "^22.23.4 || ^24.22.1 || >=26.12.1"
15
+ },
16
+ "exports": {
17
+ ".": {
18
+ "types": "./dist/index.d.ts",
19
+ "default": "./dist/index.js"
20
+ },
21
+ "./renderer.wasm": {
22
+ "types": "./src/wasm.d.ts",
23
+ "default": "./wasm/ml2drender_wasm.wasm"
24
+ }
25
+ },
26
+ "files": [
27
+ "dist",
28
+ "src/wasm.d.ts",
29
+ "wasm"
30
+ ],
31
+ "peerDependencies": {
32
+ "@maplibre/maplibre-gl-style-spec": "^26.4.4"
33
+ },
34
+ "devDependencies": {
35
+ "@maplibre/maplibre-gl-style-spec": "26.4.4",
36
+ "typedoc": "0.28.20",
37
+ "typescript": "6.0.3"
38
+ },
39
+ "scripts": {
40
+ "build": "tsc -p tsconfig.build.json",
41
+ "typecheck": "tsc --noEmit",
42
+ "test": "node tests/single-flight.ts && node tests/shared-instance.ts && node tests/projected-view.ts",
43
+ "docs": "typedoc"
44
+ }
6
45
  }
package/src/wasm.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ /** The precompiled module provided by the host bundler (e.g. Wrangler). */
2
+ declare const wasm: WebAssembly.Module;
3
+ export default wasm;
Binary file