@witchcraft/nuxt-electron 0.4.4 → 0.4.5
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/README.md +36 -11
- package/dist/module.d.mts +10 -0
- package/dist/module.json +1 -1
- package/dist/module.mjs +18 -5
- package/dist/runtime/electron/main/getPaths.d.ts +4 -2
- package/dist/runtime/electron/main/getPaths.js +2 -2
- package/dist/runtime/electron/test/index.d.ts +4 -0
- package/dist/runtime/electron/test/index.js +4 -0
- package/dist/runtime/electron/test/launchApp.d.ts +27 -0
- package/dist/runtime/electron/test/launchApp.js +59 -0
- package/dist/runtime/electron/test/launchElectron.d.ts +20 -0
- package/dist/runtime/electron/test/launchElectron.js +121 -0
- package/dist/runtime/electron/test/localhostUrl.d.ts +1 -0
- package/dist/runtime/electron/test/localhostUrl.js +4 -0
- package/dist/runtime/electron/test/waitUntilAtPath.d.ts +2 -0
- package/dist/runtime/electron/test/waitUntilAtPath.js +3 -0
- package/package.json +14 -3
- package/src/module.ts +32 -5
- package/src/runtime/electron/main/getPaths.ts +6 -3
- package/src/runtime/electron/test/index.ts +4 -0
- package/src/runtime/electron/test/launchApp.ts +94 -0
- package/src/runtime/electron/test/launchElectron.ts +176 -0
- package/src/runtime/electron/test/localhostUrl.ts +9 -0
- package/src/runtime/electron/test/waitUntilAtPath.ts +8 -0
package/README.md
CHANGED
|
@@ -138,7 +138,7 @@ Add the following to the package.json:
|
|
|
138
138
|
"description": "Your app description",
|
|
139
139
|
"author": "Your Name",
|
|
140
140
|
"repository" :"...",
|
|
141
|
-
"main": ".dist/electron/build/main.
|
|
141
|
+
"main": ".dist/electron/build/main.mjs",
|
|
142
142
|
"scripts": {
|
|
143
143
|
"dev": "nuxi dev",
|
|
144
144
|
"build": "nuxi build",
|
|
@@ -147,9 +147,11 @@ Add the following to the package.json:
|
|
|
147
147
|
"dev:electron": "AUTO_OPEN=electron pnpm dev",
|
|
148
148
|
"launch:electron": "electron .",
|
|
149
149
|
"launch:electron:dev": "LOG_LEVEL=trace OVERRIDE_PUBLIC_SERVER_URL=http://localhost:3000 electron .",
|
|
150
|
-
//
|
|
150
|
+
// release build
|
|
151
|
+
// use a custom env like "PRODUCTION_BUILD" to control the baking of the "baked" production env
|
|
151
152
|
"build:electron": "PRODUCTION_BUILD=true BUILD_ELECTRON=true pnpm build",
|
|
152
153
|
"build:electron:pack": "APP_VERSION=0.0.0 electron-builder --config electron-builder-config.js",
|
|
154
|
+
// local dev build, could be used for testing (note the lack of the baked env control)
|
|
153
155
|
"build:electron:no-pack": "APP_VERSION=0.0.0 SKIP_ELECTRON_PACK=true BUILD_ELECTRON=true nuxi build",
|
|
154
156
|
// write a dev desktop file for linux, see below
|
|
155
157
|
"preview:electron:dev": "concurrently --kill-others \"pnpm preview\" \"sleep 2 && pnpm launch:electron:dev\"",
|
|
@@ -165,9 +167,9 @@ Run `pnpm dev:electron`. This will both launch nuxt and open electron.
|
|
|
165
167
|
|
|
166
168
|
Alternatively, run the server and electron seperately:
|
|
167
169
|
|
|
168
|
-
Run `pnpm dev` to start the nuxt dev server. The dev version of the app will be written to `.dist/electron/build/main.
|
|
170
|
+
Run `pnpm dev` to start the nuxt dev server. The dev version of the app will be written to `.dist/electron/build/main.mjs`.
|
|
169
171
|
|
|
170
|
-
In a seperate terminal run `pnpm launch:electron` to start the electron app (this will do `electron .` which will run the configured `main` property, aka `.dist/electron/build/main.
|
|
172
|
+
In a seperate terminal run `pnpm launch:electron` to start the electron app (this will do `electron .` which will run the configured `main` property, aka `.dist/electron/build/main.mjs`).
|
|
171
173
|
|
|
172
174
|
#### Notes
|
|
173
175
|
By default the module will not open electron. You must set `process.env.AUTO_OPEN` to include the string `electron` or set `autoOpen `in the options to true, hence the seperate `dev:electron` script.
|
|
@@ -178,7 +180,7 @@ The idea is if you use other platform modules as well, you'd do `AUTO_OPEN=elect
|
|
|
178
180
|
|
|
179
181
|
Build the regular nuxt app with `pnpm build` then build the electron app with `pnpm build:electron` or `pnpm build:electron:no-pack` (if you just want to test, you can skip the packing).
|
|
180
182
|
|
|
181
|
-
In this case, the build written to `.dist/electron/build/main.
|
|
183
|
+
In this case, the build written to `.dist/electron/build/main.mjs` is the **production** build.
|
|
182
184
|
|
|
183
185
|
To run the built production server and the production app proxied to this server, use `pnpm preview:electron:dev`.
|
|
184
186
|
|
|
@@ -226,14 +228,13 @@ export default defineNuxtConfig({
|
|
|
226
228
|
},
|
|
227
229
|
electron: {
|
|
228
230
|
additionalElectronVariables: {
|
|
229
|
-
// this will hardcode `process.env.PUBLIC_SERVER_URL` to the server url
|
|
231
|
+
// this will hardcode `process.env.PUBLIC_SERVER_URL` to the server url
|
|
230
232
|
// this means getPaths().publicServerUrl will always return your site url (see getPaths) unless you allow getPaths an override (see it for details)
|
|
231
|
-
publicServerUrl: process.env.NODE_ENV === "production"
|
|
232
233
|
// note the quotes for strings! this is a literal replacement that happens
|
|
233
234
|
// you also cannot access process.env dynamically if you want this to work (e.g. process.env[name])
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
//
|
|
235
|
+
publicServerUrl: `"https://yoursite.com"`,
|
|
236
|
+
// this bakes the flag so it is available as `process.env.BAKED_IS_PRODUCTION`, pass `process.env.BAKED_IS_PRODUCTION === "true"` to getPaths as `isProduction` for use where runtime overriding should not be allowed
|
|
237
|
+
// the controlling env name and the baked name are just suggestions
|
|
237
238
|
bakedIsProduction: process.env.PRODUCTION_BUILD === "true" ? `"true"` : `"false"`
|
|
238
239
|
},
|
|
239
240
|
// the module will set this to prerender: true
|
|
@@ -248,6 +249,30 @@ export default defineNuxtConfig({
|
|
|
248
249
|
|
|
249
250
|
Proxying server only page routes seems possible but complicated because each route's resource calls must also be proxied. I don't think it's worth the pain. It's easier to make sure the electron app never access server only routes.
|
|
250
251
|
|
|
252
|
+
#### Baked Production Flag
|
|
253
|
+
|
|
254
|
+
Apps cannot tell when they are in production unless you bake an env. I suggest something like `BAKED_IS_PRODUCTION`. A flag like this is useful for controlling whether url overrides are allowed (e.g. for testing purposes) or not.
|
|
255
|
+
|
|
256
|
+
```ts [nuxt.config.ts]
|
|
257
|
+
electron: {
|
|
258
|
+
additionalElectronVariables: {
|
|
259
|
+
bakedIsProduction: process.env.PRODUCTION_BUILD === "true" ? `"true"` : `"false"`
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
```
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
Pass the flag to `getPaths` as `isProduction` and gate any overrides you want to gate.
|
|
266
|
+
|
|
267
|
+
```ts [app-electron/main.ts]
|
|
268
|
+
const paths = getPaths(protocolName, {
|
|
269
|
+
publicServerUrl: process.env.OVERRIDE_PUBLIC_SERVER_URL,
|
|
270
|
+
...(process.env.BAKED_IS_PRODUCTION === "true"
|
|
271
|
+
? {}
|
|
272
|
+
: { windowUrl: process.env.OVERRIDE_WINDOW_URL })
|
|
273
|
+
}, process.env.BAKED_IS_PRODUCTION === "true")
|
|
274
|
+
```
|
|
275
|
+
|
|
251
276
|
### Runtime Config
|
|
252
277
|
|
|
253
278
|
Anywhere in electron's main files you can also now use nuxt's public runtime config using the special version from the module (only the public part, you don't want to expose your server secrets to the electron app at all). Module does some magic to strinfigy it into the `ELECTRON_RUNTIME_CONFIG` env variable and read it back out:
|
|
@@ -301,7 +326,7 @@ DEBUG=true LOG_LEVEL=trace nix run "github:thiagokokada/nix-alien#nix-alien" --
|
|
|
301
326
|
|
|
302
327
|
Apart from that nix has some additional goodies.
|
|
303
328
|
|
|
304
|
-
First there
|
|
329
|
+
First there is a devenv based shell. Run `devenv shell` in the project root. Otherwise run `nix develop`.
|
|
305
330
|
|
|
306
331
|
Nearly everything should work, except the build electron-builder builds. You can do `nix run` instead.
|
|
307
332
|
|
package/dist/module.d.mts
CHANGED
|
@@ -70,6 +70,16 @@ interface ModuleOptions {
|
|
|
70
70
|
* Note that `build.emptyOutDir` cannot be changed, it must be false for the reloading to work.
|
|
71
71
|
*/
|
|
72
72
|
electronViteOptions: ElectronOptions["vite"];
|
|
73
|
+
/**
|
|
74
|
+
* Deps to leave external in the electron main build. Receives the names derived from your package.json dependencies, optionalDependencies and peerDependencies, and returns the names (or regexes) to use. Names get a subpath matcher generated, regexes are passed through.
|
|
75
|
+
*
|
|
76
|
+
* Can be used to filter (and therefore bundle) some deps that are normally externalized.
|
|
77
|
+
*
|
|
78
|
+
* The module always removes itself from this list so it can be bundled (as it relies on the bundling to bake the STATIC runtime paths.
|
|
79
|
+
*
|
|
80
|
+
* Cannot be used in combination with `electronViteOptions.build.rollupOptions.external`. Only one or the other can be used.
|
|
81
|
+
*/
|
|
82
|
+
externalDeps?: (derivedNames: string[]) => (string | RegExp)[];
|
|
73
83
|
notBundleOptions: Parameters<typeof notBundle>[0];
|
|
74
84
|
/**
|
|
75
85
|
* Additional variables to "bake" into the electron build. Note these must be quoted if they are strings.
|
package/dist/module.json
CHANGED
package/dist/module.mjs
CHANGED
|
@@ -58,6 +58,9 @@ const module$1 = defineNuxtModule({
|
|
|
58
58
|
}
|
|
59
59
|
const moduleName = "@witchcraft/nuxt-electron";
|
|
60
60
|
const logger = useLogger(moduleName);
|
|
61
|
+
if (options.externalDeps !== void 0 && options.electronViteOptions?.build?.rollupOptions?.external !== void 0) {
|
|
62
|
+
logger.error(`[${moduleName}]: externalDeps and electronViteOptions.build.rollupOptions.external can't be used at the same time, the rollup option always wins. Set one or the other but not both.`);
|
|
63
|
+
}
|
|
61
64
|
const { resolvePath, resolve } = createResolver(import.meta.url);
|
|
62
65
|
addComponentsDir({
|
|
63
66
|
global: true,
|
|
@@ -154,9 +157,20 @@ const module$1 = defineNuxtModule({
|
|
|
154
157
|
const viteConfig = await viteConfigPromise;
|
|
155
158
|
const externalDeps = [];
|
|
156
159
|
const appPackageJson = JSON.parse(await fs.readFile(path.join(nuxt.options.rootDir, "package.json"), "utf8"));
|
|
160
|
+
const dependentNames = [];
|
|
157
161
|
for (const depSection of ["dependencies", "optionalDependencies", "peerDependencies"]) {
|
|
158
162
|
for (const dep of Object.keys(appPackageJson[depSection] ?? {})) {
|
|
159
|
-
|
|
163
|
+
if (dep === moduleName || dependentNames.includes(dep)) {
|
|
164
|
+
continue;
|
|
165
|
+
}
|
|
166
|
+
dependentNames.push(dep);
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
for (const entry of options.externalDeps?.(dependentNames) ?? dependentNames) {
|
|
170
|
+
if (typeof entry === "string") {
|
|
171
|
+
externalDeps.push(entry, new RegExp(`^${entry.replaceAll(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?:/.+)?$`));
|
|
172
|
+
} else {
|
|
173
|
+
externalDeps.push(entry);
|
|
160
174
|
}
|
|
161
175
|
}
|
|
162
176
|
const electronRuntimeConfig = defu(
|
|
@@ -216,10 +230,7 @@ const module$1 = defineNuxtModule({
|
|
|
216
230
|
{
|
|
217
231
|
build: {
|
|
218
232
|
outDir: electronBuildDir,
|
|
219
|
-
minify: false
|
|
220
|
-
rollupOptions: {
|
|
221
|
-
external: externalDeps
|
|
222
|
-
}
|
|
233
|
+
minify: false
|
|
223
234
|
},
|
|
224
235
|
define: electronVariables,
|
|
225
236
|
resolve: {
|
|
@@ -228,6 +239,8 @@ const module$1 = defineNuxtModule({
|
|
|
228
239
|
}
|
|
229
240
|
}
|
|
230
241
|
);
|
|
242
|
+
electronViteOptions.build.rollupOptions ??= {};
|
|
243
|
+
electronViteOptions.build.rollupOptions.external ??= externalDeps;
|
|
231
244
|
const electronCliArgs = [
|
|
232
245
|
".",
|
|
233
246
|
...process.env.NODE_ENV !== "production" && devUserDataDir ? [
|
|
@@ -4,14 +4,16 @@
|
|
|
4
4
|
*
|
|
5
5
|
* Paths are not overridable in production unless you pass the variables that can override them.
|
|
6
6
|
*
|
|
7
|
+
* Whether the app is considered to be in production is determined by the optional isProduction parameter. It should be set to something like the example baked production env in the readme.
|
|
8
|
+
*
|
|
7
9
|
* ```ts
|
|
8
10
|
* const paths = getPaths("app", {
|
|
9
11
|
* windowUrl: process.env.OVERRIDE_WINDOW_URL,
|
|
10
12
|
* publicServerUrl: process.env.OVERRIDE_PUBLIC_SERVER_URL
|
|
11
|
-
* })
|
|
13
|
+
* }, process.env.BAKED_IS_PRODUCTION === "true")
|
|
12
14
|
* ```
|
|
13
15
|
*/
|
|
14
|
-
export declare function getPaths(protocolName?: string, overridingEnvs?: Record<string, string | undefined
|
|
16
|
+
export declare function getPaths(protocolName?: string, overridingEnvs?: Record<string, string | undefined>, isProduction?: boolean): {
|
|
15
17
|
windowUrl: string;
|
|
16
18
|
publicServerUrl: string;
|
|
17
19
|
nuxtPublicDir: string;
|
|
@@ -5,7 +5,7 @@ import { STATIC } from "../static.js";
|
|
|
5
5
|
export function getPaths(protocolName = "app", overridingEnvs = {
|
|
6
6
|
windowUrl: void 0,
|
|
7
7
|
publicServerUrl: void 0
|
|
8
|
-
}) {
|
|
8
|
+
}, isProduction) {
|
|
9
9
|
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
10
10
|
const nuxtPublicDir = path.join(__dirname, STATIC.ELECTRON_NUXT_PUBLIC_DIR);
|
|
11
11
|
const preloadPath = path.join(__dirname, STATIC.ELECTRON_BUILD_DIR, "./preload.cjs");
|
|
@@ -23,7 +23,7 @@ export function getPaths(protocolName = "app", overridingEnvs = {
|
|
|
23
23
|
windowUrl: `${overridingEnvs.windowUrl}${STATIC.ELECTRON_ROUTE}`
|
|
24
24
|
};
|
|
25
25
|
}
|
|
26
|
-
if (
|
|
26
|
+
if (!isProduction && process.env.VITE_DEV_SERVER_URL) {
|
|
27
27
|
return {
|
|
28
28
|
...base,
|
|
29
29
|
windowUrl: `${process.env.VITE_DEV_SERVER_URL}${STATIC.ELECTRON_ROUTE}`
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { type ElectronApplication, type Page } from "@playwright/test";
|
|
2
|
+
/**
|
|
3
|
+
* Launches the built app for a test, starting from a clean profile every time.
|
|
4
|
+
*
|
|
5
|
+
* ```ts
|
|
6
|
+
* const { app, page, close } = await launchApp({
|
|
7
|
+
* appDir: playgroundDir,
|
|
8
|
+
* userDataDir: path.join(playgroundDir, ".user-data-dir-test"),
|
|
9
|
+
* serverUrl: `http://localhost:${process.env.NUXT_PORT}`,
|
|
10
|
+
* windowUrlPrefix: "app://bundle"
|
|
11
|
+
* })
|
|
12
|
+
* ```
|
|
13
|
+
*/
|
|
14
|
+
export declare function launchApp({ appDir, userDataDir, serverUrl, windowUrlPrefix, useDevServer, env, extraArgs, windowTimeout }: {
|
|
15
|
+
appDir: string;
|
|
16
|
+
userDataDir: string;
|
|
17
|
+
serverUrl: string;
|
|
18
|
+
windowUrlPrefix: string;
|
|
19
|
+
useDevServer?: boolean;
|
|
20
|
+
env?: Record<string, string>;
|
|
21
|
+
extraArgs?: string[];
|
|
22
|
+
windowTimeout?: number;
|
|
23
|
+
}): Promise<{
|
|
24
|
+
app: ElectronApplication;
|
|
25
|
+
page: Page;
|
|
26
|
+
close: () => Promise<void>;
|
|
27
|
+
}>;
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { _electron as electron } from "@playwright/test";
|
|
2
|
+
import { rm } from "node:fs/promises";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
export async function launchApp({
|
|
5
|
+
appDir,
|
|
6
|
+
userDataDir,
|
|
7
|
+
serverUrl,
|
|
8
|
+
windowUrlPrefix,
|
|
9
|
+
useDevServer = false,
|
|
10
|
+
env = {},
|
|
11
|
+
extraArgs = [],
|
|
12
|
+
windowTimeout = 3e4
|
|
13
|
+
}) {
|
|
14
|
+
const relative = path.relative(path.resolve(appDir), path.resolve(userDataDir));
|
|
15
|
+
if (relative.startsWith("..") || path.isAbsolute(relative)) {
|
|
16
|
+
throw new Error(`userDataDir must be inside appDir, got ${userDataDir}.`);
|
|
17
|
+
}
|
|
18
|
+
await rm(userDataDir, { recursive: true, force: true });
|
|
19
|
+
const app = await electron.launch({
|
|
20
|
+
// launched as an app directory so `app.getAppPath()` is the app root, which is where
|
|
21
|
+
// @witchcraft/nuxt-logger resolves pino's workers from
|
|
22
|
+
args: [".", "--no-sandbox", "--ignore-certificate-errors", `--user-data-dir=${userDataDir}`, ...extraArgs],
|
|
23
|
+
cwd: appDir,
|
|
24
|
+
env: {
|
|
25
|
+
...process.env,
|
|
26
|
+
...env,
|
|
27
|
+
DISABLE_AUTO_UPDATES: "true",
|
|
28
|
+
OVERRIDE_PUBLIC_SERVER_URL: serverUrl,
|
|
29
|
+
...useDevServer ? { VITE_DEV_SERVER_URL: serverUrl } : {}
|
|
30
|
+
}
|
|
31
|
+
});
|
|
32
|
+
const deadline = Date.now() + windowTimeout;
|
|
33
|
+
const watched = /* @__PURE__ */ new Map();
|
|
34
|
+
const watch = (candidate) => {
|
|
35
|
+
let pending = watched.get(candidate);
|
|
36
|
+
if (!pending) {
|
|
37
|
+
pending = candidate.waitForURL((url) => url.toString().startsWith(windowUrlPrefix), { timeout: Math.max(deadline - Date.now(), 1) }).then(() => candidate).catch(() => void 0);
|
|
38
|
+
watched.set(candidate, pending);
|
|
39
|
+
}
|
|
40
|
+
return pending;
|
|
41
|
+
};
|
|
42
|
+
let page;
|
|
43
|
+
while (!page && Date.now() < deadline) {
|
|
44
|
+
const next = await Promise.race([
|
|
45
|
+
...app.windows().map(watch),
|
|
46
|
+
app.waitForEvent("window", { timeout: Math.max(deadline - Date.now(), 1) }).catch(() => void 0)
|
|
47
|
+
]);
|
|
48
|
+
if (next && next.url().startsWith(windowUrlPrefix)) page = next;
|
|
49
|
+
}
|
|
50
|
+
if (!page) {
|
|
51
|
+
const seen = app.windows().map((candidate) => candidate.url());
|
|
52
|
+
throw new Error(`No window with url starting with ${windowUrlPrefix}, saw: ${seen.join(", ") || "no windows"}.`);
|
|
53
|
+
}
|
|
54
|
+
await page.waitForLoadState();
|
|
55
|
+
const close = async () => {
|
|
56
|
+
await app.close();
|
|
57
|
+
};
|
|
58
|
+
return { app, page, close };
|
|
59
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { type ElectronApplication, type Page } from "@playwright/test";
|
|
2
|
+
import type { Cookie } from "electron";
|
|
3
|
+
export declare function launchElectron({ appDir, userDataDir, serverUrl, windowUrlPrefix, useDevServer, env, extraArgs, windowTimeout }: {
|
|
4
|
+
appDir: string;
|
|
5
|
+
userDataDir: string;
|
|
6
|
+
serverUrl: string;
|
|
7
|
+
windowUrlPrefix: string;
|
|
8
|
+
useDevServer?: boolean;
|
|
9
|
+
env?: Record<string, string>;
|
|
10
|
+
extraArgs?: string[];
|
|
11
|
+
windowTimeout?: number;
|
|
12
|
+
}): import("@playwright/test").TestType<import("@playwright/test").PlaywrightTestArgs & import("@playwright/test").PlaywrightTestOptions & {
|
|
13
|
+
app: ElectronApplication;
|
|
14
|
+
page: Page;
|
|
15
|
+
waitForWindow: (windowUrlPrefix?: string, windowTimeout?: number) => Promise<Page>;
|
|
16
|
+
getPageFromWindow: () => Promise<Page>;
|
|
17
|
+
blockNetwork: (page: Page) => Promise<void>;
|
|
18
|
+
unblockNetwork: (page: Page) => Promise<void>;
|
|
19
|
+
getWindowCookies: (page: Page, name?: string) => Promise<Cookie[]>;
|
|
20
|
+
}, import("@playwright/test").PlaywrightWorkerArgs & import("@playwright/test").PlaywrightWorkerOptions>;
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import { expect, test as base } from "@playwright/test";
|
|
2
|
+
import { launchApp } from "./launchApp.js";
|
|
3
|
+
export function launchElectron({
|
|
4
|
+
appDir,
|
|
5
|
+
userDataDir,
|
|
6
|
+
serverUrl,
|
|
7
|
+
windowUrlPrefix,
|
|
8
|
+
useDevServer = false,
|
|
9
|
+
env = {},
|
|
10
|
+
extraArgs = [],
|
|
11
|
+
windowTimeout = 3e4
|
|
12
|
+
}) {
|
|
13
|
+
return base.extend({
|
|
14
|
+
browser: async ({ browser }, use) => {
|
|
15
|
+
const marked = browser;
|
|
16
|
+
if (!marked.isTestContextMarked) {
|
|
17
|
+
marked.isTestContextMarked = true;
|
|
18
|
+
const newContext = browser.newContext.bind(browser);
|
|
19
|
+
browser.newContext = async (options) => {
|
|
20
|
+
const context = await newContext(options);
|
|
21
|
+
await context.addInitScript(() => {
|
|
22
|
+
window.__IS_TEST = true;
|
|
23
|
+
});
|
|
24
|
+
return context;
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
await use(browser);
|
|
28
|
+
},
|
|
29
|
+
// eslint-disable-next-line no-empty-pattern
|
|
30
|
+
app: async ({}, use) => {
|
|
31
|
+
const { app, close } = await launchApp({ appDir, userDataDir, serverUrl, windowUrlPrefix, useDevServer, env, extraArgs, windowTimeout });
|
|
32
|
+
await use(app);
|
|
33
|
+
await close();
|
|
34
|
+
},
|
|
35
|
+
page: async ({ waitForWindow }, use) => {
|
|
36
|
+
await use(await waitForWindow());
|
|
37
|
+
},
|
|
38
|
+
waitForWindow: async ({ app }, use) => {
|
|
39
|
+
await use(async (prefix = windowUrlPrefix, timeout = windowTimeout) => {
|
|
40
|
+
const deadline = Date.now() + timeout;
|
|
41
|
+
const watched = /* @__PURE__ */ new Map();
|
|
42
|
+
const watch = (candidate) => {
|
|
43
|
+
let pending = watched.get(candidate);
|
|
44
|
+
if (!pending) {
|
|
45
|
+
pending = candidate.waitForURL((url) => url.toString().startsWith(prefix), { timeout: Math.max(deadline - Date.now(), 1) }).then(() => candidate).catch(() => void 0);
|
|
46
|
+
watched.set(candidate, pending);
|
|
47
|
+
}
|
|
48
|
+
return pending;
|
|
49
|
+
};
|
|
50
|
+
let page;
|
|
51
|
+
while (!page && Date.now() < deadline) {
|
|
52
|
+
const next = await Promise.race([
|
|
53
|
+
...app.windows().map(watch),
|
|
54
|
+
app.waitForEvent("window", { timeout: Math.max(deadline - Date.now(), 1) }).catch(() => void 0)
|
|
55
|
+
]);
|
|
56
|
+
if (next && next.url().startsWith(prefix)) page = next;
|
|
57
|
+
}
|
|
58
|
+
if (!page) {
|
|
59
|
+
const seen = app.windows().map((candidate) => candidate.url());
|
|
60
|
+
throw new Error(`No window with url starting with ${prefix}, saw: ${seen.join(", ") || "no windows"}.`);
|
|
61
|
+
}
|
|
62
|
+
return page;
|
|
63
|
+
});
|
|
64
|
+
},
|
|
65
|
+
getPageFromWindow: async ({ app }, use) => {
|
|
66
|
+
const isAppWindow = (candidate) => !candidate.url().startsWith("devtools://");
|
|
67
|
+
let first = app.windows().find(isAppWindow);
|
|
68
|
+
while (!first) {
|
|
69
|
+
const candidate = await app.waitForEvent("window");
|
|
70
|
+
if (isAppWindow(candidate)) first = candidate;
|
|
71
|
+
}
|
|
72
|
+
const pending = [];
|
|
73
|
+
const waiting = [];
|
|
74
|
+
app.on("window", (window2) => {
|
|
75
|
+
if (window2 === first || !isAppWindow(window2)) return;
|
|
76
|
+
pending.push(window2);
|
|
77
|
+
waiting.shift()?.();
|
|
78
|
+
});
|
|
79
|
+
await use(async () => {
|
|
80
|
+
if (pending.length === 0) await new Promise((resolve) => waiting.push(resolve));
|
|
81
|
+
const next = pending.shift();
|
|
82
|
+
await next.waitForLoadState();
|
|
83
|
+
await expect.poll(() => app.evaluate((electron) => electron.BrowserWindow.getAllWindows().length)).toBe(1);
|
|
84
|
+
return next;
|
|
85
|
+
});
|
|
86
|
+
},
|
|
87
|
+
blockNetwork: async ({ app }, use) => {
|
|
88
|
+
await use(async (page) => {
|
|
89
|
+
const index = app.windows().filter((candidate) => !candidate.url().startsWith("devtools://")).indexOf(page);
|
|
90
|
+
if (index === -1) throw new Error("blockNetwork: the page does not belong to this app.");
|
|
91
|
+
await app.evaluate((electron, windowIndex) => {
|
|
92
|
+
const win = electron.BrowserWindow.getAllWindows()[windowIndex];
|
|
93
|
+
if (!win) throw new Error("blockNetwork: no window at that index.");
|
|
94
|
+
win.webContents.session.webRequest.onBeforeRequest({ urls: ["http://*/*"] }, (_details, callback) => callback({ cancel: true }));
|
|
95
|
+
}, index);
|
|
96
|
+
});
|
|
97
|
+
},
|
|
98
|
+
unblockNetwork: async ({ app }, use) => {
|
|
99
|
+
await use(async (page) => {
|
|
100
|
+
const index = app.windows().filter((candidate) => !candidate.url().startsWith("devtools://")).indexOf(page);
|
|
101
|
+
if (index === -1) throw new Error("unblockNetwork: the page does not belong to this app.");
|
|
102
|
+
await app.evaluate((electron, windowIndex) => {
|
|
103
|
+
const win = electron.BrowserWindow.getAllWindows()[windowIndex];
|
|
104
|
+
if (!win) throw new Error("unblockNetwork: no window at that index.");
|
|
105
|
+
win.webContents.session.webRequest.onBeforeRequest(null);
|
|
106
|
+
}, index);
|
|
107
|
+
});
|
|
108
|
+
},
|
|
109
|
+
getWindowCookies: async ({ app }, use) => {
|
|
110
|
+
await use(async (page, name) => {
|
|
111
|
+
const index = app.windows().filter((candidate) => !candidate.url().startsWith("devtools://")).indexOf(page);
|
|
112
|
+
if (index === -1) throw new Error("getWindowCookies: the page does not belong to this app.");
|
|
113
|
+
return app.evaluate((electron, { windowIndex, cookieName }) => {
|
|
114
|
+
const win = electron.BrowserWindow.getAllWindows()[windowIndex];
|
|
115
|
+
if (!win) throw new Error("getWindowCookies: no window at that index.");
|
|
116
|
+
return win.webContents.session.cookies.get(cookieName ? { name: cookieName } : {});
|
|
117
|
+
}, { windowIndex: index, cookieName: name });
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
});
|
|
121
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function localhostUrl(port?: string): string;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@witchcraft/nuxt-electron",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.5",
|
|
4
4
|
"description": "Nuxt module for working with electron.",
|
|
5
5
|
"repository": "https://github.com/witchcraftjs/nuxt-electron",
|
|
6
6
|
"license": "MIT",
|
|
@@ -27,6 +27,10 @@
|
|
|
27
27
|
"types": "./dist/runtime/electron/renderer/index.d.ts",
|
|
28
28
|
"import": "./dist/runtime/electron/renderer/index.js"
|
|
29
29
|
},
|
|
30
|
+
"./electron/test": {
|
|
31
|
+
"types": "./dist/runtime/electron/test/index.d.ts",
|
|
32
|
+
"import": "./dist/runtime/electron/test/index.js"
|
|
33
|
+
},
|
|
30
34
|
"./electron/*": {
|
|
31
35
|
"types": "./dist/runtime/electron/*.d.ts",
|
|
32
36
|
"import": "./dist/runtime/electron/*.js"
|
|
@@ -46,7 +50,7 @@
|
|
|
46
50
|
"@witchcraft/nuxt-utils": "^0.3.18",
|
|
47
51
|
"@witchcraft/ui": "^0.5.12",
|
|
48
52
|
"defu": "^6.1.4",
|
|
49
|
-
"electron": "^
|
|
53
|
+
"electron": "^44.0.0",
|
|
50
54
|
"es-toolkit": "^1.44.0",
|
|
51
55
|
"vite-plugin-electron": "^0.29.0"
|
|
52
56
|
},
|
|
@@ -70,6 +74,8 @@
|
|
|
70
74
|
"@nuxt/module-builder": "^1.0.3",
|
|
71
75
|
"@nuxt/schema": "^4.3.1",
|
|
72
76
|
"@nuxt/test-utils": "^3.23.0",
|
|
77
|
+
"@playwright/test": "=1.65.0",
|
|
78
|
+
"playwright-core": "=1.65.0",
|
|
73
79
|
"@types/node": "latest",
|
|
74
80
|
"changelogen": "^0.6.2",
|
|
75
81
|
"eslint": "^9.39.2",
|
|
@@ -103,6 +109,11 @@
|
|
|
103
109
|
"lint": "pnpm lint:eslint && pnpm lint:types",
|
|
104
110
|
"lint:eslint": "eslint \"{src,test,playground/app}/**/*.{ts,vue}\" \"*.{js,cjs,mjs,ts}\"",
|
|
105
111
|
"lint:types": "vue-tsc --noEmit && cd playground && vue-tsc --noEmit",
|
|
106
|
-
"test": "
|
|
112
|
+
"test": "pnpm test:electron",
|
|
113
|
+
"test:electron": "pnpm --dir playground test:electron",
|
|
114
|
+
"test:electron:only": "pnpm --dir playground test:electron:only",
|
|
115
|
+
"test:electron:dev": "pnpm --dir playground test:electron:dev",
|
|
116
|
+
"test:ci": "pnpm --dir playground test:ci",
|
|
117
|
+
"test:server": "pnpm --dir playground test:server"
|
|
107
118
|
}
|
|
108
119
|
}
|
package/src/module.ts
CHANGED
|
@@ -105,6 +105,16 @@ export interface ModuleOptions {
|
|
|
105
105
|
*/
|
|
106
106
|
// importing the type from vite is causing build issues :/
|
|
107
107
|
electronViteOptions: ElectronOptions["vite"]
|
|
108
|
+
/**
|
|
109
|
+
* Deps to leave external in the electron main build. Receives the names derived from your package.json dependencies, optionalDependencies and peerDependencies, and returns the names (or regexes) to use. Names get a subpath matcher generated, regexes are passed through.
|
|
110
|
+
*
|
|
111
|
+
* Can be used to filter (and therefore bundle) some deps that are normally externalized.
|
|
112
|
+
*
|
|
113
|
+
* The module always removes itself from this list so it can be bundled (as it relies on the bundling to bake the STATIC runtime paths.
|
|
114
|
+
*
|
|
115
|
+
* Cannot be used in combination with `electronViteOptions.build.rollupOptions.external`. Only one or the other can be used.
|
|
116
|
+
*/
|
|
117
|
+
externalDeps?: (derivedNames: string[]) => (string | RegExp)[]
|
|
108
118
|
notBundleOptions: Parameters<typeof notBundle>[0]
|
|
109
119
|
/**
|
|
110
120
|
* Additional variables to "bake" into the electron build. Note these must be quoted if they are strings.
|
|
@@ -185,6 +195,13 @@ export default defineNuxtModule<ModuleOptions>({
|
|
|
185
195
|
if (!options.enable) { return }
|
|
186
196
|
const moduleName = "@witchcraft/nuxt-electron"
|
|
187
197
|
const logger = useLogger(moduleName)
|
|
198
|
+
|
|
199
|
+
if (
|
|
200
|
+
options.externalDeps !== undefined
|
|
201
|
+
&& options.electronViteOptions?.build?.rollupOptions?.external !== undefined
|
|
202
|
+
) {
|
|
203
|
+
logger.error(`[${moduleName}]: externalDeps and electronViteOptions.build.rollupOptions.external can't be used at the same time, the rollup option always wins. Set one or the other but not both.`)
|
|
204
|
+
}
|
|
188
205
|
const { resolvePath, resolve } = createResolver(import.meta.url)
|
|
189
206
|
|
|
190
207
|
addComponentsDir({
|
|
@@ -309,9 +326,19 @@ export default defineNuxtModule<ModuleOptions>({
|
|
|
309
326
|
|
|
310
327
|
const externalDeps: (string | RegExp)[] = []
|
|
311
328
|
const appPackageJson = JSON.parse(await fs.readFile(path.join(nuxt.options.rootDir, "package.json"), "utf8"))
|
|
329
|
+
const dependentNames: string[] = []
|
|
312
330
|
for (const depSection of ["dependencies", "optionalDependencies", "peerDependencies"] as const) {
|
|
313
331
|
for (const dep of Object.keys(appPackageJson[depSection] ?? {})) {
|
|
314
|
-
|
|
332
|
+
// this module is always bundled so its baked values survive
|
|
333
|
+
if (dep === moduleName || dependentNames.includes(dep)) { continue }
|
|
334
|
+
dependentNames.push(dep)
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
for (const entry of options.externalDeps?.(dependentNames) ?? dependentNames) {
|
|
338
|
+
if (typeof entry === "string") {
|
|
339
|
+
externalDeps.push(entry, new RegExp(`^${entry.replaceAll(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?:/.+)?$`))
|
|
340
|
+
} else {
|
|
341
|
+
externalDeps.push(entry)
|
|
315
342
|
}
|
|
316
343
|
}
|
|
317
344
|
|
|
@@ -375,10 +402,7 @@ export default defineNuxtModule<ModuleOptions>({
|
|
|
375
402
|
{
|
|
376
403
|
build: {
|
|
377
404
|
outDir: electronBuildDir,
|
|
378
|
-
minify: false
|
|
379
|
-
rollupOptions: {
|
|
380
|
-
external: externalDeps
|
|
381
|
-
}
|
|
405
|
+
minify: false
|
|
382
406
|
},
|
|
383
407
|
define: electronVariables,
|
|
384
408
|
resolve: {
|
|
@@ -386,6 +410,9 @@ export default defineNuxtModule<ModuleOptions>({
|
|
|
386
410
|
extensions: [".mjs", ".js", ".ts", ".jsx", ".tsx", ".json", ".vue"]
|
|
387
411
|
}
|
|
388
412
|
})
|
|
413
|
+
// set after the merge, defu would union it with a value set in electronViteOptions
|
|
414
|
+
electronViteOptions.build!.rollupOptions ??= {}
|
|
415
|
+
electronViteOptions.build!.rollupOptions.external ??= externalDeps
|
|
389
416
|
|
|
390
417
|
const electronCliArgs = [
|
|
391
418
|
".",
|
|
@@ -10,11 +10,13 @@ import { STATIC } from "../static.js"
|
|
|
10
10
|
*
|
|
11
11
|
* Paths are not overridable in production unless you pass the variables that can override them.
|
|
12
12
|
*
|
|
13
|
+
* Whether the app is considered to be in production is determined by the optional isProduction parameter. It should be set to something like the example baked production env in the readme.
|
|
14
|
+
*
|
|
13
15
|
* ```ts
|
|
14
16
|
* const paths = getPaths("app", {
|
|
15
17
|
* windowUrl: process.env.OVERRIDE_WINDOW_URL,
|
|
16
18
|
* publicServerUrl: process.env.OVERRIDE_PUBLIC_SERVER_URL
|
|
17
|
-
* })
|
|
19
|
+
* }, process.env.BAKED_IS_PRODUCTION === "true")
|
|
18
20
|
* ```
|
|
19
21
|
*/
|
|
20
22
|
export function getPaths(
|
|
@@ -22,7 +24,8 @@ export function getPaths(
|
|
|
22
24
|
overridingEnvs: Record<string, string | undefined> = {
|
|
23
25
|
windowUrl: undefined,
|
|
24
26
|
publicServerUrl: undefined
|
|
25
|
-
}
|
|
27
|
+
},
|
|
28
|
+
isProduction?: boolean
|
|
26
29
|
): {
|
|
27
30
|
windowUrl: string
|
|
28
31
|
publicServerUrl: string
|
|
@@ -56,7 +59,7 @@ export function getPaths(
|
|
|
56
59
|
}
|
|
57
60
|
}
|
|
58
61
|
|
|
59
|
-
if (
|
|
62
|
+
if (!isProduction && process.env.VITE_DEV_SERVER_URL) {
|
|
60
63
|
return {
|
|
61
64
|
...base,
|
|
62
65
|
windowUrl: `${process.env.VITE_DEV_SERVER_URL}${STATIC.ELECTRON_ROUTE}`
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { _electron as electron, type ElectronApplication, type Page } from "@playwright/test"
|
|
2
|
+
import { rm } from "node:fs/promises"
|
|
3
|
+
import path from "node:path"
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Launches the built app for a test, starting from a clean profile every time.
|
|
8
|
+
*
|
|
9
|
+
* ```ts
|
|
10
|
+
* const { app, page, close } = await launchApp({
|
|
11
|
+
* appDir: playgroundDir,
|
|
12
|
+
* userDataDir: path.join(playgroundDir, ".user-data-dir-test"),
|
|
13
|
+
* serverUrl: `http://localhost:${process.env.NUXT_PORT}`,
|
|
14
|
+
* windowUrlPrefix: "app://bundle"
|
|
15
|
+
* })
|
|
16
|
+
* ```
|
|
17
|
+
*/
|
|
18
|
+
export async function launchApp(
|
|
19
|
+
{
|
|
20
|
+
appDir,
|
|
21
|
+
userDataDir,
|
|
22
|
+
serverUrl,
|
|
23
|
+
windowUrlPrefix,
|
|
24
|
+
useDevServer = false,
|
|
25
|
+
env = {},
|
|
26
|
+
extraArgs = [],
|
|
27
|
+
windowTimeout = 30_000
|
|
28
|
+
}: {
|
|
29
|
+
/* Directory the app is launched from, becomes the electron process cwd. A module playground passes its playground dir, an app passes its repo root. */
|
|
30
|
+
appDir: string
|
|
31
|
+
/* Profile directory, wiped before every launch. Point it somewhere gitignored. */
|
|
32
|
+
userDataDir: string
|
|
33
|
+
/* Server the app should talk to. */
|
|
34
|
+
serverUrl: string
|
|
35
|
+
/* Only a window whose url starts with this is returned. The bundle prefix normally, serverUrl in dev. */
|
|
36
|
+
windowUrlPrefix: string
|
|
37
|
+
/* Points the app at serverUrl with VITE_DEV_SERVER_URL instead of at its bundle. Only works when the app leaves the windowUrl override open, so a baked production flag must be false. */
|
|
38
|
+
useDevServer?: boolean
|
|
39
|
+
/* Extra env for the app process, merged last so it wins. */
|
|
40
|
+
env?: Record<string, string>
|
|
41
|
+
/* Extra args for the electron process, appended after the fixed args. */
|
|
42
|
+
extraArgs?: string[]
|
|
43
|
+
/* How long to wait for the matching window before throwing. */
|
|
44
|
+
windowTimeout?: number
|
|
45
|
+
}
|
|
46
|
+
): Promise<{ app: ElectronApplication, page: Page, close: () => Promise<void> }> {
|
|
47
|
+
const relative = path.relative(path.resolve(appDir), path.resolve(userDataDir))
|
|
48
|
+
if (relative.startsWith("..") || path.isAbsolute(relative)) {
|
|
49
|
+
throw new Error(`userDataDir must be inside appDir, got ${userDataDir}.`)
|
|
50
|
+
}
|
|
51
|
+
await rm(userDataDir, { recursive: true, force: true })
|
|
52
|
+
|
|
53
|
+
const app = await electron.launch({
|
|
54
|
+
// launched as an app directory so `app.getAppPath()` is the app root, which is where
|
|
55
|
+
// @witchcraft/nuxt-logger resolves pino's workers from
|
|
56
|
+
args: [".", "--no-sandbox", "--ignore-certificate-errors", `--user-data-dir=${userDataDir}`, ...extraArgs],
|
|
57
|
+
cwd: appDir,
|
|
58
|
+
env: {
|
|
59
|
+
...process.env,
|
|
60
|
+
...env,
|
|
61
|
+
DISABLE_AUTO_UPDATES: "true",
|
|
62
|
+
OVERRIDE_PUBLIC_SERVER_URL: serverUrl,
|
|
63
|
+
...(useDevServer ? { VITE_DEV_SERVER_URL: serverUrl } : {})
|
|
64
|
+
} as Record<string, string>
|
|
65
|
+
})
|
|
66
|
+
// the url is not set yet when a window appears, so watch every window for its url and race that against new windows arriving
|
|
67
|
+
const deadline = Date.now() + windowTimeout
|
|
68
|
+
const watched = new Map<Page, Promise<Page | undefined>>()
|
|
69
|
+
const watch = (candidate: Page) => {
|
|
70
|
+
let pending = watched.get(candidate)
|
|
71
|
+
if (!pending) {
|
|
72
|
+
pending = candidate.waitForURL(url => url.toString().startsWith(windowUrlPrefix), { timeout: Math.max(deadline - Date.now(), 1) }).then(() => candidate).catch(() => undefined)
|
|
73
|
+
watched.set(candidate, pending)
|
|
74
|
+
}
|
|
75
|
+
return pending
|
|
76
|
+
}
|
|
77
|
+
let page: Page | undefined
|
|
78
|
+
while (!page && Date.now() < deadline) {
|
|
79
|
+
const next = await Promise.race([
|
|
80
|
+
...app.windows().map(watch),
|
|
81
|
+
app.waitForEvent("window", { timeout: Math.max(deadline - Date.now(), 1) }).catch(() => undefined)
|
|
82
|
+
])
|
|
83
|
+
if (next && next.url().startsWith(windowUrlPrefix)) page = next
|
|
84
|
+
}
|
|
85
|
+
if (!page) {
|
|
86
|
+
const seen = app.windows().map(candidate => candidate.url())
|
|
87
|
+
throw new Error(`No window with url starting with ${windowUrlPrefix}, saw: ${seen.join(", ") || "no windows"}.`)
|
|
88
|
+
}
|
|
89
|
+
await page.waitForLoadState()
|
|
90
|
+
const close = async () => {
|
|
91
|
+
await app.close()
|
|
92
|
+
}
|
|
93
|
+
return { app, page, close }
|
|
94
|
+
}
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
import { type ElectronApplication, expect, type Page, test as base } from "@playwright/test"
|
|
2
|
+
// playwright's window list includes devtools, getAllWindows does not, so devtools is filtered out of every window list the fixture reads
|
|
3
|
+
import type { Cookie } from "electron"
|
|
4
|
+
|
|
5
|
+
import { launchApp } from "./launchApp.js"
|
|
6
|
+
|
|
7
|
+
export function launchElectron({
|
|
8
|
+
appDir,
|
|
9
|
+
userDataDir,
|
|
10
|
+
serverUrl,
|
|
11
|
+
windowUrlPrefix,
|
|
12
|
+
useDevServer = false,
|
|
13
|
+
env = {},
|
|
14
|
+
extraArgs = [],
|
|
15
|
+
windowTimeout = 30_000
|
|
16
|
+
}: {
|
|
17
|
+
/* Directory the app is launched from, becomes the electron process cwd. A module playground passes its playground dir, an app passes its repo root. */
|
|
18
|
+
appDir: string
|
|
19
|
+
/* Profile directory, wiped before every launch. Point it somewhere gitignored. */
|
|
20
|
+
userDataDir: string
|
|
21
|
+
/* Server the app should talk to. */
|
|
22
|
+
serverUrl: string
|
|
23
|
+
/* Only a window whose url starts with this is returned. The bundle prefix normally, serverUrl in dev. */
|
|
24
|
+
windowUrlPrefix: string
|
|
25
|
+
/* Points the app at serverUrl with VITE_DEV_SERVER_URL instead of at its bundle. Only works when the app leaves the windowUrl override open, so a baked production flag must be false. */
|
|
26
|
+
useDevServer?: boolean
|
|
27
|
+
/* Extra env for the app process, merged last so it wins. */
|
|
28
|
+
env?: Record<string, string>
|
|
29
|
+
/* Extra args for the electron process, appended after the fixed args. */
|
|
30
|
+
extraArgs?: string[]
|
|
31
|
+
/* How long to wait for the matching window before throwing. */
|
|
32
|
+
windowTimeout?: number
|
|
33
|
+
}) {
|
|
34
|
+
return base.extend<{
|
|
35
|
+
app: ElectronApplication
|
|
36
|
+
page: Page
|
|
37
|
+
/*
|
|
38
|
+
Waits for a window whose url starts with the prefix and returns it.
|
|
39
|
+
|
|
40
|
+
Without arguments it waits for the launch prefix, which is the app bundle normally and the server url in dev. Pass another prefix after an action that opens a different window, such as switching user. Already open windows are checked first, then new arrivals, and navigation is awaited since the url is not set yet when the window event fires. Throws listing the urls it saw on timeout.
|
|
41
|
+
*/
|
|
42
|
+
waitForWindow: (windowUrlPrefix?: string, windowTimeout?: number) => Promise<Page>
|
|
43
|
+
/*
|
|
44
|
+
Returns the next window the app opens, for example after switching user.
|
|
45
|
+
|
|
46
|
+
Unlike waitForWindow it does not match by url, it takes whatever non-first window arrives next. An event that fired before the caller asks is not missed, and it waits until only one window is listed since the app closes the old window asynchronously.
|
|
47
|
+
*/
|
|
48
|
+
getPageFromWindow: () => Promise<Page>
|
|
49
|
+
/*
|
|
50
|
+
Cancels every http request the given window's session makes, so proxied calls fail instead of being answered. Close enough to "the server is unreachable", and nothing about the client is faked.
|
|
51
|
+
|
|
52
|
+
The window is matched by its position among the app's windows, which share creation order on both sides, so the right session is hit even with two windows open. Restored with unblockNetwork.
|
|
53
|
+
*/
|
|
54
|
+
blockNetwork: (page: Page) => Promise<void>
|
|
55
|
+
/*
|
|
56
|
+
Lets the given window's http requests through again, after blockNetwork.
|
|
57
|
+
*/
|
|
58
|
+
unblockNetwork: (page: Page) => Promise<void>
|
|
59
|
+
/*
|
|
60
|
+
Reads the cookies of the given window's session, all of them or the ones named.
|
|
61
|
+
|
|
62
|
+
The window is matched by its position among the app's windows, which share creation order on both sides.
|
|
63
|
+
*/
|
|
64
|
+
getWindowCookies: (page: Page, name?: string) => Promise<Cookie[]>
|
|
65
|
+
}>({
|
|
66
|
+
browser: async ({ browser }, use) => {
|
|
67
|
+
// every context a test creates carries __IS_TEST from the first load, app code reads it while booting
|
|
68
|
+
const marked = browser as typeof browser & { isTestContextMarked?: boolean }
|
|
69
|
+
if (!marked.isTestContextMarked) {
|
|
70
|
+
marked.isTestContextMarked = true
|
|
71
|
+
const newContext = browser.newContext.bind(browser)
|
|
72
|
+
browser.newContext = async options => {
|
|
73
|
+
const context = await newContext(options)
|
|
74
|
+
await context.addInitScript(() => { (window as any).__IS_TEST = true })
|
|
75
|
+
return context
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
await use(browser)
|
|
79
|
+
},
|
|
80
|
+
// eslint-disable-next-line no-empty-pattern
|
|
81
|
+
app: async ({}, use) => {
|
|
82
|
+
const { app, close } = await launchApp({ appDir, userDataDir, serverUrl, windowUrlPrefix, useDevServer, env, extraArgs, windowTimeout })
|
|
83
|
+
await use(app)
|
|
84
|
+
await close()
|
|
85
|
+
},
|
|
86
|
+
page: async ({ waitForWindow }, use) => {
|
|
87
|
+
await use(await waitForWindow())
|
|
88
|
+
},
|
|
89
|
+
waitForWindow: async ({ app }, use) => {
|
|
90
|
+
// the url is not set yet when a window appears, so watch every window for its url and race that against new windows arriving
|
|
91
|
+
await use(async (prefix = windowUrlPrefix, timeout = windowTimeout) => {
|
|
92
|
+
const deadline = Date.now() + timeout
|
|
93
|
+
const watched = new Map<Page, Promise<Page | undefined>>()
|
|
94
|
+
const watch = (candidate: Page) => {
|
|
95
|
+
let pending = watched.get(candidate)
|
|
96
|
+
if (!pending) {
|
|
97
|
+
pending = candidate.waitForURL(url => url.toString().startsWith(prefix), { timeout: Math.max(deadline - Date.now(), 1) }).then(() => candidate).catch(() => undefined)
|
|
98
|
+
watched.set(candidate, pending)
|
|
99
|
+
}
|
|
100
|
+
return pending
|
|
101
|
+
}
|
|
102
|
+
let page: Page | undefined
|
|
103
|
+
while (!page && Date.now() < deadline) {
|
|
104
|
+
const next = await Promise.race([
|
|
105
|
+
...app.windows().map(watch),
|
|
106
|
+
app.waitForEvent("window", { timeout: Math.max(deadline - Date.now(), 1) }).catch(() => undefined)
|
|
107
|
+
])
|
|
108
|
+
if (next && next.url().startsWith(prefix)) page = next
|
|
109
|
+
}
|
|
110
|
+
if (!page) {
|
|
111
|
+
const seen = app.windows().map(candidate => candidate.url())
|
|
112
|
+
throw new Error(`No window with url starting with ${prefix}, saw: ${seen.join(", ") || "no windows"}.`)
|
|
113
|
+
}
|
|
114
|
+
return page
|
|
115
|
+
})
|
|
116
|
+
},
|
|
117
|
+
getPageFromWindow: async ({ app }, use) => {
|
|
118
|
+
const isAppWindow = (candidate: Page) => !candidate.url().startsWith("devtools://")
|
|
119
|
+
// the first window is not a reopen, and its event has already fired by the time this runs
|
|
120
|
+
let first = app.windows().find(isAppWindow)
|
|
121
|
+
while (!first) {
|
|
122
|
+
const candidate = await app.waitForEvent("window")
|
|
123
|
+
if (isAppWindow(candidate)) first = candidate
|
|
124
|
+
}
|
|
125
|
+
const pending: Page[] = []
|
|
126
|
+
const waiting: (() => void)[] = []
|
|
127
|
+
app.on("window", window => {
|
|
128
|
+
if (window === first || !isAppWindow(window)) return
|
|
129
|
+
pending.push(window)
|
|
130
|
+
waiting.shift()?.()
|
|
131
|
+
})
|
|
132
|
+
await use(async () => {
|
|
133
|
+
// the event can have fired before the caller asks, so the queue is the only source, never waitForEvent
|
|
134
|
+
if (pending.length === 0) await new Promise<void>(resolve => waiting.push(resolve))
|
|
135
|
+
const next = pending.shift()!
|
|
136
|
+
await next.waitForLoadState()
|
|
137
|
+
// the app closes the old window asynchronously, so it can still be listed while the new one loads
|
|
138
|
+
await expect.poll(() => app.evaluate(electron => electron.BrowserWindow.getAllWindows().length)).toBe(1)
|
|
139
|
+
return next
|
|
140
|
+
})
|
|
141
|
+
},
|
|
142
|
+
blockNetwork: async ({ app }, use) => {
|
|
143
|
+
await use(async (page: Page) => {
|
|
144
|
+
const index = app.windows().filter(candidate => !candidate.url().startsWith("devtools://")).indexOf(page)
|
|
145
|
+
if (index === -1) throw new Error("blockNetwork: the page does not belong to this app.")
|
|
146
|
+
await app.evaluate((electron, windowIndex) => {
|
|
147
|
+
const win = electron.BrowserWindow.getAllWindows()[windowIndex]
|
|
148
|
+
if (!win) throw new Error("blockNetwork: no window at that index.")
|
|
149
|
+
win.webContents.session.webRequest.onBeforeRequest({ urls: ["http://*/*"] }, (_details, callback) => callback({ cancel: true }))
|
|
150
|
+
}, index)
|
|
151
|
+
})
|
|
152
|
+
},
|
|
153
|
+
unblockNetwork: async ({ app }, use) => {
|
|
154
|
+
await use(async (page: Page) => {
|
|
155
|
+
const index = app.windows().filter(candidate => !candidate.url().startsWith("devtools://")).indexOf(page)
|
|
156
|
+
if (index === -1) throw new Error("unblockNetwork: the page does not belong to this app.")
|
|
157
|
+
await app.evaluate((electron, windowIndex) => {
|
|
158
|
+
const win = electron.BrowserWindow.getAllWindows()[windowIndex]
|
|
159
|
+
if (!win) throw new Error("unblockNetwork: no window at that index.")
|
|
160
|
+
win.webContents.session.webRequest.onBeforeRequest(null)
|
|
161
|
+
}, index)
|
|
162
|
+
})
|
|
163
|
+
},
|
|
164
|
+
getWindowCookies: async ({ app }, use) => {
|
|
165
|
+
await use(async (page: Page, name?: string) => {
|
|
166
|
+
const index = app.windows().filter(candidate => !candidate.url().startsWith("devtools://")).indexOf(page)
|
|
167
|
+
if (index === -1) throw new Error("getWindowCookies: the page does not belong to this app.")
|
|
168
|
+
return app.evaluate((electron, { windowIndex, cookieName }) => {
|
|
169
|
+
const win = electron.BrowserWindow.getAllWindows()[windowIndex]
|
|
170
|
+
if (!win) throw new Error("getWindowCookies: no window at that index.")
|
|
171
|
+
return win.webContents.session.cookies.get(cookieName ? { name: cookieName } : {})
|
|
172
|
+
}, { windowIndex: index, cookieName: name })
|
|
173
|
+
})
|
|
174
|
+
}
|
|
175
|
+
})
|
|
176
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/*
|
|
2
|
+
The url the local dev server is reached on. https when the devenv shell exported the local certificate.
|
|
3
|
+
|
|
4
|
+
Pass the port explicitly when the repo default differs, NUXT_PORT wins when it is set.
|
|
5
|
+
*/
|
|
6
|
+
export function localhostUrl(port: string = process.env.NUXT_PORT ?? "3000"): string {
|
|
7
|
+
const certs = process.env.LOCALHOST_KEY_PEM && process.env.LOCALHOST_PEM
|
|
8
|
+
return `${certs ? "https" : "http"}://localhost:${port}`
|
|
9
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { Page } from "@playwright/test"
|
|
2
|
+
|
|
3
|
+
/*
|
|
4
|
+
Waits until the page is on the route path, whatever the scheme and host are. The same route is app://bundle/authed in the bundle and http://localhost/authed in dev, so matching the pathname is what keeps one assertion working in both.
|
|
5
|
+
*/
|
|
6
|
+
export async function waitUntilAtPath(page: Page, path: string): Promise<void> {
|
|
7
|
+
await page.waitForURL(url => new URL(url).pathname === path)
|
|
8
|
+
}
|