@embroider/vite 0.1.2-unstable.a3ff5ed → 0.1.2

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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2018 Edward Faulkner
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/package.json CHANGED
@@ -1,10 +1,10 @@
1
1
  {
2
2
  "name": "@embroider/vite",
3
- "version": "0.1.2-unstable.a3ff5ed",
3
+ "version": "0.1.2",
4
4
  "main": "index.mjs",
5
5
  "peerDependencies": {
6
- "@embroider/core": "3.2.2-unstable.a3ff5ed",
7
- "vite": "^4.3.9"
6
+ "vite": "^4.3.9",
7
+ "@embroider/core": "^3.2.1"
8
8
  },
9
9
  "dependencies": {
10
10
  "@rollup/pluginutils": "^4.1.1",
@@ -17,11 +17,18 @@
17
17
  "terser": "^5.7.0"
18
18
  },
19
19
  "devDependencies": {
20
- "@embroider/core": "3.2.2-unstable.a3ff5ed",
21
20
  "@types/debug": "^4.1.5",
22
21
  "@types/jsdom": "^16.2.11",
23
22
  "@types/fs-extra": "^9.0.12",
24
23
  "rollup": "^3.23.0",
25
- "vite": "^4.3.9"
26
- }
27
- }
24
+ "vite": "^4.3.9",
25
+ "@embroider/core": "^3.2.1"
26
+ },
27
+ "files": [
28
+ "index.mjs",
29
+ "index.d.ts",
30
+ "src/**/*.js",
31
+ "src/**/*.d.ts",
32
+ "src/**/*.js.map"
33
+ ]
34
+ }
@@ -0,0 +1 @@
1
+ export declare function addons(root: string): string[];
package/src/addons.js ADDED
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.addons = void 0;
4
+ const core_1 = require("@embroider/core");
5
+ function addons(root) {
6
+ let rloader = new core_1.ResolverLoader(root);
7
+ let { options } = rloader.resolver;
8
+ let names = new Set();
9
+ for (let from of Object.keys(options.renameModules)) {
10
+ let pName = (0, core_1.packageName)(from);
11
+ if (pName) {
12
+ names.add(pName);
13
+ }
14
+ }
15
+ for (let from of Object.keys(options.renamePackages)) {
16
+ names.add(from);
17
+ }
18
+ for (let name of Object.keys(options.activeAddons)) {
19
+ names.add(name);
20
+ }
21
+ return [...names];
22
+ }
23
+ exports.addons = addons;
24
+ //# sourceMappingURL=addons.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"addons.js","sourceRoot":"","sources":["addons.ts"],"names":[],"mappings":";;;AAAA,0CAA8D;AAE9D,SAAgB,MAAM,CAAC,IAAY;IACjC,IAAI,OAAO,GAAG,IAAI,qBAAc,CAAC,IAAI,CAAC,CAAC;IACvC,IAAI,EAAE,OAAO,EAAE,GAAG,OAAO,CAAC,QAAQ,CAAC;IACnC,IAAI,KAAK,GAAG,IAAI,GAAG,EAAU,CAAC;IAC9B,KAAK,IAAI,IAAI,IAAI,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,aAAa,CAAC,EAAE;QACnD,IAAI,KAAK,GAAG,IAAA,kBAAW,EAAC,IAAI,CAAC,CAAC;QAC9B,IAAI,KAAK,EAAE;YACT,KAAK,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;SAClB;KACF;IACD,KAAK,IAAI,IAAI,IAAI,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,cAAc,CAAC,EAAE;QACpD,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;KACjB;IACD,KAAK,IAAI,IAAI,IAAI,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,YAAY,CAAC,EAAE;QAClD,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;KACjB;IACD,OAAO,CAAC,GAAG,KAAK,CAAC,CAAC;AACpB,CAAC;AAjBD,wBAiBC","sourcesContent":["import { ResolverLoader, packageName } from '@embroider/core';\n\nexport function addons(root: string): string[] {\n let rloader = new ResolverLoader(root);\n let { options } = rloader.resolver;\n let names = new Set<string>();\n for (let from of Object.keys(options.renameModules)) {\n let pName = packageName(from);\n if (pName) {\n names.add(pName);\n }\n }\n for (let from of Object.keys(options.renamePackages)) {\n names.add(from);\n }\n for (let name of Object.keys(options.activeAddons)) {\n names.add(name);\n }\n return [...names];\n}\n"]}
package/src/hbs.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ import type { Plugin } from 'vite';
2
+ export declare function hbs(): Plugin;
package/src/hbs.js ADDED
@@ -0,0 +1,117 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.hbs = void 0;
7
+ // TODO: I copied this from @embroider/addon-dev, it needs to be its own package
8
+ // (or be in shared-internals or core)
9
+ const pluginutils_1 = require("@rollup/pluginutils");
10
+ const fs_1 = require("fs");
11
+ const core_1 = require("@embroider/core");
12
+ const assert_never_1 = __importDefault(require("assert-never"));
13
+ const path_1 = require("path");
14
+ const debug_1 = __importDefault(require("debug"));
15
+ const debug = (0, debug_1.default)('embroider:hbs-plugin');
16
+ function hbs() {
17
+ return {
18
+ name: 'rollup-hbs-plugin',
19
+ enforce: 'pre',
20
+ async resolveId(source, importer) {
21
+ let resolution = await this.resolve(source, importer, {
22
+ skipSelf: true,
23
+ });
24
+ if (!resolution) {
25
+ return maybeSynthesizeComponentJS(this, source, importer);
26
+ }
27
+ else {
28
+ return maybeRewriteHBS(resolution);
29
+ }
30
+ },
31
+ load(id) {
32
+ const meta = getMeta(this, id);
33
+ if (!meta) {
34
+ return;
35
+ }
36
+ switch (meta.type) {
37
+ case 'template':
38
+ let input = (0, fs_1.readFileSync)(id, 'utf8');
39
+ let code = (0, core_1.hbsToJS)(input);
40
+ return {
41
+ code,
42
+ };
43
+ case 'template-only-component-js':
44
+ return {
45
+ code: templateOnlyComponent,
46
+ };
47
+ default:
48
+ (0, assert_never_1.default)(meta);
49
+ }
50
+ },
51
+ };
52
+ }
53
+ exports.hbs = hbs;
54
+ const templateOnlyComponent = `import templateOnly from '@ember/component/template-only';\n` + `export default templateOnly();\n`;
55
+ function getMeta(context, id) {
56
+ var _a, _b;
57
+ const meta = (_b = (_a = context.getModuleInfo(id)) === null || _a === void 0 ? void 0 : _a.meta) === null || _b === void 0 ? void 0 : _b['rollup-hbs-plugin'];
58
+ if (meta) {
59
+ return meta;
60
+ }
61
+ else {
62
+ return null;
63
+ }
64
+ }
65
+ function correspondingTemplate(filename) {
66
+ let { ext } = (0, path_1.parse)(filename);
67
+ return filename.slice(0, filename.length - ext.length) + '.hbs';
68
+ }
69
+ async function maybeSynthesizeComponentJS(context, source, importer) {
70
+ debug(`checking for template-only component: %s`, source);
71
+ let templateResolution = await context.resolve(correspondingTemplate(source), importer, {
72
+ skipSelf: true,
73
+ custom: {
74
+ embroider: {
75
+ // we don't want to recurse into the whole embroider compatbility
76
+ // resolver here. It has presumably already steered our request to the
77
+ // correct place. All we want to do is slightly modify the request we
78
+ // were given (changing the extension) and check if that would resolve
79
+ // instead.
80
+ //
81
+ // Currently this guard is only actually exercised in rollup, not in
82
+ // vite, due to https://github.com/vitejs/vite/issues/13852
83
+ enableCustomResolver: false,
84
+ },
85
+ },
86
+ });
87
+ if (!templateResolution) {
88
+ return null;
89
+ }
90
+ debug(`emitting template only component: %s`, templateResolution.id);
91
+ // we're trying to resolve a JS module but only the corresponding HBS
92
+ // file exists. Synthesize the template-only component JS.
93
+ return {
94
+ id: templateResolution.id.replace(/\.hbs$/, '.js'),
95
+ meta: {
96
+ 'rollup-hbs-plugin': {
97
+ type: 'template-only-component-js',
98
+ },
99
+ },
100
+ };
101
+ }
102
+ const hbsFilter = (0, pluginutils_1.createFilter)('**/*.hbs');
103
+ function maybeRewriteHBS(resolution) {
104
+ if (!hbsFilter(resolution.id)) {
105
+ return null;
106
+ }
107
+ debug('emitting hbs rewrite: %s', resolution.id);
108
+ return {
109
+ ...resolution,
110
+ meta: {
111
+ 'rollup-hbs-plugin': {
112
+ type: 'template',
113
+ },
114
+ },
115
+ };
116
+ }
117
+ //# sourceMappingURL=hbs.js.map
package/src/hbs.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hbs.js","sourceRoot":"","sources":["hbs.ts"],"names":[],"mappings":";;;;;;AAAA,gFAAgF;AAChF,sCAAsC;AACtC,qDAAmD;AAGnD,2BAAkC;AAClC,0CAA0C;AAC1C,gEAAuC;AACvC,+BAA0C;AAC1C,kDAA8B;AAE9B,MAAM,KAAK,GAAG,IAAA,eAAS,EAAC,sBAAsB,CAAC,CAAC;AAEhD,SAAgB,GAAG;IACjB,OAAO;QACL,IAAI,EAAE,mBAAmB;QACzB,OAAO,EAAE,KAAK;QACd,KAAK,CAAC,SAAS,CAAC,MAAc,EAAE,QAA4B;YAC1D,IAAI,UAAU,GAAG,MAAM,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,QAAQ,EAAE;gBACpD,QAAQ,EAAE,IAAI;aACf,CAAC,CAAC;YAEH,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, it needs to be its own package\n// (or be in shared-internals or core)\nimport { createFilter } from '@rollup/pluginutils';\nimport type { PluginContext, ResolvedId } from 'rollup';\nimport type { Plugin } from 'vite';\nimport { readFileSync } from 'fs';\nimport { hbsToJS } from '@embroider/core';\nimport assertNever from 'assert-never';\nimport { parse as pathParse } from 'path';\nimport makeDebug from 'debug';\n\nconst debug = makeDebug('embroider:hbs-plugin');\n\nexport function hbs(): Plugin {\n return {\n name: 'rollup-hbs-plugin',\n enforce: 'pre',\n async resolveId(source: string, importer: string | undefined) {\n let resolution = await this.resolve(source, importer, {\n skipSelf: true,\n });\n\n if (!resolution) {\n return maybeSynthesizeComponentJS(this, source, importer);\n } else {\n return maybeRewriteHBS(resolution);\n }\n },\n\n load(id: string) {\n const meta = getMeta(this, id);\n if (!meta) {\n return;\n }\n\n switch (meta.type) {\n case 'template':\n let input = readFileSync(id, 'utf8');\n let code = hbsToJS(input);\n return {\n code,\n };\n case 'template-only-component-js':\n return {\n code: templateOnlyComponent,\n };\n default:\n assertNever(meta);\n }\n },\n };\n}\n\nconst templateOnlyComponent =\n `import templateOnly from '@ember/component/template-only';\\n` + `export default templateOnly();\\n`;\n\ntype Meta =\n | {\n type: 'template';\n }\n | {\n type: 'template-only-component-js';\n };\n\nfunction getMeta(context: PluginContext, id: string): Meta | null {\n const meta = context.getModuleInfo(id)?.meta?.['rollup-hbs-plugin'];\n if (meta) {\n return meta as Meta;\n } else {\n return null;\n }\n}\n\nfunction correspondingTemplate(filename: string): string {\n let { ext } = pathParse(filename);\n return filename.slice(0, filename.length - ext.length) + '.hbs';\n}\n\nasync function maybeSynthesizeComponentJS(context: PluginContext, source: string, importer: string | undefined) {\n debug(`checking for template-only component: %s`, source);\n let templateResolution = await context.resolve(correspondingTemplate(source), importer, {\n skipSelf: true,\n custom: {\n embroider: {\n // we don't want to recurse into the whole embroider compatbility\n // resolver here. It has presumably already steered our request to the\n // correct place. All we want to do is slightly modify the request we\n // were given (changing the extension) and check if that would resolve\n // instead.\n //\n // Currently this guard is only actually exercised in rollup, not in\n // vite, due to https://github.com/vitejs/vite/issues/13852\n enableCustomResolver: false,\n },\n },\n });\n if (!templateResolution) {\n return null;\n }\n debug(`emitting template only component: %s`, templateResolution.id);\n\n // we're trying to resolve a JS module but only the corresponding HBS\n // file exists. Synthesize the template-only component JS.\n return {\n id: templateResolution.id.replace(/\\.hbs$/, '.js'),\n meta: {\n 'rollup-hbs-plugin': {\n type: 'template-only-component-js',\n },\n },\n };\n}\n\nconst hbsFilter = createFilter('**/*.hbs');\n\nfunction maybeRewriteHBS(resolution: ResolvedId) {\n if (!hbsFilter(resolution.id)) {\n return null;\n }\n debug('emitting hbs rewrite: %s', resolution.id);\n return {\n ...resolution,\n meta: {\n 'rollup-hbs-plugin': {\n type: 'template',\n },\n },\n };\n}\n"]}
@@ -0,0 +1,14 @@
1
+ import { ModuleRequest } from '@embroider/core';
2
+ export declare const virtualPrefix = "embroider_virtual:";
3
+ export declare class RollupModuleRequest implements ModuleRequest {
4
+ readonly specifier: string;
5
+ readonly fromFile: string;
6
+ readonly meta: Record<string, any> | undefined;
7
+ static from(source: string, importer: string | undefined, custom: Record<string, any> | undefined): RollupModuleRequest | undefined;
8
+ private constructor();
9
+ get isVirtual(): boolean;
10
+ alias(newSpecifier: string): this;
11
+ rehome(newFromFile: string): this;
12
+ virtualize(filename: string): this;
13
+ withMeta(meta: Record<string, any> | undefined): this;
14
+ }
package/src/request.js ADDED
@@ -0,0 +1,52 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RollupModuleRequest = exports.virtualPrefix = void 0;
4
+ const core_1 = require("@embroider/core");
5
+ exports.virtualPrefix = 'embroider_virtual:';
6
+ class RollupModuleRequest {
7
+ static from(source, importer, custom) {
8
+ var _a, _b, _c;
9
+ if (!((_b = (_a = custom === null || custom === void 0 ? void 0 : custom.embroider) === null || _a === void 0 ? void 0 : _a.enableCustomResolver) !== null && _b !== void 0 ? _b : true)) {
10
+ return;
11
+ }
12
+ if (source && importer && source[0] !== '\0') {
13
+ let nonVirtual;
14
+ if (importer.startsWith(exports.virtualPrefix)) {
15
+ nonVirtual = importer.slice(exports.virtualPrefix.length);
16
+ }
17
+ else {
18
+ nonVirtual = importer;
19
+ }
20
+ // strip query params off the importer
21
+ let fromFile = (0, core_1.cleanUrl)(nonVirtual);
22
+ return new RollupModuleRequest(source, fromFile, (_c = custom === null || custom === void 0 ? void 0 : custom.embroider) === null || _c === void 0 ? void 0 : _c.meta);
23
+ }
24
+ }
25
+ constructor(specifier, fromFile, meta) {
26
+ this.specifier = specifier;
27
+ this.fromFile = fromFile;
28
+ this.meta = meta;
29
+ }
30
+ get isVirtual() {
31
+ return this.specifier.startsWith(exports.virtualPrefix);
32
+ }
33
+ alias(newSpecifier) {
34
+ return new RollupModuleRequest(newSpecifier, this.fromFile, this.meta);
35
+ }
36
+ rehome(newFromFile) {
37
+ if (this.fromFile === newFromFile) {
38
+ return this;
39
+ }
40
+ else {
41
+ return new RollupModuleRequest(this.specifier, newFromFile, this.meta);
42
+ }
43
+ }
44
+ virtualize(filename) {
45
+ return new RollupModuleRequest(exports.virtualPrefix + filename, this.fromFile, this.meta);
46
+ }
47
+ withMeta(meta) {
48
+ return new RollupModuleRequest(this.specifier, this.fromFile, meta);
49
+ }
50
+ }
51
+ exports.RollupModuleRequest = RollupModuleRequest;
52
+ //# sourceMappingURL=request.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"request.js","sourceRoot":"","sources":["request.ts"],"names":[],"mappings":";;;AAAA,0CAA0D;AAE7C,QAAA,aAAa,GAAG,oBAAoB,CAAC;AAElD,MAAa,mBAAmB;IAC9B,MAAM,CAAC,IAAI,CACT,MAAc,EACd,QAA4B,EAC5B,MAAuC;;QAEvC,IAAI,CAAC,CAAC,MAAA,MAAA,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,SAAS,0CAAE,oBAAoB,mCAAI,IAAI,CAAC,EAAE;YACtD,OAAO;SACR;QAED,IAA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AAC,IAAI,CAAS,CAAC;IAC7F,CAAC;IACD,QAAQ,CAAC,IAAqC;QAC5C,OAAO,IAAI,mBAAmB,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,QAAQ,EAAE,IAAI,CAAS,CAAC;IAC9E,CAAC;CACF;AAlDD,kDAkDC","sourcesContent":["import { ModuleRequest, cleanUrl } from '@embroider/core';\n\nexport const virtualPrefix = 'embroider_virtual:';\n\nexport class RollupModuleRequest implements ModuleRequest {\n static from(\n source: string,\n importer: string | undefined,\n custom: Record<string, any> | undefined\n ): RollupModuleRequest | undefined {\n if (!(custom?.embroider?.enableCustomResolver ?? true)) {\n return;\n }\n\n if (source && importer && source[0] !== '\\0') {\n let nonVirtual: string;\n if (importer.startsWith(virtualPrefix)) {\n nonVirtual = importer.slice(virtualPrefix.length);\n } else {\n nonVirtual = importer;\n }\n\n // strip query params off the importer\n let fromFile = cleanUrl(nonVirtual);\n return new RollupModuleRequest(source, fromFile, custom?.embroider?.meta);\n }\n }\n\n private constructor(\n readonly specifier: string,\n readonly fromFile: string,\n readonly meta: Record<string, any> | undefined\n ) {}\n\n get isVirtual(): boolean {\n return this.specifier.startsWith(virtualPrefix);\n }\n\n alias(newSpecifier: string) {\n return new RollupModuleRequest(newSpecifier, this.fromFile, this.meta) as this;\n }\n rehome(newFromFile: string) {\n if (this.fromFile === newFromFile) {\n return this;\n } else {\n return new RollupModuleRequest(this.specifier, newFromFile, this.meta) as this;\n }\n }\n virtualize(filename: string) {\n return new RollupModuleRequest(virtualPrefix + filename, this.fromFile, this.meta) as this;\n }\n withMeta(meta: Record<string, any> | undefined): this {\n return new RollupModuleRequest(this.specifier, this.fromFile, meta) as this;\n }\n}\n"]}
@@ -0,0 +1,2 @@
1
+ import { Plugin } from 'vite';
2
+ export declare function resolver(): Plugin;
@@ -0,0 +1,66 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.resolver = void 0;
7
+ const path_1 = require("path");
8
+ const core_1 = require("@embroider/core");
9
+ const fs_extra_1 = require("fs-extra");
10
+ const request_1 = require("./request");
11
+ const assert_never_1 = __importDefault(require("assert-never"));
12
+ function resolver() {
13
+ let resolverOptions = (0, fs_extra_1.readJSONSync)((0, path_1.join)((0, core_1.locateEmbroiderWorkingDir)(process.cwd()), 'resolver.json'));
14
+ let resolver = new core_1.Resolver(resolverOptions);
15
+ return {
16
+ name: 'embroider-resolver',
17
+ enforce: 'pre',
18
+ async resolveId(source, importer, options) {
19
+ let request = request_1.RollupModuleRequest.from(source, importer, options.custom);
20
+ if (!request) {
21
+ // fallthrough to other rollup plugins
22
+ return null;
23
+ }
24
+ let resolution = await resolver.resolve(request, defaultResolve(this));
25
+ switch (resolution.type) {
26
+ case 'found':
27
+ return resolution.result;
28
+ case 'not_found':
29
+ return null;
30
+ default:
31
+ throw (0, assert_never_1.default)(resolution);
32
+ }
33
+ },
34
+ load(id) {
35
+ if (id.startsWith(request_1.virtualPrefix)) {
36
+ return (0, core_1.virtualContent)(id.slice(request_1.virtualPrefix.length), resolver);
37
+ }
38
+ },
39
+ };
40
+ }
41
+ exports.resolver = resolver;
42
+ function defaultResolve(context) {
43
+ return async (request) => {
44
+ if (request.isVirtual) {
45
+ return {
46
+ type: 'found',
47
+ result: { id: request.specifier, resolvedBy: request.fromFile },
48
+ };
49
+ }
50
+ let result = await context.resolve(request.specifier, request.fromFile, {
51
+ skipSelf: true,
52
+ custom: {
53
+ embroider: {
54
+ meta: request.meta,
55
+ },
56
+ },
57
+ });
58
+ if (result) {
59
+ return { type: 'found', result };
60
+ }
61
+ else {
62
+ return { type: 'not_found', err: undefined };
63
+ }
64
+ };
65
+ }
66
+ //# sourceMappingURL=resolver.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"resolver.js","sourceRoot":"","sources":["resolver.ts"],"names":[],"mappings":";;;;;;AAEA,+B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IAAI,OAAO,CAAC,SAAS,EAAE;YACrB,OAAO;gBACL,IAAI,EAAE,OAAO;gBACb,MAAM,EAAE,EAAE,EAAE,EAAE,OAAO,CAAC,SAAS,EAAE,UAAU,EAAE,OAAO,CAAC,QAAQ,EAAE;aAChE,CAAC;SACH;QACD,IAAI,MAAM,GAAG,MAAM,OAAO,CAAC,OAAO,CAAC,OAAO,CAAC,SAAS,EAAE,OAAO,CAAC,QAAQ,EAAE;YACtE,QAAQ,EAAE,IAAI;YACd,MAAM,EAAE;gBACN,SAAS,EAAE;oBACT,IAAI,EAAE,OAAO,CAAC,IAAI;iBACnB;aACF;SACF,CAAC,CAAC;QACH,IAAI,MAAM,EAAE;YACV,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,EAAE,CAAC;SAClC;aAAM;YACL,OAAO,EAAE,IAAI,EAAE,WAAW,EAAE,GAAG,EAAE,SAAS,EAAE,CAAC;SAC9C;IACH,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import type { PluginContext, ResolveIdResult } from 'rollup';\nimport { Plugin } from 'vite';\nimport { join } from 'path';\nimport {\n Resolution,\n Resolver,\n ResolverFunction,\n ResolverOptions,\n locateEmbroiderWorkingDir,\n virtualContent,\n} from '@embroider/core';\nimport { readJSONSync } from 'fs-extra';\nimport { RollupModuleRequest, virtualPrefix } from './request';\nimport assertNever from 'assert-never';\n\nexport function resolver(): Plugin {\n let resolverOptions: ResolverOptions = readJSONSync(join(locateEmbroiderWorkingDir(process.cwd()), 'resolver.json'));\n let resolver = new Resolver(resolverOptions);\n\n return {\n name: 'embroider-resolver',\n enforce: 'pre',\n async resolveId(source, importer, options) {\n let request = RollupModuleRequest.from(source, importer, options.custom);\n if (!request) {\n // fallthrough to other rollup plugins\n return null;\n }\n let resolution = await resolver.resolve(request, defaultResolve(this));\n switch (resolution.type) {\n case 'found':\n return resolution.result;\n case 'not_found':\n return null;\n default:\n throw assertNever(resolution);\n }\n },\n load(id) {\n if (id.startsWith(virtualPrefix)) {\n return virtualContent(id.slice(virtualPrefix.length), resolver);\n }\n },\n };\n}\n\nfunction defaultResolve(context: PluginContext): ResolverFunction<RollupModuleRequest, Resolution<ResolveIdResult>> {\n return async (request: RollupModuleRequest) => {\n if (request.isVirtual) {\n return {\n type: 'found',\n result: { id: request.specifier, resolvedBy: request.fromFile },\n };\n }\n let result = await context.resolve(request.specifier, request.fromFile, {\n skipSelf: true,\n custom: {\n embroider: {\n meta: request.meta,\n },\n },\n });\n if (result) {\n return { type: 'found', result };\n } else {\n return { type: 'not_found', err: undefined };\n }\n };\n}\n"]}
@@ -0,0 +1,5 @@
1
+ import type { Plugin } from 'vite';
2
+ export declare function scripts(params?: {
3
+ include?: string[];
4
+ exclude?: string[];
5
+ }): Plugin;
package/src/scripts.js ADDED
@@ -0,0 +1,143 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ Object.defineProperty(exports, "__esModule", { value: true });
26
+ exports.scripts = void 0;
27
+ const jsdom_1 = require("jsdom");
28
+ const fs_extra_1 = require("fs-extra");
29
+ const path_1 = require("path");
30
+ const defaults = ['/assets/vendor.js', '/assets/test-support.js'];
31
+ function scripts(params) {
32
+ var _a;
33
+ let optimizer;
34
+ // configured names are always interpreted as origin-absolute URLs.
35
+ let names = ((_a = params === null || params === void 0 ? void 0 : params.include) !== null && _a !== void 0 ? _a : defaults)
36
+ .filter(name => { var _a; return !((_a = params === null || params === void 0 ? void 0 : params.exclude) === null || _a === void 0 ? void 0 : _a.includes(name)); })
37
+ .map(name => {
38
+ if (name.startsWith('/')) {
39
+ return name;
40
+ }
41
+ else {
42
+ return '/' + name;
43
+ }
44
+ });
45
+ return {
46
+ name: 'embroider-scripts',
47
+ enforce: 'pre',
48
+ configResolved(resolvedConfig) {
49
+ optimizer = new ScriptOptimizer(resolvedConfig.root);
50
+ },
51
+ async generateBundle() {
52
+ // this hook only runs in `vite build`
53
+ for (let name of names) {
54
+ for (let file of await optimizer.optimizedScript(name)) {
55
+ this.emitFile(file);
56
+ }
57
+ }
58
+ },
59
+ transformIndexHtml(htmlIn, context) {
60
+ // we don't do anything in `vite dev`, we only need to work in `vite
61
+ // build`
62
+ if (!context.server) {
63
+ return optimizer.transformHTML(htmlIn);
64
+ }
65
+ },
66
+ };
67
+ }
68
+ exports.scripts = scripts;
69
+ class ScriptOptimizer {
70
+ constructor(rootDir) {
71
+ this.rootDir = rootDir;
72
+ this.emitted = new Map();
73
+ }
74
+ async optimizedScript(script) {
75
+ // loading these lazily here so they never load in non-production builds.
76
+ // The node cache will ensures we only load them once.
77
+ const [Terser, srcURL] = await Promise.all([Promise.resolve().then(() => __importStar(require('terser'))), Promise.resolve().then(() => __importStar(require('source-map-url')))]);
78
+ let inCode = (0, fs_extra_1.readFileSync)((0, path_1.resolve)(this.rootDir, script.slice(1)), 'utf8');
79
+ let terserOpts = {};
80
+ let fileRelativeSourceMapURL;
81
+ let appRelativeSourceMapURL;
82
+ if (srcURL.default.existsIn(inCode)) {
83
+ fileRelativeSourceMapURL = srcURL.default.getFrom(inCode);
84
+ appRelativeSourceMapURL = path_1.posix.join((0, path_1.dirname)(script.slice(1)), fileRelativeSourceMapURL);
85
+ let content;
86
+ try {
87
+ content = (0, fs_extra_1.readJSONSync)((0, path_1.resolve)(this.rootDir, appRelativeSourceMapURL));
88
+ }
89
+ catch (err) {
90
+ // the script refers to a sourcemap that doesn't exist, so we just leave
91
+ // the map out.
92
+ }
93
+ if (content) {
94
+ terserOpts.sourceMap = { content, url: fileRelativeSourceMapURL };
95
+ }
96
+ }
97
+ let { code: outCode, map: outMap } = await Terser.default.minify(inCode, terserOpts);
98
+ let finalFilename = await this.getFingerprintedFilename(script, outCode);
99
+ let emit = [];
100
+ emit.push({
101
+ type: 'asset',
102
+ fileName: finalFilename.slice(1),
103
+ source: outCode,
104
+ });
105
+ this.emitted.set(script, finalFilename);
106
+ if (appRelativeSourceMapURL && outMap) {
107
+ emit.push({
108
+ type: 'asset',
109
+ fileName: appRelativeSourceMapURL,
110
+ source: JSON.stringify(outMap, null, 2),
111
+ });
112
+ }
113
+ return emit;
114
+ }
115
+ async getFingerprintedFilename(filename, content) {
116
+ let crypto = await Promise.resolve().then(() => __importStar(require('crypto')));
117
+ let md5 = crypto.createHash('md5');
118
+ md5.update(content);
119
+ let hash = md5.digest('hex');
120
+ let fileParts = filename.split('.');
121
+ fileParts.splice(fileParts.length - 1, 0, hash);
122
+ return fileParts.join('.');
123
+ }
124
+ transformHTML(htmlIn) {
125
+ var _a;
126
+ if (((_a = this.transformState) === null || _a === void 0 ? void 0 : _a.htmlIn) !== htmlIn) {
127
+ let parsed = new jsdom_1.JSDOM(htmlIn);
128
+ let scriptTags = [...parsed.window.document.querySelectorAll('script')];
129
+ for (let scriptTag of scriptTags) {
130
+ if (scriptTag.type !== 'module') {
131
+ let fingerprinted = this.emitted.get(scriptTag.src);
132
+ if (fingerprinted) {
133
+ scriptTag.src = fingerprinted;
134
+ }
135
+ }
136
+ }
137
+ let htmlOut = parsed.serialize();
138
+ this.transformState = { htmlIn, parsed, htmlOut };
139
+ }
140
+ return this.transformState.htmlOut;
141
+ }
142
+ }
143
+ //# sourceMappingURL=scripts.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"scripts.js","sourceRoot":"","sources":["scripts.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAEA,iCAA8B;AAC9B,uCAAsD;AACtD,+BAA+C;AAO/C,MAAM,QAAQ,GAAG,CAAC,mBAAmB,EAAE,yBAAyB,CAAC,CAAC;AAElE,SAAgB,OAAO,CAAC,MAAmD;;IACzE,IAAI,SAA0B,CAAC;IAE/B,mEAAmE;IACnE,IAAI,KAAK,GAAG,CAAC,MAAA,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,OAAO,mCAAI,QAAQ,CAAC;SACtC,MAAM,CAAC,IAAI,CAAC,EAAE,WAAC,OAAA,CAAC,CAAA,MAAA,MAAM,aAAN,MAAM,uBAAN,MAAM,CAAE,OAAO,0CAAE,QAAQ,CAAC,IAAI,CAAC,CAAA,CAAA,EAAA,CAAC;SAChD,GAAG,CAAC,IAAI,CAAC,EAAE;QACV,IAAI,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,EAAE;YACxB,OAAO,IAAI,CAAC;SACb;aAAM;YACL,OAAO,GAAG,GAAG,IAAI,CAAC;SACnB;IACH,CAAC,CAAC,CAAC;IAEL,OAAO;QACL,IAAI,EAAE,mBAAmB;QACzB,OAAO,EAAE,KAAK;QAEd,cAAc,CAAC,cAAc;YAC3B,SAAS,GAAG,IAAI,eAAe,CAAC,cAAc,CAAC,IAAI,CAAC,CAAC;QACvD,CAAC;QAED,KAAK,CAAC,cAAc;YAClB,sCAAsC;YACtC,KAAK,IAAI,IAAI,IAAI,KAAK,EAAE;gBACtB,KAAK,IAAI,IAAI,IAAI,MAAM,SAAS,CAAC,eAAe,CAAC,IAAI,CAAC,EAAE;oBACtD,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;iBACrB;aACF;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AAC,GAAG,CAAC,CAAC;QACpC,SAAS,CAAC,MAAM,CAAC,SAAS,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC,EAAE,IAAI,CAAC,CAAC;QAChD,OAAO,SAAS,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IAC7B,CAAC;IAED,aAAa,CAAC,MAAc;;QAC1B,IAAI,CAAA,MAAA,IAAI,CAAC,cAAc,0CAAE,MAAM,MAAK,MAAM,EAAE;YAC1C,IAAI,MAAM,GAAG,IAAI,aAAK,CAAC,MAAM,CAAC,CAAC;YAC/B,IAAI,UAAU,GAAG,CAAC,GAAG,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAC,gBAAgB,CAAC,QAAQ,CAAC,CAAwB,CAAC;YAC/F,KAAK,IAAI,SAAS,IAAI,UAAU,EAAE;gBAChC,IAAI,SAAS,CAAC,IAAI,KAAK,QAAQ,EAAE;oBAC/B,IAAI,aAAa,GAAG,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC;oBACpD,IAAI,aAAa,EAAE;wBACjB,SAAS,CAAC,GAAG,GAAG,aAAa,CAAC;qBAC/B;iBACF;aACF;YACD,IAAI,OAAO,GAAG,MAAM,CAAC,SAAS,EAAE,CAAC;YACjC,IAAI,CAAC,cAAc,GAAG,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC;SACnD;QACD,OAAO,IAAI,CAAC,cAAc,CAAC,OAAO,CAAC;IACrC,CAAC;CACF","sourcesContent":["import type { Plugin } from 'vite';\nimport type { EmittedFile } from 'rollup';\nimport { JSDOM } from 'jsdom';\nimport { readFileSync, readJSONSync } from 'fs-extra';\nimport { dirname, posix, resolve } from 'path';\n\n// This is a type-only import, so it gets compiled away. At runtime, we load\n// terser lazily so it's only loaded for production builds that use it. Don't\n// add any non-type-only imports here.\nimport type { MinifyOptions } from 'terser';\n\nconst defaults = ['/assets/vendor.js', '/assets/test-support.js'];\n\nexport function scripts(params?: { include?: string[]; exclude?: string[] }): Plugin {\n let optimizer: ScriptOptimizer;\n\n // configured names are always interpreted as origin-absolute URLs.\n let names = (params?.include ?? defaults)\n .filter(name => !params?.exclude?.includes(name))\n .map(name => {\n if (name.startsWith('/')) {\n return name;\n } else {\n return '/' + name;\n }\n });\n\n return {\n name: 'embroider-scripts',\n enforce: 'pre',\n\n configResolved(resolvedConfig) {\n optimizer = new ScriptOptimizer(resolvedConfig.root);\n },\n\n async generateBundle() {\n // this hook only runs in `vite build`\n for (let name of names) {\n for (let file of await optimizer.optimizedScript(name)) {\n this.emitFile(file);\n }\n }\n },\n\n transformIndexHtml(htmlIn, context) {\n // we don't do anything in `vite dev`, we only need to work in `vite\n // build`\n if (!context.server) {\n return optimizer.transformHTML(htmlIn);\n }\n },\n };\n}\n\nclass ScriptOptimizer {\n private emitted = new Map<string, string>();\n private transformState:\n | {\n htmlIn: string;\n htmlOut: string;\n parsed: JSDOM;\n }\n | undefined;\n\n constructor(private rootDir: string) {}\n\n async optimizedScript(script: string): Promise<EmittedFile[]> {\n // loading these lazily here so they never load in non-production builds.\n // The node cache will ensures we only load them once.\n const [Terser, srcURL] = await Promise.all([import('terser'), import('source-map-url')]);\n\n let inCode = readFileSync(resolve(this.rootDir, script.slice(1)), 'utf8');\n let terserOpts: MinifyOptions = {};\n let fileRelativeSourceMapURL;\n let appRelativeSourceMapURL;\n if (srcURL.default.existsIn(inCode)) {\n fileRelativeSourceMapURL = srcURL.default.getFrom(inCode)!;\n appRelativeSourceMapURL = posix.join(dirname(script.slice(1)), fileRelativeSourceMapURL);\n let content;\n try {\n content = readJSONSync(resolve(this.rootDir, appRelativeSourceMapURL));\n } catch (err) {\n // the script refers to a sourcemap that doesn't exist, so we just leave\n // the map out.\n }\n if (content) {\n terserOpts.sourceMap = { content, url: fileRelativeSourceMapURL };\n }\n }\n let { code: outCode, map: outMap } = await Terser.default.minify(inCode, terserOpts);\n let finalFilename = await this.getFingerprintedFilename(script, outCode!);\n let emit: EmittedFile[] = [];\n emit.push({\n type: 'asset',\n fileName: finalFilename.slice(1),\n source: outCode!,\n });\n this.emitted.set(script, finalFilename);\n if (appRelativeSourceMapURL && outMap) {\n emit.push({\n type: 'asset',\n fileName: appRelativeSourceMapURL,\n source: JSON.stringify(outMap, null, 2),\n });\n }\n return emit;\n }\n\n async getFingerprintedFilename(filename: string, content: string): Promise<string> {\n let crypto = await import('crypto');\n let md5 = crypto.createHash('md5');\n md5.update(content);\n let hash = md5.digest('hex');\n let fileParts = filename.split('.');\n fileParts.splice(fileParts.length - 1, 0, hash);\n return fileParts.join('.');\n }\n\n transformHTML(htmlIn: string) {\n if (this.transformState?.htmlIn !== htmlIn) {\n let parsed = new JSDOM(htmlIn);\n let scriptTags = [...parsed.window.document.querySelectorAll('script')] as HTMLScriptElement[];\n for (let scriptTag of scriptTags) {\n if (scriptTag.type !== 'module') {\n let fingerprinted = this.emitted.get(scriptTag.src);\n if (fingerprinted) {\n scriptTag.src = fingerprinted;\n }\n }\n }\n let htmlOut = parsed.serialize();\n this.transformState = { htmlIn, parsed, htmlOut };\n }\n return this.transformState.htmlOut;\n }\n}\n"]}
@@ -0,0 +1,2 @@
1
+ import type { Plugin } from 'vite';
2
+ export declare function templateTag(): Plugin;
@@ -0,0 +1,48 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.templateTag = void 0;
4
+ const pluginutils_1 = require("@rollup/pluginutils");
5
+ const fs_1 = require("fs");
6
+ const content_tag_1 = require("content-tag");
7
+ const gjsFilter = (0, pluginutils_1.createFilter)('**/*.gjs');
8
+ function templateTag() {
9
+ let preprocessor = new content_tag_1.Preprocessor();
10
+ function candidates(id) {
11
+ return [id + '.gjs'];
12
+ }
13
+ return {
14
+ name: 'embroider-template-tag',
15
+ enforce: 'pre',
16
+ async resolveId(id, importer) {
17
+ let resolution = await this.resolve(id, importer, {
18
+ skipSelf: true,
19
+ });
20
+ if (resolution) {
21
+ return resolution;
22
+ }
23
+ for (let candidate of candidates(id)) {
24
+ resolution = await this.resolve(candidate, importer, {
25
+ skipSelf: true,
26
+ custom: {
27
+ embroider: {
28
+ enableCustomResolver: false,
29
+ },
30
+ },
31
+ });
32
+ if (resolution) {
33
+ return {
34
+ id: resolution.id,
35
+ };
36
+ }
37
+ }
38
+ },
39
+ load(id) {
40
+ if (!gjsFilter(id)) {
41
+ return null;
42
+ }
43
+ return preprocessor.process((0, fs_1.readFileSync)(id, 'utf8'), id);
44
+ },
45
+ };
46
+ }
47
+ exports.templateTag = templateTag;
48
+ //# sourceMappingURL=template-tag.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"template-tag.js","sourceRoot":"","sources":["template-tag.ts"],"names":[],"mappings":";;;AAAA,qDAAmD;AAEnD,2BAAkC;AAClC,6CAA2C;AAE3C,MAAM,SAAS,GAAG,IAAA,0BAAY,EAAC,UAAU,CAAC,CAAC;AAE3C,SAAgB,WAAW;IACzB,IAAI,YAAY,GAAG,IAAI,0BAAY,EAAE,CAAC;IAEtC,SAAS,UAAU,CAAC,EAAU;QAC5B,OAAO,CAAC,EAAE,GAAG,MAAM,CAAC,CAAC;IACvB,CAAC;IAED,OAAO;QACL,IAAI,EAAE,wBAAwB;QAC9B,OAAO,EAAE,KAAK;QAEd,KAAK,CAAC,SAAS,CAAC,EAAU,EAAE,QAA4B;YACtD,IAAI,UAAU,GAAG,MAAM,IAAI,CAAC,OAAO,CAAC,EAAE,EAAE,QAAQ,EAAE;gBAChD,QAAQ,EAAE,IAAI;aACf,CAAC,CAAC;YACH,IAAI,UAAU,EAAE;gBACd,OAAO,UAAU,CAAC;aACnB;YACD,KAAK,IAAI,SAAS,IAAI,UAAU,CAAC,EAAE,CAAC,EAAE;gBACpC,UAAU,GAAG,MAAM,IAAI,CAAC,OAAO,CAAC,SAAS,EAAE,QAAQ,EAAE;oBACnD,QAAQ,EAAE,IAAI;oBACd,MAAM,EAAE;wBACN,SAAS,EAAE;4BACT,oBAAoB,EAAE,KAAK;yBAC5B;qBACF;iBACF,CAAC,CAAC;gBACH,IAAI,UAAU,EAAE;oBACd,OAAO;wBACL,EAAE,EAAE,UAAU,CAAC,EAAE;qBAClB,CAAC;iBACH;aACF;QACH,CAAC;QAED,IAAI,CAAC,EAAU;YACb,IAAI,CAAC,SAAS,CAAC,EAAE,CAAC,EAAE;gBAClB,OAAO,IAAI,CAAC;aACb;YACD,OAAO,YAAY,CAAC,OAAO,CAAC,IAAA,iBAAY,EAAC,EAAE,EAAE,MAAM,CAAC,EAAE,EAAE,CAAC,CAAC;QAC5D,CAAC;KACF,CAAC;AACJ,CAAC;AA1CD,kCA0CC","sourcesContent":["import { createFilter } from '@rollup/pluginutils';\nimport type { Plugin } from 'vite';\nimport { readFileSync } from 'fs';\nimport { Preprocessor } from 'content-tag';\n\nconst gjsFilter = createFilter('**/*.gjs');\n\nexport function templateTag(): Plugin {\n let preprocessor = new Preprocessor();\n\n function candidates(id: string) {\n return [id + '.gjs'];\n }\n\n return {\n name: 'embroider-template-tag',\n enforce: 'pre',\n\n async resolveId(id: string, importer: string | undefined) {\n let resolution = await this.resolve(id, importer, {\n skipSelf: true,\n });\n if (resolution) {\n return resolution;\n }\n for (let candidate of candidates(id)) {\n resolution = await this.resolve(candidate, importer, {\n skipSelf: true,\n custom: {\n embroider: {\n enableCustomResolver: false,\n },\n },\n });\n if (resolution) {\n return {\n id: resolution.id,\n };\n }\n }\n },\n\n load(id: string) {\n if (!gjsFilter(id)) {\n return null;\n }\n return preprocessor.process(readFileSync(id, 'utf8'), id);\n },\n };\n}\n"]}
package/.eslintignore DELETED
@@ -1,11 +0,0 @@
1
- # compiled output
2
- /src/**/*.js
3
- /src/**/*.d.ts
4
-
5
- # shims
6
- /index.d.ts
7
- /index.mjs
8
-
9
- # dependencies
10
- /node_modules/
11
-
package/src/addons.ts DELETED
@@ -1,20 +0,0 @@
1
- import { ResolverLoader, packageName } from '@embroider/core';
2
-
3
- export function addons(root: string): string[] {
4
- let rloader = new ResolverLoader(root);
5
- let { options } = rloader.resolver;
6
- let names = new Set<string>();
7
- for (let from of Object.keys(options.renameModules)) {
8
- let pName = packageName(from);
9
- if (pName) {
10
- names.add(pName);
11
- }
12
- }
13
- for (let from of Object.keys(options.renamePackages)) {
14
- names.add(from);
15
- }
16
- for (let name of Object.keys(options.activeAddons)) {
17
- names.add(name);
18
- }
19
- return [...names];
20
- }
package/src/hbs.ts DELETED
@@ -1,129 +0,0 @@
1
- // TODO: I copied this from @embroider/addon-dev, it needs to be its own package
2
- // (or be in shared-internals or core)
3
- import { createFilter } from '@rollup/pluginutils';
4
- import type { PluginContext, ResolvedId } from 'rollup';
5
- import type { Plugin } from 'vite';
6
- import { readFileSync } from 'fs';
7
- import { hbsToJS } from '@embroider/core';
8
- import assertNever from 'assert-never';
9
- import { parse as pathParse } from 'path';
10
- import makeDebug from 'debug';
11
-
12
- const debug = makeDebug('embroider:hbs-plugin');
13
-
14
- export function hbs(): Plugin {
15
- return {
16
- name: 'rollup-hbs-plugin',
17
- enforce: 'pre',
18
- async resolveId(source: string, importer: string | undefined) {
19
- let resolution = await this.resolve(source, importer, {
20
- skipSelf: true,
21
- });
22
-
23
- if (!resolution) {
24
- return maybeSynthesizeComponentJS(this, source, importer);
25
- } else {
26
- return maybeRewriteHBS(resolution);
27
- }
28
- },
29
-
30
- load(id: string) {
31
- const meta = getMeta(this, id);
32
- if (!meta) {
33
- return;
34
- }
35
-
36
- switch (meta.type) {
37
- case 'template':
38
- let input = readFileSync(id, 'utf8');
39
- let code = hbsToJS(input);
40
- return {
41
- code,
42
- };
43
- case 'template-only-component-js':
44
- return {
45
- code: templateOnlyComponent,
46
- };
47
- default:
48
- assertNever(meta);
49
- }
50
- },
51
- };
52
- }
53
-
54
- const templateOnlyComponent =
55
- `import templateOnly from '@ember/component/template-only';\n` + `export default templateOnly();\n`;
56
-
57
- type Meta =
58
- | {
59
- type: 'template';
60
- }
61
- | {
62
- type: 'template-only-component-js';
63
- };
64
-
65
- function getMeta(context: PluginContext, id: string): Meta | null {
66
- const meta = context.getModuleInfo(id)?.meta?.['rollup-hbs-plugin'];
67
- if (meta) {
68
- return meta as Meta;
69
- } else {
70
- return null;
71
- }
72
- }
73
-
74
- function correspondingTemplate(filename: string): string {
75
- let { ext } = pathParse(filename);
76
- return filename.slice(0, filename.length - ext.length) + '.hbs';
77
- }
78
-
79
- async function maybeSynthesizeComponentJS(context: PluginContext, source: string, importer: string | undefined) {
80
- debug(`checking for template-only component: %s`, source);
81
- let templateResolution = await context.resolve(correspondingTemplate(source), importer, {
82
- skipSelf: true,
83
- custom: {
84
- embroider: {
85
- // we don't want to recurse into the whole embroider compatbility
86
- // resolver here. It has presumably already steered our request to the
87
- // correct place. All we want to do is slightly modify the request we
88
- // were given (changing the extension) and check if that would resolve
89
- // instead.
90
- //
91
- // Currently this guard is only actually exercised in rollup, not in
92
- // vite, due to https://github.com/vitejs/vite/issues/13852
93
- enableCustomResolver: false,
94
- },
95
- },
96
- });
97
- if (!templateResolution) {
98
- return null;
99
- }
100
- debug(`emitting template only component: %s`, templateResolution.id);
101
-
102
- // we're trying to resolve a JS module but only the corresponding HBS
103
- // file exists. Synthesize the template-only component JS.
104
- return {
105
- id: templateResolution.id.replace(/\.hbs$/, '.js'),
106
- meta: {
107
- 'rollup-hbs-plugin': {
108
- type: 'template-only-component-js',
109
- },
110
- },
111
- };
112
- }
113
-
114
- const hbsFilter = createFilter('**/*.hbs');
115
-
116
- function maybeRewriteHBS(resolution: ResolvedId) {
117
- if (!hbsFilter(resolution.id)) {
118
- return null;
119
- }
120
- debug('emitting hbs rewrite: %s', resolution.id);
121
- return {
122
- ...resolution,
123
- meta: {
124
- 'rollup-hbs-plugin': {
125
- type: 'template',
126
- },
127
- },
128
- };
129
- }
package/src/request.ts DELETED
@@ -1,55 +0,0 @@
1
- import { ModuleRequest, cleanUrl } from '@embroider/core';
2
-
3
- export const virtualPrefix = 'embroider_virtual:';
4
-
5
- export class RollupModuleRequest implements ModuleRequest {
6
- static from(
7
- source: string,
8
- importer: string | undefined,
9
- custom: Record<string, any> | undefined
10
- ): RollupModuleRequest | undefined {
11
- if (!(custom?.embroider?.enableCustomResolver ?? true)) {
12
- return;
13
- }
14
-
15
- if (source && importer && source[0] !== '\0') {
16
- let nonVirtual: string;
17
- if (importer.startsWith(virtualPrefix)) {
18
- nonVirtual = importer.slice(virtualPrefix.length);
19
- } else {
20
- nonVirtual = importer;
21
- }
22
-
23
- // strip query params off the importer
24
- let fromFile = cleanUrl(nonVirtual);
25
- return new RollupModuleRequest(source, fromFile, custom?.embroider?.meta);
26
- }
27
- }
28
-
29
- private constructor(
30
- readonly specifier: string,
31
- readonly fromFile: string,
32
- readonly meta: Record<string, any> | undefined
33
- ) {}
34
-
35
- get isVirtual(): boolean {
36
- return this.specifier.startsWith(virtualPrefix);
37
- }
38
-
39
- alias(newSpecifier: string) {
40
- return new RollupModuleRequest(newSpecifier, this.fromFile, this.meta) as this;
41
- }
42
- rehome(newFromFile: string) {
43
- if (this.fromFile === newFromFile) {
44
- return this;
45
- } else {
46
- return new RollupModuleRequest(this.specifier, newFromFile, this.meta) as this;
47
- }
48
- }
49
- virtualize(filename: string) {
50
- return new RollupModuleRequest(virtualPrefix + filename, this.fromFile, this.meta) as this;
51
- }
52
- withMeta(meta: Record<string, any> | undefined): this {
53
- return new RollupModuleRequest(this.specifier, this.fromFile, meta) as this;
54
- }
55
- }
package/src/resolver.ts DELETED
@@ -1,69 +0,0 @@
1
- import type { PluginContext, ResolveIdResult } from 'rollup';
2
- import { Plugin } from 'vite';
3
- import { join } from 'path';
4
- import {
5
- Resolution,
6
- Resolver,
7
- ResolverFunction,
8
- ResolverOptions,
9
- locateEmbroiderWorkingDir,
10
- virtualContent,
11
- } from '@embroider/core';
12
- import { readJSONSync } from 'fs-extra';
13
- import { RollupModuleRequest, virtualPrefix } from './request';
14
- import assertNever from 'assert-never';
15
-
16
- export function resolver(): Plugin {
17
- let resolverOptions: ResolverOptions = readJSONSync(join(locateEmbroiderWorkingDir(process.cwd()), 'resolver.json'));
18
- let resolver = new Resolver(resolverOptions);
19
-
20
- return {
21
- name: 'embroider-resolver',
22
- enforce: 'pre',
23
- async resolveId(source, importer, options) {
24
- let request = RollupModuleRequest.from(source, importer, options.custom);
25
- if (!request) {
26
- // fallthrough to other rollup plugins
27
- return null;
28
- }
29
- let resolution = await resolver.resolve(request, defaultResolve(this));
30
- switch (resolution.type) {
31
- case 'found':
32
- return resolution.result;
33
- case 'not_found':
34
- return null;
35
- default:
36
- throw assertNever(resolution);
37
- }
38
- },
39
- load(id) {
40
- if (id.startsWith(virtualPrefix)) {
41
- return virtualContent(id.slice(virtualPrefix.length), resolver);
42
- }
43
- },
44
- };
45
- }
46
-
47
- function defaultResolve(context: PluginContext): ResolverFunction<RollupModuleRequest, Resolution<ResolveIdResult>> {
48
- return async (request: RollupModuleRequest) => {
49
- if (request.isVirtual) {
50
- return {
51
- type: 'found',
52
- result: { id: request.specifier, resolvedBy: request.fromFile },
53
- };
54
- }
55
- let result = await context.resolve(request.specifier, request.fromFile, {
56
- skipSelf: true,
57
- custom: {
58
- embroider: {
59
- meta: request.meta,
60
- },
61
- },
62
- });
63
- if (result) {
64
- return { type: 'found', result };
65
- } else {
66
- return { type: 'not_found', err: undefined };
67
- }
68
- };
69
- }
package/src/scripts.ts DELETED
@@ -1,136 +0,0 @@
1
- import type { Plugin } from 'vite';
2
- import type { EmittedFile } from 'rollup';
3
- import { JSDOM } from 'jsdom';
4
- import { readFileSync, readJSONSync } from 'fs-extra';
5
- import { dirname, posix, resolve } from 'path';
6
-
7
- // This is a type-only import, so it gets compiled away. At runtime, we load
8
- // terser lazily so it's only loaded for production builds that use it. Don't
9
- // add any non-type-only imports here.
10
- import type { MinifyOptions } from 'terser';
11
-
12
- const defaults = ['/assets/vendor.js', '/assets/test-support.js'];
13
-
14
- export function scripts(params?: { include?: string[]; exclude?: string[] }): Plugin {
15
- let optimizer: ScriptOptimizer;
16
-
17
- // configured names are always interpreted as origin-absolute URLs.
18
- let names = (params?.include ?? defaults)
19
- .filter(name => !params?.exclude?.includes(name))
20
- .map(name => {
21
- if (name.startsWith('/')) {
22
- return name;
23
- } else {
24
- return '/' + name;
25
- }
26
- });
27
-
28
- return {
29
- name: 'embroider-scripts',
30
- enforce: 'pre',
31
-
32
- configResolved(resolvedConfig) {
33
- optimizer = new ScriptOptimizer(resolvedConfig.root);
34
- },
35
-
36
- async generateBundle() {
37
- // this hook only runs in `vite build`
38
- for (let name of names) {
39
- for (let file of await optimizer.optimizedScript(name)) {
40
- this.emitFile(file);
41
- }
42
- }
43
- },
44
-
45
- transformIndexHtml(htmlIn, context) {
46
- // we don't do anything in `vite dev`, we only need to work in `vite
47
- // build`
48
- if (!context.server) {
49
- return optimizer.transformHTML(htmlIn);
50
- }
51
- },
52
- };
53
- }
54
-
55
- class ScriptOptimizer {
56
- private emitted = new Map<string, string>();
57
- private transformState:
58
- | {
59
- htmlIn: string;
60
- htmlOut: string;
61
- parsed: JSDOM;
62
- }
63
- | undefined;
64
-
65
- constructor(private rootDir: string) {}
66
-
67
- async optimizedScript(script: string): Promise<EmittedFile[]> {
68
- // loading these lazily here so they never load in non-production builds.
69
- // The node cache will ensures we only load them once.
70
- const [Terser, srcURL] = await Promise.all([import('terser'), import('source-map-url')]);
71
-
72
- let inCode = readFileSync(resolve(this.rootDir, script.slice(1)), 'utf8');
73
- let terserOpts: MinifyOptions = {};
74
- let fileRelativeSourceMapURL;
75
- let appRelativeSourceMapURL;
76
- if (srcURL.default.existsIn(inCode)) {
77
- fileRelativeSourceMapURL = srcURL.default.getFrom(inCode)!;
78
- appRelativeSourceMapURL = posix.join(dirname(script.slice(1)), fileRelativeSourceMapURL);
79
- let content;
80
- try {
81
- content = readJSONSync(resolve(this.rootDir, appRelativeSourceMapURL));
82
- } catch (err) {
83
- // the script refers to a sourcemap that doesn't exist, so we just leave
84
- // the map out.
85
- }
86
- if (content) {
87
- terserOpts.sourceMap = { content, url: fileRelativeSourceMapURL };
88
- }
89
- }
90
- let { code: outCode, map: outMap } = await Terser.default.minify(inCode, terserOpts);
91
- let finalFilename = await this.getFingerprintedFilename(script, outCode!);
92
- let emit: EmittedFile[] = [];
93
- emit.push({
94
- type: 'asset',
95
- fileName: finalFilename.slice(1),
96
- source: outCode!,
97
- });
98
- this.emitted.set(script, finalFilename);
99
- if (appRelativeSourceMapURL && outMap) {
100
- emit.push({
101
- type: 'asset',
102
- fileName: appRelativeSourceMapURL,
103
- source: JSON.stringify(outMap, null, 2),
104
- });
105
- }
106
- return emit;
107
- }
108
-
109
- async getFingerprintedFilename(filename: string, content: string): Promise<string> {
110
- let crypto = await import('crypto');
111
- let md5 = crypto.createHash('md5');
112
- md5.update(content);
113
- let hash = md5.digest('hex');
114
- let fileParts = filename.split('.');
115
- fileParts.splice(fileParts.length - 1, 0, hash);
116
- return fileParts.join('.');
117
- }
118
-
119
- transformHTML(htmlIn: string) {
120
- if (this.transformState?.htmlIn !== htmlIn) {
121
- let parsed = new JSDOM(htmlIn);
122
- let scriptTags = [...parsed.window.document.querySelectorAll('script')] as HTMLScriptElement[];
123
- for (let scriptTag of scriptTags) {
124
- if (scriptTag.type !== 'module') {
125
- let fingerprinted = this.emitted.get(scriptTag.src);
126
- if (fingerprinted) {
127
- scriptTag.src = fingerprinted;
128
- }
129
- }
130
- }
131
- let htmlOut = parsed.serialize();
132
- this.transformState = { htmlIn, parsed, htmlOut };
133
- }
134
- return this.transformState.htmlOut;
135
- }
136
- }
@@ -1,50 +0,0 @@
1
- import { createFilter } from '@rollup/pluginutils';
2
- import type { Plugin } from 'vite';
3
- import { readFileSync } from 'fs';
4
- import { Preprocessor } from 'content-tag';
5
-
6
- const gjsFilter = createFilter('**/*.gjs');
7
-
8
- export function templateTag(): Plugin {
9
- let preprocessor = new Preprocessor();
10
-
11
- function candidates(id: string) {
12
- return [id + '.gjs'];
13
- }
14
-
15
- return {
16
- name: 'embroider-template-tag',
17
- enforce: 'pre',
18
-
19
- async resolveId(id: string, importer: string | undefined) {
20
- let resolution = await this.resolve(id, importer, {
21
- skipSelf: true,
22
- });
23
- if (resolution) {
24
- return resolution;
25
- }
26
- for (let candidate of candidates(id)) {
27
- resolution = await this.resolve(candidate, importer, {
28
- skipSelf: true,
29
- custom: {
30
- embroider: {
31
- enableCustomResolver: false,
32
- },
33
- },
34
- });
35
- if (resolution) {
36
- return {
37
- id: resolution.id,
38
- };
39
- }
40
- }
41
- },
42
-
43
- load(id: string) {
44
- if (!gjsFilter(id)) {
45
- return null;
46
- }
47
- return preprocessor.process(readFileSync(id, 'utf8'), id);
48
- },
49
- };
50
- }