nervur 0.20.0 → 0.20.2

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 (157) hide show
  1. package/README.md +229 -20
  2. package/dist/being/being.d.ts +1 -0
  3. package/dist/being/being.js +5 -1
  4. package/dist/being/faculty.d.ts +1 -0
  5. package/dist/being/faculty.js +13 -7
  6. package/dist/being/index.d.ts +1 -0
  7. package/dist/being/index.js +1 -0
  8. package/dist/being/kind.d.ts +4 -0
  9. package/dist/being/kind.js +28 -0
  10. package/dist/being/types.d.ts +3 -4
  11. package/dist/browser/index.d.ts +35 -0
  12. package/dist/browser/index.js +188 -0
  13. package/dist/browser/worker.d.ts +12 -0
  14. package/dist/browser/worker.js +40 -0
  15. package/dist/browser.d.ts +1 -0
  16. package/dist/browser.js +7 -0
  17. package/dist/cli/command.d.ts +13 -0
  18. package/dist/cli/command.js +237 -0
  19. package/dist/cli/harbor.d.ts +19 -0
  20. package/dist/cli/harbor.js +99 -0
  21. package/dist/cli/main.d.ts +2 -0
  22. package/dist/cli/main.js +14 -0
  23. package/dist/contract/index.d.ts +16 -2
  24. package/dist/contract/index.js +13 -3
  25. package/dist/edge/index.d.ts +57 -0
  26. package/dist/edge/index.js +306 -0
  27. package/dist/edge.d.ts +1 -0
  28. package/dist/edge.js +8 -0
  29. package/dist/folder/index.d.ts +9 -4
  30. package/dist/folder/index.js +89 -84
  31. package/dist/harbor/carrying.d.ts +17 -0
  32. package/dist/harbor/carrying.js +38 -0
  33. package/dist/harbor/catalogue.d.ts +27 -0
  34. package/dist/harbor/catalogue.js +101 -0
  35. package/dist/harbor/dock.d.ts +32 -3
  36. package/dist/harbor/dock.js +98 -12
  37. package/dist/harbor/harbor.d.ts +27 -8
  38. package/dist/harbor/harbor.js +217 -26
  39. package/dist/harbor/index.d.ts +8 -2
  40. package/dist/harbor/index.js +8 -1
  41. package/dist/harbor/package.d.ts +12 -0
  42. package/dist/harbor/package.js +130 -0
  43. package/dist/harbor/probe.d.ts +18 -0
  44. package/dist/harbor/probe.js +15 -0
  45. package/dist/harbor/registry.d.ts +6 -3
  46. package/dist/harbor/registry.js +83 -7
  47. package/dist/harbor/relay.d.ts +15 -0
  48. package/dist/harbor/relay.js +387 -0
  49. package/dist/harbor/root-line.d.ts +9 -0
  50. package/dist/harbor/root-line.js +38 -0
  51. package/dist/harbor/terrain.d.ts +14 -1
  52. package/dist/harbor/terrain.js +19 -0
  53. package/dist/http/index.d.ts +4 -0
  54. package/dist/http/index.js +156 -0
  55. package/dist/http/websocket.d.ts +29 -0
  56. package/dist/http/websocket.js +133 -0
  57. package/dist/index.d.ts +5 -4
  58. package/dist/index.js +12 -6
  59. package/dist/line/answer.d.ts +8 -0
  60. package/dist/line/answer.js +60 -0
  61. package/dist/line/frame.d.ts +34 -0
  62. package/dist/line/frame.js +81 -0
  63. package/dist/line/ground.d.ts +3 -0
  64. package/dist/line/ground.js +9 -0
  65. package/dist/line/index.d.ts +5 -0
  66. package/dist/line/index.js +9 -0
  67. package/dist/line/push.d.ts +7 -0
  68. package/dist/line/push.js +92 -0
  69. package/dist/line/web.d.ts +30 -0
  70. package/dist/line/web.js +181 -0
  71. package/dist/node/index.d.ts +32 -0
  72. package/dist/node/index.js +164 -0
  73. package/dist/node.d.ts +1 -0
  74. package/dist/node.js +7 -0
  75. package/dist/pointer/bodies.d.ts +11 -3
  76. package/dist/pointer/bodies.js +47 -18
  77. package/dist/pointer/index.d.ts +1 -1
  78. package/dist/pointer/index.js +1 -1
  79. package/dist/pointer/world.d.ts +12 -5
  80. package/dist/pointer/world.js +29 -14
  81. package/dist/quo/address.d.ts +19 -0
  82. package/dist/quo/address.js +84 -0
  83. package/dist/quo/door.d.ts +1 -1
  84. package/dist/quo/door.js +6 -4
  85. package/dist/quo/index.d.ts +1 -0
  86. package/dist/quo/index.js +1 -0
  87. package/dist/quo/invitation.d.ts +1 -0
  88. package/dist/quo/invitation.js +9 -5
  89. package/dist/quo/keys.js +1 -1
  90. package/dist/tcp/frame.d.ts +25 -0
  91. package/dist/tcp/frame.js +64 -0
  92. package/dist/tcp/index.d.ts +24 -0
  93. package/dist/tcp/index.js +260 -0
  94. package/dist/ward/index.d.ts +3 -2
  95. package/dist/ward/index.js +2 -1
  96. package/dist/ward/pilot.d.ts +8 -0
  97. package/dist/ward/pilot.js +50 -0
  98. package/dist/ward/stance.d.ts +4 -4
  99. package/dist/ward/stance.js +10 -7
  100. package/dist/ward/ward-being.d.ts +4 -1
  101. package/dist/ward/ward-being.js +8 -2
  102. package/dist/ward/ward.d.ts +11 -2
  103. package/dist/ward/ward.js +41 -5
  104. package/package.json +28 -2
  105. package/src/being/being.ts +5 -1
  106. package/src/being/faculty.ts +14 -7
  107. package/src/being/index.ts +1 -0
  108. package/src/being/kind.ts +30 -0
  109. package/src/being/types.ts +8 -6
  110. package/src/browser/index.ts +207 -0
  111. package/src/browser/worker.ts +66 -0
  112. package/src/browser.ts +9 -0
  113. package/src/cli/command.ts +224 -0
  114. package/src/cli/harbor.ts +103 -0
  115. package/src/cli/main.ts +13 -0
  116. package/src/contract/index.ts +42 -10
  117. package/src/edge/index.ts +359 -0
  118. package/src/edge.ts +10 -0
  119. package/src/folder/index.ts +87 -84
  120. package/src/harbor/carrying.ts +56 -0
  121. package/src/harbor/catalogue.ts +125 -0
  122. package/src/harbor/dock.ts +122 -15
  123. package/src/harbor/harbor.ts +240 -36
  124. package/src/harbor/index.ts +10 -3
  125. package/src/harbor/package.ts +147 -0
  126. package/src/harbor/probe.ts +34 -0
  127. package/src/harbor/registry.ts +73 -9
  128. package/src/harbor/relay.ts +399 -0
  129. package/src/harbor/root-line.ts +39 -0
  130. package/src/harbor/terrain.ts +31 -3
  131. package/src/http/index.ts +150 -0
  132. package/src/http/websocket.ts +124 -0
  133. package/src/index.ts +39 -6
  134. package/src/line/answer.ts +59 -0
  135. package/src/line/frame.ts +88 -0
  136. package/src/line/ground.ts +19 -0
  137. package/src/line/index.ts +9 -0
  138. package/src/line/push.ts +112 -0
  139. package/src/line/web.ts +227 -0
  140. package/src/node/index.ts +170 -0
  141. package/src/node.ts +9 -0
  142. package/src/pointer/bodies.ts +45 -16
  143. package/src/pointer/index.ts +1 -1
  144. package/src/pointer/world.ts +38 -19
  145. package/src/quo/address.ts +87 -0
  146. package/src/quo/door.ts +6 -4
  147. package/src/quo/index.ts +1 -0
  148. package/src/quo/invitation.ts +10 -6
  149. package/src/quo/keys.ts +1 -1
  150. package/src/stand/main.ts +1 -0
  151. package/src/stand/stand.ts +87 -6
  152. package/src/tcp/index.ts +284 -0
  153. package/src/ward/index.ts +3 -2
  154. package/src/ward/pilot.ts +50 -0
  155. package/src/ward/stance.ts +14 -8
  156. package/src/ward/ward-being.ts +9 -3
  157. package/src/ward/ward.ts +53 -6
@@ -0,0 +1,66 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // The browser harbor in a worker, one for every tab. A shared, dedicated
3
+ // or service worker calls `serveWorker` as its script starts, with the
4
+ // harbor it opens; every tab reaches that harbor's root line with
5
+ // `rootOf`, one request on a channel of its own. A service worker that
6
+ // hears a push asks every relay client of its harbor to `ring`, since a
7
+ // push carries nothing but the news that something waits.
8
+ import type { JsonObject } from '../being/index.ts';
9
+ import { RELAY_CLIENT, rootLine, type Harbor } from '../harbor/index.ts';
10
+
11
+ type Asked = { request?: unknown };
12
+ type Answering = { postMessage(message: unknown): void };
13
+ type Scope = {
14
+ addEventListener(type: string, listener: (event: never) => void): void;
15
+ };
16
+ type Connecting = { ports: readonly MessagePort[] };
17
+ type Messaging = { data: unknown; ports: readonly MessagePort[] };
18
+ type Pushing = { waitUntil(work: Promise<unknown>): void };
19
+
20
+ const answer = async (harbor: Promise<Harbor>, data: unknown, reply: Answering | undefined): Promise<void> => {
21
+ if (!reply) return;
22
+ let out: JsonObject;
23
+ try {
24
+ out = await rootLine(await harbor, (data as Asked | null)?.request);
25
+ } catch {
26
+ out = { error: 'the harbor threw' };
27
+ }
28
+ reply.postMessage(out);
29
+ };
30
+
31
+ // Every relay client of the harbor asked to collect what waits.
32
+ export const ringAll = async (harbor: Harbor): Promise<JsonObject[]> => {
33
+ const keys = Object.entries(harbor.box.partition.beings)
34
+ .filter(([, row]) => row.class === RELAY_CLIENT)
35
+ .map(([key]) => key);
36
+ return Promise.all(keys.map(async (being) => (await harbor.root('ask', { being, method: 'ring' })) as JsonObject));
37
+ };
38
+
39
+ // Called as the worker's script starts, so no tab's first message is
40
+ // lost while the harbor opens.
41
+ export const serveWorker = (harbor: Promise<Harbor>, scope: Scope = globalThis as unknown as Scope): void => {
42
+ scope.addEventListener('connect', (event: Connecting) => {
43
+ const port = event.ports[0]!;
44
+ port.onmessage = (message) => void answer(harbor, message.data, message.ports[0]);
45
+ port.start();
46
+ });
47
+ scope.addEventListener('message', (event: Messaging) => void answer(harbor, event.data, event.ports[0]));
48
+ scope.addEventListener('push', (event: Pushing) => event.waitUntil(harbor.then(ringAll)));
49
+ };
50
+
51
+ // Where a tab sends root requests: a shared worker's port, a dedicated
52
+ // worker, or a service worker.
53
+ export type Reaching = { postMessage(message: unknown, transfer: Transferable[]): void };
54
+
55
+ // A tab's root line to the worker's harbor.
56
+ export const rootOf =
57
+ (worker: Reaching) =>
58
+ (request: JsonObject): Promise<JsonObject> =>
59
+ new Promise((resolve) => {
60
+ const channel = new MessageChannel();
61
+ channel.port1.onmessage = (message) => {
62
+ channel.port1.close();
63
+ resolve(message.data as JsonObject);
64
+ };
65
+ worker.postMessage({ request }, [channel.port2]);
66
+ });
package/src/browser.ts ADDED
@@ -0,0 +1,9 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // `nervur` as a browser bundle reads it: the main entry, with the browser
3
+ // ground added, so `Harbor.open()` keeps a harbor in IndexedDB.
4
+ import { browserGround } from './browser/index.ts';
5
+ import { addGround } from './harbor/index.ts';
6
+
7
+ export * from './index.ts';
8
+
9
+ addGround(browserGround);
@@ -0,0 +1,224 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // `nervur`: a harbor on this machine. Each command is one root request, the
3
+ // same the root line carries from any front, printed as one JSON line.
4
+ //
5
+ // nervur init [--dir D] the harbor made: its seed drawn,
6
+ // its catalogue stood, and an owner
7
+ // invitation for whoever made it
8
+ // nervur serve [--dir D] [--host H] [--port P] the harbor served: Quo over TCP,
9
+ // and the root line on its socket
10
+ // nervur module add <file> a module the catalogue runs
11
+ // nervur module remove <module> a module it runs no more
12
+ // nervur modules what the catalogue runs
13
+ // nervur census [--ward W] the empty ask
14
+ // nervur sweep every place of the folder this
15
+ // harbor does not name, gone
16
+ // nervur export [--with-seed] the harbor as one JSON line, to
17
+ // carry it to another ground; with
18
+ // --with-seed the seed goes too
19
+ // nervur import <file> a carried harbor into an empty
20
+ // folder, `-` being this input
21
+ // nervur open <key> <kind> a faculty stands in the box ward
22
+ // nervur host <ward> [--seed S] a hosted ward stands
23
+ // nervur route <ward pk> <address... | none> where a ward is reached, in order
24
+ // nervur reach <address...> where this harbor is reached, as
25
+ // every invitation it gives says
26
+ // nervur boot [--ward W] <key> <kind> a being stands
27
+ // nervur unboot [--ward W] <being> a being goes
28
+ // nervur public [--ward W] <key | none> the being a stranger reaches
29
+ // nervur invite [--ward W] <being> <id> an invitation on a being
30
+ // nervur ask [--ward W] [being] [method] [args] a being, asked as the owner
31
+ // nervur own [--ward W] <id> an invitation for an owner
32
+ // nervur disown [--ward W] <id> an owner no more
33
+ // nervur pilot <name> <invitation> [address] a far ward held as its owner, by a
34
+ // pilot being of the box ward, at
35
+ // the address or the invitation's at
36
+ // nervur <command> --via <name> ... the command asked of the far ward
37
+ // that pilot holds, as its owner
38
+ //
39
+ // D is --dir, then $NERVUR_DIR, then ~/.nervur. A module file is named from
40
+ // where the command runs and kept by its absolute path. No --ward is the box
41
+ // ward, and a pilot holds one ward, so --via takes no --ward. The exit is 1
42
+ // when the answer is an error.
43
+ import { existsSync } from 'node:fs';
44
+ import { readFile } from 'node:fs/promises';
45
+ import { join, resolve } from 'node:path';
46
+ import type { JsonObject } from '../being/index.ts';
47
+ import type { RootRequest } from '../harbor/index.ts';
48
+ import { harborDir } from '../node/index.ts';
49
+ import { carry, isServed, land, open, request, serve } from './harbor.ts';
50
+
51
+ const USAGE = 'usage: nervur <init|serve|module|modules|census|sweep|open|host|route|reach|boot|unboot|public|invite|ask|own|disown|pilot|export|import> [args] [--dir D] [--ward W] [--via V] [--seed S] [--with-seed] [--host H] [--port P]';
52
+ const FLAGS = new Set(['dir', 'ward', 'via', 'seed', 'host', 'port']);
53
+ // The one flag that stands alone, since what it names is a yes.
54
+ const ALONE = 'with-seed';
55
+
56
+ export const parse = (argv: string[]): { command?: string; words: string[]; flags: Record<string, string> } => {
57
+ const flags: Record<string, string> = {};
58
+ const words: string[] = [];
59
+ for (let i = 0; i < argv.length; i += 1) {
60
+ const arg = argv[i]!;
61
+ const name = arg.startsWith('--') ? arg.slice(2) : undefined;
62
+ if (name === undefined) words.push(arg);
63
+ else if (name === ALONE) flags[name] = 'yes';
64
+ else if (!FLAGS.has(name) || argv[i + 1] === undefined) throw new Error(`--${name} is no flag with a value`);
65
+ else flags[name] = argv[(i += 1)]!;
66
+ }
67
+ const [command, ...rest] = words;
68
+ return { ...(command === undefined ? {} : { command }), words: rest, flags };
69
+ };
70
+
71
+ // What this command was handed on its input, for `import -`.
72
+ const standingIn = async (): Promise<string> => {
73
+ let text = '';
74
+ for await (const chunk of process.stdin) text += (chunk as Buffer).toString('utf8');
75
+ return text;
76
+ };
77
+
78
+ const none = (word: string): string | null => (word === 'none' ? null : word);
79
+ const json = (word: string | undefined): JsonObject | undefined => (word === undefined ? undefined : (JSON.parse(word) as JsonObject));
80
+ const catalogue = (method: string, args: JsonObject = {}): RootRequest => ({ method: 'ask', args: { being: 'catalogue', method, args } });
81
+
82
+ // The root request a command names, or a throw saying what it lacks.
83
+ export const requestOf = (command: string, words: string[], flags: Record<string, string>): RootRequest => {
84
+ const need = (n: number): string[] => {
85
+ if (words.length !== n) throw new Error(`${command} takes ${n} argument${n === 1 ? '' : 's'}`);
86
+ return words;
87
+ };
88
+ const at = flags.ward === undefined ? {} : { ward: flags.ward };
89
+ switch (command) {
90
+ case 'module': {
91
+ const [verb, what] = need(2);
92
+ if (verb === 'add') return catalogue('add', { from: resolve(what!) });
93
+ if (verb === 'remove') return catalogue('remove', { module: what! });
94
+ throw new Error('module is add or remove');
95
+ }
96
+ case 'modules':
97
+ return (need(0), catalogue('modules'));
98
+ case 'sweep':
99
+ return (need(0), { method: 'sweep', args: {} });
100
+ case 'census':
101
+ return (need(0), at);
102
+ case 'open': {
103
+ const [key, kind] = need(2);
104
+ return { method: 'open', args: { key: key!, class: kind! } };
105
+ }
106
+ case 'host': {
107
+ const [ward] = need(1);
108
+ return { method: 'host', args: { ward: ward!, ...(flags.seed === undefined ? {} : { seed: flags.seed }) } };
109
+ }
110
+ case 'route': {
111
+ const [ward, ...where] = words;
112
+ if (ward === undefined || where.length === 0) throw new Error('route takes a ward pk and its addresses, or none');
113
+ return { method: 'route', args: { ward, at: where.length === 1 && where[0] === 'none' ? null : where } };
114
+ }
115
+ case 'reach':
116
+ if (words.length === 0) throw new Error('reach takes the addresses this harbor is reached at');
117
+ return { method: 'reach', args: { at: words } };
118
+ case 'boot': {
119
+ const [key, kind] = need(2);
120
+ return { ...at, method: 'boot', args: { key: key!, class: kind! } };
121
+ }
122
+ case 'unboot':
123
+ return { ...at, method: 'unboot', args: { being: need(1)[0]! } };
124
+ case 'public':
125
+ return { ...at, method: 'public', args: { key: none(need(1)[0]!) } };
126
+ case 'invite': {
127
+ const [being, id] = need(2);
128
+ return { ...at, method: 'invite', args: { being: being!, id: id! } };
129
+ }
130
+ case 'ask': {
131
+ if (words.length > 3) throw new Error('ask takes at most a being, a method and its args');
132
+ const [being, method, args] = words;
133
+ return { ...at, method: 'ask', args: { ...(being === undefined ? {} : { being }), ...(method === undefined ? {} : { method }), ...(args === undefined ? {} : { args: json(args)! }) } };
134
+ }
135
+ case 'own':
136
+ case 'disown':
137
+ return { ...at, method: command, args: { id: need(1)[0]! } };
138
+ default:
139
+ throw new Error(USAGE);
140
+ }
141
+ };
142
+
143
+ // An error answer at any depth the root line or an ask carries it.
144
+ const failed = (answer: unknown): boolean => {
145
+ if (typeof answer !== 'object' || answer === null) return false;
146
+ const a = answer as JsonObject;
147
+ return 'error' in a || failed(a.answer);
148
+ };
149
+
150
+ export const main = async (argv: string[], env: Record<string, string | undefined>, print: (line: string) => void): Promise<number> => {
151
+ const { command, words, flags } = parse(argv);
152
+ if (command === undefined) throw new Error(USAGE);
153
+ const dir = flags.dir ?? harborDir(env);
154
+ const out = (answer: JsonObject): number => {
155
+ print(JSON.stringify(answer));
156
+ return failed(answer) ? 1 : 0;
157
+ };
158
+ if (command === 'init') {
159
+ if (words.length > 0) throw new Error('init takes no argument');
160
+ if (existsSync(join(dir, 'seed'))) return out({ error: `a harbor stands at ${dir}` });
161
+ const harbor = await open(dir);
162
+ try {
163
+ const owner = await harbor.root('own', { id: 'owner' });
164
+ return out({ pk: harbor.box.pk, owner: owner as JsonObject });
165
+ } finally {
166
+ await harbor.close();
167
+ }
168
+ }
169
+ if (command === 'export' || command === 'import') {
170
+ if (words.length !== (command === 'import' ? 1 : 0)) throw new Error(`${command} takes ${command === 'import' ? 'one file' : 'no argument'}`);
171
+ if (flags.via !== undefined) throw new Error(`${command} reads this folder, so it takes no --via`);
172
+ if (await isServed(dir)) throw new Error(`a harbor is served from ${dir}: stop it first`);
173
+ if (command === 'export') return out((await carry(dir, flags[ALONE] !== undefined)) as unknown as JsonObject);
174
+ const text = words[0] === '-' ? await standingIn() : await readFile(words[0]!, 'utf8');
175
+ return out({ landed: await land(dir, JSON.parse(text)) });
176
+ }
177
+ if (command === 'serve') {
178
+ if (words.length > 0) throw new Error('serve takes no argument');
179
+ const served = await serve(dir, flags.host, flags.port === undefined ? undefined : Number(flags.port));
180
+ const stop = (): void => void served.close().then(() => process.exit(0));
181
+ process.once('SIGINT', stop);
182
+ process.once('SIGTERM', stop);
183
+ print(JSON.stringify({ pk: served.pk, at: served.at, listening: served.listening, root: served.root }));
184
+ return SERVING;
185
+ }
186
+ if (command === 'pilot') {
187
+ if (words.length !== 2 && words.length !== 3) throw new Error('pilot takes a name, an invitation, and an address where the invitation carries none');
188
+ const [name, invitation, at] = words as [string, string, string | undefined];
189
+ const held = JSON.parse(invitation) as JsonObject;
190
+ for (const req of pilotRequests(name, held, at)) {
191
+ const answer = await request(dir, req);
192
+ if (!failed(answer)) continue;
193
+ if (req.method === 'ask') await request(dir, { method: 'unboot', args: { being: name } });
194
+ return out(answer);
195
+ }
196
+ return out({ piloting: name, ward: held.ward! });
197
+ }
198
+ if (flags.via === undefined) return out(await request(dir, requestOf(command, words, flags)));
199
+ if (flags.ward !== undefined) throw new Error('--via takes no --ward');
200
+ return out(farAnswer(await request(dir, via(flags.via, requestOf(command, words, flags)))));
201
+ };
202
+
203
+ // The root requests that hold a far ward: its route where one is named,
204
+ // else the take learns it from the invitation's `at`; the pilot; the take.
205
+ export const pilotRequests = (name: string, invitation: JsonObject, at?: string): RootRequest[] => [
206
+ ...(at === undefined ? [] : [{ method: 'route', args: { ward: invitation.ward ?? null, at: [at] } }]),
207
+ { method: 'boot', args: { key: name, class: 'org.nervur.pilot' } },
208
+ { method: 'ask', args: { being: name, method: 'hold', args: { invitation } } },
209
+ ];
210
+
211
+ // A root request, asked of the far ward a pilot holds.
212
+ export const via = (pilot: string, far: RootRequest): RootRequest => ({
213
+ method: 'ask',
214
+ args: { being: pilot, method: 'pilot', args: { ...(far.method === undefined ? {} : { method: far.method }), ...(far.args === undefined ? {} : { args: far.args }) } },
215
+ });
216
+
217
+ // The far ward-being's answer out of the pilot's, or the local error.
218
+ export const farAnswer = (local: JsonObject): JsonObject => {
219
+ const inner = (local.answer as JsonObject | undefined)?.answer;
220
+ return typeof inner === 'object' && inner !== null && !Array.isArray(inner) ? inner : local;
221
+ };
222
+
223
+ // What `main` answers for a harbor it keeps serving: no exit yet.
224
+ export const SERVING = -1;
@@ -0,0 +1,103 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // A harbor on this machine, as the `nervur` command stands it: a harbor of
3
+ // the Node ground in a folder, served while `serve` runs, and asked over
4
+ // its root line's socket.
5
+ //
6
+ // A root request goes to a served harbor over its socket. With none served,
7
+ // the command unpacks the harbor from its folder, asks, and closes it, so
8
+ // one process at a time writes the folder.
9
+ import { existsSync } from 'node:fs';
10
+ import { mkdir, writeFile } from 'node:fs/promises';
11
+ import { join } from 'node:path';
12
+ import type { JsonObject } from '../being/index.ts';
13
+ import { hex, isHex, unhex } from '../crypto/index.ts';
14
+ import { FolderCustody, FolderMemory } from '../folder/index.ts';
15
+ import { Harbor, rootLine, type CarrierFaculty, type RootRequest } from '../harbor/index.ts';
16
+ import { askServed, NodeTerrain, socketOf } from '../node/index.ts';
17
+ import { CryptoEntropy } from '../pointer/index.ts';
18
+ import { TCP_OPENING } from '../tcp/index.ts';
19
+
20
+ // A harbor of a folder, opened for one ask: it listens nowhere and serves
21
+ // nothing.
22
+ export const open = (dir: string): Promise<Harbor> => Harbor.open(new NodeTerrain({ dir, wakes: false, serves: false }));
23
+
24
+ // Whether a harbor of this folder is served now.
25
+ export const isServed = async (dir: string): Promise<boolean> => (await askServed(dir, {})) !== undefined;
26
+
27
+ export const request = async (dir: string, req: RootRequest): Promise<JsonObject> => {
28
+ const served = await askServed(dir, req);
29
+ if (served !== undefined) return served;
30
+ const harbor = await open(dir);
31
+ try {
32
+ return await rootLine(harbor, req);
33
+ } finally {
34
+ await harbor.close();
35
+ }
36
+ };
37
+
38
+ // A harbor as one JSON value, for carrying it to another ground: every
39
+ // place of its memory with its sealed entries as hex, and its seed only
40
+ // where the one who asks says so, since custody holds it and a package
41
+ // without it opens nowhere.
42
+ export type Carried = { seed?: string; places: Record<string, Record<string, string>> };
43
+
44
+ const carried = (value: unknown): Carried | null => {
45
+ if (typeof value !== 'object' || value === null) return null;
46
+ const { seed, places } = value as { seed?: unknown; places?: unknown };
47
+ if (seed !== undefined && !isHex(seed, 32)) return null;
48
+ if (typeof places !== 'object' || places === null || Array.isArray(places)) return null;
49
+ for (const entries of Object.values(places)) {
50
+ if (typeof entries !== 'object' || entries === null || Array.isArray(entries)) return null;
51
+ for (const bytes of Object.values(entries)) if (!isHex(bytes)) return null;
52
+ }
53
+ return { ...(seed === undefined ? {} : { seed }), places: places as Carried['places'] };
54
+ };
55
+
56
+ // The harbor of a folder, read as bytes alone. No harbor opens, so
57
+ // nothing is asked and nothing is written.
58
+ export const carry = async (dir: string, seed: boolean): Promise<Carried> => {
59
+ const memory = new FolderMemory(dir);
60
+ const places: Carried['places'] = {};
61
+ for (const place of await memory.places()) {
62
+ places[place] = Object.fromEntries([...(await memory.read(place))].map(([name, bytes]) => [name, hex(bytes)]));
63
+ }
64
+ if (!seed) return { places };
65
+ return { seed: hex(await new FolderCustody(dir, new CryptoEntropy()).seed()), places };
66
+ };
67
+
68
+ // A carried harbor into an empty folder. A folder holding a seed or a
69
+ // place is left as it stands, and a package with no seed needs one there
70
+ // already, which a terrain that seals its custody writes its own way.
71
+ export const land = async (dir: string, value: unknown): Promise<string[]> => {
72
+ const held = carried(value);
73
+ if (held === null) throw new Error('that is no carried harbor');
74
+ const memory = new FolderMemory(dir);
75
+ if ((await memory.places()).length > 0 || (held.seed !== undefined && existsSync(join(dir, 'seed')))) throw new Error(`a harbor stands at ${dir}`);
76
+ await mkdir(dir, { recursive: true, mode: 0o700 });
77
+ if (held.seed !== undefined) await writeFile(join(dir, 'seed'), `${held.seed}\n`, { mode: 0o600, flag: 'wx' });
78
+ else if (!existsSync(join(dir, 'seed'))) throw new Error('the package carries no seed, and none is held here');
79
+ for (const [place, entries] of Object.entries(held.places)) {
80
+ await memory.write(place, new Map(Object.entries(entries).map(([name, bytes]) => [name, unhex(bytes)])));
81
+ }
82
+ return Object.keys(held.places);
83
+ };
84
+
85
+ // A served harbor: its pk, its tcp address, every address its carriers
86
+ // listen at, and its root line's socket.
87
+ export type Served = { pk: string; at: string; listening: string[]; root: string; close(): Promise<void> };
88
+
89
+ // The harbor served: a harbor of the Node ground, with Quo over TCP on
90
+ // host and port.
91
+ export const serve = async (dir: string, host?: string, port?: number): Promise<Served> => {
92
+ const harbor = await Harbor.open(new NodeTerrain({ dir }));
93
+ if (!harbor.box.being(TCP_OPENING.key)) await harbor.root('open', { key: TCP_OPENING.key, class: TCP_OPENING.kind });
94
+ const tcp = harbor.box.being(TCP_OPENING.key) as CarrierFaculty;
95
+ if (host !== undefined || port !== undefined || tcp.listening().length === 0) {
96
+ const heard = (await harbor.root('ask', { being: TCP_OPENING.key, method: 'listen', args: { ...(host === undefined ? {} : { host }), ...(port === undefined ? {} : { port }) } })) as JsonObject;
97
+ if (typeof (heard.answer as JsonObject | undefined)?.at !== 'string') {
98
+ await harbor.close();
99
+ throw new Error(`the harbor does not listen: ${JSON.stringify(heard)}`);
100
+ }
101
+ }
102
+ return { pk: harbor.box.pk, at: tcp.listening()[0]!, listening: harbor.carriers.flatMap((c) => c.listening()), root: socketOf(dir), close: () => harbor.close() };
103
+ };
@@ -0,0 +1,13 @@
1
+ #!/usr/bin/env node
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ // The `nervur` program: `command.ts` over this process's arguments. A
4
+ // command that cannot run exits 2 and says why on stderr.
5
+ import { main, SERVING } from './command.ts';
6
+
7
+ try {
8
+ const code = await main(process.argv.slice(2), process.env, (line) => process.stdout.write(`${line}\n`));
9
+ if (code !== SERVING) process.exitCode = code;
10
+ } catch (e) {
11
+ process.stderr.write(`nervur: ${(e as Error).message}\n`);
12
+ process.exitCode = 2;
13
+ }
@@ -1,7 +1,8 @@
1
1
  // SPDX-License-Identifier: Apache-2.0
2
- // The contracts: what the onion cannot unpack from cells, each an abstract
3
- // class, so a registry can tell at run time which class fulfils which. The
4
- // class differs by terrain, and the contract does not.
2
+ // The contracts: what the onion cannot unpack from cells, a module's code
3
+ // among them, each an abstract class, so a registry can tell at run time
4
+ // which class fulfils which. The class differs by terrain, and the
5
+ // contract does not.
5
6
  import type { Draw } from '../quo/index.ts';
6
7
 
7
8
  // Drawn bytes.
@@ -20,25 +21,56 @@ export abstract class Clock {
20
21
  abstract wait(ms: number): { done: Promise<void>; cancel(): void };
21
22
  }
22
23
 
23
- // One ward's partition, opened by name: the rows the ward writes into
24
- // directly, told after every write, and kept once at the end of an arrival.
24
+ // One ward's partition, as the harbor's package opens it: the rows the
25
+ // ward writes into directly, told after every write, and kept once at the
26
+ // end of an arrival.
25
27
  export interface Rows {
26
28
  readonly rows: Record<string, unknown>;
27
29
  told(row: string): void;
28
30
  kept(): Promise<boolean>;
29
31
  }
30
32
 
33
+ // A harbor's memory as a terrain keeps it: sealed entries it cannot read,
34
+ // in places, each entry by name. Every name is lowercase hex the kit
35
+ // chose, so a body may use it as a file name as it stands.
31
36
  export abstract class Memory {
32
- abstract open(name: string): Promise<Rows>;
37
+ // Every entry kept in a place; a place nothing was kept in is empty.
38
+ abstract read(place: string): Promise<Map<string, Uint8Array>>;
39
+ // One keep, whole: every entry written and every null removed together,
40
+ // or none of them. A read after a keep that did not finish, in this run
41
+ // or in the run before it, holds the place as it was or as the keep
42
+ // leaves it, and never half of each.
43
+ abstract write(place: string, entries: ReadonlyMap<string, Uint8Array | null>): Promise<void>;
44
+ // Every place this memory holds something in, in any order.
45
+ abstract places(): Promise<string[]>;
46
+ // A place and everything in it, gone.
47
+ abstract forget(place: string): Promise<void>;
33
48
  }
34
49
 
35
- // A ward's seed by the harbor's name for it: thirty-two bytes, the same
36
- // every time that name is asked.
50
+ // The harbor's seed: thirty-two bytes, the same every time. It is the one
51
+ // secret a terrain holds.
37
52
  export abstract class Custody {
38
- abstract seed(name: string): Promise<Uint8Array>;
53
+ abstract seed(): Promise<Uint8Array>;
39
54
  }
40
55
 
41
- // Bytes to a ward pk in; bytes, or null for nothing, out.
56
+ // A module: the code a harbor's classes come from. It declares its own
57
+ // name, a reversed domain as a kind is, and its version.
58
+ export type Module = { readonly module: string; readonly version: string; readonly classes: readonly unknown[] };
59
+
60
+ // A module as a loader found it, with `from`, the name this loader finds
61
+ // it by again.
62
+ export type Loaded = Module & { readonly from: string };
63
+
64
+ // Code, by the name a harbor keeps for it, or null where this loader has
65
+ // none. Code never crosses a door and never lives in a cell, so it is the
66
+ // one thing beside the seed a terrain hands in: a map, an import, a bundle.
67
+ export abstract class Loader {
68
+ abstract load(from: string): Promise<Loaded | null>;
69
+ }
70
+
71
+ // Bytes to a ward pk in; bytes, or null for nothing, out. A harbor hands a
72
+ // terrain's carrier what it holds no route for; what it routes goes to its
73
+ // carrier faculties.
42
74
  export abstract class Carrier {
43
75
  abstract carry(pk: string, bytes: Uint8Array): Promise<Uint8Array | null>;
44
76
  }