@bitcobblers/wod-wiki-engine 0.51.2196 → 0.52.2198

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.
package/dist/index.cjs CHANGED
@@ -66,7 +66,7 @@ function inMemoryEventStore(events) {
66
66
  getEventsByTimeRange: async (start, end) => rows.filter((r) => r.timestamp >= start && r.timestamp <= end),
67
67
  getEventsByResult: async (resultId) => rows.filter((r) => r.resultId === resultId),
68
68
  getEventsForNote: async (noteId) => rows.filter((r) => r.noteId === noteId),
69
- getEventsByContent: async (blockContentId2) => rows.filter((r) => r.blockContentId === blockContentId2),
69
+ getEventsByContent: async (blockContentId5) => rows.filter((r) => r.blockContentId === blockContentId5),
70
70
  scanAll: async () => rows,
71
71
  appendEvents: async (appended) => {
72
72
  rows.push(...appended);
@@ -154,33 +154,87 @@ function buildStatementTree(script) {
154
154
  };
155
155
  }
156
156
  var NOTE_ID_FRONTMATTER_KEY = "wod-note-id";
157
- var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
157
+ var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
158
+ var NOTEBOOK_LANDING_ID_RE = /^notebook\/[a-z0-9][a-z0-9._-]*$/i;
159
+ function unquoteYamlScalar(raw) {
160
+ const trimmed = raw.trim();
161
+ if (trimmed.startsWith('"') && trimmed.endsWith('"') || trimmed.startsWith("'") && trimmed.endsWith("'")) {
162
+ try {
163
+ if (trimmed.startsWith('"')) return JSON.parse(trimmed);
164
+ } catch {
165
+ }
166
+ return trimmed.slice(1, -1);
167
+ }
168
+ return trimmed;
169
+ }
158
170
  function extractNoteIdentity(markdown) {
159
171
  const block = /^---\r?\n([\s\S]*?)\r?\n---/.exec(markdown);
160
172
  if (!block) return void 0;
161
173
  let noteId;
162
174
  let title;
175
+ let date;
176
+ let notebook;
177
+ let isPublic;
163
178
  for (const line of block[1].split(/\r?\n/)) {
164
179
  const kv = line.match(/^([^:]+):\s*(.*)$/);
165
180
  if (!kv) continue;
166
181
  const key = kv[1].trim();
167
- const value = kv[2].trim();
168
- if (key === NOTE_ID_FRONTMATTER_KEY && UUID_RE.test(value)) noteId = value;
182
+ const value = unquoteYamlScalar(kv[2]);
183
+ if (key === NOTE_ID_FRONTMATTER_KEY && (UUID_RE.test(value) || NOTEBOOK_LANDING_ID_RE.test(value))) {
184
+ noteId = value;
185
+ }
169
186
  if (key === "title" && value) title = value;
187
+ if (key === "date" && value) date = value;
188
+ if (key === "notebook" && value) notebook = value;
189
+ if (key === "public" && (value === "true" || value === "false")) isPublic = value === "true";
170
190
  }
171
- return noteId ? { noteId, title } : void 0;
191
+ if (!noteId) return void 0;
192
+ return {
193
+ noteId,
194
+ ...title !== void 0 ? { title } : {},
195
+ ...date !== void 0 ? { date } : {},
196
+ ...notebook !== void 0 ? { notebook } : {},
197
+ ...isPublic !== void 0 ? { public: isPublic } : {}
198
+ };
172
199
  }
173
200
  var FRONTMATTER_SAFE = /^[^:#\[\]{}'"*&,!?|>%@`\s][^:#\[\]{}"']*$/;
201
+ function formatFrontmatterScalar(value) {
202
+ if (FRONTMATTER_SAFE.test(value)) return value;
203
+ if (!value.includes("\n") && !value.includes("\r")) return JSON.stringify(value);
204
+ return void 0;
205
+ }
206
+ function parseFrontmatterDateMs(raw) {
207
+ if (!raw) return void 0;
208
+ const clean = unquoteYamlScalar(raw);
209
+ const ymd = clean.match(/^(\d{4})-(\d{2})-(\d{2})$/);
210
+ if (ymd) {
211
+ const ts = Date.parse(`${clean}T12:00:00Z`);
212
+ const d = new Date(ts);
213
+ if (Number.isFinite(ts) && d.getUTCMonth() === Number(ymd[2]) - 1 && d.getUTCDate() === Number(ymd[3])) {
214
+ return ts;
215
+ }
216
+ return void 0;
217
+ }
218
+ const parsed = Date.parse(clean);
219
+ return Number.isFinite(parsed) ? parsed : void 0;
220
+ }
174
221
  function injectIdentityFrontmatter(markdown, identity) {
175
222
  const stamp = (lines2) => {
176
223
  const replaceOrInsert = (key, value) => {
177
- if (value === void 0 || !FRONTMATTER_SAFE.test(value)) return;
224
+ if (value === void 0) return;
225
+ const formatted = formatFrontmatterScalar(value);
226
+ if (formatted === void 0) return;
178
227
  const idx = lines2.findIndex((l) => l.startsWith(`${key}:`));
179
- if (idx >= 0) lines2[idx] = `${key}: ${value}`;
180
- else lines2.push(`${key}: ${value}`);
228
+ if (idx >= 0) lines2[idx] = `${key}: ${formatted}`;
229
+ else lines2.push(`${key}: ${formatted}`);
181
230
  };
182
231
  replaceOrInsert("title", identity.title);
183
232
  replaceOrInsert(NOTE_ID_FRONTMATTER_KEY, identity.noteId);
233
+ replaceOrInsert("date", identity.date);
234
+ replaceOrInsert("notebook", identity.notebook);
235
+ if (identity.public !== void 0) {
236
+ replaceOrInsert("public", identity.public ? "true" : "false");
237
+ }
184
238
  return lines2;
185
239
  };
186
240
  const block = /^---\r?\n([\s\S]*?)\r?\n---/.exec(markdown);
@@ -197,7 +251,67 @@ ${lines.join("\n")}
197
251
  ${markdown}`;
198
252
  }
199
253
  function composeNoteMarkdown(note) {
200
- return injectIdentityFrontmatter(note.rawContent, { noteId: note.id, title: note.title });
254
+ const notebookSlug = note.notebookId ? wodWikiWql.notebookSlugFromId(note.notebookId) : void 0;
255
+ const dateStr = typeof note.date === "number" && Number.isFinite(note.date) ? new Date(note.date).toISOString().slice(0, 10) : void 0;
256
+ return injectIdentityFrontmatter(note.rawContent, {
257
+ noteId: note.id,
258
+ title: note.title,
259
+ ...dateStr ? { date: dateStr } : {},
260
+ ...notebookSlug ? { notebook: notebookSlug } : {},
261
+ ...note.public === true ? { public: true } : {}
262
+ });
263
+ }
264
+ function parseNoteMarkdown(markdown, options = {}) {
265
+ const identity = extractNoteIdentity(markdown);
266
+ const meta = readFrontmatterMeta(markdown);
267
+ const typedTags = extractTypedTags(markdown);
268
+ let rawContent = markdown;
269
+ const fmMatch = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n)?(?:\r?\n)?/.exec(markdown);
270
+ if (fmMatch) {
271
+ const fmLines = fmMatch[1].split(/\r?\n/);
272
+ const nonIdentityLines = fmLines.filter((line) => {
273
+ const kv = line.match(/^([^:]+):/);
274
+ if (!kv) return true;
275
+ const k = kv[1].trim().toLowerCase();
276
+ return k !== NOTE_ID_FRONTMATTER_KEY;
277
+ });
278
+ const onlyTitleLeft = nonIdentityLines.length === 1 && nonIdentityLines[0].trim().toLowerCase().startsWith("title:");
279
+ const body = markdown.slice(fmMatch[0].length);
280
+ if (nonIdentityLines.length === 0 || onlyTitleLeft && /^#\s+.+/m.test(body)) {
281
+ rawContent = body;
282
+ } else if (nonIdentityLines.length !== fmLines.length) {
283
+ const nl = markdown.startsWith("---\r\n") ? "\r\n" : "\n";
284
+ const rest = markdown.slice(
285
+ /^---\r?\n[\s\S]*?\r?\n---/.exec(markdown)?.[0].length ?? fmMatch[0].length
286
+ );
287
+ rawContent = `---${nl}${nonIdentityLines.join(nl)}${nl}---${rest}`;
288
+ }
289
+ }
290
+ const headingMatch = rawContent.match(/^#\s+(.+)$/m) ?? markdown.match(/^#\s+(.+)$/m);
291
+ const metaTitle = typeof meta["title"] === "string" ? unquoteYamlScalar(meta["title"]) : void 0;
292
+ const title = identity?.title ?? metaTitle ?? (headingMatch ? headingMatch[1].trim() : void 0) ?? options.fallbackTitle ?? "Imported Note";
293
+ const rawDate = identity?.date ?? (typeof meta["date"] === "string" ? meta["date"] : void 0);
294
+ const date = parseFrontmatterDateMs(rawDate) ?? options.defaultDate;
295
+ const rawNotebook = identity?.notebook ?? (typeof meta["notebook"] === "string" ? unquoteYamlScalar(meta["notebook"]) : void 0);
296
+ const notebookId = rawNotebook ? wodWikiWql.toNotebookId(rawNotebook) : void 0;
297
+ const rawPublic = meta["public"];
298
+ const isPublic = identity?.public ?? (typeof rawPublic === "string" && (rawPublic === "true" || rawPublic === "false") ? rawPublic === "true" : void 0);
299
+ const sourceRevision = options.sourceRevision ?? 1;
300
+ const blocks = wodWikiCore.reconcileNoteBlocks(rawContent, {
301
+ sourceRevision,
302
+ registeredWidgets: wodWikiCore.KNOWN_SECTION_WIDGETS
303
+ });
304
+ return {
305
+ ...identity?.noteId ? { id: identity.noteId } : {},
306
+ title,
307
+ rawContent,
308
+ ...date !== void 0 ? { date } : {},
309
+ ...notebookId ? { notebookId } : {},
310
+ ...isPublic !== void 0 ? { public: isPublic } : {},
311
+ tags: asList(meta["tags"]),
312
+ typedTags,
313
+ blocks
314
+ };
201
315
  }
202
316
  var FRONTMATTER_BLOCK_RE = /^---\r?\n([\s\S]*?)\r?\n---/;
203
317
  function readFrontmatterMeta(markdown) {
@@ -615,15 +729,224 @@ function csvToSessionRows(csv) {
615
729
  if (!session) throw new Error("[wod import] Session CSV did not contain session columns");
616
730
  return { session, events: [...eventRows.values()] };
617
731
  }
732
+ var TELEMETRY_EXTRA_COLS = [
733
+ "revisionKind",
734
+ "revisionRawContent",
735
+ "revisionSavedAt",
736
+ "revisionDialect",
737
+ "revisionSport",
738
+ "parseId",
739
+ "parseStage",
740
+ "parseStatus",
741
+ "parseDiagnosticsJson",
742
+ "parseMetricsJson"
743
+ ];
744
+ var TELEMETRY_CSV_HEADER = [
745
+ "recordKind",
746
+ ...SESSION_CSV_HEADER,
747
+ ...TELEMETRY_EXTRA_COLS
748
+ ];
749
+ function telemetryBundleToCsv(bundle) {
750
+ const lines = [TELEMETRY_CSV_HEADER.join(",")];
751
+ for (const rev of bundle.revisions ?? []) {
752
+ const sessionCols = new Array(SESSION_HEADER.length).fill("");
753
+ sessionCols[1] = escapeCsvField(rev.noteId);
754
+ sessionCols[2] = escapeCsvField(rev.blockId);
755
+ sessionCols[3] = escapeCsvField(rev.version);
756
+ const eventCols = new Array(EVENT_HEADER.length).fill("");
757
+ const extraCols = [
758
+ escapeCsvField(rev.kind),
759
+ escapeCsvField(rev.rawContent),
760
+ escapeCsvField(rev.savedAt),
761
+ escapeCsvField(rev.dialect ?? ""),
762
+ escapeCsvField(rev.sport ?? ""),
763
+ "",
764
+ "",
765
+ "",
766
+ "",
767
+ ""
768
+ ];
769
+ lines.push(["revision", ...sessionCols, ...eventCols, ...extraCols].join(","));
770
+ }
771
+ for (const p of bundle.parses ?? []) {
772
+ const sessionCols = new Array(SESSION_HEADER.length).fill("");
773
+ sessionCols[1] = escapeCsvField(p.noteId);
774
+ sessionCols[2] = escapeCsvField(p.blockId ?? "");
775
+ sessionCols[3] = escapeCsvField(p.blockVersion ?? "");
776
+ const eventCols = new Array(EVENT_HEADER.length).fill("");
777
+ eventCols[3] = escapeCsvField(p.timestamp);
778
+ const extraCols = [
779
+ "",
780
+ "",
781
+ "",
782
+ "",
783
+ "",
784
+ escapeCsvField(p.id),
785
+ escapeCsvField(p.stage),
786
+ escapeCsvField(p.status),
787
+ escapeCsvField(p.diagnostics ? JSON.stringify(p.diagnostics) : ""),
788
+ escapeCsvField(p.metrics ? JSON.stringify(p.metrics) : "")
789
+ ];
790
+ lines.push(["parse", ...sessionCols, ...eventCols, ...extraCols].join(","));
791
+ }
792
+ const eventsBySession = /* @__PURE__ */ new Map();
793
+ for (const ev of bundle.events) {
794
+ const arr = eventsBySession.get(ev.resultId);
795
+ if (arr) arr.push(ev);
796
+ else eventsBySession.set(ev.resultId, [ev]);
797
+ }
798
+ for (const session of bundle.sessions) {
799
+ const sCells = sessionCells(session);
800
+ const trailingEmpty = new Array(TELEMETRY_EXTRA_COLS.length).fill("");
801
+ lines.push(["session", ...sCells, ...new Array(EVENT_HEADER.length).fill(""), ...trailingEmpty].join(","));
802
+ const ordered = [...eventsBySession.get(session.id) ?? []].sort(
803
+ (a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0
804
+ );
805
+ for (const ev of ordered) {
806
+ const metrics = ev.metrics ?? [];
807
+ if (metrics.length === 0) {
808
+ const emptyMetric = { type: "" };
809
+ lines.push(["event", ...sCells, ...metricCells(ev, emptyMetric, -1), ...trailingEmpty].join(","));
810
+ } else {
811
+ metrics.forEach((m, i) => {
812
+ lines.push(["event", ...sCells, ...metricCells(ev, m, i), ...trailingEmpty].join(","));
813
+ });
814
+ }
815
+ }
816
+ }
817
+ return lines.join("\n") + "\n";
818
+ }
819
+ function csvToTelemetryBundle(csv) {
820
+ const records = splitCsvRecords(csv);
821
+ if (records.length < 2) return { bundles: [], errors: [] };
822
+ const header = parseCsvLine(records[0]);
823
+ if (header[0] !== "recordKind") {
824
+ try {
825
+ const single = csvToSessionRows(csv);
826
+ return {
827
+ bundles: [{ sessions: [single.session], events: single.events }],
828
+ errors: []
829
+ };
830
+ } catch (err) {
831
+ return { bundles: [], errors: [err instanceof Error ? err.message : String(err)] };
832
+ }
833
+ }
834
+ const col = /* @__PURE__ */ new Map();
835
+ header.forEach((name, idx) => col.set(name, idx));
836
+ const at = (cells, name) => {
837
+ const idx = col.get(name);
838
+ return idx === void 0 ? "" : cells[idx] ?? "";
839
+ };
840
+ const revisionsByNote = /* @__PURE__ */ new Map();
841
+ const parsesByNote = /* @__PURE__ */ new Map();
842
+ const sessionCsvLinesBySession = /* @__PURE__ */ new Map();
843
+ const errors = [];
844
+ for (const [idx, line] of records.slice(1).entries()) {
845
+ const cells = parseCsvLine(line);
846
+ if (cells.length === 1 && cells[0] === "") continue;
847
+ const kind = at(cells, "recordKind");
848
+ const noteId = nonempty(at(cells, "noteId"));
849
+ if (!noteId) {
850
+ errors.push(`Row ${idx + 2}: missing noteId`);
851
+ continue;
852
+ }
853
+ if (kind === "revision") {
854
+ const revKind = nonempty(at(cells, "revisionKind"));
855
+ const blockId = nonempty(at(cells, "blockId"));
856
+ const version = num(at(cells, "blockVersion"));
857
+ const savedAt = num(at(cells, "revisionSavedAt"));
858
+ if (!revKind || !blockId || !version || savedAt === void 0) {
859
+ errors.push(`Row ${idx + 2}: invalid revision columns`);
860
+ continue;
861
+ }
862
+ const rev = {
863
+ noteId,
864
+ blockId,
865
+ version,
866
+ kind: revKind,
867
+ rawContent: at(cells, "revisionRawContent"),
868
+ savedAt,
869
+ ...nonempty(at(cells, "revisionDialect")) ? { dialect: nonempty(at(cells, "revisionDialect")) } : {},
870
+ ...nonempty(at(cells, "revisionSport")) ? { sport: nonempty(at(cells, "revisionSport")) } : {}
871
+ };
872
+ const list = revisionsByNote.get(noteId) ?? [];
873
+ list.push(rev);
874
+ revisionsByNote.set(noteId, list);
875
+ } else if (kind === "parse") {
876
+ const id = nonempty(at(cells, "parseId"));
877
+ const stage = nonempty(at(cells, "parseStage"));
878
+ const status = nonempty(at(cells, "parseStatus"));
879
+ const timestamp = num(at(cells, "timestamp"));
880
+ if (!id || !stage || !status || timestamp === void 0) {
881
+ errors.push(`Row ${idx + 2}: invalid parse columns`);
882
+ continue;
883
+ }
884
+ const parseRec = {
885
+ id,
886
+ noteId,
887
+ ...nonempty(at(cells, "blockId")) ? { blockId: nonempty(at(cells, "blockId")) } : {},
888
+ ...num(at(cells, "blockVersion")) !== void 0 ? { blockVersion: num(at(cells, "blockVersion")) } : {},
889
+ stage,
890
+ status,
891
+ timestamp,
892
+ ...nonempty(at(cells, "parseDiagnosticsJson")) ? { diagnostics: jsonCell(at(cells, "parseDiagnosticsJson")) } : {},
893
+ ...nonempty(at(cells, "parseMetricsJson")) ? { metrics: jsonCell(at(cells, "parseMetricsJson")) } : {}
894
+ };
895
+ const list = parsesByNote.get(noteId) ?? [];
896
+ list.push(parseRec);
897
+ parsesByNote.set(noteId, list);
898
+ } else if (kind === "session" || kind === "event") {
899
+ const sessionId = nonempty(at(cells, "sessionId"));
900
+ if (!sessionId) {
901
+ errors.push(`Row ${idx + 2}: missing sessionId`);
902
+ continue;
903
+ }
904
+ const subCells = SESSION_CSV_HEADER.map((h) => escapeCsvField(at(cells, h)));
905
+ const bucket = sessionCsvLinesBySession.get(sessionId) ?? {
906
+ noteId,
907
+ lines: [SESSION_CSV_HEADER.join(",")]
908
+ };
909
+ bucket.lines.push(subCells.join(","));
910
+ sessionCsvLinesBySession.set(sessionId, bucket);
911
+ } else {
912
+ errors.push(`Row ${idx + 2}: unknown recordKind '${kind}'`);
913
+ }
914
+ }
915
+ const bundlesByNote = /* @__PURE__ */ new Map();
916
+ const ensureBundle = (noteId) => {
917
+ const existing = bundlesByNote.get(noteId);
918
+ if (existing) return existing;
919
+ const created = { sessions: [], events: [] };
920
+ bundlesByNote.set(noteId, created);
921
+ return created;
922
+ };
923
+ for (const [noteId, revs] of revisionsByNote) {
924
+ ensureBundle(noteId).revisions = revs;
925
+ }
926
+ for (const [noteId, parses] of parsesByNote) {
927
+ ensureBundle(noteId).parses = parses;
928
+ }
929
+ for (const [, { noteId, lines }] of sessionCsvLinesBySession) {
930
+ try {
931
+ const parsed = csvToSessionRows(lines.join("\n") + "\n");
932
+ const bundle = ensureBundle(noteId);
933
+ bundle.sessions.push(parsed.session);
934
+ bundle.events.push(...parsed.events);
935
+ } catch (err) {
936
+ errors.push(err instanceof Error ? err.message : String(err));
937
+ }
938
+ }
939
+ return { bundles: [...bundlesByNote.values()], errors };
940
+ }
618
941
 
619
942
  // src/version.ts
620
- var VERSION = "0.51.2196";
621
- var GIT_SHA = "817bc28";
622
- var BUILD_TIME = "2026-11-05T23:36:56.914Z";
943
+ var VERSION = "0.52.2198";
944
+ var GIT_SHA = "15e2fcb";
945
+ var BUILD_TIME = "2026-11-11T15:07:53.492Z";
623
946
  var SEMVER = {
624
- version: "0.51.2196",
625
- gitSha: "817bc28",
626
- buildTime: "2026-11-05T23:36:56.914Z"
947
+ version: "0.52.2198",
948
+ gitSha: "15e2fcb",
949
+ buildTime: "2026-11-11T15:07:53.492Z"
627
950
  };
628
951
  var SEED_SCHEMA = 9;
629
952
  var SEED_REGISTERED_WIDGETS = wodWikiCore.KNOWN_SECTION_WIDGETS;
@@ -692,6 +1015,9 @@ function positive(value) {
692
1015
  function nonnegative(value) {
693
1016
  return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
694
1017
  }
1018
+ function finite(value) {
1019
+ return typeof value === "number" && Number.isFinite(value);
1020
+ }
695
1021
  function assertSeedManifest(value) {
696
1022
  if (!object(value) || value.schema !== SEED_SCHEMA) throw new Error("Incompatible seed schema; rebuild seed artifacts");
697
1023
  if (!nonnegative(value.version) || typeof value.builtAt !== "string" || !Number.isFinite(Date.parse(value.builtAt)) || !Array.isArray(value.chunks)) throw new Error("seed manifest failed shape validation");
@@ -719,7 +1045,7 @@ function assertSeedManifest(value) {
719
1045
  }
720
1046
  function assertNotebookIndex(value) {
721
1047
  if (!object(value)) throw new Error("notebook index failed shape validation");
722
- if (typeof value.notebookId !== "string" || !value.notebookId || typeof value.label !== "string" || typeof value.indexPath !== "string" || !value.indexPath || !nonnegative(value.version) || typeof value.commit !== "string" || typeof value.builtAt !== "string" || typeof value.sha256 !== "string" || !nonnegative(value.bytes) || !nonnegative(value.count) || !Array.isArray(value.records)) {
1048
+ if (typeof value.notebookId !== "string" || !value.notebookId || typeof value.label !== "string" || !value.label || typeof value.indexPath !== "string" || !value.indexPath || !nonnegative(value.version) || typeof value.commit !== "string" || typeof value.builtAt !== "string" || typeof value.sha256 !== "string" || !nonnegative(value.bytes) || !nonnegative(value.count) || !Array.isArray(value.records)) {
723
1049
  throw new Error("notebook index failed shape validation: missing required index summary or records");
724
1050
  }
725
1051
  for (const r of value.records) {
@@ -729,6 +1055,26 @@ function assertNotebookIndex(value) {
729
1055
  }
730
1056
  return value;
731
1057
  }
1058
+ function assertTelemetry(row, blockIndex) {
1059
+ if (row.telemetry === void 0) return;
1060
+ if (!object(row.telemetry) || !Array.isArray(row.telemetry.sessions) || !Array.isArray(row.telemetry.events)) throw new Error("invalid seed telemetry");
1061
+ const sessions = /* @__PURE__ */ new Map();
1062
+ for (const session of row.telemetry.sessions) {
1063
+ if (!object(session) || typeof session.id !== "string" || !session.id || sessions.has(session.id) || typeof session.noteId !== "string" || !session.noteId || typeof row.uuid === "string" && session.noteId !== row.uuid || typeof session.blockId !== "string" || !positive(session.blockVersion) || typeof session.blockContentId !== "string" || !finite(session.startTime) || !finite(session.endTime) || !finite(session.duration) || typeof session.completed !== "boolean" || !finite(session.createdAt)) throw new Error("invalid seed session");
1064
+ const projection = blockIndex.find((candidate) => object(candidate) && candidate.blockId === session.blockId);
1065
+ if (!object(projection) || projection.dataType !== "wod" || projection.blockVersion !== session.blockVersion || projection.blockContentId !== session.blockContentId) throw new Error("orphan or incompatible seed session pin");
1066
+ sessions.set(session.id, session);
1067
+ }
1068
+ const eventIds = /* @__PURE__ */ new Set();
1069
+ for (const event of row.telemetry.events) {
1070
+ if (!object(event) || typeof event.id !== "string" || !event.id || eventIds.has(event.id) || typeof event.resultId !== "string" || typeof event.noteId !== "string" || !finite(event.timestamp) || event.grain !== "event" && event.grain !== "summary" || typeof event.outputType !== "string" || !Array.isArray(event.metrics) || !event.metrics.every((metric) => object(metric) && typeof metric.type === "string") || event.grain === "summary" && event.metrics.length !== 1) throw new Error("invalid seed event");
1071
+ const session = sessions.get(event.resultId);
1072
+ if (!session || event.noteId !== session.noteId || event.blockId !== session.blockId || event.blockVersion !== session.blockVersion || event.blockContentId !== session.blockContentId) {
1073
+ throw new Error("orphan or incompatible seed event identity");
1074
+ }
1075
+ eventIds.add(event.id);
1076
+ }
1077
+ }
732
1078
  function assertSeedRows(value) {
733
1079
  if (!Array.isArray(value)) throw new Error("seed chunk is not an array");
734
1080
  const paths = /* @__PURE__ */ new Set();
@@ -773,12 +1119,414 @@ function assertSeedRows(value) {
773
1119
  if (!object(projection) || link.noteId !== projection.noteId || link.blockContentId !== projection.blockContentId || !Number.isFinite(link.createdAt)) throw new Error("invalid seed equipment metadata");
774
1120
  equipmentLinks.add(String(link.id));
775
1121
  }
1122
+ assertTelemetry(row, row.blockIndex);
776
1123
  }
777
1124
  return value;
778
1125
  }
779
1126
  function assertSeedRow(value) {
780
1127
  return assertSeedRows([value])[0];
781
1128
  }
1129
+ function makeScopedOverrideId(notebookId, kind, slug) {
1130
+ return `${notebookId}:${kind}:${slug}`;
1131
+ }
1132
+ function contributionsFromParsedTag(parsed) {
1133
+ const contributions = [];
1134
+ for (const [mKey, mVal] of Object.entries(parsed.metrics)) {
1135
+ if (typeof mVal !== "string" && typeof mVal !== "number") continue;
1136
+ const strVal = String(mVal).trim();
1137
+ const qtyMatch = strVal.match(/^([+-]?\d+(?:\.\d+)?)\s*([A-Za-z%/][\w%/.-]*)$/);
1138
+ if (qtyMatch) {
1139
+ contributions.push({ kind: "metric", type: mKey, value: Number(qtyMatch[1]), unit: qtyMatch[2] });
1140
+ } else {
1141
+ contributions.push({ kind: "metric", type: mKey, value: mVal });
1142
+ }
1143
+ }
1144
+ for (const [sKey, sExpr] of Object.entries(parsed.summaries)) {
1145
+ contributions.push({ kind: "metric", type: `summaries.${sKey}`, value: sExpr });
1146
+ }
1147
+ for (const [wKey, wSpec] of Object.entries(parsed.widgets ?? {})) {
1148
+ contributions.push({ kind: "metric", type: `widgets.${wKey}`, value: wSpec });
1149
+ }
1150
+ for (const tSlug of parsed.tags) {
1151
+ contributions.push({ kind: "tag", slug: tSlug });
1152
+ }
1153
+ for (const fnName of parsed.functions) {
1154
+ contributions.push({ kind: "function", name: fnName });
1155
+ }
1156
+ return contributions;
1157
+ }
1158
+ async function saveScopedPropertyOverride(storage, input) {
1159
+ const targetNotebookId = wodWikiCore.toNotebookId(input.targetNotebookId);
1160
+ if (wodWikiCore.isSystemReadOnlyNotebook(targetNotebookId)) {
1161
+ throw new Error(`Notebook '${targetNotebookId}' is read-only and cannot store overrides.`);
1162
+ }
1163
+ if (targetNotebookId === "notebook/journal" || targetNotebookId === "notebook/playground") {
1164
+ throw new Error(
1165
+ `Property overrides belong in 'notebook/custom' or a shared user Notebook, not '${targetNotebookId}'.`
1166
+ );
1167
+ }
1168
+ const cleanSlug = input.slug.trim().toLowerCase();
1169
+ if (!cleanSlug) {
1170
+ throw new Error("Property override requires a non-empty canonical slug.");
1171
+ }
1172
+ const nbSlug = wodWikiCore.notebookSlugFromId(targetNotebookId);
1173
+ const ownerNoteId = `override/${nbSlug}/${input.kind}/${cleanSlug}`;
1174
+ const deterministicEntityId = `${input.kind}-override-${nbSlug}-${cleanSlug}`;
1175
+ const now = Date.now();
1176
+ let rawContent = input.rawContent;
1177
+ const fm = readFrontmatterMeta(rawContent);
1178
+ if (typeof fm["id"] !== "string" || !fm["id"].trim()) {
1179
+ rawContent = wodWikiCore.patchFrontmatterProperty(rawContent, ["id"], deterministicEntityId);
1180
+ }
1181
+ if (typeof fm["slug"] !== "string" || fm["slug"].trim() !== cleanSlug) {
1182
+ rawContent = wodWikiCore.patchFrontmatterProperty(rawContent, ["slug"], cleanSlug);
1183
+ }
1184
+ let label = input.title?.trim() || cleanSlug;
1185
+ let payload;
1186
+ if (input.kind === "effort") {
1187
+ const parsed = wodWikiLang.documentToEffort(rawContent);
1188
+ if (parsed.errors.length > 0) {
1189
+ throw new Error(parsed.errors.join("\n"));
1190
+ }
1191
+ label = parsed.effort.label || label;
1192
+ const effort = {
1193
+ ...parsed.effort,
1194
+ id: typeof fm["id"] === "string" && fm["id"].trim() ? fm["id"].trim() : deterministicEntityId,
1195
+ slug: cleanSlug,
1196
+ label,
1197
+ registrySource: "user",
1198
+ ownerNoteId,
1199
+ sourceId: targetNotebookId,
1200
+ updatedAt: new Date(now).toISOString()
1201
+ };
1202
+ payload = effort;
1203
+ } else if (input.kind === "equipment") {
1204
+ const parsed = wodWikiLang.documentToEquipment(rawContent);
1205
+ if (parsed.errors.length > 0) {
1206
+ throw new Error(parsed.errors.join("\n"));
1207
+ }
1208
+ label = parsed.equipment.label || label;
1209
+ const equipment = {
1210
+ ...parsed.equipment,
1211
+ id: typeof fm["id"] === "string" && fm["id"].trim() ? fm["id"].trim() : deterministicEntityId,
1212
+ slug: cleanSlug,
1213
+ label,
1214
+ registrySource: "user",
1215
+ ownerNoteId,
1216
+ sourceId: targetNotebookId,
1217
+ updatedAt: new Date(now).toISOString()
1218
+ };
1219
+ payload = equipment;
1220
+ } else if (input.kind === "tag") {
1221
+ const category = input.category ?? "tag";
1222
+ const parsed = wodWikiLang.documentToTag(rawContent, category);
1223
+ if (parsed.errors.length > 0) {
1224
+ throw new Error(parsed.errors.join("\n"));
1225
+ }
1226
+ const resolvedCat = parsed.tag.category || category;
1227
+ label = parsed.tag.label || label;
1228
+ const tagRow = {
1229
+ id: parsed.tag.id || deterministicEntityId,
1230
+ label: cleanSlug,
1231
+ ...resolvedCat !== "tag" ? { type: resolvedCat } : {},
1232
+ contributions: contributionsFromParsedTag(parsed.tag),
1233
+ createdAt: now
1234
+ };
1235
+ payload = tagRow;
1236
+ } else {
1237
+ const parsed = wodWikiLang.documentToTag(rawContent, "tag");
1238
+ const contributions = contributionsFromParsedTag(parsed.tag);
1239
+ label = typeof fm["label"] === "string" && fm["label"].trim() || label;
1240
+ const tagTypeRow = {
1241
+ id: deterministicEntityId,
1242
+ name: cleanSlug,
1243
+ label,
1244
+ ...typeof fm["color"] === "string" && fm["color"].trim() ? { color: fm["color"].trim() } : {},
1245
+ ...contributions.length > 0 ? { contributions } : {},
1246
+ createdAt: now
1247
+ };
1248
+ payload = tagTypeRow;
1249
+ }
1250
+ const overrideRecord = {
1251
+ id: makeScopedOverrideId(targetNotebookId, input.kind, cleanSlug),
1252
+ notebookId: targetNotebookId,
1253
+ kind: input.kind,
1254
+ slug: cleanSlug,
1255
+ label,
1256
+ ownerNoteId,
1257
+ rawContent,
1258
+ payload,
1259
+ seedOrigin: "user",
1260
+ updatedAt: now
1261
+ };
1262
+ await storage.transaction(
1263
+ ["notes", "block_revisions", "property_overrides", "tags", "tag_types"],
1264
+ "readwrite",
1265
+ async (tx) => {
1266
+ const landing = await tx.readonly("notes").get(targetNotebookId);
1267
+ if (landing && (landing.feedOrigin === "feed" || landing.seedOrigin === "seed")) {
1268
+ throw new Error(`Notebook '${targetNotebookId}' is feed-delivered and read-only.`);
1269
+ }
1270
+ const priorNote = await tx.readonly("notes").get(ownerNoteId);
1271
+ const nextRev = (priorNote?.sourceRevision ?? 0) + 1;
1272
+ const blocks = wodWikiCore.reconcileNoteBlocks(rawContent, {
1273
+ sourceRevision: nextRev,
1274
+ registeredWidgets: wodWikiCore.KNOWN_SECTION_WIDGETS
1275
+ });
1276
+ const revisions = Object.values(blocks).map((b) => ({
1277
+ noteId: ownerNoteId,
1278
+ blockId: b.id,
1279
+ version: b.version,
1280
+ kind: b.kind,
1281
+ rawContent: rawContent.slice(b.from, b.to),
1282
+ savedAt: now,
1283
+ ...b.dialect ? { dialect: b.dialect } : {},
1284
+ ...b.sport ? { sport: b.sport } : {}
1285
+ }));
1286
+ await tx.readwrite("notes").put({
1287
+ id: ownerNoteId,
1288
+ title: label,
1289
+ rawContent,
1290
+ sourceRevision: nextRev,
1291
+ blocks,
1292
+ createdAt: priorNote?.createdAt ?? now,
1293
+ notebookId: targetNotebookId,
1294
+ notebookIds: [targetNotebookId],
1295
+ seedOrigin: "user"
1296
+ });
1297
+ if (revisions.length > 0) {
1298
+ await tx.readwrite("block_revisions").putMany(revisions);
1299
+ }
1300
+ await tx.readwrite("property_overrides").put(overrideRecord);
1301
+ if (targetNotebookId === "notebook/custom") {
1302
+ if (input.kind === "tag") {
1303
+ await tx.readwrite("tags").put(payload);
1304
+ } else if (input.kind === "tag-type") {
1305
+ await tx.readwrite("tag_types").put(payload);
1306
+ }
1307
+ }
1308
+ }
1309
+ );
1310
+ return overrideRecord;
1311
+ }
1312
+ async function listScopedPropertyOverrides(storage, filter) {
1313
+ let rows;
1314
+ try {
1315
+ if (filter?.notebookId) {
1316
+ rows = await storage.readonly("property_overrides").getAllFromIndex("by-notebook", filter.notebookId);
1317
+ } else if (filter?.kind && filter?.slug) {
1318
+ rows = await storage.readonly("property_overrides").getAllFromIndex("by-kind-slug", [filter.kind, filter.slug]);
1319
+ } else {
1320
+ rows = await storage.readonly("property_overrides").getAll();
1321
+ }
1322
+ } catch {
1323
+ return [];
1324
+ }
1325
+ return rows.filter((r) => {
1326
+ if (filter?.notebookId && r.notebookId !== filter.notebookId) return false;
1327
+ if (filter?.kind && r.kind !== filter.kind) return false;
1328
+ if (filter?.slug && r.slug !== filter.slug) return false;
1329
+ return true;
1330
+ });
1331
+ }
1332
+ function deriveSourceScopes(context) {
1333
+ const scopes = [];
1334
+ const pushScope = (raw) => {
1335
+ if (!raw || !raw.trim()) return;
1336
+ if (raw.startsWith("feed:")) {
1337
+ if (!scopes.includes(raw)) scopes.push(raw);
1338
+ return;
1339
+ }
1340
+ const nb = wodWikiCore.toNotebookId(raw);
1341
+ if (nb === "notebook/defaults" || nb === "notebook/custom" || nb === "notebook/journal" || nb === "notebook/playground") {
1342
+ return;
1343
+ }
1344
+ if (!scopes.includes(nb)) scopes.push(nb);
1345
+ };
1346
+ if (context.note) {
1347
+ const feedId = context.note.provenance?.feedSourceId ?? context.note.feedSourceId;
1348
+ if (feedId && feedId !== "core" && feedId !== "local") {
1349
+ pushScope(`feed:${feedId}`);
1350
+ }
1351
+ if (context.note.provenance?.sourceNotebookId) {
1352
+ pushScope(context.note.provenance.sourceNotebookId);
1353
+ }
1354
+ for (const nb of wodWikiWql.notebooksOfItem(context.note)) {
1355
+ pushScope(nb);
1356
+ }
1357
+ const directNb = wodWikiWql.notebookOfItem(context.note);
1358
+ if (directNb) pushScope(directNb);
1359
+ }
1360
+ if (context.notebookId) pushScope(context.notebookId);
1361
+ return scopes;
1362
+ }
1363
+ async function resolveScopedPropertyCatalog(storage, context = {}) {
1364
+ let allOverrides = [];
1365
+ try {
1366
+ allOverrides = await storage.readonly("property_overrides").getAll();
1367
+ } catch {
1368
+ }
1369
+ let storedEfforts = [];
1370
+ let storedEquipment = [];
1371
+ let storedTags = [];
1372
+ let storedTagTypes = [];
1373
+ try {
1374
+ [storedEfforts, storedEquipment, storedTags, storedTagTypes] = await Promise.all([
1375
+ storage.readonly("efforts").getAll(),
1376
+ storage.readonly("equipment").getAll(),
1377
+ storage.readonly("tags").getAll(),
1378
+ storage.readonly("tag_types").getAll()
1379
+ ]);
1380
+ } catch {
1381
+ }
1382
+ const effortsBySlug = /* @__PURE__ */ new Map();
1383
+ const equipmentBySlug = /* @__PURE__ */ new Map();
1384
+ const tagsBySlug = /* @__PURE__ */ new Map();
1385
+ const tagTypesByName = /* @__PURE__ */ new Map();
1386
+ const originByKey = /* @__PURE__ */ new Map();
1387
+ for (const eff of storedEfforts) {
1388
+ if (eff.registrySource === "bundled" && (!eff.sourceId || eff.sourceId === "core" || eff.sourceId === "efforts")) {
1389
+ effortsBySlug.set(eff.slug, eff);
1390
+ originByKey.set(`effort:${eff.slug}`, "notebook/defaults");
1391
+ }
1392
+ }
1393
+ for (const eq of storedEquipment) {
1394
+ if (eq.registrySource === "bundled" && (!eq.sourceId || eq.sourceId === "core" || eq.sourceId === "equipment")) {
1395
+ equipmentBySlug.set(eq.slug, eq);
1396
+ originByKey.set(`equipment:${eq.slug}`, "notebook/defaults");
1397
+ }
1398
+ }
1399
+ for (const t of storedTags) {
1400
+ tagsBySlug.set(t.label, t);
1401
+ originByKey.set(`tag:${t.label}`, "notebook/defaults");
1402
+ }
1403
+ for (const tt of storedTagTypes) {
1404
+ tagTypesByName.set(tt.name, tt);
1405
+ originByKey.set(`tag-type:${tt.name}`, "notebook/defaults");
1406
+ }
1407
+ const explicitNb = context.notebookId ? wodWikiCore.toNotebookId(context.notebookId) : void 0;
1408
+ const mode = context.mode ?? "source-first";
1409
+ const sourceScopes = deriveSourceScopes(context);
1410
+ let orderedScopes;
1411
+ if (explicitNb === "notebook/defaults") {
1412
+ orderedScopes = ["notebook/defaults"];
1413
+ } else if (mode === "custom-runtime" || sourceScopes.length === 0) {
1414
+ orderedScopes = ["notebook/defaults", ...sourceScopes, "notebook/custom"];
1415
+ } else {
1416
+ orderedScopes = ["notebook/defaults", "notebook/custom", ...sourceScopes];
1417
+ }
1418
+ if (orderedScopes.includes("notebook/custom")) {
1419
+ for (const eff of storedEfforts) {
1420
+ if (eff.registrySource === "user" && !effortsBySlug.has(eff.slug)) {
1421
+ effortsBySlug.set(eff.slug, eff);
1422
+ originByKey.set(`effort:${eff.slug}`, "notebook/custom");
1423
+ }
1424
+ }
1425
+ for (const eq of storedEquipment) {
1426
+ if (eq.registrySource === "user" && !equipmentBySlug.has(eq.slug)) {
1427
+ equipmentBySlug.set(eq.slug, eq);
1428
+ originByKey.set(`equipment:${eq.slug}`, "notebook/custom");
1429
+ }
1430
+ }
1431
+ }
1432
+ const byScope = /* @__PURE__ */ new Map();
1433
+ for (const ov of allOverrides) {
1434
+ const arr = byScope.get(ov.notebookId) ?? [];
1435
+ arr.push(ov);
1436
+ byScope.set(ov.notebookId, arr);
1437
+ }
1438
+ for (const scope of orderedScopes) {
1439
+ const rows = byScope.get(scope) ?? [];
1440
+ for (const row of rows) {
1441
+ const originLabel = scope.startsWith("feed:") ? scope : scope;
1442
+ if (row.kind === "effort") {
1443
+ const eff = row.payload ?? wodWikiLang.documentToEffort(row.rawContent).effort;
1444
+ effortsBySlug.set(row.slug, { ...eff, slug: row.slug });
1445
+ originByKey.set(`effort:${row.slug}`, originLabel);
1446
+ } else if (row.kind === "equipment") {
1447
+ const eq = row.payload ?? wodWikiLang.documentToEquipment(row.rawContent).equipment;
1448
+ equipmentBySlug.set(row.slug, { ...eq, slug: row.slug });
1449
+ originByKey.set(`equipment:${row.slug}`, originLabel);
1450
+ } else if (row.kind === "tag") {
1451
+ const tag = row.payload;
1452
+ if (tag) {
1453
+ tagsBySlug.set(row.slug, tag);
1454
+ originByKey.set(`tag:${row.slug}`, originLabel);
1455
+ }
1456
+ } else if (row.kind === "tag-type") {
1457
+ const tt = row.payload;
1458
+ if (tt) {
1459
+ tagTypesByName.set(row.slug, tt);
1460
+ originByKey.set(`tag-type:${row.slug}`, originLabel);
1461
+ }
1462
+ }
1463
+ }
1464
+ }
1465
+ const efforts = [...effortsBySlug.values()];
1466
+ const equipment = [...equipmentBySlug.values()];
1467
+ const tags = [...tagsBySlug.values()];
1468
+ const tagTypes = [...tagTypesByName.values()];
1469
+ const tagDefs = [
1470
+ ...tagTypes.filter((tt) => tt.contributions && tt.contributions.length > 0).map((tt) => ({
1471
+ slug: `category:${tt.name}`,
1472
+ contributions: tt.contributions ?? []
1473
+ })),
1474
+ ...tags.map((t) => ({
1475
+ slug: t.label,
1476
+ contributions: t.contributions ?? []
1477
+ }))
1478
+ ];
1479
+ return {
1480
+ efforts,
1481
+ equipment,
1482
+ tags,
1483
+ tagTypes,
1484
+ referenceIndex: wodWikiLang.createReferenceIndex({ efforts, equipment }),
1485
+ tagIndex: wodWikiCore.createTagIndex(tagDefs),
1486
+ originByKey
1487
+ };
1488
+ }
1489
+ async function promoteReferencedOverridesToNotebook(storage, input) {
1490
+ const targetNb = wodWikiCore.toNotebookId(input.notebookId);
1491
+ if (wodWikiCore.isNonPublishableNotebook(targetNb)) return [];
1492
+ let customOverrides;
1493
+ let existingNbOverrides;
1494
+ try {
1495
+ [customOverrides, existingNbOverrides] = await Promise.all([
1496
+ storage.readonly("property_overrides").getAllFromIndex("by-notebook", "notebook/custom"),
1497
+ storage.readonly("property_overrides").getAllFromIndex("by-notebook", targetNb)
1498
+ ]);
1499
+ } catch {
1500
+ return [];
1501
+ }
1502
+ const existingByKey = new Map(existingNbOverrides.map((o) => [`${o.kind}:${o.slug}`, o]));
1503
+ const customByKey = new Map(customOverrides.map((o) => [`${o.kind}:${o.slug}`, o]));
1504
+ const wantedKeys = /* @__PURE__ */ new Set();
1505
+ for (const s of input.effortSlugs ?? []) wantedKeys.add(`effort:${s}`);
1506
+ for (const s of input.equipmentSlugs ?? []) wantedKeys.add(`equipment:${s}`);
1507
+ for (const s of input.tagSlugs ?? []) wantedKeys.add(`tag:${s}`);
1508
+ const toWrite = [];
1509
+ const now = Date.now();
1510
+ for (const key of wantedKeys) {
1511
+ if (existingByKey.has(key)) continue;
1512
+ const fromCustom = customByKey.get(key);
1513
+ if (!fromCustom) continue;
1514
+ const promoted = {
1515
+ ...fromCustom,
1516
+ id: makeScopedOverrideId(targetNb, fromCustom.kind, fromCustom.slug),
1517
+ notebookId: targetNb,
1518
+ updatedAt: now
1519
+ };
1520
+ toWrite.push(promoted);
1521
+ existingByKey.set(key, promoted);
1522
+ }
1523
+ if (toWrite.length > 0) {
1524
+ await storage.transaction(["property_overrides"], "readwrite", async (tx) => {
1525
+ await tx.readwrite("property_overrides").putMany(toWrite);
1526
+ });
1527
+ }
1528
+ return [...existingByKey.values()];
1529
+ }
782
1530
 
783
1531
  // src/seed/runtime.ts
784
1532
  async function seedNoteId(path) {
@@ -914,7 +1662,7 @@ async function applySeedChunk(storage, write) {
914
1662
  if (!tagIds.has(label)) tagIds.set(label, await seedNoteId(`tag:${label}`));
915
1663
  }
916
1664
  }
917
- return storage.transaction(["notes", "block_revisions", "block_index", "block_efforts", "block_equipment", "page", "page_notes", "tags", "note_tags", "efforts", "equipment", "meta"], "readwrite", async (tx) => {
1665
+ return storage.transaction(["notes", "block_revisions", "block_index", "block_efforts", "block_equipment", "page", "page_notes", "tags", "note_tags", "efforts", "equipment", "property_overrides", "meta", "sessions", "events"], "readwrite", async (tx) => {
918
1666
  const metaStore = tx.readwrite("meta");
919
1667
  const userDeleted = /* @__PURE__ */ new Set();
920
1668
  for (const row of await metaStore.getAll()) {
@@ -986,6 +1734,11 @@ async function applySeedChunk(storage, write) {
986
1734
  const tagsByLabel = new Map(labels.map((label, i) => [label, matches[i][0]]));
987
1735
  const changedTags = [], changedNotes = [], revisions = [], pages = [], pageNotes = [], noteTags = [];
988
1736
  const blocks = [], blockEfforts = [], blockEquipment = [];
1737
+ const sessionStore = tx.readwrite("sessions"), eventStore = tx.readwrite("events");
1738
+ const telemetrySessionIds = write.rows.flatMap((row) => row.telemetry?.sessions.map((session) => session.id) ?? []);
1739
+ const storedTelemetrySessions = await sessionStore.getMany(telemetrySessionIds);
1740
+ const existingTelemetrySessions = new Map(telemetrySessionIds.map((sessionId, i) => [sessionId, storedTelemetrySessions[i]]));
1741
+ const sessions = [], events = [];
989
1742
  for (const [i, row] of write.rows.entries()) {
990
1743
  const id = ids[i], existing = existingById.get(id);
991
1744
  if (!owned.has(id)) {
@@ -1035,6 +1788,36 @@ async function applySeedChunk(storage, write) {
1035
1788
  const prior = currentIndexes[slot.get(id)].find((b) => b.id === projection.id);
1036
1789
  if (!prior || prior.isStatic === true) blocks.push(projection);
1037
1790
  }
1791
+ const resolvedSessions = /* @__PURE__ */ new Map();
1792
+ for (const compiled of row.telemetry?.sessions ?? []) {
1793
+ if (compiledById.get(compiled.blockId)?.dataType !== "wod") throw new Error("Orphan seed session pin");
1794
+ const prior = existingTelemetrySessions.get(compiled.id);
1795
+ if (prior && prior.noteId !== id) throw new Error(`Seed session ${compiled.id} belongs to another note`);
1796
+ const blockId = prior?.blockId ?? remap.get(compiled.blockId);
1797
+ if (!blockId) throw new Error("Orphan seed session pin");
1798
+ const block = map[blockId];
1799
+ if (!prior && !block) throw new Error("Orphan seed session pin");
1800
+ const session = {
1801
+ ...compiled,
1802
+ noteId: id,
1803
+ blockId,
1804
+ blockVersion: prior?.blockVersion ?? block.version,
1805
+ blockContentId: prior?.blockContentId ?? compiledById.get(compiled.blockId)?.blockContentId
1806
+ };
1807
+ sessions.push(session);
1808
+ resolvedSessions.set(session.id, session);
1809
+ }
1810
+ for (const compiled of row.telemetry?.events ?? []) {
1811
+ const session = resolvedSessions.get(compiled.resultId);
1812
+ if (!session) throw new Error("Orphan seed event result");
1813
+ events.push({
1814
+ ...compiled,
1815
+ noteId: id,
1816
+ blockId: session.blockId,
1817
+ blockVersion: session.blockVersion,
1818
+ blockContentId: session.blockContentId
1819
+ });
1820
+ }
1038
1821
  for (const compiled of row.blockEfforts) {
1039
1822
  const blockId = remap.get(compiled.blockId);
1040
1823
  if (!blockId || compiledById.get(compiled.blockId)?.dataType !== "wod") throw new Error("Orphan seed effort link");
@@ -1089,17 +1872,63 @@ async function applySeedChunk(storage, write) {
1089
1872
  for (const link of currentPages[n]) await pageLinks.delete(link.id);
1090
1873
  result.deleted++;
1091
1874
  }
1875
+ const recordSeedPropertyOverrides = async (kind, parse) => {
1876
+ let overrideStore;
1877
+ try {
1878
+ overrideStore = tx.readwrite("property_overrides");
1879
+ } catch {
1880
+ return;
1881
+ }
1882
+ const scopes = feedSourceId === "core" ? ["notebook/defaults"] : [
1883
+ `feed:${feedSourceId}`,
1884
+ ...write.manifest.chunks.filter((c) => c.id.startsWith("notebook.")).map((c) => `notebook/${notebookSlugForChunkId(c.id)}`)
1885
+ ];
1886
+ const wantedIds = /* @__PURE__ */ new Set();
1887
+ const toPut = [];
1888
+ for (const [idx, row] of write.rows.entries()) {
1889
+ const parsed = parse(row.content);
1890
+ if (!parsed) continue;
1891
+ for (const scope of scopes) {
1892
+ const ovId = makeScopedOverrideId(scope, kind, parsed.slug);
1893
+ wantedIds.add(ovId);
1894
+ toPut.push({
1895
+ id: ovId,
1896
+ notebookId: scope,
1897
+ kind,
1898
+ slug: parsed.slug,
1899
+ label: parsed.label,
1900
+ ownerNoteId: ids[idx],
1901
+ rawContent: row.content,
1902
+ payload: parsed,
1903
+ seedOrigin: "seed",
1904
+ feedSourceId,
1905
+ updatedAt: write.meta.importedAt
1906
+ });
1907
+ }
1908
+ }
1909
+ if (toPut.length > 0) await overrideStore.putMany(toPut);
1910
+ const existingAll = await overrideStore.getAll();
1911
+ for (const existingOv of existingAll) {
1912
+ if (existingOv.seedOrigin === "seed" && existingOv.feedSourceId === feedSourceId && existingOv.kind === kind && !wantedIds.has(existingOv.id)) {
1913
+ await overrideStore.delete(existingOv.id);
1914
+ }
1915
+ }
1916
+ };
1092
1917
  if (write.chunkId === EFFORTS_CHUNK_ID) {
1093
1918
  result.totalEfforts = await applyDefinitionChunk(tx.readwrite("efforts"), noteStore, wodWikiLang.parseEffortFile, "efforts", seedSource, incomingRank, otherCheckpoints, priorIds, write.rows, ids, owned, existingById, allIds);
1919
+ await recordSeedPropertyOverrides("effort", wodWikiLang.parseEffortFile);
1094
1920
  }
1095
1921
  if (write.chunkId === EQUIPMENT_CHUNK_ID) {
1096
1922
  result.totalEquipment = await applyDefinitionChunk(tx.readwrite("equipment"), noteStore, wodWikiLang.parseEquipmentFile, "equipment", seedSource, incomingRank, otherCheckpoints, priorIds, write.rows, ids, owned, existingById, allIds);
1923
+ await recordSeedPropertyOverrides("equipment", wodWikiLang.parseEquipmentFile);
1097
1924
  }
1098
1925
  if (changedNotes.length) await noteStore.putMany(changedNotes);
1099
1926
  if (revisions.length) await revisionStore.putMany(revisions);
1100
1927
  await putChanged(indexStore, blocks, blocks.map((b) => b.id));
1101
1928
  await putChanged(effortLinks, blockEfforts, blockEfforts.map((b) => b.id));
1102
1929
  await putChanged(equipmentLinks, blockEquipment, blockEquipment.map((b) => b.id));
1930
+ await putChanged(sessionStore, sessions, sessions.map((session) => session.id));
1931
+ await putChanged(eventStore, events, events.map((event) => event.id));
1103
1932
  if (changedTags.length) await tagsStore.putMany([...new Map(changedTags.map((t) => [t.id, t])).values()]);
1104
1933
  if (noteTags.length) await tagLinks.putMany(noteTags);
1105
1934
  await putChanged(tx.readwrite("page"), pages, pages.map((p) => p.id));
@@ -1193,106 +2022,2661 @@ async function migrateNotebookVocabulary(storage) {
1193
2022
  });
1194
2023
  }
1195
2024
 
1196
- Object.defineProperty(exports, "ABSENT", {
1197
- enumerable: true,
1198
- get: function () { return wodWikiLang.ABSENT; }
1199
- });
1200
- Object.defineProperty(exports, "AGGREGATE_BUILTINS", {
1201
- enumerable: true,
1202
- get: function () { return wodWikiLang.AGGREGATE_BUILTINS; }
1203
- });
1204
- Object.defineProperty(exports, "AUTHORITATIVE_CASTS", {
1205
- enumerable: true,
1206
- get: function () { return wodWikiLang.AUTHORITATIVE_CASTS; }
1207
- });
1208
- Object.defineProperty(exports, "AmrapLogicStrategy", {
1209
- enumerable: true,
1210
- get: function () { return wodWikiLang.AmrapLogicStrategy; }
1211
- });
1212
- Object.defineProperty(exports, "AnalyticsEngine", {
1213
- enumerable: true,
1214
- get: function () { return wodWikiLang.AnalyticsEngine; }
1215
- });
1216
- Object.defineProperty(exports, "AnalyticsTransformer", {
1217
- enumerable: true,
1218
- get: function () { return wodWikiLang.AnalyticsTransformer; }
1219
- });
1220
- Object.defineProperty(exports, "BUILTIN_CALCS", {
1221
- enumerable: true,
1222
- get: function () { return wodWikiLang.BUILTIN_CALCS; }
1223
- });
1224
- Object.defineProperty(exports, "BUNDLED_EFFORT_COUNT", {
1225
- enumerable: true,
1226
- get: function () { return wodWikiLang.BUNDLED_EFFORT_COUNT; }
1227
- });
1228
- Object.defineProperty(exports, "BlockBuilder", {
1229
- enumerable: true,
1230
- get: function () { return wodWikiLang.BlockBuilder; }
1231
- });
1232
- Object.defineProperty(exports, "BlockContext", {
1233
- enumerable: true,
1234
- get: function () { return wodWikiLang.BlockContext; }
1235
- });
1236
- Object.defineProperty(exports, "ButtonBehavior", {
1237
- enumerable: true,
1238
- get: function () { return wodWikiLang.ButtonBehavior; }
1239
- });
1240
- Object.defineProperty(exports, "CONSUMED_HINTS", {
1241
- enumerable: true,
1242
- get: function () { return wodWikiLang.CONSUMED_HINTS; }
1243
- });
1244
- Object.defineProperty(exports, "CONSUMED_HINT_KEYS", {
1245
- enumerable: true,
1246
- get: function () { return wodWikiLang.CONSUMED_HINT_KEYS; }
1247
- });
1248
- Object.defineProperty(exports, "CONTEXT_ATOMS", {
1249
- enumerable: true,
1250
- get: function () { return wodWikiLang.CONTEXT_ATOMS; }
1251
- });
1252
- Object.defineProperty(exports, "CalcEngine", {
1253
- enumerable: true,
1254
- get: function () { return wodWikiLang.CalcEngine; }
1255
- });
1256
- Object.defineProperty(exports, "CalculationRegistry", {
1257
- enumerable: true,
1258
- get: function () { return wodWikiLang.CalculationRegistry; }
1259
- });
1260
- Object.defineProperty(exports, "CardioDialect", {
1261
- enumerable: true,
1262
- get: function () { return wodWikiLang.CardioDialect; }
1263
- });
1264
- Object.defineProperty(exports, "ChildSelectionBehavior", {
1265
- enumerable: true,
1266
- get: function () { return wodWikiLang.ChildSelectionBehavior; }
1267
- });
1268
- Object.defineProperty(exports, "ChildrenStrategy", {
1269
- enumerable: true,
1270
- get: function () { return wodWikiLang.ChildrenStrategy; }
1271
- });
1272
- Object.defineProperty(exports, "ChoiceGroupMetric", {
1273
- enumerable: true,
1274
- get: function () { return wodWikiLang.ChoiceGroupMetric; }
1275
- });
1276
- Object.defineProperty(exports, "ClimbDialect", {
1277
- enumerable: true,
1278
- get: function () { return wodWikiLang.ClimbDialect; }
1279
- });
1280
- Object.defineProperty(exports, "ClimbMetricType", {
1281
- enumerable: true,
1282
- get: function () { return wodWikiLang.ClimbMetricType; }
1283
- });
1284
- Object.defineProperty(exports, "CountdownTimerBehavior", {
1285
- enumerable: true,
1286
- get: function () { return wodWikiLang.CountdownTimerBehavior; }
1287
- });
1288
- Object.defineProperty(exports, "CountupTimerBehavior", {
1289
- enumerable: true,
1290
- get: function () { return wodWikiLang.CountupTimerBehavior; }
2025
+ // src/feed/qr.ts
2026
+ var APP_ORIGIN = "https://wod.wiki";
2027
+ var QR_SCRIPT_ID = "wod-feed-qr";
2028
+ function qrInlineScript(appOrigin = APP_ORIGIN) {
2029
+ return SCRIPT.replace("__APP_ORIGIN__", appOrigin);
2030
+ }
2031
+ var SCRIPT = `(function () {
2032
+ 'use strict';
2033
+
2034
+ var APP_ORIGIN = '__APP_ORIGIN__';
2035
+
2036
+ // Error correction level M: [ecc codewords per block, block count] for
2037
+ // versions 1..20.
2038
+ var ECC_TABLE = [
2039
+ [10, 1], [16, 1], [26, 1], [18, 2], [24, 2], [16, 4], [18, 4], [22, 4],
2040
+ [22, 5], [26, 5], [30, 5], [22, 8], [22, 9], [24, 9], [24, 10],
2041
+ [28, 10], [28, 11], [26, 13], [26, 14], [22, 18]
2042
+ ];
2043
+ var MAX_VERSION = ECC_TABLE.length;
2044
+ var MODE_BYTE = 4;
2045
+ var FORMAT_BITS_M = 0;
2046
+
2047
+ // \u2500\u2500 GF(256) arithmetic (Reed-Solomon) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
2048
+
2049
+ function gfMul(x, y) {
2050
+ var z = 0;
2051
+ for (var i = 7; i >= 0; i--) {
2052
+ z = (z << 1) ^ ((z >>> 7) * 0x11d);
2053
+ z ^= ((y >>> i) & 1) * x;
2054
+ }
2055
+ return z & 0xff;
2056
+ }
2057
+
2058
+ function rsDivisor(degree) {
2059
+ var result = [];
2060
+ for (var i = 0; i < degree - 1; i++) result.push(0);
2061
+ result.push(1);
2062
+ var root = 1;
2063
+ for (var i = 0; i < degree; i++) {
2064
+ for (var j = 0; j < result.length; j++) {
2065
+ result[j] = gfMul(result[j], root);
2066
+ if (j + 1 < result.length) result[j] ^= result[j + 1];
2067
+ }
2068
+ root = gfMul(root, 0x02);
2069
+ }
2070
+ return result;
2071
+ }
2072
+
2073
+ function rsRemainder(data, divisor) {
2074
+ var result = divisor.map(function () { return 0; });
2075
+ for (var i = 0; i < data.length; i++) {
2076
+ var factor = data[i] ^ (result.shift() & 0xff);
2077
+ result.push(0);
2078
+ for (var j = 0; j < divisor.length; j++) result[j] ^= gfMul(divisor[j], factor);
2079
+ }
2080
+ return result;
2081
+ }
2082
+
2083
+ // \u2500\u2500 Version geometry \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
2084
+
2085
+ function numRawDataModules(ver) {
2086
+ var result = (16 * ver + 128) * ver + 64;
2087
+ if (ver >= 2) {
2088
+ var numAlign = Math.floor(ver / 7) + 2;
2089
+ result -= (25 * numAlign - 10) * numAlign - 55;
2090
+ if (ver >= 7) result -= 36;
2091
+ }
2092
+ return result;
2093
+ }
2094
+
2095
+ function numDataCodewords(ver) {
2096
+ var t = ECC_TABLE[ver - 1];
2097
+ return Math.floor(numRawDataModules(ver) / 8) - t[0] * t[1];
2098
+ }
2099
+
2100
+ function alignmentPositions(ver) {
2101
+ if (ver === 1) return [];
2102
+ var numAlign = Math.floor(ver / 7) + 2;
2103
+ var step = Math.ceil((ver * 4 + 4) / (numAlign * 2 - 2)) * 2;
2104
+ var size = ver * 4 + 17;
2105
+ var result = [6];
2106
+ for (var pos = size - 7; result.length < numAlign; pos -= step) result.splice(1, 0, pos);
2107
+ return result;
2108
+ }
2109
+
2110
+ // \u2500\u2500 Bit stream \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
2111
+
2112
+ function utf8Bytes(text) {
2113
+ if (typeof TextEncoder !== 'undefined') return Array.from(new TextEncoder().encode(text));
2114
+ var out = [];
2115
+ for (var i = 0; i < text.length; i++) {
2116
+ var c = text.charCodeAt(i);
2117
+ if (c < 0x80) out.push(c);
2118
+ else if (c < 0x800) out.push(0xc0 | (c >> 6), 0x80 | (c & 0x3f));
2119
+ else out.push(0xe0 | (c >> 12), 0x80 | ((c >> 6) & 0x3f), 0x80 | (c & 0x3f));
2120
+ }
2121
+ return out;
2122
+ }
2123
+
2124
+ function buildCodewords(text, ver) {
2125
+ var bytes = utf8Bytes(text);
2126
+ var ccBits = ver <= 9 ? 8 : 16;
2127
+ var bits = [];
2128
+ function push(value, len) {
2129
+ for (var i = len - 1; i >= 0; i--) bits.push((value >>> i) & 1);
2130
+ }
2131
+ push(MODE_BYTE, 4);
2132
+ push(bytes.length, ccBits);
2133
+ for (var i = 0; i < bytes.length; i++) push(bytes[i], 8);
2134
+ var capacity = numDataCodewords(ver) * 8;
2135
+ push(0, Math.min(4, capacity - bits.length));
2136
+ push(0, (8 - (bits.length % 8)) % 8);
2137
+ for (var pad = 0xec; bits.length < capacity; pad ^= 0xec ^ 0x11) push(pad, 8);
2138
+ var codewords = [];
2139
+ for (var i = 0; i < bits.length; i += 8) {
2140
+ var b = 0;
2141
+ for (var j = 0; j < 8; j++) b = (b << 1) | bits[i + j];
2142
+ codewords.push(b);
2143
+ }
2144
+ return codewords;
2145
+ }
2146
+
2147
+ function splitBlocks(data, ver) {
2148
+ var t = ECC_TABLE[ver - 1];
2149
+ var eccLen = t[0];
2150
+ var numBlocks = t[1];
2151
+ var rawCodewords = Math.floor(numRawDataModules(ver) / 8);
2152
+ var numShort = numBlocks - (rawCodewords % numBlocks);
2153
+ var shortBlockLen = Math.floor(rawCodewords / numBlocks);
2154
+ var divisor = rsDivisor(eccLen);
2155
+ var blocks = [];
2156
+ var k = 0;
2157
+ for (var i = 0; i < numBlocks; i++) {
2158
+ var dataLen = shortBlockLen - eccLen + (i < numShort ? 0 : 1);
2159
+ var dat = data.slice(k, k + dataLen);
2160
+ k += dataLen;
2161
+ blocks.push({ data: dat, ecc: rsRemainder(dat, divisor) });
2162
+ }
2163
+ return blocks;
2164
+ }
2165
+
2166
+ function interleave(blocks) {
2167
+ var out = [];
2168
+ var maxData = 0;
2169
+ var eccLen = blocks[0].ecc.length;
2170
+ for (var b = 0; b < blocks.length; b++) {
2171
+ if (blocks[b].data.length > maxData) maxData = blocks[b].data.length;
2172
+ }
2173
+ for (var i = 0; i < maxData; i++) {
2174
+ for (var j = 0; j < blocks.length; j++) {
2175
+ if (i < blocks[j].data.length) out.push(blocks[j].data[i]);
2176
+ }
2177
+ }
2178
+ for (var i = 0; i < eccLen; i++) {
2179
+ for (var j = 0; j < blocks.length; j++) out.push(blocks[j].ecc[i]);
2180
+ }
2181
+ return out;
2182
+ }
2183
+
2184
+ // \u2500\u2500 Matrix \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
2185
+
2186
+ function newMatrix(size) {
2187
+ var modules = [];
2188
+ var isFunction = [];
2189
+ for (var y = 0; y < size; y++) {
2190
+ modules.push(new Array(size).fill(false));
2191
+ isFunction.push(new Array(size).fill(false));
2192
+ }
2193
+ return { modules: modules, isFunction: isFunction, size: size };
2194
+ }
2195
+
2196
+ function setFunction(m, x, y, dark) {
2197
+ m.modules[y][x] = dark;
2198
+ m.isFunction[y][x] = true;
2199
+ }
2200
+
2201
+ function drawFinder(m, cx, cy) {
2202
+ for (var dy = -4; dy <= 4; dy++) {
2203
+ for (var dx = -4; dx <= 4; dx++) {
2204
+ var x = cx + dx;
2205
+ var y = cy + dy;
2206
+ if (x < 0 || x >= m.size || y < 0 || y >= m.size) continue;
2207
+ var dist = Math.max(Math.abs(dx), Math.abs(dy));
2208
+ setFunction(m, x, y, dist !== 2 && dist !== 4);
2209
+ }
2210
+ }
2211
+ }
2212
+
2213
+ function drawAlignment(m, cx, cy) {
2214
+ for (var dy = -2; dy <= 2; dy++) {
2215
+ for (var dx = -2; dx <= 2; dx++) {
2216
+ setFunction(m, cx + dx, cy + dy, Math.max(Math.abs(dx), Math.abs(dy)) !== 1);
2217
+ }
2218
+ }
2219
+ }
2220
+
2221
+ function drawFunctionPatterns(m, ver) {
2222
+ for (var i = 0; i < m.size; i++) {
2223
+ setFunction(m, 6, i, i % 2 === 0);
2224
+ setFunction(m, i, 6, i % 2 === 0);
2225
+ }
2226
+ drawFinder(m, 3, 3);
2227
+ drawFinder(m, m.size - 4, 3);
2228
+ drawFinder(m, 3, m.size - 4);
2229
+ var pos = alignmentPositions(ver);
2230
+ for (var i = 0; i < pos.length; i++) {
2231
+ for (var j = 0; j < pos.length; j++) {
2232
+ var corner = (i === 0 && j === 0) ||
2233
+ (i === 0 && j === pos.length - 1) ||
2234
+ (i === pos.length - 1 && j === 0);
2235
+ if (!corner) drawAlignment(m, pos[i], pos[j]);
2236
+ }
2237
+ }
2238
+ drawFormatBits(m, 0);
2239
+ drawVersionBits(m, ver);
2240
+ }
2241
+
2242
+ function drawFormatBits(m, mask) {
2243
+ var data = (FORMAT_BITS_M << 3) | mask;
2244
+ var rem = data;
2245
+ for (var i = 0; i < 10; i++) rem = (rem << 1) ^ ((rem >>> 9) * 0x537);
2246
+ var bits = ((data << 10) | rem) ^ 0x5412;
2247
+ for (var i = 0; i <= 5; i++) setFunction(m, 8, i, ((bits >>> i) & 1) !== 0);
2248
+ setFunction(m, 8, 7, ((bits >>> 6) & 1) !== 0);
2249
+ setFunction(m, 8, 8, ((bits >>> 7) & 1) !== 0);
2250
+ setFunction(m, 7, 8, ((bits >>> 8) & 1) !== 0);
2251
+ for (var i = 9; i < 15; i++) setFunction(m, 14 - i, 8, ((bits >>> i) & 1) !== 0);
2252
+ for (var i = 0; i < 8; i++) setFunction(m, m.size - 1 - i, 8, ((bits >>> i) & 1) !== 0);
2253
+ for (var i = 8; i < 15; i++) setFunction(m, 8, m.size - 15 + i, ((bits >>> i) & 1) !== 0);
2254
+ setFunction(m, 8, m.size - 8, true);
2255
+ }
2256
+
2257
+ function drawVersionBits(m, ver) {
2258
+ if (ver < 7) return;
2259
+ var rem = ver;
2260
+ for (var i = 0; i < 12; i++) rem = (rem << 1) ^ ((rem >>> 11) * 0x1f25);
2261
+ var bits = (ver << 12) | rem;
2262
+ for (var i = 0; i < 18; i++) {
2263
+ var dark = ((bits >>> i) & 1) !== 0;
2264
+ var a = m.size - 11 + (i % 3);
2265
+ var b = Math.floor(i / 3);
2266
+ setFunction(m, a, b, dark);
2267
+ setFunction(m, b, a, dark);
2268
+ }
2269
+ }
2270
+
2271
+ function drawCodewords(m, codewords) {
2272
+ var bitIndex = 0;
2273
+ var total = codewords.length * 8;
2274
+ for (var right = m.size - 1; right >= 1; right -= 2) {
2275
+ if (right === 6) right = 5;
2276
+ for (var vert = 0; vert < m.size; vert++) {
2277
+ for (var j = 0; j < 2; j++) {
2278
+ var x = right - j;
2279
+ var upward = ((right + 1) & 2) === 0;
2280
+ var y = upward ? m.size - 1 - vert : vert;
2281
+ if (!m.isFunction[y][x] && bitIndex < total) {
2282
+ m.modules[y][x] = ((codewords[bitIndex >>> 3] >>> (7 - (bitIndex & 7))) & 1) !== 0;
2283
+ bitIndex++;
2284
+ }
2285
+ }
2286
+ }
2287
+ }
2288
+ }
2289
+
2290
+ function maskAt(mask, x, y) {
2291
+ switch (mask) {
2292
+ case 0: return (x + y) % 2 === 0;
2293
+ case 1: return y % 2 === 0;
2294
+ case 2: return x % 3 === 0;
2295
+ case 3: return (x + y) % 3 === 0;
2296
+ case 4: return (Math.floor(x / 3) + Math.floor(y / 2)) % 2 === 0;
2297
+ case 5: return (x * y) % 2 + (x * y) % 3 === 0;
2298
+ case 6: return ((x * y) % 2 + (x * y) % 3) % 2 === 0;
2299
+ default: return ((x + y) % 2 + (x * y) % 3) % 2 === 0;
2300
+ }
2301
+ }
2302
+
2303
+ function applyMask(m, mask) {
2304
+ for (var y = 0; y < m.size; y++) {
2305
+ for (var x = 0; x < m.size; x++) {
2306
+ if (!m.isFunction[y][x] && maskAt(mask, x, y)) m.modules[y][x] = !m.modules[y][x];
2307
+ }
2308
+ }
2309
+ }
2310
+
2311
+ function penalty(m) {
2312
+ var score = 0;
2313
+ var size = m.size;
2314
+ var x, y, i;
2315
+ // Rule 1: runs of five or more same-colour modules.
2316
+ for (y = 0; y < size; y++) {
2317
+ var runColor = m.modules[y][0];
2318
+ var runLen = 1;
2319
+ for (x = 1; x < size; x++) {
2320
+ if (m.modules[y][x] === runColor) {
2321
+ runLen++;
2322
+ } else {
2323
+ if (runLen >= 5) score += 3 + (runLen - 5);
2324
+ runColor = m.modules[y][x];
2325
+ runLen = 1;
2326
+ }
2327
+ }
2328
+ if (runLen >= 5) score += 3 + (runLen - 5);
2329
+ }
2330
+ for (x = 0; x < size; x++) {
2331
+ var colColor = m.modules[0][x];
2332
+ var colLen = 1;
2333
+ for (y = 1; y < size; y++) {
2334
+ if (m.modules[y][x] === colColor) {
2335
+ colLen++;
2336
+ } else {
2337
+ if (colLen >= 5) score += 3 + (colLen - 5);
2338
+ colColor = m.modules[y][x];
2339
+ colLen = 1;
2340
+ }
2341
+ }
2342
+ if (colLen >= 5) score += 3 + (colLen - 5);
2343
+ }
2344
+ // Rule 2: 2x2 blocks of one colour.
2345
+ for (y = 0; y < size - 1; y++) {
2346
+ for (x = 0; x < size - 1; x++) {
2347
+ var c = m.modules[y][x];
2348
+ if (c === m.modules[y][x + 1] && c === m.modules[y + 1][x] && c === m.modules[y + 1][x + 1]) score += 3;
2349
+ }
2350
+ }
2351
+ // Rule 3: finder-like 1:1:3:1:1 patterns with four light modules beside.
2352
+ var pattern = [true, false, true, true, true, false, true];
2353
+ var hasPattern = function (get, at) {
2354
+ for (var k = 0; k < 7; k++) {
2355
+ if (get(at + k) !== pattern[k]) return false;
2356
+ }
2357
+ return true;
2358
+ };
2359
+ var lightRun = function (get, at, count) {
2360
+ for (var k = 1; k <= count; k++) {
2361
+ if (at - k < 0) return false;
2362
+ if (get(at - k) !== false) return false;
2363
+ }
2364
+ return true;
2365
+ };
2366
+ for (y = 0; y < size; y++) {
2367
+ for (x = 0; x <= size - 7; x++) {
2368
+ if (hasPattern(function (at) { return m.modules[y][at]; }, x)) {
2369
+ if (lightRun(function (at) { return m.modules[y][at]; }, x, 4)) score += 40;
2370
+ if (x + 11 <= size && lightRun(function (at) { return m.modules[y][at]; }, x + 7, 4)) score += 40;
2371
+ }
2372
+ }
2373
+ }
2374
+ for (x = 0; x < size; x++) {
2375
+ for (y = 0; y <= size - 7; y++) {
2376
+ if (hasPattern(function (at) { return m.modules[at][x]; }, y)) {
2377
+ if (lightRun(function (at) { return m.modules[at][x]; }, y, 4)) score += 40;
2378
+ if (y + 11 <= size && lightRun(function (at) { return m.modules[at][x]; }, y + 7, 4)) score += 40;
2379
+ }
2380
+ }
2381
+ }
2382
+ // Rule 4: deviation from a 50/50 dark ratio.
2383
+ var dark = 0;
2384
+ for (y = 0; y < size; y++) {
2385
+ for (x = 0; x < size; x++) if (m.modules[y][x]) dark++;
2386
+ }
2387
+ var ratio = Math.ceil(Math.abs(dark * 20 - size * size * 10) / (size * size)) - 1;
2388
+ score += ratio * 10;
2389
+ return score;
2390
+ }
2391
+
2392
+ /**
2393
+ * Encode text as a QR module matrix: { size, modules } where modules[y][x]
2394
+ * is true for a dark module.
2395
+ */
2396
+ function qrMatrix(text) {
2397
+ var bytes = utf8Bytes(text);
2398
+ var ver = 0;
2399
+ for (var v = 1; v <= MAX_VERSION; v++) {
2400
+ var ccBits = v <= 9 ? 8 : 16;
2401
+ if (4 + ccBits + bytes.length * 8 <= numDataCodewords(v) * 8) { ver = v; break; }
2402
+ }
2403
+ if (!ver) throw new Error('QR payload too long');
2404
+ var codewords = interleave(splitBlocks(buildCodewords(text, ver), ver));
2405
+ var base = newMatrix(ver * 4 + 17);
2406
+ drawFunctionPatterns(base, ver);
2407
+ drawCodewords(base, codewords);
2408
+ var best = null;
2409
+ for (var mask = 0; mask < 8; mask++) {
2410
+ var candidate = {
2411
+ modules: base.modules.map(function (row) { return row.slice(); }),
2412
+ isFunction: base.isFunction,
2413
+ size: base.size
2414
+ };
2415
+ applyMask(candidate, mask);
2416
+ drawFormatBits(candidate, mask);
2417
+ var score = penalty(candidate);
2418
+ if (!best || score < best.score) best = { score: score, matrix: candidate };
2419
+ }
2420
+ return { size: best.matrix.size, modules: best.matrix.modules };
2421
+ }
2422
+
2423
+ /** Render text as an inline SVG QR code (no external assets). */
2424
+ function qrSvg(text) {
2425
+ var qr = qrMatrix(text);
2426
+ var margin = 4;
2427
+ var size = qr.size;
2428
+ var parts = [];
2429
+ for (var y = 0; y < size; y++) {
2430
+ var x = 0;
2431
+ while (x < size) {
2432
+ if (qr.modules[y][x]) {
2433
+ var run = 1;
2434
+ while (x + run < size && qr.modules[y][x + run]) run++;
2435
+ parts.push('M' + x + ' ' + y + 'h' + run + 'v1h-' + run + 'z');
2436
+ x += run;
2437
+ } else {
2438
+ x++;
2439
+ }
2440
+ }
2441
+ }
2442
+ var dim = size + margin * 2;
2443
+ return '<svg xmlns="http://www.w3.org/2000/svg" viewBox="' + (-margin) + ' ' + (-margin) + ' ' + dim + ' ' + dim +
2444
+ '" shape-rendering="crispEdges" role="img" aria-label="Subscription QR code" class="qr-svg">' +
2445
+ '<rect x="' + (-margin) + '" y="' + (-margin) + '" width="' + dim + '" height="' + dim + '" fill="#ffffff"/>' +
2446
+ '<path d="' + parts.join('') + '" fill="#000000"/></svg>';
2447
+ }
2448
+
2449
+ // \u2500\u2500 Subscription deep links \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
2450
+
2451
+ /** The feed's own directory URL, as served. */
2452
+ function feedUrl() {
2453
+ return new URL('.', window.location.href).href;
2454
+ }
2455
+
2456
+ /**
2457
+ * Subscription deep link for the whole feed, or for one notebook
2458
+ * (the chunk id's slug, e.g. notebook.cat1 \u2192 cat1).
2459
+ */
2460
+ function subscribeUrl(notebookId) {
2461
+ var url = APP_ORIGIN + '/subscribe?source=' + encodeURIComponent(feedUrl());
2462
+ if (notebookId) {
2463
+ url += '&notebook=' + encodeURIComponent(String(notebookId).replace(/^notebook\\./, ''));
2464
+ }
2465
+ return url;
2466
+ }
2467
+
2468
+ function each(root, selector, fn) {
2469
+ var nodes = root.querySelectorAll(selector);
2470
+ for (var i = 0; i < nodes.length; i++) fn(nodes[i]);
2471
+ }
2472
+
2473
+ function render(root) {
2474
+ var feed = subscribeUrl(null);
2475
+ each(root, '[data-subscribe-feed]', function (el) { el.setAttribute('href', feed); });
2476
+ each(root, '[data-subscribe-notebook]', function (el) {
2477
+ el.setAttribute('href', subscribeUrl(el.getAttribute('data-subscribe-notebook')));
2478
+ });
2479
+ each(root, '[data-qr-feed]', function (el) { el.innerHTML = qrSvg(feed); });
2480
+ each(root, '[data-qr-notebook]', function (el) {
2481
+ el.innerHTML = qrSvg(subscribeUrl(el.getAttribute('data-qr-notebook')));
2482
+ });
2483
+ }
2484
+
2485
+ var api = { feedUrl: feedUrl, subscribeUrl: subscribeUrl, qrSvg: qrSvg, qrMatrix: qrMatrix, render: render };
2486
+ window.wodFeedLanding = api;
2487
+
2488
+ if (typeof document !== 'undefined') {
2489
+ if (document.readyState === 'loading') {
2490
+ document.addEventListener('DOMContentLoaded', function () { render(document); });
2491
+ } else {
2492
+ render(document);
2493
+ }
2494
+ }
2495
+ })();`;
2496
+
2497
+ // src/feed/landing.ts
2498
+ function escapeHtml(s) {
2499
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
2500
+ }
2501
+ function isoDate(ms) {
2502
+ if (ms === void 0 || !Number.isFinite(ms)) return "";
2503
+ const d = new Date(ms);
2504
+ return Number.isNaN(d.getTime()) ? "" : d.toISOString().slice(0, 10);
2505
+ }
2506
+ function chunkRowHtml(c) {
2507
+ const kind = c.kind ?? "notes";
2508
+ return `<tr><td>${escapeHtml(c.id)}</td><td>${kind}</td><td>${c.count}</td><td>${(c.bytes / 1024).toFixed(1)} KB</td><td><code>${c.sha256.slice(0, 8)}</code></td></tr>`;
2509
+ }
2510
+ function noteHtml(note) {
2511
+ const date = isoDate(note.date);
2512
+ const dataTag = note.publicSessions && note.publicSessions > 0 ? ` \xB7 <strong>+${note.publicSessions} session${note.publicSessions === 1 ? "" : "s"}</strong>` : "";
2513
+ const meta = [date, `<code>${escapeHtml(note.path)}</code>`].filter(Boolean).join(" \xB7 ");
2514
+ const source = note.content ? `<details><summary>source</summary><pre>${escapeHtml(note.content)}</pre></details>` : "";
2515
+ const record = note.recordPath ? ` \xB7 <a href="${escapeHtml(note.recordPath)}">record</a>` : "";
2516
+ return ` <li><span class="title">${escapeHtml(note.title)}</span> <span class="meta">${meta}${record}${dataTag}</span>${source}</li>`;
2517
+ }
2518
+ function notebookHtml(notebook) {
2519
+ const notes = notebook.notes.map(noteHtml).join("\n");
2520
+ return ` <section class="notebook">
2521
+ <h3>${escapeHtml(notebook.label)} <small>${escapeHtml(notebook.id)} \xB7 ${notebook.notes.length} note${notebook.notes.length === 1 ? "" : "s"}</small></h3>
2522
+ <p class="subscribe-row"><a class="subscribe" data-subscribe-notebook="${escapeHtml(notebook.id)}">Subscribe to Notebook</a> <details class="qr"><summary>QR</summary><div class="qr-body" data-qr-notebook="${escapeHtml(notebook.id)}"></div></details></p>
2523
+ <ul>
2524
+ ${notes}
2525
+ </ul>
2526
+ </section>`;
2527
+ }
2528
+ function renderFeedLandingHtml(data) {
2529
+ const { manifest, totalMs, passMs, fileCount, notebooks, appOrigin = APP_ORIGIN } = data;
2530
+ const totalBytes = manifest.chunks.reduce((s, c) => s + c.bytes, 0);
2531
+ const totalNotes = notebooks.reduce((s, n) => s + n.notes.length, 0);
2532
+ const dirtyBadge = manifest.dirty ? ' <strong style="color:#b45309">(dirty working tree \u2014 not reproducible from <code>' + escapeHtml(manifest.commit ?? "") + "</code>)</strong>" : "";
2533
+ const title = manifest.name ? `${manifest.name} \u2014 feed` : "Feed";
2534
+ const description = manifest.description ? `<p class="desc">${escapeHtml(manifest.description)}</p>` : "";
2535
+ const repoLink = manifest.repositoryUrl ? `<p class="meta"><a href="${escapeHtml(manifest.repositoryUrl)}">${escapeHtml(manifest.repositoryUrl)}</a></p>` : "";
2536
+ const contents = notebooks.length ? notebooks.map(notebookHtml).join("\n") : ' <p class="meta">This feed publishes no notebooks yet.</p>';
2537
+ return `<!doctype html>
2538
+ <html lang="en">
2539
+ <head>
2540
+ <meta charset="utf-8" />
2541
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
2542
+ <title>${escapeHtml(title)}</title>
2543
+ <style>
2544
+ body { font-family: system-ui, sans-serif; max-width: 960px; margin: 2rem auto; padding: 0 1rem; color: #1f2937; }
2545
+ h1 { font-size: 1.4rem; } h2 { font-size: 1.1rem; margin-top: 2rem; }
2546
+ h3 { font-size: 1rem; margin: 1.25rem 0 .25rem; }
2547
+ table { border-collapse: collapse; width: 100%; font-size: 0.9rem; }
2548
+ th, td { text-align: left; padding: 0.3rem 0.6rem; border-bottom: 1px solid #e5e7eb; }
2549
+ code { font-size: 0.85em; }
2550
+ dl { display: grid; grid-template-columns: max-content 1fr; gap: 0.2rem 1rem; font-size: 0.95rem; }
2551
+ dt { font-weight: 600; }
2552
+ ul { list-style: none; padding-left: 0; margin: .25rem 0 0; }
2553
+ li { padding: .35rem 0; border-bottom: 1px solid #e5e7eb; }
2554
+ li .title { font-weight: 600; }
2555
+ .meta { color: #6b7280; font-size: 0.85rem; }
2556
+ .desc { font-size: 1rem; }
2557
+ pre { overflow-x: auto; background: #f3f4f6; padding: 0.6rem; border-radius: 0.25rem; font-size: 0.8rem; }
2558
+ summary { cursor: pointer; color: #6b7280; font-size: 0.85rem; }
2559
+ small { font-weight: 400; color: #6b7280; }
2560
+ .subscribe { display: inline-block; padding: .4rem .8rem; border: 1px solid #1f2937; border-radius: .25rem; color: #1f2937; text-decoration: none; font-size: .9rem; }
2561
+ .subscribe.primary { background: #1f2937; color: #fff; }
2562
+ .subscribe-row { margin: .4rem 0 .2rem; }
2563
+ .qr { display: inline-block; vertical-align: middle; margin-left: .5rem; }
2564
+ .qr-body { padding: .4rem 0; }
2565
+ .qr-svg { width: 132px; height: 132px; display: block; }
2566
+ </style>
2567
+ </head>
2568
+ <body>
2569
+ <h1>${escapeHtml(manifest.name ?? "Feed")}</h1>
2570
+ ${description}
2571
+ ${repoLink}
2572
+ <p class="meta"><a href="manifest.json">manifest.json</a> \u2014 the artifact subscribers import.</p>
2573
+ <section class="subscribe">
2574
+ <a class="subscribe primary" data-subscribe-feed>Subscribe to Whole Feed</a>
2575
+ <details class="qr"><summary>QR</summary><div class="qr-body" data-qr-feed></div></details>
2576
+ <p class="meta">Opens Wod.Wiki and subscribes to every notebook this feed publishes. <noscript>JavaScript is off \u2014 subscribe from Wod.Wiki with this feed's URL.</noscript></p>
2577
+ </section>
2578
+ <h2>Contents</h2>
2579
+ <p class="meta">${notebooks.length} notebook${notebooks.length === 1 ? "" : "s"} \xB7 ${totalNotes} note${totalNotes === 1 ? "" : "s"}</p>
2580
+ ${contents}
2581
+ <h2>Version</h2>
2582
+ <dl>
2583
+ <dt>version</dt><dd>${manifest.version} <code>${escapeHtml(manifest.versionLabel ?? "")}</code>${dirtyBadge}</dd>
2584
+ <dt>commit</dt><dd><code>${escapeHtml(manifest.commit ?? "unknown")}</code></dd>
2585
+ <dt>built at</dt><dd>${escapeHtml(manifest.builtAt)}</dd>
2586
+ <dt>schema</dt><dd>v${manifest.schema}</dd>
2587
+ </dl>
2588
+ <h2>Build report</h2>
2589
+ <dl>
2590
+ <dt>total</dt><dd>${totalMs} ms</dd>
2591
+ <dt>corpus scan + partition</dt><dd>${passMs.scan} ms (${fileCount} files)</dd>
2592
+ <dt>block-index derivation</dt><dd>${passMs.blockIndex} ms</dd>
2593
+ <dt>block syntax gate</dt><dd>${passMs.parseGate} ms</dd>
2594
+ <dt>block-efforts derivation</dt><dd>${passMs.blockEfforts} ms</dd>
2595
+ <dt>chunk writes</dt><dd>${passMs.write} ms</dd>
2596
+ </dl>
2597
+ <h2>Chunks (${manifest.chunks.length}, ${(totalBytes / 1024).toFixed(0)} KB total)</h2>
2598
+ <table>
2599
+ <thead><tr><th>id</th><th>kind</th><th>rows</th><th>size</th><th>sha256</th></tr></thead>
2600
+ <tbody>
2601
+ ${manifest.chunks.map(chunkRowHtml).join("\n")}
2602
+ </tbody>
2603
+ </table>
2604
+ <script id="${QR_SCRIPT_ID}">
2605
+ ${qrInlineScript(appOrigin)}
2606
+ </script>
2607
+ </body>
2608
+ </html>
2609
+ `;
2610
+ }
2611
+
2612
+ // src/feed/tree.ts
2613
+ var FeedTreeError = class extends Error {
2614
+ constructor(code, message) {
2615
+ super(message);
2616
+ this.code = code;
2617
+ this.name = "FeedTreeError";
2618
+ }
2619
+ code;
2620
+ };
2621
+ var encoder = new TextEncoder();
2622
+ var decoder = new TextDecoder();
2623
+ function encodeUtf8(text) {
2624
+ return encoder.encode(text);
2625
+ }
2626
+ function decodeUtf8(bytes) {
2627
+ return decoder.decode(bytes);
2628
+ }
2629
+ function normalizeFeedTreePath(rawPath) {
2630
+ if (!rawPath || rawPath.includes("\0") || rawPath.includes("\\")) {
2631
+ throw new FeedTreeError("layout", `Invalid feed path '${rawPath}'`);
2632
+ }
2633
+ const trimmed = rawPath.replace(/^\/+|\/+$/g, "");
2634
+ if (!trimmed) {
2635
+ throw new FeedTreeError("layout", "Feed path must not be empty");
2636
+ }
2637
+ const parts = trimmed.split("/");
2638
+ for (const part of parts) {
2639
+ if (!part || part === "." || part === "..") {
2640
+ throw new FeedTreeError("layout", `Disallowed path segment in '${rawPath}'`);
2641
+ }
2642
+ }
2643
+ return parts.join("/");
2644
+ }
2645
+ async function sha256HexAsync(input) {
2646
+ const data = typeof input === "string" ? encoder.encode(input) : input;
2647
+ const copy = new Uint8Array(data.byteLength);
2648
+ copy.set(data);
2649
+ const digest = await crypto.subtle.digest("SHA-256", copy.buffer);
2650
+ return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join("");
2651
+ }
2652
+ var MemoryFeedTree = class {
2653
+ store = /* @__PURE__ */ new Map();
2654
+ constructor(initial) {
2655
+ if (initial) {
2656
+ for (const [k, v] of Object.entries(initial)) {
2657
+ const p = normalizeFeedTreePath(k);
2658
+ this.store.set(p, typeof v === "string" ? encodeUtf8(v) : new Uint8Array(v));
2659
+ }
2660
+ }
2661
+ }
2662
+ async read(path) {
2663
+ const p = normalizeFeedTreePath(path);
2664
+ const bytes = this.store.get(p);
2665
+ if (!bytes) throw new FeedTreeError("not-found", `Missing feed entry: ${p}`);
2666
+ return new Uint8Array(bytes);
2667
+ }
2668
+ async readText(path) {
2669
+ return decodeUtf8(await this.read(path));
2670
+ }
2671
+ async stat(path) {
2672
+ const p = normalizeFeedTreePath(path);
2673
+ const bytes = this.store.get(p);
2674
+ if (!bytes) return void 0;
2675
+ return {
2676
+ bytes: bytes.byteLength,
2677
+ sha256: await sha256HexAsync(bytes)
2678
+ };
2679
+ }
2680
+ async write(path, bytes) {
2681
+ const p = normalizeFeedTreePath(path);
2682
+ const copy = new Uint8Array(bytes.byteLength);
2683
+ copy.set(bytes);
2684
+ this.store.set(p, copy);
2685
+ }
2686
+ async writeText(path, text) {
2687
+ await this.write(path, encodeUtf8(text));
2688
+ }
2689
+ async delete(path) {
2690
+ const p = normalizeFeedTreePath(path);
2691
+ this.store.delete(p);
2692
+ }
2693
+ async list(prefix = "") {
2694
+ const clean = prefix ? normalizeFeedTreePath(prefix) + "/" : "";
2695
+ return [...this.store.keys()].filter((k) => !clean || k.startsWith(clean) || k === clean.slice(0, -1)).sort();
2696
+ }
2697
+ entries() {
2698
+ return [...this.store.entries()].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
2699
+ }
2700
+ };
2701
+ var HttpFeedTree = class {
2702
+ baseUrl;
2703
+ fetchImpl;
2704
+ constructor(baseUrl, fetchImpl) {
2705
+ this.baseUrl = baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`;
2706
+ this.fetchImpl = fetchImpl ?? ((input, init) => globalThis.fetch(input, init));
2707
+ }
2708
+ async read(path) {
2709
+ const clean = normalizeFeedTreePath(path);
2710
+ const isMutableIndex = clean === "manifest.json" || clean.endsWith("/manifest.json");
2711
+ const doFetch = this.fetchImpl;
2712
+ const res = await doFetch(`${this.baseUrl}${clean}`, {
2713
+ cache: isMutableIndex ? "no-cache" : "default"
2714
+ });
2715
+ if (res.status === 404) {
2716
+ throw new FeedTreeError("not-found", `HTTP 404 for ${this.baseUrl}${clean}`);
2717
+ }
2718
+ if (!res.ok) {
2719
+ throw new FeedTreeError("permission", `HTTP ${res.status} fetching ${this.baseUrl}${clean}`);
2720
+ }
2721
+ return new Uint8Array(await res.arrayBuffer());
2722
+ }
2723
+ async readJson(path) {
2724
+ const text = decodeUtf8(await this.read(path));
2725
+ return JSON.parse(text);
2726
+ }
2727
+ async stat(path) {
2728
+ try {
2729
+ const bytes = await this.read(path);
2730
+ return { bytes: bytes.byteLength, sha256: await sha256HexAsync(bytes) };
2731
+ } catch (err) {
2732
+ if (err instanceof FeedTreeError && err.code === "not-found") return void 0;
2733
+ throw err;
2734
+ }
2735
+ }
2736
+ };
2737
+ var DirectoryHandleFeedTree = class {
2738
+ constructor(root) {
2739
+ this.root = root;
2740
+ }
2741
+ root;
2742
+ async resolveDir(segments, create) {
2743
+ let dir = this.root;
2744
+ for (const seg of segments) {
2745
+ dir = await dir.getDirectoryHandle(seg, { create });
2746
+ }
2747
+ return dir;
2748
+ }
2749
+ async read(path) {
2750
+ const clean = normalizeFeedTreePath(path);
2751
+ const parts = clean.split("/");
2752
+ const fileName = parts.pop();
2753
+ try {
2754
+ const dir = await this.resolveDir(parts, false);
2755
+ const handle = await dir.getFileHandle(fileName, { create: false });
2756
+ const file = await handle.getFile();
2757
+ return new Uint8Array(await file.arrayBuffer());
2758
+ } catch {
2759
+ throw new FeedTreeError("not-found", `Missing file '${clean}' in directory handle`);
2760
+ }
2761
+ }
2762
+ async stat(path) {
2763
+ try {
2764
+ const bytes = await this.read(path);
2765
+ return { bytes: bytes.byteLength, sha256: await sha256HexAsync(bytes) };
2766
+ } catch (err) {
2767
+ if (err instanceof FeedTreeError && err.code === "not-found") return void 0;
2768
+ throw err;
2769
+ }
2770
+ }
2771
+ async write(path, bytes) {
2772
+ const clean = normalizeFeedTreePath(path);
2773
+ const parts = clean.split("/");
2774
+ const fileName = parts.pop();
2775
+ try {
2776
+ const dir = await this.resolveDir(parts, true);
2777
+ const handle = await dir.getFileHandle(fileName, { create: true });
2778
+ const writable = await handle.createWritable();
2779
+ await writable.write(bytes);
2780
+ await writable.close();
2781
+ } catch (err) {
2782
+ throw new FeedTreeError(
2783
+ "permission",
2784
+ `Could not write '${clean}': ${err instanceof Error ? err.message : String(err)}`
2785
+ );
2786
+ }
2787
+ }
2788
+ async delete(path) {
2789
+ const clean = normalizeFeedTreePath(path);
2790
+ const parts = clean.split("/");
2791
+ const fileName = parts.pop();
2792
+ try {
2793
+ const dir = await this.resolveDir(parts, false);
2794
+ await dir.removeEntry(fileName);
2795
+ } catch {
2796
+ }
2797
+ }
2798
+ };
2799
+ var PUBLISHED_FEED_META_KEY = "publish:local-feed";
2800
+ function slugStem(raw, fallback) {
2801
+ const clean = raw.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
2802
+ return clean || fallback;
2803
+ }
2804
+ function repoWorkflowYaml() {
2805
+ return `name: Publish feed
2806
+
2807
+ on:
2808
+ push:
2809
+ branches: [main]
2810
+ workflow_dispatch:
2811
+
2812
+ permissions:
2813
+ contents: read
2814
+ pages: write
2815
+ id-token: write
2816
+
2817
+ concurrency:
2818
+ group: pages
2819
+ cancel-in-progress: true
2820
+
2821
+ jobs:
2822
+ publish:
2823
+ runs-on: ubuntu-latest
2824
+ environment:
2825
+ name: github-pages
2826
+ url: \${{ steps.deployment.outputs.page_url }}
2827
+ steps:
2828
+ - uses: actions/checkout@v4
2829
+ with:
2830
+ fetch-depth: 0
2831
+ - uses: oven-sh/setup-bun@v2
2832
+ with:
2833
+ bun-version: 1.4.x
2834
+ - name: Install dependencies
2835
+ run: bun install
2836
+ - name: Build seed
2837
+ run: bunx wod build . --output dist
2838
+ - uses: actions/configure-pages@v5
2839
+ - name: Upload dist
2840
+ uses: actions/upload-pages-artifact@v3
2841
+ with:
2842
+ path: dist
2843
+ - id: deployment
2844
+ uses: actions/deploy-pages@v4
2845
+ `;
2846
+ }
2847
+ function repoPackageJson(name, description, repositoryUrl) {
2848
+ const pkg = {
2849
+ name: slugStem(name, "wod-wiki-feed"),
2850
+ version: "0.1.0",
2851
+ private: true,
2852
+ ...description ? { description } : {},
2853
+ ...repositoryUrl ? { repository: { type: "git", url: repositoryUrl } } : {},
2854
+ scripts: {
2855
+ build: "wod build . --output dist"
2856
+ },
2857
+ devDependencies: {
2858
+ "@bitcobblers/wod-wiki-tools": `^${VERSION}`
2859
+ }
2860
+ };
2861
+ return JSON.stringify(pkg, null, 2) + "\n";
2862
+ }
2863
+ function repoReadmeMarkdown(name, description) {
2864
+ return `# ${name}
2865
+
2866
+ ${description ?? "A WOD Wiki workout feed compiled from authored Markdown notes and optional companion JSONL session logs."}
2867
+
2868
+ ## Layout
2869
+
2870
+ - \`markdown/notebooks/<slug>/*.md\` \u2014 Canonical workout & note Markdown with YAML frontmatter.
2871
+ - \`markdown/notebooks/<slug>/*.jsonl\` \u2014 Optional companion Session, BlockRevision, and EventRecord telemetry (present only for Sessions explicitly marked public).
2872
+ - \`dist/\` \u2014 Pre-compiled static Seed artifacts (\`manifest.json\`, \`indexes/\`, \`chunks/\`, \`index.html\`), ready for static hosting or rebuilt on push via GitHub Actions.
2873
+ `;
2874
+ }
2875
+ async function compileSeedRowForNote(params) {
2876
+ const {
2877
+ notePath,
2878
+ content,
2879
+ title,
2880
+ createdAt,
2881
+ routeId,
2882
+ sourceId,
2883
+ publicSessions,
2884
+ eventsBySession,
2885
+ revisionsByKey,
2886
+ referenceIndex
2887
+ } = params;
2888
+ const uuid = await seedNoteId(notePath);
2889
+ let ordinal = 0;
2890
+ const blocks = wodWikiCore.reconcileNoteBlocks(content, {
2891
+ sourceRevision: 1,
2892
+ registeredWidgets: SEED_REGISTERED_WIDGETS,
2893
+ createId: () => `seed:${notePath}:${ordinal++}`
2894
+ });
2895
+ const sections = wodWikiCore.parseDocumentSections(content, { registeredWidgets: SEED_REGISTERED_WIDGETS });
2896
+ const blockIndex = Object.values(blocks).map((block, position) => {
2897
+ const section = sections.find((s) => s.from === block.from && s.to === block.to);
2898
+ const fingerprint = block.kind === "wod" ? wodWikiCore.blockContentId(section?.scriptBlock?.content ?? content.slice(block.from, block.to)) : void 0;
2899
+ return {
2900
+ id: `${uuid}:${block.id}`,
2901
+ noteId: uuid,
2902
+ blockId: block.id,
2903
+ blockVersion: 1,
2904
+ sourceRevision: 1,
2905
+ from: block.from,
2906
+ to: block.to,
2907
+ position,
2908
+ dataType: block.kind,
2909
+ ...fingerprint ? { blockContentId: fingerprint } : {},
2910
+ rawContent: content.slice(block.from, block.to),
2911
+ noteTitle: title,
2912
+ createdAt,
2913
+ isStatic: true,
2914
+ ...sourceId ? { sourceId } : {},
2915
+ sourcePath: notePath,
2916
+ ...routeId ? { routeId } : {}
2917
+ };
2918
+ });
2919
+ const blockEfforts = [];
2920
+ const blockEquipment = [];
2921
+ for (const proj of blockIndex) {
2922
+ if (proj.dataType !== "wod" || !proj.rawContent) continue;
2923
+ const sec = wodWikiCore.parseDocumentSections(proj.rawContent, { registeredWidgets: SEED_REGISTERED_WIDGETS }).find(
2924
+ (s) => s.scriptBlock
2925
+ );
2926
+ const parsed = wodWikiLang.parseScript(sec?.scriptBlock?.content ?? proj.rawContent, { references: referenceIndex });
2927
+ const refs = wodWikiLang.extractStatementRefs(parsed.statements);
2928
+ const seenEfforts = /* @__PURE__ */ new Set();
2929
+ for (const rawSlug of refs.efforts) {
2930
+ const canonical = referenceIndex.resolveEffort(rawSlug)?.slug;
2931
+ if (!canonical || seenEfforts.has(canonical)) continue;
2932
+ seenEfforts.add(canonical);
2933
+ blockEfforts.push({
2934
+ id: `${proj.id}:${canonical}`,
2935
+ noteId: uuid,
2936
+ blockId: proj.blockId,
2937
+ blockContentId: proj.blockContentId,
2938
+ effortSlug: canonical,
2939
+ isStatic: true,
2940
+ sourcePath: notePath,
2941
+ createdAt
2942
+ });
2943
+ }
2944
+ const seenEquipment = /* @__PURE__ */ new Set();
2945
+ for (const rawSlug of refs.equipment) {
2946
+ const canonical = referenceIndex.resolveEquipment(rawSlug)?.slug;
2947
+ if (!canonical || seenEquipment.has(canonical)) continue;
2948
+ seenEquipment.add(canonical);
2949
+ blockEquipment.push({
2950
+ id: `${proj.id}:${canonical}`,
2951
+ noteId: uuid,
2952
+ blockId: proj.blockId,
2953
+ blockContentId: proj.blockContentId,
2954
+ equipmentSlug: canonical,
2955
+ isStatic: true,
2956
+ sourcePath: notePath,
2957
+ createdAt
2958
+ });
2959
+ }
2960
+ }
2961
+ const wodProjections = blockIndex.filter((b) => b.dataType === "wod");
2962
+ const remappedSessions = [];
2963
+ const remappedEvents = [];
2964
+ const remappedRevisions = [];
2965
+ const seenRevKeys = /* @__PURE__ */ new Set();
2966
+ for (const s of publicSessions) {
2967
+ const matchedProj = wodProjections.find((p) => p.blockContentId && p.blockContentId === s.blockContentId) ?? wodProjections[0];
2968
+ if (!matchedProj || !matchedProj.blockContentId) continue;
2969
+ const mappedSession = {
2970
+ ...s,
2971
+ noteId: uuid,
2972
+ blockId: matchedProj.blockId,
2973
+ blockVersion: 1,
2974
+ blockContentId: matchedProj.blockContentId,
2975
+ public: true
2976
+ };
2977
+ remappedSessions.push(mappedSession);
2978
+ const revKey = `${s.noteId}\0${s.blockId}\0${s.blockVersion}`;
2979
+ const origRev = revisionsByKey.get(revKey);
2980
+ const targetRevKey = `${uuid}\0${matchedProj.blockId}\x001`;
2981
+ if (!seenRevKeys.has(targetRevKey)) {
2982
+ seenRevKeys.add(targetRevKey);
2983
+ remappedRevisions.push({
2984
+ noteId: uuid,
2985
+ blockId: matchedProj.blockId,
2986
+ version: 1,
2987
+ kind: "wod",
2988
+ rawContent: matchedProj.rawContent,
2989
+ savedAt: origRev?.savedAt ?? s.createdAt,
2990
+ dialect: blocks[matchedProj.blockId]?.dialect ?? origRev?.dialect ?? "time",
2991
+ ...blocks[matchedProj.blockId]?.sport ? { sport: blocks[matchedProj.blockId].sport } : {}
2992
+ });
2993
+ }
2994
+ for (const ev of eventsBySession.get(s.id) ?? []) {
2995
+ remappedEvents.push({
2996
+ ...ev,
2997
+ noteId: uuid,
2998
+ blockId: matchedProj.blockId,
2999
+ blockVersion: 1,
3000
+ blockContentId: matchedProj.blockContentId
3001
+ });
3002
+ }
3003
+ }
3004
+ const telemetry = remappedSessions.length > 0 ? { sessions: remappedSessions, events: remappedEvents } : void 0;
3005
+ const companionBundle = remappedSessions.length > 0 ? {
3006
+ revisions: remappedRevisions,
3007
+ sessions: remappedSessions,
3008
+ events: remappedEvents
3009
+ } : void 0;
3010
+ const row = {
3011
+ path: notePath,
3012
+ content,
3013
+ blocks,
3014
+ blockIndex,
3015
+ blockEfforts,
3016
+ blockEquipment,
3017
+ uuid,
3018
+ commit: "",
3019
+ version: 1,
3020
+ ...telemetry ? { telemetry } : {}
3021
+ };
3022
+ return { row, uuid, companionBundle };
3023
+ }
3024
+ async function collectPublicStorageState(storage, options = {}) {
3025
+ let allLinks = [];
3026
+ try {
3027
+ allLinks = await storage.readonly("notebook_links").getAll();
3028
+ } catch {
3029
+ }
3030
+ const [allNotes, allSessions, allEvents, allRevisions, efforts, equipment, storedMeta] = await Promise.all([
3031
+ storage.readonly("notes").getAll(),
3032
+ storage.readonly("sessions").getAll(),
3033
+ storage.readonly("events").getAll(),
3034
+ storage.readonly("block_revisions").getAll(),
3035
+ storage.readonly("efforts").getAll(),
3036
+ storage.readonly("equipment").getAll(),
3037
+ storage.readonly("meta").get(PUBLISHED_FEED_META_KEY)
3038
+ ]);
3039
+ const notesById = new Map(allNotes.map((n) => [n.id, n]));
3040
+ const landingsBySlug = /* @__PURE__ */ new Map();
3041
+ for (const n of allNotes) {
3042
+ if (wodWikiCore.isPublishableNotebookLanding(n)) {
3043
+ landingsBySlug.set(wodWikiCore.notebookSlugFromId(n.id), n);
3044
+ }
3045
+ }
3046
+ const filterSlug = options.notebookSlug ? wodWikiCore.notebookSlugFromId(options.notebookSlug) : void 0;
3047
+ const notebooks = /* @__PURE__ */ new Map();
3048
+ for (const [slug, landing] of landingsBySlug.entries()) {
3049
+ if (filterSlug && slug !== filterSlug) continue;
3050
+ const isPublic = landing.public === true || filterSlug === slug && options.includePrivateWhenFiltered === true;
3051
+ if (!isPublic) continue;
3052
+ const fm = readFrontmatterMeta(landing.rawContent);
3053
+ const desc = typeof fm["description"] === "string" ? fm["description"].replace(/^"|"$/g, "") : void 0;
3054
+ notebooks.set(slug, {
3055
+ landing,
3056
+ label: landing.title || slug,
3057
+ description: desc,
3058
+ notes: []
3059
+ });
3060
+ }
3061
+ const noteLinkSlugsByNoteId = /* @__PURE__ */ new Map();
3062
+ for (const link of allLinks) {
3063
+ if (link.targetKind !== "note") continue;
3064
+ const set = noteLinkSlugsByNoteId.get(link.noteId) ?? /* @__PURE__ */ new Set();
3065
+ set.add(wodWikiCore.notebookSlugFromId(link.notebookId));
3066
+ noteLinkSlugsByNoteId.set(link.noteId, set);
3067
+ }
3068
+ for (const note of allNotes) {
3069
+ if (note.id.startsWith("notebook/") && note.notebookId === note.id) continue;
3070
+ if (wodWikiCore.isPublishableNotebookLanding(note)) continue;
3071
+ if (note.feedOrigin === "feed" || note.seedOrigin === "seed") {
3072
+ if (!filterSlug || !options.includePrivateWhenFiltered) continue;
3073
+ }
3074
+ const candidateSlugs = /* @__PURE__ */ new Set();
3075
+ const noteFm = readFrontmatterMeta(note.rawContent);
3076
+ const fmNotebook = (typeof noteFm["notebook"] === "string" ? noteFm["notebook"] : void 0) ?? (typeof noteFm["catalog"] === "string" ? noteFm["catalog"] : void 0);
3077
+ if (fmNotebook) candidateSlugs.add(wodWikiCore.notebookSlugFromId(fmNotebook));
3078
+ for (const nbId of wodWikiWql.notebooksOfItem(note)) {
3079
+ candidateSlugs.add(wodWikiCore.notebookSlugFromId(nbId));
3080
+ }
3081
+ if (note.sourceId) {
3082
+ const srcSlug = wodWikiWql.notebookSlugOfSourceId(note.sourceId);
3083
+ if (srcSlug) candidateSlugs.add(srcSlug);
3084
+ }
3085
+ for (const linkedSlug of noteLinkSlugsByNoteId.get(note.id) ?? []) {
3086
+ candidateSlugs.add(linkedSlug);
3087
+ }
3088
+ for (const slug of candidateSlugs) {
3089
+ if (!slug || wodWikiCore.isNonPublishableNotebook(slug)) continue;
3090
+ if (filterSlug && slug !== filterSlug) continue;
3091
+ let group = notebooks.get(slug);
3092
+ if (!group && options.includePrivateWhenFiltered) {
3093
+ group = { label: slug, notes: [] };
3094
+ notebooks.set(slug, group);
3095
+ }
3096
+ if (!group) continue;
3097
+ if (!group.notes.some((existing) => existing.id === note.id)) {
3098
+ group.notes.push(note);
3099
+ }
3100
+ }
3101
+ }
3102
+ for (const group of notebooks.values()) {
3103
+ group.notes.sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
3104
+ }
3105
+ const publicSessionsByNote = /* @__PURE__ */ new Map();
3106
+ const includedSessionIds = /* @__PURE__ */ new Set();
3107
+ for (const s of allSessions) {
3108
+ if (s.public !== true) continue;
3109
+ const list = publicSessionsByNote.get(s.noteId) ?? [];
3110
+ list.push(s);
3111
+ publicSessionsByNote.set(s.noteId, list);
3112
+ includedSessionIds.add(s.id);
3113
+ }
3114
+ for (const list of publicSessionsByNote.values()) {
3115
+ list.sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
3116
+ }
3117
+ const eventsBySession = /* @__PURE__ */ new Map();
3118
+ for (const ev of allEvents) {
3119
+ if (!includedSessionIds.has(ev.resultId)) continue;
3120
+ const list = eventsBySession.get(ev.resultId) ?? [];
3121
+ list.push(ev);
3122
+ eventsBySession.set(ev.resultId, list);
3123
+ }
3124
+ for (const list of eventsBySession.values()) {
3125
+ list.sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
3126
+ }
3127
+ const revisionsByKey = /* @__PURE__ */ new Map();
3128
+ for (const rev of allRevisions) {
3129
+ revisionsByKey.set(`${rev.noteId}\0${rev.blockId}\0${rev.version}`, rev);
3130
+ }
3131
+ const isCheckpoint = (v) => typeof v === "object" && v !== null && "key" in v && v.key === PUBLISHED_FEED_META_KEY;
3132
+ const storedCheckpoint = isCheckpoint(storedMeta) ? storedMeta : void 0;
3133
+ return {
3134
+ notebooks,
3135
+ publicSessionsByNote,
3136
+ eventsBySession,
3137
+ revisionsByKey,
3138
+ efforts,
3139
+ equipment,
3140
+ notesById,
3141
+ storedCheckpoint
3142
+ };
3143
+ }
3144
+ async function publishFeedFromStorage(storage, tree, options = {}) {
3145
+ const t0 = Date.now();
3146
+ const layout = options.layout ?? "feed";
3147
+ const state = await collectPublicStorageState(storage, options);
3148
+ if (state.notebooks.size === 0) {
3149
+ throw new Error("No public notebooks found to publish. Mark at least one user-owned notebook as Public first.");
3150
+ }
3151
+ const globalCatalog = await resolveScopedPropertyCatalog(storage, { mode: "custom-runtime" });
3152
+ const mergedEffortsBySlug = new Map(state.efforts.map((e) => [e.slug, e]));
3153
+ for (const eff of globalCatalog.efforts) mergedEffortsBySlug.set(eff.slug, eff);
3154
+ const mergedEquipBySlug = new Map(state.equipment.map((e) => [e.slug, e]));
3155
+ for (const eq of globalCatalog.equipment) mergedEquipBySlug.set(eq.slug, eq);
3156
+ const referenceIndex = wodWikiLang.createReferenceIndex({
3157
+ efforts: [...mergedEffortsBySlug.values()],
3158
+ equipment: [...mergedEquipBySlug.values()]
3159
+ });
3160
+ const nextVersion = options.version ?? (state.storedCheckpoint?.version ?? 0) + 1;
3161
+ const builtAt = options.builtAt ?? (/* @__PURE__ */ new Date()).toISOString();
3162
+ const artifactPrefix = layout === "repository" ? "dist/" : "";
3163
+ const manifestChunks = [];
3164
+ const manifestNotebooks = [];
3165
+ const landingNotebooks = [];
3166
+ const referencedUserEfforts = /* @__PURE__ */ new Set();
3167
+ const referencedUserEquipment = /* @__PURE__ */ new Set();
3168
+ let totalNotes = 0;
3169
+ let totalPublicSessions = 0;
3170
+ const sortedSlugs = [...state.notebooks.keys()].sort();
3171
+ for (const notebookSlug of sortedSlugs) {
3172
+ const group = state.notebooks.get(notebookSlug);
3173
+ const chunkId = `notebook.${notebookSlug}`;
3174
+ const usedStems = /* @__PURE__ */ new Set();
3175
+ const rows = [];
3176
+ const records = [];
3177
+ const landingNotes = [];
3178
+ const nbReferencedEfforts = /* @__PURE__ */ new Set();
3179
+ const nbReferencedEquipment = /* @__PURE__ */ new Set();
3180
+ const nbReferencedTags = /* @__PURE__ */ new Set();
3181
+ if (layout === "repository") {
3182
+ const readmeMd = group.landing ? group.landing.rawContent : `# ${group.label}
3183
+
3184
+ ${group.description ?? ""}
3185
+ `;
3186
+ await tree.write(`markdown/notebooks/${notebookSlug}/README.md`, encodeUtf8(readmeMd));
3187
+ }
3188
+ for (const note of group.notes) {
3189
+ let baseStem = slugStem(note.title || note.id, "note");
3190
+ if (baseStem.toLowerCase() === "readme") baseStem = "note-readme";
3191
+ let stem = baseStem;
3192
+ let suffix = 2;
3193
+ while (usedStems.has(stem)) {
3194
+ stem = `${baseStem}-${suffix++}`;
3195
+ }
3196
+ usedStems.add(stem);
3197
+ const notePath = `markdown/notebooks/${notebookSlug}/${stem}.md`;
3198
+ const portableMd = composeNoteMarkdown({
3199
+ ...note,
3200
+ notebookId: `notebook/${notebookSlug}`
3201
+ });
3202
+ const contentForSeed = layout === "repository" ? portableMd : note.rawContent;
3203
+ const targetNbId = wodWikiCore.toNotebookId(notebookSlug);
3204
+ const allPublicForNote = state.publicSessionsByNote.get(note.id) ?? [];
3205
+ const publicSessions = allPublicForNote.filter((sess) => {
3206
+ const userPinned = (sess.notebookIds ?? []).map((id) => wodWikiCore.toNotebookId(id)).filter((id) => !wodWikiCore.isNonPublishableNotebook(id));
3207
+ return userPinned.length === 0 || userPinned.includes(targetNbId);
3208
+ });
3209
+ totalPublicSessions += publicSessions.length;
3210
+ const { row, uuid, companionBundle } = await compileSeedRowForNote({
3211
+ notePath,
3212
+ content: contentForSeed,
3213
+ title: note.title || stem,
3214
+ createdAt: note.date ?? note.createdAt,
3215
+ routeId: `${notebookSlug}/${stem}`,
3216
+ sourceId: `notebook:${notebookSlug}/${stem}`,
3217
+ publicSessions,
3218
+ eventsBySession: state.eventsBySession,
3219
+ revisionsByKey: state.revisionsByKey,
3220
+ referenceIndex
3221
+ });
3222
+ for (const eff of row.blockEfforts) {
3223
+ referencedUserEfforts.add(eff.effortSlug);
3224
+ nbReferencedEfforts.add(eff.effortSlug);
3225
+ }
3226
+ for (const eq of row.blockEquipment) {
3227
+ referencedUserEquipment.add(eq.equipmentSlug);
3228
+ nbReferencedEquipment.add(eq.equipmentSlug);
3229
+ }
3230
+ for (const t of extractTypedTags(note.rawContent)) {
3231
+ nbReferencedTags.add(t.label);
3232
+ }
3233
+ for (const m of note.rawContent.matchAll(/#([a-z0-9][a-z0-9-]*)/gi)) {
3234
+ if (m[1]) nbReferencedTags.add(m[1].toLowerCase());
3235
+ }
3236
+ rows.push(row);
3237
+ await tree.write(notePath, encodeUtf8(portableMd));
3238
+ const recordRelPath = notePath.replace(/\.md$/, ".json");
3239
+ const recordBytes = encodeUtf8(JSON.stringify(row, null, 2));
3240
+ await tree.write(`${artifactPrefix}${recordRelPath}`, recordBytes);
3241
+ if (companionBundle) {
3242
+ const jsonlText = wodWikiCore.serializeNoteBundleToJsonl(companionBundle) + "\n";
3243
+ await tree.write(notePath.replace(/\.md$/, ".jsonl"), encodeUtf8(jsonlText));
3244
+ if (artifactPrefix) {
3245
+ await tree.write(`${artifactPrefix}${notePath.replace(/\.md$/, ".jsonl")}`, encodeUtf8(jsonlText));
3246
+ }
3247
+ }
3248
+ records.push({
3249
+ uuid,
3250
+ path: notePath,
3251
+ recordPath: recordRelPath,
3252
+ commit: "",
3253
+ version: note.sourceRevision ?? 1,
3254
+ sha256: await sha256HexAsync(recordBytes),
3255
+ title: note.title || stem,
3256
+ ...note.date !== void 0 ? { date: note.date } : {}
3257
+ });
3258
+ landingNotes.push({
3259
+ title: note.title || stem,
3260
+ path: notePath,
3261
+ date: note.date,
3262
+ recordPath: recordRelPath,
3263
+ content: note.rawContent,
3264
+ publicSessions: publicSessions.length
3265
+ });
3266
+ }
3267
+ assertSeedRows(rows);
3268
+ const chunkBytes = encodeUtf8(JSON.stringify(rows));
3269
+ const chunkSha = await sha256HexAsync(chunkBytes);
3270
+ const chunkRelPath = `chunks/${chunkId}.${chunkSha.slice(0, 8)}.json`;
3271
+ await tree.write(`${artifactPrefix}${chunkRelPath}`, chunkBytes);
3272
+ manifestChunks.push({
3273
+ id: chunkId,
3274
+ path: chunkRelPath,
3275
+ sha256: chunkSha,
3276
+ bytes: chunkBytes.byteLength,
3277
+ count: rows.length,
3278
+ kind: "notes"
3279
+ });
3280
+ totalNotes += rows.length;
3281
+ await promoteReferencedOverridesToNotebook(storage, {
3282
+ notebookId: `notebook/${notebookSlug}`,
3283
+ effortSlugs: nbReferencedEfforts,
3284
+ equipmentSlugs: nbReferencedEquipment,
3285
+ tagSlugs: nbReferencedTags
3286
+ });
3287
+ const indexPath = `indexes/notebooks/${chunkId}.json`;
3288
+ const summary = {
3289
+ notebookId: chunkId,
3290
+ label: group.label,
3291
+ category: notebookSlugForChunkId(chunkId),
3292
+ indexPath,
3293
+ version: nextVersion,
3294
+ commit: "",
3295
+ updatedAt: builtAt,
3296
+ builtAt,
3297
+ sha256: chunkSha,
3298
+ bytes: chunkBytes.byteLength,
3299
+ count: rows.length
3300
+ };
3301
+ const notebookIndex = {
3302
+ ...summary,
3303
+ records
3304
+ };
3305
+ assertNotebookIndex(notebookIndex);
3306
+ await tree.write(`${artifactPrefix}${indexPath}`, encodeUtf8(JSON.stringify(notebookIndex, null, 2) + "\n"));
3307
+ manifestNotebooks.push(summary);
3308
+ landingNotebooks.push({
3309
+ id: chunkId,
3310
+ label: group.label,
3311
+ notes: landingNotes
3312
+ });
3313
+ }
3314
+ const promotedOverrides = await listScopedPropertyOverrides(storage);
3315
+ const overrideEffortBySlug = /* @__PURE__ */ new Map();
3316
+ const overrideEquipBySlug = /* @__PURE__ */ new Map();
3317
+ for (const ov of promotedOverrides) {
3318
+ if (ov.seedOrigin === "seed") continue;
3319
+ if (ov.kind === "effort" && ov.payload) {
3320
+ overrideEffortBySlug.set(ov.slug, { eff: ov.payload, md: ov.rawContent });
3321
+ } else if (ov.kind === "equipment" && ov.payload) {
3322
+ overrideEquipBySlug.set(ov.slug, { eq: ov.payload, md: ov.rawContent });
3323
+ }
3324
+ }
3325
+ const userEffortMap = /* @__PURE__ */ new Map();
3326
+ for (const e of state.efforts) {
3327
+ if (e.registrySource !== "bundled" && referencedUserEfforts.has(e.slug)) {
3328
+ const owner = e.ownerNoteId ? state.notesById.get(e.ownerNoteId) : void 0;
3329
+ userEffortMap.set(e.slug, { eff: e, md: owner?.rawContent ?? effortToMarkdown(e) });
3330
+ }
3331
+ }
3332
+ for (const slug of referencedUserEfforts) {
3333
+ const ov = overrideEffortBySlug.get(slug);
3334
+ if (ov) userEffortMap.set(slug, ov);
3335
+ }
3336
+ if (userEffortMap.size > 0) {
3337
+ const effortRows = [];
3338
+ for (const { eff, md } of [...userEffortMap.values()].sort((a, b) => a.eff.slug < b.eff.slug ? -1 : 1)) {
3339
+ const effPath = `markdown/efforts/${eff.slug}.md`;
3340
+ await tree.write(effPath, encodeUtf8(md));
3341
+ const { row } = await compileSeedRowForNote({
3342
+ notePath: effPath,
3343
+ content: md,
3344
+ title: eff.label,
3345
+ createdAt: 0,
3346
+ sourceId: "efforts",
3347
+ publicSessions: [],
3348
+ eventsBySession: state.eventsBySession,
3349
+ revisionsByKey: state.revisionsByKey,
3350
+ referenceIndex
3351
+ });
3352
+ effortRows.push(row);
3353
+ }
3354
+ assertSeedRows(effortRows);
3355
+ const bytes = encodeUtf8(JSON.stringify(effortRows));
3356
+ const sha = await sha256HexAsync(bytes);
3357
+ const rel = `chunks/${EFFORTS_CHUNK_ID}.${sha.slice(0, 8)}.json`;
3358
+ await tree.write(`${artifactPrefix}${rel}`, bytes);
3359
+ manifestChunks.push({ id: EFFORTS_CHUNK_ID, path: rel, sha256: sha, bytes: bytes.byteLength, count: effortRows.length });
3360
+ }
3361
+ const userEquipMap = /* @__PURE__ */ new Map();
3362
+ for (const eq of state.equipment) {
3363
+ if (eq.registrySource !== "bundled" && referencedUserEquipment.has(eq.slug)) {
3364
+ const owner = eq.ownerNoteId ? state.notesById.get(eq.ownerNoteId) : void 0;
3365
+ userEquipMap.set(eq.slug, { eq, md: owner?.rawContent ?? equipmentToMarkdown(eq) });
3366
+ }
3367
+ }
3368
+ for (const slug of referencedUserEquipment) {
3369
+ const ov = overrideEquipBySlug.get(slug);
3370
+ if (ov) userEquipMap.set(slug, ov);
3371
+ }
3372
+ if (userEquipMap.size > 0) {
3373
+ const eqRows = [];
3374
+ for (const { eq, md } of [...userEquipMap.values()].sort((a, b) => a.eq.slug < b.eq.slug ? -1 : 1)) {
3375
+ const eqPath = `markdown/equipment/${eq.slug}.md`;
3376
+ await tree.write(eqPath, encodeUtf8(md));
3377
+ const { row } = await compileSeedRowForNote({
3378
+ notePath: eqPath,
3379
+ content: md,
3380
+ title: eq.label,
3381
+ createdAt: 0,
3382
+ sourceId: "equipment",
3383
+ publicSessions: [],
3384
+ eventsBySession: state.eventsBySession,
3385
+ revisionsByKey: state.revisionsByKey,
3386
+ referenceIndex
3387
+ });
3388
+ eqRows.push(row);
3389
+ }
3390
+ assertSeedRows(eqRows);
3391
+ const bytes = encodeUtf8(JSON.stringify(eqRows));
3392
+ const sha = await sha256HexAsync(bytes);
3393
+ const rel = `chunks/${EQUIPMENT_CHUNK_ID}.${sha.slice(0, 8)}.json`;
3394
+ await tree.write(`${artifactPrefix}${rel}`, bytes);
3395
+ manifestChunks.push({ id: EQUIPMENT_CHUNK_ID, path: rel, sha256: sha, bytes: bytes.byteLength, count: eqRows.length });
3396
+ }
3397
+ const safeRepoUrl = options.repositoryUrl && /^https:\/\//.test(options.repositoryUrl) ? options.repositoryUrl : void 0;
3398
+ const feedName = options.name ?? "My Published Feed";
3399
+ const manifest = {
3400
+ name: feedName,
3401
+ ...options.description ? { description: options.description } : {},
3402
+ ...safeRepoUrl ? { repositoryUrl: safeRepoUrl } : {},
3403
+ schema: SEED_SCHEMA,
3404
+ version: nextVersion,
3405
+ versionLabel: `v${nextVersion}`,
3406
+ commit: "",
3407
+ builtAt,
3408
+ chunks: manifestChunks,
3409
+ notebooks: manifestNotebooks
3410
+ };
3411
+ assertSeedManifest(manifest);
3412
+ const totalMs = Math.max(1, Date.now() - t0);
3413
+ const landingHtml = renderFeedLandingHtml({
3414
+ manifest,
3415
+ totalMs,
3416
+ passMs: { scan: 0, blockIndex: 0, parseGate: 0, blockEfforts: 0, write: totalMs },
3417
+ fileCount: totalNotes,
3418
+ notebooks: landingNotebooks
3419
+ });
3420
+ await tree.write(`${artifactPrefix}index.html`, encodeUtf8(landingHtml));
3421
+ if (layout === "repository") {
3422
+ if (!await tree.stat("package.json")) {
3423
+ await tree.write("package.json", encodeUtf8(repoPackageJson(feedName, options.description, safeRepoUrl)));
3424
+ }
3425
+ if (!await tree.stat(".github/workflows/publish-feed.yml")) {
3426
+ await tree.write(".github/workflows/publish-feed.yml", encodeUtf8(repoWorkflowYaml()));
3427
+ }
3428
+ if (!await tree.stat("README.md")) {
3429
+ await tree.write("README.md", encodeUtf8(repoReadmeMarkdown(feedName, options.description)));
3430
+ }
3431
+ }
3432
+ const manifestBytes = encodeUtf8(JSON.stringify(manifest, null, 2) + "\n");
3433
+ const manifestSha256 = await sha256HexAsync(manifestBytes);
3434
+ await tree.write(`${artifactPrefix}manifest.json`, manifestBytes);
3435
+ const shouldCheckpoint = options.recordCheckpoint ?? (layout === "feed" && !options.notebookSlug);
3436
+ if (shouldCheckpoint) {
3437
+ const chunkShas = {};
3438
+ for (const c of manifestChunks) chunkShas[c.id] = c.sha256;
3439
+ const cp = {
3440
+ key: PUBLISHED_FEED_META_KEY,
3441
+ version: nextVersion,
3442
+ builtAt,
3443
+ manifestSha256,
3444
+ chunkShas
3445
+ };
3446
+ await storage.transaction(["meta"], "readwrite", async (tx) => {
3447
+ await tx.readwrite("meta").put(cp);
3448
+ });
3449
+ }
3450
+ return {
3451
+ manifest,
3452
+ notebooks: sortedSlugs,
3453
+ totalNotes,
3454
+ totalPublicSessions,
3455
+ manifestSha256
3456
+ };
3457
+ }
3458
+ async function checkUnpublishedFeedChanges(storage, currentTree, options = {}) {
3459
+ const state = await collectPublicStorageState(storage, options);
3460
+ const publicNotebooks = state.notebooks.size;
3461
+ let publicNotes = 0;
3462
+ let publicSessions = 0;
3463
+ for (const nb of state.notebooks.values()) {
3464
+ publicNotes += nb.notes.length;
3465
+ for (const n of nb.notes) {
3466
+ publicSessions += (state.publicSessionsByNote.get(n.id) ?? []).length;
3467
+ }
3468
+ }
3469
+ let priorChunkShas = state.storedCheckpoint?.chunkShas;
3470
+ let publishedVersion = state.storedCheckpoint?.version ?? null;
3471
+ let builtAt = state.storedCheckpoint?.builtAt ?? null;
3472
+ if (currentTree) {
3473
+ try {
3474
+ const raw = decodeUtf8(await currentTree.read("manifest.json"));
3475
+ const parsed = assertSeedManifest(JSON.parse(raw));
3476
+ publishedVersion = parsed.version;
3477
+ builtAt = parsed.builtAt;
3478
+ priorChunkShas = {};
3479
+ for (const c of parsed.chunks) priorChunkShas[c.id] = c.sha256;
3480
+ } catch {
3481
+ }
3482
+ }
3483
+ if (publicNotebooks === 0) {
3484
+ const hadPrior = priorChunkShas !== void 0 && Object.keys(priorChunkShas).length > 0;
3485
+ return {
3486
+ hasPublicContent: false,
3487
+ publishedVersion,
3488
+ builtAt,
3489
+ dirty: hadPrior,
3490
+ publicNotebooks: 0,
3491
+ publicNotes: 0,
3492
+ publicSessions: 0,
3493
+ changes: hadPrior ? Object.keys(priorChunkShas).map((id) => ({ notebookId: id, status: "removed" })) : []
3494
+ };
3495
+ }
3496
+ const scratch = new MemoryFeedTree();
3497
+ const compiled = await publishFeedFromStorage(storage, scratch, {
3498
+ ...options,
3499
+ layout: "feed",
3500
+ version: publishedVersion ?? 1,
3501
+ builtAt: builtAt ?? "1970-01-01T00:00:00.000Z",
3502
+ recordCheckpoint: false
3503
+ });
3504
+ if (!priorChunkShas) {
3505
+ return {
3506
+ hasPublicContent: true,
3507
+ publishedVersion: null,
3508
+ builtAt: null,
3509
+ dirty: true,
3510
+ publicNotebooks,
3511
+ publicNotes,
3512
+ publicSessions,
3513
+ changes: compiled.manifest.chunks.map((c) => ({ notebookId: c.id, status: "added" }))
3514
+ };
3515
+ }
3516
+ const changes = [];
3517
+ const nextIds = /* @__PURE__ */ new Set();
3518
+ for (const c of compiled.manifest.chunks) {
3519
+ nextIds.add(c.id);
3520
+ if (!(c.id in priorChunkShas)) {
3521
+ changes.push({ notebookId: c.id, status: "added" });
3522
+ } else if (priorChunkShas[c.id] !== c.sha256) {
3523
+ changes.push({ notebookId: c.id, status: "modified" });
3524
+ }
3525
+ }
3526
+ for (const oldId of Object.keys(priorChunkShas)) {
3527
+ if (!nextIds.has(oldId)) {
3528
+ changes.push({ notebookId: oldId, status: "removed" });
3529
+ }
3530
+ }
3531
+ return {
3532
+ hasPublicContent: true,
3533
+ publishedVersion,
3534
+ builtAt,
3535
+ dirty: changes.length > 0,
3536
+ publicNotebooks,
3537
+ publicNotes,
3538
+ publicSessions,
3539
+ changes
3540
+ };
3541
+ }
3542
+ function makeNotebookLinkId(notebookId, targetKind, targetId) {
3543
+ return `${notebookId}:${targetKind}:${targetId}`;
3544
+ }
3545
+ function isPropertyDefinitionNoteId(noteId) {
3546
+ return noteId.startsWith("effort/") || noteId.startsWith("equipment/") || noteId.startsWith("t/");
3547
+ }
3548
+ function isNotebookLandingNote(note) {
3549
+ return note.id.startsWith("notebook/") && note.notebookId === note.id;
3550
+ }
3551
+ function baseUserMemberships(note) {
3552
+ if (note.seedOrigin === "seed" || note.feedOrigin === "feed") return [];
3553
+ if (isNotebookLandingNote(note) || isPropertyDefinitionNoteId(note.id)) return [];
3554
+ const base = ["notebook/journal"];
3555
+ if (note.type === "playground" || note.sourceId === "playground") {
3556
+ base.push("notebook/playground");
3557
+ }
3558
+ return base;
3559
+ }
3560
+ function dedupeNotebooks(ids) {
3561
+ const out = [];
3562
+ for (const raw of ids) {
3563
+ if (!raw || !raw.trim()) continue;
3564
+ const norm = wodWikiCore.toNotebookId(raw);
3565
+ if (!out.includes(norm)) out.push(norm);
3566
+ }
3567
+ return out;
3568
+ }
3569
+ async function assertWritableTargetNotebook(tx, notebookId) {
3570
+ if (wodWikiCore.isSystemReadOnlyNotebook(notebookId)) {
3571
+ throw new Error(`Notebook '${notebookId}' is read-only and cannot accept promoted notes.`);
3572
+ }
3573
+ const landing = await tx.readonly("notes").get(notebookId);
3574
+ if (landing && (landing.feedOrigin === "feed" || landing.seedOrigin === "seed")) {
3575
+ throw new Error(`Notebook '${notebookId}' is feed-delivered and read-only.`);
3576
+ }
3577
+ }
3578
+ async function ensureUserNotebookLanding(tx, notebookId, now) {
3579
+ if (wodWikiCore.isNonPublishableNotebook(notebookId)) return;
3580
+ const existing = await tx.readonly("notes").get(notebookId);
3581
+ if (existing) return;
3582
+ const slug = wodWikiCore.notebookSlugFromId(notebookId);
3583
+ const title = slug.split("-").filter(Boolean).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join(" ") || slug;
3584
+ await tx.readwrite("notes").put({
3585
+ id: notebookId,
3586
+ title,
3587
+ rawContent: `# ${title}
3588
+ `,
3589
+ sourceRevision: 1,
3590
+ blocks: {},
3591
+ createdAt: now,
3592
+ notebookId,
3593
+ seedOrigin: "user"
3594
+ });
3595
+ }
3596
+ async function createUserNotebookLanding(storage, rawName) {
3597
+ const trimmed = rawName.trim();
3598
+ let slug = trimmed.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "notebook";
3599
+ if (wodWikiCore.isNonPublishableNotebook(slug)) slug = `${slug}-user`;
3600
+ const nbId = wodWikiCore.toNotebookId(slug);
3601
+ await storage.transaction(["notes"], "readwrite", async (tx) => {
3602
+ const existing = await tx.readonly("notes").get(nbId);
3603
+ if (!existing) {
3604
+ await tx.readwrite("notes").put({
3605
+ id: nbId,
3606
+ title: trimmed || slug,
3607
+ rawContent: `# ${trimmed || slug}
3608
+ `,
3609
+ sourceRevision: 1,
3610
+ blocks: {},
3611
+ createdAt: Date.now(),
3612
+ notebookId: nbId,
3613
+ seedOrigin: "user"
3614
+ });
3615
+ }
3616
+ });
3617
+ return nbId;
3618
+ }
3619
+ async function promoteNoteToNotebooks(storage, input) {
3620
+ const requestedTargets = dedupeNotebooks(input.notebookIds);
3621
+ const now = Date.now();
3622
+ return storage.transaction(
3623
+ ["notes", "sessions", "notebook_links", "block_revisions"],
3624
+ "readwrite",
3625
+ async (tx) => {
3626
+ const note = await tx.readonly("notes").get(input.noteId);
3627
+ if (!note) {
3628
+ throw new Error(`Note not found: ${input.noteId}`);
3629
+ }
3630
+ if (note.seedOrigin === "seed" || note.feedOrigin === "feed") {
3631
+ throw new Error(`Read-only Feed Note '${input.noteId}' must be cloned before promotion.`);
3632
+ }
3633
+ for (const target of requestedTargets) {
3634
+ if (target !== "notebook/journal" && target !== "notebook/playground") {
3635
+ await assertWritableTargetNotebook(tx, target);
3636
+ await ensureUserNotebookLanding(tx, target, now);
3637
+ }
3638
+ }
3639
+ const existingLinks = await tx.readonly("notebook_links").getAllFromIndex("by-note", note.id);
3640
+ const existingNoteLinks = existingLinks.filter((l) => l.targetKind === "note" && l.targetId === note.id).map((l) => wodWikiCore.toNotebookId(l.notebookId));
3641
+ const merged = dedupeNotebooks([
3642
+ ...baseUserMemberships(note),
3643
+ ...note.notebookIds ?? [],
3644
+ ...note.notebookId ? [note.notebookId] : [],
3645
+ ...existingNoteLinks,
3646
+ ...requestedTargets
3647
+ ]);
3648
+ const primaryUserNb = merged.find(
3649
+ (id) => id !== "notebook/journal" && id !== "notebook/playground"
3650
+ );
3651
+ const updatedNote = {
3652
+ ...note,
3653
+ notebookIds: merged,
3654
+ ...primaryUserNb ? { notebookId: primaryUserNb } : {}
3655
+ };
3656
+ await tx.readwrite("notes").put(updatedNote);
3657
+ const linkRows = merged.map((nbId) => ({
3658
+ id: makeNotebookLinkId(nbId, "note", note.id),
3659
+ notebookId: nbId,
3660
+ targetKind: "note",
3661
+ targetId: note.id,
3662
+ noteId: note.id,
3663
+ createdAt: now
3664
+ }));
3665
+ const promotedSessionIds = [];
3666
+ if (input.sessionIds && input.sessionIds.length > 0) {
3667
+ const wantedSessions = new Set(input.sessionIds);
3668
+ const sessions = await tx.readonly("sessions").getAllFromIndex("by-note", note.id);
3669
+ for (const sess of sessions) {
3670
+ if (!wantedSessions.has(sess.id)) continue;
3671
+ const sessNotebooks = dedupeNotebooks([
3672
+ "notebook/journal",
3673
+ ...sess.notebookIds ?? [],
3674
+ ...requestedTargets
3675
+ ]);
3676
+ const updatedSess = {
3677
+ ...sess,
3678
+ notebookIds: sessNotebooks,
3679
+ ...input.shareSessionsPublicly !== void 0 ? { public: input.shareSessionsPublicly } : {}
3680
+ };
3681
+ await tx.readwrite("sessions").put(updatedSess);
3682
+ promotedSessionIds.push(sess.id);
3683
+ for (const nbId of sessNotebooks) {
3684
+ linkRows.push({
3685
+ id: makeNotebookLinkId(nbId, "session", sess.id),
3686
+ notebookId: nbId,
3687
+ targetKind: "session",
3688
+ targetId: sess.id,
3689
+ noteId: note.id,
3690
+ createdAt: now
3691
+ });
3692
+ }
3693
+ }
3694
+ }
3695
+ if (linkRows.length > 0) {
3696
+ await tx.readwrite("notebook_links").putMany(linkRows);
3697
+ }
3698
+ return {
3699
+ note: updatedNote,
3700
+ notebookIds: merged,
3701
+ promotedSessionIds
3702
+ };
3703
+ }
3704
+ );
3705
+ }
3706
+ async function setNoteNotebooks(storage, input) {
3707
+ const requested = dedupeNotebooks(input.notebookIds);
3708
+ const now = Date.now();
3709
+ return storage.transaction(["notes", "notebook_links", "block_revisions"], "readwrite", async (tx) => {
3710
+ const note = await tx.readonly("notes").get(input.noteId);
3711
+ if (!note) throw new Error(`Note not found: ${input.noteId}`);
3712
+ if (note.seedOrigin === "seed" || note.feedOrigin === "feed") {
3713
+ throw new Error(`Read-only Feed Note '${input.noteId}' cannot change Notebook membership.`);
3714
+ }
3715
+ const userTargets = requested.filter(
3716
+ (id) => id !== "notebook/journal" && id !== "notebook/playground"
3717
+ );
3718
+ for (const target of userTargets) {
3719
+ await assertWritableTargetNotebook(tx, target);
3720
+ await ensureUserNotebookLanding(tx, target, now);
3721
+ }
3722
+ const finalMemberships = dedupeNotebooks([
3723
+ ...baseUserMemberships(note),
3724
+ ...userTargets
3725
+ ]);
3726
+ const existingLinks = await tx.readonly("notebook_links").getAllFromIndex("by-note", note.id);
3727
+ const linkStore = tx.readwrite("notebook_links");
3728
+ for (const link of existingLinks) {
3729
+ if (link.targetKind === "note" && link.targetId === note.id) {
3730
+ if (!finalMemberships.includes(wodWikiCore.toNotebookId(link.notebookId))) {
3731
+ await linkStore.delete(link.id);
3732
+ }
3733
+ }
3734
+ }
3735
+ for (const nbId of finalMemberships) {
3736
+ await linkStore.put({
3737
+ id: makeNotebookLinkId(nbId, "note", note.id),
3738
+ notebookId: nbId,
3739
+ targetKind: "note",
3740
+ targetId: note.id,
3741
+ noteId: note.id,
3742
+ createdAt: now
3743
+ });
3744
+ }
3745
+ const primaryUserNb = finalMemberships.find(
3746
+ (id) => id !== "notebook/journal" && id !== "notebook/playground"
3747
+ );
3748
+ const { notebookId: _priorSingle, ...rest } = note;
3749
+ const updatedNote = {
3750
+ ...rest,
3751
+ notebookIds: finalMemberships,
3752
+ ...primaryUserNb ? { notebookId: primaryUserNb } : {}
3753
+ };
3754
+ await tx.readwrite("notes").put(updatedNote);
3755
+ return finalMemberships;
3756
+ });
3757
+ }
3758
+ async function removeNoteFromNotebook(storage, noteId, notebookIdOrSlug) {
3759
+ const target = wodWikiCore.toNotebookId(notebookIdOrSlug);
3760
+ if (target === "notebook/journal") {
3761
+ throw new Error("Notes cannot be removed from private notebook/journal.");
3762
+ }
3763
+ const current = await getNoteNotebooks(storage, noteId);
3764
+ const remaining = current.filter((id) => id !== target);
3765
+ return setNoteNotebooks(storage, { noteId, notebookIds: remaining });
3766
+ }
3767
+ async function getNoteNotebooks(storage, noteId) {
3768
+ const note = await storage.readonly("notes").get(noteId);
3769
+ if (!note) return [];
3770
+ let linkNotebookIds = [];
3771
+ try {
3772
+ const links = await storage.readonly("notebook_links").getAllFromIndex("by-note", noteId);
3773
+ linkNotebookIds = links.filter((l) => l.targetKind === "note" && l.targetId === noteId).map((l) => l.notebookId);
3774
+ } catch {
3775
+ }
3776
+ return dedupeNotebooks([
3777
+ ...baseUserMemberships(note),
3778
+ ...note.notebookIds ?? [],
3779
+ ...linkNotebookIds,
3780
+ ...wodWikiWql.notebooksOfItem(note)
3781
+ ]);
3782
+ }
3783
+
3784
+ // src/feed/ingestor.ts
3785
+ function mintUuidV4() {
3786
+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
3787
+ return crypto.randomUUID();
3788
+ }
3789
+ const bytes = new Uint8Array(16);
3790
+ crypto.getRandomValues(bytes);
3791
+ bytes[6] = bytes[6] & 15 | 64;
3792
+ bytes[8] = bytes[8] & 63 | 128;
3793
+ const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
3794
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
3795
+ }
3796
+ async function getNotePublicationSummary(storage, noteId) {
3797
+ const note = await storage.readonly("notes").get(noteId);
3798
+ if (!note) {
3799
+ return wodWikiCore.derivePublicationVisibility({ notebookPublic: false, publicSessions: 0, totalSessions: 0 });
3800
+ }
3801
+ if (wodWikiCore.isPublishableNotebookLanding(note)) {
3802
+ const notebookPublic2 = note.public === true;
3803
+ const [allNotes, allSessions] = await Promise.all([
3804
+ storage.readonly("notes").getAll(),
3805
+ storage.readonly("sessions").getAll()
3806
+ ]);
3807
+ let linkedNoteIds = /* @__PURE__ */ new Set();
3808
+ try {
3809
+ const links = await storage.readonly("notebook_links").getAllFromIndex("by-notebook", note.id);
3810
+ linkedNoteIds = new Set(links.filter((l) => l.targetKind === "note").map((l) => l.noteId));
3811
+ } catch {
3812
+ }
3813
+ const memberIds = new Set(
3814
+ allNotes.filter((n) => !wodWikiCore.isPublishableNotebookLanding(n) && (linkedNoteIds.has(n.id) || wodWikiWql.notebooksOfItem(n).includes(wodWikiCore.toNotebookId(note.id)))).map((n) => n.id)
3815
+ );
3816
+ const nbSessions = allSessions.filter((s) => memberIds.has(s.noteId));
3817
+ const pubCount = nbSessions.filter((s) => s.public === true).length;
3818
+ return wodWikiCore.derivePublicationVisibility({
3819
+ notebookPublic: notebookPublic2,
3820
+ publicSessions: pubCount,
3821
+ totalSessions: nbSessions.length,
3822
+ notebookId: note.id,
3823
+ notebookIds: [note.id],
3824
+ publicNotebookIds: notebookPublic2 ? [note.id] : []
3825
+ });
3826
+ }
3827
+ const linkedNotebooks = await getNoteNotebooks(storage, note.id);
3828
+ const candidateNotebooks = linkedNotebooks.length > 0 ? linkedNotebooks : note.notebookId ? [wodWikiCore.toNotebookId(note.notebookId)] : wodWikiWql.notebooksOfItem(note);
3829
+ const publicNotebookIds = [];
3830
+ for (const nbId of candidateNotebooks) {
3831
+ if (wodWikiCore.isNonPublishableNotebook(nbId)) continue;
3832
+ const landing = await storage.readonly("notes").get(nbId);
3833
+ if (landing && wodWikiCore.isPublishableNotebookLanding(landing) && landing.public === true) {
3834
+ publicNotebookIds.push(nbId);
3835
+ }
3836
+ }
3837
+ const notebookPublic = publicNotebookIds.length > 0;
3838
+ const primaryNbId = publicNotebookIds[0] ?? candidateNotebooks.find((id) => !wodWikiCore.isNonPublishableNotebook(id)) ?? candidateNotebooks[0] ?? wodWikiWql.notebookOfItem(note);
3839
+ let noteSessions;
3840
+ try {
3841
+ noteSessions = await storage.readonly("sessions").getAllFromIndex("by-note", noteId);
3842
+ } catch {
3843
+ noteSessions = (await storage.readonly("sessions").getAll()).filter((s) => s.noteId === noteId);
3844
+ }
3845
+ const publicSessions = noteSessions.filter((s) => s.public === true).length;
3846
+ return wodWikiCore.derivePublicationVisibility({
3847
+ notebookPublic,
3848
+ publicSessions,
3849
+ totalSessions: noteSessions.length,
3850
+ notebookId: primaryNbId,
3851
+ notebookIds: [...candidateNotebooks],
3852
+ publicNotebookIds
3853
+ });
3854
+ }
3855
+ async function setNotebookPublic(storage, notebookIdOrSlug, isPublic) {
3856
+ const notebookId = wodWikiCore.toNotebookId(notebookIdOrSlug);
3857
+ if (wodWikiCore.isNonPublishableNotebook(notebookId)) {
3858
+ throw new Error(`Notebook '${notebookId}' is private or system-managed and cannot be published.`);
3859
+ }
3860
+ return storage.transaction(["notes"], "readwrite", async (tx) => {
3861
+ const store = tx.readwrite("notes");
3862
+ const existing = await store.get(notebookId);
3863
+ if (existing && (existing.feedOrigin === "feed" || existing.seedOrigin === "seed")) {
3864
+ throw new Error(`Subscribed feed notebooks cannot be published directly (${notebookId}). Clone into a user notebook first.`);
3865
+ }
3866
+ const base = existing ?? {
3867
+ id: notebookId,
3868
+ title: notebookId.slice("notebook/".length),
3869
+ rawContent: `# ${notebookId.slice("notebook/".length)}
3870
+ `,
3871
+ sourceRevision: 1,
3872
+ blocks: {},
3873
+ createdAt: Date.now(),
3874
+ notebookId,
3875
+ seedOrigin: "user"
3876
+ };
3877
+ const updated = {
3878
+ ...base,
3879
+ notebookId,
3880
+ public: isPublic
3881
+ };
3882
+ await store.put(updated);
3883
+ return updated;
3884
+ });
3885
+ }
3886
+ async function setSessionPublic(storage, sessionId, isPublic) {
3887
+ return storage.transaction(["sessions"], "readwrite", async (tx) => {
3888
+ const store = tx.readwrite("sessions");
3889
+ const existing = await store.get(sessionId);
3890
+ if (!existing) {
3891
+ throw new Error(`Session not found: ${sessionId}`);
3892
+ }
3893
+ const updated = { ...existing, public: isPublic };
3894
+ await store.put(updated);
3895
+ return updated;
3896
+ });
3897
+ }
3898
+ async function previewRemoteNotebook(reader, indexPath) {
3899
+ const raw = decodeUtf8(await reader.read(indexPath));
3900
+ return assertNotebookIndex(JSON.parse(raw));
3901
+ }
3902
+ async function previewRemoteRecord(reader, recordPath) {
3903
+ const raw = decodeUtf8(await reader.read(recordPath));
3904
+ return assertSeedRow(JSON.parse(raw));
3905
+ }
3906
+ async function cloneRemoteRecord(storage, reader, input) {
3907
+ const targetNotebookId = wodWikiCore.toNotebookId(input.targetNotebookId);
3908
+ const seedRow = await previewRemoteRecord(reader, input.record.recordPath);
3909
+ const newNoteId = mintUuidV4();
3910
+ const now = Date.now();
3911
+ const sourceRevision = 1;
3912
+ const blocks = {};
3913
+ const revisions = [];
3914
+ const blockIndex = [];
3915
+ for (const [key, block] of Object.entries(seedRow.blocks)) {
3916
+ blocks[key] = { ...block, version: 1, sourceRevision: 1 };
3917
+ revisions.push({
3918
+ noteId: newNoteId,
3919
+ blockId: block.id,
3920
+ version: 1,
3921
+ kind: block.kind,
3922
+ rawContent: seedRow.content.slice(block.from, block.to),
3923
+ savedAt: now,
3924
+ ...block.dialect ? { dialect: block.dialect } : {},
3925
+ ...block.sport ? { sport: block.sport } : {}
3926
+ });
3927
+ }
3928
+ for (const proj of seedRow.blockIndex) {
3929
+ blockIndex.push({
3930
+ ...proj,
3931
+ id: `${newNoteId}:${proj.blockId}`,
3932
+ noteId: newNoteId,
3933
+ blockVersion: 1,
3934
+ sourceRevision: 1,
3935
+ isStatic: false,
3936
+ notebookId: targetNotebookId
3937
+ });
3938
+ }
3939
+ const blockEfforts = seedRow.blockEfforts.map((eff) => ({
3940
+ ...eff,
3941
+ id: `${newNoteId}:${eff.blockId}:${eff.effortSlug}`,
3942
+ noteId: newNoteId,
3943
+ isStatic: false
3944
+ }));
3945
+ const blockEquipment = seedRow.blockEquipment.map((eq) => ({
3946
+ ...eq,
3947
+ id: `${newNoteId}:${eq.blockId}:${eq.equipmentSlug}`,
3948
+ noteId: newNoteId,
3949
+ isStatic: false
3950
+ }));
3951
+ const clonedNote = {
3952
+ id: newNoteId,
3953
+ title: input.record.title || seedRow.blockIndex[0]?.noteTitle || "Cloned Note",
3954
+ rawContent: seedRow.content,
3955
+ sourceRevision,
3956
+ blocks,
3957
+ ...input.record.date !== void 0 ? { date: input.record.date } : {},
3958
+ createdAt: now,
3959
+ notebookId: targetNotebookId,
3960
+ sourceId: `feed:${input.feedId}/${seedRow.path}`,
3961
+ sourcePath: seedRow.path,
3962
+ seedOrigin: "user"
3963
+ };
3964
+ const clonedSessions = [];
3965
+ const clonedEvents = [];
3966
+ if (input.includePublicTelemetry !== false && seedRow.telemetry) {
3967
+ const sessionIdMap = /* @__PURE__ */ new Map();
3968
+ for (const s of seedRow.telemetry.sessions) {
3969
+ const nextSid = mintUuidV4();
3970
+ sessionIdMap.set(s.id, nextSid);
3971
+ clonedSessions.push({
3972
+ ...s,
3973
+ id: nextSid,
3974
+ noteId: newNoteId,
3975
+ public: false
3976
+ });
3977
+ }
3978
+ for (const ev of seedRow.telemetry.events) {
3979
+ const nextSid = sessionIdMap.get(ev.resultId);
3980
+ if (!nextSid) continue;
3981
+ clonedEvents.push({
3982
+ ...ev,
3983
+ id: `${nextSid}:${ev.id}`,
3984
+ resultId: nextSid,
3985
+ noteId: newNoteId
3986
+ });
3987
+ }
3988
+ }
3989
+ await storage.transaction(
3990
+ ["notes", "block_revisions", "block_index", "block_efforts", "block_equipment", "sessions", "events"],
3991
+ "readwrite",
3992
+ async (tx) => {
3993
+ const landing = await tx.readonly("notes").get(targetNotebookId);
3994
+ if (landing && (landing.feedOrigin === "feed" || landing.seedOrigin === "seed")) {
3995
+ throw new Error(`Target notebook '${targetNotebookId}' is read-only`);
3996
+ }
3997
+ await tx.readwrite("notes").put(clonedNote);
3998
+ if (revisions.length > 0) await tx.readwrite("block_revisions").putMany(revisions);
3999
+ if (blockIndex.length > 0) await tx.readwrite("block_index").putMany(blockIndex);
4000
+ if (blockEfforts.length > 0) await tx.readwrite("block_efforts").putMany(blockEfforts);
4001
+ if (blockEquipment.length > 0) await tx.readwrite("block_equipment").putMany(blockEquipment);
4002
+ if (clonedSessions.length > 0) await tx.readwrite("sessions").putMany(clonedSessions);
4003
+ if (clonedEvents.length > 0) await tx.readwrite("events").putMany(clonedEvents);
4004
+ }
4005
+ );
4006
+ return clonedNote;
4007
+ }
4008
+ async function exportPortableFilesFromStorage(storage, options = {}) {
4009
+ const telemetryFormat = options.telemetryFormat ?? "jsonl";
4010
+ const [allNotes, allSessions, allEvents, allRevisions] = await Promise.all([
4011
+ storage.readonly("notes").getAll(),
4012
+ storage.readonly("sessions").getAll(),
4013
+ storage.readonly("events").getAll(),
4014
+ storage.readonly("block_revisions").getAll()
4015
+ ]);
4016
+ const wantedIds = options.noteIds ? new Set(options.noteIds) : null;
4017
+ const notes = allNotes.filter((n) => {
4018
+ if (wantedIds) return wantedIds.has(n.id);
4019
+ return n.seedOrigin !== "seed" && n.feedOrigin !== "feed";
4020
+ });
4021
+ const sessionsByNote = /* @__PURE__ */ new Map();
4022
+ for (const s of allSessions) {
4023
+ const arr = sessionsByNote.get(s.noteId) ?? [];
4024
+ arr.push(s);
4025
+ sessionsByNote.set(s.noteId, arr);
4026
+ }
4027
+ const eventsBySession = /* @__PURE__ */ new Map();
4028
+ for (const ev of allEvents) {
4029
+ const arr = eventsBySession.get(ev.resultId) ?? [];
4030
+ arr.push(ev);
4031
+ eventsBySession.set(ev.resultId, arr);
4032
+ }
4033
+ const revisionsByNote = /* @__PURE__ */ new Map();
4034
+ for (const rev of allRevisions) {
4035
+ const arr = revisionsByNote.get(rev.noteId) ?? [];
4036
+ arr.push(rev);
4037
+ revisionsByNote.set(rev.noteId, arr);
4038
+ }
4039
+ const files = [];
4040
+ const usedPaths = /* @__PURE__ */ new Set();
4041
+ for (const note of notes) {
4042
+ const baseStem = note.id.replace(/[^a-zA-Z0-9-_]/g, "_");
4043
+ let stem = baseStem;
4044
+ let i = 2;
4045
+ while (usedPaths.has(stem)) stem = `${baseStem}_${i++}`;
4046
+ usedPaths.add(stem);
4047
+ files.push({
4048
+ path: `${stem}.md`,
4049
+ content: composeNoteMarkdown(note)
4050
+ });
4051
+ const sessions = sessionsByNote.get(note.id) ?? [];
4052
+ const revisions = revisionsByNote.get(note.id) ?? [];
4053
+ const events = sessions.flatMap((s) => eventsBySession.get(s.id) ?? []);
4054
+ if (sessions.length > 0 || revisions.length > 0) {
4055
+ const bundle = {
4056
+ revisions,
4057
+ sessions,
4058
+ events
4059
+ };
4060
+ if (telemetryFormat === "jsonl" || telemetryFormat === "both") {
4061
+ files.push({
4062
+ path: `${stem}.jsonl`,
4063
+ content: wodWikiCore.serializeNoteBundleToJsonl(bundle) + "\n"
4064
+ });
4065
+ }
4066
+ if (telemetryFormat === "csv" || telemetryFormat === "both") {
4067
+ files.push({
4068
+ path: `${stem}.csv`,
4069
+ content: telemetryBundleToCsv(bundle)
4070
+ });
4071
+ }
4072
+ }
4073
+ }
4074
+ return files;
4075
+ }
4076
+ async function ingestPortableFilesIntoStorage(storage, files, options = {}) {
4077
+ const now = options.now ?? Date.now();
4078
+ const errors = [];
4079
+ let notesImported = 0;
4080
+ let revisionsImported = 0;
4081
+ let sessionsImported = 0;
4082
+ let eventsImported = 0;
4083
+ const mdFiles = files.filter((f) => /\.md$/i.test(f.path) && !/(?:^|\/)README\.md$/i.test(f.path));
4084
+ const jsonlFiles = files.filter((f) => /\.jsonl$/i.test(f.path));
4085
+ const jsonlStems = new Set(jsonlFiles.map((f) => f.path.replace(/\.jsonl$/i, "")));
4086
+ const csvFiles = files.filter(
4087
+ (f) => /\.csv$/i.test(f.path) && !jsonlStems.has(f.path.replace(/\.csv$/i, ""))
4088
+ );
4089
+ const telemetryBundles = [];
4090
+ for (const jf of jsonlFiles) {
4091
+ const parsed = wodWikiCore.parseNoteBundleFromJsonl(jf.content);
4092
+ errors.push(...parsed.errors.map((e) => `${jf.path}: ${e}`));
4093
+ telemetryBundles.push(...parsed.bundles);
4094
+ }
4095
+ for (const cf of csvFiles) {
4096
+ const parsed = csvToTelemetryBundle(cf.content);
4097
+ errors.push(...parsed.errors.map((e) => `${cf.path}: ${e}`));
4098
+ telemetryBundles.push(...parsed.bundles);
4099
+ }
4100
+ await storage.transaction(
4101
+ ["notes", "block_revisions", "block_index", "tags", "note_tags", "sessions", "events"],
4102
+ "readwrite",
4103
+ async (tx) => {
4104
+ const noteStore = tx.readwrite("notes");
4105
+ const revStore = tx.readwrite("block_revisions");
4106
+ const idxStore = tx.readwrite("block_index");
4107
+ const tagStore = tx.readwrite("tags");
4108
+ const noteTagStore = tx.readwrite("note_tags");
4109
+ const sessionStore = tx.readwrite("sessions");
4110
+ const eventStore = tx.readwrite("events");
4111
+ for (const bundle of telemetryBundles) {
4112
+ if (bundle.revisions && bundle.revisions.length > 0) {
4113
+ await revStore.putMany(bundle.revisions);
4114
+ revisionsImported += bundle.revisions.length;
4115
+ }
4116
+ }
4117
+ for (const mf of mdFiles) {
4118
+ try {
4119
+ const fallbackTitle = (mf.path.split("/").at(-1) ?? "Imported Note").replace(/\.md$/i, "");
4120
+ const parsed = parseNoteMarkdown(mf.content, { fallbackTitle });
4121
+ const noteId = parsed.id ?? await seedNoteId(`import:${mf.path}:${now}`);
4122
+ const existing = await noteStore.get(noteId);
4123
+ const nextRev = existing && existing.rawContent !== parsed.rawContent ? existing.sourceRevision + 1 : existing?.sourceRevision ?? 1;
4124
+ const blocks = existing && existing.rawContent === parsed.rawContent ? existing.blocks : wodWikiCore.reconcileNoteBlocks(parsed.rawContent, {
4125
+ sourceRevision: nextRev,
4126
+ blocks: existing?.blocks,
4127
+ registeredWidgets: wodWikiCore.KNOWN_SECTION_WIDGETS
4128
+ });
4129
+ const noteRow = {
4130
+ ...existing ?? {},
4131
+ id: noteId,
4132
+ title: parsed.title,
4133
+ rawContent: parsed.rawContent,
4134
+ sourceRevision: nextRev,
4135
+ blocks,
4136
+ ...parsed.date !== void 0 ? { date: parsed.date } : {},
4137
+ createdAt: existing?.createdAt ?? parsed.date ?? now,
4138
+ ...parsed.notebookId ? { notebookId: parsed.notebookId } : options.defaultNotebookId ? { notebookId: wodWikiCore.toNotebookId(options.defaultNotebookId) } : {},
4139
+ ...parsed.public !== void 0 ? { public: parsed.public } : {},
4140
+ tags: parsed.tags,
4141
+ seedOrigin: "user"
4142
+ };
4143
+ await noteStore.put(noteRow);
4144
+ const sections = wodWikiCore.parseDocumentSections(noteRow.rawContent, { registeredWidgets: wodWikiCore.KNOWN_SECTION_WIDGETS });
4145
+ for (const [pos, b] of Object.values(blocks).entries()) {
4146
+ const existingRev = await revStore.get([noteId, b.id, b.version]);
4147
+ if (!existingRev) {
4148
+ await revStore.put({
4149
+ noteId,
4150
+ blockId: b.id,
4151
+ version: b.version,
4152
+ kind: b.kind,
4153
+ rawContent: noteRow.rawContent.slice(b.from, b.to),
4154
+ savedAt: now,
4155
+ ...b.dialect ? { dialect: b.dialect } : {},
4156
+ ...b.sport ? { sport: b.sport } : {}
4157
+ });
4158
+ }
4159
+ const sec = sections.find((s) => s.from === b.from && s.to === b.to);
4160
+ await idxStore.put({
4161
+ id: `${noteId}:${b.id}`,
4162
+ noteId,
4163
+ blockId: b.id,
4164
+ blockVersion: b.version,
4165
+ sourceRevision: nextRev,
4166
+ from: b.from,
4167
+ to: b.to,
4168
+ position: pos,
4169
+ dataType: b.kind,
4170
+ ...b.kind === "wod" ? { blockContentId: wodWikiCore.blockContentId(sec?.scriptBlock?.content ?? noteRow.rawContent.slice(b.from, b.to)) } : {},
4171
+ rawContent: noteRow.rawContent.slice(b.from, b.to),
4172
+ noteTitle: noteRow.title,
4173
+ createdAt: noteRow.date ?? noteRow.createdAt,
4174
+ isStatic: false,
4175
+ ...noteRow.notebookId ? { notebookId: noteRow.notebookId } : {}
4176
+ });
4177
+ }
4178
+ if (parsed.typedTags.length > 0) {
4179
+ const allTags = await tagStore.getAll();
4180
+ for (const item of parsed.typedTags) {
4181
+ const tagType = item.type ?? "general";
4182
+ let tag = allTags.find((t) => t.label === item.label && (t.type ?? "general") === tagType);
4183
+ if (!tag) {
4184
+ tag = { id: mintUuidV4(), label: item.label, type: tagType, createdAt: now };
4185
+ await tagStore.put(tag);
4186
+ allTags.push(tag);
4187
+ }
4188
+ const linkId = `${noteId}:${tag.id}`;
4189
+ await noteTagStore.put({ id: linkId, noteId, tagId: tag.id });
4190
+ }
4191
+ }
4192
+ notesImported++;
4193
+ } catch (err) {
4194
+ errors.push(`${mf.path}: ${err instanceof Error ? err.message : String(err)}`);
4195
+ }
4196
+ }
4197
+ for (const bundle of telemetryBundles) {
4198
+ if (bundle.note) {
4199
+ const existing = await noteStore.get(bundle.note.id);
4200
+ if (!existing) {
4201
+ const blocks = bundle.note.blocks ?? wodWikiCore.reconcileNoteBlocks(bundle.note.rawContent, {
4202
+ sourceRevision: bundle.note.sourceRevision ?? 1,
4203
+ registeredWidgets: wodWikiCore.KNOWN_SECTION_WIDGETS
4204
+ });
4205
+ await noteStore.put({
4206
+ id: bundle.note.id,
4207
+ title: bundle.note.title,
4208
+ rawContent: bundle.note.rawContent,
4209
+ sourceRevision: bundle.note.sourceRevision ?? 1,
4210
+ blocks,
4211
+ date: bundle.note.targetDate,
4212
+ createdAt: bundle.note.createdAt,
4213
+ tags: bundle.note.tags ?? [],
4214
+ ...bundle.note.type ? { type: bundle.note.type } : {},
4215
+ ...bundle.note.sourceId ? { sourceId: bundle.note.sourceId } : {},
4216
+ seedOrigin: "user"
4217
+ });
4218
+ for (const b of Object.values(blocks)) {
4219
+ const hasRev = await revStore.get([bundle.note.id, b.id, b.version]);
4220
+ if (!hasRev) {
4221
+ await revStore.put({
4222
+ noteId: bundle.note.id,
4223
+ blockId: b.id,
4224
+ version: b.version,
4225
+ kind: b.kind,
4226
+ rawContent: bundle.note.rawContent.slice(b.from, b.to),
4227
+ savedAt: now,
4228
+ ...b.dialect ? { dialect: b.dialect } : {},
4229
+ ...b.sport ? { sport: b.sport } : {}
4230
+ });
4231
+ }
4232
+ }
4233
+ notesImported++;
4234
+ }
4235
+ }
4236
+ for (const session of bundle.sessions) {
4237
+ try {
4238
+ const parent = await noteStore.get(session.noteId);
4239
+ if (!parent) {
4240
+ throw new Error(`Parent note ${session.noteId} does not exist`);
4241
+ }
4242
+ const rev = await revStore.get([session.noteId, session.blockId, session.blockVersion]);
4243
+ if (!rev || rev.kind !== "wod") {
4244
+ throw new Error(
4245
+ `Pinned wod BlockRevision [${session.noteId}, ${session.blockId}, ${session.blockVersion}] does not exist`
4246
+ );
4247
+ }
4248
+ const sessionEvents = bundle.events.filter((ev) => ev.resultId === session.id);
4249
+ for (const ev of sessionEvents) {
4250
+ if (ev.noteId !== session.noteId || ev.blockId !== session.blockId || ev.blockVersion !== session.blockVersion || ev.blockContentId !== session.blockContentId) {
4251
+ throw new Error(`Event ${ev.id} does not match session ${session.id} identity`);
4252
+ }
4253
+ }
4254
+ await sessionStore.put(session);
4255
+ if (sessionEvents.length > 0) {
4256
+ await eventStore.putMany(sessionEvents);
4257
+ eventsImported += sessionEvents.length;
4258
+ }
4259
+ sessionsImported++;
4260
+ } catch (err) {
4261
+ errors.push(
4262
+ `Failed to import session ${session.id}: ${err instanceof Error ? err.message : String(err)}`
4263
+ );
4264
+ }
4265
+ }
4266
+ }
4267
+ }
4268
+ );
4269
+ return {
4270
+ notesImported,
4271
+ revisionsImported,
4272
+ sessionsImported,
4273
+ eventsImported,
4274
+ errors
4275
+ };
4276
+ }
4277
+ function mintUuid() {
4278
+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
4279
+ return crypto.randomUUID();
4280
+ }
4281
+ const bytes = new Uint8Array(16);
4282
+ crypto.getRandomValues(bytes);
4283
+ bytes[6] = bytes[6] & 15 | 64;
4284
+ bytes[8] = bytes[8] & 63 | 128;
4285
+ const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
4286
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
4287
+ }
4288
+ function utcCivilDateKey(epochMs) {
4289
+ const d = new Date(epochMs);
4290
+ const y = d.getFullYear();
4291
+ const m = String(d.getMonth() + 1).padStart(2, "0");
4292
+ const day = String(d.getDate()).padStart(2, "0");
4293
+ return `${y}-${m}-${day}`;
4294
+ }
4295
+ function computeWodContentId(blockSource) {
4296
+ const sec = wodWikiCore.parseDocumentSections(blockSource, { registeredWidgets: wodWikiCore.KNOWN_SECTION_WIDGETS }).find(
4297
+ (s) => s.scriptBlock
4298
+ );
4299
+ if (sec?.scriptBlock?.contentId) return sec.scriptBlock.contentId;
4300
+ if (sec?.scriptBlock?.content) return wodWikiCore.blockContentId(sec.scriptBlock.content);
4301
+ return void 0;
4302
+ }
4303
+ async function prepareJournalSessionRun(storage, input) {
4304
+ const startedAt = input.startedAt ?? Date.now();
4305
+ const sessionId = input.sessionId ?? mintUuid();
4306
+ const journalDate = input.journalDate ?? utcCivilDateKey(startedAt);
4307
+ return storage.transaction(
4308
+ ["notes", "block_revisions", "block_index", "sessions", "page", "page_notes", "notebook_links"],
4309
+ "readwrite",
4310
+ async (tx) => {
4311
+ const sourceNote = await tx.readonly("notes").get(input.noteId);
4312
+ if (!sourceNote) {
4313
+ throw new Error(`Note not found: ${input.noteId}`);
4314
+ }
4315
+ const existingSession = await tx.readonly("sessions").get(sessionId);
4316
+ if (existingSession) {
4317
+ throw new Error(`Session already exists: ${sessionId}`);
4318
+ }
4319
+ const sourceBlocks = Object.values(sourceNote.blocks);
4320
+ const selectedSourceBlock = input.blockId ? sourceNote.blocks[input.blockId] ?? sourceBlocks.find((b) => b.id === input.blockId) : sourceBlocks.find((b) => b.kind === "wod");
4321
+ if (!selectedSourceBlock || selectedSourceBlock.kind !== "wod") {
4322
+ throw new Error(`Selected workout block is unavailable on Note '${input.noteId}'.`);
4323
+ }
4324
+ const nbOrigin = wodWikiWql.notebookOriginOfItem(sourceNote);
4325
+ const resolvedNb = wodWikiWql.notebookOfItem(sourceNote);
4326
+ const editable = wodWikiCore.isNoteEditable(sourceNote, nbOrigin, resolvedNb);
4327
+ if (!editable) {
4328
+ const clonedNoteId = mintUuid();
4329
+ let ordinal = 0;
4330
+ const clonedBlocks = wodWikiCore.reconcileNoteBlocks(sourceNote.rawContent, {
4331
+ sourceRevision: 1,
4332
+ registeredWidgets: wodWikiCore.KNOWN_SECTION_WIDGETS,
4333
+ createId: () => `blk-${clonedNoteId.slice(0, 8)}-${ordinal++}`
4334
+ });
4335
+ const clonedBlockList = Object.values(clonedBlocks);
4336
+ const mappedBlock = clonedBlockList.find(
4337
+ (b) => b.kind === "wod" && b.from === selectedSourceBlock.from && b.to === selectedSourceBlock.to
4338
+ ) ?? clonedBlockList.find((b) => b.kind === "wod");
4339
+ if (!mappedBlock) {
4340
+ throw new Error("Cloned Journal Note contains no runnable workout block.");
4341
+ }
4342
+ const revisions = [];
4343
+ const projections = [];
4344
+ let pinnedRevision;
4345
+ for (const [pos, b] of clonedBlockList.entries()) {
4346
+ const slice = sourceNote.rawContent.slice(b.from, b.to);
4347
+ const rev = {
4348
+ noteId: clonedNoteId,
4349
+ blockId: b.id,
4350
+ version: 1,
4351
+ kind: b.kind,
4352
+ rawContent: slice,
4353
+ savedAt: startedAt,
4354
+ ...b.dialect ? { dialect: b.dialect } : {},
4355
+ ...b.sport ? { sport: b.sport } : {}
4356
+ };
4357
+ revisions.push(rev);
4358
+ if (b.id === mappedBlock.id) pinnedRevision = rev;
4359
+ const cid3 = b.kind === "wod" ? computeWodContentId(slice) : void 0;
4360
+ projections.push({
4361
+ id: `${clonedNoteId}:${b.id}`,
4362
+ noteId: clonedNoteId,
4363
+ blockId: b.id,
4364
+ blockVersion: 1,
4365
+ sourceRevision: 1,
4366
+ from: b.from,
4367
+ to: b.to,
4368
+ position: pos,
4369
+ dataType: b.kind,
4370
+ ...cid3 ? { blockContentId: cid3 } : {},
4371
+ rawContent: slice,
4372
+ noteTitle: sourceNote.title,
4373
+ createdAt: startedAt,
4374
+ isStatic: false,
4375
+ notebookId: "notebook/journal"
4376
+ });
4377
+ }
4378
+ const provenance = buildNoteProvenance(sourceNote, resolvedNb, startedAt);
4379
+ const dateEpoch = Date.parse(`${journalDate}T12:00:00Z`);
4380
+ const clonedNote = {
4381
+ id: clonedNoteId,
4382
+ title: sourceNote.title,
4383
+ rawContent: sourceNote.rawContent,
4384
+ sourceRevision: 1,
4385
+ blocks: clonedBlocks,
4386
+ ...Number.isFinite(dateEpoch) ? { date: dateEpoch } : {},
4387
+ createdAt: startedAt,
4388
+ type: "journal",
4389
+ sourceId: sourceNote.id,
4390
+ notebookIds: ["notebook/journal"],
4391
+ provenance,
4392
+ ...sourceNote.tags?.length ? { tags: [...sourceNote.tags] } : {},
4393
+ seedOrigin: "user"
4394
+ };
4395
+ let existingPages;
4396
+ try {
4397
+ existingPages = await tx.readonly("page").getAllFromIndex("by-date", journalDate);
4398
+ } catch {
4399
+ existingPages = (await tx.readonly("page").getAll()).filter((p) => p.date === journalDate);
4400
+ }
4401
+ let targetPage = existingPages[0];
4402
+ if (!targetPage) {
4403
+ targetPage = {
4404
+ id: mintUuid(),
4405
+ date: journalDate,
4406
+ title: journalDate,
4407
+ createdAt: startedAt
4408
+ };
4409
+ await tx.readwrite("page").put(targetPage);
4410
+ }
4411
+ const pageNote = {
4412
+ id: mintUuid(),
4413
+ pageId: targetPage.id,
4414
+ noteId: clonedNoteId,
4415
+ createdAt: startedAt
4416
+ };
4417
+ const cid2 = computeWodContentId(pinnedRevision.rawContent);
4418
+ const session2 = {
4419
+ id: sessionId,
4420
+ noteId: clonedNoteId,
4421
+ blockId: mappedBlock.id,
4422
+ blockVersion: 1,
4423
+ ...cid2 ? { blockContentId: cid2 } : {},
4424
+ origin: input.origin ?? "journal",
4425
+ pageId: targetPage.id,
4426
+ status: "in-progress",
4427
+ startTime: startedAt,
4428
+ endTime: startedAt,
4429
+ duration: 0,
4430
+ completed: false,
4431
+ createdAt: startedAt,
4432
+ notebookIds: ["notebook/journal"]
4433
+ };
4434
+ const links2 = [
4435
+ {
4436
+ id: makeNotebookLinkId("notebook/journal", "note", clonedNoteId),
4437
+ notebookId: "notebook/journal",
4438
+ targetKind: "note",
4439
+ targetId: clonedNoteId,
4440
+ noteId: clonedNoteId,
4441
+ createdAt: startedAt
4442
+ },
4443
+ {
4444
+ id: makeNotebookLinkId("notebook/journal", "session", sessionId),
4445
+ notebookId: "notebook/journal",
4446
+ targetKind: "session",
4447
+ targetId: sessionId,
4448
+ noteId: clonedNoteId,
4449
+ createdAt: startedAt
4450
+ }
4451
+ ];
4452
+ await tx.readwrite("notes").put(clonedNote);
4453
+ if (revisions.length > 0) await tx.readwrite("block_revisions").putMany(revisions);
4454
+ if (projections.length > 0) await tx.readwrite("block_index").putMany(projections);
4455
+ await tx.readwrite("page_notes").put(pageNote);
4456
+ await tx.readwrite("sessions").put(session2);
4457
+ await tx.readwrite("notebook_links").putMany(links2);
4458
+ return {
4459
+ note: clonedNote,
4460
+ revision: pinnedRevision,
4461
+ session: session2,
4462
+ clonedFromReadOnly: true,
4463
+ upstreamNoteId: sourceNote.id
4464
+ };
4465
+ }
4466
+ const isPlayground = sourceNote.type === "playground" || sourceNote.sourceId === "playground" || sourceNote.notebookId === "notebook/playground";
4467
+ const baseNotebooks = isPlayground ? ["notebook/journal", "notebook/playground"] : ["notebook/journal"];
4468
+ const mergedNotebooks = [
4469
+ .../* @__PURE__ */ new Set([
4470
+ ...baseNotebooks,
4471
+ ...sourceNote.notebookIds ?? [],
4472
+ ...sourceNote.notebookId ? [sourceNote.notebookId] : []
4473
+ ])
4474
+ ];
4475
+ const updatedNote = JSON.stringify(sourceNote.notebookIds) === JSON.stringify(mergedNotebooks) ? sourceNote : { ...sourceNote, notebookIds: mergedNotebooks };
4476
+ if (updatedNote !== sourceNote) {
4477
+ await tx.readwrite("notes").put(updatedNote);
4478
+ }
4479
+ let revision = await tx.readonly("block_revisions").get([sourceNote.id, selectedSourceBlock.id, selectedSourceBlock.version]);
4480
+ if (!revision) {
4481
+ revision = {
4482
+ noteId: sourceNote.id,
4483
+ blockId: selectedSourceBlock.id,
4484
+ version: selectedSourceBlock.version,
4485
+ kind: selectedSourceBlock.kind,
4486
+ rawContent: sourceNote.rawContent.slice(selectedSourceBlock.from, selectedSourceBlock.to),
4487
+ savedAt: startedAt,
4488
+ ...selectedSourceBlock.dialect ? { dialect: selectedSourceBlock.dialect } : {},
4489
+ ...selectedSourceBlock.sport ? { sport: selectedSourceBlock.sport } : {}
4490
+ };
4491
+ await tx.readwrite("block_revisions").put(revision);
4492
+ }
4493
+ const cid = computeWodContentId(revision.rawContent);
4494
+ const effectiveOrigin = input.origin ?? (isPlayground ? "playground" : "journal");
4495
+ const session = {
4496
+ id: sessionId,
4497
+ noteId: sourceNote.id,
4498
+ blockId: selectedSourceBlock.id,
4499
+ blockVersion: revision.version,
4500
+ ...cid ? { blockContentId: cid } : {},
4501
+ origin: effectiveOrigin,
4502
+ status: "in-progress",
4503
+ startTime: startedAt,
4504
+ endTime: startedAt,
4505
+ duration: 0,
4506
+ completed: false,
4507
+ createdAt: startedAt,
4508
+ notebookIds: [...baseNotebooks]
4509
+ };
4510
+ const links = mergedNotebooks.map((nbId) => ({
4511
+ id: makeNotebookLinkId(nbId, "note", sourceNote.id),
4512
+ notebookId: nbId,
4513
+ targetKind: "note",
4514
+ targetId: sourceNote.id,
4515
+ noteId: sourceNote.id,
4516
+ createdAt: startedAt
4517
+ }));
4518
+ links.push({
4519
+ id: makeNotebookLinkId("notebook/journal", "session", sessionId),
4520
+ notebookId: "notebook/journal",
4521
+ targetKind: "session",
4522
+ targetId: sessionId,
4523
+ noteId: sourceNote.id,
4524
+ createdAt: startedAt
4525
+ });
4526
+ await tx.readwrite("sessions").put(session);
4527
+ await tx.readwrite("notebook_links").putMany(links);
4528
+ return {
4529
+ note: updatedNote,
4530
+ revision,
4531
+ session,
4532
+ clonedFromReadOnly: false
4533
+ };
4534
+ }
4535
+ );
4536
+ }
4537
+ async function resolveUpstreamProvenance(storage, note) {
4538
+ const sourceNoteId = note.provenance?.sourceNoteId ?? (note.sourceId && !note.sourceId.startsWith("/") && !note.sourceId.includes(":") && note.sourceId !== "playground" ? note.sourceId : void 0);
4539
+ if (!sourceNoteId) return null;
4540
+ const upstream = await storage.readonly("notes").get(sourceNoteId);
4541
+ if (upstream) {
4542
+ return {
4543
+ exists: true,
4544
+ sourceNoteId,
4545
+ title: upstream.title,
4546
+ sourceVersion: note.provenance?.sourceVersion,
4547
+ currentUpstreamVersion: upstream.seedVersion ?? upstream.sourceRevision,
4548
+ sourceCommit: note.provenance?.sourceCommit ?? upstream.seedCommit,
4549
+ feedSourceId: note.provenance?.feedSourceId ?? upstream.feedSourceId,
4550
+ sourceNotebookId: note.provenance?.sourceNotebookId ?? wodWikiWql.notebookOfItem(upstream),
4551
+ sourcePath: note.provenance?.sourcePath ?? upstream.sourcePath
4552
+ };
4553
+ }
4554
+ return {
4555
+ exists: false,
4556
+ sourceNoteId,
4557
+ sourceVersion: note.provenance?.sourceVersion,
4558
+ sourceCommit: note.provenance?.sourceCommit,
4559
+ feedSourceId: note.provenance?.feedSourceId,
4560
+ sourceNotebookId: note.provenance?.sourceNotebookId,
4561
+ sourcePath: note.provenance?.sourcePath
4562
+ };
4563
+ }
4564
+ function buildNoteProvenance(sourceNote, sourceNotebookId, clonedAt) {
4565
+ return {
4566
+ sourceNoteId: sourceNote.id,
4567
+ sourceVersion: sourceNote.seedVersion ?? sourceNote.sourceRevision,
4568
+ ...sourceNote.seedCommit ? { sourceCommit: sourceNote.seedCommit } : {},
4569
+ ...sourceNote.feedSourceId ? { feedSourceId: sourceNote.feedSourceId } : {},
4570
+ ...sourceNotebookId ? { sourceNotebookId } : {},
4571
+ ...sourceNote.sourcePath ? { sourcePath: sourceNote.sourcePath } : {},
4572
+ clonedAt
4573
+ };
4574
+ }
4575
+
4576
+ Object.defineProperty(exports, "ABSENT", {
4577
+ enumerable: true,
4578
+ get: function () { return wodWikiLang.ABSENT; }
4579
+ });
4580
+ Object.defineProperty(exports, "AGGREGATE_BUILTINS", {
4581
+ enumerable: true,
4582
+ get: function () { return wodWikiLang.AGGREGATE_BUILTINS; }
4583
+ });
4584
+ Object.defineProperty(exports, "AUTHORITATIVE_CASTS", {
4585
+ enumerable: true,
4586
+ get: function () { return wodWikiLang.AUTHORITATIVE_CASTS; }
4587
+ });
4588
+ Object.defineProperty(exports, "AmrapLogicStrategy", {
4589
+ enumerable: true,
4590
+ get: function () { return wodWikiLang.AmrapLogicStrategy; }
4591
+ });
4592
+ Object.defineProperty(exports, "AnalyticsEngine", {
4593
+ enumerable: true,
4594
+ get: function () { return wodWikiLang.AnalyticsEngine; }
4595
+ });
4596
+ Object.defineProperty(exports, "AnalyticsTransformer", {
4597
+ enumerable: true,
4598
+ get: function () { return wodWikiLang.AnalyticsTransformer; }
4599
+ });
4600
+ Object.defineProperty(exports, "BUILTIN_CALCS", {
4601
+ enumerable: true,
4602
+ get: function () { return wodWikiLang.BUILTIN_CALCS; }
4603
+ });
4604
+ Object.defineProperty(exports, "BUNDLED_EFFORT_COUNT", {
4605
+ enumerable: true,
4606
+ get: function () { return wodWikiLang.BUNDLED_EFFORT_COUNT; }
4607
+ });
4608
+ Object.defineProperty(exports, "BlockBuilder", {
4609
+ enumerable: true,
4610
+ get: function () { return wodWikiLang.BlockBuilder; }
4611
+ });
4612
+ Object.defineProperty(exports, "BlockContext", {
4613
+ enumerable: true,
4614
+ get: function () { return wodWikiLang.BlockContext; }
4615
+ });
4616
+ Object.defineProperty(exports, "ButtonBehavior", {
4617
+ enumerable: true,
4618
+ get: function () { return wodWikiLang.ButtonBehavior; }
4619
+ });
4620
+ Object.defineProperty(exports, "CONSUMED_HINTS", {
4621
+ enumerable: true,
4622
+ get: function () { return wodWikiLang.CONSUMED_HINTS; }
4623
+ });
4624
+ Object.defineProperty(exports, "CONSUMED_HINT_KEYS", {
4625
+ enumerable: true,
4626
+ get: function () { return wodWikiLang.CONSUMED_HINT_KEYS; }
4627
+ });
4628
+ Object.defineProperty(exports, "CONTEXT_ATOMS", {
4629
+ enumerable: true,
4630
+ get: function () { return wodWikiLang.CONTEXT_ATOMS; }
4631
+ });
4632
+ Object.defineProperty(exports, "CalcEngine", {
4633
+ enumerable: true,
4634
+ get: function () { return wodWikiLang.CalcEngine; }
4635
+ });
4636
+ Object.defineProperty(exports, "CalculationRegistry", {
4637
+ enumerable: true,
4638
+ get: function () { return wodWikiLang.CalculationRegistry; }
4639
+ });
4640
+ Object.defineProperty(exports, "CardioDialect", {
4641
+ enumerable: true,
4642
+ get: function () { return wodWikiLang.CardioDialect; }
4643
+ });
4644
+ Object.defineProperty(exports, "ChildSelectionBehavior", {
4645
+ enumerable: true,
4646
+ get: function () { return wodWikiLang.ChildSelectionBehavior; }
4647
+ });
4648
+ Object.defineProperty(exports, "ChildrenStrategy", {
4649
+ enumerable: true,
4650
+ get: function () { return wodWikiLang.ChildrenStrategy; }
4651
+ });
4652
+ Object.defineProperty(exports, "ChoiceGroupMetric", {
4653
+ enumerable: true,
4654
+ get: function () { return wodWikiLang.ChoiceGroupMetric; }
4655
+ });
4656
+ Object.defineProperty(exports, "ClimbDialect", {
4657
+ enumerable: true,
4658
+ get: function () { return wodWikiLang.ClimbDialect; }
4659
+ });
4660
+ Object.defineProperty(exports, "ClimbMetricType", {
4661
+ enumerable: true,
4662
+ get: function () { return wodWikiLang.ClimbMetricType; }
4663
+ });
4664
+ Object.defineProperty(exports, "CountdownTimerBehavior", {
4665
+ enumerable: true,
4666
+ get: function () { return wodWikiLang.CountdownTimerBehavior; }
4667
+ });
4668
+ Object.defineProperty(exports, "CountupTimerBehavior", {
4669
+ enumerable: true,
4670
+ get: function () { return wodWikiLang.CountupTimerBehavior; }
1291
4671
  });
1292
4672
  Object.defineProperty(exports, "CrossFitDialect", {
1293
4673
  enumerable: true,
1294
4674
  get: function () { return wodWikiLang.CrossFitDialect; }
1295
4675
  });
4676
+ Object.defineProperty(exports, "DAY", {
4677
+ enumerable: true,
4678
+ get: function () { return wodWikiLang.DAY; }
4679
+ });
1296
4680
  Object.defineProperty(exports, "DEFAULT_RESOLVER_OPTIONS", {
1297
4681
  enumerable: true,
1298
4682
  get: function () { return wodWikiLang.DEFAULT_RESOLVER_OPTIONS; }
@@ -1601,6 +4985,10 @@ Object.defineProperty(exports, "bundledEfforts", {
1601
4985
  enumerable: true,
1602
4986
  get: function () { return wodWikiLang.bundledEfforts; }
1603
4987
  });
4988
+ Object.defineProperty(exports, "calculateDuration", {
4989
+ enumerable: true,
4990
+ get: function () { return wodWikiLang.calculateDuration; }
4991
+ });
1604
4992
  Object.defineProperty(exports, "calculateElapsed", {
1605
4993
  enumerable: true,
1606
4994
  get: function () { return wodWikiLang.calculateElapsed; }
@@ -1637,6 +5025,10 @@ Object.defineProperty(exports, "computeLabel", {
1637
5025
  enumerable: true,
1638
5026
  get: function () { return wodWikiLang.computeLabel; }
1639
5027
  });
5028
+ Object.defineProperty(exports, "computeWorkloadRollups", {
5029
+ enumerable: true,
5030
+ get: function () { return wodWikiLang.computeWorkloadRollups; }
5031
+ });
1640
5032
  Object.defineProperty(exports, "createAnalyticsEngineForBlock", {
1641
5033
  enumerable: true,
1642
5034
  get: function () { return wodWikiLang.createAnalyticsEngineForBlock; }
@@ -1665,6 +5057,14 @@ Object.defineProperty(exports, "createParser", {
1665
5057
  enumerable: true,
1666
5058
  get: function () { return wodWikiLang.createParser; }
1667
5059
  });
5060
+ Object.defineProperty(exports, "dailySessionLoads", {
5061
+ enumerable: true,
5062
+ get: function () { return wodWikiLang.dailySessionLoads; }
5063
+ });
5064
+ Object.defineProperty(exports, "dayBucket", {
5065
+ enumerable: true,
5066
+ get: function () { return wodWikiLang.dayBucket; }
5067
+ });
1668
5068
  Object.defineProperty(exports, "dedupeEntitiesByPrecedence", {
1669
5069
  enumerable: true,
1670
5070
  get: function () { return wodWikiLang.dedupeEntitiesByPrecedence; }
@@ -1713,10 +5113,46 @@ Object.defineProperty(exports, "findUnresolvedChoices", {
1713
5113
  enumerable: true,
1714
5114
  get: function () { return wodWikiLang.findUnresolvedChoices; }
1715
5115
  });
5116
+ Object.defineProperty(exports, "formatDurationCompact", {
5117
+ enumerable: true,
5118
+ get: function () { return wodWikiLang.formatDurationCompact; }
5119
+ });
5120
+ Object.defineProperty(exports, "formatDurationSmart", {
5121
+ enumerable: true,
5122
+ get: function () { return wodWikiLang.formatDurationSmart; }
5123
+ });
5124
+ Object.defineProperty(exports, "formatSecondsHHMMSS", {
5125
+ enumerable: true,
5126
+ get: function () { return wodWikiLang.formatSecondsHHMMSS; }
5127
+ });
5128
+ Object.defineProperty(exports, "formatSecondsMMSS", {
5129
+ enumerable: true,
5130
+ get: function () { return wodWikiLang.formatSecondsMMSS; }
5131
+ });
1716
5132
  Object.defineProperty(exports, "formatSoundTrigger", {
1717
5133
  enumerable: true,
1718
5134
  get: function () { return wodWikiLang.formatSoundTrigger; }
1719
5135
  });
5136
+ Object.defineProperty(exports, "formatTime", {
5137
+ enumerable: true,
5138
+ get: function () { return wodWikiLang.formatTime; }
5139
+ });
5140
+ Object.defineProperty(exports, "formatTimeHHMMSS", {
5141
+ enumerable: true,
5142
+ get: function () { return wodWikiLang.formatTimeHHMMSS; }
5143
+ });
5144
+ Object.defineProperty(exports, "formatTimeMMSS", {
5145
+ enumerable: true,
5146
+ get: function () { return wodWikiLang.formatTimeMMSS; }
5147
+ });
5148
+ Object.defineProperty(exports, "formatTimePrecise", {
5149
+ enumerable: true,
5150
+ get: function () { return wodWikiLang.formatTimePrecise; }
5151
+ });
5152
+ Object.defineProperty(exports, "formatTimestamp", {
5153
+ enumerable: true,
5154
+ get: function () { return wodWikiLang.formatTimestamp; }
5155
+ });
1720
5156
  Object.defineProperty(exports, "frozenNow", {
1721
5157
  enumerable: true,
1722
5158
  get: function () { return wodWikiLang.frozenNow; }
@@ -1725,6 +5161,10 @@ Object.defineProperty(exports, "getAnalyticsFromLogs", {
1725
5161
  enumerable: true,
1726
5162
  get: function () { return wodWikiLang.getAnalyticsFromLogs; }
1727
5163
  });
5164
+ Object.defineProperty(exports, "getAnalyticsFromRuntime", {
5165
+ enumerable: true,
5166
+ get: function () { return wodWikiLang.getAnalyticsFromRuntime; }
5167
+ });
1728
5168
  Object.defineProperty(exports, "getHints", {
1729
5169
  enumerable: true,
1730
5170
  get: function () { return wodWikiLang.getHints; }
@@ -1845,6 +5285,10 @@ Object.defineProperty(exports, "resolveTagContributions", {
1845
5285
  enumerable: true,
1846
5286
  get: function () { return wodWikiLang.resolveTagContributions; }
1847
5287
  });
5288
+ Object.defineProperty(exports, "roundToTenth", {
5289
+ enumerable: true,
5290
+ get: function () { return wodWikiLang.roundToTenth; }
5291
+ });
1848
5292
  Object.defineProperty(exports, "runMetricShakeOutQueue", {
1849
5293
  enumerable: true,
1850
5294
  get: function () { return wodWikiLang.runMetricShakeOutQueue; }
@@ -2013,6 +5457,10 @@ Object.defineProperty(exports, "WQL_VIRTUAL_DIMS", {
2013
5457
  enumerable: true,
2014
5458
  get: function () { return wodWikiWql.WQL_VIRTUAL_DIMS; }
2015
5459
  });
5460
+ Object.defineProperty(exports, "bindQueryParams", {
5461
+ enumerable: true,
5462
+ get: function () { return wodWikiWql.bindQueryParams; }
5463
+ });
2016
5464
  Object.defineProperty(exports, "buildDashboardDocument", {
2017
5465
  enumerable: true,
2018
5466
  get: function () { return wodWikiWql.buildDashboardDocument; }
@@ -2029,6 +5477,14 @@ Object.defineProperty(exports, "buildWidgetsForWqlScope", {
2029
5477
  enumerable: true,
2030
5478
  get: function () { return wodWikiWql.buildWidgetsForWqlScope; }
2031
5479
  });
5480
+ Object.defineProperty(exports, "collectQueryBlockParams", {
5481
+ enumerable: true,
5482
+ get: function () { return wodWikiWql.collectQueryBlockParams; }
5483
+ });
5484
+ Object.defineProperty(exports, "collectQueryParams", {
5485
+ enumerable: true,
5486
+ get: function () { return wodWikiWql.collectQueryParams; }
5487
+ });
2032
5488
  Object.defineProperty(exports, "dashboardSlug", {
2033
5489
  enumerable: true,
2034
5490
  get: function () { return wodWikiWql.dashboardSlug; }
@@ -2057,6 +5513,10 @@ Object.defineProperty(exports, "isDashboardWidgetType", {
2057
5513
  enumerable: true,
2058
5514
  get: function () { return wodWikiWql.isDashboardWidgetType; }
2059
5515
  });
5516
+ Object.defineProperty(exports, "isDefaultShorthandQueryBlock", {
5517
+ enumerable: true,
5518
+ get: function () { return wodWikiWql.isDefaultShorthandQueryBlock; }
5519
+ });
2060
5520
  Object.defineProperty(exports, "isFindQuery", {
2061
5521
  enumerable: true,
2062
5522
  get: function () { return wodWikiWql.isFindQuery; }
@@ -2069,6 +5529,10 @@ Object.defineProperty(exports, "isPipelineQuery", {
2069
5529
  enumerable: true,
2070
5530
  get: function () { return wodWikiWql.isPipelineQuery; }
2071
5531
  });
5532
+ Object.defineProperty(exports, "isYamlQueryBlockBody", {
5533
+ enumerable: true,
5534
+ get: function () { return wodWikiWql.isYamlQueryBlockBody; }
5535
+ });
2072
5536
  Object.defineProperty(exports, "normalizeWql", {
2073
5537
  enumerable: true,
2074
5538
  get: function () { return wodWikiWql.normalizeWql; }
@@ -2081,10 +5545,22 @@ Object.defineProperty(exports, "notebookSlugFromId", {
2081
5545
  enumerable: true,
2082
5546
  get: function () { return wodWikiWql.notebookSlugFromId; }
2083
5547
  });
5548
+ Object.defineProperty(exports, "notebooksOfItem", {
5549
+ enumerable: true,
5550
+ get: function () { return wodWikiWql.notebooksOfItem; }
5551
+ });
5552
+ Object.defineProperty(exports, "parseFilterFragment", {
5553
+ enumerable: true,
5554
+ get: function () { return wodWikiWql.parseFilterFragment; }
5555
+ });
2084
5556
  Object.defineProperty(exports, "parseQuery", {
2085
5557
  enumerable: true,
2086
5558
  get: function () { return wodWikiWql.parseQuery; }
2087
5559
  });
5560
+ Object.defineProperty(exports, "parseQueryBlock", {
5561
+ enumerable: true,
5562
+ get: function () { return wodWikiWql.parseQueryBlock; }
5563
+ });
2088
5564
  Object.defineProperty(exports, "parseQueryWidgetSuffix", {
2089
5565
  enumerable: true,
2090
5566
  get: function () { return wodWikiWql.parseQueryWidgetSuffix; }
@@ -2093,6 +5569,14 @@ Object.defineProperty(exports, "parseWqlSuffixes", {
2093
5569
  enumerable: true,
2094
5570
  get: function () { return wodWikiWql.parseWqlSuffixes; }
2095
5571
  });
5572
+ Object.defineProperty(exports, "queryBlockAttributes", {
5573
+ enumerable: true,
5574
+ get: function () { return wodWikiWql.queryBlockAttributes; }
5575
+ });
5576
+ Object.defineProperty(exports, "queryBlockToDocumentText", {
5577
+ enumerable: true,
5578
+ get: function () { return wodWikiWql.queryBlockToDocumentText; }
5579
+ });
2096
5580
  Object.defineProperty(exports, "resolveEntityScope", {
2097
5581
  enumerable: true,
2098
5582
  get: function () { return wodWikiWql.resolveEntityScope; }
@@ -2105,6 +5589,14 @@ Object.defineProperty(exports, "serialize", {
2105
5589
  enumerable: true,
2106
5590
  get: function () { return wodWikiWql.serialize; }
2107
5591
  });
5592
+ Object.defineProperty(exports, "serializeQueryBlock", {
5593
+ enumerable: true,
5594
+ get: function () { return wodWikiWql.serializeQueryBlock; }
5595
+ });
5596
+ Object.defineProperty(exports, "serializeQueryBlockFence", {
5597
+ enumerable: true,
5598
+ get: function () { return wodWikiWql.serializeQueryBlockFence; }
5599
+ });
2108
5600
  Object.defineProperty(exports, "splitAtWhere", {
2109
5601
  enumerable: true,
2110
5602
  get: function () { return wodWikiWql.splitAtWhere; }
@@ -2141,19 +5633,27 @@ Object.defineProperty(exports, "wqlTerms", {
2141
5633
  enumerable: true,
2142
5634
  get: function () { return wodWikiWql.wqlTerms; }
2143
5635
  });
5636
+ exports.APP_ORIGIN = APP_ORIGIN;
2144
5637
  exports.BUILD_TIME = BUILD_TIME;
2145
5638
  exports.CANVAS_CHUNK_ID = CANVAS_CHUNK_ID;
2146
5639
  exports.DASHBOARDS_CHUNK_ID = DASHBOARDS_CHUNK_ID;
5640
+ exports.DirectoryHandleFeedTree = DirectoryHandleFeedTree;
2147
5641
  exports.EFFORTS_CHUNK_ID = EFFORTS_CHUNK_ID;
2148
5642
  exports.EQUIPMENT_CHUNK_ID = EQUIPMENT_CHUNK_ID;
5643
+ exports.FeedTreeError = FeedTreeError;
2149
5644
  exports.GIT_SHA = GIT_SHA;
5645
+ exports.HttpFeedTree = HttpFeedTree;
5646
+ exports.MemoryFeedTree = MemoryFeedTree;
2150
5647
  exports.NOTE_ID_FRONTMATTER_KEY = NOTE_ID_FRONTMATTER_KEY;
5648
+ exports.PUBLISHED_FEED_META_KEY = PUBLISHED_FEED_META_KEY;
5649
+ exports.QR_SCRIPT_ID = QR_SCRIPT_ID;
2151
5650
  exports.SEED_BROADCAST_CHANNEL = SEED_BROADCAST_CHANNEL;
2152
5651
  exports.SEED_NAMESPACE = SEED_NAMESPACE;
2153
5652
  exports.SEED_REGISTERED_WIDGETS = SEED_REGISTERED_WIDGETS;
2154
5653
  exports.SEED_SCHEMA = SEED_SCHEMA;
2155
5654
  exports.SEMVER = SEMVER;
2156
5655
  exports.SESSION_CSV_HEADER = SESSION_CSV_HEADER;
5656
+ exports.TELEMETRY_CSV_HEADER = TELEMETRY_CSV_HEADER;
2157
5657
  exports.VERSION = VERSION;
2158
5658
  exports.applySeedChunk = applySeedChunk;
2159
5659
  exports.assertNotebookIndex = assertNotebookIndex;
@@ -2161,38 +5661,72 @@ exports.assertSeedManifest = assertSeedManifest;
2161
5661
  exports.assertSeedRow = assertSeedRow;
2162
5662
  exports.assertSeedRows = assertSeedRows;
2163
5663
  exports.backfillFeedProvenance = backfillFeedProvenance;
5664
+ exports.buildNoteProvenance = buildNoteProvenance;
2164
5665
  exports.buildStatementTree = buildStatementTree;
2165
5666
  exports.canvasRouteSlug = canvasRouteSlug;
5667
+ exports.checkUnpublishedFeedChanges = checkUnpublishedFeedChanges;
5668
+ exports.cloneRemoteRecord = cloneRemoteRecord;
2166
5669
  exports.composeNoteMarkdown = composeNoteMarkdown;
2167
5670
  exports.createIRFile = createIRFile;
5671
+ exports.createUserNotebookLanding = createUserNotebookLanding;
2168
5672
  exports.csvToEquipmentLabels = csvToEquipmentLabels;
2169
5673
  exports.csvToSessionRows = csvToSessionRows;
5674
+ exports.csvToTelemetryBundle = csvToTelemetryBundle;
5675
+ exports.decodeUtf8 = decodeUtf8;
2170
5676
  exports.defineLanguagePack = defineLanguagePack;
2171
5677
  exports.effortToMarkdown = effortToMarkdown;
2172
5678
  exports.emptySeedMeta = emptySeedMeta;
5679
+ exports.encodeUtf8 = encodeUtf8;
2173
5680
  exports.equipmentToCsv = equipmentToCsv;
2174
5681
  exports.equipmentToMarkdown = equipmentToMarkdown;
5682
+ exports.exportPortableFilesFromStorage = exportPortableFilesFromStorage;
2175
5683
  exports.extractNoteIdentity = extractNoteIdentity;
2176
5684
  exports.extractTypedTags = extractTypedTags;
2177
5685
  exports.feedIdOfMetaKey = feedIdOfMetaKey;
5686
+ exports.getNoteNotebooks = getNoteNotebooks;
5687
+ exports.getNotePublicationSummary = getNotePublicationSummary;
2178
5688
  exports.getRegisteredLanguagePacks = getRegisteredLanguagePacks;
2179
5689
  exports.inMemoryEventStore = inMemoryEventStore;
5690
+ exports.ingestPortableFilesIntoStorage = ingestPortableFilesIntoStorage;
2180
5691
  exports.injectIdentityFrontmatter = injectIdentityFrontmatter;
2181
5692
  exports.isIRFile = isIRFile;
2182
5693
  exports.listLanguagePacks = listLanguagePacks;
5694
+ exports.listScopedPropertyOverrides = listScopedPropertyOverrides;
5695
+ exports.makeNotebookLinkId = makeNotebookLinkId;
5696
+ exports.makeScopedOverrideId = makeScopedOverrideId;
2183
5697
  exports.migrateNotebookVocabulary = migrateNotebookVocabulary;
5698
+ exports.normalizeFeedTreePath = normalizeFeedTreePath;
2184
5699
  exports.notebookSlugForChunkId = notebookSlugForChunkId;
2185
5700
  exports.parseCsvLine = parseCsvLine;
5701
+ exports.parseFrontmatterDateMs = parseFrontmatterDateMs;
5702
+ exports.parseNoteMarkdown = parseNoteMarkdown;
5703
+ exports.prepareJournalSessionRun = prepareJournalSessionRun;
5704
+ exports.previewRemoteNotebook = previewRemoteNotebook;
5705
+ exports.previewRemoteRecord = previewRemoteRecord;
5706
+ exports.promoteNoteToNotebooks = promoteNoteToNotebooks;
5707
+ exports.promoteReferencedOverridesToNotebook = promoteReferencedOverridesToNotebook;
5708
+ exports.publishFeedFromStorage = publishFeedFromStorage;
5709
+ exports.qrInlineScript = qrInlineScript;
2186
5710
  exports.readFrontmatterMeta = readFrontmatterMeta;
2187
5711
  exports.registerLanguagePack = registerLanguagePack;
5712
+ exports.removeNoteFromNotebook = removeNoteFromNotebook;
5713
+ exports.renderFeedLandingHtml = renderFeedLandingHtml;
5714
+ exports.resolveScopedPropertyCatalog = resolveScopedPropertyCatalog;
5715
+ exports.resolveUpstreamProvenance = resolveUpstreamProvenance;
5716
+ exports.saveScopedPropertyOverride = saveScopedPropertyOverride;
2188
5717
  exports.seedMetaKey = seedMetaKey;
2189
5718
  exports.seedNoteId = seedNoteId;
2190
5719
  exports.seedNoteSourceId = seedNoteSourceId;
2191
5720
  exports.seedPrecedenceRank = seedPrecedenceRank;
2192
5721
  exports.seedSourceTier = seedSourceTier;
2193
5722
  exports.sessionToCsv = sessionToCsv;
5723
+ exports.setNoteNotebooks = setNoteNotebooks;
5724
+ exports.setNotebookPublic = setNotebookPublic;
5725
+ exports.setSessionPublic = setSessionPublic;
5726
+ exports.sha256HexAsync = sha256HexAsync;
2194
5727
  exports.splitCsvRecords = splitCsvRecords;
2195
5728
  exports.statementToNode = statementToNode;
5729
+ exports.telemetryBundleToCsv = telemetryBundleToCsv;
2196
5730
  exports.unregisterLanguagePack = unregisterLanguagePack;
2197
5731
  Object.keys(wodWikiCore).forEach(function (k) {
2198
5732
  if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {