@abraca/junis 2.81.0 → 2.82.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.
@@ -7,6 +7,33 @@ declare const _default: import("h3").EventHandler<Omit<import("h3").EventHandler
7
7
  appreciations: number;
8
8
  words: number;
9
9
  newestEdit: number;
10
+ oldestPage: number;
11
+ byType: Record<string, number>;
12
+ /**
13
+ * When the ledger last SAW text change.
14
+ *
15
+ * `newestEdit` above is the newest tree-entry `updatedAt`, and that is the
16
+ * blind number this whole ledger exists because of — it moves for a rename
17
+ * or a meta change and never for typing. Reporting it alone as "last edit"
18
+ * would leave the page saying "an hour ago" ten minutes after somebody
19
+ * wrote a paragraph, which is the original bug wearing a new chart. The
20
+ * page takes whichever of the two is more recent.
21
+ *
22
+ * Its resolution is the sweep, so it can lag by up to one interval. That is
23
+ * still far closer to the truth than a number that never moves at all.
24
+ */
25
+ lastActivityAt: number;
26
+ /** Dense, oldest first — one entry per day whether or not anything happened. */
27
+ activity: {
28
+ date: string;
29
+ edits: number;
30
+ words: number;
31
+ }[];
32
+ /**
33
+ * False until the ledger has taken its baseline. The page must say "still
34
+ * measuring" rather than draw thirty empty bars and imply a silent month.
35
+ */
36
+ activityReady: boolean;
10
37
  generatedAt: number;
11
38
  }>>;
12
39
  export default _default;
@@ -1,16 +1,15 @@
1
1
  import { defineCachedEventHandler, useRuntimeConfig, useStorage } from "nitropack/runtime";
2
- import { junDocTree, junRootDocId } from "../utils/junCache.js";
2
+ import { junCountedDocIds, junDocTree, junRootDocId } from "../utils/junCache.js";
3
+ import { junReadActivity } from "../utils/junActivity.js";
4
+ import { junActivitySeries, junCountWords } from "../utils/junActivityMath.js";
3
5
  export default defineCachedEventHandler(async () => {
4
6
  const jun = useRuntimeConfig().public.jun;
5
7
  const types = jun?.typeIds ?? {};
6
8
  const rootDocId = junRootDocId();
7
9
  const tree = await junDocTree();
10
+ const countedIds = junCountedDocIds(tree, rootDocId);
8
11
  const counted = {};
9
- for (const [id, entry] of Object.entries(tree)) {
10
- if (!entry || entry.trashed || id === rootDocId) continue;
11
- if (entry.meta?.seedTest === true || entry.meta?.draft === true) continue;
12
- counted[id] = entry;
13
- }
12
+ for (const id of countedIds) counted[id] = tree[id];
14
13
  let pages = 0;
15
14
  let journalEntries = 0;
16
15
  let livePosts = 0;
@@ -18,10 +17,13 @@ export default defineCachedEventHandler(async () => {
18
17
  let signatures = 0;
19
18
  let appreciations = 0;
20
19
  let newestEdit = 0;
20
+ let oldestPage = 0;
21
+ const byType = {};
21
22
  for (const entry of Object.values(counted)) {
22
23
  pages++;
23
24
  if (types.entry && entry.type === types.entry) journalEntries++;
24
25
  if (types.now && entry.type === types.now) livePosts++;
26
+ if (entry.type) byType[entry.type] = (byType[entry.type] ?? 0) + 1;
25
27
  const parent = entry.parentId ? counted[entry.parentId] ?? tree[entry.parentId] : void 0;
26
28
  if (types.wall && parent?.type === types.wall && entry.meta?.coverUploadId) photos++;
27
29
  if (types.guestbook && parent?.type === types.guestbook && typeof entry.meta?.message === "string") {
@@ -30,6 +32,8 @@ export default defineCachedEventHandler(async () => {
30
32
  if (Array.isArray(entry.meta?.appreciatedBy)) appreciations += entry.meta.appreciatedBy.length;
31
33
  const updated = typeof entry.updatedAt === "number" ? entry.updatedAt : 0;
32
34
  if (updated > newestEdit) newestEdit = updated;
35
+ const created = typeof entry.createdAt === "number" ? entry.createdAt : 0;
36
+ if (created > 0 && (oldestPage === 0 || created < oldestPage)) oldestPage = created;
33
37
  }
34
38
  let words = 0;
35
39
  const storage = useStorage();
@@ -39,9 +43,9 @@ export default defineCachedEventHandler(async () => {
39
43
  if (!counted[docId]) continue;
40
44
  const html = await storage.getItem(key);
41
45
  if (typeof html !== "string" || !html) continue;
42
- const text = html.replace(/<[^>]*>/g, " ").replace(/&[a-z#0-9]+;/gi, " ");
43
- words += text.split(/\s+/).filter(Boolean).length;
46
+ words += junCountWords(html);
44
47
  }
48
+ const ledger = await junReadActivity();
45
49
  return {
46
50
  pages,
47
51
  journalEntries,
@@ -51,6 +55,29 @@ export default defineCachedEventHandler(async () => {
51
55
  appreciations,
52
56
  words,
53
57
  newestEdit,
58
+ oldestPage,
59
+ byType,
60
+ /**
61
+ * When the ledger last SAW text change.
62
+ *
63
+ * `newestEdit` above is the newest tree-entry `updatedAt`, and that is the
64
+ * blind number this whole ledger exists because of — it moves for a rename
65
+ * or a meta change and never for typing. Reporting it alone as "last edit"
66
+ * would leave the page saying "an hour ago" ten minutes after somebody
67
+ * wrote a paragraph, which is the original bug wearing a new chart. The
68
+ * page takes whichever of the two is more recent.
69
+ *
70
+ * Its resolution is the sweep, so it can lag by up to one interval. That is
71
+ * still far closer to the truth than a number that never moves at all.
72
+ */
73
+ lastActivityAt: ledger.lastChangeAt,
74
+ /** Dense, oldest first — one entry per day whether or not anything happened. */
75
+ activity: junActivitySeries(ledger, 30),
76
+ /**
77
+ * False until the ledger has taken its baseline. The page must say "still
78
+ * measuring" rather than draw thirty empty bars and imply a silent month.
79
+ */
80
+ activityReady: ledger.seeded,
54
81
  generatedAt: Date.now()
55
82
  };
56
83
  }, { name: "jun-stats", maxAge: 60, swr: true });
@@ -336,15 +336,41 @@ function defaultTree(typeIds) {
336
336
  ]
337
337
  });
338
338
  }
339
- if (typeIds.window) {
339
+ if (typeIds.globe) {
340
340
  nodes.push({
341
- label: "Console",
342
- type: typeIds.window,
343
- icon: "i-lucide-app-window",
344
- meta: {
345
- excerpt: "A pretend app, genuinely multiplayer. Open it in two tabs.",
346
- windowUrl: "example.com/console"
347
- }
341
+ label: "Journey",
342
+ type: typeIds.globe,
343
+ icon: "i-lucide-globe-2",
344
+ meta: { excerpt: "A journey, drawn on a real map. Click a leg to frame both ends." },
345
+ children: [
346
+ {
347
+ label: "Reykjav\xEDk",
348
+ type: "doc",
349
+ meta: { date: "2025-03-02", geoLat: 64.1466, geoLng: -21.9426, icon: "snowflake" }
350
+ },
351
+ {
352
+ label: "Lisbon",
353
+ type: "doc",
354
+ meta: {
355
+ date: "2025-05-19",
356
+ geoLat: 38.7223,
357
+ geoLng: -9.1393,
358
+ transport: "plane",
359
+ icon: "plane"
360
+ }
361
+ },
362
+ {
363
+ label: "Kyoto",
364
+ type: "doc",
365
+ meta: {
366
+ date: "2025-10-11",
367
+ geoLat: 35.0116,
368
+ geoLng: 135.7681,
369
+ transport: "plane",
370
+ icon: "torii-gate"
371
+ }
372
+ }
373
+ ]
348
374
  });
349
375
  }
350
376
  if (typeIds.mosaic) {
@@ -512,14 +538,16 @@ async function bootstrap(ctx, seed) {
512
538
  shared.observe(check);
513
539
  });
514
540
  const flat = [];
515
- const collect = (n) => {
541
+ const parentOf = /* @__PURE__ */ new Map();
542
+ const collect = (n, parentId) => {
516
543
  flat.push(n);
517
- n.children.forEach(collect);
544
+ parentOf.set(n.id, parentId);
545
+ n.children.forEach((c) => collect(c, n.id));
518
546
  };
519
- plan.forEach(collect);
547
+ plan.forEach((n) => collect(n, rootId));
520
548
  for (const node of flat) {
521
549
  try {
522
- await ctx.client.createChild(rootId, {
550
+ await ctx.client.createChild(parentOf.get(node.id) ?? rootId, {
523
551
  child_id: node.id,
524
552
  label: node.label,
525
553
  // The REAL page type. Server-side listings, the admin TUI and every
@@ -2,10 +2,15 @@ import * as Y from "yjs";
2
2
  import { AbracadabraProvider } from "@abraca/dabra";
3
3
  import { Node } from "@tiptap/core";
4
4
  import { defineNitroPlugin, useRuntimeConfig } from "nitropack/runtime";
5
+ import { junCountedDocIds } from "../utils/junCache.js";
6
+ import { junReadActivity, junSweepActivity } from "../utils/junActivity.js";
7
+ import { junDayKey } from "../utils/junActivityMath.js";
8
+ import { junCreateRegistrar, junSetRegisterTreeState } from "../utils/junRegisterTree.js";
5
9
  const MAX_DOCS = 300;
6
10
  const CONCURRENCY = 6;
7
11
  const SYNC_TIMEOUT_MS = 8e3;
8
12
  const REFRESH_INTERVAL_MS = 12e4;
13
+ const BASELINE_DELAY_MS = 3e4;
9
14
  const DocumentHeaderStub = Node.create({
10
15
  name: "documentHeader",
11
16
  group: "block",
@@ -114,11 +119,46 @@ export default defineNitroPlugin((nitroApp) => {
114
119
  unobserveDoc(docId);
115
120
  }
116
121
  treeMap.forEach((_v, docId) => track(docId));
117
- const sweep = setInterval(() => {
118
- for (const [docId, ydoc] of docs) {
119
- void limit(() => renderDoc(docId, ydoc)).catch(() => {
122
+ junSetRegisterTreeState(junCreateRegistrar({
123
+ rootId: entryDocId,
124
+ eachEntry: (fn) => treeMap.forEach(
125
+ (entry, id) => fn(entry, id)
126
+ ),
127
+ createChild: (parent, body) => client.createChild(parent, body)
128
+ }));
129
+ const baseline = setTimeout(() => void bookActivity(), BASELINE_DELAY_MS);
130
+ timers.add(baseline);
131
+ console.log(
132
+ `[jun:doc-cache] tracking ${docs.size} document(s); activity baseline in ${BASELINE_DELAY_MS / 1e3}s`
133
+ );
134
+ async function bookActivity() {
135
+ try {
136
+ const tree = {};
137
+ treeMap.forEach((entry, id) => {
138
+ tree[id] = entry;
120
139
  });
140
+ const counted = junCountedDocIds(tree, entryDocId);
141
+ const before = await junReadActivity();
142
+ const after = await junSweepActivity(counted);
143
+ const today = junDayKey(Date.now());
144
+ const booked = (after.days[today]?.edits ?? 0) - (before.days[today]?.edits ?? 0);
145
+ if (!before.seeded) {
146
+ console.log(
147
+ `[jun:doc-cache] activity baseline: ${Object.keys(after.docs).length} documents`
148
+ );
149
+ } else if (booked > 0) {
150
+ console.log(`[jun:doc-cache] activity: ${booked} document(s) changed`);
151
+ }
152
+ } catch (e) {
153
+ console.warn("[jun:doc-cache] activity sweep failed:", e);
121
154
  }
155
+ }
156
+ const sweep = setInterval(() => {
157
+ const renders = [...docs].map(
158
+ ([docId, ydoc]) => limit(() => renderDoc(docId, ydoc)).catch(() => {
159
+ })
160
+ );
161
+ void Promise.all(renders).then(bookActivity);
122
162
  }, REFRESH_INTERVAL_MS);
123
163
  const observer = (event) => {
124
164
  event.keysChanged.forEach((docId) => {
@@ -129,6 +169,7 @@ export default defineNitroPlugin((nitroApp) => {
129
169
  };
130
170
  treeMap.observe(observer);
131
171
  return () => {
172
+ junSetRegisterTreeState(null);
132
173
  clearInterval(sweep);
133
174
  treeMap.unobserve(observer);
134
175
  for (const t of timers) clearTimeout(t);
@@ -0,0 +1,16 @@
1
+ /**
2
+ * ONE result shape for every path. Nitro infers the task's result type from
3
+ * what `run` returns, so a bail-out returning `{ ok, message }` and a success
4
+ * returning the counts are two different types and neither typechecks.
5
+ */
6
+ interface JunRegisterTreeResult {
7
+ ok: boolean;
8
+ message: string;
9
+ dryRun: boolean;
10
+ total: number;
11
+ accepted: number;
12
+ alreadyPresent: number;
13
+ failed: number;
14
+ }
15
+ declare const _default: import("nitropack").Task<JunRegisterTreeResult>;
16
+ export default _default;
@@ -0,0 +1,22 @@
1
+ import { defineTask } from "nitropack/runtime";
2
+ import { junRegisterTreeState } from "../utils/junRegisterTree.js";
3
+ export default defineTask({
4
+ meta: {
5
+ name: "jun:register-tree",
6
+ description: "REST-register yjs-only tree documents so the permission cascade can see them"
7
+ },
8
+ async run({ payload }) {
9
+ const empty = { dryRun: false, total: 0, accepted: 0, alreadyPresent: 0, failed: 0 };
10
+ const state = junRegisterTreeState();
11
+ if (!state) {
12
+ const message2 = "jun:register-tree needs the jun:doc-cache runner, which has not started. It carries the service-role client and the synced root document.";
13
+ console.warn(`[jun:register-tree] ${message2}`);
14
+ return { result: { ok: false, message: message2, ...empty } };
15
+ }
16
+ const dryRun = payload?.dryRun === true;
17
+ const report = await state.registerAll({ dryRun });
18
+ const message = dryRun ? `${report.total} document(s) would be sent` : `${report.total} document(s): ${report.accepted} accepted, ${report.alreadyPresent} already present` + (report.failed ? `, ${report.failed} FAILED` : "");
19
+ console.log(`[jun:register-tree] ${message}`);
20
+ return { result: { ok: true, message, dryRun, ...report } };
21
+ }
22
+ });
@@ -0,0 +1,15 @@
1
+ import { type JunActivityLedger } from './junActivityMath.js';
2
+ export declare function junReadActivity(): Promise<JunActivityLedger>;
3
+ /**
4
+ * Diff every cached body against the ledger and book what changed.
5
+ *
6
+ * Called by the doc-cache runner after a refresh sweep, never per request: a
7
+ * request-time walk would only ever see activity while somebody happened to be
8
+ * looking at the Pulse page, which is the opposite of what it is measuring.
9
+ *
10
+ * `counted` is the set of document ids the site actually counts — the same
11
+ * exclusions `stats.get` applies, from the same `junCountedDocIds`. Passing it
12
+ * in keeps the visibility rule in ONE place rather than growing a second copy
13
+ * here.
14
+ */
15
+ export declare function junSweepActivity(counted: Set<string>): Promise<JunActivityLedger>;
@@ -0,0 +1,71 @@
1
+ import { useStorage } from "nitropack/runtime";
2
+ import {
3
+ junCountWords,
4
+ junDayKey,
5
+ junHashText,
6
+ junPruneDays
7
+ } from "./junActivityMath.js";
8
+ const RETAIN_DAYS = 60;
9
+ const STORAGE_KEY = "activity";
10
+ function store() {
11
+ return useStorage("jun");
12
+ }
13
+ export async function junReadActivity() {
14
+ const raw = await store().getItem(STORAGE_KEY);
15
+ if (!raw || typeof raw !== "object") {
16
+ return { docs: {}, days: {}, seeded: false, updatedAt: 0, lastChangeAt: 0 };
17
+ }
18
+ return {
19
+ docs: raw.docs ?? {},
20
+ days: raw.days ?? {},
21
+ seeded: raw.seeded === true,
22
+ updatedAt: raw.updatedAt ?? 0,
23
+ lastChangeAt: raw.lastChangeAt ?? 0
24
+ };
25
+ }
26
+ export async function junSweepActivity(counted) {
27
+ const storage = useStorage();
28
+ const ledger = await junReadActivity();
29
+ const now = Date.now();
30
+ const today = junDayKey(now);
31
+ const seen = {};
32
+ let changed = 0;
33
+ let wordDelta = 0;
34
+ const keys = await storage.getKeys("doc-cache:html");
35
+ for (const key of keys) {
36
+ const docId = key.slice(key.lastIndexOf(":") + 1);
37
+ if (!counted.has(docId)) continue;
38
+ const html = await storage.getItem(key);
39
+ if (typeof html !== "string") continue;
40
+ const words = junCountWords(html);
41
+ const hash = junHashText(html);
42
+ seen[docId] = [words, hash];
43
+ const before = ledger.docs[docId];
44
+ if (!before) {
45
+ if (ledger.seeded) {
46
+ changed++;
47
+ wordDelta += words;
48
+ }
49
+ continue;
50
+ }
51
+ if (before[1] !== hash) {
52
+ changed++;
53
+ wordDelta += words - before[0];
54
+ }
55
+ }
56
+ const days = junPruneDays(ledger.days, RETAIN_DAYS, now);
57
+ const booked = ledger.seeded && changed > 0;
58
+ if (booked) {
59
+ const bucket = days[today] ?? { edits: 0, words: 0 };
60
+ days[today] = { edits: bucket.edits + changed, words: bucket.words + wordDelta };
61
+ }
62
+ const next = {
63
+ docs: seen,
64
+ days,
65
+ seeded: true,
66
+ updatedAt: now,
67
+ lastChangeAt: booked ? now : ledger.lastChangeAt
68
+ };
69
+ await store().setItem(STORAGE_KEY, next);
70
+ return next;
71
+ }
@@ -0,0 +1,61 @@
1
+ /**
2
+ * The activity ledger's PURE half — day keys, word counting, and the dense
3
+ * series the Pulse page's chart is drawn from.
4
+ *
5
+ * It is a separate file from `junActivity.ts` for one reason: that file imports
6
+ * `useStorage` from `nitropack/runtime`, whose own entry pulls
7
+ * `#nitro-internal-virtual/*` — imports that exist only inside a built Nitro
8
+ * app. Nothing outside a Nitro build can load it, and that includes the test
9
+ * runner. Marking it external does not help: the import then survives and Node
10
+ * fails to resolve it at runtime instead of at bundle time.
11
+ *
12
+ * So the arithmetic lives where it can be tested, and the storage lives where
13
+ * it belongs. That split is worth keeping on its own merits — none of this
14
+ * needs to know that a ledger is persisted at all.
15
+ */
16
+ /** One day's activity. `words` is a NET delta and may be negative. */
17
+ export interface JunActivityDay {
18
+ edits: number;
19
+ words: number;
20
+ }
21
+ export interface JunActivityLedger {
22
+ /** docId → [word count, text hash] as of the last sweep. */
23
+ docs: Record<string, [number, string]>;
24
+ /** `YYYY-MM-DD` (UTC) → bucket. Pruned to the retention window. */
25
+ days: Record<string, JunActivityDay>;
26
+ /** False until the baseline pass has run. */
27
+ seeded: boolean;
28
+ /** When the last sweep RAN. Bumped every time, change or no change. */
29
+ updatedAt: number;
30
+ /**
31
+ * When a sweep last SAW text change — which is a different question, and the
32
+ * one "last edit" wants. `updatedAt` moves every two minutes forever, so
33
+ * using it would report a site as continuously active while nobody touched
34
+ * it: the same class of wrong number as the tree's `updatedAt`, which is what
35
+ * this ledger exists to replace.
36
+ */
37
+ lastChangeAt: number;
38
+ }
39
+ export declare const JUN_DAY_MS = 86400000;
40
+ /** UTC, so a container's timezone cannot shift which day an edit lands on. */
41
+ export declare function junDayKey(ts: number): string;
42
+ /**
43
+ * Words in a cached HTML body. Shared with `stats.get` deliberately — two
44
+ * definitions of "a word" would make the total and the trend disagree, and the
45
+ * page shows them side by side.
46
+ */
47
+ export declare function junCountWords(html: string): number;
48
+ /** FNV-1a. Not a checksum — just enough to answer "is this the same text?". */
49
+ export declare function junHashText(html: string): string;
50
+ /**
51
+ * A DENSE series, oldest first — one entry per day whether or not anything
52
+ * happened. The chart needs every bar to exist; a sparse map would silently
53
+ * compress quiet weeks and misdate every bar after them.
54
+ */
55
+ export declare function junActivitySeries(ledger: JunActivityLedger, days?: number, now?: number): {
56
+ date: string;
57
+ edits: number;
58
+ words: number;
59
+ }[];
60
+ /** Drop day buckets older than the retention window. Keys sort lexically. */
61
+ export declare function junPruneDays(days: Record<string, JunActivityDay>, retainDays: number, now: number): Record<string, JunActivityDay>;
@@ -0,0 +1,31 @@
1
+ export const JUN_DAY_MS = 864e5;
2
+ export function junDayKey(ts) {
3
+ return new Date(ts).toISOString().slice(0, 10);
4
+ }
5
+ export function junCountWords(html) {
6
+ const text = html.replace(/<[^>]*>/g, " ").replace(/&[a-z#0-9]+;/gi, " ");
7
+ return text.split(/\s+/).filter(Boolean).length;
8
+ }
9
+ export function junHashText(html) {
10
+ let h = 2166136261;
11
+ for (let i = 0; i < html.length; i++) {
12
+ h ^= html.charCodeAt(i);
13
+ h = Math.imul(h, 16777619);
14
+ }
15
+ return (h >>> 0).toString(36);
16
+ }
17
+ export function junActivitySeries(ledger, days = 30, now = Date.now()) {
18
+ const out = [];
19
+ for (let i = days - 1; i >= 0; i--) {
20
+ const date = junDayKey(now - i * JUN_DAY_MS);
21
+ const bucket = ledger.days[date];
22
+ out.push({ date, edits: bucket?.edits ?? 0, words: bucket?.words ?? 0 });
23
+ }
24
+ return out;
25
+ }
26
+ export function junPruneDays(days, retainDays, now) {
27
+ const floor = junDayKey(now - retainDays * JUN_DAY_MS);
28
+ const out = {};
29
+ for (const [k, v] of Object.entries(days)) if (k >= floor) out[k] = v;
30
+ return out;
31
+ }
@@ -18,6 +18,21 @@ export interface JunTreeEntry {
18
18
  export declare function junRootDocId(): string;
19
19
  /** The root document's `doc-tree` map, or `{}` before the cache is warm. */
20
20
  export declare function junDocTree(): Promise<Record<string, JunTreeEntry>>;
21
+ /**
22
+ * The set of document ids the site COUNTS — pages, in the sense the Pulse page
23
+ * means it.
24
+ *
25
+ * Excluded: trashed documents, drafts, seed-test pages, and the root's
26
+ * self-descriptor entry (its id IS the space id, so counting it adds a phantom
27
+ * page to every total). Hidden documents COUNT — they are real pages, and
28
+ * `meta.hidden` means "not in navigation", not "not there".
29
+ *
30
+ * It lives here because two places need exactly this rule and a drift between
31
+ * them is invisible: `stats.get` totals it, and the doc-cache runner books
32
+ * activity against it. Two copies would mean the ledger and the tiles quietly
33
+ * disagreeing about what a page is.
34
+ */
35
+ export declare function junCountedDocIds(tree: Record<string, JunTreeEntry>, rootDocId: string): Set<string>;
21
36
  /** Document id → canonical slug, as persisted by the doc-tree-cache runner. */
22
37
  export declare function junSlugMap(): Promise<Record<string, string>>;
23
38
  /** A document's cached HTML body, or `null` if it has not been rendered yet. */
@@ -11,6 +11,15 @@ export async function junDocTree() {
11
11
  );
12
12
  return json?.["doc-tree"] ?? {};
13
13
  }
14
+ export function junCountedDocIds(tree, rootDocId) {
15
+ const out = /* @__PURE__ */ new Set();
16
+ for (const [id, entry] of Object.entries(tree)) {
17
+ if (!entry || entry.trashed || id === rootDocId) continue;
18
+ if (entry.meta?.seedTest === true || entry.meta?.draft === true) continue;
19
+ out.add(id);
20
+ }
21
+ return out;
22
+ }
14
23
  export async function junSlugMap() {
15
24
  const map = await useStorage().getItem(
16
25
  "doc-cache:slug-map"
@@ -0,0 +1,59 @@
1
+ /**
2
+ * The tree-registration walk, and the handle the doc-cache runner publishes so
3
+ * a Nitro task can reach it.
4
+ *
5
+ * A Nitro task is invoked from outside any runner, but the work here needs two
6
+ * things only the runner has: a **service-role client** and an **already-synced
7
+ * root document**. Rather than opening a second identity and a second socket —
8
+ * which is what the standalone script this replaces had to do — the runner
9
+ * parks a handle in module scope and the task picks it up.
10
+ *
11
+ * Module scope is the right lifetime for it: one Nitro process, one runner, and
12
+ * the handle dies with the process. It is cleared on the runner's teardown so a
13
+ * task firing after a hot reload gets a clear "the runner has not started"
14
+ * rather than a client pointing at a dead socket.
15
+ */
16
+ /**
17
+ * What a run did — and the names matter, because the obvious ones lie.
18
+ *
19
+ * `accepted` is **calls the server took**, not documents newly created. The
20
+ * server's `register_subdoc` treats a re-registration as a no-op, so running
21
+ * the task twice reports the SAME figures rather than converging on zero. That
22
+ * looks like a bug and is not one: the task is idempotent, and there is no
23
+ * endpoint that distinguishes "created a row" from "there was already one".
24
+ * Calling this field `registered` invited exactly that misreading.
25
+ */
26
+ export interface JunRegisterReport {
27
+ total: number;
28
+ accepted: number;
29
+ /** Answered 409 — a row already exists and the server declined to touch it. */
30
+ alreadyPresent: number;
31
+ failed: number;
32
+ }
33
+ export interface JunTreeRegistrar {
34
+ registerAll(opts?: {
35
+ dryRun?: boolean;
36
+ }): Promise<JunRegisterReport>;
37
+ }
38
+ export declare function junSetRegisterTreeState(state: JunTreeRegistrar | null): void;
39
+ export declare function junRegisterTreeState(): JunTreeRegistrar | null;
40
+ interface RegistrarDeps {
41
+ rootId: string;
42
+ /** The root document's `doc-tree` map, read through `forEach`. */
43
+ eachEntry: (fn: (entry: Record<string, unknown>, id: string) => void) => void;
44
+ createChild: (parent: string, body: Record<string, unknown>) => Promise<unknown>;
45
+ }
46
+ /**
47
+ * Walk the live tree and register every document under its real parent.
48
+ *
49
+ * **Breadth-first from the root**, so a parent's row always exists before a
50
+ * child names it — the cascade follows `documents.parent_id`, and a child
51
+ * registered against a parent that has no row yet lands wrong or fails.
52
+ *
53
+ * Orphans — an entry whose parent is missing from the tree, or a cycle — are
54
+ * registered directly under the root. That is not their true place, but it does
55
+ * reach the space, and a document nobody can read is a worse outcome than one
56
+ * whose ancestry is approximate.
57
+ */
58
+ export declare function junCreateRegistrar(deps: RegistrarDeps): JunTreeRegistrar;
59
+ export {};
@@ -0,0 +1,76 @@
1
+ let current = null;
2
+ export function junSetRegisterTreeState(state) {
3
+ current = state;
4
+ }
5
+ export function junRegisterTreeState() {
6
+ return current;
7
+ }
8
+ export function junCreateRegistrar(deps) {
9
+ return {
10
+ async registerAll({ dryRun = false } = {}) {
11
+ const { rootId } = deps;
12
+ const entries = /* @__PURE__ */ new Map();
13
+ deps.eachEntry((raw, id) => {
14
+ const e = typeof raw?.toJSON === "function" ? raw.toJSON() : raw;
15
+ if (!e || e.trashed === true) return;
16
+ if (id === rootId) return;
17
+ entries.set(id, {
18
+ label: e.label || "Untitled",
19
+ // A legacy top-level entry uses `parentId: null`; both mean the root.
20
+ parentId: e.parentId ?? rootId,
21
+ type: e.type
22
+ });
23
+ });
24
+ const byParent = /* @__PURE__ */ new Map();
25
+ for (const [id, e] of entries) {
26
+ const list = byParent.get(e.parentId) ?? [];
27
+ list.push(id);
28
+ byParent.set(e.parentId, list);
29
+ }
30
+ const order = [];
31
+ const seen = /* @__PURE__ */ new Set([rootId]);
32
+ const queue = [rootId];
33
+ while (queue.length) {
34
+ const pid = queue.shift();
35
+ for (const id of byParent.get(pid) ?? []) {
36
+ if (seen.has(id)) continue;
37
+ seen.add(id);
38
+ order.push(id);
39
+ queue.push(id);
40
+ }
41
+ }
42
+ for (const id of entries.keys()) {
43
+ if (seen.has(id)) continue;
44
+ entries.get(id).parentId = rootId;
45
+ order.push(id);
46
+ }
47
+ const report = {
48
+ total: order.length,
49
+ accepted: 0,
50
+ alreadyPresent: 0,
51
+ failed: 0
52
+ };
53
+ if (dryRun) return report;
54
+ for (const id of order) {
55
+ const e = entries.get(id);
56
+ try {
57
+ await deps.createChild(e.parentId, {
58
+ child_id: id,
59
+ label: e.label,
60
+ doc_type: e.type
61
+ });
62
+ report.accepted++;
63
+ } catch (err) {
64
+ const msg = err?.message ?? String(err);
65
+ if (/409|already exists|conflict/i.test(msg)) {
66
+ report.alreadyPresent++;
67
+ continue;
68
+ }
69
+ report.failed++;
70
+ console.warn(`[jun:register-tree] ${id} ("${e.label}"): ${msg}`);
71
+ }
72
+ }
73
+ return report;
74
+ }
75
+ };
76
+ }
@@ -251,7 +251,7 @@ const RSS = async (ref) => {
251
251
  const HTTP = async (ref) => {
252
252
  const started = Date.now();
253
253
  let status = 0;
254
- let ms = 0;
254
+ let ms;
255
255
  try {
256
256
  const res = await safeFetch(ref, { accept: "text/html,*/*" });
257
257
  status = res.status;