Skip to content

Commit

Permalink
Add support for async/await using Babel
Browse files Browse the repository at this point in the history
For proof-of-concept, this patch converts a couple of `Promise` returning methods to use `async` instead.
Please note that the `generic` build, based on this patch, has been successfully testing in IE11 (i.e. the viewer loads and nothing is obviously broken).

Being able to use modern JavaScript features like `async`/`await` is a huge plus, but there's one (obvious) side-effect: The size of the built files will increase slightly (unless `SKIP_BABEL == true`). That's unavoidable, but seems like a small price to pay in the grand scheme of things.

Finally, note that the `chromium` build target was changed to no longer skip Babel translation, since the Chrome extension still supports version `49` of the browser (where native `async` support isn't available).
  • Loading branch information
Snuffleupagus committed Aug 17, 2018
1 parent 160ca55 commit 783d74a
Show file tree
Hide file tree
Showing 12 changed files with 155 additions and 170 deletions.
2 changes: 1 addition & 1 deletion .eslintrc
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"parserOptions": {
"ecmaVersion": 6,
"ecmaVersion": 8,
"sourceType": "module",
},

Expand Down
1 change: 1 addition & 0 deletions external/builder/preprocessor2.js
Original file line number Diff line number Diff line change
Expand Up @@ -288,6 +288,7 @@ function preprocessPDFJSCode(ctx, code) {
},
};
var parseOptions = {
ecmaVersion: 8,
locations: true,
sourceFile: ctx.sourceFile,
sourceType: 'module',
Expand Down
16 changes: 14 additions & 2 deletions gulpfile.js
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,14 @@ function createWebpackConfig(defines, output) {
exclude: /src[\\\/]core[\\\/](glyphlist|unicode)/,
options: {
presets: skipBabel ? undefined : ['env'],
plugins: ['transform-es2015-modules-commonjs'],
plugins: [
'transform-es2015-modules-commonjs',
['transform-runtime', {
'helpers': false,
'polyfill': false,
'regenerator': true,
}],
],
},
},
{
Expand Down Expand Up @@ -808,7 +815,7 @@ gulp.task('mozcentral', ['mozcentral-pre']);
gulp.task('chromium-pre', ['buildnumber', 'locale'], function () {
console.log();
console.log('### Building Chromium extension');
var defines = builder.merge(DEFINES, { CHROME: true, SKIP_BABEL: true, });
var defines = builder.merge(DEFINES, { CHROME: true, });

var CHROME_BUILD_DIR = BUILD_DIR + '/chromium/',
CHROME_BUILD_CONTENT_DIR = CHROME_BUILD_DIR + '/content/';
Expand Down Expand Up @@ -897,6 +904,11 @@ gulp.task('lib', ['buildnumber'], function () {
presets: noPreset ? undefined : ['env'],
plugins: [
'transform-es2015-modules-commonjs',
['transform-runtime', {
'helpers': false,
'polyfill': false,
'regenerator': true,
}],
babelPluginReplaceNonWebPackRequire,
],
}).code;
Expand Down
32 changes: 15 additions & 17 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
"babel-core": "^6.26.3",
"babel-loader": "^7.1.5",
"babel-plugin-transform-es2015-modules-commonjs": "^6.26.2",
"babel-plugin-transform-runtime": "^6.23.0",
"babel-preset-env": "^1.7.0",
"core-js": "^2.5.7",
"escodegen": "^1.11.0",
Expand Down
20 changes: 9 additions & 11 deletions src/core/evaluator.js
Original file line number Diff line number Diff line change
Expand Up @@ -131,19 +131,17 @@ var PartialEvaluator = (function PartialEvaluatorClosure() {
this.options = options || DefaultPartialEvaluatorOptions;
this.pdfFunctionFactory = pdfFunctionFactory;

this.fetchBuiltInCMap = (name) => {
this.fetchBuiltInCMap = async (name) => {
if (this.builtInCMapCache.has(name)) {
return Promise.resolve(this.builtInCMapCache.get(name));
return this.builtInCMapCache.get(name);
}
return this.handler.sendWithPromise('FetchBuiltInCMap', {
name,
}).then((data) => {
if (data.compressionType !== CMapCompressionType.NONE) {
// Given the size of uncompressed CMaps, only cache compressed ones.
this.builtInCMapCache.set(name, data);
}
return data;
});
const data = await this.handler.sendWithPromise('FetchBuiltInCMap',
{ name, });
if (data.compressionType !== CMapCompressionType.NONE) {
// Given the size of uncompressed CMaps, only cache compressed ones.
this.builtInCMapCache.set(name, data);
}
return data;
};
}

Expand Down
28 changes: 11 additions & 17 deletions src/core/obj.js
Original file line number Diff line number Diff line change
Expand Up @@ -1497,29 +1497,23 @@ var XRef = (function XRefClosure() {
return xrefEntry;
},

fetchIfRefAsync: function XRef_fetchIfRefAsync(obj, suppressEncryption) {
async fetchIfRefAsync(obj, suppressEncryption) {
if (!isRef(obj)) {
return Promise.resolve(obj);
return obj;
}
return this.fetchAsync(obj, suppressEncryption);
},

fetchAsync: function XRef_fetchAsync(ref, suppressEncryption) {
var streamManager = this.stream.manager;
var xref = this;
return new Promise(function tryFetch(resolve, reject) {
try {
resolve(xref.fetch(ref, suppressEncryption));
} catch (e) {
if (e instanceof MissingDataException) {
streamManager.requestRange(e.begin, e.end).then(function () {
tryFetch(resolve, reject);
}, reject);
return;
}
reject(e);
async fetchAsync(ref, suppressEncryption) {
try {
return this.fetch(ref, suppressEncryption);
} catch (ex) {
if (!(ex instanceof MissingDataException)) {
throw ex;
}
});
await this.pdfManager.requestRange(ex.begin, ex.end);
return this.fetchAsync(ref, suppressEncryption);
}
},

getCatalogObj: function XRef_getCatalogObj() {
Expand Down
55 changes: 21 additions & 34 deletions src/core/pdf_manager.js
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ class BasePdfManager {
return this.pdfDocument.cleanup();
}

ensure(obj, prop, args) {
async ensure(obj, prop, args) {
unreachable('Abstract method `ensure` called');
}

Expand Down Expand Up @@ -111,15 +111,12 @@ class LocalPdfManager extends BasePdfManager {
this._loadedStreamPromise = Promise.resolve(stream);
}

ensure(obj, prop, args) {
return new Promise(function(resolve) {
const value = obj[prop];
if (typeof value === 'function') {
resolve(value.apply(obj, args));
} else {
resolve(value);
}
});
async ensure(obj, prop, args) {
const value = obj[prop];
if (typeof value === 'function') {
return value.apply(obj, args);
}
return value;
}

requestRange(begin, end) {
Expand Down Expand Up @@ -155,30 +152,20 @@ class NetworkPdfManager extends BasePdfManager {
this.pdfDocument = new PDFDocument(this, this.streamManager.getStream());
}

ensure(obj, prop, args) {
return new Promise((resolve, reject) => {
let ensureHelper = () => {
try {
const value = obj[prop];
let result;
if (typeof value === 'function') {
result = value.apply(obj, args);
} else {
result = value;
}
resolve(result);
} catch (ex) {
if (!(ex instanceof MissingDataException)) {
reject(ex);
return;
}
this.streamManager.requestRange(ex.begin, ex.end)
.then(ensureHelper, reject);
}
};

ensureHelper();
});
async ensure(obj, prop, args) {
try {
const value = obj[prop];
if (typeof value === 'function') {
return value.apply(obj, args);
}
return value;
} catch (ex) {
if (!(ex instanceof MissingDataException)) {
throw ex;
}
await this.requestRange(ex.begin, ex.end);
return this.ensure(obj, prop, args);
}
}

requestRange(begin, end) {
Expand Down
56 changes: 26 additions & 30 deletions src/display/fetch_stream.js
Original file line number Diff line number Diff line change
Expand Up @@ -152,23 +152,21 @@ class PDFFetchStreamReader {
return this._isStreamingSupported;
}

read() {
return this._headersCapability.promise.then(() => {
return this._reader.read().then(({ value, done, }) => {
if (done) {
return Promise.resolve({ value, done, });
}
this._loaded += value.byteLength;
if (this.onProgress) {
this.onProgress({
loaded: this._loaded,
total: this._contentLength,
});
}
let buffer = new Uint8Array(value).buffer;
return Promise.resolve({ value: buffer, done: false, });
async read() {
await this._headersCapability.promise;
const { value, done, } = await this._reader.read();
if (done) {
return { value, done, };
}
this._loaded += value.byteLength;
if (this.onProgress) {
this.onProgress({
loaded: this._loaded,
total: this._contentLength,
});
});
}
let buffer = new Uint8Array(value).buffer;
return { value: buffer, done: false, };
}

cancel(reason) {
Expand Down Expand Up @@ -223,20 +221,18 @@ class PDFFetchStreamRangeReader {
return this._isStreamingSupported;
}

read() {
return this._readCapability.promise.then(() => {
return this._reader.read().then(({ value, done, }) => {
if (done) {
return Promise.resolve({ value, done, });
}
this._loaded += value.byteLength;
if (this.onProgress) {
this.onProgress({ loaded: this._loaded, });
}
let buffer = new Uint8Array(value).buffer;
return Promise.resolve({ value: buffer, done: false, });
});
});
async read() {
await this._readCapability.promise;
const { value, done, } = await this._reader.read();
if (done) {
return { value, done, };
}
this._loaded += value.byteLength;
if (this.onProgress) {
this.onProgress({ loaded: this._loaded, });
}
let buffer = new Uint8Array(value).buffer;
return { value: buffer, done: false, };
}

cancel(reason) {
Expand Down
Loading

0 comments on commit 783d74a

Please sign in to comment.