node_stream.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  1. /**
  2. * @licstart The following is the entire license notice for the
  3. * JavaScript code in this page
  4. *
  5. * Copyright 2022 Mozilla Foundation
  6. *
  7. * Licensed under the Apache License, Version 2.0 (the "License");
  8. * you may not use this file except in compliance with the License.
  9. * You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing, software
  14. * distributed under the License is distributed on an "AS IS" BASIS,
  15. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. * See the License for the specific language governing permissions and
  17. * limitations under the License.
  18. *
  19. * @licend The above is the entire license notice for the
  20. * JavaScript code in this page
  21. */
  22. "use strict";
  23. Object.defineProperty(exports, "__esModule", {
  24. value: true
  25. });
  26. exports.PDFNodeStream = void 0;
  27. var _util = require("../shared/util.js");
  28. var _network_utils = require("./network_utils.js");
  29. ;
  30. const fs = require("fs");
  31. const http = require("http");
  32. const https = require("https");
  33. const url = require("url");
  34. const fileUriRegex = /^file:\/\/\/[a-zA-Z]:\//;
  35. function parseUrl(sourceUrl) {
  36. const parsedUrl = url.parse(sourceUrl);
  37. if (parsedUrl.protocol === "file:" || parsedUrl.host) {
  38. return parsedUrl;
  39. }
  40. if (/^[a-z]:[/\\]/i.test(sourceUrl)) {
  41. return url.parse(`file:///${sourceUrl}`);
  42. }
  43. if (!parsedUrl.host) {
  44. parsedUrl.protocol = "file:";
  45. }
  46. return parsedUrl;
  47. }
  48. class PDFNodeStream {
  49. constructor(source) {
  50. this.source = source;
  51. this.url = parseUrl(source.url);
  52. this.isHttp = this.url.protocol === "http:" || this.url.protocol === "https:";
  53. this.isFsUrl = this.url.protocol === "file:";
  54. this.httpHeaders = this.isHttp && source.httpHeaders || {};
  55. this._fullRequestReader = null;
  56. this._rangeRequestReaders = [];
  57. }
  58. get _progressiveDataLength() {
  59. return this._fullRequestReader?._loaded ?? 0;
  60. }
  61. getFullReader() {
  62. (0, _util.assert)(!this._fullRequestReader, "PDFNodeStream.getFullReader can only be called once.");
  63. this._fullRequestReader = this.isFsUrl ? new PDFNodeStreamFsFullReader(this) : new PDFNodeStreamFullReader(this);
  64. return this._fullRequestReader;
  65. }
  66. getRangeReader(start, end) {
  67. if (end <= this._progressiveDataLength) {
  68. return null;
  69. }
  70. const rangeReader = this.isFsUrl ? new PDFNodeStreamFsRangeReader(this, start, end) : new PDFNodeStreamRangeReader(this, start, end);
  71. this._rangeRequestReaders.push(rangeReader);
  72. return rangeReader;
  73. }
  74. cancelAllRequests(reason) {
  75. if (this._fullRequestReader) {
  76. this._fullRequestReader.cancel(reason);
  77. }
  78. for (const reader of this._rangeRequestReaders.slice(0)) {
  79. reader.cancel(reason);
  80. }
  81. }
  82. }
  83. exports.PDFNodeStream = PDFNodeStream;
  84. class BaseFullReader {
  85. constructor(stream) {
  86. this._url = stream.url;
  87. this._done = false;
  88. this._storedError = null;
  89. this.onProgress = null;
  90. const source = stream.source;
  91. this._contentLength = source.length;
  92. this._loaded = 0;
  93. this._filename = null;
  94. this._disableRange = source.disableRange || false;
  95. this._rangeChunkSize = source.rangeChunkSize;
  96. if (!this._rangeChunkSize && !this._disableRange) {
  97. this._disableRange = true;
  98. }
  99. this._isStreamingSupported = !source.disableStream;
  100. this._isRangeSupported = !source.disableRange;
  101. this._readableStream = null;
  102. this._readCapability = (0, _util.createPromiseCapability)();
  103. this._headersCapability = (0, _util.createPromiseCapability)();
  104. }
  105. get headersReady() {
  106. return this._headersCapability.promise;
  107. }
  108. get filename() {
  109. return this._filename;
  110. }
  111. get contentLength() {
  112. return this._contentLength;
  113. }
  114. get isRangeSupported() {
  115. return this._isRangeSupported;
  116. }
  117. get isStreamingSupported() {
  118. return this._isStreamingSupported;
  119. }
  120. async read() {
  121. await this._readCapability.promise;
  122. if (this._done) {
  123. return {
  124. value: undefined,
  125. done: true
  126. };
  127. }
  128. if (this._storedError) {
  129. throw this._storedError;
  130. }
  131. const chunk = this._readableStream.read();
  132. if (chunk === null) {
  133. this._readCapability = (0, _util.createPromiseCapability)();
  134. return this.read();
  135. }
  136. this._loaded += chunk.length;
  137. if (this.onProgress) {
  138. this.onProgress({
  139. loaded: this._loaded,
  140. total: this._contentLength
  141. });
  142. }
  143. const buffer = new Uint8Array(chunk).buffer;
  144. return {
  145. value: buffer,
  146. done: false
  147. };
  148. }
  149. cancel(reason) {
  150. if (!this._readableStream) {
  151. this._error(reason);
  152. return;
  153. }
  154. this._readableStream.destroy(reason);
  155. }
  156. _error(reason) {
  157. this._storedError = reason;
  158. this._readCapability.resolve();
  159. }
  160. _setReadableStream(readableStream) {
  161. this._readableStream = readableStream;
  162. readableStream.on("readable", () => {
  163. this._readCapability.resolve();
  164. });
  165. readableStream.on("end", () => {
  166. readableStream.destroy();
  167. this._done = true;
  168. this._readCapability.resolve();
  169. });
  170. readableStream.on("error", reason => {
  171. this._error(reason);
  172. });
  173. if (!this._isStreamingSupported && this._isRangeSupported) {
  174. this._error(new _util.AbortException("streaming is disabled"));
  175. }
  176. if (this._storedError) {
  177. this._readableStream.destroy(this._storedError);
  178. }
  179. }
  180. }
  181. class BaseRangeReader {
  182. constructor(stream) {
  183. this._url = stream.url;
  184. this._done = false;
  185. this._storedError = null;
  186. this.onProgress = null;
  187. this._loaded = 0;
  188. this._readableStream = null;
  189. this._readCapability = (0, _util.createPromiseCapability)();
  190. const source = stream.source;
  191. this._isStreamingSupported = !source.disableStream;
  192. }
  193. get isStreamingSupported() {
  194. return this._isStreamingSupported;
  195. }
  196. async read() {
  197. await this._readCapability.promise;
  198. if (this._done) {
  199. return {
  200. value: undefined,
  201. done: true
  202. };
  203. }
  204. if (this._storedError) {
  205. throw this._storedError;
  206. }
  207. const chunk = this._readableStream.read();
  208. if (chunk === null) {
  209. this._readCapability = (0, _util.createPromiseCapability)();
  210. return this.read();
  211. }
  212. this._loaded += chunk.length;
  213. if (this.onProgress) {
  214. this.onProgress({
  215. loaded: this._loaded
  216. });
  217. }
  218. const buffer = new Uint8Array(chunk).buffer;
  219. return {
  220. value: buffer,
  221. done: false
  222. };
  223. }
  224. cancel(reason) {
  225. if (!this._readableStream) {
  226. this._error(reason);
  227. return;
  228. }
  229. this._readableStream.destroy(reason);
  230. }
  231. _error(reason) {
  232. this._storedError = reason;
  233. this._readCapability.resolve();
  234. }
  235. _setReadableStream(readableStream) {
  236. this._readableStream = readableStream;
  237. readableStream.on("readable", () => {
  238. this._readCapability.resolve();
  239. });
  240. readableStream.on("end", () => {
  241. readableStream.destroy();
  242. this._done = true;
  243. this._readCapability.resolve();
  244. });
  245. readableStream.on("error", reason => {
  246. this._error(reason);
  247. });
  248. if (this._storedError) {
  249. this._readableStream.destroy(this._storedError);
  250. }
  251. }
  252. }
  253. function createRequestOptions(parsedUrl, headers) {
  254. return {
  255. protocol: parsedUrl.protocol,
  256. auth: parsedUrl.auth,
  257. host: parsedUrl.hostname,
  258. port: parsedUrl.port,
  259. path: parsedUrl.path,
  260. method: "GET",
  261. headers
  262. };
  263. }
  264. class PDFNodeStreamFullReader extends BaseFullReader {
  265. constructor(stream) {
  266. super(stream);
  267. const handleResponse = response => {
  268. if (response.statusCode === 404) {
  269. const error = new _util.MissingPDFException(`Missing PDF "${this._url}".`);
  270. this._storedError = error;
  271. this._headersCapability.reject(error);
  272. return;
  273. }
  274. this._headersCapability.resolve();
  275. this._setReadableStream(response);
  276. const getResponseHeader = name => {
  277. return this._readableStream.headers[name.toLowerCase()];
  278. };
  279. const {
  280. allowRangeRequests,
  281. suggestedLength
  282. } = (0, _network_utils.validateRangeRequestCapabilities)({
  283. getResponseHeader,
  284. isHttp: stream.isHttp,
  285. rangeChunkSize: this._rangeChunkSize,
  286. disableRange: this._disableRange
  287. });
  288. this._isRangeSupported = allowRangeRequests;
  289. this._contentLength = suggestedLength || this._contentLength;
  290. this._filename = (0, _network_utils.extractFilenameFromHeader)(getResponseHeader);
  291. };
  292. this._request = null;
  293. if (this._url.protocol === "http:") {
  294. this._request = http.request(createRequestOptions(this._url, stream.httpHeaders), handleResponse);
  295. } else {
  296. this._request = https.request(createRequestOptions(this._url, stream.httpHeaders), handleResponse);
  297. }
  298. this._request.on("error", reason => {
  299. this._storedError = reason;
  300. this._headersCapability.reject(reason);
  301. });
  302. this._request.end();
  303. }
  304. }
  305. class PDFNodeStreamRangeReader extends BaseRangeReader {
  306. constructor(stream, start, end) {
  307. super(stream);
  308. this._httpHeaders = {};
  309. for (const property in stream.httpHeaders) {
  310. const value = stream.httpHeaders[property];
  311. if (typeof value === "undefined") {
  312. continue;
  313. }
  314. this._httpHeaders[property] = value;
  315. }
  316. this._httpHeaders.Range = `bytes=${start}-${end - 1}`;
  317. const handleResponse = response => {
  318. if (response.statusCode === 404) {
  319. const error = new _util.MissingPDFException(`Missing PDF "${this._url}".`);
  320. this._storedError = error;
  321. return;
  322. }
  323. this._setReadableStream(response);
  324. };
  325. this._request = null;
  326. if (this._url.protocol === "http:") {
  327. this._request = http.request(createRequestOptions(this._url, this._httpHeaders), handleResponse);
  328. } else {
  329. this._request = https.request(createRequestOptions(this._url, this._httpHeaders), handleResponse);
  330. }
  331. this._request.on("error", reason => {
  332. this._storedError = reason;
  333. });
  334. this._request.end();
  335. }
  336. }
  337. class PDFNodeStreamFsFullReader extends BaseFullReader {
  338. constructor(stream) {
  339. super(stream);
  340. let path = decodeURIComponent(this._url.path);
  341. if (fileUriRegex.test(this._url.href)) {
  342. path = path.replace(/^\//, "");
  343. }
  344. fs.lstat(path, (error, stat) => {
  345. if (error) {
  346. if (error.code === "ENOENT") {
  347. error = new _util.MissingPDFException(`Missing PDF "${path}".`);
  348. }
  349. this._storedError = error;
  350. this._headersCapability.reject(error);
  351. return;
  352. }
  353. this._contentLength = stat.size;
  354. this._setReadableStream(fs.createReadStream(path));
  355. this._headersCapability.resolve();
  356. });
  357. }
  358. }
  359. class PDFNodeStreamFsRangeReader extends BaseRangeReader {
  360. constructor(stream, start, end) {
  361. super(stream);
  362. let path = decodeURIComponent(this._url.path);
  363. if (fileUriRegex.test(this._url.href)) {
  364. path = path.replace(/^\//, "");
  365. }
  366. this._setReadableStream(fs.createReadStream(path, {
  367. start,
  368. end: end - 1
  369. }));
  370. }
  371. }