@skillbuilder/miniapp-simulator 0.2.8 → 0.2.9
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/sw/miniapp-simulator-service-worker.js +725 -375
- package/dist/sw/miniapp-simulator-service-worker.min.js +2 -1
- package/lib/{client-C59iNO5u.mjs → client-CX13jDtT.mjs} +1 -1
- package/lib/{index-BSj1bmle.mjs → index-DwepISqo.mjs} +1 -1
- package/lib/index.js +1058 -1012
- package/lib/remote-client.js +2 -2
- package/lib/types/core/simulator.d.ts +240 -2
- package/lib/types/host/shadow-host.d.ts +5 -0
- package/lib/types/offload/manifest.d.ts +12 -0
- package/lib/types/offload/resource-session.d.ts +33 -0
- package/lib/types/remote/client.d.ts +2 -0
- package/lib/types/remote/protocol.d.ts +6 -1
- package/lib/types/sw/protocol.d.ts +2 -1
- package/lib/types/sw/service-worker-host.d.ts +1 -0
- package/lib/types/sw/worker/mount-store.d.ts +7 -4
- package/lib/types/sw/worker/offloaded.d.ts +3 -0
- package/lib/types/utils/stage-fit.d.ts +7 -1
- package/lib/workbench.js +1 -1
- package/package.json +2 -1
|
@@ -1 +1,2 @@
|
|
|
1
|
-
const h=self,pe="index.html",me="default-src 'none'; script-src 'none'; connect-src 'none'; worker-src 'none'; child-src 'none'",ge={workerCsp:me},G=ge.workerCsp,ye=["default-src","script-src","connect-src","worker-src","child-src"];function Z(e){if(!e||"object"!=typeof e||Array.isArray(e))return;const t={};for(const[n,r]of Object.entries(e)){if(!ye.includes(n)||"string"!=typeof r||!r.trim()||/[;,]|[^\x20-\x7e]/u.test(r))return;t[n]=r.trim()}return Object.keys(t).length?t:void 0}function we(e){const t=Z(e);return t?G.split("; ").map(e=>{const n=e.slice(0,e.indexOf(" "));return void 0===t[n]?e:`${n} ${t[n]}`}).join("; "):G}const be={html:"text/html; charset=utf-8",htm:"text/html; charset=utf-8",js:"text/javascript; charset=utf-8",mjs:"text/javascript; charset=utf-8",cjs:"text/javascript; charset=utf-8",css:"text/css; charset=utf-8",json:"application/json; charset=utf-8",xml:"application/xml; charset=utf-8",txt:"text/plain; charset=utf-8",csv:"text/csv; charset=utf-8",svg:"image/svg+xml",wasm:"application/wasm",map:"application/json; charset=utf-8"},_e={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",avif:"image/avif",ico:"image/x-icon",bmp:"image/bmp",woff:"font/woff",woff2:"font/woff2",ttf:"font/ttf",otf:"font/otf",eot:"application/vnd.ms-fontobject",mp4:"video/mp4",webm:"video/webm",ogg:"video/ogg",mp3:"audio/mpeg",wav:"audio/wav",m4a:"audio/mp4"};function Re(e){const t=e.split(".").pop()?.toLowerCase()??"";return be[t]??_e[t]??"application/octet-stream"}function b(e){try{return decodeURIComponent(e)}catch{return null}}function W(e){const t=[];for(const n of e.replace(/\\/g,"/").split("/"))if(""!==n&&"."!==n){if(".."===n)return"";t.push(n)}return t.join("/")}const g=new Map,Y=16;function ve(e){if(!g.has(e.id)&&g.size>=Y){const e=new Error("too many active simulator mounts (max 16)");throw e.code="ERR_MOUNT_LIMIT",e}const t=new Map;for(const[n,r]of Object.entries(e.files)){const e=W(n);e&&t.set(e,{bytes:r,mime:Re(e)})}let n;if(e.worker){if(e.remoteBase||e.worker.sessionId!==e.id)throw new TypeError("Invalid package Worker mount policy");n={sessionId:e.id,csp:Z(e.worker.csp)}}return g.set(e.id,{worker:n,workerResponses:new Map,files:t,injectHead:e.injectHead,csp:e.csp,remoteBase:e.remoteBase??"",fsScope:e.fsScope??"",ownerClientId:e.ownerClientId??""}),t.size}function xe(e){g.delete(e)}function Ee(e){let t=0;for(const[n,r]of g)!r.ownerClientId||e.has(r.ownerClientId)||(g.delete(n),t+=1);return t}function P(e){let t;try{t=new URL(e).pathname}catch{return null}for(const[e,n]of g){const r=`/${e}/`,i=t.indexOf(r);if(-1===i)continue;let o=b(t.slice(i+r.length));if(null===o)return null;(""===o||o.endsWith("/"))&&(o+=pe);const s=W(o);return s?{app:n,filePath:s}:null}return null}function Q(e){let t;try{t=new URL(e).pathname}catch{return null}for(const[e,n]of g)if(t.includes(`/${e}/`))return n;return null}const Se=5,Pe="miniapp:restore-worker-mount",De=["fsWriteTempFile","fsSaveFile","fsWriteFile","fsAppendFile","fsReadFile","fsReadDir","fsStatFile","fsUnlink","fsMkdir","fsGetStorageInfo"],F=new Map;async function Ie(e,t){const n=new URL(h.registration.scope),r=new URL(e.url);if(r.origin!==n.origin||!r.pathname.startsWith(n.pathname))return;const i=r.pathname.slice(n.pathname.length),o=i.indexOf("/");if(o<1)return;const s=i.slice(0,o);if(!/^[a-zA-Z0-9_-]{1,128}$/.test(s))return;const a=await h.clients.get(t);if(!a)return;const c=new URL(a.url);if(c.origin!==n.origin||!c.pathname.startsWith(`${n.pathname}${s}/`))return;let l=F.get(s);l||(l=Te(s,n.origin).finally(()=>F.delete(s)),F.set(s,l)),await l}async function Te(e,t){const n=(await h.clients.matchAll({type:"window",includeUncontrolled:!0})).filter(e=>new URL(e.url).origin===t);n.length&&await new Promise(t=>{const r=[];let i=n.length,o=!1;const s=()=>{if(!o){o=!0,clearTimeout(a);for(const e of r)e.close();t()}},a=setTimeout(s,5e3);for(const t of n){const n=new MessageChannel;r.push(n.port1),n.port1.onmessage=({data:e})=>{(!0===e?.ok||0===--i)&&s()};try{t.postMessage({type:Pe,id:e},[n.port2])}catch{n.port2.close(),0===--i&&s()}}})}async function ke(e,t){const n=()=>new Response("Worker entry denied",{status:403,headers:{"Content-Type":"text/plain; charset=utf-8","Cache-Control":"no-store"}});if("GET"!==e.method||"worker"!==e.destination||!t)return n();let r=P(e.url);if(!r)try{await Ie(e,t),r=P(e.url)}catch{return n()}if(!r?.app.worker)return n();const{app:i,filePath:o}=r,s=i.worker,a=new URL(h.registration.scope),c=new URL(e.url);if(c.origin!==a.origin||!c.pathname.startsWith(`${a.pathname}${s.sessionId}/`))return n();try{const r=await h.clients.get(t);if(!r||Q(r.url)!==i||P(e.url)?.app!==i)return n();const a=i.workerResponses.get(o);if(a)return a.clone();const c=i.files.get(o);if(!c)return n();const l=new Response(c.bytes,{headers:{"Content-Type":"text/javascript; charset=utf-8","Cache-Control":"no-store","X-Content-Type-Options":"nosniff","Content-Security-Policy":we(s.csp)}});return i.workerResponses.set(o,l),l.clone()}catch{return n()}}const Ce={"image/png":"png","image/jpeg":"jpg","image/webp":"webp","image/gif":"gif","video/mp4":"mp4","video/quicktime":"mov","video/webm":"webm"};function J(e){const t=new Uint8Array(e);return U(t,[137,80,78,71,13,10,26,10])?"image/png":U(t,[255,216,255])?"image/jpeg":x(t,0,"GIF87a")||x(t,0,"GIF89a")?"image/gif":x(t,0,"RIFF")&&x(t,8,"WEBP")?"image/webp":x(t,4,"ftyp")?"qt "===ee(t,8,12)?"video/quicktime":"video/mp4":U(t,[26,69,223,163])?"video/webm":void 0}function Me(e){if("string"!=typeof e||0===e.length)return{error:"data is required",code:"ERR_INVALID_ARGS"};const t=/^data:([^;,]+);base64,(.*)$/s.exec(e);if(!t)return{error:"only base64 data: URI is accepted",code:"ERR_INVALID_ARGS"};const n=t[1].toLowerCase(),r=Ce[n];if(!r)return{error:`unsupported mime "${n}"`,code:"ERR_UNSUPPORTED_MIME"};let i;try{i=atob(t[2])}catch{return{error:"invalid base64 data",code:"ERR_INVALID_ARGS"}}const o=new Uint8Array(i.length);for(let e=0;e<i.length;e++)o[e]=i.charCodeAt(e);return{bytes:o.buffer,mime:n,ext:r}}function U(e,t){return t.every((t,n)=>e[n]===t)}function x(e,t,n){return ee(e,t,t+n.length)===n}function ee(e,t,n){if(e.length<n)return"";let r="";for(let i=t;i<n;i++)r+=String.fromCharCode(e[i]);return r}const Fe="miniapp-simulator-fs",Ue=1,p="files";let _=null;function R(){return _||(_=new Promise((e,t)=>{const n=indexedDB.open(Fe,1);n.onupgradeneeded=()=>{const e=n.result;if(!e.objectStoreNames.contains(p)){const t=e.createObjectStore(p,{keyPath:["scope","path"]});t.createIndex("by_scope","scope",{unique:!1}),t.createIndex("by_createdAt","createdAt",{unique:!1})}},n.onsuccess=()=>e(n.result),n.onerror=()=>{_=null,t(n.error??new Error("indexedDB open failed"))},n.onblocked=()=>{_=null,t(new Error("indexedDB open blocked"))}}),_)}function te(e){return new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>n(e.error??new Error("indexedDB request failed"))})}function T(e){return new Promise((t,n)=>{e.oncomplete=()=>t(),e.onerror=()=>n(e.error??new Error("indexedDB transaction failed")),e.onabort=()=>n(e.error??new Error("indexedDB transaction aborted"))})}function N(e,t,n,r,i){const o=Date.now();return{scope:e,path:t,mime:r,bytes:new Blob([n],{type:r}),isDir:i,createdAt:o,lastModified:o}}async function ne(e,t,n,r="application/octet-stream"){const i=(await R()).transaction(p,"readwrite");i.objectStore(p).put(N(e,t,n,r,!1)),await T(i)}async function A(e,t){const n=(await R()).transaction(p,"readwrite");n.objectStore(p).put(N(e,t,new ArrayBuffer(0),"application/x-directory",!0)),await T(n)}async function S(e,t){const n=(await R()).transaction(p,"readonly").objectStore(p),r=await te(n.get([e,t]));return r?{path:r.path,bytes:await r.bytes.arrayBuffer(),mime:r.mime,isDir:!0===r.isDir,lastModified:r.lastModified??r.createdAt??0}:null}async function v(e){const t=await R();return(await te(t.transaction(p,"readonly").objectStore(p).index("by_scope").getAll(e))).map(e=>({path:e.path,mime:e.mime,size:!0===e.isDir?0:e.bytes.size,isDir:!0===e.isDir,lastModified:e.lastModified??e.createdAt??0}))}async function Ae(e,t){const n=(await R()).transaction(p,"readwrite");n.objectStore(p).delete([e,t]),await T(n)}async function Le(e,t,n,r){const i=(await R()).transaction(p,"readwrite"),o=i.objectStore(p);o.put(N(e,n,r.bytes,r.mime,!1)),o.delete([e,t]),await T(i)}function Oe(e,t,n){if(e.files.has(t))return L(e,t);if(e.remoteBase){const r=new URL(t,e.remoteBase);return r.search=new URL(n.url).search,ie(r.href)}return L(e,t)}async function Be(e,t){try{const n=await h.clients.get(e);if(n){const e=Q(n.url);if(e){const n=new URL(t.url),r=b(n.pathname),i=null===r?"":W(r);if(i&&e.files.has(i))return L(e,i);if(e.remoteBase){return ie(new URL(n.pathname+n.search,new URL(e.remoteBase).origin).href)}}}}catch{}return fetch(t)}function re(e,t){return new Response(e,{status:200,headers:{"Content-Type":t,"Cache-Control":"no-store, no-cache, must-revalidate, max-age=0",Expires:"0",Pragma:"no-cache","Content-Length":String(e.byteLength)}})}function L(e,t){const n=e.files.get(t);if(!n)return new Response(`Not Found: ${t}`,{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});if(n.mime.startsWith("text/html")){const t=We(new TextDecoder("utf-8").decode(n.bytes),e.injectHead),r={"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-store","Origin-Agent-Cluster":"?1"};return e.csp&&(r["Content-Security-Policy"]=e.csp),new Response(t,{status:200,headers:r})}return re(n.bytes,n.mime)}async function ie(e){try{return await fetch(e,{method:"GET",credentials:"omit"})}catch{return new Response(`Bad Gateway: ${e}`,{status:502,headers:{"Content-Type":"text/plain; charset=utf-8"}})}}function We(e,t){if(!t)return e;const n=/<head\b[^>]*>/i.exec(e);if(n){const r=n.index+n[0].length;return e.slice(0,r)+t+e.slice(r)}const r=/<html\b[^>]*>/i.exec(e);if(r){const n=r.index+r[0].length;return`${e.slice(0,n)}<head>${t}</head>${e.slice(n)}`}return`<head>${t}</head>${e}`}const se=52428800,D=2097152,O=2097152,Ne=209715200,je=4,$e=255,K=1e3,j=new Set(["tmp","usr"]),k=new Set(["usr"]),qe=/^[A-Za-z0-9._-]{1,64}$/,I=new Map;let H=Promise.resolve();function C(e){const t=H.then(e,e);return H=t.then(()=>{},()=>{}),t}function ze(e){I.delete(e)}async function Ge(e){const t=t=>({type:"FS_ACK",op:e.op,id:e.id,reqId:e.reqId,...t});if(!g.has(e.id))return t({ok:!1,error:"simulator not ready",code:"ERR_NOT_MOUNTED"});try{return t(await Ye(e))}catch{return t({ok:!1,code:50101,error:"storage io error"})}}async function Ye(e){const t=e.fsScope||e.id;switch(e.op){case"fsWriteTempFile":return Ke(t,e);case"fsSaveFile":return He(t,e);case"fsWriteFile":return V(t,e,!1);case"fsAppendFile":return V(t,e,!0);case"fsReadFile":return Ve(t,e);case"fsReadDir":return Xe(t,e);case"fsStatFile":return Ze(t,e);case"fsUnlink":return Qe(t,e);case"fsMkdir":return Je(t,e);case"fsGetStorageInfo":return et(t);default:return{ok:!1,error:`unsupported operation: ${e.op}`,code:"ERR_UNSUPPORTED_OP"}}}async function Ke(e,t){const n=Me(t.data);if("error"in n)return{ok:!1,error:n.error,code:n.code};const r=`tmp/${de()}.${n.ext}`;return await ne(e,r,n.bytes,n.mime),{ok:!0,result:{path:r,url:he(e,r)}}}async function He(e,t){const n=m(t.tempFilePath,"tempFilePath");if(n)return n;if(void 0!==t.filePath&&null!==t.filePath){const e=m(t.filePath,"filePath");if(e)return e}const r=w(t.tempFilePath,e,new Set(["tmp"]),!1);if("code"in r)return l(r);const i=void 0===t.filePath||null===t.filePath?it(r.path):w(t.filePath,e,k,!1);return"code"in i?l(i):C(async()=>{const n=await S(e,r.path);if(!n)return l({code:50202,message:"file not found; reason=not_found"});if(n.isDir)return l({code:50205,message:"not a file"});const o=await v(e),s=q(o);if(s.has(i.path))return l({code:50204,message:"file already exists"});const a=ue(i.path,s);if("code"in a)return l(a);const c=ae(t.id,o,n.bytes.byteLength,0);return c?l(c):(await le(e,a.missing),await Le(e,r.path,i.path,n),ce(t.id,n.bytes.byteLength),{ok:!0,result:{savedFilePath:he(e,i.path)}})})}async function V(e,t,n){const r=m(t.filePath,"filePath");if(r)return r;const i=oe(t.data,"data",!0);if(i)return i;const o=m(t.encoding,"encoding");if(o)return o;const s=w(t.filePath,e,k,!1);if("code"in s)return l(s);if("base64"!==t.encoding&&"utf8"!==t.encoding)return l({code:10001,message:"invalid parameter; reason=encoding_unsupported"});const a=nt(t.data,t.encoding);return"code"in a?l(a):a.bytes.byteLength>D?l({code:50201,message:"storage quota exceeded; reason=single_over_limit"}):C(async()=>{const r=await v(e),i=q(r),o=await S(e,s.path);if(o?.isDir)return l({code:50205,message:"not a file"});const c=ue(s.path,i);if("code"in c)return l(c);const u=n?0:o?.bytes.byteLength??0,f=ae(t.id,r,a.bytes.byteLength,u);if(f)return l(f);await le(e,c.missing);let d=a.bytes;return n&&o&&(d=st(o.bytes,a.bytes)),await ne(e,s.path,d,at(d,t.encoding)),ce(t.id,a.bytes.byteLength),{ok:!0,result:{writtenBytes:a.bytes.byteLength}}})}async function Ve(e,t){const n=m(t.filePath,"filePath");if(n)return n;const r=m(t.encoding,"encoding");if(r)return r;const i=X(t.position,"position");if(i)return i;const o=X(t.length,"length");if(o)return o;const s=w(t.filePath,e,j,!1);if("code"in s)return l(s);if("base64"!==t.encoding&&"utf8"!==t.encoding)return l({code:10001,message:"invalid parameter; reason=encoding_unsupported"});const a=void 0===t.position?0:t.position,c=void 0===t.length?O:t.length;if(!Number.isSafeInteger(a)||a<0||!Number.isSafeInteger(c)||c<0||c>O)return l({code:10001,message:"invalid parameter; reason=range_invalid"});const u=await S(e,s.path);if(!u)return l({code:50202,message:"file not found"});if(u.isDir)return l({code:50205,message:"not a file"});const f=Math.min(u.bytes.byteLength,a+c),d=a>=u.bytes.byteLength?new ArrayBuffer(0):u.bytes.slice(a,f);let p;if("base64"===t.encoding)p=ot(d);else try{p=new TextDecoder("utf-8",{fatal:!0}).decode(d)}catch{return l({code:10001,message:"invalid parameter; reason=decode_failed"})}return{ok:!0,result:{data:p,bytesRead:d.byteLength,eof:a+d.byteLength>=u.bytes.byteLength}}}async function Xe(e,t){const n=m(t.dirPath,"dirPath");if(n)return n;const r=w(t.dirPath,e,j,!0);if("code"in r)return l(r);const i=await v(e);if(r.relativePath){const e=i.find(e=>e.path===r.path);if(!e)return l({code:50202,message:"file not found"});if(!e.isDir)return l({code:50206,message:"not a directory"})}const o=`${r.path}/`,s=i.filter(e=>{if(!e.path.startsWith(o))return!1;const t=e.path.slice(o.length);return t.length>0&&!t.includes("/")&&!E(e.path)}).sort((e,t)=>e.path.localeCompare(t.path));return{ok:!0,result:{files:s.slice(0,K).map(e=>({name:e.path.slice(o.length),size:e.isDir?0:e.size,lastModified:e.lastModified,isDir:e.isDir})),truncated:s.length>K}}}async function Ze(e,t){const n=m(t.filePath,"filePath");if(n)return n;const r=w(t.filePath,e,j,!1);if("code"in r)return l(r);const i=(await v(e)).find(e=>e.path===r.path);return i?{ok:!0,result:{size:i.isDir?0:i.size,lastModified:i.lastModified,isDir:i.isDir}}:l({code:50202,message:"file not found"})}async function Qe(e,t){const n=m(t.filePath,"filePath");if(n)return n;const r=w(t.filePath,e,k,!1);return"code"in r?l(r):C(async()=>{const t=await S(e,r.path);return t?t.isDir?l({code:50205,message:"not a file"}):(await Ae(e,r.path),{ok:!0,result:{}}):l({code:50202,message:"file not found"})})}async function Je(e,t){const n=m(t.dirPath,"dirPath");if(n)return n;if(void 0!==t.recursive&&"boolean"!=typeof t.recursive)return $("recursive");const r=w(t.dirPath,e,k,!1);if("code"in r)return l(r);const i=!0===t.recursive;return C(async()=>{const t=q(await v(e)),n=t.get(r.path);if(n)return n.isDir?i?{ok:!0,result:{}}:l({code:50204,message:"file already exists"}):l({code:50205,message:"not a file"});const o=fe(r.path);for(const e of o){const n=t.get(e);if(n&&!n.isDir)return l({code:50205,message:"not a file"});if(!n&&!i)return l({code:50202,message:"file not found"})}if(i)for(const n of o)t.has(n)||await A(e,n);return await A(e,r.path),{ok:!0,result:{}}})}async function et(e){const t=await v(e),n=t.filter(e=>!e.isDir&&e.path.startsWith("usr/")&&!E(e.path)),r=t.filter(e=>!e.isDir&&e.path.startsWith("tmp/")&&!E(e.path));return{ok:!0,result:{usedBytes:B(n),limitBytes:se,fileCount:n.length,tmpUsedBytes:B(r),writeChunkMaxBytes:D,readChunkMaxBytes:O}}}function m(e,t){return oe(e,t,!1)}function oe(e,t,n){if("string"!=typeof e||!(n||e.length>0))return $(t)}function X(e,t){if(void 0!==e&&"number"!=typeof e)return $(t)}function $(e){return{ok:!1,code:10001,error:`invalid parameter; param=${e}`}}function l(e){return{ok:!1,code:e.code,error:e.message}}function w(e,t,n,r){const i=tt(e,t);if(null===i)return{code:50203,message:"invalid path; reason=dir_not_allowed"};if("__DECODE_ERROR__"===i)return{code:50203,message:"invalid path; reason=traversal"};const o=i.indexOf("/"),s=(-1===o?i:i.slice(0,o)).toLowerCase(),a=-1===o?"":i.slice(o+1);if(!n.has(s)||!r&&0===a.length)return{code:50203,message:"invalid path; reason=dir_not_allowed"};if(i.includes("\0")||i.includes("\\")||a.split("/").includes(".."))return{code:50203,message:"invalid path; reason=traversal"};if((new TextEncoder).encode(a).byteLength>$e)return{code:50203,message:"invalid path; reason=name_too_long"};const c=a?a.split("/"):[];return c.length>4?{code:50203,message:"invalid path; reason=depth_exceeded"}:c.some(e=>"."===e||!qe.test(e))?{code:50203,message:"invalid path; reason=name_invalid"}:c.some(e=>e.startsWith("__xhs"))?{code:50203,message:"invalid path; reason=reserved_name"}:{dir:s,relativePath:a,path:a?`${s}/${a}`:s}}function tt(e,t){const n=b(e);if(null===n)return"__DECODE_ERROR__";const r=n.split(/[?#]/,1)[0];if(r.includes("\0")||r.includes("\\")||r.split("/").includes(".."))return"__DECODE_ERROR__";let i;if(e.startsWith("xhsfile://"))i=e.slice(10).split(/[?#]/,1)[0];else{let n;try{n=new URL(e)}catch{return null}if("http:"!==n.protocol&&"https:"!==n.protocol)return null;const r="/_xhsfile_/",o=n.pathname.indexOf(r);if(-1===o)return null;const s=n.pathname.slice(o+r.length),a=s.indexOf("/");if(a<=0||b(s.slice(0,a))!==t)return null;i=s.slice(a+1)}const o=b(i);return null===o?"__DECODE_ERROR__":o}function nt(e,t){if("utf8"===t)return e.length>D?{code:50201,message:"storage quota exceeded; reason=single_over_limit"}:{bytes:(new TextEncoder).encode(e).buffer};if(e.length>Math.ceil(4*D/3)+4)return{code:50201,message:"storage quota exceeded; reason=single_over_limit"};if(!rt(e))return{code:10001,message:"invalid parameter; reason=decode_failed"};try{const t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return{bytes:n.buffer}}catch{return{code:10001,message:"invalid parameter; reason=decode_failed"}}}function rt(e){return e.length%4==0&&/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e)}function ae(e,t,n,r){return(I.get(e)??0)+n>Ne?{code:50201,message:"storage quota exceeded; reason=session_limit"}:B(t.filter(e=>!e.isDir&&e.path.startsWith("usr/")&&!E(e.path)))-r+n>se?{code:50201,message:"storage quota exceeded; reason=total_over_limit"}:void 0}function ce(e,t){I.set(e,(I.get(e)??0)+t)}function q(e){return new Map(e.map(e=>[e.path,e]))}function ue(e,t){const n=[];for(const r of fe(e)){const e=t.get(r);if(e&&!e.isDir)return{code:50205,message:"not a file"};e||n.push(r)}return{missing:n}}async function le(e,t){for(const n of t)await A(e,n)}function fe(e){const t=e.split("/"),n=[];for(let e=2;e<t.length;e++)n.push(t.slice(0,e).join("/"));return n}function it(e){const t=e.slice(e.lastIndexOf("/")+1),n=t.lastIndexOf("."),r=n>0?t.slice(n):"",i=`${de()}${r}`;return{dir:"usr",relativePath:i,path:`usr/${i}`}}function st(e,t){const n=new Uint8Array(e.byteLength+t.byteLength);return n.set(new Uint8Array(e),0),n.set(new Uint8Array(t),e.byteLength),n.buffer}function ot(e){const t=new Uint8Array(e);let n="";for(let e=0;e<t.length;e+=32768)n+=String.fromCharCode(...t.subarray(e,e+32768));return btoa(n)}function at(e,t){return J(e)??("utf8"===t?"text/plain; charset=utf-8":"application/octet-stream")}function B(e){return e.reduce((e,t)=>e+t.size,0)}function E(e){return e.split("/").some(e=>e.startsWith("__xhs"))}function de(){if(typeof crypto<"u"&&"function"==typeof crypto.randomUUID)return crypto.randomUUID().replace(/-/g,"");let e="";for(let t=0;t<32;t++)e+=Math.floor(16*Math.random()).toString(16);return e}function he(e,t){return`${h.registration.scope}_xhsfile_/${encodeURIComponent(e)}/${t}`}function ct(e){let t;try{t=new URL(e).pathname}catch{return null}const n="/_xhsfile_/",r=t.indexOf(n);if(-1===r)return null;const i=t.slice(r+11),o=i.indexOf("/");if(o<=0)return null;const s=b(i.slice(0,o)),a=b(i.slice(o+1));return!s||!a||a.includes("\0")||a.includes("\\")||a.split("/").includes("..")?null:{scope:s,path:a}}async function ut(e,t){try{const n=await S(e,t);if(n&&!n.isDir&&!E(t)){const e=J(n.bytes);if(e)return re(n.bytes,e)}}catch{}return new Response("Not Found",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}})}async function lt(e,t){if(t)try{const e=await h.clients.matchAll({type:"window",includeUncontrolled:!0});Ee(new Set(e.map(e=>e.id)))}catch{}return ve({...e,ownerClientId:t})}function ft(e){if(!e||"object"!=typeof e||!("id"in e))return"";const t=e.id;return"string"==typeof t?t:""}h.addEventListener("install",()=>{h.skipWaiting()}),h.addEventListener("activate",e=>{e.waitUntil(h.clients.claim())}),h.addEventListener("message",e=>{const t=e.data;if(!t||"string"!=typeof t.type)return;const n=t=>e.ports?.[0]?.postMessage(t);if("MOUNT"===t.type){const r=lt(t,ft(e.source)).then(e=>n({type:"MOUNT_ACK",id:t.id,ok:!0,count:e,swVersion:5,fsOps:De}),e=>{const r=e;n({type:"MOUNT_ACK",id:t.id,ok:!1,error:r instanceof Error?r.message:String(e),code:r?.code})});return void e.waitUntil?.(r)}if("FS"===t.type){const r=t,i=Ge(r).then(n,e=>n({type:"FS_ACK",op:r.op,id:r.id,reqId:r.reqId,ok:!1,error:e instanceof Error?e.message:String(e),code:"ERR_UNKNOWN"}));return void e.waitUntil?.(i)}"UNMOUNT"===t.type&&(ze(t.id),xe(t.id))}),h.addEventListener("fetch",e=>{if("worker"===e.request.destination||"sharedworker"===e.request.destination)return void e.respondWith(ke(e.request,e.clientId));if("GET"!==e.request.method)return;const t=ct(e.request.url);if(t)return void e.respondWith(ut(t.scope,t.path));const n=P(e.request.url);if(n)return void e.respondWith(Oe(n.app,n.filePath,e.request));const r=e.clientId||e.resultingClientId;r&&e.respondWith(Be(r,e.request))});
|
|
1
|
+
const p=self,Ie="index.html",Ce="default-src 'none'; script-src 'none'; connect-src 'none'; worker-src 'none'; child-src 'none'",Te={workerCsp:Ce},ee=Te.workerCsp,Ue=["default-src","script-src","connect-src","worker-src","child-src"];function ue(e){if(!e||"object"!=typeof e||Array.isArray(e))return;const t={};for(const[n,r]of Object.entries(e)){if(!Ue.includes(n)||"string"!=typeof r||!r.trim()||/[;,]|[^\x20-\x7e]/u.test(r))return;t[n]=r.trim()}return Object.keys(t).length?t:void 0}function Pe(e){const t=ue(e);return t?ee.split("; ").map(e=>{const n=e.slice(0,e.indexOf(" "));return void 0===t[n]?e:`${n} ${t[n]}`}).join("; "):ee}const Le={html:"text/html; charset=utf-8",htm:"text/html; charset=utf-8",js:"text/javascript; charset=utf-8",mjs:"text/javascript; charset=utf-8",cjs:"text/javascript; charset=utf-8",css:"text/css; charset=utf-8",json:"application/json; charset=utf-8",xml:"application/xml; charset=utf-8",txt:"text/plain; charset=utf-8",csv:"text/csv; charset=utf-8",svg:"image/svg+xml",wasm:"application/wasm",map:"application/json; charset=utf-8"},ke={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",avif:"image/avif",ico:"image/x-icon",bmp:"image/bmp",woff:"font/woff",woff2:"font/woff2",ttf:"font/ttf",otf:"font/otf",eot:"application/vnd.ms-fontobject",mp4:"video/mp4",webm:"video/webm",ogg:"video/ogg",mp3:"audio/mpeg",wav:"audio/wav",aac:"audio/aac",m4a:"audio/mp4"};function Me(e){const t=e.split(".").pop()?.toLowerCase()??"";return Le[t]??ke[t]??"application/octet-stream"}function S(e){try{return decodeURIComponent(e)}catch{return null}}function q(e){const t=[];for(const n of e.replace(/\\/g,"/").split("/"))if(""!==n&&"."!==n){if(".."===n)return"";t.push(n)}return t.join("/")}const x=new Map,te=16;function Fe(e){if(!x.has(e.id)&&x.size>=16){const e=new Error("too many active simulator mounts (max 16)");throw e.code="ERR_MOUNT_LIMIT",e}const t=new Map;for(const[n,r]of Object.entries(e.files)){const e=q(n);e&&t.set(e,{bytes:r,mime:Me(e)})}let n;if(e.worker){if(e.remoteBase||e.worker.sessionId!==e.id)throw new TypeError("Invalid package Worker mount policy");n={sessionId:e.id,csp:ue(e.worker.csp)}}return Y(e.id),x.set(e.id,{offloaded:e.offloaded&&{id:e.id,resources:e.offloaded,lifetime:new AbortController},worker:n,workerResponses:new Map,files:t,injectHead:e.injectHead,csp:e.csp,remoteBase:e.remoteBase??"",fsScope:e.fsScope??"",ownerClientId:e.ownerClientId??""}),t.size}function Y(e){x.get(e)?.offloaded?.lifetime.abort(),x.delete(e)}function Oe(e){let t=0;for(const[n,r]of x)!r.ownerClientId||e.has(r.ownerClientId)||(Y(n),t+=1);return t}function T(e){let t;try{t=new URL(e).pathname}catch{return null}for(const[e,n]of x){const r=`/${e}/`,i=t.indexOf(r);if(-1===i)continue;let s=S(t.slice(i+r.length));if(null===s)return null;(""===s||s.endsWith("/"))&&(s+=Ie);const o=q(s);return o?{app:n,filePath:o}:null}return null}function K(e){let t;try{t=new URL(e).pathname}catch{return null}for(const[e,n]of x)if(t.includes(`/${e}/`))return n;return null}const Be=6,We="miniapp:offloaded-resource-url",Ne="miniapp:restore-worker-mount",$e=["fsWriteTempFile","fsSaveFile","fsWriteFile","fsAppendFile","fsReadFile","fsReadDir","fsStatFile","fsUnlink","fsMkdir","fsGetStorageInfo"],W=new Map;async function je(e,t){const n=new URL(p.registration.scope),r=new URL(e.url);if(r.origin!==n.origin||!r.pathname.startsWith(n.pathname))return;const i=r.pathname.slice(n.pathname.length),s=i.indexOf("/");if(s<1)return;const o=i.slice(0,s);if(!/^[a-zA-Z0-9_-]{1,128}$/.test(o))return;const a=await p.clients.get(t);if(!a)return;const c=new URL(a.url);if(c.origin!==n.origin||!c.pathname.startsWith(`${n.pathname}${o}/`))return;let u=W.get(o);u||(u=He(o,n.origin).finally(()=>W.delete(o)),W.set(o,u)),await u}async function He(e,t){const n=(await p.clients.matchAll({type:"window",includeUncontrolled:!0})).filter(e=>new URL(e.url).origin===t);n.length&&await new Promise(t=>{const r=[];let i=n.length,s=!1;const o=()=>{if(!s){s=!0,clearTimeout(a);for(const e of r)e.close();t()}},a=setTimeout(o,5e3);for(const t of n){const n=new MessageChannel;r.push(n.port1),n.port1.onmessage=({data:e})=>{(!0===e?.ok||0===--i)&&o()};try{t.postMessage({type:Ne,id:e},[n.port2])}catch{n.port2.close(),0===--i&&o()}}})}async function ze(e,t){const n=()=>new Response("Worker entry denied",{status:403,headers:{"Content-Type":"text/plain; charset=utf-8","Cache-Control":"no-store"}});if("GET"!==e.method||"worker"!==e.destination||!t)return n();let r=T(e.url);if(!r)try{await je(e,t),r=T(e.url)}catch{return n()}if(!r?.app.worker)return n();const{app:i,filePath:s}=r,o=i.worker,a=new URL(p.registration.scope),c=new URL(e.url);if(c.origin!==a.origin||!c.pathname.startsWith(`${a.pathname}${o.sessionId}/`))return n();try{const r=await p.clients.get(t);if(!r||K(r.url)!==i||T(e.url)?.app!==i)return n();const a=i.workerResponses.get(s);if(a)return a.clone();const c=i.files.get(s);if(!c)return n();const u=new Response(c.bytes,{headers:{"Content-Type":"text/javascript; charset=utf-8","Cache-Control":"no-store","X-Content-Type-Options":"nosniff","Content-Security-Policy":Pe(o.csp)}});return i.workerResponses.set(s,u),u.clone()}catch{return n()}}const Ge={"image/png":"png","image/jpeg":"jpg","image/webp":"webp","image/gif":"gif","video/mp4":"mp4","video/quicktime":"mov","video/webm":"webm"};function le(e){const t=new Uint8Array(e);return N(t,[137,80,78,71,13,10,26,10])?"image/png":N(t,[255,216,255])?"image/jpeg":C(t,0,"GIF87a")||C(t,0,"GIF89a")?"image/gif":C(t,0,"RIFF")&&C(t,8,"WEBP")?"image/webp":C(t,4,"ftyp")?"qt "===de(t,8,12)?"video/quicktime":"video/mp4":N(t,[26,69,223,163])?"video/webm":void 0}function Ve(e){if("string"!=typeof e||0===e.length)return{error:"data is required",code:"ERR_INVALID_ARGS"};const t=/^data:([^;,]+);base64,(.*)$/s.exec(e);if(!t)return{error:"only base64 data: URI is accepted",code:"ERR_INVALID_ARGS"};const n=t[1].toLowerCase(),r=Ge[n];if(!r)return{error:`unsupported mime "${n}"`,code:"ERR_UNSUPPORTED_MIME"};let i;try{i=atob(t[2])}catch{return{error:"invalid base64 data",code:"ERR_INVALID_ARGS"}}const s=new Uint8Array(i.length);for(let e=0;e<i.length;e++)s[e]=i.charCodeAt(e);return{bytes:s.buffer,mime:n,ext:r}}function N(e,t){return t.every((t,n)=>e[n]===t)}function C(e,t,n){return de(e,t,t+n.length)===n}function de(e,t,n){if(e.length<n)return"";let r="";for(let i=t;i<n;i++)r+=String.fromCharCode(e[i]);return r}const qe="miniapp-simulator-fs",Ye=1,g="files";let D=null;function A(){return D||(D=new Promise((e,t)=>{const n=indexedDB.open(qe,1);n.onupgradeneeded=()=>{const e=n.result;if(!e.objectStoreNames.contains(g)){const t=e.createObjectStore(g,{keyPath:["scope","path"]});t.createIndex("by_scope","scope",{unique:!1}),t.createIndex("by_createdAt","createdAt",{unique:!1})}},n.onsuccess=()=>e(n.result),n.onerror=()=>{D=null,t(n.error??new Error("indexedDB open failed"))},n.onblocked=()=>{D=null,t(new Error("indexedDB open blocked"))}}),D)}function he(e){return new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=()=>n(e.error??new Error("indexedDB request failed"))})}function M(e){return new Promise((t,n)=>{e.oncomplete=()=>t(),e.onerror=()=>n(e.error??new Error("indexedDB transaction failed")),e.onabort=()=>n(e.error??new Error("indexedDB transaction aborted"))})}function X(e,t,n,r,i){const s=Date.now();return{scope:e,path:t,mime:r,bytes:new Blob([n],{type:r}),isDir:i,createdAt:s,lastModified:s}}async function pe(e,t,n,r="application/octet-stream"){const i=(await A()).transaction(g,"readwrite");i.objectStore(g).put(X(e,t,n,r,!1)),await M(i)}async function j(e,t){const n=(await A()).transaction(g,"readwrite");n.objectStore(g).put(X(e,t,new ArrayBuffer(0),"application/x-directory",!0)),await M(n)}async function P(e,t){const n=(await A()).transaction(g,"readonly").objectStore(g),r=await he(n.get([e,t]));return r?{path:r.path,bytes:await r.bytes.arrayBuffer(),mime:r.mime,isDir:!0===r.isDir,lastModified:r.lastModified??r.createdAt??0}:null}async function I(e){const t=await A();return(await he(t.transaction(g,"readonly").objectStore(g).index("by_scope").getAll(e))).map(e=>({path:e.path,mime:e.mime,size:!0===e.isDir?0:e.bytes.size,isDir:!0===e.isDir,lastModified:e.lastModified??e.createdAt??0}))}async function Ke(e,t){const n=(await A()).transaction(g,"readwrite");n.objectStore(g).delete([e,t]),await M(n)}async function Xe(e,t,n,r){const i=(await A()).transaction(g,"readwrite"),s=i.objectStore(g);s.put(X(e,n,r.bytes,r.mime,!1)),s.delete([e,t]),await M(i)}
|
|
2
|
+
/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Ze(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function F(e,...t){if(!Ze(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function ne(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function Qe(e,t){F(e);const n=t.outputLen;if(e.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function H(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function $(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function w(e,t){return e<<32-t|e>>>t}const Je="function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex,et=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function tt(e){if(F(e),Je)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=et[e[n]];return t}function nt(e){if("string"!=typeof e)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(e))}function ge(e){return"string"==typeof e&&(e=nt(e)),F(e),e}class rt{}function it(e){const t=t=>e().update(ge(t)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function st(e,t,n,r){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,n,r);const i=BigInt(32),s=BigInt(4294967295),o=Number(n>>i&s),a=Number(n&s),c=r?4:0,u=r?0:4;e.setUint32(t+c,o,r),e.setUint32(t+u,a,r)}function ot(e,t,n){return e&t^~e&n}function at(e,t,n){return e&t^e&n^t&n}class ct extends rt{constructor(e,t,n,r){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=r,this.buffer=new Uint8Array(e),this.view=$(this.buffer)}update(e){ne(this),F(e=ge(e));const{view:t,buffer:n,blockLen:r}=this,i=e.length;for(let s=0;s<i;){const o=Math.min(r-this.pos,i-s);if(o===r){const t=$(e);for(;r<=i-s;s+=r)this.process(t,s);continue}n.set(e.subarray(s,s+o),this.pos),this.pos+=o,s+=o,this.pos===r&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){ne(this),Qe(e,this),this.finished=!0;const{buffer:t,view:n,blockLen:r,isLE:i}=this;let{pos:s}=this;t[s++]=128,H(this.buffer.subarray(s)),this.padOffset>r-s&&(this.process(n,0),s=0);for(let e=s;e<r;e++)t[e]=0;st(n,r-8,BigInt(8*this.length),i),this.process(n,0);const o=$(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const c=a/4,u=this.get();if(c>u.length)throw new Error("_sha2: outputLen bigger than state");for(let e=0;e<c;e++)o.setUint32(4*e,u[e],i)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const n=e.slice(0,t);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:n,length:r,finished:i,destroyed:s,pos:o}=this;return e.destroyed=s,e.finished=i,e.length=r,e.pos=o,r%t&&e.buffer.set(n),e}clone(){return this._cloneInto()}}const R=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ft=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),E=new Uint32Array(64);class ut extends ct{constructor(e=32){super(64,e,8,!1),this.A=0|R[0],this.B=0|R[1],this.C=0|R[2],this.D=0|R[3],this.E=0|R[4],this.F=0|R[5],this.G=0|R[6],this.H=0|R[7]}get(){const{A:e,B:t,C:n,D:r,E:i,F:s,G:o,H:a}=this;return[e,t,n,r,i,s,o,a]}set(e,t,n,r,i,s,o,a){this.A=0|e,this.B=0|t,this.C=0|n,this.D=0|r,this.E=0|i,this.F=0|s,this.G=0|o,this.H=0|a}process(e,t){for(let n=0;n<16;n++,t+=4)E[n]=e.getUint32(t,!1);for(let e=16;e<64;e++){const t=E[e-15],n=E[e-2],r=w(t,7)^w(t,18)^t>>>3,i=w(n,17)^w(n,19)^n>>>10;E[e]=i+E[e-7]+r+E[e-16]|0}let{A:n,B:r,C:i,D:s,E:o,F:a,G:c,H:u}=this;for(let e=0;e<64;e++){const t=u+(w(o,6)^w(o,11)^w(o,25))+ot(o,a,c)+ft[e]+E[e]|0,f=(w(n,2)^w(n,13)^w(n,22))+at(n,r,i)|0;u=c,c=a,a=o,o=s+t|0,s=i,i=r,r=n,n=t+f|0}n=n+this.A|0,r=r+this.B|0,i=i+this.C|0,s=s+this.D|0,o=o+this.E|0,a=a+this.F|0,c=c+this.G|0,u=u+this.H|0,this.set(n,r,i,s,o,a,c,u)}roundClean(){H(E)}destroy(){this.set(0,0,0,0,0,0,0,0),H(this.buffer)}}const lt=it(()=>new ut),dt=lt;async function re(e,t,n,r){const i=await p.clients.get(e.ownerClientId);if(!i||!e.offloaded)throw new Error("资源会话已关闭");n.throwIfAborted();const{port1:s,port2:o}=new MessageChannel;return new Promise((a,c)=>{const u=()=>{clearTimeout(d),s.close(),n.removeEventListener("abort",f)},f=()=>{u(),c(new Error("未取得资源地址"))},d=setTimeout(f,5e3);n.addEventListener("abort",f,{once:!0}),s.onmessage=({data:e})=>{u(),"string"==typeof e?.url?a(e.url):c(new Error("资源地址不可用"))},i.postMessage({type:We,id:e.offloaded.id,path:t,rejectedUrl:r},[o])})}function ht(e,t){const n=/^bytes=(\d*)-(\d*)$/i.exec(e??"");if(!n||!n[1]&&!n[2])return;return{start:n[1]?Number(n[1]):Math.max(0,t-Number(n[2])),end:n[1]&&n[2]?Math.min(Number(n[2]),t-1):t-1}}function pt(e,t,n){const r=n?dt.create():void 0;let i=0;return e.pipeThrough(new TransformStream({transform(e,n){if(i+=e.byteLength,i>t)throw new Error("资源长度超过清单");r?.update(e),n.enqueue(e)},flush(){if(i!==t||r&&tt(r.digest())!==n)throw new Error("资源校验失败")}}))}async function gt(e,t,n,r){if("document"===r.destination||"iframe"===r.destination||"script"===r.destination||"object"===r.destination||"embed"===r.destination)return new Response(null,{status:403});const i=AbortSignal.any([e.offloaded.lifetime.signal,r.signal]),s="GET"===r.method?ht(r.headers.get("Range"),n.size):void 0,o=()=>new Response(null,{status:416,headers:{"Content-Range":`bytes */${n.size}`}});if(s&&(s.start>s.end||s.start>=n.size))return o();const a=e=>fetch(e,{method:r.method,credentials:"omit",redirect:"error",referrerPolicy:"no-referrer",headers:s?{Range:`bytes=${s.start}-${s.end}`}:void 0,signal:i});let c;try{const u=await re(e,t,i);if(c=await a(u),403===c.status){let n;await(c.body?.cancel());try{n=await re(e,t,i,u)}catch{return new Response(null,{status:403})}c=await a(n)}if(200!==c.status&&206!==c.status)return await(c.body?.cancel()),416===c.status?o():new Response(null,{status:c.status});const f=new Headers({"Content-Type":n.mimeType,"Accept-Ranges":"bytes","X-Content-Type-Options":"nosniff","Content-Security-Policy":"default-src 'none'; sandbox"});let d=n.size;if(206===c.status){const e=s&&`bytes ${s.start}-${s.end}/${n.size}`;if(!e||c.headers.get("Content-Range")!==e)throw new Error("无效资源区间");f.set("Content-Range",e),d=s.end-s.start+1}if(f.set("Content-Length",String(d)),"HEAD"===r.method)return new Response(null,{headers:f});if(!c.body)throw new Error("缺少资源正文");const l=d===n.size,h=pt(c.body,d,l?n.sha256:void 0),p=l&&d<=1048576?await new Response(h).arrayBuffer():h;return new Response(p,{status:c.status,headers:f})}catch{return c?.body&&!c.body.locked&&await c.body.cancel().catch(()=>{}),new Response(null,{status:502})}}function me(e,t,n){if(e.files.has(t)){const r=z(e,t);return"HEAD"===n.method?new Response(null,r):r}const r=e.offloaded?.resources.get(t);if(r)return gt(e,t,r,n);if(e.remoteBase){const r=new URL(t,e.remoteBase);return r.search=new URL(n.url).search,we(r.href)}return z(e,t)}async function ie(e,t){try{const n=await p.clients.get(e);if(n){const e=K(n.url);if(e){const n=new URL(t.url);if(e.offloaded&&n.origin!==new URL(p.registration.scope).origin)return fetch(t);const r=S(n.pathname),i=null===r?"":q(r);if(e.offloaded&&i.startsWith("assets/"))return me(e,i,t);if("HEAD"===t.method)return fetch(t);if(i&&e.files.has(i))return z(e,i);if(e.remoteBase){return we(new URL(n.pathname+n.search,new URL(e.remoteBase).origin).href)}}}}catch{}return fetch(t)}function ye(e,t){return new Response(e,{status:200,headers:{"Content-Type":t,"Cache-Control":"no-store, no-cache, must-revalidate, max-age=0",Expires:"0",Pragma:"no-cache","Content-Length":String(e.byteLength)}})}function z(e,t){const n=e.files.get(t);if(!n)return new Response(`Not Found: ${t}`,{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});if(n.mime.startsWith("text/html")){const t=mt(new TextDecoder("utf-8").decode(n.bytes),e.injectHead),r={"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-store","Origin-Agent-Cluster":"?1"};return e.csp&&(r["Content-Security-Policy"]=e.csp),new Response(t,{status:200,headers:r})}return ye(n.bytes,n.mime)}async function we(e){try{return await fetch(e,{method:"GET",credentials:"omit"})}catch{return new Response(`Bad Gateway: ${e}`,{status:502,headers:{"Content-Type":"text/plain; charset=utf-8"}})}}function mt(e,t){if(!t)return e;const n=/<head\b[^>]*>/i.exec(e);if(n){const r=n.index+n[0].length;return e.slice(0,r)+t+e.slice(r)}const r=/<html\b[^>]*>/i.exec(e);if(r){const n=r.index+r[0].length;return`${e.slice(0,n)}<head>${t}</head>${e.slice(n)}`}return`<head>${t}</head>${e}`}const be=52428800,L=2097152,G=2097152,yt=209715200,wt=4,bt=255,se=1e3,Z=new Set(["tmp","usr"]),O=new Set(["usr"]),xt=/^[A-Za-z0-9._-]{1,64}$/,k=new Map;let oe=Promise.resolve();function B(e){const t=oe.then(e,e);return oe=t.then(()=>{},()=>{}),t}function _t(e){k.delete(e)}async function Rt(e){const t=t=>({type:"FS_ACK",op:e.op,id:e.id,reqId:e.reqId,...t});if(!x.has(e.id))return t({ok:!1,error:"simulator not ready",code:"ERR_NOT_MOUNTED"});try{return t(await Et(e))}catch{return t({ok:!1,code:50101,error:"storage io error"})}}async function Et(e){const t=e.fsScope||e.id;switch(e.op){case"fsWriteTempFile":return vt(t,e);case"fsSaveFile":return St(t,e);case"fsWriteFile":return ae(t,e,!1);case"fsAppendFile":return ae(t,e,!0);case"fsReadFile":return Dt(t,e);case"fsReadDir":return At(t,e);case"fsStatFile":return It(t,e);case"fsUnlink":return Ct(t,e);case"fsMkdir":return Tt(t,e);case"fsGetStorageInfo":return Ut(t);default:return{ok:!1,error:`unsupported operation: ${e.op}`,code:"ERR_UNSUPPORTED_OP"}}}async function vt(e,t){const n=Ve(t.data);if("error"in n)return{ok:!1,error:n.error,code:n.code};const r=`tmp/${De()}.${n.ext}`;return await pe(e,r,n.bytes,n.mime),{ok:!0,result:{path:r,url:Ae(e,r)}}}async function St(e,t){const n=b(t.tempFilePath,"tempFilePath");if(n)return n;if(void 0!==t.filePath&&null!==t.filePath){const e=b(t.filePath,"filePath");if(e)return e}const r=v(t.tempFilePath,e,new Set(["tmp"]),!1);if("code"in r)return d(r);const i=void 0===t.filePath||null===t.filePath?Mt(r.path):v(t.filePath,e,O,!1);return"code"in i?d(i):B(async()=>{const n=await P(e,r.path);if(!n)return d({code:50202,message:"file not found; reason=not_found"});if(n.isDir)return d({code:50205,message:"not a file"});const s=await I(e),o=J(s);if(o.has(i.path))return d({code:50204,message:"file already exists"});const a=Ee(i.path,o);if("code"in a)return d(a);const c=_e(t.id,s,n.bytes.byteLength,0);return c?d(c):(await ve(e,a.missing),await Xe(e,r.path,i.path,n),Re(t.id,n.bytes.byteLength),{ok:!0,result:{savedFilePath:Ae(e,i.path)}})})}async function ae(e,t,n){const r=b(t.filePath,"filePath");if(r)return r;const i=xe(t.data,"data",!0);if(i)return i;const s=b(t.encoding,"encoding");if(s)return s;const o=v(t.filePath,e,O,!1);if("code"in o)return d(o);if("base64"!==t.encoding&&"utf8"!==t.encoding)return d({code:10001,message:"invalid parameter; reason=encoding_unsupported"});const a=Lt(t.data,t.encoding);return"code"in a?d(a):a.bytes.byteLength>L?d({code:50201,message:"storage quota exceeded; reason=single_over_limit"}):B(async()=>{const r=await I(e),i=J(r),s=await P(e,o.path);if(s?.isDir)return d({code:50205,message:"not a file"});const c=Ee(o.path,i);if("code"in c)return d(c);const u=n?0:s?.bytes.byteLength??0,f=_e(t.id,r,a.bytes.byteLength,u);if(f)return d(f);await ve(e,c.missing);let l=a.bytes;return n&&s&&(l=Ft(s.bytes,a.bytes)),await pe(e,o.path,l,Bt(l,t.encoding)),Re(t.id,a.bytes.byteLength),{ok:!0,result:{writtenBytes:a.bytes.byteLength}}})}async function Dt(e,t){const n=b(t.filePath,"filePath");if(n)return n;const r=b(t.encoding,"encoding");if(r)return r;const i=ce(t.position,"position");if(i)return i;const s=ce(t.length,"length");if(s)return s;const o=v(t.filePath,e,Z,!1);if("code"in o)return d(o);if("base64"!==t.encoding&&"utf8"!==t.encoding)return d({code:10001,message:"invalid parameter; reason=encoding_unsupported"});const a=void 0===t.position?0:t.position,c=void 0===t.length?G:t.length;if(!Number.isSafeInteger(a)||a<0||!Number.isSafeInteger(c)||c<0||c>G)return d({code:10001,message:"invalid parameter; reason=range_invalid"});const u=await P(e,o.path);if(!u)return d({code:50202,message:"file not found"});if(u.isDir)return d({code:50205,message:"not a file"});const f=Math.min(u.bytes.byteLength,a+c),l=a>=u.bytes.byteLength?new ArrayBuffer(0):u.bytes.slice(a,f);let h;if("base64"===t.encoding)h=Ot(l);else try{h=new TextDecoder("utf-8",{fatal:!0}).decode(l)}catch{return d({code:10001,message:"invalid parameter; reason=decode_failed"})}return{ok:!0,result:{data:h,bytesRead:l.byteLength,eof:a+l.byteLength>=u.bytes.byteLength}}}async function At(e,t){const n=b(t.dirPath,"dirPath");if(n)return n;const r=v(t.dirPath,e,Z,!0);if("code"in r)return d(r);const i=await I(e);if(r.relativePath){const e=i.find(e=>e.path===r.path);if(!e)return d({code:50202,message:"file not found"});if(!e.isDir)return d({code:50206,message:"not a directory"})}const s=`${r.path}/`,o=i.filter(e=>{if(!e.path.startsWith(s))return!1;const t=e.path.slice(s.length);return t.length>0&&!t.includes("/")&&!U(e.path)}).sort((e,t)=>e.path.localeCompare(t.path));return{ok:!0,result:{files:o.slice(0,se).map(e=>({name:e.path.slice(s.length),size:e.isDir?0:e.size,lastModified:e.lastModified,isDir:e.isDir})),truncated:o.length>se}}}async function It(e,t){const n=b(t.filePath,"filePath");if(n)return n;const r=v(t.filePath,e,Z,!1);if("code"in r)return d(r);const i=(await I(e)).find(e=>e.path===r.path);return i?{ok:!0,result:{size:i.isDir?0:i.size,lastModified:i.lastModified,isDir:i.isDir}}:d({code:50202,message:"file not found"})}async function Ct(e,t){const n=b(t.filePath,"filePath");if(n)return n;const r=v(t.filePath,e,O,!1);return"code"in r?d(r):B(async()=>{const t=await P(e,r.path);return t?t.isDir?d({code:50205,message:"not a file"}):(await Ke(e,r.path),{ok:!0,result:{}}):d({code:50202,message:"file not found"})})}async function Tt(e,t){const n=b(t.dirPath,"dirPath");if(n)return n;if(void 0!==t.recursive&&"boolean"!=typeof t.recursive)return Q("recursive");const r=v(t.dirPath,e,O,!1);if("code"in r)return d(r);const i=!0===t.recursive;return B(async()=>{const t=J(await I(e)),n=t.get(r.path);if(n)return n.isDir?i?{ok:!0,result:{}}:d({code:50204,message:"file already exists"}):d({code:50205,message:"not a file"});const s=Se(r.path);for(const e of s){const n=t.get(e);if(n&&!n.isDir)return d({code:50205,message:"not a file"});if(!n&&!i)return d({code:50202,message:"file not found"})}if(i)for(const n of s)t.has(n)||await j(e,n);return await j(e,r.path),{ok:!0,result:{}}})}async function Ut(e){const t=await I(e),n=t.filter(e=>!e.isDir&&e.path.startsWith("usr/")&&!U(e.path)),r=t.filter(e=>!e.isDir&&e.path.startsWith("tmp/")&&!U(e.path));return{ok:!0,result:{usedBytes:V(n),limitBytes:be,fileCount:n.length,tmpUsedBytes:V(r),writeChunkMaxBytes:L,readChunkMaxBytes:G}}}function b(e,t){return xe(e,t,!1)}function xe(e,t,n){if("string"!=typeof e||!(n||e.length>0))return Q(t)}function ce(e,t){if(void 0!==e&&"number"!=typeof e)return Q(t)}function Q(e){return{ok:!1,code:10001,error:`invalid parameter; param=${e}`}}function d(e){return{ok:!1,code:e.code,error:e.message}}function v(e,t,n,r){const i=Pt(e,t);if(null===i)return{code:50203,message:"invalid path; reason=dir_not_allowed"};if("__DECODE_ERROR__"===i)return{code:50203,message:"invalid path; reason=traversal"};const s=i.indexOf("/"),o=(-1===s?i:i.slice(0,s)).toLowerCase(),a=-1===s?"":i.slice(s+1);if(!n.has(o)||!r&&0===a.length)return{code:50203,message:"invalid path; reason=dir_not_allowed"};if(i.includes("\0")||i.includes("\\")||a.split("/").includes(".."))return{code:50203,message:"invalid path; reason=traversal"};if((new TextEncoder).encode(a).byteLength>bt)return{code:50203,message:"invalid path; reason=name_too_long"};const c=a?a.split("/"):[];return c.length>4?{code:50203,message:"invalid path; reason=depth_exceeded"}:c.some(e=>"."===e||!xt.test(e))?{code:50203,message:"invalid path; reason=name_invalid"}:c.some(e=>e.startsWith("__xhs"))?{code:50203,message:"invalid path; reason=reserved_name"}:{dir:o,relativePath:a,path:a?`${o}/${a}`:o}}function Pt(e,t){const n=S(e);if(null===n)return"__DECODE_ERROR__";const r=n.split(/[?#]/,1)[0];if(r.includes("\0")||r.includes("\\")||r.split("/").includes(".."))return"__DECODE_ERROR__";let i;if(e.startsWith("xhsfile://"))i=e.slice(10).split(/[?#]/,1)[0];else{let n;try{n=new URL(e)}catch{return null}if("http:"!==n.protocol&&"https:"!==n.protocol)return null;const r="/_xhsfile_/",s=n.pathname.indexOf(r);if(-1===s)return null;const o=n.pathname.slice(s+r.length),a=o.indexOf("/");if(a<=0||S(o.slice(0,a))!==t)return null;i=o.slice(a+1)}const s=S(i);return null===s?"__DECODE_ERROR__":s}function Lt(e,t){if("utf8"===t)return e.length>L?{code:50201,message:"storage quota exceeded; reason=single_over_limit"}:{bytes:(new TextEncoder).encode(e).buffer};if(e.length>Math.ceil(4*L/3)+4)return{code:50201,message:"storage quota exceeded; reason=single_over_limit"};if(!kt(e))return{code:10001,message:"invalid parameter; reason=decode_failed"};try{const t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return{bytes:n.buffer}}catch{return{code:10001,message:"invalid parameter; reason=decode_failed"}}}function kt(e){return e.length%4==0&&/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e)}function _e(e,t,n,r){return(k.get(e)??0)+n>yt?{code:50201,message:"storage quota exceeded; reason=session_limit"}:V(t.filter(e=>!e.isDir&&e.path.startsWith("usr/")&&!U(e.path)))-r+n>be?{code:50201,message:"storage quota exceeded; reason=total_over_limit"}:void 0}function Re(e,t){k.set(e,(k.get(e)??0)+t)}function J(e){return new Map(e.map(e=>[e.path,e]))}function Ee(e,t){const n=[];for(const r of Se(e)){const e=t.get(r);if(e&&!e.isDir)return{code:50205,message:"not a file"};e||n.push(r)}return{missing:n}}async function ve(e,t){for(const n of t)await j(e,n)}function Se(e){const t=e.split("/"),n=[];for(let e=2;e<t.length;e++)n.push(t.slice(0,e).join("/"));return n}function Mt(e){const t=e.slice(e.lastIndexOf("/")+1),n=t.lastIndexOf("."),r=n>0?t.slice(n):"",i=`${De()}${r}`;return{dir:"usr",relativePath:i,path:`usr/${i}`}}function Ft(e,t){const n=new Uint8Array(e.byteLength+t.byteLength);return n.set(new Uint8Array(e),0),n.set(new Uint8Array(t),e.byteLength),n.buffer}function Ot(e){const t=new Uint8Array(e);let n="";for(let e=0;e<t.length;e+=32768)n+=String.fromCharCode(...t.subarray(e,e+32768));return btoa(n)}function Bt(e,t){return le(e)??("utf8"===t?"text/plain; charset=utf-8":"application/octet-stream")}function V(e){return e.reduce((e,t)=>e+t.size,0)}function U(e){return e.split("/").some(e=>e.startsWith("__xhs"))}function De(){if(typeof crypto<"u"&&"function"==typeof crypto.randomUUID)return crypto.randomUUID().replace(/-/g,"");let e="";for(let t=0;t<32;t++)e+=Math.floor(16*Math.random()).toString(16);return e}function Ae(e,t){return`${p.registration.scope}_xhsfile_/${encodeURIComponent(e)}/${t}`}function Wt(e){let t;try{t=new URL(e).pathname}catch{return null}const n="/_xhsfile_/",r=t.indexOf(n);if(-1===r)return null;const i=t.slice(r+11),s=i.indexOf("/");if(s<=0)return null;const o=S(i.slice(0,s)),a=S(i.slice(s+1));return!o||!a||a.includes("\0")||a.includes("\\")||a.split("/").includes("..")?null:{scope:o,path:a}}async function Nt(e,t){try{const n=await P(e,t);if(n&&!n.isDir&&!U(t)){const e=le(n.bytes);if(e)return ye(n.bytes,e)}}catch{}return new Response("Not Found",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}})}async function fe(e,t,n){const{app:r,filePath:i}=e;if(r.offloaded&&new URL(t.url).origin!==new URL(p.registration.scope).origin)return fetch(t);if(r.offloaded?.resources.has(i)&&!r.files.has(i)){const e=n&&await p.clients.get(n);if(!e||K(e.url)!==r)return new Response(null,{status:403})}return me(r,i,t)}async function $t(e,t){if(t)try{const e=await p.clients.matchAll({type:"window",includeUncontrolled:!0});Oe(new Set(e.map(e=>e.id)))}catch{}return Fe({...e,ownerClientId:t})}function jt(e){if(!e||"object"!=typeof e||!("id"in e))return"";const t=e.id;return"string"==typeof t?t:""}p.addEventListener("install",()=>{p.skipWaiting()}),p.addEventListener("activate",e=>{e.waitUntil(p.clients.claim())}),p.addEventListener("message",e=>{const t=e.data;if(!t||"string"!=typeof t.type)return;const n=t=>e.ports?.[0]?.postMessage(t);if("MOUNT"===t.type){const r=$t(t,jt(e.source)).then(e=>n({type:"MOUNT_ACK",id:t.id,ok:!0,count:e,swVersion:6,fsOps:$e}),e=>{const r=e;n({type:"MOUNT_ACK",id:t.id,ok:!1,error:r instanceof Error?r.message:String(e),code:r?.code})});return void e.waitUntil?.(r)}if("FS"===t.type){const r=t,i=Rt(r).then(n,e=>n({type:"FS_ACK",op:r.op,id:r.id,reqId:r.reqId,ok:!1,error:e instanceof Error?e.message:String(e),code:"ERR_UNKNOWN"}));return void e.waitUntil?.(i)}"UNMOUNT"===t.type&&(_t(t.id),Y(t.id))}),p.addEventListener("fetch",e=>{if("worker"===e.request.destination||"sharedworker"===e.request.destination)return void e.respondWith(ze(e.request,e.clientId));if("HEAD"===e.request.method){const t=T(e.request.url);return void(t?.app.offloaded?e.respondWith(fe(t,e.request,e.clientId)):!t&&e.clientId&&e.respondWith(ie(e.clientId,e.request)))}if("GET"!==e.request.method)return;const t=Wt(e.request.url);if(t)return void e.respondWith(Nt(t.scope,t.path));const n=T(e.request.url);if(n)return void e.respondWith(fe(n,e.request,e.clientId));const r=e.clientId||e.resultingClientId;r&&e.respondWith(ie(r,e.request))});
|