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