@dirkwa/s-100 0.0.0-stage → 0.0.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,321 @@
1
+ // Merges S-101 update files (.001, .002, ...) into the records of their base cell, as S-100 Part 10a
2
+ // describes: whole records are inserted, deleted or modified, and a modified record changes field by field.
3
+ import { DELETE, INSERT, MODIFY } from "./s101-records.js";
4
+ const key = (rcnm, rcid) => `${rcnm}:${rcid}`;
5
+ class UpdateError extends Error {
6
+ }
7
+ function fail(rec, msg) {
8
+ throw new UpdateError(`${rec.tag} ${rec.rcid}: ${msg}`);
9
+ }
10
+ /**
11
+ * Applies ATTR-like rows to an attribute tree. In a base record every row inserts; in an update a row
12
+ * inserts, deletes or modifies the sibling it names by code and ATIX, under the parent its PAIX names
13
+ * among the update's own rows.
14
+ */
15
+ export function applyAttrRows(roots, rows, isBase, rec) {
16
+ const byRow = new Map();
17
+ rows.forEach((r, i) => {
18
+ const parent = r.paix > 0 ? byRow.get(r.paix) : undefined;
19
+ if (r.paix > 0 && !parent)
20
+ fail(rec, `attribute row ${i + 1} names missing parent ${r.paix}`);
21
+ const siblings = parent ? parent.children : roots;
22
+ if (r.atin === INSERT) {
23
+ let pos = siblings.findIndex((c) => c.code === r.code && c.atix >= r.atix);
24
+ if (pos < 0)
25
+ pos = siblings.length;
26
+ if (!isBase)
27
+ for (const c of siblings.slice(pos))
28
+ if (c.code === r.code)
29
+ c.atix++;
30
+ const node = { code: r.code, atix: r.atix, value: r.value, children: [] };
31
+ siblings.splice(pos, 0, node);
32
+ byRow.set(i + 1, node);
33
+ }
34
+ else if (r.atin === DELETE || r.atin === MODIFY) {
35
+ const pos = siblings.findIndex((c) => c.code === r.code && c.atix === r.atix);
36
+ if (pos < 0)
37
+ fail(rec, `attribute ${r.code}[${r.atix}] to ${r.atin === DELETE ? 'delete' : 'modify'} not found`);
38
+ if (r.atin === DELETE) {
39
+ const [gone] = siblings.splice(pos, 1);
40
+ for (const [row, node] of byRow)
41
+ if (contains(gone, node))
42
+ byRow.delete(row);
43
+ }
44
+ else {
45
+ siblings[pos].value = r.value;
46
+ byRow.set(i + 1, siblings[pos]);
47
+ }
48
+ }
49
+ else
50
+ fail(rec, `invalid ATIN ${r.atin}`);
51
+ });
52
+ }
53
+ function contains(tree, node) {
54
+ return tree === node || tree.children.some((c) => contains(c, node));
55
+ }
56
+ const toAssoc = (a, rec) => {
57
+ const attrs = [];
58
+ applyAttrRows(attrs, a.attrs, true, rec);
59
+ return { rrnm: a.rrnm, rrid: a.rrid, association: a.association, role: a.role, attrs };
60
+ };
61
+ // A record's ATTR fields only split one attribute set, so updates address it as a whole; PAIX stays
62
+ // local to each field.
63
+ function attrTrees(r) {
64
+ const roots = [];
65
+ for (const rows of r.attr)
66
+ applyAttrRows(roots, rows, true, r);
67
+ return roots;
68
+ }
69
+ function toRec(r) {
70
+ // Shares the coordinate lists with the parsed record rather than copying them.
71
+ return {
72
+ ...r,
73
+ attr: attrTrees(r),
74
+ inas: r.inas.map((a) => toAssoc(a, r)),
75
+ fasc: r.fasc.map((a) => toAssoc(a, r))
76
+ };
77
+ }
78
+ /** A copy an update can edit: attribute trees change in place, every other list is replaced. */
79
+ const editable = (r) => ({
80
+ ...r,
81
+ attr: structuredClone(r.attr),
82
+ inas: structuredClone(r.inas),
83
+ fasc: structuredClone(r.fasc)
84
+ });
85
+ export function baseCell(file) {
86
+ if (file.info.profile !== 1)
87
+ throw new UpdateError(`${file.info.name}: not a base cell (PROF ${file.info.profile})`);
88
+ const records = new Map();
89
+ for (const r of file.records)
90
+ records.set(key(r.rcnm, r.rcid), toRec(r));
91
+ return { info: file.info, records, cancelled: false, updates: 0 };
92
+ }
93
+ const stem = (name) => name.replace(/\.\d{3}$/, '');
94
+ /** DSED is "edition.update", e.g. "10.0" for a new edition and "10.1" for its first update. */
95
+ function editionUpdate(dsed) {
96
+ const m = /^(\d+)\.(\d+)$/.exec(dsed);
97
+ return m ? [Number(m[1]), Number(m[2])] : undefined;
98
+ }
99
+ function checkSequence(cell, info) {
100
+ const name = info.name;
101
+ if (info.profile !== 2)
102
+ throw new UpdateError(`${name}: not an update file (PROF ${info.profile})`);
103
+ if (stem(name) !== stem(cell.info.name))
104
+ throw new UpdateError(`${name}: update for another cell than ${cell.info.name}`);
105
+ if (info.edition === '0')
106
+ return;
107
+ const current = editionUpdate(cell.info.edition);
108
+ const next = editionUpdate(info.edition);
109
+ if (!next)
110
+ throw new UpdateError(`${name}: edition "${info.edition}" is not edition.update`);
111
+ if (current && (next[0] !== current[0] || next[1] !== current[1] + 1)) {
112
+ throw new UpdateError(`${name}: update ${info.edition} does not follow ${cell.info.edition}`);
113
+ }
114
+ }
115
+ /**
116
+ * Applies one update file. Throws if the update does not fit the cell, as an ECDIS rejects such an update,
117
+ * and leaves the cell as it was.
118
+ */
119
+ export function applyUpdate(cell, file) {
120
+ if (cell.cancelled)
121
+ throw new UpdateError(`${file.info.name}: ${cell.info.name} is cancelled`);
122
+ checkSequence(cell, file.info);
123
+ const records = file.info.edition === '0' ? new Map() : applyRecords(cell.records, file);
124
+ cell.records = records;
125
+ cell.cancelled = file.info.edition === '0';
126
+ cell.updates++;
127
+ cell.info = { ...cell.info, edition: file.info.edition };
128
+ }
129
+ function applyRecords(current, file) {
130
+ const records = new Map(current);
131
+ const changed = new Set();
132
+ const deleted = new Set();
133
+ for (const u of file.records) {
134
+ const k = key(u.rcnm, u.rcid);
135
+ const target = records.get(k);
136
+ if (u.ruin === INSERT) {
137
+ if (target)
138
+ fail(u, 'inserted record already exists');
139
+ records.set(k, toRec(u));
140
+ changed.add(k);
141
+ continue;
142
+ }
143
+ if (u.ruin !== DELETE && u.ruin !== MODIFY)
144
+ fail(u, `invalid RUIN ${u.ruin}`);
145
+ if (!target)
146
+ fail(u, 'record to update not found');
147
+ if (u.rver !== target.rver + 1)
148
+ fail(u, `RVER ${u.rver}, expected ${target.rver + 1}`);
149
+ if (u.ruin === DELETE) {
150
+ records.delete(k);
151
+ changed.delete(k);
152
+ deleted.add(k);
153
+ }
154
+ else {
155
+ const copy = editable(target);
156
+ modify(copy, u);
157
+ records.set(k, copy);
158
+ changed.add(k);
159
+ }
160
+ }
161
+ checkReferences(records, changed, deleted);
162
+ return records;
163
+ }
164
+ function refsOf(r) {
165
+ return [...r.inas, ...r.fasc, ...r.spas, ...r.mask, ...r.cuco, ...r.rias, ...(r.ptas ?? [])];
166
+ }
167
+ /**
168
+ * Every reference a changed record makes, and every reference to a deleted record, must resolve once the
169
+ * whole file is applied: a record may name one the same file inserts further on.
170
+ */
171
+ function checkReferences(records, changed, deleted) {
172
+ for (const k of changed) {
173
+ const r = records.get(k);
174
+ if (!r)
175
+ continue;
176
+ for (const ref of refsOf(r))
177
+ if (!records.has(key(ref.rrnm, ref.rrid)))
178
+ fail(r, `references missing record ${ref.rrnm}:${ref.rrid}`);
179
+ }
180
+ if (!deleted.size)
181
+ return;
182
+ for (const r of records.values()) {
183
+ for (const ref of refsOf(r))
184
+ if (deleted.has(key(ref.rrnm, ref.rrid)))
185
+ fail(r, `still references deleted record ${ref.rrnm}:${ref.rrid}`);
186
+ }
187
+ }
188
+ function modify(t, u) {
189
+ t.rver = u.rver;
190
+ t.inas = updateAssocs(t.inas, u.inas, u);
191
+ if (u.tag === 'IRID' || u.tag === 'FRID') {
192
+ for (const rows of u.attr)
193
+ applyAttrRows(t.attr, rows, false, u);
194
+ }
195
+ switch (u.tag) {
196
+ case 'PRID':
197
+ if (u.point) {
198
+ if (t.point && t.point.length !== u.point.length)
199
+ fail(u, 'point dimension changed');
200
+ t.point = u.point;
201
+ }
202
+ break;
203
+ case 'MRID':
204
+ if (u.coordControl)
205
+ t.coords = updateCoords(t.coords, u.coords, u.coordControl, u);
206
+ break;
207
+ case 'CRID':
208
+ if (u.ptas)
209
+ t.ptas = u.ptas;
210
+ if (u.segmentControl) {
211
+ const s = u.segmentControl;
212
+ // Curves carry one segment; S-100 has no other segment updates to apply to them.
213
+ if (s.instruction !== MODIFY || s.index !== 1 || s.count !== 1)
214
+ fail(u, 'only the single segment of a curve can be updated');
215
+ if (!u.coordControl)
216
+ fail(u, 'segment update without coordinate control');
217
+ t.coords = updateCoords(t.coords, u.coords, u.coordControl, u);
218
+ }
219
+ break;
220
+ case 'CCID':
221
+ if (u.componentControl)
222
+ t.cuco = updateList(t.cuco, u.cuco, u.componentControl, u, 'curve component');
223
+ break;
224
+ case 'SRID':
225
+ if (u.rias.length)
226
+ t.rias = insertOrDelete(t.rias, u.rias, (r) => r.instruction, u, 'ring');
227
+ break;
228
+ case 'FRID':
229
+ t.fasc = updateAssocs(t.fasc, u.fasc, u);
230
+ if (u.foid)
231
+ t.foid = u.foid;
232
+ if (u.spas.length)
233
+ t.spas = insertOrDelete(t.spas, u.spas, (r) => r.instruction, u, 'spatial association');
234
+ if (u.mask.length)
235
+ t.mask = insertOrDelete(t.mask, u.mask, (r) => r.muin, u, 'mask');
236
+ break;
237
+ }
238
+ }
239
+ function updateAssocs(target, updates, rec) {
240
+ const out = [...target];
241
+ for (const a of updates) {
242
+ if (a.instruction === INSERT) {
243
+ out.push(toAssoc(a, rec));
244
+ continue;
245
+ }
246
+ // A link is named by its target, association and role; only a modification that changes the
247
+ // association or role names it by its target alone.
248
+ const sameTarget = (t) => t.rrnm === a.rrnm && t.rrid === a.rrid;
249
+ let pos = out.findIndex((t) => sameTarget(t) && t.association === a.association && t.role === a.role);
250
+ if (pos < 0 && a.instruction === MODIFY)
251
+ pos = out.findIndex(sameTarget);
252
+ if (pos < 0)
253
+ fail(rec, `association with ${a.rrnm}:${a.rrid} not found`);
254
+ if (a.instruction === DELETE)
255
+ out.splice(pos, 1);
256
+ else if (a.instruction === MODIFY) {
257
+ const t = out[pos];
258
+ applyAttrRows(t.attrs, a.attrs, false, rec);
259
+ out[pos] = { ...t, association: a.association, role: a.role };
260
+ }
261
+ else
262
+ fail(rec, `invalid association instruction ${a.instruction}`);
263
+ }
264
+ return out;
265
+ }
266
+ function insertOrDelete(target, updates, instruction, rec, what) {
267
+ const out = [...target];
268
+ for (const r of updates) {
269
+ if (instruction(r) === INSERT)
270
+ out.push({ ...r });
271
+ else if (instruction(r) === DELETE) {
272
+ const pos = out.findIndex((t) => t.rrnm === r.rrnm && t.rrid === r.rrid);
273
+ if (pos < 0)
274
+ fail(rec, `${what} ${r.rrnm}:${r.rrid} to delete not found`);
275
+ out.splice(pos, 1);
276
+ }
277
+ else
278
+ fail(rec, `invalid ${what} instruction ${instruction(r)}`);
279
+ }
280
+ return out;
281
+ }
282
+ /** Inserts, replaces or deletes `count` entries from position `index` (from 1), each `width` values long. */
283
+ function splice(target, update, ctl, width, rec, what) {
284
+ const n = target.length / width;
285
+ const max = n + (ctl.instruction === INSERT ? 1 : 0);
286
+ if (ctl.index < 1 || ctl.index > max)
287
+ fail(rec, `${what} index ${ctl.index} outside 1..${max}`);
288
+ if (ctl.count < 1)
289
+ fail(rec, `${what} count ${ctl.count}`);
290
+ if (ctl.instruction === DELETE && update.length)
291
+ fail(rec, `${what} deletion carries ${update.length / width} entries`);
292
+ if (ctl.instruction !== DELETE && ctl.count !== update.length / width) {
293
+ fail(rec, `${what} count ${ctl.count} but ${update.length / width} given`);
294
+ }
295
+ if (ctl.instruction !== INSERT && ctl.index + ctl.count > n + 1)
296
+ fail(rec, `${what} range runs past the end`);
297
+ const out = [...target];
298
+ const start = (ctl.index - 1) * width;
299
+ if (ctl.instruction === INSERT)
300
+ out.splice(start, 0, ...update);
301
+ else if (ctl.instruction === MODIFY)
302
+ out.splice(start, update.length, ...update);
303
+ else if (ctl.instruction === DELETE)
304
+ out.splice(start, ctl.count * width);
305
+ else
306
+ fail(rec, `invalid ${what} instruction ${ctl.instruction}`);
307
+ return out;
308
+ }
309
+ function updateCoords(target, update, ctl, rec) {
310
+ if (!target)
311
+ fail(rec, 'coordinate update for a record without coordinates');
312
+ if (update && update.dim !== target.dim)
313
+ fail(rec, 'coordinate dimension changed');
314
+ return {
315
+ dim: target.dim,
316
+ values: splice(target.values, update?.values ?? [], ctl, target.dim, rec, 'coordinate')
317
+ };
318
+ }
319
+ function updateList(target, update, ctl, rec, what) {
320
+ return splice(target, update, ctl, 1, rec, what);
321
+ }
package/dist/s101.d.ts ADDED
@@ -0,0 +1,103 @@
1
+ import { type MergedCell } from './s101-update.ts';
2
+ export interface AttrNode {
3
+ code: string;
4
+ value: string;
5
+ children: AttrNode[];
6
+ }
7
+ export interface InfoAssoc {
8
+ rrnm: number;
9
+ rrid: number;
10
+ association: string;
11
+ role: string;
12
+ }
13
+ export interface FeatureAssoc {
14
+ rrid: number;
15
+ association: string;
16
+ role: string;
17
+ }
18
+ export interface SpatialRef {
19
+ rrnm: number;
20
+ rrid: number;
21
+ ornt: number;
22
+ smin?: number;
23
+ smax?: number;
24
+ usag?: number;
25
+ }
26
+ export interface Mask {
27
+ rrnm: number;
28
+ rrid: number;
29
+ /** MIND: 1 truncated by the data coverage limit, 2 suppress portrayal. */
30
+ mind: number;
31
+ }
32
+ export interface Feature {
33
+ id: number;
34
+ code: string;
35
+ attrs: AttrNode[];
36
+ inas: InfoAssoc[];
37
+ spas: SpatialRef[];
38
+ fasc: FeatureAssoc[];
39
+ masks: Mask[];
40
+ }
41
+ export interface Information {
42
+ id: number;
43
+ code: string;
44
+ attrs: AttrNode[];
45
+ inas: InfoAssoc[];
46
+ }
47
+ export interface Curve {
48
+ begin?: number;
49
+ end?: number;
50
+ /** lon, lat pairs */
51
+ coords: number[];
52
+ inas: InfoAssoc[];
53
+ }
54
+ export interface S101Dataset {
55
+ name: string;
56
+ /** DSED of the base cell or of the last update applied; "0" once cancelled. */
57
+ edition: string;
58
+ /** Number of update files applied. */
59
+ updates: number;
60
+ /** A cancelled cell has no records left and is no longer valid for use. */
61
+ cancelled: boolean;
62
+ cmfx: number;
63
+ cmfy: number;
64
+ cmfz: number;
65
+ features: Map<number, Feature>;
66
+ information: Map<number, Information>;
67
+ points: Map<number, {
68
+ x: number;
69
+ y: number;
70
+ z?: number;
71
+ inas: InfoAssoc[];
72
+ }>;
73
+ multipoints: Map<number, {
74
+ pts: number[];
75
+ inas: InfoAssoc[];
76
+ }>;
77
+ curves: Map<number, Curve>;
78
+ composites: Map<number, {
79
+ refs: SpatialRef[];
80
+ inas: InfoAssoc[];
81
+ }>;
82
+ surfaces: Map<number, {
83
+ refs: SpatialRef[];
84
+ inas: InfoAssoc[];
85
+ }>;
86
+ }
87
+ export declare const RCNM: {
88
+ readonly feature: 100;
89
+ readonly information: 150;
90
+ readonly point: 110;
91
+ readonly multipoint: 115;
92
+ readonly curve: 120;
93
+ readonly composite: 125;
94
+ readonly surface: 130;
95
+ };
96
+ /**
97
+ * Reads a base cell (.000) and applies its update files (.001, .002, ...) in order. Updates after a
98
+ * cancellation are not read. Throws on an update that does not fit the cell.
99
+ */
100
+ export declare function readS101(base: Uint8Array, updates?: Uint8Array[]): S101Dataset;
101
+ /** The merged records of a cell and its updates, before they are shaped for portrayal. */
102
+ export declare function readCell(base: Uint8Array, updates?: Uint8Array[]): MergedCell;
103
+ export declare function toDataset(cell: MergedCell): S101Dataset;
package/dist/s101.js ADDED
@@ -0,0 +1,131 @@
1
+ // S-101 (S-100 Part 10a) dataset as plain records, keyed the way the portrayal host asks for them.
2
+ import { readRecords } from "./s101-records.js";
3
+ import { applyUpdate, baseCell } from "./s101-update.js";
4
+ export const RCNM = {
5
+ feature: 100,
6
+ information: 150,
7
+ point: 110,
8
+ multipoint: 115,
9
+ curve: 120,
10
+ composite: 125,
11
+ surface: 130
12
+ };
13
+ const NULL_U32 = 0xffffffff;
14
+ // S-101 reads both 0 and the null value as no scale bound.
15
+ const noScale = (n) => (n === 0 || n === NULL_U32 ? undefined : n);
16
+ /**
17
+ * Reads a base cell (.000) and applies its update files (.001, .002, ...) in order. Updates after a
18
+ * cancellation are not read. Throws on an update that does not fit the cell.
19
+ */
20
+ export function readS101(base, updates = []) {
21
+ return toDataset(readCell(base, updates));
22
+ }
23
+ /** The merged records of a cell and its updates, before they are shaped for portrayal. */
24
+ export function readCell(base, updates = []) {
25
+ const cell = baseCell(readRecords(base));
26
+ for (const bytes of updates) {
27
+ if (cell.cancelled)
28
+ break;
29
+ applyUpdate(cell, readRecords(bytes));
30
+ }
31
+ return cell;
32
+ }
33
+ const attrNodes = (trees) => trees.map((t) => ({ code: t.code, value: t.value, children: attrNodes(t.children) }));
34
+ const infoAssoc = (a) => ({
35
+ rrnm: a.rrnm,
36
+ rrid: a.rrid,
37
+ association: a.association,
38
+ role: a.role
39
+ });
40
+ export function toDataset(cell) {
41
+ const { cmfx, cmfy, cmfz } = cell.info;
42
+ const ds = {
43
+ name: cell.info.name,
44
+ edition: cell.info.edition,
45
+ updates: cell.updates,
46
+ cancelled: cell.cancelled,
47
+ cmfx,
48
+ cmfy,
49
+ cmfz,
50
+ features: new Map(),
51
+ information: new Map(),
52
+ points: new Map(),
53
+ multipoints: new Map(),
54
+ curves: new Map(),
55
+ composites: new Map(),
56
+ surfaces: new Map()
57
+ };
58
+ const refs = (rows) => rows.map((r) => ({ rrnm: r.rrnm, rrid: r.rrid, ornt: r.ornt }));
59
+ for (const r of cell.records.values()) {
60
+ const inas = r.inas.map(infoAssoc);
61
+ switch (r.tag) {
62
+ case 'IRID':
63
+ ds.information.set(r.rcid, { id: r.rcid, code: r.code, attrs: attrNodes(r.attr), inas });
64
+ break;
65
+ case 'PRID':
66
+ if (r.point) {
67
+ const [x, y] = r.point;
68
+ const z = r.point.length > 2 ? r.point[2] : undefined;
69
+ ds.points.set(r.rcid, {
70
+ x: x / cmfx,
71
+ y: y / cmfy,
72
+ z: z === undefined ? undefined : z / cmfz,
73
+ inas
74
+ });
75
+ }
76
+ break;
77
+ case 'MRID': {
78
+ const pts = [];
79
+ const c = r.coords;
80
+ if (c) {
81
+ for (let i = 0; i < c.values.length; i += c.dim) {
82
+ pts.push(c.values[i] / cmfx, c.values[i + 1] / cmfy, c.dim === 3 ? c.values[i + 2] / cmfz : NaN);
83
+ }
84
+ }
85
+ ds.multipoints.set(r.rcid, { pts, inas });
86
+ break;
87
+ }
88
+ case 'CRID': {
89
+ const curve = { coords: [], inas };
90
+ for (const p of r.ptas ?? []) {
91
+ if (p.topi === 1 || p.topi === 3)
92
+ curve.begin = p.rrid;
93
+ if (p.topi === 2 || p.topi === 3)
94
+ curve.end = p.rrid;
95
+ }
96
+ const v = r.coords?.values ?? [];
97
+ for (let i = 0; i < v.length; i += 2)
98
+ curve.coords.push(v[i] / cmfx, v[i + 1] / cmfy);
99
+ ds.curves.set(r.rcid, curve);
100
+ break;
101
+ }
102
+ case 'CCID':
103
+ ds.composites.set(r.rcid, { refs: refs(r.cuco), inas });
104
+ break;
105
+ case 'SRID':
106
+ ds.surfaces.set(r.rcid, {
107
+ refs: r.rias.map((x) => ({ rrnm: x.rrnm, rrid: x.rrid, ornt: x.ornt, usag: x.usag })),
108
+ inas
109
+ });
110
+ break;
111
+ case 'FRID':
112
+ ds.features.set(r.rcid, {
113
+ id: r.rcid,
114
+ code: r.code,
115
+ attrs: attrNodes(r.attr),
116
+ inas,
117
+ spas: r.spas.map((x) => ({
118
+ rrnm: x.rrnm,
119
+ rrid: x.rrid,
120
+ ornt: x.ornt,
121
+ smin: noScale(x.smin),
122
+ smax: noScale(x.smax)
123
+ })),
124
+ fasc: r.fasc.map((a) => ({ rrid: a.rrid, association: a.association, role: a.role })),
125
+ masks: r.mask.map((m) => ({ rrnm: m.rrnm, rrid: m.rrid, mind: m.mind }))
126
+ });
127
+ break;
128
+ }
129
+ }
130
+ return ds;
131
+ }
@@ -0,0 +1,34 @@
1
+ import { type S101Dataset } from './s101.ts';
2
+ import { type ContextParameter } from './portray.ts';
3
+ export type WorkerRequest = {
4
+ type: 'init';
5
+ rules: Record<string, string>;
6
+ hostLua: string;
7
+ wasmUri: string;
8
+ } | {
9
+ type: 'load';
10
+ bytes: Uint8Array;
11
+ updates: Uint8Array[];
12
+ fcLua: string;
13
+ params: ContextParameter[];
14
+ } | {
15
+ type: 'rerun';
16
+ params: ContextParameter[];
17
+ };
18
+ export type WorkerResponse = {
19
+ type: 'ready';
20
+ } | {
21
+ type: 'loaded';
22
+ ds: S101Dataset;
23
+ instructions: Map<string, string>;
24
+ errors: string[];
25
+ ms: Record<string, number>;
26
+ } | {
27
+ type: 'portrayed';
28
+ instructions: Map<string, string>;
29
+ errors: string[];
30
+ ms: Record<string, number>;
31
+ } | {
32
+ type: 'error';
33
+ message: string;
34
+ };
package/dist/worker.js ADDED
@@ -0,0 +1,54 @@
1
+ // Web Worker that parses S-101 cells and runs the portrayal off the main thread.
2
+ import { readS101 } from "./s101.js";
3
+ import { datasetToLua } from "./lua-data.js";
4
+ import { Portrayer } from "./portray.js";
5
+ let portrayer;
6
+ async function handle(req) {
7
+ switch (req.type) {
8
+ case 'init':
9
+ portrayer = new Portrayer({ rules: req.rules, host: req.hostLua }, req.wasmUri);
10
+ await portrayer.init();
11
+ return { type: 'ready' };
12
+ case 'load': {
13
+ if (!portrayer)
14
+ throw new Error('init first');
15
+ let t = performance.now();
16
+ const ds = readS101(req.bytes, req.updates);
17
+ const parse = performance.now() - t;
18
+ t = performance.now();
19
+ const lua = datasetToLua(ds);
20
+ const toLua = performance.now() - t;
21
+ const r = await portrayer.portray(lua, req.fcLua, req.params);
22
+ return {
23
+ type: 'loaded',
24
+ ds,
25
+ instructions: r.instructions,
26
+ errors: r.errors,
27
+ ms: { parse, toLua, luaLoad: r.ms.load, portray: r.ms.portray }
28
+ };
29
+ }
30
+ case 'rerun': {
31
+ if (!portrayer)
32
+ throw new Error('init first');
33
+ const r = await portrayer.rerun(req.params);
34
+ return {
35
+ type: 'portrayed',
36
+ instructions: r.instructions,
37
+ errors: r.errors,
38
+ ms: { portray: r.ms.portray }
39
+ };
40
+ }
41
+ }
42
+ }
43
+ const scope = self;
44
+ let queue = Promise.resolve();
45
+ scope.onmessage = (e) => {
46
+ queue = queue.then(async () => {
47
+ try {
48
+ scope.postMessage(await handle(e.data));
49
+ }
50
+ catch (err) {
51
+ scope.postMessage({ type: 'error', message: String(err) });
52
+ }
53
+ });
54
+ };