@open-xchange/vite-plugin-replace-pkg 0.0.2 → 0.0.4

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/CHANGELOG.md CHANGED
@@ -1,9 +1,19 @@
1
1
  # Changelog
2
2
 
3
- ## [0.0.2] - 2024-08-07
3
+ ## `0.0.4` 2024-Oct-21
4
+
5
+ - chore: fixed repository URL in package.json
6
+
7
+ ## `0.0.3` – 2024-Aug-09
8
+
9
+ - added: options `prepend`, `append`, `exportGlobal`
10
+ - changed: made option `replace.token` optional (defaults to `GITLAB_TOKEN` env var)
11
+ - fixed: inactive log level "info"
12
+
13
+ ## `0.0.2` – 2024-Aug-07
4
14
 
5
15
  - changed: GitLab API token as plugin parameter instead of env var
6
16
 
7
- ## [0.0.1] - 2024-08-07
17
+ ## `0.0.1` 2024-Aug-07
8
18
 
9
19
  - initial release
package/README.md CHANGED
@@ -54,14 +54,14 @@ export default defineConfig(() => {
54
54
 
55
55
  ### Options
56
56
 
57
- #### `package`
57
+ #### Option `package`
58
58
 
59
59
  - Type: `string`
60
60
  - _required_
61
61
 
62
62
  The name of the external package to be replaced, as appearing in `import` statements in source code.
63
63
 
64
- #### `replace`
64
+ #### Option `replace`
65
65
 
66
66
  - Type: _various (see below)_
67
67
  - _required_
@@ -105,10 +105,10 @@ The location of the source file to resolve the module imports with. There are di
105
105
  | Name | Type | Default | Description |
106
106
  | - | - | - | - |
107
107
  | `server` | `string` | _required_ | The URL of the GitLab server to be used for downloading the source file. |
108
- | `token` | `string\|undefined` | _required_ | A valid GitLab API access token. If the token does not exist or is empty, downloading the source wile will be skipped silently. |
109
108
  | `project` | `string\|number` | _required_ | Name or numeric identifier of the GitLab project. The project name may contain slashes (e.g. `"my-group/my-project"`) which will be encoded internally. |
110
109
  | `path` | `string` | _required_ | Path to the source file to be downloaded. Slashes in the path will be encoded internally. |
111
110
  | `ref` | `string` | `HEAD` | The name of a branch or tag, or a commit ID. Slashes in branch names will be encoded internally. |
111
+ | `token` | `string` | environment variable `GITLAB_TOKEN` | A valid GitLab API access token. If omitted, uses the contents of the environment variable `GITLAB_TOKEN`. If the resulting token is empty, downloading the source file will be skipped silently. |
112
112
 
113
113
  Example:
114
114
 
@@ -153,7 +153,7 @@ The location of the source file to resolve the module imports with. There are di
153
153
  })
154
154
  ```
155
155
 
156
- #### `transform`
156
+ #### Option `transform`
157
157
 
158
158
  - Type: `(source: string) => string | string[] | Promise<string | string[]>`
159
159
  - _optional_
@@ -173,12 +173,113 @@ export default defineConfig(() => {
173
173
  replacePlugin({
174
174
  package: "external-package"
175
175
  replace: "https://example.org/path/to/index.js",
176
- transform: source => ["/* replaced file header */", source],
176
+ transform: source => source.replaceAll(/* ... */)
177
177
  }),
178
178
  ],
179
179
  })
180
180
  ```
181
181
 
182
+ #### Option `prepend`
183
+
184
+ - Type: `string | string[]`
185
+ - _optional_
186
+
187
+ Inserts arbitrary source code to the beginning of the replacement module. An array of strings will be concatenated with newline characters.
188
+
189
+ This option will be applied after source code transformation (option `transform`).
190
+
191
+ Example:
192
+
193
+ ```ts
194
+ // vite.config.ts
195
+
196
+ import { defineConfig } from "vite" // or "vitest/config"
197
+ import replacePlugin from "@open-xchange/vite-plugin-replace-pkg"
198
+
199
+ export default defineConfig(() => {
200
+ plugins: [
201
+ replacePlugin({
202
+ package: "external-package"
203
+ replace: "https://example.org/path/to/index.js",
204
+ prepend: [/* ... */],
205
+ }),
206
+ ],
207
+ })
208
+ ```
209
+
210
+ #### Option `append`
211
+
212
+ - Type: `string | string[]`
213
+ - _optional_
214
+
215
+ Inserts arbitrary source code to the end of the replacement module. An array of strings will be concatenated with newline characters.
216
+
217
+ This option will be applied after source code transformation (option `transform`).
218
+
219
+ Example:
220
+
221
+ ```ts
222
+ // vite.config.ts
223
+
224
+ import { defineConfig } from "vite" // or "vitest/config"
225
+ import replacePlugin from "@open-xchange/vite-plugin-replace-pkg"
226
+
227
+ export default defineConfig(() => {
228
+ plugins: [
229
+ replacePlugin({
230
+ package: "external-package"
231
+ replace: "https://example.org/path/to/index.js",
232
+ append: [/* ... */],
233
+ }),
234
+ ],
235
+ })
236
+ ```
237
+
238
+ #### Option `exportGlobal`
239
+
240
+ - Type: `string`
241
+ - _optional_
242
+
243
+ Specifies the name of a global variable that will be defined by the replacement module. This plugin will append source code to the replacement module that will delete the variable from global scope, and will export it as the default export instead.
244
+
245
+ This option will be applied after source code transformation (option `transform`).
246
+
247
+ Example:
248
+
249
+ ```ts
250
+ // vite.config.ts
251
+
252
+ import { defineConfig } from "vite" // or "vitest/config"
253
+ import replacePlugin from "@open-xchange/vite-plugin-replace-pkg"
254
+
255
+ export default defineConfig(() => {
256
+ plugins: [
257
+ replacePlugin({
258
+ package: "external-package"
259
+ replace: "https://example.org/path/to/index.js",
260
+ exportGlobal: "TheModule",
261
+ }),
262
+ ],
263
+ })
264
+ ```
265
+
266
+ is equivalent to
267
+
268
+ ```ts
269
+ // vite.config.ts
270
+
271
+ // ...
272
+ replacePlugin({
273
+ package: "external-package"
274
+ replace: "https://example.org/path/to/index.js",
275
+ append: [
276
+ "const __contents = globalThis.TheModule",
277
+ "delete globalThis.TheModule",
278
+ "export default __contents",
279
+ ],
280
+ }),
281
+ ```
282
+
182
283
  ### Logging
183
284
 
184
285
  By default, warning messages and error messages will be logged to the shell. The environment variable `PLUGIN_REPLACE_PKG_LOGLEVEL` can be used to change the log level of this plugin. Possible values are `info`, `warn`, `error`, and `silent`.
package/dist/index.d.ts CHANGED
@@ -22,11 +22,6 @@ export interface VitePluginReplacePkg_GitLabFile {
22
22
  * The URL of the GitLab server to be used for downloading the source file.
23
23
  */
24
24
  server: string;
25
- /**
26
- * A valid GitLab API access token. If the token does not exist or is an
27
- * empty string, downloading the source wile will be skipped silently.
28
- */
29
- token: string | undefined;
30
25
  /**
31
26
  * Name or identifier of the GitLab project (repository). The project name
32
27
  * may contain slashes (e.g. "my-group/my-project") which will be encoded
@@ -43,6 +38,12 @@ export interface VitePluginReplacePkg_GitLabFile {
43
38
  * will be encoded internally. Default value is "HEAD".
44
39
  */
45
40
  ref?: string;
41
+ /**
42
+ * A valid GitLab API access token. If omitted, uses the contents of the
43
+ * environment variable `GITLAB_TOKEN`. If the resulting token is empty,
44
+ * downloading the source file will be skipped silently.
45
+ */
46
+ token?: string;
46
47
  }
47
48
  /**
48
49
  * A custom callback function to fetch the replacement source code for an
@@ -75,6 +76,28 @@ export interface VitePluginReplacePkgOptions {
75
76
  * multiple source lines.
76
77
  */
77
78
  transform?: (source: string) => string | string[] | Promise<string | string[]>;
79
+ /**
80
+ * Inserts arbitrary source code to the beginning of the replacement
81
+ * module. An array of strings will be concatenated with newline
82
+ * characters. This option will be applied after source code transformation
83
+ * (option `transform`).
84
+ */
85
+ prepend?: string | string[];
86
+ /**
87
+ * Inserts arbitrary source code to the end of the replacement module. An
88
+ * array of strings will be concatenated with newline characters. This
89
+ * option will be applied after source code transformation (option
90
+ * `transform`).
91
+ */
92
+ append?: string | string[];
93
+ /**
94
+ * Specifies the name of a global variable that will be defined by the
95
+ * replacement module. This plugin will append source code to the
96
+ * replacement module that will delete the variable from global scope, and
97
+ * will export it as the default export instead. This option will be
98
+ * applied after source code transformation (option `transform`).
99
+ */
100
+ exportGlobal?: string;
78
101
  }
79
102
  export declare const PROJECT_NAME = "@open-xchange/vite-plugin-replace-pkg";
80
103
  /**
package/dist/index.js CHANGED
@@ -2,48 +2,20 @@ import { onceFn } from "@open-xchange/vite-helper/utils";
2
2
  import { Logger } from "@open-xchange/vite-helper/logger";
3
3
  // constants ==================================================================
4
4
  export const PROJECT_NAME = "@open-xchange/vite-plugin-replace-pkg";
5
- const logger = new Logger({
6
- loggerPrefix: "pkg",
7
- logLevelEnvVar: "PLUGIN_REPLACE_PKG_LOGLEVEL",
8
- });
9
5
  // functions ==================================================================
10
- const resolveFetchOptions = (options) => {
11
- const { replace } = options;
12
- // callback function
13
- if (typeof replace === "function") {
14
- return;
15
- }
16
- // plain string
17
- if (typeof replace === "string") {
18
- return replace ? { url: replace } : undefined;
19
- }
20
- // `RequestInit` object
21
- if ("url" in replace) {
22
- return replace.url ? replace : undefined;
23
- }
24
- // `GitLabFile` object
25
- if ("project" in replace) {
26
- // GitLab API token
27
- if (!replace.token) {
28
- logger.warn("missing GitLab API token");
29
- return;
30
- }
31
- // build the file URL for the GitLab API
32
- // https://docs.gitlab.com/ee/api/repository_files.html#get-raw-file-from-repository
33
- const project = encodeURIComponent(replace.project);
34
- const path = encodeURIComponent(replace.path);
35
- const url = `${replace.server}/api/v4/projects/${project}/repository/files/${path}/raw`;
36
- // additional settings (query, headers, etc.)
37
- const query = { lfs: true };
38
- if (replace.ref) {
39
- query.ref = replace.ref;
40
- }
41
- const headers = { "PRIVATE-TOKEN": replace.token };
42
- return { url, headers, query };
43
- }
44
- logger.error("invalid configuration for package %f", options.package);
45
- return undefined;
46
- };
6
+ /**
7
+ * Joins a string array with newline characters, ensures trailing newline.
8
+ *
9
+ * @param contents
10
+ * The string contents to be flattened.
11
+ *
12
+ * @returns
13
+ * The flattened contents.
14
+ */
15
+ function flatten(contents) {
16
+ const result = Array.isArray(contents) ? contents.join("\n") : contents;
17
+ return result.endsWith("\n") ? result : (result + "\n");
18
+ }
47
19
  // plugin =====================================================================
48
20
  /**
49
21
  * A plugin for Vite to replace a specific external package with an arbitrary
@@ -60,12 +32,58 @@ const resolveFetchOptions = (options) => {
60
32
  export default function vitePluginReplacePkg(options) {
61
33
  const pkgName = options.package;
62
34
  const moduleId = "\0" + PROJECT_NAME + "/" + pkgName;
35
+ // must not be instantiated globally (needs initialized environment variables)
36
+ const logger = new Logger({
37
+ loggerPrefix: "pkg",
38
+ logLevelEnvVar: "PLUGIN_REPLACE_PKG_LOGLEVEL",
39
+ });
40
+ // resolves the URL of the replacement module to be fetched
41
+ const resolveFetchOptions = () => {
42
+ logger.info("resolving replacement module for %f", pkgName);
43
+ const { replace } = options;
44
+ // callback function
45
+ if (typeof replace === "function") {
46
+ return;
47
+ }
48
+ // plain string
49
+ if (typeof replace === "string") {
50
+ return replace ? { url: replace } : undefined;
51
+ }
52
+ // `RequestInit` object
53
+ if ("url" in replace) {
54
+ return replace.url ? replace : undefined;
55
+ }
56
+ // `GitLabFile` object
57
+ if ("project" in replace) {
58
+ // GitLab API token
59
+ const token = replace.token ?? process.env.GITLAB_TOKEN;
60
+ if (!token) {
61
+ logger.warn("missing GitLab API token");
62
+ return;
63
+ }
64
+ // build the file URL for the GitLab API
65
+ // https://docs.gitlab.com/ee/api/repository_files.html#get-raw-file-from-repository
66
+ const project = encodeURIComponent(replace.project);
67
+ const path = encodeURIComponent(replace.path);
68
+ const url = `${replace.server}/api/v4/projects/${project}/repository/files/${path}/raw`;
69
+ // additional settings (query, headers, etc.)
70
+ const query = { lfs: true };
71
+ if (replace.ref) {
72
+ query.ref = replace.ref;
73
+ }
74
+ const headers = { "PRIVATE-TOKEN": token };
75
+ return { url, headers, query };
76
+ }
77
+ logger.error("invalid configuration for package %f", pkgName);
78
+ return undefined;
79
+ };
80
+ // fetches the replacement module ("onceFn" wrapped to be called from "resolveId" and "load")
63
81
  const fetchSourceFile = onceFn(async () => {
64
82
  try {
65
83
  if (typeof options.replace === "function") {
66
84
  return await options.replace(pkgName);
67
85
  }
68
- const fetchOptions = resolveFetchOptions(options);
86
+ const fetchOptions = resolveFetchOptions();
69
87
  if (fetchOptions) {
70
88
  const query = Object.entries(fetchOptions.query ?? {}).map(entry => entry.map(encodeURIComponent).join("=")).join("&");
71
89
  const url = fetchOptions.url + (query ? `?${query}` : "");
@@ -94,6 +112,7 @@ export default function vitePluginReplacePkg(options) {
94
112
  if (source !== pkgName) {
95
113
  return;
96
114
  }
115
+ // try to fetch source file, skip "load" hook if not available
97
116
  const contents = await fetchSourceFile();
98
117
  return contents ? moduleId : undefined;
99
118
  },
@@ -102,9 +121,25 @@ export default function vitePluginReplacePkg(options) {
102
121
  if (id !== moduleId) {
103
122
  return;
104
123
  }
105
- const contents = await fetchSourceFile();
106
- const transformed = options.transform ? await options.transform(contents) : contents;
107
- return Array.isArray(transformed) ? transformed.join("\n") : transformed;
124
+ const { transform, prepend, append, exportGlobal } = options;
125
+ let contents = flatten(await fetchSourceFile());
126
+ if (transform) {
127
+ contents = flatten(await transform(contents));
128
+ }
129
+ if (prepend) {
130
+ contents = flatten(prepend) + contents;
131
+ }
132
+ if (append) {
133
+ contents += flatten(append);
134
+ }
135
+ if (exportGlobal) {
136
+ contents += flatten([
137
+ `const __contents = globalThis["${exportGlobal}"];`,
138
+ `delete globalThis["${exportGlobal}"];`,
139
+ "export default __contents;",
140
+ ]);
141
+ }
142
+ return contents;
108
143
  },
109
144
  };
110
145
  }
package/package.json CHANGED
@@ -1,41 +1,39 @@
1
1
  {
2
- "name": "@open-xchange/vite-plugin-replace-pkg",
3
- "version": "0.0.2",
4
- "description": "Vite plugin replacing a specific external package with an arbitrary source code module",
5
- "repository": {
6
- "url": "https://gitlab.open-xchange.com/fspd/npm-packages/vite-plugin-replace-pkg"
7
- },
8
- "license": "MIT",
9
- "engines": {
10
- "node": "18.18.0 || ^20.9.0 || >=21.1.0"
11
- },
12
- "packageManager": "yarn@4.4.0",
13
- "type": "module",
14
- "exports": "./dist/index.js",
15
- "scripts": {
16
- "prepare": "husky",
17
- "prepack": "yarn build && yarn lint",
18
- "build": "npx --yes rimraf dist && tsc",
19
- "lint": "eslint ."
20
- },
21
- "lint-staged": {
22
- "*.{js,ts,json}": "yarn lint"
23
- },
24
- "dependencies": {
25
- "@open-xchange/vite-helper": "0.0.3"
26
- },
27
- "devDependencies": {
28
- "@open-xchange/linter-presets": "0.4.2",
29
- "@types/node": "22.1.0",
30
- "eslint": "9.8.0",
31
- "husky": "9.1.4",
32
- "typescript": "5.5.4",
33
- "vite": "5.3.5"
34
- },
35
- "peerDependencies": {
36
- "vite": "^5.3"
37
- },
38
- "resolutions": {
39
- "semver": "^7.6.2"
40
- }
41
- }
2
+ "name": "@open-xchange/vite-plugin-replace-pkg",
3
+ "version": "0.0.4",
4
+ "description": "Vite plugin replacing a specific external package with an arbitrary source code module",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "https://gitlab.open-xchange.com/fspd/commons/plugins/-/tree/main/packages/vite-plugin-replace-pkg"
8
+ },
9
+ "license": "MIT",
10
+ "engines": {
11
+ "node": "18.18.0 || ^20.9.0 || >=21.1.0"
12
+ },
13
+ "packageManager": "yarn@4.5.0",
14
+ "type": "module",
15
+ "exports": "./dist/index.js",
16
+ "scripts": {
17
+ "prepare": "yarn build",
18
+ "prepack": "yarn build && yarn lint",
19
+ "build": "rimraf dist && tsc",
20
+ "lint": "eslint ."
21
+ },
22
+ "dependencies": {
23
+ "@open-xchange/vite-helper": "0.1.2"
24
+ },
25
+ "devDependencies": {
26
+ "@open-xchange/linter-presets": "0.8.8",
27
+ "@types/node": "22.7.6",
28
+ "eslint": "9.12.0",
29
+ "rimraf": "6.0.1",
30
+ "typescript": "5.6.3",
31
+ "vite": "5.4.9"
32
+ },
33
+ "peerDependencies": {
34
+ "vite": "^5.3"
35
+ },
36
+ "resolutions": {
37
+ "semver": "^7.6.2"
38
+ }
39
+ }
@@ -1,3 +0,0 @@
1
- {
2
- "typescript.tsdk": "node_modules/typescript/lib"
3
- }
package/LICENSE DELETED
@@ -1,21 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2024 OX Software GmbH, Germany <info@open-xchange.com>
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.