@impro.social/impro-plugin 0.0.21 → 0.0.22

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 (3) hide show
  1. package/main.d.ts +1420 -0
  2. package/main.js +319 -76
  3. package/package.json +10 -4
package/main.js CHANGED
@@ -11,8 +11,32 @@
11
11
  * A raw repo record: `{ uri, cid, value }`.
12
12
  * @typedef {Record<string, unknown>} FeedItem
13
13
  * A `app.bsky.feed.defs#feedViewPost` (post + reply/repost context).
14
- * @typedef {Record<string, unknown>} RichTextToken
14
+ * @typedef {{ $type: string } & Record<string, unknown>} RichTextFacetFeature
15
+ * One feature of a facet; fields beyond `$type` vary by service.
16
+ * @typedef {{ index: { byteStart: number, byteEnd: number }, features?: RichTextFacetFeature[] }} RichTextFacet
17
+ * An `app.bsky.richtext.facet` — a byte range plus the features applying to it.
18
+ * @typedef {{ type: "text", value: string }} RichTextTextToken
19
+ * A run of plain text.
20
+ * @typedef {{ type: "facet", facet: RichTextFacet, text: string }} RichTextFacetToken
21
+ * The text covered by one facet; the host restores the original facet payload.
22
+ * @typedef {{ type: "inline" | "block", node: VirtualEl | Record<string, unknown>, pluginId?: string }} RichTextNodeToken
23
+ * Custom content the plugin renders itself — `block` on its own line, `inline` in the text flow.
24
+ * @typedef {RichTextTextToken | RichTextFacetToken | RichTextNodeToken} RichTextToken
15
25
  * One token in a rich-text stream — `text`, `facet`, `inline`, or `block`.
26
+ * @typedef {Record<string, string> | Headers | Map<string, string> | Iterable<[string, string], void, undefined>} PluginFetchHeaders
27
+ * Any header collection {@link fetch} accepts — read structurally, not by class.
28
+ * @typedef {{ method?: string, headers?: PluginFetchHeaders, body?: string }} PluginFetchInit
29
+ * Options for {@link fetch} — a subset of `RequestInit` the host proxy supports.
30
+ * @typedef {{ feedGenerator: Record<string, unknown> | null, feedContext: string | null, feedProxyUrl: string | null }} PostContextMenuMeta
31
+ * Where a post was seen, passed to `post-context-menu` listeners.
32
+ * @typedef {{ kind: "post" | "reply" | "quote", replyTo: PostView | null, replyRoot: PostView | null, quotedPost: PostView | null }} PostComposerContext
33
+ * What the composer is being opened for, passed to `post-composer-open` listeners.
34
+ * @typedef {{
35
+ * "post-context-menu": (menu: Menu, post: PostView, meta?: PostContextMenuMeta) => void,
36
+ * "profile-context-menu": (menu: Menu, profile: ProfileView) => void,
37
+ * "post-composer-open": (composer: Composer, context: PostComposerContext) => void,
38
+ * }} PluginEventMap
39
+ * The events {@link Plugin.on} accepts, and the listener each one takes.
16
40
  * @typedef {VirtualEl | null | undefined} RenderResult
17
41
  * What a render callback may return: a tree to render, or nothing.
18
42
  */
@@ -26,21 +50,45 @@ export class SimpleUUID {
26
50
 
27
51
  const uuid = new SimpleUUID();
28
52
 
53
+ /**
54
+ * Posts a message to the host. The only outbound channel, so every message
55
+ * is checked against {@link WorkerMessage}.
56
+ * @param {WorkerMessage} message
57
+ * @returns {void}
58
+ */
59
+ function post(message) {
60
+ self.postMessage(message);
61
+ }
62
+
63
+ /** @type {Map<number, (...args: any[]) => unknown>} */
29
64
  const callHandlers = new Map();
30
65
 
66
+ /** @type {Map<number, { resolve: (value: unknown) => void, reject: (reason: unknown) => void }>} */
31
67
  const pendingHostCalls = new Map();
32
68
 
69
+ /**
70
+ * @param {string} method
71
+ * @param {...Cloneable} args
72
+ * @returns {Promise<unknown>}
73
+ */
33
74
  function hostCall(method, ...args) {
34
75
  const hostCallId = uuid.create();
35
76
  return new Promise((resolve, reject) => {
36
77
  pendingHostCalls.set(hostCallId, { resolve, reject });
37
- self.postMessage({ type: "hostCall", method, hostCallId, args });
78
+ post({ type: "hostCall", method, hostCallId, args });
38
79
  });
39
80
  }
40
81
 
82
+ /** @type {Map<string, Set<(...args: any[]) => unknown>>} */
41
83
  const eventListeners = new Map();
42
84
  const registeredEvents = new Set();
43
85
 
86
+ /**
87
+ * @param {Iterable<(...args: any[]) => unknown>} listeners
88
+ * @param {string} event
89
+ * @param {unknown[]} args
90
+ * @returns {Promise<void>}
91
+ */
44
92
  async function invokeListeners(listeners, event, args) {
45
93
  for (const listener of listeners) {
46
94
  try {
@@ -51,6 +99,11 @@ async function invokeListeners(listeners, event, args) {
51
99
  }
52
100
  }
53
101
 
102
+ /**
103
+ * @param {string} event
104
+ * @param {unknown[]} args
105
+ * @returns {Promise<unknown>}
106
+ */
54
107
  async function dispatchEvent(event, args) {
55
108
  const listeners = eventListeners.get(event) ?? new Set();
56
109
  switch (event) {
@@ -71,6 +124,11 @@ async function dispatchEvent(event, args) {
71
124
  }
72
125
  }
73
126
 
127
+ /**
128
+ * @param {string} event
129
+ * @param {(...args: any[]) => unknown} listener
130
+ * @returns {void}
131
+ */
74
132
  function addEventListener(event, listener) {
75
133
  let listeners = eventListeners.get(event);
76
134
  if (!listeners) {
@@ -83,7 +141,7 @@ function addEventListener(event, listener) {
83
141
  registeredEvents.add(event);
84
142
  const handlerId = uuid.create();
85
143
  callHandlers.set(handlerId, (...args) => dispatchEvent(event, args));
86
- self.postMessage({
144
+ post({
87
145
  type: "register",
88
146
  target: "eventListener",
89
147
  event,
@@ -173,6 +231,7 @@ export class Menu {
173
231
  * all listeners have run. operations from multiple plugins are applied in order.
174
232
  */
175
233
  export class Composer {
234
+ /** @type {{ op: string, text: string }[]} */
176
235
  #ops = [];
177
236
  /** @type {number | null} */
178
237
  #cursor = null;
@@ -229,7 +288,7 @@ export class PluginData {
229
288
  * @returns {Promise<PostView>}
230
289
  */
231
290
  getPost(uri) {
232
- return hostCall("getPost", { uri });
291
+ return /** @type {Promise<PostView>} */ (hostCall("getPost", { uri }));
233
292
  }
234
293
  /**
235
294
  * Fetch the basic profile view for a DID.
@@ -237,7 +296,9 @@ export class PluginData {
237
296
  * @returns {Promise<ProfileView>}
238
297
  */
239
298
  getProfile(did) {
240
- return hostCall("getProfile", { did });
299
+ return /** @type {Promise<ProfileView>} */ (
300
+ hostCall("getProfile", { did })
301
+ );
241
302
  }
242
303
  /**
243
304
  * Like {@link PluginData.getProfile}, but includes viewer relationship
@@ -248,7 +309,9 @@ export class PluginData {
248
309
  * @returns {Promise<DetailedProfileView>}
249
310
  */
250
311
  getDetailedProfile(did) {
251
- return hostCall("getDetailedProfile", { did });
312
+ return /** @type {Promise<DetailedProfileView>} */ (
313
+ hostCall("getDetailedProfile", { did })
314
+ );
252
315
  }
253
316
  /**
254
317
  * The full known-followers list for `did`. The summary on
@@ -258,7 +321,9 @@ export class PluginData {
258
321
  * @returns {Promise<KnownFollowersResponse>}
259
322
  */
260
323
  getKnownFollowers(did) {
261
- return hostCall("getKnownFollowers", { did });
324
+ return /** @type {Promise<KnownFollowersResponse>} */ (
325
+ hostCall("getKnownFollowers", { did })
326
+ );
262
327
  }
263
328
  /**
264
329
  * Fetch a raw repo record by `(repo, collection, rkey)`.
@@ -268,7 +333,9 @@ export class PluginData {
268
333
  * @returns {Promise<RepoRecord>}
269
334
  */
270
335
  getRecord(repo, collection, rkey) {
271
- return hostCall("getRecord", { repo, collection, rkey });
336
+ return /** @type {Promise<RepoRecord>} */ (
337
+ hostCall("getRecord", { repo, collection, rkey })
338
+ );
272
339
  }
273
340
  }
274
341
 
@@ -299,9 +366,11 @@ export class App {
299
366
  * - `"post-composer-open"` — `(composer: Composer, context: { kind, replyTo, replyRoot, quotedPost }) => void`,
300
367
  * called when the post composer opens; use `composer` to seed text.
301
368
  *
302
- * The `listener` signature varies per event (see above).
303
- * @param {string} event
304
- * @param {Function} listener
369
+ * The `listener` signature varies per event — see {@link PluginEventMap}.
370
+ * @template {keyof PluginEventMap} K
371
+ * @param {K} event
372
+ * @param {PluginEventMap[K]} listener
373
+ * @returns {void}
305
374
  */
306
375
  on(event, listener) {
307
376
  addEventListener(event, listener);
@@ -314,7 +383,9 @@ export class App {
314
383
  * @returns {Promise<void>}
315
384
  */
316
385
  refreshFeedFilters(feedURI = null) {
317
- return hostCall("refreshFeedFilters", feedURI);
386
+ return /** @type {Promise<void>} */ (
387
+ hostCall("refreshFeedFilters", feedURI)
388
+ );
318
389
  }
319
390
 
320
391
  /**
@@ -324,7 +395,9 @@ export class App {
324
395
  * @returns {Promise<void>}
325
396
  */
326
397
  muteActor(did) {
327
- return hostCall("muteActor", { did, mute: true });
398
+ return /** @type {Promise<void>} */ (
399
+ hostCall("muteActor", { did, mute: true })
400
+ );
328
401
  }
329
402
  /**
330
403
  * Unmute an actor. Requires the `"mute"` scope.
@@ -332,7 +405,9 @@ export class App {
332
405
  * @returns {Promise<void>}
333
406
  */
334
407
  unmuteActor(did) {
335
- return hostCall("muteActor", { did, mute: false });
408
+ return /** @type {Promise<void>} */ (
409
+ hostCall("muteActor", { did, mute: false })
410
+ );
336
411
  }
337
412
  /**
338
413
  * Block an actor on behalf of the signed-in user. Requires the `"block"`
@@ -341,7 +416,9 @@ export class App {
341
416
  * @returns {Promise<void>}
342
417
  */
343
418
  blockActor(did) {
344
- return hostCall("blockActor", { did, block: true });
419
+ return /** @type {Promise<void>} */ (
420
+ hostCall("blockActor", { did, block: true })
421
+ );
345
422
  }
346
423
  /**
347
424
  * Unblock an actor. Requires the `"block"` scope.
@@ -349,7 +426,9 @@ export class App {
349
426
  * @returns {Promise<void>}
350
427
  */
351
428
  unblockActor(did) {
352
- return hostCall("blockActor", { did, block: false });
429
+ return /** @type {Promise<void>} */ (
430
+ hostCall("blockActor", { did, block: false })
431
+ );
353
432
  }
354
433
  /**
355
434
  * Acts like the user clicking "Show less like this": sends the
@@ -361,7 +440,9 @@ export class App {
361
440
  * @returns {Promise<void>}
362
441
  */
363
442
  showLessLikeThis(postUri, feedUri) {
364
- return hostCall("showLessLikeThis", { postUri, feedUri });
443
+ return /** @type {Promise<void>} */ (
444
+ hostCall("showLessLikeThis", { postUri, feedUri })
445
+ );
365
446
  }
366
447
  /**
367
448
  * Sends the `requestMore` feedback signal to `feedUri` for `postUri`.
@@ -371,7 +452,9 @@ export class App {
371
452
  * @returns {Promise<void>}
372
453
  */
373
454
  showMoreLikeThis(postUri, feedUri) {
374
- return hostCall("showMoreLikeThis", { postUri, feedUri });
455
+ return /** @type {Promise<void>} */ (
456
+ hostCall("showMoreLikeThis", { postUri, feedUri })
457
+ );
375
458
  }
376
459
  }
377
460
 
@@ -382,31 +465,66 @@ export class App {
382
465
  * `[name, value]` iterable), and a string `body`. Resolves to a
383
466
  * {@link PluginResponse}.
384
467
  * @param {string} url
385
- * @param {{ method?: string, headers?: Record<string, string> | Headers | Map<string, string> | Iterable<[string, string], void, undefined>, body?: string }} [init]
468
+ * @param {PluginFetchInit} [init]
386
469
  * @returns {Promise<PluginResponse>}
387
470
  */
388
471
  export async function fetch(url, init = {}) {
389
- const result = await hostCall("fetch", {
390
- url,
391
- init: serializeFetchInit(init),
392
- });
472
+ const result = /** @type {SerializedFetchResponse} */ (
473
+ await hostCall("fetch", { url, init: serializeFetchInit(init) })
474
+ );
393
475
  return new PluginResponse(result);
394
476
  }
395
477
 
478
+ /**
479
+ * @param {unknown} value
480
+ * @returns {value is { forEach: (callback: (value: string, name: string) => void) => void }}
481
+ */
482
+ function hasForEach(value) {
483
+ return (
484
+ typeof value === "object" &&
485
+ value !== null &&
486
+ "forEach" in value &&
487
+ typeof value.forEach === "function"
488
+ );
489
+ }
490
+
491
+ /**
492
+ * @param {unknown} value
493
+ * @returns {value is Iterable<[string, string]>}
494
+ */
495
+ function isEntryIterable(value) {
496
+ return (
497
+ typeof value === "object" &&
498
+ value !== null &&
499
+ Symbol.iterator in value &&
500
+ typeof value[Symbol.iterator] === "function"
501
+ );
502
+ }
503
+
504
+ /**
505
+ * @param {PluginFetchInit} init
506
+ * @returns {SerializedFetchInit}
507
+ */
396
508
  function serializeFetchInit(init) {
509
+ /** @type {SerializedFetchInit} */
397
510
  const serialized = {};
398
511
  if (init.method != null) serialized.method = String(init.method);
399
512
  if (init.headers != null) {
513
+ /** @type {Record<string, string>} */
400
514
  const headers = {};
401
- if (typeof init.headers.forEach === "function") {
402
- // Headers, Map, and similar iterables expose forEach(value, name)
403
- init.headers.forEach((value, name) => {
515
+ // Probed structurally rather than by class, so any forEach-able or
516
+ // iterable header collection works. Iteration is tried first because
517
+ // Headers, Map, arrays and iterators all yield [name, value] pairs,
518
+ // whereas forEach passes (value, index) on an array or iterator.
519
+ const headersInit = init.headers;
520
+ if (isEntryIterable(headersInit)) {
521
+ for (const [name, value] of headersInit) headers[name] = value;
522
+ } else if (hasForEach(headersInit)) {
523
+ headersInit.forEach((value, name) => {
404
524
  headers[name] = value;
405
525
  });
406
- } else if (typeof init.headers[Symbol.iterator] === "function") {
407
- for (const [name, value] of init.headers) headers[name] = value;
408
526
  } else {
409
- Object.assign(headers, init.headers);
527
+ Object.assign(headers, headersInit);
410
528
  }
411
529
  serialized.headers = headers;
412
530
  }
@@ -421,7 +539,10 @@ function serializeFetchInit(init) {
421
539
  */
422
540
  export class PluginResponse {
423
541
  #body;
424
- /** @internal */
542
+ /**
543
+ * @internal
544
+ * @param {SerializedFetchResponse} response
545
+ */
425
546
  constructor({ status, ok, headers, body }) {
426
547
  /** @type {number} */
427
548
  this.status = status;
@@ -523,7 +644,7 @@ export class StyleSnippet {
523
644
  hostCall("applyStyleSnippet", {
524
645
  snippetId: this.#snippetId,
525
646
  cssText,
526
- }).then(resolve, reject);
647
+ }).then(() => resolve(), reject);
527
648
  });
528
649
  });
529
650
  }
@@ -547,8 +668,6 @@ let registered = false;
547
668
  * data. Call `MyPlugin.register()` at the top of your plugin's main.js to boot.
548
669
  */
549
670
  export class Plugin {
550
- /** @type {PluginSettingTab | null} */
551
- #settingTab = null;
552
671
  /** @internal */
553
672
  constructor() {
554
673
  /** @type {App} */
@@ -566,7 +685,7 @@ export class Plugin {
566
685
  addSidebarItem(icon, title, callback = () => {}) {
567
686
  const handlerId = uuid.create();
568
687
  callHandlers.set(handlerId, callback);
569
- self.postMessage({
688
+ post({
570
689
  type: "register",
571
690
  target: "sidebarItem",
572
691
  icon: icon instanceof VirtualEl ? icon._serialize() : icon,
@@ -586,7 +705,7 @@ export class Plugin {
586
705
 
587
706
  /**
588
707
  * Persists `data` as this plugin's account-synced JSON blob.
589
- * @param {unknown} data
708
+ * @param {Cloneable} data
590
709
  * @returns {Promise<void>}
591
710
  */
592
711
  async saveData(data) {
@@ -606,7 +725,7 @@ export class Plugin {
606
725
 
607
726
  /**
608
727
  * Device-local counterpart to {@link Plugin.saveData}.
609
- * @param {unknown} data
728
+ * @param {Cloneable} data
610
729
  * @returns {Promise<void>}
611
730
  */
612
731
  async saveLocalData(data) {
@@ -627,13 +746,12 @@ export class Plugin {
627
746
  tab.display();
628
747
  return tab.containerEl._serialize();
629
748
  });
630
- self.postMessage({
749
+ post({
631
750
  type: "register",
632
751
  target: "settingTab",
633
752
  name: tab.name ?? null,
634
753
  displayHandlerId,
635
754
  });
636
- this.#settingTab = tab;
637
755
  }
638
756
 
639
757
  /**
@@ -646,7 +764,7 @@ export class Plugin {
646
764
  addFeedFilter(callback = () => ({})) {
647
765
  const handlerId = uuid.create();
648
766
  callHandlers.set(handlerId, callback);
649
- self.postMessage({
767
+ post({
650
768
  type: "register",
651
769
  target: "feedFilter",
652
770
  handlerId,
@@ -661,6 +779,9 @@ export class Plugin {
661
779
  * {@link VirtualEl}), or `block` (a plugin-produced block VirtualEl). See
662
780
  * {@link FlattenedTokens} for pattern-matching across token boundaries.
663
781
  *
782
+ * A node token's `node` is a {@link VirtualEl} when this transform creates it,
783
+ * but arrives in serialized form when an earlier transform produced it.
784
+ *
664
785
  * `options.handlesFacetTypes` is an array of facet feature `$type` strings
665
786
  * this transform owns, so the host can suppress fallback rendering flash
666
787
  * while the transform runs.
@@ -677,7 +798,7 @@ export class Plugin {
677
798
  const value = await callback(tokens, context);
678
799
  results.push({ value: serializeTransformTokens(value) });
679
800
  } catch (error) {
680
- results.push({ error: error?.message ?? String(error) });
801
+ results.push({ error: getErrorMessage(error) });
681
802
  }
682
803
  }
683
804
  return results;
@@ -685,7 +806,7 @@ export class Plugin {
685
806
  const handlesFacetTypes = Array.isArray(options.handlesFacetTypes)
686
807
  ? options.handlesFacetTypes.filter((type) => typeof type === "string")
687
808
  : [];
688
- self.postMessage({
809
+ post({
689
810
  type: "register",
690
811
  target: "richTextTransform",
691
812
  handlerId,
@@ -722,7 +843,7 @@ export class Plugin {
722
843
  value: await getSlotContent(name, callback, context),
723
844
  });
724
845
  } catch (error) {
725
- results.push({ error: error?.message ?? String(error) });
846
+ results.push({ error: getErrorMessage(error) });
726
847
  }
727
848
  }
728
849
  return results;
@@ -730,7 +851,7 @@ export class Plugin {
730
851
  const cacheKey = Array.isArray(options.cacheKey)
731
852
  ? options.cacheKey.filter((field) => typeof field === "string")
732
853
  : null;
733
- self.postMessage({
854
+ post({
734
855
  type: "register",
735
856
  target: "slot",
736
857
  name,
@@ -759,7 +880,7 @@ export class Plugin {
759
880
  }
760
881
  return result._serialize();
761
882
  });
762
- self.postMessage({
883
+ post({
763
884
  type: "register",
764
885
  target: "page",
765
886
  id,
@@ -774,7 +895,7 @@ export class Plugin {
774
895
  * @returns {Promise<void>}
775
896
  */
776
897
  openPage(pageId) {
777
- return hostCall("openPage", { pageId });
898
+ return /** @type {Promise<void>} */ (hostCall("openPage", { pageId }));
778
899
  }
779
900
 
780
901
  /**
@@ -785,7 +906,9 @@ export class Plugin {
785
906
  * @returns {Promise<void>}
786
907
  */
787
908
  refreshPage(pageId, { reset = false } = {}) {
788
- return hostCall("refreshPage", { pageId, reset });
909
+ return /** @type {Promise<void>} */ (
910
+ hostCall("refreshPage", { pageId, reset })
911
+ );
789
912
  }
790
913
 
791
914
  /**
@@ -803,7 +926,9 @@ export class Plugin {
803
926
  * @returns {Promise<void>}
804
927
  */
805
928
  refreshSlot(name, options = {}) {
806
- return hostCall("refreshSlot", { name, keys: options.keys ?? null });
929
+ return /** @type {Promise<void>} */ (
930
+ hostCall("refreshSlot", { name, keys: options.keys ?? null })
931
+ );
807
932
  }
808
933
 
809
934
  /**
@@ -827,22 +952,35 @@ export class Plugin {
827
952
  if (registered) return;
828
953
  registered = true;
829
954
  const instance = new this();
830
- hostCall("getCurrentUser")
955
+ /** @type {Promise<ProfileView | null>} */ (hostCall("getCurrentUser"))
831
956
  .then((user) => {
832
957
  instance.app.currentUser = user;
833
958
  return instance.onload();
834
959
  })
835
960
  .then(
836
- () => self.postMessage({ type: "ready" }),
961
+ () => post({ type: "ready" }),
837
962
  (error) =>
838
- self.postMessage({
963
+ post({
839
964
  type: "ready",
840
- error: error?.message ?? String(error),
965
+ error: getErrorMessage(error),
841
966
  }),
842
967
  );
843
968
  }
844
969
  }
845
970
 
971
+ /**
972
+ * Extracts a message from a caught value, which need not be an Error.
973
+ * @param {unknown} error
974
+ * @returns {string}
975
+ */
976
+ function getErrorMessage(error) {
977
+ if (error instanceof Error) return error.message;
978
+ if (typeof error === "object" && error !== null && "message" in error) {
979
+ return String(error.message);
980
+ }
981
+ return String(error);
982
+ }
983
+
846
984
  /**
847
985
  * Names the type of an arbitrary value, for use in an error message.
848
986
  * @param {unknown} value
@@ -854,6 +992,12 @@ function describeValue(value) {
854
992
  return value.constructor?.name ?? "object";
855
993
  }
856
994
 
995
+ /**
996
+ * @param {string} name
997
+ * @param {(context: Record<string, string>) => RenderResult | Promise<RenderResult>} callback
998
+ * @param {Record<string, string>} context
999
+ * @returns {Promise<SerializedElement | null>}
1000
+ */
857
1001
  async function getSlotContent(name, callback, context) {
858
1002
  const result = /** @type {unknown} */ (await callback(context));
859
1003
  if (result == null) return null;
@@ -865,6 +1009,10 @@ async function getSlotContent(name, callback, context) {
865
1009
  return result._serialize();
866
1010
  }
867
1011
 
1012
+ /**
1013
+ * @param {RichTextToken[]} tokens
1014
+ * @returns {SerializedRichTextToken[]}
1015
+ */
868
1016
  function serializeTransformTokens(tokens) {
869
1017
  if (!Array.isArray(tokens)) return tokens;
870
1018
  return tokens.map((token) => {
@@ -885,6 +1033,7 @@ function serializeTransformTokens(tokens) {
885
1033
  * back to the original tokens.
886
1034
  */
887
1035
  export class FlattenedTokens {
1036
+ /** @type {{ token: RichTextToken, start: number, end: number }[]} */
888
1037
  #segments = [];
889
1038
  /**
890
1039
  * @param {RichTextToken[]} tokens
@@ -922,6 +1071,7 @@ export class FlattenedTokens {
922
1071
  * @returns {RichTextToken[]}
923
1072
  */
924
1073
  tokensFor(start, end) {
1074
+ /** @type {RichTextToken[]} */
925
1075
  const out = [];
926
1076
  for (const segment of this.#segments) {
927
1077
  if (segment.start === segment.end) {
@@ -953,6 +1103,7 @@ export function flattenForScan(tokens) {
953
1103
  return new FlattenedTokens(tokens);
954
1104
  }
955
1105
 
1106
+ /** @type {Map<number, Modal>} */
956
1107
  const openModals = new Map();
957
1108
 
958
1109
  /**
@@ -977,7 +1128,7 @@ export class Modal {
977
1128
  if (openModals.has(this.#modalId)) return;
978
1129
  openModals.set(this.#modalId, this);
979
1130
  this.onOpen();
980
- self.postMessage({
1131
+ post({
981
1132
  type: "hostCall",
982
1133
  method: "openModal",
983
1134
  args: [
@@ -996,7 +1147,7 @@ export class Modal {
996
1147
  */
997
1148
  update() {
998
1149
  if (!openModals.has(this.#modalId)) return;
999
- self.postMessage({
1150
+ post({
1000
1151
  type: "hostCall",
1001
1152
  method: "updateModal",
1002
1153
  args: [
@@ -1016,7 +1167,7 @@ export class Modal {
1016
1167
  close() {
1017
1168
  if (!openModals.has(this.#modalId)) return;
1018
1169
  openModals.delete(this.#modalId);
1019
- self.postMessage({
1170
+ post({
1020
1171
  type: "hostCall",
1021
1172
  method: "closeModal",
1022
1173
  args: [{ modalId: this.#modalId }],
@@ -1038,15 +1189,16 @@ export class Modal {
1038
1189
 
1039
1190
  /**
1040
1191
  * A tab in the plugin's settings UI. Subclass and override {@link PluginSettingTab.display}
1041
- * to render into `this.containerEl`. Register with `plugin.addSettingTab(tab)`.
1192
+ * to render into `this.containerEl`. Pass the owning plugin to `super(plugin)`
1193
+ * and register with `plugin.addSettingTab(tab)`.
1042
1194
  */
1043
1195
  export class PluginSettingTab {
1044
1196
  /**
1045
- * The owning plugin. Set by the host in {@link Plugin.addSettingTab}.
1046
- * @type {Plugin}
1197
+ * @param {Plugin} plugin The owning plugin, available as `this.plugin`.
1047
1198
  */
1048
- plugin;
1049
- constructor() {
1199
+ constructor(plugin) {
1200
+ /** @type {Plugin} */
1201
+ this.plugin = plugin;
1050
1202
  /** @type {VirtualEl} */
1051
1203
  this.containerEl = new VirtualEl("div");
1052
1204
  /** @type {string | null} */
@@ -1072,7 +1224,9 @@ export class PluginSettingTab {
1072
1224
  * @returns {Promise<void>}
1073
1225
  */
1074
1226
  refresh({ reset = false } = {}) {
1075
- return hostCall("refreshSettingTab", { reset });
1227
+ return /** @type {Promise<void>} */ (
1228
+ hostCall("refreshSettingTab", { reset })
1229
+ );
1076
1230
  }
1077
1231
  }
1078
1232
 
@@ -1171,7 +1325,10 @@ export class Setting {
1171
1325
 
1172
1326
  /** Single-line text input, built via {@link Setting.addText}. */
1173
1327
  export class TextComponent {
1174
- /** @internal */
1328
+ /**
1329
+ * @internal
1330
+ * @param {VirtualEl} containerEl
1331
+ */
1175
1332
  constructor(containerEl) {
1176
1333
  /** @type {VirtualEl} */
1177
1334
  this.el = containerEl.createEl("input", {
@@ -1210,7 +1367,10 @@ export class TextComponent {
1210
1367
 
1211
1368
  /** Multi-line text input, built via {@link Setting.addTextArea}. */
1212
1369
  export class TextAreaComponent {
1213
- /** @internal */
1370
+ /**
1371
+ * @internal
1372
+ * @param {VirtualEl} containerEl
1373
+ */
1214
1374
  constructor(containerEl) {
1215
1375
  /** @type {VirtualEl} */
1216
1376
  this.el = containerEl.createEl("textarea", {
@@ -1248,7 +1408,10 @@ export class TextAreaComponent {
1248
1408
 
1249
1409
  /** On/off toggle switch, built via {@link Setting.addToggle}. */
1250
1410
  export class ToggleComponent {
1251
- /** @internal */
1411
+ /**
1412
+ * @internal
1413
+ * @param {VirtualEl} containerEl
1414
+ */
1252
1415
  constructor(containerEl) {
1253
1416
  /** @type {VirtualEl} */
1254
1417
  this.el = containerEl.createEl("toggle-switch", {
@@ -1278,7 +1441,10 @@ export class ToggleComponent {
1278
1441
 
1279
1442
  /** Single-select dropdown, built via {@link Setting.addDropdown}. */
1280
1443
  export class DropdownComponent {
1281
- /** @internal */
1444
+ /**
1445
+ * @internal
1446
+ * @param {VirtualEl} containerEl
1447
+ */
1282
1448
  constructor(containerEl) {
1283
1449
  /** @type {VirtualEl} */
1284
1450
  this.el = containerEl.createEl("select", {
@@ -1335,7 +1501,10 @@ export class DropdownComponent {
1335
1501
 
1336
1502
  /** Clickable button, built via {@link Setting.addButton}. */
1337
1503
  export class ButtonComponent {
1338
- /** @internal */
1504
+ /**
1505
+ * @internal
1506
+ * @param {VirtualEl} containerEl
1507
+ */
1339
1508
  constructor(containerEl) {
1340
1509
  /** @type {VirtualEl} */
1341
1510
  this.el = containerEl.createEl("button", {
@@ -1372,7 +1541,10 @@ export class ButtonComponent {
1372
1541
 
1373
1542
  /** Renders a host-provided icon by name. Built via {@link VirtualEl.createIcon}. */
1374
1543
  export class IconComponent {
1375
- /** @internal */
1544
+ /**
1545
+ * @internal
1546
+ * @param {VirtualEl} containerEl
1547
+ */
1376
1548
  constructor(containerEl) {
1377
1549
  /** @type {VirtualEl} */
1378
1550
  this.el = containerEl.createEl("plugin-icon");
@@ -1393,7 +1565,10 @@ export class IconComponent {
1393
1565
  * {@link VirtualEl.createBlobImage}.
1394
1566
  */
1395
1567
  export class BlobImageComponent {
1396
- /** @internal */
1568
+ /**
1569
+ * @internal
1570
+ * @param {VirtualEl} containerEl
1571
+ */
1397
1572
  constructor(containerEl) {
1398
1573
  /** @type {VirtualEl} */
1399
1574
  this.el = containerEl.createEl("plugin-blob-image");
@@ -1441,7 +1616,10 @@ export class BlobImageComponent {
1441
1616
  * Built via {@link VirtualEl.createProfilesList}.
1442
1617
  */
1443
1618
  export class ProfilesListComponent {
1444
- /** @internal */
1619
+ /**
1620
+ * @internal
1621
+ * @param {VirtualEl} containerEl
1622
+ */
1445
1623
  constructor(containerEl) {
1446
1624
  /** @type {VirtualEl} */
1447
1625
  this.el = containerEl.createEl("plugin-profiles-list");
@@ -1472,7 +1650,10 @@ export class ProfilesListComponent {
1472
1650
  * Built via {@link VirtualEl.createPostsFeed}.
1473
1651
  */
1474
1652
  export class PostsFeedComponent {
1475
- /** @internal */
1653
+ /**
1654
+ * @internal
1655
+ * @param {VirtualEl} containerEl
1656
+ */
1476
1657
  constructor(containerEl) {
1477
1658
  /** @type {VirtualEl} */
1478
1659
  this.el = containerEl.createEl("plugin-posts-feed");
@@ -1510,7 +1691,10 @@ export class VirtualText {
1510
1691
  this.value = value == null ? "" : String(value);
1511
1692
  }
1512
1693
 
1513
- /** @internal */
1694
+ /**
1695
+ * @internal
1696
+ * @returns {SerializedText}
1697
+ */
1514
1698
  _serialize() {
1515
1699
  return { type: "text", value: this.value };
1516
1700
  }
@@ -1749,8 +1933,12 @@ export class VirtualEl {
1749
1933
  return component;
1750
1934
  }
1751
1935
 
1752
- /** @internal */
1936
+ /**
1937
+ * @internal
1938
+ * @returns {SerializedElement}
1939
+ */
1753
1940
  _serialize() {
1941
+ /** @type {SerializedElement} */
1754
1942
  const serialized = {
1755
1943
  type: "element",
1756
1944
  tag: this.tag,
@@ -1763,7 +1951,63 @@ export class VirtualEl {
1763
1951
  }
1764
1952
  }
1765
1953
 
1954
+ /**
1955
+ * @typedef {{ type: "text", value: string }} SerializedText
1956
+ * {@internal} The wire format of a {@link VirtualText} node.
1957
+ * @typedef {{ type: "element", tag: string, attrs: Record<string, string>, events: Record<string, number>, children: SerializedNode[], styles?: Record<string, string> }} SerializedElement
1958
+ * {@internal} The wire format of a {@link VirtualEl} node.
1959
+ * @typedef {SerializedText | SerializedElement} SerializedNode
1960
+ * {@internal} One node of the serialized tree the host renders and reconciles.
1961
+ * @typedef {{ [key: string]: Cloneable }} CloneableObject
1962
+ * An object whose values are all {@link Cloneable}.
1963
+ * @typedef {Cloneable[]} CloneableArray
1964
+ * An array of {@link Cloneable} values.
1965
+ * @typedef {null | undefined | boolean | number | string | CloneableArray | CloneableObject} Cloneable
1966
+ * JSON-shaped data — the only thing that can cross between a plugin and the
1967
+ * host. Functions, class instances, `Date`, `Map` and friends cannot.
1968
+ * @typedef {{ type: "register", target: "eventListener", event: string, handlerId: number }} RegisterEventListenerMessage
1969
+ * {@internal}
1970
+ * @typedef {{ type: "register", target: "sidebarItem", icon: string | SerializedElement, title: string, handlerId: number }} RegisterSidebarItemMessage
1971
+ * {@internal}
1972
+ * @typedef {{ type: "register", target: "settingTab", name: string | null, displayHandlerId: number }} RegisterSettingTabMessage
1973
+ * {@internal}
1974
+ * @typedef {{ type: "register", target: "feedFilter", handlerId: number }} RegisterFeedFilterMessage
1975
+ * {@internal}
1976
+ * @typedef {{ type: "register", target: "richTextTransform", handlerId: number, handlesFacetTypes: string[] }} RegisterRichTextTransformMessage
1977
+ * {@internal}
1978
+ * @typedef {{ type: "register", target: "slot", name: string, handlerId: number, cacheKey: string[] | null, batch: true }} RegisterSlotMessage
1979
+ * {@internal}
1980
+ * @typedef {{ type: "register", target: "page", id: string, title: string | null, displayHandlerId: number }} RegisterPageMessage
1981
+ * {@internal}
1982
+ * @typedef {RegisterEventListenerMessage | RegisterSidebarItemMessage | RegisterSettingTabMessage | RegisterFeedFilterMessage | RegisterRichTextTransformMessage | RegisterSlotMessage | RegisterPageMessage} RegisterMessage
1983
+ * {@internal} Announces an extension point this plugin provides.
1984
+ * @typedef {{ type: "hostCall", method: string, hostCallId?: number, args: Cloneable[] }} HostCallRequestMessage
1985
+ * {@internal} Calls a host method. Without a `hostCallId` it is fire-and-forget.
1986
+ * @typedef {{ type: "result", callId: number, value?: unknown, error?: string }} CallResultMessage
1987
+ * {@internal} Answers a {@link HostCallMessage}.
1988
+ * @typedef {{ type: "ready", error?: string }} ReadyMessage
1989
+ * {@internal} Reports the outcome of plugin load.
1990
+ * @typedef {RegisterMessage | HostCallRequestMessage | CallResultMessage | ReadyMessage} WorkerMessage
1991
+ * {@internal} Anything this worker may post to the host.
1992
+ * @typedef {{ type: "call", callId: number, handlerId: number, args: Cloneable[] }} HostCallMessage
1993
+ * {@internal} The host invoking a handler this worker registered.
1994
+ * @typedef {{ type: "hostResult", hostCallId: number, value?: Cloneable, error?: string }} HostResultMessage
1995
+ * {@internal} The host answering a {@link hostCall}.
1996
+ * @typedef {{ type: "event", event: "modalDismissed", data: { modalId: number } }} HostEventMessage
1997
+ * {@internal} An out-of-band notification from the host.
1998
+ * @typedef {HostCallMessage | HostResultMessage | HostEventMessage} HostMessage
1999
+ * {@internal} Anything the host may post to this worker.
2000
+ * @typedef {{ status: number, ok: boolean, headers: Record<string, string>, body: string }} SerializedFetchResponse
2001
+ * {@internal} The host's reply to a proxied {@link fetch}.
2002
+ * @typedef {{ method?: string, headers?: Record<string, string>, body?: string }} SerializedFetchInit
2003
+ * {@internal} A {@link PluginFetchInit} with its headers flattened for transfer.
2004
+ * @typedef {Record<string, unknown>} SerializedRichTextToken
2005
+ * {@internal} A {@link RichTextToken} whose `inline`/`block` node, if any, has
2006
+ * been replaced by its serialized form.
2007
+ */
2008
+
1766
2009
  self.onmessage = async (event) => {
2010
+ /** @type {HostMessage} */
1767
2011
  const message = event.data;
1768
2012
  if (!message || typeof message !== "object") return;
1769
2013
 
@@ -1771,7 +2015,7 @@ self.onmessage = async (event) => {
1771
2015
  if (message.type === "call") {
1772
2016
  const fn = callHandlers.get(message.handlerId);
1773
2017
  if (!fn) {
1774
- self.postMessage({
2018
+ post({
1775
2019
  type: "result",
1776
2020
  callId: message.callId,
1777
2021
  error: `unknown handler ${message.handlerId}`,
@@ -1780,12 +2024,12 @@ self.onmessage = async (event) => {
1780
2024
  }
1781
2025
  try {
1782
2026
  const value = await fn(...message.args);
1783
- self.postMessage({ type: "result", callId: message.callId, value });
2027
+ post({ type: "result", callId: message.callId, value });
1784
2028
  } catch (error) {
1785
- self.postMessage({
2029
+ post({
1786
2030
  type: "result",
1787
2031
  callId: message.callId,
1788
- error: error.message ?? String(error),
2032
+ error: getErrorMessage(error),
1789
2033
  });
1790
2034
  }
1791
2035
  return;
@@ -1813,6 +2057,5 @@ self.onmessage = async (event) => {
1813
2057
  return;
1814
2058
  }
1815
2059
  }
1816
- return;
1817
2060
  }
1818
2061
  };