single-file-extension.js 80 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507
  1. (function () {
  2. 'use strict';
  3. /* global TextEncoder, TextDecoder */
  4. const DEFAULT_CHUNK_SIZE = 8 * 1024 * 1024;
  5. const TYPE_REFERENCE = 0;
  6. const SPECIAL_TYPES = [TYPE_REFERENCE];
  7. const EMPTY_SLOT_VALUE = Symbol();
  8. const textEncoder = new TextEncoder();
  9. const textDecoder = new TextDecoder();
  10. const types = new Array(256);
  11. let typeIndex = 0;
  12. registerType(serializeCircularReference, parseCircularReference, testCircularReference, TYPE_REFERENCE);
  13. registerType(null, parseObject, testObject);
  14. registerType(serializeArray, parseArray, testArray);
  15. registerType(serializeString, parseString, testString);
  16. registerType(serializeTypedArray, parseFloat64Array, testFloat64Array);
  17. registerType(serializeTypedArray, parseFloat32Array, testFloat32Array);
  18. registerType(serializeTypedArray, parseUint32Array, testUint32Array);
  19. registerType(serializeTypedArray, parseInt32Array, testInt32Array);
  20. registerType(serializeTypedArray, parseUint16Array, testUint16Array);
  21. registerType(serializeTypedArray, parseInt16Array, testInt16Array);
  22. registerType(serializeTypedArray, parseUint8ClampedArray, testUint8ClampedArray);
  23. registerType(serializeTypedArray, parseUint8Array, testUint8Array);
  24. registerType(serializeTypedArray, parseInt8Array, testInt8Array);
  25. registerType(serializeArrayBuffer, parseArrayBuffer, testArrayBuffer);
  26. registerType(serializeNumber, parseNumber, testNumber);
  27. registerType(serializeUint32, parseUint32, testUint32);
  28. registerType(serializeInt32, parseInt32, testInt32);
  29. registerType(serializeUint16, parseUint16, testUint16);
  30. registerType(serializeInt16, parseInt16, testInt16);
  31. registerType(serializeUint8, parseUint8, testUint8);
  32. registerType(serializeInt8, parseInt8, testInt8);
  33. registerType(null, parseUndefined, testUndefined);
  34. registerType(null, parseNull, testNull);
  35. registerType(null, parseNaN, testNaN);
  36. registerType(serializeBoolean, parseBoolean, testBoolean);
  37. registerType(serializeSymbol, parseSymbol, testSymbol);
  38. registerType(null, parseEmptySlot, testEmptySlot);
  39. registerType(serializeMap, parseMap, testMap);
  40. registerType(serializeSet, parseSet, testSet);
  41. registerType(serializeDate, parseDate, testDate);
  42. registerType(serializeError, parseError, testError);
  43. registerType(serializeRegExp, parseRegExp, testRegExp);
  44. registerType(serializeStringObject, parseStringObject, testStringObject);
  45. registerType(serializeNumberObject, parseNumberObject, testNumberObject);
  46. registerType(serializeBooleanObject, parseBooleanObject, testBooleanObject);
  47. function registerType(serialize, parse, test, type) {
  48. if (type === undefined) {
  49. typeIndex++;
  50. if (types.length - typeIndex >= SPECIAL_TYPES.length) {
  51. types[types.length - typeIndex] = { serialize, parse, test };
  52. } else {
  53. throw new Error("Reached maximum number of custom types");
  54. }
  55. } else {
  56. types[type] = { serialize, parse, test };
  57. }
  58. }
  59. async function serialize(object, options) {
  60. const serializer = getSerializer(object, options);
  61. let result = new Uint8Array([]);
  62. for await (const chunk of serializer) {
  63. const previousResult = result;
  64. result = new Uint8Array(previousResult.length + chunk.length);
  65. result.set(previousResult, 0);
  66. result.set(chunk, previousResult.length);
  67. }
  68. return result;
  69. }
  70. class SerializerData {
  71. constructor(appendData, chunkSize) {
  72. this.stream = new WriteStream(appendData, chunkSize);
  73. this.objects = [];
  74. }
  75. append(array) {
  76. return this.stream.append(array);
  77. }
  78. flush() {
  79. return this.stream.flush();
  80. }
  81. addObject(value) {
  82. this.objects.push(testReferenceable(value) && !testCircularReference(value, this) ? value : undefined);
  83. }
  84. }
  85. class WriteStream {
  86. constructor(appendData, chunkSize) {
  87. this.offset = 0;
  88. this.appendData = appendData;
  89. this.value = new Uint8Array(chunkSize);
  90. }
  91. async append(array) {
  92. if (this.offset + array.length > this.value.length) {
  93. const offset = this.value.length - this.offset;
  94. await this.append(array.subarray(0, offset));
  95. await this.appendData({ value: this.value });
  96. this.offset = 0;
  97. await this.append(array.subarray(offset));
  98. } else {
  99. this.value.set(array, this.offset);
  100. this.offset += array.length;
  101. }
  102. }
  103. async flush() {
  104. if (this.offset) {
  105. await this.appendData({ value: this.value.subarray(0, this.offset), done: true });
  106. }
  107. }
  108. }
  109. function getSerializer(value, { chunkSize = DEFAULT_CHUNK_SIZE } = {}) {
  110. let serializerData, result, setResult, iterationDone, previousResult, resolvePreviousResult;
  111. return {
  112. [Symbol.asyncIterator]() {
  113. return {
  114. next() {
  115. return iterationDone ? { done: iterationDone } : getResult();
  116. },
  117. return() {
  118. return { done: true };
  119. }
  120. };
  121. }
  122. };
  123. async function getResult() {
  124. if (resolvePreviousResult) {
  125. resolvePreviousResult();
  126. } else {
  127. initSerializerData().catch(() => { /* ignored */ });
  128. }
  129. initPreviousData();
  130. const value = await getValue();
  131. return { value };
  132. }
  133. async function initSerializerData() {
  134. initResult();
  135. serializerData = new SerializerData(appendData, chunkSize);
  136. await serializeValue(serializerData, value);
  137. await serializerData.flush();
  138. }
  139. function initResult() {
  140. result = new Promise(resolve => setResult = resolve);
  141. }
  142. function initPreviousData() {
  143. previousResult = new Promise(resolve => resolvePreviousResult = resolve);
  144. }
  145. async function appendData(result) {
  146. setResult(result);
  147. await previousResult;
  148. }
  149. async function getValue() {
  150. const { value, done } = await result;
  151. iterationDone = done;
  152. if (!done) {
  153. initResult();
  154. }
  155. return value;
  156. }
  157. }
  158. async function serializeValue(data, value) {
  159. const type = types.findIndex(({ test } = {}) => test && test(value, data));
  160. data.addObject(value);
  161. await data.append(new Uint8Array([type]));
  162. const serialize = types[type].serialize;
  163. if (serialize) {
  164. await serialize(data, value);
  165. }
  166. if (type != TYPE_REFERENCE && testObject(value)) {
  167. await serializeSymbols(data, value);
  168. await serializeOwnProperties(data, value);
  169. }
  170. }
  171. async function serializeSymbols(data, value) {
  172. const ownPropertySymbols = Object.getOwnPropertySymbols(value);
  173. const symbols = ownPropertySymbols.map(propertySymbol => [propertySymbol, value[propertySymbol]]);
  174. await serializeArray(data, symbols);
  175. }
  176. async function serializeOwnProperties(data, value) {
  177. if (!ArrayBuffer.isView(value)) {
  178. let entries = Object.entries(value);
  179. if (testArray(value)) {
  180. entries = entries.filter(([key]) => !testInteger(Number(key)));
  181. }
  182. await serializeValue(data, entries.length);
  183. for (const [key, value] of entries) {
  184. await serializeString(data, key);
  185. await serializeValue(data, value);
  186. }
  187. } else {
  188. await serializeValue(data, 0);
  189. }
  190. }
  191. async function serializeCircularReference(data, value) {
  192. const index = data.objects.indexOf(value);
  193. await serializeValue(data, index);
  194. }
  195. async function serializeArray(data, array) {
  196. await serializeValue(data, array.length);
  197. const notEmptyIndexes = Object.keys(array).filter(key => testInteger(Number(key))).map(key => Number(key));
  198. let indexNotEmptyIndexes = 0, currentNotEmptyIndex = notEmptyIndexes[indexNotEmptyIndexes];
  199. for (const [indexArray, value] of array.entries()) {
  200. if (currentNotEmptyIndex == indexArray) {
  201. currentNotEmptyIndex = notEmptyIndexes[++indexNotEmptyIndexes];
  202. await serializeValue(data, value);
  203. } else {
  204. await serializeValue(data, EMPTY_SLOT_VALUE);
  205. }
  206. }
  207. }
  208. async function serializeString(data, string) {
  209. const encodedString = textEncoder.encode(string);
  210. await serializeValue(data, encodedString.length);
  211. await data.append(encodedString);
  212. }
  213. async function serializeTypedArray(data, array) {
  214. await serializeValue(data, array.length);
  215. await data.append(array.constructor.name == "Uint8Array" ? array : new Uint8Array(array.buffer));
  216. }
  217. async function serializeArrayBuffer(data, arrayBuffer) {
  218. await serializeValue(data, arrayBuffer.byteLength);
  219. await data.append(new Uint8Array(arrayBuffer));
  220. }
  221. async function serializeNumber(data, number) {
  222. const serializedNumber = new Uint8Array(new Float64Array([number]).buffer);
  223. await data.append(serializedNumber);
  224. }
  225. async function serializeUint32(data, number) {
  226. const serializedNumber = new Uint8Array(new Uint32Array([number]).buffer);
  227. await data.append(serializedNumber);
  228. }
  229. async function serializeInt32(data, number) {
  230. const serializedNumber = new Uint8Array(new Int32Array([number]).buffer);
  231. await data.append(serializedNumber);
  232. }
  233. async function serializeUint16(data, number) {
  234. const serializedNumber = new Uint8Array(new Uint16Array([number]).buffer);
  235. await data.append(serializedNumber);
  236. }
  237. async function serializeInt16(data, number) {
  238. const serializedNumber = new Uint8Array(new Int16Array([number]).buffer);
  239. await data.append(serializedNumber);
  240. }
  241. async function serializeUint8(data, number) {
  242. const serializedNumber = new Uint8Array([number]);
  243. await data.append(serializedNumber);
  244. }
  245. async function serializeInt8(data, number) {
  246. const serializedNumber = new Uint8Array(new Int8Array([number]).buffer);
  247. await data.append(serializedNumber);
  248. }
  249. async function serializeBoolean(data, boolean) {
  250. const serializedBoolean = new Uint8Array([Number(boolean)]);
  251. await data.append(serializedBoolean);
  252. }
  253. async function serializeMap(data, map) {
  254. const entries = map.entries();
  255. await serializeValue(data, map.size);
  256. for (const [key, value] of entries) {
  257. await serializeValue(data, key);
  258. await serializeValue(data, value);
  259. }
  260. }
  261. async function serializeSet(data, set) {
  262. await serializeValue(data, set.size);
  263. for (const value of set) {
  264. await serializeValue(data, value);
  265. }
  266. }
  267. async function serializeDate(data, date) {
  268. await serializeNumber(data, date.getTime());
  269. }
  270. async function serializeError(data, error) {
  271. await serializeString(data, error.message);
  272. await serializeString(data, error.stack);
  273. }
  274. async function serializeRegExp(data, regExp) {
  275. await serializeString(data, regExp.source);
  276. await serializeString(data, regExp.flags);
  277. }
  278. async function serializeStringObject(data, string) {
  279. await serializeString(data, string.valueOf());
  280. }
  281. async function serializeNumberObject(data, number) {
  282. await serializeNumber(data, number.valueOf());
  283. }
  284. async function serializeBooleanObject(data, boolean) {
  285. await serializeBoolean(data, boolean.valueOf());
  286. }
  287. async function serializeSymbol(data, symbol) {
  288. await serializeString(data, symbol.description);
  289. }
  290. class Reference {
  291. constructor(index, data) {
  292. this.index = index;
  293. this.data = data;
  294. }
  295. getObject() {
  296. return this.data.objects[this.index];
  297. }
  298. }
  299. class ParserData {
  300. constructor(consumeData) {
  301. this.stream = new ReadStream(consumeData);
  302. this.objects = [];
  303. this.setters = [];
  304. }
  305. consume(size) {
  306. return this.stream.consume(size);
  307. }
  308. getObjectId() {
  309. const objectIndex = this.objects.length;
  310. this.objects.push(undefined);
  311. return objectIndex;
  312. }
  313. resolveObject(objectId, value) {
  314. if (testReferenceable(value) && !testReference(value)) {
  315. this.objects[objectId] = value;
  316. }
  317. }
  318. setObject(functionArguments, setterFunction) {
  319. this.setters.push({ functionArguments, setterFunction });
  320. }
  321. executeSetters() {
  322. this.setters.forEach(({ functionArguments, setterFunction }) => {
  323. const resolvedArguments = functionArguments.map(argument => testReference(argument) ? argument.getObject() : argument);
  324. setterFunction(...resolvedArguments);
  325. });
  326. }
  327. }
  328. class ReadStream {
  329. constructor(consumeData) {
  330. this.offset = 0;
  331. this.value = new Uint8Array(0);
  332. this.consumeData = consumeData;
  333. }
  334. async consume(size) {
  335. if (this.offset + size > this.value.length) {
  336. const pending = this.value.subarray(this.offset, this.value.length);
  337. const value = await this.consumeData();
  338. if (pending.length + value.length != this.value.length) {
  339. this.value = new Uint8Array(pending.length + value.length);
  340. }
  341. this.value.set(pending);
  342. this.value.set(value, pending.length);
  343. this.offset = 0;
  344. return this.consume(size);
  345. } else {
  346. const result = this.value.slice(this.offset, this.offset + size);
  347. this.offset += result.length;
  348. return result;
  349. }
  350. }
  351. }
  352. function getParser() {
  353. let parserData, input, setInput, value, previousData, resolvePreviousData;
  354. return {
  355. async next(input) {
  356. return input ? getResult(input) : { value: await value, done: true };
  357. },
  358. return() {
  359. return { done: true };
  360. }
  361. };
  362. async function getResult(input) {
  363. if (previousData) {
  364. await previousData;
  365. } else {
  366. initParserData().catch(() => { /* ignored */ });
  367. }
  368. initPreviousData();
  369. setInput(input);
  370. return { done: false };
  371. }
  372. async function initParserData() {
  373. let setValue;
  374. value = new Promise(resolve => setValue = resolve);
  375. parserData = new ParserData(consumeData);
  376. initChunk();
  377. const data = await parseValue(parserData);
  378. parserData.executeSetters();
  379. setValue(data);
  380. }
  381. function initChunk() {
  382. input = new Promise(resolve => setInput = resolve);
  383. }
  384. function initPreviousData() {
  385. previousData = new Promise(resolve => resolvePreviousData = resolve);
  386. }
  387. async function consumeData() {
  388. const data = await input;
  389. initChunk();
  390. if (resolvePreviousData) {
  391. resolvePreviousData();
  392. }
  393. return data;
  394. }
  395. }
  396. async function parseValue(data) {
  397. const array = await data.consume(1);
  398. const parserType = array[0];
  399. const parse = types[parserType].parse;
  400. const valueId = data.getObjectId();
  401. const result = await parse(data);
  402. if (parserType != TYPE_REFERENCE && testObject(result)) {
  403. await parseSymbols(data, result);
  404. await parseOwnProperties(data, result);
  405. }
  406. data.resolveObject(valueId, result);
  407. return result;
  408. }
  409. async function parseSymbols(data, value) {
  410. const symbols = await parseArray(data);
  411. data.setObject([symbols], symbols => symbols.forEach(([symbol, propertyValue]) => value[symbol] = propertyValue));
  412. }
  413. async function parseOwnProperties(data, object) {
  414. const size = await parseValue(data);
  415. if (size) {
  416. await parseNextProperty();
  417. }
  418. async function parseNextProperty(indexKey = 0) {
  419. const key = await parseString(data);
  420. const value = await parseValue(data);
  421. data.setObject([value], value => object[key] = value);
  422. if (indexKey < size - 1) {
  423. await parseNextProperty(indexKey + 1);
  424. }
  425. }
  426. }
  427. async function parseCircularReference(data) {
  428. const index = await parseValue(data);
  429. const result = new Reference(index, data);
  430. return result;
  431. }
  432. function parseObject() {
  433. return {};
  434. }
  435. async function parseArray(data) {
  436. const length = await parseValue(data);
  437. const array = new Array(length);
  438. if (length) {
  439. await parseNextSlot();
  440. }
  441. return array;
  442. async function parseNextSlot(indexArray = 0) {
  443. const value = await parseValue(data);
  444. if (!testEmptySlot(value)) {
  445. data.setObject([value], value => array[indexArray] = value);
  446. }
  447. if (indexArray < length - 1) {
  448. await parseNextSlot(indexArray + 1);
  449. }
  450. }
  451. }
  452. function parseEmptySlot() {
  453. return EMPTY_SLOT_VALUE;
  454. }
  455. async function parseString(data) {
  456. const size = await parseValue(data);
  457. const array = await data.consume(size);
  458. return textDecoder.decode(array);
  459. }
  460. async function parseFloat64Array(data) {
  461. const length = await parseValue(data);
  462. const array = await data.consume(length * 8);
  463. return new Float64Array(array.buffer);
  464. }
  465. async function parseFloat32Array(data) {
  466. const length = await parseValue(data);
  467. const array = await data.consume(length * 4);
  468. return new Float32Array(array.buffer);
  469. }
  470. async function parseUint32Array(data) {
  471. const length = await parseValue(data);
  472. const array = await data.consume(length * 4);
  473. return new Uint32Array(array.buffer);
  474. }
  475. async function parseInt32Array(data) {
  476. const length = await parseValue(data);
  477. const array = await data.consume(length * 4);
  478. return new Int32Array(array.buffer);
  479. }
  480. async function parseUint16Array(data) {
  481. const length = await parseValue(data);
  482. const array = await data.consume(length * 2);
  483. return new Uint16Array(array.buffer);
  484. }
  485. async function parseInt16Array(data) {
  486. const length = await parseValue(data);
  487. const array = await data.consume(length * 2);
  488. return new Int16Array(array.buffer);
  489. }
  490. async function parseUint8ClampedArray(data) {
  491. const length = await parseValue(data);
  492. const array = await data.consume(length);
  493. return new Uint8ClampedArray(array.buffer);
  494. }
  495. async function parseUint8Array(data) {
  496. const length = await parseValue(data);
  497. const array = await data.consume(length);
  498. return array;
  499. }
  500. async function parseInt8Array(data) {
  501. const length = await parseValue(data);
  502. const array = await data.consume(length);
  503. return new Int8Array(array.buffer);
  504. }
  505. async function parseArrayBuffer(data) {
  506. const length = await parseValue(data);
  507. const array = await data.consume(length);
  508. return array.buffer;
  509. }
  510. async function parseNumber(data) {
  511. const array = await data.consume(8);
  512. return new Float64Array(array.buffer)[0];
  513. }
  514. async function parseUint32(data) {
  515. const array = await data.consume(4);
  516. return new Uint32Array(array.buffer)[0];
  517. }
  518. async function parseInt32(data) {
  519. const array = await data.consume(4);
  520. return new Int32Array(array.buffer)[0];
  521. }
  522. async function parseUint16(data) {
  523. const array = await data.consume(2);
  524. return new Uint16Array(array.buffer)[0];
  525. }
  526. async function parseInt16(data) {
  527. const array = await data.consume(2);
  528. return new Int16Array(array.buffer)[0];
  529. }
  530. async function parseUint8(data) {
  531. const array = await data.consume(1);
  532. return new Uint8Array(array.buffer)[0];
  533. }
  534. async function parseInt8(data) {
  535. const array = await data.consume(1);
  536. return new Int8Array(array.buffer)[0];
  537. }
  538. function parseUndefined() {
  539. return undefined;
  540. }
  541. function parseNull() {
  542. return null;
  543. }
  544. function parseNaN() {
  545. return NaN;
  546. }
  547. async function parseBoolean(data) {
  548. const array = await data.consume(1);
  549. return Boolean(array[0]);
  550. }
  551. async function parseMap(data) {
  552. const size = await parseValue(data);
  553. const map = new Map();
  554. if (size) {
  555. await parseNextEntry();
  556. }
  557. return map;
  558. async function parseNextEntry(indexKey = 0) {
  559. const key = await parseValue(data);
  560. const value = await parseValue(data);
  561. data.setObject([key, value], (key, value) => map.set(key, value));
  562. if (indexKey < size - 1) {
  563. await parseNextEntry(indexKey + 1);
  564. }
  565. }
  566. }
  567. async function parseSet(data) {
  568. const size = await parseValue(data);
  569. const set = new Set();
  570. if (size) {
  571. await parseNextEntry();
  572. }
  573. return set;
  574. async function parseNextEntry(indexKey = 0) {
  575. const value = await parseValue(data);
  576. data.setObject([value], value => set.add(value));
  577. if (indexKey < size - 1) {
  578. await parseNextEntry(indexKey + 1);
  579. }
  580. }
  581. }
  582. async function parseDate(data) {
  583. const milliseconds = await parseNumber(data);
  584. return new Date(milliseconds);
  585. }
  586. async function parseError(data) {
  587. const message = await parseString(data);
  588. const stack = await parseString(data);
  589. const error = new Error(message);
  590. error.stack = stack;
  591. return error;
  592. }
  593. async function parseRegExp(data) {
  594. const source = await parseString(data);
  595. const flags = await parseString(data);
  596. return new RegExp(source, flags);
  597. }
  598. async function parseStringObject(data) {
  599. return new String(await parseString(data));
  600. }
  601. async function parseNumberObject(data) {
  602. return new Number(await parseNumber(data));
  603. }
  604. async function parseBooleanObject(data) {
  605. return new Boolean(await parseBoolean(data));
  606. }
  607. async function parseSymbol(data) {
  608. const description = await parseString(data);
  609. return Symbol(description);
  610. }
  611. function testCircularReference(value, data) {
  612. return testObject(value) && data.objects.includes(value);
  613. }
  614. function testReference(value) {
  615. return value instanceof Reference;
  616. }
  617. function testObject(value) {
  618. return value === Object(value);
  619. }
  620. function testArray(value) {
  621. return typeof value.length == "number";
  622. }
  623. function testEmptySlot(value) {
  624. return value === EMPTY_SLOT_VALUE;
  625. }
  626. function testString(value) {
  627. return typeof value == "string";
  628. }
  629. function testFloat64Array(value) {
  630. return value.constructor.name == "Float64Array";
  631. }
  632. function testUint32Array(value) {
  633. return value.constructor.name == "Uint32Array";
  634. }
  635. function testInt32Array(value) {
  636. return value.constructor.name == "Int32Array";
  637. }
  638. function testUint16Array(value) {
  639. return value.constructor.name == "Uint16Array";
  640. }
  641. function testFloat32Array(value) {
  642. return value.constructor.name == "Float32Array";
  643. }
  644. function testInt16Array(value) {
  645. return value.constructor.name == "Int16Array";
  646. }
  647. function testUint8ClampedArray(value) {
  648. return value.constructor.name == "Uint8ClampedArray";
  649. }
  650. function testUint8Array(value) {
  651. return value.constructor.name == "Uint8Array";
  652. }
  653. function testInt8Array(value) {
  654. return value.constructor.name == "Int8Array";
  655. }
  656. function testArrayBuffer(value) {
  657. return value.constructor.name == "ArrayBuffer";
  658. }
  659. function testNumber(value) {
  660. return typeof value == "number";
  661. }
  662. function testUint32(value) {
  663. return testInteger(value) && value >= 0 && value <= 4294967295;
  664. }
  665. function testInt32(value) {
  666. return testInteger(value) && value >= -2147483648 && value <= 2147483647;
  667. }
  668. function testUint16(value) {
  669. return testInteger(value) && value >= 0 && value <= 65535;
  670. }
  671. function testInt16(value) {
  672. return testInteger(value) && value >= -32768 && value <= 32767;
  673. }
  674. function testUint8(value) {
  675. return testInteger(value) && value >= 0 && value <= 255;
  676. }
  677. function testInt8(value) {
  678. return testInteger(value) && value >= -128 && value <= 127;
  679. }
  680. function testInteger(value) {
  681. return testNumber(value) && Number.isInteger(value);
  682. }
  683. function testUndefined(value) {
  684. return value === undefined;
  685. }
  686. function testNull(value) {
  687. return value === null;
  688. }
  689. function testNaN(value) {
  690. return Number.isNaN(value);
  691. }
  692. function testBoolean(value) {
  693. return typeof value == "boolean";
  694. }
  695. function testMap(value) {
  696. return value instanceof Map;
  697. }
  698. function testSet(value) {
  699. return value instanceof Set;
  700. }
  701. function testDate(value) {
  702. return value instanceof Date;
  703. }
  704. function testError(value) {
  705. return value instanceof Error;
  706. }
  707. function testRegExp(value) {
  708. return value instanceof RegExp;
  709. }
  710. function testStringObject(value) {
  711. return value instanceof String;
  712. }
  713. function testNumberObject(value) {
  714. return value instanceof Number;
  715. }
  716. function testBooleanObject(value) {
  717. return value instanceof Boolean;
  718. }
  719. function testSymbol(value) {
  720. return typeof value == "symbol";
  721. }
  722. function testReferenceable(value) {
  723. return testObject(value) || testSymbol(value);
  724. }
  725. /*
  726. * Copyright 2010-2020 Gildas Lormeau
  727. * contact : gildas.lormeau <at> gmail.com
  728. *
  729. * This file is part of SingleFile.
  730. *
  731. * The code in this file is free software: you can redistribute it and/or
  732. * modify it under the terms of the GNU Affero General Public License
  733. * (GNU AGPL) as published by the Free Software Foundation, either version 3
  734. * of the License, or (at your option) any later version.
  735. *
  736. * The code in this file is distributed in the hope that it will be useful,
  737. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  738. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
  739. * General Public License for more details.
  740. *
  741. * As additional permission under GNU AGPL version 3 section 7, you may
  742. * distribute UNMODIFIED VERSIONS OF THIS file without the copy of the GNU
  743. * AGPL normally required by section 4, provided you include this license
  744. * notice and a URL through which recipients can access the Corresponding
  745. * Source.
  746. */
  747. /* global document, globalThis, getComputedStyle, FileReader, Image, OffscreenCanvas, createImageBitmap */
  748. const singlefile$2 = globalThis.singlefile;
  749. const CLOSE_ICON = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAABhmlDQ1BJQ0MgcHJvZmlsZQAAKJF9kT1Iw0AYht+mSlUqHewg4hChOogFURFHqWIRLJS2QqsOJpf+CE0akhQXR8G14ODPYtXBxVlXB1dBEPwBcXNzUnSREr9LCi1ivOO4h/e+9+XuO0Col5lqdowDqmYZqXhMzOZWxMAruhGiOYohiZl6Ir2Qgef4uoeP73dRnuVd9+foVfImA3wi8SzTDYt4nXh609I57xOHWUlSiM+Jxwy6IPEj12WX3zgXHRZ4ZtjIpOaIw8RisY3lNmYlQyWeIo4oqkb5QtZlhfMWZ7VcZc178hcG89pymuu0BhHHIhJIQoSMKjZQhoUo7RopJlJ0HvPwDzj+JLlkcm2AkWMeFaiQHD/4H/zurVmYnHCTgjGg88W2P4aBwC7QqNn297FtN04A/zNwpbX8lTow80l6raVFjoDQNnBx3dLkPeByB+h/0iVDciQ/LaFQAN7P6JtyQN8t0LPq9q15jtMHIEO9WroBDg6BkSJlr3m8u6u9b//WNPv3A6mTcr3f/E/sAAAABmJLR0QAigCKAIrj2uckAAAACXBIWXMAAC4jAAAuIwF4pT92AAAAB3RJTUUH5QkPDysvCdPVuwAAABl0RVh0Q29tbWVudABDcmVhdGVkIHdpdGggR0lNUFeBDhcAAAELSURBVHja7ZpLFsIwDAPj3v/OsGHDe1BIa8tKO7Mnlkw+dpoxAAAAAGCfx4ur6Yx/B337UUS4mp/VuWUEcjSfOgO+BXCZCWe0hSqQo/npBLglIUNLdAV2MH84Ad1JyIwdLkK6YoabIHWscBWmihHuAqvHtv+XqmdXOK9TxdKy3axUm2vZkXXGgPJksTuz1bVFeeU2Y6ijsLIpXbtKa1kDs2ews69o7+A+ihJ2lvI+/lcS1G21zUVG18XKNm4OS4BNkGOQQohSmGaIdpgLESvzyiRwKepsXjE2H0ZWMF8Zi4+jK5mviM0DiRXNZ2rhkdTK5jO0xermz2o8dCnq+FS2XNNVH0sDAAAA3JYnre9cH8BZmhEAAAAASUVORK5CYII=";
  750. const SINGLE_FILE_UI_ELEMENT_CLASS$1 = singlefile$2.helper.SINGLE_FILE_UI_ELEMENT_CLASS;
  751. const ERROR_BAR_TAGNAME = "singlefile-error-bar";
  752. const OPEN_FILE_BAR_TAGNAME = "singlefile-open-file-bar";
  753. const SHARE_PAGE_BAR_TAGNAME = "singlefile-share-page-bar";
  754. let EMBEDDED_IMAGE_BUTTON_MESSAGE$2, SHARE_PAGE_BUTTON_MESSAGE$2, SHARE_SELECTION_BUTTON_MESSAGE$2, ERROR_TITLE_MESSAGE$2;
  755. const CSS_PROPERTIES$1 = new Set(Array.from(getComputedStyle(document.documentElement)));
  756. function setLabels(labels) {
  757. ({ EMBEDDED_IMAGE_BUTTON_MESSAGE: EMBEDDED_IMAGE_BUTTON_MESSAGE$2, SHARE_PAGE_BUTTON_MESSAGE: SHARE_PAGE_BUTTON_MESSAGE$2, SHARE_SELECTION_BUTTON_MESSAGE: SHARE_SELECTION_BUTTON_MESSAGE$2, ERROR_TITLE_MESSAGE: ERROR_TITLE_MESSAGE$2 } = labels);
  758. }
  759. function onError(message, link) {
  760. console.error("SingleFile", message, link); // eslint-disable-line no-console
  761. displayBar(ERROR_BAR_TAGNAME, ERROR_TITLE_MESSAGE$2 + message, { link });
  762. }
  763. function getOpenFileBar() {
  764. let resolvePromise;
  765. return {
  766. display: async function () {
  767. return new Promise(resolve => {
  768. resolvePromise = resolve;
  769. displayBar(OPEN_FILE_BAR_TAGNAME, "", { buttonLabel: EMBEDDED_IMAGE_BUTTON_MESSAGE$2, buttonOnclick: resolve });
  770. });
  771. },
  772. hide: function () {
  773. const barElement = document.querySelector(OPEN_FILE_BAR_TAGNAME);
  774. if (barElement) {
  775. barElement.remove();
  776. }
  777. },
  778. cancel: function () {
  779. this.hide();
  780. if (resolvePromise) {
  781. resolvePromise(true);
  782. }
  783. }
  784. };
  785. }
  786. function getSharePageBar() {
  787. let resolvePromise;
  788. return {
  789. display: async function (selectedContent) {
  790. return new Promise(resolve => {
  791. resolvePromise = resolve;
  792. displayBar(SHARE_PAGE_BAR_TAGNAME, "", {
  793. buttonLabel: selectedContent ? SHARE_SELECTION_BUTTON_MESSAGE$2 : SHARE_PAGE_BUTTON_MESSAGE$2,
  794. buttonOnclick: resolve
  795. });
  796. });
  797. },
  798. hide: function () {
  799. const barElement = document.querySelector(SHARE_PAGE_BAR_TAGNAME);
  800. if (barElement) {
  801. barElement.remove();
  802. }
  803. },
  804. cancel: function () {
  805. this.hide();
  806. if (resolvePromise) {
  807. resolvePromise(true);
  808. }
  809. }
  810. };
  811. }
  812. function openFile({ accept } = { accept: "image/*" }) {
  813. const inputElement = document.createElement("input");
  814. inputElement.type = "file";
  815. inputElement.accept = accept;
  816. inputElement.click();
  817. return new Promise(resolve => {
  818. inputElement.addEventListener("change", async event => {
  819. if (event.target.files.length) {
  820. const file = event.target.files[0];
  821. let mimeType = file.type;
  822. if (mimeType == "image/png") {
  823. const fileReader = new FileReader();
  824. fileReader.addEventListener("load", async () => resolve(new Uint8Array(fileReader.result)));
  825. fileReader.addEventListener("error", () => resolve());
  826. fileReader.readAsArrayBuffer(file);
  827. } else {
  828. const dataURI = await new Promise(resolve => {
  829. const fileReader = new FileReader();
  830. fileReader.addEventListener("load", () => resolve(fileReader.result));
  831. fileReader.addEventListener("error", () => resolve());
  832. fileReader.readAsDataURL(file);
  833. });
  834. if (dataURI) {
  835. const imageBitmap = await createImageBitmap(file);
  836. const image = new Image();
  837. image.src = dataURI;
  838. image.addEventListener("error", () => resolve());
  839. await new Promise(resolve => image.addEventListener("load", resolve));
  840. const canvas = new OffscreenCanvas(image.width, image.height);
  841. const context = canvas.getContext("2d");
  842. context.drawImage(imageBitmap, 0, 0);
  843. const blob = await canvas.convertToBlob({ type: "image/png" });
  844. const fileReader = new FileReader();
  845. fileReader.addEventListener("load", () => resolve(new Uint8Array(fileReader.result)));
  846. fileReader.addEventListener("error", () => resolve());
  847. fileReader.readAsArrayBuffer(blob);
  848. } else {
  849. resolve();
  850. }
  851. }
  852. } else {
  853. resolve();
  854. }
  855. });
  856. inputElement.addEventListener("cancel", () => resolve());
  857. });
  858. }
  859. function displayBar(tagName, message, { link, buttonLabel, buttonOnclick } = {}) {
  860. try {
  861. const barElement = document.querySelector(tagName);
  862. if (!barElement) {
  863. const barElement = createElement$1(tagName);
  864. const shadowRoot = barElement.attachShadow({ mode: "open" });
  865. const styleElement = document.createElement("style");
  866. styleElement.textContent = `
  867. .container {
  868. background-color: #ff6c00;
  869. color: white;
  870. display: flex;
  871. position: fixed;
  872. top: 0px;
  873. left: 0px;
  874. right: 0px;
  875. height: auto;
  876. width: auto;
  877. min-height: 24px;
  878. min-width: 24px;
  879. z-index: 2147483647;
  880. margin: 0;
  881. padding: 2px;
  882. font-family: Arial;
  883. }
  884. .singlefile-open-file-bar.container, .singlefile-share-page-bar.container {
  885. background-color: gainsboro;
  886. border-block-end: gray 1px solid;
  887. }
  888. .text {
  889. flex: 1;
  890. padding-top: 4px;
  891. padding-bottom: 4px;
  892. padding-left: 8px;
  893. }
  894. button {
  895. background-color: grey;
  896. color: white;
  897. border: 1px solid darkgrey;
  898. padding: 3px;
  899. padding-left: 8px;
  900. padding-right: 8px;
  901. border-radius: 4px;
  902. cursor: pointer;
  903. }
  904. .close-button {
  905. opacity: .7;
  906. padding-left: 8px;
  907. padding-right: 8px;
  908. cursor: pointer;
  909. transition: opacity 250ms;
  910. height: 16px;
  911. font-size: .8rem;
  912. align-self: center;
  913. }
  914. .singlefile-open-file-bar button, .singlefile-share-page-bar button{
  915. background-color: dimgrey;
  916. }
  917. .singlefile-open-file-bar .close-button, .singlefile-share-page-bar .close-button{
  918. filter: invert(1);
  919. }
  920. a {
  921. color: #303036;
  922. }
  923. .close-button:hover {
  924. opacity: 1;
  925. }
  926. `;
  927. shadowRoot.appendChild(styleElement);
  928. const containerElement = document.createElement("div");
  929. containerElement.classList.add(tagName);
  930. containerElement.classList.add("container");
  931. const textElement = document.createElement("span");
  932. textElement.classList.add("text");
  933. const content = message.split("__DOC_LINK__");
  934. textElement.textContent = content[0];
  935. if (link && content.length == 2) {
  936. const linkElement = document.createElement("a");
  937. linkElement.textContent = link;
  938. linkElement.href = link;
  939. linkElement.target = "_blank";
  940. textElement.appendChild(linkElement);
  941. textElement.appendChild(document.createTextNode(content[1]));
  942. }
  943. if (buttonLabel && buttonOnclick) {
  944. const buttonElement = document.createElement("button");
  945. buttonElement.textContent = buttonLabel;
  946. buttonElement.onclick = () => buttonOnclick();
  947. textElement.appendChild(buttonElement);
  948. }
  949. containerElement.appendChild(textElement);
  950. const closeElement = document.createElement("img");
  951. closeElement.classList.add("close-button");
  952. containerElement.appendChild(closeElement);
  953. shadowRoot.appendChild(containerElement);
  954. closeElement.src = CLOSE_ICON;
  955. closeElement.onclick = event => {
  956. if (event.button === 0) {
  957. if (buttonOnclick) {
  958. buttonOnclick(true);
  959. }
  960. barElement.remove();
  961. }
  962. };
  963. document.documentElement.appendChild(barElement);
  964. }
  965. } catch (error) {
  966. // iignored
  967. }
  968. }
  969. function createElement$1(tagName, parentElement) {
  970. const element = document.createElement(tagName);
  971. element.className = SINGLE_FILE_UI_ELEMENT_CLASS$1;
  972. if (parentElement) {
  973. parentElement.appendChild(element);
  974. }
  975. CSS_PROPERTIES$1.forEach(property => element.style.setProperty(property, "initial", "important"));
  976. return element;
  977. }
  978. /*
  979. * Copyright 2010-2020 Gildas Lormeau
  980. * contact : gildas.lormeau <at> gmail.com
  981. *
  982. * This file is part of SingleFile.
  983. *
  984. * The code in this file is free software: you can redistribute it and/or
  985. * modify it under the terms of the GNU Affero General Public License
  986. * (GNU AGPL) as published by the Free Software Foundation, either version 3
  987. * of the License, or (at your option) any later version.
  988. *
  989. * The code in this file is distributed in the hope that it will be useful,
  990. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  991. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
  992. * General Public License for more details.
  993. *
  994. * As additional permission under GNU AGPL version 3 section 7, you may
  995. * distribute UNMODIFIED VERSIONS OF THIS file without the copy of the GNU
  996. * AGPL normally required by section 4, provided you include this license
  997. * notice and a URL through which recipients can access the Corresponding
  998. * Source.
  999. */
  1000. const MAX_CONTENT_SIZE = 16 * (1024 * 1024);
  1001. let EMBEDDED_IMAGE_BUTTON_MESSAGE$1, SHARE_PAGE_BUTTON_MESSAGE$1, SHARE_SELECTION_BUTTON_MESSAGE$1, ERROR_TITLE_MESSAGE$1;
  1002. try {
  1003. EMBEDDED_IMAGE_BUTTON_MESSAGE$1 = browser.i18n.getMessage("topPanelEmbeddedImageButton");
  1004. SHARE_PAGE_BUTTON_MESSAGE$1 = browser.i18n.getMessage("topPanelSharePageButton");
  1005. SHARE_SELECTION_BUTTON_MESSAGE$1 = browser.i18n.getMessage("topPanelShareSelectionButton");
  1006. ERROR_TITLE_MESSAGE$1 = browser.i18n.getMessage("topPanelError");
  1007. } catch (error) {
  1008. // ignored
  1009. }
  1010. let sharePageBar;
  1011. setLabels({
  1012. EMBEDDED_IMAGE_BUTTON_MESSAGE: EMBEDDED_IMAGE_BUTTON_MESSAGE$1,
  1013. SHARE_PAGE_BUTTON_MESSAGE: SHARE_PAGE_BUTTON_MESSAGE$1,
  1014. SHARE_SELECTION_BUTTON_MESSAGE: SHARE_SELECTION_BUTTON_MESSAGE$1,
  1015. ERROR_TITLE_MESSAGE: ERROR_TITLE_MESSAGE$1
  1016. });
  1017. async function downloadPage(pageData, options) {
  1018. if (options.includeBOM) {
  1019. pageData.content = "\ufeff" + pageData.content;
  1020. }
  1021. const embeddedImage = options.embeddedImage;
  1022. const message = {
  1023. method: "downloads.download",
  1024. taskId: options.taskId,
  1025. insertTextBody: options.insertTextBody,
  1026. confirmFilename: options.confirmFilename,
  1027. filenameConflictAction: options.filenameConflictAction,
  1028. filename: pageData.filename,
  1029. mimeType: pageData.mimeType,
  1030. saveToClipboard: options.saveToClipboard,
  1031. saveToGDrive: options.saveToGDrive,
  1032. saveToDropbox: options.saveToDropbox,
  1033. saveWithWebDAV: options.saveWithWebDAV,
  1034. webDAVURL: options.webDAVURL,
  1035. webDAVUser: options.webDAVUser,
  1036. webDAVPassword: options.webDAVPassword,
  1037. saveToGitHub: options.saveToGitHub,
  1038. githubToken: options.githubToken,
  1039. githubUser: options.githubUser,
  1040. githubRepository: options.githubRepository,
  1041. githubBranch: options.githubBranch,
  1042. saveWithCompanion: options.saveWithCompanion,
  1043. forceWebAuthFlow: options.forceWebAuthFlow,
  1044. filenameReplacementCharacter: options.filenameReplacementCharacter,
  1045. openEditor: options.openEditor,
  1046. openSavedPage: options.openSavedPage,
  1047. compressHTML: options.compressHTML,
  1048. backgroundSave: options.backgroundSave,
  1049. bookmarkId: options.bookmarkId,
  1050. replaceBookmarkURL: options.replaceBookmarkURL,
  1051. applySystemTheme: options.applySystemTheme,
  1052. defaultEditorMode: options.defaultEditorMode,
  1053. includeInfobar: options.includeInfobar,
  1054. warnUnsavedPage: options.warnUnsavedPage,
  1055. createRootDirectory: options.createRootDirectory,
  1056. selfExtractingArchive: options.selfExtractingArchive,
  1057. embeddedImage: embeddedImage ? Array.from(embeddedImage) : null,
  1058. preventAppendedData: options.preventAppendedData,
  1059. extractDataFromPage: options.extractDataFromPage,
  1060. insertCanonicalLink: options.insertCanonicalLink,
  1061. insertMetaNoIndex: options.insertMetaNoIndex,
  1062. insertMetaCSP: options.insertMetaCSP,
  1063. password: options.password,
  1064. compressContent: options.compressContent,
  1065. foregroundSave: options.foregroundSave,
  1066. sharePage: options.sharePage,
  1067. saveToRestFormApi: options.saveToRestFormApi,
  1068. saveToRestFormApiUrl: options.saveToRestFormApiUrl,
  1069. saveToRestFormApiFileFieldName: options.saveToRestFormApiFileFieldName,
  1070. saveToRestFormApiUrlFieldName: options.saveToRestFormApiUrlFieldName,
  1071. saveToRestFormApiToken: options.saveToRestFormApiToken,
  1072. };
  1073. if (options.compressContent) {
  1074. const blob = new Blob([await serialize(pageData)], { type: pageData.mimeType });
  1075. const blobURL = URL.createObjectURL(blob);
  1076. message.blobURL = blobURL;
  1077. const result = await browser.runtime.sendMessage(message);
  1078. URL.revokeObjectURL(blobURL);
  1079. if (result.error) {
  1080. message.embeddedImage = embeddedImage;
  1081. message.blobURL = null;
  1082. message.pageData = pageData;
  1083. let data, indexData = 0;
  1084. const dataArray = await serialize(message);
  1085. do {
  1086. data = Array.from(dataArray.slice(indexData, indexData + MAX_CONTENT_SIZE));
  1087. indexData += MAX_CONTENT_SIZE;
  1088. await browser.runtime.sendMessage({
  1089. method: "downloads.download",
  1090. compressContent: true,
  1091. data
  1092. });
  1093. } while (data.length);
  1094. await browser.runtime.sendMessage({
  1095. method: "downloads.download",
  1096. compressContent: true,
  1097. mimeType: pageData.mimeType
  1098. });
  1099. }
  1100. if (options.backgroundSave) {
  1101. await browser.runtime.sendMessage({ method: "downloads.end", taskId: options.taskId });
  1102. }
  1103. } else {
  1104. if ((options.backgroundSave && !options.sharePage) || options.openEditor || options.saveToGDrive || options.saveToGitHub || options.saveWithCompanion || options.saveWithWebDAV || options.saveToDropbox || options.saveToRestFormApi) {
  1105. const blobURL = URL.createObjectURL(new Blob([pageData.content], { type: pageData.mimeType }));
  1106. message.blobURL = blobURL;
  1107. const result = await browser.runtime.sendMessage(message);
  1108. URL.revokeObjectURL(blobURL);
  1109. if (result.error) {
  1110. message.blobURL = null;
  1111. for (let blockIndex = 0; blockIndex * MAX_CONTENT_SIZE < pageData.content.length; blockIndex++) {
  1112. message.truncated = pageData.content.length > MAX_CONTENT_SIZE;
  1113. if (message.truncated) {
  1114. message.finished = (blockIndex + 1) * MAX_CONTENT_SIZE > pageData.content.length;
  1115. message.content = pageData.content.substring(blockIndex * MAX_CONTENT_SIZE, (blockIndex + 1) * MAX_CONTENT_SIZE);
  1116. } else {
  1117. message.content = pageData.content;
  1118. }
  1119. await browser.runtime.sendMessage(message);
  1120. }
  1121. }
  1122. } else {
  1123. if (options.saveToClipboard) {
  1124. saveToClipboard(pageData);
  1125. } else {
  1126. await downloadPageForeground(pageData, options);
  1127. }
  1128. if (options.openSavedPage) {
  1129. open(URL.createObjectURL(new Blob([pageData.content], { type: pageData.mimeType })));
  1130. }
  1131. browser.runtime.sendMessage({ method: "ui.processEnd" });
  1132. }
  1133. await browser.runtime.sendMessage({ method: "downloads.end", taskId: options.taskId, hash: pageData.hash, woleetKey: options.woleetKey });
  1134. }
  1135. }
  1136. async function downloadPageForeground(pageData, options) {
  1137. if (Array.isArray(pageData.content)) {
  1138. pageData.content = new Uint8Array(pageData.content);
  1139. }
  1140. if (options.sharePage && navigator.share) {
  1141. await sharePage(pageData, options);
  1142. } else {
  1143. if (pageData.filename && pageData.filename.length) {
  1144. const link = document.createElement("a");
  1145. link.download = pageData.filename;
  1146. link.href = URL.createObjectURL(new Blob([pageData.content], { type: pageData.mimeType }));
  1147. link.dispatchEvent(new MouseEvent("click"));
  1148. return new Promise(resolve => setTimeout(() => { URL.revokeObjectURL(link.href); resolve(); }, 1000));
  1149. }
  1150. }
  1151. }
  1152. async function sharePage(pageData, options) {
  1153. sharePageBar = getSharePageBar();
  1154. const cancelled = await sharePageBar.display(options.selected);
  1155. if (!cancelled) {
  1156. const data = { files: [new File([pageData.content], pageData.filename, { type: pageData.mimeType })] };
  1157. try {
  1158. await navigator.share(data);
  1159. sharePageBar.hide();
  1160. } catch (error) {
  1161. sharePageBar.hide();
  1162. if (error.name === "AbortError") {
  1163. await sharePage(pageData, options);
  1164. } else {
  1165. throw error;
  1166. }
  1167. }
  1168. }
  1169. }
  1170. function saveToClipboard(pageData) {
  1171. const command = "copy";
  1172. document.addEventListener(command, listener);
  1173. document.execCommand(command);
  1174. document.removeEventListener(command, listener);
  1175. function listener(event) {
  1176. event.clipboardData.setData(pageData.mimeType, pageData.content);
  1177. event.clipboardData.setData("text/plain", pageData.content);
  1178. event.preventDefault();
  1179. }
  1180. }
  1181. /*
  1182. * Copyright 2010-2020 Gildas Lormeau
  1183. * contact : gildas.lormeau <at> gmail.com
  1184. *
  1185. * This file is part of SingleFile.
  1186. *
  1187. * The code in this file is free software: you can redistribute it and/or
  1188. * modify it under the terms of the GNU Affero General Public License
  1189. * (GNU AGPL) as published by the Free Software Foundation, either version 3
  1190. * of the License, or (at your option) any later version.
  1191. *
  1192. * The code in this file is distributed in the hope that it will be useful,
  1193. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  1194. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
  1195. * General Public License for more details.
  1196. *
  1197. * As additional permission under GNU AGPL version 3 section 7, you may
  1198. * distribute UNMODIFIED VERSIONS OF THIS file without the copy of the GNU
  1199. * AGPL normally required by section 4, provided you include this license
  1200. * notice and a URL through which recipients can access the Corresponding
  1201. * Source.
  1202. */
  1203. /* global browser, window, document, CustomEvent, setTimeout, clearTimeout */
  1204. const FETCH_REQUEST_EVENT = "single-file-request-fetch";
  1205. const FETCH_ACK_EVENT = "single-file-ack-fetch";
  1206. const FETCH_RESPONSE_EVENT = "single-file-response-fetch";
  1207. const ERR_HOST_FETCH = "Host fetch error (SingleFile)";
  1208. const HOST_FETCH_MAX_DELAY = 2500;
  1209. const USE_HOST_FETCH = Boolean(window.wrappedJSObject);
  1210. const fetch = (url, options) => window.fetch(url, options);
  1211. let requestId = 0, pendingResponses = new Map();
  1212. browser.runtime.onMessage.addListener(message => {
  1213. if (message.method == "singlefile.fetchFrame" && window.frameId && window.frameId == message.frameId) {
  1214. return onFetchFrame(message);
  1215. }
  1216. if (message.method == "singlefile.fetchResponse") {
  1217. return onFetchResponse(message);
  1218. }
  1219. });
  1220. async function onFetchFrame(message) {
  1221. try {
  1222. const response = await fetch(message.url, { cache: "force-cache", headers: message.headers });
  1223. return {
  1224. status: response.status,
  1225. headers: [...response.headers],
  1226. array: Array.from(new Uint8Array(await response.arrayBuffer()))
  1227. };
  1228. } catch (error) {
  1229. return {
  1230. error: error && error.toString()
  1231. };
  1232. }
  1233. }
  1234. async function onFetchResponse(message) {
  1235. const pendingResponse = pendingResponses.get(message.requestId);
  1236. if (pendingResponse) {
  1237. if (message.error) {
  1238. pendingResponse.reject(new Error(message.error));
  1239. pendingResponses.delete(message.requestId);
  1240. } else {
  1241. if (message.truncated) {
  1242. if (pendingResponse.array) {
  1243. pendingResponse.array = pendingResponse.array.concat(message.array);
  1244. } else {
  1245. pendingResponse.array = message.array;
  1246. pendingResponses.set(message.requestId, pendingResponse);
  1247. }
  1248. if (message.finished) {
  1249. message.array = pendingResponse.array;
  1250. }
  1251. }
  1252. if (!message.truncated || message.finished) {
  1253. pendingResponse.resolve({
  1254. status: message.status,
  1255. headers: { get: headerName => message.headers && message.headers[headerName] },
  1256. arrayBuffer: async () => new Uint8Array(message.array).buffer
  1257. });
  1258. pendingResponses.delete(message.requestId);
  1259. }
  1260. }
  1261. }
  1262. return {};
  1263. }
  1264. async function hostFetch(url, options) {
  1265. const result = new Promise((resolve, reject) => {
  1266. document.dispatchEvent(new CustomEvent(FETCH_REQUEST_EVENT, { detail: JSON.stringify({ url, options }) }));
  1267. document.addEventListener(FETCH_ACK_EVENT, onAckFetch, false);
  1268. document.addEventListener(FETCH_RESPONSE_EVENT, onResponseFetch, false);
  1269. const timeout = setTimeout(() => {
  1270. removeListeners();
  1271. reject(new Error(ERR_HOST_FETCH));
  1272. }, HOST_FETCH_MAX_DELAY);
  1273. function onResponseFetch(event) {
  1274. if (event.detail) {
  1275. if (event.detail.url == url) {
  1276. removeListeners();
  1277. if (event.detail.response) {
  1278. resolve({
  1279. status: event.detail.status,
  1280. headers: new Map(event.detail.headers),
  1281. arrayBuffer: async () => event.detail.response
  1282. });
  1283. } else {
  1284. reject(event.detail.error);
  1285. }
  1286. }
  1287. } else {
  1288. reject();
  1289. }
  1290. }
  1291. function onAckFetch() {
  1292. clearTimeout(timeout);
  1293. }
  1294. function removeListeners() {
  1295. document.removeEventListener(FETCH_RESPONSE_EVENT, onResponseFetch, false);
  1296. document.removeEventListener(FETCH_ACK_EVENT, onAckFetch, false);
  1297. }
  1298. });
  1299. try {
  1300. return await result;
  1301. } catch (error) {
  1302. if (error && error.message == ERR_HOST_FETCH) {
  1303. return fetch(url, options);
  1304. } else {
  1305. throw error;
  1306. }
  1307. }
  1308. }
  1309. async function fetchResource(url, options = {}) {
  1310. try {
  1311. const fetchOptions = { cache: "force-cache", headers: options.headers };
  1312. return await (options.referrer && USE_HOST_FETCH ? hostFetch(url, fetchOptions) : fetch(url, fetchOptions));
  1313. }
  1314. catch (error) {
  1315. requestId++;
  1316. const promise = new Promise((resolve, reject) => pendingResponses.set(requestId, { resolve, reject }));
  1317. await sendMessage({ method: "singlefile.fetch", url, requestId, referrer: options.referrer, headers: options.headers });
  1318. return promise;
  1319. }
  1320. }
  1321. async function frameFetch(url, options) {
  1322. const response = await sendMessage({ method: "singlefile.fetchFrame", url, frameId: options.frameId, referrer: options.referrer, headers: options.headers });
  1323. return {
  1324. status: response.status,
  1325. headers: new Map(response.headers),
  1326. arrayBuffer: async () => new Uint8Array(response.array).buffer
  1327. };
  1328. }
  1329. async function sendMessage(message) {
  1330. const response = await browser.runtime.sendMessage(message);
  1331. if (!response || response.error) {
  1332. throw new Error(response && response.error && response.error.toString());
  1333. } else {
  1334. return response;
  1335. }
  1336. }
  1337. /*
  1338. * Copyright 2010-2020 Gildas Lormeau
  1339. * contact : gildas.lormeau <at> gmail.com
  1340. *
  1341. * This file is part of SingleFile.
  1342. *
  1343. * The code in this file is free software: you can redistribute it and/or
  1344. * modify it under the terms of the GNU Affero General Public License
  1345. * (GNU AGPL) as published by the Free Software Foundation, either version 3
  1346. * of the License, or (at your option) any later version.
  1347. *
  1348. * The code in this file is distributed in the hope that it will be useful,
  1349. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  1350. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
  1351. * General Public License for more details.
  1352. *
  1353. * As additional permission under GNU AGPL version 3 section 7, you may
  1354. * distribute UNMODIFIED VERSIONS OF THIS file without the copy of the GNU
  1355. * AGPL normally required by section 4, provided you include this license
  1356. * notice and a URL through which recipients can access the Corresponding
  1357. * Source.
  1358. */
  1359. /* global browser, document, globalThis, prompt, getComputedStyle, addEventListener, removeEventListener, requestAnimationFrame, setTimeout, getSelection, Node */
  1360. const singlefile$1 = globalThis.singlefile;
  1361. const SELECTED_CONTENT_ATTRIBUTE_NAME = singlefile$1.helper.SELECTED_CONTENT_ATTRIBUTE_NAME;
  1362. const MASK_TAGNAME = "singlefile-mask";
  1363. const MASK_CONTENT_CLASSNAME = "singlefile-mask-content";
  1364. const PROGRESSBAR_CLASSNAME = "singlefile-progress-bar";
  1365. const PROGRESSBAR_CONTENT_CLASSNAME = "singlefile-progress-bar-content";
  1366. const SELECTION_ZONE_TAGNAME = "single-file-selection-zone";
  1367. const LOGS_WINDOW_TAGNAME = "singlefile-logs-window";
  1368. const LOGS_CLASSNAME = "singlefile-logs";
  1369. const LOGS_LINE_CLASSNAME = "singlefile-logs-line";
  1370. const LOGS_LINE_TEXT_ELEMENT_CLASSNAME = "singlefile-logs-line-text";
  1371. const LOGS_LINE_STATUS_ELEMENT_CLASSNAME = "singlefile-logs-line-icon";
  1372. const SINGLE_FILE_UI_ELEMENT_CLASS = singlefile$1.helper.SINGLE_FILE_UI_ELEMENT_CLASS;
  1373. const SELECT_PX_THRESHOLD = 8;
  1374. const LOG_PANEL_DEFERRED_IMAGES_MESSAGE = browser.i18n.getMessage("logPanelDeferredImages");
  1375. const LOG_PANEL_FRAME_CONTENTS_MESSAGE = browser.i18n.getMessage("logPanelFrameContents");
  1376. const LOG_PANEL_EMBEDDED_IMAGE_MESSAGE = browser.i18n.getMessage("logPanelEmbeddedImage");
  1377. const LOG_PANEL_STEP_MESSAGE = browser.i18n.getMessage("logPanelStep");
  1378. const LOG_PANEL_WIDTH = browser.i18n.getMessage("logPanelWidth");
  1379. const CSS_PROPERTIES = new Set(Array.from(getComputedStyle(document.documentElement)));
  1380. let selectedAreaElement, logsWindowElement;
  1381. createLogsWindowElement();
  1382. function promptMessage(message, defaultValue) {
  1383. return prompt(message, defaultValue);
  1384. }
  1385. function setVisible(visible) {
  1386. const maskElement = document.querySelector(MASK_TAGNAME);
  1387. if (maskElement) {
  1388. maskElement.style.setProperty("display", visible ? "block" : "none");
  1389. }
  1390. if (logsWindowElement) {
  1391. logsWindowElement.style.setProperty("display", visible ? "block" : "none");
  1392. }
  1393. }
  1394. function onStartPage(options) {
  1395. let maskElement = document.querySelector(MASK_TAGNAME);
  1396. if (!maskElement) {
  1397. if (options.logsEnabled) {
  1398. document.documentElement.appendChild(logsWindowElement);
  1399. }
  1400. if (options.shadowEnabled) {
  1401. const maskElement = createMaskElement();
  1402. if (options.progressBarEnabled) {
  1403. createProgressBarElement(maskElement);
  1404. }
  1405. }
  1406. }
  1407. }
  1408. function onEndPage() {
  1409. const maskElement = document.querySelector(MASK_TAGNAME);
  1410. if (maskElement) {
  1411. maskElement.remove();
  1412. }
  1413. logsWindowElement.remove();
  1414. clearLogs();
  1415. }
  1416. function onLoadResource(index, maxIndex, options) {
  1417. if (options.shadowEnabled && options.progressBarEnabled) {
  1418. updateProgressBar(index, maxIndex);
  1419. }
  1420. }
  1421. function onLoadingDeferResources(options) {
  1422. updateLog("load-deferred-images", LOG_PANEL_DEFERRED_IMAGES_MESSAGE, "…", options);
  1423. }
  1424. function onLoadDeferResources(options) {
  1425. updateLog("load-deferred-images", LOG_PANEL_DEFERRED_IMAGES_MESSAGE, "✓", options);
  1426. }
  1427. function onInsertingEmbeddedImage(options) {
  1428. updateLog("insert-embedded-image", LOG_PANEL_EMBEDDED_IMAGE_MESSAGE, "…", options);
  1429. }
  1430. function onInsertEmbeddedImage(options) {
  1431. updateLog("insert-embedded-image", LOG_PANEL_EMBEDDED_IMAGE_MESSAGE, "✓", options);
  1432. }
  1433. function onLoadingFrames(options) {
  1434. updateLog("load-frames", LOG_PANEL_FRAME_CONTENTS_MESSAGE, "…", options);
  1435. }
  1436. function onLoadFrames(options) {
  1437. updateLog("load-frames", LOG_PANEL_FRAME_CONTENTS_MESSAGE, "✓", options);
  1438. }
  1439. function onStartStage(step, options) {
  1440. updateLog("step-" + step, `${LOG_PANEL_STEP_MESSAGE} ${step + 1} / 3`, "…", options);
  1441. }
  1442. function onEndStage(step, options) {
  1443. updateLog("step-" + step, `${LOG_PANEL_STEP_MESSAGE} ${step + 1} / 3`, "✓", options);
  1444. }
  1445. function getSelectedLinks() {
  1446. let selectionFound;
  1447. const links = [];
  1448. const selection = getSelection();
  1449. for (let indexRange = 0; indexRange < selection.rangeCount; indexRange++) {
  1450. let range = selection.getRangeAt(indexRange);
  1451. if (range && range.commonAncestorContainer) {
  1452. const treeWalker = document.createTreeWalker(range.commonAncestorContainer);
  1453. let rangeSelectionFound = false;
  1454. let finished = false;
  1455. while (!finished) {
  1456. if (rangeSelectionFound || treeWalker.currentNode == range.startContainer || treeWalker.currentNode == range.endContainer) {
  1457. rangeSelectionFound = true;
  1458. if (range.startContainer != range.endContainer || range.startOffset != range.endOffset) {
  1459. selectionFound = true;
  1460. if (treeWalker.currentNode.tagName == "A" && treeWalker.currentNode.href) {
  1461. links.push(treeWalker.currentNode.href);
  1462. }
  1463. }
  1464. }
  1465. if (treeWalker.currentNode == range.endContainer) {
  1466. finished = true;
  1467. } else {
  1468. treeWalker.nextNode();
  1469. }
  1470. }
  1471. if (selectionFound && treeWalker.currentNode == range.endContainer && treeWalker.currentNode.querySelectorAll) {
  1472. treeWalker.currentNode.querySelectorAll("*").forEach(descendantElement => {
  1473. if (descendantElement.tagName == "A" && descendantElement.href) {
  1474. links.push(treeWalker.currentNode.href);
  1475. }
  1476. });
  1477. }
  1478. }
  1479. }
  1480. return Array.from(new Set(links));
  1481. }
  1482. async function markSelection(optionallySelected) {
  1483. let selectionFound = markSelectedContent();
  1484. if (selectionFound || optionallySelected) {
  1485. return selectionFound;
  1486. } else {
  1487. selectionFound = await selectArea();
  1488. if (selectionFound) {
  1489. return markSelectedContent();
  1490. }
  1491. }
  1492. }
  1493. function markSelectedContent() {
  1494. const selection = getSelection();
  1495. let selectionFound;
  1496. for (let indexRange = 0; indexRange < selection.rangeCount; indexRange++) {
  1497. let range = selection.getRangeAt(indexRange);
  1498. if (range && range.commonAncestorContainer) {
  1499. const treeWalker = document.createTreeWalker(range.commonAncestorContainer);
  1500. let rangeSelectionFound = false;
  1501. let finished = false;
  1502. while (!finished) {
  1503. if (rangeSelectionFound || treeWalker.currentNode == range.startContainer || treeWalker.currentNode == range.endContainer) {
  1504. rangeSelectionFound = true;
  1505. if (range.startContainer != range.endContainer || range.startOffset != range.endOffset) {
  1506. selectionFound = true;
  1507. markSelectedNode(treeWalker.currentNode);
  1508. }
  1509. }
  1510. if (selectionFound && treeWalker.currentNode == range.startContainer) {
  1511. markSelectedParents(treeWalker.currentNode);
  1512. }
  1513. if (treeWalker.currentNode == range.endContainer) {
  1514. finished = true;
  1515. } else {
  1516. treeWalker.nextNode();
  1517. }
  1518. }
  1519. if (selectionFound && treeWalker.currentNode == range.endContainer && treeWalker.currentNode.querySelectorAll) {
  1520. for (
  1521. let offset = range.startContainer === range.endContainer ? range.startOffset : 0;
  1522. offset < range.endOffset;
  1523. offset++
  1524. ) {
  1525. const node = range.endContainer.childNodes[offset];
  1526. if (node) {
  1527. markSelectedNode(node);
  1528. if (node.querySelectorAll) {
  1529. node.querySelectorAll("*").forEach(markSelectedNode);
  1530. }
  1531. }
  1532. }
  1533. }
  1534. }
  1535. }
  1536. return selectionFound;
  1537. }
  1538. function markSelectedNode(node) {
  1539. const element = node.nodeType == Node.ELEMENT_NODE ? node : node.parentElement;
  1540. element.setAttribute(SELECTED_CONTENT_ATTRIBUTE_NAME, "");
  1541. }
  1542. function markSelectedParents(node) {
  1543. if (node.parentElement) {
  1544. markSelectedNode(node);
  1545. markSelectedParents(node.parentElement);
  1546. }
  1547. }
  1548. function unmarkSelection() {
  1549. document.querySelectorAll("[" + SELECTED_CONTENT_ATTRIBUTE_NAME + "]").forEach(selectedContent => selectedContent.removeAttribute(SELECTED_CONTENT_ATTRIBUTE_NAME));
  1550. }
  1551. function selectArea() {
  1552. return new Promise(resolve => {
  1553. let selectedRanges = [];
  1554. addEventListener("mousemove", mousemoveListener, true);
  1555. addEventListener("click", clickListener, true);
  1556. addEventListener("keyup", keypressListener, true);
  1557. document.addEventListener("contextmenu", contextmenuListener, true);
  1558. getSelection().removeAllRanges();
  1559. function contextmenuListener(event) {
  1560. selectedRanges = [];
  1561. select();
  1562. event.preventDefault();
  1563. }
  1564. function mousemoveListener(event) {
  1565. const targetElement = getTarget(event);
  1566. if (targetElement) {
  1567. selectedAreaElement = targetElement;
  1568. moveAreaSelector(targetElement);
  1569. }
  1570. }
  1571. function clickListener(event) {
  1572. event.preventDefault();
  1573. event.stopPropagation();
  1574. if (event.button == 0) {
  1575. select(selectedAreaElement, event.ctrlKey);
  1576. } else {
  1577. cancel();
  1578. }
  1579. }
  1580. function keypressListener(event) {
  1581. if (event.key == "Escape") {
  1582. cancel();
  1583. }
  1584. }
  1585. function cancel() {
  1586. if (selectedRanges.length) {
  1587. getSelection().removeAllRanges();
  1588. }
  1589. selectedRanges = [];
  1590. cleanupAndResolve();
  1591. }
  1592. function select(selectedElement, multiSelect) {
  1593. if (selectedElement) {
  1594. if (!multiSelect) {
  1595. restoreSelectedRanges();
  1596. }
  1597. const range = document.createRange();
  1598. range.selectNodeContents(selectedElement);
  1599. cleanupSelectionRanges();
  1600. getSelection().addRange(range);
  1601. saveSelectedRanges();
  1602. if (!multiSelect) {
  1603. cleanupAndResolve();
  1604. }
  1605. } else {
  1606. cleanupAndResolve();
  1607. }
  1608. }
  1609. function cleanupSelectionRanges() {
  1610. const selection = getSelection();
  1611. for (let indexRange = selection.rangeCount - 1; indexRange >= 0; indexRange--) {
  1612. const range = selection.getRangeAt(indexRange);
  1613. if (range.startOffset == range.endOffset) {
  1614. selection.removeRange(range);
  1615. indexRange--;
  1616. }
  1617. }
  1618. }
  1619. function cleanupAndResolve() {
  1620. getAreaSelector().remove();
  1621. removeEventListener("mousemove", mousemoveListener, true);
  1622. removeEventListener("click", clickListener, true);
  1623. removeEventListener("keyup", keypressListener, true);
  1624. selectedAreaElement = null;
  1625. resolve(Boolean(selectedRanges.length));
  1626. setTimeout(() => document.removeEventListener("contextmenu", contextmenuListener, true), 0);
  1627. }
  1628. function restoreSelectedRanges() {
  1629. getSelection().removeAllRanges();
  1630. selectedRanges.forEach(range => getSelection().addRange(range));
  1631. }
  1632. function saveSelectedRanges() {
  1633. selectedRanges = [];
  1634. for (let indexRange = 0; indexRange < getSelection().rangeCount; indexRange++) {
  1635. const range = getSelection().getRangeAt(indexRange);
  1636. selectedRanges.push(range);
  1637. }
  1638. }
  1639. });
  1640. }
  1641. function getTarget(event) {
  1642. let newTarget, target = event.target, boundingRect = target.getBoundingClientRect();
  1643. newTarget = determineTargetElement("floor", target, event.clientX - boundingRect.left, getMatchedParents(target, "left"));
  1644. if (newTarget == target) {
  1645. newTarget = determineTargetElement("ceil", target, boundingRect.left + boundingRect.width - event.clientX, getMatchedParents(target, "right"));
  1646. }
  1647. if (newTarget == target) {
  1648. newTarget = determineTargetElement("floor", target, event.clientY - boundingRect.top, getMatchedParents(target, "top"));
  1649. }
  1650. if (newTarget == target) {
  1651. newTarget = determineTargetElement("ceil", target, boundingRect.top + boundingRect.height - event.clientY, getMatchedParents(target, "bottom"));
  1652. }
  1653. target = newTarget;
  1654. while (target && target.clientWidth <= SELECT_PX_THRESHOLD && target.clientHeight <= SELECT_PX_THRESHOLD) {
  1655. target = target.parentElement;
  1656. }
  1657. return target;
  1658. }
  1659. function moveAreaSelector(target) {
  1660. requestAnimationFrame(() => {
  1661. const selectorElement = getAreaSelector();
  1662. const boundingRect = target.getBoundingClientRect();
  1663. const scrollingElement = document.scrollingElement || document.documentElement;
  1664. selectorElement.style.setProperty("top", (scrollingElement.scrollTop + boundingRect.top - 10) + "px");
  1665. selectorElement.style.setProperty("left", (scrollingElement.scrollLeft + boundingRect.left - 10) + "px");
  1666. selectorElement.style.setProperty("width", (boundingRect.width + 20) + "px");
  1667. selectorElement.style.setProperty("height", (boundingRect.height + 20) + "px");
  1668. });
  1669. }
  1670. function getAreaSelector() {
  1671. let selectorElement = document.querySelector(SELECTION_ZONE_TAGNAME);
  1672. if (!selectorElement) {
  1673. selectorElement = createElement(SELECTION_ZONE_TAGNAME, document.body);
  1674. selectorElement.style.setProperty("box-sizing", "border-box", "important");
  1675. selectorElement.style.setProperty("background-color", "#3ea9d7", "important");
  1676. selectorElement.style.setProperty("border", "10px solid #0b4892", "important");
  1677. selectorElement.style.setProperty("border-radius", "2px", "important");
  1678. selectorElement.style.setProperty("opacity", ".25", "important");
  1679. selectorElement.style.setProperty("pointer-events", "none", "important");
  1680. selectorElement.style.setProperty("position", "absolute", "important");
  1681. selectorElement.style.setProperty("transition", "all 100ms", "important");
  1682. selectorElement.style.setProperty("cursor", "pointer", "important");
  1683. selectorElement.style.setProperty("z-index", "2147483647", "important");
  1684. selectorElement.style.removeProperty("border-inline-end");
  1685. selectorElement.style.removeProperty("border-inline-start");
  1686. selectorElement.style.removeProperty("inline-size");
  1687. selectorElement.style.removeProperty("block-size");
  1688. selectorElement.style.removeProperty("inset-block-start");
  1689. selectorElement.style.removeProperty("inset-inline-end");
  1690. selectorElement.style.removeProperty("inset-block-end");
  1691. selectorElement.style.removeProperty("inset-inline-start");
  1692. }
  1693. return selectorElement;
  1694. }
  1695. function createMaskElement() {
  1696. try {
  1697. let maskElement = document.querySelector(MASK_TAGNAME);
  1698. if (!maskElement) {
  1699. maskElement = createElement(MASK_TAGNAME, document.documentElement);
  1700. const shadowRoot = maskElement.attachShadow({ mode: "open" });
  1701. const styleElement = document.createElement("style");
  1702. styleElement.textContent = `
  1703. @keyframes single-file-progress {
  1704. 0% {
  1705. left: -50px;
  1706. }
  1707. 100% {
  1708. left: 0;
  1709. }
  1710. }
  1711. .${PROGRESSBAR_CLASSNAME} {
  1712. position: fixed;
  1713. top: 0;
  1714. left: 0;
  1715. width: 0;
  1716. height: 8px;
  1717. z-index: 2147483646;
  1718. opacity: .5;
  1719. overflow: hidden;
  1720. transition: width 200ms ease-in-out;
  1721. }
  1722. .${PROGRESSBAR_CONTENT_CLASSNAME} {
  1723. position: absolute;
  1724. left: 0;
  1725. animation: single-file-progress 3s linear infinite reverse;
  1726. background:
  1727. white
  1728. linear-gradient(-45deg, rgba(0, 0, 0, 0.075) 25%,
  1729. transparent 25%,
  1730. transparent 50%,
  1731. rgba(0, 0, 0, 0.075) 50%,
  1732. rgba(0, 0, 0, 0.075) 75%,
  1733. transparent 75%, transparent)
  1734. repeat scroll 0% 0% / 50px 50px padding-box border-box;
  1735. width: calc(100% + 50px);
  1736. height: 100%;
  1737. }
  1738. .${MASK_CONTENT_CLASSNAME} {
  1739. position: fixed;
  1740. top: 0;
  1741. left: 0;
  1742. width: 100%;
  1743. height: 100%;
  1744. z-index: 2147483646;
  1745. opacity: 0;
  1746. background-color: black;
  1747. transition: opacity 250ms;
  1748. }
  1749. `;
  1750. shadowRoot.appendChild(styleElement);
  1751. let maskElementContent = document.createElement("div");
  1752. maskElementContent.classList.add(MASK_CONTENT_CLASSNAME);
  1753. shadowRoot.appendChild(maskElementContent);
  1754. maskElement.offsetWidth;
  1755. maskElementContent.style.setProperty("opacity", .3);
  1756. maskElement.offsetWidth;
  1757. }
  1758. return maskElement;
  1759. } catch (error) {
  1760. // ignored
  1761. }
  1762. }
  1763. function createProgressBarElement(maskElement) {
  1764. try {
  1765. let progressBarElement = maskElement.shadowRoot.querySelector("." + PROGRESSBAR_CLASSNAME);
  1766. if (!progressBarElement) {
  1767. let progressBarContent = document.createElement("div");
  1768. progressBarContent.classList.add(PROGRESSBAR_CLASSNAME);
  1769. maskElement.shadowRoot.appendChild(progressBarContent);
  1770. const progressBarContentElement = document.createElement("div");
  1771. progressBarContentElement.classList.add(PROGRESSBAR_CONTENT_CLASSNAME);
  1772. progressBarContent.appendChild(progressBarContentElement);
  1773. }
  1774. } catch (error) {
  1775. // ignored
  1776. }
  1777. }
  1778. function createLogsWindowElement() {
  1779. try {
  1780. logsWindowElement = document.querySelector(LOGS_WINDOW_TAGNAME);
  1781. if (!logsWindowElement) {
  1782. logsWindowElement = createElement(LOGS_WINDOW_TAGNAME);
  1783. const shadowRoot = logsWindowElement.attachShadow({ mode: "open" });
  1784. const styleElement = document.createElement("style");
  1785. styleElement.textContent = `
  1786. @keyframes single-file-pulse {
  1787. 0% {
  1788. opacity: .25;
  1789. }
  1790. 100% {
  1791. opacity: 1;
  1792. }
  1793. }
  1794. .${LOGS_CLASSNAME} {
  1795. position: fixed;
  1796. bottom: 24px;
  1797. left: 8px;
  1798. z-index: 2147483647;
  1799. opacity: 0.9;
  1800. padding: 4px;
  1801. background-color: white;
  1802. min-width: ${LOG_PANEL_WIDTH}px;
  1803. min-height: 16px;
  1804. transition: height 100ms;
  1805. }
  1806. .${LOGS_LINE_CLASSNAME} {
  1807. display: flex;
  1808. justify-content: space-between;
  1809. padding: 2px;
  1810. font-family: arial, sans-serif;
  1811. color: black;
  1812. background-color: white;
  1813. }
  1814. .${LOGS_LINE_TEXT_ELEMENT_CLASSNAME} {
  1815. font-size: 13px;
  1816. opacity: 1;
  1817. transition: opacity 200ms;
  1818. }
  1819. .${LOGS_LINE_STATUS_ELEMENT_CLASSNAME} {
  1820. font-size: 11px;
  1821. min-width: 15px;
  1822. text-align: center;
  1823. position: relative;
  1824. top: 1px;
  1825. }
  1826. `;
  1827. shadowRoot.appendChild(styleElement);
  1828. const logsContentElement = document.createElement("div");
  1829. logsContentElement.classList.add(LOGS_CLASSNAME);
  1830. shadowRoot.appendChild(logsContentElement);
  1831. }
  1832. } catch (error) {
  1833. // ignored
  1834. }
  1835. }
  1836. function updateLog(id, textContent, textStatus, options) {
  1837. try {
  1838. if (options.logsEnabled) {
  1839. const logsContentElement = logsWindowElement.shadowRoot.querySelector("." + LOGS_CLASSNAME);
  1840. let lineElement = logsContentElement.querySelector("[data-id='" + id + "']");
  1841. if (!lineElement) {
  1842. lineElement = document.createElement("div");
  1843. lineElement.classList.add(LOGS_LINE_CLASSNAME);
  1844. logsContentElement.appendChild(lineElement);
  1845. lineElement.setAttribute("data-id", id);
  1846. const textElement = document.createElement("div");
  1847. textElement.classList.add(LOGS_LINE_TEXT_ELEMENT_CLASSNAME);
  1848. lineElement.appendChild(textElement);
  1849. textElement.textContent = textContent;
  1850. const statusElement = document.createElement("div");
  1851. statusElement.classList.add(LOGS_LINE_STATUS_ELEMENT_CLASSNAME);
  1852. lineElement.appendChild(statusElement);
  1853. }
  1854. updateLogLine(lineElement, textContent, textStatus);
  1855. }
  1856. } catch (error) {
  1857. // ignored
  1858. }
  1859. }
  1860. function updateLogLine(lineElement, textContent, textStatus) {
  1861. const textElement = lineElement.childNodes[0];
  1862. const statusElement = lineElement.childNodes[1];
  1863. textElement.textContent = textContent;
  1864. statusElement.style.setProperty("color", textStatus == "✓" ? "#055000" : "black");
  1865. if (textStatus == "✓") {
  1866. textElement.style.setProperty("opacity", ".5");
  1867. statusElement.style.setProperty("opacity", ".5");
  1868. statusElement.style.setProperty("animation", "none");
  1869. } else {
  1870. statusElement.style.setProperty("animation", "1s ease-in-out 0s infinite alternate none running single-file-pulse");
  1871. }
  1872. statusElement.textContent = textStatus;
  1873. }
  1874. function updateProgressBar(index, maxIndex) {
  1875. try {
  1876. const maskElement = document.querySelector(MASK_TAGNAME);
  1877. if (maskElement) {
  1878. const progressBarElement = maskElement.shadowRoot.querySelector("." + PROGRESSBAR_CLASSNAME);
  1879. if (progressBarElement && maxIndex) {
  1880. const width = Math.floor((index / maxIndex) * 100) + "%";
  1881. if (progressBarElement.style.getPropertyValue("width") != width) {
  1882. progressBarElement.style.setProperty("width", width);
  1883. progressBarElement.offsetWidth;
  1884. }
  1885. }
  1886. }
  1887. } catch (error) {
  1888. // ignored
  1889. }
  1890. }
  1891. function clearLogs() {
  1892. createLogsWindowElement();
  1893. }
  1894. function getMatchedParents(target, property) {
  1895. let element = target, matchedParent, parents = [];
  1896. do {
  1897. const boundingRect = element.getBoundingClientRect();
  1898. if (element.parentElement) {
  1899. const parentBoundingRect = element.parentElement.getBoundingClientRect();
  1900. matchedParent = Math.abs(parentBoundingRect[property] - boundingRect[property]) <= SELECT_PX_THRESHOLD;
  1901. if (matchedParent) {
  1902. if (element.parentElement.clientWidth > SELECT_PX_THRESHOLD && element.parentElement.clientHeight > SELECT_PX_THRESHOLD &&
  1903. ((element.parentElement.clientWidth - element.clientWidth > SELECT_PX_THRESHOLD) || (element.parentElement.clientHeight - element.clientHeight > SELECT_PX_THRESHOLD))) {
  1904. parents.push(element.parentElement);
  1905. }
  1906. element = element.parentElement;
  1907. }
  1908. } else {
  1909. matchedParent = false;
  1910. }
  1911. } while (matchedParent && element);
  1912. return parents;
  1913. }
  1914. function determineTargetElement(roundingMethod, target, widthDistance, parents) {
  1915. if (Math[roundingMethod](widthDistance / SELECT_PX_THRESHOLD) <= parents.length) {
  1916. target = parents[parents.length - Math[roundingMethod](widthDistance / SELECT_PX_THRESHOLD) - 1];
  1917. }
  1918. return target;
  1919. }
  1920. function createElement(tagName, parentElement) {
  1921. const element = document.createElement(tagName);
  1922. element.className = SINGLE_FILE_UI_ELEMENT_CLASS;
  1923. if (parentElement) {
  1924. parentElement.appendChild(element);
  1925. }
  1926. CSS_PROPERTIES.forEach(property => element.style.setProperty(property, "initial", "important"));
  1927. return element;
  1928. }
  1929. /*
  1930. * Copyright 2010-2020 Gildas Lormeau
  1931. * contact : gildas.lormeau <at> gmail.com
  1932. *
  1933. * This file is part of SingleFile.
  1934. *
  1935. * The code in this file is free software: you can redistribute it and/or
  1936. * modify it under the terms of the GNU Affero General Public License
  1937. * (GNU AGPL) as published by the Free Software Foundation, either version 3
  1938. * of the License, or (at your option) any later version.
  1939. *
  1940. * The code in this file is distributed in the hope that it will be useful,
  1941. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  1942. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
  1943. * General Public License for more details.
  1944. *
  1945. * As additional permission under GNU AGPL version 3 section 7, you may
  1946. * distribute UNMODIFIED VERSIONS OF THIS file without the copy of the GNU
  1947. * AGPL normally required by section 4, provided you include this license
  1948. * notice and a URL through which recipients can access the Corresponding
  1949. * Source.
  1950. */
  1951. const singlefile = globalThis.singlefile;
  1952. const bootstrap = globalThis.singlefileBootstrap;
  1953. const MOZ_EXTENSION_PROTOCOL = "moz-extension:";
  1954. const EMBEDDED_IMAGE_BUTTON_MESSAGE = browser.i18n.getMessage("topPanelEmbeddedImageButton");
  1955. const SHARE_PAGE_BUTTON_MESSAGE = browser.i18n.getMessage("topPanelSharePageButton");
  1956. const SHARE_SELECTION_BUTTON_MESSAGE = browser.i18n.getMessage("topPanelShareSelectionButton");
  1957. const ERROR_TITLE_MESSAGE = browser.i18n.getMessage("topPanelError");
  1958. let processor, processing, downloadParser, openFileInfobar, scrollY, transform, overflow;
  1959. setLabels({
  1960. EMBEDDED_IMAGE_BUTTON_MESSAGE,
  1961. SHARE_PAGE_BUTTON_MESSAGE,
  1962. SHARE_SELECTION_BUTTON_MESSAGE,
  1963. ERROR_TITLE_MESSAGE
  1964. });
  1965. if (!bootstrap || !bootstrap.initializedSingleFile) {
  1966. singlefile.init({ fetch: fetchResource, frameFetch });
  1967. browser.runtime.onMessage.addListener(message => {
  1968. if (message.method == "content.save" ||
  1969. message.method == "content.cancelSave" ||
  1970. message.method == "content.download" ||
  1971. message.method == "content.getSelectedLinks" ||
  1972. message.method == "content.error" ||
  1973. message.method == "content.prompt" ||
  1974. message.method == "content.beginScrollTo" ||
  1975. message.method == "content.scrollTo" ||
  1976. message.method == "content.endScrollTo") {
  1977. return onMessage(message);
  1978. }
  1979. });
  1980. if (bootstrap) {
  1981. bootstrap.initializedSingleFile = true;
  1982. } else {
  1983. globalThis.singlefileBootstrap = { initializedSingleFile: true };
  1984. }
  1985. }
  1986. async function onMessage(message) {
  1987. if (!location.href.startsWith(MOZ_EXTENSION_PROTOCOL)) {
  1988. if (message.method == "content.save") {
  1989. await savePage(message);
  1990. return {};
  1991. }
  1992. if (message.method == "content.cancelSave") {
  1993. if (processor) {
  1994. processor.cancel();
  1995. onEndPage();
  1996. if (openFileInfobar) {
  1997. openFileInfobar.cancel();
  1998. openFileInfobar = null;
  1999. }
  2000. browser.runtime.sendMessage({ method: "ui.processCancelled" });
  2001. }
  2002. if (message.options.loadDeferredImages) {
  2003. singlefile.processors.lazy.resetZoomLevel(message.options);
  2004. }
  2005. return {};
  2006. }
  2007. if (message.method == "content.getSelectedLinks") {
  2008. return {
  2009. urls: getSelectedLinks()
  2010. };
  2011. }
  2012. if (message.method == "content.download") {
  2013. if (!downloadParser) {
  2014. downloadParser = getParser();
  2015. }
  2016. const result = await downloadParser.next(message.data);
  2017. if (result.done) {
  2018. downloadParser = null;
  2019. try {
  2020. await downloadPageForeground(result.value, {
  2021. foregroundSave: result.value.foregroundSave,
  2022. sharePage: result.value.sharePage,
  2023. });
  2024. } catch (error) {
  2025. return {
  2026. error: error.toString()
  2027. };
  2028. } finally {
  2029. await browser.runtime.sendMessage({ method: "downloads.end", taskId: result.value.taskId });
  2030. }
  2031. }
  2032. return {};
  2033. }
  2034. if (message.method == "content.error") {
  2035. onError(message.error, message.link);
  2036. return {};
  2037. }
  2038. if (message.method == "content.prompt") {
  2039. return promptMessage(message.message, message.value);
  2040. }
  2041. if (message.method == "content.beginScrollTo") {
  2042. scrollY = globalThis.scrollY;
  2043. transform = document.documentElement.style.getPropertyValue("transform");
  2044. overflow = document.documentElement.style.getPropertyValue("overflow");
  2045. globalThis.scrollTo(0, 0);
  2046. document.documentElement.style.setProperty("transform", "translateY(0px)");
  2047. document.documentElement.style.setProperty("overflow", "hidden");
  2048. return {};
  2049. }
  2050. if (message.method == "content.scrollTo") {
  2051. document.documentElement.style.setProperty("transform", "translateY(-" + message.y + "px)");
  2052. await new Promise(resolve => setTimeout(resolve, 500));
  2053. return {};
  2054. }
  2055. if (message.method == "content.endScrollTo") {
  2056. globalThis.scrollTo(0, scrollY);
  2057. document.documentElement.style.setProperty("transform", transform);
  2058. document.documentElement.style.setProperty("overflow", overflow);
  2059. return {};
  2060. }
  2061. }
  2062. }
  2063. async function savePage(message) {
  2064. const options = message.options;
  2065. let selectionFound;
  2066. if (options.selected || options.optionallySelected) {
  2067. selectionFound = await markSelection(options.optionallySelected);
  2068. }
  2069. if (!processing && (!bootstrap || !bootstrap.pageInfo.processing)) {
  2070. options.updatedResources = bootstrap ? bootstrap.pageInfo.updatedResources : {};
  2071. options.visitDate = bootstrap ? bootstrap.pageInfo.visitDate : new Date();
  2072. Object.keys(options.updatedResources).forEach(url => options.updatedResources[url].retrieved = false);
  2073. if (options.optionallySelected && selectionFound) {
  2074. options.selected = true;
  2075. }
  2076. if (!options.selected || selectionFound) {
  2077. if (bootstrap) {
  2078. bootstrap.pageInfo.processing = true;
  2079. }
  2080. processing = true;
  2081. try {
  2082. const pageData = await processPage(options);
  2083. if (pageData) {
  2084. if (((!options.backgroundSave && !options.saveToClipboard) || options.saveToGDrive || options.saveToGitHub || options.saveWithCompanion || options.saveWithWebDAV || options.saveToDropbox || options.saveToRestFormApi) && options.confirmFilename) {
  2085. pageData.filename = promptMessage("Save as", pageData.filename) || pageData.filename;
  2086. }
  2087. await downloadPage(pageData, options);
  2088. }
  2089. } catch (error) {
  2090. if (!processor.cancelled) {
  2091. console.error(error); // eslint-disable-line no-console
  2092. const errorMessage = error.toString();
  2093. browser.runtime.sendMessage({ method: "ui.processError", error: errorMessage });
  2094. onError(errorMessage);
  2095. }
  2096. }
  2097. } else {
  2098. browser.runtime.sendMessage({ method: "ui.processCancelled" });
  2099. }
  2100. processing = false;
  2101. if (bootstrap) {
  2102. bootstrap.pageInfo.processing = false;
  2103. }
  2104. }
  2105. }
  2106. async function processPage(options) {
  2107. const frames = singlefile.processors.frameTree;
  2108. let framesSessionId;
  2109. options.keepFilename = options.saveToGDrive || options.saveToGitHub || options.saveWithWebDAV || options.saveToDropbox || options.saveToRestFormApi;
  2110. singlefile.helper.initDoc(document);
  2111. onStartPage(options);
  2112. processor = new singlefile.SingleFile(options);
  2113. const preInitializationPromises = [];
  2114. options.insertCanonicalLink = true;
  2115. let index = 0, maxIndex = 0, initializing;
  2116. options.onprogress = async event => {
  2117. const { options } = event.detail;
  2118. if (!processor.cancelled) {
  2119. if (event.type == event.RESOURCES_INITIALIZING) {
  2120. if (!initializing && options.insertEmbeddedScreenshotImage && options.compressContent) {
  2121. initializing = true;
  2122. setVisible(false);
  2123. const screenshotBlobURI = await browser.runtime.sendMessage({
  2124. method: "tabs.getScreenshot",
  2125. width: document.documentElement.scrollWidth,
  2126. height: document.documentElement.scrollHeight,
  2127. innerHeight: globalThis.innerHeight
  2128. });
  2129. setVisible(true);
  2130. onInsertingEmbeddedImage(options);
  2131. options.embeddedImage = new Uint8Array(await (await fetchResource(screenshotBlobURI)).arrayBuffer());
  2132. URL.revokeObjectURL(screenshotBlobURI);
  2133. onInsertEmbeddedImage(options);
  2134. }
  2135. }
  2136. if (event.type == event.RESOURCES_INITIALIZED) {
  2137. maxIndex = event.detail.max;
  2138. if (options.loadDeferredImages) {
  2139. singlefile.processors.lazy.resetZoomLevel(options);
  2140. }
  2141. }
  2142. if (event.type == event.RESOURCES_INITIALIZED || event.type == event.RESOURCE_LOADED) {
  2143. if (event.type == event.RESOURCE_LOADED) {
  2144. index++;
  2145. }
  2146. await browser.runtime.sendMessage({ method: "ui.processProgress", index, maxIndex });
  2147. onLoadResource(index, maxIndex, options);
  2148. } else if (!event.detail.frame) {
  2149. if (event.type == event.PAGE_LOADING) ; else if (event.type == event.PAGE_LOADED) ; else if (event.type == event.STAGE_STARTED) {
  2150. if (event.detail.step < 3) {
  2151. onStartStage(event.detail.step, options);
  2152. }
  2153. } else if (event.type == event.STAGE_ENDED) {
  2154. if (event.detail.step < 3) {
  2155. onEndStage(event.detail.step, options);
  2156. }
  2157. }
  2158. }
  2159. }
  2160. };
  2161. const cancelProcessor = processor.cancel.bind(processor);
  2162. if (options.insertEmbeddedImage && options.compressContent) {
  2163. onInsertingEmbeddedImage(options);
  2164. openFileInfobar = getOpenFileBar();
  2165. const cancelled = await openFileInfobar.display();
  2166. if (!cancelled) {
  2167. options.embeddedImage = await openFile({ accept: "image/*" });
  2168. openFileInfobar.hide();
  2169. }
  2170. onInsertEmbeddedImage(options);
  2171. }
  2172. if (!options.saveRawPage && !processor.cancelled) {
  2173. let lazyLoadPromise;
  2174. if (options.loadDeferredImages) {
  2175. lazyLoadPromise = singlefile.processors.lazy.process(options);
  2176. onLoadingDeferResources(options);
  2177. lazyLoadPromise.then(() => {
  2178. if (!processor.cancelled) {
  2179. onLoadDeferResources(options);
  2180. }
  2181. });
  2182. if (options.loadDeferredImagesBeforeFrames) {
  2183. await lazyLoadPromise;
  2184. }
  2185. }
  2186. if (!options.removeFrames && frames && globalThis.frames) {
  2187. let frameTreePromise;
  2188. if (options.loadDeferredImages) {
  2189. frameTreePromise = new Promise(resolve => globalThis.setTimeout(() => resolve(frames.getAsync(options)), options.loadDeferredImagesBeforeFrames || !options.loadDeferredImages ? 0 : options.loadDeferredImagesMaxIdleTime));
  2190. } else {
  2191. frameTreePromise = frames.getAsync(options);
  2192. }
  2193. onLoadingFrames(options);
  2194. frameTreePromise.then(() => {
  2195. if (!processor.cancelled) {
  2196. onLoadFrames(options);
  2197. }
  2198. });
  2199. if (options.loadDeferredImagesBeforeFrames) {
  2200. options.frames = await new Promise(resolve => {
  2201. processor.cancel = function () {
  2202. cancelProcessor();
  2203. resolve([]);
  2204. };
  2205. frameTreePromise.then(resolve);
  2206. });
  2207. } else {
  2208. preInitializationPromises.push(frameTreePromise);
  2209. }
  2210. }
  2211. if (options.loadDeferredImages && !options.loadDeferredImagesBeforeFrames) {
  2212. preInitializationPromises.push(lazyLoadPromise);
  2213. }
  2214. }
  2215. if (!options.loadDeferredImagesBeforeFrames && !processor.cancelled) {
  2216. [options.frames] = await new Promise(resolve => {
  2217. const preInitializationAllPromises = Promise.all(preInitializationPromises);
  2218. processor.cancel = function () {
  2219. cancelProcessor();
  2220. resolve([[]]);
  2221. };
  2222. preInitializationAllPromises.then(() => resolve(preInitializationAllPromises));
  2223. });
  2224. }
  2225. if (options.delayBeforeProcessing) {
  2226. await new Promise(resolve => setTimeout(resolve, options.delayBeforeProcessing * 1000));
  2227. }
  2228. framesSessionId = options.frames && options.frames.sessionId;
  2229. const selectedFrame = options.frames && options.frames.find(frameData => frameData.requestedFrame);
  2230. options.win = globalThis;
  2231. if (selectedFrame) {
  2232. options.content = selectedFrame.content;
  2233. options.url = selectedFrame.baseURI;
  2234. options.canvases = selectedFrame.canvases;
  2235. options.fonts = selectedFrame.fonts;
  2236. options.stylesheets = selectedFrame.stylesheets;
  2237. options.images = selectedFrame.images;
  2238. options.posters = selectedFrame.posters;
  2239. options.videos = selectedFrame.videos;
  2240. options.usedFonts = selectedFrame.usedFonts;
  2241. options.shadowRoots = selectedFrame.shadowRoots;
  2242. options.adoptedStyleSheets = selectedFrame.adoptedStyleSheets;
  2243. } else {
  2244. options.doc = document;
  2245. }
  2246. if (!processor.cancelled) {
  2247. await processor.run();
  2248. }
  2249. if (framesSessionId) {
  2250. frames.cleanup(framesSessionId);
  2251. }
  2252. let page;
  2253. if (!processor.cancelled) {
  2254. if (options.confirmInfobarContent) {
  2255. options.infobarContent = promptMessage("Infobar content", options.infobarContent) || "";
  2256. }
  2257. page = await processor.getPageData();
  2258. if (options.selected || options.optionallySelected) {
  2259. unmarkSelection();
  2260. }
  2261. onEndPage();
  2262. if (options.displayStats) {
  2263. console.log("SingleFile stats"); // eslint-disable-line no-console
  2264. console.table(page.stats); // eslint-disable-line no-console
  2265. }
  2266. }
  2267. return page;
  2268. }
  2269. })();