single-file-zip.js 185 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963
  1. const { Array, Object: Object$1, String, Number, BigInt, Math, Date, Map, Set, Response, URL, Error, Uint8Array, Uint16Array, Uint32Array, DataView, Blob, Promise: Promise$1, TextEncoder, TextDecoder, crypto, btoa, TransformStream, ReadableStream, WritableStream, CompressionStream, DecompressionStream, navigator, Worker } = globalThis;
  2. /*
  3. Copyright (c) 2022 Gildas Lormeau. All rights reserved.
  4. Redistribution and use in source and binary forms, with or without
  5. modification, are permitted provided that the following conditions are met:
  6. 1. Redistributions of source code must retain the above copyright notice,
  7. this list of conditions and the following disclaimer.
  8. 2. Redistributions in binary form must reproduce the above copyright
  9. notice, this list of conditions and the following disclaimer in
  10. the documentation and/or other materials provided with the distribution.
  11. 3. The names of the authors may not be used to endorse or promote products
  12. derived from this software without specific prior written permission.
  13. THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  14. INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  15. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
  16. INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
  17. INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  18. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  19. OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  20. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  21. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  22. EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  23. */
  24. const MAX_32_BITS = 0xffffffff;
  25. const MAX_16_BITS = 0xffff;
  26. const COMPRESSION_METHOD_DEFLATE = 0x08;
  27. const COMPRESSION_METHOD_STORE = 0x00;
  28. const COMPRESSION_METHOD_AES = 0x63;
  29. const LOCAL_FILE_HEADER_SIGNATURE = 0x04034b50;
  30. const SPLIT_ZIP_FILE_SIGNATURE = 0x08074b50;
  31. const DATA_DESCRIPTOR_RECORD_SIGNATURE = SPLIT_ZIP_FILE_SIGNATURE;
  32. const CENTRAL_FILE_HEADER_SIGNATURE = 0x02014b50;
  33. const END_OF_CENTRAL_DIR_SIGNATURE = 0x06054b50;
  34. const ZIP64_END_OF_CENTRAL_DIR_SIGNATURE = 0x06064b50;
  35. const ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIGNATURE = 0x07064b50;
  36. const END_OF_CENTRAL_DIR_LENGTH = 22;
  37. const ZIP64_END_OF_CENTRAL_DIR_LOCATOR_LENGTH = 20;
  38. const ZIP64_END_OF_CENTRAL_DIR_LENGTH = 56;
  39. const ZIP64_END_OF_CENTRAL_DIR_TOTAL_LENGTH = END_OF_CENTRAL_DIR_LENGTH + ZIP64_END_OF_CENTRAL_DIR_LOCATOR_LENGTH + ZIP64_END_OF_CENTRAL_DIR_LENGTH;
  40. const EXTRAFIELD_TYPE_ZIP64 = 0x0001;
  41. const EXTRAFIELD_TYPE_AES = 0x9901;
  42. const EXTRAFIELD_TYPE_NTFS = 0x000a;
  43. const EXTRAFIELD_TYPE_NTFS_TAG1 = 0x0001;
  44. const EXTRAFIELD_TYPE_EXTENDED_TIMESTAMP = 0x5455;
  45. const EXTRAFIELD_TYPE_UNICODE_PATH = 0x7075;
  46. const EXTRAFIELD_TYPE_UNICODE_COMMENT = 0x6375;
  47. const EXTRAFIELD_TYPE_USDZ = 0x1986;
  48. const BITFLAG_ENCRYPTED = 0x01;
  49. const BITFLAG_LEVEL = 0x06;
  50. const BITFLAG_DATA_DESCRIPTOR = 0x0008;
  51. const BITFLAG_LANG_ENCODING_FLAG = 0x0800;
  52. const FILE_ATTR_MSDOS_DIR_MASK = 0x10;
  53. const VERSION_DEFLATE = 0x14;
  54. const VERSION_ZIP64 = 0x2D;
  55. const VERSION_AES = 0x33;
  56. const DIRECTORY_SIGNATURE = "/";
  57. const MAX_DATE = new Date(2107, 11, 31);
  58. const MIN_DATE = new Date(1980, 0, 1);
  59. const UNDEFINED_VALUE = undefined;
  60. const UNDEFINED_TYPE$1 = "undefined";
  61. const FUNCTION_TYPE$1 = "function";
  62. /*
  63. Copyright (c) 2022 Gildas Lormeau. All rights reserved.
  64. Redistribution and use in source and binary forms, with or without
  65. modification, are permitted provided that the following conditions are met:
  66. 1. Redistributions of source code must retain the above copyright notice,
  67. this list of conditions and the following disclaimer.
  68. 2. Redistributions in binary form must reproduce the above copyright
  69. notice, this list of conditions and the following disclaimer in
  70. the documentation and/or other materials provided with the distribution.
  71. 3. The names of the authors may not be used to endorse or promote products
  72. derived from this software without specific prior written permission.
  73. THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  74. INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  75. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
  76. INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
  77. INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  78. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  79. OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  80. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  81. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  82. EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  83. */
  84. class StreamAdapter {
  85. constructor(Codec) {
  86. return class extends TransformStream {
  87. constructor(_format, options) {
  88. const codec = new Codec(options);
  89. super({
  90. transform(chunk, controller) {
  91. controller.enqueue(codec.append(chunk));
  92. },
  93. flush(controller) {
  94. const chunk = codec.flush();
  95. if (chunk) {
  96. controller.enqueue(chunk);
  97. }
  98. }
  99. });
  100. }
  101. };
  102. }
  103. }
  104. /*
  105. Copyright (c) 2022 Gildas Lormeau. All rights reserved.
  106. Redistribution and use in source and binary forms, with or without
  107. modification, are permitted provided that the following conditions are met:
  108. 1. Redistributions of source code must retain the above copyright notice,
  109. this list of conditions and the following disclaimer.
  110. 2. Redistributions in binary form must reproduce the above copyright
  111. notice, this list of conditions and the following disclaimer in
  112. the documentation and/or other materials provided with the distribution.
  113. 3. The names of the authors may not be used to endorse or promote products
  114. derived from this software without specific prior written permission.
  115. THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  116. INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  117. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
  118. INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
  119. INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  120. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  121. OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  122. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  123. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  124. EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  125. */
  126. const MINIMUM_CHUNK_SIZE = 64;
  127. let maxWorkers = 2;
  128. try {
  129. if (typeof navigator != UNDEFINED_TYPE$1 && navigator.hardwareConcurrency) {
  130. maxWorkers = navigator.hardwareConcurrency;
  131. }
  132. } catch (_error) {
  133. // ignored
  134. }
  135. const DEFAULT_CONFIGURATION = {
  136. chunkSize: 512 * 1024,
  137. maxWorkers,
  138. terminateWorkerTimeout: 5000,
  139. useWebWorkers: true,
  140. useCompressionStream: true,
  141. workerScripts: UNDEFINED_VALUE,
  142. CompressionStreamNative: typeof CompressionStream != UNDEFINED_TYPE$1 && CompressionStream,
  143. DecompressionStreamNative: typeof DecompressionStream != UNDEFINED_TYPE$1 && DecompressionStream
  144. };
  145. const config = Object$1.assign({}, DEFAULT_CONFIGURATION);
  146. function getConfiguration() {
  147. return config;
  148. }
  149. function getChunkSize(config) {
  150. return Math.max(config.chunkSize, MINIMUM_CHUNK_SIZE);
  151. }
  152. function configure(configuration) {
  153. const {
  154. baseURL,
  155. chunkSize,
  156. maxWorkers,
  157. terminateWorkerTimeout,
  158. useCompressionStream,
  159. useWebWorkers,
  160. Deflate,
  161. Inflate,
  162. CompressionStream,
  163. DecompressionStream,
  164. workerScripts
  165. } = configuration;
  166. setIfDefined("baseURL", baseURL);
  167. setIfDefined("chunkSize", chunkSize);
  168. setIfDefined("maxWorkers", maxWorkers);
  169. setIfDefined("terminateWorkerTimeout", terminateWorkerTimeout);
  170. setIfDefined("useCompressionStream", useCompressionStream);
  171. setIfDefined("useWebWorkers", useWebWorkers);
  172. if (Deflate) {
  173. config.CompressionStream = new StreamAdapter(Deflate);
  174. }
  175. if (Inflate) {
  176. config.DecompressionStream = new StreamAdapter(Inflate);
  177. }
  178. setIfDefined("CompressionStream", CompressionStream);
  179. setIfDefined("DecompressionStream", DecompressionStream);
  180. if (workerScripts !== UNDEFINED_VALUE) {
  181. const { deflate, inflate } = workerScripts;
  182. if (deflate || inflate) {
  183. if (!config.workerScripts) {
  184. config.workerScripts = {};
  185. }
  186. }
  187. if (deflate) {
  188. if (!Array.isArray(deflate)) {
  189. throw new Error("workerScripts.deflate must be an array");
  190. }
  191. config.workerScripts.deflate = deflate;
  192. }
  193. if (inflate) {
  194. if (!Array.isArray(inflate)) {
  195. throw new Error("workerScripts.inflate must be an array");
  196. }
  197. config.workerScripts.inflate = inflate;
  198. }
  199. }
  200. }
  201. function setIfDefined(propertyName, propertyValue) {
  202. if (propertyValue !== UNDEFINED_VALUE) {
  203. config[propertyName] = propertyValue;
  204. }
  205. }
  206. function e(e){const t=()=>URL.createObjectURL(new Blob(['const{Array:e,Object:t,Number:n,Math:r,Error:s,Uint8Array:a,Uint16Array:i,Uint32Array:o,Int32Array:l,Map:c,DataView:h,Promise:f,TextEncoder:u,crypto:p,postMessage:d,TransformStream:g,ReadableStream:w,WritableStream:v,CompressionStream:y,DecompressionStream:b}=self;class m{constructor(e){return class extends g{constructor(t,n){const r=new e(n);super({transform(e,t){t.enqueue(r.append(e))},flush(e){const t=r.flush();t&&e.enqueue(t)}})}}}}const _=[];for(let e=0;256>e;e++){let t=e;for(let e=0;8>e;e++)1&t?t=t>>>1^3988292384:t>>>=1;_[e]=t}class k{constructor(e){this.crc=e||-1}append(e){let t=0|this.crc;for(let n=0,r=0|e.length;r>n;n++)t=t>>>8^_[255&(t^e[n])];this.crc=t}get(){return~this.crc}}class S extends g{constructor(){let e;const t=new k;super({transform(e,n){t.append(e),n.enqueue(e)},flush(){const n=new a(4);new h(n.buffer).setUint32(0,t.get()),e.value=n}}),e=this}}const z={concat(e,t){if(0===e.length||0===t.length)return e.concat(t);const n=e[e.length-1],r=z.getPartial(n);return 32===r?e.concat(t):z._shiftRight(t,r,0|n,e.slice(0,e.length-1))},bitLength(e){const t=e.length;if(0===t)return 0;const n=e[t-1];return 32*(t-1)+z.getPartial(n)},clamp(e,t){if(32*e.length<t)return e;const n=(e=e.slice(0,r.ceil(t/32))).length;return t&=31,n>0&&t&&(e[n-1]=z.partial(t,e[n-1]&2147483648>>t-1,1)),e},partial:(e,t,n)=>32===e?t:(n?0|t:t<<32-e)+1099511627776*e,getPartial:e=>r.round(e/1099511627776)||32,_shiftRight(e,t,n,r){for(void 0===r&&(r=[]);t>=32;t-=32)r.push(n),n=0;if(0===t)return r.concat(e);for(let s=0;s<e.length;s++)r.push(n|e[s]>>>t),n=e[s]<<32-t;const s=e.length?e[e.length-1]:0,a=z.getPartial(s);return r.push(z.partial(t+a&31,t+a>32?n:r.pop(),1)),r}},D={bytes:{fromBits(e){const t=z.bitLength(e)/8,n=new a(t);let r;for(let s=0;t>s;s++)0==(3&s)&&(r=e[s/4]),n[s]=r>>>24,r<<=8;return n},toBits(e){const t=[];let n,r=0;for(n=0;n<e.length;n++)r=r<<8|e[n],3==(3&n)&&(t.push(r),r=0);return 3&n&&t.push(z.partial(8*(3&n),r)),t}}},C=class{constructor(e){const t=this;t.blockSize=512,t._init=[1732584193,4023233417,2562383102,271733878,3285377520],t._key=[1518500249,1859775393,2400959708,3395469782],e?(t._h=e._h.slice(0),t._buffer=e._buffer.slice(0),t._length=e._length):t.reset()}reset(){const e=this;return e._h=e._init.slice(0),e._buffer=[],e._length=0,e}update(e){const t=this;"string"==typeof e&&(e=D.utf8String.toBits(e));const n=t._buffer=z.concat(t._buffer,e),r=t._length,a=t._length=r+z.bitLength(e);if(a>9007199254740991)throw new s("Cannot hash more than 2^53 - 1 bits");const i=new o(n);let l=0;for(let e=t.blockSize+r-(t.blockSize+r&t.blockSize-1);a>=e;e+=t.blockSize)t._block(i.subarray(16*l,16*(l+1))),l+=1;return n.splice(0,16*l),t}finalize(){const e=this;let t=e._buffer;const n=e._h;t=z.concat(t,[z.partial(1,1)]);for(let e=t.length+2;15&e;e++)t.push(0);for(t.push(r.floor(e._length/4294967296)),t.push(0|e._length);t.length;)e._block(t.splice(0,16));return e.reset(),n}_f(e,t,n,r){return e>19?e>39?e>59?e>79?void 0:t^n^r:t&n|t&r|n&r:t^n^r:t&n|~t&r}_S(e,t){return t<<e|t>>>32-e}_block(t){const n=this,s=n._h,a=e(80);for(let e=0;16>e;e++)a[e]=t[e];let i=s[0],o=s[1],l=s[2],c=s[3],h=s[4];for(let e=0;79>=e;e++){16>e||(a[e]=n._S(1,a[e-3]^a[e-8]^a[e-14]^a[e-16]));const t=n._S(5,i)+n._f(e,o,l,c)+h+a[e]+n._key[r.floor(e/20)]|0;h=c,c=l,l=n._S(30,o),o=i,i=t}s[0]=s[0]+i|0,s[1]=s[1]+o|0,s[2]=s[2]+l|0,s[3]=s[3]+c|0,s[4]=s[4]+h|0}},I={getRandomValues(e){const t=new o(e.buffer),n=e=>{let t=987654321;const n=4294967295;return()=>(t=36969*(65535&t)+(t>>16)&n,(((t<<16)+(e=18e3*(65535&e)+(e>>16)&n)&n)/4294967296+.5)*(r.random()>.5?1:-1))};for(let s,a=0;a<e.length;a+=4){const e=n(4294967296*(s||r.random()));s=987654071*e(),t[a/4]=4294967296*e()|0}return e}},x={importKey:e=>new x.hmacSha1(D.bytes.toBits(e)),pbkdf2(e,t,n,r){if(n=n||1e4,0>r||0>n)throw new s("invalid params to pbkdf2");const a=1+(r>>5)<<2;let i,o,l,c,f;const u=new ArrayBuffer(a),p=new h(u);let d=0;const g=z;for(t=D.bytes.toBits(t),f=1;(a||1)>d;f++){for(i=o=e.encrypt(g.concat(t,[f])),l=1;n>l;l++)for(o=e.encrypt(o),c=0;c<o.length;c++)i[c]^=o[c];for(l=0;(a||1)>d&&l<i.length;l++)p.setInt32(d,i[l]),d+=4}return u.slice(0,r/8)},hmacSha1:class{constructor(e){const t=this,n=t._hash=C,r=[[],[]];t._baseHash=[new n,new n];const s=t._baseHash[0].blockSize/32;e.length>s&&(e=(new n).update(e).finalize());for(let t=0;s>t;t++)r[0][t]=909522486^e[t],r[1][t]=1549556828^e[t];t._baseHash[0].update(r[0]),t._baseHash[1].update(r[1]),t._resultHash=new n(t._baseHash[0])}reset(){const e=this;e._resultHash=new e._hash(e._baseHash[0]),e._updated=!1}update(e){this._updated=!0,this._resultHash.update(e)}digest(){const e=this,t=e._resultHash.finalize(),n=new e._hash(e._baseHash[1]).update(t).finalize();return e.reset(),n}encrypt(e){if(this._updated)throw new s("encrypt on already updated hmac called!");return this.update(e),this.digest(e)}}},A=void 0!==p&&"function"==typeof p.getRandomValues,T="Invalid password",R="Invalid signature",H="zipjs-abort-check-password";function q(e){return A?p.getRandomValues(e):I.getRandomValues(e)}const B=16,K={name:"PBKDF2"},V=t.assign({hash:{name:"HMAC"}},K),P=t.assign({iterations:1e3,hash:{name:"SHA-1"}},K),E=["deriveBits"],U=[8,12,16],W=[16,24,32],M=10,N=[0,0,0,0],O="undefined",F="function",L=typeof p!=O,j=L&&p.subtle,G=L&&typeof j!=O,X=D.bytes,J=class{constructor(e){const t=this;t._tables=[[[],[],[],[],[]],[[],[],[],[],[]]],t._tables[0][0][0]||t._precompute();const n=t._tables[0][4],r=t._tables[1],a=e.length;let i,o,l,c=1;if(4!==a&&6!==a&&8!==a)throw new s("invalid aes key size");for(t._key=[o=e.slice(0),l=[]],i=a;4*a+28>i;i++){let e=o[i-1];(i%a==0||8===a&&i%a==4)&&(e=n[e>>>24]<<24^n[e>>16&255]<<16^n[e>>8&255]<<8^n[255&e],i%a==0&&(e=e<<8^e>>>24^c<<24,c=c<<1^283*(c>>7))),o[i]=o[i-a]^e}for(let e=0;i;e++,i--){const t=o[3&e?i:i-4];l[e]=4>=i||4>e?t:r[0][n[t>>>24]]^r[1][n[t>>16&255]]^r[2][n[t>>8&255]]^r[3][n[255&t]]}}encrypt(e){return this._crypt(e,0)}decrypt(e){return this._crypt(e,1)}_precompute(){const e=this._tables[0],t=this._tables[1],n=e[4],r=t[4],s=[],a=[];let i,o,l,c;for(let e=0;256>e;e++)a[(s[e]=e<<1^283*(e>>7))^e]=e;for(let h=i=0;!n[h];h^=o||1,i=a[i]||1){let a=i^i<<1^i<<2^i<<3^i<<4;a=a>>8^255&a^99,n[h]=a,r[a]=h,c=s[l=s[o=s[h]]];let f=16843009*c^65537*l^257*o^16843008*h,u=257*s[a]^16843008*a;for(let n=0;4>n;n++)e[n][h]=u=u<<24^u>>>8,t[n][a]=f=f<<24^f>>>8}for(let n=0;5>n;n++)e[n]=e[n].slice(0),t[n]=t[n].slice(0)}_crypt(e,t){if(4!==e.length)throw new s("invalid aes block size");const n=this._key[t],r=n.length/4-2,a=[0,0,0,0],i=this._tables[t],o=i[0],l=i[1],c=i[2],h=i[3],f=i[4];let u,p,d,g=e[0]^n[0],w=e[t?3:1]^n[1],v=e[2]^n[2],y=e[t?1:3]^n[3],b=4;for(let e=0;r>e;e++)u=o[g>>>24]^l[w>>16&255]^c[v>>8&255]^h[255&y]^n[b],p=o[w>>>24]^l[v>>16&255]^c[y>>8&255]^h[255&g]^n[b+1],d=o[v>>>24]^l[y>>16&255]^c[g>>8&255]^h[255&w]^n[b+2],y=o[y>>>24]^l[g>>16&255]^c[w>>8&255]^h[255&v]^n[b+3],b+=4,g=u,w=p,v=d;for(let e=0;4>e;e++)a[t?3&-e:e]=f[g>>>24]<<24^f[w>>16&255]<<16^f[v>>8&255]<<8^f[255&y]^n[b++],u=g,g=w,w=v,v=y,y=u;return a}},Q=class{constructor(e,t){this._prf=e,this._initIv=t,this._iv=t}reset(){this._iv=this._initIv}update(e){return this.calculate(this._prf,e,this._iv)}incWord(e){if(255==(e>>24&255)){let t=e>>16&255,n=e>>8&255,r=255&e;255===t?(t=0,255===n?(n=0,255===r?r=0:++r):++n):++t,e=0,e+=t<<16,e+=n<<8,e+=r}else e+=1<<24;return e}incCounter(e){0===(e[0]=this.incWord(e[0]))&&(e[1]=this.incWord(e[1]))}calculate(e,t,n){let r;if(!(r=t.length))return[];const s=z.bitLength(t);for(let s=0;r>s;s+=4){this.incCounter(n);const r=e.encrypt(n);t[s]^=r[0],t[s+1]^=r[1],t[s+2]^=r[2],t[s+3]^=r[3]}return z.clamp(t,s)}},Y=x.hmacSha1;let Z=L&&G&&typeof j.importKey==F,$=L&&G&&typeof j.deriveBits==F;class ee extends g{constructor({password:e,signed:n,encryptionStrength:r,checkPasswordOnly:i}){super({start(){t.assign(this,{ready:new f((e=>this.resolveReady=e)),password:e,signed:n,strength:r-1,pending:new a})},async transform(e,t){const n=this,{password:r,strength:o,resolveReady:l,ready:c}=n;r?(await(async(e,t,n,r)=>{const a=await re(e,t,n,ae(r,0,U[t])),i=ae(r,U[t]);if(a[0]!=i[0]||a[1]!=i[1])throw new s(T)})(n,o,r,ae(e,0,U[o]+2)),e=ae(e,U[o]+2),i?t.error(new s(H)):l()):await c;const h=new a(e.length-M-(e.length-M)%B);t.enqueue(ne(n,e,h,0,M,!0))},async flush(e){const{signed:t,ctr:n,hmac:r,pending:i,ready:o}=this;if(r&&n){await o;const l=ae(i,0,i.length-M),c=ae(i,i.length-M);let h=new a;if(l.length){const e=oe(X,l);r.update(e);const t=n.update(e);h=ie(X,t)}if(t){const e=ae(ie(X,r.digest()),0,M);for(let t=0;M>t;t++)if(e[t]!=c[t])throw new s(R)}e.enqueue(h)}}})}}class te extends g{constructor({password:e,encryptionStrength:n}){let r;super({start(){t.assign(this,{ready:new f((e=>this.resolveReady=e)),password:e,strength:n-1,pending:new a})},async transform(e,t){const n=this,{password:r,strength:s,resolveReady:i,ready:o}=n;let l=new a;r?(l=await(async(e,t,n)=>{const r=q(new a(U[t]));return se(r,await re(e,t,n,r))})(n,s,r),i()):await o;const c=new a(l.length+e.length-e.length%B);c.set(l,0),t.enqueue(ne(n,e,c,l.length,0))},async flush(e){const{ctr:t,hmac:n,pending:s,ready:i}=this;if(n&&t){await i;let o=new a;if(s.length){const e=t.update(oe(X,s));n.update(e),o=ie(X,e)}r.signature=ie(X,n.digest()).slice(0,M),e.enqueue(se(o,r.signature))}}}),r=this}}function ne(e,t,n,r,s,i){const{ctr:o,hmac:l,pending:c}=e,h=t.length-s;let f;for(c.length&&(t=se(c,t),n=((e,t)=>{if(t&&t>e.length){const n=e;(e=new a(t)).set(n,0)}return e})(n,h-h%B)),f=0;h-B>=f;f+=B){const e=oe(X,ae(t,f,f+B));i&&l.update(e);const s=o.update(e);i||l.update(s),n.set(ie(X,s),f+r)}return e.pending=ae(t,f),n}async function re(n,r,s,i){n.password=null;const o=(e=>{if(void 0===u){const t=new a((e=unescape(encodeURIComponent(e))).length);for(let n=0;n<t.length;n++)t[n]=e.charCodeAt(n);return t}return(new u).encode(e)})(s),l=await(async(e,t,n,r,s)=>{if(!Z)return x.importKey(t);try{return await j.importKey("raw",t,n,!1,s)}catch(e){return Z=!1,x.importKey(t)}})(0,o,V,0,E),c=await(async(e,t,n)=>{if(!$)return x.pbkdf2(t,e.salt,P.iterations,n);try{return await j.deriveBits(e,t,n)}catch(r){return $=!1,x.pbkdf2(t,e.salt,P.iterations,n)}})(t.assign({salt:i},P),l,8*(2*W[r]+2)),h=new a(c),f=oe(X,ae(h,0,W[r])),p=oe(X,ae(h,W[r],2*W[r])),d=ae(h,2*W[r]);return t.assign(n,{keys:{key:f,authentication:p,passwordVerification:d},ctr:new Q(new J(f),e.from(N)),hmac:new Y(p)}),d}function se(e,t){let n=e;return e.length+t.length&&(n=new a(e.length+t.length),n.set(e,0),n.set(t,e.length)),n}function ae(e,t,n){return e.subarray(t,n)}function ie(e,t){return e.fromBits(t)}function oe(e,t){return e.toBits(t)}class le extends g{constructor({password:e,passwordVerification:n,checkPasswordOnly:r}){super({start(){t.assign(this,{password:e,passwordVerification:n}),ue(this,e)},transform(e,t){const n=this;if(n.password){const t=he(n,e.subarray(0,12));if(n.password=null,t[11]!=n.passwordVerification)throw new s(T);e=e.subarray(12)}r?t.error(new s(H)):t.enqueue(he(n,e))}})}}class ce extends g{constructor({password:e,passwordVerification:n}){super({start(){t.assign(this,{password:e,passwordVerification:n}),ue(this,e)},transform(e,t){const n=this;let r,s;if(n.password){n.password=null;const t=q(new a(12));t[11]=n.passwordVerification,r=new a(e.length+t.length),r.set(fe(n,t),0),s=12}else r=new a(e.length),s=0;r.set(fe(n,e),s),t.enqueue(r)}})}}function he(e,t){const n=new a(t.length);for(let r=0;r<t.length;r++)n[r]=de(e)^t[r],pe(e,n[r]);return n}function fe(e,t){const n=new a(t.length);for(let r=0;r<t.length;r++)n[r]=de(e)^t[r],pe(e,t[r]);return n}function ue(e,n){const r=[305419896,591751049,878082192];t.assign(e,{keys:r,crcKey0:new k(r[0]),crcKey2:new k(r[2])});for(let t=0;t<n.length;t++)pe(e,n.charCodeAt(t))}function pe(e,t){let[n,s,a]=e.keys;e.crcKey0.append([t]),n=~e.crcKey0.get(),s=we(r.imul(we(s+ge(n)),134775813)+1),e.crcKey2.append([s>>>24]),a=~e.crcKey2.get(),e.keys=[n,s,a]}function de(e){const t=2|e.keys[2];return ge(r.imul(t,1^t)>>>8)}function ge(e){return 255&e}function we(e){return 4294967295&e}const ve="deflate-raw";class ye extends g{constructor(e,{chunkSize:t,CompressionStream:n,CompressionStreamNative:r}){super({});const{compressed:s,encrypted:a,useCompressionStream:i,zipCrypto:o,signed:l,level:c}=e,f=this;let u,p,d=me(super.readable);a&&!o||!l||(u=new S,d=Se(d,u)),s&&(d=ke(d,i,{level:c,chunkSize:t},r,n)),a&&(o?d=Se(d,new ce(e)):(p=new te(e),d=Se(d,p))),_e(f,d,(()=>{let e;a&&!o&&(e=p.signature),a&&!o||!l||(e=new h(u.value.buffer).getUint32(0)),f.signature=e}))}}class be extends g{constructor(e,{chunkSize:t,DecompressionStream:n,DecompressionStreamNative:r}){super({});const{zipCrypto:a,encrypted:i,signed:o,signature:l,compressed:c,useCompressionStream:f}=e;let u,p,d=me(super.readable);i&&(a?d=Se(d,new le(e)):(p=new ee(e),d=Se(d,p))),c&&(d=ke(d,f,{chunkSize:t},r,n)),i&&!a||!o||(u=new S,d=Se(d,u)),_e(this,d,(()=>{if((!i||a)&&o){const e=new h(u.value.buffer);if(l!=e.getUint32(0,!1))throw new s(R)}}))}}function me(e){return Se(e,new g({transform(e,t){e&&e.length&&t.enqueue(e)}}))}function _e(e,n,r){n=Se(n,new g({flush:r})),t.defineProperty(e,"readable",{get:()=>n})}function ke(e,t,n,r,s){try{e=Se(e,new(t&&r?r:s)(ve,n))}catch(r){if(!t)throw r;e=Se(e,new s(ve,n))}return e}function Se(e,t){return e.pipeThrough(t)}const ze="data";class De extends g{constructor(e,n){super({});const r=this,{codecType:s}=e;let a;s.startsWith("deflate")?a=ye:s.startsWith("inflate")&&(a=be);let i=0;const o=new a(e,n),l=super.readable,c=new g({transform(e,t){e&&e.length&&(i+=e.length,t.enqueue(e))},flush(){const{signature:e}=o;t.assign(r,{signature:e,size:i})}});t.defineProperty(r,"readable",{get:()=>l.pipeThrough(o).pipeThrough(c)})}}const Ce=new c,Ie=new c;let xe=0;async function Ae(e){try{const{options:t,scripts:r,config:s}=e;r&&r.length&&importScripts.apply(void 0,r),self.initCodec&&self.initCodec(),s.CompressionStreamNative=self.CompressionStream,s.DecompressionStreamNative=self.DecompressionStream,self.Deflate&&(s.CompressionStream=new m(self.Deflate)),self.Inflate&&(s.DecompressionStream=new m(self.Inflate));const a={highWaterMark:1,size:()=>s.chunkSize},i=e.readable||new w({async pull(e){const t=new f((e=>Ce.set(xe,e)));Te({type:"pull",messageId:xe}),xe=(xe+1)%n.MAX_SAFE_INTEGER;const{value:r,done:s}=await t;e.enqueue(r),s&&e.close()}},a),o=e.writable||new v({async write(e){let t;const r=new f((e=>t=e));Ie.set(xe,t),Te({type:ze,value:e,messageId:xe}),xe=(xe+1)%n.MAX_SAFE_INTEGER,await r}},a),l=new De(t,s);await i.pipeThrough(l).pipeTo(o,{preventClose:!0,preventAbort:!0});try{await o.getWriter().close()}catch(e){}const{signature:c,size:h}=l;Te({type:"close",result:{signature:c,size:h}})}catch(e){Re(e)}}function Te(e){let{value:t}=e;if(t)if(t.length)try{t=new a(t),e.value=t.buffer,d(e,[e.value])}catch(t){d(e)}else d(e);else d(e)}function Re(e=new s("Unknown error")){const{message:t,stack:n,code:r,name:a}=e;d({error:{message:t,stack:n,code:r,name:a}})}addEventListener("message",(({data:e})=>{const{type:t,messageId:n,value:r,done:s}=e;try{if("start"==t&&Ae(e),t==ze){const e=Ce.get(n);Ce.delete(n),e({value:new a(r),done:s})}if("ack"==t){const e=Ie.get(n);Ie.delete(n),e()}}catch(e){Re(e)}}));var He=a,qe=i,Be=l,Ke=new He([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Ve=new He([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),Pe=new He([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Ee=(e,t)=>{for(var n=new qe(31),r=0;31>r;++r)n[r]=t+=1<<e[r-1];var s=new Be(n[30]);for(r=1;30>r;++r)for(var a=n[r];a<n[r+1];++a)s[a]=a-n[r]<<5|r;return{b:n,r:s}},Ue=Ee(Ke,2),We=Ue.b,Me=Ue.r;We[28]=258,Me[258]=28;for(var Ne=Ee(Ve,0),Oe=Ne.b,Fe=Ne.r,Le=new qe(32768),je=0;32768>je;++je){var Ge=(43690&je)>>1|(21845&je)<<1;Ge=(61680&(Ge=(52428&Ge)>>2|(13107&Ge)<<2))>>4|(3855&Ge)<<4,Le[je]=((65280&Ge)>>8|(255&Ge)<<8)>>1}var Xe=(e,t,n)=>{for(var r=e.length,s=0,a=new qe(t);r>s;++s)e[s]&&++a[e[s]-1];var i,o=new qe(t);for(s=1;t>s;++s)o[s]=o[s-1]+a[s-1]<<1;if(n){i=new qe(1<<t);var l=15-t;for(s=0;r>s;++s)if(e[s])for(var c=s<<4|e[s],h=t-e[s],f=o[e[s]-1]++<<h,u=f|(1<<h)-1;u>=f;++f)i[Le[f]>>l]=c}else for(i=new qe(r),s=0;r>s;++s)e[s]&&(i[s]=Le[o[e[s]-1]++]>>15-e[s]);return i},Je=new He(288);for(je=0;144>je;++je)Je[je]=8;for(je=144;256>je;++je)Je[je]=9;for(je=256;280>je;++je)Je[je]=7;for(je=280;288>je;++je)Je[je]=8;var Qe=new He(32);for(je=0;32>je;++je)Qe[je]=5;var Ye=Xe(Je,9,0),Ze=Xe(Je,9,1),$e=Xe(Qe,5,0),et=Xe(Qe,5,1),tt=e=>{for(var t=e[0],n=1;n<e.length;++n)e[n]>t&&(t=e[n]);return t},nt=(e,t,n)=>{var r=t/8|0;return(e[r]|e[r+1]<<8)>>(7&t)&n},rt=(e,t)=>{var n=t/8|0;return(e[n]|e[n+1]<<8|e[n+2]<<16)>>(7&t)},st=e=>(e+7)/8|0,at=(e,t,n)=>((null==t||0>t)&&(t=0),(null==n||n>e.length)&&(n=e.length),new He(e.subarray(t,n))),it=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],ot=(e,t,n)=>{var r=new s(t||it[e]);if(r.code=e,s.captureStackTrace&&s.captureStackTrace(r,ot),!n)throw r;return r},lt=(e,t,n)=>{n<<=7&t;var r=t/8|0;e[r]|=n,e[r+1]|=n>>8},ct=(e,t,n)=>{n<<=7&t;var r=t/8|0;e[r]|=n,e[r+1]|=n>>8,e[r+2]|=n>>16},ht=(e,t)=>{for(var n=[],r=0;r<e.length;++r)e[r]&&n.push({s:r,f:e[r]});var s=n.length,a=n.slice();if(!s)return{t:vt,l:0};if(1==s){var i=new He(n[0].s+1);return i[n[0].s]=1,{t:i,l:1}}n.sort(((e,t)=>e.f-t.f)),n.push({s:-1,f:25001});var o=n[0],l=n[1],c=0,h=1,f=2;for(n[0]={s:-1,f:o.f+l.f,l:o,r:l};h!=s-1;)o=n[n[c].f<n[f].f?c++:f++],l=n[c!=h&&n[c].f<n[f].f?c++:f++],n[h++]={s:-1,f:o.f+l.f,l:o,r:l};var u=a[0].s;for(r=1;s>r;++r)a[r].s>u&&(u=a[r].s);var p=new qe(u+1),d=ft(n[h-1],p,0);if(d>t){r=0;var g=0,w=d-t,v=1<<w;for(a.sort(((e,t)=>p[t.s]-p[e.s]||e.f-t.f));s>r;++r){var y=a[r].s;if(p[y]<=t)break;g+=v-(1<<d-p[y]),p[y]=t}for(g>>=w;g>0;){var b=a[r].s;p[b]<t?g-=1<<t-p[b]++-1:++r}for(;r>=0&&g;--r){var m=a[r].s;p[m]==t&&(--p[m],++g)}d=t}return{t:new He(p),l:d}},ft=(e,t,n)=>-1==e.s?r.max(ft(e.l,t,n+1),ft(e.r,t,n+1)):t[e.s]=n,ut=e=>{for(var t=e.length;t&&!e[--t];);for(var n=new qe(++t),r=0,s=e[0],a=1,i=e=>{n[r++]=e},o=1;t>=o;++o)if(e[o]==s&&o!=t)++a;else{if(!s&&a>2){for(;a>138;a-=138)i(32754);a>2&&(i(a>10?a-11<<5|28690:a-3<<5|12305),a=0)}else if(a>3){for(i(s),--a;a>6;a-=6)i(8304);a>2&&(i(a-3<<5|8208),a=0)}for(;a--;)i(s);a=1,s=e[o]}return{c:n.subarray(0,r),n:t}},pt=(e,t)=>{for(var n=0,r=0;r<t.length;++r)n+=e[r]*t[r];return n},dt=(e,t,n)=>{var r=n.length,s=st(t+2);e[s]=255&r,e[s+1]=r>>8,e[s+2]=255^e[s],e[s+3]=255^e[s+1];for(var a=0;r>a;++a)e[s+a+4]=n[a];return 8*(s+4+r)},gt=(e,t,n,r,s,a,i,o,l,c,h)=>{lt(t,h++,n),++s[256];for(var f=ht(s,15),u=f.t,p=f.l,d=ht(a,15),g=d.t,w=d.l,v=ut(u),y=v.c,b=v.n,m=ut(g),_=m.c,k=m.n,S=new qe(19),z=0;z<y.length;++z)++S[31&y[z]];for(z=0;z<_.length;++z)++S[31&_[z]];for(var D=ht(S,7),C=D.t,I=D.l,x=19;x>4&&!C[Pe[x-1]];--x);var A,T,R,H,q=c+5<<3,B=pt(s,Je)+pt(a,Qe)+i,K=pt(s,u)+pt(a,g)+i+14+3*x+pt(S,C)+2*S[16]+3*S[17]+7*S[18];if(l>=0&&B>=q&&K>=q)return dt(t,h,e.subarray(l,l+c));if(lt(t,h,1+(B>K)),h+=2,B>K){A=Xe(u,p,0),T=u,R=Xe(g,w,0),H=g;var V=Xe(C,I,0);for(lt(t,h,b-257),lt(t,h+5,k-1),lt(t,h+10,x-4),h+=14,z=0;x>z;++z)lt(t,h+3*z,C[Pe[z]]);h+=3*x;for(var P=[y,_],E=0;2>E;++E){var U=P[E];for(z=0;z<U.length;++z){var W=31&U[z];lt(t,h,V[W]),h+=C[W],W>15&&(lt(t,h,U[z]>>5&127),h+=U[z]>>12)}}}else A=Ye,T=Je,R=$e,H=Qe;for(z=0;o>z;++z){var M=r[z];if(M>255){ct(t,h,A[257+(W=M>>18&31)]),h+=T[W+257],W>7&&(lt(t,h,M>>23&31),h+=Ke[W]);var N=31&M;ct(t,h,R[N]),h+=H[N],N>3&&(ct(t,h,M>>5&8191),h+=Ve[N])}else ct(t,h,A[M]),h+=T[M]}return ct(t,h,A[256]),h+T[256]},wt=new Be([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),vt=new He(0),yt=function(){function e(e,t){if("function"==typeof e&&(t=e,e={}),this.ondata=t,this.o=e||{},this.s={l:0,i:32768,w:32768,z:32768},this.b=new He(98304),this.o.dictionary){var n=this.o.dictionary.subarray(-32768);this.b.set(n,32768-n.length),this.s.i=32768-n.length}}return e.prototype.p=function(e,t){this.ondata(((e,t,n,s,a)=>{if(!a&&(a={l:1},t.dictionary)){var i=t.dictionary.subarray(-32768),o=new He(i.length+e.length);o.set(i),o.set(e,i.length),e=o,a.w=i.length}return((e,t,n,s,a,i)=>{var o=i.z||e.length,l=new He(0+o+5*(1+r.ceil(o/7e3))+0),c=l.subarray(0,l.length-0),h=i.l,f=7&(i.r||0);if(t){f&&(c[0]=i.r>>3);for(var u=wt[t-1],p=u>>13,d=8191&u,g=(1<<n)-1,w=i.p||new qe(32768),v=i.h||new qe(g+1),y=r.ceil(n/3),b=2*y,m=t=>(e[t]^e[t+1]<<y^e[t+2]<<b)&g,_=new Be(25e3),k=new qe(288),S=new qe(32),z=0,D=0,C=i.i||0,I=0,x=i.w||0,A=0;o>C+2;++C){var T=m(C),R=32767&C,H=v[T];if(w[R]=H,v[T]=R,C>=x){var q=o-C;if((z>7e3||I>24576)&&(q>423||!h)){f=gt(e,c,0,_,k,S,D,I,A,C-A,f),I=z=D=0,A=C;for(var B=0;286>B;++B)k[B]=0;for(B=0;30>B;++B)S[B]=0}var K=2,V=0,P=d,E=R-H&32767;if(q>2&&T==m(C-E))for(var U=r.min(p,q)-1,W=r.min(32767,C),M=r.min(258,q);W>=E&&--P&&R!=H;){if(e[C+K]==e[C+K-E]){for(var N=0;M>N&&e[C+N]==e[C+N-E];++N);if(N>K){if(K=N,V=E,N>U)break;var O=r.min(E,N-2),F=0;for(B=0;O>B;++B){var L=C-E+B&32767,j=L-w[L]&32767;j>F&&(F=j,H=L)}}}E+=(R=H)-(H=w[R])&32767}if(V){_[I++]=268435456|Me[K]<<18|Fe[V];var G=31&Me[K],X=31&Fe[V];D+=Ke[G]+Ve[X],++k[257+G],++S[X],x=C+K,++z}else _[I++]=e[C],++k[e[C]]}}for(C=r.max(C,x);o>C;++C)_[I++]=e[C],++k[e[C]];f=gt(e,c,h,_,k,S,D,I,A,C-A,f),h||(i.r=7&f|c[f/8|0]<<3,f-=7,i.h=v,i.p=w,i.i=C,i.w=x)}else{for(C=i.w||0;o+h>C;C+=65535){var J=C+65535;o>J||(c[f/8|0]=h,J=o),f=dt(c,f+1,e.subarray(C,J))}i.i=o}return at(l,0,0+st(f)+0)})(e,null==t.level?6:t.level,null==t.mem?r.ceil(1.5*r.max(8,r.min(13,r.log(e.length)))):12+t.mem,0,0,a)})(e,this.o,0,0,this.s),t)},e.prototype.push=function(e,t){this.ondata||ot(5),this.s.l&&ot(4);var n=e.length+this.s.z;if(n>this.b.length){if(n>2*this.b.length-32768){var r=new He(-32768&n);r.set(this.b.subarray(0,this.s.z)),this.b=r}var s=this.b.length-this.s.z;s&&(this.b.set(e.subarray(0,s),this.s.z),this.s.z=this.b.length,this.p(this.b,!1)),this.b.set(this.b.subarray(-32768)),this.b.set(e.subarray(s),32768),this.s.z=e.length-s+32768,this.s.i=32766,this.s.w=32768}else this.b.set(e,this.s.z),this.s.z+=e.length;this.s.l=1&t,(this.s.z>this.s.w+8191||t)&&(this.p(this.b,t||!1),this.s.w=this.s.i,this.s.i-=2)},e}(),bt=function(){function e(e,t){"function"==typeof e&&(t=e,e={}),this.ondata=t;var n=e&&e.dictionary&&e.dictionary.subarray(-32768);this.s={i:0,b:n?n.length:0},this.o=new He(32768),this.p=new He(0),n&&this.o.set(n)}return e.prototype.e=function(e){if(this.ondata||ot(5),this.d&&ot(4),this.p.length){if(e.length){var t=new He(this.p.length+e.length);t.set(this.p),t.set(e,this.p.length),this.p=t}}else this.p=e},e.prototype.c=function(e){this.s.i=+(this.d=e||!1);var t=this.s.b,n=((e,t,n)=>{var s=e.length;if(!s||t.f&&!t.l)return n||new He(0);var a=!n,i=a||2!=t.i,o=t.i;a&&(n=new He(3*s));var l=e=>{var t=n.length;if(e>t){var s=new He(r.max(2*t,e));s.set(n),n=s}},c=t.f||0,h=t.p||0,f=t.b||0,u=t.l,p=t.d,d=t.m,g=t.n,w=8*s;do{if(!u){c=nt(e,h,1);var v=nt(e,h+1,3);if(h+=3,!v){var y=e[(A=st(h)+4)-4]|e[A-3]<<8,b=A+y;if(b>s){o&&ot(0);break}i&&l(f+y),n.set(e.subarray(A,b),f),t.b=f+=y,t.p=h=8*b,t.f=c;continue}if(1==v)u=Ze,p=et,d=9,g=5;else if(2==v){var m=nt(e,h,31)+257,_=nt(e,h+10,15)+4,k=m+nt(e,h+5,31)+1;h+=14;for(var S=new He(k),z=new He(19),D=0;_>D;++D)z[Pe[D]]=nt(e,h+3*D,7);h+=3*_;var C=tt(z),I=(1<<C)-1,x=Xe(z,C,1);for(D=0;k>D;){var A,T=x[nt(e,h,I)];if(h+=15&T,16>(A=T>>4))S[D++]=A;else{var R=0,H=0;for(16==A?(H=3+nt(e,h,3),h+=2,R=S[D-1]):17==A?(H=3+nt(e,h,7),h+=3):18==A&&(H=11+nt(e,h,127),h+=7);H--;)S[D++]=R}}var q=S.subarray(0,m),B=S.subarray(m);d=tt(q),g=tt(B),u=Xe(q,d,1),p=Xe(B,g,1)}else ot(1);if(h>w){o&&ot(0);break}}i&&l(f+131072);for(var K=(1<<d)-1,V=(1<<g)-1,P=h;;P=h){var E=(R=u[rt(e,h)&K])>>4;if((h+=15&R)>w){o&&ot(0);break}if(R||ot(2),256>E)n[f++]=E;else{if(256==E){P=h,u=null;break}var U=E-254;if(E>264){var W=Ke[D=E-257];U=nt(e,h,(1<<W)-1)+We[D],h+=W}var M=p[rt(e,h)&V],N=M>>4;if(M||ot(3),h+=15&M,B=Oe[N],N>3&&(W=Ve[N],B+=rt(e,h)&(1<<W)-1,h+=W),h>w){o&&ot(0);break}i&&l(f+131072);var O=f+U;if(B>f){var F=0-B,L=r.min(B,O);for(0>F+f&&ot(3);L>f;++f)n[f]=undefined[F+f]}for(;O>f;++f)n[f]=n[f-B]}}t.l=u,t.p=P,t.b=f,t.f=c,u&&(c=1,t.m=d,t.d=p,t.n=g)}while(!c);return f!=n.length&&a?at(n,0,f):n.subarray(0,f)})(this.p,this.s,this.o);this.ondata(at(n,t,this.s.b),this.d),this.o=at(n,this.s.b-32768),this.s.b=this.o.length,this.p=at(this.p,this.s.p/8|0),this.s.p&=7},e.prototype.push=function(e,t){this.e(e),this.c(t)},e}(),mt="undefined"!=typeof TextDecoder&&new TextDecoder;try{mt.decode(vt,{stream:!0})}catch(e){}function _t(e,n,r){return class{constructor(s){const i=this;var o,l;o=s,l="level",("function"==typeof t.hasOwn?t.hasOwn(o,l):o.hasOwnProperty(l))&&void 0===s.level&&delete s.level,i.codec=new e(t.assign({},n,s)),r(i.codec,(e=>{if(i.pendingData){const t=i.pendingData;i.pendingData=new a(t.length+e.length);const{pendingData:n}=i;n.set(t,0),n.set(e,t.length)}else i.pendingData=new a(e)}))}append(e){return this.codec.push(e),s(this)}flush(){return this.codec.push(new a,!0),s(this)}};function s(e){if(e.pendingData){const t=e.pendingData;return e.pendingData=null,t}return new a}}const{Deflate:kt,Inflate:St}=((e,t={},n)=>({Deflate:_t(e.Deflate,t.deflate,n),Inflate:_t(e.Inflate,t.inflate,n)}))({Deflate:yt,Inflate:bt},void 0,((e,t)=>e.ondata=t));self.initCodec=()=>{self.Deflate=kt,self.Inflate=St};\n'],{type:"text/javascript"}));e({workerScripts:{inflate:[t],deflate:[t]}});}
  207. /*
  208. Copyright (c) 2022 Gildas Lormeau. All rights reserved.
  209. Redistribution and use in source and binary forms, with or without
  210. modification, are permitted provided that the following conditions are met:
  211. 1. Redistributions of source code must retain the above copyright notice,
  212. this list of conditions and the following disclaimer.
  213. 2. Redistributions in binary form must reproduce the above copyright
  214. notice, this list of conditions and the following disclaimer in
  215. the documentation and/or other materials provided with the distribution.
  216. 3. The names of the authors may not be used to endorse or promote products
  217. derived from this software without specific prior written permission.
  218. THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  219. INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  220. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
  221. INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
  222. INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  223. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  224. OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  225. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  226. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  227. EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  228. */
  229. function getMimeType() {
  230. return "application/octet-stream";
  231. }
  232. function initShimAsyncCodec(library, options = {}, registerDataHandler) {
  233. return {
  234. Deflate: createCodecClass(library.Deflate, options.deflate, registerDataHandler),
  235. Inflate: createCodecClass(library.Inflate, options.inflate, registerDataHandler)
  236. };
  237. }
  238. function objectHasOwn(object, propertyName) {
  239. // eslint-disable-next-line no-prototype-builtins
  240. return typeof Object$1.hasOwn === "function" ? Object$1.hasOwn(object, propertyName) : object.hasOwnProperty(propertyName);
  241. }
  242. function createCodecClass(constructor, constructorOptions, registerDataHandler) {
  243. return class {
  244. constructor(options) {
  245. const codecAdapter = this;
  246. const onData = data => {
  247. if (codecAdapter.pendingData) {
  248. const previousPendingData = codecAdapter.pendingData;
  249. codecAdapter.pendingData = new Uint8Array(previousPendingData.length + data.length);
  250. const { pendingData } = codecAdapter;
  251. pendingData.set(previousPendingData, 0);
  252. pendingData.set(data, previousPendingData.length);
  253. } else {
  254. codecAdapter.pendingData = new Uint8Array(data);
  255. }
  256. };
  257. if (objectHasOwn(options, "level") && options.level === undefined) {
  258. delete options.level;
  259. }
  260. codecAdapter.codec = new constructor(Object$1.assign({}, constructorOptions, options));
  261. registerDataHandler(codecAdapter.codec, onData);
  262. }
  263. append(data) {
  264. this.codec.push(data);
  265. return getResponse(this);
  266. }
  267. flush() {
  268. this.codec.push(new Uint8Array(), true);
  269. return getResponse(this);
  270. }
  271. };
  272. function getResponse(codec) {
  273. if (codec.pendingData) {
  274. const output = codec.pendingData;
  275. codec.pendingData = null;
  276. return output;
  277. } else {
  278. return new Uint8Array();
  279. }
  280. }
  281. }
  282. /*
  283. Copyright (c) 2022 Gildas Lormeau. All rights reserved.
  284. Redistribution and use in source and binary forms, with or without
  285. modification, are permitted provided that the following conditions are met:
  286. 1. Redistributions of source code must retain the above copyright notice,
  287. this list of conditions and the following disclaimer.
  288. 2. Redistributions in binary form must reproduce the above copyright
  289. notice, this list of conditions and the following disclaimer in
  290. the documentation and/or other materials provided with the distribution.
  291. 3. The names of the authors may not be used to endorse or promote products
  292. derived from this software without specific prior written permission.
  293. THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  294. INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  295. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
  296. INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
  297. INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  298. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  299. OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  300. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  301. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  302. EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  303. */
  304. const table = [];
  305. for (let i = 0; i < 256; i++) {
  306. let t = i;
  307. for (let j = 0; j < 8; j++) {
  308. if (t & 1) {
  309. t = (t >>> 1) ^ 0xEDB88320;
  310. } else {
  311. t = t >>> 1;
  312. }
  313. }
  314. table[i] = t;
  315. }
  316. class Crc32 {
  317. constructor(crc) {
  318. this.crc = crc || -1;
  319. }
  320. append(data) {
  321. let crc = this.crc | 0;
  322. for (let offset = 0, length = data.length | 0; offset < length; offset++) {
  323. crc = (crc >>> 8) ^ table[(crc ^ data[offset]) & 0xFF];
  324. }
  325. this.crc = crc;
  326. }
  327. get() {
  328. return ~this.crc;
  329. }
  330. }
  331. /*
  332. Copyright (c) 2022 Gildas Lormeau. All rights reserved.
  333. Redistribution and use in source and binary forms, with or without
  334. modification, are permitted provided that the following conditions are met:
  335. 1. Redistributions of source code must retain the above copyright notice,
  336. this list of conditions and the following disclaimer.
  337. 2. Redistributions in binary form must reproduce the above copyright
  338. notice, this list of conditions and the following disclaimer in
  339. the documentation and/or other materials provided with the distribution.
  340. 3. The names of the authors may not be used to endorse or promote products
  341. derived from this software without specific prior written permission.
  342. THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  343. INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  344. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
  345. INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
  346. INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  347. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  348. OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  349. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  350. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  351. EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  352. */
  353. class Crc32Stream extends TransformStream {
  354. constructor() {
  355. let stream;
  356. const crc32 = new Crc32();
  357. super({
  358. transform(chunk, controller) {
  359. crc32.append(chunk);
  360. controller.enqueue(chunk);
  361. },
  362. flush() {
  363. const value = new Uint8Array(4);
  364. const dataView = new DataView(value.buffer);
  365. dataView.setUint32(0, crc32.get());
  366. stream.value = value;
  367. }
  368. });
  369. stream = this;
  370. }
  371. }
  372. /*
  373. Copyright (c) 2022 Gildas Lormeau. All rights reserved.
  374. Redistribution and use in source and binary forms, with or without
  375. modification, are permitted provided that the following conditions are met:
  376. 1. Redistributions of source code must retain the above copyright notice,
  377. this list of conditions and the following disclaimer.
  378. 2. Redistributions in binary form must reproduce the above copyright
  379. notice, this list of conditions and the following disclaimer in
  380. the documentation and/or other materials provided with the distribution.
  381. 3. The names of the authors may not be used to endorse or promote products
  382. derived from this software without specific prior written permission.
  383. THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  384. INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  385. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
  386. INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
  387. INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  388. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  389. OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  390. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  391. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  392. EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  393. */
  394. function encodeText(value) {
  395. if (typeof TextEncoder == "undefined") {
  396. value = unescape(encodeURIComponent(value));
  397. const result = new Uint8Array(value.length);
  398. for (let i = 0; i < result.length; i++) {
  399. result[i] = value.charCodeAt(i);
  400. }
  401. return result;
  402. } else {
  403. return new TextEncoder().encode(value);
  404. }
  405. }
  406. // Derived from https://github.com/xqdoo00o/jszip/blob/master/lib/sjcl.js and https://github.com/bitwiseshiftleft/sjcl
  407. // deno-lint-ignore-file no-this-alias
  408. /*
  409. * SJCL is open. You can use, modify and redistribute it under a BSD
  410. * license or under the GNU GPL, version 2.0.
  411. */
  412. /** @fileOverview Javascript cryptography implementation.
  413. *
  414. * Crush to remove comments, shorten variable names and
  415. * generally reduce transmission size.
  416. *
  417. * @author Emily Stark
  418. * @author Mike Hamburg
  419. * @author Dan Boneh
  420. */
  421. /*jslint indent: 2, bitwise: false, nomen: false, plusplus: false, white: false, regexp: false */
  422. /** @fileOverview Arrays of bits, encoded as arrays of Numbers.
  423. *
  424. * @author Emily Stark
  425. * @author Mike Hamburg
  426. * @author Dan Boneh
  427. */
  428. /**
  429. * Arrays of bits, encoded as arrays of Numbers.
  430. * @namespace
  431. * @description
  432. * <p>
  433. * These objects are the currency accepted by SJCL's crypto functions.
  434. * </p>
  435. *
  436. * <p>
  437. * Most of our crypto primitives operate on arrays of 4-byte words internally,
  438. * but many of them can take arguments that are not a multiple of 4 bytes.
  439. * This library encodes arrays of bits (whose size need not be a multiple of 8
  440. * bits) as arrays of 32-bit words. The bits are packed, big-endian, into an
  441. * array of words, 32 bits at a time. Since the words are double-precision
  442. * floating point numbers, they fit some extra data. We use this (in a private,
  443. * possibly-changing manner) to encode the number of bits actually present
  444. * in the last word of the array.
  445. * </p>
  446. *
  447. * <p>
  448. * Because bitwise ops clear this out-of-band data, these arrays can be passed
  449. * to ciphers like AES which want arrays of words.
  450. * </p>
  451. */
  452. const bitArray = {
  453. /**
  454. * Concatenate two bit arrays.
  455. * @param {bitArray} a1 The first array.
  456. * @param {bitArray} a2 The second array.
  457. * @return {bitArray} The concatenation of a1 and a2.
  458. */
  459. concat(a1, a2) {
  460. if (a1.length === 0 || a2.length === 0) {
  461. return a1.concat(a2);
  462. }
  463. const last = a1[a1.length - 1], shift = bitArray.getPartial(last);
  464. if (shift === 32) {
  465. return a1.concat(a2);
  466. } else {
  467. return bitArray._shiftRight(a2, shift, last | 0, a1.slice(0, a1.length - 1));
  468. }
  469. },
  470. /**
  471. * Find the length of an array of bits.
  472. * @param {bitArray} a The array.
  473. * @return {Number} The length of a, in bits.
  474. */
  475. bitLength(a) {
  476. const l = a.length;
  477. if (l === 0) {
  478. return 0;
  479. }
  480. const x = a[l - 1];
  481. return (l - 1) * 32 + bitArray.getPartial(x);
  482. },
  483. /**
  484. * Truncate an array.
  485. * @param {bitArray} a The array.
  486. * @param {Number} len The length to truncate to, in bits.
  487. * @return {bitArray} A new array, truncated to len bits.
  488. */
  489. clamp(a, len) {
  490. if (a.length * 32 < len) {
  491. return a;
  492. }
  493. a = a.slice(0, Math.ceil(len / 32));
  494. const l = a.length;
  495. len = len & 31;
  496. if (l > 0 && len) {
  497. a[l - 1] = bitArray.partial(len, a[l - 1] & 0x80000000 >> (len - 1), 1);
  498. }
  499. return a;
  500. },
  501. /**
  502. * Make a partial word for a bit array.
  503. * @param {Number} len The number of bits in the word.
  504. * @param {Number} x The bits.
  505. * @param {Number} [_end=0] Pass 1 if x has already been shifted to the high side.
  506. * @return {Number} The partial word.
  507. */
  508. partial(len, x, _end) {
  509. if (len === 32) {
  510. return x;
  511. }
  512. return (_end ? x | 0 : x << (32 - len)) + len * 0x10000000000;
  513. },
  514. /**
  515. * Get the number of bits used by a partial word.
  516. * @param {Number} x The partial word.
  517. * @return {Number} The number of bits used by the partial word.
  518. */
  519. getPartial(x) {
  520. return Math.round(x / 0x10000000000) || 32;
  521. },
  522. /** Shift an array right.
  523. * @param {bitArray} a The array to shift.
  524. * @param {Number} shift The number of bits to shift.
  525. * @param {Number} [carry=0] A byte to carry in
  526. * @param {bitArray} [out=[]] An array to prepend to the output.
  527. * @private
  528. */
  529. _shiftRight(a, shift, carry, out) {
  530. if (out === undefined) {
  531. out = [];
  532. }
  533. for (; shift >= 32; shift -= 32) {
  534. out.push(carry);
  535. carry = 0;
  536. }
  537. if (shift === 0) {
  538. return out.concat(a);
  539. }
  540. for (let i = 0; i < a.length; i++) {
  541. out.push(carry | a[i] >>> shift);
  542. carry = a[i] << (32 - shift);
  543. }
  544. const last2 = a.length ? a[a.length - 1] : 0;
  545. const shift2 = bitArray.getPartial(last2);
  546. out.push(bitArray.partial(shift + shift2 & 31, (shift + shift2 > 32) ? carry : out.pop(), 1));
  547. return out;
  548. }
  549. };
  550. /** @fileOverview Bit array codec implementations.
  551. *
  552. * @author Emily Stark
  553. * @author Mike Hamburg
  554. * @author Dan Boneh
  555. */
  556. /**
  557. * Arrays of bytes
  558. * @namespace
  559. */
  560. const codec = {
  561. bytes: {
  562. /** Convert from a bitArray to an array of bytes. */
  563. fromBits(arr) {
  564. const bl = bitArray.bitLength(arr);
  565. const byteLength = bl / 8;
  566. const out = new Uint8Array(byteLength);
  567. let tmp;
  568. for (let i = 0; i < byteLength; i++) {
  569. if ((i & 3) === 0) {
  570. tmp = arr[i / 4];
  571. }
  572. out[i] = tmp >>> 24;
  573. tmp <<= 8;
  574. }
  575. return out;
  576. },
  577. /** Convert from an array of bytes to a bitArray. */
  578. toBits(bytes) {
  579. const out = [];
  580. let i;
  581. let tmp = 0;
  582. for (i = 0; i < bytes.length; i++) {
  583. tmp = tmp << 8 | bytes[i];
  584. if ((i & 3) === 3) {
  585. out.push(tmp);
  586. tmp = 0;
  587. }
  588. }
  589. if (i & 3) {
  590. out.push(bitArray.partial(8 * (i & 3), tmp));
  591. }
  592. return out;
  593. }
  594. }
  595. };
  596. const hash = {};
  597. /**
  598. * Context for a SHA-1 operation in progress.
  599. * @constructor
  600. */
  601. hash.sha1 = class {
  602. constructor(hash) {
  603. const sha1 = this;
  604. /**
  605. * The hash's block size, in bits.
  606. * @constant
  607. */
  608. sha1.blockSize = 512;
  609. /**
  610. * The SHA-1 initialization vector.
  611. * @private
  612. */
  613. sha1._init = [0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0];
  614. /**
  615. * The SHA-1 hash key.
  616. * @private
  617. */
  618. sha1._key = [0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xCA62C1D6];
  619. if (hash) {
  620. sha1._h = hash._h.slice(0);
  621. sha1._buffer = hash._buffer.slice(0);
  622. sha1._length = hash._length;
  623. } else {
  624. sha1.reset();
  625. }
  626. }
  627. /**
  628. * Reset the hash state.
  629. * @return this
  630. */
  631. reset() {
  632. const sha1 = this;
  633. sha1._h = sha1._init.slice(0);
  634. sha1._buffer = [];
  635. sha1._length = 0;
  636. return sha1;
  637. }
  638. /**
  639. * Input several words to the hash.
  640. * @param {bitArray|String} data the data to hash.
  641. * @return this
  642. */
  643. update(data) {
  644. const sha1 = this;
  645. if (typeof data === "string") {
  646. data = codec.utf8String.toBits(data);
  647. }
  648. const b = sha1._buffer = bitArray.concat(sha1._buffer, data);
  649. const ol = sha1._length;
  650. const nl = sha1._length = ol + bitArray.bitLength(data);
  651. if (nl > 9007199254740991) {
  652. throw new Error("Cannot hash more than 2^53 - 1 bits");
  653. }
  654. const c = new Uint32Array(b);
  655. let j = 0;
  656. for (let i = sha1.blockSize + ol - ((sha1.blockSize + ol) & (sha1.blockSize - 1)); i <= nl;
  657. i += sha1.blockSize) {
  658. sha1._block(c.subarray(16 * j, 16 * (j + 1)));
  659. j += 1;
  660. }
  661. b.splice(0, 16 * j);
  662. return sha1;
  663. }
  664. /**
  665. * Complete hashing and output the hash value.
  666. * @return {bitArray} The hash value, an array of 5 big-endian words. TODO
  667. */
  668. finalize() {
  669. const sha1 = this;
  670. let b = sha1._buffer;
  671. const h = sha1._h;
  672. // Round out and push the buffer
  673. b = bitArray.concat(b, [bitArray.partial(1, 1)]);
  674. // Round out the buffer to a multiple of 16 words, less the 2 length words.
  675. for (let i = b.length + 2; i & 15; i++) {
  676. b.push(0);
  677. }
  678. // append the length
  679. b.push(Math.floor(sha1._length / 0x100000000));
  680. b.push(sha1._length | 0);
  681. while (b.length) {
  682. sha1._block(b.splice(0, 16));
  683. }
  684. sha1.reset();
  685. return h;
  686. }
  687. /**
  688. * The SHA-1 logical functions f(0), f(1), ..., f(79).
  689. * @private
  690. */
  691. _f(t, b, c, d) {
  692. if (t <= 19) {
  693. return (b & c) | (~b & d);
  694. } else if (t <= 39) {
  695. return b ^ c ^ d;
  696. } else if (t <= 59) {
  697. return (b & c) | (b & d) | (c & d);
  698. } else if (t <= 79) {
  699. return b ^ c ^ d;
  700. }
  701. }
  702. /**
  703. * Circular left-shift operator.
  704. * @private
  705. */
  706. _S(n, x) {
  707. return (x << n) | (x >>> 32 - n);
  708. }
  709. /**
  710. * Perform one cycle of SHA-1.
  711. * @param {Uint32Array|bitArray} words one block of words.
  712. * @private
  713. */
  714. _block(words) {
  715. const sha1 = this;
  716. const h = sha1._h;
  717. // When words is passed to _block, it has 16 elements. SHA1 _block
  718. // function extends words with new elements (at the end there are 80 elements).
  719. // The problem is that if we use Uint32Array instead of Array,
  720. // the length of Uint32Array cannot be changed. Thus, we replace words with a
  721. // normal Array here.
  722. const w = Array(80); // do not use Uint32Array here as the instantiation is slower
  723. for (let j = 0; j < 16; j++) {
  724. w[j] = words[j];
  725. }
  726. let a = h[0];
  727. let b = h[1];
  728. let c = h[2];
  729. let d = h[3];
  730. let e = h[4];
  731. for (let t = 0; t <= 79; t++) {
  732. if (t >= 16) {
  733. w[t] = sha1._S(1, w[t - 3] ^ w[t - 8] ^ w[t - 14] ^ w[t - 16]);
  734. }
  735. const tmp = (sha1._S(5, a) + sha1._f(t, b, c, d) + e + w[t] +
  736. sha1._key[Math.floor(t / 20)]) | 0;
  737. e = d;
  738. d = c;
  739. c = sha1._S(30, b);
  740. b = a;
  741. a = tmp;
  742. }
  743. h[0] = (h[0] + a) | 0;
  744. h[1] = (h[1] + b) | 0;
  745. h[2] = (h[2] + c) | 0;
  746. h[3] = (h[3] + d) | 0;
  747. h[4] = (h[4] + e) | 0;
  748. }
  749. };
  750. /** @fileOverview Low-level AES implementation.
  751. *
  752. * This file contains a low-level implementation of AES, optimized for
  753. * size and for efficiency on several browsers. It is based on
  754. * OpenSSL's aes_core.c, a public-domain implementation by Vincent
  755. * Rijmen, Antoon Bosselaers and Paulo Barreto.
  756. *
  757. * An older version of this implementation is available in the public
  758. * domain, but this one is (c) Emily Stark, Mike Hamburg, Dan Boneh,
  759. * Stanford University 2008-2010 and BSD-licensed for liability
  760. * reasons.
  761. *
  762. * @author Emily Stark
  763. * @author Mike Hamburg
  764. * @author Dan Boneh
  765. */
  766. const cipher = {};
  767. /**
  768. * Schedule out an AES key for both encryption and decryption. This
  769. * is a low-level class. Use a cipher mode to do bulk encryption.
  770. *
  771. * @constructor
  772. * @param {Array} key The key as an array of 4, 6 or 8 words.
  773. */
  774. cipher.aes = class {
  775. constructor(key) {
  776. /**
  777. * The expanded S-box and inverse S-box tables. These will be computed
  778. * on the client so that we don't have to send them down the wire.
  779. *
  780. * There are two tables, _tables[0] is for encryption and
  781. * _tables[1] is for decryption.
  782. *
  783. * The first 4 sub-tables are the expanded S-box with MixColumns. The
  784. * last (_tables[01][4]) is the S-box itself.
  785. *
  786. * @private
  787. */
  788. const aes = this;
  789. aes._tables = [[[], [], [], [], []], [[], [], [], [], []]];
  790. if (!aes._tables[0][0][0]) {
  791. aes._precompute();
  792. }
  793. const sbox = aes._tables[0][4];
  794. const decTable = aes._tables[1];
  795. const keyLen = key.length;
  796. let i, encKey, decKey, rcon = 1;
  797. if (keyLen !== 4 && keyLen !== 6 && keyLen !== 8) {
  798. throw new Error("invalid aes key size");
  799. }
  800. aes._key = [encKey = key.slice(0), decKey = []];
  801. // schedule encryption keys
  802. for (i = keyLen; i < 4 * keyLen + 28; i++) {
  803. let tmp = encKey[i - 1];
  804. // apply sbox
  805. if (i % keyLen === 0 || (keyLen === 8 && i % keyLen === 4)) {
  806. tmp = sbox[tmp >>> 24] << 24 ^ sbox[tmp >> 16 & 255] << 16 ^ sbox[tmp >> 8 & 255] << 8 ^ sbox[tmp & 255];
  807. // shift rows and add rcon
  808. if (i % keyLen === 0) {
  809. tmp = tmp << 8 ^ tmp >>> 24 ^ rcon << 24;
  810. rcon = rcon << 1 ^ (rcon >> 7) * 283;
  811. }
  812. }
  813. encKey[i] = encKey[i - keyLen] ^ tmp;
  814. }
  815. // schedule decryption keys
  816. for (let j = 0; i; j++, i--) {
  817. const tmp = encKey[j & 3 ? i : i - 4];
  818. if (i <= 4 || j < 4) {
  819. decKey[j] = tmp;
  820. } else {
  821. decKey[j] = decTable[0][sbox[tmp >>> 24]] ^
  822. decTable[1][sbox[tmp >> 16 & 255]] ^
  823. decTable[2][sbox[tmp >> 8 & 255]] ^
  824. decTable[3][sbox[tmp & 255]];
  825. }
  826. }
  827. }
  828. // public
  829. /* Something like this might appear here eventually
  830. name: "AES",
  831. blockSize: 4,
  832. keySizes: [4,6,8],
  833. */
  834. /**
  835. * Encrypt an array of 4 big-endian words.
  836. * @param {Array} data The plaintext.
  837. * @return {Array} The ciphertext.
  838. */
  839. encrypt(data) {
  840. return this._crypt(data, 0);
  841. }
  842. /**
  843. * Decrypt an array of 4 big-endian words.
  844. * @param {Array} data The ciphertext.
  845. * @return {Array} The plaintext.
  846. */
  847. decrypt(data) {
  848. return this._crypt(data, 1);
  849. }
  850. /**
  851. * Expand the S-box tables.
  852. *
  853. * @private
  854. */
  855. _precompute() {
  856. const encTable = this._tables[0];
  857. const decTable = this._tables[1];
  858. const sbox = encTable[4];
  859. const sboxInv = decTable[4];
  860. const d = [];
  861. const th = [];
  862. let xInv, x2, x4, x8;
  863. // Compute double and third tables
  864. for (let i = 0; i < 256; i++) {
  865. th[(d[i] = i << 1 ^ (i >> 7) * 283) ^ i] = i;
  866. }
  867. for (let x = xInv = 0; !sbox[x]; x ^= x2 || 1, xInv = th[xInv] || 1) {
  868. // Compute sbox
  869. let s = xInv ^ xInv << 1 ^ xInv << 2 ^ xInv << 3 ^ xInv << 4;
  870. s = s >> 8 ^ s & 255 ^ 99;
  871. sbox[x] = s;
  872. sboxInv[s] = x;
  873. // Compute MixColumns
  874. x8 = d[x4 = d[x2 = d[x]]];
  875. let tDec = x8 * 0x1010101 ^ x4 * 0x10001 ^ x2 * 0x101 ^ x * 0x1010100;
  876. let tEnc = d[s] * 0x101 ^ s * 0x1010100;
  877. for (let i = 0; i < 4; i++) {
  878. encTable[i][x] = tEnc = tEnc << 24 ^ tEnc >>> 8;
  879. decTable[i][s] = tDec = tDec << 24 ^ tDec >>> 8;
  880. }
  881. }
  882. // Compactify. Considerable speedup on Firefox.
  883. for (let i = 0; i < 5; i++) {
  884. encTable[i] = encTable[i].slice(0);
  885. decTable[i] = decTable[i].slice(0);
  886. }
  887. }
  888. /**
  889. * Encryption and decryption core.
  890. * @param {Array} input Four words to be encrypted or decrypted.
  891. * @param dir The direction, 0 for encrypt and 1 for decrypt.
  892. * @return {Array} The four encrypted or decrypted words.
  893. * @private
  894. */
  895. _crypt(input, dir) {
  896. if (input.length !== 4) {
  897. throw new Error("invalid aes block size");
  898. }
  899. const key = this._key[dir];
  900. const nInnerRounds = key.length / 4 - 2;
  901. const out = [0, 0, 0, 0];
  902. const table = this._tables[dir];
  903. // load up the tables
  904. const t0 = table[0];
  905. const t1 = table[1];
  906. const t2 = table[2];
  907. const t3 = table[3];
  908. const sbox = table[4];
  909. // state variables a,b,c,d are loaded with pre-whitened data
  910. let a = input[0] ^ key[0];
  911. let b = input[dir ? 3 : 1] ^ key[1];
  912. let c = input[2] ^ key[2];
  913. let d = input[dir ? 1 : 3] ^ key[3];
  914. let kIndex = 4;
  915. let a2, b2, c2;
  916. // Inner rounds. Cribbed from OpenSSL.
  917. for (let i = 0; i < nInnerRounds; i++) {
  918. a2 = t0[a >>> 24] ^ t1[b >> 16 & 255] ^ t2[c >> 8 & 255] ^ t3[d & 255] ^ key[kIndex];
  919. b2 = t0[b >>> 24] ^ t1[c >> 16 & 255] ^ t2[d >> 8 & 255] ^ t3[a & 255] ^ key[kIndex + 1];
  920. c2 = t0[c >>> 24] ^ t1[d >> 16 & 255] ^ t2[a >> 8 & 255] ^ t3[b & 255] ^ key[kIndex + 2];
  921. d = t0[d >>> 24] ^ t1[a >> 16 & 255] ^ t2[b >> 8 & 255] ^ t3[c & 255] ^ key[kIndex + 3];
  922. kIndex += 4;
  923. a = a2; b = b2; c = c2;
  924. }
  925. // Last round.
  926. for (let i = 0; i < 4; i++) {
  927. out[dir ? 3 & -i : i] =
  928. sbox[a >>> 24] << 24 ^
  929. sbox[b >> 16 & 255] << 16 ^
  930. sbox[c >> 8 & 255] << 8 ^
  931. sbox[d & 255] ^
  932. key[kIndex++];
  933. a2 = a; a = b; b = c; c = d; d = a2;
  934. }
  935. return out;
  936. }
  937. };
  938. /**
  939. * Random values
  940. * @namespace
  941. */
  942. const random = {
  943. /**
  944. * Generate random words with pure js, cryptographically not as strong & safe as native implementation.
  945. * @param {TypedArray} typedArray The array to fill.
  946. * @return {TypedArray} The random values.
  947. */
  948. getRandomValues(typedArray) {
  949. const words = new Uint32Array(typedArray.buffer);
  950. const r = (m_w) => {
  951. let m_z = 0x3ade68b1;
  952. const mask = 0xffffffff;
  953. return function () {
  954. m_z = (0x9069 * (m_z & 0xFFFF) + (m_z >> 0x10)) & mask;
  955. m_w = (0x4650 * (m_w & 0xFFFF) + (m_w >> 0x10)) & mask;
  956. const result = ((((m_z << 0x10) + m_w) & mask) / 0x100000000) + .5;
  957. return result * (Math.random() > .5 ? 1 : -1);
  958. };
  959. };
  960. for (let i = 0, rcache; i < typedArray.length; i += 4) {
  961. const _r = r((rcache || Math.random()) * 0x100000000);
  962. rcache = _r() * 0x3ade67b7;
  963. words[i / 4] = (_r() * 0x100000000) | 0;
  964. }
  965. return typedArray;
  966. }
  967. };
  968. /** @fileOverview CTR mode implementation.
  969. *
  970. * Special thanks to Roy Nicholson for pointing out a bug in our
  971. * implementation.
  972. *
  973. * @author Emily Stark
  974. * @author Mike Hamburg
  975. * @author Dan Boneh
  976. */
  977. /** Brian Gladman's CTR Mode.
  978. * @constructor
  979. * @param {Object} _prf The aes instance to generate key.
  980. * @param {bitArray} _iv The iv for ctr mode, it must be 128 bits.
  981. */
  982. const mode = {};
  983. /**
  984. * Brian Gladman's CTR Mode.
  985. * @namespace
  986. */
  987. mode.ctrGladman = class {
  988. constructor(prf, iv) {
  989. this._prf = prf;
  990. this._initIv = iv;
  991. this._iv = iv;
  992. }
  993. reset() {
  994. this._iv = this._initIv;
  995. }
  996. /** Input some data to calculate.
  997. * @param {bitArray} data the data to process, it must be intergral multiple of 128 bits unless it's the last.
  998. */
  999. update(data) {
  1000. return this.calculate(this._prf, data, this._iv);
  1001. }
  1002. incWord(word) {
  1003. if (((word >> 24) & 0xff) === 0xff) { //overflow
  1004. let b1 = (word >> 16) & 0xff;
  1005. let b2 = (word >> 8) & 0xff;
  1006. let b3 = word & 0xff;
  1007. if (b1 === 0xff) { // overflow b1
  1008. b1 = 0;
  1009. if (b2 === 0xff) {
  1010. b2 = 0;
  1011. if (b3 === 0xff) {
  1012. b3 = 0;
  1013. } else {
  1014. ++b3;
  1015. }
  1016. } else {
  1017. ++b2;
  1018. }
  1019. } else {
  1020. ++b1;
  1021. }
  1022. word = 0;
  1023. word += (b1 << 16);
  1024. word += (b2 << 8);
  1025. word += b3;
  1026. } else {
  1027. word += (0x01 << 24);
  1028. }
  1029. return word;
  1030. }
  1031. incCounter(counter) {
  1032. if ((counter[0] = this.incWord(counter[0])) === 0) {
  1033. // encr_data in fileenc.c from Dr Brian Gladman's counts only with DWORD j < 8
  1034. counter[1] = this.incWord(counter[1]);
  1035. }
  1036. }
  1037. calculate(prf, data, iv) {
  1038. let l;
  1039. if (!(l = data.length)) {
  1040. return [];
  1041. }
  1042. const bl = bitArray.bitLength(data);
  1043. for (let i = 0; i < l; i += 4) {
  1044. this.incCounter(iv);
  1045. const e = prf.encrypt(iv);
  1046. data[i] ^= e[0];
  1047. data[i + 1] ^= e[1];
  1048. data[i + 2] ^= e[2];
  1049. data[i + 3] ^= e[3];
  1050. }
  1051. return bitArray.clamp(data, bl);
  1052. }
  1053. };
  1054. const misc = {
  1055. importKey(password) {
  1056. return new misc.hmacSha1(codec.bytes.toBits(password));
  1057. },
  1058. pbkdf2(prf, salt, count, length) {
  1059. count = count || 10000;
  1060. if (length < 0 || count < 0) {
  1061. throw new Error("invalid params to pbkdf2");
  1062. }
  1063. const byteLength = ((length >> 5) + 1) << 2;
  1064. let u, ui, i, j, k;
  1065. const arrayBuffer = new ArrayBuffer(byteLength);
  1066. const out = new DataView(arrayBuffer);
  1067. let outLength = 0;
  1068. const b = bitArray;
  1069. salt = codec.bytes.toBits(salt);
  1070. for (k = 1; outLength < (byteLength || 1); k++) {
  1071. u = ui = prf.encrypt(b.concat(salt, [k]));
  1072. for (i = 1; i < count; i++) {
  1073. ui = prf.encrypt(ui);
  1074. for (j = 0; j < ui.length; j++) {
  1075. u[j] ^= ui[j];
  1076. }
  1077. }
  1078. for (i = 0; outLength < (byteLength || 1) && i < u.length; i++) {
  1079. out.setInt32(outLength, u[i]);
  1080. outLength += 4;
  1081. }
  1082. }
  1083. return arrayBuffer.slice(0, length / 8);
  1084. }
  1085. };
  1086. /** @fileOverview HMAC implementation.
  1087. *
  1088. * @author Emily Stark
  1089. * @author Mike Hamburg
  1090. * @author Dan Boneh
  1091. */
  1092. /** HMAC with the specified hash function.
  1093. * @constructor
  1094. * @param {bitArray} key the key for HMAC.
  1095. * @param {Object} [Hash=hash.sha1] The hash function to use.
  1096. */
  1097. misc.hmacSha1 = class {
  1098. constructor(key) {
  1099. const hmac = this;
  1100. const Hash = hmac._hash = hash.sha1;
  1101. const exKey = [[], []];
  1102. hmac._baseHash = [new Hash(), new Hash()];
  1103. const bs = hmac._baseHash[0].blockSize / 32;
  1104. if (key.length > bs) {
  1105. key = new Hash().update(key).finalize();
  1106. }
  1107. for (let i = 0; i < bs; i++) {
  1108. exKey[0][i] = key[i] ^ 0x36363636;
  1109. exKey[1][i] = key[i] ^ 0x5C5C5C5C;
  1110. }
  1111. hmac._baseHash[0].update(exKey[0]);
  1112. hmac._baseHash[1].update(exKey[1]);
  1113. hmac._resultHash = new Hash(hmac._baseHash[0]);
  1114. }
  1115. reset() {
  1116. const hmac = this;
  1117. hmac._resultHash = new hmac._hash(hmac._baseHash[0]);
  1118. hmac._updated = false;
  1119. }
  1120. update(data) {
  1121. const hmac = this;
  1122. hmac._updated = true;
  1123. hmac._resultHash.update(data);
  1124. }
  1125. digest() {
  1126. const hmac = this;
  1127. const w = hmac._resultHash.finalize();
  1128. const result = new (hmac._hash)(hmac._baseHash[1]).update(w).finalize();
  1129. hmac.reset();
  1130. return result;
  1131. }
  1132. encrypt(data) {
  1133. if (!this._updated) {
  1134. this.update(data);
  1135. return this.digest(data);
  1136. } else {
  1137. throw new Error("encrypt on already updated hmac called!");
  1138. }
  1139. }
  1140. };
  1141. /*
  1142. Copyright (c) 2022 Gildas Lormeau. All rights reserved.
  1143. Redistribution and use in source and binary forms, with or without
  1144. modification, are permitted provided that the following conditions are met:
  1145. 1. Redistributions of source code must retain the above copyright notice,
  1146. this list of conditions and the following disclaimer.
  1147. 2. Redistributions in binary form must reproduce the above copyright
  1148. notice, this list of conditions and the following disclaimer in
  1149. the documentation and/or other materials provided with the distribution.
  1150. 3. The names of the authors may not be used to endorse or promote products
  1151. derived from this software without specific prior written permission.
  1152. THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  1153. INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  1154. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
  1155. INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
  1156. INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  1157. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  1158. OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  1159. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  1160. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  1161. EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  1162. */
  1163. const GET_RANDOM_VALUES_SUPPORTED = typeof crypto != "undefined" && typeof crypto.getRandomValues == "function";
  1164. const ERR_INVALID_PASSWORD = "Invalid password";
  1165. const ERR_INVALID_SIGNATURE = "Invalid signature";
  1166. const ERR_ABORT_CHECK_PASSWORD = "zipjs-abort-check-password";
  1167. function getRandomValues(array) {
  1168. if (GET_RANDOM_VALUES_SUPPORTED) {
  1169. return crypto.getRandomValues(array);
  1170. } else {
  1171. return random.getRandomValues(array);
  1172. }
  1173. }
  1174. /*
  1175. Copyright (c) 2022 Gildas Lormeau. All rights reserved.
  1176. Redistribution and use in source and binary forms, with or without
  1177. modification, are permitted provided that the following conditions are met:
  1178. 1. Redistributions of source code must retain the above copyright notice,
  1179. this list of conditions and the following disclaimer.
  1180. 2. Redistributions in binary form must reproduce the above copyright
  1181. notice, this list of conditions and the following disclaimer in
  1182. the documentation and/or other materials provided with the distribution.
  1183. 3. The names of the authors may not be used to endorse or promote products
  1184. derived from this software without specific prior written permission.
  1185. THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  1186. INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  1187. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
  1188. INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
  1189. INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  1190. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  1191. OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  1192. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  1193. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  1194. EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  1195. */
  1196. const BLOCK_LENGTH = 16;
  1197. const RAW_FORMAT = "raw";
  1198. const PBKDF2_ALGORITHM = { name: "PBKDF2" };
  1199. const HASH_ALGORITHM = { name: "HMAC" };
  1200. const HASH_FUNCTION = "SHA-1";
  1201. const BASE_KEY_ALGORITHM = Object$1.assign({ hash: HASH_ALGORITHM }, PBKDF2_ALGORITHM);
  1202. const DERIVED_BITS_ALGORITHM = Object$1.assign({ iterations: 1000, hash: { name: HASH_FUNCTION } }, PBKDF2_ALGORITHM);
  1203. const DERIVED_BITS_USAGE = ["deriveBits"];
  1204. const SALT_LENGTH = [8, 12, 16];
  1205. const KEY_LENGTH = [16, 24, 32];
  1206. const SIGNATURE_LENGTH = 10;
  1207. const COUNTER_DEFAULT_VALUE = [0, 0, 0, 0];
  1208. const UNDEFINED_TYPE = "undefined";
  1209. const FUNCTION_TYPE = "function";
  1210. // deno-lint-ignore valid-typeof
  1211. const CRYPTO_API_SUPPORTED = typeof crypto != UNDEFINED_TYPE;
  1212. const subtle = CRYPTO_API_SUPPORTED && crypto.subtle;
  1213. const SUBTLE_API_SUPPORTED = CRYPTO_API_SUPPORTED && typeof subtle != UNDEFINED_TYPE;
  1214. const codecBytes = codec.bytes;
  1215. const Aes = cipher.aes;
  1216. const CtrGladman = mode.ctrGladman;
  1217. const HmacSha1 = misc.hmacSha1;
  1218. let IMPORT_KEY_SUPPORTED = CRYPTO_API_SUPPORTED && SUBTLE_API_SUPPORTED && typeof subtle.importKey == FUNCTION_TYPE;
  1219. let DERIVE_BITS_SUPPORTED = CRYPTO_API_SUPPORTED && SUBTLE_API_SUPPORTED && typeof subtle.deriveBits == FUNCTION_TYPE;
  1220. class AESDecryptionStream extends TransformStream {
  1221. constructor({ password, signed, encryptionStrength, checkPasswordOnly }) {
  1222. super({
  1223. start() {
  1224. Object$1.assign(this, {
  1225. ready: new Promise$1(resolve => this.resolveReady = resolve),
  1226. password,
  1227. signed,
  1228. strength: encryptionStrength - 1,
  1229. pending: new Uint8Array()
  1230. });
  1231. },
  1232. async transform(chunk, controller) {
  1233. const aesCrypto = this;
  1234. const {
  1235. password,
  1236. strength,
  1237. resolveReady,
  1238. ready
  1239. } = aesCrypto;
  1240. if (password) {
  1241. await createDecryptionKeys(aesCrypto, strength, password, subarray(chunk, 0, SALT_LENGTH[strength] + 2));
  1242. chunk = subarray(chunk, SALT_LENGTH[strength] + 2);
  1243. if (checkPasswordOnly) {
  1244. controller.error(new Error(ERR_ABORT_CHECK_PASSWORD));
  1245. } else {
  1246. resolveReady();
  1247. }
  1248. } else {
  1249. await ready;
  1250. }
  1251. const output = new Uint8Array(chunk.length - SIGNATURE_LENGTH - ((chunk.length - SIGNATURE_LENGTH) % BLOCK_LENGTH));
  1252. controller.enqueue(append(aesCrypto, chunk, output, 0, SIGNATURE_LENGTH, true));
  1253. },
  1254. async flush(controller) {
  1255. const {
  1256. signed,
  1257. ctr,
  1258. hmac,
  1259. pending,
  1260. ready
  1261. } = this;
  1262. if (hmac && ctr) {
  1263. await ready;
  1264. const chunkToDecrypt = subarray(pending, 0, pending.length - SIGNATURE_LENGTH);
  1265. const originalSignature = subarray(pending, pending.length - SIGNATURE_LENGTH);
  1266. let decryptedChunkArray = new Uint8Array();
  1267. if (chunkToDecrypt.length) {
  1268. const encryptedChunk = toBits(codecBytes, chunkToDecrypt);
  1269. hmac.update(encryptedChunk);
  1270. const decryptedChunk = ctr.update(encryptedChunk);
  1271. decryptedChunkArray = fromBits(codecBytes, decryptedChunk);
  1272. }
  1273. if (signed) {
  1274. const signature = subarray(fromBits(codecBytes, hmac.digest()), 0, SIGNATURE_LENGTH);
  1275. for (let indexSignature = 0; indexSignature < SIGNATURE_LENGTH; indexSignature++) {
  1276. if (signature[indexSignature] != originalSignature[indexSignature]) {
  1277. throw new Error(ERR_INVALID_SIGNATURE);
  1278. }
  1279. }
  1280. }
  1281. controller.enqueue(decryptedChunkArray);
  1282. }
  1283. }
  1284. });
  1285. }
  1286. }
  1287. class AESEncryptionStream extends TransformStream {
  1288. constructor({ password, encryptionStrength }) {
  1289. // deno-lint-ignore prefer-const
  1290. let stream;
  1291. super({
  1292. start() {
  1293. Object$1.assign(this, {
  1294. ready: new Promise$1(resolve => this.resolveReady = resolve),
  1295. password,
  1296. strength: encryptionStrength - 1,
  1297. pending: new Uint8Array()
  1298. });
  1299. },
  1300. async transform(chunk, controller) {
  1301. const aesCrypto = this;
  1302. const {
  1303. password,
  1304. strength,
  1305. resolveReady,
  1306. ready
  1307. } = aesCrypto;
  1308. let preamble = new Uint8Array();
  1309. if (password) {
  1310. preamble = await createEncryptionKeys(aesCrypto, strength, password);
  1311. resolveReady();
  1312. } else {
  1313. await ready;
  1314. }
  1315. const output = new Uint8Array(preamble.length + chunk.length - (chunk.length % BLOCK_LENGTH));
  1316. output.set(preamble, 0);
  1317. controller.enqueue(append(aesCrypto, chunk, output, preamble.length, 0));
  1318. },
  1319. async flush(controller) {
  1320. const {
  1321. ctr,
  1322. hmac,
  1323. pending,
  1324. ready
  1325. } = this;
  1326. if (hmac && ctr) {
  1327. await ready;
  1328. let encryptedChunkArray = new Uint8Array();
  1329. if (pending.length) {
  1330. const encryptedChunk = ctr.update(toBits(codecBytes, pending));
  1331. hmac.update(encryptedChunk);
  1332. encryptedChunkArray = fromBits(codecBytes, encryptedChunk);
  1333. }
  1334. stream.signature = fromBits(codecBytes, hmac.digest()).slice(0, SIGNATURE_LENGTH);
  1335. controller.enqueue(concat(encryptedChunkArray, stream.signature));
  1336. }
  1337. }
  1338. });
  1339. stream = this;
  1340. }
  1341. }
  1342. function append(aesCrypto, input, output, paddingStart, paddingEnd, verifySignature) {
  1343. const {
  1344. ctr,
  1345. hmac,
  1346. pending
  1347. } = aesCrypto;
  1348. const inputLength = input.length - paddingEnd;
  1349. if (pending.length) {
  1350. input = concat(pending, input);
  1351. output = expand(output, inputLength - (inputLength % BLOCK_LENGTH));
  1352. }
  1353. let offset;
  1354. for (offset = 0; offset <= inputLength - BLOCK_LENGTH; offset += BLOCK_LENGTH) {
  1355. const inputChunk = toBits(codecBytes, subarray(input, offset, offset + BLOCK_LENGTH));
  1356. if (verifySignature) {
  1357. hmac.update(inputChunk);
  1358. }
  1359. const outputChunk = ctr.update(inputChunk);
  1360. if (!verifySignature) {
  1361. hmac.update(outputChunk);
  1362. }
  1363. output.set(fromBits(codecBytes, outputChunk), offset + paddingStart);
  1364. }
  1365. aesCrypto.pending = subarray(input, offset);
  1366. return output;
  1367. }
  1368. async function createDecryptionKeys(decrypt, strength, password, preamble) {
  1369. const passwordVerificationKey = await createKeys$1(decrypt, strength, password, subarray(preamble, 0, SALT_LENGTH[strength]));
  1370. const passwordVerification = subarray(preamble, SALT_LENGTH[strength]);
  1371. if (passwordVerificationKey[0] != passwordVerification[0] || passwordVerificationKey[1] != passwordVerification[1]) {
  1372. throw new Error(ERR_INVALID_PASSWORD);
  1373. }
  1374. }
  1375. async function createEncryptionKeys(encrypt, strength, password) {
  1376. const salt = getRandomValues(new Uint8Array(SALT_LENGTH[strength]));
  1377. const passwordVerification = await createKeys$1(encrypt, strength, password, salt);
  1378. return concat(salt, passwordVerification);
  1379. }
  1380. async function createKeys$1(aesCrypto, strength, password, salt) {
  1381. aesCrypto.password = null;
  1382. const encodedPassword = encodeText(password);
  1383. const baseKey = await importKey(RAW_FORMAT, encodedPassword, BASE_KEY_ALGORITHM, false, DERIVED_BITS_USAGE);
  1384. const derivedBits = await deriveBits(Object$1.assign({ salt }, DERIVED_BITS_ALGORITHM), baseKey, 8 * ((KEY_LENGTH[strength] * 2) + 2));
  1385. const compositeKey = new Uint8Array(derivedBits);
  1386. const key = toBits(codecBytes, subarray(compositeKey, 0, KEY_LENGTH[strength]));
  1387. const authentication = toBits(codecBytes, subarray(compositeKey, KEY_LENGTH[strength], KEY_LENGTH[strength] * 2));
  1388. const passwordVerification = subarray(compositeKey, KEY_LENGTH[strength] * 2);
  1389. Object$1.assign(aesCrypto, {
  1390. keys: {
  1391. key,
  1392. authentication,
  1393. passwordVerification
  1394. },
  1395. ctr: new CtrGladman(new Aes(key), Array.from(COUNTER_DEFAULT_VALUE)),
  1396. hmac: new HmacSha1(authentication)
  1397. });
  1398. return passwordVerification;
  1399. }
  1400. async function importKey(format, password, algorithm, extractable, keyUsages) {
  1401. if (IMPORT_KEY_SUPPORTED) {
  1402. try {
  1403. return await subtle.importKey(format, password, algorithm, extractable, keyUsages);
  1404. } catch (_error) {
  1405. IMPORT_KEY_SUPPORTED = false;
  1406. return misc.importKey(password);
  1407. }
  1408. } else {
  1409. return misc.importKey(password);
  1410. }
  1411. }
  1412. async function deriveBits(algorithm, baseKey, length) {
  1413. if (DERIVE_BITS_SUPPORTED) {
  1414. try {
  1415. return await subtle.deriveBits(algorithm, baseKey, length);
  1416. } catch (_error) {
  1417. DERIVE_BITS_SUPPORTED = false;
  1418. return misc.pbkdf2(baseKey, algorithm.salt, DERIVED_BITS_ALGORITHM.iterations, length);
  1419. }
  1420. } else {
  1421. return misc.pbkdf2(baseKey, algorithm.salt, DERIVED_BITS_ALGORITHM.iterations, length);
  1422. }
  1423. }
  1424. function concat(leftArray, rightArray) {
  1425. let array = leftArray;
  1426. if (leftArray.length + rightArray.length) {
  1427. array = new Uint8Array(leftArray.length + rightArray.length);
  1428. array.set(leftArray, 0);
  1429. array.set(rightArray, leftArray.length);
  1430. }
  1431. return array;
  1432. }
  1433. function expand(inputArray, length) {
  1434. if (length && length > inputArray.length) {
  1435. const array = inputArray;
  1436. inputArray = new Uint8Array(length);
  1437. inputArray.set(array, 0);
  1438. }
  1439. return inputArray;
  1440. }
  1441. function subarray(array, begin, end) {
  1442. return array.subarray(begin, end);
  1443. }
  1444. function fromBits(codecBytes, chunk) {
  1445. return codecBytes.fromBits(chunk);
  1446. }
  1447. function toBits(codecBytes, chunk) {
  1448. return codecBytes.toBits(chunk);
  1449. }
  1450. /*
  1451. Copyright (c) 2022 Gildas Lormeau. All rights reserved.
  1452. Redistribution and use in source and binary forms, with or without
  1453. modification, are permitted provided that the following conditions are met:
  1454. 1. Redistributions of source code must retain the above copyright notice,
  1455. this list of conditions and the following disclaimer.
  1456. 2. Redistributions in binary form must reproduce the above copyright
  1457. notice, this list of conditions and the following disclaimer in
  1458. the documentation and/or other materials provided with the distribution.
  1459. 3. The names of the authors may not be used to endorse or promote products
  1460. derived from this software without specific prior written permission.
  1461. THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  1462. INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  1463. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
  1464. INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
  1465. INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  1466. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  1467. OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  1468. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  1469. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  1470. EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  1471. */
  1472. const HEADER_LENGTH = 12;
  1473. class ZipCryptoDecryptionStream extends TransformStream {
  1474. constructor({ password, passwordVerification, checkPasswordOnly }) {
  1475. super({
  1476. start() {
  1477. Object$1.assign(this, {
  1478. password,
  1479. passwordVerification
  1480. });
  1481. createKeys(this, password);
  1482. },
  1483. transform(chunk, controller) {
  1484. const zipCrypto = this;
  1485. if (zipCrypto.password) {
  1486. const decryptedHeader = decrypt(zipCrypto, chunk.subarray(0, HEADER_LENGTH));
  1487. zipCrypto.password = null;
  1488. if (decryptedHeader[HEADER_LENGTH - 1] != zipCrypto.passwordVerification) {
  1489. throw new Error(ERR_INVALID_PASSWORD);
  1490. }
  1491. chunk = chunk.subarray(HEADER_LENGTH);
  1492. }
  1493. if (checkPasswordOnly) {
  1494. controller.error(new Error(ERR_ABORT_CHECK_PASSWORD));
  1495. } else {
  1496. controller.enqueue(decrypt(zipCrypto, chunk));
  1497. }
  1498. }
  1499. });
  1500. }
  1501. }
  1502. class ZipCryptoEncryptionStream extends TransformStream {
  1503. constructor({ password, passwordVerification }) {
  1504. super({
  1505. start() {
  1506. Object$1.assign(this, {
  1507. password,
  1508. passwordVerification
  1509. });
  1510. createKeys(this, password);
  1511. },
  1512. transform(chunk, controller) {
  1513. const zipCrypto = this;
  1514. let output;
  1515. let offset;
  1516. if (zipCrypto.password) {
  1517. zipCrypto.password = null;
  1518. const header = getRandomValues(new Uint8Array(HEADER_LENGTH));
  1519. header[HEADER_LENGTH - 1] = zipCrypto.passwordVerification;
  1520. output = new Uint8Array(chunk.length + header.length);
  1521. output.set(encrypt(zipCrypto, header), 0);
  1522. offset = HEADER_LENGTH;
  1523. } else {
  1524. output = new Uint8Array(chunk.length);
  1525. offset = 0;
  1526. }
  1527. output.set(encrypt(zipCrypto, chunk), offset);
  1528. controller.enqueue(output);
  1529. }
  1530. });
  1531. }
  1532. }
  1533. function decrypt(target, input) {
  1534. const output = new Uint8Array(input.length);
  1535. for (let index = 0; index < input.length; index++) {
  1536. output[index] = getByte(target) ^ input[index];
  1537. updateKeys(target, output[index]);
  1538. }
  1539. return output;
  1540. }
  1541. function encrypt(target, input) {
  1542. const output = new Uint8Array(input.length);
  1543. for (let index = 0; index < input.length; index++) {
  1544. output[index] = getByte(target) ^ input[index];
  1545. updateKeys(target, input[index]);
  1546. }
  1547. return output;
  1548. }
  1549. function createKeys(target, password) {
  1550. const keys = [0x12345678, 0x23456789, 0x34567890];
  1551. Object$1.assign(target, {
  1552. keys,
  1553. crcKey0: new Crc32(keys[0]),
  1554. crcKey2: new Crc32(keys[2]),
  1555. });
  1556. for (let index = 0; index < password.length; index++) {
  1557. updateKeys(target, password.charCodeAt(index));
  1558. }
  1559. }
  1560. function updateKeys(target, byte) {
  1561. let [key0, key1, key2] = target.keys;
  1562. target.crcKey0.append([byte]);
  1563. key0 = ~target.crcKey0.get();
  1564. key1 = getInt32(Math.imul(getInt32(key1 + getInt8(key0)), 134775813) + 1);
  1565. target.crcKey2.append([key1 >>> 24]);
  1566. key2 = ~target.crcKey2.get();
  1567. target.keys = [key0, key1, key2];
  1568. }
  1569. function getByte(target) {
  1570. const temp = target.keys[2] | 2;
  1571. return getInt8(Math.imul(temp, (temp ^ 1)) >>> 8);
  1572. }
  1573. function getInt8(number) {
  1574. return number & 0xFF;
  1575. }
  1576. function getInt32(number) {
  1577. return number & 0xFFFFFFFF;
  1578. }
  1579. /*
  1580. Copyright (c) 2022 Gildas Lormeau. All rights reserved.
  1581. Redistribution and use in source and binary forms, with or without
  1582. modification, are permitted provided that the following conditions are met:
  1583. 1. Redistributions of source code must retain the above copyright notice,
  1584. this list of conditions and the following disclaimer.
  1585. 2. Redistributions in binary form must reproduce the above copyright
  1586. notice, this list of conditions and the following disclaimer in
  1587. the documentation and/or other materials provided with the distribution.
  1588. 3. The names of the authors may not be used to endorse or promote products
  1589. derived from this software without specific prior written permission.
  1590. THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  1591. INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  1592. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
  1593. INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
  1594. INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  1595. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  1596. OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  1597. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  1598. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  1599. EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  1600. */
  1601. const COMPRESSION_FORMAT = "deflate-raw";
  1602. class DeflateStream extends TransformStream {
  1603. constructor(options, { chunkSize, CompressionStream, CompressionStreamNative }) {
  1604. super({});
  1605. const { compressed, encrypted, useCompressionStream, zipCrypto, signed, level } = options;
  1606. const stream = this;
  1607. let crc32Stream, encryptionStream;
  1608. let readable = filterEmptyChunks(super.readable);
  1609. if ((!encrypted || zipCrypto) && signed) {
  1610. crc32Stream = new Crc32Stream();
  1611. readable = pipeThrough(readable, crc32Stream);
  1612. }
  1613. if (compressed) {
  1614. readable = pipeThroughCommpressionStream(readable, useCompressionStream, { level, chunkSize }, CompressionStreamNative, CompressionStream);
  1615. }
  1616. if (encrypted) {
  1617. if (zipCrypto) {
  1618. readable = pipeThrough(readable, new ZipCryptoEncryptionStream(options));
  1619. } else {
  1620. encryptionStream = new AESEncryptionStream(options);
  1621. readable = pipeThrough(readable, encryptionStream);
  1622. }
  1623. }
  1624. setReadable(stream, readable, () => {
  1625. let signature;
  1626. if (encrypted && !zipCrypto) {
  1627. signature = encryptionStream.signature;
  1628. }
  1629. if ((!encrypted || zipCrypto) && signed) {
  1630. signature = new DataView(crc32Stream.value.buffer).getUint32(0);
  1631. }
  1632. stream.signature = signature;
  1633. });
  1634. }
  1635. }
  1636. class InflateStream extends TransformStream {
  1637. constructor(options, { chunkSize, DecompressionStream, DecompressionStreamNative }) {
  1638. super({});
  1639. const { zipCrypto, encrypted, signed, signature, compressed, useCompressionStream } = options;
  1640. let crc32Stream, decryptionStream;
  1641. let readable = filterEmptyChunks(super.readable);
  1642. if (encrypted) {
  1643. if (zipCrypto) {
  1644. readable = pipeThrough(readable, new ZipCryptoDecryptionStream(options));
  1645. } else {
  1646. decryptionStream = new AESDecryptionStream(options);
  1647. readable = pipeThrough(readable, decryptionStream);
  1648. }
  1649. }
  1650. if (compressed) {
  1651. readable = pipeThroughCommpressionStream(readable, useCompressionStream, { chunkSize }, DecompressionStreamNative, DecompressionStream);
  1652. }
  1653. if ((!encrypted || zipCrypto) && signed) {
  1654. crc32Stream = new Crc32Stream();
  1655. readable = pipeThrough(readable, crc32Stream);
  1656. }
  1657. setReadable(this, readable, () => {
  1658. if ((!encrypted || zipCrypto) && signed) {
  1659. const dataViewSignature = new DataView(crc32Stream.value.buffer);
  1660. if (signature != dataViewSignature.getUint32(0, false)) {
  1661. throw new Error(ERR_INVALID_SIGNATURE);
  1662. }
  1663. }
  1664. });
  1665. }
  1666. }
  1667. function filterEmptyChunks(readable) {
  1668. return pipeThrough(readable, new TransformStream({
  1669. transform(chunk, controller) {
  1670. if (chunk && chunk.length) {
  1671. controller.enqueue(chunk);
  1672. }
  1673. }
  1674. }));
  1675. }
  1676. function setReadable(stream, readable, flush) {
  1677. readable = pipeThrough(readable, new TransformStream({ flush }));
  1678. Object$1.defineProperty(stream, "readable", {
  1679. get() {
  1680. return readable;
  1681. }
  1682. });
  1683. }
  1684. function pipeThroughCommpressionStream(readable, useCompressionStream, options, CodecStreamNative, CodecStream) {
  1685. try {
  1686. const CompressionStream = useCompressionStream && CodecStreamNative ? CodecStreamNative : CodecStream;
  1687. readable = pipeThrough(readable, new CompressionStream(COMPRESSION_FORMAT, options));
  1688. } catch (error) {
  1689. if (useCompressionStream) {
  1690. readable = pipeThrough(readable, new CodecStream(COMPRESSION_FORMAT, options));
  1691. } else {
  1692. throw error;
  1693. }
  1694. }
  1695. return readable;
  1696. }
  1697. function pipeThrough(readable, transformStream) {
  1698. return readable.pipeThrough(transformStream);
  1699. }
  1700. /*
  1701. Copyright (c) 2022 Gildas Lormeau. All rights reserved.
  1702. Redistribution and use in source and binary forms, with or without
  1703. modification, are permitted provided that the following conditions are met:
  1704. 1. Redistributions of source code must retain the above copyright notice,
  1705. this list of conditions and the following disclaimer.
  1706. 2. Redistributions in binary form must reproduce the above copyright
  1707. notice, this list of conditions and the following disclaimer in
  1708. the documentation and/or other materials provided with the distribution.
  1709. 3. The names of the authors may not be used to endorse or promote products
  1710. derived from this software without specific prior written permission.
  1711. THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  1712. INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  1713. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
  1714. INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
  1715. INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  1716. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  1717. OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  1718. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  1719. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  1720. EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  1721. */
  1722. const MESSAGE_EVENT_TYPE = "message";
  1723. const MESSAGE_START = "start";
  1724. const MESSAGE_PULL = "pull";
  1725. const MESSAGE_DATA = "data";
  1726. const MESSAGE_ACK_DATA = "ack";
  1727. const MESSAGE_CLOSE = "close";
  1728. const CODEC_DEFLATE = "deflate";
  1729. const CODEC_INFLATE = "inflate";
  1730. class CodecStream extends TransformStream {
  1731. constructor(options, config) {
  1732. super({});
  1733. const codec = this;
  1734. const { codecType } = options;
  1735. let Stream;
  1736. if (codecType.startsWith(CODEC_DEFLATE)) {
  1737. Stream = DeflateStream;
  1738. } else if (codecType.startsWith(CODEC_INFLATE)) {
  1739. Stream = InflateStream;
  1740. }
  1741. let size = 0;
  1742. const stream = new Stream(options, config);
  1743. const readable = super.readable;
  1744. const transformStream = new TransformStream({
  1745. transform(chunk, controller) {
  1746. if (chunk && chunk.length) {
  1747. size += chunk.length;
  1748. controller.enqueue(chunk);
  1749. }
  1750. },
  1751. flush() {
  1752. const { signature } = stream;
  1753. Object$1.assign(codec, {
  1754. signature,
  1755. size
  1756. });
  1757. }
  1758. });
  1759. Object$1.defineProperty(codec, "readable", {
  1760. get() {
  1761. return readable.pipeThrough(stream).pipeThrough(transformStream);
  1762. }
  1763. });
  1764. }
  1765. }
  1766. /*
  1767. Copyright (c) 2022 Gildas Lormeau. All rights reserved.
  1768. Redistribution and use in source and binary forms, with or without
  1769. modification, are permitted provided that the following conditions are met:
  1770. 1. Redistributions of source code must retain the above copyright notice,
  1771. this list of conditions and the following disclaimer.
  1772. 2. Redistributions in binary form must reproduce the above copyright
  1773. notice, this list of conditions and the following disclaimer in
  1774. the documentation and/or other materials provided with the distribution.
  1775. 3. The names of the authors may not be used to endorse or promote products
  1776. derived from this software without specific prior written permission.
  1777. THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  1778. INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  1779. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
  1780. INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
  1781. INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  1782. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  1783. OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  1784. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  1785. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  1786. EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  1787. */
  1788. // deno-lint-ignore valid-typeof
  1789. const WEB_WORKERS_SUPPORTED = typeof Worker != UNDEFINED_TYPE$1;
  1790. class CodecWorker {
  1791. constructor(workerData, { readable, writable }, { options, config, streamOptions, useWebWorkers, transferStreams, scripts }, onTaskFinished) {
  1792. const { signal } = streamOptions;
  1793. Object$1.assign(workerData, {
  1794. busy: true,
  1795. readable: readable.pipeThrough(new ProgressWatcherStream(readable, streamOptions, config), { signal }),
  1796. writable,
  1797. options: Object$1.assign({}, options),
  1798. scripts,
  1799. transferStreams,
  1800. terminate() {
  1801. const { worker, busy } = workerData;
  1802. if (worker && !busy) {
  1803. worker.terminate();
  1804. workerData.interface = null;
  1805. }
  1806. },
  1807. onTaskFinished() {
  1808. workerData.busy = false;
  1809. onTaskFinished(workerData);
  1810. }
  1811. });
  1812. return (useWebWorkers && WEB_WORKERS_SUPPORTED ? createWebWorkerInterface : createWorkerInterface)(workerData, config);
  1813. }
  1814. }
  1815. class ProgressWatcherStream extends TransformStream {
  1816. constructor(readableSource, { onstart, onprogress, size, onend }, { chunkSize }) {
  1817. let chunkOffset = 0;
  1818. super({
  1819. start() {
  1820. if (onstart) {
  1821. callHandler(onstart, size);
  1822. }
  1823. },
  1824. async transform(chunk, controller) {
  1825. chunkOffset += chunk.length;
  1826. if (onprogress) {
  1827. await callHandler(onprogress, chunkOffset, size);
  1828. }
  1829. controller.enqueue(chunk);
  1830. },
  1831. flush() {
  1832. readableSource.size = chunkOffset;
  1833. if (onend) {
  1834. callHandler(onend, chunkOffset);
  1835. }
  1836. }
  1837. }, { highWaterMark: 1, size: () => chunkSize });
  1838. }
  1839. }
  1840. async function callHandler(handler, ...parameters) {
  1841. try {
  1842. await handler(...parameters);
  1843. } catch (_error) {
  1844. // ignored
  1845. }
  1846. }
  1847. function createWorkerInterface(workerData, config) {
  1848. return {
  1849. run: () => runWorker$1(workerData, config)
  1850. };
  1851. }
  1852. function createWebWorkerInterface(workerData, { baseURL, chunkSize }) {
  1853. if (!workerData.interface) {
  1854. Object$1.assign(workerData, {
  1855. worker: getWebWorker(workerData.scripts[0], baseURL, workerData),
  1856. interface: {
  1857. run: () => runWebWorker(workerData, { chunkSize })
  1858. }
  1859. });
  1860. }
  1861. return workerData.interface;
  1862. }
  1863. async function runWorker$1({ options, readable, writable, onTaskFinished }, config) {
  1864. const codecStream = new CodecStream(options, config);
  1865. try {
  1866. await readable.pipeThrough(codecStream).pipeTo(writable, { preventClose: true, preventAbort: true });
  1867. const {
  1868. signature,
  1869. size
  1870. } = codecStream;
  1871. return {
  1872. signature,
  1873. size
  1874. };
  1875. } finally {
  1876. onTaskFinished();
  1877. }
  1878. }
  1879. async function runWebWorker(workerData, config) {
  1880. let resolveResult, rejectResult;
  1881. const result = new Promise$1((resolve, reject) => {
  1882. resolveResult = resolve;
  1883. rejectResult = reject;
  1884. });
  1885. Object$1.assign(workerData, {
  1886. reader: null,
  1887. writer: null,
  1888. resolveResult,
  1889. rejectResult,
  1890. result
  1891. });
  1892. const { readable, options, scripts } = workerData;
  1893. const { writable, closed } = watchClosedStream(workerData.writable);
  1894. const streamsTransferred = sendMessage({
  1895. type: MESSAGE_START,
  1896. scripts: scripts.slice(1),
  1897. options,
  1898. config,
  1899. readable,
  1900. writable
  1901. }, workerData);
  1902. if (!streamsTransferred) {
  1903. Object$1.assign(workerData, {
  1904. reader: readable.getReader(),
  1905. writer: writable.getWriter()
  1906. });
  1907. }
  1908. const resultValue = await result;
  1909. try {
  1910. await writable.getWriter().close();
  1911. } catch (_error) {
  1912. // ignored
  1913. }
  1914. await closed;
  1915. return resultValue;
  1916. }
  1917. function watchClosedStream(writableSource) {
  1918. const writer = writableSource.getWriter();
  1919. let resolveStreamClosed;
  1920. const closed = new Promise$1(resolve => resolveStreamClosed = resolve);
  1921. const writable = new WritableStream({
  1922. async write(chunk) {
  1923. await writer.ready;
  1924. await writer.write(chunk);
  1925. },
  1926. close() {
  1927. writer.releaseLock();
  1928. resolveStreamClosed();
  1929. },
  1930. abort(reason) {
  1931. return writer.abort(reason);
  1932. }
  1933. });
  1934. return { writable, closed };
  1935. }
  1936. let classicWorkersSupported = true;
  1937. let transferStreamsSupported = true;
  1938. function getWebWorker(url, baseURL, workerData) {
  1939. const workerOptions = { type: "module" };
  1940. let scriptUrl, worker;
  1941. // deno-lint-ignore valid-typeof
  1942. if (typeof url == FUNCTION_TYPE$1) {
  1943. url = url();
  1944. }
  1945. try {
  1946. scriptUrl = new URL(url, baseURL);
  1947. } catch (_error) {
  1948. scriptUrl = url;
  1949. }
  1950. if (classicWorkersSupported) {
  1951. try {
  1952. worker = new Worker(scriptUrl);
  1953. } catch (_error) {
  1954. classicWorkersSupported = false;
  1955. worker = new Worker(scriptUrl, workerOptions);
  1956. }
  1957. } else {
  1958. worker = new Worker(scriptUrl, workerOptions);
  1959. }
  1960. worker.addEventListener(MESSAGE_EVENT_TYPE, event => onMessage(event, workerData));
  1961. return worker;
  1962. }
  1963. function sendMessage(message, { worker, writer, onTaskFinished, transferStreams }) {
  1964. try {
  1965. let { value, readable, writable } = message;
  1966. const transferables = [];
  1967. if (value) {
  1968. message.value = value.buffer;
  1969. transferables.push(message.value);
  1970. }
  1971. if (transferStreams && transferStreamsSupported) {
  1972. if (readable) {
  1973. transferables.push(readable);
  1974. }
  1975. if (writable) {
  1976. transferables.push(writable);
  1977. }
  1978. } else {
  1979. message.readable = message.writable = null;
  1980. }
  1981. if (transferables.length) {
  1982. try {
  1983. worker.postMessage(message, transferables);
  1984. return true;
  1985. } catch (_error) {
  1986. transferStreamsSupported = false;
  1987. message.readable = message.writable = null;
  1988. worker.postMessage(message);
  1989. }
  1990. } else {
  1991. worker.postMessage(message);
  1992. }
  1993. } catch (error) {
  1994. if (writer) {
  1995. writer.releaseLock();
  1996. }
  1997. onTaskFinished();
  1998. throw error;
  1999. }
  2000. }
  2001. async function onMessage({ data }, workerData) {
  2002. const { type, value, messageId, result, error } = data;
  2003. const { reader, writer, resolveResult, rejectResult, onTaskFinished } = workerData;
  2004. try {
  2005. if (error) {
  2006. const { message, stack, code, name } = error;
  2007. const responseError = new Error(message);
  2008. Object$1.assign(responseError, { stack, code, name });
  2009. close(responseError);
  2010. } else {
  2011. if (type == MESSAGE_PULL) {
  2012. const { value, done } = await reader.read();
  2013. sendMessage({ type: MESSAGE_DATA, value, done, messageId }, workerData);
  2014. }
  2015. if (type == MESSAGE_DATA) {
  2016. await writer.ready;
  2017. await writer.write(new Uint8Array(value));
  2018. sendMessage({ type: MESSAGE_ACK_DATA, messageId }, workerData);
  2019. }
  2020. if (type == MESSAGE_CLOSE) {
  2021. close(null, result);
  2022. }
  2023. }
  2024. } catch (error) {
  2025. close(error);
  2026. }
  2027. function close(error, result) {
  2028. if (error) {
  2029. rejectResult(error);
  2030. } else {
  2031. resolveResult(result);
  2032. }
  2033. if (writer) {
  2034. writer.releaseLock();
  2035. }
  2036. onTaskFinished();
  2037. }
  2038. }
  2039. /*
  2040. Copyright (c) 2022 Gildas Lormeau. All rights reserved.
  2041. Redistribution and use in source and binary forms, with or without
  2042. modification, are permitted provided that the following conditions are met:
  2043. 1. Redistributions of source code must retain the above copyright notice,
  2044. this list of conditions and the following disclaimer.
  2045. 2. Redistributions in binary form must reproduce the above copyright
  2046. notice, this list of conditions and the following disclaimer in
  2047. the documentation and/or other materials provided with the distribution.
  2048. 3. The names of the authors may not be used to endorse or promote products
  2049. derived from this software without specific prior written permission.
  2050. THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  2051. INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  2052. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
  2053. INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
  2054. INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  2055. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  2056. OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  2057. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  2058. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  2059. EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  2060. */
  2061. let pool = [];
  2062. const pendingRequests = [];
  2063. let indexWorker = 0;
  2064. async function runWorker(stream, workerOptions) {
  2065. const { options, config } = workerOptions;
  2066. const { transferStreams, useWebWorkers, useCompressionStream, codecType, compressed, signed, encrypted } = options;
  2067. const { workerScripts, maxWorkers, terminateWorkerTimeout } = config;
  2068. workerOptions.transferStreams = transferStreams || transferStreams === UNDEFINED_VALUE;
  2069. const streamCopy = !compressed && !signed && !encrypted && !workerOptions.transferStreams;
  2070. workerOptions.useWebWorkers = !streamCopy && (useWebWorkers || (useWebWorkers === UNDEFINED_VALUE && config.useWebWorkers));
  2071. workerOptions.scripts = workerOptions.useWebWorkers && workerScripts ? workerScripts[codecType] : [];
  2072. options.useCompressionStream = useCompressionStream || (useCompressionStream === UNDEFINED_VALUE && config.useCompressionStream);
  2073. let worker;
  2074. const workerData = pool.find(workerData => !workerData.busy);
  2075. if (workerData) {
  2076. clearTerminateTimeout(workerData);
  2077. worker = new CodecWorker(workerData, stream, workerOptions, onTaskFinished);
  2078. } else if (pool.length < maxWorkers) {
  2079. const workerData = { indexWorker };
  2080. indexWorker++;
  2081. pool.push(workerData);
  2082. worker = new CodecWorker(workerData, stream, workerOptions, onTaskFinished);
  2083. } else {
  2084. worker = await new Promise$1(resolve => pendingRequests.push({ resolve, stream, workerOptions }));
  2085. }
  2086. return worker.run();
  2087. function onTaskFinished(workerData) {
  2088. if (pendingRequests.length) {
  2089. const [{ resolve, stream, workerOptions }] = pendingRequests.splice(0, 1);
  2090. resolve(new CodecWorker(workerData, stream, workerOptions, onTaskFinished));
  2091. } else if (workerData.worker) {
  2092. clearTerminateTimeout(workerData);
  2093. if (Number.isFinite(terminateWorkerTimeout) && terminateWorkerTimeout >= 0) {
  2094. workerData.terminateTimeout = setTimeout(() => {
  2095. pool = pool.filter(data => data != workerData);
  2096. workerData.terminate();
  2097. }, terminateWorkerTimeout);
  2098. }
  2099. } else {
  2100. pool = pool.filter(data => data != workerData);
  2101. }
  2102. }
  2103. }
  2104. function clearTerminateTimeout(workerData) {
  2105. const { terminateTimeout } = workerData;
  2106. if (terminateTimeout) {
  2107. clearTimeout(terminateTimeout);
  2108. workerData.terminateTimeout = null;
  2109. }
  2110. }
  2111. function terminateWorkers() {
  2112. pool.forEach(workerData => {
  2113. clearTerminateTimeout(workerData);
  2114. workerData.terminate();
  2115. });
  2116. }
  2117. /*
  2118. Copyright (c) 2022 Gildas Lormeau. All rights reserved.
  2119. Redistribution and use in source and binary forms, with or without
  2120. modification, are permitted provided that the following conditions are met:
  2121. 1. Redistributions of source code must retain the above copyright notice,
  2122. this list of conditions and the following disclaimer.
  2123. 2. Redistributions in binary form must reproduce the above copyright
  2124. notice, this list of conditions and the following disclaimer in
  2125. the documentation and/or other materials provided with the distribution.
  2126. 3. The names of the authors may not be used to endorse or promote products
  2127. derived from this software without specific prior written permission.
  2128. THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  2129. INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  2130. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
  2131. INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
  2132. INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  2133. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  2134. OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  2135. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  2136. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  2137. EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  2138. */
  2139. const ERR_HTTP_STATUS = "HTTP error ";
  2140. const ERR_HTTP_RANGE = "HTTP Range not supported";
  2141. const ERR_ITERATOR_COMPLETED_TOO_SOON = "Writer iterator completed too soon";
  2142. const CONTENT_TYPE_TEXT_PLAIN = "text/plain";
  2143. const HTTP_HEADER_CONTENT_LENGTH = "Content-Length";
  2144. const HTTP_HEADER_CONTENT_RANGE = "Content-Range";
  2145. const HTTP_HEADER_ACCEPT_RANGES = "Accept-Ranges";
  2146. const HTTP_HEADER_RANGE = "Range";
  2147. const HTTP_HEADER_CONTENT_TYPE = "Content-Type";
  2148. const HTTP_METHOD_HEAD = "HEAD";
  2149. const HTTP_METHOD_GET = "GET";
  2150. const HTTP_RANGE_UNIT = "bytes";
  2151. const DEFAULT_CHUNK_SIZE = 64 * 1024;
  2152. const PROPERTY_NAME_WRITABLE = "writable";
  2153. class Stream {
  2154. constructor() {
  2155. this.size = 0;
  2156. }
  2157. init() {
  2158. this.initialized = true;
  2159. }
  2160. }
  2161. class Reader extends Stream {
  2162. get readable() {
  2163. const reader = this;
  2164. const { chunkSize = DEFAULT_CHUNK_SIZE } = reader;
  2165. const readable = new ReadableStream({
  2166. start() {
  2167. this.chunkOffset = 0;
  2168. },
  2169. async pull(controller) {
  2170. const { offset = 0, size, diskNumberStart } = readable;
  2171. const { chunkOffset } = this;
  2172. controller.enqueue(await readUint8Array(reader, offset + chunkOffset, Math.min(chunkSize, size - chunkOffset), diskNumberStart));
  2173. if (chunkOffset + chunkSize > size) {
  2174. controller.close();
  2175. } else {
  2176. this.chunkOffset += chunkSize;
  2177. }
  2178. }
  2179. });
  2180. return readable;
  2181. }
  2182. }
  2183. class Writer extends Stream {
  2184. constructor() {
  2185. super();
  2186. const writer = this;
  2187. const writable = new WritableStream({
  2188. write(chunk) {
  2189. return writer.writeUint8Array(chunk);
  2190. }
  2191. });
  2192. Object$1.defineProperty(writer, PROPERTY_NAME_WRITABLE, {
  2193. get() {
  2194. return writable;
  2195. }
  2196. });
  2197. }
  2198. writeUint8Array() {
  2199. // abstract
  2200. }
  2201. }
  2202. class Data64URIReader extends Reader {
  2203. constructor(dataURI) {
  2204. super();
  2205. let dataEnd = dataURI.length;
  2206. while (dataURI.charAt(dataEnd - 1) == "=") {
  2207. dataEnd--;
  2208. }
  2209. const dataStart = dataURI.indexOf(",") + 1;
  2210. Object$1.assign(this, {
  2211. dataURI,
  2212. dataStart,
  2213. size: Math.floor((dataEnd - dataStart) * 0.75)
  2214. });
  2215. }
  2216. readUint8Array(offset, length) {
  2217. const {
  2218. dataStart,
  2219. dataURI
  2220. } = this;
  2221. const dataArray = new Uint8Array(length);
  2222. const start = Math.floor(offset / 3) * 4;
  2223. const bytes = atob(dataURI.substring(start + dataStart, Math.ceil((offset + length) / 3) * 4 + dataStart));
  2224. const delta = offset - Math.floor(start / 4) * 3;
  2225. for (let indexByte = delta; indexByte < delta + length; indexByte++) {
  2226. dataArray[indexByte - delta] = bytes.charCodeAt(indexByte);
  2227. }
  2228. return dataArray;
  2229. }
  2230. }
  2231. class Data64URIWriter extends Writer {
  2232. constructor(contentType) {
  2233. super();
  2234. Object$1.assign(this, {
  2235. data: "data:" + (contentType || "") + ";base64,",
  2236. pending: []
  2237. });
  2238. }
  2239. writeUint8Array(array) {
  2240. const writer = this;
  2241. let indexArray = 0;
  2242. let dataString = writer.pending;
  2243. const delta = writer.pending.length;
  2244. writer.pending = "";
  2245. for (indexArray = 0; indexArray < (Math.floor((delta + array.length) / 3) * 3) - delta; indexArray++) {
  2246. dataString += String.fromCharCode(array[indexArray]);
  2247. }
  2248. for (; indexArray < array.length; indexArray++) {
  2249. writer.pending += String.fromCharCode(array[indexArray]);
  2250. }
  2251. if (dataString.length > 2) {
  2252. writer.data += btoa(dataString);
  2253. } else {
  2254. writer.pending = dataString;
  2255. }
  2256. }
  2257. getData() {
  2258. return this.data + btoa(this.pending);
  2259. }
  2260. }
  2261. class BlobReader extends Reader {
  2262. constructor(blob) {
  2263. super();
  2264. Object$1.assign(this, {
  2265. blob,
  2266. size: blob.size
  2267. });
  2268. }
  2269. async readUint8Array(offset, length) {
  2270. const reader = this;
  2271. const offsetEnd = offset + length;
  2272. const blob = offset || offsetEnd < reader.size ? reader.blob.slice(offset, offsetEnd) : reader.blob;
  2273. let arrayBuffer = await blob.arrayBuffer();
  2274. if (arrayBuffer.byteLength > length) {
  2275. arrayBuffer = arrayBuffer.slice(offset, offsetEnd);
  2276. }
  2277. return new Uint8Array(arrayBuffer);
  2278. }
  2279. }
  2280. class BlobWriter extends Stream {
  2281. constructor(contentType) {
  2282. super();
  2283. const writer = this;
  2284. const transformStream = new TransformStream();
  2285. const headers = [];
  2286. if (contentType) {
  2287. headers.push([HTTP_HEADER_CONTENT_TYPE, contentType]);
  2288. }
  2289. Object$1.defineProperty(writer, PROPERTY_NAME_WRITABLE, {
  2290. get() {
  2291. return transformStream.writable;
  2292. }
  2293. });
  2294. writer.blob = new Response(transformStream.readable, { headers }).blob();
  2295. }
  2296. getData() {
  2297. return this.blob;
  2298. }
  2299. }
  2300. class TextReader extends BlobReader {
  2301. constructor(text) {
  2302. super(new Blob([text], { type: CONTENT_TYPE_TEXT_PLAIN }));
  2303. }
  2304. }
  2305. class TextWriter extends BlobWriter {
  2306. constructor(encoding) {
  2307. super(encoding);
  2308. Object$1.assign(this, {
  2309. encoding,
  2310. utf8: !encoding || encoding.toLowerCase() == "utf-8"
  2311. });
  2312. }
  2313. async getData() {
  2314. const {
  2315. encoding,
  2316. utf8
  2317. } = this;
  2318. const blob = await super.getData();
  2319. if (blob.text && utf8) {
  2320. return blob.text();
  2321. } else {
  2322. const reader = new FileReader();
  2323. return new Promise$1((resolve, reject) => {
  2324. Object$1.assign(reader, {
  2325. onload: ({ target }) => resolve(target.result),
  2326. onerror: () => reject(reader.error)
  2327. });
  2328. reader.readAsText(blob, encoding);
  2329. });
  2330. }
  2331. }
  2332. }
  2333. class FetchReader extends Reader {
  2334. constructor(url, options) {
  2335. super();
  2336. createHtpReader(this, url, options);
  2337. }
  2338. async init() {
  2339. await initHttpReader(this, sendFetchRequest, getFetchRequestData);
  2340. super.init();
  2341. }
  2342. readUint8Array(index, length) {
  2343. return readUint8ArrayHttpReader(this, index, length, sendFetchRequest, getFetchRequestData);
  2344. }
  2345. }
  2346. class XHRReader extends Reader {
  2347. constructor(url, options) {
  2348. super();
  2349. createHtpReader(this, url, options);
  2350. }
  2351. async init() {
  2352. await initHttpReader(this, sendXMLHttpRequest, getXMLHttpRequestData);
  2353. super.init();
  2354. }
  2355. readUint8Array(index, length) {
  2356. return readUint8ArrayHttpReader(this, index, length, sendXMLHttpRequest, getXMLHttpRequestData);
  2357. }
  2358. }
  2359. function createHtpReader(httpReader, url, options) {
  2360. const {
  2361. preventHeadRequest,
  2362. useRangeHeader,
  2363. forceRangeRequests
  2364. } = options;
  2365. options = Object$1.assign({}, options);
  2366. delete options.preventHeadRequest;
  2367. delete options.useRangeHeader;
  2368. delete options.forceRangeRequests;
  2369. delete options.useXHR;
  2370. Object$1.assign(httpReader, {
  2371. url,
  2372. options,
  2373. preventHeadRequest,
  2374. useRangeHeader,
  2375. forceRangeRequests
  2376. });
  2377. }
  2378. async function initHttpReader(httpReader, sendRequest, getRequestData) {
  2379. const {
  2380. url,
  2381. useRangeHeader,
  2382. forceRangeRequests
  2383. } = httpReader;
  2384. if (isHttpFamily(url) && (useRangeHeader || forceRangeRequests)) {
  2385. const { headers } = await sendRequest(HTTP_METHOD_GET, httpReader, getRangeHeaders(httpReader));
  2386. if (!forceRangeRequests && headers.get(HTTP_HEADER_ACCEPT_RANGES) != HTTP_RANGE_UNIT) {
  2387. throw new Error(ERR_HTTP_RANGE);
  2388. } else {
  2389. let contentSize;
  2390. const contentRangeHeader = headers.get(HTTP_HEADER_CONTENT_RANGE);
  2391. if (contentRangeHeader) {
  2392. const splitHeader = contentRangeHeader.trim().split(/\s*\/\s*/);
  2393. if (splitHeader.length) {
  2394. const headerValue = splitHeader[1];
  2395. if (headerValue && headerValue != "*") {
  2396. contentSize = Number(headerValue);
  2397. }
  2398. }
  2399. }
  2400. if (contentSize === UNDEFINED_VALUE) {
  2401. await getContentLength(httpReader, sendRequest, getRequestData);
  2402. } else {
  2403. httpReader.size = contentSize;
  2404. }
  2405. }
  2406. } else {
  2407. await getContentLength(httpReader, sendRequest, getRequestData);
  2408. }
  2409. }
  2410. async function readUint8ArrayHttpReader(httpReader, index, length, sendRequest, getRequestData) {
  2411. const {
  2412. useRangeHeader,
  2413. forceRangeRequests,
  2414. options
  2415. } = httpReader;
  2416. if (useRangeHeader || forceRangeRequests) {
  2417. const response = await sendRequest(HTTP_METHOD_GET, httpReader, getRangeHeaders(httpReader, index, length));
  2418. if (response.status != 206) {
  2419. throw new Error(ERR_HTTP_RANGE);
  2420. }
  2421. return new Uint8Array(await response.arrayBuffer());
  2422. } else {
  2423. const { data } = httpReader;
  2424. if (!data) {
  2425. await getRequestData(httpReader, options);
  2426. }
  2427. return new Uint8Array(httpReader.data.subarray(index, index + length));
  2428. }
  2429. }
  2430. function getRangeHeaders(httpReader, index = 0, length = 1) {
  2431. return Object$1.assign({}, getHeaders(httpReader), { [HTTP_HEADER_RANGE]: HTTP_RANGE_UNIT + "=" + index + "-" + (index + length - 1) });
  2432. }
  2433. function getHeaders({ options }) {
  2434. const { headers } = options;
  2435. if (headers) {
  2436. if (Symbol.iterator in headers) {
  2437. return Object$1.fromEntries(headers);
  2438. } else {
  2439. return headers;
  2440. }
  2441. }
  2442. }
  2443. async function getFetchRequestData(httpReader) {
  2444. await getRequestData(httpReader, sendFetchRequest);
  2445. }
  2446. async function getXMLHttpRequestData(httpReader) {
  2447. await getRequestData(httpReader, sendXMLHttpRequest);
  2448. }
  2449. async function getRequestData(httpReader, sendRequest) {
  2450. const response = await sendRequest(HTTP_METHOD_GET, httpReader, getHeaders(httpReader));
  2451. httpReader.data = new Uint8Array(await response.arrayBuffer());
  2452. if (!httpReader.size) {
  2453. httpReader.size = httpReader.data.length;
  2454. }
  2455. }
  2456. async function getContentLength(httpReader, sendRequest, getRequestData) {
  2457. if (httpReader.preventHeadRequest) {
  2458. await getRequestData(httpReader, httpReader.options);
  2459. } else {
  2460. const response = await sendRequest(HTTP_METHOD_HEAD, httpReader, getHeaders(httpReader));
  2461. const contentLength = response.headers.get(HTTP_HEADER_CONTENT_LENGTH);
  2462. if (contentLength) {
  2463. httpReader.size = Number(contentLength);
  2464. } else {
  2465. await getRequestData(httpReader, httpReader.options);
  2466. }
  2467. }
  2468. }
  2469. async function sendFetchRequest(method, { options, url }, headers) {
  2470. const response = await fetch(url, Object$1.assign({}, options, { method, headers }));
  2471. if (response.status < 400) {
  2472. return response;
  2473. } else {
  2474. throw response.status == 416 ? new Error(ERR_HTTP_RANGE) : new Error(ERR_HTTP_STATUS + (response.statusText || response.status));
  2475. }
  2476. }
  2477. function sendXMLHttpRequest(method, { url }, headers) {
  2478. return new Promise$1((resolve, reject) => {
  2479. const request = new XMLHttpRequest();
  2480. request.addEventListener("load", () => {
  2481. if (request.status < 400) {
  2482. const headers = [];
  2483. request.getAllResponseHeaders().trim().split(/[\r\n]+/).forEach(header => {
  2484. const splitHeader = header.trim().split(/\s*:\s*/);
  2485. splitHeader[0] = splitHeader[0].trim().replace(/^[a-z]|-[a-z]/g, value => value.toUpperCase());
  2486. headers.push(splitHeader);
  2487. });
  2488. resolve({
  2489. status: request.status,
  2490. arrayBuffer: () => request.response,
  2491. headers: new Map(headers)
  2492. });
  2493. } else {
  2494. reject(request.status == 416 ? new Error(ERR_HTTP_RANGE) : new Error(ERR_HTTP_STATUS + (request.statusText || request.status)));
  2495. }
  2496. }, false);
  2497. request.addEventListener("error", event => reject(event.detail ? event.detail.error : new Error("Network error")), false);
  2498. request.open(method, url);
  2499. if (headers) {
  2500. for (const entry of Object$1.entries(headers)) {
  2501. request.setRequestHeader(entry[0], entry[1]);
  2502. }
  2503. }
  2504. request.responseType = "arraybuffer";
  2505. request.send();
  2506. });
  2507. }
  2508. class HttpReader extends Reader {
  2509. constructor(url, options = {}) {
  2510. super();
  2511. Object$1.assign(this, {
  2512. url,
  2513. reader: options.useXHR ? new XHRReader(url, options) : new FetchReader(url, options)
  2514. });
  2515. }
  2516. set size(value) {
  2517. // ignored
  2518. }
  2519. get size() {
  2520. return this.reader.size;
  2521. }
  2522. async init() {
  2523. await this.reader.init();
  2524. super.init();
  2525. }
  2526. readUint8Array(index, length) {
  2527. return this.reader.readUint8Array(index, length);
  2528. }
  2529. }
  2530. class HttpRangeReader extends HttpReader {
  2531. constructor(url, options = {}) {
  2532. options.useRangeHeader = true;
  2533. super(url, options);
  2534. }
  2535. }
  2536. class Uint8ArrayReader extends Reader {
  2537. constructor(array) {
  2538. super();
  2539. Object$1.assign(this, {
  2540. array,
  2541. size: array.length
  2542. });
  2543. }
  2544. readUint8Array(index, length) {
  2545. return this.array.slice(index, index + length);
  2546. }
  2547. }
  2548. class Uint8ArrayWriter extends Writer {
  2549. init(initSize = 0) {
  2550. Object$1.assign(this, {
  2551. offset: 0,
  2552. array: new Uint8Array(initSize)
  2553. });
  2554. super.init();
  2555. }
  2556. writeUint8Array(array) {
  2557. const writer = this;
  2558. if (writer.offset + array.length > writer.array.length) {
  2559. const previousArray = writer.array;
  2560. writer.array = new Uint8Array(previousArray.length + array.length);
  2561. writer.array.set(previousArray);
  2562. }
  2563. writer.array.set(array, writer.offset);
  2564. writer.offset += array.length;
  2565. }
  2566. getData() {
  2567. return this.array;
  2568. }
  2569. }
  2570. class SplitDataReader extends Reader {
  2571. constructor(readers) {
  2572. super();
  2573. this.readers = readers;
  2574. }
  2575. async init() {
  2576. const reader = this;
  2577. const { readers } = reader;
  2578. reader.lastDiskNumber = 0;
  2579. reader.lastDiskOffset = 0;
  2580. await Promise$1.all(readers.map(async (diskReader, indexDiskReader) => {
  2581. await diskReader.init();
  2582. if (indexDiskReader != readers.length - 1) {
  2583. reader.lastDiskOffset += diskReader.size;
  2584. }
  2585. reader.size += diskReader.size;
  2586. }));
  2587. super.init();
  2588. }
  2589. async readUint8Array(offset, length, diskNumber = 0) {
  2590. const reader = this;
  2591. const { readers } = this;
  2592. let result;
  2593. let currentDiskNumber = diskNumber;
  2594. if (currentDiskNumber == -1) {
  2595. currentDiskNumber = readers.length - 1;
  2596. }
  2597. let currentReaderOffset = offset;
  2598. while (currentReaderOffset >= readers[currentDiskNumber].size) {
  2599. currentReaderOffset -= readers[currentDiskNumber].size;
  2600. currentDiskNumber++;
  2601. }
  2602. const currentReader = readers[currentDiskNumber];
  2603. const currentReaderSize = currentReader.size;
  2604. if (currentReaderOffset + length <= currentReaderSize) {
  2605. result = await readUint8Array(currentReader, currentReaderOffset, length);
  2606. } else {
  2607. const chunkLength = currentReaderSize - currentReaderOffset;
  2608. result = new Uint8Array(length);
  2609. result.set(await readUint8Array(currentReader, currentReaderOffset, chunkLength));
  2610. result.set(await reader.readUint8Array(offset + chunkLength, length - chunkLength, diskNumber), chunkLength);
  2611. }
  2612. reader.lastDiskNumber = Math.max(currentDiskNumber, reader.lastDiskNumber);
  2613. return result;
  2614. }
  2615. }
  2616. class SplitDataWriter extends Stream {
  2617. constructor(writerGenerator, maxSize = 4294967295) {
  2618. super();
  2619. const zipWriter = this;
  2620. Object$1.assign(zipWriter, {
  2621. diskNumber: 0,
  2622. diskOffset: 0,
  2623. size: 0,
  2624. maxSize,
  2625. availableSize: maxSize
  2626. });
  2627. let diskSourceWriter, diskWritable, diskWriter;
  2628. const writable = new WritableStream({
  2629. async write(chunk) {
  2630. const { availableSize } = zipWriter;
  2631. if (!diskWriter) {
  2632. const { value, done } = await writerGenerator.next();
  2633. if (done && !value) {
  2634. throw new Error(ERR_ITERATOR_COMPLETED_TOO_SOON);
  2635. } else {
  2636. diskSourceWriter = value;
  2637. diskSourceWriter.size = 0;
  2638. if (diskSourceWriter.maxSize) {
  2639. zipWriter.maxSize = diskSourceWriter.maxSize;
  2640. }
  2641. zipWriter.availableSize = zipWriter.maxSize;
  2642. await initStream(diskSourceWriter);
  2643. diskWritable = value.writable;
  2644. diskWriter = diskWritable.getWriter();
  2645. }
  2646. await this.write(chunk);
  2647. } else if (chunk.length >= availableSize) {
  2648. await writeChunk(chunk.slice(0, availableSize));
  2649. await closeDisk();
  2650. zipWriter.diskOffset += diskSourceWriter.size;
  2651. zipWriter.diskNumber++;
  2652. diskWriter = null;
  2653. await this.write(chunk.slice(availableSize));
  2654. } else {
  2655. await writeChunk(chunk);
  2656. }
  2657. },
  2658. async close() {
  2659. await diskWriter.ready;
  2660. await closeDisk();
  2661. }
  2662. });
  2663. Object$1.defineProperty(zipWriter, PROPERTY_NAME_WRITABLE, {
  2664. get() {
  2665. return writable;
  2666. }
  2667. });
  2668. async function writeChunk(chunk) {
  2669. const chunkLength = chunk.length;
  2670. if (chunkLength) {
  2671. await diskWriter.ready;
  2672. await diskWriter.write(chunk);
  2673. diskSourceWriter.size += chunkLength;
  2674. zipWriter.size += chunkLength;
  2675. zipWriter.availableSize -= chunkLength;
  2676. }
  2677. }
  2678. async function closeDisk() {
  2679. diskWritable.size = diskSourceWriter.size;
  2680. await diskWriter.close();
  2681. }
  2682. }
  2683. }
  2684. function isHttpFamily(url) {
  2685. const { baseURL } = getConfiguration();
  2686. const { protocol } = new URL(url, baseURL);
  2687. return protocol == "http:" || protocol == "https:";
  2688. }
  2689. async function initStream(stream, initSize) {
  2690. if (stream.init && !stream.initialized) {
  2691. await stream.init(initSize);
  2692. }
  2693. }
  2694. function initReader(reader) {
  2695. if (Array.isArray(reader)) {
  2696. reader = new SplitDataReader(reader);
  2697. }
  2698. if (reader instanceof ReadableStream) {
  2699. reader = {
  2700. readable: reader
  2701. };
  2702. }
  2703. return reader;
  2704. }
  2705. function initWriter(writer) {
  2706. if (writer.writable === UNDEFINED_VALUE && typeof writer.next == FUNCTION_TYPE$1) {
  2707. writer = new SplitDataWriter(writer);
  2708. }
  2709. if (writer instanceof WritableStream) {
  2710. writer = {
  2711. writable: writer
  2712. };
  2713. }
  2714. const { writable } = writer;
  2715. if (writable.size === UNDEFINED_VALUE) {
  2716. writable.size = 0;
  2717. }
  2718. const splitZipFile = writer instanceof SplitDataWriter;
  2719. if (!splitZipFile) {
  2720. Object$1.assign(writer, {
  2721. diskNumber: 0,
  2722. diskOffset: 0,
  2723. availableSize: Infinity,
  2724. maxSize: Infinity
  2725. });
  2726. }
  2727. return writer;
  2728. }
  2729. function readUint8Array(reader, offset, size, diskNumber) {
  2730. return reader.readUint8Array(offset, size, diskNumber);
  2731. }
  2732. const SplitZipReader = SplitDataReader;
  2733. const SplitZipWriter = SplitDataWriter;
  2734. /*
  2735. Copyright (c) 2022 Gildas Lormeau. All rights reserved.
  2736. Redistribution and use in source and binary forms, with or without
  2737. modification, are permitted provided that the following conditions are met:
  2738. 1. Redistributions of source code must retain the above copyright notice,
  2739. this list of conditions and the following disclaimer.
  2740. 2. Redistributions in binary form must reproduce the above copyright
  2741. notice, this list of conditions and the following disclaimer in
  2742. the documentation and/or other materials provided with the distribution.
  2743. 3. The names of the authors may not be used to endorse or promote products
  2744. derived from this software without specific prior written permission.
  2745. THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  2746. INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  2747. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
  2748. INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
  2749. INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  2750. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  2751. OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  2752. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  2753. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  2754. EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  2755. */
  2756. /* global TextDecoder */
  2757. const CP437 = "\0☺☻♥♦♣♠•◘○◙♂♀♪♫☼►◄↕‼¶§▬↨↑↓→←∟↔▲▼ !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~⌂ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ ".split("");
  2758. const VALID_CP437 = CP437.length == 256;
  2759. function decodeCP437(stringValue) {
  2760. if (VALID_CP437) {
  2761. let result = "";
  2762. for (let indexCharacter = 0; indexCharacter < stringValue.length; indexCharacter++) {
  2763. result += CP437[stringValue[indexCharacter]];
  2764. }
  2765. return result;
  2766. } else {
  2767. return new TextDecoder().decode(stringValue);
  2768. }
  2769. }
  2770. /*
  2771. Copyright (c) 2022 Gildas Lormeau. All rights reserved.
  2772. Redistribution and use in source and binary forms, with or without
  2773. modification, are permitted provided that the following conditions are met:
  2774. 1. Redistributions of source code must retain the above copyright notice,
  2775. this list of conditions and the following disclaimer.
  2776. 2. Redistributions in binary form must reproduce the above copyright
  2777. notice, this list of conditions and the following disclaimer in
  2778. the documentation and/or other materials provided with the distribution.
  2779. 3. The names of the authors may not be used to endorse or promote products
  2780. derived from this software without specific prior written permission.
  2781. THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  2782. INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  2783. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
  2784. INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
  2785. INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  2786. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  2787. OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  2788. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  2789. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  2790. EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  2791. */
  2792. function decodeText(value, encoding) {
  2793. if (encoding && encoding.trim().toLowerCase() == "cp437") {
  2794. return decodeCP437(value);
  2795. } else {
  2796. return new TextDecoder(encoding).decode(value);
  2797. }
  2798. }
  2799. /*
  2800. Copyright (c) 2022 Gildas Lormeau. All rights reserved.
  2801. Redistribution and use in source and binary forms, with or without
  2802. modification, are permitted provided that the following conditions are met:
  2803. 1. Redistributions of source code must retain the above copyright notice,
  2804. this list of conditions and the following disclaimer.
  2805. 2. Redistributions in binary form must reproduce the above copyright
  2806. notice, this list of conditions and the following disclaimer in
  2807. the documentation and/or other materials provided with the distribution.
  2808. 3. The names of the authors may not be used to endorse or promote products
  2809. derived from this software without specific prior written permission.
  2810. THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  2811. INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  2812. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
  2813. INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
  2814. INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  2815. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  2816. OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  2817. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  2818. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  2819. EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  2820. */
  2821. const PROPERTY_NAME_FILENAME = "filename";
  2822. const PROPERTY_NAME_RAW_FILENAME = "rawFilename";
  2823. const PROPERTY_NAME_COMMENT = "comment";
  2824. const PROPERTY_NAME_RAW_COMMENT = "rawComment";
  2825. const PROPERTY_NAME_UNCOMPPRESSED_SIZE = "uncompressedSize";
  2826. const PROPERTY_NAME_COMPPRESSED_SIZE = "compressedSize";
  2827. const PROPERTY_NAME_OFFSET = "offset";
  2828. const PROPERTY_NAME_DISK_NUMBER_START = "diskNumberStart";
  2829. const PROPERTY_NAME_LAST_MODIFICATION_DATE = "lastModDate";
  2830. const PROPERTY_NAME_RAW_LAST_MODIFICATION_DATE = "rawLastModDate";
  2831. const PROPERTY_NAME_LAST_ACCESS_DATE = "lastAccessDate";
  2832. const PROPERTY_NAME_RAW_LAST_ACCESS_DATE = "rawLastAccessDate";
  2833. const PROPERTY_NAME_CREATION_DATE = "creationDate";
  2834. const PROPERTY_NAME_RAW_CREATION_DATE = "rawCreationDate";
  2835. const PROPERTY_NAME_INTERNAL_FILE_ATTRIBUTE = "internalFileAttribute";
  2836. const PROPERTY_NAME_EXTERNAL_FILE_ATTRIBUTE = "externalFileAttribute";
  2837. const PROPERTY_NAME_MS_DOS_COMPATIBLE = "msDosCompatible";
  2838. const PROPERTY_NAME_ZIP64 = "zip64";
  2839. const PROPERTY_NAMES = [
  2840. PROPERTY_NAME_FILENAME, PROPERTY_NAME_RAW_FILENAME, PROPERTY_NAME_COMPPRESSED_SIZE, PROPERTY_NAME_UNCOMPPRESSED_SIZE,
  2841. PROPERTY_NAME_LAST_MODIFICATION_DATE, PROPERTY_NAME_RAW_LAST_MODIFICATION_DATE, PROPERTY_NAME_COMMENT, PROPERTY_NAME_RAW_COMMENT,
  2842. PROPERTY_NAME_LAST_ACCESS_DATE, PROPERTY_NAME_CREATION_DATE, PROPERTY_NAME_OFFSET, PROPERTY_NAME_DISK_NUMBER_START,
  2843. PROPERTY_NAME_DISK_NUMBER_START, PROPERTY_NAME_INTERNAL_FILE_ATTRIBUTE, PROPERTY_NAME_EXTERNAL_FILE_ATTRIBUTE,
  2844. PROPERTY_NAME_MS_DOS_COMPATIBLE, PROPERTY_NAME_ZIP64,
  2845. "directory", "bitFlag", "encrypted", "signature", "filenameUTF8", "commentUTF8", "compressionMethod", "version", "versionMadeBy",
  2846. "extraField", "rawExtraField", "extraFieldZip64", "extraFieldUnicodePath", "extraFieldUnicodeComment", "extraFieldAES", "extraFieldNTFS",
  2847. "extraFieldExtendedTimestamp"];
  2848. class Entry {
  2849. constructor(data) {
  2850. PROPERTY_NAMES.forEach(name => this[name] = data[name]);
  2851. }
  2852. }
  2853. /*
  2854. Copyright (c) 2022 Gildas Lormeau. All rights reserved.
  2855. Redistribution and use in source and binary forms, with or without
  2856. modification, are permitted provided that the following conditions are met:
  2857. 1. Redistributions of source code must retain the above copyright notice,
  2858. this list of conditions and the following disclaimer.
  2859. 2. Redistributions in binary form must reproduce the above copyright
  2860. notice, this list of conditions and the following disclaimer in
  2861. the documentation and/or other materials provided with the distribution.
  2862. 3. The names of the authors may not be used to endorse or promote products
  2863. derived from this software without specific prior written permission.
  2864. THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  2865. INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  2866. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
  2867. INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
  2868. INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  2869. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  2870. OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  2871. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  2872. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  2873. EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  2874. */
  2875. const ERR_BAD_FORMAT = "File format is not recognized";
  2876. const ERR_EOCDR_NOT_FOUND = "End of central directory not found";
  2877. const ERR_EOCDR_ZIP64_NOT_FOUND = "End of Zip64 central directory not found";
  2878. const ERR_EOCDR_LOCATOR_ZIP64_NOT_FOUND = "End of Zip64 central directory locator not found";
  2879. const ERR_CENTRAL_DIRECTORY_NOT_FOUND = "Central directory header not found";
  2880. const ERR_LOCAL_FILE_HEADER_NOT_FOUND = "Local file header not found";
  2881. const ERR_EXTRAFIELD_ZIP64_NOT_FOUND = "Zip64 extra field not found";
  2882. const ERR_ENCRYPTED = "File contains encrypted entry";
  2883. const ERR_UNSUPPORTED_ENCRYPTION = "Encryption method not supported";
  2884. const ERR_UNSUPPORTED_COMPRESSION = "Compression method not supported";
  2885. const ERR_SPLIT_ZIP_FILE = "Split zip file";
  2886. const CHARSET_UTF8 = "utf-8";
  2887. const CHARSET_CP437 = "cp437";
  2888. const ZIP64_PROPERTIES = [
  2889. [PROPERTY_NAME_UNCOMPPRESSED_SIZE, MAX_32_BITS],
  2890. [PROPERTY_NAME_COMPPRESSED_SIZE, MAX_32_BITS],
  2891. [PROPERTY_NAME_OFFSET, MAX_32_BITS],
  2892. [PROPERTY_NAME_DISK_NUMBER_START, MAX_16_BITS]
  2893. ];
  2894. const ZIP64_EXTRACTION = {
  2895. [MAX_16_BITS]: {
  2896. getValue: getUint32,
  2897. bytes: 4
  2898. },
  2899. [MAX_32_BITS]: {
  2900. getValue: getBigUint64,
  2901. bytes: 8
  2902. }
  2903. };
  2904. class ZipReader {
  2905. constructor(reader, options = {}) {
  2906. Object$1.assign(this, {
  2907. reader: initReader(reader),
  2908. options,
  2909. config: getConfiguration()
  2910. });
  2911. }
  2912. async* getEntriesGenerator(options = {}) {
  2913. const zipReader = this;
  2914. let { reader } = zipReader;
  2915. const { config } = zipReader;
  2916. await initStream(reader);
  2917. if (reader.size === UNDEFINED_VALUE || !reader.readUint8Array) {
  2918. reader = new BlobReader(await new Response(reader.readable).blob());
  2919. await initStream(reader);
  2920. }
  2921. if (reader.size < END_OF_CENTRAL_DIR_LENGTH) {
  2922. throw new Error(ERR_BAD_FORMAT);
  2923. }
  2924. reader.chunkSize = getChunkSize(config);
  2925. const endOfDirectoryInfo = await seekSignature(reader, END_OF_CENTRAL_DIR_SIGNATURE, reader.size, END_OF_CENTRAL_DIR_LENGTH, MAX_16_BITS * 16);
  2926. if (!endOfDirectoryInfo) {
  2927. const signatureArray = await readUint8Array(reader, 0, 4);
  2928. const signatureView = getDataView$1(signatureArray);
  2929. if (getUint32(signatureView) == SPLIT_ZIP_FILE_SIGNATURE) {
  2930. throw new Error(ERR_SPLIT_ZIP_FILE);
  2931. } else {
  2932. throw new Error(ERR_EOCDR_NOT_FOUND);
  2933. }
  2934. }
  2935. const endOfDirectoryView = getDataView$1(endOfDirectoryInfo);
  2936. let directoryDataLength = getUint32(endOfDirectoryView, 12);
  2937. let directoryDataOffset = getUint32(endOfDirectoryView, 16);
  2938. const commentOffset = endOfDirectoryInfo.offset;
  2939. const commentLength = getUint16(endOfDirectoryView, 20);
  2940. const appendedDataOffset = commentOffset + END_OF_CENTRAL_DIR_LENGTH + commentLength;
  2941. let lastDiskNumber = getUint16(endOfDirectoryView, 4);
  2942. const expectedLastDiskNumber = reader.lastDiskNumber || 0;
  2943. let diskNumber = getUint16(endOfDirectoryView, 6);
  2944. let filesLength = getUint16(endOfDirectoryView, 8);
  2945. let prependedDataLength = 0;
  2946. let startOffset = 0;
  2947. if (directoryDataOffset == MAX_32_BITS || directoryDataLength == MAX_32_BITS || filesLength == MAX_16_BITS || diskNumber == MAX_16_BITS) {
  2948. const endOfDirectoryLocatorArray = await readUint8Array(reader, endOfDirectoryInfo.offset - ZIP64_END_OF_CENTRAL_DIR_LOCATOR_LENGTH, ZIP64_END_OF_CENTRAL_DIR_LOCATOR_LENGTH);
  2949. const endOfDirectoryLocatorView = getDataView$1(endOfDirectoryLocatorArray);
  2950. if (getUint32(endOfDirectoryLocatorView, 0) != ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIGNATURE) {
  2951. throw new Error(ERR_EOCDR_ZIP64_NOT_FOUND);
  2952. }
  2953. directoryDataOffset = getBigUint64(endOfDirectoryLocatorView, 8);
  2954. let endOfDirectoryArray = await readUint8Array(reader, directoryDataOffset, ZIP64_END_OF_CENTRAL_DIR_LENGTH, -1);
  2955. let endOfDirectoryView = getDataView$1(endOfDirectoryArray);
  2956. const expectedDirectoryDataOffset = endOfDirectoryInfo.offset - ZIP64_END_OF_CENTRAL_DIR_LOCATOR_LENGTH - ZIP64_END_OF_CENTRAL_DIR_LENGTH;
  2957. if (getUint32(endOfDirectoryView, 0) != ZIP64_END_OF_CENTRAL_DIR_SIGNATURE && directoryDataOffset != expectedDirectoryDataOffset) {
  2958. const originalDirectoryDataOffset = directoryDataOffset;
  2959. directoryDataOffset = expectedDirectoryDataOffset;
  2960. prependedDataLength = directoryDataOffset - originalDirectoryDataOffset;
  2961. endOfDirectoryArray = await readUint8Array(reader, directoryDataOffset, ZIP64_END_OF_CENTRAL_DIR_LENGTH, -1);
  2962. endOfDirectoryView = getDataView$1(endOfDirectoryArray);
  2963. }
  2964. if (getUint32(endOfDirectoryView, 0) != ZIP64_END_OF_CENTRAL_DIR_SIGNATURE) {
  2965. throw new Error(ERR_EOCDR_LOCATOR_ZIP64_NOT_FOUND);
  2966. }
  2967. if (lastDiskNumber == MAX_16_BITS) {
  2968. lastDiskNumber = getUint32(endOfDirectoryView, 16);
  2969. }
  2970. if (diskNumber == MAX_16_BITS) {
  2971. diskNumber = getUint32(endOfDirectoryView, 20);
  2972. }
  2973. if (filesLength == MAX_16_BITS) {
  2974. filesLength = getBigUint64(endOfDirectoryView, 32);
  2975. }
  2976. if (directoryDataLength == MAX_32_BITS) {
  2977. directoryDataLength = getBigUint64(endOfDirectoryView, 40);
  2978. }
  2979. directoryDataOffset -= directoryDataLength;
  2980. }
  2981. if (directoryDataOffset >= reader.size) {
  2982. prependedDataLength = reader.size - directoryDataOffset - directoryDataLength - END_OF_CENTRAL_DIR_LENGTH;
  2983. directoryDataOffset = reader.size - directoryDataLength - END_OF_CENTRAL_DIR_LENGTH;
  2984. }
  2985. if (expectedLastDiskNumber != lastDiskNumber) {
  2986. throw new Error(ERR_SPLIT_ZIP_FILE);
  2987. }
  2988. if (directoryDataOffset < 0) {
  2989. throw new Error(ERR_BAD_FORMAT);
  2990. }
  2991. let offset = 0;
  2992. let directoryArray = await readUint8Array(reader, directoryDataOffset, directoryDataLength, diskNumber);
  2993. let directoryView = getDataView$1(directoryArray);
  2994. if (directoryDataLength) {
  2995. const expectedDirectoryDataOffset = endOfDirectoryInfo.offset - directoryDataLength;
  2996. if (getUint32(directoryView, offset) != CENTRAL_FILE_HEADER_SIGNATURE && directoryDataOffset != expectedDirectoryDataOffset) {
  2997. const originalDirectoryDataOffset = directoryDataOffset;
  2998. directoryDataOffset = expectedDirectoryDataOffset;
  2999. prependedDataLength += directoryDataOffset - originalDirectoryDataOffset;
  3000. directoryArray = await readUint8Array(reader, directoryDataOffset, directoryDataLength, diskNumber);
  3001. directoryView = getDataView$1(directoryArray);
  3002. }
  3003. }
  3004. const expectedDirectoryDataLength = endOfDirectoryInfo.offset - directoryDataOffset - (reader.lastDiskOffset || 0);
  3005. if (directoryDataLength != expectedDirectoryDataLength && expectedDirectoryDataLength >= 0) {
  3006. directoryDataLength = expectedDirectoryDataLength;
  3007. directoryArray = await readUint8Array(reader, directoryDataOffset, directoryDataLength, diskNumber);
  3008. directoryView = getDataView$1(directoryArray);
  3009. }
  3010. if (directoryDataOffset < 0 || directoryDataOffset >= reader.size) {
  3011. throw new Error(ERR_BAD_FORMAT);
  3012. }
  3013. const filenameEncoding = getOptionValue$1(zipReader, options, "filenameEncoding");
  3014. const commentEncoding = getOptionValue$1(zipReader, options, "commentEncoding");
  3015. for (let indexFile = 0; indexFile < filesLength; indexFile++) {
  3016. const fileEntry = new ZipEntry(reader, config, zipReader.options);
  3017. if (getUint32(directoryView, offset) != CENTRAL_FILE_HEADER_SIGNATURE) {
  3018. throw new Error(ERR_CENTRAL_DIRECTORY_NOT_FOUND);
  3019. }
  3020. readCommonHeader(fileEntry, directoryView, offset + 6);
  3021. const languageEncodingFlag = Boolean(fileEntry.bitFlag.languageEncodingFlag);
  3022. const filenameOffset = offset + 46;
  3023. const extraFieldOffset = filenameOffset + fileEntry.filenameLength;
  3024. const commentOffset = extraFieldOffset + fileEntry.extraFieldLength;
  3025. const versionMadeBy = getUint16(directoryView, offset + 4);
  3026. const msDosCompatible = (versionMadeBy & 0) == 0;
  3027. const rawFilename = directoryArray.subarray(filenameOffset, extraFieldOffset);
  3028. const commentLength = getUint16(directoryView, offset + 32);
  3029. const endOffset = commentOffset + commentLength;
  3030. const rawComment = directoryArray.subarray(commentOffset, endOffset);
  3031. const filenameUTF8 = languageEncodingFlag;
  3032. const commentUTF8 = languageEncodingFlag;
  3033. const directory = msDosCompatible && ((getUint8(directoryView, offset + 38) & FILE_ATTR_MSDOS_DIR_MASK) == FILE_ATTR_MSDOS_DIR_MASK);
  3034. const offsetFileEntry = getUint32(directoryView, offset + 42) + prependedDataLength;
  3035. Object$1.assign(fileEntry, {
  3036. versionMadeBy,
  3037. msDosCompatible,
  3038. compressedSize: 0,
  3039. uncompressedSize: 0,
  3040. commentLength,
  3041. directory,
  3042. offset: offsetFileEntry,
  3043. diskNumberStart: getUint16(directoryView, offset + 34),
  3044. internalFileAttribute: getUint16(directoryView, offset + 36),
  3045. externalFileAttribute: getUint32(directoryView, offset + 38),
  3046. rawFilename,
  3047. filenameUTF8,
  3048. commentUTF8,
  3049. rawExtraField: directoryArray.subarray(extraFieldOffset, commentOffset)
  3050. });
  3051. const [filename, comment] = await Promise$1.all([
  3052. decodeText(rawFilename, filenameUTF8 ? CHARSET_UTF8 : filenameEncoding || CHARSET_CP437),
  3053. decodeText(rawComment, commentUTF8 ? CHARSET_UTF8 : commentEncoding || CHARSET_CP437)
  3054. ]);
  3055. Object$1.assign(fileEntry, {
  3056. rawComment,
  3057. filename,
  3058. comment,
  3059. directory: directory || filename.endsWith(DIRECTORY_SIGNATURE)
  3060. });
  3061. startOffset = Math.max(offsetFileEntry, startOffset);
  3062. await readCommonFooter(fileEntry, fileEntry, directoryView, offset + 6);
  3063. const entry = new Entry(fileEntry);
  3064. entry.getData = (writer, options) => fileEntry.getData(writer, entry, options);
  3065. offset = endOffset;
  3066. const { onprogress } = options;
  3067. if (onprogress) {
  3068. try {
  3069. await onprogress(indexFile + 1, filesLength, new Entry(fileEntry));
  3070. } catch (_error) {
  3071. // ignored
  3072. }
  3073. }
  3074. yield entry;
  3075. }
  3076. const extractPrependedData = getOptionValue$1(zipReader, options, "extractPrependedData");
  3077. const extractAppendedData = getOptionValue$1(zipReader, options, "extractAppendedData");
  3078. if (extractPrependedData) {
  3079. zipReader.prependedData = startOffset > 0 ? await readUint8Array(reader, 0, startOffset) : new Uint8Array();
  3080. }
  3081. zipReader.comment = commentLength ? await readUint8Array(reader, commentOffset + END_OF_CENTRAL_DIR_LENGTH, commentLength) : new Uint8Array();
  3082. if (extractAppendedData) {
  3083. zipReader.appendedData = appendedDataOffset < reader.size ? await readUint8Array(reader, appendedDataOffset, reader.size - appendedDataOffset) : new Uint8Array();
  3084. }
  3085. return true;
  3086. }
  3087. async getEntries(options = {}) {
  3088. const entries = [];
  3089. for await (const entry of this.getEntriesGenerator(options)) {
  3090. entries.push(entry);
  3091. }
  3092. return entries;
  3093. }
  3094. async close() {
  3095. }
  3096. }
  3097. class ZipEntry {
  3098. constructor(reader, config, options) {
  3099. Object$1.assign(this, {
  3100. reader,
  3101. config,
  3102. options
  3103. });
  3104. }
  3105. async getData(writer, fileEntry, options = {}) {
  3106. const zipEntry = this;
  3107. const {
  3108. reader,
  3109. offset,
  3110. diskNumberStart,
  3111. extraFieldAES,
  3112. compressionMethod,
  3113. config,
  3114. bitFlag,
  3115. signature,
  3116. rawLastModDate,
  3117. uncompressedSize,
  3118. compressedSize
  3119. } = zipEntry;
  3120. const localDirectory = fileEntry.localDirectory = {};
  3121. const dataArray = await readUint8Array(reader, offset, 30, diskNumberStart);
  3122. const dataView = getDataView$1(dataArray);
  3123. let password = getOptionValue$1(zipEntry, options, "password");
  3124. password = password && password.length && password;
  3125. if (extraFieldAES) {
  3126. if (extraFieldAES.originalCompressionMethod != COMPRESSION_METHOD_AES) {
  3127. throw new Error(ERR_UNSUPPORTED_COMPRESSION);
  3128. }
  3129. }
  3130. if (compressionMethod != COMPRESSION_METHOD_STORE && compressionMethod != COMPRESSION_METHOD_DEFLATE) {
  3131. throw new Error(ERR_UNSUPPORTED_COMPRESSION);
  3132. }
  3133. if (getUint32(dataView, 0) != LOCAL_FILE_HEADER_SIGNATURE) {
  3134. throw new Error(ERR_LOCAL_FILE_HEADER_NOT_FOUND);
  3135. }
  3136. readCommonHeader(localDirectory, dataView, 4);
  3137. localDirectory.rawExtraField = localDirectory.extraFieldLength ?
  3138. await readUint8Array(reader, offset + 30 + localDirectory.filenameLength, localDirectory.extraFieldLength, diskNumberStart) :
  3139. new Uint8Array();
  3140. await readCommonFooter(zipEntry, localDirectory, dataView, 4, true);
  3141. Object$1.assign(fileEntry, {
  3142. lastAccessDate: localDirectory.lastAccessDate,
  3143. creationDate: localDirectory.creationDate
  3144. });
  3145. const encrypted = zipEntry.encrypted && localDirectory.encrypted;
  3146. const zipCrypto = encrypted && !extraFieldAES;
  3147. if (encrypted) {
  3148. if (!zipCrypto && extraFieldAES.strength === UNDEFINED_VALUE) {
  3149. throw new Error(ERR_UNSUPPORTED_ENCRYPTION);
  3150. } else if (!password) {
  3151. throw new Error(ERR_ENCRYPTED);
  3152. }
  3153. }
  3154. const dataOffset = offset + 30 + localDirectory.filenameLength + localDirectory.extraFieldLength;
  3155. const size = compressedSize;
  3156. const readable = reader.readable;
  3157. Object$1.assign(readable, {
  3158. diskNumberStart,
  3159. offset: dataOffset,
  3160. size
  3161. });
  3162. const signal = getOptionValue$1(zipEntry, options, "signal");
  3163. const checkPasswordOnly = getOptionValue$1(zipEntry, options, "checkPasswordOnly");
  3164. if (checkPasswordOnly) {
  3165. writer = new WritableStream();
  3166. }
  3167. writer = initWriter(writer);
  3168. await initStream(writer, uncompressedSize);
  3169. const { writable } = writer;
  3170. const { onstart, onprogress, onend } = options;
  3171. const workerOptions = {
  3172. options: {
  3173. codecType: CODEC_INFLATE,
  3174. password,
  3175. zipCrypto,
  3176. encryptionStrength: extraFieldAES && extraFieldAES.strength,
  3177. signed: getOptionValue$1(zipEntry, options, "checkSignature"),
  3178. passwordVerification: zipCrypto && (bitFlag.dataDescriptor ? ((rawLastModDate >>> 8) & 0xFF) : ((signature >>> 24) & 0xFF)),
  3179. signature,
  3180. compressed: compressionMethod != 0,
  3181. encrypted,
  3182. useWebWorkers: getOptionValue$1(zipEntry, options, "useWebWorkers"),
  3183. useCompressionStream: getOptionValue$1(zipEntry, options, "useCompressionStream"),
  3184. transferStreams: getOptionValue$1(zipEntry, options, "transferStreams"),
  3185. checkPasswordOnly
  3186. },
  3187. config,
  3188. streamOptions: { signal, size, onstart, onprogress, onend }
  3189. };
  3190. let outputSize = 0;
  3191. try {
  3192. ({ outputSize } = (await runWorker({ readable, writable }, workerOptions)));
  3193. } catch (error) {
  3194. if (!checkPasswordOnly || error.message != ERR_ABORT_CHECK_PASSWORD) {
  3195. throw error;
  3196. }
  3197. } finally {
  3198. const preventClose = getOptionValue$1(zipEntry, options, "preventClose");
  3199. writable.size += outputSize;
  3200. if (!preventClose && !writable.locked) {
  3201. await writable.getWriter().close();
  3202. }
  3203. }
  3204. return checkPasswordOnly ? undefined : writer.getData ? writer.getData() : writable;
  3205. }
  3206. }
  3207. function readCommonHeader(directory, dataView, offset) {
  3208. const rawBitFlag = directory.rawBitFlag = getUint16(dataView, offset + 2);
  3209. const encrypted = (rawBitFlag & BITFLAG_ENCRYPTED) == BITFLAG_ENCRYPTED;
  3210. const rawLastModDate = getUint32(dataView, offset + 6);
  3211. Object$1.assign(directory, {
  3212. encrypted,
  3213. version: getUint16(dataView, offset),
  3214. bitFlag: {
  3215. level: (rawBitFlag & BITFLAG_LEVEL) >> 1,
  3216. dataDescriptor: (rawBitFlag & BITFLAG_DATA_DESCRIPTOR) == BITFLAG_DATA_DESCRIPTOR,
  3217. languageEncodingFlag: (rawBitFlag & BITFLAG_LANG_ENCODING_FLAG) == BITFLAG_LANG_ENCODING_FLAG
  3218. },
  3219. rawLastModDate,
  3220. lastModDate: getDate(rawLastModDate),
  3221. filenameLength: getUint16(dataView, offset + 22),
  3222. extraFieldLength: getUint16(dataView, offset + 24)
  3223. });
  3224. }
  3225. async function readCommonFooter(fileEntry, directory, dataView, offset, localDirectory) {
  3226. const { rawExtraField } = directory;
  3227. const extraField = directory.extraField = new Map();
  3228. const rawExtraFieldView = getDataView$1(new Uint8Array(rawExtraField));
  3229. let offsetExtraField = 0;
  3230. try {
  3231. while (offsetExtraField < rawExtraField.length) {
  3232. const type = getUint16(rawExtraFieldView, offsetExtraField);
  3233. const size = getUint16(rawExtraFieldView, offsetExtraField + 2);
  3234. extraField.set(type, {
  3235. type,
  3236. data: rawExtraField.slice(offsetExtraField + 4, offsetExtraField + 4 + size)
  3237. });
  3238. offsetExtraField += 4 + size;
  3239. }
  3240. } catch (_error) {
  3241. // ignored
  3242. }
  3243. const compressionMethod = getUint16(dataView, offset + 4);
  3244. Object$1.assign(directory, {
  3245. signature: getUint32(dataView, offset + 10),
  3246. uncompressedSize: getUint32(dataView, offset + 18),
  3247. compressedSize: getUint32(dataView, offset + 14)
  3248. });
  3249. const extraFieldZip64 = extraField.get(EXTRAFIELD_TYPE_ZIP64);
  3250. if (extraFieldZip64) {
  3251. readExtraFieldZip64(extraFieldZip64, directory);
  3252. directory.extraFieldZip64 = extraFieldZip64;
  3253. }
  3254. const extraFieldUnicodePath = extraField.get(EXTRAFIELD_TYPE_UNICODE_PATH);
  3255. if (extraFieldUnicodePath) {
  3256. await readExtraFieldUnicode(extraFieldUnicodePath, PROPERTY_NAME_FILENAME, PROPERTY_NAME_RAW_FILENAME, directory, fileEntry);
  3257. directory.extraFieldUnicodePath = extraFieldUnicodePath;
  3258. }
  3259. const extraFieldUnicodeComment = extraField.get(EXTRAFIELD_TYPE_UNICODE_COMMENT);
  3260. if (extraFieldUnicodeComment) {
  3261. await readExtraFieldUnicode(extraFieldUnicodeComment, PROPERTY_NAME_COMMENT, PROPERTY_NAME_RAW_COMMENT, directory, fileEntry);
  3262. directory.extraFieldUnicodeComment = extraFieldUnicodeComment;
  3263. }
  3264. const extraFieldAES = extraField.get(EXTRAFIELD_TYPE_AES);
  3265. if (extraFieldAES) {
  3266. readExtraFieldAES(extraFieldAES, directory, compressionMethod);
  3267. directory.extraFieldAES = extraFieldAES;
  3268. } else {
  3269. directory.compressionMethod = compressionMethod;
  3270. }
  3271. const extraFieldNTFS = extraField.get(EXTRAFIELD_TYPE_NTFS);
  3272. if (extraFieldNTFS) {
  3273. readExtraFieldNTFS(extraFieldNTFS, directory);
  3274. directory.extraFieldNTFS = extraFieldNTFS;
  3275. }
  3276. const extraFieldExtendedTimestamp = extraField.get(EXTRAFIELD_TYPE_EXTENDED_TIMESTAMP);
  3277. if (extraFieldExtendedTimestamp) {
  3278. readExtraFieldExtendedTimestamp(extraFieldExtendedTimestamp, directory, localDirectory);
  3279. directory.extraFieldExtendedTimestamp = extraFieldExtendedTimestamp;
  3280. }
  3281. const extraFieldUSDZ = extraField.get(EXTRAFIELD_TYPE_USDZ);
  3282. if (extraFieldUSDZ) {
  3283. directory.extraFieldUSDZ = extraFieldUSDZ;
  3284. }
  3285. }
  3286. function readExtraFieldZip64(extraFieldZip64, directory) {
  3287. directory.zip64 = true;
  3288. const extraFieldView = getDataView$1(extraFieldZip64.data);
  3289. const missingProperties = ZIP64_PROPERTIES.filter(([propertyName, max]) => directory[propertyName] == max);
  3290. for (let indexMissingProperty = 0, offset = 0; indexMissingProperty < missingProperties.length; indexMissingProperty++) {
  3291. const [propertyName, max] = missingProperties[indexMissingProperty];
  3292. if (directory[propertyName] == max) {
  3293. const extraction = ZIP64_EXTRACTION[max];
  3294. directory[propertyName] = extraFieldZip64[propertyName] = extraction.getValue(extraFieldView, offset);
  3295. offset += extraction.bytes;
  3296. } else if (extraFieldZip64[propertyName]) {
  3297. throw new Error(ERR_EXTRAFIELD_ZIP64_NOT_FOUND);
  3298. }
  3299. }
  3300. }
  3301. async function readExtraFieldUnicode(extraFieldUnicode, propertyName, rawPropertyName, directory, fileEntry) {
  3302. const extraFieldView = getDataView$1(extraFieldUnicode.data);
  3303. const crc32 = new Crc32();
  3304. crc32.append(fileEntry[rawPropertyName]);
  3305. const dataViewSignature = getDataView$1(new Uint8Array(4));
  3306. dataViewSignature.setUint32(0, crc32.get(), true);
  3307. const signature = getUint32(extraFieldView, 1);
  3308. Object$1.assign(extraFieldUnicode, {
  3309. version: getUint8(extraFieldView, 0),
  3310. [propertyName]: decodeText(extraFieldUnicode.data.subarray(5)),
  3311. valid: !fileEntry.bitFlag.languageEncodingFlag && signature == getUint32(dataViewSignature, 0)
  3312. });
  3313. if (extraFieldUnicode.valid) {
  3314. directory[propertyName] = extraFieldUnicode[propertyName];
  3315. directory[propertyName + "UTF8"] = true;
  3316. }
  3317. }
  3318. function readExtraFieldAES(extraFieldAES, directory, compressionMethod) {
  3319. const extraFieldView = getDataView$1(extraFieldAES.data);
  3320. const strength = getUint8(extraFieldView, 4);
  3321. Object$1.assign(extraFieldAES, {
  3322. vendorVersion: getUint8(extraFieldView, 0),
  3323. vendorId: getUint8(extraFieldView, 2),
  3324. strength,
  3325. originalCompressionMethod: compressionMethod,
  3326. compressionMethod: getUint16(extraFieldView, 5)
  3327. });
  3328. directory.compressionMethod = extraFieldAES.compressionMethod;
  3329. }
  3330. function readExtraFieldNTFS(extraFieldNTFS, directory) {
  3331. const extraFieldView = getDataView$1(extraFieldNTFS.data);
  3332. let offsetExtraField = 4;
  3333. let tag1Data;
  3334. try {
  3335. while (offsetExtraField < extraFieldNTFS.data.length && !tag1Data) {
  3336. const tagValue = getUint16(extraFieldView, offsetExtraField);
  3337. const attributeSize = getUint16(extraFieldView, offsetExtraField + 2);
  3338. if (tagValue == EXTRAFIELD_TYPE_NTFS_TAG1) {
  3339. tag1Data = extraFieldNTFS.data.slice(offsetExtraField + 4, offsetExtraField + 4 + attributeSize);
  3340. }
  3341. offsetExtraField += 4 + attributeSize;
  3342. }
  3343. } catch (_error) {
  3344. // ignored
  3345. }
  3346. try {
  3347. if (tag1Data && tag1Data.length == 24) {
  3348. const tag1View = getDataView$1(tag1Data);
  3349. const rawLastModDate = tag1View.getBigUint64(0, true);
  3350. const rawLastAccessDate = tag1View.getBigUint64(8, true);
  3351. const rawCreationDate = tag1View.getBigUint64(16, true);
  3352. Object$1.assign(extraFieldNTFS, {
  3353. rawLastModDate,
  3354. rawLastAccessDate,
  3355. rawCreationDate
  3356. });
  3357. const lastModDate = getDateNTFS(rawLastModDate);
  3358. const lastAccessDate = getDateNTFS(rawLastAccessDate);
  3359. const creationDate = getDateNTFS(rawCreationDate);
  3360. const extraFieldData = { lastModDate, lastAccessDate, creationDate };
  3361. Object$1.assign(extraFieldNTFS, extraFieldData);
  3362. Object$1.assign(directory, extraFieldData);
  3363. }
  3364. } catch (_error) {
  3365. // ignored
  3366. }
  3367. }
  3368. function readExtraFieldExtendedTimestamp(extraFieldExtendedTimestamp, directory, localDirectory) {
  3369. const extraFieldView = getDataView$1(extraFieldExtendedTimestamp.data);
  3370. const flags = getUint8(extraFieldView, 0);
  3371. const timeProperties = [];
  3372. const timeRawProperties = [];
  3373. if (localDirectory) {
  3374. if ((flags & 0x1) == 0x1) {
  3375. timeProperties.push(PROPERTY_NAME_LAST_MODIFICATION_DATE);
  3376. timeRawProperties.push(PROPERTY_NAME_RAW_LAST_MODIFICATION_DATE);
  3377. }
  3378. if ((flags & 0x2) == 0x2) {
  3379. timeProperties.push(PROPERTY_NAME_LAST_ACCESS_DATE);
  3380. timeRawProperties.push(PROPERTY_NAME_RAW_LAST_ACCESS_DATE);
  3381. }
  3382. if ((flags & 0x4) == 0x4) {
  3383. timeProperties.push(PROPERTY_NAME_CREATION_DATE);
  3384. timeRawProperties.push(PROPERTY_NAME_RAW_CREATION_DATE);
  3385. }
  3386. } else if (extraFieldExtendedTimestamp.data.length >= 5) {
  3387. timeProperties.push(PROPERTY_NAME_LAST_MODIFICATION_DATE);
  3388. timeRawProperties.push(PROPERTY_NAME_RAW_LAST_MODIFICATION_DATE);
  3389. }
  3390. let offset = 1;
  3391. timeProperties.forEach((propertyName, indexProperty) => {
  3392. if (extraFieldExtendedTimestamp.data.length >= offset + 4) {
  3393. const time = getUint32(extraFieldView, offset);
  3394. directory[propertyName] = extraFieldExtendedTimestamp[propertyName] = new Date(time * 1000);
  3395. const rawPropertyName = timeRawProperties[indexProperty];
  3396. extraFieldExtendedTimestamp[rawPropertyName] = time;
  3397. }
  3398. offset += 4;
  3399. });
  3400. }
  3401. async function seekSignature(reader, signature, startOffset, minimumBytes, maximumLength) {
  3402. const signatureArray = new Uint8Array(4);
  3403. const signatureView = getDataView$1(signatureArray);
  3404. setUint32$1(signatureView, 0, signature);
  3405. const maximumBytes = minimumBytes + maximumLength;
  3406. return (await seek(minimumBytes)) || await seek(Math.min(maximumBytes, startOffset));
  3407. async function seek(length) {
  3408. const offset = startOffset - length;
  3409. const bytes = await readUint8Array(reader, offset, length);
  3410. for (let indexByte = bytes.length - minimumBytes; indexByte >= 0; indexByte--) {
  3411. if (bytes[indexByte] == signatureArray[0] && bytes[indexByte + 1] == signatureArray[1] &&
  3412. bytes[indexByte + 2] == signatureArray[2] && bytes[indexByte + 3] == signatureArray[3]) {
  3413. return {
  3414. offset: offset + indexByte,
  3415. buffer: bytes.slice(indexByte, indexByte + minimumBytes).buffer
  3416. };
  3417. }
  3418. }
  3419. }
  3420. }
  3421. function getOptionValue$1(zipReader, options, name) {
  3422. return options[name] === UNDEFINED_VALUE ? zipReader.options[name] : options[name];
  3423. }
  3424. function getDate(timeRaw) {
  3425. const date = (timeRaw & 0xffff0000) >> 16, time = timeRaw & 0x0000ffff;
  3426. try {
  3427. return new Date(1980 + ((date & 0xFE00) >> 9), ((date & 0x01E0) >> 5) - 1, date & 0x001F, (time & 0xF800) >> 11, (time & 0x07E0) >> 5, (time & 0x001F) * 2, 0);
  3428. } catch (_error) {
  3429. // ignored
  3430. }
  3431. }
  3432. function getDateNTFS(timeRaw) {
  3433. return new Date((Number((timeRaw / BigInt(10000)) - BigInt(11644473600000))));
  3434. }
  3435. function getUint8(view, offset) {
  3436. return view.getUint8(offset);
  3437. }
  3438. function getUint16(view, offset) {
  3439. return view.getUint16(offset, true);
  3440. }
  3441. function getUint32(view, offset) {
  3442. return view.getUint32(offset, true);
  3443. }
  3444. function getBigUint64(view, offset) {
  3445. return Number(view.getBigUint64(offset, true));
  3446. }
  3447. function setUint32$1(view, offset, value) {
  3448. view.setUint32(offset, value, true);
  3449. }
  3450. function getDataView$1(array) {
  3451. return new DataView(array.buffer);
  3452. }
  3453. /*
  3454. Copyright (c) 2022 Gildas Lormeau. All rights reserved.
  3455. Redistribution and use in source and binary forms, with or without
  3456. modification, are permitted provided that the following conditions are met:
  3457. 1. Redistributions of source code must retain the above copyright notice,
  3458. this list of conditions and the following disclaimer.
  3459. 2. Redistributions in binary form must reproduce the above copyright
  3460. notice, this list of conditions and the following disclaimer in
  3461. the documentation and/or other materials provided with the distribution.
  3462. 3. The names of the authors may not be used to endorse or promote products
  3463. derived from this software without specific prior written permission.
  3464. THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  3465. INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
  3466. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
  3467. INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
  3468. INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  3469. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  3470. OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  3471. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  3472. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  3473. EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  3474. */
  3475. const ERR_DUPLICATED_NAME = "File already exists";
  3476. const ERR_INVALID_COMMENT = "Zip file comment exceeds 64KB";
  3477. const ERR_INVALID_ENTRY_COMMENT = "File entry comment exceeds 64KB";
  3478. const ERR_INVALID_ENTRY_NAME = "File entry name exceeds 64KB";
  3479. const ERR_INVALID_VERSION = "Version exceeds 65535";
  3480. const ERR_INVALID_ENCRYPTION_STRENGTH = "The strength must equal 1, 2, or 3";
  3481. const ERR_INVALID_EXTRAFIELD_TYPE = "Extra field type exceeds 65535";
  3482. const ERR_INVALID_EXTRAFIELD_DATA = "Extra field data exceeds 64KB";
  3483. const ERR_UNSUPPORTED_FORMAT = "Zip64 is not supported (make sure 'keepOrder' is set to 'true')";
  3484. const EXTRAFIELD_DATA_AES = new Uint8Array([0x07, 0x00, 0x02, 0x00, 0x41, 0x45, 0x03, 0x00, 0x00]);
  3485. let workers = 0;
  3486. const pendingEntries = [];
  3487. class ZipWriter {
  3488. constructor(writer, options = {}) {
  3489. writer = initWriter(writer);
  3490. Object$1.assign(this, {
  3491. writer,
  3492. addSplitZipSignature: writer instanceof SplitDataWriter,
  3493. options,
  3494. config: getConfiguration(),
  3495. files: new Map(),
  3496. filenames: new Set(),
  3497. offset: writer.writable.size,
  3498. pendingEntriesSize: 0,
  3499. pendingAddFileCalls: new Set(),
  3500. bufferedWrites: 0
  3501. });
  3502. }
  3503. async add(name = "", reader, options = {}) {
  3504. const zipWriter = this;
  3505. const {
  3506. pendingAddFileCalls,
  3507. config
  3508. } = zipWriter;
  3509. if (workers < config.maxWorkers) {
  3510. workers++;
  3511. } else {
  3512. await new Promise$1(resolve => pendingEntries.push(resolve));
  3513. }
  3514. let promiseAddFile;
  3515. try {
  3516. name = name.trim();
  3517. if (zipWriter.filenames.has(name)) {
  3518. throw new Error(ERR_DUPLICATED_NAME);
  3519. }
  3520. zipWriter.filenames.add(name);
  3521. promiseAddFile = addFile(zipWriter, name, reader, options);
  3522. pendingAddFileCalls.add(promiseAddFile);
  3523. return await promiseAddFile;
  3524. } catch (error) {
  3525. zipWriter.filenames.delete(name);
  3526. throw error;
  3527. } finally {
  3528. pendingAddFileCalls.delete(promiseAddFile);
  3529. const pendingEntry = pendingEntries.shift();
  3530. if (pendingEntry) {
  3531. pendingEntry();
  3532. } else {
  3533. workers--;
  3534. }
  3535. }
  3536. }
  3537. async close(comment = new Uint8Array(), options = {}) {
  3538. const zipWriter = this;
  3539. const { pendingAddFileCalls, writer } = this;
  3540. const { writable } = writer;
  3541. while (pendingAddFileCalls.size) {
  3542. await Promise$1.all(Array.from(pendingAddFileCalls));
  3543. }
  3544. await closeFile(this, comment, options);
  3545. const preventClose = getOptionValue(zipWriter, options, "preventClose");
  3546. if (!preventClose) {
  3547. await writable.getWriter().close();
  3548. }
  3549. return writer.getData ? writer.getData() : writable;
  3550. }
  3551. }
  3552. async function addFile(zipWriter, name, reader, options) {
  3553. name = name.trim();
  3554. if (options.directory && (!name.endsWith(DIRECTORY_SIGNATURE))) {
  3555. name += DIRECTORY_SIGNATURE;
  3556. } else {
  3557. options.directory = name.endsWith(DIRECTORY_SIGNATURE);
  3558. }
  3559. const rawFilename = encodeText(name);
  3560. if (getLength(rawFilename) > MAX_16_BITS) {
  3561. throw new Error(ERR_INVALID_ENTRY_NAME);
  3562. }
  3563. const comment = options.comment || "";
  3564. const rawComment = encodeText(comment);
  3565. if (getLength(rawComment) > MAX_16_BITS) {
  3566. throw new Error(ERR_INVALID_ENTRY_COMMENT);
  3567. }
  3568. const version = getOptionValue(zipWriter, options, "version", VERSION_DEFLATE);
  3569. if (version > MAX_16_BITS) {
  3570. throw new Error(ERR_INVALID_VERSION);
  3571. }
  3572. const versionMadeBy = getOptionValue(zipWriter, options, "versionMadeBy", 20);
  3573. if (versionMadeBy > MAX_16_BITS) {
  3574. throw new Error(ERR_INVALID_VERSION);
  3575. }
  3576. const lastModDate = getOptionValue(zipWriter, options, PROPERTY_NAME_LAST_MODIFICATION_DATE, new Date());
  3577. const lastAccessDate = getOptionValue(zipWriter, options, PROPERTY_NAME_LAST_ACCESS_DATE);
  3578. const creationDate = getOptionValue(zipWriter, options, PROPERTY_NAME_CREATION_DATE);
  3579. const msDosCompatible = getOptionValue(zipWriter, options, PROPERTY_NAME_MS_DOS_COMPATIBLE, true);
  3580. const internalFileAttribute = getOptionValue(zipWriter, options, PROPERTY_NAME_INTERNAL_FILE_ATTRIBUTE, 0);
  3581. const externalFileAttribute = getOptionValue(zipWriter, options, PROPERTY_NAME_EXTERNAL_FILE_ATTRIBUTE, 0);
  3582. const password = getOptionValue(zipWriter, options, "password");
  3583. const encryptionStrength = getOptionValue(zipWriter, options, "encryptionStrength", 3);
  3584. const zipCrypto = getOptionValue(zipWriter, options, "zipCrypto");
  3585. const extendedTimestamp = getOptionValue(zipWriter, options, "extendedTimestamp", true);
  3586. const keepOrder = getOptionValue(zipWriter, options, "keepOrder", true);
  3587. const level = getOptionValue(zipWriter, options, "level");
  3588. const useWebWorkers = getOptionValue(zipWriter, options, "useWebWorkers");
  3589. const bufferedWrite = getOptionValue(zipWriter, options, "bufferedWrite");
  3590. const dataDescriptorSignature = getOptionValue(zipWriter, options, "dataDescriptorSignature", false);
  3591. const signal = getOptionValue(zipWriter, options, "signal");
  3592. const useCompressionStream = getOptionValue(zipWriter, options, "useCompressionStream");
  3593. let dataDescriptor = getOptionValue(zipWriter, options, "dataDescriptor", true);
  3594. let zip64 = getOptionValue(zipWriter, options, PROPERTY_NAME_ZIP64);
  3595. if (password !== UNDEFINED_VALUE && encryptionStrength !== UNDEFINED_VALUE && (encryptionStrength < 1 || encryptionStrength > 3)) {
  3596. throw new Error(ERR_INVALID_ENCRYPTION_STRENGTH);
  3597. }
  3598. let rawExtraField = new Uint8Array();
  3599. const { extraField } = options;
  3600. if (extraField) {
  3601. let extraFieldSize = 0;
  3602. let offset = 0;
  3603. extraField.forEach(data => extraFieldSize += 4 + getLength(data));
  3604. rawExtraField = new Uint8Array(extraFieldSize);
  3605. extraField.forEach((data, type) => {
  3606. if (type > MAX_16_BITS) {
  3607. throw new Error(ERR_INVALID_EXTRAFIELD_TYPE);
  3608. }
  3609. if (getLength(data) > MAX_16_BITS) {
  3610. throw new Error(ERR_INVALID_EXTRAFIELD_DATA);
  3611. }
  3612. arraySet(rawExtraField, new Uint16Array([type]), offset);
  3613. arraySet(rawExtraField, new Uint16Array([getLength(data)]), offset + 2);
  3614. arraySet(rawExtraField, data, offset + 4);
  3615. offset += 4 + getLength(data);
  3616. });
  3617. }
  3618. let maximumCompressedSize = 0;
  3619. let maximumEntrySize = 0;
  3620. let uncompressedSize = 0;
  3621. const zip64Enabled = zip64 === true;
  3622. if (reader) {
  3623. reader = initReader(reader);
  3624. await initStream(reader);
  3625. if (reader.size === UNDEFINED_VALUE) {
  3626. dataDescriptor = true;
  3627. if (zip64 || zip64 === UNDEFINED_VALUE) {
  3628. zip64 = true;
  3629. uncompressedSize = maximumCompressedSize = MAX_32_BITS;
  3630. }
  3631. } else {
  3632. uncompressedSize = reader.size;
  3633. maximumCompressedSize = getMaximumCompressedSize(uncompressedSize);
  3634. }
  3635. }
  3636. const { diskOffset, diskNumber, maxSize } = zipWriter.writer;
  3637. const zip64UncompressedSize = zip64Enabled || uncompressedSize >= MAX_32_BITS;
  3638. const zip64CompressedSize = zip64Enabled || maximumCompressedSize >= MAX_32_BITS;
  3639. const zip64Offset = zip64Enabled || zipWriter.offset + zipWriter.pendingEntriesSize - diskOffset >= MAX_32_BITS;
  3640. const supportZip64SplitFile = getOptionValue(zipWriter, options, "supportZip64SplitFile", true);
  3641. const zip64DiskNumberStart = (supportZip64SplitFile && zip64Enabled) || diskNumber + Math.ceil(zipWriter.pendingEntriesSize / maxSize) >= MAX_16_BITS;
  3642. if (zip64Offset || zip64UncompressedSize || zip64CompressedSize || zip64DiskNumberStart) {
  3643. if (zip64 === false || !keepOrder) {
  3644. throw new Error(ERR_UNSUPPORTED_FORMAT);
  3645. } else {
  3646. zip64 = true;
  3647. }
  3648. }
  3649. zip64 = zip64 || false;
  3650. options = Object$1.assign({}, options, {
  3651. rawFilename,
  3652. rawComment,
  3653. version,
  3654. versionMadeBy,
  3655. lastModDate,
  3656. lastAccessDate,
  3657. creationDate,
  3658. rawExtraField,
  3659. zip64,
  3660. zip64UncompressedSize,
  3661. zip64CompressedSize,
  3662. zip64Offset,
  3663. zip64DiskNumberStart,
  3664. password,
  3665. level,
  3666. useWebWorkers,
  3667. encryptionStrength,
  3668. extendedTimestamp,
  3669. zipCrypto,
  3670. bufferedWrite,
  3671. keepOrder,
  3672. dataDescriptor,
  3673. dataDescriptorSignature,
  3674. signal,
  3675. msDosCompatible,
  3676. internalFileAttribute,
  3677. externalFileAttribute,
  3678. useCompressionStream
  3679. });
  3680. const headerInfo = getHeaderInfo(options);
  3681. const dataDescriptorInfo = getDataDescriptorInfo(options);
  3682. const metadataSize = getLength(headerInfo.localHeaderArray, dataDescriptorInfo.dataDescriptorArray);
  3683. maximumEntrySize = metadataSize + maximumCompressedSize;
  3684. if (zipWriter.options.usdz) {
  3685. maximumEntrySize += maximumEntrySize + 64;
  3686. }
  3687. zipWriter.pendingEntriesSize += maximumEntrySize;
  3688. let fileEntry;
  3689. try {
  3690. fileEntry = await getFileEntry(zipWriter, name, reader, { headerInfo, dataDescriptorInfo, metadataSize }, options);
  3691. } finally {
  3692. zipWriter.pendingEntriesSize -= maximumEntrySize;
  3693. }
  3694. Object$1.assign(fileEntry, { name, comment, extraField });
  3695. return new Entry(fileEntry);
  3696. }
  3697. async function getFileEntry(zipWriter, name, reader, entryInfo, options) {
  3698. const {
  3699. files,
  3700. writer
  3701. } = zipWriter;
  3702. const {
  3703. keepOrder,
  3704. dataDescriptor,
  3705. signal
  3706. } = options;
  3707. const {
  3708. headerInfo
  3709. } = entryInfo;
  3710. const { usdz } = zipWriter.options;
  3711. const previousFileEntry = Array.from(files.values()).pop();
  3712. let fileEntry = {};
  3713. let bufferedWrite;
  3714. let releaseLockWriter;
  3715. let releaseLockCurrentFileEntry;
  3716. let writingBufferedEntryData;
  3717. let writingEntryData;
  3718. let fileWriter;
  3719. files.set(name, fileEntry);
  3720. try {
  3721. let lockPreviousFileEntry;
  3722. if (keepOrder) {
  3723. lockPreviousFileEntry = previousFileEntry && previousFileEntry.lock;
  3724. requestLockCurrentFileEntry();
  3725. }
  3726. if ((options.bufferedWrite || zipWriter.writerLocked || (zipWriter.bufferedWrites && keepOrder) || !dataDescriptor) && !usdz) {
  3727. fileWriter = new BlobWriter();
  3728. fileWriter.writable.size = 0;
  3729. bufferedWrite = true;
  3730. zipWriter.bufferedWrites++;
  3731. await initStream(writer);
  3732. } else {
  3733. fileWriter = writer;
  3734. await requestLockWriter();
  3735. }
  3736. await initStream(fileWriter);
  3737. const { writable } = writer;
  3738. let { diskOffset } = writer;
  3739. if (zipWriter.addSplitZipSignature) {
  3740. delete zipWriter.addSplitZipSignature;
  3741. const signatureArray = new Uint8Array(4);
  3742. const signatureArrayView = getDataView(signatureArray);
  3743. setUint32(signatureArrayView, 0, SPLIT_ZIP_FILE_SIGNATURE);
  3744. await writeData(writable, signatureArray);
  3745. zipWriter.offset += 4;
  3746. }
  3747. if (usdz) {
  3748. appendExtraFieldUSDZ(entryInfo, zipWriter.offset - diskOffset);
  3749. }
  3750. if (!bufferedWrite) {
  3751. await lockPreviousFileEntry;
  3752. await skipDiskIfNeeded(writable);
  3753. }
  3754. const { diskNumber } = writer;
  3755. writingEntryData = true;
  3756. fileEntry.diskNumberStart = diskNumber;
  3757. fileEntry = await createFileEntry(reader, fileWriter, fileEntry, entryInfo, zipWriter.config, options);
  3758. writingEntryData = false;
  3759. files.set(name, fileEntry);
  3760. fileEntry.filename = name;
  3761. if (bufferedWrite) {
  3762. await fileWriter.writable.getWriter().close();
  3763. let blob = await fileWriter.getData();
  3764. await lockPreviousFileEntry;
  3765. await requestLockWriter();
  3766. writingBufferedEntryData = true;
  3767. if (!dataDescriptor) {
  3768. blob = await writeExtraHeaderInfo(fileEntry, blob, writable, options);
  3769. }
  3770. await skipDiskIfNeeded(writable);
  3771. fileEntry.diskNumberStart = writer.diskNumber;
  3772. diskOffset = writer.diskOffset;
  3773. await blob.stream().pipeTo(writable, { preventClose: true, preventAbort: true, signal });
  3774. writable.size += blob.size;
  3775. writingBufferedEntryData = false;
  3776. }
  3777. fileEntry.offset = zipWriter.offset - diskOffset;
  3778. if (fileEntry.zip64) {
  3779. setZip64ExtraInfo(fileEntry, options);
  3780. } else if (fileEntry.offset >= MAX_32_BITS) {
  3781. throw new Error(ERR_UNSUPPORTED_FORMAT);
  3782. }
  3783. zipWriter.offset += fileEntry.length;
  3784. return fileEntry;
  3785. } catch (error) {
  3786. if ((bufferedWrite && writingBufferedEntryData) || (!bufferedWrite && writingEntryData)) {
  3787. zipWriter.hasCorruptedEntries = true;
  3788. if (error) {
  3789. try {
  3790. error.corruptedEntry = true;
  3791. } catch (_error) {
  3792. // ignored
  3793. }
  3794. }
  3795. if (bufferedWrite) {
  3796. zipWriter.offset += fileWriter.writable.size;
  3797. } else {
  3798. zipWriter.offset = fileWriter.writable.size;
  3799. }
  3800. }
  3801. files.delete(name);
  3802. throw error;
  3803. } finally {
  3804. if (bufferedWrite) {
  3805. zipWriter.bufferedWrites--;
  3806. }
  3807. if (releaseLockCurrentFileEntry) {
  3808. releaseLockCurrentFileEntry();
  3809. }
  3810. if (releaseLockWriter) {
  3811. releaseLockWriter();
  3812. }
  3813. }
  3814. function requestLockCurrentFileEntry() {
  3815. fileEntry.lock = new Promise$1(resolve => releaseLockCurrentFileEntry = resolve);
  3816. }
  3817. async function requestLockWriter() {
  3818. zipWriter.writerLocked = true;
  3819. const { lockWriter } = zipWriter;
  3820. zipWriter.lockWriter = new Promise$1(resolve => releaseLockWriter = () => {
  3821. zipWriter.writerLocked = false;
  3822. resolve();
  3823. });
  3824. await lockWriter;
  3825. }
  3826. async function skipDiskIfNeeded(writable) {
  3827. if (headerInfo.localHeaderArray.length > writer.availableSize) {
  3828. writer.availableSize = 0;
  3829. await writeData(writable, new Uint8Array());
  3830. }
  3831. }
  3832. }
  3833. async function createFileEntry(reader, writer, { diskNumberStart, lock }, entryInfo, config, options) {
  3834. const {
  3835. headerInfo,
  3836. dataDescriptorInfo,
  3837. metadataSize
  3838. } = entryInfo;
  3839. const {
  3840. localHeaderArray,
  3841. headerArray,
  3842. lastModDate,
  3843. rawLastModDate,
  3844. encrypted,
  3845. compressed,
  3846. version,
  3847. compressionMethod,
  3848. rawExtraFieldExtendedTimestamp,
  3849. extraFieldExtendedTimestampFlag,
  3850. rawExtraFieldNTFS,
  3851. rawExtraFieldAES
  3852. } = headerInfo;
  3853. const { dataDescriptorArray } = dataDescriptorInfo;
  3854. const {
  3855. rawFilename,
  3856. lastAccessDate,
  3857. creationDate,
  3858. password,
  3859. level,
  3860. zip64,
  3861. zip64UncompressedSize,
  3862. zip64CompressedSize,
  3863. zip64Offset,
  3864. zip64DiskNumberStart,
  3865. zipCrypto,
  3866. dataDescriptor,
  3867. directory,
  3868. versionMadeBy,
  3869. rawComment,
  3870. rawExtraField,
  3871. useWebWorkers,
  3872. onstart,
  3873. onprogress,
  3874. onend,
  3875. signal,
  3876. encryptionStrength,
  3877. extendedTimestamp,
  3878. msDosCompatible,
  3879. internalFileAttribute,
  3880. externalFileAttribute,
  3881. useCompressionStream
  3882. } = options;
  3883. const fileEntry = {
  3884. lock,
  3885. versionMadeBy,
  3886. zip64,
  3887. directory: Boolean(directory),
  3888. filenameUTF8: true,
  3889. rawFilename,
  3890. commentUTF8: true,
  3891. rawComment,
  3892. rawExtraFieldExtendedTimestamp,
  3893. rawExtraFieldNTFS,
  3894. rawExtraFieldAES,
  3895. rawExtraField,
  3896. extendedTimestamp,
  3897. msDosCompatible,
  3898. internalFileAttribute,
  3899. externalFileAttribute,
  3900. diskNumberStart
  3901. };
  3902. let compressedSize = 0;
  3903. let uncompressedSize = 0;
  3904. let signature;
  3905. const { writable } = writer;
  3906. if (reader) {
  3907. reader.chunkSize = getChunkSize(config);
  3908. await writeData(writable, localHeaderArray);
  3909. const readable = reader.readable;
  3910. const size = readable.size = reader.size;
  3911. const workerOptions = {
  3912. options: {
  3913. codecType: CODEC_DEFLATE,
  3914. level,
  3915. password,
  3916. encryptionStrength,
  3917. zipCrypto: encrypted && zipCrypto,
  3918. passwordVerification: encrypted && zipCrypto && (rawLastModDate >> 8) & 0xFF,
  3919. signed: true,
  3920. compressed,
  3921. encrypted,
  3922. useWebWorkers,
  3923. useCompressionStream,
  3924. transferStreams: false
  3925. },
  3926. config,
  3927. streamOptions: { signal, size, onstart, onprogress, onend }
  3928. };
  3929. const result = await runWorker({ readable, writable }, workerOptions);
  3930. writable.size += result.size;
  3931. signature = result.signature;
  3932. uncompressedSize = reader.size = readable.size;
  3933. compressedSize = result.size;
  3934. } else {
  3935. await writeData(writable, localHeaderArray);
  3936. }
  3937. let rawExtraFieldZip64;
  3938. if (zip64) {
  3939. let rawExtraFieldZip64Length = 4;
  3940. if (zip64UncompressedSize) {
  3941. rawExtraFieldZip64Length += 8;
  3942. }
  3943. if (zip64CompressedSize) {
  3944. rawExtraFieldZip64Length += 8;
  3945. }
  3946. if (zip64Offset) {
  3947. rawExtraFieldZip64Length += 8;
  3948. }
  3949. if (zip64DiskNumberStart) {
  3950. rawExtraFieldZip64Length += 4;
  3951. }
  3952. rawExtraFieldZip64 = new Uint8Array(rawExtraFieldZip64Length);
  3953. } else {
  3954. rawExtraFieldZip64 = new Uint8Array();
  3955. }
  3956. setEntryInfo({
  3957. signature,
  3958. rawExtraFieldZip64,
  3959. compressedSize,
  3960. uncompressedSize,
  3961. headerInfo,
  3962. dataDescriptorInfo
  3963. }, options);
  3964. if (dataDescriptor) {
  3965. await writeData(writable, dataDescriptorArray);
  3966. }
  3967. Object$1.assign(fileEntry, {
  3968. uncompressedSize,
  3969. compressedSize,
  3970. lastModDate,
  3971. rawLastModDate,
  3972. creationDate,
  3973. lastAccessDate,
  3974. encrypted,
  3975. length: metadataSize + compressedSize,
  3976. compressionMethod,
  3977. version,
  3978. headerArray,
  3979. signature,
  3980. rawExtraFieldZip64,
  3981. extraFieldExtendedTimestampFlag,
  3982. zip64UncompressedSize,
  3983. zip64CompressedSize,
  3984. zip64Offset,
  3985. zip64DiskNumberStart
  3986. });
  3987. return fileEntry;
  3988. }
  3989. function getHeaderInfo(options) {
  3990. const {
  3991. rawFilename,
  3992. lastModDate,
  3993. lastAccessDate,
  3994. creationDate,
  3995. password,
  3996. level,
  3997. zip64,
  3998. zipCrypto,
  3999. dataDescriptor,
  4000. directory,
  4001. rawExtraField,
  4002. encryptionStrength,
  4003. extendedTimestamp
  4004. } = options;
  4005. const compressed = level !== 0 && !directory;
  4006. const encrypted = Boolean(password && getLength(password));
  4007. let version = options.version;
  4008. let rawExtraFieldAES;
  4009. if (encrypted && !zipCrypto) {
  4010. rawExtraFieldAES = new Uint8Array(getLength(EXTRAFIELD_DATA_AES) + 2);
  4011. const extraFieldAESView = getDataView(rawExtraFieldAES);
  4012. setUint16(extraFieldAESView, 0, EXTRAFIELD_TYPE_AES);
  4013. arraySet(rawExtraFieldAES, EXTRAFIELD_DATA_AES, 2);
  4014. setUint8(extraFieldAESView, 8, encryptionStrength);
  4015. } else {
  4016. rawExtraFieldAES = new Uint8Array();
  4017. }
  4018. let rawExtraFieldNTFS;
  4019. let rawExtraFieldExtendedTimestamp;
  4020. let extraFieldExtendedTimestampFlag;
  4021. if (extendedTimestamp) {
  4022. rawExtraFieldExtendedTimestamp = new Uint8Array(9 + (lastAccessDate ? 4 : 0) + (creationDate ? 4 : 0));
  4023. const extraFieldExtendedTimestampView = getDataView(rawExtraFieldExtendedTimestamp);
  4024. setUint16(extraFieldExtendedTimestampView, 0, EXTRAFIELD_TYPE_EXTENDED_TIMESTAMP);
  4025. setUint16(extraFieldExtendedTimestampView, 2, getLength(rawExtraFieldExtendedTimestamp) - 4);
  4026. extraFieldExtendedTimestampFlag = 0x1 + (lastAccessDate ? 0x2 : 0) + (creationDate ? 0x4 : 0);
  4027. setUint8(extraFieldExtendedTimestampView, 4, extraFieldExtendedTimestampFlag);
  4028. let offset = 5;
  4029. setUint32(extraFieldExtendedTimestampView, offset, Math.floor(lastModDate.getTime() / 1000));
  4030. offset += 4;
  4031. if (lastAccessDate) {
  4032. setUint32(extraFieldExtendedTimestampView, offset, Math.floor(lastAccessDate.getTime() / 1000));
  4033. offset += 4;
  4034. }
  4035. if (creationDate) {
  4036. setUint32(extraFieldExtendedTimestampView, offset, Math.floor(creationDate.getTime() / 1000));
  4037. }
  4038. try {
  4039. rawExtraFieldNTFS = new Uint8Array(36);
  4040. const extraFieldNTFSView = getDataView(rawExtraFieldNTFS);
  4041. const lastModTimeNTFS = getTimeNTFS(lastModDate);
  4042. setUint16(extraFieldNTFSView, 0, EXTRAFIELD_TYPE_NTFS);
  4043. setUint16(extraFieldNTFSView, 2, 32);
  4044. setUint16(extraFieldNTFSView, 8, EXTRAFIELD_TYPE_NTFS_TAG1);
  4045. setUint16(extraFieldNTFSView, 10, 24);
  4046. setBigUint64(extraFieldNTFSView, 12, lastModTimeNTFS);
  4047. setBigUint64(extraFieldNTFSView, 20, getTimeNTFS(lastAccessDate) || lastModTimeNTFS);
  4048. setBigUint64(extraFieldNTFSView, 28, getTimeNTFS(creationDate) || lastModTimeNTFS);
  4049. } catch (_error) {
  4050. rawExtraFieldNTFS = new Uint8Array();
  4051. }
  4052. } else {
  4053. rawExtraFieldNTFS = rawExtraFieldExtendedTimestamp = new Uint8Array();
  4054. }
  4055. let bitFlag = BITFLAG_LANG_ENCODING_FLAG;
  4056. if (dataDescriptor) {
  4057. bitFlag = bitFlag | BITFLAG_DATA_DESCRIPTOR;
  4058. }
  4059. let compressionMethod = COMPRESSION_METHOD_STORE;
  4060. if (compressed) {
  4061. compressionMethod = COMPRESSION_METHOD_DEFLATE;
  4062. }
  4063. if (zip64) {
  4064. version = version > VERSION_ZIP64 ? version : VERSION_ZIP64;
  4065. }
  4066. if (encrypted) {
  4067. bitFlag = bitFlag | BITFLAG_ENCRYPTED;
  4068. if (!zipCrypto) {
  4069. version = version > VERSION_AES ? version : VERSION_AES;
  4070. compressionMethod = COMPRESSION_METHOD_AES;
  4071. if (compressed) {
  4072. rawExtraFieldAES[9] = COMPRESSION_METHOD_DEFLATE;
  4073. }
  4074. }
  4075. }
  4076. const headerArray = new Uint8Array(26);
  4077. const headerView = getDataView(headerArray);
  4078. setUint16(headerView, 0, version);
  4079. setUint16(headerView, 2, bitFlag);
  4080. setUint16(headerView, 4, compressionMethod);
  4081. const dateArray = new Uint32Array(1);
  4082. const dateView = getDataView(dateArray);
  4083. let lastModDateMsDos;
  4084. if (lastModDate < MIN_DATE) {
  4085. lastModDateMsDos = MIN_DATE;
  4086. } else if (lastModDate > MAX_DATE) {
  4087. lastModDateMsDos = MAX_DATE;
  4088. } else {
  4089. lastModDateMsDos = lastModDate;
  4090. }
  4091. setUint16(dateView, 0, (((lastModDateMsDos.getHours() << 6) | lastModDateMsDos.getMinutes()) << 5) | lastModDateMsDos.getSeconds() / 2);
  4092. setUint16(dateView, 2, ((((lastModDateMsDos.getFullYear() - 1980) << 4) | (lastModDateMsDos.getMonth() + 1)) << 5) | lastModDateMsDos.getDate());
  4093. const rawLastModDate = dateArray[0];
  4094. setUint32(headerView, 6, rawLastModDate);
  4095. setUint16(headerView, 22, getLength(rawFilename));
  4096. const extraFieldLength = getLength(rawExtraFieldAES, rawExtraFieldExtendedTimestamp, rawExtraFieldNTFS, rawExtraField);
  4097. setUint16(headerView, 24, extraFieldLength);
  4098. const localHeaderArray = new Uint8Array(30 + getLength(rawFilename) + extraFieldLength);
  4099. const localHeaderView = getDataView(localHeaderArray);
  4100. setUint32(localHeaderView, 0, LOCAL_FILE_HEADER_SIGNATURE);
  4101. arraySet(localHeaderArray, headerArray, 4);
  4102. arraySet(localHeaderArray, rawFilename, 30);
  4103. arraySet(localHeaderArray, rawExtraFieldAES, 30 + getLength(rawFilename));
  4104. arraySet(localHeaderArray, rawExtraFieldExtendedTimestamp, 30 + getLength(rawFilename, rawExtraFieldAES));
  4105. arraySet(localHeaderArray, rawExtraFieldNTFS, 30 + getLength(rawFilename, rawExtraFieldAES, rawExtraFieldExtendedTimestamp));
  4106. arraySet(localHeaderArray, rawExtraField, 30 + getLength(rawFilename, rawExtraFieldAES, rawExtraFieldExtendedTimestamp, rawExtraFieldNTFS));
  4107. return {
  4108. localHeaderArray,
  4109. headerArray,
  4110. headerView,
  4111. lastModDate,
  4112. rawLastModDate,
  4113. encrypted,
  4114. compressed,
  4115. version,
  4116. compressionMethod,
  4117. extraFieldExtendedTimestampFlag,
  4118. rawExtraFieldExtendedTimestamp,
  4119. rawExtraFieldNTFS,
  4120. rawExtraFieldAES,
  4121. extraFieldLength
  4122. };
  4123. }
  4124. function appendExtraFieldUSDZ(entryInfo, zipWriterOffset) {
  4125. const { headerInfo } = entryInfo;
  4126. let { localHeaderArray, extraFieldLength } = headerInfo;
  4127. let localHeaderArrayView = getDataView(localHeaderArray);
  4128. let extraBytesLength = 64 - ((zipWriterOffset + localHeaderArray.length) % 64);
  4129. if (extraBytesLength < 4) {
  4130. extraBytesLength += 64;
  4131. }
  4132. const rawExtraFieldUSDZ = new Uint8Array(extraBytesLength);
  4133. const extraFieldUSDZView = getDataView(rawExtraFieldUSDZ);
  4134. setUint16(extraFieldUSDZView, 0, EXTRAFIELD_TYPE_USDZ);
  4135. setUint16(extraFieldUSDZView, 2, extraBytesLength - 2);
  4136. const previousLocalHeaderArray = localHeaderArray;
  4137. headerInfo.localHeaderArray = localHeaderArray = new Uint8Array(previousLocalHeaderArray.length + extraBytesLength);
  4138. arraySet(localHeaderArray, previousLocalHeaderArray);
  4139. arraySet(localHeaderArray, rawExtraFieldUSDZ, previousLocalHeaderArray.length);
  4140. localHeaderArrayView = getDataView(localHeaderArray);
  4141. setUint16(localHeaderArrayView, 28, extraFieldLength + extraBytesLength);
  4142. entryInfo.metadataSize += extraBytesLength;
  4143. }
  4144. function getDataDescriptorInfo(options) {
  4145. const {
  4146. zip64,
  4147. dataDescriptor,
  4148. dataDescriptorSignature
  4149. } = options;
  4150. let dataDescriptorArray = new Uint8Array();
  4151. let dataDescriptorView, dataDescriptorOffset = 0;
  4152. if (dataDescriptor) {
  4153. dataDescriptorArray = new Uint8Array(zip64 ? (dataDescriptorSignature ? 24 : 20) : (dataDescriptorSignature ? 16 : 12));
  4154. dataDescriptorView = getDataView(dataDescriptorArray);
  4155. if (dataDescriptorSignature) {
  4156. dataDescriptorOffset = 4;
  4157. setUint32(dataDescriptorView, 0, DATA_DESCRIPTOR_RECORD_SIGNATURE);
  4158. }
  4159. }
  4160. return {
  4161. dataDescriptorArray,
  4162. dataDescriptorView,
  4163. dataDescriptorOffset
  4164. };
  4165. }
  4166. function setEntryInfo(entryInfo, options) {
  4167. const {
  4168. signature,
  4169. rawExtraFieldZip64,
  4170. compressedSize,
  4171. uncompressedSize,
  4172. headerInfo,
  4173. dataDescriptorInfo
  4174. } = entryInfo;
  4175. const {
  4176. headerView,
  4177. encrypted
  4178. } = headerInfo;
  4179. const {
  4180. dataDescriptorView,
  4181. dataDescriptorOffset
  4182. } = dataDescriptorInfo;
  4183. const {
  4184. zip64,
  4185. zip64UncompressedSize,
  4186. zip64CompressedSize,
  4187. zipCrypto,
  4188. dataDescriptor
  4189. } = options;
  4190. if ((!encrypted || zipCrypto) && signature !== UNDEFINED_VALUE) {
  4191. setUint32(headerView, 10, signature);
  4192. if (dataDescriptor) {
  4193. setUint32(dataDescriptorView, dataDescriptorOffset, signature);
  4194. }
  4195. }
  4196. if (zip64) {
  4197. const rawExtraFieldZip64View = getDataView(rawExtraFieldZip64);
  4198. setUint16(rawExtraFieldZip64View, 0, EXTRAFIELD_TYPE_ZIP64);
  4199. setUint16(rawExtraFieldZip64View, 2, rawExtraFieldZip64.length - 4);
  4200. let rawExtraFieldZip64Offset = 4;
  4201. if (zip64UncompressedSize) {
  4202. setUint32(headerView, 18, MAX_32_BITS);
  4203. setBigUint64(rawExtraFieldZip64View, rawExtraFieldZip64Offset, BigInt(uncompressedSize));
  4204. rawExtraFieldZip64Offset += 8;
  4205. }
  4206. if (zip64CompressedSize) {
  4207. setUint32(headerView, 14, MAX_32_BITS);
  4208. setBigUint64(rawExtraFieldZip64View, rawExtraFieldZip64Offset, BigInt(compressedSize));
  4209. }
  4210. if (dataDescriptor) {
  4211. setBigUint64(dataDescriptorView, dataDescriptorOffset + 4, BigInt(compressedSize));
  4212. setBigUint64(dataDescriptorView, dataDescriptorOffset + 12, BigInt(uncompressedSize));
  4213. }
  4214. } else {
  4215. setUint32(headerView, 14, compressedSize);
  4216. setUint32(headerView, 18, uncompressedSize);
  4217. if (dataDescriptor) {
  4218. setUint32(dataDescriptorView, dataDescriptorOffset + 4, compressedSize);
  4219. setUint32(dataDescriptorView, dataDescriptorOffset + 8, uncompressedSize);
  4220. }
  4221. }
  4222. }
  4223. async function writeExtraHeaderInfo(fileEntry, entryData, writable, { zipCrypto }) {
  4224. let arrayBuffer;
  4225. arrayBuffer = await entryData.slice(0, 26).arrayBuffer();
  4226. if (arrayBuffer.byteLength != 26) {
  4227. arrayBuffer = arrayBuffer.slice(0, 26);
  4228. }
  4229. const arrayBufferView = new DataView(arrayBuffer);
  4230. if (!fileEntry.encrypted || zipCrypto) {
  4231. setUint32(arrayBufferView, 14, fileEntry.signature);
  4232. }
  4233. if (fileEntry.zip64) {
  4234. setUint32(arrayBufferView, 18, MAX_32_BITS);
  4235. setUint32(arrayBufferView, 22, MAX_32_BITS);
  4236. } else {
  4237. setUint32(arrayBufferView, 18, fileEntry.compressedSize);
  4238. setUint32(arrayBufferView, 22, fileEntry.uncompressedSize);
  4239. }
  4240. await writeData(writable, new Uint8Array(arrayBuffer));
  4241. return entryData.slice(arrayBuffer.byteLength);
  4242. }
  4243. function setZip64ExtraInfo(fileEntry, options) {
  4244. const { rawExtraFieldZip64, offset, diskNumberStart } = fileEntry;
  4245. const { zip64UncompressedSize, zip64CompressedSize, zip64Offset, zip64DiskNumberStart } = options;
  4246. const rawExtraFieldZip64View = getDataView(rawExtraFieldZip64);
  4247. let rawExtraFieldZip64Offset = 4;
  4248. if (zip64UncompressedSize) {
  4249. rawExtraFieldZip64Offset += 8;
  4250. }
  4251. if (zip64CompressedSize) {
  4252. rawExtraFieldZip64Offset += 8;
  4253. }
  4254. if (zip64Offset) {
  4255. setBigUint64(rawExtraFieldZip64View, rawExtraFieldZip64Offset, BigInt(offset));
  4256. rawExtraFieldZip64Offset += 8;
  4257. }
  4258. if (zip64DiskNumberStart) {
  4259. setUint32(rawExtraFieldZip64View, rawExtraFieldZip64Offset, diskNumberStart);
  4260. }
  4261. }
  4262. async function closeFile(zipWriter, comment, options) {
  4263. const { files, writer } = zipWriter;
  4264. const { diskOffset, writable } = writer;
  4265. let { diskNumber } = writer;
  4266. let offset = 0;
  4267. let directoryDataLength = 0;
  4268. let directoryOffset = zipWriter.offset - diskOffset;
  4269. let filesLength = files.size;
  4270. for (const [, fileEntry] of files) {
  4271. const {
  4272. rawFilename,
  4273. rawExtraFieldZip64,
  4274. rawExtraFieldAES,
  4275. rawComment,
  4276. rawExtraFieldNTFS,
  4277. rawExtraField,
  4278. extendedTimestamp,
  4279. extraFieldExtendedTimestampFlag,
  4280. lastModDate
  4281. } = fileEntry;
  4282. let rawExtraFieldTimestamp;
  4283. if (extendedTimestamp) {
  4284. rawExtraFieldTimestamp = new Uint8Array(9);
  4285. const extraFieldExtendedTimestampView = getDataView(rawExtraFieldTimestamp);
  4286. setUint16(extraFieldExtendedTimestampView, 0, EXTRAFIELD_TYPE_EXTENDED_TIMESTAMP);
  4287. setUint16(extraFieldExtendedTimestampView, 2, 5);
  4288. setUint8(extraFieldExtendedTimestampView, 4, extraFieldExtendedTimestampFlag);
  4289. setUint32(extraFieldExtendedTimestampView, 5, Math.floor(lastModDate.getTime() / 1000));
  4290. } else {
  4291. rawExtraFieldTimestamp = new Uint8Array();
  4292. }
  4293. fileEntry.rawExtraFieldCDExtendedTimestamp = rawExtraFieldTimestamp;
  4294. directoryDataLength += 46 +
  4295. getLength(
  4296. rawFilename,
  4297. rawComment,
  4298. rawExtraFieldZip64,
  4299. rawExtraFieldAES,
  4300. rawExtraFieldNTFS,
  4301. rawExtraFieldTimestamp,
  4302. rawExtraField);
  4303. }
  4304. const directoryArray = new Uint8Array(directoryDataLength);
  4305. const directoryView = getDataView(directoryArray);
  4306. await initStream(writer);
  4307. let directoryDiskOffset = 0;
  4308. for (const [indexFileEntry, fileEntry] of Array.from(files.values()).entries()) {
  4309. const {
  4310. offset: fileEntryOffset,
  4311. rawFilename,
  4312. rawExtraFieldZip64,
  4313. rawExtraFieldAES,
  4314. rawExtraFieldCDExtendedTimestamp,
  4315. rawExtraFieldNTFS,
  4316. rawExtraField,
  4317. rawComment,
  4318. versionMadeBy,
  4319. headerArray,
  4320. directory,
  4321. zip64,
  4322. zip64UncompressedSize,
  4323. zip64CompressedSize,
  4324. zip64DiskNumberStart,
  4325. zip64Offset,
  4326. msDosCompatible,
  4327. internalFileAttribute,
  4328. externalFileAttribute,
  4329. diskNumberStart,
  4330. uncompressedSize,
  4331. compressedSize
  4332. } = fileEntry;
  4333. const extraFieldLength = getLength(rawExtraFieldZip64, rawExtraFieldAES, rawExtraFieldCDExtendedTimestamp, rawExtraFieldNTFS, rawExtraField);
  4334. setUint32(directoryView, offset, CENTRAL_FILE_HEADER_SIGNATURE);
  4335. setUint16(directoryView, offset + 4, versionMadeBy);
  4336. const headerView = getDataView(headerArray);
  4337. if (!zip64UncompressedSize) {
  4338. setUint32(headerView, 18, uncompressedSize);
  4339. }
  4340. if (!zip64CompressedSize) {
  4341. setUint32(headerView, 14, compressedSize);
  4342. }
  4343. arraySet(directoryArray, headerArray, offset + 6);
  4344. setUint16(directoryView, offset + 30, extraFieldLength);
  4345. setUint16(directoryView, offset + 32, getLength(rawComment));
  4346. setUint16(directoryView, offset + 34, zip64 && zip64DiskNumberStart ? MAX_16_BITS : diskNumberStart);
  4347. setUint16(directoryView, offset + 36, internalFileAttribute);
  4348. if (externalFileAttribute) {
  4349. setUint32(directoryView, offset + 38, externalFileAttribute);
  4350. } else if (directory && msDosCompatible) {
  4351. setUint8(directoryView, offset + 38, FILE_ATTR_MSDOS_DIR_MASK);
  4352. }
  4353. setUint32(directoryView, offset + 42, zip64 && zip64Offset ? MAX_32_BITS : fileEntryOffset);
  4354. arraySet(directoryArray, rawFilename, offset + 46);
  4355. arraySet(directoryArray, rawExtraFieldZip64, offset + 46 + getLength(rawFilename));
  4356. arraySet(directoryArray, rawExtraFieldAES, offset + 46 + getLength(rawFilename, rawExtraFieldZip64));
  4357. arraySet(directoryArray, rawExtraFieldCDExtendedTimestamp, offset + 46 + getLength(rawFilename, rawExtraFieldZip64, rawExtraFieldAES));
  4358. arraySet(directoryArray, rawExtraFieldNTFS, offset + 46 + getLength(rawFilename, rawExtraFieldZip64, rawExtraFieldAES, rawExtraFieldCDExtendedTimestamp));
  4359. arraySet(directoryArray, rawExtraField, offset + 46 + getLength(rawFilename, rawExtraFieldZip64, rawExtraFieldAES, rawExtraFieldCDExtendedTimestamp, rawExtraFieldNTFS));
  4360. arraySet(directoryArray, rawComment, offset + 46 + getLength(rawFilename) + extraFieldLength);
  4361. const directoryEntryLength = 46 + getLength(rawFilename, rawComment) + extraFieldLength;
  4362. if (offset - directoryDiskOffset > writer.availableSize) {
  4363. writer.availableSize = 0;
  4364. await writeData(writable, directoryArray.slice(directoryDiskOffset, offset));
  4365. directoryDiskOffset = offset;
  4366. }
  4367. offset += directoryEntryLength;
  4368. if (options.onprogress) {
  4369. try {
  4370. await options.onprogress(indexFileEntry + 1, files.size, new Entry(fileEntry));
  4371. } catch (_error) {
  4372. // ignored
  4373. }
  4374. }
  4375. }
  4376. await writeData(writable, directoryDiskOffset ? directoryArray.slice(directoryDiskOffset) : directoryArray);
  4377. let lastDiskNumber = writer.diskNumber;
  4378. const { availableSize } = writer;
  4379. if (availableSize < END_OF_CENTRAL_DIR_LENGTH) {
  4380. lastDiskNumber++;
  4381. }
  4382. let zip64 = getOptionValue(zipWriter, options, "zip64");
  4383. if (directoryOffset >= MAX_32_BITS || directoryDataLength >= MAX_32_BITS || filesLength >= MAX_16_BITS || lastDiskNumber >= MAX_16_BITS) {
  4384. if (zip64 === false) {
  4385. throw new Error(ERR_UNSUPPORTED_FORMAT);
  4386. } else {
  4387. zip64 = true;
  4388. }
  4389. }
  4390. const endOfdirectoryArray = new Uint8Array(zip64 ? ZIP64_END_OF_CENTRAL_DIR_TOTAL_LENGTH : END_OF_CENTRAL_DIR_LENGTH);
  4391. const endOfdirectoryView = getDataView(endOfdirectoryArray);
  4392. offset = 0;
  4393. if (zip64) {
  4394. setUint32(endOfdirectoryView, 0, ZIP64_END_OF_CENTRAL_DIR_SIGNATURE);
  4395. setBigUint64(endOfdirectoryView, 4, BigInt(44));
  4396. setUint16(endOfdirectoryView, 12, 45);
  4397. setUint16(endOfdirectoryView, 14, 45);
  4398. setUint32(endOfdirectoryView, 16, lastDiskNumber);
  4399. setUint32(endOfdirectoryView, 20, diskNumber);
  4400. setBigUint64(endOfdirectoryView, 24, BigInt(filesLength));
  4401. setBigUint64(endOfdirectoryView, 32, BigInt(filesLength));
  4402. setBigUint64(endOfdirectoryView, 40, BigInt(directoryDataLength));
  4403. setBigUint64(endOfdirectoryView, 48, BigInt(directoryOffset));
  4404. setUint32(endOfdirectoryView, 56, ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIGNATURE);
  4405. setBigUint64(endOfdirectoryView, 64, BigInt(directoryOffset) + BigInt(directoryDataLength));
  4406. setUint32(endOfdirectoryView, 72, lastDiskNumber + 1);
  4407. const supportZip64SplitFile = getOptionValue(zipWriter, options, "supportZip64SplitFile", true);
  4408. if (supportZip64SplitFile) {
  4409. lastDiskNumber = MAX_16_BITS;
  4410. diskNumber = MAX_16_BITS;
  4411. }
  4412. filesLength = MAX_16_BITS;
  4413. directoryOffset = MAX_32_BITS;
  4414. directoryDataLength = MAX_32_BITS;
  4415. offset += ZIP64_END_OF_CENTRAL_DIR_LENGTH + ZIP64_END_OF_CENTRAL_DIR_LOCATOR_LENGTH;
  4416. }
  4417. setUint32(endOfdirectoryView, offset, END_OF_CENTRAL_DIR_SIGNATURE);
  4418. setUint16(endOfdirectoryView, offset + 4, lastDiskNumber);
  4419. setUint16(endOfdirectoryView, offset + 6, diskNumber);
  4420. setUint16(endOfdirectoryView, offset + 8, filesLength);
  4421. setUint16(endOfdirectoryView, offset + 10, filesLength);
  4422. setUint32(endOfdirectoryView, offset + 12, directoryDataLength);
  4423. setUint32(endOfdirectoryView, offset + 16, directoryOffset);
  4424. const commentLength = getLength(comment);
  4425. if (commentLength) {
  4426. if (commentLength <= MAX_16_BITS) {
  4427. setUint16(endOfdirectoryView, offset + 20, commentLength);
  4428. } else {
  4429. throw new Error(ERR_INVALID_COMMENT);
  4430. }
  4431. }
  4432. await writeData(writable, endOfdirectoryArray);
  4433. if (commentLength) {
  4434. await writeData(writable, comment);
  4435. }
  4436. }
  4437. async function writeData(writable, array) {
  4438. const streamWriter = writable.getWriter();
  4439. await streamWriter.ready;
  4440. writable.size += getLength(array);
  4441. await streamWriter.write(array);
  4442. streamWriter.releaseLock();
  4443. }
  4444. function getTimeNTFS(date) {
  4445. if (date) {
  4446. return ((BigInt(date.getTime()) + BigInt(11644473600000)) * BigInt(10000));
  4447. }
  4448. }
  4449. function getOptionValue(zipWriter, options, name, defaultValue) {
  4450. const result = options[name] === UNDEFINED_VALUE ? zipWriter.options[name] : options[name];
  4451. return result === UNDEFINED_VALUE ? defaultValue : result;
  4452. }
  4453. function getMaximumCompressedSize(uncompressedSize) {
  4454. return uncompressedSize + (5 * (Math.floor(uncompressedSize / 16383) + 1));
  4455. }
  4456. function setUint8(view, offset, value) {
  4457. view.setUint8(offset, value);
  4458. }
  4459. function setUint16(view, offset, value) {
  4460. view.setUint16(offset, value, true);
  4461. }
  4462. function setUint32(view, offset, value) {
  4463. view.setUint32(offset, value, true);
  4464. }
  4465. function setBigUint64(view, offset, value) {
  4466. view.setBigUint64(offset, value, true);
  4467. }
  4468. function arraySet(array, typedArray, offset) {
  4469. array.set(typedArray, offset);
  4470. }
  4471. function getDataView(array) {
  4472. return new DataView(array.buffer);
  4473. }
  4474. function getLength(...arrayLikes) {
  4475. let result = 0;
  4476. arrayLikes.forEach(arrayLike => arrayLike && (result += arrayLike.length));
  4477. return result;
  4478. }
  4479. /*
  4480. Copyright (c) 2022 Gildas Lormeau. All rights reserved.
  4481. Redistribution and use in source and binary forms, with or without
  4482. modification, are permitted provided that the following conditions are met:
  4483. 1. Redistributions of source code must retain the above copyright notice,
  4484. this list of conditions and the following disclaimer.
  4485. 2. Redistributions in binary form must reproduce the above copyright
  4486. notice, this list of conditions and the following disclaimer in
  4487. the documentation and/or other materials provided with the distribution.
  4488. 3. The names of the authors may not be used to endorse or promote products
  4489. derived from this software without specific prior written permission.
  4490. THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
  4491. INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WA RRANTIES OF MERCHANTABILITY AND
  4492. FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
  4493. INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
  4494. INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  4495. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
  4496. OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  4497. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  4498. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  4499. EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  4500. */
  4501. let baseURL;
  4502. try {
  4503. baseURL = import.meta.url;
  4504. } catch (_error) {
  4505. // ignored
  4506. }
  4507. configure({ baseURL });
  4508. e(configure);
  4509. export { BlobReader, BlobWriter, Data64URIReader, Data64URIWriter, ERR_BAD_FORMAT, ERR_CENTRAL_DIRECTORY_NOT_FOUND, ERR_DUPLICATED_NAME, ERR_ENCRYPTED, ERR_EOCDR_LOCATOR_ZIP64_NOT_FOUND, ERR_EOCDR_NOT_FOUND, ERR_EOCDR_ZIP64_NOT_FOUND, ERR_EXTRAFIELD_ZIP64_NOT_FOUND, ERR_HTTP_RANGE, ERR_INVALID_COMMENT, ERR_INVALID_ENCRYPTION_STRENGTH, ERR_INVALID_ENTRY_COMMENT, ERR_INVALID_ENTRY_NAME, ERR_INVALID_EXTRAFIELD_DATA, ERR_INVALID_EXTRAFIELD_TYPE, ERR_INVALID_PASSWORD, ERR_INVALID_SIGNATURE, ERR_INVALID_VERSION, ERR_ITERATOR_COMPLETED_TOO_SOON, ERR_LOCAL_FILE_HEADER_NOT_FOUND, ERR_SPLIT_ZIP_FILE, ERR_UNSUPPORTED_COMPRESSION, ERR_UNSUPPORTED_ENCRYPTION, ERR_UNSUPPORTED_FORMAT, HttpRangeReader, HttpReader, Reader, SplitDataReader, SplitDataWriter, SplitZipReader, SplitZipWriter, TextReader, TextWriter, Uint8ArrayReader, Uint8ArrayWriter, Writer, ZipReader, ZipWriter, configure, getMimeType, initReader, initShimAsyncCodec, initStream, initWriter, readUint8Array, terminateWorkers };