grayling 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/LICENSE +661 -0
  2. package/README.md +268 -2
  3. package/dist/index.d.ts +290 -0
  4. package/dist/index.js +50 -0
  5. package/dist/node/archive.d.ts +4 -0
  6. package/dist/node/archive.js +115 -0
  7. package/dist/node/client.d.ts +188 -0
  8. package/dist/node/client.js +669 -0
  9. package/dist/node/connection.d.ts +56 -0
  10. package/dist/node/connection.js +240 -0
  11. package/dist/node/errors.d.ts +14 -0
  12. package/dist/node/errors.js +13 -0
  13. package/dist/node/handler.d.ts +56 -0
  14. package/dist/node/handler.js +208 -0
  15. package/dist/node/index.d.ts +15 -0
  16. package/dist/node/index.js +14 -0
  17. package/dist/node/paths.d.ts +51 -0
  18. package/dist/node/paths.js +115 -0
  19. package/dist/node/program.d.ts +74 -0
  20. package/dist/node/program.js +385 -0
  21. package/dist/node/state.d.ts +7 -0
  22. package/dist/node/state.js +12 -0
  23. package/dist/node/suggest.d.ts +13 -0
  24. package/dist/node/suggest.js +87 -0
  25. package/dist/node/types.d.ts +142 -0
  26. package/dist/node/types.js +13 -0
  27. package/dist/node/version.d.ts +10 -0
  28. package/dist/node/version.js +50 -0
  29. package/dist/node/wire.d.ts +32 -0
  30. package/dist/node/wire.js +44 -0
  31. package/dist/react/index.d.ts +121 -0
  32. package/dist/react/index.js +205 -0
  33. package/dist/web/announce.d.ts +51 -0
  34. package/dist/web/announce.js +141 -0
  35. package/dist/web/attach.d.ts +77 -0
  36. package/dist/web/attach.js +89 -0
  37. package/dist/web/box.d.ts +57 -0
  38. package/dist/web/box.js +150 -0
  39. package/dist/web/dom.d.ts +80 -0
  40. package/dist/web/dom.js +265 -0
  41. package/dist/web/index.d.ts +8 -0
  42. package/dist/web/index.js +8 -0
  43. package/dist/web/logic.d.ts +308 -0
  44. package/dist/web/logic.js +467 -0
  45. package/dist/web/overlay.d.ts +56 -0
  46. package/dist/web/overlay.js +211 -0
  47. package/dist/web/style.css +193 -0
  48. package/dist/web/suggester.d.ts +189 -0
  49. package/dist/web/suggester.js +696 -0
  50. package/dist/web/ui.d.ts +65 -0
  51. package/dist/web/ui.js +32 -0
  52. package/dist/web/usage.d.ts +39 -0
  53. package/dist/web/usage.js +84 -0
  54. package/package.json +89 -4
  55. package/program.json +35 -0
@@ -0,0 +1,115 @@
1
+ /** Reading the one file we want out of a `.tar.gz` or a `.zip`, with Node's own zlib (no dependencies). */
2
+ import { gunzipSync, inflateRawSync } from 'node:zlib';
3
+ import { GraylingError } from './errors.js';
4
+ const MAX_OUT = 512 * 1024 * 1024;
5
+ const base = (name) => name.slice(name.lastIndexOf('/') + 1);
6
+ /** The contents of the first file named `want` (anywhere in the archive) of a `.tar.gz` made by `tar` (ustar, pax or GNU). */
7
+ export function fromTarGz(archive, want) {
8
+ let tar;
9
+ try {
10
+ tar = gunzipSync(archive, { maxOutputLength: MAX_OUT });
11
+ }
12
+ catch (e) {
13
+ throw new GraylingError('unpack', `the archive is not a valid .tar.gz: ${e.message}`);
14
+ }
15
+ let off = 0;
16
+ let longName;
17
+ const text = (b) => {
18
+ const z = b.indexOf(0);
19
+ return b.toString('utf8', 0, z < 0 ? b.length : z);
20
+ };
21
+ while (off + 512 <= tar.length) {
22
+ const h = tar.subarray(off, off + 512);
23
+ if (h.every((b) => b === 0))
24
+ break;
25
+ // The header's checksum: the sum of its bytes with the checksum field read as spaces.
26
+ let sum = 0;
27
+ for (let i = 0; i < 512; i++)
28
+ sum += i >= 148 && i < 156 ? 32 : h[i];
29
+ const stored = parseInt(text(h.subarray(148, 156)).trim() || 'x', 8);
30
+ if (sum !== stored)
31
+ throw new GraylingError('unpack', 'the .tar.gz has a damaged header');
32
+ const sizeField = h.subarray(124, 136);
33
+ if (sizeField[0] & 0x80)
34
+ throw new GraylingError('unpack', 'the .tar.gz holds a file too large to read');
35
+ const size = parseInt(text(sizeField).trim() || '0', 8);
36
+ const type = String.fromCharCode(h[156] || 48);
37
+ const data = tar.subarray(off + 512, off + 512 + size);
38
+ off += 512 + Math.ceil(size / 512) * 512;
39
+ if (type === 'L') {
40
+ longName = text(data);
41
+ continue;
42
+ }
43
+ if (type === 'x' || type === 'g') {
44
+ const m = /(?:^|\n)\d+ path=([^\n]*)\n/.exec(data.toString('utf8'));
45
+ if (type === 'x' && m)
46
+ longName = m[1];
47
+ continue;
48
+ }
49
+ let name = text(h.subarray(0, 100));
50
+ if (text(h.subarray(257, 262)) === 'ustar') {
51
+ const prefix = text(h.subarray(345, 500));
52
+ if (prefix)
53
+ name = `${prefix}/${name}`;
54
+ }
55
+ if (longName !== undefined) {
56
+ name = longName;
57
+ longName = undefined;
58
+ }
59
+ if ((type === '0' || type === '7') && base(name) === want) {
60
+ if (data.length < size)
61
+ throw new GraylingError('unpack', 'the .tar.gz ends too soon');
62
+ return Buffer.from(data);
63
+ }
64
+ }
65
+ throw new GraylingError('unpack', `the archive does not hold ${want}`);
66
+ }
67
+ /** The contents of the first file named `want` (anywhere in the archive) of a `.zip` (stored or deflated; no zip64). */
68
+ export function fromZip(zip, want) {
69
+ let eocd = -1;
70
+ for (let i = zip.length - 22; i >= Math.max(0, zip.length - 22 - 0xffff); i--) {
71
+ if (zip.readUInt32LE(i) === 0x06054b50) {
72
+ eocd = i;
73
+ break;
74
+ }
75
+ }
76
+ if (eocd < 0)
77
+ throw new GraylingError('unpack', 'the archive is not a valid .zip');
78
+ const count = zip.readUInt16LE(eocd + 10);
79
+ let p = zip.readUInt32LE(eocd + 16);
80
+ for (let n = 0; n < count; n++) {
81
+ if (p + 46 > zip.length || zip.readUInt32LE(p) !== 0x02014b50)
82
+ throw new GraylingError('unpack', 'the .zip has a damaged directory');
83
+ const method = zip.readUInt16LE(p + 10);
84
+ const csize = zip.readUInt32LE(p + 20);
85
+ const usize = zip.readUInt32LE(p + 24);
86
+ const nameLen = zip.readUInt16LE(p + 28);
87
+ const extraLen = zip.readUInt16LE(p + 30);
88
+ const commentLen = zip.readUInt16LE(p + 32);
89
+ const local = zip.readUInt32LE(p + 42);
90
+ const name = zip.toString('utf8', p + 46, p + 46 + nameLen);
91
+ p += 46 + nameLen + extraLen + commentLen;
92
+ if (name.endsWith('/') || base(name) !== want)
93
+ continue;
94
+ if (csize === 0xffffffff || usize === 0xffffffff || local === 0xffffffff)
95
+ throw new GraylingError('unpack', 'zip64 archives are not supported');
96
+ if (usize > MAX_OUT)
97
+ throw new GraylingError('unpack', 'the .zip holds a file too large to read');
98
+ if (zip.readUInt32LE(local) !== 0x04034b50)
99
+ throw new GraylingError('unpack', 'the .zip has a damaged entry');
100
+ const start = local + 30 + zip.readUInt16LE(local + 26) + zip.readUInt16LE(local + 28);
101
+ const raw = zip.subarray(start, start + csize);
102
+ if (method === 0)
103
+ return Buffer.from(raw);
104
+ if (method === 8) {
105
+ try {
106
+ return inflateRawSync(raw, { maxOutputLength: MAX_OUT });
107
+ }
108
+ catch (e) {
109
+ throw new GraylingError('unpack', `the .zip entry is damaged: ${e.message}`);
110
+ }
111
+ }
112
+ throw new GraylingError('unpack', `the .zip entry is packed in a way that is not supported (method ${method})`);
113
+ }
114
+ throw new GraylingError('unpack', `the archive does not hold ${want}`);
115
+ }
@@ -0,0 +1,188 @@
1
+ import type { SuggestJudged, SuggestResponse, SuggestSettings } from '../index.js';
2
+ import { type GraylingPaths } from './paths.js';
3
+ import { type InstallOptions } from './program.js';
4
+ import { GRAYLING_SETTING_KEYS, type AdoptWhat, type ClaimedApp, type GraylingEvents, type GraylingSettings, type GraylingState, type GraylingSuggestRequest, type HostHello, type HostInfo, type LearnAction, type SuggestCounts, type SuggestOutcome, type TextsProvider, type UsageAnswer } from './types.js';
5
+ /** The protocol this client speaks (docs/protocol.md). */
6
+ export declare const PROTOCOL = 1;
7
+ /** All the waits, in milliseconds. The defaults are the protocol's; tests make them short. */
8
+ export interface Timeouts {
9
+ /** How long to try to connect to a host that is starting: 15 s. */
10
+ start: number;
11
+ /** How long hello may take: 10 s. */
12
+ hello: number;
13
+ /** How long a request may take: 30 s. */
14
+ request: number;
15
+ /** How long a request made while the connection is down waits for it to come back: 3 s. */
16
+ wait: number;
17
+ /** How long to wait for the old host to let go after `replace`: 10 s. */
18
+ replace: number;
19
+ /** The time between tries to connect to a host that is starting: 50 ms. */
20
+ poll: number;
21
+ /** The wait before the first reconnect try (doubled after each failure) and its limit: 0.2 s, 5 s. */
22
+ backoffMin: number;
23
+ backoffMax: number;
24
+ /** The most a provider has to write its texts: 10 min. */
25
+ provider: number;
26
+ /** The least time between two `provide` messages that only say the person typed: 1 min. */
27
+ provideEvery: number;
28
+ }
29
+ export declare const DEFAULT_TIMEOUTS: Timeouts;
30
+ export interface ConnectOptions {
31
+ /** Who this is: letters, digits, `.`, `_`, `-`, at most 40 (default `node`). Hydor: `hydor`. */
32
+ client?: string;
33
+ /** Tells two copies of one client apart (default none). */
34
+ instance?: string;
35
+ /** The client's own version (default: this package's). */
36
+ clientVersion?: string;
37
+ /** The `grayling` program to start when nothing answers (default: `findProgram()`). `null`: none. */
38
+ program?: string | null;
39
+ /** false: never start a host (and never replace one); connect to the one that runs, or fail. */
40
+ start?: boolean;
41
+ /** The version of the program (default: `GRAYLING_TEST_VERSION`, else what the program says, else this package's). */
42
+ engine?: string;
43
+ /** `GRAYLING_HOME`: keep everything in this folder (tests). */
44
+ home?: string;
45
+ /** The environment the paths are read from, and the host's is made from (default: this process's). */
46
+ env?: NodeJS.ProcessEnv;
47
+ /** The app's folder, to look for the platform package from (default: the working folder). */
48
+ appDir?: string;
49
+ /** Waits (for tests). */
50
+ timeouts?: Partial<Timeouts>;
51
+ /**
52
+ * When no program is found (and none is given): connect to an engine that already runs (another program started it) and get the
53
+ * program in the background, so that this client can start one when that engine ends (`setProgram`); with no engine running,
54
+ * get the program first, then start it. `progress` hears the download (also in the background). A download that fails leaves the
55
+ * client as it is (`programError` says why, and it reconnects to an engine as before). Only with `connect()`.
56
+ */
57
+ install?: boolean | Pick<InstallOptions, 'progress' | 'signal' | 'baseUrl' | 'manifest' | 'target'>;
58
+ }
59
+ export interface SuggestCallOptions {
60
+ /** Abort it when the suggestion is no longer wanted: the host is told to cancel. */
61
+ signal?: AbortSignal;
62
+ /** A text box or browser tab: a newer request of the tab drops the one before (default: the request's `client`). */
63
+ tab?: string;
64
+ }
65
+ type Listener<T> = (value: T) => void;
66
+ /** A connection to the engine host that keeps itself up. Make one with `connect()`. */
67
+ export declare class Grayling {
68
+ readonly paths: GraylingPaths;
69
+ private readonly t;
70
+ private readonly env;
71
+ private program;
72
+ private readonly canStart;
73
+ private engine;
74
+ private readonly hello;
75
+ private conn;
76
+ private helloAnswer;
77
+ private closing;
78
+ private reconnecting;
79
+ private lastError;
80
+ private lastState;
81
+ private waiters;
82
+ private nap;
83
+ private listeners;
84
+ private watched;
85
+ private claimed;
86
+ private provider;
87
+ private typedAt;
88
+ private providedAt;
89
+ private providedKey;
90
+ private provideTimer;
91
+ /** Lines the host sent that were not JSON (a count, for people who look). */
92
+ garbage: number;
93
+ /** Why the program could not be had in the background (`connect`'s `install`), when it could not. */
94
+ programError: Error | undefined;
95
+ /** @internal Use `connect()`. */
96
+ constructor(o?: ConnectOptions);
97
+ /** @internal */
98
+ open(): Promise<void>;
99
+ /** Whether this client has a program to start the engine with. */
100
+ get hasProgram(): boolean;
101
+ /**
102
+ * Gives the client the program to start the engine with, when it had none (what `installProgram` made): from now on it starts an
103
+ * engine when none answers, and hands an older one over to its own, as a client that had a program from the start does. (Not for a
104
+ * client made with `start: false`.)
105
+ */
106
+ setProgram(program: string): void;
107
+ /** The host's pid, version and protocol, from hello; null while there is no connection. */
108
+ get host(): HostHello | null;
109
+ get connected(): boolean;
110
+ private openConn;
111
+ private shake;
112
+ private newSocket;
113
+ /** Connects, starting the program when no host answers, and trying again every 50 ms until `timeouts.start`. */
114
+ private connectStarting;
115
+ /** A connection is up: wake the asks that wait, put back what was watched, claimed and provided. */
116
+ private up;
117
+ private down;
118
+ /** Connects again, with a wait that grows from 0.2 s to 5 s while the host is not there. */
119
+ private reconnect;
120
+ /** The connection, waiting up to `ms` for it to come back; null when it did not (or the client was closed, or `signal` aborted). */
121
+ private waitUp;
122
+ private unavailable;
123
+ /** A request and its answer; made while the connection is down it waits for it (up to `timeouts.wait`), and once more after `replaced`. */
124
+ private call;
125
+ private has;
126
+ private emit;
127
+ /** Listens to an event; returns what stops listening. `state` and `claims` are watched on the host while someone listens. */
128
+ on<K extends keyof GraylingEvents>(event: K, fn: Listener<GraylingEvents[K]>): () => void;
129
+ off<K extends keyof GraylingEvents>(event: K, fn: Listener<GraylingEvents[K]>): void;
130
+ /** The host's state whenever it changes (at most every 150 ms): `on('state', fn)`. */
131
+ watch(fn: Listener<GraylingState>): () => void;
132
+ /** What the host is told to send: the events someone listens to. */
133
+ private syncWatch;
134
+ private onEvent;
135
+ /** A suggestion, or null (and `suggestRaw` says why): off, still starting, cancelled by a newer one of the tab, or the host is not there. */
136
+ suggest(req: GraylingSuggestRequest, o?: SuggestCallOptions): Promise<SuggestResponse | null>;
137
+ /** `suggest`, with the reason there was none: `starting`, `dropped`, `memory`, `failed`, `off`, `elsewhere`, `unavailable`, `aborted`, `timeout`. */
138
+ suggestRaw(req: GraylingSuggestRequest, o?: SuggestCallOptions): Promise<SuggestOutcome<SuggestResponse>>;
139
+ /** A text box got the focus: what is set up is loaded (the first one ever starts the set-up). Null when the host is not there. */
140
+ warm(): Promise<GraylingState | null>;
141
+ /** Chat text for the session cache (the person's own words are `own: true`). Best effort: nothing happens when the host is not there. */
142
+ session(id: string, texts: string[], own?: boolean[]): Promise<void>;
143
+ private remember;
144
+ /**
145
+ * The settings and the status. When the host cannot be reached it is still an answer: the last state known, with `status.state`
146
+ * `failed` and the reason in `status.detail`.
147
+ */
148
+ state(): Promise<GraylingState>;
149
+ /** Changes some of the host's settings (shared by every client); every field is checked, and a bad one is the error `bad`. */
150
+ set(patch: Partial<GraylingSettings>): Promise<GraylingState>;
151
+ /** Adds counts (and judged guesses) of what suggestions did: never any text. Gives this client's usage and thresholds. */
152
+ usage(counts: Partial<SuggestCounts>, judged?: SuggestJudged): Promise<UsageAnswer>;
153
+ /** Starts this client's counts again from nothing (and what was judged with them). */
154
+ resetUsage(): Promise<GraylingState>;
155
+ /** A word the person kept as typed: never offered as a typo again, to any client. How many are kept now. */
156
+ keep(word: string): Promise<number>;
157
+ /** Forgets every kept word. */
158
+ forgetKept(): Promise<GraylingState>;
159
+ /** Controls learning: `now` (also goes on with a paused run), `pause`, `stop`, `forget` (the personal model). */
160
+ learn(action: LearnAction): Promise<GraylingState>;
161
+ /**
162
+ * Says this client has texts to learn from (`fn`), or no longer (`null`). When a learning run begins the host asks for them and
163
+ * `fn` writes them (see `TextsProvider`). Call it again with `typedAt` (milliseconds; 0: unknown) when the person has typed: it
164
+ * is sent at most once a minute. It is put back after a reconnect.
165
+ */
166
+ provide(fn: TextsProvider | null, typedAt?: number): Promise<void>;
167
+ private sendProvide;
168
+ private runProvider;
169
+ /** The programs of this client that show suggestions of their own: the desktop app leaves them alone. They are this connection's. */
170
+ claim(apps: ClaimedApp[]): Promise<void>;
171
+ /** Brings in what an earlier Hydor kept for itself, once, each only where the host has none. What was adopted. */
172
+ adopt(what: AdoptWhat): Promise<string[]>;
173
+ /** The host's process, folders and clients. */
174
+ info(): Promise<HostInfo>;
175
+ /**
176
+ * Asks the host to end, and ends this client (it would otherwise start the host again). With `ifAlone` the host ends only when this
177
+ * is the only connection it has; the answer says whether it is ending (this client ends either way).
178
+ */
179
+ stopHost(options?: {
180
+ ifAlone?: boolean;
181
+ }): Promise<boolean>;
182
+ /** Ends the connection, and does not connect again. The host goes on (it ends itself ten minutes after the last client left). */
183
+ close(): Promise<void>;
184
+ }
185
+ /** Connects to the engine host, starting the `grayling` program when none answers. Rejects when it cannot (`GraylingError`). */
186
+ export declare function connect(o?: ConnectOptions): Promise<Grayling>;
187
+ export { GRAYLING_SETTING_KEYS };
188
+ export type { SuggestSettings };