@bendyline/squisq 0.1.2 → 1.1.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/dist/{themeLibrary-DySHPcgj.d.ts → Doc-1hmT1LZl.d.ts} +1 -42
- package/dist/MediaProvider-wpSe21B3.d.ts +66 -0
- package/dist/__tests__/animationUtils.test.d.ts +2 -0
- package/dist/__tests__/animationUtils.test.d.ts.map +1 -0
- package/dist/__tests__/animationUtils.test.js +60 -0
- package/dist/__tests__/animationUtils.test.js.map +1 -0
- package/dist/__tests__/contentContainer.test.d.ts +2 -0
- package/dist/__tests__/contentContainer.test.d.ts.map +1 -0
- package/dist/__tests__/contentContainer.test.js +234 -0
- package/dist/__tests__/contentContainer.test.js.map +1 -0
- package/dist/__tests__/contentExtractor.test.d.ts +2 -0
- package/dist/__tests__/contentExtractor.test.d.ts.map +1 -0
- package/dist/__tests__/contentExtractor.test.js +151 -0
- package/dist/__tests__/contentExtractor.test.js.map +1 -0
- package/dist/__tests__/geohash.test.d.ts +2 -0
- package/dist/__tests__/geohash.test.d.ts.map +1 -0
- package/dist/__tests__/geohash.test.js +87 -0
- package/dist/__tests__/geohash.test.js.map +1 -0
- package/dist/__tests__/getLayers.test.d.ts +2 -0
- package/dist/__tests__/getLayers.test.d.ts.map +1 -0
- package/dist/__tests__/getLayers.test.js +167 -0
- package/dist/__tests__/getLayers.test.js.map +1 -0
- package/dist/__tests__/haversine.test.d.ts +2 -0
- package/dist/__tests__/haversine.test.d.ts.map +1 -0
- package/dist/__tests__/haversine.test.js +56 -0
- package/dist/__tests__/haversine.test.js.map +1 -0
- package/dist/__tests__/localForageAdapter.test.d.ts +8 -0
- package/dist/__tests__/localForageAdapter.test.d.ts.map +1 -0
- package/dist/__tests__/localForageAdapter.test.js +130 -0
- package/dist/__tests__/localForageAdapter.test.js.map +1 -0
- package/dist/__tests__/markdown.test.d.ts +2 -0
- package/dist/__tests__/markdown.test.d.ts.map +1 -0
- package/dist/__tests__/markdown.test.js +654 -0
- package/dist/__tests__/markdown.test.js.map +1 -0
- package/dist/__tests__/markdownToDoc.test.d.ts +2 -0
- package/dist/__tests__/markdownToDoc.test.d.ts.map +1 -0
- package/dist/__tests__/markdownToDoc.test.js +313 -0
- package/dist/__tests__/markdownToDoc.test.js.map +1 -0
- package/dist/__tests__/seededRandom.test.d.ts +2 -0
- package/dist/__tests__/seededRandom.test.d.ts.map +1 -0
- package/dist/__tests__/seededRandom.test.js +125 -0
- package/dist/__tests__/seededRandom.test.js.map +1 -0
- package/dist/__tests__/slideshowGenerator.test.d.ts +2 -0
- package/dist/__tests__/slideshowGenerator.test.d.ts.map +1 -0
- package/dist/__tests__/slideshowGenerator.test.js +114 -0
- package/dist/__tests__/slideshowGenerator.test.js.map +1 -0
- package/dist/__tests__/storage.test.d.ts +2 -0
- package/dist/__tests__/storage.test.d.ts.map +1 -0
- package/dist/__tests__/storage.test.js +51 -0
- package/dist/__tests__/storage.test.js.map +1 -0
- package/dist/__tests__/templates.test.d.ts +2 -0
- package/dist/__tests__/templates.test.d.ts.map +1 -0
- package/dist/__tests__/templates.test.js +217 -0
- package/dist/__tests__/templates.test.js.map +1 -0
- package/dist/__tests__/timing.test.d.ts +2 -0
- package/dist/__tests__/timing.test.d.ts.map +1 -0
- package/dist/__tests__/timing.test.js +131 -0
- package/dist/__tests__/timing.test.js.map +1 -0
- package/dist/chunk-3E5F2XMR.js +129 -0
- package/dist/chunk-3E5F2XMR.js.map +1 -0
- package/dist/chunk-4CRBS35L.js +292 -0
- package/dist/chunk-4CRBS35L.js.map +1 -0
- package/dist/chunk-6YJPI6VI.js +35 -0
- package/dist/chunk-6YJPI6VI.js.map +1 -0
- package/dist/chunk-FVTQSNR7.js +100 -0
- package/dist/chunk-FVTQSNR7.js.map +1 -0
- package/dist/chunk-V543AI2F.js +1 -0
- package/dist/chunk-V543AI2F.js.map +1 -0
- package/dist/chunk-VP5SZTZ2.js +792 -0
- package/dist/chunk-VP5SZTZ2.js.map +1 -0
- package/dist/doc/docToMarkdown.d.ts +41 -0
- package/dist/doc/docToMarkdown.d.ts.map +1 -0
- package/dist/doc/docToMarkdown.js +88 -0
- package/dist/doc/docToMarkdown.js.map +1 -0
- package/dist/doc/getLayers.d.ts +65 -0
- package/dist/doc/getLayers.d.ts.map +1 -0
- package/dist/doc/getLayers.js +103 -0
- package/dist/doc/getLayers.js.map +1 -0
- package/dist/doc/index.d.ts +9 -3
- package/dist/doc/index.d.ts.map +1 -0
- package/dist/doc/index.js +6 -125
- package/dist/doc/index.js.map +1 -1
- package/dist/doc/markdownToDoc.d.ts +68 -0
- package/dist/doc/markdownToDoc.d.ts.map +1 -0
- package/dist/doc/markdownToDoc.js +225 -0
- package/dist/doc/markdownToDoc.js.map +1 -0
- package/dist/doc/templates/accentImage.d.ts +59 -0
- package/dist/doc/templates/accentImage.d.ts.map +1 -0
- package/dist/doc/templates/accentImage.js +275 -0
- package/dist/doc/templates/accentImage.js.map +1 -0
- package/dist/doc/templates/captionUtils.d.ts +20 -0
- package/dist/doc/templates/captionUtils.d.ts.map +1 -0
- package/dist/doc/templates/captionUtils.js +29 -0
- package/dist/doc/templates/captionUtils.js.map +1 -0
- package/dist/doc/templates/comparisonBar.d.ts +13 -0
- package/dist/doc/templates/comparisonBar.d.ts.map +1 -0
- package/dist/doc/templates/comparisonBar.js +127 -0
- package/dist/doc/templates/comparisonBar.js.map +1 -0
- package/dist/doc/templates/coverBlock.d.ts +51 -0
- package/dist/doc/templates/coverBlock.d.ts.map +1 -0
- package/dist/doc/templates/coverBlock.js +125 -0
- package/dist/doc/templates/coverBlock.js.map +1 -0
- package/dist/doc/templates/dateEvent.d.ts +15 -0
- package/dist/doc/templates/dateEvent.d.ts.map +1 -0
- package/dist/doc/templates/dateEvent.js +110 -0
- package/dist/doc/templates/dateEvent.js.map +1 -0
- package/dist/doc/templates/definitionCard.d.ts +13 -0
- package/dist/doc/templates/definitionCard.d.ts.map +1 -0
- package/dist/doc/templates/definitionCard.js +114 -0
- package/dist/doc/templates/definitionCard.js.map +1 -0
- package/dist/doc/templates/factCard.d.ts +15 -0
- package/dist/doc/templates/factCard.d.ts.map +1 -0
- package/dist/doc/templates/factCard.js +100 -0
- package/dist/doc/templates/factCard.js.map +1 -0
- package/dist/doc/templates/fullBleedQuote.d.ts +13 -0
- package/dist/doc/templates/fullBleedQuote.d.ts.map +1 -0
- package/dist/doc/templates/fullBleedQuote.js +54 -0
- package/dist/doc/templates/fullBleedQuote.js.map +1 -0
- package/dist/doc/templates/imageWithCaption.d.ts +13 -0
- package/dist/doc/templates/imageWithCaption.d.ts.map +1 -0
- package/dist/doc/templates/imageWithCaption.js +142 -0
- package/dist/doc/templates/imageWithCaption.js.map +1 -0
- package/dist/doc/templates/index.d.ts +104 -0
- package/dist/doc/templates/index.d.ts.map +1 -0
- package/dist/doc/templates/index.js +442 -0
- package/dist/doc/templates/index.js.map +1 -0
- package/dist/doc/templates/listBlock.d.ts +13 -0
- package/dist/doc/templates/listBlock.d.ts.map +1 -0
- package/dist/doc/templates/listBlock.js +89 -0
- package/dist/doc/templates/listBlock.js.map +1 -0
- package/dist/doc/templates/mapBlock.d.ts +17 -0
- package/dist/doc/templates/mapBlock.d.ts.map +1 -0
- package/dist/doc/templates/mapBlock.js +112 -0
- package/dist/doc/templates/mapBlock.js.map +1 -0
- package/dist/doc/templates/persistentLayers.d.ts +39 -0
- package/dist/doc/templates/persistentLayers.d.ts.map +1 -0
- package/dist/doc/templates/persistentLayers.js +447 -0
- package/dist/doc/templates/persistentLayers.js.map +1 -0
- package/dist/doc/templates/photoGrid.d.ts +20 -0
- package/dist/doc/templates/photoGrid.d.ts.map +1 -0
- package/dist/doc/templates/photoGrid.js +172 -0
- package/dist/doc/templates/photoGrid.js.map +1 -0
- package/dist/doc/templates/pullQuote.d.ts +13 -0
- package/dist/doc/templates/pullQuote.d.ts.map +1 -0
- package/dist/doc/templates/pullQuote.js +109 -0
- package/dist/doc/templates/pullQuote.js.map +1 -0
- package/dist/doc/templates/quoteBlock.d.ts +15 -0
- package/dist/doc/templates/quoteBlock.d.ts.map +1 -0
- package/dist/doc/templates/quoteBlock.js +97 -0
- package/dist/doc/templates/quoteBlock.js.map +1 -0
- package/dist/doc/templates/sectionHeader.d.ts +14 -0
- package/dist/doc/templates/sectionHeader.d.ts.map +1 -0
- package/dist/doc/templates/sectionHeader.js +96 -0
- package/dist/doc/templates/sectionHeader.js.map +1 -0
- package/dist/doc/templates/statHighlight.d.ts +15 -0
- package/dist/doc/templates/statHighlight.d.ts.map +1 -0
- package/dist/doc/templates/statHighlight.js +99 -0
- package/dist/doc/templates/statHighlight.js.map +1 -0
- package/dist/doc/templates/titleBlock.d.ts +13 -0
- package/dist/doc/templates/titleBlock.d.ts.map +1 -0
- package/dist/doc/templates/titleBlock.js +92 -0
- package/dist/doc/templates/titleBlock.js.map +1 -0
- package/dist/doc/templates/twoColumn.d.ts +15 -0
- package/dist/doc/templates/twoColumn.d.ts.map +1 -0
- package/dist/doc/templates/twoColumn.js +219 -0
- package/dist/doc/templates/twoColumn.js.map +1 -0
- package/dist/doc/templates/videoPullQuote.d.ts +20 -0
- package/dist/doc/templates/videoPullQuote.d.ts.map +1 -0
- package/dist/doc/templates/videoPullQuote.js +118 -0
- package/dist/doc/templates/videoPullQuote.js.map +1 -0
- package/dist/doc/templates/videoWithCaption.d.ts +20 -0
- package/dist/doc/templates/videoWithCaption.d.ts.map +1 -0
- package/dist/doc/templates/videoWithCaption.js +104 -0
- package/dist/doc/templates/videoWithCaption.js.map +1 -0
- package/dist/doc/utils/animationUtils.d.ts +34 -0
- package/dist/doc/utils/animationUtils.d.ts.map +1 -0
- package/dist/doc/utils/animationUtils.js +110 -0
- package/dist/doc/utils/animationUtils.js.map +1 -0
- package/dist/doc/utils/themeUtils.d.ts +55 -0
- package/dist/doc/utils/themeUtils.d.ts.map +1 -0
- package/dist/doc/utils/themeUtils.js +109 -0
- package/dist/doc/utils/themeUtils.js.map +1 -0
- package/dist/generate/contentExtractor.d.ts +112 -0
- package/dist/generate/contentExtractor.d.ts.map +1 -0
- package/dist/generate/contentExtractor.js +638 -0
- package/dist/generate/contentExtractor.js.map +1 -0
- package/dist/generate/index.d.ts +7 -0
- package/dist/generate/index.d.ts.map +1 -0
- package/dist/generate/index.js +4 -0
- package/dist/generate/index.js.map +1 -0
- package/dist/generate/slideshowGenerator.d.ts +72 -0
- package/dist/generate/slideshowGenerator.d.ts.map +1 -0
- package/dist/generate/slideshowGenerator.js +159 -0
- package/dist/generate/slideshowGenerator.js.map +1 -0
- package/dist/generate/templateMapper.d.ts +23 -0
- package/dist/generate/templateMapper.d.ts.map +1 -0
- package/dist/generate/templateMapper.js +114 -0
- package/dist/generate/templateMapper.js.map +1 -0
- package/dist/index.d.ts +9 -8
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +8 -216
- package/dist/index.js.map +1 -1
- package/dist/markdown/convert.d.ts +71 -0
- package/dist/markdown/convert.d.ts.map +1 -0
- package/dist/markdown/convert.js +746 -0
- package/dist/markdown/convert.js.map +1 -0
- package/dist/markdown/htmlParse.d.ts +26 -0
- package/dist/markdown/htmlParse.d.ts.map +1 -0
- package/dist/markdown/htmlParse.js +195 -0
- package/dist/markdown/htmlParse.js.map +1 -0
- package/dist/markdown/index.d.ts +19 -225
- package/dist/markdown/index.d.ts.map +1 -0
- package/dist/markdown/index.js +33 -32
- package/dist/markdown/index.js.map +1 -1
- package/dist/markdown/parse.d.ts +27 -0
- package/dist/markdown/parse.d.ts.map +1 -0
- package/dist/markdown/parse.js +90 -0
- package/dist/markdown/parse.js.map +1 -0
- package/dist/markdown/stringify.d.ts +32 -0
- package/dist/markdown/stringify.d.ts.map +1 -0
- package/dist/markdown/stringify.js +108 -0
- package/dist/markdown/stringify.js.map +1 -0
- package/dist/markdown/types.d.ts +496 -0
- package/dist/markdown/types.d.ts.map +1 -0
- package/dist/markdown/types.js +17 -0
- package/dist/markdown/types.js.map +1 -0
- package/dist/markdown/utils.d.ts +78 -0
- package/dist/markdown/utils.d.ts.map +1 -0
- package/dist/markdown/utils.js +149 -0
- package/dist/markdown/utils.js.map +1 -0
- package/dist/random/SeededRandom.d.ts +50 -0
- package/dist/random/SeededRandom.d.ts.map +1 -0
- package/dist/random/SeededRandom.js +115 -0
- package/dist/random/SeededRandom.js.map +1 -0
- package/dist/random/index.d.ts +2 -0
- package/dist/random/index.d.ts.map +1 -0
- package/dist/random/index.js +2 -0
- package/dist/random/index.js.map +1 -0
- package/dist/schemas/BlockTemplates.d.ts +583 -0
- package/dist/schemas/BlockTemplates.d.ts.map +1 -0
- package/dist/schemas/BlockTemplates.js +72 -0
- package/dist/schemas/BlockTemplates.js.map +1 -0
- package/dist/schemas/Doc.d.ts +411 -0
- package/dist/schemas/Doc.d.ts.map +1 -0
- package/dist/schemas/Doc.js +90 -0
- package/dist/schemas/Doc.js.map +1 -0
- package/dist/schemas/LayoutStrategy.d.ts +84 -0
- package/dist/schemas/LayoutStrategy.d.ts.map +1 -0
- package/dist/schemas/LayoutStrategy.js +123 -0
- package/dist/schemas/LayoutStrategy.js.map +1 -0
- package/dist/schemas/MediaProvider.d.ts +65 -0
- package/dist/schemas/MediaProvider.d.ts.map +1 -0
- package/dist/schemas/MediaProvider.js +13 -0
- package/dist/schemas/MediaProvider.js.map +1 -0
- package/dist/schemas/Theme.d.ts +163 -0
- package/dist/schemas/Theme.d.ts.map +1 -0
- package/dist/schemas/Theme.js +62 -0
- package/dist/schemas/Theme.js.map +1 -0
- package/dist/schemas/Types.d.ts +14 -0
- package/dist/schemas/Types.d.ts.map +1 -0
- package/dist/schemas/Types.js +5 -0
- package/dist/schemas/Types.js.map +1 -0
- package/dist/schemas/Viewport.d.ts +74 -0
- package/dist/schemas/Viewport.d.ts.map +1 -0
- package/dist/schemas/Viewport.js +63 -0
- package/dist/schemas/Viewport.js.map +1 -0
- package/dist/schemas/index.d.ts +10 -70
- package/dist/schemas/index.d.ts.map +1 -0
- package/dist/schemas/index.js +7 -60
- package/dist/schemas/index.js.map +1 -1
- package/dist/schemas/themeLibrary.d.ts +41 -0
- package/dist/schemas/themeLibrary.d.ts.map +1 -0
- package/dist/schemas/themeLibrary.js +466 -0
- package/dist/schemas/themeLibrary.js.map +1 -0
- package/dist/spatial/Geohash.d.ts +85 -0
- package/dist/spatial/Geohash.d.ts.map +1 -0
- package/dist/spatial/Geohash.js +142 -0
- package/dist/spatial/Geohash.js.map +1 -0
- package/dist/spatial/Haversine.d.ts +24 -0
- package/dist/spatial/Haversine.d.ts.map +1 -0
- package/dist/spatial/Haversine.js +48 -0
- package/dist/spatial/Haversine.js.map +1 -0
- package/dist/spatial/index.d.ts +3 -111
- package/dist/spatial/index.d.ts.map +1 -0
- package/dist/spatial/index.js +2 -24
- package/dist/spatial/index.js.map +1 -1
- package/dist/storage/ContentContainer.d.ts +87 -0
- package/dist/storage/ContentContainer.d.ts.map +1 -0
- package/dist/storage/ContentContainer.js +122 -0
- package/dist/storage/ContentContainer.js.map +1 -0
- package/dist/storage/LocalForageAdapter.d.ts +36 -0
- package/dist/storage/LocalForageAdapter.d.ts.map +1 -0
- package/dist/storage/LocalForageAdapter.js +82 -0
- package/dist/storage/LocalForageAdapter.js.map +1 -0
- package/dist/storage/LocalStorageAdapter.d.ts +16 -0
- package/dist/storage/LocalStorageAdapter.d.ts.map +1 -0
- package/dist/storage/LocalStorageAdapter.js +50 -0
- package/dist/storage/LocalStorageAdapter.js.map +1 -0
- package/dist/storage/MediaProviderFromContainer.d.ts +21 -0
- package/dist/storage/MediaProviderFromContainer.d.ts.map +1 -0
- package/dist/storage/MediaProviderFromContainer.js +79 -0
- package/dist/storage/MediaProviderFromContainer.js.map +1 -0
- package/dist/storage/MemoryStorageAdapter.d.ts +15 -0
- package/dist/storage/MemoryStorageAdapter.d.ts.map +1 -0
- package/dist/storage/MemoryStorageAdapter.js +34 -0
- package/dist/storage/MemoryStorageAdapter.js.map +1 -0
- package/dist/storage/Storage.d.ts +23 -0
- package/dist/storage/Storage.d.ts.map +1 -0
- package/dist/storage/Storage.js +9 -0
- package/dist/storage/Storage.js.map +1 -0
- package/dist/storage/index.d.ts +9 -91
- package/dist/storage/index.d.ts.map +1 -0
- package/dist/storage/index.js +5 -10
- package/dist/storage/index.js.map +1 -1
- package/dist/story/index.d.ts +3 -2
- package/dist/themeLibrary-DR1VRo-8.d.ts +44 -0
- package/dist/timing/index.d.ts +4 -0
- package/dist/timing/index.d.ts.map +1 -0
- package/dist/timing/index.js +3 -0
- package/dist/timing/index.js.map +1 -0
- package/dist/timing/narrationTiming.d.ts +54 -0
- package/dist/timing/narrationTiming.d.ts.map +1 -0
- package/dist/timing/narrationTiming.js +190 -0
- package/dist/timing/narrationTiming.js.map +1 -0
- package/dist/timing/readingTime.d.ts +54 -0
- package/dist/timing/readingTime.d.ts.map +1 -0
- package/dist/timing/readingTime.js +49 -0
- package/dist/timing/readingTime.js.map +1 -0
- package/package.json +17 -3
- package/src/__tests__/contentContainer.test.ts +282 -0
- package/src/__tests__/contentExtractor.test.ts +183 -0
- package/src/__tests__/seededRandom.test.ts +142 -0
- package/src/__tests__/slideshowGenerator.test.ts +128 -0
- package/src/__tests__/timing.test.ts +167 -0
- package/src/generate/contentExtractor.ts +808 -0
- package/src/generate/index.ts +21 -0
- package/src/generate/slideshowGenerator.ts +273 -0
- package/src/generate/templateMapper.ts +170 -0
- package/src/index.ts +3 -0
- package/src/random/SeededRandom.ts +127 -0
- package/src/random/index.ts +1 -0
- package/src/storage/ContentContainer.ts +200 -0
- package/src/storage/MediaProviderFromContainer.ts +92 -0
- package/src/storage/index.ts +3 -0
- package/src/timing/index.ts +17 -0
- package/src/timing/narrationTiming.ts +220 -0
- package/src/timing/readingTime.ts +94 -0
- package/dist/chunk-VJN7UB2Z.js +0 -145
- package/dist/chunk-VJN7UB2Z.js.map +0 -1
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
// src/timing/narrationTiming.ts
|
|
2
|
+
var NUMBER_SPEAKING_MULTIPLIER = 1.3;
|
|
3
|
+
var COMMA_PAUSE_PENALTY = 0.3;
|
|
4
|
+
var DEFAULT_WORDS_PER_SECOND = 2.5;
|
|
5
|
+
function estimateSpokenWordCount(token) {
|
|
6
|
+
const cleaned = token.replace(/,/g, "");
|
|
7
|
+
const num = parseFloat(cleaned);
|
|
8
|
+
if (isNaN(num) || !isFinite(num)) {
|
|
9
|
+
return 1;
|
|
10
|
+
}
|
|
11
|
+
return estimateNumberWordCount(cleaned, num) * NUMBER_SPEAKING_MULTIPLIER;
|
|
12
|
+
}
|
|
13
|
+
function estimateNumberWordCount(cleaned, num) {
|
|
14
|
+
if (cleaned.includes(".")) {
|
|
15
|
+
const [whole, decimal] = cleaned.split(".");
|
|
16
|
+
const wholeNum = parseFloat(whole) || 0;
|
|
17
|
+
return estimateNumberWordCount(whole, wholeNum) + 1 + decimal.length;
|
|
18
|
+
}
|
|
19
|
+
const absNum = Math.abs(num);
|
|
20
|
+
let words = num < 0 ? 1 : 0;
|
|
21
|
+
if (absNum === 0) return 1;
|
|
22
|
+
if (absNum >= 1e3 && absNum <= 2099 && Number.isInteger(absNum)) {
|
|
23
|
+
const yearStr = absNum.toString();
|
|
24
|
+
if (yearStr.length === 4) {
|
|
25
|
+
const firstTwo = parseInt(yearStr.slice(0, 2));
|
|
26
|
+
const lastTwo = parseInt(yearStr.slice(2));
|
|
27
|
+
if (firstTwo >= 10 && firstTwo <= 19) {
|
|
28
|
+
words += 1;
|
|
29
|
+
} else if (firstTwo >= 20 && firstTwo <= 99) {
|
|
30
|
+
words += firstTwo % 10 === 0 ? 1 : 2;
|
|
31
|
+
} else {
|
|
32
|
+
words += 2;
|
|
33
|
+
}
|
|
34
|
+
if (lastTwo === 0) {
|
|
35
|
+
if (firstTwo >= 10 && firstTwo <= 99 && firstTwo !== 20) {
|
|
36
|
+
words += 1;
|
|
37
|
+
}
|
|
38
|
+
} else if (lastTwo >= 1 && lastTwo <= 9) {
|
|
39
|
+
words += 2;
|
|
40
|
+
} else if (lastTwo >= 10 && lastTwo <= 19) {
|
|
41
|
+
words += 1;
|
|
42
|
+
} else {
|
|
43
|
+
words += lastTwo % 10 === 0 ? 1 : 2;
|
|
44
|
+
}
|
|
45
|
+
return Math.max(words, 2);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
let remaining = absNum;
|
|
49
|
+
if (remaining >= 1e9) {
|
|
50
|
+
const billions = Math.floor(remaining / 1e9);
|
|
51
|
+
words += estimateNumberWordCount(String(billions), billions);
|
|
52
|
+
words += 1;
|
|
53
|
+
remaining %= 1e9;
|
|
54
|
+
}
|
|
55
|
+
if (remaining >= 1e6) {
|
|
56
|
+
const millions = Math.floor(remaining / 1e6);
|
|
57
|
+
words += estimateNumberWordCount(String(millions), millions);
|
|
58
|
+
words += 1;
|
|
59
|
+
remaining %= 1e6;
|
|
60
|
+
}
|
|
61
|
+
if (remaining >= 1e3) {
|
|
62
|
+
const thousands = Math.floor(remaining / 1e3);
|
|
63
|
+
words += estimateNumberWordCount(String(thousands), thousands);
|
|
64
|
+
words += 1;
|
|
65
|
+
remaining %= 1e3;
|
|
66
|
+
}
|
|
67
|
+
if (remaining >= 100) {
|
|
68
|
+
words += 2;
|
|
69
|
+
remaining %= 100;
|
|
70
|
+
}
|
|
71
|
+
if (remaining >= 1) {
|
|
72
|
+
if (remaining >= 20) {
|
|
73
|
+
words += remaining % 10 === 0 ? 1 : 2;
|
|
74
|
+
} else {
|
|
75
|
+
words += 1;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
return Math.max(words, 1);
|
|
79
|
+
}
|
|
80
|
+
function countSpokenWords(text) {
|
|
81
|
+
const tokens = text.split(/\s+/).filter((w) => w.length > 0);
|
|
82
|
+
let count = 0;
|
|
83
|
+
for (const token of tokens) {
|
|
84
|
+
const stripped = token.replace(/^[.,!?;:'"()[\]{}]+|[.,!?;:'"()[\]{}]+$/g, "");
|
|
85
|
+
count += estimateSpokenWordCount(stripped);
|
|
86
|
+
let punctuationCommaCount = 0;
|
|
87
|
+
for (let i = 0; i < token.length; i++) {
|
|
88
|
+
if (token[i] === ",") {
|
|
89
|
+
const prev = i > 0 ? token[i - 1] : "";
|
|
90
|
+
const next = i < token.length - 1 ? token[i + 1] : "";
|
|
91
|
+
const prevIsDigit = prev >= "0" && prev <= "9";
|
|
92
|
+
const nextIsDigit = next >= "0" && next <= "9";
|
|
93
|
+
if (!(prevIsDigit && nextIsDigit)) {
|
|
94
|
+
punctuationCommaCount++;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
count += punctuationCommaCount * COMMA_PAUSE_PENALTY;
|
|
99
|
+
}
|
|
100
|
+
return count;
|
|
101
|
+
}
|
|
102
|
+
function estimateTimeFromText(text, charOffset, totalDuration) {
|
|
103
|
+
const textBefore = text.slice(0, charOffset);
|
|
104
|
+
const spokenWordsBefore = countSpokenWords(textBefore);
|
|
105
|
+
const totalSpokenWords = countSpokenWords(text);
|
|
106
|
+
if (totalSpokenWords === 0) return 0;
|
|
107
|
+
return spokenWordsBefore / totalSpokenWords * totalDuration;
|
|
108
|
+
}
|
|
109
|
+
function calculatePrefixDuration(prefix, wordsPerSecond = DEFAULT_WORDS_PER_SECOND) {
|
|
110
|
+
if (!prefix) return 0;
|
|
111
|
+
const words = prefix.split(/\s+/).filter((w) => w.length > 0);
|
|
112
|
+
const newlineCount = (prefix.match(/\n\n/g) || []).length;
|
|
113
|
+
const pauseTime = newlineCount * 0.5;
|
|
114
|
+
return words.length / wordsPerSecond + pauseTime;
|
|
115
|
+
}
|
|
116
|
+
function estimateNarrationDuration(text, wordsPerSecond = DEFAULT_WORDS_PER_SECOND) {
|
|
117
|
+
const spokenWords = countSpokenWords(text);
|
|
118
|
+
return spokenWords / wordsPerSecond;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export {
|
|
122
|
+
DEFAULT_WORDS_PER_SECOND,
|
|
123
|
+
estimateSpokenWordCount,
|
|
124
|
+
countSpokenWords,
|
|
125
|
+
estimateTimeFromText,
|
|
126
|
+
calculatePrefixDuration,
|
|
127
|
+
estimateNarrationDuration
|
|
128
|
+
};
|
|
129
|
+
//# sourceMappingURL=chunk-3E5F2XMR.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/timing/narrationTiming.ts"],"sourcesContent":["/**\n * Narration timing estimation.\n *\n * Estimates how long text takes to speak aloud, accounting for:\n * - Numbers spoken as multiple words (e.g., \"1910\" → \"nineteen ten\")\n * - Pauses at commas\n * - Year pronunciation conventions (1000–2099)\n *\n * Ported from qualla-internal's AudioTiming.ts (pure functions, no Node.js deps).\n */\n\n/** Numbers are spoken more slowly than regular words (1.3× multiplier). */\nconst NUMBER_SPEAKING_MULTIPLIER = 1.3;\n\n/** Comma pause in \"word equivalents\" — speakers pause ~0.3 words at commas. */\nconst COMMA_PAUSE_PENALTY = 0.3;\n\n/** Default speaking rate in words per second (~150 WPM). */\nexport const DEFAULT_WORDS_PER_SECOND = 2.5;\n\n/**\n * Estimate how many \"spoken word equivalents\" a single token represents.\n * Numbers get expanded (e.g., \"175,000\" → ~5 words × 1.3 multiplier).\n */\nexport function estimateSpokenWordCount(token: string): number {\n const cleaned = token.replace(/,/g, '');\n const num = parseFloat(cleaned);\n\n if (isNaN(num) || !isFinite(num)) {\n return 1; // Not a number — count as 1 word\n }\n\n return estimateNumberWordCount(cleaned, num) * NUMBER_SPEAKING_MULTIPLIER;\n}\n\n/**\n * Raw word count for a number (before the speaking multiplier).\n */\nfunction estimateNumberWordCount(cleaned: string, num: number): number {\n // Handle decimals: \"3.14\" → words(\"3\") + \"point\" + 2 digits\n if (cleaned.includes('.')) {\n const [whole, decimal] = cleaned.split('.');\n const wholeNum = parseFloat(whole) || 0;\n return estimateNumberWordCount(whole, wholeNum) + 1 + decimal.length;\n }\n\n const absNum = Math.abs(num);\n let words = num < 0 ? 1 : 0; // \"negative\" / \"minus\"\n\n if (absNum === 0) return 1; // \"zero\"\n\n // Years (1000–2099) are spoken as two two-digit groups:\n // \"1910\" → \"nineteen ten\", \"2024\" → \"twenty twenty-four\"\n if (absNum >= 1000 && absNum <= 2099 && Number.isInteger(absNum)) {\n const yearStr = absNum.toString();\n if (yearStr.length === 4) {\n const firstTwo = parseInt(yearStr.slice(0, 2));\n const lastTwo = parseInt(yearStr.slice(2));\n\n // First part\n if (firstTwo >= 10 && firstTwo <= 19) {\n words += 1;\n } else if (firstTwo >= 20 && firstTwo <= 99) {\n words += firstTwo % 10 === 0 ? 1 : 2;\n } else {\n words += 2; // \"two thousand\"\n }\n\n // Second part\n if (lastTwo === 0) {\n if (firstTwo >= 10 && firstTwo <= 99 && firstTwo !== 20) {\n words += 1; // \"hundred\"\n }\n } else if (lastTwo >= 1 && lastTwo <= 9) {\n words += 2; // \"oh five\"\n } else if (lastTwo >= 10 && lastTwo <= 19) {\n words += 1;\n } else {\n words += lastTwo % 10 === 0 ? 1 : 2;\n }\n\n return Math.max(words, 2);\n }\n }\n\n // General number handling — each magnitude group adds words\n let remaining = absNum;\n\n if (remaining >= 1_000_000_000) {\n const billions = Math.floor(remaining / 1_000_000_000);\n words += estimateNumberWordCount(String(billions), billions);\n words += 1; // \"billion\"\n remaining %= 1_000_000_000;\n }\n\n if (remaining >= 1_000_000) {\n const millions = Math.floor(remaining / 1_000_000);\n words += estimateNumberWordCount(String(millions), millions);\n words += 1; // \"million\"\n remaining %= 1_000_000;\n }\n\n if (remaining >= 1_000) {\n const thousands = Math.floor(remaining / 1_000);\n words += estimateNumberWordCount(String(thousands), thousands);\n words += 1; // \"thousand\"\n remaining %= 1_000;\n }\n\n if (remaining >= 100) {\n words += 2; // digit + \"hundred\"\n remaining %= 100;\n }\n\n if (remaining >= 1) {\n if (remaining >= 20) {\n words += remaining % 10 === 0 ? 1 : 2;\n } else {\n words += 1; // 1–19\n }\n }\n\n return Math.max(words, 1);\n}\n\n/**\n * Count \"spoken word equivalents\" in a block of text,\n * expanding numbers and adding comma pauses.\n */\nexport function countSpokenWords(text: string): number {\n const tokens = text.split(/\\s+/).filter((w) => w.length > 0);\n let count = 0;\n\n for (const token of tokens) {\n // Strip punctuation only at token boundaries so internal punctuation\n // (e.g., decimals like \"3.14\" or digit-grouping commas \"1,000\") is preserved.\n const stripped = token.replace(/^[.,!?;:'\"()[\\]{}]+|[.,!?;:'\"()[\\]{}]+$/g, '');\n count += estimateSpokenWordCount(stripped);\n\n // Count only punctuation commas for pauses: exclude digit-grouping commas\n // (i.e., commas with digits on both sides, like in \"1,234\").\n let punctuationCommaCount = 0;\n for (let i = 0; i < token.length; i++) {\n if (token[i] === ',') {\n const prev = i > 0 ? token[i - 1] : '';\n const next = i < token.length - 1 ? token[i + 1] : '';\n const prevIsDigit = prev >= '0' && prev <= '9';\n const nextIsDigit = next >= '0' && next <= '9';\n if (!(prevIsDigit && nextIsDigit)) {\n punctuationCommaCount++;\n }\n }\n }\n count += punctuationCommaCount * COMMA_PAUSE_PENALTY;\n }\n\n return count;\n}\n\n/**\n * Estimate audio time at a character offset using word-proportion mapping.\n *\n * Given the full source text and a character position, returns the\n * estimated time (in seconds) at which that position would be spoken.\n *\n * @param text - Full source text\n * @param charOffset - Character offset to estimate timing for\n * @param totalDuration - Total audio duration in seconds\n * @returns Estimated time in seconds\n */\nexport function estimateTimeFromText(\n text: string,\n charOffset: number,\n totalDuration: number,\n): number {\n const textBefore = text.slice(0, charOffset);\n const spokenWordsBefore = countSpokenWords(textBefore);\n const totalSpokenWords = countSpokenWords(text);\n\n if (totalSpokenWords === 0) return 0;\n return (spokenWordsBefore / totalSpokenWords) * totalDuration;\n}\n\n/**\n * Estimate how long a spoken prefix adds to audio duration.\n *\n * When audio includes a spoken title or header before the main content,\n * this calculates the extra duration to offset timing calculations.\n *\n * @param prefix - Prefix text (e.g., an article title spoken before the body)\n * @param wordsPerSecond - Speaking rate (default: 2.5)\n * @returns Estimated duration in seconds\n */\nexport function calculatePrefixDuration(\n prefix: string,\n wordsPerSecond: number = DEFAULT_WORDS_PER_SECOND,\n): number {\n if (!prefix) return 0;\n\n const words = prefix.split(/\\s+/).filter((w) => w.length > 0);\n const newlineCount = (prefix.match(/\\n\\n/g) || []).length;\n const pauseTime = newlineCount * 0.5;\n\n return words.length / wordsPerSecond + pauseTime;\n}\n\n/**\n * Estimate narration duration for a block of text.\n *\n * @param text - The text to estimate\n * @param wordsPerSecond - Speaking rate (default: 2.5, i.e. ~150 WPM)\n * @returns Duration in seconds\n */\nexport function estimateNarrationDuration(\n text: string,\n wordsPerSecond: number = DEFAULT_WORDS_PER_SECOND,\n): number {\n const spokenWords = countSpokenWords(text);\n return spokenWords / wordsPerSecond;\n}\n"],"mappings":";AAYA,IAAM,6BAA6B;AAGnC,IAAM,sBAAsB;AAGrB,IAAM,2BAA2B;AAMjC,SAAS,wBAAwB,OAAuB;AAC7D,QAAM,UAAU,MAAM,QAAQ,MAAM,EAAE;AACtC,QAAM,MAAM,WAAW,OAAO;AAE9B,MAAI,MAAM,GAAG,KAAK,CAAC,SAAS,GAAG,GAAG;AAChC,WAAO;AAAA,EACT;AAEA,SAAO,wBAAwB,SAAS,GAAG,IAAI;AACjD;AAKA,SAAS,wBAAwB,SAAiB,KAAqB;AAErE,MAAI,QAAQ,SAAS,GAAG,GAAG;AACzB,UAAM,CAAC,OAAO,OAAO,IAAI,QAAQ,MAAM,GAAG;AAC1C,UAAM,WAAW,WAAW,KAAK,KAAK;AACtC,WAAO,wBAAwB,OAAO,QAAQ,IAAI,IAAI,QAAQ;AAAA,EAChE;AAEA,QAAM,SAAS,KAAK,IAAI,GAAG;AAC3B,MAAI,QAAQ,MAAM,IAAI,IAAI;AAE1B,MAAI,WAAW,EAAG,QAAO;AAIzB,MAAI,UAAU,OAAQ,UAAU,QAAQ,OAAO,UAAU,MAAM,GAAG;AAChE,UAAM,UAAU,OAAO,SAAS;AAChC,QAAI,QAAQ,WAAW,GAAG;AACxB,YAAM,WAAW,SAAS,QAAQ,MAAM,GAAG,CAAC,CAAC;AAC7C,YAAM,UAAU,SAAS,QAAQ,MAAM,CAAC,CAAC;AAGzC,UAAI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
1
|
+
// src/storage/MemoryStorageAdapter.ts
|
|
2
|
+
var MemoryStorageAdapter = class {
|
|
3
|
+
constructor() {
|
|
4
|
+
this.supportsEnumeration = true;
|
|
5
|
+
this.store = /* @__PURE__ */ new Map();
|
|
6
|
+
}
|
|
7
|
+
async get(key) {
|
|
8
|
+
const val = this.store.get(key);
|
|
9
|
+
if (val === void 0) return null;
|
|
10
|
+
try {
|
|
11
|
+
return JSON.parse(val);
|
|
12
|
+
} catch {
|
|
13
|
+
return null;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
async set(key, value) {
|
|
17
|
+
this.store.set(key, JSON.stringify(value));
|
|
18
|
+
}
|
|
19
|
+
async remove(key) {
|
|
20
|
+
this.store.delete(key);
|
|
21
|
+
}
|
|
22
|
+
async clear() {
|
|
23
|
+
this.store.clear();
|
|
24
|
+
}
|
|
25
|
+
async keys() {
|
|
26
|
+
return Array.from(this.store.keys());
|
|
27
|
+
}
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
// src/storage/LocalStorageAdapter.ts
|
|
31
|
+
var LocalStorageAdapter = class {
|
|
32
|
+
constructor(prefix = "") {
|
|
33
|
+
this.supportsEnumeration = true;
|
|
34
|
+
this.prefix = prefix;
|
|
35
|
+
}
|
|
36
|
+
async get(key) {
|
|
37
|
+
try {
|
|
38
|
+
const raw = localStorage.getItem(this.prefix + key);
|
|
39
|
+
if (raw === null) return null;
|
|
40
|
+
return JSON.parse(raw);
|
|
41
|
+
} catch {
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
async set(key, value) {
|
|
46
|
+
localStorage.setItem(this.prefix + key, JSON.stringify(value));
|
|
47
|
+
}
|
|
48
|
+
async remove(key) {
|
|
49
|
+
localStorage.removeItem(this.prefix + key);
|
|
50
|
+
}
|
|
51
|
+
async clear() {
|
|
52
|
+
const keysToRemove = [];
|
|
53
|
+
for (let i = 0; i < localStorage.length; i++) {
|
|
54
|
+
const k = localStorage.key(i);
|
|
55
|
+
if (k && k.startsWith(this.prefix)) {
|
|
56
|
+
keysToRemove.push(k);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
for (const k of keysToRemove) {
|
|
60
|
+
localStorage.removeItem(k);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
async keys() {
|
|
64
|
+
const result = [];
|
|
65
|
+
for (let i = 0; i < localStorage.length; i++) {
|
|
66
|
+
const k = localStorage.key(i);
|
|
67
|
+
if (k && k.startsWith(this.prefix)) {
|
|
68
|
+
result.push(k.slice(this.prefix.length));
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
return result;
|
|
72
|
+
}
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
// src/storage/LocalForageAdapter.ts
|
|
76
|
+
import localforage from "localforage";
|
|
77
|
+
var LocalForageAdapter = class {
|
|
78
|
+
constructor(options = {}) {
|
|
79
|
+
this.supportsEnumeration = true;
|
|
80
|
+
const {
|
|
81
|
+
name = "squisq",
|
|
82
|
+
storeName = "data",
|
|
83
|
+
prefix = "",
|
|
84
|
+
description = "Squisq storage"
|
|
85
|
+
} = options;
|
|
86
|
+
this.prefix = prefix;
|
|
87
|
+
this.store = localforage.createInstance({ name, storeName, description });
|
|
88
|
+
}
|
|
89
|
+
async get(key) {
|
|
90
|
+
try {
|
|
91
|
+
const value = await this.store.getItem(this.prefix + key);
|
|
92
|
+
return value;
|
|
93
|
+
} catch (e) {
|
|
94
|
+
console.warn("[Storage] get (IndexedDB) failed:", key, e);
|
|
95
|
+
return null;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
async set(key, value) {
|
|
99
|
+
try {
|
|
100
|
+
await this.store.setItem(this.prefix + key, value);
|
|
101
|
+
} catch (e) {
|
|
102
|
+
console.error("[Storage] set (IndexedDB) failed:", key, e);
|
|
103
|
+
throw e;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
async remove(key) {
|
|
107
|
+
try {
|
|
108
|
+
await this.store.removeItem(this.prefix + key);
|
|
109
|
+
} catch (e) {
|
|
110
|
+
console.warn("[Storage] remove (IndexedDB) failed:", key, e);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
async clear() {
|
|
114
|
+
try {
|
|
115
|
+
if (this.prefix) {
|
|
116
|
+
const keys = await this.store.keys();
|
|
117
|
+
const keysToRemove = keys.filter((k) => k.startsWith(this.prefix));
|
|
118
|
+
await Promise.all(keysToRemove.map((k) => this.store.removeItem(k)));
|
|
119
|
+
} else {
|
|
120
|
+
await this.store.clear();
|
|
121
|
+
}
|
|
122
|
+
} catch (e) {
|
|
123
|
+
console.error("[Storage] clear (IndexedDB) failed:", e);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
async keys() {
|
|
127
|
+
try {
|
|
128
|
+
const allKeys = await this.store.keys();
|
|
129
|
+
if (this.prefix) {
|
|
130
|
+
return allKeys.filter((k) => k.startsWith(this.prefix)).map((k) => k.slice(this.prefix.length));
|
|
131
|
+
}
|
|
132
|
+
return allKeys;
|
|
133
|
+
} catch (e) {
|
|
134
|
+
console.warn("[Storage] keys (IndexedDB) failed:", e);
|
|
135
|
+
return [];
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
};
|
|
139
|
+
|
|
140
|
+
// src/storage/ContentContainer.ts
|
|
141
|
+
var MARKDOWN_PRIORITY = ["index.md", "doc.md", "document.md"];
|
|
142
|
+
function findDocumentPath(entries) {
|
|
143
|
+
const rootFiles = entries.filter((e) => !e.path.includes("/"));
|
|
144
|
+
for (const name of MARKDOWN_PRIORITY) {
|
|
145
|
+
if (rootFiles.some((e) => e.path.toLowerCase() === name)) {
|
|
146
|
+
return name;
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
const firstMd = rootFiles.find((e) => e.path.toLowerCase().endsWith(".md"));
|
|
150
|
+
return firstMd?.path ?? null;
|
|
151
|
+
}
|
|
152
|
+
var MemoryContentContainer = class {
|
|
153
|
+
constructor() {
|
|
154
|
+
this.files = /* @__PURE__ */ new Map();
|
|
155
|
+
}
|
|
156
|
+
async readFile(path) {
|
|
157
|
+
return this.files.get(path)?.data ?? null;
|
|
158
|
+
}
|
|
159
|
+
async writeFile(path, data, mimeType) {
|
|
160
|
+
const buffer = data instanceof ArrayBuffer ? data : data.slice().buffer;
|
|
161
|
+
this.files.set(path, {
|
|
162
|
+
data: buffer,
|
|
163
|
+
mimeType: mimeType ?? guessMimeType(path)
|
|
164
|
+
});
|
|
165
|
+
}
|
|
166
|
+
async removeFile(path) {
|
|
167
|
+
this.files.delete(path);
|
|
168
|
+
}
|
|
169
|
+
async listFiles(prefix) {
|
|
170
|
+
const entries = [];
|
|
171
|
+
for (const [path, file] of this.files) {
|
|
172
|
+
if (prefix && !path.startsWith(prefix)) continue;
|
|
173
|
+
entries.push({
|
|
174
|
+
path,
|
|
175
|
+
mimeType: file.mimeType,
|
|
176
|
+
size: file.data.byteLength
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
return entries;
|
|
180
|
+
}
|
|
181
|
+
async exists(path) {
|
|
182
|
+
return this.files.has(path);
|
|
183
|
+
}
|
|
184
|
+
async getDocumentPath() {
|
|
185
|
+
return findDocumentPath(await this.listFiles());
|
|
186
|
+
}
|
|
187
|
+
async readDocument() {
|
|
188
|
+
const docPath = await this.getDocumentPath();
|
|
189
|
+
if (!docPath) return null;
|
|
190
|
+
const data = await this.readFile(docPath);
|
|
191
|
+
if (!data) return null;
|
|
192
|
+
return new TextDecoder().decode(data);
|
|
193
|
+
}
|
|
194
|
+
async writeDocument(markdown, filename) {
|
|
195
|
+
const name = filename ?? "index.md";
|
|
196
|
+
const data = new TextEncoder().encode(markdown);
|
|
197
|
+
await this.writeFile(name, data, "text/markdown");
|
|
198
|
+
}
|
|
199
|
+
};
|
|
200
|
+
var EXTENSION_MIME_MAP = {
|
|
201
|
+
".md": "text/markdown",
|
|
202
|
+
".txt": "text/plain",
|
|
203
|
+
".json": "application/json",
|
|
204
|
+
".jpg": "image/jpeg",
|
|
205
|
+
".jpeg": "image/jpeg",
|
|
206
|
+
".png": "image/png",
|
|
207
|
+
".gif": "image/gif",
|
|
208
|
+
".svg": "image/svg+xml",
|
|
209
|
+
".webp": "image/webp",
|
|
210
|
+
".avif": "image/avif",
|
|
211
|
+
".mp4": "video/mp4",
|
|
212
|
+
".webm": "video/webm",
|
|
213
|
+
".mp3": "audio/mpeg",
|
|
214
|
+
".wav": "audio/wav",
|
|
215
|
+
".ogg": "audio/ogg",
|
|
216
|
+
".css": "text/css",
|
|
217
|
+
".html": "text/html",
|
|
218
|
+
".js": "application/javascript"
|
|
219
|
+
};
|
|
220
|
+
function guessMimeType(path) {
|
|
221
|
+
const dot = path.lastIndexOf(".");
|
|
222
|
+
if (dot === -1) return "application/octet-stream";
|
|
223
|
+
const ext = path.slice(dot).toLowerCase();
|
|
224
|
+
return EXTENSION_MIME_MAP[ext] ?? "application/octet-stream";
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
// src/storage/MediaProviderFromContainer.ts
|
|
228
|
+
function createMediaProviderFromContainer(container) {
|
|
229
|
+
const blobUrlCache = /* @__PURE__ */ new Map();
|
|
230
|
+
return {
|
|
231
|
+
async resolveUrl(relativePath) {
|
|
232
|
+
const cached = blobUrlCache.get(relativePath);
|
|
233
|
+
if (cached) return cached;
|
|
234
|
+
const data = await container.readFile(relativePath);
|
|
235
|
+
if (!data) return relativePath;
|
|
236
|
+
const entries = await container.listFiles();
|
|
237
|
+
const entry = entries.find((e) => e.path === relativePath);
|
|
238
|
+
const mimeType = entry?.mimeType ?? "application/octet-stream";
|
|
239
|
+
const blob = new Blob([data], { type: mimeType });
|
|
240
|
+
const url = URL.createObjectURL(blob);
|
|
241
|
+
blobUrlCache.set(relativePath, url);
|
|
242
|
+
return url;
|
|
243
|
+
},
|
|
244
|
+
async listMedia() {
|
|
245
|
+
const entries = await container.listFiles();
|
|
246
|
+
return entries.filter((e) => !e.path.toLowerCase().endsWith(".md")).map((e) => ({
|
|
247
|
+
name: e.path,
|
|
248
|
+
mimeType: e.mimeType,
|
|
249
|
+
size: e.size
|
|
250
|
+
}));
|
|
251
|
+
},
|
|
252
|
+
async addMedia(name, data, mimeType) {
|
|
253
|
+
const cached = blobUrlCache.get(name);
|
|
254
|
+
if (cached) {
|
|
255
|
+
URL.revokeObjectURL(cached);
|
|
256
|
+
blobUrlCache.delete(name);
|
|
257
|
+
}
|
|
258
|
+
let buffer;
|
|
259
|
+
if (data instanceof Blob) {
|
|
260
|
+
buffer = await data.arrayBuffer();
|
|
261
|
+
} else {
|
|
262
|
+
buffer = data;
|
|
263
|
+
}
|
|
264
|
+
await container.writeFile(name, buffer, mimeType);
|
|
265
|
+
return name;
|
|
266
|
+
},
|
|
267
|
+
async removeMedia(relativePath) {
|
|
268
|
+
const cached = blobUrlCache.get(relativePath);
|
|
269
|
+
if (cached) {
|
|
270
|
+
URL.revokeObjectURL(cached);
|
|
271
|
+
blobUrlCache.delete(relativePath);
|
|
272
|
+
}
|
|
273
|
+
await container.removeFile(relativePath);
|
|
274
|
+
},
|
|
275
|
+
dispose() {
|
|
276
|
+
for (const url of blobUrlCache.values()) {
|
|
277
|
+
URL.revokeObjectURL(url);
|
|
278
|
+
}
|
|
279
|
+
blobUrlCache.clear();
|
|
280
|
+
}
|
|
281
|
+
};
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
export {
|
|
285
|
+
MemoryStorageAdapter,
|
|
286
|
+
LocalStorageAdapter,
|
|
287
|
+
LocalForageAdapter,
|
|
288
|
+
findDocumentPath,
|
|
289
|
+
MemoryContentContainer,
|
|
290
|
+
createMediaProviderFromContainer
|
|
291
|
+
};
|
|
292
|
+
//# sourceMappingURL=chunk-4CRBS35L.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/storage/MemoryStorageAdapter.ts","../src/storage/LocalStorageAdapter.ts","../src/storage/LocalForageAdapter.ts","../src/storage/ContentContainer.ts","../src/storage/MediaProviderFromContainer.ts"],"sourcesContent":["/**\n * In-memory storage adapter for testing and SSR environments.\n * Data does not persist across page reloads.\n */\n\nimport type { StorageAdapter } from './Storage.js';\n\nexport class MemoryStorageAdapter implements StorageAdapter {\n readonly supportsEnumeration = true;\n private store = new Map<string, string>();\n\n async get<T>(key: string): Promise<T | null> {\n const val = this.store.get(key);\n if (val === undefined) return null;\n try {\n return JSON.parse(val) as T;\n } catch {\n return null;\n }\n }\n\n async set<T>(key: string, value: T): Promise<void> {\n this.store.set(key, JSON.stringify(value));\n }\n\n async remove(key: string): Promise<void> {\n this.store.delete(key);\n }\n\n async clear(): Promise<void> {\n this.store.clear();\n }\n\n async keys(): Promise<string[]> {\n return Array.from(this.store.keys());\n }\n}\n","/**\n * localStorage adapter for web browsers.\n * Supports a configurable key prefix to namespace stored data.\n */\n\nimport type { StorageAdapter } from './Storage.js';\n\nexport class LocalStorageAdapter implements StorageAdapter {\n readonly supportsEnumeration = true;\n private prefix: string;\n\n constructor(prefix = '') {\n this.prefix = prefix;\n }\n\n async get<T>(key: string): Promise<T | null> {\n try {\n const raw = localStorage.getItem(this.prefix + key);\n if (raw === null) return null;\n return JSON.parse(raw) as T;\n } catch {\n return null;\n }\n }\n\n async set<T>(key: string, value: T): Promise<void> {\n localStorage.setItem(this.prefix + key, JSON.stringify(value));\n }\n\n async remove(key: string): Promise<void> {\n localStorage.removeItem(this.prefix + key);\n }\n\n async clear(): Promise<void> {\n const keysToRemove: string[] = [];\n for (let i = 0; i < localStorage.length; i++) {\n const k = localStorage.key(i);\n if (k && k.startsWith(this.prefix)) {\n keysToRemove.push(k);\n }\n }\n for (const k of keysToRemove) {\n localStorage.removeItem(k);\n }\n }\n\n async keys(): Promise<string[]> {\n const result: string[] = [];\n for (let i = 0; i < localStorage.length; i++) {\n const k = localStorage.key(i);\n if (k && k.startsWith(this.prefix)) {\n result.push(k.slice(this.prefix.length));\n }\n }\n return result;\n }\n}\n","/**\n * LocalForage adapter - IndexedDB storage with automatic fallbacks.\n *\n * Uses localforage which provides IndexedDB storage with automatic\n * fallbacks to WebSQL and localStorage. This allows storing much more\n * data than raw localStorage (which is limited to ~5MB).\n *\n * Unlike LocalStorageAdapter, this adapter can store binary data\n * (ArrayBuffer, Blob, Uint8Array) natively without JSON serialization.\n *\n * Ported from qualla-internal/shared/services/StorageAdapters.ts with\n * configurable store name and key prefix.\n */\n\nimport localforage from 'localforage';\nimport type { StorageAdapter } from './Storage.js';\n\nexport interface LocalForageAdapterOptions {\n /** IndexedDB database name (default: 'squisq') */\n name?: string;\n /** IndexedDB object store name (default: 'data') */\n storeName?: string;\n /** Key prefix for namespacing (default: '') */\n prefix?: string;\n /** Human-readable description (default: 'Squisq storage') */\n description?: string;\n}\n\nexport class LocalForageAdapter implements StorageAdapter {\n readonly supportsEnumeration = true;\n private store: LocalForage;\n private prefix: string;\n\n constructor(options: LocalForageAdapterOptions = {}) {\n const {\n name = 'squisq',\n storeName = 'data',\n prefix = '',\n description = 'Squisq storage',\n } = options;\n\n this.prefix = prefix;\n this.store = localforage.createInstance({ name, storeName, description });\n }\n\n async get<T>(key: string): Promise<T | null> {\n try {\n const value = await this.store.getItem<T>(this.prefix + key);\n return value;\n } catch (e: unknown) {\n console.warn('[Storage] get (IndexedDB) failed:', key, e);\n return null;\n }\n }\n\n async set<T>(key: string, value: T): Promise<void> {\n try {\n await this.store.setItem(this.prefix + key, value);\n } catch (e: unknown) {\n console.error('[Storage] set (IndexedDB) failed:', key, e);\n throw e;\n }\n }\n\n async remove(key: string): Promise<void> {\n try {\n await this.store.removeItem(this.prefix + key);\n } catch (e: unknown) {\n console.warn('[Storage] remove (IndexedDB) failed:', key, e);\n }\n }\n\n async clear(): Promise<void> {\n try {\n if (this.prefix) {\n // Only remove keys with our prefix\n const keys = await this.store.keys();\n const keysToRemove = keys.filter((k) => k.startsWith(this.prefix));\n await Promise.all(keysToRemove.map((k) => this.store.removeItem(k)));\n } else {\n // No prefix — clear the entire store\n await this.store.clear();\n }\n } catch (e: unknown) {\n console.error('[Storage] clear (IndexedDB) failed:', e);\n }\n }\n\n async keys(): Promise<string[]> {\n try {\n const allKeys = await this.store.keys();\n if (this.prefix) {\n return allKeys\n .filter((k) => k.startsWith(this.prefix))\n .map((k) => k.slice(this.prefix.length));\n }\n return allKeys;\n } catch (e: unknown) {\n console.warn('[Storage] keys (IndexedDB) failed:', e);\n return [];\n }\n }\n}\n","/**\n * ContentContainer — virtual file system for document containers.\n *\n * A Squisq document is more than just markdown: it's a container of files\n * including the primary markdown document, images, audio, timing data, and\n * other media. ContentContainer provides an abstract async file system\n * interface for reading, writing, and listing these files.\n *\n * Paths are forward-slash separated strings relative to the container root\n * (e.g., 'images/hero.jpg', 'index.md'). No leading slash.\n *\n * Implementations:\n * - MemoryContentContainer — in-memory Map (for zip import, tests, transient use)\n * - SlotContentContainer — backed by IndexedDB slot storage (in the site package)\n */\n\n/**\n * Metadata about a file in a ContentContainer.\n */\nexport interface ContentEntry {\n /** Relative path within the container (e.g., 'images/hero.jpg') */\n path: string;\n /** MIME type (e.g., 'image/jpeg') */\n mimeType: string;\n /** File size in bytes */\n size: number;\n}\n\n/**\n * Abstract async file system for document containers.\n *\n * All paths are forward-slash separated, relative to the container root,\n * with no leading slash. Example: 'images/hero.jpg', 'index.md'.\n */\nexport interface ContentContainer {\n /** Read a file's binary content. Returns null if the file does not exist. */\n readFile(path: string): Promise<ArrayBuffer | null>;\n\n /** Write a file. Creates or overwrites. */\n writeFile(path: string, data: ArrayBuffer | Uint8Array, mimeType?: string): Promise<void>;\n\n /** Remove a file. No-op if the file does not exist. */\n removeFile(path: string): Promise<void>;\n\n /**\n * List files in the container.\n * @param prefix — Optional path prefix to filter by (e.g., 'images/')\n */\n listFiles(prefix?: string): Promise<ContentEntry[]>;\n\n /** Check whether a file exists. */\n exists(path: string): Promise<boolean>;\n\n /**\n * Find the primary markdown document path.\n *\n * Discovery order: index.md → doc.md → document.md → first *.md at root.\n * Returns null if no markdown file is found at the root level.\n */\n getDocumentPath(): Promise<string | null>;\n\n /**\n * Convenience: read the primary markdown document as a UTF-8 string.\n * Returns null if no markdown file is found.\n */\n readDocument(): Promise<string | null>;\n\n /**\n * Convenience: write a markdown document.\n * @param markdown — The markdown content\n * @param filename — Filename to use (defaults to 'index.md')\n */\n writeDocument(markdown: string, filename?: string): Promise<void>;\n}\n\n// ============================================\n// Well-known markdown filenames in priority order\n// ============================================\n\nconst MARKDOWN_PRIORITY = ['index.md', 'doc.md', 'document.md'];\n\n/**\n * Find the primary markdown path from a list of file entries.\n * Exported for reuse by other ContentContainer implementations.\n */\nexport function findDocumentPath(entries: ContentEntry[]): string | null {\n // Only consider root-level files (no '/' in path)\n const rootFiles = entries.filter((e) => !e.path.includes('/'));\n\n for (const name of MARKDOWN_PRIORITY) {\n if (rootFiles.some((e) => e.path.toLowerCase() === name)) {\n return name;\n }\n }\n\n // Fallback: first .md file at root\n const firstMd = rootFiles.find((e) => e.path.toLowerCase().endsWith('.md'));\n return firstMd?.path ?? null;\n}\n\n// ============================================\n// MemoryContentContainer\n// ============================================\n\ninterface MemoryFile {\n data: ArrayBuffer;\n mimeType: string;\n}\n\n/**\n * In-memory ContentContainer backed by a Map.\n *\n * Used for zip import (deserialize into memory), tests, and transient operations.\n */\nexport class MemoryContentContainer implements ContentContainer {\n private files = new Map<string, MemoryFile>();\n\n async readFile(path: string): Promise<ArrayBuffer | null> {\n return this.files.get(path)?.data ?? null;\n }\n\n async writeFile(path: string, data: ArrayBuffer | Uint8Array, mimeType?: string): Promise<void> {\n const buffer = data instanceof ArrayBuffer ? data : data.slice().buffer;\n this.files.set(path, {\n data: buffer,\n mimeType: mimeType ?? guessMimeType(path),\n });\n }\n\n async removeFile(path: string): Promise<void> {\n this.files.delete(path);\n }\n\n async listFiles(prefix?: string): Promise<ContentEntry[]> {\n const entries: ContentEntry[] = [];\n for (const [path, file] of this.files) {\n if (prefix && !path.startsWith(prefix)) continue;\n entries.push({\n path,\n mimeType: file.mimeType,\n size: file.data.byteLength,\n });\n }\n return entries;\n }\n\n async exists(path: string): Promise<boolean> {\n return this.files.has(path);\n }\n\n async getDocumentPath(): Promise<string | null> {\n return findDocumentPath(await this.listFiles());\n }\n\n async readDocument(): Promise<string | null> {\n const docPath = await this.getDocumentPath();\n if (!docPath) return null;\n const data = await this.readFile(docPath);\n if (!data) return null;\n return new TextDecoder().decode(data);\n }\n\n async writeDocument(markdown: string, filename?: string): Promise<void> {\n const name = filename ?? 'index.md';\n const data = new TextEncoder().encode(markdown);\n await this.writeFile(name, data, 'text/markdown');\n }\n}\n\n// ============================================\n// MIME type guessing\n// ============================================\n\nconst EXTENSION_MIME_MAP: Record<string, string> = {\n '.md': 'text/markdown',\n '.txt': 'text/plain',\n '.json': 'application/json',\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.png': 'image/png',\n '.gif': 'image/gif',\n '.svg': 'image/svg+xml',\n '.webp': 'image/webp',\n '.avif': 'image/avif',\n '.mp4': 'video/mp4',\n '.webm': 'video/webm',\n '.mp3': 'audio/mpeg',\n '.wav': 'audio/wav',\n '.ogg': 'audio/ogg',\n '.css': 'text/css',\n '.html': 'text/html',\n '.js': 'application/javascript',\n};\n\nfunction guessMimeType(path: string): string {\n const dot = path.lastIndexOf('.');\n if (dot === -1) return 'application/octet-stream';\n const ext = path.slice(dot).toLowerCase();\n return EXTENSION_MIME_MAP[ext] ?? 'application/octet-stream';\n}\n","/**\n * MediaProviderFromContainer — bridges ContentContainer to MediaProvider.\n *\n * Creates a MediaProvider that resolves relative paths by reading binary data\n * from a ContentContainer and generating blob URLs. Blob URLs are cached and\n * revoked on dispose().\n *\n * This allows any ContentContainer (memory, slot-backed, zip-loaded) to be\n * used with existing rendering components (DocPlayer, ImageLayer, VideoLayer)\n * that consume MediaProvider.\n */\n\nimport type { MediaProvider, MediaEntry } from '../schemas/MediaProvider.js';\nimport type { ContentContainer } from './ContentContainer.js';\n\n/**\n * Create a MediaProvider backed by a ContentContainer.\n *\n * @param container — The ContentContainer to read/write media from\n * @returns A MediaProvider that resolves paths to blob URLs\n */\nexport function createMediaProviderFromContainer(container: ContentContainer): MediaProvider {\n const blobUrlCache = new Map<string, string>();\n\n return {\n async resolveUrl(relativePath: string): Promise<string> {\n const cached = blobUrlCache.get(relativePath);\n if (cached) return cached;\n\n const data = await container.readFile(relativePath);\n if (!data) return relativePath;\n\n const entries = await container.listFiles();\n const entry = entries.find((e) => e.path === relativePath);\n const mimeType = entry?.mimeType ?? 'application/octet-stream';\n\n const blob = new Blob([data], { type: mimeType });\n const url = URL.createObjectURL(blob);\n blobUrlCache.set(relativePath, url);\n return url;\n },\n\n async listMedia(): Promise<MediaEntry[]> {\n const entries = await container.listFiles();\n return entries\n .filter((e) => !e.path.toLowerCase().endsWith('.md'))\n .map((e) => ({\n name: e.path,\n mimeType: e.mimeType,\n size: e.size,\n }));\n },\n\n async addMedia(\n name: string,\n data: ArrayBuffer | Blob | Uint8Array,\n mimeType: string,\n ): Promise<string> {\n // Invalidate any cached blob URL for this path before overwriting\n const cached = blobUrlCache.get(name);\n if (cached) {\n URL.revokeObjectURL(cached);\n blobUrlCache.delete(name);\n }\n\n let buffer: ArrayBuffer | Uint8Array;\n if (data instanceof Blob) {\n buffer = await data.arrayBuffer();\n } else {\n buffer = data;\n }\n await container.writeFile(name, buffer, mimeType);\n return name;\n },\n\n async removeMedia(relativePath: string): Promise<void> {\n const cached = blobUrlCache.get(relativePath);\n if (cached) {\n URL.revokeObjectURL(cached);\n blobUrlCache.delete(relativePath);\n }\n await container.removeFile(relativePath);\n },\n\n dispose(): void {\n for (const url of blobUrlCache.values()) {\n URL.revokeObjectURL(url);\n }\n blobUrlCache.clear();\n },\n };\n}\n"],"mappings":";AAOO,IAAM,uBAAN,MAAqD;AAAA,EAArD;AACL,SAAS,sBAAsB;AAC/B,SAAQ,QAAQ,oBAAI,IAAoB;AAAA;AAAA,EAExC,MAAM,IAAO,KAAgC;AAC3C,UAAM,MAAM,KAAK,MAAM,IAAI,GAAG;AAC9B,QAAI,QAAQ,OAAW,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AA,QACX,MAAM,EAAE;AAAA,QACR,UAAU,EAAE;AAAA,QACZ,MAAM,EAAE;AAAA,MACV,EAAE;AAAA,IACN;AAAA,IAEA,MAAM,SACJ,MACA,MACA,UACiB;AAEjB,YAAM,SAAS,aAAa,IAAI,IAAI;AACpC,UAAI,QAAQ;AACV,YAAI,gBAAgB,MAAM;AAC1B,qBAAa,OAAO,IAAI;AAAA,MAC1B;AAEA,UAAI;AACJ,UAAI,gBAAgB,MAAM;AACxB,iBAAS,MAAM,KAAK,YAAY;AAAA,MAClC,OAAO;AACL,iBAAS;AAAA,MACX;AACA,YAAM,UAAU,UAAU,MAAM,QAAQ,QAAQ;AAChD,aAAO;AAAA,IACT;AAAA,IAEA,MAAM,YAAY,cAAqC;AACrD,YAAM,SAAS,aAAa,IAAI,YAAY;AAC5C,UAAI,QAAQ;AACV,YAAI,gBAAgB,MAAM;AAC1B,qBAAa,OAAO,YAAY;AAAA,MAClC;AACA,YAAM,UAAU,WAAW,YAAY;AAAA,IACzC;AAAA,IAEA,UAAgB;AACd,iBAAW,OAAO,aAAa,OAAO,GAAG;AACvC,YAAI,gBAAgB,GAAG;AAAA,MACzB;AACA,mBAAa,MAAM;AAAA,IACrB;AAAA,EACF;AACF;","names":[]}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import {
|
|
2
|
+
DEFAULT_WORDS_PER_SECOND,
|
|
3
|
+
countSpokenWords
|
|
4
|
+
} from "./chunk-3E5F2XMR.js";
|
|
5
|
+
|
|
6
|
+
// src/timing/readingTime.ts
|
|
7
|
+
var DEFAULT_READING_WPM = 200;
|
|
8
|
+
function estimateReadingTime(text, options) {
|
|
9
|
+
const configuredWpm = options?.wordsPerMinute;
|
|
10
|
+
const wpm = typeof configuredWpm === "number" && configuredWpm > 0 ? configuredWpm : DEFAULT_READING_WPM;
|
|
11
|
+
const words = text.split(/\s+/).filter((w) => w.length > 0).length;
|
|
12
|
+
const minutes = words / wpm;
|
|
13
|
+
return {
|
|
14
|
+
words,
|
|
15
|
+
minutes,
|
|
16
|
+
seconds: Math.round(minutes * 60)
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
function estimateNarrationTime(text, options) {
|
|
20
|
+
const providedWps = options?.wordsPerSecond;
|
|
21
|
+
const wps = typeof providedWps === "number" && providedWps > 0 ? providedWps : DEFAULT_WORDS_PER_SECOND;
|
|
22
|
+
const spokenWords = countSpokenWords(text);
|
|
23
|
+
const totalSeconds = spokenWords / wps;
|
|
24
|
+
return {
|
|
25
|
+
spokenWords,
|
|
26
|
+
minutes: totalSeconds / 60,
|
|
27
|
+
seconds: Math.round(totalSeconds)
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export {
|
|
32
|
+
estimateReadingTime,
|
|
33
|
+
estimateNarrationTime
|
|
34
|
+
};
|
|
35
|
+
//# sourceMappingURL=chunk-6YJPI6VI.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/timing/readingTime.ts"],"sourcesContent":["/**\n * Reading time estimation.\n *\n * Estimates how long it takes to read text silently vs. narrate it aloud.\n * Uses configurable words-per-minute rates.\n */\n\nimport { countSpokenWords, DEFAULT_WORDS_PER_SECOND } from './narrationTiming.js';\n\n/** Default silent reading rate (adults average ~200–250 WPM). */\nconst DEFAULT_READING_WPM = 200;\n\n/** Result of a reading-time estimate. */\nexport interface ReadingTimeEstimate {\n /** Number of words (plain word count, not spoken equivalents). */\n words: number;\n /** Estimated minutes (decimal). */\n minutes: number;\n /** Estimated seconds (rounded). */\n seconds: number;\n}\n\n/** Options for reading-time estimation. */\nexport interface ReadingTimeOptions {\n /** Words per minute for silent reading (default: 200). */\n wordsPerMinute?: number;\n}\n\n/**\n * Estimate silent reading time for a block of text.\n *\n * @param text - The text to estimate\n * @param options - Optional configuration\n * @returns Word count + time estimate\n */\nexport function estimateReadingTime(\n text: string,\n options?: ReadingTimeOptions,\n): ReadingTimeEstimate {\n const configuredWpm = options?.wordsPerMinute;\n const wpm =\n typeof configuredWpm === 'number' && configuredWpm > 0 ? configuredWpm : DEFAULT_READING_WPM;\n const words = text.split(/\\s+/).filter((w) => w.length > 0).length;\n const minutes = words / wpm;\n\n return {\n words,\n minutes,\n seconds: Math.round(minutes * 60),\n };\n}\n\n/** Result of a narration-time estimate. */\nexport interface NarrationTimeEstimate {\n /** Spoken word equivalents (numbers expanded, comma pauses added). */\n spokenWords: number;\n /** Estimated minutes (decimal). */\n minutes: number;\n /** Estimated seconds (rounded). */\n seconds: number;\n}\n\n/** Options for narration-time estimation. */\nexport interface NarrationTimeOptions {\n /** Words per second for narration (default: 2.5 ≈ 150 WPM). */\n wordsPerSecond?: number;\n}\n\n/**\n * Estimate narration (spoken) time for a block of text.\n *\n * Unlike silent reading, this accounts for numbers being spoken as\n * multiple words and pauses at commas.\n *\n * @param text - The text to estimate\n * @param options - Optional configuration\n * @returns Spoken word equivalents + time estimate\n */\nexport function estimateNarrationTime(\n text: string,\n options?: NarrationTimeOptions,\n): NarrationTimeEstimate {\n const providedWps = options?.wordsPerSecond;\n const wps =\n typeof providedWps === 'number' && providedWps > 0 ? providedWps : DEFAULT_WORDS_PER_SECOND;\n const spokenWords = countSpokenWords(text);\n const totalSeconds = spokenWords / wps;\n\n return {\n spokenWords,\n minutes: totalSeconds / 60,\n seconds: Math.round(totalSeconds),\n };\n}\n"],"mappings":";;;;;;AAUA,IAAM,sBAAsB;AAyBrB,SAAS,oBACd,MACA,SACqB;AACrB,QAAM,gBAAgB,SAAS;AAC/B,QAAM,MACJ,OAAO,kBAAkB,YAAY,gBAAgB,IAAI,gBAAgB;AAC3E,QAAM,QAAQ,KAAK,MAAM,KAAK,EAAE,OAAO,CAAC,MAAM,EAAE,SAAS,CAAC,EAAE;AAC5D,QAAM,UAAU,QAAQ;AAExB,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA,SAAS,KAAK,MAAM,UAAU,EAAE;AAAA,EAClC;AACF;AA4BO,SAAS,sBACd,MACA,SACuB;AACvB,QAAM,cAAc,SAAS;AAC7B,QAAM,MACJ,OAAO,gBAAgB,YAAY,cAAc,IAAI,cAAc;AACrE,QAAM,cAAc,iBAAiB,IAAI;AACzC,QAAM,eAAe,cAAc;AAEnC,SAAO;AAAA,IACL;AAAA,IACA,SAAS,eAAe;AAAA,IACxB,SAAS,KAAK,MAAM,YAAY;AAAA,EAClC;AACF;","names":[]}
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
// src/random/SeededRandom.ts
|
|
2
|
+
var SeededRandom = class _SeededRandom {
|
|
3
|
+
constructor(seed) {
|
|
4
|
+
this.state = seed >>> 0;
|
|
5
|
+
if (this.state === 0) {
|
|
6
|
+
this.state = 3735928559;
|
|
7
|
+
}
|
|
8
|
+
}
|
|
9
|
+
/** Random float in [0, 1). */
|
|
10
|
+
next() {
|
|
11
|
+
let t = this.state += 1831565813;
|
|
12
|
+
t = Math.imul(t ^ t >>> 15, t | 1);
|
|
13
|
+
t ^= t + Math.imul(t ^ t >>> 7, t | 61);
|
|
14
|
+
return ((t ^ t >>> 14) >>> 0) / 4294967296;
|
|
15
|
+
}
|
|
16
|
+
/** Random integer in [0, max). */
|
|
17
|
+
nextInt(max) {
|
|
18
|
+
return Math.floor(this.next() * max);
|
|
19
|
+
}
|
|
20
|
+
/** Random integer in [min, max). */
|
|
21
|
+
nextIntRange(min, max) {
|
|
22
|
+
return min + Math.floor(this.next() * (max - min));
|
|
23
|
+
}
|
|
24
|
+
/** Random boolean with given probability of `true` (default 0.5). */
|
|
25
|
+
nextBool(probability = 0.5) {
|
|
26
|
+
return this.next() < probability;
|
|
27
|
+
}
|
|
28
|
+
/** Pick a random element, or `undefined` if array is empty. */
|
|
29
|
+
pick(array) {
|
|
30
|
+
if (array.length === 0) return void 0;
|
|
31
|
+
return array[this.nextInt(array.length)];
|
|
32
|
+
}
|
|
33
|
+
/** Pick a random element; throws if empty. */
|
|
34
|
+
pickRequired(array) {
|
|
35
|
+
if (array.length === 0) {
|
|
36
|
+
throw new Error("Cannot pick from empty array");
|
|
37
|
+
}
|
|
38
|
+
return array[this.nextInt(array.length)];
|
|
39
|
+
}
|
|
40
|
+
/** Pick `count` unique random elements (fewer if array is smaller). */
|
|
41
|
+
pickMultiple(array, count) {
|
|
42
|
+
if (count >= array.length) {
|
|
43
|
+
return this.shuffle([...array]);
|
|
44
|
+
}
|
|
45
|
+
const result = [];
|
|
46
|
+
const available = [...array];
|
|
47
|
+
for (let i = 0; i < count && available.length > 0; i++) {
|
|
48
|
+
const index = this.nextInt(available.length);
|
|
49
|
+
result.push(available[index]);
|
|
50
|
+
available.splice(index, 1);
|
|
51
|
+
}
|
|
52
|
+
return result;
|
|
53
|
+
}
|
|
54
|
+
/** Fisher-Yates shuffle **in place**. Returns the same array. */
|
|
55
|
+
shuffle(array) {
|
|
56
|
+
for (let i = array.length - 1; i > 0; i--) {
|
|
57
|
+
const j = this.nextInt(i + 1);
|
|
58
|
+
[array[i], array[j]] = [array[j], array[i]];
|
|
59
|
+
}
|
|
60
|
+
return array;
|
|
61
|
+
}
|
|
62
|
+
/** Return a **new** shuffled copy. */
|
|
63
|
+
shuffled(array) {
|
|
64
|
+
return this.shuffle([...array]);
|
|
65
|
+
}
|
|
66
|
+
/** Weighted random selection. Returns `undefined` if items is empty. */
|
|
67
|
+
pickWeighted(items) {
|
|
68
|
+
if (items.length === 0) return void 0;
|
|
69
|
+
const totalWeight = items.reduce((sum, { weight }) => sum + weight, 0);
|
|
70
|
+
if (totalWeight <= 0) return items[0]?.item;
|
|
71
|
+
let random = this.next() * totalWeight;
|
|
72
|
+
for (const { item, weight } of items) {
|
|
73
|
+
random -= weight;
|
|
74
|
+
if (random <= 0) return item;
|
|
75
|
+
}
|
|
76
|
+
return items[items.length - 1]?.item;
|
|
77
|
+
}
|
|
78
|
+
/** Current internal state (for debugging / serialization). */
|
|
79
|
+
getState() {
|
|
80
|
+
return this.state;
|
|
81
|
+
}
|
|
82
|
+
/** Create an independent sub-stream keyed by a modifier. */
|
|
83
|
+
derive(modifier) {
|
|
84
|
+
const hash = typeof modifier === "string" ? hashString(modifier) : modifier >>> 0;
|
|
85
|
+
return new _SeededRandom(this.state ^ hash);
|
|
86
|
+
}
|
|
87
|
+
};
|
|
88
|
+
function hashString(str) {
|
|
89
|
+
let hash = 5381;
|
|
90
|
+
for (let i = 0; i < str.length; i++) {
|
|
91
|
+
hash = (hash << 5) + hash ^ str.charCodeAt(i);
|
|
92
|
+
}
|
|
93
|
+
return hash >>> 0;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export {
|
|
97
|
+
SeededRandom,
|
|
98
|
+
hashString
|
|
99
|
+
};
|
|
100
|
+
//# sourceMappingURL=chunk-FVTQSNR7.js.map
|
|
@@ -0,0 +1 @@
|
|
|
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 let hash = 5381;\n for (let i = 0; i < str.length; i++) {\n hash = ((hash << 5) + hash) ^ str.charCodeAt(i);\n }\n return hash >>> 0;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