@bendyline/squisq 2.0.1 → 2.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/NOTICE.md +24 -0
- package/dist/{ContentContainer-BXUlIf18.d.ts → ContentContainer-B2w9sUoL.d.ts} +15 -0
- package/dist/{Doc-ylqWKDc_.d.ts → Doc-BubIpWsp.d.ts} +160 -3
- package/dist/{ImageEditDoc-D828IXJ1.d.ts → ImageEditDoc-CGxk5CHc.d.ts} +1 -1
- package/dist/{annotationCoercion-Dr_DY9Hx.d.ts → annotationCoercion-PtRQhk5V.d.ts} +1 -1
- package/dist/chunk-2L55443L.js +0 -0
- package/dist/chunk-2ZWIXGAC.js +214 -0
- package/dist/{chunk-2PWOO4ZE.js → chunk-32R2RZAO.js} +72 -3
- package/dist/chunk-3IGPAPQ7.js +645 -0
- package/dist/{chunk-QE7TWGVT.js → chunk-4VOD55SX.js} +0 -1
- package/dist/{chunk-3E5F2XMR.js → chunk-67L6WRJN.js} +0 -1
- package/dist/{chunk-5DKBFXPY.js → chunk-6ECMNUIP.js} +26 -18
- package/dist/{chunk-X6DUONGT.js → chunk-7ARJZYQY.js} +280 -128
- package/dist/{chunk-DBS6RIFL.js → chunk-7N4G32LG.js} +0 -1
- package/dist/{chunk-JOQYPRDZ.js → chunk-7YEZFHLS.js} +10 -8
- package/dist/{chunk-2UQOHYE2.js → chunk-7ZAAICW4.js} +0 -1
- package/dist/{chunk-66QO7XFB.js → chunk-ACZOVWX3.js} +117 -7
- package/dist/{chunk-5J4HKRJF.js → chunk-BAOV476U.js} +0 -1
- package/dist/chunk-BCCXTMN5.js +699 -0
- package/dist/{chunk-W4O2TX5I.js → chunk-C33GTPUZ.js} +579 -4
- package/dist/{chunk-MMPBOUK7.js → chunk-CB45YGAM.js} +7 -2
- package/dist/{chunk-CY2R2VPR.js → chunk-DYPMOPIW.js} +18 -2
- package/dist/{chunk-VR7UPJ7C.js → chunk-FCG3BIZN.js} +12 -1
- package/dist/{chunk-5UYI3RJB.js → chunk-FDYDYL77.js} +54 -40
- package/dist/{chunk-TFJVXUHH.js → chunk-I2O6W7DX.js} +1513 -79
- package/dist/{chunk-Q7LROV2H.js → chunk-NKNMGIIN.js} +0 -1
- package/dist/chunk-OPO5K4DZ.js +241 -0
- package/dist/{chunk-TUWMK62B.js → chunk-PUS54YU6.js} +45 -2
- package/dist/chunk-QKPXHDLR.js +0 -0
- package/dist/{chunk-GZY66SDN.js → chunk-R3KTTOMS.js} +0 -1
- package/dist/{chunk-PXLVXTLW.js → chunk-RS5AP3J4.js} +72 -15
- package/dist/chunk-WV5ARNDA.js +0 -0
- package/dist/{chunk-4X3JQXNM.js → chunk-XOFT65EX.js} +1 -2
- package/dist/{chunk-FVTQSNR7.js → chunk-XRW6P7IF.js} +13 -5
- package/dist/chunk-XWNNA3KE.js +0 -0
- package/dist/chunk-YZNGMV3G.js +0 -0
- package/dist/{chunk-R2YZTCLO.js → chunk-ZQKZSJAX.js} +1 -2
- package/dist/doc/index.d.ts +166 -12
- package/dist/doc/index.js +36 -17
- package/dist/generate/index.d.ts +2 -2
- package/dist/generate/index.js +2 -3
- package/dist/icons/index.js +3 -4
- package/dist/icons/inlineIconMarker.js +1 -2
- package/dist/imageEdit/index.d.ts +48 -17
- package/dist/imageEdit/index.js +3 -4
- package/dist/index.d.ts +13 -12
- package/dist/index.js +118 -33
- package/dist/jsonForm/index.d.ts +10 -3
- package/dist/jsonForm/index.js +8 -7
- package/dist/markdown/index.d.ts +75 -11
- package/dist/markdown/index.js +32 -7
- package/dist/materializePageSection-wSLA2A1g.d.ts +223 -0
- package/dist/narration/index.d.ts +16 -3
- package/dist/narration/index.js +13 -14
- package/dist/random/index.d.ts +11 -2
- package/dist/random/index.js +2 -3
- package/dist/recommend/index.d.ts +1 -1
- package/dist/recommend/index.js +3 -4
- package/dist/schemas/index.d.ts +31 -6
- package/dist/schemas/index.js +43 -6
- package/dist/spatial/index.d.ts +2 -1
- package/dist/spatial/index.js +1 -2
- package/dist/storage/index.d.ts +4 -2
- package/dist/storage/index.js +1 -2
- package/dist/{themeLibrary-RjVgLpUi.d.ts → themeLibrary-DU9mUmVl.d.ts} +1 -1
- package/dist/timing/index.js +3 -4
- package/dist/transform/index.d.ts +9 -10
- package/dist/transform/index.js +6 -7
- package/dist/{types-C4kiRn_k.d.ts → types-8QjefM9J.d.ts} +38 -2
- package/dist/{types-BwMPl2CB.d.ts → types-CUNc9biN.d.ts} +24 -1
- package/dist/versions/index.d.ts +14 -11
- package/dist/versions/index.js +2 -3
- package/package.json +4 -2
- package/dist/chunk-2PWOO4ZE.js.map +0 -1
- package/dist/chunk-2UQOHYE2.js.map +0 -1
- package/dist/chunk-3E5F2XMR.js.map +0 -1
- package/dist/chunk-4X3JQXNM.js.map +0 -1
- package/dist/chunk-5DKBFXPY.js.map +0 -1
- package/dist/chunk-5J4HKRJF.js.map +0 -1
- package/dist/chunk-5UYI3RJB.js.map +0 -1
- package/dist/chunk-66QO7XFB.js.map +0 -1
- package/dist/chunk-AMIR72JP.js +0 -380
- package/dist/chunk-AMIR72JP.js.map +0 -1
- package/dist/chunk-CY2R2VPR.js.map +0 -1
- package/dist/chunk-DBS6RIFL.js.map +0 -1
- package/dist/chunk-DNJKBAI7.js +0 -1
- package/dist/chunk-DNJKBAI7.js.map +0 -1
- package/dist/chunk-ET53IIEP.js +0 -1
- package/dist/chunk-ET53IIEP.js.map +0 -1
- package/dist/chunk-FVJUUTEM.js +0 -74
- package/dist/chunk-FVJUUTEM.js.map +0 -1
- package/dist/chunk-FVTQSNR7.js.map +0 -1
- package/dist/chunk-GZY66SDN.js.map +0 -1
- package/dist/chunk-JOQYPRDZ.js.map +0 -1
- package/dist/chunk-MMPBOUK7.js.map +0 -1
- package/dist/chunk-PGGGKYWG.js +0 -1
- package/dist/chunk-PGGGKYWG.js.map +0 -1
- package/dist/chunk-PXLVXTLW.js.map +0 -1
- package/dist/chunk-Q7LROV2H.js.map +0 -1
- package/dist/chunk-QE7TWGVT.js.map +0 -1
- package/dist/chunk-R2GC6RLD.js +0 -344
- package/dist/chunk-R2GC6RLD.js.map +0 -1
- package/dist/chunk-R2YZTCLO.js.map +0 -1
- package/dist/chunk-S7A5D7ZJ.js +0 -174
- package/dist/chunk-S7A5D7ZJ.js.map +0 -1
- package/dist/chunk-TFJVXUHH.js.map +0 -1
- package/dist/chunk-TUWMK62B.js.map +0 -1
- package/dist/chunk-V543AI2F.js +0 -1
- package/dist/chunk-V543AI2F.js.map +0 -1
- package/dist/chunk-VR7UPJ7C.js.map +0 -1
- package/dist/chunk-W4O2TX5I.js.map +0 -1
- package/dist/chunk-X6DUONGT.js.map +0 -1
- package/dist/chunk-ZLQKNOZQ.js +0 -1
- package/dist/chunk-ZLQKNOZQ.js.map +0 -1
- package/dist/doc/index.js.map +0 -1
- package/dist/generate/index.js.map +0 -1
- package/dist/icons/index.js.map +0 -1
- package/dist/icons/inlineIconMarker.js.map +0 -1
- package/dist/imageEdit/index.js.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/jsonForm/index.js.map +0 -1
- package/dist/markdown/index.js.map +0 -1
- package/dist/narration/index.js.map +0 -1
- package/dist/random/index.js.map +0 -1
- package/dist/recommend/index.js.map +0 -1
- package/dist/schemas/index.js.map +0 -1
- package/dist/spatial/index.js.map +0 -1
- package/dist/storage/index.js.map +0 -1
- package/dist/timing/index.js.map +0 -1
- package/dist/transform/index.js.map +0 -1
- package/dist/versions/index.js.map +0 -1
- package/src/__tests__/animationUtils.test.ts +0 -117
- package/src/__tests__/annotationCoercion.test.ts +0 -243
- package/src/__tests__/applyNarrationTiming.test.ts +0 -190
- package/src/__tests__/applyRenderStyle.test.ts +0 -146
- package/src/__tests__/asciiDiagramBattle.test.ts +0 -246
- package/src/__tests__/asciiDiagramDetect.test.ts +0 -162
- package/src/__tests__/asciiDiagramMapping.test.ts +0 -38
- package/src/__tests__/asciiDiagramParse.test.ts +0 -233
- package/src/__tests__/asciiDiagramPipeline.test.ts +0 -273
- package/src/__tests__/asciiDiagramRender.test.ts +0 -162
- package/src/__tests__/asciiDiagramRepair.test.ts +0 -84
- package/src/__tests__/asciiTimelineDetect.test.ts +0 -157
- package/src/__tests__/asciiTimelineParse.test.ts +0 -205
- package/src/__tests__/asciiTimelinePipeline.test.ts +0 -349
- package/src/__tests__/asciiTimelineRender.test.ts +0 -376
- package/src/__tests__/atmosphereLayers.test.ts +0 -108
- package/src/__tests__/attrTokens.test.ts +0 -167
- package/src/__tests__/colorUtils.test.ts +0 -112
- package/src/__tests__/contentContainer.test.ts +0 -325
- package/src/__tests__/contentExtractor.test.ts +0 -243
- package/src/__tests__/coverBlock.test.ts +0 -310
- package/src/__tests__/customTemplateSample.test.ts +0 -144
- package/src/__tests__/customTemplatesFrontmatter.test.ts +0 -221
- package/src/__tests__/customThemesFrontmatter.test.ts +0 -146
- package/src/__tests__/dataTable.test.ts +0 -145
- package/src/__tests__/diagramBlock.test.ts +0 -122
- package/src/__tests__/diagramLayout.test.ts +0 -134
- package/src/__tests__/diagramText.test.ts +0 -26
- package/src/__tests__/docToMarkdownMedia.test.ts +0 -83
- package/src/__tests__/drawing.test.ts +0 -109
- package/src/__tests__/drawingBlock.test.ts +0 -124
- package/src/__tests__/drawingLayout.test.ts +0 -171
- package/src/__tests__/fixtures/asciiDiagramBattle.ts +0 -512
- package/src/__tests__/fixtures/asciiDiagrams.ts +0 -287
- package/src/__tests__/fixtures/asciiTimelines.ts +0 -35
- package/src/__tests__/fixtures/treeviewFixtures.ts +0 -243
- package/src/__tests__/geohash.test.ts +0 -110
- package/src/__tests__/getLayers.test.ts +0 -243
- package/src/__tests__/getLayersFallback.test.ts +0 -103
- package/src/__tests__/haversine.test.ts +0 -63
- package/src/__tests__/iconResolve.test.ts +0 -122
- package/src/__tests__/imageEditExportSvg.test.ts +0 -70
- package/src/__tests__/imageEditState.test.ts +0 -74
- package/src/__tests__/imageEditVersions.test.ts +0 -243
- package/src/__tests__/inferDocumentTitle.test.ts +0 -50
- package/src/__tests__/inlineIconMarker.test.ts +0 -36
- package/src/__tests__/inputDescriptors.test.ts +0 -162
- package/src/__tests__/jsonForm.chooseControl.test.ts +0 -86
- package/src/__tests__/jsonForm.evaluateWhen.test.ts +0 -59
- package/src/__tests__/jsonForm.inferSchema.test.ts +0 -25
- package/src/__tests__/jsonForm.pointer.test.ts +0 -149
- package/src/__tests__/jsonForm.tokens.test.ts +0 -84
- package/src/__tests__/layoutBlock.test.ts +0 -83
- package/src/__tests__/layoutLayout.test.ts +0 -169
- package/src/__tests__/localForageAdapter.test.ts +0 -155
- package/src/__tests__/majorApiTypes.test.ts +0 -18
- package/src/__tests__/markdown.test.ts +0 -1009
- package/src/__tests__/markdownIcons.test.ts +0 -104
- package/src/__tests__/markdownSanitize.test.ts +0 -81
- package/src/__tests__/markdownToDoc.test.ts +0 -957
- package/src/__tests__/matchFontFamily.test.ts +0 -114
- package/src/__tests__/materializeBlockLayers.test.ts +0 -135
- package/src/__tests__/materializeTestUtils.ts +0 -17
- package/src/__tests__/mediaAnnotations.test.ts +0 -91
- package/src/__tests__/mediaSchedule.test.ts +0 -118
- package/src/__tests__/narrationAlign.test.ts +0 -150
- package/src/__tests__/narrationFeatures.test.ts +0 -71
- package/src/__tests__/narrationNuclei.test.ts +0 -45
- package/src/__tests__/narrationPacing.test.ts +0 -189
- package/src/__tests__/narrationScript.test.ts +0 -149
- package/src/__tests__/narrationSessionRepro.test.ts +0 -62
- package/src/__tests__/narrationSidecar.test.ts +0 -88
- package/src/__tests__/narrationSyllables.test.ts +0 -65
- package/src/__tests__/narrationTestSignals.ts +0 -167
- package/src/__tests__/narrationVad.test.ts +0 -66
- package/src/__tests__/pandocAttrParse.test.ts +0 -187
- package/src/__tests__/recommendTemplates.test.ts +0 -183
- package/src/__tests__/resolveDocTheme.test.ts +0 -69
- package/src/__tests__/rootExports.test.ts +0 -61
- package/src/__tests__/scopedContentContainer.test.ts +0 -109
- package/src/__tests__/seededRandom.test.ts +0 -142
- package/src/__tests__/shapeGeometry.test.ts +0 -138
- package/src/__tests__/shapeVocabulary.test.ts +0 -133
- package/src/__tests__/storage.test.ts +0 -60
- package/src/__tests__/structuredData.test.ts +0 -249
- package/src/__tests__/surface.test.ts +0 -68
- package/src/__tests__/templateAnnotationParse.test.ts +0 -160
- package/src/__tests__/templateInputs.test.ts +0 -69
- package/src/__tests__/templateMetadata.test.ts +0 -32
- package/src/__tests__/templates.test.ts +0 -710
- package/src/__tests__/themeCompile.test.ts +0 -225
- package/src/__tests__/themeValidator.test.ts +0 -131
- package/src/__tests__/timing.test.ts +0 -167
- package/src/__tests__/transformProvenance.test.ts +0 -160
- package/src/__tests__/transformV2.test.ts +0 -163
- package/src/__tests__/transitionNormalize.test.ts +0 -61
- package/src/__tests__/treeviewBattle.test.ts +0 -76
- package/src/__tests__/treeviewDetect.test.ts +0 -168
- package/src/__tests__/treeviewParse.test.ts +0 -118
- package/src/__tests__/treeviewPipeline.test.ts +0 -183
- package/src/__tests__/treeviewRender.test.ts +0 -91
- package/src/__tests__/validateDoc.test.ts +0 -260
- package/src/__tests__/versions.test.ts +0 -459
- package/src/doc/annotationBlocks.ts +0 -117
- package/src/doc/applyNarrationTiming.ts +0 -244
- package/src/doc/asciiDiagram/chars.ts +0 -210
- package/src/doc/asciiDiagram/detect.ts +0 -175
- package/src/doc/asciiDiagram/index.ts +0 -38
- package/src/doc/asciiDiagram/mapping.ts +0 -225
- package/src/doc/asciiDiagram/parse.ts +0 -1095
- package/src/doc/asciiDiagram/render.ts +0 -963
- package/src/doc/asciiDiagram/repair.ts +0 -400
- package/src/doc/asciiDiagram/types.ts +0 -65
- package/src/doc/asciiTimeline/detect.ts +0 -138
- package/src/doc/asciiTimeline/index.ts +0 -26
- package/src/doc/asciiTimeline/mapping.ts +0 -43
- package/src/doc/asciiTimeline/parse.ts +0 -870
- package/src/doc/asciiTimeline/render.ts +0 -427
- package/src/doc/asciiTimeline/types.ts +0 -73
- package/src/doc/asciiTimeline/wrappedFlow.ts +0 -427
- package/src/doc/audioMapping.ts +0 -442
- package/src/doc/customTemplatesFrontmatter.ts +0 -273
- package/src/doc/customThemesFrontmatter.ts +0 -95
- package/src/doc/docToMarkdown.ts +0 -284
- package/src/doc/index.ts +0 -127
- package/src/doc/markdownToDoc.ts +0 -1054
- package/src/doc/materializeBlockLayers.ts +0 -304
- package/src/doc/mediaAnnotations.ts +0 -120
- package/src/doc/resolveDocTheme.ts +0 -56
- package/src/doc/standaloneAnnotation.ts +0 -58
- package/src/doc/structuredData.ts +0 -301
- package/src/doc/templateInputs.ts +0 -423
- package/src/doc/templates/__tests__/customTemplate.test.ts +0 -170
- package/src/doc/templates/__tests__/customTemplateRegistry.test.ts +0 -124
- package/src/doc/templates/__tests__/listBlock.test.ts +0 -64
- package/src/doc/templates/accentImage.ts +0 -362
- package/src/doc/templates/captionUtils.ts +0 -56
- package/src/doc/templates/comparisonBar.ts +0 -173
- package/src/doc/templates/coverBlock.ts +0 -255
- package/src/doc/templates/customTemplate.ts +0 -51
- package/src/doc/templates/dataTable.ts +0 -102
- package/src/doc/templates/dateEvent.ts +0 -147
- package/src/doc/templates/definitionCard.ts +0 -140
- package/src/doc/templates/diagramBlock.ts +0 -403
- package/src/doc/templates/diagramLayout.ts +0 -159
- package/src/doc/templates/drawingBlock.ts +0 -325
- package/src/doc/templates/drawingLayout.ts +0 -539
- package/src/doc/templates/factCard.ts +0 -146
- package/src/doc/templates/fallbackBlock.ts +0 -123
- package/src/doc/templates/featureBlock.ts +0 -209
- package/src/doc/templates/fullBleedQuote.ts +0 -83
- package/src/doc/templates/imageWithCaption.ts +0 -186
- package/src/doc/templates/index.ts +0 -642
- package/src/doc/templates/inputDescriptors.ts +0 -451
- package/src/doc/templates/layoutBlock.ts +0 -43
- package/src/doc/templates/layoutLayout.ts +0 -243
- package/src/doc/templates/listBlock.ts +0 -207
- package/src/doc/templates/mapBlock.ts +0 -138
- package/src/doc/templates/metadata.ts +0 -130
- package/src/doc/templates/persistentLayers.ts +0 -526
- package/src/doc/templates/photoGrid.ts +0 -190
- package/src/doc/templates/pullQuote.ts +0 -141
- package/src/doc/templates/quoteBlock.ts +0 -141
- package/src/doc/templates/registry.ts +0 -88
- package/src/doc/templates/sectionHeader.ts +0 -120
- package/src/doc/templates/statHighlight.ts +0 -146
- package/src/doc/templates/templateNames.ts +0 -22
- package/src/doc/templates/timelineBlock.ts +0 -613
- package/src/doc/templates/titleBlock.ts +0 -150
- package/src/doc/templates/tokens/__tests__/resolveTokens.test.ts +0 -487
- package/src/doc/templates/tokens/resolveTokens.ts +0 -453
- package/src/doc/templates/treeBlock.ts +0 -131
- package/src/doc/templates/twoColumn.ts +0 -263
- package/src/doc/templates/videoPullQuote.ts +0 -142
- package/src/doc/templates/videoWithCaption.ts +0 -135
- package/src/doc/treeview/chars.ts +0 -72
- package/src/doc/treeview/detect.ts +0 -145
- package/src/doc/treeview/index.ts +0 -30
- package/src/doc/treeview/mapping.ts +0 -95
- package/src/doc/treeview/parse.ts +0 -201
- package/src/doc/treeview/render.ts +0 -41
- package/src/doc/treeview/types.ts +0 -43
- package/src/doc/utils/animationUtils.ts +0 -399
- package/src/doc/utils/applyRenderStyle.ts +0 -106
- package/src/doc/utils/diagramText.ts +0 -78
- package/src/doc/utils/imageTreatment.ts +0 -70
- package/src/doc/utils/nearest.ts +0 -59
- package/src/doc/utils/shapeGeometry.ts +0 -614
- package/src/doc/utils/themeUtils.ts +0 -243
- package/src/doc/validate.ts +0 -575
- package/src/generate/contentExtractor.ts +0 -921
- package/src/generate/index.ts +0 -18
- package/src/generate/templateMapper.ts +0 -177
- package/src/icons/iconData.ts +0 -31
- package/src/icons/index.ts +0 -26
- package/src/icons/inlineIconMarker.ts +0 -73
- package/src/icons/resolve.ts +0 -139
- package/src/imageEdit/ImageEditVersionManager.ts +0 -73
- package/src/imageEdit/export.ts +0 -410
- package/src/imageEdit/index.ts +0 -72
- package/src/imageEdit/persistence.ts +0 -113
- package/src/imageEdit/state.ts +0 -112
- package/src/imageEdit/versionPaths.ts +0 -44
- package/src/imageEdit/versions.ts +0 -152
- package/src/index.ts +0 -15
- package/src/internal/immutable.ts +0 -58
- package/src/jsonForm/chooseControl.ts +0 -88
- package/src/jsonForm/evaluateWhen.ts +0 -59
- package/src/jsonForm/index.ts +0 -32
- package/src/jsonForm/inferSchema.ts +0 -25
- package/src/jsonForm/pointer.ts +0 -154
- package/src/jsonForm/tokens.ts +0 -78
- package/src/jsonForm/types.ts +0 -167
- package/src/markdown/annotationCoercion.ts +0 -295
- package/src/markdown/attrTokens.ts +0 -243
- package/src/markdown/convert.ts +0 -1353
- package/src/markdown/htmlParse.ts +0 -212
- package/src/markdown/index.ts +0 -152
- package/src/markdown/parse.ts +0 -103
- package/src/markdown/sanitize.ts +0 -318
- package/src/markdown/stringify.ts +0 -207
- package/src/markdown/types.ts +0 -710
- package/src/markdown/utils.ts +0 -459
- package/src/narration/align.ts +0 -514
- package/src/narration/features.ts +0 -231
- package/src/narration/index.ts +0 -86
- package/src/narration/nuclei.ts +0 -118
- package/src/narration/pacing.ts +0 -211
- package/src/narration/script.ts +0 -239
- package/src/narration/session.ts +0 -100
- package/src/narration/sidecar.ts +0 -187
- package/src/narration/syllables.ts +0 -85
- package/src/narration/trace.ts +0 -50
- package/src/narration/types.ts +0 -299
- package/src/narration/vad.ts +0 -131
- package/src/ngeohash.d.ts +0 -11
- package/src/random/SeededRandom.ts +0 -127
- package/src/random/index.ts +0 -1
- package/src/recommend/index.ts +0 -16
- package/src/recommend/numberHighlight.ts +0 -25
- package/src/recommend/templates.ts +0 -393
- package/src/schemas/BlockTemplates.ts +0 -1046
- package/src/schemas/CustomTemplates.ts +0 -126
- package/src/schemas/Doc.ts +0 -1052
- package/src/schemas/ImageEditDoc.ts +0 -102
- package/src/schemas/LayoutStrategy.ts +0 -178
- package/src/schemas/Media.ts +0 -179
- package/src/schemas/MediaProvider.ts +0 -70
- package/src/schemas/Theme.ts +0 -406
- package/src/schemas/Transitions.ts +0 -224
- package/src/schemas/Types.ts +0 -15
- package/src/schemas/Viewport.ts +0 -91
- package/src/schemas/colorUtils.ts +0 -219
- package/src/schemas/fontStacks.ts +0 -339
- package/src/schemas/index.ts +0 -29
- package/src/schemas/themeCompile.ts +0 -237
- package/src/schemas/themeConstants.ts +0 -2
- package/src/schemas/themeLibrary.ts +0 -60
- package/src/schemas/themeValidator.ts +0 -426
- package/src/schemas/themes/bold.json +0 -48
- package/src/schemas/themes/cinematic.json +0 -111
- package/src/schemas/themes/documentary.json +0 -96
- package/src/schemas/themes/gezellig.json +0 -93
- package/src/schemas/themes/index.ts +0 -53
- package/src/schemas/themes/magazine.json +0 -89
- package/src/schemas/themes/minimalist.json +0 -45
- package/src/schemas/themes/morning-light.json +0 -85
- package/src/schemas/themes/standard-dark.json +0 -85
- package/src/schemas/themes/standard.json +0 -74
- package/src/schemas/themes/tech-dark.json +0 -101
- package/src/schemas/themes/warm-earth.json +0 -50
- package/src/spatial/Geohash.ts +0 -196
- package/src/spatial/Haversine.ts +0 -59
- package/src/spatial/index.ts +0 -2
- package/src/storage/ContentContainer.ts +0 -220
- package/src/storage/LocalForageAdapter.ts +0 -103
- package/src/storage/LocalStorageAdapter.ts +0 -57
- package/src/storage/MediaProviderFromContainer.ts +0 -92
- package/src/storage/MemoryStorageAdapter.ts +0 -37
- package/src/storage/ScopedContentContainer.ts +0 -143
- package/src/storage/Storage.ts +0 -28
- package/src/storage/index.ts +0 -9
- package/src/timing/index.ts +0 -17
- package/src/timing/narrationTiming.ts +0 -220
- package/src/timing/readingTime.ts +0 -94
- package/src/transform/applyTransform.ts +0 -122
- package/src/transform/blockAnalyzer.ts +0 -181
- package/src/transform/index.ts +0 -23
- package/src/transform/registry.ts +0 -198
- package/src/transform/styles/dataDriven.ts +0 -17
- package/src/transform/styles/documentary.ts +0 -17
- package/src/transform/styles/index.ts +0 -5
- package/src/transform/styles/magazine.ts +0 -18
- package/src/transform/styles/minimal.ts +0 -17
- package/src/transform/styles/narrative.ts +0 -18
- package/src/transform/templateSelector.ts +0 -389
- package/src/transform/timingAllocator.ts +0 -257
- package/src/transform/types.ts +0 -151
- package/src/versions/DocumentVersionManager.ts +0 -70
- package/src/versions/gitignore.ts +0 -34
- package/src/versions/index.ts +0 -56
- package/src/versions/operations.ts +0 -144
- package/src/versions/paths.ts +0 -51
- package/src/versions/snapshotStore.ts +0 -202
- package/src/versions/timestamp.ts +0 -48
- package/src/versions/types.ts +0 -93
package/dist/chunk-DNJKBAI7.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
//# sourceMappingURL=chunk-DNJKBAI7.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
package/dist/chunk-ET53IIEP.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
//# sourceMappingURL=chunk-ET53IIEP.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
package/dist/chunk-FVJUUTEM.js
DELETED
|
@@ -1,74 +0,0 @@
|
|
|
1
|
-
// src/schemas/Media.ts
|
|
2
|
-
function flatten(blocks, out = []) {
|
|
3
|
-
for (const b of blocks) {
|
|
4
|
-
out.push(b);
|
|
5
|
-
if (b.children && b.children.length > 0) flatten(b.children, out);
|
|
6
|
-
}
|
|
7
|
-
return out;
|
|
8
|
-
}
|
|
9
|
-
function clipLength(clip) {
|
|
10
|
-
if (clip.clipEnd == null) return null;
|
|
11
|
-
return Math.max(0, clip.clipEnd - (clip.clipStart ?? 0));
|
|
12
|
-
}
|
|
13
|
-
function baseTimelineEnd(doc) {
|
|
14
|
-
const blockEnd = flatten(doc.blocks).reduce(
|
|
15
|
-
(max, b) => Math.max(max, b.startTime + b.duration),
|
|
16
|
-
0
|
|
17
|
-
);
|
|
18
|
-
return Math.max(doc.duration ?? 0, blockEnd);
|
|
19
|
-
}
|
|
20
|
-
function resolveMediaSchedule(doc) {
|
|
21
|
-
const out = [];
|
|
22
|
-
const docEnd = baseTimelineEnd(doc);
|
|
23
|
-
for (const block of flatten(doc.blocks)) {
|
|
24
|
-
const blockEnd = block.startTime + block.duration;
|
|
25
|
-
for (const clip of block.media ?? []) {
|
|
26
|
-
const start = block.startTime + clip.startAt;
|
|
27
|
-
const len = clipLength(clip);
|
|
28
|
-
let end;
|
|
29
|
-
if (clip.spillover) {
|
|
30
|
-
end = len != null ? start + len : blockEnd;
|
|
31
|
-
} else {
|
|
32
|
-
end = len != null ? Math.min(start + len, blockEnd) : blockEnd;
|
|
33
|
-
}
|
|
34
|
-
out.push({
|
|
35
|
-
id: clip.id,
|
|
36
|
-
src: clip.src,
|
|
37
|
-
kind: clip.kind,
|
|
38
|
-
absoluteStart: start,
|
|
39
|
-
absoluteEnd: Math.max(start, end),
|
|
40
|
-
sourceIn: clip.clipStart ?? 0,
|
|
41
|
-
anchor: "block",
|
|
42
|
-
blockId: block.id,
|
|
43
|
-
...clip.sourceLine != null ? { sourceLine: clip.sourceLine } : {}
|
|
44
|
-
});
|
|
45
|
-
}
|
|
46
|
-
}
|
|
47
|
-
for (const clip of doc.documentMedia ?? []) {
|
|
48
|
-
const start = clip.startAt;
|
|
49
|
-
const len = clipLength(clip);
|
|
50
|
-
const end = len != null ? start + len : docEnd;
|
|
51
|
-
out.push({
|
|
52
|
-
id: clip.id,
|
|
53
|
-
src: clip.src,
|
|
54
|
-
kind: clip.kind,
|
|
55
|
-
absoluteStart: start,
|
|
56
|
-
absoluteEnd: Math.max(start, end),
|
|
57
|
-
sourceIn: clip.clipStart ?? 0,
|
|
58
|
-
anchor: "document",
|
|
59
|
-
...clip.sourceLine != null ? { sourceLine: clip.sourceLine } : {}
|
|
60
|
-
});
|
|
61
|
-
}
|
|
62
|
-
return out;
|
|
63
|
-
}
|
|
64
|
-
function getDocPlaybackDuration(doc) {
|
|
65
|
-
const base = baseTimelineEnd(doc);
|
|
66
|
-
const mediaEnd = resolveMediaSchedule(doc).reduce((max, c) => Math.max(max, c.absoluteEnd), 0);
|
|
67
|
-
return Math.max(base, mediaEnd);
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
export {
|
|
71
|
-
resolveMediaSchedule,
|
|
72
|
-
getDocPlaybackDuration
|
|
73
|
-
};
|
|
74
|
-
//# sourceMappingURL=chunk-FVJUUTEM.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/schemas/Media.ts"],"sourcesContent":["/**\n * Media-clip timing model.\n *\n * An additive layer on top of the simple sequential `Doc.audio.segments[]`\n * narration track, which remains first-class. A {@link MediaClip} is a piece\n * of audio or video whose\n * timing is expressed *relative to its parent block* (or the whole document),\n * with an optional `startAt` offset and an optional `spillover` past the\n * block's end. {@link resolveMediaSchedule} flattens these into absolute,\n * doc-timeline `ScheduledClip`s that playback and export consume.\n *\n * Authoring: a body-level `{[audio …]}` / `{[video …]}` annotation inside a\n * block becomes a `block.media` clip; the same annotation in the preamble\n * (before the first heading) with `anchor=document` becomes a\n * `doc.documentMedia` clip that spans the whole timeline.\n */\n\nimport type { Block, Doc } from './Doc.js';\n\n/**\n * A timed piece of media attached to a block (or the document).\n */\nexport interface MediaClip {\n /** Stable id (for React keys and timeline selection). */\n id: string;\n /** Source path (mp3/mp4/…), relative to the article media dir. */\n src: string;\n kind: 'audio' | 'video';\n /**\n * Seconds from the parent block's start when this clip begins. For an\n * `anchor='document'` clip, seconds from the document start. Default 0.\n */\n startAt: number;\n /** Source in-point within the file (seconds). Default 0. */\n clipStart?: number;\n /** Source out-point within the file (seconds). Default: file/block end. */\n clipEnd?: number;\n /**\n * When false (default) the clip stops at its block's end. When true it\n * keeps playing past the block boundary until the clip itself finishes.\n * Ignored for `anchor='document'` clips (they already span the timeline).\n */\n spillover?: boolean;\n /**\n * `'block'` (default) — timed relative to the parent block. `'document'` —\n * timed relative to the document start and able to span every block.\n */\n anchor: 'block' | 'document';\n /**\n * 1-based source line of the authoring annotation, when derived from\n * markdown. Enables round-tripping edits (e.g. the timeline editor rewriting\n * `startAt`) back to the exact line. Absent for programmatically built clips.\n */\n sourceLine?: number;\n /**\n * Round-trip home of the authoring annotation: the block whose contents\n * held the paragraph, its position in that block's ORIGINAL contents\n * array (before extraction), and the paragraph's exact source text.\n * `docToMarkdown` re-inserts the annotation from this — `raw` verbatim\n * when present, a re-serialized annotation otherwise. Absent for\n * programmatically built clips (those emit at the document top).\n */\n origin?: { blockId: string; index: number; raw?: string };\n}\n\n/**\n * A {@link MediaClip} resolved to absolute document-timeline coordinates.\n * Produced by {@link resolveMediaSchedule}; consumed by the playback\n * scheduler and the MP4 export.\n */\nexport interface ScheduledClip {\n id: string;\n src: string;\n kind: 'audio' | 'video';\n /** Absolute doc-timeline second the clip starts. */\n absoluteStart: number;\n /** Absolute doc-timeline second the clip ends (exclusive). */\n absoluteEnd: number;\n /** Source in-point to seek to at `absoluteStart`. */\n sourceIn: number;\n anchor: 'block' | 'document';\n /** Owning block id for block-anchored clips (for video re-homing/export). */\n blockId?: string;\n /** 1-based source line of the authoring annotation, when known. */\n sourceLine?: number;\n}\n\n/** Depth-first flatten of the block tree (local copy to avoid a doc-layer dep). */\nfunction flatten(blocks: Block[], out: Block[] = []): Block[] {\n for (const b of blocks) {\n out.push(b);\n if (b.children && b.children.length > 0) flatten(b.children, out);\n }\n return out;\n}\n\n/** Played length of a clip when known from its in/out points, else null. */\nfunction clipLength(clip: MediaClip): number | null {\n if (clip.clipEnd == null) return null;\n return Math.max(0, clip.clipEnd - (clip.clipStart ?? 0));\n}\n\n/**\n * Base playback span ignoring media — the larger of the audio-segment sum\n * and the last block's end. Document clips that don't pin a length run to\n * this point.\n */\nfunction baseTimelineEnd(doc: Doc): number {\n const blockEnd = flatten(doc.blocks).reduce(\n (max, b) => Math.max(max, b.startTime + b.duration),\n 0,\n );\n return Math.max(doc.duration ?? 0, blockEnd);\n}\n\n/**\n * Flatten every block clip and document clip into absolute-timed\n * `ScheduledClip`s. Pure — depends only on `doc`.\n */\nexport function resolveMediaSchedule(doc: Doc): ScheduledClip[] {\n const out: ScheduledClip[] = [];\n const docEnd = baseTimelineEnd(doc);\n\n for (const block of flatten(doc.blocks)) {\n const blockEnd = block.startTime + block.duration;\n for (const clip of block.media ?? []) {\n const start = block.startTime + clip.startAt;\n const len = clipLength(clip);\n let end: number;\n if (clip.spillover) {\n // Continue past the block; fall back to the block end when the\n // played length is unknown (no clipEnd authored).\n end = len != null ? start + len : blockEnd;\n } else {\n end = len != null ? Math.min(start + len, blockEnd) : blockEnd;\n }\n out.push({\n id: clip.id,\n src: clip.src,\n kind: clip.kind,\n absoluteStart: start,\n absoluteEnd: Math.max(start, end),\n sourceIn: clip.clipStart ?? 0,\n anchor: 'block',\n blockId: block.id,\n ...(clip.sourceLine != null ? { sourceLine: clip.sourceLine } : {}),\n });\n }\n }\n\n for (const clip of doc.documentMedia ?? []) {\n const start = clip.startAt;\n const len = clipLength(clip);\n const end = len != null ? start + len : docEnd;\n out.push({\n id: clip.id,\n src: clip.src,\n kind: clip.kind,\n absoluteStart: start,\n absoluteEnd: Math.max(start, end),\n sourceIn: clip.clipStart ?? 0,\n anchor: 'document',\n ...(clip.sourceLine != null ? { sourceLine: clip.sourceLine } : {}),\n });\n }\n\n return out;\n}\n\n/**\n * Total playback duration including any media that spills past the last\n * block (or audio segment). Export uses this for the frame count and the\n * player for its effective timeline length.\n */\nexport function getDocPlaybackDuration(doc: Doc): number {\n const base = baseTimelineEnd(doc);\n const mediaEnd = resolveMediaSchedule(doc).reduce((max, c) => Math.max(max, c.absoluteEnd), 0);\n return Math.max(base, mediaEnd);\n}\n"],"mappings":";AAwFA,SAAS,QAAQ,QAAiB,MAAe,CAAC,GAAY;AAC5D,aAAW,KAAK,QAAQ;AACtB,QAAI,KAAK,CAAC;AACV,QAAI,EAAE,YAAY,EAAE,SAAS,SAAS,EAAG,SAAQ,EAAE,UAAU,GAAG;AAAA,EAClE;AACA,SAAO;AACT;AAGA,SAAS,WAAW,MAAgC;AAClD,MAAI,K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ACxC,QAAI,KAAK;AAAA,MACP,IAAI,KAAK;AAAA,MACT,KAAK,KAAK;AAAA,MACV,MAAM,KAAK;AAAA,MACX,eAAe;AAAA,MACf,aAAa,KAAK,IAAI,OAAO,GAAG;AAAA,MAChC,UAAU,KAAK,aAAa;AAAA,MAC5B,QAAQ;AAAA,MACR,GAAI,KAAK,cAAc,OAAO,EAAE,YAAY,KAAK,WAAW,IAAI,CAAC;AAAA,IACnE,CAAC;AAAA,EACH;AAEA,SAAO;AACT;AAOO,SAAS,uBAAuB,KAAkB;AACvD,QAAM,OAAO,gBAAgB,GAAG;AAChC,QAAM,WAAW,qBAAqB,GAAG,EAAE,OAAO,CAAC,KAAK,MAAM,KAAK,IAAI,KAAK,EAAE,WAAW,GAAG,CAAC;AAC7F,SAAO,KAAK,IAAI,MAAM,QAAQ;AAChC;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/random/SeededRandom.ts"],"sourcesContent":["/**\n * Seeded pseudo-random number generator (Mulberry32 algorithm).\n *\n * Provides deterministic, reproducible randomness from an integer seed.\n * Useful for consistent slideshow generation, shuffling, and selection.\n *\n * ```ts\n * const rng = new SeededRandom(42);\n * rng.next(); // 0.0–1.0\n * rng.nextInt(10); // 0–9\n * rng.pick(['a', 'b']); // 'a' or 'b'\n * ```\n */\nexport class SeededRandom {\n private state: number;\n\n constructor(seed: number) {\n this.state = seed >>> 0;\n if (this.state === 0) {\n this.state = 0xdeadbeef;\n }\n }\n\n /** Random float in [0, 1). */\n next(): number {\n let t = (this.state += 0x6d2b79f5);\n t = Math.imul(t ^ (t >>> 15), t | 1);\n t ^= t + Math.imul(t ^ (t >>> 7), t | 61);\n return ((t ^ (t >>> 14)) >>> 0) / 4294967296;\n }\n\n /** Random integer in [0, max). */\n nextInt(max: number): number {\n return Math.floor(this.next() * max);\n }\n\n /** Random integer in [min, max). */\n nextIntRange(min: number, max: number): number {\n return min + Math.floor(this.next() * (max - min));\n }\n\n /** Random boolean with given probability of `true` (default 0.5). */\n nextBool(probability: number = 0.5): boolean {\n return this.next() < probability;\n }\n\n /** Pick a random element, or `undefined` if array is empty. */\n pick<T>(array: T[]): T | undefined {\n if (array.length === 0) return undefined;\n return array[this.nextInt(array.length)];\n }\n\n /** Pick a random element; throws if empty. */\n pickRequired<T>(array: T[]): T {\n if (array.length === 0) {\n throw new Error('Cannot pick from empty array');\n }\n return array[this.nextInt(array.length)];\n }\n\n /** Pick `count` unique random elements (fewer if array is smaller). */\n pickMultiple<T>(array: T[], count: number): T[] {\n if (count >= array.length) {\n return this.shuffle([...array]);\n }\n const result: T[] = [];\n const available = [...array];\n for (let i = 0; i < count && available.length > 0; i++) {\n const index = this.nextInt(available.length);\n result.push(available[index]);\n available.splice(index, 1);\n }\n return result;\n }\n\n /** Fisher-Yates shuffle **in place**. Returns the same array. */\n shuffle<T>(array: T[]): T[] {\n for (let i = array.length - 1; i > 0; i--) {\n const j = this.nextInt(i + 1);\n [array[i], array[j]] = [array[j], array[i]];\n }\n return array;\n }\n\n /** Return a **new** shuffled copy. */\n shuffled<T>(array: readonly T[]): T[] {\n return this.shuffle([...array]);\n }\n\n /** Weighted random selection. Returns `undefined` if items is empty. */\n pickWeighted<T>(items: { item: T; weight: number }[]): T | undefined {\n if (items.length === 0) return undefined;\n\n const totalWeight = items.reduce((sum, { weight }) => sum + weight, 0);\n if (totalWeight <= 0) return items[0]?.item;\n\n let random = this.next() * totalWeight;\n for (const { item, weight } of items) {\n random -= weight;\n if (random <= 0) return item;\n }\n return items[items.length - 1]?.item;\n }\n\n /** Current internal state (for debugging / serialization). */\n getState(): number {\n return this.state;\n }\n\n /** Create an independent sub-stream keyed by a modifier. */\n derive(modifier: string | number): SeededRandom {\n const hash = typeof modifier === 'string' ? hashString(modifier) : modifier >>> 0;\n return new SeededRandom(this.state ^ hash);\n }\n}\n\n/**\n * Simple string → 32-bit hash (djb2 algorithm).\n * Useful for turning a document ID into a numeric seed.\n */\nexport function hashString(str: string): number {\n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AI,GAAG,IAAI,IAAI,QAAQ,KAAK;AACnC,YAAS,QAAQ,KAAK,OAAQ,IAAI,WAAW,CAAC;AAAA,EAChD;AACA,SAAO,SAAS;AAClB;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/spatial/Haversine.ts","../src/spatial/Geohash.ts"],"sourcesContent":["/**\n * Haversine Distance Calculation\n *\n * Provides accurate distance calculation between two geographic coordinates\n * using the Haversine formula, which accounts for Earth's curvature.\n */\n\nimport type { Coordinates } from '../schemas/Types.js';\n\n/**\n * Calculate distance between two coordinates using Haversine formula.\n *\n * @param from Start coordinates\n * @param to End coordinates\n * @returns Distance in kilometers\n */\nexport function haversineDistance(from: Coordinates, to: Coordinates): number {\n const R = 6371; // Earth's radius in kilometers\n\n const dLat = toRadians(to.lat - from.lat);\n const dLng = toRadians(to.lng - from.lng);\n\n const a =\n Math.sin(dLat / 2) * Math.sin(dLat / 2) +\n Math.cos(toRadians(from.lat)) *\n Math.cos(toRadians(to.lat)) *\n Math.sin(dLng / 2) *\n Math.sin(dLng / 2);\n\n const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));\n\n return R * c;\n}\n\n/**\n * Calculate bearing from one coordinate to another.\n *\n * @param from Start coordinates\n * @param to End coordinates\n * @returns Bearing in degrees (0-360, where 0 = north, 90 = east)\n */\nexport function calculateBearing(from: Coordinates, to: Coordinates): number {\n const dLng = toRadians(to.lng - from.lng);\n const lat1 = toRadians(from.lat);\n const lat2 = toRadians(to.lat);\n\n const x = Math.sin(dLng) * Math.cos(lat2);\n const y = Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1) * Math.cos(lat2) * Math.cos(dLng);\n\n const bearing = Math.atan2(x, y);\n return ((bearing * 180) / Math.PI + 360) % 360;\n}\n\n/**\n * Convert degrees to radians.\n */\nfunction toRadians(degrees: number): number {\n return (degrees * Math.PI) / 180;\n}\n","/**\n * Geohash Utilities\n *\n * Provides geohash encoding/decoding and spatial utilities using the standard\n * ngeohash library for core operations, plus custom utilities for overlap checking\n * and distance calculation.\n *\n * Geohashes are a hierarchical spatial indexing system that divides the world\n * into a grid of cells. Each additional character narrows the area by ~1/32.\n *\n * Precision guide:\n * - 4 chars: ~39km x 19km (used for tile indexing)\n * - 5 chars: ~5km x 5km\n * - 6 chars: ~1.2km x 0.6km\n */\n\nimport ngeohash from 'ngeohash';\nimport { haversineDistance } from './Haversine.js';\n\n/**\n * Encode latitude/longitude to a geohash string.\n * Uses the standard ngeohash library.\n */\nexport function encodeGeohash(lat: number, lng: number, precision = 9): string {\n return ngeohash.encode(lat, lng, precision);\n}\n\n/**\n * Decode a geohash to latitude/longitude center with error bounds.\n * Uses the standard ngeohash library.\n */\nexport function decodeGeohash(hash: string): {\n lat: number;\n lng: number;\n latErr: number;\n lngErr: number;\n} {\n const result = ngeohash.decode(hash);\n return {\n lat: result.latitude,\n lng: result.longitude,\n latErr: result.error.latitude,\n lngErr: result.error.longitude,\n };\n}\n\n/**\n * Get the 8 neighboring geohash cells.\n * Returns up to 8 neighbors (fewer at poles or antimeridian).\n * Uses the standard ngeohash library.\n */\nexport function getNeighbors(hash: string): string[] {\n return ngeohash.neighbors(hash);\n}\n\n/**\n * Get a 3x3 grid of geohash4 cells (center + 8 neighbors).\n * Used for landing bonus expansions in Fly mode.\n *\n * @param geohash4 - Center geohash4 cell\n * @returns Array of 9 geohash4 cells (center first, then neighbors)\n *\n * @example\n * getGeohash4Neighbors('c23n')\n * // => ['c23n', 'c23p', 'c23q', 'c23j', 'c23m', 'c23k', 'c23h', 'c23e', 'c23s']\n */\nexport function getGeohash4Neighbors(geohash4: string): string[] {\n if (geohash4.length !== 4) return [];\n const neighbors = getNeighbors(geohash4);\n return [geohash4, ...neighbors];\n}\n\n/**\n * Get the prefix of a geohash at a given precision.\n * Simple helper for extracting geohash prefixes for directory organization.\n */\nexport function getGeohashPrefix(geohash: string, precision: number): string {\n return geohash.slice(0, precision);\n}\n\n/**\n * Convert a geohash prefix to a hierarchical path.\n *\n * Examples:\n * \"9mud\" -> \"9/m/u/d\"\n * \"9q8y\" -> \"9/q/8/y\"\n * \"c24k\" -> \"c/2/4/k\"\n *\n * This is used for organizing files in hierarchical directories to avoid\n * thousands of folders in a single directory, which causes filesystem\n * performance issues.\n */\nexport function geohashToHierarchicalPath(geohash4: string): string {\n if (geohash4.length !== 4) return '';\n const [c1, c2, c3, c4] = geohash4.split('');\n return `${c1}/${c2}/${c3}/${c4}`;\n}\n\n/**\n * Compute all geohash cells along the great-circle path between two geohash cells.\n * Samples points along the spherical arc from `from` to `to`, encoding each to a\n * geohash at the given precision, and returns the deduplicated list of intermediate\n * cells (excluding `from` and `to`).\n *\n * Uses spherical linear interpolation (SLERP) via 3D unit vectors, which correctly\n * handles antimeridian crossings and polar paths — both of which flat lat/lng\n * interpolation gets wrong.\n */\nexport function getGeohashPath(from: string, to: string, precision = 4): string[] {\n if (from === to) return [];\n\n const fromCenter = decodeGeohash(from);\n const toCenter = decodeGeohash(to);\n\n // Use haversine for accurate great-circle distance (step sizing)\n const distKm = haversineDistance(\n { lat: fromCenter.lat, lng: fromCenter.lng },\n { lat: toCenter.lat, lng: toCenter.lng },\n );\n\n // Step every ~15km to avoid skipping any geohash4 cell (~39x19km)\n const steps = Math.max(2, Math.ceil(distKm / 15));\n\n // Convert endpoints to unit Cartesian vectors for SLERP\n const φ1 = (fromCenter.lat * Math.PI) / 180;\n const λ1 = (fromCenter.lng * Math.PI) / 180;\n const φ2 = (toCenter.lat * Math.PI) / 180;\n const λ2 = (toCenter.lng * Math.PI) / 180;\n\n const x1 = Math.cos(φ1) * Math.cos(λ1);\n const y1 = Math.cos(φ1) * Math.sin(λ1);\n const z1 = Math.sin(φ1);\n const x2 = Math.cos(φ2) * Math.cos(λ2);\n const y2 = Math.cos(φ2) * Math.sin(λ2);\n const z2 = Math.sin(φ2);\n\n // Central angle between the two points\n const dot = Math.max(-1, Math.min(1, x1 * x2 + y1 * y2 + z1 * z2));\n const d = Math.acos(dot);\n // Near-antipodal fallback: sin(d)≈0 means the great circle is undefined.\n // Extremely unlikely for geohash path use; fall back to linear lat/lng.\n const useLinear = Math.abs(Math.sin(d)) < 1e-10;\n\n const seen = new Set<string>();\n seen.add(from);\n seen.add(to);\n\n const path: string[] = [];\n for (let i = 1; i < steps; i++) {\n const t = i / steps;\n let lat: number;\n let lng: number;\n if (useLinear) {\n lat = fromCenter.lat + t * (toCenter.lat - fromCenter.lat);\n lng = fromCenter.lng + t * (toCenter.lng - fromCenter.lng);\n } else {\n const A = Math.sin((1 - t) * d) / Math.sin(d);\n const B = Math.sin(t * d) / Math.sin(d);\n const x = A * x1 + B * x2;\n const y = A * y1 + B * y2;\n const z = A * z1 + B * z2;\n lat = (Math.atan2(z, Math.sqrt(x * x + y * y)) * 180) / Math.PI;\n lng = (Math.atan2(y, x) * 180) / Math.PI;\n }\n const hash = encodeGeohash(lat, lng, precision);\n if (!seen.has(hash)) {\n seen.add(hash);\n path.push(hash);\n }\n }\n\n return path;\n}\n\n/**\n * Check if a geohash cell overlaps with a bounding box.\n * Custom implementation (not available in ngeohash).\n */\nexport function geohashOverlapsBounds(\n hash: string,\n bounds: { north: number; south: number; east: number; west: number },\n): boolean {\n const { lat, lng, latErr, lngErr } = decodeGeohash(hash);\n\n const hashNorth = lat + latErr;\n const hashSouth = lat - latErr;\n const hashEast = lng + lngErr;\n const hashWest = lng - lngErr;\n\n return !(\n hashNorth < bounds.south ||\n hashSouth > bounds.north ||\n hashEast < bounds.west ||\n hashWest > bounds.east\n );\n}\n"],"mappings":";AAgBO,SAAS,kBAAkB,MAAmB,IAAyB;AAC5E,QAAM,IAAI;AAEV,QAAM,OAAO,UAAU,GAAG,MAAM,KAAK,GAAG;AACxC,QAAM,OAAO,UAAU,GAAG,MAAM,KAAK,GAAG;AAExC,QAAM,IACJ,KAAK,IAAI,OAAO,CAAC,IAAI,KAAK,IAAI,OAAO,CAAC,IACtC,KAAK,IAAI,UAAU,KAAK,GAAG,CAAC,IA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AO,QAClB,WAAW,OAAO;AAEtB;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/versions/paths.ts","../src/versions/operations.ts","../src/versions/DocumentVersionManager.ts"],"sourcesContent":["/**\n * Path conventions for version snapshots.\n *\n * Snapshots live at `<VERSIONS_PREFIX><basename>.<timestamp>[<-suffix>].md`.\n * The optional numeric suffix (`-2`, `-3`, ...) is appended only when two\n * snapshots collide on the same UTC second.\n */\n\nimport {\n buildSnapshotPath,\n parseSnapshotPath,\n type SnapshotPathStrategy,\n} from './snapshotStore.js';\n\n/** Subfolder (inside the ContentContainer) that holds version snapshots. */\nexport const VERSIONS_PREFIX = '.versions/';\n\n/** Internal strategy shared with the generic snapshot store. */\nexport const DOCUMENT_VERSION_PATHS: SnapshotPathStrategy = Object.freeze({\n prefix: VERSIONS_PREFIX,\n extension: 'md',\n});\n\n/**\n * Strip the directory and extension from a document path to produce the\n * basename used in version filenames. `subdir/index.md` -> `index`.\n */\nexport function getDocBasename(documentPath: string): string {\n const slash = documentPath.lastIndexOf('/');\n const file = slash >= 0 ? documentPath.slice(slash + 1) : documentPath;\n const dot = file.lastIndexOf('.');\n return dot > 0 ? file.slice(0, dot) : file;\n}\n\n/**\n * Build a version snapshot path. Optionally append a collision suffix\n * (e.g. `2`, `3`) when two saves land on the same UTC second.\n */\nexport function buildVersionPath(basename: string, date: Date, collision = 0): string {\n return buildSnapshotPath(DOCUMENT_VERSION_PATHS, basename, date, collision);\n}\n\n/**\n * Parse a version snapshot path. Returns null if it doesn't match the\n * convention (so unrelated files stored under `.versions/` are ignored).\n */\nexport function parseVersionPath(\n path: string,\n): { basename: string; timestamp: Date; collision: number } | null {\n return parseSnapshotPath(DOCUMENT_VERSION_PATHS, path);\n}\n","/**\n * Pure-ish version operations against a {@link ContentContainer}.\n *\n * These functions are the canonical implementation. {@link DocumentVersionManager}\n * is a thin wrapper that captures a container reference for ergonomics.\n */\n\nimport type { ContentContainer } from '../storage/ContentContainer.js';\nimport { DOCUMENT_VERSION_PATHS, getDocBasename } from './paths.js';\nimport {\n coalesceSnapshots,\n listSnapshots,\n pruneSnapshots,\n readTextSnapshot,\n saveTextSnapshot,\n} from './snapshotStore.js';\nimport type {\n CoalesceOptions,\n PrunePolicy,\n RevertOptions,\n SaveVersionOptions,\n SaveVersionResult,\n Version,\n} from './types.js';\n\nasync function resolveBasename(\n container: ContentContainer,\n override: string | undefined,\n): Promise<string | null> {\n if (override) return override;\n const docPath = await container.getDocumentPath();\n if (!docPath) return null;\n return getDocBasename(docPath);\n}\n\nasync function resolveDocPath(container: ContentContainer): Promise<string> {\n // Default to `index.md` when the container has no document yet — matches\n // `MemoryContentContainer.writeDocument`'s default.\n const docPath = await container.getDocumentPath();\n return docPath ?? 'index.md';\n}\n\n/**\n * List all snapshots in the container, newest-first.\n *\n * @param basename Optional filter: when set, only versions whose basename\n * matches are returned.\n */\nexport async function listVersions(\n container: ContentContainer,\n basename?: string,\n): Promise<Version[]> {\n return listSnapshots(container, DOCUMENT_VERSION_PATHS, basename);\n}\n\n/**\n * Read the markdown content of a snapshot. Returns null if the snapshot\n * doesn't exist.\n */\nexport async function readVersion(\n container: ContentContainer,\n version: Version | string,\n): Promise<string | null> {\n return readTextSnapshot(container, version);\n}\n\n/**\n * Save a new snapshot of the document if its content differs from the\n * latest existing snapshot.\n */\nexport async function saveVersion(\n container: ContentContainer,\n options: SaveVersionOptions = {},\n): Promise<SaveVersionResult> {\n const content = options.content ?? (await container.readDocument());\n if (content === null || content === undefined) {\n return { saved: false, version: null, reason: 'no-document' };\n }\n if (content.length === 0) {\n return { saved: false, version: null, reason: 'empty' };\n }\n\n const basename = await resolveBasename(container, options.basename);\n if (!basename) {\n return { saved: false, version: null, reason: 'no-document' };\n }\n\n return saveTextSnapshot(container, DOCUMENT_VERSION_PATHS, {\n content,\n basename,\n mimeType: 'text/markdown',\n now: options.now,\n force: options.force,\n });\n}\n\n/**\n * Revert the document to a prior snapshot. By default, the *current*\n * document is snapshotted first so the revert is itself recoverable.\n */\nexport async function revertToVersion(\n container: ContentContainer,\n version: Version | string,\n options: RevertOptions = {},\n): Promise<{ reverted: boolean; snapshotted: Version | null }> {\n const content = await readVersion(container, version);\n if (content === null) {\n return { reverted: false, snapshotted: null };\n }\n\n let snapshotted: Version | null = null;\n if (options.snapshotCurrent !== false) {\n const result = await saveVersion(container);\n snapshotted = result.version;\n }\n\n const docPath = await resolveDocPath(container);\n await container.writeDocument(content, docPath);\n return { reverted: true, snapshotted };\n}\n\n/**\n * Delete snapshots that don't satisfy the policy. Returns the deleted\n * versions in their original (newest-first) order.\n */\nexport async function pruneVersions(\n container: ContentContainer,\n policy: PrunePolicy,\n basename?: string,\n): Promise<Version[]> {\n return pruneSnapshots(container, DOCUMENT_VERSION_PATHS, policy, basename);\n}\n\n/**\n * Collapse adjacent snapshots that occurred close together — keeping the\n * newer one — to keep history readable across rapid edits.\n */\nexport async function coalesceVersions(\n container: ContentContainer,\n options: CoalesceOptions = {},\n basename?: string,\n): Promise<Version[]> {\n return coalesceSnapshots(container, DOCUMENT_VERSION_PATHS, options, basename);\n}\n","/**\n * Convenience wrapper around the version operations that captures a\n * {@link ContentContainer} reference and an optional basename override.\n *\n * Hosts that prefer a stable handle (e.g. to pass into a UI component)\n * use this; everything it does is also reachable as a free function.\n */\n\nimport type { ContentContainer } from '../storage/ContentContainer.js';\nimport {\n coalesceVersions,\n listVersions,\n pruneVersions,\n readVersion,\n revertToVersion,\n saveVersion,\n} from './operations.js';\nimport type {\n CoalesceOptions,\n PrunePolicy,\n RevertOptions,\n SaveVersionOptions,\n SaveVersionResult,\n Version,\n} from './types.js';\n\nexport interface DocumentVersionManagerOptions {\n /**\n * Override the document basename used in version filenames. Defaults to\n * the basename of `container.getDocumentPath()` resolved at call time.\n */\n basename?: string;\n}\n\nexport class DocumentVersionManager {\n private readonly container: ContentContainer;\n private readonly basename: string | undefined;\n\n constructor(container: ContentContainer, options: DocumentVersionManagerOptions = {}) {\n this.container = container;\n this.basename = options.basename;\n }\n\n saveVersion(options: SaveVersionOptions = {}): Promise<SaveVersionResult> {\n return saveVersion(this.container, { basename: this.basename, ...options });\n }\n\n listVersions(): Promise<Version[]> {\n return listVersions(this.container, this.basename);\n }\n\n readVersion(version: Version | string): Promise<string | null> {\n return readVersion(this.container, version);\n }\n\n revertToVersion(\n version: Version | string,\n options?: RevertOptions,\n ): Promise<{ reverted: boolean; snapshotted: Version | null }> {\n return revertToVersion(this.container, version, options);\n }\n\n pruneVersions(policy: PrunePolicy): Promise<Version[]> {\n return pruneVersions(this.container, policy, this.basename);\n }\n\n coalesceVersions(options?: CoalesceOptions): Promise<Version[]> {\n return coalesceVersions(this.container, options, this.basename);\n }\n}\n"],"mappings":";;;;;;;;;;;AAeO,IAAM,kBAAkB;AAGxB,IAAM,yBAA+C,OAAO,OAAO;AAAA,EACxE,QAAQ;AAAA,EACR,WAAW;AACb,CAAC;AAMM,SAAS,eAAe,cAA8B;AAC3D,QAAM,QAAQ,aAAa,YAAY,GAAG;AAC1C,QAAM,OAAO,SAAS,IAAI,aAAa,MAAM,QAAQ,CAAC,IAAI;AAC1D,QAAM,MAAM,KAAK,YAAY,GAAG;AAChC,SAAO,MAAM,IAAI,KAAK,MAAM,GAAG,GAAG,IAAI;AACxC;AAMO,SAAS,iBAAiB,UAAkB,MAAY,YAAY,GAAW;AACpF,SAAO,kBAAkB,wBAAwB,UAAU,MAAM,SAAS;AAC5E;AAMO,SAAS,iBACd,MACiE;AACjE,SAAO,kBAAkB,wBAAwB,IAAI;AACvD;;;ACzBA,eAAe,gBACb,WACA,UACwB;AACxB,MAAI,SAAU,QAAO;AACrB,QAAM,UAAU,MAAM,UAAU,gBAAgB;AAChD,MAAI,CAAC,QAAS,QAAO;AACrB,SAAO,eAAe,OAAO;AAC/B;AAEA,eAAe,eAAe,WAA8C;AAG1E,QAAM,UAAU,MAAM,UAAU,gBAAgB;AAChD,SAAO,WAAW;AACpB;AAQA,eAAsB,aACpB,WACA,UACoB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A2B,CAAC,GAC5B,UACoB;AACpB,SAAO,kBAAkB,WAAW,wBAAwB,SAAS,QAAQ;AAC/E;;;AC7GO,IAAM,yBAAN,MAA6B;AAAA,EAIlC,YAAY,WAA6B,UAAyC,CAAC,GAAG;AACpF,SAAK,YAAY;AACjB,SAAK,WAAW,QAAQ;AAAA,EAC1B;AAAA,EAEA,YAAY,UAA8B,CAAC,GAA+B;AACxE,WAAO,YAAY,KAAK,WAAW,EAAE,UAAU,KAAK,UAAU,GAAG,QAAQ,CAAC;AAAA,EAC5E;AAAA,EAEA,eAAmC;AACjC,WAAO,aAAa,KAAK,WAAW,KAAK,QAAQ;AAAA,EACnD;AAAA,EAEA,YAAY,SAAmD;AAC7D,WAAO,YAAY,KAAK,WAAW,OAAO;AAAA,EAC5C;AAAA,EAEA,gBACE,SACA,SAC6D;AAC7D,WAAO,gBAAgB,KAAK,WAAW,SAAS,OAAO;AAAA,EACzD;AAAA,EAEA,cAAc,QAAyC;AACrD,WAAO,cAAc,KAAK,WAAW,QAAQ,KAAK,QAAQ;AAAA,EAC5D;AAAA,EAEA,iBAAiB,SAA+C;AAC9D,WAAO,iBAAiB,KAAK,WAAW,SAAS,KAAK,QAAQ;AAAA,EAChE;AACF;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/schemas/Doc.ts","../src/schemas/themeCompile.ts"],"sourcesContent":["/**\n * Doc Schema\n *\n * Defines the JSON format for AI-scriptable visual docs that accompany\n * audio narration. A Doc describes a sequence of animated blocks\n * with text overlays, images, and transitions synchronized to audio.\n *\n * The format is designed to be:\n * 1. AI-generatable - Claude can create scripts from article content\n * 2. Browser-renderable - SVG + CSS animations (ES2015 compatible)\n * 3. Video-exportable - Frame-by-frame capture via Playwright\n *\n * Timing: Blocks are timed to match narration audio segments. Each article\n * has 3-6 MP3 files (intro + sections), and blocks are grouped by segment.\n */\n\nimport type { Transition } from './Transitions.js';\nexport type { Transition, TransitionType, TransitionDirection } from './Transitions.js';\n\n// ============================================\n// Core Types\n// ============================================\n\n/**\n * A directed connection from one block to another.\n *\n * Populated from a heading's Pandoc-style `{connectsTo=…}` attribute\n * (e.g. `## Step 1 {#step1 connectsTo=foo:flow,bar}`). Each item is\n * `target` or `target:type`. Used by diagram-style layouts that draw\n * edges between blocks.\n */\nexport interface BlockConnection {\n /** Target block id (matches another block's `id`). */\n target: string;\n /** Optional connection type/label (e.g., \"flow\", \"requires\"). */\n type?: string;\n}\n\n/**\n * Configuration for the Start/resting block shown before playback begins.\n */\nexport interface StartBlockConfig {\n /** Hero image path (relative to article media). When omitted, a theme-driven background is used. */\n heroSrc?: string;\n /** Alt text for the hero image */\n heroAlt?: string;\n /** Title to display over the hero */\n title: string;\n /** Optional subtitle */\n subtitle?: string;\n /** Ambient motion for the hero image */\n ambientMotion?: 'zoomIn' | 'zoomOut' | 'panLeft' | 'panRight';\n /** Photo credit / artist name for the hero image */\n heroCredit?: string;\n /** License identifier for the hero image */\n heroLicense?: string;\n}\n\n/**\n * A structural problem detected while converting or validating a document.\n *\n * Diagnostics ride on `Doc.diagnostics` so any consumer — the editor, the\n * CLI `validate` command, or an agent re-parsing its own output — gets the\n * same feedback without watching the console. Conversion never throws for\n * content problems; it degrades gracefully and records a diagnostic.\n */\nexport interface DocDiagnostic {\n /** `error` = the author's intent could not be honored (e.g. unparseable\n * data fence); `warning` = something looks wrong but rendering proceeds\n * with a fallback (e.g. unknown template name); `info` = nothing is\n * broken, but the author may want to know (e.g. a redundant annotation). */\n severity: 'error' | 'warning' | 'info';\n /** Stable machine-readable code (e.g. `unknown-template`, `duplicate-id`,\n * `unresolved-connection`, `data-fence-parse`, `missing-asset`). */\n code: string;\n /** Human-readable description, including a suggestion when one exists. */\n message: string;\n /** Id of the block the problem belongs to, when attributable. */\n blockId?: string;\n /** 1-based line number in the markdown source, when known. */\n line?: number;\n}\n\n/**\n * A complete visual doc for an article.\n */\nexport interface Doc {\n /** Article ID this doc belongs to */\n articleId: string;\n\n /** Total duration in seconds (sum of all audio segments) */\n duration: number;\n\n /** Ordered list of blocks */\n blocks: Block[];\n\n /** Audio track configuration */\n audio: AudioTrack;\n\n /** Caption track for closed captions (generated by postprocess-doc) */\n captions?: CaptionTrack;\n\n /**\n * Start/resting block shown before playback begins.\n * Displays hero image with title - acts as a \"poster\" for the doc.\n * The player shows this until the user starts playback.\n */\n startBlock?: StartBlockConfig;\n\n /**\n * Persistent layers rendered on every block (behind and/or on top of content).\n * Used for consistent branding overlays, background gradients, etc.\n */\n persistentLayers?: import('./BlockTemplates.js').PersistentLayerConfig;\n\n /**\n * Optional theme identifier. Resolved at render time via `resolveTheme()`.\n * When omitted, the renderer uses the default theme ('documentary').\n */\n themeId?: string;\n\n /** Optional metadata */\n meta?: {\n generatedAt?: string;\n generatedBy?: string;\n version?: number;\n };\n\n /**\n * YAML frontmatter from the source markdown.\n * Carries rendering hints like `document-render-as` and custom metadata.\n */\n frontmatter?: Record<string, unknown>;\n\n /**\n * User-defined block templates inlined into this doc.\n *\n * Populated from the markdown frontmatter key\n * `squisq-custom-templates`. The template-expansion pipeline\n * (`expandDocBlocks` in `doc/templates/index.ts`) merges these into\n * the registry before walking blocks, so a heading annotated\n * `{[myhero]}` resolves against a doc-defined template named `myhero`.\n *\n * Library templates (stored in localStorage on the editor side) are\n * NOT auto-loaded here — applying a library template to a block\n * copies its definition into this list so the doc remains\n * self-sufficient for SSR and export.\n */\n customTemplates?: import('./CustomTemplates.js').CustomTemplateDefinition[];\n\n /**\n * User-defined themes inlined into this doc.\n *\n * The theme analog of {@link Doc.customTemplates}. Populated from the\n * markdown frontmatter key `squisq-custom-themes`. Exactly one is active\n * at a time — selected by id via `squisq-theme` / {@link Doc.themeId},\n * the doc-level counterpart of a block's `{[name]}` template annotation —\n * but the payload is a list so a doc can carry a small catalog and stay\n * self-sufficient for SSR / export. `resolveThemeForDoc(doc, id)` resolves\n * against this list first (pure, doc-scoped) before built-ins, mirroring\n * how `buildRegistry` resolves custom templates.\n */\n customThemes?: import('./Theme.js').Theme[];\n\n /**\n * Structural problems found while building this doc (unknown templates,\n * unparseable data fences, duplicate ids, unresolved connections, …).\n * Populated by `markdownToDoc()`; extended by `validateMarkdownDoc()`.\n * Absent when the document is clean.\n */\n diagnostics?: DocDiagnostic[];\n\n /**\n * Document-spanning timed media (e.g. a full-length narration MP3/MP4),\n * authored as a media annotation in the preamble (before the first\n * heading) with `anchor=document`. Each clip is timed from the document\n * start and may play across every block. See `resolveMediaSchedule`.\n */\n documentMedia?: import('./Media.js').MediaClip[];\n}\n\n/**\n * A single block in the doc.\n *\n * Blocks can be flat (audio-synced timeline) or nested (markdown-driven hierarchy).\n * When derived from markdown, a block corresponds to a heading section:\n * - `sourceHeading` references the original MarkdownHeading node\n * - `contents` holds the body markdown between this heading and the next\n * - `children` holds sub-heading blocks (e.g., H2s under an H1)\n *\n * Four adjacent fields carry template information — do not confuse them:\n * - `template` — the *resolved* template id this block renders with.\n * - `templateOverrides` — raw `{[…]}` inline params (always strings).\n * - `templateData` — structured inputs from a data fence / GFM table\n * (parsed types, not strings).\n * - `sourceAnnotation.template` — the raw *requested* template name for a\n * standalone-annotation block (before alias resolution).\n * Merge order at render time: template defaults → `templateData` →\n * `templateOverrides`.\n */\nexport interface Block {\n /** Unique identifier for this block.\n * Defaults to a slug derived from the heading text. May be overridden by\n * a Pandoc-style `{#custom-id}` attribute on the heading. */\n id: string;\n\n /** When this block appears (seconds from start).\n * Overridden by a heading attribute `startTime=…` when present. */\n startTime: number;\n\n /** How long this block is visible (seconds).\n * Overridden by a heading attribute `duration=…` when present. */\n duration: number;\n\n /** Which audio segment this block belongs to (0-indexed) */\n audioSegment: number;\n\n /**\n * Transform provenance: the source block id this block was derived\n * from (see `BaseTemplateBlock.sourceBlockId`). Present on blocks a\n * transform produced; lets a persisted transformed Doc keep its typed\n * link back to the source content.\n */\n sourceBlockId?: string;\n /** All source block ids when this block summarizes several. */\n sourceBlockIds?: string[];\n /** Char offset of the extraction inside the source block's plain text. */\n sourceCharOffset?: number;\n\n /**\n * Pre-computed visual layers, rendered back-to-front.\n *\n * Optional — template-derived blocks typically omit this and compute\n * layers on demand via `materializeBlockLayers()` from `@bendyline/squisq/doc`.\n * Raw blocks (e.g., hand-crafted by AI) may provide layers directly.\n */\n layers?: Layer[];\n\n /** Entry transition from previous block */\n transition?: Transition;\n\n /** Resolved template id this block renders with (see the quartet note above). */\n template?: string;\n\n /**\n * True when `template` was chosen by content-aware auto-picking\n * (`markdownToDoc`'s `autoTemplates`) rather than authored. Ephemeral:\n * `docToMarkdown` does not materialize auto-picked templates as heading\n * annotations, keeping the markdown round-trip lossless.\n */\n autoTemplate?: boolean;\n\n /**\n * True when this block was produced from a *standalone* `{[templateName …]}`\n * annotation paragraph in another block's body (rather than from a heading).\n * Such blocks have no `sourceHeading`; `docToMarkdown` re-emits their\n * annotation as a synthesized paragraph before their `contents` so the\n * markdown round-trips. See `annotationBlocks.ts`.\n *\n * Presence-marker: only ever `true` (never `false`). Test with\n * `block.standaloneAnnotation` presence, not as a boolean toggle.\n */\n standaloneAnnotation?: true;\n\n /**\n * The annotation a standalone block was built from — the raw (un-resolved)\n * template name and its params, in author order. Round-tripped by\n * `docToMarkdown` (via `serializeAnnotation`) and read by validation as the\n * raw requested template name (symmetric with\n * `sourceHeading.templateAnnotation`). Present only when\n * `standaloneAnnotation` is true.\n */\n sourceAnnotation?: { template?: string; params?: Record<string, string> };\n\n /**\n * Display title for template rendering.\n * Extracted from the sourceHeading when the block is created by markdownToDoc().\n * Templates like sectionHeader and titleBlock read this for their title layer.\n */\n title?: string;\n\n // ── Markdown-driven hierarchy (optional) ──\n\n /**\n * Nested sub-blocks (heading hierarchy).\n * When a doc is derived from markdown, sub-headings within this\n * heading's section become child blocks. For example, H2 blocks\n * under an H1 block appear here.\n */\n children?: Block[];\n\n /**\n * Markdown body content for this block's section.\n * Contains the block-level markdown nodes (paragraphs, lists, code,\n * blockquotes, etc.) that appear between this heading and the next\n * heading or sub-heading. Empty for pure structural blocks.\n */\n contents?: import('../markdown/types.js').MarkdownBlockNode[];\n\n /**\n * Reference to the MarkdownHeading node that created this block.\n * Present when the block was derived from markdown via markdownToDoc().\n * Enables round-tripping back to markdown and provides heading depth.\n * Absent for the preamble block (content before the first heading).\n */\n sourceHeading?: import('../markdown/types.js').MarkdownHeading;\n\n /**\n * Template overrides extracted from a heading's `{[templateName key=value]}`\n * annotation. Only carries template-specific params (e.g. `colorScheme=blue`).\n * Block-level metadata lives in `x` / `y` / `connectsTo` / `metadata` and is\n * sourced from the Pandoc-style `{#id .class key=value}` attribute block instead.\n */\n templateOverrides?: Record<string, string>;\n\n /**\n * Structured template inputs sourced from the block's body content:\n * a ```json data / ```yaml data fence under the heading, or — for the\n * `dataTable` template — the first GFM table in the section. Unlike\n * `templateOverrides` (always strings), values here keep their parsed\n * types (arrays, numbers, nested objects). Merge order at render time:\n * template defaults → `templateData` → `templateOverrides`.\n */\n templateData?: Record<string, unknown>;\n\n // ── Block-level metadata from Pandoc-style `{#id .class key=value}` ──\n\n /**\n * X coordinate for diagram-style positioning (in author-defined units).\n * Sourced from a heading attribute `x=…`.\n */\n x?: number;\n\n /**\n * Y coordinate for diagram-style positioning (in author-defined units).\n * Sourced from a heading attribute `y=…`.\n */\n y?: number;\n\n /**\n * Outgoing connections to other blocks, by id. Sourced from a heading\n * attribute `connectsTo=target1,target2:type,target3`.\n */\n connectsTo?: BlockConnection[];\n\n /**\n * CSS-style class tokens from a heading's Pandoc attribute (e.g. `{.important .v2}`).\n * Parsed and stored; downstream consumers may use them for styling or filtering.\n */\n classes?: string[];\n\n /**\n * Free-form metadata for heading attribute keys outside the typed registry\n * (anything that isn't `x` / `y` / `connectsTo` / `startTime` / `duration`).\n * Values are raw strings exactly as authored.\n */\n metadata?: Record<string, string>;\n\n /**\n * Timed media clips attached to this block, authored as body-level\n * `{[audio …]}` / `{[video …]}` annotations. Each clip is timed relative\n * to this block's `startTime` (via `startAt`) and optionally spills past\n * the block's end. See `MediaClip` / `resolveMediaSchedule`.\n */\n media?: import('./Media.js').MediaClip[];\n}\n\n// ============================================\n// Layer Types\n// ============================================\n\n/**\n * A visual element within a block.\n * Layers are composited back-to-front (first layer is background).\n */\nexport type Layer =\n | ImageLayer\n | TextLayer\n | ShapeLayer\n | PathLayer\n | MapLayer\n | VideoLayer\n | TableLayer\n | TreeLayer;\n\ninterface BaseLayer {\n /** Unique identifier for this layer */\n id: string;\n\n /** Position and size */\n position: Position;\n\n /** Animation to apply */\n animation?: Animation;\n}\n\n/**\n * Photographic treatment applied to an image layer — a theme-level \"grade\"\n * so the same photo looks native in every theme. Rendered as CSS filter\n * functions, which behave identically in the browser player and headless\n * frame capture (video/still export).\n */\nexport interface ImageTreatment {\n /**\n * mono: desaturate toward archival black & white.\n * duotone: single-hue tint (hue taken from `color`).\n * warm / cool: gentle temperature grade.\n */\n type: 'none' | 'mono' | 'duotone' | 'warm' | 'cool';\n /** Blend strength 0..1. Default 0.6. */\n strength?: number;\n /** Duotone tint color (themes default this to their primary). */\n color?: string;\n}\n\n/**\n * Image layer - displays an image with optional Ken Burns effect.\n */\nexport interface ImageLayer extends BaseLayer {\n type: 'image';\n content: {\n /** Path to image file (relative to article media dir) */\n src: string;\n /** Alt text for accessibility */\n alt: string;\n /** How to fit image in bounds */\n fit?: 'cover' | 'contain' | 'fill';\n /** Photo credit / artist name */\n credit?: string;\n /** License identifier (e.g., 'CC BY-SA 4.0') */\n license?: string;\n /** Theme-derived photographic grade (see ImageTreatment). */\n treatment?: ImageTreatment;\n /** Gaussian blur radius in px (background/atmosphere imagery). */\n blur?: number;\n };\n}\n\n/**\n * Text layer - displays text with styling.\n */\nexport interface TextLayer extends BaseLayer {\n type: 'text';\n content: {\n /**\n * Plain text (supports \\n for line breaks). Source of truth for plain\n * consumers — PDF/markdown export, search, accessibility — and the SVG\n * `<text>` fallback. When `html` is set, this is its plain-text\n * projection and must be kept in sync.\n */\n text: string;\n /**\n * Optional sanitized **inline** HTML for rich formatting (bold/italic/\n * links, and — for layout textboxes — headings/lists). When present the\n * renderer draws it via `<foreignObject>` instead of SVG `<text>`. Treated\n * as untrusted and re-sanitized at render time. See `RichTextLayer` in\n * `@bendyline/squisq-react`.\n */\n html?: string;\n /** Text styling */\n style: TextStyle;\n };\n}\n\n/**\n * A two-stop linear gradient fill, shared by shape/path fills and text\n * backgrounds. When present it overrides the solid `fill` color.\n *\n * `angle` is in degrees: 0 = top→bottom, 90 = left→right, increasing\n * clockwise. Defaults to 0. Rendered as an SVG `<linearGradient>` in\n * objectBoundingBox units so it scales with the layer's box.\n */\nexport interface LinearGradient {\n from: string;\n to: string;\n angle?: number;\n}\n\n/** Border line style, mapped to an SVG stroke-dasharray by the renderer. */\nexport type BorderStyle = 'solid' | 'dashed' | 'dotted';\n\n/**\n * Shape layer - simple geometric shapes for visual accents.\n */\n/**\n * Repeating SVG pattern fill for a shape (dots, grid, diagonal lines).\n * Rendered as a native `<pattern>` def — fully vector and export-safe.\n */\nexport interface ShapePattern {\n kind: 'dots' | 'grid' | 'diagonal';\n /** Pattern ink color. */\n color: string;\n /** Tile size in px (default 24). */\n size?: number;\n /** Pattern opacity 0–1 (default 1; tint via a translucent color or this). */\n opacity?: number;\n}\n\n/**\n * Procedural filter applied to a shape. `noise` renders static film grain\n * via SVG feTurbulence — deliberately not animated so frame capture and\n * the live player agree.\n */\nexport interface ShapeFilter {\n type: 'noise';\n /** feTurbulence base frequency (default 0.8 — fine grain). */\n baseFrequency?: number;\n /** Grain opacity 0–1 (default 0.05). */\n opacity?: number;\n}\n\nexport interface ShapeLayer extends BaseLayer {\n type: 'shape';\n content: {\n /** Shape type */\n shape: 'rect' | 'circle' | 'line';\n /** Fill color (CSS color or 'none') */\n fill?: string;\n /** Fill opacity 0–1 (applies to solid and gradient fills). */\n fillOpacity?: number;\n /** Gradient fill; overrides `fill` when set. */\n gradient?: LinearGradient;\n /** Repeating pattern fill; overrides `fill`/`gradient` when set. */\n pattern?: ShapePattern;\n /** Procedural filter (film grain). */\n filter?: ShapeFilter;\n /** Stroke color */\n stroke?: string;\n /** Stroke width in pixels */\n strokeWidth?: number;\n /** Border line style (solid/dashed/dotted). Default solid. */\n borderStyle?: BorderStyle;\n /** Corner radius for rect */\n borderRadius?: number;\n };\n}\n\n/**\n * End-of-line marker style for a path/connector endpoint.\n * `arrow` is a filled triangle (the classic arrowhead); `open` is a stroked\n * V; `diamond`/`circle`/`square` are filled glyphs; `none` draws nothing.\n */\nexport type MarkerStyle = 'none' | 'arrow' | 'open' | 'diamond' | 'circle' | 'square';\n\n/**\n * Path layer - renders an SVG `<path>` for arbitrary curves, connectors,\n * arrows, or filled regions. Used by the diagram template for edges\n * between nodes, the drawing template for non-rect/circle/line shapes, and\n * available to any template that needs a custom geometry.\n *\n * The `position` field carries the layer's bounding box (so animations\n * and clipping work the same as for other layers), but the actual\n * geometry is encoded in the `d` attribute using absolute SVG path\n * coordinates relative to the block viewport.\n */\nexport interface PathLayer extends BaseLayer {\n type: 'path';\n content: {\n /** SVG path `d` attribute (e.g. \"M 10 10 L 90 90\"). Absolute viewBox coords. */\n d: string;\n /**\n * Named shape kind (e.g. `'diamond'`, `'star'`, `'arrow-right'`) for\n * path layers that represent one of Squisq's standard shapes. When\n * set, the renderer re-derives `d` from the layer's `position` box\n * (resolved against the viewport) instead of using the stored `d` —\n * so the shape moves, resizes, and adapts to any aspect ratio like\n * the native rect/circle/line layers do. Plain paths (connectors,\n * freehand) leave this unset and keep their absolute `d`.\n */\n shapeKind?: string;\n /** Stroke color (default: theme text color). */\n stroke?: string;\n /** Stroke width in pixels (default: 2). */\n strokeWidth?: number;\n /** Optional fill color (default: 'none' — pure connectors). */\n fill?: string;\n /** Fill opacity 0–1 (applies to solid and gradient fills). */\n fillOpacity?: number;\n /** Gradient fill; overrides `fill` when set. */\n gradient?: LinearGradient;\n /**\n * Border line style (solid/dashed/dotted). A convenience over\n * `dasharray` for named shapes; when set the renderer derives the\n * dash pattern from it (scaled by stroke width).\n */\n borderStyle?: BorderStyle;\n /** Optional stroke dash pattern (SVG `stroke-dasharray` syntax). */\n dasharray?: string;\n /** Marker at the path start. */\n startMarker?: MarkerStyle;\n /** Marker at the path end. */\n endMarker?: MarkerStyle;\n };\n}\n\n/**\n * Map layer - displays a geographic map with optional markers.\n *\n * Maps are rendered as composite tile images from free tile providers.\n * Supported styles use open-source/free tiles requiring attribution.\n */\nexport interface MapLayer extends BaseLayer {\n type: 'map';\n content: {\n /** Center coordinates for the map */\n center: {\n lat: number;\n lng: number;\n };\n /** Zoom level (0-18, typically 8-14 for doc blocks) */\n zoom: number;\n /** Map tile style */\n style: MapTileStyle;\n /** Optional markers to display on the map */\n markers?: MapMarker[];\n /** Pre-rendered static image path (for video export reliability) */\n staticSrc?: string;\n /** Show attribution text (default: true) */\n showAttribution?: boolean;\n };\n}\n\n/**\n * Video layer - displays a short video clip, always muted (narration provides audio).\n *\n * Rendered via an HTML5 <video> element inside <foreignObject>, similar to how\n * ImageLayer uses <img> for Ken Burns effects. clipStart/clipEnd define the window\n * within the source video to play. During Playwright frame capture (seekTo mode),\n * the video is seeked programmatically rather than playing in real time.\n */\nexport interface VideoLayer extends BaseLayer {\n type: 'video';\n content: {\n /** Path to video file (relative to article media dir) */\n src: string;\n /** Path to poster frame (shown before video loads / during seek) */\n posterSrc?: string;\n /** Alt text for accessibility */\n alt: string;\n /** How to fit video in bounds */\n fit?: 'cover' | 'contain' | 'fill';\n /** Start time within the source video (seconds) */\n clipStart: number;\n /** End time within the source video (seconds) */\n clipEnd: number;\n /** Total source video duration (for validation) */\n sourceDuration?: number;\n /**\n * Seconds into the owning block before this video begins playing\n * (the block-relative `startAt`). Default 0 — plays from block start.\n */\n startAt?: number;\n /**\n * When true, the video keeps playing past the block's end (the\n * playback scheduler re-homes it to the player level). Default false.\n */\n spillover?: boolean;\n /** Video credit / artist name */\n credit?: string;\n /** License identifier (e.g., 'CC BY-SA 4.0') */\n license?: string;\n };\n}\n\n/**\n * Table layer - renders a data table with themed styling.\n * Uses foreignObject inside SVG for HTML-based table layout.\n */\nexport interface TableLayer extends BaseLayer {\n type: 'table';\n content: {\n /** Header cell values */\n headers: string[];\n /** Data rows (array of cell value arrays) */\n rows: string[][];\n /** Per-column alignment */\n align?: (('left' | 'right' | 'center') | null)[];\n /** Visual styling */\n style: TableLayerStyle;\n };\n}\n\n/**\n * Styling options for a TableLayer.\n */\nexport interface TableLayerStyle {\n /** Header row background color */\n headerBackground: string;\n /** Header row text color */\n headerColor: string;\n /** Body cell background color */\n cellBackground: string;\n /** Body cell text color */\n cellColor: string;\n /** Border/divider color */\n borderColor: string;\n /** Font size in pixels */\n fontSize: number;\n /** Font family */\n fontFamily?: string;\n /** Header font family (falls back to fontFamily) */\n headerFontFamily?: string;\n /** Corner radius for the table container */\n borderRadius?: number;\n}\n\n/**\n * One node in a `TreeLayer` — a JSON-serializable hierarchy item (mirrors\n * the treeview codec's `TreeItem`). Rendered as an indented filesystem-style\n * row with a folder/file icon and connector rails.\n */\nexport interface TreeLayerItem {\n id: string;\n label: string;\n /** True renders a folder (container) icon; else a file (leaf) icon. */\n isDir?: boolean;\n /** Trailing comment shown muted after the label. */\n comment?: string;\n children: TreeLayerItem[];\n}\n\n/**\n * A hierarchical treeview rendered as interactive HTML inside a\n * `<foreignObject>` (like `TableLayer`): folder/file icons, connector\n * rails, and collapse chevrons. Interactive (collapse/expand) in the live\n * React player; captured fully-expanded and static in frame/PDF export.\n */\nexport interface TreeLayer extends BaseLayer {\n type: 'tree';\n content: {\n items: TreeLayerItem[];\n style: TreeLayerStyle;\n };\n}\n\n/** Styling options for a TreeLayer. */\nexport interface TreeLayerStyle {\n /** Leaf (file) row text color. */\n rowColor: string;\n /** Container (folder) row text color. */\n dirColor: string;\n /** Connector rail / branch color. */\n connectorColor: string;\n /** Icon color. */\n iconColor: string;\n /** Muted comment color. */\n commentColor: string;\n /** Font size in pixels. */\n fontSize: number;\n /** Row label font family. */\n fontFamily?: string;\n /** Monospace font for the connector rails. */\n monoFontFamily?: string;\n /** Indent step per depth level, in pixels. */\n indentPx: number;\n /** FontAwesome icon token for containers (default `folder`). */\n folderIcon?: string;\n /** FontAwesome icon token for leaves (default `file`). */\n fileIcon?: string;\n}\n\n/**\n * Available map tile styles from free/open-source providers.\n */\nexport type MapTileStyle =\n | 'terrain' // OpenTopoMap - topographic/terrain (default)\n | 'satellite' // ESRI World Imagery\n | 'road' // OpenStreetMap standard\n | 'toner' // Stadia Toner (high contrast B&W)\n | 'watercolor'; // Stadia Watercolor (artistic)\n\n/**\n * A marker to display on the map.\n */\nexport interface MapMarker {\n /** Marker latitude */\n lat: number;\n /** Marker longitude */\n lng: number;\n /** Optional label text */\n label?: string;\n /** Marker color (CSS color, default: #ef4444) */\n color?: string;\n /** Marker icon type */\n icon?: 'pin' | 'circle' | 'star';\n}\n\n// ============================================\n// Position & Styling\n// ============================================\n\n/**\n * Position and dimensions for a layer.\n * Values can be pixels (number) or percentages (string like \"50%\").\n */\nexport interface Position {\n /** X position (pixels or percentage) */\n x: number | string;\n /** Y position (pixels or percentage) */\n y: number | string;\n /** Width (pixels or percentage) */\n width?: number | string;\n /** Height (pixels or percentage) */\n height?: number | string;\n /** Anchor point for positioning */\n anchor?: 'center' | 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right';\n}\n\n/**\n * Text styling options.\n */\nexport interface TextStyle {\n /** Font size in pixels */\n fontSize: number;\n /** Font family (defaults to system sans-serif) */\n fontFamily?: string;\n /** Font weight */\n fontWeight?: 'normal' | 'bold';\n /** Font style. Also the inherited baseline for rich `content.html`. */\n fontStyle?: 'normal' | 'italic';\n /** Text color (CSS color) */\n color: string;\n /** Horizontal text alignment within the layer's position box. */\n textAlign?: 'left' | 'center' | 'right';\n /**\n * Vertical alignment of the text within the layer's position box.\n * Requires a `position.height` to have an effect. When omitted, the\n * vertical baseline is derived from `position.anchor` (legacy behavior).\n */\n verticalAlign?: 'top' | 'middle' | 'bottom';\n /** Line height multiplier */\n lineHeight?: number;\n /** Add drop shadow for readability over images */\n shadow?: boolean;\n /** Background color for text box */\n background?: string;\n /** Background opacity 0–1 (applies to solid and gradient backgrounds). */\n backgroundOpacity?: number;\n /** Gradient background; overrides `background` when set. */\n backgroundGradient?: LinearGradient;\n /** Border (stroke) color for the text box. */\n borderColor?: string;\n /** Border width in pixels. A border renders when > 0 and a color is set. */\n borderWidth?: number;\n /** Border line style (solid/dashed/dotted). Default solid. */\n borderStyle?: BorderStyle;\n /** Padding around text (pixels) */\n padding?: number;\n /** Maximum number of lines before truncation (adds \"...\" to last line) */\n maxLines?: number;\n}\n\n// ============================================\n// Animation & Transitions\n// ============================================\n\n/**\n * Animation to apply to a layer.\n */\nexport interface Animation {\n /** Animation type */\n type: AnimationType;\n /** Duration in seconds (defaults to layer's block duration) */\n duration?: number;\n /** Delay before animation starts (seconds) */\n delay?: number;\n /** CSS easing function */\n easing?: string;\n /** For Ken Burns: zoom direction */\n direction?: 'in' | 'out';\n /** For pan animations: pan direction */\n panDirection?: 'left' | 'right' | 'up' | 'down';\n}\n\n/**\n * Available animation types.\n */\nexport type AnimationType =\n | 'none'\n | 'fadeIn'\n | 'fadeOut'\n | 'slowZoom' // Slow zoom with optional pan\n | 'zoomIn'\n | 'zoomOut'\n | 'panLeft'\n | 'panRight'\n | 'typewriter'; // Text appears letter by letter\n\n// ============================================\n// Audio Configuration\n// ============================================\n\n/**\n * Audio track configuration.\n * Articles have multiple MP3 segments (intro + sections).\n */\nexport interface AudioTrack {\n /** Audio segments in playback order */\n segments: AudioSegment[];\n}\n\n// ============================================\n// Captions\n// ============================================\n\n/**\n * A single word with precise timing, used for word-level highlighting\n * in social-style captions. Populated from TTS timing data when available.\n */\nexport interface CaptionWord {\n /** The word text */\n text: string;\n /** Start time in seconds (relative to doc start) */\n startTime: number;\n /** End time in seconds */\n endTime: number;\n}\n\n/**\n * A single caption phrase to display during playback.\n */\nexport interface CaptionPhrase {\n /** The text to display */\n text: string;\n /** Start time in seconds (relative to doc start) */\n startTime: number;\n /** End time in seconds */\n endTime: number;\n /** Which audio segment this caption belongs to (0-indexed) */\n audioSegment: number;\n /**\n * Optional per-word timing from TTS timing data.\n * When present, enables precise word-level highlighting in social\n * caption style. When absent, word timing is interpolated evenly\n * across the phrase duration.\n */\n words?: CaptionWord[];\n}\n\n/**\n * Caption track for a doc.\n */\nexport interface CaptionTrack {\n /** Caption phrases in chronological order */\n phrases: CaptionPhrase[];\n /** When the captions were generated. Optional so that conversion stays\n * deterministic — `markdownToDoc()` only sets it when the caller\n * supplies a timestamp via `captionsGeneratedAt`. */\n generatedAt?: string;\n /** Algorithm version for regeneration detection */\n version: number;\n}\n\n/**\n * A single audio segment (one MP3 file).\n */\nexport interface AudioSegment {\n /** Path to MP3 file (relative to article media dir) */\n src: string;\n /** Segment name (e.g., \"intro\", \"history\") */\n name: string;\n /** Duration in seconds */\n duration: number;\n /** Start time in overall timeline (calculated) */\n startTime: number;\n}\n\n// ============================================\n// Audio Timing Data (from TTS)\n// ============================================\n\n/**\n * A single word-level timing bookmark from TTS synthesis.\n * Used for precise audio-to-content mapping and word-level caption sync.\n */\nexport interface AudioBookmark {\n /** Unique identifier (e.g., \"word-0\", \"word-1\") */\n id: string;\n /** Timestamp in seconds from audio start */\n time: number;\n /** Character offset in the source text */\n charOffset: number;\n /** The word text at this position */\n textFragment?: string;\n}\n\n/**\n * Timing data for an audio segment, typically from a `.timing.json` file\n * generated alongside TTS audio. Contains the source text and per-word\n * timing bookmarks for precise content matching and caption sync.\n */\nexport interface AudioTimingData {\n /** The normalized plain text that was synthesized */\n sourceText: string;\n /** Word-level timing bookmarks */\n bookmarks: AudioBookmark[];\n /** Total audio duration in seconds */\n duration: number;\n}\n\n// ============================================\n// Helper Functions\n// ============================================\n\n/**\n * Calculate total duration from audio segments.\n */\nexport function calculateDuration(audio: AudioTrack): number {\n return audio.segments.reduce((sum, seg) => sum + seg.duration, 0);\n}\n\n/**\n * Find which audio segment is playing at a given time.\n */\nexport function getSegmentAtTime(audio: AudioTrack, time: number): number {\n let elapsed = 0;\n for (let i = 0; i < audio.segments.length; i++) {\n elapsed += audio.segments[i].duration;\n if (time < elapsed) return i;\n }\n return audio.segments.length - 1;\n}\n\n/**\n * Find which block should be visible at a given time.\n */\nexport function getBlockAtTime(blocks: Block[], time: number): Block | null {\n for (let i = blocks.length - 1; i >= 0; i--) {\n const block = blocks[i];\n if (time >= block.startTime && time < block.startTime + block.duration) {\n return block;\n }\n }\n return blocks[0] || null;\n}\n\n/**\n * Find the caption phrase that should be displayed at a given time.\n */\nexport function getCaptionAtTime(\n captions: CaptionTrack | undefined,\n time: number,\n): CaptionPhrase | null {\n if (!captions || !captions.phrases.length) return null;\n\n for (const phrase of captions.phrases) {\n if (time >= phrase.startTime && time < phrase.endTime) {\n return phrase;\n }\n }\n return null;\n}\n","/**\n * Theme Compilation\n *\n * Turns a partial Theme (typically authored by the customizer panel from\n * a few seed colors and preset choices) into a complete, validated Theme\n * by:\n *\n * 1. Filling unspecified fields from a hardcoded `STARTER_THEME`.\n * 2. Deriving missing color slots from `seedColors` via OKLCh math.\n * 3. Validating the result.\n *\n * Built-in themes ship as fully-specified Theme JSON and skip this step.\n */\n\nimport type {\n Theme,\n DeepPartial,\n ThemeColorPalette,\n ThemeColorScheme,\n ThemeSeedColors,\n FontFamily,\n} from './Theme.js';\nimport { THEME_SCHEMA_VERSION, createTheme } from './Theme.js';\nimport { assertTheme } from './themeValidator.js';\nimport {\n oklchLighten,\n oklchDarken,\n oklchSetChroma,\n pickContrastingText,\n relativeLuminance,\n deriveScale,\n isHex,\n} from './colorUtils.js';\n\n/** Internal default theme used to fill in fields the customizer doesn't expose. */\nconst STARTER_BODY_FONT: FontFamily = { stackId: 'system-sans' };\nconst STARTER_TITLE_FONT: FontFamily = { stackId: 'system-serif' };\nconst STARTER_MONO_FONT: FontFamily = { stackId: 'system-mono' };\n\nconst STARTER_COLOR_SCHEMES: Record<string, ThemeColorScheme> = {\n blue: { bg: '#1a365d', text: '#63b3ed', accent: '#90cdf4' },\n green: { bg: '#22543d', text: '#9ae6b4', accent: '#68d391' },\n purple: { bg: '#44337a', text: '#d6bcfa', accent: '#b794f4' },\n red: { bg: '#742a2a', text: '#fc8181', accent: '#feb2b2' },\n orange: { bg: '#744210', text: '#fbd38d', accent: '#f6ad55' },\n teal: { bg: '#234e52', text: '#81e6d9', accent: '#4fd1c5' },\n};\n\nexport const STARTER_THEME: Theme = {\n schemaVersion: THEME_SCHEMA_VERSION,\n id: 'custom',\n name: 'Custom Theme',\n description: 'Customizer starter — gets overridden by user choices.',\n colors: {\n primary: '#3182ce',\n secondary: '#4a5568',\n background: '#1a202c',\n backgroundLight: '#2d3748',\n text: '#f7fafc',\n textMuted: '#a0aec0',\n highlight: '#4299e1',\n warning: '#fc8181',\n },\n typography: {\n bodyFont: STARTER_BODY_FONT,\n titleFont: STARTER_TITLE_FONT,\n monoFont: STARTER_MONO_FONT,\n titleWeight: 'bold',\n },\n style: {\n textShadow: true,\n overlayOpacity: 0.45,\n animationSpeed: 1.0,\n borderRadius: 6,\n },\n renderStyle: {\n name: 'standard',\n defaultTextAnimation: 'fadeIn',\n defaultImageAnimation: 'slowZoom',\n ambientMotion: true,\n defaultTransition: { type: 'fade', duration: 0.7 },\n },\n colorSchemes: STARTER_COLOR_SCHEMES,\n};\n\n/**\n * Derive a full `ThemeColorPalette` from `seedColors`, with any explicit\n * `partialColors` taking precedence over derived values. Background and\n * text are guessed from luminance when the user gave only a primary.\n */\nexport function deriveColorPalette(\n seeds: ThemeSeedColors,\n partialColors: Partial<ThemeColorPalette> = {},\n opts: { contrast?: 'subtle' | 'balanced' | 'high' } = {},\n): ThemeColorPalette {\n const spread = opts.contrast === 'high' ? 0.22 : opts.contrast === 'subtle' ? 0.08 : 0.15;\n\n const primary = seeds.primary;\n const secondary = seeds.secondary ?? oklchSetChroma(oklchLighten(primary, 0.05), 0.5);\n const accent = seeds.accent ?? oklchLighten(primary, spread);\n\n // Decide light vs dark surface from the explicit background, the seed background,\n // or default to dark.\n const bgSeed = partialColors.background ?? seeds.background;\n let background: string;\n if (bgSeed) {\n background = bgSeed;\n } else {\n // Pick a dark or light background that contrasts with primary\n background = relativeLuminance(primary) > 0.5 ? '#0a0a0a' : '#1a202c';\n }\n const isLightSurface = relativeLuminance(background) > 0.5;\n\n const backgroundLight =\n partialColors.backgroundLight ??\n (isLightSurface ? oklchDarken(background, 0.04) : oklchLighten(background, 0.04));\n\n const text =\n partialColors.text ?? seeds.text ?? pickContrastingText(background, '#f7fafc', '#1a202c');\n const textMuted =\n partialColors.textMuted ??\n (isLightSurface ? oklchLighten(text, 0.25) : oklchDarken(text, 0.25));\n\n const highlight = partialColors.highlight ?? accent;\n const warning = partialColors.warning ?? '#fc8181';\n\n return {\n primary: partialColors.primary ?? primary,\n secondary: partialColors.secondary ?? secondary,\n background,\n backgroundLight,\n text,\n textMuted,\n highlight,\n warning,\n };\n}\n\n/**\n * Expand one accent color into a full `{bg, text, accent}` color scheme via\n * the OKLCh scale — dark saturated bg, light readable text, the picked accent.\n * Falls back to a neutral scheme when the input isn't a valid hex. Shared by\n * the editor's accent list and file-import theme inference so both derive\n * identical schemes from the same accent.\n */\nexport function accentToColorScheme(accent: string): ThemeColorScheme {\n if (!isHex(accent)) return { bg: '#1a202c', text: '#e2e8f0', accent: '#63b3ed' };\n const scale = deriveScale(accent, 0.3);\n return { bg: scale.darker2, text: scale.lighter2, accent: scale.base };\n}\n\n/** Map a contrast preset to numeric spread used by `deriveColorPalette`. */\nexport type ContrastPreset = 'subtle' | 'balanced' | 'high';\n\nexport interface CompileOptions {\n /** Contrast level for OKLCh derivation (default 'balanced'). */\n contrast?: ContrastPreset;\n /**\n * Base theme to inherit from. When provided, the partial is deep-merged\n * over this theme instead of the neutral `STARTER_THEME`, so the compiled\n * theme inherits the base's render style, color schemes, typography, and\n * persistent layers — and only the fields the user changed are overridden.\n * The base's id is recorded on the result as `basedOn`.\n */\n base?: Theme;\n}\n\n/**\n * Compile a partial Theme into a complete one. Fills missing fields from\n * the base (`opts.base` when given, else `STARTER_THEME`), derives missing\n * color slots from `seedColors` (when present), and validates the result.\n */\nexport function compileTheme(partial: DeepPartial<Theme>, opts: CompileOptions = {}): Theme {\n // Step 1: deep-merge over the base (a chosen theme, or the neutral starter)\n const base = opts.base ?? STARTER_THEME;\n const merged = createTheme(base, partial);\n merged.schemaVersion = THEME_SCHEMA_VERSION;\n // Record which theme this was derived from so a customizer can re-inherit.\n if (opts.base && !merged.basedOn) merged.basedOn = opts.base.id;\n\n // Step 1b: typography fonts are discriminated unions ({stackId} | {custom}),\n // so deep-merge would leave stale keys from the starter when the partial\n // switches form. Replace each font wholesale when explicitly provided.\n const partialTypography = partial.typography;\n if (partialTypography) {\n if (partialTypography.titleFont !== undefined) {\n merged.typography.titleFont = partialTypography.titleFont as FontFamily;\n }\n if (partialTypography.bodyFont !== undefined) {\n merged.typography.bodyFont = partialTypography.bodyFont as FontFamily;\n }\n if (partialTypography.monoFont !== undefined) {\n merged.typography.monoFont = partialTypography.monoFont as FontFamily;\n }\n }\n\n // Step 1c: colorSchemes is a map the user edits wholesale (add / remove\n // accents). Deep-merge can't delete keys, so replace it outright when the\n // partial provides it — mirroring the font replacement above. This lets a\n // removed accent actually disappear rather than lingering from the base.\n if (partial.colorSchemes !== undefined) {\n merged.colorSchemes = partial.colorSchemes as Record<string, ThemeColorScheme>;\n }\n\n // Step 2: derive missing color slots from seeds, if present\n if (merged.seedColors) {\n const partialColors = (partial.colors ?? {}) as Partial<ThemeColorPalette>;\n merged.colors = deriveColorPalette(merged.seedColors, partialColors, {\n contrast: opts.contrast,\n });\n }\n\n // Step 3: validate\n return assertTheme(merged, `compiled theme \"${merged.id}\"`);\n}\n\n/**\n * Parse a JSON string into a validated Theme. Throws on invalid input.\n */\nexport function parseTheme(json: string): Theme {\n let parsed: unknown;\n try {\n parsed = JSON.parse(json);\n } catch (err: unknown) {\n const msg = err instanceof Error ? err.message : String(err);\n throw new Error(`Invalid theme JSON: ${msg}`);\n }\n return assertTheme(parsed, 'parsed theme');\n}\n\n/**\n * Serialize a Theme to a stable, pretty-printed JSON string. Round-trips\n * cleanly through `parseTheme`.\n */\nexport function serializeTheme(theme: Theme): string {\n return JSON.stringify(theme, null, 2);\n}\n"],"mappings":";;;;;;;;;;;;;;AA++BO,SAAS,kBAAkB,OAA2B;AAC3D,SAAO,MAAM,SAAS,OAAO,CAAC,KAAK,QAAQ,MAAM,IAAI,UAAU,CAAC;AAClE;AAKO,SAAS,iBAAiB,OAAmB,MAAsB;AACxE,MAAI,UAAU;AACd,WAAS,IAAI,GAAG,IAAI,MAAM,SAAS,QAAQ,KAAK;AAC9C,eAAW,MAAM,SAAS,CAAC,EAAE;AAC7B,QAAI,OAAO,QAAS,QAAO;AAAA,EAC7B;AACA,SAAO,MAAM,SAAS,SAAS;AACjC;AAKO,SAAS,eAAe,QAAiB,MAA4B;AAC1E,WAAS,IAAI,OAAO,SAAS,GAAG,KAAK,GAAG,KAAK;AAC3C,UAAM,QAAQ,OAAO,CAAC;AACtB,QAAI,QAAQ,MAAM,aAAa,OAAO,MAAM,YAAY,MAAM,UAAU;AACtE,aAAO;AAAA,IACT;AAAA,EACF;AACA,SAAO,OAAO,CAAC,KAAK;AACtB;AAKO,SAAS,iBACd,UACA,MACsB;AACtB,MAAI,CAAC,YAAY,CAAC,SAAS,QAAQ,OAAQ,QAAO;AAElD,aAAW,UAAU,SAAS,SAAS;AACrC,QAAI,QAAQ,OAAO,aAAa,OAAO,OAAO,SAAS;AACrD,aAAO;AAAA,IACT;AAAA,EACF;AACA,SAAO;AACT;;;ACx/BA,IAAM,oBAAgC,EAAE,SAAS,cAAc;AAC/D,IAAM,qBAAiC,EAAE,SAAS,eAAe;AACjE,IAAM,oBAAgC,EAAE,SAAS,cAAc;AAE/D,IAAM,wBAA0D;AAAA,EAC9D,MAAM,EAAE,IAAI,WAAW,MAAM,WAAW,QAAQ,UAAU;AAAA,EAC1D,OAAO,EAAE,IAAI,WAAW,MAAM,WAAW,QAAQ,UAAU;AAAA,EAC3D,QAAQ,EAAE,IAAI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AAW,WAAW,kBAAkB;AAAA,IACjD;AAAA,EACF;AAMA,MAAI,QAAQ,iBAAiB,QAAW;AACtC,WAAO,eAAe,QAAQ;AAAA,EAChC;AAGA,MAAI,OAAO,YAAY;AACrB,UAAM,gBAAiB,QAAQ,UAAU,CAAC;AAC1C,WAAO,SAAS,mBAAmB,OAAO,YAAY,eAAe;AAAA,MACnE,UAAU,KAAK;AAAA,IACjB,CAAC;AAAA,EACH;AAGA,SAAO,YAAY,QAAQ,mBAAmB,OAAO,EAAE,GAAG;AAC5D;AAKO,SAAS,WAAW,MAAqB;AAC9C,MAAI;AACJ,MAAI;AACF,aAAS,KAAK,MAAM,IAAI;AAAA,EAC1B,SAAS,KAAc;AACrB,UAAM,MAAM,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAC3D,UAAM,IAAI,MAAM,uBAAuB,GAAG,EAAE;AAAA,EAC9C;AACA,SAAO,YAAY,QAAQ,cAAc;AAC3C;AAMO,SAAS,eAAe,OAAsB;AACnD,SAAO,KAAK,UAAU,OAAO,MAAM,CAAC;AACtC;","names":[]}
|
package/dist/chunk-PGGGKYWG.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
//# sourceMappingURL=chunk-PGGGKYWG.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/transform/styles/documentary.ts","../src/transform/styles/magazine.ts","../src/transform/styles/dataDriven.ts","../src/transform/styles/narrative.ts","../src/transform/styles/minimal.ts","../src/transform/registry.ts","../src/transform/blockAnalyzer.ts","../src/transform/templateSelector.ts","../src/transform/timingAllocator.ts","../src/transform/applyTransform.ts"],"sourcesContent":["import type { TransformStyleConfig } from '../types.js';\n\n/** Conservative style — sparse highlights, preserves most text as-is. */\nexport const documentaryStyle: TransformStyleConfig = {\n id: 'documentary',\n name: 'Documentary',\n description: 'Conservative — highlights only the strongest stats, dates, and quotes',\n minConfidence: 0.5,\n transformRatio: 0.3,\n preferredTypes: ['stat', 'date', 'quote', 'fact'],\n colorSchemes: ['blue', 'green', 'purple'],\n insertSectionHeaders: false,\n interleaveImages: true,\n blocksPerSection: { max: 3 },\n transitionStyle: 'fade',\n suggestedThemeId: 'documentary',\n};\n","import type { TransformStyleConfig } from '../types.js';\n\n/** Visual variety — pull quotes, definitions, image-heavy layout. */\nexport const magazineStyle: TransformStyleConfig = {\n id: 'magazine',\n name: 'Magazine',\n description: 'Visual variety with pull quotes, facts, and rich image layouts',\n minConfidence: 0.4,\n transformRatio: 0.6,\n preferredTypes: ['quote', 'fact', 'list', 'definition', 'stat', 'impactLine'],\n colorSchemes: ['blue', 'green', 'purple', 'orange', 'red'],\n insertSectionHeaders: true,\n interleaveImages: true,\n blocksPerSection: { max: 5 },\n transitionStyle: 'dissolve',\n suggestedThemeId: 'magazine',\n templateMap: { quote: 'pullQuote', impactLine: 'fullBleedQuote' },\n};\n","import type { TransformStyleConfig } from '../types.js';\n\n/** Numbers-forward — aggressively extracts stats, comparisons, and dates. */\nexport const dataDrivenStyle: TransformStyleConfig = {\n id: 'data-driven',\n name: 'Data-Driven',\n description: 'Aggressively highlights statistics, comparisons, and timelines',\n minConfidence: 0.3,\n transformRatio: 0.8,\n preferredTypes: ['stat', 'comparison', 'date', 'list', 'fact'],\n colorSchemes: ['blue', 'orange', 'green', 'purple', 'red'],\n insertSectionHeaders: true,\n interleaveImages: false,\n blocksPerSection: { max: 6 },\n transitionStyle: 'cut',\n suggestedThemeId: 'tech-dark',\n};\n","import type { TransformStyleConfig } from '../types.js';\n\n/** Timeline-focused — emphasizes dates, quotes, and story arc. */\nexport const narrativeStyle: TransformStyleConfig = {\n id: 'narrative',\n name: 'Narrative',\n description: 'Story-driven with timeline events, quotes, and impact moments',\n minConfidence: 0.4,\n transformRatio: 0.5,\n preferredTypes: ['date', 'quote', 'impactLine', 'fact', 'stat'],\n colorSchemes: ['blue', 'purple', 'green'],\n insertSectionHeaders: true,\n interleaveImages: true,\n blocksPerSection: { max: 4 },\n transitionStyle: 'fade',\n suggestedThemeId: 'cinematic',\n pacing: { intro: true, outro: true },\n};\n","import type { TransformStyleConfig } from '../types.js';\n\n/** Light touch — only the highest-confidence items get transformed. */\nexport const minimalStyle: TransformStyleConfig = {\n id: 'minimal',\n name: 'Minimal',\n description: 'Light touch — only the strongest highlights, mostly text',\n minConfidence: 0.6,\n transformRatio: 0.2,\n preferredTypes: ['stat', 'quote'],\n colorSchemes: ['blue', 'green'],\n insertSectionHeaders: false,\n interleaveImages: false,\n blocksPerSection: { max: 2 },\n transitionStyle: 'fade',\n suggestedThemeId: 'minimalist',\n};\n","/**\n * Transform Style Registry\n *\n * Immutable built-in lookup plus explicit caller-owned custom registries.\n * There is deliberately no process-global mutable registry.\n */\n\nimport type { TransformStyleConfig, TransformStyleInput, TransformStyleRegistry } from './types.js';\nimport { documentaryStyle } from './styles/documentary.js';\nimport { magazineStyle } from './styles/magazine.js';\nimport { dataDrivenStyle } from './styles/dataDriven.js';\nimport { narrativeStyle } from './styles/narrative.js';\nimport { minimalStyle } from './styles/minimal.js';\nimport { cloneAndFreezeData } from '../internal/immutable.js';\n\n/** All built-in transform styles, keyed by id. */\nconst TRANSFORM_STYLES: Readonly<Record<string, TransformStyleConfig>> = Object.freeze({\n [documentaryStyle.id]: cloneAndFreezeData(documentaryStyle),\n [magazineStyle.id]: cloneAndFreezeData(magazineStyle),\n [dataDrivenStyle.id]: cloneAndFreezeData(dataDrivenStyle),\n [narrativeStyle.id]: cloneAndFreezeData(narrativeStyle),\n [minimalStyle.id]: cloneAndFreezeData(minimalStyle),\n});\n\n/** Default style used when no id is provided. */\nexport const DEFAULT_TRANSFORM_STYLE_ID = 'documentary';\n\nconst EXTRACTION_TYPES = new Set([\n 'stat',\n 'date',\n 'quote',\n 'comparison',\n 'fact',\n 'impactLine',\n 'list',\n 'definition',\n]);\nconst TRANSITION_STYLES = new Set(['cut', 'fade', 'dissolve', 'mixed']);\n\nfunction validateTransformStyle(style: TransformStyleConfig): void {\n const candidate = style as unknown as Record<string, unknown>;\n const fail = (message: string): never => {\n throw new TypeError(`Invalid transform style: ${message}`);\n };\n for (const key of ['id', 'name', 'description']) {\n if (typeof candidate[key] !== 'string' || !(candidate[key] as string).trim()) {\n fail(`${key} must be a non-empty string`);\n }\n }\n for (const key of ['minConfidence', 'transformRatio']) {\n const value = candidate[key];\n if (typeof value !== 'number' || !Number.isFinite(value) || value < 0 || value > 1) {\n fail(`${key} must be a finite number between 0 and 1`);\n }\n }\n if (\n !Array.isArray(candidate.preferredTypes) ||\n candidate.preferredTypes.some((type) => !EXTRACTION_TYPES.has(type))\n ) {\n fail('preferredTypes contains an unknown extraction type');\n }\n if (\n !Array.isArray(candidate.colorSchemes) ||\n candidate.colorSchemes.length === 0 ||\n candidate.colorSchemes.some((scheme) => typeof scheme !== 'string' || !scheme)\n ) {\n fail('colorSchemes must contain at least one non-empty string');\n }\n for (const key of ['insertSectionHeaders', 'interleaveImages']) {\n if (typeof candidate[key] !== 'boolean') fail(`${key} must be a boolean`);\n }\n const blocks = candidate.blocksPerSection as { max?: unknown } | undefined;\n if (!blocks || !Number.isInteger(blocks.max) || (blocks.max as number) < 1) {\n fail('blocksPerSection.max must be a positive integer');\n }\n if (\n typeof candidate.transitionStyle !== 'string' ||\n !TRANSITION_STYLES.has(candidate.transitionStyle)\n ) {\n fail('transitionStyle must be cut, fade, dissolve, or mixed');\n }\n const templateMap = candidate.templateMap;\n if (templateMap !== undefined) {\n if (!templateMap || typeof templateMap !== 'object' || Array.isArray(templateMap)) {\n fail('templateMap must be an object');\n }\n for (const [type, template] of Object.entries(templateMap as Record<string, unknown>)) {\n if (!EXTRACTION_TYPES.has(type) || typeof template !== 'string' || !template) {\n fail('templateMap must map known extraction types to non-empty template names');\n }\n }\n }\n if (\n candidate.suggestedThemeId !== undefined &&\n (typeof candidate.suggestedThemeId !== 'string' || !candidate.suggestedThemeId)\n ) {\n fail('suggestedThemeId must be a non-empty string');\n }\n const pacingValue = candidate.pacing;\n if (pacingValue !== undefined) {\n if (!pacingValue || typeof pacingValue !== 'object' || Array.isArray(pacingValue)) {\n fail('pacing must be an object');\n }\n const pacing = pacingValue as { intro?: unknown; outro?: unknown };\n for (const key of ['intro', 'outro'] as const) {\n if (pacing[key] !== undefined && typeof pacing[key] !== 'boolean') {\n fail(`pacing.${key} must be a boolean`);\n }\n }\n }\n const budget = candidate.budget as { slidesPerMinute?: unknown } | undefined;\n if (\n candidate.budget !== undefined &&\n (!budget || typeof budget !== 'object' || Array.isArray(budget))\n ) {\n fail('budget must be an object');\n }\n if (budget && budget.slidesPerMinute !== undefined) {\n const value = budget.slidesPerMinute;\n if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) {\n fail('budget.slidesPerMinute must be a positive finite number');\n }\n }\n}\n\nfunction styleSnapshot(style: TransformStyleConfig): TransformStyleConfig {\n validateTransformStyle(style);\n return cloneAndFreezeData(style);\n}\n\n/** Stored documents emitted before the canonical kebab-case id. Not exported. */\nfunction normalizeBuiltinStyleId(id: string): string {\n return id === 'dataDriven' ? 'data-driven' : id;\n}\n\nfunction resolveBuiltinStyle(id: string): TransformStyleConfig {\n return (\n TRANSFORM_STYLES[normalizeBuiltinStyleId(id)] ?? TRANSFORM_STYLES[DEFAULT_TRANSFORM_STYLE_ID]\n );\n}\n\n/**\n * Create a caller-owned registry. Custom styles are validated, cloned, and\n * deeply frozen at registration time. Built-in resolution remains in the\n * top-level helpers, separate from the registry's caller-owned state.\n */\nexport function createTransformStyleRegistry(\n initialStyles: readonly TransformStyleConfig[] = [],\n): TransformStyleRegistry {\n const registeredStyles = new Map<string, TransformStyleConfig>();\n const registry: TransformStyleRegistry = {\n register(style): void {\n const snapshot = styleSnapshot(style);\n registeredStyles.set(snapshot.id, snapshot);\n },\n unregister(id): boolean {\n return registeredStyles.delete(id);\n },\n get(id): TransformStyleConfig | undefined {\n return registeredStyles.get(id);\n },\n list(): TransformStyleConfig[] {\n return Array.from(registeredStyles.values());\n },\n };\n for (const style of initialStyles) registry.register(style);\n return Object.freeze(registry);\n}\n\n/**\n * Resolve a built-in id, explicit-registry id, or call-scoped style config.\n * Unknown ids fall back to the default style.\n */\nexport function resolveTransformStyle(\n style: TransformStyleInput,\n registry?: TransformStyleRegistry,\n): TransformStyleConfig {\n if (typeof style !== 'string') return styleSnapshot(style);\n return registry?.get(style) ?? resolveBuiltinStyle(style);\n}\n\n/** Get built-in ids plus ids from an optional caller-owned registry. */\nexport function getTransformStyleIds(registry?: TransformStyleRegistry): string[] {\n return Array.from(\n new Set([\n ...Object.keys(TRANSFORM_STYLES),\n ...(registry?.list().map((style) => style.id) ?? []),\n ]),\n );\n}\n\n/** Get summaries for built-ins plus an optional caller-owned registry. */\nexport function getTransformStyleSummaries(registry?: TransformStyleRegistry) {\n return getTransformStyleIds(registry).map((id) => {\n const { name, description } = resolveTransformStyle(id, registry);\n return { id, name, description };\n });\n}\n","/**\n * Block Analyzer\n *\n * Walks Doc blocks, extracts plain text from their markdown contents,\n * and runs the content extractor on each block to identify stats, dates,\n * quotes, etc. that can be promoted to visual template blocks.\n */\n\nimport type { Block } from '../schemas/Doc.js';\nimport type { MarkdownBlockNode, MarkdownNode } from '../markdown/types.js';\nimport type { ExtractedElement, ExtractionOptions } from '../generate/contentExtractor.js';\nimport type { TransformImage } from './types.js';\nimport { extractContent, stripMarkdown } from '../generate/contentExtractor.js';\nimport { extractPlainText, getChildren } from '../markdown/utils.js';\n\n/** An image found in a block's markdown contents. */\nexport interface BlockImage {\n /** Image URL (relative or absolute). */\n src: string;\n /** Alt text. */\n alt: string;\n /** Index of the source block in the analyzed array. */\n sourceBlockIndex: number;\n}\n\n/** A block enriched with extraction analysis. */\nexport interface AnalyzedBlock {\n /** The original block. */\n block: Block;\n /** Plain text extracted from the block's contents. */\n plainText: string;\n /** Content extractions found in the block's text. */\n extractions: ExtractedElement[];\n /** Whether this block has child blocks. */\n hasChildren: boolean;\n /** Word count of the block's body text. */\n bodyWordCount: number;\n /** Images found in this block's markdown contents. */\n images: BlockImage[];\n}\n\n/**\n * Extract plain text from an array of MarkdownBlockNodes.\n */\nfunction contentsToPlainText(contents: MarkdownBlockNode[]): string {\n return contents.map((node) => extractPlainText(node)).join('\\n');\n}\n\n/**\n * Recursively walk a markdown node tree and collect all images.\n */\nfunction collectImages(node: MarkdownNode): Array<{ src: string; alt: string }> {\n const results: Array<{ src: string; alt: string }> = [];\n\n if ('type' in node && node.type === 'image' && 'url' in node) {\n const img = node as { url: string; alt?: string };\n if (img.url) {\n results.push({ src: img.url, alt: img.alt ?? '' });\n }\n }\n\n for (const child of getChildren(node)) {\n results.push(...collectImages(child));\n }\n\n return results;\n}\n\n/**\n * Extract images from a block's markdown contents.\n */\nfunction extractBlockImages(block: Block, blockIndex: number): BlockImage[] {\n if (!block.contents || block.contents.length === 0) return [];\n\n const images: BlockImage[] = [];\n for (const node of block.contents) {\n for (const img of collectImages(node)) {\n images.push({ ...img, sourceBlockIndex: blockIndex });\n }\n }\n return images;\n}\n\n/**\n * Collect all unique images from all blocks in a Doc.\n * Returns them as TransformImages for use in the transform pipeline.\n */\nexport function extractDocImages(blocks: Block[]): TransformImage[] {\n const seen = new Set<string>();\n const images: TransformImage[] = [];\n\n function walk(blockList: Block[]): void {\n for (const block of blockList) {\n if (block.contents) {\n for (const node of block.contents) {\n for (const img of collectImages(node)) {\n if (!seen.has(img.src)) {\n seen.add(img.src);\n images.push({ src: img.src, alt: img.alt });\n }\n }\n }\n }\n if (block.children) {\n walk(block.children);\n }\n }\n }\n\n walk(blocks);\n return images;\n}\n\n/**\n * Collect leaf blocks from a nested block tree.\n * Only returns blocks that have their own `contents` but no children,\n * preventing parent blocks from duplicating text that also appears\n * in their children. Parent-only blocks (with a title but no body\n * content) are included as structural placeholders.\n */\nfunction collectLeafBlocks(blocks: Block[]): Block[] {\n const result: Block[] = [];\n for (const block of blocks) {\n if (block.children && block.children.length > 0) {\n // Parent block — only include it as a structural marker\n // (title only, no body extraction) if it has no contents of its own.\n // Then recurse into children for the actual content.\n if (!block.contents || block.contents.length === 0) {\n result.push(block);\n }\n result.push(...collectLeafBlocks(block.children));\n } else {\n // Leaf block — include for content analysis\n result.push(block);\n }\n }\n return result;\n}\n\n/**\n * Analyze all blocks in a Doc, extracting text and running content extraction.\n *\n * @param blocks - The Doc's block array (may be nested via children).\n * @param options - Extraction options (minConfidence, types filter).\n * @returns Analyzed blocks with extractions, in flattened order.\n */\nexport function analyzeBlocks(blocks: Block[], options?: ExtractionOptions): AnalyzedBlock[] {\n const flat = collectLeafBlocks(blocks);\n const results: AnalyzedBlock[] = [];\n\n for (const block of flat) {\n let plainText = '';\n\n if (block.contents && block.contents.length > 0) {\n plainText = contentsToPlainText(block.contents);\n } else if (block.title) {\n plainText = block.title;\n }\n\n // Strip any remaining markdown syntax\n const stripped = stripMarkdown(plainText);\n const bodyWordCount = stripped.split(/\\s+/).filter((w) => w.length > 0).length;\n\n // Run content extraction\n const extraction = extractContent(stripped, options);\n\n // Extract images from markdown contents\n const images = extractBlockImages(block, results.length);\n\n results.push({\n block,\n plainText: stripped,\n extractions: extraction.elements,\n hasChildren: !!(block.children && block.children.length > 0),\n bodyWordCount,\n images,\n });\n }\n\n return results;\n}\n","/**\n * Template Selector\n *\n * Selects which extracted elements to promote to visual template blocks\n * and handles color scheme rotation, image interleaving, and template\n * variety. Ported and generalized from qualla-internal's TemplateSelector.\n */\n\nimport type { Block, TransitionType } from '../schemas/Doc.js';\nimport type {\n TemplateBlock,\n AccentImage,\n AccentPosition,\n ImageWithCaptionInput,\n SectionHeaderInput,\n QuoteBlockInput,\n FullBleedQuoteInput,\n StatHighlightInput,\n} from '../schemas/BlockTemplates.js';\nimport type { ExtractedElement } from '../generate/contentExtractor.js';\nimport type { TransformStyleConfig, TransformImage } from './types.js';\nimport type { AnalyzedBlock } from './blockAnalyzer.js';\nimport { mapElementToBlock } from '../generate/templateMapper.js';\nimport { SeededRandom } from '../random/SeededRandom.js';\nimport { estimateTimeFromText } from '../timing/narrationTiming.js';\n\n/** Accent positions to rotate through. */\nconst ACCENT_POSITIONS: AccentPosition[] = [\n 'left-strip',\n 'right-strip',\n 'bottom-strip',\n 'corner-inset',\n];\n\n/** Ambient motions to rotate on image blocks. */\nconst AMBIENT_MOTIONS: Array<'zoomIn' | 'zoomOut' | 'panLeft' | 'panRight'> = [\n 'zoomIn',\n 'zoomOut',\n 'panLeft',\n 'panRight',\n];\n\n/** A selected element paired with its source block. */\ninterface SelectedExtraction {\n element: ExtractedElement;\n sourceBlock: Block;\n /** Index in the original analyzed blocks array. */\n sourceIndex: number;\n}\n\n/** Result of template selection. */\nexport interface SelectionResult {\n /** Replacement blocks: a mix of original blocks and new template blocks. */\n blocks: Array<Block | TemplateBlock>;\n /** How many blocks were transformed. */\n transformedCount: number;\n /** How many blocks were inserted (images, section headers). */\n insertedCount: number;\n}\n\n/**\n * Select extractions and build a transformed block sequence.\n *\n * @param analyzed - Analyzed blocks from blockAnalyzer.\n * @param config - The transform style configuration.\n * @param images - Available images for interleaving.\n * @param seed - Random seed for deterministic output.\n */\nexport function selectAndBuild(\n analyzed: AnalyzedBlock[],\n config: TransformStyleConfig,\n images: TransformImage[],\n seed: number,\n): SelectionResult {\n const rng = new SeededRandom(seed);\n\n // 1. Collect all extractions across all blocks, filtered by config\n const candidates = collectCandidates(analyzed, config);\n\n // 2. Determine how many blocks to transform. `transformRatio` scales\n // with block count; an optional duration-based budget (slides per\n // minute) caps runaway promotion on long dense documents.\n const ratioCap = Math.max(1, Math.floor(analyzed.length * config.transformRatio));\n const slidesPerMinute = config.budget?.slidesPerMinute;\n const totalDurationSeconds = analyzed.reduce((sum, ab) => sum + (ab.block.duration || 0), 0);\n const budgetCap =\n slidesPerMinute && totalDurationSeconds > 0\n ? Math.max(1, Math.round((totalDurationSeconds / 60) * slidesPerMinute))\n : Infinity;\n const maxTransforms = Math.min(ratioCap, budgetCap);\n const selected = candidates.slice(0, maxTransforms);\n\n // 3. Build the output block sequence\n const result = buildBlockSequence(analyzed, selected, config, images, rng);\n\n return result;\n}\n\n/**\n * Collect candidate extractions from all analyzed blocks, sorted by\n * a combined score of confidence and type preference.\n */\nfunction collectCandidates(\n analyzed: AnalyzedBlock[],\n config: TransformStyleConfig,\n): SelectedExtraction[] {\n const candidates: SelectedExtraction[] = [];\n\n for (let i = 0; i < analyzed.length; i++) {\n const ab = analyzed[i];\n // Skip blocks with no meaningful text\n if (ab.bodyWordCount < 5) continue;\n\n for (const element of ab.extractions) {\n if (element.confidence < config.minConfidence) continue;\n\n candidates.push({\n element,\n sourceBlock: ab.block,\n sourceIndex: i,\n });\n }\n }\n\n // Sort by: preferred type rank (lower = better), then confidence (higher = better)\n const typeRank = new Map(config.preferredTypes.map((t, i) => [t, i]));\n const maxRank = config.preferredTypes.length;\n\n candidates.sort((a, b) => {\n const rankA = typeRank.get(a.element.type) ?? maxRank;\n const rankB = typeRank.get(b.element.type) ?? maxRank;\n if (rankA !== rankB) return rankA - rankB;\n return b.element.confidence - a.element.confidence;\n });\n\n // Deduplicate: if the same extracted text appears multiple times\n // (e.g., from overlapping parent/child blocks), keep only the\n // highest-ranked occurrence.\n const seenTexts = new Set<string>();\n const deduplicated: SelectedExtraction[] = [];\n for (const candidate of candidates) {\n const key = candidate.element.text.trim().toLowerCase();\n if (seenTexts.has(key)) continue;\n seenTexts.add(key);\n deduplicated.push(candidate);\n }\n\n return deduplicated;\n}\n\n/**\n * Build the output block sequence, replacing source blocks with template\n * blocks where extractions were selected, and interleaving images.\n */\nfunction buildBlockSequence(\n analyzed: AnalyzedBlock[],\n selected: SelectedExtraction[],\n config: TransformStyleConfig,\n images: TransformImage[],\n rng: SeededRandom,\n): SelectionResult {\n // Map: sourceIndex → list of selected extractions for that block\n const blockExtractions = new Map<number, SelectedExtraction[]>();\n for (const sel of selected) {\n const list = blockExtractions.get(sel.sourceIndex) ?? [];\n list.push(sel);\n blockExtractions.set(sel.sourceIndex, list);\n }\n\n // Limit extractions per block: cap at blocksPerSection.max and ensure\n // template type variety within each block (no two same-type extractions).\n for (const [idx, list] of blockExtractions) {\n const diverse: SelectedExtraction[] = [];\n const usedTypes = new Set<string>();\n for (const sel of list) {\n if (usedTypes.has(sel.element.type)) continue;\n usedTypes.add(sel.element.type);\n diverse.push(sel);\n if (diverse.length >= config.blocksPerSection.max) break;\n }\n blockExtractions.set(idx, diverse);\n }\n\n const blocks: Array<Block | TemplateBlock> = [];\n let transformedCount = 0;\n let insertedCount = 0;\n let colorIndex = 0;\n let blockIdCounter = 0;\n let imageIndex = 0;\n let accentPositionIndex = 0;\n let elementsSinceImage = 0;\n let prevTemplateType = '';\n\n // Calculate image interleaving interval\n const totalTransformed = Array.from(blockExtractions.values()).reduce(\n (sum, list) => sum + list.length,\n 0,\n );\n const imageInterval =\n config.interleaveImages && images.length > 0 && totalTransformed > 0\n ? Math.max(2, Math.floor(totalTransformed / (images.length + 1)))\n : Infinity;\n\n for (let i = 0; i < analyzed.length; i++) {\n const ab = analyzed[i];\n const extractions = blockExtractions.get(i);\n\n if (!extractions || extractions.length === 0) {\n // Keep the original block unchanged\n blocks.push(ab.block);\n continue;\n }\n\n // Insert section header before a group of transformed blocks (if enabled)\n if (config.insertSectionHeaders && ab.block.title) {\n const headerBlock: SectionHeaderInput = {\n template: 'sectionHeader',\n id: `transform-header-${blockIdCounter++}`,\n duration: ab.block.duration > 0 ? Math.min(3, ab.block.duration * 0.2) : 3,\n audioSegment: ab.block.audioSegment,\n title: ab.block.title,\n colorScheme: config.colorSchemes[colorIndex % config.colorSchemes.length],\n sourceBlockId: ab.block.id,\n };\n blocks.push(headerBlock);\n insertedCount++;\n }\n\n // Convert each selected extraction to a template block.\n // Track the last template used globally (not just within this block)\n // to avoid consecutive same-template slides across the entire output.\n for (const sel of extractions) {\n const colorScheme = config.colorSchemes[colorIndex % config.colorSchemes.length];\n\n // Build accent image if we have images in the pool\n let accentImage: AccentImage | undefined;\n if (images.length > 0 && config.interleaveImages) {\n const img = images[imageIndex % images.length];\n accentImage = {\n src: img.src,\n alt: img.alt ?? '',\n position: ACCENT_POSITIONS[accentPositionIndex % ACCENT_POSITIONS.length],\n ambientMotion: rng.pick(AMBIENT_MOTIONS) ?? 'zoomIn',\n credit: img.credit,\n license: img.license,\n };\n accentPositionIndex++;\n }\n\n // `sourcePosition` is a CHAR OFFSET into the analyzed plain text;\n // `sourceStartTime` is doc-timeline SECONDS. Convert via spoken-word\n // proportion over the source block's timing — which, when the doc\n // carries a narration take (applyNarrationTiming ran upstream), is\n // the recorded voice: summarized slides land where the words are\n // actually spoken.\n const slideShare = ab.block.duration > 0 ? ab.block.duration / extractions.length : 6;\n const offsetInBlock =\n ab.block.duration > 0\n ? estimateTimeFromText(ab.plainText, sel.element.sourcePosition, ab.block.duration)\n : 0;\n let templateBlock = mapElementToBlock(sel.element, {\n id: `transform-${blockIdCounter++}`,\n duration: slideShare,\n audioSegment: ab.block.audioSegment,\n colorScheme,\n accentImage,\n sourceStartTime: ab.block.startTime + offsetInBlock,\n sourceDuration: slideShare,\n sourceBlockId: ab.block.id,\n sourceCharOffset: sel.element.sourcePosition,\n });\n\n // Style-level extraction→template remap (v2 contract). Only known\n // text-compatible pairings translate; image-backed targets consume\n // the accent image as their background. Unknown pairings keep the\n // default mapping.\n const remapTarget = config.templateMap?.[sel.element.data.type];\n if (remapTarget && remapTarget !== templateBlock.template) {\n const translated = translateTemplateBlock(templateBlock, remapTarget);\n if (translated) templateBlock = translated;\n }\n\n // Apply transition based on style\n if (config.transitionStyle !== 'cut') {\n const transitionType: TransitionType =\n config.transitionStyle === 'mixed'\n ? (rng.pick<TransitionType>(['fade', 'dissolve']) ?? 'fade')\n : config.transitionStyle;\n templateBlock.transition = {\n type: transitionType,\n duration: 0.5,\n };\n }\n\n // Avoid consecutive same-template blocks by bumping color for variety\n if (templateBlock.template === prevTemplateType) {\n colorIndex++;\n }\n prevTemplateType = templateBlock.template;\n\n blocks.push(templateBlock);\n transformedCount++;\n colorIndex++;\n elementsSinceImage++;\n\n // Interleave standalone image at intervals\n if (\n config.interleaveImages &&\n imageIndex < images.length &&\n elementsSinceImage >= imageInterval\n ) {\n const img = images[imageIndex];\n const imageBlock: ImageWithCaptionInput = {\n template: 'imageWithCaption',\n id: `transform-img-${blockIdCounter++}`,\n duration: 4,\n audioSegment: ab.block.audioSegment,\n imageSrc: img.src,\n imageAlt: img.alt ?? '',\n ambientMotion: rng.pick(AMBIENT_MOTIONS) ?? 'zoomIn',\n sourceBlockId: ab.block.id,\n };\n blocks.push(imageBlock);\n imageIndex++;\n insertedCount++;\n elementsSinceImage = 0;\n }\n }\n }\n\n return { blocks, transformedCount, insertedCount };\n}\n\n/**\n * Translate a mapped template block into a style-requested target\n * template. Only text-compatible pairings are supported; returns null\n * (keep the default) for unknown pairs or when a required input —\n * a background image for `pullQuote` — is unavailable.\n */\nfunction translateTemplateBlock(block: TemplateBlock, target: string): TemplateBlock | null {\n const base = {\n id: block.id,\n duration: block.duration,\n audioSegment: block.audioSegment,\n sourceStartTime: block.sourceStartTime,\n sourceDuration: block.sourceDuration,\n sourceBlockId: block.sourceBlockId,\n sourceCharOffset: block.sourceCharOffset,\n };\n\n if (block.template === 'quote') {\n const quote = block as QuoteBlockInput;\n if (target === 'fullBleedQuote') {\n return { ...base, template: 'fullBleedQuote', text: quote.quote };\n }\n if (target === 'pullQuote') {\n // pullQuote requires a full-bleed background image — reuse the\n // accent image the selector already assigned to this block.\n const bg = quote.accentImage;\n if (!bg) return null;\n return {\n ...base,\n template: 'pullQuote',\n text: quote.quote,\n attribution: quote.attribution,\n backgroundImage: { src: bg.src, alt: bg.alt, credit: bg.credit, license: bg.license },\n };\n }\n return null;\n }\n\n if (block.template === 'fullBleedQuote' && target === 'quote') {\n const fbq = block as FullBleedQuoteInput;\n return { ...base, template: 'quote', quote: fbq.text };\n }\n\n if (block.template === 'statHighlight' && target === 'factCard') {\n const stat = block as StatHighlightInput;\n return {\n ...base,\n template: 'factCard',\n fact: stat.stat,\n explanation: stat.description,\n accentImage: stat.accentImage,\n };\n }\n\n return null;\n}\n","/**\n * Timing Allocator\n *\n * Distributes timing (startTime, duration) across transformed blocks.\n * When the source Doc has audio, blocks are fitted to the overall duration.\n * When no audio is present, uses reading-time estimation.\n */\n\nimport type { Block } from '../schemas/Doc.js';\nimport type { TemplateBlock } from '../schemas/BlockTemplates.js';\nimport { isTemplateBlock } from '../schemas/BlockTemplates.js';\n\n/** Minimum block duration in seconds. */\nconst MIN_BLOCK_DURATION = 3;\n/** Maximum block duration in seconds. */\nconst MAX_BLOCK_DURATION = 20;\n/** Default duration when no timing info is available. */\nconst DEFAULT_BLOCK_DURATION = 6;\n\n/**\n * Allocate startTime and duration across a mixed array of blocks and\n * template blocks. Template blocks get timing assigned; existing blocks\n * retain their original timing when possible.\n *\n * @param blocks - The output from templateSelector (mixed Block | TemplateBlock).\n * @param totalDuration - The Doc's total duration (from audio or estimation).\n * @returns A new array of Blocks with consistent timing. Template blocks\n * are returned as Blocks (with startTime/duration set, layers empty).\n */\nexport function allocateTiming(\n blocks: Array<Block | TemplateBlock>,\n totalDuration: number,\n): Block[] {\n if (blocks.length === 0) return [];\n\n // Template blocks carrying a numeric `sourceStartTime` are ANCHORED to\n // the doc timeline — when the source doc is narration-timed\n // (`applyNarrationTiming`), those anchors are where the words are\n // actually spoken, and rescaling would tear the slides away from the\n // voice. Anchored blocks keep their positions; floating blocks\n // (intro/outro bookends, section headers, interleaved images) fill the\n // gaps between anchors. With no anchors at all, behavior is the\n // historical rescale-to-fit.\n const hasAnchors = blocks.some(\n (b) => isTemplateBlock(b) && typeof b.sourceStartTime === 'number',\n );\n return hasAnchors\n ? allocateAnchored(blocks, totalDuration)\n : allocateRescaled(blocks, totalDuration);\n}\n\n/** Historical behavior: scale every duration to fill the total, clamp 3–20 s. */\nfunction allocateRescaled(blocks: Array<Block | TemplateBlock>, totalDuration: number): Block[] {\n const effectiveDuration = totalDuration > 0 ? totalDuration : estimateDefaultDuration(blocks);\n\n // First pass: assign raw durations\n const durations = blocks.map((block) => {\n if (!isTemplateBlock(block) && block.duration > 0) {\n // Existing block with known duration — keep it\n return block.duration;\n }\n if (isTemplateBlock(block) && block.duration > 0) {\n return block.duration;\n }\n return DEFAULT_BLOCK_DURATION;\n });\n\n // Scale durations to fit the total\n const rawTotal = durations.reduce((sum, d) => sum + d, 0);\n if (rawTotal > 0 && effectiveDuration > 0) {\n const scale = effectiveDuration / rawTotal;\n for (let i = 0; i < durations.length; i++) {\n durations[i] = clampDuration(durations[i] * scale);\n }\n }\n\n // Second pass: assign startTimes and build output Blocks\n let currentTime = 0;\n const result: Block[] = [];\n for (let i = 0; i < blocks.length; i++) {\n result.push(toOutputBlock(blocks[i], currentTime, durations[i]));\n currentTime += durations[i];\n }\n return result;\n}\n\n/** Minimum duration for a floating block squeezed between anchors. */\nconst MIN_FLOATING_DURATION = 1;\n\n/**\n * Anchor-aware allocation: anchored entries (template blocks with a\n * numeric `sourceStartTime`, and untransformed source Blocks with their\n * own real timing) are PLACED at their timeline positions; runs of\n * floating blocks (bookends, headers, images) distribute across the gap\n * before the next anchor. Durations then derive from consecutive starts\n * so the timeline stays CONTIGUOUS — a slide summarizing unpromoted\n * source content simply holds until the next slide begins, which is\n * what keeps every narration second covered by some block.\n */\nfunction allocateAnchored(blocks: Array<Block | TemplateBlock>, totalDuration: number): Block[] {\n interface Entry {\n block: Block | TemplateBlock;\n anchorStart: number | null;\n rawDuration: number;\n }\n const entries: Entry[] = blocks.map((block) => {\n if (isTemplateBlock(block)) {\n return {\n block,\n anchorStart: typeof block.sourceStartTime === 'number' ? block.sourceStartTime : null,\n rawDuration: block.duration > 0 ? block.duration : DEFAULT_BLOCK_DURATION,\n };\n }\n // Untransformed source blocks carry real (possibly narration) timing.\n return {\n block,\n anchorStart: block.startTime,\n rawDuration: block.duration > 0 ? block.duration : DEFAULT_BLOCK_DURATION,\n };\n });\n\n // Pass 1: starts. Anchors pin their positions (the cursor then jumps\n // past the anchor's authored span, so following floats land AFTER it).\n // Float runs place differently by position: LEADING floats (before any\n // anchor — intro bookends) fill the opening gap from t=0; MID floats\n // (section headers, images) end-align just before the next anchor —\n // a header belongs to the section it introduces; TRAILING floats\n // (outro) run sequentially after the last anchor's span.\n const starts = new Array<number>(entries.length);\n let cursor = 0;\n let seenAnchor = false;\n let i = 0;\n while (i < entries.length) {\n const entry = entries[i];\n if (entry.anchorStart !== null) {\n const start = Math.max(cursor, entry.anchorStart);\n starts[i] = start;\n const hint = isTemplateBlock(entry.block)\n ? (entry.block.sourceDuration ?? entry.rawDuration)\n : entry.rawDuration;\n cursor = start + Math.max(MIN_FLOATING_DURATION, hint);\n seenAnchor = true;\n i++;\n continue;\n }\n const runStart = i;\n while (i < entries.length && entries[i].anchorStart === null) i++;\n const run = entries.slice(runStart, i);\n const rawSum = run.reduce((sum, e) => sum + e.rawDuration, 0);\n const nextAnchorStart =\n i < entries.length ? Math.max(entries[i].anchorStart ?? cursor, cursor) : null;\n\n if (nextAnchorStart === null) {\n // Trailing floats: natural sizes after the last anchor's span.\n let acc = cursor;\n for (let k = 0; k < run.length; k++) {\n starts[runStart + k] = acc;\n acc += run[k].rawDuration;\n }\n cursor = acc;\n } else if (!seenAnchor) {\n // Leading floats: fill [cursor, nextAnchorStart) proportionally.\n const gap = nextAnchorStart - cursor;\n let acc = cursor;\n for (let k = 0; k < run.length; k++) {\n starts[runStart + k] = acc;\n acc += rawSum > 0 ? (run[k].rawDuration / rawSum) * gap : gap / run.length;\n }\n cursor = nextAnchorStart;\n } else {\n // Mid floats: end-aligned at natural size, capped by the gap.\n const gap = Math.max(0, nextAnchorStart - cursor);\n const scale = rawSum > 0 ? Math.min(1, gap / rawSum) : 0;\n let acc = Math.max(cursor, nextAnchorStart - rawSum * scale);\n for (let k = 0; k < run.length; k++) {\n starts[runStart + k] = acc;\n acc += run[k].rawDuration * scale;\n }\n cursor = nextAnchorStart;\n }\n }\n\n // Pass 2: strictly increasing starts, then contiguous durations.\n for (let k = 0; k < starts.length; k++) {\n const floor = k > 0 ? starts[k - 1] + MIN_FLOATING_DURATION : 0;\n if (starts[k] < floor) starts[k] = floor;\n }\n const result: Block[] = [];\n for (let k = 0; k < entries.length; k++) {\n const entry = entries[k];\n let duration: number;\n if (k + 1 < entries.length) {\n duration = Math.max(MIN_FLOATING_DURATION, starts[k + 1] - starts[k]);\n } else {\n const authored = isTemplateBlock(entry.block)\n ? (entry.block.sourceDuration ?? entry.rawDuration)\n : entry.rawDuration;\n // The final block covers through the end of the doc/narration when\n // the caller knows it runs longer.\n duration = Math.max(MIN_FLOATING_DURATION, authored, totalDuration - starts[k]);\n }\n result.push(toOutputBlock(entry.block, starts[k], duration));\n }\n return result;\n}\n\n/**\n * Convert an entry to an output Block shell. Template blocks preserve all\n * template-specific fields (stat, quote, description, …) so they survive\n * through to the player's template expansion step.\n */\nfunction toOutputBlock(block: Block | TemplateBlock, startTime: number, duration: number): Block {\n if (isTemplateBlock(block)) {\n return {\n ...block,\n startTime,\n duration,\n title: getTemplateTitle(block),\n } as unknown as Block;\n }\n return { ...block, startTime, duration };\n}\n\n/** Clamp a duration to the min/max range. */\nfunction clampDuration(d: number): number {\n return Math.max(MIN_BLOCK_DURATION, Math.min(MAX_BLOCK_DURATION, d));\n}\n\n/** Estimate a total duration from block contents when no audio is available. */\nfunction estimateDefaultDuration(blocks: Array<Block | TemplateBlock>): number {\n let totalSeconds = 0;\n for (const block of blocks) {\n if (!isTemplateBlock(block) && block.duration > 0) {\n totalSeconds += block.duration;\n } else {\n totalSeconds += DEFAULT_BLOCK_DURATION;\n }\n }\n return Math.max(totalSeconds, blocks.length * MIN_BLOCK_DURATION);\n}\n\n/** Extract a display title from a template block if available. */\nfunction getTemplateTitle(block: TemplateBlock): string | undefined {\n if ('title' in block && typeof block.title === 'string') {\n return block.title;\n }\n if ('stat' in block && typeof block.stat === 'string') {\n return block.stat;\n }\n if ('fact' in block && typeof block.fact === 'string') {\n return block.fact;\n }\n if ('quote' in block && typeof block.quote === 'string') {\n return block.quote.slice(0, 60);\n }\n return undefined;\n}\n","/**\n * Apply Transform\n *\n * Main entry point for the transform module. Takes a Doc and a style,\n * analyzes block content, selects extractions to promote, and returns\n * a new Doc with blocks optimized for visual presentation.\n *\n * The input Doc is never mutated — a fresh Doc is always returned.\n */\n\nimport type { Doc } from '../schemas/Doc.js';\nimport type { DocBlock, TitleBlockInput, SectionHeaderInput } from '../schemas/BlockTemplates.js';\nimport type { TransformStyleInput, TransformOptions, TransformResult } from './types.js';\nimport { resolveTransformStyle } from './registry.js';\nimport { analyzeBlocks, extractDocImages } from './blockAnalyzer.js';\nimport { selectAndBuild } from './templateSelector.js';\nimport { allocateTiming } from './timingAllocator.js';\nimport { hashString } from '../random/SeededRandom.js';\n\n/**\n * Apply a transform style to a Doc, producing a new Doc with blocks\n * optimized for visual presentation.\n *\n * @param doc - The source Doc (not mutated).\n * @param style - Built-in/registry id or a call-scoped declarative style.\n * @param options - Optional seed, images, theme override, and explicit registry.\n * @returns TransformResult with the new Doc and stats.\n */\nexport function applyTransform(\n doc: Doc,\n style: TransformStyleInput,\n options?: TransformOptions,\n): TransformResult {\n const baseConfig = resolveTransformStyle(style, options?.registry);\n const config = options?.overrides\n ? { ...baseConfig, ...options.overrides, id: baseConfig.id }\n : baseConfig;\n\n const seed = options?.seed ?? hashString(doc.articleId || 'transform');\n\n // Use provided images or auto-extract from the doc's markdown content\n const images = options?.images ?? extractDocImages(doc.blocks);\n\n // 1. Analyze blocks\n const analyzed = analyzeBlocks(doc.blocks, {\n minConfidence: config.minConfidence,\n types: config.preferredTypes,\n });\n\n // If no blocks have meaningful content, return the doc unchanged\n const hasContent = analyzed.some((ab) => ab.bodyWordCount >= 5);\n if (!hasContent) {\n return {\n doc: { ...doc },\n stats: {\n totalInputBlocks: doc.blocks.length,\n transformedBlocks: 0,\n insertedBlocks: 0,\n },\n };\n }\n\n // 2. Select extractions and build template blocks\n const selection = selectAndBuild(analyzed, config, images, seed);\n\n // 2b. Pacing bookends: an opening title beat and/or a closing beat.\n let paced: DocBlock[] = selection.blocks;\n let pacingInserted = 0;\n const docTitle = firstTitle(doc);\n if (config.pacing?.intro && docTitle && !doc.startBlock) {\n const intro: TitleBlockInput = {\n template: 'title',\n id: 'transform-intro',\n duration: 4,\n audioSegment: 0,\n title: docTitle,\n };\n paced = [intro, ...paced];\n pacingInserted++;\n }\n if (config.pacing?.outro && docTitle) {\n const outro: SectionHeaderInput = {\n template: 'sectionHeader',\n id: 'transform-outro',\n duration: 3,\n audioSegment: 0,\n title: docTitle,\n colorScheme: config.colorSchemes[0],\n };\n paced = [...paced, outro];\n pacingInserted++;\n }\n\n // 3. Allocate timing across the new block sequence\n const timedBlocks = allocateTiming(paced, doc.duration);\n\n // 4. Assemble the output Doc. A style's suggested theme applies only\n // when neither the caller nor the doc declares one.\n const transformedDoc: Doc = {\n ...doc,\n blocks: timedBlocks,\n themeId: options?.themeId ?? doc.themeId ?? config.suggestedThemeId,\n };\n\n return {\n doc: transformedDoc,\n stats: {\n totalInputBlocks: doc.blocks.length,\n transformedBlocks: selection.transformedCount,\n insertedBlocks: selection.insertedCount + pacingInserted,\n },\n };\n}\n\n/** First non-empty block title (the doc's working title). */\nfunction firstTitle(doc: Doc): string | undefined {\n if (doc.startBlock?.title) return doc.startBlock.title;\n for (const block of doc.blocks) {\n if (block.title) return block.title;\n }\n return undefined;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAGO,IAAM,mBAAyC;AAAA,EACpD,IAAI;AAAA,EACJ,MAAM;AAAA,EACN,aAAa;AAAA,EACb,eAAe;AAAA,EACf,gBAAgB;AAAA,EAChB,gBAAgB,CAAC,QAAQ,QAAQ,SAAS,MAAM;AAAA,EAChD,cAAc,CAAC,QAAQ,SAAS,QAAQ;AAAA,EACxC,sBAAsB;AAAA,EACtB,kBAAkB;AAAA,EAClB,kBAAkB,EAAE,KAAK,EAAE;AAAA,EAC3B,iBAAiB;AAAA,EACjB,kBAAkB;AACpB;;;ACbO,IAAM,gBAAsC;AAAA,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