@prose-reader/streamer 1.296.0 → 1.297.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.
@@ -1,7 +1,7 @@
1
- (function(f,m){typeof exports=="object"&&typeof module<"u"?m(exports,require("@prose-reader/shared"),require("@prose-reader/archive-parser"),require("xmldoc"),require("rxjs")):typeof define=="function"&&define.amd?define(["exports","@prose-reader/shared","@prose-reader/archive-parser","xmldoc","rxjs"],m):(f=typeof globalThis<"u"?globalThis:f||self,m(f["prose-streamer"]={},f.shared,f.archiveParser,f.xmldoc,f.rxjs))})(this,(function(f,m,y,T,c){"use strict";const I=(e,t)=>{const i=e.split(/(\d+)/),r=t.split(/(\d+)/);for(let n=0,o=i.length;n<o;n++)if(i[n]!==r[n])return i[n]?.match(/\d/)?+(i[n]||"")-+(r[n]||""):(i[n]||"").localeCompare(r[n]||"");return 1},w=e=>e.substring(e.lastIndexOf("/")+1)||e,L=e=>e.endsWith("/")?e.slice(0,-1):e,M=e=>{const t=e.lastIndexOf("/");return t>=0?e.substring(0,t):""},te=async(e,{orderByAlpha:t,name:i}={})=>{let r=e;return t&&(r=r.slice().sort((n,o)=>I(n.name,o.name))),{filename:i||"",records:r.map(n=>{const o=n.size,s=w(n.name);return n.isDir?{dir:!0,basename:s,uri:n.name,size:o}:{dir:n.isDir,basename:s,encodingFormat:m.detectMimeTypeFromName(n.name),uri:n.name,blob:async()=>new Blob([await n.data()],{type:m.detectMimeTypeFromName(n.name)??""}),string:async()=>{const a=await n.data();return String.fromCharCode.apply(null,Array.from(new Uint16Array(a)))},size:o}}),close:()=>Promise.resolve()}},h=m.Report.namespace("@prose-reader/streamer",!1,{color:"#ffae42"}),ne=e=>{const t={};for(const r of e){const n=r.split("/");let o=t;for(let s=0;s<n.length;s++){const a=n[s];a!==void 0&&(o[a]||(o[a]={}),o=o[a])}}const i=(r,n="")=>Object.keys(r).sort().map((o,s,a)=>{const d=s===a.length-1,p=n+(d?"└── ":"├── "),u=n+(d?" ":"│ "),g=r[o];return g&&Object.keys(g).length>0?`${p}${o}/
2
- ${i(g,u)}`:`${p}${o}`}).join(`
3
- `);return i(t)},re=async(e,{orderByAlpha:t,name:i}={})=>{let r=Object.values(e.files);t&&(r=r.slice().sort((o,s)=>I(o.name,s.name)));const n={filename:i||"",records:r.map(o=>{const s=o._data.uncompressedSize,a=w(o.name);return o.dir?{dir:!0,basename:a,uri:o.name,size:s}:{dir:!1,basename:w(o.name),uri:o.name,encodingFormat:m.detectMimeTypeFromName(o.name),blob:()=>o.async("blob"),string:()=>o.async("string"),...o.internalStream&&{stream:o.internalStream},size:o._data.uncompressedSize}}),close:()=>Promise.resolve()};if(h.log("Generated archive",n),process.env.NODE_ENV==="development"&&h.isEnabled()){const o=ne(r.map(s=>s.name));h.groupCollapsed(...h.getGroupArgs("Archive folder structure")),h.log(`
4
- ${o}`),h.groupEnd()}return n},ie=async(e,{name:t}={})=>{const i=await e.getFilesArray(),r={close:()=>e.close(),filename:t??"",records:i.map(n=>({dir:!1,basename:n.file.name,encodingFormat:m.detectMimeTypeFromName(n.file.name),size:n.file.size,uri:`${n.path}${n.file.name}`,blob:async()=>await n.file.extract(),string:async()=>(await n.file.extract()).text()}))};return h.log("Generated archive",r),r},oe=async(e,{mimeType:t,direction:i}={mimeType:"text/plain"})=>{const r=`
1
+ (function(m,h){typeof exports=="object"&&typeof module<"u"?h(exports,require("@prose-reader/shared"),require("@prose-reader/archive-parser"),require("xmldoc"),require("rxjs")):typeof define=="function"&&define.amd?define(["exports","@prose-reader/shared","@prose-reader/archive-parser","xmldoc","rxjs"],h):(m=typeof globalThis<"u"?globalThis:m||self,h(m["prose-streamer"]={},m.shared,m.archiveParser,m.xmldoc,m.rxjs))})(this,(function(m,h,b,I,c){"use strict";const S=(e,t)=>{const i=e.split(/(\d+)/),r=t.split(/(\d+)/);for(let n=0,o=i.length;n<o;n++)if(i[n]!==r[n])return i[n]?.match(/\d/)?+(i[n]||"")-+(r[n]||""):(i[n]||"").localeCompare(r[n]||"");return 1},$=e=>e.substring(e.lastIndexOf("/")+1)||e,R=e=>e.endsWith("/")?e.slice(0,-1):e,k=e=>{const t=e.lastIndexOf("/");return t>=0?e.substring(0,t):""},G=async(e,{orderByAlpha:t,name:i}={})=>{let r=e;return t&&(r=r.slice().sort((n,o)=>S(n.name,o.name))),{filename:i||"",records:r.map(n=>{const o=n.size,s=$(n.name);return n.isDir?{dir:!0,basename:s,uri:n.name,size:o}:{dir:n.isDir,basename:s,encodingFormat:h.detectMimeTypeFromName(n.name),uri:n.name,blob:async()=>new Blob([await n.data()],{type:h.detectMimeTypeFromName(n.name)??""}),string:async()=>{const a=await n.data();return String.fromCharCode.apply(null,Array.from(new Uint16Array(a)))},size:o}}),close:()=>Promise.resolve()}},g=h.Report.namespace("@prose-reader/streamer",!1,{color:"#ffae42"}),J=e=>{const t={};for(const r of e){const n=r.split("/");let o=t;for(let s=0;s<n.length;s++){const a=n[s];a!==void 0&&(o[a]||(o[a]={}),o=o[a])}}const i=(r,n="")=>Object.keys(r).sort().map((o,s,a)=>{const d=s===a.length-1,u=n+(d?"└── ":"├── "),p=n+(d?" ":"│ "),f=r[o];return f&&Object.keys(f).length>0?`${u}${o}/
2
+ ${i(f,p)}`:`${u}${o}`}).join(`
3
+ `);return i(t)},K=async(e,{orderByAlpha:t,name:i}={})=>{let r=Object.values(e.files);t&&(r=r.slice().sort((o,s)=>S(o.name,s.name)));const n={filename:i||"",records:r.map(o=>{const s=o._data.uncompressedSize,a=$(o.name);return o.dir?{dir:!0,basename:a,uri:o.name,size:s}:{dir:!1,basename:$(o.name),uri:o.name,encodingFormat:h.detectMimeTypeFromName(o.name),blob:()=>o.async("blob"),string:()=>o.async("string"),...o.internalStream&&{stream:o.internalStream},size:o._data.uncompressedSize}}),close:()=>Promise.resolve()};if(g.log("Generated archive",n),process.env.NODE_ENV==="development"&&g.isEnabled()){const o=J(r.map(s=>s.name));g.groupCollapsed(...g.getGroupArgs("Archive folder structure")),g.log(`
4
+ ${o}`),g.groupEnd()}return n},x=async(e,{name:t}={})=>{const i=await e.getFilesArray(),r={close:()=>e.close(),filename:t??"",records:i.map(n=>({dir:!1,basename:n.file.name,encodingFormat:h.detectMimeTypeFromName(n.file.name),size:n.file.size,uri:`${n.path}${n.file.name}`,blob:async()=>await n.file.extract(),string:async()=>(await n.file.extract()).text()}))};return g.log("Generated archive",r),r},Y=async(e,{mimeType:t,direction:i}={mimeType:"text/plain"})=>{const r=`
5
5
  <?xml version="1.0" encoding="UTF-8"?>
6
6
  <package xmlns="http://www.idpf.org/2007/opf" version="3.0" xml:lang="ja" prefix="rendition: http://www.idpf.org/vocab/rendition/#"
7
7
  unique-identifier="ootuya-id">
@@ -16,51 +16,24 @@ ${o}`),h.groupEnd()}return n},ie=async(e,{name:t}={})=>{const i=await e.getFiles
16
16
  <itemref idref="p01" />
17
17
  </spine>
18
18
  </package>
19
- `;return{filename:"content.txt",records:[{dir:!1,basename:w("generated.opf"),uri:"generated.opf",blob:async()=>new Blob([r]),string:async()=>r,size:0},{dir:!1,basename:w("p01.txt"),uri:"p01.txt",blob:async()=>typeof e=="string"?new Blob([e]):e,string:async()=>typeof e=="string"?e:e.text(),size:typeof e=="string"?e.length:e.size,encodingFormat:t}],close:()=>Promise.resolve()}},se=async(e,t)=>{const i=`
19
+ `;return{filename:"content.txt",records:[{dir:!1,basename:$("generated.opf"),uri:"generated.opf",blob:async()=>new Blob([r]),string:async()=>r,size:0},{dir:!1,basename:$("p01.txt"),uri:"p01.txt",blob:async()=>typeof e=="string"?new Blob([e]):e,string:async()=>typeof e=="string"?e:e.text(),size:typeof e=="string"?e.length:e.size,encodingFormat:t}],close:()=>Promise.resolve()}},Q=async(e,t)=>{const i=`
20
20
  <?xml version="1.0" encoding="UTF-8"?><package xmlns="http://www.idpf.org/2007/opf" version="2.0" unique-identifier="bookid">
21
21
  <metadata>
22
22
  <meta property="rendition:layout">${t?.useRenditionFlow?"reflowable":"pre-paginated"}</meta>
23
23
  ${t?.useRenditionFlow?'<meta property="rendition:flow">scrolled-continuous</meta>':""}
24
24
  </metadata>
25
25
  <manifest>
26
- ${e.map(o=>`<item id="${w(o)}" href="${o}" media-type="${m.detectMimeTypeFromName(o)}"/>`).join(`
26
+ ${e.map(o=>`<item id="${$(o)}" href="${o}" media-type="${h.detectMimeTypeFromName(o)}"/>`).join(`
27
27
  `)}
28
28
  </manifest>
29
29
  <spine>
30
- ${e.map(o=>`<itemref idref="${w(o)}" />`).join(`
30
+ ${e.map(o=>`<itemref idref="${$(o)}" />`).join(`
31
31
  `)}
32
32
  </spine>
33
33
  </package>
34
- `,r=e.map(o=>({dir:!1,basename:w(o),encodingFormat:m.detectMimeTypeFromName(o),uri:o,size:100/e.length,blob:async()=>(await fetch(o)).blob(),string:async()=>""}));return{filename:"",records:[{dir:!1,basename:"content.opf",uri:"content.opf",size:0,blob:async()=>new Blob,string:async()=>i},...r],close:()=>Promise.resolve()}},ae=({enableReport:e}={})=>{h.enable(!!e)},R=e=>{const i=Object.values(e.records).filter(r=>!r.dir).find(r=>r.uri.endsWith(".opf"));return{data:i,basePath:i?.uri.substring(0,i.uri.lastIndexOf("/"))||""}},C=e=>e.toLowerCase().endsWith(".opf"),W=e=>e.records.some(t=>!t.dir&&(C(t.basename)||C(t.uri))),N=({baseUrl:e="",resourcePath:t})=>{if(!e&&/^https?:\/\//.test(t))return encodeURI(t);const i=e?`${e}${e.endsWith("/")?"":"/"}`:"file://";return encodeURI(`${i}${t}`)},ce=2e3,O=e=>{const t=Number.parseInt(e,10);if(Number.isFinite(t)&&!(t<0||t>ce))return t},de=e=>{const t=/(?:^|[\s._(-]|\[)p\s*(\d{1,5})\s*[-_]\s*(?:p\s*)?(\d{1,5})(?=$|[^\d])/i.exec(e);return t||/(?:^|[\s._(]|\[)(0\d{1,4})\s*[-_]\s*(0\d{1,4})(?=$|[^\d])/i.exec(e)},le=e=>{const t=e.replace(/\.[^.]+$/,""),i=de(t);if(!i)return;const[,r,n]=i;if(r===void 0||n===void 0)return;const o=O(r),s=O(n);if(!(o===void 0||s===void 0)&&s===o+1)return{firstPageLabel:r,secondPageLabel:n}},k="__prose-reader__/page-spread",_="application/xhtml+xml",pe=new Set(["image/jpg","image/jpeg","image/png","image/webp"]),B=e=>e===void 0?!1:pe.has(e),ue=e=>encodeURIComponent(e),me=({cropSide:e,originalUri:t})=>`${k}/${ue(t)}/${e}.xhtml`,fe=e=>e==="left"?{pageSpreadLeft:!0,pageSpreadRight:void 0}:{pageSpreadLeft:void 0,pageSpreadRight:!0},he=e=>e==="rtl"?["right","left"]:["left","right"],U=({baseUrl:e,cropSide:t,label:i,originalSpineItem:r,originalUri:n,progressionWeight:o})=>{const s=me({cropSide:t,originalUri:n});return{...r,id:`${r.id}.${i}`,href:N({baseUrl:e,resourcePath:s}),mediaType:_,progressionWeight:o,renditionLayout:"pre-paginated",...fe(t)}},z=({href:e,id:t,mediaType:i})=>({href:e,id:t,mediaType:i}),ge=({archive:e,baseUrl:t,spineItem:i})=>{const r=[i.href,ye(i.href)],n=new Set(r.flatMap(o=>be(o,t)));return e.records.find(o=>!o.dir&&n.has(o.uri))},ye=e=>{try{return decodeURI(e)}catch{return e}},ve=e=>e.endsWith("/")?e:`${e}/`,be=(e,t)=>{const i=[e];if(e.startsWith("file://")&&i.push(e.slice(7)),t){const r=ve(t);e.startsWith(r)&&i.push(e.slice(r.length))}return i},we=e=>m.parseContentType(e?.encodingFormat??"")||m.detectMimeTypeFromName(e?.basename??""),$e=e=>m.detectMimeTypeFromName(e.uri)||m.detectMimeTypeFromName(e.basename),Se=e=>{if(e===void 0||e.dir)return!1;const t=$e(e);return B(t)?B(we(e)):!1},Fe=({archive:e,baseUrl:t})=>async i=>{if(W(e))return i;const r=[],n=i.spineItems.flatMap(o=>{const s=ge({archive:e,baseUrl:t,spineItem:o});if(!Se(s))return[o];const a=le(s.basename);if(a===void 0)return[o];const[d,p]=he(i.readingDirection),u=o.progressionWeight!==void 0?o.progressionWeight/2:void 0,g=U({baseUrl:t,cropSide:d,label:a.firstPageLabel,originalSpineItem:o,originalUri:s.uri,progressionWeight:u}),v=U({baseUrl:t,cropSide:p,label:a.secondPageLabel,originalSpineItem:o,originalUri:s.uri,progressionWeight:u});return r.push(z(g),z(v)),[g,v]});return r.length===0?i:{...i,spineItems:n.map((o,s)=>({...o,index:s})),items:[...i.items,...r]}};async function D(e){const{data:t,basePath:i}=R(e)||{};if(!t||t.dir)return;const r=await t.string();return{opf:y.parseOpf(r),basePath:i}}const Ae=y.APPLE_IBOOKS_DISPLAY_OPTIONS_FILENAME.toLowerCase(),Te=({archive:e})=>async t=>{const i=e.records.find(n=>!n.dir&&n.basename.toLowerCase()===Ae);if(!i||i.dir)return t;const r=await i.string();try{const n=y.parseAppleDisplayOptionsXml(r),{renditionLayout:o}=y.resolveArchiveMetadata(n);return{...t,renditionLayout:t.renditionLayout??o}}catch(n){return console.error(`Unable to parse ${y.APPLE_IBOOKS_DISPLAY_OPTIONS_FILENAME} for content
35
- `,r),console.error(n),t}},x=y.COMIC_INFO_FILENAME.toLowerCase(),Ie=({archive:e})=>async t=>{const i=e.records.find(o=>o.basename.toLowerCase()===x&&!o.dir);if(!i||i.dir)return t;const r={...t,spineItems:t.spineItems.filter(o=>!o.id.toLowerCase().endsWith(x)).map((o,s,a)=>({...o,progressionWeight:1/a.length}))},n=await i.string();try{const o=y.parseComicInfo(n),s=y.resolveArchiveMetadata(o);return{...r,readingDirection:s.readingDirection??"ltr"}}catch(o){return console.error(`Unable to parse ${y.COMIC_INFO_FILENAME} for content
36
- `,n),console.error(o),r}},Re=({archive:e,baseUrl:t})=>async()=>{const i=Object.values(e.records).filter(r=>!r.dir);return{filename:e.filename,title:e.records.find(({dir:r})=>r)?.basename.replace(/\/$/,"")||e.filename,renditionLayout:void 0,renditionSpread:"auto",readingDirection:"ltr",spineItems:i.filter(r=>!r.basename.endsWith(".db")).map((r,n)=>({id:`${n}.${r.basename}`,index:n,href:N({baseUrl:t,resourcePath:r.uri}),renditionLayout:void 0,progressionWeight:1/i.length,pageSpreadLeft:void 0,pageSpreadRight:void 0,mediaType:r.encodingFormat})),items:i.map((r,n)=>({id:`${n}.${r.basename}`,href:encodeURI(`${t}${r.uri}`)}))}},X=async({archive:e,archiveOpf:t})=>{if(!t)return[];const{opf:i,basePath:r}=t,{spineRows:n}=i;return e.records.filter(s=>n.find(a=>r?`${r}/${a.href}`===s.uri:`${a.href}`===s.uri))},V=(e,t,i)=>{const{basePath:r}=R(t)||{};return e.map(n=>{const o=n.href,s=i?.(o)??"";return{href:r?`${s}${r}/${o}`:`${s}${o}`,id:n.id,mediaType:n.mediaType}})},Le=e=>{const t=e?.trim();return t==="scrolled-continuous"||t==="scrolled-doc"||t==="paginated"||t==="auto"?t:"auto"},Ee=e=>{const t=e?.trim();if(t==="none"||t==="landscape"||t==="portrait"||t==="both"||t==="auto")return t},Pe=e=>{const t=e?.trim();if(t==="cover"||t==="title-page"||t==="copyright-page"||t==="text")return t},Me=({archive:e,baseUrl:t,archiveOpf:i})=>async r=>{if(!i)return r;const{opf:n,basePath:o}=i,s=y.resolveArchiveMetadata(n);h.groupCollapsed(...h.getGroupArgs("OPF parsed")),h.log("opf",n),h.groupEnd();const a=n.renditionLayoutMeta?.trim(),d=a==="reflowable"||a==="pre-paginated"?a:s.renditionLayout,p=n.title?.trim()||e.records.find(({dir:l})=>l)?.basename||"",u=s.readingDirection??"ltr",v=(await X({archive:e,archiveOpf:i})).reduce((l,F)=>F.size+l,0),$=n.guide,S=[];for(const l of $){const F=Pe(l.type);F!==void 0&&S.push({href:l.href,title:l.title,type:F})}return{filename:e.filename,renditionLayout:d,renditionFlow:Le(n.renditionFlowMeta),renditionSpread:Ee(n.renditionSpreadMeta),title:p,readingDirection:u,spineItems:n.spineRows.map((l,F)=>{const b=e.records.find(P=>P.uri.endsWith(l.href))?.size||0,A=t||(/^https?:\/\//.test(l.href)?"":"file://");return{id:l.id,index:F,href:l.href.startsWith("https://")?l.href:o?`${A}${o}/${l.href}`:`${A}${l.href}`,renditionLayout:l.renditionLayout??d,progressionWeight:b/v,pageSpreadLeft:l.pageSpreadLeft,pageSpreadRight:l.pageSpreadRight,mediaType:l.mediaType}}),items:V(n.manifestItems,e,l=>/^https?:\/\//.test(l)?"":t||"file://"),guide:S.length>0?S:void 0}},Ce=e=>{const t=e.descendantWithPath("head")?.childrenNamed("meta").find(i=>i.attr.name==="viewport");return!!(t&&t.attr.name==="viewport")},We=e=>e.reduce(async(t,i)=>{if(!await t||!m.isXmlBasedMimeType({mimeType:i.encodingFormat,uri:i.uri}))return!1;const n=i.dir?null:await i.string();return n?Ce(new T.XmlDocument(n)):!1},Promise.resolve(!0)),Ne=({archive:e,archiveOpf:t})=>async i=>{if(i.renditionLayout==="reflowable"&&i.spineItems.every(n=>n.renditionLayout==="reflowable")){const n=await X({archive:e,archiveOpf:t});if(await We(n))return{...i,spineItems:i.spineItems.map(s=>({...s,renditionLayout:"pre-paginated"})),renditionLayout:"pre-paginated"}}return i},Oe=async e=>{let t;return await Promise.all(e.records.map(async i=>{if(i.dir||!i.uri.endsWith(y.KOBO_DISPLAY_OPTIONS_FILENAME))return;const r=await i.string();try{const{renditionLayout:n}=y.parseKoboXml(r);n&&(t=n)}catch(n){console.error(`Unable to parse ${y.KOBO_DISPLAY_OPTIONS_FILENAME} for content
37
- `,r),console.error(n)}})),{kind:"kobo",...t!==void 0?{renditionLayout:t}:{}}},ke=({archive:e})=>async t=>{const i=await Oe(e),{renditionLayout:r}=y.resolveArchiveMetadata(i);return{...t,renditionLayout:t.renditionLayout??r}},_e=({archive:e})=>async t=>W(e)?t:{...t,spineItems:t.spineItems.map(r=>{const n=e.records.find(s=>decodeURI(r.href).endsWith(s.uri)),o=m.parseContentType(n?.encodingFormat??"")||m.detectMimeTypeFromName(n?.basename??"");return{...r,renditionLayout:o&&m.isMediaContentMimeType(o)?"pre-paginated":r.renditionLayout}})},H=e=>e?e.children.map(t=>t instanceof T.XmlTextNode?t.text:t instanceof T.XmlElement?H(t):"").join("").trim():"",Be=e=>y.tokenizeXmlSpaceSeparatedList(e.properties).includes("nav"),G=(e,{basePath:t,baseUrl:i})=>{const r={contents:[],path:"",href:"",title:""};let n=e.childNamed("span")||e.childNamed("a");r.title=(n?.attr.title||n?.val.trim()||H(n))??"";let o=n?.name;o!=="a"&&(n=e.descendantWithPath(`${o}.a`),n&&(o=n.name.toLowerCase())),o==="a"&&n?.attr.href&&(r.path=m.urlJoin(t,n.attr.href),r.href=m.urlJoin(i,t,n.attr.href));const s=e.childNamed("ol");if(s){const a=s.childrenNamed("li");a&&a.length>0&&(r.contents=a.map(d=>G(d,{basePath:t,baseUrl:i})))}return r},Ue=(e,{basePath:t,baseUrl:i})=>{const r=[];let n;return e.descendantWithPath("body.nav.ol")?n=e.descendantWithPath("body.nav.ol")?.children:e.descendantWithPath("body.section.nav.ol")&&(n=e.descendantWithPath("body.section.nav.ol")?.children),n&&n.length>0&&n.filter(o=>o.name==="li").forEach(o=>{r.push(G(o,{basePath:t,baseUrl:i}))}),r},ze=async(e,t,{baseUrl:i})=>{const r=e.manifestItems.find(Be);if(r?.href){const n=Object.values(t.records).find(o=>o.uri.endsWith(r.href));if(n&&!n.dir){const o=new T.XmlDocument(await n.string()),s=M(n.uri);return Ue(o,{basePath:s,baseUrl:i})}}},q=(e,{opfBasePath:t,baseUrl:i,prefix:r})=>{const n=e?.childNamed(`${r}content`)?.attr.src||"",o={title:e?.descendantWithPath(`${r}navLabel.${r}text`)?.val||"",path:m.urlJoin(t,n),href:m.urlJoin(i,t,n),contents:[]},s=e.childrenNamed(`${r}navPoint`);return s&&s.length>0&&(o.contents=s.map(a=>q(a,{opfBasePath:t,baseUrl:i,prefix:r}))),o},De=(e,{opfBasePath:t,baseUrl:i})=>{const r=[],n=e.name;let o="";return n.indexOf(":")!==-1&&(o=`${n.split(":")[0]}:`),e.childNamed(`${o}navMap`)?.childrenNamed(`${o}navPoint`).forEach(s=>{r.push(q(s,{opfBasePath:t,baseUrl:i,prefix:o}))}),r},xe=async({opf:e,opfBasePath:t,baseUrl:i,archive:r})=>{const n=e.spineTocIdref;if(n){const o=e.manifestItems.find(s=>s.id===n);if(o){const s=`${t}${t===""?"":"/"}${o.href}`,a=Object.values(r.records).find(d=>d.uri.endsWith(s));if(a&&!a.dir){const d=new T.XmlDocument(await a.string());return De(d,{opfBasePath:t,baseUrl:i})}}}},Xe=async(e,t,{baseUrl:i})=>{const{basePath:r}=R(t)||{},n=await ze(e,t,{baseUrl:i});if(n)return n;const o=await xe({opf:e,opfBasePath:r??"",archive:t,baseUrl:i});if(o)return o},Ve=e=>e.replace(/\.[^.]+$/,"").replace(/[_-]/g," ").replace(/\s+/g," ").trim(),He=(e,t)=>{if(!(e.spineItems.length===0||!e.spineItems.every(r=>(m.parseContentType(r.mediaType??"")||m.detectMimeTypeFromName(r.href))?.startsWith("audio/"))))return e.spineItems.map(r=>{const n=t.records.find(o=>!o.dir&&decodeURI(r.href).endsWith(o.uri));return{title:Ve(n?.basename??r.href),href:r.href,path:n?.uri??r.href,contents:[]}})},Ge=(e,{baseUrl:t})=>{const i=[...e.records].sort((n,o)=>I(n.uri,o.uri)),r=(n,o,s,a,d)=>{const p=n.find(v=>v.title===o),[u,...g]=s;return p?u?[...n.filter($=>$!==p),{...p,contents:[...p.contents,...r(p.contents,u,g,a,d)]}]:p.path.split("/").length>d.split("/").length?[...n.filter($=>$!==p),{...p,path:d,href:a}]:n:u?[...n,{contents:r([],u,g,a,d),href:a,path:d,title:o}]:[...n,{contents:[],href:a,path:d,title:o}]};return i.reduce((n,o)=>{if(o.dir)return n;const s=o.uri.split("/").slice(0,-1),[a,...d]=s;if(!a)return n;const p=m.urlJoin(t,encodeURI(o.uri)).replace(/\/$/,""),u=o.uri.replace(/\/$/,"");return r(n,a,d,p,u)},[])},qe=async(e,t,{baseUrl:i,archiveOpf:r})=>{if(r)return await Xe(r.opf,e,{baseUrl:i})||[];const n=He(t,e);if(n)return n;const o=Ge(e,{baseUrl:i});if(o.length!==0)return o},Je=({archive:e,baseUrl:t,archiveOpf:i})=>async r=>{if(r.nav)return r;const n=await qe(e,r,{baseUrl:t,archiveOpf:i});return n?{...r,nav:{toc:n}}:r},Ke=e=>e?e.endsWith("/")?e:`${e}/`:"",J=async(e,{baseUrl:t=""}={})=>{const i=await D(e),r=Ke(t),n=[Me({archive:e,baseUrl:r,archiveOpf:i}),Ie({archive:e}),Te({archive:e}),_e({archive:e}),Fe({archive:e,baseUrl:r}),Ne({archive:e,archiveOpf:i}),ke({archive:e}),Je({archive:e,baseUrl:r,archiveOpf:i})];try{const o=Re({archive:e,baseUrl:r})(),s=await n.reduce(async(a,d)=>await d(await a),o);if(h.log("Generated manifest",s),process.env.NODE_ENV==="development"&&h.isEnabled()){const a=JSON.stringify(s,null,2);h.groupCollapsed(...h.getGroupArgs("Generated manifest")),h.log(`
38
- ${a}`),h.groupEnd()}return s}catch(o){throw h.error(o),o}},E=new WeakMap,Ye=e=>{try{return decodeURIComponent(e)}catch{return}},Qe=e=>{const t=e.indexOf(`${k}/`);if(t<0)return;const r=e.slice(t).split("/"),n=r[2],o=r[3];if(r.length!==4||r[0]!=="__prose-reader__"||r[1]!=="page-spread"||n===void 0||o===void 0)return;const s=o.split(".")[0];if(s!=="left"&&s!=="right")return;const a=Ye(n);if(a!==void 0)return{originalUri:a,cropSide:s}},Ze=({cropSide:e,imageHeight:t,imageWidth:i})=>{const r=Math.floor(i/2),n=i-r;return e==="left"?{x:0,width:r,height:t}:{x:r,width:n,height:t}},je=e=>/^https?:\/\//.test(e)?e:`../../../${encodeURI(e)}`,et=async e=>{if(typeof createImageBitmap!="function")throw new Error("Page spread XHTML generation requires createImageBitmap");const t=await createImageBitmap(e);try{return{height:t.height,width:t.width}}finally{t.close()}},tt=({cropSide:e,imageDimensions:t,originalUri:i})=>{if(t.width<2)throw new Error("Page spread image is too narrow to split");const r=Ze({cropSide:e,imageHeight:t.height,imageWidth:t.width});return`<?xml version="1.0" encoding="UTF-8"?>
39
- <html xmlns="http://www.w3.org/1999/xhtml">
40
- <head>
41
- <meta name="viewport" content="width=${r.width}, height=${r.height}" />
42
- <style>
43
- html,
44
- body {
45
- width: ${r.width}px;
46
- height: ${r.height}px;
47
- margin: 0;
48
- overflow: hidden;
49
- }
50
-
51
- img {
52
- display: block;
53
- width: ${t.width}px;
54
- height: ${t.height}px;
55
- max-width: none;
56
- transform: translateX(-${r.x}px);
57
- user-select: none;
58
- -webkit-user-drag: none;
59
- }
60
- </style>
61
- </head>
62
- <body>
63
- <img src="${m.escapeXmlAttributeValue(je(i))}" alt="" />
64
- </body>
65
- </html>`},nt=async({archive:e,resourcePath:t})=>{const i=Qe(t);if(i===void 0)return;const r=e.records.find(a=>a.uri===i.originalUri&&!a.dir);if(r===void 0||r.dir)throw new Error(`no source file found for virtual page spread resourcePath:${t}`);const n=E.get(e)??new Map;E.has(e)||E.set(e,n);const o=n.get(i.originalUri)??await et(await r.blob());return n.set(i.originalUri,o),{body:tt({cropSide:i.cropSide,imageDimensions:o,originalUri:i.originalUri}),params:{contentType:_}}},rt=({archive:e,resourcePath:t})=>async i=>{const r=await nt({archive:e,resourcePath:t});return r===void 0?i:{...i,...r,params:{...i.params,...r.params}}},it=e=>{const t=e.descendantWithPath("head")?.childrenNamed("meta").find(i=>i.attr.name==="calibre:cover");return!!(t&&t.attr.name==="calibre:cover")},ot=e=>e.descendantWithPath("body")?.descendantWithPath("div")?.childrenNamed("svg")?.find(t=>t.attr.width==="100%"&&t.attr.preserveAspectRatio==="none"),st=({archive:e,resourcePath:t})=>async i=>{const r=Object.values(e.records).find(n=>n.uri===t&&!n.dir);if(r&&!r.dir&&r.basename.endsWith(".xhtml")){const n=typeof i.body=="string"?i.body:await r.string(),o=new T.XmlDocument(n);if(it(o)){const s=ot(o);return s&&delete s.attr.preserveAspectRatio,{...i,body:o?.toString()}}}return i},at=({archive:e,resourcePath:t})=>async i=>st({archive:e,resourcePath:t})(i),ct=({archive:e,resourcePath:t})=>async i=>{const r=Object.values(e.records).find(n=>n.uri===t&&!n.dir);if(r&&!r.dir&&r.basename.endsWith(".css")){const o=(typeof i.body=="string"?i.body:await r.string()).replaceAll("-webkit-writing-mode","writing-mode");return{...i,body:o}}return i},dt=async(e,t)=>{const i=await D(e);if(i){const{opf:r}=i,n=V(r.manifestItems,e,()=>"");if(n.find(s=>t.endsWith(s.href))?.mediaType)return{mediaType:n.find(s=>t.endsWith(s.href))?.mediaType}}return{mediaType:lt(t)}},lt=e=>{if(e.endsWith(".css"))return"text/css; charset=UTF-8";if(e.endsWith(".jpg"))return"image/jpg";if(e.endsWith(".xhtml"))return"application/xhtml+xml";if(e.endsWith(".mp4"))return"video/mp4";if(e.endsWith(".svg"))return"image/svg+xml"},pt=({archive:e,resourcePath:t})=>async i=>{const r=Object.values(e.records).find(o=>o.uri===t&&!o.dir);if(!r||r.dir)return i;const n=await dt(e,t);return{...i,params:{...i.params,...r?.encodingFormat&&{contentType:r.encodingFormat},...n.mediaType&&{contentType:n.mediaType}}}},K=["div","span","p","a","li","ul","ol","h1","h2","h3","h4","h5","h6","table","tr","td","th","thead","tbody","tfoot","section","article","header","footer","nav","aside","main","figure","figcaption","blockquote","pre","code","form","textarea","select","option","button","label","fieldset","legend","caption","dl","dt","dd","iframe","video","audio","canvas","script","style"],ut=({archive:e,resourcePath:t})=>async i=>{const r=Object.values(e.records).find(n=>n.uri===t&&!n.dir);if(r&&!r.dir&&r.basename.endsWith(".xhtml")){const n=typeof i.body=="string"?i.body:await r.string();if(!new RegExp(`<(${K.join("|")})[\\s/>]`,"i").test(n))return i;const s=new RegExp(`<(${K.join("|")})(\\s[^>]*)?\\s*/>`,"gi"),a=n.replace(s,(d,p,u="")=>`<${p} ${u.trim()}></${p}>`);return{...i,body:a}}return i},Y=async(e,t)=>{const i={params:{}},r=[rt({archive:e,resourcePath:t}),pt({archive:e,resourcePath:t}),ut({archive:e,resourcePath:t}),ct({archive:e,resourcePath:t}),at({archive:e,resourcePath:t})];try{const n=await r.reduce(async(s,a)=>await a(await s),Promise.resolve(i));if(h.log("Generated resource",t,n),n.body!==void 0)return n;const o=Object.values(e.records).find(s=>s.uri===t&&!s.dir);if(!o||o.dir)throw new Error(`no file found for resourcePath:${t}`);return{...n,body:await o.blob()}}catch(n){throw h.error(n),n}};class mt{constructor(t){this.cleanArchiveAfter=t,this.state$=new c.BehaviorSubject({status:"idle",locks:0})}update(t){this.state$.next({...this.state$.getValue(),...t})}get locks$(){return this.state$.pipe(c.map(({locks:t})=>t))}get state(){return this.state$.getValue()}get isUnlocked$(){return this.locks$.pipe(c.map(t=>t<=0),c.distinctUntilChanged(),c.shareReplay())}get overTTL$(){return this.isUnlocked$.pipe(c.switchMap(t=>t?this.cleanArchiveAfter===1/0?c.NEVER:c.timer(this.cleanArchiveAfter):c.NEVER))}}const ft=({getArchive:e,cleanArchiveAfter:t=300*1e3})=>{const i=new c.Subject,r=new c.Subject,n=new c.Subject,o={},s=i.pipe(c.mergeMap(p=>{const u=o[p];if(!u||u.state.status!=="idle")return c.EMPTY;let g=!1;const v=b=>{h.debug(`Cleaning up archive with key: ${b}`);const A=o[b];delete o[b],g||(A?.state.archive?.close(),g=!0)};u.update({status:"loading"});const $=u.locks$,S=u.isUnlocked$,l=$.pipe(c.pairwise(),c.filter(([b,A])=>A>b),c.startWith(!0));return c.from(e(p)).pipe(c.tap(b=>{u.update({archive:b,status:"success"})}),c.catchError(b=>(v(p),u.update({status:"error",error:b}),c.EMPTY)),c.switchMap(()=>{const b=l.pipe(c.switchMap(()=>n),c.switchMap(()=>S),c.filter(P=>P));return c.merge(b,u.overTTL$).pipe(c.first(),c.tap(()=>{v(p)}))}))}),c.takeUntil(r)),a=p=>{let u=!1;const g=o[p]??new mt(t);o[p]=g,g.update({locks:g.state.locks+1});const v=()=>{u||(u=!0,g.update({locks:g.state.locks-1}))};i.next(p);const $=g.state$.pipe(c.map(({archive:l})=>l),c.filter(l=>!!l)),S=g.state$.pipe(c.tap(({error:l})=>{if(l)throw l}),c.ignoreElements());return c.merge($,S).pipe(c.first(),c.map(l=>({archive:l,release:v})),c.catchError(l=>{throw v(),l}))},d=()=>{n.next()};return s.subscribe(),{access:a,purge:d,_archives:o}},Q=e=>e?/^\d+$/.test(e)?{valid:!0,value:Number.parseInt(e,10)}:{valid:!1,value:void 0}:{valid:!0,value:void 0},ht=e=>{if(!e.toLowerCase().startsWith("bytes="))return{kind:"missing"};const t=e.slice(6).trim();if(!t)return{kind:"invalid"};if(t.includes(","))return{kind:"multi"};const i=/^(\d*)-(\d*)$/.exec(t);if(!i)return{kind:"invalid"};const[,r="",n=""]=i,o=Q(r.trim()),s=Q(n.trim());return!o.valid||!s.valid?{kind:"invalid"}:{kind:"single",start:o.value,end:s.value}},gt=e=>{if(e instanceof Blob)return{size:e.size,slice:(i,r)=>{const n=e.slice(i,r);return{content:n,length:n.size}}};const t=new TextEncoder().encode(e);return{size:t.byteLength,slice:(i,r)=>{const n=t.slice(i,r);return{content:n,length:n.byteLength}}}},yt=({body:e,contentType:t,rangeHeader:i})=>{const r=new Headers;if(t&&r.set("Content-Type",t),r.set("Accept-Ranges","bytes"),!i)return e instanceof Blob&&r.set("Content-Length",String(e.size)),new Response(e,{status:200,headers:r});const n=ht(i);if(n.kind==="missing"||n.kind==="multi")return e instanceof Blob&&r.set("Content-Length",String(e.size)),new Response(e,{status:200,headers:r});const o=gt(e),s=o.size;if(n.kind==="invalid")return new Response(null,{status:416,headers:{"Content-Range":`bytes */${s}`}});let a=n.start,d=n.end;if(a===void 0&&d===void 0)return new Response(null,{status:416,headers:{"Content-Range":`bytes */${s}`}});if(a===void 0){const u=Math.min(d??0,s);a=Math.max(0,s-u),d=s-1}else(d===void 0||d>=s)&&(d=s-1);if(a<0||d<0||a>=s||d>=s||a>d)return new Response(null,{status:416,headers:{"Content-Range":`bytes */${s}`}});const p=o.slice(a,d+1);return r.set("Content-Length",String(p.length)),r.set("Content-Range",`bytes ${a}-${d}/${s}`),new Response(p.content,{status:206,headers:r})},Z="file://",vt=/^https?:\/\//,bt=e=>{try{return decodeURIComponent(e)}catch{return e}},j=e=>e.startsWith(Z)?e.slice(Z.length):e,wt=e=>{const t=j(e);return vt.test(t)?t:j(bt(t))};class ee{constructor({onError:t,onManifestSuccess:i,...r}){this.onError=n=>(console.error(n),new Response(String(n),{status:500})),this.archiveLoader=ft(r),this.onManifestSuccess=i??(({manifest:n})=>Promise.resolve(n)),this.onError=t??this.onError}prune(){this.archiveLoader.purge()}accessArchive(t){return this.lastAccessedKey!==void 0&&this.lastAccessedKey!==t&&this.archiveLoader.purge(),this.lastAccessedKey=t,this.archiveLoader.access(t)}accessArchiveWithoutLock(t){return this.accessArchive(t).pipe(c.map(({archive:i,release:r})=>(r(),i)))}withArchiveResponse({key:t,getResponse:i}){const r=this.accessArchive(t).pipe(c.mergeMap(({archive:n,release:o})=>c.from(i(n)).pipe(c.finalize(()=>{o()}))),c.catchError(n=>c.of(this.onError(n))));return c.lastValueFrom(r)}fetchManifest({key:t,baseUrl:i}){return this.withArchiveResponse({key:t,getResponse:r=>c.from(J(r,{baseUrl:i})).pipe(c.switchMap(o=>c.from(this.onManifestSuccess({manifest:o,archive:r}))),c.map(o=>new Response(JSON.stringify(o),{status:200})))})}fetchResource({key:t,resourcePath:i,request:r}){return this.withArchiveResponse({key:t,getResponse:n=>{const o=wt(i);return c.from(Y(n,o)).pipe(c.map(a=>yt({body:a.body??"",contentType:a.params.contentType,rangeHeader:r?.headers.get("range")})))}})}}class $t extends ee{constructor({getUriInfo:t,...i}){super(i),this.getUriInfo=t,this.fetchEventListener=this.fetchEventListener.bind(this)}fetchEventListener(t){try{const i=this.getUriInfo(t);if(!i)return;const r=L(i.baseUrl),n=t.request.url.substring(r.length+1),[o=""]=n.split("/"),s=L(n.substring(o.length+1));n.endsWith("/manifest")?t.respondWith(this.fetchManifest({key:o,baseUrl:`${r}/${o}/`})):t.respondWith(this.fetchResource({key:o,resourcePath:s,request:t.request}))}catch(i){t.respondWith(new Response(String(i),{status:500}))}}}f.ServiceWorkerStreamer=$t,f.Streamer=ee,f.configure=ae,f.createArchiveFromArrayBufferList=te,f.createArchiveFromJszip=re,f.createArchiveFromLibArchive=ie,f.createArchiveFromText=oe,f.createArchiveFromUrls=se,f.generateManifestFromArchive=J,f.generateResourceFromArchive=Y,f.getArchiveOpfInfo=R,f.getUriBasePath=M,f.getUriBasename=w,f.removeTrailingSlash=L,f.sortByTitleComparator=I,Object.defineProperty(f,Symbol.toStringTag,{value:"Module"})}));
34
+ `,r=e.map(o=>({dir:!1,basename:$(o),encodingFormat:h.detectMimeTypeFromName(o),uri:o,size:100/e.length,blob:async()=>(await fetch(o)).blob(),string:async()=>""}));return{filename:"",records:[{dir:!1,basename:"content.opf",uri:"content.opf",size:0,blob:async()=>new Blob,string:async()=>i},...r],close:()=>Promise.resolve()}},Z=({enableReport:e}={})=>{g.enable(!!e)},L=e=>{const i=Object.values(e.records).filter(r=>!r.dir).find(r=>r.uri.endsWith(".opf"));return{data:i,basePath:i?.uri.substring(0,i.uri.lastIndexOf("/"))||""}};async function C(e){const{data:t,basePath:i}=L(e)||{};if(!t||t.dir)return;const r=await t.string();return{opf:b.parseOpf(r),basePath:i}}const j=b.APPLE_IBOOKS_DISPLAY_OPTIONS_FILENAME.toLowerCase(),ee=({archive:e})=>async t=>{const i=e.records.find(n=>!n.dir&&n.basename.toLowerCase()===j);if(!i||i.dir)return t;const r=await i.string();try{const n=b.parseAppleDisplayOptionsXml(r),{renditionLayout:o}=b.resolveArchiveMetadata(n);return{...t,renditionLayout:t.renditionLayout??o}}catch(n){return console.error(`Unable to parse ${b.APPLE_IBOOKS_DISPLAY_OPTIONS_FILENAME} for content
35
+ `,r),console.error(n),t}},M=b.COMIC_INFO_FILENAME.toLowerCase(),te=({archive:e})=>async t=>{const i=e.records.find(o=>o.basename.toLowerCase()===M&&!o.dir);if(!i||i.dir)return t;const r={...t,spineItems:t.spineItems.filter(o=>!o.id.toLowerCase().endsWith(M)).map((o,s,a)=>({...o,progressionWeight:1/a.length}))},n=await i.string();try{const o=b.parseComicInfo(n),s=b.resolveArchiveMetadata(o);return{...r,readingDirection:s.readingDirection??"ltr"}}catch(o){return console.error(`Unable to parse ${b.COMIC_INFO_FILENAME} for content
36
+ `,n),console.error(o),r}},ne=({baseUrl:e="",resourcePath:t})=>{if(!e&&/^https?:\/\//.test(t))return encodeURI(t);const i=e?`${e}${e.endsWith("/")?"":"/"}`:"file://";return encodeURI(`${i}${t}`)},re=({archive:e,baseUrl:t})=>async()=>{const i=Object.values(e.records).filter(r=>!r.dir);return{filename:e.filename,title:e.records.find(({dir:r})=>r)?.basename.replace(/\/$/,"")||e.filename,renditionLayout:void 0,renditionSpread:"auto",readingDirection:"ltr",spineItems:i.filter(r=>!r.basename.endsWith(".db")).map((r,n)=>({id:`${n}.${r.basename}`,index:n,href:ne({baseUrl:t,resourcePath:r.uri}),renditionLayout:void 0,progressionWeight:1/i.length,pageSpreadLeft:void 0,pageSpreadRight:void 0,mediaType:r.encodingFormat})),items:i.map((r,n)=>({id:`${n}.${r.basename}`,href:encodeURI(`${t}${r.uri}`)}))}},W=async({archive:e,archiveOpf:t})=>{if(!t)return[];const{opf:i,basePath:r}=t,{spineRows:n}=i;return e.records.filter(s=>n.find(a=>r?`${r}/${a.href}`===s.uri:`${a.href}`===s.uri))},N=(e,t,i)=>{const{basePath:r}=L(t)||{};return e.map(n=>{const o=n.href,s=i?.(o)??"";return{href:r?`${s}${r}/${o}`:`${s}${o}`,id:n.id,mediaType:n.mediaType}})},oe=e=>{const t=e?.trim();return t==="scrolled-continuous"||t==="scrolled-doc"||t==="paginated"||t==="auto"?t:"auto"},ie=e=>{const t=e?.trim();if(t==="none"||t==="landscape"||t==="portrait"||t==="both"||t==="auto")return t},se=e=>{const t=e?.trim();if(t==="cover"||t==="title-page"||t==="copyright-page"||t==="text")return t},ae=({archive:e,baseUrl:t,archiveOpf:i})=>async r=>{if(!i)return r;const{opf:n,basePath:o}=i,s=b.resolveArchiveMetadata(n);g.groupCollapsed(...g.getGroupArgs("OPF parsed")),g.log("opf",n),g.groupEnd();const a=n.renditionLayoutMeta?.trim(),d=a==="reflowable"||a==="pre-paginated"?a:s.renditionLayout,u=n.title?.trim()||e.records.find(({dir:l})=>l)?.basename||"",p=s.readingDirection??"ltr",y=(await W({archive:e,archiveOpf:i})).reduce((l,A)=>A.size+l,0),v=n.guide,F=[];for(const l of v){const A=se(l.type);A!==void 0&&F.push({href:l.href,title:l.title,type:A})}return{filename:e.filename,renditionLayout:d,renditionFlow:oe(n.renditionFlowMeta),renditionSpread:ie(n.renditionSpreadMeta),title:u,readingDirection:p,spineItems:n.spineRows.map((l,A)=>{const w=e.records.find(E=>E.uri.endsWith(l.href))?.size||0,T=t||(/^https?:\/\//.test(l.href)?"":"file://");return{id:l.id,index:A,href:l.href.startsWith("https://")?l.href:o?`${T}${o}/${l.href}`:`${T}${l.href}`,renditionLayout:l.renditionLayout??d,...l.renditionFlow!==void 0?{renditionFlow:l.renditionFlow}:{},progressionWeight:w/y,pageSpreadLeft:l.pageSpreadLeft,pageSpreadRight:l.pageSpreadRight,mediaType:l.mediaType}}),items:N(n.manifestItems,e,l=>/^https?:\/\//.test(l)?"":t||"file://"),guide:F.length>0?F:void 0}},ce=e=>{const t=e.descendantWithPath("head")?.childrenNamed("meta").find(i=>i.attr.name==="viewport");return!!(t&&t.attr.name==="viewport")},de=e=>e.reduce(async(t,i)=>{if(!await t||!h.isXmlBasedMimeType({mimeType:i.encodingFormat,uri:i.uri}))return!1;const n=i.dir?null:await i.string();return n?ce(new I.XmlDocument(n)):!1},Promise.resolve(!0)),le=({archive:e,archiveOpf:t})=>async i=>{if(i.renditionLayout==="reflowable"&&i.spineItems.every(n=>n.renditionLayout==="reflowable")){const n=await W({archive:e,archiveOpf:t});if(await de(n))return{...i,spineItems:i.spineItems.map(s=>({...s,renditionLayout:"pre-paginated"})),renditionLayout:"pre-paginated"}}return i},ue=async e=>{let t;return await Promise.all(e.records.map(async i=>{if(i.dir||!i.uri.endsWith(b.KOBO_DISPLAY_OPTIONS_FILENAME))return;const r=await i.string();try{const{renditionLayout:n}=b.parseKoboXml(r);n&&(t=n)}catch(n){console.error(`Unable to parse ${b.KOBO_DISPLAY_OPTIONS_FILENAME} for content
37
+ `,r),console.error(n)}})),{kind:"kobo",...t!==void 0?{renditionLayout:t}:{}}},pe=({archive:e})=>async t=>{const i=await ue(e),{renditionLayout:r}=b.resolveArchiveMetadata(i);return{...t,renditionLayout:t.renditionLayout??r}},O=e=>e.toLowerCase().endsWith(".opf"),fe=e=>e.records.some(t=>!t.dir&&(O(t.basename)||O(t.uri))),me=({archive:e})=>async t=>fe(e)?t:{...t,spineItems:t.spineItems.map(r=>{const n=e.records.find(s=>decodeURI(r.href).endsWith(s.uri)),o=h.parseContentType(n?.encodingFormat??"")||h.detectMimeTypeFromName(n?.basename??"");return{...r,renditionLayout:o&&h.isMediaContentMimeType(o)?"pre-paginated":r.renditionLayout}})},P=e=>e?e.children.map(t=>t instanceof I.XmlTextNode?t.text:t instanceof I.XmlElement?P(t):"").join("").trim():"",he=e=>b.tokenizeXmlSpaceSeparatedList(e.properties).includes("nav"),B=(e,{basePath:t,baseUrl:i})=>{const r={contents:[],path:"",href:"",title:""};let n=e.childNamed("span")||e.childNamed("a");r.title=(n?.attr.title||n?.val.trim()||P(n))??"";let o=n?.name;o!=="a"&&(n=e.descendantWithPath(`${o}.a`),n&&(o=n.name.toLowerCase())),o==="a"&&n?.attr.href&&(r.path=h.urlJoin(t,n.attr.href),r.href=h.urlJoin(i,t,n.attr.href));const s=e.childNamed("ol");if(s){const a=s.childrenNamed("li");a&&a.length>0&&(r.contents=a.map(d=>B(d,{basePath:t,baseUrl:i})))}return r},ge=(e,{basePath:t,baseUrl:i})=>{const r=[];let n;return e.descendantWithPath("body.nav.ol")?n=e.descendantWithPath("body.nav.ol")?.children:e.descendantWithPath("body.section.nav.ol")&&(n=e.descendantWithPath("body.section.nav.ol")?.children),n&&n.length>0&&n.filter(o=>o.name==="li").forEach(o=>{r.push(B(o,{basePath:t,baseUrl:i}))}),r},ye=async(e,t,{baseUrl:i})=>{const r=e.manifestItems.find(he);if(r?.href){const n=Object.values(t.records).find(o=>o.uri.endsWith(r.href));if(n&&!n.dir){const o=new I.XmlDocument(await n.string()),s=k(n.uri);return ge(o,{basePath:s,baseUrl:i})}}},z=(e,{opfBasePath:t,baseUrl:i,prefix:r})=>{const n=e?.childNamed(`${r}content`)?.attr.src||"",o={title:e?.descendantWithPath(`${r}navLabel.${r}text`)?.val||"",path:h.urlJoin(t,n),href:h.urlJoin(i,t,n),contents:[]},s=e.childrenNamed(`${r}navPoint`);return s&&s.length>0&&(o.contents=s.map(a=>z(a,{opfBasePath:t,baseUrl:i,prefix:r}))),o},be=(e,{opfBasePath:t,baseUrl:i})=>{const r=[],n=e.name;let o="";return n.indexOf(":")!==-1&&(o=`${n.split(":")[0]}:`),e.childNamed(`${o}navMap`)?.childrenNamed(`${o}navPoint`).forEach(s=>{r.push(z(s,{opfBasePath:t,baseUrl:i,prefix:o}))}),r},ve=async({opf:e,opfBasePath:t,baseUrl:i,archive:r})=>{const n=e.spineTocIdref;if(n){const o=e.manifestItems.find(s=>s.id===n);if(o){const s=`${t}${t===""?"":"/"}${o.href}`,a=Object.values(r.records).find(d=>d.uri.endsWith(s));if(a&&!a.dir){const d=new I.XmlDocument(await a.string());return be(d,{opfBasePath:t,baseUrl:i})}}}},we=async(e,t,{baseUrl:i})=>{const{basePath:r}=L(t)||{},n=await ye(e,t,{baseUrl:i});if(n)return n;const o=await ve({opf:e,opfBasePath:r??"",archive:t,baseUrl:i});if(o)return o},$e=e=>e.replace(/\.[^.]+$/,"").replace(/[_-]/g," ").replace(/\s+/g," ").trim(),Fe=(e,t)=>{if(!(e.spineItems.length===0||!e.spineItems.every(r=>(h.parseContentType(r.mediaType??"")||h.detectMimeTypeFromName(r.href))?.startsWith("audio/"))))return e.spineItems.map(r=>{const n=t.records.find(o=>!o.dir&&decodeURI(r.href).endsWith(o.uri));return{title:$e(n?.basename??r.href),href:r.href,path:n?.uri??r.href,contents:[]}})},Ae=(e,{baseUrl:t})=>{const i=[...e.records].sort((n,o)=>S(n.uri,o.uri)),r=(n,o,s,a,d)=>{const u=n.find(y=>y.title===o),[p,...f]=s;return u?p?[...n.filter(v=>v!==u),{...u,contents:[...u.contents,...r(u.contents,p,f,a,d)]}]:u.path.split("/").length>d.split("/").length?[...n.filter(v=>v!==u),{...u,path:d,href:a}]:n:p?[...n,{contents:r([],p,f,a,d),href:a,path:d,title:o}]:[...n,{contents:[],href:a,path:d,title:o}]};return i.reduce((n,o)=>{if(o.dir)return n;const s=o.uri.split("/").slice(0,-1),[a,...d]=s;if(!a)return n;const u=h.urlJoin(t,encodeURI(o.uri)).replace(/\/$/,""),p=o.uri.replace(/\/$/,"");return r(n,a,d,u,p)},[])},Te=async(e,t,{baseUrl:i,archiveOpf:r})=>{if(r)return await we(r.opf,e,{baseUrl:i})||[];const n=Fe(t,e);if(n)return n;const o=Ae(e,{baseUrl:i});if(o.length!==0)return o},Ie=({archive:e,baseUrl:t,archiveOpf:i})=>async r=>{if(r.nav)return r;const n=await Te(e,r,{baseUrl:t,archiveOpf:i});return n?{...r,nav:{toc:n}}:r},Se=e=>e?e.endsWith("/")?e:`${e}/`:"",U=async(e,{baseUrl:t="",hooks:i={}}={})=>{const r=await C(e),n=Se(t),o=f=>(f??[]).map(y=>y({archive:e,baseUrl:n})),s=[ae({archive:e,baseUrl:n,archiveOpf:r}),te({archive:e}),ee({archive:e}),me({archive:e}),...o(i.content)],a=o(i.spine),d=[le({archive:e,archiveOpf:r}),pe({archive:e}),...o(i.presentation)],u=[Ie({archive:e,baseUrl:n,archiveOpf:r}),...o(i.navigation)],p=[...s,...a,...d,...u];try{const f=re({archive:e,baseUrl:n})(),y=await p.reduce(async(v,F)=>await F(await v),f);if(g.log("Generated manifest",y),process.env.NODE_ENV==="development"&&g.isEnabled()){const v=JSON.stringify(y,null,2);g.groupCollapsed(...g.getGroupArgs("Generated manifest")),g.log(`
38
+ ${v}`),g.groupEnd()}return y}catch(f){throw g.error(f),f}},Le=e=>{const t=e.descendantWithPath("head")?.childrenNamed("meta").find(i=>i.attr.name==="calibre:cover");return!!(t&&t.attr.name==="calibre:cover")},Re=e=>e.descendantWithPath("body")?.descendantWithPath("div")?.childrenNamed("svg")?.find(t=>t.attr.width==="100%"&&t.attr.preserveAspectRatio==="none"),Ee=({archive:e,resourcePath:t})=>async i=>{const r=Object.values(e.records).find(n=>n.uri===t&&!n.dir);if(r&&!r.dir&&r.basename.endsWith(".xhtml")){const n=typeof i.body=="string"?i.body:await r.string(),o=new I.XmlDocument(n);if(Le(o)){const s=Re(o);return s&&delete s.attr.preserveAspectRatio,{...i,body:o?.toString()}}}return i},ke=({archive:e,resourcePath:t})=>async i=>Ee({archive:e,resourcePath:t})(i),Ce=({archive:e,resourcePath:t})=>async i=>{const r=Object.values(e.records).find(n=>n.uri===t&&!n.dir);if(r&&!r.dir&&r.basename.endsWith(".css")){const o=(typeof i.body=="string"?i.body:await r.string()).replaceAll("-webkit-writing-mode","writing-mode");return{...i,body:o}}return i},Me=async(e,t)=>{const i=await C(e);if(i){const{opf:r}=i,n=N(r.manifestItems,e,()=>"");if(n.find(s=>t.endsWith(s.href))?.mediaType)return{mediaType:n.find(s=>t.endsWith(s.href))?.mediaType}}return{mediaType:We(t)}},We=e=>{if(e.endsWith(".css"))return"text/css; charset=UTF-8";if(e.endsWith(".jpg"))return"image/jpg";if(e.endsWith(".xhtml"))return"application/xhtml+xml";if(e.endsWith(".mp4"))return"video/mp4";if(e.endsWith(".svg"))return"image/svg+xml"},Ne=({archive:e,resourcePath:t})=>async i=>{const r=Object.values(e.records).find(o=>o.uri===t&&!o.dir);if(!r||r.dir)return i;const n=await Me(e,t);return{...i,params:{...i.params,...r?.encodingFormat&&{contentType:r.encodingFormat},...n.mediaType&&{contentType:n.mediaType}}}},_=["div","span","p","a","li","ul","ol","h1","h2","h3","h4","h5","h6","table","tr","td","th","thead","tbody","tfoot","section","article","header","footer","nav","aside","main","figure","figcaption","blockquote","pre","code","form","textarea","select","option","button","label","fieldset","legend","caption","dl","dt","dd","iframe","video","audio","canvas","script","style"],Oe=({archive:e,resourcePath:t})=>async i=>{const r=Object.values(e.records).find(n=>n.uri===t&&!n.dir);if(r&&!r.dir&&r.basename.endsWith(".xhtml")){const n=typeof i.body=="string"?i.body:await r.string();if(!new RegExp(`<(${_.join("|")})[\\s/>]`,"i").test(n))return i;const s=new RegExp(`<(${_.join("|")})(\\s[^>]*)?\\s*/>`,"gi"),a=n.replace(s,(d,u,p="")=>`<${u} ${p.trim()}></${u}>`);return{...i,body:a}}return i},D=async(e,t,{hooks:i=[]}={})=>{const r={params:{}},o=[...i.map(s=>s({archive:e,resourcePath:t})),Ne({archive:e,resourcePath:t}),Oe({archive:e,resourcePath:t}),Ce({archive:e,resourcePath:t}),ke({archive:e,resourcePath:t})];try{const s=await o.reduce(async(d,u)=>await u(await d),Promise.resolve(r));if(g.log("Generated resource",t,s),s.body!==void 0)return s;const a=Object.values(e.records).find(d=>d.uri===t&&!d.dir);if(!a||a.dir)throw new Error(`no file found for resourcePath:${t}`);return{...s,body:await a.blob()}}catch(s){throw g.error(s),s}};class Pe{constructor(t){this.cleanArchiveAfter=t,this.state$=new c.BehaviorSubject({status:"idle",locks:0})}update(t){this.state$.next({...this.state$.getValue(),...t})}get locks$(){return this.state$.pipe(c.map(({locks:t})=>t))}get state(){return this.state$.getValue()}get isUnlocked$(){return this.locks$.pipe(c.map(t=>t<=0),c.distinctUntilChanged(),c.shareReplay())}get overTTL$(){return this.isUnlocked$.pipe(c.switchMap(t=>t?this.cleanArchiveAfter===1/0?c.NEVER:c.timer(this.cleanArchiveAfter):c.NEVER))}}const Be=({getArchive:e,cleanArchiveAfter:t=300*1e3})=>{const i=new c.Subject,r=new c.Subject,n=new c.Subject,o={},s=i.pipe(c.mergeMap(u=>{const p=o[u];if(!p||p.state.status!=="idle")return c.EMPTY;let f=!1;const y=w=>{g.debug(`Cleaning up archive with key: ${w}`);const T=o[w];delete o[w],f||(T?.state.archive?.close(),f=!0)};p.update({status:"loading"});const v=p.locks$,F=p.isUnlocked$,l=v.pipe(c.pairwise(),c.filter(([w,T])=>T>w),c.startWith(!0));return c.from(e(u)).pipe(c.tap(w=>{p.update({archive:w,status:"success"})}),c.catchError(w=>(y(u),p.update({status:"error",error:w}),c.EMPTY)),c.switchMap(()=>{const w=l.pipe(c.switchMap(()=>n),c.switchMap(()=>F),c.filter(E=>E));return c.merge(w,p.overTTL$).pipe(c.first(),c.tap(()=>{y(u)}))}))}),c.takeUntil(r)),a=u=>{let p=!1;const f=o[u]??new Pe(t);o[u]=f,f.update({locks:f.state.locks+1});const y=()=>{p||(p=!0,f.update({locks:f.state.locks-1}))};i.next(u);const v=f.state$.pipe(c.map(({archive:l})=>l),c.filter(l=>!!l)),F=f.state$.pipe(c.tap(({error:l})=>{if(l)throw l}),c.ignoreElements());return c.merge(v,F).pipe(c.first(),c.map(l=>({archive:l,release:y})),c.catchError(l=>{throw y(),l}))},d=()=>{n.next()};return s.subscribe(),{access:a,purge:d,_archives:o}},H=e=>e?/^\d+$/.test(e)?{valid:!0,value:Number.parseInt(e,10)}:{valid:!1,value:void 0}:{valid:!0,value:void 0},ze=e=>{if(!e.toLowerCase().startsWith("bytes="))return{kind:"missing"};const t=e.slice(6).trim();if(!t)return{kind:"invalid"};if(t.includes(","))return{kind:"multi"};const i=/^(\d*)-(\d*)$/.exec(t);if(!i)return{kind:"invalid"};const[,r="",n=""]=i,o=H(r.trim()),s=H(n.trim());return!o.valid||!s.valid?{kind:"invalid"}:{kind:"single",start:o.value,end:s.value}},Ue=e=>{if(e instanceof Blob)return{size:e.size,slice:(i,r)=>{const n=e.slice(i,r);return{content:n,length:n.size}}};const t=new TextEncoder().encode(e);return{size:t.byteLength,slice:(i,r)=>{const n=t.slice(i,r);return{content:n,length:n.byteLength}}}},_e=({body:e,contentType:t,rangeHeader:i})=>{const r=new Headers;if(t&&r.set("Content-Type",t),r.set("Accept-Ranges","bytes"),!i)return e instanceof Blob&&r.set("Content-Length",String(e.size)),new Response(e,{status:200,headers:r});const n=ze(i);if(n.kind==="missing"||n.kind==="multi")return e instanceof Blob&&r.set("Content-Length",String(e.size)),new Response(e,{status:200,headers:r});const o=Ue(e),s=o.size;if(n.kind==="invalid")return new Response(null,{status:416,headers:{"Content-Range":`bytes */${s}`}});let a=n.start,d=n.end;if(a===void 0&&d===void 0)return new Response(null,{status:416,headers:{"Content-Range":`bytes */${s}`}});if(a===void 0){const p=Math.min(d??0,s);a=Math.max(0,s-p),d=s-1}else(d===void 0||d>=s)&&(d=s-1);if(a<0||d<0||a>=s||d>=s||a>d)return new Response(null,{status:416,headers:{"Content-Range":`bytes */${s}`}});const u=o.slice(a,d+1);return r.set("Content-Length",String(u.length)),r.set("Content-Range",`bytes ${a}-${d}/${s}`),new Response(u.content,{status:206,headers:r})},X="file://",De=/^https?:\/\//,He=e=>{try{return decodeURIComponent(e)}catch{return e}},V=e=>e.startsWith(X)?e.slice(X.length):e,Xe=e=>{const t=V(e);return De.test(t)?t:V(He(t))};class q{constructor({hooks:t,onError:i,onManifestSuccess:r,...n}){this.onError=o=>(console.error(o),new Response(String(o),{status:500})),this.archiveLoader=Be(n),this.hooks=t??{},this.onManifestSuccess=r??(({manifest:o})=>Promise.resolve(o)),this.onError=i??this.onError}prune(){this.archiveLoader.purge()}accessArchive(t){return this.lastAccessedKey!==void 0&&this.lastAccessedKey!==t&&this.archiveLoader.purge(),this.lastAccessedKey=t,this.archiveLoader.access(t)}accessArchiveWithoutLock(t){return this.accessArchive(t).pipe(c.map(({archive:i,release:r})=>(r(),i)))}withArchiveResponse({key:t,getResponse:i}){const r=this.accessArchive(t).pipe(c.mergeMap(({archive:n,release:o})=>c.from(i(n)).pipe(c.finalize(()=>{o()}))),c.catchError(n=>c.of(this.onError(n))));return c.lastValueFrom(r)}fetchManifest({key:t,baseUrl:i}){return this.withArchiveResponse({key:t,getResponse:r=>c.from(U(r,{baseUrl:i,hooks:this.hooks.manifest})).pipe(c.switchMap(o=>c.from(this.onManifestSuccess({manifest:o,archive:r}))),c.map(o=>new Response(JSON.stringify(o),{status:200})))})}fetchResource({key:t,resourcePath:i,request:r}){return this.withArchiveResponse({key:t,getResponse:n=>{const o=Xe(i);return c.from(D(n,o,{hooks:this.hooks.resource})).pipe(c.map(a=>_e({body:a.body??"",contentType:a.params.contentType,rangeHeader:r?.headers.get("range")})))}})}}class Ve extends q{constructor({getUriInfo:t,...i}){super(i),this.getUriInfo=t,this.fetchEventListener=this.fetchEventListener.bind(this)}fetchEventListener(t){try{const i=this.getUriInfo(t);if(!i)return;const r=R(i.baseUrl),n=t.request.url.substring(r.length+1),[o=""]=n.split("/"),s=R(n.substring(o.length+1));n.endsWith("/manifest")?t.respondWith(this.fetchManifest({key:o,baseUrl:`${r}/${o}/`})):t.respondWith(this.fetchResource({key:o,resourcePath:s,request:t.request}))}catch(i){t.respondWith(new Response(String(i),{status:500}))}}}m.ServiceWorkerStreamer=Ve,m.Streamer=q,m.configure=Z,m.createArchiveFromArrayBufferList=G,m.createArchiveFromJszip=K,m.createArchiveFromLibArchive=x,m.createArchiveFromText=Y,m.createArchiveFromUrls=Q,m.generateManifestFromArchive=U,m.generateResourceFromArchive=D,m.getArchiveOpfInfo=L,m.getUriBasePath=k,m.getUriBasename=$,m.removeTrailingSlash=R,m.sortByTitleComparator=S,Object.defineProperty(m,Symbol.toStringTag,{value:"Module"})}));
66
39
  //# sourceMappingURL=index.umd.cjs.map