@alexwohlbruck/portolan 0.3.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.
Files changed (46) hide show
  1. package/README.md +262 -0
  2. package/bin/darwin-arm64/portolan +0 -0
  3. package/bin/darwin-x64/portolan +0 -0
  4. package/bin/linux-arm64/portolan +0 -0
  5. package/bin/linux-x64/portolan +0 -0
  6. package/bin/win32-arm64/portolan.exe +0 -0
  7. package/bin/win32-x64/portolan.exe +0 -0
  8. package/dist/binary.d.ts +16 -0
  9. package/dist/binary.d.ts.map +1 -0
  10. package/dist/binary.js +117 -0
  11. package/dist/binary.js.map +1 -0
  12. package/dist/client.d.ts +61 -0
  13. package/dist/client.d.ts.map +1 -0
  14. package/dist/client.js +201 -0
  15. package/dist/client.js.map +1 -0
  16. package/dist/index.d.ts +47 -0
  17. package/dist/index.d.ts.map +1 -0
  18. package/dist/index.js +41 -0
  19. package/dist/index.js.map +1 -0
  20. package/dist/plnb.d.ts +89 -0
  21. package/dist/plnb.d.ts.map +1 -0
  22. package/dist/plnb.js +268 -0
  23. package/dist/plnb.js.map +1 -0
  24. package/dist/server.d.ts +68 -0
  25. package/dist/server.d.ts.map +1 -0
  26. package/dist/server.js +208 -0
  27. package/dist/server.js.map +1 -0
  28. package/dist/types.d.ts +177 -0
  29. package/dist/types.d.ts.map +1 -0
  30. package/dist/types.js +10 -0
  31. package/dist/types.js.map +1 -0
  32. package/package.json +49 -0
  33. package/style/_default.json +5 -0
  34. package/style/amsterdam.json +19 -0
  35. package/style/amtrak.json +5 -0
  36. package/style/barcelona-tmb.json +7 -0
  37. package/style/berlin.json +7 -0
  38. package/style/charlotte.json +12 -0
  39. package/style/chicago-cta.json +28 -0
  40. package/style/chicago.json +7 -0
  41. package/style/mexico.json +13 -0
  42. package/style/mta-subway.json +5 -0
  43. package/style/nj-transit-rail.json +5 -0
  44. package/style/paris.json +10 -0
  45. package/style/santiago.json +7 -0
  46. package/style/vienna.json +19 -0
package/dist/client.js ADDED
@@ -0,0 +1,201 @@
1
+ import { decodePlnb } from "./plnb.js";
2
+ export class PortolanError extends Error {
3
+ status;
4
+ constructor(message, status) {
5
+ super(message);
6
+ this.status = status;
7
+ this.name = "PortolanError";
8
+ }
9
+ }
10
+ /** camelCase in, snake_case on the wire — the mapping lives only here. */
11
+ function toWire(req) {
12
+ const w = {};
13
+ const set = (k, v) => {
14
+ if (v !== undefined && v !== null)
15
+ w[k] = v;
16
+ };
17
+ set("gtfs", req.gtfs);
18
+ set("gtfs_inline", req.gtfsInline);
19
+ set("rail", req.rail);
20
+ set("corridors", req.corridors);
21
+ set("corridors_inline", req.corridorsInline);
22
+ set("corridor_nodes", req.corridorNodes);
23
+ set("stops", req.stops);
24
+ set("streets", req.streets);
25
+ // both accept an object or a tuple; the wire is always the tuple, and
26
+ // the two orders differ (bbox longitude-first, anchor latitude-first)
27
+ // so the conversion is the one place that has to be right
28
+ if (req.bbox) {
29
+ set("bbox", Array.isArray(req.bbox) ? req.bbox : [req.bbox.w, req.bbox.s, req.bbox.e, req.bbox.n]);
30
+ }
31
+ if (req.anchor) {
32
+ set("anchor", Array.isArray(req.anchor) ? req.anchor : [req.anchor.lat, req.anchor.lon]);
33
+ }
34
+ set("city", req.city);
35
+ set("style_dir", req.styleDir);
36
+ set("style_inline", req.styleInline);
37
+ set("line_agencies", req.lineAgencies);
38
+ set("scenario", req.scenario);
39
+ set("cover", req.cover);
40
+ set("format", req.format);
41
+ // the engine takes the band as a string, and 0 is a REAL band — so it
42
+ // must survive the falsy check that would drop it
43
+ if (req.band !== undefined && req.band !== null)
44
+ w["band"] = String(req.band);
45
+ return w;
46
+ }
47
+ /** A build in flight, or finished. */
48
+ export class Job {
49
+ id;
50
+ client;
51
+ constructor(id, client) {
52
+ this.id = id;
53
+ this.client = client;
54
+ }
55
+ /** Stream progress until the terminal frame. */
56
+ watch(onProgress, signal) {
57
+ return this.client.watch(this.id, onProgress, signal);
58
+ }
59
+ /** Abandon the build. The engine stops between stages. */
60
+ cancel() {
61
+ return this.client.cancel(this.id);
62
+ }
63
+ /** Fetch an artifact as bytes. */
64
+ bytes(artifact) {
65
+ return this.client.artifactBytes(this.id, artifact);
66
+ }
67
+ /** Fetch and decode the binary segments. */
68
+ plnb() {
69
+ return this.client.plnb(this.id);
70
+ }
71
+ /** Fetch an artifact as parsed JSON. */
72
+ json(artifact) {
73
+ return this.client.artifactJson(this.id, artifact);
74
+ }
75
+ }
76
+ export class PortolanClient {
77
+ origin;
78
+ headers;
79
+ constructor(origin, headers = {}) {
80
+ this.origin = origin;
81
+ this.headers = headers;
82
+ }
83
+ /** Point a client at an already-running server. */
84
+ static at(origin, token) {
85
+ return new PortolanClient(origin, token ? { Authorization: `Bearer ${token}` } : {});
86
+ }
87
+ /** Wrap a server this process started. */
88
+ static from(server) {
89
+ return new PortolanClient(server.origin, server.headers);
90
+ }
91
+ async version() {
92
+ const r = await fetch(`${this.origin}/version`);
93
+ if (!r.ok)
94
+ throw new PortolanError(`GET /version: ${r.status}`, r.status);
95
+ return (await r.json());
96
+ }
97
+ /** Start a build. Returns as soon as the engine accepts it. */
98
+ async start(req) {
99
+ const r = await fetch(`${this.origin}/chart`, {
100
+ method: "POST",
101
+ headers: { ...this.headers, "Content-Type": "application/json" },
102
+ body: JSON.stringify(toWire(req)),
103
+ });
104
+ // 202, not 200 — the build has been accepted, not completed
105
+ if (r.status !== 202) {
106
+ throw new PortolanError(`POST /chart: ${r.status} ${(await r.text()).trim()}`, r.status);
107
+ }
108
+ const { id } = (await r.json());
109
+ return new Job(id, this);
110
+ }
111
+ /**
112
+ * Build and wait. The common case.
113
+ *
114
+ * Aborting cancels SERVER-side as well as locally: an interactive
115
+ * caller supersedes builds constantly, and one that keeps running
116
+ * after nobody wants it piles up behind the one they do.
117
+ */
118
+ async chart(req, opts = {}) {
119
+ const job = await this.start(req);
120
+ const onAbort = () => void job.cancel().catch(() => { });
121
+ opts.signal?.addEventListener("abort", onAbort, { once: true });
122
+ try {
123
+ await job.watch(opts.onProgress, opts.signal);
124
+ }
125
+ finally {
126
+ opts.signal?.removeEventListener("abort", onAbort);
127
+ }
128
+ return job;
129
+ }
130
+ /** Follow a job's SSE stream until it ends. */
131
+ async watch(id, onProgress, signal) {
132
+ const r = await fetch(`${this.origin}/chart/${id}/progress`, {
133
+ headers: this.headers,
134
+ signal,
135
+ });
136
+ if (!r.ok || !r.body) {
137
+ throw new PortolanError(`GET progress: ${r.status}`, r.status);
138
+ }
139
+ const reader = r.body.getReader();
140
+ const dec = new TextDecoder();
141
+ let buf = "";
142
+ try {
143
+ for (;;) {
144
+ const { done, value } = await reader.read();
145
+ if (done)
146
+ break;
147
+ buf += dec.decode(value, { stream: true });
148
+ // SSE frames are separated by a blank line
149
+ let sep;
150
+ while ((sep = buf.indexOf("\n\n")) >= 0) {
151
+ const frame = buf.slice(0, sep);
152
+ buf = buf.slice(sep + 2);
153
+ for (const line of frame.split("\n")) {
154
+ if (!line.startsWith("data: "))
155
+ continue;
156
+ const e = JSON.parse(line.slice(6));
157
+ onProgress?.(e);
158
+ if (e.done) {
159
+ if (e.error)
160
+ throw new PortolanError(`build failed: ${e.error}`);
161
+ return;
162
+ }
163
+ }
164
+ }
165
+ }
166
+ }
167
+ finally {
168
+ reader.cancel().catch(() => { });
169
+ }
170
+ }
171
+ async cancel(id) {
172
+ const r = await fetch(`${this.origin}/chart/${id}/cancel`, {
173
+ method: "POST",
174
+ headers: this.headers,
175
+ });
176
+ if (r.status !== 204)
177
+ throw new PortolanError(`cancel: ${r.status}`, r.status);
178
+ }
179
+ async status(id) {
180
+ const r = await fetch(`${this.origin}/chart/${id}`, { headers: this.headers });
181
+ if (!r.ok)
182
+ throw new PortolanError(`status: ${r.status}`, r.status);
183
+ return (await r.json());
184
+ }
185
+ async artifactBytes(id, artifact = "segments") {
186
+ const q = artifact === "segments" ? "" : `?artifact=${artifact}`;
187
+ const r = await fetch(`${this.origin}/chart/${id}/build${q}`, { headers: this.headers });
188
+ if (!r.ok) {
189
+ throw new PortolanError(`GET build: ${r.status} ${(await r.text()).trim()}`, r.status);
190
+ }
191
+ return new Uint8Array(await r.arrayBuffer());
192
+ }
193
+ async artifactJson(id, artifact = "segments") {
194
+ const bytes = await this.artifactBytes(id, artifact);
195
+ return JSON.parse(new TextDecoder().decode(bytes));
196
+ }
197
+ async plnb(id) {
198
+ return decodePlnb(await this.artifactBytes(id, "segments"));
199
+ }
200
+ }
201
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAa,MAAM,WAAW,CAAC;AAIlD,MAAM,OAAO,aAAc,SAAQ,KAAK;IAG3B;IAFX,YACE,OAAe,EACN,MAAe;QAExB,KAAK,CAAC,OAAO,CAAC,CAAC;QAFN,WAAM,GAAN,MAAM,CAAS;QAGxB,IAAI,CAAC,IAAI,GAAG,eAAe,CAAC;IAC9B,CAAC;CACF;AAED,0EAA0E;AAC1E,SAAS,MAAM,CAAC,GAAiB;IAC/B,MAAM,CAAC,GAA4B,EAAE,CAAC;IACtC,MAAM,GAAG,GAAG,CAAC,CAAS,EAAE,CAAU,EAAE,EAAE;QACpC,IAAI,CAAC,KAAK,SAAS,IAAI,CAAC,KAAK,IAAI;YAAE,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;IAC9C,CAAC,CAAC;IACF,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,IAAI,CAAC,CAAC;IACtB,GAAG,CAAC,aAAa,EAAE,GAAG,CAAC,UAAU,CAAC,CAAC;IACnC,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,IAAI,CAAC,CAAC;IACtB,GAAG,CAAC,WAAW,EAAE,GAAG,CAAC,SAAS,CAAC,CAAC;IAChC,GAAG,CAAC,kBAAkB,EAAE,GAAG,CAAC,eAAe,CAAC,CAAC;IAC7C,GAAG,CAAC,gBAAgB,EAAE,GAAG,CAAC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C,MAAM,IAAI,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,EAAE,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC;QACzF,CAAC;QACD,OAAO,IAAI,UAAU,CAAC,MAAM,CAAC,CAAC,WAAW,EAAE,CAAC,CAAC;IAC/C,CAAC;IAED,KAAK,CAAC,YAAY,CAAc,EAAU,EAAE,WAAqB,UAAU;QACzE,MAAM,KAAK,GAAG,MAAM,IAAI,CAAC,aAAa,CAAC,EAAE,EAAE,QAAQ,CAAC,CAAC;QACrD,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,CAAM,CAAC;IAC1D,CAAC;IAED,KAAK,CAAC,IAAI,CAAC,EAAU;QACnB,OAAO,UAAU,CAAC,MAAM,IAAI,CAAC,aAAa,CAAC,EAAE,EAAE,UAAU,CAAC,CAAC,CAAC;IAC9D,CAAC;CACF"}
@@ -0,0 +1,47 @@
1
+ /**
2
+ * @alexwohlbruck/portolan — automatic transit line maps.
3
+ *
4
+ * Spawns the portolan engine, speaks its build API, and decodes its
5
+ * binary output. Every platform's engine ships inside this package, so a
6
+ * version bump here ships a new engine and there is nothing to fetch.
7
+ *
8
+ * import { portolan } from "@alexwohlbruck/portolan";
9
+ *
10
+ * await using p = await portolan();
11
+ * const job = await p.chart({
12
+ * gtfsInline: { "routes.txt": "...", "stops.txt": "..." },
13
+ * corridorsInline: graph,
14
+ * format: "bin",
15
+ * band: 15,
16
+ * }, { onProgress: e => console.log(e.stage, e.pct) });
17
+ *
18
+ * const plnb = await job.plnb();
19
+ */
20
+ export { PortolanServer, PortolanStartupError, IncompatibleEngineError } from "./server.js";
21
+ export type { StartOptions } from "./server.js";
22
+ export { PortolanClient, PortolanError, Job } from "./client.js";
23
+ export type { ChartOptions } from "./client.js";
24
+ export { Plnb, decodePlnb, PlnbError, SUPPORTED_PLNB } from "./plnb.js";
25
+ export { resolveBinary, platformKey, styleDir, BinaryNotFoundError } from "./binary.js";
26
+ export type { ChartRequest, GtfsTables, Band, Format, VersionInfo, ProgressEvent, Artifact, PlnbFeature, } from "./types.js";
27
+ import { PortolanServer, type StartOptions } from "./server.js";
28
+ import { PortolanClient } from "./client.js";
29
+ import type { ChartOptions, Job } from "./client.js";
30
+ import type { ChartRequest, VersionInfo } from "./types.js";
31
+ /**
32
+ * A started engine and a client for it, as one object.
33
+ *
34
+ * Disposable: `await using p = await portolan()` stops the process when
35
+ * the scope ends, which is the failure this most wants to prevent — an
36
+ * orphaned engine per rebuild, each holding a port.
37
+ */
38
+ export interface Portolan extends AsyncDisposable {
39
+ readonly server: PortolanServer;
40
+ readonly client: PortolanClient;
41
+ readonly version: VersionInfo;
42
+ chart(req: ChartRequest, opts?: ChartOptions): Promise<Job>;
43
+ stop(): Promise<void>;
44
+ }
45
+ /** Start an engine and return a client bound to it. */
46
+ export declare function portolan(opts?: StartOptions): Promise<Portolan>;
47
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAEH,OAAO,EAAE,cAAc,EAAE,oBAAoB,EAAE,uBAAuB,EAAE,MAAM,aAAa,CAAC;AAC5F,YAAY,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAChD,OAAO,EAAE,cAAc,EAAE,aAAa,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AACjE,YAAY,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAChD,OAAO,EAAE,IAAI,EAAE,UAAU,EAAE,SAAS,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AACxE,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,QAAQ,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAC;AACxF,YAAY,EACV,YAAY,EACZ,UAAU,EACV,IAAI,EACJ,MAAM,EACN,WAAW,EACX,aAAa,EACb,QAAQ,EACR,WAAW,GACZ,MAAM,YAAY,CAAC;AAEpB,OAAO,EAAE,cAAc,EAAE,KAAK,YAAY,EAAE,MAAM,aAAa,CAAC;AAChE,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAC7C,OAAO,KAAK,EAAE,YAAY,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AACrD,OAAO,KAAK,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAE5D;;;;;;GAMG;AACH,MAAM,WAAW,QAAS,SAAQ,eAAe;IAC/C,QAAQ,CAAC,MAAM,EAAE,cAAc,CAAC;IAChC,QAAQ,CAAC,MAAM,EAAE,cAAc,CAAC;IAChC,QAAQ,CAAC,OAAO,EAAE,WAAW,CAAC;IAC9B,KAAK,CAAC,GAAG,EAAE,YAAY,EAAE,IAAI,CAAC,EAAE,YAAY,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC;IAC5D,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CACvB;AAED,uDAAuD;AACvD,wBAAsB,QAAQ,CAAC,IAAI,GAAE,YAAiB,GAAG,OAAO,CAAC,QAAQ,CAAC,CAazE"}
package/dist/index.js ADDED
@@ -0,0 +1,41 @@
1
+ /**
2
+ * @alexwohlbruck/portolan — automatic transit line maps.
3
+ *
4
+ * Spawns the portolan engine, speaks its build API, and decodes its
5
+ * binary output. Every platform's engine ships inside this package, so a
6
+ * version bump here ships a new engine and there is nothing to fetch.
7
+ *
8
+ * import { portolan } from "@alexwohlbruck/portolan";
9
+ *
10
+ * await using p = await portolan();
11
+ * const job = await p.chart({
12
+ * gtfsInline: { "routes.txt": "...", "stops.txt": "..." },
13
+ * corridorsInline: graph,
14
+ * format: "bin",
15
+ * band: 15,
16
+ * }, { onProgress: e => console.log(e.stage, e.pct) });
17
+ *
18
+ * const plnb = await job.plnb();
19
+ */
20
+ export { PortolanServer, PortolanStartupError, IncompatibleEngineError } from "./server.js";
21
+ export { PortolanClient, PortolanError, Job } from "./client.js";
22
+ export { Plnb, decodePlnb, PlnbError, SUPPORTED_PLNB } from "./plnb.js";
23
+ export { resolveBinary, platformKey, styleDir, BinaryNotFoundError } from "./binary.js";
24
+ import { PortolanServer } from "./server.js";
25
+ import { PortolanClient } from "./client.js";
26
+ /** Start an engine and return a client bound to it. */
27
+ export async function portolan(opts = {}) {
28
+ const server = await PortolanServer.start(opts);
29
+ const client = PortolanClient.from(server);
30
+ return {
31
+ server,
32
+ client,
33
+ version: server.version,
34
+ chart: (req, o) => client.chart(req, o),
35
+ stop: () => server.stop(),
36
+ async [Symbol.asyncDispose]() {
37
+ await server.stop();
38
+ },
39
+ };
40
+ }
41
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAEH,OAAO,EAAE,cAAc,EAAE,oBAAoB,EAAE,uBAAuB,EAAE,MAAM,aAAa,CAAC;AAE5F,OAAO,EAAE,cAAc,EAAE,aAAa,EAAE,GAAG,EAAE,MAAM,aAAa,CAAC;AAEjE,OAAO,EAAE,IAAI,EAAE,UAAU,EAAE,SAAS,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AACxE,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,QAAQ,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAC;AAYxF,OAAO,EAAE,cAAc,EAAqB,MAAM,aAAa,CAAC;AAChE,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAmB7C,uDAAuD;AACvD,MAAM,CAAC,KAAK,UAAU,QAAQ,CAAC,OAAqB,EAAE;IACpD,MAAM,MAAM,GAAG,MAAM,cAAc,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IAChD,MAAM,MAAM,GAAG,cAAc,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IAC3C,OAAO;QACL,MAAM;QACN,MAAM;QACN,OAAO,EAAE,MAAM,CAAC,OAAO;QACvB,KAAK,EAAE,CAAC,GAAG,EAAE,CAAC,EAAE,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,CAAC;QACvC,IAAI,EAAE,GAAG,EAAE,CAAC,MAAM,CAAC,IAAI,EAAE;QACzB,KAAK,CAAC,CAAC,MAAM,CAAC,YAAY,CAAC;YACzB,MAAM,MAAM,CAAC,IAAI,EAAE,CAAC;QACtB,CAAC;KACF,CAAC;AACJ,CAAC"}
package/dist/plnb.d.ts ADDED
@@ -0,0 +1,89 @@
1
+ import type { PlnbFeature } from "./types.js";
2
+ /** The layout version this decoder understands. */
3
+ export declare const SUPPORTED_PLNB = 1;
4
+ export declare class PlnbError extends Error {
5
+ constructor(message: string);
6
+ }
7
+ /**
8
+ * A decoded build. The typed arrays are VIEWS over the source buffer —
9
+ * no copying — so `positions` can go straight into a GPU buffer and the
10
+ * property columns can be read by index without allocating per feature.
11
+ *
12
+ * Use `feature(i)` only when you want a plain object; the whole point of
13
+ * the format is that a renderer does not need one.
14
+ */
15
+ export declare class Plnb {
16
+ #private;
17
+ /** Zoom band this file holds, or `null` for the union of all bands. */
18
+ readonly band: number | null;
19
+ readonly featureCount: number;
20
+ readonly positionCount: number;
21
+ /**
22
+ * `[lon, lat]` pairs as signed 1e-7 degrees, `positionCount * 2` long.
23
+ * Integers, not floats: a float32 holds about seven significant digits
24
+ * where a longitude needs nine, which would quantise vertices to
25
+ * roughly two metres and visibly kink a ribbon.
26
+ */
27
+ readonly positions: Int32Array;
28
+ /** `featureCount + 1` offsets into `positions` (in vertices, not bytes). */
29
+ readonly starts: Uint32Array;
30
+ readonly kinds: Uint8Array;
31
+ readonly colors: Uint32Array;
32
+ readonly f32s: Float32Array;
33
+ readonly i16s: Int16Array;
34
+ readonly u32s: Uint32Array;
35
+ readonly strings: string[];
36
+ constructor(buf: ArrayBuffer);
37
+ /**
38
+ * Every position in DEGREES as one flat interleaved `Float64Array`
39
+ * — `[lon₀, lat₀, lon₁, lat₁, …]`, `positionCount * 2` long.
40
+ *
41
+ * This is what a GPU consumer actually wants. `positions` is integer
42
+ * 1e-7 degrees, which is right on the wire and wrong in a vertex
43
+ * buffer: nothing off the shelf divides by 1e7, and projection happens
44
+ * in the shader from lng/lat.
45
+ *
46
+ * f64 rather than f32 is not a preference. A float32 holds about seven
47
+ * significant digits where a longitude needs nine, so an f32 buffer
48
+ * quantises vertices to roughly two metres and visibly kinks a ribbon
49
+ * — the same reason the wire format is i32 and not f32. deck.gl's
50
+ * binary attribute path takes f64 and splits it into hi/lo f32 pairs
51
+ * for exactly this.
52
+ *
53
+ * One pass, cached, so calling it per frame is free after the first.
54
+ * Pair it with `starts` as deck.gl's `startIndices`.
55
+ */
56
+ degrees(): Float64Array;
57
+ /** Vertex range of feature `i`: `[startVertex, endVertex)`. */
58
+ vertexRange(i: number): [number, number];
59
+ kind(i: number): PlnbFeature["kind"];
60
+ /** 0xRRGGBB. */
61
+ color(i: number): number;
62
+ /** `#rrggbb`, for handing to a canvas or a style expression. */
63
+ colorHex(i: number): string;
64
+ offsetPx(i: number): number;
65
+ offFromPx(i: number): number;
66
+ offToPx(i: number): number;
67
+ slot(i: number): number;
68
+ nslots(i: number): number;
69
+ bandMin(i: number): number;
70
+ /** EXCLUSIVE: the range is `[bandMin, bandMax)`, and each band's max is the next band's min. */
71
+ bandMax(i: number): number;
72
+ routeType(i: number): number;
73
+ label(i: number): string;
74
+ mode(i: number): string;
75
+ /** Route ids, verbatim. Split from the CSV the emitter writes. */
76
+ routes(i: number): string[];
77
+ /** Weekly hex masks aligned with `routes`; empty when the feed had no calendar. */
78
+ acts(i: number): string[];
79
+ /** `[lon, lat]` in degrees. Allocates — prefer `positions` in a hot path. */
80
+ coordinates(i: number): Array<[number, number]>;
81
+ /** A plain object for one feature. Convenience, not the fast path. */
82
+ feature(i: number): PlnbFeature;
83
+ features(): Generator<PlnbFeature>;
84
+ /** GeoJSON, for comparing against the `geojson` emit or for a quick look. */
85
+ toGeoJSON(): unknown;
86
+ }
87
+ /** Decode a PLNB buffer. */
88
+ export declare function decodePlnb(buf: ArrayBuffer | Uint8Array): Plnb;
89
+ //# sourceMappingURL=plnb.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"plnb.d.ts","sourceRoot":"","sources":["../src/plnb.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAuB9C,mDAAmD;AACnD,eAAO,MAAM,cAAc,IAAI,CAAC;AAQhC,qBAAa,SAAU,SAAQ,KAAK;gBACtB,OAAO,EAAE,MAAM;CAI5B;AAED;;;;;;;GAOG;AACH,qBAAa,IAAI;;IACf,uEAAuE;IACvE,QAAQ,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;IAC7B,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAC;IAC9B,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAC;IAE/B;;;;;OAKG;IACH,QAAQ,CAAC,SAAS,EAAE,UAAU,CAAC;IAC/B,4EAA4E;IAC5E,QAAQ,CAAC,MAAM,EAAE,WAAW,CAAC;IAE7B,QAAQ,CAAC,KAAK,EAAE,UAAU,CAAC;IAC3B,QAAQ,CAAC,MAAM,EAAE,WAAW,CAAC;IAC7B,QAAQ,CAAC,IAAI,EAAE,YAAY,CAAC;IAC5B,QAAQ,CAAC,IAAI,EAAE,UAAU,CAAC;IAC1B,QAAQ,CAAC,IAAI,EAAE,WAAW,CAAC;IAC3B,QAAQ,CAAC,OAAO,EAAE,MAAM,EAAE,CAAC;gBAEf,GAAG,EAAE,WAAW;IA+D5B;;;;;;;;;;;;;;;;;;OAkBG;IACH,OAAO,IAAI,YAAY;IAUvB,+DAA+D;IAC/D,WAAW,CAAC,CAAC,EAAE,MAAM,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC;IAIxC,IAAI,CAAC,CAAC,EAAE,MAAM,GAAG,WAAW,C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because the layout is easy to misread and misreading
5
+ * it fails SILENTLY. The property blocks are grouped by WIDTH and
6
+ * interleaved within a block — `f32s` is
7
+ * `[offsetPx₀, offFromPx₀, offToPx₀, offsetPx₁, …]`, stride 3 — not one
8
+ * contiguous array per property. A decoder that assumes the latter reads
9
+ * plausible-but-wrong values (nslots picking up bandMin, routes picking
10
+ * up label) because every lane is a valid value of the right width.
11
+ * That has already cost one consumer a debugging cycle against a comment
12
+ * that described the opposite layout.
13
+ *
14
+ * So: decode once, here, and check the format version.
15
+ *
16
+ * The authority is the package comment at the top of
17
+ * `internal/pipeline/binary.go`; the address formulas below are copied
18
+ * from it verbatim.
19
+ */
20
+ const MAGIC = 0x424e4c50; // "PLNB", little-endian
21
+ /** The layout version this decoder understands. */
22
+ export const SUPPORTED_PLNB = 1;
23
+ const HEADER = 32;
24
+ const COORD_SCALE = 1e7;
25
+ const KINDS = ["steady", "transition", "bridge"];
26
+ const align4 = (n) => (n + 3) & ~3;
27
+ export class PlnbError extends Error {
28
+ constructor(message) {
29
+ super(message);
30
+ this.name = "PlnbError";
31
+ }
32
+ }
33
+ /**
34
+ * A decoded build. The typed arrays are VIEWS over the source buffer —
35
+ * no copying — so `positions` can go straight into a GPU buffer and the
36
+ * property columns can be read by index without allocating per feature.
37
+ *
38
+ * Use `feature(i)` only when you want a plain object; the whole point of
39
+ * the format is that a renderer does not need one.
40
+ */
41
+ export class Plnb {
42
+ /** Zoom band this file holds, or `null` for the union of all bands. */
43
+ band;
44
+ featureCount;
45
+ positionCount;
46
+ /**
47
+ * `[lon, lat]` pairs as signed 1e-7 degrees, `positionCount * 2` long.
48
+ * Integers, not floats: a float32 holds about seven significant digits
49
+ * where a longitude needs nine, which would quantise vertices to
50
+ * roughly two metres and visibly kink a ribbon.
51
+ */
52
+ positions;
53
+ /** `featureCount + 1` offsets into `positions` (in vertices, not bytes). */
54
+ starts;
55
+ kinds; // stride 1
56
+ colors; // stride 1, 0x00RRGGBB
57
+ f32s; // stride 3: offsetPx, offFromPx, offToPx
58
+ i16s; // stride 5: slot, nslots, bandMin, bandMax, routeType
59
+ u32s; // stride 4: label, mode, routes, acts
60
+ strings;
61
+ constructor(buf) {
62
+ const dv = new DataView(buf);
63
+ if (buf.byteLength < HEADER) {
64
+ throw new PlnbError(`buffer is ${buf.byteLength} bytes, too short for a header`);
65
+ }
66
+ if (dv.getUint32(0, true) !== MAGIC) {
67
+ throw new PlnbError("not a PLNB buffer (bad magic)");
68
+ }
69
+ const version = dv.getUint16(4, true);
70
+ if (version !== SUPPORTED_PLNB) {
71
+ throw new PlnbError(`PLNB layout version ${version}, this decoder understands ${SUPPORTED_PLNB}. ` +
72
+ `Upgrade @alexwohlbruck/portolan to match the engine.`);
73
+ }
74
+ const nFeat = dv.getUint32(8, true);
75
+ const nPos = dv.getUint32(12, true);
76
+ const band = dv.getInt32(16, true);
77
+ const strTabOff = dv.getUint32(20, true);
78
+ this.featureCount = nFeat;
79
+ this.positionCount = nPos;
80
+ this.band = band < 0 ? null : band;
81
+ // block addresses, exactly as binary.go states them
82
+ const posOff = HEADER;
83
+ const startsOff = posOff + nPos * 8;
84
+ const kindsOff = startsOff + (nFeat + 1) * 4;
85
+ const colorsOff = kindsOff + align4(nFeat);
86
+ const f32Off = colorsOff + nFeat * 4;
87
+ const i16Off = f32Off + nFeat * 12;
88
+ const u32Off = i16Off + align4(nFeat * 10);
89
+ if (strTabOff !== u32Off + nFeat * 16 || strTabOff > buf.byteLength) {
90
+ throw new PlnbError(`string table at ${strTabOff} but the block formulas give ${u32Off + nFeat * 16} ` +
91
+ `— the file is truncated or the layout has changed`);
92
+ }
93
+ // Views, not copies. Every block is 4-byte aligned by construction
94
+ // (binary.go pads kinds and i16s), so these never need a slice.
95
+ this.positions = new Int32Array(buf, posOff, nPos * 2);
96
+ this.starts = new Uint32Array(buf, startsOff, nFeat + 1);
97
+ this.kinds = new Uint8Array(buf, kindsOff, nFeat);
98
+ this.colors = new Uint32Array(buf, colorsOff, nFeat);
99
+ this.f32s = new Float32Array(buf, f32Off, nFeat * 3);
100
+ this.i16s = new Int16Array(buf, i16Off, nFeat * 5);
101
+ this.u32s = new Uint32Array(buf, u32Off, nFeat * 4);
102
+ // strings: u32 count, then u32 length + utf-8 bytes each
103
+ const count = dv.getUint32(strTabOff, true);
104
+ const dec = new TextDecoder();
105
+ const strs = new Array(count);
106
+ let at = strTabOff + 4;
107
+ for (let i = 0; i < count; i++) {
108
+ const len = dv.getUint32(at, true);
109
+ strs[i] = len === 0 ? "" : dec.decode(new Uint8Array(buf, at + 4, len));
110
+ at += 4 + len;
111
+ }
112
+ this.strings = strs;
113
+ }
114
+ /**
115
+ * Every position in DEGREES as one flat interleaved `Float64Array`
116
+ * — `[lon₀, lat₀, lon₁, lat₁, …]`, `positionCount * 2` long.
117
+ *
118
+ * This is what a GPU consumer actually wants. `positions` is integer
119
+ * 1e-7 degrees, which is right on the wire and wrong in a vertex
120
+ * buffer: nothing off the shelf divides by 1e7, and projection happens
121
+ * in the shader from lng/lat.
122
+ *
123
+ * f64 rather than f32 is not a preference. A float32 holds about seven
124
+ * significant digits where a longitude needs nine, so an f32 buffer
125
+ * quantises vertices to roughly two metres and visibly kinks a ribbon
126
+ * — the same reason the wire format is i32 and not f32. deck.gl's
127
+ * binary attribute path takes f64 and splits it into hi/lo f32 pairs
128
+ * for exactly this.
129
+ *
130
+ * One pass, cached, so calling it per frame is free after the first.
131
+ * Pair it with `starts` as deck.gl's `startIndices`.
132
+ */
133
+ degrees() {
134
+ if (!this.#degrees) {
135
+ const out = new Float64Array(this.positionCount * 2);
136
+ for (let i = 0; i < out.length; i++)
137
+ out[i] = this.positions[i] / COORD_SCALE;
138
+ this.#degrees = out;
139
+ }
140
+ return this.#degrees;
141
+ }
142
+ #degrees = null;
143
+ /** Vertex range of feature `i`: `[startVertex, endVertex)`. */
144
+ vertexRange(i) {
145
+ return [this.starts[i], this.starts[i + 1]];
146
+ }
147
+ kind(i) {
148
+ return KINDS[this.kinds[i]] ?? "unknown";
149
+ }
150
+ /** 0xRRGGBB. */
151
+ color(i) {
152
+ return this.colors[i];
153
+ }
154
+ /** `#rrggbb`, for handing to a canvas or a style expression. */
155
+ colorHex(i) {
156
+ return "#" + this.colors[i].toString(16).padStart(6, "0");
157
+ }
158
+ offsetPx(i) {
159
+ return this.f32s[i * 3];
160
+ }
161
+ offFromPx(i) {
162
+ return this.f32s[i * 3 + 1];
163
+ }
164
+ offToPx(i) {
165
+ return this.f32s[i * 3 + 2];
166
+ }
167
+ slot(i) {
168
+ return this.i16s[i * 5];
169
+ }
170
+ nslots(i) {
171
+ return this.i16s[i * 5 + 1];
172
+ }
173
+ bandMin(i) {
174
+ return this.i16s[i * 5 + 2];
175
+ }
176
+ /** EXCLUSIVE: the range is `[bandMin, bandMax)`, and each band's max is the next band's min. */
177
+ bandMax(i) {
178
+ return this.i16s[i * 5 + 3];
179
+ }
180
+ routeType(i) {
181
+ return this.i16s[i * 5 + 4];
182
+ }
183
+ label(i) {
184
+ return this.strings[this.u32s[i * 4]];
185
+ }
186
+ mode(i) {
187
+ return this.strings[this.u32s[i * 4 + 1]];
188
+ }
189
+ /** Route ids, verbatim. Split from the CSV the emitter writes. */
190
+ routes(i) {
191
+ const s = this.strings[this.u32s[i * 4 + 2]];
192
+ return s === "" ? [] : s.split(",");
193
+ }
194
+ /** Weekly hex masks aligned with `routes`; empty when the feed had no calendar. */
195
+ acts(i) {
196
+ const s = this.strings[this.u32s[i * 4 + 3]];
197
+ return s === "" ? [] : s.split(";");
198
+ }
199
+ /** `[lon, lat]` in degrees. Allocates — prefer `positions` in a hot path. */
200
+ coordinates(i) {
201
+ const [a, b] = this.vertexRange(i);
202
+ const out = new Array(b - a);
203
+ for (let k = a; k < b; k++) {
204
+ out[k - a] = [this.positions[k * 2] / COORD_SCALE, this.positions[k * 2 + 1] / COORD_SCALE];
205
+ }
206
+ return out;
207
+ }
208
+ /** A plain object for one feature. Convenience, not the fast path. */
209
+ feature(i) {
210
+ return {
211
+ index: i,
212
+ kind: this.kind(i),
213
+ color: this.color(i),
214
+ offsetPx: this.offsetPx(i),
215
+ offFromPx: this.offFromPx(i),
216
+ offToPx: this.offToPx(i),
217
+ slot: this.slot(i),
218
+ nslots: this.nslots(i),
219
+ bandMin: this.bandMin(i),
220
+ bandMax: this.bandMax(i),
221
+ routeType: this.routeType(i),
222
+ label: this.label(i),
223
+ mode: this.mode(i),
224
+ routes: this.routes(i),
225
+ acts: this.acts(i),
226
+ coordinates: this.coordinates(i),
227
+ };
228
+ }
229
+ *features() {
230
+ for (let i = 0; i < this.featureCount; i++)
231
+ yield this.feature(i);
232
+ }
233
+ /** GeoJSON, for comparing against the `geojson` emit or for a quick look. */
234
+ toGeoJSON() {
235
+ return {
236
+ type: "FeatureCollection",
237
+ features: Array.from(this.features(), (f) => ({
238
+ type: "Feature",
239
+ properties: {
240
+ kind: f.kind,
241
+ color: this.colorHex(f.index).slice(1).toUpperCase(),
242
+ routes: f.routes.join(","),
243
+ label: f.label,
244
+ route_type: f.routeType,
245
+ mode: f.mode,
246
+ slot: f.slot,
247
+ nslots: f.nslots,
248
+ offset_px: f.offsetPx,
249
+ off_from_px: f.offFromPx,
250
+ off_to_px: f.offToPx,
251
+ band_min: f.bandMin,
252
+ band_max: f.bandMax,
253
+ },
254
+ geometry: { type: "LineString", coordinates: f.coordinates },
255
+ })),
256
+ };
257
+ }
258
+ }
259
+ /** Decode a PLNB buffer. */
260
+ export function decodePlnb(buf) {
261
+ if (buf instanceof Uint8Array) {
262
+ // a Node Buffer is usually a view into a larger pooled allocation,
263
+ // so slice to its own bytes rather than handing the pool to a view
264
+ return new Plnb(buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength));
265
+ }
266
+ return new Plnb(buf);
267
+ }
268
+ //# sourceMappingURL=plnb.js.map