2
0

node_stream.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666
  1. /**
  2. * @licstart The following is the entire license notice for the
  3. * Javascript code in this page
  4. *
  5. * Copyright 2019 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 _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
  28. var _util = require("../shared/util");
  29. var _network_utils = require("./network_utils");
  30. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
  31. function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
  32. function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
  33. function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
  34. function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
  35. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
  36. function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
  37. function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
  38. function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
  39. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  40. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
  41. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
  42. var fs = require('fs');
  43. var http = require('http');
  44. var https = require('https');
  45. var url = require('url');
  46. var fileUriRegex = /^file:\/\/\/[a-zA-Z]:\//;
  47. function parseUrl(sourceUrl) {
  48. var parsedUrl = url.parse(sourceUrl);
  49. if (parsedUrl.protocol === 'file:' || parsedUrl.host) {
  50. return parsedUrl;
  51. }
  52. if (/^[a-z]:[/\\]/i.test(sourceUrl)) {
  53. return url.parse("file:///".concat(sourceUrl));
  54. }
  55. if (!parsedUrl.host) {
  56. parsedUrl.protocol = 'file:';
  57. }
  58. return parsedUrl;
  59. }
  60. var PDFNodeStream =
  61. /*#__PURE__*/
  62. function () {
  63. function PDFNodeStream(source) {
  64. _classCallCheck(this, PDFNodeStream);
  65. this.source = source;
  66. this.url = parseUrl(source.url);
  67. this.isHttp = this.url.protocol === 'http:' || this.url.protocol === 'https:';
  68. this.isFsUrl = this.url.protocol === 'file:';
  69. this.httpHeaders = this.isHttp && source.httpHeaders || {};
  70. this._fullRequestReader = null;
  71. this._rangeRequestReaders = [];
  72. }
  73. _createClass(PDFNodeStream, [{
  74. key: "getFullReader",
  75. value: function getFullReader() {
  76. (0, _util.assert)(!this._fullRequestReader);
  77. this._fullRequestReader = this.isFsUrl ? new PDFNodeStreamFsFullReader(this) : new PDFNodeStreamFullReader(this);
  78. return this._fullRequestReader;
  79. }
  80. }, {
  81. key: "getRangeReader",
  82. value: function getRangeReader(start, end) {
  83. if (end <= this._progressiveDataLength) {
  84. return null;
  85. }
  86. var rangeReader = this.isFsUrl ? new PDFNodeStreamFsRangeReader(this, start, end) : new PDFNodeStreamRangeReader(this, start, end);
  87. this._rangeRequestReaders.push(rangeReader);
  88. return rangeReader;
  89. }
  90. }, {
  91. key: "cancelAllRequests",
  92. value: function cancelAllRequests(reason) {
  93. if (this._fullRequestReader) {
  94. this._fullRequestReader.cancel(reason);
  95. }
  96. var readers = this._rangeRequestReaders.slice(0);
  97. readers.forEach(function (reader) {
  98. reader.cancel(reason);
  99. });
  100. }
  101. }, {
  102. key: "_progressiveDataLength",
  103. get: function get() {
  104. return this._fullRequestReader ? this._fullRequestReader._loaded : 0;
  105. }
  106. }]);
  107. return PDFNodeStream;
  108. }();
  109. exports.PDFNodeStream = PDFNodeStream;
  110. var BaseFullReader =
  111. /*#__PURE__*/
  112. function () {
  113. function BaseFullReader(stream) {
  114. _classCallCheck(this, BaseFullReader);
  115. this._url = stream.url;
  116. this._done = false;
  117. this._storedError = null;
  118. this.onProgress = null;
  119. var source = stream.source;
  120. this._contentLength = source.length;
  121. this._loaded = 0;
  122. this._filename = null;
  123. this._disableRange = source.disableRange || false;
  124. this._rangeChunkSize = source.rangeChunkSize;
  125. if (!this._rangeChunkSize && !this._disableRange) {
  126. this._disableRange = true;
  127. }
  128. this._isStreamingSupported = !source.disableStream;
  129. this._isRangeSupported = !source.disableRange;
  130. this._readableStream = null;
  131. this._readCapability = (0, _util.createPromiseCapability)();
  132. this._headersCapability = (0, _util.createPromiseCapability)();
  133. }
  134. _createClass(BaseFullReader, [{
  135. key: "read",
  136. value: function () {
  137. var _read = _asyncToGenerator(
  138. /*#__PURE__*/
  139. _regenerator["default"].mark(function _callee() {
  140. var chunk, buffer;
  141. return _regenerator["default"].wrap(function _callee$(_context) {
  142. while (1) {
  143. switch (_context.prev = _context.next) {
  144. case 0:
  145. _context.next = 2;
  146. return this._readCapability.promise;
  147. case 2:
  148. if (!this._done) {
  149. _context.next = 4;
  150. break;
  151. }
  152. return _context.abrupt("return", {
  153. value: undefined,
  154. done: true
  155. });
  156. case 4:
  157. if (!this._storedError) {
  158. _context.next = 6;
  159. break;
  160. }
  161. throw this._storedError;
  162. case 6:
  163. chunk = this._readableStream.read();
  164. if (!(chunk === null)) {
  165. _context.next = 10;
  166. break;
  167. }
  168. this._readCapability = (0, _util.createPromiseCapability)();
  169. return _context.abrupt("return", this.read());
  170. case 10:
  171. this._loaded += chunk.length;
  172. if (this.onProgress) {
  173. this.onProgress({
  174. loaded: this._loaded,
  175. total: this._contentLength
  176. });
  177. }
  178. buffer = new Uint8Array(chunk).buffer;
  179. return _context.abrupt("return", {
  180. value: buffer,
  181. done: false
  182. });
  183. case 14:
  184. case "end":
  185. return _context.stop();
  186. }
  187. }
  188. }, _callee, this);
  189. }));
  190. function read() {
  191. return _read.apply(this, arguments);
  192. }
  193. return read;
  194. }()
  195. }, {
  196. key: "cancel",
  197. value: function cancel(reason) {
  198. if (!this._readableStream) {
  199. this._error(reason);
  200. return;
  201. }
  202. this._readableStream.destroy(reason);
  203. }
  204. }, {
  205. key: "_error",
  206. value: function _error(reason) {
  207. this._storedError = reason;
  208. this._readCapability.resolve();
  209. }
  210. }, {
  211. key: "_setReadableStream",
  212. value: function _setReadableStream(readableStream) {
  213. var _this = this;
  214. this._readableStream = readableStream;
  215. readableStream.on('readable', function () {
  216. _this._readCapability.resolve();
  217. });
  218. readableStream.on('end', function () {
  219. readableStream.destroy();
  220. _this._done = true;
  221. _this._readCapability.resolve();
  222. });
  223. readableStream.on('error', function (reason) {
  224. _this._error(reason);
  225. });
  226. if (!this._isStreamingSupported && this._isRangeSupported) {
  227. this._error(new _util.AbortException('streaming is disabled'));
  228. }
  229. if (this._storedError) {
  230. this._readableStream.destroy(this._storedError);
  231. }
  232. }
  233. }, {
  234. key: "headersReady",
  235. get: function get() {
  236. return this._headersCapability.promise;
  237. }
  238. }, {
  239. key: "filename",
  240. get: function get() {
  241. return this._filename;
  242. }
  243. }, {
  244. key: "contentLength",
  245. get: function get() {
  246. return this._contentLength;
  247. }
  248. }, {
  249. key: "isRangeSupported",
  250. get: function get() {
  251. return this._isRangeSupported;
  252. }
  253. }, {
  254. key: "isStreamingSupported",
  255. get: function get() {
  256. return this._isStreamingSupported;
  257. }
  258. }]);
  259. return BaseFullReader;
  260. }();
  261. var BaseRangeReader =
  262. /*#__PURE__*/
  263. function () {
  264. function BaseRangeReader(stream) {
  265. _classCallCheck(this, BaseRangeReader);
  266. this._url = stream.url;
  267. this._done = false;
  268. this._storedError = null;
  269. this.onProgress = null;
  270. this._loaded = 0;
  271. this._readableStream = null;
  272. this._readCapability = (0, _util.createPromiseCapability)();
  273. var source = stream.source;
  274. this._isStreamingSupported = !source.disableStream;
  275. }
  276. _createClass(BaseRangeReader, [{
  277. key: "read",
  278. value: function () {
  279. var _read2 = _asyncToGenerator(
  280. /*#__PURE__*/
  281. _regenerator["default"].mark(function _callee2() {
  282. var chunk, buffer;
  283. return _regenerator["default"].wrap(function _callee2$(_context2) {
  284. while (1) {
  285. switch (_context2.prev = _context2.next) {
  286. case 0:
  287. _context2.next = 2;
  288. return this._readCapability.promise;
  289. case 2:
  290. if (!this._done) {
  291. _context2.next = 4;
  292. break;
  293. }
  294. return _context2.abrupt("return", {
  295. value: undefined,
  296. done: true
  297. });
  298. case 4:
  299. if (!this._storedError) {
  300. _context2.next = 6;
  301. break;
  302. }
  303. throw this._storedError;
  304. case 6:
  305. chunk = this._readableStream.read();
  306. if (!(chunk === null)) {
  307. _context2.next = 10;
  308. break;
  309. }
  310. this._readCapability = (0, _util.createPromiseCapability)();
  311. return _context2.abrupt("return", this.read());
  312. case 10:
  313. this._loaded += chunk.length;
  314. if (this.onProgress) {
  315. this.onProgress({
  316. loaded: this._loaded
  317. });
  318. }
  319. buffer = new Uint8Array(chunk).buffer;
  320. return _context2.abrupt("return", {
  321. value: buffer,
  322. done: false
  323. });
  324. case 14:
  325. case "end":
  326. return _context2.stop();
  327. }
  328. }
  329. }, _callee2, this);
  330. }));
  331. function read() {
  332. return _read2.apply(this, arguments);
  333. }
  334. return read;
  335. }()
  336. }, {
  337. key: "cancel",
  338. value: function cancel(reason) {
  339. if (!this._readableStream) {
  340. this._error(reason);
  341. return;
  342. }
  343. this._readableStream.destroy(reason);
  344. }
  345. }, {
  346. key: "_error",
  347. value: function _error(reason) {
  348. this._storedError = reason;
  349. this._readCapability.resolve();
  350. }
  351. }, {
  352. key: "_setReadableStream",
  353. value: function _setReadableStream(readableStream) {
  354. var _this2 = this;
  355. this._readableStream = readableStream;
  356. readableStream.on('readable', function () {
  357. _this2._readCapability.resolve();
  358. });
  359. readableStream.on('end', function () {
  360. readableStream.destroy();
  361. _this2._done = true;
  362. _this2._readCapability.resolve();
  363. });
  364. readableStream.on('error', function (reason) {
  365. _this2._error(reason);
  366. });
  367. if (this._storedError) {
  368. this._readableStream.destroy(this._storedError);
  369. }
  370. }
  371. }, {
  372. key: "isStreamingSupported",
  373. get: function get() {
  374. return this._isStreamingSupported;
  375. }
  376. }]);
  377. return BaseRangeReader;
  378. }();
  379. function createRequestOptions(url, headers) {
  380. return {
  381. protocol: url.protocol,
  382. auth: url.auth,
  383. host: url.hostname,
  384. port: url.port,
  385. path: url.path,
  386. method: 'GET',
  387. headers: headers
  388. };
  389. }
  390. var PDFNodeStreamFullReader =
  391. /*#__PURE__*/
  392. function (_BaseFullReader) {
  393. _inherits(PDFNodeStreamFullReader, _BaseFullReader);
  394. function PDFNodeStreamFullReader(stream) {
  395. var _this3;
  396. _classCallCheck(this, PDFNodeStreamFullReader);
  397. _this3 = _possibleConstructorReturn(this, _getPrototypeOf(PDFNodeStreamFullReader).call(this, stream));
  398. var handleResponse = function handleResponse(response) {
  399. if (response.statusCode === 404) {
  400. var error = new _util.MissingPDFException("Missing PDF \"".concat(_this3._url, "\"."));
  401. _this3._storedError = error;
  402. _this3._headersCapability.reject(error);
  403. return;
  404. }
  405. _this3._headersCapability.resolve();
  406. _this3._setReadableStream(response);
  407. var getResponseHeader = function getResponseHeader(name) {
  408. return _this3._readableStream.headers[name.toLowerCase()];
  409. };
  410. var _validateRangeRequest = (0, _network_utils.validateRangeRequestCapabilities)({
  411. getResponseHeader: getResponseHeader,
  412. isHttp: stream.isHttp,
  413. rangeChunkSize: _this3._rangeChunkSize,
  414. disableRange: _this3._disableRange
  415. }),
  416. allowRangeRequests = _validateRangeRequest.allowRangeRequests,
  417. suggestedLength = _validateRangeRequest.suggestedLength;
  418. _this3._isRangeSupported = allowRangeRequests;
  419. _this3._contentLength = suggestedLength || _this3._contentLength;
  420. _this3._filename = (0, _network_utils.extractFilenameFromHeader)(getResponseHeader);
  421. };
  422. _this3._request = null;
  423. if (_this3._url.protocol === 'http:') {
  424. _this3._request = http.request(createRequestOptions(_this3._url, stream.httpHeaders), handleResponse);
  425. } else {
  426. _this3._request = https.request(createRequestOptions(_this3._url, stream.httpHeaders), handleResponse);
  427. }
  428. _this3._request.on('error', function (reason) {
  429. _this3._storedError = reason;
  430. _this3._headersCapability.reject(reason);
  431. });
  432. _this3._request.end();
  433. return _this3;
  434. }
  435. return PDFNodeStreamFullReader;
  436. }(BaseFullReader);
  437. var PDFNodeStreamRangeReader =
  438. /*#__PURE__*/
  439. function (_BaseRangeReader) {
  440. _inherits(PDFNodeStreamRangeReader, _BaseRangeReader);
  441. function PDFNodeStreamRangeReader(stream, start, end) {
  442. var _this4;
  443. _classCallCheck(this, PDFNodeStreamRangeReader);
  444. _this4 = _possibleConstructorReturn(this, _getPrototypeOf(PDFNodeStreamRangeReader).call(this, stream));
  445. _this4._httpHeaders = {};
  446. for (var property in stream.httpHeaders) {
  447. var value = stream.httpHeaders[property];
  448. if (typeof value === 'undefined') {
  449. continue;
  450. }
  451. _this4._httpHeaders[property] = value;
  452. }
  453. _this4._httpHeaders['Range'] = "bytes=".concat(start, "-").concat(end - 1);
  454. var handleResponse = function handleResponse(response) {
  455. if (response.statusCode === 404) {
  456. var error = new _util.MissingPDFException("Missing PDF \"".concat(_this4._url, "\"."));
  457. _this4._storedError = error;
  458. return;
  459. }
  460. _this4._setReadableStream(response);
  461. };
  462. _this4._request = null;
  463. if (_this4._url.protocol === 'http:') {
  464. _this4._request = http.request(createRequestOptions(_this4._url, _this4._httpHeaders), handleResponse);
  465. } else {
  466. _this4._request = https.request(createRequestOptions(_this4._url, _this4._httpHeaders), handleResponse);
  467. }
  468. _this4._request.on('error', function (reason) {
  469. _this4._storedError = reason;
  470. });
  471. _this4._request.end();
  472. return _this4;
  473. }
  474. return PDFNodeStreamRangeReader;
  475. }(BaseRangeReader);
  476. var PDFNodeStreamFsFullReader =
  477. /*#__PURE__*/
  478. function (_BaseFullReader2) {
  479. _inherits(PDFNodeStreamFsFullReader, _BaseFullReader2);
  480. function PDFNodeStreamFsFullReader(stream) {
  481. var _this5;
  482. _classCallCheck(this, PDFNodeStreamFsFullReader);
  483. _this5 = _possibleConstructorReturn(this, _getPrototypeOf(PDFNodeStreamFsFullReader).call(this, stream));
  484. var path = decodeURIComponent(_this5._url.path);
  485. if (fileUriRegex.test(_this5._url.href)) {
  486. path = path.replace(/^\//, '');
  487. }
  488. fs.lstat(path, function (error, stat) {
  489. if (error) {
  490. if (error.code === 'ENOENT') {
  491. error = new _util.MissingPDFException("Missing PDF \"".concat(path, "\"."));
  492. }
  493. _this5._storedError = error;
  494. _this5._headersCapability.reject(error);
  495. return;
  496. }
  497. _this5._contentLength = stat.size;
  498. _this5._setReadableStream(fs.createReadStream(path));
  499. _this5._headersCapability.resolve();
  500. });
  501. return _this5;
  502. }
  503. return PDFNodeStreamFsFullReader;
  504. }(BaseFullReader);
  505. var PDFNodeStreamFsRangeReader =
  506. /*#__PURE__*/
  507. function (_BaseRangeReader2) {
  508. _inherits(PDFNodeStreamFsRangeReader, _BaseRangeReader2);
  509. function PDFNodeStreamFsRangeReader(stream, start, end) {
  510. var _this6;
  511. _classCallCheck(this, PDFNodeStreamFsRangeReader);
  512. _this6 = _possibleConstructorReturn(this, _getPrototypeOf(PDFNodeStreamFsRangeReader).call(this, stream));
  513. var path = decodeURIComponent(_this6._url.path);
  514. if (fileUriRegex.test(_this6._url.href)) {
  515. path = path.replace(/^\//, '');
  516. }
  517. _this6._setReadableStream(fs.createReadStream(path, {
  518. start: start,
  519. end: end - 1
  520. }));
  521. return _this6;
  522. }
  523. return PDFNodeStreamFsRangeReader;
  524. }(BaseRangeReader);