From 3d3796c1e97cead4a2699e83d51ddb7f20b70aa6 Mon Sep 17 00:00:00 2001 From: Marnix Kok Date: Sun, 9 Oct 2022 01:51:40 +1300 Subject: [PATCH] Make library compatible with workers When using Handlebars in a Cloudflare Worker, an environment in which the `window` and `global` objects both don't exist, an error is thrown about `window` being undefined. According to the ECMA specification, only `self` is available in a worker. Since we support old runtimes in our 4.x branch, we can't use `globalThis` but have to use a polyfill. --- lib/handlebars/no-conflict.js | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/lib/handlebars/no-conflict.js b/lib/handlebars/no-conflict.js index f89e7aa9..91ef1da5 100644 --- a/lib/handlebars/no-conflict.js +++ b/lib/handlebars/no-conflict.js @@ -1,12 +1,22 @@ -/* global global, window */ +/* global globalThis */ export default function(Handlebars) { /* istanbul ignore next */ - let root = typeof global !== 'undefined' ? global : window, - $Handlebars = root.Handlebars; + // https://mathiasbynens.be/notes/globalthis + (function() { + if (typeof globalThis === 'object') return; + Object.prototype.__defineGetter__('__magic__', function() { + return this; + }); + __magic__.globalThis = __magic__; // eslint-disable-line no-undef + delete Object.prototype.__magic__; + })(); + + const $Handlebars = globalThis.Handlebars; + /* istanbul ignore next */ Handlebars.noConflict = function() { - if (root.Handlebars === Handlebars) { - root.Handlebars = $Handlebars; + if (globalThis.Handlebars === Handlebars) { + globalThis.Handlebars = $Handlebars; } return Handlebars; };