@abraca/junis 2.85.0 → 2.86.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 (152) hide show
  1. package/dist/module.d.mts +17 -2
  2. package/dist/module.json +1 -1
  3. package/dist/module.mjs +235 -19
  4. package/dist/runtime/assets/css/jun.css +1 -1
  5. package/dist/runtime/components/JunCampfirePresence.client.vue +75 -10
  6. package/dist/runtime/components/JunCollectionIntro.d.vue.ts +11 -0
  7. package/dist/runtime/components/JunCollectionIntro.vue +45 -0
  8. package/dist/runtime/components/JunCollectionIntro.vue.d.ts +11 -0
  9. package/dist/runtime/components/JunConfigRow.d.vue.ts +43 -0
  10. package/dist/runtime/components/JunConfigRow.vue +34 -0
  11. package/dist/runtime/components/JunConfigRow.vue.d.ts +43 -0
  12. package/dist/runtime/components/JunFooter.vue +1 -1
  13. package/dist/runtime/components/JunHorizontalTimeline.d.vue.ts +30 -0
  14. package/dist/runtime/components/JunHorizontalTimeline.vue.d.ts +30 -0
  15. package/dist/runtime/components/JunLinksRow.d.vue.ts +16 -1
  16. package/dist/runtime/components/JunLinksRow.vue +17 -7
  17. package/dist/runtime/components/JunLinksRow.vue.d.ts +16 -1
  18. package/dist/runtime/components/JunMedia.client.d.vue.ts +1 -1
  19. package/dist/runtime/components/JunMedia.client.vue.d.ts +1 -1
  20. package/dist/runtime/components/JunNavigation.vue +21 -4
  21. package/dist/runtime/components/JunNoteLinks.d.vue.ts +6 -0
  22. package/dist/runtime/components/JunNoteLinks.vue +57 -0
  23. package/dist/runtime/components/JunNoteLinks.vue.d.ts +6 -0
  24. package/dist/runtime/components/JunPageHero.d.vue.ts +8 -2
  25. package/dist/runtime/components/JunPageHero.vue +15 -3
  26. package/dist/runtime/components/JunPageHero.vue.d.ts +8 -2
  27. package/dist/runtime/components/JunReaders.d.vue.ts +11 -0
  28. package/dist/runtime/components/JunReaders.vue +99 -0
  29. package/dist/runtime/components/JunReaders.vue.d.ts +11 -0
  30. package/dist/runtime/components/JunSearch.client.vue +2 -2
  31. package/dist/runtime/components/JunSectionPresence.client.d.vue.ts +17 -0
  32. package/dist/runtime/components/JunSectionPresence.client.vue +99 -0
  33. package/dist/runtime/components/JunSectionPresence.client.vue.d.ts +17 -0
  34. package/dist/runtime/components/JunThreadComposer.d.vue.ts +37 -0
  35. package/dist/runtime/components/JunThreadComposer.vue +54 -0
  36. package/dist/runtime/components/JunThreadComposer.vue.d.ts +37 -0
  37. package/dist/runtime/components/JunTravellersChip.vue +35 -5
  38. package/dist/runtime/components/JunVideoEmbed.client.d.vue.ts +1 -1
  39. package/dist/runtime/components/JunVideoEmbed.client.vue.d.ts +1 -1
  40. package/dist/runtime/components/JunViewControl.d.vue.ts +29 -0
  41. package/dist/runtime/components/JunViewControl.vue +340 -0
  42. package/dist/runtime/components/JunViewControl.vue.d.ts +29 -0
  43. package/dist/runtime/components/JunViewControls.d.vue.ts +27 -0
  44. package/dist/runtime/components/JunViewControls.vue +94 -0
  45. package/dist/runtime/components/JunViewControls.vue.d.ts +27 -0
  46. package/dist/runtime/components/renderers/JunAppsRenderer.vue +45 -4
  47. package/dist/runtime/components/renderers/JunCinemaRenderer.vue +42 -4
  48. package/dist/runtime/components/renderers/JunConfigRenderer.vue +348 -225
  49. package/dist/runtime/components/renderers/JunCourseRenderer.d.vue.ts +10 -0
  50. package/dist/runtime/components/renderers/JunCourseRenderer.vue +229 -0
  51. package/dist/runtime/components/renderers/JunCourseRenderer.vue.d.ts +10 -0
  52. package/dist/runtime/components/renderers/JunCvRenderer.vue +44 -6
  53. package/dist/runtime/components/renderers/JunDeckRenderer.d.vue.ts +9 -0
  54. package/dist/runtime/components/renderers/JunDeckRenderer.vue +370 -0
  55. package/dist/runtime/components/renderers/JunDeckRenderer.vue.d.ts +9 -0
  56. package/dist/runtime/components/renderers/JunEntryRenderer.vue +151 -23
  57. package/dist/runtime/components/renderers/JunFestivalRenderer.vue +41 -4
  58. package/dist/runtime/components/renderers/JunGardenRenderer.d.vue.ts +10 -0
  59. package/dist/runtime/components/renderers/JunGardenRenderer.vue +280 -0
  60. package/dist/runtime/components/renderers/JunGardenRenderer.vue.d.ts +10 -0
  61. package/dist/runtime/components/renderers/JunGuestbookRenderer.vue +96 -14
  62. package/dist/runtime/components/renderers/JunHomeRenderer.vue +28 -129
  63. package/dist/runtime/components/renderers/JunItemRenderer.d.vue.ts +10 -0
  64. package/dist/runtime/components/renderers/JunItemRenderer.vue +398 -0
  65. package/dist/runtime/components/renderers/JunItemRenderer.vue.d.ts +10 -0
  66. package/dist/runtime/components/renderers/JunJournalRenderer.vue +141 -11
  67. package/dist/runtime/components/renderers/JunLibraryRenderer.vue +295 -12
  68. package/dist/runtime/components/renderers/JunLinksRenderer.vue +33 -1
  69. package/dist/runtime/components/renderers/JunLiveRenderer.vue +37 -1
  70. package/dist/runtime/components/renderers/JunMosaicRenderer.vue +3 -2
  71. package/dist/runtime/components/renderers/JunMovieRenderer.vue +32 -5
  72. package/dist/runtime/components/renderers/JunNowRenderer.vue +38 -5
  73. package/dist/runtime/components/renderers/JunPollRenderer.d.vue.ts +9 -0
  74. package/dist/runtime/components/renderers/JunPollRenderer.vue +231 -0
  75. package/dist/runtime/components/renderers/JunPollRenderer.vue.d.ts +9 -0
  76. package/dist/runtime/components/renderers/JunProjectRenderer.vue +74 -18
  77. package/dist/runtime/components/renderers/JunServicesRenderer.vue +40 -2
  78. package/dist/runtime/components/renderers/JunStatsRenderer.vue +37 -50
  79. package/dist/runtime/components/renderers/JunThreadRenderer.d.vue.ts +9 -0
  80. package/dist/runtime/components/renderers/JunThreadRenderer.vue +304 -0
  81. package/dist/runtime/components/renderers/JunThreadRenderer.vue.d.ts +9 -0
  82. package/dist/runtime/components/renderers/JunTrackRenderer.vue +32 -4
  83. package/dist/runtime/components/renderers/JunUsesRenderer.vue +51 -5
  84. package/dist/runtime/components/renderers/JunWallRenderer.vue +60 -5
  85. package/dist/runtime/composables/useJunDeck.d.ts +66 -0
  86. package/dist/runtime/composables/useJunDeck.js +61 -0
  87. package/dist/runtime/composables/useJunDocPage.d.ts +14 -11
  88. package/dist/runtime/composables/useJunDocPage.js +67 -3
  89. package/dist/runtime/composables/useJunFollow.d.ts +65 -9
  90. package/dist/runtime/composables/useJunFollow.js +237 -20
  91. package/dist/runtime/composables/useJunGarden.d.ts +67 -0
  92. package/dist/runtime/composables/useJunGarden.js +92 -0
  93. package/dist/runtime/composables/useJunPresence.d.ts +26 -0
  94. package/dist/runtime/composables/useJunPresence.js +9 -2
  95. package/dist/runtime/composables/useJunSections.d.ts +73 -0
  96. package/dist/runtime/composables/useJunSections.js +117 -0
  97. package/dist/runtime/composables/useJunSettings.d.ts +1 -1
  98. package/dist/runtime/composables/useJunSettings.js +5 -1
  99. package/dist/runtime/composables/useJunSiteConfig.d.ts +37 -0
  100. package/dist/runtime/composables/useJunTheme.js +40 -2
  101. package/dist/runtime/composables/useJunViewOptions.d.ts +85 -0
  102. package/dist/runtime/composables/useJunViewOptions.js +63 -0
  103. package/dist/runtime/pages/doc.vue +14 -8
  104. package/dist/runtime/server/api/health.get.d.ts +19 -0
  105. package/dist/runtime/server/api/health.get.js +40 -0
  106. package/dist/runtime/server/api/links.get.d.ts +19 -0
  107. package/dist/runtime/server/api/links.get.js +37 -0
  108. package/dist/runtime/server/api/resolve/[...slug].get.d.ts +9 -0
  109. package/dist/runtime/server/api/resolve/[...slug].get.js +5 -0
  110. package/dist/runtime/server/api/stats.get.js +2 -1
  111. package/dist/runtime/server/janitor/junJanitorChores.js +8 -0
  112. package/dist/runtime/server/plugins/jun-bootstrap.js +103 -15
  113. package/dist/runtime/server/plugins/jun-doc-cache.js +42 -4
  114. package/dist/runtime/server/plugins/jun-janitor.js +7 -0
  115. package/dist/runtime/server/plugins/jun-rpc.js +293 -0
  116. package/dist/runtime/server/plugins/jun-watchdog.d.ts +2 -0
  117. package/dist/runtime/server/plugins/jun-watchdog.js +54 -0
  118. package/dist/runtime/server/routes/sitemap.xml.get.js +2 -0
  119. package/dist/runtime/server/utils/junBoot.d.ts +1 -0
  120. package/dist/runtime/server/utils/junBoot.js +4 -0
  121. package/dist/runtime/server/utils/junCache.d.ts +17 -0
  122. package/dist/runtime/server/utils/junCache.js +5 -0
  123. package/dist/runtime/server/utils/junSeedGate.d.ts +68 -0
  124. package/dist/runtime/server/utils/junSeedGate.js +41 -0
  125. package/dist/runtime/types.d.ts +57 -1
  126. package/dist/runtime/utils/junCourse.d.ts +106 -0
  127. package/dist/runtime/utils/junCourse.js +65 -0
  128. package/dist/runtime/utils/junGarden.d.ts +193 -0
  129. package/dist/runtime/utils/junGarden.js +233 -0
  130. package/dist/runtime/utils/junMetaSchemas.js +8 -1
  131. package/dist/runtime/utils/junModeration.d.ts +67 -0
  132. package/dist/runtime/utils/junModeration.js +20 -0
  133. package/dist/runtime/utils/junMotion.d.ts +26 -0
  134. package/dist/runtime/utils/junMotion.js +31 -0
  135. package/dist/runtime/utils/junPeople.d.ts +43 -0
  136. package/dist/runtime/utils/junPeople.js +9 -0
  137. package/dist/runtime/utils/junPoll.d.ts +79 -0
  138. package/dist/runtime/utils/junPoll.js +82 -0
  139. package/dist/runtime/utils/junReadiness.d.ts +131 -0
  140. package/dist/runtime/utils/junReadiness.js +69 -0
  141. package/dist/runtime/utils/junSections.d.ts +115 -0
  142. package/dist/runtime/utils/junSections.js +45 -0
  143. package/dist/runtime/utils/junSlides.d.ts +66 -0
  144. package/dist/runtime/utils/junSlides.js +47 -0
  145. package/dist/runtime/utils/junThread.d.ts +81 -0
  146. package/dist/runtime/utils/junThread.js +75 -0
  147. package/dist/runtime/utils/junViewSpecs.d.ts +671 -0
  148. package/dist/runtime/utils/junViewSpecs.js +534 -0
  149. package/dist/runtime/utils/junViewValues.d.ts +125 -0
  150. package/dist/runtime/utils/junViewValues.js +104 -0
  151. package/dist/types.d.mts +1 -1
  152. package/package.json +5 -1
@@ -2,10 +2,11 @@ import * as Y from "yjs";
2
2
  import { AbracadabraProvider } from "@abraca/dabra";
3
3
  import { markdownToFragmentNodes } from "@abraca/convert";
4
4
  import { defineNitroPlugin, useRuntimeConfig } from "nitropack/runtime";
5
+ import { junSeedFinished, junSeedStarted } from "../utils/junSeedGate.js";
5
6
  const BOOT_DELAY_MS = 4e3;
6
7
  const SYNC_TIMEOUT_MS = 1e4;
7
8
  const ECHO_TIMEOUT_MS = 8e3;
8
- const BODY_CONCURRENCY = 4;
9
+ const BODY_CONCURRENCY = 8;
9
10
  const BODY_FLUSH_MS = 400;
10
11
  function plain(e) {
11
12
  if (!e) return void 0;
@@ -128,7 +129,8 @@ function defaultTree(typeIds) {
128
129
  {
129
130
  label: "Something in progress",
130
131
  type: typeIds.app ?? "doc",
131
- meta: { status: "building", description: "Tiles reorder by dragging \u2014 their order is stored." }
132
+ meta: { status: "building", description: "Tiles reorder by dragging \u2014 their order is stored." },
133
+ body: "Tiles reorder by dragging, and the order is stored on the documents \u2014 so everyone sees the same arrangement rather than a per-browser one."
132
134
  }
133
135
  ]
134
136
  });
@@ -148,7 +150,8 @@ function defaultTree(typeIds) {
148
150
  place: "Everywhere",
149
151
  description: 'An open end reads as "now" \u2014 leave it blank while something is ongoing.',
150
152
  icon: "sprout"
151
- }
153
+ },
154
+ body: "A station is a document, so it holds as much as you want to write about it. This one has no end date, which is how the timeline draws it as ongoing."
152
155
  },
153
156
  {
154
157
  label: "Something earlier",
@@ -158,7 +161,8 @@ function defaultTree(typeIds) {
158
161
  end: "2021",
159
162
  place: "Elsewhere",
160
163
  description: "A bare year is fine. Stations sort newest first by their start."
161
- }
164
+ },
165
+ body: "Stations sort by their start date, newest first. A bare year is enough \u2014 and a station with no dates at all sorts last rather than being dropped, which is the rule every collection here follows."
162
166
  }
163
167
  ]
164
168
  });
@@ -177,7 +181,8 @@ function defaultTree(typeIds) {
177
181
  url: "https://github.com/abracadabra",
178
182
  icon: "github",
179
183
  description: "The platform this site is built on."
180
- }
184
+ },
185
+ body: "A links row is a document too, so it can carry a note about why the link is here. Rows with a destination open outward; the page behind them is still indexed and still yours to write."
181
186
  },
182
187
  {
183
188
  // No url on purpose: a row without one links to its own page, which
@@ -187,7 +192,8 @@ function defaultTree(typeIds) {
187
192
  meta: {
188
193
  icon: "file-text",
189
194
  description: "No URL, so this row opens its own page instead."
190
- }
195
+ },
196
+ body: "No `url`, so this row opens its own page rather than pointing outward. Add one from the editor and it starts leaving the site \u2014 which is how a note grows into a link, or the other way round."
191
197
  }
192
198
  ]
193
199
  });
@@ -202,19 +208,22 @@ function defaultTree(typeIds) {
202
208
  {
203
209
  label: "A laptop",
204
210
  type: "doc",
205
- meta: { category: "Hardware", icon: "laptop", description: "Sections come from the page's own meta.categories." }
211
+ meta: { category: "Hardware", icon: "laptop", description: "Sections come from the page's own meta.categories." },
212
+ body: "Sections on the Uses page come from that page's own `categories` metadata, not from code \u2014 so the headings are yours to name."
206
213
  },
207
214
  {
208
215
  label: "An editor",
209
216
  type: "doc",
210
- meta: { category: "Software", icon: "code", description: "Change an item's category and it moves section." }
217
+ meta: { category: "Software", icon: "code", description: "Change an item's category and it moves section." },
218
+ body: "Change this item's category and it moves section, live, for everyone reading the page. The move is one write; nothing is duplicated and nothing is deleted."
211
219
  },
212
220
  {
213
221
  // No category on purpose: it must surface under "Other" rather than
214
222
  // vanish, which is the rule that makes page types convertible.
215
223
  label: "Something uncategorised",
216
224
  type: "doc",
217
- meta: { icon: "box", description: 'No category \u2014 shows under "Other".' }
225
+ meta: { icon: "box", description: 'No category \u2014 shows under "Other".' },
226
+ body: "No category at all, so it shows under **Other** rather than vanishing. Every collection here tolerates a child it did not expect \u2014 that is what makes changing a page's type safe."
218
227
  }
219
228
  ]
220
229
  });
@@ -229,14 +238,21 @@ function defaultTree(typeIds) {
229
238
  {
230
239
  label: "Something being read",
231
240
  type: "doc",
232
- meta: { status: "reading", author: "An author", rating: 4 }
241
+ meta: { status: "reading", author: "An author", rating: 4 },
242
+ body: "Books are child documents shelved by one metadata field. Open one and you get a page of its own \u2014 the place for a note about what it changed."
233
243
  },
234
244
  {
235
245
  label: "Something finished",
236
246
  type: "doc",
237
- meta: { status: "read", author: "Another author", rating: 5 }
247
+ meta: { status: "read", author: "Another author", rating: 5 },
248
+ body: "Drag a book between shelves to change its status. That is a single write, and it is live for everyone reading the page."
238
249
  },
239
- { label: "Something next", type: "doc", meta: { status: "want" } }
250
+ {
251
+ label: "Something next",
252
+ type: "doc",
253
+ meta: { status: "want" },
254
+ body: 'Nothing has been read here yet. A book with no status at all shelves under "Up next" \u2014 the state a book starts in \u2014 rather than needing one set before it can appear.'
255
+ }
240
256
  ]
241
257
  });
242
258
  }
@@ -436,12 +452,16 @@ export default defineNitroPlugin((nitroApp) => {
436
452
  {
437
453
  name: "jun:bootstrap",
438
454
  start(ctx) {
455
+ junSeedStarted();
439
456
  const timer = setTimeout(() => {
440
457
  void bootstrap(ctx, seed).catch((err) => {
441
458
  console.warn("[jun:bootstrap] failed:", err?.message ?? err);
442
- });
459
+ }).finally(() => junSeedFinished());
443
460
  }, BOOT_DELAY_MS);
444
- return () => clearTimeout(timer);
461
+ return () => {
462
+ clearTimeout(timer);
463
+ junSeedFinished();
464
+ };
445
465
  }
446
466
  }
447
467
  ]
@@ -488,6 +508,7 @@ async function bootstrap(ctx, seed) {
488
508
  if (hasContent) {
489
509
  console.log("[jun:bootstrap] root already has content \u2014 skipping seed");
490
510
  repairIconFormat(ydoc, tree);
511
+ if (backfillRequested()) await backfillBodies(ctx, tree, rootId, nodes);
491
512
  return;
492
513
  }
493
514
  console.log("[jun:bootstrap] empty root \u2014 seeding starter content");
@@ -677,6 +698,72 @@ function attachJsonNodes(target, nodes) {
677
698
  }
678
699
  }
679
700
  }
701
+ const SCHEMA_NODE_NAMES = /* @__PURE__ */ new Set(["documentHeader", "documentMeta"]);
702
+ function fragmentHasProse(fragment) {
703
+ for (const child of fragment.toArray()) {
704
+ const name = child.nodeName;
705
+ if (name && SCHEMA_NODE_NAMES.has(name)) continue;
706
+ if (name === "paragraph") {
707
+ const text = child.toString?.().replace(/<[^>]*>/g, "").trim();
708
+ if (!text) continue;
709
+ }
710
+ return true;
711
+ }
712
+ return false;
713
+ }
714
+ function backfillRequested() {
715
+ const v = process.env.JUN_SEED_BACKFILL;
716
+ return v === "1" || v === "true";
717
+ }
718
+ async function backfillBodies(ctx, tree, rootId, nodes) {
719
+ const childrenByLabel = (parentId) => {
720
+ const out = /* @__PURE__ */ new Map();
721
+ tree.forEach((raw, id) => {
722
+ const e = plain(raw);
723
+ if (!e || e.trashed || e.parentId !== parentId || id === parentId) return;
724
+ const label = e.label;
725
+ if (!label) return;
726
+ out.set(label, out.has(label) ? null : id);
727
+ });
728
+ return out;
729
+ };
730
+ const matched = [];
731
+ const ambiguous = [];
732
+ const missing = [];
733
+ const walk = (seedNodes, parentId) => {
734
+ const live = childrenByLabel(parentId);
735
+ for (const node of seedNodes) {
736
+ const id = live.get(node.label);
737
+ if (id === null) {
738
+ ambiguous.push(node.label);
739
+ continue;
740
+ }
741
+ if (!id) {
742
+ missing.push(node.label);
743
+ continue;
744
+ }
745
+ const planned = toPlan(node);
746
+ if (typeof planned.meta.body === "string" && planned.meta.body) {
747
+ matched.push({ ...planned, id, children: [] });
748
+ }
749
+ if (node.children?.length) walk(node.children, id);
750
+ }
751
+ };
752
+ walk(nodes, rootId);
753
+ if (ambiguous.length) {
754
+ console.warn(
755
+ `[jun:bootstrap] backfill skipped ${ambiguous.length} ambiguous label(s): ` + ambiguous.slice(0, 8).join(", ")
756
+ );
757
+ }
758
+ if (!matched.length) {
759
+ console.log(
760
+ `[jun:bootstrap] backfill: nothing to fill` + (missing.length ? ` (${missing.length} seed page(s) not found in this tree)` : "")
761
+ );
762
+ return;
763
+ }
764
+ console.log(`[jun:bootstrap] backfill: ${matched.length} candidate document(s)`);
765
+ await writeBodies(ctx, matched);
766
+ }
680
767
  async function writeBodies(ctx, flat) {
681
768
  const withBody = flat.filter((n) => typeof n.meta.body === "string" && n.meta.body);
682
769
  if (!withBody.length) return;
@@ -703,12 +790,13 @@ async function writeBodies(ctx, flat) {
703
790
  });
704
791
  }
705
792
  const fragment = ydoc.getXmlFragment("default");
706
- if (fragment.length > 0) return;
793
+ if (fragmentHasProse(fragment)) return;
707
794
  const { header, meta, body } = markdownToFragmentNodes(
708
795
  String(node.meta.body),
709
796
  node.label
710
797
  );
711
798
  ydoc.transact(() => {
799
+ if (fragment.length > 0) fragment.delete(0, fragment.length);
712
800
  attachJsonNodes(fragment, [
713
801
  ...header ? [header] : [],
714
802
  ...meta ? [meta] : [],
@@ -1,8 +1,8 @@
1
1
  import * as Y from "yjs";
2
2
  import { AbracadabraProvider } from "@abraca/dabra";
3
3
  import { Node } from "@tiptap/core";
4
- import { defineNitroPlugin, useRuntimeConfig } from "nitropack/runtime";
5
- import { junCountedDocIds } from "../utils/junCache.js";
4
+ import { defineNitroPlugin, useRuntimeConfig, useStorage } from "nitropack/runtime";
5
+ import { JUN_HEARTBEAT_KEY, junCountedDocIds } from "../utils/junCache.js";
6
6
  import { junReadActivity, junSweepActivity } from "../utils/junActivity.js";
7
7
  import { junDayKey } from "../utils/junActivityMath.js";
8
8
  import { junCreateRegistrar, junSetRegisterTreeState } from "../utils/junRegisterTree.js";
@@ -29,6 +29,27 @@ const CalloutStub = Node.create({
29
29
  content: "block+",
30
30
  renderHTML: () => ["div", { class: "callout" }, 0]
31
31
  });
32
+ const DocLinkStub = Node.create({
33
+ name: "docLink",
34
+ group: "inline",
35
+ inline: true,
36
+ atom: true,
37
+ addAttributes: () => ({ docId: { default: null } }),
38
+ renderHTML: ({ HTMLAttributes }) => ["a", {
39
+ "href": `/doc/${HTMLAttributes.docId}`,
40
+ "data-doc-link": ""
41
+ }]
42
+ });
43
+ const DocEmbedStub = Node.create({
44
+ name: "docEmbed",
45
+ group: "block",
46
+ atom: true,
47
+ addAttributes: () => ({ docId: { default: null } }),
48
+ renderHTML: ({ HTMLAttributes }) => ["div", { "data-doc-embed": "" }, [
49
+ "a",
50
+ { href: `/doc/${HTMLAttributes.docId}` }
51
+ ]]
52
+ });
32
53
  function createLimiter(concurrency) {
33
54
  let active = 0;
34
55
  const queue = [];
@@ -55,7 +76,13 @@ export default defineNitroPlugin((nitroApp) => {
55
76
  nitroApp.hooks.hook("abracadabra:before-runners", () => {
56
77
  registerServerPlugin({
57
78
  name: "jun:doc-cache",
58
- serverExtensions: () => [DocumentHeaderStub, DocumentMetaStub, CalloutStub],
79
+ serverExtensions: () => [
80
+ DocumentHeaderStub,
81
+ DocumentMetaStub,
82
+ CalloutStub,
83
+ DocLinkStub,
84
+ DocEmbedStub
85
+ ],
59
86
  serverRunners: [
60
87
  {
61
88
  name: "jun:doc-cache",
@@ -153,12 +180,23 @@ export default defineNitroPlugin((nitroApp) => {
153
180
  console.warn("[jun:doc-cache] activity sweep failed:", e);
154
181
  }
155
182
  }
183
+ const beat = async () => {
184
+ try {
185
+ await useStorage().setItem(JUN_HEARTBEAT_KEY, {
186
+ at: Date.now(),
187
+ docs: docs.size
188
+ });
189
+ } catch (e) {
190
+ console.warn("[jun:doc-cache] heartbeat write failed:", e);
191
+ }
192
+ };
193
+ void beat();
156
194
  const sweep = setInterval(() => {
157
195
  const renders = [...docs].map(
158
196
  ([docId, ydoc]) => limit(() => renderDoc(docId, ydoc)).catch(() => {
159
197
  })
160
198
  );
161
- void Promise.all(renders).then(bookActivity);
199
+ void Promise.all(renders).then(bookActivity).then(beat);
162
200
  }, REFRESH_INTERVAL_MS);
163
201
  const observer = (event) => {
164
202
  event.keysChanged.forEach((docId) => {
@@ -8,7 +8,9 @@ import {
8
8
  plain
9
9
  } from "../janitor/junJanitorStore.js";
10
10
  import { junSiteConfigMeta, junSlugMap } from "../utils/junCache.js";
11
+ import { junSeedExpected, junSeedSettled, junWaitForSeed } from "../utils/junSeedGate.js";
11
12
  const BOOT_DELAY_MS = 2e4;
13
+ const SEED_WAIT_MS = 18e4;
12
14
  export default defineNitroPlugin((nitroApp) => {
13
15
  const runtime = useRuntimeConfig();
14
16
  const jun = runtime.public.jun;
@@ -27,6 +29,11 @@ export default defineNitroPlugin((nitroApp) => {
27
29
  const boot = setTimeout(() => {
28
30
  void (async () => {
29
31
  try {
32
+ if (junSeedExpected() && !junSeedSettled()) {
33
+ log('waiting for the seeder to finish before deciding what "clean" means');
34
+ const settled = await junWaitForSeed(SEED_WAIT_MS);
35
+ log(settled ? "seed finished \u2014 reading the site" : `seed still running after ${Math.round(SEED_WAIT_MS / 1e3)}s \u2014 starting anyway`);
36
+ }
30
37
  shutdown = await hire(ctx, options, log);
31
38
  } catch (error) {
32
39
  log(`could not start: ${error?.message ?? error}`);
@@ -1,4 +1,14 @@
1
1
  import * as Y from "yjs";
2
+ import {
3
+ junCapBallots,
4
+ junMyBallot,
5
+ junNextBallot,
6
+ junPollBallots,
7
+ junPollChoices,
8
+ junTallyVotes
9
+ } from "../../utils/junPoll.js";
10
+ import { junCanReplyTo } from "../../utils/junThread.js";
11
+ import { junCapProgress, junCourseProgress, junNextProgress } from "../../utils/junCourse.js";
2
12
  import { AbracadabraProvider } from "@abraca/dabra";
3
13
  import { defineNitroPlugin, useRuntimeConfig } from "nitropack/runtime";
4
14
  const SYNC_TIMEOUT_MS = 8e3;
@@ -50,6 +60,35 @@ const reactSchema = {
50
60
  return { docId: v.docId };
51
61
  }
52
62
  };
63
+ const voteSchema = {
64
+ parse(value) {
65
+ const v = value;
66
+ if (typeof v?.docId !== "string" || !v.docId) throw new Error("docId required");
67
+ const choice = typeof v?.choice === "number" ? v.choice : Number(v?.choice);
68
+ if (!Number.isInteger(choice) || choice < 0 || choice > 64) throw new Error("choice must be an index");
69
+ return { docId: v.docId, choice };
70
+ }
71
+ };
72
+ const postSchema = {
73
+ parse(value) {
74
+ const v = value;
75
+ if (typeof v?.docId !== "string" || !v.docId) throw new Error("docId required");
76
+ const message = cleanText(String(v?.message ?? ""));
77
+ if (!message) throw new Error("message is empty");
78
+ if (message.length > MAX_MESSAGE) throw new Error(`message too long (max ${MAX_MESSAGE})`);
79
+ const handle = cleanText(String(v.handle ?? "")).replace(/\n/g, " ").slice(0, MAX_HANDLE) || "Traveller";
80
+ const replyTo = typeof v?.replyTo === "string" && v.replyTo ? v.replyTo : null;
81
+ return { docId: v.docId, message, handle, replyTo };
82
+ }
83
+ };
84
+ const stepSchema = {
85
+ parse(value) {
86
+ const v = value;
87
+ if (typeof v?.docId !== "string" || !v.docId) throw new Error("docId required");
88
+ if (typeof v?.stepId !== "string" || !v.stepId) throw new Error("stepId required");
89
+ return { docId: v.docId, stepId: v.stepId };
90
+ }
91
+ };
53
92
  export default defineNitroPlugin((nitroApp) => {
54
93
  const jun = useRuntimeConfig().public.jun;
55
94
  if (!jun?.features?.rpc) return;
@@ -408,6 +447,260 @@ export default defineNitroPlugin((nitroApp) => {
408
447
  }
409
448
  }),
410
449
  // @ts-expect-error — server auto-import from @abraca/nuxt
450
+ defineRpcHandler({
451
+ method: "jun.thread.post@1",
452
+ schema: postSchema,
453
+ /**
454
+ * Post to a `jun-thread`.
455
+ *
456
+ * The guestbook's signature with one more field. Every post is a
457
+ * hidden child DOCUMENT rather than an entry in a blob of meta, so
458
+ * moderation, the trash, search exclusion and the permission cascade
459
+ * all work without inventing anything — and adding a reply never
460
+ * rewrites somebody else's words, which a nested structure in one
461
+ * document would do on every post.
462
+ */
463
+ async handler({ docId, message, handle, replyTo }, ctx) {
464
+ if (siteConfig().guestbookEnabled === false) {
465
+ throw new RpcError("DISABLED", "the conversation is closed right now");
466
+ }
467
+ const page = plain(sharedTree().get(docId));
468
+ const threadType = jun?.typeIds?.thread;
469
+ if (!page || page.trashed || threadType && page.type !== threadType) {
470
+ throw new RpcError("NOT_FOUND", "no conversation here");
471
+ }
472
+ if (page.meta?.threadClosed === true) {
473
+ throw new RpcError("DISABLED", "this conversation is closed");
474
+ }
475
+ const siblings = [];
476
+ const now = Date.now();
477
+ let mineRecent = 0;
478
+ let recentAny = 0;
479
+ sharedTree().forEach((e, id2) => {
480
+ const entry = plain(e);
481
+ if (!entry || entry.parentId !== docId || entry.trashed) return;
482
+ siblings.push({ id: id2, parentId: entry.parentId, trashed: entry.trashed, meta: entry.meta });
483
+ const date = typeof entry.meta?.date === "number" ? entry.meta.date : 0;
484
+ if (date > now - FLOOD_WINDOW_MS) recentAny++;
485
+ if (entry.meta?.signerId === ctx.from && date > now - PER_SIGNER_COOLDOWN_MS) mineRecent++;
486
+ });
487
+ if (!junCanReplyTo(siblings, docId, replyTo)) {
488
+ throw new RpcError("NOT_FOUND", "that post is not in this conversation");
489
+ }
490
+ if (mineRecent > 0) {
491
+ throw new RpcError("RATE_LIMITED", "one at a time \u2014 try again in a moment");
492
+ }
493
+ if (recentAny >= FLOOD_MAX) {
494
+ throw new RpcError("RATE_LIMITED", "this conversation is busy \u2014 try again in a minute");
495
+ }
496
+ const id = crypto.randomUUID();
497
+ await withRootTree(
498
+ (tree) => {
499
+ tree.set(id, {
500
+ label: handle,
501
+ type: "doc",
502
+ parentId: docId,
503
+ order: now,
504
+ createdAt: now,
505
+ updatedAt: now,
506
+ meta: {
507
+ hidden: true,
508
+ message,
509
+ // The SERVER stamps who wrote this, never the client.
510
+ signerId: ctx.from,
511
+ signerHandle: handle,
512
+ date: now,
513
+ ...replyTo ? { replyTo } : {}
514
+ }
515
+ });
516
+ },
517
+ () => !!sharedTree().get(id)
518
+ );
519
+ try {
520
+ await runner.client.createChild(docId, { child_id: id, label: handle, doc_type: "doc" });
521
+ } catch (err) {
522
+ console.warn(`[jun:rpc] register post ${id} failed:`, err?.message ?? err);
523
+ }
524
+ return { id, date: now };
525
+ }
526
+ }),
527
+ // @ts-expect-error — server auto-import from @abraca/nuxt
528
+ defineRpcHandler({
529
+ method: "jun.course.step@1",
530
+ schema: stepSchema,
531
+ /**
532
+ * Tick (or untick) a step of a `jun-course`.
533
+ *
534
+ * The fourth write path of this shape, and the one where the rule
535
+ * matters most: progress is a claim about a PERSON, so it is keyed by
536
+ * `ctx.from` — the identity the server stamped. A second tab, a
537
+ * reload and a reconnect are one learner, and nobody can tick a step
538
+ * on somebody else's behalf.
539
+ *
540
+ * The step must be a CHILD of the course. Without that check any
541
+ * document id would be storable as progress, which turns a narrow
542
+ * write path into a general-purpose one — the same reason the poll
543
+ * checks its choice index and the thread checks its parent.
544
+ */
545
+ async handler({ docId, stepId }, ctx) {
546
+ if (siteConfig().reactionsEnabled === false) {
547
+ throw new RpcError("DISABLED", "this course is not taking progress right now");
548
+ }
549
+ const page = plain(sharedTree().get(docId));
550
+ const courseType = jun?.typeIds?.course;
551
+ if (!page || page.trashed || courseType && page.type !== courseType) {
552
+ throw new RpcError("NOT_FOUND", "no course here");
553
+ }
554
+ const stepIds = () => {
555
+ const out = [];
556
+ sharedTree().forEach((e, id) => {
557
+ const entry2 = plain(e);
558
+ if (!entry2 || entry2.parentId !== docId || entry2.trashed) return;
559
+ out.push({ id, order: typeof entry2.order === "number" ? entry2.order : 0 });
560
+ });
561
+ return out.sort((a, b) => a.order - b.order).map((step) => step.id);
562
+ };
563
+ if (!stepIds().includes(stepId)) {
564
+ throw new RpcError("NOT_FOUND", "that step is not part of this course");
565
+ }
566
+ let stored = [];
567
+ let refused = false;
568
+ await withRootTree(
569
+ (tree) => {
570
+ const entry2 = plain(tree.get(docId));
571
+ if (!entry2) {
572
+ throw new RpcError("NOT_FOUND", "no course here");
573
+ }
574
+ const ids2 = stepIds();
575
+ const progress2 = junCourseProgress(entry2.meta, ids2);
576
+ if (!junCapProgress(progress2, ctx.from)) {
577
+ refused = true;
578
+ return;
579
+ }
580
+ const next = junNextProgress(progress2[ctx.from], ids2, stepId);
581
+ if (next === null) {
582
+ refused = true;
583
+ return;
584
+ }
585
+ stored = next;
586
+ const kept = Object.fromEntries(
587
+ Object.entries(progress2).filter(([person]) => person !== ctx.from)
588
+ );
589
+ tree.set(docId, {
590
+ ...entry2,
591
+ // `updatedAt` deliberately not bumped: ticking a step is not
592
+ // an edit of the course, and bumping it would put every course
593
+ // at the top of every "recently changed" list forever.
594
+ meta: {
595
+ ...entry2.meta ?? {},
596
+ courseProgress: next.length ? { ...kept, [ctx.from]: next } : kept
597
+ }
598
+ });
599
+ },
600
+ () => {
601
+ if (refused) return true;
602
+ const entry2 = plain(sharedTree().get(docId));
603
+ const mine = junCourseProgress(entry2?.meta, stepIds())[ctx.from] ?? [];
604
+ return mine.length === stored.length && mine.every((id, i) => id === stored[i]);
605
+ }
606
+ );
607
+ if (refused) {
608
+ throw new RpcError("LIMIT", "this course cannot take any more progress");
609
+ }
610
+ const entry = plain(sharedTree().get(docId));
611
+ const ids = stepIds();
612
+ const progress = junCourseProgress(entry?.meta, ids);
613
+ return {
614
+ mine: stored,
615
+ people: Object.keys(progress).length,
616
+ finished: Object.values(progress).filter((l) => ids.length > 0 && l.length === ids.length).length
617
+ };
618
+ }
619
+ }),
620
+ // @ts-expect-error — server auto-import from @abraca/nuxt
621
+ defineRpcHandler({
622
+ method: "jun.poll.vote@1",
623
+ schema: voteSchema,
624
+ /**
625
+ * Cast a vote on a `jun-poll`.
626
+ *
627
+ * The same shape as the guestbook's signature and for the same
628
+ * reason: a visitor has no write access to this document, so the
629
+ * server writes on their behalf after checking who they are. What
630
+ * it stores is keyed by `ctx.from` — the identity the SERVER
631
+ * stamped — which is what makes "one vote per person" true rather
632
+ * than merely intended. A client-supplied voter id would make
633
+ * ballot-stuffing a one-line change.
634
+ */
635
+ async handler({ docId, choice }, ctx) {
636
+ if (siteConfig().reactionsEnabled === false) {
637
+ throw new RpcError("DISABLED", "voting is off right now");
638
+ }
639
+ const page = plain(sharedTree().get(docId));
640
+ const pollType = jun?.typeIds?.poll;
641
+ if (!page || page.trashed || pollType && page.type !== pollType) {
642
+ throw new RpcError("NOT_FOUND", "no poll here");
643
+ }
644
+ const choices = junPollChoices(page.meta?.pollOptions);
645
+ if (!choices.length) {
646
+ throw new RpcError("NOT_FOUND", "this poll has no choices yet");
647
+ }
648
+ if (choice >= choices.length) {
649
+ throw new RpcError("INVALID", "no such choice");
650
+ }
651
+ let stored = [];
652
+ let refused = false;
653
+ await withRootTree(
654
+ (tree) => {
655
+ const entry2 = plain(tree.get(docId));
656
+ if (!entry2) {
657
+ throw new RpcError("NOT_FOUND", "no poll here");
658
+ }
659
+ const live = junPollChoices(entry2.meta?.pollOptions);
660
+ const ballots = junPollBallots(entry2.meta?.pollVotes, live.length);
661
+ const next = junNextBallot(junMyBallot(ballots, ctx.from), choice, {
662
+ multiple: entry2.meta?.pollMultiple === true,
663
+ revote: entry2.meta?.pollRevote !== false
664
+ });
665
+ if (next === null) {
666
+ refused = true;
667
+ return;
668
+ }
669
+ stored = next;
670
+ const kept = Object.fromEntries(
671
+ Object.entries(ballots).filter(([voter]) => voter !== ctx.from)
672
+ );
673
+ const votes = junCapBallots(
674
+ next.length ? { ...kept, [ctx.from]: next } : kept
675
+ );
676
+ tree.set(docId, {
677
+ ...entry2,
678
+ // `updatedAt` deliberately not bumped — a vote is not an
679
+ // edit, and bumping it would put every poll at the top of
680
+ // every "recently changed" list forever.
681
+ meta: { ...entry2.meta ?? {}, pollVotes: votes }
682
+ });
683
+ },
684
+ () => {
685
+ if (refused) return true;
686
+ const entry2 = plain(sharedTree().get(docId));
687
+ const live = junPollChoices(entry2?.meta?.pollOptions);
688
+ const mine = junMyBallot(junPollBallots(entry2?.meta?.pollVotes, live.length), ctx.from);
689
+ return mine.length === stored.length && mine.every((c, i) => c === stored[i]);
690
+ }
691
+ );
692
+ if (refused) {
693
+ throw new RpcError("LIMIT", "this poll only takes one vote per person");
694
+ }
695
+ const entry = plain(sharedTree().get(docId));
696
+ const tally = junTallyVotes(
697
+ junPollBallots(entry?.meta?.pollVotes, choices.length),
698
+ choices.length
699
+ );
700
+ return { mine: stored, counts: tally.counts, voters: tally.voters };
701
+ }
702
+ }),
703
+ // @ts-expect-error — server auto-import from @abraca/nuxt
411
704
  defineRpcHandler({
412
705
  method: "jun.react@1",
413
706
  schema: reactSchema,
@@ -0,0 +1,2 @@
1
+ declare const _default: import("nitropack").NitroAppPlugin;
2
+ export default _default;