@prose-reader/streamer 1.300.0 → 1.303.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/archives/createArchiveFromArrayBufferList.d.ts +2 -1
- package/dist/archives/createArchiveFromJszip.d.ts +2 -1
- package/dist/archives/createArchiveFromLibArchive.d.ts +2 -1
- package/dist/archives/getArchiveHasComicInfo.d.ts +2 -0
- package/dist/archives/types.d.ts +9 -3
- package/dist/epubs/getArchiveOpfInfo.d.ts +1 -10
- package/dist/epubs/getSpineItemFilesFromArchive.d.ts +1 -16
- package/dist/generators/manifest/hooks/finalDefaults.d.ts +2 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +394 -348
- package/dist/index.js.map +1 -1
- package/dist/index.umd.cjs +12 -12
- package/dist/index.umd.cjs.map +1 -1
- package/dist/utils/createXmlSafeId.d.ts +3 -0
- package/dist/utils/createXmlSafeId.test.d.ts +1 -0
- package/package.json +4 -4
package/dist/index.umd.cjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
(function(
|
|
2
|
-
${i(f
|
|
3
|
-
`);return i(t)},
|
|
4
|
-
${
|
|
1
|
+
(function(p,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):(p=typeof globalThis<"u"?globalThis:p||self,h(p["prose-streamer"]={},p.shared,p.archiveParser,p.xmldoc,p.rxjs))})(this,(function(p,h,y,T,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},A=e=>e.substring(e.lastIndexOf("/")+1)||e,E=e=>e.endsWith("/")?e.slice(0,-1):e,M=e=>{const t=e.lastIndexOf("/");return t>=0?e.substring(0,t):""},Z=async(e,{orderByAlpha:t,name:i,encodingFormat:r}={})=>{let n=e;return t&&(n=n.slice().sort((o,s)=>S(o.name,s.name))),{filename:i||"",encodingFormat:r,records:n.map(o=>{const s=o.size,a=A(o.name);return o.isDir?{dir:!0,basename:a,uri:o.name,size:s}:{dir:o.isDir,basename:a,encodingFormat:h.detectMimeTypeFromName(o.name),uri:o.name,blob:async()=>new Blob([await o.data()],{type:h.detectMimeTypeFromName(o.name)??""}),string:async()=>{const d=await o.data();return String.fromCharCode.apply(null,Array.from(new Uint16Array(d)))},size:s}}),close:()=>Promise.resolve()}},g=h.Report.namespace("@prose-reader/streamer",!1,{color:"#ffae42"}),Q=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,l=n+(d?"└── ":"├── "),f=n+(d?" ":"│ "),m=r[o];return m&&Object.keys(m).length>0?`${l}${o}/
|
|
2
|
+
${i(m,f)}`:`${l}${o}`}).join(`
|
|
3
|
+
`);return i(t)},j=async(e,{orderByAlpha:t,name:i,encodingFormat:r}={})=>{let n=Object.values(e.files);t&&(n=n.slice().sort((s,a)=>S(s.name,a.name)));const o={filename:i||"",encodingFormat:r,records:n.map(s=>{const a=s._data.uncompressedSize,d=A(s.name);return s.dir?{dir:!0,basename:d,uri:s.name,size:a}:{dir:!1,basename:A(s.name),uri:s.name,encodingFormat:h.detectMimeTypeFromName(s.name),blob:()=>s.async("blob"),string:()=>s.async("string"),...s.internalStream&&{stream:s.internalStream},size:s._data.uncompressedSize}}),close:()=>Promise.resolve()};if(g.log("Generated archive",o),process.env.NODE_ENV==="development"&&g.isEnabled()){const s=Q(n.map(a=>a.name));g.groupCollapsed(...g.getGroupArgs("Archive folder structure")),g.log(`
|
|
4
|
+
${s}`),g.groupEnd()}return o},ee=async(e,{name:t,encodingFormat:i}={})=>{const r=await e.getFilesArray(),n={close:()=>e.close(),filename:t??"",encodingFormat:i,records:r.map(o=>({dir:!1,basename:o.file.name,encodingFormat:h.detectMimeTypeFromName(o.file.name),size:o.file.size,uri:`${o.path}${o.file.name}`,blob:async()=>await o.file.extract(),string:async()=>(await o.file.extract()).text()}))};return g.log("Generated archive",n),n},te=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,24 +16,24 @@ ${o}`),g.groupEnd()}return n},x=async(e,{name:t}={})=>{const i=await e.getFilesA
|
|
|
16
16
|
<itemref idref="p01" />
|
|
17
17
|
</spine>
|
|
18
18
|
</package>
|
|
19
|
-
`;return{filename:"content.txt",records:[{dir:!1,basename
|
|
19
|
+
`;return{filename:"content.txt",encodingFormat:t,records:[{dir:!1,basename:A("generated.opf"),uri:"generated.opf",blob:async()=>new Blob([r]),string:async()=>r,size:0},{dir:!1,basename:A("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()}},ne=/^[A-Za-z0-9_][A-Za-z0-9_.-]*$/,re=/^[A-Za-z0-9_]/,k=/^xml/i,oe=/[^A-Za-z0-9_.-]+/g,N="_",ie=e=>e.replace(/^_+|_+$/g,""),se=e=>ie(e.trim().replaceAll("/","_").replace(oe,"_")),_=e=>{if(ne.test(e)&&!k.test(e))return e;const t=se(e),i=t&&!k.test(t)?t:`${N}${t}`;return re.test(i)?i:`${N}${i}`},W=(e,t)=>{const i=_(e);if(!t.has(i))return t.add(i),i;let r=2,n=`${i}-${r}`;for(;t.has(n);)r+=1,n=`${i}-${r}`;return t.add(n),n},R=()=>{const e=new Set;return t=>W(t,e)},ae=async(e,t)=>{const i=R(),r=e.map(a=>({id:i(a),url:a})),n=`
|
|
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
|
-
${
|
|
26
|
+
${r.map(({id:a,url:d})=>{const l=h.detectMimeTypeFromName(d);return`<item id="${a}" href="${h.escapeXmlAttributeValue(d)}" media-type="${h.escapeXmlAttributeValue(l??"")}"/>`}).join(`
|
|
27
27
|
`)}
|
|
28
28
|
</manifest>
|
|
29
29
|
<spine>
|
|
30
|
-
${
|
|
30
|
+
${r.map(({id:a})=>`<itemref idref="${a}" />`).join(`
|
|
31
31
|
`)}
|
|
32
32
|
</spine>
|
|
33
33
|
</package>
|
|
34
|
-
`,
|
|
35
|
-
`,r),console.error(n),t}},
|
|
36
|
-
`,n),console.error(o),r}},
|
|
37
|
-
`,r),console.error(n)}})),{kind:"kobo",...t!==void 0?{renditionLayout:t}:{}}},
|
|
38
|
-
${v}`),g.groupEnd()}return
|
|
34
|
+
`,o=e.map(a=>({dir:!1,basename:A(a),encodingFormat:h.detectMimeTypeFromName(a),uri:a,size:100/e.length,blob:async()=>(await fetch(a)).blob(),string:async()=>""}));return{filename:"",records:[{dir:!1,basename:"content.opf",uri:"content.opf",size:0,blob:async()=>new Blob,string:async()=>n},...o],close:()=>Promise.resolve()}},ce=e=>!e.dir,de=y.COMIC_INFO_FILENAME.toLowerCase(),O=e=>e.records.find(t=>ce(t)&&t.basename.toLowerCase()===de),le=({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 P(e){const{data:t,basePath:i}=L(e)||{};if(!t||t.dir)return;const r=await t.string();return{opf:y.parseOpf(r),basePath:i}}const ue=y.APPLE_IBOOKS_DISPLAY_OPTIONS_FILENAME.toLowerCase(),pe=({archive:e})=>async t=>{const i=e.records.find(n=>!n.dir&&n.basename.toLowerCase()===ue);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}},fe=y.COMIC_INFO_FILENAME.toLowerCase(),me=({archive:e})=>async t=>{const i=O(e);if(!i)return t;const r={...t,spineItems:t.spineItems.filter(o=>!o.id.toLowerCase().endsWith(fe)).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??r.readingDirection}}catch(o){return console.error(`Unable to parse ${y.COMIC_INFO_FILENAME} for content
|
|
36
|
+
`,n),console.error(o),r}},he=({baseUrl:e="",resourcePath:t})=>{if(!e&&/^https?:\/\//.test(t))return encodeURI(t);const i=e?`${e}${e.endsWith("/")?"":"/"}`:"file://";return encodeURI(`${i}${t}`)},ge=({archive:e,baseUrl:t})=>async()=>{const i=Object.values(e.records).filter(o=>!o.dir),r=R(),n=i.map(o=>({file:o,id:r(o.uri)}));return{filename:e.filename,title:e.records.find(({dir:o})=>o)?.basename.replace(/\/$/,"")||e.filename,renditionLayout:void 0,renditionSpread:"auto",readingDirection:void 0,spineItems:n.filter(({file:o})=>!o.basename.endsWith(".db")).map(({file:o,id:s},a)=>({id:s,index:a,href:he({baseUrl:t,resourcePath:o.uri}),renditionLayout:void 0,progressionWeight:1/i.length,pageSpreadLeft:void 0,pageSpreadRight:void 0,mediaType:o.encodingFormat})),items:n.map(({file:o,id:s})=>({id:s,href:encodeURI(`${t}${o.uri}`)}))}},z=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))},B=(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}})},ye=e=>{const t=e?.trim();return t==="scrolled-continuous"||t==="scrolled-doc"||t==="paginated"||t==="auto"?t:"auto"},be=e=>{const t=e?.trim();if(t==="none"||t==="landscape"||t==="portrait"||t==="both"||t==="auto")return t},ve=e=>{const t=e?.trim();if(t==="cover"||t==="title-page"||t==="copyright-page"||t==="text")return t},we=({archive:e,baseUrl:t,archiveOpf:i})=>async r=>{if(!i)return r;const{opf:n,basePath:o}=i,s=y.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,l=n.title?.trim()||e.records.find(({dir:u})=>u)?.basename||"",f=s.readingDirection??r.readingDirection,b=(await z({archive:e,archiveOpf:i})).reduce((u,F)=>F.size+u,0),v=n.guide,$=[];for(const u of v){const F=ve(u.type);F!==void 0&&$.push({href:u.href,title:u.title,type:F})}return{filename:e.filename,renditionLayout:d,renditionFlow:ye(n.renditionFlowMeta),renditionSpread:be(n.renditionSpreadMeta),title:l,readingDirection:f,spineItems:n.spineRows.map((u,F)=>{const w=e.records.find(C=>C.uri.endsWith(u.href))?.size||0,I=t||(/^https?:\/\//.test(u.href)?"":"file://");return{id:u.id,index:F,href:u.href.startsWith("https://")?u.href:o?`${I}${o}/${u.href}`:`${I}${u.href}`,renditionLayout:u.renditionLayout??d,...u.renditionFlow!==void 0?{renditionFlow:u.renditionFlow}:{},progressionWeight:w/b,pageSpreadLeft:u.pageSpreadLeft,pageSpreadRight:u.pageSpreadRight,mediaType:u.mediaType}}),items:B(n.manifestItems,e,u=>/^https?:\/\//.test(u)?"":t||"file://"),guide:$.length>0?$:void 0}},$e=e=>{const t=e.descendantWithPath("head")?.childrenNamed("meta").find(i=>i.attr.name==="viewport");return!!(t&&t.attr.name==="viewport")},Ae=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?$e(new T.XmlDocument(n)):!1},Promise.resolve(!0)),Fe=({archive:e,archiveOpf:t})=>async i=>{if(i.renditionLayout==="reflowable"&&i.spineItems.every(n=>n.renditionLayout==="reflowable")){const n=await z({archive:e,archiveOpf:t});if(await Ae(n))return{...i,spineItems:i.spineItems.map(s=>({...s,renditionLayout:"pre-paginated"})),renditionLayout:"pre-paginated"}}return i},Ie=()=>e=>({...e,readingDirection:e.readingDirection??"ltr"}),Te=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}:{}}},Se=({archive:e})=>async t=>{const i=await Te(e),{renditionLayout:r}=y.resolveArchiveMetadata(i);return{...t,renditionLayout:t.renditionLayout??r}},D=e=>e.toLowerCase().endsWith(".opf"),Le=e=>e.records.some(t=>!t.dir&&(D(t.basename)||D(t.uri))),Ee=({archive:e})=>async t=>Le(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}})},U=e=>e?e.children.map(t=>t instanceof T.XmlTextNode?t.text:t instanceof T.XmlElement?U(t):"").join("").trim():"",Re=e=>y.tokenizeXmlSpaceSeparatedList(e.properties).includes("nav"),X=(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()||U(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=>X(d,{basePath:t,baseUrl:i})))}return r},Ce=(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(X(o,{basePath:t,baseUrl:i}))}),r},Me=async(e,t,{baseUrl:i})=>{const r=e.manifestItems.find(Re);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 Ce(o,{basePath:s,baseUrl:i})}}},H=(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=>H(a,{opfBasePath:t,baseUrl:i,prefix:r}))),o},ke=(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(H(s,{opfBasePath:t,baseUrl:i,prefix:o}))}),r},Ne=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 ke(d,{opfBasePath:t,baseUrl:i})}}}},_e=async(e,t,{baseUrl:i})=>{const{basePath:r}=L(t)||{},n=await Me(e,t,{baseUrl:i});if(n)return n;const o=await Ne({opf:e,opfBasePath:r??"",archive:t,baseUrl:i});if(o)return o},We=e=>e.replace(/\.[^.]+$/,"").replace(/[_-]/g," ").replace(/\s+/g," ").trim(),Oe=(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:We(n?.basename??r.href),href:r.href,path:n?.uri??r.href,contents:[]}})},Pe=(e,{baseUrl:t})=>{const i=[...e.records].sort((n,o)=>S(n.uri,o.uri)),r=(n,o,s,a,d)=>{const l=n.find(b=>b.title===o),[f,...m]=s;return l?f?[...n.filter(v=>v!==l),{...l,contents:[...l.contents,...r(l.contents,f,m,a,d)]}]:l.path.split("/").length>d.split("/").length?[...n.filter(v=>v!==l),{...l,path:d,href:a}]:n:f?[...n,{contents:r([],f,m,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 l=h.urlJoin(t,encodeURI(o.uri)).replace(/\/$/,""),f=o.uri.replace(/\/$/,"");return r(n,a,d,l,f)},[])},ze=async(e,t,{baseUrl:i,archiveOpf:r})=>{if(r)return await _e(r.opf,e,{baseUrl:i})||[];const n=Oe(t,e);if(n)return n;const o=Pe(e,{baseUrl:i});if(o.length!==0)return o},Be=({archive:e,baseUrl:t,archiveOpf:i})=>async r=>{if(r.nav)return r;const n=await ze(e,r,{baseUrl:t,archiveOpf:i});return n?{...r,nav:{toc:n}}:r},De=e=>e?e.endsWith("/")?e:`${e}/`:"",V=async(e,{baseUrl:t="",hooks:i={}}={})=>{g.log("Generating manifest from archive",e);const r=await P(e),n=De(t),o=m=>(m??[]).map(b=>b({archive:e,baseUrl:n})),s=[we({archive:e,baseUrl:n,archiveOpf:r}),me({archive:e}),pe({archive:e}),Ee({archive:e}),...o(i.content)],a=o(i.spine),d=[Fe({archive:e,archiveOpf:r}),Se({archive:e}),...o(i.presentation)],l=[Be({archive:e,baseUrl:n,archiveOpf:r}),...o(i.navigation)],f=[...s,...a,...d,...l,Ie()];try{const m=ge({archive:e,baseUrl:n})(),b=await f.reduce(async(v,$)=>await $(await v),m);if(g.log("Generated manifest",b),process.env.NODE_ENV==="development"&&g.isEnabled()){const v=JSON.stringify(b,null,2);g.groupCollapsed(...g.getGroupArgs("Generated manifest")),g.log(`
|
|
38
|
+
${v}`),g.groupEnd()}return b}catch(m){throw g.error(m),m}},Ue=e=>{const t=e.descendantWithPath("head")?.childrenNamed("meta").find(i=>i.attr.name==="calibre:cover");return!!(t&&t.attr.name==="calibre:cover")},Xe=e=>e.descendantWithPath("body")?.descendantWithPath("div")?.childrenNamed("svg")?.find(t=>t.attr.width==="100%"&&t.attr.preserveAspectRatio==="none"),He=({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(Ue(o)){const s=Xe(o);return s&&delete s.attr.preserveAspectRatio,{...i,body:o?.toString()}}}return i},Ve=({archive:e,resourcePath:t})=>async i=>He({archive:e,resourcePath:t})(i),qe=({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},Ge=async(e,t)=>{const i=await P(e);if(i){const{opf:r}=i,n=B(r.manifestItems,e,()=>"");if(n.find(s=>t.endsWith(s.href))?.mediaType)return{mediaType:n.find(s=>t.endsWith(s.href))?.mediaType}}return{mediaType:Ke(t)}},Ke=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"},Je=({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 Ge(e,t);return{...i,params:{...i.params,...r?.encodingFormat&&{contentType:r.encodingFormat},...n.mediaType&&{contentType:n.mediaType}}}},q=["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"],xe=({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(`<(${q.join("|")})[\\s/>]`,"i").test(n))return i;const s=new RegExp(`<(${q.join("|")})(\\s[^>]*)?\\s*/>`,"gi"),a=n.replace(s,(d,l,f="")=>`<${l} ${f.trim()}></${l}>`);return{...i,body:a}}return i},G=async(e,t,{hooks:i=[]}={})=>{const r={params:{}},o=[...i.map(s=>s({archive:e,resourcePath:t})),Je({archive:e,resourcePath:t}),xe({archive:e,resourcePath:t}),qe({archive:e,resourcePath:t}),Ve({archive:e,resourcePath:t})];try{const s=await o.reduce(async(d,l)=>await l(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 Ye{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 Ze=({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(l=>{const f=o[l];if(!f||f.state.status!=="idle")return c.EMPTY;let m=!1;const b=w=>{g.debug(`Cleaning up archive with key: ${w}`);const I=o[w];delete o[w],m||(I?.state.archive?.close(),m=!0)};f.update({status:"loading"});const v=f.locks$,$=f.isUnlocked$,u=v.pipe(c.pairwise(),c.filter(([w,I])=>I>w),c.startWith(!0));return c.from(e(l)).pipe(c.tap(w=>{f.update({archive:w,status:"success"})}),c.catchError(w=>(b(l),f.update({status:"error",error:w}),c.EMPTY)),c.switchMap(()=>{const w=u.pipe(c.switchMap(()=>n),c.switchMap(()=>$),c.filter(C=>C));return c.merge(w,f.overTTL$).pipe(c.first(),c.tap(()=>{b(l)}))}))}),c.takeUntil(r)),a=l=>{let f=!1;const m=o[l]??new Ye(t);o[l]=m,m.update({locks:m.state.locks+1});const b=()=>{f||(f=!0,m.update({locks:m.state.locks-1}))};i.next(l);const v=m.state$.pipe(c.map(({archive:u})=>u),c.filter(u=>!!u)),$=m.state$.pipe(c.tap(({error:u})=>{if(u)throw u}),c.ignoreElements());return c.merge(v,$).pipe(c.first(),c.map(u=>({archive:u,release:b})),c.catchError(u=>{throw b(),u}))},d=()=>{n.next()};return s.subscribe(),{access:a,purge:d,_archives:o}},K=e=>e?/^\d+$/.test(e)?{valid:!0,value:Number.parseInt(e,10)}:{valid:!1,value:void 0}:{valid:!0,value:void 0},Qe=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=K(r.trim()),s=K(n.trim());return!o.valid||!s.valid?{kind:"invalid"}:{kind:"single",start:o.value,end:s.value}},je=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}}}},et=({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=Qe(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=je(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 f=Math.min(d??0,s);a=Math.max(0,s-f),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 l=o.slice(a,d+1);return r.set("Content-Length",String(l.length)),r.set("Content-Range",`bytes ${a}-${d}/${s}`),new Response(l.content,{status:206,headers:r})},J="file://",tt=/^https?:\/\//,nt=e=>{try{return decodeURIComponent(e)}catch{return e}},x=e=>e.startsWith(J)?e.slice(J.length):e,rt=e=>{const t=x(e);return tt.test(t)?t:x(nt(t))};class Y{constructor({hooks:t,onError:i,onManifestSuccess:r,...n}){this.onError=o=>(console.error(o),new Response(String(o),{status:500})),this.archiveLoader=Ze(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(V(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=rt(i);return c.from(G(n,o,{hooks:this.hooks.resource})).pipe(c.map(a=>et({body:a.body??"",contentType:a.params.contentType,rangeHeader:r?.headers.get("range")})))}})}}class ot extends Y{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=E(i.baseUrl),n=t.request.url.substring(r.length+1),[o=""]=n.split("/"),s=E(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}))}}}p.ServiceWorkerStreamer=ot,p.Streamer=Y,p.configure=le,p.createArchiveFromArrayBufferList=Z,p.createArchiveFromJszip=j,p.createArchiveFromLibArchive=ee,p.createArchiveFromText=te,p.createArchiveFromUrls=ae,p.createUniqueXmlSafeId=W,p.createXmlSafeId=_,p.createXmlSafeIdFactory=R,p.generateManifestFromArchive=V,p.generateResourceFromArchive=G,p.getArchiveHasComicInfo=O,p.getArchiveOpfInfo=L,p.getUriBasePath=M,p.getUriBasename=A,p.removeTrailingSlash=E,p.sortByTitleComparator=S,Object.defineProperty(p,Symbol.toStringTag,{value:"Module"})}));
|
|
39
39
|
//# sourceMappingURL=index.umd.cjs.map
|