@bitcobblers/wod-wiki-engine 0.59.2236 → 0.59.2240

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
@@ -4,6 +4,7 @@ var wodWikiCore = require('@bitcobblers/wod-wiki-core');
4
4
  var wodWikiLang = require('@bitcobblers/wod-wiki-lang');
5
5
  var wodWikiWql = require('@bitcobblers/wod-wiki-wql');
6
6
  var wodWikiStorage = require('@bitcobblers/wod-wiki-storage');
7
+ var testing = require('@bitcobblers/wod-wiki-core/testing');
7
8
 
8
9
  // src/index.ts
9
10
  var activePacks = /* @__PURE__ */ new Map();
@@ -66,7 +67,7 @@ function inMemoryEventStore(events) {
66
67
  getEventsByTimeRange: async (start, end) => rows.filter((r) => r.timestamp >= start && r.timestamp <= end),
67
68
  getEventsByResult: async (resultId) => rows.filter((r) => r.resultId === resultId),
68
69
  getEventsForNote: async (noteId) => rows.filter((r) => r.noteId === noteId),
69
- getEventsByContent: async (blockContentId5) => rows.filter((r) => r.blockContentId === blockContentId5),
70
+ getEventsByContent: async (blockContentId6) => rows.filter((r) => r.blockContentId === blockContentId6),
70
71
  scanAll: async () => rows,
71
72
  appendEvents: async (appended) => {
72
73
  rows.push(...appended);
@@ -940,13 +941,13 @@ function csvToTelemetryBundle(csv) {
940
941
  }
941
942
 
942
943
  // src/version.ts
943
- var VERSION = "0.59.2236";
944
- var GIT_SHA = "7b4743b";
945
- var BUILD_TIME = "2026-11-16T04:52:27.639Z";
944
+ var VERSION = "0.59.2240";
945
+ var GIT_SHA = "920602f";
946
+ var BUILD_TIME = "2026-11-17T14:03:29.403Z";
946
947
  var SEMVER = {
947
- version: "0.59.2236",
948
- gitSha: "7b4743b",
949
- buildTime: "2026-11-16T04:52:27.639Z"
948
+ version: "0.59.2240",
949
+ gitSha: "920602f",
950
+ buildTime: "2026-11-17T14:03:29.403Z"
950
951
  };
951
952
  var SEED_SCHEMA = 9;
952
953
  var SEED_REGISTERED_WIDGETS = wodWikiCore.KNOWN_SECTION_WIDGETS;
@@ -1837,7 +1838,7 @@ async function applyPreparedSeedChunkInTx(tx, prepared) {
1837
1838
  if (compiledById.get(compiled.blockId)?.dataType !== "wod") throw new Error("Orphan seed session pin");
1838
1839
  const prior = existingTelemetrySessions.get(compiled.id);
1839
1840
  if (prior && prior.noteId !== id) throw new Error(`Seed session ${compiled.id} belongs to another note`);
1840
- if (prior?.origin) {
1841
+ if (prior && (prior.origin || !prior.id.startsWith("seed:"))) {
1841
1842
  userRecordedSessions.add(compiled.id);
1842
1843
  continue;
1843
1844
  }
@@ -3189,10 +3190,26 @@ async function collectPublicStorageState(storage, options = {}) {
3189
3190
  storedCheckpoint
3190
3191
  };
3191
3192
  }
3193
+ async function recordPublishedFeedCheckpoint(storage, report) {
3194
+ const chunkShas = {};
3195
+ for (const c of report.manifest.chunks) chunkShas[c.id] = c.sha256;
3196
+ const cp = {
3197
+ key: PUBLISHED_FEED_META_KEY,
3198
+ version: report.manifest.version,
3199
+ builtAt: report.manifest.builtAt,
3200
+ manifestSha256: report.manifestSha256,
3201
+ chunkShas
3202
+ };
3203
+ await storage.transaction(["meta"], "readwrite", async (tx) => {
3204
+ await tx.readwrite("meta").put(cp);
3205
+ });
3206
+ }
3192
3207
  async function publishFeedFromStorage(storage, tree, options = {}) {
3208
+ options.signal?.throwIfAborted();
3193
3209
  const t0 = Date.now();
3194
3210
  const layout = options.layout ?? "feed";
3195
3211
  const state = await collectPublicStorageState(storage, options);
3212
+ options.signal?.throwIfAborted();
3196
3213
  if (state.notebooks.size === 0) {
3197
3214
  throw new Error("No public notebooks found to publish. Mark at least one user-owned notebook as Public first.");
3198
3215
  }
@@ -3480,28 +3497,19 @@ ${group.description ?? ""}
3480
3497
  const manifestBytes = encodeUtf8(JSON.stringify(manifest, null, 2) + "\n");
3481
3498
  const manifestSha256 = await sha256HexAsync(manifestBytes);
3482
3499
  await tree.write(`${artifactPrefix}manifest.json`, manifestBytes);
3483
- const shouldCheckpoint = options.recordCheckpoint ?? (layout === "feed" && !options.notebookSlug);
3484
- if (shouldCheckpoint) {
3485
- const chunkShas = {};
3486
- for (const c of manifestChunks) chunkShas[c.id] = c.sha256;
3487
- const cp = {
3488
- key: PUBLISHED_FEED_META_KEY,
3489
- version: nextVersion,
3490
- builtAt,
3491
- manifestSha256,
3492
- chunkShas
3493
- };
3494
- await storage.transaction(["meta"], "readwrite", async (tx) => {
3495
- await tx.readwrite("meta").put(cp);
3496
- });
3497
- }
3498
- return {
3500
+ const report = {
3499
3501
  manifest,
3500
3502
  notebooks: sortedSlugs,
3501
3503
  totalNotes,
3502
3504
  totalPublicSessions,
3503
3505
  manifestSha256
3504
3506
  };
3507
+ const shouldCheckpoint = options.recordCheckpoint ?? (layout === "feed" && !options.notebookSlug);
3508
+ if (shouldCheckpoint) {
3509
+ options.signal?.throwIfAborted();
3510
+ await recordPublishedFeedCheckpoint(storage, report);
3511
+ }
3512
+ return report;
3505
3513
  }
3506
3514
  async function checkUnpublishedFeedChanges(storage, currentTree, options = {}) {
3507
3515
  const state = await collectPublicStorageState(storage, options);
@@ -4322,6 +4330,208 @@ async function ingestPortableFilesIntoStorage(storage, files, options = {}) {
4322
4330
  errors
4323
4331
  };
4324
4332
  }
4333
+ var FEED_SUBSCRIPTIONS_META_KEY = "feed:subscriptions";
4334
+ async function removeSeedSourceContent(storage, meta) {
4335
+ return await storage.transaction(
4336
+ [
4337
+ "notes",
4338
+ "attachments",
4339
+ "tags",
4340
+ "note_tags",
4341
+ "block_index",
4342
+ "block_efforts",
4343
+ "block_equipment",
4344
+ "page_notes",
4345
+ "efforts",
4346
+ "equipment",
4347
+ "property_overrides",
4348
+ "meta"
4349
+ ],
4350
+ "readwrite",
4351
+ async (tx) => {
4352
+ const targetIds = /* @__PURE__ */ new Set();
4353
+ const legacyChunks = [];
4354
+ for (const [chunkId, chunk] of Object.entries(meta.chunks)) {
4355
+ if (chunk.noteIds?.length) {
4356
+ for (const id of chunk.noteIds) targetIds.add(id);
4357
+ } else {
4358
+ legacyChunks.push(chunkId);
4359
+ }
4360
+ }
4361
+ if (legacyChunks.length) {
4362
+ for (const note of await tx.readwrite("notes").getAll()) {
4363
+ if (note.seedOrigin === "seed" && note.seedChunkId && legacyChunks.includes(note.seedChunkId)) {
4364
+ targetIds.add(note.id);
4365
+ }
4366
+ }
4367
+ }
4368
+ const metaStore = tx.readwrite("meta");
4369
+ const otherCheckpoints = [];
4370
+ for (const row of await metaStore.getAll()) {
4371
+ const other = row;
4372
+ if (!other || typeof other.key !== "string" || !other.key.startsWith("seed:") || other.key === meta.key) {
4373
+ continue;
4374
+ }
4375
+ const noteIds = /* @__PURE__ */ new Set();
4376
+ for (const chunk of Object.values(other.chunks ?? {})) {
4377
+ for (const id of chunk.noteIds ?? []) noteIds.add(id);
4378
+ }
4379
+ otherCheckpoints.push({
4380
+ key: other.key,
4381
+ sourceId: other.key.slice(5),
4382
+ rank: seedPrecedenceRank(other.key, other.tier),
4383
+ meta: other,
4384
+ noteIds
4385
+ });
4386
+ }
4387
+ otherCheckpoints.sort((a, b) => b.rank - a.rank);
4388
+ const isClaimedByOther = (noteId) => otherCheckpoints.some((cp) => cp.noteIds.has(noteId));
4389
+ const removedSourceId = meta.key.startsWith("seed:") ? meta.key.slice(5) : meta.key;
4390
+ const notes = tx.readwrite("notes");
4391
+ const noteTags = tx.readwrite("note_tags");
4392
+ let deleted = 0;
4393
+ const removedPaths = /* @__PURE__ */ new Set();
4394
+ const touchedTagIds = /* @__PURE__ */ new Set();
4395
+ for (const id of targetIds) {
4396
+ if (isClaimedByOther(id)) continue;
4397
+ const note = await notes.get(id);
4398
+ if (!note || note.seedOrigin !== "seed") continue;
4399
+ if (note.seedChunkId && !meta.chunks[note.seedChunkId]) continue;
4400
+ if (note.sourcePath) removedPaths.add(note.sourcePath);
4401
+ await notes.delete(id);
4402
+ const attachments = tx.readwrite("attachments");
4403
+ for (const attachment of await attachments.getAllFromIndex("by-note", id)) {
4404
+ await attachments.delete(attachment.id);
4405
+ }
4406
+ for (const link of await noteTags.getAllFromIndex("by-note", id)) {
4407
+ touchedTagIds.add(link.tagId);
4408
+ await noteTags.delete(link.id);
4409
+ }
4410
+ const blockIndex = tx.readwrite("block_index");
4411
+ for (const row of await blockIndex.getAllFromIndex("by-note", id)) await blockIndex.delete(row.id);
4412
+ const blockEfforts = tx.readwrite("block_efforts");
4413
+ for (const row of await blockEfforts.getAllFromIndex("by-note", id)) await blockEfforts.delete(row.id);
4414
+ const blockEquipment = tx.readwrite("block_equipment");
4415
+ for (const row of await blockEquipment.getAllFromIndex("by-note", id)) await blockEquipment.delete(row.id);
4416
+ const pageNotes = tx.readwrite("page_notes");
4417
+ for (const link of await pageNotes.getAllFromIndex("by-note", id)) await pageNotes.delete(link.id);
4418
+ deleted++;
4419
+ }
4420
+ if (touchedTagIds.size > 0) {
4421
+ const tagsStore = tx.readwrite("tags");
4422
+ for (const tagId of touchedTagIds) {
4423
+ const remainingLinks = await noteTags.countFromIndex("by-tag", tagId);
4424
+ if (remainingLinks > 0) continue;
4425
+ const tag = await tagsStore.get(tagId);
4426
+ if (!tag) continue;
4427
+ if (tag.contributions && tag.contributions.length > 0) continue;
4428
+ const refNote = await notes.get(`t/${tag.type ?? "tag"}/${tag.label}`);
4429
+ if (refNote) continue;
4430
+ await tagsStore.delete(tagId);
4431
+ }
4432
+ }
4433
+ const defFamilies = [
4434
+ { storeName: "efforts", familyPathPrefix: "markdown/efforts/", parse: wodWikiLang.parseEffortFile },
4435
+ { storeName: "equipment", familyPathPrefix: "markdown/equipment/", parse: wodWikiLang.parseEquipmentFile }
4436
+ ];
4437
+ for (const { storeName, familyPathPrefix, parse } of defFamilies) {
4438
+ const store = tx.readwrite(storeName);
4439
+ for (const row of await store.getAll()) {
4440
+ if (row.registrySource !== "bundled") continue;
4441
+ const owned = row.sourceId === removedSourceId || row.ownerNoteId !== void 0 && targetIds.has(row.ownerNoteId) && (!row.sourceId || row.sourceId === storeName) || row.sourcePath !== void 0 && row.sourcePath.startsWith(familyPathPrefix) && removedPaths.has(row.sourcePath);
4442
+ if (!owned) continue;
4443
+ let restored = false;
4444
+ for (const cp of otherCheckpoints) {
4445
+ const candidateIds = cp.meta.chunks?.[storeName]?.noteIds ?? [];
4446
+ for (const candidateId of candidateIds) {
4447
+ const candidateNote = await notes.get(candidateId);
4448
+ if (!candidateNote || candidateNote.seedOrigin !== "seed") continue;
4449
+ const parsed = parse(candidateNote.rawContent);
4450
+ if (parsed && parsed.slug === row.slug) {
4451
+ await store.put({
4452
+ ...parsed,
4453
+ registrySource: "bundled",
4454
+ ownerNoteId: candidateNote.id,
4455
+ sourceId: cp.sourceId,
4456
+ feedSourceId: cp.sourceId,
4457
+ sourcePath: candidateNote.sourcePath ?? ""
4458
+ });
4459
+ restored = true;
4460
+ break;
4461
+ }
4462
+ }
4463
+ if (restored) break;
4464
+ }
4465
+ if (!restored) await store.delete(row.slug);
4466
+ }
4467
+ }
4468
+ try {
4469
+ const overrideStore = tx.readwrite("property_overrides");
4470
+ for (const ov of await overrideStore.getAll()) {
4471
+ if (ov.seedOrigin === "seed" && ov.feedSourceId === removedSourceId) {
4472
+ await overrideStore.delete(ov.id);
4473
+ }
4474
+ }
4475
+ } catch {
4476
+ }
4477
+ await metaStore.delete(meta.key);
4478
+ return deleted;
4479
+ }
4480
+ );
4481
+ }
4482
+ async function readFeedSubscriptionsMap(storage) {
4483
+ const row = await storage.readonly("meta").get(FEED_SUBSCRIPTIONS_META_KEY);
4484
+ return { ...row?.entries ?? {} };
4485
+ }
4486
+ async function writeFeedSubscriptionEntry(storage, sourceId, entry) {
4487
+ await storage.transaction(["meta"], "readwrite", async (tx) => {
4488
+ const metaStore = tx.readwrite("meta");
4489
+ const existing = await metaStore.get(FEED_SUBSCRIPTIONS_META_KEY);
4490
+ const entries = { ...existing?.entries ?? {}, [sourceId]: entry };
4491
+ await metaStore.put({ key: FEED_SUBSCRIPTIONS_META_KEY, entries });
4492
+ });
4493
+ }
4494
+ async function listFeedSubscriptionsHeadless(storage) {
4495
+ return readFeedSubscriptionsMap(storage);
4496
+ }
4497
+ async function subscribeFeedSourceHeadless(storage, sourceId, options) {
4498
+ const notebookIds = options?.notebookIds && options.notebookIds.length > 0 ? options.notebookIds : null;
4499
+ await writeFeedSubscriptionEntry(storage, sourceId, {
4500
+ subscribed: true,
4501
+ notebookIds,
4502
+ hidden: false,
4503
+ ...options?.url ? { url: options.url } : {},
4504
+ ...options?.name ? { name: options.name } : {},
4505
+ updatedAt: Date.now()
4506
+ });
4507
+ return { sourceId, subscribed: true, notebookIds };
4508
+ }
4509
+ async function unsubscribeFeedSourceHeadless(storage, sourceId) {
4510
+ if (sourceId === "core") {
4511
+ throw new Error("Core feed cannot be unsubscribed.");
4512
+ }
4513
+ const meta = await storage.readonly("meta").get(seedMetaKey(sourceId));
4514
+ const deletedNotes = meta ? await removeSeedSourceContent(storage, meta) : 0;
4515
+ await writeFeedSubscriptionEntry(storage, sourceId, {
4516
+ subscribed: false,
4517
+ hidden: false,
4518
+ updatedAt: Date.now()
4519
+ });
4520
+ return { sourceId, unsubscribed: true, deletedNotes };
4521
+ }
4522
+ async function deleteFeedSourceHeadless(storage, sourceId) {
4523
+ if (sourceId === "core") {
4524
+ throw new Error("Core feed cannot be deleted.");
4525
+ }
4526
+ const meta = await storage.readonly("meta").get(seedMetaKey(sourceId));
4527
+ const deletedNotes = meta ? await removeSeedSourceContent(storage, meta) : 0;
4528
+ await writeFeedSubscriptionEntry(storage, sourceId, {
4529
+ subscribed: false,
4530
+ hidden: true,
4531
+ updatedAt: Date.now()
4532
+ });
4533
+ return { sourceId, deleted: true, deletedNotes };
4534
+ }
4325
4535
  function mintUuid() {
4326
4536
  if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
4327
4537
  return crypto.randomUUID();
@@ -4620,6 +4830,705 @@ function buildNoteProvenance(sourceNote, sourceNotebookId, clonedAt) {
4620
4830
  clonedAt
4621
4831
  };
4622
4832
  }
4833
+ function buildQueryServiceStoresFromStorage(storage, options = {}) {
4834
+ const asRange = (lower, upper) => typeof IDBKeyRange !== "undefined" ? IDBKeyRange.bound(lower, upper) : { lower, upper };
4835
+ const resultRows = (key) => asRange([key, ""], [`${key}\uFFFF`, "\uFFFF"]);
4836
+ const rawEventStore = {
4837
+ getEventsByTimeRange: async (start, end) => storage.readonly("events").getAllFromIndex("by-timestamp", asRange(start, end)),
4838
+ getEventsByMetricDates: async (dates) => {
4839
+ const store = storage.readonly("events");
4840
+ const byId = /* @__PURE__ */ new Map();
4841
+ for (const date of dates) {
4842
+ for (const row of await store.getAllFromIndex("by-metric-date", date)) {
4843
+ byId.set(row.id, row);
4844
+ }
4845
+ }
4846
+ return Array.from(byId.values());
4847
+ },
4848
+ getEventsByResult: async (resultId) => storage.readonly("events").getAllFromIndex("by-result-grain", resultRows(resultId)),
4849
+ getEventsForNote: async (noteId) => (await storage.readonly("events").getAll()).filter((row) => row.noteId === noteId),
4850
+ getEventsByContent: async (cid) => storage.readonly("events").getAllFromIndex("by-content-grain", resultRows(cid)),
4851
+ scanAll: () => storage.readonly("events").getAll(),
4852
+ appendEvents: async (rows) => {
4853
+ if (rows.length > 0) await storage.readwrite("events").putMany(rows);
4854
+ },
4855
+ finalizeSummaries: async (resultId, rows) => {
4856
+ await storage.transaction(["events"], "readwrite", async (tx) => {
4857
+ const allForResult = (await tx.readonly("events").getAll()).filter(
4858
+ (r) => r.resultId === resultId && r.grain === "summary" && r.origin !== "user"
4859
+ );
4860
+ for (const r of allForResult) await tx.readwrite("events").delete(r.id);
4861
+ if (rows.length > 0) await tx.readwrite("events").putMany(rows);
4862
+ });
4863
+ },
4864
+ deleteEvents: async (ids) => {
4865
+ for (const id of ids) await storage.readwrite("events").delete(id);
4866
+ }
4867
+ };
4868
+ const eventStore = options.coalesce !== false ? wodWikiWql.coalescingEventStore(rawEventStore) : rawEventStore;
4869
+ const noteStore = {
4870
+ getAllNotes: () => storage.readonly("notes").getAll(),
4871
+ getNotesByIds: async (ids) => {
4872
+ const rows = await storage.readonly("notes").getMany([...ids]);
4873
+ return rows.filter((row) => row !== void 0);
4874
+ },
4875
+ getNoteIdsForTag: async (label) => {
4876
+ const ids = /* @__PURE__ */ new Set();
4877
+ for (const tag of await storage.readonly("tags").getAllFromIndex("by-label", label)) {
4878
+ for (const link of await storage.readonly("note_tags").getAllFromIndex("by-tag", tag.id)) {
4879
+ ids.add(link.noteId);
4880
+ }
4881
+ }
4882
+ return ids;
4883
+ },
4884
+ getNoteTagLabels: async (noteId) => {
4885
+ const links = await storage.readonly("note_tags").getAllFromIndex("by-note", noteId);
4886
+ const tags = await storage.readonly("tags").getMany(links.map((l) => l.tagId));
4887
+ return tags.flatMap((t) => t ? [t.label] : []);
4888
+ },
4889
+ queryDomain: async (request) => {
4890
+ if (!storage.queryDomain) return void 0;
4891
+ const result = await storage.queryDomain({ ...request, plan: "notes" });
4892
+ return result && result.plan === "notes" ? result : void 0;
4893
+ }
4894
+ };
4895
+ const blockStore = {
4896
+ getAllBlocks: () => storage.readonly("block_index").getAll(),
4897
+ queryDomain: async (request) => {
4898
+ if (!storage.queryDomain) return void 0;
4899
+ const result = await storage.queryDomain({ ...request, plan: "blocks" });
4900
+ return result && result.plan === "blocks" ? result : void 0;
4901
+ }
4902
+ };
4903
+ const effortStore = options.effortStore ?? {
4904
+ getAllEfforts: async () => {
4905
+ const stored = await storage.readonly("efforts").getAll();
4906
+ const bySlug = /* @__PURE__ */ new Map();
4907
+ for (const eff of wodWikiLang.bundledEfforts) bySlug.set(eff.slug, eff);
4908
+ for (const eff of stored) bySlug.set(eff.slug, eff);
4909
+ return [...bySlug.values()];
4910
+ }
4911
+ };
4912
+ const feedCatalogStore = options.feedCatalogStore ?? {
4913
+ getAllFeeds: async () => {
4914
+ const rows = [];
4915
+ for (const row of await storage.readonly("meta").getAll()) {
4916
+ const key = row.key;
4917
+ if (typeof key !== "string" || !key.startsWith("seed:") || key === seedMetaKey("user")) continue;
4918
+ const id = key.slice("seed:".length);
4919
+ rows.push({
4920
+ id,
4921
+ label: id,
4922
+ url: `https://${id}.example/feed/`,
4923
+ tier: "imported",
4924
+ subscribed: true,
4925
+ installed: true,
4926
+ notebookCount: 0,
4927
+ itemCount: 0
4928
+ });
4929
+ }
4930
+ return rows;
4931
+ },
4932
+ getAllNotebooks: async () => {
4933
+ const links = await storage.readonly("notebook_links").getAll().catch(() => []);
4934
+ const notes = await storage.readonly("notes").getAll();
4935
+ const memberCount = /* @__PURE__ */ new Map();
4936
+ for (const link of links) {
4937
+ if (link.targetKind === "note") {
4938
+ memberCount.set(link.notebookId, (memberCount.get(link.notebookId) ?? 0) + 1);
4939
+ }
4940
+ }
4941
+ const rows = [];
4942
+ for (const [notebookId, count] of memberCount) {
4943
+ const slug = notebookId.startsWith("notebook/") ? notebookId.slice("notebook/".length) : notebookId;
4944
+ const landing = notes.find((n) => n.id === notebookId);
4945
+ const feedSourceId = landing?.feedSourceId;
4946
+ const chunkId = `notebook.${slug}`;
4947
+ const feedId = feedSourceId ?? "local";
4948
+ let subscribed = feedSourceId !== void 0;
4949
+ if (options.isNotebookSubscribed) {
4950
+ const res = options.isNotebookSubscribed(feedId, chunkId);
4951
+ subscribed = typeof res === "boolean" ? res : Boolean(await res);
4952
+ }
4953
+ rows.push({
4954
+ id: notebookId,
4955
+ feedId,
4956
+ feedLabel: feedSourceId ?? "Yours (Local)",
4957
+ chunkId,
4958
+ slug,
4959
+ label: landing?.title ?? slug,
4960
+ count,
4961
+ subscribed,
4962
+ installed: true,
4963
+ origin: feedSourceId ? "feed" : "user",
4964
+ ...landing?.public !== void 0 ? { public: landing.public } : {}
4965
+ });
4966
+ }
4967
+ return rows;
4968
+ }
4969
+ };
4970
+ const stores = {
4971
+ eventStore,
4972
+ noteStore,
4973
+ blockStore,
4974
+ effortStore,
4975
+ blockEffortsStore: {
4976
+ getAllFromIndex: (index, key) => storage.readonly("block_efforts").getAllFromIndex(index, key)
4977
+ },
4978
+ blockEquipmentStore: {
4979
+ getAllFromIndex: (index, key) => storage.readonly("block_equipment").getAllFromIndex(index, key)
4980
+ },
4981
+ tagsStore: {
4982
+ getAllFromIndex: (index, key) => storage.readonly("tags").getAllFromIndex(index, key),
4983
+ getAll: () => storage.readonly("tags").getAll()
4984
+ },
4985
+ noteTagsStore: {
4986
+ getAllFromIndex: (index, key) => storage.readonly("note_tags").getAllFromIndex(index, key)
4987
+ },
4988
+ pageStore: {
4989
+ getNotePages: (noteId) => storage.readonly("page_notes").getAllFromIndex("by-note", noteId),
4990
+ getPage: (pageId) => storage.readonly("page").get(pageId),
4991
+ getAllPages: () => storage.readonly("page").getAll(),
4992
+ getAllLinks: () => storage.readonly("page_notes").getAll()
4993
+ },
4994
+ relationStore: {
4995
+ getBatches: async (noteIds) => {
4996
+ const bundles = /* @__PURE__ */ new Map();
4997
+ for (const noteId of noteIds) {
4998
+ const links = await storage.readonly("page_notes").getAllFromIndex("by-note", noteId);
4999
+ const tagLinks = await storage.readonly("note_tags").getAllFromIndex("by-note", noteId);
5000
+ const tags = await storage.readonly("tags").getMany(tagLinks.map((l) => l.tagId));
5001
+ const pages = await storage.readonly("page").getMany([...new Set(links.map((l) => l.pageId))]);
5002
+ bundles.set(noteId, {
5003
+ tags: tags.flatMap((t) => t ? [{ label: t.label, ...t.type ? { type: t.type } : {} }] : []),
5004
+ links,
5005
+ pages: pages.filter((p) => p !== void 0)
5006
+ });
5007
+ }
5008
+ return bundles;
5009
+ }
5010
+ },
5011
+ feedCatalogStore
5012
+ };
5013
+ if (options.datasetStore) {
5014
+ stores.datasetStore = options.datasetStore;
5015
+ }
5016
+ if (options.isNotebookSubscribed) {
5017
+ stores.isNotebookSubscribed = (feedId, chunkId) => {
5018
+ const res = options.isNotebookSubscribed(feedId, chunkId);
5019
+ return typeof res === "boolean" ? res : true;
5020
+ };
5021
+ }
5022
+ return stores;
5023
+ }
5024
+ var PERSIST_WORLD_STORES = [
5025
+ "notes",
5026
+ "block_revisions",
5027
+ "block_index",
5028
+ "block_efforts",
5029
+ "block_equipment",
5030
+ "tags",
5031
+ "tag_types",
5032
+ "note_tags",
5033
+ "notebook_links",
5034
+ "property_overrides",
5035
+ "efforts",
5036
+ "equipment",
5037
+ "page",
5038
+ "page_notes",
5039
+ "sessions",
5040
+ "events"
5041
+ ];
5042
+ async function persistDomainWorld(storage, worldInput) {
5043
+ const isBuiltWorld = worldInput !== void 0 && "revisions" in worldInput && Array.isArray(worldInput.revisions) && "events" in worldInput && Array.isArray(worldInput.events);
5044
+ let world;
5045
+ if (isBuiltWorld) {
5046
+ world = worldInput;
5047
+ } else {
5048
+ testing.resetTestingVocabulary();
5049
+ world = testing.buildDomainWorld(worldInput ?? {});
5050
+ }
5051
+ const explicitNoteIds = new Set(world.notes.map((n) => n.id));
5052
+ await storage.transaction([...PERSIST_WORLD_STORES], "readwrite", async (tx) => {
5053
+ for (const nb of world.notebooks) {
5054
+ if (!explicitNoteIds.has(nb.id)) {
5055
+ await tx.readwrite("notes").put(nb);
5056
+ }
5057
+ }
5058
+ if (world.notes.length) await tx.readwrite("notes").putMany(world.notes);
5059
+ if (world.revisions.length) await tx.readwrite("block_revisions").putMany(world.revisions);
5060
+ if (world.blockIndex.length) await tx.readwrite("block_index").putMany(world.blockIndex);
5061
+ if (world.blockEfforts.length) await tx.readwrite("block_efforts").putMany(world.blockEfforts);
5062
+ if (world.blockEquipment.length) await tx.readwrite("block_equipment").putMany(world.blockEquipment);
5063
+ if (world.tags.length) await tx.readwrite("tags").putMany(world.tags);
5064
+ if (world.noteTags.length) await tx.readwrite("note_tags").putMany(world.noteTags);
5065
+ if (world.notebookLinks.length) await tx.readwrite("notebook_links").putMany(world.notebookLinks);
5066
+ for (const override of world.propertyOverrides) {
5067
+ await tx.readwrite("property_overrides").put(override);
5068
+ if (override.kind === "tag" && override.payload) {
5069
+ await tx.readwrite("tags").put(override.payload);
5070
+ } else if (override.kind === "tag-type" && override.payload) {
5071
+ await tx.readwrite("tag_types").put(override.payload);
5072
+ }
5073
+ }
5074
+ if (!isBuiltWorld && worldInput?.propertyNotes) {
5075
+ for (const propInput of worldInput.propertyNotes ?? []) {
5076
+ const isDefault = !propInput.asOverride && (propInput.notebookId === void 0 || propInput.notebookId === "notebook/defaults");
5077
+ if (!isDefault) continue;
5078
+ if (propInput.kind === "effort") {
5079
+ const effortRow = {
5080
+ id: propInput.id ?? `effort-${propInput.slug}`,
5081
+ slug: propInput.slug,
5082
+ label: propInput.label,
5083
+ aliases: propInput.aliases ?? [],
5084
+ baseAttributes: {
5085
+ met: 5,
5086
+ ...propInput.baseAttributes ?? {}
5087
+ },
5088
+ registrySource: "bundled",
5089
+ sourceId: "core",
5090
+ ...propInput.body ? { body: propInput.body } : {}
5091
+ };
5092
+ await tx.readwrite("efforts").put(effortRow);
5093
+ } else if (propInput.kind === "equipment") {
5094
+ const equipRow = {
5095
+ id: propInput.id ?? `equipment-${propInput.slug}`,
5096
+ slug: propInput.slug,
5097
+ label: propInput.label,
5098
+ aliases: propInput.aliases ?? [],
5099
+ registrySource: "bundled",
5100
+ sourceId: "core",
5101
+ ...propInput.body ? { body: propInput.body } : {}
5102
+ };
5103
+ await tx.readwrite("equipment").put(equipRow);
5104
+ }
5105
+ }
5106
+ }
5107
+ if (world.pages.length) await tx.readwrite("page").putMany(world.pages);
5108
+ if (world.pageNotes.length) await tx.readwrite("page_notes").putMany(world.pageNotes);
5109
+ if (world.sessions.length) await tx.readwrite("sessions").putMany(world.sessions);
5110
+ if (world.events.length) await tx.readwrite("events").putMany(world.events);
5111
+ });
5112
+ return world;
5113
+ }
5114
+ var SAMPLE_TAG = "sample";
5115
+ var DAY = 864e5;
5116
+ var WEEK = 7 * DAY;
5117
+ var LB_TO_KG = 0.453592;
5118
+ function round1(n) {
5119
+ return Math.round(n * 10) / 10;
5120
+ }
5121
+ var INTENSITY_BY_EFFORT = {
5122
+ thruster: "high",
5123
+ "pull-up": "high",
5124
+ "push-up": "moderate",
5125
+ "air-squat": "moderate",
5126
+ "double-under": "high",
5127
+ "sit-up": "low",
5128
+ rowing: "moderate",
5129
+ running: "moderate",
5130
+ "recovery-run": "low",
5131
+ "back-squat": "high",
5132
+ "bench-press": "high",
5133
+ deadlift: "high",
5134
+ "max-hang": "high",
5135
+ climb: "high"
5136
+ };
5137
+ var SESSION_INTENSITY = {
5138
+ fran: "high",
5139
+ cindy: "moderate",
5140
+ annie: "moderate",
5141
+ rowing: "moderate",
5142
+ running: "moderate",
5143
+ strength: "high",
5144
+ recoveryRun: "low",
5145
+ hangboard: "high"
5146
+ };
5147
+ function buildFran(now, weekOffset, attempt) {
5148
+ const baseDuration = 330 - attempt * 16;
5149
+ const durationSeconds = Math.max(180, round1(baseDuration + Math.sin(weekOffset) * 10));
5150
+ const loadLbs = 95 + attempt * 5;
5151
+ const reps = 45;
5152
+ return {
5153
+ noteId: `sample-fran-${weekOffset}`,
5154
+ title: `Sample \u2014 Fran (week ${16 - weekOffset})`,
5155
+ workoutType: "fran",
5156
+ timestamp: now - weekOffset * WEEK - 2 * DAY,
5157
+ durationSeconds,
5158
+ tags: [SAMPLE_TAG, "benchmark", "crossfit"],
5159
+ movements: [
5160
+ { effortSlug: "thruster", discipline: "strength", reps, loadLbs, tisSeconds: round1(reps * 2.2) },
5161
+ { effortSlug: "pull-up", discipline: "gymnastics", reps, loadLbs: 0, tisSeconds: round1(reps * 1.6) }
5162
+ ]
5163
+ };
5164
+ }
5165
+ function buildCindy(now, weekOffset, attempt) {
5166
+ const rounds = 10 + attempt + weekOffset % 3;
5167
+ return {
5168
+ noteId: `sample-cindy-${weekOffset}`,
5169
+ title: `Sample \u2014 Cindy (week ${16 - weekOffset})`,
5170
+ workoutType: "cindy",
5171
+ timestamp: now - weekOffset * WEEK - 2 * DAY,
5172
+ durationSeconds: 1200,
5173
+ tags: [SAMPLE_TAG, "benchmark", "crossfit"],
5174
+ movements: [
5175
+ { effortSlug: "pull-up", discipline: "gymnastics", reps: rounds * 5, loadLbs: 0, tisSeconds: round1(rounds * 5 * 1.5) },
5176
+ { effortSlug: "push-up", discipline: "gymnastics", reps: rounds * 10, loadLbs: 0, tisSeconds: round1(rounds * 10 * 1.2) },
5177
+ { effortSlug: "air-squat", discipline: "bodyweight", reps: rounds * 15, loadLbs: 0, tisSeconds: round1(rounds * 15 * 1.1) }
5178
+ ]
5179
+ };
5180
+ }
5181
+ function buildAnnie(now, weekOffset, attempt) {
5182
+ const baseDuration = 540 - attempt * 22;
5183
+ const durationSeconds = Math.max(360, round1(baseDuration + Math.cos(weekOffset) * 15));
5184
+ const reps = 150;
5185
+ return {
5186
+ noteId: `sample-annie-${weekOffset}`,
5187
+ title: `Sample \u2014 Annie (week ${16 - weekOffset})`,
5188
+ workoutType: "annie",
5189
+ timestamp: now - weekOffset * WEEK - 2 * DAY,
5190
+ durationSeconds,
5191
+ tags: [SAMPLE_TAG, "benchmark", "crossfit"],
5192
+ movements: [
5193
+ { effortSlug: "double-under", discipline: "gymnastics", reps, loadLbs: 0, tisSeconds: round1(reps * 0.5) },
5194
+ { effortSlug: "sit-up", discipline: "bodyweight", reps, loadLbs: 0, tisSeconds: round1(reps * 1.3) }
5195
+ ]
5196
+ };
5197
+ }
5198
+ function buildStrengthAccessory(now, weekOffset, attempt) {
5199
+ const baseBackSquat = 135 + attempt * 5;
5200
+ const baseBenchPress = 115 + attempt * 5;
5201
+ const baseDeadlift = 185 + attempt * 5;
5202
+ const backSquatReps = 25;
5203
+ const benchPressReps = 25;
5204
+ const deadliftReps = 15;
5205
+ return {
5206
+ noteId: `sample-strength-${weekOffset}`,
5207
+ title: `Sample \u2014 Strength accessory (week ${16 - weekOffset})`,
5208
+ workoutType: "strength",
5209
+ timestamp: now - weekOffset * WEEK - 4 * DAY,
5210
+ durationSeconds: 2400,
5211
+ tags: [SAMPLE_TAG, "strength"],
5212
+ movements: [
5213
+ { effortSlug: "back-squat", discipline: "strength", reps: backSquatReps, loadLbs: baseBackSquat, tisSeconds: round1(backSquatReps * 2.5) },
5214
+ { effortSlug: "bench-press", discipline: "strength", reps: benchPressReps, loadLbs: baseBenchPress, tisSeconds: round1(benchPressReps * 2) },
5215
+ { effortSlug: "deadlift", discipline: "strength", reps: deadliftReps, loadLbs: baseDeadlift, tisSeconds: round1(deadliftReps * 2.8) }
5216
+ ]
5217
+ };
5218
+ }
5219
+ function buildRowing(now, weekOffset, attempt) {
5220
+ const distanceMeters = 2e3 + attempt * 250;
5221
+ const durationSeconds = round1(distanceMeters / 2);
5222
+ return {
5223
+ noteId: `sample-rowing-${weekOffset}`,
5224
+ title: `Sample \u2014 Rowing (week ${16 - weekOffset})`,
5225
+ workoutType: "rowing",
5226
+ timestamp: now - weekOffset * WEEK - 5 * DAY,
5227
+ durationSeconds,
5228
+ tags: [SAMPLE_TAG, "endurance", "rowing"],
5229
+ movements: [
5230
+ { effortSlug: "rowing", discipline: "rowing", reps: 1, loadLbs: 0, tisSeconds: durationSeconds, distanceMeters }
5231
+ ]
5232
+ };
5233
+ }
5234
+ function buildRunning(now, weekOffset, attempt) {
5235
+ const distanceMeters = 5e3 + attempt * 500;
5236
+ const durationSeconds = round1(distanceMeters / 2.8);
5237
+ return {
5238
+ noteId: `sample-running-${weekOffset}`,
5239
+ title: `Sample \u2014 Running (week ${16 - weekOffset})`,
5240
+ workoutType: "running",
5241
+ timestamp: now - weekOffset * WEEK - 5 * DAY,
5242
+ durationSeconds,
5243
+ tags: [SAMPLE_TAG, "endurance", "running"],
5244
+ movements: [
5245
+ { effortSlug: "running", discipline: "running", reps: 1, loadLbs: 0, tisSeconds: durationSeconds, distanceMeters }
5246
+ ]
5247
+ };
5248
+ }
5249
+ function buildRecoveryRun(now, weekOffset, attempt) {
5250
+ const distanceMeters = 3e3 + attempt * 50;
5251
+ const durationSeconds = round1(distanceMeters / 2.2);
5252
+ return {
5253
+ noteId: `sample-recovery-run-${weekOffset}`,
5254
+ title: `Sample \u2014 Recovery run (week ${16 - weekOffset})`,
5255
+ workoutType: "recoveryRun",
5256
+ timestamp: now - weekOffset * WEEK - 6 * DAY,
5257
+ durationSeconds,
5258
+ tags: [SAMPLE_TAG, "recovery", "running"],
5259
+ movements: [
5260
+ { effortSlug: "recovery-run", discipline: "running", reps: 1, loadLbs: 0, tisSeconds: durationSeconds, distanceMeters }
5261
+ ]
5262
+ };
5263
+ }
5264
+ function buildHangboard(now, weekOffset, attempt) {
5265
+ const durationSeconds = 1200;
5266
+ const grade = `V${Math.min(8, 5 + attempt % 4)}`;
5267
+ return {
5268
+ noteId: `sample-hangboard-${weekOffset}`,
5269
+ title: `Sample \u2014 Hangboard session (week ${16 - weekOffset})`,
5270
+ workoutType: "hangboard",
5271
+ timestamp: now - weekOffset * WEEK - 3 * DAY,
5272
+ durationSeconds,
5273
+ tags: [SAMPLE_TAG, "hangboard", "climbing"],
5274
+ movements: [
5275
+ { effortSlug: "max-hang", discipline: "climbing", reps: 5, loadLbs: 35, tisSeconds: 60 },
5276
+ { effortSlug: "climb", discipline: "climbing", reps: 3, loadLbs: 0, tisSeconds: 180, grade }
5277
+ ]
5278
+ };
5279
+ }
5280
+ function generateSampleSessions(anchorNow = Date.now()) {
5281
+ const sessions = [];
5282
+ for (let weekOffset = 0; weekOffset < 16; weekOffset++) {
5283
+ const block = Math.floor(weekOffset / 4);
5284
+ sessions.push(buildStrengthAccessory(anchorNow, weekOffset, weekOffset));
5285
+ if (weekOffset % 4 === 0) {
5286
+ sessions.push(buildFran(anchorNow, weekOffset, block));
5287
+ } else if (weekOffset % 4 === 1) {
5288
+ sessions.push(buildCindy(anchorNow, weekOffset, block));
5289
+ } else if (weekOffset % 4 === 2) {
5290
+ sessions.push(buildAnnie(anchorNow, weekOffset, block));
5291
+ } else if (weekOffset === 3 || weekOffset === 11) {
5292
+ sessions.push(buildRowing(anchorNow, weekOffset, block));
5293
+ } else if (weekOffset === 7 || weekOffset === 15) {
5294
+ sessions.push(buildRunning(anchorNow, weekOffset, block));
5295
+ }
5296
+ sessions.push(buildRecoveryRun(anchorNow, weekOffset, weekOffset));
5297
+ if (weekOffset % 2 === 0) {
5298
+ sessions.push(buildHangboard(anchorNow, weekOffset, weekOffset));
5299
+ }
5300
+ }
5301
+ return sessions.sort((a, b) => a.timestamp - b.timestamp);
5302
+ }
5303
+ function buildSessionLogs(session) {
5304
+ const startedAt = session.timestamp;
5305
+ const sessionIntensity = SESSION_INTENSITY[session.workoutType];
5306
+ const totalReps = session.movements.reduce((sum, m) => sum + m.reps, 0);
5307
+ const totalVolumeLbs = session.movements.reduce((sum, m) => sum + m.reps * m.loadLbs, 0);
5308
+ const totalTis = session.movements.reduce((sum, m) => sum + m.tisSeconds, 0);
5309
+ const totalDistance = session.movements.reduce((sum, m) => sum + (m.distanceMeters ?? 0), 0);
5310
+ const sessionLoad = round1(totalVolumeLbs / 100 + totalReps + session.durationSeconds / 10);
5311
+ const logs = [];
5312
+ const push = (label, value, unit, canonicalKey, tags) => {
5313
+ const metadata = { canonicalKey };
5314
+ if (tags?.effortSlug) metadata.effortSlug = tags.effortSlug;
5315
+ if (tags?.discipline) metadata.effortDiscipline = tags.discipline;
5316
+ if (tags?.intensityTier) metadata.effortIntensityTier = tags.intensityTier;
5317
+ if (tags?.grade) metadata.grade = tags.grade;
5318
+ logs.push({
5319
+ id: logs.length,
5320
+ outputType: "analytics",
5321
+ timeSpan: { started: startedAt },
5322
+ metrics: [
5323
+ { type: wodWikiCore.MetricType.Label, value: label, origin: "analyzed" },
5324
+ { type: wodWikiCore.MetricType.Metric, value, unit, metadata, origin: "analyzed" }
5325
+ ],
5326
+ sourceBlockKey: "",
5327
+ stackLevel: 0
5328
+ });
5329
+ };
5330
+ const isBenchmark = session.workoutType === "fran" || session.workoutType === "cindy" || session.workoutType === "annie";
5331
+ const workoutEffortSlug = isBenchmark ? session.workoutType : void 0;
5332
+ push("Elapsed time", session.durationSeconds, "s", "elapsed", {
5333
+ effortSlug: workoutEffortSlug,
5334
+ intensityTier: sessionIntensity
5335
+ });
5336
+ push("Total reps", totalReps, "reps", "totalReps", { intensityTier: sessionIntensity });
5337
+ push("Time in motion", round1(totalTis), "s", "tis", { intensityTier: sessionIntensity });
5338
+ if (totalVolumeLbs > 0) {
5339
+ const discipline = session.workoutType === "strength" ? "strength" : void 0;
5340
+ push("Total volume", round1(totalVolumeLbs * LB_TO_KG), "kg", "totalVolume", {
5341
+ discipline,
5342
+ intensityTier: sessionIntensity
5343
+ });
5344
+ }
5345
+ if (totalDistance > 0) {
5346
+ const distanceDiscipline = session.movements.find((m) => m.distanceMeters && m.distanceMeters > 0)?.discipline;
5347
+ push("Total distance", round1(totalDistance), "m", "totalDistance", {
5348
+ discipline: distanceDiscipline,
5349
+ intensityTier: sessionIntensity
5350
+ });
5351
+ }
5352
+ const sessionDiscipline = session.workoutType === "strength" ? "strength" : void 0;
5353
+ push("Session load", sessionLoad, "AU", "sessionLoad", {
5354
+ discipline: sessionDiscipline,
5355
+ intensityTier: sessionIntensity
5356
+ });
5357
+ for (const m of session.movements) {
5358
+ const movementVolumeLbs = m.reps * m.loadLbs;
5359
+ const movementIntensity = INTENSITY_BY_EFFORT[m.effortSlug] ?? "moderate";
5360
+ const tags = {
5361
+ effortSlug: m.effortSlug,
5362
+ discipline: m.discipline,
5363
+ intensityTier: movementIntensity,
5364
+ grade: m.grade
5365
+ };
5366
+ push("Total reps", m.reps, "reps", "totalReps", tags);
5367
+ push("Time in motion", m.tisSeconds, "s", "tis", tags);
5368
+ if (movementVolumeLbs > 0) {
5369
+ push("Total volume", round1(movementVolumeLbs * LB_TO_KG), "kg", "totalVolume", tags);
5370
+ }
5371
+ push(
5372
+ "Session load",
5373
+ round1(movementVolumeLbs / 100 + m.reps + m.tisSeconds / 10),
5374
+ "AU",
5375
+ "sessionLoad",
5376
+ tags
5377
+ );
5378
+ if (m.discipline === "strength" && m.loadLbs > 0) {
5379
+ const loadKg = round1(m.loadLbs * LB_TO_KG);
5380
+ const e1rm = round1(loadKg * (1 + m.reps / 30));
5381
+ const pct1rm = round1(100 / (1 + m.reps / 30));
5382
+ push("Estimated 1RM", e1rm, "kg", "calc.e1rm", tags);
5383
+ push("%1RM intensity", pct1rm, "%", "calc.pct1rm", tags);
5384
+ }
5385
+ if (m.effortSlug === "max-hang") {
5386
+ const mvcBw = round1(28 + session.timestamp / DAY % 8);
5387
+ push("Max Hang %BW", mvcBw, "%", "calc.mvcBw", tags);
5388
+ }
5389
+ if (m.effortSlug === "climb" && m.grade) {
5390
+ push("Sends", m.reps, "count", "calc.sends", tags);
5391
+ }
5392
+ }
5393
+ const dayPhase = (salt) => {
5394
+ const x = Math.sin(session.timestamp / DAY * (12.9898 + salt) + salt * 78.233) * 43758.5453;
5395
+ return x - Math.floor(x);
5396
+ };
5397
+ const soreness = 2 + Math.round(dayPhase(1) * 4);
5398
+ const sleepHours = round1(6.8 + dayPhase(2) * 1.6);
5399
+ const hrvMs = Math.round(52 + dayPhase(3) * 22);
5400
+ const readiness = round1((10 - soreness) / 10 * 40 + sleepHours / 8 * 30 + hrvMs / 90 * 30);
5401
+ const monotony = round1(1.1 + dayPhase(4) * 0.7);
5402
+ const acwr = round1(0.85 + dayPhase(5) * 0.4);
5403
+ push("Readiness", readiness, "pts", "calc.readiness", { intensityTier: sessionIntensity });
5404
+ push("HRV", hrvMs, "pts", "calc.hrv", { intensityTier: sessionIntensity });
5405
+ push("Sleep", sleepHours, "pts", "calc.sleep", { intensityTier: sessionIntensity });
5406
+ push("Soreness", soreness, "rating", "calc.soreness", { intensityTier: sessionIntensity });
5407
+ push("Monotony", monotony, "ratio", "calc.monotony", { intensityTier: sessionIntensity });
5408
+ push("ACWR", acwr, "ratio", "calc.acwr", { intensityTier: sessionIntensity });
5409
+ const ctl = round1(45 + dayPhase(6) * 15);
5410
+ const atl = round1(50 + dayPhase(7) * 20);
5411
+ const tsb = round1(ctl - atl);
5412
+ push("Fitness (CTL)", ctl, "AU", "calc.ctl", { intensityTier: sessionIntensity });
5413
+ push("Fatigue (ATL)", atl, "AU", "calc.atl", { intensityTier: sessionIntensity });
5414
+ push("Form (TSB)", tsb, "AU", "calc.tsb", { intensityTier: sessionIntensity });
5415
+ const adherence = round1(0.8 + dayPhase(8) * 0.2);
5416
+ push("Adherence", adherence, "ratio", "calc.adherence", { intensityTier: sessionIntensity });
5417
+ if (session.workoutType === "running" || session.workoutType === "recoveryRun") {
5418
+ const paceMPerS = round1(totalDistance / session.durationSeconds);
5419
+ const ef = round1(paceMPerS / 140 * 1e5);
5420
+ push("Efficiency factor", ef, "pts", "calc.ef", { intensityTier: sessionIntensity });
5421
+ }
5422
+ return logs;
5423
+ }
5424
+ function buildSampleResult(session, contentId, createdAt) {
5425
+ const baseId = `sample-${session.noteId}`;
5426
+ const resultId = `${baseId}-result`;
5427
+ const startTime = session.timestamp;
5428
+ const endTime = startTime + session.durationSeconds * 1e3;
5429
+ return {
5430
+ id: resultId,
5431
+ noteId: session.noteId,
5432
+ blockId: "blk-0",
5433
+ blockVersion: 1,
5434
+ blockContentId: contentId,
5435
+ origin: "journal",
5436
+ status: "completed",
5437
+ createdAt,
5438
+ startTime,
5439
+ endTime,
5440
+ duration: session.durationSeconds * 1e3,
5441
+ completed: true
5442
+ };
5443
+ }
5444
+ function buildSampleBundle(session, now = Date.now()) {
5445
+ const body = session.movements.map(
5446
+ (m) => `${m.distanceMeters ? `${m.distanceMeters}m` : m.reps} ${m.effortSlug.replaceAll("-", " ")}${m.loadLbs ? ` ${m.loadLbs}lb` : ""}`
5447
+ ).join("\n");
5448
+ const rawContent = `# ${session.title}
5449
+
5450
+ \`\`\`log
5451
+ ${body}
5452
+ \`\`\`
5453
+ `;
5454
+ const blocks = wodWikiCore.reconcileNoteBlocks(rawContent, { sourceRevision: 1, createId: () => "blk-0" });
5455
+ const logs = buildSessionLogs(session);
5456
+ const result = buildSampleResult(session, wodWikiCore.blockContentId(body), now);
5457
+ const identity = {
5458
+ noteId: session.noteId,
5459
+ resultId: result.id,
5460
+ blockId: "blk-0",
5461
+ blockVersion: 1,
5462
+ blockContentId: result.blockContentId,
5463
+ origin: result.origin,
5464
+ pageId: result.pageId,
5465
+ workoutTimestamp: session.timestamp
5466
+ };
5467
+ const rawEvents = wodWikiWql.toEventRows(logs, identity);
5468
+ const summaries = wodWikiWql.toSummaryEventRows(logs, identity).map((r) => {
5469
+ const metric = r.metrics[0];
5470
+ if (metric && typeof metric.value === "number") {
5471
+ return {
5472
+ ...r,
5473
+ reducerStats: {
5474
+ observedCount: 1,
5475
+ sum: metric.value,
5476
+ min: metric.value,
5477
+ max: metric.value
5478
+ }
5479
+ };
5480
+ }
5481
+ return r;
5482
+ });
5483
+ const bundle = {
5484
+ note: {
5485
+ id: session.noteId,
5486
+ title: session.title,
5487
+ createdAt: session.timestamp,
5488
+ updatedAt: session.timestamp,
5489
+ targetDate: session.timestamp,
5490
+ rawContent,
5491
+ sourceRevision: 1,
5492
+ blocks,
5493
+ tags: session.tags,
5494
+ type: "playground"
5495
+ },
5496
+ sessions: [result],
5497
+ events: [...rawEvents, ...summaries]
5498
+ };
5499
+ return { bundle, rawContent, blocks, result, rawEvents, summaries };
5500
+ }
5501
+ function buildSampleWorld(anchorNow = Date.now()) {
5502
+ const sessions = generateSampleSessions(anchorNow);
5503
+ const testNotes = [];
5504
+ const testSessions = [];
5505
+ for (const session of sessions) {
5506
+ const { rawContent, result, rawEvents, summaries } = buildSampleBundle(session, anchorNow);
5507
+ testNotes.push({
5508
+ id: session.noteId,
5509
+ title: session.title,
5510
+ rawContent,
5511
+ createdAt: session.timestamp,
5512
+ tags: session.tags,
5513
+ type: "playground"
5514
+ });
5515
+ testSessions.push({
5516
+ id: result.id,
5517
+ noteId: session.noteId,
5518
+ blockId: "blk-0",
5519
+ blockVersion: 1,
5520
+ startedAt: result.startTime,
5521
+ completedAt: result.endTime,
5522
+ durationMs: result.duration,
5523
+ origin: result.origin,
5524
+ events: [...rawEvents, ...summaries]
5525
+ });
5526
+ }
5527
+ return {
5528
+ notes: testNotes,
5529
+ sessions: testSessions
5530
+ };
5531
+ }
4623
5532
 
4624
5533
  Object.defineProperty(exports, "ABSENT", {
4625
5534
  enumerable: true,
@@ -5720,13 +6629,16 @@ exports.DASHBOARDS_CHUNK_ID = DASHBOARDS_CHUNK_ID;
5720
6629
  exports.DirectoryHandleFeedTree = DirectoryHandleFeedTree;
5721
6630
  exports.EFFORTS_CHUNK_ID = EFFORTS_CHUNK_ID;
5722
6631
  exports.EQUIPMENT_CHUNK_ID = EQUIPMENT_CHUNK_ID;
6632
+ exports.FEED_SUBSCRIPTIONS_META_KEY = FEED_SUBSCRIPTIONS_META_KEY;
5723
6633
  exports.FeedTreeError = FeedTreeError;
5724
6634
  exports.GIT_SHA = GIT_SHA;
5725
6635
  exports.HttpFeedTree = HttpFeedTree;
5726
6636
  exports.MemoryFeedTree = MemoryFeedTree;
5727
6637
  exports.NOTE_ID_FRONTMATTER_KEY = NOTE_ID_FRONTMATTER_KEY;
6638
+ exports.PERSIST_WORLD_STORES = PERSIST_WORLD_STORES;
5728
6639
  exports.PUBLISHED_FEED_META_KEY = PUBLISHED_FEED_META_KEY;
5729
6640
  exports.QR_SCRIPT_ID = QR_SCRIPT_ID;
6641
+ exports.SAMPLE_TAG = SAMPLE_TAG;
5730
6642
  exports.SEED_BROADCAST_CHANNEL = SEED_BROADCAST_CHANNEL;
5731
6643
  exports.SEED_NAMESPACE = SEED_NAMESPACE;
5732
6644
  exports.SEED_REGISTERED_WIDGETS = SEED_REGISTERED_WIDGETS;
@@ -5743,6 +6655,10 @@ exports.assertSeedRow = assertSeedRow;
5743
6655
  exports.assertSeedRows = assertSeedRows;
5744
6656
  exports.backfillFeedProvenance = backfillFeedProvenance;
5745
6657
  exports.buildNoteProvenance = buildNoteProvenance;
6658
+ exports.buildQueryServiceStoresFromStorage = buildQueryServiceStoresFromStorage;
6659
+ exports.buildSampleBundle = buildSampleBundle;
6660
+ exports.buildSampleWorld = buildSampleWorld;
6661
+ exports.buildSessionLogs = buildSessionLogs;
5746
6662
  exports.buildStatementTree = buildStatementTree;
5747
6663
  exports.canvasRouteSlug = canvasRouteSlug;
5748
6664
  exports.checkUnpublishedFeedChanges = checkUnpublishedFeedChanges;
@@ -5755,6 +6671,7 @@ exports.csvToSessionRows = csvToSessionRows;
5755
6671
  exports.csvToTelemetryBundle = csvToTelemetryBundle;
5756
6672
  exports.decodeUtf8 = decodeUtf8;
5757
6673
  exports.defineLanguagePack = defineLanguagePack;
6674
+ exports.deleteFeedSourceHeadless = deleteFeedSourceHeadless;
5758
6675
  exports.effortToMarkdown = effortToMarkdown;
5759
6676
  exports.emptySeedMeta = emptySeedMeta;
5760
6677
  exports.encodeUtf8 = encodeUtf8;
@@ -5764,6 +6681,7 @@ exports.exportPortableFilesFromStorage = exportPortableFilesFromStorage;
5764
6681
  exports.extractNoteIdentity = extractNoteIdentity;
5765
6682
  exports.extractTypedTags = extractTypedTags;
5766
6683
  exports.feedIdOfMetaKey = feedIdOfMetaKey;
6684
+ exports.generateSampleSessions = generateSampleSessions;
5767
6685
  exports.getNoteNotebooks = getNoteNotebooks;
5768
6686
  exports.getNotePublicationSummary = getNotePublicationSummary;
5769
6687
  exports.getRegisteredLanguagePacks = getRegisteredLanguagePacks;
@@ -5771,6 +6689,7 @@ exports.inMemoryEventStore = inMemoryEventStore;
5771
6689
  exports.ingestPortableFilesIntoStorage = ingestPortableFilesIntoStorage;
5772
6690
  exports.injectIdentityFrontmatter = injectIdentityFrontmatter;
5773
6691
  exports.isIRFile = isIRFile;
6692
+ exports.listFeedSubscriptionsHeadless = listFeedSubscriptionsHeadless;
5774
6693
  exports.listLanguagePacks = listLanguagePacks;
5775
6694
  exports.listScopedPropertyOverrides = listScopedPropertyOverrides;
5776
6695
  exports.makeNotebookLinkId = makeNotebookLinkId;
@@ -5781,6 +6700,7 @@ exports.notebookSlugForChunkId = notebookSlugForChunkId;
5781
6700
  exports.parseCsvLine = parseCsvLine;
5782
6701
  exports.parseFrontmatterDateMs = parseFrontmatterDateMs;
5783
6702
  exports.parseNoteMarkdown = parseNoteMarkdown;
6703
+ exports.persistDomainWorld = persistDomainWorld;
5784
6704
  exports.prepareJournalSessionRun = prepareJournalSessionRun;
5785
6705
  exports.previewRemoteNotebook = previewRemoteNotebook;
5786
6706
  exports.previewRemoteRecord = previewRemoteRecord;
@@ -5789,11 +6709,14 @@ exports.promoteReferencedOverridesToNotebook = promoteReferencedOverridesToNoteb
5789
6709
  exports.publishFeedFromStorage = publishFeedFromStorage;
5790
6710
  exports.qrInlineScript = qrInlineScript;
5791
6711
  exports.readFrontmatterMeta = readFrontmatterMeta;
6712
+ exports.recordPublishedFeedCheckpoint = recordPublishedFeedCheckpoint;
5792
6713
  exports.registerLanguagePack = registerLanguagePack;
5793
6714
  exports.removeNoteFromNotebook = removeNoteFromNotebook;
6715
+ exports.removeSeedSourceContent = removeSeedSourceContent;
5794
6716
  exports.renderFeedLandingHtml = renderFeedLandingHtml;
5795
6717
  exports.resolveScopedPropertyCatalog = resolveScopedPropertyCatalog;
5796
6718
  exports.resolveUpstreamProvenance = resolveUpstreamProvenance;
6719
+ exports.round1 = round1;
5797
6720
  exports.saveScopedPropertyOverride = saveScopedPropertyOverride;
5798
6721
  exports.seedMetaKey = seedMetaKey;
5799
6722
  exports.seedNoteId = seedNoteId;
@@ -5807,8 +6730,10 @@ exports.setSessionPublic = setSessionPublic;
5807
6730
  exports.sha256HexAsync = sha256HexAsync;
5808
6731
  exports.splitCsvRecords = splitCsvRecords;
5809
6732
  exports.statementToNode = statementToNode;
6733
+ exports.subscribeFeedSourceHeadless = subscribeFeedSourceHeadless;
5810
6734
  exports.telemetryBundleToCsv = telemetryBundleToCsv;
5811
6735
  exports.unregisterLanguagePack = unregisterLanguagePack;
6736
+ exports.unsubscribeFeedSourceHeadless = unsubscribeFeedSourceHeadless;
5812
6737
  Object.keys(wodWikiCore).forEach(function (k) {
5813
6738
  if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
5814
6739
  enumerable: true,