@trickfilm400/rollup-plugin-off-main-thread 2.2.3-fix

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/.github/workflows/ci.yml +32 -0
  2. package/.travis.yml +8 -0
  3. package/CODEOWNERS +1 -0
  4. package/CONTRIBUTING +27 -0
  5. package/CONTRIBUTORS +11 -0
  6. package/Dockerfile +20 -0
  7. package/LICENSE +202 -0
  8. package/README.md +97 -0
  9. package/index.js +318 -0
  10. package/karma.conf.js +46 -0
  11. package/loader.ejs +76 -0
  12. package/package.json +39 -0
  13. package/renovate.json +3 -0
  14. package/run_tests.js +105 -0
  15. package/tests/amd-function-name.test.js +33 -0
  16. package/tests/asset-in-worker.test.js +33 -0
  17. package/tests/dynamic-import.test.js +33 -0
  18. package/tests/fixtures/amd-function-name/a.js +16 -0
  19. package/tests/fixtures/amd-function-name/build/runner.html +15 -0
  20. package/tests/fixtures/amd-function-name/config.json +3 -0
  21. package/tests/fixtures/amd-function-name/entry.js +22 -0
  22. package/tests/fixtures/assets-in-worker/build/assets/my-asset-620b911b.bin +1 -0
  23. package/tests/fixtures/assets-in-worker/build/runner.html +15 -0
  24. package/tests/fixtures/assets-in-worker/entry.js +17 -0
  25. package/tests/fixtures/assets-in-worker/rollup.config.js +25 -0
  26. package/tests/fixtures/assets-in-worker/worker.js +18 -0
  27. package/tests/fixtures/dynamic-import/a.js +16 -0
  28. package/tests/fixtures/dynamic-import/build/runner.html +15 -0
  29. package/tests/fixtures/dynamic-import/entry.js +14 -0
  30. package/tests/fixtures/empty.js +0 -0
  31. package/tests/fixtures/import-meta/a.js +16 -0
  32. package/tests/fixtures/import-meta/build/runner.html +15 -0
  33. package/tests/fixtures/import-meta/entry.js +14 -0
  34. package/tests/fixtures/import-meta-worker/a.js +12 -0
  35. package/tests/fixtures/import-meta-worker/build/runner.html +15 -0
  36. package/tests/fixtures/import-meta-worker/entry.js +22 -0
  37. package/tests/fixtures/import-worker-url/a.js +16 -0
  38. package/tests/fixtures/import-worker-url/b.js +16 -0
  39. package/tests/fixtures/import-worker-url/build/runner.html +15 -0
  40. package/tests/fixtures/import-worker-url/entry.js +21 -0
  41. package/tests/fixtures/import-worker-url/worker.js +17 -0
  42. package/tests/fixtures/import-worker-url-custom-scheme/a.js +16 -0
  43. package/tests/fixtures/import-worker-url-custom-scheme/b.js +16 -0
  44. package/tests/fixtures/import-worker-url-custom-scheme/build/runner.html +15 -0
  45. package/tests/fixtures/import-worker-url-custom-scheme/config.json +3 -0
  46. package/tests/fixtures/import-worker-url-custom-scheme/entry.js +21 -0
  47. package/tests/fixtures/import-worker-url-custom-scheme/worker.js +17 -0
  48. package/tests/fixtures/module-worker/a.js +20 -0
  49. package/tests/fixtures/module-worker/b.js +20 -0
  50. package/tests/fixtures/module-worker/build/runner.html +15 -0
  51. package/tests/fixtures/module-worker/entry.js +17 -0
  52. package/tests/fixtures/module-worker/rollup.config.js +4 -0
  53. package/tests/fixtures/module-worker/worker.js +17 -0
  54. package/tests/fixtures/more-workers/a.js +16 -0
  55. package/tests/fixtures/more-workers/b.js +16 -0
  56. package/tests/fixtures/more-workers/build/runner.html +15 -0
  57. package/tests/fixtures/more-workers/entry.js +34 -0
  58. package/tests/fixtures/more-workers/worker_a.js +16 -0
  59. package/tests/fixtures/more-workers/worker_b.js +18 -0
  60. package/tests/fixtures/public-path/a.js +16 -0
  61. package/tests/fixtures/public-path/build/runner.html +15 -0
  62. package/tests/fixtures/public-path/config.json +3 -0
  63. package/tests/fixtures/public-path/entry.js +14 -0
  64. package/tests/fixtures/simple-bundle/a.js +16 -0
  65. package/tests/fixtures/simple-bundle/build/runner.html +15 -0
  66. package/tests/fixtures/simple-bundle/entry.js +16 -0
  67. package/tests/fixtures/single-default/a.js +14 -0
  68. package/tests/fixtures/single-default/build/runner.html +15 -0
  69. package/tests/fixtures/single-default/entry.js +16 -0
  70. package/tests/fixtures/url-import-meta-worker/a.js +17 -0
  71. package/tests/fixtures/url-import-meta-worker/b.js +16 -0
  72. package/tests/fixtures/url-import-meta-worker/build/runner.html +15 -0
  73. package/tests/fixtures/url-import-meta-worker/entry.js +20 -0
  74. package/tests/fixtures/url-import-meta-worker/worker.js +16 -0
  75. package/tests/fixtures/worker/a.js +17 -0
  76. package/tests/fixtures/worker/b.js +16 -0
  77. package/tests/fixtures/worker/build/runner.html +15 -0
  78. package/tests/fixtures/worker/entry.js +18 -0
  79. package/tests/fixtures/worker/worker.js +16 -0
  80. package/tests/import-meta-worker.test.js +37 -0
  81. package/tests/import-meta.test.js +33 -0
  82. package/tests/import-worker-url-custom-scheme.test.js +42 -0
  83. package/tests/import-worker-url.test.js +41 -0
  84. package/tests/module-worker.test.js +47 -0
  85. package/tests/more-workers.test.js +33 -0
  86. package/tests/public-path.test.js +33 -0
  87. package/tests/simple-bundle.test.js +33 -0
  88. package/tests/single-default.test.js +33 -0
  89. package/tests/url-import-meta-worker.test.js +34 -0
  90. package/tests/worker.test.js +33 -0
package/index.js ADDED
@@ -0,0 +1,318 @@
1
+ /**
2
+ * Copyright 2018 Google Inc. All Rights Reserved.
3
+ * Licensed under the Apache License, Version 2.0 (the "License");
4
+ * you may not use this file except in compliance with the License.
5
+ * You may obtain a copy of the License at
6
+ * http://www.apache.org/licenses/LICENSE-2.0
7
+ * Unless required by applicable law or agreed to in writing, software
8
+ * distributed under the License is distributed on an "AS IS" BASIS,
9
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10
+ * See the License for the specific language governing permissions and
11
+ * limitations under the License.
12
+ */
13
+
14
+ "use strict";
15
+
16
+ const { readFileSync } = require("fs");
17
+ const { join } = require("path");
18
+ const ejs = require("ejs");
19
+ const MagicString = require("magic-string");
20
+ const json5 = require("json5");
21
+ // See https://github.com/surma/rollup-plugin-off-main-thread/issues/49
22
+ const matchAll = require("string.prototype.matchall");
23
+
24
+ const defaultOpts = {
25
+ // A string containing the EJS template for the amd loader. If `undefined`,
26
+ // OMT will use `loader.ejs`.
27
+ loader: readFileSync(join(__dirname, "/loader.ejs"), "utf8"),
28
+ // Use `fetch()` + `eval()` to load dependencies instead of `<script>` tags
29
+ // and `importScripts()`. _This is not CSP compliant, but is required if you
30
+ // want to use dynamic imports in ServiceWorker_.
31
+ useEval: false,
32
+ // Function name to use instead of AMD’s `define`.
33
+ amdFunctionName: "define",
34
+ // A function that determines whether the loader code should be prepended to a
35
+ // certain chunk. Should return true if the load is supposed to be prepended.
36
+ prependLoader: (chunk, workerFiles) =>
37
+ chunk.isEntry || workerFiles.includes(chunk.facadeModuleId),
38
+ // The scheme used when importing workers as a URL.
39
+ urlLoaderScheme: "omt",
40
+ // Silence the warning about ESM being badly supported in workers.
41
+ silenceESMWorkerWarning: false
42
+ };
43
+
44
+ // A regexp to find static `new Worker` invocations.
45
+ // Matches `new Worker(...file part...`
46
+ // File part matches one of:
47
+ // - '...'
48
+ // - "..."
49
+ // - `import.meta.url`
50
+ // - new URL('...', import.meta.url)
51
+ // - new URL("...", import.meta.url)
52
+ const workerRegexpForTransform = /(new\s+Worker\()\s*(('.*?'|".*?")|import\.meta\.url|new\s+URL\(('.*?'|".*?"),\s*import\.meta\.url\))/gs;
53
+
54
+ // A regexp to find static `new Worker` invocations we've rewritten during the transform phase.
55
+ // Matches `new Worker(...file part..., ...options...`.
56
+ // File part matches one of:
57
+ // - new URL('...', module.uri)
58
+ // - new URL("...", module.uri)
59
+ const workerRegexpForOutput = /new\s+Worker\(new\s+URL\((?:'.*?'|".*?"),\s*module\.uri\)\s*(,([^)]+))/gs;
60
+
61
+ let longWarningAlreadyShown = false;
62
+
63
+ module.exports = function(opts = {}) {
64
+ opts = Object.assign({}, defaultOpts, opts);
65
+
66
+ opts.loader = ejs.render(opts.loader, opts);
67
+
68
+ const urlLoaderPrefix = opts.urlLoaderScheme + ":";
69
+
70
+ let workerFiles;
71
+ let isEsmOutput = () => { throw new Error("outputOptions hasn't been called yet") };
72
+ return {
73
+ name: "off-main-thread",
74
+
75
+ async buildStart(options) {
76
+ workerFiles = [];
77
+ },
78
+
79
+ async resolveId(id, importer) {
80
+ if (!id.startsWith(urlLoaderPrefix)) return;
81
+
82
+ const path = id.slice(urlLoaderPrefix.length);
83
+ const resolved = await this.resolve(path, importer);
84
+ if (!resolved)
85
+ throw Error(`Cannot find module '${path}' from '${importer}'`);
86
+ const newId = resolved.id;
87
+
88
+ return urlLoaderPrefix + newId;
89
+ },
90
+
91
+ load(id) {
92
+ if (!id.startsWith(urlLoaderPrefix)) return;
93
+
94
+ const realId = id.slice(urlLoaderPrefix.length);
95
+ const chunkRef = this.emitFile({ id: realId, type: "chunk" });
96
+ return `export default import.meta.ROLLUP_FILE_URL_${chunkRef};`;
97
+ },
98
+
99
+ async transform(code, id) {
100
+ const ms = new MagicString(code);
101
+
102
+ const replacementPromises = [];
103
+
104
+ for (const match of matchAll(code, workerRegexpForTransform)) {
105
+ let [
106
+ fullMatch,
107
+ partBeforeArgs,
108
+ workerSource,
109
+ directWorkerFile,
110
+ workerFile,
111
+ ] = match;
112
+
113
+ const workerParametersEndIndex = match.index + fullMatch.length;
114
+ const matchIndex = match.index;
115
+ const workerParametersStartIndex = matchIndex + partBeforeArgs.length;
116
+
117
+ let workerIdPromise;
118
+ if (workerSource === "import.meta.url") {
119
+ // Turn the current file into a chunk
120
+ workerIdPromise = Promise.resolve(id);
121
+ } else {
122
+ // Otherwise it's a string literal either directly or in the `new URL(...)`.
123
+ if (directWorkerFile) {
124
+ const fullMatchWithOpts = `${fullMatch}, …)`;
125
+ const fullReplacement = `new Worker(new URL(${directWorkerFile}, import.meta.url), …)`;
126
+
127
+ if (!longWarningAlreadyShown) {
128
+ this.warn(
129
+ `rollup-plugin-off-main-thread:
130
+ \`${fullMatchWithOpts}\` suggests that the Worker should be relative to the document, not the script.
131
+ In the bundler, we don't know what the final document's URL will be, and instead assume it's a URL relative to the current module.
132
+ This might lead to incorrect behaviour during runtime.
133
+ If you did mean to use a URL relative to the current module, please change your code to the following form:
134
+ \`${fullReplacement}\`
135
+ This will become a hard error in the future.`,
136
+ matchIndex
137
+ );
138
+ longWarningAlreadyShown = true;
139
+ } else {
140
+ this.warn(
141
+ `rollup-plugin-off-main-thread: Treating \`${fullMatchWithOpts}\` as \`${fullReplacement}\``,
142
+ matchIndex
143
+ );
144
+ }
145
+ workerFile = directWorkerFile;
146
+ }
147
+
148
+ // Cut off surrounding quotes.
149
+ workerFile = workerFile.slice(1, -1);
150
+
151
+ if (!/^\.{1,2}\//.test(workerFile)) {
152
+ let isError = false;
153
+ if (directWorkerFile) {
154
+ // If direct worker file, it must be in `./something` form.
155
+ isError = true;
156
+ } else {
157
+ // If `new URL(...)` it can be in `new URL('something', import.meta.url)` form too,
158
+ // so just check it's not absolute.
159
+ if (/^(\/|https?:)/.test(workerFile)) {
160
+ isError = true;
161
+ } else {
162
+ // If it does turn out to be `new URL('something', import.meta.url)` form,
163
+ // prepend `./` so that it becomes valid module specifier.
164
+ workerFile = `./${workerFile}`;
165
+ }
166
+ }
167
+ if (isError) {
168
+ this.warn(
169
+ `Paths passed to the Worker constructor must be relative to the current file, i.e. start with ./ or ../ (just like dynamic import!). Ignoring "${workerFile}".`,
170
+ matchIndex
171
+ );
172
+ continue;
173
+ }
174
+ }
175
+
176
+ workerIdPromise = this.resolve(workerFile, id).then(res => res.id);
177
+ }
178
+
179
+ replacementPromises.push(
180
+ (async () => {
181
+ const resolvedWorkerFile = await workerIdPromise;
182
+ workerFiles.push(resolvedWorkerFile);
183
+ const chunkRefId = this.emitFile({
184
+ id: resolvedWorkerFile,
185
+ type: "chunk"
186
+ });
187
+
188
+ ms.overwrite(
189
+ workerParametersStartIndex,
190
+ workerParametersEndIndex,
191
+ `new URL(import.meta.ROLLUP_FILE_URL_${chunkRefId}, import.meta.url)`
192
+ );
193
+ })()
194
+ );
195
+ }
196
+
197
+ // No matches found.
198
+ if (!replacementPromises.length) {
199
+ return;
200
+ }
201
+
202
+ // Wait for all the scheduled replacements to finish.
203
+ await Promise.all(replacementPromises);
204
+
205
+ return {
206
+ code: ms.toString(),
207
+ map: ms.generateMap({ hires: true })
208
+ };
209
+ },
210
+
211
+ resolveFileUrl(chunk) {
212
+ return JSON.stringify(chunk.relativePath);
213
+ },
214
+
215
+ outputOptions({ format }) {
216
+ if (format === "esm" || format === "es") {
217
+ if (!opts.silenceESMWorkerWarning) {
218
+ this.warn(
219
+ 'Very few browsers support ES modules in Workers. If you want to your code to run in all browsers, set `output.format = "amd";`'
220
+ );
221
+ }
222
+ // In ESM, we never prepend a loader.
223
+ isEsmOutput = () => true;
224
+ } else if (format !== "amd") {
225
+ this.error(
226
+ `\`output.format\` must either be "amd" or "esm", got "${format}"`
227
+ );
228
+ } else {
229
+ isEsmOutput = () => false;
230
+ }
231
+ },
232
+
233
+ renderDynamicImport() {
234
+ if (isEsmOutput()) return;
235
+
236
+ // In our loader, `require` simply return a promise directly.
237
+ // This is tinier and simpler output than the Rollup's default.
238
+ return {
239
+ left: 'require(',
240
+ right: ')'
241
+ };
242
+ },
243
+
244
+ resolveImportMeta(property) {
245
+ if (isEsmOutput()) return;
246
+
247
+ if (property === 'url') {
248
+ // In our loader, `module.uri` is already fully resolved
249
+ // so we can emit something shorter than the Rollup's default.
250
+ return `module.uri`;
251
+ }
252
+ },
253
+
254
+ renderChunk(code, chunk, outputOptions) {
255
+ // We don’t need to do any loader processing when targeting ESM format.
256
+ if (isEsmOutput()) return;
257
+
258
+ if (outputOptions.banner && outputOptions.banner.length > 0) {
259
+ this.error(
260
+ "OMT currently doesn’t work with `banner`. Feel free to submit a PR at https://github.com/trickfilm400/rollup-plugin-off-main-thread"
261
+ );
262
+ return;
263
+ }
264
+ const ms = new MagicString(code);
265
+
266
+ for (const match of matchAll(code, workerRegexpForOutput)) {
267
+ let [fullMatch, optionsWithCommaStr, optionsStr] = match;
268
+ let options;
269
+ try {
270
+ options = json5.parse(optionsStr);
271
+ } catch (e) {
272
+ // If we couldn't parse the options object, maybe it's something dynamic or has nested
273
+ // parentheses or something like that. In that case, treat it as a warning
274
+ // and not a hard error, just like we wouldn't break on unmatched regex.
275
+ console.warn("Couldn't match options object", fullMatch, ": ", e);
276
+ continue;
277
+ }
278
+ if (!("type" in options)) {
279
+ // Nothing to do.
280
+ continue;
281
+ }
282
+ delete options.type;
283
+ const replacementEnd = match.index + fullMatch.length;
284
+ const replacementStart = replacementEnd - optionsWithCommaStr.length;
285
+ optionsStr = json5.stringify(options);
286
+ optionsWithCommaStr = optionsStr === "{}" ? "" : `, ${optionsStr}`;
287
+ ms.overwrite(
288
+ replacementStart,
289
+ replacementEnd,
290
+ optionsWithCommaStr
291
+ );
292
+ }
293
+
294
+ // Mangle define() call
295
+ ms.remove(0, "define(".length);
296
+ // If the module does not have any dependencies, it’s technically okay
297
+ // to skip the dependency array. But our minimal loader expects it, so
298
+ // we add it back in.
299
+ if (!code.startsWith("define([")) {
300
+ ms.prepend("[],");
301
+ }
302
+ ms.prepend(`${opts.amdFunctionName}(`);
303
+
304
+ // Prepend loader if it’s an entry point or a worker file
305
+ if (opts.prependLoader(chunk, workerFiles)) {
306
+ ms.prepend(opts.loader);
307
+ }
308
+
309
+ const newCode = ms.toString();
310
+ const hasCodeChanged = code !== newCode;
311
+ return {
312
+ code: newCode,
313
+ // Avoid generating sourcemaps if possible as it can be a very expensive operation
314
+ map: hasCodeChanged ? ms.generateMap({ hires: true }) : null
315
+ };
316
+ }
317
+ };
318
+ };
package/karma.conf.js ADDED
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Copyright 2018 Google Inc. All Rights Reserved.
3
+ * Licensed under the Apache License, Version 2.0 (the "License");
4
+ * you may not use this file except in compliance with the License.
5
+ * You may obtain a copy of the License at
6
+ * http://www.apache.org/licenses/LICENSE-2.0
7
+ * Unless required by applicable law or agreed to in writing, software
8
+ * distributed under the License is distributed on an "AS IS" BASIS,
9
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10
+ * See the License for the specific language governing permissions and
11
+ * limitations under the License.
12
+ */
13
+
14
+ module.exports = function(config) {
15
+ const configuration = {
16
+ basePath: "",
17
+ frameworks: ["mocha", "chai"],
18
+ files: [
19
+ {
20
+ pattern: "tests/fixtures/**",
21
+ included: false
22
+ },
23
+ {
24
+ pattern: "tests/*.test.js"
25
+ }
26
+ ],
27
+ reporters: ["progress"],
28
+ port: 9876,
29
+ colors: true,
30
+ logLevel: config.LOG_INFO,
31
+ autoWatch: true,
32
+ singleRun: true,
33
+ concurrency: 1,
34
+ browsers: ["Chrome", "Firefox", "Safari"],
35
+ customLaunchers: {
36
+ DockerChrome: {
37
+ base: "ChromeHeadless",
38
+ flags: ["--no-sandbox"]
39
+ }
40
+ }
41
+ };
42
+
43
+ if (process.env.INSIDE_DOCKER) configuration.browsers = ["DockerChrome"];
44
+
45
+ config.set(configuration);
46
+ };
package/loader.ejs ADDED
@@ -0,0 +1,76 @@
1
+ /**
2
+ * Copyright 2018 Google Inc. All Rights Reserved.
3
+ * Licensed under the Apache License, Version 2.0 (the "License");
4
+ * you may not use this file except in compliance with the License.
5
+ * You may obtain a copy of the License at
6
+ * http://www.apache.org/licenses/LICENSE-2.0
7
+ * Unless required by applicable law or agreed to in writing, software
8
+ * distributed under the License is distributed on an "AS IS" BASIS,
9
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10
+ * See the License for the specific language governing permissions and
11
+ * limitations under the License.
12
+ */
13
+
14
+ // If the loader is already loaded, just stop.
15
+ if (!self.<%- amdFunctionName %>) {
16
+ let registry = {};
17
+
18
+ // Used for `eval` and `importScripts` where we can't get script URL by other means.
19
+ // In both cases, it's safe to use a global var because those functions are synchronous.
20
+ let nextDefineUri;
21
+
22
+ const singleRequire = (uri, parentUri) => {
23
+ uri = new URL(uri + ".js", parentUri).href;
24
+ return registry[uri] || (
25
+ <% if (useEval) { %>
26
+ fetch(uri)
27
+ .then(resp => resp.text())
28
+ .then(code => {
29
+ nextDefineUri = uri;
30
+ eval(code);
31
+ })
32
+ <% } else { %>
33
+ new Promise(resolve => {
34
+ if ("document" in self) {
35
+ const script = document.createElement("script");
36
+ script.src = uri;
37
+ script.onload = resolve;
38
+ document.head.appendChild(script);
39
+ } else {
40
+ nextDefineUri = uri;
41
+ importScripts(uri);
42
+ resolve();
43
+ }
44
+ })
45
+ <% } %>
46
+ .then(() => {
47
+ let promise = registry[uri];
48
+ if (!promise) {
49
+ throw new Error(`Module ${uri} didn’t register its module`);
50
+ }
51
+ return promise;
52
+ })
53
+ );
54
+ };
55
+
56
+ self.<%- amdFunctionName %> = (depsNames, factory) => {
57
+ const uri = nextDefineUri || ("document" in self ? document.currentScript.src : "") || location.href;
58
+ if (registry[uri]) {
59
+ // Module is already loading or loaded.
60
+ return;
61
+ }
62
+ let exports = {};
63
+ const require = depUri => singleRequire(depUri, uri);
64
+ const specialDeps = {
65
+ module: { uri },
66
+ exports,
67
+ require
68
+ };
69
+ registry[uri] = Promise.all(depsNames.map(
70
+ depName => specialDeps[depName] || require(depName)
71
+ )).then(deps => {
72
+ factory(...deps);
73
+ return exports;
74
+ });
75
+ };
76
+ }
package/package.json ADDED
@@ -0,0 +1,39 @@
1
+ {
2
+ "name": "@trickfilm400/rollup-plugin-off-main-thread",
3
+ "version": "2.2.3-fix",
4
+ "description": "Use Rollup with workers and ES6 modules today.",
5
+ "main": "index.js",
6
+ "scripts": {
7
+ "fmt": "prettier --write 'tests/**/*.js' *.js *.md *.json",
8
+ "test": "node ./run_tests.js"
9
+ },
10
+ "author": "Surma <surma@google.com>",
11
+ "contributors": [
12
+ "trickfilm400 <trickfilm400@gmail.com>"
13
+ ],
14
+ "license": "Apache-2.0",
15
+ "devDependencies": {
16
+ "chai": "4.2.0",
17
+ "chalk": "^2.4.2",
18
+ "karma": "4.2.0",
19
+ "karma-chai": "0.1.0",
20
+ "karma-chrome-launcher": "3.0.0",
21
+ "karma-firefox-launcher": "1.1.0",
22
+ "karma-mocha": "1.3.0",
23
+ "karma-safari-launcher": "1.0.0",
24
+ "karma-safaritechpreview-launcher": "2.0.2",
25
+ "mocha": "6.1.4",
26
+ "prettier": "1.18.2",
27
+ "rollup": "2.2.0"
28
+ },
29
+ "repository": {
30
+ "type": "git",
31
+ "url": "https://github.com/trickfilm400/rollup-plugin-off-main-thread"
32
+ },
33
+ "dependencies": {
34
+ "ejs": "^3.1.6",
35
+ "json5": "^2.2.0",
36
+ "magic-string": "^0.25.0",
37
+ "string.prototype.matchall": "^4.0.6"
38
+ }
39
+ }
package/renovate.json ADDED
@@ -0,0 +1,3 @@
1
+ {
2
+ "extends": ["config:base"]
3
+ }
package/run_tests.js ADDED
@@ -0,0 +1,105 @@
1
+ /**
2
+ * Copyright 2018 Google Inc. All Rights Reserved.
3
+ * Licensed under the Apache License, Version 2.0 (the "License");
4
+ * you may not use this file except in compliance with the License.
5
+ * You may obtain a copy of the License at
6
+ * http://www.apache.org/licenses/LICENSE-2.0
7
+ * Unless required by applicable law or agreed to in writing, software
8
+ * distributed under the License is distributed on an "AS IS" BASIS,
9
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10
+ * See the License for the specific language governing permissions and
11
+ * limitations under the License.
12
+ */
13
+
14
+ const rollup = require("rollup");
15
+ const path = require("path");
16
+ const omt = require(".");
17
+ const fs = require("fs");
18
+ const chalk = require("chalk");
19
+
20
+ const karma = require("karma");
21
+ const myKarmaConfig = require("./karma.conf.js");
22
+
23
+ async function fileExists(file) {
24
+ try {
25
+ const stat = await fs.promises.stat(file);
26
+ return stat.isFile();
27
+ } catch (e) {
28
+ return false;
29
+ }
30
+ }
31
+
32
+ async function init() {
33
+ await Promise.all(
34
+ [
35
+ "./tests/fixtures/simple-bundle/entry.js",
36
+ "./tests/fixtures/import-meta/entry.js",
37
+ "./tests/fixtures/dynamic-import/entry.js",
38
+ "./tests/fixtures/public-path/entry.js",
39
+ "./tests/fixtures/worker/entry.js",
40
+ "./tests/fixtures/module-worker/entry.js",
41
+ "./tests/fixtures/more-workers/entry.js",
42
+ "./tests/fixtures/amd-function-name/entry.js",
43
+ "./tests/fixtures/single-default/entry.js",
44
+ "./tests/fixtures/import-worker-url/entry.js",
45
+ "./tests/fixtures/import-meta-worker/entry.js",
46
+ "./tests/fixtures/import-worker-url-custom-scheme/entry.js",
47
+ "./tests/fixtures/assets-in-worker/entry.js",
48
+ "./tests/fixtures/url-import-meta-worker/entry.js"
49
+ ].map(async input => {
50
+ const pathName = path.dirname(input);
51
+ const outputOptions = {
52
+ dir: path.join(pathName, "build"),
53
+ format: "amd"
54
+ };
55
+ let rollupConfig = {
56
+ input,
57
+ strictDeprecations: true,
58
+ // Copied / adapted from default `onwarn` in Rollup CLI.
59
+ onwarn: warning => {
60
+ console.warn(`⚠️ ${chalk.bold(warning.message)}`);
61
+
62
+ if (warning.url) {
63
+ console.warn(chalk.cyan(warning.url));
64
+ }
65
+
66
+ if (warning.loc) {
67
+ console.warn(
68
+ `${warning.loc.file} (${warning.loc.line}:${warning.loc.column})`
69
+ );
70
+ }
71
+
72
+ if (warning.frame) {
73
+ console.warn(chalk.dim(warning.frame));
74
+ }
75
+
76
+ console.warn("");
77
+ }
78
+ };
79
+ const rollupConfigPath = "./" + path.join(pathName, "rollup.config.js");
80
+ const configPath = "./" + path.join(pathName, "config.json");
81
+ if (await fileExists(rollupConfigPath)) {
82
+ require(rollupConfigPath)(rollupConfig, outputOptions, omt);
83
+ } else if (await fileExists(configPath)) {
84
+ rollupConfig.plugins = [omt(require(configPath))];
85
+ } else {
86
+ rollupConfig.plugins = [omt()];
87
+ }
88
+ const bundle = await rollup.rollup(rollupConfig);
89
+ await bundle.write(outputOptions);
90
+ })
91
+ );
92
+
93
+ const karmaConfig = { port: 9876 };
94
+ myKarmaConfig({
95
+ set(config) {
96
+ Object.assign(karmaConfig, config);
97
+ }
98
+ });
99
+ const server = new karma.Server(karmaConfig, code => {
100
+ console.log(`Karma exited with code ${code}`);
101
+ process.exit(code);
102
+ });
103
+ server.start();
104
+ }
105
+ init();
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Copyright 2018 Google Inc. All Rights Reserved.
3
+ * Licensed under the Apache License, Version 2.0 (the "License");
4
+ * you may not use this file except in compliance with the License.
5
+ * You may obtain a copy of the License at
6
+ * http://www.apache.org/licenses/LICENSE-2.0
7
+ * Unless required by applicable law or agreed to in writing, software
8
+ * distributed under the License is distributed on an "AS IS" BASIS,
9
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10
+ * See the License for the specific language governing permissions and
11
+ * limitations under the License.
12
+ */
13
+
14
+ describe("AMD Function Name", function() {
15
+ beforeEach(function() {
16
+ this.ifr = document.createElement("iframe");
17
+ document.body.append(this.ifr);
18
+ });
19
+
20
+ afterEach(function() {
21
+ this.ifr.remove();
22
+ });
23
+
24
+ it("loads with a different AMD function name", function(done) {
25
+ window.addEventListener("message", function l(ev) {
26
+ if (ev.data === "a") {
27
+ window.removeEventListener("message", l);
28
+ done();
29
+ }
30
+ });
31
+ this.ifr.src = "/base/tests/fixtures/amd-function-name/build/runner.html";
32
+ });
33
+ });
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Copyright 2018 Google Inc. All Rights Reserved.
3
+ * Licensed under the Apache License, Version 2.0 (the "License");
4
+ * you may not use this file except in compliance with the License.
5
+ * You may obtain a copy of the License at
6
+ * http://www.apache.org/licenses/LICENSE-2.0
7
+ * Unless required by applicable law or agreed to in writing, software
8
+ * distributed under the License is distributed on an "AS IS" BASIS,
9
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10
+ * See the License for the specific language governing permissions and
11
+ * limitations under the License.
12
+ */
13
+
14
+ describe("Assets in workers", function() {
15
+ beforeEach(function() {
16
+ this.ifr = document.createElement("iframe");
17
+ document.body.append(this.ifr);
18
+ });
19
+
20
+ afterEach(function() {
21
+ this.ifr.remove();
22
+ });
23
+
24
+ it("can be fetched", function(done) {
25
+ window.addEventListener("message", function l(ev) {
26
+ if (ev.data === "assetcontent") {
27
+ window.removeEventListener("message", l);
28
+ done();
29
+ }
30
+ });
31
+ this.ifr.src = "/base/tests/fixtures/assets-in-worker/build/runner.html";
32
+ });
33
+ });
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Copyright 2018 Google Inc. All Rights Reserved.
3
+ * Licensed under the Apache License, Version 2.0 (the "License");
4
+ * you may not use this file except in compliance with the License.
5
+ * You may obtain a copy of the License at
6
+ * http://www.apache.org/licenses/LICENSE-2.0
7
+ * Unless required by applicable law or agreed to in writing, software
8
+ * distributed under the License is distributed on an "AS IS" BASIS,
9
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10
+ * See the License for the specific language governing permissions and
11
+ * limitations under the License.
12
+ */
13
+
14
+ describe("Dynamic import", function() {
15
+ beforeEach(function() {
16
+ this.ifr = document.createElement("iframe");
17
+ document.body.append(this.ifr);
18
+ });
19
+
20
+ afterEach(function() {
21
+ this.ifr.remove();
22
+ });
23
+
24
+ it("loads transpiled modules", function(done) {
25
+ window.addEventListener("message", function l(ev) {
26
+ if (ev.data === "a") {
27
+ window.removeEventListener("message", l);
28
+ done();
29
+ }
30
+ });
31
+ this.ifr.src = "/base/tests/fixtures/dynamic-import/build/runner.html";
32
+ });
33
+ });