single-file-extension.js 69 KB

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