@bitcobblers/wod-wiki-engine 0.56.2210 → 0.58.2220

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
@@ -940,13 +940,13 @@ function csvToTelemetryBundle(csv) {
940
940
  }
941
941
 
942
942
  // src/version.ts
943
- var VERSION = "0.56.2210";
944
- var GIT_SHA = "92d64b5";
945
- var BUILD_TIME = "2026-11-12T20:56:12.928Z";
943
+ var VERSION = "0.58.2220";
944
+ var GIT_SHA = "89b2e39";
945
+ var BUILD_TIME = "2026-11-14T03:19:12.696Z";
946
946
  var SEMVER = {
947
- version: "0.56.2210",
948
- gitSha: "92d64b5",
949
- buildTime: "2026-11-12T20:56:12.928Z"
947
+ version: "0.58.2220",
948
+ gitSha: "89b2e39",
949
+ buildTime: "2026-11-14T03:19:12.696Z"
950
950
  };
951
951
  var SEED_SCHEMA = 9;
952
952
  var SEED_REGISTERED_WIDGETS = wodWikiCore.KNOWN_SECTION_WIDGETS;
@@ -1644,10 +1644,26 @@ async function putChanged(store, values, keys) {
1644
1644
  const changed = values.filter((value, i) => !equal(value, prior[i]));
1645
1645
  if (changed.length) await store.putMany(changed);
1646
1646
  }
1647
- async function applySeedChunk(storage, write) {
1647
+ var SEED_TX_STORES = [
1648
+ "notes",
1649
+ "block_revisions",
1650
+ "block_index",
1651
+ "block_efforts",
1652
+ "block_equipment",
1653
+ "page",
1654
+ "page_notes",
1655
+ "tags",
1656
+ "note_tags",
1657
+ "efforts",
1658
+ "equipment",
1659
+ "property_overrides",
1660
+ "meta",
1661
+ "sessions",
1662
+ "events"
1663
+ ];
1664
+ async function prepareSeedChunkWrite(write) {
1648
1665
  assertSeedManifest(write.manifest);
1649
1666
  assertSeedRows(write.rows);
1650
- const result = { totalNotes: 0, totalEfforts: 0, totalEquipment: 0, totalBlocks: 0, skippedUserOwned: 0, deleted: 0, addedNotes: 0, updatedNotes: 0 };
1651
1667
  const ids = await Promise.all(write.rows.map((row) => seedNoteId(row.path)));
1652
1668
  const pagesBySlug = /* @__PURE__ */ new Map();
1653
1669
  const linkIds = /* @__PURE__ */ new Map();
@@ -1662,286 +1678,312 @@ async function applySeedChunk(storage, write) {
1662
1678
  if (!tagIds.has(label)) tagIds.set(label, await seedNoteId(`tag:${label}`));
1663
1679
  }
1664
1680
  }
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) => {
1666
- const metaStore = tx.readwrite("meta");
1667
- const userDeleted = /* @__PURE__ */ new Set();
1668
- for (const row of await metaStore.getAll()) {
1669
- const suppressed = wodWikiStorage.userDeletedSeedNoteId(row?.key);
1670
- if (suppressed !== void 0) userDeleted.add(suppressed);
1681
+ return { write, ids, pagesBySlug, linkIds, tagIds };
1682
+ }
1683
+ async function applySeedChunks(storage, writes) {
1684
+ const empty = { totalNotes: 0, totalEfforts: 0, totalEquipment: 0, totalBlocks: 0, skippedUserOwned: 0, deleted: 0, addedNotes: 0, updatedNotes: 0 };
1685
+ if (!writes.length) return empty;
1686
+ const prepared = await Promise.all(writes.map(prepareSeedChunkWrite));
1687
+ return storage.transaction(SEED_TX_STORES, "readwrite", async (tx) => {
1688
+ const total = { ...empty };
1689
+ for (const item of prepared) {
1690
+ const part = await applyPreparedSeedChunkInTx(tx, item);
1691
+ total.totalNotes += part.totalNotes;
1692
+ total.totalEfforts += part.totalEfforts;
1693
+ total.totalEquipment += part.totalEquipment;
1694
+ total.totalBlocks += part.totalBlocks;
1695
+ total.skippedUserOwned += part.skippedUserOwned;
1696
+ total.deleted += part.deleted;
1697
+ total.addedNotes += part.addedNotes;
1698
+ total.updatedNotes += part.updatedNotes;
1699
+ }
1700
+ return total;
1701
+ });
1702
+ }
1703
+ async function applySeedChunk(storage, write) {
1704
+ return applySeedChunks(storage, [write]);
1705
+ }
1706
+ async function applyPreparedSeedChunkInTx(tx, prepared) {
1707
+ const { write, ids, pagesBySlug, linkIds, tagIds } = prepared;
1708
+ const result = { totalNotes: 0, totalEfforts: 0, totalEquipment: 0, totalBlocks: 0, skippedUserOwned: 0, deleted: 0, addedNotes: 0, updatedNotes: 0 };
1709
+ const metaStore = tx.readwrite("meta");
1710
+ const userDeleted = /* @__PURE__ */ new Set();
1711
+ for (const row of await metaStore.getAll()) {
1712
+ const suppressed = wodWikiStorage.userDeletedSeedNoteId(row?.key);
1713
+ if (suppressed !== void 0) userDeleted.add(suppressed);
1714
+ }
1715
+ const actualMeta = await metaStore.get(write.meta.key);
1716
+ if (!equal(actualMeta, write.expectedMeta)) throw new Error("Seed checkpoint changed during import");
1717
+ if (write.meta.schema !== SEED_SCHEMA || write.manifest.schema !== SEED_SCHEMA) throw new Error("Incompatible seed schema; recreate artifacts");
1718
+ const noteStore = tx.readwrite("notes");
1719
+ const priorIds = write.chunkId ? write.expectedMeta?.chunks[write.chunkId]?.noteIds ?? [] : [];
1720
+ const declared = new Set((write.chunkId ? write.meta.chunks[write.chunkId]?.noteIds : void 0) ?? ids);
1721
+ const goneIds = priorIds.filter((id) => !declared.has(id));
1722
+ const allIds = [.../* @__PURE__ */ new Set([...ids, ...goneIds])];
1723
+ const stored = await noteStore.getMany(allIds);
1724
+ const existingById = new Map(allIds.map((id, i) => [id, stored[i]]));
1725
+ const seedSource = write.meta.key.startsWith("seed:") ? write.meta.key.slice(5) : write.meta.key;
1726
+ const feedSourceId = feedIdOfMetaKey(write.meta.key);
1727
+ const incomingRank = seedPrecedenceRank(write.meta.key, write.meta.tier);
1728
+ const otherCheckpoints = [];
1729
+ for (const row of await metaStore.getAll()) {
1730
+ const meta = row;
1731
+ if (!meta || typeof meta.key !== "string" || !meta.key.startsWith("seed:") || meta.key === write.meta.key) continue;
1732
+ const noteIds = /* @__PURE__ */ new Set();
1733
+ for (const chunk of Object.values(meta.chunks ?? {})) {
1734
+ for (const noteId of chunk.noteIds ?? []) noteIds.add(noteId);
1735
+ }
1736
+ otherCheckpoints.push({
1737
+ key: meta.key,
1738
+ sourceId: meta.key.slice(5),
1739
+ rank: seedPrecedenceRank(meta.key, meta.tier),
1740
+ meta,
1741
+ noteIds
1742
+ });
1743
+ }
1744
+ otherCheckpoints.sort((a, b) => b.rank - a.rank);
1745
+ const maxOtherRankForNote = (noteId) => {
1746
+ let max = -1;
1747
+ for (const cp of otherCheckpoints) {
1748
+ if (cp.noteIds.has(noteId) && cp.rank > max) max = cp.rank;
1671
1749
  }
1672
- const actualMeta = await metaStore.get(write.meta.key);
1673
- if (!equal(actualMeta, write.expectedMeta)) throw new Error("Seed checkpoint changed during import");
1674
- if (write.meta.schema !== SEED_SCHEMA || write.manifest.schema !== SEED_SCHEMA) throw new Error("Incompatible seed schema; recreate artifacts");
1675
- const noteStore = tx.readwrite("notes");
1676
- const priorIds = write.chunkId ? write.expectedMeta?.chunks[write.chunkId]?.noteIds ?? [] : [];
1677
- const declared = new Set((write.chunkId ? write.meta.chunks[write.chunkId]?.noteIds : void 0) ?? ids);
1678
- const goneIds = priorIds.filter((id) => !declared.has(id));
1679
- const allIds = [.../* @__PURE__ */ new Set([...ids, ...goneIds])];
1680
- const stored = await noteStore.getMany(allIds);
1681
- const existingById = new Map(allIds.map((id, i) => [id, stored[i]]));
1682
- const seedSource = write.meta.key.startsWith("seed:") ? write.meta.key.slice(5) : write.meta.key;
1683
- const feedSourceId = feedIdOfMetaKey(write.meta.key);
1684
- const incomingRank = seedPrecedenceRank(write.meta.key, write.meta.tier);
1685
- const otherCheckpoints = [];
1686
- for (const row of await metaStore.getAll()) {
1687
- const meta = row;
1688
- if (!meta || typeof meta.key !== "string" || !meta.key.startsWith("seed:") || meta.key === write.meta.key) continue;
1689
- const noteIds = /* @__PURE__ */ new Set();
1690
- for (const chunk of Object.values(meta.chunks ?? {})) {
1691
- for (const noteId of chunk.noteIds ?? []) noteIds.add(noteId);
1692
- }
1693
- otherCheckpoints.push({
1694
- key: meta.key,
1695
- sourceId: meta.key.slice(5),
1696
- rank: seedPrecedenceRank(meta.key, meta.tier),
1697
- meta,
1698
- noteIds
1699
- });
1750
+ return max;
1751
+ };
1752
+ const ownedIds = allIds.filter((id) => {
1753
+ if (userDeleted.has(id)) return false;
1754
+ const note = existingById.get(id);
1755
+ if (!note) return declared.has(id);
1756
+ if (note.seedOrigin !== "seed") return false;
1757
+ const otherRank = maxOtherRankForNote(id);
1758
+ if (declared.has(id)) return incomingRank >= otherRank;
1759
+ return otherRank < 0 && note.seedChunkId === write.chunkId;
1760
+ });
1761
+ const owned = new Set(ownedIds);
1762
+ const revisionStore = tx.readwrite("block_revisions");
1763
+ const historyIds = ids.filter((id, i) => owned.has(id) && existingById.get(id)?.rawContent !== write.rows[i].content);
1764
+ const histories = await revisionStore.getAllFromIndexMany("by-note", historyIds);
1765
+ const history = new Map(historyIds.map((id, i) => [id, histories[i]]));
1766
+ const indexStore = tx.readwrite("block_index"), effortLinks = tx.readwrite("block_efforts"), equipmentLinks = tx.readwrite("block_equipment");
1767
+ const tagLinks = tx.readwrite("note_tags"), pageLinks = tx.readwrite("page_notes");
1768
+ const currentIndexes = await indexStore.getAllFromIndexMany("by-note", ownedIds);
1769
+ const currentEfforts = await effortLinks.getAllFromIndexMany("by-note", ownedIds);
1770
+ const currentEquipment = await equipmentLinks.getAllFromIndexMany("by-note", ownedIds);
1771
+ const currentTags = await tagLinks.getAllFromIndexMany("by-note", ownedIds);
1772
+ const currentPages = await pageLinks.getAllFromIndexMany("by-note", ownedIds);
1773
+ const slot = new Map(ownedIds.map((id, i) => [id, i]));
1774
+ const tagsStore = tx.readwrite("tags");
1775
+ const labels = [...tagIds.keys()];
1776
+ const matches = await tagsStore.getAllFromIndexMany("by-label", labels);
1777
+ const tagsByLabel = new Map(labels.map((label, i) => [label, matches[i][0]]));
1778
+ const changedTags = [], changedNotes = [], revisions = [], pages = [], pageNotes = [], noteTags = [];
1779
+ const blocks = [], blockEfforts = [], blockEquipment = [];
1780
+ const sessionStore = tx.readwrite("sessions"), eventStore = tx.readwrite("events");
1781
+ const telemetrySessionIds = write.rows.flatMap((row) => row.telemetry?.sessions.map((session) => session.id) ?? []);
1782
+ const storedTelemetrySessions = await sessionStore.getMany(telemetrySessionIds);
1783
+ const existingTelemetrySessions = new Map(telemetrySessionIds.map((sessionId, i) => [sessionId, storedTelemetrySessions[i]]));
1784
+ const sessions = [], events = [];
1785
+ for (const [i, row] of write.rows.entries()) {
1786
+ const id = ids[i], existing = existingById.get(id);
1787
+ if (!owned.has(id)) {
1788
+ if (existing && existing.seedOrigin !== "seed") result.skippedUserOwned++;
1789
+ continue;
1700
1790
  }
1701
- otherCheckpoints.sort((a, b) => b.rank - a.rank);
1702
- const maxOtherRankForNote = (noteId) => {
1703
- let max = -1;
1704
- for (const cp of otherCheckpoints) {
1705
- if (cp.noteIds.has(noteId) && cp.rank > max) max = cp.rank;
1706
- }
1707
- return max;
1708
- };
1709
- const ownedIds = allIds.filter((id) => {
1710
- if (userDeleted.has(id)) return false;
1711
- const note = existingById.get(id);
1712
- if (!note) return declared.has(id);
1713
- if (note.seedOrigin !== "seed") return false;
1714
- const otherRank = maxOtherRankForNote(id);
1715
- if (declared.has(id)) return incomingRank >= otherRank;
1716
- return otherRank < 0 && note.seedChunkId === write.chunkId;
1717
- });
1718
- const owned = new Set(ownedIds);
1719
- const revisionStore = tx.readwrite("block_revisions");
1720
- const historyIds = ids.filter((id, i) => owned.has(id) && existingById.get(id)?.rawContent !== write.rows[i].content);
1721
- const histories = await revisionStore.getAllFromIndexMany("by-note", historyIds);
1722
- const history = new Map(historyIds.map((id, i) => [id, histories[i]]));
1723
- const indexStore = tx.readwrite("block_index"), effortLinks = tx.readwrite("block_efforts"), equipmentLinks = tx.readwrite("block_equipment");
1724
- const tagLinks = tx.readwrite("note_tags"), pageLinks = tx.readwrite("page_notes");
1725
- const currentIndexes = await indexStore.getAllFromIndexMany("by-note", ownedIds);
1726
- const currentEfforts = await effortLinks.getAllFromIndexMany("by-note", ownedIds);
1727
- const currentEquipment = await equipmentLinks.getAllFromIndexMany("by-note", ownedIds);
1728
- const currentTags = await tagLinks.getAllFromIndexMany("by-note", ownedIds);
1729
- const currentPages = await pageLinks.getAllFromIndexMany("by-note", ownedIds);
1730
- const slot = new Map(ownedIds.map((id, i) => [id, i]));
1731
- const tagsStore = tx.readwrite("tags");
1732
- const labels = [...tagIds.keys()];
1733
- const matches = await tagsStore.getAllFromIndexMany("by-label", labels);
1734
- const tagsByLabel = new Map(labels.map((label, i) => [label, matches[i][0]]));
1735
- const changedTags = [], changedNotes = [], revisions = [], pages = [], pageNotes = [], noteTags = [];
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 = [];
1742
- for (const [i, row] of write.rows.entries()) {
1743
- const id = ids[i], existing = existingById.get(id);
1744
- if (!owned.has(id)) {
1745
- if (existing && existing.seedOrigin !== "seed") result.skippedUserOwned++;
1791
+ if (!existing) result.addedNotes++;
1792
+ else if (existing.rawContent !== row.content) result.updatedNotes++;
1793
+ wodWikiCore.validateNoteBlocks(row.content, row.blocks, 1, { registeredWidgets: SEED_REGISTERED_WIDGETS });
1794
+ const sourceRevision = existing ? existing.sourceRevision + (existing.rawContent === row.content ? 0 : 1) : 1;
1795
+ let ordinal = 0;
1796
+ const retainedHistory = history.get(id) ?? [];
1797
+ const map = !existing ? retainedHistory.length ? wodWikiCore.reconcileNoteBlocks(row.content, { sourceRevision, registeredWidgets: SEED_REGISTERED_WIDGETS, createId: () => `seed:${id}:new${retainedHistory.length}:${ordinal++}` }) : structuredClone(row.blocks) : existing.rawContent === row.content ? structuredClone(existing.blocks) : refreshedBlocks(existing, row.content, sourceRevision);
1798
+ for (const block of Object.values(map)) {
1799
+ const saved = (history.get(id) ?? []).filter((r) => r.blockId === block.id).sort((a, b) => b.version - a.version)[0];
1800
+ const source = row.content.slice(block.from, block.to);
1801
+ if (existing?.rawContent === row.content) continue;
1802
+ const same = saved && saved.kind === block.kind && saved.rawContent === source && saved.dialect === block.dialect && saved.sport === block.sport;
1803
+ block.version = !existing ? 1 : same ? saved.version : (saved?.version ?? 0) + 1;
1804
+ if (!existing || !same) revisions.push({ noteId: id, blockId: block.id, version: block.version, kind: block.kind, rawContent: source, savedAt: write.meta.importedAt, ...block.dialect ? { dialect: block.dialect } : {}, ...block.sport ? { sport: block.sport } : {} });
1805
+ }
1806
+ wodWikiCore.validateNoteBlocks(row.content, map, sourceRevision, { registeredWidgets: SEED_REGISTERED_WIDGETS });
1807
+ const fm = readFrontmatterMeta(row.content);
1808
+ const title = typeof fm["title"] === "string" && fm["title"].trim() ? fm["title"].trim() : titleFromPath(row.path);
1809
+ const sourceId = write.chunkId ? seedNoteSourceId(row.path, row.content, write.chunkId) : void 0;
1810
+ if (!sourceId) throw new Error(`Unknown seed source family ${write.chunkId}`);
1811
+ const dateMatch = typeof fm["date"] === "string" ? fm["date"].match(/^(\d{4})-(\d{2})-(\d{2})$/) : null;
1812
+ let date;
1813
+ if (dateMatch) {
1814
+ const ts = Date.parse(`${fm["date"]}T12:00:00Z`);
1815
+ const real = Number.isFinite(ts) && new Date(ts).getUTCMonth() === Number(dateMatch[2]) - 1 && new Date(ts).getUTCDate() === Number(dateMatch[3]);
1816
+ if (!real) throw new Error(`invalid frontmatter date '${fm["date"]}' in '${row.path}' \u2014 expected a real calendar day (YYYY-MM-DD)`);
1817
+ date = ts;
1818
+ }
1819
+ const seedCommit = row.commit ?? write.manifest.commit;
1820
+ const note = { ...existing, id, title, rawContent: row.content, sourceRevision, blocks: map, createdAt: write.manifest.version, ...date === void 0 ? {} : { date }, type: write.chunkId === DASHBOARDS_CHUNK_ID ? "dashboard" : "note", sourceId, seedOrigin: "seed", seedVersion: write.manifest.version, seedChunkId: write.chunkId ?? void 0, feedOrigin: "feed", feedSourceId, sourcePath: row.path, ...seedCommit ? { seedCommit } : {} };
1821
+ if (date === void 0) delete note.date;
1822
+ if (!equal(note, existing)) changedNotes.push(note);
1823
+ const byRange = new Map(Object.values(map).map((b) => [`${b.from}:${b.to}`, b]));
1824
+ const compiledById = new Map(row.blockIndex.map((b) => [b.blockId, b]));
1825
+ const remap = /* @__PURE__ */ new Map();
1826
+ for (const compiled of row.blockIndex) {
1827
+ const block = byRange.get(`${compiled.from}:${compiled.to}`);
1828
+ if (!block || block.kind !== compiled.dataType) throw new Error("Orphan seed projection");
1829
+ remap.set(compiled.blockId, block.id);
1830
+ const projection = { ...compiled, id: `${id}:${block.id}`, noteId: id, blockId: block.id, blockVersion: block.version, sourceRevision, noteTitle: title, sourceId, sourcePath: row.path, rawContent: row.content.slice(block.from, block.to) };
1831
+ const prior = currentIndexes[slot.get(id)].find((b) => b.id === projection.id);
1832
+ if (!prior || prior.isStatic === true) blocks.push(projection);
1833
+ }
1834
+ const resolvedSessions = /* @__PURE__ */ new Map();
1835
+ const userRecordedSessions = /* @__PURE__ */ new Set();
1836
+ for (const compiled of row.telemetry?.sessions ?? []) {
1837
+ if (compiledById.get(compiled.blockId)?.dataType !== "wod") throw new Error("Orphan seed session pin");
1838
+ const prior = existingTelemetrySessions.get(compiled.id);
1839
+ if (prior && prior.noteId !== id) throw new Error(`Seed session ${compiled.id} belongs to another note`);
1840
+ if (prior?.origin) {
1841
+ userRecordedSessions.add(compiled.id);
1746
1842
  continue;
1747
1843
  }
1748
- if (!existing) result.addedNotes++;
1749
- else if (existing.rawContent !== row.content) result.updatedNotes++;
1750
- wodWikiCore.validateNoteBlocks(row.content, row.blocks, 1, { registeredWidgets: SEED_REGISTERED_WIDGETS });
1751
- const sourceRevision = existing ? existing.sourceRevision + (existing.rawContent === row.content ? 0 : 1) : 1;
1752
- let ordinal = 0;
1753
- const retainedHistory = history.get(id) ?? [];
1754
- const map = !existing ? retainedHistory.length ? wodWikiCore.reconcileNoteBlocks(row.content, { sourceRevision, registeredWidgets: SEED_REGISTERED_WIDGETS, createId: () => `seed:${id}:new${retainedHistory.length}:${ordinal++}` }) : structuredClone(row.blocks) : existing.rawContent === row.content ? structuredClone(existing.blocks) : refreshedBlocks(existing, row.content, sourceRevision);
1755
- for (const block of Object.values(map)) {
1756
- const saved = (history.get(id) ?? []).filter((r) => r.blockId === block.id).sort((a, b) => b.version - a.version)[0];
1757
- const source = row.content.slice(block.from, block.to);
1758
- if (existing?.rawContent === row.content) continue;
1759
- const same = saved && saved.kind === block.kind && saved.rawContent === source && saved.dialect === block.dialect && saved.sport === block.sport;
1760
- block.version = !existing ? 1 : same ? saved.version : (saved?.version ?? 0) + 1;
1761
- if (!existing || !same) revisions.push({ noteId: id, blockId: block.id, version: block.version, kind: block.kind, rawContent: source, savedAt: write.meta.importedAt, ...block.dialect ? { dialect: block.dialect } : {}, ...block.sport ? { sport: block.sport } : {} });
1762
- }
1763
- wodWikiCore.validateNoteBlocks(row.content, map, sourceRevision, { registeredWidgets: SEED_REGISTERED_WIDGETS });
1764
- const fm = readFrontmatterMeta(row.content);
1765
- const title = typeof fm["title"] === "string" && fm["title"].trim() ? fm["title"].trim() : titleFromPath(row.path);
1766
- const sourceId = write.chunkId ? seedNoteSourceId(row.path, row.content, write.chunkId) : void 0;
1767
- if (!sourceId) throw new Error(`Unknown seed source family ${write.chunkId}`);
1768
- const dateMatch = typeof fm["date"] === "string" ? fm["date"].match(/^(\d{4})-(\d{2})-(\d{2})$/) : null;
1769
- let date;
1770
- if (dateMatch) {
1771
- const ts = Date.parse(`${fm["date"]}T12:00:00Z`);
1772
- const real = Number.isFinite(ts) && new Date(ts).getUTCMonth() === Number(dateMatch[2]) - 1 && new Date(ts).getUTCDate() === Number(dateMatch[3]);
1773
- if (!real) throw new Error(`invalid frontmatter date '${fm["date"]}' in '${row.path}' \u2014 expected a real calendar day (YYYY-MM-DD)`);
1774
- date = ts;
1775
- }
1776
- const seedCommit = row.commit ?? write.manifest.commit;
1777
- const note = { ...existing, id, title, rawContent: row.content, sourceRevision, blocks: map, createdAt: write.manifest.version, ...date === void 0 ? {} : { date }, type: write.chunkId === DASHBOARDS_CHUNK_ID ? "dashboard" : "note", sourceId, seedOrigin: "seed", seedVersion: write.manifest.version, seedChunkId: write.chunkId ?? void 0, feedOrigin: "feed", feedSourceId, sourcePath: row.path, ...seedCommit ? { seedCommit } : {} };
1778
- if (date === void 0) delete note.date;
1779
- if (!equal(note, existing)) changedNotes.push(note);
1780
- const byRange = new Map(Object.values(map).map((b) => [`${b.from}:${b.to}`, b]));
1781
- const compiledById = new Map(row.blockIndex.map((b) => [b.blockId, b]));
1782
- const remap = /* @__PURE__ */ new Map();
1783
- for (const compiled of row.blockIndex) {
1784
- const block = byRange.get(`${compiled.from}:${compiled.to}`);
1785
- if (!block || block.kind !== compiled.dataType) throw new Error("Orphan seed projection");
1786
- remap.set(compiled.blockId, block.id);
1787
- const projection = { ...compiled, id: `${id}:${block.id}`, noteId: id, blockId: block.id, blockVersion: block.version, sourceRevision, noteTitle: title, sourceId, sourcePath: row.path, rawContent: row.content.slice(block.from, block.to) };
1788
- const prior = currentIndexes[slot.get(id)].find((b) => b.id === projection.id);
1789
- if (!prior || prior.isStatic === true) blocks.push(projection);
1790
- }
1791
- const resolvedSessions = /* @__PURE__ */ new Map();
1792
- const userRecordedSessions = /* @__PURE__ */ new Set();
1793
- for (const compiled of row.telemetry?.sessions ?? []) {
1794
- if (compiledById.get(compiled.blockId)?.dataType !== "wod") throw new Error("Orphan seed session pin");
1795
- const prior = existingTelemetrySessions.get(compiled.id);
1796
- if (prior && prior.noteId !== id) throw new Error(`Seed session ${compiled.id} belongs to another note`);
1797
- if (prior?.origin) {
1798
- userRecordedSessions.add(compiled.id);
1799
- continue;
1800
- }
1801
- const blockId = prior?.blockId ?? remap.get(compiled.blockId);
1802
- if (!blockId) throw new Error("Orphan seed session pin");
1803
- const block = map[blockId];
1804
- if (!prior && !block) throw new Error("Orphan seed session pin");
1805
- const session = {
1806
- ...compiled,
1807
- noteId: id,
1808
- blockId,
1809
- blockVersion: prior?.blockVersion ?? block.version,
1810
- blockContentId: prior?.blockContentId ?? compiledById.get(compiled.blockId)?.blockContentId
1811
- };
1812
- sessions.push(session);
1813
- resolvedSessions.set(session.id, session);
1844
+ const blockId = prior?.blockId ?? remap.get(compiled.blockId);
1845
+ if (!blockId) throw new Error("Orphan seed session pin");
1846
+ const block = map[blockId];
1847
+ if (!prior && !block) throw new Error("Orphan seed session pin");
1848
+ const session = {
1849
+ ...compiled,
1850
+ noteId: id,
1851
+ blockId,
1852
+ blockVersion: prior?.blockVersion ?? block.version,
1853
+ blockContentId: prior?.blockContentId ?? compiledById.get(compiled.blockId)?.blockContentId
1854
+ };
1855
+ sessions.push(session);
1856
+ resolvedSessions.set(session.id, session);
1857
+ }
1858
+ for (const compiled of row.telemetry?.events ?? []) {
1859
+ if (userRecordedSessions.has(compiled.resultId)) continue;
1860
+ const session = resolvedSessions.get(compiled.resultId);
1861
+ if (!session) throw new Error("Orphan seed event result");
1862
+ events.push({
1863
+ ...compiled,
1864
+ noteId: id,
1865
+ blockId: session.blockId,
1866
+ blockVersion: session.blockVersion,
1867
+ blockContentId: session.blockContentId
1868
+ });
1869
+ }
1870
+ for (const compiled of row.blockEfforts) {
1871
+ const blockId = remap.get(compiled.blockId);
1872
+ if (!blockId || compiledById.get(compiled.blockId)?.dataType !== "wod") throw new Error("Orphan seed effort link");
1873
+ const link = { ...compiled, id: `${id}:${blockId}:${compiled.effortSlug}`, noteId: id, blockId, sourcePath: row.path };
1874
+ const prior = currentEfforts[slot.get(id)].find((b) => b.id === link.id);
1875
+ if (!prior || prior.isStatic === true) blockEfforts.push(prior ? { ...link, createdAt: prior.createdAt } : link);
1876
+ }
1877
+ for (const compiled of row.blockEquipment) {
1878
+ const blockId = remap.get(compiled.blockId);
1879
+ if (!blockId || compiledById.get(compiled.blockId)?.dataType !== "wod") throw new Error("Orphan seed equipment link");
1880
+ const link = { ...compiled, id: `${id}:${blockId}:${compiled.equipmentSlug}`, noteId: id, blockId, sourcePath: row.path };
1881
+ const prior = currentEquipment[slot.get(id)].find((b) => b.id === link.id);
1882
+ if (!prior || prior.isStatic === true) blockEquipment.push(prior ? { ...link, createdAt: prior.createdAt } : link);
1883
+ }
1884
+ const n = slot.get(id);
1885
+ const wantedTags = /* @__PURE__ */ new Set();
1886
+ for (const item of extractTypedTags(row.content)) {
1887
+ let tag = tagsByLabel.get(item.label);
1888
+ if (!tag) {
1889
+ tag = { id: tagIds.get(item.label), label: item.label, type: item.type, createdAt: write.meta.importedAt };
1890
+ changedTags.push(tag);
1891
+ tagsByLabel.set(item.label, tag);
1892
+ } else if (item.type && !tag.type) {
1893
+ tag = { ...tag, type: item.type };
1894
+ changedTags.push(tag);
1895
+ tagsByLabel.set(item.label, tag);
1814
1896
  }
1815
- for (const compiled of row.telemetry?.events ?? []) {
1816
- if (userRecordedSessions.has(compiled.resultId)) continue;
1817
- const session = resolvedSessions.get(compiled.resultId);
1818
- if (!session) throw new Error("Orphan seed event result");
1819
- events.push({
1820
- ...compiled,
1821
- noteId: id,
1822
- blockId: session.blockId,
1823
- blockVersion: session.blockVersion,
1824
- blockContentId: session.blockContentId
1897
+ if (wantedTags.has(tag.id)) continue;
1898
+ wantedTags.add(tag.id);
1899
+ const link = currentTags[n].find((l) => l.tagId === tag.id);
1900
+ if (!link) noteTags.push({ id: `${id}:${tag.id}`, noteId: id, tagId: tag.id });
1901
+ }
1902
+ for (const link of currentTags[n]) if (!wantedTags.has(link.tagId)) await tagLinks.delete(link.id);
1903
+ const slug = fm["slug"];
1904
+ if (typeof slug === "string" && pagesBySlug.has(slug)) {
1905
+ const pageId = pagesBySlug.get(slug);
1906
+ pages.push({ id: pageId, slug, title: titleFromPath(row.path), createdAt: write.manifest.version });
1907
+ pageNotes.push({ id: linkIds.get(id), pageId, noteId: id, createdAt: write.manifest.version });
1908
+ }
1909
+ result.totalNotes++;
1910
+ result.totalBlocks += Object.keys(map).length;
1911
+ }
1912
+ const wantedBlocks = new Set(blocks.map((b) => b.id)), wantedEfforts = new Set(blockEfforts.map((b) => b.id)), wantedEquipment = new Set(blockEquipment.map((b) => b.id));
1913
+ for (const rows of currentIndexes) for (const row of rows) if (row.isStatic === true && !wantedBlocks.has(row.id)) await indexStore.delete(row.id);
1914
+ for (const rows of currentEfforts) for (const row of rows) if (row.isStatic === true && !wantedEfforts.has(row.id)) await effortLinks.delete(row.id);
1915
+ for (const rows of currentEquipment) for (const row of rows) if (row.isStatic === true && !wantedEquipment.has(row.id)) await equipmentLinks.delete(row.id);
1916
+ for (const id of goneIds) {
1917
+ if (!owned.has(id) || !existingById.get(id)) continue;
1918
+ const n = slot.get(id);
1919
+ await noteStore.delete(id);
1920
+ for (const link of currentTags[n]) await tagLinks.delete(link.id);
1921
+ for (const link of currentPages[n]) await pageLinks.delete(link.id);
1922
+ result.deleted++;
1923
+ }
1924
+ const recordSeedPropertyOverrides = async (kind, parse) => {
1925
+ let overrideStore;
1926
+ try {
1927
+ overrideStore = tx.readwrite("property_overrides");
1928
+ } catch {
1929
+ return;
1930
+ }
1931
+ const scopes = feedSourceId === "core" ? ["notebook/defaults"] : [
1932
+ `feed:${feedSourceId}`,
1933
+ ...write.manifest.chunks.filter((c) => c.id.startsWith("notebook.")).map((c) => `notebook/${notebookSlugForChunkId(c.id)}`)
1934
+ ];
1935
+ const wantedIds = /* @__PURE__ */ new Set();
1936
+ const toPut = [];
1937
+ for (const [idx, row] of write.rows.entries()) {
1938
+ const parsed = parse(row.content);
1939
+ if (!parsed) continue;
1940
+ for (const scope of scopes) {
1941
+ const ovId = makeScopedOverrideId(scope, kind, parsed.slug);
1942
+ wantedIds.add(ovId);
1943
+ toPut.push({
1944
+ id: ovId,
1945
+ notebookId: scope,
1946
+ kind,
1947
+ slug: parsed.slug,
1948
+ label: parsed.label,
1949
+ ownerNoteId: ids[idx],
1950
+ rawContent: row.content,
1951
+ payload: parsed,
1952
+ seedOrigin: "seed",
1953
+ feedSourceId,
1954
+ updatedAt: write.meta.importedAt
1825
1955
  });
1826
1956
  }
1827
- for (const compiled of row.blockEfforts) {
1828
- const blockId = remap.get(compiled.blockId);
1829
- if (!blockId || compiledById.get(compiled.blockId)?.dataType !== "wod") throw new Error("Orphan seed effort link");
1830
- const link = { ...compiled, id: `${id}:${blockId}:${compiled.effortSlug}`, noteId: id, blockId, sourcePath: row.path };
1831
- const prior = currentEfforts[slot.get(id)].find((b) => b.id === link.id);
1832
- if (!prior || prior.isStatic === true) blockEfforts.push(prior ? { ...link, createdAt: prior.createdAt } : link);
1833
- }
1834
- for (const compiled of row.blockEquipment) {
1835
- const blockId = remap.get(compiled.blockId);
1836
- if (!blockId || compiledById.get(compiled.blockId)?.dataType !== "wod") throw new Error("Orphan seed equipment link");
1837
- const link = { ...compiled, id: `${id}:${blockId}:${compiled.equipmentSlug}`, noteId: id, blockId, sourcePath: row.path };
1838
- const prior = currentEquipment[slot.get(id)].find((b) => b.id === link.id);
1839
- if (!prior || prior.isStatic === true) blockEquipment.push(prior ? { ...link, createdAt: prior.createdAt } : link);
1840
- }
1841
- const n = slot.get(id);
1842
- const wantedTags = /* @__PURE__ */ new Set();
1843
- for (const item of extractTypedTags(row.content)) {
1844
- let tag = tagsByLabel.get(item.label);
1845
- if (!tag) {
1846
- tag = { id: tagIds.get(item.label), label: item.label, type: item.type, createdAt: write.meta.importedAt };
1847
- changedTags.push(tag);
1848
- tagsByLabel.set(item.label, tag);
1849
- } else if (item.type && !tag.type) {
1850
- tag = { ...tag, type: item.type };
1851
- changedTags.push(tag);
1852
- tagsByLabel.set(item.label, tag);
1853
- }
1854
- if (wantedTags.has(tag.id)) continue;
1855
- wantedTags.add(tag.id);
1856
- const link = currentTags[n].find((l) => l.tagId === tag.id);
1857
- if (!link) noteTags.push({ id: `${id}:${tag.id}`, noteId: id, tagId: tag.id });
1858
- }
1859
- for (const link of currentTags[n]) if (!wantedTags.has(link.tagId)) await tagLinks.delete(link.id);
1860
- const slug = fm["slug"];
1861
- if (typeof slug === "string" && pagesBySlug.has(slug)) {
1862
- const pageId = pagesBySlug.get(slug);
1863
- pages.push({ id: pageId, slug, title: titleFromPath(row.path), createdAt: write.manifest.version });
1864
- pageNotes.push({ id: linkIds.get(id), pageId, noteId: id, createdAt: write.manifest.version });
1865
- }
1866
- result.totalNotes++;
1867
- result.totalBlocks += Object.keys(map).length;
1868
- }
1869
- const wantedBlocks = new Set(blocks.map((b) => b.id)), wantedEfforts = new Set(blockEfforts.map((b) => b.id)), wantedEquipment = new Set(blockEquipment.map((b) => b.id));
1870
- for (const rows of currentIndexes) for (const row of rows) if (row.isStatic === true && !wantedBlocks.has(row.id)) await indexStore.delete(row.id);
1871
- for (const rows of currentEfforts) for (const row of rows) if (row.isStatic === true && !wantedEfforts.has(row.id)) await effortLinks.delete(row.id);
1872
- for (const rows of currentEquipment) for (const row of rows) if (row.isStatic === true && !wantedEquipment.has(row.id)) await equipmentLinks.delete(row.id);
1873
- for (const id of goneIds) {
1874
- if (!owned.has(id) || !existingById.get(id)) continue;
1875
- const n = slot.get(id);
1876
- await noteStore.delete(id);
1877
- for (const link of currentTags[n]) await tagLinks.delete(link.id);
1878
- for (const link of currentPages[n]) await pageLinks.delete(link.id);
1879
- result.deleted++;
1880
- }
1881
- const recordSeedPropertyOverrides = async (kind, parse) => {
1882
- let overrideStore;
1883
- try {
1884
- overrideStore = tx.readwrite("property_overrides");
1885
- } catch {
1886
- return;
1887
- }
1888
- const scopes = feedSourceId === "core" ? ["notebook/defaults"] : [
1889
- `feed:${feedSourceId}`,
1890
- ...write.manifest.chunks.filter((c) => c.id.startsWith("notebook.")).map((c) => `notebook/${notebookSlugForChunkId(c.id)}`)
1891
- ];
1892
- const wantedIds = /* @__PURE__ */ new Set();
1893
- const toPut = [];
1894
- for (const [idx, row] of write.rows.entries()) {
1895
- const parsed = parse(row.content);
1896
- if (!parsed) continue;
1897
- for (const scope of scopes) {
1898
- const ovId = makeScopedOverrideId(scope, kind, parsed.slug);
1899
- wantedIds.add(ovId);
1900
- toPut.push({
1901
- id: ovId,
1902
- notebookId: scope,
1903
- kind,
1904
- slug: parsed.slug,
1905
- label: parsed.label,
1906
- ownerNoteId: ids[idx],
1907
- rawContent: row.content,
1908
- payload: parsed,
1909
- seedOrigin: "seed",
1910
- feedSourceId,
1911
- updatedAt: write.meta.importedAt
1912
- });
1913
- }
1914
- }
1915
- if (toPut.length > 0) await overrideStore.putMany(toPut);
1916
- const existingAll = await overrideStore.getAll();
1917
- for (const existingOv of existingAll) {
1918
- if (existingOv.seedOrigin === "seed" && existingOv.feedSourceId === feedSourceId && existingOv.kind === kind && !wantedIds.has(existingOv.id)) {
1919
- await overrideStore.delete(existingOv.id);
1920
- }
1957
+ }
1958
+ if (toPut.length > 0) await overrideStore.putMany(toPut);
1959
+ const existingAll = await overrideStore.getAll();
1960
+ for (const existingOv of existingAll) {
1961
+ if (existingOv.seedOrigin === "seed" && existingOv.feedSourceId === feedSourceId && existingOv.kind === kind && !wantedIds.has(existingOv.id)) {
1962
+ await overrideStore.delete(existingOv.id);
1921
1963
  }
1922
- };
1923
- if (write.chunkId === EFFORTS_CHUNK_ID) {
1924
- result.totalEfforts = await applyDefinitionChunk(tx.readwrite("efforts"), noteStore, wodWikiLang.parseEffortFile, "efforts", seedSource, incomingRank, otherCheckpoints, priorIds, write.rows, ids, owned, existingById, allIds);
1925
- await recordSeedPropertyOverrides("effort", wodWikiLang.parseEffortFile);
1926
- }
1927
- if (write.chunkId === EQUIPMENT_CHUNK_ID) {
1928
- result.totalEquipment = await applyDefinitionChunk(tx.readwrite("equipment"), noteStore, wodWikiLang.parseEquipmentFile, "equipment", seedSource, incomingRank, otherCheckpoints, priorIds, write.rows, ids, owned, existingById, allIds);
1929
- await recordSeedPropertyOverrides("equipment", wodWikiLang.parseEquipmentFile);
1930
- }
1931
- if (changedNotes.length) await noteStore.putMany(changedNotes);
1932
- if (revisions.length) await revisionStore.putMany(revisions);
1933
- await putChanged(indexStore, blocks, blocks.map((b) => b.id));
1934
- await putChanged(effortLinks, blockEfforts, blockEfforts.map((b) => b.id));
1935
- await putChanged(equipmentLinks, blockEquipment, blockEquipment.map((b) => b.id));
1936
- await putChanged(sessionStore, sessions, sessions.map((session) => session.id));
1937
- await putChanged(eventStore, events, events.map((event) => event.id));
1938
- if (changedTags.length) await tagsStore.putMany([...new Map(changedTags.map((t) => [t.id, t])).values()]);
1939
- if (noteTags.length) await tagLinks.putMany(noteTags);
1940
- await putChanged(tx.readwrite("page"), pages, pages.map((p) => p.id));
1941
- await putChanged(pageLinks, pageNotes, pageNotes.map((p) => p.id));
1942
- await metaStore.put(write.meta);
1943
- return result;
1944
- });
1964
+ }
1965
+ };
1966
+ if (write.chunkId === EFFORTS_CHUNK_ID) {
1967
+ result.totalEfforts = await applyDefinitionChunk(tx.readwrite("efforts"), noteStore, wodWikiLang.parseEffortFile, "efforts", seedSource, incomingRank, otherCheckpoints, priorIds, write.rows, ids, owned, existingById, allIds);
1968
+ await recordSeedPropertyOverrides("effort", wodWikiLang.parseEffortFile);
1969
+ }
1970
+ if (write.chunkId === EQUIPMENT_CHUNK_ID) {
1971
+ result.totalEquipment = await applyDefinitionChunk(tx.readwrite("equipment"), noteStore, wodWikiLang.parseEquipmentFile, "equipment", seedSource, incomingRank, otherCheckpoints, priorIds, write.rows, ids, owned, existingById, allIds);
1972
+ await recordSeedPropertyOverrides("equipment", wodWikiLang.parseEquipmentFile);
1973
+ }
1974
+ if (changedNotes.length) await noteStore.putMany(changedNotes);
1975
+ if (revisions.length) await revisionStore.putMany(revisions);
1976
+ await putChanged(indexStore, blocks, blocks.map((b) => b.id));
1977
+ await putChanged(effortLinks, blockEfforts, blockEfforts.map((b) => b.id));
1978
+ await putChanged(equipmentLinks, blockEquipment, blockEquipment.map((b) => b.id));
1979
+ await putChanged(sessionStore, sessions, sessions.map((session) => session.id));
1980
+ await putChanged(eventStore, events, events.map((event) => event.id));
1981
+ if (changedTags.length) await tagsStore.putMany([...new Map(changedTags.map((t) => [t.id, t])).values()]);
1982
+ if (noteTags.length) await tagLinks.putMany(noteTags);
1983
+ await putChanged(tx.readwrite("page"), pages, pages.map((p) => p.id));
1984
+ await putChanged(pageLinks, pageNotes, pageNotes.map((p) => p.id));
1985
+ await metaStore.put(write.meta);
1986
+ return result;
1945
1987
  }
1946
1988
  function owningFeed(claims, note) {
1947
1989
  const byChunk = note.seedChunkId ? claims.filter((claim) => claim.chunkId === note.seedChunkId) : [];
@@ -5694,6 +5736,7 @@ exports.SESSION_CSV_HEADER = SESSION_CSV_HEADER;
5694
5736
  exports.TELEMETRY_CSV_HEADER = TELEMETRY_CSV_HEADER;
5695
5737
  exports.VERSION = VERSION;
5696
5738
  exports.applySeedChunk = applySeedChunk;
5739
+ exports.applySeedChunks = applySeedChunks;
5697
5740
  exports.assertNotebookIndex = assertNotebookIndex;
5698
5741
  exports.assertSeedManifest = assertSeedManifest;
5699
5742
  exports.assertSeedRow = assertSeedRow;