node_stream.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  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. this._fullRequestReader?.cancel(reason);
  76. for (const reader of this._rangeRequestReaders.slice(0)) {
  77. reader.cancel(reason);
  78. }
  79. }
  80. }
  81. exports.PDFNodeStream = PDFNodeStream;
  82. class BaseFullReader {
  83. constructor(stream) {
  84. this._url = stream.url;
  85. this._done = false;
  86. this._storedError = null;
  87. this.onProgress = null;
  88. const source = stream.source;
  89. this._contentLength = source.length;
  90. this._loaded = 0;
  91. this._filename = null;
  92. this._disableRange = source.disableRange || false;
  93. this._rangeChunkSize = source.rangeChunkSize;
  94. if (!this._rangeChunkSize && !this._disableRange) {
  95. this._disableRange = true;
  96. }
  97. this._isStreamingSupported = !source.disableStream;
  98. this._isRangeSupported = !source.disableRange;
  99. this._readableStream = null;
  100. this._readCapability = (0, _util.createPromiseCapability)();
  101. this._headersCapability = (0, _util.createPromiseCapability)();
  102. }
  103. get headersReady() {
  104. return this._headersCapability.promise;
  105. }
  106. get filename() {
  107. return this._filename;
  108. }
  109. get contentLength() {
  110. return this._contentLength;
  111. }
  112. get isRangeSupported() {
  113. return this._isRangeSupported;
  114. }
  115. get isStreamingSupported() {
  116. return this._isStreamingSupported;
  117. }
  118. async read() {
  119. await this._readCapability.promise;
  120. if (this._done) {
  121. return {
  122. value: undefined,
  123. done: true
  124. };
  125. }
  126. if (this._storedError) {
  127. throw this._storedError;
  128. }
  129. const chunk = this._readableStream.read();
  130. if (chunk === null) {
  131. this._readCapability = (0, _util.createPromiseCapability)();
  132. return this.read();
  133. }
  134. this._loaded += chunk.length;
  135. this.onProgress?.({
  136. loaded: this._loaded,
  137. total: this._contentLength
  138. });
  139. const buffer = new Uint8Array(chunk).buffer;
  140. return {
  141. value: buffer,
  142. done: false
  143. };
  144. }
  145. cancel(reason) {
  146. if (!this._readableStream) {
  147. this._error(reason);
  148. return;
  149. }
  150. this._readableStream.destroy(reason);
  151. }
  152. _error(reason) {
  153. this._storedError = reason;
  154. this._readCapability.resolve();
  155. }
  156. _setReadableStream(readableStream) {
  157. this._readableStream = readableStream;
  158. readableStream.on("readable", () => {
  159. this._readCapability.resolve();
  160. });
  161. readableStream.on("end", () => {
  162. readableStream.destroy();
  163. this._done = true;
  164. this._readCapability.resolve();
  165. });
  166. readableStream.on("error", reason => {
  167. this._error(reason);
  168. });
  169. if (!this._isStreamingSupported && this._isRangeSupported) {
  170. this._error(new _util.AbortException("streaming is disabled"));
  171. }
  172. if (this._storedError) {
  173. this._readableStream.destroy(this._storedError);
  174. }
  175. }
  176. }
  177. class BaseRangeReader {
  178. constructor(stream) {
  179. this._url = stream.url;
  180. this._done = false;
  181. this._storedError = null;
  182. this.onProgress = null;
  183. this._loaded = 0;
  184. this._readableStream = null;
  185. this._readCapability = (0, _util.createPromiseCapability)();
  186. const source = stream.source;
  187. this._isStreamingSupported = !source.disableStream;
  188. }
  189. get isStreamingSupported() {
  190. return this._isStreamingSupported;
  191. }
  192. async read() {
  193. await this._readCapability.promise;
  194. if (this._done) {
  195. return {
  196. value: undefined,
  197. done: true
  198. };
  199. }
  200. if (this._storedError) {
  201. throw this._storedError;
  202. }
  203. const chunk = this._readableStream.read();
  204. if (chunk === null) {
  205. this._readCapability = (0, _util.createPromiseCapability)();
  206. return this.read();
  207. }
  208. this._loaded += chunk.length;
  209. this.onProgress?.({
  210. loaded: this._loaded
  211. });
  212. const buffer = new Uint8Array(chunk).buffer;
  213. return {
  214. value: buffer,
  215. done: false
  216. };
  217. }
  218. cancel(reason) {
  219. if (!this._readableStream) {
  220. this._error(reason);
  221. return;
  222. }
  223. this._readableStream.destroy(reason);
  224. }
  225. _error(reason) {
  226. this._storedError = reason;
  227. this._readCapability.resolve();
  228. }
  229. _setReadableStream(readableStream) {
  230. this._readableStream = readableStream;
  231. readableStream.on("readable", () => {
  232. this._readCapability.resolve();
  233. });
  234. readableStream.on("end", () => {
  235. readableStream.destroy();
  236. this._done = true;
  237. this._readCapability.resolve();
  238. });
  239. readableStream.on("error", reason => {
  240. this._error(reason);
  241. });
  242. if (this._storedError) {
  243. this._readableStream.destroy(this._storedError);
  244. }
  245. }
  246. }
  247. function createRequestOptions(parsedUrl, headers) {
  248. return {
  249. protocol: parsedUrl.protocol,
  250. auth: parsedUrl.auth,
  251. host: parsedUrl.hostname,
  252. port: parsedUrl.port,
  253. path: parsedUrl.path,
  254. method: "GET",
  255. headers
  256. };
  257. }
  258. class PDFNodeStreamFullReader extends BaseFullReader {
  259. constructor(stream) {
  260. super(stream);
  261. const handleResponse = response => {
  262. if (response.statusCode === 404) {
  263. const error = new _util.MissingPDFException(`Missing PDF "${this._url}".`);
  264. this._storedError = error;
  265. this._headersCapability.reject(error);
  266. return;
  267. }
  268. this._headersCapability.resolve();
  269. this._setReadableStream(response);
  270. const getResponseHeader = name => {
  271. return this._readableStream.headers[name.toLowerCase()];
  272. };
  273. const {
  274. allowRangeRequests,
  275. suggestedLength
  276. } = (0, _network_utils.validateRangeRequestCapabilities)({
  277. getResponseHeader,
  278. isHttp: stream.isHttp,
  279. rangeChunkSize: this._rangeChunkSize,
  280. disableRange: this._disableRange
  281. });
  282. this._isRangeSupported = allowRangeRequests;
  283. this._contentLength = suggestedLength || this._contentLength;
  284. this._filename = (0, _network_utils.extractFilenameFromHeader)(getResponseHeader);
  285. };
  286. this._request = null;
  287. if (this._url.protocol === "http:") {
  288. this._request = http.request(createRequestOptions(this._url, stream.httpHeaders), handleResponse);
  289. } else {
  290. this._request = https.request(createRequestOptions(this._url, stream.httpHeaders), handleResponse);
  291. }
  292. this._request.on("error", reason => {
  293. this._storedError = reason;
  294. this._headersCapability.reject(reason);
  295. });
  296. this._request.end();
  297. }
  298. }
  299. class PDFNodeStreamRangeReader extends BaseRangeReader {
  300. constructor(stream, start, end) {
  301. super(stream);
  302. this._httpHeaders = {};
  303. for (const property in stream.httpHeaders) {
  304. const value = stream.httpHeaders[property];
  305. if (typeof value === "undefined") {
  306. continue;
  307. }
  308. this._httpHeaders[property] = value;
  309. }
  310. this._httpHeaders.Range = `bytes=${start}-${end - 1}`;
  311. const handleResponse = response => {
  312. if (response.statusCode === 404) {
  313. const error = new _util.MissingPDFException(`Missing PDF "${this._url}".`);
  314. this._storedError = error;
  315. return;
  316. }
  317. this._setReadableStream(response);
  318. };
  319. this._request = null;
  320. if (this._url.protocol === "http:") {
  321. this._request = http.request(createRequestOptions(this._url, this._httpHeaders), handleResponse);
  322. } else {
  323. this._request = https.request(createRequestOptions(this._url, this._httpHeaders), handleResponse);
  324. }
  325. this._request.on("error", reason => {
  326. this._storedError = reason;
  327. });
  328. this._request.end();
  329. }
  330. }
  331. class PDFNodeStreamFsFullReader extends BaseFullReader {
  332. constructor(stream) {
  333. super(stream);
  334. let path = decodeURIComponent(this._url.path);
  335. if (fileUriRegex.test(this._url.href)) {
  336. path = path.replace(/^\//, "");
  337. }
  338. fs.lstat(path, (error, stat) => {
  339. if (error) {
  340. if (error.code === "ENOENT") {
  341. error = new _util.MissingPDFException(`Missing PDF "${path}".`);
  342. }
  343. this._storedError = error;
  344. this._headersCapability.reject(error);
  345. return;
  346. }
  347. this._contentLength = stat.size;
  348. this._setReadableStream(fs.createReadStream(path));
  349. this._headersCapability.resolve();
  350. });
  351. }
  352. }
  353. class PDFNodeStreamFsRangeReader extends BaseRangeReader {
  354. constructor(stream, start, end) {
  355. super(stream);
  356. let path = decodeURIComponent(this._url.path);
  357. if (fileUriRegex.test(this._url.href)) {
  358. path = path.replace(/^\//, "");
  359. }
  360. this._setReadableStream(fs.createReadStream(path, {
  361. start,
  362. end: end - 1
  363. }));
  364. }
  365. }