chirli 0.1.0 → 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 (90) hide show
  1. package/ARCHITECTURE.md +18 -20
  2. package/CONTRIBUTING.md +7 -3
  3. package/README.md +63 -55
  4. package/SECURITY.md +11 -11
  5. package/dist/allowlist.d.ts +3 -0
  6. package/dist/allowlist.js +9 -0
  7. package/dist/announcements.d.ts +4 -4
  8. package/dist/announcements.js +66 -34
  9. package/dist/attachments.d.ts +43 -0
  10. package/dist/attachments.js +340 -0
  11. package/dist/blossom.d.ts +2 -2
  12. package/dist/blossom.js +120 -66
  13. package/dist/bot-handlers.d.ts +9 -18
  14. package/dist/bot-handlers.js +125 -66
  15. package/dist/bot.d.ts +17 -20
  16. package/dist/bot.js +150 -55
  17. package/dist/client.d.ts +43 -39
  18. package/dist/client.js +476 -290
  19. package/dist/command-discovery.d.ts +2 -2
  20. package/dist/command-discovery.js +16 -7
  21. package/dist/command-schema.d.ts +2 -2
  22. package/dist/command-schema.js +62 -31
  23. package/dist/commands.d.ts +7 -6
  24. package/dist/commands.js +116 -51
  25. package/dist/defaults.js +13 -6
  26. package/dist/errors.d.ts +12 -12
  27. package/dist/errors.js +55 -18
  28. package/dist/inbox.d.ts +9 -7
  29. package/dist/inbox.js +107 -62
  30. package/dist/index.d.ts +25 -24
  31. package/dist/index.js +11 -11
  32. package/dist/key-sync.d.ts +4 -4
  33. package/dist/key-sync.js +88 -50
  34. package/dist/keys.d.ts +7 -6
  35. package/dist/keys.js +187 -93
  36. package/dist/message-storage-sqlite.d.ts +1 -1
  37. package/dist/message-storage-sqlite.js +32 -27
  38. package/dist/message-storage.d.ts +2 -2
  39. package/dist/messaging-metadata.d.ts +4 -4
  40. package/dist/messaging-metadata.js +73 -46
  41. package/dist/metadata.d.ts +3 -3
  42. package/dist/metadata.js +29 -15
  43. package/dist/modes.d.ts +7 -7
  44. package/dist/modes.js +53 -24
  45. package/dist/nip4e-compat.d.ts +2 -2
  46. package/dist/nip4e-compat.js +2 -2
  47. package/dist/nipcd.d.ts +14 -14
  48. package/dist/nipcd.js +225 -126
  49. package/dist/protocol.d.ts +7 -6
  50. package/dist/protocol.js +101 -54
  51. package/dist/public-inbox.d.ts +17 -15
  52. package/dist/public-inbox.js +129 -138
  53. package/dist/public-thread.d.ts +7 -4
  54. package/dist/public-thread.js +205 -88
  55. package/dist/relay-pool.d.ts +5 -5
  56. package/dist/relay-pool.js +172 -67
  57. package/dist/relay-roles.js +22 -13
  58. package/dist/relay.d.ts +11 -11
  59. package/dist/relay.js +194 -100
  60. package/dist/request-timing.d.ts +2 -2
  61. package/dist/request-timing.js +19 -7
  62. package/dist/session.js +7 -5
  63. package/dist/signer.d.ts +1 -1
  64. package/dist/signers/bunker-relays.d.ts +2 -2
  65. package/dist/signers/bunker-relays.js +16 -13
  66. package/dist/signers/bunker.d.ts +2 -2
  67. package/dist/signers/bunker.js +57 -37
  68. package/dist/signers/nsec.d.ts +2 -2
  69. package/dist/signers/nsec.js +8 -8
  70. package/dist/signers.d.ts +8 -8
  71. package/dist/signers.js +25 -18
  72. package/dist/storage-sqlite.d.ts +3 -1
  73. package/dist/storage-sqlite.js +110 -58
  74. package/dist/storage.d.ts +10 -6
  75. package/dist/store.d.ts +12 -8
  76. package/dist/store.js +156 -78
  77. package/docs/ACCESS.md +14 -25
  78. package/docs/API.md +125 -79
  79. package/docs/KEYS.md +3 -3
  80. package/docs/NIP-CD.md +29 -19
  81. package/docs/PUBLIC.md +33 -23
  82. package/docs/RECOVERY.md +7 -5
  83. package/docs/RELAYS.md +6 -6
  84. package/docs/SESSIONS.md +25 -21
  85. package/docs/SIGNERS.md +5 -3
  86. package/docs/STORAGE.md +15 -15
  87. package/docs/TUTORIAL.md +42 -39
  88. package/package.json +1 -37
  89. package/dist/inbound-policy.d.ts +0 -4
  90. package/dist/inbound-policy.js +0 -9
package/dist/nipcd.js CHANGED
@@ -1,115 +1,155 @@
1
- import { verifyEvent } from 'nostr-tools';
2
- import { decode } from 'nostr-tools/nip19';
3
- import { hexKey, validTimestamp } from './protocol.js';
1
+ import { verifyEvent } from "nostr-tools";
2
+ import { decode } from "nostr-tools/nip19";
3
+ import { hexKey, validTimestamp } from "./protocol.js";
4
4
  export const COMMAND_DEFINITION_KIND = 31992;
5
- const types = new Set(['pubkey', 'event', 'address', 'relay', 'number', 'bool', 'enum', 'word', 'text']);
5
+ const types = new Set([
6
+ "pubkey",
7
+ "event",
8
+ "address",
9
+ "relay",
10
+ "number",
11
+ "bool",
12
+ "enum",
13
+ "word",
14
+ "text",
15
+ ]);
6
16
  export function commandRelayURL(value) {
7
17
  try {
8
18
  const url = new URL(value);
9
- if (!['ws:', 'wss:'].includes(url.protocol) || !url.hostname || url.username || url.password || url.hash) {
19
+ if (!["ws:", "wss:"].includes(url.protocol) ||
20
+ !url.hostname ||
21
+ url.username ||
22
+ url.password ||
23
+ url.hash) {
10
24
  throw new Error();
11
25
  }
12
26
  return url.toString();
13
27
  }
14
28
  catch {
15
- throw new TypeError('Invalid command relay URL');
29
+ throw new TypeError("Invalid command relay URL");
16
30
  }
17
31
  }
18
32
  export function commandAddress(executor, id) {
19
- if (!hexKey(executor) || typeof id !== 'string') {
20
- throw new TypeError('Invalid command address');
33
+ if (!hexKey(executor) || typeof id !== "string") {
34
+ throw new TypeError("Invalid command address");
21
35
  }
22
36
  return `${COMMAND_DEFINITION_KIND}:${executor}:${id}`;
23
37
  }
24
38
  function scope(value) {
25
- const colon = value.indexOf(':'), type = value.slice(0, colon), rest = value.slice(colon + 1);
39
+ const colon = value.indexOf(":"), type = value.slice(0, colon), rest = value.slice(colon + 1);
26
40
  if (colon < 1 || !rest) {
27
- throw new TypeError('Invalid command scope');
41
+ throw new TypeError("Invalid command scope");
28
42
  }
29
- if (type === 'kind' && /^[0-9]+$/.test(rest) && Number.isSafeInteger(+rest) && +rest <= 65535) {
43
+ if (type === "kind" &&
44
+ /^[0-9]+$/.test(rest) &&
45
+ Number.isSafeInteger(+rest) &&
46
+ +rest <= 65535) {
30
47
  return {
31
- group: type, matches: event => event.kind === +rest
48
+ group: type,
49
+ matches: (event) => event.kind === +rest,
32
50
  };
33
51
  }
34
- if (type === 'author' && hexKey(rest)) {
52
+ if (type === "author" && hexKey(rest)) {
35
53
  return {
36
- group: type, matches: event => event.pubkey === rest
54
+ group: type,
55
+ matches: (event) => event.pubkey === rest,
37
56
  };
38
57
  }
39
- if (type === 'relay') {
58
+ if (type === "relay") {
40
59
  const expected = commandRelayURL(rest);
41
60
  return {
42
- group: type, matches: (_event, context) => {
61
+ group: type,
62
+ matches: (_event, context) => {
43
63
  try {
44
- return context.relay !== undefined && commandRelayURL(context.relay) === expected;
64
+ return (context.relay !== undefined &&
65
+ commandRelayURL(context.relay) === expected);
45
66
  }
46
67
  catch {
47
68
  return false;
48
69
  }
49
- }
70
+ },
50
71
  };
51
72
  }
52
- if (type === 'tag') {
53
- const split = rest.indexOf(':'), name = split === -1 ? rest : rest.slice(0, split), expected = split === -1 ? undefined : rest.slice(split + 1);
73
+ if (type === "tag") {
74
+ const split = rest.indexOf(":"), name = split === -1 ? rest : rest.slice(0, split), expected = split === -1 ? undefined : rest.slice(split + 1);
54
75
  if (!name) {
55
- throw new TypeError('Invalid tag scope');
76
+ throw new TypeError("Invalid tag scope");
56
77
  }
57
78
  return {
58
- group: `tag:${name}`, matches: event => event.tags.some(tag => tag[0] === name && (expected === undefined ? typeof tag[1] === 'string' && tag[1].length > 0 : tag[1] === expected))
79
+ group: `tag:${name}`,
80
+ matches: (event) => event.tags.some((tag) => tag[0] === name &&
81
+ (expected === undefined
82
+ ? typeof tag[1] === "string" && tag[1].length > 0
83
+ : tag[1] === expected)),
59
84
  };
60
85
  }
61
- throw new TypeError('Unsupported command scope'); // Unknown constraints never become unrestricted.
86
+ throw new TypeError("Unsupported command scope"); // Unknown constraints never become unrestricted.
62
87
  }
63
88
  export function validateCommandDefinition(input) {
64
- if (typeof input.id !== 'string') {
65
- throw new TypeError('An explicit stable command id (d value) is required');
89
+ if (typeof input.id !== "string") {
90
+ throw new TypeError("An explicit stable command id (d value) is required");
66
91
  }
67
- if (typeof input.command !== 'string' || !input.command || input.command.startsWith('/') || /[\s@]/u.test(input.command)) {
68
- throw new TypeError('Invalid command trigger');
92
+ if (typeof input.command !== "string" ||
93
+ !input.command ||
94
+ input.command.startsWith("/") ||
95
+ /[\s@]/u.test(input.command)) {
96
+ throw new TypeError("Invalid command trigger");
69
97
  }
70
- if (typeof input.title !== 'string' || !input.title || typeof input.description !== 'string' || !input.description) {
71
- throw new TypeError('Command title and description are required');
98
+ if (typeof input.title !== "string" ||
99
+ !input.title ||
100
+ typeof input.description !== "string" ||
101
+ !input.description) {
102
+ throw new TypeError("Command title and description are required");
72
103
  }
73
104
  const args = input.args ?? [];
74
105
  const scopes = input.scopes ?? [];
75
106
  if (!Array.isArray(args) || !Array.isArray(scopes)) {
76
- throw new TypeError('Invalid command arguments or scopes');
107
+ throw new TypeError("Invalid command arguments or scopes");
77
108
  }
78
109
  let optional = 0, text = 0;
79
110
  const names = new Set();
80
111
  for (let i = 0; i < args.length; i++) {
81
112
  const arg = args[i];
82
- if (!arg || typeof arg.name !== 'string' || !arg.name || names.has(arg.name) || !types.has(arg.type) || typeof arg.required !== 'boolean' || typeof arg.label !== 'string') {
83
- throw new TypeError('Invalid or duplicate command argument');
113
+ if (!arg ||
114
+ typeof arg.name !== "string" ||
115
+ !arg.name ||
116
+ names.has(arg.name) ||
117
+ !types.has(arg.type) ||
118
+ typeof arg.required !== "boolean" ||
119
+ typeof arg.label !== "string") {
120
+ throw new TypeError("Invalid or duplicate command argument");
84
121
  }
85
122
  names.add(arg.name);
86
123
  if (!arg.required) {
87
124
  optional++;
88
125
  }
89
126
  else if (optional > 0) {
90
- throw new TypeError('Required arguments must precede optional arguments');
127
+ throw new TypeError("Required arguments must precede optional arguments");
91
128
  }
92
- if (arg.type === 'text') {
129
+ if (arg.type === "text") {
93
130
  text++;
94
131
  if (i !== args.length - 1) {
95
- throw new TypeError('Text must be the final argument');
132
+ throw new TypeError("Text must be the final argument");
96
133
  }
97
134
  }
98
- if (arg.type === 'enum') {
99
- if (!Array.isArray(arg.choices) || !arg.choices.length || arg.choices.some((choice) => typeof choice !== 'string' || !choice) || new Set(arg.choices).size !== arg.choices.length) {
100
- throw new TypeError('Enum requires distinct nonempty choices');
135
+ if (arg.type === "enum") {
136
+ if (!Array.isArray(arg.choices) ||
137
+ !arg.choices.length ||
138
+ arg.choices.some((choice) => typeof choice !== "string" || !choice) ||
139
+ new Set(arg.choices).size !== arg.choices.length) {
140
+ throw new TypeError("Enum requires distinct nonempty choices");
101
141
  }
102
142
  }
103
- else if (arg.choices !== undefined && arg.choices.length) {
104
- throw new TypeError('Choices apply only to enum arguments');
143
+ else if (arg.choices?.length) {
144
+ throw new TypeError("Choices apply only to enum arguments");
105
145
  }
106
146
  }
107
147
  if (optional > 1 || text > 1) {
108
- throw new TypeError('At most one optional and one text argument are supported by NIP-CD');
148
+ throw new TypeError("At most one optional and one text argument are supported by NIP-CD");
109
149
  }
110
150
  for (const value of scopes) {
111
- if (typeof value !== 'string') {
112
- throw new TypeError('Invalid scope');
151
+ if (typeof value !== "string") {
152
+ throw new TypeError("Invalid scope");
113
153
  }
114
154
  scope(value);
115
155
  }
@@ -118,37 +158,49 @@ export function validateCommandDefinition(input) {
118
158
  command: input.command,
119
159
  title: input.title,
120
160
  description: input.description,
121
- args,
122
- scopes
161
+ args: args.map(({ choices, ...arg }) => choices === null || choices === undefined ? arg : { ...arg, choices }),
162
+ scopes,
123
163
  });
124
164
  }
125
165
  export function encodeCommandDefinition(input, createdAt = Math.floor(Date.now() / 1000)) {
126
166
  const definition = validateCommandDefinition(input);
127
167
  if (!validTimestamp(createdAt)) {
128
- throw new TypeError('Invalid command definition time');
168
+ throw new TypeError("Invalid command definition time");
129
169
  }
130
170
  return {
131
171
  kind: COMMAND_DEFINITION_KIND,
132
172
  created_at: createdAt,
133
- content: '',
173
+ content: "",
134
174
  tags: [
135
- ['d', definition.id], ['command', definition.command], ['title', definition.title], ['description', definition.description],
136
- ...(definition.args ?? []).map(arg => ['arg', arg.name, arg.type, arg.required ? 'required' : 'optional', arg.label, ...(arg.choices ?? [])]),
137
- ...(definition.scopes ?? []).map(value => ['s', value]),
138
- ]
175
+ ["d", definition.id],
176
+ ["command", definition.command],
177
+ ["title", definition.title],
178
+ ["description", definition.description],
179
+ ...(definition.args ?? []).map((arg) => [
180
+ "arg",
181
+ arg.name,
182
+ arg.type,
183
+ arg.required ? "required" : "optional",
184
+ arg.label,
185
+ ...(arg.choices ?? []),
186
+ ]),
187
+ ...(definition.scopes ?? []).map((value) => ["s", value]),
188
+ ],
139
189
  };
140
190
  }
141
191
  function signed(input) {
142
192
  try {
143
193
  const event = JSON.parse(JSON.stringify(input));
144
- return validTimestamp(event.created_at) && verifyEvent(event) ? event : undefined;
194
+ return validTimestamp(event.created_at) && verifyEvent(event)
195
+ ? event
196
+ : undefined;
145
197
  }
146
198
  catch {
147
199
  return;
148
200
  }
149
201
  }
150
202
  function identifier(event) {
151
- return event.tags.find(tag => tag[0] === 'd')?.[1] ?? '';
203
+ return event.tags.find((tag) => tag[0] === "d")?.[1] ?? "";
152
204
  }
153
205
  export function decodeCommandDefinition(input) {
154
206
  const event = signed(input);
@@ -157,34 +209,40 @@ export function decodeCommandDefinition(input) {
157
209
  }
158
210
  try {
159
211
  const one = (name) => {
160
- const tags = event.tags.filter(tag => tag[0] === name);
212
+ const tags = event.tags.filter((tag) => tag[0] === name);
161
213
  if (tags.length !== 1 || tags[0].length !== 2) {
162
- throw new TypeError('Missing or ambiguous command field');
214
+ throw new TypeError("Missing or ambiguous command field");
163
215
  }
164
216
  return tags[0][1];
165
217
  };
166
218
  const definition = validateCommandDefinition({
167
- id: one('d'),
168
- command: one('command'),
169
- title: one('title'),
170
- description: one('description'),
171
- args: event.tags.filter(tag => tag[0] === 'arg').map(tag => {
172
- if (tag.length < 5 || !['required', 'optional'].includes(tag[3])) {
173
- throw new TypeError('Invalid arg tag');
219
+ id: one("d"),
220
+ command: one("command"),
221
+ title: one("title"),
222
+ description: one("description"),
223
+ args: event.tags
224
+ .filter((tag) => tag[0] === "arg")
225
+ .map((tag) => {
226
+ if (tag.length < 5 || !["required", "optional"].includes(tag[3])) {
227
+ throw new TypeError("Invalid arg tag");
174
228
  }
175
229
  return {
176
230
  name: tag[1],
177
231
  type: tag[2],
178
- required: tag[3] === 'required',
232
+ required: tag[3] === "required",
179
233
  label: tag[4],
180
- ...(tag.length > 5 ? {
181
- choices: tag.slice(5)
182
- } : {})
234
+ ...(tag.length > 5
235
+ ? {
236
+ choices: tag.slice(5),
237
+ }
238
+ : {}),
183
239
  };
184
240
  }),
185
- scopes: event.tags.filter(tag => tag[0] === 's').map(tag => {
241
+ scopes: event.tags
242
+ .filter((tag) => tag[0] === "s")
243
+ .map((tag) => {
186
244
  if (tag.length !== 2) {
187
- throw new TypeError('Invalid scope tag');
245
+ throw new TypeError("Invalid scope tag");
188
246
  }
189
247
  return tag[1];
190
248
  }),
@@ -193,7 +251,7 @@ export function decodeCommandDefinition(input) {
193
251
  address: commandAddress(event.pubkey, definition.id),
194
252
  executor: event.pubkey,
195
253
  definition,
196
- event
254
+ event,
197
255
  };
198
256
  }
199
257
  catch {
@@ -202,37 +260,54 @@ export function decodeCommandDefinition(input) {
202
260
  }
203
261
  export function encodeCommandRevocation(executor, id, createdAt = Math.floor(Date.now() / 1000)) {
204
262
  if (!validTimestamp(createdAt)) {
205
- throw new TypeError('Invalid command revocation time');
263
+ throw new TypeError("Invalid command revocation time");
206
264
  }
207
265
  return {
208
266
  kind: 5,
209
267
  created_at: createdAt,
210
- tags: [['a', commandAddress(executor, id)], ['k', String(COMMAND_DEFINITION_KIND)]],
211
- content: ''
268
+ tags: [
269
+ ["a", commandAddress(executor, id)],
270
+ ["k", String(COMMAND_DEFINITION_KIND)],
271
+ ],
272
+ content: "",
212
273
  };
213
274
  }
214
275
  /** Select newest signed coordinates first; deleted/malformed latest versions never reveal an older fallback. */
215
276
  export function selectCommandDefinitions(inputs, authors, ids) {
216
- if (!authors.length || !authors.every(hexKey) || (ids !== undefined && (!ids.length || !ids.every(id => typeof id === 'string')))) {
217
- throw new TypeError('Explicit command authors and nonempty ID filters are required');
218
- }
219
- const events = inputs.map(signed).filter((event) => !!event && authors.includes(event.pubkey));
277
+ if (!authors.length ||
278
+ !authors.every(hexKey) ||
279
+ (ids !== undefined &&
280
+ (!ids.length || !ids.every((id) => typeof id === "string")))) {
281
+ throw new TypeError("Explicit command authors and nonempty ID filters are required");
282
+ }
283
+ const events = inputs
284
+ .map(signed)
285
+ .filter((event) => !!event && authors.includes(event.pubkey));
220
286
  const latest = new Map();
221
287
  for (const event of events) {
222
- if (event.kind !== COMMAND_DEFINITION_KIND || (ids && !ids.includes(identifier(event)))) {
288
+ if (event.kind !== COMMAND_DEFINITION_KIND ||
289
+ (ids && !ids.includes(identifier(event)))) {
223
290
  continue;
224
291
  }
225
292
  const address = commandAddress(event.pubkey, identifier(event)), previous = latest.get(address);
226
- if (!previous || event.created_at > previous.created_at || (event.created_at === previous.created_at && event.id < previous.id)) {
293
+ if (!previous ||
294
+ event.created_at > previous.created_at ||
295
+ (event.created_at === previous.created_at && event.id < previous.id)) {
227
296
  latest.set(address, event);
228
297
  }
229
298
  }
230
299
  const commands = [], retired = [];
231
300
  for (const [address, event] of latest) {
232
- const deleted = events.some(deletion => deletion.kind === 5 && deletion.pubkey === event.pubkey && deletion.tags.some(tag => (tag[0] === 'e' && tag[1] === event.id) || (tag[0] === 'a' && tag[1] === address && deletion.created_at >= event.created_at)));
301
+ const deleted = events.some((deletion) => deletion.kind === 5 &&
302
+ deletion.pubkey === event.pubkey &&
303
+ deletion.tags.some((tag) => (tag[0] === "e" && tag[1] === event.id) ||
304
+ (tag[0] === "a" &&
305
+ tag[1] === address &&
306
+ deletion.created_at >= event.created_at)));
233
307
  if (deleted) {
234
308
  retired.push({
235
- address, reason: 'deleted'
309
+ address,
310
+ reason: "deleted",
236
311
  });
237
312
  continue;
238
313
  }
@@ -242,20 +317,25 @@ export function selectCommandDefinitions(inputs, authors, ids) {
242
317
  }
243
318
  else {
244
319
  retired.push({
245
- address, reason: 'invalid-definition'
320
+ address,
321
+ reason: "invalid-definition",
246
322
  });
247
323
  }
248
324
  }
249
325
  for (const deletion of events) {
250
326
  if (deletion.kind === 5) {
251
327
  for (const tag of deletion.tags) {
252
- if (tag[0] !== 'a' || !tag[1]?.startsWith(`${COMMAND_DEFINITION_KIND}:${deletion.pubkey}:`)) {
328
+ if (tag[0] !== "a" ||
329
+ !tag[1]?.startsWith(`${COMMAND_DEFINITION_KIND}:${deletion.pubkey}:`)) {
253
330
  continue;
254
331
  }
255
332
  const address = tag[1], id = address.slice(`${COMMAND_DEFINITION_KIND}:${deletion.pubkey}:`.length);
256
- if (!latest.has(address) && (!ids || ids.includes(id)) && !retired.some(item => item.address === address)) {
333
+ if (!latest.has(address) &&
334
+ (!ids || ids.includes(id)) &&
335
+ !retired.some((item) => item.address === address)) {
257
336
  retired.push({
258
- address, reason: 'deleted'
337
+ address,
338
+ reason: "deleted",
259
339
  });
260
340
  }
261
341
  }
@@ -264,40 +344,43 @@ export function selectCommandDefinitions(inputs, authors, ids) {
264
344
  return {
265
345
  commands: commands.sort((a, b) => a.address.localeCompare(b.address)),
266
346
  retired,
267
- coverage: 'relay-snapshot',
268
- complete: false
347
+ coverage: "relay-snapshot",
348
+ complete: false,
269
349
  };
270
350
  }
271
351
  export function matchesCommandScopes(scopes, event, context = {}) {
272
352
  const groups = new Map();
273
353
  for (const value of scopes) {
274
354
  const condition = scope(value);
275
- groups.set(condition.group, [...(groups.get(condition.group) ?? []), condition]);
355
+ groups.set(condition.group, [
356
+ ...(groups.get(condition.group) ?? []),
357
+ condition,
358
+ ]);
276
359
  }
277
- return [...groups.values()].every(alternatives => alternatives.some(condition => condition.matches(event, context)));
360
+ return [...groups.values()].every((alternatives) => alternatives.some((condition) => condition.matches(event, context)));
278
361
  }
279
- const unprefix = (value) => value.replace(/^nostr:/i, '');
362
+ const unprefix = (value) => value.replace(/^nostr:/i, "");
280
363
  function argumentValue(arg, raw) {
281
364
  const value = unprefix(raw);
282
- if (arg.type === 'word') {
365
+ if (arg.type === "word") {
283
366
  return value;
284
367
  }
285
- if (arg.type === 'number') {
368
+ if (arg.type === "number") {
286
369
  if (!/^[0-9]+$/.test(value)) {
287
370
  throw new Error();
288
371
  }
289
372
  return BigInt(value);
290
373
  }
291
- if (arg.type === 'bool') {
292
- if (['true', 'yes', '1', 't', 'y'].includes(value)) {
374
+ if (arg.type === "bool") {
375
+ if (["true", "yes", "1", "t", "y"].includes(value)) {
293
376
  return true;
294
377
  }
295
- if (['false', 'no', '0', 'f', 'n'].includes(value)) {
378
+ if (["false", "no", "0", "f", "n"].includes(value)) {
296
379
  return false;
297
380
  }
298
381
  throw new Error();
299
382
  }
300
- if (arg.type === 'enum') {
383
+ if (arg.type === "enum") {
301
384
  if (arg.choices?.includes(raw)) {
302
385
  return raw;
303
386
  }
@@ -306,32 +389,38 @@ function argumentValue(arg, raw) {
306
389
  }
307
390
  return value;
308
391
  }
309
- if (arg.type === 'relay') {
392
+ if (arg.type === "relay") {
310
393
  commandRelayURL(value);
311
394
  return value;
312
395
  }
313
- if ((arg.type === 'pubkey' || arg.type === 'event') && /^[0-9a-fA-F]{64}$/.test(value)) {
396
+ if ((arg.type === "pubkey" || arg.type === "event") &&
397
+ /^[0-9a-fA-F]{64}$/.test(value)) {
314
398
  return value.toLowerCase();
315
399
  }
316
400
  const decoded = decode(value);
317
- if (arg.type === 'pubkey' && decoded.type === 'npub') {
401
+ if (arg.type === "pubkey" && decoded.type === "npub") {
318
402
  return decoded.data;
319
403
  }
320
- if (arg.type === 'pubkey' && decoded.type === 'nprofile') {
404
+ if (arg.type === "pubkey" && decoded.type === "nprofile") {
321
405
  return decoded.data.pubkey;
322
406
  }
323
- if (arg.type === 'event' && decoded.type === 'note') {
407
+ if (arg.type === "event" && decoded.type === "note") {
324
408
  return decoded.data;
325
409
  }
326
- if (arg.type === 'event' && decoded.type === 'nevent') {
410
+ if (arg.type === "event" && decoded.type === "nevent") {
327
411
  return decoded.data.id;
328
412
  }
329
- if (arg.type === 'address' && decoded.type === 'naddr' && Number.isSafeInteger(decoded.data.kind) && decoded.data.kind >= 0 && decoded.data.kind <= 65535 && hexKey(decoded.data.pubkey)) {
413
+ if (arg.type === "address" &&
414
+ decoded.type === "naddr" &&
415
+ Number.isSafeInteger(decoded.data.kind) &&
416
+ decoded.data.kind >= 0 &&
417
+ decoded.data.kind <= 65535 &&
418
+ hexKey(decoded.data.pubkey)) {
330
419
  return {
331
420
  kind: decoded.data.kind,
332
421
  pubkey: decoded.data.pubkey,
333
422
  identifier: decoded.data.identifier,
334
- relays: decoded.data.relays ?? []
423
+ relays: decoded.data.relays ?? [],
335
424
  };
336
425
  }
337
426
  throw new Error();
@@ -341,77 +430,83 @@ export function parseCommandHead(content, command, executor) {
341
430
  const head = /^\/([^\s@]+)/u.exec(content);
342
431
  if (!head || head[1] !== command) {
343
432
  return {
344
- status: 'not-matched'
433
+ status: "not-matched",
345
434
  };
346
435
  }
347
436
  let cursor = head[0].length, qualifier;
348
- if (content[cursor] === '@') {
437
+ if (content[cursor] === "@") {
349
438
  const token = /^(?:nostr:)?npub1[qpzry9x8gf2tvdw0s3jn54khce6mua7l]+/i.exec(content.slice(cursor + 1));
350
439
  if (!token) {
351
440
  return {
352
- status: 'invalid', reason: 'Invalid command qualifier'
441
+ status: "invalid",
442
+ reason: "Invalid command qualifier",
353
443
  };
354
444
  }
355
445
  try {
356
446
  const decoded = decode(unprefix(token[0]));
357
- if (decoded.type !== 'npub') {
447
+ if (decoded.type !== "npub") {
358
448
  throw new Error();
359
449
  }
360
450
  qualifier = decoded.data;
361
451
  }
362
452
  catch {
363
453
  return {
364
- status: 'invalid', reason: 'Invalid command qualifier'
454
+ status: "invalid",
455
+ reason: "Invalid command qualifier",
365
456
  };
366
457
  }
367
458
  cursor += token[0].length + 1;
368
459
  if (cursor < content.length && !/\s/u.test(content[cursor])) {
369
460
  return {
370
- status: 'invalid', reason: 'Expected whitespace after qualifier'
461
+ status: "invalid",
462
+ reason: "Expected whitespace after qualifier",
371
463
  };
372
464
  }
373
465
  if (qualifier !== executor) {
374
466
  return {
375
- status: 'not-matched'
467
+ status: "not-matched",
376
468
  };
377
469
  }
378
470
  }
379
471
  return {
380
- status: 'matched',
472
+ status: "matched",
381
473
  cursor,
382
- ...(qualifier ? {
383
- qualifier
384
- } : {})
474
+ ...(qualifier
475
+ ? {
476
+ qualifier,
477
+ }
478
+ : {}),
385
479
  };
386
480
  }
387
481
  export function parseCommand(input, event, context) {
388
482
  const definition = validateCommandDefinition(input), content = event.content;
389
483
  const head = parseCommandHead(content, definition.command, context.executor);
390
- if (head.status !== 'matched') {
484
+ if (head.status !== "matched") {
391
485
  return head;
392
486
  }
393
487
  let { cursor } = head;
394
488
  const { qualifier } = head;
395
489
  if (!hexKey(context.executor)) {
396
- throw new TypeError('Executor pubkey is required');
490
+ throw new TypeError("Executor pubkey is required");
397
491
  }
398
492
  if (!matchesCommandScopes(definition.scopes ?? [], event, context)) {
399
493
  return {
400
- status: 'not-matched'
494
+ status: "not-matched",
401
495
  };
402
496
  }
403
497
  const args = Object.create(null), rawArgs = Object.create(null);
404
498
  for (const arg of definition.args ?? []) {
405
- if (arg.type === 'text') {
499
+ if (arg.type === "text") {
406
500
  // Remove one separator only; preserve every remaining character, including leading whitespace.
407
501
  if (cursor < content.length && /\s/u.test(content[cursor])) {
408
- cursor += content.slice(cursor, cursor + 2) === '\r\n' ? 2 : 1;
502
+ cursor += content.slice(cursor, cursor + 2) === "\r\n" ? 2 : 1;
409
503
  }
410
504
  const remainder = content.slice(cursor);
411
505
  cursor = content.length;
412
506
  if (!remainder && arg.required) {
413
507
  return {
414
- status: 'invalid', reason: `Missing argument: ${arg.name}`
508
+ status: "invalid",
509
+ reason: `Missing argument: ${arg.name}`,
415
510
  };
416
511
  }
417
512
  args[arg.name] = rawArgs[arg.name] = remainder || undefined;
@@ -423,7 +518,8 @@ export function parseCommand(input, event, context) {
423
518
  if (!token) {
424
519
  if (arg.required) {
425
520
  return {
426
- status: 'invalid', reason: `Missing argument: ${arg.name}`
521
+ status: "invalid",
522
+ reason: `Missing argument: ${arg.name}`,
427
523
  };
428
524
  }
429
525
  args[arg.name] = rawArgs[arg.name] = undefined;
@@ -436,21 +532,24 @@ export function parseCommand(input, event, context) {
436
532
  }
437
533
  catch {
438
534
  return {
439
- status: 'invalid', reason: `Invalid ${arg.type} argument: ${arg.name}`
535
+ status: "invalid",
536
+ reason: `Invalid ${arg.type} argument: ${arg.name}`,
440
537
  };
441
538
  }
442
539
  }
443
540
  if (content.slice(cursor).trim()) {
444
541
  return {
445
- status: 'invalid', reason: 'Unexpected extra arguments'
542
+ status: "invalid",
543
+ reason: "Unexpected extra arguments",
446
544
  };
447
545
  }
448
546
  return {
449
- status: 'matched', invocation: {
547
+ status: "matched",
548
+ invocation: {
450
549
  definition,
451
550
  qualifier,
452
551
  args,
453
- rawArgs
454
- }
552
+ rawArgs,
553
+ },
455
554
  };
456
555
  }