@open-xchange/vite-plugin-replace-pkg 0.0.1 → 0.0.3

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,5 +1,15 @@
1
1
  # Changelog
2
2
 
3
- ## [0.0.1] - 2024-08-06
3
+ ## [0.0.3] - 2024-08-09
4
+
5
+ - added: options `prepend`, `append`, `exportGlobal`
6
+ - changed: made option `replace.token` optional (defaults to `GITLAB_TOKEN` env var)
7
+ - fixed: inactive log level "info"
8
+
9
+ ## [0.0.2] - 2024-08-07
10
+
11
+ - changed: GitLab API token as plugin parameter instead of env var
12
+
13
+ ## [0.0.1] - 2024-08-07
4
14
 
5
15
  - 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_
@@ -108,6 +108,7 @@ The location of the source file to resolve the module imports with. There are di
108
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. |
109
109
  | `path` | `string` | _required_ | Path to the source file to be downloaded. Slashes in the path will be encoded internally. |
110
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. |
111
112
 
112
113
  Example:
113
114
 
@@ -152,7 +153,7 @@ The location of the source file to resolve the module imports with. There are di
152
153
  })
153
154
  ```
154
155
 
155
- #### `transform`
156
+ #### Option `transform`
156
157
 
157
158
  - Type: `(source: string) => string | string[] | Promise<string | string[]>`
158
159
  - _optional_
@@ -172,8 +173,113 @@ export default defineConfig(() => {
172
173
  replacePlugin({
173
174
  package: "external-package"
174
175
  replace: "https://example.org/path/to/index.js",
175
- transform: source => ["/* replaced file header */", source],
176
+ transform: source => source.replaceAll(/* ... */)
176
177
  }),
177
178
  ],
178
179
  })
179
180
  ```
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
+
283
+ ### Logging
284
+
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
@@ -16,10 +16,6 @@ export interface VitePluginReplacePkg_RequestInit extends RequestInit {
16
16
  }
17
17
  /**
18
18
  * The specification of a source file in a GitLab repository.
19
- *
20
- * Downloading the source file needs a valid GitLab API token stored in the
21
- * environment variable "GITLAB_TOKEN". If the variable does not exist,
22
- * downloading the source wile will be skipped.
23
19
  */
24
20
  export interface VitePluginReplacePkg_GitLabFile {
25
21
  /**
@@ -42,6 +38,12 @@ export interface VitePluginReplacePkg_GitLabFile {
42
38
  * will be encoded internally. Default value is "HEAD".
43
39
  */
44
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;
45
47
  }
46
48
  /**
47
49
  * A custom callback function to fetch the replacement source code for an
@@ -74,6 +76,28 @@ export interface VitePluginReplacePkgOptions {
74
76
  * multiple source lines.
75
77
  */
76
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;
77
101
  }
78
102
  export declare const PROJECT_NAME = "@open-xchange/vite-plugin-replace-pkg";
79
103
  /**
package/dist/index.js CHANGED
@@ -2,49 +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_PACKAGES_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
- // resolve GitLab API tokens
27
- const token = process.env.GITLAB_TOKEN;
28
- if (!token) {
29
- logger.warn("missing environment variable %f with GitLab API token", "GITLAB_TOKEN");
30
- return;
31
- }
32
- // build the file URL for the GitLab API
33
- // https://docs.gitlab.com/ee/api/repository_files.html#get-raw-file-from-repository
34
- const project = encodeURIComponent(replace.project);
35
- const path = encodeURIComponent(replace.path);
36
- const url = `${replace.server}/api/v4/projects/${project}/repository/files/${path}/raw`;
37
- // additional settings (query, headers, etc.)
38
- const query = { lfs: true };
39
- if (replace.ref) {
40
- query.ref = replace.ref;
41
- }
42
- const headers = { "PRIVATE-TOKEN": token };
43
- return { url, headers, query };
44
- }
45
- logger.error("invalid configuration for package %f", options.package);
46
- return undefined;
47
- };
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
+ }
48
19
  // plugin =====================================================================
49
20
  /**
50
21
  * A plugin for Vite to replace a specific external package with an arbitrary
@@ -61,12 +32,58 @@ const resolveFetchOptions = (options) => {
61
32
  export default function vitePluginReplacePkg(options) {
62
33
  const pkgName = options.package;
63
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")
64
81
  const fetchSourceFile = onceFn(async () => {
65
82
  try {
66
83
  if (typeof options.replace === "function") {
67
84
  return await options.replace(pkgName);
68
85
  }
69
- const fetchOptions = resolveFetchOptions(options);
86
+ const fetchOptions = resolveFetchOptions();
70
87
  if (fetchOptions) {
71
88
  const query = Object.entries(fetchOptions.query ?? {}).map(entry => entry.map(encodeURIComponent).join("=")).join("&");
72
89
  const url = fetchOptions.url + (query ? `?${query}` : "");
@@ -95,6 +112,7 @@ export default function vitePluginReplacePkg(options) {
95
112
  if (source !== pkgName) {
96
113
  return;
97
114
  }
115
+ // try to fetch source file, skip "load" hook if not available
98
116
  const contents = await fetchSourceFile();
99
117
  return contents ? moduleId : undefined;
100
118
  },
@@ -103,9 +121,25 @@ export default function vitePluginReplacePkg(options) {
103
121
  if (id !== moduleId) {
104
122
  return;
105
123
  }
106
- const contents = await fetchSourceFile();
107
- const transformed = options.transform ? await options.transform(contents) : contents;
108
- 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;
109
143
  },
110
144
  };
111
145
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-xchange/vite-plugin-replace-pkg",
3
- "version": "0.0.1",
3
+ "version": "0.0.3",
4
4
  "description": "Vite plugin replacing a specific external package with an arbitrary source code module",
5
5
  "repository": {
6
6
  "url": "https://gitlab.open-xchange.com/fspd/npm-packages/vite-plugin-replace-pkg"
@@ -22,15 +22,15 @@
22
22
  "*.{js,ts,json}": "yarn lint"
23
23
  },
24
24
  "dependencies": {
25
- "@open-xchange/vite-helper": "0.0.3"
25
+ "@open-xchange/vite-helper": "0.1.1"
26
26
  },
27
27
  "devDependencies": {
28
- "@open-xchange/linter-presets": "0.4.2",
28
+ "@open-xchange/linter-presets": "0.4.3",
29
29
  "@types/node": "22.1.0",
30
30
  "eslint": "9.8.0",
31
31
  "husky": "9.1.4",
32
32
  "typescript": "5.5.4",
33
- "vite": "5.3.5"
33
+ "vite": "5.4.0"
34
34
  },
35
35
  "peerDependencies": {
36
36
  "vite": "^5.3"