oculon 0.1.6 → 0.2.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.
Files changed (106) hide show
  1. package/README.md +93 -17
  2. package/dist/cli/main.js +397 -0
  3. package/dist/core/calls.d.ts +63 -0
  4. package/dist/core/calls.js +120 -0
  5. package/dist/core/der.d.ts +2 -0
  6. package/dist/core/der.js +17 -0
  7. package/dist/core/http.d.ts +30 -1
  8. package/dist/core/http.js +133 -29
  9. package/dist/core/pdf.d.ts +51 -0
  10. package/dist/core/pdf.js +211 -0
  11. package/dist/core/qr.d.ts +23 -0
  12. package/dist/core/qr.js +577 -0
  13. package/dist/core/quota.js +5 -0
  14. package/dist/core/raster.d.ts +6 -0
  15. package/dist/core/raster.js +298 -0
  16. package/dist/core/safeurl.d.ts +5 -0
  17. package/dist/core/safeurl.js +26 -0
  18. package/dist/core/verdict.d.ts +30 -0
  19. package/dist/core/verdict.js +164 -0
  20. package/dist/core/zip.d.ts +9 -0
  21. package/dist/core/zip.js +46 -0
  22. package/dist/index.d.ts +83 -0
  23. package/dist/index.js +128 -0
  24. package/dist/mcp.d.ts +1 -0
  25. package/dist/mcp.js +256 -6
  26. package/dist/modules/address.d.ts +6 -2
  27. package/dist/modules/address.js +32 -5
  28. package/dist/modules/apk.d.ts +37 -0
  29. package/dist/modules/apk.js +191 -0
  30. package/dist/modules/approvals.d.ts +40 -0
  31. package/dist/modules/approvals.js +155 -0
  32. package/dist/modules/archive.d.ts +21 -0
  33. package/dist/modules/archive.js +94 -0
  34. package/dist/modules/checks.d.ts +59 -0
  35. package/dist/modules/checks.js +167 -0
  36. package/dist/modules/contract.d.ts +56 -0
  37. package/dist/modules/contract.js +167 -0
  38. package/dist/modules/deployer.d.ts +42 -0
  39. package/dist/modules/deployer.js +90 -0
  40. package/dist/modules/doc.d.ts +83 -0
  41. package/dist/modules/doc.js +841 -0
  42. package/dist/modules/eml.d.ts +46 -0
  43. package/dist/modules/eml.js +175 -0
  44. package/dist/modules/hashcheck.d.ts +19 -3
  45. package/dist/modules/hashcheck.js +28 -4
  46. package/dist/modules/image.d.ts +32 -0
  47. package/dist/modules/image.js +276 -0
  48. package/dist/modules/invite.d.ts +27 -0
  49. package/dist/modules/invite.js +69 -0
  50. package/dist/modules/job.d.ts +33 -0
  51. package/dist/modules/job.js +64 -0
  52. package/dist/modules/meerkat.d.ts +1 -1
  53. package/dist/modules/meerkat.js +35 -2
  54. package/dist/modules/monitor.js +14 -0
  55. package/dist/modules/poisoning.d.ts +43 -0
  56. package/dist/modules/poisoning.js +114 -0
  57. package/dist/modules/qrcheck.d.ts +24 -0
  58. package/dist/modules/qrcheck.js +136 -0
  59. package/dist/modules/repo.d.ts +61 -0
  60. package/dist/modules/repo.js +162 -0
  61. package/dist/modules/report.d.ts +32 -0
  62. package/dist/modules/report.js +108 -0
  63. package/dist/modules/signature.d.ts +35 -0
  64. package/dist/modules/signature.js +283 -0
  65. package/dist/modules/site.d.ts +62 -0
  66. package/dist/modules/site.js +191 -0
  67. package/dist/modules/stocktoken.d.ts +48 -0
  68. package/dist/modules/stocktoken.js +99 -0
  69. package/dist/modules/trace.d.ts +37 -0
  70. package/dist/modules/trace.js +150 -0
  71. package/dist/modules/txexplain.d.ts +40 -0
  72. package/dist/modules/txexplain.js +135 -0
  73. package/dist/modules/urlcheck.js +15 -1
  74. package/dist/modules/utility.d.ts +27 -1
  75. package/dist/modules/utility.js +108 -11
  76. package/dist/modules/where.d.ts +63 -0
  77. package/dist/modules/where.js +165 -0
  78. package/dist/report-pdf.d.ts +7 -0
  79. package/dist/report-pdf.js +84 -0
  80. package/dist/sources/cfurlscan.d.ts +24 -0
  81. package/dist/sources/cfurlscan.js +46 -0
  82. package/dist/sources/chainabuse.d.ts +17 -0
  83. package/dist/sources/chainabuse.js +19 -0
  84. package/dist/sources/evm.d.ts +135 -0
  85. package/dist/sources/evm.js +260 -0
  86. package/dist/sources/phishlists.d.ts +20 -0
  87. package/dist/sources/phishlists.js +90 -0
  88. package/dist/telegram.d.ts +17 -0
  89. package/dist/telegram.js +151 -4
  90. package/dist/web/card.d.ts +28 -0
  91. package/dist/web/card.js +75 -0
  92. package/dist/web/docs.html +1 -1
  93. package/dist/web/index.html +213 -5
  94. package/dist/web/landing.html +1 -1
  95. package/dist/web/legal.html +3 -1
  96. package/dist/web/mcp.html +1 -1
  97. package/dist/web/openapi.js +15 -0
  98. package/dist/web/pages.d.ts +24 -0
  99. package/dist/web/pages.js +139 -0
  100. package/dist/web/public.js +16 -1
  101. package/dist/web/server.d.ts +13 -0
  102. package/dist/web/server.js +152 -13
  103. package/dist/web/token.html +25 -4
  104. package/dist/web/token.json +12 -1
  105. package/dist/web/utility.html +40 -14
  106. package/package.json +2 -2
@@ -1,5 +1,5 @@
1
1
  import type { Store } from './store.js';
2
- import type { Sourced } from './types.js';
2
+ import type { Provenance, Sourced } from './types.js';
3
3
  export declare function userAgent(url?: string): string;
4
4
  export interface GetOptions {
5
5
  source: string;
@@ -18,6 +18,8 @@ export interface HttpConfig {
18
18
  fetch?: typeof fetch;
19
19
  throttle?: boolean;
20
20
  retryDelayMs?: number;
21
+ /** Skip a host for a few minutes after it fails several times in a row (default on). */
22
+ breaker?: boolean;
21
23
  }
22
24
  export declare class Http {
23
25
  private readonly store;
@@ -31,6 +33,7 @@ export declare class Http {
31
33
  timeoutMs?: number;
32
34
  retries?: number;
33
35
  }): Promise<Sourced<Buffer>>;
36
+ private postBytesRaw;
34
37
  /** Uncached binary GET; 404 is reported as UNAVAILABLE. Network errors and 5xx are retried once. */
35
38
  getBytes(url: string, o: {
36
39
  source: string;
@@ -38,5 +41,31 @@ export declare class Http {
38
41
  timeoutMs?: number;
39
42
  retries?: number;
40
43
  }): Promise<Sourced<Buffer>>;
44
+ private getBytesRaw;
45
+ /**
46
+ * Uncached GET of a web page that keeps what a page check needs: the final URL after redirects, the status,
47
+ * the response headers and the body (capped at `maxBytes`). Not retried: a page that fails is reported as is.
48
+ */
49
+ getPage(url: string, o: {
50
+ source: string;
51
+ headers?: Record<string, string>;
52
+ timeoutMs?: number;
53
+ maxBytes?: number;
54
+ }): Promise<{
55
+ data: {
56
+ status: number;
57
+ finalUrl: string;
58
+ headers: Record<string, string>;
59
+ body: Buffer;
60
+ } | null;
61
+ prov: Provenance;
62
+ }>;
63
+ /** Record a finished call: the running check's replay log, and (for live calls) the /status stats. */
64
+ private note;
65
+ /**
66
+ * One live request with retries. `hostDown` is true when the failure says the host is unhealthy (network error,
67
+ * timeout, 5xx, 429), which feeds the breaker; a 4xx answer means the host is up.
68
+ */
69
+ private live;
41
70
  get<T = unknown>(url: string, o: GetOptions): Promise<Sourced<T>>;
42
71
  }
package/dist/core/http.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { breakerOpenUntil, breakerResult, logCall, MIRRORS, recordSourceCall } from './calls.js';
1
2
  import { scrubSecrets } from './keys.js';
2
3
  import { takeQuota } from './quota.js';
3
4
  /** Minimum gap between requests per host, following each provider's published guidance. */
@@ -130,6 +131,12 @@ export class Http {
130
131
  }
131
132
  /** Uncached binary POST (used for timestamp calendars). Returns the raw response bytes. */
132
133
  async postBytes(url, body, o) {
134
+ const t0 = Date.now();
135
+ const r = await this.postBytesRaw(url, body, o);
136
+ this.note(o.source, url, r.prov.status, Date.now() - t0, r.prov.note, undefined, r.prov.note !== 'daily quota reached');
137
+ return r;
138
+ }
139
+ async postBytesRaw(url, body, o) {
133
140
  if (!takeQuota(this.store, o.source))
134
141
  return { data: null, prov: prov(o.source, url, 'UNAVAILABLE', Date.now(), 'daily quota reached') };
135
142
  const doFetch = this.cfg.fetch ?? fetch;
@@ -161,6 +168,12 @@ export class Http {
161
168
  }
162
169
  /** Uncached binary GET; 404 is reported as UNAVAILABLE. Network errors and 5xx are retried once. */
163
170
  async getBytes(url, o) {
171
+ const t0 = Date.now();
172
+ const r = await this.getBytesRaw(url, o);
173
+ this.note(o.source, url, r.prov.status, Date.now() - t0, r.prov.note);
174
+ return r;
175
+ }
176
+ async getBytesRaw(url, o) {
164
177
  const doFetch = this.cfg.fetch ?? fetch;
165
178
  const retries = o.retries ?? 1;
166
179
  let lastErr = 'unknown error';
@@ -185,41 +198,64 @@ export class Http {
185
198
  }
186
199
  return { data: null, prov: prov(o.source, url, 'ERROR', Date.now(), lastErr) };
187
200
  }
188
- async get(url, o) {
189
- const as = o.as ?? 'json';
190
- const ttl = (o.ttlSec ?? 900) * 1000;
191
- const retries = o.retries ?? 2;
192
- const cached = this.store.cacheGet(url);
193
- const now = Date.now();
194
- if (cached && now - cached.fetchedAt < ttl) {
195
- return { data: this.parse(cached.body, as), prov: prov(o.source, url, 'CACHED', cached.fetchedAt) };
201
+ /**
202
+ * Uncached GET of a web page that keeps what a page check needs: the final URL after redirects, the status,
203
+ * the response headers and the body (capped at `maxBytes`). Not retried: a page that fails is reported as is.
204
+ */
205
+ async getPage(url, o) {
206
+ const doFetch = this.cfg.fetch ?? fetch;
207
+ const t0 = Date.now();
208
+ try {
209
+ if (this.cfg.throttle !== false)
210
+ await throttle(new URL(url).host);
211
+ const res = await doFetch(url, { headers: { 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0 Safari/537.36', accept: 'text/html,application/xhtml+xml,*/*', ...o.headers }, redirect: 'follow', signal: AbortSignal.timeout(o.timeoutMs ?? 20_000) });
212
+ const buf = Buffer.from(await res.arrayBuffer());
213
+ const headers = {};
214
+ res.headers.forEach((v, k) => { headers[k] = v; });
215
+ const data = { status: res.status, finalUrl: res.url || url, headers, body: buf.subarray(0, o.maxBytes ?? 3_000_000) };
216
+ const st = res.ok ? 'LIVE' : res.status === 404 ? 'UNAVAILABLE' : 'ERROR';
217
+ this.note(o.source, url, st, Date.now() - t0, res.ok ? undefined : `HTTP ${res.status}`);
218
+ return { data, prov: prov(o.source, url, st, Date.now(), res.ok ? undefined : `HTTP ${res.status}`) };
196
219
  }
197
- if (!takeQuota(this.store, o.source)) {
198
- if (cached)
199
- return { data: this.parse(cached.body, as), prov: prov(o.source, url, 'CACHED', cached.fetchedAt, 'daily quota reached; showing last cached result') };
200
- return { data: null, prov: prov(o.source, url, 'UNAVAILABLE', Date.now(), 'daily quota reached') };
220
+ catch (e) {
221
+ this.note(o.source, url, 'ERROR', Date.now() - t0, errMsg(e));
222
+ return { data: null, prov: prov(o.source, url, 'ERROR', Date.now(), errMsg(e)) };
223
+ }
224
+ }
225
+ /** Record a finished call: the running check's replay log, and (for live calls) the /status stats. */
226
+ note(source, url, status, ms, note, via, live = true) {
227
+ let host = '';
228
+ try {
229
+ host = new URL(url).host;
201
230
  }
231
+ catch { }
232
+ logCall({ source, host, status, ms: Math.round(ms), at: new Date().toISOString(), ...(note ? { note: scrubSecrets(note).slice(0, 200) } : {}), ...(via ? { via } : {}) });
233
+ if (live)
234
+ recordSourceCall(this.store, source, via ?? host, status === 'LIVE' || (status === 'UNAVAILABLE' && note === 'HTTP 404'), ms, note ? scrubSecrets(note) : undefined);
235
+ }
236
+ /**
237
+ * One live request with retries. `hostDown` is true when the failure says the host is unhealthy (network error,
238
+ * timeout, 5xx, 429), which feeds the breaker; a 4xx answer means the host is up.
239
+ */
240
+ async live(url, o, as, retries, extraHeaders = {}) {
202
241
  const doFetch = this.cfg.fetch ?? fetch;
203
242
  const host = new URL(url).host;
204
243
  const baseDelay = this.cfg.retryDelayMs ?? 1500;
205
244
  let lastErr = 'unknown error';
245
+ let hostDown = false;
206
246
  for (let attempt = 0; attempt <= retries; attempt++) {
207
247
  if (this.cfg.throttle !== false)
208
248
  await throttle(host);
209
249
  try {
210
250
  const res = await doFetch(url, {
211
- headers: {
212
- 'user-agent': userAgent(url),
213
- accept: as === 'json' ? 'application/json' : '*/*',
214
- ...o.headers,
215
- },
251
+ headers: { 'user-agent': userAgent(url), accept: as === 'json' ? 'application/json' : '*/*', ...o.headers, ...extraHeaders },
216
252
  signal: AbortSignal.timeout(o.timeoutMs ?? 20_000),
217
253
  });
218
- if (res.status === 404) {
219
- return { data: null, prov: prov(o.source, url, 'UNAVAILABLE', Date.now(), 'HTTP 404') };
220
- }
254
+ if (res.status === 404)
255
+ return { ok: false, notFound: true, err: 'HTTP 404', hostDown: false };
221
256
  if (res.status === 429 || res.status >= 500) {
222
257
  lastErr = `HTTP ${res.status}`;
258
+ hostDown = true;
223
259
  const retryAfter = Number(res.headers.get('retry-after'));
224
260
  const wait = Number.isFinite(retryAfter) && retryAfter > 0 ? Math.min(retryAfter * 1000, 30_000) : baseDelay * 2 ** attempt;
225
261
  if (attempt < retries)
@@ -229,6 +265,7 @@ export class Http {
229
265
  if (!res.ok) {
230
266
  const text = await res.text().catch(() => '');
231
267
  lastErr = `HTTP ${res.status}${errorReason(text)}`;
268
+ hostDown = false;
232
269
  // GitHub signals (secondary) rate limits with 403.
233
270
  if (res.status === 403 && (res.headers.get('x-ratelimit-remaining') === '0' || /rate limit/i.test(text))) {
234
271
  lastErr = 'HTTP 403 rate limited';
@@ -241,27 +278,94 @@ export class Http {
241
278
  const body = await res.text();
242
279
  if (o.rateLimitText?.test(body.slice(0, 300))) {
243
280
  lastErr = 'rate limited';
281
+ hostDown = false;
244
282
  if (attempt < retries)
245
283
  await sleep(Math.max(baseDelay, 6000) * 2 ** attempt);
246
284
  continue;
247
285
  }
248
- let data = this.parse(body, as);
249
- let stored = body;
250
- if (o.keep && as === 'json' && data != null) {
251
- data = o.keep(data);
252
- stored = JSON.stringify(data);
253
- }
254
- this.store.cachePut(url, stored);
255
- return { data, prov: prov(o.source, url, 'LIVE', Date.now()) };
286
+ this.parse(body, as); // throws ParseError on a broken body
287
+ return { ok: true, body };
256
288
  }
257
289
  catch (e) {
258
290
  lastErr = errMsg(e);
259
- if (e instanceof ParseError)
291
+ if (e instanceof ParseError) {
292
+ hostDown = false;
260
293
  break;
294
+ }
295
+ hostDown = true;
261
296
  if (attempt < retries)
262
297
  await sleep(baseDelay * 2 ** attempt);
263
298
  }
264
299
  }
300
+ return { ok: false, notFound: false, err: lastErr, hostDown };
301
+ }
302
+ async get(url, o) {
303
+ const as = o.as ?? 'json';
304
+ const ttl = (o.ttlSec ?? 900) * 1000;
305
+ const retries = o.retries ?? 2;
306
+ const cached = this.store.cacheGet(url);
307
+ const now = Date.now();
308
+ if (cached && now - cached.fetchedAt < ttl) {
309
+ this.note(o.source, url, 'CACHED', 0, undefined, undefined, false);
310
+ return { data: this.parse(cached.body, as), prov: prov(o.source, url, 'CACHED', cached.fetchedAt) };
311
+ }
312
+ if (!takeQuota(this.store, o.source)) {
313
+ this.note(o.source, url, cached ? 'CACHED' : 'UNAVAILABLE', 0, 'daily quota reached', undefined, false);
314
+ if (cached)
315
+ return { data: this.parse(cached.body, as), prov: prov(o.source, url, 'CACHED', cached.fetchedAt, 'daily quota reached; showing last cached result') };
316
+ return { data: null, prov: prov(o.source, url, 'UNAVAILABLE', Date.now(), 'daily quota reached') };
317
+ }
318
+ const host = new URL(url).host;
319
+ const useBreaker = this.cfg.breaker !== false;
320
+ const keep = (body) => {
321
+ let data = this.parse(body, as);
322
+ let stored = body;
323
+ if (o.keep && as === 'json' && data != null) {
324
+ data = o.keep(data);
325
+ stored = JSON.stringify(data);
326
+ }
327
+ return { data, stored };
328
+ };
329
+ let lastErr;
330
+ const skipped = useBreaker ? breakerOpenUntil(host) : null;
331
+ if (skipped) {
332
+ lastErr = `skipped: ${host} kept failing, retrying it after ${new Date(skipped).toISOString().slice(11, 16)} UTC`;
333
+ }
334
+ else {
335
+ const t0 = Date.now();
336
+ const r = await this.live(url, o, as, retries);
337
+ if (useBreaker)
338
+ breakerResult(host, r.ok || !r.hostDown);
339
+ if (r.ok) {
340
+ const { data, stored } = keep(r.body);
341
+ this.store.cachePut(url, stored);
342
+ this.note(o.source, url, 'LIVE', Date.now() - t0);
343
+ return { data, prov: prov(o.source, url, 'LIVE', Date.now()) };
344
+ }
345
+ if (r.notFound) {
346
+ this.note(o.source, url, 'UNAVAILABLE', Date.now() - t0, 'HTTP 404');
347
+ return { data: null, prov: prov(o.source, url, 'UNAVAILABLE', Date.now(), 'HTTP 404') };
348
+ }
349
+ lastErr = r.err;
350
+ this.note(o.source, url, 'ERROR', Date.now() - t0, r.err);
351
+ }
352
+ // Auto fallback: the same request on a mirror host, when there is one.
353
+ const mirror = MIRRORS[host];
354
+ const alt = mirror?.rewrite(new URL(url));
355
+ if (mirror && alt && !(useBreaker && breakerOpenUntil(mirror.host))) {
356
+ const t0 = Date.now();
357
+ const r = await this.live(alt.url, o, as, 1, alt.headers);
358
+ if (useBreaker)
359
+ breakerResult(mirror.host, r.ok || !r.hostDown);
360
+ if (r.ok) {
361
+ const { data, stored } = keep(r.body);
362
+ this.store.cachePut(url, stored);
363
+ const why = `${host} failed (${lastErr}); answered by ${mirror.host}`;
364
+ this.note(o.source, alt.url, 'LIVE', Date.now() - t0, why, mirror.host);
365
+ return { data, prov: prov(o.source, url, 'LIVE', Date.now(), why) };
366
+ }
367
+ this.note(o.source, alt.url, 'ERROR', Date.now() - t0, r.err, mirror.host);
368
+ }
265
369
  if (cached) {
266
370
  return {
267
371
  data: this.parse(cached.body, as),
@@ -0,0 +1,51 @@
1
+ /**
2
+ * A small PDF writer for reports, no dependencies: A4 pages, the standard Helvetica and Courier fonts
3
+ * (WinAnsi), headings, paragraphs with word wrap, bullet lists, key-value rows, coloured verdict bars and links.
4
+ * Characters outside WinAnsi are replaced, so any input gives a valid file.
5
+ */
6
+ type RGB = [number, number, number];
7
+ export type Block = {
8
+ t: 'title';
9
+ text: string;
10
+ } | {
11
+ t: 'h';
12
+ text: string;
13
+ } | {
14
+ t: 'p';
15
+ text: string;
16
+ size?: number;
17
+ color?: RGB;
18
+ } | {
19
+ t: 'mono';
20
+ text: string;
21
+ } | {
22
+ t: 'bullets';
23
+ items: string[];
24
+ color?: RGB;
25
+ } | {
26
+ t: 'kv';
27
+ rows: [string, string][];
28
+ } | {
29
+ t: 'bar';
30
+ label: string;
31
+ text: string;
32
+ color: RGB;
33
+ } | {
34
+ t: 'link';
35
+ text: string;
36
+ url: string;
37
+ } | {
38
+ t: 'table';
39
+ head: string[];
40
+ rows: string[][];
41
+ widths: number[];
42
+ } | {
43
+ t: 'gap';
44
+ h?: number;
45
+ };
46
+ /** WinAnsi-safe text: common punctuation mapped, anything else outside Latin-1 becomes '?'. */
47
+ export declare function ansi(s: string): string;
48
+ /** Render blocks to a PDF file. `footer` is printed on every page. */
49
+ export declare function renderPdf(blocks: Block[], footer: string): Buffer;
50
+ export declare const TONE_RGB: Record<string, RGB>;
51
+ export {};
@@ -0,0 +1,211 @@
1
+ /**
2
+ * A small PDF writer for reports, no dependencies: A4 pages, the standard Helvetica and Courier fonts
3
+ * (WinAnsi), headings, paragraphs with word wrap, bullet lists, key-value rows, coloured verdict bars and links.
4
+ * Characters outside WinAnsi are replaced, so any input gives a valid file.
5
+ */
6
+ const W = 595, H = 842, M = 50, CW = W - 2 * M;
7
+ const INK = [0.08, 0.1, 0.11], MUTE = [0.42, 0.47, 0.49], ACCENT = [0, 0.48, 0.53];
8
+ // Helvetica widths (per 1000 em) for ASCII 32-126; other characters use 556.
9
+ const HELV = [278, 278, 355, 556, 556, 889, 667, 191, 333, 333, 389, 584, 278, 333, 278, 278, 556, 556, 556, 556, 556, 556, 556, 556, 556, 556, 278, 278, 584, 584, 584, 556, 1015, 667, 667, 722, 722, 667, 611, 778, 722, 278, 500, 667, 556, 833, 722, 778, 667, 778, 722, 667, 611, 722, 667, 944, 667, 667, 611, 278, 278, 278, 469, 556, 333, 556, 556, 500, 556, 556, 278, 556, 556, 222, 222, 500, 222, 833, 556, 556, 556, 556, 333, 500, 278, 556, 500, 722, 500, 500, 500, 334, 260, 334, 584];
10
+ const BOLD_EXTRA = 1.06;
11
+ function width(s, size, font) {
12
+ if (font === 'F3')
13
+ return s.length * 600 * size / 1000;
14
+ let w = 0;
15
+ for (const ch of s) {
16
+ const c = ch.charCodeAt(0);
17
+ w += c >= 32 && c <= 126 ? HELV[c - 32] : 556;
18
+ }
19
+ return (w * size / 1000) * (font === 'F2' ? BOLD_EXTRA : 1);
20
+ }
21
+ /** WinAnsi-safe text: common punctuation mapped, anything else outside Latin-1 becomes '?'. */
22
+ export function ansi(s) {
23
+ return s
24
+ .replace(/[‘’]/g, "'").replace(/[“”]/g, '"').replace(/[–—]/g, '-').replace(/…/g, '...').replace(/→/g, '->').replace(/•/g, '-')
25
+ .replace(/[\r\t]/g, ' ')
26
+ .replace(/[^\n\x20-\x7e\xa0-\xff]/g, '?');
27
+ }
28
+ const esc = (s) => s.replace(/\\/g, '\\\\').replace(/\(/g, '\\(').replace(/\)/g, '\\)');
29
+ function wrap(text, size, font, max) {
30
+ const out = [];
31
+ for (const para of ansi(text).split('\n')) {
32
+ let line = '';
33
+ for (const word of para.split(/ +/)) {
34
+ const tryLine = line ? `${line} ${word}` : word;
35
+ if (width(tryLine, size, font) <= max) {
36
+ line = tryLine;
37
+ continue;
38
+ }
39
+ if (line)
40
+ out.push(line);
41
+ // A single word wider than the line (a hash, a URL) is cut into pieces.
42
+ let w = word;
43
+ while (width(w, size, font) > max) {
44
+ let n = w.length;
45
+ while (n > 1 && width(w.slice(0, n), size, font) > max)
46
+ n--;
47
+ out.push(w.slice(0, n));
48
+ w = w.slice(n);
49
+ }
50
+ line = w;
51
+ }
52
+ out.push(line);
53
+ }
54
+ return out;
55
+ }
56
+ class Doc {
57
+ footer;
58
+ pages = [];
59
+ links = [];
60
+ y = 0;
61
+ constructor(footer) {
62
+ this.footer = footer;
63
+ this.page();
64
+ }
65
+ get ops() { return this.pages[this.pages.length - 1]; }
66
+ page() {
67
+ this.pages.push([]);
68
+ this.links.push([]);
69
+ this.y = H - M;
70
+ }
71
+ need(h) { if (this.y - h < M + 24)
72
+ this.page(); }
73
+ text(x, y, s, size, font, color = INK) {
74
+ this.ops.push(`BT /${font} ${size} Tf ${color.map((c) => c.toFixed(3)).join(' ')} rg ${x.toFixed(1)} ${y.toFixed(1)} Td (${esc(s)}) Tj ET`);
75
+ }
76
+ rect(x, y, w, h, color) {
77
+ this.ops.push(`${color.map((c) => c.toFixed(3)).join(' ')} rg ${x.toFixed(1)} ${y.toFixed(1)} ${w.toFixed(1)} ${h.toFixed(1)} re f`);
78
+ }
79
+ line(y, color = [0.85, 0.87, 0.88]) {
80
+ this.ops.push(`${color.map((c) => c.toFixed(3)).join(' ')} RG 0.8 w ${M} ${y.toFixed(1)} m ${W - M} ${y.toFixed(1)} l S`);
81
+ }
82
+ para(s, size, font, color = INK, indent = 0, lead = 1.45) {
83
+ for (const l of wrap(s, size, font, CW - indent)) {
84
+ this.need(size * lead);
85
+ this.y -= size * lead;
86
+ this.text(M + indent, this.y, l, size, font, color);
87
+ }
88
+ }
89
+ build() {
90
+ const objs = [];
91
+ const add = (s) => { objs.push(s); return objs.length; };
92
+ add('<< /Type /Catalog /Pages 2 0 R >>');
93
+ add('PAGES');
94
+ const f1 = add('<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>');
95
+ const f2 = add('<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Bold /Encoding /WinAnsiEncoding >>');
96
+ const f3 = add('<< /Type /Font /Subtype /Type1 /BaseFont /Courier /Encoding /WinAnsiEncoding >>');
97
+ const kids = [];
98
+ this.pages.forEach((ops, i) => {
99
+ const foot = `BT /F1 8 Tf ${MUTE.join(' ')} rg ${M} 28 Td (${esc(ansi(this.footer))}) Tj ET BT /F1 8 Tf ${MUTE.join(' ')} rg ${W - M - 40} 28 Td (Page ${i + 1} of ${this.pages.length}) Tj ET`;
100
+ const content = [...ops, foot].join('\n');
101
+ const c = add(`<< /Length ${Buffer.byteLength(content, 'latin1')} >>\nstream\n${content}\nendstream`);
102
+ const annots = this.links[i].map((l) => add(`<< /Type /Annot /Subtype /Link /Rect [${l.rect.map((n) => n.toFixed(1)).join(' ')}] /Border [0 0 0] /A << /S /URI /URI (${esc(ansi(l.url))}) >> >>`));
103
+ kids.push(add(`<< /Type /Page /Parent 2 0 R /MediaBox [0 0 ${W} ${H}] /Resources << /Font << /F1 ${f1} 0 R /F2 ${f2} 0 R /F3 ${f3} 0 R >> >> /Contents ${c} 0 R${annots.length ? ` /Annots [${annots.map((a) => `${a} 0 R`).join(' ')}]` : ''} >>`));
104
+ });
105
+ objs[1] = `<< /Type /Pages /Kids [${kids.map((k) => `${k} 0 R`).join(' ')}] /Count ${kids.length} >>`;
106
+ add('<< /Producer (Oculon) /Title (Oculon report) >>');
107
+ return Buffer.from(rebuild(objs), 'latin1');
108
+ }
109
+ }
110
+ function rebuild(objs) {
111
+ let out = '%PDF-1.4\n%\xe2\xe3\xcf\xd3\n';
112
+ const offsets = [];
113
+ objs.forEach((o, i) => {
114
+ offsets.push(Buffer.byteLength(out, 'latin1'));
115
+ out += `${i + 1} 0 obj\n${o}\nendobj\n`;
116
+ });
117
+ const xref = Buffer.byteLength(out, 'latin1');
118
+ out += `xref\n0 ${objs.length + 1}\n0000000000 65535 f \n${offsets.map((o) => `${String(o).padStart(10, '0')} 00000 n \n`).join('')}`;
119
+ out += `trailer\n<< /Size ${objs.length + 1} /Root 1 0 R /Info ${objs.length} 0 R >>\nstartxref\n${xref}\n%%EOF\n`;
120
+ return out;
121
+ }
122
+ /** Render blocks to a PDF file. `footer` is printed on every page. */
123
+ export function renderPdf(blocks, footer) {
124
+ const d = new Doc(footer);
125
+ for (const b of blocks) {
126
+ switch (b.t) {
127
+ case 'title':
128
+ d.text(M, d.y - 10, 'OCULON', 9, 'F2', ACCENT);
129
+ d.y -= 22;
130
+ d.para(b.text, 20, 'F2', INK, 0, 1.25);
131
+ d.y -= 8;
132
+ d.line(d.y);
133
+ d.y -= 6;
134
+ break;
135
+ case 'h':
136
+ d.need(40);
137
+ d.y -= 14;
138
+ d.para(b.text.toUpperCase(), 9.5, 'F2', ACCENT, 0, 1.6);
139
+ d.y -= 2;
140
+ break;
141
+ case 'p':
142
+ d.para(b.text, b.size ?? 10.5, 'F1', b.color ?? INK);
143
+ break;
144
+ case 'mono':
145
+ d.para(b.text, 8.5, 'F3', INK, 0, 1.4);
146
+ break;
147
+ case 'bullets':
148
+ for (const it of b.items) {
149
+ const lines = wrap(it, 10.5, 'F1', CW - 14);
150
+ lines.forEach((l, i) => {
151
+ d.need(15);
152
+ d.y -= 15;
153
+ if (i === 0)
154
+ d.text(M, d.y, '-', 10.5, 'F2', b.color ?? ACCENT);
155
+ d.text(M + 14, d.y, l, 10.5, 'F1');
156
+ });
157
+ }
158
+ break;
159
+ case 'kv':
160
+ for (const [k, v] of b.rows) {
161
+ const lines = wrap(v, 10, 'F1', CW - 150);
162
+ lines.forEach((l, i) => {
163
+ d.need(15);
164
+ d.y -= 15;
165
+ if (i === 0)
166
+ d.text(M, d.y, ansi(k), 9, 'F2', MUTE);
167
+ d.text(M + 150, d.y, l, 10, 'F1');
168
+ });
169
+ d.y -= 3;
170
+ }
171
+ break;
172
+ case 'bar': {
173
+ d.need(48);
174
+ d.y -= 42;
175
+ d.rect(M, d.y, CW, 36, b.color);
176
+ d.text(M + 14, d.y + 22, ansi(b.label), 8, 'F2', [1, 1, 1]);
177
+ d.text(M + 14, d.y + 8, ansi(b.text).slice(0, 70), 14, 'F2', [1, 1, 1]);
178
+ d.y -= 4;
179
+ break;
180
+ }
181
+ case 'link': {
182
+ d.need(15);
183
+ d.y -= 15;
184
+ const s = ansi(b.text);
185
+ d.text(M, d.y, s, 10, 'F1', ACCENT);
186
+ d.links[d.pages.length - 1].push({ page: d.pages.length - 1, rect: [M, d.y - 2, M + width(s, 10, 'F1'), d.y + 10], url: b.url });
187
+ break;
188
+ }
189
+ case 'table': {
190
+ const xs = b.widths.reduce((a, w, i) => [...a, (a[i - 1] ?? M) + (i ? b.widths[i - 1] : 0)], []).map((x, i) => (i === 0 ? M : x));
191
+ const row = (cells, font, color) => {
192
+ const wrapped = cells.map((c, i) => wrap(c, 8.5, font, b.widths[i] - 6));
193
+ const h = Math.max(...wrapped.map((w) => w.length)) * 11 + 4;
194
+ d.need(h);
195
+ wrapped.forEach((ls, i) => ls.forEach((l, j) => d.text(xs[i], d.y - 11 - j * 11, l, 8.5, font, color)));
196
+ d.y -= h;
197
+ d.line(d.y + 1);
198
+ };
199
+ row(b.head, 'F2', MUTE);
200
+ for (const r of b.rows)
201
+ row(r, 'F1', INK);
202
+ break;
203
+ }
204
+ case 'gap':
205
+ d.y -= b.h ?? 8;
206
+ break;
207
+ }
208
+ }
209
+ return d.build();
210
+ }
211
+ export const TONE_RGB = { bad: [0.78, 0.18, 0.24], warn: [0.79, 0.52, 0.06], ok: [0.1, 0.55, 0.35], info: [0.25, 0.32, 0.36] };
@@ -0,0 +1,23 @@
1
+ /**
2
+ * QR code reader without dependencies: finds the three finder patterns in a grayscale image, locates the
3
+ * alignment pattern, samples the module grid through a perspective transform, reads format information,
4
+ * removes the mask, de-interleaves the blocks, corrects errors with Reed-Solomon and decodes numeric,
5
+ * alphanumeric and byte segments (UTF-8). Supports versions 1 to 15 (up to about 400 characters), which covers
6
+ * links, payment and wallet codes, Wi-Fi codes and contact cards in practice.
7
+ */
8
+ import type { Gray } from './raster.js';
9
+ /** Corrects a block in place (data then EC codewords). Returns false when there are too many errors. */
10
+ export declare function rsCorrect(msg: number[], nsym: number): boolean;
11
+ type Ec = [number, [number, number][]];
12
+ /** Per version: EC codewords per block and (block count, data codewords) groups, for L, M, Q, H. */
13
+ export declare const EC: Record<number, [Ec, Ec, Ec, Ec]>;
14
+ export declare const ALIGN: Record<number, number[]>;
15
+ /** Modules that hold function patterns (not data) for a version. */
16
+ export declare function functionMask(version: number): Uint8Array;
17
+ /** Decodes a sampled module grid (1 = dark), row-major. */
18
+ export declare function decodeGrid(grid: Uint8Array, n: number): string | null;
19
+ /** Dark/light per pixel: local mean thresholding over an integral image. */
20
+ export declare function binarize(img: Gray, invert?: boolean): Uint8Array;
21
+ /** Finds and decodes QR codes in an image. Returns the decoded texts (usually one). */
22
+ export declare function readQr(img: Gray): string[];
23
+ export {};