sha
stringlengths 40
40
| author
stringclasses 155
values | date
stringlengths 19
19
| commit_message
stringlengths 24
9.22k
| git_diff
stringlengths 110
332k
⌀ | type
stringclasses 9
values |
|---|---|---|---|---|---|
78fa4777261edafb27f228669465de1e80161ee4
|
Charles Kerr
|
2024-10-09 13:02:00
|
fix: -Wunsafe-buffer-usage warning in HasWordCharacters() (#44133)
|
diff --git a/shell/renderer/api/electron_api_spell_check_client.cc b/shell/renderer/api/electron_api_spell_check_client.cc
index 2c2e0e5ee6..78c4c955b0 100644
--- a/shell/renderer/api/electron_api_spell_check_client.cc
+++ b/shell/renderer/api/electron_api_spell_check_client.cc
@@ -15,6 +15,7 @@
#include "base/containers/contains.h"
#include "base/logging.h"
#include "base/numerics/safe_conversions.h"
+#include "base/strings/utf_string_conversion_utils.h"
#include "base/task/single_thread_task_runner.h"
#include "components/spellcheck/renderer/spellcheck_worditerator.h"
#include "shell/common/gin_helper/dictionary.h"
@@ -29,12 +30,9 @@ namespace electron::api {
namespace {
-bool HasWordCharacters(const std::u16string& text, int index) {
- const char16_t* data = text.data();
- int length = text.length();
- while (index < length) {
- uint32_t code = 0;
- U16_NEXT(data, index, length, code);
+bool HasWordCharacters(const std::u16string& text, size_t index) {
+ base_icu::UChar32 code;
+ while (base::ReadUnicodeCharacter(text.c_str(), text.size(), &index, &code)) {
UErrorCode error = U_ZERO_ERROR;
if (uscript_getScript(code, &error) != USCRIPT_COMMON)
return true;
|
fix
|
8c71e2adc9b47f8d9e9ad07be9e6a9b3a764a670
|
Devraj Mehta
|
2024-01-04 16:20:37
|
feat: add net module to utility process (#40017)
* chore: initial prototype of net api from utility process
* chore: update url loader to work on both browser and utility processes
* chore: add net files to utility process bundle
* chore: re-add app ready check but only on main process
* chore: replace browser thread dcheck's with sequence checker
* refactor: move url loader from browser to common
* refactor: move net-client-request.ts from browser to common
* docs: add utility process to net api docs
* refactor: move net module app ready check to browser only
* refactor: switch import from main to common after moving to common
* test: add basic net module test for utility process
* refactor: switch browser pid with utility pid
* refactor: move electron_api_net from browser to common
* chore: add fetch to utility net module
* chore: add isOnline and online to utility net module
* refactor: move net spec helpers into helper file
* refactor: break apart net module tests
Adds two additional net module test files: `api-net-session-spec.ts` for
tests that depend on a session being available (aka depend on running on
the main process) and `api-net-custom-protocols-spec.ts` for custom
protocol tests. This enables running `api-net-spec.ts` in the utility
process.
* test: add utility process mocha runner to run net module tests
* docs: add utility process to net module classes
* refactor: update imports in lib/utility to use electron/utility
* chore: check browser context before using in main process
Since the browser context supplied to the SimpleURLLoaderWrapper can now
be null for use in the UtilityProcess, adding a null check for the main
process before use to get a more sensible error if something goes wrong.
Co-authored-by: Cheng Zhao <[email protected]>
* chore: remove test debugging
* chore: remove unnecessary header include
* docs: add utility process net module limitations
* test: run net module tests in utility process individually
* refactor: clean up prior utility process net tests
* chore: add resolveHost to utility process net module
* chore: replace resolve host dcheck with sequence checker
* test: add net module tests for net.resolveHost
* docs: remove utility process limitation for resolveHost
---------
Co-authored-by: deepak1556 <[email protected]>
Co-authored-by: Cheng Zhao <[email protected]>
|
diff --git a/docs/api/client-request.md b/docs/api/client-request.md
index 300fafa3ed..2d4d4ccac9 100644
--- a/docs/api/client-request.md
+++ b/docs/api/client-request.md
@@ -2,7 +2,7 @@
> Make HTTP/HTTPS requests.
-Process: [Main](../glossary.md#main-process)<br />
+Process: [Main](../glossary.md#main-process), [Utility](../glossary.md#utility-process)<br />
_This class is not exported from the `'electron'` module. It is only available as a return value of other methods in the Electron API._
`ClientRequest` implements the [Writable Stream](https://nodejs.org/api/stream.html#stream_writable_streams)
diff --git a/docs/api/incoming-message.md b/docs/api/incoming-message.md
index 02243fb7e9..021a44b803 100644
--- a/docs/api/incoming-message.md
+++ b/docs/api/incoming-message.md
@@ -2,7 +2,7 @@
> Handle responses to HTTP/HTTPS requests.
-Process: [Main](../glossary.md#main-process)<br />
+Process: [Main](../glossary.md#main-process), [Utility](../glossary.md#utility-process)<br />
_This class is not exported from the `'electron'` module. It is only available as a return value of other methods in the Electron API._
`IncomingMessage` implements the [Readable Stream](https://nodejs.org/api/stream.html#stream_readable_streams)
diff --git a/docs/api/net.md b/docs/api/net.md
index d670126146..79b2ca2cd3 100644
--- a/docs/api/net.md
+++ b/docs/api/net.md
@@ -2,7 +2,7 @@
> Issue HTTP/HTTPS requests using Chromium's native networking library
-Process: [Main](../glossary.md#main-process)
+Process: [Main](../glossary.md#main-process), [Utility](../glossary.md#utility-process)
The `net` module is a client-side API for issuing HTTP(S) requests. It is
similar to the [HTTP](https://nodejs.org/api/http.html) and
@@ -119,6 +119,9 @@ protocol.handle('https', (req) => {
})
```
+Note: in the [utility process](../glossary.md#utility-process) custom protocols
+are not supported.
+
### `net.isOnline()`
Returns `boolean` - Whether there is currently internet connection.
diff --git a/filenames.auto.gni b/filenames.auto.gni
index bbf228d5ab..b972dc9f4e 100644
--- a/filenames.auto.gni
+++ b/filenames.auto.gni
@@ -219,7 +219,6 @@ auto_filenames = {
"lib/browser/api/message-channel.ts",
"lib/browser/api/module-list.ts",
"lib/browser/api/native-theme.ts",
- "lib/browser/api/net-client-request.ts",
"lib/browser/api/net-fetch.ts",
"lib/browser/api/net-log.ts",
"lib/browser/api/net.ts",
@@ -255,6 +254,7 @@ auto_filenames = {
"lib/browser/web-view-events.ts",
"lib/common/api/module-list.ts",
"lib/common/api/native-image.ts",
+ "lib/common/api/net-client-request.ts",
"lib/common/api/shell.ts",
"lib/common/define-properties.ts",
"lib/common/deprecate.ts",
@@ -348,12 +348,16 @@ auto_filenames = {
]
utility_bundle_deps = [
+ "lib/browser/api/net-fetch.ts",
"lib/browser/message-port-main.ts",
+ "lib/common/api/net-client-request.ts",
"lib/common/define-properties.ts",
"lib/common/init.ts",
"lib/common/reset-search-paths.ts",
+ "lib/common/webpack-globals-provider.ts",
"lib/utility/api/exports/electron.ts",
"lib/utility/api/module-list.ts",
+ "lib/utility/api/net.ts",
"lib/utility/init.ts",
"lib/utility/parent-port.ts",
"package.json",
diff --git a/filenames.gni b/filenames.gni
index d142f312bb..c98bbb57fd 100644
--- a/filenames.gni
+++ b/filenames.gni
@@ -279,7 +279,6 @@ filenames = {
"shell/browser/api/electron_api_menu.h",
"shell/browser/api/electron_api_native_theme.cc",
"shell/browser/api/electron_api_native_theme.h",
- "shell/browser/api/electron_api_net.cc",
"shell/browser/api/electron_api_net_log.cc",
"shell/browser/api/electron_api_net_log.h",
"shell/browser/api/electron_api_notification.cc",
@@ -305,8 +304,6 @@ filenames = {
"shell/browser/api/electron_api_system_preferences.h",
"shell/browser/api/electron_api_tray.cc",
"shell/browser/api/electron_api_tray.h",
- "shell/browser/api/electron_api_url_loader.cc",
- "shell/browser/api/electron_api_url_loader.h",
"shell/browser/api/electron_api_utility_process.cc",
"shell/browser/api/electron_api_utility_process.h",
"shell/browser/api/electron_api_view.cc",
@@ -544,8 +541,11 @@ filenames = {
"shell/common/api/electron_api_key_weak_map.h",
"shell/common/api/electron_api_native_image.cc",
"shell/common/api/electron_api_native_image.h",
+ "shell/common/api/electron_api_net.cc",
"shell/common/api/electron_api_shell.cc",
"shell/common/api/electron_api_testing.cc",
+ "shell/common/api/electron_api_url_loader.cc",
+ "shell/common/api/electron_api_url_loader.h",
"shell/common/api/electron_api_v8_util.cc",
"shell/common/api/electron_bindings.cc",
"shell/common/api/electron_bindings.h",
diff --git a/lib/browser/api/net-fetch.ts b/lib/browser/api/net-fetch.ts
index b73512f43f..4f44f2cc42 100644
--- a/lib/browser/api/net-fetch.ts
+++ b/lib/browser/api/net-fetch.ts
@@ -1,6 +1,6 @@
-import { net, IncomingMessage, Session as SessionT } from 'electron/main';
+import { ClientRequestConstructorOptions, ClientRequest, IncomingMessage, Session as SessionT } from 'electron/main';
import { Readable, Writable, isReadable } from 'stream';
-import { allowAnyProtocol } from '@electron/internal/browser/api/net-client-request';
+import { allowAnyProtocol } from '@electron/internal/common/api/net-client-request';
function createDeferredPromise<T, E extends Error = Error> (): { promise: Promise<T>; resolve: (x: T) => void; reject: (e: E) => void; } {
let res: (x: T) => void;
@@ -13,7 +13,8 @@ function createDeferredPromise<T, E extends Error = Error> (): { promise: Promis
return { promise, resolve: res!, reject: rej! };
}
-export function fetchWithSession (input: RequestInfo, init: (RequestInit & {bypassCustomProtocolHandlers?: boolean}) | undefined, session: SessionT): Promise<Response> {
+export function fetchWithSession (input: RequestInfo, init: (RequestInit & {bypassCustomProtocolHandlers?: boolean}) | undefined, session: SessionT | undefined,
+ request: (options: ClientRequestConstructorOptions | string) => ClientRequest) {
const p = createDeferredPromise<Response>();
let req: Request;
try {
@@ -73,7 +74,7 @@ export function fetchWithSession (input: RequestInfo, init: (RequestInit & {bypa
// We can't set credentials to same-origin unless there's an origin set.
const credentials = req.credentials === 'same-origin' && !origin ? 'include' : req.credentials;
- const r = net.request(allowAnyProtocol({
+ const r = request(allowAnyProtocol({
session,
method: req.method,
url: req.url,
diff --git a/lib/browser/api/net.ts b/lib/browser/api/net.ts
index 7d2ec17563..dd824c990f 100644
--- a/lib/browser/api/net.ts
+++ b/lib/browser/api/net.ts
@@ -1,10 +1,13 @@
-import { IncomingMessage, session } from 'electron/main';
+import { app, IncomingMessage, session } from 'electron/main';
import type { ClientRequestConstructorOptions } from 'electron/main';
-import { ClientRequest } from '@electron/internal/browser/api/net-client-request';
+import { ClientRequest } from '@electron/internal/common/api/net-client-request';
-const { isOnline } = process._linkedBinding('electron_browser_net');
+const { isOnline } = process._linkedBinding('electron_common_net');
export function request (options: ClientRequestConstructorOptions | string, callback?: (message: IncomingMessage) => void) {
+ if (!app.isReady()) {
+ throw new Error('net module can only be used after app is ready');
+ }
return new ClientRequest(options, callback);
}
diff --git a/lib/browser/api/session.ts b/lib/browser/api/session.ts
index ea74cc8873..5f9343c1bd 100644
--- a/lib/browser/api/session.ts
+++ b/lib/browser/api/session.ts
@@ -1,8 +1,9 @@
import { fetchWithSession } from '@electron/internal/browser/api/net-fetch';
+import { net } from 'electron/main';
const { fromPartition, fromPath, Session } = process._linkedBinding('electron_browser_session');
Session.prototype.fetch = function (input: RequestInfo, init?: RequestInit) {
- return fetchWithSession(input, init, this);
+ return fetchWithSession(input, init, this, net.request);
};
export default {
diff --git a/lib/browser/guest-view-manager.ts b/lib/browser/guest-view-manager.ts
index 942163711c..6b82328472 100644
--- a/lib/browser/guest-view-manager.ts
+++ b/lib/browser/guest-view-manager.ts
@@ -14,7 +14,7 @@ interface GuestInstance {
}
const webViewManager = process._linkedBinding('electron_browser_web_view_manager');
-const netBinding = process._linkedBinding('electron_browser_net');
+const netBinding = process._linkedBinding('electron_common_net');
const supportedWebViewEvents = Object.keys(webViewEvents);
diff --git a/lib/browser/api/net-client-request.ts b/lib/common/api/net-client-request.ts
similarity index 95%
rename from lib/browser/api/net-client-request.ts
rename to lib/common/api/net-client-request.ts
index 9332f86ce1..97055411bf 100644
--- a/lib/browser/api/net-client-request.ts
+++ b/lib/common/api/net-client-request.ts
@@ -1,14 +1,15 @@
import * as url from 'url';
import { Readable, Writable } from 'stream';
-import { app } from 'electron/main';
-import type { ClientRequestConstructorOptions, UploadProgress } from 'electron/main';
+import type {
+ ClientRequestConstructorOptions,
+ UploadProgress
+} from 'electron/common';
const {
isValidHeaderName,
isValidHeaderValue,
createURLLoader
-} = process._linkedBinding('electron_browser_net');
-const { Session } = process._linkedBinding('electron_browser_session');
+} = process._linkedBinding('electron_common_net');
const kHttpProtocols = new Set(['http:', 'https:']);
@@ -283,14 +284,17 @@ function parseOptions (optionsIn: ClientRequestConstructorOptions | string): Nod
const key = name.toLowerCase();
urlLoaderOptions.headers[key] = { name, value };
}
- if (options.session) {
- if (!(options.session instanceof Session)) { throw new TypeError('`session` should be an instance of the Session class'); }
- urlLoaderOptions.session = options.session;
- } else if (options.partition) {
- if (typeof options.partition === 'string') {
- urlLoaderOptions.partition = options.partition;
- } else {
- throw new TypeError('`partition` should be a string');
+ if (process.type !== 'utility') {
+ const { Session } = process._linkedBinding('electron_browser_session');
+ if (options.session) {
+ if (!(options.session instanceof Session)) { throw new TypeError('`session` should be an instance of the Session class'); }
+ urlLoaderOptions.session = options.session;
+ } else if (options.partition) {
+ if (typeof options.partition === 'string') {
+ urlLoaderOptions.partition = options.partition;
+ } else {
+ throw new TypeError('`partition` should be a string');
+ }
}
}
return urlLoaderOptions;
@@ -312,10 +316,6 @@ export class ClientRequest extends Writable implements Electron.ClientRequest {
constructor (options: ClientRequestConstructorOptions | string, callback?: (message: IncomingMessage) => void) {
super({ autoDestroy: true });
- if (!app.isReady()) {
- throw new Error('net module can only be used after app is ready');
- }
-
if (callback) {
this.once('response', callback);
}
diff --git a/lib/utility/api/module-list.ts b/lib/utility/api/module-list.ts
index 53f2e5d9bf..9d6670217e 100644
--- a/lib/utility/api/module-list.ts
+++ b/lib/utility/api/module-list.ts
@@ -1,2 +1,4 @@
// Utility side modules, please sort alphabetically.
-export const utilityNodeModuleList: ElectronInternal.ModuleEntry[] = [];
+export const utilityNodeModuleList: ElectronInternal.ModuleEntry[] = [
+ { name: 'net', loader: () => require('./net') }
+];
diff --git a/lib/utility/api/net.ts b/lib/utility/api/net.ts
new file mode 100644
index 0000000000..b5237e8233
--- /dev/null
+++ b/lib/utility/api/net.ts
@@ -0,0 +1,22 @@
+import { IncomingMessage } from 'electron/utility';
+import type { ClientRequestConstructorOptions } from 'electron/utility';
+import { ClientRequest } from '@electron/internal/common/api/net-client-request';
+import { fetchWithSession } from '@electron/internal/browser/api/net-fetch';
+
+const { isOnline, resolveHost } = process._linkedBinding('electron_common_net');
+
+export function request (options: ClientRequestConstructorOptions | string, callback?: (message: IncomingMessage) => void) {
+ return new ClientRequest(options, callback);
+}
+
+export function fetch (input: RequestInfo, init?: RequestInit): Promise<Response> {
+ return fetchWithSession(input, init, undefined, request);
+}
+
+exports.resolveHost = resolveHost;
+
+exports.isOnline = isOnline;
+
+Object.defineProperty(exports, 'online', {
+ get: () => isOnline()
+});
diff --git a/lib/utility/init.ts b/lib/utility/init.ts
index 6012995387..14cf0cf5ce 100644
--- a/lib/utility/init.ts
+++ b/lib/utility/init.ts
@@ -1,3 +1,4 @@
+import { EventEmitter } from 'events';
import { pathToFileURL } from 'url';
import { ParentPort } from '@electron/internal/utility/parent-port';
@@ -15,6 +16,8 @@ require('../common/reset-search-paths');
// Import common settings.
require('@electron/internal/common/init');
+process._linkedBinding('electron_browser_event_emitter').setEventEmitterPrototype(EventEmitter.prototype);
+
const parentPort: ParentPort = new ParentPort();
Object.defineProperty(process, 'parentPort', {
enumerable: true,
diff --git a/shell/browser/api/electron_api_utility_process.cc b/shell/browser/api/electron_api_utility_process.cc
index aac2e6d7ca..593f238f5e 100644
--- a/shell/browser/api/electron_api_utility_process.cc
+++ b/shell/browser/api/electron_api_utility_process.cc
@@ -13,6 +13,7 @@
#include "base/process/kill.h"
#include "base/process/launch.h"
#include "base/process/process.h"
+#include "chrome/browser/browser_process.h"
#include "content/public/browser/child_process_host.h"
#include "content/public/browser/service_process_host.h"
#include "content/public/common/result_codes.h"
@@ -22,6 +23,7 @@
#include "mojo/public/cpp/bindings/pending_receiver.h"
#include "shell/browser/api/message_port.h"
#include "shell/browser/javascript_environment.h"
+#include "shell/browser/net/system_network_context_manager.h"
#include "shell/common/gin_converters/callback_converter.h"
#include "shell/common/gin_converters/file_path_converter.h"
#include "shell/common/gin_helper/dictionary.h"
@@ -192,6 +194,22 @@ UtilityProcessWrapper::UtilityProcessWrapper(
connector_->set_connection_error_handler(base::BindOnce(
&UtilityProcessWrapper::CloseConnectorPort, weak_factory_.GetWeakPtr()));
+ mojo::PendingRemote<network::mojom::URLLoaderFactory> url_loader_factory;
+ network::mojom::URLLoaderFactoryParamsPtr loader_params =
+ network::mojom::URLLoaderFactoryParams::New();
+ loader_params->process_id = pid_;
+ loader_params->is_corb_enabled = false;
+ loader_params->is_trusted = true;
+ network::mojom::NetworkContext* network_context =
+ g_browser_process->system_network_context_manager()->GetContext();
+ network_context->CreateURLLoaderFactory(
+ url_loader_factory.InitWithNewPipeAndPassReceiver(),
+ std::move(loader_params));
+ params->url_loader_factory = std::move(url_loader_factory);
+ mojo::PendingRemote<network::mojom::HostResolver> host_resolver;
+ network_context->CreateHostResolver(
+ {}, host_resolver.InitWithNewPipeAndPassReceiver());
+ params->host_resolver = std::move(host_resolver);
node_service_remote_->Initialize(std::move(params));
}
diff --git a/shell/browser/net/resolve_host_function.cc b/shell/browser/net/resolve_host_function.cc
index 8c62c2089e..3071955e92 100644
--- a/shell/browser/net/resolve_host_function.cc
+++ b/shell/browser/net/resolve_host_function.cc
@@ -15,7 +15,10 @@
#include "net/base/net_errors.h"
#include "net/base/network_isolation_key.h"
#include "net/dns/public/resolve_error_info.h"
+#include "services/network/public/mojom/network_context.mojom.h"
#include "shell/browser/electron_browser_context.h"
+#include "shell/common/process_util.h"
+#include "shell/services/node/node_service.h"
#include "url/origin.h"
using content::BrowserThread;
@@ -30,15 +33,17 @@ ResolveHostFunction::ResolveHostFunction(
: browser_context_(browser_context),
host_(std::move(host)),
params_(std::move(params)),
- callback_(std::move(callback)) {}
+ callback_(std::move(callback)) {
+ DETACH_FROM_SEQUENCE(sequence_checker_);
+}
ResolveHostFunction::~ResolveHostFunction() {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
+ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK(!receiver_.is_bound());
}
void ResolveHostFunction::Run() {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
+ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK(!receiver_.is_bound());
// Start the request.
@@ -50,12 +55,21 @@ void ResolveHostFunction::Run() {
net::ResolveErrorInfo(net::ERR_FAILED),
/*resolved_addresses=*/absl::nullopt,
/*endpoint_results_with_metadata=*/absl::nullopt));
- browser_context_->GetDefaultStoragePartition()
- ->GetNetworkContext()
- ->ResolveHost(network::mojom::HostResolverHost::NewHostPortPair(
- std::move(host_port_pair)),
- net::NetworkAnonymizationKey(), std::move(params_),
- std::move(resolve_host_client));
+ if (electron::IsUtilityProcess()) {
+ URLLoaderBundle::GetInstance()->GetHostResolver()->ResolveHost(
+ network::mojom::HostResolverHost::NewHostPortPair(
+ std::move(host_port_pair)),
+ net::NetworkAnonymizationKey(), std::move(params_),
+ std::move(resolve_host_client));
+ } else {
+ DCHECK_CURRENTLY_ON(BrowserThread::UI);
+ browser_context_->GetDefaultStoragePartition()
+ ->GetNetworkContext()
+ ->ResolveHost(network::mojom::HostResolverHost::NewHostPortPair(
+ std::move(host_port_pair)),
+ net::NetworkAnonymizationKey(), std::move(params_),
+ std::move(resolve_host_client));
+ }
}
void ResolveHostFunction::OnComplete(
@@ -64,7 +78,7 @@ void ResolveHostFunction::OnComplete(
const absl::optional<net::AddressList>& resolved_addresses,
const absl::optional<net::HostResolverEndpointResults>&
endpoint_results_with_metadata) {
- DCHECK_CURRENTLY_ON(BrowserThread::UI);
+ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
// Ensure that we outlive the `receiver_.reset()` call.
scoped_refptr<ResolveHostFunction> self(this);
diff --git a/shell/browser/net/resolve_host_function.h b/shell/browser/net/resolve_host_function.h
index 60da16c726..a860e09d5f 100644
--- a/shell/browser/net/resolve_host_function.h
+++ b/shell/browser/net/resolve_host_function.h
@@ -9,6 +9,7 @@
#include "base/memory/raw_ptr.h"
#include "base/memory/ref_counted.h"
+#include "base/sequence_checker.h"
#include "mojo/public/cpp/bindings/receiver.h"
#include "net/base/address_list.h"
#include "net/dns/public/host_resolver_results.h"
@@ -53,6 +54,8 @@ class ResolveHostFunction
const absl::optional<net::HostResolverEndpointResults>&
endpoint_results_with_metadata) override;
+ SEQUENCE_CHECKER(sequence_checker_);
+
// Receiver for the currently in-progress request, if any.
mojo::Receiver<network::mojom::ResolveHostClient> receiver_{this};
diff --git a/shell/browser/api/electron_api_net.cc b/shell/common/api/electron_api_net.cc
similarity index 54%
rename from shell/browser/api/electron_api_net.cc
rename to shell/common/api/electron_api_net.cc
index 62063d572b..8339dc68db 100644
--- a/shell/browser/api/electron_api_net.cc
+++ b/shell/common/api/electron_api_net.cc
@@ -9,13 +9,16 @@
#include "net/base/network_change_notifier.h"
#include "net/http/http_util.h"
#include "services/network/public/cpp/features.h"
-#include "shell/browser/api/electron_api_url_loader.h"
+#include "services/network/public/mojom/host_resolver.mojom.h"
+#include "shell/browser/net/resolve_host_function.h"
+#include "shell/common/api/electron_api_url_loader.h"
#include "shell/common/gin_converters/file_path_converter.h"
#include "shell/common/gin_converters/gurl_converter.h"
+#include "shell/common/gin_converters/net_converter.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/gin_helper/error_thrower.h"
#include "shell/common/gin_helper/object_template_builder.h"
-
+#include "shell/common/gin_helper/promise.h"
#include "shell/common/node_includes.h"
namespace {
@@ -40,6 +43,37 @@ base::FilePath FileURLToFilePath(v8::Isolate* isolate, const GURL& url) {
return path;
}
+v8::Local<v8::Promise> ResolveHost(
+ v8::Isolate* isolate,
+ std::string host,
+ absl::optional<network::mojom::ResolveHostParametersPtr> params) {
+ gin_helper::Promise<gin_helper::Dictionary> promise(isolate);
+ v8::Local<v8::Promise> handle = promise.GetHandle();
+
+ auto fn = base::MakeRefCounted<electron::ResolveHostFunction>(
+ nullptr, std::move(host), params ? std::move(params.value()) : nullptr,
+ base::BindOnce(
+ [](gin_helper::Promise<gin_helper::Dictionary> promise,
+ int64_t net_error, const absl::optional<net::AddressList>& addrs) {
+ if (net_error < 0) {
+ promise.RejectWithErrorMessage(net::ErrorToString(net_error));
+ } else {
+ DCHECK(addrs.has_value() && !addrs->empty());
+
+ v8::HandleScope handle_scope(promise.isolate());
+ auto dict =
+ gin_helper::Dictionary::CreateEmpty(promise.isolate());
+ dict.Set("endpoints", addrs->endpoints());
+ promise.Resolve(dict);
+ }
+ },
+ std::move(promise)));
+
+ fn->Run();
+
+ return handle;
+}
+
using electron::api::SimpleURLLoaderWrapper;
void Initialize(v8::Local<v8::Object> exports,
@@ -54,8 +88,9 @@ void Initialize(v8::Local<v8::Object> exports,
dict.SetMethod("isValidHeaderValue", &IsValidHeaderValue);
dict.SetMethod("createURLLoader", &SimpleURLLoaderWrapper::Create);
dict.SetMethod("fileURLToFilePath", &FileURLToFilePath);
+ dict.SetMethod("resolveHost", &ResolveHost);
}
} // namespace
-NODE_LINKED_BINDING_CONTEXT_AWARE(electron_browser_net, Initialize)
+NODE_LINKED_BINDING_CONTEXT_AWARE(electron_common_net, Initialize)
diff --git a/shell/browser/api/electron_api_url_loader.cc b/shell/common/api/electron_api_url_loader.cc
similarity index 95%
rename from shell/browser/api/electron_api_url_loader.cc
rename to shell/common/api/electron_api_url_loader.cc
index e95586a22a..9cb27af9b7 100644
--- a/shell/browser/api/electron_api_url_loader.cc
+++ b/shell/common/api/electron_api_url_loader.cc
@@ -2,7 +2,7 @@
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
-#include "shell/browser/api/electron_api_url_loader.h"
+#include "shell/common/api/electron_api_url_loader.h"
#include <algorithm>
#include <memory>
@@ -13,6 +13,7 @@
#include "base/containers/fixed_flat_map.h"
#include "base/memory/raw_ptr.h"
#include "base/no_destructor.h"
+#include "base/sequence_checker.h"
#include "gin/handle.h"
#include "gin/object_template_builder.h"
#include "gin/wrappable.h"
@@ -39,7 +40,10 @@
#include "shell/common/gin_converters/net_converter.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/gin_helper/object_template_builder.h"
+#include "shell/common/gin_helper/promise.h"
#include "shell/common/node_includes.h"
+#include "shell/common/process_util.h"
+#include "shell/services/node/node_service.h"
#include "third_party/blink/public/common/loader/referrer_utils.h"
#include "third_party/blink/public/mojom/fetch/fetch_api_request.mojom.h"
@@ -186,6 +190,7 @@ class JSChunkedDataPipeGetter : public gin::Wrappable<JSChunkedDataPipeGetter>,
mojo::PendingReceiver<network::mojom::ChunkedDataPipeGetter>
chunked_data_pipe_getter)
: isolate_(isolate), body_func_(isolate, body_func) {
+ DETACH_FROM_SEQUENCE(sequence_checker_);
receiver_.Bind(std::move(chunked_data_pipe_getter));
}
@@ -195,7 +200,7 @@ class JSChunkedDataPipeGetter : public gin::Wrappable<JSChunkedDataPipeGetter>,
}
void StartReading(mojo::ScopedDataPipeProducerHandle pipe) override {
- DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
+ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
if (body_func_.IsEmpty()) {
LOG(ERROR) << "Tried to read twice from a JSChunkedDataPipeGetter";
@@ -251,7 +256,7 @@ class JSChunkedDataPipeGetter : public gin::Wrappable<JSChunkedDataPipeGetter>,
void OnWriteChunkComplete(gin_helper::Promise<void> promise,
MojoResult result) {
- DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
+ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
is_writing_ = false;
if (result == MOJO_RESULT_OK) {
promise.Resolve();
@@ -278,6 +283,7 @@ class JSChunkedDataPipeGetter : public gin::Wrappable<JSChunkedDataPipeGetter>,
size_callback_.Reset();
}
+ SEQUENCE_CHECKER(sequence_checker_);
GetSizeCallback size_callback_;
mojo::Receiver<network::mojom::ChunkedDataPipeGetter> receiver_{this};
std::unique_ptr<mojo::DataPipeProducer> data_producer_;
@@ -320,6 +326,7 @@ SimpleURLLoaderWrapper::SimpleURLLoaderWrapper(
: browser_context_(browser_context),
request_options_(options),
request_(std::move(request)) {
+ DETACH_FROM_SEQUENCE(sequence_checker_);
if (!request_->trusted_params)
request_->trusted_params = network::ResourceRequest::TrustedParams();
mojo::PendingRemote<network::mojom::URLLoaderNetworkServiceObserver>
@@ -393,7 +400,7 @@ void SimpleURLLoaderWrapper::OnAuthRequired(
const scoped_refptr<net::HttpResponseHeaders>& head_headers,
mojo::PendingRemote<network::mojom::AuthChallengeResponder>
auth_challenge_responder) {
- DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
+ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
mojo::Remote<network::mojom::AuthChallengeResponder> auth_responder(
std::move(auth_challenge_responder));
// WeakPtr because if we're Cancel()ed while waiting for auth, and the
@@ -462,6 +469,10 @@ void SimpleURLLoaderWrapper::Cancel() {
}
scoped_refptr<network::SharedURLLoaderFactory>
SimpleURLLoaderWrapper::GetURLLoaderFactoryForURL(const GURL& url) {
+ if (electron::IsUtilityProcess()) {
+ return URLLoaderBundle::GetInstance()->GetSharedURLLoaderFactory();
+ }
+ CHECK(browser_context_);
scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory;
auto* protocol_registry =
ProtocolRegistry::FromBrowserContext(browser_context_);
@@ -660,18 +671,22 @@ gin::Handle<SimpleURLLoaderWrapper> SimpleURLLoaderWrapper::Create(
}
}
- std::string partition;
- gin::Handle<Session> session;
- if (!opts.Get("session", &session)) {
- if (opts.Get("partition", &partition))
- session = Session::FromPartition(args->isolate(), partition);
- else // default session
- session = Session::FromPartition(args->isolate(), "");
+ ElectronBrowserContext* browser_context = nullptr;
+ if (electron::IsBrowserProcess()) {
+ std::string partition;
+ gin::Handle<Session> session;
+ if (!opts.Get("session", &session)) {
+ if (opts.Get("partition", &partition))
+ session = Session::FromPartition(args->isolate(), partition);
+ else // default session
+ session = Session::FromPartition(args->isolate(), "");
+ }
+ browser_context = session->browser_context();
}
auto ret = gin::CreateHandle(
- args->isolate(), new SimpleURLLoaderWrapper(session->browser_context(),
- std::move(request), options));
+ args->isolate(),
+ new SimpleURLLoaderWrapper(browser_context, std::move(request), options));
ret->Pin();
if (!chunk_pipe_getter.IsEmpty()) {
ret->PinBodyGetter(chunk_pipe_getter);
@@ -681,7 +696,7 @@ gin::Handle<SimpleURLLoaderWrapper> SimpleURLLoaderWrapper::Create(
void SimpleURLLoaderWrapper::OnDataReceived(base::StringPiece string_piece,
base::OnceClosure resume) {
- DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
+ DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
auto array_buffer = v8::ArrayBuffer::New(isolate, string_piece.size());
diff --git a/shell/browser/api/electron_api_url_loader.h b/shell/common/api/electron_api_url_loader.h
similarity index 98%
rename from shell/browser/api/electron_api_url_loader.h
rename to shell/common/api/electron_api_url_loader.h
index 2f16f5d39e..ccabfb83bd 100644
--- a/shell/browser/api/electron_api_url_loader.h
+++ b/shell/common/api/electron_api_url_loader.h
@@ -11,6 +11,7 @@
#include "base/memory/raw_ptr.h"
#include "base/memory/weak_ptr.h"
+#include "base/sequence_checker.h"
#include "gin/wrappable.h"
#include "mojo/public/cpp/bindings/receiver_set.h"
#include "net/base/auth.h"
@@ -133,6 +134,7 @@ class SimpleURLLoaderWrapper
void Pin();
void PinBodyGetter(v8::Local<v8::Value>);
+ SEQUENCE_CHECKER(sequence_checker_);
raw_ptr<ElectronBrowserContext> browser_context_;
int request_options_;
std::unique_ptr<network::ResourceRequest> request_;
diff --git a/shell/common/node_bindings.cc b/shell/common/node_bindings.cc
index d598722472..704f71e8b9 100644
--- a/shell/common/node_bindings.cc
+++ b/shell/common/node_bindings.cc
@@ -57,7 +57,6 @@
V(electron_browser_menu) \
V(electron_browser_message_port) \
V(electron_browser_native_theme) \
- V(electron_browser_net) \
V(electron_browser_notification) \
V(electron_browser_power_monitor) \
V(electron_browser_power_save_blocker) \
@@ -76,7 +75,8 @@
V(electron_browser_web_contents_view) \
V(electron_browser_web_frame_main) \
V(electron_browser_web_view_manager) \
- V(electron_browser_window)
+ V(electron_browser_window) \
+ V(electron_common_net)
#define ELECTRON_COMMON_BINDINGS(V) \
V(electron_common_asar) \
@@ -96,7 +96,10 @@
V(electron_renderer_ipc) \
V(electron_renderer_web_frame)
-#define ELECTRON_UTILITY_BINDINGS(V) V(electron_utility_parent_port)
+#define ELECTRON_UTILITY_BINDINGS(V) \
+ V(electron_browser_event_emitter) \
+ V(electron_common_net) \
+ V(electron_utility_parent_port)
#define ELECTRON_TESTING_BINDINGS(V) V(electron_common_testing)
diff --git a/shell/services/node/node_service.cc b/shell/services/node/node_service.cc
index 0a9048e3c2..e742198937 100644
--- a/shell/services/node/node_service.cc
+++ b/shell/services/node/node_service.cc
@@ -7,7 +7,11 @@
#include <utility>
#include "base/command_line.h"
+#include "base/no_destructor.h"
#include "base/strings/utf_string_conversions.h"
+#include "services/network/public/cpp/wrapper_shared_url_loader_factory.h"
+#include "services/network/public/mojom/host_resolver.mojom.h"
+#include "services/network/public/mojom/network_context.mojom.h"
#include "shell/browser/javascript_environment.h"
#include "shell/common/api/electron_bindings.h"
#include "shell/common/gin_converters/file_path_converter.h"
@@ -18,6 +22,34 @@
namespace electron {
+URLLoaderBundle::URLLoaderBundle() = default;
+
+URLLoaderBundle::~URLLoaderBundle() = default;
+
+URLLoaderBundle* URLLoaderBundle::GetInstance() {
+ static base::NoDestructor<URLLoaderBundle> instance;
+ return instance.get();
+}
+
+void URLLoaderBundle::SetURLLoaderFactory(
+ mojo::PendingRemote<network::mojom::URLLoaderFactory> pending_factory,
+ mojo::Remote<network::mojom::HostResolver> host_resolver) {
+ factory_ = network::SharedURLLoaderFactory::Create(
+ std::make_unique<network::WrapperPendingSharedURLLoaderFactory>(
+ std::move(pending_factory)));
+ host_resolver_ = std::move(host_resolver);
+}
+
+scoped_refptr<network::SharedURLLoaderFactory>
+URLLoaderBundle::GetSharedURLLoaderFactory() {
+ return factory_;
+}
+
+network::mojom::HostResolver* URLLoaderBundle::GetHostResolver() {
+ DCHECK(host_resolver_);
+ return host_resolver_.get();
+}
+
NodeService::NodeService(
mojo::PendingReceiver<node::mojom::NodeService> receiver)
: node_bindings_{NodeBindings::Create(
@@ -42,6 +74,10 @@ void NodeService::Initialize(node::mojom::NodeServiceParamsPtr params) {
ParentPort::GetInstance()->Initialize(std::move(params->port));
+ URLLoaderBundle::GetInstance()->SetURLLoaderFactory(
+ std::move(params->url_loader_factory),
+ mojo::Remote(std::move(params->host_resolver)));
+
js_env_ = std::make_unique<JavascriptEnvironment>(node_bindings_->uv_loop());
v8::HandleScope scope(js_env_->isolate());
diff --git a/shell/services/node/node_service.h b/shell/services/node/node_service.h
index 03301e95a3..eae1bd2a5a 100644
--- a/shell/services/node/node_service.h
+++ b/shell/services/node/node_service.h
@@ -8,7 +8,12 @@
#include <memory>
#include "mojo/public/cpp/bindings/pending_receiver.h"
+#include "mojo/public/cpp/bindings/pending_remote.h"
#include "mojo/public/cpp/bindings/receiver.h"
+#include "mojo/public/cpp/bindings/remote.h"
+#include "services/network/public/cpp/shared_url_loader_factory.h"
+#include "services/network/public/mojom/host_resolver.mojom.h"
+#include "services/network/public/mojom/url_loader_factory.mojom-forward.h"
#include "shell/services/node/public/mojom/node_service.mojom.h"
namespace node {
@@ -23,6 +28,26 @@ class ElectronBindings;
class JavascriptEnvironment;
class NodeBindings;
+class URLLoaderBundle {
+ public:
+ URLLoaderBundle();
+ ~URLLoaderBundle();
+
+ URLLoaderBundle(const URLLoaderBundle&) = delete;
+ URLLoaderBundle& operator=(const URLLoaderBundle&) = delete;
+
+ static URLLoaderBundle* GetInstance();
+ void SetURLLoaderFactory(
+ mojo::PendingRemote<network::mojom::URLLoaderFactory> factory,
+ mojo::Remote<network::mojom::HostResolver> host_resolver);
+ scoped_refptr<network::SharedURLLoaderFactory> GetSharedURLLoaderFactory();
+ network::mojom::HostResolver* GetHostResolver();
+
+ private:
+ scoped_refptr<network::SharedURLLoaderFactory> factory_;
+ mojo::Remote<network::mojom::HostResolver> host_resolver_;
+};
+
class NodeService : public node::mojom::NodeService {
public:
explicit NodeService(
diff --git a/shell/services/node/public/mojom/node_service.mojom b/shell/services/node/public/mojom/node_service.mojom
index 02dacc8a67..30ebcae92c 100644
--- a/shell/services/node/public/mojom/node_service.mojom
+++ b/shell/services/node/public/mojom/node_service.mojom
@@ -6,6 +6,8 @@ module node.mojom;
import "mojo/public/mojom/base/file_path.mojom";
import "sandbox/policy/mojom/sandbox.mojom";
+import "services/network/public/mojom/host_resolver.mojom";
+import "services/network/public/mojom/url_loader_factory.mojom";
import "third_party/blink/public/mojom/messaging/message_port_descriptor.mojom";
struct NodeServiceParams {
@@ -13,6 +15,8 @@ struct NodeServiceParams {
array<string> args;
array<string> exec_args;
blink.mojom.MessagePortDescriptor port;
+ pending_remote<network.mojom.URLLoaderFactory> url_loader_factory;
+ pending_remote<network.mojom.HostResolver> host_resolver;
};
[ServiceSandbox=sandbox.mojom.Sandbox.kNoSandbox]
diff --git a/spec/api-net-custom-protocols-spec.ts b/spec/api-net-custom-protocols-spec.ts
new file mode 100644
index 0000000000..d9ffc43d81
--- /dev/null
+++ b/spec/api-net-custom-protocols-spec.ts
@@ -0,0 +1,85 @@
+import { expect } from 'chai';
+import { net, protocol } from 'electron/main';
+import * as url from 'node:url';
+import * as path from 'node:path';
+import { defer } from './lib/spec-helpers';
+
+describe('net module custom protocols', () => {
+ it('can request file:// URLs', async () => {
+ const resp = await net.fetch(url.pathToFileURL(path.join(__dirname, 'fixtures', 'hello.txt')).toString());
+ expect(resp.ok).to.be.true();
+ // trimRight instead of asserting the whole string to avoid line ending shenanigans on WOA
+ expect((await resp.text()).trimRight()).to.equal('hello world');
+ });
+
+ it('can make requests to custom protocols', async () => {
+ protocol.registerStringProtocol('electron-test', (req, cb) => { cb('hello ' + req.url); });
+ defer(() => {
+ protocol.unregisterProtocol('electron-test');
+ });
+ const body = await net.fetch('electron-test://foo').then(r => r.text());
+ expect(body).to.equal('hello electron-test://foo');
+ });
+
+ it('runs through intercept handlers', async () => {
+ protocol.interceptStringProtocol('http', (req, cb) => { cb('hello ' + req.url); });
+ defer(() => {
+ protocol.uninterceptProtocol('http');
+ });
+ const body = await net.fetch('http://foo').then(r => r.text());
+ expect(body).to.equal('hello http://foo/');
+ });
+
+ it('file: runs through intercept handlers', async () => {
+ protocol.interceptStringProtocol('file', (req, cb) => { cb('hello ' + req.url); });
+ defer(() => {
+ protocol.uninterceptProtocol('file');
+ });
+ const body = await net.fetch('file://foo').then(r => r.text());
+ expect(body).to.equal('hello file://foo/');
+ });
+
+ it('can be redirected', async () => {
+ protocol.interceptStringProtocol('file', (req, cb) => { cb({ statusCode: 302, headers: { location: 'electron-test://bar' } }); });
+ defer(() => {
+ protocol.uninterceptProtocol('file');
+ });
+ protocol.registerStringProtocol('electron-test', (req, cb) => { cb('hello ' + req.url); });
+ defer(() => {
+ protocol.unregisterProtocol('electron-test');
+ });
+ const body = await net.fetch('file://foo').then(r => r.text());
+ expect(body).to.equal('hello electron-test://bar');
+ });
+
+ it('should not follow redirect when redirect: error', async () => {
+ protocol.registerStringProtocol('electron-test', (req, cb) => {
+ if (/redirect/.test(req.url)) return cb({ statusCode: 302, headers: { location: 'electron-test://bar' } });
+ cb('hello ' + req.url);
+ });
+ defer(() => {
+ protocol.unregisterProtocol('electron-test');
+ });
+ await expect(net.fetch('electron-test://redirect', { redirect: 'error' })).to.eventually.be.rejectedWith('Attempted to redirect, but redirect policy was \'error\'');
+ });
+
+ it('a 307 redirected POST request preserves the body', async () => {
+ const bodyData = 'Hello World!';
+ let postedBodyData: any;
+ protocol.registerStringProtocol('electron-test', async (req, cb) => {
+ if (/redirect/.test(req.url)) return cb({ statusCode: 307, headers: { location: 'electron-test://bar' } });
+ postedBodyData = req.uploadData![0].bytes.toString();
+ cb('hello ' + req.url);
+ });
+ defer(() => {
+ protocol.unregisterProtocol('electron-test');
+ });
+ const response = await net.fetch('electron-test://redirect', {
+ method: 'POST',
+ body: bodyData
+ });
+ expect(response.status).to.equal(200);
+ await response.text();
+ expect(postedBodyData).to.equal(bodyData);
+ });
+});
diff --git a/spec/api-net-session-spec.ts b/spec/api-net-session-spec.ts
new file mode 100644
index 0000000000..6067d6634f
--- /dev/null
+++ b/spec/api-net-session-spec.ts
@@ -0,0 +1,642 @@
+import { expect } from 'chai';
+import * as dns from 'node:dns';
+import { net, session, BrowserWindow, ClientRequestConstructorOptions } from 'electron/main';
+import { collectStreamBody, getResponse, respondNTimes, respondOnce } from './lib/net-helpers';
+
+// See https://github.com/nodejs/node/issues/40702.
+dns.setDefaultResultOrder('ipv4first');
+
+describe('net module (session)', () => {
+ beforeEach(() => {
+ respondNTimes.routeFailure = false;
+ });
+ afterEach(async function () {
+ await session.defaultSession.clearCache();
+ if (respondNTimes.routeFailure && this.test) {
+ if (!this.test.isFailed()) {
+ throw new Error('Failing this test due an unhandled error in the respondOnce route handler, check the logs above for the actual error');
+ }
+ }
+ });
+
+ describe('HTTP basics', () => {
+ for (const extraOptions of [{}, { credentials: 'include' }, { useSessionCookies: false, credentials: 'include' }] as ClientRequestConstructorOptions[]) {
+ describe(`authentication when ${JSON.stringify(extraOptions)}`, () => {
+ it('should share credentials with WebContents', async () => {
+ const [user, pass] = ['user', 'pass'];
+ const serverUrl = await respondNTimes.toSingleURL((request, response) => {
+ if (!request.headers.authorization) {
+ return response.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' }).end();
+ }
+ return response.writeHead(200).end('ok');
+ }, 2);
+ const bw = new BrowserWindow({ show: false });
+ bw.webContents.on('login', (event, details, authInfo, cb) => {
+ event.preventDefault();
+ cb(user, pass);
+ });
+ await bw.loadURL(serverUrl);
+ bw.close();
+ const request = net.request({ method: 'GET', url: serverUrl, ...extraOptions });
+ let logInCount = 0;
+ request.on('login', () => {
+ logInCount++;
+ });
+ const response = await getResponse(request);
+ await collectStreamBody(response);
+ expect(logInCount).to.equal(0, 'should not receive a login event, credentials should be cached');
+ });
+
+ it('should share proxy credentials with WebContents', async () => {
+ const [user, pass] = ['user', 'pass'];
+ const proxyUrl = await respondNTimes((request, response) => {
+ if (!request.headers['proxy-authorization']) {
+ return response.writeHead(407, { 'Proxy-Authenticate': 'Basic realm="Foo"' }).end();
+ }
+ return response.writeHead(200).end('ok');
+ }, 2);
+ const customSession = session.fromPartition(`net-proxy-test-${Math.random()}`);
+ await customSession.setProxy({ proxyRules: proxyUrl.replace('http://', ''), proxyBypassRules: '<-loopback>' });
+ const bw = new BrowserWindow({ show: false, webPreferences: { session: customSession } });
+ bw.webContents.on('login', (event, details, authInfo, cb) => {
+ event.preventDefault();
+ cb(user, pass);
+ });
+ await bw.loadURL('http://127.0.0.1:9999');
+ bw.close();
+ const request = net.request({ method: 'GET', url: 'http://127.0.0.1:9999', session: customSession, ...extraOptions });
+ let logInCount = 0;
+ request.on('login', () => {
+ logInCount++;
+ });
+ const response = await getResponse(request);
+ const body = await collectStreamBody(response);
+ expect(response.statusCode).to.equal(200);
+ expect(body).to.equal('ok');
+ expect(logInCount).to.equal(0, 'should not receive a login event, credentials should be cached');
+ });
+ });
+ }
+
+ describe('authentication when {"credentials":"omit"}', () => {
+ it('should not share credentials with WebContents', async () => {
+ const [user, pass] = ['user', 'pass'];
+ const serverUrl = await respondNTimes.toSingleURL((request, response) => {
+ if (!request.headers.authorization) {
+ return response.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' }).end();
+ }
+ return response.writeHead(200).end('ok');
+ }, 2);
+ const bw = new BrowserWindow({ show: false });
+ bw.webContents.on('login', (event, details, authInfo, cb) => {
+ event.preventDefault();
+ cb(user, pass);
+ });
+ await bw.loadURL(serverUrl);
+ bw.close();
+ const request = net.request({ method: 'GET', url: serverUrl, credentials: 'omit' });
+ request.on('login', () => {
+ expect.fail();
+ });
+ const response = await getResponse(request);
+ expect(response.statusCode).to.equal(401);
+ expect(response.headers['www-authenticate']).to.equal('Basic realm="Foo"');
+ });
+
+ it('should share proxy credentials with WebContents', async () => {
+ const [user, pass] = ['user', 'pass'];
+ const proxyUrl = await respondNTimes((request, response) => {
+ if (!request.headers['proxy-authorization']) {
+ return response.writeHead(407, { 'Proxy-Authenticate': 'Basic realm="Foo"' }).end();
+ }
+ return response.writeHead(200).end('ok');
+ }, 2);
+ const customSession = session.fromPartition(`net-proxy-test-${Math.random()}`);
+ await customSession.setProxy({ proxyRules: proxyUrl.replace('http://', ''), proxyBypassRules: '<-loopback>' });
+ const bw = new BrowserWindow({ show: false, webPreferences: { session: customSession } });
+ bw.webContents.on('login', (event, details, authInfo, cb) => {
+ event.preventDefault();
+ cb(user, pass);
+ });
+ await bw.loadURL('http://127.0.0.1:9999');
+ bw.close();
+ const request = net.request({ method: 'GET', url: 'http://127.0.0.1:9999', session: customSession, credentials: 'omit' });
+ request.on('login', () => {
+ expect.fail();
+ });
+ const response = await getResponse(request);
+ const body = await collectStreamBody(response);
+ expect(response.statusCode).to.equal(200);
+ expect(body).to.equal('ok');
+ });
+ });
+ });
+
+ describe('ClientRequest API', () => {
+ it('should be able to set cookie header line', async () => {
+ const cookieHeaderName = 'Cookie';
+ const cookieHeaderValue = 'test=12345';
+ const customSession = session.fromPartition(`test-cookie-header-${Math.random()}`);
+ const serverUrl = await respondOnce.toSingleURL((request, response) => {
+ expect(request.headers[cookieHeaderName.toLowerCase()]).to.equal(cookieHeaderValue);
+ response.statusCode = 200;
+ response.statusMessage = 'OK';
+ response.end();
+ });
+ await customSession.cookies.set({
+ url: `${serverUrl}`,
+ name: 'test',
+ value: '11111',
+ expirationDate: 0
+ });
+ const urlRequest = net.request({
+ method: 'GET',
+ url: serverUrl,
+ session: customSession
+ });
+ urlRequest.setHeader(cookieHeaderName, cookieHeaderValue);
+ expect(urlRequest.getHeader(cookieHeaderName)).to.equal(cookieHeaderValue);
+ const response = await getResponse(urlRequest);
+ expect(response.statusCode).to.equal(200);
+ await collectStreamBody(response);
+ });
+
+ it('should not use the sessions cookie store by default', async () => {
+ const serverUrl = await respondOnce.toSingleURL((request, response) => {
+ response.statusCode = 200;
+ response.statusMessage = 'OK';
+ response.setHeader('x-cookie', `${request.headers.cookie!}`);
+ response.end();
+ });
+ const sess = session.fromPartition(`cookie-tests-${Math.random()}`);
+ const cookieVal = `${Date.now()}`;
+ await sess.cookies.set({
+ url: serverUrl,
+ name: 'wild_cookie',
+ value: cookieVal
+ });
+ const urlRequest = net.request({
+ url: serverUrl,
+ session: sess
+ });
+ const response = await getResponse(urlRequest);
+ expect(response.headers['x-cookie']).to.equal('undefined');
+ });
+
+ for (const extraOptions of [{ useSessionCookies: true }, { credentials: 'include' }] as ClientRequestConstructorOptions[]) {
+ describe(`when ${JSON.stringify(extraOptions)}`, () => {
+ it('should be able to use the sessions cookie store', async () => {
+ const serverUrl = await respondOnce.toSingleURL((request, response) => {
+ response.statusCode = 200;
+ response.statusMessage = 'OK';
+ response.setHeader('x-cookie', request.headers.cookie!);
+ response.end();
+ });
+ const sess = session.fromPartition(`cookie-tests-${Math.random()}`);
+ const cookieVal = `${Date.now()}`;
+ await sess.cookies.set({
+ url: serverUrl,
+ name: 'wild_cookie',
+ value: cookieVal
+ });
+ const urlRequest = net.request({
+ url: serverUrl,
+ session: sess,
+ ...extraOptions
+ });
+ const response = await getResponse(urlRequest);
+ expect(response.headers['x-cookie']).to.equal(`wild_cookie=${cookieVal}`);
+ });
+
+ it('should be able to use the sessions cookie store with set-cookie', async () => {
+ const serverUrl = await respondOnce.toSingleURL((request, response) => {
+ response.statusCode = 200;
+ response.statusMessage = 'OK';
+ response.setHeader('set-cookie', 'foo=bar');
+ response.end();
+ });
+ const sess = session.fromPartition(`cookie-tests-${Math.random()}`);
+ let cookies = await sess.cookies.get({});
+ expect(cookies).to.have.lengthOf(0);
+ const urlRequest = net.request({
+ url: serverUrl,
+ session: sess,
+ ...extraOptions
+ });
+ await collectStreamBody(await getResponse(urlRequest));
+ cookies = await sess.cookies.get({});
+ expect(cookies).to.have.lengthOf(1);
+ expect(cookies[0]).to.deep.equal({
+ name: 'foo',
+ value: 'bar',
+ domain: '127.0.0.1',
+ hostOnly: true,
+ path: '/',
+ secure: false,
+ httpOnly: false,
+ session: true,
+ sameSite: 'unspecified'
+ });
+ });
+
+ for (const mode of ['Lax', 'Strict']) {
+ it(`should be able to use the sessions cookie store with same-site ${mode} cookies`, async () => {
+ const serverUrl = await respondNTimes.toSingleURL((request, response) => {
+ response.statusCode = 200;
+ response.statusMessage = 'OK';
+ response.setHeader('set-cookie', `same=site; SameSite=${mode}`);
+ response.setHeader('x-cookie', `${request.headers.cookie}`);
+ response.end();
+ }, 2);
+ const sess = session.fromPartition(`cookie-tests-${Math.random()}`);
+ let cookies = await sess.cookies.get({});
+ expect(cookies).to.have.lengthOf(0);
+ const urlRequest = net.request({
+ url: serverUrl,
+ session: sess,
+ ...extraOptions
+ });
+ const response = await getResponse(urlRequest);
+ expect(response.headers['x-cookie']).to.equal('undefined');
+ await collectStreamBody(response);
+ cookies = await sess.cookies.get({});
+ expect(cookies).to.have.lengthOf(1);
+ expect(cookies[0]).to.deep.equal({
+ name: 'same',
+ value: 'site',
+ domain: '127.0.0.1',
+ hostOnly: true,
+ path: '/',
+ secure: false,
+ httpOnly: false,
+ session: true,
+ sameSite: mode.toLowerCase()
+ });
+ const urlRequest2 = net.request({
+ url: serverUrl,
+ session: sess,
+ ...extraOptions
+ });
+ const response2 = await getResponse(urlRequest2);
+ expect(response2.headers['x-cookie']).to.equal('same=site');
+ });
+ }
+
+ it('should be able to use the sessions cookie store safely across redirects', async () => {
+ const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
+ response.statusCode = 302;
+ response.statusMessage = 'Moved';
+ const newUrl = await respondOnce.toSingleURL((req, res) => {
+ res.statusCode = 200;
+ res.statusMessage = 'OK';
+ res.setHeader('x-cookie', req.headers.cookie!);
+ res.end();
+ });
+ response.setHeader('x-cookie', request.headers.cookie!);
+ response.setHeader('location', newUrl.replace('127.0.0.1', 'localhost'));
+ response.end();
+ });
+ const sess = session.fromPartition(`cookie-tests-${Math.random()}`);
+ const cookie127Val = `${Date.now()}-127`;
+ const cookieLocalVal = `${Date.now()}-local`;
+ const localhostUrl = serverUrl.replace('127.0.0.1', 'localhost');
+ expect(localhostUrl).to.not.equal(serverUrl);
+ // cookies with lax or strict same-site settings will not
+ // persist after redirects. no_restriction must be used
+ await Promise.all([
+ sess.cookies.set({
+ url: serverUrl,
+ name: 'wild_cookie',
+ sameSite: 'no_restriction',
+ value: cookie127Val
+ }), sess.cookies.set({
+ url: localhostUrl,
+ name: 'wild_cookie',
+ sameSite: 'no_restriction',
+ value: cookieLocalVal
+ })
+ ]);
+ const urlRequest = net.request({
+ url: serverUrl,
+ session: sess,
+ ...extraOptions
+ });
+ urlRequest.on('redirect', (status, method, url, headers) => {
+ // The initial redirect response should have received the 127 value here
+ expect(headers['x-cookie'][0]).to.equal(`wild_cookie=${cookie127Val}`);
+ urlRequest.followRedirect();
+ });
+ const response = await getResponse(urlRequest);
+ // We expect the server to have received the localhost value here
+ // The original request was to a 127.0.0.1 URL
+ // That request would have the cookie127Val cookie attached
+ // The request is then redirect to a localhost URL (different site)
+ // Because we are using the session cookie store it should do the safe / secure thing
+ // and attach the cookies for the new target domain
+ expect(response.headers['x-cookie']).to.equal(`wild_cookie=${cookieLocalVal}`);
+ });
+ });
+ }
+
+ it('should be able correctly filter out cookies that are secure', async () => {
+ const sess = session.fromPartition(`cookie-tests-${Math.random()}`);
+
+ await Promise.all([
+ sess.cookies.set({
+ url: 'https://electronjs.org',
+ domain: 'electronjs.org',
+ name: 'cookie1',
+ value: '1',
+ secure: true
+ }),
+ sess.cookies.set({
+ url: 'https://electronjs.org',
+ domain: 'electronjs.org',
+ name: 'cookie2',
+ value: '2',
+ secure: false
+ })
+ ]);
+
+ const secureCookies = await sess.cookies.get({
+ secure: true
+ });
+ expect(secureCookies).to.have.lengthOf(1);
+ expect(secureCookies[0].name).to.equal('cookie1');
+
+ const cookies = await sess.cookies.get({
+ secure: false
+ });
+ expect(cookies).to.have.lengthOf(1);
+ expect(cookies[0].name).to.equal('cookie2');
+ });
+
+ it('throws when an invalid domain is passed', async () => {
+ const sess = session.fromPartition(`cookie-tests-${Math.random()}`);
+
+ await expect(sess.cookies.set({
+ url: 'https://electronjs.org',
+ domain: 'wssss.iamabaddomain.fun',
+ name: 'cookie1'
+ })).to.eventually.be.rejectedWith(/Failed to set cookie with an invalid domain attribute/);
+ });
+
+ it('should be able correctly filter out cookies that are session', async () => {
+ const sess = session.fromPartition(`cookie-tests-${Math.random()}`);
+
+ await Promise.all([
+ sess.cookies.set({
+ url: 'https://electronjs.org',
+ domain: 'electronjs.org',
+ name: 'cookie1',
+ value: '1'
+ }),
+ sess.cookies.set({
+ url: 'https://electronjs.org',
+ domain: 'electronjs.org',
+ name: 'cookie2',
+ value: '2',
+ expirationDate: Math.round(Date.now() / 1000) + 10000
+ })
+ ]);
+
+ const sessionCookies = await sess.cookies.get({
+ session: true
+ });
+ expect(sessionCookies).to.have.lengthOf(1);
+ expect(sessionCookies[0].name).to.equal('cookie1');
+
+ const cookies = await sess.cookies.get({
+ session: false
+ });
+ expect(cookies).to.have.lengthOf(1);
+ expect(cookies[0].name).to.equal('cookie2');
+ });
+
+ it('should be able correctly filter out cookies that are httpOnly', async () => {
+ const sess = session.fromPartition(`cookie-tests-${Math.random()}`);
+
+ await Promise.all([
+ sess.cookies.set({
+ url: 'https://electronjs.org',
+ domain: 'electronjs.org',
+ name: 'cookie1',
+ value: '1',
+ httpOnly: true
+ }),
+ sess.cookies.set({
+ url: 'https://electronjs.org',
+ domain: 'electronjs.org',
+ name: 'cookie2',
+ value: '2',
+ httpOnly: false
+ })
+ ]);
+
+ const httpOnlyCookies = await sess.cookies.get({
+ httpOnly: true
+ });
+ expect(httpOnlyCookies).to.have.lengthOf(1);
+ expect(httpOnlyCookies[0].name).to.equal('cookie1');
+
+ const cookies = await sess.cookies.get({
+ httpOnly: false
+ });
+ expect(cookies).to.have.lengthOf(1);
+ expect(cookies[0].name).to.equal('cookie2');
+ });
+
+ describe('webRequest', () => {
+ afterEach(() => {
+ session.defaultSession.webRequest.onBeforeRequest(null);
+ });
+
+ it('Should throw when invalid filters are passed', () => {
+ expect(() => {
+ session.defaultSession.webRequest.onBeforeRequest(
+ { urls: ['*://www.googleapis.com'] },
+ (details, callback) => { callback({ cancel: false }); }
+ );
+ }).to.throw('Invalid url pattern *://www.googleapis.com: Empty path.');
+
+ expect(() => {
+ session.defaultSession.webRequest.onBeforeRequest(
+ { urls: ['*://www.googleapis.com/', '*://blahblah.dev'] },
+ (details, callback) => { callback({ cancel: false }); }
+ );
+ }).to.throw('Invalid url pattern *://blahblah.dev: Empty path.');
+ });
+
+ it('Should not throw when valid filters are passed', () => {
+ expect(() => {
+ session.defaultSession.webRequest.onBeforeRequest(
+ { urls: ['*://www.googleapis.com/'] },
+ (details, callback) => { callback({ cancel: false }); }
+ );
+ }).to.not.throw();
+ });
+
+ it('Requests should be intercepted by webRequest module', async () => {
+ const requestUrl = '/requestUrl';
+ const redirectUrl = '/redirectUrl';
+ let requestIsRedirected = false;
+ const serverUrl = await respondOnce.toURL(redirectUrl, (request, response) => {
+ requestIsRedirected = true;
+ response.end();
+ });
+ let requestIsIntercepted = false;
+ session.defaultSession.webRequest.onBeforeRequest(
+ (details, callback) => {
+ if (details.url === `${serverUrl}${requestUrl}`) {
+ requestIsIntercepted = true;
+ callback({
+ redirectURL: `${serverUrl}${redirectUrl}`
+ });
+ } else {
+ callback({
+ cancel: false
+ });
+ }
+ });
+
+ const urlRequest = net.request(`${serverUrl}${requestUrl}`);
+ const response = await getResponse(urlRequest);
+
+ expect(response.statusCode).to.equal(200);
+ await collectStreamBody(response);
+ expect(requestIsRedirected).to.be.true('The server should receive a request to the forward URL');
+ expect(requestIsIntercepted).to.be.true('The request should be intercepted by the webRequest module');
+ });
+
+ it('should to able to create and intercept a request using a custom session object', async () => {
+ const requestUrl = '/requestUrl';
+ const redirectUrl = '/redirectUrl';
+ const customPartitionName = `custom-partition-${Math.random()}`;
+ let requestIsRedirected = false;
+ const serverUrl = await respondOnce.toURL(redirectUrl, (request, response) => {
+ requestIsRedirected = true;
+ response.end();
+ });
+ session.defaultSession.webRequest.onBeforeRequest(() => {
+ expect.fail('Request should not be intercepted by the default session');
+ });
+
+ const customSession = session.fromPartition(customPartitionName, { cache: false });
+ let requestIsIntercepted = false;
+ customSession.webRequest.onBeforeRequest((details, callback) => {
+ if (details.url === `${serverUrl}${requestUrl}`) {
+ requestIsIntercepted = true;
+ callback({
+ redirectURL: `${serverUrl}${redirectUrl}`
+ });
+ } else {
+ callback({
+ cancel: false
+ });
+ }
+ });
+
+ const urlRequest = net.request({
+ url: `${serverUrl}${requestUrl}`,
+ session: customSession
+ });
+ const response = await getResponse(urlRequest);
+ expect(response.statusCode).to.equal(200);
+ await collectStreamBody(response);
+ expect(requestIsRedirected).to.be.true('The server should receive a request to the forward URL');
+ expect(requestIsIntercepted).to.be.true('The request should be intercepted by the webRequest module');
+ });
+
+ it('should to able to create and intercept a request using a custom partition name', async () => {
+ const requestUrl = '/requestUrl';
+ const redirectUrl = '/redirectUrl';
+ const customPartitionName = `custom-partition-${Math.random()}`;
+ let requestIsRedirected = false;
+ const serverUrl = await respondOnce.toURL(redirectUrl, (request, response) => {
+ requestIsRedirected = true;
+ response.end();
+ });
+ session.defaultSession.webRequest.onBeforeRequest(() => {
+ expect.fail('Request should not be intercepted by the default session');
+ });
+
+ const customSession = session.fromPartition(customPartitionName, { cache: false });
+ let requestIsIntercepted = false;
+ customSession.webRequest.onBeforeRequest((details, callback) => {
+ if (details.url === `${serverUrl}${requestUrl}`) {
+ requestIsIntercepted = true;
+ callback({
+ redirectURL: `${serverUrl}${redirectUrl}`
+ });
+ } else {
+ callback({
+ cancel: false
+ });
+ }
+ });
+
+ const urlRequest = net.request({
+ url: `${serverUrl}${requestUrl}`,
+ partition: customPartitionName
+ });
+ const response = await getResponse(urlRequest);
+ expect(response.statusCode).to.equal(200);
+ await collectStreamBody(response);
+ expect(requestIsRedirected).to.be.true('The server should receive a request to the forward URL');
+ expect(requestIsIntercepted).to.be.true('The request should be intercepted by the webRequest module');
+ });
+
+ it('triggers webRequest handlers when bypassCustomProtocolHandlers', async () => {
+ let webRequestDetails: Electron.OnBeforeRequestListenerDetails | null = null;
+ const serverUrl = await respondOnce.toSingleURL((req, res) => res.end('hi'));
+ session.defaultSession.webRequest.onBeforeRequest((details, cb) => {
+ webRequestDetails = details;
+ cb({});
+ });
+ const body = await net.fetch(serverUrl, { bypassCustomProtocolHandlers: true }).then(r => r.text());
+ expect(body).to.equal('hi');
+ expect(webRequestDetails).to.have.property('url', serverUrl);
+ });
+ });
+
+ it('should throw if given an invalid session option', () => {
+ expect(() => {
+ net.request({
+ url: 'https://foo',
+ session: 1 as any
+ });
+ }).to.throw('`session` should be an instance of the Session class');
+ });
+
+ it('should throw if given an invalid partition option', () => {
+ expect(() => {
+ net.request({
+ url: 'https://foo',
+ partition: 1 as any
+ });
+ }).to.throw('`partition` should be a string');
+ });
+ });
+
+ describe('net.fetch', () => {
+ it('should be able to use a session cookie store', async () => {
+ const serverUrl = await respondOnce.toSingleURL((request, response) => {
+ response.statusCode = 200;
+ response.statusMessage = 'OK';
+ response.setHeader('x-cookie', request.headers.cookie!);
+ response.end();
+ });
+ const sess = session.fromPartition(`cookie-tests-${Math.random()}`);
+ const cookieVal = `${Date.now()}`;
+ await sess.cookies.set({
+ url: serverUrl,
+ name: 'wild_cookie',
+ value: cookieVal
+ });
+ const response = await sess.fetch(serverUrl, {
+ credentials: 'include'
+ });
+ expect(response.headers.get('x-cookie')).to.equal(`wild_cookie=${cookieVal}`);
+ });
+ });
+});
diff --git a/spec/api-net-spec.ts b/spec/api-net-spec.ts
index 882957db7f..1a92186742 100644
--- a/spec/api-net-spec.ts
+++ b/spec/api-net-spec.ts
@@ -1,1076 +1,495 @@
import { expect } from 'chai';
-import * as dns from 'node:dns';
-import { net, session, ClientRequest, BrowserWindow, ClientRequestConstructorOptions, protocol } from 'electron/main';
+import { net, ClientRequest, ClientRequestConstructorOptions, utilityProcess } from 'electron/main';
import * as http from 'node:http';
-import * as url from 'node:url';
import * as path from 'node:path';
-import { Socket } from 'node:net';
-import { defer, listen } from './lib/spec-helpers';
+import * as url from 'node:url';
import { once } from 'node:events';
import { setTimeout } from 'node:timers/promises';
+import { collectStreamBody, collectStreamBodyBuffer, getResponse, kOneKiloByte, kOneMegaByte, randomBuffer, randomString, respondNTimes, respondOnce } from './lib/net-helpers';
-// See https://github.com/nodejs/node/issues/40702.
-dns.setDefaultResultOrder('ipv4first');
-
-const kOneKiloByte = 1024;
-const kOneMegaByte = kOneKiloByte * kOneKiloByte;
-
-function randomBuffer (size: number, start: number = 0, end: number = 255) {
- const range = 1 + end - start;
- const buffer = Buffer.allocUnsafe(size);
- for (let i = 0; i < size; ++i) {
- buffer[i] = start + Math.floor(Math.random() * range);
- }
- return buffer;
-}
-
-function randomString (length: number) {
- const buffer = randomBuffer(length, '0'.charCodeAt(0), 'z'.charCodeAt(0));
- return buffer.toString();
-}
+const utilityFixturePath = path.resolve(__dirname, 'fixtures', 'api', 'utility-process', 'api-net-spec.js');
-async function getResponse (urlRequest: Electron.ClientRequest) {
- return new Promise<Electron.IncomingMessage>((resolve, reject) => {
- urlRequest.on('error', reject);
- urlRequest.on('abort', reject);
- urlRequest.on('response', (response) => resolve(response));
- urlRequest.end();
- });
-}
-
-async function collectStreamBody (response: Electron.IncomingMessage | http.IncomingMessage) {
- return (await collectStreamBodyBuffer(response)).toString();
-}
-
-function collectStreamBodyBuffer (response: Electron.IncomingMessage | http.IncomingMessage) {
- return new Promise<Buffer>((resolve, reject) => {
- response.on('error', reject);
- (response as NodeJS.EventEmitter).on('aborted', reject);
- const data: Buffer[] = [];
- response.on('data', (chunk) => data.push(chunk));
- response.on('end', (chunk?: Buffer) => {
- if (chunk) data.push(chunk);
- resolve(Buffer.concat(data));
+async function itUtility (name: string, fn?: Function, args?: {[key:string]: any}) {
+ it(`${name} in utility process`, async () => {
+ const child = utilityProcess.fork(utilityFixturePath, [], {
+ execArgv: ['--expose-gc']
});
- });
-}
-
-async function respondNTimes (fn: http.RequestListener, n: number): Promise<string> {
- const server = http.createServer((request, response) => {
- fn(request, response);
- // don't close if a redirect was returned
- if ((response.statusCode < 300 || response.statusCode >= 399) && n <= 0) {
- n--;
- server.close();
- }
- });
- const sockets: Socket[] = [];
- server.on('connection', s => sockets.push(s));
- defer(() => {
- server.close();
- for (const socket of sockets) {
- socket.destroy();
+ if (fn) {
+ child.postMessage({ fn: `(${fn})()`, args });
+ } else {
+ child.postMessage({ fn: '(() => {})()', args });
}
+ const [data] = await once(child, 'message');
+ expect(data.ok).to.be.true(data.message);
+ // Cleanup.
+ const [code] = await once(child, 'exit');
+ expect(code).to.equal(0);
});
- return (await listen(server)).url;
}
-function respondOnce (fn: http.RequestListener) {
- return respondNTimes(fn, 1);
+// eslint-disable-next-line @typescript-eslint/no-unused-vars
+async function itIgnoringArgs (name: string, fn?: Mocha.Func|Mocha.AsyncFunc, args?: {[key:string]: any}) {
+ it(name, fn);
}
-let routeFailure = false;
-
-respondNTimes.toRoutes = (routes: Record<string, http.RequestListener>, n: number) => {
- return respondNTimes((request, response) => {
- if (Object.hasOwn(routes, request.url || '')) {
- (async () => {
- await Promise.resolve(routes[request.url || ''](request, response));
- })().catch((err) => {
- routeFailure = true;
- console.error('Route handler failed, this is probably why your test failed', err);
- response.statusCode = 500;
- response.end();
- });
- } else {
- response.statusCode = 500;
- response.end();
- expect.fail(`Unexpected URL: ${request.url}`);
- }
- }, n);
-};
-respondOnce.toRoutes = (routes: Record<string, http.RequestListener>) => respondNTimes.toRoutes(routes, 1);
-
-respondNTimes.toURL = (url: string, fn: http.RequestListener, n: number) => {
- return respondNTimes.toRoutes({ [url]: fn }, n);
-};
-respondOnce.toURL = (url: string, fn: http.RequestListener) => respondNTimes.toURL(url, fn, 1);
-
-respondNTimes.toSingleURL = (fn: http.RequestListener, n: number) => {
- const requestUrl = '/requestUrl';
- return respondNTimes.toURL(requestUrl, fn, n).then(url => `${url}${requestUrl}`);
-};
-respondOnce.toSingleURL = (fn: http.RequestListener) => respondNTimes.toSingleURL(fn, 1);
-
describe('net module', () => {
beforeEach(() => {
- routeFailure = false;
+ respondNTimes.routeFailure = false;
});
afterEach(async function () {
- await session.defaultSession.clearCache();
- if (routeFailure && this.test) {
+ if (respondNTimes.routeFailure && this.test) {
if (!this.test.isFailed()) {
throw new Error('Failing this test due an unhandled error in the respondOnce route handler, check the logs above for the actual error');
}
}
});
- describe('HTTP basics', () => {
- it('should be able to issue a basic GET request', async () => {
- const serverUrl = await respondOnce.toSingleURL((request, response) => {
- expect(request.method).to.equal('GET');
- response.end();
+ for (const test of [itIgnoringArgs, itUtility]) {
+ describe('HTTP basics', () => {
+ test('should be able to issue a basic GET request', async () => {
+ const serverUrl = await respondOnce.toSingleURL((request, response) => {
+ expect(request.method).to.equal('GET');
+ response.end();
+ });
+ const urlRequest = net.request(serverUrl);
+ const response = await getResponse(urlRequest);
+ expect(response.statusCode).to.equal(200);
+ await collectStreamBody(response);
});
- const urlRequest = net.request(serverUrl);
- const response = await getResponse(urlRequest);
- expect(response.statusCode).to.equal(200);
- await collectStreamBody(response);
- });
- it('should be able to issue a basic POST request', async () => {
- const serverUrl = await respondOnce.toSingleURL((request, response) => {
- expect(request.method).to.equal('POST');
- response.end();
- });
- const urlRequest = net.request({
- method: 'POST',
- url: serverUrl
+ test('should be able to issue a basic POST request', async () => {
+ const serverUrl = await respondOnce.toSingleURL((request, response) => {
+ expect(request.method).to.equal('POST');
+ response.end();
+ });
+ const urlRequest = net.request({
+ method: 'POST',
+ url: serverUrl
+ });
+ const response = await getResponse(urlRequest);
+ expect(response.statusCode).to.equal(200);
+ await collectStreamBody(response);
});
- const response = await getResponse(urlRequest);
- expect(response.statusCode).to.equal(200);
- await collectStreamBody(response);
- });
- it('should fetch correct data in a GET request', async () => {
- const expectedBodyData = 'Hello World!';
- const serverUrl = await respondOnce.toSingleURL((request, response) => {
- expect(request.method).to.equal('GET');
- response.end(expectedBodyData);
- });
- const urlRequest = net.request(serverUrl);
- const response = await getResponse(urlRequest);
- expect(response.statusCode).to.equal(200);
- const body = await collectStreamBody(response);
- expect(body).to.equal(expectedBodyData);
- });
-
- it('should post the correct data in a POST request', async () => {
- const bodyData = 'Hello World!';
- let postedBodyData: string = '';
- const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
- postedBodyData = await collectStreamBody(request);
- response.end();
- });
- const urlRequest = net.request({
- method: 'POST',
- url: serverUrl
- });
- urlRequest.write(bodyData);
- const response = await getResponse(urlRequest);
- expect(response.statusCode).to.equal(200);
- expect(postedBodyData).to.equal(bodyData);
- });
-
- it('a 307 redirected POST request preserves the body', async () => {
- const bodyData = 'Hello World!';
- let postedBodyData: string = '';
- let methodAfterRedirect: string | undefined;
- const serverUrl = await respondNTimes.toRoutes({
- '/redirect': (req, res) => {
- res.statusCode = 307;
- res.setHeader('location', serverUrl);
- return res.end();
- },
- '/': async (req, res) => {
- methodAfterRedirect = req.method;
- postedBodyData = await collectStreamBody(req);
- res.end();
- }
- }, 2);
- const urlRequest = net.request({
- method: 'POST',
- url: serverUrl + '/redirect'
- });
- urlRequest.write(bodyData);
- const response = await getResponse(urlRequest);
- expect(response.statusCode).to.equal(200);
- await collectStreamBody(response);
- expect(methodAfterRedirect).to.equal('POST');
- expect(postedBodyData).to.equal(bodyData);
- });
-
- it('a 302 redirected POST request DOES NOT preserve the body', async () => {
- const bodyData = 'Hello World!';
- let postedBodyData: string = '';
- let methodAfterRedirect: string | undefined;
- const serverUrl = await respondNTimes.toRoutes({
- '/redirect': (req, res) => {
- res.statusCode = 302;
- res.setHeader('location', serverUrl);
- return res.end();
- },
- '/': async (req, res) => {
- methodAfterRedirect = req.method;
- postedBodyData = await collectStreamBody(req);
- res.end();
- }
- }, 2);
- const urlRequest = net.request({
- method: 'POST',
- url: serverUrl + '/redirect'
- });
- urlRequest.write(bodyData);
- const response = await getResponse(urlRequest);
- expect(response.statusCode).to.equal(200);
- await collectStreamBody(response);
- expect(methodAfterRedirect).to.equal('GET');
- expect(postedBodyData).to.equal('');
- });
+ test('should fetch correct data in a GET request', async () => {
+ const expectedBodyData = 'Hello World!';
+ const serverUrl = await respondOnce.toSingleURL((request, response) => {
+ expect(request.method).to.equal('GET');
+ response.end(expectedBodyData);
+ });
+ const urlRequest = net.request(serverUrl);
+ const response = await getResponse(urlRequest);
+ expect(response.statusCode).to.equal(200);
+ const body = await collectStreamBody(response);
+ expect(body).to.equal(expectedBodyData);
+ });
- it('should support chunked encoding', async () => {
- let receivedRequest: http.IncomingMessage = null as any;
- const serverUrl = await respondOnce.toSingleURL((request, response) => {
- response.statusCode = 200;
- response.statusMessage = 'OK';
- response.chunkedEncoding = true;
- receivedRequest = request;
- request.on('data', (chunk: Buffer) => {
- response.write(chunk);
+ test('should post the correct data in a POST request', async () => {
+ const bodyData = 'Hello World!';
+ let postedBodyData: string = '';
+ const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
+ postedBodyData = await collectStreamBody(request);
+ response.end();
});
- request.on('end', (chunk: Buffer) => {
- response.end(chunk);
+ const urlRequest = net.request({
+ method: 'POST',
+ url: serverUrl
});
+ urlRequest.write(bodyData);
+ const response = await getResponse(urlRequest);
+ expect(response.statusCode).to.equal(200);
+ expect(postedBodyData).to.equal(bodyData);
+ });
+
+ test('a 307 redirected POST request preserves the body', async () => {
+ const bodyData = 'Hello World!';
+ let postedBodyData: string = '';
+ let methodAfterRedirect: string | undefined;
+ const serverUrl = await respondNTimes.toRoutes({
+ '/redirect': (req, res) => {
+ res.statusCode = 307;
+ res.setHeader('location', serverUrl);
+ return res.end();
+ },
+ '/': async (req, res) => {
+ methodAfterRedirect = req.method;
+ postedBodyData = await collectStreamBody(req);
+ res.end();
+ }
+ }, 2);
+ const urlRequest = net.request({
+ method: 'POST',
+ url: serverUrl + '/redirect'
+ });
+ urlRequest.write(bodyData);
+ const response = await getResponse(urlRequest);
+ expect(response.statusCode).to.equal(200);
+ await collectStreamBody(response);
+ expect(methodAfterRedirect).to.equal('POST');
+ expect(postedBodyData).to.equal(bodyData);
+ });
+
+ test('a 302 redirected POST request DOES NOT preserve the body', async () => {
+ const bodyData = 'Hello World!';
+ let postedBodyData: string = '';
+ let methodAfterRedirect: string | undefined;
+ const serverUrl = await respondNTimes.toRoutes({
+ '/redirect': (req, res) => {
+ res.statusCode = 302;
+ res.setHeader('location', serverUrl);
+ return res.end();
+ },
+ '/': async (req, res) => {
+ methodAfterRedirect = req.method;
+ postedBodyData = await collectStreamBody(req);
+ res.end();
+ }
+ }, 2);
+ const urlRequest = net.request({
+ method: 'POST',
+ url: serverUrl + '/redirect'
+ });
+ urlRequest.write(bodyData);
+ const response = await getResponse(urlRequest);
+ expect(response.statusCode).to.equal(200);
+ await collectStreamBody(response);
+ expect(methodAfterRedirect).to.equal('GET');
+ expect(postedBodyData).to.equal('');
});
- const urlRequest = net.request({
- method: 'POST',
- url: serverUrl
- });
-
- let chunkIndex = 0;
- const chunkCount = 100;
- let sent = Buffer.alloc(0);
-
- urlRequest.chunkedEncoding = true;
- while (chunkIndex < chunkCount) {
- chunkIndex += 1;
- const chunk = randomBuffer(kOneKiloByte);
- sent = Buffer.concat([sent, chunk]);
- urlRequest.write(chunk);
- }
- const response = await getResponse(urlRequest);
- expect(receivedRequest.method).to.equal('POST');
- expect(receivedRequest.headers['transfer-encoding']).to.equal('chunked');
- expect(receivedRequest.headers['content-length']).to.equal(undefined);
- expect(response.statusCode).to.equal(200);
- const received = await collectStreamBodyBuffer(response);
- expect(sent.equals(received)).to.be.true();
- expect(chunkIndex).to.be.equal(chunkCount);
- });
-
- for (const extraOptions of [{}, { credentials: 'include' }, { useSessionCookies: false, credentials: 'include' }] as ClientRequestConstructorOptions[]) {
- describe(`authentication when ${JSON.stringify(extraOptions)}`, () => {
- it('should emit the login event when 401', async () => {
- const [user, pass] = ['user', 'pass'];
- const serverUrl = await respondOnce.toSingleURL((request, response) => {
- if (!request.headers.authorization) {
- return response.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' }).end();
- }
- response.writeHead(200).end('ok');
+ test('should support chunked encoding', async () => {
+ let receivedRequest: http.IncomingMessage = null as any;
+ const serverUrl = await respondOnce.toSingleURL((request, response) => {
+ response.statusCode = 200;
+ response.statusMessage = 'OK';
+ response.chunkedEncoding = true;
+ receivedRequest = request;
+ request.on('data', (chunk: Buffer) => {
+ response.write(chunk);
});
- let loginAuthInfo: Electron.AuthInfo;
- const request = net.request({ method: 'GET', url: serverUrl, ...extraOptions });
- request.on('login', (authInfo, cb) => {
- loginAuthInfo = authInfo;
- cb(user, pass);
+ request.on('end', (chunk: Buffer) => {
+ response.end(chunk);
});
- const response = await getResponse(request);
- expect(response.statusCode).to.equal(200);
- expect(loginAuthInfo!.realm).to.equal('Foo');
- expect(loginAuthInfo!.scheme).to.equal('basic');
});
-
- it('should receive 401 response when cancelling authentication', async () => {
- const serverUrl = await respondOnce.toSingleURL((request, response) => {
- if (!request.headers.authorization) {
- response.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' });
- response.end('unauthenticated');
- } else {
- response.writeHead(200).end('ok');
- }
- });
- const request = net.request({ method: 'GET', url: serverUrl, ...extraOptions });
- request.on('login', (authInfo, cb) => {
- cb();
- });
- const response = await getResponse(request);
- const body = await collectStreamBody(response);
- expect(response.statusCode).to.equal(401);
- expect(body).to.equal('unauthenticated');
+ const urlRequest = net.request({
+ method: 'POST',
+ url: serverUrl
});
- it('should share credentials with WebContents', async () => {
- const [user, pass] = ['user', 'pass'];
- const serverUrl = await respondNTimes.toSingleURL((request, response) => {
- if (!request.headers.authorization) {
- return response.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' }).end();
- }
- return response.writeHead(200).end('ok');
- }, 2);
- const bw = new BrowserWindow({ show: false });
- bw.webContents.on('login', (event, details, authInfo, cb) => {
- event.preventDefault();
- cb(user, pass);
- });
- await bw.loadURL(serverUrl);
- bw.close();
- const request = net.request({ method: 'GET', url: serverUrl, ...extraOptions });
- let logInCount = 0;
- request.on('login', () => {
- logInCount++;
- });
- const response = await getResponse(request);
- await collectStreamBody(response);
- expect(logInCount).to.equal(0, 'should not receive a login event, credentials should be cached');
- });
+ let chunkIndex = 0;
+ const chunkCount = 100;
+ let sent = Buffer.alloc(0);
- it('should share proxy credentials with WebContents', async () => {
- const [user, pass] = ['user', 'pass'];
- const proxyUrl = await respondNTimes((request, response) => {
- if (!request.headers['proxy-authorization']) {
- return response.writeHead(407, { 'Proxy-Authenticate': 'Basic realm="Foo"' }).end();
- }
- return response.writeHead(200).end('ok');
- }, 2);
- const customSession = session.fromPartition(`net-proxy-test-${Math.random()}`);
- await customSession.setProxy({ proxyRules: proxyUrl.replace('http://', ''), proxyBypassRules: '<-loopback>' });
- const bw = new BrowserWindow({ show: false, webPreferences: { session: customSession } });
- bw.webContents.on('login', (event, details, authInfo, cb) => {
- event.preventDefault();
- cb(user, pass);
- });
- await bw.loadURL('http://127.0.0.1:9999');
- bw.close();
- const request = net.request({ method: 'GET', url: 'http://127.0.0.1:9999', session: customSession, ...extraOptions });
- let logInCount = 0;
- request.on('login', () => {
- logInCount++;
- });
- const response = await getResponse(request);
- const body = await collectStreamBody(response);
- expect(response.statusCode).to.equal(200);
- expect(body).to.equal('ok');
- expect(logInCount).to.equal(0, 'should not receive a login event, credentials should be cached');
+ urlRequest.chunkedEncoding = true;
+ while (chunkIndex < chunkCount) {
+ chunkIndex += 1;
+ const chunk = randomBuffer(kOneKiloByte);
+ sent = Buffer.concat([sent, chunk]);
+ urlRequest.write(chunk);
+ }
+
+ const response = await getResponse(urlRequest);
+ expect(receivedRequest.method).to.equal('POST');
+ expect(receivedRequest.headers['transfer-encoding']).to.equal('chunked');
+ expect(receivedRequest.headers['content-length']).to.equal(undefined);
+ expect(response.statusCode).to.equal(200);
+ const received = await collectStreamBodyBuffer(response);
+ expect(sent.equals(received)).to.be.true();
+ expect(chunkIndex).to.be.equal(chunkCount);
+ });
+
+ for (const extraOptions of [{}, { credentials: 'include' }, { useSessionCookies: false, credentials: 'include' }] as ClientRequestConstructorOptions[]) {
+ describe(`authentication when ${JSON.stringify(extraOptions)}`, () => {
+ test('should emit the login event when 401', async () => {
+ const [user, pass] = ['user', 'pass'];
+ const serverUrl = await respondOnce.toSingleURL((request, response) => {
+ if (!request.headers.authorization) {
+ return response.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' }).end();
+ }
+ response.writeHead(200).end('ok');
+ });
+ let loginAuthInfo: Electron.AuthInfo;
+ const request = net.request({ method: 'GET', url: serverUrl, ...extraOptions });
+ request.on('login', (authInfo, cb) => {
+ loginAuthInfo = authInfo;
+ cb(user, pass);
+ });
+ const response = await getResponse(request);
+ expect(response.statusCode).to.equal(200);
+ expect(loginAuthInfo!.realm).to.equal('Foo');
+ expect(loginAuthInfo!.scheme).to.equal('basic');
+ }, { extraOptions });
+
+ test('should receive 401 response when cancelling authentication', async () => {
+ const serverUrl = await respondOnce.toSingleURL((request, response) => {
+ if (!request.headers.authorization) {
+ response.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' });
+ response.end('unauthenticated');
+ } else {
+ response.writeHead(200).end('ok');
+ }
+ });
+ const request = net.request({ method: 'GET', url: serverUrl, ...extraOptions });
+ request.on('login', (authInfo, cb) => {
+ cb();
+ });
+ const response = await getResponse(request);
+ const body = await collectStreamBody(response);
+ expect(response.statusCode).to.equal(401);
+ expect(body).to.equal('unauthenticated');
+ }, { extraOptions });
+
+ test('should upload body when 401', async () => {
+ const [user, pass] = ['user', 'pass'];
+ const serverUrl = await respondOnce.toSingleURL((request, response) => {
+ if (!request.headers.authorization) {
+ return response.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' }).end();
+ }
+ response.writeHead(200);
+ request.on('data', (chunk) => response.write(chunk));
+ request.on('end', () => response.end());
+ });
+ const requestData = randomString(kOneKiloByte);
+ const request = net.request({ method: 'GET', url: serverUrl, ...extraOptions });
+ request.on('login', (authInfo, cb) => {
+ cb(user, pass);
+ });
+ request.write(requestData);
+ const response = await getResponse(request);
+ const responseData = await collectStreamBody(response);
+ expect(responseData).to.equal(requestData);
+ }, { extraOptions });
});
+ }
- it('should upload body when 401', async () => {
- const [user, pass] = ['user', 'pass'];
+ describe('authentication when {"credentials":"omit"}', () => {
+ test('should not emit the login event when 401', async () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => {
if (!request.headers.authorization) {
return response.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' }).end();
}
- response.writeHead(200);
- request.on('data', (chunk) => response.write(chunk));
- request.on('end', () => response.end());
+ response.writeHead(200).end('ok');
});
- const requestData = randomString(kOneKiloByte);
- const request = net.request({ method: 'GET', url: serverUrl, ...extraOptions });
- request.on('login', (authInfo, cb) => {
- cb(user, pass);
+ const request = net.request({ method: 'GET', url: serverUrl, credentials: 'omit' });
+ request.on('login', () => {
+ expect.fail('unexpected login event');
});
- request.write(requestData);
const response = await getResponse(request);
- const responseData = await collectStreamBody(response);
- expect(responseData).to.equal(requestData);
+ expect(response.statusCode).to.equal(401);
+ expect(response.headers['www-authenticate']).to.equal('Basic realm="Foo"');
});
});
- }
+ });
- describe('authentication when {"credentials":"omit"}', () => {
- it('should not emit the login event when 401', async () => {
+ describe('ClientRequest API', () => {
+ test('request/response objects should emit expected events', async () => {
+ const bodyData = randomString(kOneKiloByte);
const serverUrl = await respondOnce.toSingleURL((request, response) => {
- if (!request.headers.authorization) {
- return response.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' }).end();
- }
- response.writeHead(200).end('ok');
+ response.end(bodyData);
+ });
+
+ const urlRequest = net.request(serverUrl);
+ // request close event
+ const closePromise = once(urlRequest, 'close');
+ // request finish event
+ const finishPromise = once(urlRequest, 'close');
+ // request "response" event
+ const response = await getResponse(urlRequest);
+ response.on('error', (error: Error) => {
+ expect(error).to.be.an('Error');
});
- const request = net.request({ method: 'GET', url: serverUrl, credentials: 'omit' });
- request.on('login', () => {
- expect.fail('unexpected login event');
+ const statusCode = response.statusCode;
+ expect(statusCode).to.equal(200);
+ // response data event
+ // respond end event
+ const body = await collectStreamBody(response);
+ expect(body).to.equal(bodyData);
+ urlRequest.on('error', (error) => {
+ expect(error).to.be.an('Error');
});
- const response = await getResponse(request);
- expect(response.statusCode).to.equal(401);
- expect(response.headers['www-authenticate']).to.equal('Basic realm="Foo"');
+ await Promise.all([closePromise, finishPromise]);
});
- it('should not share credentials with WebContents', async () => {
- const [user, pass] = ['user', 'pass'];
- const serverUrl = await respondNTimes.toSingleURL((request, response) => {
- if (!request.headers.authorization) {
- return response.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' }).end();
- }
- return response.writeHead(200).end('ok');
- }, 2);
- const bw = new BrowserWindow({ show: false });
- bw.webContents.on('login', (event, details, authInfo, cb) => {
- event.preventDefault();
- cb(user, pass);
- });
- await bw.loadURL(serverUrl);
- bw.close();
- const request = net.request({ method: 'GET', url: serverUrl, credentials: 'omit' });
- request.on('login', () => {
- expect.fail();
- });
- const response = await getResponse(request);
- expect(response.statusCode).to.equal(401);
- expect(response.headers['www-authenticate']).to.equal('Basic realm="Foo"');
- });
-
- it('should share proxy credentials with WebContents', async () => {
- const [user, pass] = ['user', 'pass'];
- const proxyUrl = await respondNTimes((request, response) => {
- if (!request.headers['proxy-authorization']) {
- return response.writeHead(407, { 'Proxy-Authenticate': 'Basic realm="Foo"' }).end();
- }
- return response.writeHead(200).end('ok');
- }, 2);
- const customSession = session.fromPartition(`net-proxy-test-${Math.random()}`);
- await customSession.setProxy({ proxyRules: proxyUrl.replace('http://', ''), proxyBypassRules: '<-loopback>' });
- const bw = new BrowserWindow({ show: false, webPreferences: { session: customSession } });
- bw.webContents.on('login', (event, details, authInfo, cb) => {
- event.preventDefault();
- cb(user, pass);
- });
- await bw.loadURL('http://127.0.0.1:9999');
- bw.close();
- const request = net.request({ method: 'GET', url: 'http://127.0.0.1:9999', session: customSession, credentials: 'omit' });
- request.on('login', () => {
- expect.fail();
- });
- const response = await getResponse(request);
- const body = await collectStreamBody(response);
+ test('should be able to set a custom HTTP request header before first write', async () => {
+ const customHeaderName = 'Some-Custom-Header-Name';
+ const customHeaderValue = 'Some-Customer-Header-Value';
+ const serverUrl = await respondOnce.toSingleURL((request, response) => {
+ expect(request.headers[customHeaderName.toLowerCase()]).to.equal(customHeaderValue);
+ response.statusCode = 200;
+ response.statusMessage = 'OK';
+ response.end();
+ });
+ const urlRequest = net.request(serverUrl);
+ urlRequest.setHeader(customHeaderName, customHeaderValue);
+ expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue);
+ expect(urlRequest.getHeader(customHeaderName.toLowerCase())).to.equal(customHeaderValue);
+ urlRequest.write('');
+ expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue);
+ expect(urlRequest.getHeader(customHeaderName.toLowerCase())).to.equal(customHeaderValue);
+ const response = await getResponse(urlRequest);
expect(response.statusCode).to.equal(200);
- expect(body).to.equal('ok');
+ await collectStreamBody(response);
});
- });
- });
-
- describe('ClientRequest API', () => {
- it('request/response objects should emit expected events', async () => {
- const bodyData = randomString(kOneKiloByte);
- const serverUrl = await respondOnce.toSingleURL((request, response) => {
- response.end(bodyData);
- });
-
- const urlRequest = net.request(serverUrl);
- // request close event
- const closePromise = once(urlRequest, 'close');
- // request finish event
- const finishPromise = once(urlRequest, 'close');
- // request "response" event
- const response = await getResponse(urlRequest);
- response.on('error', (error: Error) => {
- expect(error).to.be.an('Error');
- });
- const statusCode = response.statusCode;
- expect(statusCode).to.equal(200);
- // response data event
- // respond end event
- const body = await collectStreamBody(response);
- expect(body).to.equal(bodyData);
- urlRequest.on('error', (error) => {
- expect(error).to.be.an('Error');
- });
- await Promise.all([closePromise, finishPromise]);
- });
- it('should be able to set a custom HTTP request header before first write', async () => {
- const customHeaderName = 'Some-Custom-Header-Name';
- const customHeaderValue = 'Some-Customer-Header-Value';
- const serverUrl = await respondOnce.toSingleURL((request, response) => {
- expect(request.headers[customHeaderName.toLowerCase()]).to.equal(customHeaderValue);
- response.statusCode = 200;
- response.statusMessage = 'OK';
- response.end();
- });
- const urlRequest = net.request(serverUrl);
- urlRequest.setHeader(customHeaderName, customHeaderValue);
- expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue);
- expect(urlRequest.getHeader(customHeaderName.toLowerCase())).to.equal(customHeaderValue);
- urlRequest.write('');
- expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue);
- expect(urlRequest.getHeader(customHeaderName.toLowerCase())).to.equal(customHeaderValue);
- const response = await getResponse(urlRequest);
- expect(response.statusCode).to.equal(200);
- await collectStreamBody(response);
- });
+ test('should be able to set a non-string object as a header value', async () => {
+ const customHeaderName = 'Some-Integer-Value';
+ const customHeaderValue = 900;
+ const serverUrl = await respondOnce.toSingleURL((request, response) => {
+ expect(request.headers[customHeaderName.toLowerCase()]).to.equal(customHeaderValue.toString());
+ response.statusCode = 200;
+ response.statusMessage = 'OK';
+ response.end();
+ });
- it('should be able to set a non-string object as a header value', async () => {
- const customHeaderName = 'Some-Integer-Value';
- const customHeaderValue = 900;
- const serverUrl = await respondOnce.toSingleURL((request, response) => {
- expect(request.headers[customHeaderName.toLowerCase()]).to.equal(customHeaderValue.toString());
- response.statusCode = 200;
- response.statusMessage = 'OK';
- response.end();
- });
-
- const urlRequest = net.request(serverUrl);
- urlRequest.setHeader(customHeaderName, customHeaderValue as any);
- expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue);
- expect(urlRequest.getHeader(customHeaderName.toLowerCase())).to.equal(customHeaderValue);
- urlRequest.write('');
- expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue);
- expect(urlRequest.getHeader(customHeaderName.toLowerCase())).to.equal(customHeaderValue);
- const response = await getResponse(urlRequest);
- expect(response.statusCode).to.equal(200);
- await collectStreamBody(response);
- });
+ const urlRequest = net.request(serverUrl);
+ urlRequest.setHeader(customHeaderName, customHeaderValue as any);
+ expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue);
+ expect(urlRequest.getHeader(customHeaderName.toLowerCase())).to.equal(customHeaderValue);
+ urlRequest.write('');
+ expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue);
+ expect(urlRequest.getHeader(customHeaderName.toLowerCase())).to.equal(customHeaderValue);
+ const response = await getResponse(urlRequest);
+ expect(response.statusCode).to.equal(200);
+ await collectStreamBody(response);
+ });
- it('should not change the case of header name', async () => {
- const customHeaderName = 'X-Header-Name';
- const customHeaderValue = 'value';
- const serverUrl = await respondOnce.toSingleURL((request, response) => {
- expect(request.headers[customHeaderName.toLowerCase()]).to.equal(customHeaderValue.toString());
- expect(request.rawHeaders.includes(customHeaderName)).to.equal(true);
- response.statusCode = 200;
- response.statusMessage = 'OK';
- response.end();
- });
-
- const urlRequest = net.request(serverUrl);
- urlRequest.setHeader(customHeaderName, customHeaderValue);
- expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue);
- urlRequest.write('');
- const response = await getResponse(urlRequest);
- expect(response.statusCode).to.equal(200);
- await collectStreamBody(response);
- });
+ test('should not change the case of header name', async () => {
+ const customHeaderName = 'X-Header-Name';
+ const customHeaderValue = 'value';
+ const serverUrl = await respondOnce.toSingleURL((request, response) => {
+ expect(request.headers[customHeaderName.toLowerCase()]).to.equal(customHeaderValue.toString());
+ expect(request.rawHeaders.includes(customHeaderName)).to.equal(true);
+ response.statusCode = 200;
+ response.statusMessage = 'OK';
+ response.end();
+ });
- it('should not be able to set a custom HTTP request header after first write', async () => {
- const customHeaderName = 'Some-Custom-Header-Name';
- const customHeaderValue = 'Some-Customer-Header-Value';
- const serverUrl = await respondOnce.toSingleURL((request, response) => {
- expect(request.headers[customHeaderName.toLowerCase()]).to.equal(undefined);
- response.statusCode = 200;
- response.statusMessage = 'OK';
- response.end();
- });
- const urlRequest = net.request(serverUrl);
- urlRequest.write('');
- expect(() => {
+ const urlRequest = net.request(serverUrl);
urlRequest.setHeader(customHeaderName, customHeaderValue);
- }).to.throw();
- expect(urlRequest.getHeader(customHeaderName)).to.equal(undefined);
- const response = await getResponse(urlRequest);
- expect(response.statusCode).to.equal(200);
- await collectStreamBody(response);
- });
-
- it('should be able to remove a custom HTTP request header before first write', async () => {
- const customHeaderName = 'Some-Custom-Header-Name';
- const customHeaderValue = 'Some-Customer-Header-Value';
- const serverUrl = await respondOnce.toSingleURL((request, response) => {
- expect(request.headers[customHeaderName.toLowerCase()]).to.equal(undefined);
- response.statusCode = 200;
- response.statusMessage = 'OK';
- response.end();
- });
- const urlRequest = net.request(serverUrl);
- urlRequest.setHeader(customHeaderName, customHeaderValue);
- expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue);
- urlRequest.removeHeader(customHeaderName);
- expect(urlRequest.getHeader(customHeaderName)).to.equal(undefined);
- urlRequest.write('');
- const response = await getResponse(urlRequest);
- expect(response.statusCode).to.equal(200);
- await collectStreamBody(response);
- });
-
- it('should not be able to remove a custom HTTP request header after first write', async () => {
- const customHeaderName = 'Some-Custom-Header-Name';
- const customHeaderValue = 'Some-Customer-Header-Value';
- const serverUrl = await respondOnce.toSingleURL((request, response) => {
- expect(request.headers[customHeaderName.toLowerCase()]).to.equal(customHeaderValue);
- response.statusCode = 200;
- response.statusMessage = 'OK';
- response.end();
- });
- const urlRequest = net.request(serverUrl);
- urlRequest.setHeader(customHeaderName, customHeaderValue);
- expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue);
- urlRequest.write('');
- expect(() => {
- urlRequest.removeHeader(customHeaderName);
- }).to.throw();
- expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue);
- const response = await getResponse(urlRequest);
- expect(response.statusCode).to.equal(200);
- await collectStreamBody(response);
- });
-
- it('should keep the order of headers', async () => {
- const customHeaderNameA = 'X-Header-100';
- const customHeaderNameB = 'X-Header-200';
- const serverUrl = await respondOnce.toSingleURL((request, response) => {
- const headerNames = Array.from(Object.keys(request.headers));
- const headerAIndex = headerNames.indexOf(customHeaderNameA.toLowerCase());
- const headerBIndex = headerNames.indexOf(customHeaderNameB.toLowerCase());
- expect(headerBIndex).to.be.below(headerAIndex);
- response.statusCode = 200;
- response.statusMessage = 'OK';
- response.end();
- });
-
- const urlRequest = net.request(serverUrl);
- urlRequest.setHeader(customHeaderNameB, 'b');
- urlRequest.setHeader(customHeaderNameA, 'a');
- const response = await getResponse(urlRequest);
- expect(response.statusCode).to.equal(200);
- await collectStreamBody(response);
- });
-
- it('should be able to set cookie header line', async () => {
- const cookieHeaderName = 'Cookie';
- const cookieHeaderValue = 'test=12345';
- const customSession = session.fromPartition(`test-cookie-header-${Math.random()}`);
- const serverUrl = await respondOnce.toSingleURL((request, response) => {
- expect(request.headers[cookieHeaderName.toLowerCase()]).to.equal(cookieHeaderValue);
- response.statusCode = 200;
- response.statusMessage = 'OK';
- response.end();
- });
- await customSession.cookies.set({
- url: `${serverUrl}`,
- name: 'test',
- value: '11111',
- expirationDate: 0
- });
- const urlRequest = net.request({
- method: 'GET',
- url: serverUrl,
- session: customSession
- });
- urlRequest.setHeader(cookieHeaderName, cookieHeaderValue);
- expect(urlRequest.getHeader(cookieHeaderName)).to.equal(cookieHeaderValue);
- const response = await getResponse(urlRequest);
- expect(response.statusCode).to.equal(200);
- await collectStreamBody(response);
- });
-
- it('should be able to receive cookies', async () => {
- const cookie = ['cookie1', 'cookie2'];
- const serverUrl = await respondOnce.toSingleURL((request, response) => {
- response.statusCode = 200;
- response.statusMessage = 'OK';
- response.setHeader('set-cookie', cookie);
- response.end();
- });
- const urlRequest = net.request(serverUrl);
- const response = await getResponse(urlRequest);
- expect(response.headers['set-cookie']).to.have.same.members(cookie);
- });
-
- it('should be able to receive content-type', async () => {
- const contentType = 'mime/test; charset=test';
- const serverUrl = await respondOnce.toSingleURL((request, response) => {
- response.statusCode = 200;
- response.statusMessage = 'OK';
- response.setHeader('content-type', contentType);
- response.end();
- });
- const urlRequest = net.request(serverUrl);
- const response = await getResponse(urlRequest);
- expect(response.headers['content-type']).to.equal(contentType);
- });
-
- it('should not use the sessions cookie store by default', async () => {
- const serverUrl = await respondOnce.toSingleURL((request, response) => {
- response.statusCode = 200;
- response.statusMessage = 'OK';
- response.setHeader('x-cookie', `${request.headers.cookie!}`);
- response.end();
- });
- const sess = session.fromPartition(`cookie-tests-${Math.random()}`);
- const cookieVal = `${Date.now()}`;
- await sess.cookies.set({
- url: serverUrl,
- name: 'wild_cookie',
- value: cookieVal
- });
- const urlRequest = net.request({
- url: serverUrl,
- session: sess
- });
- const response = await getResponse(urlRequest);
- expect(response.headers['x-cookie']).to.equal('undefined');
- });
-
- for (const extraOptions of [{ useSessionCookies: true }, { credentials: 'include' }] as ClientRequestConstructorOptions[]) {
- describe(`when ${JSON.stringify(extraOptions)}`, () => {
- it('should be able to use the sessions cookie store', async () => {
- const serverUrl = await respondOnce.toSingleURL((request, response) => {
- response.statusCode = 200;
- response.statusMessage = 'OK';
- response.setHeader('x-cookie', request.headers.cookie!);
- response.end();
- });
- const sess = session.fromPartition(`cookie-tests-${Math.random()}`);
- const cookieVal = `${Date.now()}`;
- await sess.cookies.set({
- url: serverUrl,
- name: 'wild_cookie',
- value: cookieVal
- });
- const urlRequest = net.request({
- url: serverUrl,
- session: sess,
- ...extraOptions
- });
- const response = await getResponse(urlRequest);
- expect(response.headers['x-cookie']).to.equal(`wild_cookie=${cookieVal}`);
- });
+ expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue);
+ urlRequest.write('');
+ const response = await getResponse(urlRequest);
+ expect(response.statusCode).to.equal(200);
+ await collectStreamBody(response);
+ });
- it('should be able to use the sessions cookie store with set-cookie', async () => {
- const serverUrl = await respondOnce.toSingleURL((request, response) => {
- response.statusCode = 200;
- response.statusMessage = 'OK';
- response.setHeader('set-cookie', 'foo=bar');
- response.end();
- });
- const sess = session.fromPartition(`cookie-tests-${Math.random()}`);
- let cookies = await sess.cookies.get({});
- expect(cookies).to.have.lengthOf(0);
- const urlRequest = net.request({
- url: serverUrl,
- session: sess,
- ...extraOptions
- });
- await collectStreamBody(await getResponse(urlRequest));
- cookies = await sess.cookies.get({});
- expect(cookies).to.have.lengthOf(1);
- expect(cookies[0]).to.deep.equal({
- name: 'foo',
- value: 'bar',
- domain: '127.0.0.1',
- hostOnly: true,
- path: '/',
- secure: false,
- httpOnly: false,
- session: true,
- sameSite: 'unspecified'
- });
+ test('should not be able to set a custom HTTP request header after first write', async () => {
+ const customHeaderName = 'Some-Custom-Header-Name';
+ const customHeaderValue = 'Some-Customer-Header-Value';
+ const serverUrl = await respondOnce.toSingleURL((request, response) => {
+ expect(request.headers[customHeaderName.toLowerCase()]).to.equal(undefined);
+ response.statusCode = 200;
+ response.statusMessage = 'OK';
+ response.end();
});
+ const urlRequest = net.request(serverUrl);
+ urlRequest.write('');
+ expect(() => {
+ urlRequest.setHeader(customHeaderName, customHeaderValue);
+ }).to.throw();
+ expect(urlRequest.getHeader(customHeaderName)).to.equal(undefined);
+ const response = await getResponse(urlRequest);
+ expect(response.statusCode).to.equal(200);
+ await collectStreamBody(response);
+ });
- for (const mode of ['Lax', 'Strict']) {
- it(`should be able to use the sessions cookie store with same-site ${mode} cookies`, async () => {
- const serverUrl = await respondNTimes.toSingleURL((request, response) => {
- response.statusCode = 200;
- response.statusMessage = 'OK';
- response.setHeader('set-cookie', `same=site; SameSite=${mode}`);
- response.setHeader('x-cookie', `${request.headers.cookie}`);
- response.end();
- }, 2);
- const sess = session.fromPartition(`cookie-tests-${Math.random()}`);
- let cookies = await sess.cookies.get({});
- expect(cookies).to.have.lengthOf(0);
- const urlRequest = net.request({
- url: serverUrl,
- session: sess,
- ...extraOptions
- });
- const response = await getResponse(urlRequest);
- expect(response.headers['x-cookie']).to.equal('undefined');
- await collectStreamBody(response);
- cookies = await sess.cookies.get({});
- expect(cookies).to.have.lengthOf(1);
- expect(cookies[0]).to.deep.equal({
- name: 'same',
- value: 'site',
- domain: '127.0.0.1',
- hostOnly: true,
- path: '/',
- secure: false,
- httpOnly: false,
- session: true,
- sameSite: mode.toLowerCase()
- });
- const urlRequest2 = net.request({
- url: serverUrl,
- session: sess,
- ...extraOptions
- });
- const response2 = await getResponse(urlRequest2);
- expect(response2.headers['x-cookie']).to.equal('same=site');
- });
- }
-
- it('should be able to use the sessions cookie store safely across redirects', async () => {
- const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
- response.statusCode = 302;
- response.statusMessage = 'Moved';
- const newUrl = await respondOnce.toSingleURL((req, res) => {
- res.statusCode = 200;
- res.statusMessage = 'OK';
- res.setHeader('x-cookie', req.headers.cookie!);
- res.end();
- });
- response.setHeader('x-cookie', request.headers.cookie!);
- response.setHeader('location', newUrl.replace('127.0.0.1', 'localhost'));
- response.end();
- });
- const sess = session.fromPartition(`cookie-tests-${Math.random()}`);
- const cookie127Val = `${Date.now()}-127`;
- const cookieLocalVal = `${Date.now()}-local`;
- const localhostUrl = serverUrl.replace('127.0.0.1', 'localhost');
- expect(localhostUrl).to.not.equal(serverUrl);
- // cookies with lax or strict same-site settings will not
- // persist after redirects. no_restriction must be used
- await Promise.all([
- sess.cookies.set({
- url: serverUrl,
- name: 'wild_cookie',
- sameSite: 'no_restriction',
- value: cookie127Val
- }), sess.cookies.set({
- url: localhostUrl,
- name: 'wild_cookie',
- sameSite: 'no_restriction',
- value: cookieLocalVal
- })
- ]);
- const urlRequest = net.request({
- url: serverUrl,
- session: sess,
- ...extraOptions
- });
- urlRequest.on('redirect', (status, method, url, headers) => {
- // The initial redirect response should have received the 127 value here
- expect(headers['x-cookie'][0]).to.equal(`wild_cookie=${cookie127Val}`);
- urlRequest.followRedirect();
- });
- const response = await getResponse(urlRequest);
- // We expect the server to have received the localhost value here
- // The original request was to a 127.0.0.1 URL
- // That request would have the cookie127Val cookie attached
- // The request is then redirect to a localhost URL (different site)
- // Because we are using the session cookie store it should do the safe / secure thing
- // and attach the cookies for the new target domain
- expect(response.headers['x-cookie']).to.equal(`wild_cookie=${cookieLocalVal}`);
+ test('should be able to remove a custom HTTP request header before first write', async () => {
+ const customHeaderName = 'Some-Custom-Header-Name';
+ const customHeaderValue = 'Some-Customer-Header-Value';
+ const serverUrl = await respondOnce.toSingleURL((request, response) => {
+ expect(request.headers[customHeaderName.toLowerCase()]).to.equal(undefined);
+ response.statusCode = 200;
+ response.statusMessage = 'OK';
+ response.end();
});
+ const urlRequest = net.request(serverUrl);
+ urlRequest.setHeader(customHeaderName, customHeaderValue);
+ expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue);
+ urlRequest.removeHeader(customHeaderName);
+ expect(urlRequest.getHeader(customHeaderName)).to.equal(undefined);
+ urlRequest.write('');
+ const response = await getResponse(urlRequest);
+ expect(response.statusCode).to.equal(200);
+ await collectStreamBody(response);
});
- }
-
- it('should be able correctly filter out cookies that are secure', async () => {
- const sess = session.fromPartition(`cookie-tests-${Math.random()}`);
-
- await Promise.all([
- sess.cookies.set({
- url: 'https://electronjs.org',
- domain: 'electronjs.org',
- name: 'cookie1',
- value: '1',
- secure: true
- }),
- sess.cookies.set({
- url: 'https://electronjs.org',
- domain: 'electronjs.org',
- name: 'cookie2',
- value: '2',
- secure: false
- })
- ]);
-
- const secureCookies = await sess.cookies.get({
- secure: true
- });
- expect(secureCookies).to.have.lengthOf(1);
- expect(secureCookies[0].name).to.equal('cookie1');
-
- const cookies = await sess.cookies.get({
- secure: false
- });
- expect(cookies).to.have.lengthOf(1);
- expect(cookies[0].name).to.equal('cookie2');
- });
-
- it('throws when an invalid domain is passed', async () => {
- const sess = session.fromPartition(`cookie-tests-${Math.random()}`);
-
- await expect(sess.cookies.set({
- url: 'https://electronjs.org',
- domain: 'wssss.iamabaddomain.fun',
- name: 'cookie1'
- })).to.eventually.be.rejectedWith(/Failed to set cookie with an invalid domain attribute/);
- });
- it('should be able correctly filter out cookies that are session', async () => {
- const sess = session.fromPartition(`cookie-tests-${Math.random()}`);
-
- await Promise.all([
- sess.cookies.set({
- url: 'https://electronjs.org',
- domain: 'electronjs.org',
- name: 'cookie1',
- value: '1'
- }),
- sess.cookies.set({
- url: 'https://electronjs.org',
- domain: 'electronjs.org',
- name: 'cookie2',
- value: '2',
- expirationDate: Math.round(Date.now() / 1000) + 10000
- })
- ]);
-
- const sessionCookies = await sess.cookies.get({
- session: true
- });
- expect(sessionCookies).to.have.lengthOf(1);
- expect(sessionCookies[0].name).to.equal('cookie1');
-
- const cookies = await sess.cookies.get({
- session: false
- });
- expect(cookies).to.have.lengthOf(1);
- expect(cookies[0].name).to.equal('cookie2');
- });
-
- it('should be able correctly filter out cookies that are httpOnly', async () => {
- const sess = session.fromPartition(`cookie-tests-${Math.random()}`);
-
- await Promise.all([
- sess.cookies.set({
- url: 'https://electronjs.org',
- domain: 'electronjs.org',
- name: 'cookie1',
- value: '1',
- httpOnly: true
- }),
- sess.cookies.set({
- url: 'https://electronjs.org',
- domain: 'electronjs.org',
- name: 'cookie2',
- value: '2',
- httpOnly: false
- })
- ]);
-
- const httpOnlyCookies = await sess.cookies.get({
- httpOnly: true
- });
- expect(httpOnlyCookies).to.have.lengthOf(1);
- expect(httpOnlyCookies[0].name).to.equal('cookie1');
-
- const cookies = await sess.cookies.get({
- httpOnly: false
- });
- expect(cookies).to.have.lengthOf(1);
- expect(cookies[0].name).to.equal('cookie2');
- });
-
- describe('when {"credentials":"omit"}', () => {
- it('should not send cookies');
- it('should not store cookies');
- });
-
- it('should set sec-fetch-site to same-origin for request from same origin', async () => {
- const serverUrl = await respondOnce.toSingleURL((request, response) => {
- expect(request.headers['sec-fetch-site']).to.equal('same-origin');
- response.statusCode = 200;
- response.statusMessage = 'OK';
- response.end();
- });
- const urlRequest = net.request({
- url: serverUrl,
- origin: serverUrl
+ test('should not be able to remove a custom HTTP request header after first write', async () => {
+ const customHeaderName = 'Some-Custom-Header-Name';
+ const customHeaderValue = 'Some-Customer-Header-Value';
+ const serverUrl = await respondOnce.toSingleURL((request, response) => {
+ expect(request.headers[customHeaderName.toLowerCase()]).to.equal(customHeaderValue);
+ response.statusCode = 200;
+ response.statusMessage = 'OK';
+ response.end();
+ });
+ const urlRequest = net.request(serverUrl);
+ urlRequest.setHeader(customHeaderName, customHeaderValue);
+ expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue);
+ urlRequest.write('');
+ expect(() => {
+ urlRequest.removeHeader(customHeaderName);
+ }).to.throw();
+ expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue);
+ const response = await getResponse(urlRequest);
+ expect(response.statusCode).to.equal(200);
+ await collectStreamBody(response);
});
- await collectStreamBody(await getResponse(urlRequest));
- });
- it('should set sec-fetch-site to same-origin for request with the same origin header', async () => {
- const serverUrl = await respondOnce.toSingleURL((request, response) => {
- expect(request.headers['sec-fetch-site']).to.equal('same-origin');
- response.statusCode = 200;
- response.statusMessage = 'OK';
- response.end();
- });
- const urlRequest = net.request({
- url: serverUrl
- });
- urlRequest.setHeader('Origin', serverUrl);
- await collectStreamBody(await getResponse(urlRequest));
- });
+ test('should keep the order of headers', async () => {
+ const customHeaderNameA = 'X-Header-100';
+ const customHeaderNameB = 'X-Header-200';
+ const serverUrl = await respondOnce.toSingleURL((request, response) => {
+ const headerNames = Array.from(Object.keys(request.headers));
+ const headerAIndex = headerNames.indexOf(customHeaderNameA.toLowerCase());
+ const headerBIndex = headerNames.indexOf(customHeaderNameB.toLowerCase());
+ expect(headerBIndex).to.be.below(headerAIndex);
+ response.statusCode = 200;
+ response.statusMessage = 'OK';
+ response.end();
+ });
- it('should set sec-fetch-site to cross-site for request from other origin', async () => {
- const serverUrl = await respondOnce.toSingleURL((request, response) => {
- expect(request.headers['sec-fetch-site']).to.equal('cross-site');
- response.statusCode = 200;
- response.statusMessage = 'OK';
- response.end();
- });
- const urlRequest = net.request({
- url: serverUrl,
- origin: 'https://not-exists.com'
+ const urlRequest = net.request(serverUrl);
+ urlRequest.setHeader(customHeaderNameB, 'b');
+ urlRequest.setHeader(customHeaderNameA, 'a');
+ const response = await getResponse(urlRequest);
+ expect(response.statusCode).to.equal(200);
+ await collectStreamBody(response);
});
- await collectStreamBody(await getResponse(urlRequest));
- });
- it('should not send sec-fetch-user header by default', async () => {
- const serverUrl = await respondOnce.toSingleURL((request, response) => {
- expect(request.headers).not.to.have.property('sec-fetch-user');
- response.statusCode = 200;
- response.statusMessage = 'OK';
- response.end();
- });
- const urlRequest = net.request({
- url: serverUrl
+ test('should be able to receive cookies', async () => {
+ const cookie = ['cookie1', 'cookie2'];
+ const serverUrl = await respondOnce.toSingleURL((request, response) => {
+ response.statusCode = 200;
+ response.statusMessage = 'OK';
+ response.setHeader('set-cookie', cookie);
+ response.end();
+ });
+ const urlRequest = net.request(serverUrl);
+ const response = await getResponse(urlRequest);
+ expect(response.headers['set-cookie']).to.have.same.members(cookie);
});
- await collectStreamBody(await getResponse(urlRequest));
- });
- it('should set sec-fetch-user to ?1 if requested', async () => {
- const serverUrl = await respondOnce.toSingleURL((request, response) => {
- expect(request.headers['sec-fetch-user']).to.equal('?1');
- response.statusCode = 200;
- response.statusMessage = 'OK';
- response.end();
- });
- const urlRequest = net.request({
- url: serverUrl
+ test('should be able to receive content-type', async () => {
+ const contentType = 'mime/test; charset=test';
+ const serverUrl = await respondOnce.toSingleURL((request, response) => {
+ response.statusCode = 200;
+ response.statusMessage = 'OK';
+ response.setHeader('content-type', contentType);
+ response.end();
+ });
+ const urlRequest = net.request(serverUrl);
+ const response = await getResponse(urlRequest);
+ expect(response.headers['content-type']).to.equal(contentType);
});
- urlRequest.setHeader('sec-fetch-user', '?1');
- await collectStreamBody(await getResponse(urlRequest));
- });
- it('should set sec-fetch-mode to no-cors by default', async () => {
- const serverUrl = await respondOnce.toSingleURL((request, response) => {
- expect(request.headers['sec-fetch-mode']).to.equal('no-cors');
- response.statusCode = 200;
- response.statusMessage = 'OK';
- response.end();
+ describe('when {"credentials":"omit"}', () => {
+ test('should not send cookies');
+ test('should not store cookies');
});
- const urlRequest = net.request({
- url: serverUrl
- });
- await collectStreamBody(await getResponse(urlRequest));
- });
- for (const mode of ['navigate', 'cors', 'no-cors', 'same-origin']) {
- it(`should set sec-fetch-mode to ${mode} if requested`, async () => {
+ test('should set sec-fetch-site to same-origin for request from same origin', async () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => {
- expect(request.headers['sec-fetch-mode']).to.equal(mode);
+ expect(request.headers['sec-fetch-site']).to.equal('same-origin');
response.statusCode = 200;
response.statusMessage = 'OK';
response.end();
@@ -1079,1266 +498,1120 @@ describe('net module', () => {
url: serverUrl,
origin: serverUrl
});
- urlRequest.setHeader('sec-fetch-mode', mode);
await collectStreamBody(await getResponse(urlRequest));
});
- }
- it('should set sec-fetch-dest to empty by default', async () => {
- const serverUrl = await respondOnce.toSingleURL((request, response) => {
- expect(request.headers['sec-fetch-dest']).to.equal('empty');
- response.statusCode = 200;
- response.statusMessage = 'OK';
- response.end();
- });
- const urlRequest = net.request({
- url: serverUrl
+ test('should set sec-fetch-site to same-origin for request with the same origin header', async () => {
+ const serverUrl = await respondOnce.toSingleURL((request, response) => {
+ expect(request.headers['sec-fetch-site']).to.equal('same-origin');
+ response.statusCode = 200;
+ response.statusMessage = 'OK';
+ response.end();
+ });
+ const urlRequest = net.request({
+ url: serverUrl
+ });
+ urlRequest.setHeader('Origin', serverUrl);
+ await collectStreamBody(await getResponse(urlRequest));
});
- await collectStreamBody(await getResponse(urlRequest));
- });
- for (const dest of [
- 'empty', 'audio', 'audioworklet', 'document', 'embed', 'font',
- 'frame', 'iframe', 'image', 'manifest', 'object', 'paintworklet',
- 'report', 'script', 'serviceworker', 'style', 'track', 'video',
- 'worker', 'xslt'
- ]) {
- it(`should set sec-fetch-dest to ${dest} if requested`, async () => {
+ test('should set sec-fetch-site to cross-site for request from other origin', async () => {
const serverUrl = await respondOnce.toSingleURL((request, response) => {
- expect(request.headers['sec-fetch-dest']).to.equal(dest);
+ expect(request.headers['sec-fetch-site']).to.equal('cross-site');
response.statusCode = 200;
response.statusMessage = 'OK';
response.end();
});
const urlRequest = net.request({
url: serverUrl,
- origin: serverUrl
+ origin: 'https://not-exists.com'
});
- urlRequest.setHeader('sec-fetch-dest', dest);
await collectStreamBody(await getResponse(urlRequest));
});
- }
-
- it('should be able to abort an HTTP request before first write', async () => {
- const serverUrl = await respondOnce.toSingleURL((request, response) => {
- response.end();
- expect.fail('Unexpected request event');
- });
- const urlRequest = net.request(serverUrl);
- urlRequest.on('response', () => {
- expect.fail('unexpected response event');
+ test('should not send sec-fetch-user header by default', async () => {
+ const serverUrl = await respondOnce.toSingleURL((request, response) => {
+ expect(request.headers).not.to.have.property('sec-fetch-user');
+ response.statusCode = 200;
+ response.statusMessage = 'OK';
+ response.end();
+ });
+ const urlRequest = net.request({
+ url: serverUrl
+ });
+ await collectStreamBody(await getResponse(urlRequest));
});
- const aborted = once(urlRequest, 'abort');
- urlRequest.abort();
- urlRequest.write('');
- urlRequest.end();
- await aborted;
- });
- it('it should be able to abort an HTTP request before request end', async () => {
- let requestReceivedByServer = false;
- let urlRequest: ClientRequest | null = null;
- const serverUrl = await respondOnce.toSingleURL(() => {
- requestReceivedByServer = true;
- urlRequest!.abort();
+ test('should set sec-fetch-user to ?1 if requested', async () => {
+ const serverUrl = await respondOnce.toSingleURL((request, response) => {
+ expect(request.headers['sec-fetch-user']).to.equal('?1');
+ response.statusCode = 200;
+ response.statusMessage = 'OK';
+ response.end();
+ });
+ const urlRequest = net.request({
+ url: serverUrl
+ });
+ urlRequest.setHeader('sec-fetch-user', '?1');
+ await collectStreamBody(await getResponse(urlRequest));
});
- let requestAbortEventEmitted = false;
- urlRequest = net.request(serverUrl);
- urlRequest.on('response', () => {
- expect.fail('Unexpected response event');
- });
- urlRequest.on('finish', () => {
- expect.fail('Unexpected finish event');
- });
- urlRequest.on('error', () => {
- expect.fail('Unexpected error event');
- });
- urlRequest.on('abort', () => {
- requestAbortEventEmitted = true;
+ test('should set sec-fetch-mode to no-cors by default', async () => {
+ const serverUrl = await respondOnce.toSingleURL((request, response) => {
+ expect(request.headers['sec-fetch-mode']).to.equal('no-cors');
+ response.statusCode = 200;
+ response.statusMessage = 'OK';
+ response.end();
+ });
+ const urlRequest = net.request({
+ url: serverUrl
+ });
+ await collectStreamBody(await getResponse(urlRequest));
});
- const p = once(urlRequest, 'close');
- urlRequest.chunkedEncoding = true;
- urlRequest.write(randomString(kOneKiloByte));
- await p;
- expect(requestReceivedByServer).to.equal(true);
- expect(requestAbortEventEmitted).to.equal(true);
- });
+ for (const mode of ['navigate', 'cors', 'no-cors', 'same-origin']) {
+ test(`should set sec-fetch-mode to ${mode} if requested`, async () => {
+ const serverUrl = await respondOnce.toSingleURL((request, response) => {
+ expect(request.headers['sec-fetch-mode']).to.equal(mode);
+ response.statusCode = 200;
+ response.statusMessage = 'OK';
+ response.end();
+ });
+ const urlRequest = net.request({
+ url: serverUrl,
+ origin: serverUrl
+ });
+ urlRequest.setHeader('sec-fetch-mode', mode);
+ await collectStreamBody(await getResponse(urlRequest));
+ }, { mode });
+ }
- it('it should be able to abort an HTTP request after request end and before response', async () => {
- let requestReceivedByServer = false;
- let urlRequest: ClientRequest | null = null;
- const serverUrl = await respondOnce.toSingleURL((request, response) => {
- requestReceivedByServer = true;
- urlRequest!.abort();
- process.nextTick(() => {
+ test('should set sec-fetch-dest to empty by default', async () => {
+ const serverUrl = await respondOnce.toSingleURL((request, response) => {
+ expect(request.headers['sec-fetch-dest']).to.equal('empty');
response.statusCode = 200;
response.statusMessage = 'OK';
response.end();
});
+ const urlRequest = net.request({
+ url: serverUrl
+ });
+ await collectStreamBody(await getResponse(urlRequest));
});
- let requestFinishEventEmitted = false;
- urlRequest = net.request(serverUrl);
- urlRequest.on('response', () => {
- expect.fail('Unexpected response event');
- });
- urlRequest.on('finish', () => {
- requestFinishEventEmitted = true;
- });
- urlRequest.on('error', () => {
- expect.fail('Unexpected error event');
+ for (const dest of [
+ 'empty', 'audio', 'audioworklet', 'document', 'embed', 'font',
+ 'frame', 'iframe', 'image', 'manifest', 'object', 'paintworklet',
+ 'report', 'script', 'serviceworker', 'style', 'track', 'video',
+ 'worker', 'xslt'
+ ]) {
+ test(`should set sec-fetch-dest to ${dest} if requested`, async () => {
+ const serverUrl = await respondOnce.toSingleURL((request, response) => {
+ expect(request.headers['sec-fetch-dest']).to.equal(dest);
+ response.statusCode = 200;
+ response.statusMessage = 'OK';
+ response.end();
+ });
+ const urlRequest = net.request({
+ url: serverUrl,
+ origin: serverUrl
+ });
+ urlRequest.setHeader('sec-fetch-dest', dest);
+ await collectStreamBody(await getResponse(urlRequest));
+ }, { dest });
+ }
+
+ test('should be able to abort an HTTP request before first write', async () => {
+ const serverUrl = await respondOnce.toSingleURL((request, response) => {
+ response.end();
+ expect.fail('Unexpected request event');
+ });
+
+ const urlRequest = net.request(serverUrl);
+ urlRequest.on('response', () => {
+ expect.fail('unexpected response event');
+ });
+ const aborted = once(urlRequest, 'abort');
+ urlRequest.abort();
+ urlRequest.write('');
+ urlRequest.end();
+ await aborted;
});
- urlRequest.end(randomString(kOneKiloByte));
- await once(urlRequest, 'abort');
- expect(requestFinishEventEmitted).to.equal(true);
- expect(requestReceivedByServer).to.equal(true);
- });
- it('it should be able to abort an HTTP request after response start', async () => {
- let requestReceivedByServer = false;
- const serverUrl = await respondOnce.toSingleURL((request, response) => {
- requestReceivedByServer = true;
- response.statusCode = 200;
- response.statusMessage = 'OK';
- response.write(randomString(kOneKiloByte));
- });
- let requestFinishEventEmitted = false;
- let requestResponseEventEmitted = false;
- let responseCloseEventEmitted = false;
-
- const urlRequest = net.request(serverUrl);
- urlRequest.on('response', (response) => {
- requestResponseEventEmitted = true;
- const statusCode = response.statusCode;
- expect(statusCode).to.equal(200);
- response.on('data', () => {});
- response.on('end', () => {
- expect.fail('Unexpected end event');
+ test('it should be able to abort an HTTP request before request end', async () => {
+ let requestReceivedByServer = false;
+ let urlRequest: ClientRequest | null = null;
+ const serverUrl = await respondOnce.toSingleURL(() => {
+ requestReceivedByServer = true;
+ urlRequest!.abort();
+ });
+ let requestAbortEventEmitted = false;
+
+ urlRequest = net.request(serverUrl);
+ urlRequest.on('response', () => {
+ expect.fail('Unexpected response event');
+ });
+ urlRequest.on('finish', () => {
+ expect.fail('Unexpected finish event');
});
- response.on('error', () => {
+ urlRequest.on('error', () => {
expect.fail('Unexpected error event');
});
- response.on('close' as any, () => {
- responseCloseEventEmitted = true;
+ urlRequest.on('abort', () => {
+ requestAbortEventEmitted = true;
});
- urlRequest.abort();
- });
- urlRequest.on('finish', () => {
- requestFinishEventEmitted = true;
- });
- urlRequest.on('error', () => {
- expect.fail('Unexpected error event');
- });
- urlRequest.end(randomString(kOneKiloByte));
- await once(urlRequest, 'abort');
- expect(requestFinishEventEmitted).to.be.true('request should emit "finish" event');
- expect(requestReceivedByServer).to.be.true('request should be received by the server');
- expect(requestResponseEventEmitted).to.be.true('"response" event should be emitted');
- expect(responseCloseEventEmitted).to.be.true('response should emit "close" event');
- });
- it('abort event should be emitted at most once', async () => {
- let requestReceivedByServer = false;
- let urlRequest: ClientRequest | null = null;
- const serverUrl = await respondOnce.toSingleURL(() => {
- requestReceivedByServer = true;
- urlRequest!.abort();
- urlRequest!.abort();
+ const p = once(urlRequest, 'close');
+ urlRequest.chunkedEncoding = true;
+ urlRequest.write(randomString(kOneKiloByte));
+ await p;
+ expect(requestReceivedByServer).to.equal(true);
+ expect(requestAbortEventEmitted).to.equal(true);
});
- let requestFinishEventEmitted = false;
- let abortsEmitted = 0;
- urlRequest = net.request(serverUrl);
- urlRequest.on('response', () => {
- expect.fail('Unexpected response event');
- });
- urlRequest.on('finish', () => {
- requestFinishEventEmitted = true;
- });
- urlRequest.on('error', () => {
- expect.fail('Unexpected error event');
- });
- urlRequest.on('abort', () => {
- abortsEmitted++;
- });
- urlRequest.end(randomString(kOneKiloByte));
- await once(urlRequest, 'abort');
- expect(requestFinishEventEmitted).to.be.true('request should emit "finish" event');
- expect(requestReceivedByServer).to.be.true('request should be received by server');
- expect(abortsEmitted).to.equal(1, 'request should emit exactly 1 "abort" event');
- });
+ test('it should be able to abort an HTTP request after request end and before response', async () => {
+ let requestReceivedByServer = false;
+ let urlRequest: ClientRequest | null = null;
+ const serverUrl = await respondOnce.toSingleURL((request, response) => {
+ requestReceivedByServer = true;
+ urlRequest!.abort();
+ process.nextTick(() => {
+ response.statusCode = 200;
+ response.statusMessage = 'OK';
+ response.end();
+ });
+ });
+ let requestFinishEventEmitted = false;
- it('should allow to read response body from non-2xx response', async () => {
- const bodyData = randomString(kOneKiloByte);
- const serverUrl = await respondOnce.toSingleURL((request, response) => {
- response.statusCode = 404;
- response.end(bodyData);
+ urlRequest = net.request(serverUrl);
+ urlRequest.on('response', () => {
+ expect.fail('Unexpected response event');
+ });
+ urlRequest.on('finish', () => {
+ requestFinishEventEmitted = true;
+ });
+ urlRequest.on('error', () => {
+ expect.fail('Unexpected error event');
+ });
+ urlRequest.end(randomString(kOneKiloByte));
+ await once(urlRequest, 'abort');
+ expect(requestFinishEventEmitted).to.equal(true);
+ expect(requestReceivedByServer).to.equal(true);
});
- const urlRequest = net.request(serverUrl);
- const bodyCheckPromise = getResponse(urlRequest).then(r => {
- expect(r.statusCode).to.equal(404);
- return r;
- }).then(collectStreamBody).then(receivedBodyData => {
- expect(receivedBodyData.toString()).to.equal(bodyData);
+ test('it should be able to abort an HTTP request after response start', async () => {
+ let requestReceivedByServer = false;
+ const serverUrl = await respondOnce.toSingleURL((request, response) => {
+ requestReceivedByServer = true;
+ response.statusCode = 200;
+ response.statusMessage = 'OK';
+ response.write(randomString(kOneKiloByte));
+ });
+ let requestFinishEventEmitted = false;
+ let requestResponseEventEmitted = false;
+ let responseCloseEventEmitted = false;
+
+ const urlRequest = net.request(serverUrl);
+ urlRequest.on('response', (response) => {
+ requestResponseEventEmitted = true;
+ const statusCode = response.statusCode;
+ expect(statusCode).to.equal(200);
+ response.on('data', () => {});
+ response.on('end', () => {
+ expect.fail('Unexpected end event');
+ });
+ response.on('error', () => {
+ expect.fail('Unexpected error event');
+ });
+ response.on('close' as any, () => {
+ responseCloseEventEmitted = true;
+ });
+ urlRequest.abort();
+ });
+ urlRequest.on('finish', () => {
+ requestFinishEventEmitted = true;
+ });
+ urlRequest.on('error', () => {
+ expect.fail('Unexpected error event');
+ });
+ urlRequest.end(randomString(kOneKiloByte));
+ await once(urlRequest, 'abort');
+ expect(requestFinishEventEmitted).to.be.true('request should emit "finish" event');
+ expect(requestReceivedByServer).to.be.true('request should be received by the server');
+ expect(requestResponseEventEmitted).to.be.true('"response" event should be emitted');
+ expect(responseCloseEventEmitted).to.be.true('response should emit "close" event');
+ });
+
+ test('abort event should be emitted at most once', async () => {
+ let requestReceivedByServer = false;
+ let urlRequest: ClientRequest | null = null;
+ const serverUrl = await respondOnce.toSingleURL(() => {
+ requestReceivedByServer = true;
+ urlRequest!.abort();
+ urlRequest!.abort();
+ });
+ let requestFinishEventEmitted = false;
+ let abortsEmitted = 0;
+
+ urlRequest = net.request(serverUrl);
+ urlRequest.on('response', () => {
+ expect.fail('Unexpected response event');
+ });
+ urlRequest.on('finish', () => {
+ requestFinishEventEmitted = true;
+ });
+ urlRequest.on('error', () => {
+ expect.fail('Unexpected error event');
+ });
+ urlRequest.on('abort', () => {
+ abortsEmitted++;
+ });
+ urlRequest.end(randomString(kOneKiloByte));
+ await once(urlRequest, 'abort');
+ expect(requestFinishEventEmitted).to.be.true('request should emit "finish" event');
+ expect(requestReceivedByServer).to.be.true('request should be received by server');
+ expect(abortsEmitted).to.equal(1, 'request should emit exactly 1 "abort" event');
});
- const eventHandlers = Promise.all([
- bodyCheckPromise,
- once(urlRequest, 'close')
- ]);
- urlRequest.end();
+ test('should allow to read response body from non-2xx response', async () => {
+ const bodyData = randomString(kOneKiloByte);
+ const serverUrl = await respondOnce.toSingleURL((request, response) => {
+ response.statusCode = 404;
+ response.end(bodyData);
+ });
+
+ const urlRequest = net.request(serverUrl);
+ const bodyCheckPromise = getResponse(urlRequest).then(r => {
+ expect(r.statusCode).to.equal(404);
+ return r;
+ }).then(collectStreamBody).then(receivedBodyData => {
+ expect(receivedBodyData.toString()).to.equal(bodyData);
+ });
+ const eventHandlers = Promise.all([
+ bodyCheckPromise,
+ once(urlRequest, 'close')
+ ]);
- await eventHandlers;
- });
+ urlRequest.end();
- describe('webRequest', () => {
- afterEach(() => {
- session.defaultSession.webRequest.onBeforeRequest(null);
+ await eventHandlers;
});
- it('Should throw when invalid filters are passed', () => {
+ test('should throw when calling getHeader without a name', () => {
expect(() => {
- session.defaultSession.webRequest.onBeforeRequest(
- { urls: ['*://www.googleapis.com'] },
- (details, callback) => { callback({ cancel: false }); }
- );
- }).to.throw('Invalid url pattern *://www.googleapis.com: Empty path.');
+ (net.request({ url: 'https://test' }).getHeader as any)();
+ }).to.throw(/`name` is required for getHeader\(name\)/);
expect(() => {
- session.defaultSession.webRequest.onBeforeRequest(
- { urls: ['*://www.googleapis.com/', '*://blahblah.dev'] },
- (details, callback) => { callback({ cancel: false }); }
- );
- }).to.throw('Invalid url pattern *://blahblah.dev: Empty path.');
+ net.request({ url: 'https://test' }).getHeader(null as any);
+ }).to.throw(/`name` is required for getHeader\(name\)/);
});
- it('Should not throw when valid filters are passed', () => {
+ test('should throw when calling removeHeader without a name', () => {
expect(() => {
- session.defaultSession.webRequest.onBeforeRequest(
- { urls: ['*://www.googleapis.com/'] },
- (details, callback) => { callback({ cancel: false }); }
- );
- }).to.not.throw();
- });
-
- it('Requests should be intercepted by webRequest module', async () => {
- const requestUrl = '/requestUrl';
- const redirectUrl = '/redirectUrl';
- let requestIsRedirected = false;
- const serverUrl = await respondOnce.toURL(redirectUrl, (request, response) => {
- requestIsRedirected = true;
- response.end();
- });
- let requestIsIntercepted = false;
- session.defaultSession.webRequest.onBeforeRequest(
- (details, callback) => {
- if (details.url === `${serverUrl}${requestUrl}`) {
- requestIsIntercepted = true;
- callback({
- redirectURL: `${serverUrl}${redirectUrl}`
- });
- } else {
- callback({
- cancel: false
- });
- }
- });
+ (net.request({ url: 'https://test' }).removeHeader as any)();
+ }).to.throw(/`name` is required for removeHeader\(name\)/);
- const urlRequest = net.request(`${serverUrl}${requestUrl}`);
- const response = await getResponse(urlRequest);
-
- expect(response.statusCode).to.equal(200);
- await collectStreamBody(response);
- expect(requestIsRedirected).to.be.true('The server should receive a request to the forward URL');
- expect(requestIsIntercepted).to.be.true('The request should be intercepted by the webRequest module');
+ expect(() => {
+ net.request({ url: 'https://test' }).removeHeader(null as any);
+ }).to.throw(/`name` is required for removeHeader\(name\)/);
});
- it('should to able to create and intercept a request using a custom session object', async () => {
- const requestUrl = '/requestUrl';
- const redirectUrl = '/redirectUrl';
- const customPartitionName = `custom-partition-${Math.random()}`;
- let requestIsRedirected = false;
- const serverUrl = await respondOnce.toURL(redirectUrl, (request, response) => {
- requestIsRedirected = true;
- response.end();
- });
- session.defaultSession.webRequest.onBeforeRequest(() => {
- expect.fail('Request should not be intercepted by the default session');
- });
-
- const customSession = session.fromPartition(customPartitionName, { cache: false });
- let requestIsIntercepted = false;
- customSession.webRequest.onBeforeRequest((details, callback) => {
- if (details.url === `${serverUrl}${requestUrl}`) {
- requestIsIntercepted = true;
- callback({
- redirectURL: `${serverUrl}${redirectUrl}`
- });
- } else {
- callback({
- cancel: false
- });
+ test('should follow redirect when no redirect handler is provided', async () => {
+ const requestUrl = '/302';
+ const serverUrl = await respondOnce.toRoutes({
+ '/302': (request, response) => {
+ response.statusCode = 302;
+ response.setHeader('Location', '/200');
+ response.end();
+ },
+ '/200': (request, response) => {
+ response.statusCode = 200;
+ response.end();
}
});
-
const urlRequest = net.request({
- url: `${serverUrl}${requestUrl}`,
- session: customSession
+ url: `${serverUrl}${requestUrl}`
});
const response = await getResponse(urlRequest);
expect(response.statusCode).to.equal(200);
- await collectStreamBody(response);
- expect(requestIsRedirected).to.be.true('The server should receive a request to the forward URL');
- expect(requestIsIntercepted).to.be.true('The request should be intercepted by the webRequest module');
});
- it('should to able to create and intercept a request using a custom partition name', async () => {
- const requestUrl = '/requestUrl';
- const redirectUrl = '/redirectUrl';
- const customPartitionName = `custom-partition-${Math.random()}`;
- let requestIsRedirected = false;
- const serverUrl = await respondOnce.toURL(redirectUrl, (request, response) => {
- requestIsRedirected = true;
- response.end();
- });
- session.defaultSession.webRequest.onBeforeRequest(() => {
- expect.fail('Request should not be intercepted by the default session');
- });
-
- const customSession = session.fromPartition(customPartitionName, { cache: false });
- let requestIsIntercepted = false;
- customSession.webRequest.onBeforeRequest((details, callback) => {
- if (details.url === `${serverUrl}${requestUrl}`) {
- requestIsIntercepted = true;
- callback({
- redirectURL: `${serverUrl}${redirectUrl}`
- });
- } else {
- callback({
- cancel: false
- });
+ test('should follow redirect chain when no redirect handler is provided', async () => {
+ const serverUrl = await respondOnce.toRoutes({
+ '/redirectChain': (request, response) => {
+ response.statusCode = 302;
+ response.setHeader('Location', '/302');
+ response.end();
+ },
+ '/302': (request, response) => {
+ response.statusCode = 302;
+ response.setHeader('Location', '/200');
+ response.end();
+ },
+ '/200': (request, response) => {
+ response.statusCode = 200;
+ response.end();
}
});
-
const urlRequest = net.request({
- url: `${serverUrl}${requestUrl}`,
- partition: customPartitionName
+ url: `${serverUrl}/redirectChain`
});
const response = await getResponse(urlRequest);
expect(response.statusCode).to.equal(200);
- await collectStreamBody(response);
- expect(requestIsRedirected).to.be.true('The server should receive a request to the forward URL');
- expect(requestIsIntercepted).to.be.true('The request should be intercepted by the webRequest module');
- });
-
- it('triggers webRequest handlers when bypassCustomProtocolHandlers', async () => {
- let webRequestDetails: Electron.OnBeforeRequestListenerDetails | null = null;
- const serverUrl = await respondOnce.toSingleURL((req, res) => res.end('hi'));
- session.defaultSession.webRequest.onBeforeRequest((details, cb) => {
- webRequestDetails = details;
- cb({});
- });
- const body = await net.fetch(serverUrl, { bypassCustomProtocolHandlers: true }).then(r => r.text());
- expect(body).to.equal('hi');
- expect(webRequestDetails).to.have.property('url', serverUrl);
});
- });
-
- it('should throw when calling getHeader without a name', () => {
- expect(() => {
- (net.request({ url: 'https://test' }).getHeader as any)();
- }).to.throw(/`name` is required for getHeader\(name\)/);
-
- expect(() => {
- net.request({ url: 'https://test' }).getHeader(null as any);
- }).to.throw(/`name` is required for getHeader\(name\)/);
- });
-
- it('should throw when calling removeHeader without a name', () => {
- expect(() => {
- (net.request({ url: 'https://test' }).removeHeader as any)();
- }).to.throw(/`name` is required for removeHeader\(name\)/);
-
- expect(() => {
- net.request({ url: 'https://test' }).removeHeader(null as any);
- }).to.throw(/`name` is required for removeHeader\(name\)/);
- });
- it('should follow redirect when no redirect handler is provided', async () => {
- const requestUrl = '/302';
- const serverUrl = await respondOnce.toRoutes({
- '/302': (request, response) => {
+ test('should not follow redirect when request is canceled in redirect handler', async () => {
+ const serverUrl = await respondOnce.toSingleURL((request, response) => {
response.statusCode = 302;
response.setHeader('Location', '/200');
response.end();
- },
- '/200': (request, response) => {
- response.statusCode = 200;
- response.end();
- }
- });
- const urlRequest = net.request({
- url: `${serverUrl}${requestUrl}`
+ });
+ const urlRequest = net.request({
+ url: serverUrl
+ });
+ urlRequest.end();
+ urlRequest.on('redirect', () => { urlRequest.abort(); });
+ urlRequest.on('error', () => {});
+ urlRequest.on('response', () => {
+ expect.fail('Unexpected response');
+ });
+ await once(urlRequest, 'abort');
});
- const response = await getResponse(urlRequest);
- expect(response.statusCode).to.equal(200);
- });
- it('should follow redirect chain when no redirect handler is provided', async () => {
- const serverUrl = await respondOnce.toRoutes({
- '/redirectChain': (request, response) => {
- response.statusCode = 302;
- response.setHeader('Location', '/302');
- response.end();
- },
- '/302': (request, response) => {
+ test('should not follow redirect when mode is error', async () => {
+ const serverUrl = await respondOnce.toSingleURL((request, response) => {
response.statusCode = 302;
response.setHeader('Location', '/200');
response.end();
- },
- '/200': (request, response) => {
- response.statusCode = 200;
- response.end();
- }
- });
- const urlRequest = net.request({
- url: `${serverUrl}/redirectChain`
- });
- const response = await getResponse(urlRequest);
- expect(response.statusCode).to.equal(200);
- });
-
- it('should not follow redirect when request is canceled in redirect handler', async () => {
- const serverUrl = await respondOnce.toSingleURL((request, response) => {
- response.statusCode = 302;
- response.setHeader('Location', '/200');
- response.end();
- });
- const urlRequest = net.request({
- url: serverUrl
- });
- urlRequest.end();
- urlRequest.on('redirect', () => { urlRequest.abort(); });
- urlRequest.on('error', () => {});
- urlRequest.on('response', () => {
- expect.fail('Unexpected response');
- });
- await once(urlRequest, 'abort');
- });
-
- it('should not follow redirect when mode is error', async () => {
- const serverUrl = await respondOnce.toSingleURL((request, response) => {
- response.statusCode = 302;
- response.setHeader('Location', '/200');
- response.end();
- });
- const urlRequest = net.request({
- url: serverUrl,
- redirect: 'error'
+ });
+ const urlRequest = net.request({
+ url: serverUrl,
+ redirect: 'error'
+ });
+ urlRequest.end();
+ await once(urlRequest, 'error');
});
- urlRequest.end();
- await once(urlRequest, 'error');
- });
- it('should follow redirect when handler calls callback', async () => {
- const serverUrl = await respondOnce.toRoutes({
- '/redirectChain': (request, response) => {
- response.statusCode = 302;
- response.setHeader('Location', '/302');
- response.end();
- },
- '/302': (request, response) => {
- response.statusCode = 302;
- response.setHeader('Location', '/200');
- response.end();
- },
- '/200': (request, response) => {
+ test('should follow redirect when handler calls callback', async () => {
+ const serverUrl = await respondOnce.toRoutes({
+ '/redirectChain': (request, response) => {
+ response.statusCode = 302;
+ response.setHeader('Location', '/302');
+ response.end();
+ },
+ '/302': (request, response) => {
+ response.statusCode = 302;
+ response.setHeader('Location', '/200');
+ response.end();
+ },
+ '/200': (request, response) => {
+ response.statusCode = 200;
+ response.end();
+ }
+ });
+ const urlRequest = net.request({ url: `${serverUrl}/redirectChain`, redirect: 'manual' });
+ const redirects: string[] = [];
+ urlRequest.on('redirect', (status, method, url) => {
+ redirects.push(url);
+ urlRequest.followRedirect();
+ });
+ const response = await getResponse(urlRequest);
+ expect(response.statusCode).to.equal(200);
+ expect(redirects).to.deep.equal([
+ `${serverUrl}/302`,
+ `${serverUrl}/200`
+ ]);
+ });
+
+ test('should be able to create a request with options', async () => {
+ const customHeaderName = 'Some-Custom-Header-Name';
+ const customHeaderValue = 'Some-Customer-Header-Value';
+ const serverUrlUnparsed = await respondOnce.toURL('/', (request, response) => {
+ expect(request.method).to.equal('GET');
+ expect(request.headers[customHeaderName.toLowerCase()]).to.equal(customHeaderValue);
response.statusCode = 200;
+ response.statusMessage = 'OK';
response.end();
- }
- });
- const urlRequest = net.request({ url: `${serverUrl}/redirectChain`, redirect: 'manual' });
- const redirects: string[] = [];
- urlRequest.on('redirect', (status, method, url) => {
- redirects.push(url);
- urlRequest.followRedirect();
- });
- const response = await getResponse(urlRequest);
- expect(response.statusCode).to.equal(200);
- expect(redirects).to.deep.equal([
- `${serverUrl}/302`,
- `${serverUrl}/200`
- ]);
- });
-
- it('should throw if given an invalid session option', () => {
- expect(() => {
- net.request({
- url: 'https://foo',
- session: 1 as any
- });
- }).to.throw('`session` should be an instance of the Session class');
- });
-
- it('should throw if given an invalid partition option', () => {
- expect(() => {
- net.request({
- url: 'https://foo',
- partition: 1 as any
});
- }).to.throw('`partition` should be a string');
- });
+ const serverUrl = url.parse(serverUrlUnparsed);
+ const options = {
+ port: serverUrl.port ? parseInt(serverUrl.port, 10) : undefined,
+ hostname: '127.0.0.1',
+ headers: { [customHeaderName]: customHeaderValue }
+ };
+ const urlRequest = net.request(options);
+ const response = await getResponse(urlRequest);
+ expect(response.statusCode).to.be.equal(200);
+ await collectStreamBody(response);
+ });
- it('should be able to create a request with options', async () => {
- const customHeaderName = 'Some-Custom-Header-Name';
- const customHeaderValue = 'Some-Customer-Header-Value';
- const serverUrlUnparsed = await respondOnce.toURL('/', (request, response) => {
- expect(request.method).to.equal('GET');
- expect(request.headers[customHeaderName.toLowerCase()]).to.equal(customHeaderValue);
- response.statusCode = 200;
- response.statusMessage = 'OK';
- response.end();
- });
- const serverUrl = url.parse(serverUrlUnparsed);
- const options = {
- port: serverUrl.port ? parseInt(serverUrl.port, 10) : undefined,
- hostname: '127.0.0.1',
- headers: { [customHeaderName]: customHeaderValue }
- };
- const urlRequest = net.request(options);
- const response = await getResponse(urlRequest);
- expect(response.statusCode).to.be.equal(200);
- await collectStreamBody(response);
- });
+ test('should be able to pipe a readable stream into a net request', async () => {
+ const bodyData = randomString(kOneMegaByte);
+ let netRequestReceived = false;
+ let netRequestEnded = false;
- it('should be able to pipe a readable stream into a net request', async () => {
- const bodyData = randomString(kOneMegaByte);
- let netRequestReceived = false;
- let netRequestEnded = false;
-
- const [nodeServerUrl, netServerUrl] = await Promise.all([
- respondOnce.toSingleURL((request, response) => response.end(bodyData)),
- respondOnce.toSingleURL((request, response) => {
- netRequestReceived = true;
- let receivedBodyData = '';
- request.on('data', (chunk) => {
- receivedBodyData += chunk.toString();
- });
- request.on('end', (chunk: Buffer | undefined) => {
- netRequestEnded = true;
- if (chunk) {
+ const [nodeServerUrl, netServerUrl] = await Promise.all([
+ respondOnce.toSingleURL((request, response) => response.end(bodyData)),
+ respondOnce.toSingleURL((request, response) => {
+ netRequestReceived = true;
+ let receivedBodyData = '';
+ request.on('data', (chunk) => {
receivedBodyData += chunk.toString();
- }
- expect(receivedBodyData).to.be.equal(bodyData);
- response.end();
- });
- })
- ]);
- const nodeRequest = http.request(nodeServerUrl);
- const nodeResponse = await getResponse(nodeRequest as any) as any as http.ServerResponse;
- const netRequest = net.request(netServerUrl);
- const responsePromise = once(netRequest, 'response');
- // TODO(@MarshallOfSound) - FIXME with #22730
- nodeResponse.pipe(netRequest as any);
- const [netResponse] = await responsePromise;
- expect(netResponse.statusCode).to.equal(200);
- await collectStreamBody(netResponse);
- expect(netRequestReceived).to.be.true('net request received');
- expect(netRequestEnded).to.be.true('net request ended');
- });
+ });
+ request.on('end', (chunk: Buffer | undefined) => {
+ netRequestEnded = true;
+ if (chunk) {
+ receivedBodyData += chunk.toString();
+ }
+ expect(receivedBodyData).to.be.equal(bodyData);
+ response.end();
+ });
+ })
+ ]);
+ const nodeRequest = http.request(nodeServerUrl);
+ const nodeResponse = await getResponse(nodeRequest as any) as any as http.ServerResponse;
+ const netRequest = net.request(netServerUrl);
+ const responsePromise = once(netRequest, 'response');
+ // TODO(@MarshallOfSound) - FIXME with #22730
+ nodeResponse.pipe(netRequest as any);
+ const [netResponse] = await responsePromise;
+ expect(netResponse.statusCode).to.equal(200);
+ await collectStreamBody(netResponse);
+ expect(netRequestReceived).to.be.true('net request received');
+ expect(netRequestEnded).to.be.true('net request ended');
+ });
+
+ test('should report upload progress', async () => {
+ const serverUrl = await respondOnce.toSingleURL((request, response) => {
+ response.end();
+ });
+ const netRequest = net.request({ url: serverUrl, method: 'POST' });
+ expect(netRequest.getUploadProgress()).to.have.property('active', false);
+ netRequest.end(Buffer.from('hello'));
+ const [position, total] = await once(netRequest, 'upload-progress');
+ expect(netRequest.getUploadProgress()).to.deep.equal({ active: true, started: true, current: position, total });
+ });
- it('should report upload progress', async () => {
- const serverUrl = await respondOnce.toSingleURL((request, response) => {
- response.end();
+ test('should emit error event on server socket destroy', async () => {
+ const serverUrl = await respondOnce.toSingleURL((request) => {
+ request.socket.destroy();
+ });
+ const urlRequest = net.request(serverUrl);
+ urlRequest.end();
+ const [error] = await once(urlRequest, 'error');
+ expect(error.message).to.equal('net::ERR_EMPTY_RESPONSE');
});
- const netRequest = net.request({ url: serverUrl, method: 'POST' });
- expect(netRequest.getUploadProgress()).to.have.property('active', false);
- netRequest.end(Buffer.from('hello'));
- const [position, total] = await once(netRequest, 'upload-progress');
- expect(netRequest.getUploadProgress()).to.deep.equal({ active: true, started: true, current: position, total });
- });
- it('should emit error event on server socket destroy', async () => {
- const serverUrl = await respondOnce.toSingleURL((request) => {
- request.socket.destroy();
+ test('should emit error event on server request destroy', async () => {
+ const serverUrl = await respondOnce.toSingleURL((request, response) => {
+ request.destroy();
+ response.end();
+ });
+ const urlRequest = net.request(serverUrl);
+ urlRequest.end(randomBuffer(kOneMegaByte));
+ const [error] = await once(urlRequest, 'error');
+ expect(error.message).to.be.oneOf(['net::ERR_FAILED', 'net::ERR_CONNECTION_RESET', 'net::ERR_CONNECTION_ABORTED']);
});
- const urlRequest = net.request(serverUrl);
- urlRequest.end();
- const [error] = await once(urlRequest, 'error');
- expect(error.message).to.equal('net::ERR_EMPTY_RESPONSE');
- });
- it('should emit error event on server request destroy', async () => {
- const serverUrl = await respondOnce.toSingleURL((request, response) => {
- request.destroy();
- response.end();
+ test('should not emit any event after close', async () => {
+ const serverUrl = await respondOnce.toSingleURL((request, response) => {
+ response.end();
+ });
+
+ const urlRequest = net.request(serverUrl);
+ urlRequest.end();
+
+ await once(urlRequest, 'close');
+ await new Promise((resolve, reject) => {
+ for (const evName of ['finish', 'abort', 'close', 'error']) {
+ urlRequest.on(evName as any, () => {
+ reject(new Error(`Unexpected ${evName} event`));
+ });
+ }
+ setTimeout(50).then(resolve);
+ });
});
- const urlRequest = net.request(serverUrl);
- urlRequest.end(randomBuffer(kOneMegaByte));
- const [error] = await once(urlRequest, 'error');
- expect(error.message).to.be.oneOf(['net::ERR_FAILED', 'net::ERR_CONNECTION_RESET', 'net::ERR_CONNECTION_ABORTED']);
- });
- it('should not emit any event after close', async () => {
- const serverUrl = await respondOnce.toSingleURL((request, response) => {
- response.end();
+ test('should remove the referer header when no referrer url specified', async () => {
+ const serverUrl = await respondOnce.toSingleURL((request, response) => {
+ expect(request.headers.referer).to.equal(undefined);
+ response.statusCode = 200;
+ response.statusMessage = 'OK';
+ response.end();
+ });
+ const urlRequest = net.request(serverUrl);
+ urlRequest.end();
+
+ const response = await getResponse(urlRequest);
+ expect(response.statusCode).to.equal(200);
+ await collectStreamBody(response);
});
- const urlRequest = net.request(serverUrl);
- urlRequest.end();
+ test('should set the referer header when a referrer url specified', async () => {
+ const referrerURL = 'https://www.electronjs.org/';
+ const serverUrl = await respondOnce.toSingleURL((request, response) => {
+ expect(request.headers.referer).to.equal(referrerURL);
+ response.statusCode = 200;
+ response.statusMessage = 'OK';
+ response.end();
+ });
+ // The referrerPolicy must be unsafe-url because the referrer's origin
+ // doesn't match the loaded page. With the default referrer policy
+ // (strict-origin-when-cross-origin), the request will be canceled by the
+ // network service when the referrer header is invalid.
+ // See:
+ // - https://source.chromium.org/chromium/chromium/src/+/main:net/url_request/url_request.cc;l=682-683;drc=ae587fa7cd2e5cc308ce69353ee9ce86437e5d41
+ // - https://source.chromium.org/chromium/chromium/src/+/main:services/network/public/mojom/network_context.mojom;l=316-318;drc=ae5c7fcf09509843c1145f544cce3a61874b9698
+ // - https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer
+ const urlRequest = net.request({ url: serverUrl, referrerPolicy: 'unsafe-url' });
+ urlRequest.setHeader('referer', referrerURL);
+ urlRequest.end();
- await once(urlRequest, 'close');
- await new Promise((resolve, reject) => {
- for (const evName of ['finish', 'abort', 'close', 'error']) {
- urlRequest.on(evName as any, () => {
- reject(new Error(`Unexpected ${evName} event`));
- });
- }
- setTimeout(50).then(resolve);
+ const response = await getResponse(urlRequest);
+ expect(response.statusCode).to.equal(200);
+ await collectStreamBody(response);
});
});
- it('should remove the referer header when no referrer url specified', async () => {
- const serverUrl = await respondOnce.toSingleURL((request, response) => {
- expect(request.headers.referer).to.equal(undefined);
- response.statusCode = 200;
- response.statusMessage = 'OK';
- response.end();
- });
- const urlRequest = net.request(serverUrl);
- urlRequest.end();
+ describe('IncomingMessage API', () => {
+ test('response object should implement the IncomingMessage API', async () => {
+ const customHeaderName = 'Some-Custom-Header-Name';
+ const customHeaderValue = 'Some-Customer-Header-Value';
- const response = await getResponse(urlRequest);
- expect(response.statusCode).to.equal(200);
- await collectStreamBody(response);
- });
+ const serverUrl = await respondOnce.toSingleURL((request, response) => {
+ response.statusCode = 200;
+ response.statusMessage = 'OK';
+ response.setHeader(customHeaderName, customHeaderValue);
+ response.end();
+ });
- it('should set the referer header when a referrer url specified', async () => {
- const referrerURL = 'https://www.electronjs.org/';
- const serverUrl = await respondOnce.toSingleURL((request, response) => {
- expect(request.headers.referer).to.equal(referrerURL);
- response.statusCode = 200;
- response.statusMessage = 'OK';
- response.end();
- });
- // The referrerPolicy must be unsafe-url because the referrer's origin
- // doesn't match the loaded page. With the default referrer policy
- // (strict-origin-when-cross-origin), the request will be canceled by the
- // network service when the referrer header is invalid.
- // See:
- // - https://source.chromium.org/chromium/chromium/src/+/main:net/url_request/url_request.cc;l=682-683;drc=ae587fa7cd2e5cc308ce69353ee9ce86437e5d41
- // - https://source.chromium.org/chromium/chromium/src/+/main:services/network/public/mojom/network_context.mojom;l=316-318;drc=ae5c7fcf09509843c1145f544cce3a61874b9698
- // - https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer
- const urlRequest = net.request({ url: serverUrl, referrerPolicy: 'unsafe-url' });
- urlRequest.setHeader('referer', referrerURL);
- urlRequest.end();
-
- const response = await getResponse(urlRequest);
- expect(response.statusCode).to.equal(200);
- await collectStreamBody(response);
- });
- });
+ const urlRequest = net.request(serverUrl);
+ const response = await getResponse(urlRequest);
- describe('IncomingMessage API', () => {
- it('response object should implement the IncomingMessage API', async () => {
- const customHeaderName = 'Some-Custom-Header-Name';
- const customHeaderValue = 'Some-Customer-Header-Value';
+ expect(response.statusCode).to.equal(200);
+ expect(response.statusMessage).to.equal('OK');
- const serverUrl = await respondOnce.toSingleURL((request, response) => {
- response.statusCode = 200;
- response.statusMessage = 'OK';
- response.setHeader(customHeaderName, customHeaderValue);
- response.end();
- });
+ const headers = response.headers;
+ expect(headers).to.be.an('object');
+ const headerValue = headers[customHeaderName.toLowerCase()];
+ expect(headerValue).to.equal(customHeaderValue);
- const urlRequest = net.request(serverUrl);
- const response = await getResponse(urlRequest);
+ const rawHeaders = response.rawHeaders;
+ expect(rawHeaders).to.be.an('array');
+ expect(rawHeaders[0]).to.equal(customHeaderName);
+ expect(rawHeaders[1]).to.equal(customHeaderValue);
- expect(response.statusCode).to.equal(200);
- expect(response.statusMessage).to.equal('OK');
+ const httpVersion = response.httpVersion;
+ expect(httpVersion).to.be.a('string').and.to.have.lengthOf.at.least(1);
- const headers = response.headers;
- expect(headers).to.be.an('object');
- const headerValue = headers[customHeaderName.toLowerCase()];
- expect(headerValue).to.equal(customHeaderValue);
+ const httpVersionMajor = response.httpVersionMajor;
+ expect(httpVersionMajor).to.be.a('number').and.to.be.at.least(1);
- const rawHeaders = response.rawHeaders;
- expect(rawHeaders).to.be.an('array');
- expect(rawHeaders[0]).to.equal(customHeaderName);
- expect(rawHeaders[1]).to.equal(customHeaderValue);
+ const httpVersionMinor = response.httpVersionMinor;
+ expect(httpVersionMinor).to.be.a('number').and.to.be.at.least(0);
- const httpVersion = response.httpVersion;
- expect(httpVersion).to.be.a('string').and.to.have.lengthOf.at.least(1);
+ await collectStreamBody(response);
+ });
- const httpVersionMajor = response.httpVersionMajor;
- expect(httpVersionMajor).to.be.a('number').and.to.be.at.least(1);
+ test('should discard duplicate headers', async () => {
+ const includedHeader = 'max-forwards';
+ const discardableHeader = 'Max-Forwards';
- const httpVersionMinor = response.httpVersionMinor;
- expect(httpVersionMinor).to.be.a('number').and.to.be.at.least(0);
+ const includedHeaderValue = 'max-fwds-val';
+ const discardableHeaderValue = 'max-fwds-val-two';
- await collectStreamBody(response);
- });
+ const serverUrl = await respondOnce.toSingleURL((request, response) => {
+ response.statusCode = 200;
+ response.statusMessage = 'OK';
+ response.setHeader(discardableHeader, discardableHeaderValue);
+ response.setHeader(includedHeader, includedHeaderValue);
+ response.end();
+ });
+ const urlRequest = net.request(serverUrl);
+ const response = await getResponse(urlRequest);
+ expect(response.statusCode).to.equal(200);
+ expect(response.statusMessage).to.equal('OK');
- it('should discard duplicate headers', async () => {
- const includedHeader = 'max-forwards';
- const discardableHeader = 'Max-Forwards';
+ const headers = response.headers;
+ expect(headers).to.be.an('object');
- const includedHeaderValue = 'max-fwds-val';
- const discardableHeaderValue = 'max-fwds-val-two';
+ expect(headers).to.have.property(includedHeader);
+ expect(headers).to.not.have.property(discardableHeader);
+ expect(headers[includedHeader]).to.equal(includedHeaderValue);
- const serverUrl = await respondOnce.toSingleURL((request, response) => {
- response.statusCode = 200;
- response.statusMessage = 'OK';
- response.setHeader(discardableHeader, discardableHeaderValue);
- response.setHeader(includedHeader, includedHeaderValue);
- response.end();
+ await collectStreamBody(response);
});
- const urlRequest = net.request(serverUrl);
- const response = await getResponse(urlRequest);
- expect(response.statusCode).to.equal(200);
- expect(response.statusMessage).to.equal('OK');
- const headers = response.headers;
- expect(headers).to.be.an('object');
-
- expect(headers).to.have.property(includedHeader);
- expect(headers).to.not.have.property(discardableHeader);
- expect(headers[includedHeader]).to.equal(includedHeaderValue);
+ test('should join repeated non-discardable header values with ,', async () => {
+ const serverUrl = await respondOnce.toSingleURL((request, response) => {
+ response.statusCode = 200;
+ response.statusMessage = 'OK';
+ response.setHeader('referrer-policy', ['first-text', 'second-text']);
+ response.end();
+ });
+ const urlRequest = net.request(serverUrl);
+ const response = await getResponse(urlRequest);
+ expect(response.statusCode).to.equal(200);
+ expect(response.statusMessage).to.equal('OK');
- await collectStreamBody(response);
- });
+ const headers = response.headers;
+ expect(headers).to.be.an('object');
+ expect(headers).to.have.property('referrer-policy');
+ expect(headers['referrer-policy']).to.equal('first-text, second-text');
- it('should join repeated non-discardable header values with ,', async () => {
- const serverUrl = await respondOnce.toSingleURL((request, response) => {
- response.statusCode = 200;
- response.statusMessage = 'OK';
- response.setHeader('referrer-policy', ['first-text', 'second-text']);
- response.end();
+ await collectStreamBody(response);
});
- const urlRequest = net.request(serverUrl);
- const response = await getResponse(urlRequest);
- expect(response.statusCode).to.equal(200);
- expect(response.statusMessage).to.equal('OK');
- const headers = response.headers;
- expect(headers).to.be.an('object');
- expect(headers).to.have.property('referrer-policy');
- expect(headers['referrer-policy']).to.equal('first-text, second-text');
+ test('should not join repeated discardable header values with ,', async () => {
+ const serverUrl = await respondOnce.toSingleURL((request, response) => {
+ response.statusCode = 200;
+ response.statusMessage = 'OK';
+ response.setHeader('last-modified', ['yesterday', 'today']);
+ response.end();
+ });
+ const urlRequest = net.request(serverUrl);
+ const response = await getResponse(urlRequest);
+ expect(response.statusCode).to.equal(200);
+ expect(response.statusMessage).to.equal('OK');
- await collectStreamBody(response);
- });
+ const headers = response.headers;
+ expect(headers).to.be.an('object');
+ expect(headers).to.have.property('last-modified');
+ expect(headers['last-modified']).to.equal('yesterday');
- it('should not join repeated discardable header values with ,', async () => {
- const serverUrl = await respondOnce.toSingleURL((request, response) => {
- response.statusCode = 200;
- response.statusMessage = 'OK';
- response.setHeader('last-modified', ['yesterday', 'today']);
- response.end();
+ await collectStreamBody(response);
});
- const urlRequest = net.request(serverUrl);
- const response = await getResponse(urlRequest);
- expect(response.statusCode).to.equal(200);
- expect(response.statusMessage).to.equal('OK');
- const headers = response.headers;
- expect(headers).to.be.an('object');
- expect(headers).to.have.property('last-modified');
- expect(headers['last-modified']).to.equal('yesterday');
+ test('should make set-cookie header an array even if single value', async () => {
+ const serverUrl = await respondOnce.toSingleURL((request, response) => {
+ response.statusCode = 200;
+ response.statusMessage = 'OK';
+ response.setHeader('set-cookie', 'chocolate-chip');
+ response.end();
+ });
+ const urlRequest = net.request(serverUrl);
+ const response = await getResponse(urlRequest);
+ expect(response.statusCode).to.equal(200);
+ expect(response.statusMessage).to.equal('OK');
- await collectStreamBody(response);
- });
+ const headers = response.headers;
+ expect(headers).to.be.an('object');
+ expect(headers).to.have.property('set-cookie');
+ expect(headers['set-cookie']).to.be.an('array');
+ expect(headers['set-cookie'][0]).to.equal('chocolate-chip');
- it('should make set-cookie header an array even if single value', async () => {
- const serverUrl = await respondOnce.toSingleURL((request, response) => {
- response.statusCode = 200;
- response.statusMessage = 'OK';
- response.setHeader('set-cookie', 'chocolate-chip');
- response.end();
- });
- const urlRequest = net.request(serverUrl);
- const response = await getResponse(urlRequest);
- expect(response.statusCode).to.equal(200);
- expect(response.statusMessage).to.equal('OK');
-
- const headers = response.headers;
- expect(headers).to.be.an('object');
- expect(headers).to.have.property('set-cookie');
- expect(headers['set-cookie']).to.be.an('array');
- expect(headers['set-cookie'][0]).to.equal('chocolate-chip');
-
- await collectStreamBody(response);
- });
+ await collectStreamBody(response);
+ });
- it('should keep set-cookie header an array when an array', async () => {
- const serverUrl = await respondOnce.toSingleURL((request, response) => {
- response.statusCode = 200;
- response.statusMessage = 'OK';
- response.setHeader('set-cookie', ['chocolate-chip', 'oatmeal']);
- response.end();
- });
- const urlRequest = net.request(serverUrl);
- const response = await getResponse(urlRequest);
- expect(response.statusCode).to.equal(200);
- expect(response.statusMessage).to.equal('OK');
-
- const headers = response.headers;
- expect(headers).to.be.an('object');
- expect(headers).to.have.property('set-cookie');
- expect(headers['set-cookie']).to.be.an('array');
- expect(headers['set-cookie'][0]).to.equal('chocolate-chip');
- expect(headers['set-cookie'][1]).to.equal('oatmeal');
-
- await collectStreamBody(response);
- });
+ test('should keep set-cookie header an array when an array', async () => {
+ const serverUrl = await respondOnce.toSingleURL((request, response) => {
+ response.statusCode = 200;
+ response.statusMessage = 'OK';
+ response.setHeader('set-cookie', ['chocolate-chip', 'oatmeal']);
+ response.end();
+ });
+ const urlRequest = net.request(serverUrl);
+ const response = await getResponse(urlRequest);
+ expect(response.statusCode).to.equal(200);
+ expect(response.statusMessage).to.equal('OK');
- it('should lowercase header keys', async () => {
- const serverUrl = await respondOnce.toSingleURL((request, response) => {
- response.statusCode = 200;
- response.statusMessage = 'OK';
- response.setHeader('HEADER-KEY', ['header-value']);
- response.setHeader('SeT-CookiE', ['chocolate-chip', 'oatmeal']);
- response.setHeader('rEFERREr-pOLICy', ['first-text', 'second-text']);
- response.setHeader('LAST-modified', 'yesterday');
+ const headers = response.headers;
+ expect(headers).to.be.an('object');
+ expect(headers).to.have.property('set-cookie');
+ expect(headers['set-cookie']).to.be.an('array');
+ expect(headers['set-cookie'][0]).to.equal('chocolate-chip');
+ expect(headers['set-cookie'][1]).to.equal('oatmeal');
- response.end();
+ await collectStreamBody(response);
});
- const urlRequest = net.request(serverUrl);
- const response = await getResponse(urlRequest);
- expect(response.statusCode).to.equal(200);
- expect(response.statusMessage).to.equal('OK');
- const headers = response.headers;
- expect(headers).to.be.an('object');
+ test('should lowercase header keys', async () => {
+ const serverUrl = await respondOnce.toSingleURL((request, response) => {
+ response.statusCode = 200;
+ response.statusMessage = 'OK';
+ response.setHeader('HEADER-KEY', ['header-value']);
+ response.setHeader('SeT-CookiE', ['chocolate-chip', 'oatmeal']);
+ response.setHeader('rEFERREr-pOLICy', ['first-text', 'second-text']);
+ response.setHeader('LAST-modified', 'yesterday');
- expect(headers).to.have.property('header-key');
- expect(headers).to.have.property('set-cookie');
- expect(headers).to.have.property('referrer-policy');
- expect(headers).to.have.property('last-modified');
+ response.end();
+ });
+ const urlRequest = net.request(serverUrl);
+ const response = await getResponse(urlRequest);
+ expect(response.statusCode).to.equal(200);
+ expect(response.statusMessage).to.equal('OK');
- await collectStreamBody(response);
- });
+ const headers = response.headers;
+ expect(headers).to.be.an('object');
- it('should return correct raw headers', async () => {
- const customHeaders: [string, string|string[]][] = [
- ['HEADER-KEY-ONE', 'header-value-one'],
- ['set-cookie', 'chocolate-chip'],
- ['header-key-two', 'header-value-two'],
- ['referrer-policy', ['first-text', 'second-text']],
- ['HEADER-KEY-THREE', 'header-value-three'],
- ['last-modified', ['first-text', 'second-text']],
- ['header-key-four', 'header-value-four']
- ];
-
- const serverUrl = await respondOnce.toSingleURL((request, response) => {
- response.statusCode = 200;
- response.statusMessage = 'OK';
- for (const headerTuple of customHeaders) {
- response.setHeader(headerTuple[0], headerTuple[1]);
- }
- response.end();
- });
- const urlRequest = net.request(serverUrl);
- const response = await getResponse(urlRequest);
- expect(response.statusCode).to.equal(200);
- expect(response.statusMessage).to.equal('OK');
-
- const rawHeaders = response.rawHeaders;
- expect(rawHeaders).to.be.an('array');
-
- let rawHeadersIdx = 0;
- for (const headerTuple of customHeaders) {
- const headerKey = headerTuple[0];
- const headerValues = Array.isArray(headerTuple[1]) ? headerTuple[1] : [headerTuple[1]];
- for (const headerValue of headerValues) {
- expect(rawHeaders[rawHeadersIdx]).to.equal(headerKey);
- expect(rawHeaders[rawHeadersIdx + 1]).to.equal(headerValue);
- rawHeadersIdx += 2;
- }
- }
+ expect(headers).to.have.property('header-key');
+ expect(headers).to.have.property('set-cookie');
+ expect(headers).to.have.property('referrer-policy');
+ expect(headers).to.have.property('last-modified');
- await collectStreamBody(response);
- });
+ await collectStreamBody(response);
+ });
- it('should be able to pipe a net response into a writable stream', async () => {
- const bodyData = randomString(kOneKiloByte);
- let nodeRequestProcessed = false;
- const [netServerUrl, nodeServerUrl] = await Promise.all([
- respondOnce.toSingleURL((request, response) => response.end(bodyData)),
- respondOnce.toSingleURL(async (request, response) => {
- const receivedBodyData = await collectStreamBody(request);
- expect(receivedBodyData).to.be.equal(bodyData);
- nodeRequestProcessed = true;
- response.end();
- })
- ]);
- const netRequest = net.request(netServerUrl);
- const netResponse = await getResponse(netRequest);
- const serverUrl = url.parse(nodeServerUrl);
- const nodeOptions = {
- method: 'POST',
- path: serverUrl.path,
- port: serverUrl.port
- };
- const nodeRequest = http.request(nodeOptions);
- const nodeResponsePromise = once(nodeRequest, 'response');
- // TODO(@MarshallOfSound) - FIXME with #22730
- (netResponse as any).pipe(nodeRequest);
- const [nodeResponse] = await nodeResponsePromise;
- netRequest.end();
- await collectStreamBody(nodeResponse);
- expect(nodeRequestProcessed).to.equal(true);
- });
+ test('should return correct raw headers', async () => {
+ const customHeaders: [string, string|string[]][] = [
+ ['HEADER-KEY-ONE', 'header-value-one'],
+ ['set-cookie', 'chocolate-chip'],
+ ['header-key-two', 'header-value-two'],
+ ['referrer-policy', ['first-text', 'second-text']],
+ ['HEADER-KEY-THREE', 'header-value-three'],
+ ['last-modified', ['first-text', 'second-text']],
+ ['header-key-four', 'header-value-four']
+ ];
- it('should correctly throttle an incoming stream', async () => {
- let numChunksSent = 0;
- const serverUrl = await respondOnce.toSingleURL((request, response) => {
- const data = randomString(kOneMegaByte);
- const write = () => {
- let ok = true;
- do {
- numChunksSent++;
- if (numChunksSent > 30) return;
- ok = response.write(data);
- } while (ok);
- response.once('drain', write);
- };
- write();
- });
- const urlRequest = net.request(serverUrl);
- urlRequest.on('response', () => {});
- urlRequest.end();
- await setTimeout(2000);
- // TODO(nornagon): I think this ought to max out at 20, but in practice
- // it seems to exceed that sometimes. This is at 25 to avoid test flakes,
- // but we should investigate if there's actually something broken here and
- // if so fix it and reset this to max at 20, and if not then delete this
- // comment.
- expect(numChunksSent).to.be.at.most(25);
- });
- });
+ const serverUrl = await respondOnce.toSingleURL((request, response) => {
+ response.statusCode = 200;
+ response.statusMessage = 'OK';
+ for (const headerTuple of customHeaders) {
+ response.setHeader(headerTuple[0], headerTuple[1]);
+ }
+ response.end();
+ });
+ const urlRequest = net.request(serverUrl);
+ const response = await getResponse(urlRequest);
+ expect(response.statusCode).to.equal(200);
+ expect(response.statusMessage).to.equal('OK');
- describe('net.isOnline', () => {
- it('getter returns boolean', () => {
- expect(net.isOnline()).to.be.a('boolean');
- });
+ const rawHeaders = response.rawHeaders;
+ expect(rawHeaders).to.be.an('array');
- it('property returns boolean', () => {
- expect(net.online).to.be.a('boolean');
- });
- });
+ let rawHeadersIdx = 0;
+ for (const headerTuple of customHeaders) {
+ const headerKey = headerTuple[0];
+ const headerValues = Array.isArray(headerTuple[1]) ? headerTuple[1] : [headerTuple[1]];
+ for (const headerValue of headerValues) {
+ expect(rawHeaders[rawHeadersIdx]).to.equal(headerKey);
+ expect(rawHeaders[rawHeadersIdx + 1]).to.equal(headerValue);
+ rawHeadersIdx += 2;
+ }
+ }
- describe('Stability and performance', () => {
- it('should free unreferenced, never-started request objects without crash', (done) => {
- net.request('https://test');
- process.nextTick(() => {
- const v8Util = process._linkedBinding('electron_common_v8_util');
- v8Util.requestGarbageCollectionForTesting();
- done();
+ await collectStreamBody(response);
});
- });
- it('should collect on-going requests without crash', async () => {
- let finishResponse: (() => void) | null = null;
- const serverUrl = await respondOnce.toSingleURL((request, response) => {
- response.write(randomString(kOneKiloByte));
- finishResponse = () => {
- response.write(randomString(kOneKiloByte));
- response.end();
+ test('should be able to pipe a net response into a writable stream', async () => {
+ const bodyData = randomString(kOneKiloByte);
+ let nodeRequestProcessed = false;
+ const [netServerUrl, nodeServerUrl] = await Promise.all([
+ respondOnce.toSingleURL((request, response) => response.end(bodyData)),
+ respondOnce.toSingleURL(async (request, response) => {
+ const receivedBodyData = await collectStreamBody(request);
+ expect(receivedBodyData).to.be.equal(bodyData);
+ nodeRequestProcessed = true;
+ response.end();
+ })
+ ]);
+ const netRequest = net.request(netServerUrl);
+ const netResponse = await getResponse(netRequest);
+ const serverUrl = url.parse(nodeServerUrl);
+ const nodeOptions = {
+ method: 'POST',
+ path: serverUrl.path,
+ port: serverUrl.port
};
+ const nodeRequest = http.request(nodeOptions);
+ const nodeResponsePromise = once(nodeRequest, 'response');
+ // TODO(@MarshallOfSound) - FIXME with #22730
+ (netResponse as any).pipe(nodeRequest);
+ const [nodeResponse] = await nodeResponsePromise;
+ netRequest.end();
+ await collectStreamBody(nodeResponse);
+ expect(nodeRequestProcessed).to.equal(true);
+ });
+
+ test('should correctly throttle an incoming stream', async () => {
+ let numChunksSent = 0;
+ const serverUrl = await respondOnce.toSingleURL((request, response) => {
+ const data = randomString(kOneMegaByte);
+ const write = () => {
+ let ok = true;
+ do {
+ numChunksSent++;
+ if (numChunksSent > 30) return;
+ ok = response.write(data);
+ } while (ok);
+ response.once('drain', write);
+ };
+ write();
+ });
+ const urlRequest = net.request(serverUrl);
+ urlRequest.on('response', () => {});
+ urlRequest.end();
+ await setTimeout(2000);
+ // TODO(nornagon): I think this ought to max out at 20, but in practice
+ // it seems to exceed that sometimes. This is at 25 to avoid test flakes,
+ // but we should investigate if there's actually something broken here and
+ // if so fix it and reset this to max at 20, and if not then delete this
+ // comment.
+ expect(numChunksSent).to.be.at.most(25);
});
- const urlRequest = net.request(serverUrl);
- const response = await getResponse(urlRequest);
- process.nextTick(() => {
- // Trigger a garbage collection.
- const v8Util = process._linkedBinding('electron_common_v8_util');
- v8Util.requestGarbageCollectionForTesting();
- finishResponse!();
- });
- await collectStreamBody(response);
});
- it('should collect unreferenced, ended requests without crash', async () => {
- const serverUrl = await respondOnce.toSingleURL((request, response) => {
- response.end();
+ describe('net.isOnline', () => {
+ test('getter returns boolean', () => {
+ expect(net.isOnline()).to.be.a('boolean');
});
- const urlRequest = net.request(serverUrl);
- process.nextTick(() => {
- const v8Util = process._linkedBinding('electron_common_v8_util');
- v8Util.requestGarbageCollectionForTesting();
+
+ test('property returns boolean', () => {
+ expect(net.online).to.be.a('boolean');
});
- const response = await getResponse(urlRequest);
- await collectStreamBody(response);
});
- it('should finish sending data when urlRequest is unreferenced', async () => {
- const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
- const received = await collectStreamBodyBuffer(request);
- expect(received.length).to.equal(kOneMegaByte);
- response.end();
+ describe('Stability and performance', () => {
+ test('should free unreferenced, never-started request objects without crash', async () => {
+ net.request('https://test');
+ await new Promise<void>((resolve) => {
+ process.nextTick(() => {
+ const v8Util = process._linkedBinding('electron_common_v8_util');
+ v8Util.requestGarbageCollectionForTesting();
+ resolve();
+ });
+ });
});
- const urlRequest = net.request(serverUrl);
- urlRequest.on('close', () => {
+
+ test('should collect on-going requests without crash', async () => {
+ let finishResponse: (() => void) | null = null;
+ const serverUrl = await respondOnce.toSingleURL((request, response) => {
+ response.write(randomString(kOneKiloByte));
+ finishResponse = () => {
+ response.write(randomString(kOneKiloByte));
+ response.end();
+ };
+ });
+ const urlRequest = net.request(serverUrl);
+ const response = await getResponse(urlRequest);
process.nextTick(() => {
+ // Trigger a garbage collection.
const v8Util = process._linkedBinding('electron_common_v8_util');
v8Util.requestGarbageCollectionForTesting();
+ finishResponse!();
});
+ await collectStreamBody(response);
});
- urlRequest.write(randomBuffer(kOneMegaByte));
- const response = await getResponse(urlRequest);
- await collectStreamBody(response);
- });
-
- it('should finish sending data when urlRequest is unreferenced for chunked encoding', async () => {
- const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
- const received = await collectStreamBodyBuffer(request);
- response.end();
- expect(received.length).to.equal(kOneMegaByte);
- });
- const urlRequest = net.request(serverUrl);
- urlRequest.chunkedEncoding = true;
- urlRequest.write(randomBuffer(kOneMegaByte));
- const response = await getResponse(urlRequest);
- await collectStreamBody(response);
- process.nextTick(() => {
- const v8Util = process._linkedBinding('electron_common_v8_util');
- v8Util.requestGarbageCollectionForTesting();
- });
- });
-
- it('should finish sending data when urlRequest is unreferenced before close event for chunked encoding', async () => {
- const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
- const received = await collectStreamBodyBuffer(request);
- response.end();
- expect(received.length).to.equal(kOneMegaByte);
- });
- const urlRequest = net.request(serverUrl);
- urlRequest.chunkedEncoding = true;
- urlRequest.write(randomBuffer(kOneMegaByte));
- const v8Util = process._linkedBinding('electron_common_v8_util');
- v8Util.requestGarbageCollectionForTesting();
- await collectStreamBody(await getResponse(urlRequest));
- });
- it('should finish sending data when urlRequest is unreferenced', async () => {
- const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
- const received = await collectStreamBodyBuffer(request);
- response.end();
- expect(received.length).to.equal(kOneMegaByte);
- });
- const urlRequest = net.request(serverUrl);
- urlRequest.on('close', () => {
+ test('should collect unreferenced, ended requests without crash', async () => {
+ const serverUrl = await respondOnce.toSingleURL((request, response) => {
+ response.end();
+ });
+ const urlRequest = net.request(serverUrl);
process.nextTick(() => {
const v8Util = process._linkedBinding('electron_common_v8_util');
v8Util.requestGarbageCollectionForTesting();
});
+ const response = await getResponse(urlRequest);
+ await collectStreamBody(response);
});
- urlRequest.write(randomBuffer(kOneMegaByte));
- await collectStreamBody(await getResponse(urlRequest));
- });
- it('should finish sending data when urlRequest is unreferenced for chunked encoding', async () => {
- const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
- const received = await collectStreamBodyBuffer(request);
- response.end();
- expect(received.length).to.equal(kOneMegaByte);
+ test('should finish sending data when urlRequest is unreferenced', async () => {
+ const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
+ const received = await collectStreamBodyBuffer(request);
+ expect(received.length).to.equal(kOneMegaByte);
+ response.end();
+ });
+ const urlRequest = net.request(serverUrl);
+ urlRequest.on('close', () => {
+ process.nextTick(() => {
+ const v8Util = process._linkedBinding('electron_common_v8_util');
+ v8Util.requestGarbageCollectionForTesting();
+ });
+ });
+ urlRequest.write(randomBuffer(kOneMegaByte));
+ const response = await getResponse(urlRequest);
+ await collectStreamBody(response);
});
- const urlRequest = net.request(serverUrl);
- urlRequest.on('close', () => {
+
+ test('should finish sending data when urlRequest is unreferenced for chunked encoding', async () => {
+ const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
+ const received = await collectStreamBodyBuffer(request);
+ response.end();
+ expect(received.length).to.equal(kOneMegaByte);
+ });
+ const urlRequest = net.request(serverUrl);
+ urlRequest.chunkedEncoding = true;
+ urlRequest.write(randomBuffer(kOneMegaByte));
+ const response = await getResponse(urlRequest);
+ await collectStreamBody(response);
process.nextTick(() => {
const v8Util = process._linkedBinding('electron_common_v8_util');
v8Util.requestGarbageCollectionForTesting();
});
});
- urlRequest.chunkedEncoding = true;
- urlRequest.write(randomBuffer(kOneMegaByte));
- await collectStreamBody(await getResponse(urlRequest));
- });
- });
-
- describe('non-http schemes', () => {
- it('should be rejected by net.request', async () => {
- expect(() => {
- net.request('file://bar');
- }).to.throw('ClientRequest only supports http: and https: protocols');
- });
-
- it('should be rejected by net.request when passed in url:', async () => {
- expect(() => {
- net.request({ url: 'file://bar' });
- }).to.throw('ClientRequest only supports http: and https: protocols');
- });
- });
- describe('net.fetch', () => {
- // NB. there exist much more comprehensive tests for fetch() in the form of
- // the WPT: https://github.com/web-platform-tests/wpt/tree/master/fetch
- // It's possible to run these tests against net.fetch(), but the test
- // harness to do so is quite complex and hasn't been munged to smoothly run
- // inside the Electron test runner yet.
- //
- // In the meantime, here are some tests for basic functionality and
- // Electron-specific behavior.
-
- describe('basic', () => {
- it('can fetch http urls', async () => {
- const serverUrl = await respondOnce.toSingleURL((request, response) => {
- response.end('test');
+ test('should finish sending data when urlRequest is unreferenced before close event for chunked encoding', async () => {
+ const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
+ const received = await collectStreamBodyBuffer(request);
+ response.end();
+ expect(received.length).to.equal(kOneMegaByte);
});
- const resp = await net.fetch(serverUrl);
- expect(resp.ok).to.be.true();
- expect(await resp.text()).to.equal('test');
+ const urlRequest = net.request(serverUrl);
+ urlRequest.chunkedEncoding = true;
+ urlRequest.write(randomBuffer(kOneMegaByte));
+ const v8Util = process._linkedBinding('electron_common_v8_util');
+ v8Util.requestGarbageCollectionForTesting();
+ await collectStreamBody(await getResponse(urlRequest));
});
- it('can upload a string body', async () => {
- const serverUrl = await respondOnce.toSingleURL((request, response) => {
- request.on('data', chunk => response.write(chunk));
- request.on('end', () => response.end());
+ test('should finish sending data when urlRequest is unreferenced', async () => {
+ const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
+ const received = await collectStreamBodyBuffer(request);
+ response.end();
+ expect(received.length).to.equal(kOneMegaByte);
});
- const resp = await net.fetch(serverUrl, {
- method: 'POST',
- body: 'anchovies'
+ const urlRequest = net.request(serverUrl);
+ urlRequest.on('close', () => {
+ process.nextTick(() => {
+ const v8Util = process._linkedBinding('electron_common_v8_util');
+ v8Util.requestGarbageCollectionForTesting();
+ });
});
- expect(await resp.text()).to.equal('anchovies');
+ urlRequest.write(randomBuffer(kOneMegaByte));
+ await collectStreamBody(await getResponse(urlRequest));
});
- it('can read response as an array buffer', async () => {
- const serverUrl = await respondOnce.toSingleURL((request, response) => {
- request.on('data', chunk => response.write(chunk));
- request.on('end', () => response.end());
+ test('should finish sending data when urlRequest is unreferenced for chunked encoding', async () => {
+ const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
+ const received = await collectStreamBodyBuffer(request);
+ response.end();
+ expect(received.length).to.equal(kOneMegaByte);
});
- const resp = await net.fetch(serverUrl, {
- method: 'POST',
- body: 'anchovies'
+ const urlRequest = net.request(serverUrl);
+ urlRequest.on('close', () => {
+ process.nextTick(() => {
+ const v8Util = process._linkedBinding('electron_common_v8_util');
+ v8Util.requestGarbageCollectionForTesting();
+ });
});
- expect(new TextDecoder().decode(new Uint8Array(await resp.arrayBuffer()))).to.equal('anchovies');
+ urlRequest.chunkedEncoding = true;
+ urlRequest.write(randomBuffer(kOneMegaByte));
+ await collectStreamBody(await getResponse(urlRequest));
+ });
+ });
+
+ describe('non-http schemes', () => {
+ test('should be rejected by net.request', async () => {
+ expect(() => {
+ net.request('file://bar');
+ }).to.throw('ClientRequest only supports http: and https: protocols');
});
- it('can read response as form data', async () => {
- const serverUrl = await respondOnce.toSingleURL((request, response) => {
- response.setHeader('content-type', 'application/x-www-form-urlencoded');
- response.end('foo=bar');
- });
- const resp = await net.fetch(serverUrl);
- const result = await resp.formData();
- expect(result.get('foo')).to.equal('bar');
+ test('should be rejected by net.request when passed in url:', async () => {
+ expect(() => {
+ net.request({ url: 'file://bar' });
+ }).to.throw('ClientRequest only supports http: and https: protocols');
});
+ });
- it('should be able to use a session cookie store', async () => {
- const serverUrl = await respondOnce.toSingleURL((request, response) => {
- response.statusCode = 200;
- response.statusMessage = 'OK';
- response.setHeader('x-cookie', request.headers.cookie!);
- response.end();
- });
- const sess = session.fromPartition(`cookie-tests-${Math.random()}`);
- const cookieVal = `${Date.now()}`;
- await sess.cookies.set({
- url: serverUrl,
- name: 'wild_cookie',
- value: cookieVal
+ describe('net.fetch', () => {
+ // NB. there exist much more comprehensive tests for fetch() in the form of
+ // the WPT: https://github.com/web-platform-tests/wpt/tree/master/fetch
+ // It's possible to run these tests against net.fetch(), but the test
+ // harness to do so is quite complex and hasn't been munged to smoothly run
+ // inside the Electron test runner yet.
+ //
+ // In the meantime, here are some tests for basic functionality and
+ // Electron-specific behavior.
+
+ describe('basic', () => {
+ test('can fetch http urls', async () => {
+ const serverUrl = await respondOnce.toSingleURL((request, response) => {
+ response.end('test');
+ });
+ const resp = await net.fetch(serverUrl);
+ expect(resp.ok).to.be.true();
+ expect(await resp.text()).to.equal('test');
});
- const response = await sess.fetch(serverUrl, {
- credentials: 'include'
+
+ test('can upload a string body', async () => {
+ const serverUrl = await respondOnce.toSingleURL((request, response) => {
+ request.on('data', chunk => response.write(chunk));
+ request.on('end', () => response.end());
+ });
+ const resp = await net.fetch(serverUrl, {
+ method: 'POST',
+ body: 'anchovies'
+ });
+ expect(await resp.text()).to.equal('anchovies');
});
- expect(response.headers.get('x-cookie')).to.equal(`wild_cookie=${cookieVal}`);
- });
- it('should reject promise on DNS failure', async () => {
- const r = net.fetch('https://i.do.not.exist');
- await expect(r).to.be.rejectedWith(/ERR_NAME_NOT_RESOLVED/);
- });
+ test('can read response as an array buffer', async () => {
+ const serverUrl = await respondOnce.toSingleURL((request, response) => {
+ request.on('data', chunk => response.write(chunk));
+ request.on('end', () => response.end());
+ });
+ const resp = await net.fetch(serverUrl, {
+ method: 'POST',
+ body: 'anchovies'
+ });
+ expect(new TextDecoder().decode(new Uint8Array(await resp.arrayBuffer()))).to.equal('anchovies');
+ });
- it('should reject body promise when stream fails', async () => {
- const serverUrl = await respondOnce.toSingleURL((request, response) => {
- response.write('first chunk');
- setTimeout().then(() => response.destroy());
+ test('can read response as form data', async () => {
+ const serverUrl = await respondOnce.toSingleURL((request, response) => {
+ response.setHeader('content-type', 'application/x-www-form-urlencoded');
+ response.end('foo=bar');
+ });
+ const resp = await net.fetch(serverUrl);
+ const result = await resp.formData();
+ expect(result.get('foo')).to.equal('bar');
});
- const r = await net.fetch(serverUrl);
- expect(r.status).to.equal(200);
- await expect(r.text()).to.be.rejectedWith(/ERR_INCOMPLETE_CHUNKED_ENCODING/);
- });
- });
- it('can request file:// URLs', async () => {
- const resp = await net.fetch(url.pathToFileURL(path.join(__dirname, 'fixtures', 'hello.txt')).toString());
- expect(resp.ok).to.be.true();
- // trimRight instead of asserting the whole string to avoid line ending shenanigans on WOA
- expect((await resp.text()).trimRight()).to.equal('hello world');
- });
+ test('should reject promise on DNS failure', async () => {
+ const r = net.fetch('https://i.do.not.exist');
+ await expect(r).to.be.rejectedWith(/ERR_NAME_NOT_RESOLVED/);
+ });
- it('can make requests to custom protocols', async () => {
- protocol.registerStringProtocol('electron-test', (req, cb) => { cb('hello ' + req.url); });
- defer(() => {
- protocol.unregisterProtocol('electron-test');
+ test('should reject body promise when stream fails', async () => {
+ const serverUrl = await respondOnce.toSingleURL((request, response) => {
+ response.write('first chunk');
+ setTimeout().then(() => response.destroy());
+ });
+ const r = await net.fetch(serverUrl);
+ expect(r.status).to.equal(200);
+ await expect(r.text()).to.be.rejectedWith(/ERR_INCOMPLETE_CHUNKED_ENCODING/);
+ });
});
- const body = await net.fetch('electron-test://foo').then(r => r.text());
- expect(body).to.equal('hello electron-test://foo');
});
- it('runs through intercept handlers', async () => {
- protocol.interceptStringProtocol('http', (req, cb) => { cb('hello ' + req.url); });
- defer(() => {
- protocol.uninterceptProtocol('http');
+ describe('net.resolveHost', () => {
+ test('resolves ipv4.localhost2', async () => {
+ const { endpoints } = await net.resolveHost('ipv4.localhost2');
+ expect(endpoints).to.be.a('array');
+ expect(endpoints).to.have.lengthOf(1);
+ expect(endpoints[0].family).to.equal('ipv4');
+ expect(endpoints[0].address).to.equal('10.0.0.1');
});
- const body = await net.fetch('http://foo').then(r => r.text());
- expect(body).to.equal('hello http://foo/');
- });
- it('file: runs through intercept handlers', async () => {
- protocol.interceptStringProtocol('file', (req, cb) => { cb('hello ' + req.url); });
- defer(() => {
- protocol.uninterceptProtocol('file');
+ test('fails to resolve AAAA record for ipv4.localhost2', async () => {
+ await expect(net.resolveHost('ipv4.localhost2', {
+ queryType: 'AAAA'
+ }))
+ .to.eventually.be.rejectedWith(/net::ERR_NAME_NOT_RESOLVED/);
});
- const body = await net.fetch('file://foo').then(r => r.text());
- expect(body).to.equal('hello file://foo/');
- });
- it('can be redirected', async () => {
- protocol.interceptStringProtocol('file', (req, cb) => { cb({ statusCode: 302, headers: { location: 'electron-test://bar' } }); });
- defer(() => {
- protocol.uninterceptProtocol('file');
+ test('resolves ipv6.localhost2', async () => {
+ const { endpoints } = await net.resolveHost('ipv6.localhost2');
+ expect(endpoints).to.be.a('array');
+ expect(endpoints).to.have.lengthOf(1);
+ expect(endpoints[0].family).to.equal('ipv6');
+ expect(endpoints[0].address).to.equal('::1');
});
- protocol.registerStringProtocol('electron-test', (req, cb) => { cb('hello ' + req.url); });
- defer(() => {
- protocol.unregisterProtocol('electron-test');
- });
- const body = await net.fetch('file://foo').then(r => r.text());
- expect(body).to.equal('hello electron-test://bar');
- });
- it('should not follow redirect when redirect: error', async () => {
- protocol.registerStringProtocol('electron-test', (req, cb) => {
- if (/redirect/.test(req.url)) return cb({ statusCode: 302, headers: { location: 'electron-test://bar' } });
- cb('hello ' + req.url);
+ test('fails to resolve A record for ipv6.localhost2', async () => {
+ await expect(net.resolveHost('notfound.localhost2', {
+ queryType: 'A'
+ }))
+ .to.eventually.be.rejectedWith(/net::ERR_NAME_NOT_RESOLVED/);
});
- defer(() => {
- protocol.unregisterProtocol('electron-test');
- });
- await expect(net.fetch('electron-test://redirect', { redirect: 'error' })).to.eventually.be.rejectedWith('Attempted to redirect, but redirect policy was \'error\'');
- });
- it('a 307 redirected POST request preserves the body', async () => {
- const bodyData = 'Hello World!';
- let postedBodyData: any;
- protocol.registerStringProtocol('electron-test', async (req, cb) => {
- if (/redirect/.test(req.url)) return cb({ statusCode: 307, headers: { location: 'electron-test://bar' } });
- postedBodyData = req.uploadData![0].bytes.toString();
- cb('hello ' + req.url);
+ test('fails to resolve notfound.localhost2', async () => {
+ await expect(net.resolveHost('notfound.localhost2'))
+ .to.eventually.be.rejectedWith(/net::ERR_NAME_NOT_RESOLVED/);
});
- defer(() => {
- protocol.unregisterProtocol('electron-test');
- });
- const response = await net.fetch('electron-test://redirect', {
- method: 'POST',
- body: bodyData
- });
- expect(response.status).to.equal(200);
- await response.text();
- expect(postedBodyData).to.equal(bodyData);
});
- });
+ }
});
diff --git a/spec/fixtures/api/utility-process/api-net-spec.js b/spec/fixtures/api/utility-process/api-net-spec.js
new file mode 100644
index 0000000000..a97259cdf7
--- /dev/null
+++ b/spec/fixtures/api/utility-process/api-net-spec.js
@@ -0,0 +1,49 @@
+/* eslint-disable @typescript-eslint/no-unused-vars */
+/* eslint-disable camelcase */
+require('ts-node/register');
+
+const chai_1 = require('chai');
+const main_1 = require('electron/main');
+const http = require('node:http');
+const url = require('node:url');
+const node_events_1 = require('node:events');
+const promises_1 = require('node:timers/promises');
+const net_helpers_1 = require('../../../lib/net-helpers');
+const v8 = require('node:v8');
+
+v8.setFlagsFromString('--expose_gc');
+chai_1.use(require('chai-as-promised'));
+chai_1.use(require('dirty-chai'));
+
+function fail (message) {
+ process.parentPort.postMessage({ ok: false, message });
+}
+
+process.parentPort.on('message', async (e) => {
+ // Equivalent of beforeEach in spec/api-net-spec.ts
+ net_helpers_1.respondNTimes.routeFailure = false;
+
+ try {
+ if (e.data.args) {
+ for (const [key, value] of Object.entries(e.data.args)) {
+ // eslint-disable-next-line no-eval
+ eval(`var ${key} = value;`);
+ }
+ }
+ // eslint-disable-next-line no-eval
+ await eval(e.data.fn);
+ } catch (err) {
+ fail(`${err}`);
+ process.exit(1);
+ }
+
+ // Equivalent of afterEach in spec/api-net-spec.ts
+ if (net_helpers_1.respondNTimes.routeFailure) {
+ fail('Failing this test due an unhandled error in the respondOnce route handler, check the logs above for the actual error');
+ process.exit(1);
+ }
+
+ // Test passed
+ process.parentPort.postMessage({ ok: true });
+ process.exit(0);
+});
diff --git a/spec/lib/net-helpers.ts b/spec/lib/net-helpers.ts
new file mode 100644
index 0000000000..350885278c
--- /dev/null
+++ b/spec/lib/net-helpers.ts
@@ -0,0 +1,108 @@
+import { expect } from 'chai';
+import * as dns from 'node:dns';
+import * as http from 'node:http';
+import { Socket } from 'node:net';
+import { defer, listen } from './spec-helpers';
+
+// See https://github.com/nodejs/node/issues/40702.
+dns.setDefaultResultOrder('ipv4first');
+
+export const kOneKiloByte = 1024;
+export const kOneMegaByte = kOneKiloByte * kOneKiloByte;
+
+export function randomBuffer (size: number, start: number = 0, end: number = 255) {
+ const range = 1 + end - start;
+ const buffer = Buffer.allocUnsafe(size);
+ for (let i = 0; i < size; ++i) {
+ buffer[i] = start + Math.floor(Math.random() * range);
+ }
+ return buffer;
+}
+
+export function randomString (length: number) {
+ const buffer = randomBuffer(length, '0'.charCodeAt(0), 'z'.charCodeAt(0));
+ return buffer.toString();
+}
+
+export async function getResponse (urlRequest: Electron.ClientRequest) {
+ return new Promise<Electron.IncomingMessage>((resolve, reject) => {
+ urlRequest.on('error', reject);
+ urlRequest.on('abort', reject);
+ urlRequest.on('response', (response) => resolve(response));
+ urlRequest.end();
+ });
+}
+
+export async function collectStreamBody (response: Electron.IncomingMessage | http.IncomingMessage) {
+ return (await collectStreamBodyBuffer(response)).toString();
+}
+
+export function collectStreamBodyBuffer (response: Electron.IncomingMessage | http.IncomingMessage) {
+ return new Promise<Buffer>((resolve, reject) => {
+ response.on('error', reject);
+ (response as NodeJS.EventEmitter).on('aborted', reject);
+ const data: Buffer[] = [];
+ response.on('data', (chunk) => data.push(chunk));
+ response.on('end', (chunk?: Buffer) => {
+ if (chunk) data.push(chunk);
+ resolve(Buffer.concat(data));
+ });
+ });
+}
+
+export async function respondNTimes (fn: http.RequestListener, n: number): Promise<string> {
+ const server = http.createServer((request, response) => {
+ fn(request, response);
+ // don't close if a redirect was returned
+ if ((response.statusCode < 300 || response.statusCode >= 399) && n <= 0) {
+ n--;
+ server.close();
+ }
+ });
+ const sockets: Socket[] = [];
+ server.on('connection', s => sockets.push(s));
+ defer(() => {
+ server.close();
+ for (const socket of sockets) {
+ socket.destroy();
+ }
+ });
+ return (await listen(server)).url;
+}
+
+export function respondOnce (fn: http.RequestListener) {
+ return respondNTimes(fn, 1);
+}
+
+respondNTimes.routeFailure = false;
+
+respondNTimes.toRoutes = (routes: Record<string, http.RequestListener>, n: number) => {
+ return respondNTimes((request, response) => {
+ if (Object.hasOwn(routes, request.url || '')) {
+ (async () => {
+ await Promise.resolve(routes[request.url || ''](request, response));
+ })().catch((err) => {
+ respondNTimes.routeFailure = true;
+ console.error('Route handler failed, this is probably why your test failed', err);
+ response.statusCode = 500;
+ response.end();
+ });
+ } else {
+ response.statusCode = 500;
+ response.end();
+ expect.fail(`Unexpected URL: ${request.url}`);
+ }
+ }, n);
+};
+respondOnce.toRoutes = (routes: Record<string, http.RequestListener>) => respondNTimes.toRoutes(routes, 1);
+
+respondNTimes.toURL = (url: string, fn: http.RequestListener, n: number) => {
+ return respondNTimes.toRoutes({ [url]: fn }, n);
+};
+respondOnce.toURL = (url: string, fn: http.RequestListener) => respondNTimes.toURL(url, fn, 1);
+
+respondNTimes.toSingleURL = (fn: http.RequestListener, n: number) => {
+ const requestUrl = '/requestUrl';
+ return respondNTimes.toURL(requestUrl, fn, n).then(url => `${url}${requestUrl}`);
+};
+respondOnce.toSingleURL = (fn: http.RequestListener) => respondNTimes.toSingleURL(fn, 1);
diff --git a/typings/internal-ambient.d.ts b/typings/internal-ambient.d.ts
index cd657d304e..04a6ad6b7d 100644
--- a/typings/internal-ambient.d.ts
+++ b/typings/internal-ambient.d.ts
@@ -101,6 +101,7 @@ declare namespace NodeJS {
Net: any;
net: any;
createURLLoader(options: CreateURLLoaderOptions): URLLoader;
+ resolveHost(host: string, options?: Electron.ResolveHostOptions): Promise<Electron.ResolvedHost>;
}
interface NotificationBinding {
@@ -209,6 +210,7 @@ declare namespace NodeJS {
_linkedBinding(name: 'electron_common_environment'): EnvironmentBinding;
_linkedBinding(name: 'electron_common_features'): FeaturesBinding;
_linkedBinding(name: 'electron_common_native_image'): { nativeImage: typeof Electron.NativeImage };
+ _linkedBinding(name: 'electron_common_net'): NetBinding;
_linkedBinding(name: 'electron_common_shell'): Electron.Shell;
_linkedBinding(name: 'electron_common_v8_util'): V8UtilBinding;
_linkedBinding(name: 'electron_browser_app'): { app: Electron.App, App: Function };
@@ -221,7 +223,6 @@ declare namespace NodeJS {
_linkedBinding(name: 'electron_browser_in_app_purchase'): { inAppPurchase: Electron.InAppPurchase };
_linkedBinding(name: 'electron_browser_message_port'): { createPair(): { port1: Electron.MessagePortMain, port2: Electron.MessagePortMain }; };
_linkedBinding(name: 'electron_browser_native_theme'): { nativeTheme: Electron.NativeTheme };
- _linkedBinding(name: 'electron_browser_net'): NetBinding;
_linkedBinding(name: 'electron_browser_notification'): NotificationBinding;
_linkedBinding(name: 'electron_browser_power_monitor'): PowerMonitorBinding;
_linkedBinding(name: 'electron_browser_power_save_blocker'): { powerSaveBlocker: Electron.PowerSaveBlocker };
|
feat
|
a7bc57922010062784b2be877ba778323499e0f9
|
David Sanders
|
2023-01-17 10:41:05
|
ci: update pinned versions for security scorecard workflow (#36910)
|
diff --git a/.github/workflows/scorecards.yml b/.github/workflows/scorecards.yml
index 3d5646523d..532734c542 100644
--- a/.github/workflows/scorecards.yml
+++ b/.github/workflows/scorecards.yml
@@ -22,12 +22,12 @@ jobs:
steps:
- name: "Checkout code"
- uses: actions/checkout@a12a3943b4bdde767164f792f33f40b04645d846 # tag=v3.0.0
+ uses: actions/checkout@ac593985615ec2ede58e132d2e21d2b1cbd6127c # tag=v3.1.0
with:
persist-credentials: false
- name: "Run analysis"
- uses: ossf/scorecard-action@99c53751e09b9529366343771cc321ec74e9bd3d # tag=v2.0.6
+ uses: ossf/scorecard-action@e38b1902ae4f44df626f11ba0734b14fb91f8f86 # tag=v2.1.2
with:
results_file: results.sarif
results_format: sarif
@@ -41,7 +41,7 @@ jobs:
# Upload the results as artifacts (optional). Commenting out will disable uploads of run results in SARIF
# format to the repository Actions tab.
- name: "Upload artifact"
- uses: actions/upload-artifact@6673cd052c4cd6fcf4b4e6e60ea986c889389535 # tag=v3.0.0
+ uses: actions/upload-artifact@0b7f8abb1508181956e8e162db84b466c27e18ce # tag=v3.1.2
with:
name: SARIF file
path: results.sarif
@@ -49,6 +49,6 @@ jobs:
# Upload the results to GitHub's code scanning dashboard.
- name: "Upload to code-scanning"
- uses: github/codeql-action/upload-sarif@5f532563584d71fdef14ee64d17bafb34f751ce5 # tag=v1.0.26
+ uses: github/codeql-action/upload-sarif@959cbb7472c4d4ad70cdfe6f4976053fe48ab394 # tag=v2.1.27
with:
sarif_file: results.sarif
|
ci
|
e19500fa03bf08af1466dac5dbca39f1b4281d9c
|
Shelley Vohr
|
2023-05-15 22:31:57
|
feat: support Mica/Acrylic on Windows (#38163)
* feat: support Mica/Acrylic on Windows
* chore: feedback from review
|
diff --git a/docs/api/browser-window.md b/docs/api/browser-window.md
index ee206597bb..177a3395a7 100644
--- a/docs/api/browser-window.md
+++ b/docs/api/browser-window.md
@@ -1557,6 +1557,21 @@ will remove the vibrancy effect on the window.
Note that `appearance-based`, `light`, `dark`, `medium-light`, and `ultra-dark` have been
deprecated and will be removed in an upcoming version of macOS.
+#### `win.setBackgroundMaterial(material)` _Windows_
+
+* `material` string
+ * `auto` - Let the Desktop Window Manager (DWM) automatically decide the system-drawn backdrop material for this window. This is the default.
+ * `none` - Don't draw any system backdrop.
+ * `mica` - Draw the backdrop material effect corresponding to a long-lived window.
+ * `acrylic` - Draw the backdrop material effect corresponding to a transient window.
+ * `tabbed` - Draw the backdrop material effect corresponding to a window with a tabbed title bar.
+
+This method sets the browser window's system-drawn background material, including behind the non-client area.
+
+See the [Windows documentation](https://learn.microsoft.com/en-us/windows/win32/api/dwmapi/ne-dwmapi-dwm_systembackdrop_type) for more details.
+
+**Note:** This method is only supported on Windows 11 22H2 and up.
+
#### `win.setWindowButtonPosition(position)` _macOS_
* `position` [Point](structures/point.md) | null
diff --git a/docs/api/structures/browser-window-options.md b/docs/api/structures/browser-window-options.md
index fafefa9ccf..64204ba470 100644
--- a/docs/api/structures/browser-window-options.md
+++ b/docs/api/structures/browser-window-options.md
@@ -110,6 +110,9 @@
`tooltip`, `content`, `under-window`, or `under-page`. Please note that
`appearance-based`, `light`, `dark`, `medium-light`, and `ultra-dark` are
deprecated and have been removed in macOS Catalina (10.15).
+* `backgroundMaterial` string (optional) _Windows_ - Set the window's
+ system-drawn background material, including behind the non-client area.
+ Can be `auto`, `none`, `mica`, `acrylic` or `tabbed`. See [win.setBackgroundMaterial](../browser-window.md#winsetbackgroundmaterialmaterial-windows) for more information.
* `zoomToPageWidth` boolean (optional) _macOS_ - Controls the behavior on
macOS when option-clicking the green stoplight button on the toolbar or by
clicking the Window > Zoom menu item. If `true`, the window will grow to
diff --git a/shell/browser/api/electron_api_base_window.cc b/shell/browser/api/electron_api_base_window.cc
index fdbe58cf2b..0ef53104ec 100644
--- a/shell/browser/api/electron_api_base_window.cc
+++ b/shell/browser/api/electron_api_base_window.cc
@@ -864,6 +864,10 @@ void BaseWindow::SetVibrancy(v8::Isolate* isolate, v8::Local<v8::Value> value) {
window_->SetVibrancy(type);
}
+void BaseWindow::SetBackgroundMaterial(const std::string& material_type) {
+ window_->SetBackgroundMaterial(material_type);
+}
+
#if BUILDFLAG(IS_MAC)
std::string BaseWindow::GetAlwaysOnTopLevel() {
return window_->GetAlwaysOnTopLevel();
@@ -1267,6 +1271,7 @@ void BaseWindow::BuildPrototype(v8::Isolate* isolate,
.SetMethod("setAutoHideCursor", &BaseWindow::SetAutoHideCursor)
#endif
.SetMethod("setVibrancy", &BaseWindow::SetVibrancy)
+ .SetMethod("setBackgroundMaterial", &BaseWindow::SetBackgroundMaterial)
#if BUILDFLAG(IS_MAC)
.SetMethod("isHiddenInMissionControl",
diff --git a/shell/browser/api/electron_api_base_window.h b/shell/browser/api/electron_api_base_window.h
index 28207f1e57..f95ca67d30 100644
--- a/shell/browser/api/electron_api_base_window.h
+++ b/shell/browser/api/electron_api_base_window.h
@@ -190,6 +190,7 @@ class BaseWindow : public gin_helper::TrackableObject<BaseWindow>,
bool IsVisibleOnAllWorkspaces();
void SetAutoHideCursor(bool auto_hide);
virtual void SetVibrancy(v8::Isolate* isolate, v8::Local<v8::Value> value);
+ void SetBackgroundMaterial(const std::string& vibrancy);
#if BUILDFLAG(IS_MAC)
std::string GetAlwaysOnTopLevel();
diff --git a/shell/browser/native_window.cc b/shell/browser/native_window.cc
index ce7186bb49..1477f4e7e5 100644
--- a/shell/browser/native_window.cc
+++ b/shell/browser/native_window.cc
@@ -249,6 +249,11 @@ void NativeWindow::InitFromOptions(const gin_helper::Dictionary& options) {
if (options.Get(options::kVibrancyType, &type)) {
SetVibrancy(type);
}
+#elif BUILDFLAG(IS_WIN)
+ std::string material;
+ if (options.Get(options::kBackgroundMaterial, &material)) {
+ SetBackgroundMaterial(material);
+ }
#endif
std::string color;
if (options.Get(options::kBackgroundColor, &color)) {
@@ -445,6 +450,8 @@ bool NativeWindow::AddTabbedWindow(NativeWindow* window) {
void NativeWindow::SetVibrancy(const std::string& type) {}
+void NativeWindow::SetBackgroundMaterial(const std::string& type) {}
+
void NativeWindow::SetTouchBar(
std::vector<gin_helper::PersistentDictionary> items) {}
diff --git a/shell/browser/native_window.h b/shell/browser/native_window.h
index ce5d1a7b62..098fa2fcf4 100644
--- a/shell/browser/native_window.h
+++ b/shell/browser/native_window.h
@@ -216,6 +216,8 @@ class NativeWindow : public base::SupportsUserData,
// Vibrancy API
virtual void SetVibrancy(const std::string& type);
+ virtual void SetBackgroundMaterial(const std::string& type);
+
// Traffic Light API
#if BUILDFLAG(IS_MAC)
virtual void SetWindowButtonVisibility(bool visible) = 0;
diff --git a/shell/browser/native_window_views.cc b/shell/browser/native_window_views.cc
index 3511d7ba15..e92247f2a0 100644
--- a/shell/browser/native_window_views.cc
+++ b/shell/browser/native_window_views.cc
@@ -5,6 +5,7 @@
#include "shell/browser/native_window_views.h"
#if BUILDFLAG(IS_WIN)
+#include <dwmapi.h>
#include <wrl/client.h>
#endif
@@ -69,6 +70,7 @@
#elif BUILDFLAG(IS_WIN)
#include "base/win/win_util.h"
+#include "base/win/windows_version.h"
#include "content/public/common/color_parser.h"
#include "shell/browser/ui/views/win_frame_view.h"
#include "shell/browser/ui/win/electron_desktop_native_widget_aura.h"
@@ -83,6 +85,19 @@ namespace electron {
#if BUILDFLAG(IS_WIN)
+DWM_SYSTEMBACKDROP_TYPE GetBackdropFromString(const std::string& material) {
+ if (material == "none") {
+ return DWMSBT_NONE;
+ } else if (material == "acrylic") {
+ return DWMSBT_TRANSIENTWINDOW;
+ } else if (material == "mica") {
+ return DWMSBT_MAINWINDOW;
+ } else if (material == "tabbed") {
+ return DWMSBT_TABBEDWINDOW;
+ }
+ return DWMSBT_AUTO;
+}
+
// Similar to the ones in display::win::ScreenWin, but with rounded values
// These help to avoid problems that arise from unresizable windows where the
// original ceil()-ed values can cause calculation errors, since converting
@@ -1379,6 +1394,21 @@ bool NativeWindowViews::IsMenuBarVisible() {
return root_view_->IsMenuBarVisible();
}
+void NativeWindowViews::SetBackgroundMaterial(const std::string& material) {
+#if BUILDFLAG(IS_WIN)
+ // DWMWA_USE_HOSTBACKDROPBRUSH is only supported on Windows 11 22H2 and up.
+ if (base::win::GetVersion() < base::win::Version::WIN11_22H2)
+ return;
+
+ DWM_SYSTEMBACKDROP_TYPE backdrop_type = GetBackdropFromString(material);
+ HRESULT result =
+ DwmSetWindowAttribute(GetAcceleratedWidget(), DWMWA_SYSTEMBACKDROP_TYPE,
+ &backdrop_type, sizeof(backdrop_type));
+ if (FAILED(result))
+ LOG(WARNING) << "Failed to set background material to " << material;
+#endif
+}
+
void NativeWindowViews::SetVisibleOnAllWorkspaces(
bool visible,
bool visibleOnFullScreen,
diff --git a/shell/browser/native_window_views.h b/shell/browser/native_window_views.h
index 2961072ed4..a84e17c265 100644
--- a/shell/browser/native_window_views.h
+++ b/shell/browser/native_window_views.h
@@ -138,6 +138,7 @@ class NativeWindowViews : public NativeWindow,
bool IsMenuBarAutoHide() override;
void SetMenuBarVisibility(bool visible) override;
bool IsMenuBarVisible() override;
+ void SetBackgroundMaterial(const std::string& type) override;
void SetVisibleOnAllWorkspaces(bool visible,
bool visibleOnFullScreen,
diff --git a/shell/common/options_switches.cc b/shell/common/options_switches.cc
index a50ea98c1e..57b66f2e2d 100644
--- a/shell/common/options_switches.cc
+++ b/shell/common/options_switches.cc
@@ -110,6 +110,9 @@ const char kWebPreferences[] = "webPreferences";
// Add a vibrancy effect to the browser window
const char kVibrancyType[] = "vibrancy";
+// Add a vibrancy effect to the browser window.
+const char kBackgroundMaterial[] = "backgroundMaterial";
+
// Specify how the material appearance should reflect window activity state on
// macOS.
const char kVisualEffectState[] = "visualEffectState";
diff --git a/shell/common/options_switches.h b/shell/common/options_switches.h
index 46f966f879..b0199569db 100644
--- a/shell/common/options_switches.h
+++ b/shell/common/options_switches.h
@@ -55,6 +55,7 @@ extern const char kOpacity[];
extern const char kFocusable[];
extern const char kWebPreferences[];
extern const char kVibrancyType[];
+extern const char kBackgroundMaterial[];
extern const char kVisualEffectState[];
extern const char kTrafficLightPosition[];
extern const char kRoundedCorners[];
|
feat
|
cdb65c15a81ba36685696daa4ffcb974481d8c5a
|
Robo
|
2023-01-21 09:42:45
|
fix: make plugin helper executable unconditional (#36971)
|
diff --git a/shell/app/electron_main_delegate_mac.mm b/shell/app/electron_main_delegate_mac.mm
index b3c3e5df9e..3805ad76a2 100644
--- a/shell/app/electron_main_delegate_mac.mm
+++ b/shell/app/electron_main_delegate_mac.mm
@@ -15,7 +15,6 @@
#include "base/strings/sys_string_conversions.h"
#include "content/common/mac_helpers.h"
#include "content/public/common/content_paths.h"
-#include "ppapi/buildflags/buildflags.h"
#include "shell/browser/mac/electron_application.h"
#include "shell/common/application_info.h"
#include "shell/common/mac/main_application_bundle.h"
@@ -41,11 +40,9 @@ base::FilePath GetHelperAppPath(const base::FilePath& frameworks_path,
} else if (base::EndsWith(path.value(), content::kMacHelperSuffix_gpu,
base::CompareCase::SENSITIVE)) {
helper_name += content::kMacHelperSuffix_gpu;
-#if BUILDFLAG(ENABLE_PLUGINS)
} else if (base::EndsWith(path.value(), content::kMacHelperSuffix_plugin,
base::CompareCase::SENSITIVE)) {
helper_name += content::kMacHelperSuffix_plugin;
-#endif
}
return frameworks_path.Append(name + " " + helper_name + ".app")
diff --git a/shell/browser/electron_browser_client.cc b/shell/browser/electron_browser_client.cc
index 89e3603fd1..45dc1f66dd 100644
--- a/shell/browser/electron_browser_client.cc
+++ b/shell/browser/electron_browser_client.cc
@@ -474,15 +474,10 @@ void ElectronBrowserClient::AppendExtraCommandLineSwitches(
content::ChildProcessHost::CHILD_RENDERER);
auto gpu_child_path = content::ChildProcessHost::GetChildPath(
content::ChildProcessHost::CHILD_GPU);
-#if BUILDFLAG(ENABLE_PLUGINS)
auto plugin_child_path = content::ChildProcessHost::GetChildPath(
content::ChildProcessHost::CHILD_PLUGIN);
-#endif
- if (program != renderer_child_path && program != gpu_child_path
-#if BUILDFLAG(ENABLE_PLUGINS)
- && program != plugin_child_path
-#endif
- ) {
+ if (program != renderer_child_path && program != gpu_child_path &&
+ program != plugin_child_path) {
child_path = content::ChildProcessHost::GetChildPath(
content::ChildProcessHost::CHILD_NORMAL);
CHECK_EQ(program, child_path)
diff --git a/shell/common/mac/main_application_bundle.mm b/shell/common/mac/main_application_bundle.mm
index 0e8058e8f9..a73275b3f2 100644
--- a/shell/common/mac/main_application_bundle.mm
+++ b/shell/common/mac/main_application_bundle.mm
@@ -11,7 +11,6 @@
#include "base/path_service.h"
#include "base/strings/string_util.h"
#include "content/common/mac_helpers.h"
-#include "ppapi/buildflags/buildflags.h"
namespace electron {
@@ -33,10 +32,8 @@ base::FilePath MainApplicationBundlePath() {
// Up to Contents.
if (!HasMainProcessKey() &&
(base::EndsWith(path.value(), " Helper", base::CompareCase::SENSITIVE) ||
-#if BUILDFLAG(ENABLE_PLUGINS)
base::EndsWith(path.value(), content::kMacHelperSuffix_plugin,
base::CompareCase::SENSITIVE) ||
-#endif
base::EndsWith(path.value(), content::kMacHelperSuffix_renderer,
base::CompareCase::SENSITIVE) ||
base::EndsWith(path.value(), content::kMacHelperSuffix_gpu,
|
fix
|
9f97c3e50a11b364f02f57209854bb4000ac1136
|
Jeremy Rose
|
2022-09-13 10:49:34
|
feat: expose content-bounds-updated event (#35533)
|
diff --git a/docs/api/web-contents.md b/docs/api/web-contents.md
index 2cf6e17263..0de4fd0354 100644
--- a/docs/api/web-contents.md
+++ b/docs/api/web-contents.md
@@ -130,10 +130,6 @@ Corresponds to the points in time when the spinner of the tab stopped spinning.
#### Event: 'dom-ready'
-Returns:
-
-* `event` Event
-
Emitted when the document in the top-level frame is loaded.
#### Event: 'page-title-updated'
@@ -156,6 +152,18 @@ Returns:
Emitted when page receives favicon urls.
+#### Event: 'content-bounds-updated'
+
+Returns:
+
+* `event` Event
+* `bounds` [Rectangle](structures/rectangle.md) - requested new content bounds
+
+Emitted when the page calls `window.moveTo`, `window.resizeTo` or related APIs.
+
+By default, this will move the window. To prevent that behavior, call
+`event.preventDefault()`.
+
#### Event: 'did-create-window'
Returns:
diff --git a/shell/browser/api/electron_api_web_contents.cc b/shell/browser/api/electron_api_web_contents.cc
index ebf0091121..fe53806541 100755
--- a/shell/browser/api/electron_api_web_contents.cc
+++ b/shell/browser/api/electron_api_web_contents.cc
@@ -1180,8 +1180,9 @@ void WebContents::BeforeUnloadFired(content::WebContents* tab,
void WebContents::SetContentsBounds(content::WebContents* source,
const gfx::Rect& rect) {
- for (ExtendedWebContentsObserver& observer : observers_)
- observer.OnSetContentBounds(rect);
+ if (!Emit("content-bounds-updated", rect))
+ for (ExtendedWebContentsObserver& observer : observers_)
+ observer.OnSetContentBounds(rect);
}
void WebContents::CloseContents(content::WebContents* source) {
diff --git a/spec/api-web-contents-spec.ts b/spec/api-web-contents-spec.ts
index 3ceb081c76..98251ac790 100644
--- a/spec/api-web-contents-spec.ts
+++ b/spec/api-web-contents-spec.ts
@@ -2132,4 +2132,62 @@ describe('webContents module', () => {
expect(params.y).to.be.a('number');
});
});
+
+ describe('content-bounds-updated event', () => {
+ afterEach(closeAllWindows);
+ it('emits when moveTo is called', async () => {
+ const w = new BrowserWindow({ show: false });
+ w.loadURL('about:blank');
+ w.webContents.executeJavaScript('window.moveTo(100, 100)', true);
+ const [, rect] = await emittedOnce(w.webContents, 'content-bounds-updated');
+ const { width, height } = w.getBounds();
+ expect(rect).to.deep.equal({
+ x: 100,
+ y: 100,
+ width,
+ height
+ });
+ await new Promise(setImmediate);
+ expect(w.getBounds().x).to.equal(100);
+ expect(w.getBounds().y).to.equal(100);
+ });
+
+ it('emits when resizeTo is called', async () => {
+ const w = new BrowserWindow({ show: false });
+ w.loadURL('about:blank');
+ w.webContents.executeJavaScript('window.resizeTo(100, 100)', true);
+ const [, rect] = await emittedOnce(w.webContents, 'content-bounds-updated');
+ const { x, y } = w.getBounds();
+ expect(rect).to.deep.equal({
+ x,
+ y,
+ width: 100,
+ height: 100
+ });
+ await new Promise(setImmediate);
+ expect({
+ width: w.getBounds().width,
+ height: w.getBounds().height
+ }).to.deep.equal(process.platform === 'win32' ? {
+ // The width is reported as being larger on Windows? I'm not sure why
+ // this is.
+ width: 136,
+ height: 100
+ } : {
+ width: 100,
+ height: 100
+ });
+ });
+
+ it('does not change window bounds if cancelled', async () => {
+ const w = new BrowserWindow({ show: false });
+ const { width, height } = w.getBounds();
+ w.loadURL('about:blank');
+ w.webContents.once('content-bounds-updated', e => e.preventDefault());
+ await w.webContents.executeJavaScript('window.resizeTo(100, 100)', true);
+ await new Promise(setImmediate);
+ expect(w.getBounds().width).to.equal(width);
+ expect(w.getBounds().height).to.equal(height);
+ });
+ });
});
|
feat
|
3bdc7ce64a79120c4001d0c614e4ad037246229e
|
David Sanders
|
2023-08-25 11:09:28
|
ci: don't mark status/confirmed labeled issues as stale (#39659)
|
diff --git a/.github/workflows/stale.yml b/.github/workflows/stale.yml
index d14c3f6a1a..ddbb399615 100644
--- a/.github/workflows/stale.yml
+++ b/.github/workflows/stale.yml
@@ -22,7 +22,7 @@ jobs:
This issue has been automatically marked as stale. **If this issue is still affecting you, please leave any comment** (for example, "bump"), and we'll keep it open. If you have any new additional information—in particular, if this is still reproducible in the [latest version of Electron](https://www.electronjs.org/releases/stable) or in the [beta](https://www.electronjs.org/releases/beta)—please include it with your comment!
close-issue-message: >
This issue has been closed due to inactivity, and will not be monitored. If this is a bug and you can reproduce this issue on a [supported version of Electron](https://www.electronjs.org/docs/latest/tutorial/electron-timelines#timeline) please open a new issue and include instructions for reproducing the issue.
- exempt-issue-labels: "discussion,security \U0001F512,enhancement :sparkles:"
+ exempt-issue-labels: "discussion,security \U0001F512,enhancement :sparkles:,status/confirmed"
only-pr-labels: not-a-real-label
pending-repro:
runs-on: ubuntu-latest
|
ci
|
9b8b8f5880c29b9ae0b112433e7a51c51b501c2b
|
Jeremy Rose
|
2023-01-05 01:36:14
|
fix: move report_raw_headers to TrustedParams (#36725)
* fix: move report_raw_headers to TrustedParams
* Update electron_api_url_loader.cc
* missed a copy constructor
|
diff --git a/patches/chromium/feat_expose_raw_response_headers_from_urlloader.patch b/patches/chromium/feat_expose_raw_response_headers_from_urlloader.patch
index c4662e855d..c5dff54801 100644
--- a/patches/chromium/feat_expose_raw_response_headers_from_urlloader.patch
+++ b/patches/chromium/feat_expose_raw_response_headers_from_urlloader.patch
@@ -17,69 +17,78 @@ headers, moving forward we should find a way in upstream to provide
access to these headers for loader clients created on the browser process.
diff --git a/services/network/public/cpp/resource_request.cc b/services/network/public/cpp/resource_request.cc
-index 65921550e62dbcd79f77192951b95991c3e904a1..c45a2a8c5adf3df78b4e4c4c0d4d945ade2a6826 100644
+index 65921550e62dbcd79f77192951b95991c3e904a1..743e81c07052979dfb83cc0ed44a6653ddf52321 100644
--- a/services/network/public/cpp/resource_request.cc
+++ b/services/network/public/cpp/resource_request.cc
-@@ -234,6 +234,7 @@ bool ResourceRequest::EqualsForTesting(const ResourceRequest& request) const {
- do_not_prompt_for_login == request.do_not_prompt_for_login &&
- is_outermost_main_frame == request.is_outermost_main_frame &&
- transition_type == request.transition_type &&
-+ report_raw_headers == request.report_raw_headers &&
- previews_state == request.previews_state &&
- upgrade_if_insecure == request.upgrade_if_insecure &&
- is_revalidating == request.is_revalidating &&
+@@ -119,6 +119,7 @@ ResourceRequest::TrustedParams& ResourceRequest::TrustedParams::operator=(
+ isolation_info = other.isolation_info;
+ disable_secure_dns = other.disable_secure_dns;
+ has_user_activation = other.has_user_activation;
++ report_raw_headers = other.report_raw_headers;
+ cookie_observer =
+ Clone(&const_cast<mojo::PendingRemote<mojom::CookieAccessObserver>&>(
+ other.cookie_observer));
+@@ -139,6 +140,7 @@ bool ResourceRequest::TrustedParams::EqualsForTesting(
+ const TrustedParams& other) const {
+ return isolation_info.IsEqualForTesting(other.isolation_info) &&
+ disable_secure_dns == other.disable_secure_dns &&
++ report_raw_headers == other.report_raw_headers &&
+ has_user_activation == other.has_user_activation &&
+ client_security_state == other.client_security_state;
+ }
diff --git a/services/network/public/cpp/resource_request.h b/services/network/public/cpp/resource_request.h
-index b3ff3cc494d5d63ed0af9745131cfd52da12cd43..9bd521e08540102e992423cb0a6eacbfc514f03b 100644
+index b3ff3cc494d5d63ed0af9745131cfd52da12cd43..05954160ee3cbc86a3dec4ba2b1f6750cd6d5209 100644
--- a/services/network/public/cpp/resource_request.h
+++ b/services/network/public/cpp/resource_request.h
-@@ -160,6 +160,7 @@ struct COMPONENT_EXPORT(NETWORK_CPP_BASE) ResourceRequest {
- bool do_not_prompt_for_login = false;
- bool is_outermost_main_frame = false;
- int transition_type = 0;
-+ bool report_raw_headers = false;
- int previews_state = 0;
- bool upgrade_if_insecure = false;
- bool is_revalidating = false;
+@@ -62,6 +62,7 @@ struct COMPONENT_EXPORT(NETWORK_CPP_BASE) ResourceRequest {
+ net::IsolationInfo isolation_info;
+ bool disable_secure_dns = false;
+ bool has_user_activation = false;
++ bool report_raw_headers = false;
+ mojo::PendingRemote<mojom::CookieAccessObserver> cookie_observer;
+ mojo::PendingRemote<mojom::URLLoaderNetworkServiceObserver>
+ url_loader_network_observer;
diff --git a/services/network/public/cpp/url_request_mojom_traits.cc b/services/network/public/cpp/url_request_mojom_traits.cc
-index 1702f66d2ec0871f15e475ae3901b48637140d59..9b4370d6c0e08662fac1892217e28f142c983576 100644
+index 1702f66d2ec0871f15e475ae3901b48637140d59..824523653ae45ae9b66f316f9ee608f351aae728 100644
--- a/services/network/public/cpp/url_request_mojom_traits.cc
+++ b/services/network/public/cpp/url_request_mojom_traits.cc
-@@ -210,6 +210,7 @@ bool StructTraits<
- out->do_not_prompt_for_login = data.do_not_prompt_for_login();
- out->is_outermost_main_frame = data.is_outermost_main_frame();
- out->transition_type = data.transition_type();
+@@ -88,6 +88,7 @@ bool StructTraits<network::mojom::TrustedUrlRequestParamsDataView,
+ }
+ out->disable_secure_dns = data.disable_secure_dns();
+ out->has_user_activation = data.has_user_activation();
+ out->report_raw_headers = data.report_raw_headers();
- out->previews_state = data.previews_state();
- out->upgrade_if_insecure = data.upgrade_if_insecure();
- out->is_revalidating = data.is_revalidating();
+ out->cookie_observer = data.TakeCookieObserver<
+ mojo::PendingRemote<network::mojom::CookieAccessObserver>>();
+ out->url_loader_network_observer = data.TakeUrlLoaderNetworkObserver<
diff --git a/services/network/public/cpp/url_request_mojom_traits.h b/services/network/public/cpp/url_request_mojom_traits.h
-index af527034303f0660934d50a441fa178ddaeca475..65e0719fef13fbf730d74f9982d1b54d741a60fd 100644
+index af527034303f0660934d50a441fa178ddaeca475..aa1a1290ebb261a4f5045cf14882e750822784c4 100644
--- a/services/network/public/cpp/url_request_mojom_traits.h
+++ b/services/network/public/cpp/url_request_mojom_traits.h
-@@ -272,6 +272,9 @@ struct COMPONENT_EXPORT(NETWORK_CPP_BASE)
- static int32_t transition_type(const network::ResourceRequest& request) {
- return request.transition_type;
+@@ -65,6 +65,10 @@ struct COMPONENT_EXPORT(NETWORK_CPP_BASE)
+ const network::ResourceRequest::TrustedParams& trusted_params) {
+ return trusted_params.has_user_activation;
}
-+ static bool report_raw_headers(const network::ResourceRequest& request) {
-+ return request.report_raw_headers;
++ static bool report_raw_headers(
++ const network::ResourceRequest::TrustedParams& trusted_params) {
++ return trusted_params.report_raw_headers;
+ }
- static int32_t previews_state(const network::ResourceRequest& request) {
- return request.previews_state;
- }
+ static mojo::PendingRemote<network::mojom::CookieAccessObserver>
+ cookie_observer(
+ const network::ResourceRequest::TrustedParams& trusted_params) {
diff --git a/services/network/public/mojom/url_request.mojom b/services/network/public/mojom/url_request.mojom
-index bf3c8e3dc4d15d33118144f801b661fed667a5ba..733bb2b2b20094520c3e944288dfa01dad01ebc5 100644
+index bf3c8e3dc4d15d33118144f801b661fed667a5ba..4bce0983d28d44d3dd6d34aaca684f1f978e18fd 100644
--- a/services/network/public/mojom/url_request.mojom
+++ b/services/network/public/mojom/url_request.mojom
-@@ -317,6 +317,9 @@ struct URLRequest {
- // about this.
- int32 transition_type;
+@@ -55,6 +55,9 @@ struct TrustedUrlRequestParams {
+ // without user gesture. Used to determine the `Sec-Fetch-User` header.
+ bool has_user_activation;
-+ // Whether to provide unfiltered response headers.
++ // [Electron] Whether to provide unfiltered response headers.
+ bool report_raw_headers;
+
- // Whether or not to request a Preview version of the resource or let the
- // browser decide.
- // Note: this is an enum of type PreviewsState.
+ // Observer which should be notified when this URLRequest reads or writes
+ // a cookie. If this is set to non-null, the observer passed to
+ // URLLoaderFactory will be ignored.
diff --git a/services/network/public/mojom/url_response_head.mojom b/services/network/public/mojom/url_response_head.mojom
index f4cbafde0cfa92e3e93f5480242025b3d5c822c4..73a7a02a224a4737c4f7a97a98a73e7f67ce3250 100644
--- a/services/network/public/mojom/url_response_head.mojom
@@ -103,17 +112,17 @@ index f4cbafde0cfa92e3e93f5480242025b3d5c822c4..73a7a02a224a4737c4f7a97a98a73e7f
string mime_type;
diff --git a/services/network/url_loader.cc b/services/network/url_loader.cc
-index 023729747d16816a6ba38159ace5ab1ec7bb2db5..93b14019539c3527cd7f119093bb16e47186f060 100644
+index 023729747d16816a6ba38159ace5ab1ec7bb2db5..aa3277bfd3dc1f7bab474ba0ff21f8c6e1d851eb 100644
--- a/services/network/url_loader.cc
+++ b/services/network/url_loader.cc
-@@ -463,6 +463,7 @@ URLLoader::URLLoader(
- mojo::SimpleWatcher::ArmingPolicy::MANUAL,
- base::SequencedTaskRunner::GetCurrentDefault()),
- per_factory_corb_state_(context.GetMutableCorbState()),
-+ report_raw_headers_(request.report_raw_headers),
- devtools_request_id_(request.devtools_request_id),
- request_mode_(request.mode),
- request_credentials_mode_(request.credentials_mode),
+@@ -582,6 +582,7 @@ URLLoader::URLLoader(
+
+ if (request.trusted_params) {
+ has_user_activation_ = request.trusted_params->has_user_activation;
++ report_raw_headers_ = request.trusted_params->report_raw_headers;
+ }
+
+ throttling_token_ = network::ScopedThrottlingToken::MaybeCreate(
@@ -645,7 +646,7 @@ URLLoader::URLLoader(
url_request_->SetRequestHeadersCallback(base::BindRepeating(
&URLLoader::SetRawRequestHeadersAndNotify, base::Unretained(this)));
diff --git a/shell/browser/api/electron_api_url_loader.cc b/shell/browser/api/electron_api_url_loader.cc
index 6fed3bf105..e8575141e7 100644
--- a/shell/browser/api/electron_api_url_loader.cc
+++ b/shell/browser/api/electron_api_url_loader.cc
@@ -280,7 +280,7 @@ SimpleURLLoaderWrapper::SimpleURLLoaderWrapper(
// Chromium filters headers using browser rules, while for net module we have
// every header passed. The following setting will allow us to capture the
// raw headers in the URLLoader.
- request->report_raw_headers = true;
+ request->trusted_params->report_raw_headers = true;
// SimpleURLLoader wants to control the request body itself. We have other
// ideas.
auto request_body = std::move(request->request_body);
|
fix
|
c7ca29e80f4dcc8e08ed63fa435cd9677ba60059
|
David Sanders
|
2023-05-16 13:42:24
|
chore: add smoke test for `devtools-open-url` (#38302)
|
diff --git a/spec/ts-smoke/electron/main.ts b/spec/ts-smoke/electron/main.ts
index 468d16df7f..9dfe9e819f 100644
--- a/spec/ts-smoke/electron/main.ts
+++ b/spec/ts-smoke/electron/main.ts
@@ -1226,6 +1226,10 @@ win4.webContents.on('paint', (event, dirty, _image) => {
console.log(dirty, _image.getBitmap());
});
+win4.webContents.on('devtools-open-url', (event, url) => {
+ console.log(url);
+});
+
win4.loadURL('http://github.com');
// TouchBar
|
chore
|
38ef9a76909a74eb99d290f29feefcfb2293ea9e
|
Shelley Vohr
|
2024-04-10 01:59:48
|
refactor: move PDF viewer to OOPIF (#41728)
https://issues.chromium.org/issues/40268279
|
diff --git a/shell/browser/extensions/api/management/electron_management_api_delegate.cc b/shell/browser/extensions/api/management/electron_management_api_delegate.cc
index 341ea9ee3f..f0d49e0f6a 100644
--- a/shell/browser/extensions/api/management/electron_management_api_delegate.cc
+++ b/shell/browser/extensions/api/management/electron_management_api_delegate.cc
@@ -154,7 +154,7 @@ void ElectronManagementAPIDelegate::InstallOrLaunchReplacementWebApp(
void ElectronManagementAPIDelegate::EnableExtension(
content::BrowserContext* context,
- const std::string& extension_id) const {
+ const extensions::ExtensionId& extension_id) const {
// const extensions::Extension* extension =
// extensions::ExtensionRegistry::Get(context)->GetExtensionById(
// extension_id, extensions::ExtensionRegistry::EVERYTHING);
@@ -171,7 +171,7 @@ void ElectronManagementAPIDelegate::EnableExtension(
void ElectronManagementAPIDelegate::DisableExtension(
content::BrowserContext* context,
const extensions::Extension* source_extension,
- const std::string& extension_id,
+ const extensions::ExtensionId& extension_id,
extensions::disable_reason::DisableReason disable_reason) const {
// TODO(sentialx): we don't have ExtensionService
// extensions::ExtensionSystem::Get(context)
@@ -182,7 +182,7 @@ void ElectronManagementAPIDelegate::DisableExtension(
bool ElectronManagementAPIDelegate::UninstallExtension(
content::BrowserContext* context,
- const std::string& transient_extension_id,
+ const extensions::ExtensionId& transient_extension_id,
extensions::UninstallReason reason,
std::u16string* error) const {
// TODO(sentialx): we don't have ExtensionService
@@ -194,7 +194,7 @@ bool ElectronManagementAPIDelegate::UninstallExtension(
void ElectronManagementAPIDelegate::SetLaunchType(
content::BrowserContext* context,
- const std::string& extension_id,
+ const extensions::ExtensionId& extension_id,
extensions::LaunchType launch_type) const {
// TODO(sentialx)
// extensions::SetLaunchType(context, extension_id, launch_type);
diff --git a/shell/browser/extensions/api/management/electron_management_api_delegate.h b/shell/browser/extensions/api/management/electron_management_api_delegate.h
index 19402d392d..fce21d57b1 100644
--- a/shell/browser/extensions/api/management/electron_management_api_delegate.h
+++ b/shell/browser/extensions/api/management/electron_management_api_delegate.h
@@ -10,6 +10,7 @@
#include "base/task/cancelable_task_tracker.h"
#include "extensions/browser/api/management/management_api_delegate.h"
+#include "extensions/common/extension_id.h"
class ElectronManagementAPIDelegate : public extensions::ManagementAPIDelegate {
public:
@@ -51,19 +52,20 @@ class ElectronManagementAPIDelegate : public extensions::ManagementAPIDelegate {
const GURL& web_app_url,
ManagementAPIDelegate::InstallOrLaunchWebAppCallback callback)
const override;
- void EnableExtension(content::BrowserContext* context,
- const std::string& extension_id) const override;
+ void EnableExtension(
+ content::BrowserContext* context,
+ const extensions::ExtensionId& extension_id) const override;
void DisableExtension(
content::BrowserContext* context,
const extensions::Extension* source_extension,
- const std::string& extension_id,
+ const extensions::ExtensionId& extension_id,
extensions::disable_reason::DisableReason disable_reason) const override;
bool UninstallExtension(content::BrowserContext* context,
- const std::string& transient_extension_id,
+ const extensions::ExtensionId& transient_extension_id,
extensions::UninstallReason reason,
std::u16string* error) const override;
void SetLaunchType(content::BrowserContext* context,
- const std::string& extension_id,
+ const extensions::ExtensionId& extension_id,
extensions::LaunchType launch_type) const override;
GURL GetIconURL(const extensions::Extension* extension,
int icon_size,
diff --git a/shell/browser/extensions/api/pdf_viewer_private/pdf_viewer_private_api.cc b/shell/browser/extensions/api/pdf_viewer_private/pdf_viewer_private_api.cc
index e93bd81b71..ec83bcd768 100644
--- a/shell/browser/extensions/api/pdf_viewer_private/pdf_viewer_private_api.cc
+++ b/shell/browser/extensions/api/pdf_viewer_private/pdf_viewer_private_api.cc
@@ -6,10 +6,16 @@
#include <string>
+#include "base/memory/weak_ptr.h"
+#include "base/numerics/safe_conversions.h"
+#include "base/strings/utf_string_conversions.h"
#include "base/values.h"
+#include "chrome/browser/pdf/pdf_viewer_stream_manager.h"
#include "chrome/common/extensions/api/pdf_viewer_private.h"
#include "chrome/common/pref_names.h"
+#include "components/pdf/common/constants.h"
#include "components/prefs/pref_service.h"
+#include "extensions/browser/guest_view/mime_handler_view/mime_handler_view_guest.h"
#include "shell/browser/electron_browser_context.h"
#include "url/url_constants.h"
@@ -22,6 +28,11 @@ namespace IsAllowedLocalFileAccess =
namespace SetPdfOcrPref = api::pdf_viewer_private::SetPdfOcrPref;
+namespace SetPdfPluginAttributes =
+ api::pdf_viewer_private::SetPdfPluginAttributes;
+
+namespace SetPdfDocumentTitle = api::pdf_viewer_private::SetPdfDocumentTitle;
+
// Check if the current URL is allowed based on a list of allowlisted domains.
bool IsUrlAllowedToEmbedLocalFiles(
const GURL& current_url,
@@ -43,8 +54,46 @@ bool IsUrlAllowedToEmbedLocalFiles(
return false;
}
+// Get the `StreamContainer` associated with the `extension_host`.
+base::WeakPtr<StreamContainer> GetStreamContainer(
+ content::RenderFrameHost* extension_host) {
+ content::RenderFrameHost* embedder_host = extension_host->GetParent();
+ if (!embedder_host) {
+ return nullptr;
+ }
+
+ auto* pdf_viewer_stream_manager =
+ pdf::PdfViewerStreamManager::FromRenderFrameHost(embedder_host);
+ if (!pdf_viewer_stream_manager) {
+ return nullptr;
+ }
+
+ return pdf_viewer_stream_manager->GetStreamContainer(embedder_host);
+}
+
} // namespace
+PdfViewerPrivateGetStreamInfoFunction::PdfViewerPrivateGetStreamInfoFunction() =
+ default;
+
+PdfViewerPrivateGetStreamInfoFunction::
+ ~PdfViewerPrivateGetStreamInfoFunction() = default;
+
+ExtensionFunction::ResponseAction PdfViewerPrivateGetStreamInfoFunction::Run() {
+ base::WeakPtr<StreamContainer> stream =
+ GetStreamContainer(render_frame_host());
+ if (!stream) {
+ return RespondNow(Error("Failed to get StreamContainer"));
+ }
+
+ api::pdf_viewer_private::StreamInfo stream_info;
+ stream_info.original_url = stream->original_url().spec();
+ stream_info.stream_url = stream->stream_url().spec();
+ stream_info.tab_id = stream->tab_id();
+ stream_info.embedded = stream->embedded();
+ return RespondNow(WithArguments(stream_info.ToValue()));
+}
+
PdfViewerPrivateIsAllowedLocalFileAccessFunction::
PdfViewerPrivateIsAllowedLocalFileAccessFunction() = default;
@@ -61,6 +110,37 @@ PdfViewerPrivateIsAllowedLocalFileAccessFunction::Run() {
IsUrlAllowedToEmbedLocalFiles(GURL(params->url), base::Value::List())));
}
+PdfViewerPrivateSetPdfDocumentTitleFunction::
+ PdfViewerPrivateSetPdfDocumentTitleFunction() = default;
+
+PdfViewerPrivateSetPdfDocumentTitleFunction::
+ ~PdfViewerPrivateSetPdfDocumentTitleFunction() = default;
+
+// This function is only called for full-page PDFs.
+ExtensionFunction::ResponseAction
+PdfViewerPrivateSetPdfDocumentTitleFunction::Run() {
+ content::WebContents* web_contents = GetSenderWebContents();
+ if (!web_contents) {
+ return RespondNow(Error("Could not find a valid web contents."));
+ }
+
+ // Title should only be set for full-page PDFs.
+ // MIME type associated with sender `WebContents` must be `application/pdf`
+ // for a full-page PDF.
+ EXTENSION_FUNCTION_VALIDATE(web_contents->GetContentsMimeType() ==
+ pdf::kPDFMimeType);
+
+ std::optional<SetPdfDocumentTitle::Params> params =
+ SetPdfDocumentTitle::Params::Create(args());
+ EXTENSION_FUNCTION_VALIDATE(params);
+
+ web_contents->UpdateTitleForEntry(
+ web_contents->GetController().GetLastCommittedEntry(),
+ base::UTF8ToUTF16(params->title));
+
+ return RespondNow(NoArguments());
+}
+
PdfViewerPrivateIsPdfOcrAlwaysActiveFunction::
PdfViewerPrivateIsPdfOcrAlwaysActiveFunction() = default;
@@ -87,4 +167,42 @@ ExtensionFunction::ResponseAction PdfViewerPrivateSetPdfOcrPrefFunction::Run() {
return RespondNow(WithArguments(false));
}
+PdfViewerPrivateSetPdfPluginAttributesFunction::
+ PdfViewerPrivateSetPdfPluginAttributesFunction() = default;
+
+PdfViewerPrivateSetPdfPluginAttributesFunction::
+ ~PdfViewerPrivateSetPdfPluginAttributesFunction() = default;
+
+ExtensionFunction::ResponseAction
+PdfViewerPrivateSetPdfPluginAttributesFunction::Run() {
+ std::optional<SetPdfPluginAttributes::Params> params =
+ SetPdfPluginAttributes::Params::Create(args());
+ EXTENSION_FUNCTION_VALIDATE(params);
+
+ base::WeakPtr<StreamContainer> stream =
+ GetStreamContainer(render_frame_host());
+ if (!stream) {
+ return RespondNow(Error("Failed to get StreamContainer"));
+ }
+
+ const api::pdf_viewer_private::PdfPluginAttributes& attributes =
+ params->attributes;
+ // Check the `background_color` is an integer.
+ double whole = 0.0;
+ if (std::modf(attributes.background_color, &whole) != 0.0) {
+ return RespondNow(Error("Background color is not an integer"));
+ }
+
+ // Check the `background_color` is within the range of a uint32_t.
+ if (!base::IsValueInRangeForNumericType<uint32_t>(
+ attributes.background_color)) {
+ return RespondNow(Error("Background color out of bounds"));
+ }
+
+ stream->set_pdf_plugin_attributes(mime_handler::PdfPluginAttributes::New(
+ /*background_color=*/attributes.background_color,
+ /*allow_javascript=*/attributes.allow_javascript));
+ return RespondNow(NoArguments());
+}
+
} // namespace extensions
diff --git a/shell/browser/extensions/api/pdf_viewer_private/pdf_viewer_private_api.h b/shell/browser/extensions/api/pdf_viewer_private/pdf_viewer_private_api.h
index f2e1401e76..468b3de3af 100644
--- a/shell/browser/extensions/api/pdf_viewer_private/pdf_viewer_private_api.h
+++ b/shell/browser/extensions/api/pdf_viewer_private/pdf_viewer_private_api.h
@@ -9,6 +9,24 @@
namespace extensions {
+class PdfViewerPrivateGetStreamInfoFunction : public ExtensionFunction {
+ public:
+ DECLARE_EXTENSION_FUNCTION("pdfViewerPrivate.getStreamInfo",
+ PDFVIEWERPRIVATE_GETSTREAMINFO)
+
+ PdfViewerPrivateGetStreamInfoFunction();
+ PdfViewerPrivateGetStreamInfoFunction(
+ const PdfViewerPrivateGetStreamInfoFunction&) = delete;
+ PdfViewerPrivateGetStreamInfoFunction& operator=(
+ const PdfViewerPrivateGetStreamInfoFunction&) = delete;
+
+ protected:
+ ~PdfViewerPrivateGetStreamInfoFunction() override;
+
+ // Override from ExtensionFunction:
+ ResponseAction Run() override;
+};
+
class PdfViewerPrivateIsAllowedLocalFileAccessFunction
: public ExtensionFunction {
public:
@@ -28,6 +46,24 @@ class PdfViewerPrivateIsAllowedLocalFileAccessFunction
ResponseAction Run() override;
};
+class PdfViewerPrivateSetPdfDocumentTitleFunction : public ExtensionFunction {
+ public:
+ DECLARE_EXTENSION_FUNCTION("pdfViewerPrivate.setPdfDocumentTitle",
+ PDFVIEWERPRIVATE_SETPDFDOCUMENTTITLE)
+
+ PdfViewerPrivateSetPdfDocumentTitleFunction();
+ PdfViewerPrivateSetPdfDocumentTitleFunction(
+ const PdfViewerPrivateSetPdfDocumentTitleFunction&) = delete;
+ PdfViewerPrivateSetPdfDocumentTitleFunction& operator=(
+ const PdfViewerPrivateSetPdfDocumentTitleFunction&) = delete;
+
+ protected:
+ ~PdfViewerPrivateSetPdfDocumentTitleFunction() override;
+
+ // Override from ExtensionFunction:
+ ResponseAction Run() override;
+};
+
class PdfViewerPrivateIsPdfOcrAlwaysActiveFunction : public ExtensionFunction {
public:
DECLARE_EXTENSION_FUNCTION("pdfViewerPrivate.isPdfOcrAlwaysActive",
@@ -64,6 +100,25 @@ class PdfViewerPrivateSetPdfOcrPrefFunction : public ExtensionFunction {
ResponseAction Run() override;
};
+class PdfViewerPrivateSetPdfPluginAttributesFunction
+ : public ExtensionFunction {
+ public:
+ DECLARE_EXTENSION_FUNCTION("pdfViewerPrivate.setPdfPluginAttributes",
+ PDFVIEWERPRIVATE_SETPDFPLUGINATTRIBUTES)
+
+ PdfViewerPrivateSetPdfPluginAttributesFunction();
+ PdfViewerPrivateSetPdfPluginAttributesFunction(
+ const PdfViewerPrivateSetPdfPluginAttributesFunction&) = delete;
+ PdfViewerPrivateSetPdfPluginAttributesFunction& operator=(
+ const PdfViewerPrivateSetPdfPluginAttributesFunction&) = delete;
+
+ protected:
+ ~PdfViewerPrivateSetPdfPluginAttributesFunction() override;
+
+ // Override from ExtensionFunction:
+ ResponseAction Run() override;
+};
+
} // namespace extensions
#endif // ELECTRON_SHELL_BROWSER_EXTENSIONS_API_PDF_VIEWER_PRIVATE_PDF_VIEWER_PRIVATE_API_H_
diff --git a/shell/browser/extensions/api/streams_private/streams_private_api.cc b/shell/browser/extensions/api/streams_private/streams_private_api.cc
index 5960fd2e82..9d015c151b 100644
--- a/shell/browser/extensions/api/streams_private/streams_private_api.cc
+++ b/shell/browser/extensions/api/streams_private/streams_private_api.cc
@@ -10,12 +10,20 @@
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/web_contents.h"
+#include "electron/buildflags/buildflags.h"
#include "extensions/browser/extension_registry.h"
#include "extensions/browser/guest_view/mime_handler_view/mime_handler_stream_manager.h"
#include "extensions/browser/guest_view/mime_handler_view/mime_handler_view_guest.h"
#include "extensions/common/manifest_handlers/mime_types_handler.h"
#include "shell/browser/api/electron_api_web_contents.h"
+#if BUILDFLAG(ENABLE_PDF_VIEWER)
+#include "base/feature_list.h"
+#include "chrome/browser/pdf/pdf_viewer_stream_manager.h"
+#include "extensions/common/constants.h"
+#include "pdf/pdf_features.h"
+#endif // BUILDFLAG(ENABLE_PDF_VIEWER)
+
namespace extensions {
void StreamsPrivateAPI::SendExecuteMimeTypeHandlerEvent(
@@ -51,13 +59,27 @@ void StreamsPrivateAPI::SendExecuteMimeTypeHandlerEvent(
GURL handler_url(
extensions::Extension::GetBaseURLFromExtensionId(extension_id).spec() +
handler->handler_url());
+
int tab_id = -1;
auto* api_contents = electron::api::WebContents::From(web_contents);
if (api_contents)
tab_id = api_contents->ID();
+
auto stream_container = std::make_unique<extensions::StreamContainer>(
tab_id, embedded, handler_url, extension_id,
std::move(transferrable_loader), original_url);
+
+#if BUILDFLAG(ENABLE_PDF_VIEWER)
+ if (base::FeatureList::IsEnabled(chrome_pdf::features::kPdfOopif) &&
+ extension_id == extension_misc::kPdfExtensionId) {
+ pdf::PdfViewerStreamManager::Create(web_contents);
+ pdf::PdfViewerStreamManager::FromWebContents(web_contents)
+ ->AddStreamContainer(frame_tree_node_id, internal_id,
+ std::move(stream_container));
+ return;
+ }
+#endif // BUILDFLAG(ENABLE_PDF_VIEWER)
+
extensions::MimeHandlerStreamManager::Get(browser_context)
->AddStream(stream_id, std::move(stream_container), frame_tree_node_id);
}
diff --git a/shell/common/extensions/api/pdf_viewer_private.idl b/shell/common/extensions/api/pdf_viewer_private.idl
index 67eaab116f..677a600c3d 100644
--- a/shell/common/extensions/api/pdf_viewer_private.idl
+++ b/shell/common/extensions/api/pdf_viewer_private.idl
@@ -6,34 +6,85 @@
// functionality that the PDF Viewer needs from outside the PDF plugin. This API
// is exclusively for the PDF Viewer.
namespace pdfViewerPrivate {
+ // Nearly identical to mimeHandlerPrivate.StreamInfo, but without a mime type
+ // nor a response header field. Those fields are unused by the PDF viewer.
+ dictionary StreamInfo {
+ // The original URL that was intercepted.
+ DOMString originalUrl;
+
+ // The URL that the stream can be read from.
+ DOMString streamUrl;
+
+ // The ID of the tab that opened the stream. If the stream is not opened in
+ // a tab, it will be -1.
+ long tabId;
+
+ // Whether the stream is embedded within another document.
+ boolean embedded;
+ };
+
+ // Identical to mimeHandlerPrivate.StreamInfo.
+ dictionary PdfPluginAttributes {
+ // The background color in ARGB format for painting. Since the background
+ // color is an unsigned 32-bit integer which can be outside the range of
+ // "long" type, define it as a "double" type here.
+ double backgroundColor;
+
+ // Indicates whether the plugin allows to execute JavaScript and maybe XFA.
+ // Loading XFA for PDF forms will automatically be disabled if this flag is
+ // false.
+ boolean allowJavascript;
+ };
+
+ callback GetStreamInfoCallback = void(StreamInfo streamInfo);
callback IsAllowedLocalFileAccessCallback = void(boolean result);
callback IsPdfOcrAlwaysActiveCallback = void(boolean result);
callback OnPdfOcrPrefSetCallback = void(boolean result);
+ callback VoidCallback = void();
interface Functions {
+ // Returns the StreamInfo for the stream for this context if there is one.
+ static void getStreamInfo(
+ GetStreamInfoCallback callback);
+
// Determines if the given URL should be allowed to access local files from
// the PDF Viewer. |callback|: Called with true if URL should be allowed to
// access local files from the PDF Viewer, false otherwise.
- [supportsPromises] static void isAllowedLocalFileAccess(
+ static void isAllowedLocalFileAccess(
DOMString url,
IsAllowedLocalFileAccessCallback callback);
// Determines if the preference for PDF OCR is set to run PDF OCR always.
// |callback|: Called with true if PDF OCR is set to be always active;
// false otherwise.
- [supportsPromises] static void isPdfOcrAlwaysActive(
+ static void isPdfOcrAlwaysActive(
IsPdfOcrAlwaysActiveCallback callback);
+ // Sets the current tab title to `title` for a full-page PDF.
+ static void setPdfDocumentTitle(
+ DOMString title,
+ optional VoidCallback callback);
+
// Sets a pref value for PDF OCR.
// |value|: The new value of the pref.
// |callback|: The callback for whether the pref was set or not.
- [supportsPromises] static void setPdfOcrPref(
+ static void setPdfOcrPref(
boolean value, OnPdfOcrPrefSetCallback callback);
+
+ // Sets PDF plugin attributes in the stream for this context if there is
+ // one.
+ static void setPdfPluginAttributes(
+ PdfPluginAttributes attributes,
+ optional VoidCallback callback);
};
interface Events {
// Fired when a pref value for PDF OCR has changed.
// |value| The pref value that changed.
static void onPdfOcrPrefChanged(boolean value);
+
+ // Fired when the browser wants the listener to perform a save.
+ // `streamUrl`: Unique ID for the instance that should perform the save.
+ static void onSave(DOMString streamUrl);
};
};
|
refactor
|
a0effaf9b85b8efbec819d3d5a18851a3a9a3e5c
|
Tomasz
|
2023-08-09 16:06:39
|
fix: promise resolved to early when browser initiated in-page navigation (#39260)
|
diff --git a/lib/browser/api/web-contents.ts b/lib/browser/api/web-contents.ts
index 8f0f53aa2b..0c1cb11d9e 100644
--- a/lib/browser/api/web-contents.ts
+++ b/lib/browser/api/web-contents.ts
@@ -446,6 +446,7 @@ WebContents.prototype.loadURL = function (url, options) {
};
let navigationStarted = false;
+ let browserInitiatedInPageNavigation = false;
const navigationListener = (event: Electron.Event, url: string, isSameDocument: boolean, isMainFrame: boolean) => {
if (isMainFrame) {
if (navigationStarted && !isSameDocument) {
@@ -460,6 +461,7 @@ WebContents.prototype.loadURL = function (url, options) {
// as the routing does not leave the document
return rejectAndCleanup(-3, 'ERR_ABORTED', url);
}
+ browserInitiatedInPageNavigation = navigationStarted && isSameDocument;
navigationStarted = true;
}
};
@@ -474,17 +476,22 @@ WebContents.prototype.loadURL = function (url, options) {
// would be more appropriate.
rejectAndCleanup(-2, 'ERR_FAILED', url);
};
+ const finishListenerWhenUserInitiatedNavigation = () => {
+ if (!browserInitiatedInPageNavigation) {
+ finishListener();
+ }
+ };
const removeListeners = () => {
this.removeListener('did-finish-load', finishListener);
this.removeListener('did-fail-load', failListener);
- this.removeListener('did-navigate-in-page', finishListener);
+ this.removeListener('did-navigate-in-page', finishListenerWhenUserInitiatedNavigation);
this.removeListener('did-start-navigation', navigationListener);
this.removeListener('did-stop-loading', stopLoadingListener);
this.removeListener('destroyed', stopLoadingListener);
};
this.on('did-finish-load', finishListener);
this.on('did-fail-load', failListener);
- this.on('did-navigate-in-page', finishListener);
+ this.on('did-navigate-in-page', finishListenerWhenUserInitiatedNavigation);
this.on('did-start-navigation', navigationListener);
this.on('did-stop-loading', stopLoadingListener);
this.on('destroyed', stopLoadingListener);
diff --git a/spec/api-web-contents-spec.ts b/spec/api-web-contents-spec.ts
index aeb2a11349..0be6172bb9 100644
--- a/spec/api-web-contents-spec.ts
+++ b/spec/api-web-contents-spec.ts
@@ -375,6 +375,16 @@ describe('webContents module', () => {
await expect(w.loadURL(w.getURL() + '#foo')).to.eventually.be.fulfilled();
});
+ it('resolves after browser initiated navigation', async () => {
+ let finishedLoading = false;
+ w.webContents.on('did-finish-load', function () {
+ finishedLoading = true;
+ });
+
+ await w.loadFile(path.join(fixturesPath, 'pages', 'navigate_in_page_and_wait.html'));
+ expect(finishedLoading).to.be.true();
+ });
+
it('rejects when failing to load a file URL', async () => {
await expect(w.loadURL('file:non-existent')).to.eventually.be.rejected()
.and.have.property('code', 'ERR_FILE_NOT_FOUND');
diff --git a/spec/fixtures/pages/navigate_in_page_and_wait.html b/spec/fixtures/pages/navigate_in_page_and_wait.html
new file mode 100644
index 0000000000..40b12b7385
--- /dev/null
+++ b/spec/fixtures/pages/navigate_in_page_and_wait.html
@@ -0,0 +1,13 @@
+<html>
+<header>
+<script type="text/javascript">
+ window.history.replaceState(window.location.href, "Sample Title", window.location.href);
+ // Simulate that we load web page.
+ for (let i = 0; i < 10000; i++) {
+ console.log('wait : ' + i);
+ }
+</script>
+</header>
+<body>
+</body>
+</html>
|
fix
|
62331f5ac14954367e1e762b9f206c81ebe35109
|
Shelley Vohr
|
2024-03-06 12:45:28
|
chore: add missing `gin::Wrappable` `GetTypeName` overrides (#41512)
chore: add missing gin::Wrappable GetTypeName overrides
|
diff --git a/shell/browser/api/electron_api_data_pipe_holder.cc b/shell/browser/api/electron_api_data_pipe_holder.cc
index 5b04ac29a1..7842211d46 100644
--- a/shell/browser/api/electron_api_data_pipe_holder.cc
+++ b/shell/browser/api/electron_api_data_pipe_holder.cc
@@ -162,6 +162,10 @@ v8::Local<v8::Promise> DataPipeHolder::ReadAll(v8::Isolate* isolate) {
return handle;
}
+const char* DataPipeHolder::GetTypeName() {
+ return "DataPipeHolder";
+}
+
// static
gin::Handle<DataPipeHolder> DataPipeHolder::Create(
v8::Isolate* isolate,
diff --git a/shell/browser/api/electron_api_data_pipe_holder.h b/shell/browser/api/electron_api_data_pipe_holder.h
index 17b9dd244a..cc3b1b32f6 100644
--- a/shell/browser/api/electron_api_data_pipe_holder.h
+++ b/shell/browser/api/electron_api_data_pipe_holder.h
@@ -18,7 +18,9 @@ namespace electron::api {
// Retains reference to the data pipe.
class DataPipeHolder : public gin::Wrappable<DataPipeHolder> {
public:
+ // gin::Wrappable
static gin::WrapperInfo kWrapperInfo;
+ const char* GetTypeName() override;
static gin::Handle<DataPipeHolder> Create(
v8::Isolate* isolate,
diff --git a/shell/browser/api/electron_api_power_save_blocker.cc b/shell/browser/api/electron_api_power_save_blocker.cc
index 2f3f9c727f..c34ffe989f 100644
--- a/shell/browser/api/electron_api_power_save_blocker.cc
+++ b/shell/browser/api/electron_api_power_save_blocker.cc
@@ -124,6 +124,10 @@ gin::ObjectTemplateBuilder PowerSaveBlocker::GetObjectTemplateBuilder(
.SetMethod("isStarted", &PowerSaveBlocker::IsStarted);
}
+const char* PowerSaveBlocker::GetTypeName() {
+ return "PowerSaveBlocker";
+}
+
} // namespace electron::api
namespace {
diff --git a/shell/browser/api/electron_api_power_save_blocker.h b/shell/browser/api/electron_api_power_save_blocker.h
index e4e495dbc2..349aaf18d7 100644
--- a/shell/browser/api/electron_api_power_save_blocker.h
+++ b/shell/browser/api/electron_api_power_save_blocker.h
@@ -19,10 +19,10 @@ class PowerSaveBlocker : public gin::Wrappable<PowerSaveBlocker> {
static gin::Handle<PowerSaveBlocker> Create(v8::Isolate* isolate);
// gin::Wrappable
+ static gin::WrapperInfo kWrapperInfo;
gin::ObjectTemplateBuilder GetObjectTemplateBuilder(
v8::Isolate* isolate) override;
-
- static gin::WrapperInfo kWrapperInfo;
+ const char* GetTypeName() override;
// disable copy
PowerSaveBlocker(const PowerSaveBlocker&) = delete;
diff --git a/shell/browser/api/electron_api_web_request.h b/shell/browser/api/electron_api_web_request.h
index a4bf0a9e10..c11267b2fb 100644
--- a/shell/browser/api/electron_api_web_request.h
+++ b/shell/browser/api/electron_api_web_request.h
@@ -24,8 +24,6 @@ namespace electron::api {
class WebRequest : public gin::Wrappable<WebRequest>, public WebRequestAPI {
public:
- static gin::WrapperInfo kWrapperInfo;
-
// Return the WebRequest object attached to |browser_context|, create if there
// is no one.
// Note that the lifetime of WebRequest object is managed by Session, instead
@@ -44,6 +42,7 @@ class WebRequest : public gin::Wrappable<WebRequest>, public WebRequestAPI {
content::BrowserContext* browser_context);
// gin::Wrappable:
+ static gin::WrapperInfo kWrapperInfo;
gin::ObjectTemplateBuilder GetObjectTemplateBuilder(
v8::Isolate* isolate) override;
const char* GetTypeName() override;
diff --git a/shell/browser/api/message_port.h b/shell/browser/api/message_port.h
index 70fe2add2d..9239db2aa5 100644
--- a/shell/browser/api/message_port.h
+++ b/shell/browser/api/message_port.h
@@ -53,9 +53,9 @@ class MessagePort : public gin::Wrappable<MessagePort>,
bool* threw_exception);
// gin::Wrappable
+ static gin::WrapperInfo kWrapperInfo;
gin::ObjectTemplateBuilder GetObjectTemplateBuilder(
v8::Isolate* isolate) override;
- static gin::WrapperInfo kWrapperInfo;
const char* GetTypeName() override;
private:
diff --git a/shell/common/api/electron_api_url_loader.cc b/shell/common/api/electron_api_url_loader.cc
index f84342dd81..5f622845f9 100644
--- a/shell/common/api/electron_api_url_loader.cc
+++ b/shell/common/api/electron_api_url_loader.cc
@@ -182,6 +182,8 @@ class JSChunkedDataPipeGetter : public gin::Wrappable<JSChunkedDataPipeGetter>,
.SetMethod("done", &JSChunkedDataPipeGetter::Done);
}
+ const char* GetTypeName() override { return "JSChunkedDataPipeGetter"; }
+
static gin::WrapperInfo kWrapperInfo;
~JSChunkedDataPipeGetter() override = default;
diff --git a/shell/common/gin_converters/net_converter.cc b/shell/common/gin_converters/net_converter.cc
index ec89a403e5..1f076e82a1 100644
--- a/shell/common/gin_converters/net_converter.cc
+++ b/shell/common/gin_converters/net_converter.cc
@@ -271,6 +271,8 @@ class ChunkedDataPipeReadableStream
.SetMethod("read", &ChunkedDataPipeReadableStream::Read);
}
+ const char* GetTypeName() override { return "ChunkedDataPipeReadableStream"; }
+
static gin::WrapperInfo kWrapperInfo;
private:
diff --git a/shell/common/gin_helper/event.cc b/shell/common/gin_helper/event.cc
index 347ee9ba97..e1ea3fd781 100644
--- a/shell/common/gin_helper/event.cc
+++ b/shell/common/gin_helper/event.cc
@@ -28,4 +28,8 @@ Event::~Event() = default;
gin::WrapperInfo Event::kWrapperInfo = {gin::kEmbedderNativeGin};
+const char* Event::GetTypeName() {
+ return GetClassName();
+}
+
} // namespace gin_helper::internal
diff --git a/shell/common/gin_helper/event.h b/shell/common/gin_helper/event.h
index b55426b9f5..a1565ffb7d 100644
--- a/shell/common/gin_helper/event.h
+++ b/shell/common/gin_helper/event.h
@@ -31,6 +31,7 @@ class Event : public gin::Wrappable<Event>,
// gin::Wrappable
static gin::WrapperInfo kWrapperInfo;
+ const char* GetTypeName() override;
~Event() override;
|
chore
|
06612cf5d49ee8571f08d375d2e77c926404afb6
|
Charles Kerr
|
2024-12-02 10:34:21
|
chore: remove unused isolate argument from Cookies constructor (#44907)
* chore: remove unused isolate argument from Cookies constructor
unused since the ginify cookies refactor in Mar 2020, commit 22202255
* fix: constructor only takes one arg now, so mark it explicit
|
diff --git a/shell/browser/api/electron_api_cookies.cc b/shell/browser/api/electron_api_cookies.cc
index 4ec26e9539..f0cb9131de 100644
--- a/shell/browser/api/electron_api_cookies.cc
+++ b/shell/browser/api/electron_api_cookies.cc
@@ -292,8 +292,8 @@ std::string StringToCookieSameSite(const std::string* str_ptr,
gin::WrapperInfo Cookies::kWrapperInfo = {gin::kEmbedderNativeGin};
-Cookies::Cookies(v8::Isolate* isolate, ElectronBrowserContext* browser_context)
- : browser_context_(browser_context) {
+Cookies::Cookies(ElectronBrowserContext* browser_context)
+ : browser_context_{browser_context} {
cookie_change_subscription_ =
browser_context_->cookie_change_notifier()->RegisterCookieChangeCallback(
base::BindRepeating(&Cookies::OnCookieChanged,
@@ -458,7 +458,7 @@ void Cookies::OnCookieChanged(const net::CookieChangeInfo& change) {
// static
gin::Handle<Cookies> Cookies::Create(v8::Isolate* isolate,
ElectronBrowserContext* browser_context) {
- return gin::CreateHandle(isolate, new Cookies(isolate, browser_context));
+ return gin::CreateHandle(isolate, new Cookies{browser_context});
}
gin::ObjectTemplateBuilder Cookies::GetObjectTemplateBuilder(
diff --git a/shell/browser/api/electron_api_cookies.h b/shell/browser/api/electron_api_cookies.h
index 64b2417927..a8f71cafd0 100644
--- a/shell/browser/api/electron_api_cookies.h
+++ b/shell/browser/api/electron_api_cookies.h
@@ -50,7 +50,7 @@ class Cookies final : public gin::Wrappable<Cookies>,
Cookies& operator=(const Cookies&) = delete;
protected:
- Cookies(v8::Isolate* isolate, ElectronBrowserContext* browser_context);
+ explicit Cookies(ElectronBrowserContext* browser_context);
~Cookies() override;
v8::Local<v8::Promise> Get(v8::Isolate*,
|
chore
|
563c370d51f302b6d4a7fee8b47e1cc3e1ca2fe3
|
Milan Burda
|
2023-10-10 12:45:44
|
refactor: use gin_helper::Dictionary::CreateEmpty() helper (#40140)
|
diff --git a/shell/browser/api/electron_api_base_window.cc b/shell/browser/api/electron_api_base_window.cc
index 373a536a46..071ebe3200 100644
--- a/shell/browser/api/electron_api_base_window.cc
+++ b/shell/browser/api/electron_api_base_window.cc
@@ -1180,8 +1180,7 @@ void BaseWindow::RemoveFromParentChildWindows() {
// static
gin_helper::WrappableBase* BaseWindow::New(gin_helper::Arguments* args) {
- gin_helper::Dictionary options =
- gin::Dictionary::CreateEmpty(args->isolate());
+ auto options = gin_helper::Dictionary::CreateEmpty(args->isolate());
args->GetNext(&options);
return new BaseWindow(args, options);
diff --git a/shell/browser/api/electron_api_browser_view.cc b/shell/browser/api/electron_api_browser_view.cc
index 9f703f1ec6..cc0641e347 100644
--- a/shell/browser/api/electron_api_browser_view.cc
+++ b/shell/browser/api/electron_api_browser_view.cc
@@ -74,8 +74,7 @@ gin::WrapperInfo BrowserView::kWrapperInfo = {gin::kEmbedderNativeGin};
BrowserView::BrowserView(gin::Arguments* args,
const gin_helper::Dictionary& options)
: id_(GetNextId()) {
- gin_helper::Dictionary web_preferences =
- gin::Dictionary::CreateEmpty(args->isolate());
+ auto web_preferences = gin_helper::Dictionary::CreateEmpty(args->isolate());
options.Get(options::kWebPreferences, &web_preferences);
web_preferences.Set("type", "browserView");
@@ -143,7 +142,7 @@ gin::Handle<BrowserView> BrowserView::New(gin_helper::ErrorThrower thrower,
return gin::Handle<BrowserView>();
}
- gin::Dictionary options = gin::Dictionary::CreateEmpty(args->isolate());
+ auto options = gin::Dictionary::CreateEmpty(args->isolate());
args->GetNext(&options);
auto handle =
diff --git a/shell/browser/api/electron_api_content_tracing.cc b/shell/browser/api/electron_api_content_tracing.cc
index f44f2d8494..4a5f373b69 100644
--- a/shell/browser/api/electron_api_content_tracing.cc
+++ b/shell/browser/api/electron_api_content_tracing.cc
@@ -152,7 +152,7 @@ void OnTraceBufferUsageAvailable(
gin_helper::Promise<gin_helper::Dictionary> promise,
float percent_full,
size_t approximate_count) {
- gin_helper::Dictionary dict = gin::Dictionary::CreateEmpty(promise.isolate());
+ auto dict = gin_helper::Dictionary::CreateEmpty(promise.isolate());
dict.Set("percentage", percent_full);
dict.Set("value", approximate_count);
diff --git a/shell/browser/api/electron_api_session.cc b/shell/browser/api/electron_api_session.cc
index 660b9b730a..bfe8db9456 100644
--- a/shell/browser/api/electron_api_session.cc
+++ b/shell/browser/api/electron_api_session.cc
@@ -448,8 +448,8 @@ v8::Local<v8::Promise> Session::ResolveHost(
DCHECK(addrs.has_value() && !addrs->empty());
v8::HandleScope handle_scope(promise.isolate());
- gin_helper::Dictionary dict =
- gin::Dictionary::CreateEmpty(promise.isolate());
+ auto dict =
+ gin_helper::Dictionary::CreateEmpty(promise.isolate());
dict.Set("endpoints", addrs->endpoints());
promise.Resolve(dict);
}
diff --git a/shell/browser/api/electron_api_web_contents.cc b/shell/browser/api/electron_api_web_contents.cc
index 4bd23d5b7b..cb6cdaacc7 100644
--- a/shell/browser/api/electron_api_web_contents.cc
+++ b/shell/browser/api/electron_api_web_contents.cc
@@ -1658,8 +1658,7 @@ void WebContents::RenderFrameCreated(
if (lifecycle_state == content::RenderFrameHost::LifecycleState::kActive) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
- gin_helper::Dictionary details =
- gin_helper::Dictionary::CreateEmpty(isolate);
+ auto details = gin_helper::Dictionary::CreateEmpty(isolate);
details.SetGetter("frame", render_frame_host);
Emit("frame-created", details);
}
@@ -1731,7 +1730,7 @@ void WebContents::PrimaryMainFrameRenderProcessGone(
base::TerminationStatus status) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope handle_scope(isolate);
- gin_helper::Dictionary details = gin_helper::Dictionary::CreateEmpty(isolate);
+ auto details = gin_helper::Dictionary::CreateEmpty(isolate);
details.Set("reason", status);
details.Set("exitCode", web_contents()->GetCrashedErrorCode());
Emit("render-process-gone", details);
@@ -2529,7 +2528,7 @@ v8::Local<v8::Value> WebContents::GetWebRTCUDPPortRange(
v8::Isolate* isolate) const {
auto* prefs = web_contents()->GetMutableRendererPrefs();
- gin_helper::Dictionary dict = gin::Dictionary::CreateEmpty(isolate);
+ auto dict = gin_helper::Dictionary::CreateEmpty(isolate);
dict.Set("min", static_cast<uint32_t>(prefs->webrtc_udp_min_port));
dict.Set("max", static_cast<uint32_t>(prefs->webrtc_udp_max_port));
return dict.GetHandle();
@@ -2907,8 +2906,7 @@ void WebContents::OnGetDeviceNameToUse(
}
void WebContents::Print(gin::Arguments* args) {
- gin_helper::Dictionary options =
- gin::Dictionary::CreateEmpty(args->isolate());
+ auto options = gin_helper::Dictionary::CreateEmpty(args->isolate());
base::Value::Dict settings;
if (args->Length() >= 1 && !args->GetNext(&options)) {
@@ -2933,8 +2931,7 @@ void WebContents::Print(gin::Arguments* args) {
settings.Set(printing::kSettingShouldPrintBackgrounds, print_background);
// Set custom margin settings
- gin_helper::Dictionary margins =
- gin::Dictionary::CreateEmpty(args->isolate());
+ auto margins = gin_helper::Dictionary::CreateEmpty(args->isolate());
if (options.Get("margins", &margins)) {
printing::mojom::MarginType margin_type =
printing::mojom::MarginType::kDefaultMargins;
diff --git a/shell/browser/bluetooth/electron_bluetooth_delegate.cc b/shell/browser/bluetooth/electron_bluetooth_delegate.cc
index b95b3f351a..94e7a3b2a6 100644
--- a/shell/browser/bluetooth/electron_bluetooth_delegate.cc
+++ b/shell/browser/bluetooth/electron_bluetooth_delegate.cc
@@ -169,8 +169,7 @@ void ElectronBluetoothDelegate::ShowDevicePairPrompt(
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope scope(isolate);
- gin_helper::Dictionary details =
- gin_helper::Dictionary::CreateEmpty(isolate);
+ auto details = gin_helper::Dictionary::CreateEmpty(isolate);
details.Set("deviceId", device_identifier);
details.Set("pairingKind", pairing_kind);
details.SetGetter("frame", frame);
diff --git a/shell/browser/hid/hid_chooser_context.cc b/shell/browser/hid/hid_chooser_context.cc
index 1a01be443b..1ca309be62 100644
--- a/shell/browser/hid/hid_chooser_context.cc
+++ b/shell/browser/hid/hid_chooser_context.cc
@@ -119,8 +119,7 @@ void HidChooserContext::RevokeDevicePermission(
if (session) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope scope(isolate);
- gin_helper::Dictionary details =
- gin_helper::Dictionary::CreateEmpty(isolate);
+ auto details = gin_helper::Dictionary::CreateEmpty(isolate);
details.Set("device", device.Clone());
details.Set("origin", origin.Serialize());
session->Emit("hid-device-revoked", details);
diff --git a/shell/browser/native_window.cc b/shell/browser/native_window.cc
index 12e8e36782..90540c2689 100644
--- a/shell/browser/native_window.cc
+++ b/shell/browser/native_window.cc
@@ -114,8 +114,8 @@ NativeWindow::NativeWindow(const gin_helper::Dictionary& options,
} else if (titlebar_overlay->IsObject()) {
titlebar_overlay_ = true;
- gin_helper::Dictionary titlebar_overlay_dict =
- gin::Dictionary::CreateEmpty(options.isolate());
+ auto titlebar_overlay_dict =
+ gin_helper::Dictionary::CreateEmpty(options.isolate());
options.Get(options::ktitleBarOverlay, &titlebar_overlay_dict);
int height;
if (titlebar_overlay_dict.Get(options::kOverlayHeight, &height))
diff --git a/shell/browser/native_window_views.cc b/shell/browser/native_window_views.cc
index d67f31388c..e895ffc2c0 100644
--- a/shell/browser/native_window_views.cc
+++ b/shell/browser/native_window_views.cc
@@ -231,8 +231,8 @@ NativeWindowViews::NativeWindowViews(const gin_helper::Dictionary& options,
v8::Local<v8::Value> titlebar_overlay;
if (options.Get(options::ktitleBarOverlay, &titlebar_overlay) &&
titlebar_overlay->IsObject()) {
- gin_helper::Dictionary titlebar_overlay_obj =
- gin::Dictionary::CreateEmpty(options.isolate());
+ auto titlebar_overlay_obj =
+ gin_helper::Dictionary::CreateEmpty(options.isolate());
options.Get(options::ktitleBarOverlay, &titlebar_overlay_obj);
std::string overlay_color_string;
diff --git a/shell/browser/serial/serial_chooser_context.cc b/shell/browser/serial/serial_chooser_context.cc
index e2dd32d619..521fe7c53a 100644
--- a/shell/browser/serial/serial_chooser_context.cc
+++ b/shell/browser/serial/serial_chooser_context.cc
@@ -158,8 +158,7 @@ void SerialChooserContext::RevokePortPermissionWebInitiated(
if (session) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope scope(isolate);
- gin_helper::Dictionary details =
- gin_helper::Dictionary::CreateEmpty(isolate);
+ auto details = gin_helper::Dictionary::CreateEmpty(isolate);
details.Set("port", it->second);
details.SetGetter("frame", render_frame_host);
details.Set("origin", origin.Serialize());
diff --git a/shell/browser/ui/file_dialog_gtk.cc b/shell/browser/ui/file_dialog_gtk.cc
index c8a81553c4..ffe2e7a86f 100644
--- a/shell/browser/ui/file_dialog_gtk.cc
+++ b/shell/browser/ui/file_dialog_gtk.cc
@@ -246,8 +246,7 @@ void FileChooserDialog::OnFileDialogResponse(GtkWidget* widget, int response) {
v8::Isolate* isolate = electron::JavascriptEnvironment::GetIsolate();
v8::HandleScope scope(isolate);
if (save_promise_) {
- gin_helper::Dictionary dict =
- gin::Dictionary::CreateEmpty(save_promise_->isolate());
+ auto dict = gin_helper::Dictionary::CreateEmpty(save_promise_->isolate());
if (response == GTK_RESPONSE_ACCEPT) {
dict.Set("canceled", false);
dict.Set("filePath", GetFileName());
@@ -257,8 +256,7 @@ void FileChooserDialog::OnFileDialogResponse(GtkWidget* widget, int response) {
}
save_promise_->Resolve(dict);
} else if (open_promise_) {
- gin_helper::Dictionary dict =
- gin::Dictionary::CreateEmpty(open_promise_->isolate());
+ auto dict = gin_helper::Dictionary::CreateEmpty(open_promise_->isolate());
if (response == GTK_RESPONSE_ACCEPT) {
dict.Set("canceled", false);
dict.Set("filePaths", GetFileNames());
diff --git a/shell/browser/ui/file_dialog_mac.mm b/shell/browser/ui/file_dialog_mac.mm
index 045260036a..1c9a044e01 100644
--- a/shell/browser/ui/file_dialog_mac.mm
+++ b/shell/browser/ui/file_dialog_mac.mm
@@ -353,7 +353,7 @@ void OpenDialogCompletion(int chosen,
bool security_scoped_bookmarks,
gin_helper::Promise<gin_helper::Dictionary> promise) {
v8::HandleScope scope(promise.isolate());
- gin_helper::Dictionary dict = gin::Dictionary::CreateEmpty(promise.isolate());
+ auto dict = gin_helper::Dictionary::CreateEmpty(promise.isolate());
if (chosen == NSModalResponseCancel) {
dict.Set("canceled", true);
dict.Set("filePaths", std::vector<base::FilePath>());
@@ -431,7 +431,7 @@ void SaveDialogCompletion(int chosen,
bool security_scoped_bookmarks,
gin_helper::Promise<gin_helper::Dictionary> promise) {
v8::HandleScope scope(promise.isolate());
- gin_helper::Dictionary dict = gin::Dictionary::CreateEmpty(promise.isolate());
+ auto dict = gin_helper::Dictionary::CreateEmpty(promise.isolate());
if (chosen == NSModalResponseCancel) {
dict.Set("canceled", true);
dict.Set("filePath", base::FilePath());
diff --git a/shell/browser/ui/file_dialog_win.cc b/shell/browser/ui/file_dialog_win.cc
index cefe30f245..3e82b9cfad 100644
--- a/shell/browser/ui/file_dialog_win.cc
+++ b/shell/browser/ui/file_dialog_win.cc
@@ -220,7 +220,7 @@ void ShowOpenDialog(const DialogSettings& settings,
auto done = [](gin_helper::Promise<gin_helper::Dictionary> promise,
bool success, std::vector<base::FilePath> result) {
v8::HandleScope handle_scope(promise.isolate());
- gin::Dictionary dict = gin::Dictionary::CreateEmpty(promise.isolate());
+ auto dict = gin::Dictionary::CreateEmpty(promise.isolate());
dict.Set("canceled", !success);
dict.Set("filePaths", result);
promise.Resolve(dict);
@@ -269,7 +269,7 @@ void ShowSaveDialog(const DialogSettings& settings,
auto done = [](gin_helper::Promise<gin_helper::Dictionary> promise,
bool success, base::FilePath result) {
v8::HandleScope handle_scope(promise.isolate());
- gin::Dictionary dict = gin::Dictionary::CreateEmpty(promise.isolate());
+ auto dict = gin::Dictionary::CreateEmpty(promise.isolate());
dict.Set("canceled", !success);
dict.Set("filePath", result);
promise.Resolve(dict);
diff --git a/shell/browser/usb/usb_chooser_context.cc b/shell/browser/usb/usb_chooser_context.cc
index 53df5c666f..78289af41b 100644
--- a/shell/browser/usb/usb_chooser_context.cc
+++ b/shell/browser/usb/usb_chooser_context.cc
@@ -203,8 +203,7 @@ void UsbChooserContext::RevokeObjectPermissionInternal(
if (session) {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope scope(isolate);
- gin_helper::Dictionary details =
- gin_helper::Dictionary::CreateEmpty(isolate);
+ auto details = gin_helper::Dictionary::CreateEmpty(isolate);
details.Set("device", object);
details.Set("origin", origin.Serialize());
session->Emit("usb-device-revoked", details);
diff --git a/shell/common/api/electron_api_clipboard.cc b/shell/common/api/electron_api_clipboard.cc
index 84a3a1337f..ea1c8d5f91 100644
--- a/shell/common/api/electron_api_clipboard.cc
+++ b/shell/common/api/electron_api_clipboard.cc
@@ -204,8 +204,7 @@ void Clipboard::WriteHTML(const std::u16string& html,
v8::Local<v8::Value> Clipboard::ReadBookmark(gin_helper::Arguments* args) {
std::u16string title;
std::string url;
- gin_helper::Dictionary dict =
- gin_helper::Dictionary::CreateEmpty(args->isolate());
+ auto dict = gin_helper::Dictionary::CreateEmpty(args->isolate());
ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread();
clipboard->ReadBookmark(/* data_dst = */ nullptr, &title, &url);
dict.Set("title", title);
diff --git a/shell/common/api/electron_api_shell.cc b/shell/common/api/electron_api_shell.cc
index 1055cb73d4..b05b5216b5 100644
--- a/shell/common/api/electron_api_shell.cc
+++ b/shell/common/api/electron_api_shell.cc
@@ -111,7 +111,7 @@ bool WriteShortcutLink(const base::FilePath& shortcut_path,
base::win::ShortcutOperation operation =
base::win::ShortcutOperation::kCreateAlways;
args->GetNext(&operation);
- gin::Dictionary options = gin::Dictionary::CreateEmpty(args->isolate());
+ auto options = gin::Dictionary::CreateEmpty(args->isolate());
if (!args->GetNext(&options)) {
args->ThrowError();
return false;
@@ -146,7 +146,7 @@ bool WriteShortcutLink(const base::FilePath& shortcut_path,
v8::Local<v8::Value> ReadShortcutLink(gin_helper::ErrorThrower thrower,
const base::FilePath& path) {
using base::win::ShortcutProperties;
- gin::Dictionary options = gin::Dictionary::CreateEmpty(thrower.isolate());
+ auto options = gin::Dictionary::CreateEmpty(thrower.isolate());
electron::ScopedAllowBlockingForElectron allow_blocking;
base::win::ScopedCOMInitializer com_initializer;
base::win::ShortcutProperties properties;
diff --git a/shell/renderer/api/electron_api_context_bridge.cc b/shell/renderer/api/electron_api_context_bridge.cc
index 674a503eb9..2a5e22728b 100644
--- a/shell/renderer/api/electron_api_context_bridge.cc
+++ b/shell/renderer/api/electron_api_context_bridge.cc
@@ -573,8 +573,8 @@ v8::MaybeLocal<v8::Object> CreateProxyForAPI(
{
v8::Context::Scope destination_context_scope(destination_context);
- gin_helper::Dictionary proxy =
- gin::Dictionary::CreateEmpty(destination_context->GetIsolate());
+ auto proxy =
+ gin_helper::Dictionary::CreateEmpty(destination_context->GetIsolate());
object_cache->CacheProxiedObject(api.GetHandle(), proxy.GetHandle());
auto maybe_keys = api.GetHandle()->GetOwnPropertyNames(
source_context, static_cast<v8::PropertyFilter>(v8::ONLY_ENUMERABLE));
|
refactor
|
09e6e4b9a7862416e1ac8e45d94c17b015a80165
|
Michaela Laurencin
|
2023-07-24 06:33:41
|
docs: update window-open.md to include target (#39162)
Update window-open.md to include target
|
diff --git a/docs/api/window-open.md b/docs/api/window-open.md
index a0af4ab611..0f2fab7751 100644
--- a/docs/api/window-open.md
+++ b/docs/api/window-open.md
@@ -59,7 +59,7 @@ window.open('https://github.com', '_blank', 'top=500,left=200,frame=false,nodeIn
* Non-standard features (that are not handled by Chromium or Electron) given in
`features` will be passed to any registered `webContents`'s
`did-create-window` event handler in the `options` argument.
-* `frameName` follows the specification of `windowName` located in the [native documentation](https://developer.mozilla.org/en-US/docs/Web/API/Window/open#parameters).
+* `frameName` follows the specification of `target` located in the [native documentation](https://developer.mozilla.org/en-US/docs/Web/API/Window/open#parameters).
* When opening `about:blank`, the child window's [`WebPreferences`](structures/web-preferences.md) will be copied
from the parent window, and there is no way to override it because Chromium
skips browser side navigation in this case.
|
docs
|
9280b79112be0dc307ed81784c885d896bb20e5e
|
Milan Burda
|
2023-08-29 21:52:16
|
docs: enable contextIsolation in fiddles (#39613)
|
diff --git a/docs/fiddles/features/web-bluetooth/preload.js b/docs/fiddles/features/web-bluetooth/preload.js
index 6800eaccd9..1b1c636725 100644
--- a/docs/fiddles/features/web-bluetooth/preload.js
+++ b/docs/fiddles/features/web-bluetooth/preload.js
@@ -1,7 +1,7 @@
const { contextBridge, ipcRenderer } = require('electron/renderer')
contextBridge.exposeInMainWorld('electronAPI', {
- cancelBluetoothRequest: (callback) => ipcRenderer.send('cancel-bluetooth-request', callback),
- bluetoothPairingRequest: (callback) => ipcRenderer.on('bluetooth-pairing-request', callback),
+ cancelBluetoothRequest: () => ipcRenderer.send('cancel-bluetooth-request'),
+ bluetoothPairingRequest: (callback) => ipcRenderer.on('bluetooth-pairing-request', () => callback()),
bluetoothPairingResponse: (response) => ipcRenderer.send('bluetooth-pairing-response', response)
})
diff --git a/docs/fiddles/ipc/pattern-3/preload.js b/docs/fiddles/ipc/pattern-3/preload.js
index 0c0402e53f..1df2941caa 100644
--- a/docs/fiddles/ipc/pattern-3/preload.js
+++ b/docs/fiddles/ipc/pattern-3/preload.js
@@ -1,5 +1,5 @@
const { contextBridge, ipcRenderer } = require('electron/renderer')
contextBridge.exposeInMainWorld('electronAPI', {
- handleCounter: (callback) => ipcRenderer.on('update-counter', callback)
+ handleCounter: (callback) => ipcRenderer.on('update-counter', () => callback())
})
diff --git a/docs/fiddles/media/screenshot/take-screenshot/index.html b/docs/fiddles/media/screenshot/take-screenshot/index.html
index 264899abdd..ca05880ef4 100644
--- a/docs/fiddles/media/screenshot/take-screenshot/index.html
+++ b/docs/fiddles/media/screenshot/take-screenshot/index.html
@@ -17,9 +17,6 @@
<p>Clicking the demo button will take a screenshot of your current screen and open it in your default viewer.</p>
</div>
</div>
- <script>
- // You can also require other files to run in this process
- require('./renderer.js')
- </script>
+ <script src="renderer.js"></script>
</body>
</html>
diff --git a/docs/fiddles/media/screenshot/take-screenshot/main.js b/docs/fiddles/media/screenshot/take-screenshot/main.js
index 73b8b97870..2ce55cd94a 100644
--- a/docs/fiddles/media/screenshot/take-screenshot/main.js
+++ b/docs/fiddles/media/screenshot/take-screenshot/main.js
@@ -1,14 +1,38 @@
-const { BrowserWindow, app, screen, ipcMain, desktopCapturer } = require('electron/main')
+const { BrowserWindow, app, screen, ipcMain, desktopCapturer, shell } = require('electron/main')
+const fs = require('node:fs').promises
+const os = require('node:os')
+const path = require('node:path')
let mainWindow = null
-ipcMain.handle('get-screen-size', () => {
- return screen.getPrimaryDisplay().workAreaSize
-})
+function determineScreenShotSize (devicePixelRatio) {
+ const screenSize = screen.getPrimaryDisplay().workAreaSize
+ const maxDimension = Math.max(screenSize.width, screenSize.height)
+ return {
+ width: maxDimension * devicePixelRatio,
+ height: maxDimension * devicePixelRatio
+ }
+}
-ipcMain.handle('get-sources', (event, options) => {
- return desktopCapturer.getSources(options)
-})
+async function takeScreenshot (devicePixelRatio) {
+ const thumbSize = determineScreenShotSize(devicePixelRatio)
+ const options = { types: ['screen'], thumbnailSize: thumbSize }
+
+ const sources = await desktopCapturer.getSources(options)
+ for (const source of sources) {
+ const sourceName = source.name.toLowerCase()
+ if (sourceName === 'entire screen' || sourceName === 'screen 1') {
+ const screenshotPath = path.join(os.tmpdir(), 'screenshot.png')
+
+ await fs.writeFile(screenshotPath, source.thumbnail.toPNG())
+ shell.openExternal(`file://${screenshotPath}`)
+
+ return `Saved screenshot to: ${screenshotPath}`
+ }
+ }
+}
+
+ipcMain.handle('take-screenshot', (event, devicePixelRatio) => takeScreenshot(devicePixelRatio))
function createWindow () {
const windowOptions = {
@@ -16,8 +40,7 @@ function createWindow () {
height: 300,
title: 'Take a Screenshot',
webPreferences: {
- contextIsolation: false,
- nodeIntegration: true
+ preload: path.join(__dirname, 'preload.js')
}
}
diff --git a/docs/fiddles/media/screenshot/take-screenshot/preload.js b/docs/fiddles/media/screenshot/take-screenshot/preload.js
new file mode 100644
index 0000000000..9af9f2faac
--- /dev/null
+++ b/docs/fiddles/media/screenshot/take-screenshot/preload.js
@@ -0,0 +1,5 @@
+const { contextBridge, ipcRenderer } = require('electron/renderer')
+
+contextBridge.exposeInMainWorld('electronAPI', {
+ takeScreenshot: () => ipcRenderer.invoke('take-screenshot', window.devicePixelRatio)
+})
diff --git a/docs/fiddles/media/screenshot/take-screenshot/renderer.js b/docs/fiddles/media/screenshot/take-screenshot/renderer.js
index 4712a2f0ea..6b4329e7df 100644
--- a/docs/fiddles/media/screenshot/take-screenshot/renderer.js
+++ b/docs/fiddles/media/screenshot/take-screenshot/renderer.js
@@ -1,37 +1,7 @@
-const { shell, ipcRenderer } = require('electron/renderer')
-
-const fs = require('node:fs').promises
-const os = require('node:os')
-const path = require('node:path')
-
const screenshot = document.getElementById('screen-shot')
const screenshotMsg = document.getElementById('screenshot-path')
screenshot.addEventListener('click', async (event) => {
screenshotMsg.textContent = 'Gathering screens...'
- const thumbSize = await determineScreenShotSize()
- const options = { types: ['screen'], thumbnailSize: thumbSize }
-
- const sources = await ipcRenderer.invoke('get-sources', options)
- for (const source of sources) {
- const sourceName = source.name.toLowerCase()
- if (sourceName === 'entire screen' || sourceName === 'screen 1') {
- const screenshotPath = path.join(os.tmpdir(), 'screenshot.png')
-
- await fs.writeFile(screenshotPath, source.thumbnail.toPNG())
- shell.openExternal(`file://${screenshotPath}`)
-
- const message = `Saved screenshot to: ${screenshotPath}`
- screenshotMsg.textContent = message
- }
- }
+ screenshotMsg.textContent = await window.electronAPI.takeScreenshot()
})
-
-async function determineScreenShotSize () {
- const screenSize = await ipcRenderer.invoke('get-screen-size')
- const maxDimension = Math.max(screenSize.width, screenSize.height)
- return {
- width: maxDimension * window.devicePixelRatio,
- height: maxDimension * window.devicePixelRatio
- }
-}
diff --git a/docs/fiddles/menus/customize-menus/index.html b/docs/fiddles/menus/customize-menus/index.html
index 798745c173..1fda8f5ecd 100644
--- a/docs/fiddles/menus/customize-menus/index.html
+++ b/docs/fiddles/menus/customize-menus/index.html
@@ -119,10 +119,6 @@
</div>
</div>
</div>
-
- <script>
- // You can also require other files to run in this process
- require("./renderer.js");
- </script>
+ <script src="renderer.js"></script>
</body>
</html>
diff --git a/docs/fiddles/menus/customize-menus/main.js b/docs/fiddles/menus/customize-menus/main.js
index 63289526d9..3fc16f847d 100644
--- a/docs/fiddles/menus/customize-menus/main.js
+++ b/docs/fiddles/menus/customize-menus/main.js
@@ -9,6 +9,7 @@ const {
dialog,
autoUpdater
} = require('electron/main')
+const path = require('node:path')
const menu = new Menu()
menu.append(new MenuItem({ label: 'Hello' }))
@@ -295,8 +296,7 @@ function createWindow () {
width: 800,
height: 600,
webPreferences: {
- contextIsolation: false,
- nodeIntegration: true
+ preload: path.join(__dirname, 'preload.js')
}
})
diff --git a/docs/fiddles/menus/customize-menus/preload.js b/docs/fiddles/menus/customize-menus/preload.js
new file mode 100644
index 0000000000..00bc6be37d
--- /dev/null
+++ b/docs/fiddles/menus/customize-menus/preload.js
@@ -0,0 +1,5 @@
+const { contextBridge, ipcRenderer } = require('electron/renderer')
+
+contextBridge.exposeInMainWorld('electronAPI', {
+ showContextMenu: () => ipcRenderer.send('show-context-menu')
+})
diff --git a/docs/fiddles/menus/customize-menus/renderer.js b/docs/fiddles/menus/customize-menus/renderer.js
index 372db5ce68..89ba97dcc5 100644
--- a/docs/fiddles/menus/customize-menus/renderer.js
+++ b/docs/fiddles/menus/customize-menus/renderer.js
@@ -1,8 +1,6 @@
-const { ipcRenderer } = require('electron/renderer')
-
// Tell main process to show the menu when demo button is clicked
const contextMenuBtn = document.getElementById('context-menu')
contextMenuBtn.addEventListener('click', () => {
- ipcRenderer.send('show-context-menu')
+ window.electronAPI.showContextMenu()
})
diff --git a/docs/fiddles/menus/shortcuts/main.js b/docs/fiddles/menus/shortcuts/main.js
index 1b295eef49..9207702d44 100644
--- a/docs/fiddles/menus/shortcuts/main.js
+++ b/docs/fiddles/menus/shortcuts/main.js
@@ -9,11 +9,7 @@ function createWindow () {
// Create the browser window.
mainWindow = new BrowserWindow({
width: 800,
- height: 600,
- webPreferences: {
- contextIsolation: false,
- nodeIntegration: true
- }
+ height: 600
})
globalShortcut.register('CommandOrControl+Alt+K', () => {
diff --git a/docs/fiddles/native-ui/dialogs/error-dialog/index.html b/docs/fiddles/native-ui/dialogs/error-dialog/index.html
index bce7d0db84..8f694ed265 100644
--- a/docs/fiddles/native-ui/dialogs/error-dialog/index.html
+++ b/docs/fiddles/native-ui/dialogs/error-dialog/index.html
@@ -73,9 +73,6 @@ ipcMain.on('open-error-dialog', (event) => {
</div>
</div>
- <script>
- // You can also require other files to run in this process
- require("./renderer.js");
- </script>
+ <script src="renderer.js"></script>
</body>
</html>
diff --git a/docs/fiddles/native-ui/dialogs/error-dialog/main.js b/docs/fiddles/native-ui/dialogs/error-dialog/main.js
index bfedd4a3be..149cf4e0f5 100644
--- a/docs/fiddles/native-ui/dialogs/error-dialog/main.js
+++ b/docs/fiddles/native-ui/dialogs/error-dialog/main.js
@@ -1,5 +1,6 @@
// Modules to control application life and create native browser window
const { app, BrowserWindow, ipcMain, dialog, shell } = require('electron/main')
+const path = require('node:path')
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
@@ -11,8 +12,7 @@ function createWindow () {
width: 800,
height: 600,
webPreferences: {
- contextIsolation: false,
- nodeIntegration: true
+ preload: path.join(__dirname, 'preload.js')
}
})
diff --git a/docs/fiddles/native-ui/dialogs/error-dialog/preload.js b/docs/fiddles/native-ui/dialogs/error-dialog/preload.js
new file mode 100644
index 0000000000..e47c74f614
--- /dev/null
+++ b/docs/fiddles/native-ui/dialogs/error-dialog/preload.js
@@ -0,0 +1,5 @@
+const { contextBridge, ipcRenderer } = require('electron/renderer')
+
+contextBridge.exposeInMainWorld('electronAPI', {
+ openErrorDialog: () => ipcRenderer.send('open-error-dialog')
+})
diff --git a/docs/fiddles/native-ui/dialogs/error-dialog/renderer.js b/docs/fiddles/native-ui/dialogs/error-dialog/renderer.js
index 0dff640bf8..20ae84f772 100644
--- a/docs/fiddles/native-ui/dialogs/error-dialog/renderer.js
+++ b/docs/fiddles/native-ui/dialogs/error-dialog/renderer.js
@@ -1,7 +1,5 @@
-const { ipcRenderer } = require('electron/renderer')
-
const errorBtn = document.getElementById('error-dialog')
-errorBtn.addEventListener('click', event => {
- ipcRenderer.send('open-error-dialog')
+errorBtn.addEventListener('click', () => {
+ window.electronAPI.openErrorDialog()
})
diff --git a/docs/fiddles/native-ui/dialogs/information-dialog/index.html b/docs/fiddles/native-ui/dialogs/information-dialog/index.html
index 4823946cb8..8e28f86362 100644
--- a/docs/fiddles/native-ui/dialogs/information-dialog/index.html
+++ b/docs/fiddles/native-ui/dialogs/information-dialog/index.html
@@ -96,9 +96,6 @@ ipcMain.on('open-information-dialog', (event) => {
</div>
</div>
- <script>
- // You can also require other files to run in this process
- require("./renderer.js");
- </script>
+ <script src="renderer.js"></script>
</body>
</html>
diff --git a/docs/fiddles/native-ui/dialogs/information-dialog/main.js b/docs/fiddles/native-ui/dialogs/information-dialog/main.js
index bb0196e817..bbe460464c 100644
--- a/docs/fiddles/native-ui/dialogs/information-dialog/main.js
+++ b/docs/fiddles/native-ui/dialogs/information-dialog/main.js
@@ -1,5 +1,6 @@
// Modules to control application life and create native browser window
const { app, BrowserWindow, ipcMain, dialog, shell } = require('electron/main')
+const path = require('node:path')
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
@@ -11,8 +12,7 @@ function createWindow () {
width: 800,
height: 600,
webPreferences: {
- contextIsolation: false,
- nodeIntegration: true
+ preload: path.join(__dirname, 'preload.js')
}
})
@@ -59,16 +59,14 @@ app.on('activate', function () {
}
})
-ipcMain.on('open-information-dialog', event => {
+ipcMain.handle('open-information-dialog', async () => {
const options = {
type: 'info',
title: 'Information',
message: "This is an information dialog. Isn't it nice?",
buttons: ['Yes', 'No']
}
- dialog.showMessageBox(options, index => {
- event.sender.send('information-dialog-selection', index)
- })
+ return (await dialog.showMessageBox(options)).response
})
// In this file you can include the rest of your app's specific main process
diff --git a/docs/fiddles/native-ui/dialogs/information-dialog/preload.js b/docs/fiddles/native-ui/dialogs/information-dialog/preload.js
new file mode 100644
index 0000000000..5191aacea2
--- /dev/null
+++ b/docs/fiddles/native-ui/dialogs/information-dialog/preload.js
@@ -0,0 +1,5 @@
+const { contextBridge, ipcRenderer } = require('electron/renderer')
+
+contextBridge.exposeInMainWorld('electronAPI', {
+ openInformationDialog: () => ipcRenderer.invoke('open-information-dialog')
+})
diff --git a/docs/fiddles/native-ui/dialogs/information-dialog/renderer.js b/docs/fiddles/native-ui/dialogs/information-dialog/renderer.js
index f6fe51bac7..57c8fcc006 100644
--- a/docs/fiddles/native-ui/dialogs/information-dialog/renderer.js
+++ b/docs/fiddles/native-ui/dialogs/information-dialog/renderer.js
@@ -1,14 +1,7 @@
-const { ipcRenderer } = require('electron/renderer')
-
const informationBtn = document.getElementById('information-dialog')
-informationBtn.addEventListener('click', event => {
- ipcRenderer.send('open-information-dialog')
-})
-
-ipcRenderer.on('information-dialog-selection', (event, index) => {
- let message = 'You selected '
- if (index === 0) message += 'yes.'
- else message += 'no.'
+informationBtn.addEventListener('click', async () => {
+ const index = await window.electronAPI.openInformationDialog()
+ const message = `You selected: ${index === 0 ? 'yes' : 'no'}`
document.getElementById('info-selection').innerHTML = message
})
diff --git a/docs/fiddles/native-ui/dialogs/open-file-or-directory/index.html b/docs/fiddles/native-ui/dialogs/open-file-or-directory/index.html
index 226888218f..9443a62ce9 100644
--- a/docs/fiddles/native-ui/dialogs/open-file-or-directory/index.html
+++ b/docs/fiddles/native-ui/dialogs/open-file-or-directory/index.html
@@ -100,9 +100,6 @@ ipc.on('open-file-dialog-sheet', function (event) {
</div>
</div>
- <script>
- // You can also require other files to run in this process
- require("./renderer.js");
- </script>
+ <script src="renderer.js"></script>
</body>
</html>
diff --git a/docs/fiddles/native-ui/dialogs/open-file-or-directory/main.js b/docs/fiddles/native-ui/dialogs/open-file-or-directory/main.js
index 52ead02c9d..5721c69869 100644
--- a/docs/fiddles/native-ui/dialogs/open-file-or-directory/main.js
+++ b/docs/fiddles/native-ui/dialogs/open-file-or-directory/main.js
@@ -1,5 +1,6 @@
// Modules to control application life and create native browser window
const { app, BrowserWindow, ipcMain, dialog, shell } = require('electron/main')
+const path = require('node:path')
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
@@ -11,8 +12,7 @@ function createWindow () {
width: 800,
height: 600,
webPreferences: {
- contextIsolation: false,
- nodeIntegration: true
+ preload: path.join(__dirname, 'preload.js')
}
})
@@ -59,17 +59,11 @@ app.on('activate', function () {
}
})
-ipcMain.on('open-file-dialog', event => {
- dialog.showOpenDialog(
- {
- properties: ['openFile', 'openDirectory']
- },
- files => {
- if (files) {
- event.sender.send('selected-directory', files)
- }
- }
- )
+ipcMain.handle('open-file-dialog', async () => {
+ const options = {
+ properties: ['openFile', 'openDirectory']
+ }
+ return (await dialog.showOpenDialog(options)).filePaths
})
// In this file you can include the rest of your app's specific main process
diff --git a/docs/fiddles/native-ui/dialogs/open-file-or-directory/preload.js b/docs/fiddles/native-ui/dialogs/open-file-or-directory/preload.js
new file mode 100644
index 0000000000..ace7c2d165
--- /dev/null
+++ b/docs/fiddles/native-ui/dialogs/open-file-or-directory/preload.js
@@ -0,0 +1,5 @@
+const { contextBridge, ipcRenderer } = require('electron/renderer')
+
+contextBridge.exposeInMainWorld('electronAPI', {
+ openFileDialog: () => ipcRenderer.invoke('open-file-dialog')
+})
diff --git a/docs/fiddles/native-ui/dialogs/open-file-or-directory/renderer.js b/docs/fiddles/native-ui/dialogs/open-file-or-directory/renderer.js
index 0c5efd6735..badfd8776e 100644
--- a/docs/fiddles/native-ui/dialogs/open-file-or-directory/renderer.js
+++ b/docs/fiddles/native-ui/dialogs/open-file-or-directory/renderer.js
@@ -1,11 +1,6 @@
-const { ipcRenderer } = require('electron/renderer')
-
const selectDirBtn = document.getElementById('select-directory')
-selectDirBtn.addEventListener('click', event => {
- ipcRenderer.send('open-file-dialog')
-})
-
-ipcRenderer.on('selected-directory', (event, path) => {
+selectDirBtn.addEventListener('click', async () => {
+ const path = await window.electronAPI.openFileDialog()
document.getElementById('selected-file').innerHTML = `You selected: ${path}`
})
diff --git a/docs/fiddles/native-ui/dialogs/save-dialog/index.html b/docs/fiddles/native-ui/dialogs/save-dialog/index.html
index 6165af46ae..d8e97edbf8 100644
--- a/docs/fiddles/native-ui/dialogs/save-dialog/index.html
+++ b/docs/fiddles/native-ui/dialogs/save-dialog/index.html
@@ -83,9 +83,6 @@ ipcMain.on('save-dialog', (event) => {
</div>
</div>
- <script>
- // You can also require other files to run in this process
- require("./renderer.js");
- </script>
+ <script src="renderer.js"></script>
</body>
</html>
diff --git a/docs/fiddles/native-ui/dialogs/save-dialog/main.js b/docs/fiddles/native-ui/dialogs/save-dialog/main.js
index d33fa33d32..44c8fa1a1e 100644
--- a/docs/fiddles/native-ui/dialogs/save-dialog/main.js
+++ b/docs/fiddles/native-ui/dialogs/save-dialog/main.js
@@ -1,5 +1,6 @@
// Modules to control application life and create native browser window
const { app, BrowserWindow, ipcMain, dialog, shell } = require('electron/main')
+const path = require('node:path')
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
@@ -11,8 +12,7 @@ function createWindow () {
width: 800,
height: 600,
webPreferences: {
- contextIsolation: false,
- nodeIntegration: true
+ preload: path.join(__dirname, 'preload.js')
}
})
@@ -59,14 +59,12 @@ app.on('activate', function () {
}
})
-ipcMain.on('save-dialog', event => {
+ipcMain.handle('save-dialog', async () => {
const options = {
title: 'Save an Image',
filters: [{ name: 'Images', extensions: ['jpg', 'png', 'gif'] }]
}
- dialog.showSaveDialog(options, filename => {
- event.sender.send('saved-file', filename)
- })
+ return (await dialog.showSaveDialog(options)).filePath
})
// In this file you can include the rest of your app's specific main process
diff --git a/docs/fiddles/native-ui/dialogs/save-dialog/preload.js b/docs/fiddles/native-ui/dialogs/save-dialog/preload.js
new file mode 100644
index 0000000000..6d63c2e455
--- /dev/null
+++ b/docs/fiddles/native-ui/dialogs/save-dialog/preload.js
@@ -0,0 +1,5 @@
+const { contextBridge, ipcRenderer } = require('electron/renderer')
+
+contextBridge.exposeInMainWorld('electronAPI', {
+ saveDialog: () => ipcRenderer.invoke('save-dialog')
+})
diff --git a/docs/fiddles/native-ui/dialogs/save-dialog/renderer.js b/docs/fiddles/native-ui/dialogs/save-dialog/renderer.js
index ae06226891..c36088c775 100644
--- a/docs/fiddles/native-ui/dialogs/save-dialog/renderer.js
+++ b/docs/fiddles/native-ui/dialogs/save-dialog/renderer.js
@@ -1,12 +1,6 @@
-const { ipcRenderer } = require('electron/renderer')
-
const saveBtn = document.getElementById('save-dialog')
-saveBtn.addEventListener('click', event => {
- ipcRenderer.send('save-dialog')
-})
-
-ipcRenderer.on('saved-file', (event, path) => {
- if (!path) path = 'No path'
+saveBtn.addEventListener('click', async () => {
+ const path = await window.electronAPI.saveDialog()
document.getElementById('file-saved').innerHTML = `Path selected: ${path}`
})
diff --git a/docs/fiddles/native-ui/drag-and-drop/index.html b/docs/fiddles/native-ui/drag-and-drop/index.html
index 5f7d4853c3..0ed547401f 100644
--- a/docs/fiddles/native-ui/drag-and-drop/index.html
+++ b/docs/fiddles/native-ui/drag-and-drop/index.html
@@ -68,9 +68,6 @@ ipcMain.on('ondragstart', (event, filepath) => {
</div>
</div>
- <script>
- // You can also require other files to run in this process
- require("./renderer.js");
- </script>
+ <script src="renderer.js"></script>
</body>
</html>
diff --git a/docs/fiddles/native-ui/drag-and-drop/main.js b/docs/fiddles/native-ui/drag-and-drop/main.js
index 2186de038c..b4dce1a663 100644
--- a/docs/fiddles/native-ui/drag-and-drop/main.js
+++ b/docs/fiddles/native-ui/drag-and-drop/main.js
@@ -1,5 +1,7 @@
// Modules to control application life and create native browser window
const { app, BrowserWindow, ipcMain, nativeImage, shell } = require('electron/main')
+const path = require('node:path')
+
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow
@@ -10,8 +12,7 @@ function createWindow () {
width: 800,
height: 600,
webPreferences: {
- contextIsolation: false,
- nodeIntegration: true
+ preload: path.join(__dirname, 'preload.js')
}
})
@@ -58,7 +59,8 @@ app.on('activate', function () {
}
})
-ipcMain.on('ondragstart', (event, filepath) => {
+ipcMain.on('ondragstart', (event) => {
+ const filepath = path.join(__dirname, 'renderer.js')
const icon = nativeImage.createFromDataURL('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACQAAAAkCAYAAADhAJiYAAAAAXNSR0IArs4c6QAAAAlwSFlzAAALEwAACxMBAJqcGAAAAVlpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IlhNUCBDb3JlIDUuNC4wIj4KICAgPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4KICAgICAgPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIKICAgICAgICAgICAgeG1sbnM6dGlmZj0iaHR0cDovL25zLmFkb2JlLmNvbS90aWZmLzEuMC8iPgogICAgICAgICA8dGlmZjpPcmllbnRhdGlvbj4xPC90aWZmOk9yaWVudGF0aW9uPgogICAgICA8L3JkZjpEZXNjcmlwdGlvbj4KICAgPC9yZGY6UkRGPgo8L3g6eG1wbWV0YT4KTMInWQAACsZJREFUWAmtWFlsXFcZ/u82++Jt7IyT2Em6ZFHTpAtWIzspEgjEUhA8VNAiIYEQUvuABBIUwUMkQIVKPCIoEiABLShISEBbhFJwIGRpIKRpbNeJ7bh2HHvssR3PPnPnLnzfmRlju6EQqUc+c++c8y/fv54z1uQOh+/7Glh0TD59TE/TND7lnfa4/64OKsM071QoeZpA/y9WWvk/B4XCC06TUC+Xyw8HTXNQ1+Ww6PpOrMebewXxvBueJ6/XHOdMJBL5J9Y97m2R0SS/wweE6JxkGx5dilWr1S/7dXsEa2o4+LyFmcFcaL5zbX3Y9gh5hpeWYpSB9XV5/H678V89BGYDXnHJlCsWn4gHrGc1K9CXxferOdvPOOKUfF8cH7nUyCtklQZXih/VNNlmirk3GdBSoIcRswW7/vVkLPYi5W2Uze8bh7J+4wLfh4dViFx5/nmrUi7/MhGNvrCkBfpeWqnW/7BUdadqntQ8zwr6vhUV34xpYnDynWvcmwQNaclDXsqgLMqkocPDw7fNx7d5qIX+/PmJxKGD6VdDkeh7ztyqOFfrokGCEWiiZ1mp0uITnuKAosaT7+pNxMYTyefutcQfbA+b1XLpH5fnF97/yD335Fu6mqTqsclDINBVmI4fDxw80KPAvJSt1MZtMcLiGxYUu83p4UkgnJZlqcl3LAj3WnTkIS9lUBYNPJjueVWgg7qocyOgliFqjZsg8gq5tRdiieQTf1gq15Y8CUbRZtyWOzZwc8lEqS3PTCtgqd13ieO68BQ2uNl64tXAewktrFuX2mPdkWAxn3sxnmx7sqUTJGqso8MGS9tbXFz8DMH8bblUX3T9QARVi8RV8qljfcJy0zRlaf6mzHEuzEtmekqCoZB4rqp0OmudHtUnlEWZlE0d1EWd1N3EozourcO65pw4eTIZQTW9VazJtbqvw9XwKVFQMsKDBuNhtp4uvGGFI+IDgKnpMjYyIis3ZsQMBIR7pONsIaMsyqRs6ohY1rPUSd3EQFDqo+kdZ3Fh4aupbdu+99uFQr2A1CBs4uEAjZjIFUMHi4dVxMXzCdCXQj4vBrwVCofl0ulTcv/DAxJJJBUPc8mpoyI2JDw7bFyT+ifTcSubyXytJ51+roWBxwG9Q73WWjZ7eSUU3//nXM0NI+x0PBGrTSgsLS9JFuFxHFrvSqIrJV279gi6tjiVspTza3JjZhY+0CQZj0mlWJSeHTslCro6eFqymCcVVN77kkGjs1p4sy2VOoSlOrFwT+XR+PjkgGaZ+ycKVbRTYUdVrmaImCvzk1dlFCEJdHRJ284+ie/ol0h7p7jFvExcvCCXzp2Rqem3pAMAiqWS6JGYhFI9Mjo6KjevXVUyKEuFHrKpY6JQ8TXT3D8+OTkAHBw6o6LCFo9ag3o4JtlCyTHEt5AxKvS6YUi5kJeZG3Py0NAxlLcJ9xti+K7Mjo/JfGZRuvv6Ze+9+yWEhDZAvzg3JyhX2d6/S7q6e+TimdOS7ElLKBZDwqvmj6rztayr1fVI1IoXi4PAcYZY1tPEEO1wEVlXgRFBDcmIXTqJsS+XyhKLJ5A/OpIVXXptWUYv/UvaenfIocEhMQ2EzHHErlXFCgQl3paU1eVl6QAY8sQTCSmVihKJx1V/ogvgIYF/pACdcMBhqONoHhF88/2d+bojyA6cRvje2IdFjoSjUSnBS8hgyS9lZOzKFdmPxO3o6gQIGzwuDn1dVSCtCKPy1pZXlATXqUsVYMLRmKo87vP4Y1ioqwCdCegmMYx3W/VPn8RrSDwwIMMbcEjkYo29JZVOy+ybI7K4eksODx1VSqvligpReSVLgySM/FI5h2q062jNyL3s7FtoAyGJIlx1225UmwJF6aJRJ3XzHXO9bWvsJa3jQFlBJkz6iuXdu32HzM7MyP0PPNgAU6ko4Qzp6b+flr8MD9OYJg9CwtzL5+T65ITs2bsP3mGxN/ZbBcOn0sk20gAkLQ+huXpFi8vkoY9AoyDjxTR1mbo6Ltt275HpN0dlNxQE40mVM8Ajjxx9VAGhAvQR1akZFCq799ADysMuQqOxh2FNmamEaz51ItGLfFD9+oUJoZkLowHoFA2mljUacqOMflKuVmHpfmnfvlMuvXZeStmMBIMhcWEdjgFJtrUjXI0KchAuAg0ilxLJNoRVBxhIBm0TjjKAuqjTqTs3CQZ6QUUMGFW7eiWMUg6w+yo8YMW7DqtqlZLkUDV2ISfd29KyDwk9MjYmMyOXxQIIKuShqo4VGFNBEgeDQYqVam5N5tEePFQgURIUBCsd1EWd1XrtDUUMLARD9bKaK5ytQ2Gb75g8WMiEP6VkfnZGevv6UF1vSBW5E0PFDAweFRvlfun8WVmamhDNrkmweQ0pwaPt6M4m8mgKTTFXqcrV0ZH1FKBg6qAu6qTuJiCV1Cp2Q0NDr9Uq5Ym+oMEDlSewsoRwrVBEaij7AJ4s7zrOpumxEdm15y6558GHJVe1Zezy6zJx6aJkpq5JFB4z6zVZmBiX1VWUP0IY4CFMYcpQdZ3xqIs6oftCE5DHKwd0q/tzOV8svdDb3nk8VnG9qmgQC0ZURz8Ur91alXgSByZ6ES9kZZTr/PR16UOCh+7dq0CWyyXJ4xqCQ0nKt9YQSlPue2gAeYZzD7yNLk0wmqAreb2WYSxAJ8Dget64wxtEBlDaqVOn/K5dB67t6+t5MhoMJuc8w8UPKiQ9CQR9JK5czhZAQxPt7TKF3OiAIisUViAD2Lg5d0P2HDgoKeRaW0enyqVwBJcO5fFG5dqa7h406qaeX8384uTZL5w9+UqxhYHFp0YLIYA9ddfu3T+4UJF6Rg+YAc9D0+RoIGP1ULhpWspr10evyK7+ftWTrk9PS/++A9KZSm26cih2mMOErem6n/ZsZwA2TM/MPHXs2LEftnSTbh0Q36mIIbx44cLvOnu3f+xUwbWLmoHTCUlF6g2jBQo/GnFrnGNqSHdvr+rIKGMW1KahwEBdzHft98aNwMr8zd8/NDDwccihc0hLi3GubRjY0Bm6H19fPvnZI4c/fHd7PJ2peXYZ+WQ26JufZELjQ6lbAQtnWre0d3apY8TFIdtAo+Qri6mupsB49lBMC+QXF0YefObZT8j0eKWlswVjEyCCOXHihPGb575VCvVuf3lvetsH9rXF0rla3cnhpoIGjgsUPhR3I4TMKYJQV1Z6WO02aEjHa5mNe3OPW3OPRHVrbXFh9Ocvv/KR1372owx1Pf3005uc35Ddgtd8rsf06IdS5777zZ+mUqmPzjm6TPpmvayZOq4LyATeCzkanmiy4qEuC/yXiO8CSMRzvLs1x9phepLNZl868sy3Pyen/5hd1/EfRvWmuvSWNeaRS/RkPDI4+NjE1NSXEoXlpaNB1zqo20abi59/vu/UfM2pie7WUDVq8l3wTwnskeZ+zTbIQ17KoCzKpGzq2KqX32/roRbh8ePHdUzl0s9/5Rv9n/7go19MxCKfCkZiu3V06wrO5gocxL7Dgd/IEobEMH6rejg+auXidL5Y/vWv/vTX53/y/e/MkGajTH7fOt4RUJOY1df4RdtY6ICFRzqTySOhUOA+3Ai3o31H1ZbnlXBruFmt2iMrudy5xx9//BzWV7nXDBGN2xpjbt/5oGUEdhtO3iD47xZOvm8a5CHvpsV38wsUaMwBWsz3rbK5xr0mzdv2t9Jv/f5vhsF4J+Q63IUAAAAASUVORK5CYII=')
event.sender.startDrag({
diff --git a/docs/fiddles/native-ui/drag-and-drop/preload.js b/docs/fiddles/native-ui/drag-and-drop/preload.js
new file mode 100644
index 0000000000..bad5ed4c84
--- /dev/null
+++ b/docs/fiddles/native-ui/drag-and-drop/preload.js
@@ -0,0 +1,5 @@
+const { contextBridge, ipcRenderer } = require('electron/renderer')
+
+contextBridge.exposeInMainWorld('electronAPI', {
+ dragStart: () => ipcRenderer.send('ondragstart')
+})
diff --git a/docs/fiddles/native-ui/drag-and-drop/renderer.js b/docs/fiddles/native-ui/drag-and-drop/renderer.js
index 48df46b460..031601023d 100644
--- a/docs/fiddles/native-ui/drag-and-drop/renderer.js
+++ b/docs/fiddles/native-ui/drag-and-drop/renderer.js
@@ -1,8 +1,6 @@
-const { ipcRenderer } = require('electron/renderer')
-
const dragFileLink = document.getElementById('drag-file-link')
dragFileLink.addEventListener('dragstart', event => {
event.preventDefault()
- ipcRenderer.send('ondragstart', __filename)
+ window.electronAPI.dragStart()
})
diff --git a/docs/fiddles/native-ui/external-links-file-manager/index.html b/docs/fiddles/native-ui/external-links-file-manager/index.html
index 32e6dd1da2..83788b8e4f 100644
--- a/docs/fiddles/native-ui/external-links-file-manager/index.html
+++ b/docs/fiddles/native-ui/external-links-file-manager/index.html
@@ -95,10 +95,6 @@ for (const link of links) {
</div>
</div>
</div>
-
- <script>
- // You can also require other files to run in this process
- require("./renderer.js");
- </script>
+ <script src="renderer.js"></script>
</body>
</html>
diff --git a/docs/fiddles/native-ui/external-links-file-manager/main.js b/docs/fiddles/native-ui/external-links-file-manager/main.js
index f3e3c0ec62..b98a8669b0 100644
--- a/docs/fiddles/native-ui/external-links-file-manager/main.js
+++ b/docs/fiddles/native-ui/external-links-file-manager/main.js
@@ -1,5 +1,15 @@
// Modules to control application life and create native browser window
-const { app, BrowserWindow, shell } = require('electron/main')
+const { app, BrowserWindow, shell, ipcMain } = require('electron/main')
+const path = require('node:path')
+const os = require('node:os')
+
+ipcMain.on('open-home-dir', () => {
+ shell.showItemInFolder(os.homedir())
+})
+
+ipcMain.on('open-external', (event, url) => {
+ shell.openExternal(url)
+})
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
@@ -11,8 +21,7 @@ function createWindow () {
width: 800,
height: 600,
webPreferences: {
- contextIsolation: false,
- nodeIntegration: true
+ preload: path.join(__dirname, 'preload.js')
}
})
diff --git a/docs/fiddles/native-ui/external-links-file-manager/preload.js b/docs/fiddles/native-ui/external-links-file-manager/preload.js
new file mode 100644
index 0000000000..9be85a13ea
--- /dev/null
+++ b/docs/fiddles/native-ui/external-links-file-manager/preload.js
@@ -0,0 +1,6 @@
+const { contextBridge, ipcRenderer } = require('electron/renderer')
+
+contextBridge.exposeInMainWorld('electronAPI', {
+ openHomeDir: () => ipcRenderer.send('open-home-dir'),
+ openExternal: (url) => ipcRenderer.send('open-external', url)
+})
diff --git a/docs/fiddles/native-ui/external-links-file-manager/renderer.js b/docs/fiddles/native-ui/external-links-file-manager/renderer.js
index 7bbea2ca1a..6903268fd0 100644
--- a/docs/fiddles/native-ui/external-links-file-manager/renderer.js
+++ b/docs/fiddles/native-ui/external-links-file-manager/renderer.js
@@ -1,13 +1,10 @@
-const { shell } = require('electron/renderer')
-const os = require('node:os')
-
const exLinksBtn = document.getElementById('open-ex-links')
const fileManagerBtn = document.getElementById('open-file-manager')
fileManagerBtn.addEventListener('click', (event) => {
- shell.showItemInFolder(os.homedir())
+ window.electronAPI.openHomeDir()
})
exLinksBtn.addEventListener('click', (event) => {
- shell.openExternal('https://electronjs.org')
+ window.electronAPI.openExternal('https://electronjs.org')
})
diff --git a/docs/fiddles/native-ui/notifications/index.html b/docs/fiddles/native-ui/notifications/index.html
index 27725a448d..0eb9e213d5 100644
--- a/docs/fiddles/native-ui/notifications/index.html
+++ b/docs/fiddles/native-ui/notifications/index.html
@@ -59,9 +59,6 @@
</div>
</div>
- <script>
- // You can also require other files to run in this process
- require("./renderer.js");
- </script>
+ <script src="renderer.js"></script>
</body>
</html>
diff --git a/docs/fiddles/native-ui/notifications/main.js b/docs/fiddles/native-ui/notifications/main.js
index f3e3c0ec62..f880a67a49 100644
--- a/docs/fiddles/native-ui/notifications/main.js
+++ b/docs/fiddles/native-ui/notifications/main.js
@@ -9,11 +9,7 @@ function createWindow () {
// Create the browser window.
mainWindow = new BrowserWindow({
width: 800,
- height: 600,
- webPreferences: {
- contextIsolation: false,
- nodeIntegration: true
- }
+ height: 600
})
// and load the index.html of the app.
diff --git a/docs/fiddles/system/system-app-user-information/app-information/index.html b/docs/fiddles/system/system-app-user-information/app-information/index.html
index b08a8d0c82..f8b0e38c3f 100644
--- a/docs/fiddles/system/system-app-user-information/app-information/index.html
+++ b/docs/fiddles/system/system-app-user-information/app-information/index.html
@@ -18,9 +18,6 @@
</div>
</div>
</div>
- <script>
- // You can also require other files to run in this process
- require('./renderer.js')
- </script>
+ <script src="renderer.js"></script>
</body>
</html>
\ No newline at end of file
diff --git a/docs/fiddles/system/system-app-user-information/app-information/main.js b/docs/fiddles/system/system-app-user-information/app-information/main.js
index 7ec2bd5d32..247bad8f52 100644
--- a/docs/fiddles/system/system-app-user-information/app-information/main.js
+++ b/docs/fiddles/system/system-app-user-information/app-information/main.js
@@ -1,4 +1,5 @@
const { app, BrowserWindow, ipcMain, shell } = require('electron/main')
+const path = require('node:path')
let mainWindow = null
@@ -10,8 +11,7 @@ function createWindow () {
height: 400,
title: 'Get app information',
webPreferences: {
- contextIsolation: false,
- nodeIntegration: true
+ preload: path.join(__dirname, 'preload.js')
}
}
diff --git a/docs/fiddles/system/system-app-user-information/app-information/preload.js b/docs/fiddles/system/system-app-user-information/app-information/preload.js
new file mode 100644
index 0000000000..92e3efa325
--- /dev/null
+++ b/docs/fiddles/system/system-app-user-information/app-information/preload.js
@@ -0,0 +1,5 @@
+const { contextBridge, ipcRenderer } = require('electron/renderer')
+
+contextBridge.exposeInMainWorld('electronAPI', {
+ getAppPath: () => ipcRenderer.invoke('get-app-path')
+})
diff --git a/docs/fiddles/system/system-app-user-information/app-information/renderer.js b/docs/fiddles/system/system-app-user-information/app-information/renderer.js
index 62705b3770..35b201bf40 100644
--- a/docs/fiddles/system/system-app-user-information/app-information/renderer.js
+++ b/docs/fiddles/system/system-app-user-information/app-information/renderer.js
@@ -1,9 +1,7 @@
-const { ipcRenderer } = require('electron/renderer')
-
const appInfoBtn = document.getElementById('app-info')
appInfoBtn.addEventListener('click', async () => {
- const path = await ipcRenderer.invoke('get-app-path')
+ const path = await window.electronAPI.getAppPath()
const message = `This app is located at: ${path}`
document.getElementById('got-app-info').innerHTML = message
})
diff --git a/docs/fiddles/system/system-information/get-version-information/index.html b/docs/fiddles/system/system-information/get-version-information/index.html
index de0a39b423..3bd06b382e 100644
--- a/docs/fiddles/system/system-information/get-version-information/index.html
+++ b/docs/fiddles/system/system-information/get-version-information/index.html
@@ -20,7 +20,5 @@
</div>
</div>
</body>
- <script>
- require('./renderer.js')
- </script>
+ <script src="renderer.js"></script>
</html>
diff --git a/docs/fiddles/system/system-information/get-version-information/main.js b/docs/fiddles/system/system-information/get-version-information/main.js
index 14ffef1acd..e1a7434a52 100644
--- a/docs/fiddles/system/system-information/get-version-information/main.js
+++ b/docs/fiddles/system/system-information/get-version-information/main.js
@@ -1,4 +1,5 @@
const { app, BrowserWindow, shell } = require('electron/main')
+const path = require('node:path')
let mainWindow = null
@@ -8,8 +9,7 @@ function createWindow () {
height: 400,
title: 'Get version information',
webPreferences: {
- contextIsolation: false,
- nodeIntegration: true
+ preload: path.join(__dirname, 'preload.js')
}
}
diff --git a/docs/fiddles/system/system-information/get-version-information/preload.js b/docs/fiddles/system/system-information/get-version-information/preload.js
new file mode 100644
index 0000000000..fa4eab9154
--- /dev/null
+++ b/docs/fiddles/system/system-information/get-version-information/preload.js
@@ -0,0 +1,3 @@
+const { contextBridge } = require('electron/renderer')
+
+contextBridge.exposeInMainWorld('electronVersion', process.versions.electron)
diff --git a/docs/fiddles/system/system-information/get-version-information/renderer.js b/docs/fiddles/system/system-information/get-version-information/renderer.js
index 40f7f2cf2c..3e7c22e5c2 100644
--- a/docs/fiddles/system/system-information/get-version-information/renderer.js
+++ b/docs/fiddles/system/system-information/get-version-information/renderer.js
@@ -1,8 +1,6 @@
const versionInfoBtn = document.getElementById('version-info')
-const electronVersion = process.versions.electron
-
versionInfoBtn.addEventListener('click', () => {
- const message = `This app is using Electron version: ${electronVersion}`
+ const message = `This app is using Electron version: ${window.electronVersion}`
document.getElementById('got-version-info').innerHTML = message
})
diff --git a/docs/fiddles/windows/manage-windows/frameless-window/index.html b/docs/fiddles/windows/manage-windows/frameless-window/index.html
index 5041b1939e..69ef074f23 100644
--- a/docs/fiddles/windows/manage-windows/frameless-window/index.html
+++ b/docs/fiddles/windows/manage-windows/frameless-window/index.html
@@ -68,10 +68,6 @@
</div>
</div>
</div>
-
- <script>
- // You can also require other files to run in this process
- require("./renderer.js");
- </script>
+ <script src="renderer.js"></script>
</body>
</html>
diff --git a/docs/fiddles/windows/manage-windows/frameless-window/main.js b/docs/fiddles/windows/manage-windows/frameless-window/main.js
index 021679fc5e..507242962a 100644
--- a/docs/fiddles/windows/manage-windows/frameless-window/main.js
+++ b/docs/fiddles/windows/manage-windows/frameless-window/main.js
@@ -1,5 +1,6 @@
// Modules to control application life and create native browser window
const { app, BrowserWindow, ipcMain, shell } = require('electron/main')
+const path = require('node:path')
ipcMain.on('create-frameless-window', (event, { url }) => {
const win = new BrowserWindow({ frame: false })
@@ -12,8 +13,7 @@ function createWindow () {
width: 800,
height: 600,
webPreferences: {
- contextIsolation: false,
- nodeIntegration: true
+ preload: path.join(__dirname, 'preload.js')
}
})
diff --git a/docs/fiddles/windows/manage-windows/frameless-window/preload.js b/docs/fiddles/windows/manage-windows/frameless-window/preload.js
new file mode 100644
index 0000000000..0feaa67675
--- /dev/null
+++ b/docs/fiddles/windows/manage-windows/frameless-window/preload.js
@@ -0,0 +1,5 @@
+const { contextBridge, ipcRenderer } = require('electron/renderer')
+
+contextBridge.exposeInMainWorld('electronAPI', {
+ createFramelessWindow: (args) => ipcRenderer.send('create-frameless-window', args)
+})
diff --git a/docs/fiddles/windows/manage-windows/frameless-window/renderer.js b/docs/fiddles/windows/manage-windows/frameless-window/renderer.js
index b8aafe29d1..7638f56099 100644
--- a/docs/fiddles/windows/manage-windows/frameless-window/renderer.js
+++ b/docs/fiddles/windows/manage-windows/frameless-window/renderer.js
@@ -1,8 +1,6 @@
-const { ipcRenderer } = require('electron/renderer')
-
const newWindowBtn = document.getElementById('frameless-window')
newWindowBtn.addEventListener('click', () => {
const url = 'data:text/html,<h2>Hello World!</h2><a id="close" href="javascript:window.close()">Close this Window</a>'
- ipcRenderer.send('create-frameless-window', { url })
+ window.electronAPI.createFramelessWindow({ url })
})
diff --git a/docs/fiddles/windows/manage-windows/manage-window-state/index.html b/docs/fiddles/windows/manage-windows/manage-window-state/index.html
index eca1d0a475..9c6236dd77 100644
--- a/docs/fiddles/windows/manage-windows/manage-window-state/index.html
+++ b/docs/fiddles/windows/manage-windows/manage-window-state/index.html
@@ -55,10 +55,6 @@
</div>
</div>
</div>
-
- <script>
- // You can also require other files to run in this process
- require("./renderer.js");
- </script>
+ <script src="renderer.js"></script>
</body>
</html>
diff --git a/docs/fiddles/windows/manage-windows/manage-window-state/main.js b/docs/fiddles/windows/manage-windows/manage-window-state/main.js
index f41240b46f..afb4223392 100644
--- a/docs/fiddles/windows/manage-windows/manage-window-state/main.js
+++ b/docs/fiddles/windows/manage-windows/manage-window-state/main.js
@@ -1,5 +1,6 @@
// Modules to control application life and create native browser window
const { app, BrowserWindow, ipcMain, shell } = require('electron/main')
+const path = require('node:path')
ipcMain.on('create-demo-window', (event) => {
const win = new BrowserWindow({ width: 400, height: 275 })
@@ -22,8 +23,7 @@ function createWindow () {
width: 800,
height: 600,
webPreferences: {
- contextIsolation: false,
- nodeIntegration: true
+ preload: path.join(__dirname, 'preload.js')
}
})
diff --git a/docs/fiddles/windows/manage-windows/manage-window-state/preload.js b/docs/fiddles/windows/manage-windows/manage-window-state/preload.js
new file mode 100644
index 0000000000..d604ee529c
--- /dev/null
+++ b/docs/fiddles/windows/manage-windows/manage-window-state/preload.js
@@ -0,0 +1,6 @@
+const { contextBridge, ipcRenderer } = require('electron/renderer')
+
+contextBridge.exposeInMainWorld('electronAPI', {
+ createDemoWindow: () => ipcRenderer.send('create-demo-window'),
+ onBoundsChanged: (callback) => ipcRenderer.on('bounds-changed', () => callback())
+})
diff --git a/docs/fiddles/windows/manage-windows/manage-window-state/renderer.js b/docs/fiddles/windows/manage-windows/manage-window-state/renderer.js
index 2efe3199a8..c152fd5ae1 100644
--- a/docs/fiddles/windows/manage-windows/manage-window-state/renderer.js
+++ b/docs/fiddles/windows/manage-windows/manage-window-state/renderer.js
@@ -1,13 +1,11 @@
-const { ipcRenderer } = require('electron/renderer')
-
const manageWindowBtn = document.getElementById('manage-window')
-ipcRenderer.on('bounds-changed', (event, bounds) => {
+window.electronAPI.onBoundsChanged((event, bounds) => {
const manageWindowReply = document.getElementById('manage-window-reply')
const message = `Size: ${bounds.size} Position: ${bounds.position}`
manageWindowReply.textContent = message
})
manageWindowBtn.addEventListener('click', (event) => {
- ipcRenderer.send('create-demo-window')
+ window.electronAPI.createDemoWindow()
})
diff --git a/docs/fiddles/windows/manage-windows/new-window/index.html b/docs/fiddles/windows/manage-windows/new-window/index.html
index 19e3c33e0b..3cd5df4a17 100644
--- a/docs/fiddles/windows/manage-windows/new-window/index.html
+++ b/docs/fiddles/windows/manage-windows/new-window/index.html
@@ -9,17 +9,14 @@
<button id="new-window">View Demo</button>
<p>The <code>BrowserWindow</code> module gives you the ability to create new windows in your app.</p>
<p>There are a lot of options when creating a new window. A few are in this demo, but visit the <a href="https://www.electronjs.org/docs/latest/api/browser-window">documentation<span>(opens in new window)</span></a>
-<div>
- <h2>ProTip</h2>
- <strong>Use an invisible browser window to run background tasks.</strong>
- <p>You can set a new browser window to not be shown (be invisible) in order to use that additional renderer process as a kind of new thread in which to run JavaScript in the background of your app. You do this by setting the <code>show</code> property to <code>false</code> when defining the new window.</p>
- <pre><code><span>var</span> win = <span>new</span> BrowserWindow({
+ <div>
+ <h2>ProTip</h2>
+ <strong>Use an invisible browser window to run background tasks.</strong>
+ <p>You can set a new browser window to not be shown (be invisible) in order to use that additional renderer process as a kind of new thread in which to run JavaScript in the background of your app. You do this by setting the <code>show</code> property to <code>false</code> when defining the new window.</p>
+ <pre><code><span>var</span> win = <span>new</span> BrowserWindow({
<span>width</span>: <span>400</span>, <span>height</span>: <span>225</span>, <span>show</span>: <span>false</span>
})</code></pre>
- </div>
- <script>
- // You can also require other files to run in this process
- require('./renderer.js')
- </script>
+ </div>
+ <script src="renderer.js"></script>
</body>
</html>
diff --git a/docs/fiddles/windows/manage-windows/new-window/main.js b/docs/fiddles/windows/manage-windows/new-window/main.js
index 4e2f9c6beb..109055ac80 100644
--- a/docs/fiddles/windows/manage-windows/new-window/main.js
+++ b/docs/fiddles/windows/manage-windows/new-window/main.js
@@ -1,5 +1,6 @@
// Modules to control application life and create native browser window
const { app, BrowserWindow, ipcMain, shell } = require('electron/main')
+const path = require('node:path')
ipcMain.on('new-window', (event, { url, width, height }) => {
const win = new BrowserWindow({ width, height })
@@ -12,8 +13,7 @@ function createWindow () {
width: 800,
height: 600,
webPreferences: {
- contextIsolation: false,
- nodeIntegration: true
+ preload: path.join(__dirname, 'preload.js')
}
})
diff --git a/docs/fiddles/windows/manage-windows/new-window/preload.js b/docs/fiddles/windows/manage-windows/new-window/preload.js
new file mode 100644
index 0000000000..53019d908f
--- /dev/null
+++ b/docs/fiddles/windows/manage-windows/new-window/preload.js
@@ -0,0 +1,5 @@
+const { contextBridge, ipcRenderer } = require('electron/renderer')
+
+contextBridge.exposeInMainWorld('electronAPI', {
+ newWindow: (args) => ipcRenderer.send('new-window', args)
+})
diff --git a/docs/fiddles/windows/manage-windows/new-window/renderer.js b/docs/fiddles/windows/manage-windows/new-window/renderer.js
index ce4b7a4b51..22caea84a3 100644
--- a/docs/fiddles/windows/manage-windows/new-window/renderer.js
+++ b/docs/fiddles/windows/manage-windows/new-window/renderer.js
@@ -1,8 +1,6 @@
-const { ipcRenderer } = require('electron/renderer')
-
const newWindowBtn = document.getElementById('new-window')
newWindowBtn.addEventListener('click', (event) => {
const url = 'https://electronjs.org'
- ipcRenderer.send('new-window', { url, width: 400, height: 320 })
+ window.electronAPI.newWindow({ url, width: 400, height: 320 })
})
diff --git a/docs/fiddles/windows/manage-windows/window-events/index.html b/docs/fiddles/windows/manage-windows/window-events/index.html
index 028a70b6c1..5c05a3c9a2 100644
--- a/docs/fiddles/windows/manage-windows/window-events/index.html
+++ b/docs/fiddles/windows/manage-windows/window-events/index.html
@@ -49,10 +49,6 @@
</div>
</div>
</div>
-
- <script>
- // You can also require other files to run in this process
- require("./renderer.js");
- </script>
+ <script src="renderer.js"></script>
</body>
</html>
diff --git a/docs/fiddles/windows/manage-windows/window-events/main.js b/docs/fiddles/windows/manage-windows/window-events/main.js
index a7fd20cc92..5f10651d24 100644
--- a/docs/fiddles/windows/manage-windows/window-events/main.js
+++ b/docs/fiddles/windows/manage-windows/window-events/main.js
@@ -1,5 +1,6 @@
// Modules to control application life and create native browser window
const { app, BrowserWindow, ipcMain, shell } = require('electron/main')
+const path = require('node:path')
function createWindow () {
// Create the browser window.
@@ -7,8 +8,7 @@ function createWindow () {
width: 800,
height: 600,
webPreferences: {
- contextIsolation: false,
- nodeIntegration: true
+ preload: path.join(__dirname, 'preload.js')
}
})
@@ -30,6 +30,7 @@ function createWindow () {
demoWindow = new BrowserWindow({ width: 600, height: 400 })
demoWindow.loadURL('https://electronjs.org')
demoWindow.on('close', () => {
+ demoWindow = undefined
mainWindow.webContents.send('window-close')
})
demoWindow.on('focus', () => {
diff --git a/docs/fiddles/windows/manage-windows/window-events/preload.js b/docs/fiddles/windows/manage-windows/window-events/preload.js
new file mode 100644
index 0000000000..b33f860a64
--- /dev/null
+++ b/docs/fiddles/windows/manage-windows/window-events/preload.js
@@ -0,0 +1,9 @@
+const { contextBridge, ipcRenderer } = require('electron/renderer')
+
+contextBridge.exposeInMainWorld('electronAPI', {
+ showDemoWindow: () => ipcRenderer.send('show-demo-window'),
+ focusDemoWindow: () => ipcRenderer.send('focus-demo-window'),
+ onWindowFocus: (callback) => ipcRenderer.on('window-focus', () => callback()),
+ onWindowBlur: (callback) => ipcRenderer.on('window-blur', () => callback()),
+ onWindowClose: (callback) => ipcRenderer.on('window-close', () => callback())
+})
diff --git a/docs/fiddles/windows/manage-windows/window-events/renderer.js b/docs/fiddles/windows/manage-windows/window-events/renderer.js
index 99f9909526..814605ecbe 100644
--- a/docs/fiddles/windows/manage-windows/window-events/renderer.js
+++ b/docs/fiddles/windows/manage-windows/window-events/renderer.js
@@ -1,5 +1,3 @@
-const { ipcRenderer } = require('electron/renderer')
-
const listenToWindowBtn = document.getElementById('listen-to-window')
const focusModalBtn = document.getElementById('focus-on-modal-window')
@@ -15,13 +13,13 @@ const showFocusBtn = (btn) => {
focusModalBtn.addEventListener('click', focusWindow)
}
const focusWindow = () => {
- ipcRenderer.send('focus-demo-window')
+ window.electronAPI.focusDemoWindow()
}
-ipcRenderer.on('window-focus', hideFocusBtn)
-ipcRenderer.on('window-close', hideFocusBtn)
-ipcRenderer.on('window-blur', showFocusBtn)
+window.electronAPI.onWindowFocus(hideFocusBtn)
+window.electronAPI.onWindowClose(hideFocusBtn)
+window.electronAPI.onWindowBlur(showFocusBtn)
listenToWindowBtn.addEventListener('click', () => {
- ipcRenderer.send('show-demo-window')
+ window.electronAPI.showDemoWindow()
})
|
docs
|
aa23198ad8ed023a09bf6162f0e268f4aa0aa524
|
Charles Kerr
|
2024-07-25 04:25:45
|
chore: remove more unused #include calls (#43000)
* chore: in shell/renderer/renderer_client_base.h, remove include media/base/key_systems_support_registration.h
last use removed in c670e38b (##41610)
* chore: iwyu electron/fuses.h
* chore: iwyu media/base/video_frame.h
* chore: iwyu base/functional/callback.h
* chore: iwyu base/task/cancelable_task_tracker.h
* chore: iwyu shell/browser/draggable_region_provider.h
* chore: iwyu shell/browser/ui/inspectable_web_contents_view.h
* chore: iwyu ui/aura/window.h
* chore: iwyu ui/base/win/shell.h
* chore: iwyu ui/display/win/screen_win.h
* chore: iwyu ui/gfx/geometry/insets.h
* chore: iwyu ui/display/display.h
* chore: iwyu ui/gfx/geometry/skia_conversions.h
* chore: iwyu ui/gfx/geometry/rect_conversions.h
* chore: iwyu ui/gfx/geometry/point.h
* chore: iwyu ui/gfx/scoped_canvas.h
* chore: iwyu ui/gfx/image/image.h
* chore: iwyu ui/accessibility/ax_node_data.h
* chore: iwyu ui/views/animation/ink_drop_highlight.h
* chore: iwyu ui/gfx/font_list.h
* chore: iwyu ui/linux/nav_button_provider.h
* chore: iwyu shell/browser/ui/views/frameless_view.h
* chore: iwyu services/metrics/public/cpp/ukm_source_id.h
* chore: iwyu net/http/http_util.h
* chore: iwyu net/base/mime_util.h
* chore: iwyu content/public/common/content_client.h
* chore: iwyu <list>
* chore: iwyu <optional>
* chore: iwyu <memory>
* chore: iwyu base/files/file_path.h
* chore: iwyu ui/base/cursor/cursor.h
* chore: iwyu build/build_config.h
* chore: iwyu content/public/browser/web_contents.h
* chore: iwyu shell/browser/hid/hid_chooser_context.h
* chore: iwyu shell/common/platform_util.h
* chore: iwyu base/task/single_thread_task_runner.h
* chore: iwyu content/browser/renderer_host/render_widget_host_impl.h
* chore: iwyu content/public/browser/render_widget_host.h
* chore: iwyu shell/browser/electron_browser_context.h
* chore: iwyu content/public/browser/web_contents_observer.h
* chore: iwyu content/public/browser/render_frame_host.h
* chore: iwyu content/public/browser/media_stream_request.h
* chore: iwyu chrome/common/chrome_paths.h
* chore: iwyu chrome/browser/icon_manager.h
* chore: iwyu printing/print_settings.h
* chore: iwyu renderer/pepper_helper.h
* chore: iwyu shell/browser/api/process_metric.h
* chore: iwyu shell/browser/electron_browser_client.h
* chore: iwyu shell/browser/electron_browser_context.h
* chore: iwyu shell/browser/api/electron_api_session.h
* chore: iwyu shell/browser/api/electron_api_app.h
* chore: iwyu shell/browser/ui/views/client_frame_view_linux.h
* chore: iwyu shell/browser/native_window_views.h
* chore: iwyu base/win/windows_version.h
* chore: iwyu shell/common/electron_paths.h
* chore: iwyu content/public/common/content_switches.h
* chore: iwyu third_party/skia/include/core/SkRRect.h
* chore: iwyu third_party/skia/include/core/SkBitmap.h
* chore: iwyu third_party/skia
* chore: iwyu shell/browser/osr/osr_host_display_client.h
* chore: iwyu shell/browser/login_handler.h
* chore: iwyu shell/browser/javascript_environment.h
* chore: iwyu shell/browser/event_emitter_mixin.h
* fix: mac
* fix: mac
* chore: iwyu base/nix/xdg_util.h
* fix: win
* fix: win
* fix: win
* fix: win
|
diff --git a/shell/app/electron_content_client.cc b/shell/app/electron_content_client.cc
index 4b195f505c..2bf129da84 100644
--- a/shell/app/electron_content_client.cc
+++ b/shell/app/electron_content_client.cc
@@ -13,13 +13,11 @@
#include "base/files/file_util.h"
#include "base/strings/string_split.h"
#include "content/public/common/content_constants.h"
-#include "content/public/common/content_switches.h"
#include "electron/buildflags/buildflags.h"
#include "electron/fuses.h"
#include "extensions/common/constants.h"
#include "pdf/buildflags.h"
#include "ppapi/buildflags/buildflags.h"
-#include "shell/common/electron_paths.h"
#include "shell/common/options_switches.h"
#include "shell/common/process_util.h"
#include "third_party/widevine/cdm/buildflags.h"
diff --git a/shell/app/electron_crash_reporter_client.cc b/shell/app/electron_crash_reporter_client.cc
index 6a01219030..28cb6b0bf8 100644
--- a/shell/app/electron_crash_reporter_client.cc
+++ b/shell/app/electron_crash_reporter_client.cc
@@ -13,7 +13,6 @@
#include "base/path_service.h"
#include "base/strings/utf_string_conversions.h"
#include "build/build_config.h"
-#include "chrome/common/chrome_paths.h"
#include "components/crash/core/common/crash_keys.h"
#include "components/upload_list/crash_upload_list.h"
#include "content/public/common/content_switches.h"
diff --git a/shell/app/electron_main_delegate.h b/shell/app/electron_main_delegate.h
index e8929bf103..ebc8bd6792 100644
--- a/shell/app/electron_main_delegate.h
+++ b/shell/app/electron_main_delegate.h
@@ -9,7 +9,10 @@
#include <string>
#include "content/public/app/content_main_delegate.h"
-#include "content/public/common/content_client.h"
+
+namespace content {
+class Client;
+}
namespace tracing {
class TracingSamplerProfiler;
diff --git a/shell/app/electron_main_win.cc b/shell/app/electron_main_win.cc
index c205a00b3d..75eee069a7 100644
--- a/shell/app/electron_main_win.cc
+++ b/shell/app/electron_main_win.cc
@@ -17,12 +17,12 @@
#include <vector>
#include "base/at_exit.h"
+#include "base/debug/alias.h"
#include "base/i18n/icu_util.h"
#include "base/memory/raw_ptr_exclusion.h"
#include "base/process/launch.h"
#include "base/strings/utf_string_conversions.h"
#include "base/win/dark_mode_support.h"
-#include "base/win/windows_version.h"
#include "chrome/app/exit_code_watcher_win.h"
#include "components/crash/core/app/crash_switches.h"
#include "components/crash/core/app/run_as_crashpad_handler_win.h"
diff --git a/shell/app/uv_task_runner.h b/shell/app/uv_task_runner.h
index d792d2711a..7f23826db1 100644
--- a/shell/app/uv_task_runner.h
+++ b/shell/app/uv_task_runner.h
@@ -7,7 +7,6 @@
#include <map>
-#include "base/functional/callback.h"
#include "base/memory/raw_ptr.h"
#include "base/task/single_thread_task_runner.h"
#include "uv.h" // NOLINT(build/include_directory)
diff --git a/shell/browser/api/electron_api_app.cc b/shell/browser/api/electron_api_app.cc
index 1e1a5da2f7..a93b8d672a 100644
--- a/shell/browser/api/electron_api_app.cc
+++ b/shell/browser/api/electron_api_app.cc
@@ -38,7 +38,6 @@
#include "content/public/browser/gpu_data_manager.h"
#include "content/public/browser/network_service_instance.h"
#include "content/public/browser/render_frame_host.h"
-#include "content/public/common/content_switches.h"
#include "crypto/crypto_buildflags.h"
#include "media/audio/audio_manager.h"
#include "net/dns/public/dns_over_https_config.h"
@@ -51,15 +50,14 @@
#include "services/network/network_service.h"
#include "shell/app/command_line_args.h"
#include "shell/browser/api/electron_api_menu.h"
-#include "shell/browser/api/electron_api_session.h"
#include "shell/browser/api/electron_api_utility_process.h"
#include "shell/browser/api/electron_api_web_contents.h"
#include "shell/browser/api/gpuinfo_manager.h"
+#include "shell/browser/api/process_metric.h"
#include "shell/browser/browser_process_impl.h"
-#include "shell/browser/electron_browser_context.h"
#include "shell/browser/electron_browser_main_parts.h"
#include "shell/browser/javascript_environment.h"
-#include "shell/browser/login_handler.h"
+#include "shell/browser/net/resolve_proxy_helper.h"
#include "shell/browser/relauncher.h"
#include "shell/common/application_info.h"
#include "shell/common/electron_command_line.h"
@@ -78,7 +76,6 @@
#include "shell/common/language_util.h"
#include "shell/common/node_includes.h"
#include "shell/common/options_switches.h"
-#include "shell/common/platform_util.h"
#include "shell/common/thread_restrictions.h"
#include "shell/common/v8_value_serializer.h"
#include "ui/gfx/image/image.h"
diff --git a/shell/browser/api/electron_api_app.h b/shell/browser/api/electron_api_app.h
index 10bb09985e..d158d20a8b 100644
--- a/shell/browser/api/electron_api_app.h
+++ b/shell/browser/api/electron_api_app.h
@@ -12,7 +12,6 @@
#include "base/containers/flat_map.h"
#include "base/task/cancelable_task_tracker.h"
-#include "chrome/browser/icon_manager.h"
#include "chrome/browser/process_singleton.h"
#include "content/public/browser/browser_child_process_observer.h"
#include "content/public/browser/gpu_data_manager_observer.h"
@@ -22,7 +21,6 @@
#include "net/base/completion_once_callback.h"
#include "net/base/completion_repeating_callback.h"
#include "net/ssl/client_cert_identity.h"
-#include "shell/browser/api/process_metric.h"
#include "shell/browser/browser.h"
#include "shell/browser/browser_observer.h"
#include "shell/browser/electron_browser_client.h"
@@ -39,8 +37,14 @@ namespace base {
class FilePath;
}
+namespace gfx {
+class Image;
+}
+
namespace electron {
+struct ProcessMetric;
+
#if BUILDFLAG(IS_WIN)
enum class JumpListResult : int;
#endif
diff --git a/shell/browser/api/electron_api_app_mac.mm b/shell/browser/api/electron_api_app_mac.mm
index 5415c8cfac..37bf73426a 100644
--- a/shell/browser/api/electron_api_app_mac.mm
+++ b/shell/browser/api/electron_api_app_mac.mm
@@ -2,10 +2,11 @@
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
+#include "shell/browser/api/electron_api_app.h"
+
#include <string>
#include "base/path_service.h"
-#include "shell/browser/api/electron_api_app.h"
#include "shell/common/electron_paths.h"
#include "shell/common/node_includes.h"
#include "shell/common/process_util.h"
diff --git a/shell/browser/api/electron_api_browser_window.cc b/shell/browser/api/electron_api_browser_window.cc
index b1ea0974bf..cd757612af 100644
--- a/shell/browser/api/electron_api_browser_window.cc
+++ b/shell/browser/api/electron_api_browser_window.cc
@@ -4,8 +4,6 @@
#include "shell/browser/api/electron_api_browser_window.h"
-#include "base/task/single_thread_task_runner.h"
-#include "content/browser/renderer_host/render_widget_host_impl.h" // nogncheck
#include "content/browser/renderer_host/render_widget_host_owner_delegate.h" // nogncheck
#include "content/browser/web_contents/web_contents_impl.h" // nogncheck
#include "content/public/browser/render_process_host.h"
@@ -22,10 +20,6 @@
#include "shell/common/options_switches.h"
#include "ui/gl/gpu_switching_manager.h"
-#if defined(TOOLKIT_VIEWS)
-#include "shell/browser/native_window_views.h"
-#endif
-
namespace electron::api {
BrowserWindow::BrowserWindow(gin::Arguments* args,
diff --git a/shell/browser/api/electron_api_crash_reporter.cc b/shell/browser/api/electron_api_crash_reporter.cc
index aa293ab1ee..8058838c1d 100644
--- a/shell/browser/api/electron_api_crash_reporter.cc
+++ b/shell/browser/api/electron_api_crash_reporter.cc
@@ -18,7 +18,6 @@
#include "chrome/common/chrome_paths.h"
#include "components/upload_list/crash_upload_list.h"
#include "components/upload_list/text_log_upload_list.h"
-#include "content/public/common/content_switches.h"
#include "gin/arguments.h"
#include "gin/data_object_builder.h"
#include "shell/common/electron_paths.h"
diff --git a/shell/browser/api/electron_api_crash_reporter.h b/shell/browser/api/electron_api_crash_reporter.h
index 8b96b8e929..6b2f1c58b3 100644
--- a/shell/browser/api/electron_api_crash_reporter.h
+++ b/shell/browser/api/electron_api_crash_reporter.h
@@ -7,7 +7,8 @@
#include <map>
#include <string>
-#include "base/files/file_path.h"
+
+#include "build/build_config.h"
namespace electron::api::crash_reporter {
diff --git a/shell/browser/api/electron_api_debugger.h b/shell/browser/api/electron_api_debugger.h
index c2c669b8c3..3bbc0f0423 100644
--- a/shell/browser/api/electron_api_debugger.h
+++ b/shell/browser/api/electron_api_debugger.h
@@ -7,7 +7,6 @@
#include <map>
-#include "base/functional/callback.h"
#include "base/memory/raw_ptr.h"
#include "base/values.h"
#include "content/public/browser/devtools_agent_host_client.h"
diff --git a/shell/browser/api/electron_api_event_emitter.cc b/shell/browser/api/electron_api_event_emitter.cc
index 26062935d2..d346b757e2 100644
--- a/shell/browser/api/electron_api_event_emitter.cc
+++ b/shell/browser/api/electron_api_event_emitter.cc
@@ -5,7 +5,6 @@
#include "shell/browser/api/electron_api_event_emitter.h"
#include "base/functional/bind.h"
-#include "base/functional/callback.h"
#include "base/no_destructor.h"
#include "gin/dictionary.h"
#include "shell/common/gin_converters/callback_converter.h"
diff --git a/shell/browser/api/electron_api_menu.h b/shell/browser/api/electron_api_menu.h
index d18babaaa8..2191c412aa 100644
--- a/shell/browser/api/electron_api_menu.h
+++ b/shell/browser/api/electron_api_menu.h
@@ -8,7 +8,6 @@
#include <memory>
#include <string>
-#include "base/functional/callback.h"
#include "base/memory/raw_ptr.h"
#include "shell/browser/api/electron_api_base_window.h"
#include "shell/browser/event_emitter_mixin.h"
diff --git a/shell/browser/api/electron_api_menu_mac.mm b/shell/browser/api/electron_api_menu_mac.mm
index c07a4264a4..aac780025d 100644
--- a/shell/browser/api/electron_api_menu_mac.mm
+++ b/shell/browser/api/electron_api_menu_mac.mm
@@ -12,7 +12,6 @@
#include "base/task/current_thread.h"
#include "base/task/sequenced_task_runner.h"
#include "content/public/browser/browser_task_traits.h"
-#include "content/public/browser/web_contents.h"
#include "shell/browser/native_window.h"
#include "shell/common/keyboard_util.h"
#include "shell/common/node_includes.h"
diff --git a/shell/browser/api/electron_api_net_log.h b/shell/browser/api/electron_api_net_log.h
index 3a745ca695..0cc0c1b15c 100644
--- a/shell/browser/api/electron_api_net_log.h
+++ b/shell/browser/api/electron_api_net_log.h
@@ -8,7 +8,6 @@
#include <optional>
#include "base/files/file_path.h"
-#include "base/functional/callback.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/weak_ptr.h"
#include "base/values.h"
diff --git a/shell/browser/api/electron_api_power_monitor_win.cc b/shell/browser/api/electron_api_power_monitor_win.cc
index 3e408c1182..e08e191b42 100644
--- a/shell/browser/api/electron_api_power_monitor_win.cc
+++ b/shell/browser/api/electron_api_power_monitor_win.cc
@@ -11,7 +11,6 @@
#include "base/win/wrapped_window_proc.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
-#include "ui/base/win/shell.h"
#include "ui/gfx/win/hwnd_util.h"
namespace electron {
diff --git a/shell/browser/api/electron_api_safe_storage.cc b/shell/browser/api/electron_api_safe_storage.cc
index 2bbf774c2b..b1704754d1 100644
--- a/shell/browser/api/electron_api_safe_storage.cc
+++ b/shell/browser/api/electron_api_safe_storage.cc
@@ -13,7 +13,6 @@
#include "shell/common/gin_converters/callback_converter.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/node_includes.h"
-#include "shell/common/platform_util.h"
namespace electron::safestorage {
diff --git a/shell/browser/api/electron_api_system_preferences_win.cc b/shell/browser/api/electron_api_system_preferences_win.cc
index b510c9683b..eeeb7361c2 100644
--- a/shell/browser/api/electron_api_system_preferences_win.cc
+++ b/shell/browser/api/electron_api_system_preferences_win.cc
@@ -16,7 +16,6 @@
#include "base/win/windows_types.h"
#include "base/win/wrapped_window_proc.h"
#include "shell/common/color_util.h"
-#include "ui/base/win/shell.h"
#include "ui/gfx/color_utils.h"
#include "ui/gfx/win/hwnd_util.h"
diff --git a/shell/browser/api/electron_api_tray.h b/shell/browser/api/electron_api_tray.h
index 9eaebb5066..2eb7126673 100644
--- a/shell/browser/api/electron_api_tray.h
+++ b/shell/browser/api/electron_api_tray.h
@@ -13,7 +13,6 @@
#include "gin/handle.h"
#include "gin/wrappable.h"
#include "shell/browser/event_emitter_mixin.h"
-#include "shell/browser/javascript_environment.h"
#include "shell/browser/ui/tray_icon.h"
#include "shell/browser/ui/tray_icon_observer.h"
#include "shell/common/gin_converters/guid_converter.h"
diff --git a/shell/browser/api/electron_api_web_contents.cc b/shell/browser/api/electron_api_web_contents.cc
index ecdd929a24..fb671694de 100644
--- a/shell/browser/api/electron_api_web_contents.cc
+++ b/shell/browser/api/electron_api_web_contents.cc
@@ -5,6 +5,7 @@
#include "shell/browser/api/electron_api_web_contents.h"
#include <limits>
+#include <list>
#include <memory>
#include <optional>
#include <set>
@@ -86,7 +87,6 @@
#include "shell/browser/browser.h"
#include "shell/browser/child_web_contents_tracker.h"
#include "shell/browser/electron_autofill_driver_factory.h"
-#include "shell/browser/electron_browser_client.h"
#include "shell/browser/electron_browser_context.h"
#include "shell/browser/electron_browser_main_parts.h"
#include "shell/browser/electron_navigation_throttle.h"
@@ -142,13 +142,7 @@
#include "ui/display/screen.h"
#include "ui/events/base_event_utils.h"
-#if BUILDFLAG(IS_WIN)
-#include "shell/browser/native_window_views.h"
-#endif
-
-#if !BUILDFLAG(IS_MAC)
-#include "ui/aura/window.h"
-#else
+#if BUILDFLAG(IS_MAC)
#include "ui/base/cocoa/defaults_utils.h"
#endif
@@ -157,6 +151,7 @@
#endif
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_WIN)
+#include "ui/aura/window.h"
#include "ui/gfx/font_render_params.h"
#endif
diff --git a/shell/browser/api/electron_api_web_contents.h b/shell/browser/api/electron_api_web_contents.h
index 8f7956f20e..df5e8c31dd 100644
--- a/shell/browser/api/electron_api_web_contents.h
+++ b/shell/browser/api/electron_api_web_contents.h
@@ -50,7 +50,6 @@
#include "shell/common/gin_helper/constructible.h"
#include "shell/common/gin_helper/error_thrower.h"
#include "shell/common/gin_helper/pinnable.h"
-#include "ui/base/cursor/cursor.h"
#include "ui/base/models/image_model.h"
#if BUILDFLAG(ENABLE_PRINTING)
@@ -83,6 +82,10 @@ namespace gin {
class Arguments;
}
+namespace ui {
+class Cursor;
+}
+
class SkRegion;
namespace electron {
diff --git a/shell/browser/api/save_page_handler.cc b/shell/browser/api/save_page_handler.cc
index c6837e9fc9..b06fda2741 100644
--- a/shell/browser/api/save_page_handler.cc
+++ b/shell/browser/api/save_page_handler.cc
@@ -7,7 +7,6 @@
#include <utility>
#include "base/files/file_path.h"
-#include "base/functional/callback.h"
#include "content/public/browser/web_contents.h"
#include "shell/browser/electron_browser_context.h"
diff --git a/shell/browser/auto_updater.cc b/shell/browser/auto_updater.cc
index 519f84a83e..cd6c9d8676 100644
--- a/shell/browser/auto_updater.cc
+++ b/shell/browser/auto_updater.cc
@@ -3,6 +3,7 @@
// found in the LICENSE file.
#include "shell/browser/auto_updater.h"
+#include "build/build_config.h"
namespace auto_updater {
diff --git a/shell/browser/auto_updater.h b/shell/browser/auto_updater.h
index 017c702ba6..be2487c22d 100644
--- a/shell/browser/auto_updater.h
+++ b/shell/browser/auto_updater.h
@@ -8,8 +8,6 @@
#include <map>
#include <string>
-#include "build/build_config.h"
-
namespace base {
class Time;
}
diff --git a/shell/browser/badging/badge_manager.cc b/shell/browser/badging/badge_manager.cc
index 3de1482bfb..c7811e56ef 100755
--- a/shell/browser/badging/badge_manager.cc
+++ b/shell/browser/badging/badge_manager.cc
@@ -8,7 +8,6 @@
#include "base/i18n/number_formatting.h"
#include "base/strings/utf_string_conversions.h"
-#include "build/build_config.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/render_frame_host.h"
diff --git a/shell/browser/bluetooth/electron_bluetooth_delegate.cc b/shell/browser/bluetooth/electron_bluetooth_delegate.cc
index 3616c55b03..8db70add67 100644
--- a/shell/browser/bluetooth/electron_bluetooth_delegate.cc
+++ b/shell/browser/bluetooth/electron_bluetooth_delegate.cc
@@ -9,7 +9,6 @@
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
-#include "build/build_config.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/web_contents.h"
#include "device/bluetooth/bluetooth_device.h"
diff --git a/shell/browser/bluetooth/electron_bluetooth_delegate.h b/shell/browser/bluetooth/electron_bluetooth_delegate.h
index a5c90f50a6..a53353b119 100644
--- a/shell/browser/bluetooth/electron_bluetooth_delegate.h
+++ b/shell/browser/bluetooth/electron_bluetooth_delegate.h
@@ -11,8 +11,8 @@
#include <vector>
#include "base/memory/weak_ptr.h"
+#include "base/values.h"
#include "content/public/browser/bluetooth_delegate.h"
-#include "content/public/browser/render_frame_host.h"
#include "third_party/blink/public/mojom/bluetooth/web_bluetooth.mojom-forward.h"
namespace blink {
diff --git a/shell/browser/browser.cc b/shell/browser/browser.cc
index 8680c04f00..928c19cdf4 100644
--- a/shell/browser/browser.cc
+++ b/shell/browser/browser.cc
@@ -16,11 +16,9 @@
#include "chrome/common/chrome_paths.h"
#include "shell/browser/browser_observer.h"
#include "shell/browser/electron_browser_main_parts.h"
-#include "shell/browser/login_handler.h"
#include "shell/browser/native_window.h"
#include "shell/browser/window_list.h"
#include "shell/common/application_info.h"
-#include "shell/common/electron_paths.h"
#include "shell/common/gin_converters/login_item_settings_converter.h"
#include "shell/common/gin_helper/arguments.h"
#include "shell/common/thread_restrictions.h"
diff --git a/shell/browser/browser.h b/shell/browser/browser.h
index d554fb0e00..6d098812cd 100644
--- a/shell/browser/browser.h
+++ b/shell/browser/browser.h
@@ -10,6 +10,7 @@
#include <string>
#include <vector>
+#include "base/files/file_path.h"
#include "base/observer_list.h"
#include "base/task/cancelable_task_tracker.h"
#include "base/values.h"
@@ -27,8 +28,10 @@
#include "ui/base/cocoa/secure_password_input.h"
#endif
-namespace base {
-class FilePath;
+class GURL;
+
+namespace gin {
+class Arguments;
}
namespace gin_helper {
diff --git a/shell/browser/browser_observer.h b/shell/browser/browser_observer.h
index e4ab06fde1..a5146660d5 100644
--- a/shell/browser/browser_observer.h
+++ b/shell/browser/browser_observer.h
@@ -9,8 +9,8 @@
#include "base/memory/scoped_refptr.h"
#include "base/observer_list_types.h"
+#include "base/values.h"
#include "build/build_config.h"
-#include "shell/browser/login_handler.h"
namespace electron {
diff --git a/shell/browser/browser_process_impl.cc b/shell/browser/browser_process_impl.cc
index c27d9afb75..6b98426e84 100644
--- a/shell/browser/browser_process_impl.cc
+++ b/shell/browser/browser_process_impl.cc
@@ -12,7 +12,6 @@
#include "base/files/file_path.h"
#include "base/path_service.h"
#include "chrome/browser/browser_process.h"
-#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "components/os_crypt/async/browser/key_provider.h"
#include "components/os_crypt/async/browser/os_crypt_async.h"
@@ -30,7 +29,6 @@
#include "content/public/browser/network_quality_observer_factory.h"
#include "content/public/browser/network_service_instance.h"
#include "content/public/common/content_switches.h"
-#include "electron/fuses.h"
#include "extensions/common/constants.h"
#include "net/proxy_resolution/proxy_config.h"
#include "net/proxy_resolution/proxy_config_service.h"
diff --git a/shell/browser/browser_win.cc b/shell/browser/browser_win.cc
index 077a786280..3d261fe495 100644
--- a/shell/browser/browser_win.cc
+++ b/shell/browser/browser_win.cc
@@ -15,6 +15,7 @@
#include <shobjidl.h> // NOLINT(build/include_order)
#include "base/base_paths.h"
+#include "base/command_line.h"
#include "base/file_version_info.h"
#include "base/files/file_path.h"
#include "base/logging.h"
@@ -27,7 +28,6 @@
#include "base/win/windows_version.h"
#include "chrome/browser/icon_manager.h"
#include "electron/electron_version.h"
-#include "shell/browser/api/electron_api_app.h"
#include "shell/browser/badging/badge_manager.h"
#include "shell/browser/electron_browser_main_parts.h"
#include "shell/browser/javascript_environment.h"
diff --git a/shell/browser/electron_autofill_driver_factory.cc b/shell/browser/electron_autofill_driver_factory.cc
index 9aa01c23f1..edbea8e4b0 100644
--- a/shell/browser/electron_autofill_driver_factory.cc
+++ b/shell/browser/electron_autofill_driver_factory.cc
@@ -8,7 +8,6 @@
#include <utility>
#include "base/functional/bind.h"
-#include "base/functional/callback.h"
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/web_contents.h"
diff --git a/shell/browser/electron_browser_client.cc b/shell/browser/electron_browser_client.cc
index 8e28587a58..5f96f1ca2d 100644
--- a/shell/browser/electron_browser_client.cc
+++ b/shell/browser/electron_browser_client.cc
@@ -18,6 +18,7 @@
#include "base/files/file_util.h"
#include "base/no_destructor.h"
#include "base/path_service.h"
+#include "base/process/process_metrics.h"
#include "base/strings/escape.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
@@ -73,7 +74,6 @@
#include "shell/browser/api/electron_api_app.h"
#include "shell/browser/api/electron_api_crash_reporter.h"
#include "shell/browser/api/electron_api_protocol.h"
-#include "shell/browser/api/electron_api_session.h"
#include "shell/browser/api/electron_api_web_contents.h"
#include "shell/browser/api/electron_api_web_request.h"
#include "shell/browser/badging/badge_manager.h"
@@ -87,6 +87,7 @@
#include "shell/browser/electron_web_contents_utility_handler_impl.h"
#include "shell/browser/font_defaults.h"
#include "shell/browser/javascript_environment.h"
+#include "shell/browser/login_handler.h"
#include "shell/browser/media/media_capture_devices_dispatcher.h"
#include "shell/browser/native_window.h"
#include "shell/browser/net/network_context_service.h"
diff --git a/shell/browser/electron_browser_client.h b/shell/browser/electron_browser_client.h
index e1e69adeef..7276467ade 100644
--- a/shell/browser/electron_browser_client.h
+++ b/shell/browser/electron_browser_client.h
@@ -30,6 +30,7 @@
namespace content {
class ClientCertificateDelegate;
+class PlatformNotificationService;
class QuotaPermissionContext;
} // namespace content
diff --git a/shell/browser/electron_browser_main_parts.cc b/shell/browser/electron_browser_main_parts.cc
index 5882e0d78b..218e7f5ee2 100644
--- a/shell/browser/electron_browser_main_parts.cc
+++ b/shell/browser/electron_browser_main_parts.cc
@@ -22,7 +22,6 @@
#include "base/task/single_thread_task_runner.h"
#include "chrome/browser/icon_manager.h"
#include "chrome/browser/ui/color/chrome_color_mixers.h"
-#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "components/os_crypt/sync/key_storage_config_linux.h"
#include "components/os_crypt/sync/key_storage_util_linux.h"
@@ -35,6 +34,7 @@
#include "content/public/browser/child_process_data.h"
#include "content/public/browser/child_process_security_policy.h"
#include "content/public/browser/device_service.h"
+#include "content/public/browser/download_manager.h"
#include "content/public/browser/first_party_sets_handler.h"
#include "content/public/browser/web_ui_controller_factory.h"
#include "content/public/common/content_features.h"
@@ -42,12 +42,10 @@
#include "content/public/common/process_type.h"
#include "content/public/common/result_codes.h"
#include "electron/buildflags/buildflags.h"
-#include "electron/fuses.h"
#include "media/base/localized_strings.h"
#include "services/network/public/cpp/features.h"
#include "services/tracing/public/cpp/stack_sampling/tracing_sampler_profiler.h"
#include "shell/app/electron_main_delegate.h"
-#include "shell/browser/api/electron_api_app.h"
#include "shell/browser/api/electron_api_utility_process.h"
#include "shell/browser/browser.h"
#include "shell/browser/browser_process_impl.h"
@@ -69,9 +67,9 @@
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/ui_base_switches.h"
#include "ui/color/color_provider_manager.h"
+#include "url/url_util.h"
#if defined(USE_AURA)
-#include "ui/display/display.h"
#include "ui/display/screen.h"
#include "ui/views/widget/desktop_aura/desktop_screen.h"
#include "ui/wm/core/wm_state.h"
diff --git a/shell/browser/electron_browser_main_parts_mac.mm b/shell/browser/electron_browser_main_parts_mac.mm
index 975853b2f5..c7c093010e 100644
--- a/shell/browser/electron_browser_main_parts_mac.mm
+++ b/shell/browser/electron_browser_main_parts_mac.mm
@@ -13,7 +13,6 @@
#include "shell/browser/browser_process_impl.h"
#include "shell/browser/mac/electron_application.h"
#include "shell/browser/mac/electron_application_delegate.h"
-#include "shell/common/electron_paths.h"
#include "ui/base/l10n/l10n_util_mac.h"
namespace electron {
diff --git a/shell/browser/electron_permission_manager.cc b/shell/browser/electron_permission_manager.cc
index 41a47c7eed..31089aa50e 100644
--- a/shell/browser/electron_permission_manager.cc
+++ b/shell/browser/electron_permission_manager.cc
@@ -19,7 +19,7 @@
#include "content/public/browser/web_contents.h"
#include "gin/data_object_builder.h"
#include "shell/browser/api/electron_api_web_contents.h"
-#include "shell/browser/electron_browser_client.h"
+#include "shell/browser/electron_browser_context.h"
#include "shell/browser/electron_browser_main_parts.h"
#include "shell/browser/web_contents_permission_helper.h"
#include "shell/browser/web_contents_preferences.h"
diff --git a/shell/browser/electron_permission_manager.h b/shell/browser/electron_permission_manager.h
index 9c6ff7af30..af8e85b686 100644
--- a/shell/browser/electron_permission_manager.h
+++ b/shell/browser/electron_permission_manager.h
@@ -10,20 +10,18 @@
#include "base/containers/id_map.h"
#include "base/functional/callback.h"
+#include "base/values.h"
#include "content/public/browser/permission_controller_delegate.h"
-#include "shell/browser/electron_browser_context.h"
#include "shell/common/gin_helper/dictionary.h"
-namespace base {
-class Value;
-} // namespace base
-
namespace content {
class WebContents;
}
namespace electron {
+class ElectronBrowserContext;
+
class ElectronPermissionManager : public content::PermissionControllerDelegate {
public:
ElectronPermissionManager();
diff --git a/shell/browser/extensions/api/management/electron_management_api_delegate.h b/shell/browser/extensions/api/management/electron_management_api_delegate.h
index 65030697ce..7b415b855b 100644
--- a/shell/browser/extensions/api/management/electron_management_api_delegate.h
+++ b/shell/browser/extensions/api/management/electron_management_api_delegate.h
@@ -8,7 +8,6 @@
#include <memory>
#include <string>
-#include "base/task/cancelable_task_tracker.h"
#include "extensions/browser/api/management/management_api_delegate.h"
#include "extensions/common/extension_id.h"
diff --git a/shell/browser/extensions/api/pdf_viewer_private/pdf_viewer_private_api.cc b/shell/browser/extensions/api/pdf_viewer_private/pdf_viewer_private_api.cc
index df1a36390c..bab4336953 100644
--- a/shell/browser/extensions/api/pdf_viewer_private/pdf_viewer_private_api.cc
+++ b/shell/browser/extensions/api/pdf_viewer_private/pdf_viewer_private_api.cc
@@ -16,7 +16,6 @@
#include "components/pdf/common/constants.h"
#include "components/prefs/pref_service.h"
#include "extensions/browser/guest_view/mime_handler_view/mime_handler_view_guest.h"
-#include "shell/browser/electron_browser_context.h"
#include "url/url_constants.h"
namespace extensions {
diff --git a/shell/browser/extensions/api/runtime/electron_runtime_api_delegate.cc b/shell/browser/extensions/api/runtime/electron_runtime_api_delegate.cc
index be69be338f..d41b2acc27 100644
--- a/shell/browser/extensions/api/runtime/electron_runtime_api_delegate.cc
+++ b/shell/browser/extensions/api/runtime/electron_runtime_api_delegate.cc
@@ -6,7 +6,6 @@
#include <string>
-#include "build/build_config.h"
#include "components/update_client/update_query_params.h"
#include "extensions/common/api/runtime.h"
#include "shell/browser/extensions/electron_extension_system.h"
diff --git a/shell/browser/extensions/api/streams_private/streams_private_api.cc b/shell/browser/extensions/api/streams_private/streams_private_api.cc
index 9d015c151b..c5a7001854 100644
--- a/shell/browser/extensions/api/streams_private/streams_private_api.cc
+++ b/shell/browser/extensions/api/streams_private/streams_private_api.cc
@@ -8,7 +8,6 @@
#include <utility>
#include "content/public/browser/browser_thread.h"
-#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/web_contents.h"
#include "electron/buildflags/buildflags.h"
#include "extensions/browser/extension_registry.h"
diff --git a/shell/browser/extensions/api/tabs/tabs_api.cc b/shell/browser/extensions/api/tabs/tabs_api.cc
index 9fcb8efdb1..a7205bae7b 100644
--- a/shell/browser/extensions/api/tabs/tabs_api.cc
+++ b/shell/browser/extensions/api/tabs/tabs_api.cc
@@ -4,8 +4,10 @@
#include "shell/browser/extensions/api/tabs/tabs_api.h"
-#include <memory>
+#include <optional>
+#include <string>
#include <utility>
+#include <vector>
#include "base/command_line.h"
#include "base/strings/pattern.h"
diff --git a/shell/browser/extensions/electron_component_extension_resource_manager.cc b/shell/browser/extensions/electron_component_extension_resource_manager.cc
index 34f664ec51..b675f630b9 100644
--- a/shell/browser/extensions/electron_component_extension_resource_manager.cc
+++ b/shell/browser/extensions/electron_component_extension_resource_manager.cc
@@ -10,7 +10,6 @@
#include "base/containers/contains.h"
#include "base/path_service.h"
#include "base/values.h"
-#include "build/build_config.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/grit/component_extension_resources_map.h"
#include "electron/buildflags/buildflags.h"
diff --git a/shell/browser/extensions/electron_extensions_browser_client.cc b/shell/browser/extensions/electron_extensions_browser_client.cc
index e3d4e5338a..3f235e2095 100644
--- a/shell/browser/extensions/electron_extensions_browser_client.cc
+++ b/shell/browser/extensions/electron_extensions_browser_client.cc
@@ -10,7 +10,6 @@
#include "base/functional/bind.h"
#include "base/memory/ptr_util.h"
#include "base/path_service.h"
-#include "build/build_config.h"
#include "chrome/browser/extensions/chrome_url_request_util.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/extensions/chrome_manifest_url_handlers.h"
@@ -33,7 +32,6 @@
#include "extensions/common/file_util.h"
#include "extensions/common/manifest_constants.h"
#include "extensions/common/manifest_url_handlers.h"
-#include "net/base/mime_util.h"
#include "services/network/public/mojom/url_loader.mojom.h"
#include "shell/browser/browser.h"
#include "shell/browser/electron_browser_client.h"
diff --git a/shell/browser/extensions/electron_extensions_browser_client.h b/shell/browser/extensions/electron_extensions_browser_client.h
index 89a29ce468..1e0fd04f78 100644
--- a/shell/browser/extensions/electron_extensions_browser_client.h
+++ b/shell/browser/extensions/electron_extensions_browser_client.h
@@ -9,7 +9,6 @@
#include <string>
#include <vector>
-#include "build/build_config.h"
#include "extensions/browser/extensions_browser_client.h"
#include "extensions/browser/kiosk/kiosk_delegate.h"
#include "mojo/public/cpp/bindings/pending_remote.h"
diff --git a/shell/browser/extensions/electron_messaging_delegate.cc b/shell/browser/extensions/electron_messaging_delegate.cc
index a534759a0b..711f426ec1 100644
--- a/shell/browser/extensions/electron_messaging_delegate.cc
+++ b/shell/browser/extensions/electron_messaging_delegate.cc
@@ -9,7 +9,6 @@
#include "base/functional/callback.h"
#include "base/values.h"
-#include "build/build_config.h"
#include "components/prefs/pref_service.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_thread.h"
diff --git a/shell/browser/extensions/electron_process_manager_delegate.cc b/shell/browser/extensions/electron_process_manager_delegate.cc
index ce9df4a071..8b61178ef7 100644
--- a/shell/browser/extensions/electron_process_manager_delegate.cc
+++ b/shell/browser/extensions/electron_process_manager_delegate.cc
@@ -7,7 +7,6 @@
#include "base/command_line.h"
#include "base/one_shot_event.h"
-#include "build/build_config.h"
#include "content/public/browser/notification_service.h"
#include "extensions/browser/extension_system.h"
#include "extensions/browser/process_manager.h"
diff --git a/shell/browser/fake_location_provider.cc b/shell/browser/fake_location_provider.cc
index eaeb075d57..60d1c51490 100644
--- a/shell/browser/fake_location_provider.cc
+++ b/shell/browser/fake_location_provider.cc
@@ -4,7 +4,6 @@
#include "shell/browser/fake_location_provider.h"
-#include "base/functional/callback.h"
#include "base/time/time.h"
#include "services/device/public/mojom/geoposition.mojom-shared.h"
#include "services/device/public/mojom/geoposition.mojom.h"
diff --git a/shell/browser/file_select_helper.cc b/shell/browser/file_select_helper.cc
index fc80a64fbd..45e03035c2 100644
--- a/shell/browser/file_select_helper.cc
+++ b/shell/browser/file_select_helper.cc
@@ -19,7 +19,6 @@
#include "base/threading/hang_watcher.h"
#include "build/build_config.h"
#include "chrome/browser/browser_process.h"
-#include "chrome/browser/platform_util.h"
#include "chrome/common/pref_names.h"
#include "chrome/grit/generated_resources.h"
#include "components/prefs/pref_service.h"
diff --git a/shell/browser/file_select_helper.h b/shell/browser/file_select_helper.h
index 0035c68cfe..7bd21ab509 100644
--- a/shell/browser/file_select_helper.h
+++ b/shell/browser/file_select_helper.h
@@ -12,8 +12,6 @@
#include "base/memory/raw_ptr.h"
#include "build/build_config.h"
#include "content/public/browser/browser_thread.h"
-#include "content/public/browser/render_widget_host.h"
-#include "content/public/browser/render_widget_host_observer.h"
#include "content/public/browser/web_contents_observer.h"
#include "net/base/directory_lister.h"
#include "third_party/blink/public/mojom/choosers/file_chooser.mojom.h"
diff --git a/shell/browser/hid/electron_hid_delegate.cc b/shell/browser/hid/electron_hid_delegate.cc
index 017a95b8cc..1058dc7897 100644
--- a/shell/browser/hid/electron_hid_delegate.cc
+++ b/shell/browser/hid/electron_hid_delegate.cc
@@ -13,6 +13,7 @@
#include "content/public/browser/web_contents.h"
#include "electron/buildflags/buildflags.h"
#include "services/device/public/cpp/hid/hid_switches.h"
+#include "shell/browser/electron_browser_context.h"
#include "shell/browser/electron_permission_manager.h"
#include "shell/browser/hid/hid_chooser_context.h"
#include "shell/browser/hid/hid_chooser_context_factory.h"
diff --git a/shell/browser/hid/electron_hid_delegate.h b/shell/browser/hid/electron_hid_delegate.h
index 7c2f703781..b1c1f87789 100644
--- a/shell/browser/hid/electron_hid_delegate.h
+++ b/shell/browser/hid/electron_hid_delegate.h
@@ -14,7 +14,6 @@
#include "content/public/browser/hid_chooser.h"
#include "content/public/browser/hid_delegate.h"
#include "services/device/public/mojom/hid.mojom-forward.h"
-#include "shell/browser/hid/hid_chooser_context.h"
#include "third_party/blink/public/mojom/hid/hid.mojom-forward.h"
#include "url/origin.h"
diff --git a/shell/browser/hid/hid_chooser_context.cc b/shell/browser/hid/hid_chooser_context.cc
index 34dc9092e4..147c10af0e 100644
--- a/shell/browser/hid/hid_chooser_context.cc
+++ b/shell/browser/hid/hid_chooser_context.cc
@@ -4,11 +4,8 @@
#include "shell/browser/hid/hid_chooser_context.h"
-#include <utility>
-
-#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
#include <string_view>
-#endif // BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
+#include <utility>
#include "base/command_line.h"
#include "base/containers/contains.h"
@@ -23,6 +20,7 @@
#include "services/device/public/cpp/hid/hid_blocklist.h"
#include "services/device/public/cpp/hid/hid_switches.h"
#include "shell/browser/api/electron_api_session.h"
+#include "shell/browser/electron_browser_context.h"
#include "shell/browser/electron_permission_manager.h"
#include "shell/browser/web_contents_permission_helper.h"
#include "shell/common/electron_constants.h"
diff --git a/shell/browser/hid/hid_chooser_context.h b/shell/browser/hid/hid_chooser_context.h
index 6d67fab74c..85804c52f5 100644
--- a/shell/browser/hid/hid_chooser_context.h
+++ b/shell/browser/hid/hid_chooser_context.h
@@ -17,12 +17,10 @@
#include "base/scoped_observation_traits.h"
#include "base/unguessable_token.h"
#include "components/keyed_service/core/keyed_service.h"
-#include "content/public/browser/web_contents.h"
#include "mojo/public/cpp/bindings/associated_receiver.h"
#include "mojo/public/cpp/bindings/pending_remote.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "services/device/public/mojom/hid.mojom.h"
-#include "shell/browser/electron_browser_context.h"
#include "url/origin.h"
namespace base {
@@ -31,6 +29,8 @@ class Value;
namespace electron {
+class ElectronBrowserContext;
+
extern const char kHidDeviceNameKey[];
extern const char kHidGuidKey[];
extern const char kHidProductIdKey[];
diff --git a/shell/browser/hid/hid_chooser_controller.h b/shell/browser/hid/hid_chooser_controller.h
index edc0c08b8c..fc5944979d 100644
--- a/shell/browser/hid/hid_chooser_controller.h
+++ b/shell/browser/hid/hid_chooser_controller.h
@@ -17,7 +17,6 @@
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_observer.h"
#include "services/device/public/mojom/hid.mojom-forward.h"
-#include "shell/browser/api/electron_api_session.h"
#include "shell/browser/hid/electron_hid_delegate.h"
#include "shell/browser/hid/hid_chooser_context.h"
#include "shell/common/gin_converters/frame_converter.h"
@@ -28,7 +27,14 @@ namespace content {
class RenderFrameHost;
} // namespace content
+namespace gin {
+class Arguments;
+}
+
namespace electron {
+namespace api {
+class Session;
+}
class ElectronHidDelegate;
diff --git a/shell/browser/linux/unity_service.cc b/shell/browser/linux/unity_service.cc
index 65cb52e3e0..a8710541eb 100644
--- a/shell/browser/linux/unity_service.cc
+++ b/shell/browser/linux/unity_service.cc
@@ -9,8 +9,6 @@
#include <string>
-#include "base/nix/xdg_util.h"
-
// Unity data typedefs.
typedef struct _UnityInspector UnityInspector;
typedef UnityInspector* (*unity_inspector_get_default_func)();
diff --git a/shell/browser/login_handler.cc b/shell/browser/login_handler.cc
index 44d14b1463..1000507731 100644
--- a/shell/browser/login_handler.cc
+++ b/shell/browser/login_handler.cc
@@ -6,7 +6,6 @@
#include <utility>
-#include "base/functional/callback.h"
#include "base/task/sequenced_task_runner.h"
#include "gin/arguments.h"
#include "gin/dictionary.h"
diff --git a/shell/browser/mac/electron_application_delegate.mm b/shell/browser/mac/electron_application_delegate.mm
index 953e480890..655174d4b4 100644
--- a/shell/browser/mac/electron_application_delegate.mm
+++ b/shell/browser/mac/electron_application_delegate.mm
@@ -4,11 +4,11 @@
#import "shell/browser/mac/electron_application_delegate.h"
-#include <memory>
#include <string>
#include "base/allocator/buildflags.h"
#include "base/allocator/partition_allocator/src/partition_alloc/shim/allocator_shim.h"
+#include "base/functional/callback.h"
#include "base/mac/mac_util.h"
#include "base/strings/sys_string_conversions.h"
#include "shell/browser/api/electron_api_push_notifications.h"
diff --git a/shell/browser/mac/in_app_purchase_observer.h b/shell/browser/mac/in_app_purchase_observer.h
index b8a1b4cdb8..a02903e709 100644
--- a/shell/browser/mac/in_app_purchase_observer.h
+++ b/shell/browser/mac/in_app_purchase_observer.h
@@ -9,7 +9,6 @@
#include <string>
#include <vector>
-#include "base/functional/callback.h"
#include "base/memory/raw_ptr_exclusion.h"
#include "base/memory/weak_ptr.h"
diff --git a/shell/browser/media/media_capture_devices_dispatcher.h b/shell/browser/media/media_capture_devices_dispatcher.h
index 4f173064b1..364aabcb68 100644
--- a/shell/browser/media/media_capture_devices_dispatcher.h
+++ b/shell/browser/media/media_capture_devices_dispatcher.h
@@ -7,7 +7,6 @@
#include "components/webrtc/media_stream_device_enumerator_impl.h"
#include "content/public/browser/media_observer.h"
-#include "content/public/browser/media_stream_request.h"
#include "third_party/blink/public/common/mediastream/media_stream_request.h"
#include "third_party/blink/public/mojom/mediastream/media_stream.mojom.h"
diff --git a/shell/browser/native_window.cc b/shell/browser/native_window.cc
index bb1d82fd82..b4ca7c4962 100644
--- a/shell/browser/native_window.cc
+++ b/shell/browser/native_window.cc
@@ -16,6 +16,7 @@
#include "include/core/SkColor.h"
#include "shell/browser/background_throttling_source.h"
#include "shell/browser/browser.h"
+#include "shell/browser/draggable_region_provider.h"
#include "shell/browser/native_window_features.h"
#include "shell/browser/ui/drag_util.h"
#include "shell/browser/window_list.h"
@@ -23,7 +24,6 @@
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/gin_helper/persistent_dictionary.h"
#include "shell/common/options_switches.h"
-#include "third_party/skia/include/core/SkRegion.h"
#include "ui/base/hit_test.h"
#include "ui/compositor/compositor.h"
#include "ui/views/widget/widget.h"
@@ -33,7 +33,6 @@
#endif
#if BUILDFLAG(IS_WIN)
-#include "ui/base/win/shell.h"
#include "ui/display/win/screen_win.h"
#endif
diff --git a/shell/browser/native_window.h b/shell/browser/native_window.h
index 5256d34a6a..421e1440b7 100644
--- a/shell/browser/native_window.h
+++ b/shell/browser/native_window.h
@@ -20,12 +20,11 @@
#include "content/public/browser/web_contents_user_data.h"
#include "electron/shell/common/api/api.mojom.h"
#include "extensions/browser/app_window/size_constraints.h"
-#include "shell/browser/draggable_region_provider.h"
#include "shell/browser/native_window_observer.h"
-#include "shell/browser/ui/inspectable_web_contents_view.h"
#include "ui/views/widget/widget_delegate.h"
class SkRegion;
+class DraggableRegionProvider;
namespace input {
struct NativeWebKeyboardEvent;
diff --git a/shell/browser/native_window_mac.h b/shell/browser/native_window_mac.h
index cf6f0c1d9d..363dfecb9a 100644
--- a/shell/browser/native_window_mac.h
+++ b/shell/browser/native_window_mac.h
@@ -14,6 +14,7 @@
#include "electron/shell/common/api/api.mojom.h"
#include "shell/browser/native_window.h"
+#include "third_party/skia/include/core/SkRegion.h"
#include "ui/display/display_observer.h"
#include "ui/native_theme/native_theme_observer.h"
#include "ui/views/controls/native/native_view_host.h"
diff --git a/shell/browser/native_window_mac.mm b/shell/browser/native_window_mac.mm
index fd94b01353..bdc02d2e1d 100644
--- a/shell/browser/native_window_mac.mm
+++ b/shell/browser/native_window_mac.mm
@@ -40,7 +40,6 @@
#include "shell/common/node_includes.h"
#include "shell/common/options_switches.h"
#include "skia/ext/skia_utils_mac.h"
-#include "third_party/skia/include/core/SkRegion.h"
#include "third_party/webrtc/modules/desktop_capture/mac/window_list_utils.h"
#include "ui/base/hit_test.h"
#include "ui/display/screen.h"
diff --git a/shell/browser/native_window_views.cc b/shell/browser/native_window_views.cc
index 6485cf0ec6..a5364f80e0 100644
--- a/shell/browser/native_window_views.cc
+++ b/shell/browser/native_window_views.cc
@@ -27,7 +27,6 @@
#include "content/public/common/color_parser.h"
#include "shell/browser/api/electron_api_web_contents.h"
#include "shell/browser/ui/inspectable_web_contents.h"
-#include "shell/browser/ui/inspectable_web_contents_view.h"
#include "shell/browser/ui/views/root_view.h"
#include "shell/browser/web_contents_preferences.h"
#include "shell/browser/web_view_manager.h"
@@ -56,7 +55,6 @@
#include "shell/browser/linux/unity_service.h"
#include "shell/browser/ui/electron_desktop_window_tree_host_linux.h"
#include "shell/browser/ui/views/client_frame_view_linux.h"
-#include "shell/browser/ui/views/frameless_view.h"
#include "shell/browser/ui/views/native_frame_view.h"
#include "shell/browser/ui/views/opaque_frame_view.h"
#include "shell/common/platform_util.h"
@@ -79,7 +77,6 @@
#include "shell/browser/ui/views/win_frame_view.h"
#include "shell/browser/ui/win/electron_desktop_native_widget_aura.h"
#include "skia/ext/skia_utils_win.h"
-#include "ui/base/win/shell.h"
#include "ui/display/win/screen_win.h"
#include "ui/gfx/color_utils.h"
#include "ui/gfx/win/hwnd_util.h"
diff --git a/shell/browser/native_window_views_win.cc b/shell/browser/native_window_views_win.cc
index 9899123909..6f4f3e0e40 100644
--- a/shell/browser/native_window_views_win.cc
+++ b/shell/browser/native_window_views_win.cc
@@ -15,8 +15,7 @@
#include "shell/browser/ui/views/win_frame_view.h"
#include "shell/common/electron_constants.h"
#include "ui/display/display.h"
-#include "ui/display/win/screen_win.h"
-#include "ui/gfx/geometry/insets.h"
+#include "ui/display/screen.h"
#include "ui/gfx/geometry/resize_utils.h"
#include "ui/views/widget/native_widget_private.h"
diff --git a/shell/browser/net/asar/asar_file_validator.h b/shell/browser/net/asar/asar_file_validator.h
index d2e9dfb4ec..aa5bf2a041 100644
--- a/shell/browser/net/asar/asar_file_validator.h
+++ b/shell/browser/net/asar/asar_file_validator.h
@@ -5,9 +5,7 @@
#ifndef ELECTRON_SHELL_BROWSER_NET_ASAR_ASAR_FILE_VALIDATOR_H_
#define ELECTRON_SHELL_BROWSER_NET_ASAR_ASAR_FILE_VALIDATOR_H_
-#include <algorithm>
#include <memory>
-#include <optional>
#include "crypto/secure_hash.h"
#include "mojo/public/cpp/system/file_data_source.h"
diff --git a/shell/browser/net/asar/asar_url_loader.cc b/shell/browser/net/asar/asar_url_loader.cc
index d13dc55c7d..3acc2d8cc3 100644
--- a/shell/browser/net/asar/asar_url_loader.cc
+++ b/shell/browser/net/asar/asar_url_loader.cc
@@ -13,7 +13,6 @@
#include "base/strings/string_piece.h"
#include "base/task/thread_pool.h"
#include "content/public/browser/file_url_loader.h"
-#include "electron/fuses.h"
#include "mojo/public/cpp/bindings/receiver.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "mojo/public/cpp/system/data_pipe_producer.h"
diff --git a/shell/browser/net/electron_url_loader_factory.cc b/shell/browser/net/electron_url_loader_factory.cc
index fd3b0b091b..ae9bdc4b8d 100644
--- a/shell/browser/net/electron_url_loader_factory.cc
+++ b/shell/browser/net/electron_url_loader_factory.cc
@@ -4,7 +4,6 @@
#include "shell/browser/net/electron_url_loader_factory.h"
-#include <list>
#include <memory>
#include <string>
#include <string_view>
diff --git a/shell/browser/net/network_context_service.cc b/shell/browser/net/network_context_service.cc
index a2b75ea84d..7c465c9991 100644
--- a/shell/browser/net/network_context_service.cc
+++ b/shell/browser/net/network_context_service.cc
@@ -17,6 +17,7 @@
#include "services/network/public/cpp/cors/origin_access_list.h"
#include "shell/browser/browser_process_impl.h"
#include "shell/browser/electron_browser_client.h"
+#include "shell/browser/electron_browser_context.h"
#include "shell/browser/net/system_network_context_manager.h"
namespace electron {
diff --git a/shell/browser/net/network_context_service.h b/shell/browser/net/network_context_service.h
index 113e576079..e212c97dc6 100644
--- a/shell/browser/net/network_context_service.h
+++ b/shell/browser/net/network_context_service.h
@@ -11,14 +11,19 @@
#include "mojo/public/cpp/bindings/remote.h"
#include "services/cert_verifier/public/mojom/cert_verifier_service_factory.mojom.h"
#include "services/network/public/mojom/network_context.mojom.h"
-#include "shell/browser/electron_browser_context.h"
namespace base {
class FilePath;
} // namespace base
+namespace content {
+class BrowserContext;
+} // namespace content
+
namespace electron {
+class ElectronBrowserContext;
+
// KeyedService that initializes and provides access to the NetworkContexts for
// a BrowserContext.
class NetworkContextService : public KeyedService {
diff --git a/shell/browser/net/network_context_service_factory.cc b/shell/browser/net/network_context_service_factory.cc
index f2c635a533..b74c5671b9 100644
--- a/shell/browser/net/network_context_service_factory.cc
+++ b/shell/browser/net/network_context_service_factory.cc
@@ -6,6 +6,7 @@
#include "base/no_destructor.h"
#include "components/keyed_service/content/browser_context_dependency_manager.h"
+#include "shell/browser/electron_browser_context.h"
#include "shell/browser/net/network_context_service.h"
namespace electron {
diff --git a/shell/browser/net/proxying_url_loader_factory.cc b/shell/browser/net/proxying_url_loader_factory.cc
index 7c8df6192c..b8f5cf2219 100644
--- a/shell/browser/net/proxying_url_loader_factory.cc
+++ b/shell/browser/net/proxying_url_loader_factory.cc
@@ -20,7 +20,6 @@
#include "net/http/http_status_code.h"
#include "net/http/http_util.h"
#include "net/url_request/redirect_info.h"
-#include "services/metrics/public/cpp/ukm_source_id.h"
#include "services/network/public/cpp/features.h"
#include "services/network/public/mojom/early_hints.mojom.h"
#include "shell/browser/net/asar/asar_url_loader.h"
diff --git a/shell/browser/net/proxying_url_loader_factory.h b/shell/browser/net/proxying_url_loader_factory.h
index 828c7da67f..3ffd1d416a 100644
--- a/shell/browser/net/proxying_url_loader_factory.h
+++ b/shell/browser/net/proxying_url_loader_factory.h
@@ -17,7 +17,6 @@
#include "base/memory/raw_ref.h"
#include "base/memory/weak_ptr.h"
#include "content/public/browser/content_browser_client.h"
-#include "content/public/browser/render_frame_host.h"
#include "extensions/browser/api/web_request/web_request_info.h"
#include "mojo/public/cpp/bindings/pending_receiver.h"
#include "mojo/public/cpp/bindings/pending_remote.h"
diff --git a/shell/browser/net/proxying_websocket.cc b/shell/browser/net/proxying_websocket.cc
index a14bb2a9cf..9419322139 100644
--- a/shell/browser/net/proxying_websocket.cc
+++ b/shell/browser/net/proxying_websocket.cc
@@ -12,7 +12,6 @@
#include "content/public/browser/browser_thread.h"
#include "extensions/browser/extension_navigation_ui_data.h"
#include "net/base/ip_endpoint.h"
-#include "net/http/http_util.h"
#include "services/network/public/mojom/url_response_head.mojom.h"
namespace electron {
diff --git a/shell/browser/net/system_network_context_manager.cc b/shell/browser/net/system_network_context_manager.cc
index f2785ef8fa..be839e1742 100644
--- a/shell/browser/net/system_network_context_manager.cc
+++ b/shell/browser/net/system_network_context_manager.cc
@@ -15,7 +15,6 @@
#include "chrome/browser/browser_process.h"
#include "chrome/browser/net/chrome_mojo_proxy_resolver_factory.h"
#include "chrome/common/chrome_features.h"
-#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "components/os_crypt/sync/os_crypt.h"
#include "components/prefs/pref_service.h"
@@ -37,7 +36,6 @@
#include "shell/browser/browser.h"
#include "shell/browser/electron_browser_client.h"
#include "shell/common/application_info.h"
-#include "shell/common/electron_paths.h"
#include "shell/common/options_switches.h"
#include "url/gurl.h"
diff --git a/shell/browser/net/system_network_context_manager.h b/shell/browser/net/system_network_context_manager.h
index 02b0a08512..a8e9a6e554 100644
--- a/shell/browser/net/system_network_context_manager.h
+++ b/shell/browser/net/system_network_context_manager.h
@@ -5,8 +5,6 @@
#ifndef ELECTRON_SHELL_BROWSER_NET_SYSTEM_NETWORK_CONTEXT_MANAGER_H_
#define ELECTRON_SHELL_BROWSER_NET_SYSTEM_NETWORK_CONTEXT_MANAGER_H_
-#include <optional>
-
#include "chrome/browser/net/proxy_config_monitor.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "sandbox/policy/features.h"
diff --git a/shell/browser/network_hints_handler_impl.cc b/shell/browser/network_hints_handler_impl.cc
index 417215d142..ec2f9fac0d 100644
--- a/shell/browser/network_hints_handler_impl.cc
+++ b/shell/browser/network_hints_handler_impl.cc
@@ -12,7 +12,6 @@
#include "content/public/browser/render_process_host.h"
#include "mojo/public/cpp/bindings/self_owned_receiver.h"
#include "shell/browser/api/electron_api_session.h"
-#include "shell/browser/electron_browser_context.h"
#include "shell/common/gin_converters/gurl_converter.h"
#include "v8/include/v8.h"
diff --git a/shell/browser/notifications/win/notification_presenter_win.cc b/shell/browser/notifications/win/notification_presenter_win.cc
index 407250614d..3f0e1b6e01 100644
--- a/shell/browser/notifications/win/notification_presenter_win.cc
+++ b/shell/browser/notifications/win/notification_presenter_win.cc
@@ -17,7 +17,6 @@
#include "base/strings/string_number_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "base/time/time.h"
-#include "base/win/windows_version.h"
#include "shell/browser/notifications/win/windows_toast_notification.h"
#include "shell/common/thread_restrictions.h"
#include "third_party/skia/include/core/SkBitmap.h"
diff --git a/shell/browser/osr/osr_host_display_client.h b/shell/browser/osr/osr_host_display_client.h
index 3cd58f5409..a47aaf67f3 100644
--- a/shell/browser/osr/osr_host_display_client.h
+++ b/shell/browser/osr/osr_host_display_client.h
@@ -11,10 +11,11 @@
#include "base/memory/shared_memory_mapping.h"
#include "components/viz/host/host_display_client.h"
#include "services/viz/privileged/mojom/compositing/layered_window_updater.mojom.h"
-#include "third_party/skia/include/core/SkBitmap.h"
-#include "third_party/skia/include/core/SkCanvas.h"
#include "ui/gfx/native_widget_types.h"
+class SkBitmap;
+class SkCanvas;
+
namespace electron {
typedef base::RepeatingCallback<void(const gfx::Rect&, const SkBitmap&)>
diff --git a/shell/browser/osr/osr_host_display_client_mac.mm b/shell/browser/osr/osr_host_display_client_mac.mm
index 73d40f81ba..f171474323 100644
--- a/shell/browser/osr/osr_host_display_client_mac.mm
+++ b/shell/browser/osr/osr_host_display_client_mac.mm
@@ -3,6 +3,8 @@
// found in the LICENSE file.
#include "shell/browser/osr/osr_host_display_client.h"
+#include "third_party/skia/include/core/SkBitmap.h"
+#include "third_party/skia/include/core/SkImageInfo.h"
#include <IOSurface/IOSurface.h>
diff --git a/shell/browser/osr/osr_render_widget_host_view.cc b/shell/browser/osr/osr_render_widget_host_view.cc
index 8ec96213bd..0542eac860 100644
--- a/shell/browser/osr/osr_render_widget_host_view.cc
+++ b/shell/browser/osr/osr_render_widget_host_view.cc
@@ -32,7 +32,7 @@
#include "content/public/browser/gpu_data_manager.h"
#include "content/public/browser/render_process_host.h"
#include "gpu/command_buffer/client/gl_helper.h"
-#include "media/base/video_frame.h"
+#include "shell/browser/osr/osr_host_display_client.h"
#include "third_party/blink/public/common/input/web_input_event.h"
#include "third_party/skia/include/core/SkCanvas.h"
#include "ui/compositor/compositor.h"
diff --git a/shell/browser/osr/osr_render_widget_host_view.h b/shell/browser/osr/osr_render_widget_host_view.h
index cfd192d26b..3b6971c8b1 100644
--- a/shell/browser/osr/osr_render_widget_host_view.h
+++ b/shell/browser/osr/osr_render_widget_host_view.h
@@ -26,17 +26,14 @@
#include "content/browser/renderer_host/render_widget_host_impl.h" // nogncheck
#include "content/browser/renderer_host/render_widget_host_view_base.h" // nogncheck
#include "content/browser/web_contents/web_contents_view.h" // nogncheck
-#include "shell/browser/osr/osr_host_display_client.h"
#include "shell/browser/osr/osr_video_consumer.h"
#include "shell/browser/osr/osr_view_proxy.h"
#include "third_party/blink/public/mojom/widget/record_content_to_visible_time_request.mojom-forward.h"
#include "third_party/blink/public/platform/web_vector.h"
-#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/base/ime/text_input_client.h"
#include "ui/compositor/compositor.h"
#include "ui/compositor/layer_delegate.h"
#include "ui/compositor/layer_owner.h"
-#include "ui/gfx/geometry/point.h"
#include "components/viz/host/host_display_client.h"
@@ -44,20 +41,28 @@
#include "ui/gfx/win/window_impl.h"
#endif
+class SkBitmap;
+
+namespace gfx {
+class Point;
+class PointF;
+class Rect;
+} // namespace gfx
+
namespace input {
class CursorManager;
}
namespace electron {
-class ElectronCopyFrameGenerator;
class ElectronBeginFrameTimer;
-
+class ElectronCopyFrameGenerator;
class ElectronDelegatedFrameHostClient;
+class OffScreenHostDisplayClient;
-typedef base::RepeatingCallback<void(const gfx::Rect&, const SkBitmap&)>
- OnPaintCallback;
-typedef base::RepeatingCallback<void(const gfx::Rect&)> OnPopupPaintCallback;
+using OnPaintCallback =
+ base::RepeatingCallback<void(const gfx::Rect&, const SkBitmap&)>;
+using OnPopupPaintCallback = base::RepeatingCallback<void(const gfx::Rect&)>;
class OffScreenRenderWidgetHostView
: public content::RenderWidgetHostViewBase,
diff --git a/shell/browser/osr/osr_video_consumer.cc b/shell/browser/osr/osr_video_consumer.cc
index 818c98ef0e..a921fc6d8d 100644
--- a/shell/browser/osr/osr_video_consumer.cc
+++ b/shell/browser/osr/osr_video_consumer.cc
@@ -12,6 +12,8 @@
#include "media/capture/mojom/video_capture_types.mojom.h"
#include "services/viz/privileged/mojom/compositing/frame_sink_video_capture.mojom-shared.h"
#include "shell/browser/osr/osr_render_widget_host_view.h"
+#include "third_party/skia/include/core/SkImageInfo.h"
+#include "third_party/skia/include/core/SkRegion.h"
#include "ui/gfx/skbitmap_operations.h"
namespace {
diff --git a/shell/browser/osr/osr_view_proxy.h b/shell/browser/osr/osr_view_proxy.h
index 0450762442..22fc091887 100644
--- a/shell/browser/osr/osr_view_proxy.h
+++ b/shell/browser/osr/osr_view_proxy.h
@@ -8,11 +8,12 @@
#include <memory>
#include "base/memory/raw_ptr.h"
-#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/events/event.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/views/view.h"
+class SkBitmap;
+
namespace electron {
class OffscreenViewProxy;
diff --git a/shell/browser/printing/print_view_manager_electron.cc b/shell/browser/printing/print_view_manager_electron.cc
index 9f2c63929e..bda9d67507 100644
--- a/shell/browser/printing/print_view_manager_electron.cc
+++ b/shell/browser/printing/print_view_manager_electron.cc
@@ -8,7 +8,6 @@
#include "base/containers/contains.h"
#include "base/functional/bind.h"
-#include "build/build_config.h"
#include "components/printing/browser/print_to_pdf/pdf_print_utils.h"
#include "printing/mojom/print.mojom.h"
#include "printing/page_range.h"
diff --git a/shell/browser/printing/print_view_manager_electron.h b/shell/browser/printing/print_view_manager_electron.h
index 362c85359b..4206d42727 100644
--- a/shell/browser/printing/print_view_manager_electron.h
+++ b/shell/browser/printing/print_view_manager_electron.h
@@ -9,14 +9,14 @@
#include <vector>
#include "base/memory/ref_counted_memory.h"
-#include "build/build_config.h"
#include "chrome/browser/printing/print_view_manager_base.h"
#include "components/printing/browser/print_to_pdf/pdf_print_job.h"
#include "components/printing/common/print.mojom.h"
-#include "content/public/browser/render_frame_host.h"
-#include "content/public/browser/web_contents_observer.h"
#include "content/public/browser/web_contents_user_data.h"
-#include "printing/print_settings.h"
+
+namespace content {
+class RenderFrameHost;
+}
namespace electron {
diff --git a/shell/browser/protocol_registry.cc b/shell/browser/protocol_registry.cc
index d680f48b16..ad88e95be7 100644
--- a/shell/browser/protocol_registry.cc
+++ b/shell/browser/protocol_registry.cc
@@ -4,7 +4,6 @@
#include "shell/browser/protocol_registry.h"
-#include "content/public/browser/web_contents.h"
#include "electron/fuses.h"
#include "shell/browser/electron_browser_context.h"
#include "shell/browser/net/asar/asar_url_loader_factory.h"
diff --git a/shell/browser/relauncher.cc b/shell/browser/relauncher.cc
index a3454196ba..c15221181c 100644
--- a/shell/browser/relauncher.cc
+++ b/shell/browser/relauncher.cc
@@ -16,7 +16,6 @@
#include "base/path_service.h"
#include "base/process/launch.h"
#include "content/public/common/content_paths.h"
-#include "content/public/common/content_switches.h"
#include "content/public/common/main_function_params.h"
#include "shell/common/electron_command_line.h"
diff --git a/shell/browser/relauncher_win.cc b/shell/browser/relauncher_win.cc
index 6d69b171a3..5d0d0d2ed6 100644
--- a/shell/browser/relauncher_win.cc
+++ b/shell/browser/relauncher_win.cc
@@ -14,7 +14,6 @@
#include "base/win/scoped_handle.h"
#include "sandbox/win/src/nt_internals.h"
#include "sandbox/win/src/win_utils.h"
-#include "ui/base/win/shell.h"
namespace relauncher::internal {
diff --git a/shell/browser/serial/serial_chooser_context.cc b/shell/browser/serial/serial_chooser_context.cc
index ec5ac12c73..fe24160010 100644
--- a/shell/browser/serial/serial_chooser_context.cc
+++ b/shell/browser/serial/serial_chooser_context.cc
@@ -15,6 +15,7 @@
#include "content/public/browser/web_contents.h"
#include "mojo/public/cpp/bindings/pending_remote.h"
#include "shell/browser/api/electron_api_session.h"
+#include "shell/browser/electron_browser_context.h"
#include "shell/browser/electron_permission_manager.h"
#include "shell/browser/web_contents_permission_helper.h"
#include "shell/common/gin_converters/frame_converter.h"
diff --git a/shell/browser/serial/serial_chooser_context.h b/shell/browser/serial/serial_chooser_context.h
index baccf465d3..f04f9a54ea 100644
--- a/shell/browser/serial/serial_chooser_context.h
+++ b/shell/browser/serial/serial_chooser_context.h
@@ -16,9 +16,9 @@
#include "components/keyed_service/core/keyed_service.h"
#include "content/public/browser/serial_delegate.h"
#include "mojo/public/cpp/bindings/pending_remote.h"
+#include "mojo/public/cpp/bindings/receiver.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "services/device/public/mojom/serial.mojom-forward.h"
-#include "shell/browser/electron_browser_context.h"
#include "third_party/blink/public/mojom/serial/serial.mojom.h"
#include "url/gurl.h"
#include "url/origin.h"
@@ -29,6 +29,8 @@ class Value;
namespace electron {
+class ElectronBrowserContext;
+
#if BUILDFLAG(IS_WIN)
extern const char kDeviceInstanceIdKey[];
#else
diff --git a/shell/browser/serial/serial_chooser_controller.h b/shell/browser/serial/serial_chooser_controller.h
index aff668edae..3ea152b8dc 100644
--- a/shell/browser/serial/serial_chooser_controller.h
+++ b/shell/browser/serial/serial_chooser_controller.h
@@ -14,7 +14,6 @@
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_observer.h"
#include "services/device/public/mojom/serial.mojom-forward.h"
-#include "shell/browser/api/electron_api_session.h"
#include "shell/browser/serial/electron_serial_delegate.h"
#include "shell/browser/serial/serial_chooser_context.h"
#include "third_party/blink/public/mojom/serial/serial.mojom.h"
@@ -25,6 +24,10 @@ class RenderFrameHost;
namespace electron {
+namespace api {
+class Session;
+}
+
class ElectronSerialDelegate;
// SerialChooserController provides data for the Serial API permission prompt.
diff --git a/shell/browser/special_storage_policy.cc b/shell/browser/special_storage_policy.cc
index 74541727be..b2818971cf 100644
--- a/shell/browser/special_storage_policy.cc
+++ b/shell/browser/special_storage_policy.cc
@@ -5,7 +5,6 @@
#include "shell/browser/special_storage_policy.h"
#include "base/functional/bind.h"
-#include "base/functional/callback.h"
#include "services/network/public/cpp/session_cookie_delete_predicate.h"
namespace electron {
diff --git a/shell/browser/ui/autofill_popup.cc b/shell/browser/ui/autofill_popup.cc
index 5b051098fb..341258ec0e 100644
--- a/shell/browser/ui/autofill_popup.cc
+++ b/shell/browser/ui/autofill_popup.cc
@@ -11,7 +11,6 @@
#include "components/autofill/core/common/autofill_features.h"
#include "electron/buildflags/buildflags.h"
#include "mojo/public/cpp/bindings/associated_remote.h"
-#include "shell/browser/native_window_views.h"
#include "shell/browser/osr/osr_render_widget_host_view.h"
#include "shell/browser/osr/osr_view_proxy.h"
#include "shell/browser/ui/autofill_popup.h"
@@ -19,7 +18,6 @@
#include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h"
#include "ui/color/color_id.h"
#include "ui/color/color_provider.h"
-#include "ui/display/display.h"
#include "ui/display/screen.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/geometry/rect.h"
diff --git a/shell/browser/ui/cocoa/electron_menu_controller.mm b/shell/browser/ui/cocoa/electron_menu_controller.mm
index 7ee1ced9e5..dc7a32ee5c 100644
--- a/shell/browser/ui/cocoa/electron_menu_controller.mm
+++ b/shell/browser/ui/cocoa/electron_menu_controller.mm
@@ -9,6 +9,7 @@
#include <utility>
#include "base/apple/foundation_util.h"
+#include "base/functional/callback.h"
#include "base/logging.h"
#include "base/strings/sys_string_conversions.h"
#include "base/strings/utf_string_conversions.h"
diff --git a/shell/browser/ui/devtools_manager_delegate.cc b/shell/browser/ui/devtools_manager_delegate.cc
index 439ac68f5b..e62729171b 100644
--- a/shell/browser/ui/devtools_manager_delegate.cc
+++ b/shell/browser/ui/devtools_manager_delegate.cc
@@ -12,7 +12,6 @@
#include "base/functional/bind.h"
#include "base/path_service.h"
#include "base/strings/string_number_conversions.h"
-#include "chrome/common/chrome_paths.h"
#include "content/public/browser/devtools_agent_host.h"
#include "content/public/browser/devtools_frontend_host.h"
#include "content/public/browser/devtools_socket_factory.h"
diff --git a/shell/browser/ui/drag_util.cc b/shell/browser/ui/drag_util.cc
index 1710cb8ea1..1cbe3f20bb 100644
--- a/shell/browser/ui/drag_util.cc
+++ b/shell/browser/ui/drag_util.cc
@@ -5,7 +5,7 @@
#include "shell/browser/ui/drag_util.h"
#include "third_party/blink/public/mojom/page/draggable_region.mojom.h"
-#include "ui/gfx/geometry/skia_conversions.h"
+#include "third_party/skia/include/core/SkRegion.h"
namespace electron {
diff --git a/shell/browser/ui/drag_util.h b/shell/browser/ui/drag_util.h
index 92385fcb27..0c7c35e7ba 100644
--- a/shell/browser/ui/drag_util.h
+++ b/shell/browser/ui/drag_util.h
@@ -10,13 +10,18 @@
#include "electron/shell/common/api/api.mojom.h"
#include "third_party/blink/public/mojom/page/draggable_region.mojom-forward.h"
-#include "third_party/skia/include/core/SkRegion.h"
-#include "ui/gfx/image/image.h"
+#include "ui/gfx/native_widget_types.h"
+
+class SkRegion;
namespace base {
class FilePath;
}
+namespace gfx {
+class Image;
+}
+
namespace electron {
void DragFileItems(const std::vector<base::FilePath>& files,
diff --git a/shell/browser/ui/drag_util_mac.mm b/shell/browser/ui/drag_util_mac.mm
index 013f868f95..d0576830ef 100644
--- a/shell/browser/ui/drag_util_mac.mm
+++ b/shell/browser/ui/drag_util_mac.mm
@@ -10,6 +10,8 @@
#include "base/apple/foundation_util.h"
#include "base/files/file_path.h"
+#include "third_party/skia/include/core/SkImageInfo.h"
+#include "ui/gfx/image/image.h"
// Contents largely copied from
// chrome/browser/download/drag_download_item_mac.mm.
diff --git a/shell/browser/ui/electron_desktop_window_tree_host_linux.cc b/shell/browser/ui/electron_desktop_window_tree_host_linux.cc
index d384f1d60c..eb0723f78a 100644
--- a/shell/browser/ui/electron_desktop_window_tree_host_linux.cc
+++ b/shell/browser/ui/electron_desktop_window_tree_host_linux.cc
@@ -13,7 +13,9 @@
#include "base/feature_list.h"
#include "base/i18n/rtl.h"
#include "shell/browser/native_window_features.h"
+#include "shell/browser/native_window_views.h"
#include "shell/browser/ui/views/client_frame_view_linux.h"
+#include "third_party/skia/include/core/SkRegion.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/skia_conversions.h"
#include "ui/linux/linux_ui.h"
@@ -21,7 +23,6 @@
#include "ui/platform_window/platform_window.h"
#include "ui/views/widget/desktop_aura/desktop_window_tree_host.h"
#include "ui/views/widget/desktop_aura/desktop_window_tree_host_linux.h"
-#include "ui/views/window/non_client_view.h"
namespace electron {
diff --git a/shell/browser/ui/electron_desktop_window_tree_host_linux.h b/shell/browser/ui/electron_desktop_window_tree_host_linux.h
index 29bc4254a4..f68b219c23 100644
--- a/shell/browser/ui/electron_desktop_window_tree_host_linux.h
+++ b/shell/browser/ui/electron_desktop_window_tree_host_linux.h
@@ -11,16 +11,17 @@
#include "base/memory/raw_ptr.h"
#include "base/scoped_observation.h"
-#include "shell/browser/native_window_views.h"
-#include "shell/browser/ui/views/client_frame_view_linux.h"
-#include "third_party/skia/include/core/SkRRect.h"
#include "ui/linux/device_scale_factor_observer.h"
+#include "ui/linux/linux_ui.h"
#include "ui/native_theme/native_theme_observer.h"
#include "ui/platform_window/platform_window.h"
#include "ui/views/widget/desktop_aura/desktop_window_tree_host_linux.h"
namespace electron {
+class ClientFrameViewLinux;
+class NativeWindowViews;
+
class ElectronDesktopWindowTreeHostLinux
: public views::DesktopWindowTreeHostLinux,
private ui::NativeThemeObserver,
diff --git a/shell/browser/ui/file_dialog_linux.cc b/shell/browser/ui/file_dialog_linux.cc
index 5efe45eb70..7910367f4a 100644
--- a/shell/browser/ui/file_dialog_linux.cc
+++ b/shell/browser/ui/file_dialog_linux.cc
@@ -2,8 +2,7 @@
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
-#include <memory>
-#include <string>
+#include <vector>
#include "base/files/file_util.h"
#include "base/functional/bind.h"
diff --git a/shell/browser/ui/gtk/menu_gtk.h b/shell/browser/ui/gtk/menu_gtk.h
index 4ea65b7b45..0ea6217b02 100644
--- a/shell/browser/ui/gtk/menu_gtk.h
+++ b/shell/browser/ui/gtk/menu_gtk.h
@@ -5,7 +5,6 @@
#ifndef ELECTRON_SHELL_BROWSER_UI_GTK_MENU_GTK_H_
#define ELECTRON_SHELL_BROWSER_UI_GTK_MENU_GTK_H_
-#include "base/functional/callback.h"
#include "base/memory/raw_ptr.h"
#include "ui/base/glib/scoped_gobject.h"
#include "ui/base/glib/scoped_gsignal.h"
diff --git a/shell/browser/ui/gtk/menu_util.cc b/shell/browser/ui/gtk/menu_util.cc
index 8eb5810009..5870a85414 100644
--- a/shell/browser/ui/gtk/menu_util.cc
+++ b/shell/browser/ui/gtk/menu_util.cc
@@ -14,7 +14,6 @@
#include "chrome/app/chrome_command_ids.h"
#include "shell/browser/ui/gtk_util.h"
#include "third_party/skia/include/core/SkBitmap.h"
-#include "third_party/skia/include/core/SkUnPreMultiply.h"
#include "ui/base/accelerators/accelerator.h"
#include "ui/base/accelerators/menu_label_accelerator_util_linux.h"
#include "ui/base/models/image_model.h"
diff --git a/shell/browser/ui/gtk/menu_util.h b/shell/browser/ui/gtk/menu_util.h
index 2b7116d268..155cb8415f 100644
--- a/shell/browser/ui/gtk/menu_util.h
+++ b/shell/browser/ui/gtk/menu_util.h
@@ -11,7 +11,10 @@
#include "base/functional/callback.h"
#include "ui/base/glib/scoped_gsignal.h"
-#include "ui/gfx/image/image.h"
+
+namespace gfx {
+class Image;
+}
namespace ui {
class MenuModel;
diff --git a/shell/browser/ui/inspectable_web_contents.cc b/shell/browser/ui/inspectable_web_contents.cc
index 2236d83910..2acff1b4c0 100644
--- a/shell/browser/ui/inspectable_web_contents.cc
+++ b/shell/browser/ui/inspectable_web_contents.cc
@@ -64,7 +64,6 @@
#include "content/public/browser/render_process_host.h"
#include "extensions/browser/extension_registry.h"
#include "extensions/common/permissions/permissions_data.h"
-#include "shell/browser/electron_browser_context.h"
#endif
namespace electron {
diff --git a/shell/browser/ui/inspectable_web_contents_delegate.h b/shell/browser/ui/inspectable_web_contents_delegate.h
index c73a7fd74f..91f2f12362 100644
--- a/shell/browser/ui/inspectable_web_contents_delegate.h
+++ b/shell/browser/ui/inspectable_web_contents_delegate.h
@@ -8,7 +8,9 @@
#include <string>
-#include "base/files/file_path.h"
+namespace base {
+class FilePath;
+}
namespace electron {
diff --git a/shell/browser/ui/message_box_gtk.cc b/shell/browser/ui/message_box_gtk.cc
index c215dfbe04..338975d6d6 100644
--- a/shell/browser/ui/message_box_gtk.cc
+++ b/shell/browser/ui/message_box_gtk.cc
@@ -7,7 +7,6 @@
#include "base/containers/contains.h"
#include "base/containers/flat_map.h"
#include "base/functional/bind.h"
-#include "base/functional/callback.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/raw_ptr_exclusion.h"
#include "base/no_destructor.h"
diff --git a/shell/browser/ui/message_box_mac.mm b/shell/browser/ui/message_box_mac.mm
index c1cce045f6..373fab1b54 100644
--- a/shell/browser/ui/message_box_mac.mm
+++ b/shell/browser/ui/message_box_mac.mm
@@ -10,7 +10,6 @@
#include "base/containers/contains.h"
#include "base/containers/flat_map.h"
-#include "base/functional/callback.h"
#include "base/mac/mac_util.h"
#include "base/no_destructor.h"
#include "base/strings/sys_string_conversions.h"
diff --git a/shell/browser/ui/run_all_unittests.cc b/shell/browser/ui/run_all_unittests.cc
index 99c78acdb6..8063e93d29 100644
--- a/shell/browser/ui/run_all_unittests.cc
+++ b/shell/browser/ui/run_all_unittests.cc
@@ -5,7 +5,6 @@
#include "base/functional/bind.h"
#include "base/test/launcher/unit_test_launcher.h"
#include "base/test/test_suite.h"
-#include "build/build_config.h"
int main(int argc, char** argv) {
base::TestSuite test_suite(argc, argv);
diff --git a/shell/browser/ui/views/autofill_popup_view.h b/shell/browser/ui/views/autofill_popup_view.h
index 5c9a5bad76..dfbe956cc1 100644
--- a/shell/browser/ui/views/autofill_popup_view.h
+++ b/shell/browser/ui/views/autofill_popup_view.h
@@ -15,7 +15,6 @@
#include "content/public/browser/render_widget_host.h"
#include "electron/buildflags/buildflags.h"
#include "shell/browser/osr/osr_view_proxy.h"
-#include "ui/accessibility/ax_node_data.h"
#include "ui/base/metadata/metadata_header_macros.h"
#include "ui/base/metadata/metadata_impl_macros.h"
#include "ui/views/drag_controller.h"
@@ -23,6 +22,10 @@
#include "ui/views/widget/widget_delegate.h"
#include "ui/views/widget/widget_observer.h"
+namespace ui {
+struct AXNodeData;
+}
+
namespace electron {
const int kPopupBorderThickness = 1;
diff --git a/shell/browser/ui/views/caption_button_placeholder_container.cc b/shell/browser/ui/views/caption_button_placeholder_container.cc
index ac77c6149a..8e1137abc4 100644
--- a/shell/browser/ui/views/caption_button_placeholder_container.cc
+++ b/shell/browser/ui/views/caption_button_placeholder_container.cc
@@ -5,9 +5,6 @@
#include "shell/browser/ui/views/caption_button_placeholder_container.h"
#include "ui/base/metadata/metadata_impl_macros.h"
-#include "ui/gfx/canvas.h"
-#include "ui/gfx/scoped_canvas.h"
-#include "ui/views/view.h"
CaptionButtonPlaceholderContainer::CaptionButtonPlaceholderContainer() {
SetPaintToLayer();
diff --git a/shell/browser/ui/views/client_frame_view_linux.h b/shell/browser/ui/views/client_frame_view_linux.h
index 552760514d..c05632de86 100644
--- a/shell/browser/ui/views/client_frame_view_linux.h
+++ b/shell/browser/ui/views/client_frame_view_linux.h
@@ -13,6 +13,7 @@
#include "base/memory/raw_ptr_exclusion.h"
#include "base/scoped_observation.h"
#include "shell/browser/ui/views/frameless_view.h"
+#include "third_party/skia/include/core/SkRRect.h"
#include "ui/base/metadata/metadata_header_macros.h"
#include "ui/base/ui_base_types.h"
#include "ui/linux/linux_ui.h"
@@ -28,6 +29,8 @@
namespace electron {
+class NativeWindowViews;
+
class ClientFrameViewLinux : public FramelessView,
private ui::NativeThemeObserver,
private ui::WindowButtonOrderObserver {
diff --git a/shell/browser/ui/views/frameless_view.cc b/shell/browser/ui/views/frameless_view.cc
index 501f032a38..159172c541 100644
--- a/shell/browser/ui/views/frameless_view.cc
+++ b/shell/browser/ui/views/frameless_view.cc
@@ -5,8 +5,6 @@
#include "shell/browser/ui/views/frameless_view.h"
#include "shell/browser/native_window_views.h"
-#include "shell/browser/ui/inspectable_web_contents_view.h"
-#include "ui/aura/window.h"
#include "ui/base/hit_test.h"
#include "ui/base/metadata/metadata_impl_macros.h"
#include "ui/views/widget/widget.h"
diff --git a/shell/browser/ui/views/menu_delegate.h b/shell/browser/ui/views/menu_delegate.h
index b7511688e8..036a124a5a 100644
--- a/shell/browser/ui/views/menu_delegate.h
+++ b/shell/browser/ui/views/menu_delegate.h
@@ -12,6 +12,10 @@
#include "shell/browser/ui/electron_menu_model.h"
#include "ui/views/controls/menu/menu_delegate.h"
+namespace gfx {
+class FontList;
+} // namespace gfx
+
namespace views {
class MenuRunner;
class Button;
diff --git a/shell/browser/ui/views/opaque_frame_view.cc b/shell/browser/ui/views/opaque_frame_view.cc
index 1dc0c4f8dc..f6b379ca6f 100644
--- a/shell/browser/ui/views/opaque_frame_view.cc
+++ b/shell/browser/ui/views/opaque_frame_view.cc
@@ -9,13 +9,12 @@
#include "chrome/grit/generated_resources.h"
#include "components/strings/grit/components_strings.h"
#include "shell/browser/native_window_views.h"
-#include "shell/browser/ui/inspectable_web_contents_view.h"
#include "shell/browser/ui/views/caption_button_placeholder_container.h"
-#include "ui/aura/window.h"
#include "ui/base/hit_test.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/metadata/metadata_impl_macros.h"
#include "ui/compositor/layer.h"
+#include "ui/gfx/font_list.h"
#include "ui/linux/linux_ui.h"
#include "ui/views/background.h"
#include "ui/views/widget/widget.h"
diff --git a/shell/browser/ui/views/opaque_frame_view.h b/shell/browser/ui/views/opaque_frame_view.h
index af5f8eb8b5..dae79d03f4 100644
--- a/shell/browser/ui/views/opaque_frame_view.h
+++ b/shell/browser/ui/views/opaque_frame_view.h
@@ -5,14 +5,12 @@
#ifndef ELECTRON_SHELL_BROWSER_UI_VIEWS_OPAQUE_FRAME_VIEW_H_
#define ELECTRON_SHELL_BROWSER_UI_VIEWS_OPAQUE_FRAME_VIEW_H_
-#include <memory>
+#include <vector>
#include "base/memory/raw_ptr.h"
#include "chrome/browser/ui/view_ids.h"
#include "shell/browser/ui/views/frameless_view.h"
#include "ui/base/metadata/metadata_header_macros.h"
-#include "ui/gfx/font_list.h"
-#include "ui/linux/nav_button_provider.h"
#include "ui/linux/window_button_order_observer.h"
#include "ui/views/controls/button/button.h"
#include "ui/views/window/caption_button_types.h"
@@ -23,6 +21,8 @@ class CaptionButtonPlaceholderContainer;
namespace electron {
+class NativeWindowViews;
+
class OpaqueFrameView : public FramelessView {
METADATA_HEADER(OpaqueFrameView, FramelessView)
diff --git a/shell/browser/ui/views/root_view.h b/shell/browser/ui/views/root_view.h
index 22d92aea19..ac93b030ec 100644
--- a/shell/browser/ui/views/root_view.h
+++ b/shell/browser/ui/views/root_view.h
@@ -9,7 +9,6 @@
#include "base/memory/raw_ref.h"
#include "shell/browser/ui/accelerator_util.h"
-#include "ui/gfx/geometry/insets.h"
#include "ui/views/view.h"
#include "ui/views/view_tracker.h"
diff --git a/shell/browser/ui/views/submenu_button.cc b/shell/browser/ui/views/submenu_button.cc
index 9ff4a96038..730cccf1de 100644
--- a/shell/browser/ui/views/submenu_button.cc
+++ b/shell/browser/ui/views/submenu_button.cc
@@ -10,6 +10,7 @@
#include "ui/gfx/color_utils.h"
#include "ui/gfx/text_utils.h"
#include "ui/views/animation/flood_fill_ink_drop_ripple.h"
+#include "ui/views/animation/ink_drop_highlight.h"
#include "ui/views/animation/ink_drop_host.h"
#include "ui/views/animation/ink_drop_impl.h"
#include "ui/views/controls/button/label_button_border.h"
diff --git a/shell/browser/ui/views/submenu_button.h b/shell/browser/ui/views/submenu_button.h
index 260c795bc6..63e4dc8de7 100644
--- a/shell/browser/ui/views/submenu_button.h
+++ b/shell/browser/ui/views/submenu_button.h
@@ -7,12 +7,14 @@
#include <string>
-#include "ui/accessibility/ax_node_data.h"
#include "ui/base/metadata/metadata_header_macros.h"
#include "ui/base/metadata/metadata_impl_macros.h"
-#include "ui/views/animation/ink_drop_highlight.h"
#include "ui/views/controls/button/menu_button.h"
+namespace ui {
+struct AXNodeData;
+}
+
namespace electron {
// Special button that used by menu bar to show submenus.
diff --git a/shell/browser/ui/views/win_caption_button.cc b/shell/browser/ui/views/win_caption_button.cc
index 6320a60c65..63b69f42e7 100644
--- a/shell/browser/ui/views/win_caption_button.cc
+++ b/shell/browser/ui/views/win_caption_button.cc
@@ -12,6 +12,7 @@
#include "base/numerics/safe_conversions.h"
#include "base/win/windows_version.h"
#include "chrome/grit/theme_resources.h"
+#include "shell/browser/native_window_views.h"
#include "shell/browser/ui/views/win_frame_view.h"
#include "shell/common/color_util.h"
#include "ui/base/metadata/metadata_impl_macros.h"
diff --git a/shell/browser/ui/views/win_caption_button_container.cc b/shell/browser/ui/views/win_caption_button_container.cc
index 7d55af42f9..d98af95380 100644
--- a/shell/browser/ui/views/win_caption_button_container.cc
+++ b/shell/browser/ui/views/win_caption_button_container.cc
@@ -10,6 +10,10 @@
#include <memory>
#include <utility>
+#include <windows.h>
+#include <winuser.h>
+
+#include "shell/browser/native_window_views.h"
#include "shell/browser/ui/views/win_caption_button.h"
#include "shell/browser/ui/views/win_frame_view.h"
#include "ui/base/l10n/l10n_util.h"
diff --git a/shell/browser/ui/views/win_frame_view.cc b/shell/browser/ui/views/win_frame_view.cc
index 56d7f9b017..75b7794462 100644
--- a/shell/browser/ui/views/win_frame_view.cc
+++ b/shell/browser/ui/views/win_frame_view.cc
@@ -12,7 +12,6 @@
#include <dwmapi.h>
#include <memory>
-#include "base/win/windows_version.h"
#include "shell/browser/native_window_views.h"
#include "shell/browser/ui/views/win_caption_button_container.h"
#include "ui/base/metadata/metadata_impl_macros.h"
diff --git a/shell/browser/ui/views/win_frame_view.h b/shell/browser/ui/views/win_frame_view.h
index 34252dfa0e..4441c26ea1 100644
--- a/shell/browser/ui/views/win_frame_view.h
+++ b/shell/browser/ui/views/win_frame_view.h
@@ -10,7 +10,6 @@
#ifndef ELECTRON_SHELL_BROWSER_UI_VIEWS_WIN_FRAME_VIEW_H_
#define ELECTRON_SHELL_BROWSER_UI_VIEWS_WIN_FRAME_VIEW_H_
-#include "shell/browser/native_window_views.h"
#include "shell/browser/ui/views/frameless_view.h"
#include "shell/browser/ui/views/win_caption_button.h"
#include "shell/browser/ui/views/win_caption_button_container.h"
@@ -18,6 +17,8 @@
namespace electron {
+class NativeWindowViews;
+
class WinFrameView : public FramelessView {
METADATA_HEADER(WinFrameView, FramelessView)
diff --git a/shell/browser/ui/views/win_icon_painter.cc b/shell/browser/ui/views/win_icon_painter.cc
index d50c0f1396..798e02d04b 100644
--- a/shell/browser/ui/views/win_icon_painter.cc
+++ b/shell/browser/ui/views/win_icon_painter.cc
@@ -8,10 +8,7 @@
#include "cc/paint/paint_flags.h"
#include "third_party/skia/include/core/SkPath.h"
#include "ui/gfx/canvas.h"
-#include "ui/gfx/geometry/rect_conversions.h"
#include "ui/gfx/geometry/rrect_f.h"
-#include "ui/gfx/geometry/skia_conversions.h"
-#include "ui/gfx/scoped_canvas.h"
namespace {
diff --git a/shell/browser/ui/webui/accessibility_ui.cc b/shell/browser/ui/webui/accessibility_ui.cc
index fcf9a7fea6..f21d50ee13 100644
--- a/shell/browser/ui/webui/accessibility_ui.cc
+++ b/shell/browser/ui/webui/accessibility_ui.cc
@@ -5,7 +5,6 @@
#include "shell/browser/ui/webui/accessibility_ui.h"
#include <memory>
-#include <optional>
#include <string>
#include <utility>
#include <vector>
@@ -17,7 +16,6 @@
#include "base/strings/string_split.h"
#include "base/strings/utf_string_conversions.h"
#include "base/values.h"
-#include "build/build_config.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/webui_url_constants.h"
#include "chrome/grit/accessibility_resources.h" // nogncheck
diff --git a/shell/browser/ui/win/electron_desktop_native_widget_aura.cc b/shell/browser/ui/win/electron_desktop_native_widget_aura.cc
index fef641a50a..044d0941f1 100644
--- a/shell/browser/ui/win/electron_desktop_native_widget_aura.cc
+++ b/shell/browser/ui/win/electron_desktop_native_widget_aura.cc
@@ -6,6 +6,7 @@
#include <utility>
+#include "shell/browser/native_window_views.h"
#include "shell/browser/ui/win/electron_desktop_window_tree_host_win.h"
#include "ui/views/corewm/tooltip_controller.h"
#include "ui/wm/public/tooltip_client.h"
diff --git a/shell/browser/ui/win/electron_desktop_native_widget_aura.h b/shell/browser/ui/win/electron_desktop_native_widget_aura.h
index 2279a26d40..b1424990ba 100644
--- a/shell/browser/ui/win/electron_desktop_native_widget_aura.h
+++ b/shell/browser/ui/win/electron_desktop_native_widget_aura.h
@@ -5,7 +5,6 @@
#ifndef ELECTRON_SHELL_BROWSER_UI_WIN_ELECTRON_DESKTOP_NATIVE_WIDGET_AURA_H_
#define ELECTRON_SHELL_BROWSER_UI_WIN_ELECTRON_DESKTOP_NATIVE_WIDGET_AURA_H_
-#include "shell/browser/native_window_views.h"
#include "ui/views/widget/desktop_aura/desktop_native_widget_aura.h"
namespace views {
@@ -14,6 +13,8 @@ class DesktopWindowTreeHost;
namespace electron {
+class NativeWindowViews;
+
class ElectronDesktopNativeWidgetAura : public views::DesktopNativeWidgetAura {
public:
explicit ElectronDesktopNativeWidgetAura(
diff --git a/shell/browser/ui/win/electron_desktop_window_tree_host_win.cc b/shell/browser/ui/win/electron_desktop_window_tree_host_win.cc
index 9ec2588c70..48d6894d90 100644
--- a/shell/browser/ui/win/electron_desktop_window_tree_host_win.cc
+++ b/shell/browser/ui/win/electron_desktop_window_tree_host_win.cc
@@ -4,14 +4,12 @@
#include "shell/browser/ui/win/electron_desktop_window_tree_host_win.h"
-#include <optional>
-
#include "base/win/windows_version.h"
#include "electron/buildflags/buildflags.h"
+#include "shell/browser/native_window_views.h"
#include "shell/browser/ui/views/win_frame_view.h"
#include "shell/browser/win/dark_mode.h"
#include "ui/base/win/hwnd_metrics.h"
-#include "ui/base/win/shell.h"
namespace electron {
diff --git a/shell/browser/ui/win/electron_desktop_window_tree_host_win.h b/shell/browser/ui/win/electron_desktop_window_tree_host_win.h
index 9c3fcdad9b..d654431b66 100644
--- a/shell/browser/ui/win/electron_desktop_window_tree_host_win.h
+++ b/shell/browser/ui/win/electron_desktop_window_tree_host_win.h
@@ -9,11 +9,12 @@
#include <optional>
-#include "shell/browser/native_window_views.h"
#include "ui/views/widget/desktop_aura/desktop_window_tree_host_win.h"
namespace electron {
+class NativeWindowViews;
+
class ElectronDesktopWindowTreeHostWin : public views::DesktopWindowTreeHostWin,
public ::ui::NativeThemeObserver {
public:
diff --git a/shell/browser/ui/win/notify_icon.cc b/shell/browser/ui/win/notify_icon.cc
index 1f06d34817..6666ea4447 100644
--- a/shell/browser/ui/win/notify_icon.cc
+++ b/shell/browser/ui/win/notify_icon.cc
@@ -9,14 +9,11 @@
#include "base/logging.h"
#include "base/strings/string_util_win.h"
#include "base/strings/utf_string_conversions.h"
-#include "base/win/windows_version.h"
#include "shell/browser/ui/win/notify_icon_host.h"
-#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/display/screen.h"
#include "ui/display/win/screen_win.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/geometry/rect.h"
-#include "ui/gfx/image/image.h"
#include "ui/views/controls/menu/menu_runner.h"
namespace {
diff --git a/shell/browser/ui/win/taskbar_host.h b/shell/browser/ui/win/taskbar_host.h
index 0134abfb07..9db58388d1 100644
--- a/shell/browser/ui/win/taskbar_host.h
+++ b/shell/browser/ui/win/taskbar_host.h
@@ -12,7 +12,6 @@
#include <string>
#include <vector>
-#include "base/functional/callback.h"
#include "shell/browser/native_window.h"
#include "ui/gfx/image/image.h"
diff --git a/shell/browser/usb/electron_usb_delegate.cc b/shell/browser/usb/electron_usb_delegate.cc
index 4e15d1954a..22444f2b10 100644
--- a/shell/browser/usb/electron_usb_delegate.cc
+++ b/shell/browser/usb/electron_usb_delegate.cc
@@ -15,6 +15,7 @@
#include "content/public/browser/web_contents.h"
#include "electron/buildflags/buildflags.h"
#include "services/device/public/mojom/usb_enumeration_options.mojom.h"
+#include "shell/browser/electron_browser_context.h"
#include "shell/browser/electron_permission_manager.h"
#include "shell/browser/usb/usb_chooser_context.h"
#include "shell/browser/usb/usb_chooser_context_factory.h"
diff --git a/shell/browser/usb/usb_chooser_context.cc b/shell/browser/usb/usb_chooser_context.cc
index 40577f067f..0a18e593c3 100644
--- a/shell/browser/usb/usb_chooser_context.cc
+++ b/shell/browser/usb/usb_chooser_context.cc
@@ -12,12 +12,12 @@
#include "base/strings/string_piece.h"
#include "base/task/sequenced_task_runner.h"
#include "base/values.h"
-#include "build/build_config.h"
#include "components/content_settings/core/common/content_settings.h"
#include "content/public/browser/device_service.h"
#include "services/device/public/cpp/usb/usb_ids.h"
#include "services/device/public/mojom/usb_device.mojom.h"
#include "shell/browser/api/electron_api_session.h"
+#include "shell/browser/electron_browser_context.h"
#include "shell/browser/electron_permission_manager.h"
#include "shell/browser/web_contents_permission_helper.h"
#include "shell/common/electron_constants.h"
diff --git a/shell/browser/usb/usb_chooser_context.h b/shell/browser/usb/usb_chooser_context.h
index a9c1d07a5c..c4dd074f9a 100644
--- a/shell/browser/usb/usb_chooser_context.h
+++ b/shell/browser/usb/usb_chooser_context.h
@@ -14,7 +14,6 @@
#include "base/memory/raw_ptr.h"
#include "base/observer_list.h"
#include "base/values.h"
-#include "build/build_config.h"
#include "components/keyed_service/core/keyed_service.h"
#include "mojo/public/cpp/bindings/associated_receiver.h"
#include "mojo/public/cpp/bindings/pending_receiver.h"
@@ -22,11 +21,12 @@
#include "mojo/public/cpp/bindings/remote.h"
#include "services/device/public/mojom/usb_manager.mojom.h"
#include "services/device/public/mojom/usb_manager_client.mojom.h"
-#include "shell/browser/electron_browser_context.h"
#include "url/origin.h"
namespace electron {
+class ElectronBrowserContext;
+
class UsbChooserContext : public KeyedService,
public device::mojom::UsbDeviceManagerClient {
public:
diff --git a/shell/browser/usb/usb_chooser_controller.cc b/shell/browser/usb/usb_chooser_controller.cc
index d4366062e9..5f92eefcb7 100644
--- a/shell/browser/usb/usb_chooser_controller.cc
+++ b/shell/browser/usb/usb_chooser_controller.cc
@@ -9,13 +9,13 @@
#include "base/functional/bind.h"
#include "base/ranges/algorithm.h"
-#include "build/build_config.h"
#include "components/strings/grit/components_strings.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/web_contents.h"
#include "gin/data_object_builder.h"
#include "services/device/public/cpp/usb/usb_utils.h"
#include "services/device/public/mojom/usb_enumeration_options.mojom.h"
+#include "shell/browser/api/electron_api_session.h"
#include "shell/browser/javascript_environment.h"
#include "shell/browser/usb/usb_chooser_context_factory.h"
#include "shell/common/gin_converters/callback_converter.h"
diff --git a/shell/browser/usb/usb_chooser_controller.h b/shell/browser/usb/usb_chooser_controller.h
index c04b3e266a..7abbddaff0 100644
--- a/shell/browser/usb/usb_chooser_controller.h
+++ b/shell/browser/usb/usb_chooser_controller.h
@@ -12,7 +12,6 @@
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_observer.h"
#include "services/device/public/mojom/usb_device.mojom.h"
-#include "shell/browser/api/electron_api_session.h"
#include "shell/browser/usb/electron_usb_delegate.h"
#include "shell/browser/usb/usb_chooser_context.h"
#include "third_party/blink/public/mojom/usb/web_usb_service.mojom.h"
@@ -22,7 +21,14 @@ namespace content {
class RenderFrameHost;
}
+namespace gin {
+class Arguments;
+}
+
namespace electron {
+namespace api {
+class Session;
+}
// UsbChooserController creates a chooser for WebUSB.
class UsbChooserController final : private UsbChooserContext::DeviceObserver,
diff --git a/shell/browser/web_contents_permission_helper.cc b/shell/browser/web_contents_permission_helper.cc
index f97385aaa1..40f77feed1 100644
--- a/shell/browser/web_contents_permission_helper.cc
+++ b/shell/browser/web_contents_permission_helper.cc
@@ -12,6 +12,7 @@
#include "content/public/browser/browser_context.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/web_contents_user_data.h"
+#include "shell/browser/electron_browser_context.h"
#include "shell/browser/electron_permission_manager.h"
#include "shell/browser/media/media_capture_devices_dispatcher.h"
diff --git a/shell/browser/web_contents_preferences.cc b/shell/browser/web_contents_preferences.cc
index 1704344be5..19c81d1437 100644
--- a/shell/browser/web_contents_preferences.cc
+++ b/shell/browser/web_contents_preferences.cc
@@ -14,7 +14,6 @@
#include "base/containers/fixed_flat_map.h"
#include "base/memory/ptr_util.h"
#include "cc/base/switches.h"
-#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/web_contents_user_data.h"
#include "content/public/common/content_switches.h"
diff --git a/shell/common/api/electron_api_clipboard.cc b/shell/common/api/electron_api_clipboard.cc
index af03e7e99a..7d741cb70c 100644
--- a/shell/common/api/electron_api_clipboard.cc
+++ b/shell/common/api/electron_api_clipboard.cc
@@ -14,8 +14,6 @@
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/node_includes.h"
#include "third_party/skia/include/core/SkBitmap.h"
-#include "third_party/skia/include/core/SkImageInfo.h"
-#include "third_party/skia/include/core/SkPixmap.h"
#include "ui/base/clipboard/clipboard_format_type.h"
#include "ui/base/clipboard/file_info.h"
#include "ui/base/clipboard/scoped_clipboard_writer.h"
diff --git a/shell/common/api/electron_bindings.cc b/shell/common/api/electron_bindings.cc
index 127be2e0e7..2d9d7f72ce 100644
--- a/shell/common/api/electron_bindings.cc
+++ b/shell/common/api/electron_bindings.cc
@@ -10,6 +10,7 @@
#include <vector>
#include "base/containers/contains.h"
+#include "base/files/file.h"
#include "base/process/process.h"
#include "base/process/process_handle.h"
#include "base/system/sys_info.h"
diff --git a/shell/common/electron_constants.h b/shell/common/electron_constants.h
index ed40d73b23..ad2b77aa0d 100644
--- a/shell/common/electron_constants.h
+++ b/shell/common/electron_constants.h
@@ -6,7 +6,6 @@
#define ELECTRON_SHELL_COMMON_ELECTRON_CONSTANTS_H_
#include "base/files/file_path.h"
-#include "build/build_config.h"
#include "electron/buildflags/buildflags.h"
namespace electron {
diff --git a/shell/common/language_util_win.cc b/shell/common/language_util_win.cc
index 183d70a999..127d7f2817 100644
--- a/shell/common/language_util_win.cc
+++ b/shell/common/language_util_win.cc
@@ -12,7 +12,6 @@
#include "base/win/core_winrt_util.h"
#include "base/win/i18n.h"
#include "base/win/win_util.h"
-#include "base/win/windows_version.h"
namespace electron {
diff --git a/shell/common/logging.cc b/shell/common/logging.cc
index b9d58e187b..47e0d93e2c 100644
--- a/shell/common/logging.cc
+++ b/shell/common/logging.cc
@@ -16,7 +16,6 @@
#include "base/strings/string_number_conversions.h"
#include "chrome/common/chrome_paths.h"
#include "content/public/common/content_switches.h"
-#include "shell/common/electron_paths.h"
namespace logging {
diff --git a/shell/common/node_bindings.h b/shell/common/node_bindings.h
index 93363117df..03813e793b 100644
--- a/shell/common/node_bindings.h
+++ b/shell/common/node_bindings.h
@@ -11,7 +11,6 @@
#include <type_traits>
#include <vector>
-#include "base/files/file_path.h"
#include "base/functional/callback.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/raw_ptr_exclusion.h"
diff --git a/shell/common/node_util.h b/shell/common/node_util.h
index 7044abcac2..38f9d28b2b 100644
--- a/shell/common/node_util.h
+++ b/shell/common/node_util.h
@@ -7,7 +7,6 @@
#include <vector>
-#include "build/build_config.h"
#include "v8/include/v8.h"
namespace node {
diff --git a/shell/common/platform_util_mac.mm b/shell/common/platform_util_mac.mm
index 811836dec6..49752dd4a2 100644
--- a/shell/common/platform_util_mac.mm
+++ b/shell/common/platform_util_mac.mm
@@ -16,7 +16,6 @@
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/functional/bind.h"
-#include "base/functional/callback.h"
#include "base/logging.h"
#include "base/mac/scoped_aedesc.h"
#include "base/strings/sys_string_conversions.h"
diff --git a/shell/common/platform_util_win.cc b/shell/common/platform_util_win.cc
index 7afdb35ccd..369aa3dd92 100644
--- a/shell/common/platform_util_win.cc
+++ b/shell/common/platform_util_win.cc
@@ -29,7 +29,6 @@
#include "base/win/registry.h"
#include "base/win/scoped_co_mem.h"
#include "base/win/scoped_com_initializer.h"
-#include "base/win/windows_version.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "shell/common/electron_paths.h"
diff --git a/shell/renderer/api/electron_api_spell_check_client.h b/shell/renderer/api/electron_api_spell_check_client.h
index 32ccf8014c..befd74e806 100644
--- a/shell/renderer/api/electron_api_spell_check_client.h
+++ b/shell/renderer/api/electron_api_spell_check_client.h
@@ -10,7 +10,6 @@
#include <string>
#include <vector>
-#include "base/functional/callback.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/weak_ptr.h"
#include "components/spellcheck/renderer/spellcheck_worditerator.h"
diff --git a/shell/renderer/browser_exposed_renderer_interfaces.cc b/shell/renderer/browser_exposed_renderer_interfaces.cc
index bc3ec52514..359548773c 100644
--- a/shell/renderer/browser_exposed_renderer_interfaces.cc
+++ b/shell/renderer/browser_exposed_renderer_interfaces.cc
@@ -8,7 +8,6 @@
#include "base/functional/bind.h"
#include "base/task/sequenced_task_runner.h"
-#include "build/build_config.h"
#include "electron/buildflags/buildflags.h"
#include "mojo/public/cpp/bindings/binder_map.h"
#include "shell/renderer/renderer_client_base.h"
diff --git a/shell/renderer/extensions/electron_extensions_renderer_api_provider.h b/shell/renderer/extensions/electron_extensions_renderer_api_provider.h
index f4b4e4e2e6..b4af558359 100644
--- a/shell/renderer/extensions/electron_extensions_renderer_api_provider.h
+++ b/shell/renderer/extensions/electron_extensions_renderer_api_provider.h
@@ -5,8 +5,6 @@
#ifndef ELECTRON_SHELL_RENDERER_EXTENSIONS_ELECTRON_EXTENSIONS_RENDERER_API_PROVIDER_H_
#define ELECTRON_SHELL_RENDERER_EXTENSIONS_ELECTRON_EXTENSIONS_RENDERER_API_PROVIDER_H_
-#include <memory>
-
#include "extensions/renderer/extensions_renderer_api_provider.h"
namespace electron {
diff --git a/shell/renderer/pepper_helper.h b/shell/renderer/pepper_helper.h
index 98c41b5a67..e8d01ffbb6 100644
--- a/shell/renderer/pepper_helper.h
+++ b/shell/renderer/pepper_helper.h
@@ -5,7 +5,6 @@
#ifndef ELECTRON_SHELL_RENDERER_PEPPER_HELPER_H_
#define ELECTRON_SHELL_RENDERER_PEPPER_HELPER_H_
-#include "base/component_export.h"
#include "content/public/renderer/render_frame_observer.h"
// This class listens for Pepper creation events from the RenderFrame and
diff --git a/shell/renderer/renderer_client_base.cc b/shell/renderer/renderer_client_base.cc
index c958c3fa22..4e84c276f2 100644
--- a/shell/renderer/renderer_client_base.cc
+++ b/shell/renderer/renderer_client_base.cc
@@ -20,7 +20,6 @@
#include "content/public/renderer/render_thread.h"
#include "electron/buildflags/buildflags.h"
#include "electron/fuses.h"
-#include "media/base/key_systems_support_registration.h"
#include "printing/buildflags/buildflags.h"
#include "shell/browser/api/electron_api_protocol.h"
#include "shell/common/api/electron_api_native_image.h"
diff --git a/shell/renderer/renderer_client_base.h b/shell/renderer/renderer_client_base.h
index 39753ddee5..1d5deeec3f 100644
--- a/shell/renderer/renderer_client_base.h
+++ b/shell/renderer/renderer_client_base.h
@@ -10,8 +10,6 @@
#include "content/public/renderer/content_renderer_client.h"
#include "electron/buildflags/buildflags.h"
-#include "media/base/key_systems_support_registration.h"
-#include "printing/buildflags/buildflags.h"
// In SHARED_INTERMEDIATE_DIR.
#include "widevine_cdm_version.h" // NOLINT(build/include_directory)
diff --git a/shell/services/node/parent_port.cc b/shell/services/node/parent_port.cc
index 13d9433f30..e62b2076b2 100644
--- a/shell/services/node/parent_port.cc
+++ b/shell/services/node/parent_port.cc
@@ -9,7 +9,9 @@
#include "base/no_destructor.h"
#include "gin/data_object_builder.h"
#include "gin/handle.h"
+#include "gin/object_template_builder.h"
#include "shell/browser/api/message_port.h"
+#include "shell/browser/javascript_environment.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/gin_helper/event_emitter_caller.h"
#include "shell/common/node_includes.h"
diff --git a/shell/services/node/parent_port.h b/shell/services/node/parent_port.h
index bb56886573..082d47a2ef 100644
--- a/shell/services/node/parent_port.h
+++ b/shell/services/node/parent_port.h
@@ -10,7 +10,7 @@
#include "gin/wrappable.h"
#include "mojo/public/cpp/bindings/connector.h"
#include "mojo/public/cpp/bindings/message.h"
-#include "shell/browser/event_emitter_mixin.h"
+#include "third_party/blink/public/common/messaging/message_port_descriptor.h"
namespace v8 {
template <class T>
|
chore
|
beafbfd51115ed6cc2a800461ffb91aea8603e7e
|
Shelley Vohr
|
2024-03-29 13:34:56
|
build: combine `ImportModuleDynamically` patches (#41712)
build: combine ImportModuleDynamically patches
|
diff --git a/patches/node/.patches b/patches/node/.patches
index 09ea299e4b..fd8ff52255 100644
--- a/patches/node/.patches
+++ b/patches/node/.patches
@@ -33,7 +33,6 @@ fix_assert_module_in_the_renderer_process.patch
fix_add_trusted_space_and_trusted_lo_space_to_the_v8_heap.patch
win_process_avoid_assert_after_spawning_store_app_4152.patch
chore_remove_use_of_deprecated_kmaxlength.patch
-fix_missing_include_for_node_extern.patch
feat_optionally_prevent_calling_v8_enablewebassemblytraphandler.patch
build_only_create_cppgc_heap_on_non-32_bit_platforms.patch
fix_-wshadow_error_in_uvwasi_c.patch
diff --git a/patches/node/chore_expose_importmoduledynamically_and.patch b/patches/node/chore_expose_importmoduledynamically_and.patch
index ae6a48547e..2599c58985 100644
--- a/patches/node/chore_expose_importmoduledynamically_and.patch
+++ b/patches/node/chore_expose_importmoduledynamically_and.patch
@@ -87,10 +87,18 @@ index 895ff3a5948add3513700ecc2f32fce4c2fbe4eb..3182a5e4aad2ba0be2b6769edb696b81
MaybeLocal<Value> ModuleWrap::SyntheticModuleEvaluationStepsCallback(
diff --git a/src/module_wrap.h b/src/module_wrap.h
-index e17048357feca2419087621ed280de30882a90bc..061117dc3182d63e35d7e99ffd95801f96356322 100644
+index e17048357feca2419087621ed280de30882a90bc..63682be31ce00a3bf7b9be909cac4b7f9ec02a8e 100644
--- a/src/module_wrap.h
+++ b/src/module_wrap.h
-@@ -31,7 +31,14 @@ enum HostDefinedOptions : int {
+@@ -7,6 +7,7 @@
+ #include <string>
+ #include <vector>
+ #include "base_object.h"
++#include "node.h"
+
+ namespace node {
+
+@@ -31,7 +32,14 @@ enum HostDefinedOptions : int {
kLength = 9,
};
@@ -106,7 +114,7 @@ index e17048357feca2419087621ed280de30882a90bc..061117dc3182d63e35d7e99ffd95801f
public:
enum InternalFields {
kModuleSlot = BaseObject::kInternalFieldCount,
-@@ -68,6 +75,8 @@ class ModuleWrap : public BaseObject {
+@@ -68,6 +76,8 @@ class ModuleWrap : public BaseObject {
return true;
}
@@ -115,7 +123,7 @@ index e17048357feca2419087621ed280de30882a90bc..061117dc3182d63e35d7e99ffd95801f
private:
ModuleWrap(Realm* realm,
v8::Local<v8::Object> object,
-@@ -102,7 +111,6 @@ class ModuleWrap : public BaseObject {
+@@ -102,7 +112,6 @@ class ModuleWrap : public BaseObject {
v8::Local<v8::String> specifier,
v8::Local<v8::FixedArray> import_attributes,
v8::Local<v8::Module> referrer);
diff --git a/patches/node/fix_missing_include_for_node_extern.patch b/patches/node/fix_missing_include_for_node_extern.patch
deleted file mode 100644
index 3e727b102b..0000000000
--- a/patches/node/fix_missing_include_for_node_extern.patch
+++ /dev/null
@@ -1,26 +0,0 @@
-From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
-From: Shelley Vohr <[email protected]>
-Date: Wed, 15 Nov 2023 12:25:39 +0100
-Subject: fix: missing include for NODE_EXTERN
-
-At some point it seems that node.h was removed from the include chain,
-causing the following error:
-
-../../third_party/electron_node/src/module_wrap.h:33:1: error: unknown type name 'NODE_EXTERN'
- 33 | NODE_EXTERN v8::MaybeLocal<v8::Promise> ImportModuleDynamically(
- | ^
-
-This should be upstreamed.
-
-diff --git a/src/module_wrap.h b/src/module_wrap.h
-index 061117dc3182d63e35d7e99ffd95801f96356322..63682be31ce00a3bf7b9be909cac4b7f9ec02a8e 100644
---- a/src/module_wrap.h
-+++ b/src/module_wrap.h
-@@ -7,6 +7,7 @@
- #include <string>
- #include <vector>
- #include "base_object.h"
-+#include "node.h"
-
- namespace node {
-
|
build
|
01b4e3b521a46df1c9e810da2e6244767fd6288e
|
David Sanders
|
2023-01-31 12:30:40
|
ci: update actions/stale to v6.0.1 (#37079)
|
diff --git a/.github/workflows/stale.yml b/.github/workflows/stale.yml
index 5720c6f249..df9af0dfee 100644
--- a/.github/workflows/stale.yml
+++ b/.github/workflows/stale.yml
@@ -11,7 +11,7 @@ jobs:
stale:
runs-on: ubuntu-latest
steps:
- - uses: actions/stale@3de2653986ebd134983c79fe2be5d45cc3d9f4e1
+ - uses: actions/stale@5ebf00ea0e4c1561e9b43a292ed34424fb1d4578 # tag: v6.0.1
with:
days-before-stale: 90
days-before-close: 30
@@ -28,7 +28,7 @@ jobs:
if: ${{ always() }}
needs: stale
steps:
- - uses: actions/stale@3de2653986ebd134983c79fe2be5d45cc3d9f4e1
+ - uses: actions/stale@5ebf00ea0e4c1561e9b43a292ed34424fb1d4578 # tag: v6.0.1
with:
days-before-stale: -1
days-before-close: 10
|
ci
|
a00a25376d339ba78c4a1efbae2de05fd534332e
|
Shelley Vohr
|
2023-06-21 21:20:54
|
fix: crash calling `BrowserWindow.removeBrowserView()` with destroyed `webContents` (#38842)
fix: crash calling removeBrowserView() with destroyed webContents
https://github.com/electron/electron/issues/37642
|
diff --git a/shell/browser/api/electron_api_browser_view.cc b/shell/browser/api/electron_api_browser_view.cc
index cc7a1d717e..2049664c6a 100644
--- a/shell/browser/api/electron_api_browser_view.cc
+++ b/shell/browser/api/electron_api_browser_view.cc
@@ -131,6 +131,10 @@ void BrowserView::WebContentsDestroyed() {
Unpin();
}
+void BrowserView::OnCloseContents() {
+ api_web_contents_ = nullptr;
+}
+
// static
gin::Handle<BrowserView> BrowserView::New(gin_helper::ErrorThrower thrower,
gin::Arguments* args) {
diff --git a/shell/browser/api/electron_api_browser_view.h b/shell/browser/api/electron_api_browser_view.h
index 409b5dda0c..caf31bae15 100644
--- a/shell/browser/api/electron_api_browser_view.h
+++ b/shell/browser/api/electron_api_browser_view.h
@@ -71,6 +71,9 @@ class BrowserView : public gin::Wrappable<BrowserView>,
// content::WebContentsObserver:
void WebContentsDestroyed() override;
+ // ExtendedWebContentsObserver:
+ void OnCloseContents() override;
+
private:
void SetAutoResize(AutoResizeFlags flags);
void SetBounds(const gfx::Rect& bounds);
diff --git a/spec/api-browser-view-spec.ts b/spec/api-browser-view-spec.ts
index 69084034d2..80bb56478d 100644
--- a/spec/api-browser-view-spec.ts
+++ b/spec/api-browser-view-spec.ts
@@ -257,6 +257,20 @@ describe('BrowserView module', () => {
w.removeBrowserView(view);
}).to.not.throw();
});
+
+ it('can be called on a BrowserView with a destroyed webContents', (done) => {
+ view = new BrowserView();
+ w.addBrowserView(view);
+
+ view.webContents.on('destroyed', () => {
+ w.removeBrowserView(view);
+ done();
+ });
+
+ view.webContents.loadURL('data:text/html,hello there').then(() => {
+ view.webContents.close();
+ });
+ });
});
describe('BrowserWindow.getBrowserViews()', () => {
|
fix
|
7858921a1f318a4bffe9a570addfde2360a701e8
|
David Sanders
|
2023-08-30 18:10:32
|
docs: fix return typing of ses.getExtension (#39697)
|
diff --git a/docs/api/session.md b/docs/api/session.md
index a6bfe2340d..4a77828fac 100644
--- a/docs/api/session.md
+++ b/docs/api/session.md
@@ -1491,7 +1491,7 @@ is emitted.
* `extensionId` string - ID of extension to query
-Returns `Extension` | `null` - The loaded extension with the given ID.
+Returns `Extension | null` - The loaded extension with the given ID.
**Note:** This API cannot be called before the `ready` event of the `app` module
is emitted.
|
docs
|
5fd7a43970c2bdfa1017a4b23098aec3dafbf513
|
Milan Burda
|
2022-12-14 22:07:38
|
test: replace (webContents as any).destroy() with webContents.destroy() (#36653)
Co-authored-by: Milan Burda <[email protected]>
Co-authored-by: John Kleinschmidt <[email protected]>
|
diff --git a/spec/api-browser-view-spec.ts b/spec/api-browser-view-spec.ts
index 89ee7af47d..a87d2dff7b 100644
--- a/spec/api-browser-view-spec.ts
+++ b/spec/api-browser-view-spec.ts
@@ -32,7 +32,7 @@ describe('BrowserView module', () => {
if (view && view.webContents) {
const p = emittedOnce(view.webContents, 'destroyed');
- (view.webContents as any).destroy();
+ view.webContents.destroy();
view = null as any;
await p;
}
@@ -193,11 +193,11 @@ describe('BrowserView module', () => {
describe('BrowserWindow.addBrowserView()', () => {
it('does not throw for valid args', () => {
const view1 = new BrowserView();
- defer(() => (view1.webContents as any).destroy());
+ defer(() => view1.webContents.destroy());
w.addBrowserView(view1);
defer(() => w.removeBrowserView(view1));
const view2 = new BrowserView();
- defer(() => (view2.webContents as any).destroy());
+ defer(() => view2.webContents.destroy());
w.addBrowserView(view2);
defer(() => w.removeBrowserView(view2));
});
@@ -212,7 +212,7 @@ describe('BrowserView module', () => {
it('does not crash if the BrowserView webContents are destroyed prior to window addition', () => {
expect(() => {
const view1 = new BrowserView();
- (view1.webContents as any).destroy();
+ view1.webContents.destroy();
w.addBrowserView(view1);
}).to.not.throw();
});
@@ -262,11 +262,11 @@ describe('BrowserView module', () => {
describe('BrowserWindow.getBrowserViews()', () => {
it('returns same views as was added', () => {
const view1 = new BrowserView();
- defer(() => (view1.webContents as any).destroy());
+ defer(() => view1.webContents.destroy());
w.addBrowserView(view1);
defer(() => w.removeBrowserView(view1));
const view2 = new BrowserView();
- defer(() => (view2.webContents as any).destroy());
+ defer(() => view2.webContents.destroy());
w.addBrowserView(view2);
defer(() => w.removeBrowserView(view2));
diff --git a/spec/api-browser-window-spec.ts b/spec/api-browser-window-spec.ts
index 9b6eb24f75..82b1614523 100644
--- a/spec/api-browser-window-spec.ts
+++ b/spec/api-browser-window-spec.ts
@@ -2206,7 +2206,7 @@ describe('BrowserWindow module', () => {
w.setBrowserView(bv);
defer(() => {
w.removeBrowserView(bv);
- (bv.webContents as any).destroy();
+ bv.webContents.destroy();
});
await bv.webContents.loadURL('about:blank');
expect(BrowserWindow.fromWebContents(bv.webContents)!.id).to.equal(w.id);
@@ -2254,7 +2254,7 @@ describe('BrowserWindow module', () => {
w.setBrowserView(bv);
defer(() => {
w.removeBrowserView(bv);
- (bv.webContents as any).destroy();
+ bv.webContents.destroy();
});
expect(BrowserWindow.fromBrowserView(bv)!.id).to.equal(w.id);
});
@@ -2268,8 +2268,8 @@ describe('BrowserWindow module', () => {
defer(() => {
w.removeBrowserView(bv1);
w.removeBrowserView(bv2);
- (bv1.webContents as any).destroy();
- (bv2.webContents as any).destroy();
+ bv1.webContents.destroy();
+ bv2.webContents.destroy();
});
expect(BrowserWindow.fromBrowserView(bv1)!.id).to.equal(w.id);
expect(BrowserWindow.fromBrowserView(bv2)!.id).to.equal(w.id);
@@ -2278,7 +2278,7 @@ describe('BrowserWindow module', () => {
it('returns undefined if not attached', () => {
const bv = new BrowserView();
defer(() => {
- (bv.webContents as any).destroy();
+ bv.webContents.destroy();
});
expect(BrowserWindow.fromBrowserView(bv)).to.be.null('BrowserWindow associated with bv');
});
diff --git a/spec/api-ipc-renderer-spec.ts b/spec/api-ipc-renderer-spec.ts
index 16f2d15a8a..861dbe6e44 100644
--- a/spec/api-ipc-renderer-spec.ts
+++ b/spec/api-ipc-renderer-spec.ts
@@ -144,7 +144,7 @@ describe('ipcRenderer module', () => {
});
after(() => {
- (contents as any).destroy();
+ contents.destroy();
contents = null as unknown as WebContents;
});
diff --git a/spec/api-protocol-spec.ts b/spec/api-protocol-spec.ts
index f39dff7a5c..d97a61961a 100644
--- a/spec/api-protocol-spec.ts
+++ b/spec/api-protocol-spec.ts
@@ -74,7 +74,7 @@ describe('protocol module', () => {
let contents: WebContents = null as unknown as WebContents;
// NB. sandbox: true is used because it makes navigations much (~8x) faster.
before(() => { contents = (webContents as any).create({ sandbox: true }); });
- after(() => (contents as any).destroy());
+ after(() => contents.destroy());
async function ajax (url: string, options = {}) {
// Note that we need to do navigation every time after a protocol is
@@ -964,7 +964,7 @@ describe('protocol module', () => {
// This is called in a timeout to avoid a crash that happens when
// calling destroy() in a microtask.
setTimeout(() => {
- (newContents as any).destroy();
+ newContents.destroy();
});
}
}
@@ -1062,7 +1062,7 @@ describe('protocol module', () => {
// This is called in a timeout to avoid a crash that happens when
// calling destroy() in a microtask.
setTimeout(() => {
- (newContents as any).destroy();
+ newContents.destroy();
});
}
}
diff --git a/spec/api-service-workers-spec.ts b/spec/api-service-workers-spec.ts
index 5f7f81f918..9df6714cfa 100644
--- a/spec/api-service-workers-spec.ts
+++ b/spec/api-service-workers-spec.ts
@@ -43,7 +43,7 @@ describe('session.serviceWorkers', () => {
});
afterEach(async () => {
- (w as any).destroy();
+ w.destroy();
server.close();
await ses.clearStorageData();
});
diff --git a/spec/api-web-contents-spec.ts b/spec/api-web-contents-spec.ts
index f92ff5abe7..66626be965 100644
--- a/spec/api-web-contents-spec.ts
+++ b/spec/api-web-contents-spec.ts
@@ -1552,7 +1552,7 @@ describe('webContents module', () => {
const contents = (webContents as any).create() as WebContents;
const originalEmit = contents.emit.bind(contents);
contents.emit = (...args) => { return originalEmit(...args); };
- contents.once(e.name as any, () => (contents as any).destroy());
+ contents.once(e.name as any, () => contents.destroy());
const destroyed = emittedOnce(contents, 'destroyed');
contents.loadURL(serverUrl + e.url);
await destroyed;
diff --git a/spec/api-web-request-spec.ts b/spec/api-web-request-spec.ts
index 22e58e5fe8..734740b271 100644
--- a/spec/api-web-request-spec.ts
+++ b/spec/api-web-request-spec.ts
@@ -55,7 +55,7 @@ describe('webRequest module', () => {
contents = (webContents as any).create({ sandbox: true });
await contents.loadFile(path.join(fixturesPath, 'pages', 'fetch.html'));
});
- after(() => (contents as any).destroy());
+ after(() => contents.destroy());
async function ajax (url: string, options = {}) {
return contents.executeJavaScript(`ajax("${url}", ${JSON.stringify(options)})`);
diff --git a/spec/chromium-spec.ts b/spec/chromium-spec.ts
index ec5224d3b0..703f7bf250 100644
--- a/spec/chromium-spec.ts
+++ b/spec/chromium-spec.ts
@@ -1479,7 +1479,7 @@ describe('chromium features', () => {
});
afterEach(() => {
- (contents as any).destroy();
+ contents.destroy();
contents = null as any;
});
@@ -1595,7 +1595,7 @@ describe('chromium features', () => {
afterEach(async () => {
if (contents) {
- (contents as any).destroy();
+ contents.destroy();
contents = null as any;
}
await closeAllWindows();
diff --git a/spec/node-spec.ts b/spec/node-spec.ts
index d682d12752..1eced8ab1d 100644
--- a/spec/node-spec.ts
+++ b/spec/node-spec.ts
@@ -790,7 +790,7 @@ describe('node feature', () => {
}
})`))
.then(() => {
- (w as any).destroy();
+ w.destroy();
child.send('plz-quit');
done();
});
|
test
|
efde7a140bc48e0e3e08404f41f6179c26858ce4
|
John Kleinschmidt
|
2023-03-07 12:40:40
|
fix: WebUSB on ARM64 macs (#37441)
|
diff --git a/patches/chromium/.patches b/patches/chromium/.patches
index 34fe0d8325..150dacaf66 100644
--- a/patches/chromium/.patches
+++ b/patches/chromium/.patches
@@ -126,3 +126,4 @@ chore_patch_out_partition_attribute_dcheck_for_webviews.patch
expose_v8initializer_codegenerationcheckcallbackinmainthread.patch
chore_patch_out_profile_methods_in_profile_selections_cc.patch
fix_x11_window_restore_minimized_maximized_window.patch
+chore_defer_usb_service_getdevices_request_until_usb_service_is.patch
diff --git a/patches/chromium/chore_defer_usb_service_getdevices_request_until_usb_service_is.patch b/patches/chromium/chore_defer_usb_service_getdevices_request_until_usb_service_is.patch
new file mode 100644
index 0000000000..616a1e956d
--- /dev/null
+++ b/patches/chromium/chore_defer_usb_service_getdevices_request_until_usb_service_is.patch
@@ -0,0 +1,23 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: John Kleinschmidt <[email protected]>
+Date: Thu, 2 Mar 2023 15:26:46 -0500
+Subject: chore: defer USB service GetDevices request until USB service is
+ ready.
+
+On macOS we need to wait until the USB service is ready before the list of
+devices is available. This should no longer be necessary if/when
+https://crbug.com/1096743 is completed.
+
+diff --git a/services/device/usb/usb_service_impl.cc b/services/device/usb/usb_service_impl.cc
+index 99456d1baa098e8a48b4a31cc8f5661586f7fc82..11d98208c85093598813897a144812c76bc67bea 100644
+--- a/services/device/usb/usb_service_impl.cc
++++ b/services/device/usb/usb_service_impl.cc
+@@ -198,7 +198,7 @@ void UsbServiceImpl::GetDevices(GetDevicesCallback callback) {
+ return;
+ }
+
+- if (enumeration_in_progress_) {
++ if (enumeration_in_progress_ || !enumeration_ready_) {
+ pending_enumeration_callbacks_.push_back(std::move(callback));
+ return;
+ }
diff --git a/shell/browser/feature_list.cc b/shell/browser/feature_list.cc
index 0cf9374876..ea4c74c52c 100644
--- a/shell/browser/feature_list.cc
+++ b/shell/browser/feature_list.cc
@@ -36,11 +36,6 @@ void InitializeFeatureList() {
disable_features +=
std::string(",") + features::kSpareRendererForSitePerProcess.name;
-#if BUILDFLAG(IS_MAC)
- // Needed for WebUSB implementation
- enable_features += std::string(",") + device::kNewUsbBackend.name;
-#endif
-
#if !BUILDFLAG(ENABLE_PICTURE_IN_PICTURE)
disable_features += std::string(",") + media::kPictureInPicture.name;
#endif
|
fix
|
56e45baeb8205da41f3a1a06582cf9958fc9cff2
|
github-actions[bot]
|
2023-09-21 09:49:04
|
build: update appveyor image to latest version - e-119.0.6019.2 (#39924)
build: update appveyor image to latest version
Co-authored-by: jkleinsc <[email protected]>
|
diff --git a/appveyor-woa.yml b/appveyor-woa.yml
index 582569c48b..a3d6470da4 100644
--- a/appveyor-woa.yml
+++ b/appveyor-woa.yml
@@ -29,7 +29,7 @@
version: 1.0.{build}
build_cloud: electronhq-16-core
-image: e-119.0.6006.0
+image: e-119.0.6019.2
environment:
GIT_CACHE_PATH: C:\Users\appveyor\libcc_cache
ELECTRON_OUT_DIR: Default
diff --git a/appveyor.yml b/appveyor.yml
index fc18c6704a..fea902ca6c 100644
--- a/appveyor.yml
+++ b/appveyor.yml
@@ -29,7 +29,7 @@
version: 1.0.{build}
build_cloud: electronhq-16-core
-image: e-119.0.6006.0
+image: e-119.0.6019.2
environment:
GIT_CACHE_PATH: C:\Users\appveyor\libcc_cache
ELECTRON_OUT_DIR: Default
|
build
|
67a6fbf2656c5aa18c59721b56b081c156e79fad
|
Mikael Finstad
|
2023-02-20 20:06:19
|
docs: fixed a typo in `process.defaultApp` doc (#37342)
docs: improve `defaultApp`
|
diff --git a/docs/api/process.md b/docs/api/process.md
index 9cc34c691e..e54cc6c2cf 100644
--- a/docs/api/process.md
+++ b/docs/api/process.md
@@ -49,8 +49,11 @@ beginning to load the web page or the main script.
### `process.defaultApp` _Readonly_
-A `boolean`. When app is started by being passed as parameter to the default app, this
+A `boolean`. When the app is started by being passed as parameter to the default Electron executable, this
property is `true` in the main process, otherwise it is `undefined`.
+For example when running the app with `electron .`, it is `true`,
+even if the app is packaged ([`isPackaged`](app.md#appispackaged-readonly)) is `true`.
+This can be useful to determine how many arguments will need to be sliced off from `process.argv`.
### `process.isMainFrame` _Readonly_
|
docs
|
83d023747cab48180640ec3c21ecf91a3da7438c
|
Charles Kerr
|
2023-06-05 00:37:46
|
refactor: use direct aggregation in NativeWindowViews (#38559)
* refactor: in NativeWindowViews, aggregate root_view_ directly
* refactor: in NativeWindowViews, aggregate keyboard_event_handler_ directly
* refactor: make NativeWindowClientView::window_ a raw_ref
Xref: https://chromium.googlesource.com/chromium/src/+/main/styleguide/c++/c++.md\#non_owning-pointers-in-class-fields
Prefer const raw_ref<T> whenever the held pointer will never be null
* chore: make lint happy
|
diff --git a/shell/browser/native_window_views.cc b/shell/browser/native_window_views.cc
index e57e81f696..0298aba40c 100644
--- a/shell/browser/native_window_views.cc
+++ b/shell/browser/native_window_views.cc
@@ -36,7 +36,6 @@
#include "ui/gfx/image/image.h"
#include "ui/gfx/native_widget_types.h"
#include "ui/views/background.h"
-#include "ui/views/controls/webview/unhandled_keyboard_event_handler.h"
#include "ui/views/controls/webview/webview.h"
#include "ui/views/widget/native_widget_private.h"
#include "ui/views/widget/widget.h"
@@ -166,7 +165,8 @@ class NativeWindowClientView : public views::ClientView {
NativeWindowClientView(views::Widget* widget,
views::View* root_view,
NativeWindowViews* window)
- : views::ClientView(widget, root_view), window_(window) {}
+ : views::ClientView{widget, root_view},
+ window_{raw_ref<NativeWindowViews>::from_ptr(window)} {}
~NativeWindowClientView() override = default;
// disable copy
@@ -179,22 +179,19 @@ class NativeWindowClientView : public views::ClientView {
}
private:
- raw_ptr<NativeWindowViews> window_;
+ const raw_ref<NativeWindowViews> window_;
};
} // namespace
NativeWindowViews::NativeWindowViews(const gin_helper::Dictionary& options,
NativeWindow* parent)
- : NativeWindow(options, parent),
- root_view_(std::make_unique<RootView>(this)),
- keyboard_event_handler_(
- std::make_unique<views::UnhandledKeyboardEventHandler>()) {
+ : NativeWindow(options, parent) {
options.Get(options::kTitle, &title_);
bool menu_bar_autohide;
if (options.Get(options::kAutoHideMenuBar, &menu_bar_autohide))
- root_view_->SetAutoHideMenuBar(menu_bar_autohide);
+ root_view_.SetAutoHideMenuBar(menu_bar_autohide);
#if BUILDFLAG(IS_WIN)
// On Windows we rely on the CanResize() to indicate whether window can be
@@ -455,12 +452,12 @@ void NativeWindowViews::SetGTKDarkThemeEnabled(bool use_dark_theme) {
void NativeWindowViews::SetContentView(views::View* view) {
if (content_view()) {
- root_view_->RemoveChildView(content_view());
+ root_view_.RemoveChildView(content_view());
}
set_content_view(view);
focused_view_ = view;
- root_view_->AddChildView(content_view());
- root_view_->Layout();
+ root_view_.AddChildView(content_view());
+ root_view_.Layout();
}
void NativeWindowViews::Close() {
@@ -1097,7 +1094,7 @@ bool NativeWindowViews::IsTabletMode() const {
}
SkColor NativeWindowViews::GetBackgroundColor() {
- auto* background = root_view_->background();
+ auto* background = root_view_.background();
if (!background)
return SK_ColorTRANSPARENT;
return background->get_color();
@@ -1105,7 +1102,7 @@ SkColor NativeWindowViews::GetBackgroundColor() {
void NativeWindowViews::SetBackgroundColor(SkColor background_color) {
// web views' background color.
- root_view_->SetBackground(views::CreateSolidBackground(background_color));
+ root_view_.SetBackground(views::CreateSolidBackground(background_color));
#if BUILDFLAG(IS_WIN)
// Set the background color of native window.
@@ -1240,7 +1237,7 @@ void NativeWindowViews::SetMenu(ElectronMenuModel* menu_model) {
// Remove global menu bar.
if (global_menu_bar_ && menu_model == nullptr) {
global_menu_bar_.reset();
- root_view_->UnregisterAcceleratorsWithFocusManager();
+ root_view_.UnregisterAcceleratorsWithFocusManager();
return;
}
@@ -1249,7 +1246,7 @@ void NativeWindowViews::SetMenu(ElectronMenuModel* menu_model) {
if (!global_menu_bar_)
global_menu_bar_ = std::make_unique<GlobalMenuBarX11>(this);
if (global_menu_bar_->IsServerStarted()) {
- root_view_->RegisterAcceleratorsWithFocusManager(menu_model);
+ root_view_.RegisterAcceleratorsWithFocusManager(menu_model);
global_menu_bar_->SetMenu(menu_model);
return;
}
@@ -1260,13 +1257,13 @@ void NativeWindowViews::SetMenu(ElectronMenuModel* menu_model) {
gfx::Size content_size = GetContentSize();
bool should_reset_size = use_content_size_ && has_frame() &&
!IsMenuBarAutoHide() &&
- ((!!menu_model) != root_view_->HasMenu());
+ ((!!menu_model) != root_view_.HasMenu());
- root_view_->SetMenu(menu_model);
+ root_view_.SetMenu(menu_model);
if (should_reset_size) {
// Enlarge the size constraints for the menu.
- int menu_bar_height = root_view_->GetMenuBarHeight();
+ int menu_bar_height = root_view_.GetMenuBarHeight();
extensions::SizeConstraints constraints = GetContentSizeConstraints();
if (constraints.HasMinimumSize()) {
gfx::Size min_size = constraints.GetMinimumSize();
@@ -1393,19 +1390,19 @@ void NativeWindowViews::SetOverlayIcon(const gfx::Image& overlay,
}
void NativeWindowViews::SetAutoHideMenuBar(bool auto_hide) {
- root_view_->SetAutoHideMenuBar(auto_hide);
+ root_view_.SetAutoHideMenuBar(auto_hide);
}
bool NativeWindowViews::IsMenuBarAutoHide() {
- return root_view_->IsMenuBarAutoHide();
+ return root_view_.IsMenuBarAutoHide();
}
void NativeWindowViews::SetMenuBarVisibility(bool visible) {
- root_view_->SetMenuBarVisibility(visible);
+ root_view_.SetMenuBarVisibility(visible);
}
bool NativeWindowViews::IsMenuBarVisible() {
- return root_view_->IsMenuBarVisible();
+ return root_view_.IsMenuBarVisible();
}
void NativeWindowViews::SetBackgroundMaterial(const std::string& material) {
@@ -1503,8 +1500,8 @@ gfx::Rect NativeWindowViews::ContentBoundsToWindowBounds(
}
#endif
- if (root_view_->HasMenu() && root_view_->IsMenuBarVisible()) {
- int menu_bar_height = root_view_->GetMenuBarHeight();
+ if (root_view_.HasMenu() && root_view_.IsMenuBarVisible()) {
+ int menu_bar_height = root_view_.GetMenuBarHeight();
window_bounds.set_y(window_bounds.y() - menu_bar_height);
window_bounds.set_height(window_bounds.height() + menu_bar_height);
}
@@ -1530,8 +1527,8 @@ gfx::Rect NativeWindowViews::WindowBoundsToContentBounds(
content_bounds.set_size(ScreenToDIPRect(hwnd, content_bounds).size());
#endif
- if (root_view_->HasMenu() && root_view_->IsMenuBarVisible()) {
- int menu_bar_height = root_view_->GetMenuBarHeight();
+ if (root_view_.HasMenu() && root_view_.IsMenuBarVisible()) {
+ int menu_bar_height = root_view_.GetMenuBarHeight();
content_bounds.set_y(content_bounds.y() + menu_bar_height);
content_bounds.set_height(content_bounds.height() - menu_bar_height);
}
@@ -1574,7 +1571,7 @@ void NativeWindowViews::OnWidgetActivationChanged(views::Widget* changed_widget,
if (!active && IsMenuBarAutoHide() && IsMenuBarVisible())
SetMenuBarVisibility(false);
- root_view_->ResetAltState();
+ root_view_.ResetAltState();
}
void NativeWindowViews::OnWidgetBoundsChanged(views::Widget* changed_widget,
@@ -1630,7 +1627,7 @@ std::u16string NativeWindowViews::GetWindowTitle() const {
}
views::View* NativeWindowViews::GetContentsView() {
- return root_view_.get();
+ return &root_view_;
}
bool NativeWindowViews::ShouldDescendIntoChildForEventHandling(
@@ -1640,7 +1637,7 @@ bool NativeWindowViews::ShouldDescendIntoChildForEventHandling(
}
views::ClientView* NativeWindowViews::CreateClientView(views::Widget* widget) {
- return new NativeWindowClientView(widget, root_view_.get(), this);
+ return new NativeWindowClientView{widget, GetContentsView(), this};
}
std::unique_ptr<views::NonClientFrameView>
@@ -1679,9 +1676,9 @@ void NativeWindowViews::HandleKeyboardEvent(
NotifyWindowExecuteAppCommand(kBrowserForward);
#endif
- keyboard_event_handler_->HandleKeyboardEvent(event,
- root_view_->GetFocusManager());
- root_view_->HandleKeyEvent(event);
+ keyboard_event_handler_.HandleKeyboardEvent(event,
+ root_view_.GetFocusManager());
+ root_view_.HandleKeyEvent(event);
}
void NativeWindowViews::OnMouseEvent(ui::MouseEvent* event) {
@@ -1689,7 +1686,7 @@ void NativeWindowViews::OnMouseEvent(ui::MouseEvent* event) {
return;
// Alt+Click should not toggle menu bar.
- root_view_->ResetAltState();
+ root_view_.ResetAltState();
#if BUILDFLAG(IS_LINUX)
if (event->changed_button_flags() == ui::EF_BACK_MOUSE_BUTTON)
diff --git a/shell/browser/native_window_views.h b/shell/browser/native_window_views.h
index a84e17c265..179f4575b2 100644
--- a/shell/browser/native_window_views.h
+++ b/shell/browser/native_window_views.h
@@ -13,6 +13,8 @@
#include <vector>
#include "base/memory/raw_ptr.h"
+#include "shell/browser/ui/views/root_view.h"
+#include "ui/views/controls/webview/unhandled_keyboard_event_handler.h"
#include "ui/views/widget/widget_observer.h"
#if defined(USE_OZONE)
@@ -28,14 +30,9 @@
#endif
-namespace views {
-class UnhandledKeyboardEventHandler;
-}
-
namespace electron {
class GlobalMenuBarX11;
-class RootView;
class WindowStateWatcher;
#if defined(USE_OZONE_PLATFORM_X11)
@@ -251,7 +248,7 @@ class NativeWindowViews : public NativeWindow,
// Maintain window placement.
void MoveBehindTaskBarIfNeeded();
- std::unique_ptr<RootView> root_view_;
+ RootView root_view_{this};
// The view should be focused by default.
raw_ptr<views::View> focused_view_ = nullptr;
@@ -322,7 +319,7 @@ class NativeWindowViews : public NativeWindow,
#endif
// Handles unhandled keyboard messages coming back from the renderer process.
- std::unique_ptr<views::UnhandledKeyboardEventHandler> keyboard_event_handler_;
+ views::UnhandledKeyboardEventHandler keyboard_event_handler_;
// Whether the window should be enabled based on user calls to SetEnabled()
bool is_enabled_ = true;
|
refactor
|
89659fa9c997977ee2a25ce2c769d86742eccb90
|
Samuel Attard
|
2023-09-01 01:28:01
|
chore: fix broken patches on main (#39715)
|
diff --git a/patches/chromium/refactor_expose_hostimportmoduledynamically_and.patch b/patches/chromium/refactor_expose_hostimportmoduledynamically_and.patch
index 05ce732c6e..8cc9dd7b72 100644
--- a/patches/chromium/refactor_expose_hostimportmoduledynamically_and.patch
+++ b/patches/chromium/refactor_expose_hostimportmoduledynamically_and.patch
@@ -7,10 +7,10 @@ Subject: refactor: expose HostImportModuleDynamically and
This is so that Electron can blend Blink's and Node's implementations of these isolate handlers.
diff --git a/third_party/blink/renderer/bindings/core/v8/v8_initializer.cc b/third_party/blink/renderer/bindings/core/v8/v8_initializer.cc
-index b8b20d8c8340c63bd3039a0683446ef1eb4fdf0d..a0781bd3817c2e0d4be37835f0c02063b2e548f1 100644
+index 3da7200c92ccaf8330d46280e26124c1ad558a76..5ceecd071ca2efd2a7db214b65c4a997ef31d0b0 100644
--- a/third_party/blink/renderer/bindings/core/v8/v8_initializer.cc
+++ b/third_party/blink/renderer/bindings/core/v8/v8_initializer.cc
-@@ -606,7 +606,9 @@ bool JavaScriptCompileHintsMagicEnabledCallback(
+@@ -578,7 +578,9 @@ bool JavaScriptCompileHintsMagicEnabledCallback(
execution_context);
}
@@ -21,7 +21,7 @@ index b8b20d8c8340c63bd3039a0683446ef1eb4fdf0d..a0781bd3817c2e0d4be37835f0c02063
v8::Local<v8::Context> context,
v8::Local<v8::Data> v8_host_defined_options,
v8::Local<v8::Value> v8_referrer_resource_url,
-@@ -672,7 +674,7 @@ v8::MaybeLocal<v8::Promise> HostImportModuleDynamically(
+@@ -644,7 +646,7 @@ v8::MaybeLocal<v8::Promise> HostImportModuleDynamically(
}
// https://html.spec.whatwg.org/C/#hostgetimportmetaproperties
@@ -30,7 +30,7 @@ index b8b20d8c8340c63bd3039a0683446ef1eb4fdf0d..a0781bd3817c2e0d4be37835f0c02063
v8::Local<v8::Module> module,
v8::Local<v8::Object> meta) {
ScriptState* script_state = ScriptState::From(context);
-@@ -699,6 +701,8 @@ void HostGetImportMetaProperties(v8::Local<v8::Context> context,
+@@ -671,6 +673,8 @@ void HostGetImportMetaProperties(v8::Local<v8::Context> context,
meta->CreateDataProperty(context, resolve_key, resolve_value).ToChecked();
}
@@ -39,7 +39,7 @@ index b8b20d8c8340c63bd3039a0683446ef1eb4fdf0d..a0781bd3817c2e0d4be37835f0c02063
void InitializeV8Common(v8::Isolate* isolate) {
// Set up garbage collection before setting up anything else as V8 may trigger
// GCs during Blink setup.
-@@ -718,9 +722,9 @@ void InitializeV8Common(v8::Isolate* isolate) {
+@@ -690,9 +694,9 @@ void InitializeV8Common(v8::Isolate* isolate) {
SharedArrayBufferConstructorEnabledCallback);
isolate->SetJavaScriptCompileHintsMagicEnabledCallback(
JavaScriptCompileHintsMagicEnabledCallback);
@@ -52,10 +52,10 @@ index b8b20d8c8340c63bd3039a0683446ef1eb4fdf0d..a0781bd3817c2e0d4be37835f0c02063
V8ContextSnapshot::EnsureInterfaceTemplates(isolate);
diff --git a/third_party/blink/renderer/bindings/core/v8/v8_initializer.h b/third_party/blink/renderer/bindings/core/v8/v8_initializer.h
-index 30a36cf16d4a8f4692ec6a13be1217212390172a..1924f7cef7f5a1f7523c00071639a6c72f9cca70 100644
+index 9e628b96a845322d407f9da30a63c04ef5de9c24..8f5e4602f5e3f6787a9e54d510b39519074d51e6 100644
--- a/third_party/blink/renderer/bindings/core/v8/v8_initializer.h
+++ b/third_party/blink/renderer/bindings/core/v8/v8_initializer.h
-@@ -77,6 +77,17 @@ class CORE_EXPORT V8Initializer {
+@@ -76,6 +76,17 @@ class CORE_EXPORT V8Initializer {
v8::Local<v8::Context> context,
v8::Local<v8::String> source);
diff --git a/patches/v8/.patches b/patches/v8/.patches
index 562b73cdd4..4bd64c3307 100644
--- a/patches/v8/.patches
+++ b/patches/v8/.patches
@@ -2,4 +2,3 @@ build_gn.patch
do_not_export_private_v8_symbols_on_windows.patch
fix_build_deprecated_attribute_for_older_msvc_versions.patch
chore_allow_customizing_microtask_policy_per_context.patch
-fix_compile_error_on_macos_with_fork_optimization.patch
diff --git a/patches/v8/fix_compile_error_on_macos_with_fork_optimization.patch b/patches/v8/fix_compile_error_on_macos_with_fork_optimization.patch
deleted file mode 100644
index d1fc9ccdbc..0000000000
--- a/patches/v8/fix_compile_error_on_macos_with_fork_optimization.patch
+++ /dev/null
@@ -1,34 +0,0 @@
-From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
-From: deepak1556 <[email protected]>
-Date: Tue, 15 Aug 2023 23:59:59 +0900
-Subject: fix: compile error on macOS with
- v8_enable_private_mapping_fork_optimization=true
-
-Follow-up to https://chromium-review.googlesource.com/c/v8/v8/+/4602858,
-we are trying to enable this flag in Electron without any OS conditions in
-args.gn which results in a compilation failure on macOS due to the lack of MADV_DONTFORK.
-
-Given that Node.js and Electron both use posix_spawn on macOS which
-by default does not copy MAP_JIT locations, it would be safe to isolate
-the change only for linux.
-
-Change-Id: I58ad50e557016fa573d7a27f33a60e2e5b7d1804
-Reviewed-on: https://chromium-review.googlesource.com/c/v8/v8/+/4780212
-Reviewed-by: Michael Lippautz <[email protected]>
-Commit-Queue: Michael Lippautz <[email protected]>
-Auto-Submit: Deepak Mohan (Robo) <[email protected]>
-Cr-Commit-Position: refs/heads/main@{#89557}
-
-diff --git a/src/base/platform/platform-posix.cc b/src/base/platform/platform-posix.cc
-index 77fd9e8f6dd5938d38344ffb0074fb70a0969fd9..73cdbdb19df2aecf3046b2bb2b6cb121f4dc5ca7 100644
---- a/src/base/platform/platform-posix.cc
-+++ b/src/base/platform/platform-posix.cc
-@@ -161,7 +161,7 @@ void* Allocate(void* hint, size_t size, OS::MemoryPermission access,
- void* result = mmap(hint, size, prot, flags, kMmapFd, kMmapFdOffset);
- if (result == MAP_FAILED) return nullptr;
-
--#if V8_ENABLE_PRIVATE_MAPPING_FORK_OPTIMIZATION
-+#if V8_OS_LINUX && V8_ENABLE_PRIVATE_MAPPING_FORK_OPTIMIZATION
- // This is advisory, so we ignore errors.
- madvise(result, size, MADV_DONTFORK);
- #endif
|
chore
|
df22e62bf41f1ab7167a87b7aa63379a33ea56d2
|
Calvin
|
2024-04-11 19:37:47
|
docs: update release timeline (#41825)
|
diff --git a/docs/tutorial/electron-timelines.md b/docs/tutorial/electron-timelines.md
index 1b02f4eda1..108c441dd4 100644
--- a/docs/tutorial/electron-timelines.md
+++ b/docs/tutorial/electron-timelines.md
@@ -9,10 +9,11 @@ check out our [Electron Versioning](./electron-versioning.md) doc.
| Electron | Alpha | Beta | Stable | EOL | Chrome | Node | Supported |
| ------- | ----- | ------- | ------ | ------ | ---- | ---- | ---- |
-| 30.0.0 | 2024-Feb-22 | 2024-Mar-20 | 2024-Apr-16 | 2024-Oct-15 | M124 | v20.9+ | ✅ |
+| 31.0.0 | 2024-Apr-18 | 2024-May-15 | 2024-Jun-11 | 2025-Jan-07 | M126 | TBD | ✅ |
+| 30.0.0 | 2024-Feb-22 | 2024-Mar-20 | 2024-Apr-16 | 2024-Oct-15 | M124 | v20.11 | ✅ |
| 29.0.0 | 2023-Dec-07 | 2024-Jan-24 | 2024-Feb-20 | 2024-Aug-20 | M122 | v20.9 | ✅ |
| 28.0.0 | 2023-Oct-11 | 2023-Nov-06 | 2023-Dec-05 | 2024-Jun-11 | M120 | v18.18 | ✅ |
-| 27.0.0 | 2023-Aug-17 | 2023-Sep-13 | 2023-Oct-10 | 2024-Apr-16 | M118 | v18.17 | ✅ |
+| 27.0.0 | 2023-Aug-17 | 2023-Sep-13 | 2023-Oct-10 | 2024-Apr-16 | M118 | v18.17 | 🚫 |
| 26.0.0 | 2023-Jun-01 | 2023-Jun-27 | 2023-Aug-15 | 2024-Feb-20 | M116 | v18.16 | 🚫 |
| 25.0.0 | 2023-Apr-10 | 2023-May-02 | 2023-May-30 | 2023-Dec-05 | M114 | v18.15 | 🚫 |
| 24.0.0 | 2023-Feb-09 | 2023-Mar-07 | 2023-Apr-04 | 2023-Oct-10 | M112 | v18.14 | 🚫 |
|
docs
|
69479b2fb7c5bbbf7e9bfff51f6867829439059c
|
John Kleinschmidt
|
2024-12-14 01:26:25
|
build: update build tools to correct sha (#45018)
chore: update build tools to correct sha
|
diff --git a/.github/actions/install-build-tools/action.yml b/.github/actions/install-build-tools/action.yml
index 9efb72a744..f84472b4b1 100644
--- a/.github/actions/install-build-tools/action.yml
+++ b/.github/actions/install-build-tools/action.yml
@@ -11,7 +11,7 @@ runs:
git config --global core.autocrlf false
git config --global branch.autosetuprebase always
fi
- export BUILD_TOOLS_SHA=bf2a839205d569be99e0b23ede5d8a0d5041a777
+ export BUILD_TOOLS_SHA=8246e57791b0af4ae5975eb96f09855f9269b1cd
npm i -g @electron/build-tools
e auto-update disable
if [ "$(expr substr $(uname -s) 1 10)" == "MSYS_NT-10" ]; then
|
build
|
32a721fa2bdff874270d50b5609866bdb43ef3c4
|
Shelley Vohr
|
2023-10-18 21:39:53
|
test: fix Node.js color edge snapshot stack traces (#40250)
|
diff --git a/patches/node/.patches b/patches/node/.patches
index 548b3ad9d7..7a33769862 100644
--- a/patches/node/.patches
+++ b/patches/node/.patches
@@ -40,7 +40,6 @@ fix_do_not_resolve_electron_entrypoints.patch
fix_ftbfs_werror_wextra-semi.patch
fix_isurl_implementation.patch
ci_ensure_node_tests_set_electron_run_as_node.patch
-chore_update_fixtures_errors_force_colors_snapshot.patch
fix_assert_module_in_the_renderer_process.patch
src_cast_v8_object_getinternalfield_return_value_to_v8_value.patch
fix_add_trusted_space_and_trusted_lo_space_to_the_v8_heap.patch
@@ -53,3 +52,4 @@ src_adapt_to_v8_exception_api_change.patch
lib_test_do_not_hardcode_buffer_kmaxlength.patch
fix_handle_possible_disabled_sharedarraybuffer.patch
win_process_avoid_assert_after_spawning_store_app_4152.patch
+test_fix_edge_snapshot_stack_traces.patch
diff --git a/patches/node/chore_update_fixtures_errors_force_colors_snapshot.patch b/patches/node/chore_update_fixtures_errors_force_colors_snapshot.patch
deleted file mode 100644
index ea1f2520da..0000000000
--- a/patches/node/chore_update_fixtures_errors_force_colors_snapshot.patch
+++ /dev/null
@@ -1,34 +0,0 @@
-From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
-From: Charles Kerr <[email protected]>
-Date: Mon, 7 Aug 2023 20:29:10 -0500
-Subject: chore: update fixtures/errors/force_colors.snapshot
-
-The line numbers in the stacktrace from our v8 build don't match what
-Node's tests are expecting, so update the stacktrace to match our build.
-
-The specific probably isn't needed for the force_colors test, which is
-trying to see whether or not the lines are greyed out. One possibility
-would be to upstream a changed test that doesn't hardcode line numbers.
-
-diff --git a/test/fixtures/errors/force_colors.snapshot b/test/fixtures/errors/force_colors.snapshot
-index 4c33acbc2d5c12ac8750b72e0796284176af3da2..035f00b0a4a76a606ba707617b56c9beb074052e 100644
---- a/test/fixtures/errors/force_colors.snapshot
-+++ b/test/fixtures/errors/force_colors.snapshot
-@@ -4,11 +4,12 @@ throw new Error('Should include grayed stack trace')
-
- Error: Should include grayed stack trace
- at Object.<anonymous> [90m(/[39mtest*force_colors.js:1:7[90m)[39m
--[90m at Module._compile (node:internal*modules*cjs*loader:1256:14)[39m
--[90m at Module._extensions..js (node:internal*modules*cjs*loader:1310:10)[39m
--[90m at Module.load (node:internal*modules*cjs*loader:1119:32)[39m
--[90m at Module._load (node:internal*modules*cjs*loader:960:12)[39m
--[90m at Function.executeUserEntryPoint [as runMain] (node:internal*modules*run_main:86:12)[39m
-+[90m at Module._compile (node:internal*modules*cjs*loader:1271:14)[39m
-+[90m at Module._extensions..js (node:internal*modules*cjs*loader:1326:10)[39m
-+[90m at Module.load (node:internal*modules*cjs*loader:1126:32)[39m
-+[90m at Module._load (node:internal*modules*cjs*loader:967:12)[39m
-+[90m at Module._load (node:electron*js2c*asar_bundle:775:32)[39m
-+[90m at Function.executeUserEntryPoint [as runMain] (node:internal*modules*run_main:101:12)[39m
- [90m at node:internal*main*run_main_module:23:47[39m
-
- Node.js *
diff --git a/patches/node/test_fix_edge_snapshot_stack_traces.patch b/patches/node/test_fix_edge_snapshot_stack_traces.patch
new file mode 100644
index 0000000000..a467c0da89
--- /dev/null
+++ b/patches/node/test_fix_edge_snapshot_stack_traces.patch
@@ -0,0 +1,141 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: Shelley Vohr <[email protected]>
+Date: Wed, 18 Oct 2023 10:40:34 +0200
+Subject: test: fix edge snapshot stack traces
+
+https://github.com/nodejs/node/pull/49659
+
+diff --git a/test/common/assertSnapshot.js b/test/common/assertSnapshot.js
+index 83ee45f5f906adddcbc701112f373332dd1f66f9..7b6a9d59bfaa0247f4466277097cd5575ff81d0c 100644
+--- a/test/common/assertSnapshot.js
++++ b/test/common/assertSnapshot.js
+@@ -8,6 +8,10 @@ const assert = require('node:assert/strict');
+ const stackFramesRegexp = /(\s+)((.+?)\s+\()?(?:\(?(.+?):(\d+)(?::(\d+))?)\)?(\s+\{)?(\[\d+m)?(\n|$)/g;
+ const windowNewlineRegexp = /\r/g;
+
++function replaceNodeVersion(str) {
++ return str.replaceAll(process.version, '*');
++}
++
+ function replaceStackTrace(str, replacement = '$1*$7$8\n') {
+ return str.replace(stackFramesRegexp, replacement);
+ }
+@@ -70,6 +74,7 @@ async function spawnAndAssert(filename, transform = (x) => x, { tty = false, ...
+ module.exports = {
+ assertSnapshot,
+ getSnapshotPath,
++ replaceNodeVersion,
+ replaceStackTrace,
+ replaceWindowsLineEndings,
+ replaceWindowsPaths,
+diff --git a/test/fixtures/errors/force_colors.snapshot b/test/fixtures/errors/force_colors.snapshot
+index 4c33acbc2d5c12ac8750b72e0796284176af3da2..21410d492db861876ecfcb82dcc3c1815cba6d09 100644
+--- a/test/fixtures/errors/force_colors.snapshot
++++ b/test/fixtures/errors/force_colors.snapshot
+@@ -4,11 +4,12 @@ throw new Error('Should include grayed stack trace')
+
+ Error: Should include grayed stack trace
+ at Object.<anonymous> [90m(/[39mtest*force_colors.js:1:7[90m)[39m
+-[90m at Module._compile (node:internal*modules*cjs*loader:1256:14)[39m
+-[90m at Module._extensions..js (node:internal*modules*cjs*loader:1310:10)[39m
+-[90m at Module.load (node:internal*modules*cjs*loader:1119:32)[39m
+-[90m at Module._load (node:internal*modules*cjs*loader:960:12)[39m
+-[90m at Function.executeUserEntryPoint [as runMain] (node:internal*modules*run_main:86:12)[39m
+-[90m at node:internal*main*run_main_module:23:47[39m
++[90m at *[39m
++[90m at *[39m
++[90m at *[39m
++[90m at *[39m
++[90m at *[39m
++[90m at *[39m
++[90m at *[39m
+
+ Node.js *
+diff --git a/test/parallel/test-node-output-errors.mjs b/test/parallel/test-node-output-errors.mjs
+index b9a55fb7ea22e62553f69bd035797f7aaee1fc38..1f5ce52cf674cfc5fb75ad2cd979752a991c7e28 100644
+--- a/test/parallel/test-node-output-errors.mjs
++++ b/test/parallel/test-node-output-errors.mjs
+@@ -10,14 +10,15 @@ const skipForceColors =
+ (common.isWindows && (Number(os.release().split('.')[0]) !== 10 || Number(os.release().split('.')[2]) < 14393)); // See https://github.com/nodejs/node/pull/33132
+
+
+-function replaceNodeVersion(str) {
+- return str.replaceAll(process.version, '*');
+-}
+-
+ function replaceStackTrace(str) {
+ return snapshot.replaceStackTrace(str, '$1at *$7\n');
+ }
+
++function replaceForceColorsStackTrace(str) {
++ // eslint-disable-next-line no-control-regex
++ return str.replaceAll(/(\[90m\W+)at .*node:.*/g, '$1at *[39m');
++}
++
+ describe('errors output', { concurrency: true }, () => {
+ function normalize(str) {
+ return str.replaceAll(snapshot.replaceWindowsPaths(process.cwd()), '').replaceAll('//', '*').replaceAll(/\/(\w)/g, '*$1').replaceAll('*test*', '*').replaceAll('*fixtures*errors*', '*').replaceAll('file:**', 'file:*/');
+@@ -28,9 +29,12 @@ describe('errors output', { concurrency: true }, () => {
+ }
+ const common = snapshot
+ .transform(snapshot.replaceWindowsLineEndings, snapshot.replaceWindowsPaths);
+- const defaultTransform = snapshot.transform(common, normalize, replaceNodeVersion);
+- const errTransform = snapshot.transform(common, normalizeNoNumbers, replaceNodeVersion);
+- const promiseTransform = snapshot.transform(common, replaceStackTrace, normalizeNoNumbers, replaceNodeVersion);
++ const defaultTransform = snapshot.transform(common, normalize, snapshot.replaceNodeVersion);
++ const errTransform = snapshot.transform(common, normalizeNoNumbers, snapshot.replaceNodeVersion);
++ const promiseTransform = snapshot.transform(common, replaceStackTrace,
++ normalizeNoNumbers, snapshot.replaceNodeVersion);
++ const forceColorsTransform = snapshot.transform(common, normalize,
++ replaceForceColorsStackTrace, snapshot.replaceNodeVersion);
+
+ const tests = [
+ { name: 'errors/async_error_eval_cjs.js' },
+@@ -50,7 +54,11 @@ describe('errors output', { concurrency: true }, () => {
+ { name: 'errors/throw_in_line_with_tabs.js', transform: errTransform },
+ { name: 'errors/throw_non_error.js', transform: errTransform },
+ { name: 'errors/promise_always_throw_unhandled.js', transform: promiseTransform },
+- !skipForceColors ? { name: 'errors/force_colors.js', env: { FORCE_COLOR: 1 } } : null,
++ !skipForceColors ? {
++ name: 'errors/force_colors.js',
++ transform: forceColorsTransform,
++ env: { FORCE_COLOR: 1 }
++ } : null,
+ ].filter(Boolean);
+ for (const { name, transform, env } of tests) {
+ if (env) env.ELECTRON_RUN_AS_NODE = 1;
+diff --git a/test/parallel/test-node-output-sourcemaps.mjs b/test/parallel/test-node-output-sourcemaps.mjs
+index 8e43947ab2188f087056eab39d0e1a11481f9da5..c53a0598958e4e386db1993caeb312dae3f302a8 100644
+--- a/test/parallel/test-node-output-sourcemaps.mjs
++++ b/test/parallel/test-node-output-sourcemaps.mjs
+@@ -4,10 +4,6 @@ import * as snapshot from '../common/assertSnapshot.js';
+ import * as path from 'node:path';
+ import { describe, it } from 'node:test';
+
+-function replaceNodeVersion(str) {
+- return str.replaceAll(process.version, '*');
+-}
+-
+ describe('sourcemaps output', { concurrency: true }, () => {
+ function normalize(str) {
+ const result = str
+@@ -16,7 +12,8 @@ describe('sourcemaps output', { concurrency: true }, () => {
+ .replaceAll('/Users/bencoe/oss/coffee-script-test', '')
+ .replaceAll(/\/(\w)/g, '*$1')
+ .replaceAll('*test*', '*')
+- .replaceAll('*fixtures*source-map*', '*');
++ .replaceAll('*fixtures*source-map*', '*')
++ .replaceAll(/(\W+).*node:internal\*modules.*/g, '$1*');
+ if (common.isWindows) {
+ const currentDeviceLetter = path.parse(process.cwd()).root.substring(0, 1).toLowerCase();
+ const regex = new RegExp(`${currentDeviceLetter}:/?`, 'gi');
+@@ -25,7 +22,8 @@ describe('sourcemaps output', { concurrency: true }, () => {
+ return result;
+ }
+ const defaultTransform = snapshot
+- .transform(snapshot.replaceWindowsLineEndings, snapshot.replaceWindowsPaths, normalize, replaceNodeVersion);
++ .transform(snapshot.replaceWindowsLineEndings, snapshot.replaceWindowsPaths,
++ normalize, snapshot.replaceNodeVersion);
+
+ const tests = [
+ { name: 'source-map/output/source_map_disabled_by_api.js' },
|
test
|
5aabb6bec5eed5775e106ae2c4b093b986d63ca4
|
Shelley Vohr
|
2025-01-22 17:02:29
|
fix: potential crash in `chrome.tabs.update()` (#45276)
fix: potential crash in chrome.tabs.update()
|
diff --git a/shell/browser/extensions/api/tabs/tabs_api.cc b/shell/browser/extensions/api/tabs/tabs_api.cc
index aa57c2c8c6..c1962e0b0d 100644
--- a/shell/browser/extensions/api/tabs/tabs_api.cc
+++ b/shell/browser/extensions/api/tabs/tabs_api.cc
@@ -651,7 +651,16 @@ bool TabsUpdateFunction::UpdateURL(const std::string& url_string,
// will stay in the omnibox - see https://crbug.com/1085779.
load_params.transition_type = ui::PAGE_TRANSITION_FROM_API;
- web_contents_->GetController().LoadURLWithParams(load_params);
+ base::WeakPtr<content::NavigationHandle> navigation_handle =
+ web_contents_->GetController().LoadURLWithParams(load_params);
+ // Navigation can fail for any number of reasons at the content layer.
+ // Unfortunately, we can't provide a detailed error message here, because
+ // there are too many possible triggers. At least notify the extension that
+ // the update failed.
+ if (!navigation_handle) {
+ *error = "Navigation rejected.";
+ return false;
+ }
DCHECK_EQ(url,
web_contents_->GetController().GetPendingEntry()->GetVirtualURL());
|
fix
|
58dc990f7a725537b447c22862956ac6d711291d
|
Shelley Vohr
|
2024-11-18 21:25:20
|
chore: fix multi-version parsing in issue assignment (#44679)
* chore: fix multi-version parsing
* chore: tweak for review
|
diff --git a/.github/workflows/issue-opened.yml b/.github/workflows/issue-opened.yml
index 15fcf9cc30..c9feb27fd0 100644
--- a/.github/workflows/issue-opened.yml
+++ b/.github/workflows/issue-opened.yml
@@ -57,34 +57,40 @@ jobs:
const electronVersion = select('heading:has(> text[value="Electron Version"]) + paragraph > text', tree)?.value.trim();
if (electronVersion !== undefined) {
- const major = semver.parse(electronVersion)?.major;
- if (major) {
- const versionLabel = `${major}-x-y`;
- let labelExists = false;
-
- try {
- await github.rest.issues.getLabel({
- owner,
- repo,
- name: versionLabel,
- });
- labelExists = true;
- } catch {}
-
- if (labelExists) {
- // Check if it's an unsupported major
- const { ElectronVersions } = await import('${{ github.workspace }}/node_modules/@electron/fiddle-core/dist/index.js');
- const versions = await ElectronVersions.create(undefined, { ignoreCache: true });
-
- const validVersions = [...versions.supportedMajors, ...versions.prereleaseMajors];
- if (!validVersions.includes(major)) {
- core.setOutput('unsupportedMajor', true);
- labels.push('blocked/need-info ❌');
+ // It's possible for multiple versions to be listed -
+ // for now check for comma or space separated version.
+ const versions = electronVersion.split(/, | /);
+ for (const version of versions) {
+ const major = semver.parse(version)?.major;
+ if (major) {
+ const versionLabel = `${major}-x-y`;
+ let labelExists = false;
+
+ try {
+ await github.rest.issues.getLabel({
+ owner,
+ repo,
+ name: versionLabel,
+ });
+ labelExists = true;
+ } catch {}
+
+ if (labelExists) {
+ // Check if it's an unsupported major
+ const { ElectronVersions } = await import('${{ github.workspace }}/node_modules/@electron/fiddle-core/dist/index.js');
+ const versions = await ElectronVersions.create(undefined, { ignoreCache: true });
+
+ const validVersions = [...versions.supportedMajors, ...versions.prereleaseMajors];
+ if (validVersions.includes(major)) {
+ labels.push(versionLabel);
+ }
}
-
- labels.push(versionLabel);
}
}
+ if (labels.length === 0) {
+ core.setOutput('No supported versions found', true);
+ labels.push('blocked/need-info ❌');
+ }
}
const operatingSystems = select('heading:has(> text[value="What operating system(s) are you using?"]) + paragraph > text', tree)?.value.trim().split(', ');
|
chore
|
aa06b065c06e2e7fa1ac88e402d9113ca9c1bc39
|
Charles Kerr
|
2025-02-11 17:26:39
|
chore: bump chromium to 134.0.6998.10 (main) (#45564)
* chore: bump chromium to 134.0.6992.0
* chore: add BrowserProcessImpl::CreateGlobalFeaturesForTesting() stub
Xref: https://chromium-review.googlesource.com/c/chromium/src/+/6216193
Remove GlobalFeatures from TestingBrowserProcess::Init
* chore: bump chromium to 134.0.6994.0
* 6208630: Mac sandbox: don't use protobuf for policy serialization | https://chromium-review.googlesource.com/c/chromium/src/+/6208630
* [PDF] Remove HasUnsupportedFeature Mojo interface
Xref: https://chromium-review.googlesource.com/c/chromium/src/+/6220800
* 6217444: Remove scoped_gdi_object.h type aliases. | https://chromium-review.googlesource.com/c/chromium/src/+/6217444
* chore: bump chromium to 134.0.6998.10
* 6221378: Revert [OBC] Exclude Aliasing Cookies in FilterCookiesWithOptions() | https://chromium-review.googlesource.com/c/chromium/src/+/6221378
* Update ExtensionPrefs::GetDisableReasons to return DisableReasonSet
Xref: https://chromium-review.googlesource.com/c/chromium/src/+/6218840
change copied from 6218840 extensions/shell/browser/shell_extension_loader.cc
* 6218402: Typemap ui.gfx.DXGIHandle <=> gfx::DXGIHandle | https://chromium-review.googlesource.com/c/chromium/src/+/6218402
* chore: disable flaky contentTracing test
not new to this roll; it is happening in main as well
* fixup! chore: disable flaky contentTracing test
---------
Co-authored-by: alice <[email protected]>
|
diff --git a/DEPS b/DEPS
index c9bf8fb014..6b19f310af 100644
--- a/DEPS
+++ b/DEPS
@@ -2,7 +2,7 @@ gclient_gn_args_from = 'src'
vars = {
'chromium_version':
- '134.0.6990.0',
+ '134.0.6998.10',
'node_version':
'v22.13.1',
'nan_version':
diff --git a/patches/chromium/mas_avoid_private_macos_api_usage.patch.patch b/patches/chromium/mas_avoid_private_macos_api_usage.patch.patch
index 8c7d7ad2a7..760f84c9e8 100644
--- a/patches/chromium/mas_avoid_private_macos_api_usage.patch.patch
+++ b/patches/chromium/mas_avoid_private_macos_api_usage.patch.patch
@@ -35,10 +35,10 @@ system font by checking if it's kCTFontPriorityAttribute is set to
system priority.
diff --git a/base/BUILD.gn b/base/BUILD.gn
-index a4ae9c4c242551f6850cdcbb42551b676db76c95..22281156bcfdd6999d15d511c508415f8f3f9ac7 100644
+index 05ba2110698b69af677ad1fe898ae6e5953c7af4..7bcbb8f647faea889e295d8919f67745a7f72136 100644
--- a/base/BUILD.gn
+++ b/base/BUILD.gn
-@@ -1028,6 +1028,7 @@ component("base") {
+@@ -1027,6 +1027,7 @@ component("base") {
"//build:ios_buildflags",
"//build/config/compiler:compiler_buildflags",
"//third_party/modp_b64",
@@ -192,10 +192,10 @@ index e12c1d078147d956a1d9b1bc498c1b1d6fe7b974..233362259dc4e728ed37435e65041764
} // namespace base
diff --git a/components/os_crypt/sync/BUILD.gn b/components/os_crypt/sync/BUILD.gn
-index bfb0d2f208170f77df96fb9f14c8525e9dec6e11..e234d95a862198148bae97b4b276d93922f3ca92 100644
+index ff1e356ff696d3830d02644969c36a71fdf32ff6..b39c716c52524b95f2d3417a98e60c0c41147c93 100644
--- a/components/os_crypt/sync/BUILD.gn
+++ b/components/os_crypt/sync/BUILD.gn
-@@ -43,6 +43,8 @@ component("os_crypt") {
+@@ -38,6 +38,8 @@ component("sync") {
"os_crypt_mac.mm",
]
deps += [ "//crypto:mock_apple_keychain" ]
@@ -269,7 +269,7 @@ index e9f4e5131238b9fb5f1b4b3e90a0cb84a7fc15b4..8b5f4cae3123ac5480ad73f0c873fca0
} // namespace
diff --git a/components/remote_cocoa/app_shim/browser_native_widget_window_mac.mm b/components/remote_cocoa/app_shim/browser_native_widget_window_mac.mm
-index 19fff43c3daaef5451b6b60b84a610a21311448e..240b954661d34fcc4329d39490be33c485fa8b6e 100644
+index 3a8b44a2a295119f37ca37d5866dfcfa21121db0..b408e9c73fe97dd8885b5479923481e20955cf8d 100644
--- a/components/remote_cocoa/app_shim/browser_native_widget_window_mac.mm
+++ b/components/remote_cocoa/app_shim/browser_native_widget_window_mac.mm
@@ -9,7 +9,9 @@
@@ -298,7 +298,7 @@ index 19fff43c3daaef5451b6b60b84a610a21311448e..240b954661d34fcc4329d39490be33c4
+ (Class)frameViewClassForStyleMask:(NSUInteger)windowStyle {
// - NSThemeFrame and its subclasses will be nil if it's missing at runtime.
if ([BrowserWindowFrame class])
-@@ -165,6 +170,8 @@ - (BOOL)_usesCustomDrawing {
+@@ -163,6 +168,8 @@ - (BOOL)_usesCustomDrawing {
return NO;
}
@@ -307,7 +307,7 @@ index 19fff43c3daaef5451b6b60b84a610a21311448e..240b954661d34fcc4329d39490be33c4
// Handle "Move focus to the window toolbar" configured in System Preferences ->
// Keyboard -> Shortcuts -> Keyboard. Usually Ctrl+F5. The argument (|unknown|)
// tends to just be nil.
-@@ -175,8 +182,8 @@ - (void)_handleFocusToolbarHotKey:(id)unknown {
+@@ -173,8 +180,8 @@ - (void)_handleFocusToolbarHotKey:(id)unknown {
}
- (void)setAlwaysShowTrafficLights:(BOOL)alwaysShow {
@@ -354,7 +354,7 @@ index 3a815ebf505bd95fa7f6b61ba433d98fbfe20225..149de0175c2ec0e41e3ba40caad7019c
+
@end
diff --git a/components/remote_cocoa/app_shim/native_widget_mac_nswindow.h b/components/remote_cocoa/app_shim/native_widget_mac_nswindow.h
-index d55914779bc097cab8afb144f2c47c001bfa7350..e55db3f550b4c082aa087fbcab6760da237f8471 100644
+index 127a2829fafa04bfbab0b883304dfb815d7e1c22..61d7946e52862f3586b1e098d7d44a125656de81 100644
--- a/components/remote_cocoa/app_shim/native_widget_mac_nswindow.h
+++ b/components/remote_cocoa/app_shim/native_widget_mac_nswindow.h
@@ -9,6 +9,7 @@
@@ -382,7 +382,7 @@ index d55914779bc097cab8afb144f2c47c001bfa7350..e55db3f550b4c082aa087fbcab6760da
// The NSWindow used by BridgedNativeWidget. Provides hooks into AppKit that
// can only be accomplished by overriding methods.
diff --git a/components/remote_cocoa/app_shim/native_widget_mac_nswindow.mm b/components/remote_cocoa/app_shim/native_widget_mac_nswindow.mm
-index 03ff0478f16f237e6b8082508d5399195bfdca44..9b74f6ca6de6ec057073e175170014b5512040b4 100644
+index 2b50e3c3750c9ac6dd84a514663062a5d754b43e..49ced9aa87d3bcb00cd3d76ac32d4eec89873549 100644
--- a/components/remote_cocoa/app_shim/native_widget_mac_nswindow.mm
+++ b/components/remote_cocoa/app_shim/native_widget_mac_nswindow.mm
@@ -26,6 +26,7 @@
@@ -449,7 +449,7 @@ index 03ff0478f16f237e6b8082508d5399195bfdca44..9b74f6ca6de6ec057073e175170014b5
bool shouldShowWindowTitle = YES;
if (_bridge)
diff --git a/components/remote_cocoa/app_shim/native_widget_ns_window_bridge.mm b/components/remote_cocoa/app_shim/native_widget_ns_window_bridge.mm
-index 89aca4b47c202f137a5ffe8390986ef6dd62942a..59276806afa7659573eb276149ff8ed47ca72c1f 100644
+index 36c522793dc37f7c72f7cccde50895927b5560cb..689351b5a6e6e6013b808c1b4924b8848dcc0fa2 100644
--- a/components/remote_cocoa/app_shim/native_widget_ns_window_bridge.mm
+++ b/components/remote_cocoa/app_shim/native_widget_ns_window_bridge.mm
@@ -41,6 +41,7 @@
@@ -579,10 +579,10 @@ index a76028eed0249244d0559de102a756e3b2771b63..cb65efb56849d57e2e656f90d5b1d737
return kAttributes;
}
diff --git a/content/browser/BUILD.gn b/content/browser/BUILD.gn
-index 74ca66c0f38b4fc4448d50a9f3674cda6a078f0e..5c49a11dfbe1275f0f8cd21bf970d3b6b98cb71e 100644
+index e5ca8881f7e05fc3c600cf6f785a2070efff2e5d..ce57b1e635f26ef248fbf8285cf69fe3c6c41105 100644
--- a/content/browser/BUILD.gn
+++ b/content/browser/BUILD.gn
-@@ -329,6 +329,7 @@ source_set("browser") {
+@@ -330,6 +330,7 @@ source_set("browser") {
"//ui/touch_selection",
"//ui/webui/resources",
"//v8:v8_version",
@@ -625,7 +625,7 @@ index bea4e26ef8577e8e8bc60287cf1b94c7dfcc9478..eed42b0cbc3422b7fd59ae1b2550c53d
// Used to force the NSApplication's focused accessibility element to be the
// content::BrowserAccessibilityCocoa accessibility tree when the NSView for
diff --git a/content/browser/renderer_host/render_widget_host_view_mac.mm b/content/browser/renderer_host/render_widget_host_view_mac.mm
-index 9185fd223c9611faee546570c0df36bc94cdb28c..86886e94e9e2c52e297a82175f6071852e792148 100644
+index 430426a0123508a45bf48dcbfb46d1c4dc9d9347..efa697b7c4d428200d14e436ab062c13273916f4 100644
--- a/content/browser/renderer_host/render_widget_host_view_mac.mm
+++ b/content/browser/renderer_host/render_widget_host_view_mac.mm
@@ -48,6 +48,7 @@
@@ -647,7 +647,7 @@ index 9185fd223c9611faee546570c0df36bc94cdb28c..86886e94e9e2c52e297a82175f607185
// Reset `ns_view_` before resetting `remote_ns_view_` to avoid dangling
// pointers. `ns_view_` gets reinitialized later in this method.
-@@ -1616,8 +1619,10 @@ void CombineTextNodesAndMakeCallback(SpeechCallback callback,
+@@ -1622,8 +1625,10 @@ void CombineTextNodesAndMakeCallback(SpeechCallback callback,
gfx::NativeViewAccessible
RenderWidgetHostViewMac::AccessibilityGetNativeViewAccessibleForWindow() {
@@ -658,7 +658,7 @@ index 9185fd223c9611faee546570c0df36bc94cdb28c..86886e94e9e2c52e297a82175f607185
return [GetInProcessNSView() window];
}
-@@ -1666,9 +1671,11 @@ void CombineTextNodesAndMakeCallback(SpeechCallback callback,
+@@ -1672,9 +1677,11 @@ void CombineTextNodesAndMakeCallback(SpeechCallback callback,
}
void RenderWidgetHostViewMac::SetAccessibilityWindow(NSWindow* window) {
@@ -670,7 +670,7 @@ index 9185fd223c9611faee546570c0df36bc94cdb28c..86886e94e9e2c52e297a82175f607185
}
bool RenderWidgetHostViewMac::SyncIsWidgetForMainFrame(
-@@ -2195,20 +2202,26 @@ void CombineTextNodesAndMakeCallback(SpeechCallback callback,
+@@ -2201,20 +2208,26 @@ void CombineTextNodesAndMakeCallback(SpeechCallback callback,
void RenderWidgetHostViewMac::GetRenderWidgetAccessibilityToken(
GetRenderWidgetAccessibilityTokenCallback callback) {
base::ProcessId pid = getpid();
@@ -792,7 +792,7 @@ index a1068589ad844518038ee7bc15a3de9bc5cba525..1ff781c49f086ec8015c7d3c44567dbe
} // namespace content
diff --git a/content/test/BUILD.gn b/content/test/BUILD.gn
-index 27adf4138c7ea1cb90460bdd21586163f7614a48..6b422c331bb14489b36a762ad2ced88544d21b60 100644
+index 190b593519ab8ccfc6309b40947c6e42ff8c6131..ec3dd70e677d7215df1c2cb504faa62ac1e6dff4 100644
--- a/content/test/BUILD.gn
+++ b/content/test/BUILD.gn
@@ -652,6 +652,7 @@ static_library("test_support") {
@@ -811,7 +811,7 @@ index 27adf4138c7ea1cb90460bdd21586163f7614a48..6b422c331bb14489b36a762ad2ced885
}
mojom("content_test_mojo_bindings") {
-@@ -1924,6 +1926,7 @@ test("content_browsertests") {
+@@ -1935,6 +1937,7 @@ test("content_browsertests") {
"//ui/shell_dialogs",
"//ui/snapshot",
"//ui/webui:test_support",
@@ -819,7 +819,7 @@ index 27adf4138c7ea1cb90460bdd21586163f7614a48..6b422c331bb14489b36a762ad2ced885
]
if (!(is_chromeos && target_cpu == "arm64" && current_cpu == "arm")) {
-@@ -3210,6 +3213,7 @@ test("content_unittests") {
+@@ -3228,6 +3231,7 @@ test("content_unittests") {
"//ui/latency:test_support",
"//ui/shell_dialogs:shell_dialogs",
"//ui/webui:test_support",
@@ -932,10 +932,10 @@ index 36322ddd3047f96569f35807541a37d3c6672b09..0121a780cf3b79fc1120c1b85cd5cd30
namespace ui {
diff --git a/media/audio/BUILD.gn b/media/audio/BUILD.gn
-index 977aa5b452c882ee69690ba034ec00c9e7ff7e24..3ae3e2ead48ea1af9307dcd12647ca2a24b3a6f4 100644
+index 87126a36725849cbaf478e2dc24dc3a628a30846..a3a88b07af91b86191d9e5727a1d021ebbbb22ce 100644
--- a/media/audio/BUILD.gn
+++ b/media/audio/BUILD.gn
-@@ -198,6 +198,7 @@ source_set("audio") {
+@@ -196,6 +196,7 @@ source_set("audio") {
"CoreMedia.framework",
]
weak_frameworks = [ "ScreenCaptureKit.framework" ] # macOS 13.0
@@ -1023,18 +1023,18 @@ index 70d5665ad7b9ef62370497636af919ede2508ad4..f4dc3e2b8053cdb3e8c439ab1a1d6369
}
diff --git a/sandbox/mac/BUILD.gn b/sandbox/mac/BUILD.gn
-index 4e53d573ff67615bc7dcee7db6f855c67094f414..8b061d66b1a854b51a5a38b6a71eadab6a7dbbec 100644
+index 453e2185fc85fcb29fa7af3f94cce5bda8118b0c..1c383675bb9113b5b1df9280b8ee994123794dfc 100644
--- a/sandbox/mac/BUILD.gn
+++ b/sandbox/mac/BUILD.gn
-@@ -39,6 +39,7 @@ component("seatbelt") {
- ]
- public_deps = [ "//third_party/protobuf:protobuf_lite" ]
+@@ -25,6 +25,7 @@ component("seatbelt") {
+ libs = [ "sandbox" ]
+ deps = [ ":seatbelt_export" ]
defines = [ "SEATBELT_IMPLEMENTATION" ]
+ deps += ["//electron/build/config:generate_mas_config"]
}
component("seatbelt_extension") {
-@@ -52,6 +53,7 @@ component("seatbelt_extension") {
+@@ -38,6 +39,7 @@ component("seatbelt_extension") {
libs = [ "sandbox" ]
public_deps = [ "//base" ]
defines = [ "SEATBELT_IMPLEMENTATION" ]
@@ -1042,7 +1042,7 @@ index 4e53d573ff67615bc7dcee7db6f855c67094f414..8b061d66b1a854b51a5a38b6a71eadab
}
component("system_services") {
-@@ -66,6 +68,7 @@ component("system_services") {
+@@ -52,6 +54,7 @@ component("system_services") {
deps = [ ":seatbelt_export" ]
public_deps = [ "//base" ]
defines = [ "SEATBELT_IMPLEMENTATION" ]
@@ -1050,36 +1050,6 @@ index 4e53d573ff67615bc7dcee7db6f855c67094f414..8b061d66b1a854b51a5a38b6a71eadab
}
source_set("sandbox_unittests") {
-diff --git a/sandbox/mac/sandbox_compiler.cc b/sandbox/mac/sandbox_compiler.cc
-index f35d9ef2a2df3db8ecbf1d7b909c7b1cf33f3cd9..5d52330d1bd70cd7b97ee3360721f10c8447c717 100644
---- a/sandbox/mac/sandbox_compiler.cc
-+++ b/sandbox/mac/sandbox_compiler.cc
-@@ -7,6 +7,7 @@
- #include <string>
- #include <vector>
-
-+#include "electron/mas.h"
- #include "sandbox/mac/seatbelt.h"
-
- namespace sandbox {
-@@ -47,6 +48,7 @@ bool SandboxCompiler::SetParameter(const std::string& key,
- }
-
- bool SandboxCompiler::CompileAndApplyProfile(std::string& error) {
-+#if !IS_MAS_BUILD()
- if (mode_ == Target::kSource) {
- std::vector<const char*> params;
-
-@@ -67,6 +69,9 @@ bool SandboxCompiler::CompileAndApplyProfile(std::string& error) {
- }
- }
- return false;
-+#else
-+ return true;
-+#endif
- }
-
- bool SandboxCompiler::CompilePolicyToProto(mac::SandboxPolicy& policy,
diff --git a/sandbox/mac/sandbox_logging.cc b/sandbox/mac/sandbox_logging.cc
index 095c639b9893e885d8937e29ed7d47a7c28bc6b6..7e0cf9b9f94b16741358bdb45122f8b2bd68c0f9 100644
--- a/sandbox/mac/sandbox_logging.cc
@@ -1117,7 +1087,7 @@ index 095c639b9893e885d8937e29ed7d47a7c28bc6b6..7e0cf9b9f94b16741358bdb45122f8b2
// |error| is strerror(errno) when a P* logging function is called. Pass
diff --git a/sandbox/mac/seatbelt.cc b/sandbox/mac/seatbelt.cc
-index 15c835e118456394c0a00ac98c11241c14ca75bd..a16faabe2bd63a5e0fbe9082a3b4b7c8aa0ea064 100644
+index 1960e1c8771fad615a098af09ff1f9a191f67764..29b97b352d08cd1fe73b17fd80cb41cc7e58dcaa 100644
--- a/sandbox/mac/seatbelt.cc
+++ b/sandbox/mac/seatbelt.cc
@@ -4,12 +4,14 @@
@@ -1220,14 +1190,21 @@ index 15c835e118456394c0a00ac98c11241c14ca75bd..a16faabe2bd63a5e0fbe9082a3b4b7c8
}
// static
-@@ -129,10 +147,14 @@ bool Seatbelt::InitWithParams(const char* profile,
+@@ -129,16 +147,21 @@ bool Seatbelt::InitWithParams(const std::string& profile,
uint64_t flags,
- const char* const parameters[],
+ const std::vector<std::string>& parameters,
std::string* error) {
+#if !IS_MAS_BUILD()
+ std::vector<const char*> weak_params;
+ for (const std::string& param : parameters) {
+ weak_params.push_back(param.c_str());
+ }
+ // The parameters array must be null terminated.
+ weak_params.push_back(nullptr);
++
char* errorbuf = nullptr;
- int rv =
- ::sandbox_init_with_parameters(profile, flags, parameters, &errorbuf);
+ int rv = ::sandbox_init_with_parameters(profile.c_str(), flags,
+ weak_params.data(), &errorbuf);
return HandleSandboxResult(rv, errorbuf, error);
+#else
+ return true;
@@ -1235,7 +1212,7 @@ index 15c835e118456394c0a00ac98c11241c14ca75bd..a16faabe2bd63a5e0fbe9082a3b4b7c8
}
// static
-@@ -140,6 +162,7 @@ bool Seatbelt::Compile(const char* profile,
+@@ -146,6 +169,7 @@ bool Seatbelt::Compile(const char* profile,
const Seatbelt::Parameters& params,
std::string& compiled_profile,
std::string* error) {
@@ -1243,7 +1220,7 @@ index 15c835e118456394c0a00ac98c11241c14ca75bd..a16faabe2bd63a5e0fbe9082a3b4b7c8
char* errorbuf = nullptr;
sandbox_profile_t* sandbox_profile =
::sandbox_compile_string(profile, params.params(), &errorbuf);
-@@ -149,33 +172,44 @@ bool Seatbelt::Compile(const char* profile,
+@@ -155,33 +179,44 @@ bool Seatbelt::Compile(const char* profile,
compiled_profile.assign(reinterpret_cast<const char*>(sandbox_profile->data),
sandbox_profile->size);
::sandbox_free_profile(sandbox_profile);
@@ -1392,7 +1369,7 @@ index eb81a70e4d5d5cd3e6ae9b45f8cd1c795ea76c51..9921ccb10d3455600eddd85f77f10228
} // namespace sandbox
diff --git a/third_party/blink/renderer/core/BUILD.gn b/third_party/blink/renderer/core/BUILD.gn
-index 076ae475b3c4f0d2568e5efc9fedf2de7ccc82ad..b961c9c000bbb82c5f6ae63466c6d5d679d92de6 100644
+index 17b3ddd66513a01a631d77535cfeb1ae94881e0e..bde6c61489fe4f88abba79fd2fb809c292a3f99a 100644
--- a/third_party/blink/renderer/core/BUILD.gn
+++ b/third_party/blink/renderer/core/BUILD.gn
@@ -409,6 +409,7 @@ component("core") {
@@ -1634,7 +1611,7 @@ index c8171f0527fe5194f0ea73b57c4444d4c630fbc4..c2ac4da580e3e7f749a0a4de1e859af6
// Accessible object
if (AXElementWrapper::IsValidElement(value)) {
diff --git a/ui/base/BUILD.gn b/ui/base/BUILD.gn
-index 5ca4c8fc961d24985aa4e0459dc2c42003a5346f..2f5880d1d3fbc3aa1461bbe611c33f789a6f4dde 100644
+index f211074c41fd50597db8b72510149d27ffc8d90a..885511f666318ce1218a09c3ebf5ec1aa00e9ecf 100644
--- a/ui/base/BUILD.gn
+++ b/ui/base/BUILD.gn
@@ -363,6 +363,13 @@ component("base") {
@@ -1804,10 +1781,10 @@ index 29ae2da6a8a2c2a612dfb92f7f9c03ca5fa306b1..440c139a32a0c205e77b657d4aab6468
// Query the display's refresh rate.
if (@available(macos 12.0, *)) {
diff --git a/ui/gfx/BUILD.gn b/ui/gfx/BUILD.gn
-index 6cf9f1a38ed76edc8f64500476b4b3014dc7677f..54dcf71bd0bf5a1455b31f3d042305f0fc3e345b 100644
+index 230a9e8266fa494f870ed7fc7dc444d1db5bbb48..99facff7a8e98cbc175354ae4e1d1f592197320a 100644
--- a/ui/gfx/BUILD.gn
+++ b/ui/gfx/BUILD.gn
-@@ -331,6 +331,12 @@ component("gfx") {
+@@ -332,6 +332,12 @@ component("gfx") {
"//ui/base:ui_data_pack",
]
@@ -1859,7 +1836,7 @@ index fe3f85073e31de487a08e57d7f9b07aa4eccf8f3..cf5b07203c8bd559a404600cc98cc8ec
// enough.
return PlatformFontMac::SystemFontType::kGeneral;
diff --git a/ui/views/BUILD.gn b/ui/views/BUILD.gn
-index 94afec13361d4ee8d0441da3cbe37d62e287c94b..fd13add3291b113dc57c69700f35ac9943124786 100644
+index ee47ca61db4c321edce0d6ae49f9f6a21f01918a..c8fcad4a3af57cfb993018f0ad457c271bdefe0e 100644
--- a/ui/views/BUILD.gn
+++ b/ui/views/BUILD.gn
@@ -718,6 +718,8 @@ component("views") {
@@ -1871,7 +1848,7 @@ index 94afec13361d4ee8d0441da3cbe37d62e287c94b..fd13add3291b113dc57c69700f35ac99
}
if (is_win) {
-@@ -1135,6 +1137,8 @@ source_set("test_support") {
+@@ -1138,6 +1140,8 @@ source_set("test_support") {
"//ui/base/mojom:ui_base_types",
]
diff --git a/shell/browser/api/electron_api_cookies.cc b/shell/browser/api/electron_api_cookies.cc
index fbd37fec81..c9292d4c12 100644
--- a/shell/browser/api/electron_api_cookies.cc
+++ b/shell/browser/api/electron_api_cookies.cc
@@ -250,11 +250,7 @@ const std::string InclusionStatusToString(net::CookieInclusionStatus status) {
{Reason::EXCLUDE_THIRD_PARTY_PHASEOUT,
"The cookie is blocked for third-party cookie phaseout."},
{Reason::EXCLUDE_NO_COOKIE_CONTENT,
- "The cookie contains no content or only whitespace."},
- {Reason::EXCLUDE_ALIASING,
- "Cookie aliases that of another with a different source_port or "
- "source scheme. I.e.: Two or more cookies share the same name "
- "but have different ports/schemes."}});
+ "The cookie contains no content or only whitespace."}});
static_assert(
Reasons.size() ==
net::CookieInclusionStatus::ExclusionReasonBitset::kValueCount,
diff --git a/shell/browser/browser_process_impl.h b/shell/browser/browser_process_impl.h
index ef663f7c95..cd8c00243b 100644
--- a/shell/browser/browser_process_impl.h
+++ b/shell/browser/browser_process_impl.h
@@ -70,6 +70,7 @@ class BrowserProcessImpl : public BrowserProcess {
// BrowserProcess
BuildState* GetBuildState() override;
GlobalFeatures* GetFeatures() override;
+ void CreateGlobalFeaturesForTesting() override {}
void EndSession() override {}
void FlushLocalStateAndReply(base::OnceClosure reply) override {}
bool IsShuttingDown() override;
diff --git a/shell/browser/electron_pdf_document_helper_client.h b/shell/browser/electron_pdf_document_helper_client.h
index 94eb3c7452..137af0f251 100644
--- a/shell/browser/electron_pdf_document_helper_client.h
+++ b/shell/browser/electron_pdf_document_helper_client.h
@@ -20,7 +20,6 @@ class ElectronPDFDocumentHelperClient : public pdf::PDFDocumentHelperClient {
// pdf::PDFDocumentHelperClient
void UpdateContentRestrictions(content::RenderFrameHost* render_frame_host,
int content_restrictions) override;
- void OnPDFHasUnsupportedFeature(content::WebContents* contents) override {}
void OnSaveURL(content::WebContents* contents) override {}
void SetPluginCanSave(content::RenderFrameHost* render_frame_host,
bool can_save) override;
diff --git a/shell/browser/extensions/electron_extension_loader.cc b/shell/browser/extensions/electron_extension_loader.cc
index 03c37fdfec..2930274eb6 100644
--- a/shell/browser/extensions/electron_extension_loader.cc
+++ b/shell/browser/extensions/electron_extension_loader.cc
@@ -181,8 +181,7 @@ void ElectronExtensionLoader::PreAddExtension(const Extension* extension,
extension_prefs->RemoveDisableReason(extension->id(),
disable_reason::DISABLE_RELOAD);
// Only re-enable the extension if there are no other disable reasons.
- if (extension_prefs->GetDisableReasons(extension->id()) ==
- disable_reason::DISABLE_NONE) {
+ if (extension_prefs->GetDisableReasons(extension->id()).empty()) {
extension_prefs->SetExtensionEnabled(extension->id());
}
}
diff --git a/shell/browser/native_window_views.cc b/shell/browser/native_window_views.cc
index 44de6c197f..a74e0ef365 100644
--- a/shell/browser/native_window_views.cc
+++ b/shell/browser/native_window_views.cc
@@ -1636,8 +1636,8 @@ gfx::Rect NativeWindowViews::WindowBoundsToContentBounds(
#if BUILDFLAG(IS_WIN)
void NativeWindowViews::SetIcon(HICON window_icon, HICON app_icon) {
// We are responsible for storing the images.
- window_icon_ = base::win::ScopedHICON(CopyIcon(window_icon));
- app_icon_ = base::win::ScopedHICON(CopyIcon(app_icon));
+ window_icon_ = base::win::ScopedGDIObject<HICON>(CopyIcon(window_icon));
+ app_icon_ = base::win::ScopedGDIObject<HICON>(CopyIcon(app_icon));
HWND hwnd = GetAcceleratedWidget();
SendMessage(hwnd, WM_SETICON, ICON_SMALL,
diff --git a/shell/browser/native_window_views.h b/shell/browser/native_window_views.h
index fe2c3a197b..4f3c38bedb 100644
--- a/shell/browser/native_window_views.h
+++ b/shell/browser/native_window_views.h
@@ -277,8 +277,8 @@ class NativeWindowViews : public NativeWindow,
gfx::Rect restore_bounds_;
// The icons of window and taskbar.
- base::win::ScopedHICON window_icon_;
- base::win::ScopedHICON app_icon_;
+ base::win::ScopedGDIObject<HICON> window_icon_;
+ base::win::ScopedGDIObject<HICON> app_icon_;
// The set of windows currently forwarding mouse messages.
static std::set<NativeWindowViews*> forwarding_windows_;
diff --git a/shell/browser/osr/osr_video_consumer.cc b/shell/browser/osr/osr_video_consumer.cc
index 62efaf6261..a09cb46f20 100644
--- a/shell/browser/osr/osr_video_consumer.cc
+++ b/shell/browser/osr/osr_video_consumer.cc
@@ -99,7 +99,7 @@ void OffScreenVideoConsumer::OnFrameCaptured(
#if BUILDFLAG(IS_WIN)
texture.shared_texture_handle =
- reinterpret_cast<uintptr_t>(gmb_handle.dxgi_handle.Get());
+ reinterpret_cast<uintptr_t>(gmb_handle.dxgi_handle().buffer_handle());
#elif BUILDFLAG(IS_APPLE)
texture.shared_texture_handle =
reinterpret_cast<uintptr_t>(gmb_handle.io_surface.get());
diff --git a/shell/browser/ui/message_box_win.cc b/shell/browser/ui/message_box_win.cc
index 3761ccd7d3..2b513e50c7 100644
--- a/shell/browser/ui/message_box_win.cc
+++ b/shell/browser/ui/message_box_win.cc
@@ -176,7 +176,7 @@ DialogResult ShowTaskDialogWstr(gfx::AcceleratedWidget parent,
config.pszWindowTitle = base::as_wcstr(title);
}
- base::win::ScopedHICON hicon;
+ base::win::ScopedGDIObject<HICON> hicon;
if (!icon.isNull()) {
hicon = IconUtil::CreateHICONFromSkBitmap(*icon.bitmap());
config.dwFlags |= TDF_USE_HICON_MAIN;
diff --git a/shell/browser/ui/win/notify_icon.cc b/shell/browser/ui/win/notify_icon.cc
index beaca1675b..9beadca880 100644
--- a/shell/browser/ui/win/notify_icon.cc
+++ b/shell/browser/ui/win/notify_icon.cc
@@ -129,7 +129,7 @@ void NotifyIcon::ResetIcon() {
}
void NotifyIcon::SetImage(HICON image) {
- icon_ = base::win::ScopedHICON(CopyIcon(image));
+ icon_ = base::win::ScopedGDIObject<HICON>(CopyIcon(image));
// Create the icon.
NOTIFYICONDATA icon_data;
diff --git a/shell/browser/ui/win/notify_icon.h b/shell/browser/ui/win/notify_icon.h
index d41a3b642d..0f49f8bbb9 100644
--- a/shell/browser/ui/win/notify_icon.h
+++ b/shell/browser/ui/win/notify_icon.h
@@ -91,7 +91,7 @@ class NotifyIcon : public TrayIcon {
UINT message_id_;
// The currently-displayed icon for the window.
- base::win::ScopedHICON icon_;
+ base::win::ScopedGDIObject<HICON> icon_;
// The context menu.
raw_ptr<ElectronMenuModel> menu_model_ = nullptr;
diff --git a/shell/browser/ui/win/taskbar_host.cc b/shell/browser/ui/win/taskbar_host.cc
index 568067fa02..f94950eb57 100644
--- a/shell/browser/ui/win/taskbar_host.cc
+++ b/shell/browser/ui/win/taskbar_host.cc
@@ -73,7 +73,8 @@ bool TaskbarHost::SetThumbarButtons(HWND window,
// The number of buttons in thumbar can not be changed once it is created,
// so we have to claim kMaxButtonsCount buttons initially in case users add
// more buttons later.
- auto icons = std::array<base::win::ScopedHICON, kMaxButtonsCount>{};
+ auto icons =
+ std::array<base::win::ScopedGDIObject<HICON>, kMaxButtonsCount>{};
auto thumb_buttons = std::array<THUMBBUTTON, kMaxButtonsCount>{};
for (size_t i = 0U; i < kMaxButtonsCount; ++i) {
diff --git a/shell/common/api/electron_api_native_image.cc b/shell/common/api/electron_api_native_image.cc
index 18b468370f..a6e2700360 100644
--- a/shell/common/api/electron_api_native_image.cc
+++ b/shell/common/api/electron_api_native_image.cc
@@ -102,7 +102,8 @@ bool IsTemplateFilename(const base::FilePath& path) {
#endif
#if BUILDFLAG(IS_WIN)
-base::win::ScopedHICON ReadICOFromPath(int size, const base::FilePath& path) {
+base::win::ScopedGDIObject<HICON> ReadICOFromPath(int size,
+ const base::FilePath& path) {
// If file is in asar archive, we extract it to a temp file so LoadImage can
// load it.
base::FilePath asar_path, relative_path;
@@ -115,7 +116,7 @@ base::win::ScopedHICON ReadICOFromPath(int size, const base::FilePath& path) {
}
// Load the icon from file.
- return base::win::ScopedHICON(
+ return base::win::ScopedGDIObject<HICON>(
static_cast<HICON>(LoadImage(nullptr, image_path.value().c_str(),
IMAGE_ICON, size, size, LR_LOADFROMFILE)));
}
diff --git a/shell/common/api/electron_api_native_image.h b/shell/common/api/electron_api_native_image.h
index a840c51445..60f4acb1a5 100644
--- a/shell/common/api/electron_api_native_image.h
+++ b/shell/common/api/electron_api_native_image.h
@@ -134,7 +134,7 @@ class NativeImage final : public gin::Wrappable<NativeImage> {
base::FilePath hicon_path_;
// size -> hicon
- base::flat_map<int, base::win::ScopedHICON> hicons_;
+ base::flat_map<int, base::win::ScopedGDIObject<HICON>> hicons_;
#endif
gfx::Image image_;
diff --git a/shell/common/api/electron_api_native_image_win.cc b/shell/common/api/electron_api_native_image_win.cc
index 4bc5e8f4b9..53f1fe7137 100644
--- a/shell/common/api/electron_api_native_image_win.cc
+++ b/shell/common/api/electron_api_native_image_win.cc
@@ -90,7 +90,7 @@ v8::Local<v8::Promise> NativeImage::CreateThumbnailFromPath(
icon_info.hbmMask = hBitmap;
icon_info.hbmColor = hBitmap;
- base::win::ScopedHICON icon(CreateIconIndirect(&icon_info));
+ base::win::ScopedGDIObject<HICON> icon(CreateIconIndirect(&icon_info));
SkBitmap skbitmap = IconUtil::CreateSkBitmapFromHICON(icon.get());
gfx::ImageSkia image_skia =
gfx::ImageSkia::CreateFromBitmap(skbitmap, 1.0 /*scale factor*/);
diff --git a/spec/api-content-tracing-spec.ts b/spec/api-content-tracing-spec.ts
index ccd8fbde10..b3be18f9c0 100644
--- a/spec/api-content-tracing-spec.ts
+++ b/spec/api-content-tracing-spec.ts
@@ -6,7 +6,7 @@ import * as fs from 'node:fs';
import * as path from 'node:path';
import { setTimeout } from 'node:timers/promises';
-import { ifdescribe } from './lib/spec-helpers';
+import { ifdescribe, ifit } from './lib/spec-helpers';
// FIXME: The tests are skipped on linux arm/arm64
ifdescribe(!(['arm', 'arm64'].includes(process.arch)) || (process.platform !== 'linux'))('contentTracing', () => {
@@ -112,7 +112,8 @@ ifdescribe(!(['arm', 'arm64'].includes(process.arch)) || (process.platform !== '
expect(fs.statSync(path).isFile()).to.be.true('output exists');
});
- it('calls its callback with a result file path', async () => {
+ // FIXME(ckerr): this test regularly flakes
+ ifit(process.platform !== 'linux')('calls its callback with a result file path', async () => {
const resultFilePath = await record(/* options */ {}, outputFilePath);
expect(resultFilePath).to.be.a('string').and.be.equal(outputFilePath);
});
|
chore
|
a8622aed7b6c378b25c39cc025552412dccf2538
|
Charles Kerr
|
2023-07-13 01:37:43
|
perf: avoid redundant map lookup in NativeImage::GetHICON() (#39058)
perf: avoid double map lookup in NativeImage::GetHICON()
|
diff --git a/shell/common/api/electron_api_native_image.cc b/shell/common/api/electron_api_native_image.cc
index 21785db9ea..9cb7b396ea 100644
--- a/shell/common/api/electron_api_native_image.cc
+++ b/shell/common/api/electron_api_native_image.cc
@@ -202,21 +202,23 @@ bool NativeImage::TryConvertNativeImage(v8::Isolate* isolate,
#if BUILDFLAG(IS_WIN)
HICON NativeImage::GetHICON(int size) {
- auto iter = hicons_.find(size);
- if (iter != hicons_.end())
+ if (auto iter = hicons_.find(size); iter != hicons_.end())
return iter->second.get();
// First try loading the icon with specified size.
if (!hicon_path_.empty()) {
- hicons_[size] = ReadICOFromPath(size, hicon_path_);
- return hicons_[size].get();
+ auto& hicon = hicons_[size];
+ hicon = ReadICOFromPath(size, hicon_path_);
+ return hicon.get();
}
// Then convert the image to ICO.
if (image_.IsEmpty())
return NULL;
- hicons_[size] = IconUtil::CreateHICONFromSkBitmap(image_.AsBitmap());
- return hicons_[size].get();
+
+ auto& hicon = hicons_[size];
+ hicon = IconUtil::CreateHICONFromSkBitmap(image_.AsBitmap());
+ return hicon.get();
}
#endif
|
perf
|
a0a13ad623d2f0beae8b2574a22cf012100e6b6b
|
Samuel Attard
|
2024-06-17 16:33:44
|
build: fix macOS tests on GHA (#42524)
* build: use --frozen-lockfile
* build: don't include src/electron in src artifacts
* Use mac intel runner for mac-x64 tests
* test: debug mac tests not exiting
* skip navigator.serial tests on GHA
* TCC magic
* Fix release notes tests needing ELECTRON_GITHUB_TOKEN
* Add Azure env vars to gn check pipeline segment
* use RO token for tests
* temporarily disable codesign tests
* test: disable LoginItemSettings on x64 macOS
* test: bump up time on protocol test for slower machines
* fixup: use RO token for tests
---------
Co-authored-by: Shelley Vohr <[email protected]>
Co-authored-by: John Kleinschmidt <[email protected]>
|
diff --git a/.github/actions/checkout/action.yml b/.github/actions/checkout/action.yml
index 241e93c67b..e9481a3eac 100644
--- a/.github/actions/checkout/action.yml
+++ b/.github/actions/checkout/action.yml
@@ -16,7 +16,7 @@ runs:
shell: bash
run: |
cd src/electron
- node script/yarn install
+ node script/yarn install --frozen-lockfile
- name: Get Depot Tools
shell: bash
run: |
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index 5fa22cbdf3..7df8ce2353 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -109,11 +109,15 @@ jobs:
# Build Jobs - These cascade into testing jobs
macos-x64:
+ permissions:
+ contents: read
+ issues: read
+ pull-requests: read
uses: ./.github/workflows/pipeline-electron-build-and-test.yml
needs: checkout-macos
with:
build-runs-on: macos-14-xlarge
- test-runs-on: macos-14-xlarge
+ test-runs-on: macos-13
target-platform: macos
target-arch: x64
is-release: false
@@ -123,11 +127,15 @@ jobs:
secrets: inherit
macos-arm64:
+ permissions:
+ contents: read
+ issues: read
+ pull-requests: read
uses: ./.github/workflows/pipeline-electron-build-and-test.yml
needs: checkout-macos
with:
build-runs-on: macos-14-xlarge
- test-runs-on: macos-14-xlarge
+ test-runs-on: macos-14
target-platform: macos
target-arch: arm64
is-release: false
@@ -137,6 +145,10 @@ jobs:
secrets: inherit
linux-x64:
+ permissions:
+ contents: read
+ issues: read
+ pull-requests: read
uses: ./.github/workflows/pipeline-electron-build-and-test-and-nan.yml
needs: checkout-linux
with:
@@ -153,6 +165,10 @@ jobs:
secrets: inherit
linux-arm:
+ permissions:
+ contents: read
+ issues: read
+ pull-requests: read
uses: ./.github/workflows/pipeline-electron-build-and-test.yml
needs: checkout-linux
with:
@@ -169,6 +185,10 @@ jobs:
secrets: inherit
linux-arm64:
+ permissions:
+ contents: read
+ issues: read
+ pull-requests: read
uses: ./.github/workflows/pipeline-electron-build-and-test.yml
needs: checkout-linux
with:
diff --git a/.github/workflows/pipeline-electron-build-and-test.yml b/.github/workflows/pipeline-electron-build-and-test.yml
index f61fa6a07d..37b79751be 100644
--- a/.github/workflows/pipeline-electron-build-and-test.yml
+++ b/.github/workflows/pipeline-electron-build-and-test.yml
@@ -54,6 +54,11 @@ concurrency:
group: electron-build-and-test-${{ inputs.target-platform }}-${{ inputs.target-arch }}-${{ github.ref }}
cancel-in-progress: ${{ github.ref != 'refs/heads/main' && !endsWith(github.ref, '-x-y') }}
+permissions:
+ contents: read
+ issues: read
+ pull-requests: read
+
jobs:
build:
uses: ./.github/workflows/pipeline-segment-electron-build.yml
diff --git a/.github/workflows/pipeline-electron-docs-only.yml b/.github/workflows/pipeline-electron-docs-only.yml
index f5b67d9a97..5086393f96 100644
--- a/.github/workflows/pipeline-electron-docs-only.yml
+++ b/.github/workflows/pipeline-electron-docs-only.yml
@@ -27,7 +27,7 @@ jobs:
- name: Install Dependencies
run: |
cd src/electron
- node script/yarn install
+ node script/yarn install --frozen-lockfile
- name: Run TS/JS compile
shell: bash
run: |
diff --git a/.github/workflows/pipeline-electron-lint.yml b/.github/workflows/pipeline-electron-lint.yml
index ebb62ecb6f..ed48a2cd15 100644
--- a/.github/workflows/pipeline-electron-lint.yml
+++ b/.github/workflows/pipeline-electron-lint.yml
@@ -27,7 +27,7 @@ jobs:
- name: Install Dependencies
run: |
cd src/electron
- node script/yarn install
+ node script/yarn install --frozen-lockfile
- name: Setup third_party Depot Tools
shell: bash
run: |
diff --git a/.github/workflows/pipeline-segment-electron-build.yml b/.github/workflows/pipeline-segment-electron-build.yml
index c8ab252849..a433c1a1d4 100644
--- a/.github/workflows/pipeline-segment-electron-build.yml
+++ b/.github/workflows/pipeline-segment-electron-build.yml
@@ -89,7 +89,7 @@ jobs:
- name: Install Dependencies
run: |
cd src/electron
- node script/yarn install
+ node script/yarn install --frozen-lockfile
- name: Install AZCopy
if: ${{ inputs.target-platform == 'macos' }}
run: brew install azcopy
diff --git a/.github/workflows/pipeline-segment-electron-test.yml b/.github/workflows/pipeline-segment-electron-test.yml
index 5386eedb65..a59bbe72f3 100644
--- a/.github/workflows/pipeline-segment-electron-test.yml
+++ b/.github/workflows/pipeline-segment-electron-test.yml
@@ -24,9 +24,16 @@ on:
concurrency:
group: electron-test-${{ inputs.target-platform }}-${{ inputs.target-arch }}-${{ github.ref }}
cancel-in-progress: ${{ github.ref != 'refs/heads/main' && !endsWith(github.ref, '-x-y') }}
+
+permissions:
+ contents: read
+ issues: read
+ pull-requests: read
+
env:
ELECTRON_OUT_DIR: Default
ELECTRON_RBE_JWT: ${{ secrets.ELECTRON_RBE_JWT }}
+ ELECTRON_GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
jobs:
test:
@@ -36,7 +43,7 @@ jobs:
fail-fast: false
matrix:
build-type: ${{ inputs.target-platform == 'macos' && fromJSON('["darwin","mas"]') || fromJSON('["linux"]') }}
- shard: ${{ inputs.target-platform == 'macos' && fromJSON('[1]') || fromJSON('[1, 2, 3]') }}
+ shard: ${{ inputs.target-platform == 'macos' && fromJSON('[1, 2]') || fromJSON('[1, 2, 3]') }}
env:
BUILD_TYPE: ${{ matrix.build-type }}
TARGET_ARCH: ${{ inputs.target-arch }}
@@ -45,6 +52,39 @@ jobs:
if: ${{ inputs.target-arch == 'arm' }}
run: |
cp $(which node) /mnt/runner-externals/node20/bin/
+ - name: Add TCC permissions on macOS
+ if: ${{ inputs.target-platform == 'macos' }}
+ run: |
+ configure_user_tccdb () {
+ local values=$1
+ local dbPath="$HOME/Library/Application Support/com.apple.TCC/TCC.db"
+ local sqlQuery="INSERT OR REPLACE INTO access VALUES($values);"
+ sqlite3 "$dbPath" "$sqlQuery"
+ }
+
+ configure_sys_tccdb () {
+ local values=$1
+ local dbPath="/Library/Application Support/com.apple.TCC/TCC.db"
+ local sqlQuery="INSERT OR REPLACE INTO access VALUES($values);"
+ sudo sqlite3 "$dbPath" "$sqlQuery"
+ }
+
+ userValuesArray=(
+ "'kTCCServiceMicrophone','/usr/local/opt/runner/provisioner/provisioner',1,2,4,1,NULL,NULL,0,'UNUSED',NULL,0,1687786159"
+ "'kTCCServiceCamera','/usr/local/opt/runner/provisioner/provisioner',1,2,4,1,NULL,NULL,0,'UNUSED',NULL,0,1687786159"
+ "'kTCCServiceBluetoothAlways','/usr/local/opt/runner/provisioner/provisioner',1,2,4,1,NULL,NULL,0,'UNUSED',NULL,0,1687786159"
+ )
+ for values in "${userValuesArray[@]}"; do
+ # Sonoma and higher have a few extra values
+ # Ref: https://github.com/actions/runner-images/blob/main/images/macos/scripts/build/configure-tccdb-macos.sh
+ if [ "$OSTYPE" = "darwin23" ]; then
+ configure_user_tccdb "$values,NULL,NULL,'UNUSED',${values##*,}"
+ configure_sys_tccdb "$values,NULL,NULL,'UNUSED',${values##*,}"
+ else
+ configure_user_tccdb "$values"
+ configure_sys_tccdb "$values"
+ fi
+ done
- name: Checkout Electron
uses: actions/checkout@a5ac7e51b41094c92402da3b24376905380afc29
with:
@@ -53,7 +93,7 @@ jobs:
- name: Install Dependencies
run: |
cd src/electron
- node script/yarn install
+ node script/yarn install --frozen-lockfile
- name: Get Depot Tools
timeout-minutes: 5
run: |
@@ -97,6 +137,7 @@ jobs:
# cd src/electron
# ./script/codesign/generate-identity.sh
- name: Run Electron Tests
+ shell: bash
env:
MOCHA_REPORTER: mocha-multi-reporters
ELECTRON_TEST_RESULTS_DIR: junit
@@ -107,11 +148,12 @@ jobs:
run: |
cd src/electron
# Get which tests are on this shard
- tests_files=$(node script/split-tests ${{ matrix.shard }} ${{ inputs.target-platform == 'macos' && 1 || 3 }})
+ tests_files=$(node script/split-tests ${{ matrix.shard }} ${{ inputs.target-platform == 'macos' && 2 || 3 }})
# Run tests
if [ "`uname`" = "Darwin" ]; then
- node script/yarn test --runners=main --trace-uncaught --enable-logging
+ echo "About to start tests"
+ node script/yarn test --runners=main --trace-uncaught --enable-logging --files $tests_files
else
chown :builduser .. && chmod g+w ..
chown -R :builduser . && chmod -R g+w .
diff --git a/.github/workflows/pipeline-segment-node-nan-test.yml b/.github/workflows/pipeline-segment-node-nan-test.yml
index 5f0bb5a474..fcc3df1978 100644
--- a/.github/workflows/pipeline-segment-node-nan-test.yml
+++ b/.github/workflows/pipeline-segment-node-nan-test.yml
@@ -57,7 +57,7 @@ jobs:
- name: Install Dependencies
run: |
cd src/electron
- node script/yarn install
+ node script/yarn install --frozen-lockfile
- name: Get Depot Tools
timeout-minutes: 5
run: |
@@ -121,7 +121,7 @@ jobs:
- name: Install Dependencies
run: |
cd src/electron
- node script/yarn install
+ node script/yarn install --frozen-lockfile
- name: Get Depot Tools
timeout-minutes: 5
run: |
diff --git a/script/actions/move-artifacts.sh b/script/actions/move-artifacts.sh
index e4030b300c..eff0ba7472 100755
--- a/script/actions/move-artifacts.sh
+++ b/script/actions/move-artifacts.sh
@@ -51,7 +51,6 @@ move_src_dirs_if_exist() {
src/out/Default/overlapped-checker \
src/out/Default/ffmpeg \
src/out/Default/hunspell_dictionaries \
- src/electron \
src/third_party/electron_node \
src/third_party/nan \
src/cross-arch-snapshots \
diff --git a/spec/api-app-spec.ts b/spec/api-app-spec.ts
index 491f1cc859..277cf38084 100644
--- a/spec/api-app-spec.ts
+++ b/spec/api-app-spec.ts
@@ -595,7 +595,7 @@ describe('app module', () => {
});
});
- ifdescribe(process.platform !== 'linux' && !process.mas)('app.get/setLoginItemSettings API', function () {
+ ifdescribe(process.platform !== 'linux' && !process.mas && (process.platform !== 'darwin' || process.arch === 'arm64'))('app.get/setLoginItemSettings API', function () {
const isMac = process.platform === 'darwin';
const isWin = process.platform === 'win32';
diff --git a/spec/api-protocol-spec.ts b/spec/api-protocol-spec.ts
index 122cc4e84f..3ba77351d8 100644
--- a/spec/api-protocol-spec.ts
+++ b/spec/api-protocol-spec.ts
@@ -1749,7 +1749,7 @@ describe('protocol module', () => {
const end = Date.now();
return end - begin;
})();
- expect(interceptedTime).to.be.lessThan(rawTime * 1.5);
+ expect(interceptedTime).to.be.lessThan(rawTime * 1.6);
});
});
});
diff --git a/spec/lib/codesign-helpers.ts b/spec/lib/codesign-helpers.ts
index 58c08b1e05..ca5caa5147 100644
--- a/spec/lib/codesign-helpers.ts
+++ b/spec/lib/codesign-helpers.ts
@@ -8,7 +8,7 @@ const fixturesPath = path.resolve(__dirname, '..', 'fixtures');
export const shouldRunCodesignTests =
process.platform === 'darwin' &&
- !(process.env.CI && process.arch === 'arm64') &&
+ !process.env.CI &&
!process.mas &&
!features.isComponentBuild();
|
build
|
77ba40bc01a206b5c3bac27cd6143adabd46d437
|
BILL SHEN
|
2024-07-26 21:34:40
|
chore: avoid crash while notification removal (#43040)
* avoid crash of operation on an invalid entry while erase set iterator.
* fix notification removal crash due to the nullptr presenter
---------
Co-authored-by: bill.shen <[email protected]>
|
diff --git a/shell/browser/notifications/notification.cc b/shell/browser/notifications/notification.cc
index 40b5f846fd..9dae5fc56b 100644
--- a/shell/browser/notifications/notification.cc
+++ b/shell/browser/notifications/notification.cc
@@ -46,7 +46,9 @@ void Notification::NotificationFailed(const std::string& error) {
void Notification::Remove() {}
void Notification::Destroy() {
- presenter()->RemoveNotification(this);
+ if (presenter()) {
+ presenter()->RemoveNotification(this);
+ }
}
} // namespace electron
diff --git a/shell/browser/notifications/notification_presenter.cc b/shell/browser/notifications/notification_presenter.cc
index 4aef716a72..0bfb5c049c 100644
--- a/shell/browser/notifications/notification_presenter.cc
+++ b/shell/browser/notifications/notification_presenter.cc
@@ -27,6 +27,11 @@ base::WeakPtr<Notification> NotificationPresenter::CreateNotification(
}
void NotificationPresenter::RemoveNotification(Notification* notification) {
+ auto it = notifications_.find(notification);
+ if (it == notifications_.end()) {
+ return;
+ }
+
notifications_.erase(notification);
delete notification;
}
|
chore
|
bcb7362ab9807cc5e1a6efc262ff9fdb746498d5
|
Charles Kerr
|
2024-09-19 23:35:21
|
docs: document Windows pitfall when updating patches (#43787)
|
diff --git a/docs/development/patches.md b/docs/development/patches.md
index 634a35c355..e7c744f34a 100644
--- a/docs/development/patches.md
+++ b/docs/development/patches.md
@@ -65,6 +65,8 @@ $ git rebase --autosquash -i [COMMIT_SHA]^
$ ../electron/script/git-export-patches -o ../electron/patches/v8
```
+Note that the `^` symbol [can cause trouble on Windows](https://stackoverflow.com/questions/14203952/git-reset-asks-more/14204318#14204318). The workaround is to either quote it `"[COMMIT_SHA]^"` or avoid it `[COMMIT_SHA]~1`.
+
#### Removing a patch
```bash
|
docs
|
46fb0d8f5f3a33c5b9bba2329ac5de946cd66a3c
|
Shelley Vohr
|
2023-06-15 16:46:38
|
fix: `webContents.print({ silent: true })` not working correctly (#38741)
fix: webContents.print({ silent: true }) not working correctly
|
diff --git a/patches/chromium/printing.patch b/patches/chromium/printing.patch
index dd1dddb209..2085b41bb4 100644
--- a/patches/chromium/printing.patch
+++ b/patches/chromium/printing.patch
@@ -91,7 +91,7 @@ index 3a66a52b8d3c6da9cd8d7e9afdc8d59f528ec3d5..facaa6fbca8ee7c04f83607e62b81b95
: PdfRenderSettings::Mode::POSTSCRIPT_LEVEL3;
}
diff --git a/chrome/browser/printing/print_view_manager_base.cc b/chrome/browser/printing/print_view_manager_base.cc
-index 2bb42383d753ac39953adf5dccf1cbc02f100b88..65f2ad490414f1631cb65ead5dafcffdd4ff2077 100644
+index 2bb42383d753ac39953adf5dccf1cbc02f100b88..2ff3f9391cb60082e2e72af8d9d82c9e33f2e7f6 100644
--- a/chrome/browser/printing/print_view_manager_base.cc
+++ b/chrome/browser/printing/print_view_manager_base.cc
@@ -23,7 +23,9 @@
@@ -212,7 +212,43 @@ index 2bb42383d753ac39953adf5dccf1cbc02f100b88..65f2ad490414f1631cb65ead5dafcffd
return true;
}
-@@ -451,7 +482,8 @@ void PrintViewManagerBase::GetDefaultPrintSettingsReply(
+@@ -323,12 +354,13 @@ void PrintViewManagerBase::OnDidUpdatePrintableArea(
+ }
+ PRINTER_LOG(EVENT) << "Paper printable area updated for vendor id "
+ << print_settings->requested_media().vendor_id;
+- CompleteUpdatePrintSettings(std::move(job_settings),
++ CompleteUpdatePrintSettings(nullptr /* printer_query */, std::move(job_settings),
+ std::move(print_settings), std::move(callback));
+ }
+ #endif
+
+ void PrintViewManagerBase::CompleteUpdatePrintSettings(
++ std::unique_ptr<PrinterQuery> printer_query,
+ base::Value::Dict job_settings,
+ std::unique_ptr<PrintSettings> print_settings,
+ UpdatePrintSettingsCallback callback) {
+@@ -336,7 +368,8 @@ void PrintViewManagerBase::CompleteUpdatePrintSettings(
+ settings->pages = GetPageRangesFromJobSettings(job_settings);
+ settings->params = mojom::PrintParams::New();
+ RenderParamsFromPrintSettings(*print_settings, settings->params.get());
+- settings->params->document_cookie = PrintSettings::NewCookie();
++ settings->params->document_cookie = printer_query ? printer_query->cookie()
++ : PrintSettings::NewCookie();
+ if (!PrintMsgPrintParamsIsValid(*settings->params)) {
+ mojom::PrinterType printer_type = static_cast<mojom::PrinterType>(
+ *job_settings.FindInt(kSettingPrinterType));
+@@ -348,6 +381,10 @@ void PrintViewManagerBase::CompleteUpdatePrintSettings(
+ return;
+ }
+
++ if (printer_query && printer_query->cookie() && printer_query->settings().dpi()) {
++ queue_->QueuePrinterQuery(std::move(printer_query));
++ }
++
+ set_cookie(settings->params->document_cookie);
+ std::move(callback).Run(std::move(settings));
+ }
+@@ -451,7 +488,8 @@ void PrintViewManagerBase::GetDefaultPrintSettingsReply(
void PrintViewManagerBase::ScriptedPrintReply(
ScriptedPrintCallback callback,
int process_id,
@@ -222,7 +258,7 @@ index 2bb42383d753ac39953adf5dccf1cbc02f100b88..65f2ad490414f1631cb65ead5dafcffd
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
#if BUILDFLAG(ENABLE_OOP_PRINTING)
-@@ -466,12 +498,15 @@ void PrintViewManagerBase::ScriptedPrintReply(
+@@ -466,12 +504,15 @@ void PrintViewManagerBase::ScriptedPrintReply(
return;
}
@@ -240,7 +276,7 @@ index 2bb42383d753ac39953adf5dccf1cbc02f100b88..65f2ad490414f1631cb65ead5dafcffd
}
}
-@@ -608,10 +643,12 @@ void PrintViewManagerBase::DidPrintDocument(
+@@ -608,10 +649,12 @@ void PrintViewManagerBase::DidPrintDocument(
void PrintViewManagerBase::GetDefaultPrintSettings(
GetDefaultPrintSettingsCallback callback) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
@@ -253,7 +289,7 @@ index 2bb42383d753ac39953adf5dccf1cbc02f100b88..65f2ad490414f1631cb65ead5dafcffd
#if BUILDFLAG(ENABLE_OOP_PRINTING)
if (printing::features::kEnableOopPrintDriversJobPrint.Get() &&
#if BUILDFLAG(ENABLE_PRINT_CONTENT_ANALYSIS)
-@@ -662,10 +699,12 @@ void PrintViewManagerBase::UpdatePrintSettings(
+@@ -662,10 +705,12 @@ void PrintViewManagerBase::UpdatePrintSettings(
base::Value::Dict job_settings,
UpdatePrintSettingsCallback callback) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
@@ -266,7 +302,7 @@ index 2bb42383d753ac39953adf5dccf1cbc02f100b88..65f2ad490414f1631cb65ead5dafcffd
absl::optional<int> printer_type_value =
job_settings.FindInt(kSettingPrinterType);
-@@ -676,6 +715,7 @@ void PrintViewManagerBase::UpdatePrintSettings(
+@@ -676,6 +721,7 @@ void PrintViewManagerBase::UpdatePrintSettings(
mojom::PrinterType printer_type =
static_cast<mojom::PrinterType>(*printer_type_value);
@@ -274,7 +310,7 @@ index 2bb42383d753ac39953adf5dccf1cbc02f100b88..65f2ad490414f1631cb65ead5dafcffd
if (printer_type != mojom::PrinterType::kExtension &&
printer_type != mojom::PrinterType::kPdf &&
printer_type != mojom::PrinterType::kLocal) {
-@@ -695,6 +735,7 @@ void PrintViewManagerBase::UpdatePrintSettings(
+@@ -695,6 +741,7 @@ void PrintViewManagerBase::UpdatePrintSettings(
if (value > 0)
job_settings.Set(kSettingRasterizePdfDpi, value);
}
@@ -282,7 +318,32 @@ index 2bb42383d753ac39953adf5dccf1cbc02f100b88..65f2ad490414f1631cb65ead5dafcffd
std::unique_ptr<PrintSettings> print_settings =
PrintSettingsFromJobSettings(job_settings);
-@@ -744,7 +785,7 @@ void PrintViewManagerBase::UpdatePrintSettings(
+@@ -714,6 +761,16 @@ void PrintViewManagerBase::UpdatePrintSettings(
+ }
+ }
+
++ std::unique_ptr<PrinterQuery> query =
++ queue_->CreatePrinterQuery(GetCurrentTargetFrame()->GetGlobalId());
++ auto* query_ptr = query.get();
++ query_ptr->SetSettings(
++ job_settings.Clone(),
++ base::BindOnce(&PrintViewManagerBase::CompleteUpdatePrintSettings,
++ weak_ptr_factory_.GetWeakPtr(), std::move(query),
++ std::move(job_settings), std::move(print_settings),
++ std::move(callback)));
++
+ #if BUILDFLAG(IS_WIN)
+ // TODO(crbug.com/1424368): Remove this if the printable areas can be made
+ // fully available from `PrintBackend::GetPrinterSemanticCapsAndDefaults()`
+@@ -736,15 +793,13 @@ void PrintViewManagerBase::UpdatePrintSettings(
+ }
+ #endif
+
+- CompleteUpdatePrintSettings(std::move(job_settings),
+- std::move(print_settings), std::move(callback));
+ }
+ #endif // BUILDFLAG(ENABLE_PRINT_PREVIEW)
+
void PrintViewManagerBase::IsPrintingEnabled(
IsPrintingEnabledCallback callback) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
@@ -291,7 +352,7 @@ index 2bb42383d753ac39953adf5dccf1cbc02f100b88..65f2ad490414f1631cb65ead5dafcffd
}
void PrintViewManagerBase::ScriptedPrint(mojom::ScriptedPrintParamsPtr params,
-@@ -760,14 +801,14 @@ void PrintViewManagerBase::ScriptedPrint(mojom::ScriptedPrintParamsPtr params,
+@@ -760,14 +815,14 @@ void PrintViewManagerBase::ScriptedPrint(mojom::ScriptedPrintParamsPtr params,
// didn't happen for some reason.
bad_message::ReceivedBadMessage(
render_process_host, bad_message::PVMB_SCRIPTED_PRINT_FENCED_FRAME);
@@ -308,7 +369,7 @@ index 2bb42383d753ac39953adf5dccf1cbc02f100b88..65f2ad490414f1631cb65ead5dafcffd
return;
}
#endif
-@@ -802,6 +843,7 @@ void PrintViewManagerBase::PrintingFailed(int32_t cookie,
+@@ -802,6 +857,7 @@ void PrintViewManagerBase::PrintingFailed(int32_t cookie,
PrintManager::PrintingFailed(cookie, reason);
@@ -316,7 +377,7 @@ index 2bb42383d753ac39953adf5dccf1cbc02f100b88..65f2ad490414f1631cb65ead5dafcffd
// `PrintingFailed()` can occur because asynchronous compositing results
// don't complete until after a print job has already failed and been
// destroyed. In such cases the error notification to the user will
-@@ -811,7 +853,7 @@ void PrintViewManagerBase::PrintingFailed(int32_t cookie,
+@@ -811,7 +867,7 @@ void PrintViewManagerBase::PrintingFailed(int32_t cookie,
print_job_->document()->cookie() == cookie) {
ShowPrintErrorDialogForGenericError();
}
@@ -325,7 +386,7 @@ index 2bb42383d753ac39953adf5dccf1cbc02f100b88..65f2ad490414f1631cb65ead5dafcffd
ReleasePrinterQuery();
}
-@@ -823,15 +865,24 @@ void PrintViewManagerBase::RemoveTestObserver(TestObserver& observer) {
+@@ -823,15 +879,24 @@ void PrintViewManagerBase::RemoveTestObserver(TestObserver& observer) {
test_observers_.RemoveObserver(&observer);
}
@@ -350,7 +411,7 @@ index 2bb42383d753ac39953adf5dccf1cbc02f100b88..65f2ad490414f1631cb65ead5dafcffd
}
void PrintViewManagerBase::RenderFrameDeleted(
-@@ -883,7 +934,12 @@ void PrintViewManagerBase::OnJobDone() {
+@@ -883,7 +948,12 @@ void PrintViewManagerBase::OnJobDone() {
// Printing is done, we don't need it anymore.
// print_job_->is_job_pending() may still be true, depending on the order
// of object registration.
@@ -364,7 +425,7 @@ index 2bb42383d753ac39953adf5dccf1cbc02f100b88..65f2ad490414f1631cb65ead5dafcffd
ReleasePrintJob();
}
-@@ -892,9 +948,10 @@ void PrintViewManagerBase::OnCanceling() {
+@@ -892,9 +962,10 @@ void PrintViewManagerBase::OnCanceling() {
}
void PrintViewManagerBase::OnFailed() {
@@ -376,7 +437,7 @@ index 2bb42383d753ac39953adf5dccf1cbc02f100b88..65f2ad490414f1631cb65ead5dafcffd
TerminatePrintJob(true);
}
-@@ -904,7 +961,7 @@ bool PrintViewManagerBase::RenderAllMissingPagesNow() {
+@@ -904,7 +975,7 @@ bool PrintViewManagerBase::RenderAllMissingPagesNow() {
// Is the document already complete?
if (print_job_->document() && print_job_->document()->IsComplete()) {
@@ -385,7 +446,7 @@ index 2bb42383d753ac39953adf5dccf1cbc02f100b88..65f2ad490414f1631cb65ead5dafcffd
return true;
}
-@@ -952,7 +1009,10 @@ bool PrintViewManagerBase::CreateNewPrintJob(
+@@ -952,7 +1023,10 @@ bool PrintViewManagerBase::CreateNewPrintJob(
// Disconnect the current `print_job_`.
auto weak_this = weak_ptr_factory_.GetWeakPtr();
@@ -397,7 +458,7 @@ index 2bb42383d753ac39953adf5dccf1cbc02f100b88..65f2ad490414f1631cb65ead5dafcffd
if (!weak_this)
return false;
-@@ -973,7 +1033,7 @@ bool PrintViewManagerBase::CreateNewPrintJob(
+@@ -973,7 +1047,7 @@ bool PrintViewManagerBase::CreateNewPrintJob(
#endif
print_job_->AddObserver(*this);
@@ -406,7 +467,7 @@ index 2bb42383d753ac39953adf5dccf1cbc02f100b88..65f2ad490414f1631cb65ead5dafcffd
return true;
}
-@@ -1041,6 +1101,11 @@ void PrintViewManagerBase::ReleasePrintJob() {
+@@ -1041,6 +1115,11 @@ void PrintViewManagerBase::ReleasePrintJob() {
}
#endif
@@ -418,7 +479,7 @@ index 2bb42383d753ac39953adf5dccf1cbc02f100b88..65f2ad490414f1631cb65ead5dafcffd
if (!print_job_)
return;
-@@ -1048,7 +1113,7 @@ void PrintViewManagerBase::ReleasePrintJob() {
+@@ -1048,7 +1127,7 @@ void PrintViewManagerBase::ReleasePrintJob() {
// printing_rfh_ should only ever point to a RenderFrameHost with a live
// RenderFrame.
DCHECK(rfh->IsRenderFrameLive());
@@ -427,7 +488,7 @@ index 2bb42383d753ac39953adf5dccf1cbc02f100b88..65f2ad490414f1631cb65ead5dafcffd
}
print_job_->RemoveObserver(*this);
-@@ -1090,7 +1155,7 @@ bool PrintViewManagerBase::RunInnerMessageLoop() {
+@@ -1090,7 +1169,7 @@ bool PrintViewManagerBase::RunInnerMessageLoop() {
}
bool PrintViewManagerBase::OpportunisticallyCreatePrintJob(int cookie) {
@@ -436,7 +497,7 @@ index 2bb42383d753ac39953adf5dccf1cbc02f100b88..65f2ad490414f1631cb65ead5dafcffd
return true;
if (!cookie) {
-@@ -1199,7 +1264,7 @@ void PrintViewManagerBase::ReleasePrinterQuery() {
+@@ -1199,7 +1278,7 @@ void PrintViewManagerBase::ReleasePrinterQuery() {
}
void PrintViewManagerBase::CompletePrintNow(content::RenderFrameHost* rfh) {
@@ -445,7 +506,7 @@ index 2bb42383d753ac39953adf5dccf1cbc02f100b88..65f2ad490414f1631cb65ead5dafcffd
for (auto& observer : GetTestObservers()) {
observer.OnPrintNow(rfh);
-@@ -1249,7 +1314,7 @@ void PrintViewManagerBase::CompleteScriptedPrintAfterContentAnalysis(
+@@ -1249,7 +1328,7 @@ void PrintViewManagerBase::CompleteScriptedPrintAfterContentAnalysis(
set_analyzing_content(/*analyzing*/ false);
if (!allowed || !printing_rfh_ || IsCrashed() ||
!printing_rfh_->IsRenderFrameLive()) {
@@ -455,7 +516,7 @@ index 2bb42383d753ac39953adf5dccf1cbc02f100b88..65f2ad490414f1631cb65ead5dafcffd
}
CompleteScriptedPrint(printing_rfh_, std::move(params), std::move(callback));
diff --git a/chrome/browser/printing/print_view_manager_base.h b/chrome/browser/printing/print_view_manager_base.h
-index 8af22e511701a595b77bea31da096caedc2e47ce..d1e3bc5ea012de1f1155546ef66c5e3e1c6b11de 100644
+index 8af22e511701a595b77bea31da096caedc2e47ce..3136fac6935c998de10e36474b85521dba18012a 100644
--- a/chrome/browser/printing/print_view_manager_base.h
+++ b/chrome/browser/printing/print_view_manager_base.h
@@ -47,6 +47,8 @@ namespace printing {
@@ -505,7 +566,15 @@ index 8af22e511701a595b77bea31da096caedc2e47ce..d1e3bc5ea012de1f1155546ef66c5e3e
protected:
explicit PrintViewManagerBase(content::WebContents* web_contents);
-@@ -293,7 +308,8 @@ class PrintViewManagerBase : public PrintManager, public PrintJob::Observer {
+@@ -264,6 +279,7 @@ class PrintViewManagerBase : public PrintManager, public PrintJob::Observer {
+ bool success);
+ #endif
+ void CompleteUpdatePrintSettings(
++ std::unique_ptr<PrinterQuery> printer_query,
+ base::Value::Dict job_settings,
+ std::unique_ptr<PrintSettings> print_settings,
+ UpdatePrintSettingsCallback callback);
+@@ -293,7 +309,8 @@ class PrintViewManagerBase : public PrintManager, public PrintJob::Observer {
// Runs `callback` with `params` to reply to ScriptedPrint().
void ScriptedPrintReply(ScriptedPrintCallback callback,
int process_id,
@@ -515,7 +584,7 @@ index 8af22e511701a595b77bea31da096caedc2e47ce..d1e3bc5ea012de1f1155546ef66c5e3e
// Requests the RenderView to render all the missing pages for the print job.
// No-op if no print job is pending. Returns true if at least one page has
-@@ -363,8 +379,11 @@ class PrintViewManagerBase : public PrintManager, public PrintJob::Observer {
+@@ -363,8 +380,11 @@ class PrintViewManagerBase : public PrintManager, public PrintJob::Observer {
// The current RFH that is printing with a system printing dialog.
raw_ptr<content::RenderFrameHost> printing_rfh_ = nullptr;
|
fix
|
d002f16157bbc7f4bc70f2db6edde21d74c02276
|
ILikeTeaALot
|
2023-09-28 23:56:16
|
feat: `systemPreferences.getColor` should return RGBA instead of RGB (#38960)
* fix: return RGBA hex value from `SystemPreferences.getColor`
* docs: update docs to match changes of last commit
* fix: GetColor on windows now returns RGBA too
* fix: update tests for getColor RGBA on Windows
---------
Co-authored-by: John Kleinschmidt <[email protected]>
|
diff --git a/docs/api/system-preferences.md b/docs/api/system-preferences.md
index ab0fafd1ed..1fea0e3fbc 100644
--- a/docs/api/system-preferences.md
+++ b/docs/api/system-preferences.md
@@ -306,7 +306,7 @@ This API is only available on macOS 10.14 Mojave or newer.
* `window-background` - The background of a window.
* `window-frame-text` - The text in the window's titlebar area.
-Returns `string` - The system color setting in RGB hexadecimal form (`#ABCDEF`).
+Returns `string` - The system color setting in RGBA hexadecimal form (`#RRGGBBAA`).
See the [Windows docs][windows-colors] and the [macOS docs][macos-colors] for more details.
The following colors are only available on macOS 10.14: `find-highlight`, `selected-content-background`, `separator`, `unemphasized-selected-content-background`, `unemphasized-selected-text-background`, and `unemphasized-selected-text`.
diff --git a/shell/browser/api/electron_api_system_preferences_mac.mm b/shell/browser/api/electron_api_system_preferences_mac.mm
index df2868ac99..0cdf585d16 100644
--- a/shell/browser/api/electron_api_system_preferences_mac.mm
+++ b/shell/browser/api/electron_api_system_preferences_mac.mm
@@ -540,7 +540,7 @@ std::string SystemPreferences::GetColor(gin_helper::ErrorThrower thrower,
}
if (sysColor)
- return ToRGBHex(skia::NSSystemColorToSkColor(sysColor));
+ return ToRGBAHex(skia::NSSystemColorToSkColor(sysColor));
return "";
}
diff --git a/shell/browser/api/electron_api_system_preferences_win.cc b/shell/browser/api/electron_api_system_preferences_win.cc
index 982edd2131..1e05b697d1 100644
--- a/shell/browser/api/electron_api_system_preferences_win.cc
+++ b/shell/browser/api/electron_api_system_preferences_win.cc
@@ -133,7 +133,7 @@ std::string SystemPreferences::GetColor(gin_helper::ErrorThrower thrower,
});
if (const auto* iter = Lookup.find(color); iter != Lookup.end())
- return ToRGBHex(color_utils::GetSysSkColor(iter->second));
+ return ToRGBAHex(color_utils::GetSysSkColor(iter->second));
thrower.ThrowError("Unknown color: " + color);
return "";
diff --git a/spec/api-system-preferences-spec.ts b/spec/api-system-preferences-spec.ts
index d5a205aec0..adedba8953 100644
--- a/spec/api-system-preferences-spec.ts
+++ b/spec/api-system-preferences-spec.ts
@@ -17,8 +17,8 @@ describe('systemPreferences module', () => {
}).to.throw('Unknown color: not-a-color');
});
- it('returns a hex RGB color string', () => {
- expect(systemPreferences.getColor('window')).to.match(/^#[0-9A-F]{6}$/i);
+ it('returns a hex RGBA color string', () => {
+ expect(systemPreferences.getColor('window')).to.match(/^#[0-9A-F]{8}$/i);
});
});
|
feat
|
de76fc01ec9891d5918424982512d4648a725027
|
Cheng Zhao
|
2024-01-29 15:35:33
|
chore: fix outdated osk patch on main branch (#41152)
|
diff --git a/patches/chromium/fix_on-screen-keyboard_hides_on_input_blur_in_webview.patch b/patches/chromium/fix_on-screen-keyboard_hides_on_input_blur_in_webview.patch
index 9a44e9fcef..29f48c024d 100644
--- a/patches/chromium/fix_on-screen-keyboard_hides_on_input_blur_in_webview.patch
+++ b/patches/chromium/fix_on-screen-keyboard_hides_on_input_blur_in_webview.patch
@@ -9,10 +9,10 @@ focus node change via TextInputManager.
chromium-bug: https://crbug.com/1369605
diff --git a/content/browser/renderer_host/render_widget_host_view_aura.cc b/content/browser/renderer_host/render_widget_host_view_aura.cc
-index 4d2de00328f0b6437789612b14a53aae79eb15ab..c1ad97a53b59ccd7528ae51f27f9863b88cdac60 100644
+index dbf1556cfae0e1ae18734e37f6b67acd34861180..9fbc026dff4007e5673f2ebdecc6fe2695ae10fe 100644
--- a/content/browser/renderer_host/render_widget_host_view_aura.cc
+++ b/content/browser/renderer_host/render_widget_host_view_aura.cc
-@@ -2926,6 +2926,12 @@ void RenderWidgetHostViewAura::OnTextSelectionChanged(
+@@ -2919,6 +2919,12 @@ void RenderWidgetHostViewAura::OnTextSelectionChanged(
}
}
@@ -26,10 +26,10 @@ index 4d2de00328f0b6437789612b14a53aae79eb15ab..c1ad97a53b59ccd7528ae51f27f9863b
RenderWidgetHostViewAura* popup_child_host_view) {
popup_child_host_view_ = popup_child_host_view;
diff --git a/content/browser/renderer_host/render_widget_host_view_aura.h b/content/browser/renderer_host/render_widget_host_view_aura.h
-index 0f8d970ffb54a652c9235d13a7515b5ed3be7945..dcadbdb852ec03539168b4f27488107a800acc23 100644
+index 46f75904d60abd176b98adb5515b571ca46313d0..f1e20db777f16980cbd3f0451859704d9f898de9 100644
--- a/content/browser/renderer_host/render_widget_host_view_aura.h
+++ b/content/browser/renderer_host/render_widget_host_view_aura.h
-@@ -626,6 +626,8 @@ class CONTENT_EXPORT RenderWidgetHostViewAura
+@@ -629,6 +629,8 @@ class CONTENT_EXPORT RenderWidgetHostViewAura
RenderWidgetHostViewBase* updated_view) override;
void OnTextSelectionChanged(TextInputManager* text_input_mangager,
RenderWidgetHostViewBase* updated_view) override;
|
chore
|
5fa9dee68a7ef9f0fd74d5be0c836dc4fefa5b70
|
github-actions[bot]
|
2023-09-07 09:40:42
|
build: update appveyor image to latest version e-118.0.5993.0 (#39765)
build: update appveyor image to latest version
Co-authored-by: jkleinsc <[email protected]>
|
diff --git a/appveyor-woa.yml b/appveyor-woa.yml
index b93c60cb22..59e541d479 100644
--- a/appveyor-woa.yml
+++ b/appveyor-woa.yml
@@ -29,7 +29,7 @@
version: 1.0.{build}
build_cloud: electronhq-16-core
-image: e-118.0.5991.0
+image: e-118.0.5993.0
environment:
GIT_CACHE_PATH: C:\Users\appveyor\libcc_cache
ELECTRON_OUT_DIR: Default
diff --git a/appveyor.yml b/appveyor.yml
index 883db27610..4fca561e54 100644
--- a/appveyor.yml
+++ b/appveyor.yml
@@ -29,7 +29,7 @@
version: 1.0.{build}
build_cloud: electronhq-16-core
-image: e-118.0.5991.0
+image: e-118.0.5993.0
environment:
GIT_CACHE_PATH: C:\Users\appveyor\libcc_cache
ELECTRON_OUT_DIR: Default
|
build
|
6d4c271268afba6e3bbca676425cd82a99524ed0
|
Charles Kerr
|
2024-12-02 13:02:47
|
chore: remove unused registry arg from GetPrivilegeRequiredByUrl() (#44908)
this has never been used; introduced by 91071570
|
diff --git a/shell/browser/electron_browser_client.cc b/shell/browser/electron_browser_client.cc
index a642449676..c2f22836fd 100644
--- a/shell/browser/electron_browser_client.cc
+++ b/shell/browser/electron_browser_client.cc
@@ -264,9 +264,7 @@ bool AllowFileAccess(const std::string& extension_id,
extension_id);
}
-RenderProcessHostPrivilege GetPrivilegeRequiredByUrl(
- const GURL& url,
- extensions::ExtensionRegistry* registry) {
+RenderProcessHostPrivilege GetPrivilegeRequiredByUrl(const GURL& url) {
// Default to a normal renderer cause it is lower privileged. This should only
// occur if the URL on a site instance is either malformed, or uninitialized.
// If it is malformed, then there is no need for better privileges anyways.
@@ -735,15 +733,12 @@ bool ElectronBrowserClient::IsSuitableHost(
const GURL& site_url) {
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
auto* browser_context = process_host->GetBrowserContext();
- extensions::ExtensionRegistry* registry =
- extensions::ExtensionRegistry::Get(browser_context);
extensions::ProcessMap* process_map =
extensions::ProcessMap::Get(browser_context);
// Otherwise, just make sure the process privilege matches the privilege
// required by the site.
- RenderProcessHostPrivilege privilege_required =
- GetPrivilegeRequiredByUrl(site_url, registry);
+ const auto privilege_required = GetPrivilegeRequiredByUrl(site_url);
return GetProcessPrivilege(process_host, process_map) == privilege_required;
#else
return content::ContentBrowserClient::IsSuitableHost(process_host, site_url);
|
chore
|
8bfbb251cc76a722cd9a1c298ca4e2d15f47cd33
|
Milan Burda
|
2022-10-10 12:00:56
|
fix: add missing #include "base/cxx17_backports.h" (#35945)
|
diff --git a/shell/browser/ui/autofill_popup.cc b/shell/browser/ui/autofill_popup.cc
index 93975bf676..2afbe05059 100644
--- a/shell/browser/ui/autofill_popup.cc
+++ b/shell/browser/ui/autofill_popup.cc
@@ -6,6 +6,7 @@
#include <memory>
#include <vector>
+#include "base/cxx17_backports.h"
#include "base/feature_list.h"
#include "base/i18n/rtl.h"
#include "components/autofill/core/common/autofill_features.h"
|
fix
|
c8544e25dffd7a7ca6133e00518afa72fc976c63
|
John Kleinschmidt
|
2023-09-18 16:43:27
|
build: fixup autoninja (#39896)
chore: set GOMA_DIR for autoninja
(cherry picked from commit 94f24bde4dd19764fbbae083f5970b007c9dc8b2)
(cherry picked from commit 90c1f6e1cb8d22d94dd01791dc4b9c3e0a7e86fc)
|
diff --git a/.circleci/config/base.yml b/.circleci/config/base.yml
index 3626c8ff94..c16e18c240 100644
--- a/.circleci/config/base.yml
+++ b/.circleci/config/base.yml
@@ -354,7 +354,7 @@ step-setup-goma-for-build: &step-setup-goma-for-build
exit 1
fi
echo 'export GN_GOMA_FILE='`node -e "console.log(require('./src/utils/goma.js').gnFilePath)"` >> $BASH_ENV
- echo 'export LOCAL_GOMA_DIR='`node -e "console.log(require('./src/utils/goma.js').dir)"` >> $BASH_ENV
+ echo 'export GOMA_DIR='`node -e "console.log(require('./src/utils/goma.js').dir)"` >> $BASH_ENV
echo 'export GOMA_FALLBACK_ON_AUTH_FAILURE=true' >> $BASH_ENV
cd ..
touch "${TMPDIR:=/tmp}"/.goma-ready
@@ -749,8 +749,8 @@ step-show-goma-stats: &step-show-goma-stats
command: |
set +e
set +o pipefail
- $LOCAL_GOMA_DIR/goma_ctl.py stat
- $LOCAL_GOMA_DIR/diagnose_goma_log.py
+ $GOMA_DIR/goma_ctl.py stat
+ $GOMA_DIR/diagnose_goma_log.py
true
when: always
background: true
|
build
|
bec6ddda7035be6aa77f9f4c9523a06bfc49470d
|
Robo
|
2025-02-05 15:13:29
|
feat: route deprecated sync clipboard read through permission checks (#45377)
* feat: route deprecated clipboard commands through permission checks
* docs: address review feedback
* fix: enable checks for child windows
|
diff --git a/BUILD.gn b/BUILD.gn
index 6fb16d7bd6..0892c19505 100644
--- a/BUILD.gn
+++ b/BUILD.gn
@@ -441,6 +441,7 @@ source_set("electron_lib") {
"chromium_src:chrome_spellchecker",
"shell/common:mojo",
"shell/common:plugin",
+ "shell/common:web_contents_utility",
"shell/services/node/public/mojom",
"//base:base_static",
"//base/allocator:buildflags",
diff --git a/docs/api/session.md b/docs/api/session.md
index cc6a22e59b..ff335ec96b 100644
--- a/docs/api/session.md
+++ b/docs/api/session.md
@@ -933,6 +933,7 @@ session.fromPartition('some-partition').setPermissionRequestHandler((webContents
* `storage-access` - Allows content loaded in a third-party context to request access to third-party cookies using the [Storage Access API](https://developer.mozilla.org/en-US/docs/Web/API/Storage_Access_API).
* `top-level-storage-access` - Allow top-level sites to request third-party cookie access on behalf of embedded content originating from another site in the same related website set using the [Storage Access API](https://developer.mozilla.org/en-US/docs/Web/API/Storage_Access_API).
* `usb` - Expose non-standard Universal Serial Bus (USB) compatible devices services to the web with the [WebUSB API](https://developer.mozilla.org/en-US/docs/Web/API/WebUSB_API).
+ * `deprecated-sync-clipboard-read` _Deprecated_ - Request access to run `document.execCommand("paste")`
* `requestingOrigin` string - The origin URL of the permission check
* `details` Object - Some properties are only available on certain permission types.
* `embeddingOrigin` string (optional) - The origin of the frame embedding the frame that made the permission check. Only set for cross-origin sub frames making permission checks.
diff --git a/docs/api/structures/web-preferences.md b/docs/api/structures/web-preferences.md
index 414d9c6c3b..26ead57c23 100644
--- a/docs/api/structures/web-preferences.md
+++ b/docs/api/structures/web-preferences.md
@@ -148,6 +148,7 @@
this will cause the `preferred-size-changed` event to be emitted on the
`WebContents` when the preferred size changes. Default is `false`.
* `transparent` boolean (optional) - Whether to enable background transparency for the guest page. Default is `true`. **Note:** The guest page's text and background colors are derived from the [color scheme](https://developer.mozilla.org/en-US/docs/Web/CSS/color-scheme) of its root element. When transparency is enabled, the text color will still change accordingly but the background will remain transparent.
+* `enableDeprecatedPaste` boolean (optional) _Deprecated_ - Whether to enable the `paste` [execCommand](https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand). Default is `false`.
[chrome-content-scripts]: https://developer.chrome.com/extensions/content_scripts#execution-environment
[runtime-enabled-features]: https://source.chromium.org/chromium/chromium/src/+/main:third_party/blink/renderer/platform/runtime_enabled_features.json5
diff --git a/docs/breaking-changes.md b/docs/breaking-changes.md
index 849f9d5ef3..3d6292d976 100644
--- a/docs/breaking-changes.md
+++ b/docs/breaking-changes.md
@@ -73,6 +73,15 @@ This brings the behavior to parity with Linux. Prior behavior: Menu bar is still
## Planned Breaking API Changes (33.0)
+### Deprecated: `document.execCommand("paste")`
+
+The synchronous clipboard read API [document.execCommand("paste")](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Interact_with_the_clipboard) has been
+deprecated in favor of [async clipboard API](https://developer.mozilla.org/en-US/docs/Web/API/Clipboard_API). This is to align with the browser defaults.
+
+The `enableDeprecatedPaste` option on `WebPreferences` that triggers the permission
+checks for this API and the associated permission type `deprecated-sync-clipboard-read`
+are also deprecated.
+
### Behavior Changed: frame properties may retrieve detached WebFrameMain instances or none at all
APIs which provide access to a `WebFrameMain` instance may return an instance
diff --git a/patches/chromium/.patches b/patches/chromium/.patches
index b0ae1dc093..8ab0f8bd3e 100644
--- a/patches/chromium/.patches
+++ b/patches/chromium/.patches
@@ -128,7 +128,7 @@ fix_font_face_resolution_when_renderer_is_blocked.patch
feat_enable_passing_exit_code_on_service_process_crash.patch
chore_remove_reference_to_chrome_browser_themes.patch
feat_enable_customizing_symbol_color_in_framecaptionbutton.patch
-build_expose_webplugininfo_interface_to_electron.patch
+build_allow_electron_mojom_interfaces_to_depend_on_blink.patch
osr_shared_texture_remove_keyed_mutex_on_win_dxgi.patch
feat_allow_usage_of_sccontentsharingpicker_on_supported_platforms.patch
chore_partial_revert_of.patch
@@ -141,3 +141,4 @@ revert_code_health_clean_up_stale_macwebcontentsocclusion.patch
build_remove_vr_directx_helpers_dependency.patch
ignore_parse_errors_for_pkey_appusermodel_toastactivatorclsid.patch
feat_add_signals_when_embedder_cleanup_callbacks_run_for.patch
+feat_separate_content_settings_callback_for_sync_and_async_clipboard.patch
diff --git a/patches/chromium/build_expose_webplugininfo_interface_to_electron.patch b/patches/chromium/build_allow_electron_mojom_interfaces_to_depend_on_blink.patch
similarity index 55%
rename from patches/chromium/build_expose_webplugininfo_interface_to_electron.patch
rename to patches/chromium/build_allow_electron_mojom_interfaces_to_depend_on_blink.patch
index 01892ec763..3350dadff1 100644
--- a/patches/chromium/build_expose_webplugininfo_interface_to_electron.patch
+++ b/patches/chromium/build_allow_electron_mojom_interfaces_to_depend_on_blink.patch
@@ -1,20 +1,24 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: deepak1556 <[email protected]>
Date: Fri, 9 Aug 2024 22:39:47 +0900
-Subject: build: expose webplugininfo interface to electron
+Subject: build: allow electron mojom interfaces to depend on blink
+ mojom_platform
-Allows implementing electron::mojom::ElectronPluginInfoHost interface
-which provides plugin details between browser<->renderer.
+Needed for:
+
+1) //electron/shell/common:plugin
+2) //electron/shell/common:web_contents_utility
diff --git a/content/public/common/BUILD.gn b/content/public/common/BUILD.gn
-index 659f500a47eb0f2d1f753dee2b234bb7bf1027d4..46e4714e14a5992b30ea8bfa99c126e5f1d2c3eb 100644
+index 659f500a47eb0f2d1f753dee2b234bb7bf1027d4..8f6e733b1ae1081f19a090cbdf2372b164e514a8 100644
--- a/content/public/common/BUILD.gn
+++ b/content/public/common/BUILD.gn
-@@ -379,6 +379,7 @@ mojom("interfaces") {
+@@ -379,6 +379,8 @@ mojom("interfaces") {
"//content/common/*",
"//extensions/common:mojom",
"//extensions/common:mojom_blink",
+ "//electron/shell/common:plugin",
++ "//electron/shell/common:web_contents_utility",
]
sources = [
diff --git a/patches/chromium/feat_separate_content_settings_callback_for_sync_and_async_clipboard.patch b/patches/chromium/feat_separate_content_settings_callback_for_sync_and_async_clipboard.patch
new file mode 100644
index 0000000000..9dc49d8aa3
--- /dev/null
+++ b/patches/chromium/feat_separate_content_settings_callback_for_sync_and_async_clipboard.patch
@@ -0,0 +1,114 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: deepak1556 <[email protected]>
+Date: Thu, 30 Jan 2025 20:28:38 +0900
+Subject: feat: separate content settings callback for sync and async clipboard
+
+`AllowReadFromClipboard` is called from both the types without a way to differentiate.
+
+[sync path] - third_party/blink/renderer/core/editing/commands/clipboard_commands.cc
+[async path] - third_party/blink/renderer/modules/clipboard/clipboard_promise.cc
+
+This patch adds a new callback to separate these two paths so that we
+can have sync permission checks for the sync path.
+
+Additionally, `blink::PermissionType::DEPRECATED_SYNC_CLIPBOARD_READ`
+has been added to support type conversion in permission policy checks. We have extended
+`blink::PermissionType` in `electron::WebContentsPermissionHelper::PermissionType`
+but it is hard to import the latter into the content permission layer checks.
+
+This patch will be removed when the deprecated sync api support is
+removed.
+
+diff --git a/components/permissions/permission_util.cc b/components/permissions/permission_util.cc
+index 0265815ae3b300c1c0637686e212d3a1c55fdd1b..eb7ea287de24a2563604e639de3bb783d80d98eb 100644
+--- a/components/permissions/permission_util.cc
++++ b/components/permissions/permission_util.cc
+@@ -384,6 +384,7 @@ ContentSettingsType PermissionUtil::PermissionTypeToContentSettingsTypeSafe(
+ return ContentSettingsType::AUTOMATIC_FULLSCREEN;
+ case PermissionType::WEB_APP_INSTALLATION:
+ return ContentSettingsType::WEB_APP_INSTALLATION;
++ case PermissionType::DEPRECATED_SYNC_CLIPBOARD_READ:
+ case PermissionType::NUM:
+ break;
+ }
+diff --git a/content/browser/permissions/permission_controller_impl.cc b/content/browser/permissions/permission_controller_impl.cc
+index e991887c103618b35688cf72307ca05fdb202e6e..54894f3412d42264eae80d767be5215e52f08184 100644
+--- a/content/browser/permissions/permission_controller_impl.cc
++++ b/content/browser/permissions/permission_controller_impl.cc
+@@ -86,6 +86,7 @@ PermissionToSchedulingFeature(PermissionType permission_name) {
+ case PermissionType::POINTER_LOCK:
+ case PermissionType::AUTOMATIC_FULLSCREEN:
+ case PermissionType::WEB_APP_INSTALLATION:
++ case PermissionType::DEPRECATED_SYNC_CLIPBOARD_READ:
+ return std::nullopt;
+ }
+ }
+diff --git a/third_party/blink/common/permissions/permission_utils.cc b/third_party/blink/common/permissions/permission_utils.cc
+index dfcd99a4336db5c5b8b722c6612b8abbf419a08f..9f074285203e6ee408abf8275f3070221b0d25c0 100644
+--- a/third_party/blink/common/permissions/permission_utils.cc
++++ b/third_party/blink/common/permissions/permission_utils.cc
+@@ -99,6 +99,8 @@ std::string GetPermissionString(PermissionType permission) {
+ return "AutomaticFullscreen";
+ case PermissionType::WEB_APP_INSTALLATION:
+ return "WebAppInstallation";
++ case PermissionType::DEPRECATED_SYNC_CLIPBOARD_READ:
++ return "DeprecatedSyncClipboardRead";
+ case PermissionType::NUM:
+ NOTREACHED();
+ }
+@@ -171,6 +173,7 @@ PermissionTypeToPermissionsPolicyFeature(PermissionType permission) {
+ case PermissionType::NOTIFICATIONS:
+ case PermissionType::KEYBOARD_LOCK:
+ case PermissionType::POINTER_LOCK:
++ case PermissionType::DEPRECATED_SYNC_CLIPBOARD_READ:
+ return std::nullopt;
+
+ case PermissionType::NUM:
+diff --git a/third_party/blink/public/common/permissions/permission_utils.h b/third_party/blink/public/common/permissions/permission_utils.h
+index ae03b7f099d30c157cfda7d1beb7c535d3615471..ca287e7a5271ee83c393de6c1fe347973f4292ba 100644
+--- a/third_party/blink/public/common/permissions/permission_utils.h
++++ b/third_party/blink/public/common/permissions/permission_utils.h
+@@ -64,6 +64,7 @@ enum class PermissionType {
+ AUTOMATIC_FULLSCREEN = 40,
+ HAND_TRACKING = 41,
+ WEB_APP_INSTALLATION = 42,
++ DEPRECATED_SYNC_CLIPBOARD_READ = 43,
+
+ // Always keep this at the end.
+ NUM,
+diff --git a/third_party/blink/public/platform/web_content_settings_client.h b/third_party/blink/public/platform/web_content_settings_client.h
+index 28f616f21f998c7cd1c794e58efaccf9e6c11e6e..c64896642209124e500db2ed6fe2357e426cd10b 100644
+--- a/third_party/blink/public/platform/web_content_settings_client.h
++++ b/third_party/blink/public/platform/web_content_settings_client.h
+@@ -55,6 +55,9 @@ class WebContentSettingsClient {
+ // Controls whether access to write the clipboard is allowed for this frame.
+ virtual bool AllowWriteToClipboard() { return false; }
+
++ // Controls whether synchronous access to read the clipboard is allowed for this frame.
++ virtual bool AllowReadFromClipboardSync() { return false; }
++
+ // Controls whether to enable MutationEvents for this frame.
+ // The common use case of this method is actually to selectively disable
+ // MutationEvents, but it's been named for consistency with the rest of the
+diff --git a/third_party/blink/renderer/core/editing/commands/clipboard_commands.cc b/third_party/blink/renderer/core/editing/commands/clipboard_commands.cc
+index 271ca7ba88fc92b8f6bad5ee4cffedf7f1b05aee..d8d01062de4af45a59eb10a1c0fa046a4adf1894 100644
+--- a/third_party/blink/renderer/core/editing/commands/clipboard_commands.cc
++++ b/third_party/blink/renderer/core/editing/commands/clipboard_commands.cc
+@@ -121,7 +121,7 @@ bool ClipboardCommands::CanReadClipboard(LocalFrame& frame,
+ return true;
+ }
+ return frame.GetContentSettingsClient() &&
+- frame.GetContentSettingsClient()->AllowReadFromClipboard();
++ frame.GetContentSettingsClient()->AllowReadFromClipboardSync();
+ }
+
+ bool ClipboardCommands::CanWriteClipboard(LocalFrame& frame,
+@@ -310,7 +310,7 @@ bool ClipboardCommands::PasteSupported(LocalFrame* frame) {
+ return true;
+ }
+ return frame->GetContentSettingsClient() &&
+- frame->GetContentSettingsClient()->AllowReadFromClipboard();
++ frame->GetContentSettingsClient()->AllowReadFromClipboardSync();
+ }
+
+ bool ClipboardCommands::ExecuteCopy(LocalFrame& frame,
diff --git a/shell/browser/api/electron_api_service_worker_main.cc b/shell/browser/api/electron_api_service_worker_main.cc
index 8d24d872e0..6c135894e2 100644
--- a/shell/browser/api/electron_api_service_worker_main.cc
+++ b/shell/browser/api/electron_api_service_worker_main.cc
@@ -13,13 +13,13 @@
#include "base/no_destructor.h"
#include "content/browser/service_worker/service_worker_context_wrapper.h" // nogncheck
#include "content/browser/service_worker/service_worker_version.h" // nogncheck
-#include "electron/shell/common/api/api.mojom.h"
#include "gin/handle.h"
#include "gin/object_template_builder.h"
#include "services/service_manager/public/cpp/interface_provider.h"
#include "shell/browser/api/message_port.h"
#include "shell/browser/browser.h"
#include "shell/browser/javascript_environment.h"
+#include "shell/common/api/api.mojom.h"
#include "shell/common/gin_converters/blink_converter.h"
#include "shell/common/gin_converters/gurl_converter.h"
#include "shell/common/gin_converters/value_converter.h"
diff --git a/shell/browser/api/electron_api_web_contents.cc b/shell/browser/api/electron_api_web_contents.cc
index 21cd725587..2b6a9fe5f7 100644
--- a/shell/browser/api/electron_api_web_contents.cc
+++ b/shell/browser/api/electron_api_web_contents.cc
@@ -70,7 +70,6 @@
#include "content/public/common/webplugininfo.h"
#include "electron/buildflags/buildflags.h"
#include "electron/mas.h"
-#include "electron/shell/common/api/api.mojom.h"
#include "gin/arguments.h"
#include "gin/data_object_builder.h"
#include "gin/handle.h"
@@ -110,6 +109,7 @@
#include "shell/browser/web_contents_zoom_controller.h"
#include "shell/browser/web_view_guest_delegate.h"
#include "shell/browser/web_view_manager.h"
+#include "shell/common/api/api.mojom.h"
#include "shell/common/api/electron_api_native_image.h"
#include "shell/common/api/electron_bindings.h"
#include "shell/common/color_util.h"
diff --git a/shell/browser/api/electron_api_web_contents.h b/shell/browser/api/electron_api_web_contents.h
index 2275f90171..7509ac2ddb 100644
--- a/shell/browser/api/electron_api_web_contents.h
+++ b/shell/browser/api/electron_api_web_contents.h
@@ -31,7 +31,6 @@
#include "content/public/browser/web_contents_delegate.h"
#include "content/public/browser/web_contents_observer.h"
#include "electron/buildflags/buildflags.h"
-#include "electron/shell/common/api/api.mojom.h"
#include "gin/handle.h"
#include "gin/wrappable.h"
#include "printing/buildflags/buildflags.h"
@@ -43,9 +42,11 @@
#include "shell/browser/preload_script.h"
#include "shell/browser/ui/inspectable_web_contents_delegate.h"
#include "shell/browser/ui/inspectable_web_contents_view_delegate.h"
+#include "shell/common/api/api.mojom.h"
#include "shell/common/gin_helper/cleaned_up_at_exit.h"
#include "shell/common/gin_helper/constructible.h"
#include "shell/common/gin_helper/pinnable.h"
+#include "shell/common/web_contents_utility.mojom.h"
#include "ui/base/models/image_model.h"
#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
diff --git a/shell/browser/api/electron_api_web_frame_main.cc b/shell/browser/api/electron_api_web_frame_main.cc
index b855e7a63a..3e800659a4 100644
--- a/shell/browser/api/electron_api_web_frame_main.cc
+++ b/shell/browser/api/electron_api_web_frame_main.cc
@@ -17,13 +17,13 @@
#include "content/public/browser/frame_tree_node_id.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/common/isolated_world_ids.h"
-#include "electron/shell/common/api/api.mojom.h"
#include "gin/handle.h"
#include "gin/object_template_builder.h"
#include "services/service_manager/public/cpp/interface_provider.h"
#include "shell/browser/api/message_port.h"
#include "shell/browser/browser.h"
#include "shell/browser/javascript_environment.h"
+#include "shell/common/api/api.mojom.h"
#include "shell/common/gin_converters/blink_converter.h"
#include "shell/common/gin_converters/frame_converter.h"
#include "shell/common/gin_converters/gurl_converter.h"
diff --git a/shell/browser/electron_api_ipc_handler_impl.h b/shell/browser/electron_api_ipc_handler_impl.h
index 96e9a620eb..819407a0de 100644
--- a/shell/browser/electron_api_ipc_handler_impl.h
+++ b/shell/browser/electron_api_ipc_handler_impl.h
@@ -10,9 +10,9 @@
#include "base/memory/weak_ptr.h"
#include "content/public/browser/global_routing_id.h"
#include "content/public/browser/web_contents_observer.h"
-#include "electron/shell/common/api/api.mojom.h"
#include "mojo/public/cpp/bindings/associated_receiver.h"
#include "shell/browser/api/electron_api_web_contents.h"
+#include "shell/common/api/api.mojom.h"
namespace content {
class RenderFrameHost;
diff --git a/shell/browser/electron_browser_client.cc b/shell/browser/electron_browser_client.cc
index ac8dfca095..d39afef9a6 100644
--- a/shell/browser/electron_browser_client.cc
+++ b/shell/browser/electron_browser_client.cc
@@ -53,7 +53,6 @@
#include "crypto/crypto_buildflags.h"
#include "electron/buildflags/buildflags.h"
#include "electron/fuses.h"
-#include "electron/shell/common/api/api.mojom.h"
#include "extensions/browser/extension_navigation_ui_data.h"
#include "extensions/common/extension_id.h"
#include "mojo/public/cpp/bindings/binder_map.h"
@@ -118,6 +117,7 @@
#include "shell/common/platform_util.h"
#include "shell/common/plugin.mojom.h"
#include "shell/common/thread_restrictions.h"
+#include "shell/common/web_contents_utility.mojom.h"
#include "third_party/blink/public/common/associated_interfaces/associated_interface_registry.h"
#include "third_party/blink/public/common/loader/url_loader_throttle.h"
#include "third_party/blink/public/common/renderer_preferences/renderer_preferences.h"
diff --git a/shell/browser/electron_permission_manager.cc b/shell/browser/electron_permission_manager.cc
index 90ebeb2fee..2ab961ec30 100644
--- a/shell/browser/electron_permission_manager.cc
+++ b/shell/browser/electron_permission_manager.cc
@@ -298,8 +298,13 @@ bool ElectronPermissionManager::CheckPermissionWithDetails(
content::RenderFrameHost* render_frame_host,
const GURL& requesting_origin,
base::Value::Dict details) const {
- if (check_handler_.is_null())
- return true;
+ if (check_handler_.is_null()) {
+ if (permission == blink::PermissionType::DEPRECATED_SYNC_CLIPBOARD_READ) {
+ return false;
+ } else {
+ return true;
+ }
+ }
auto* web_contents =
render_frame_host
diff --git a/shell/browser/electron_web_contents_utility_handler_impl.cc b/shell/browser/electron_web_contents_utility_handler_impl.cc
index 33b5f01790..e1baff6b4e 100644
--- a/shell/browser/electron_web_contents_utility_handler_impl.cc
+++ b/shell/browser/electron_web_contents_utility_handler_impl.cc
@@ -6,15 +6,19 @@
#include <utility>
+#include "content/public/browser/browser_context.h"
+#include "content/public/browser/permission_controller.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_process_host.h"
#include "mojo/public/cpp/bindings/self_owned_receiver.h"
+#include "shell/browser/web_contents_permission_helper.h"
+#include "third_party/blink/public/mojom/permissions/permission_status.mojom.h"
namespace electron {
ElectronWebContentsUtilityHandlerImpl::ElectronWebContentsUtilityHandlerImpl(
content::RenderFrameHost* frame_host,
mojo::PendingAssociatedReceiver<mojom::ElectronWebContentsUtility> receiver)
- : render_frame_host_id_(frame_host->GetGlobalId()) {
+ : render_frame_host_token_(frame_host->GetGlobalFrameToken()) {
content::WebContents* web_contents =
content::WebContents::FromRenderFrameHost(frame_host);
DCHECK(web_contents);
@@ -28,8 +32,11 @@ ElectronWebContentsUtilityHandlerImpl::ElectronWebContentsUtilityHandlerImpl(
ElectronWebContentsUtilityHandlerImpl::
~ElectronWebContentsUtilityHandlerImpl() = default;
-void ElectronWebContentsUtilityHandlerImpl::WebContentsDestroyed() {
- delete this;
+void ElectronWebContentsUtilityHandlerImpl::RenderFrameDeleted(
+ content::RenderFrameHost* render_frame_host) {
+ if (render_frame_host->GetGlobalFrameToken() == render_frame_host_token_) {
+ delete this;
+ }
}
void ElectronWebContentsUtilityHandlerImpl::OnConnectionError() {
@@ -59,9 +66,42 @@ void ElectronWebContentsUtilityHandlerImpl::DoGetZoomLevel(
}
}
+void ElectronWebContentsUtilityHandlerImpl::CanAccessClipboardDeprecated(
+ mojom::PermissionName name,
+ const blink::LocalFrameToken& frame_token,
+ CanAccessClipboardDeprecatedCallback callback) {
+ if (render_frame_host_token_.frame_token == frame_token) {
+ // Paste requires either (1) user activation, ...
+ if (web_contents()->HasRecentInteraction()) {
+ std::move(callback).Run(blink::mojom::PermissionStatus::GRANTED);
+ return;
+ }
+
+ // (2) granted permission, ...
+ content::RenderFrameHost* render_frame_host = GetRenderFrameHost();
+ content::BrowserContext* browser_context =
+ render_frame_host->GetBrowserContext();
+ content::PermissionController* permission_controller =
+ browser_context->GetPermissionController();
+ blink::PermissionType permission;
+ if (name == mojom::PermissionName::DEPRECATED_SYNC_CLIPBOARD_READ) {
+ permission = blink::PermissionType::DEPRECATED_SYNC_CLIPBOARD_READ;
+ } else {
+ std::move(callback).Run(blink::mojom::PermissionStatus::DENIED);
+ return;
+ }
+ blink::mojom::PermissionStatus status =
+ permission_controller->GetPermissionStatusForCurrentDocument(
+ permission, render_frame_host);
+ std::move(callback).Run(status);
+ } else {
+ std::move(callback).Run(blink::mojom::PermissionStatus::DENIED);
+ }
+}
+
content::RenderFrameHost*
ElectronWebContentsUtilityHandlerImpl::GetRenderFrameHost() {
- return content::RenderFrameHost::FromID(render_frame_host_id_);
+ return content::RenderFrameHost::FromFrameToken(render_frame_host_token_);
}
// static
diff --git a/shell/browser/electron_web_contents_utility_handler_impl.h b/shell/browser/electron_web_contents_utility_handler_impl.h
index 2f0f07d007..c4b53c4a51 100644
--- a/shell/browser/electron_web_contents_utility_handler_impl.h
+++ b/shell/browser/electron_web_contents_utility_handler_impl.h
@@ -10,7 +10,7 @@
#include "base/memory/weak_ptr.h"
#include "content/public/browser/global_routing_id.h"
#include "content/public/browser/web_contents_observer.h"
-#include "electron/shell/common/api/api.mojom.h"
+#include "electron/shell/common/web_contents_utility.mojom.h"
#include "mojo/public/cpp/bindings/associated_receiver.h"
#include "shell/browser/api/electron_api_web_contents.h"
@@ -43,6 +43,10 @@ class ElectronWebContentsUtilityHandlerImpl
void OnFirstNonEmptyLayout() override;
void SetTemporaryZoomLevel(double level) override;
void DoGetZoomLevel(DoGetZoomLevelCallback callback) override;
+ void CanAccessClipboardDeprecated(
+ mojom::PermissionName name,
+ const blink::LocalFrameToken& frame_token,
+ CanAccessClipboardDeprecatedCallback callback) override;
base::WeakPtr<ElectronWebContentsUtilityHandlerImpl> GetWeakPtr() {
return weak_factory_.GetWeakPtr();
@@ -52,13 +56,13 @@ class ElectronWebContentsUtilityHandlerImpl
~ElectronWebContentsUtilityHandlerImpl() override;
// content::WebContentsObserver:
- void WebContentsDestroyed() override;
+ void RenderFrameDeleted(content::RenderFrameHost* render_frame_host) override;
void OnConnectionError();
content::RenderFrameHost* GetRenderFrameHost();
- content::GlobalRenderFrameHostId render_frame_host_id_;
+ content::GlobalRenderFrameHostToken render_frame_host_token_;
mojo::AssociatedReceiver<mojom::ElectronWebContentsUtility> receiver_{this};
diff --git a/shell/browser/web_contents_permission_helper.h b/shell/browser/web_contents_permission_helper.h
index 4dfd6a53f7..0bf7ea4965 100644
--- a/shell/browser/web_contents_permission_helper.h
+++ b/shell/browser/web_contents_permission_helper.h
@@ -32,7 +32,7 @@ class WebContentsPermissionHelper
HID,
USB,
KEYBOARD_LOCK,
- FILE_SYSTEM
+ FILE_SYSTEM,
};
// Asynchronous Requests
diff --git a/shell/browser/web_contents_preferences.cc b/shell/browser/web_contents_preferences.cc
index 2547819313..5066bc2e00 100644
--- a/shell/browser/web_contents_preferences.cc
+++ b/shell/browser/web_contents_preferences.cc
@@ -148,6 +148,7 @@ void WebContentsPreferences::Clear() {
blink::mojom::ImageAnimationPolicy::kImageAnimationPolicyAllowed;
preload_path_ = std::nullopt;
v8_cache_options_ = blink::mojom::V8CacheOptions::kDefault;
+ deprecated_paste_enabled_ = false;
#if BUILDFLAG(IS_MAC)
scroll_bounce_ = false;
@@ -245,6 +246,9 @@ void WebContentsPreferences::SetFromDictionary(
web_preferences.Get("v8CacheOptions", &v8_cache_options_);
+ web_preferences.Get(options::kEnableDeprecatedPaste,
+ &deprecated_paste_enabled_);
+
#if BUILDFLAG(IS_MAC)
web_preferences.Get(options::kScrollBounce, &scroll_bounce_);
#endif
@@ -472,6 +476,8 @@ void WebContentsPreferences::OverrideWebkitPrefs(
prefs->webview_tag = webview_tag_;
prefs->v8_cache_options = v8_cache_options_;
+
+ prefs->dom_paste_enabled = deprecated_paste_enabled_;
}
WEB_CONTENTS_USER_DATA_KEY_IMPL(WebContentsPreferences);
diff --git a/shell/browser/web_contents_preferences.h b/shell/browser/web_contents_preferences.h
index 26cf7667e3..4bb6132752 100644
--- a/shell/browser/web_contents_preferences.h
+++ b/shell/browser/web_contents_preferences.h
@@ -133,6 +133,7 @@ class WebContentsPreferences
blink::mojom::ImageAnimationPolicy image_animation_policy_;
std::optional<base::FilePath> preload_path_;
blink::mojom::V8CacheOptions v8_cache_options_;
+ bool deprecated_paste_enabled_ = false;
#if BUILDFLAG(IS_MAC)
bool scroll_bounce_;
diff --git a/shell/common/BUILD.gn b/shell/common/BUILD.gn
index e9b365fddb..7b25bdecc7 100644
--- a/shell/common/BUILD.gn
+++ b/shell/common/BUILD.gn
@@ -26,3 +26,16 @@ mojom("plugin") {
"//mojo/public/mojom/base",
]
}
+
+mojom("web_contents_utility") {
+ # We don't want Blink variants of these bindings to be generated.
+ disable_variants = true
+
+ sources = [ "web_contents_utility.mojom" ]
+
+ public_deps = [
+ "//content/public/common:interfaces",
+ "//third_party/blink/public/mojom/tokens",
+ "//url/mojom:url_mojom_origin",
+ ]
+}
diff --git a/shell/common/api/api.mojom b/shell/common/api/api.mojom
index 64c60f25cd..b9859ba7f2 100644
--- a/shell/common/api/api.mojom
+++ b/shell/common/api/api.mojom
@@ -25,17 +25,6 @@ interface ElectronAutofillDriver {
HideAutofillPopup();
};
-interface ElectronWebContentsUtility {
- // Informs underlying WebContents that first non-empty layout was performed
- // by compositor.
- OnFirstNonEmptyLayout();
-
- SetTemporaryZoomLevel(double zoom_level);
-
- [Sync]
- DoGetZoomLevel() => (double result);
-};
-
interface ElectronApiIPC {
// Emits an event on |channel| from the ipcMain JavaScript object in the main
// process.
diff --git a/shell/common/gin_converters/content_converter.cc b/shell/common/gin_converters/content_converter.cc
index 55a6638b1d..7e593c324a 100644
--- a/shell/common/gin_converters/content_converter.cc
+++ b/shell/common/gin_converters/content_converter.cc
@@ -226,6 +226,8 @@ v8::Local<v8::Value> Converter<blink::PermissionType>::ToV8(
return StringToV8(isolate, "speaker-selection");
case blink::PermissionType::WEB_APP_INSTALLATION:
return StringToV8(isolate, "web-app-installation");
+ case blink::PermissionType::DEPRECATED_SYNC_CLIPBOARD_READ:
+ return StringToV8(isolate, "deprecated-sync-clipboard-read");
case blink::PermissionType::NUM:
break;
}
diff --git a/shell/common/options_switches.h b/shell/common/options_switches.h
index 04b47bda3b..7f2608410c 100644
--- a/shell/common/options_switches.h
+++ b/shell/common/options_switches.h
@@ -205,6 +205,11 @@ inline constexpr std::string_view kEnablePreferredSizeMode =
inline constexpr std::string_view kHiddenPage = "hiddenPage";
inline constexpr std::string_view kSpellcheck = "spellcheck";
+
+// Enables the permission managed support for
+// document.execCommand("paste").
+inline constexpr std::string_view kEnableDeprecatedPaste =
+ "enableDeprecatedPaste";
} // namespace options
// Following are actually command line switches, should be moved to other files.
diff --git a/shell/common/web_contents_utility.mojom b/shell/common/web_contents_utility.mojom
new file mode 100644
index 0000000000..a941ee42a7
--- /dev/null
+++ b/shell/common/web_contents_utility.mojom
@@ -0,0 +1,25 @@
+module electron.mojom;
+
+import "third_party/blink/public/mojom/permissions/permission_status.mojom";
+import "third_party/blink/public/mojom/tokens/tokens.mojom";
+import "url/mojom/origin.mojom";
+
+enum PermissionName {
+ DEPRECATED_SYNC_CLIPBOARD_READ,
+};
+
+interface ElectronWebContentsUtility {
+ // Informs underlying WebContents that first non-empty layout was performed
+ // by compositor.
+ OnFirstNonEmptyLayout();
+
+ SetTemporaryZoomLevel(double zoom_level);
+
+ [Sync]
+ DoGetZoomLevel() => (double result);
+
+ [Sync]
+ CanAccessClipboardDeprecated(
+ PermissionName name,
+ blink.mojom.LocalFrameToken frame_token) => (blink.mojom.PermissionStatus status);
+};
diff --git a/shell/renderer/api/electron_api_web_frame.cc b/shell/renderer/api/electron_api_web_frame.cc
index 0f5211c5b2..13b8b2b7bb 100644
--- a/shell/renderer/api/electron_api_web_frame.cc
+++ b/shell/renderer/api/electron_api_web_frame.cc
@@ -31,6 +31,7 @@
#include "shell/common/gin_helper/promise.h"
#include "shell/common/node_includes.h"
#include "shell/common/options_switches.h"
+#include "shell/common/web_contents_utility.mojom.h"
#include "shell/renderer/api/context_bridge/object_cache.h"
#include "shell/renderer/api/electron_api_context_bridge.h"
#include "shell/renderer/api/electron_api_spell_check_client.h"
diff --git a/shell/renderer/content_settings_observer.cc b/shell/renderer/content_settings_observer.cc
index ce66e8d007..e0d2cdae3d 100644
--- a/shell/renderer/content_settings_observer.cc
+++ b/shell/renderer/content_settings_observer.cc
@@ -6,10 +6,12 @@
#include "content/public/renderer/render_frame.h"
#include "shell/common/options_switches.h"
+#include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h"
#include "third_party/blink/public/common/web_preferences/web_preferences.h"
#include "third_party/blink/public/platform/url_conversion.h"
#include "third_party/blink/public/platform/web_security_origin.h"
#include "third_party/blink/public/web/web_local_frame.h"
+#include "third_party/blink/public/web/web_view.h"
namespace electron {
@@ -21,6 +23,15 @@ ContentSettingsObserver::ContentSettingsObserver(
ContentSettingsObserver::~ContentSettingsObserver() = default;
+mojom::ElectronWebContentsUtility&
+ContentSettingsObserver::GetWebContentsUtility() {
+ if (!web_contents_utility_) {
+ render_frame()->GetRemoteAssociatedInterfaces()->GetInterface(
+ &web_contents_utility_);
+ }
+ return *web_contents_utility_;
+}
+
bool ContentSettingsObserver::AllowStorageAccessSync(StorageType storage_type) {
blink::WebFrame* frame = render_frame()->GetWebFrame();
if (frame->GetSecurityOrigin().IsOpaque() ||
@@ -32,6 +43,20 @@ bool ContentSettingsObserver::AllowStorageAccessSync(StorageType storage_type) {
return true;
}
+bool ContentSettingsObserver::AllowReadFromClipboardSync() {
+ blink::WebLocalFrame* frame = render_frame()->GetWebFrame();
+ if (frame->View()->GetWebPreferences().dom_paste_enabled) {
+ blink::mojom::PermissionStatus status{
+ blink::mojom::PermissionStatus::DENIED};
+ GetWebContentsUtility().CanAccessClipboardDeprecated(
+ mojom::PermissionName::DEPRECATED_SYNC_CLIPBOARD_READ,
+ frame->GetLocalFrameToken(), &status);
+ return status == blink::mojom::PermissionStatus::GRANTED;
+ } else {
+ return false;
+ }
+}
+
void ContentSettingsObserver::OnDestruct() {
delete this;
}
diff --git a/shell/renderer/content_settings_observer.h b/shell/renderer/content_settings_observer.h
index 77c04b973a..c58dcf6271 100644
--- a/shell/renderer/content_settings_observer.h
+++ b/shell/renderer/content_settings_observer.h
@@ -6,7 +6,10 @@
#define ELECTRON_SHELL_RENDERER_CONTENT_SETTINGS_OBSERVER_H_
#include "content/public/renderer/render_frame_observer.h"
+#include "mojo/public/cpp/bindings/associated_remote.h"
+#include "shell/common/web_contents_utility.mojom.h"
#include "third_party/blink/public/platform/web_content_settings_client.h"
+#include "url/origin.h"
namespace electron {
@@ -22,10 +25,17 @@ class ContentSettingsObserver : public content::RenderFrameObserver,
// blink::WebContentSettingsClient implementation.
bool AllowStorageAccessSync(StorageType storage_type) override;
+ bool AllowReadFromClipboardSync() override;
private:
// content::RenderFrameObserver implementation.
void OnDestruct() override;
+
+ // A getter for `content_settings_manager_` that ensures it is bound.
+ mojom::ElectronWebContentsUtility& GetWebContentsUtility();
+
+ mojo::AssociatedRemote<mojom::ElectronWebContentsUtility>
+ web_contents_utility_;
};
} // namespace electron
diff --git a/shell/renderer/electron_api_service_impl.h b/shell/renderer/electron_api_service_impl.h
index 1a50a18b01..8c6820f020 100644
--- a/shell/renderer/electron_api_service_impl.h
+++ b/shell/renderer/electron_api_service_impl.h
@@ -10,9 +10,9 @@
#include "base/memory/weak_ptr.h"
#include "content/public/renderer/render_frame.h"
#include "content/public/renderer/render_frame_observer.h"
-#include "electron/shell/common/api/api.mojom.h"
#include "mojo/public/cpp/bindings/pending_receiver.h"
#include "mojo/public/cpp/bindings/receiver.h"
+#include "shell/common/api/api.mojom.h"
namespace electron {
diff --git a/shell/renderer/electron_render_frame_observer.cc b/shell/renderer/electron_render_frame_observer.cc
index b8c7a464b6..23b2b6698f 100644
--- a/shell/renderer/electron_render_frame_observer.cc
+++ b/shell/renderer/electron_render_frame_observer.cc
@@ -9,13 +9,14 @@
#include "base/memory/ref_counted_memory.h"
#include "base/trace_event/trace_event.h"
#include "content/public/renderer/render_frame.h"
-#include "electron/shell/common/api/api.mojom.h"
#include "ipc/ipc_message_macros.h"
#include "net/base/net_module.h"
#include "net/grit/net_resources.h"
#include "services/service_manager/public/cpp/interface_provider.h"
+#include "shell/common/api/api.mojom.h"
#include "shell/common/gin_helper/microtasks_scope.h"
#include "shell/common/options_switches.h"
+#include "shell/common/web_contents_utility.mojom.h"
#include "shell/common/world_ids.h"
#include "shell/renderer/renderer_client_base.h"
#include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h"
diff --git a/spec/chromium-spec.ts b/spec/chromium-spec.ts
index e7491432af..dc54a816df 100644
--- a/spec/chromium-spec.ts
+++ b/spec/chromium-spec.ts
@@ -3326,6 +3326,153 @@ describe('navigator.clipboard.write', () => {
});
});
+describe('paste execCommand', () => {
+ const readClipboard: any = (w: BrowserWindow) => {
+ return w.webContents.executeJavaScript(`
+ new Promise((resolve) => {
+ const timeout = setTimeout(() => {
+ resolve('');
+ }, 2000);
+ document.addEventListener('paste', (event) => {
+ clearTimeout(timeout);
+ event.preventDefault();
+ let paste = event.clipboardData.getData("text");
+ resolve(paste);
+ });
+ document.execCommand('paste');
+ });
+ `, true);
+ };
+
+ let ses: Electron.Session;
+ beforeEach(() => {
+ ses = session.fromPartition(`paste-execCommand-${Math.random()}`);
+ });
+
+ afterEach(() => {
+ ses.setPermissionCheckHandler(null);
+ closeAllWindows();
+ });
+
+ it('is disabled by default', async () => {
+ const w: BrowserWindow = new BrowserWindow({});
+ await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
+ const text = 'Sync Clipboard Disabled by default';
+ clipboard.write({
+ text
+ });
+ const paste = await readClipboard(w);
+ expect(paste).to.be.empty();
+ expect(clipboard.readText()).to.equal(text);
+ });
+
+ it('does not execute with default permissions', async () => {
+ const w: BrowserWindow = new BrowserWindow({
+ webPreferences: {
+ enableDeprecatedPaste: true,
+ session: ses
+ }
+ });
+ await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
+ const text = 'Sync Clipboard Disabled by default permissions';
+ clipboard.write({
+ text
+ });
+ const paste = await readClipboard(w);
+ expect(paste).to.be.empty();
+ expect(clipboard.readText()).to.equal(text);
+ });
+
+ it('does not execute with permission denied', async () => {
+ const w: BrowserWindow = new BrowserWindow({
+ webPreferences: {
+ enableDeprecatedPaste: true,
+ session: ses
+ }
+ });
+ await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
+ ses.setPermissionCheckHandler((webContents, permission) => {
+ if (permission === 'deprecated-sync-clipboard-read') {
+ return false;
+ }
+ return true;
+ });
+ const text = 'Sync Clipboard Disabled by permission denied';
+ clipboard.write({
+ text
+ });
+ const paste = await readClipboard(w);
+ expect(paste).to.be.empty();
+ expect(clipboard.readText()).to.equal(text);
+ });
+
+ it('can trigger paste event when permission is granted', async () => {
+ const w: BrowserWindow = new BrowserWindow({
+ webPreferences: {
+ enableDeprecatedPaste: true,
+ session: ses
+ }
+ });
+ await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
+ ses.setPermissionCheckHandler((webContents, permission) => {
+ if (permission === 'deprecated-sync-clipboard-read') {
+ return true;
+ }
+ return false;
+ });
+ const text = 'Sync Clipboard Test';
+ clipboard.write({
+ text
+ });
+ const paste = await readClipboard(w);
+ expect(paste).to.equal(text);
+ });
+
+ it('can trigger paste event when permission is granted for child windows', async () => {
+ const w: BrowserWindow = new BrowserWindow({
+ webPreferences: {
+ session: ses
+ }
+ });
+ await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
+ w.webContents.setWindowOpenHandler(details => {
+ if (details.url === 'about:blank') {
+ return {
+ action: 'allow',
+ overrideBrowserWindowOptions: {
+ webPreferences: {
+ enableDeprecatedPaste: true,
+ session: ses
+ }
+ }
+ };
+ } else {
+ return {
+ action: 'deny'
+ };
+ }
+ });
+ ses.setPermissionCheckHandler((webContents, permission, requestingOrigin, details) => {
+ if (requestingOrigin === `${webContents?.opener?.origin}/` &&
+ details.requestingUrl === 'about:blank' &&
+ permission === 'deprecated-sync-clipboard-read') {
+ return true;
+ }
+ return false;
+ });
+ const childPromise = once(w.webContents, 'did-create-window') as Promise<[BrowserWindow, Electron.DidCreateWindowDetails]>;
+ w.webContents.executeJavaScript('window.open("about:blank")', true);
+ const [childWindow] = await childPromise;
+ expect(childWindow.webContents.opener).to.equal(w.webContents.mainFrame);
+ const text = 'Sync Clipboard Test for Child Window';
+ clipboard.write({
+ text
+ });
+ const paste = await readClipboard(childWindow);
+ expect(paste).to.equal(text);
+ });
+});
+
ifdescribe((process.platform !== 'linux' || app.isUnityRunning()))('navigator.setAppBadge/clearAppBadge', () => {
let w: BrowserWindow;
|
feat
|
edb939ae8052d7b7f981c1fdd8ab25397bcdce7d
|
Keeley Hammond
|
2024-06-20 03:11:53
|
build: Add ASan Linux build to Actions build/test (#42545)
Co-authored-by: Shelley Vohr <[email protected]>
|
diff --git a/.github/actions/build-electron/action.yml b/.github/actions/build-electron/action.yml
index 3f23db6995..934130ffaf 100644
--- a/.github/actions/build-electron/action.yml
+++ b/.github/actions/build-electron/action.yml
@@ -23,6 +23,9 @@ inputs:
upload-to-storage:
description: 'Upload to storage'
required: true
+ is-asan:
+ description: 'The ASan Linux build'
+ required: false
runs:
using: "composite"
steps:
@@ -56,7 +59,7 @@ runs:
run: |
cd src
e build electron:electron_dist_zip -j $NUMBER_OF_NINJA_PROCESSES
- if [ "${{ env.CHECK_DIST_MANIFEST }}" = "true" ]; then
+ if [ "${{ inputs.is-asan }}" != "true" ]; then
target_os=${{ inputs.target-platform == 'linux' && 'linux' || 'mac'}}
if [ "${{ inputs.artifact-platform }}" = "mas" ]; then
target_os="${target_os}_mas"
@@ -181,6 +184,15 @@ runs:
echo 'Uploading Electron release distribution to GitHub releases'
script/release/uploaders/upload.py --verbose
fi
+ - name: Generate Artifact Key
+ shell: bash
+ run: |
+ if [ "${{ inputs.is-asan }}" = "true" ]; then
+ ARTIFACT_KEY=${{ inputs.artifact-platform }}_${{ env.TARGET_ARCH }}_asan
+ else
+ ARTIFACT_KEY=${{ inputs.artifact-platform }}_${{ env.TARGET_ARCH }}
+ fi
+ echo "ARTIFACT_KEY=$ARTIFACT_KEY" >> $GITHUB_ENV
# The current generated_artifacts_<< artifact.key >> name was taken from CircleCI
# to ensure we don't break anything, but we may be able to improve that.
- name: Move all Generated Artifacts to Upload Folder ${{ inputs.step-suffix }}
@@ -189,10 +201,10 @@ runs:
- name: Upload Generated Artifacts ${{ inputs.step-suffix }}
uses: actions/upload-artifact@65462800fd760344b1a7b4382951275a0abb4808
with:
- name: generated_artifacts_${{ inputs.artifact-platform }}_${{ env.TARGET_ARCH }}
+ name: generated_artifacts_${{ env.ARTIFACT_KEY }}
path: ./generated_artifacts_${{ inputs.artifact-platform }}_${{ env.TARGET_ARCH }}
- name: Upload Src Artifacts ${{ inputs.step-suffix }}
uses: actions/upload-artifact@65462800fd760344b1a7b4382951275a0abb4808
with:
- name: src_artifacts_${{ inputs.artifact-platform }}_${{ env.TARGET_ARCH }}
+ name: src_artifacts_${{ env.ARTIFACT_KEY }}
path: ./src_artifacts_${{ inputs.artifact-platform }}_${{ env.TARGET_ARCH }}
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index 3c63cd14e9..d373d383eb 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -163,6 +163,27 @@ jobs:
generate-symbols: false
upload-to-storage: '0'
secrets: inherit
+
+ linux-x64-asan:
+ permissions:
+ contents: read
+ issues: read
+ pull-requests: read
+ uses: ./.github/workflows/pipeline-electron-build-and-test.yml
+ needs: checkout-linux
+ with:
+ build-runs-on: aks-linux-large
+ test-runs-on: aks-linux-medium
+ build-container: '{"image":"ghcr.io/electron/build:${{ inputs.build-image-sha }}","options":"--user root","volumes":["/mnt/cross-instance-cache:/mnt/cross-instance-cache"]}'
+ test-container: '{"image":"ghcr.io/electron/build:${{ inputs.build-image-sha }}","options":"--user root --privileged --init"}'
+ target-platform: linux
+ target-arch: x64
+ is-release: false
+ gn-build-type: testing
+ generate-symbols: false
+ upload-to-storage: '0'
+ is-asan: true
+ secrets: inherit
linux-arm:
permissions:
diff --git a/.github/workflows/pipeline-electron-build-and-test-and-nan.yml b/.github/workflows/pipeline-electron-build-and-test-and-nan.yml
index f17ca4d096..2e0792d5cb 100644
--- a/.github/workflows/pipeline-electron-build-and-test-and-nan.yml
+++ b/.github/workflows/pipeline-electron-build-and-test-and-nan.yml
@@ -49,6 +49,11 @@ on:
required: true
type: string
default: '0'
+ is-asan:
+ description: 'Building the Address Sanitizer (ASan) Linux build'
+ required: false
+ type: boolean
+ default: false
concurrency:
group: electron-build-and-test-and-nan-${{ inputs.target-platform }}-${{ inputs.target-arch }}-${{ github.ref }}
@@ -75,6 +80,7 @@ jobs:
check-runs-on: ${{ inputs.build-runs-on }}
check-container: ${{ inputs.build-container }}
gn-build-type: ${{ inputs.gn-build-type }}
+ is-asan: ${{ inputs.is-asan }}
secrets: inherit
test:
uses: ./.github/workflows/pipeline-segment-electron-test.yml
diff --git a/.github/workflows/pipeline-electron-build-and-test.yml b/.github/workflows/pipeline-electron-build-and-test.yml
index 37b79751be..51eb9bd46c 100644
--- a/.github/workflows/pipeline-electron-build-and-test.yml
+++ b/.github/workflows/pipeline-electron-build-and-test.yml
@@ -49,6 +49,11 @@ on:
required: true
type: string
default: '0'
+ is-asan:
+ description: 'Building the Address Sanitizer (ASan) Linux build'
+ required: false
+ type: boolean
+ default: false
concurrency:
group: electron-build-and-test-${{ inputs.target-platform }}-${{ inputs.target-arch }}-${{ github.ref }}
@@ -71,6 +76,7 @@ jobs:
gn-build-type: ${{ inputs.gn-build-type }}
generate-symbols: ${{ inputs.generate-symbols }}
upload-to-storage: ${{ inputs.upload-to-storage }}
+ is-asan: ${{ inputs.is-asan}}
secrets: inherit
gn-check:
uses: ./.github/workflows/pipeline-segment-electron-gn-check.yml
@@ -80,6 +86,7 @@ jobs:
check-runs-on: ${{ inputs.build-runs-on }}
check-container: ${{ inputs.build-container }}
gn-build-type: ${{ inputs.gn-build-type }}
+ is-asan: ${{ inputs.is-asan }}
secrets: inherit
test:
uses: ./.github/workflows/pipeline-segment-electron-test.yml
@@ -89,4 +96,5 @@ jobs:
target-platform: ${{ inputs.target-platform }}
test-runs-on: ${{ inputs.test-runs-on }}
test-container: ${{ inputs.test-container }}
+ is-asan: ${{ inputs.is-asan}}
secrets: inherit
diff --git a/.github/workflows/pipeline-segment-electron-build.yml b/.github/workflows/pipeline-segment-electron-build.yml
index 21c1250832..1b2f2e64ba 100644
--- a/.github/workflows/pipeline-segment-electron-build.yml
+++ b/.github/workflows/pipeline-segment-electron-build.yml
@@ -44,10 +44,15 @@ on:
required: true
type: string
default: '0'
+ is-asan:
+ description: 'Building the Address Sanitizer (ASan) Linux build'
+ required: false
+ type: boolean
+ default: false
concurrency:
- group: electron-build-${{ inputs.target-platform }}-${{ inputs.target-arch }}-${{ github.ref }}
+ group: electron-build-${{ inputs.target-platform }}-${{ inputs.target-arch }}-${{ inputs.is-asan }}-${{ github.ref }}
cancel-in-progress: ${{ github.ref != 'refs/heads/main' && !endsWith(github.ref, '-x-y') }}
env:
@@ -102,6 +107,8 @@ jobs:
fi
elif [ "${{ inputs.target-arch }}" = "arm64" ]; then
GN_EXTRA_ARGS='target_cpu="arm64" fatal_linker_warnings=false enable_linux_installer=false'
+ elif [ "${{ inputs.is-asan }}" = true ]; then
+ GN_EXTRA_ARGS='is_asan=true'
fi
echo "GN_EXTRA_ARGS=$GN_EXTRA_ARGS" >> $GITHUB_ENV
- name: Get Depot Tools
@@ -183,6 +190,7 @@ jobs:
is-release: '${{ inputs.is-release }}'
generate-symbols: '${{ inputs.generate-symbols }}'
upload-to-storage: '${{ inputs.upload-to-storage }}'
+ is-asan: '${{ inputs.is-asan }}'
- name: Set GN_EXTRA_ARGS for MAS Build
if: ${{ inputs.target-platform == 'macos' }}
run: |
diff --git a/.github/workflows/pipeline-segment-electron-gn-check.yml b/.github/workflows/pipeline-segment-electron-gn-check.yml
index 051e0a052f..378c5d320f 100644
--- a/.github/workflows/pipeline-segment-electron-gn-check.yml
+++ b/.github/workflows/pipeline-segment-electron-gn-check.yml
@@ -25,9 +25,14 @@ on:
required: true
type: string
default: testing
+ is-asan:
+ description: 'Building the Address Sanitizer (ASan) Linux build'
+ required: false
+ type: boolean
+ default: false
concurrency:
- group: electron-gn-check-${{ inputs.target-platform }}-${{ inputs.target-arch }}-${{ github.ref }}
+ group: electron-gn-check-${{ inputs.target-platform }}-${{ inputs.target-arch }}-${{ inputs.is-asan }}-${{ github.ref }}
cancel-in-progress: true
env:
diff --git a/.github/workflows/pipeline-segment-electron-test.yml b/.github/workflows/pipeline-segment-electron-test.yml
index 4767e4211d..fb9e678023 100644
--- a/.github/workflows/pipeline-segment-electron-test.yml
+++ b/.github/workflows/pipeline-segment-electron-test.yml
@@ -20,9 +20,14 @@ on:
description: 'JSON container information for aks runs-on'
required: false
default: '{"image":null}'
+ is-asan:
+ description: 'Building the Address Sanitizer (ASan) Linux build'
+ required: false
+ type: boolean
+ default: false
concurrency:
- group: electron-test-${{ inputs.target-platform }}-${{ inputs.target-arch }}-${{ github.ref }}
+ group: electron-test-${{ inputs.target-platform }}-${{ inputs.target-arch }}-${{ inputs.is-asan }}-${{ github.ref }}
cancel-in-progress: ${{ github.ref != 'refs/heads/main' && !endsWith(github.ref, '-x-y') }}
permissions:
@@ -47,6 +52,7 @@ jobs:
env:
BUILD_TYPE: ${{ matrix.build-type }}
TARGET_ARCH: ${{ inputs.target-arch }}
+ ARTIFACT_KEY: ${{ matrix.build-type }}_${{ inputs.target-arch }}
steps:
- name: Fix node20 on arm32 runners
if: ${{ inputs.target-arch == 'arm' }}
@@ -112,16 +118,22 @@ jobs:
touch .disable_auto_update
- name: Add Depot Tools to PATH
run: echo "$(pwd)/depot_tools" >> $GITHUB_PATH
+ - name: Load ASan specific environment variables
+ if: ${{ inputs.is-asan == true }}
+ run: |
+ echo "ARTIFACT_KEY=${{ matrix.build-type }}_${{ inputs.target-arch }}_asan" >> $GITHUB_ENV
+ echo "DISABLE_CRASH_REPORTER_TESTS=true" >> $GITHUB_ENV
+ echo "IS_ASAN=true" >> $GITHUB_ENV
- name: Download Generated Artifacts
uses: actions/download-artifact@65a9edc5881444af0b9093a5e628f2fe47ea3b2e
with:
- name: generated_artifacts_${{ matrix.build-type }}_${{ inputs.target-arch }}
+ name: generated_artifacts_${{ env.ARTIFACT_KEY }}
path: ./generated_artifacts_${{ matrix.build-type }}_${{ inputs.target-arch }}
- name: Download Src Artifacts
uses: actions/download-artifact@65a9edc5881444af0b9093a5e628f2fe47ea3b2e
with:
- name: src_artifacts_${{ matrix.build-type }}_${{ env.TARGET_ARCH }}
- path: ./src_artifacts_${{ matrix.build-type }}_${{ env.TARGET_ARCH }}
+ name: src_artifacts_${{ env.ARTIFACT_KEY }}
+ path: ./src_artifacts_${{ matrix.build-type }}_${{ inputs.target-arch }}
- name: Restore Generated Artifacts
run: ./src/electron/script/actions/restore-artifacts.sh
- name: Unzip Dist, Mksnapshot & Chromedriver
@@ -159,7 +171,21 @@ jobs:
chown -R :builduser . && chmod -R g+w .
chmod 4755 ../out/Default/chrome-sandbox
runuser -u builduser -- git config --global --add safe.directory $(pwd)
- runuser -u builduser -- xvfb-run script/actions/run-tests.sh script/yarn test --runners=main --trace-uncaught --enable-logging --files $tests_files
+ if [ "${{ inputs.is-asan }}" == "true" ]; then
+ cd ..
+ ASAN_SYMBOLIZE="$PWD/tools/valgrind/asan/asan_symbolize.py --executable-path=$PWD/out/Default/electron"
+ export ASAN_OPTIONS="symbolize=0 handle_abort=1"
+ export G_SLICE=always-malloc
+ export NSS_DISABLE_ARENA_FREE_LIST=1
+ export NSS_DISABLE_UNLOAD=1
+ export LLVM_SYMBOLIZER_PATH=$PWD/third_party/llvm-build/Release+Asserts/bin/llvm-symbolizer
+ export MOCHA_TIMEOUT=180000
+ echo "Piping output to ASAN_SYMBOLIZE ($ASAN_SYMBOLIZE)"
+ cd electron
+ runuser -u builduser -- xvfb-run script/actions/run-tests.sh script/yarn test --runners=main --trace-uncaught --enable-logging --files $tests_files | $ASAN_SYMBOLIZE
+ else
+ runuser -u builduser -- xvfb-run script/actions/run-tests.sh script/yarn test --runners=main --trace-uncaught --enable-logging --files $tests_files
+ fi
fi
- name: Wait for active SSH sessions
if: always() && !cancelled()
|
build
|
efff369639b459b89b8e241063e8f764fbf37f84
|
Keeley Hammond
|
2024-07-01 02:34:37
|
build: remove MacOS x64 from CircleCI (#42718)
|
diff --git a/.circleci/config/base.yml b/.circleci/config/base.yml
index 5b9e62f6bf..51af7d5253 100644
--- a/.circleci/config/base.yml
+++ b/.circleci/config/base.yml
@@ -33,7 +33,7 @@ parameters:
macos-publish-arch-limit:
type: enum
default: all
- enum: ["all", "osx-x64", "osx-arm64", "mas-x64", "mas-arm64"]
+ enum: ["all", "osx-arm64", "mas-arm64"]
medium-linux-executor:
type: enum
@@ -64,7 +64,7 @@ executors:
size:
description: "macOS executor size"
type: enum
- enum: ["macos.x86.medium.gen2", "macos.m1.large.gen1", "macos.m1.medium.gen1"]
+ enum: ["macos.m1.large.gen1", "macos.m1.medium.gen1"]
version:
description: "xcode version"
type: enum
@@ -2029,76 +2029,6 @@ jobs:
checkout: true
build-type: 'Linux ARM64'
- osx-testing-x64:
- executor:
- name: macos
- size: macos.x86.medium.gen2
- environment:
- <<: *env-mac-large
- <<: *env-testing-build
- <<: *env-ninja-status
- <<: *env-macos-build
- GCLIENT_EXTRA_ARGS: '--custom-var=checkout_mac=True --custom-var=host_os=mac'
- steps:
- - electron-build:
- persist: true
- checkout: false
- checkout-and-assume-cache: true
- attach: true
- artifact-key: 'darwin-x64'
- build-type: 'Darwin'
- after-build-and-save:
- - run:
- name: Configuring MAS build
- command: |
- echo 'export GN_EXTRA_ARGS="is_mas_build = true $GN_EXTRA_ARGS"' >> $BASH_ENV
- echo 'export MAS_BUILD="true"' >> $BASH_ENV
- rm -rf "src/out/Default/Electron Framework.framework"
- rm -rf src/out/Default/Electron*.app
- - build_and_save_artifacts:
- artifact-key: 'mas-x64'
- build-type: 'MAS'
- after-persist:
- - persist_to_workspace:
- root: .
- paths:
- - generated_artifacts_mas-x64
- could-be-aks: false
-
- osx-testing-x64-gn-check:
- executor:
- name: macos
- size: macos.x86.medium.gen2
- environment:
- <<: *env-machine-mac
- <<: *env-testing-build
- GCLIENT_EXTRA_ARGS: '--custom-var=checkout_mac=True --custom-var=host_os=mac'
- steps:
- - run-gn-check:
- could-be-aks: false
-
- osx-publish-x64:
- executor:
- name: macos
- size: macos.x86.medium.gen2
- environment:
- <<: *env-mac-large-release
- <<: *env-release-build
- UPLOAD_TO_STORAGE: << pipeline.parameters.upload-to-storage >>
- <<: *env-ninja-status
- steps:
- - run: echo running
- - when:
- condition:
- or:
- - equal: ["all", << pipeline.parameters.macos-publish-arch-limit >>]
- - equal: ["osx-x64", << pipeline.parameters.macos-publish-arch-limit >>]
- steps:
- - electron-publish:
- attach: true
- checkout: false
- build-type: 'Darwin'
-
osx-publish-arm64:
executor:
name: macos
@@ -2308,20 +2238,6 @@ jobs:
- electron-tests:
artifact-key: darwin-arm64
- mas-testing-x64-tests:
- executor:
- name: macos
- size: macos.x86.medium.gen2
- version: 14.0.0
- environment:
- <<: *env-mac-large
- <<: *env-stack-dumping
- parallelism: 2
- steps:
- - run: nvm install lts/iron && nvm alias default lts/iron
- - electron-tests:
- artifact-key: mas-x64
-
mas-testing-arm64-tests:
executor:
name: macos
@@ -2356,27 +2272,6 @@ workflows:
- linux-arm64-publish:
context: release-env
- publish-macos:
- when: << pipeline.parameters.run-macos-publish >>
- jobs:
- - mac-checkout
- - osx-publish-x64:
- requires:
- - mac-checkout
- context: release-env
- - mas-publish-x64:
- requires:
- - mac-checkout
- context: release-env
- - osx-publish-arm64:
- requires:
- - mac-checkout
- context: release-env
- - mas-publish-arm64:
- requires:
- - mac-checkout
- context: release-env
-
build-linux:
when:
and:
@@ -2437,17 +2332,7 @@ workflows:
- equal: [false, << pipeline.parameters.run-linux-publish >>]
- equal: [true, << pipeline.parameters.run-build-mac >>]
jobs:
- - mac-make-src-cache-x64
- mac-make-src-cache-arm64
- - osx-testing-x64:
- requires:
- - mac-make-src-cache-x64
- - osx-testing-x64-gn-check:
- requires:
- - mac-make-src-cache-x64
- - darwin-testing-x64-tests:
- requires:
- - osx-testing-x64
- osx-testing-arm64:
requires:
- mac-make-src-cache-arm64
@@ -2458,9 +2343,6 @@ workflows:
ignore: /pull\/[0-9]+/
requires:
- osx-testing-arm64
- - mas-testing-x64-tests:
- requires:
- - osx-testing-x64
- mas-testing-arm64-tests:
filters:
branches:
|
build
|
febf305a4f77030ca46acc7cc7826acebe01c629
|
David Sanders
|
2024-11-19 01:52:08
|
chore: fix unsupported major comment in issue automation (#44706)
|
diff --git a/.github/workflows/issue-opened.yml b/.github/workflows/issue-opened.yml
index c9feb27fd0..ad2a03c780 100644
--- a/.github/workflows/issue-opened.yml
+++ b/.github/workflows/issue-opened.yml
@@ -88,7 +88,7 @@ jobs:
}
}
if (labels.length === 0) {
- core.setOutput('No supported versions found', true);
+ core.setOutput('unsupportedMajor', true);
labels.push('blocked/need-info ❌');
}
}
|
chore
|
1a6e6518440cb3cf325b4648e2dfef8f9e68053f
|
John Kleinschmidt
|
2024-07-30 09:14:45
|
test: fixup flaky visibility test (#43064)
|
diff --git a/spec/api-web-contents-view-spec.ts b/spec/api-web-contents-view-spec.ts
index 220100434d..cfbca6dc19 100644
--- a/spec/api-web-contents-view-spec.ts
+++ b/spec/api-web-contents-view-spec.ts
@@ -3,7 +3,7 @@ import { BaseWindow, BrowserWindow, View, WebContentsView, webContents, screen }
import { once } from 'node:events';
import { closeAllWindows } from './lib/window-helpers';
-import { defer, ifdescribe } from './lib/spec-helpers';
+import { defer, ifdescribe, waitUntil } from './lib/spec-helpers';
import { HexColors, ScreenCapture, hasCapturableScreen, nextFrameTime } from './lib/screen-helpers';
describe('WebContentsView', () => {
@@ -136,6 +136,11 @@ describe('WebContentsView', () => {
});
describe('visibilityState', () => {
+ async function haveVisibilityState (view: WebContentsView, state: string) {
+ const docVisState = await view.webContents.executeJavaScript('document.visibilityState');
+ return docVisState === state;
+ }
+
it('is initially hidden', async () => {
const v = new WebContentsView();
await v.webContents.loadURL('data:text/html,<script>initialVisibility = document.visibilityState</script>');
@@ -172,7 +177,7 @@ describe('WebContentsView', () => {
const v = new WebContentsView();
w.setContentView(v);
await v.webContents.loadURL('about:blank');
- expect(await v.webContents.executeJavaScript('document.visibilityState')).to.equal('visible');
+ await expect(waitUntil(async () => await haveVisibilityState(v, 'visible'))).to.eventually.be.fulfilled();
const p = v.webContents.executeJavaScript('new Promise(resolve => document.addEventListener("visibilitychange", resolve))');
// We have to wait until the listener above is fully registered before hiding the window.
// On Windows, the executeJavaScript and the visibilitychange can happen out of order
@@ -204,7 +209,7 @@ describe('WebContentsView', () => {
const v = new WebContentsView();
w.setContentView(v);
await v.webContents.loadURL('about:blank');
- expect(await v.webContents.executeJavaScript('document.visibilityState')).to.equal('visible');
+ await expect(waitUntil(async () => await haveVisibilityState(v, 'visible'))).to.eventually.be.fulfilled();
const p = v.webContents.executeJavaScript('new Promise(resolve => document.addEventListener("visibilitychange", () => resolve(document.visibilityState)))');
// Ensure the listener has been registered.
diff --git a/spec/lib/spec-helpers.ts b/spec/lib/spec-helpers.ts
index b12ca77b55..c2ecb4b16a 100644
--- a/spec/lib/spec-helpers.ts
+++ b/spec/lib/spec-helpers.ts
@@ -9,6 +9,7 @@ import * as url from 'node:url';
import { SuiteFunction, TestFunction } from 'mocha';
import { BrowserWindow } from 'electron/main';
import { AssertionError } from 'chai';
+import { setTimeout } from 'node:timers/promises';
const addOnly = <T>(fn: Function): T => {
const wrapped = (...args: any[]) => {
@@ -92,49 +93,50 @@ export async function startRemoteControlApp (extraArgs: string[] = [], options?:
}
export function waitUntil (
- callback: () => boolean,
+ callback: () => boolean|Promise<boolean>,
opts: { rate?: number, timeout?: number } = {}
) {
const { rate = 10, timeout = 10000 } = opts;
- return new Promise<void>((resolve, reject) => {
- let intervalId: NodeJS.Timeout | undefined; // eslint-disable-line prefer-const
- let timeoutId: NodeJS.Timeout | undefined;
+ return (async () => {
+ const ac = new AbortController();
+ const signal = ac.signal;
+ let checkCompleted = false;
+ let timedOut = false;
- const cleanup = () => {
- if (intervalId) clearInterval(intervalId);
- if (timeoutId) clearTimeout(timeoutId);
- };
-
- const check = () => {
+ const check = async () => {
let result;
try {
- result = callback();
+ result = await callback();
} catch (e) {
- cleanup();
- reject(e);
- return;
+ ac.abort();
+ throw e;
}
- if (result === true) {
- cleanup();
- resolve();
- return true;
- }
+ return result;
};
- if (check()) {
- return;
- }
+ setTimeout(timeout, { signal })
+ .then(() => {
+ timedOut = true;
+ checkCompleted = true;
+ });
- intervalId = setInterval(check, rate);
+ while (checkCompleted === false) {
+ const checkSatisfied = await check();
+ if (checkSatisfied === true) {
+ ac.abort();
+ checkCompleted = true;
+ return;
+ } else {
+ await setTimeout(rate);
+ }
+ }
- timeoutId = setTimeout(() => {
- timeoutId = undefined;
- cleanup();
- reject(new Error(`waitUntil timed out after ${timeout}ms`));
- }, timeout);
- });
+ if (timedOut) {
+ throw new Error(`waitUntil timed out after ${timeout}ms`);
+ }
+ })();
}
export async function repeatedly<T> (
|
test
|
dffe00b232010811f37f07d509c0f3a00d9f119e
|
Charles Kerr
|
2024-10-29 07:23:08
|
fix: -Wunsafe-buffer-usage warnings with argc, argv (#44366)
* refactor: move uv_setup_args() calls to startup
* refactor: call base::CommandLine::Init() before ContentMain()
* feat: add ElectronCommandLine::AsUtf8()
* refactor: call base::CommandLine::Init() before NodeMain()
* refactor: use ElectronCommandLine::AsUtf8() in NodeMain()
* fix: -Wunsafe-buffer-usage warning in ElectronCommandLine::Init()
* chore: add a DCHECK to confirm ElectronCommandLine was initialized before AsUtf8() is called
* chore: const correctness in ElectronCommandLine::Init() args
* chore: add ElectronCommandLine to macOS Electron Helper app
* chore: move argc, argvc setup into electron_library_main on macOS
* chore: revert BUILD.gn changes
* fix: WideToUTF8() call in ElectronCommandLine::AsUtf8()
* build: add uv to the include paths for app/electron_main_linux
* build: add uv to the include paths for app/electron_library_main.mm
* chore: revert unrelated changes
these were intended for another branch
|
diff --git a/BUILD.gn b/BUILD.gn
index a4a552b784..b0c54bf6bc 100644
--- a/BUILD.gn
+++ b/BUILD.gn
@@ -865,6 +865,7 @@ if (is_mac) {
":electron_framework_resources",
":electron_swiftshader_library",
":electron_xibs",
+ "//third_party/electron_node:node_lib",
]
if (!is_mas_build) {
deps += [ ":electron_crashpad_helper" ]
@@ -1188,6 +1189,7 @@ if (is_mac) {
"//components/crash/core/app",
"//content:sandbox_helper_win",
"//electron/buildflags",
+ "//third_party/electron_node:node_lib",
"//ui/strings",
]
diff --git a/shell/app/electron_library_main.mm b/shell/app/electron_library_main.mm
index 114b8e22e8..3945d97db1 100644
--- a/shell/app/electron_library_main.mm
+++ b/shell/app/electron_library_main.mm
@@ -9,6 +9,7 @@
#include "base/apple/bundle_locations.h"
#include "base/apple/scoped_nsautorelease_pool.h"
#include "base/at_exit.h"
+#include "base/command_line.h"
#include "base/i18n/icu_util.h"
#include "content/public/app/content_main.h"
#include "electron/fuses.h"
@@ -16,21 +17,22 @@
#include "shell/app/node_main.h"
#include "shell/common/electron_command_line.h"
#include "shell/common/mac/main_application_bundle.h"
+#include "uv.h"
int ElectronMain(int argc, char* argv[]) {
- electron::ElectronMainDelegate delegate;
- content::ContentMainParams params(&delegate);
- params.argc = argc;
- params.argv = const_cast<const char**>(argv);
+ argv = uv_setup_args(argc, argv);
+ base::CommandLine::Init(argc, argv);
electron::ElectronCommandLine::Init(argc, argv);
+ electron::ElectronMainDelegate delegate;
+
// Ensure that Bundle Id is set before ContentMain.
// Refs https://chromium-review.googlesource.com/c/chromium/src/+/5581006
delegate.OverrideChildProcessPath();
delegate.OverrideFrameworkBundlePath();
delegate.SetUpBundleOverrides();
- return content::ContentMain(std::move(params));
+ return content::ContentMain(content::ContentMainParams{&delegate});
}
int ElectronInitializeICUandStartNode(int argc, char* argv[]) {
@@ -39,6 +41,10 @@ int ElectronInitializeICUandStartNode(int argc, char* argv[]) {
return 1;
}
+ argv = uv_setup_args(argc, argv);
+ base::CommandLine::Init(argc, argv);
+ electron::ElectronCommandLine::Init(argc, argv);
+
base::AtExitManager atexit_manager;
base::apple::ScopedNSAutoreleasePool pool;
base::apple::SetOverrideFrameworkBundlePath(
@@ -47,5 +53,5 @@ int ElectronInitializeICUandStartNode(int argc, char* argv[]) {
.Append("Frameworks")
.Append(ELECTRON_PRODUCT_NAME " Framework.framework"));
base::i18n::InitializeICU();
- return electron::NodeMain(argc, argv);
+ return electron::NodeMain();
}
diff --git a/shell/app/electron_main_linux.cc b/shell/app/electron_main_linux.cc
index 0eaf88ba57..d12cd55f7e 100644
--- a/shell/app/electron_main_linux.cc
+++ b/shell/app/electron_main_linux.cc
@@ -16,6 +16,7 @@
#include "shell/app/uv_stdio_fix.h"
#include "shell/common/electron_command_line.h"
#include "shell/common/electron_constants.h"
+#include "uv.h"
namespace {
@@ -29,17 +30,16 @@ namespace {
int main(int argc, char* argv[]) {
FixStdioStreams();
+ argv = uv_setup_args(argc, argv);
+ base::CommandLine::Init(argc, argv);
+ electron::ElectronCommandLine::Init(argc, argv);
+
if (electron::fuses::IsRunAsNodeEnabled() && IsEnvSet(electron::kRunAsNode)) {
base::i18n::InitializeICU();
base::AtExitManager atexit_manager;
- return electron::NodeMain(argc, argv);
+ return electron::NodeMain();
}
electron::ElectronMainDelegate delegate;
- content::ContentMainParams params(&delegate);
- electron::ElectronCommandLine::Init(argc, argv);
- params.argc = argc;
- params.argv = const_cast<const char**>(argv);
- base::CommandLine::Init(params.argc, params.argv);
- return content::ContentMain(std::move(params));
+ return content::ContentMain(content::ContentMainParams{&delegate});
}
diff --git a/shell/app/electron_main_win.cc b/shell/app/electron_main_win.cc
index fbf3f9c825..4f89cb5a4c 100644
--- a/shell/app/electron_main_win.cc
+++ b/shell/app/electron_main_win.cc
@@ -127,16 +127,15 @@ int APIENTRY wWinMain(HINSTANCE instance, HINSTANCE, wchar_t* cmd, int) {
// If we are already a fiber then continue normal execution.
#endif // defined(ARCH_CPU_32_BITS)
- struct Arguments {
+ {
int argc = 0;
- RAW_PTR_EXCLUSION wchar_t** argv =
- ::CommandLineToArgvW(::GetCommandLineW(), &argc);
-
- ~Arguments() { LocalFree(argv); }
- } arguments;
-
- if (!arguments.argv)
- return -1;
+ wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc);
+ if (!argv)
+ return -1;
+ base::CommandLine::Init(0, nullptr); // args ignored on Windows
+ electron::ElectronCommandLine::Init(argc, argv);
+ LocalFree(argv);
+ }
#ifdef _DEBUG
// Don't display assert dialog boxes in CI test runs
@@ -159,18 +158,12 @@ int APIENTRY wWinMain(HINSTANCE instance, HINSTANCE, wchar_t* cmd, int) {
if (run_as_node || !IsEnvSet("ELECTRON_NO_ATTACH_CONSOLE"))
base::RouteStdioToConsole(false);
- std::vector<char*> argv(arguments.argc);
- std::transform(arguments.argv, arguments.argv + arguments.argc, argv.begin(),
- [](auto& a) { return _strdup(base::WideToUTF8(a).c_str()); });
if (run_as_node) {
base::AtExitManager atexit_manager;
base::i18n::InitializeICU();
- auto ret = electron::NodeMain(argv.size(), argv.data());
- std::ranges::for_each(argv, free);
- return ret;
+ return electron::NodeMain();
}
- base::CommandLine::Init(argv.size(), argv.data());
const base::CommandLine* command_line =
base::CommandLine::ForCurrentProcess();
@@ -235,6 +228,5 @@ int APIENTRY wWinMain(HINSTANCE instance, HINSTANCE, wchar_t* cmd, int) {
content::ContentMainParams params(&delegate);
params.instance = instance;
params.sandbox_info = &sandbox_info;
- electron::ElectronCommandLine::Init(arguments.argc, arguments.argv);
return content::ContentMain(std::move(params));
}
diff --git a/shell/app/node_main.cc b/shell/app/node_main.cc
index 88e2a8d6e5..8db8d80c14 100644
--- a/shell/app/node_main.cc
+++ b/shell/app/node_main.cc
@@ -27,6 +27,7 @@
#include "shell/app/uv_task_runner.h"
#include "shell/browser/javascript_environment.h"
#include "shell/common/api/electron_bindings.h"
+#include "shell/common/electron_command_line.h"
#include "shell/common/gin_helper/dictionary.h"
#include "shell/common/node_bindings.h"
#include "shell/common/node_includes.h"
@@ -115,12 +116,8 @@ v8::Local<v8::Value> GetParameters(v8::Isolate* isolate) {
namespace electron {
-int NodeMain(int argc, char* argv[]) {
- bool initialized = base::CommandLine::Init(argc, argv);
- if (!initialized) {
- LOG(ERROR) << "Failed to initialize CommandLine";
- exit(1);
- }
+int NodeMain() {
+ DCHECK(base::CommandLine::InitializedForCurrentProcess());
auto os_env = base::Environment::Create();
bool node_options_enabled = electron::fuses::IsNodeOptionsEnabled();
@@ -182,11 +179,8 @@ int NodeMain(int argc, char* argv[]) {
// Explicitly register electron's builtin bindings.
NodeBindings::RegisterBuiltinBindings();
- // Hack around with the argv pointer. Used for process.title = "blah".
- argv = uv_setup_args(argc, argv);
-
// Parse Node.js cli flags and strip out disallowed options.
- std::vector<std::string> args(argv, argv + argc);
+ const std::vector<std::string> args = ElectronCommandLine::AsUtf8();
ExitIfContainsDisallowedFlags(args);
std::unique_ptr<node::InitializationResult> result =
diff --git a/shell/app/node_main.h b/shell/app/node_main.h
index 9aaa91b8dc..90cbb8b434 100644
--- a/shell/app/node_main.h
+++ b/shell/app/node_main.h
@@ -7,7 +7,7 @@
namespace electron {
-int NodeMain(int argc, char* argv[]);
+int NodeMain();
} // namespace electron
diff --git a/shell/common/electron_command_line.cc b/shell/common/electron_command_line.cc
index bc50114cdb..0f474e91eb 100644
--- a/shell/common/electron_command_line.cc
+++ b/shell/common/electron_command_line.cc
@@ -5,7 +5,8 @@
#include "shell/common/electron_command_line.h"
#include "base/command_line.h"
-#include "uv.h" // NOLINT(build/include_directory)
+#include "base/containers/to_vector.h"
+#include "base/strings/utf_string_conversions.h"
namespace electron {
@@ -13,17 +14,25 @@ namespace electron {
base::CommandLine::StringVector ElectronCommandLine::argv_;
// static
-void ElectronCommandLine::Init(int argc, base::CommandLine::CharType** argv) {
+void ElectronCommandLine::Init(int argc,
+ base::CommandLine::CharType const* const* argv) {
DCHECK(argv_.empty());
- // NOTE: uv_setup_args does nothing on Windows, so we don't need to call it.
- // Otherwise we'd have to convert the arguments from UTF16.
-#if !BUILDFLAG(IS_WIN)
- // Hack around with the argv pointer. Used for process.title = "blah"
- argv = uv_setup_args(argc, argv);
-#endif
+ // Safety: as is normal in command lines, argc and argv must correspond
+ // to one another. Otherwise there will be out-of-bounds accesses.
+ argv_.assign(argv, UNSAFE_BUFFERS(argv + argc));
+}
- argv_.assign(argv, argv + argc);
+// static
+std::vector<std::string> ElectronCommandLine::AsUtf8() {
+ DCHECK(!argv_.empty());
+
+#if BUILDFLAG(IS_WIN)
+ return base::ToVector(
+ argv_, [](const auto& wstr) { return base::WideToUTF8(wstr); });
+#else
+ return argv_;
+#endif
}
#if BUILDFLAG(IS_LINUX)
diff --git a/shell/common/electron_command_line.h b/shell/common/electron_command_line.h
index b6c910016b..f9e713c6c3 100644
--- a/shell/common/electron_command_line.h
+++ b/shell/common/electron_command_line.h
@@ -20,7 +20,9 @@ class ElectronCommandLine {
static const base::CommandLine::StringVector& argv() { return argv_; }
- static void Init(int argc, base::CommandLine::CharType** argv);
+ static std::vector<std::string> AsUtf8();
+
+ static void Init(int argc, base::CommandLine::CharType const* const* argv);
#if BUILDFLAG(IS_LINUX)
// On Linux the command line has to be read from base::CommandLine since
diff --git a/shell/common/node_bindings.cc b/shell/common/node_bindings.cc
index ef97b468ff..b2b94d89e0 100644
--- a/shell/common/node_bindings.cc
+++ b/shell/common/node_bindings.cc
@@ -799,15 +799,8 @@ std::shared_ptr<node::Environment> NodeBindings::CreateEnvironment(
v8::Local<v8::Context> context,
node::MultiIsolatePlatform* platform,
std::optional<base::RepeatingCallback<void()>> on_app_code_ready) {
-#if BUILDFLAG(IS_WIN)
- auto& electron_args = ElectronCommandLine::argv();
- std::vector<std::string> args(electron_args.size());
- std::ranges::transform(electron_args, args.begin(),
- [](auto& a) { return base::WideToUTF8(a); });
-#else
- auto args = ElectronCommandLine::argv();
-#endif
- return CreateEnvironment(context, platform, args, {}, on_app_code_ready);
+ return CreateEnvironment(context, platform, ElectronCommandLine::AsUtf8(), {},
+ on_app_code_ready);
}
void NodeBindings::LoadEnvironment(node::Environment* env) {
|
fix
|
22429e21129bd22c06c23f7d714b96d31063d495
|
Shelley Vohr
|
2023-08-15 20:49:21
|
refactor: clean up Node.js cli arg parsing (#39465)
* refactor: clean up Node.js arg parsing
* chore: feedback from review
|
diff --git a/docs/api/command-line-switches.md b/docs/api/command-line-switches.md
index fd63da4f1c..8237cf53f2 100644
--- a/docs/api/command-line-switches.md
+++ b/docs/api/command-line-switches.md
@@ -116,14 +116,20 @@ Ignore the connections limit for `domains` list separated by `,`.
### --js-flags=`flags`
-Specifies the flags passed to the Node.js engine. It has to be passed when starting
-Electron if you want to enable the `flags` in the main process.
+Specifies the flags passed to the [V8 engine](https://v8.dev). In order to enable the `flags` in the main process,
+this switch must be passed on startup.
```sh
$ electron --js-flags="--harmony_proxies --harmony_collections" your-app
```
-See the [Node.js documentation][node-cli] or run `node --help` in your terminal for a list of available flags. Additionally, run `node --v8-options` to see a list of flags that specifically refer to Node.js's V8 JavaScript engine.
+Run `node --v8-options` or `electron --js-flags="--help"` in your terminal for the list of available flags. These can be used to enable early-stage JavaScript features, or log and manipulate garbage collection, among other things.
+
+For example, to trace V8 optimization and deoptimization:
+
+```sh
+$ electron --js-flags="--trace-opt --trace-deopt" your-app
+```
### --lang
diff --git a/shell/app/node_main.cc b/shell/app/node_main.cc
index 8d06bef9a7..79483e2fae 100644
--- a/shell/app/node_main.cc
+++ b/shell/app/node_main.cc
@@ -50,10 +50,10 @@
namespace {
-// Initialize Node.js cli options to pass to Node.js
+// Preparse Node.js cli options to pass to Node.js
// See https://nodejs.org/api/cli.html#cli_options
-int SetNodeCliFlags() {
- // Options that are unilaterally disallowed
+void ExitIfContainsDisallowedFlags(const std::vector<std::string>& argv) {
+ // Options that are unilaterally disallowed.
static constexpr auto disallowed = base::MakeFixedFlatSet<base::StringPiece>({
"--enable-fips",
"--force-fips",
@@ -62,40 +62,18 @@ int SetNodeCliFlags() {
"--use-openssl-ca",
});
- const auto argv = base::CommandLine::ForCurrentProcess()->argv();
- std::vector<std::string> args;
-
- // TODO(codebytere): We need to set the first entry in args to the
- // process name owing to src/node_options-inl.h#L286-L290 but this is
- // redundant and so should be refactored upstream.
- args.reserve(argv.size() + 1);
- args.emplace_back("electron");
-
for (const auto& arg : argv) {
-#if BUILDFLAG(IS_WIN)
- const auto& option = base::WideToUTF8(arg);
-#else
- const auto& option = arg;
-#endif
- const auto stripped = base::StringPiece(option).substr(0, option.find('='));
- if (disallowed.contains(stripped)) {
- LOG(ERROR) << "The Node.js cli flag " << stripped
+ const auto key = base::StringPiece(arg).substr(0, arg.find('='));
+ if (disallowed.contains(key)) {
+ LOG(ERROR) << "The Node.js cli flag " << key
<< " is not supported in Electron";
// Node.js returns 9 from ProcessGlobalArgs for any errors encountered
// when setting up cli flags and env vars. Since we're outlawing these
- // flags (making them errors) return 9 here for consistency.
- return 9;
- } else {
- args.push_back(option);
+ // flags (making them errors) exit with the same error code for
+ // consistency.
+ exit(9);
}
}
-
- std::vector<std::string> errors;
-
- // Node.js itself will output parsing errors to
- // console so we don't need to handle that ourselves
- return ProcessGlobalArgs(&args, nullptr, &errors,
- node::kDisallowedInEnvironment);
}
#if IS_MAS_BUILD()
@@ -116,7 +94,11 @@ v8::Local<v8::Value> GetParameters(v8::Isolate* isolate) {
}
int NodeMain(int argc, char* argv[]) {
- base::CommandLine::Init(argc, argv);
+ bool initialized = base::CommandLine::Init(argc, argv);
+ if (!initialized) {
+ LOG(ERROR) << "Failed to initialize CommandLine";
+ exit(1);
+ }
#if BUILDFLAG(IS_WIN)
v8_crashpad_support::SetUp();
@@ -153,15 +135,13 @@ int NodeMain(int argc, char* argv[]) {
// Explicitly register electron's builtin bindings.
NodeBindings::RegisterBuiltinBindings();
- // Parse and set Node.js cli flags.
- int flags_exit_code = SetNodeCliFlags();
- if (flags_exit_code != 0)
- exit(flags_exit_code);
-
// Hack around with the argv pointer. Used for process.title = "blah".
argv = uv_setup_args(argc, argv);
+ // Parse Node.js cli flags and strip out disallowed options.
std::vector<std::string> args(argv, argv + argc);
+ ExitIfContainsDisallowedFlags(args);
+
std::unique_ptr<node::InitializationResult> result =
node::InitializeOncePerProcess(
args,
diff --git a/shell/common/node_bindings.cc b/shell/common/node_bindings.cc
index 766d043059..815dbb7d28 100644
--- a/shell/common/node_bindings.cc
+++ b/shell/common/node_bindings.cc
@@ -386,7 +386,7 @@ bool NodeBindings::IsInitialized() {
// Initialize Node.js cli options to pass to Node.js
// See https://nodejs.org/api/cli.html#cli_options
-void NodeBindings::SetNodeCliFlags() {
+std::vector<std::string> NodeBindings::ParseNodeCliFlags() {
const auto argv = base::CommandLine::ForCurrentProcess()->argv();
std::vector<std::string> args;
@@ -403,9 +403,7 @@ void NodeBindings::SetNodeCliFlags() {
const auto& option = arg;
#endif
const auto stripped = base::StringPiece(option).substr(0, option.find('='));
-
- // Only allow in no-op (--) option or a small set of debug
- // and trace related options.
+ // Only allow no-op or a small set of debug/trace related options.
if (IsAllowedOption(stripped) || stripped == "--")
args.push_back(option);
}
@@ -417,16 +415,7 @@ void NodeBindings::SetNodeCliFlags() {
args.push_back("--no-experimental-fetch");
}
- std::vector<std::string> errors;
- const int exit_code = ProcessGlobalArgs(&args, nullptr, &errors,
- node::kDisallowedInEnvironment);
-
- const std::string err_str = "Error parsing Node.js cli flags ";
- if (exit_code != 0) {
- LOG(ERROR) << err_str;
- } else if (!errors.empty()) {
- LOG(ERROR) << err_str << base::JoinString(errors, " ");
- }
+ return args;
}
void NodeBindings::Initialize(v8::Local<v8::Context> context) {
@@ -442,13 +431,11 @@ void NodeBindings::Initialize(v8::Local<v8::Context> context) {
// Explicitly register electron's builtin bindings.
RegisterBuiltinBindings();
- // Parse and set Node.js cli flags.
- SetNodeCliFlags();
-
auto env = base::Environment::Create();
SetNodeOptions(env.get());
- std::vector<std::string> argv = {"electron"};
+ // Parse and set Node.js cli flags.
+ std::vector<std::string> argv = ParseNodeCliFlags();
std::vector<std::string> exec_argv;
std::vector<std::string> errors;
uint64_t process_flags = node::ProcessFlags::kNoFlags;
diff --git a/shell/common/node_bindings.h b/shell/common/node_bindings.h
index cb0dd998c9..9182f5440b 100644
--- a/shell/common/node_bindings.h
+++ b/shell/common/node_bindings.h
@@ -92,7 +92,7 @@ class NodeBindings {
// Setup V8, libuv.
void Initialize(v8::Local<v8::Context> context);
- void SetNodeCliFlags();
+ std::vector<std::string> ParseNodeCliFlags();
// Create the environment and load node.js.
node::Environment* CreateEnvironment(v8::Handle<v8::Context> context,
|
refactor
|
9a2ee763d0e8a7fc27ddc1c5a92ed47883917641
|
Shay Molcho
|
2025-02-13 11:55:43
|
docs: added missing period for consistency and readability (#45333)
Added missing period for consistency and readability
Added a missing period in a specific part of the text to maintain consistency across the document. This ensures a uniform writing style, improves readability, and aligns with the formatting used throughout the content.
|
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 3cc4fcca3a..c7cd2de29b 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -71,4 +71,4 @@ See [Coding Style](https://electronjs.org/docs/development/coding-style) for inf
## Further Reading
For more in-depth guides on developing Electron, see
-[/docs/development](/docs/development/README.md)
+[/docs/development](/docs/development/README.md).
|
docs
|
2f288bc7ccfff4e2cae5c4d19cef9eef3e5ec54c
|
Josh Jancourtz
|
2025-02-10 16:15:32
|
docs: fix grammar in preload tutorial summary (#45522)
|
diff --git a/docs/tutorial/tutorial-3-preload.md b/docs/tutorial/tutorial-3-preload.md
index f4138ef893..0854de8305 100644
--- a/docs/tutorial/tutorial-3-preload.md
+++ b/docs/tutorial/tutorial-3-preload.md
@@ -252,7 +252,7 @@ apps often use the preload script to set up inter-process communication (IPC) in
to pass arbitrary messages between the two kinds of processes.
In the next part of the tutorial, we will be showing you resources on adding more
-functionality to your app, then teaching you distributing your app to users.
+functionality to your app, then teaching you how to distribute your app to users.
<!-- Links -->
|
docs
|
7032c0d03c9d4b80fd11bfb972d6fda48b0e6a20
|
Shelley Vohr
|
2024-03-26 12:33:47
|
test: add test and `api_feature` definition for `chrome.scripting.globalParams` (#41685)
chore: add test and api_feature for chrome.scripting.globalParams
|
diff --git a/shell/common/extensions/api/_api_features.json b/shell/common/extensions/api/_api_features.json
index 1358a507e1..a04c487c90 100644
--- a/shell/common/extensions/api/_api_features.json
+++ b/shell/common/extensions/api/_api_features.json
@@ -39,6 +39,14 @@
"contexts": ["blessed_extension", "unblessed_extension", "content_script"],
"max_manifest_version": 2
},
+ "extension.lastError": {
+ "contexts": [
+ "blessed_extension",
+ "unblessed_extension",
+ "content_script"
+ ],
+ "max_manifest_version": 2
+ },
"i18n": {
"channel": "stable",
"extension_types": ["extension"],
@@ -68,5 +76,10 @@
"scripting": {
"dependencies": ["permission:scripting"],
"contexts": ["blessed_extension"]
+ },
+ "scripting.globalParams": {
+ "channel": "trunk",
+ "dependencies": ["permission:scripting"],
+ "contexts": ["content_script"]
}
}
diff --git a/spec/extensions-spec.ts b/spec/extensions-spec.ts
index 97605c62fe..d6fe871447 100644
--- a/spec/extensions-spec.ts
+++ b/spec/extensions-spec.ts
@@ -1285,6 +1285,16 @@ describe('chrome extensions', () => {
});
});
+ it('globalParams', async () => {
+ await w.loadURL(url);
+
+ const message = { method: 'globalParams' };
+ w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
+ const [,, responseString] = await once(w.webContents, 'console-message');
+ const response = JSON.parse(responseString);
+ expect(response).to.deep.equal({ changed: true });
+ });
+
it('insertCSS', async () => {
await w.loadURL(url);
diff --git a/spec/fixtures/extensions/chrome-scripting/background.js b/spec/fixtures/extensions/chrome-scripting/background.js
index 9c080286c0..53a02b1065 100644
--- a/spec/fixtures/extensions/chrome-scripting/background.js
+++ b/spec/fixtures/extensions/chrome-scripting/background.js
@@ -20,6 +20,27 @@ const handleRequest = async (request, sender, sendResponse) => {
break;
}
+ case 'globalParams' : {
+ await chrome.scripting.executeScript({
+ target: { tabId },
+ func: () => {
+ chrome.scripting.globalParams.changed = true;
+ },
+ world: 'ISOLATED'
+ });
+
+ const results = await chrome.scripting.executeScript({
+ target: { tabId },
+ func: () => JSON.stringify(chrome.scripting.globalParams),
+ world: 'ISOLATED'
+ });
+
+ const result = JSON.parse(results[0].result);
+
+ sendResponse(result);
+ break;
+ }
+
case 'registerContentScripts': {
await chrome.scripting.registerContentScripts([{
id: 'session-script',
diff --git a/spec/fixtures/extensions/chrome-scripting/main.js b/spec/fixtures/extensions/chrome-scripting/main.js
index 07aa7d8007..9528d57297 100644
--- a/spec/fixtures/extensions/chrome-scripting/main.js
+++ b/spec/fixtures/extensions/chrome-scripting/main.js
@@ -19,6 +19,11 @@ const map = {
chrome.runtime.sendMessage({ method: 'insertCSS' }, response => {
console.log(JSON.stringify(response));
});
+ },
+ globalParams () {
+ chrome.runtime.sendMessage({ method: 'globalParams' }, response => {
+ console.log(JSON.stringify(response));
+ });
}
};
|
test
|
62a897b75b68ce97ef241bdb0e63ab4ed6a8d8a7
|
Shelley Vohr
|
2024-03-06 10:39:30
|
chore: fix fs overrides for asar (#41507)
fix: fs overrides for asar
|
diff --git a/patches/node/chore_allow_the_node_entrypoint_to_be_a_builtin_module.patch b/patches/node/chore_allow_the_node_entrypoint_to_be_a_builtin_module.patch
index 6955eeada1..4d17a2946c 100644
--- a/patches/node/chore_allow_the_node_entrypoint_to_be_a_builtin_module.patch
+++ b/patches/node/chore_allow_the_node_entrypoint_to_be_a_builtin_module.patch
@@ -8,10 +8,10 @@ they use themselves as the entry point. We should try to upstream some form
of this.
diff --git a/lib/internal/modules/cjs/loader.js b/lib/internal/modules/cjs/loader.js
-index 1f3b719048f2477de183e2856b9b8eee8502f708..21116088c101f4679b5a5f41762ce710368e69ed 100644
+index dbbb454c3fc8a7774c1d190713e88862fda50f22..7a326e925a5769b8ea8e512e30fa655768beae3f 100644
--- a/lib/internal/modules/cjs/loader.js
+++ b/lib/internal/modules/cjs/loader.js
-@@ -1351,6 +1351,13 @@ Module.prototype._compile = function(content, filename) {
+@@ -1350,6 +1350,13 @@ Module.prototype._compile = function(content, filename) {
if (getOptionValue('--inspect-brk') && process._eval == null) {
if (!resolvedArgv) {
// We enter the repl if we're not given a filename argument.
diff --git a/patches/node/fix_lazyload_fs_in_esm_loaders_to_apply_asar_patches.patch b/patches/node/fix_lazyload_fs_in_esm_loaders_to_apply_asar_patches.patch
index 7cbce3398d..b2c21b6e80 100644
--- a/patches/node/fix_lazyload_fs_in_esm_loaders_to_apply_asar_patches.patch
+++ b/patches/node/fix_lazyload_fs_in_esm_loaders_to_apply_asar_patches.patch
@@ -38,7 +38,7 @@ index 6a15fcae677b3bda58fc85f705862bbcd9feec9d..449131b9af99744c08d62d73f8d124ce
const match = RegExpPrototypeExec(DATA_URL_PATTERN, url.pathname);
if (!match) {
diff --git a/lib/internal/modules/esm/resolve.js b/lib/internal/modules/esm/resolve.js
-index 66ecfbcdd4fb2c9986e2d4619a381337839979fe..102165af37a42ca0394ec0d4efc21d3b03efe5eb 100644
+index 66ecfbcdd4fb2c9986e2d4619a381337839979fe..06d23dac1d0f591893643ed2c32711eb2b5c0675 100644
--- a/lib/internal/modules/esm/resolve.js
+++ b/lib/internal/modules/esm/resolve.js
@@ -24,7 +24,7 @@ const {
@@ -50,6 +50,15 @@ index 66ecfbcdd4fb2c9986e2d4619a381337839979fe..102165af37a42ca0394ec0d4efc21d3b
const { getOptionValue } = require('internal/options');
// Do not eagerly grab .manifest, it may be in TDZ
const policy = getOptionValue('--experimental-policy') ?
+@@ -250,7 +250,7 @@ function finalizeResolution(resolved, base, preserveSymlinks) {
+ throw err;
+ }
+
+- const stats = internalModuleStat(toNamespacedPath(StringPrototypeEndsWith(path, '/') ?
++ const stats = internalFsBinding.internalModuleStat(toNamespacedPath(StringPrototypeEndsWith(path, '/') ?
+ StringPrototypeSlice(path, -1) : path));
+
+ // Check for stats.isDirectory()
@@ -266,7 +266,7 @@ function finalizeResolution(resolved, base, preserveSymlinks) {
}
@@ -59,6 +68,15 @@ index 66ecfbcdd4fb2c9986e2d4619a381337839979fe..102165af37a42ca0394ec0d4efc21d3b
[internalFS.realpathCacheKey]: realpathCache,
});
const { search, hash } = resolved;
+@@ -825,7 +825,7 @@ function packageResolve(specifier, base, conditions) {
+ let packageJSONPath = fileURLToPath(packageJSONUrl);
+ let lastPath;
+ do {
+- const stat = internalModuleStat(toNamespacedPath(StringPrototypeSlice(packageJSONPath, 0,
++ const stat = internalFsBinding.internalModuleStat(toNamespacedPath(StringPrototypeSlice(packageJSONPath, 0,
+ packageJSONPath.length - 13)));
+ // Check for !stat.isDirectory()
+ if (stat !== 1) {
diff --git a/lib/internal/modules/esm/translators.js b/lib/internal/modules/esm/translators.js
index e5fea28126b1b810cd3e1e5a13c0fdc97b6b71f5..cea066d1073a31573e134d584f1991e7a06b1036 100644
--- a/lib/internal/modules/esm/translators.js
diff --git a/patches/node/fix_revert_src_lb_reducing_c_calls_of_esm_legacy_main_resolve.patch b/patches/node/fix_revert_src_lb_reducing_c_calls_of_esm_legacy_main_resolve.patch
index ced296ea53..ef4ff1250e 100644
--- a/patches/node/fix_revert_src_lb_reducing_c_calls_of_esm_legacy_main_resolve.patch
+++ b/patches/node/fix_revert_src_lb_reducing_c_calls_of_esm_legacy_main_resolve.patch
@@ -15,7 +15,7 @@ to recognize asar files.
This reverts commit 9cf2e1f55b8446a7cde23699d00a3be73aa0c8f1.
diff --git a/lib/internal/modules/esm/resolve.js b/lib/internal/modules/esm/resolve.js
-index 102165af37a42ca0394ec0d4efc21d3b03efe5eb..cb8341f7378f16d4c0cc5368047a893704147842 100644
+index 06d23dac1d0f591893643ed2c32711eb2b5c0675..585437ce6a5382cd8657e02e4f3bcefc92206d7b 100644
--- a/lib/internal/modules/esm/resolve.js
+++ b/lib/internal/modules/esm/resolve.js
@@ -36,10 +36,9 @@ const preserveSymlinksMain = getOptionValue('--preserve-symlinks-main');
@@ -30,6 +30,15 @@ index 102165af37a42ca0394ec0d4efc21d3b03efe5eb..cb8341f7378f16d4c0cc5368047a8937
const {
ERR_INPUT_TYPE_NOT_ALLOWED,
ERR_INVALID_ARG_TYPE,
+@@ -58,7 +57,7 @@ const { Module: CJSModule } = require('internal/modules/cjs/loader');
+ const { getPackageScopeConfig } = require('internal/modules/esm/package_config');
+ const { getConditionsSet } = require('internal/modules/esm/utils');
+ const packageJsonReader = require('internal/modules/package_json_reader');
+-const { internalModuleStat } = internalBinding('fs');
++const internalFsBinding = internalBinding('fs');
+
+ /**
+ * @typedef {import('internal/modules/esm/package_config.js').PackageConfig} PackageConfig
@@ -161,34 +160,13 @@ function emitLegacyIndexDeprecation(url, packageJSONUrl, base, main) {
const realpathCache = new SafeMap();
@@ -67,7 +76,7 @@ index 102165af37a42ca0394ec0d4efc21d3b03efe5eb..cb8341f7378f16d4c0cc5368047a8937
+ * @returns {boolean}
+ */
+function fileExists(url) {
-+ return internalModuleStat(toNamespacedPath(toPathIfFileURL(url))) === 0;
++ return internalFsBinding.internalModuleStat(toNamespacedPath(toPathIfFileURL(url))) === 0;
+}
/**
diff --git a/patches/node/refactor_allow_embedder_overriding_of_internal_fs_calls.patch b/patches/node/refactor_allow_embedder_overriding_of_internal_fs_calls.patch
index dd6cc69c2d..6584bc3d7a 100644
--- a/patches/node/refactor_allow_embedder_overriding_of_internal_fs_calls.patch
+++ b/patches/node/refactor_allow_embedder_overriding_of_internal_fs_calls.patch
@@ -22,18 +22,19 @@ index 7a773d5208e250abd8b0efb6dde66c45060bbee4..45e38ca0a122e3b1c5d8d59865f9610c
const binding = internalBinding('builtins');
diff --git a/lib/internal/modules/cjs/loader.js b/lib/internal/modules/cjs/loader.js
-index d4b70bab5e89300bfe6305263d556c986380e2e0..1f3b719048f2477de183e2856b9b8eee8502f708 100644
+index d4b70bab5e89300bfe6305263d556c986380e2e0..dbbb454c3fc8a7774c1d190713e88862fda50f22 100644
--- a/lib/internal/modules/cjs/loader.js
+++ b/lib/internal/modules/cjs/loader.js
-@@ -96,6 +96,7 @@ const assert = require('internal/assert');
+@@ -95,7 +95,7 @@ const { containsModuleSyntax } = internalBinding('contextify');
+ const assert = require('internal/assert');
const fs = require('fs');
const path = require('path');
- const { internalModuleStat } = internalBinding('fs');
+-const { internalModuleStat } = internalBinding('fs');
+const internalFsBinding = internalBinding('fs');
const { safeGetenv } = internalBinding('credentials');
const {
privateSymbols: {
-@@ -195,7 +196,7 @@ function stat(filename) {
+@@ -195,7 +195,7 @@ function stat(filename) {
const result = statCache.get(filename);
if (result !== undefined) { return result; }
}
@@ -43,18 +44,19 @@ index d4b70bab5e89300bfe6305263d556c986380e2e0..1f3b719048f2477de183e2856b9b8eee
// Only set cache when `internalModuleStat(filename)` succeeds.
statCache.set(filename, result);
diff --git a/lib/internal/modules/package_json_reader.js b/lib/internal/modules/package_json_reader.js
-index 88c079d10d116107aa34dc9281f64c799c48c0b5..146e2e49dc46c7f5302638f75cca4af548509d77 100644
+index 88c079d10d116107aa34dc9281f64c799c48c0b5..069f922612777f226127dc44f4091eed30416925 100644
--- a/lib/internal/modules/package_json_reader.js
+++ b/lib/internal/modules/package_json_reader.js
-@@ -13,6 +13,7 @@ const {
+@@ -12,7 +12,7 @@ const {
+ const {
ERR_INVALID_PACKAGE_CONFIG,
} = require('internal/errors').codes;
- const { internalModuleReadJSON } = internalBinding('fs');
+-const { internalModuleReadJSON } = internalBinding('fs');
+const internalFsBinding = internalBinding('fs');
const { resolve, sep, toNamespacedPath } = require('path');
const permission = require('internal/process/permission');
const { kEmptyObject } = require('internal/util');
-@@ -53,7 +54,7 @@ function read(jsonPath, { base, specifier, isESM } = kEmptyObject) {
+@@ -53,7 +53,7 @@ function read(jsonPath, { base, specifier, isESM } = kEmptyObject) {
const {
0: string,
1: containsKeys,
|
chore
|
f49f6ff68b5edef36ec503a3fe08569b116f74fd
|
Shelley Vohr
|
2024-08-09 10:08:49
|
fix: check screen capture permissions in `desktopCapturer` (#43080)
fix: check screen capture permissions in desktopCapturer
|
diff --git a/shell/browser/api/electron_api_desktop_capturer.cc b/shell/browser/api/electron_api_desktop_capturer.cc
index c0e1f4eca3..14e6739fd8 100644
--- a/shell/browser/api/electron_api_desktop_capturer.cc
+++ b/shell/browser/api/electron_api_desktop_capturer.cc
@@ -42,6 +42,10 @@
#include "ui/gfx/x/randr.h"
#endif
+#if BUILDFLAG(IS_MAC)
+#include "ui/base/cocoa/permissions_utils.h"
+#endif
+
#if BUILDFLAG(IS_LINUX)
// Private function in ui/base/x/x11_display_util.cc
base::flat_map<x11::RandR::Output, int> GetMonitors(
@@ -305,6 +309,13 @@ void DesktopCapturer::StartHandling(bool capture_window,
capture_window_ = capture_window;
capture_screen_ = capture_screen;
+#if BUILDFLAG(IS_MAC)
+ if (!ui::TryPromptUserForScreenCapture()) {
+ HandleFailure();
+ return;
+ }
+#endif
+
{
// Initialize the source list.
// Apply the new thumbnail size and restart capture.
@@ -456,21 +467,25 @@ void DesktopCapturer::UpdateSourcesList(DesktopMediaList* list) {
std::back_inserter(captured_sources_));
}
- if (!capture_window_ && !capture_screen_) {
- v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
- v8::HandleScope scope(isolate);
- gin_helper::CallMethod(this, "_onfinished", captured_sources_);
+ if (!capture_window_ && !capture_screen_)
+ HandleSuccess();
+}
+
+void DesktopCapturer::HandleSuccess() {
+ v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
+ v8::HandleScope scope(isolate);
+ gin_helper::CallMethod(this, "_onfinished", captured_sources_);
- screen_capturer_.reset();
- window_capturer_.reset();
+ screen_capturer_.reset();
+ window_capturer_.reset();
- Unpin();
- }
+ Unpin();
}
void DesktopCapturer::HandleFailure() {
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
v8::HandleScope scope(isolate);
+
gin_helper::CallMethod(this, "_onerror", "Failed to get sources.");
screen_capturer_.reset();
diff --git a/shell/browser/api/electron_api_desktop_capturer.h b/shell/browser/api/electron_api_desktop_capturer.h
index 2269fa6bb7..f02d782a20 100644
--- a/shell/browser/api/electron_api_desktop_capturer.h
+++ b/shell/browser/api/electron_api_desktop_capturer.h
@@ -94,6 +94,7 @@ class DesktopCapturer : public gin::Wrappable<DesktopCapturer>,
void UpdateSourcesList(DesktopMediaList* list);
void HandleFailure();
+ void HandleSuccess();
std::unique_ptr<DesktopListListener> window_listener_;
std::unique_ptr<DesktopListListener> screen_listener_;
|
fix
|
ac58607605642f721fca2a0fb5b8167e4b2dfbac
|
Jeremy Rose
|
2023-03-30 10:07:54
|
docs: remove save-to-disk disposition (#37758)
|
diff --git a/docs/api/web-contents.md b/docs/api/web-contents.md
index 4568936030..d3f200ebdd 100644
--- a/docs/api/web-contents.md
+++ b/docs/api/web-contents.md
@@ -225,7 +225,7 @@ Returns:
Only defined when the window is being created by a form that set
`target=_blank`.
* `disposition` string - Can be `default`, `foreground-tab`,
- `background-tab`, `new-window`, `save-to-disk` and `other`.
+ `background-tab`, `new-window` or `other`.
Emitted _after_ successful creation of a window via `window.open` in the renderer.
Not emitted if the creation of the window is canceled from
@@ -1290,7 +1290,7 @@ Ignore application menu shortcuts while this web contents is focused.
* `frameName` string - Name of the window provided in `window.open()`
* `features` string - Comma separated list of window features provided to `window.open()`.
* `disposition` string - Can be `default`, `foreground-tab`, `background-tab`,
- `new-window`, `save-to-disk` or `other`.
+ `new-window` or `other`.
* `referrer` [Referrer](structures/referrer.md) - The referrer that will be
passed to the new window. May or may not result in the `Referer` header being
sent, depending on the referrer policy.
|
docs
|
f828c1da092caae6b2944d7da151d5a38644892f
|
Samuel Attard
|
2024-10-01 08:50:42
|
build: remove github actions dependabot on release branches (#44054)
|
diff --git a/.github/dependabot.yml b/.github/dependabot.yml
index d747d13d68..04a32c3587 100644
--- a/.github/dependabot.yml
+++ b/.github/dependabot.yml
@@ -11,38 +11,6 @@ updates:
- "no-backport"
- "semver/none"
target-branch: main
- - package-ecosystem: github-actions
- directory: /
- schedule:
- interval: weekly
- labels:
- - "backport-check-skip"
- - "semver/none"
- target-branch: 33-x-y
- - package-ecosystem: github-actions
- directory: /
- schedule:
- interval: weekly
- labels:
- - "backport-check-skip"
- - "semver/none"
- target-branch: 32-x-y
- - package-ecosystem: github-actions
- directory: /
- schedule:
- interval: weekly
- labels:
- - "backport-check-skip"
- - "semver/none"
- target-branch: 31-x-y
- - package-ecosystem: github-actions
- directory: /
- schedule:
- interval: weekly
- labels:
- - "backport-check-skip"
- - "semver/none"
- target-branch: 30-x-y
- package-ecosystem: npm
directories:
- /
|
build
|
855f2193011370f9dac6ebc54af5f7ac12c10ed6
|
BILL SHEN
|
2024-09-19 19:01:36
|
chore: fix compile issue about ambiguous error of multiple methods named 'highlight'. (#43773)
chore: fix ambiguous error of multiple methods named 'highlight'
|
diff --git a/shell/browser/ui/message_box_mac.mm b/shell/browser/ui/message_box_mac.mm
index 373fab1b54..07c60847bb 100644
--- a/shell/browser/ui/message_box_mac.mm
+++ b/shell/browser/ui/message_box_mac.mm
@@ -81,7 +81,7 @@ NSAlert* CreateNSAlert(const MessageBoxSettings& settings) {
// TODO(@codebytere): This behavior violates HIG & should be deprecated.
if (settings.cancel_id == settings.default_id) {
- [[ns_buttons objectAtIndex:settings.default_id] highlight:YES];
+ [(NSButton*)[ns_buttons objectAtIndex:settings.default_id] highlight:YES];
}
}
|
chore
|
885c1878d436ee79f0870fa6f46af8727914b6d8
|
David Sanders
|
2023-01-19 18:59:20
|
test: fix nativeTheme test when system in dark mode (#36943)
|
diff --git a/spec/api-native-theme-spec.ts b/spec/api-native-theme-spec.ts
index 12b9951ad5..d813a5f5a2 100644
--- a/spec/api-native-theme-spec.ts
+++ b/spec/api-native-theme-spec.ts
@@ -36,6 +36,7 @@ describe('nativeTheme module', () => {
});
it('should emit the "updated" event when it is set and the resulting "shouldUseDarkColors" value changes', async () => {
+ nativeTheme.themeSource = 'light';
let updatedEmitted = emittedOnce(nativeTheme, 'updated');
nativeTheme.themeSource = 'dark';
await updatedEmitted;
|
test
|
94a65df2708ddc96bb9c91bd98b66e93a5f22a8e
|
Charles Kerr
|
2024-11-24 08:55:46
|
refactor: remove unnecessary constructor code (#44816)
|
diff --git a/shell/browser/api/electron_api_web_contents.cc b/shell/browser/api/electron_api_web_contents.cc
index 9d4565a19b..a638f04cd3 100644
--- a/shell/browser/api/electron_api_web_contents.cc
+++ b/shell/browser/api/electron_api_web_contents.cc
@@ -540,16 +540,6 @@ const void* kElectronApiWebContentsKey = &kElectronApiWebContentsKey;
const char kRootName[] = "<root>";
struct FileSystem {
- FileSystem() = default;
- FileSystem(const std::string& type,
- const std::string& file_system_name,
- const std::string& root_url,
- const std::string& file_system_path)
- : type(type),
- file_system_name(file_system_name),
- root_url(root_url),
- file_system_path(file_system_path) {}
-
std::string type;
std::string file_system_name;
std::string root_url;
|
refactor
|
4ae43dcb3b34949697e333b863c34cce30701575
|
Shelley Vohr
|
2024-08-22 12:48:25
|
fix: touch bar functionality on BaseWindow (#43353)
* fix: touch bar functionality on BaseWindow
* test: add test for BaseWindow.setTouchBar
|
diff --git a/lib/browser/api/base-window.ts b/lib/browser/api/base-window.ts
index 71385d21e8..8d9c5899da 100644
--- a/lib/browser/api/base-window.ts
+++ b/lib/browser/api/base-window.ts
@@ -1,5 +1,7 @@
import { EventEmitter } from 'events';
import type { BaseWindow as TLWT } from 'electron/main';
+import { TouchBar } from 'electron/main';
+
const { BaseWindow } = process._linkedBinding('electron_browser_base_window') as { BaseWindow: typeof TLWT };
Object.setPrototypeOf(BaseWindow.prototype, EventEmitter.prototype);
@@ -15,6 +17,10 @@ BaseWindow.prototype._init = function (this: TLWT) {
}
};
+BaseWindow.prototype.setTouchBar = function (touchBar) {
+ (TouchBar as any)._setOnWindow(touchBar, this);
+};
+
// Properties
Object.defineProperty(BaseWindow.prototype, 'autoHideMenuBar', {
diff --git a/lib/browser/api/browser-window.ts b/lib/browser/api/browser-window.ts
index 13ec3ef264..ec6b99e141 100644
--- a/lib/browser/api/browser-window.ts
+++ b/lib/browser/api/browser-window.ts
@@ -1,4 +1,4 @@
-import { BaseWindow, WebContents, TouchBar, BrowserView } from 'electron/main';
+import { BaseWindow, WebContents, BrowserView } from 'electron/main';
import type { BrowserWindow as BWT } from 'electron/main';
const { BrowserWindow } = process._linkedBinding('electron_browser_window') as { BrowserWindow: typeof BWT };
@@ -100,10 +100,6 @@ BrowserWindow.fromBrowserView = (browserView: BrowserView) => {
return BrowserWindow.fromWebContents(browserView.webContents);
};
-BrowserWindow.prototype.setTouchBar = function (touchBar) {
- (TouchBar as any)._setOnWindow(touchBar, this);
-};
-
// Forwarded to webContents:
BrowserWindow.prototype.loadURL = function (...args) {
diff --git a/lib/browser/api/touch-bar.ts b/lib/browser/api/touch-bar.ts
index 8f1c244fd8..b9f674f9df 100644
--- a/lib/browser/api/touch-bar.ts
+++ b/lib/browser/api/touch-bar.ts
@@ -284,7 +284,7 @@ const escapeItemSymbol = Symbol('escape item');
class TouchBar extends EventEmitter implements Electron.TouchBar {
// Bind a touch bar to a window
- static _setOnWindow (touchBar: TouchBar | Electron.TouchBarConstructorOptions['items'], window: Electron.BrowserWindow) {
+ static _setOnWindow (touchBar: TouchBar | Electron.TouchBarConstructorOptions['items'], window: Electron.BaseWindow) {
if (window._touchBar != null) {
window._touchBar._removeFromWindow(window);
}
@@ -383,7 +383,7 @@ class TouchBar extends EventEmitter implements Electron.TouchBar {
return this[escapeItemSymbol];
}
- _addToWindow (window: Electron.BrowserWindow) {
+ _addToWindow (window: Electron.BaseWindow) {
const { id } = window;
// Already added to window
@@ -439,7 +439,7 @@ class TouchBar extends EventEmitter implements Electron.TouchBar {
escapeItemListener(this.escapeItem);
}
- _removeFromWindow (window: Electron.BrowserWindow) {
+ _removeFromWindow (window: Electron.BaseWindow) {
const removeListeners = this.windowListeners.get(window.id);
if (removeListeners != null) removeListeners();
}
diff --git a/shell/browser/api/electron_api_base_window.cc b/shell/browser/api/electron_api_base_window.cc
index 3d1a5c292d..91030ed491 100644
--- a/shell/browser/api/electron_api_base_window.cc
+++ b/shell/browser/api/electron_api_base_window.cc
@@ -1251,7 +1251,6 @@ void BaseWindow::BuildPrototype(v8::Isolate* isolate,
.SetMethod("setHiddenInMissionControl",
&BaseWindow::SetHiddenInMissionControl)
#endif
-
.SetMethod("_setTouchBarItems", &BaseWindow::SetTouchBar)
.SetMethod("_refreshTouchBarItem", &BaseWindow::RefreshTouchBarItem)
.SetMethod("_setEscapeTouchBarItem", &BaseWindow::SetEscapeTouchBarItem)
diff --git a/spec/api-touch-bar-spec.ts b/spec/api-touch-bar-spec.ts
index 0de1bbe3b9..2d54eef062 100644
--- a/spec/api-touch-bar-spec.ts
+++ b/spec/api-touch-bar-spec.ts
@@ -1,5 +1,5 @@
import * as path from 'node:path';
-import { BrowserWindow, TouchBar } from 'electron/main';
+import { BaseWindow, BrowserWindow, TouchBar } from 'electron/main';
import { closeWindow } from './lib/window-helpers';
import { expect } from 'chai';
@@ -47,82 +47,86 @@ describe('TouchBar module', () => {
}).to.throw('Cannot add a single instance of TouchBarItem multiple times in a TouchBar');
});
- describe('BrowserWindow behavior', () => {
- let window: BrowserWindow;
+ describe('Window behavior', () => {
+ for (const WindowType of [BrowserWindow, BaseWindow]) {
+ describe(`in ${WindowType.name}`, () => {
+ let window: BaseWindow | BrowserWindow;
- beforeEach(() => {
- window = new BrowserWindow({ show: false });
- });
+ beforeEach(() => {
+ window = new WindowType({ show: false });
+ });
- afterEach(async () => {
- window.setTouchBar(null);
- await closeWindow(window);
- window = null as unknown as BrowserWindow;
- });
+ afterEach(async () => {
+ window.setTouchBar(null);
+ await closeWindow(window);
+ window = null as unknown as BaseWindow | BrowserWindow;
+ });
- it('can be added to and removed from a window', () => {
- const label = new TouchBarLabel({ label: 'bar' });
- const touchBar = new TouchBar({
- items: [
- new TouchBarButton({ label: 'foo', backgroundColor: '#F00', click: () => { } }),
- new TouchBarButton({
- icon: path.join(__dirname, 'fixtures', 'assets', 'logo.png'),
- iconPosition: 'right',
- click: () => { }
- }),
- new TouchBarColorPicker({ selectedColor: '#F00', change: () => { } }),
- new TouchBarGroup({ items: new TouchBar({ items: [new TouchBarLabel({ label: 'hello' })] }) }),
- label,
- new TouchBarOtherItemsProxy(),
- new TouchBarPopover({ items: new TouchBar({ items: [new TouchBarButton({ label: 'pop' })] }) }),
- new TouchBarSlider({ label: 'slide', value: 5, minValue: 2, maxValue: 75, change: () => { } }),
- new TouchBarSpacer({ size: 'large' }),
- new TouchBarSegmentedControl({
- segmentStyle: 'capsule',
- segments: [{ label: 'baz', enabled: false }],
- selectedIndex: 5
- }),
- new TouchBarSegmentedControl({ segments: [] }),
- new TouchBarScrubber({
- items: [{ label: 'foo' }, { label: 'bar' }, { label: 'baz' }],
- selectedStyle: 'outline',
- mode: 'fixed',
- showArrowButtons: true
- })
- ]
- });
- const escapeButton = new TouchBarButton({ label: 'foo' });
- window.setTouchBar(touchBar);
- touchBar.escapeItem = escapeButton;
- label.label = 'baz';
- escapeButton.label = 'hello';
- window.setTouchBar(null);
- window.setTouchBar(new TouchBar({ items: [new TouchBarLabel({ label: 'two' })] }));
- touchBar.escapeItem = null;
- });
+ it('can be added to and removed from a window', () => {
+ const label = new TouchBarLabel({ label: 'bar' });
+ const touchBar = new TouchBar({
+ items: [
+ new TouchBarButton({ label: 'foo', backgroundColor: '#F00', click: () => { } }),
+ new TouchBarButton({
+ icon: path.join(__dirname, 'fixtures', 'assets', 'logo.png'),
+ iconPosition: 'right',
+ click: () => { }
+ }),
+ new TouchBarColorPicker({ selectedColor: '#F00', change: () => { } }),
+ new TouchBarGroup({ items: new TouchBar({ items: [new TouchBarLabel({ label: 'hello' })] }) }),
+ label,
+ new TouchBarOtherItemsProxy(),
+ new TouchBarPopover({ items: new TouchBar({ items: [new TouchBarButton({ label: 'pop' })] }) }),
+ new TouchBarSlider({ label: 'slide', value: 5, minValue: 2, maxValue: 75, change: () => { } }),
+ new TouchBarSpacer({ size: 'large' }),
+ new TouchBarSegmentedControl({
+ segmentStyle: 'capsule',
+ segments: [{ label: 'baz', enabled: false }],
+ selectedIndex: 5
+ }),
+ new TouchBarSegmentedControl({ segments: [] }),
+ new TouchBarScrubber({
+ items: [{ label: 'foo' }, { label: 'bar' }, { label: 'baz' }],
+ selectedStyle: 'outline',
+ mode: 'fixed',
+ showArrowButtons: true
+ })
+ ]
+ });
+ const escapeButton = new TouchBarButton({ label: 'foo' });
+ window.setTouchBar(touchBar);
+ touchBar.escapeItem = escapeButton;
+ label.label = 'baz';
+ escapeButton.label = 'hello';
+ window.setTouchBar(null);
+ window.setTouchBar(new TouchBar({ items: [new TouchBarLabel({ label: 'two' })] }));
+ touchBar.escapeItem = null;
+ });
- it('calls the callback on the items when a window interaction event fires', (done) => {
- const button = new TouchBarButton({
- label: 'bar',
- click: () => {
- done();
- }
- });
- const touchBar = new TouchBar({ items: [button] });
- window.setTouchBar(touchBar);
- window.emit('-touch-bar-interaction', {}, (button as any).id);
- });
+ it('calls the callback on the items when a window interaction event fires', (done) => {
+ const button = new TouchBarButton({
+ label: 'bar',
+ click: () => {
+ done();
+ }
+ });
+ const touchBar = new TouchBar({ items: [button] });
+ window.setTouchBar(touchBar);
+ window.emit('-touch-bar-interaction', {}, (button as any).id);
+ });
- it('calls the callback on the escape item when a window interaction event fires', (done) => {
- const button = new TouchBarButton({
- label: 'bar',
- click: () => {
- done();
- }
+ it('calls the callback on the escape item when a window interaction event fires', (done) => {
+ const button = new TouchBarButton({
+ label: 'bar',
+ click: () => {
+ done();
+ }
+ });
+ const touchBar = new TouchBar({ escapeItem: button });
+ window.setTouchBar(touchBar);
+ window.emit('-touch-bar-interaction', {}, (button as any).id);
+ });
});
- const touchBar = new TouchBar({ escapeItem: button });
- window.setTouchBar(touchBar);
- window.emit('-touch-bar-interaction', {}, (button as any).id);
- });
+ };
});
});
diff --git a/typings/internal-electron.d.ts b/typings/internal-electron.d.ts
index 3632b0118e..c2ef3a496c 100644
--- a/typings/internal-electron.d.ts
+++ b/typings/internal-electron.d.ts
@@ -29,22 +29,23 @@ declare namespace Electron {
interface BaseWindow {
_init(): void;
- }
-
- interface BrowserWindow {
- _init(): void;
_touchBar: Electron.TouchBar | null;
_setTouchBarItems: (items: TouchBarItemType[]) => void;
_setEscapeTouchBarItem: (item: TouchBarItemType | {}) => void;
_refreshTouchBarItem: (itemID: string) => void;
+ on(event: '-touch-bar-interaction', listener: (event: Event, itemID: string, details: any) => void): this;
+ removeListener(event: '-touch-bar-interaction', listener: (event: Event, itemID: string, details: any) => void): this;
+ }
+
+ interface BrowserWindow extends BaseWindow {
+ _init(): void;
_getWindowButtonVisibility: () => boolean;
_getAlwaysOnTopLevel: () => string;
devToolsWebContents: WebContents;
frameName: string;
+ _browserViews: BrowserView[];
on(event: '-touch-bar-interaction', listener: (event: Event, itemID: string, details: any) => void): this;
removeListener(event: '-touch-bar-interaction', listener: (event: Event, itemID: string, details: any) => void): this;
-
- _browserViews: BrowserView[];
}
interface BrowserView {
@@ -67,7 +68,7 @@ declare namespace Electron {
}
interface TouchBar {
- _removeFromWindow: (win: BrowserWindow) => void;
+ _removeFromWindow: (win: BaseWindow) => void;
}
interface WebContents {
|
fix
|
cf67dc8898a1dbc76b60c4f8b50bc794f0259f5a
|
Erick Zhao
|
2025-01-22 01:27:30
|
docs: add DocCardList component for index doc (#45275)
|
diff --git a/docs/tutorial/window-customization.md b/docs/tutorial/window-customization.md
index 71840bdaec..c932035fae 100644
--- a/docs/tutorial/window-customization.md
+++ b/docs/tutorial/window-customization.md
@@ -1,3 +1,5 @@
+import DocCardList from '@theme/DocCardList';
+
# Window Customization
The [`BrowserWindow`][] module is the foundation of your Electron application, and
@@ -5,13 +7,15 @@ it exposes many APIs that let you customize the look and behavior of your app’
This section covers how to implement various use cases for window customization on macOS,
Windows, and Linux.
-:::info
-`BrowserWindow` is a subclass of the [`BaseWindow`][] module. Both modules allow
-you to create and manage application windows in Electron, with the main difference
-being that `BrowserWindow` supports a single, full size web view while `BaseWindow`
-supports composing many web views. `BaseWindow` can be used interchangeably with `BrowserWindow`
-in the examples of the documents in this section.
-:::
+> [!NOTE]
+> `BrowserWindow` is a subclass of the [`BaseWindow`][] module. Both modules allow
+> you to create and manage application windows in Electron, with the main difference
+> being that `BrowserWindow` supports a single, full size web view while `BaseWindow`
+> supports composing many web views. `BaseWindow` can be used interchangeably with `BrowserWindow`
+> in the examples of the documents in this section.
+
+ <!-- markdownlint-disable-next-line MD033 -->
+<DocCardList />
[`BaseWindow`]: ../api/base-window.md
[`BrowserWindow`]: ../api/browser-window.md
|
docs
|
5078cae86181735bc50684fd56d50488bc6766f5
|
Milan Burda
|
2023-08-28 16:29:27
|
chore: remove deprecated `ipcRenderer.sendTo()` (#39087)
chore: remove deprecated ipcRenderer.sendTo()
|
diff --git a/docs/api/ipc-renderer.md b/docs/api/ipc-renderer.md
index 1238ee50c4..6c229a7612 100644
--- a/docs/api/ipc-renderer.md
+++ b/docs/api/ipc-renderer.md
@@ -192,14 +192,6 @@ ipcMain.on('port', (e, msg) => {
For more information on using `MessagePort` and `MessageChannel`, see the [MDN
documentation](https://developer.mozilla.org/en-US/docs/Web/API/MessageChannel).
-### `ipcRenderer.sendTo(webContentsId, channel, ...args)` _Deprecated_
-
-* `webContentsId` number
-* `channel` string
-* `...args` any[]
-
-Sends a message to a window with `webContentsId` via `channel`.
-
### `ipcRenderer.sendToHost(channel, ...args)`
* `channel` string
diff --git a/docs/api/structures/ipc-renderer-event.md b/docs/api/structures/ipc-renderer-event.md
index 4e8b32f47c..135834f209 100644
--- a/docs/api/structures/ipc-renderer-event.md
+++ b/docs/api/structures/ipc-renderer-event.md
@@ -1,9 +1,6 @@
# IpcRendererEvent Object extends `Event`
* `sender` [IpcRenderer](../ipc-renderer.md) - The `IpcRenderer` instance that emitted the event originally
-* `senderId` Integer _Deprecated_ - The `webContents.id` that sent the message, you can call `event.sender.sendTo(event.senderId, ...)` to reply to the message, see [ipcRenderer.sendTo][ipc-renderer-sendto] for more information. This only applies to messages sent from a different renderer. Messages sent directly from the main process set `event.senderId` to `0`.
-* `senderIsMainFrame` boolean (optional) _Deprecated_ - Whether the message sent via [ipcRenderer.sendTo][ipc-renderer-sendto] was sent by the main frame. This is relevant when `nodeIntegrationInSubFrames` is enabled in the originating `webContents`.
* `ports` [MessagePort][][] - A list of MessagePorts that were transferred with this message
-[ipc-renderer-sendto]: ../ipc-renderer.md#ipcrenderersendtowebcontentsid-channel-args-deprecated
[MessagePort]: https://developer.mozilla.org/en-US/docs/Web/API/MessagePort
diff --git a/docs/breaking-changes.md b/docs/breaking-changes.md
index 7a15b66b1f..607437ded4 100644
--- a/docs/breaking-changes.md
+++ b/docs/breaking-changes.md
@@ -52,6 +52,12 @@ if (ret === null) {
}
```
+### Removed: `ipcRenderer.sendTo()`
+
+The `ipcRenderer.sendTo()` API has been removed. It should be replaced by setting up a [`MessageChannel`](tutorial/message-ports.md#setting-up-a-messagechannel-between-two-renderers) between the renderers.
+
+The `senderId` and `senderIsMainFrame` properties of `IpcRendererEvent` have been removed as well.
+
## Planned Breaking API Changes (27.0)
### Removed: macOS 10.13 / 10.14 support
diff --git a/filenames.auto.gni b/filenames.auto.gni
index d7aeead8c3..1d89fc05e3 100644
--- a/filenames.auto.gni
+++ b/filenames.auto.gni
@@ -144,7 +144,6 @@ auto_filenames = {
sandbox_bundle_deps = [
"lib/common/api/native-image.ts",
"lib/common/define-properties.ts",
- "lib/common/deprecate.ts",
"lib/common/ipc-messages.ts",
"lib/common/web-view-methods.ts",
"lib/common/webpack-globals-provider.ts",
@@ -270,7 +269,6 @@ auto_filenames = {
"lib/common/api/native-image.ts",
"lib/common/api/shell.ts",
"lib/common/define-properties.ts",
- "lib/common/deprecate.ts",
"lib/common/init.ts",
"lib/common/ipc-messages.ts",
"lib/common/reset-search-paths.ts",
@@ -309,7 +307,6 @@ auto_filenames = {
"lib/common/api/native-image.ts",
"lib/common/api/shell.ts",
"lib/common/define-properties.ts",
- "lib/common/deprecate.ts",
"lib/common/init.ts",
"lib/common/ipc-messages.ts",
"lib/common/reset-search-paths.ts",
diff --git a/lib/renderer/api/ipc-renderer.ts b/lib/renderer/api/ipc-renderer.ts
index 1977ce4ed3..b637f19271 100644
--- a/lib/renderer/api/ipc-renderer.ts
+++ b/lib/renderer/api/ipc-renderer.ts
@@ -1,5 +1,4 @@
import { EventEmitter } from 'events';
-import * as deprecate from '@electron/internal/common/deprecate';
const { ipc } = process._linkedBinding('electron_renderer_ipc');
@@ -18,12 +17,6 @@ ipcRenderer.sendToHost = function (channel, ...args) {
return ipc.sendToHost(channel, args);
};
-const sendToDeprecated = deprecate.warnOnce('ipcRenderer.sendTo');
-ipcRenderer.sendTo = function (webContentsId, channel, ...args) {
- sendToDeprecated();
- return ipc.sendTo(webContentsId, channel, args);
-};
-
ipcRenderer.invoke = async function (channel, ...args) {
const { error, result } = await ipc.invoke(internal, channel, args);
if (error) {
diff --git a/lib/renderer/common-init.ts b/lib/renderer/common-init.ts
index d4e4bfb910..4910ca6671 100644
--- a/lib/renderer/common-init.ts
+++ b/lib/renderer/common-init.ts
@@ -17,13 +17,9 @@ const isWebView = mainFrame.getWebPreference('isWebView');
// ElectronApiServiceImpl will look for the "ipcNative" hidden object when
// invoking the 'onMessage' callback.
v8Util.setHiddenValue(global, 'ipcNative', {
- onMessage (internal: boolean, channel: string, ports: MessagePort[], args: any[], senderId: number, senderIsMainFrame: boolean) {
- if (internal && senderId !== 0) {
- console.error(`Message ${channel} sent by unexpected WebContents (${senderId})`);
- return;
- }
+ onMessage (internal: boolean, channel: string, ports: MessagePort[], args: any[]) {
const sender = internal ? ipcRendererInternal : ipcRenderer;
- sender.emit(channel, { sender, senderId, ...(senderId ? { senderIsMainFrame } : {}), ports }, ...args);
+ sender.emit(channel, { sender, ports }, ...args);
}
});
diff --git a/shell/browser/api/electron_api_web_contents.cc b/shell/browser/api/electron_api_web_contents.cc
index 4f946d1668..2d0de7c0f6 100644
--- a/shell/browser/api/electron_api_web_contents.cc
+++ b/shell/browser/api/electron_api_web_contents.cc
@@ -2029,32 +2029,6 @@ void WebContents::MessageSync(
internal, channel, std::move(arguments));
}
-void WebContents::MessageTo(int32_t web_contents_id,
- const std::string& channel,
- blink::CloneableMessage arguments,
- content::RenderFrameHost* render_frame_host) {
- TRACE_EVENT1("electron", "WebContents::MessageTo", "channel", channel);
- auto* target_web_contents = FromID(web_contents_id);
-
- if (target_web_contents) {
- content::RenderFrameHost* frame = target_web_contents->MainFrame();
- DCHECK(frame);
-
- v8::HandleScope handle_scope(JavascriptEnvironment::GetIsolate());
- gin::Handle<WebFrameMain> web_frame_main =
- WebFrameMain::From(JavascriptEnvironment::GetIsolate(), frame);
-
- if (!web_frame_main->CheckRenderFrame())
- return;
-
- int32_t sender_id = ID();
- bool sender_is_main_frame = render_frame_host->GetParent() == nullptr;
- web_frame_main->GetRendererApi()->Message(false /* internal */, channel,
- std::move(arguments), sender_id,
- sender_is_main_frame);
- }
-}
-
void WebContents::MessageHost(const std::string& channel,
blink::CloneableMessage arguments,
content::RenderFrameHost* render_frame_host) {
diff --git a/shell/browser/api/electron_api_web_contents.h b/shell/browser/api/electron_api_web_contents.h
index e1fc66378b..fb47ebb904 100644
--- a/shell/browser/api/electron_api_web_contents.h
+++ b/shell/browser/api/electron_api_web_contents.h
@@ -434,10 +434,6 @@ class WebContents : public ExclusiveAccessContext,
blink::CloneableMessage arguments,
electron::mojom::ElectronApiIPC::MessageSyncCallback callback,
content::RenderFrameHost* render_frame_host);
- void MessageTo(int32_t web_contents_id,
- const std::string& channel,
- blink::CloneableMessage arguments,
- content::RenderFrameHost* render_frame_host);
void MessageHost(const std::string& channel,
blink::CloneableMessage arguments,
content::RenderFrameHost* render_frame_host);
diff --git a/shell/browser/api/electron_api_web_frame_main.cc b/shell/browser/api/electron_api_web_frame_main.cc
index 6bd620b99b..24952767db 100644
--- a/shell/browser/api/electron_api_web_frame_main.cc
+++ b/shell/browser/api/electron_api_web_frame_main.cc
@@ -184,9 +184,7 @@ void WebFrameMain::Send(v8::Isolate* isolate,
if (!CheckRenderFrame())
return;
- GetRendererApi()->Message(internal, channel, std::move(message),
- 0 /* sender_id */,
- false /* sender_is_main_frame */);
+ GetRendererApi()->Message(internal, channel, std::move(message));
}
const mojo::Remote<mojom::ElectronRenderer>& WebFrameMain::GetRendererApi() {
diff --git a/shell/browser/electron_api_ipc_handler_impl.cc b/shell/browser/electron_api_ipc_handler_impl.cc
index 2a05bd9d76..8902622a78 100644
--- a/shell/browser/electron_api_ipc_handler_impl.cc
+++ b/shell/browser/electron_api_ipc_handler_impl.cc
@@ -76,16 +76,6 @@ void ElectronApiIPCHandlerImpl::MessageSync(bool internal,
}
}
-void ElectronApiIPCHandlerImpl::MessageTo(int32_t web_contents_id,
- const std::string& channel,
- blink::CloneableMessage arguments) {
- api::WebContents* api_web_contents = api::WebContents::From(web_contents());
- if (api_web_contents) {
- api_web_contents->MessageTo(web_contents_id, channel, std::move(arguments),
- GetRenderFrameHost());
- }
-}
-
void ElectronApiIPCHandlerImpl::MessageHost(const std::string& channel,
blink::CloneableMessage arguments) {
api::WebContents* api_web_contents = api::WebContents::From(web_contents());
diff --git a/shell/browser/electron_api_ipc_handler_impl.h b/shell/browser/electron_api_ipc_handler_impl.h
index 282003f494..1a0ad3a013 100644
--- a/shell/browser/electron_api_ipc_handler_impl.h
+++ b/shell/browser/electron_api_ipc_handler_impl.h
@@ -49,9 +49,6 @@ class ElectronApiIPCHandlerImpl : public mojom::ElectronApiIPC,
const std::string& channel,
blink::CloneableMessage arguments,
MessageSyncCallback callback) override;
- void MessageTo(int32_t web_contents_id,
- const std::string& channel,
- blink::CloneableMessage arguments) override;
void MessageHost(const std::string& channel,
blink::CloneableMessage arguments) override;
diff --git a/shell/common/api/api.mojom b/shell/common/api/api.mojom
index fdf082c25c..3af7f28c19 100644
--- a/shell/common/api/api.mojom
+++ b/shell/common/api/api.mojom
@@ -9,9 +9,7 @@ interface ElectronRenderer {
Message(
bool internal,
string channel,
- blink.mojom.CloneableMessage arguments,
- int32 sender_id,
- bool sender_is_main_frame);
+ blink.mojom.CloneableMessage arguments);
ReceivePostMessage(string channel, blink.mojom.TransferableMessage message);
@@ -71,13 +69,6 @@ interface ElectronApiIPC {
string channel,
blink.mojom.CloneableMessage arguments) => (blink.mojom.CloneableMessage result);
- // Emits an event from the |ipcRenderer| JavaScript object in the target
- // WebContents's main frame, specified by |web_contents_id|.
- MessageTo(
- int32 web_contents_id,
- string channel,
- blink.mojom.CloneableMessage arguments);
-
MessageHost(
string channel,
blink.mojom.CloneableMessage arguments);
diff --git a/shell/renderer/api/electron_api_ipc_renderer.cc b/shell/renderer/api/electron_api_ipc_renderer.cc
index 7096a35ae7..58feca6ad4 100644
--- a/shell/renderer/api/electron_api_ipc_renderer.cc
+++ b/shell/renderer/api/electron_api_ipc_renderer.cc
@@ -77,7 +77,6 @@ class IPCRenderer : public gin::Wrappable<IPCRenderer>,
return gin::Wrappable<IPCRenderer>::GetObjectTemplateBuilder(isolate)
.SetMethod("send", &IPCRenderer::SendMessage)
.SetMethod("sendSync", &IPCRenderer::SendSync)
- .SetMethod("sendTo", &IPCRenderer::SendTo)
.SetMethod("sendToHost", &IPCRenderer::SendToHost)
.SetMethod("invoke", &IPCRenderer::Invoke)
.SetMethod("postMessage", &IPCRenderer::PostMessage);
@@ -169,23 +168,6 @@ class IPCRenderer : public gin::Wrappable<IPCRenderer>,
std::move(transferable_message));
}
- void SendTo(v8::Isolate* isolate,
- gin_helper::ErrorThrower thrower,
- int32_t web_contents_id,
- const std::string& channel,
- v8::Local<v8::Value> arguments) {
- if (!electron_ipc_remote_) {
- thrower.ThrowError(kIPCMethodCalledAfterContextReleasedError);
- return;
- }
- blink::CloneableMessage message;
- if (!electron::SerializeV8Value(isolate, arguments, &message)) {
- return;
- }
- electron_ipc_remote_->MessageTo(web_contents_id, channel,
- std::move(message));
- }
-
void SendToHost(v8::Isolate* isolate,
gin_helper::ErrorThrower thrower,
const std::string& channel,
diff --git a/shell/renderer/electron_api_service_impl.cc b/shell/renderer/electron_api_service_impl.cc
index b1c980a72d..529de045fb 100644
--- a/shell/renderer/electron_api_service_impl.cc
+++ b/shell/renderer/electron_api_service_impl.cc
@@ -82,9 +82,7 @@ void EmitIPCEvent(v8::Local<v8::Context> context,
bool internal,
const std::string& channel,
std::vector<v8::Local<v8::Value>> ports,
- v8::Local<v8::Value> args,
- int32_t sender_id = 0,
- bool sender_is_main_frame = false) {
+ v8::Local<v8::Value> args) {
auto* isolate = context->GetIsolate();
v8::HandleScope handle_scope(isolate);
@@ -93,12 +91,8 @@ void EmitIPCEvent(v8::Local<v8::Context> context,
v8::MicrotasksScope::kRunMicrotasks);
std::vector<v8::Local<v8::Value>> argv = {
- gin::ConvertToV8(isolate, internal),
- gin::ConvertToV8(isolate, channel),
- gin::ConvertToV8(isolate, ports),
- args,
- gin::ConvertToV8(isolate, sender_id),
- gin::ConvertToV8(isolate, sender_is_main_frame)};
+ gin::ConvertToV8(isolate, internal), gin::ConvertToV8(isolate, channel),
+ gin::ConvertToV8(isolate, ports), args};
InvokeIpcCallback(context, "onMessage", argv);
}
@@ -160,9 +154,7 @@ void ElectronApiServiceImpl::OnConnectionError() {
void ElectronApiServiceImpl::Message(bool internal,
const std::string& channel,
- blink::CloneableMessage arguments,
- int32_t sender_id,
- bool sender_is_main_frame) {
+ blink::CloneableMessage arguments) {
blink::WebLocalFrame* frame = render_frame()->GetWebFrame();
if (!frame)
return;
@@ -175,8 +167,7 @@ void ElectronApiServiceImpl::Message(bool internal,
v8::Local<v8::Value> args = gin::ConvertToV8(isolate, arguments);
- EmitIPCEvent(context, internal, channel, {}, args, sender_id,
- sender_is_main_frame);
+ EmitIPCEvent(context, internal, channel, {}, args);
}
void ElectronApiServiceImpl::ReceivePostMessage(
diff --git a/shell/renderer/electron_api_service_impl.h b/shell/renderer/electron_api_service_impl.h
index 0d35b51283..e4488b7f1c 100644
--- a/shell/renderer/electron_api_service_impl.h
+++ b/shell/renderer/electron_api_service_impl.h
@@ -34,9 +34,7 @@ class ElectronApiServiceImpl : public mojom::ElectronRenderer,
void Message(bool internal,
const std::string& channel,
- blink::CloneableMessage arguments,
- int32_t sender_id,
- bool sender_is_main_frame) override;
+ blink::CloneableMessage arguments) override;
void ReceivePostMessage(const std::string& channel,
blink::TransferableMessage message) override;
void TakeHeapSnapshot(mojo::ScopedHandle file,
diff --git a/spec/api-ipc-renderer-spec.ts b/spec/api-ipc-renderer-spec.ts
index 23d0c450b7..558a93a5e0 100644
--- a/spec/api-ipc-renderer-spec.ts
+++ b/spec/api-ipc-renderer-spec.ts
@@ -1,12 +1,9 @@
import { expect } from 'chai';
-import * as path from 'node:path';
-import { ipcMain, BrowserWindow, WebContents, WebPreferences, webContents } from 'electron/main';
+import { ipcMain, BrowserWindow } from 'electron/main';
import { closeWindow } from './lib/window-helpers';
import { once } from 'node:events';
describe('ipcRenderer module', () => {
- const fixtures = path.join(__dirname, 'fixtures');
-
let w: BrowserWindow;
before(async () => {
w = new BrowserWindow({
@@ -135,81 +132,6 @@ describe('ipcRenderer module', () => {
});
});
- describe('sendTo()', () => {
- const generateSpecs = (description: string, webPreferences: WebPreferences) => {
- describe(description, () => {
- let contents: WebContents;
- const payload = 'Hello World!';
-
- before(async () => {
- contents = (webContents as typeof ElectronInternal.WebContents).create({
- preload: path.join(fixtures, 'module', 'preload-ipc-ping-pong.js'),
- ...webPreferences
- });
-
- await contents.loadURL('about:blank');
- });
-
- after(() => {
- contents.destroy();
- contents = null as unknown as WebContents;
- });
-
- it('sends message to WebContents', async () => {
- const data = await w.webContents.executeJavaScript(`new Promise(resolve => {
- const { ipcRenderer } = require('electron')
- ipcRenderer.sendTo(${contents.id}, 'ping', ${JSON.stringify(payload)})
- ipcRenderer.once('pong', (event, data) => resolve(data))
- })`);
- expect(data.payload).to.equal(payload);
- expect(data.senderIsMainFrame).to.be.true();
- });
-
- it('sends message to WebContents from a child frame', async () => {
- const frameCreated = once(w.webContents, 'frame-created') as Promise<[any, Electron.FrameCreatedDetails]>;
-
- const promise = w.webContents.executeJavaScript(`new Promise(resolve => {
- const iframe = document.createElement('iframe');
- iframe.src = 'data:text/html,';
- iframe.name = 'iframe';
- document.body.appendChild(iframe);
-
- const { ipcRenderer } = require('electron');
- ipcRenderer.once('pong', (event, data) => resolve(data));
- })`);
-
- const [, details] = await frameCreated;
- expect(details.frame.name).to.equal('iframe');
-
- await once(details.frame, 'dom-ready');
-
- details.frame.executeJavaScript(`new Promise(resolve => {
- const { ipcRenderer } = require('electron');
- ipcRenderer.sendTo(${contents.id}, 'ping', ${JSON.stringify(payload)});
- })`);
-
- const data = await promise;
- expect(data.payload).to.equal(payload);
- expect(data.senderIsMainFrame).to.be.false();
- });
-
- it('sends message on channel with non-ASCII characters to WebContents', async () => {
- const data = await w.webContents.executeJavaScript(`new Promise(resolve => {
- const { ipcRenderer } = require('electron')
- ipcRenderer.sendTo(${contents.id}, 'ping-æøåü', ${JSON.stringify(payload)})
- ipcRenderer.once('pong-æøåü', (event, data) => resolve(data))
- })`);
- expect(data).to.equal(payload);
- });
- });
- };
-
- generateSpecs('without sandbox', {});
- generateSpecs('with sandbox', { sandbox: true });
- generateSpecs('with contextIsolation', { contextIsolation: true });
- generateSpecs('with contextIsolation + sandbox', { contextIsolation: true, sandbox: true });
- });
-
describe('ipcRenderer.on', () => {
it('is not used for internals', async () => {
const result = await w.webContents.executeJavaScript(`
diff --git a/spec/fixtures/module/preload-ipc-ping-pong.js b/spec/fixtures/module/preload-ipc-ping-pong.js
deleted file mode 100644
index 6fb1834628..0000000000
--- a/spec/fixtures/module/preload-ipc-ping-pong.js
+++ /dev/null
@@ -1,9 +0,0 @@
-const { ipcRenderer } = require('electron');
-
-ipcRenderer.on('ping', function ({ senderId, senderIsMainFrame }, payload) {
- ipcRenderer.sendTo(senderId, 'pong', { payload, senderIsMainFrame });
-});
-
-ipcRenderer.on('ping-æøåü', function (event, payload) {
- ipcRenderer.sendTo(event.senderId, 'pong-æøåü', payload);
-});
diff --git a/spec/ts-smoke/electron/renderer.ts b/spec/ts-smoke/electron/renderer.ts
index 16d0f9c02b..331594179b 100644
--- a/spec/ts-smoke/electron/renderer.ts
+++ b/spec/ts-smoke/electron/renderer.ts
@@ -13,6 +13,9 @@ ipcRenderer.on('asynchronous-reply', (event, arg: any) => {
ipcRenderer.send('asynchronous-message', 'ping');
+// @ts-expect-error Removed API
+ipcRenderer.sendTo(1, 'test', 'Hello World!');
+
// web-frame
// https://github.com/electron/electron/blob/main/docs/api/web-frame.md
diff --git a/typings/internal-ambient.d.ts b/typings/internal-ambient.d.ts
index d4feb411af..9a94341dd1 100644
--- a/typings/internal-ambient.d.ts
+++ b/typings/internal-ambient.d.ts
@@ -17,7 +17,6 @@ declare namespace NodeJS {
send(internal: boolean, channel: string, args: any[]): void;
sendSync(internal: boolean, channel: string, args: any[]): any;
sendToHost(channel: string, args: any[]): void;
- sendTo(webContentsId: number, channel: string, args: any[]): void;
invoke<T>(internal: boolean, channel: string, args: any[]): Promise<{ error: string, result: T }>;
postMessage(channel: string, message: any, transferables: MessagePort[]): void;
}
|
chore
|
72802c374b8fa719fbd2ec69cf25079a3db67df3
|
Niklas Wenzel
|
2024-10-15 17:49:54
|
docs: add section on resource management to base-window.md (#43610)
|
diff --git a/docs/api/base-window.md b/docs/api/base-window.md
index a5a7487ee6..30f2db76fa 100644
--- a/docs/api/base-window.md
+++ b/docs/api/base-window.md
@@ -64,6 +64,31 @@ const child = new BaseWindow({ parent, modal: true })
* On Linux the type of modal windows will be changed to `dialog`.
* On Linux many desktop environments do not support hiding a modal window.
+## Resource management
+
+When you add a [`WebContentsView`](web-contents-view.md) to a `BaseWindow` and the `BaseWindow`
+is closed, the [`webContents`](web-contents.md) of the `WebContentsView` are not destroyed
+automatically.
+
+It is your responsibility to close the `webContents` when you no longer need them, e.g. when
+the `BaseWindow` is closed:
+
+```js
+const { BaseWindow, WebContentsView } = require('electron')
+
+const win = new BaseWindow({ width: 800, height: 600 })
+
+const view = new WebContentsView()
+win.contentView.addChildView(view)
+
+win.on('closed', () => {
+ view.webContents.close()
+})
+```
+
+Unlike with a [`BrowserWindow`](browser-window.md), if you don't explicitly close the
+`webContents`, you'll encounter memory leaks.
+
## Class: BaseWindow
> Create and control windows.
|
docs
|
2844e346b98857ee96f797fced3f9e6df6a88263
|
Charles Kerr
|
2024-09-09 11:51:42
|
refactor: use std::optional in MicrotasksScope (#43621)
avoid an unnecessary heap allocation/free
|
diff --git a/shell/common/gin_helper/microtasks_scope.cc b/shell/common/gin_helper/microtasks_scope.cc
index d1bb0674e6..763d1893d8 100644
--- a/shell/common/gin_helper/microtasks_scope.cc
+++ b/shell/common/gin_helper/microtasks_scope.cc
@@ -16,8 +16,7 @@ MicrotasksScope::MicrotasksScope(v8::Isolate* isolate,
if (!ignore_browser_checkpoint)
v8::MicrotasksScope::PerformCheckpoint(isolate);
} else {
- v8_microtasks_scope_ = std::make_unique<v8::MicrotasksScope>(
- isolate, microtask_queue, scope_type);
+ v8_microtasks_scope_.emplace(isolate, microtask_queue, scope_type);
}
}
diff --git a/shell/common/gin_helper/microtasks_scope.h b/shell/common/gin_helper/microtasks_scope.h
index 69c52552fd..55772dea44 100644
--- a/shell/common/gin_helper/microtasks_scope.h
+++ b/shell/common/gin_helper/microtasks_scope.h
@@ -5,7 +5,7 @@
#ifndef ELECTRON_SHELL_COMMON_GIN_HELPER_MICROTASKS_SCOPE_H_
#define ELECTRON_SHELL_COMMON_GIN_HELPER_MICROTASKS_SCOPE_H_
-#include <memory>
+#include <optional>
#include "v8/include/v8-forward.h"
#include "v8/include/v8-microtask-queue.h"
@@ -27,7 +27,7 @@ class MicrotasksScope {
MicrotasksScope& operator=(const MicrotasksScope&) = delete;
private:
- std::unique_ptr<v8::MicrotasksScope> v8_microtasks_scope_;
+ std::optional<v8::MicrotasksScope> v8_microtasks_scope_;
};
} // namespace gin_helper
|
refactor
|
c9eb3deab58f2562113866eaf89d094e60f8184a
|
Milan Burda
|
2023-09-20 23:41:29
|
chore: remove deprecated `scroll-touch-{begin,end,edge}` events (#39814)
* chore: remove deprecated `scroll-touch-{begin,end,edge}` events
* update spec/ts-smoke
---------
Co-authored-by: John Kleinschmidt <[email protected]>
|
diff --git a/docs/api/browser-window.md b/docs/api/browser-window.md
index dfd2ca6779..f3d621c995 100644
--- a/docs/api/browser-window.md
+++ b/docs/api/browser-window.md
@@ -367,36 +367,6 @@ The following app commands are explicitly supported on Linux:
* `browser-backward`
* `browser-forward`
-#### Event: 'scroll-touch-begin' _macOS_ _Deprecated_
-
-Emitted when scroll wheel event phase has begun.
-
-> **Note**
-> This event is deprecated beginning in Electron 22.0.0. See [Breaking
-> Changes](../breaking-changes.md#deprecated-browserwindow-scroll-touch--events)
-> for details of how to migrate to using the [WebContents
-> `input-event`](./web-contents.md#event-input-event) event.
-
-#### Event: 'scroll-touch-end' _macOS_ _Deprecated_
-
-Emitted when scroll wheel event phase has ended.
-
-> **Note**
-> This event is deprecated beginning in Electron 22.0.0. See [Breaking
-> Changes](../breaking-changes.md#deprecated-browserwindow-scroll-touch--events)
-> for details of how to migrate to using the [WebContents
-> `input-event`](./web-contents.md#event-input-event) event.
-
-#### Event: 'scroll-touch-edge' _macOS_ _Deprecated_
-
-Emitted when scroll wheel event phase filed upon reaching the edge of element.
-
-> **Note**
-> This event is deprecated beginning in Electron 22.0.0. See [Breaking
-> Changes](../breaking-changes.md#deprecated-browserwindow-scroll-touch--events)
-> for details of how to migrate to using the [WebContents
-> `input-event`](./web-contents.md#event-input-event) event.
-
#### Event: 'swipe' _macOS_
Returns:
diff --git a/lib/browser/api/browser-window.ts b/lib/browser/api/browser-window.ts
index a53129d726..2b052218c3 100644
--- a/lib/browser/api/browser-window.ts
+++ b/lib/browser/api/browser-window.ts
@@ -1,6 +1,5 @@
import { BaseWindow, WebContents, BrowserView, TouchBar } from 'electron/main';
import type { BrowserWindow as BWT } from 'electron/main';
-import * as deprecate from '@electron/internal/common/deprecate';
const { BrowserWindow } = process._linkedBinding('electron_browser_window') as { BrowserWindow: typeof BWT };
Object.setPrototypeOf(BrowserWindow.prototype, BaseWindow.prototype);
@@ -53,28 +52,6 @@ BrowserWindow.prototype._init = function (this: BWT) {
this.on(event as any, visibilityChanged);
}
- const warn = deprecate.warnOnceMessage('\'scroll-touch-{begin,end,edge}\' are deprecated and will be removed. Please use the WebContents \'input-event\' event instead.');
- this.webContents.on('input-event', (_, e) => {
- if (e.type === 'gestureScrollBegin') {
- if (this.listenerCount('scroll-touch-begin') !== 0) {
- warn();
- this.emit('scroll-touch-edge');
- this.emit('scroll-touch-begin');
- }
- } else if (e.type === 'gestureScrollUpdate') {
- if (this.listenerCount('scroll-touch-edge') !== 0) {
- warn();
- this.emit('scroll-touch-edge');
- }
- } else if (e.type === 'gestureScrollEnd') {
- if (this.listenerCount('scroll-touch-end') !== 0) {
- warn();
- this.emit('scroll-touch-edge');
- this.emit('scroll-touch-end');
- }
- }
- });
-
// Notify the creation of the window.
app.emit('browser-window-created', { preventDefault () {} }, this);
diff --git a/spec/ts-smoke/electron/main.ts b/spec/ts-smoke/electron/main.ts
index 16c37e96c4..11bc068af0 100644
--- a/spec/ts-smoke/electron/main.ts
+++ b/spec/ts-smoke/electron/main.ts
@@ -1284,6 +1284,13 @@ win4.loadURL('http://github.com');
// @ts-expect-error Removed API
win4.webContents.getPrinters();
+// @ts-expect-error Removed API
+win4.webContents.on('scroll-touch-begin', () => {});
+// @ts-expect-error Removed API
+win4.webContents.on('scroll-touch-edge', () => {});
+// @ts-expect-error Removed API
+win4.webContents.on('scroll-touch-end', () => {});
+
// TouchBar
// https://github.com/electron/electron/blob/main/docs/api/touch-bar.md
|
chore
|
20cff642821cf9dc57b55fef4414fa0b010d329f
|
David Sanders
|
2023-01-02 02:52:18
|
docs: update links (#36657)
|
diff --git a/docs/README.md b/docs/README.md
index 57172020a8..83c3df1fde 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -42,7 +42,7 @@ an issue:
* [Web embeds in Electron](tutorial/web-embeds.md)
* [Boilerplates and CLIs](tutorial/boilerplates-and-clis.md)
* [Boilerplate vs CLI](tutorial/boilerplates-and-clis.md#boilerplate-vs-cli)
- * [electron-forge](tutorial/boilerplates-and-clis.md#electron-forge)
+ * [Electron Forge](tutorial/boilerplates-and-clis.md#electron-forge)
* [electron-builder](tutorial/boilerplates-and-clis.md#electron-builder)
* [electron-react-boilerplate](tutorial/boilerplates-and-clis.md#electron-react-boilerplate)
* [Other Tools and Boilerplates](tutorial/boilerplates-and-clis.md#other-tools-and-boilerplates)
diff --git a/docs/api/auto-updater.md b/docs/api/auto-updater.md
index d181dfaccb..dc82b783ba 100644
--- a/docs/api/auto-updater.md
+++ b/docs/api/auto-updater.md
@@ -32,9 +32,9 @@ This is a requirement of `Squirrel.Mac`.
On Windows, you have to install your app into a user's machine before you can
use the `autoUpdater`, so it is recommended that you use the
-[electron-winstaller][installer-lib], [electron-forge][electron-forge-lib] or the [grunt-electron-installer][installer] package to generate a Windows installer.
+[electron-winstaller][installer-lib], [Electron Forge][electron-forge-lib] or the [grunt-electron-installer][installer] package to generate a Windows installer.
-When using [electron-winstaller][installer-lib] or [electron-forge][electron-forge-lib] make sure you do not try to update your app [the first time it runs](https://github.com/electron/windows-installer#handling-squirrel-events) (Also see [this issue for more info](https://github.com/electron/electron/issues/7155)). It's also recommended to use [electron-squirrel-startup](https://github.com/mongodb-js/electron-squirrel-startup) to get desktop shortcuts for your app.
+When using [electron-winstaller][installer-lib] or [Electron Forge][electron-forge-lib] make sure you do not try to update your app [the first time it runs](https://github.com/electron/windows-installer#handling-squirrel-events) (Also see [this issue for more info](https://github.com/electron/electron/issues/7155)). It's also recommended to use [electron-squirrel-startup](https://github.com/mongodb-js/electron-squirrel-startup) to get desktop shortcuts for your app.
The installer generated with Squirrel will create a shortcut icon with an
[Application User Model ID][app-user-model-id] in the format of
@@ -139,6 +139,6 @@ application starts.
[squirrel-windows]: https://github.com/Squirrel/Squirrel.Windows
[installer]: https://github.com/electron/grunt-electron-installer
[installer-lib]: https://github.com/electron/windows-installer
-[electron-forge-lib]: https://github.com/electron-userland/electron-forge
+[electron-forge-lib]: https://github.com/electron/forge
[app-user-model-id]: https://msdn.microsoft.com/en-us/library/windows/desktop/dd378459(v=vs.85).aspx
[event-emitter]: https://nodejs.org/api/events.html#events_class_eventemitter
diff --git a/docs/api/utility-process.md b/docs/api/utility-process.md
index ed9b44af1a..2c228598de 100644
--- a/docs/api/utility-process.md
+++ b/docs/api/utility-process.md
@@ -132,7 +132,7 @@ Returns:
Emitted when the child process sends a message using [`process.parentPort.postMessage()`](process.md#processparentport).
[`child_process.fork`]: https://nodejs.org/dist/latest-v16.x/docs/api/child_process.html#child_processforkmodulepath-args-options
-[Services API]: https://chromium.googlesource.com/chromium/src/+/master/docs/mojo_and_services.md
+[Services API]: https://chromium.googlesource.com/chromium/src/+/main/docs/mojo_and_services.md
[stdio]: https://nodejs.org/dist/latest/docs/api/child_process.html#optionsstdio
[event-emitter]: https://nodejs.org/api/events.html#events_class_eventemitter
[`MessagePortMain`]: message-port-main.md
diff --git a/docs/tutorial/boilerplates-and-clis.md b/docs/tutorial/boilerplates-and-clis.md
index f344ae1b25..68a7a5728f 100644
--- a/docs/tutorial/boilerplates-and-clis.md
+++ b/docs/tutorial/boilerplates-and-clis.md
@@ -24,7 +24,7 @@ development and release. They are more helpful and supportive but enforce
guidelines on how your code should be structured and built. *Especially for
beginners, using a command line tool is likely to be helpful*.
-## electron-forge
+## Electron Forge
Electron Forge is a tool for packaging and publishing Electron applications. It unifies Electron's tooling ecosystem
into a single extensible interface so that anyone can jump right into making Electron apps.
diff --git a/docs/tutorial/forge-overview.md b/docs/tutorial/forge-overview.md
index e297e700c4..0ec6872ce7 100644
--- a/docs/tutorial/forge-overview.md
+++ b/docs/tutorial/forge-overview.md
@@ -31,6 +31,6 @@ template and submit a new issue.
[(package)]: https://www.electronforge.io/cli#package
[(make)]: https://www.electronforge.io/cli#make
[(publish)]: https://www.electronforge.io/cli#publish
-[GitHub issue tracker]: https://github.com/electron-userland/electron-forge/issues
+[GitHub issue tracker]: https://github.com/electron/forge/issues
[discord]: https://discord.gg/APGC3k5yaH
[tutorial]: https://www.electronjs.org/docs/latest/tutorial/tutorial-prerequisites
diff --git a/docs/tutorial/notifications.md b/docs/tutorial/notifications.md
index 3d3b5ff7ef..3a37dab622 100644
--- a/docs/tutorial/notifications.md
+++ b/docs/tutorial/notifications.md
@@ -138,4 +138,4 @@ GNOME, KDE.
[notification-spec]: https://developer-old.gnome.org/notification-spec/
[app-user-model-id]: https://msdn.microsoft.com/en-us/library/windows/desktop/dd378459(v=vs.85).aspx
[set-app-user-model-id]: ../api/app.md#appsetappusermodelidid-windows
-[squirrel-events]: https://github.com/electron/windows-installer/blob/master/README.md#handling-squirrel-events
+[squirrel-events]: https://github.com/electron/windows-installer/blob/main/README.md#handling-squirrel-events
diff --git a/docs/tutorial/performance.md b/docs/tutorial/performance.md
index d06a8220cf..e45e68a0e5 100644
--- a/docs/tutorial/performance.md
+++ b/docs/tutorial/performance.md
@@ -438,7 +438,7 @@ Call `Menu.setApplicationMenu(null)` before `app.on("ready")`. This will prevent
[request-idle-callback]: https://developer.mozilla.org/en-US/docs/Web/API/Window/requestIdleCallback
[multithreading]: ./multithreading.md
[caniuse]: https://caniuse.com/
-[jquery-need]: http://youmightnotneedjquery.com/
+[jquery-need]: https://youmightnotneedjquery.com/
[service-workers]: https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API
[webpack]: https://webpack.js.org/
[parcel]: https://parceljs.org/
diff --git a/docs/tutorial/snapcraft.md b/docs/tutorial/snapcraft.md
index f87e4cf9af..c315e831cf 100644
--- a/docs/tutorial/snapcraft.md
+++ b/docs/tutorial/snapcraft.md
@@ -13,7 +13,7 @@ system modification.
There are three ways to create a `.snap` file:
-1) Using [`electron-forge`][electron-forge] or
+1) Using [Electron Forge][electron-forge] or
[`electron-builder`][electron-builder], both tools that come with `snap`
support out of the box. This is the easiest option.
2) Using `electron-installer-snap`, which takes `electron-packager`'s output.
@@ -162,7 +162,7 @@ building blocks.
If you do not already have a `.deb` package, using `electron-installer-snap`
might be an easier path to create snap packages. However, multiple solutions
-for creating Debian packages exist, including [`electron-forge`][electron-forge],
+for creating Debian packages exist, including [Electron Forge][electron-forge],
[`electron-builder`][electron-builder] or
[`electron-installer-debian`][electron-installer-debian].
@@ -239,7 +239,7 @@ apps:
[snapcraft-syntax]: https://docs.snapcraft.io/build-snaps/syntax
[electron-packager]: https://github.com/electron/electron-packager
-[electron-forge]: https://github.com/electron-userland/electron-forge
+[electron-forge]: https://github.com/electron/forge
[electron-builder]: https://github.com/electron-userland/electron-builder
[electron-installer-debian]: https://github.com/unindented/electron-installer-debian
[electron-winstaller]: https://github.com/electron/windows-installer
diff --git a/docs/tutorial/tutorial-4-adding-features.md b/docs/tutorial/tutorial-4-adding-features.md
index b5fd630ed6..fc74559cee 100644
--- a/docs/tutorial/tutorial-4-adding-features.md
+++ b/docs/tutorial/tutorial-4-adding-features.md
@@ -63,7 +63,7 @@ into end users' hands.
<!-- Link labels -->
[discord]: https://discord.gg/electronjs
-[github]: https://github.com/electron/electronjs.org-new/issues/new
+[github]: https://github.com/electron/website/issues/new
[how-to]: ./examples.md
[node-platform]: https://nodejs.org/api/process.html#process_process_platform
diff --git a/docs/tutorial/tutorial-6-publishing-updating.md b/docs/tutorial/tutorial-6-publishing-updating.md
index a5a67e7683..f10c536968 100644
--- a/docs/tutorial/tutorial-6-publishing-updating.md
+++ b/docs/tutorial/tutorial-6-publishing-updating.md
@@ -222,8 +222,8 @@ rest of our docs and happy developing! If you have questions, please stop by our
[code-signed]: ./code-signing.md
[discord server]: https://discord.gg/electronjs
[electron fiddle]: https://electronjs.org/fiddle
-[fiddle-build]: https://github.com/electron/fiddle/blob/master/.github/workflows/build.yaml
-[fiddle-forge-config]: https://github.com/electron/fiddle/blob/master/forge.config.js
+[fiddle-build]: https://github.com/electron/fiddle/blob/main/.github/workflows/build.yaml
+[fiddle-forge-config]: https://github.com/electron/fiddle/blob/main/forge.config.js
[github actions]: https://github.com/features/actions
[github publisher]: https://www.electronforge.io/config/publishers/github
[github releases]: https://docs.github.com/en/repositories/releasing-projects-on-github/managing-releases-in-a-repository
|
docs
|
fc917985ae8165e0cbcc11b3bebbcc995b1bd271
|
Shelley Vohr
|
2024-01-30 11:53:19
|
fix: ensure `WebContents` before checking draggable region (#41154)
fix: ensure WebContents before checking draggable region
|
diff --git a/shell/browser/api/electron_api_web_contents_view.cc b/shell/browser/api/electron_api_web_contents_view.cc
index aabda22ff9..9fbc2e2b8e 100644
--- a/shell/browser/api/electron_api_web_contents_view.cc
+++ b/shell/browser/api/electron_api_web_contents_view.cc
@@ -81,11 +81,14 @@ void WebContentsView::SetBackgroundColor(std::optional<WrappedSkColor> color) {
}
int WebContentsView::NonClientHitTest(const gfx::Point& point) {
- gfx::Point local_point(point);
- views::View::ConvertPointFromWidget(view(), &local_point);
- SkRegion* region = api_web_contents_->draggable_region();
- if (region && region->contains(local_point.x(), local_point.y()))
- return HTCAPTION;
+ if (api_web_contents_) {
+ gfx::Point local_point(point);
+ views::View::ConvertPointFromWidget(view(), &local_point);
+ SkRegion* region = api_web_contents_->draggable_region();
+ if (region && region->contains(local_point.x(), local_point.y()))
+ return HTCAPTION;
+ }
+
return HTNOWHERE;
}
|
fix
|
c2d0a28fa2e1940433db30b78b2dffbe2c20f0bc
|
David Sanders
|
2025-01-06 11:41:48
|
ci: enable debugging mode when building electron_dist_zip (#45108)
|
diff --git a/.github/actions/build-electron/action.yml b/.github/actions/build-electron/action.yml
index fe9193b682..6f12ffe4ed 100644
--- a/.github/actions/build-electron/action.yml
+++ b/.github/actions/build-electron/action.yml
@@ -69,7 +69,7 @@ runs:
shell: bash
run: |
cd src
- e build --target electron:electron_dist_zip -j $NUMBER_OF_NINJA_PROCESSES
+ e build --target electron:electron_dist_zip -j $NUMBER_OF_NINJA_PROCESSES -d explain
if [ "${{ inputs.is-asan }}" != "true" ]; then
target_os=${{ inputs.target-platform == 'macos' && 'mac' || inputs.target-platform }}
if [ "${{ inputs.artifact-platform }}" = "mas" ]; then
|
ci
|
327abb4b522423287cf9bcf1fb5a8ea6e8fabe62
|
David Sanders
|
2023-01-02 02:02:15
|
docs: improve dark mode example fiddle (#36596)
|
diff --git a/docs/fiddles/features/macos-dark-mode/index.html b/docs/fiddles/features/dark-mode/index.html
similarity index 100%
rename from docs/fiddles/features/macos-dark-mode/index.html
rename to docs/fiddles/features/dark-mode/index.html
diff --git a/docs/fiddles/features/macos-dark-mode/main.js b/docs/fiddles/features/dark-mode/main.js
similarity index 64%
rename from docs/fiddles/features/macos-dark-mode/main.js
rename to docs/fiddles/features/dark-mode/main.js
index 9503efb5f9..34c0211a43 100644
--- a/docs/fiddles/features/macos-dark-mode/main.js
+++ b/docs/fiddles/features/dark-mode/main.js
@@ -11,20 +11,20 @@ function createWindow () {
})
win.loadFile('index.html')
+}
- ipcMain.handle('dark-mode:toggle', () => {
- if (nativeTheme.shouldUseDarkColors) {
- nativeTheme.themeSource = 'light'
- } else {
- nativeTheme.themeSource = 'dark'
- }
- return nativeTheme.shouldUseDarkColors
- })
+ipcMain.handle('dark-mode:toggle', () => {
+ if (nativeTheme.shouldUseDarkColors) {
+ nativeTheme.themeSource = 'light'
+ } else {
+ nativeTheme.themeSource = 'dark'
+ }
+ return nativeTheme.shouldUseDarkColors
+})
- ipcMain.handle('dark-mode:system', () => {
- nativeTheme.themeSource = 'system'
- })
-}
+ipcMain.handle('dark-mode:system', () => {
+ nativeTheme.themeSource = 'system'
+})
app.whenReady().then(() => {
createWindow()
diff --git a/docs/fiddles/features/macos-dark-mode/preload.js b/docs/fiddles/features/dark-mode/preload.js
similarity index 100%
rename from docs/fiddles/features/macos-dark-mode/preload.js
rename to docs/fiddles/features/dark-mode/preload.js
diff --git a/docs/fiddles/features/macos-dark-mode/renderer.js b/docs/fiddles/features/dark-mode/renderer.js
similarity index 100%
rename from docs/fiddles/features/macos-dark-mode/renderer.js
rename to docs/fiddles/features/dark-mode/renderer.js
diff --git a/docs/fiddles/features/macos-dark-mode/styles.css b/docs/fiddles/features/dark-mode/styles.css
similarity index 81%
rename from docs/fiddles/features/macos-dark-mode/styles.css
rename to docs/fiddles/features/dark-mode/styles.css
index eb6dd2f243..8f9ad8f04d 100644
--- a/docs/fiddles/features/macos-dark-mode/styles.css
+++ b/docs/fiddles/features/dark-mode/styles.css
@@ -1,3 +1,7 @@
+:root {
+ color-scheme: light dark;
+}
+
@media (prefers-color-scheme: dark) {
body { background: #333; color: white; }
}
diff --git a/docs/tutorial/dark-mode.md b/docs/tutorial/dark-mode.md
index 27fbff07d1..41e9fd3112 100644
--- a/docs/tutorial/dark-mode.md
+++ b/docs/tutorial/dark-mode.md
@@ -50,7 +50,7 @@ of this theming, due to the use of the macOS 10.14 SDK.
This example demonstrates an Electron application that derives its theme colors from the
`nativeTheme`. Additionally, it provides theme toggle and reset controls using IPC channels.
-```javascript fiddle='docs/fiddles/features/macos-dark-mode'
+```javascript fiddle='docs/fiddles/features/dark-mode'
```
|
docs
|
dfe501941cd9e7092829c3ef8e27e322047cf736
|
Shelley Vohr
|
2023-01-10 12:46:30
|
build: update release deps workflow (#36530)
|
diff --git a/.github/workflows/release_dependency_versions.yml b/.github/workflows/release_dependency_versions.yml
index 32806dcc68..62c48fc797 100644
--- a/.github/workflows/release_dependency_versions.yml
+++ b/.github/workflows/release_dependency_versions.yml
@@ -11,24 +11,22 @@ permissions: # added using https://github.com/step-security/secure-workflows
contents: read
jobs:
- check_tag:
+ trigger_chromedriver:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@93ea575cb5d8a053eaa0ac8fa3b40d7e05a33cc8 # tag: v3
- - name: Check Tag
+ - name: Trigger New chromedriver Release
run: |
if [[ ${{ github.event.release.tag_name }} =~ ^v[0-9]+\.0\.0$ ]]; then
- echo ::set-output name=should_release::true
+ gh api /repos/:owner/chromedriver/actions/workflows/release.yml/dispatches --input - <<< '{"ref":"main","inputs":{"version":"${{ github.event.release.tag_name }}"}}'
+ else
+ echo "Not releasing for version ${{ github.event.release.tag_name }}: requires major version change"
fi
- trigger:
+
+ trigger_mksnapshot:
runs-on: ubuntu-latest
- needs: check_tag
- if: needs.check_tag.outputs.should_release == 'true'
steps:
- uses: actions/checkout@93ea575cb5d8a053eaa0ac8fa3b40d7e05a33cc8 # tag: v3
- - name: Trigger New chromedriver Release
- run: |
- gh api /repos/:owner/chromedriver/actions/workflows/release.yml/dispatches --input - <<< '{"ref":"main","inputs":{"version":"${{ github.event.release.tag_name }}"}}'
- name: Trigger New mksnapshot Release
run: |
gh api /repos/:owner/mksnapshot/actions/workflows/release.yml/dispatches --input - <<< '{"ref":"main","inputs":{"version":"${{ github.event.release.tag_name }}"}}'
|
build
|
629c54ba36fcca787cd3ac69924a2527ba131bfc
|
John Kleinschmidt
|
2022-11-22 16:50:32
|
feat: add support for WebUSB (#36289)
* feat: add support for WebUSB
* fixup for gn check
* fixup gn check on Windows
* Apply review feedback
Co-authored-by: Charles Kerr <[email protected]>
* chore: address review feedback
* chore: removed unneeded code
* Migrate non-default ScopedObservation<> instantiations to ScopedObservationTraits<> in chrome/browser/
https://chromium-review.googlesource.com/c/chromium/src/+/4016595
Co-authored-by: Charles Kerr <[email protected]>
|
diff --git a/docs/api/session.md b/docs/api/session.md
index 764243c7b1..bc86c21713 100644
--- a/docs/api/session.md
+++ b/docs/api/session.md
@@ -239,7 +239,7 @@ app.whenReady().then(() => {
const selectedDevice = details.deviceList.find((device) => {
return device.vendorId === '9025' && device.productId === '67'
})
- callback(selectedPort?.deviceId)
+ callback(selectedDevice?.deviceId)
})
})
```
@@ -429,6 +429,118 @@ const portConnect = async () => {
}
```
+#### Event: 'select-usb-device'
+
+Returns:
+
+* `event` Event
+* `details` Object
+ * `deviceList` [USBDevice[]](structures/usb-device.md)
+ * `frame` [WebFrameMain](web-frame-main.md)
+* `callback` Function
+ * `deviceId` string (optional)
+
+Emitted when a USB device needs to be selected when a call to
+`navigator.usb.requestDevice` is made. `callback` should be called with
+`deviceId` to be selected; passing no arguments to `callback` will
+cancel the request. Additionally, permissioning on `navigator.usb` can
+be further managed by using [ses.setPermissionCheckHandler(handler)](#sessetpermissioncheckhandlerhandler)
+and [ses.setDevicePermissionHandler(handler)`](#sessetdevicepermissionhandlerhandler).
+
+```javascript
+const { app, BrowserWindow } = require('electron')
+
+let win = null
+
+app.whenReady().then(() => {
+ win = new BrowserWindow()
+
+ win.webContents.session.setPermissionCheckHandler((webContents, permission, requestingOrigin, details) => {
+ if (permission === 'usb') {
+ // Add logic here to determine if permission should be given to allow USB selection
+ return true
+ }
+ return false
+ })
+
+ // Optionally, retrieve previously persisted devices from a persistent store (fetchGrantedDevices needs to be implemented by developer to fetch persisted permissions)
+ const grantedDevices = fetchGrantedDevices()
+
+ win.webContents.session.setDevicePermissionHandler((details) => {
+ if (new URL(details.origin).hostname === 'some-host' && details.deviceType === 'usb') {
+ if (details.device.vendorId === 123 && details.device.productId === 345) {
+ // Always allow this type of device (this allows skipping the call to `navigator.usb.requestDevice` first)
+ return true
+ }
+
+ // Search through the list of devices that have previously been granted permission
+ return grantedDevices.some((grantedDevice) => {
+ return grantedDevice.vendorId === details.device.vendorId &&
+ grantedDevice.productId === details.device.productId &&
+ grantedDevice.serialNumber && grantedDevice.serialNumber === details.device.serialNumber
+ })
+ }
+ return false
+ })
+
+ win.webContents.session.on('select-usb-device', (event, details, callback) => {
+ event.preventDefault()
+ const selectedDevice = details.deviceList.find((device) => {
+ return device.vendorId === '9025' && device.productId === '67'
+ })
+ if (selectedDevice) {
+ // Optionally, add this to the persisted devices (updateGrantedDevices needs to be implemented by developer to persist permissions)
+ grantedDevices.push(selectedDevice)
+ updateGrantedDevices(grantedDevices)
+ }
+ callback(selectedDevice?.deviceId)
+ })
+})
+```
+
+#### Event: 'usb-device-added'
+
+Returns:
+
+* `event` Event
+* `details` Object
+ * `device` [USBDevice](structures/usb-device.md)
+ * `frame` [WebFrameMain](web-frame-main.md)
+
+Emitted after `navigator.usb.requestDevice` has been called and
+`select-usb-device` has fired if a new device becomes available before
+the callback from `select-usb-device` is called. This event is intended for
+use when using a UI to ask users to pick a device so that the UI can be updated
+with the newly added device.
+
+#### Event: 'usb-device-removed'
+
+Returns:
+
+* `event` Event
+* `details` Object
+ * `device` [USBDevice](structures/usb-device.md)
+ * `frame` [WebFrameMain](web-frame-main.md)
+
+Emitted after `navigator.usb.requestDevice` has been called and
+`select-usb-device` has fired if a device has been removed before the callback
+from `select-usb-device` is called. This event is intended for use when using
+a UI to ask users to pick a device so that the UI can be updated to remove the
+specified device.
+
+#### Event: 'usb-device-revoked'
+
+Returns:
+
+* `event` Event
+* `details` Object
+ * `device` [USBDevice[]](structures/usb-device.md)
+ * `origin` string (optional) - The origin that the device has been revoked from.
+
+Emitted after `USBDevice.forget()` has been called. This event can be used
+to help maintain persistent storage of permissions when
+`setDevicePermissionHandler` is used.
+
### Instance Methods
The following methods are available on instances of `Session`:
@@ -714,7 +826,7 @@ session.fromPartition('some-partition').setPermissionRequestHandler((webContents
* `handler` Function\<boolean> | null
* `webContents` ([WebContents](web-contents.md) | null) - WebContents checking the permission. Please note that if the request comes from a subframe you should use `requestingUrl` to check the request origin. All cross origin sub frames making permission checks will pass a `null` webContents to this handler, while certain other permission checks such as `notifications` checks will always pass `null`. You should use `embeddingOrigin` and `requestingOrigin` to determine what origin the owning frame and the requesting frame are on respectively.
- * `permission` string - Type of permission check. Valid values are `midiSysex`, `notifications`, `geolocation`, `media`,`mediaKeySystem`,`midi`, `pointerLock`, `fullscreen`, `openExternal`, `hid`, or `serial`.
+ * `permission` string - Type of permission check. Valid values are `midiSysex`, `notifications`, `geolocation`, `media`,`mediaKeySystem`,`midi`, `pointerLock`, `fullscreen`, `openExternal`, `hid`, `serial`, or `usb`.
* `requestingOrigin` string - The origin URL of the permission check
* `details` Object - Some properties are only available on certain permission types.
* `embeddingOrigin` string (optional) - The origin of the frame embedding the frame that made the permission check. Only set for cross-origin sub frames making permission checks.
@@ -800,7 +912,7 @@ Passing `null` instead of a function resets the handler to its default state.
* `handler` Function\<boolean> | null
* `details` Object
- * `deviceType` string - The type of device that permission is being requested on, can be `hid` or `serial`.
+ * `deviceType` string - The type of device that permission is being requested on, can be `hid`, `serial`, or `usb`.
* `origin` string - The origin URL of the device permission check.
* `device` [HIDDevice](structures/hid-device.md) | [SerialPort](structures/serial-port.md)- the device that permission is being requested for.
@@ -828,6 +940,8 @@ app.whenReady().then(() => {
return true
} else if (permission === 'serial') {
// Add logic here to determine if permission should be given to allow serial port selection
+ } else if (permission === 'usb') {
+ // Add logic here to determine if permission should be given to allow USB device selection
}
return false
})
diff --git a/docs/api/structures/usb-device.md b/docs/api/structures/usb-device.md
new file mode 100644
index 0000000000..e1f427fb4e
--- /dev/null
+++ b/docs/api/structures/usb-device.md
@@ -0,0 +1,17 @@
+# USBDevice Object
+
+* `deviceId` string - Unique identifier for the device.
+* `vendorId` Integer - The USB vendor ID.
+* `productId` Integer - The USB product ID.
+* `productName` string (optional) - Name of the device.
+* `serialNumber` string (optional) - The USB device serial number.
+* `manufacturerName` string (optional) - The manufacturer name of the device.
+* `usbVersionMajor` Integer - The USB protocol major version supported by the device
+* `usbVersionMinor` Integer - The USB protocol minor version supported by the device
+* `usbVersionSubminor` Integer - The USB protocol subminor version supported by the device
+* `deviceClass` Integer - The device class for the communication interface supported by the device
+* `deviceSubclass` Integer - The device subclass for the communication interface supported by the device
+* `deviceProtocol` Integer - The device protocol for the communication interface supported by the device
+* `deviceVersionMajor` Integer - The major version number of the device as defined by the device manufacturer.
+* `deviceVersionMinor` Integer - The minor version number of the device as defined by the device manufacturer.
+* `deviceVersionSubminor` Integer - The subminor version number of the device as defined by the device manufacturer.
diff --git a/docs/fiddles/features/web-usb/index.html b/docs/fiddles/features/web-usb/index.html
new file mode 100644
index 0000000000..95541d9a1f
--- /dev/null
+++ b/docs/fiddles/features/web-usb/index.html
@@ -0,0 +1,21 @@
+<!DOCTYPE html>
+<html>
+ <head>
+ <meta charset="UTF-8">
+ <meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'">
+ <title>WebUSB API</title>
+ </head>
+ <body>
+ <h1>WebUSB API</h1>
+
+ <button id="clickme">Test WebUSB</button>
+
+ <h3>USB devices automatically granted access via <i>setDevicePermissionHandler</i></h3>
+ <div id="granted-devices"></div>
+
+ <h3>USB devices automatically granted access via <i>select-usb-device</i></h3>
+ <div id="granted-devices2"></div>
+
+ <script src="./renderer.js"></script>
+ </body>
+</html>
diff --git a/docs/fiddles/features/web-usb/main.js b/docs/fiddles/features/web-usb/main.js
new file mode 100644
index 0000000000..316a0dbdf8
--- /dev/null
+++ b/docs/fiddles/features/web-usb/main.js
@@ -0,0 +1,72 @@
+const {app, BrowserWindow} = require('electron')
+const e = require('express')
+const path = require('path')
+
+function createWindow () {
+ const mainWindow = new BrowserWindow({
+ width: 800,
+ height: 600
+ })
+
+ let grantedDeviceThroughPermHandler
+
+ mainWindow.webContents.session.on('select-usb-device', (event, details, callback) => {
+ //Add events to handle devices being added or removed before the callback on
+ //`select-usb-device` is called.
+ mainWindow.webContents.session.on('usb-device-added', (event, device) => {
+ console.log('usb-device-added FIRED WITH', device)
+ //Optionally update details.deviceList
+ })
+
+ mainWindow.webContents.session.on('usb-device-removed', (event, device) => {
+ console.log('usb-device-removed FIRED WITH', device)
+ //Optionally update details.deviceList
+ })
+
+ event.preventDefault()
+ if (details.deviceList && details.deviceList.length > 0) {
+ const deviceToReturn = details.deviceList.find((device) => {
+ if (!grantedDeviceThroughPermHandler || (device.deviceId != grantedDeviceThroughPermHandler.deviceId)) {
+ return true
+ }
+ })
+ if (deviceToReturn) {
+ callback(deviceToReturn.deviceId)
+ } else {
+ callback()
+ }
+ }
+ })
+
+ mainWindow.webContents.session.setPermissionCheckHandler((webContents, permission, requestingOrigin, details) => {
+ if (permission === 'usb' && details.securityOrigin === 'file:///') {
+ return true
+ }
+ })
+
+
+ mainWindow.webContents.session.setDevicePermissionHandler((details) => {
+ if (details.deviceType === 'usb' && details.origin === 'file://') {
+ if (!grantedDeviceThroughPermHandler) {
+ grantedDeviceThroughPermHandler = details.device
+ return true
+ } else {
+ return false
+ }
+ }
+ })
+
+ mainWindow.loadFile('index.html')
+}
+
+app.whenReady().then(() => {
+ createWindow()
+
+ app.on('activate', function () {
+ if (BrowserWindow.getAllWindows().length === 0) createWindow()
+ })
+})
+
+app.on('window-all-closed', function () {
+ if (process.platform !== 'darwin') app.quit()
+})
diff --git a/docs/fiddles/features/web-usb/renderer.js b/docs/fiddles/features/web-usb/renderer.js
new file mode 100644
index 0000000000..f1aa3be30b
--- /dev/null
+++ b/docs/fiddles/features/web-usb/renderer.js
@@ -0,0 +1,33 @@
+function getDeviceDetails(device) {
+ return grantedDevice.productName || `Unknown device ${grantedDevice.deviceId}`
+}
+
+async function testIt() {
+ const noDevicesFoundMsg = 'No devices found'
+ const grantedDevices = await navigator.usb.getDevices()
+ let grantedDeviceList = ''
+ if (grantedDevices.length > 0) {
+ grantedDevices.forEach(device => {
+ grantedDeviceList += `<hr>${getDeviceDetails(device)}</hr>`
+ })
+ } else {
+ grantedDeviceList = noDevicesFoundMsg
+ }
+ document.getElementById('granted-devices').innerHTML = grantedDeviceList
+
+ grantedDeviceList = ''
+ try {
+ const grantedDevice = await navigator.usb.requestDevice({
+ filters: []
+ })
+ grantedDeviceList += `<hr>${getDeviceDetails(device)}</hr>`
+
+ } catch (ex) {
+ if (ex.name === 'NotFoundError') {
+ grantedDeviceList = noDevicesFoundMsg
+ }
+ }
+ document.getElementById('granted-devices2').innerHTML = grantedDeviceList
+}
+
+document.getElementById('clickme').addEventListener('click',testIt)
diff --git a/docs/tutorial/devices.md b/docs/tutorial/devices.md
index 6f11fec760..fc988c5224 100644
--- a/docs/tutorial/devices.md
+++ b/docs/tutorial/devices.md
@@ -115,3 +115,41 @@ when the `Test Web Serial` button is clicked.
```javascript fiddle='docs/fiddles/features/web-serial'
```
+
+## WebUSB API
+
+The [WebUSB API](https://web.dev/usb/) can be used to access USB devices.
+Electron provides several APIs for working with the WebUSB API:
+
+* The [`select-usb-device` event on the Session](../api/session.md#event-select-usb-device)
+ can be used to select a USB device when a call to
+ `navigator.usb.requestDevice` is made. Additionally the [`usb-device-added`](../api/session.md#event-usb-device-added)
+ and [`usb-device-removed`](../api/session.md#event-usb-device-removed) events
+ on the Session can be used to handle devices being plugged in or unplugged
+ when handling the `select-usb-device` event.
+ **Note:** These two events only fire until the callback from `select-usb-device`
+ is called. They are not intended to be used as a generic usb device listener.
+* The [`usb-device-revoked' event on the Session](../api/session.md#event-usb-device-revoked) can
+ be used to respond when [device.forget()](https://developer.chrome.com/articles/usb/#revoke-access)
+ is called on a USB device.
+* [`ses.setDevicePermissionHandler(handler)`](../api/session.md#sessetdevicepermissionhandlerhandler)
+ can be used to provide default permissioning to devices without first calling
+ for permission to devices via `navigator.usb.requestDevice`. Additionally,
+ the default behavior of Electron is to store granted device permission through
+ the lifetime of the corresponding WebContents. If longer term storage is
+ needed, a developer can store granted device permissions (eg when handling
+ the `select-usb-device` event) and then read from that storage with
+ `setDevicePermissionHandler`.
+* [`ses.setPermissionCheckHandler(handler)`](../api/session.md#sessetpermissioncheckhandlerhandler)
+ can be used to disable USB access for specific origins.
+
+### Example
+
+This example demonstrates an Electron application that automatically selects
+USB devices (if they are attached) through [`ses.setDevicePermissionHandler(handler)`](../api/session.md#sessetdevicepermissionhandlerhandler)
+and through [`select-usb-device` event on the Session](../api/session.md#event-select-usb-device)
+when the `Test WebUSB` button is clicked.
+
+```javascript fiddle='docs/fiddles/features/web-usb'
+
+```
diff --git a/filenames.auto.gni b/filenames.auto.gni
index f34e4c88cc..274e7270a1 100644
--- a/filenames.auto.gni
+++ b/filenames.auto.gni
@@ -132,6 +132,7 @@ auto_filenames = {
"docs/api/structures/upload-data.md",
"docs/api/structures/upload-file.md",
"docs/api/structures/upload-raw-data.md",
+ "docs/api/structures/usb-device.md",
"docs/api/structures/user-default-types.md",
"docs/api/structures/web-request-filter.md",
"docs/api/structures/web-source.md",
diff --git a/filenames.gni b/filenames.gni
index c87fa8744e..d68a04943b 100644
--- a/filenames.gni
+++ b/filenames.gni
@@ -505,6 +505,14 @@ filenames = {
"shell/browser/ui/tray_icon_observer.h",
"shell/browser/ui/webui/accessibility_ui.cc",
"shell/browser/ui/webui/accessibility_ui.h",
+ "shell/browser/usb/electron_usb_delegate.cc",
+ "shell/browser/usb/electron_usb_delegate.h",
+ "shell/browser/usb/usb_chooser_context.cc",
+ "shell/browser/usb/usb_chooser_context.h",
+ "shell/browser/usb/usb_chooser_context_factory.cc",
+ "shell/browser/usb/usb_chooser_context_factory.h",
+ "shell/browser/usb/usb_chooser_controller.cc",
+ "shell/browser/usb/usb_chooser_controller.h",
"shell/browser/web_contents_permission_helper.cc",
"shell/browser/web_contents_permission_helper.h",
"shell/browser/web_contents_preferences.cc",
@@ -586,6 +594,7 @@ filenames = {
"shell/common/gin_converters/std_converter.h",
"shell/common/gin_converters/time_converter.cc",
"shell/common/gin_converters/time_converter.h",
+ "shell/common/gin_converters/usb_device_info_converter.h",
"shell/common/gin_converters/value_converter.cc",
"shell/common/gin_converters/value_converter.h",
"shell/common/gin_helper/arguments.cc",
diff --git a/shell/browser/electron_browser_client.cc b/shell/browser/electron_browser_client.cc
index 51faa6ae8a..89e3603fd1 100644
--- a/shell/browser/electron_browser_client.cc
+++ b/shell/browser/electron_browser_client.cc
@@ -1715,6 +1715,12 @@ content::BluetoothDelegate* ElectronBrowserClient::GetBluetoothDelegate() {
return bluetooth_delegate_.get();
}
+content::UsbDelegate* ElectronBrowserClient::GetUsbDelegate() {
+ if (!usb_delegate_)
+ usb_delegate_ = std::make_unique<ElectronUsbDelegate>();
+ return usb_delegate_.get();
+}
+
void BindBadgeServiceForServiceWorker(
const content::ServiceWorkerVersionBaseInfo& info,
mojo::PendingReceiver<blink::mojom::BadgeService> receiver) {
diff --git a/shell/browser/electron_browser_client.h b/shell/browser/electron_browser_client.h
index 840ff7b31e..a410ef9781 100644
--- a/shell/browser/electron_browser_client.h
+++ b/shell/browser/electron_browser_client.h
@@ -22,6 +22,7 @@
#include "shell/browser/bluetooth/electron_bluetooth_delegate.h"
#include "shell/browser/hid/electron_hid_delegate.h"
#include "shell/browser/serial/electron_serial_delegate.h"
+#include "shell/browser/usb/electron_usb_delegate.h"
#include "third_party/blink/public/mojom/badging/badging.mojom-forward.h"
namespace content {
@@ -103,6 +104,7 @@ class ElectronBrowserClient : public content::ContentBrowserClient,
content::BluetoothDelegate* GetBluetoothDelegate() override;
content::HidDelegate* GetHidDelegate() override;
+ content::UsbDelegate* GetUsbDelegate() override;
content::WebAuthenticationDelegate* GetWebAuthenticationDelegate() override;
@@ -326,6 +328,7 @@ class ElectronBrowserClient : public content::ContentBrowserClient,
std::unique_ptr<ElectronSerialDelegate> serial_delegate_;
std::unique_ptr<ElectronBluetoothDelegate> bluetooth_delegate_;
+ std::unique_ptr<ElectronUsbDelegate> usb_delegate_;
std::unique_ptr<ElectronHidDelegate> hid_delegate_;
std::unique_ptr<ElectronWebAuthenticationDelegate>
web_authentication_delegate_;
diff --git a/shell/browser/electron_browser_context.cc b/shell/browser/electron_browser_context.cc
index 14e4e15149..3e1706747c 100644
--- a/shell/browser/electron_browser_context.cc
+++ b/shell/browser/electron_browser_context.cc
@@ -51,6 +51,7 @@
#include "shell/browser/web_view_manager.h"
#include "shell/browser/zoom_level_delegate.h"
#include "shell/common/application_info.h"
+#include "shell/common/electron_constants.h"
#include "shell/common/electron_paths.h"
#include "shell/common/gin_converters/frame_converter.h"
#include "shell/common/gin_helper/error_thrower.h"
@@ -583,19 +584,22 @@ bool ElectronBrowserContext::DoesDeviceMatch(
const base::Value* device_to_compare,
blink::PermissionType permission_type) {
if (permission_type ==
- static_cast<blink::PermissionType>(
- WebContentsPermissionHelper::PermissionType::HID)) {
- if (device.GetDict().FindInt(kHidVendorIdKey) !=
- device_to_compare->GetDict().FindInt(kHidVendorIdKey) ||
- device.GetDict().FindInt(kHidProductIdKey) !=
- device_to_compare->GetDict().FindInt(kHidProductIdKey)) {
+ static_cast<blink::PermissionType>(
+ WebContentsPermissionHelper::PermissionType::HID) ||
+ permission_type ==
+ static_cast<blink::PermissionType>(
+ WebContentsPermissionHelper::PermissionType::USB)) {
+ if (device.GetDict().FindInt(kDeviceVendorIdKey) !=
+ device_to_compare->GetDict().FindInt(kDeviceVendorIdKey) ||
+ device.GetDict().FindInt(kDeviceProductIdKey) !=
+ device_to_compare->GetDict().FindInt(kDeviceProductIdKey)) {
return false;
}
const auto* serial_number =
- device_to_compare->GetDict().FindString(kHidSerialNumberKey);
+ device_to_compare->GetDict().FindString(kDeviceSerialNumberKey);
const auto* device_serial_number =
- device.GetDict().FindString(kHidSerialNumberKey);
+ device.GetDict().FindString(kDeviceSerialNumberKey);
if (serial_number && device_serial_number &&
*device_serial_number == *serial_number)
diff --git a/shell/browser/feature_list.cc b/shell/browser/feature_list.cc
index 47c057fdae..0cf9374876 100644
--- a/shell/browser/feature_list.cc
+++ b/shell/browser/feature_list.cc
@@ -17,6 +17,10 @@
#include "net/base/features.h"
#include "services/network/public/cpp/features.h"
+#if BUILDFLAG(IS_MAC)
+#include "device/base/features.h" // nogncheck
+#endif
+
namespace electron {
void InitializeFeatureList() {
@@ -32,6 +36,11 @@ void InitializeFeatureList() {
disable_features +=
std::string(",") + features::kSpareRendererForSitePerProcess.name;
+#if BUILDFLAG(IS_MAC)
+ // Needed for WebUSB implementation
+ enable_features += std::string(",") + device::kNewUsbBackend.name;
+#endif
+
#if !BUILDFLAG(ENABLE_PICTURE_IN_PICTURE)
disable_features += std::string(",") + media::kPictureInPicture.name;
#endif
diff --git a/shell/browser/hid/hid_chooser_context.cc b/shell/browser/hid/hid_chooser_context.cc
index 108ecb28f4..4445a2b7b1 100644
--- a/shell/browser/hid/hid_chooser_context.cc
+++ b/shell/browser/hid/hid_chooser_context.cc
@@ -22,6 +22,7 @@
#include "shell/browser/api/electron_api_session.h"
#include "shell/browser/electron_permission_manager.h"
#include "shell/browser/web_contents_permission_helper.h"
+#include "shell/common/electron_constants.h"
#include "shell/common/gin_converters/content_converter.h"
#include "shell/common/gin_converters/frame_converter.h"
#include "shell/common/gin_converters/hid_device_info_converter.h"
@@ -35,9 +36,6 @@ namespace electron {
const char kHidDeviceNameKey[] = "name";
const char kHidGuidKey[] = "guid";
-const char kHidVendorIdKey[] = "vendorId";
-const char kHidProductIdKey[] = "productId";
-const char kHidSerialNumberKey[] = "serialNumber";
HidChooserContext::HidChooserContext(ElectronBrowserContext* context)
: browser_context_(context) {}
@@ -76,12 +74,12 @@ base::Value HidChooserContext::DeviceInfoToValue(
value.SetStringKey(
kHidDeviceNameKey,
base::UTF16ToUTF8(HidChooserContext::DisplayNameFromDeviceInfo(device)));
- value.SetIntKey(kHidVendorIdKey, device.vendor_id);
- value.SetIntKey(kHidProductIdKey, device.product_id);
+ value.SetIntKey(kDeviceVendorIdKey, device.vendor_id);
+ value.SetIntKey(kDeviceProductIdKey, device.product_id);
if (HidChooserContext::CanStorePersistentEntry(device)) {
// Use the USB serial number as a persistent identifier. If it is
// unavailable, only ephemeral permissions may be granted.
- value.SetStringKey(kHidSerialNumberKey, device.serial_number);
+ value.SetStringKey(kDeviceSerialNumberKey, device.serial_number);
} else {
// The GUID is a temporary ID created on connection that remains valid until
// the device is disconnected. Ephemeral permissions are keyed by this ID
diff --git a/shell/browser/hid/hid_chooser_context.h b/shell/browser/hid/hid_chooser_context.h
index e748eeb396..6c174427f4 100644
--- a/shell/browser/hid/hid_chooser_context.h
+++ b/shell/browser/hid/hid_chooser_context.h
@@ -33,9 +33,7 @@ namespace electron {
extern const char kHidDeviceNameKey[];
extern const char kHidGuidKey[];
-extern const char kHidVendorIdKey[];
extern const char kHidProductIdKey[];
-extern const char kHidSerialNumberKey[];
// Manages the internal state and connection to the device service for the
// Human Interface Device (HID) chooser UI.
diff --git a/shell/browser/serial/serial_chooser_context.h b/shell/browser/serial/serial_chooser_context.h
index 1c3e2d7641..f64597b667 100644
--- a/shell/browser/serial/serial_chooser_context.h
+++ b/shell/browser/serial/serial_chooser_context.h
@@ -29,9 +29,6 @@ class Value;
namespace electron {
-extern const char kHidVendorIdKey[];
-extern const char kHidProductIdKey[];
-
#if BUILDFLAG(IS_WIN)
extern const char kDeviceInstanceIdKey[];
#else
diff --git a/shell/browser/usb/electron_usb_delegate.cc b/shell/browser/usb/electron_usb_delegate.cc
new file mode 100644
index 0000000000..a5bb4bc0e3
--- /dev/null
+++ b/shell/browser/usb/electron_usb_delegate.cc
@@ -0,0 +1,317 @@
+// Copyright (c) 2022 Microsoft, Inc.
+// Use of this source code is governed by the MIT license that can be
+// found in the LICENSE file.
+
+#include "shell/browser/usb/electron_usb_delegate.h"
+
+#include <utility>
+
+#include "base/containers/contains.h"
+#include "base/containers/cxx20_erase.h"
+#include "base/observer_list.h"
+#include "base/observer_list_types.h"
+#include "base/scoped_observation.h"
+#include "content/public/browser/render_frame_host.h"
+#include "content/public/browser/web_contents.h"
+#include "extensions/buildflags/buildflags.h"
+#include "services/device/public/mojom/usb_enumeration_options.mojom.h"
+#include "shell/browser/electron_permission_manager.h"
+#include "shell/browser/usb/usb_chooser_context.h"
+#include "shell/browser/usb/usb_chooser_context_factory.h"
+#include "shell/browser/usb/usb_chooser_controller.h"
+#include "shell/browser/web_contents_permission_helper.h"
+
+#if BUILDFLAG(ENABLE_EXTENSIONS)
+#include "base/containers/fixed_flat_set.h"
+#include "chrome/common/chrome_features.h"
+#include "extensions/browser/extension_registry.h"
+#include "extensions/common/constants.h"
+#include "extensions/common/extension.h"
+#include "services/device/public/mojom/usb_device.mojom.h"
+#endif
+
+namespace {
+
+using ::content::UsbChooser;
+
+electron::UsbChooserContext* GetChooserContext(
+ content::BrowserContext* browser_context) {
+ return electron::UsbChooserContextFactory::GetForBrowserContext(
+ browser_context);
+}
+
+#if BUILDFLAG(ENABLE_EXTENSIONS)
+// These extensions can claim the smart card USB class and automatically gain
+// permissions for devices that have an interface with this class.
+constexpr auto kSmartCardPrivilegedExtensionIds =
+ base::MakeFixedFlatSet<base::StringPiece>({
+ // Smart Card Connector Extension and its Beta version, see
+ // crbug.com/1233881.
+ "khpfeaanjngmcnplbdlpegiifgpfgdco",
+ "mockcojkppdndnhgonljagclgpkjbkek",
+ });
+
+bool DeviceHasInterfaceWithClass(
+ const device::mojom::UsbDeviceInfo& device_info,
+ uint8_t interface_class) {
+ for (const auto& configuration : device_info.configurations) {
+ for (const auto& interface : configuration->interfaces) {
+ for (const auto& alternate : interface->alternates) {
+ if (alternate->class_code == interface_class)
+ return true;
+ }
+ }
+ }
+ return false;
+}
+#endif // BUILDFLAG(ENABLE_EXTENSIONS)
+
+bool IsDevicePermissionAutoGranted(
+ const url::Origin& origin,
+ const device::mojom::UsbDeviceInfo& device_info) {
+#if BUILDFLAG(ENABLE_EXTENSIONS)
+ // Note: The `DeviceHasInterfaceWithClass()` call is made after checking the
+ // origin, since that method call is expensive.
+ if (origin.scheme() == extensions::kExtensionScheme &&
+ base::Contains(kSmartCardPrivilegedExtensionIds, origin.host()) &&
+ DeviceHasInterfaceWithClass(device_info,
+ device::mojom::kUsbSmartCardClass)) {
+ return true;
+ }
+#endif // BUILDFLAG(ENABLE_EXTENSIONS)
+
+ return false;
+}
+
+} // namespace
+
+namespace electron {
+
+// Manages the UsbDelegate observers for a single browser context.
+class ElectronUsbDelegate::ContextObservation
+ : public UsbChooserContext::DeviceObserver {
+ public:
+ ContextObservation(ElectronUsbDelegate* parent,
+ content::BrowserContext* browser_context)
+ : parent_(parent), browser_context_(browser_context) {
+ auto* chooser_context = GetChooserContext(browser_context_);
+ device_observation_.Observe(chooser_context);
+ }
+ ContextObservation(ContextObservation&) = delete;
+ ContextObservation& operator=(ContextObservation&) = delete;
+ ~ContextObservation() override = default;
+
+ // UsbChooserContext::DeviceObserver:
+ void OnDeviceAdded(const device::mojom::UsbDeviceInfo& device_info) override {
+ for (auto& observer : observer_list_)
+ observer.OnDeviceAdded(device_info);
+ }
+
+ void OnDeviceRemoved(
+ const device::mojom::UsbDeviceInfo& device_info) override {
+ for (auto& observer : observer_list_)
+ observer.OnDeviceRemoved(device_info);
+ }
+
+ void OnDeviceManagerConnectionError() override {
+ for (auto& observer : observer_list_)
+ observer.OnDeviceManagerConnectionError();
+ }
+
+ void OnBrowserContextShutdown() override {
+ parent_->observations_.erase(browser_context_);
+ // Return since `this` is now deleted.
+ }
+
+ void AddObserver(content::UsbDelegate::Observer* observer) {
+ observer_list_.AddObserver(observer);
+ }
+
+ void RemoveObserver(content::UsbDelegate::Observer* observer) {
+ observer_list_.RemoveObserver(observer);
+ }
+
+ private:
+ // Safe because `parent_` owns `this`.
+ const raw_ptr<ElectronUsbDelegate> parent_;
+
+ // Safe because `this` is destroyed when the context is lost.
+ const raw_ptr<content::BrowserContext> browser_context_;
+
+ base::ScopedObservation<UsbChooserContext, UsbChooserContext::DeviceObserver>
+ device_observation_{this};
+ base::ObserverList<content::UsbDelegate::Observer> observer_list_;
+};
+
+ElectronUsbDelegate::ElectronUsbDelegate() = default;
+
+ElectronUsbDelegate::~ElectronUsbDelegate() = default;
+
+void ElectronUsbDelegate::AdjustProtectedInterfaceClasses(
+ content::BrowserContext* browser_context,
+ const url::Origin& origin,
+ content::RenderFrameHost* frame,
+ std::vector<uint8_t>& classes) {
+ // Isolated Apps have unrestricted access to any USB interface class.
+ if (frame && frame->GetWebExposedIsolationLevel() >=
+ content::RenderFrameHost::WebExposedIsolationLevel::
+ kMaybeIsolatedApplication) {
+ // TODO(https://crbug.com/1236706): Should the list of interface classes the
+ // app expects to claim be encoded in the Web App Manifest?
+ classes.clear();
+ return;
+ }
+
+#if BUILDFLAG(ENABLE_EXTENSIONS)
+ // Don't enforce protected interface classes for Chrome Apps since the
+ // chrome.usb API has no such restriction.
+ if (origin.scheme() == extensions::kExtensionScheme) {
+ auto* extension_registry =
+ extensions::ExtensionRegistry::Get(browser_context);
+ if (extension_registry) {
+ const extensions::Extension* extension =
+ extension_registry->enabled_extensions().GetByID(origin.host());
+ if (extension && extension->is_platform_app()) {
+ classes.clear();
+ return;
+ }
+ }
+ }
+
+ if (origin.scheme() == extensions::kExtensionScheme &&
+ base::Contains(kSmartCardPrivilegedExtensionIds, origin.host())) {
+ base::Erase(classes, device::mojom::kUsbSmartCardClass);
+ }
+#endif // BUILDFLAG(ENABLE_EXTENSIONS)
+}
+
+std::unique_ptr<UsbChooser> ElectronUsbDelegate::RunChooser(
+ content::RenderFrameHost& frame,
+ std::vector<device::mojom::UsbDeviceFilterPtr> filters,
+ blink::mojom::WebUsbService::GetPermissionCallback callback) {
+ UsbChooserController* controller = ControllerForFrame(&frame);
+ if (controller) {
+ DeleteControllerForFrame(&frame);
+ }
+ AddControllerForFrame(&frame, std::move(filters), std::move(callback));
+ // Return a nullptr because the return value isn't used for anything. The
+ // return value is simply used in Chromium to cleanup the chooser UI once the
+ // usb service is destroyed.
+ return nullptr;
+}
+
+bool ElectronUsbDelegate::CanRequestDevicePermission(
+ content::BrowserContext* browser_context,
+ const url::Origin& origin) {
+ base::Value::Dict details;
+ details.Set("securityOrigin", origin.GetURL().spec());
+ auto* permission_manager = static_cast<ElectronPermissionManager*>(
+ browser_context->GetPermissionControllerDelegate());
+ return permission_manager->CheckPermissionWithDetails(
+ static_cast<blink::PermissionType>(
+ WebContentsPermissionHelper::PermissionType::USB),
+ nullptr, origin.GetURL(), std::move(details));
+}
+
+void ElectronUsbDelegate::RevokeDevicePermissionWebInitiated(
+ content::BrowserContext* browser_context,
+ const url::Origin& origin,
+ const device::mojom::UsbDeviceInfo& device) {
+ GetChooserContext(browser_context)
+ ->RevokeDevicePermissionWebInitiated(origin, device);
+}
+
+const device::mojom::UsbDeviceInfo* ElectronUsbDelegate::GetDeviceInfo(
+ content::BrowserContext* browser_context,
+ const std::string& guid) {
+ return GetChooserContext(browser_context)->GetDeviceInfo(guid);
+}
+
+bool ElectronUsbDelegate::HasDevicePermission(
+ content::BrowserContext* browser_context,
+ const url::Origin& origin,
+ const device::mojom::UsbDeviceInfo& device) {
+ if (IsDevicePermissionAutoGranted(origin, device))
+ return true;
+
+ return GetChooserContext(browser_context)
+ ->HasDevicePermission(origin, device);
+}
+
+void ElectronUsbDelegate::GetDevices(
+ content::BrowserContext* browser_context,
+ blink::mojom::WebUsbService::GetDevicesCallback callback) {
+ GetChooserContext(browser_context)->GetDevices(std::move(callback));
+}
+
+void ElectronUsbDelegate::GetDevice(
+ content::BrowserContext* browser_context,
+ const std::string& guid,
+ base::span<const uint8_t> blocked_interface_classes,
+ mojo::PendingReceiver<device::mojom::UsbDevice> device_receiver,
+ mojo::PendingRemote<device::mojom::UsbDeviceClient> device_client) {
+ GetChooserContext(browser_context)
+ ->GetDevice(guid, blocked_interface_classes, std::move(device_receiver),
+ std::move(device_client));
+}
+
+void ElectronUsbDelegate::AddObserver(content::BrowserContext* browser_context,
+ Observer* observer) {
+ GetContextObserver(browser_context)->AddObserver(observer);
+}
+
+void ElectronUsbDelegate::RemoveObserver(
+ content::BrowserContext* browser_context,
+ Observer* observer) {
+ GetContextObserver(browser_context)->RemoveObserver(observer);
+}
+
+ElectronUsbDelegate::ContextObservation*
+ElectronUsbDelegate::GetContextObserver(
+ content::BrowserContext* browser_context) {
+ if (!base::Contains(observations_, browser_context)) {
+ observations_.emplace(browser_context, std::make_unique<ContextObservation>(
+ this, browser_context));
+ }
+ return observations_[browser_context].get();
+}
+
+bool ElectronUsbDelegate::IsServiceWorkerAllowedForOrigin(
+ const url::Origin& origin) {
+#if BUILDFLAG(ENABLE_EXTENSIONS)
+ // WebUSB is only available on extension service workers for now.
+ if (base::FeatureList::IsEnabled(
+ features::kEnableWebUsbOnExtensionServiceWorker) &&
+ origin.scheme() == extensions::kExtensionScheme) {
+ return true;
+ }
+#endif // BUILDFLAG(ENABLE_EXTENSIONS)
+ return false;
+}
+
+UsbChooserController* ElectronUsbDelegate::ControllerForFrame(
+ content::RenderFrameHost* render_frame_host) {
+ auto mapping = controller_map_.find(render_frame_host);
+ return mapping == controller_map_.end() ? nullptr : mapping->second.get();
+}
+
+UsbChooserController* ElectronUsbDelegate::AddControllerForFrame(
+ content::RenderFrameHost* render_frame_host,
+ std::vector<device::mojom::UsbDeviceFilterPtr> filters,
+ blink::mojom::WebUsbService::GetPermissionCallback callback) {
+ auto* web_contents =
+ content::WebContents::FromRenderFrameHost(render_frame_host);
+ auto controller = std::make_unique<UsbChooserController>(
+ render_frame_host, std::move(filters), std::move(callback), web_contents,
+ weak_factory_.GetWeakPtr());
+ controller_map_.insert(
+ std::make_pair(render_frame_host, std::move(controller)));
+ return ControllerForFrame(render_frame_host);
+}
+
+void ElectronUsbDelegate::DeleteControllerForFrame(
+ content::RenderFrameHost* render_frame_host) {
+ controller_map_.erase(render_frame_host);
+}
+
+} // namespace electron
diff --git a/shell/browser/usb/electron_usb_delegate.h b/shell/browser/usb/electron_usb_delegate.h
new file mode 100644
index 0000000000..943921bfb7
--- /dev/null
+++ b/shell/browser/usb/electron_usb_delegate.h
@@ -0,0 +1,106 @@
+// Copyright (c) 2022 Microsoft, Inc.
+// Use of this source code is governed by the MIT license that can be
+// found in the LICENSE file.
+
+#ifndef ELECTRON_SHELL_BROWSER_USB_ELECTRON_USB_DELEGATE_H_
+#define ELECTRON_SHELL_BROWSER_USB_ELECTRON_USB_DELEGATE_H_
+
+#include <memory>
+#include <string>
+#include <unordered_map>
+#include <vector>
+
+#include "base/containers/span.h"
+#include "base/memory/weak_ptr.h"
+#include "content/public/browser/usb_chooser.h"
+#include "content/public/browser/usb_delegate.h"
+#include "mojo/public/cpp/bindings/pending_receiver.h"
+#include "mojo/public/cpp/bindings/pending_remote.h"
+#include "services/device/public/mojom/usb_device.mojom-forward.h"
+#include "services/device/public/mojom/usb_enumeration_options.mojom-forward.h"
+#include "services/device/public/mojom/usb_manager.mojom-forward.h"
+#include "third_party/blink/public/mojom/usb/web_usb_service.mojom.h"
+#include "url/origin.h"
+
+namespace content {
+class BrowserContext;
+class RenderFrameHost;
+} // namespace content
+
+namespace electron {
+
+class UsbChooserController;
+
+class ElectronUsbDelegate : public content::UsbDelegate {
+ public:
+ ElectronUsbDelegate();
+ ElectronUsbDelegate(ElectronUsbDelegate&&) = delete;
+ ElectronUsbDelegate& operator=(ElectronUsbDelegate&) = delete;
+ ~ElectronUsbDelegate() override;
+
+ // content::UsbDelegate:
+ void AdjustProtectedInterfaceClasses(content::BrowserContext* browser_context,
+ const url::Origin& origin,
+ content::RenderFrameHost* frame,
+ std::vector<uint8_t>& classes) override;
+ std::unique_ptr<content::UsbChooser> RunChooser(
+ content::RenderFrameHost& frame,
+ std::vector<device::mojom::UsbDeviceFilterPtr> filters,
+ blink::mojom::WebUsbService::GetPermissionCallback callback) override;
+ bool CanRequestDevicePermission(content::BrowserContext* browser_context,
+ const url::Origin& origin) override;
+ void RevokeDevicePermissionWebInitiated(
+ content::BrowserContext* browser_context,
+ const url::Origin& origin,
+ const device::mojom::UsbDeviceInfo& device) override;
+ const device::mojom::UsbDeviceInfo* GetDeviceInfo(
+ content::BrowserContext* browser_context,
+ const std::string& guid) override;
+ bool HasDevicePermission(content::BrowserContext* browser_context,
+ const url::Origin& origin,
+ const device::mojom::UsbDeviceInfo& device) override;
+ void GetDevices(
+ content::BrowserContext* browser_context,
+ blink::mojom::WebUsbService::GetDevicesCallback callback) override;
+ void GetDevice(
+ content::BrowserContext* browser_context,
+ const std::string& guid,
+ base::span<const uint8_t> blocked_interface_classes,
+ mojo::PendingReceiver<device::mojom::UsbDevice> device_receiver,
+ mojo::PendingRemote<device::mojom::UsbDeviceClient> device_client)
+ override;
+ void AddObserver(content::BrowserContext* browser_context,
+ Observer* observer) override;
+ void RemoveObserver(content::BrowserContext* browser_context,
+ Observer* observer) override;
+ bool IsServiceWorkerAllowedForOrigin(const url::Origin& origin) override;
+
+ void DeleteControllerForFrame(content::RenderFrameHost* render_frame_host);
+
+ private:
+ UsbChooserController* ControllerForFrame(
+ content::RenderFrameHost* render_frame_host);
+
+ UsbChooserController* AddControllerForFrame(
+ content::RenderFrameHost* render_frame_host,
+ std::vector<device::mojom::UsbDeviceFilterPtr> filters,
+ blink::mojom::WebUsbService::GetPermissionCallback callback);
+
+ class ContextObservation;
+
+ ContextObservation* GetContextObserver(
+ content::BrowserContext* browser_context);
+
+ base::flat_map<content::BrowserContext*, std::unique_ptr<ContextObservation>>
+ observations_;
+
+ std::unordered_map<content::RenderFrameHost*,
+ std::unique_ptr<UsbChooserController>>
+ controller_map_;
+
+ base::WeakPtrFactory<ElectronUsbDelegate> weak_factory_{this};
+};
+
+} // namespace electron
+
+#endif // ELECTRON_SHELL_BROWSER_USB_ELECTRON_USB_DELEGATE_H_
diff --git a/shell/browser/usb/usb_chooser_context.cc b/shell/browser/usb/usb_chooser_context.cc
new file mode 100644
index 0000000000..79f101d8c0
--- /dev/null
+++ b/shell/browser/usb/usb_chooser_context.cc
@@ -0,0 +1,354 @@
+// Copyright (c) 2022 Microsoft, Inc.
+// Use of this source code is governed by the MIT license that can be
+// found in the LICENSE file.
+
+#include "shell/browser/usb/usb_chooser_context.h"
+
+#include <memory>
+#include <utility>
+#include <vector>
+
+#include "base/bind.h"
+#include "base/containers/contains.h"
+#include "base/observer_list.h"
+#include "base/strings/string_number_conversions.h"
+#include "base/strings/string_util.h"
+#include "base/strings/stringprintf.h"
+#include "base/strings/utf_string_conversions.h"
+#include "base/threading/sequenced_task_runner_handle.h"
+#include "base/values.h"
+#include "build/build_config.h"
+#include "components/content_settings/core/common/content_settings.h"
+#include "content/public/browser/device_service.h"
+#include "services/device/public/cpp/usb/usb_ids.h"
+#include "services/device/public/mojom/usb_device.mojom.h"
+#include "shell/browser/api/electron_api_session.h"
+#include "shell/browser/electron_permission_manager.h"
+#include "shell/browser/web_contents_permission_helper.h"
+#include "shell/common/electron_constants.h"
+#include "shell/common/gin_converters/usb_device_info_converter.h"
+#include "shell/common/node_includes.h"
+#include "ui/base/l10n/l10n_util.h"
+
+namespace {
+
+constexpr char kDeviceNameKey[] = "productName";
+constexpr char kDeviceIdKey[] = "deviceId";
+constexpr int kUsbClassMassStorage = 0x08;
+
+bool CanStorePersistentEntry(const device::mojom::UsbDeviceInfo& device_info) {
+ return device_info.serial_number && !device_info.serial_number->empty();
+}
+
+bool IsMassStorageInterface(const device::mojom::UsbInterfaceInfo& interface) {
+ for (auto& alternate : interface.alternates) {
+ if (alternate->class_code == kUsbClassMassStorage)
+ return true;
+ }
+ return false;
+}
+
+bool ShouldExposeDevice(const device::mojom::UsbDeviceInfo& device_info) {
+ // blink::USBDevice::claimInterface() disallows claiming mass storage
+ // interfaces, but explicitly prevent access in the browser process as
+ // ChromeOS would allow these interfaces to be claimed.
+ for (auto& configuration : device_info.configurations) {
+ if (configuration->interfaces.size() == 0) {
+ return true;
+ }
+ for (auto& interface : configuration->interfaces) {
+ if (!IsMassStorageInterface(*interface))
+ return true;
+ }
+ }
+ return false;
+}
+
+} // namespace
+
+namespace electron {
+
+void UsbChooserContext::DeviceObserver::OnDeviceAdded(
+ const device::mojom::UsbDeviceInfo& device_info) {}
+
+void UsbChooserContext::DeviceObserver::OnDeviceRemoved(
+ const device::mojom::UsbDeviceInfo& device_info) {}
+
+void UsbChooserContext::DeviceObserver::OnDeviceManagerConnectionError() {}
+
+UsbChooserContext::UsbChooserContext(ElectronBrowserContext* context)
+ : browser_context_(context) {}
+
+// static
+base::Value UsbChooserContext::DeviceInfoToValue(
+ const device::mojom::UsbDeviceInfo& device_info) {
+ base::Value device_value(base::Value::Type::DICTIONARY);
+ device_value.SetStringKey(kDeviceNameKey, device_info.product_name
+ ? *device_info.product_name
+ : base::StringPiece16());
+ device_value.SetIntKey(kDeviceVendorIdKey, device_info.vendor_id);
+ device_value.SetIntKey(kDeviceProductIdKey, device_info.product_id);
+
+ if (device_info.manufacturer_name) {
+ device_value.SetStringKey("manufacturerName",
+ *device_info.manufacturer_name);
+ }
+
+ // CanStorePersistentEntry checks if |device_info.serial_number| is not empty.
+ if (CanStorePersistentEntry(device_info)) {
+ device_value.SetStringKey(kDeviceSerialNumberKey,
+ *device_info.serial_number);
+ }
+
+ device_value.SetStringKey(kDeviceIdKey, device_info.guid);
+
+ device_value.SetIntKey("usbVersionMajor", device_info.usb_version_major);
+ device_value.SetIntKey("usbVersionMinor", device_info.usb_version_minor);
+ device_value.SetIntKey("usbVersionSubminor",
+ device_info.usb_version_subminor);
+ device_value.SetIntKey("deviceClass", device_info.class_code);
+ device_value.SetIntKey("deviceSubclass", device_info.subclass_code);
+ device_value.SetIntKey("deviceProtocol", device_info.protocol_code);
+ device_value.SetIntKey("deviceVersionMajor",
+ device_info.device_version_major);
+ device_value.SetIntKey("deviceVersionMinor",
+ device_info.device_version_minor);
+ device_value.SetIntKey("deviceVersionSubminor",
+ device_info.device_version_subminor);
+ return device_value;
+}
+
+void UsbChooserContext::InitDeviceList(
+ std::vector<device::mojom::UsbDeviceInfoPtr> devices) {
+ for (auto& device_info : devices) {
+ DCHECK(device_info);
+ if (ShouldExposeDevice(*device_info)) {
+ devices_.insert(
+ std::make_pair(device_info->guid, std::move(device_info)));
+ }
+ }
+ is_initialized_ = true;
+
+ while (!pending_get_devices_requests_.empty()) {
+ std::vector<device::mojom::UsbDeviceInfoPtr> device_list;
+ for (const auto& entry : devices_) {
+ device_list.push_back(entry.second->Clone());
+ }
+ std::move(pending_get_devices_requests_.front())
+ .Run(std::move(device_list));
+ pending_get_devices_requests_.pop();
+ }
+}
+
+void UsbChooserContext::EnsureConnectionWithDeviceManager() {
+ if (device_manager_)
+ return;
+
+ // Receive mojo::Remote<UsbDeviceManager> from DeviceService.
+ content::GetDeviceService().BindUsbDeviceManager(
+ device_manager_.BindNewPipeAndPassReceiver());
+
+ SetUpDeviceManagerConnection();
+}
+
+void UsbChooserContext::SetUpDeviceManagerConnection() {
+ DCHECK(device_manager_);
+ device_manager_.set_disconnect_handler(
+ base::BindOnce(&UsbChooserContext::OnDeviceManagerConnectionError,
+ base::Unretained(this)));
+
+ // Listen for added/removed device events.
+ DCHECK(!client_receiver_.is_bound());
+ device_manager_->EnumerateDevicesAndSetClient(
+ client_receiver_.BindNewEndpointAndPassRemote(),
+ base::BindOnce(&UsbChooserContext::InitDeviceList,
+ weak_factory_.GetWeakPtr()));
+}
+
+UsbChooserContext::~UsbChooserContext() {
+ OnDeviceManagerConnectionError();
+ for (auto& observer : device_observer_list_) {
+ observer.OnBrowserContextShutdown();
+ DCHECK(!device_observer_list_.HasObserver(&observer));
+ }
+}
+
+void UsbChooserContext::RevokeDevicePermissionWebInitiated(
+ const url::Origin& origin,
+ const device::mojom::UsbDeviceInfo& device) {
+ DCHECK(base::Contains(devices_, device.guid));
+ RevokeObjectPermissionInternal(origin, DeviceInfoToValue(device),
+ /*revoked_by_website=*/true);
+}
+
+void UsbChooserContext::RevokeObjectPermissionInternal(
+ const url::Origin& origin,
+ const base::Value& object,
+ bool revoked_by_website = false) {
+ if (object.FindStringKey(kDeviceSerialNumberKey)) {
+ auto* permission_manager = static_cast<ElectronPermissionManager*>(
+ browser_context_->GetPermissionControllerDelegate());
+ permission_manager->RevokeDevicePermission(
+ static_cast<blink::PermissionType>(
+ WebContentsPermissionHelper::PermissionType::USB),
+ origin, object, browser_context_);
+ } else {
+ const std::string* guid = object.FindStringKey(kDeviceIdKey);
+ auto it = ephemeral_devices_.find(origin);
+ if (it != ephemeral_devices_.end()) {
+ it->second.erase(*guid);
+ if (it->second.empty())
+ ephemeral_devices_.erase(it);
+ }
+ }
+
+ api::Session* session = api::Session::FromBrowserContext(browser_context_);
+ if (session) {
+ v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
+ v8::HandleScope scope(isolate);
+ gin_helper::Dictionary details =
+ gin_helper::Dictionary::CreateEmpty(isolate);
+ details.Set("device", object.Clone());
+ details.Set("origin", origin.Serialize());
+ session->Emit("usb-device-revoked", details);
+ }
+}
+
+void UsbChooserContext::GrantDevicePermission(
+ const url::Origin& origin,
+ const device::mojom::UsbDeviceInfo& device_info) {
+ if (CanStorePersistentEntry(device_info)) {
+ auto* permission_manager = static_cast<ElectronPermissionManager*>(
+ browser_context_->GetPermissionControllerDelegate());
+ permission_manager->GrantDevicePermission(
+ static_cast<blink::PermissionType>(
+ WebContentsPermissionHelper::PermissionType::USB),
+ origin, DeviceInfoToValue(device_info), browser_context_);
+ } else {
+ ephemeral_devices_[origin].insert(device_info.guid);
+ }
+}
+
+bool UsbChooserContext::HasDevicePermission(
+ const url::Origin& origin,
+ const device::mojom::UsbDeviceInfo& device_info) {
+ auto it = ephemeral_devices_.find(origin);
+ if (it != ephemeral_devices_.end() &&
+ base::Contains(it->second, device_info.guid)) {
+ return true;
+ }
+
+ auto* permission_manager = static_cast<ElectronPermissionManager*>(
+ browser_context_->GetPermissionControllerDelegate());
+
+ return permission_manager->CheckDevicePermission(
+ static_cast<blink::PermissionType>(
+ WebContentsPermissionHelper::PermissionType::USB),
+ origin, DeviceInfoToValue(device_info), browser_context_);
+}
+
+void UsbChooserContext::GetDevices(
+ device::mojom::UsbDeviceManager::GetDevicesCallback callback) {
+ if (!is_initialized_) {
+ EnsureConnectionWithDeviceManager();
+ pending_get_devices_requests_.push(std::move(callback));
+ return;
+ }
+
+ std::vector<device::mojom::UsbDeviceInfoPtr> device_list;
+ for (const auto& pair : devices_) {
+ device_list.push_back(pair.second->Clone());
+ }
+ base::SequencedTaskRunnerHandle::Get()->PostTask(
+ FROM_HERE, base::BindOnce(std::move(callback), std::move(device_list)));
+}
+
+void UsbChooserContext::GetDevice(
+ const std::string& guid,
+ base::span<const uint8_t> blocked_interface_classes,
+ mojo::PendingReceiver<device::mojom::UsbDevice> device_receiver,
+ mojo::PendingRemote<device::mojom::UsbDeviceClient> device_client) {
+ EnsureConnectionWithDeviceManager();
+ device_manager_->GetDevice(
+ guid,
+ std::vector<uint8_t>(blocked_interface_classes.begin(),
+ blocked_interface_classes.end()),
+ std::move(device_receiver), std::move(device_client));
+}
+
+const device::mojom::UsbDeviceInfo* UsbChooserContext::GetDeviceInfo(
+ const std::string& guid) {
+ DCHECK(is_initialized_);
+ auto it = devices_.find(guid);
+ return it == devices_.end() ? nullptr : it->second.get();
+}
+
+void UsbChooserContext::AddObserver(DeviceObserver* observer) {
+ EnsureConnectionWithDeviceManager();
+ device_observer_list_.AddObserver(observer);
+}
+
+void UsbChooserContext::RemoveObserver(DeviceObserver* observer) {
+ device_observer_list_.RemoveObserver(observer);
+}
+
+base::WeakPtr<UsbChooserContext> UsbChooserContext::AsWeakPtr() {
+ return weak_factory_.GetWeakPtr();
+}
+
+void UsbChooserContext::OnDeviceAdded(
+ device::mojom::UsbDeviceInfoPtr device_info) {
+ DCHECK(device_info);
+ // Update the device list.
+ DCHECK(!base::Contains(devices_, device_info->guid));
+ if (!ShouldExposeDevice(*device_info))
+ return;
+ devices_.insert(std::make_pair(device_info->guid, device_info->Clone()));
+
+ // Notify all observers.
+ for (auto& observer : device_observer_list_)
+ observer.OnDeviceAdded(*device_info);
+}
+
+void UsbChooserContext::OnDeviceRemoved(
+ device::mojom::UsbDeviceInfoPtr device_info) {
+ DCHECK(device_info);
+
+ if (!ShouldExposeDevice(*device_info)) {
+ DCHECK(!base::Contains(devices_, device_info->guid));
+ return;
+ }
+
+ // Update the device list.
+ DCHECK(base::Contains(devices_, device_info->guid));
+ devices_.erase(device_info->guid);
+
+ // Notify all device observers.
+ for (auto& observer : device_observer_list_)
+ observer.OnDeviceRemoved(*device_info);
+
+ // If the device was persistent, return. Otherwise, notify all permission
+ // observers that its permissions were revoked.
+ if (device_info->serial_number &&
+ !device_info->serial_number.value().empty()) {
+ return;
+ }
+ for (auto& map_entry : ephemeral_devices_) {
+ map_entry.second.erase(device_info->guid);
+ }
+}
+
+void UsbChooserContext::OnDeviceManagerConnectionError() {
+ device_manager_.reset();
+ client_receiver_.reset();
+ devices_.clear();
+ is_initialized_ = false;
+
+ ephemeral_devices_.clear();
+
+ // Notify all device observers.
+ for (auto& observer : device_observer_list_)
+ observer.OnDeviceManagerConnectionError();
+}
+
+} // namespace electron
diff --git a/shell/browser/usb/usb_chooser_context.h b/shell/browser/usb/usb_chooser_context.h
new file mode 100644
index 0000000000..76c55b0dd1
--- /dev/null
+++ b/shell/browser/usb/usb_chooser_context.h
@@ -0,0 +1,122 @@
+// Copyright (c) 2022 Microsoft, Inc.
+// Use of this source code is governed by the MIT license that can be
+// found in the LICENSE file.
+
+#ifndef ELECTRON_SHELL_BROWSER_USB_USB_CHOOSER_CONTEXT_H_
+#define ELECTRON_SHELL_BROWSER_USB_USB_CHOOSER_CONTEXT_H_
+
+#include <map>
+#include <memory>
+#include <set>
+#include <string>
+#include <utility>
+#include <vector>
+
+#include "base/containers/queue.h"
+#include "base/observer_list.h"
+#include "base/values.h"
+#include "build/build_config.h"
+#include "components/keyed_service/core/keyed_service.h"
+#include "mojo/public/cpp/bindings/associated_receiver.h"
+#include "mojo/public/cpp/bindings/pending_receiver.h"
+#include "mojo/public/cpp/bindings/pending_remote.h"
+#include "mojo/public/cpp/bindings/remote.h"
+#include "services/device/public/mojom/usb_manager.mojom.h"
+#include "services/device/public/mojom/usb_manager_client.mojom.h"
+#include "shell/browser/electron_browser_context.h"
+#include "url/origin.h"
+
+namespace electron {
+
+class UsbChooserContext : public KeyedService,
+ public device::mojom::UsbDeviceManagerClient {
+ public:
+ explicit UsbChooserContext(ElectronBrowserContext* context);
+
+ UsbChooserContext(const UsbChooserContext&) = delete;
+ UsbChooserContext& operator=(const UsbChooserContext&) = delete;
+
+ ~UsbChooserContext() override;
+
+ // This observer can be used to be notified of changes to USB devices that are
+ // connected.
+ class DeviceObserver : public base::CheckedObserver {
+ public:
+ virtual void OnDeviceAdded(const device::mojom::UsbDeviceInfo&);
+ virtual void OnDeviceRemoved(const device::mojom::UsbDeviceInfo&);
+ virtual void OnDeviceManagerConnectionError();
+
+ // Called when the BrowserContext is shutting down. Observers must remove
+ // themselves before returning.
+ virtual void OnBrowserContextShutdown() = 0;
+ };
+
+ static base::Value DeviceInfoToValue(
+ const device::mojom::UsbDeviceInfo& device_info);
+
+ // Grants |origin| access to the USB device.
+ void GrantDevicePermission(const url::Origin& origin,
+ const device::mojom::UsbDeviceInfo& device_info);
+
+ // Checks if |origin| has access to a device with |device_info|.
+ bool HasDevicePermission(const url::Origin& origin,
+ const device::mojom::UsbDeviceInfo& device_info);
+
+ // Revokes |origin| access to the USB device ordered by website.
+ void RevokeDevicePermissionWebInitiated(
+ const url::Origin& origin,
+ const device::mojom::UsbDeviceInfo& device);
+
+ void AddObserver(DeviceObserver* observer);
+ void RemoveObserver(DeviceObserver* observer);
+
+ // Forward UsbDeviceManager methods.
+ void GetDevices(device::mojom::UsbDeviceManager::GetDevicesCallback callback);
+ void GetDevice(
+ const std::string& guid,
+ base::span<const uint8_t> blocked_interface_classes,
+ mojo::PendingReceiver<device::mojom::UsbDevice> device_receiver,
+ mojo::PendingRemote<device::mojom::UsbDeviceClient> device_client);
+
+ // This method should only be called when you are sure that |devices_| has
+ // been initialized. It will return nullptr if the guid cannot be found.
+ const device::mojom::UsbDeviceInfo* GetDeviceInfo(const std::string& guid);
+
+ base::WeakPtr<UsbChooserContext> AsWeakPtr();
+
+ void InitDeviceList(std::vector<::device::mojom::UsbDeviceInfoPtr> devices);
+
+ private:
+ // device::mojom::UsbDeviceManagerClient implementation.
+ void OnDeviceAdded(device::mojom::UsbDeviceInfoPtr device_info) override;
+ void OnDeviceRemoved(device::mojom::UsbDeviceInfoPtr device_info) override;
+
+ void RevokeObjectPermissionInternal(const url::Origin& origin,
+ const base::Value& object,
+ bool revoked_by_website);
+
+ void OnDeviceManagerConnectionError();
+ void EnsureConnectionWithDeviceManager();
+ void SetUpDeviceManagerConnection();
+
+ bool is_initialized_ = false;
+ base::queue<device::mojom::UsbDeviceManager::GetDevicesCallback>
+ pending_get_devices_requests_;
+
+ std::map<url::Origin, std::set<std::string>> ephemeral_devices_;
+ std::map<std::string, device::mojom::UsbDeviceInfoPtr> devices_;
+
+ // Connection to |device_manager_instance_|.
+ mojo::Remote<device::mojom::UsbDeviceManager> device_manager_;
+ mojo::AssociatedReceiver<device::mojom::UsbDeviceManagerClient>
+ client_receiver_{this};
+ base::ObserverList<DeviceObserver> device_observer_list_;
+
+ ElectronBrowserContext* browser_context_;
+
+ base::WeakPtrFactory<UsbChooserContext> weak_factory_{this};
+};
+
+} // namespace electron
+
+#endif // ELECTRON_SHELL_BROWSER_USB_USB_CHOOSER_CONTEXT_H_
diff --git a/shell/browser/usb/usb_chooser_context_factory.cc b/shell/browser/usb/usb_chooser_context_factory.cc
new file mode 100644
index 0000000000..28fa16f5d1
--- /dev/null
+++ b/shell/browser/usb/usb_chooser_context_factory.cc
@@ -0,0 +1,45 @@
+// Copyright (c) 2022 Microsoft, Inc.
+// Use of this source code is governed by the MIT license that can be
+// found in the LICENSE file.
+
+#include "shell/browser/usb/usb_chooser_context_factory.h"
+
+#include "components/keyed_service/content/browser_context_dependency_manager.h"
+#include "shell/browser/electron_browser_context.h"
+#include "shell/browser/usb/usb_chooser_context.h"
+
+namespace electron {
+
+UsbChooserContextFactory::UsbChooserContextFactory()
+ : BrowserContextKeyedServiceFactory(
+ "UsbChooserContext",
+ BrowserContextDependencyManager::GetInstance()) {}
+
+UsbChooserContextFactory::~UsbChooserContextFactory() {}
+
+KeyedService* UsbChooserContextFactory::BuildServiceInstanceFor(
+ content::BrowserContext* context) const {
+ auto* browser_context =
+ static_cast<electron::ElectronBrowserContext*>(context);
+ return new UsbChooserContext(browser_context);
+}
+
+// static
+UsbChooserContextFactory* UsbChooserContextFactory::GetInstance() {
+ return base::Singleton<UsbChooserContextFactory>::get();
+}
+
+// static
+UsbChooserContext* UsbChooserContextFactory::GetForBrowserContext(
+ content::BrowserContext* context) {
+ return static_cast<UsbChooserContext*>(
+ GetInstance()->GetServiceForBrowserContext(context, /*create=*/true));
+}
+
+UsbChooserContext* UsbChooserContextFactory::GetForBrowserContextIfExists(
+ content::BrowserContext* context) {
+ return static_cast<UsbChooserContext*>(
+ GetInstance()->GetServiceForBrowserContext(context, /*create=*/false));
+}
+
+} // namespace electron
diff --git a/shell/browser/usb/usb_chooser_context_factory.h b/shell/browser/usb/usb_chooser_context_factory.h
new file mode 100644
index 0000000000..14e18df2e8
--- /dev/null
+++ b/shell/browser/usb/usb_chooser_context_factory.h
@@ -0,0 +1,39 @@
+// Copyright (c) 2022 Microsoft, Inc.
+// Use of this source code is governed by the MIT license that can be
+// found in the LICENSE file.
+
+#ifndef ELECTRON_SHELL_BROWSER_USB_USB_CHOOSER_CONTEXT_FACTORY_H_
+#define ELECTRON_SHELL_BROWSER_USB_USB_CHOOSER_CONTEXT_FACTORY_H_
+
+#include "base/memory/singleton.h"
+#include "components/keyed_service/content/browser_context_keyed_service_factory.h"
+
+namespace electron {
+
+class UsbChooserContext;
+
+class UsbChooserContextFactory : public BrowserContextKeyedServiceFactory {
+ public:
+ static UsbChooserContext* GetForBrowserContext(
+ content::BrowserContext* context);
+ static UsbChooserContext* GetForBrowserContextIfExists(
+ content::BrowserContext* context);
+ static UsbChooserContextFactory* GetInstance();
+
+ UsbChooserContextFactory(const UsbChooserContextFactory&) = delete;
+ UsbChooserContextFactory& operator=(const UsbChooserContextFactory&) = delete;
+
+ private:
+ friend struct base::DefaultSingletonTraits<UsbChooserContextFactory>;
+
+ UsbChooserContextFactory();
+ ~UsbChooserContextFactory() override;
+
+ // BrowserContextKeyedServiceFactory methods:
+ KeyedService* BuildServiceInstanceFor(
+ content::BrowserContext* profile) const override;
+};
+
+} // namespace electron
+
+#endif // ELECTRON_SHELL_BROWSER_USB_USB_CHOOSER_CONTEXT_FACTORY_H_
diff --git a/shell/browser/usb/usb_chooser_controller.cc b/shell/browser/usb/usb_chooser_controller.cc
new file mode 100644
index 0000000000..87e5457884
--- /dev/null
+++ b/shell/browser/usb/usb_chooser_controller.cc
@@ -0,0 +1,165 @@
+// Copyright (c) 2022 Microsoft, Inc.
+// Use of this source code is governed by the MIT license that can be
+// found in the LICENSE file.
+
+#include "shell/browser/usb/usb_chooser_controller.h"
+
+#include <stddef.h>
+#include <utility>
+
+#include "base/bind.h"
+#include "base/strings/stringprintf.h"
+#include "base/strings/utf_string_conversions.h"
+#include "build/build_config.h"
+#include "components/strings/grit/components_strings.h"
+#include "content/public/browser/render_frame_host.h"
+#include "content/public/browser/web_contents.h"
+#include "gin/data_object_builder.h"
+#include "services/device/public/cpp/usb/usb_utils.h"
+#include "services/device/public/mojom/usb_enumeration_options.mojom.h"
+#include "shell/browser/javascript_environment.h"
+#include "shell/browser/usb/usb_chooser_context_factory.h"
+#include "shell/common/gin_converters/callback_converter.h"
+#include "shell/common/gin_converters/content_converter.h"
+#include "shell/common/gin_converters/frame_converter.h"
+#include "shell/common/gin_converters/usb_device_info_converter.h"
+#include "shell/common/node_includes.h"
+#include "shell/common/process_util.h"
+#include "ui/base/l10n/l10n_util.h"
+#include "url/gurl.h"
+
+using content::RenderFrameHost;
+using content::WebContents;
+
+namespace electron {
+
+UsbChooserController::UsbChooserController(
+ RenderFrameHost* render_frame_host,
+ std::vector<device::mojom::UsbDeviceFilterPtr> device_filters,
+ blink::mojom::WebUsbService::GetPermissionCallback callback,
+ content::WebContents* web_contents,
+ base::WeakPtr<ElectronUsbDelegate> usb_delegate)
+ : WebContentsObserver(web_contents),
+ filters_(std::move(device_filters)),
+ callback_(std::move(callback)),
+ origin_(render_frame_host->GetMainFrame()->GetLastCommittedOrigin()),
+ usb_delegate_(usb_delegate),
+ render_frame_host_id_(render_frame_host->GetGlobalId()) {
+ chooser_context_ = UsbChooserContextFactory::GetForBrowserContext(
+ web_contents->GetBrowserContext())
+ ->AsWeakPtr();
+ DCHECK(chooser_context_);
+ chooser_context_->GetDevices(base::BindOnce(
+ &UsbChooserController::GotUsbDeviceList, weak_factory_.GetWeakPtr()));
+}
+
+UsbChooserController::~UsbChooserController() {
+ RunCallback(/*device=*/nullptr);
+}
+
+api::Session* UsbChooserController::GetSession() {
+ if (!web_contents()) {
+ return nullptr;
+ }
+ return api::Session::FromBrowserContext(web_contents()->GetBrowserContext());
+}
+
+void UsbChooserController::OnDeviceAdded(
+ const device::mojom::UsbDeviceInfo& device_info) {
+ if (DisplayDevice(device_info)) {
+ api::Session* session = GetSession();
+ if (session) {
+ session->Emit("usb-device-added", device_info.Clone(), web_contents());
+ }
+ }
+}
+
+void UsbChooserController::OnDeviceRemoved(
+ const device::mojom::UsbDeviceInfo& device_info) {
+ api::Session* session = GetSession();
+ if (session) {
+ session->Emit("usb-device-removed", device_info.Clone(), web_contents());
+ }
+}
+
+void UsbChooserController::OnDeviceChosen(gin::Arguments* args) {
+ std::string device_id;
+ if (!args->GetNext(&device_id) || device_id.empty()) {
+ RunCallback(/*device=*/nullptr);
+ } else {
+ auto* device_info = chooser_context_->GetDeviceInfo(device_id);
+ if (device_info) {
+ RunCallback(device_info->Clone());
+ } else {
+ v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
+ node::Environment* env = node::Environment::GetCurrent(isolate);
+ EmitWarning(env, "The device id " + device_id + " was not found.",
+ "UnknownUsbDeviceId");
+ RunCallback(/*device=*/nullptr);
+ }
+ }
+}
+
+void UsbChooserController::OnBrowserContextShutdown() {
+ observation_.Reset();
+}
+
+// Get a list of devices that can be shown in the chooser bubble UI for
+// user to grant permsssion.
+void UsbChooserController::GotUsbDeviceList(
+ std::vector<::device::mojom::UsbDeviceInfoPtr> devices) {
+ // Listen to UsbChooserContext for OnDeviceAdded/Removed events after the
+ // enumeration.
+ if (chooser_context_)
+ observation_.Observe(chooser_context_.get());
+
+ bool prevent_default = false;
+ api::Session* session = GetSession();
+ if (session) {
+ auto* rfh = content::RenderFrameHost::FromID(render_frame_host_id_);
+ v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
+ v8::HandleScope scope(isolate);
+ v8::Local<v8::Object> details = gin::DataObjectBuilder(isolate)
+ .Set("deviceList", devices)
+ .Set("frame", rfh)
+ .Build();
+
+ prevent_default =
+ session->Emit("select-usb-device", details,
+ base::AdaptCallbackForRepeating(
+ base::BindOnce(&UsbChooserController::OnDeviceChosen,
+ weak_factory_.GetWeakPtr())));
+ }
+ if (!prevent_default) {
+ RunCallback(/*port=*/nullptr);
+ }
+}
+
+bool UsbChooserController::DisplayDevice(
+ const device::mojom::UsbDeviceInfo& device_info) const {
+ if (!device::UsbDeviceFilterMatchesAny(filters_, device_info))
+ return false;
+
+ return true;
+}
+
+void UsbChooserController::RenderFrameDeleted(
+ content::RenderFrameHost* render_frame_host) {
+ if (usb_delegate_) {
+ usb_delegate_->DeleteControllerForFrame(render_frame_host);
+ }
+}
+
+void UsbChooserController::RunCallback(
+ device::mojom::UsbDeviceInfoPtr device_info) {
+ if (callback_) {
+ if (!chooser_context_ || !device_info) {
+ std::move(callback_).Run(nullptr);
+ } else {
+ chooser_context_->GrantDevicePermission(origin_, *device_info);
+ std::move(callback_).Run(std::move(device_info));
+ }
+ }
+}
+
+} // namespace electron
diff --git a/shell/browser/usb/usb_chooser_controller.h b/shell/browser/usb/usb_chooser_controller.h
new file mode 100644
index 0000000000..4e71bc17c1
--- /dev/null
+++ b/shell/browser/usb/usb_chooser_controller.h
@@ -0,0 +1,81 @@
+// Copyright (c) 2022 Microsoft, Inc.
+// Use of this source code is governed by the MIT license that can be
+// found in the LICENSE file.
+
+#ifndef ELECTRON_SHELL_BROWSER_USB_USB_CHOOSER_CONTROLLER_H_
+#define ELECTRON_SHELL_BROWSER_USB_USB_CHOOSER_CONTROLLER_H_
+
+#include <string>
+#include <unordered_map>
+#include <utility>
+#include <vector>
+
+#include "base/memory/raw_ptr.h"
+#include "base/memory/ref_counted.h"
+#include "base/memory/weak_ptr.h"
+#include "base/scoped_observation.h"
+#include "content/public/browser/web_contents.h"
+#include "content/public/browser/web_contents_observer.h"
+#include "services/device/public/mojom/usb_device.mojom.h"
+#include "shell/browser/api/electron_api_session.h"
+#include "shell/browser/usb/electron_usb_delegate.h"
+#include "shell/browser/usb/usb_chooser_context.h"
+#include "third_party/blink/public/mojom/usb/web_usb_service.mojom.h"
+#include "url/origin.h"
+
+namespace content {
+class RenderFrameHost;
+}
+
+namespace electron {
+
+// UsbChooserController creates a chooser for WebUSB.
+class UsbChooserController final : public UsbChooserContext::DeviceObserver,
+ public content::WebContentsObserver {
+ public:
+ UsbChooserController(
+ content::RenderFrameHost* render_frame_host,
+ std::vector<device::mojom::UsbDeviceFilterPtr> device_filters,
+ blink::mojom::WebUsbService::GetPermissionCallback callback,
+ content::WebContents* web_contents,
+ base::WeakPtr<ElectronUsbDelegate> usb_delegate);
+
+ UsbChooserController(const UsbChooserController&) = delete;
+ UsbChooserController& operator=(const UsbChooserController&) = delete;
+
+ ~UsbChooserController() override;
+
+ // UsbChooserContext::DeviceObserver implementation:
+ void OnDeviceAdded(const device::mojom::UsbDeviceInfo& device_info) override;
+ void OnDeviceRemoved(
+ const device::mojom::UsbDeviceInfo& device_info) override;
+ void OnBrowserContextShutdown() override;
+
+ // content::WebContentsObserver:
+ void RenderFrameDeleted(content::RenderFrameHost* render_frame_host) override;
+
+ private:
+ api::Session* GetSession();
+ void GotUsbDeviceList(std::vector<device::mojom::UsbDeviceInfoPtr> devices);
+ bool DisplayDevice(const device::mojom::UsbDeviceInfo& device) const;
+ void RunCallback(device::mojom::UsbDeviceInfoPtr device_info);
+ void OnDeviceChosen(gin::Arguments* args);
+
+ std::vector<device::mojom::UsbDeviceFilterPtr> filters_;
+ blink::mojom::WebUsbService::GetPermissionCallback callback_;
+ url::Origin origin_;
+
+ base::WeakPtr<UsbChooserContext> chooser_context_;
+ base::ScopedObservation<UsbChooserContext, UsbChooserContext::DeviceObserver>
+ observation_{this};
+
+ base::WeakPtr<ElectronUsbDelegate> usb_delegate_;
+
+ content::GlobalRenderFrameHostId render_frame_host_id_;
+
+ base::WeakPtrFactory<UsbChooserController> weak_factory_{this};
+};
+
+} // namespace electron
+
+#endif // ELECTRON_SHELL_BROWSER_USB_USB_CHOOSER_CONTROLLER_H_
diff --git a/shell/browser/web_contents_permission_helper.h b/shell/browser/web_contents_permission_helper.h
index 43a5ca63ec..972675c19f 100644
--- a/shell/browser/web_contents_permission_helper.h
+++ b/shell/browser/web_contents_permission_helper.h
@@ -29,7 +29,8 @@ class WebContentsPermissionHelper
FULLSCREEN,
OPEN_EXTERNAL,
SERIAL,
- HID
+ HID,
+ USB
};
// Asynchronous Requests
diff --git a/shell/common/electron_constants.cc b/shell/common/electron_constants.cc
index 3d6eda0e9e..763c2e18e5 100644
--- a/shell/common/electron_constants.cc
+++ b/shell/common/electron_constants.cc
@@ -25,6 +25,10 @@ const char kSecureProtocolDescription[] =
"The connection to this site is using a strong protocol version "
"and cipher suite.";
+const char kDeviceVendorIdKey[] = "vendorId";
+const char kDeviceProductIdKey[] = "productId";
+const char kDeviceSerialNumberKey[] = "serialNumber";
+
#if BUILDFLAG(ENABLE_RUN_AS_NODE)
const char kRunAsNode[] = "ELECTRON_RUN_AS_NODE";
#endif
diff --git a/shell/common/electron_constants.h b/shell/common/electron_constants.h
index 4218b3e47f..6927411006 100644
--- a/shell/common/electron_constants.h
+++ b/shell/common/electron_constants.h
@@ -25,6 +25,11 @@ extern const char kValidCertificateDescription[];
extern const char kSecureProtocol[];
extern const char kSecureProtocolDescription[];
+// Keys for Device APIs
+extern const char kDeviceVendorIdKey[];
+extern const char kDeviceProductIdKey[];
+extern const char kDeviceSerialNumberKey[];
+
#if BUILDFLAG(ENABLE_RUN_AS_NODE)
extern const char kRunAsNode[];
#endif
diff --git a/shell/common/gin_converters/content_converter.cc b/shell/common/gin_converters/content_converter.cc
index 71c2e9bb24..2c1bf9c52a 100644
--- a/shell/common/gin_converters/content_converter.cc
+++ b/shell/common/gin_converters/content_converter.cc
@@ -209,6 +209,8 @@ v8::Local<v8::Value> Converter<blink::PermissionType>::ToV8(
return StringToV8(isolate, "serial");
case PermissionType::HID:
return StringToV8(isolate, "hid");
+ case PermissionType::USB:
+ return StringToV8(isolate, "usb");
default:
return StringToV8(isolate, "unknown");
}
diff --git a/shell/common/gin_converters/usb_device_info_converter.h b/shell/common/gin_converters/usb_device_info_converter.h
new file mode 100644
index 0000000000..d8ffda006b
--- /dev/null
+++ b/shell/common/gin_converters/usb_device_info_converter.h
@@ -0,0 +1,27 @@
+// Copyright (c) 2022 Microsoft, Inc.
+// Use of this source code is governed by the MIT license that can be
+// found in the LICENSE file.
+
+#ifndef ELECTRON_SHELL_COMMON_GIN_CONVERTERS_USB_DEVICE_INFO_CONVERTER_H_
+#define ELECTRON_SHELL_COMMON_GIN_CONVERTERS_USB_DEVICE_INFO_CONVERTER_H_
+
+#include "gin/converter.h"
+#include "services/device/public/mojom/usb_device.mojom.h"
+#include "shell/browser/usb/usb_chooser_context.h"
+#include "shell/common/gin_converters/value_converter.h"
+
+namespace gin {
+
+template <>
+struct Converter<device::mojom::UsbDeviceInfoPtr> {
+ static v8::Local<v8::Value> ToV8(
+ v8::Isolate* isolate,
+ const device::mojom::UsbDeviceInfoPtr& device) {
+ base::Value value = electron::UsbChooserContext::DeviceInfoToValue(*device);
+ return gin::ConvertToV8(isolate, value);
+ }
+};
+
+} // namespace gin
+
+#endif // ELECTRON_SHELL_COMMON_GIN_CONVERTERS_USB_DEVICE_INFO_CONVERTER_H_
diff --git a/spec/chromium-spec.ts b/spec/chromium-spec.ts
index 53281f6604..dc8f8fc86a 100644
--- a/spec/chromium-spec.ts
+++ b/spec/chromium-spec.ts
@@ -2857,3 +2857,164 @@ describe('navigator.hid', () => {
}
});
});
+
+describe('navigator.usb', () => {
+ let w: BrowserWindow;
+ let server: http.Server;
+ let serverUrl: string;
+ before(async () => {
+ w = new BrowserWindow({
+ show: false
+ });
+ await w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
+ server = http.createServer((req, res) => {
+ res.setHeader('Content-Type', 'text/html');
+ res.end('<body>');
+ });
+ await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
+ serverUrl = `http://localhost:${(server.address() as any).port}`;
+ });
+
+ const requestDevices: any = () => {
+ return w.webContents.executeJavaScript(`
+ navigator.usb.requestDevice({filters: []}).then(device => device.toString()).catch(err => err.toString());
+ `, true);
+ };
+
+ const notFoundError = 'NotFoundError: Failed to execute \'requestDevice\' on \'USB\': No device selected.';
+
+ after(() => {
+ server.close();
+ closeAllWindows();
+ });
+ afterEach(() => {
+ session.defaultSession.setPermissionCheckHandler(null);
+ session.defaultSession.setDevicePermissionHandler(null);
+ session.defaultSession.removeAllListeners('select-usb-device');
+ });
+
+ it('does not return a device if select-usb-device event is not defined', async () => {
+ w.loadFile(path.join(fixturesPath, 'pages', 'blank.html'));
+ const device = await requestDevices();
+ expect(device).to.equal(notFoundError);
+ });
+
+ it('does not return a device when permission denied', async () => {
+ let selectFired = false;
+ w.webContents.session.on('select-usb-device', (event, details, callback) => {
+ selectFired = true;
+ callback();
+ });
+ session.defaultSession.setPermissionCheckHandler(() => false);
+ const device = await requestDevices();
+ expect(selectFired).to.be.false();
+ expect(device).to.equal(notFoundError);
+ });
+
+ it('returns a device when select-usb-device event is defined', async () => {
+ let haveDevices = false;
+ let selectFired = false;
+ w.webContents.session.on('select-usb-device', (event, details, callback) => {
+ expect(details.frame).to.have.ownProperty('frameTreeNodeId').that.is.a('number');
+ selectFired = true;
+ if (details.deviceList.length > 0) {
+ haveDevices = true;
+ callback(details.deviceList[0].deviceId);
+ } else {
+ callback();
+ }
+ });
+ const device = await requestDevices();
+ expect(selectFired).to.be.true();
+ if (haveDevices) {
+ expect(device).to.contain('[object USBDevice]');
+ } else {
+ expect(device).to.equal(notFoundError);
+ }
+ if (haveDevices) {
+ // Verify that navigation will clear device permissions
+ const grantedDevices = await w.webContents.executeJavaScript('navigator.usb.getDevices()');
+ expect(grantedDevices).to.not.be.empty();
+ w.loadURL(serverUrl);
+ const [,,,,, frameProcessId, frameRoutingId] = await emittedOnce(w.webContents, 'did-frame-navigate');
+ const frame = webFrameMain.fromId(frameProcessId, frameRoutingId);
+ expect(frame).to.not.be.empty();
+ if (frame) {
+ const grantedDevicesOnNewPage = await frame.executeJavaScript('navigator.usb.getDevices()');
+ expect(grantedDevicesOnNewPage).to.be.empty();
+ }
+ }
+ });
+
+ it('returns a device when DevicePermissionHandler is defined', async () => {
+ let haveDevices = false;
+ let selectFired = false;
+ let gotDevicePerms = false;
+ w.webContents.session.on('select-usb-device', (event, details, callback) => {
+ selectFired = true;
+ if (details.deviceList.length > 0) {
+ const foundDevice = details.deviceList.find((device) => {
+ if (device.productName && device.productName !== '' && device.serialNumber && device.serialNumber !== '') {
+ haveDevices = true;
+ return true;
+ }
+ });
+ if (foundDevice) {
+ callback(foundDevice.deviceId);
+ return;
+ }
+ }
+ callback();
+ });
+ session.defaultSession.setDevicePermissionHandler(() => {
+ gotDevicePerms = true;
+ return true;
+ });
+ await w.webContents.executeJavaScript('navigator.usb.getDevices();', true);
+ const device = await requestDevices();
+ expect(selectFired).to.be.true();
+ if (haveDevices) {
+ expect(device).to.contain('[object USBDevice]');
+ expect(gotDevicePerms).to.be.true();
+ } else {
+ expect(device).to.equal(notFoundError);
+ }
+ });
+
+ it('supports device.forget()', async () => {
+ let deletedDeviceFromEvent;
+ let haveDevices = false;
+ w.webContents.session.on('select-usb-device', (event, details, callback) => {
+ if (details.deviceList.length > 0) {
+ haveDevices = true;
+ callback(details.deviceList[0].deviceId);
+ } else {
+ callback();
+ }
+ });
+ w.webContents.session.on('usb-device-revoked', (event, details) => {
+ deletedDeviceFromEvent = details.device;
+ });
+ await requestDevices();
+ if (haveDevices) {
+ const grantedDevices = await w.webContents.executeJavaScript('navigator.usb.getDevices()');
+ if (grantedDevices.length > 0) {
+ const deletedDevice = await w.webContents.executeJavaScript(`
+ navigator.usb.getDevices().then(devices => {
+ devices[0].forget();
+ return {
+ vendorId: devices[0].vendorId,
+ productId: devices[0].productId,
+ productName: devices[0].productName
+ }
+ })
+ `);
+ const grantedDevices2 = await w.webContents.executeJavaScript('navigator.usb.getDevices()');
+ expect(grantedDevices2.length).to.be.lessThan(grantedDevices.length);
+ if (deletedDevice.name !== '' && deletedDevice.productId && deletedDevice.vendorId) {
+ expect(deletedDeviceFromEvent).to.include(deletedDevice);
+ }
+ }
+ }
+ });
+});
|
feat
|
dc74092a090cb6448951036e951ae0f4d775cc98
|
Quinn
|
2024-12-16 15:38:25
|
fix: better prompt not supported message in window-setup.ts (#45017)
Update window-setup.ts
The message should simply read "is not supported" or, alternatively, "is not, and will not, be supported", but not "is and will not be supported".
|
diff --git a/lib/renderer/window-setup.ts b/lib/renderer/window-setup.ts
index 9f48ea3941..0fab8eb77e 100644
--- a/lib/renderer/window-setup.ts
+++ b/lib/renderer/window-setup.ts
@@ -15,7 +15,7 @@ export const windowSetup = (isWebView: boolean, isHiddenPage: boolean) => {
// But we do not support prompt().
window.prompt = function () {
- throw new Error('prompt() is and will not be supported.');
+ throw new Error('prompt() is not supported.');
};
if (contextIsolationEnabled) internalContextBridge.overrideGlobalValueFromIsolatedWorld(['prompt'], window.prompt);
|
fix
|
c63d0d61e71f12d29efb1df885a0883ae76bb164
|
Shelley Vohr
|
2024-11-04 19:41:56
|
chore: bump Node.js to v22.9.0 (#44281)
* chore: bump Node.js to v22.9.0
* build: drop base64 dep in GN build
https://github.com/nodejs/node/pull/52856
* build,tools: make addons tests work with GN
https://github.com/nodejs/node/pull/50737
* fs: add fast api for InternalModuleStat
https://github.com/nodejs/node/pull/51344
* src: move package_json_reader cache to c++
https://github.com/nodejs/node/pull/50322
* crypto: disable PKCS#1 padding for privateDecrypt
https://github.com/nodejs-private/node-private/pull/525
* src: move more crypto code to ncrypto
https://github.com/nodejs/node/pull/54320
* crypto: ensure valid point on elliptic curve in SubtleCrypto.importKey
https://github.com/nodejs/node/pull/50234
* src: shift more crypto impl details to ncrypto
https://github.com/nodejs/node/pull/54028
* src: switch crypto APIs to use Maybe<void>
https://github.com/nodejs/node/pull/54775
* crypto: remove DEFAULT_ENCODING
https://github.com/nodejs/node/pull/47182
* deps: update libuv to 1.47.0
https://github.com/nodejs/node/pull/50650
* build: fix conflict gyp configs
https://github.com/nodejs/node/pull/53605
* lib,src: drop --experimental-network-imports
https://github.com/nodejs/node/pull/53822
* esm: align sync and async load implementations
https://github.com/nodejs/node/pull/49152
* esm: remove unnecessary toNamespacedPath calls
https://github.com/nodejs/node/pull/53656
* module: detect ESM syntax by trying to recompile as SourceTextModule
https://github.com/nodejs/node/pull/52413
* test: adapt debugger tests to V8 11.4
https://github.com/nodejs/node/pull/49639
* lib: update usage of always on Atomics API
https://github.com/nodejs/node/pull/49639
* test: adapt test-fs-write to V8 internal changes
https://github.com/nodejs/node/pull/49639
* test: adapt to new V8 trusted memory spaces
https://github.com/nodejs/node/pull/50115
* deps: update libuv to 1.47.0
https://github.com/nodejs/node/pull/50650
* src: use non-deprecated v8::Uint8Array::kMaxLength
https://github.com/nodejs/node/pull/50115
* src: update default V8 platform to override functions with location
https://github.com/nodejs/node/pull/51362
* src: add missing TryCatch
https://github.com/nodejs/node/pull/51362
* lib,test: handle new Iterator global
https://github.com/nodejs/node/pull/51362
* src: use non-deprecated version of CreateSyntheticModule
https://github.com/nodejs/node/pull/50115
* src: remove calls to recently deprecated V8 APIs
https://github.com/nodejs/node/pull/52996
* src: use new V8 API to define stream accessor
https://github.com/nodejs/node/pull/53084
* src: do not use deprecated V8 API
https://github.com/nodejs/node/pull/53084
* src: do not use soon-to-be-deprecated V8 API
https://github.com/nodejs/node/pull/53174
* src: migrate to new V8 interceptors API
https://github.com/nodejs/node/pull/52745
* src: use supported API to get stalled TLA messages
https://github.com/nodejs/node/pull/51362
* module: print location of unsettled top-level await in entry points
https://github.com/nodejs/node/pull/51999
* test: make snapshot comparison more flexible
https://github.com/nodejs/node/pull/54375
* test: do not set concurrency on parallelized runs
https://github.com/nodejs/node/pull/52177
* src: move FromNamespacedPath to path.cc
https://github.com/nodejs/node/pull/53540
* test: adapt to new V8 trusted memory spaces
https://github.com/nodejs/node/pull/50115
* build: add option to enable clang-cl on Windows
https://github.com/nodejs/node/pull/52870
* chore: fixup patch indices
* chore: add/remove changed files
* esm: drop support for import assertions
https://github.com/nodejs/node/pull/54890
* build: compile with C++20 support
https://github.com/nodejs/node/pull/52838
* deps: update nghttp2 to 1.62.1
https://github.com/nodejs/node/pull/52966
* src: parse inspector profiles with simdjson
https://github.com/nodejs/node/pull/51783
* build: add GN build files
https://github.com/nodejs/node/pull/47637
* deps,lib,src: add experimental web storage
https://github.com/nodejs/node/pull/52435
* build: add missing BoringSSL dep
* src: rewrite task runner in c++
https://github.com/nodejs/node/pull/52609
* fixup! build: add GN build files
* src: stop using deprecated fields of v8::FastApiCallbackOptions
https://github.com/nodejs/node/pull/54077
* fix: shadow variable
* build: add back incorrectly removed SetAccessor patch
* fixup! fixup! build: add GN build files
* crypto: fix integer comparison in crypto for BoringSSL
* src,lib: reducing C++ calls of esm legacy main resolve
https://github.com/nodejs/node/pull/48325
* src: move more crypto_dh.cc code to ncrypto
https://github.com/nodejs/node/pull/54459
* chore: fixup GN files for previous commit
* src: move more crypto code to ncrypto
https://github.com/nodejs/node/pull/54320
* Fixup Perfetto ifdef guards
* fix: missing electron_natives dep
* fix: node_use_node_platform = false
* fix: include src/node_snapshot_stub.cc in libnode
* 5507047: [import-attributes] Remove support for import assertions
https://chromium-review.googlesource.com/c/v8/v8/+/5507047
* fix: restore v8-sandbox.h in filenames.json
* fix: re-add original-fs generation logic
* fix: ngtcp2 openssl dep
* test: try removing NAPI_VERSION undef
* chore(deps): bump @types/node
* src: move more crypto_dh.cc code to ncrypto
https://github.com/nodejs/node/pull/54459
* esm: remove unnecessary toNamespacedPath calls
https://github.com/nodejs/node/pull/53656
* buffer: fix out of range for toString
https://github.com/nodejs/node/pull/54553
* lib: rewrite AsyncLocalStorage without async_hooks
https://github.com/nodejs/node/pull/48528
* module: print amount of load time of a cjs module
https://github.com/nodejs/node/pull/52213
* test: skip reproducible snapshot test on 32-bit
https://github.com/nodejs/node/pull/53592
* fixup! src: move more crypto_dh.cc code to ncrypto
* test: adjust emittedUntil return type
* chore: remove redundant wpt streams patch
* fixup! chore(deps): bump @types/node
* fix: gn executable name on Windows
* fix: build on Windows
* fix: rename conflicting win32 symbols in //third_party/sqlite
On Windows otherwise we get:
lld-link: error: duplicate symbol: sqlite3_win32_write_debug
>>> defined at .\..\..\third_party\electron_node\deps\sqlite\sqlite3.c:47987
>>> obj/third_party/electron_node/deps/sqlite/sqlite/sqlite3.obj
>>> defined at obj/third_party/sqlite\chromium_sqlite3/sqlite3_shim.obj
lld-link: error: duplicate symbol: sqlite3_win32_sleep
>>> defined at .\..\..\third_party\electron_node\deps\sqlite\sqlite3.c:48042
>>> obj/third_party/electron_node/deps/sqlite/sqlite/sqlite3.obj
>>> defined at obj/third_party/sqlite\chromium_sqlite3/sqlite3_shim.obj
lld-link: error: duplicate symbol: sqlite3_win32_is_nt
>>> defined at .\..\..\third_party\electron_node\deps\sqlite\sqlite3.c:48113
>>> obj/third_party/electron_node/deps/sqlite/sqlite/sqlite3.obj
>>> defined at obj/third_party/sqlite\chromium_sqlite3/sqlite3_shim.obj
lld-link: error: duplicate symbol: sqlite3_win32_utf8_to_unicode
>>> defined at .\..\..\third_party\electron_node\deps\sqlite\sqlite3.c:48470
>>> obj/third_party/electron_node/deps/sqlite/sqlite/sqlite3.obj
>>> defined at obj/third_party/sqlite\chromium_sqlite3/sqlite3_shim.obj
lld-link: error: duplicate symbol: sqlite3_win32_unicode_to_utf8
>>> defined at .\..\..\third_party\electron_node\deps\sqlite\sqlite3.c:48486
>>> obj/third_party/electron_node/deps/sqlite/sqlite/sqlite3.obj
>>> defined at obj/third_party/sqlite\chromium_sqlite3/sqlite3_shim.obj
lld-link: error: duplicate symbol: sqlite3_win32_mbcs_to_utf8
>>> defined at .\..\..\third_party\electron_node\deps\sqlite\sqlite3.c:48502
>>> obj/third_party/electron_node/deps/sqlite/sqlite/sqlite3.obj
>>> defined at obj/third_party/sqlite\chromium_sqlite3/sqlite3_shim.obj
lld-link: error: duplicate symbol: sqlite3_win32_mbcs_to_utf8_v2
>>> defined at .\..\..\third_party\electron_node\deps\sqlite\sqlite3.c:48518
>>> obj/third_party/electron_node/deps/sqlite/sqlite/sqlite3.obj
>>> defined at obj/third_party/sqlite\chromium_sqlite3/sqlite3_shim.obj
lld-link: error: duplicate symbol: sqlite3_win32_utf8_to_mbcs
>>> defined at .\..\..\third_party\electron_node\deps\sqlite\sqlite3.c:48534
>>> obj/third_party/electron_node/deps/sqlite/sqlite/sqlite3.obj
>>> defined at obj/third_party/sqlite\chromium_sqlite3/sqlite3_shim.obj
lld-link: error: duplicate symbol: sqlite3_win32_utf8_to_mbcs_v2
>>> defined at .\..\..\third_party\electron_node\deps\sqlite\sqlite3.c:48550
>>> obj/third_party/electron_node/deps/sqlite/sqlite/sqlite3.obj
>>> defined at obj/third_party/sqlite\chromium_sqlite3/sqlite3_shim.obj
* docs: remove unnecessary ts-expect-error after types bump
* src: move package resolver to c++
https://github.com/nodejs/node/pull/50322
* build: set ASAN detect_container_overflow=0
https://github.com/nodejs/node/issues/55584
* chore: fixup rebase
* test: disable failing ASAN test
* win: almost fix race detecting ESRCH in uv_kill
https://github.com/libuv/libuv/pull/4341
|
diff --git a/.github/workflows/pipeline-segment-electron-test.yml b/.github/workflows/pipeline-segment-electron-test.yml
index ab850c0e77..5e91be33db 100644
--- a/.github/workflows/pipeline-segment-electron-test.yml
+++ b/.github/workflows/pipeline-segment-electron-test.yml
@@ -176,7 +176,7 @@ jobs:
if [ "${{ inputs.is-asan }}" == "true" ]; then
cd ..
ASAN_SYMBOLIZE="$PWD/tools/valgrind/asan/asan_symbolize.py --executable-path=$PWD/out/Default/electron"
- export ASAN_OPTIONS="symbolize=0 handle_abort=1"
+ export ASAN_OPTIONS="symbolize=0 handle_abort=1 detect_container_overflow=0"
export G_SLICE=always-malloc
export NSS_DISABLE_ARENA_FREE_LIST=1
export NSS_DISABLE_UNLOAD=1
diff --git a/BUILD.gn b/BUILD.gn
index b0c54bf6bc..38c67abbdf 100644
--- a/BUILD.gn
+++ b/BUILD.gn
@@ -9,7 +9,7 @@ import("//pdf/features.gni")
import("//ppapi/buildflags/buildflags.gni")
import("//printing/buildflags/buildflags.gni")
import("//testing/test.gni")
-import("//third_party/electron_node/electron_node.gni")
+import("//third_party/electron_node/node.gni")
import("//third_party/ffmpeg/ffmpeg_options.gni")
import("//tools/generate_library_loader/generate_library_loader.gni")
import("//tools/grit/grit_rule.gni")
@@ -408,7 +408,7 @@ action("electron_generate_node_defines") {
source_set("electron_lib") {
configs += [
"//v8:external_startup_data",
- "//third_party/electron_node:node_internals",
+ "//third_party/electron_node:node_external_config",
]
public_configs = [
@@ -483,7 +483,7 @@ source_set("electron_lib") {
"//third_party/blink/public:blink_devtools_inspector_resources",
"//third_party/blink/public/platform/media",
"//third_party/boringssl",
- "//third_party/electron_node:node_lib",
+ "//third_party/electron_node:libnode",
"//third_party/inspector_protocol:crdtp",
"//third_party/leveldatabase",
"//third_party/libyuv",
@@ -865,7 +865,7 @@ if (is_mac) {
":electron_framework_resources",
":electron_swiftshader_library",
":electron_xibs",
- "//third_party/electron_node:node_lib",
+ "//third_party/electron_node:libnode",
]
if (!is_mas_build) {
deps += [ ":electron_crashpad_helper" ]
@@ -1189,7 +1189,7 @@ if (is_mac) {
"//components/crash/core/app",
"//content:sandbox_helper_win",
"//electron/buildflags",
- "//third_party/electron_node:node_lib",
+ "//third_party/electron_node:libnode",
"//ui/strings",
]
diff --git a/DEPS b/DEPS
index 493b20346b..08517cdcf9 100644
--- a/DEPS
+++ b/DEPS
@@ -4,7 +4,7 @@ vars = {
'chromium_version':
'132.0.6807.0',
'node_version':
- 'v20.18.0',
+ 'v22.9.0',
'nan_version':
'e14bdcd1f72d62bca1d541b66da43130384ec213',
'squirrel.mac_version':
diff --git a/docs/tutorial/multithreading.md b/docs/tutorial/multithreading.md
index eb2bcc9e47..ab70b88a50 100644
--- a/docs/tutorial/multithreading.md
+++ b/docs/tutorial/multithreading.md
@@ -42,7 +42,7 @@ safe.
The only way to load a native module safely for now, is to make sure the app
loads no native modules after the Web Workers get started.
-```js @ts-expect-error=[1]
+```js
process.dlopen = () => {
throw new Error('Load native module is not safe')
}
diff --git a/lib/node/asar-fs-wrapper.ts b/lib/node/asar-fs-wrapper.ts
index aebd5b3021..a46b97290f 100644
--- a/lib/node/asar-fs-wrapper.ts
+++ b/lib/node/asar-fs-wrapper.ts
@@ -841,6 +841,27 @@ export const wrapFsWithAsar = (fs: Record<string, any>) => {
return files;
};
+ const modBinding = internalBinding('modules');
+ const { readPackageJSON } = modBinding;
+ internalBinding('modules').readPackageJSON = (
+ jsonPath: string,
+ isESM: boolean,
+ base: undefined | string,
+ specifier: undefined | string
+ ) => {
+ const pathInfo = splitPath(jsonPath);
+ if (!pathInfo.isAsar) return readPackageJSON(jsonPath, isESM, base, specifier);
+ const { asarPath, filePath } = pathInfo;
+
+ const archive = getOrCreateArchive(asarPath);
+ if (!archive) return undefined;
+
+ const realPath = archive.copyFileOut(filePath);
+ if (!realPath) return undefined;
+
+ return readPackageJSON(realPath, isESM, base, specifier);
+ };
+
const binding = internalBinding('fs');
const { internalModuleReadJSON, kUsePromises } = binding;
internalBinding('fs').internalModuleReadJSON = (pathArgument: string) => {
diff --git a/npm/package.json b/npm/package.json
index 69015766c5..96fd3c3ad0 100644
--- a/npm/package.json
+++ b/npm/package.json
@@ -9,7 +9,7 @@
},
"dependencies": {
"@electron/get": "^2.0.0",
- "@types/node": "^20.9.0",
+ "@types/node": "^22.7.7",
"extract-zip": "^2.0.1"
},
"engines": {
diff --git a/package.json b/package.json
index 6b1f040c78..12b3f777d2 100644
--- a/package.json
+++ b/package.json
@@ -14,7 +14,7 @@
"@octokit/rest": "^20.0.2",
"@primer/octicons": "^10.0.0",
"@types/minimist": "^1.2.5",
- "@types/node": "^20.9.0",
+ "@types/node": "^22.7.7",
"@types/semver": "^7.5.8",
"@types/stream-json": "^1.7.7",
"@types/temp": "^0.9.4",
diff --git a/patches/chromium/build_allow_electron_to_use_exec_script.patch b/patches/chromium/build_allow_electron_to_use_exec_script.patch
index c8b4c3a439..ef798e6bf1 100644
--- a/patches/chromium/build_allow_electron_to_use_exec_script.patch
+++ b/patches/chromium/build_allow_electron_to_use_exec_script.patch
@@ -6,15 +6,34 @@ Subject: build: allow electron to use exec_script
This is similar to the //build usecase so we're OK adding ourselves here
diff --git a/.gn b/.gn
-index 44a11ec90ec9b67cf22b6d529c6843e6b6af12bc..783dd77dcdf92ec32cc6594b739eab9738f3e3ba 100644
+index 44a11ec90ec9b67cf22b6d529c6843e6b6af12bc..3e880eed02ca57db10d734d6a7566e0a977433a5 100644
--- a/.gn
+++ b/.gn
-@@ -172,4 +172,8 @@ exec_script_whitelist =
+@@ -172,4 +172,27 @@ exec_script_whitelist =
"//tools/grit/grit_rule.gni",
"//tools/gritsettings/BUILD.gn",
+
+ "//electron/BUILD.gn",
++ "//third_party/electron_node/deps/ada/unofficial.gni",
+ "//third_party/electron_node/deps/base64/BUILD.gn",
+ "//third_party/electron_node/deps/base64/unofficial.gni",
++ "//third_party/electron_node/node.gni",
++ "//third_party/electron_node/unofficial.gni",
++ "//third_party/electron_node/deps/brotli/unofficial.gni",
++ "//third_party/electron_node/deps/cares/unofficial.gni",
++ "//third_party/electron_node/deps/googletest/unofficial.gni",
++ "//third_party/electron_node/deps/histogram/unofficial.gni",
++ "//third_party/electron_node/deps/llhttp/unofficial.gni",
++ "//third_party/electron_node/deps/nbytes/unofficial.gni",
++ "//third_party/electron_node/deps/ncrypto/unofficial.gni",
++ "//third_party/electron_node/deps/nghttp2/unofficial.gni",
++ "//third_party/electron_node/deps/ngtcp2/unofficial.gni",
++ "//third_party/electron_node/deps/openssl/unofficial.gni",
++ "//third_party/electron_node/deps/simdutf/unofficial.gni",
++ "//third_party/electron_node/deps/simdjson/unofficial.gni",
++ "//third_party/electron_node/deps/sqlite/unofficial.gni",
++ "//third_party/electron_node/deps/uv/unofficial.gni",
++ "//third_party/electron_node/deps/uvwasi/unofficial.gni",
++ "//third_party/electron_node/src/inspector/unofficial.gni",
]
diff --git a/patches/config.json b/patches/config.json
index 8cf28d8d2b..8d297c0fd3 100644
--- a/patches/config.json
+++ b/patches/config.json
@@ -11,5 +11,6 @@
{ "patch_dir": "src/electron/patches/Mantle", "repo": "src/third_party/squirrel.mac/vendor/Mantle" },
{ "patch_dir": "src/electron/patches/ReactiveObjC", "repo": "src/third_party/squirrel.mac/vendor/ReactiveObjC" },
{ "patch_dir": "src/electron/patches/webrtc", "repo": "src/third_party/webrtc" },
- { "patch_dir": "src/electron/patches/reclient-configs", "repo": "src/third_party/engflow-reclient-configs" }
+ { "patch_dir": "src/electron/patches/reclient-configs", "repo": "src/third_party/engflow-reclient-configs" },
+ { "patch_dir": "src/electron/patches/sqlite", "repo": "src/third_party/sqlite/src" }
]
diff --git a/patches/node/.patches b/patches/node/.patches
index abdfda54fa..1394c2d7bc 100644
--- a/patches/node/.patches
+++ b/patches/node/.patches
@@ -21,37 +21,24 @@ enable_crashpad_linux_node_processes.patch
fix_lazyload_fs_in_esm_loaders_to_apply_asar_patches.patch
chore_expose_importmoduledynamically_and.patch
test_formally_mark_some_tests_as_flaky.patch
-fix_adapt_debugger_tests_for_upstream_v8_changes.patch
-chore_remove_--no-harmony-atomics_related_code.patch
-fix_account_for_createexternalizablestring_v8_global.patch
fix_do_not_resolve_electron_entrypoints.patch
ci_ensure_node_tests_set_electron_run_as_node.patch
fix_assert_module_in_the_renderer_process.patch
-fix_add_trusted_space_and_trusted_lo_space_to_the_v8_heap.patch
-win_process_avoid_assert_after_spawning_store_app_4152.patch
-chore_remove_use_of_deprecated_kmaxlength.patch
-src_update_default_v8_platform_to_override_functions_with_location.patch
fix_capture_embedder_exceptions_before_entering_v8.patch
-spec_add_iterator_to_global_intrinsics.patch
test_make_test-node-output-v8-warning_generic.patch
-test_match_wpt_streams_transferable_transform-stream-members_any_js.patch
fix_revert_src_lb_reducing_c_calls_of_esm_legacy_main_resolve.patch
-deprecate_vector_v8_local_in_v8.patch
fix_remove_deprecated_errno_constants.patch
build_enable_perfetto.patch
fix_add_source_location_for_v8_task_runner.patch
-cherry-pick_src_remove_calls_to_recently_deprecated_v8_apis.patch
-src_do_not_use_deprecated_v8_api.patch
-src_use_new_v8_api_to_define_stream_accessor.patch
src_remove_dependency_on_wrapper-descriptor-based_cppheap.patch
test_update_v8-stats_test_for_v8_12_6.patch
src_do_not_use_soon-to-be-deprecated_v8_api.patch
-fix_add_property_query_interceptors.patch
src_stop_using_deprecated_fields_of_fastapicallbackoptions.patch
-src_use_supported_api_to_get_stalled_tla_messages.patch
build_don_t_redefine_win32_lean_and_mean.patch
build_compile_with_c_20_support.patch
add_v8_taskpirority_to_foreground_task_runner_signature.patch
cli_remove_deprecated_v8_flag.patch
build_restore_clang_as_default_compiler_on_macos.patch
-esm_drop_support_for_import_assertions.patch
+fix_-wextra-semi_errors_in_nghttp2_helper_h.patch
+fix_remove_harmony-import-assertions_from_node_cc.patch
+win_almost_fix_race_detecting_esrch_in_uv_kill.patch
diff --git a/patches/node/build_add_gn_build_files.patch b/patches/node/build_add_gn_build_files.patch
index 1cb0332f0c..1fc6f58658 100644
--- a/patches/node/build_add_gn_build_files.patch
+++ b/patches/node/build_add_gn_build_files.patch
@@ -10,1268 +10,58 @@ however those files were cherry-picked from main branch and do not
really in 20/21. We have to wait until 22 is released to be able to
build with upstream GN files.
-diff --git a/BUILD.gn b/BUILD.gn
-index 1ed186b597eece7c34cb69c8e1e20870555a040d..e36168f0a051ca2fa2fc024aadcf5375b860105e 100644
---- a/BUILD.gn
-+++ b/BUILD.gn
-@@ -1,14 +1,406 @@
--##############################################################################
--# #
--# DO NOT EDIT THIS FILE! #
--# #
--##############################################################################
-+import("//v8/gni/v8.gni")
-+import("//electron/js2c_toolchain.gni")
-+import("electron_node.gni")
+diff --git a/deps/ncrypto/ncrypto.h b/deps/ncrypto/ncrypto.h
+index 60bfce3ea8999e8e145aaf8cd14f0fdf21ed9c54..661c996889d0a89c1c38658a0933fcf5e3cdc1b9 100644
+--- a/deps/ncrypto/ncrypto.h
++++ b/deps/ncrypto/ncrypto.h
+@@ -400,17 +400,21 @@ public:
+ UNABLE_TO_CHECK_GENERATOR = DH_UNABLE_TO_CHECK_GENERATOR,
+ NOT_SUITABLE_GENERATOR = DH_NOT_SUITABLE_GENERATOR,
+ Q_NOT_PRIME = DH_CHECK_Q_NOT_PRIME,
++#ifndef OPENSSL_IS_BORINGSSL
+ INVALID_Q = DH_CHECK_INVALID_Q_VALUE,
+ INVALID_J = DH_CHECK_INVALID_J_VALUE,
++#endif
+ CHECK_FAILED = 512,
+ };
+ CheckResult check();
--# This file is used by GN for building, which is NOT the build system used for
--# building official binaries.
--# Please modify the gyp files if you are making changes to build system.
-+declare_args() {
-+ # Enable the V8 inspector protocol for use with node.
-+ node_enable_inspector = true
-
--import("unofficial.gni")
-+ # Build node with SSL support.
-+ # The variable is called "openssl" for parity with node's GYP build.
-+ node_use_openssl = true
-
--node_gn_build("node") {
-+ # Use the specified path to system CA (PEM format) in addition to
-+ # the BoringSSL supplied CA store or compiled-in Mozilla CA copy.
-+ node_openssl_system_ca_path = ""
-+
-+ # Initialize v8 platform during node.js startup.
-+ # NB. this must be turned off in Electron, because Electron initializes the
-+ # v8 platform itself.
-+ node_use_v8_platform = false
-+
-+ # Build with DTrace support.
-+ node_use_dtrace = false
-+
-+ # Build with ETW support.
-+ node_use_etw = false
-+
-+ # Build JavaScript in lib/ with DCHECK macros.
-+ node_debug_lib = false
-+
-+ # Custom build tag.
-+ node_tag = ""
-+
-+ # V8 options to pass, see `node --v8-options` for examples
-+ node_v8_options = ""
-+
-+ # Provide a custom URL prefix for the `process.release` properties
-+ # `sourceUrl` and `headersUrl`. When compiling a release build, this will
-+ # default to https://nodejs.org/download/release/')
-+ node_release_urlbase = ""
-+
-+ # Allows downstream packagers (eg. Linux distributions) to build Electron against system shared libraries.
-+ use_system_cares = false
-+ use_system_nghttp2 = false
-+ use_system_llhttp = false
-+ use_system_histogram = false
-+}
-+
-+if (is_linux) {
-+ import("//build/config/linux/pkg_config.gni")
-+ if (use_system_cares) {
-+ pkg_config("cares") {
-+ packages = [ "libcares" ]
-+ }
-+ }
-+ if (use_system_nghttp2) {
-+ pkg_config("nghttp2") {
-+ packages = [ "libnghttp2" ]
-+ }
-+ }
-+}
-+
-+assert(!node_use_dtrace, "node_use_dtrace not supported in GN")
-+assert(!node_use_etw, "node_use_etw not supported in GN")
-+
-+assert(!node_enable_inspector || node_use_openssl,
-+ "node_enable_inspector requires node_use_openssl")
-+
-+config("node_internals") {
-+ defines = [ "NODE_WANT_INTERNALS=1" ]
-+}
-+
-+node_files = read_file("filenames.json", "json")
-+library_files = node_files.library_files
-+fs_files = node_files.fs_files
-+original_fs_files = []
-+foreach(file, fs_files) {
-+ original_fs_files += [string_replace(string_replace(string_replace(file, "internal/fs/", "internal/original-fs/"), "lib/fs.js", "lib/original-fs.js"), "lib/fs/", "lib/original-fs/")]
-+}
-+
-+copy("node_js2c_inputs") {
-+ sources = library_files
-+ outputs = [
-+ "$target_gen_dir/js2c_inputs/{{source_target_relative}}",
-+ ]
-+}
-+
-+action("node_js2c_original_fs") {
-+ script = "//electron/script/node/generate_original_fs.py"
-+ inputs = fs_files
-+ outputs = []
-+ foreach(file, fs_files + original_fs_files) {
-+ outputs += ["$target_gen_dir/js2c_inputs/$file"]
-+ }
-+
-+ args = [rebase_path("$target_gen_dir/js2c_inputs")] + fs_files
-+}
-+
-+action("node_js2c_exec") {
-+ deps = [
-+ "//electron:generate_config_gypi",
-+ ":node_js2c_original_fs",
-+ ":node_js2c_inputs",
-+ ":node_js2c($electron_js2c_toolchain)"
-+ ]
-+ config_gypi = [ "$root_gen_dir/config.gypi" ]
-+ inputs = library_files + get_target_outputs(":node_js2c_original_fs") + config_gypi
-+ outputs = [
-+ "$target_gen_dir/node_javascript.cc",
-+ ]
-+
-+ script = "//electron/build/run-in-dir.py"
-+ out_dir = get_label_info(":anything($electron_js2c_toolchain)", "root_out_dir")
-+ args = [ rebase_path("$target_gen_dir/js2c_inputs"), rebase_path("$out_dir/node_js2c") ] +
-+ rebase_path(outputs) + library_files + fs_files + original_fs_files + rebase_path(config_gypi)
-+}
-+
-+config("node_features") {
-+ defines = []
-+ if (node_enable_inspector) {
-+ defines += [ "HAVE_INSPECTOR=1" ]
-+ } else {
-+ defines += [ "HAVE_INSPECTOR=0" ]
-+ }
-+ if (node_use_openssl) {
-+ defines += [ "HAVE_OPENSSL=1" ]
-+ } else {
-+ defines += [ "HAVE_OPENSSL=0" ]
-+ }
-+ if (v8_enable_i18n_support) {
-+ defines += [ "NODE_HAVE_I18N_SUPPORT=1" ]
-+ } else {
-+ defines += [ "NODE_HAVE_I18N_SUPPORT=0" ]
-+ }
-+ if (node_use_v8_platform) {
-+ defines += [ "NODE_USE_V8_PLATFORM=1" ]
-+ } else {
-+ defines += [ "NODE_USE_V8_PLATFORM=0" ]
-+ }
-+}
-+
-+config("node_lib_config") {
-+ include_dirs = [ "src" ]
-+
-+ cflags = [
-+ "-Wno-shadow",
-+ # FIXME(deepak1556): include paths should be corrected,
-+ # refer https://docs.google.com/presentation/d/1oxNHaVjA9Gn_rTzX6HIpJHP7nXRua_0URXxxJ3oYRq0/edit#slide=id.g71ecd450e_2_702
-+ "-Wno-microsoft-include",
-+ ]
-+
-+ configs = [ ":node_features" ]
-+
-+ if (is_debug) {
-+ defines = [ "DEBUG" ]
-+ }
-+}
-+
-+config("node_internal_config") {
-+ visibility = [
-+ ":*",
-+ "src/inspector:*",
-+ ]
-+ defines = [
-+ "NODE_WANT_INTERNALS=1",
-+ "NODE_IMPLEMENTATION",
-+ ]
-+ if (node_module_version != "") {
-+ defines += [ "NODE_EMBEDDER_MODULE_VERSION=" + node_module_version ]
-+ }
-+ if (is_component_build) {
-+ defines += [
-+ "NODE_SHARED_MODE",
+ enum class CheckPublicKeyResult {
+ NONE,
++ #ifndef OPENSSL_IS_BORINGSSL
+ TOO_SMALL = DH_R_CHECK_PUBKEY_TOO_SMALL,
+ TOO_LARGE = DH_R_CHECK_PUBKEY_TOO_LARGE,
+ INVALID = DH_R_CHECK_PUBKEY_INVALID,
++ #endif
+ CHECK_FAILED = 512,
+ };
+ // Check to see if the given public key is suitable for this DH instance.
+diff --git a/deps/sqlite/unofficial.gni b/deps/sqlite/unofficial.gni
+index ebb3ffcd6d42b4c16b6865a91ccf4428cffe864b..00225afa1fb4205f1e02d9f185aeb97d642b3fd9 100644
+--- a/deps/sqlite/unofficial.gni
++++ b/deps/sqlite/unofficial.gni
+@@ -18,8 +18,14 @@ template("sqlite_gn_build") {
+ forward_variables_from(invoker, "*")
+ public_configs = [ ":sqlite_config" ]
+ sources = gypi_values.sqlite_sources
++ cflags_c = [
++ "-Wno-implicit-fallthrough",
++ "-Wno-unreachable-code-break",
++ "-Wno-unreachable-code-return",
++ "-Wno-unreachable-code",
+ ]
-+ }
-+
-+ if (target_cpu == "x86") {
-+ node_arch = "ia32"
-+ } else {
-+ node_arch = target_cpu
-+ }
-+ defines += [ "NODE_ARCH=\"$node_arch\"" ]
-+
-+ if (target_os == "win") {
-+ node_platform = "win32"
-+ } else if (target_os == "mac") {
-+ node_platform = "darwin"
-+ } else {
-+ node_platform = target_os
-+ }
-+ defines += [ "NODE_PLATFORM=\"$node_platform\"" ]
-+
-+ if (is_win) {
-+ defines += [
-+ "NOMINMAX",
-+ "_UNICODE=1",
-+ ]
-+ } else {
-+ defines += [ "__POSIX__" ]
-+ }
-+
-+ if (node_tag != "") {
-+ defines += [ "NODE_TAG=\"$node_tag\"" ]
-+ }
-+ if (node_v8_options != "") {
-+ defines += [ "NODE_V8_OPTIONS=\"$node_v8_options\"" ]
-+ }
-+ if (node_release_urlbase != "") {
-+ defines += [ "NODE_RELEASE_URLBASE=\"$node_release_urlbase\"" ]
-+ }
-+
-+ if (node_use_openssl) {
-+ defines += [
-+ "NODE_OPENSSL_SYSTEM_CERT_PATH=\"$node_openssl_system_ca_path\"",
-+ "EVP_CTRL_CCM_SET_TAG=EVP_CTRL_GCM_SET_TAG",
-+ ]
-+ }
-+}
-+
-+executable("overlapped-checker") {
-+ sources = []
-+ if (is_win) {
-+ sources += [ "test/overlapped-checker/main_win.c" ]
-+ } else {
-+ sources += [ "test/overlapped-checker/main_unix.c" ]
-+ }
-+}
-+
-+if (current_toolchain == electron_js2c_toolchain) {
-+ executable("node_js2c") {
-+ defines = []
-+ sources = [
-+ "tools/js2c.cc",
-+ "tools/executable_wrapper.h",
-+ "src/embedded_data.cc",
-+ "src/embedded_data.h",
-+ ]
-+ include_dirs = [ "tools", "src" ]
-+ deps = [
-+ "deps/simdutf($electron_js2c_toolchain)",
-+ "deps/uv($electron_js2c_toolchain)",
-+ "//v8"
-+ ]
-+
-+ if (!is_win) {
-+ defines += [ "NODE_JS2C_USE_STRING_LITERALS" ]
-+ }
-+ if (is_debug) {
-+ cflags_cc = [ "-g", "-O0" ]
-+ defines += [ "DEBUG" ]
-+ }
-+ }
-+}
-+
-+component("node_lib") {
-+ deps = [
-+ ":node_js2c_exec",
-+ "deps/googletest:gtest",
-+ "deps/ada",
-+ "deps/base64",
-+ "deps/simdutf",
-+ "deps/uvwasi",
-+ "//third_party/zlib",
-+ "//third_party/brotli:dec",
-+ "//third_party/brotli:enc",
-+ "//v8:v8_libplatform",
-+ ]
-+ if (use_system_cares) {
-+ configs += [ ":cares" ]
-+ } else {
-+ deps += [ "deps/cares" ]
-+ }
-+ if (use_system_nghttp2) {
-+ configs += [ ":nghttp2" ]
-+ } else {
-+ deps += [ "deps/nghttp2" ]
-+ }
-+ public_deps = [
-+ "deps/uv",
-+ "//electron:electron_js2c",
-+ "//v8",
-+ ]
-+ configs += [ ":node_internal_config" ]
-+ public_configs = [ ":node_lib_config" ]
-+ include_dirs = [
-+ "src",
-+ "deps/postject"
-+ ]
-+ libs = []
-+ if (use_system_llhttp) {
-+ libs += [ "llhttp" ]
-+ } else {
-+ deps += [ "deps/llhttp" ]
-+ }
-+ if (use_system_histogram) {
-+ libs += [ "hdr_histogram" ]
-+ include_dirs += [ "/usr/include/hdr" ]
-+ } else {
-+ deps += [ "deps/histogram" ]
-+ }
-+ frameworks = []
-+ cflags_cc = [
-+ "-Wno-deprecated-declarations",
-+ "-Wno-implicit-fallthrough",
-+ "-Wno-return-type",
-+ "-Wno-sometimes-uninitialized",
-+ "-Wno-string-plus-int",
-+ "-Wno-unused-function",
-+ "-Wno-unused-label",
-+ "-Wno-unused-private-field",
-+ "-Wno-unused-variable",
-+ ]
-+
-+ if (v8_enable_i18n_support) {
-+ deps += [ "//third_party/icu" ]
-+ }
-+
-+ sources = node_files.node_sources
-+ sources += [
-+ "$root_gen_dir/electron_natives.cc",
-+ "$target_gen_dir/node_javascript.cc",
-+ "src/node_snapshot_stub.cc",
-+ ]
-+
-+ if (is_win) {
-+ libs += [ "psapi.lib" ]
-+ }
-+ if (is_mac) {
-+ frameworks += [ "CoreFoundation.framework" ]
-+ }
-+
-+ if (node_enable_inspector) {
-+ sources += [
-+ "src/inspector_agent.cc",
-+ "src/inspector_agent.h",
-+ "src/inspector_io.cc",
-+ "src/inspector_io.h",
-+ "src/inspector_js_api.cc",
-+ "src/inspector_profiler.cc",
-+ "src/inspector_socket.cc",
-+ "src/inspector_socket.h",
-+ "src/inspector_socket_server.cc",
-+ "src/inspector_socket_server.h",
-+ ]
-+ deps += [ "src/inspector" ]
-+ }
-+
-+ if (node_use_openssl) {
-+ deps += [ "//third_party/boringssl" ]
-+ sources += [
-+ "src/crypto/crypto_aes.cc",
-+ "src/crypto/crypto_aes.h",
-+ "src/crypto/crypto_bio.cc",
-+ "src/crypto/crypto_bio.h",
-+ "src/crypto/crypto_cipher.cc",
-+ "src/crypto/crypto_cipher.h",
-+ "src/crypto/crypto_clienthello-inl.h",
-+ "src/crypto/crypto_clienthello.cc",
-+ "src/crypto/crypto_clienthello.h",
-+ "src/crypto/crypto_common.cc",
-+ "src/crypto/crypto_common.h",
-+ "src/crypto/crypto_context.cc",
-+ "src/crypto/crypto_context.h",
-+ "src/crypto/crypto_dh.cc",
-+ "src/crypto/crypto_dh.h",
-+ "src/crypto/crypto_dsa.cc",
-+ "src/crypto/crypto_dsa.h",
-+ "src/crypto/crypto_ec.cc",
-+ "src/crypto/crypto_ec.h",
-+ "src/crypto/crypto_groups.h",
-+ "src/crypto/crypto_hash.cc",
-+ "src/crypto/crypto_hash.h",
-+ "src/crypto/crypto_hkdf.cc",
-+ "src/crypto/crypto_hkdf.h",
-+ "src/crypto/crypto_hmac.cc",
-+ "src/crypto/crypto_hmac.h",
-+ "src/crypto/crypto_keygen.cc",
-+ "src/crypto/crypto_keygen.h",
-+ "src/crypto/crypto_keys.cc",
-+ "src/crypto/crypto_keys.h",
-+ "src/crypto/crypto_pbkdf2.cc",
-+ "src/crypto/crypto_pbkdf2.h",
-+ "src/crypto/crypto_random.cc",
-+ "src/crypto/crypto_random.h",
-+ "src/crypto/crypto_rsa.cc",
-+ "src/crypto/crypto_rsa.h",
-+ "src/crypto/crypto_scrypt.cc",
-+ "src/crypto/crypto_scrypt.h",
-+ "src/crypto/crypto_sig.cc",
-+ "src/crypto/crypto_sig.h",
-+ "src/crypto/crypto_spkac.cc",
-+ "src/crypto/crypto_spkac.h",
-+ "src/crypto/crypto_timing.cc",
-+ "src/crypto/crypto_timing.h",
-+ "src/crypto/crypto_tls.cc",
-+ "src/crypto/crypto_tls.h",
-+ "src/crypto/crypto_util.cc",
-+ "src/crypto/crypto_util.h",
-+ "src/crypto/crypto_x509.cc",
-+ "src/crypto/crypto_x509.h",
-+ "src/node_crypto.cc",
-+ "src/node_crypto.h",
-+ ]
-+ cflags_cc += [ "-Wno-sign-compare" ]
-+ }
- }
-diff --git a/deps/ada/BUILD.gn b/deps/ada/BUILD.gn
-index e92ac3a3beac143dced2efb05304ed8ba832b067..1ce69e9deba1a9b191e8d95f4c82e0ec1f7b50ca 100644
---- a/deps/ada/BUILD.gn
-+++ b/deps/ada/BUILD.gn
-@@ -1,14 +1,12 @@
--##############################################################################
--# #
--# DO NOT EDIT THIS FILE! #
--# #
--##############################################################################
-+import("//v8/gni/v8.gni")
-
--# This file is used by GN for building, which is NOT the build system used for
--# building official binaries.
--# Please modify the gyp files if you are making changes to build system.
-+config("ada_config") {
-+ include_dirs = [ "." ]
-+}
-
--import("unofficial.gni")
-+static_library("ada") {
-+ include_dirs = [ "." ]
-+ sources = [ "ada.cpp" ]
-
--ada_gn_build("ada") {
-+ public_configs = [ ":ada_config" ]
- }
-diff --git a/deps/base64/unofficial.gni b/deps/base64/unofficial.gni
-index 0e69d7383762f6b81c5b57698aa9d121d5a9c401..35bbeb37acc7ccb14b4b8a644ec3d4c76ca5c61c 100644
---- a/deps/base64/unofficial.gni
-+++ b/deps/base64/unofficial.gni
-@@ -12,6 +12,10 @@ template("base64_gn_build") {
- }
- }
-
-+ # FIXME(zcbenz): ASM on win/x86 compiles perfectly in upstream Node, figure
-+ # out why it does not work in Electron's build configs.
-+ support_x86_asm = current_cpu == "x64" || (current_cpu == "x86" && !is_win)
-+
- config("base64_internal_config") {
- include_dirs = [ "base64/lib" ]
- if (is_component_build) {
-@@ -19,7 +23,7 @@ template("base64_gn_build") {
- } else {
- defines = []
- }
-- if (current_cpu == "x86" || current_cpu == "x64") {
-+ if (support_x86_asm) {
- defines += [
- "HAVE_SSSE3=1",
- "HAVE_SSE41=1",
-@@ -69,7 +73,7 @@ template("base64_gn_build") {
- source_set("base64_ssse3") {
- configs += [ ":base64_internal_config" ]
- sources = [ "base64/lib/arch/ssse3/codec.c" ]
-- if (current_cpu == "x86" || current_cpu == "x64") {
-+ if (support_x86_asm) {
- if (is_clang || !is_win) {
- cflags_c = [ "-mssse3" ]
- }
-@@ -79,7 +83,7 @@ template("base64_gn_build") {
- source_set("base64_sse41") {
- configs += [ ":base64_internal_config" ]
- sources = [ "base64/lib/arch/sse41/codec.c" ]
-- if (current_cpu == "x86" || current_cpu == "x64") {
-+ if (support_x86_asm) {
- if (is_clang || !is_win) {
- cflags_c = [ "-msse4.1" ]
- }
-@@ -89,7 +93,7 @@ template("base64_gn_build") {
- source_set("base64_sse42") {
- configs += [ ":base64_internal_config" ]
- sources = [ "base64/lib/arch/sse42/codec.c" ]
-- if (current_cpu == "x86" || current_cpu == "x64") {
-+ if (support_x86_asm) {
- if (is_clang || !is_win) {
- cflags_c = [ "-msse4.2" ]
- }
-@@ -99,7 +103,7 @@ template("base64_gn_build") {
- source_set("base64_avx") {
- configs += [ ":base64_internal_config" ]
- sources = [ "base64/lib/arch/avx/codec.c" ]
-- if (current_cpu == "x86" || current_cpu == "x64") {
-+ if (support_x86_asm) {
- if (is_clang || !is_win) {
- cflags_c = [ "-mavx" ]
- } else if (is_win) {
-@@ -111,7 +115,7 @@ template("base64_gn_build") {
- source_set("base64_avx2") {
- configs += [ ":base64_internal_config" ]
- sources = [ "base64/lib/arch/avx2/codec.c" ]
-- if (current_cpu == "x86" || current_cpu == "x64") {
-+ if (support_x86_asm) {
- if (is_clang || !is_win) {
- cflags_c = [ "-mavx2" ]
- } else if (is_win) {
-@@ -123,7 +127,7 @@ template("base64_gn_build") {
- source_set("base64_avx512") {
- configs += [ ":base64_internal_config" ]
- sources = [ "base64/lib/arch/avx512/codec.c" ]
-- if (current_cpu == "x86" || current_cpu == "x64") {
-+ if (support_x86_asm) {
- if (is_clang || !is_win) {
- cflags_c = [
- "-mavx512vl",
-diff --git a/deps/cares/BUILD.gn b/deps/cares/BUILD.gn
-index ac19ac73ed1e24c61cb679f3851685b79cfc8b39..7f4885631a85a25692e8969991951be02e5d73f1 100644
---- a/deps/cares/BUILD.gn
-+++ b/deps/cares/BUILD.gn
-@@ -1,14 +1,175 @@
--##############################################################################
--# #
--# DO NOT EDIT THIS FILE! #
--# #
--##############################################################################
-+config("cares_config") {
-+ include_dirs = [ "include", "src/lib" ]
-+}
-+static_library("cares") {
-+ defines = [ "CARES_STATICLIB" ]
-+ include_dirs = [ "include" ]
-+ public_configs = [ ":cares_config" ]
-+
-+ libs = []
-+ cflags_c = [
-+ "-Wno-logical-not-parentheses",
-+ "-Wno-implicit-fallthrough",
-+ "-Wno-sign-compare",
-+ ]
-+
-+ sources = [
-+ "include/ares.h",
-+ "include/ares_dns.h",
-+ "include/ares_dns_record.h",
-+ "include/ares_nameser.h",
-+ "include/ares_version.h",
-+ "src/lib/ares__addrinfo2hostent.c",
-+ "src/lib/ares__addrinfo_localhost.c",
-+ "src/lib/ares__close_sockets.c",
-+ "src/lib/ares__hosts_file.c",
-+ "src/lib/ares__parse_into_addrinfo.c",
-+ "src/lib/ares__socket.c",
-+ "src/lib/ares__sortaddrinfo.c",
-+ "src/lib/ares_android.c",
-+ "src/lib/ares_android.h",
-+ "src/lib/ares_cancel.c",
-+ "src/lib/ares_cookie.c",
-+ "src/lib/ares_data.c",
-+ "src/lib/ares_data.h",
-+ "src/lib/ares_destroy.c",
-+ "src/lib/ares_free_hostent.c",
-+ "src/lib/ares_free_string.c",
-+ "src/lib/ares_freeaddrinfo.c",
-+ "src/lib/ares_getaddrinfo.c",
-+ "src/lib/ares_getenv.c",
-+ "src/lib/ares_getenv.h",
-+ "src/lib/ares_gethostbyaddr.c",
-+ "src/lib/ares_gethostbyname.c",
-+ "src/lib/ares_getnameinfo.c",
-+ "src/lib/ares_inet_net_pton.h",
-+ "src/lib/ares_init.c",
-+ "src/lib/ares_ipv6.h",
-+ "src/lib/ares_library_init.c",
-+ "src/lib/ares_metrics.c",
-+ "src/lib/ares_options.c",
-+ "src/lib/ares_platform.c",
-+ "src/lib/ares_platform.h",
-+ "src/lib/ares_private.h",
-+ "src/lib/ares_process.c",
-+ "src/lib/ares_qcache.c",
-+ "src/lib/ares_query.c",
-+ "src/lib/ares_search.c",
-+ "src/lib/ares_send.c",
-+ "src/lib/ares_setup.h",
-+ "src/lib/ares_strerror.c",
-+ "src/lib/ares_sysconfig.c",
-+ "src/lib/ares_sysconfig_files.c",
-+ "src/lib/ares_timeout.c",
-+ "src/lib/ares_update_servers.c",
-+ "src/lib/ares_version.c",
-+ "src/lib/dsa/ares__array.c",
-+ "src/lib/dsa/ares__array.h",
-+ "src/lib/dsa/ares__htable.c",
-+ "src/lib/dsa/ares__htable.h",
-+ "src/lib/dsa/ares__htable_asvp.c",
-+ "src/lib/dsa/ares__htable_asvp.h",
-+ "src/lib/dsa/ares__htable_strvp.c",
-+ "src/lib/dsa/ares__htable_strvp.h",
-+ "src/lib/dsa/ares__htable_szvp.c",
-+ "src/lib/dsa/ares__htable_szvp.h",
-+ "src/lib/dsa/ares__htable_vpvp.c",
-+ "src/lib/dsa/ares__htable_vpvp.h",
-+ "src/lib/dsa/ares__llist.c",
-+ "src/lib/dsa/ares__llist.h",
-+ "src/lib/dsa/ares__slist.c",
-+ "src/lib/dsa/ares__slist.h",
-+ "src/lib/event/ares_event.h",
-+ "src/lib/event/ares_event_configchg.c",
-+ "src/lib/event/ares_event_epoll.c",
-+ "src/lib/event/ares_event_kqueue.c",
-+ "src/lib/event/ares_event_poll.c",
-+ "src/lib/event/ares_event_select.c",
-+ "src/lib/event/ares_event_thread.c",
-+ "src/lib/event/ares_event_wake_pipe.c",
-+ "src/lib/event/ares_event_win32.c",
-+ "src/lib/event/ares_event_win32.h",
-+ "src/lib/inet_net_pton.c",
-+ "src/lib/inet_ntop.c",
-+ "src/lib/legacy/ares_create_query.c",
-+ "src/lib/legacy/ares_expand_name.c",
-+ "src/lib/legacy/ares_expand_string.c",
-+ "src/lib/legacy/ares_fds.c",
-+ "src/lib/legacy/ares_getsock.c",
-+ "src/lib/legacy/ares_parse_a_reply.c",
-+ "src/lib/legacy/ares_parse_aaaa_reply.c",
-+ "src/lib/legacy/ares_parse_caa_reply.c",
-+ "src/lib/legacy/ares_parse_mx_reply.c",
-+ "src/lib/legacy/ares_parse_naptr_reply.c",
-+ "src/lib/legacy/ares_parse_ns_reply.c",
-+ "src/lib/legacy/ares_parse_ptr_reply.c",
-+ "src/lib/legacy/ares_parse_soa_reply.c",
-+ "src/lib/legacy/ares_parse_srv_reply.c",
-+ "src/lib/legacy/ares_parse_txt_reply.c",
-+ "src/lib/legacy/ares_parse_uri_reply.c",
-+ "src/lib/record/ares_dns_mapping.c",
-+ "src/lib/record/ares_dns_multistring.c",
-+ "src/lib/record/ares_dns_multistring.h",
-+ "src/lib/record/ares_dns_name.c",
-+ "src/lib/record/ares_dns_parse.c",
-+ "src/lib/record/ares_dns_private.h",
-+ "src/lib/record/ares_dns_record.c",
-+ "src/lib/record/ares_dns_write.c",
-+ "src/lib/str/ares__buf.c",
-+ "src/lib/str/ares__buf.h",
-+ "src/lib/str/ares_str.c",
-+ "src/lib/str/ares_str.h",
-+ "src/lib/str/ares_strcasecmp.c",
-+ "src/lib/str/ares_strcasecmp.h",
-+ "src/lib/str/ares_strsplit.c",
-+ "src/lib/str/ares_strsplit.h",
-+ "src/lib/util/ares__iface_ips.c",
-+ "src/lib/util/ares__iface_ips.h",
-+ "src/lib/util/ares__threads.c",
-+ "src/lib/util/ares__threads.h",
-+ "src/lib/util/ares__timeval.c",
-+ "src/lib/util/ares_math.c",
-+ "src/lib/util/ares_rand.c",
-+ "src/tools/ares_getopt.c",
-+ "src/tools/ares_getopt.h",
-+ ]
-+
-+ if (!is_win) {
-+ defines += [
-+ "_DARWIN_USE_64_BIT_INODE=1",
-+ "_LARGEFILE_SOURCE",
-+ "_FILE_OFFSET_BITS=64",
-+ "_GNU_SOURCE",
-+ ]
-+ }
-
--# This file is used by GN for building, which is NOT the build system used for
--# building official binaries.
--# Please modify the gyp files if you are making changes to build system.
-+ if (is_win) {
-+ defines += [ "CARES_PULL_WS2TCPIP_H=1" ]
-+ include_dirs += [ "config/win32" ]
-+ sources += [
-+ "src/lib/ares_sysconfig_win.c",
-+ "src/lib/config-win32.h",
-+ "src/lib/windows_port.c",
-+ ]
-+ libs += [
-+ "ws2_32.lib",
-+ "iphlpapi.lib",
-+ ]
-+ } else {
-+ defines += [ "HAVE_CONFIG_H" ]
-+ }
-
--import("unofficial.gni")
-+ if (is_linux) {
-+ include_dirs += [ "config/linux" ]
-+ sources += [ "config/linux/ares_config.h" ]
-+ }
-
--cares_gn_build("cares") {
-+ if (is_mac) {
-+ include_dirs += [ "config/darwin" ]
-+ sources += [
-+ "config/darwin/ares_config.h",
-+ "src/lib/ares_sysconfig_mac.c",
-+ "src/lib/thirdparty/apple/dnsinfo.h",
-+ ]
-+ }
- }
-diff --git a/deps/googletest/BUILD.gn b/deps/googletest/BUILD.gn
-index de13f3f653b5d53610f4611001c10dce332293c2..0daf8c006cef89e76d7eccec3e924bd2718021c9 100644
---- a/deps/googletest/BUILD.gn
-+++ b/deps/googletest/BUILD.gn
-@@ -1,14 +1,64 @@
--##############################################################################
--# #
--# DO NOT EDIT THIS FILE! #
--# #
--##############################################################################
-+config("gtest_config") {
-+ include_dirs = [ "include" ]
-+ defines = [ "UNIT_TEST" ]
-+}
-+
-+static_library("gtest") {
-+ include_dirs = [
-+ "include",
-+ "." # src
-+ ]
-+
-+ public_configs = [ ":gtest_config" ]
-
--# This file is used by GN for building, which is NOT the build system used for
--# building official binaries.
--# Please modify the gyp files if you are making changes to build system.
-+ cflags_cc = [
-+ "-Wno-c++98-compat-extra-semi",
-+ "-Wno-unused-const-variable",
-+ "-Wno-unreachable-code-return",
-+ ]
-
--import("unofficial.gni")
-+ defines = [
-+ "GTEST_HAS_POSIX_RE=0",
-+ "GTEST_LANG_CXX11=1",
-+ ]
-+
-+ sources = [
-+ "include/gtest/gtest_pred_impl.h",
-+ "include/gtest/gtest_prod.h",
-+ "include/gtest/gtest-death-test.h",
-+ "include/gtest/gtest-matchers.h",
-+ "include/gtest/gtest-message.h",
-+ "include/gtest/gtest-param-test.h",
-+ "include/gtest/gtest-printers.h",
-+ "include/gtest/gtest-spi.h",
-+ "include/gtest/gtest-test-part.h",
-+ "include/gtest/gtest-typed-test.h",
-+ "include/gtest/gtest.h",
-+ "include/gtest/internal/gtest-death-test-internal.h",
-+ "include/gtest/internal/gtest-filepath.h",
-+ "include/gtest/internal/gtest-internal.h",
-+ "include/gtest/internal/gtest-param-util.h",
-+ "include/gtest/internal/gtest-port-arch.h",
-+ "include/gtest/internal/gtest-port.h",
-+ "include/gtest/internal/gtest-string.h",
-+ "include/gtest/internal/gtest-type-util.h",
-+ "include/gtest/internal/custom/gtest-port.h",
-+ "include/gtest/internal/custom/gtest-printers.h",
-+ "include/gtest/internal/custom/gtest.h",
-+ "src/gtest-all.cc",
-+ "src/gtest-death-test.cc",
-+ "src/gtest-filepath.cc",
-+ "src/gtest-internal-inl.h",
-+ "src/gtest-matchers.cc",
-+ "src/gtest-port.cc",
-+ "src/gtest-printers.cc",
-+ "src/gtest-test-part.cc",
-+ "src/gtest-typed-test.cc",
-+ "src/gtest.cc",
-+ ]
-+}
-
--googletest_gn_build("googletest") {
-+static_library("gtest_main") {
-+ deps = [ ":gtest" ]
-+ sources = [ "src/gtest_main.cc" ]
- }
-diff --git a/deps/histogram/BUILD.gn b/deps/histogram/BUILD.gn
-index e2f3ee37137a6b7d45cbe79f8b9ba7f693ffc4d3..85467b372f01cf602af45fa2f0d599acabfc2310 100644
---- a/deps/histogram/BUILD.gn
-+++ b/deps/histogram/BUILD.gn
-@@ -1,14 +1,19 @@
--##############################################################################
--# #
--# DO NOT EDIT THIS FILE! #
--# #
--##############################################################################
-+config("histogram_config") {
-+ include_dirs = [ "include" ]
-
--# This file is used by GN for building, which is NOT the build system used for
--# building official binaries.
--# Please modify the gyp files if you are making changes to build system.
-+ cflags = [
-+ "-Wno-implicit-function-declaration",
-+ "-Wno-incompatible-pointer-types",
-+ "-Wno-unused-function",
-+ "-Wno-atomic-alignment",
-+ ]
-+}
-
--import("unofficial.gni")
-+static_library("histogram") {
-+ public_configs = [ ":histogram_config" ]
-
--histogram_gn_build("histogram") {
-+ sources = [
-+ "src/hdr_histogram.c",
-+ "src/hdr_histogram.h",
-+ ]
- }
-diff --git a/deps/llhttp/BUILD.gn b/deps/llhttp/BUILD.gn
-index 64a2a4799d5530276f46aa1faa63ece063390ada..fb000f8ee7647c375bc190d1729d67bb7770d109 100644
---- a/deps/llhttp/BUILD.gn
-+++ b/deps/llhttp/BUILD.gn
-@@ -1,14 +1,15 @@
--##############################################################################
--# #
--# DO NOT EDIT THIS FILE! #
--# #
--##############################################################################
--
--# This file is used by GN for building, which is NOT the build system used for
--# building official binaries.
--# Please modify the gyp files if you are making changes to build system.
--
--import("unofficial.gni")
-+config("llhttp_config") {
-+ include_dirs = [ "include" ]
-+ cflags = [ "-Wno-unreachable-code" ]
-+}
-
--llhttp_gn_build("llhttp") {
-+static_library("llhttp") {
-+ include_dirs = [ "include" ]
-+ public_configs = [ ":llhttp_config" ]
-+ cflags_c = [ "-Wno-implicit-fallthrough" ]
-+ sources = [
-+ "src/api.c",
-+ "src/http.c",
-+ "src/llhttp.c",
-+ ]
- }
-diff --git a/deps/nghttp2/BUILD.gn b/deps/nghttp2/BUILD.gn
-index 274352b0e2449f8db49d9a49c6b92a69f97e8363..f04c7ca24af6cdbe8d739bcd55172110963888e9 100644
---- a/deps/nghttp2/BUILD.gn
-+++ b/deps/nghttp2/BUILD.gn
-@@ -1,14 +1,51 @@
--##############################################################################
--# #
--# DO NOT EDIT THIS FILE! #
--# #
--##############################################################################
--
--# This file is used by GN for building, which is NOT the build system used for
--# building official binaries.
--# Please modify the gyp files if you are making changes to build system.
-+config("nghttp2_config") {
-+ defines = [ "NGHTTP2_STATICLIB" ]
-+ include_dirs = [ "lib/includes" ]
-+}
-+static_library("nghttp2") {
-+ public_configs = [ ":nghttp2_config" ]
-+ defines = [
-+ "_U_",
-+ "BUILDING_NGHTTP2",
-+ "NGHTTP2_STATICLIB",
-+ "HAVE_CONFIG_H",
-+ ]
-+ include_dirs = [ "lib/includes" ]
-
--import("unofficial.gni")
-+ cflags_c = [
-+ "-Wno-implicit-function-declaration",
-+ "-Wno-implicit-fallthrough",
-+ "-Wno-string-plus-int",
-+ "-Wno-unreachable-code-return",
-+ "-Wno-unused-but-set-variable",
-+ ]
-
--nghttp2_gn_build("nghttp2") {
-+ sources = [
-+ "lib/nghttp2_buf.c",
-+ "lib/nghttp2_callbacks.c",
-+ "lib/nghttp2_debug.c",
-+ "lib/nghttp2_extpri.c",
-+ "lib/nghttp2_frame.c",
-+ "lib/nghttp2_hd.c",
-+ "lib/nghttp2_hd_huffman.c",
-+ "lib/nghttp2_hd_huffman_data.c",
-+ "lib/nghttp2_helper.c",
-+ "lib/nghttp2_http.c",
-+ "lib/nghttp2_map.c",
-+ "lib/nghttp2_mem.c",
-+ "lib/nghttp2_alpn.c",
-+ "lib/nghttp2_option.c",
-+ "lib/nghttp2_outbound_item.c",
-+ "lib/nghttp2_pq.c",
-+ "lib/nghttp2_priority_spec.c",
-+ "lib/nghttp2_queue.c",
-+ "lib/nghttp2_ratelim.c",
-+ "lib/nghttp2_rcbuf.c",
-+ "lib/nghttp2_session.c",
-+ "lib/nghttp2_stream.c",
-+ "lib/nghttp2_submit.c",
-+ "lib/nghttp2_time.c",
-+ "lib/nghttp2_version.c",
-+ "lib/sfparse.c",
-+ ]
- }
-diff --git a/deps/simdjson/BUILD.gn b/deps/simdjson/BUILD.gn
-index d0580ccf354d2000fb0075fd3bb4579f93477927..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 100644
---- a/deps/simdjson/BUILD.gn
-+++ b/deps/simdjson/BUILD.gn
-@@ -1,14 +0,0 @@
--##############################################################################
--# #
--# DO NOT EDIT THIS FILE! #
--# #
--##############################################################################
--
--# This file is used by GN for building, which is NOT the build system used for
--# building official binaries.
--# Please modify the gyp files if you are making changes to build system.
--
--import("unofficial.gni")
--
--simdjson_gn_build("simdjson") {
--}
-diff --git a/deps/simdutf/BUILD.gn b/deps/simdutf/BUILD.gn
-index 119d49456911e99944294bd00b3f182a8f0e35b5..ce38c3633a228306622a7237067393d25332c59c 100644
---- a/deps/simdutf/BUILD.gn
-+++ b/deps/simdutf/BUILD.gn
-@@ -1,14 +1,21 @@
--##############################################################################
--# #
--# DO NOT EDIT THIS FILE! #
--# #
--##############################################################################
-+config("simdutf_config") {
-+ include_dirs = [ "." ]
-+}
-
--# This file is used by GN for building, which is NOT the build system used for
--# building official binaries.
--# Please modify the gyp files if you are making changes to build system.
-+static_library("simdutf") {
-+ include_dirs = [ "." ]
-+ sources = [
-+ "simdutf.cpp",
-+ ]
-
--import("unofficial.gni")
-+ public_configs = [ ":simdutf_config" ]
-
--simdutf_gn_build("simdutf") {
-+ cflags_cc = [
-+ "-Wno-ambiguous-reversed-operator",
-+ "-Wno-c++98-compat-extra-semi",
-+ "-Wno-unreachable-code",
-+ "-Wno-unreachable-code-break",
-+ "-Wno-unused-const-variable",
-+ "-Wno-unused-function",
-+ ]
- }
-diff --git a/deps/uv/BUILD.gn b/deps/uv/BUILD.gn
-index 8e6ac27048b5965e20f35c7a63e469beb6fa5970..7518168141db7958550c7f5dc1ed17ccdbbe4a60 100644
---- a/deps/uv/BUILD.gn
-+++ b/deps/uv/BUILD.gn
-@@ -1,14 +1,194 @@
--##############################################################################
--# #
--# DO NOT EDIT THIS FILE! #
--# #
--##############################################################################
-+config("libuv_config") {
-+ include_dirs = [ "include" ]
-
--# This file is used by GN for building, which is NOT the build system used for
--# building official binaries.
--# Please modify the gyp files if you are making changes to build system.
-+ defines = []
-
--import("unofficial.gni")
-+ if (is_linux) {
-+ defines += [ "_POSIX_C_SOURCE=200112" ]
-+ }
-+ if (!is_win) {
-+ defines += [
-+ "_LARGEFILE_SOURCE",
-+ "_FILE_OFFSET_BITS=64",
-+ ]
-+ }
-+ if (is_mac) {
-+ defines += [ "_DARWIN_USE_64_BIT_INODE=1" ]
-+ }
-+}
-+
-+static_library("uv") {
-+ include_dirs = [
-+ "include",
-+ "src",
-+ ]
-+
-+ public_configs = [ ":libuv_config" ]
-+
-+ ldflags = []
-+
-+ defines = []
-+
-+ # This only has an effect on Windows, where it will cause libuv's symbols to be exported in node.lib
-+ defines += [ "BUILDING_UV_SHARED=1" ]
-+
-+ cflags_c = [
-+ "-Wno-incompatible-pointer-types",
-+ "-Wno-bitwise-op-parentheses",
-+ "-Wno-implicit-fallthrough",
-+ "-Wno-implicit-function-declaration",
-+ "-Wno-missing-braces",
-+ "-Wno-sign-compare",
-+ "-Wno-sometimes-uninitialized",
-+ "-Wno-string-conversion",
-+ "-Wno-switch",
-+ "-Wno-unused-function",
-+ "-Wno-unused-result",
-+ "-Wno-unused-variable",
-+ "-Wno-unreachable-code",
-+ "-Wno-unreachable-code-return",
-+ "-Wno-unused-but-set-variable",
-+ "-Wno-shadow",
-+ ]
-+
-+ libs = []
-+
-+ sources = [
-+ "include/uv.h",
-+ "include/uv/tree.h",
-+ "include/uv/errno.h",
-+ "include/uv/threadpool.h",
-+ "include/uv/version.h",
-+ "src/fs-poll.c",
-+ "src/heap-inl.h",
-+ "src/idna.c",
-+ "src/idna.h",
-+ "src/inet.c",
-+ "src/queue.h",
-+ "src/random.c",
-+ "src/strscpy.c",
-+ "src/strscpy.h",
-+ "src/strtok.c",
-+ "src/strtok.h",
-+ "src/thread-common.c",
-+ "src/threadpool.c",
-+ "src/timer.c",
-+ "src/uv-data-getter-setters.c",
-+ "src/uv-common.c",
-+ "src/uv-common.h",
-+ "src/version.c",
-+ ]
-+
-+ if (is_win) {
-+ defines += [ "_GNU_SOURCE" ]
-+ sources += [
-+ "include/uv/win.h",
-+ "src/win/async.c",
-+ "src/win/atomicops-inl.h",
-+ "src/win/core.c",
-+ "src/win/detect-wakeup.c",
-+ "src/win/dl.c",
-+ "src/win/error.c",
-+ "src/win/fs.c",
-+ "src/win/fs-event.c",
-+ "src/win/getaddrinfo.c",
-+ "src/win/getnameinfo.c",
-+ "src/win/handle.c",
-+ "src/win/handle-inl.h",
-+ "src/win/internal.h",
-+ "src/win/loop-watcher.c",
-+ "src/win/pipe.c",
-+ "src/win/thread.c",
-+ "src/win/poll.c",
-+ "src/win/process.c",
-+ "src/win/process-stdio.c",
-+ "src/win/req-inl.h",
-+ "src/win/signal.c",
-+ "src/win/snprintf.c",
-+ "src/win/stream.c",
-+ "src/win/stream-inl.h",
-+ "src/win/tcp.c",
-+ "src/win/tty.c",
-+ "src/win/udp.c",
-+ "src/win/util.c",
-+ "src/win/winapi.c",
-+ "src/win/winapi.h",
-+ "src/win/winsock.c",
-+ "src/win/winsock.h",
-+ ]
-
--uv_gn_build("uv") {
-+ libs += [
-+ "advapi32.lib",
-+ "iphlpapi.lib",
-+ "psapi.lib",
-+ "shell32.lib",
-+ "user32.lib",
-+ "userenv.lib",
-+ "ws2_32.lib",
-+ ]
-+ } else {
-+ sources += [
-+ "include/uv/unix.h",
-+ "include/uv/linux.h",
-+ "include/uv/sunos.h",
-+ "include/uv/darwin.h",
-+ "include/uv/bsd.h",
-+ "include/uv/aix.h",
-+ "src/unix/async.c",
-+ "src/unix/core.c",
-+ "src/unix/dl.c",
-+ "src/unix/fs.c",
-+ "src/unix/getaddrinfo.c",
-+ "src/unix/getnameinfo.c",
-+ "src/unix/internal.h",
-+ "src/unix/loop.c",
-+ "src/unix/loop-watcher.c",
-+ "src/unix/pipe.c",
-+ "src/unix/poll.c",
-+ "src/unix/process.c",
-+ "src/unix/random-devurandom.c",
-+ "src/unix/signal.c",
-+ "src/unix/stream.c",
-+ "src/unix/tcp.c",
-+ "src/unix/thread.c",
-+ "src/unix/tty.c",
-+ "src/unix/udp.c",
-+ ]
-+ libs += [ "m" ]
-+ ldflags += [ "-pthread" ]
-+ }
-+ if (is_mac || is_linux) {
-+ sources += [ "src/unix/proctitle.c" ]
-+ }
-+ if (is_mac) {
-+ sources += [
-+ "src/unix/darwin-proctitle.c",
-+ "src/unix/darwin.c",
-+ "src/unix/fsevents.c",
-+ "src/unix/random-getentropy.c",
-+ ]
-+ defines += [
-+ "_DARWIN_USE_64_BIT_INODE=1",
-+ "_DARWIN_UNLIMITED_SELECT=1",
-+ ]
-+ }
-+ if (is_linux) {
-+ defines += [ "_GNU_SOURCE" ]
-+ sources += [
-+ "src/unix/linux.c",
-+ "src/unix/procfs-exepath.c",
-+ "src/unix/random-getrandom.c",
-+ "src/unix/random-sysctl-linux.c",
-+ ]
-+ libs += [
-+ "dl",
-+ "rt",
-+ ]
-+ }
-+ if (is_mac) { # is_bsd
-+ sources += [
-+ "src/unix/bsd-ifaddrs.c",
-+ "src/unix/kqueue.c",
-+ ]
-+ }
- }
-diff --git a/deps/uvwasi/BUILD.gn b/deps/uvwasi/BUILD.gn
-index 4f8fb081df805a786e523e5f0ffbb0096fdeca99..d9fcf8dc972b1caa2b7a130b1144c685316035cd 100644
---- a/deps/uvwasi/BUILD.gn
-+++ b/deps/uvwasi/BUILD.gn
-@@ -1,14 +1,39 @@
--##############################################################################
--# #
--# DO NOT EDIT THIS FILE! #
--# #
--##############################################################################
-+config("uvwasi_config") {
-+ include_dirs = [ "include" ]
-+}
-+
-+static_library("uvwasi") {
-+ include_dirs = [
-+ "include",
-+ "src",
-+ ]
-+
-+ defines = []
-+ if (is_linux) {
-+ defines += [
-+ "_GNU_SOURCE",
-+ "_POSIX_C_SOURCE=200112"
-+ ]
-+ }
-+
-+ deps = [ "../../deps/uv" ]
-
--# This file is used by GN for building, which is NOT the build system used for
--# building official binaries.
--# Please modify the gyp files if you are making changes to build system.
-+ public_configs = [ ":uvwasi_config" ]
-
--import("unofficial.gni")
-+ cflags_c = []
-+ if (!is_win) {
-+ cflags_c += [ "-fvisibility=hidden" ]
-+ }
-
--uvwasi_gn_build("uvwasi") {
-+ sources = [
-+ "src/clocks.c",
-+ "src/fd_table.c",
-+ "src/path_resolver.c",
-+ "src/poll_oneoff.c",
-+ "src/sync_helpers.c",
-+ "src/uv_mapping.c",
-+ "src/uvwasi.c",
-+ "src/wasi_rights.c",
-+ "src/wasi_serdes.c"
-+ ]
- }
-diff --git a/electron_node.gni b/electron_node.gni
-new file mode 100644
-index 0000000000000000000000000000000000000000..af9cbada10203b387fb9732b346583b1c4349223
---- /dev/null
-+++ b/electron_node.gni
-@@ -0,0 +1,4 @@
-+declare_args() {
-+ # Allows embedders to override the NODE_MODULE_VERSION define
-+ node_module_version = ""
-+}
+ if (is_win) {
+- cflags_c = [
++ cflags_c += [
+ "-Wno-sign-compare",
+ "-Wno-unused-but-set-variable",
+ "-Wno-unused-function",
diff --git a/filenames.json b/filenames.json
new file mode 100644
-index 0000000000000000000000000000000000000000..889a487e24721a8ecfef91f5a655892a607bb12f
+index 0000000000000000000000000000000000000000..5af3886d8d3d74d31249a4d79030a8373b8dad52
--- /dev/null
+++ b/filenames.json
-@@ -0,0 +1,741 @@
+@@ -0,0 +1,756 @@
+// This file is automatically generated by generate_gn_filenames_json.py
+// DO NOT EDIT
+{
@@ -1279,6 +69,7 @@ index 0000000000000000000000000000000000000000..889a487e24721a8ecfef91f5a655892a
+ "lib/internal/fs/cp/cp-sync.js",
+ "lib/internal/fs/cp/cp.js",
+ "lib/internal/fs/dir.js",
++ "lib/internal/fs/glob.js",
+ "lib/internal/fs/promises.js",
+ "lib/internal/fs/read/context.js",
+ "lib/internal/fs/recursive_watch.js",
@@ -1481,7 +272,10 @@ index 0000000000000000000000000000000000000000..889a487e24721a8ecfef91f5a655892a
+ "lib/internal/assert/assertion_error.js",
+ "lib/internal/assert/calltracker.js",
+ "lib/internal/assert/utils.js",
++ "lib/internal/async_context_frame.js",
+ "lib/internal/async_hooks.js",
++ "lib/internal/async_local_storage/async_context_frame.js",
++ "lib/internal/async_local_storage/async_hooks.js",
+ "lib/internal/blob.js",
+ "lib/internal/blocklist.js",
+ "lib/internal/bootstrap/node.js",
@@ -1527,6 +321,7 @@ index 0000000000000000000000000000000000000000..889a487e24721a8ecfef91f5a655892a
+ "lib/internal/crypto/webcrypto.js",
+ "lib/internal/crypto/webidl.js",
+ "lib/internal/crypto/x509.js",
++ "lib/internal/data_url.js",
+ "lib/internal/debugger/inspect.js",
+ "lib/internal/debugger/inspect_client.js",
+ "lib/internal/debugger/inspect_repl.js",
@@ -1582,7 +377,6 @@ index 0000000000000000000000000000000000000000..889a487e24721a8ecfef91f5a655892a
+ "lib/internal/modules/esm/loader.js",
+ "lib/internal/modules/esm/module_job.js",
+ "lib/internal/modules/esm/module_map.js",
-+ "lib/internal/modules/esm/package_config.js",
+ "lib/internal/modules/esm/resolve.js",
+ "lib/internal/modules/esm/shared_constants.js",
+ "lib/internal/modules/esm/translators.js",
@@ -1607,13 +401,11 @@ index 0000000000000000000000000000000000000000..889a487e24721a8ecfef91f5a655892a
+ "lib/internal/perf/timerify.js",
+ "lib/internal/perf/usertiming.js",
+ "lib/internal/perf/utils.js",
-+ "lib/internal/policy/manifest.js",
-+ "lib/internal/policy/sri.js",
+ "lib/internal/priority_queue.js",
+ "lib/internal/process/execution.js",
++ "lib/internal/process/finalization.js",
+ "lib/internal/process/per_thread.js",
+ "lib/internal/process/permission.js",
-+ "lib/internal/process/policy.js",
+ "lib/internal/process/pre_execution.js",
+ "lib/internal/process/promises.js",
+ "lib/internal/process/report.js",
@@ -1637,6 +429,7 @@ index 0000000000000000000000000000000000000000..889a487e24721a8ecfef91f5a655892a
+ "lib/internal/source_map/prepare_stack_trace.js",
+ "lib/internal/source_map/source_map.js",
+ "lib/internal/source_map/source_map_cache.js",
++ "lib/internal/source_map/source_map_cache_map.js",
+ "lib/internal/stream_base_commons.js",
+ "lib/internal/streams/add-abort-signal.js",
+ "lib/internal/streams/compose.js",
@@ -1671,6 +464,7 @@ index 0000000000000000000000000000000000000000..889a487e24721a8ecfef91f5a655892a
+ "lib/internal/test_runner/reporter/utils.js",
+ "lib/internal/test_runner/reporter/v8-serializer.js",
+ "lib/internal/test_runner/runner.js",
++ "lib/internal/test_runner/snapshot.js",
+ "lib/internal/test_runner/test.js",
+ "lib/internal/test_runner/tests_stream.js",
+ "lib/internal/test_runner/utils.js",
@@ -1684,10 +478,8 @@ index 0000000000000000000000000000000000000000..889a487e24721a8ecfef91f5a655892a
+ "lib/internal/util/colors.js",
+ "lib/internal/util/comparisons.js",
+ "lib/internal/util/debuglog.js",
-+ "lib/internal/util/embedding.js",
+ "lib/internal/util/inspect.js",
+ "lib/internal/util/inspector.js",
-+ "lib/internal/util/iterable_weak_map.js",
+ "lib/internal/util/parse_args/parse_args.js",
+ "lib/internal/util/parse_args/utils.js",
+ "lib/internal/util/types.js",
@@ -1701,6 +493,7 @@ index 0000000000000000000000000000000000000000..889a487e24721a8ecfef91f5a655892a
+ "lib/internal/watch_mode/files_watcher.js",
+ "lib/internal/watchdog.js",
+ "lib/internal/webidl.js",
++ "lib/internal/webstorage.js",
+ "lib/internal/webstreams/adapters.js",
+ "lib/internal/webstreams/compression.js",
+ "lib/internal/webstreams/encoding.js",
@@ -1713,6 +506,7 @@ index 0000000000000000000000000000000000000000..889a487e24721a8ecfef91f5a655892a
+ "lib/internal/worker.js",
+ "lib/internal/worker/io.js",
+ "lib/internal/worker/js_transferable.js",
++ "lib/internal/worker/messaging.js",
+ "lib/module.js",
+ "lib/net.js",
+ "lib/os.js",
@@ -1727,6 +521,7 @@ index 0000000000000000000000000000000000000000..889a487e24721a8ecfef91f5a655892a
+ "lib/readline/promises.js",
+ "lib/repl.js",
+ "lib/sea.js",
++ "lib/sqlite.js",
+ "lib/stream.js",
+ "lib/stream/consumers.js",
+ "lib/stream/promises.js",
@@ -1775,10 +570,12 @@ index 0000000000000000000000000000000000000000..889a487e24721a8ecfef91f5a655892a
+ "src/api/exceptions.cc",
+ "src/api/hooks.cc",
+ "src/api/utils.cc",
++ "src/async_context_frame.cc",
+ "src/async_wrap.cc",
+ "src/base_object.cc",
+ "src/cares_wrap.cc",
+ "src/cleanup_queue.cc",
++ "src/compile_cache.cc",
+ "src/connect_wrap.cc",
+ "src/connection_wrap.cc",
+ "src/dataqueue/queue.cc",
@@ -1812,6 +609,7 @@ index 0000000000000000000000000000000000000000..889a487e24721a8ecfef91f5a655892a
+ "src/node_constants.cc",
+ "src/node_contextify.cc",
+ "src/node_credentials.cc",
++ "src/node_debug.cc",
+ "src/node_dir.cc",
+ "src/node_dotenv.cc",
+ "src/node_env_var.cc",
@@ -1824,6 +622,7 @@ index 0000000000000000000000000000000000000000..889a487e24721a8ecfef91f5a655892a
+ "src/node_main_instance.cc",
+ "src/node_messaging.cc",
+ "src/node_metadata.cc",
++ "src/node_modules.cc",
+ "src/node_options.cc",
+ "src/node_os.cc",
+ "src/node_perf.cc",
@@ -1841,9 +640,11 @@ index 0000000000000000000000000000000000000000..889a487e24721a8ecfef91f5a655892a
+ "src/node_shadow_realm.cc",
+ "src/node_snapshotable.cc",
+ "src/node_sockaddr.cc",
++ "src/node_sqlite.cc",
+ "src/node_stat_watcher.cc",
+ "src/node_symbols.cc",
+ "src/node_task_queue.cc",
++ "src/node_task_runner.cc",
+ "src/node_trace_events.cc",
+ "src/node_types.cc",
+ "src/node_url.cc",
@@ -1852,6 +653,7 @@ index 0000000000000000000000000000000000000000..889a487e24721a8ecfef91f5a655892a
+ "src/node_wasi.cc",
+ "src/node_wasm_web_api.cc",
+ "src/node_watchdog.cc",
++ "src/node_webstorage.cc",
+ "src/node_worker.cc",
+ "src/node_zlib.cc",
+ "src/path.cc",
@@ -1886,19 +688,19 @@ index 0000000000000000000000000000000000000000..889a487e24721a8ecfef91f5a655892a
+ "src/aliased_buffer-inl.h",
+ "src/aliased_struct.h",
+ "src/aliased_struct-inl.h",
++ "src/async_context_frame.h",
+ "src/async_wrap.h",
+ "src/async_wrap-inl.h",
+ "src/base_object.h",
+ "src/base_object-inl.h",
+ "src/base_object_types.h",
-+ "src/base64.h",
-+ "src/base64-inl.h",
+ "src/blob_serializer_deserializer.h",
+ "src/blob_serializer_deserializer-inl.h",
+ "src/callback_queue.h",
+ "src/callback_queue-inl.h",
+ "src/cleanup_queue.h",
+ "src/cleanup_queue-inl.h",
++ "src/compile_cache.h",
+ "src/connect_wrap.h",
+ "src/connection_wrap.h",
+ "src/dataqueue/queue.h",
@@ -1929,6 +731,7 @@ index 0000000000000000000000000000000000000000..889a487e24721a8ecfef91f5a655892a
+ "src/node_constants.h",
+ "src/node_context_data.h",
+ "src/node_contextify.h",
++ "src/node_debug.h",
+ "src/node_dir.h",
+ "src/node_dotenv.h",
+ "src/node_errors.h",
@@ -1948,6 +751,7 @@ index 0000000000000000000000000000000000000000..889a487e24721a8ecfef91f5a655892a
+ "src/node_messaging.h",
+ "src/node_metadata.h",
+ "src/node_mutex.h",
++ "src/node_modules.h",
+ "src/node_object_wrap.h",
+ "src/node_options.h",
+ "src/node_options-inl.h",
@@ -1967,6 +771,7 @@ index 0000000000000000000000000000000000000000..889a487e24721a8ecfef91f5a655892a
+ "src/node_snapshot_builder.h",
+ "src/node_sockaddr.h",
+ "src/node_sockaddr-inl.h",
++ "src/node_sqlite.h",
+ "src/node_stat_watcher.h",
+ "src/node_union_bytes.h",
+ "src/node_url.h",
@@ -1975,6 +780,7 @@ index 0000000000000000000000000000000000000000..889a487e24721a8ecfef91f5a655892a
+ "src/node_v8_platform-inl.h",
+ "src/node_wasi.h",
+ "src/node_watchdog.h",
++ "src/node_webstorage.h",
+ "src/node_worker.h",
+ "src/path.h",
+ "src/permission/child_process_permission.h",
@@ -1994,7 +800,6 @@ index 0000000000000000000000000000000000000000..889a487e24721a8ecfef91f5a655892a
+ "src/string_bytes.h",
+ "src/string_decoder.h",
+ "src/string_decoder-inl.h",
-+ "src/string_search.h",
+ "src/tcp_wrap.h",
+ "src/timers.h",
+ "src/tracing/agent.h",
@@ -2013,234 +818,46 @@ index 0000000000000000000000000000000000000000..889a487e24721a8ecfef91f5a655892a
+ "deps/postject/postject-api.h"
+ ]
+}
-diff --git a/src/inspector/BUILD.gn b/src/inspector/BUILD.gn
-index 909fd14345fcd988c381e640280f4b33f2e0c351..3b430a666a7d5cb52ec41f8d828284625f916701 100644
---- a/src/inspector/BUILD.gn
-+++ b/src/inspector/BUILD.gn
-@@ -1,14 +1,208 @@
--##############################################################################
--# #
--# DO NOT EDIT THIS FILE! #
--# #
--##############################################################################
-+import("//v8/gni/v8.gni")
+diff --git a/node.gni b/node.gni
+index 9dca810decebd75aab427e306b3cc37c80fb55c9..32709b860ccb12d8d1e75342a65dda0b86129b21 100644
+--- a/node.gni
++++ b/node.gni
+@@ -5,10 +5,10 @@
+ # Embedder options.
+ declare_args() {
+ # The location of Node.js in source code tree.
+- node_path = "//node"
++ node_path = "//third_party/electron_node"
--# This file is used by GN for building, which is NOT the build system used for
--# building official binaries.
--# Please modify the gyp files if you are making changes to build system.
-+inspector_protocol_dir = "../../tools/inspector_protocol"
+ # The location of V8, use the one from node's deps by default.
+- node_v8_path = "$node_path/deps/v8"
++ node_v8_path = "//v8"
--import("unofficial.gni")
-+_protocol_generated = [
-+ "protocol/Forward.h",
-+ "protocol/Protocol.cpp",
-+ "protocol/Protocol.h",
-+ "protocol/NodeWorker.cpp",
-+ "protocol/NodeWorker.h",
-+ "protocol/NodeTracing.cpp",
-+ "protocol/NodeTracing.h",
-+ "protocol/NodeRuntime.cpp",
-+ "protocol/NodeRuntime.h",
-+ "protocol/Network.cpp",
-+ "protocol/Network.h",
-+]
+ # The NODE_MODULE_VERSION defined in node_version.h.
+ node_module_version = exec_script("$node_path/tools/getmoduleversion.py", [], "value")
+@@ -38,7 +38,7 @@ declare_args() {
+ node_openssl_system_ca_path = ""
--inspector_gn_build("inspector") {
-+# These are from node_protocol_config.json
-+# These convoluted path hacks are to work around the fact that node.js is very
-+# confused about what paths are in its includes, without changing node at all.
-+# Hopefully, keying everything in this file off the paths that are in
-+# node_protocol_config.json will mean that the paths stay in sync.
-+inspector_protocol_package = "src/node/inspector/protocol"
-+inspector_protocol_output = "node/inspector/protocol"
-+
-+config("inspector_config") {
-+ include_dirs = [
-+ "$target_gen_dir",
-+ "$target_gen_dir/src",
-+ ]
-+
-+ configs = [ "../..:node_features" ]
-+}
-+
-+source_set("inspector") {
-+ sources = [
-+ "main_thread_interface.cc",
-+ "main_thread_interface.h",
-+ "node_string.cc",
-+ "node_string.h",
-+ "runtime_agent.cc",
-+ "runtime_agent.h",
-+ "tracing_agent.cc",
-+ "tracing_agent.h",
-+ "worker_agent.cc",
-+ "worker_agent.h",
-+ "network_inspector.cc",
-+ "network_inspector.h",
-+ "network_agent.cc",
-+ "network_agent.h",
-+ "worker_inspector.cc",
-+ "worker_inspector.h",
-+ ]
-+ sources += rebase_path(_protocol_generated,
-+ ".",
-+ "$target_gen_dir/$inspector_protocol_package/..")
-+ include_dirs = [
-+ "//v8/include",
-+ "..",
-+ ]
-+ deps = [
-+ ":protocol_generated_sources",
-+ ":v8_inspector_compress_protocol_json",
-+ "../../deps/uv",
-+ "../../deps/simdutf",
-+ "//third_party/icu:icuuc",
-+ ]
-+ configs += [
-+ "../..:node_internal_config",
-+ "../..:node_lib_config",
-+ ]
-+ public_configs = [ ":inspector_config" ]
-+}
-+
-+# This based on the template from //v8/../inspector_protocol.gni
-+action("protocol_generated_sources") {
-+ # This is to ensure that the output directory exists--the code generator
-+ # doesn't create it.
-+ write_file("$target_gen_dir/$inspector_protocol_package/.dummy", "")
-+ script = "$inspector_protocol_dir/code_generator.py"
-+
-+ inputs = [
-+ "$target_gen_dir/node_protocol_config.json",
-+ "$target_gen_dir/src/node_protocol.json",
-+ "$inspector_protocol_dir/lib/base_string_adapter_cc.template",
-+ "$inspector_protocol_dir/lib/base_string_adapter_h.template",
-+ "$inspector_protocol_dir/lib/Allocator_h.template",
-+ "$inspector_protocol_dir/lib/DispatcherBase_cpp.template",
-+ "$inspector_protocol_dir/lib/DispatcherBase_h.template",
-+ "$inspector_protocol_dir/lib/ErrorSupport_cpp.template",
-+ "$inspector_protocol_dir/lib/ErrorSupport_h.template",
-+ "$inspector_protocol_dir/lib/Forward_h.template",
-+ "$inspector_protocol_dir/lib/FrontendChannel_h.template",
-+ "$inspector_protocol_dir/lib/Maybe_h.template",
-+ "$inspector_protocol_dir/lib/Object_cpp.template",
-+ "$inspector_protocol_dir/lib/Object_h.template",
-+ "$inspector_protocol_dir/lib/Parser_cpp.template",
-+ "$inspector_protocol_dir/lib/Parser_h.template",
-+ "$inspector_protocol_dir/lib/Protocol_cpp.template",
-+ "$inspector_protocol_dir/lib/ValueConversions_h.template",
-+ "$inspector_protocol_dir/lib/Values_cpp.template",
-+ "$inspector_protocol_dir/lib/Values_h.template",
-+ "$inspector_protocol_dir/templates/Exported_h.template",
-+ "$inspector_protocol_dir/templates/Imported_h.template",
-+ "$inspector_protocol_dir/templates/TypeBuilder_cpp.template",
-+ "$inspector_protocol_dir/templates/TypeBuilder_h.template",
-+ ]
-+
-+ deps = [
-+ ":node_protocol_config",
-+ ":node_protocol_json",
-+ ]
-+
-+ args = [
-+ "--jinja_dir",
-+ rebase_path("//third_party/", root_build_dir), # jinja is in chromium's third_party
-+ "--output_base",
-+ rebase_path("$target_gen_dir/src", root_build_dir),
-+ "--config",
-+ rebase_path("$target_gen_dir/node_protocol_config.json", root_build_dir),
-+ ]
-+
-+ outputs =
-+ get_path_info(rebase_path(rebase_path(_protocol_generated,
-+ ".",
-+ "$inspector_protocol_output/.."),
-+ ".",
-+ "$target_gen_dir/src"),
-+ "abspath")
-+}
-+
-+template("generate_protocol_json") {
-+ copy_target_name = target_name + "_copy"
-+ copy(copy_target_name) {
-+ sources = invoker.sources
-+ outputs = [
-+ "$target_gen_dir/{{source_file_part}}",
-+ ]
-+ }
-+ copied_pdl = get_target_outputs(":$copy_target_name")
-+ action(target_name) {
-+ deps = [
-+ ":$copy_target_name",
-+ ]
-+ sources = copied_pdl
-+ outputs = invoker.outputs
-+ script = "$inspector_protocol_dir/convert_protocol_to_json.py"
-+ args = rebase_path(sources + outputs, root_build_dir)
-+ }
-+}
-+
-+copy("node_protocol_config") {
-+ sources = [
-+ "node_protocol_config.json",
-+ ]
-+ outputs = [
-+ "$target_gen_dir/{{source_file_part}}",
-+ ]
-+}
-+
-+generate_protocol_json("node_protocol_json") {
-+ sources = [
-+ "node_protocol.pdl",
-+ ]
-+ outputs = [
-+ "$target_gen_dir/src/node_protocol.json",
-+ ]
-+}
-+
-+generate_protocol_json("v8_protocol_json") {
-+ sources = [
-+ "//v8/include/js_protocol.pdl",
-+ ]
-+ outputs = [
-+ "$target_gen_dir/js_protocol.json",
-+ ]
-+}
-+
-+action("concatenate_protocols") {
-+ deps = [
-+ ":node_protocol_json",
-+ ":v8_protocol_json",
-+ ]
-+ inputs = [
-+ "$target_gen_dir/js_protocol.json",
-+ "$target_gen_dir/src/node_protocol.json",
-+ ]
-+ outputs = [
-+ "$target_gen_dir/concatenated_protocol.json",
-+ ]
-+ script = "//v8/third_party/inspector_protocol/concatenate_protocols.py"
-+ args = rebase_path(inputs + outputs, root_build_dir)
-+}
-+
-+action("v8_inspector_compress_protocol_json") {
-+ deps = [
-+ ":concatenate_protocols",
-+ ]
-+ inputs = [
-+ "$target_gen_dir/concatenated_protocol.json",
-+ ]
-+ outputs = [
-+ "$target_gen_dir/v8_inspector_protocol_json.h",
-+ ]
-+ script = "../../tools/compress_json.py"
-+ args = rebase_path(inputs + outputs, root_build_dir)
+ # Initialize v8 platform during node.js startup.
+- node_use_v8_platform = true
++ node_use_v8_platform = false
+
+ # Custom build tag.
+ node_tag = ""
+@@ -58,7 +58,7 @@ declare_args() {
+ # TODO(zcbenz): There are few broken things for now:
+ # 1. cross-os compilation is not supported.
+ # 2. node_mksnapshot crashes when cross-compiling for x64 from arm64.
+- node_use_node_snapshot = (host_os == target_os) && !(host_cpu == "arm64" && target_cpu == "x64")
++ node_use_node_snapshot = false
}
+
+ assert(!node_enable_inspector || node_use_openssl,
diff --git a/src/node_builtins.cc b/src/node_builtins.cc
-index 706ea4f5cb90525c8ea56f794320a733c45a193f..c7ae7759595bfc7fdc31dab174a7514ddd8345e7 100644
+index 2bc7155f7c075e5a22ece7159a64a1c9ba3d8ac9..48d29a0d05538cd1d992f3f086d826e78d0d8882 100644
--- a/src/node_builtins.cc
+++ b/src/node_builtins.cc
-@@ -773,6 +773,7 @@ void BuiltinLoader::RegisterExternalReferences(
+@@ -775,6 +775,7 @@ void BuiltinLoader::RegisterExternalReferences(
registry->Register(GetNatives);
RegisterExternalReferencesForInternalizedBuiltinCode(registry);
@@ -2261,12 +878,25 @@ index 1cb85b9058d06555382e565dc32192a9fa48ed9f..cec9be01abd107e8612f70daf19b4834
// Handles compilation and caching of built-in JavaScript modules and
// bootstrap scripts, whose source are bundled into the binary as static data.
+diff --git a/tools/generate_config_gypi.py b/tools/generate_config_gypi.py
+index 45b3ac5006140fb55aad0e6b78084b753a947a76..8667857107e4f2481fd98032d4333b086fb7b479 100755
+--- a/tools/generate_config_gypi.py
++++ b/tools/generate_config_gypi.py
+@@ -21,7 +21,7 @@ import getnapibuildversion
+ GN_RE = re.compile(r'(\w+)\s+=\s+(.*?)$', re.MULTILINE)
+
+ if sys.platform == 'win32':
+- GN = 'gn.exe'
++ GN = 'gn.bat'
+ else:
+ GN = 'gn'
+
diff --git a/tools/generate_gn_filenames_json.py b/tools/generate_gn_filenames_json.py
new file mode 100755
-index 0000000000000000000000000000000000000000..37c16859003e61636fe2f1a4040b1e904c472d0b
+index 0000000000000000000000000000000000000000..54b761d91734aead50aeeba8c91a1262531df713
--- /dev/null
+++ b/tools/generate_gn_filenames_json.py
-@@ -0,0 +1,117 @@
+@@ -0,0 +1,118 @@
+#!/usr/bin/env python3
+import json
+import os
@@ -2318,6 +948,7 @@ index 0000000000000000000000000000000000000000..37c16859003e61636fe2f1a4040b1e90
+ '<@(deps_files)',
+ '<@(node_sources)',
+ 'common.gypi',
++ 'common_node.gypi',
+ '<(SHARED_INTERMEDIATE_DIR)/node_javascript.cc',
+ }
+
@@ -2385,27 +1016,10 @@ index 0000000000000000000000000000000000000000..37c16859003e61636fe2f1a4040b1e90
+ f.write(json.dumps(out, sort_keys=True, indent=2, separators=(',', ': ')))
+ f.write('\n')
diff --git a/tools/install.py b/tools/install.py
-index b132c7bf26c02886a7ab341a1973bf449744ba0f..757e3e60a7be01fac55c5fbb010dbbae00b1bfca 100755
+index bf54249b66c0d4e179deaae5a9fd55568e694fe0..57b51b03d237fba4b25aa69a663c88e9541b6cb5 100755
--- a/tools/install.py
+++ b/tools/install.py
-@@ -264,6 +264,7 @@ def headers(options, action):
- 'include/v8-forward.h',
- 'include/v8-function-callback.h',
- 'include/v8-function.h',
-+ 'include/v8-handle-base.h',
- 'include/v8-initialization.h',
- 'include/v8-internal.h',
- 'include/v8-isolate.h',
-@@ -284,6 +285,8 @@ def headers(options, action):
- 'include/v8-promise.h',
- 'include/v8-proxy.h',
- 'include/v8-regexp.h',
-+ "include/v8-sandbox.h",
-+ "include/v8-source-location.h",
- 'include/v8-script.h',
- 'include/v8-snapshot.h',
- 'include/v8-statistics.h',
-@@ -390,7 +393,7 @@ def parse_options(args):
+@@ -392,7 +392,7 @@ def parse_options(args):
parser.add_argument('--build-dir', help='the location of built binaries',
default='out/Release')
parser.add_argument('--v8-dir', help='the location of V8',
@@ -2417,7 +1031,7 @@ index b132c7bf26c02886a7ab341a1973bf449744ba0f..757e3e60a7be01fac55c5fbb010dbbae
diff --git a/tools/js2c.cc b/tools/js2c.cc
old mode 100644
new mode 100755
-index e0f3d8844718ab8a6478c40ff713c1fd6bcff95a..c73a5b666dbaf555c749d836c20a7ae19a840847
+index a536b5dcd857275d3b02e361bd7d37a939f6b573..b2d5678d58a79774d5aeedc15ac5d5fd786f64bb
--- a/tools/js2c.cc
+++ b/tools/js2c.cc
@@ -30,6 +30,7 @@ namespace js2c {
@@ -2552,7 +1166,7 @@ index e0f3d8844718ab8a6478c40ff713c1fd6bcff95a..c73a5b666dbaf555c749d836c20a7ae1
// Should have exactly 3 types: `.js`, `.mjs` and `.gypi`.
assert(file_map.size() == 3);
auto gypi_it = file_map.find(".gypi");
-@@ -932,6 +989,7 @@ int Main(int argc, char* argv[]) {
+@@ -939,6 +996,7 @@ int Main(int argc, char* argv[]) {
std::sort(mjs_it->second.begin(), mjs_it->second.end());
return JS2C(js_it->second, mjs_it->second, gypi_it->second[0], output);
@@ -2560,10 +1174,171 @@ index e0f3d8844718ab8a6478c40ff713c1fd6bcff95a..c73a5b666dbaf555c749d836c20a7ae1
}
} // namespace js2c
} // namespace node
-@@ -940,4 +998,4 @@ NODE_MAIN(int argc, node::argv_type raw_argv[]) {
- char** argv;
- node::FixupMain(argc, raw_argv, &argv);
- return node::js2c::Main(argc, argv);
--}
-+}
-\ No newline at end of file
+diff --git a/tools/search_files.py b/tools/search_files.py
+index 65d0e1be42f0a85418491ebb548278cf431aa6a0..d4a31342f1c6107b029394c6e1d00a1d1e877e03 100755
+--- a/tools/search_files.py
++++ b/tools/search_files.py
+@@ -14,6 +14,7 @@ if __name__ == '__main__':
+ try:
+ files = SearchFiles(*sys.argv[2:])
+ files = [ os.path.relpath(x, sys.argv[1]) for x in files ]
++ files = [os.path.normpath(x).replace(os.sep, '/') for x in files]
+ print('\n'.join(files))
+ except Exception as e:
+ print(str(e))
+diff --git a/unofficial.gni b/unofficial.gni
+index c3b311e4a7f5444b07d4d7028d4621806959804e..de6ff5548ca5282199b7d85c11941c1fa351a9d9 100644
+--- a/unofficial.gni
++++ b/unofficial.gni
+@@ -139,6 +139,7 @@ template("node_gn_build") {
+ public_deps = [
+ "deps/ada",
+ "deps/uv",
++ "//electron:electron_js2c",
+ "deps/simdjson",
+ "$node_v8_path",
+ ]
+@@ -150,7 +151,6 @@ template("node_gn_build") {
+ "deps/llhttp",
+ "deps/nbytes",
+ "deps/nghttp2",
+- "deps/ngtcp2",
+ "deps/postject",
+ "deps/simdutf",
+ "deps/sqlite",
+@@ -159,7 +159,11 @@ template("node_gn_build") {
+ "$node_v8_path:v8_libplatform",
+ ]
+
++ cflags_cc = [ "-Wno-unguarded-availability-new" ]
++
+ sources = [
++ "src/node_snapshot_stub.cc",
++ "$root_gen_dir/electron_natives.cc",
+ "$target_gen_dir/node_javascript.cc",
+ ] + gypi_values.node_sources
+
+@@ -178,8 +182,10 @@ template("node_gn_build") {
+ deps += [ "//third_party/icu" ]
+ }
+ if (node_use_openssl) {
+- deps += [ "deps/ncrypto" ]
+- public_deps += [ "deps/openssl" ]
++ deps += [
++ "deps/ncrypto",
++ "//third_party/boringssl"
++ ]
+ sources += gypi_values.node_crypto_sources
+ }
+ if (node_enable_inspector) {
+@@ -276,6 +282,7 @@ template("node_gn_build") {
+ }
+
+ executable("node_js2c") {
++ defines = []
+ deps = [
+ "deps/simdutf",
+ "deps/uv",
+@@ -286,26 +293,75 @@ template("node_gn_build") {
+ "src/embedded_data.cc",
+ "src/embedded_data.h",
+ ]
+- include_dirs = [ "src" ]
++ include_dirs = [ "src", "tools" ]
++
++ if (!is_win) {
++ defines += [ "NODE_JS2C_USE_STRING_LITERALS" ]
++ }
++ }
++
++ node_deps_files = gypi_values.deps_files + node_builtin_shareable_builtins
++ node_library_files = exec_script("./tools/search_files.py",
++ [ rebase_path(".", root_build_dir),
++ rebase_path("lib", root_build_dir),
++ "js" ],
++ "list lines")
++
++ fs_files = [
++ "lib/internal/fs/cp/cp-sync.js",
++ "lib/internal/fs/cp/cp.js",
++ "lib/internal/fs/dir.js",
++ "lib/internal/fs/glob.js",
++ "lib/internal/fs/promises.js",
++ "lib/internal/fs/read/context.js",
++ "lib/internal/fs/recursive_watch.js",
++ "lib/internal/fs/rimraf.js",
++ "lib/internal/fs/streams.js",
++ "lib/internal/fs/sync_write_stream.js",
++ "lib/internal/fs/utils.js",
++ "lib/internal/fs/watchers.js",
++ "lib/fs.js",
++ "lib/fs/promises.js"
++ ]
++
++ original_fs_files = []
++ foreach(file, fs_files) {
++ original_fs_files += [string_replace(string_replace(string_replace(file, "internal/fs/", "internal/original-fs/"), "lib/fs.js", "lib/original-fs.js"), "lib/fs/", "lib/original-fs/")]
++ }
++
++ copy("node_js2c_inputs") {
++ sources = node_deps_files + node_library_files
++ outputs = [
++ "$target_gen_dir/js2c_inputs/{{source_target_relative}}",
++ ]
++ }
++
++ action("node_js2c_original_fs") {
++ script = "//electron/script/node/generate_original_fs.py"
++ inputs = fs_files
++ deps = [ ":node_js2c_inputs" ]
++
++ outputs = []
++ foreach(file, original_fs_files) {
++ outputs += ["$target_gen_dir/js2c_inputs/$file"]
++ }
++
++ args = [rebase_path("$target_gen_dir/js2c_inputs")] + fs_files
+ }
+
+ action("run_node_js2c") {
+- script = "$node_v8_path/tools/run.py"
++ script = "//electron/build/run-in-dir.py"
+ deps = [
++ ":node_js2c_original_fs",
+ ":node_js2c($host_toolchain)",
+ ":generate_config_gypi",
+ ]
+
+- node_deps_files = gypi_values.deps_files + node_builtin_shareable_builtins
+- node_library_files = exec_script("./tools/search_files.py",
+- [ rebase_path(".", root_build_dir),
+- rebase_path("lib", root_build_dir),
+- "js" ],
+- "list lines")
+-
++ config_gypi = [ "$target_gen_dir/config.gypi" ]
+ inputs = node_library_files +
+ node_deps_files +
+- [ "$target_gen_dir/config.gypi" ]
++ get_target_outputs(":node_js2c_original_fs") +
++ config_gypi
+ outputs = [ "$target_gen_dir/node_javascript.cc" ]
+
+ # Get the path to node_js2c executable of the host toolchain.
+@@ -319,11 +375,11 @@ template("node_gn_build") {
+ get_label_info(":node_js2c($host_toolchain)", "name") +
+ host_executable_suffix
+
+- args = [ rebase_path(node_js2c_path),
+- rebase_path("$target_gen_dir/node_javascript.cc"),
+- "--root", rebase_path("."),
+- "lib", rebase_path("$target_gen_dir/config.gypi") ] +
+- node_deps_files
++ args = [ rebase_path("$target_gen_dir/js2c_inputs"),
++ rebase_path(node_js2c_path),
++ rebase_path("$target_gen_dir/node_javascript.cc")] +
++ rebase_path(config_gypi) + node_deps_files +
++ original_fs_files + node_library_files
+ }
+
+ executable("node_cctest") {
diff --git a/patches/node/build_compile_with_c_20_support.patch b/patches/node/build_compile_with_c_20_support.patch
index bef0bb28e9..c83de137e2 100644
--- a/patches/node/build_compile_with_c_20_support.patch
+++ b/patches/node/build_compile_with_c_20_support.patch
@@ -10,28 +10,19 @@ V8 requires C++20 support as of https://chromium-review.googlesource.com/c/v8/v8
This can be removed when Electron upgrades to a version of Node.js containing the required V8 version.
diff --git a/common.gypi b/common.gypi
-index bdf1a1f33f3ea09d933757c7fee87c563cc833ab..2eb62610db2f0ebf68fa9a55ffba98291ecfe451 100644
+index 74616453e2e047acbb9e25f2f93ebeab06011669..bce15fc4a8b3f2fa0b5a588e6a2b28d2b8b6ac45 100644
--- a/common.gypi
+++ b/common.gypi
-@@ -305,7 +305,7 @@
- 'VCCLCompilerTool': {
- 'AdditionalOptions': [
- '/Zc:__cplusplus',
-- '-std:c++17'
-+ '-std:c++20'
+@@ -518,7 +518,7 @@
+ '-fno-rtti',
+ '-fno-exceptions',
+ '-fno-strict-aliasing',
+- '-std=gnu++17',
++ '-std=gnu++20',
],
- 'BufferSecurityCheck': 'true',
- 'DebugInformationFormat': 1, # /Z7 embed info in .obj files
-@@ -487,7 +487,7 @@
- }],
- [ 'OS in "linux freebsd openbsd solaris android aix os400 cloudabi"', {
- 'cflags': [ '-Wall', '-Wextra', '-Wno-unused-parameter', ],
-- 'cflags_cc': [ '-fno-rtti', '-fno-exceptions', '-std=gnu++17' ],
-+ 'cflags_cc': [ '-fno-rtti', '-fno-exceptions', '-std=gnu++20' ],
'defines': [ '__STDC_FORMAT_MACROS' ],
'ldflags': [ '-rdynamic' ],
- 'target_conditions': [
-@@ -658,7 +658,7 @@
+@@ -688,7 +688,7 @@
['clang==1', {
'xcode_settings': {
'GCC_VERSION': 'com.apple.compilers.llvm.clang.1_0',
diff --git a/patches/node/build_enable_perfetto.patch b/patches/node/build_enable_perfetto.patch
index 2d8e77f07f..0bfc4367eb 100644
--- a/patches/node/build_enable_perfetto.patch
+++ b/patches/node/build_enable_perfetto.patch
@@ -12,6 +12,19 @@ adding associated guards there should be relatively small.
We should upstream this as it will eventually impact Node.js as well.
+diff --git a/filenames.json b/filenames.json
+index 5af3886d8d3d74d31249a4d79030a8373b8dad52..8ab04d0b1b58454c6ea21f33870f9557f3a57b56 100644
+--- a/filenames.json
++++ b/filenames.json
+@@ -739,8 +739,6 @@
+ "src/tcp_wrap.h",
+ "src/timers.h",
+ "src/tracing/agent.h",
+- "src/tracing/node_trace_buffer.h",
+- "src/tracing/node_trace_writer.h",
+ "src/tracing/trace_event.h",
+ "src/tracing/trace_event_common.h",
+ "src/tracing/traced_value.h",
diff --git a/lib/internal/constants.js b/lib/internal/constants.js
index 8d7204f6cb48f783adc4d1c1eb2de0c83b7fffe2..a154559a56bf383d3c26af523c9bb07b564ef600 100644
--- a/lib/internal/constants.js
@@ -63,11 +76,62 @@ index 251f51ec454f9cba4023b8b6729241ee753aac13..1de8cac6e3953ce9cab9db03530da327
}
module.exports = {
+diff --git a/node.gyp b/node.gyp
+index 11474953b186c7b3ec2edb0539f34572e6c551b7..eeaaef8a06cdc2d17e89f9c719f9922e6e04ce92 100644
+--- a/node.gyp
++++ b/node.gyp
+@@ -174,7 +174,6 @@
+ 'src/timers.cc',
+ 'src/timer_wrap.cc',
+ 'src/tracing/agent.cc',
+- 'src/tracing/node_trace_buffer.cc',
+ 'src/tracing/node_trace_writer.cc',
+ 'src/tracing/trace_event.cc',
+ 'src/tracing/traced_value.cc',
+@@ -302,7 +301,6 @@
+ 'src/tcp_wrap.h',
+ 'src/timers.h',
+ 'src/tracing/agent.h',
+- 'src/tracing/node_trace_buffer.h',
+ 'src/tracing/node_trace_writer.h',
+ 'src/tracing/trace_event.h',
+ 'src/tracing/trace_event_common.h',
+diff --git a/src/inspector/tracing_agent.cc b/src/inspector/tracing_agent.cc
+index e7b6d3b3ea63bdc80e569f56209e958b4fcde328..b52d5b1c7293539315626cd67f794cce4cfd1760 100644
+--- a/src/inspector/tracing_agent.cc
++++ b/src/inspector/tracing_agent.cc
+@@ -84,14 +84,14 @@ class InspectorTraceWriter : public node::tracing::AsyncTraceWriter {
+ explicit InspectorTraceWriter(int frontend_object_id,
+ std::shared_ptr<MainThreadHandle> main_thread)
+ : frontend_object_id_(frontend_object_id), main_thread_(main_thread) {}
+-
++#ifndef V8_USE_PERFETTO
+ void AppendTraceEvent(
+ v8::platform::tracing::TraceObject* trace_event) override {
+ if (!json_writer_)
+ json_writer_.reset(TraceWriter::CreateJSONTraceWriter(stream_, "value"));
+ json_writer_->AppendTraceEvent(trace_event);
+ }
+-
++#endif
+ void Flush(bool) override {
+ if (!json_writer_)
+ return;
diff --git a/src/tracing/agent.cc b/src/tracing/agent.cc
-index 7ce59674356f9743438350949be42fa7ead2afbe..c5fedc3be86a77730c57321b9c73cc8e94a001d7 100644
+index 7ce59674356f9743438350949be42fa7ead2afbe..30bff4272ed8eb5146e3b73a4849c187177fc3bd 100644
--- a/src/tracing/agent.cc
+++ b/src/tracing/agent.cc
-@@ -50,7 +50,9 @@ using v8::platform::tracing::TraceWriter;
+@@ -2,7 +2,9 @@
+
+ #include <string>
+ #include "trace_event.h"
++#ifndef V8_USE_PERFETTO
+ #include "tracing/node_trace_buffer.h"
++#endif
+ #include "debug_utils-inl.h"
+ #include "env-inl.h"
+
+@@ -50,7 +52,9 @@ using v8::platform::tracing::TraceWriter;
using std::string;
Agent::Agent() : tracing_controller_(new TracingController()) {
@@ -77,7 +141,7 @@ index 7ce59674356f9743438350949be42fa7ead2afbe..c5fedc3be86a77730c57321b9c73cc8e
CHECK_EQ(uv_loop_init(&tracing_loop_), 0);
CHECK_EQ(uv_async_init(&tracing_loop_,
-@@ -86,10 +88,14 @@ Agent::~Agent() {
+@@ -86,10 +90,14 @@ Agent::~Agent() {
void Agent::Start() {
if (started_)
return;
@@ -93,7 +157,7 @@ index 7ce59674356f9743438350949be42fa7ead2afbe..c5fedc3be86a77730c57321b9c73cc8e
// This thread should be created *after* async handles are created
// (within NodeTraceWriter and NodeTraceBuffer constructors).
-@@ -143,8 +149,10 @@ void Agent::StopTracing() {
+@@ -143,8 +151,10 @@ void Agent::StopTracing() {
return;
// Perform final Flush on TraceBuffer. We don't want the tracing controller
// to flush the buffer again on destruction of the V8::Platform.
@@ -105,7 +169,7 @@ index 7ce59674356f9743438350949be42fa7ead2afbe..c5fedc3be86a77730c57321b9c73cc8e
started_ = false;
// Thread should finish when the tracing loop is stopped.
-@@ -202,6 +210,7 @@ std::string Agent::GetEnabledCategories() const {
+@@ -202,6 +212,7 @@ std::string Agent::GetEnabledCategories() const {
return categories;
}
@@ -113,7 +177,7 @@ index 7ce59674356f9743438350949be42fa7ead2afbe..c5fedc3be86a77730c57321b9c73cc8e
void Agent::AppendTraceEvent(TraceObject* trace_event) {
for (const auto& id_writer : writers_)
id_writer.second->AppendTraceEvent(trace_event);
-@@ -211,18 +220,21 @@ void Agent::AddMetadataEvent(std::unique_ptr<TraceObject> event) {
+@@ -211,18 +222,21 @@ void Agent::AddMetadataEvent(std::unique_ptr<TraceObject> event) {
Mutex::ScopedLock lock(metadata_events_mutex_);
metadata_events_.push_back(std::move(event));
}
@@ -136,7 +200,7 @@ index 7ce59674356f9743438350949be42fa7ead2afbe..c5fedc3be86a77730c57321b9c73cc8e
void TracingController::AddMetadataEvent(
const unsigned char* category_group_enabled,
const char* name,
-@@ -246,6 +258,6 @@ void TracingController::AddMetadataEvent(
+@@ -246,6 +260,6 @@ void TracingController::AddMetadataEvent(
if (node_agent != nullptr)
node_agent->AddMetadataEvent(std::move(trace_event));
}
@@ -198,26 +262,20 @@ index b542a849fe8da7e8bbbcca7067b73dc32b18d6d3..059ce6f6ea17199ead09c6c13bcc680f
};
void AgentWriterHandle::reset() {
-diff --git a/src/tracing/node_trace_buffer.cc b/src/tracing/node_trace_buffer.cc
-index e187a1d78c81972b69cd4e03f7079cdb727956ad..3256c6326a08c6cafd83f1e49e3350193e813b51 100644
---- a/src/tracing/node_trace_buffer.cc
-+++ b/src/tracing/node_trace_buffer.cc
-@@ -55,6 +55,7 @@ TraceObject* InternalTraceBuffer::GetEventByHandle(uint64_t handle) {
- }
-
- void InternalTraceBuffer::Flush(bool blocking) {
+diff --git a/src/tracing/node_trace_buffer.h b/src/tracing/node_trace_buffer.h
+index 18e4f43efaae3a60b924e697918867e604513194..7cbaf01235750138c680c8ec2ed5d206d638f8b6 100644
+--- a/src/tracing/node_trace_buffer.h
++++ b/src/tracing/node_trace_buffer.h
+@@ -42,7 +42,9 @@ class InternalTraceBuffer {
+ bool flushing_;
+ size_t max_chunks_;
+ Agent* agent_;
+#ifndef V8_USE_PERFETTO
- {
- Mutex::ScopedLock scoped_lock(mutex_);
- if (total_chunks_ > 0) {
-@@ -75,6 +76,7 @@ void InternalTraceBuffer::Flush(bool blocking) {
- flushing_ = false;
- }
- }
+ std::vector<std::unique_ptr<TraceBufferChunk>> chunks_;
+#endif
- agent_->Flush(blocking);
- }
-
+ size_t total_chunks_ = 0;
+ uint32_t current_chunk_seq_ = 1;
+ uint32_t id_;
diff --git a/src/tracing/node_trace_writer.cc b/src/tracing/node_trace_writer.cc
index 8f053efe93324b9acbb4e85f7b974b4f7712e200..e331ed5567caa39ade90ce28cea69f1d10533812 100644
--- a/src/tracing/node_trace_writer.cc
diff --git a/patches/node/build_ensure_native_module_compilation_fails_if_not_using_a_new.patch b/patches/node/build_ensure_native_module_compilation_fails_if_not_using_a_new.patch
index ae020d1bb1..4001cf3cb6 100644
--- a/patches/node/build_ensure_native_module_compilation_fails_if_not_using_a_new.patch
+++ b/patches/node/build_ensure_native_module_compilation_fails_if_not_using_a_new.patch
@@ -7,7 +7,7 @@ Subject: build: ensure native module compilation fails if not using a new
This should not be upstreamed, it is a quality-of-life patch for downstream module builders.
diff --git a/common.gypi b/common.gypi
-index 697b8bba6a55358924d6986f2eb347a99ff73889..bdf1a1f33f3ea09d933757c7fee87c563cc833ab 100644
+index 229cb96c1385c597138719f2b01f78bd54ad44ab..74616453e2e047acbb9e25f2f93ebeab06011669 100644
--- a/common.gypi
+++ b/common.gypi
@@ -86,6 +86,8 @@
@@ -19,7 +19,7 @@ index 697b8bba6a55358924d6986f2eb347a99ff73889..bdf1a1f33f3ea09d933757c7fee87c56
##### end V8 defaults #####
# When building native modules using 'npm install' with the system npm,
-@@ -285,6 +287,7 @@
+@@ -291,6 +293,7 @@
# Defines these mostly for node-gyp to pickup.
'defines': [
'_GLIBCXX_USE_CXX11_ABI=1',
@@ -27,7 +27,7 @@ index 697b8bba6a55358924d6986f2eb347a99ff73889..bdf1a1f33f3ea09d933757c7fee87c56
],
# Forcibly disable -Werror. We support a wide range of compilers, it's
-@@ -414,6 +417,11 @@
+@@ -437,6 +440,11 @@
}],
],
}],
@@ -40,19 +40,19 @@ index 697b8bba6a55358924d6986f2eb347a99ff73889..bdf1a1f33f3ea09d933757c7fee87c56
# list in v8/BUILD.gn.
['v8_enable_v8_checks == 1', {
diff --git a/configure.py b/configure.py
-index a6f66c41f75bffcfaf75d4415c694300b7624136..7ca0762fe3590fef7b88ba684de44d99aaecace4 100755
+index d03db1970fd7a1629a7a7719a5ff267402ab4a66..ce055fb5dfc84c75c486b99f01fea6b9531ff54b 100755
--- a/configure.py
+++ b/configure.py
-@@ -1585,6 +1585,7 @@ def configure_library(lib, output, pkgname=None):
+@@ -1634,6 +1634,7 @@ def configure_library(lib, output, pkgname=None):
+ def configure_v8(o, configs):
+ set_configuration_variable(configs, 'v8_enable_v8_checks', release=1, debug=0)
-
- def configure_v8(o):
+ o['variables']['using_electron_config_gypi'] = 1
o['variables']['v8_enable_webassembly'] = 0 if options.v8_lite_mode else 1
o['variables']['v8_enable_javascript_promise_hooks'] = 1
o['variables']['v8_enable_lite_mode'] = 1 if options.v8_lite_mode else 0
diff --git a/src/node.h b/src/node.h
-index 4f2eb9d0aab88b70c86339e750799080e980d7da..df3fb3372d6357b5d77b4f683e309b8483998128 100644
+index 0fec9477fd0f2a3c2aa68284131c510b0da0e025..c16204ad2a4787eeffe61eedda254d3a5509df8c 100644
--- a/src/node.h
+++ b/src/node.h
@@ -22,6 +22,12 @@
diff --git a/patches/node/build_modify_js2c_py_to_allow_injection_of_original-fs_and_custom_embedder_js.patch b/patches/node/build_modify_js2c_py_to_allow_injection_of_original-fs_and_custom_embedder_js.patch
index 6c5aa02753..aaba7297e7 100644
--- a/patches/node/build_modify_js2c_py_to_allow_injection_of_original-fs_and_custom_embedder_js.patch
+++ b/patches/node/build_modify_js2c_py_to_allow_injection_of_original-fs_and_custom_embedder_js.patch
@@ -34,10 +34,10 @@ index f5ecc15159f457cd0b8069c0427b7c758c916c4e..c9ce67391f321989b0af48159b4da3ab
let kResistStopPropagation;
diff --git a/src/node_builtins.cc b/src/node_builtins.cc
-index c7ae7759595bfc7fdc31dab174a7514ddd8345e7..4bf80aa6cc6385dc376fd0a3538efc27fe5bd0a2 100644
+index 48d29a0d05538cd1d992f3f086d826e78d0d8882..8987234c2d08449242b5fd037ed314b725bc42a5 100644
--- a/src/node_builtins.cc
+++ b/src/node_builtins.cc
-@@ -35,6 +35,7 @@ using v8::Value;
+@@ -34,6 +34,7 @@ using v8::Value;
BuiltinLoader::BuiltinLoader()
: config_(GetConfig()), code_cache_(std::make_shared<BuiltinCodeCache>()) {
LoadJavaScriptSource();
diff --git a/patches/node/build_restore_clang_as_default_compiler_on_macos.patch b/patches/node/build_restore_clang_as_default_compiler_on_macos.patch
index 0423182e8b..5cee2b1aef 100644
--- a/patches/node/build_restore_clang_as_default_compiler_on_macos.patch
+++ b/patches/node/build_restore_clang_as_default_compiler_on_macos.patch
@@ -11,7 +11,7 @@ node-gyp will use the result of `process.config` that reflects the environment
in which the binary got built.
diff --git a/common.gypi b/common.gypi
-index 2eb62610db2f0ebf68fa9a55ffba98291ecfe451..3ec08ee144b586d05c4e49c2251416734cbc02c5 100644
+index bce15fc4a8b3f2fa0b5a588e6a2b28d2b8b6ac45..289ab5d282e93c795eafb5fb992c3bbc4790a687 100644
--- a/common.gypi
+++ b/common.gypi
@@ -125,6 +125,7 @@
diff --git a/patches/node/cherry-pick_src_remove_calls_to_recently_deprecated_v8_apis.patch b/patches/node/cherry-pick_src_remove_calls_to_recently_deprecated_v8_apis.patch
deleted file mode 100644
index 2d33d6a273..0000000000
--- a/patches/node/cherry-pick_src_remove_calls_to_recently_deprecated_v8_apis.patch
+++ /dev/null
@@ -1,182 +0,0 @@
-From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
-From: Adam Klein <[email protected]>
-Date: Wed, 15 May 2024 09:16:00 +0200
-Subject: cherry-pick: src: remove calls to recently deprecated V8 APIs
-
-Node.js Commit: a6d54f179d997497a95c18456bef6bc3ee15e2c4
-Node.js PR: https://github.com/nodejs/node/pull/52996
-V8 API Removal CL: https://chromium-review.googlesource.com/c/v8/v8/+/5539888
-
-This patch is slightly modified from the original commit in order to
-resolve conflicts due to the base commit difference between the Node.js
-PR and the current upgrade roll.
-
-This patch is expected to be deleted once we catch up with a Node.js
-upgrade that includes the original Node.js commit above.
-
-diff --git a/src/module_wrap.cc b/src/module_wrap.cc
-index ff658ec88e5161cd66536ee6e95dba675b16eccc..9bbb8ab908d8d992abb43254860d51f57f56387b 100644
---- a/src/module_wrap.cc
-+++ b/src/module_wrap.cc
-@@ -202,8 +202,7 @@ void ModuleWrap::New(const FunctionCallbackInfo<Value>& args) {
- }
-
- Local<String> source_text = args[2].As<String>();
-- ScriptOrigin origin(isolate,
-- url,
-+ ScriptOrigin origin(url,
- line_offset,
- column_offset,
- true, // is cross origin
-@@ -464,7 +463,6 @@ void ModuleWrap::Evaluate(const FunctionCallbackInfo<Value>& args) {
-
- ShouldNotAbortOnUncaughtScope no_abort_scope(realm->env());
- TryCatchScope try_catch(realm->env());
-- Isolate::SafeForTerminationScope safe_for_termination(isolate);
-
- bool timed_out = false;
- bool received_signal = false;
-diff --git a/src/node_builtins.cc b/src/node_builtins.cc
-index 4bf80aa6cc6385dc376fd0a3538efc27fe5bd0a2..3e37aa8b0c9696cceb3f3cfab9721f38c74a2fba 100644
---- a/src/node_builtins.cc
-+++ b/src/node_builtins.cc
-@@ -267,7 +267,7 @@ MaybeLocal<Function> BuiltinLoader::LookupAndCompileInternal(
- std::string filename_s = std::string("node:") + id;
- Local<String> filename =
- OneByteString(isolate, filename_s.c_str(), filename_s.size());
-- ScriptOrigin origin(isolate, filename, 0, 0, true);
-+ ScriptOrigin origin(filename, 0, 0, true);
-
- BuiltinCodeCacheData cached_data{};
- {
-diff --git a/src/node_contextify.cc b/src/node_contextify.cc
-index 6456d87d4202c013aafe071adbac06852b3ae2c1..28ba7dbe66a44a43c39e3d75edf0be9513bcf732 100644
---- a/src/node_contextify.cc
-+++ b/src/node_contextify.cc
-@@ -877,16 +877,15 @@ void ContextifyScript::New(const FunctionCallbackInfo<Value>& args) {
- host_defined_options->Set(
- isolate, loader::HostDefinedOptions::kID, id_symbol);
-
-- ScriptOrigin origin(isolate,
-- filename,
-- line_offset, // line offset
-- column_offset, // column offset
-- true, // is cross origin
-- -1, // script id
-- Local<Value>(), // source map URL
-- false, // is opaque (?)
-- false, // is WASM
-- false, // is ES Module
-+ ScriptOrigin origin(filename,
-+ line_offset, // line offset
-+ column_offset, // column offset
-+ true, // is cross origin
-+ -1, // script id
-+ Local<Value>(), // source map URL
-+ false, // is opaque (?)
-+ false, // is WASM
-+ false, // is ES Module
- host_defined_options);
- ScriptCompiler::Source source(code, origin, cached_data);
- ScriptCompiler::CompileOptions compile_options =
-@@ -998,7 +997,7 @@ MaybeLocal<Function> CompileFunction(Local<Context> context,
- Local<String> filename,
- Local<String> content,
- std::vector<Local<String>>* parameters) {
-- ScriptOrigin script_origin(context->GetIsolate(), filename, 0, 0, true);
-+ ScriptOrigin script_origin(filename, 0, 0, true);
- ScriptCompiler::Source script_source(content, script_origin);
-
- return ScriptCompiler::CompileFunction(context,
-@@ -1108,7 +1107,6 @@ bool ContextifyScript::EvalMachine(Local<Context> context,
- }
-
- TryCatchScope try_catch(env);
-- Isolate::SafeForTerminationScope safe_for_termination(env->isolate());
- ContextifyScript* wrapped_script;
- ASSIGN_OR_RETURN_UNWRAP(&wrapped_script, args.This(), false);
- Local<UnboundScript> unbound_script =
-@@ -1286,8 +1284,7 @@ void ContextifyContext::CompileFunction(
- Local<PrimitiveArray> host_defined_options =
- GetHostDefinedOptions(isolate, id_symbol);
- ScriptCompiler::Source source =
-- GetCommonJSSourceInstance(isolate,
-- code,
-+ GetCommonJSSourceInstance(code,
- filename,
- line_offset,
- column_offset,
-@@ -1342,15 +1339,13 @@ void ContextifyContext::CompileFunction(
- }
-
- ScriptCompiler::Source ContextifyContext::GetCommonJSSourceInstance(
-- Isolate* isolate,
- Local<String> code,
- Local<String> filename,
- int line_offset,
- int column_offset,
- Local<PrimitiveArray> host_defined_options,
- ScriptCompiler::CachedData* cached_data) {
-- ScriptOrigin origin(isolate,
-- filename,
-+ ScriptOrigin origin(filename,
- line_offset, // line offset
- column_offset, // column offset
- true, // is cross origin
-@@ -1528,7 +1523,7 @@ void ContextifyContext::ContainsModuleSyntax(
- Local<PrimitiveArray> host_defined_options =
- GetHostDefinedOptions(isolate, id_symbol);
- ScriptCompiler::Source source = GetCommonJSSourceInstance(
-- isolate, code, filename, 0, 0, host_defined_options, nullptr);
-+ code, filename, 0, 0, host_defined_options, nullptr);
- ScriptCompiler::CompileOptions options = GetCompileOptions(source);
-
- std::vector<Local<String>> params = GetCJSParameters(env->isolate_data());
-@@ -1576,7 +1571,7 @@ void ContextifyContext::ContainsModuleSyntax(
- code,
- String::NewFromUtf8(isolate, "})();").ToLocalChecked());
- ScriptCompiler::Source wrapped_source = GetCommonJSSourceInstance(
-- isolate, code, filename, 0, 0, host_defined_options, nullptr);
-+ code, filename, 0, 0, host_defined_options, nullptr);
- std::ignore = ScriptCompiler::CompileFunction(
- context,
- &wrapped_source,
-@@ -1629,8 +1624,7 @@ static void CompileFunctionForCJSLoader(
-
- Local<Symbol> symbol = env->vm_dynamic_import_default_internal();
- Local<PrimitiveArray> hdo = GetHostDefinedOptions(isolate, symbol);
-- ScriptOrigin origin(isolate,
-- filename,
-+ ScriptOrigin origin(filename,
- 0, // line offset
- 0, // column offset
- true, // is cross origin
-diff --git a/src/node_contextify.h b/src/node_contextify.h
-index 517e3f44d324900222e1da961a4cd60bbb4a85f9..10715c7eb07715cc11e49734bd54747dad95f6a4 100644
---- a/src/node_contextify.h
-+++ b/src/node_contextify.h
-@@ -99,7 +99,6 @@ class ContextifyContext : public BaseObject {
- v8::Local<v8::Symbol> id_symbol,
- const errors::TryCatchScope& try_catch);
- static v8::ScriptCompiler::Source GetCommonJSSourceInstance(
-- v8::Isolate* isolate,
- v8::Local<v8::String> code,
- v8::Local<v8::String> filename,
- int line_offset,
-diff --git a/test/cctest/test_environment.cc b/test/cctest/test_environment.cc
-index 64e38c83006a004ebc3519a5e9f8b04263244514..14e82cc80ff73084fb43b2ef07febfd2667a0abc 100644
---- a/test/cctest/test_environment.cc
-+++ b/test/cctest/test_environment.cc
-@@ -620,12 +620,9 @@ TEST_F(EnvironmentTest, SetImmediateMicrotasks) {
-
- #ifndef _WIN32 // No SIGINT on Windows.
- TEST_F(NodeZeroIsolateTestFixture, CtrlCWithOnlySafeTerminationTest) {
-- // We need to go through the whole setup dance here because we want to
-- // set only_terminate_in_safe_scope.
- // Allocate and initialize Isolate.
- v8::Isolate::CreateParams create_params;
- create_params.array_buffer_allocator = allocator.get();
-- create_params.only_terminate_in_safe_scope = true;
- v8::Isolate* isolate = v8::Isolate::Allocate();
- CHECK_NOT_NULL(isolate);
- platform->RegisterIsolate(isolate, ¤t_loop);
diff --git a/patches/node/chore_add_context_to_context_aware_module_prevention.patch b/patches/node/chore_add_context_to_context_aware_module_prevention.patch
index b0119bd437..c74109225a 100644
--- a/patches/node/chore_add_context_to_context_aware_module_prevention.patch
+++ b/patches/node/chore_add_context_to_context_aware_module_prevention.patch
@@ -8,7 +8,7 @@ modules from being used in the renderer process. This should be upstreamed as
a customizable error message.
diff --git a/src/node_binding.cc b/src/node_binding.cc
-index 4e750be66452de47040e3a46555c062dfccf7807..5e1caeee18e447cc76b980df712521cf8b60e8da 100644
+index b5c0a93d83ab4d4f6792d0eb648e7198de874bcf..0fd01987c29b06b91944d18266ba67994c1fac45 100644
--- a/src/node_binding.cc
+++ b/src/node_binding.cc
@@ -4,6 +4,7 @@
@@ -19,7 +19,7 @@ index 4e750be66452de47040e3a46555c062dfccf7807..5e1caeee18e447cc76b980df712521cf
#include "util.h"
#include <string>
-@@ -483,7 +484,12 @@ void DLOpen(const FunctionCallbackInfo<Value>& args) {
+@@ -495,7 +496,12 @@ void DLOpen(const FunctionCallbackInfo<Value>& args) {
if (mp->nm_context_register_func == nullptr) {
if (env->force_context_aware()) {
dlib->Close();
diff --git a/patches/node/chore_allow_the_node_entrypoint_to_be_a_builtin_module.patch b/patches/node/chore_allow_the_node_entrypoint_to_be_a_builtin_module.patch
index db246d414e..23e2ee6694 100644
--- a/patches/node/chore_allow_the_node_entrypoint_to_be_a_builtin_module.patch
+++ b/patches/node/chore_allow_the_node_entrypoint_to_be_a_builtin_module.patch
@@ -8,10 +8,10 @@ they use themselves as the entry point. We should try to upstream some form
of this.
diff --git a/lib/internal/modules/cjs/loader.js b/lib/internal/modules/cjs/loader.js
-index 364469160af5e348f8890417de16a63c0d1dca67..75d5f58fe02fa8cfa7716ffaf761d567ab403a2c 100644
+index d49941881e6cfd8647a6d44a57e0daaf1c874702..f696fb263b356a76b87cd4b6c4b1a0fd60a84afd 100644
--- a/lib/internal/modules/cjs/loader.js
+++ b/lib/internal/modules/cjs/loader.js
-@@ -1441,6 +1441,13 @@ Module.prototype._compile = function(content, filename, loadAsESM = false) {
+@@ -1518,6 +1518,13 @@ Module.prototype._compile = function(content, filename, format) {
if (getOptionValue('--inspect-brk') && process._eval == null) {
if (!resolvedArgv) {
// We enter the repl if we're not given a filename argument.
@@ -26,10 +26,10 @@ index 364469160af5e348f8890417de16a63c0d1dca67..75d5f58fe02fa8cfa7716ffaf761d567
try {
resolvedArgv = Module._resolveFilename(process.argv[1], null, false);
diff --git a/lib/internal/process/pre_execution.js b/lib/internal/process/pre_execution.js
-index ea7afd52fab1cf3fde1674be1429a00562b714c0..02cfc8b3328fedb6306abf6c738bea772c674458 100644
+index cb96fd1bc4fcdce750ce241ee5f47f2ae39cfdc6..c46b270109697f7cc1683f8f9f463575e5040216 100644
--- a/lib/internal/process/pre_execution.js
+++ b/lib/internal/process/pre_execution.js
-@@ -247,12 +247,14 @@ function patchProcessObject(expandArgv1) {
+@@ -243,12 +243,14 @@ function patchProcessObject(expandArgv1) {
if (expandArgv1 && process.argv[1] &&
!StringPrototypeStartsWith(process.argv[1], '-')) {
// Expand process.argv[1] into a full path.
diff --git a/patches/node/chore_expose_importmoduledynamically_and.patch b/patches/node/chore_expose_importmoduledynamically_and.patch
index 18583f403a..53d3d0a6e0 100644
--- a/patches/node/chore_expose_importmoduledynamically_and.patch
+++ b/patches/node/chore_expose_importmoduledynamically_and.patch
@@ -11,7 +11,7 @@ its own blended handler between Node and Blink.
Not upstreamable.
diff --git a/lib/internal/modules/esm/utils.js b/lib/internal/modules/esm/utils.js
-index 150816057129c147c13ce044474f341581679f34..dd8627653265e22f55e67ec4a47641b20fba6c9d 100644
+index d393d4336a0c1e681e4f6b4e5c7cf2bcc5fc287e..807cb5172e0c2178b6c20e81f8175141d3a0284f 100644
--- a/lib/internal/modules/esm/utils.js
+++ b/lib/internal/modules/esm/utils.js
@@ -30,7 +30,7 @@ const {
@@ -40,10 +40,10 @@ index 150816057129c147c13ce044474f341581679f34..dd8627653265e22f55e67ec4a47641b2
/**
diff --git a/src/module_wrap.cc b/src/module_wrap.cc
-index eea74bed4bb8a980f99a9a1404c9a2df203ca09c..e862b51293135995c527c32aa3c3579780d7831c 100644
+index 48b61e8b7600701c4992a98ff802614ce915faee..4e9835e502a8d078a448aa4253f37de0f49f4854 100644
--- a/src/module_wrap.cc
+++ b/src/module_wrap.cc
-@@ -752,7 +752,7 @@ MaybeLocal<Module> ModuleWrap::ResolveModuleCallback(
+@@ -813,7 +813,7 @@ MaybeLocal<Module> ModuleWrap::ResolveModuleCallback(
return module->module_.Get(isolate);
}
@@ -52,7 +52,7 @@ index eea74bed4bb8a980f99a9a1404c9a2df203ca09c..e862b51293135995c527c32aa3c35797
Local<Context> context,
Local<v8::Data> host_defined_options,
Local<Value> resource_name,
-@@ -817,12 +817,13 @@ void ModuleWrap::SetImportModuleDynamicallyCallback(
+@@ -878,12 +878,13 @@ void ModuleWrap::SetImportModuleDynamicallyCallback(
Realm* realm = Realm::GetCurrent(args);
HandleScope handle_scope(isolate);
@@ -68,7 +68,7 @@ index eea74bed4bb8a980f99a9a1404c9a2df203ca09c..e862b51293135995c527c32aa3c35797
}
void ModuleWrap::HostInitializeImportMetaObjectCallback(
-@@ -864,13 +865,14 @@ void ModuleWrap::SetInitializeImportMetaObjectCallback(
+@@ -925,13 +926,14 @@ void ModuleWrap::SetInitializeImportMetaObjectCallback(
Realm* realm = Realm::GetCurrent(args);
Isolate* isolate = realm->isolate();
@@ -87,18 +87,18 @@ index eea74bed4bb8a980f99a9a1404c9a2df203ca09c..e862b51293135995c527c32aa3c35797
MaybeLocal<Value> ModuleWrap::SyntheticModuleEvaluationStepsCallback(
diff --git a/src/module_wrap.h b/src/module_wrap.h
-index 45a338b38e01c824f69ea59ee286130c67e9eddf..99bb079df11696fc3ba5e6bcca7e7a42818fe3d1 100644
+index 83b5793013cbc453cf92c0a006fc7be3c06ad276..90353954bc497cb4ae413dc134850f8abb4efc7c 100644
--- a/src/module_wrap.h
+++ b/src/module_wrap.h
-@@ -7,6 +7,7 @@
- #include <string>
+@@ -8,6 +8,7 @@
+ #include <unordered_map>
#include <vector>
#include "base_object.h"
+#include "node.h"
+ #include "v8-script.h"
namespace node {
-
-@@ -31,7 +32,14 @@ enum HostDefinedOptions : int {
+@@ -33,7 +34,14 @@ enum HostDefinedOptions : int {
kLength = 9,
};
@@ -114,20 +114,20 @@ index 45a338b38e01c824f69ea59ee286130c67e9eddf..99bb079df11696fc3ba5e6bcca7e7a42
public:
enum InternalFields {
kModuleSlot = BaseObject::kInternalFieldCount,
-@@ -68,6 +76,8 @@ class ModuleWrap : public BaseObject {
- return true;
- }
+@@ -91,6 +99,8 @@ class ModuleWrap : public BaseObject {
+ static void CreateRequiredModuleFacade(
+ const v8::FunctionCallbackInfo<v8::Value>& args);
+ static ModuleWrap* GetFromModule(node::Environment*, v8::Local<v8::Module>);
+
private:
ModuleWrap(Realm* realm,
v8::Local<v8::Object> object,
-@@ -110,7 +120,6 @@ class ModuleWrap : public BaseObject {
+@@ -129,7 +139,6 @@ class ModuleWrap : public BaseObject {
v8::Local<v8::String> specifier,
v8::Local<v8::FixedArray> import_attributes,
v8::Local<v8::Module> referrer);
- static ModuleWrap* GetFromModule(node::Environment*, v8::Local<v8::Module>);
v8::Global<v8::Module> module_;
- std::unordered_map<std::string, v8::Global<v8::Promise>> resolve_cache_;
+ std::unordered_map<std::string, v8::Global<v8::Object>> resolve_cache_;
diff --git a/patches/node/chore_remove_--no-harmony-atomics_related_code.patch b/patches/node/chore_remove_--no-harmony-atomics_related_code.patch
deleted file mode 100644
index cc52a3017c..0000000000
--- a/patches/node/chore_remove_--no-harmony-atomics_related_code.patch
+++ /dev/null
@@ -1,52 +0,0 @@
-From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
-From: Shelley Vohr <[email protected]>
-Date: Wed, 19 Apr 2023 14:13:23 +0200
-Subject: chore: remove --no-harmony-atomics related code
-
-This was removed in https://chromium-review.googlesource.com/c/v8/v8/+/4416459.
-
-This patch can be removed when Node.js upgrades to a version of V8 containing
-the above CL.
-
-diff --git a/lib/.eslintrc.yaml b/lib/.eslintrc.yaml
-index 74e867ace6207751a96b4da03802b50b620dbd7b..53ceabeb58f56ebd27e60fd49c362d26e361e6d8 100644
---- a/lib/.eslintrc.yaml
-+++ b/lib/.eslintrc.yaml
-@@ -30,10 +30,6 @@ rules:
- message: Use `const { AbortController } = require('internal/abort_controller');` instead of the global.
- - name: AbortSignal
- message: Use `const { AbortSignal } = require('internal/abort_controller');` instead of the global.
-- # Atomics is not available in primordials because it can be
-- # disabled with --no-harmony-atomics CLI flag.
-- - name: Atomics
-- message: Use `const { Atomics } = globalThis;` instead of the global.
- - name: Blob
- message: Use `const { Blob } = require('buffer');` instead of the global.
- - name: BroadcastChannel
-diff --git a/lib/internal/main/worker_thread.js b/lib/internal/main/worker_thread.js
-index 30f7a5f79e50fdeb4e1775a0e56dafa4c6908898..f7250985277c4127425ef36dff566c1fe06603e2 100644
---- a/lib/internal/main/worker_thread.js
-+++ b/lib/internal/main/worker_thread.js
-@@ -112,7 +112,7 @@ port.on('message', (message) => {
-
- require('internal/worker').assignEnvironmentData(environmentData);
-
-- if (SharedArrayBuffer !== undefined && Atomics !== undefined) {
-+ if (SharedArrayBuffer !== undefined) {
- // The counter is only passed to the workers created by the main thread,
- // not to workers created by other workers.
- let cachedCwd = '';
-diff --git a/lib/internal/worker.js b/lib/internal/worker.js
-index 401bc43550ea7f19847dfd588e3fba0507243905..560f69c6c2de2bd976bcd62cd7ac9c770b838446 100644
---- a/lib/internal/worker.js
-+++ b/lib/internal/worker.js
-@@ -101,8 +101,7 @@ let cwdCounter;
- const environmentData = new SafeMap();
-
- // SharedArrayBuffers can be disabled with --no-harmony-sharedarraybuffer.
--// Atomics can be disabled with --no-harmony-atomics.
--if (isMainThread && SharedArrayBuffer !== undefined && Atomics !== undefined) {
-+if (isMainThread && SharedArrayBuffer !== undefined) {
- cwdCounter = new Uint32Array(new SharedArrayBuffer(4));
- const originalChdir = process.chdir;
- process.chdir = function(path) {
diff --git a/patches/node/chore_remove_use_of_deprecated_kmaxlength.patch b/patches/node/chore_remove_use_of_deprecated_kmaxlength.patch
deleted file mode 100644
index ded4d1f30d..0000000000
--- a/patches/node/chore_remove_use_of_deprecated_kmaxlength.patch
+++ /dev/null
@@ -1,35 +0,0 @@
-From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
-From: Charles Kerr <[email protected]>
-Date: Tue, 17 Oct 2023 10:58:41 -0500
-Subject: chore: remove use of deprecated kMaxLength
-
-https://chromium-review.googlesource.com/c/v8/v8/+/4935412
-
-This patch can be removed when upstream moves to kMaxByteLength
-
-diff --git a/src/node_buffer.h b/src/node_buffer.h
-index 606a6f5caa3b11b6d2a9068ed2fd65800530a5eb..080dcce21da05ccea398d8a856deb397b1ac8b07 100644
---- a/src/node_buffer.h
-+++ b/src/node_buffer.h
-@@ -29,7 +29,7 @@ namespace node {
-
- namespace Buffer {
-
--static const size_t kMaxLength = v8::TypedArray::kMaxLength;
-+static const size_t kMaxLength = v8::TypedArray::kMaxByteLength;
-
- typedef void (*FreeCallback)(char* data, void* hint);
-
-diff --git a/src/node_errors.h b/src/node_errors.h
-index 1662491bac44311421eeb7ee35bb47c025162abf..a62b18e832986ee38d93b412b36020a2c22255a9 100644
---- a/src/node_errors.h
-+++ b/src/node_errors.h
-@@ -230,7 +230,7 @@ inline v8::Local<v8::Object> ERR_BUFFER_TOO_LARGE(v8::Isolate* isolate) {
- char message[128];
- snprintf(message, sizeof(message),
- "Cannot create a Buffer larger than 0x%zx bytes",
-- v8::TypedArray::kMaxLength);
-+ v8::TypedArray::kMaxByteLength);
- return ERR_BUFFER_TOO_LARGE(isolate, message);
- }
-
diff --git a/patches/node/ci_ensure_node_tests_set_electron_run_as_node.patch b/patches/node/ci_ensure_node_tests_set_electron_run_as_node.patch
index 05a70dd710..ef4d76a3e8 100644
--- a/patches/node/ci_ensure_node_tests_set_electron_run_as_node.patch
+++ b/patches/node/ci_ensure_node_tests_set_electron_run_as_node.patch
@@ -7,53 +7,6 @@ Some node tests / test fixtures spawn other tests that clobber env,
which causes the `ELECTRON_RUN_AS_NODE` variable to be lost. This patch
re-injects it.
-diff --git a/test/fixtures/errors/promise_unhandled_warn_with_error.snapshot b/test/fixtures/errors/promise_unhandled_warn_with_error.snapshot
-index d7f1aa2f72007f6f70b6b66b81913f39e5678d2f..e091b1575954f5dc82a05a5d200ee028e053f616 100644
---- a/test/fixtures/errors/promise_unhandled_warn_with_error.snapshot
-+++ b/test/fixtures/errors/promise_unhandled_warn_with_error.snapshot
-@@ -6,5 +6,5 @@
- at *
- at *
- at *
--(Use `node --trace-warnings ...` to show where the warning was created)
-+(Use `* --trace-warnings ...` to show where the warning was created)
- (node:*) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https:*nodejs.org*api*cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
-diff --git a/test/fixtures/errors/throw_error_with_getter_throw.snapshot b/test/fixtures/errors/throw_error_with_getter_throw.snapshot
-index 30bbb336a22aaffbd63333f297eb598a8f501d75..1786f96f19856cdc43e0e86c8271a845e337359f 100644
---- a/test/fixtures/errors/throw_error_with_getter_throw.snapshot
-+++ b/test/fixtures/errors/throw_error_with_getter_throw.snapshot
-@@ -3,6 +3,6 @@
- throw { * eslint-disable-line no-throw-literal
- ^
- [object Object]
--(Use `node --trace-uncaught ...` to show where the exception was thrown)
-+(Use `* --trace-uncaught ...` to show where the exception was thrown)
-
- Node.js *
-diff --git a/test/fixtures/errors/throw_null.snapshot b/test/fixtures/errors/throw_null.snapshot
-index 88494ec6832205b30e7ae159708112a45494834c..1a1191ca9ced90936b764c32c1c334cce114b46e 100644
---- a/test/fixtures/errors/throw_null.snapshot
-+++ b/test/fixtures/errors/throw_null.snapshot
-@@ -3,6 +3,6 @@
- throw null;
- ^
- null
--(Use `node --trace-uncaught ...` to show where the exception was thrown)
-+(Use `* --trace-uncaught ...` to show where the exception was thrown)
-
- Node.js *
-diff --git a/test/fixtures/errors/throw_undefined.snapshot b/test/fixtures/errors/throw_undefined.snapshot
-index baae7384453373f3a005b4f85abb702a4c165f98..b6b6060b17839f3452aa915c12bd5174b7585414 100644
---- a/test/fixtures/errors/throw_undefined.snapshot
-+++ b/test/fixtures/errors/throw_undefined.snapshot
-@@ -3,6 +3,6 @@
- throw undefined;
- ^
- undefined
--(Use `node --trace-uncaught ...` to show where the exception was thrown)
-+(Use `* --trace-uncaught ...` to show where the exception was thrown)
-
- Node.js *
diff --git a/test/fixtures/test-runner/output/arbitrary-output-colored.js b/test/fixtures/test-runner/output/arbitrary-output-colored.js
index af23e674cb361ed81dafa22670d5633559cd1144..1dd59990cb7cdba8aecf4f499ee6b92e7cd41b30 100644
--- a/test/fixtures/test-runner/output/arbitrary-output-colored.js
@@ -67,32 +20,3 @@ index af23e674cb361ed81dafa22670d5633559cd1144..1dd59990cb7cdba8aecf4f499ee6b92e
+ await once(spawn(process.execPath, ['-r', reset, '--test', test], { stdio: 'inherit', env: { ELECTRON_RUN_AS_NODE: 1 }}), 'exit');
+ await once(spawn(process.execPath, ['-r', reset, '--test', '--test-reporter', 'tap', test], { stdio: 'inherit', env: { ELECTRON_RUN_AS_NODE: 1 } }), 'exit');
})().then(common.mustCall());
-diff --git a/test/parallel/test-node-output-errors.mjs b/test/parallel/test-node-output-errors.mjs
-index 84f20a77dda367fe1ada8d616c7b6813d39efd43..9bebb256776c5be155a8de07abbe4284bc8dad8a 100644
---- a/test/parallel/test-node-output-errors.mjs
-+++ b/test/parallel/test-node-output-errors.mjs
-@@ -3,6 +3,7 @@ import * as fixtures from '../common/fixtures.mjs';
- import * as snapshot from '../common/assertSnapshot.js';
- import * as os from 'node:os';
- import { describe, it } from 'node:test';
-+import { basename } from 'node:path';
- import { pathToFileURL } from 'node:url';
-
- const skipForceColors =
-@@ -20,13 +21,15 @@ function replaceForceColorsStackTrace(str) {
-
- describe('errors output', { concurrency: true }, () => {
- function normalize(str) {
-+ const baseName = basename(process.argv0 || 'node', '.exe');
- return str.replaceAll(snapshot.replaceWindowsPaths(process.cwd()), '')
- .replaceAll(pathToFileURL(process.cwd()).pathname, '')
- .replaceAll('//', '*')
- .replaceAll(/\/(\w)/g, '*$1')
- .replaceAll('*test*', '*')
- .replaceAll('*fixtures*errors*', '*')
-- .replaceAll('file:**', 'file:*/');
-+ .replaceAll('file:**', 'file:*/')
-+ .replaceAll(`${baseName} --`, '* --');
- }
-
- function normalizeNoNumbers(str) {
diff --git a/patches/node/cli_remove_deprecated_v8_flag.patch b/patches/node/cli_remove_deprecated_v8_flag.patch
index 0a4e8eb25b..8a9772f144 100644
--- a/patches/node/cli_remove_deprecated_v8_flag.patch
+++ b/patches/node/cli_remove_deprecated_v8_flag.patch
@@ -18,10 +18,10 @@ Reviewed-By: Michaël Zasso <[email protected]>
Reviewed-By: Yagiz Nizipli <[email protected]>
diff --git a/doc/api/cli.md b/doc/api/cli.md
-index ed0a43306e87962cf0e756d9e059ec5c08ad674b..7ada2802b2590e78fa5b9847935866b743cf94ed 100644
+index 0cfed4a4a91a3d3fb5aee6c9a4db3405ba836565..61d980a12fcf7c799e726e1462c65ce478a8ed0c 100644
--- a/doc/api/cli.md
+++ b/doc/api/cli.md
-@@ -2868,7 +2868,6 @@ V8 options that are allowed are:
+@@ -3151,7 +3151,6 @@ V8 options that are allowed are:
* `--disallow-code-generation-from-strings`
* `--enable-etw-stack-walking`
* `--expose-gc`
@@ -30,10 +30,10 @@ index ed0a43306e87962cf0e756d9e059ec5c08ad674b..7ada2802b2590e78fa5b9847935866b7
* `--jitless`
* `--max-old-space-size`
diff --git a/src/node_options.cc b/src/node_options.cc
-index 4e3c82e9528b04fd1a0cc99d30fb885e4b224bc9..38e173f72b446aa2db07f676b6ece26247bbf56b 100644
+index 4b3f7751db2871c8ce76b197a84a2417097030ea..21e53e1053fe2e4194d91b27a726d3a1306b1683 100644
--- a/src/node_options.cc
+++ b/src/node_options.cc
-@@ -866,11 +866,6 @@ PerIsolateOptionsParser::PerIsolateOptionsParser(
+@@ -922,11 +922,6 @@ PerIsolateOptionsParser::PerIsolateOptionsParser(
"disallow eval and friends",
V8Option{},
kAllowedInEnvvar);
@@ -46,7 +46,7 @@ index 4e3c82e9528b04fd1a0cc99d30fb885e4b224bc9..38e173f72b446aa2db07f676b6ece262
"disable runtime allocation of executable memory",
V8Option{},
diff --git a/test/parallel/test-cli-node-options.js b/test/parallel/test-cli-node-options.js
-index 8d614e607177cdd922fef65a85a2ccdcf54116c0..146df3a21a0551e910c46248d2fd97dde8896164 100644
+index e898a81af09ca6852ddc866310e5b8e0dc82971b..22d5a342df5d55f065383a6ebe1aebe59dc0f8d2 100644
--- a/test/parallel/test-cli-node-options.js
+++ b/test/parallel/test-cli-node-options.js
@@ -70,7 +70,6 @@ if (common.hasCrypto) {
diff --git a/patches/node/deprecate_vector_v8_local_in_v8.patch b/patches/node/deprecate_vector_v8_local_in_v8.patch
deleted file mode 100644
index 7462efb97f..0000000000
--- a/patches/node/deprecate_vector_v8_local_in_v8.patch
+++ /dev/null
@@ -1,25 +0,0 @@
-From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
-From: Shelley Vohr <[email protected]>
-Date: Sun, 10 Mar 2024 16:59:30 +0100
-Subject: Deprecate vector<v8::Local> in v8
-
-Adapts for changes in https://chromium-review.googlesource.com/c/v8/v8/+/4866222.
-
-This patch can be removed when Electron upgrades to a version of Node.js that
-contains the above CL.
-
-diff --git a/src/module_wrap.cc b/src/module_wrap.cc
-index e862b51293135995c527c32aa3c3579780d7831c..ff658ec88e5161cd66536ee6e95dba675b16eccc 100644
---- a/src/module_wrap.cc
-+++ b/src/module_wrap.cc
-@@ -186,7 +186,9 @@ void ModuleWrap::New(const FunctionCallbackInfo<Value>& args) {
- export_names[i] = export_name_val.As<String>();
- }
-
-- module = Module::CreateSyntheticModule(isolate, url, export_names,
-+
-+ module = Module::CreateSyntheticModule(isolate, url,
-+ v8::MemorySpan<const Local<String>>(export_names.begin(), export_names.end()),
- SyntheticModuleEvaluationStepsCallback);
- } else {
- ScriptCompiler::CachedData* cached_data = nullptr;
diff --git a/patches/node/enable_crashpad_linux_node_processes.patch b/patches/node/enable_crashpad_linux_node_processes.patch
index 931c066507..6f403b6ac8 100644
--- a/patches/node/enable_crashpad_linux_node_processes.patch
+++ b/patches/node/enable_crashpad_linux_node_processes.patch
@@ -8,7 +8,7 @@ to child processes spawned with `ELECTRON_RUN_AS_NODE` which is used
by the crashpad client to connect with the handler process.
diff --git a/lib/child_process.js b/lib/child_process.js
-index 48870b35ad0f3411f2d509b12d92a9e0d20046f9..e7ef454d2d71207ae7b2788a437b82bf7732716e 100644
+index 580a441a803bdd0b57871c0cdd8af576f11609b1..755712d24219de7ffe491957d941df7c8cf7baad 100644
--- a/lib/child_process.js
+++ b/lib/child_process.js
@@ -61,6 +61,7 @@ let debug = require('internal/util/debuglog').debuglog(
@@ -19,7 +19,7 @@ index 48870b35ad0f3411f2d509b12d92a9e0d20046f9..e7ef454d2d71207ae7b2788a437b82bf
const {
AbortError,
-@@ -154,7 +155,6 @@ function fork(modulePath, args = [], options) {
+@@ -153,7 +154,6 @@ function fork(modulePath, args = [], options) {
ArrayPrototypeSplice(execArgv, index - 1, 2);
}
}
@@ -27,7 +27,7 @@ index 48870b35ad0f3411f2d509b12d92a9e0d20046f9..e7ef454d2d71207ae7b2788a437b82bf
args = [...execArgv, modulePath, ...args];
if (typeof options.stdio === 'string') {
-@@ -618,6 +618,22 @@ function normalizeSpawnArguments(file, args, options) {
+@@ -617,6 +617,22 @@ function normalizeSpawnArguments(file, args, options) {
'options.windowsVerbatimArguments');
}
@@ -50,7 +50,7 @@ index 48870b35ad0f3411f2d509b12d92a9e0d20046f9..e7ef454d2d71207ae7b2788a437b82bf
if (options.shell) {
validateArgumentNullCheck(options.shell, 'options.shell');
const command = ArrayPrototypeJoin([file, ...args], ' ');
-@@ -651,7 +667,6 @@ function normalizeSpawnArguments(file, args, options) {
+@@ -650,7 +666,6 @@ function normalizeSpawnArguments(file, args, options) {
ArrayPrototypeUnshift(args, file);
}
diff --git a/patches/node/esm_drop_support_for_import_assertions.patch b/patches/node/esm_drop_support_for_import_assertions.patch
deleted file mode 100644
index ff45e7c990..0000000000
--- a/patches/node/esm_drop_support_for_import_assertions.patch
+++ /dev/null
@@ -1,53 +0,0 @@
-From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
-From: =?UTF-8?q?Nicol=C3=B2=20Ribaudo?= <[email protected]>
-Date: Fri, 19 Apr 2024 02:01:24 +0200
-Subject: esm: drop support for import assertions
-
-This patch removes support for the `assert` keyword
-for import attributes. It was an old variant of the
-proposal that was only shipped in V8 and no other
-engine, and that has then been replaced by the `with`
-keyword.
-
-Chrome is planning to remove support for `assert`
-in version 126, which will be released in June.
-
-Node.js already supports the `with` keyword for
-import attributes, and this patch does not change that.
-
-PR-URL: https://github.com/nodejs/node/pull/52104
-Reviewed-By: Matteo Collina <[email protected]>
-Reviewed-By: Joyee Cheung <[email protected]>
-Reviewed-By: Yagiz Nizipli <[email protected]>
-Reviewed-By: Ethan Arrowood <[email protected]>
-Reviewed-By: Geoffrey Booth <[email protected]>
-(cherry picked from commit 25c79f333104d1feb0d84794d5bcdb4227177c9b)
-
-esm: remove --no-import-harmony-assertions
-
-It is off by default now.
-
-PR-URL: https://github.com/nodejs/node/pull/54890
-Reviewed-By: Luigi Pinca <[email protected]>
-Reviewed-By: Yagiz Nizipli <[email protected]>
-Reviewed-By: Antoine du Hamel <[email protected]>
-Reviewed-By: James M Snell <[email protected]>
-(cherry picked from commit 8fd90938f923ef2a04bb3ebb08b89568fe6fd4ee)
-
-diff --git a/src/node.cc b/src/node.cc
-index 9f6f8e53abd7e447d88c187c447431a0d96cd150..4415f18ecbd84c1f41e0febbf2446fb636242d58 100644
---- a/src/node.cc
-+++ b/src/node.cc
-@@ -778,12 +778,6 @@ static ExitCode ProcessGlobalArgsInternal(std::vector<std::string>* args,
- return ExitCode::kInvalidCommandLineArgument2;
- }
-
-- // TODO(aduh95): remove this when the harmony-import-assertions flag
-- // is removed in V8.
-- if (std::find(v8_args.begin(), v8_args.end(),
-- "--no-harmony-import-assertions") == v8_args.end()) {
-- v8_args.emplace_back("--harmony-import-assertions");
-- }
- // TODO(aduh95): remove this when the harmony-import-attributes flag
- // is removed in V8.
- if (std::find(v8_args.begin(),
diff --git a/patches/node/expose_get_builtin_module_function.patch b/patches/node/expose_get_builtin_module_function.patch
index 4a9b451241..39d3c031d4 100644
--- a/patches/node/expose_get_builtin_module_function.patch
+++ b/patches/node/expose_get_builtin_module_function.patch
@@ -9,10 +9,10 @@ modules to sandboxed renderers.
TODO(codebytere): remove and replace with a public facing API.
diff --git a/src/node_binding.cc b/src/node_binding.cc
-index 6b0297d8984ccb34b8d0019fedd1307d48cf49f8..4e750be66452de47040e3a46555c062dfccf7807 100644
+index c2ef9b36d5b2967c798c123b6cbbd099b15c2791..b5c0a93d83ab4d4f6792d0eb648e7198de874bcf 100644
--- a/src/node_binding.cc
+++ b/src/node_binding.cc
-@@ -641,6 +641,10 @@ void GetInternalBinding(const FunctionCallbackInfo<Value>& args) {
+@@ -653,6 +653,10 @@ void GetInternalBinding(const FunctionCallbackInfo<Value>& args) {
args.GetReturnValue().Set(exports);
}
@@ -24,10 +24,10 @@ index 6b0297d8984ccb34b8d0019fedd1307d48cf49f8..4e750be66452de47040e3a46555c062d
Environment* env = Environment::GetCurrent(args);
diff --git a/src/node_binding.h b/src/node_binding.h
-index 7256bf2bbcf73214a25e61156305cc212b6f2451..d129981ad8588376eeee61155964062f624695d6 100644
+index eb1364cb01a2bea52bce768056e73b0f3a86ae35..d421a2773403e7b22fcca2fcf8275ef2d9654c55 100644
--- a/src/node_binding.h
+++ b/src/node_binding.h
-@@ -137,6 +137,8 @@ void GetInternalBinding(const v8::FunctionCallbackInfo<v8::Value>& args);
+@@ -146,6 +146,8 @@ void GetInternalBinding(const v8::FunctionCallbackInfo<v8::Value>& args);
void GetLinkedBinding(const v8::FunctionCallbackInfo<v8::Value>& args);
void DLOpen(const v8::FunctionCallbackInfo<v8::Value>& args);
diff --git a/patches/node/feat_add_uv_loop_interrupt_on_io_change_option_to_uv_loop_configure.patch b/patches/node/feat_add_uv_loop_interrupt_on_io_change_option_to_uv_loop_configure.patch
index a1b2774b5c..68284309f8 100644
--- a/patches/node/feat_add_uv_loop_interrupt_on_io_change_option_to_uv_loop_configure.patch
+++ b/patches/node/feat_add_uv_loop_interrupt_on_io_change_option_to_uv_loop_configure.patch
@@ -26,7 +26,7 @@ index 0f5ddfb3ca21b7e5b38d0a4ce4b9e77387597199..ba815202fb157aa82859ec0518523cf6
.. c:function:: int uv_loop_close(uv_loop_t* loop)
diff --git a/deps/uv/include/uv.h b/deps/uv/include/uv.h
-index 02397dd0fdd43d51f86c0dde9a62046702f12bdb..3375600023e39ddacf62cc17deb4f206db942084 100644
+index a62b3fa69b1087847f37c7093954e19a07959b74..7f48b7daa87d1a5b14bc6f641b60f21263fa5ec3 100644
--- a/deps/uv/include/uv.h
+++ b/deps/uv/include/uv.h
@@ -260,7 +260,8 @@ typedef struct uv_metrics_s uv_metrics_t;
@@ -101,10 +101,10 @@ index 0ff2669e30a628dbb2df9e28ba14b38cf14114e5..117190ef26338944b78dbed7380c631d
static int uv__async_start(uv_loop_t* loop) {
int pipefd[2];
diff --git a/deps/uv/src/unix/core.c b/deps/uv/src/unix/core.c
-index 25c5181f370e94983e8a5f797f02f7a8dc207e00..f4d9059796d2c65339a5d48ecb273b09d9364d21 100644
+index 965e7f775250cf9899266bc3aaf62eda69367264..45b3dec662b093a61af356e431416530b35343d2 100644
--- a/deps/uv/src/unix/core.c
+++ b/deps/uv/src/unix/core.c
-@@ -926,6 +926,9 @@ void uv__io_start(uv_loop_t* loop, uv__io_t* w, unsigned int events) {
+@@ -927,6 +927,9 @@ void uv__io_start(uv_loop_t* loop, uv__io_t* w, unsigned int events) {
loop->watchers[w->fd] = w;
loop->nfds++;
}
@@ -114,7 +114,7 @@ index 25c5181f370e94983e8a5f797f02f7a8dc207e00..f4d9059796d2c65339a5d48ecb273b09
}
-@@ -957,6 +960,9 @@ void uv__io_stop(uv_loop_t* loop, uv__io_t* w, unsigned int events) {
+@@ -958,6 +961,9 @@ void uv__io_stop(uv_loop_t* loop, uv__io_t* w, unsigned int events) {
}
else if (uv__queue_empty(&w->watcher_queue))
uv__queue_insert_tail(&loop->watcher_queue, &w->watcher_queue);
@@ -124,7 +124,7 @@ index 25c5181f370e94983e8a5f797f02f7a8dc207e00..f4d9059796d2c65339a5d48ecb273b09
}
-@@ -973,6 +979,9 @@ void uv__io_close(uv_loop_t* loop, uv__io_t* w) {
+@@ -974,6 +980,9 @@ void uv__io_close(uv_loop_t* loop, uv__io_t* w) {
void uv__io_feed(uv_loop_t* loop, uv__io_t* w) {
if (uv__queue_empty(&w->pending_queue))
uv__queue_insert_tail(&loop->pending_queue, &w->pending_queue);
@@ -241,7 +241,7 @@ index e9885a0f1ff3890a8d957c8793e22b01cedc0e97..ae3d09878253fe7169ad7b74b3faea02
return -1;
}
diff --git a/deps/uv/test/test-embed.c b/deps/uv/test/test-embed.c
-index bbe56e176db17a502d7f3864ba529212f553590a..b0da9d1cddc69428e9fb3379d1338cf893ab93d2 100644
+index 6e9917239aa5626dd56fffd6eb2469d3e63224bf..b0da9d1cddc69428e9fb3379d1338cf893ab93d2 100644
--- a/deps/uv/test/test-embed.c
+++ b/deps/uv/test/test-embed.c
@@ -25,54 +25,184 @@
@@ -278,7 +278,7 @@ index bbe56e176db17a502d7f3864ba529212f553590a..b0da9d1cddc69428e9fb3379d1338cf8
-static void thread_main(void* arg) {
- ASSERT_LE(0, uv_barrier_wait(&barrier));
- uv_sleep(250);
-- ASSERT_EQ(0, uv_async_send(&async));
+- ASSERT_OK(uv_async_send(&async));
-}
+static uv_timer_t main_timer;
+static int main_timer_called;
@@ -333,9 +333,9 @@ index bbe56e176db17a502d7f3864ba529212f553590a..b0da9d1cddc69428e9fb3379d1338cf8
- uv_loop_t* loop;
-
- loop = uv_default_loop();
-- ASSERT_EQ(0, uv_async_init(loop, &async, async_cb));
-- ASSERT_EQ(0, uv_barrier_init(&barrier, 2));
-- ASSERT_EQ(0, uv_thread_create(&thread, thread_main, NULL));
+- ASSERT_OK(uv_async_init(loop, &async, async_cb));
+- ASSERT_OK(uv_barrier_init(&barrier, 2));
+- ASSERT_OK(uv_thread_create(&thread, thread_main, NULL));
- ASSERT_LE(0, uv_barrier_wait(&barrier));
-
- while (uv_loop_alive(loop)) {
@@ -457,7 +457,7 @@ index bbe56e176db17a502d7f3864ba529212f553590a..b0da9d1cddc69428e9fb3379d1338cf8
+ uv_timer_init(&external_loop, &external_timer);
+ uv_timer_start(&external_timer, external_timer_cb, 100, 0);
-- ASSERT_EQ(0, uv_thread_join(&thread));
+- ASSERT_OK(uv_thread_join(&thread));
- uv_barrier_destroy(&barrier);
+ run_loop();
+ ASSERT_EQ(main_timer_called, 1);
@@ -465,10 +465,10 @@ index bbe56e176db17a502d7f3864ba529212f553590a..b0da9d1cddc69428e9fb3379d1338cf8
MAKE_VALGRIND_HAPPY(loop);
return 0;
diff --git a/deps/uv/test/test-list.h b/deps/uv/test/test-list.h
-index 78ff9c2d1621676feab5d357609970cdf1ba5864..204160f324ad1a80c9b042e62c4bedcb745666ba 100644
+index d30f02faa8515ca3a995490d53f2e85fda11c6a2..a392f5e3d701b0d973db2bbc6553977ce55a8775 100644
--- a/deps/uv/test/test-list.h
+++ b/deps/uv/test/test-list.h
-@@ -273,6 +273,7 @@ TEST_DECLARE (process_priority)
+@@ -276,6 +276,7 @@ TEST_DECLARE (process_priority)
TEST_DECLARE (has_ref)
TEST_DECLARE (active)
TEST_DECLARE (embed)
@@ -476,7 +476,7 @@ index 78ff9c2d1621676feab5d357609970cdf1ba5864..204160f324ad1a80c9b042e62c4bedcb
TEST_DECLARE (async)
TEST_DECLARE (async_null_cb)
TEST_DECLARE (eintr_handling)
-@@ -894,6 +895,7 @@ TASK_LIST_START
+@@ -906,6 +907,7 @@ TASK_LIST_START
TEST_ENTRY (active)
TEST_ENTRY (embed)
diff --git a/patches/node/fix_-wextra-semi_errors_in_nghttp2_helper_h.patch b/patches/node/fix_-wextra-semi_errors_in_nghttp2_helper_h.patch
new file mode 100644
index 0000000000..238db21385
--- /dev/null
+++ b/patches/node/fix_-wextra-semi_errors_in_nghttp2_helper_h.patch
@@ -0,0 +1,60 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: Shelley Vohr <[email protected]>
+Date: Wed, 16 Oct 2024 16:09:37 +0200
+Subject: fix: -Wextra-semi errors in nghttp2_helper.h
+
+Introduced in https://github.com/nodejs/node/pull/52966
+
+Upstreamed in https://github.com/nghttp2/nghttp2/pull/2258
+
+diff --git a/deps/nghttp2/lib/nghttp2_helper.h b/deps/nghttp2/lib/nghttp2_helper.h
+index 89b0d4f535db795cd1df582475c02b2f4d1ac98f..f5de6290dab0e17ae3aff10230dd8ad7414f9631 100644
+--- a/deps/nghttp2/lib/nghttp2_helper.h
++++ b/deps/nghttp2/lib/nghttp2_helper.h
+@@ -38,28 +38,28 @@
+ #define nghttp2_max_def(SUFFIX, T) \
+ static inline T nghttp2_max_##SUFFIX(T a, T b) { return a < b ? b : a; }
+
+-nghttp2_max_def(int8, int8_t);
+-nghttp2_max_def(int16, int16_t);
+-nghttp2_max_def(int32, int32_t);
+-nghttp2_max_def(int64, int64_t);
+-nghttp2_max_def(uint8, uint8_t);
+-nghttp2_max_def(uint16, uint16_t);
+-nghttp2_max_def(uint32, uint32_t);
+-nghttp2_max_def(uint64, uint64_t);
+-nghttp2_max_def(size, size_t);
++nghttp2_max_def(int8, int8_t)
++nghttp2_max_def(int16, int16_t)
++nghttp2_max_def(int32, int32_t)
++nghttp2_max_def(int64, int64_t)
++nghttp2_max_def(uint8, uint8_t)
++nghttp2_max_def(uint16, uint16_t)
++nghttp2_max_def(uint32, uint32_t)
++nghttp2_max_def(uint64, uint64_t)
++nghttp2_max_def(size, size_t)
+
+ #define nghttp2_min_def(SUFFIX, T) \
+ static inline T nghttp2_min_##SUFFIX(T a, T b) { return a < b ? a : b; }
+
+-nghttp2_min_def(int8, int8_t);
+-nghttp2_min_def(int16, int16_t);
+-nghttp2_min_def(int32, int32_t);
+-nghttp2_min_def(int64, int64_t);
+-nghttp2_min_def(uint8, uint8_t);
+-nghttp2_min_def(uint16, uint16_t);
+-nghttp2_min_def(uint32, uint32_t);
+-nghttp2_min_def(uint64, uint64_t);
+-nghttp2_min_def(size, size_t);
++nghttp2_min_def(int8, int8_t)
++nghttp2_min_def(int16, int16_t)
++nghttp2_min_def(int32, int32_t)
++nghttp2_min_def(int64, int64_t)
++nghttp2_min_def(uint8, uint8_t)
++nghttp2_min_def(uint16, uint16_t)
++nghttp2_min_def(uint32, uint32_t)
++nghttp2_min_def(uint64, uint64_t)
++nghttp2_min_def(size, size_t)
+
+ #define lstreq(A, B, N) ((sizeof((A)) - 1) == (N) && memcmp((A), (B), (N)) == 0)
+
diff --git a/patches/node/fix_account_for_createexternalizablestring_v8_global.patch b/patches/node/fix_account_for_createexternalizablestring_v8_global.patch
deleted file mode 100644
index d0dc5f5e72..0000000000
--- a/patches/node/fix_account_for_createexternalizablestring_v8_global.patch
+++ /dev/null
@@ -1,23 +0,0 @@
-From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
-From: Shelley Vohr <[email protected]>
-Date: Tue, 23 May 2023 18:21:17 +0200
-Subject: fix: account for createExternalizableString V8 global
-
-Introduced in https://chromium-review.googlesource.com/c/v8/v8/+/4531903.
-
-This patch can be removed when Node.js upgrades to a version of V8 with the above
-CL - they'll need to make the same change.
-
-diff --git a/test/parallel/test-fs-write.js b/test/parallel/test-fs-write.js
-index 59b83f531cf0a60f960d0096aea70854f45bd629..9dcc35987a4757ea090e81c7de38a6af5bc3182f 100644
---- a/test/parallel/test-fs-write.js
-+++ b/test/parallel/test-fs-write.js
-@@ -38,7 +38,7 @@ const constants = fs.constants;
- const { externalizeString, isOneByteString } = global;
-
- // Account for extra globals exposed by --expose_externalize_string.
--common.allowGlobals(externalizeString, isOneByteString, global.x);
-+common.allowGlobals(createExternalizableString, externalizeString, isOneByteString, global.x);
-
- {
- const expected = 'ümlaut sechzig'; // Must be a unique string.
diff --git a/patches/node/fix_adapt_debugger_tests_for_upstream_v8_changes.patch b/patches/node/fix_adapt_debugger_tests_for_upstream_v8_changes.patch
deleted file mode 100644
index 978b11d75f..0000000000
--- a/patches/node/fix_adapt_debugger_tests_for_upstream_v8_changes.patch
+++ /dev/null
@@ -1,82 +0,0 @@
-From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
-From: Shelley Vohr <[email protected]>
-Date: Wed, 29 Mar 2023 09:55:47 +0200
-Subject: fix: adapt debugger tests for upstream v8 changes
-
-Updates debugger tests to conform to changes in https://chromium-review.googlesource.com/c/v8/v8/+/4290476
-
-This can be removed when Node.js updates to at least V8 11.4.
-
-diff --git a/test/common/debugger.js b/test/common/debugger.js
-index 4aff5b9a0f74d99f8f605b68631f820e282091ab..d5d77fc7c648ddb45225f04c6cf23f9816b2186d 100644
---- a/test/common/debugger.js
-+++ b/test/common/debugger.js
-@@ -4,7 +4,7 @@ const spawn = require('child_process').spawn;
-
- const BREAK_MESSAGE = new RegExp('(?:' + [
- 'assert', 'break', 'break on start', 'debugCommand',
-- 'exception', 'other', 'promiseRejection',
-+ 'exception', 'other', 'promiseRejection', 'step',
- ].join('|') + ') in', 'i');
-
- let TIMEOUT = common.platformTimeout(5000);
-@@ -121,13 +121,13 @@ function startCLI(args, flags = [], spawnOpts = {}) {
- get breakInfo() {
- const output = this.output;
- const breakMatch =
-- output.match(/break (?:on start )?in ([^\n]+):(\d+)\n/i);
-+ output.match(/(step |break (?:on start )?)in ([^\n]+):(\d+)\n/i);
-
- if (breakMatch === null) {
- throw new Error(
- `Could not find breakpoint info in ${JSON.stringify(output)}`);
- }
-- return { filename: breakMatch[1], line: +breakMatch[2] };
-+ return { filename: breakMatch[2], line: +breakMatch[3] };
- },
-
- ctrlC() {
-diff --git a/test/parallel/test-debugger-break.js b/test/parallel/test-debugger-break.js
-index 65b4355cfe7bc25464626cca6f1c3b0de1dd9a45..8e3a290321a2e70304859eb57a2056c3a70af0f6 100644
---- a/test/parallel/test-debugger-break.js
-+++ b/test/parallel/test-debugger-break.js
-@@ -27,7 +27,7 @@ const cli = startCLI(['--port=0', script]);
-
- await cli.stepCommand('n');
- assert.ok(
-- cli.output.includes(`break in ${script}:2`),
-+ cli.output.includes(`step in ${script}:2`),
- 'pauses in next line of the script');
- assert.match(
- cli.output,
-@@ -36,7 +36,7 @@ const cli = startCLI(['--port=0', script]);
-
- await cli.stepCommand('next');
- assert.ok(
-- cli.output.includes(`break in ${script}:3`),
-+ cli.output.includes(`step in ${script}:3`),
- 'pauses in next line of the script');
- assert.match(
- cli.output,
-@@ -89,7 +89,7 @@ const cli = startCLI(['--port=0', script]);
- await cli.stepCommand('');
- assert.match(
- cli.output,
-- /break in node:timers/,
-+ /step in node:timers/,
- 'entered timers.js');
-
- await cli.stepCommand('cont');
-diff --git a/test/parallel/test-debugger-run-after-quit-restart.js b/test/parallel/test-debugger-run-after-quit-restart.js
-index 2c56f7227aed69d781392ce2f3f40e489e3501f2..0e1048699206dcc77696974e097e97de6b217811 100644
---- a/test/parallel/test-debugger-run-after-quit-restart.js
-+++ b/test/parallel/test-debugger-run-after-quit-restart.js
-@@ -25,7 +25,7 @@ const path = require('path');
- .then(() => cli.stepCommand('n'))
- .then(() => {
- assert.ok(
-- cli.output.includes(`break in ${script}:2`),
-+ cli.output.includes(`step in ${script}:2`),
- 'steps to the 2nd line'
- );
- })
diff --git a/patches/node/fix_add_default_values_for_variables_in_common_gypi.patch b/patches/node/fix_add_default_values_for_variables_in_common_gypi.patch
index 0c0aebff56..d7cf142afa 100644
--- a/patches/node/fix_add_default_values_for_variables_in_common_gypi.patch
+++ b/patches/node/fix_add_default_values_for_variables_in_common_gypi.patch
@@ -7,7 +7,7 @@ common.gypi is a file that's included in the node header bundle, despite
the fact that we do not build node with gyp.
diff --git a/common.gypi b/common.gypi
-index 1ece4f5e494533ea0fa25e0d35143fe424dbf70b..697b8bba6a55358924d6986f2eb347a99ff73889 100644
+index a97e77860e151f5126515d65ef99b34aa7301f76..229cb96c1385c597138719f2b01f78bd54ad44ab 100644
--- a/common.gypi
+++ b/common.gypi
@@ -88,6 +88,23 @@
diff --git a/patches/node/fix_add_property_query_interceptors.patch b/patches/node/fix_add_property_query_interceptors.patch
deleted file mode 100644
index b0c4211c1c..0000000000
--- a/patches/node/fix_add_property_query_interceptors.patch
+++ /dev/null
@@ -1,574 +0,0 @@
-From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
-From: VerteDinde <[email protected]>
-Date: Mon, 24 Jun 2024 21:48:40 -0700
-Subject: fix: add property query interceptors
-
-This commit cherry-picks an upstream interceptor API change
-from node-v8/canary to accomodate V8's upstream changes to old
-interceptor APIs.
-
-Node PR: https://github.com/nodejs/node-v8/commit/d1f18b0bf16efbc1e54ba04a54735ce4683cb936
-CL: https://chromium-review.googlesource.com/c/v8/v8/+/5630388
-
-This patch can be removed when the node change is incorporated into main.
-
-diff --git a/src/node_contextify.cc b/src/node_contextify.cc
-index 28ba7dbe66a44a43c39e3d75edf0be9513bcf732..0401b968916e5f45d148281c74b7e465e11439b8 100644
---- a/src/node_contextify.cc
-+++ b/src/node_contextify.cc
-@@ -49,6 +49,7 @@ using v8::FunctionTemplate;
- using v8::HandleScope;
- using v8::IndexedPropertyHandlerConfiguration;
- using v8::Int32;
-+using v8::Intercepted;
- using v8::Isolate;
- using v8::Just;
- using v8::Local;
-@@ -484,14 +485,15 @@ bool ContextifyContext::IsStillInitializing(const ContextifyContext* ctx) {
- }
-
- // static
--void ContextifyContext::PropertyGetterCallback(
-- Local<Name> property,
-- const PropertyCallbackInfo<Value>& args) {
-+Intercepted ContextifyContext::PropertyGetterCallback(
-+ Local<Name> property, const PropertyCallbackInfo<Value>& args) {
- Environment* env = Environment::GetCurrent(args);
- ContextifyContext* ctx = ContextifyContext::Get(args);
-
- // Still initializing
-- if (IsStillInitializing(ctx)) return;
-+ if (IsStillInitializing(ctx)) {
-+ return Intercepted::kNo;
-+ }
-
- Local<Context> context = ctx->context();
- Local<Object> sandbox = ctx->sandbox();
-@@ -515,18 +517,22 @@ void ContextifyContext::PropertyGetterCallback(
- rv = ctx->global_proxy();
-
- args.GetReturnValue().Set(rv);
-+ return Intercepted::kYes;
- }
-+ return Intercepted::kNo;
- }
-
- // static
--void ContextifyContext::PropertySetterCallback(
-+Intercepted ContextifyContext::PropertySetterCallback(
- Local<Name> property,
- Local<Value> value,
-- const PropertyCallbackInfo<Value>& args) {
-+ const PropertyCallbackInfo<void>& args) {
- ContextifyContext* ctx = ContextifyContext::Get(args);
-
- // Still initializing
-- if (IsStillInitializing(ctx)) return;
-+ if (IsStillInitializing(ctx)) {
-+ return Intercepted::kNo;
-+ }
-
- Local<Context> context = ctx->context();
- PropertyAttribute attributes = PropertyAttribute::None;
-@@ -544,8 +550,9 @@ void ContextifyContext::PropertySetterCallback(
- (static_cast<int>(attributes) &
- static_cast<int>(PropertyAttribute::ReadOnly));
-
-- if (read_only)
-- return;
-+ if (read_only) {
-+ return Intercepted::kNo;
-+ }
-
- // true for x = 5
- // false for this.x = 5
-@@ -564,11 +571,16 @@ void ContextifyContext::PropertySetterCallback(
-
- bool is_declared = is_declared_on_global_proxy || is_declared_on_sandbox;
- if (!is_declared && args.ShouldThrowOnError() && is_contextual_store &&
-- !is_function)
-- return;
-+ !is_function) {
-+ return Intercepted::kNo;
-+ }
-
-- if (!is_declared && property->IsSymbol()) return;
-- if (ctx->sandbox()->Set(context, property, value).IsNothing()) return;
-+ if (!is_declared && property->IsSymbol()) {
-+ return Intercepted::kNo;
-+ }
-+ if (ctx->sandbox()->Set(context, property, value).IsNothing()) {
-+ return Intercepted::kNo;
-+ }
-
- Local<Value> desc;
- if (is_declared_on_sandbox &&
-@@ -582,19 +594,23 @@ void ContextifyContext::PropertySetterCallback(
- // We have to specify the return value for any contextual or get/set
- // property
- if (desc_obj->HasOwnProperty(context, env->get_string()).FromMaybe(false) ||
-- desc_obj->HasOwnProperty(context, env->set_string()).FromMaybe(false))
-+ desc_obj->HasOwnProperty(context, env->set_string()).FromMaybe(false)) {
- args.GetReturnValue().Set(value);
-+ return Intercepted::kYes;
-+ }
- }
-+ return Intercepted::kNo;
- }
-
- // static
--void ContextifyContext::PropertyDescriptorCallback(
-- Local<Name> property,
-- const PropertyCallbackInfo<Value>& args) {
-+Intercepted ContextifyContext::PropertyDescriptorCallback(
-+ Local<Name> property, const PropertyCallbackInfo<Value>& args) {
- ContextifyContext* ctx = ContextifyContext::Get(args);
-
- // Still initializing
-- if (IsStillInitializing(ctx)) return;
-+ if (IsStillInitializing(ctx)) {
-+ return Intercepted::kNo;
-+ }
-
- Local<Context> context = ctx->context();
-
-@@ -604,19 +620,23 @@ void ContextifyContext::PropertyDescriptorCallback(
- Local<Value> desc;
- if (sandbox->GetOwnPropertyDescriptor(context, property).ToLocal(&desc)) {
- args.GetReturnValue().Set(desc);
-+ return Intercepted::kYes;
- }
- }
-+ return Intercepted::kNo;
- }
-
- // static
--void ContextifyContext::PropertyDefinerCallback(
-+Intercepted ContextifyContext::PropertyDefinerCallback(
- Local<Name> property,
- const PropertyDescriptor& desc,
-- const PropertyCallbackInfo<Value>& args) {
-+ const PropertyCallbackInfo<void>& args) {
- ContextifyContext* ctx = ContextifyContext::Get(args);
-
- // Still initializing
-- if (IsStillInitializing(ctx)) return;
-+ if (IsStillInitializing(ctx)) {
-+ return Intercepted::kNo;
-+ }
-
- Local<Context> context = ctx->context();
- Isolate* isolate = context->GetIsolate();
-@@ -635,7 +655,7 @@ void ContextifyContext::PropertyDefinerCallback(
- // If the property is set on the global as neither writable nor
- // configurable, don't change it on the global or sandbox.
- if (is_declared && read_only && dont_delete) {
-- return;
-+ return Intercepted::kNo;
- }
-
- Local<Object> sandbox = ctx->sandbox();
-@@ -658,6 +678,9 @@ void ContextifyContext::PropertyDefinerCallback(
- desc.has_set() ? desc.set() : Undefined(isolate).As<Value>());
-
- define_prop_on_sandbox(&desc_for_sandbox);
-+ // TODO(https://github.com/nodejs/node/issues/52634): this should return
-+ // kYes to behave according to the expected semantics.
-+ return Intercepted::kNo;
- } else {
- Local<Value> value =
- desc.has_value() ? desc.value() : Undefined(isolate).As<Value>();
-@@ -669,26 +692,32 @@ void ContextifyContext::PropertyDefinerCallback(
- PropertyDescriptor desc_for_sandbox(value);
- define_prop_on_sandbox(&desc_for_sandbox);
- }
-+ // TODO(https://github.com/nodejs/node/issues/52634): this should return
-+ // kYes to behave according to the expected semantics.
-+ return Intercepted::kNo;
- }
- }
-
- // static
--void ContextifyContext::PropertyDeleterCallback(
-- Local<Name> property,
-- const PropertyCallbackInfo<Boolean>& args) {
-+Intercepted ContextifyContext::PropertyDeleterCallback(
-+ Local<Name> property, const PropertyCallbackInfo<Boolean>& args) {
- ContextifyContext* ctx = ContextifyContext::Get(args);
-
- // Still initializing
-- if (IsStillInitializing(ctx)) return;
-+ if (IsStillInitializing(ctx)) {
-+ return Intercepted::kNo;
-+ }
-
- Maybe<bool> success = ctx->sandbox()->Delete(ctx->context(), property);
-
-- if (success.FromMaybe(false))
-- return;
-+ if (success.FromMaybe(false)) {
-+ return Intercepted::kNo;
-+ }
-
- // Delete failed on the sandbox, intercept and do not delete on
- // the global object.
- args.GetReturnValue().Set(false);
-+ return Intercepted::kYes;
- }
-
- // static
-@@ -708,76 +737,84 @@ void ContextifyContext::PropertyEnumeratorCallback(
- }
-
- // static
--void ContextifyContext::IndexedPropertyGetterCallback(
-- uint32_t index,
-- const PropertyCallbackInfo<Value>& args) {
-+Intercepted ContextifyContext::IndexedPropertyGetterCallback(
-+ uint32_t index, const PropertyCallbackInfo<Value>& args) {
- ContextifyContext* ctx = ContextifyContext::Get(args);
-
- // Still initializing
-- if (IsStillInitializing(ctx)) return;
-+ if (IsStillInitializing(ctx)) {
-+ return Intercepted::kNo;
-+ }
-
-- ContextifyContext::PropertyGetterCallback(
-+ return ContextifyContext::PropertyGetterCallback(
- Uint32ToName(ctx->context(), index), args);
- }
-
--
--void ContextifyContext::IndexedPropertySetterCallback(
-+Intercepted ContextifyContext::IndexedPropertySetterCallback(
- uint32_t index,
- Local<Value> value,
-- const PropertyCallbackInfo<Value>& args) {
-+ const PropertyCallbackInfo<void>& args) {
- ContextifyContext* ctx = ContextifyContext::Get(args);
-
- // Still initializing
-- if (IsStillInitializing(ctx)) return;
-+ if (IsStillInitializing(ctx)) {
-+ return Intercepted::kNo;
-+ }
-
-- ContextifyContext::PropertySetterCallback(
-+ return ContextifyContext::PropertySetterCallback(
- Uint32ToName(ctx->context(), index), value, args);
- }
-
- // static
--void ContextifyContext::IndexedPropertyDescriptorCallback(
-- uint32_t index,
-- const PropertyCallbackInfo<Value>& args) {
-+Intercepted ContextifyContext::IndexedPropertyDescriptorCallback(
-+ uint32_t index, const PropertyCallbackInfo<Value>& args) {
- ContextifyContext* ctx = ContextifyContext::Get(args);
-
- // Still initializing
-- if (IsStillInitializing(ctx)) return;
-+ if (IsStillInitializing(ctx)) {
-+ return Intercepted::kNo;
-+ }
-
-- ContextifyContext::PropertyDescriptorCallback(
-+ return ContextifyContext::PropertyDescriptorCallback(
- Uint32ToName(ctx->context(), index), args);
- }
-
-
--void ContextifyContext::IndexedPropertyDefinerCallback(
-+Intercepted ContextifyContext::IndexedPropertyDefinerCallback(
- uint32_t index,
- const PropertyDescriptor& desc,
-- const PropertyCallbackInfo<Value>& args) {
-+ const PropertyCallbackInfo<void>& args) {
- ContextifyContext* ctx = ContextifyContext::Get(args);
-
- // Still initializing
-- if (IsStillInitializing(ctx)) return;
-+ if (IsStillInitializing(ctx)) {
-+ return Intercepted::kNo;
-+ }
-
-- ContextifyContext::PropertyDefinerCallback(
-+ return ContextifyContext::PropertyDefinerCallback(
- Uint32ToName(ctx->context(), index), desc, args);
- }
-
- // static
--void ContextifyContext::IndexedPropertyDeleterCallback(
-- uint32_t index,
-- const PropertyCallbackInfo<Boolean>& args) {
-+Intercepted ContextifyContext::IndexedPropertyDeleterCallback(
-+ uint32_t index, const PropertyCallbackInfo<Boolean>& args) {
- ContextifyContext* ctx = ContextifyContext::Get(args);
-
- // Still initializing
-- if (IsStillInitializing(ctx)) return;
-+ if (IsStillInitializing(ctx)) {
-+ return Intercepted::kNo;
-+ }
-
- Maybe<bool> success = ctx->sandbox()->Delete(ctx->context(), index);
-
-- if (success.FromMaybe(false))
-- return;
-+ if (success.FromMaybe(false)) {
-+ return Intercepted::kNo;
-+ }
-
- // Delete failed on the sandbox, intercept and do not delete on
- // the global object.
- args.GetReturnValue().Set(false);
-+ return Intercepted::kYes;
- }
-
- void ContextifyScript::CreatePerIsolateProperties(
-diff --git a/src/node_contextify.h b/src/node_contextify.h
-index 10715c7eb07715cc11e49734bd54747dad95f6a4..49b9fabb399aed962e0d29e784a25ca4e9780a8f 100644
---- a/src/node_contextify.h
-+++ b/src/node_contextify.h
-@@ -111,42 +111,39 @@ class ContextifyContext : public BaseObject {
- const v8::FunctionCallbackInfo<v8::Value>& args);
- static void WeakCallback(
- const v8::WeakCallbackInfo<ContextifyContext>& data);
-- static void PropertyGetterCallback(
-+ static v8::Intercepted PropertyGetterCallback(
- v8::Local<v8::Name> property,
- const v8::PropertyCallbackInfo<v8::Value>& args);
-- static void PropertySetterCallback(
-+ static v8::Intercepted PropertySetterCallback(
- v8::Local<v8::Name> property,
- v8::Local<v8::Value> value,
-- const v8::PropertyCallbackInfo<v8::Value>& args);
-- static void PropertyDescriptorCallback(
-+ const v8::PropertyCallbackInfo<void>& args);
-+ static v8::Intercepted PropertyDescriptorCallback(
- v8::Local<v8::Name> property,
- const v8::PropertyCallbackInfo<v8::Value>& args);
-- static void PropertyDefinerCallback(
-+ static v8::Intercepted PropertyDefinerCallback(
- v8::Local<v8::Name> property,
- const v8::PropertyDescriptor& desc,
-- const v8::PropertyCallbackInfo<v8::Value>& args);
-- static void PropertyDeleterCallback(
-+ const v8::PropertyCallbackInfo<void>& args);
-+ static v8::Intercepted PropertyDeleterCallback(
- v8::Local<v8::Name> property,
- const v8::PropertyCallbackInfo<v8::Boolean>& args);
- static void PropertyEnumeratorCallback(
- const v8::PropertyCallbackInfo<v8::Array>& args);
-- static void IndexedPropertyGetterCallback(
-- uint32_t index,
-- const v8::PropertyCallbackInfo<v8::Value>& args);
-- static void IndexedPropertySetterCallback(
-+ static v8::Intercepted IndexedPropertyGetterCallback(
-+ uint32_t index, const v8::PropertyCallbackInfo<v8::Value>& args);
-+ static v8::Intercepted IndexedPropertySetterCallback(
- uint32_t index,
- v8::Local<v8::Value> value,
-- const v8::PropertyCallbackInfo<v8::Value>& args);
-- static void IndexedPropertyDescriptorCallback(
-- uint32_t index,
-- const v8::PropertyCallbackInfo<v8::Value>& args);
-- static void IndexedPropertyDefinerCallback(
-+ const v8::PropertyCallbackInfo<void>& args);
-+ static v8::Intercepted IndexedPropertyDescriptorCallback(
-+ uint32_t index, const v8::PropertyCallbackInfo<v8::Value>& args);
-+ static v8::Intercepted IndexedPropertyDefinerCallback(
- uint32_t index,
- const v8::PropertyDescriptor& desc,
-- const v8::PropertyCallbackInfo<v8::Value>& args);
-- static void IndexedPropertyDeleterCallback(
-- uint32_t index,
-- const v8::PropertyCallbackInfo<v8::Boolean>& args);
-+ const v8::PropertyCallbackInfo<void>& args);
-+ static v8::Intercepted IndexedPropertyDeleterCallback(
-+ uint32_t index, const v8::PropertyCallbackInfo<v8::Boolean>& args);
-
- v8::Global<v8::Context> context_;
- std::unique_ptr<v8::MicrotaskQueue> microtask_queue_;
-diff --git a/src/node_env_var.cc b/src/node_env_var.cc
-index bce7ae07214ddf970a530db29ed6970e14b7a5ed..85f82180d48d6cfd7738cd7b1e504f23b38153e8 100644
---- a/src/node_env_var.cc
-+++ b/src/node_env_var.cc
-@@ -16,6 +16,7 @@ using v8::DontEnum;
- using v8::FunctionTemplate;
- using v8::HandleScope;
- using v8::Integer;
-+using v8::Intercepted;
- using v8::Isolate;
- using v8::Just;
- using v8::Local;
-@@ -336,24 +337,27 @@ Maybe<bool> KVStore::AssignToObject(v8::Isolate* isolate,
- return Just(true);
- }
-
--static void EnvGetter(Local<Name> property,
-- const PropertyCallbackInfo<Value>& info) {
-+static Intercepted EnvGetter(Local<Name> property,
-+ const PropertyCallbackInfo<Value>& info) {
- Environment* env = Environment::GetCurrent(info);
- CHECK(env->has_run_bootstrapping_code());
- if (property->IsSymbol()) {
-- return info.GetReturnValue().SetUndefined();
-+ info.GetReturnValue().SetUndefined();
-+ return Intercepted::kYes;
- }
- CHECK(property->IsString());
- MaybeLocal<String> value_string =
- env->env_vars()->Get(env->isolate(), property.As<String>());
- if (!value_string.IsEmpty()) {
- info.GetReturnValue().Set(value_string.ToLocalChecked());
-+ return Intercepted::kYes;
- }
-+ return Intercepted::kNo;
- }
-
--static void EnvSetter(Local<Name> property,
-- Local<Value> value,
-- const PropertyCallbackInfo<Value>& info) {
-+static Intercepted EnvSetter(Local<Name> property,
-+ Local<Value> value,
-+ const PropertyCallbackInfo<void>& info) {
- Environment* env = Environment::GetCurrent(info);
- CHECK(env->has_run_bootstrapping_code());
- // calling env->EmitProcessEnvWarning() sets a variable indicating that
-@@ -369,35 +373,40 @@ static void EnvSetter(Local<Name> property,
- "the "
- "value to a string before setting process.env with it.",
- "DEP0104")
-- .IsNothing())
-- return;
-+ .IsNothing()) {
-+ return Intercepted::kNo;
-+ }
- }
-
- Local<String> key;
- Local<String> value_string;
- if (!property->ToString(env->context()).ToLocal(&key) ||
- !value->ToString(env->context()).ToLocal(&value_string)) {
-- return;
-+ return Intercepted::kNo;
- }
-
- env->env_vars()->Set(env->isolate(), key, value_string);
-
-- // Whether it worked or not, always return value.
-- info.GetReturnValue().Set(value);
-+ return Intercepted::kYes;
- }
-
--static void EnvQuery(Local<Name> property,
-- const PropertyCallbackInfo<Integer>& info) {
-+static Intercepted EnvQuery(Local<Name> property,
-+ const PropertyCallbackInfo<Integer>& info) {
- Environment* env = Environment::GetCurrent(info);
- CHECK(env->has_run_bootstrapping_code());
- if (property->IsString()) {
- int32_t rc = env->env_vars()->Query(env->isolate(), property.As<String>());
-- if (rc != -1) info.GetReturnValue().Set(rc);
-+ if (rc != -1) {
-+ // Return attributes for the property.
-+ info.GetReturnValue().Set(v8::None);
-+ return Intercepted::kYes;
-+ }
- }
-+ return Intercepted::kNo;
- }
-
--static void EnvDeleter(Local<Name> property,
-- const PropertyCallbackInfo<Boolean>& info) {
-+static Intercepted EnvDeleter(Local<Name> property,
-+ const PropertyCallbackInfo<Boolean>& info) {
- Environment* env = Environment::GetCurrent(info);
- CHECK(env->has_run_bootstrapping_code());
- if (property->IsString()) {
-@@ -407,6 +416,7 @@ static void EnvDeleter(Local<Name> property,
- // process.env never has non-configurable properties, so always
- // return true like the tc39 delete operator.
- info.GetReturnValue().Set(true);
-+ return Intercepted::kYes;
- }
-
- static void EnvEnumerator(const PropertyCallbackInfo<Array>& info) {
-@@ -417,9 +427,9 @@ static void EnvEnumerator(const PropertyCallbackInfo<Array>& info) {
- env->env_vars()->Enumerate(env->isolate()));
- }
-
--static void EnvDefiner(Local<Name> property,
-- const PropertyDescriptor& desc,
-- const PropertyCallbackInfo<Value>& info) {
-+static Intercepted EnvDefiner(Local<Name> property,
-+ const PropertyDescriptor& desc,
-+ const PropertyCallbackInfo<void>& info) {
- Environment* env = Environment::GetCurrent(info);
- if (desc.has_value()) {
- if (!desc.has_writable() ||
-@@ -430,6 +440,7 @@ static void EnvDefiner(Local<Name> property,
- "configurable, writable,"
- " and enumerable "
- "data descriptor");
-+ return Intercepted::kYes;
- } else if (!desc.configurable() ||
- !desc.enumerable() ||
- !desc.writable()) {
-@@ -438,6 +449,7 @@ static void EnvDefiner(Local<Name> property,
- "configurable, writable,"
- " and enumerable "
- "data descriptor");
-+ return Intercepted::kYes;
- } else {
- return EnvSetter(property, desc.value(), info);
- }
-@@ -447,12 +459,14 @@ static void EnvDefiner(Local<Name> property,
- "'process.env' does not accept an"
- " accessor(getter/setter)"
- " descriptor");
-+ return Intercepted::kYes;
- } else {
- THROW_ERR_INVALID_OBJECT_DEFINE_PROPERTY(env,
- "'process.env' only accepts a "
- "configurable, writable,"
- " and enumerable "
- "data descriptor");
-+ return Intercepted::kYes;
- }
- }
-
-diff --git a/src/node_external_reference.h b/src/node_external_reference.h
-index c4aba23510872d66b58a1adc88cdd1ee85a86cfe..6d9988810b951771064de523bc20aaf389a9c08a 100644
---- a/src/node_external_reference.h
-+++ b/src/node_external_reference.h
-@@ -66,16 +66,17 @@ class ExternalReferenceRegistry {
- V(v8::FunctionCallback) \
- V(v8::AccessorNameGetterCallback) \
- V(v8::AccessorNameSetterCallback) \
-- V(v8::GenericNamedPropertyDefinerCallback) \
-- V(v8::GenericNamedPropertyDeleterCallback) \
-- V(v8::GenericNamedPropertyEnumeratorCallback) \
-- V(v8::GenericNamedPropertyQueryCallback) \
-- V(v8::GenericNamedPropertySetterCallback) \
-- V(v8::IndexedPropertySetterCallback) \
-- V(v8::IndexedPropertyDefinerCallback) \
-- V(v8::IndexedPropertyDeleterCallback) \
-- V(v8::IndexedPropertyQueryCallback) \
-- V(v8::IndexedPropertyDescriptorCallback) \
-+ V(v8::NamedPropertyGetterCallback) \
-+ V(v8::NamedPropertyDefinerCallback) \
-+ V(v8::NamedPropertyDeleterCallback) \
-+ V(v8::NamedPropertyEnumeratorCallback) \
-+ V(v8::NamedPropertyQueryCallback) \
-+ V(v8::NamedPropertySetterCallback) \
-+ V(v8::IndexedPropertyGetterCallbackV2) \
-+ V(v8::IndexedPropertySetterCallbackV2) \
-+ V(v8::IndexedPropertyDefinerCallbackV2) \
-+ V(v8::IndexedPropertyDeleterCallbackV2) \
-+ V(v8::IndexedPropertyQueryCallbackV2) \
- V(const v8::String::ExternalStringResourceBase*)
-
- #define V(ExternalReferenceType) \
diff --git a/patches/node/fix_add_trusted_space_and_trusted_lo_space_to_the_v8_heap.patch b/patches/node/fix_add_trusted_space_and_trusted_lo_space_to_the_v8_heap.patch
deleted file mode 100644
index 311a90be6d..0000000000
--- a/patches/node/fix_add_trusted_space_and_trusted_lo_space_to_the_v8_heap.patch
+++ /dev/null
@@ -1,23 +0,0 @@
-From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
-From: Shelley Vohr <[email protected]>
-Date: Tue, 12 Sep 2023 11:08:18 +0200
-Subject: fix: Add TRUSTED_SPACE and TRUSTED_LO_SPACE to the V8 heap
-
-Added by V8 in https://chromium-review.googlesource.com/c/v8/v8/+/4791643
-
-This patch can be removed when Node.js upgrades to a version of V8 that
-includes this change.
-
-diff --git a/test/parallel/test-v8-stats.js b/test/parallel/test-v8-stats.js
-index dd774267910aa0920ed077dd5bd5cfed93aab6cb..2366cbf716c11851bb3a759dce5db47d616516dc 100644
---- a/test/parallel/test-v8-stats.js
-+++ b/test/parallel/test-v8-stats.js
-@@ -48,6 +48,8 @@ const expectedHeapSpaces = [
- 'read_only_space',
- 'shared_large_object_space',
- 'shared_space',
-+ 'trusted_large_object_space',
-+ 'trusted_space'
- ];
- const heapSpaceStatistics = v8.getHeapSpaceStatistics();
- const actualHeapSpaceNames = heapSpaceStatistics.map((s) => s.space_name);
diff --git a/patches/node/fix_assert_module_in_the_renderer_process.patch b/patches/node/fix_assert_module_in_the_renderer_process.patch
index b89325039f..8bceb9a241 100644
--- a/patches/node/fix_assert_module_in_the_renderer_process.patch
+++ b/patches/node/fix_assert_module_in_the_renderer_process.patch
@@ -44,7 +44,7 @@ index 59b5a16f1309a5e4055bccfdb7a529045ad30402..bfdaf6211466a01b64b7942f7b16c480
let filename = call.getFileName();
const line = call.getLineNumber() - 1;
diff --git a/src/api/environment.cc b/src/api/environment.cc
-index b9098d102b40adad7fafcc331ac62870617019b9..cb9269a31e073caf86164aa39c0640370ade60fd 100644
+index f59abcb21d64b910d8d42eb23c03109f62558813..1b6613d1de8c89c8271066a652afd1024988362d 100644
--- a/src/api/environment.cc
+++ b/src/api/environment.cc
@@ -244,6 +244,9 @@ void SetIsolateErrorHandlers(v8::Isolate* isolate, const IsolateSettings& s) {
@@ -58,10 +58,10 @@ index b9098d102b40adad7fafcc331ac62870617019b9..cb9269a31e073caf86164aa39c064037
}
diff --git a/src/node_options.cc b/src/node_options.cc
-index 818baf611fcab7838a339f3ea137467653e270d0..4e3c82e9528b04fd1a0cc99d30fb885e4b224bc9 100644
+index 29630fcccc3bd9d24ad6aec64bef2fedfc3c4031..4b3f7751db2871c8ce76b197a84a2417097030ea 100644
--- a/src/node_options.cc
+++ b/src/node_options.cc
-@@ -1405,14 +1405,16 @@ void GetEmbedderOptions(const FunctionCallbackInfo<Value>& args) {
+@@ -1464,14 +1464,16 @@ void GetEmbedderOptions(const FunctionCallbackInfo<Value>& args) {
}
Isolate* isolate = args.GetIsolate();
diff --git a/patches/node/fix_capture_embedder_exceptions_before_entering_v8.patch b/patches/node/fix_capture_embedder_exceptions_before_entering_v8.patch
index c2909b32d8..ac22a29a41 100644
--- a/patches/node/fix_capture_embedder_exceptions_before_entering_v8.patch
+++ b/patches/node/fix_capture_embedder_exceptions_before_entering_v8.patch
@@ -10,7 +10,7 @@ in the nodejs test suite. Need to be followed-up with upstream
on the broader change as there maybe other callsites.
diff --git a/src/handle_wrap.cc b/src/handle_wrap.cc
-index be02d4aaa04685cbd6a9ecfe082e38f179129ab5..277748a30bd97ae816d9ba1f2d73851a29b81010 100644
+index 70db7ddbeab5963f1bdf6cb05ee2763d76011cec..6ffe2a2ad01f33ff68c6646df330ec3ac7781a19 100644
--- a/src/handle_wrap.cc
+++ b/src/handle_wrap.cc
@@ -148,6 +148,9 @@ void HandleWrap::OnClose(uv_handle_t* handle) {
@@ -21,62 +21,5 @@ index be02d4aaa04685cbd6a9ecfe082e38f179129ab5..277748a30bd97ae816d9ba1f2d73851a
+ return;
+
if (!wrap->persistent().IsEmpty() &&
- wrap->object()->Has(env->context(), env->handle_onclose_symbol())
- .FromMaybe(false)) {
-diff --git a/src/node_contextify.cc b/src/node_contextify.cc
-index 8951cd378a9025f58fada47cf96f686d14639f95..6456d87d4202c013aafe071adbac06852b3ae2c1 100644
---- a/src/node_contextify.cc
-+++ b/src/node_contextify.cc
-@@ -487,6 +487,7 @@ bool ContextifyContext::IsStillInitializing(const ContextifyContext* ctx) {
- void ContextifyContext::PropertyGetterCallback(
- Local<Name> property,
- const PropertyCallbackInfo<Value>& args) {
-+ Environment* env = Environment::GetCurrent(args);
- ContextifyContext* ctx = ContextifyContext::Get(args);
-
- // Still initializing
-@@ -494,6 +495,8 @@ void ContextifyContext::PropertyGetterCallback(
-
- Local<Context> context = ctx->context();
- Local<Object> sandbox = ctx->sandbox();
-+
-+ TryCatchScope try_catch(env);
- MaybeLocal<Value> maybe_rv =
- sandbox->GetRealNamedProperty(context, property);
- if (maybe_rv.IsEmpty()) {
-@@ -503,6 +506,11 @@ void ContextifyContext::PropertyGetterCallback(
-
- Local<Value> rv;
- if (maybe_rv.ToLocal(&rv)) {
-+ if (try_catch.HasCaught() &&
-+ !try_catch.HasTerminated()) {
-+ try_catch.ReThrow();
-+ }
-+
- if (rv == sandbox)
- rv = ctx->global_proxy();
-
-diff --git a/src/node_messaging.cc b/src/node_messaging.cc
-index e7d2bfbafef13f04a73dcbefe7d6e90b37b904d1..31b870c5f003b62b848c00d6032ed98eb829778d 100644
---- a/src/node_messaging.cc
-+++ b/src/node_messaging.cc
-@@ -907,7 +907,7 @@ Maybe<bool> MessagePort::PostMessage(Environment* env,
- const TransferList& transfer_v) {
- Isolate* isolate = env->isolate();
- Local<Object> obj = object(isolate);
--
-+ TryCatchScope try_catch(env);
- std::shared_ptr<Message> msg = std::make_shared<Message>();
-
- // Per spec, we need to both check if transfer list has the source port, and
-@@ -915,6 +915,10 @@ Maybe<bool> MessagePort::PostMessage(Environment* env,
-
- Maybe<bool> serialization_maybe =
- msg->Serialize(env, context, message_v, transfer_v, obj);
-+ if (try_catch.HasCaught() &&
-+ !try_catch.HasTerminated()) {
-+ try_catch.ReThrow();
-+ }
- if (data_ == nullptr) {
- return serialization_maybe;
- }
+ wrap->object()
+ ->Has(env->context(), env->handle_onclose_symbol())
diff --git a/patches/node/fix_crypto_tests_to_run_with_bssl.patch b/patches/node/fix_crypto_tests_to_run_with_bssl.patch
index 83b02e0c3f..544e4ef6af 100644
--- a/patches/node/fix_crypto_tests_to_run_with_bssl.patch
+++ b/patches/node/fix_crypto_tests_to_run_with_bssl.patch
@@ -10,15 +10,50 @@ This should be upstreamed in some form, though it may need to be tweaked
before it's acceptable to upstream, as this patch comments out a couple
of tests that upstream probably cares about.
+diff --git a/test/common/index.js b/test/common/index.js
+index 172cdb6b049824539a9850789e0e7c5baf613367..c29abc18191aec78ad8eb810093a9a4ef9e854e4 100644
+--- a/test/common/index.js
++++ b/test/common/index.js
+@@ -65,6 +65,8 @@ const opensslVersionNumber = (major = 0, minor = 0, patch = 0) => {
+ return (major << 28) | (minor << 20) | (patch << 4);
+ };
+
++const openSSLIsBoringSSL = process.versions.openssl === '0.0.0';
++
+ let OPENSSL_VERSION_NUMBER;
+ const hasOpenSSL = (major = 0, minor = 0, patch = 0) => {
+ if (!hasCrypto) return false;
+@@ -996,6 +998,7 @@ const common = {
+ mustNotMutateObjectDeep,
+ mustSucceed,
+ nodeProcessAborted,
++ openSSLIsBoringSSL,
+ PIPE,
+ parseTestFlags,
+ platformTimeout,
+diff --git a/test/parallel/test-buffer-tostring-range.js b/test/parallel/test-buffer-tostring-range.js
+index d033cd204b3200cdd736b581abe027d6e46e4ff3..73fec107a36c3db4af6f492137d0ca174f2d0547 100644
+--- a/test/parallel/test-buffer-tostring-range.js
++++ b/test/parallel/test-buffer-tostring-range.js
+@@ -102,7 +102,8 @@ assert.throws(() => {
+ // Must not throw when start and end are within kMaxLength
+ // Cannot test on 32bit machine as we are testing the case
+ // when start and end are above the threshold
+-common.skipIf32Bits();
++if (!common.openSSLIsBoringSSL) {
+ const threshold = 0xFFFFFFFF;
+ const largeBuffer = Buffer.alloc(threshold + 20);
+ largeBuffer.toString('utf8', threshold, threshold + 20);
++}
diff --git a/test/parallel/test-crypto-async-sign-verify.js b/test/parallel/test-crypto-async-sign-verify.js
-index 4e3c32fdcd23fbe3e74bd5e624b739d224689f33..19d65aae7fa8ec9f9b907733ead17a208ed47909 100644
+index 4e3c32fdcd23fbe3e74bd5e624b739d224689f33..29149838ca76986928c7649a5f60a0f5e22a0705 100644
--- a/test/parallel/test-crypto-async-sign-verify.js
+++ b/test/parallel/test-crypto-async-sign-verify.js
@@ -88,6 +88,7 @@ test('rsa_public.pem', 'rsa_private.pem', 'sha256', false,
// ED25519
test('ed25519_public.pem', 'ed25519_private.pem', undefined, true);
// ED448
-+/*
++if (!common.openSSLIsBoringSSL) {
test('ed448_public.pem', 'ed448_private.pem', undefined, true);
// ECDSA w/ der signature encoding
@@ -26,145 +61,10 @@ index 4e3c32fdcd23fbe3e74bd5e624b739d224689f33..19d65aae7fa8ec9f9b907733ead17a20
// DSA w/ ieee-p1363 signature encoding
test('dsa_public.pem', 'dsa_private.pem', 'sha256', false,
{ dsaEncoding: 'ieee-p1363' });
-+*/
++}
// Test Parallel Execution w/ KeyObject is threadsafe in openssl3
{
-diff --git a/test/parallel/test-crypto-authenticated.js b/test/parallel/test-crypto-authenticated.js
-index 59dd3b69c4bdf6dbd7b5e4f03df74caac551d459..1e0f9ce4c979683530afdf83ac3dc095acad2eb8 100644
---- a/test/parallel/test-crypto-authenticated.js
-+++ b/test/parallel/test-crypto-authenticated.js
-@@ -48,7 +48,9 @@ const errMessages = {
- const ciphers = crypto.getCiphers();
-
- const expectedWarnings = common.hasFipsCrypto ?
-- [] : [
-+ [] : !ciphers.includes('aes-192-ccm') ? [
-+ ['Use Cipheriv for counter mode of aes-192-gcm'],
-+ ] : [
- ['Use Cipheriv for counter mode of aes-192-gcm'],
- ['Use Cipheriv for counter mode of aes-192-ccm'],
- ['Use Cipheriv for counter mode of aes-192-ccm'],
-@@ -315,7 +317,9 @@ for (const test of TEST_CASES) {
-
- // Test that create(De|C)ipher(iv)? throws if the mode is CCM and an invalid
- // authentication tag length has been specified.
--{
-+if (!ciphers.includes('aes-256-ccm')) {
-+ common.printSkipMessage(`unsupported aes-256-ccm test`);
-+} else {
- for (const authTagLength of [-1, true, false, NaN, 5.5]) {
- assert.throws(() => {
- crypto.createCipheriv('aes-256-ccm',
-@@ -403,6 +407,10 @@ for (const test of TEST_CASES) {
- // authentication tag has been specified.
- {
- for (const mode of ['ccm', 'ocb']) {
-+ if (!ciphers.includes(`aes-256-${mode}`)) {
-+ common.printSkipMessage(`unsupported aes-256-${mode} test`);
-+ continue;
-+ }
- assert.throws(() => {
- crypto.createCipheriv(`aes-256-${mode}`,
- 'FxLKsqdmv0E9xrQhp0b1ZgI0K7JFZJM8',
-@@ -437,7 +445,9 @@ for (const test of TEST_CASES) {
- }
-
- // Test that setAAD throws if an invalid plaintext length has been specified.
--{
-+if (!ciphers.includes('aes-256-ccm')) {
-+ common.printSkipMessage(`unsupported aes-256-ccm test`);
-+} else {
- const cipher = crypto.createCipheriv('aes-256-ccm',
- 'FxLKsqdmv0E9xrQhp0b1ZgI0K7JFZJM8',
- 'qkuZpJWCewa6S',
-@@ -458,7 +468,9 @@ for (const test of TEST_CASES) {
- }
-
- // Test that setAAD and update throw if the plaintext is too long.
--{
-+if (!ciphers.includes('aes-256-ccm')) {
-+ common.printSkipMessage(`unsupported aes-256-ccm test`);
-+} else {
- for (const ivLength of [13, 12]) {
- const maxMessageSize = (1 << (8 * (15 - ivLength))) - 1;
- const key = 'FxLKsqdmv0E9xrQhp0b1ZgI0K7JFZJM8';
-@@ -489,7 +501,9 @@ for (const test of TEST_CASES) {
-
- // Test that setAAD throws if the mode is CCM and the plaintext length has not
- // been specified.
--{
-+if (!ciphers.includes('aes-256-ccm')) {
-+ common.printSkipMessage(`unsupported aes-256-ccm test`);
-+} else {
- assert.throws(() => {
- const cipher = crypto.createCipheriv('aes-256-ccm',
- 'FxLKsqdmv0E9xrQhp0b1ZgI0K7JFZJM8',
-@@ -514,7 +528,9 @@ for (const test of TEST_CASES) {
- }
-
- // Test that final() throws in CCM mode when no authentication tag is provided.
--{
-+if (!ciphers.includes('aes-128-ccm')) {
-+ common.printSkipMessage(`unsupported aes-256-ccm test`);
-+} else {
- if (!common.hasFipsCrypto) {
- const key = Buffer.from('1ed2233fa2223ef5d7df08546049406c', 'hex');
- const iv = Buffer.from('7305220bca40d4c90e1791e9', 'hex');
-@@ -546,7 +562,9 @@ for (const test of TEST_CASES) {
- }
-
- // Test that an IV length of 11 does not overflow max_message_size_.
--{
-+if (!ciphers.includes('aes-128-ccm')) {
-+ common.printSkipMessage(`unsupported aes-128-ccm test`);
-+} else {
- const key = 'x'.repeat(16);
- const iv = Buffer.from('112233445566778899aabb', 'hex');
- const options = { authTagLength: 8 };
-@@ -563,6 +581,10 @@ for (const test of TEST_CASES) {
- const iv = Buffer.from('0123456789ab', 'utf8');
-
- for (const mode of ['gcm', 'ocb']) {
-+ if (!ciphers.includes(`aes-128-${mode}`)) {
-+ common.printSkipMessage(`unsupported aes-128-${mode} test`);
-+ continue;
-+ }
- for (const authTagLength of mode === 'gcm' ? [undefined, 8] : [8]) {
- const cipher = crypto.createCipheriv(`aes-128-${mode}`, key, iv, {
- authTagLength
-@@ -597,6 +619,10 @@ for (const test of TEST_CASES) {
- const opts = { authTagLength: 8 };
-
- for (const mode of ['gcm', 'ccm', 'ocb']) {
-+ if (!ciphers.includes(`aes-128-${mode}`)) {
-+ common.printSkipMessage(`unsupported aes-128-${mode} test`);
-+ continue;
-+ }
- const cipher = crypto.createCipheriv(`aes-128-${mode}`, key, iv, opts);
- const ciphertext = Buffer.concat([cipher.update(plain), cipher.final()]);
- const tag = cipher.getAuthTag();
-@@ -619,7 +645,9 @@ for (const test of TEST_CASES) {
- // Test chacha20-poly1305 rejects invalid IV lengths of 13, 14, 15, and 16 (a
- // length of 17 or greater was already rejected).
- // - https://www.openssl.org/news/secadv/20190306.txt
--{
-+if (!ciphers.includes('chacha20-poly1305')) {
-+ common.printSkipMessage(`unsupported chacha20-poly1305 test`);
-+} else {
- // Valid extracted from TEST_CASES, check that it detects IV tampering.
- const valid = {
- algo: 'chacha20-poly1305',
-@@ -664,6 +692,9 @@ for (const test of TEST_CASES) {
-
- {
- // CCM cipher without data should not crash, see https://github.com/nodejs/node/issues/38035.
-+ common.printSkipMessage(`unsupported aes-128-ccm test`);
-+ return;
-+
- const algo = 'aes-128-ccm';
- const key = Buffer.alloc(16);
- const iv = Buffer.alloc(12);
diff --git a/test/parallel/test-crypto-certificate.js b/test/parallel/test-crypto-certificate.js
index 4a5f1f149fe6c739f7f1d2ee17df6e61a942d621..b3287f428ce6b3fde11d449c601a57ff5e3843f9 100644
--- a/test/parallel/test-crypto-certificate.js
@@ -194,115 +94,6 @@ index 4a5f1f149fe6c739f7f1d2ee17df6e61a942d621..b3287f428ce6b3fde11d449c601a57ff
}
{
-diff --git a/test/parallel/test-crypto-cipher-decipher.js b/test/parallel/test-crypto-cipher-decipher.js
-index 35514afbea92562a81c163b1e4d918b4ab609f71..13098e1acf12c309f2ed6f6143a2c2eeb8a2763d 100644
---- a/test/parallel/test-crypto-cipher-decipher.js
-+++ b/test/parallel/test-crypto-cipher-decipher.js
-@@ -22,7 +22,7 @@ common.expectWarning({
- function testCipher1(key) {
- // Test encryption and decryption
- const plaintext = 'Keep this a secret? No! Tell everyone about node.js!';
-- const cipher = crypto.createCipher('aes192', key);
-+ const cipher = crypto.createCipher('aes-192-cbc', key);
-
- // Encrypt plaintext which is in utf8 format
- // to a ciphertext which will be in hex
-@@ -30,7 +30,7 @@ function testCipher1(key) {
- // Only use binary or hex, not base64.
- ciph += cipher.final('hex');
-
-- const decipher = crypto.createDecipher('aes192', key);
-+ const decipher = crypto.createDecipher('aes-192-cbc', key);
- let txt = decipher.update(ciph, 'hex', 'utf8');
- txt += decipher.final('utf8');
-
-@@ -40,11 +40,11 @@ function testCipher1(key) {
- // NB: In real life, it's not guaranteed that you can get all of it
- // in a single read() like this. But in this case, we know it's
- // quite small, so there's no harm.
-- const cStream = crypto.createCipher('aes192', key);
-+ const cStream = crypto.createCipher('aes-192-cbc', key);
- cStream.end(plaintext);
- ciph = cStream.read();
-
-- const dStream = crypto.createDecipher('aes192', key);
-+ const dStream = crypto.createDecipher('aes-192-cbc', key);
- dStream.end(ciph);
- txt = dStream.read().toString('utf8');
-
-@@ -59,14 +59,14 @@ function testCipher2(key) {
- '32|RmVZZkFUVmpRRkp0TmJaUm56ZU9qcnJkaXNNWVNpTTU*|iXmckfRWZBGWWELw' +
- 'eCBsThSsfUHLeRe0KCsK8ooHgxie0zOINpXxfZi/oNG7uq9JWFVCk70gfzQH8ZUJ' +
- 'jAfaFg**';
-- const cipher = crypto.createCipher('aes256', key);
-+ const cipher = crypto.createCipher('aes-256-cbc', key);
-
- // Encrypt plaintext which is in utf8 format to a ciphertext which will be in
- // Base64.
- let ciph = cipher.update(plaintext, 'utf8', 'base64');
- ciph += cipher.final('base64');
-
-- const decipher = crypto.createDecipher('aes256', key);
-+ const decipher = crypto.createDecipher('aes-256-cbc', key);
- let txt = decipher.update(ciph, 'base64', 'utf8');
- txt += decipher.final('utf8');
-
-@@ -170,7 +170,7 @@ testCipher2(Buffer.from('0123456789abcdef'));
- // Regression test for https://github.com/nodejs/node-v0.x-archive/issues/5482:
- // string to Cipher#update() should not assert.
- {
-- const c = crypto.createCipher('aes192', '0123456789abcdef');
-+ const c = crypto.createCipher('aes-192-cbc', '0123456789abcdef');
- c.update('update');
- c.final();
- }
-@@ -178,15 +178,15 @@ testCipher2(Buffer.from('0123456789abcdef'));
- // https://github.com/nodejs/node-v0.x-archive/issues/5655 regression tests,
- // 'utf-8' and 'utf8' are identical.
- {
-- let c = crypto.createCipher('aes192', '0123456789abcdef');
-+ let c = crypto.createCipher('aes-192-cbc', '0123456789abcdef');
- c.update('update', ''); // Defaults to "utf8".
- c.final('utf-8'); // Should not throw.
-
-- c = crypto.createCipher('aes192', '0123456789abcdef');
-+ c = crypto.createCipher('aes-192-cbc', '0123456789abcdef');
- c.update('update', 'utf8');
- c.final('utf-8'); // Should not throw.
-
-- c = crypto.createCipher('aes192', '0123456789abcdef');
-+ c = crypto.createCipher('aes-192-cbc', '0123456789abcdef');
- c.update('update', 'utf-8');
- c.final('utf8'); // Should not throw.
- }
-@@ -195,23 +195,23 @@ testCipher2(Buffer.from('0123456789abcdef'));
- {
- const key = '0123456789abcdef';
- const plaintext = 'Top secret!!!';
-- const c = crypto.createCipher('aes192', key);
-+ const c = crypto.createCipher('aes-192-cbc', key);
- let ciph = c.update(plaintext, 'utf16le', 'base64');
- ciph += c.final('base64');
-
-- let decipher = crypto.createDecipher('aes192', key);
-+ let decipher = crypto.createDecipher('aes-192-cbc', key);
-
- let txt;
- txt = decipher.update(ciph, 'base64', 'ucs2');
- txt += decipher.final('ucs2');
- assert.strictEqual(txt, plaintext);
-
-- decipher = crypto.createDecipher('aes192', key);
-+ decipher = crypto.createDecipher('aes-192-cbc', key);
- txt = decipher.update(ciph, 'base64', 'ucs-2');
- txt += decipher.final('ucs-2');
- assert.strictEqual(txt, plaintext);
-
-- decipher = crypto.createDecipher('aes192', key);
-+ decipher = crypto.createDecipher('aes-192-cbc', key);
- txt = decipher.update(ciph, 'base64', 'utf-16le');
- txt += decipher.final('utf-16le');
- assert.strictEqual(txt, plaintext);
diff --git a/test/parallel/test-crypto-cipheriv-decipheriv.js b/test/parallel/test-crypto-cipheriv-decipheriv.js
index 3e3632203af72c54f2795d8de0cf345862a043bb..a066bbb803d41d9d1f26a02e41115b71233988d6 100644
--- a/test/parallel/test-crypto-cipheriv-decipheriv.js
@@ -318,21 +109,6 @@ index 3e3632203af72c54f2795d8de0cf345862a043bb..a066bbb803d41d9d1f26a02e41115b71
// Test encryption and decryption with explicit key and iv.
// AES Key Wrap test vector comes from RFC3394
const plaintext = Buffer.from('00112233445566778899AABBCCDDEEFF', 'hex');
-diff --git a/test/parallel/test-crypto-classes.js b/test/parallel/test-crypto-classes.js
-index dd073274aef765e8f1e403aa2c8baf9694b521cb..fc6339e040debe61ecc61a3eb5b26823b102f1ff 100644
---- a/test/parallel/test-crypto-classes.js
-+++ b/test/parallel/test-crypto-classes.js
-@@ -22,8 +22,8 @@ const TEST_CASES = {
- };
-
- if (!common.hasFipsCrypto) {
-- TEST_CASES.Cipher = ['aes192', 'secret'];
-- TEST_CASES.Decipher = ['aes192', 'secret'];
-+ TEST_CASES.Cipher = ['aes-192-cbc', 'secret'];
-+ TEST_CASES.Decipher = ['aes-192-cbc', 'secret'];
- TEST_CASES.DiffieHellman = [common.hasOpenSSL3 ? 1024 : 256];
- }
-
diff --git a/test/parallel/test-crypto-dh-curves.js b/test/parallel/test-crypto-dh-curves.js
index 81a469c226c261564dee1e0b06b6571b18a41f1f..58b66045dba4201b7ebedd78b129420ffc316051 100644
--- a/test/parallel/test-crypto-dh-curves.js
@@ -381,7 +157,7 @@ index fcf1922bcdba733af6c22f142db4f7b099947757..9f72ae4e41a113e752f40795103c2af5
assert.throws(() => crypto.createDiffieHellman('abcdef', g), ex);
assert.throws(() => crypto.createDiffieHellman('abcdef', 'hex', g), ex);
diff --git a/test/parallel/test-crypto-dh.js b/test/parallel/test-crypto-dh.js
-index 8ae0a002fec0944737d2c6ae73fc8956e41beb50..5b37236a6c2f1ec1761d8143c8ea6a7e2a837a7a 100644
+index 9ebe14011eed223994e0901bc22dcc582b4b0739..e78f90eb76380916ce7098fb517c83a954edb053 100644
--- a/test/parallel/test-crypto-dh.js
+++ b/test/parallel/test-crypto-dh.js
@@ -55,18 +55,17 @@ const crypto = require('crypto');
@@ -411,13 +187,21 @@ index 8ae0a002fec0944737d2c6ae73fc8956e41beb50..5b37236a6c2f1ec1761d8143c8ea6a7e
};
}
-@@ -100,10 +99,16 @@ const crypto = require('crypto');
+@@ -93,17 +92,23 @@ const crypto = require('crypto');
+ dh3.computeSecret('');
+ }, { message: common.hasOpenSSL3 && !hasOpenSSL3WithNewErrorMessage ?
+ 'Unspecified validation error' :
+- 'Supplied key is too small' });
++ 'Supplied key is invalid' });
+ }
+ }
+
// Through a fluke of history, g=0 defaults to DH_GENERATOR (2).
{
const g = 0;
- crypto.createDiffieHellman('abcdef', g);
+ assert.throws(() => crypto.createDiffieHellman('abcdef', g), {
-+ code: /INVALID_PARAMETERS/,
++ code: /ERR_CRYPTO_OPERATION_FAILED/,
+ name: 'Error'
+ });
crypto.createDiffieHellman('abcdef', 'hex', g);
@@ -426,28 +210,28 @@ index 8ae0a002fec0944737d2c6ae73fc8956e41beb50..5b37236a6c2f1ec1761d8143c8ea6a7e
{
- crypto.createDiffieHellman('abcdef', Buffer.from([2])); // OK
+ assert.throws(() => crypto.createDiffieHellman('abcdef', Buffer.from([2])), {
-+ code: /INVALID_PARAMETERS/,
++ code: /ERR_CRYPTO_OPERATION_FAILED/,
+ name: 'Error'
+ });
}
diff --git a/test/parallel/test-crypto-getcipherinfo.js b/test/parallel/test-crypto-getcipherinfo.js
-index 64b79fc36ccf4d38f763fcd8c1930473c82cefd7..892490fc7dd8da09f8aa10a20bec69385c0fee28 100644
+index 64b79fc36ccf4d38f763fcd8c1930473c82cefd7..1c6717ebd46497384b9b13174b65894ca89e7f2d 100644
--- a/test/parallel/test-crypto-getcipherinfo.js
+++ b/test/parallel/test-crypto-getcipherinfo.js
@@ -62,9 +62,13 @@ assert(getCipherInfo('aes-128-cbc', { ivLength: 16 }));
assert(!getCipherInfo('aes-128-ccm', { ivLength: 1 }));
assert(!getCipherInfo('aes-128-ccm', { ivLength: 14 }));
-+/*
++if (!common.openSSLIsBoringSSL) {
for (let n = 7; n <= 13; n++)
assert(getCipherInfo('aes-128-ccm', { ivLength: n }));
-+*/
++}
assert(!getCipherInfo('aes-128-ocb', { ivLength: 16 }));
-+/*
++if (!common.openSSLIsBoringSSL) {
for (let n = 1; n < 16; n++)
assert(getCipherInfo('aes-128-ocb', { ivLength: n }));
-+*/
++}
\ No newline at end of file
diff --git a/test/parallel/test-crypto-hash-stream-pipe.js b/test/parallel/test-crypto-hash-stream-pipe.js
index d22281abbd5c3cab3aaa3ac494301fa6b4a8a968..5f0c6a4aed2e868a1a1049212edf218791cd6868 100644
@@ -471,7 +255,7 @@ index d22281abbd5c3cab3aaa3ac494301fa6b4a8a968..5f0c6a4aed2e868a1a1049212edf2187
s.pipe(h).on('data', common.mustCall(function(c) {
assert.strictEqual(c, expect);
diff --git a/test/parallel/test-crypto-hash.js b/test/parallel/test-crypto-hash.js
-index af2146982c7a3bf7bd7527f44e4b17a3b605026e..f6b91f675cfea367c608892dee078b565814f2dd 100644
+index 83218c105a4596e0ae0381136f176bb8d759899e..afb3c8c592d2a8e2a053fd44f455af06c592a85e 100644
--- a/test/parallel/test-crypto-hash.js
+++ b/test/parallel/test-crypto-hash.js
@@ -182,6 +182,7 @@ assert.throws(
@@ -549,7 +333,7 @@ index 1785f5eef3d202976666081d09850ed744d83446..e88227a215ba4f7fa196f7642ae694a5
});
diff --git a/test/parallel/test-crypto-rsa-dsa.js b/test/parallel/test-crypto-rsa-dsa.js
-index 5f4fafdfffbf726b7cb39c472baa3df25c9794cf..73bb53b0405b20f51b13326cc70e52755c674366 100644
+index 5f4fafdfffbf726b7cb39c472baa3df25c9794cf..d52376da2cddd90adcdf8a9b7dcd03e348d9f2b4 100644
--- a/test/parallel/test-crypto-rsa-dsa.js
+++ b/test/parallel/test-crypto-rsa-dsa.js
@@ -28,12 +28,11 @@ const dsaPkcs8KeyPem = fixtures.readKey('dsa_private_pkcs8.pem');
@@ -580,22 +364,25 @@ index 5f4fafdfffbf726b7cb39c472baa3df25c9794cf..73bb53b0405b20f51b13326cc70e5275
if (!process.config.variables.node_shared_openssl) {
assert.throws(() => {
crypto.privateDecrypt({
-@@ -466,7 +466,7 @@ assert.throws(() => {
+@@ -466,10 +466,10 @@ assert.throws(() => {
assert.strictEqual(verify2.verify(publicKey, signature, 'hex'), true);
}
-
-+/*
//
// Test DSA signing and verification
//
++if (!common.openSSLIsBoringSSL) {
+ {
+ const input = 'I AM THE WALRUS';
+
@@ -541,3 +541,4 @@ const input = 'I AM THE WALRUS';
assert.strictEqual(verify.verify(dsaPubPem, signature, 'hex'), true);
}
-+*/
++}
diff --git a/test/parallel/test-crypto-scrypt.js b/test/parallel/test-crypto-scrypt.js
-index 61bd65fc92678c24baa3c0eb9ffb1ead64ace70b..cb690351696a811210b9d990ee4cde3cfb2a3446 100644
+index 338a19b0e88ad6f08d2f6b6a5d38b9980996ce11..a4ee215575d072450ba66c558ddca88bfb23d85f 100644
--- a/test/parallel/test-crypto-scrypt.js
+++ b/test/parallel/test-crypto-scrypt.js
@@ -178,7 +178,7 @@ for (const options of bad) {
@@ -608,26 +395,19 @@ index 61bd65fc92678c24baa3c0eb9ffb1ead64ace70b..cb690351696a811210b9d990ee4cde3c
};
assert.throws(() => crypto.scrypt('pass', 'salt', 1, options, () => {}),
diff --git a/test/parallel/test-crypto-sign-verify.js b/test/parallel/test-crypto-sign-verify.js
-index 9dd586a1a1f9a00d9bb0af5b0532e81e7b96a5ce..1a0d0cfc09fb61d65472723ba54e1d0be69b5c68 100644
+index 9dd586a1a1f9a00d9bb0af5b0532e81e7b96a5ce..a37e6d50914345829c8260a97949cee7d17ab676 100644
--- a/test/parallel/test-crypto-sign-verify.js
+++ b/test/parallel/test-crypto-sign-verify.js
-@@ -28,6 +28,7 @@ const keySize = 2048;
- 'instance when called without `new`');
+@@ -29,7 +29,7 @@ const keySize = 2048;
}
-+/*
// Test handling of exceptional conditions
- {
+-{
++if (!common.openSSLIsBoringSSL) {
const library = {
-@@ -68,6 +69,7 @@ const keySize = 2048;
-
- delete Object.prototype.opensslErrorStack;
- }
-+*/
-
- assert.throws(
- () => crypto.createVerify('SHA256').verify({
-@@ -341,15 +343,17 @@ assert.throws(
+ configurable: true,
+ set() {
+@@ -341,15 +341,17 @@ assert.throws(
padding: crypto.constants.RSA_PKCS1_OAEP_PADDING
});
}, common.hasOpenSSL3 ? {
@@ -649,7 +429,7 @@ index 9dd586a1a1f9a00d9bb0af5b0532e81e7b96a5ce..1a0d0cfc09fb61d65472723ba54e1d0b
});
}
-@@ -419,10 +423,12 @@ assert.throws(
+@@ -419,10 +421,12 @@ assert.throws(
public: fixtures.readKey('ed25519_public.pem', 'ascii'),
algo: null,
sigLen: 64 },
@@ -662,7 +442,7 @@ index 9dd586a1a1f9a00d9bb0af5b0532e81e7b96a5ce..1a0d0cfc09fb61d65472723ba54e1d0b
{ private: fixtures.readKey('rsa_private_2048.pem', 'ascii'),
public: fixtures.readKey('rsa_public_2048.pem', 'ascii'),
algo: 'sha1',
-@@ -493,7 +499,7 @@ assert.throws(
+@@ -493,7 +497,7 @@ assert.throws(
{
const data = Buffer.from('Hello world');
@@ -776,10 +556,10 @@ index 89a7521544f7051edc1779138551bbad1972b3fb..91df6acc65d4003999f29f0fa5f63905
}
+*/
diff --git a/test/parallel/test-crypto.js b/test/parallel/test-crypto.js
-index a8ceb169de2b3de73f062083c42292babc673e73..8fb950d0814e5014faf5c1ef576b65795857da1b 100644
+index 4271121881379b6c6892e89e520345f77e4181df..6c87a1ac687aa37d4ba245d1b6fc746a5f1eeffc 100644
--- a/test/parallel/test-crypto.js
+++ b/test/parallel/test-crypto.js
-@@ -67,7 +67,7 @@ assert.throws(() => {
+@@ -61,7 +61,7 @@ assert.throws(() => {
// Throws general Error, so there is no opensslErrorStack property.
return err instanceof Error &&
err.name === 'Error' &&
@@ -788,7 +568,7 @@ index a8ceb169de2b3de73f062083c42292babc673e73..8fb950d0814e5014faf5c1ef576b6579
!('opensslErrorStack' in err);
});
-@@ -77,7 +77,7 @@ assert.throws(() => {
+@@ -71,7 +71,7 @@ assert.throws(() => {
// Throws general Error, so there is no opensslErrorStack property.
return err instanceof Error &&
err.name === 'Error' &&
@@ -797,7 +577,7 @@ index a8ceb169de2b3de73f062083c42292babc673e73..8fb950d0814e5014faf5c1ef576b6579
!('opensslErrorStack' in err);
});
-@@ -87,7 +87,7 @@ assert.throws(() => {
+@@ -81,7 +81,7 @@ assert.throws(() => {
// Throws general Error, so there is no opensslErrorStack property.
return err instanceof Error &&
err.name === 'Error' &&
@@ -806,7 +586,7 @@ index a8ceb169de2b3de73f062083c42292babc673e73..8fb950d0814e5014faf5c1ef576b6579
!('opensslErrorStack' in err);
});
-@@ -150,8 +150,6 @@ assert(crypto.getHashes().includes('sha1'));
+@@ -144,8 +144,6 @@ assert(crypto.getHashes().includes('sha1'));
assert(crypto.getHashes().includes('sha256'));
assert(!crypto.getHashes().includes('SHA1'));
assert(!crypto.getHashes().includes('SHA256'));
@@ -815,16 +595,7 @@ index a8ceb169de2b3de73f062083c42292babc673e73..8fb950d0814e5014faf5c1ef576b6579
validateList(crypto.getHashes());
// Make sure all of the hashes are supported by OpenSSL
for (const algo of crypto.getHashes())
-@@ -188,7 +186,7 @@ const encodingError = {
- // hex input that's not a power of two should throw, not assert in C++ land.
- ['createCipher', 'createDecipher'].forEach((funcName) => {
- assert.throws(
-- () => crypto[funcName]('aes192', 'test').update('0', 'hex'),
-+ () => crypto[funcName]('aes-192-cbc', 'test').update('0', 'hex'),
- (error) => {
- assert.ok(!('opensslErrorStack' in error));
- if (common.hasFipsCrypto) {
-@@ -219,7 +217,7 @@ assert.throws(
+@@ -195,7 +193,7 @@ assert.throws(
return true;
}
);
@@ -833,7 +604,7 @@ index a8ceb169de2b3de73f062083c42292babc673e73..8fb950d0814e5014faf5c1ef576b6579
assert.throws(() => {
const priv = [
'-----BEGIN RSA PRIVATE KEY-----',
-@@ -232,6 +230,7 @@ assert.throws(() => {
+@@ -208,6 +206,7 @@ assert.throws(() => {
].join('\n');
crypto.createSign('SHA256').update('test').sign(priv);
}, (err) => {
@@ -841,7 +612,7 @@ index a8ceb169de2b3de73f062083c42292babc673e73..8fb950d0814e5014faf5c1ef576b6579
if (!common.hasOpenSSL3)
assert.ok(!('opensslErrorStack' in err));
assert.throws(() => { throw err; }, common.hasOpenSSL3 ? {
-@@ -240,10 +239,10 @@ assert.throws(() => {
+@@ -216,10 +215,10 @@ assert.throws(() => {
library: 'rsa routines',
} : {
name: 'Error',
@@ -856,7 +627,7 @@ index a8ceb169de2b3de73f062083c42292babc673e73..8fb950d0814e5014faf5c1ef576b6579
code: 'ERR_OSSL_RSA_DIGEST_TOO_BIG_FOR_RSA_KEY'
});
return true;
-@@ -276,7 +275,7 @@ if (!common.hasOpenSSL3) {
+@@ -252,7 +251,7 @@ if (!common.hasOpenSSL3) {
return true;
});
}
@@ -954,56 +725,62 @@ index b06f2fa2c53ea72f9a66f0d002dd9281d0259a0f..864fffeebfad75d95416fd47efdea7f2
const server = https.createServer(opts, (req, res) => {
diff --git a/test/parallel/test-webcrypto-derivebits.js b/test/parallel/test-webcrypto-derivebits.js
-index eb09bc24f0cb8244b05987e3a7c1d203360d3a38..da891fffa29d5666d91e4445e54c43e3688b870a 100644
+index eb09bc24f0cb8244b05987e3a7c1d203360d3a38..011990db171faa708c5211f6ab9ae1ac0e0ab90e 100644
--- a/test/parallel/test-webcrypto-derivebits.js
+++ b/test/parallel/test-webcrypto-derivebits.js
-@@ -101,6 +101,7 @@ const { subtle } = globalThis.crypto;
+@@ -101,8 +101,9 @@ const { subtle } = globalThis.crypto;
tests.then(common.mustCall());
}
-+/*
++
// Test X25519 and X448 bit derivation
- {
+-{
++if (!common.openSSLIsBoringSSL) {
async function test(name) {
+ const [alice, bob] = await Promise.all([
+ subtle.generateKey({ name }, true, ['deriveBits']),
@@ -126,3 +127,4 @@ const { subtle } = globalThis.crypto;
test('X25519').then(common.mustCall());
test('X448').then(common.mustCall());
}
-+*/
++
diff --git a/test/parallel/test-webcrypto-derivekey.js b/test/parallel/test-webcrypto-derivekey.js
-index 558d37d90d5796b30101d1b512c9df3e7661d0db..c18f9670b10cb84c6902391f20e0ff75729cc960 100644
+index 558d37d90d5796b30101d1b512c9df3e7661d0db..f42bf8f4be0b439dd7e7c8d0f6f8a41e01588870 100644
--- a/test/parallel/test-webcrypto-derivekey.js
+++ b/test/parallel/test-webcrypto-derivekey.js
-@@ -175,6 +175,7 @@ const { KeyObject } = require('crypto');
- })().then(common.mustCall());
+@@ -176,7 +176,7 @@ const { KeyObject } = require('crypto');
}
-+/*
// Test X25519 and X448 key derivation
- {
+-{
++if (!common.openSSLIsBoringSSL) {
async function test(name) {
-@@ -209,3 +210,4 @@ const { KeyObject } = require('crypto');
- test('X25519').then(common.mustCall());
- test('X448').then(common.mustCall());
- }
-+*/
+ const [alice, bob] = await Promise.all([
+ subtle.generateKey({ name }, true, ['deriveKey']),
diff --git a/test/parallel/test-webcrypto-sign-verify.js b/test/parallel/test-webcrypto-sign-verify.js
-index de736102bdcb71a5560c95f7041537f25026aed4..638fdf0d798f3309528c63f0f8598f3df5528339 100644
+index de736102bdcb71a5560c95f7041537f25026aed4..12d7fa39446c196bdf1479dbe74c9ee8ab02f949 100644
--- a/test/parallel/test-webcrypto-sign-verify.js
+++ b/test/parallel/test-webcrypto-sign-verify.js
-@@ -105,6 +105,7 @@ const { subtle } = globalThis.crypto;
+@@ -105,8 +105,9 @@ const { subtle } = globalThis.crypto;
test('hello world').then(common.mustCall());
}
-+/*
++
// Test Sign/Verify Ed25519
- {
+-{
++if (!common.openSSLIsBoringSSL) {
async function test(data) {
-@@ -144,3 +145,4 @@ const { subtle } = globalThis.crypto;
-
- test('hello world').then(common.mustCall());
+ const ec = new TextEncoder();
+ const { publicKey, privateKey } = await subtle.generateKey({
+@@ -126,7 +127,7 @@ const { subtle } = globalThis.crypto;
}
-+*/
+
+ // Test Sign/Verify Ed448
+-{
++if (!common.openSSLIsBoringSSL) {
+ async function test(data) {
+ const ec = new TextEncoder();
+ const { publicKey, privateKey } = await subtle.generateKey({
diff --git a/test/parallel/test-webcrypto-wrap-unwrap.js b/test/parallel/test-webcrypto-wrap-unwrap.js
index d1ca571af4be713082d32093bfb8a65f2aef9800..57b8df2ce18df58ff54b2d828af67e3c2e082fe0 100644
--- a/test/parallel/test-webcrypto-wrap-unwrap.js
diff --git a/patches/node/fix_do_not_resolve_electron_entrypoints.patch b/patches/node/fix_do_not_resolve_electron_entrypoints.patch
index e5177c8297..fba87eb85f 100644
--- a/patches/node/fix_do_not_resolve_electron_entrypoints.patch
+++ b/patches/node/fix_do_not_resolve_electron_entrypoints.patch
@@ -6,10 +6,10 @@ Subject: fix: do not resolve electron entrypoints
This wastes fs cycles and can result in strange behavior if this path actually exists on disk
diff --git a/lib/internal/modules/esm/load.js b/lib/internal/modules/esm/load.js
-index 22248b753c14960122f1d6b9bfe6b89fdb8d2010..9d245a04fbcb98dcd1c61e60f7cfe528bd1c8af0 100644
+index 463e76cb1abc0c2fdddba4db2ca2e00f7c591e12..d7bc3c35c77b5bf9ec122b38248d0cf1f4d2a548 100644
--- a/lib/internal/modules/esm/load.js
+++ b/lib/internal/modules/esm/load.js
-@@ -132,7 +132,7 @@ async function defaultLoad(url, context = kEmptyObject) {
+@@ -111,7 +111,7 @@ async function defaultLoad(url, context = kEmptyObject) {
source = null;
format ??= 'builtin';
} else if (format !== 'commonjs' || defaultType === 'module') {
@@ -19,10 +19,10 @@ index 22248b753c14960122f1d6b9bfe6b89fdb8d2010..9d245a04fbcb98dcd1c61e60f7cfe528
context = { __proto__: context, source };
}
diff --git a/lib/internal/modules/esm/translators.js b/lib/internal/modules/esm/translators.js
-index f3dfc69cd2cdec50bc3b3f7cb2d63349812d87dd..b6f2d7194cb75ecc8c47869761c63184707ade40 100644
+index 06b31af80ebbfbf35ec787a94f345775eb512ebf..deca5aa4b8829ba9921440fcb5c285a10e40c8f0 100644
--- a/lib/internal/modules/esm/translators.js
+++ b/lib/internal/modules/esm/translators.js
-@@ -375,6 +375,9 @@ function cjsPreparseModuleExports(filename, source) {
+@@ -354,6 +354,9 @@ function cjsPreparseModuleExports(filename, source) {
if (module && module[kModuleExportNames] !== undefined) {
return { module, exportNames: module[kModuleExportNames] };
}
@@ -33,7 +33,7 @@ index f3dfc69cd2cdec50bc3b3f7cb2d63349812d87dd..b6f2d7194cb75ecc8c47869761c63184
if (!loaded) {
module = new CJSModule(filename);
diff --git a/lib/internal/modules/run_main.js b/lib/internal/modules/run_main.js
-index ca401044c0178c46db9b439b27c440a5d7924c84..dc1a682f0a3cf1ba1095c60bf6a6ca992d6043b3 100644
+index 1e1a1ea46fc6c1b43cad4038ab0d9cdf21d6ba3d..95e2fa5479ea31559fdb5a2e03515f243b231b75 100644
--- a/lib/internal/modules/run_main.js
+++ b/lib/internal/modules/run_main.js
@@ -2,6 +2,7 @@
@@ -41,10 +41,10 @@ index ca401044c0178c46db9b439b27c440a5d7924c84..dc1a682f0a3cf1ba1095c60bf6a6ca99
const {
StringPrototypeEndsWith,
+ StringPrototypeStartsWith,
+ globalThis,
} = primordials;
- const { containsModuleSyntax } = internalBinding('contextify');
-@@ -22,6 +23,13 @@ const {
+@@ -26,6 +27,13 @@ const {
* @param {string} main - Entry point path
*/
function resolveMainPath(main) {
@@ -58,7 +58,7 @@ index ca401044c0178c46db9b439b27c440a5d7924c84..dc1a682f0a3cf1ba1095c60bf6a6ca99
const defaultType = getOptionValue('--experimental-default-type');
/** @type {string} */
let mainPath;
-@@ -59,6 +67,13 @@ function resolveMainPath(main) {
+@@ -63,6 +71,13 @@ function resolveMainPath(main) {
* @param {string} mainPath - Absolute path to the main entry point
*/
function shouldUseESMLoader(mainPath) {
diff --git a/patches/node/fix_expose_the_built-in_electron_module_via_the_esm_loader.patch b/patches/node/fix_expose_the_built-in_electron_module_via_the_esm_loader.patch
index ee7a6cf34a..1f84223398 100644
--- a/patches/node/fix_expose_the_built-in_electron_module_via_the_esm_loader.patch
+++ b/patches/node/fix_expose_the_built-in_electron_module_via_the_esm_loader.patch
@@ -6,22 +6,22 @@ Subject: fix: expose the built-in electron module via the ESM loader
This allows usage of `import { app } from 'electron'` and `import('electron')` natively in the browser + non-sandboxed renderer
diff --git a/lib/internal/modules/esm/get_format.js b/lib/internal/modules/esm/get_format.js
-index 1fe5564545dbc86d7f2968274a25ee1579bcbf28..b876af21a0e97ae06dc344d9f78c8f5c7e403d43 100644
+index a89446df710a941390c15171fea63c551776fc93..912f03bfa96c3aa12bfa6e709746642452568bb7 100644
--- a/lib/internal/modules/esm/get_format.js
+++ b/lib/internal/modules/esm/get_format.js
-@@ -31,6 +31,7 @@ const protocolHandlers = {
- 'http:': getHttpProtocolModuleFormat,
- 'https:': getHttpProtocolModuleFormat,
+@@ -26,6 +26,7 @@ const protocolHandlers = {
+ 'data:': getDataProtocolModuleFormat,
+ 'file:': getFileProtocolModuleFormat,
'node:'() { return 'builtin'; },
+ 'electron:'() { return 'electron'; },
};
/**
diff --git a/lib/internal/modules/esm/load.js b/lib/internal/modules/esm/load.js
-index 7b77af35a1dfebf6ad45ace521f1a55b5fa18293..ac24cf305bd5995ad13b37ee36f9e1fe3589c5d7 100644
+index 8b157f0f461c7b92c567fffe4d99357dbc09aee7..605e812d515fc467001e4ab88fc15b4af3fd4aa2 100644
--- a/lib/internal/modules/esm/load.js
+++ b/lib/internal/modules/esm/load.js
-@@ -142,7 +142,7 @@ async function defaultLoad(url, context = kEmptyObject) {
+@@ -121,7 +121,7 @@ async function defaultLoad(url, context = kEmptyObject) {
// Now that we have the source for the module, run `defaultGetFormat` to detect its format.
format = await defaultGetFormat(urlInstance, context);
@@ -30,37 +30,35 @@ index 7b77af35a1dfebf6ad45ace521f1a55b5fa18293..ac24cf305bd5995ad13b37ee36f9e1fe
// For backward compatibility reasons, we need to discard the source in
// order for the CJS loader to re-fetch it.
source = null;
-@@ -234,6 +234,7 @@ function throwIfUnsupportedURLScheme(parsed, experimentalNetworkImports) {
+@@ -218,12 +218,13 @@ function throwIfUnsupportedURLScheme(parsed) {
protocol !== 'file:' &&
protocol !== 'data:' &&
protocol !== 'node:' &&
+ protocol !== 'electron:' &&
(
- !experimentalNetworkImports ||
- (
-@@ -242,7 +243,7 @@ function throwIfUnsupportedURLScheme(parsed, experimentalNetworkImports) {
- )
+ protocol !== 'https:' &&
+ protocol !== 'http:'
)
) {
- const schemes = ['file', 'data', 'node'];
+ const schemes = ['file', 'data', 'node', 'electron'];
- if (experimentalNetworkImports) {
- ArrayPrototypePush(schemes, 'https', 'http');
- }
+ throw new ERR_UNSUPPORTED_ESM_URL_SCHEME(parsed, schemes);
+ }
+ }
diff --git a/lib/internal/modules/esm/resolve.js b/lib/internal/modules/esm/resolve.js
-index e73a8ad60a13925d6773c32cead8d04ec9d96ee7..52cdb7d5e14a18ed7b1b65e429729cf47dce3f98 100644
+index 1fbbb6773c9479128408fa1f27cf19f1a7786ba6..f05c6f99c0037193c5802024be46a967d6cf47a0 100644
--- a/lib/internal/modules/esm/resolve.js
+++ b/lib/internal/modules/esm/resolve.js
-@@ -741,6 +741,8 @@ function packageImportsResolve(name, base, conditions) {
- throw importNotDefined(name, packageJSONUrl, base);
+@@ -772,6 +772,8 @@ function parsePackageName(specifier, base) {
+ return { packageName, packageSubpath, isScoped };
}
+const electronTypes = ['electron', 'electron/main', 'electron/common', 'electron/renderer'];
+
/**
- * Returns the package type for a given URL.
- * @param {URL} url - The URL to get the package type for.
-@@ -801,6 +803,11 @@ function packageResolve(specifier, base, conditions) {
+ * Resolves a package specifier to a URL.
+ * @param {string} specifier - The package specifier to resolve.
+@@ -785,6 +787,11 @@ function packageResolve(specifier, base, conditions) {
return new URL('node:' + specifier);
}
@@ -73,10 +71,10 @@ index e73a8ad60a13925d6773c32cead8d04ec9d96ee7..52cdb7d5e14a18ed7b1b65e429729cf4
parsePackageName(specifier, base);
diff --git a/lib/internal/modules/esm/translators.js b/lib/internal/modules/esm/translators.js
-index 8f4b6b25d8889686d00613fd9821b0aa822a946a..89ca269294ee1afa7f5aeb0ac6b8958f7a8b49d0 100644
+index 8f88214f558c52ef26000fb0e1ef4d391327e84e..d182eedf5e96039e0029d36e51f40b75c6fb2a39 100644
--- a/lib/internal/modules/esm/translators.js
+++ b/lib/internal/modules/esm/translators.js
-@@ -272,7 +272,7 @@ function createCJSModuleWrap(url, source, isMain, loadCJS = loadCJSModule) {
+@@ -246,7 +246,7 @@ function createCJSModuleWrap(url, source, isMain, loadCJS = loadCJSModule) {
const { exportNames, module } = cjsPreparseModuleExports(filename, source);
cjsCache.set(url, module);
@@ -85,7 +83,7 @@ index 8f4b6b25d8889686d00613fd9821b0aa822a946a..89ca269294ee1afa7f5aeb0ac6b8958f
[...exportNames] : ['default', ...exportNames];
if (isMain) {
-@@ -294,8 +294,8 @@ function createCJSModuleWrap(url, source, isMain, loadCJS = loadCJSModule) {
+@@ -268,8 +268,8 @@ function createCJSModuleWrap(url, source, isMain, loadCJS = loadCJSModule) {
({ exports } = module);
}
for (const exportName of exportNames) {
@@ -96,7 +94,7 @@ index 8f4b6b25d8889686d00613fd9821b0aa822a946a..89ca269294ee1afa7f5aeb0ac6b8958f
continue;
}
// We might trigger a getter -> dont fail.
-@@ -329,6 +329,10 @@ translators.set('require-commonjs', (url, source, isMain) => {
+@@ -304,6 +304,10 @@ translators.set('require-commonjs', (url, source, isMain) => {
return createCJSModuleWrap(url, source);
});
@@ -104,14 +102,14 @@ index 8f4b6b25d8889686d00613fd9821b0aa822a946a..89ca269294ee1afa7f5aeb0ac6b8958f
+ return createCJSModuleWrap('electron', '');
+});
+
- // Handle CommonJS modules referenced by `import` statements or expressions,
- // or as the initial entry point when the ESM loader handles a CommonJS entry.
- translators.set('commonjs', async function commonjsStrategy(url, source,
+ // Handle CommonJS modules referenced by `require` calls.
+ // This translator function must be sync, as `require` is sync.
+ translators.set('require-commonjs-typescript', (url, source, isMain) => {
diff --git a/lib/internal/url.js b/lib/internal/url.js
-index e6ed5466b8807a52633d8406824058bdc8c2ce13..e055facddf086eb8fb456b865ce006cdb7602b0a 100644
+index 3cb186182947a14407e9d5c4d94ab0554298a658..e35ae9ac316ba2e5b8f562d353b2c5ae978abb63 100644
--- a/lib/internal/url.js
+++ b/lib/internal/url.js
-@@ -1485,6 +1485,8 @@ function fileURLToPath(path, options = kEmptyObject) {
+@@ -1495,6 +1495,8 @@ function fileURLToPath(path, options = kEmptyObject) {
path = new URL(path);
else if (!isURL(path))
throw new ERR_INVALID_ARG_TYPE('path', ['string', 'URL'], path);
diff --git a/patches/node/fix_expose_tracing_agent_and_use_tracing_tracingcontroller_instead.patch b/patches/node/fix_expose_tracing_agent_and_use_tracing_tracingcontroller_instead.patch
index cf1dc86655..5f005aef01 100644
--- a/patches/node/fix_expose_tracing_agent_and_use_tracing_tracingcontroller_instead.patch
+++ b/patches/node/fix_expose_tracing_agent_and_use_tracing_tracingcontroller_instead.patch
@@ -7,10 +7,10 @@ Subject: fix: expose tracing::Agent and use tracing::TracingController instead
This API is used by Electron to create Node's tracing controller.
diff --git a/src/api/environment.cc b/src/api/environment.cc
-index 46106fa94b3055648e4f01cd28860d427268a253..e0bf37f09dceb93af58990438ab577a9d4b843e8 100644
+index 77c20a4b6b9db414444974f68c5def8788386d2b..5fc1b6f2446d7c786024eb60800e2edab613dcd1 100644
--- a/src/api/environment.cc
+++ b/src/api/environment.cc
-@@ -557,6 +557,10 @@ MultiIsolatePlatform* GetMultiIsolatePlatform(IsolateData* env) {
+@@ -564,6 +564,10 @@ MultiIsolatePlatform* GetMultiIsolatePlatform(IsolateData* env) {
return env->platform();
}
@@ -22,7 +22,7 @@ index 46106fa94b3055648e4f01cd28860d427268a253..e0bf37f09dceb93af58990438ab577a9
int thread_pool_size,
node::tracing::TracingController* tracing_controller) {
diff --git a/src/node.h b/src/node.h
-index 6373adacb628459a4c9d7237da2587aee318e2d8..4f2eb9d0aab88b70c86339e750799080e980d7da 100644
+index 60598f54114b2424f10706e57d8aa50c4634bcb0..0fec9477fd0f2a3c2aa68284131c510b0da0e025 100644
--- a/src/node.h
+++ b/src/node.h
@@ -133,6 +133,7 @@ struct SnapshotData;
diff --git a/patches/node/fix_handle_boringssl_and_openssl_incompatibilities.patch b/patches/node/fix_handle_boringssl_and_openssl_incompatibilities.patch
index 82c13656c6..0ffc9526e8 100644
--- a/patches/node/fix_handle_boringssl_and_openssl_incompatibilities.patch
+++ b/patches/node/fix_handle_boringssl_and_openssl_incompatibilities.patch
@@ -16,11 +16,125 @@ Upstreams:
- https://github.com/nodejs/node/pull/39138
- https://github.com/nodejs/node/pull/39136
+diff --git a/deps/ncrypto/ncrypto.cc b/deps/ncrypto/ncrypto.cc
+index eb3533bb4623b152605c3c590f37f086cce5f073..ded231aeaa15af22845704cfcc7d24a44bd88f8e 100644
+--- a/deps/ncrypto/ncrypto.cc
++++ b/deps/ncrypto/ncrypto.cc
+@@ -6,13 +6,11 @@
+ #include <openssl/evp.h>
+ #include <openssl/hmac.h>
+ #include <openssl/pkcs12.h>
++#include <openssl/rand.h>
+ #include <openssl/x509v3.h>
+ #if OPENSSL_VERSION_MAJOR >= 3
+ #include <openssl/provider.h>
+ #endif
+-#ifdef OPENSSL_IS_BORINGSSL
+-#include "dh-primes.h"
+-#endif // OPENSSL_IS_BORINGSSL
+
+ namespace ncrypto {
+ namespace {
+@@ -665,7 +663,7 @@ bool SafeX509SubjectAltNamePrint(const BIOPointer& out, X509_EXTENSION* ext) {
+
+ bool ok = true;
+
+- for (int i = 0; i < sk_GENERAL_NAME_num(names); i++) {
++ for (size_t i = 0; i < sk_GENERAL_NAME_num(names); i++) {
+ GENERAL_NAME* gen = sk_GENERAL_NAME_value(names, i);
+
+ if (i != 0)
+@@ -691,7 +689,7 @@ bool SafeX509InfoAccessPrint(const BIOPointer& out, X509_EXTENSION* ext) {
+
+ bool ok = true;
+
+- for (int i = 0; i < sk_ACCESS_DESCRIPTION_num(descs); i++) {
++ for (size_t i = 0; i < sk_ACCESS_DESCRIPTION_num(descs); i++) {
+ ACCESS_DESCRIPTION* desc = sk_ACCESS_DESCRIPTION_value(descs, i);
+
+ if (i != 0)
+@@ -1002,7 +1000,11 @@ BIOPointer BIOPointer::NewMem() {
+ }
+
+ BIOPointer BIOPointer::NewSecMem() {
++#ifdef OPENSSL_IS_BORINGSSL
++ return BIOPointer(BIO_new(BIO_s_mem()));
++#else
+ return BIOPointer(BIO_new(BIO_s_secmem()));
++#endif
+ }
+
+ BIOPointer BIOPointer::New(const BIO_METHOD* method) {
+@@ -1057,8 +1059,10 @@ BignumPointer DHPointer::FindGroup(const std::string_view name,
+ FindGroupOption option) {
+ #define V(n, p) if (EqualNoCase(name, n)) return BignumPointer(p(nullptr));
+ if (option != FindGroupOption::NO_SMALL_PRIMES) {
++#ifndef OPENSSL_IS_BORINGSSL
+ V("modp1", BN_get_rfc2409_prime_768);
+ V("modp2", BN_get_rfc2409_prime_1024);
++#endif
+ V("modp5", BN_get_rfc3526_prime_1536);
+ }
+ V("modp14", BN_get_rfc3526_prime_2048);
+@@ -1130,11 +1134,13 @@ DHPointer::CheckPublicKeyResult DHPointer::checkPublicKey(const BignumPointer& p
+ int codes = 0;
+ if (DH_check_pub_key(dh_.get(), pub_key.get(), &codes) != 1)
+ return DHPointer::CheckPublicKeyResult::CHECK_FAILED;
++#ifndef OPENSSL_IS_BORINGSSL
+ if (codes & DH_CHECK_PUBKEY_TOO_SMALL) {
+ return DHPointer::CheckPublicKeyResult::TOO_SMALL;
+ } else if (codes & DH_CHECK_PUBKEY_TOO_SMALL) {
+ return DHPointer::CheckPublicKeyResult::TOO_LARGE;
+- } else if (codes != 0) {
++#endif
++ if (codes != 0) {
+ return DHPointer::CheckPublicKeyResult::INVALID;
+ }
+ return CheckPublicKeyResult::NONE;
+diff --git a/deps/ncrypto/ncrypto.h b/deps/ncrypto/ncrypto.h
+index 661c996889d0a89c1c38658a0933fcf5e3cdc1b9..1261d5d99fdf4e17b8dec66660028ce184f1cf89 100644
+--- a/deps/ncrypto/ncrypto.h
++++ b/deps/ncrypto/ncrypto.h
+@@ -413,8 +413,8 @@ public:
+ #ifndef OPENSSL_IS_BORINGSSL
+ TOO_SMALL = DH_R_CHECK_PUBKEY_TOO_SMALL,
+ TOO_LARGE = DH_R_CHECK_PUBKEY_TOO_LARGE,
+- INVALID = DH_R_CHECK_PUBKEY_INVALID,
+ #endif
++ INVALID = DH_R_INVALID_PUBKEY,
+ CHECK_FAILED = 512,
+ };
+ // Check to see if the given public key is suitable for this DH instance.
+diff --git a/deps/ncrypto/unofficial.gni b/deps/ncrypto/unofficial.gni
+index ea024af73e215b3cad5f08796ac405f419530c86..41061b524eea74330b8d2452635a38c48f21386b 100644
+--- a/deps/ncrypto/unofficial.gni
++++ b/deps/ncrypto/unofficial.gni
+@@ -27,6 +27,6 @@ template("ncrypto_gn_build") {
+ forward_variables_from(invoker, "*")
+ public_configs = [ ":ncrypto_config" ]
+ sources = gypi_values.ncrypto_sources
+- deps = [ "../openssl" ]
++ deps = [ "$node_crypto_path" ]
+ }
+ }
+diff --git a/node.gni b/node.gni
+index 32709b860ccb12d8d1e75342a65dda0b86129b21..18d58591e3d0f1f3512db00033c3410a65702864 100644
+--- a/node.gni
++++ b/node.gni
+@@ -10,6 +10,8 @@ declare_args() {
+ # The location of V8, use the one from node's deps by default.
+ node_v8_path = "//v8"
+
++ node_crypto_path = "//third_party/boringssl"
++
+ # The NODE_MODULE_VERSION defined in node_version.h.
+ node_module_version = exec_script("$node_path/tools/getmoduleversion.py", [], "value")
+
diff --git a/src/crypto/crypto_cipher.cc b/src/crypto/crypto_cipher.cc
-index 4f0637f9511d1b90ae9d33760428dceb772667bd..5aba390c49613816ac359dfe995dc2c0a93f2206 100644
+index fe35a8e0f6bbb7ab515a0343a7ed046c44e86474..43a7abbf237d8d809953e302b83755a3283a1bf4 100644
--- a/src/crypto/crypto_cipher.cc
+++ b/src/crypto/crypto_cipher.cc
-@@ -1088,7 +1088,7 @@ void PublicKeyCipher::Cipher(const FunctionCallbackInfo<Value>& args) {
+@@ -1078,7 +1078,7 @@ void PublicKeyCipher::Cipher(const FunctionCallbackInfo<Value>& args) {
if (EVP_PKEY_decrypt_init(ctx.get()) <= 0) {
return ThrowCryptoError(env, ERR_get_error());
}
@@ -29,19 +143,19 @@ index 4f0637f9511d1b90ae9d33760428dceb772667bd..5aba390c49613816ac359dfe995dc2c0
int rsa_pkcs1_implicit_rejection =
EVP_PKEY_CTX_ctrl_str(ctx.get(), "rsa_pkcs1_implicit_rejection", "1");
// From the doc -2 means that the option is not supported.
-@@ -1104,6 +1104,7 @@ void PublicKeyCipher::Cipher(const FunctionCallbackInfo<Value>& args) {
+@@ -1094,6 +1094,7 @@ void PublicKeyCipher::Cipher(const FunctionCallbackInfo<Value>& args) {
"RSA_PKCS1_PADDING is no longer supported for private decryption,"
- " this can be reverted with --security-revert=CVE-2023-46809");
+ " this can be reverted with --security-revert=CVE-2024-PEND");
}
+#endif
}
const EVP_MD* digest = nullptr;
diff --git a/src/crypto/crypto_common.cc b/src/crypto/crypto_common.cc
-index 85d48dfd2c15c453707bf6eb94e22f89b4f856b2..fe31a9a7f465a03d2de365cef392dfbb7c540156 100644
+index 6a967702b22df0eb8aa10e853fd232794955860d..31058cccc6ffeed6b09aaecda320ee2f15849ec8 100644
--- a/src/crypto/crypto_common.cc
+++ b/src/crypto/crypto_common.cc
-@@ -158,7 +158,7 @@ const char* GetClientHelloALPN(const SSLPointer& ssl) {
+@@ -134,7 +134,7 @@ const char* GetClientHelloALPN(const SSLPointer& ssl) {
const unsigned char* buf;
size_t len;
size_t rem;
@@ -50,7 +164,7 @@ index 85d48dfd2c15c453707bf6eb94e22f89b4f856b2..fe31a9a7f465a03d2de365cef392dfbb
if (!SSL_client_hello_get0_ext(
ssl.get(),
TLSEXT_TYPE_application_layer_protocol_negotiation,
-@@ -171,13 +171,15 @@ const char* GetClientHelloALPN(const SSLPointer& ssl) {
+@@ -147,13 +147,15 @@ const char* GetClientHelloALPN(const SSLPointer& ssl) {
len = (buf[0] << 8) | buf[1];
if (len + 2 != rem) return nullptr;
return reinterpret_cast<const char*>(buf + 3);
@@ -67,7 +181,7 @@ index 85d48dfd2c15c453707bf6eb94e22f89b4f856b2..fe31a9a7f465a03d2de365cef392dfbb
if (!SSL_client_hello_get0_ext(
ssl.get(),
TLSEXT_TYPE_server_name,
-@@ -199,6 +201,8 @@ const char* GetClientHelloServerName(const SSLPointer& ssl) {
+@@ -175,6 +177,8 @@ const char* GetClientHelloServerName(const SSLPointer& ssl) {
if (len + 2 > rem)
return nullptr;
return reinterpret_cast<const char*>(buf + 5);
@@ -76,7 +190,25 @@ index 85d48dfd2c15c453707bf6eb94e22f89b4f856b2..fe31a9a7f465a03d2de365cef392dfbb
}
const char* GetServerName(SSL* ssl) {
-@@ -1036,14 +1040,14 @@ MaybeLocal<Array> GetClientHelloCiphers(
+@@ -282,7 +286,7 @@ StackOfX509 CloneSSLCerts(X509Pointer&& cert,
+ if (!peer_certs) return StackOfX509();
+ if (cert && !sk_X509_push(peer_certs.get(), cert.release()))
+ return StackOfX509();
+- for (int i = 0; i < sk_X509_num(ssl_certs); i++) {
++ for (size_t i = 0; i < sk_X509_num(ssl_certs); i++) {
+ X509Pointer cert(X509_dup(sk_X509_value(ssl_certs, i)));
+ if (!cert || !sk_X509_push(peer_certs.get(), cert.get()))
+ return StackOfX509();
+@@ -298,7 +302,7 @@ MaybeLocal<Object> AddIssuerChainToObject(X509Pointer* cert,
+ Environment* const env) {
+ cert->reset(sk_X509_delete(peer_certs.get(), 0));
+ for (;;) {
+- int i;
++ size_t i;
+ for (i = 0; i < sk_X509_num(peer_certs.get()); i++) {
+ ncrypto::X509View ca(sk_X509_value(peer_certs.get(), i));
+ if (!cert->view().isIssuedBy(ca)) continue;
+@@ -384,14 +388,14 @@ MaybeLocal<Array> GetClientHelloCiphers(
Environment* env,
const SSLPointer& ssl) {
EscapableHandleScope scope(env->isolate());
@@ -95,7 +227,7 @@ index 85d48dfd2c15c453707bf6eb94e22f89b4f856b2..fe31a9a7f465a03d2de365cef392dfbb
Local<Object> obj = Object::New(env->isolate());
if (!Set(env->context(),
obj,
-@@ -1096,8 +1100,11 @@ MaybeLocal<Object> GetEphemeralKey(Environment* env, const SSLPointer& ssl) {
+@@ -444,8 +448,11 @@ MaybeLocal<Object> GetEphemeralKey(Environment* env, const SSLPointer& ssl) {
EscapableHandleScope scope(env->isolate());
Local<Object> info = Object::New(env->isolate());
@@ -109,19 +241,19 @@ index 85d48dfd2c15c453707bf6eb94e22f89b4f856b2..fe31a9a7f465a03d2de365cef392dfbb
crypto::EVPKeyPointer key(raw_key);
diff --git a/src/crypto/crypto_context.cc b/src/crypto/crypto_context.cc
-index cef0c877c67643d47da787eddb95ed5a410a941b..1b8af49a48f1a34a92d4f0b502d435f3a4ab5d8e 100644
+index c924a54639e8c22d765dc240dffacfffb200ca0c..287afcc792a0a2b7e19126ee9a48ebe21cc8844e 100644
--- a/src/crypto/crypto_context.cc
+++ b/src/crypto/crypto_context.cc
-@@ -63,7 +63,7 @@ inline X509_STORE* GetOrCreateRootCertStore() {
- // Caller responsible for BIO_free_all-ing the returned object.
- BIOPointer LoadBIO(Environment* env, Local<Value> v) {
- if (v->IsString() || v->IsArrayBufferView()) {
-- BIOPointer bio(BIO_new(BIO_s_secmem()));
-+ BIOPointer bio(BIO_new(BIO_s_mem()));
- if (!bio) return nullptr;
- ByteSource bsrc = ByteSource::FromStringOrBuffer(env, v);
- if (bsrc.size() > INT_MAX) return nullptr;
-@@ -882,10 +882,12 @@ void SecureContext::SetDHParam(const FunctionCallbackInfo<Value>& args) {
+@@ -94,7 +94,7 @@ int SSL_CTX_use_certificate_chain(SSL_CTX* ctx,
+ // the CA certificates.
+ SSL_CTX_clear_extra_chain_certs(ctx);
+
+- for (int i = 0; i < sk_X509_num(extra_certs); i++) {
++ for (size_t i = 0; i < sk_X509_num(extra_certs); i++) {
+ X509* ca = sk_X509_value(extra_certs, i);
+
+ // NOTE: Increments reference count on `ca`
+@@ -920,11 +920,12 @@ void SecureContext::SetDHParam(const FunctionCallbackInfo<Value>& args) {
// If the user specified "auto" for dhparams, the JavaScript layer will pass
// true to this function instead of the original string. Any other string
// value will be interpreted as custom DH parameters below.
@@ -130,66 +262,106 @@ index cef0c877c67643d47da787eddb95ed5a410a941b..1b8af49a48f1a34a92d4f0b502d435f3
CHECK(SSL_CTX_set_dh_auto(sc->ctx_.get(), true));
return;
}
+-
+#endif
-
DHPointer dh;
{
+ BIOPointer bio(LoadBIO(env, args[0]));
+@@ -1150,7 +1151,7 @@ void SecureContext::LoadPKCS12(const FunctionCallbackInfo<Value>& args) {
+ }
+
+ // Add CA certs too
+- for (int i = 0; i < sk_X509_num(extra_certs.get()); i++) {
++ for (size_t i = 0; i < sk_X509_num(extra_certs.get()); i++) {
+ X509* ca = sk_X509_value(extra_certs.get(), i);
+
+ X509_STORE_add_cert(sc->GetCertStoreOwnedByThisSecureContext(), ca);
diff --git a/src/crypto/crypto_dh.cc b/src/crypto/crypto_dh.cc
-index dac37f52b9687cadfa2d02152241e9a6e4c16ddf..d47cfa4ad8707ed7f0a42e7fe176fec25be64305 100644
+index e5664dfa2bc7e11922fa965f28acdf21470d1147..33ffbbb85d05f5356183e3aa1ca23707c5629b5d 100644
--- a/src/crypto/crypto_dh.cc
+++ b/src/crypto/crypto_dh.cc
-@@ -154,13 +154,11 @@ bool DiffieHellman::Init(BignumPointer&& bn_p, int g) {
- bool DiffieHellman::Init(const char* p, int p_len, int g) {
- dh_.reset(DH_new());
- if (p_len <= 0) {
-- ERR_put_error(ERR_LIB_BN, BN_F_BN_GENERATE_PRIME_EX,
-- BN_R_BITS_TOO_SMALL, __FILE__, __LINE__);
-+ OPENSSL_PUT_ERROR(BN, BN_R_BITS_TOO_SMALL);
- return false;
- }
- if (g <= 1) {
-- ERR_put_error(ERR_LIB_DH, DH_F_DH_BUILTIN_GENPARAMS,
-- DH_R_BAD_GENERATOR, __FILE__, __LINE__);
-+ OPENSSL_PUT_ERROR(DH, DH_R_BAD_GENERATOR);
- return false;
- }
- BignumPointer bn_p(
-@@ -176,20 +174,17 @@ bool DiffieHellman::Init(const char* p, int p_len, int g) {
- bool DiffieHellman::Init(const char* p, int p_len, const char* g, int g_len) {
- dh_.reset(DH_new());
- if (p_len <= 0) {
-- ERR_put_error(ERR_LIB_BN, BN_F_BN_GENERATE_PRIME_EX,
-- BN_R_BITS_TOO_SMALL, __FILE__, __LINE__);
-+ OPENSSL_PUT_ERROR(BN, BN_R_BITS_TOO_SMALL);
- return false;
- }
- if (g_len <= 0) {
-- ERR_put_error(ERR_LIB_DH, DH_F_DH_BUILTIN_GENPARAMS,
-- DH_R_BAD_GENERATOR, __FILE__, __LINE__);
-+ OPENSSL_PUT_ERROR(DH, DH_R_BAD_GENERATOR);
- return false;
- }
- BignumPointer bn_g(
- BN_bin2bn(reinterpret_cast<const unsigned char*>(g), g_len, nullptr));
- if (BN_is_zero(bn_g.get()) || BN_is_one(bn_g.get())) {
-- ERR_put_error(ERR_LIB_DH, DH_F_DH_BUILTIN_GENPARAMS,
-- DH_R_BAD_GENERATOR, __FILE__, __LINE__);
-+ OPENSSL_PUT_ERROR(DH, DH_R_BAD_GENERATOR);
- return false;
+@@ -7,7 +7,9 @@
+ #include "memory_tracker-inl.h"
+ #include "ncrypto.h"
+ #include "node_errors.h"
++#ifndef OPENSSL_IS_BORINGSSL
+ #include "openssl/bnerr.h"
++#endif
+ #include "openssl/dh.h"
+ #include "threadpoolwork-inl.h"
+ #include "v8.h"
+@@ -86,11 +88,7 @@ void New(const FunctionCallbackInfo<Value>& args) {
+ if (args[0]->IsInt32()) {
+ int32_t bits = args[0].As<Int32>()->Value();
+ if (bits < 2) {
+-#if OPENSSL_VERSION_MAJOR >= 3
+- ERR_put_error(ERR_LIB_DH, 0, DH_R_MODULUS_TOO_SMALL, __FILE__, __LINE__);
+-#else
+- ERR_put_error(ERR_LIB_BN, 0, BN_R_BITS_TOO_SMALL, __FILE__, __LINE__);
+-#endif
++ OPENSSL_PUT_ERROR(BN, BN_R_BITS_TOO_SMALL);
+ return ThrowCryptoError(env, ERR_get_error(), "Invalid prime length");
+ }
+
+@@ -103,7 +101,7 @@ void New(const FunctionCallbackInfo<Value>& args) {
+ }
+ int32_t generator = args[1].As<Int32>()->Value();
+ if (generator < 2) {
+- ERR_put_error(ERR_LIB_DH, 0, DH_R_BAD_GENERATOR, __FILE__, __LINE__);
++ OPENSSL_PUT_ERROR(DH, DH_R_BAD_GENERATOR);
+ return ThrowCryptoError(env, ERR_get_error(), "Invalid generator");
+ }
+
+@@ -132,12 +130,12 @@ void New(const FunctionCallbackInfo<Value>& args) {
+ if (args[1]->IsInt32()) {
+ int32_t generator = args[1].As<Int32>()->Value();
+ if (generator < 2) {
+- ERR_put_error(ERR_LIB_DH, 0, DH_R_BAD_GENERATOR, __FILE__, __LINE__);
++ OPENSSL_PUT_ERROR(DH, DH_R_BAD_GENERATOR);
+ return ThrowCryptoError(env, ERR_get_error(), "Invalid generator");
+ }
+ bn_g = BignumPointer::New();
+ if (!bn_g.setWord(generator)) {
+- ERR_put_error(ERR_LIB_DH, 0, DH_R_BAD_GENERATOR, __FILE__, __LINE__);
++ OPENSSL_PUT_ERROR(DH, DH_R_BAD_GENERATOR);
+ return ThrowCryptoError(env, ERR_get_error(), "Invalid generator");
+ }
+ } else {
+@@ -146,11 +144,11 @@ void New(const FunctionCallbackInfo<Value>& args) {
+ return THROW_ERR_OUT_OF_RANGE(env, "generator is too big");
+ bn_g = BignumPointer(reinterpret_cast<uint8_t*>(arg1.data()), arg1.size());
+ if (!bn_g) {
+- ERR_put_error(ERR_LIB_DH, 0, DH_R_BAD_GENERATOR, __FILE__, __LINE__);
++ OPENSSL_PUT_ERROR(DH, DH_R_BAD_GENERATOR);
+ return ThrowCryptoError(env, ERR_get_error(), "Invalid generator");
+ }
+ if (bn_g.getWord() < 2) {
+- ERR_put_error(ERR_LIB_DH, 0, DH_R_BAD_GENERATOR, __FILE__, __LINE__);
++ OPENSSL_PUT_ERROR(DH, DH_R_BAD_GENERATOR);
+ return ThrowCryptoError(env, ERR_get_error(), "Invalid generator");
+ }
}
- BignumPointer bn_p(
-@@ -219,8 +214,10 @@ typedef BignumPointer (*StandardizedGroupInstantiator)();
- inline StandardizedGroupInstantiator FindDiffieHellmanGroup(const char* name) {
- #define V(n, p) \
- if (StringEqualNoCase(name, n)) return InstantiateStandardizedGroup<p>
+@@ -258,15 +256,17 @@ void ComputeSecret(const FunctionCallbackInfo<Value>& args) {
+ BignumPointer key(key_buf.data(), key_buf.size());
+
+ switch (dh.checkPublicKey(key)) {
+- case DHPointer::CheckPublicKeyResult::INVALID:
+- // Fall-through
+ case DHPointer::CheckPublicKeyResult::CHECK_FAILED:
+ return THROW_ERR_CRYPTO_INVALID_KEYTYPE(env,
+ "Unspecified validation error");
+#ifndef OPENSSL_IS_BORINGSSL
- V("modp1", BN_get_rfc2409_prime_768);
- V("modp2", BN_get_rfc2409_prime_1024);
+ case DHPointer::CheckPublicKeyResult::TOO_SMALL:
+ return THROW_ERR_CRYPTO_INVALID_KEYLEN(env, "Supplied key is too small");
+ case DHPointer::CheckPublicKeyResult::TOO_LARGE:
+ return THROW_ERR_CRYPTO_INVALID_KEYLEN(env, "Supplied key is too large");
+#endif
- V("modp5", BN_get_rfc3526_prime_1536);
- V("modp14", BN_get_rfc3526_prime_2048);
- V("modp15", BN_get_rfc3526_prime_3072);
-@@ -565,9 +562,11 @@ EVPKeyCtxPointer DhKeyGenTraits::Setup(DhKeyPairGenConfig* params) {
++ case DHPointer::CheckPublicKeyResult::INVALID:
++ return THROW_ERR_CRYPTO_INVALID_KEYTYPE(env, "Supplied key is invalid");
+ case DHPointer::CheckPublicKeyResult::NONE:
+ break;
+ }
+@@ -398,9 +398,11 @@ EVPKeyCtxPointer DhKeyGenTraits::Setup(DhKeyPairGenConfig* params) {
key_params = EVPKeyPointer(EVP_PKEY_new());
CHECK(key_params);
CHECK_EQ(EVP_PKEY_assign_DH(key_params.get(), dh.release()), 1);
@@ -202,7 +374,7 @@ index dac37f52b9687cadfa2d02152241e9a6e4c16ddf..d47cfa4ad8707ed7f0a42e7fe176fec2
if (!param_ctx ||
EVP_PKEY_paramgen_init(param_ctx.get()) <= 0 ||
EVP_PKEY_CTX_set_dh_paramgen_prime_len(
-@@ -581,6 +580,9 @@ EVPKeyCtxPointer DhKeyGenTraits::Setup(DhKeyPairGenConfig* params) {
+@@ -414,6 +416,9 @@ EVPKeyCtxPointer DhKeyGenTraits::Setup(DhKeyPairGenConfig* params) {
}
key_params = EVPKeyPointer(raw_params);
@@ -213,7 +385,7 @@ index dac37f52b9687cadfa2d02152241e9a6e4c16ddf..d47cfa4ad8707ed7f0a42e7fe176fec2
UNREACHABLE();
}
diff --git a/src/crypto/crypto_dsa.cc b/src/crypto/crypto_dsa.cc
-index 3fa4a415dc911a13afd90dfb31c1ed4ad0fd268f..fa48dffc31342c44a1c1207b9d4c3dc72ed93b60 100644
+index 5d081863cf2dcdcf8c2d09db6060eeb5e78c452f..67523ec1c406e345945e1dde663c784c43a1c624 100644
--- a/src/crypto/crypto_dsa.cc
+++ b/src/crypto/crypto_dsa.cc
@@ -40,7 +40,7 @@ namespace crypto {
@@ -237,18 +409,18 @@ index 3fa4a415dc911a13afd90dfb31c1ed4ad0fd268f..fa48dffc31342c44a1c1207b9d4c3dc7
return EVPKeyCtxPointer();
diff --git a/src/crypto/crypto_keys.cc b/src/crypto/crypto_keys.cc
-index 35474c31bfc2e3692b7ca10e4ed7026b9c275dfb..43c42c14f75018d4705f218fe4ed7e5dacb46bb8 100644
+index 8488fc57faaf722174032c5a927d150c76120d60..c51efc92d4818ee7701b4725585fb7e1d2d644ad 100644
--- a/src/crypto/crypto_keys.cc
+++ b/src/crypto/crypto_keys.cc
-@@ -1239,6 +1239,7 @@ void KeyObjectHandle::GetAsymmetricKeyType(
+@@ -1204,6 +1204,7 @@ void KeyObjectHandle::GetAsymmetricKeyType(
}
bool KeyObjectHandle::CheckEcKeyData() const {
+#ifndef OPENSSL_IS_BORINGSSL
MarkPopErrorOnReturn mark_pop_error_on_return;
- const ManagedEVPPKey& key = data_->GetAsymmetricKey();
-@@ -1257,6 +1258,9 @@ bool KeyObjectHandle::CheckEcKeyData() const {
+ const auto& key = data_.GetAsymmetricKey();
+@@ -1220,6 +1221,9 @@ bool KeyObjectHandle::CheckEcKeyData() const {
#else
return EVP_PKEY_public_check(ctx.get()) == 1;
#endif
@@ -259,43 +431,43 @@ index 35474c31bfc2e3692b7ca10e4ed7026b9c275dfb..43c42c14f75018d4705f218fe4ed7e5d
void KeyObjectHandle::CheckEcKeyData(const FunctionCallbackInfo<Value>& args) {
diff --git a/src/crypto/crypto_random.cc b/src/crypto/crypto_random.cc
-index 48154df7dc91ed7c0d65323199bc2f59dfc68135..6431e5c3062890975854780d15ecb84370b81770 100644
+index b59e394d9a7e2c19fdf1f2b0177753ff488da0fa..91218f49da5392c6f769495ee7f9275a47ce09b1 100644
--- a/src/crypto/crypto_random.cc
+++ b/src/crypto/crypto_random.cc
-@@ -140,7 +140,7 @@ Maybe<bool> RandomPrimeTraits::AdditionalConfig(
+@@ -134,7 +134,7 @@ Maybe<void> RandomPrimeTraits::AdditionalConfig(
params->bits = bits;
params->safe = safe;
-- params->prime.reset(BN_secure_new());
-+ params->prime.reset(BN_new());
+- params->prime = BignumPointer::NewSecure();
++ params->prime = BignumPointer::New();
if (!params->prime) {
THROW_ERR_CRYPTO_OPERATION_FAILED(env, "could not generate prime");
- return Nothing<bool>();
+ return Nothing<void>();
diff --git a/src/crypto/crypto_rsa.cc b/src/crypto/crypto_rsa.cc
-index 23b2b8c56dec8ac600b8f14b78d9e80b7fa3ed3b..e7a8fe4181542252d9142ea9460cacc5b4acd00d 100644
+index 02e8e24b4054afd4c3ca797c19a78927319a0d9e..d2a931a3f8f9490fe17ef8a82d0204ee2cca409d 100644
--- a/src/crypto/crypto_rsa.cc
+++ b/src/crypto/crypto_rsa.cc
-@@ -616,10 +616,11 @@ Maybe<bool> GetRsaKeyDetail(
+@@ -608,10 +608,11 @@ Maybe<void> GetRsaKeyDetail(Environment* env,
}
if (params->saltLength != nullptr) {
- if (ASN1_INTEGER_get_int64(&salt_length, params->saltLength) != 1) {
- ThrowCryptoError(env, ERR_get_error(), "ASN1_INTEGER_get_in64 error");
-- return Nothing<bool>();
+- return Nothing<void>();
- }
+ // TODO(codebytere): Upstream a shim to BoringSSL?
+ // if (ASN1_INTEGER_get_int64(&salt_length, params->saltLength) != 1) {
+ // ThrowCryptoError(env, ERR_get_error(), "ASN1_INTEGER_get_in64 error");
-+ // return Nothing<bool>();
++ // return Nothing<void>();
+ // }
}
if (target
diff --git a/src/crypto/crypto_util.cc b/src/crypto/crypto_util.cc
-index 990638ec3993bde40ad3dd40d373d816ebc66a6a..63d971e1fe6b861e29c12f04563701b01fdfb976 100644
+index 793c196f8ce538c66b20611d00e12392ff9e878b..ee81048caab4ccfe26ea9e677782c9c955d162a9 100644
--- a/src/crypto/crypto_util.cc
+++ b/src/crypto/crypto_util.cc
-@@ -518,24 +518,15 @@ Maybe<void> Decorate(Environment* env,
+@@ -495,24 +495,15 @@ Maybe<void> Decorate(Environment* env,
V(BIO) \
V(PKCS7) \
V(X509V3) \
@@ -321,7 +493,7 @@ index 990638ec3993bde40ad3dd40d373d816ebc66a6a..63d971e1fe6b861e29c12f04563701b0
V(USER) \
#define V(name) case ERR_LIB_##name: lib = #name "_"; break;
-@@ -716,7 +707,7 @@ void SecureBuffer(const FunctionCallbackInfo<Value>& args) {
+@@ -654,7 +645,7 @@ void SecureBuffer(const FunctionCallbackInfo<Value>& args) {
CHECK(args[0]->IsUint32());
Environment* env = Environment::GetCurrent(args);
uint32_t len = args[0].As<Uint32>()->Value();
@@ -330,7 +502,7 @@ index 990638ec3993bde40ad3dd40d373d816ebc66a6a..63d971e1fe6b861e29c12f04563701b0
if (data == nullptr) {
// There's no memory available for the allocation.
// Return nothing.
-@@ -727,7 +718,7 @@ void SecureBuffer(const FunctionCallbackInfo<Value>& args) {
+@@ -665,7 +656,7 @@ void SecureBuffer(const FunctionCallbackInfo<Value>& args) {
data,
len,
[](void* data, size_t len, void* deleter_data) {
@@ -339,7 +511,7 @@ index 990638ec3993bde40ad3dd40d373d816ebc66a6a..63d971e1fe6b861e29c12f04563701b0
},
data);
Local<ArrayBuffer> buffer = ArrayBuffer::New(env->isolate(), store);
-@@ -735,10 +726,12 @@ void SecureBuffer(const FunctionCallbackInfo<Value>& args) {
+@@ -673,10 +664,12 @@ void SecureBuffer(const FunctionCallbackInfo<Value>& args) {
}
void SecureHeapUsed(const FunctionCallbackInfo<Value>& args) {
@@ -353,10 +525,10 @@ index 990638ec3993bde40ad3dd40d373d816ebc66a6a..63d971e1fe6b861e29c12f04563701b0
} // namespace
diff --git a/src/env.h b/src/env.h
-index 30561ab7a24c734be71ed29d963c11e2ea2c2b22..7cb77fb4f35a60fbda5b868798321ac8b6340bfa 100644
+index fc8dbd615255851cad90e1d8ffe225f5e0c6a718..49ca9c0042ccf22ad1fffa54f05fd443cbc681ba 100644
--- a/src/env.h
+++ b/src/env.h
-@@ -49,7 +49,7 @@
+@@ -50,7 +50,7 @@
#include "uv.h"
#include "v8.h"
@@ -365,7 +537,7 @@ index 30561ab7a24c734be71ed29d963c11e2ea2c2b22..7cb77fb4f35a60fbda5b868798321ac8
#include <openssl/evp.h>
#endif
-@@ -1065,7 +1065,7 @@ class Environment : public MemoryRetainer {
+@@ -1073,7 +1073,7 @@ class Environment final : public MemoryRetainer {
kExitInfoFieldCount
};
@@ -375,7 +547,7 @@ index 30561ab7a24c734be71ed29d963c11e2ea2c2b22..7cb77fb4f35a60fbda5b868798321ac8
// We declare another alias here to avoid having to include crypto_util.h
using EVPMDPointer = DeleteFnPtr<EVP_MD, EVP_MD_free>;
diff --git a/src/node_metadata.h b/src/node_metadata.h
-index cf051585e779e2b03bd7b95fe5008b89cc7f8162..9de49c6828468fdf846dcd4ad445390f14446099 100644
+index c59e65ad1fe3fac23f1fc25ca77e6133d1ccaccd..f2f07434e076e2977755ef7dac7d489aedb760b0 100644
--- a/src/node_metadata.h
+++ b/src/node_metadata.h
@@ -6,7 +6,7 @@
@@ -388,7 +560,7 @@ index cf051585e779e2b03bd7b95fe5008b89cc7f8162..9de49c6828468fdf846dcd4ad445390f
#if NODE_OPENSSL_HAS_QUIC
#include <openssl/quic.h>
diff --git a/src/node_options.cc b/src/node_options.cc
-index dba59c5560c22899bd108789360f21fd85dd41bf..818baf611fcab7838a339f3ea137467653e270d0 100644
+index cfc599ec9a6197231c3469d318f02c620cdb03a8..29630fcccc3bd9d24ad6aec64bef2fedfc3c4031 100644
--- a/src/node_options.cc
+++ b/src/node_options.cc
@@ -6,7 +6,7 @@
@@ -401,7 +573,7 @@ index dba59c5560c22899bd108789360f21fd85dd41bf..818baf611fcab7838a339f3ea1374676
#endif
diff --git a/src/node_options.h b/src/node_options.h
-index 10c220f66122336215f25b9674acfdfe6df82a8e..e8b2243d24fe95ff31254071133fb646e186c07e 100644
+index 9e656a2815045aa5da7eb267708c03058be9f362..600e0850f01e01024414d42b25605f256200540a 100644
--- a/src/node_options.h
+++ b/src/node_options.h
@@ -11,7 +11,7 @@
@@ -413,3 +585,37 @@ index 10c220f66122336215f25b9674acfdfe6df82a8e..e8b2243d24fe95ff31254071133fb646
#include "openssl/opensslv.h"
#endif
+diff --git a/unofficial.gni b/unofficial.gni
+index de6ff5548ca5282199b7d85c11941c1fa351a9d9..3d8b7957e791ce2fa2a8d0937a87b6010087803d 100644
+--- a/unofficial.gni
++++ b/unofficial.gni
+@@ -145,7 +145,6 @@ template("node_gn_build") {
+ ]
+ deps = [
+ ":run_node_js2c",
+- "deps/brotli",
+ "deps/cares",
+ "deps/histogram",
+ "deps/llhttp",
+@@ -156,6 +155,8 @@ template("node_gn_build") {
+ "deps/sqlite",
+ "deps/uvwasi",
+ "//third_party/zlib",
++ "//third_party/brotli:dec",
++ "//third_party/brotli:enc",
+ "$node_v8_path:v8_libplatform",
+ ]
+
+@@ -182,10 +183,8 @@ template("node_gn_build") {
+ deps += [ "//third_party/icu" ]
+ }
+ if (node_use_openssl) {
+- deps += [
+- "deps/ncrypto",
+- "//third_party/boringssl"
+- ]
++ deps += [ "deps/ncrypto" ]
++ public_deps += [ "$node_crypto_path" ]
+ sources += gypi_values.node_crypto_sources
+ }
+ if (node_enable_inspector) {
diff --git a/patches/node/fix_lazyload_fs_in_esm_loaders_to_apply_asar_patches.patch b/patches/node/fix_lazyload_fs_in_esm_loaders_to_apply_asar_patches.patch
index 787043e5cc..bc8e7cea5a 100644
--- a/patches/node/fix_lazyload_fs_in_esm_loaders_to_apply_asar_patches.patch
+++ b/patches/node/fix_lazyload_fs_in_esm_loaders_to_apply_asar_patches.patch
@@ -6,39 +6,39 @@ Subject: fix: lazyload fs in esm loaders to apply asar patches
Changes { foo } from fs to just "fs.foo" so that our patching of fs is applied to esm loaders
diff --git a/lib/internal/modules/esm/load.js b/lib/internal/modules/esm/load.js
-index ac24cf305bd5995ad13b37ee36f9e1fe3589c5d7..22248b753c14960122f1d6b9bfe6b89fdb8d2010 100644
+index 605e812d515fc467001e4ab88fc15b4af3fd4aa2..463e76cb1abc0c2fdddba4db2ca2e00f7c591e12 100644
--- a/lib/internal/modules/esm/load.js
+++ b/lib/internal/modules/esm/load.js
-@@ -10,7 +10,7 @@ const { kEmptyObject } = require('internal/util');
+@@ -8,7 +8,7 @@ const { kEmptyObject } = require('internal/util');
const { defaultGetFormat } = require('internal/modules/esm/get_format');
const { validateAttributes, emitImportAssertionWarning } = require('internal/modules/esm/assert');
const { getOptionValue } = require('internal/options');
-const { readFileSync } = require('fs');
+const fs = require('fs');
- // Do not eagerly grab .manifest, it may be in TDZ
- const policy = getOptionValue('--experimental-policy') ?
-@@ -42,8 +42,7 @@ async function getSource(url, context) {
- let responseURL = href;
+ const defaultType =
+ getOptionValue('--experimental-default-type');
+@@ -40,8 +40,7 @@ async function getSource(url, context) {
+ const responseURL = href;
let source;
if (protocol === 'file:') {
- const { readFile: readFileAsync } = require('internal/fs/promises').exports;
- source = await readFileAsync(url);
+ source = await fs.promises.readFile(url);
} else if (protocol === 'data:') {
- const match = RegExpPrototypeExec(DATA_URL_PATTERN, url.pathname);
- if (!match) {
-@@ -82,7 +81,7 @@ function getSourceSync(url, context) {
+ const result = dataURLProcessor(url);
+ if (result === 'failure') {
+@@ -65,7 +64,7 @@ function getSourceSync(url, context) {
const responseURL = href;
let source;
if (protocol === 'file:') {
- source = readFileSync(url);
+ source = fs.readFileSync(url);
} else if (protocol === 'data:') {
- const match = RegExpPrototypeExec(DATA_URL_PATTERN, url.pathname);
- if (!match) {
+ const result = dataURLProcessor(url);
+ if (result === 'failure') {
diff --git a/lib/internal/modules/esm/resolve.js b/lib/internal/modules/esm/resolve.js
-index 52cdb7d5e14a18ed7b1b65e429729cf47dce3f98..69f73f829706deddc4f328b78af9d58434af647d 100644
+index f05c6f99c0037193c5802024be46a967d6cf47a0..f3dad958b2ec275992554477b9344214c8c1e2c8 100644
--- a/lib/internal/modules/esm/resolve.js
+++ b/lib/internal/modules/esm/resolve.js
@@ -24,7 +24,7 @@ const {
@@ -49,17 +49,8 @@ index 52cdb7d5e14a18ed7b1b65e429729cf47dce3f98..69f73f829706deddc4f328b78af9d584
+const fs = require('fs');
const { getOptionValue } = require('internal/options');
// Do not eagerly grab .manifest, it may be in TDZ
- const policy = getOptionValue('--experimental-policy') ?
-@@ -251,7 +251,7 @@ function finalizeResolution(resolved, base, preserveSymlinks) {
- throw err;
- }
-
-- const stats = internalModuleStat(toNamespacedPath(StringPrototypeEndsWith(path, '/') ?
-+ const stats = internalFsBinding.internalModuleStat(toNamespacedPath(StringPrototypeEndsWith(path, '/') ?
- StringPrototypeSlice(path, -1) : path));
-
- // Check for stats.isDirectory()
-@@ -267,7 +267,7 @@ function finalizeResolution(resolved, base, preserveSymlinks) {
+ const { sep, posix: { relative: relativePosixPath }, resolve } = require('path');
+@@ -259,7 +259,7 @@ function finalizeResolution(resolved, base, preserveSymlinks) {
}
if (!preserveSymlinks) {
@@ -68,20 +59,11 @@ index 52cdb7d5e14a18ed7b1b65e429729cf47dce3f98..69f73f829706deddc4f328b78af9d584
[internalFS.realpathCacheKey]: realpathCache,
});
const { search, hash } = resolved;
-@@ -826,7 +826,7 @@ function packageResolve(specifier, base, conditions) {
- let packageJSONPath = fileURLToPath(packageJSONUrl);
- let lastPath;
- do {
-- const stat = internalModuleStat(toNamespacedPath(StringPrototypeSlice(packageJSONPath, 0,
-+ const stat = internalFsBinding.internalModuleStat(toNamespacedPath(StringPrototypeSlice(packageJSONPath, 0,
- packageJSONPath.length - 13)));
- // Check for !stat.isDirectory()
- if (stat !== 1) {
diff --git a/lib/internal/modules/esm/translators.js b/lib/internal/modules/esm/translators.js
-index 89ca269294ee1afa7f5aeb0ac6b8958f7a8b49d0..f3dfc69cd2cdec50bc3b3f7cb2d63349812d87dd 100644
+index d182eedf5e96039e0029d36e51f40b75c6fb2a39..06b31af80ebbfbf35ec787a94f345775eb512ebf 100644
--- a/lib/internal/modules/esm/translators.js
+++ b/lib/internal/modules/esm/translators.js
-@@ -36,7 +36,7 @@ const {
+@@ -34,7 +34,7 @@ const {
const { BuiltinModule } = require('internal/bootstrap/realm');
const assert = require('internal/assert');
@@ -90,7 +72,7 @@ index 89ca269294ee1afa7f5aeb0ac6b8958f7a8b49d0..f3dfc69cd2cdec50bc3b3f7cb2d63349
const { dirname, extname, isAbsolute } = require('path');
const {
loadBuiltinModule,
-@@ -356,7 +356,7 @@ translators.set('commonjs', async function commonjsStrategy(url, source,
+@@ -335,7 +335,7 @@ translators.set('commonjs', async function commonjsStrategy(url, source,
try {
// We still need to read the FS to detect the exports.
@@ -99,7 +81,7 @@ index 89ca269294ee1afa7f5aeb0ac6b8958f7a8b49d0..f3dfc69cd2cdec50bc3b3f7cb2d63349
} catch {
// Continue regardless of error.
}
-@@ -424,7 +424,7 @@ function cjsPreparseModuleExports(filename, source) {
+@@ -403,7 +403,7 @@ function cjsPreparseModuleExports(filename, source) {
isAbsolute(resolved)) {
// TODO: this should be calling the `load` hook chain to get the source
// (and fallback to reading the FS only if the source is nullish).
diff --git a/patches/node/fix_remove_deprecated_errno_constants.patch b/patches/node/fix_remove_deprecated_errno_constants.patch
index cf9b4ec08c..e86a1fada5 100644
--- a/patches/node/fix_remove_deprecated_errno_constants.patch
+++ b/patches/node/fix_remove_deprecated_errno_constants.patch
@@ -10,7 +10,7 @@ This change removes the usage of these constants to fix a compilation failure du
See: https://github.com/llvm/llvm-project/pull/80542
diff --git a/deps/uv/include/uv.h b/deps/uv/include/uv.h
-index 3375600023e39ddacf62cc17deb4f206db942084..cc106422dd36aa0564e74dd8a16eec496433d3bd 100644
+index 7f48b7daa87d1a5b14bc6f641b60f21263fa5ec3..0be470c9139a6da19414295a59f1a237cc3a50d7 100644
--- a/deps/uv/include/uv.h
+++ b/deps/uv/include/uv.h
@@ -155,7 +155,6 @@ struct uv__queue {
@@ -86,10 +86,10 @@ index 149c7c107322919dfeea1dfe89dc223f78b0e979..e4e8dac6b8b5924a7eae83935031e091
NODE_DEFINE_CONSTANT(target, ETIMEDOUT);
#endif
diff --git a/src/node_errors.cc b/src/node_errors.cc
-index 69e474257b0427f894375fbc8a2c031f1b8e0c55..f0e968c0dfa8963404c3b87827b8d11a139051cc 100644
+index 65f95c3157add2afca26a133183b65ccba6e9924..81091d364d32094dc91c7abb0c5fe9963d100a8b 100644
--- a/src/node_errors.cc
+++ b/src/node_errors.cc
-@@ -855,10 +855,6 @@ const char* errno_string(int errorno) {
+@@ -857,10 +857,6 @@ const char* errno_string(int errorno) {
ERRNO_CASE(ENOBUFS);
#endif
@@ -100,7 +100,7 @@ index 69e474257b0427f894375fbc8a2c031f1b8e0c55..f0e968c0dfa8963404c3b87827b8d11a
#ifdef ENODEV
ERRNO_CASE(ENODEV);
#endif
-@@ -897,14 +893,6 @@ const char* errno_string(int errorno) {
+@@ -899,14 +895,6 @@ const char* errno_string(int errorno) {
ERRNO_CASE(ENOSPC);
#endif
@@ -115,7 +115,7 @@ index 69e474257b0427f894375fbc8a2c031f1b8e0c55..f0e968c0dfa8963404c3b87827b8d11a
#ifdef ENOSYS
ERRNO_CASE(ENOSYS);
#endif
-@@ -987,10 +975,6 @@ const char* errno_string(int errorno) {
+@@ -989,10 +977,6 @@ const char* errno_string(int errorno) {
ERRNO_CASE(ESTALE);
#endif
diff --git a/patches/node/fix_remove_harmony-import-assertions_from_node_cc.patch b/patches/node/fix_remove_harmony-import-assertions_from_node_cc.patch
new file mode 100644
index 0000000000..0e7268f6cf
--- /dev/null
+++ b/patches/node/fix_remove_harmony-import-assertions_from_node_cc.patch
@@ -0,0 +1,25 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: Shelley Vohr <[email protected]>
+Date: Fri, 18 Oct 2024 17:01:06 +0200
+Subject: fix: remove harmony-import-assertions from node.cc
+
+harmony-import-assertions has been removed from V8 as of
+https://chromium-review.googlesource.com/c/v8/v8/+/5507047,
+so we should remove it from node.cc as well.
+
+This patch can be removed when we upgrade to a V8 version that
+contains the above CL.
+
+diff --git a/src/node.cc b/src/node.cc
+index ccc1085a84b214d241687fa9ebd45b55b2cc60d8..1df8e1f00a0e2ffa63bfd4369240b837ab6a9c50 100644
+--- a/src/node.cc
++++ b/src/node.cc
+@@ -804,7 +804,7 @@ static ExitCode ProcessGlobalArgsInternal(std::vector<std::string>* args,
+ }
+ // TODO(nicolo-ribaudo): remove this once V8 doesn't enable it by default
+ // anymore.
+- v8_args.emplace_back("--no-harmony-import-assertions");
++ // v8_args.emplace_back("--no-harmony-import-assertions");
+
+ auto env_opts = per_process::cli_options->per_isolate->per_env;
+ if (std::find(v8_args.begin(), v8_args.end(),
diff --git a/patches/node/fix_revert_src_lb_reducing_c_calls_of_esm_legacy_main_resolve.patch b/patches/node/fix_revert_src_lb_reducing_c_calls_of_esm_legacy_main_resolve.patch
index 831e237f29..15039649de 100644
--- a/patches/node/fix_revert_src_lb_reducing_c_calls_of_esm_legacy_main_resolve.patch
+++ b/patches/node/fix_revert_src_lb_reducing_c_calls_of_esm_legacy_main_resolve.patch
@@ -15,31 +15,27 @@ to recognize asar files.
This reverts commit 9cf2e1f55b8446a7cde23699d00a3be73aa0c8f1.
diff --git a/lib/internal/modules/esm/resolve.js b/lib/internal/modules/esm/resolve.js
-index 69f73f829706deddc4f328b78af9d58434af647d..1d53a2a47423150e822bb917b2725d3a6a794814 100644
+index f3dad958b2ec275992554477b9344214c8c1e2c8..a086217046fd5ed7cfb09cfd2ed62f3987eb1f31 100644
--- a/lib/internal/modules/esm/resolve.js
+++ b/lib/internal/modules/esm/resolve.js
-@@ -36,10 +36,9 @@ const preserveSymlinksMain = getOptionValue('--preserve-symlinks-main');
- const experimentalNetworkImports =
- getOptionValue('--experimental-network-imports');
+@@ -27,14 +27,13 @@ const { BuiltinModule } = require('internal/bootstrap/realm');
+ const fs = require('fs');
+ const { getOptionValue } = require('internal/options');
+ // Do not eagerly grab .manifest, it may be in TDZ
+-const { sep, posix: { relative: relativePosixPath }, resolve } = require('path');
++const { sep, posix: { relative: relativePosixPath }, toNamespacedPath, resolve } = require('path');
+ const preserveSymlinks = getOptionValue('--preserve-symlinks');
+ const preserveSymlinksMain = getOptionValue('--preserve-symlinks-main');
const inputTypeFlag = getOptionValue('--input-type');
--const { URL, pathToFileURL, fileURLToPath, isURL } = require('internal/url');
-+const { URL, pathToFileURL, fileURLToPath, isURL, toPathIfFileURL } = require('internal/url');
+-const { URL, pathToFileURL, fileURLToPath, isURL, URLParse } = require('internal/url');
++const { URL, pathToFileURL, fileURLToPath, isURL, URLParse, toPathIfFileURL } = require('internal/url');
const { getCWDURL, setOwnProperty } = require('internal/util');
const { canParse: URLCanParse } = internalBinding('url');
-const { legacyMainResolve: FSLegacyMainResolve } = internalBinding('fs');
const {
ERR_INPUT_TYPE_NOT_ALLOWED,
ERR_INVALID_ARG_TYPE,
-@@ -59,7 +58,7 @@ const { Module: CJSModule } = require('internal/modules/cjs/loader');
- const { getPackageScopeConfig } = require('internal/modules/esm/package_config');
- const { getConditionsSet } = require('internal/modules/esm/utils');
- const packageJsonReader = require('internal/modules/package_json_reader');
--const { internalModuleStat } = internalBinding('fs');
-+const internalFsBinding = internalBinding('fs');
-
- /**
- * @typedef {import('internal/modules/esm/package_config.js').PackageConfig} PackageConfig
-@@ -162,34 +161,13 @@ function emitLegacyIndexDeprecation(url, packageJSONUrl, base, main) {
+@@ -154,34 +153,13 @@ function emitLegacyIndexDeprecation(url, packageJSONUrl, base, main) {
const realpathCache = new SafeMap();
@@ -81,7 +77,7 @@ index 69f73f829706deddc4f328b78af9d58434af647d..1d53a2a47423150e822bb917b2725d3a
/**
* Legacy CommonJS main resolution:
-@@ -204,22 +182,44 @@ const legacyMainResolveExtensionsIndexes = {
+@@ -196,22 +174,44 @@ const legacyMainResolveExtensionsIndexes = {
* @returns {URL}
*/
function legacyMainResolve(packageJSONUrl, packageConfig, base) {
@@ -142,10 +138,10 @@ index 69f73f829706deddc4f328b78af9d58434af647d..1d53a2a47423150e822bb917b2725d3a
const encodedSepRegEx = /%2F|%5C/i;
diff --git a/src/node_file.cc b/src/node_file.cc
-index 73ad5a1a2c092d7f8dac84585fb9b13e76e84e13..039f693de14bec248f93262ad70f2736c24827e3 100644
+index 0bb70eb0fcd42ddf4d5e585065cf1ad8e74faab3..b565beae625d970ba92ab667a145d8897d4e8a6e 100644
--- a/src/node_file.cc
+++ b/src/node_file.cc
-@@ -19,14 +19,11 @@
+@@ -19,14 +19,12 @@
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
#include "node_file.h" // NOLINT(build/include_inline)
@@ -153,14 +149,14 @@ index 73ad5a1a2c092d7f8dac84585fb9b13e76e84e13..039f693de14bec248f93262ad70f2736
#include "aliased_buffer-inl.h"
#include "memory_tracker-inl.h"
#include "node_buffer.h"
--#include "node_errors.h"
+ #include "node_errors.h"
#include "node_external_reference.h"
#include "node_file-inl.h"
-#include "node_metadata.h"
#include "node_process-inl.h"
#include "node_stat_watcher.h"
#include "node_url.h"
-@@ -3127,135 +3124,6 @@ constexpr std::array<std::string_view, 10> legacy_main_extensions = {
+@@ -3208,146 +3206,6 @@ constexpr std::array<std::string_view, 10> legacy_main_extensions = {
} // namespace
@@ -202,14 +198,20 @@ index 73ad5a1a2c092d7f8dac84585fb9b13e76e84e13..039f693de14bec248f93262ad70f2736
- return;
- }
-
-- node::url::FromNamespacedPath(&initial_file_path.value());
+- FromNamespacedPath(&initial_file_path.value());
-
- package_initial_file = *initial_file_path;
-
- for (int i = 0; i < legacy_main_extensions_with_main_end; i++) {
- file_path = *initial_file_path + std::string(legacy_main_extensions[i]);
--
-- switch (FilePathIsFile(env, file_path)) {
+- // TODO(anonrig): Remove this when ToNamespacedPath supports std::string
+- Local<Value> local_file_path =
+- Buffer::Copy(env->isolate(), file_path.c_str(), file_path.size())
+- .ToLocalChecked();
+- BufferValue buff_file_path(isolate, local_file_path);
+- ToNamespacedPath(env, &buff_file_path);
+-
+- switch (FilePathIsFile(env, buff_file_path.ToString())) {
- case BindingData::FilePathIsFileReturnType::kIsFile:
- return args.GetReturnValue().Set(i);
- case BindingData::FilePathIsFileReturnType::kIsNotFile:
@@ -239,14 +241,20 @@ index 73ad5a1a2c092d7f8dac84585fb9b13e76e84e13..039f693de14bec248f93262ad70f2736
- return;
- }
-
-- node::url::FromNamespacedPath(&initial_file_path.value());
+- FromNamespacedPath(&initial_file_path.value());
-
- for (int i = legacy_main_extensions_with_main_end;
- i < legacy_main_extensions_package_fallback_end;
- i++) {
- file_path = *initial_file_path + std::string(legacy_main_extensions[i]);
--
-- switch (FilePathIsFile(env, file_path)) {
+- // TODO(anonrig): Remove this when ToNamespacedPath supports std::string
+- Local<Value> local_file_path =
+- Buffer::Copy(env->isolate(), file_path.c_str(), file_path.size())
+- .ToLocalChecked();
+- BufferValue buff_file_path(isolate, local_file_path);
+- ToNamespacedPath(env, &buff_file_path);
+-
+- switch (FilePathIsFile(env, buff_file_path.ToString())) {
- case BindingData::FilePathIsFileReturnType::kIsFile:
- return args.GetReturnValue().Set(i);
- case BindingData::FilePathIsFileReturnType::kIsNotFile:
@@ -292,11 +300,10 @@ index 73ad5a1a2c092d7f8dac84585fb9b13e76e84e13..039f693de14bec248f93262ad70f2736
- package_initial_file,
- *module_base);
-}
--
+
void BindingData::MemoryInfo(MemoryTracker* tracker) const {
tracker->TrackField("stats_field_array", stats_field_array);
- tracker->TrackField("stats_field_bigint_array", stats_field_bigint_array);
-@@ -3355,19 +3223,6 @@ InternalFieldInfoBase* BindingData::Serialize(int index) {
+@@ -3448,19 +3306,6 @@ InternalFieldInfoBase* BindingData::Serialize(int index) {
return info;
}
@@ -316,15 +323,15 @@ index 73ad5a1a2c092d7f8dac84585fb9b13e76e84e13..039f693de14bec248f93262ad70f2736
static void CreatePerIsolateProperties(IsolateData* isolate_data,
Local<ObjectTemplate> target) {
Isolate* isolate = isolate_data->isolate();
-@@ -3422,7 +3277,6 @@ static void CreatePerIsolateProperties(IsolateData* isolate_data,
- SetMethod(isolate, target, "mkdtemp", Mkdtemp);
+@@ -3520,7 +3365,6 @@ static void CreatePerIsolateProperties(IsolateData* isolate_data,
+ SetMethod(isolate, target, "cpSyncCheckPaths", CpSyncCheckPaths);
StatWatcher::CreatePerIsolateProperties(isolate_data, target);
- BindingData::CreatePerIsolateProperties(isolate_data, target);
target->Set(
FIXED_ONE_BYTE_STRING(isolate, "kFsStatsFieldsNumber"),
-@@ -3495,7 +3349,6 @@ BindingData* FSReqBase::binding_data() {
+@@ -3593,7 +3437,6 @@ BindingData* FSReqBase::binding_data() {
void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
registry->Register(Access);
StatWatcher::RegisterExternalReferences(registry);
@@ -333,7 +340,7 @@ index 73ad5a1a2c092d7f8dac84585fb9b13e76e84e13..039f693de14bec248f93262ad70f2736
registry->Register(GetFormatOfExtensionlessFile);
registry->Register(Close);
diff --git a/src/node_file.h b/src/node_file.h
-index 6f1b55284db0f4f8c70081b4834a074c717f3cc9..a969fff32bd156aa9393c1db9eec474eb7432cea 100644
+index bdad1ae25f4892cbbfd8cc30c4d8b4a6f600edbc..5a3c462853aa784d9ef61ff4f63010848c48b92c 100644
--- a/src/node_file.h
+++ b/src/node_file.h
@@ -86,13 +86,6 @@ class BindingData : public SnapshotableObject {
diff --git a/patches/node/fix_suppress_clang_-wdeprecated-declarations_in_libuv.patch b/patches/node/fix_suppress_clang_-wdeprecated-declarations_in_libuv.patch
index 391271a50f..0ff052ab11 100644
--- a/patches/node/fix_suppress_clang_-wdeprecated-declarations_in_libuv.patch
+++ b/patches/node/fix_suppress_clang_-wdeprecated-declarations_in_libuv.patch
@@ -6,10 +6,10 @@ Subject: fix: suppress clang -Wdeprecated-declarations in libuv
Should be upstreamed.
diff --git a/deps/uv/src/win/util.c b/deps/uv/src/win/util.c
-index f6ec79cd57b5010ed5fd6829d952bcdacc8b7671..5cda078a55f7825d135a107fa98e1aa3527dd147 100644
+index a96cb915930a30a49ba55fd7d15ea48f0b471f89..3c15f348bd3a9a42afcf0e4d0182d2d6f3d05cb1 100644
--- a/deps/uv/src/win/util.c
+++ b/deps/uv/src/win/util.c
-@@ -1685,10 +1685,17 @@ int uv_os_uname(uv_utsname_t* buffer) {
+@@ -1537,10 +1537,17 @@ int uv_os_uname(uv_utsname_t* buffer) {
#ifdef _MSC_VER
#pragma warning(suppress : 4996)
#endif
diff --git a/patches/node/pass_all_globals_through_require.patch b/patches/node/pass_all_globals_through_require.patch
index 596b997812..d9d6dc91df 100644
--- a/patches/node/pass_all_globals_through_require.patch
+++ b/patches/node/pass_all_globals_through_require.patch
@@ -6,10 +6,10 @@ Subject: Pass all globals through "require"
(cherry picked from commit 7d015419cb7a0ecfe6728431a4ed2056cd411d62)
diff --git a/lib/internal/modules/cjs/loader.js b/lib/internal/modules/cjs/loader.js
-index c284b39b1ac13eaea8776b7b4f457c084dce5fb8..c794751ecd4448119ce33d661e694f83b3323f03 100644
+index 451b7c2195e7ad3ab0bde95259e054dc431d7de9..d49941881e6cfd8647a6d44a57e0daaf1c874702 100644
--- a/lib/internal/modules/cjs/loader.js
+++ b/lib/internal/modules/cjs/loader.js
-@@ -185,6 +185,13 @@ const {
+@@ -182,6 +182,13 @@ const {
CHAR_FORWARD_SLASH,
} = require('internal/constants');
@@ -23,7 +23,7 @@ index c284b39b1ac13eaea8776b7b4f457c084dce5fb8..c794751ecd4448119ce33d661e694f83
const {
isProxy,
} = require('internal/util/types');
-@@ -1464,10 +1471,12 @@ Module.prototype._compile = function(content, filename, loadAsESM = false) {
+@@ -1541,10 +1548,12 @@ Module.prototype._compile = function(content, filename, format) {
this[kIsExecuting] = true;
if (inspectorWrapper) {
result = inspectorWrapper(compiledWrapper, thisValue, exports,
diff --git a/patches/node/refactor_allow_embedder_overriding_of_internal_fs_calls.patch b/patches/node/refactor_allow_embedder_overriding_of_internal_fs_calls.patch
index f36422f981..5e5b538818 100644
--- a/patches/node/refactor_allow_embedder_overriding_of_internal_fs_calls.patch
+++ b/patches/node/refactor_allow_embedder_overriding_of_internal_fs_calls.patch
@@ -7,7 +7,7 @@ We use this to allow node's 'fs' module to read from ASAR files as if they were
a real filesystem.
diff --git a/lib/internal/bootstrap/node.js b/lib/internal/bootstrap/node.js
-index 12262f40ce123440a9a0f974386cfbe8511f4459..f3c15b61d33bdae44de528e106fcc6f930f1c388 100644
+index f7a62364b6107ab0bad33ea2f745703c746991dc..bab2aaf3db66452216035db594dc3ebdc3606c8b 100644
--- a/lib/internal/bootstrap/node.js
+++ b/lib/internal/bootstrap/node.js
@@ -134,6 +134,10 @@ process.domain = null;
@@ -21,47 +21,3 @@ index 12262f40ce123440a9a0f974386cfbe8511f4459..f3c15b61d33bdae44de528e106fcc6f9
// process.config is serialized config.gypi
const binding = internalBinding('builtins');
-diff --git a/lib/internal/modules/cjs/loader.js b/lib/internal/modules/cjs/loader.js
-index c794751ecd4448119ce33d661e694f83b3323f03..364469160af5e348f8890417de16a63c0d1dca67 100644
---- a/lib/internal/modules/cjs/loader.js
-+++ b/lib/internal/modules/cjs/loader.js
-@@ -138,7 +138,7 @@ const {
- const assert = require('internal/assert');
- const fs = require('fs');
- const path = require('path');
--const { internalModuleStat } = internalBinding('fs');
-+const internalFsBinding = internalBinding('fs');
- const { safeGetenv } = internalBinding('credentials');
- const {
- privateSymbols: {
-@@ -233,7 +233,7 @@ function stat(filename) {
- const result = statCache.get(filename);
- if (result !== undefined) { return result; }
- }
-- const result = internalModuleStat(filename);
-+ const result = internalFsBinding.internalModuleStat(filename);
- if (statCache !== null && result >= 0) {
- // Only set cache when `internalModuleStat(filename)` succeeds.
- statCache.set(filename, result);
-diff --git a/lib/internal/modules/package_json_reader.js b/lib/internal/modules/package_json_reader.js
-index 88c079d10d116107aa34dc9281f64c799c48c0b5..069f922612777f226127dc44f4091eed30416925 100644
---- a/lib/internal/modules/package_json_reader.js
-+++ b/lib/internal/modules/package_json_reader.js
-@@ -12,7 +12,7 @@ const {
- const {
- ERR_INVALID_PACKAGE_CONFIG,
- } = require('internal/errors').codes;
--const { internalModuleReadJSON } = internalBinding('fs');
-+const internalFsBinding = internalBinding('fs');
- const { resolve, sep, toNamespacedPath } = require('path');
- const permission = require('internal/process/permission');
- const { kEmptyObject } = require('internal/util');
-@@ -53,7 +53,7 @@ function read(jsonPath, { base, specifier, isESM } = kEmptyObject) {
- const {
- 0: string,
- 1: containsKeys,
-- } = internalModuleReadJSON(
-+ } = internalFsBinding.internalModuleReadJSON(
- toNamespacedPath(jsonPath),
- );
- const result = {
diff --git a/patches/node/spec_add_iterator_to_global_intrinsics.patch b/patches/node/spec_add_iterator_to_global_intrinsics.patch
deleted file mode 100644
index 45f3a8e62c..0000000000
--- a/patches/node/spec_add_iterator_to_global_intrinsics.patch
+++ /dev/null
@@ -1,19 +0,0 @@
-From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
-From: Samuel Attard <[email protected]>
-Date: Thu, 11 Jan 2024 15:14:43 +1300
-Subject: spec: add Iterator to global intrinsics
-
-Ref: https://chromium-review.googlesource.com/c/v8/v8/+/4266490
-
-diff --git a/test/common/globals.js b/test/common/globals.js
-index cb7c1629007ecfc6c6a1aae0e6d1e9a50f07d147..5d1c4415eeb09e92d062330afc0aecb1d297b6d3 100644
---- a/test/common/globals.js
-+++ b/test/common/globals.js
-@@ -63,6 +63,7 @@ const intrinsics = new Set([
- 'SharedArrayBuffer',
- 'Atomics',
- 'WebAssembly',
-+ 'Iterator',
- ]);
-
- if (global.gc) {
diff --git a/patches/node/src_do_not_use_deprecated_v8_api.patch b/patches/node/src_do_not_use_deprecated_v8_api.patch
deleted file mode 100644
index 7e2ac1f2eb..0000000000
--- a/patches/node/src_do_not_use_deprecated_v8_api.patch
+++ /dev/null
@@ -1,118 +0,0 @@
-From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
-From: ishell <[email protected]>
-Date: Mon, 25 Mar 2024 15:45:41 +0100
-Subject: src: do not use deprecated V8 API
-MIME-Version: 1.0
-Content-Type: text/plain; charset=UTF-8
-Content-Transfer-Encoding: 8bit
-
-Namely:
- - `v8::ObjectTemplate::SetAccessor(v8::Local<v8::String>, ...);`
- - `v8::ObjectTemplate::SetNativeDataProperty` with `AccessControl`
-
-Refs: https://github.com/v8/v8/commit/46c241eb99557fe8205acac5c526650c3847d180
-Refs: https://github.com/v8/v8/commit/6ec883986bd417e2a42ddb960bd9449deb7e4639
-Co-authored-by: Michaël Zasso <[email protected]>
-PR-URL: https://github.com/nodejs/node/pull/53084
-Reviewed-By: Luigi Pinca <[email protected]>
-Reviewed-By: Tobias Nießen <[email protected]>
-Reviewed-By: James M Snell <[email protected]>
-Reviewed-By: Joyee Cheung <[email protected]>
-(cherry picked from commit 26d5cafff76d3a096ebfd7d7a6279d4b5b190230)
-
-diff --git a/src/base_object-inl.h b/src/base_object-inl.h
-index da8fed7b3013df10ae02be2070545c74d9a978f0..518b22dabef0974c2e7ecb466669925338524059 100644
---- a/src/base_object-inl.h
-+++ b/src/base_object-inl.h
-@@ -132,14 +132,14 @@ v8::EmbedderGraph::Node::Detachedness BaseObject::GetDetachedness() const {
-
- template <int Field>
- void BaseObject::InternalFieldGet(
-- v8::Local<v8::String> property,
-+ v8::Local<v8::Name> property,
- const v8::PropertyCallbackInfo<v8::Value>& info) {
- info.GetReturnValue().Set(
- info.This()->GetInternalField(Field).As<v8::Value>());
- }
-
--template <int Field, bool (v8::Value::* typecheck)() const>
--void BaseObject::InternalFieldSet(v8::Local<v8::String> property,
-+template <int Field, bool (v8::Value::*typecheck)() const>
-+void BaseObject::InternalFieldSet(v8::Local<v8::Name> property,
- v8::Local<v8::Value> value,
- const v8::PropertyCallbackInfo<void>& info) {
- // This could be e.g. value->IsFunction().
-diff --git a/src/base_object.h b/src/base_object.h
-index 5968694e8393d8434fb2ffee411dfac4c93aff29..5c16d0d1b32e2d056f4fcfa0e01781292932a0fa 100644
---- a/src/base_object.h
-+++ b/src/base_object.h
-@@ -111,10 +111,10 @@ class BaseObject : public MemoryRetainer {
-
- // Setter/Getter pair for internal fields that can be passed to SetAccessor.
- template <int Field>
-- static void InternalFieldGet(v8::Local<v8::String> property,
-+ static void InternalFieldGet(v8::Local<v8::Name> property,
- const v8::PropertyCallbackInfo<v8::Value>& info);
- template <int Field, bool (v8::Value::*typecheck)() const>
-- static void InternalFieldSet(v8::Local<v8::String> property,
-+ static void InternalFieldSet(v8::Local<v8::Name> property,
- v8::Local<v8::Value> value,
- const v8::PropertyCallbackInfo<void>& info);
-
-diff --git a/src/node_builtins.cc b/src/node_builtins.cc
-index 3e37aa8b0c9696cceb3f3cfab9721f38c74a2fba..78f20de6b127961e9de7b5caaeca702ed7a36e01 100644
---- a/src/node_builtins.cc
-+++ b/src/node_builtins.cc
-@@ -11,7 +11,6 @@ namespace node {
- namespace builtins {
-
- using v8::Context;
--using v8::DEFAULT;
- using v8::EscapableHandleScope;
- using v8::Function;
- using v8::FunctionCallbackInfo;
-@@ -720,7 +719,6 @@ void BuiltinLoader::CreatePerIsolateProperties(IsolateData* isolate_data,
- nullptr,
- Local<Value>(),
- None,
-- DEFAULT,
- SideEffectType::kHasNoSideEffect);
-
- target->SetNativeDataProperty(FIXED_ONE_BYTE_STRING(isolate, "builtinIds"),
-@@ -728,7 +726,6 @@ void BuiltinLoader::CreatePerIsolateProperties(IsolateData* isolate_data,
- nullptr,
- Local<Value>(),
- None,
-- DEFAULT,
- SideEffectType::kHasNoSideEffect);
-
- target->SetNativeDataProperty(
-@@ -737,7 +734,6 @@ void BuiltinLoader::CreatePerIsolateProperties(IsolateData* isolate_data,
- nullptr,
- Local<Value>(),
- None,
-- DEFAULT,
- SideEffectType::kHasNoSideEffect);
-
- target->SetNativeDataProperty(FIXED_ONE_BYTE_STRING(isolate, "natives"),
-@@ -745,7 +741,6 @@ void BuiltinLoader::CreatePerIsolateProperties(IsolateData* isolate_data,
- nullptr,
- Local<Value>(),
- None,
-- DEFAULT,
- SideEffectType::kHasNoSideEffect);
-
- SetMethod(isolate, target, "getCacheUsage", BuiltinLoader::GetCacheUsage);
-diff --git a/src/node_external_reference.h b/src/node_external_reference.h
-index 4e2ad9024020fa0851da41da44afccdf188c7044..c4aba23510872d66b58a1adc88cdd1ee85a86cfe 100644
---- a/src/node_external_reference.h
-+++ b/src/node_external_reference.h
-@@ -64,8 +64,6 @@ class ExternalReferenceRegistry {
- V(CFunctionWithBool) \
- V(const v8::CFunctionInfo*) \
- V(v8::FunctionCallback) \
-- V(v8::AccessorGetterCallback) \
-- V(v8::AccessorSetterCallback) \
- V(v8::AccessorNameGetterCallback) \
- V(v8::AccessorNameSetterCallback) \
- V(v8::GenericNamedPropertyDefinerCallback) \
diff --git a/patches/node/src_remove_dependency_on_wrapper-descriptor-based_cppheap.patch b/patches/node/src_remove_dependency_on_wrapper-descriptor-based_cppheap.patch
index 78b759febc..ef2c934d36 100644
--- a/patches/node/src_remove_dependency_on_wrapper-descriptor-based_cppheap.patch
+++ b/patches/node/src_remove_dependency_on_wrapper-descriptor-based_cppheap.patch
@@ -16,7 +16,7 @@ patch:
(cherry picked from commit 30329d06235a9f9733b1d4da479b403462d1b326)
diff --git a/src/env-inl.h b/src/env-inl.h
-index d98a32d6ec311459877bc3b0de33cca4766aeda7..9fc934975b015b97ddd84bf3eea5d53144130035 100644
+index 28a15aa741ddd40c664aae641797e7cc2813442f..08fe98e10b7716c694bbc882299fe0ed9e282d73 100644
--- a/src/env-inl.h
+++ b/src/env-inl.h
@@ -62,31 +62,6 @@ inline uv_loop_t* IsolateData::event_loop() const {
@@ -52,10 +52,10 @@ index d98a32d6ec311459877bc3b0de33cca4766aeda7..9fc934975b015b97ddd84bf3eea5d531
return &(wrapper_data_->cppgc_id);
}
diff --git a/src/env.cc b/src/env.cc
-index 38802b1e9acf9b3e99fdc4f39770e896393befe3..e0433e29ca98c42a38d1da6d66085fdea1edde29 100644
+index 665b064091d4cc42a4dc9ee5b0ea9e2f190338ca..4c8cb75945d82544ce2237d94cd1406d15efe424 100644
--- a/src/env.cc
+++ b/src/env.cc
-@@ -22,6 +22,7 @@
+@@ -23,6 +23,7 @@
#include "util-inl.h"
#include "v8-cppgc.h"
#include "v8-profiler.h"
@@ -63,7 +63,7 @@ index 38802b1e9acf9b3e99fdc4f39770e896393befe3..e0433e29ca98c42a38d1da6d66085fde
#include <algorithm>
#include <atomic>
-@@ -68,7 +69,6 @@ using v8::TryCatch;
+@@ -71,7 +72,6 @@ using v8::TryCatch;
using v8::Uint32;
using v8::Undefined;
using v8::Value;
@@ -71,7 +71,7 @@ index 38802b1e9acf9b3e99fdc4f39770e896393befe3..e0433e29ca98c42a38d1da6d66085fde
using worker::Worker;
int const ContextEmbedderTag::kNodeContextTag = 0x6e6f64;
-@@ -530,6 +530,14 @@ void IsolateData::CreateProperties() {
+@@ -532,6 +532,14 @@ void IsolateData::CreateProperties() {
CreateEnvProxyTemplate(this);
}
@@ -86,7 +86,7 @@ index 38802b1e9acf9b3e99fdc4f39770e896393befe3..e0433e29ca98c42a38d1da6d66085fde
constexpr uint16_t kDefaultCppGCEmbedderID = 0x90de;
Mutex IsolateData::isolate_data_mutex_;
std::unordered_map<uint16_t, std::unique_ptr<PerIsolateWrapperData>>
-@@ -567,36 +575,16 @@ IsolateData::IsolateData(Isolate* isolate,
+@@ -569,36 +577,16 @@ IsolateData::IsolateData(Isolate* isolate,
v8::CppHeap* cpp_heap = isolate->GetCppHeap();
uint16_t cppgc_id = kDefaultCppGCEmbedderID;
@@ -130,7 +130,7 @@ index 38802b1e9acf9b3e99fdc4f39770e896393befe3..e0433e29ca98c42a38d1da6d66085fde
{
// GC could still be run after the IsolateData is destroyed, so we store
-@@ -628,11 +616,12 @@ IsolateData::~IsolateData() {
+@@ -630,11 +618,12 @@ IsolateData::~IsolateData() {
}
}
@@ -146,10 +146,10 @@ index 38802b1e9acf9b3e99fdc4f39770e896393befe3..e0433e29ca98c42a38d1da6d66085fde
void IsolateData::MemoryInfo(MemoryTracker* tracker) const {
diff --git a/src/env.h b/src/env.h
-index 7cb77fb4f35a60fbda5b868798321ac8b6340bfa..06746554e1d60a9377ff6d7d970220f3fa88e4ac 100644
+index 49ca9c0042ccf22ad1fffa54f05fd443cbc681ba..945535d0dc40f1a32f7e3ecf7d50361e591ba6c8 100644
--- a/src/env.h
+++ b/src/env.h
-@@ -174,10 +174,6 @@ class NODE_EXTERN_PRIVATE IsolateData : public MemoryRetainer {
+@@ -175,10 +175,6 @@ class NODE_EXTERN_PRIVATE IsolateData : public MemoryRetainer {
uint16_t* embedder_id_for_cppgc() const;
uint16_t* embedder_id_for_non_cppgc() const;
@@ -161,7 +161,7 @@ index 7cb77fb4f35a60fbda5b868798321ac8b6340bfa..06746554e1d60a9377ff6d7d970220f3
inline MultiIsolatePlatform* platform() const;
inline const SnapshotData* snapshot_data() const;
diff --git a/src/node.h b/src/node.h
-index df3fb3372d6357b5d77b4f683e309b8483998128..01e8a4f2ed905bf5bbb803419012a014c204b460 100644
+index c16204ad2a4787eeffe61eedda254d3a5509df8c..c39f586e9c5e7e9db75d922d244ea8e4d6d56841 100644
--- a/src/node.h
+++ b/src/node.h
@@ -1561,24 +1561,14 @@ void RegisterSignalHandler(int signal,
diff --git a/patches/node/src_stop_using_deprecated_fields_of_fastapicallbackoptions.patch b/patches/node/src_stop_using_deprecated_fields_of_fastapicallbackoptions.patch
index 6aa803f630..861bd69338 100644
--- a/patches/node/src_stop_using_deprecated_fields_of_fastapicallbackoptions.patch
+++ b/patches/node/src_stop_using_deprecated_fields_of_fastapicallbackoptions.patch
@@ -11,6 +11,20 @@ two fields in node.js.
branch of Node.js. This patch can be removed when Electron upgrades to
a stable Node release that contains the change. -- Charles)
+diff --git a/src/crypto/crypto_timing.cc b/src/crypto/crypto_timing.cc
+index 3d8ccc77b5952a999c5fe48792259d32b402c460..867a1c4aca54b9d41490d23a5eb55088b7e941cc 100644
+--- a/src/crypto/crypto_timing.cc
++++ b/src/crypto/crypto_timing.cc
+@@ -59,7 +59,8 @@ bool FastTimingSafeEqual(Local<Value> receiver,
+ if (a.length() != b.length() || !a.getStorageIfAligned(&data_a) ||
+ !b.getStorageIfAligned(&data_b)) {
+ TRACK_V8_FAST_API_CALL("crypto.timingSafeEqual.error");
+- options.fallback = true;
++ v8::HandleScope scope(options.isolate);
++ THROW_ERR_CRYPTO_TIMING_SAFE_EQUAL_LENGTH(options.isolate);
+ return false;
+ }
+
diff --git a/src/histogram.cc b/src/histogram.cc
index 4dbdea9be5721486d71a9dda77311b4919d450a3..4aacaa2a5d12533a039b4b96cb7f1fd79063d50f 100644
--- a/src/histogram.cc
@@ -25,6 +39,36 @@ index 4dbdea9be5721486d71a9dda77311b4919d450a3..4aacaa2a5d12533a039b4b96cb7f1fd7
return;
}
HistogramBase* histogram;
+diff --git a/src/node_file.cc b/src/node_file.cc
+index b565beae625d970ba92ab667a145d8897d4e8a6e..31c2fe82299d6905855c4efffeea4a4d161a88d5 100644
+--- a/src/node_file.cc
++++ b/src/node_file.cc
+@@ -1049,23 +1049,10 @@ static int32_t FastInternalModuleStat(
+ const FastOneByteString& input,
+ // NOLINTNEXTLINE(runtime/references) This is V8 api.
+ FastApiCallbackOptions& options) {
+- // This needs a HandleScope which needs an isolate.
+- Isolate* isolate = Isolate::TryGetCurrent();
+- if (!isolate) {
+- options.fallback = true;
+- return -1;
+- }
+-
+- HandleScope scope(isolate);
+- Environment* env = Environment::GetCurrent(recv->GetCreationContextChecked());
++ Environment* env = Environment::GetCurrent(options.isolate);
++ HandleScope scope(env->isolate());
+
+ auto path = std::filesystem::path(input.data, input.data + input.length);
+- if (UNLIKELY(!env->permission()->is_granted(
+- env, permission::PermissionScope::kFileSystemRead, path.string()))) {
+- options.fallback = true;
+- return -1;
+- }
+-
+ switch (std::filesystem::status(path).type()) {
+ case std::filesystem::file_type::directory:
+ return 1;
diff --git a/src/node_wasi.cc b/src/node_wasi.cc
index ad1da44a01f437c97e06a3857eebd2edcebc83da..7123278e1a0942b61a76e9b1e7464eb8b5064079 100644
--- a/src/node_wasi.cc
diff --git a/patches/node/src_update_default_v8_platform_to_override_functions_with_location.patch b/patches/node/src_update_default_v8_platform_to_override_functions_with_location.patch
deleted file mode 100644
index 8d576cc657..0000000000
--- a/patches/node/src_update_default_v8_platform_to_override_functions_with_location.patch
+++ /dev/null
@@ -1,87 +0,0 @@
-From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
-From: Etienne Pierre-Doray <[email protected]>
-Date: Mon, 11 Dec 2023 04:13:38 -0500
-Subject: src: update default V8 platform to override functions with location
-
-Xref: https://chromium-review.googlesource.com/c/v8/v8/+/4514946
-Xref: https://chromium-review.googlesource.com/c/v8/v8/+/4336198
-
-Backported from https://github.com/nodejs/node-v8/commit/f66b996030e94a7e4874820a53475338e1df4fe3
-
-diff --git a/src/node_platform.cc b/src/node_platform.cc
-index 97cf6cb840bab5016e485b0dd90b3e4e1d8686c9..00ca9757bc4d0cdeb03a3f32be3ef19077cb7969 100644
---- a/src/node_platform.cc
-+++ b/src/node_platform.cc
-@@ -501,17 +501,22 @@ bool PerIsolatePlatformData::FlushForegroundTasksInternal() {
- return did_work;
- }
-
--void NodePlatform::CallOnWorkerThread(std::unique_ptr<Task> task) {
-+void NodePlatform::PostTaskOnWorkerThreadImpl(
-+ v8::TaskPriority priority,
-+ std::unique_ptr<v8::Task> task,
-+ const v8::SourceLocation& location) {
- worker_thread_task_runner_->PostTask(std::move(task));
- }
-
--void NodePlatform::CallDelayedOnWorkerThread(std::unique_ptr<Task> task,
-- double delay_in_seconds) {
-+void NodePlatform::PostDelayedTaskOnWorkerThreadImpl(
-+ v8::TaskPriority priority,
-+ std::unique_ptr<v8::Task> task,
-+ double delay_in_seconds,
-+ const v8::SourceLocation& location) {
- worker_thread_task_runner_->PostDelayedTask(std::move(task),
- delay_in_seconds);
- }
-
--
- IsolatePlatformDelegate* NodePlatform::ForIsolate(Isolate* isolate) {
- Mutex::ScopedLock lock(per_isolate_mutex_);
- auto data = per_isolate_[isolate];
-@@ -533,8 +538,10 @@ bool NodePlatform::FlushForegroundTasks(Isolate* isolate) {
- return per_isolate->FlushForegroundTasksInternal();
- }
-
--std::unique_ptr<v8::JobHandle> NodePlatform::CreateJob(
-- v8::TaskPriority priority, std::unique_ptr<v8::JobTask> job_task) {
-+std::unique_ptr<v8::JobHandle> NodePlatform::CreateJobImpl(
-+ v8::TaskPriority priority,
-+ std::unique_ptr<v8::JobTask> job_task,
-+ const v8::SourceLocation& location) {
- return v8::platform::NewDefaultJobHandle(
- this, priority, std::move(job_task), NumberOfWorkerThreads());
- }
-diff --git a/src/node_platform.h b/src/node_platform.h
-index 1062f3b1b9c386a7bde8dca366c6f008bb183ab7..77cb5e6e4f891c510cdaf7fd6175a1f00d9bc420 100644
---- a/src/node_platform.h
-+++ b/src/node_platform.h
-@@ -147,17 +147,23 @@ class NodePlatform : public MultiIsolatePlatform {
-
- // v8::Platform implementation.
- int NumberOfWorkerThreads() override;
-- void CallOnWorkerThread(std::unique_ptr<v8::Task> task) override;
-- void CallDelayedOnWorkerThread(std::unique_ptr<v8::Task> task,
-- double delay_in_seconds) override;
-+ void PostTaskOnWorkerThreadImpl(v8::TaskPriority priority,
-+ std::unique_ptr<v8::Task> task,
-+ const v8::SourceLocation& location) override;
-+ void PostDelayedTaskOnWorkerThreadImpl(
-+ v8::TaskPriority priority,
-+ std::unique_ptr<v8::Task> task,
-+ double delay_in_seconds,
-+ const v8::SourceLocation& location) override;
- bool IdleTasksEnabled(v8::Isolate* isolate) override;
- double MonotonicallyIncreasingTime() override;
- double CurrentClockTimeMillis() override;
- v8::TracingController* GetTracingController() override;
- bool FlushForegroundTasks(v8::Isolate* isolate) override;
-- std::unique_ptr<v8::JobHandle> CreateJob(
-+ std::unique_ptr<v8::JobHandle> CreateJobImpl(
- v8::TaskPriority priority,
-- std::unique_ptr<v8::JobTask> job_task) override;
-+ std::unique_ptr<v8::JobTask> job_task,
-+ const v8::SourceLocation& location) override;
-
- void RegisterIsolate(v8::Isolate* isolate, uv_loop_t* loop) override;
- void RegisterIsolate(v8::Isolate* isolate,
diff --git a/patches/node/src_use_new_v8_api_to_define_stream_accessor.patch b/patches/node/src_use_new_v8_api_to_define_stream_accessor.patch
deleted file mode 100644
index 3688d4d252..0000000000
--- a/patches/node/src_use_new_v8_api_to_define_stream_accessor.patch
+++ /dev/null
@@ -1,153 +0,0 @@
-From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
-From: Igor Sheludko <[email protected]>
-Date: Tue, 30 Apr 2024 15:22:06 +0200
-Subject: src: use new V8 API to define stream accessor
-MIME-Version: 1.0
-Content-Type: text/plain; charset=UTF-8
-Content-Transfer-Encoding: 8bit
-
-Define XxxStream.prototype.onread as an accessor in JavaScript sense.
-
-Previously it was defined via soon-to-be-deprecated
-`v8::ObjectTemplate::SetAccessor(..)` which used to call setter even
-for property stores via stream object.
-
-The replacement V8 API `v8::ObjectTemplate::SetNativeDataProperty(..)`
-defines a properly behaving data property and thus a store to a stream
-object will not trigger the "onread" setter callback.
-
-In order to preserve the desired behavior of storing the value in the
-receiver's internal field the "onread" property should be defined as
-a proper JavaScript accessor.
-
-PR-URL: https://github.com/nodejs/node/pull/53084
-Refs: https://github.com/v8/v8/commit/46c241eb99557fe8205acac5c526650c3847d180
-Refs: https://github.com/v8/v8/commit/6ec883986bd417e2a42ddb960bd9449deb7e4639
-Reviewed-By: Luigi Pinca <[email protected]>
-Reviewed-By: Tobias Nießen <[email protected]>
-Reviewed-By: James M Snell <[email protected]>
-Reviewed-By: Joyee Cheung <[email protected]>
-(cherry picked from commit bd151552ef35b0eed415eb1c50d30dafd341cee8)
-
-diff --git a/src/base_object-inl.h b/src/base_object-inl.h
-index 518b22dabef0974c2e7ecb466669925338524059..61f30b3cfbdb0f3d21fe8e93dc97c55162b69a69 100644
---- a/src/base_object-inl.h
-+++ b/src/base_object-inl.h
-@@ -132,19 +132,18 @@ v8::EmbedderGraph::Node::Detachedness BaseObject::GetDetachedness() const {
-
- template <int Field>
- void BaseObject::InternalFieldGet(
-- v8::Local<v8::Name> property,
-- const v8::PropertyCallbackInfo<v8::Value>& info) {
-- info.GetReturnValue().Set(
-- info.This()->GetInternalField(Field).As<v8::Value>());
-+ const v8::FunctionCallbackInfo<v8::Value>& args) {
-+ args.GetReturnValue().Set(
-+ args.This()->GetInternalField(Field).As<v8::Value>());
- }
-
- template <int Field, bool (v8::Value::*typecheck)() const>
--void BaseObject::InternalFieldSet(v8::Local<v8::Name> property,
-- v8::Local<v8::Value> value,
-- const v8::PropertyCallbackInfo<void>& info) {
-+void BaseObject::InternalFieldSet(
-+ const v8::FunctionCallbackInfo<v8::Value>& args) {
-+ v8::Local<v8::Value> value = args[0];
- // This could be e.g. value->IsFunction().
- CHECK(((*value)->*typecheck)());
-- info.This()->SetInternalField(Field, value);
-+ args.This()->SetInternalField(Field, value);
- }
-
- bool BaseObject::has_pointer_data() const {
-diff --git a/src/base_object.h b/src/base_object.h
-index 5c16d0d1b32e2d056f4fcfa0e01781292932a0fa..ce6277dec5a2b9313ecd3699b39ec17585d5adc5 100644
---- a/src/base_object.h
-+++ b/src/base_object.h
-@@ -111,12 +111,9 @@ class BaseObject : public MemoryRetainer {
-
- // Setter/Getter pair for internal fields that can be passed to SetAccessor.
- template <int Field>
-- static void InternalFieldGet(v8::Local<v8::Name> property,
-- const v8::PropertyCallbackInfo<v8::Value>& info);
-+ static void InternalFieldGet(const v8::FunctionCallbackInfo<v8::Value>& args);
- template <int Field, bool (v8::Value::*typecheck)() const>
-- static void InternalFieldSet(v8::Local<v8::Name> property,
-- v8::Local<v8::Value> value,
-- const v8::PropertyCallbackInfo<void>& info);
-+ static void InternalFieldSet(const v8::FunctionCallbackInfo<v8::Value>& args);
-
- // This is a bit of a hack. See the override in async_wrap.cc for details.
- virtual bool IsDoneInitializing() const;
-diff --git a/src/stream_base.cc b/src/stream_base.cc
-index d2649ea0a649bb2f6c6becf1891c0b6d773c1a62..9d855c2992492d3394d9f8af4e53781027a2dd83 100644
---- a/src/stream_base.cc
-+++ b/src/stream_base.cc
-@@ -492,6 +492,29 @@ Local<Object> StreamBase::GetObject() {
- return GetAsyncWrap()->object();
- }
-
-+void StreamBase::AddAccessor(v8::Isolate* isolate,
-+ v8::Local<v8::Signature> signature,
-+ enum v8::PropertyAttribute attributes,
-+ v8::Local<v8::FunctionTemplate> t,
-+ JSMethodFunction* getter,
-+ JSMethodFunction* setter,
-+ v8::Local<v8::String> string) {
-+ Local<FunctionTemplate> getter_templ =
-+ NewFunctionTemplate(isolate,
-+ getter,
-+ signature,
-+ ConstructorBehavior::kThrow,
-+ SideEffectType::kHasNoSideEffect);
-+ Local<FunctionTemplate> setter_templ =
-+ NewFunctionTemplate(isolate,
-+ setter,
-+ signature,
-+ ConstructorBehavior::kThrow,
-+ SideEffectType::kHasSideEffect);
-+ t->PrototypeTemplate()->SetAccessorProperty(
-+ string, getter_templ, setter_templ, attributes);
-+}
-+
- void StreamBase::AddMethod(Isolate* isolate,
- Local<Signature> signature,
- enum PropertyAttribute attributes,
-@@ -561,11 +584,14 @@ void StreamBase::AddMethods(IsolateData* isolate_data,
- JSMethod<&StreamBase::WriteString<LATIN1>>);
- t->PrototypeTemplate()->Set(FIXED_ONE_BYTE_STRING(isolate, "isStreamBase"),
- True(isolate));
-- t->PrototypeTemplate()->SetAccessor(
-- FIXED_ONE_BYTE_STRING(isolate, "onread"),
-- BaseObject::InternalFieldGet<StreamBase::kOnReadFunctionField>,
-- BaseObject::InternalFieldSet<StreamBase::kOnReadFunctionField,
-- &Value::IsFunction>);
-+ AddAccessor(isolate,
-+ sig,
-+ static_cast<PropertyAttribute>(DontDelete | DontEnum),
-+ t,
-+ BaseObject::InternalFieldGet<StreamBase::kOnReadFunctionField>,
-+ BaseObject::InternalFieldSet<StreamBase::kOnReadFunctionField,
-+ &Value::IsFunction>,
-+ FIXED_ONE_BYTE_STRING(isolate, "onread"));
- }
-
- void StreamBase::RegisterExternalReferences(
-diff --git a/src/stream_base.h b/src/stream_base.h
-index 62a8928e144ad6aa67eeccdbc46d44da22887fb8..ccbd769ceaf3c1e024defb3104e601d037c98b6a 100644
---- a/src/stream_base.h
-+++ b/src/stream_base.h
-@@ -413,6 +413,13 @@ class StreamBase : public StreamResource {
- EmitToJSStreamListener default_listener_;
-
- void SetWriteResult(const StreamWriteResult& res);
-+ static void AddAccessor(v8::Isolate* isolate,
-+ v8::Local<v8::Signature> sig,
-+ enum v8::PropertyAttribute attributes,
-+ v8::Local<v8::FunctionTemplate> t,
-+ JSMethodFunction* getter,
-+ JSMethodFunction* setter,
-+ v8::Local<v8::String> str);
- static void AddMethod(v8::Isolate* isolate,
- v8::Local<v8::Signature> sig,
- enum v8::PropertyAttribute attributes,
diff --git a/patches/node/src_use_supported_api_to_get_stalled_tla_messages.patch b/patches/node/src_use_supported_api_to_get_stalled_tla_messages.patch
deleted file mode 100644
index c4c302dc66..0000000000
--- a/patches/node/src_use_supported_api_to_get_stalled_tla_messages.patch
+++ /dev/null
@@ -1,27 +0,0 @@
-From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
-From: =?UTF-8?q?Micha=C3=ABl=20Zasso?= <[email protected]>
-Date: Mon, 11 Mar 2024 09:27:11 +0000
-Subject: src: use supported API to get stalled TLA messages
-
-Refs: https://github.com/v8/v8/commit/23e3b6f650162ed2b332e55aa802adb8f41b50f2
-
-diff --git a/src/module_wrap.cc b/src/module_wrap.cc
-index 9bbb8ab908d8d992abb43254860d51f57f56387b..92edfc6fc6401edd3685a0137eac25d9e37566f6 100644
---- a/src/module_wrap.cc
-+++ b/src/module_wrap.cc
-@@ -587,11 +587,10 @@ void ModuleWrap::EvaluateSync(const FunctionCallbackInfo<Value>& args) {
-
- if (module->IsGraphAsync()) {
- CHECK(env->options()->print_required_tla);
-- auto stalled = module->GetStalledTopLevelAwaitMessage(isolate);
-- if (stalled.size() != 0) {
-- for (auto pair : stalled) {
-- Local<v8::Message> message = std::get<1>(pair);
--
-+ auto stalled_messages =
-+ std::get<1>(module->GetStalledTopLevelAwaitMessages(isolate));
-+ if (stalled_messages.size() != 0) {
-+ for (auto& message : stalled_messages) {
- std::string reason = "Error: unexpected top-level await at ";
- std::string info =
- FormatErrorMessage(isolate, context, "", message, true);
diff --git a/patches/node/support_v8_sandboxed_pointers.patch b/patches/node/support_v8_sandboxed_pointers.patch
index abeae7e10d..40624c1ca8 100644
--- a/patches/node/support_v8_sandboxed_pointers.patch
+++ b/patches/node/support_v8_sandboxed_pointers.patch
@@ -7,7 +7,7 @@ This refactors several allocators to allocate within the V8 memory cage,
allowing them to be compatible with the V8_SANDBOXED_POINTERS feature.
diff --git a/src/api/environment.cc b/src/api/environment.cc
-index e0bf37f09dceb93af58990438ab577a9d4b843e8..b9098d102b40adad7fafcc331ac62870617019b9 100644
+index 5fc1b6f2446d7c786024eb60800e2edab613dcd1..f59abcb21d64b910d8d42eb23c03109f62558813 100644
--- a/src/api/environment.cc
+++ b/src/api/environment.cc
@@ -101,6 +101,14 @@ MaybeLocal<Value> PrepareStackTraceCallback(Local<Context> context,
@@ -25,11 +25,49 @@ index e0bf37f09dceb93af58990438ab577a9d4b843e8..b9098d102b40adad7fafcc331ac62870
void* NodeArrayBufferAllocator::Allocate(size_t size) {
void* ret;
if (zero_fill_field_ || per_process::cli_options->zero_fill_all_buffers)
+diff --git a/src/crypto/crypto_dh.cc b/src/crypto/crypto_dh.cc
+index 33ffbbb85d05f5356183e3aa1ca23707c5629b5d..008d212ebe25b0022020379aa08963c12828940c 100644
+--- a/src/crypto/crypto_dh.cc
++++ b/src/crypto/crypto_dh.cc
+@@ -51,6 +51,25 @@ void DiffieHellman::MemoryInfo(MemoryTracker* tracker) const {
+ namespace {
+ MaybeLocal<Value> DataPointerToBuffer(Environment* env,
+ ncrypto::DataPointer&& data) {
++#if defined(V8_ENABLE_SANDBOX)
++ std::unique_ptr<v8::BackingStore> backing;
++ if (data.size() > 0) {
++ std::unique_ptr<ArrayBuffer::Allocator> allocator(ArrayBuffer::Allocator::NewDefaultAllocator());
++ void* v8_data = allocator->Allocate(data.size());
++ CHECK(v8_data);
++ memcpy(v8_data, data.get(), data.size());
++ backing = ArrayBuffer::NewBackingStore(
++ v8_data,
++ data.size(),
++ [](void* data, size_t length, void*) {
++ std::unique_ptr<ArrayBuffer::Allocator> allocator(ArrayBuffer::Allocator::NewDefaultAllocator());
++ allocator->Free(data, length);
++ }, nullptr);
++ } else {
++ NoArrayBufferZeroFillScope no_zero_fill_scope(env->isolate_data());
++ backing = v8::ArrayBuffer::NewBackingStore(env->isolate(), data.size());
++ }
++#else
+ auto backing = ArrayBuffer::NewBackingStore(
+ data.get(),
+ data.size(),
+@@ -59,6 +78,7 @@ MaybeLocal<Value> DataPointerToBuffer(Environment* env,
+ },
+ nullptr);
+ data.release();
++#endif
+
+ auto ab = ArrayBuffer::New(env->isolate(), std::move(backing));
+ return Buffer::New(env, ab, 0, ab->ByteLength()).FromMaybe(Local<Value>());
diff --git a/src/crypto/crypto_util.cc b/src/crypto/crypto_util.cc
-index 63d971e1fe6b861e29c12f04563701b01fdfb976..f39652a6f5196531cd78ce74e91076b1b9e970ca 100644
+index ee81048caab4ccfe26ea9e677782c9c955d162a9..643c9d31dc2737faa2ec51684ffceb35a1014a58 100644
--- a/src/crypto/crypto_util.cc
+++ b/src/crypto/crypto_util.cc
-@@ -348,10 +348,35 @@ ByteSource& ByteSource::operator=(ByteSource&& other) noexcept {
+@@ -326,10 +326,35 @@ ByteSource& ByteSource::operator=(ByteSource&& other) noexcept {
return *this;
}
@@ -66,7 +104,7 @@ index 63d971e1fe6b861e29c12f04563701b01fdfb976..f39652a6f5196531cd78ce74e91076b1
std::unique_ptr<BackingStore> ptr = ArrayBuffer::NewBackingStore(
allocated_data_,
size(),
-@@ -363,10 +388,11 @@ std::unique_ptr<BackingStore> ByteSource::ReleaseToBackingStore() {
+@@ -341,10 +366,11 @@ std::unique_ptr<BackingStore> ByteSource::ReleaseToBackingStore() {
data_ = nullptr;
size_ = 0;
return ptr;
@@ -79,7 +117,7 @@ index 63d971e1fe6b861e29c12f04563701b01fdfb976..f39652a6f5196531cd78ce74e91076b1
return ArrayBuffer::New(env->isolate(), std::move(store));
}
-@@ -703,6 +729,16 @@ namespace {
+@@ -641,6 +667,16 @@ namespace {
// in which case this has the same semantics as
// using OPENSSL_malloc. However, if the secure heap is
// initialized, SecureBuffer will automatically use it.
@@ -96,7 +134,7 @@ index 63d971e1fe6b861e29c12f04563701b01fdfb976..f39652a6f5196531cd78ce74e91076b1
void SecureBuffer(const FunctionCallbackInfo<Value>& args) {
CHECK(args[0]->IsUint32());
Environment* env = Environment::GetCurrent(args);
-@@ -724,6 +760,7 @@ void SecureBuffer(const FunctionCallbackInfo<Value>& args) {
+@@ -662,6 +698,7 @@ void SecureBuffer(const FunctionCallbackInfo<Value>& args) {
Local<ArrayBuffer> buffer = ArrayBuffer::New(env->isolate(), store);
args.GetReturnValue().Set(Uint8Array::New(buffer, 0, len));
}
@@ -105,10 +143,10 @@ index 63d971e1fe6b861e29c12f04563701b01fdfb976..f39652a6f5196531cd78ce74e91076b1
void SecureHeapUsed(const FunctionCallbackInfo<Value>& args) {
#ifndef OPENSSL_IS_BORINGSSL
diff --git a/src/crypto/crypto_util.h b/src/crypto/crypto_util.h
-index 4ba261014695cf1aa8eb53b21a2873f4c4ea8e43..b695d131bcdc331974f544924138bb5eedc50c9f 100644
+index 922e77091d72172ed6cfc5e8477901e3608396c5..16a236c69caed6d60248c7973531a95adc8f2edb 100644
--- a/src/crypto/crypto_util.h
+++ b/src/crypto/crypto_util.h
-@@ -285,7 +285,7 @@ class ByteSource {
+@@ -268,7 +268,7 @@ class ByteSource {
// Creates a v8::BackingStore that takes over responsibility for
// any allocated data. The ByteSource will be reset with size = 0
// after being called.
@@ -117,11 +155,44 @@ index 4ba261014695cf1aa8eb53b21a2873f4c4ea8e43..b695d131bcdc331974f544924138bb5e
v8::Local<v8::ArrayBuffer> ToArrayBuffer(Environment* env);
+diff --git a/src/crypto/crypto_x509.cc b/src/crypto/crypto_x509.cc
+index af2f953f0388dbce326b0c519de3883552f8f009..7fb34057a486914dd886ec4d3d23be90cccb4fea 100644
+--- a/src/crypto/crypto_x509.cc
++++ b/src/crypto/crypto_x509.cc
+@@ -174,6 +174,19 @@ MaybeLocal<Value> ToV8Value(Local<Context> context, const BIOPointer& bio) {
+ MaybeLocal<Value> ToBuffer(Environment* env, BIOPointer* bio) {
+ if (bio == nullptr || !*bio) return {};
+ BUF_MEM* mem = *bio;
++#if defined(V8_ENABLE_SANDBOX)
++ std::unique_ptr<ArrayBuffer::Allocator> allocator(ArrayBuffer::Allocator::NewDefaultAllocator());
++ void* v8_data = allocator->Allocate(mem->length);
++ CHECK(v8_data);
++ memcpy(v8_data, mem->data, mem->length);
++ std::unique_ptr<v8::BackingStore> backing = ArrayBuffer::NewBackingStore(
++ v8_data,
++ mem->length,
++ [](void* data, size_t length, void*) {
++ std::unique_ptr<ArrayBuffer::Allocator> allocator(ArrayBuffer::Allocator::NewDefaultAllocator());
++ allocator->Free(data, length);
++ }, nullptr);
++#else
+ auto backing = ArrayBuffer::NewBackingStore(
+ mem->data,
+ mem->length,
+@@ -181,6 +194,8 @@ MaybeLocal<Value> ToBuffer(Environment* env, BIOPointer* bio) {
+ BIOPointer free_me(static_cast<BIO*>(data));
+ },
+ bio->release());
++#endif
++
+ auto ab = ArrayBuffer::New(env->isolate(), std::move(backing));
+ Local<Value> ret;
+ if (!Buffer::New(env, ab, 0, ab->ByteLength()).ToLocal(&ret)) return {};
diff --git a/src/node_i18n.cc b/src/node_i18n.cc
-index 2aa7cd98ecc179519a6bb1932dafa86a38bda4f5..79376bef2e674f05fd95380dd419e8778cb98623 100644
+index 43bb68351bf0a68285e464601013bbdbd5d5df5f..4126bbff080548c91154a6dcc437359c82a6c771 100644
--- a/src/node_i18n.cc
+++ b/src/node_i18n.cc
-@@ -106,7 +106,7 @@ namespace {
+@@ -107,7 +107,7 @@ namespace {
template <typename T>
MaybeLocal<Object> ToBufferEndian(Environment* env, MaybeStackBuffer<T>* buf) {
@@ -130,7 +201,7 @@ index 2aa7cd98ecc179519a6bb1932dafa86a38bda4f5..79376bef2e674f05fd95380dd419e877
if (ret.IsEmpty())
return ret;
-@@ -183,7 +183,7 @@ MaybeLocal<Object> TranscodeLatin1ToUcs2(Environment* env,
+@@ -184,7 +184,7 @@ MaybeLocal<Object> TranscodeLatin1ToUcs2(Environment* env,
return {};
}
@@ -139,7 +210,7 @@ index 2aa7cd98ecc179519a6bb1932dafa86a38bda4f5..79376bef2e674f05fd95380dd419e877
}
MaybeLocal<Object> TranscodeFromUcs2(Environment* env,
-@@ -228,7 +228,7 @@ MaybeLocal<Object> TranscodeUcs2FromUtf8(Environment* env,
+@@ -229,7 +229,7 @@ MaybeLocal<Object> TranscodeUcs2FromUtf8(Environment* env,
return {};
}
@@ -148,7 +219,7 @@ index 2aa7cd98ecc179519a6bb1932dafa86a38bda4f5..79376bef2e674f05fd95380dd419e877
}
MaybeLocal<Object> TranscodeUtf8FromUcs2(Environment* env,
-@@ -252,7 +252,7 @@ MaybeLocal<Object> TranscodeUtf8FromUcs2(Environment* env,
+@@ -253,7 +253,7 @@ MaybeLocal<Object> TranscodeUtf8FromUcs2(Environment* env,
return {};
}
@@ -158,7 +229,7 @@ index 2aa7cd98ecc179519a6bb1932dafa86a38bda4f5..79376bef2e674f05fd95380dd419e877
constexpr const char* EncodingName(const enum encoding encoding) {
diff --git a/src/node_internals.h b/src/node_internals.h
-index 6264f23d54d6028bb0158f12a9296ba67a846358..613300215766aeb108219b0d1c3b95ee02db964f 100644
+index fe2d25decd883085e4c3f368ab4acc01a7f66f6e..bcd5c87afcff9c56429443363c63fc8079521451 100644
--- a/src/node_internals.h
+++ b/src/node_internals.h
@@ -117,7 +117,9 @@ v8::Maybe<bool> InitializePrimordials(v8::Local<v8::Context> context);
diff --git a/patches/node/test_formally_mark_some_tests_as_flaky.patch b/patches/node/test_formally_mark_some_tests_as_flaky.patch
index 79b02f4e85..5b01232074 100644
--- a/patches/node/test_formally_mark_some_tests_as_flaky.patch
+++ b/patches/node/test_formally_mark_some_tests_as_flaky.patch
@@ -7,7 +7,7 @@ Instead of disabling the tests, flag them as flaky so they still run
but don't cause CI failures on flakes.
diff --git a/test/parallel/parallel.status b/test/parallel/parallel.status
-index 79a953df7da64b7d7580e099a5cc5160e7842999..94616df356cab50c8ef4099e7863f5986deed377 100644
+index 24e1a74886bad536dc08df75fbdb0508e4e1420a..7f3be73474557788050a9110b0e29e602b7d6397 100644
--- a/test/parallel/parallel.status
+++ b/test/parallel/parallel.status
@@ -5,6 +5,16 @@ prefix parallel
diff --git a/patches/node/test_make_test-node-output-v8-warning_generic.patch b/patches/node/test_make_test-node-output-v8-warning_generic.patch
index 97df457cbd..85e434f823 100644
--- a/patches/node/test_make_test-node-output-v8-warning_generic.patch
+++ b/patches/node/test_make_test-node-output-v8-warning_generic.patch
@@ -14,7 +14,7 @@ meaningless. Fix it for now by replacing the process.argv0 basename instead.
Some form of fix for this should be upstreamed.
diff --git a/test/parallel/test-node-output-v8-warning.mjs b/test/parallel/test-node-output-v8-warning.mjs
-index 8e497739d21c70d5c792f43c268746a200916063..cad1910e020b15775ee16122bc9d310680fed687 100644
+index 309e904c49b7124b64831293e0473a5d35249081..6636144f5074811f95bbe53a62718c8084088bdc 100644
--- a/test/parallel/test-node-output-v8-warning.mjs
+++ b/test/parallel/test-node-output-v8-warning.mjs
@@ -2,11 +2,18 @@ import '../common/index.mjs';
@@ -33,10 +33,10 @@ index 8e497739d21c70d5c792f43c268746a200916063..cad1910e020b15775ee16122bc9d3106
+ return str.replaceAll(`${baseName} --`, '* --');
+}
+
- describe('v8 output', { concurrency: true }, () => {
+ describe('v8 output', { concurrency: !process.env.TEST_PARALLEL }, () => {
function normalize(str) {
return str.replaceAll(snapshot.replaceWindowsPaths(process.cwd()), '')
-@@ -15,10 +22,10 @@ describe('v8 output', { concurrency: true }, () => {
+@@ -15,10 +22,10 @@ describe('v8 output', { concurrency: !process.env.TEST_PARALLEL }, () => {
.replaceAll('*test*', '*')
.replaceAll(/.*?\*fixtures\*v8\*/g, '(node:*) V8: *') // Replace entire path before fixtures/v8
.replaceAll('*fixtures*v8*', '*')
diff --git a/patches/node/test_match_wpt_streams_transferable_transform-stream-members_any_js.patch b/patches/node/test_match_wpt_streams_transferable_transform-stream-members_any_js.patch
deleted file mode 100644
index 6a0a9f4b9d..0000000000
--- a/patches/node/test_match_wpt_streams_transferable_transform-stream-members_any_js.patch
+++ /dev/null
@@ -1,23 +0,0 @@
-From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
-From: Shelley Vohr <[email protected]>
-Date: Tue, 16 Jan 2024 19:39:10 +0100
-Subject: test: match wpt/streams/transferable/transform-stream-members.any.js
- to upstream
-
-All four of this calls should fail - see third_party/blink/web_tests/external/wpt/streams/transferable/transform-stream-members.any-expected.txt
-
-diff --git a/test/wpt/status/streams.json b/test/wpt/status/streams.json
-index 5425c86bba85079a44745779d998337aaa063df1..775661cd59b14132c9a811e448792ea02198f949 100644
---- a/test/wpt/status/streams.json
-+++ b/test/wpt/status/streams.json
-@@ -60,7 +60,9 @@
- "fail": {
- "expected": [
- "Transferring [object TransformStream],[object ReadableStream] should fail",
-- "Transferring [object TransformStream],[object WritableStream] should fail"
-+ "Transferring [object TransformStream],[object WritableStream] should fail",
-+ "Transferring [object ReadableStream],[object TransformStream] should fail",
-+ "Transferring [object WritableStream],[object TransformStream] should fail"
- ]
- }
- },
diff --git a/patches/node/test_update_v8-stats_test_for_v8_12_6.patch b/patches/node/test_update_v8-stats_test_for_v8_12_6.patch
index 1e0ac6eaca..671fcb14ed 100644
--- a/patches/node/test_update_v8-stats_test_for_v8_12_6.patch
+++ b/patches/node/test_update_v8-stats_test_for_v8_12_6.patch
@@ -6,7 +6,7 @@ Subject: test: update v8-stats test for V8 12.6
Refs: https://github.com/v8/v8/commit/e30e228ee6e034de49a40af0173113198a19b497
diff --git a/test/parallel/test-v8-stats.js b/test/parallel/test-v8-stats.js
-index 2366cbf716c11851bb3a759dce5db47d616516dc..9d2971ba9411bb98107f6a9acc8a07ec438b76e5 100644
+index bb954165f42c9de3db66bc5fdcac647654ad71ea..07be833e6e749a2bb68490c935c6791c178d126f 100644
--- a/test/parallel/test-v8-stats.js
+++ b/test/parallel/test-v8-stats.js
@@ -48,6 +48,8 @@ const expectedHeapSpaces = [
@@ -16,5 +16,5 @@ index 2366cbf716c11851bb3a759dce5db47d616516dc..9d2971ba9411bb98107f6a9acc8a07ec
+ 'shared_trusted_large_object_space',
+ 'shared_trusted_space',
'trusted_large_object_space',
- 'trusted_space'
+ 'trusted_space',
];
diff --git a/patches/node/win_almost_fix_race_detecting_esrch_in_uv_kill.patch b/patches/node/win_almost_fix_race_detecting_esrch_in_uv_kill.patch
new file mode 100644
index 0000000000..4a210d885a
--- /dev/null
+++ b/patches/node/win_almost_fix_race_detecting_esrch_in_uv_kill.patch
@@ -0,0 +1,70 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: Santiago Gimeno <[email protected]>
+Date: Tue, 5 Mar 2024 14:54:59 +0100
+Subject: win: almost fix race detecting ESRCH in uv_kill
+
+It might happen that only using `WaitForSingleObject()` with timeout 0
+could return WAIT_TIMEOUT as the process might not have been signaled
+yet. To improve things, first use `GetExitCodeProcess()` and check
+that `status` is not `STILL_ACTIVE`. Then, to cover for the case that the exit
+code was actually `STILL_ACTIVE` use `WaitForSingleObject()`. This could
+still be prone to the race condition but only for that case.
+
+diff --git a/deps/uv/src/win/process.c b/deps/uv/src/win/process.c
+index 4e94dee90e13eede63d8e97ddc9992726f874ea9..f46f34289e8e7d3a2af914d89e6164b751a3e47d 100644
+--- a/deps/uv/src/win/process.c
++++ b/deps/uv/src/win/process.c
+@@ -1308,16 +1308,34 @@ static int uv__kill(HANDLE process_handle, int signum) {
+ /* Unconditionally terminate the process. On Windows, killed processes
+ * normally return 1. */
+ int err;
++ DWORD status;
+
+ if (TerminateProcess(process_handle, 1))
+ return 0;
+
+- /* If the process already exited before TerminateProcess was called,.
++ /* If the process already exited before TerminateProcess was called,
+ * TerminateProcess will fail with ERROR_ACCESS_DENIED. */
+ err = GetLastError();
+- if (err == ERROR_ACCESS_DENIED &&
+- WaitForSingleObject(process_handle, 0) == WAIT_OBJECT_0) {
+- return UV_ESRCH;
++ if (err == ERROR_ACCESS_DENIED) {
++ /* First check using GetExitCodeProcess() with status different from
++ * STILL_ACTIVE (259). This check can be set incorrectly by the process,
++ * though that is uncommon. */
++ if (GetExitCodeProcess(process_handle, &status) &&
++ status != STILL_ACTIVE) {
++ return UV_ESRCH;
++ }
++
++ /* But the process could have exited with code == STILL_ACTIVE, use then
++ * WaitForSingleObject with timeout zero. This is prone to a race
++ * condition as it could return WAIT_TIMEOUT because the handle might
++ * not have been signaled yet.That would result in returning the wrong
++ * error code here (UV_EACCES instead of UV_ESRCH), but we cannot fix
++ * the kernel synchronization issue that TerminateProcess is
++ * inconsistent with WaitForSingleObject with just the APIs available to
++ * us in user space. */
++ if (WaitForSingleObject(process_handle, 0) == WAIT_OBJECT_0) {
++ return UV_ESRCH;
++ }
+ }
+
+ return uv_translate_sys_error(err);
+@@ -1325,6 +1343,14 @@ static int uv__kill(HANDLE process_handle, int signum) {
+
+ case 0: {
+ /* Health check: is the process still alive? */
++ DWORD status;
++
++ if (!GetExitCodeProcess(process_handle, &status))
++ return uv_translate_sys_error(GetLastError());
++
++ if (status != STILL_ACTIVE)
++ return UV_ESRCH;
++
+ switch (WaitForSingleObject(process_handle, 0)) {
+ case WAIT_OBJECT_0:
+ return UV_ESRCH;
diff --git a/patches/node/win_process_avoid_assert_after_spawning_store_app_4152.patch b/patches/node/win_process_avoid_assert_after_spawning_store_app_4152.patch
deleted file mode 100644
index ff3ed47f1d..0000000000
--- a/patches/node/win_process_avoid_assert_after_spawning_store_app_4152.patch
+++ /dev/null
@@ -1,85 +0,0 @@
-From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
-From: Jameson Nash <[email protected]>
-Date: Mon, 2 Oct 2023 15:15:18 +0200
-Subject: win,process: avoid assert after spawning Store app (#4152)
-
-Make sure this handle is functional. The Windows kernel seems to have a
-bug that if the first use of AssignProcessToJobObject is for a Windows
-Store program, subsequent attempts to use the handle with fail with
-INVALID_PARAMETER (87). This is possilby because all uses of the handle
-must be for the same Terminal Services session. We can ensure it is
-tied to our current session now by adding ourself to it. We could
-remove ourself afterwards, but there doesn't seem to be a reason to.
-
-Secondly, we start the process suspended so that we can make sure we
-added it to the job control object before it does anything itself (such
-as launch more jobs or exit).
-
-Fixes: https://github.com/JuliaLang/julia/issues/51461
-
-diff --git a/deps/uv/src/win/process.c b/deps/uv/src/win/process.c
-index 3e451e2291d6ed200ec258e874becbbea22bbc27..a71a08bdd60166ef1d4ef490ff3e083b44188852 100644
---- a/deps/uv/src/win/process.c
-+++ b/deps/uv/src/win/process.c
-@@ -105,6 +105,21 @@ static void uv__init_global_job_handle(void) {
- &info,
- sizeof info))
- uv_fatal_error(GetLastError(), "SetInformationJobObject");
-+
-+
-+ if (!AssignProcessToJobObject(uv_global_job_handle_, GetCurrentProcess())) {
-+ /* Make sure this handle is functional. The Windows kernel has a bug that
-+ * if the first use of AssignProcessToJobObject is for a Windows Store
-+ * program, subsequent attempts to use the handle with fail with
-+ * INVALID_PARAMETER (87). This is possibly because all uses of the handle
-+ * must be for the same Terminal Services session. We can ensure it is tied
-+ * to our current session now by adding ourself to it. We could remove
-+ * ourself afterwards, but there doesn't seem to be a reason to.
-+ */
-+ DWORD err = GetLastError();
-+ if (err != ERROR_ACCESS_DENIED)
-+ uv_fatal_error(err, "AssignProcessToJobObject");
-+ }
- }
-
-
-@@ -1102,6 +1117,7 @@ int uv_spawn(uv_loop_t* loop,
- * breakaway.
- */
- process_flags |= DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP;
-+ process_flags |= CREATE_SUSPENDED;
- }
-
- if (!CreateProcessW(application_path,
-@@ -1119,11 +1135,6 @@ int uv_spawn(uv_loop_t* loop,
- goto done;
- }
-
-- /* Spawn succeeded. Beyond this point, failure is reported asynchronously. */
--
-- process->process_handle = info.hProcess;
-- process->pid = info.dwProcessId;
--
- /* If the process isn't spawned as detached, assign to the global job object
- * so windows will kill it when the parent process dies. */
- if (!(options->flags & UV_PROCESS_DETACHED)) {
-@@ -1146,6 +1157,19 @@ int uv_spawn(uv_loop_t* loop,
- }
- }
-
-+ if (process_flags & CREATE_SUSPENDED) {
-+ if (ResumeThread(info.hThread) == ((DWORD)-1)) {
-+ err = GetLastError();
-+ TerminateProcess(info.hProcess, 1);
-+ goto done;
-+ }
-+ }
-+
-+ /* Spawn succeeded. Beyond this point, failure is reported asynchronously. */
-+
-+ process->process_handle = info.hProcess;
-+ process->pid = info.dwProcessId;
-+
- /* Set IPC pid to all IPC pipes. */
- for (i = 0; i < options->stdio_count; i++) {
- const uv_stdio_container_t* fdopt = &options->stdio[i];
diff --git a/patches/sqlite/.patches b/patches/sqlite/.patches
new file mode 100644
index 0000000000..ce35559581
--- /dev/null
+++ b/patches/sqlite/.patches
@@ -0,0 +1 @@
+fix_rename_sqlite_win32_exports_to_avoid_conflicts_with_node_js.patch
diff --git a/patches/sqlite/fix_rename_sqlite_win32_exports_to_avoid_conflicts_with_node_js.patch b/patches/sqlite/fix_rename_sqlite_win32_exports_to_avoid_conflicts_with_node_js.patch
new file mode 100644
index 0000000000..0978319495
--- /dev/null
+++ b/patches/sqlite/fix_rename_sqlite_win32_exports_to_avoid_conflicts_with_node_js.patch
@@ -0,0 +1,31 @@
+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
+From: Shelley Vohr <[email protected]>
+Date: Sun, 27 Oct 2024 21:01:11 +0100
+Subject: fix: rename sqlite win32 exports to avoid conflicts with Node.js
+
+As of https://github.com/nodejs/node/pull/53752, a number of symbols
+exported by SQLite are now exported by Node.js. This change renames
+the exported symbols in SQLite to avoid conflicts with Node.js.
+
+This should be upstreamed to SQLite.
+
+diff --git a/amalgamation/rename_exports.h b/amalgamation/rename_exports.h
+index b1c485159a624ea1bfbec603aabc58074721e72a..8eb71ae67acc3e0ad17bae2e87e85bf12c10b9af 100644
+--- a/amalgamation/rename_exports.h
++++ b/amalgamation/rename_exports.h
+@@ -367,6 +367,15 @@
+ #define sqlite3session_patchset chrome_sqlite3session_patchset // Lines 11449-11453
+ #define sqlite3session_patchset_strm chrome_sqlite3session_patchset_strm // Lines 12728-12732
+ #define sqlite3session_table_filter chrome_sqlite3session_table_filter // Lines 11219-11226
++#define sqlite3_win32_write_debug chrome_sqlite3_win32_write_debug
++#define sqlite3_win32_sleep chrome_sqlite3_win32_sleep
++#define sqlite3_win32_is_nt chrome_sqlite3_win32_is_nt
++#define sqlite3_win32_utf8_to_unicode chrome_sqlite3_win32_utf8_to_unicode
++#define sqlite3_win32_unicode_to_utf8 chrome_sqlite3_win32_unicode_to_utf8
++#define sqlite3_win32_mbcs_to_utf8 chrome_sqlite3_win32_mbcs_to_utf8
++#define sqlite3_win32_utf8_to_mbcs_v2 chrome_sqlite3_win32_utf8_to_mbcs_v2
++#define sqlite3_win32_utf8_to_mbcs chrome_sqlite3_win32_utf8_to_mbcs
++#define sqlite3_win32_mbcs_to_utf8_v2 chrome_sqlite3_win32_mbcs_to_utf8_v2
+
+ #endif // THIRD_PARTY_SQLITE_AMALGAMATION_RENAME_EXPORTS_H_
+
diff --git a/script/node-disabled-tests.json b/script/node-disabled-tests.json
index e14cf2394a..e967f2e10c 100644
--- a/script/node-disabled-tests.json
+++ b/script/node-disabled-tests.json
@@ -1,12 +1,14 @@
[
"abort/test-abort-backtrace",
"es-module/test-vm-compile-function-lineoffset",
+ "parallel/test-async-context-frame",
"parallel/test-bootstrap-modules",
"parallel/test-child-process-fork-exec-path",
"parallel/test-code-cache",
"parallel/test-cluster-primary-error",
"parallel/test-cluster-primary-kill",
"parallel/test-crypto-aes-wrap",
+ "parallel/test-crypto-authenticated",
"parallel/test-crypto-authenticated-stream",
"parallel/test-crypto-des3-wrap",
"parallel/test-crypto-dh-group-setters",
@@ -35,6 +37,7 @@
"parallel/test-inspector-port-zero-cluster",
"parallel/test-inspector-tracing-domain",
"parallel/test-module-loading-globalpaths",
+ "parallel/test-module-print-timing",
"parallel/test-openssl-ca-options",
"parallel/test-process-versions",
"parallel/test-process-get-builtin",
@@ -60,6 +63,7 @@
"parallel/test-snapshot-incompatible",
"parallel/test-snapshot-namespaced-builtin",
"parallel/test-snapshot-net",
+ "parallel/test-snapshot-reproducible",
"parallel/test-snapshot-typescript",
"parallel/test-snapshot-umd",
"parallel/test-snapshot-warning",
diff --git a/shell/app/node_main.cc b/shell/app/node_main.cc
index 8db8d80c14..782357ac37 100644
--- a/shell/app/node_main.cc
+++ b/shell/app/node_main.cc
@@ -183,7 +183,7 @@ int NodeMain() {
const std::vector<std::string> args = ElectronCommandLine::AsUtf8();
ExitIfContainsDisallowedFlags(args);
- std::unique_ptr<node::InitializationResult> result =
+ std::shared_ptr<node::InitializationResult> result =
node::InitializeOncePerProcess(
args,
{node::ProcessInitializationFlags::kNoInitializeV8,
diff --git a/shell/browser/file_system_access/file_system_access_permission_context.cc b/shell/browser/file_system_access/file_system_access_permission_context.cc
index 4addf43708..6e8d360982 100644
--- a/shell/browser/file_system_access/file_system_access_permission_context.cc
+++ b/shell/browser/file_system_access/file_system_access_permission_context.cc
@@ -165,8 +165,10 @@ bool ShouldBlockAccessToPath(const base::FilePath& path,
ChromeFileSystemAccessPermissionContext::kBlockedPaths) {
if (key == ChromeFileSystemAccessPermissionContext::kNoBasePathKey) {
rules.emplace_back(base::FilePath{rule_path}, type);
- } else if (base::FilePath path; base::PathService::Get(key, &path)) {
- rules.emplace_back(rule_path ? path.Append(rule_path) : path, type);
+ } else if (base::FilePath block_path;
+ base::PathService::Get(key, &block_path)) {
+ rules.emplace_back(rule_path ? block_path.Append(rule_path) : block_path,
+ type);
}
}
diff --git a/shell/common/node_bindings.cc b/shell/common/node_bindings.cc
index b2b94d89e0..5a0aaa6e96 100644
--- a/shell/common/node_bindings.cc
+++ b/shell/common/node_bindings.cc
@@ -568,7 +568,7 @@ void NodeBindings::Initialize(v8::Local<v8::Context> context) {
if (!fuses::IsNodeOptionsEnabled())
process_flags |= node::ProcessInitializationFlags::kDisableNodeOptionsEnv;
- std::unique_ptr<node::InitializationResult> result =
+ std::shared_ptr<node::InitializationResult> result =
node::InitializeOncePerProcess(
args,
static_cast<node::ProcessInitializationFlags::Flags>(process_flags));
diff --git a/spec/api-utility-process-spec.ts b/spec/api-utility-process-spec.ts
index b17a6f70a8..9e2dad10df 100644
--- a/spec/api-utility-process-spec.ts
+++ b/spec/api-utility-process-spec.ts
@@ -510,7 +510,8 @@ describe('utilityProcess module', () => {
expect(output).to.equal(result);
});
- it('does not inherit parent env when custom env is provided', async () => {
+ // TODO(codebytere): figure out why this is failing in ASAN- builds on Linux.
+ ifit(!process.env.IS_ASAN)('does not inherit parent env when custom env is provided', async () => {
const appProcess = childProcess.spawn(process.execPath, [path.join(fixturesPath, 'env-app'), '--create-custom-env'], {
env: {
FROM: 'parent',
diff --git a/spec/fixtures/native-addon/external-ab/binding.cc b/spec/fixtures/native-addon/external-ab/binding.cc
index 277e13f97e..df1d52546c 100644
--- a/spec/fixtures/native-addon/external-ab/binding.cc
+++ b/spec/fixtures/native-addon/external-ab/binding.cc
@@ -1,5 +1,4 @@
#include <node_api.h>
-#undef NAPI_VERSION
#include <node_buffer.h>
#include <v8.h>
diff --git a/spec/lib/events-helpers.ts b/spec/lib/events-helpers.ts
index 2eca91da38..ead2cb5539 100644
--- a/spec/lib/events-helpers.ts
+++ b/spec/lib/events-helpers.ts
@@ -20,4 +20,5 @@ export const emittedUntil = async (emitter: NodeJS.EventEmitter, eventName: stri
for await (const args of on(emitter, eventName)) {
if (untilFn(...args)) { return args; }
}
+ return [];
};
diff --git a/yarn.lock b/yarn.lock
index f7dc46f92f..cac51c4a3f 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -997,12 +997,12 @@
dependencies:
undici-types "~6.19.2"
-"@types/node@^20.9.0":
- version "20.9.0"
- resolved "https://registry.yarnpkg.com/@types/node/-/node-20.9.0.tgz#bfcdc230583aeb891cf51e73cfdaacdd8deae298"
- integrity sha512-nekiGu2NDb1BcVofVcEKMIwzlx4NjHlcjhoxxKBNLtz15Y1z7MYf549DFvkHSId02Ax6kGwWntIBPC3l/JZcmw==
+"@types/node@^22.7.7":
+ version "22.7.7"
+ resolved "https://registry.yarnpkg.com/@types/node/-/node-22.7.7.tgz#6cd9541c3dccb4f7e8b141b491443f4a1570e307"
+ integrity sha512-SRxCrrg9CL/y54aiMCG3edPKdprgMVGDXjA3gB8UmmBW5TcXzRUYAh8EWzTnSJFAd1rgImPELza+A3bJ+qxz8Q==
dependencies:
- undici-types "~5.26.4"
+ undici-types "~6.19.2"
"@types/normalize-package-data@^2.4.0":
version "2.4.1"
@@ -7042,14 +7042,7 @@ stringify-object@^3.3.0:
is-obj "^1.0.1"
is-regexp "^1.0.0"
-"strip-ansi-cjs@npm:strip-ansi@^6.0.1":
- version "6.0.1"
- resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-6.0.1.tgz#9e26c63d30f53443e9489495b2105d37b67a85d9"
- integrity sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==
- dependencies:
- ansi-regex "^5.0.1"
-
-strip-ansi@^6.0.0, strip-ansi@^6.0.1:
+"strip-ansi-cjs@npm:strip-ansi@^6.0.1", strip-ansi@^6.0.0, strip-ansi@^6.0.1:
version "6.0.1"
resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-6.0.1.tgz#9e26c63d30f53443e9489495b2105d37b67a85d9"
integrity sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==
@@ -7441,11 +7434,6 @@ unbox-primitive@^1.0.2:
has-symbols "^1.0.3"
which-boxed-primitive "^1.0.2"
-undici-types@~5.26.4:
- version "5.26.5"
- resolved "https://registry.yarnpkg.com/undici-types/-/undici-types-5.26.5.tgz#bcd539893d00b56e964fd2657a4866b221a65617"
- integrity sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==
-
undici-types@~6.19.2:
version "6.19.8"
resolved "https://registry.yarnpkg.com/undici-types/-/undici-types-6.19.8.tgz#35111c9d1437ab83a7cdc0abae2f26d88eda0a02"
|
chore
|
c2c64d27fd2e96064b648128967d25436fb04de1
|
David Sanders
|
2024-01-10 04:25:11
|
ci: fix missing inputs for release project board automation (#40726)
|
diff --git a/.github/workflows/branch-created.yml b/.github/workflows/branch-created.yml
index 8d4edfc1d8..2a0bf85694 100644
--- a/.github/workflows/branch-created.yml
+++ b/.github/workflows/branch-created.yml
@@ -116,8 +116,10 @@ jobs:
id: find-prev-release-board
with:
title: ${{ steps.generate-project-metadata.outputs.prev-prev-major }}-x-y
+ token: ${{ steps.generate-token.outputs.token }}
- name: Close Previous Release Project Board
if: ${{ steps.check-major-version.outputs.MAJOR }}
uses: dsanders11/project-actions/close-project@3a81985616963f32fae17d1d1b406c631f3201a1 # v1.1.0
with:
project-number: ${{ steps.find-prev-release-board.outputs.number }}
+ token: ${{ steps.generate-token.outputs.token }}
|
ci
|
1729a9868c9ca0fe6f68400296e1efc6fda3efd1
|
Shelley Vohr
|
2024-07-02 14:02:49
|
fix: use `BlockedRequest` struct to handle `webRequest` data (#42647)
Fixes an issue where Chromium could crash on a dangling unretained pointer in one of several webRequest functions. This was happening as a result of the fact that we had outstanding blocking requests continue to reference state owned by ProxyingWebsocket and ProxyingURLLoaderFactory after the requests were destroyed.
This had been going on for a few years, and was likely leading to some ongoing memory issues. To fix this, we need to ensure that all state is cleaned up in OnRequestWillBeDestroyed. I chose to create a new BlockedRequest struct to do so, which approximates the approach that upstream takes. The complexities of doing so also made our templated approach more trouble than it felt worth, so i pried that apart into separate handlers.
|
diff --git a/shell/browser/api/electron_api_web_request.cc b/shell/browser/api/electron_api_web_request.cc
index 2ffc346bbf..0ad852279a 100644
--- a/shell/browser/api/electron_api_web_request.cc
+++ b/shell/browser/api/electron_api_web_request.cc
@@ -185,37 +185,41 @@ void FillDetails(gin_helper::Dictionary* details, Arg arg, Args... args) {
FillDetails(details, args...);
}
-// Fill the native types with the result from the response object.
-void ReadFromResponse(v8::Isolate* isolate,
- gin::Dictionary* response,
- GURL* new_location) {
- response->Get("redirectURL", new_location);
-}
-
-void ReadFromResponse(v8::Isolate* isolate,
- gin::Dictionary* response,
- net::HttpRequestHeaders* headers) {
- v8::Local<v8::Value> value;
- if (response->Get("requestHeaders", &value) && value->IsObject()) {
- headers->Clear();
- gin::Converter<net::HttpRequestHeaders>::FromV8(isolate, value, headers);
- }
-}
+// Modified from extensions/browser/api/web_request/web_request_api_helpers.cc.
+std::pair<std::set<std::string>, std::set<std::string>>
+CalculateOnBeforeSendHeadersDelta(const net::HttpRequestHeaders* old_headers,
+ const net::HttpRequestHeaders* new_headers) {
+ // Newly introduced or overridden request headers.
+ std::set<std::string> modified_request_headers;
+ // Keys of request headers to be deleted.
+ std::set<std::string> deleted_request_headers;
+
+ // The event listener might not have passed any new headers if it
+ // just wanted to cancel the request.
+ if (new_headers) {
+ // Find deleted headers.
+ {
+ net::HttpRequestHeaders::Iterator i(*old_headers);
+ while (i.GetNext()) {
+ if (!new_headers->HasHeader(i.name())) {
+ deleted_request_headers.insert(i.name());
+ }
+ }
+ }
-void ReadFromResponse(v8::Isolate* isolate,
- gin::Dictionary* response,
- const std::pair<scoped_refptr<net::HttpResponseHeaders>*,
- const std::string>& headers) {
- std::string status_line;
- if (!response->Get("statusLine", &status_line))
- status_line = headers.second;
- v8::Local<v8::Value> value;
- if (response->Get("responseHeaders", &value) && value->IsObject()) {
- *headers.first = new net::HttpResponseHeaders("");
- (*headers.first)->ReplaceStatusLine(status_line);
- gin::Converter<net::HttpResponseHeaders*>::FromV8(isolate, value,
- (*headers.first).get());
+ // Find modified headers.
+ {
+ net::HttpRequestHeaders::Iterator i(*new_headers);
+ while (i.GetNext()) {
+ std::string value;
+ if (!old_headers->GetHeader(i.name(), &value) || i.value() != value) {
+ modified_request_headers.insert(i.name());
+ }
+ }
+ }
}
+
+ return std::make_pair(modified_request_headers, deleted_request_headers);
}
} // namespace
@@ -260,6 +264,24 @@ bool WebRequest::RequestFilter::MatchesRequest(
return MatchesURL(info->url) && MatchesType(info->web_request_type);
}
+struct WebRequest::BlockedRequest {
+ BlockedRequest() = default;
+ raw_ptr<const extensions::WebRequestInfo> request = nullptr;
+ net::CompletionOnceCallback callback;
+ // Only used for onBeforeSendHeaders.
+ BeforeSendHeadersCallback before_send_headers_callback;
+ // Only used for onBeforeSendHeaders.
+ raw_ptr<net::HttpRequestHeaders> request_headers = nullptr;
+ // Only used for onHeadersReceived.
+ scoped_refptr<const net::HttpResponseHeaders> original_response_headers;
+ // Only used for onHeadersReceived.
+ raw_ptr<scoped_refptr<net::HttpResponseHeaders>> override_response_headers =
+ nullptr;
+ std::string status_line;
+ // Only used for onBeforeRequest.
+ raw_ptr<GURL> new_url = nullptr;
+};
+
WebRequest::SimpleListenerInfo::SimpleListenerInfo(RequestFilter filter_,
SimpleListener listener_)
: filter(std::move(filter_)), listener(listener_) {}
@@ -320,19 +342,152 @@ int WebRequest::OnBeforeRequest(extensions::WebRequestInfo* info,
const network::ResourceRequest& request,
net::CompletionOnceCallback callback,
GURL* new_url) {
- return HandleResponseEvent(ResponseEvent::kOnBeforeRequest, info,
- std::move(callback), new_url, request);
+ return HandleOnBeforeRequestResponseEvent(info, request, std::move(callback),
+ new_url);
+}
+
+int WebRequest::HandleOnBeforeRequestResponseEvent(
+ extensions::WebRequestInfo* request_info,
+ const network::ResourceRequest& request,
+ net::CompletionOnceCallback callback,
+ GURL* new_url) {
+ const auto iter = response_listeners_.find(ResponseEvent::kOnBeforeRequest);
+ if (iter == std::end(response_listeners_))
+ return net::OK;
+
+ const auto& info = iter->second;
+ if (!info.filter.MatchesRequest(request_info))
+ return net::OK;
+
+ BlockedRequest blocked_request;
+ blocked_request.callback = std::move(callback);
+ blocked_request.new_url = new_url;
+ blocked_requests_[request_info->id] = std::move(blocked_request);
+
+ v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
+ v8::HandleScope handle_scope(isolate);
+ gin_helper::Dictionary details(isolate, v8::Object::New(isolate));
+ FillDetails(&details, request_info, request, *new_url);
+
+ ResponseCallback response =
+ base::BindOnce(&WebRequest::OnBeforeRequestListenerResult,
+ base::Unretained(this), request_info->id);
+ info.listener.Run(gin::ConvertToV8(isolate, details), std::move(response));
+ return net::ERR_IO_PENDING;
+}
+
+void WebRequest::OnBeforeRequestListenerResult(uint64_t id,
+ v8::Local<v8::Value> response) {
+ const auto iter = blocked_requests_.find(id);
+ if (iter == std::end(blocked_requests_))
+ return;
+
+ auto& request = iter->second;
+
+ int result = net::OK;
+ if (response->IsObject()) {
+ v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
+ gin::Dictionary dict(isolate, response.As<v8::Object>());
+
+ bool cancel = false;
+ dict.Get("cancel", &cancel);
+ if (cancel) {
+ result = net::ERR_BLOCKED_BY_CLIENT;
+ } else {
+ dict.Get("redirectURL", request.new_url.get());
+ }
+ }
+
+ base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
+ FROM_HERE, base::BindOnce(std::move(request.callback), result));
+ blocked_requests_.erase(iter);
}
int WebRequest::OnBeforeSendHeaders(extensions::WebRequestInfo* info,
const network::ResourceRequest& request,
BeforeSendHeadersCallback callback,
net::HttpRequestHeaders* headers) {
- return HandleResponseEvent(
- ResponseEvent::kOnBeforeSendHeaders, info,
- base::BindOnce(std::move(callback), std::set<std::string>(),
- std::set<std::string>()),
- headers, request, *headers);
+ return HandleOnBeforeSendHeadersResponseEvent(info, request,
+ std::move(callback), headers);
+}
+
+int WebRequest::HandleOnBeforeSendHeadersResponseEvent(
+ extensions::WebRequestInfo* request_info,
+ const network::ResourceRequest& request,
+ BeforeSendHeadersCallback callback,
+ net::HttpRequestHeaders* headers) {
+ const auto iter =
+ response_listeners_.find(ResponseEvent::kOnBeforeSendHeaders);
+ if (iter == std::end(response_listeners_))
+ return net::OK;
+
+ const auto& info = iter->second;
+ if (!info.filter.MatchesRequest(request_info))
+ return net::OK;
+
+ BlockedRequest blocked_request;
+ blocked_request.before_send_headers_callback = std::move(callback);
+ blocked_request.request_headers = headers;
+ blocked_requests_[request_info->id] = std::move(blocked_request);
+
+ v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
+ v8::HandleScope handle_scope(isolate);
+ gin_helper::Dictionary details(isolate, v8::Object::New(isolate));
+ FillDetails(&details, request_info, request, *headers);
+
+ ResponseCallback response =
+ base::BindOnce(&WebRequest::OnBeforeSendHeadersListenerResult,
+ base::Unretained(this), request_info->id);
+ info.listener.Run(gin::ConvertToV8(isolate, details), std::move(response));
+ return net::ERR_IO_PENDING;
+}
+
+void WebRequest::OnBeforeSendHeadersListenerResult(
+ uint64_t id,
+ v8::Local<v8::Value> response) {
+ const auto iter = blocked_requests_.find(id);
+ if (iter == std::end(blocked_requests_))
+ return;
+
+ auto& request = iter->second;
+
+ net::HttpRequestHeaders* old_headers = request.request_headers;
+ net::HttpRequestHeaders new_headers;
+
+ int result = net::OK;
+ bool user_modified_headers = false;
+ if (response->IsObject()) {
+ v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
+ gin::Dictionary dict(isolate, response.As<v8::Object>());
+
+ bool cancel = false;
+ dict.Get("cancel", &cancel);
+ if (cancel) {
+ result = net::ERR_BLOCKED_BY_CLIENT;
+ } else {
+ v8::Local<v8::Value> value;
+ if (dict.Get("requestHeaders", &value) && value->IsObject()) {
+ user_modified_headers = true;
+ gin::Converter<net::HttpRequestHeaders>::FromV8(isolate, value,
+ &new_headers);
+ }
+ }
+ }
+
+ // If the user passes |cancel|, |new_headers| should be nullptr.
+ const auto updated_headers = CalculateOnBeforeSendHeadersDelta(
+ old_headers,
+ result == net::ERR_BLOCKED_BY_CLIENT ? nullptr : &new_headers);
+
+ // Leave |request.request_headers| unchanged if the user didn't modify it.
+ if (user_modified_headers)
+ request.request_headers->Swap(&new_headers);
+
+ base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
+ FROM_HERE,
+ base::BindOnce(std::move(request.before_send_headers_callback),
+ updated_headers.first, updated_headers.second, result));
+ blocked_requests_.erase(iter);
}
int WebRequest::OnHeadersReceived(
@@ -342,12 +497,86 @@ int WebRequest::OnHeadersReceived(
const net::HttpResponseHeaders* original_response_headers,
scoped_refptr<net::HttpResponseHeaders>* override_response_headers,
GURL* allowed_unsafe_redirect_url) {
- const std::string& status_line =
- original_response_headers ? original_response_headers->GetStatusLine()
- : std::string();
- return HandleResponseEvent(
- ResponseEvent::kOnHeadersReceived, info, std::move(callback),
- std::make_pair(override_response_headers, status_line), request);
+ return HandleOnHeadersReceivedResponseEvent(
+ info, request, std::move(callback), original_response_headers,
+ override_response_headers);
+}
+
+int WebRequest::HandleOnHeadersReceivedResponseEvent(
+ extensions::WebRequestInfo* request_info,
+ const network::ResourceRequest& request,
+ net::CompletionOnceCallback callback,
+ const net::HttpResponseHeaders* original_response_headers,
+ scoped_refptr<net::HttpResponseHeaders>* override_response_headers) {
+ const auto iter = response_listeners_.find(ResponseEvent::kOnHeadersReceived);
+ if (iter == std::end(response_listeners_))
+ return net::OK;
+
+ const auto& info = iter->second;
+ if (!info.filter.MatchesRequest(request_info))
+ return net::OK;
+
+ BlockedRequest blocked_request;
+ blocked_request.callback = std::move(callback);
+ blocked_request.override_response_headers = override_response_headers;
+ blocked_request.status_line = original_response_headers
+ ? original_response_headers->GetStatusLine()
+ : std::string();
+ blocked_requests_[request_info->id] = std::move(blocked_request);
+
+ v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
+ v8::HandleScope handle_scope(isolate);
+ gin_helper::Dictionary details(isolate, v8::Object::New(isolate));
+ FillDetails(&details, request_info, request);
+
+ ResponseCallback response =
+ base::BindOnce(&WebRequest::OnHeadersReceivedListenerResult,
+ base::Unretained(this), request_info->id);
+ info.listener.Run(gin::ConvertToV8(isolate, details), std::move(response));
+ return net::ERR_IO_PENDING;
+}
+
+void WebRequest::OnHeadersReceivedListenerResult(
+ uint64_t id,
+ v8::Local<v8::Value> response) {
+ const auto iter = blocked_requests_.find(id);
+ if (iter == std::end(blocked_requests_))
+ return;
+
+ auto& request = iter->second;
+
+ int result = net::OK;
+ bool user_modified_headers = false;
+ scoped_refptr<net::HttpResponseHeaders> override_headers(
+ new net::HttpResponseHeaders(""));
+ if (response->IsObject()) {
+ v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
+ gin::Dictionary dict(isolate, response.As<v8::Object>());
+
+ bool cancel = false;
+ dict.Get("cancel", &cancel);
+ if (cancel) {
+ result = net::ERR_BLOCKED_BY_CLIENT;
+ } else {
+ std::string status_line;
+ if (!dict.Get("statusLine", &status_line))
+ status_line = request.status_line;
+ v8::Local<v8::Value> value;
+ if (dict.Get("responseHeaders", &value) && value->IsObject()) {
+ user_modified_headers = true;
+ override_headers->ReplaceStatusLine(status_line);
+ gin::Converter<net::HttpResponseHeaders*>::FromV8(
+ isolate, value, override_headers.get());
+ }
+ }
+ }
+
+ if (user_modified_headers)
+ request.override_response_headers->swap(override_headers);
+
+ base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
+ FROM_HERE, base::BindOnce(std::move(request.callback), result));
+ blocked_requests_.erase(iter);
}
void WebRequest::OnSendHeaders(extensions::WebRequestInfo* info,
@@ -371,7 +600,7 @@ void WebRequest::OnResponseStarted(extensions::WebRequestInfo* info,
void WebRequest::OnErrorOccurred(extensions::WebRequestInfo* info,
const network::ResourceRequest& request,
int net_error) {
- callbacks_.erase(info->id);
+ blocked_requests_.erase(info->id);
HandleSimpleEvent(SimpleEvent::kOnErrorOccurred, info, request, net_error);
}
@@ -379,13 +608,13 @@ void WebRequest::OnErrorOccurred(extensions::WebRequestInfo* info,
void WebRequest::OnCompleted(extensions::WebRequestInfo* info,
const network::ResourceRequest& request,
int net_error) {
- callbacks_.erase(info->id);
+ blocked_requests_.erase(info->id);
HandleSimpleEvent(SimpleEvent::kOnCompleted, info, request, net_error);
}
void WebRequest::OnRequestWillBeDestroyed(extensions::WebRequestInfo* info) {
- callbacks_.erase(info->id);
+ blocked_requests_.erase(info->id);
}
template <WebRequest::SimpleEvent event>
@@ -479,62 +708,6 @@ void WebRequest::HandleSimpleEvent(SimpleEvent event,
info.listener.Run(gin::ConvertToV8(isolate, details));
}
-template <typename Out, typename... Args>
-int WebRequest::HandleResponseEvent(ResponseEvent event,
- extensions::WebRequestInfo* request_info,
- net::CompletionOnceCallback callback,
- Out out,
- Args... args) {
- const auto iter = response_listeners_.find(event);
- if (iter == std::end(response_listeners_))
- return net::OK;
-
- const auto& info = iter->second;
- if (!info.filter.MatchesRequest(request_info))
- return net::OK;
-
- callbacks_[request_info->id] = std::move(callback);
-
- v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
- v8::HandleScope handle_scope(isolate);
- gin_helper::Dictionary details(isolate, v8::Object::New(isolate));
- FillDetails(&details, request_info, args...);
-
- ResponseCallback response =
- base::BindOnce(&WebRequest::OnListenerResult<Out>, base::Unretained(this),
- request_info->id, out);
- info.listener.Run(gin::ConvertToV8(isolate, details), std::move(response));
- return net::ERR_IO_PENDING;
-}
-
-template <typename T>
-void WebRequest::OnListenerResult(uint64_t id,
- T out,
- v8::Local<v8::Value> response) {
- const auto iter = callbacks_.find(id);
- if (iter == std::end(callbacks_))
- return;
-
- int result = net::OK;
- if (response->IsObject()) {
- v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
- gin::Dictionary dict(isolate, response.As<v8::Object>());
-
- bool cancel = false;
- dict.Get("cancel", &cancel);
- if (cancel)
- result = net::ERR_BLOCKED_BY_CLIENT;
- else
- ReadFromResponse(isolate, &dict, out);
- }
-
- // The ProxyingURLLoaderFactory expects the callback to be executed
- // asynchronously, because it used to work on IO thread before NetworkService.
- base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
- FROM_HERE, base::BindOnce(std::move(callbacks_[id]), result));
- callbacks_.erase(iter);
-}
-
// static
gin::Handle<WebRequest> WebRequest::FromOrCreate(
v8::Isolate* isolate,
diff --git a/shell/browser/api/electron_api_web_request.h b/shell/browser/api/electron_api_web_request.h
index c11267b2fb..6444458535 100644
--- a/shell/browser/api/electron_api_web_request.h
+++ b/shell/browser/api/electron_api_web_request.h
@@ -84,6 +84,10 @@ class WebRequest : public gin::Wrappable<WebRequest>, public WebRequestAPI {
WebRequest(v8::Isolate* isolate, content::BrowserContext* browser_context);
~WebRequest() override;
+ // Contains info about requests that are blocked waiting for a response from
+ // the user.
+ struct BlockedRequest;
+
enum class SimpleEvent {
kOnSendHeaders,
kOnBeforeRedirect,
@@ -91,6 +95,7 @@ class WebRequest : public gin::Wrappable<WebRequest>, public WebRequestAPI {
kOnCompleted,
kOnErrorOccurred,
};
+
enum class ResponseEvent {
kOnBeforeRequest,
kOnBeforeSendHeaders,
@@ -113,15 +118,30 @@ class WebRequest : public gin::Wrappable<WebRequest>, public WebRequestAPI {
void HandleSimpleEvent(SimpleEvent event,
extensions::WebRequestInfo* info,
Args... args);
- template <typename Out, typename... Args>
- int HandleResponseEvent(ResponseEvent event,
- extensions::WebRequestInfo* info,
- net::CompletionOnceCallback callback,
- Out out,
- Args... args);
- template <typename T>
- void OnListenerResult(uint64_t id, T out, v8::Local<v8::Value> response);
+ int HandleOnBeforeRequestResponseEvent(
+ extensions::WebRequestInfo* info,
+ const network::ResourceRequest& request,
+ net::CompletionOnceCallback callback,
+ GURL* redirect_url);
+ int HandleOnBeforeSendHeadersResponseEvent(
+ extensions::WebRequestInfo* info,
+ const network::ResourceRequest& request,
+ BeforeSendHeadersCallback callback,
+ net::HttpRequestHeaders* headers);
+ int HandleOnHeadersReceivedResponseEvent(
+ extensions::WebRequestInfo* info,
+ const network::ResourceRequest& request,
+ net::CompletionOnceCallback callback,
+ const net::HttpResponseHeaders* original_response_headers,
+ scoped_refptr<net::HttpResponseHeaders>* override_response_headers);
+
+ void OnBeforeRequestListenerResult(uint64_t id,
+ v8::Local<v8::Value> response);
+ void OnBeforeSendHeadersListenerResult(uint64_t id,
+ v8::Local<v8::Value> response);
+ void OnHeadersReceivedListenerResult(uint64_t id,
+ v8::Local<v8::Value> response);
class RequestFilter {
public:
@@ -164,7 +184,7 @@ class WebRequest : public gin::Wrappable<WebRequest>, public WebRequestAPI {
std::map<SimpleEvent, SimpleListenerInfo> simple_listeners_;
std::map<ResponseEvent, ResponseListenerInfo> response_listeners_;
- std::map<uint64_t, net::CompletionOnceCallback> callbacks_;
+ std::map<uint64_t, BlockedRequest> blocked_requests_;
// Weak-ref, it manages us.
raw_ptr<content::BrowserContext> browser_context_;
diff --git a/spec/api-web-request-spec.ts b/spec/api-web-request-spec.ts
index 3afaba1cd9..e57c7a2063 100644
--- a/spec/api-web-request-spec.ts
+++ b/spec/api-web-request-spec.ts
@@ -328,7 +328,7 @@ describe('webRequest module', () => {
ses.webRequest.onBeforeSendHeaders((details, callback) => {
const requestHeaders = details.requestHeaders;
requestHeaders.Accept = '*/*;test/header';
- callback({ requestHeaders: requestHeaders });
+ callback({ requestHeaders });
});
const { data } = await ajax('no-cors://fake-host/redirect');
expect(data).to.equal('header-received');
@@ -341,7 +341,7 @@ describe('webRequest module', () => {
ses.webRequest.onBeforeSendHeaders((details, callback) => {
const requestHeaders = details.requestHeaders;
requestHeaders.Origin = 'http://new-origin';
- callback({ requestHeaders: requestHeaders });
+ callback({ requestHeaders });
});
const { data } = await ajax(defaultURL);
expect(data).to.equal('/new/origin');
|
fix
|
7f5364f98dd8d0b0baf4d6530ac23dbb5e2634df
|
Russell Carpenella
|
2023-05-03 08:52:02
|
docs: moves icpMain.handle call in tutorial part 3 (#38138)
|
diff --git a/docs/tutorial/tutorial-3-preload.md b/docs/tutorial/tutorial-3-preload.md
index 97c45780e3..2074d3c515 100644
--- a/docs/tutorial/tutorial-3-preload.md
+++ b/docs/tutorial/tutorial-3-preload.md
@@ -202,7 +202,7 @@ Then, set up your `handle` listener in the main process. We do this _before_
loading the HTML file so that the handler is guaranteed to be ready before
you send out the `invoke` call from the renderer.
-```js {1,12} title="main.js"
+```js {1,15} title="main.js"
const { app, BrowserWindow, ipcMain } = require('electron')
const path = require('path')
@@ -214,10 +214,12 @@ const createWindow = () => {
preload: path.join(__dirname, 'preload.js'),
},
})
- ipcMain.handle('ping', () => 'pong')
win.loadFile('index.html')
}
-app.whenReady().then(createWindow)
+app.whenReady().then(() => {
+ ipcMain.handle('ping', () => 'pong')
+ createWindow()
+})
```
Once you have the sender and receiver set up, you can now send messages from the renderer
|
docs
|
ee87438d28386ff2753923d1ed32db5ca72e706a
|
Milan Burda
|
2023-02-17 19:32:39
|
test: use async helpers to simplify tests (#37314)
test: use async helpers to simplify the tests
Co-authored-by: Milan Burda <[email protected]>
|
diff --git a/spec/api-browser-window-spec.ts b/spec/api-browser-window-spec.ts
index 5141f076f0..92bc1d29c3 100644
--- a/spec/api-browser-window-spec.ts
+++ b/spec/api-browser-window-spec.ts
@@ -62,7 +62,7 @@ describe('BrowserWindow module', () => {
ifit(process.platform === 'linux')('does not crash when setting large window icons', async () => {
const appPath = path.join(fixtures, 'apps', 'xwindow-icon');
const appProcess = childProcess.spawn(process.execPath, [appPath]);
- await new Promise((resolve) => { appProcess.once('exit', resolve); });
+ await emittedOnce(appProcess, 'exit');
});
it('does not crash or throw when passed an invalid icon', async () => {
diff --git a/spec/api-session-spec.ts b/spec/api-session-spec.ts
index 4a85649485..405c0819c7 100644
--- a/spec/api-session-spec.ts
+++ b/spec/api-session-spec.ts
@@ -291,7 +291,7 @@ describe('session module', () => {
expect(itemUrl).to.equal(url);
expect(itemFilename).to.equal('mockFile.txt');
// Delay till the next tick.
- await new Promise<void>(resolve => setImmediate(() => resolve()));
+ await new Promise(setImmediate);
expect(() => item.getURL()).to.throw('DownloadItem used after being destroyed');
});
});
diff --git a/spec/api-web-contents-spec.ts b/spec/api-web-contents-spec.ts
index a11e38ec5e..b6208b3d05 100644
--- a/spec/api-web-contents-spec.ts
+++ b/spec/api-web-contents-spec.ts
@@ -364,7 +364,7 @@ describe('webContents module', () => {
it('resolves when navigating within the page', async () => {
await w.loadFile(path.join(fixturesPath, 'pages', 'base-page.html'));
- await new Promise(resolve => setTimeout(resolve));
+ await delay();
await expect(w.loadURL(w.getURL() + '#foo')).to.eventually.be.fulfilled();
});
diff --git a/spec/api-web-frame-main-spec.ts b/spec/api-web-frame-main-spec.ts
index f666fc5b10..a55cb95b05 100644
--- a/spec/api-web-frame-main-spec.ts
+++ b/spec/api-web-frame-main-spec.ts
@@ -6,7 +6,7 @@ import { BrowserWindow, WebFrameMain, webFrameMain, ipcMain, app, WebContents }
import { closeAllWindows } from './lib/window-helpers';
import { emittedOnce, emittedNTimes } from './lib/events-helpers';
import { AddressInfo } from 'net';
-import { defer, ifit, waitUntil } from './lib/spec-helpers';
+import { defer, delay, ifit, waitUntil } from './lib/spec-helpers';
describe('webFrameMain module', () => {
const fixtures = path.resolve(__dirname, 'fixtures');
@@ -297,7 +297,7 @@ describe('webFrameMain module', () => {
const { mainFrame } = w.webContents;
w.destroy();
// Wait for WebContents, and thus RenderFrameHost, to be destroyed.
- await new Promise(resolve => setTimeout(resolve, 0));
+ await delay();
expect(() => mainFrame.url).to.throw();
});
@@ -338,7 +338,7 @@ describe('webFrameMain module', () => {
w.webContents.forcefullyCrashRenderer();
await crashEvent;
// A short wait seems to be required to reproduce the crash.
- await new Promise(resolve => setTimeout(resolve, 100));
+ await delay(100);
await w.webContents.loadURL(crossOriginUrl);
// Log just to keep mainFrame in scope.
console.log('mainFrame.url', mainFrame.url);
diff --git a/spec/chromium-spec.ts b/spec/chromium-spec.ts
index 013c5a1dd4..9b814ddec5 100644
--- a/spec/chromium-spec.ts
+++ b/spec/chromium-spec.ts
@@ -474,7 +474,7 @@ describe('command line switches', () => {
const stdio = appProcess.stdio as unknown as [NodeJS.ReadableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.WritableStream, NodeJS.ReadableStream];
const pipe = new PipeTransport(stdio[3], stdio[4]);
pipe.send({ id: 1, method: 'Browser.close', params: {} });
- await new Promise(resolve => { appProcess!.on('exit', resolve); });
+ await emittedOnce(appProcess, 'exit');
});
});
@@ -2658,7 +2658,7 @@ ifdescribe((process.platform !== 'linux' || app.isUnityRunning()))('navigator.se
async function waitForBadgeCount (value: number) {
let badgeCount = app.getBadgeCount();
while (badgeCount !== value) {
- await new Promise(resolve => setTimeout(resolve, 10));
+ await delay(10);
badgeCount = app.getBadgeCount();
}
return badgeCount;
diff --git a/spec/get-files.ts b/spec/get-files.ts
index 240a85bd18..3f3a15f817 100644
--- a/spec/get-files.ts
+++ b/spec/get-files.ts
@@ -1,4 +1,5 @@
import * as walkdir from 'walkdir';
+import { emittedOnce } from './lib/events-helpers';
export async function getFiles (directoryPath: string, { filter = null }: {filter?: ((file: string) => boolean) | null} = {}) {
const files: string[] = [];
@@ -8,6 +9,6 @@ export async function getFiles (directoryPath: string, { filter = null }: {filte
walker.on('file', (file) => {
if (!filter || filter(file)) { files.push(file); }
});
- await new Promise((resolve) => walker.on('end', resolve));
+ await emittedOnce(walker, 'end');
return files;
}
diff --git a/spec/modules-spec.ts b/spec/modules-spec.ts
index 7b639f228b..6870b2f57c 100644
--- a/spec/modules-spec.ts
+++ b/spec/modules-spec.ts
@@ -62,9 +62,7 @@ describe('modules support', () => {
ifit(features.isRunAsNodeEnabled())('can be required in node binary', async function () {
const child = childProcess.fork(path.join(fixtures, 'module', 'uv-dlopen.js'));
- const exitCode = await new Promise<number | null>(resolve => child.once('exit', (exitCode) => {
- resolve(exitCode);
- }));
+ const [exitCode] = await emittedOnce(child, 'exit');
expect(exitCode).to.equal(0);
});
});
diff --git a/spec/node-spec.ts b/spec/node-spec.ts
index df8b4f0cd3..f5808c9c10 100644
--- a/spec/node-spec.ts
+++ b/spec/node-spec.ts
@@ -104,7 +104,7 @@ describe('node feature', () => {
it('has the electron version in process.versions', async () => {
const source = 'process.send(process.versions)';
const forked = require('child_process').fork('--eval', [source]);
- const message = await new Promise(resolve => forked.once('message', resolve));
+ const [message] = await emittedOnce(forked, 'message');
expect(message)
.to.have.own.property('electron')
.that.is.a('string')
diff --git a/spec/webview-spec.ts b/spec/webview-spec.ts
index bd6cdb280d..362219a8a0 100644
--- a/spec/webview-spec.ts
+++ b/spec/webview-spec.ts
@@ -1774,6 +1774,14 @@ describe('<webview> tag', function () {
describe('<webview>.goForward()', () => {
useRemoteContext({ webPreferences: { webviewTag: true } });
itremote('should work after a replaced history entry', async (fixtures: string) => {
+ function waitForEvent (target: EventTarget, event: string) {
+ return new Promise<any>(resolve => target.addEventListener(event, resolve, { once: true }));
+ }
+
+ function waitForEvents (target: EventTarget, ...events: string[]) {
+ return Promise.all(events.map(event => waitForEvent(webview, event)));
+ }
+
const webview = new WebView();
webview.setAttribute('nodeintegration', 'on');
@@ -1782,10 +1790,7 @@ describe('<webview> tag', function () {
document.body.appendChild(webview);
{
- const [e] = await Promise.all([
- new Promise<any>(resolve => webview.addEventListener('ipc-message', resolve, { once: true })),
- new Promise<void>(resolve => webview.addEventListener('did-stop-loading', resolve, { once: true }))
- ]);
+ const [e] = await waitForEvents(webview, 'ipc-message', 'did-stop-loading');
expect(e.channel).to.equal('history');
expect(e.args[0]).to.equal(1);
expect(webview.canGoBack()).to.be.false();
@@ -1802,10 +1807,7 @@ describe('<webview> tag', function () {
webview.goBack();
{
- const [e] = await Promise.all([
- new Promise<any>(resolve => webview.addEventListener('ipc-message', resolve, { once: true })),
- new Promise<void>(resolve => webview.addEventListener('did-stop-loading', resolve, { once: true }))
- ]);
+ const [e] = await waitForEvents(webview, 'ipc-message', 'did-stop-loading');
expect(e.channel).to.equal('history');
expect(e.args[0]).to.equal(2);
expect(webview.canGoBack()).to.be.false();
|
test
|
fa3cd1747556b66a3e714f99e988e47334187e44
|
Jeremy Rose
|
2022-09-15 15:53:26
|
docs: reverse support matrix order (#35699)
|
diff --git a/docs/tutorial/electron-timelines.md b/docs/tutorial/electron-timelines.md
index 6af3e41815..d764964a8b 100644
--- a/docs/tutorial/electron-timelines.md
+++ b/docs/tutorial/electron-timelines.md
@@ -9,26 +9,26 @@ check out our [Electron Versioning](./electron-versioning.md) doc.
| Electron | Alpha | Beta | Stable | Chrome | Node | Supported |
| ------- | ----- | ------- | ------ | ------ | ---- | ---- |
-| 2.0.0 | -- | 2018-Feb-21 | 2018-May-01 | M61 | v8.9 | 🚫 |
-| 3.0.0 | -- | 2018-Jun-21 | 2018-Sep-18 | M66 | v10.2 | 🚫 |
-| 4.0.0 | -- | 2018-Oct-11 | 2018-Dec-20 | M69 | v10.11 | 🚫 |
-| 5.0.0 | -- | 2019-Jan-22 | 2019-Apr-24 | M73 | v12.0 | 🚫 |
-| 6.0.0 | -- | 2019-May-01 | 2019-Jul-30 | M76 | v12.4 | 🚫 |
-| 7.0.0 | -- | 2019-Aug-01 | 2019-Oct-22 | M78 | v12.8 | 🚫 |
-| 8.0.0 | -- | 2019-Oct-24 | 2020-Feb-04 | M80 | v12.13 | 🚫 |
-| 9.0.0 | -- | 2020-Feb-06 | 2020-May-19 | M83 | v12.14 | 🚫 |
-| 10.0.0 | -- | 2020-May-21 | 2020-Aug-25 | M85 | v12.16 | 🚫 |
-| 11.0.0 | -- | 2020-Aug-27 | 2020-Nov-17 | M87 | v12.18 | 🚫 |
-| 12.0.0 | -- | 2020-Nov-19 | 2021-Mar-02 | M89 | v14.16 | 🚫 |
-| 13.0.0 | -- | 2021-Mar-04 | 2021-May-25 | M91 | v14.16 | 🚫 |
-| 14.0.0 | -- | 2021-May-27 | 2021-Aug-31 | M93 | v14.17 | 🚫 |
-| 15.0.0 | 2021-Jul-20 | 2021-Sep-01 | 2021-Sep-21 | M94 | v16.5 | 🚫 |
-| 16.0.0 | 2021-Sep-23 | 2021-Oct-20 | 2021-Nov-16 | M96 | v16.9 | 🚫 |
-| 17.0.0 | 2021-Nov-18 | 2022-Jan-06 | 2022-Feb-01 | M98 | v16.13 | 🚫 |
-| 18.0.0 | 2022-Feb-03 | 2022-Mar-03 | 2022-Mar-29 | M100 | v16.13 | ✅ |
-| 19.0.0 | 2022-Mar-31 | 2022-Apr-26 | 2022-May-24 | M102 | v16.14 | ✅ |
-| 20.0.0 | 2022-May-26 | 2022-Jun-21 | 2022-Aug-02 | M104 | v16.15 | ✅ |
| 21.0.0 | 2022-Aug-04 | 2022-Aug-30 | 2022-Sep-27 | M106 | TBD | ✅ |
+| 20.0.0 | 2022-May-26 | 2022-Jun-21 | 2022-Aug-02 | M104 | v16.15 | ✅ |
+| 19.0.0 | 2022-Mar-31 | 2022-Apr-26 | 2022-May-24 | M102 | v16.14 | ✅ |
+| 18.0.0 | 2022-Feb-03 | 2022-Mar-03 | 2022-Mar-29 | M100 | v16.13 | ✅ |
+| 17.0.0 | 2021-Nov-18 | 2022-Jan-06 | 2022-Feb-01 | M98 | v16.13 | 🚫 |
+| 16.0.0 | 2021-Sep-23 | 2021-Oct-20 | 2021-Nov-16 | M96 | v16.9 | 🚫 |
+| 15.0.0 | 2021-Jul-20 | 2021-Sep-01 | 2021-Sep-21 | M94 | v16.5 | 🚫 |
+| 14.0.0 | -- | 2021-May-27 | 2021-Aug-31 | M93 | v14.17 | 🚫 |
+| 13.0.0 | -- | 2021-Mar-04 | 2021-May-25 | M91 | v14.16 | 🚫 |
+| 12.0.0 | -- | 2020-Nov-19 | 2021-Mar-02 | M89 | v14.16 | 🚫 |
+| 11.0.0 | -- | 2020-Aug-27 | 2020-Nov-17 | M87 | v12.18 | 🚫 |
+| 10.0.0 | -- | 2020-May-21 | 2020-Aug-25 | M85 | v12.16 | 🚫 |
+| 9.0.0 | -- | 2020-Feb-06 | 2020-May-19 | M83 | v12.14 | 🚫 |
+| 8.0.0 | -- | 2019-Oct-24 | 2020-Feb-04 | M80 | v12.13 | 🚫 |
+| 7.0.0 | -- | 2019-Aug-01 | 2019-Oct-22 | M78 | v12.8 | 🚫 |
+| 6.0.0 | -- | 2019-May-01 | 2019-Jul-30 | M76 | v12.4 | 🚫 |
+| 5.0.0 | -- | 2019-Jan-22 | 2019-Apr-24 | M73 | v12.0 | 🚫 |
+| 4.0.0 | -- | 2018-Oct-11 | 2018-Dec-20 | M69 | v10.11 | 🚫 |
+| 3.0.0 | -- | 2018-Jun-21 | 2018-Sep-18 | M66 | v10.2 | 🚫 |
+| 2.0.0 | -- | 2018-Feb-21 | 2018-May-01 | M61 | v8.9 | 🚫 |
**Notes:**
|
docs
|
6d0e8044ebca06a3de8d7063a0aa989735bab343
|
Shelley Vohr
|
2023-08-03 18:34:02
|
fix: update `chrome.tabs` for Manifest v3 (#39317)
|
diff --git a/shell/common/extensions/api/tabs.json b/shell/common/extensions/api/tabs.json
index 14d83b015a..c39e67a88c 100644
--- a/shell/common/extensions/api/tabs.json
+++ b/shell/common/extensions/api/tabs.json
@@ -3,13 +3,23 @@
"namespace": "tabs",
"description": "Use the <code>chrome.tabs</code> API to interact with the browser's tab system. You can use this API to create, modify, and rearrange tabs in the browser.",
"types": [
- { "id": "MutedInfoReason",
+ {
+ "id": "MutedInfoReason",
"type": "string",
"description": "An event that caused a muted state change.",
"enum": [
- {"name": "user", "description": "A user input action set the muted state."},
- {"name": "capture", "description": "Tab capture was started, forcing a muted state change."},
- {"name": "extension", "description": "An extension, identified by the extensionId field, set the muted state."}
+ {
+ "name": "user",
+ "description": "A user input action set the muted state."
+ },
+ {
+ "name": "capture",
+ "description": "Tab capture was started, forcing a muted state change."
+ },
+ {
+ "name": "extension",
+ "description": "An extension, identified by the extensionId field, set the muted state."
+ }
]
},
{
@@ -37,29 +47,112 @@
"id": "Tab",
"type": "object",
"properties": {
- "id": {"type": "integer", "minimum": -1, "optional": true, "description": "The ID of the tab. Tab IDs are unique within a browser session. Under some circumstances a tab may not be assigned an ID; for example, when querying foreign tabs using the $(ref:sessions) API, in which case a session ID may be present. Tab ID can also be set to <code>chrome.tabs.TAB_ID_NONE</code> for apps and devtools windows."},
- // TODO(kalman): Investigate how this is ending up as -1 (based on window type? a bug?) and whether it should be optional instead.
- "index": {"type": "integer", "minimum": -1, "description": "The zero-based index of the tab within its window."},
- "groupId": {"type": "integer", "minimum": -1, "description": "The ID of the group that the tab belongs to."},
- "windowId": {"type": "integer", "minimum": 0, "description": "The ID of the window that contains the tab."},
- "openerTabId": {"type": "integer", "minimum": 0, "optional": true, "description": "The ID of the tab that opened this tab, if any. This property is only present if the opener tab still exists."},
- "selected": {"type": "boolean", "description": "Whether the tab is selected.", "deprecated": "Please use $(ref:tabs.Tab.highlighted)."},
- "highlighted": {"type": "boolean", "description": "Whether the tab is highlighted."},
- "active": {"type": "boolean", "description": "Whether the tab is active in its window. Does not necessarily mean the window is focused."},
- "pinned": {"type": "boolean", "description": "Whether the tab is pinned."},
- "audible": {"type": "boolean", "optional": true, "description": "Whether the tab has produced sound over the past couple of seconds (but it might not be heard if also muted). Equivalent to whether the 'speaker audio' indicator is showing."},
- "discarded": {"type": "boolean", "description": "Whether the tab is discarded. A discarded tab is one whose content has been unloaded from memory, but is still visible in the tab strip. Its content is reloaded the next time it is activated."},
- "autoDiscardable": {"type": "boolean", "description": "Whether the tab can be discarded automatically by the browser when resources are low."},
- "mutedInfo": {"$ref": "MutedInfo", "optional": true, "description": "The tab's muted state and the reason for the last state change."},
- "url": {"type": "string", "optional": true, "description": "The last committed URL of the main frame of the tab. This property is only present if the extension's manifest includes the <code>\"tabs\"</code> permission and may be an empty string if the tab has not yet committed. See also $(ref:Tab.pendingUrl)."},
- "pendingUrl": {"type": "string", "optional": true, "description": "The URL the tab is navigating to, before it has committed. This property is only present if the extension's manifest includes the <code>\"tabs\"</code> permission and there is a pending navigation."},
- "title": {"type": "string", "optional": true, "description": "The title of the tab. This property is only present if the extension's manifest includes the <code>\"tabs\"</code> permission."},
- "favIconUrl": {"type": "string", "optional": true, "description": "The URL of the tab's favicon. This property is only present if the extension's manifest includes the <code>\"tabs\"</code> permission. It may also be an empty string if the tab is loading."},
- "status": {"type": "string", "optional": true, "description": "Either <em>loading</em> or <em>complete</em>."},
- "incognito": {"type": "boolean", "description": "Whether the tab is in an incognito window."},
- "width": {"type": "integer", "optional": true, "description": "The width of the tab in pixels."},
- "height": {"type": "integer", "optional": true, "description": "The height of the tab in pixels."},
- "sessionId": {"type": "string", "optional": true, "description": "The session ID used to uniquely identify a tab obtained from the $(ref:sessions) API."}
+ "id": {
+ "type": "integer",
+ "minimum": -1,
+ "optional": true,
+ "description": "The ID of the tab. Tab IDs are unique within a browser session. Under some circumstances a tab may not be assigned an ID; for example, when querying foreign tabs using the $(ref:sessions) API, in which case a session ID may be present. Tab ID can also be set to <code>chrome.tabs.TAB_ID_NONE</code> for apps and devtools windows."
+ },
+ "index": {
+ "type": "integer",
+ "minimum": -1,
+ "description": "The zero-based index of the tab within its window."
+ },
+ "groupId": {
+ "type": "integer",
+ "minimum": -1,
+ "description": "The ID of the group that the tab belongs to."
+ },
+ "windowId": {
+ "type": "integer",
+ "minimum": 0,
+ "description": "The ID of the window that contains the tab."
+ },
+ "openerTabId": {
+ "type": "integer",
+ "minimum": 0,
+ "optional": true,
+ "description": "The ID of the tab that opened this tab, if any. This property is only present if the opener tab still exists."
+ },
+ "selected": {
+ "type": "boolean",
+ "description": "Whether the tab is selected.",
+ "deprecated": "Please use $(ref:tabs.Tab.highlighted)."
+ },
+ "highlighted": {
+ "type": "boolean",
+ "description": "Whether the tab is highlighted."
+ },
+ "active": {
+ "type": "boolean",
+ "description": "Whether the tab is active in its window. Does not necessarily mean the window is focused."
+ },
+ "pinned": {
+ "type": "boolean",
+ "description": "Whether the tab is pinned."
+ },
+ "audible": {
+ "type": "boolean",
+ "optional": true,
+ "description": "Whether the tab has produced sound over the past couple of seconds (but it might not be heard if also muted). Equivalent to whether the 'speaker audio' indicator is showing."
+ },
+ "discarded": {
+ "type": "boolean",
+ "description": "Whether the tab is discarded. A discarded tab is one whose content has been unloaded from memory, but is still visible in the tab strip. Its content is reloaded the next time it is activated."
+ },
+ "autoDiscardable": {
+ "type": "boolean",
+ "description": "Whether the tab can be discarded automatically by the browser when resources are low."
+ },
+ "mutedInfo": {
+ "$ref": "MutedInfo",
+ "optional": true,
+ "description": "The tab's muted state and the reason for the last state change."
+ },
+ "url": {
+ "type": "string",
+ "optional": true,
+ "description": "The last committed URL of the main frame of the tab. This property is only present if the extension's manifest includes the <code>\"tabs\"</code> permission and may be an empty string if the tab has not yet committed. See also $(ref:Tab.pendingUrl)."
+ },
+ "pendingUrl": {
+ "type": "string",
+ "optional": true,
+ "description": "The URL the tab is navigating to, before it has committed. This property is only present if the extension's manifest includes the <code>\"tabs\"</code> permission and there is a pending navigation."
+ },
+ "title": {
+ "type": "string",
+ "optional": true,
+ "description": "The title of the tab. This property is only present if the extension's manifest includes the <code>\"tabs\"</code> permission."
+ },
+ "favIconUrl": {
+ "type": "string",
+ "optional": true,
+ "description": "The URL of the tab's favicon. This property is only present if the extension's manifest includes the <code>\"tabs\"</code> permission. It may also be an empty string if the tab is loading."
+ },
+ "status": {
+ "type": "string",
+ "optional": true,
+ "description": "Either <em>loading</em> or <em>complete</em>."
+ },
+ "incognito": {
+ "type": "boolean",
+ "description": "Whether the tab is in an incognito window."
+ },
+ "width": {
+ "type": "integer",
+ "optional": true,
+ "description": "The width of the tab in pixels."
+ },
+ "height": {
+ "type": "integer",
+ "optional": true,
+ "description": "The height of the tab in pixels."
+ },
+ "sessionId": {
+ "type": "string",
+ "optional": true,
+ "description": "The session ID used to uniquely identify a tab obtained from the $(ref:sessions) API."
+ }
}
},
{
@@ -125,7 +218,13 @@
"type": "function",
"description": "Reload a tab.",
"parameters": [
- {"type": "integer", "name": "tabId", "minimum": 0, "optional": true, "description": "The ID of the tab to reload; defaults to the selected tab of the current window."},
+ {
+ "type": "integer",
+ "name": "tabId",
+ "minimum": 0,
+ "optional": true,
+ "description": "The ID of the tab to reload; defaults to the selected tab of the current window."
+ },
{
"type": "object",
"name": "reloadProperties",
@@ -134,12 +233,16 @@
"bypassCache": {
"type": "boolean",
"optional": true,
- "description": "Whether using any local cache. Default is false."
+ "description": "Whether to bypass local caching. Defaults to <code>false</code>."
}
}
- },
- {"type": "function", "name": "callback", "optional": true, "parameters": []}
- ]
+ }
+ ],
+ "returns_async": {
+ "name": "callback",
+ "optional": true,
+ "parameters": []
+ }
},
{
"name": "get",
@@ -150,15 +253,17 @@
"type": "integer",
"name": "tabId",
"minimum": 0
- },
- {
- "type": "function",
- "name": "callback",
- "parameters": [
- {"name": "tab", "$ref": "Tab"}
- ]
}
- ]
+ ],
+ "returns_async": {
+ "name": "callback",
+ "parameters": [
+ {
+ "name": "tab",
+ "$ref": "Tab"
+ }
+ ]
+ }
},
{
"name": "connect",
@@ -175,12 +280,21 @@
"type": "object",
"name": "connectInfo",
"properties": {
- "name": { "type": "string", "optional": true, "description": "Is passed into onConnect for content scripts that are listening for the connection event." },
+ "name": {
+ "type": "string",
+ "optional": true,
+ "description": "Is passed into onConnect for content scripts that are listening for the connection event."
+ },
"frameId": {
"type": "integer",
"optional": true,
"minimum": 0,
"description": "Open a port to a specific <a href='webNavigation#frame_ids'>frame</a> identified by <code>frameId</code> instead of all frames in the tab."
+ },
+ "documentId": {
+ "type": "string",
+ "optional": true,
+ "description": "Open a port to a specific <a href='webNavigation#document_ids'>document</a> identified by <code>documentId</code> instead of all frames in the tab."
}
},
"optional": true
@@ -193,7 +307,9 @@
},
{
"name": "executeScript",
+ "deprecated": "Replaced by $(ref:scripting.executeScript) in Manifest V3.",
"type": "function",
+ "description": "Injects JavaScript code into a page. For details, see the <a href='content_scripts#pi'>programmatic injection</a> section of the content scripts doc.",
"parameters": [
{
"type": "integer",
@@ -206,26 +322,25 @@
"$ref": "extensionTypes.InjectDetails",
"name": "details",
"description": "Details of the script to run. Either the code or the file property must be set, but both may not be set at the same time."
- },
- {
- "type": "function",
- "name": "callback",
- "optional": true,
- "description": "Called after all the JavaScript has been executed.",
- "parameters": [
- {
- "name": "result",
- "optional": true,
- "type": "array",
- "items": {
- "type": "any",
- "minimum": 0
- },
- "description": "The result of the script in every injected frame."
- }
- ]
}
- ]
+ ],
+ "returns_async": {
+ "name": "callback",
+ "optional": true,
+ "description": "Called after all the JavaScript has been executed.",
+ "parameters": [
+ {
+ "name": "result",
+ "optional": true,
+ "type": "array",
+ "items": {
+ "type": "any",
+ "minimum": 0
+ },
+ "description": "The result of the script in every injected frame."
+ }
+ ]
+ }
},
{
"name": "sendMessage",
@@ -252,23 +367,27 @@
"optional": true,
"minimum": 0,
"description": "Send a message to a specific <a href='webNavigation#frame_ids'>frame</a> identified by <code>frameId</code> instead of all frames in the tab."
+ },
+ "documentId": {
+ "type": "string",
+ "optional": true,
+ "description": "Send a message to a specific <a href='webNavigation#document_ids'>document</a> identified by <code>documentId</code> instead of all frames in the tab."
}
},
"optional": true
- },
- {
- "type": "function",
- "name": "responseCallback",
- "optional": true,
- "parameters": [
- {
- "name": "response",
- "type": "any",
- "description": "The JSON response object sent by the handler of the message. If an error occurs while connecting to the specified tab, the callback is called with no arguments and $(ref:runtime.lastError) is set to the error message."
- }
- ]
}
- ]
+ ],
+ "returns_async": {
+ "name": "callback",
+ "optional": true,
+ "parameters": [
+ {
+ "name": "response",
+ "type": "any",
+ "description": "The JSON response object sent by the handler of the message. If an error occurs while connecting to the specified tab, the callback is called with no arguments and $(ref:runtime.lastError) is set to the error message."
+ }
+ ]
+ }
},
{
"name": "setZoom",
@@ -286,15 +405,14 @@
"type": "number",
"name": "zoomFactor",
"description": "The new zoom factor. A value of <code>0</code> sets the tab to its current default zoom factor. Values greater than <code>0</code> specify a (possibly non-default) zoom factor for the tab."
- },
- {
- "type": "function",
- "name": "callback",
- "optional": true,
- "description": "Called after the zoom factor has been changed.",
- "parameters": []
}
- ]
+ ],
+ "returns_async": {
+ "name": "callback",
+ "optional": true,
+ "description": "Called after the zoom factor has been changed.",
+ "parameters": []
+ }
},
{
"name": "getZoom",
@@ -307,20 +425,19 @@
"minimum": 0,
"optional": true,
"description": "The ID of the tab to get the current zoom factor from; defaults to the active tab of the current window."
- },
- {
- "type": "function",
- "name": "callback",
- "description": "Called with the tab's current zoom factor after it has been fetched.",
- "parameters": [
- {
- "type": "number",
- "name": "zoomFactor",
- "description": "The tab's current zoom factor."
- }
- ]
}
- ]
+ ],
+ "returns_async": {
+ "name": "callback",
+ "description": "Called with the tab's current zoom factor after it has been fetched.",
+ "parameters": [
+ {
+ "type": "number",
+ "name": "zoomFactor",
+ "description": "The tab's current zoom factor."
+ }
+ ]
+ }
},
{
"name": "setZoomSettings",
@@ -338,15 +455,14 @@
"$ref": "ZoomSettings",
"name": "zoomSettings",
"description": "Defines how zoom changes are handled and at what scope."
- },
- {
- "type": "function",
- "name": "callback",
- "optional": true,
- "description": "Called after the zoom settings are changed.",
- "parameters": []
}
- ]
+ ],
+ "returns_async": {
+ "name": "callback",
+ "optional": true,
+ "description": "Called after the zoom settings are changed.",
+ "parameters": []
+ }
},
{
"name": "getZoomSettings",
@@ -359,20 +475,19 @@
"optional": true,
"minimum": 0,
"description": "The ID of the tab to get the current zoom settings from; defaults to the active tab of the current window."
- },
- {
- "type": "function",
- "name": "callback",
- "description": "Called with the tab's current zoom settings.",
- "parameters": [
- {
- "$ref": "ZoomSettings",
- "name": "zoomSettings",
- "description": "The tab's current zoom settings."
- }
- ]
}
- ]
+ ],
+ "returns_async": {
+ "name": "callback",
+ "description": "Called with the tab's current zoom settings.",
+ "parameters": [
+ {
+ "$ref": "ZoomSettings",
+ "name": "zoomSettings",
+ "description": "The tab's current zoom settings."
+ }
+ ]
+ }
},
{
"name": "update",
@@ -454,17 +569,28 @@
"name": "onZoomChange",
"type": "function",
"description": "Fired when a tab is zoomed.",
- "parameters": [{
- "type": "object",
- "name": "ZoomChangeInfo",
- "properties": {
- "tabId": {"type": "integer", "minimum": 0},
- "oldZoomFactor": {"type": "number"},
- "newZoomFactor": {"type": "number"},
- "zoomSettings": {"$ref": "ZoomSettings"}
+ "parameters": [
+ {
+ "type": "object",
+ "name": "ZoomChangeInfo",
+ "properties": {
+ "tabId": {
+ "type": "integer",
+ "minimum": 0
+ },
+ "oldZoomFactor": {
+ "type": "number"
+ },
+ "newZoomFactor": {
+ "type": "number"
+ },
+ "zoomSettings": {
+ "$ref": "ZoomSettings"
+ }
+ }
}
- }]
+ ]
}
]
}
-]
+]
\ No newline at end of file
diff --git a/spec/extensions-spec.ts b/spec/extensions-spec.ts
index 5a0f5ddff2..cc8b49c6c2 100644
--- a/spec/extensions-spec.ts
+++ b/spec/extensions-spec.ts
@@ -373,7 +373,7 @@ describe('chrome extensions', () => {
const message = { method: 'executeScript', args: ['1 + 2'] };
w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
- const [,, responseString] = await once(w.webContents, 'console-message');
+ const [, , responseString] = await once(w.webContents, 'console-message');
const response = JSON.parse(responseString);
expect(response).to.equal(3);
@@ -835,5 +835,121 @@ describe('chrome extensions', () => {
]);
});
});
+
+ describe('chrome.tabs', () => {
+ let customSession: Session;
+ let w = null as unknown as BrowserWindow;
+
+ before(async () => {
+ customSession = session.fromPartition(`persist:${uuid.v4()}`);
+ await customSession.loadExtension(path.join(fixtures, 'extensions', 'tabs-api-async'));
+ });
+
+ beforeEach(() => {
+ w = new BrowserWindow({
+ show: false,
+ webPreferences: {
+ session: customSession,
+ nodeIntegration: true
+ }
+ });
+ });
+
+ afterEach(closeAllWindows);
+
+ it('getZoom', async () => {
+ await w.loadURL(url);
+
+ const message = { method: 'getZoom' };
+ w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
+
+ const [,, responseString] = await once(w.webContents, 'console-message');
+
+ const response = JSON.parse(responseString);
+ expect(response).to.equal(1);
+ });
+
+ it('setZoom', async () => {
+ await w.loadURL(url);
+
+ const message = { method: 'setZoom', args: [2] };
+ w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
+
+ const [,, responseString] = await once(w.webContents, 'console-message');
+
+ const response = JSON.parse(responseString);
+ expect(response).to.deep.equal(2);
+ });
+
+ it('getZoomSettings', async () => {
+ await w.loadURL(url);
+
+ const message = { method: 'getZoomSettings' };
+ w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
+
+ const [,, responseString] = await once(w.webContents, 'console-message');
+
+ const response = JSON.parse(responseString);
+ expect(response).to.deep.equal({
+ defaultZoomFactor: 1,
+ mode: 'automatic',
+ scope: 'per-origin'
+ });
+ });
+
+ it('setZoomSettings', async () => {
+ await w.loadURL(url);
+
+ const message = { method: 'setZoomSettings', args: [{ mode: 'disabled' }] };
+ w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
+
+ const [,, responseString] = await once(w.webContents, 'console-message');
+
+ const response = JSON.parse(responseString);
+ expect(response).to.deep.equal({
+ defaultZoomFactor: 1,
+ mode: 'disabled',
+ scope: 'per-tab'
+ });
+ });
+
+ it('get', async () => {
+ await w.loadURL(url);
+
+ const message = { method: 'get' };
+ w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
+
+ const [,, responseString] = await once(w.webContents, 'console-message');
+
+ const response = JSON.parse(responseString);
+ expect(response).to.have.property('active').that.is.a('boolean');
+ expect(response).to.have.property('autoDiscardable').that.is.a('boolean');
+ expect(response).to.have.property('discarded').that.is.a('boolean');
+ expect(response).to.have.property('groupId').that.is.a('number');
+ expect(response).to.have.property('highlighted').that.is.a('boolean');
+ expect(response).to.have.property('id').that.is.a('number');
+ expect(response).to.have.property('incognito').that.is.a('boolean');
+ expect(response).to.have.property('index').that.is.a('number');
+ expect(response).to.have.property('pinned').that.is.a('boolean');
+ expect(response).to.have.property('selected').that.is.a('boolean');
+ expect(response).to.have.property('url').that.is.a('string');
+ expect(response).to.have.property('windowId').that.is.a('number');
+ });
+
+ it('reload', async () => {
+ await w.loadURL(url);
+
+ const message = { method: 'reload' };
+ w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`);
+
+ const consoleMessage = once(w.webContents, 'console-message');
+ const finish = once(w.webContents, 'did-finish-load');
+
+ await Promise.all([consoleMessage, finish]).then(([[,, responseString]]) => {
+ const response = JSON.parse(responseString);
+ expect(response.status).to.equal('reloaded');
+ });
+ });
+ });
});
});
diff --git a/spec/fixtures/extensions/chrome-api/main.js b/spec/fixtures/extensions/chrome-api/main.js
index 14331534b7..e24784d9fb 100644
--- a/spec/fixtures/extensions/chrome-api/main.js
+++ b/spec/fixtures/extensions/chrome-api/main.js
@@ -49,4 +49,5 @@ const dispatchTest = (event) => {
const { method, args = [] } = JSON.parse(event.data);
testMap[method](...args);
};
+
window.addEventListener('message', dispatchTest, false);
diff --git a/spec/fixtures/extensions/tabs-api-async/background.js b/spec/fixtures/extensions/tabs-api-async/background.js
new file mode 100644
index 0000000000..32290c36fb
--- /dev/null
+++ b/spec/fixtures/extensions/tabs-api-async/background.js
@@ -0,0 +1,52 @@
+/* global chrome */
+
+const handleRequest = (request, sender, sendResponse) => {
+ const { method, args = [] } = request;
+ const tabId = sender.tab.id;
+
+ switch (method) {
+ case 'getZoom': {
+ chrome.tabs.getZoom(tabId).then(sendResponse);
+ break;
+ }
+
+ case 'setZoom': {
+ const [zoom] = args;
+ chrome.tabs.setZoom(tabId, zoom).then(async () => {
+ const updatedZoom = await chrome.tabs.getZoom(tabId);
+ sendResponse(updatedZoom);
+ });
+ break;
+ }
+
+ case 'getZoomSettings': {
+ chrome.tabs.getZoomSettings(tabId).then(sendResponse);
+ break;
+ }
+
+ case 'setZoomSettings': {
+ const [settings] = args;
+ chrome.tabs.setZoomSettings(tabId, { mode: settings.mode }).then(async () => {
+ const zoomSettings = await chrome.tabs.getZoomSettings(tabId);
+ sendResponse(zoomSettings);
+ });
+ break;
+ }
+
+ case 'get': {
+ chrome.tabs.get(tabId).then(sendResponse);
+ break;
+ }
+
+ case 'reload': {
+ chrome.tabs.reload(tabId).then(() => {
+ sendResponse({ status: 'reloaded' });
+ });
+ }
+ }
+};
+
+chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
+ handleRequest(request, sender, sendResponse);
+ return true;
+});
diff --git a/spec/fixtures/extensions/tabs-api-async/main.js b/spec/fixtures/extensions/tabs-api-async/main.js
new file mode 100644
index 0000000000..8c23bb00d0
--- /dev/null
+++ b/spec/fixtures/extensions/tabs-api-async/main.js
@@ -0,0 +1,45 @@
+/* global chrome */
+
+chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
+ sendResponse(request);
+});
+
+const testMap = {
+ getZoomSettings () {
+ chrome.runtime.sendMessage({ method: 'getZoomSettings' }, response => {
+ console.log(JSON.stringify(response));
+ });
+ },
+ setZoomSettings (settings) {
+ chrome.runtime.sendMessage({ method: 'setZoomSettings', args: [settings] }, response => {
+ console.log(JSON.stringify(response));
+ });
+ },
+ getZoom () {
+ chrome.runtime.sendMessage({ method: 'getZoom', args: [] }, response => {
+ console.log(JSON.stringify(response));
+ });
+ },
+ setZoom (zoom) {
+ chrome.runtime.sendMessage({ method: 'setZoom', args: [zoom] }, response => {
+ console.log(JSON.stringify(response));
+ });
+ },
+ get () {
+ chrome.runtime.sendMessage({ method: 'get' }, response => {
+ console.log(JSON.stringify(response));
+ });
+ },
+ reload () {
+ chrome.runtime.sendMessage({ method: 'reload' }, response => {
+ console.log(JSON.stringify(response));
+ });
+ }
+};
+
+const dispatchTest = (event) => {
+ const { method, args = [] } = JSON.parse(event.data);
+ testMap[method](...args);
+};
+
+window.addEventListener('message', dispatchTest, false);
diff --git a/spec/fixtures/extensions/tabs-api-async/manifest.json b/spec/fixtures/extensions/tabs-api-async/manifest.json
new file mode 100644
index 0000000000..58081152de
--- /dev/null
+++ b/spec/fixtures/extensions/tabs-api-async/manifest.json
@@ -0,0 +1,15 @@
+{
+ "name": "tabs-api-async",
+ "version": "1.0",
+ "content_scripts": [
+ {
+ "matches": [ "<all_urls>"],
+ "js": ["main.js"],
+ "run_at": "document_start"
+ }
+ ],
+ "background": {
+ "service_worker": "background.js"
+ },
+ "manifest_version": 3
+}
|
fix
|
397aee7315fdc2349921501933f1d77f03448125
|
Milan Burda
|
2023-01-26 01:57:20
|
chore: update README.md (#37002)
Update README.md
|
diff --git a/README.md b/README.md
index 2baee7b9da..c8c1376720 100644
--- a/README.md
+++ b/README.md
@@ -39,7 +39,7 @@ For more installation options and troubleshooting tips, see
Each Electron release provides binaries for macOS, Windows, and Linux.
* macOS (High Sierra and up): Electron provides 64-bit Intel and ARM binaries for macOS. Apple Silicon support was added in Electron 11.
-* Windows (Windows 10 and up): Electron provides `ia32` (`x86`), `x64` (`amd64`), and `arm64` binaries for Windows. Windows on ARM support was added in Electron 5.0.8. Support for Windows 7 and 8 was [removed in Electron 23, in line with Chromium's Windows deprecation policy](https://www.electronjs.org/blog/windows-7-to-8-1-deprecation-notice).
+* Windows (Windows 10 and up): Electron provides `ia32` (`x86`), `x64` (`amd64`), and `arm64` binaries for Windows. Windows on ARM support was added in Electron 5.0.8. Support for Windows 7, 8 and 8.1 was [removed in Electron 23, in line with Chromium's Windows deprecation policy](https://www.electronjs.org/blog/windows-7-to-8-1-deprecation-notice).
* Linux: The prebuilt binaries of Electron are built on Ubuntu 20.04. They have also been verified to work on:
* Ubuntu 14.04 and newer
* Fedora 24 and newer
|
chore
|
ba8887f5860818db4a49f3bb48df5a3351032695
|
Shelley Vohr
|
2023-04-27 12:54:51
|
feat: emit `context-menu` event from extensions (#38029)
feat: emit context-menu event from extensions
|
diff --git a/shell/browser/api/electron_api_web_contents.h b/shell/browser/api/electron_api_web_contents.h
index b6e2bcb041..3c7e0ec1b6 100644
--- a/shell/browser/api/electron_api_web_contents.h
+++ b/shell/browser/api/electron_api_web_contents.h
@@ -326,6 +326,9 @@ class WebContents : public ExclusiveAccessContext,
const base::FilePath& file_path);
v8::Local<v8::Promise> GetProcessMemoryInfo(v8::Isolate* isolate);
+ bool HandleContextMenu(content::RenderFrameHost& render_frame_host,
+ const content::ContextMenuParams& params) override;
+
// Properties.
int32_t ID() const { return id_; }
v8::Local<v8::Value> Session(v8::Isolate* isolate);
@@ -551,8 +554,6 @@ class WebContents : public ExclusiveAccessContext,
void RendererResponsive(
content::WebContents* source,
content::RenderWidgetHost* render_widget_host) override;
- bool HandleContextMenu(content::RenderFrameHost& render_frame_host,
- const content::ContextMenuParams& params) override;
void FindReply(content::WebContents* web_contents,
int request_id,
int number_of_matches,
diff --git a/shell/browser/extensions/electron_extensions_api_client.cc b/shell/browser/extensions/electron_extensions_api_client.cc
index 1a4c24700b..827044836e 100644
--- a/shell/browser/extensions/electron_extensions_api_client.cc
+++ b/shell/browser/extensions/electron_extensions_api_client.cc
@@ -65,10 +65,19 @@ class ElectronMimeHandlerViewGuestDelegate
// MimeHandlerViewGuestDelegate.
bool HandleContextMenu(content::RenderFrameHost& render_frame_host,
const content::ContextMenuParams& params) override {
- // TODO(nornagon): surface this event to JS
- LOG(INFO) << "HCM";
+ auto* web_contents =
+ content::WebContents::FromRenderFrameHost(&render_frame_host);
+ if (!web_contents)
+ return true;
+
+ electron::api::WebContents* api_web_contents =
+ electron::api::WebContents::From(
+ web_contents->GetOutermostWebContents());
+ if (api_web_contents)
+ api_web_contents->HandleContextMenu(render_frame_host, params);
return true;
}
+
void RecordLoadMetric(bool in_main_frame,
const std::string& mime_type) override {}
};
|
feat
|
1328d8d6708cce054bf0d81044fa3f8032d3885f
|
Milan Burda
|
2022-10-12 16:27:58
|
docs: use webContents.mainFrame.on() in MessagePort tutorial (#35824)
* docs: use webContents.mainFrame.on() in MessagePort tutorial
* Update docs/tutorial/message-ports.md
Co-authored-by: Samuel Maddock <[email protected]>
Co-authored-by: Samuel Maddock <[email protected]>
|
diff --git a/docs/tutorial/message-ports.md b/docs/tutorial/message-ports.md
index 583ced73c4..73ec5f6f9b 100644
--- a/docs/tutorial/message-ports.md
+++ b/docs/tutorial/message-ports.md
@@ -180,19 +180,16 @@ app.whenReady().then(async () => {
// We can't use ipcMain.handle() here, because the reply needs to transfer a
// MessagePort.
- ipcMain.on('request-worker-channel', (event) => {
- // For security reasons, let's make sure only the frames we expect can
- // access the worker.
- if (event.senderFrame === mainWindow.webContents.mainFrame) {
- // Create a new channel ...
- const { port1, port2 } = new MessageChannelMain()
- // ... send one end to the worker ...
- worker.webContents.postMessage('new-client', null, [port1])
- // ... and the other end to the main window.
- event.senderFrame.postMessage('provide-worker-channel', null, [port2])
- // Now the main window and the worker can communicate with each other
- // without going through the main process!
- }
+ // Listen for message sent from the top-level frame
+ mainWindow.webContents.mainFrame.on('request-worker-channel', (event) => {
+ // Create a new channel ...
+ const { port1, port2 } = new MessageChannelMain()
+ // ... send one end to the worker ...
+ worker.webContents.postMessage('new-client', null, [port1])
+ // ... and the other end to the main window.
+ event.senderFrame.postMessage('provide-worker-channel', null, [port2])
+ // Now the main window and the worker can communicate with each other
+ // without going through the main process!
})
})
```
|
docs
|
37c79ea844b09aec3c8f2254e191879383257225
|
Athul Iddya
|
2023-10-02 03:19:23
|
docs: add PipeWire integration instructions for snaps (#40019)
|
diff --git a/docs/tutorial/snapcraft.md b/docs/tutorial/snapcraft.md
index 09e7a7830c..1b978b81d6 100644
--- a/docs/tutorial/snapcraft.md
+++ b/docs/tutorial/snapcraft.md
@@ -91,14 +91,14 @@ version: '0.1'
summary: Hello World Electron app
description: |
Simple Hello World Electron app as an example
-base: core18
+base: core22
confinement: strict
grade: stable
apps:
electron-packager-hello-world:
command: electron-quick-start/electron-quick-start --no-sandbox
- extensions: [gnome-3-34]
+ extensions: [gnome]
plugs:
- browser-support
- network
@@ -237,6 +237,34 @@ apps:
desktop: usr/share/applications/desktop.desktop
```
+## Optional: Enabling desktop capture
+
+Capturing the desktop requires PipeWire library in some Linux configurations that use
+the Wayland protocol. To bundle PipeWire with your application, ensure that the base
+snap is set to `core22` or newer. Next, create a part called `pipewire` and add it to
+the `after` section of your application:
+
+```yaml
+ pipewire:
+ plugin: nil
+ build-packages: [libpipewire-0.3-dev]
+ stage-packages: [pipewire]
+ prime:
+ - usr/lib/*/pipewire-*
+ - usr/lib/*/spa-*
+ - usr/lib/*/libpipewire*.so*
+ - usr/share/pipewire
+```
+
+Finally, configure your application's environment for PipeWire:
+
+```yaml
+ environment:
+ SPA_PLUGIN_DIR: $SNAP/usr/lib/$CRAFT_ARCH_TRIPLET/spa-0.2
+ PIPEWIRE_CONFIG_NAME: $SNAP/usr/share/pipewire/pipewire.conf
+ PIPEWIRE_MODULE_DIR: $SNAP/usr/lib/$CRAFT_ARCH_TRIPLET/pipewire-0.3
+```
+
[snapcraft-syntax]: https://docs.snapcraft.io/build-snaps/syntax
[electron-packager]: https://github.com/electron/electron-packager
[electron-forge]: https://github.com/electron/forge
|
docs
|
e254593616e0c0ce8ae861ec860002ee14cb74f9
|
Ali Yousefi
|
2023-10-18 16:56:17
|
docs: replace the example app using electron (#37805)
* replace the example app using electron
* Update README.md
Remove the trailing space to pass linter. Suggested by @jkleinsc. Thank you @jkleinsc for the suggestion.
---------
Co-authored-by: John Kleinschmidt <[email protected]>
|
diff --git a/README.md b/README.md
index bc3eb1987d..d45d3cfe50 100644
--- a/README.md
+++ b/README.md
@@ -9,8 +9,8 @@ View these docs in other languages on our [Crowdin](https://crowdin.com/project/
The Electron framework lets you write cross-platform desktop applications
using JavaScript, HTML and CSS. It is based on [Node.js](https://nodejs.org/) and
-[Chromium](https://www.chromium.org) and is used by the [Atom
-editor](https://github.com/atom/atom) and many other [apps](https://electronjs.org/apps).
+[Chromium](https://www.chromium.org) and is used by the [Visual Studio
+Code](https://github.com/Microsoft/vscode/) and many other [apps](https://electronjs.org/apps).
Follow [@electronjs](https://twitter.com/electronjs) on Twitter for important
announcements.
|
docs
|
6cb5f5a1eb68c3013a2d62392b4289c70b2ce668
|
Marco Pelloni
|
2023-01-04 05:52:29
|
docs: update incorrect grammar (#36780)
#### Description of Change
The first sentence within the documentation "[Important: signing your code](https://www.electronjs.org/docs/latest/tutorial/tutorial-packaging#important-signing-your-code)" is grammatically incorrect.
> In order to distribute desktop applications to end users, we highly recommended for you to code sign your Electron app.
I've adjusted the copy to switch "highly recommended" to "highly recommend". I've also switched out "for you to code sign" for "that you code sign" for clarity.
> In order to distribute desktop applications to end users, we _highly recommend_ that you **code sign** your Electron app.
|
diff --git a/docs/tutorial/tutorial-5-packaging.md b/docs/tutorial/tutorial-5-packaging.md
index d803035675..b917bbe58d 100644
--- a/docs/tutorial/tutorial-5-packaging.md
+++ b/docs/tutorial/tutorial-5-packaging.md
@@ -127,8 +127,7 @@ documentation.
## Important: signing your code
-In order to distribute desktop applications to end users, we _highly recommended_ for you
-to **code sign** your Electron app. Code signing is an important part of shipping
+In order to distribute desktop applications to end users, we _highly recommend_ that you **code sign** your Electron app. Code signing is an important part of shipping
desktop applications, and is mandatory for the auto-update step in the final part
of the tutorial.
|
docs
|
517935cd551c15384cfb6d058e00e549fa6f981d
|
Milan Burda
|
2025-02-07 02:44:19
|
refactor: only pass `v8::Context` to `gin_helper::MicrotasksScope` constructor (#45484)
refactor: forward v8::Context to v8::MicrotasksScope constructor
|
diff --git a/shell/browser/api/electron_api_auto_updater.cc b/shell/browser/api/electron_api_auto_updater.cc
index 2d870bba83..2a1feaa9d8 100644
--- a/shell/browser/api/electron_api_auto_updater.cc
+++ b/shell/browser/api/electron_api_auto_updater.cc
@@ -47,8 +47,8 @@ void AutoUpdater::OnError(const std::string& message) {
};
gin_helper::MicrotasksScope microtasks_scope{
- isolate, wrapper->GetCreationContextChecked()->GetMicrotaskQueue(),
- true, v8::MicrotasksScope::kRunMicrotasks};
+ wrapper->GetCreationContextChecked(), true,
+ v8::MicrotasksScope::kRunMicrotasks};
node::MakeCallback(isolate, wrapper, "emit", args.size(), args.data(),
{0, 0});
diff --git a/shell/common/api/electron_bindings.cc b/shell/common/api/electron_bindings.cc
index 1bd968e16a..a2bc082ed0 100644
--- a/shell/common/api/electron_bindings.cc
+++ b/shell/common/api/electron_bindings.cc
@@ -240,8 +240,7 @@ void ElectronBindings::DidReceiveMemoryDump(
v8::Local<v8::Context> local_context =
v8::Local<v8::Context>::New(isolate, context);
gin_helper::MicrotasksScope microtasks_scope{
- isolate, local_context->GetMicrotaskQueue(), true,
- v8::MicrotasksScope::kRunMicrotasks};
+ local_context, true, v8::MicrotasksScope::kRunMicrotasks};
v8::Context::Scope context_scope(local_context);
if (!success) {
diff --git a/shell/common/gin_helper/callback.h b/shell/common/gin_helper/callback.h
index 7be65ec6d4..40babf18db 100644
--- a/shell/common/gin_helper/callback.h
+++ b/shell/common/gin_helper/callback.h
@@ -51,8 +51,7 @@ struct V8FunctionInvoker<v8::Local<v8::Value>(ArgTypes...)> {
v8::Local<v8::Function> holder = function.NewHandle(isolate);
v8::Local<v8::Context> context = holder->GetCreationContextChecked();
gin_helper::MicrotasksScope microtasks_scope{
- isolate, context->GetMicrotaskQueue(), true,
- v8::MicrotasksScope::kRunMicrotasks};
+ context, true, v8::MicrotasksScope::kRunMicrotasks};
v8::Context::Scope context_scope(context);
std::array<v8::Local<v8::Value>, sizeof...(raw)> args{
gin::ConvertToV8(isolate, std::forward<ArgTypes>(raw))...};
@@ -77,8 +76,7 @@ struct V8FunctionInvoker<void(ArgTypes...)> {
v8::Local<v8::Function> holder = function.NewHandle(isolate);
v8::Local<v8::Context> context = holder->GetCreationContextChecked();
gin_helper::MicrotasksScope microtasks_scope{
- isolate, context->GetMicrotaskQueue(), true,
- v8::MicrotasksScope::kRunMicrotasks};
+ context, true, v8::MicrotasksScope::kRunMicrotasks};
v8::Context::Scope context_scope(context);
std::array<v8::Local<v8::Value>, sizeof...(raw)> args{
gin::ConvertToV8(isolate, std::forward<ArgTypes>(raw))...};
@@ -102,8 +100,7 @@ struct V8FunctionInvoker<ReturnType(ArgTypes...)> {
v8::Local<v8::Function> holder = function.NewHandle(isolate);
v8::Local<v8::Context> context = holder->GetCreationContextChecked();
gin_helper::MicrotasksScope microtasks_scope{
- isolate, context->GetMicrotaskQueue(), true,
- v8::MicrotasksScope::kRunMicrotasks};
+ context, true, v8::MicrotasksScope::kRunMicrotasks};
v8::Context::Scope context_scope(context);
std::array<v8::Local<v8::Value>, sizeof...(raw)> args{
gin::ConvertToV8(isolate, std::forward<ArgTypes>(raw))...};
diff --git a/shell/common/gin_helper/event_emitter_caller.cc b/shell/common/gin_helper/event_emitter_caller.cc
index 2f4c50056e..360c84bebf 100644
--- a/shell/common/gin_helper/event_emitter_caller.cc
+++ b/shell/common/gin_helper/event_emitter_caller.cc
@@ -25,7 +25,7 @@ v8::Local<v8::Value> CallMethodWithArgs(
// Perform microtask checkpoint after running JavaScript.
gin_helper::MicrotasksScope microtasks_scope{
- isolate, obj->GetCreationContextChecked()->GetMicrotaskQueue(), true,
+ obj->GetCreationContextChecked(), true,
v8::MicrotasksScope::kRunMicrotasks};
// node::MakeCallback will also run pending tasks in Node.js.
diff --git a/shell/common/gin_helper/function_template.h b/shell/common/gin_helper/function_template.h
index 0737c8b474..5633184bec 100644
--- a/shell/common/gin_helper/function_template.h
+++ b/shell/common/gin_helper/function_template.h
@@ -268,8 +268,7 @@ class Invoker<std::index_sequence<indices...>, ArgTypes...>
void DispatchToCallback(
base::RepeatingCallback<ReturnType(ArgTypes...)> callback) {
gin_helper::MicrotasksScope microtasks_scope{
- args_->isolate(),
- args_->GetHolderCreationContext()->GetMicrotaskQueue(), true,
+ args_->GetHolderCreationContext(), true,
v8::MicrotasksScope::kRunMicrotasks};
args_->Return(
callback.Run(std::move(ArgumentHolder<indices, ArgTypes>::value)...));
@@ -280,8 +279,7 @@ class Invoker<std::index_sequence<indices...>, ArgTypes...>
// that have the void return type.
void DispatchToCallback(base::RepeatingCallback<void(ArgTypes...)> callback) {
gin_helper::MicrotasksScope microtasks_scope{
- args_->isolate(),
- args_->GetHolderCreationContext()->GetMicrotaskQueue(), true,
+ args_->GetHolderCreationContext(), true,
v8::MicrotasksScope::kRunMicrotasks};
callback.Run(std::move(ArgumentHolder<indices, ArgTypes>::value)...);
}
diff --git a/shell/common/gin_helper/microtasks_scope.cc b/shell/common/gin_helper/microtasks_scope.cc
index 763d1893d8..9daff7872a 100644
--- a/shell/common/gin_helper/microtasks_scope.cc
+++ b/shell/common/gin_helper/microtasks_scope.cc
@@ -5,13 +5,15 @@
#include "shell/common/gin_helper/microtasks_scope.h"
#include "shell/common/process_util.h"
+#include "v8/include/v8-context.h"
namespace gin_helper {
-MicrotasksScope::MicrotasksScope(v8::Isolate* isolate,
- v8::MicrotaskQueue* microtask_queue,
+MicrotasksScope::MicrotasksScope(v8::Local<v8::Context> context,
bool ignore_browser_checkpoint,
v8::MicrotasksScope::Type scope_type) {
+ auto* isolate = context->GetIsolate();
+ auto* microtask_queue = context->GetMicrotaskQueue();
if (electron::IsBrowserProcess()) {
if (!ignore_browser_checkpoint)
v8::MicrotasksScope::PerformCheckpoint(isolate);
diff --git a/shell/common/gin_helper/microtasks_scope.h b/shell/common/gin_helper/microtasks_scope.h
index 55772dea44..55487a6498 100644
--- a/shell/common/gin_helper/microtasks_scope.h
+++ b/shell/common/gin_helper/microtasks_scope.h
@@ -16,8 +16,7 @@ namespace gin_helper {
// In the render process creates a v8::MicrotasksScope.
class MicrotasksScope {
public:
- MicrotasksScope(v8::Isolate* isolate,
- v8::MicrotaskQueue* microtask_queue,
+ MicrotasksScope(v8::Local<v8::Context> context,
bool ignore_browser_checkpoint,
v8::MicrotasksScope::Type scope_type);
~MicrotasksScope();
diff --git a/shell/common/gin_helper/promise.cc b/shell/common/gin_helper/promise.cc
index 17da3f4bb3..531dede1fa 100644
--- a/shell/common/gin_helper/promise.cc
+++ b/shell/common/gin_helper/promise.cc
@@ -17,8 +17,7 @@ namespace gin_helper {
PromiseBase::SettleScope::SettleScope(const PromiseBase& base)
: handle_scope_{base.isolate()},
context_{base.GetContext()},
- microtasks_scope_{base.isolate(), context_->GetMicrotaskQueue(), false,
- v8::MicrotasksScope::kRunMicrotasks},
+ microtasks_scope_{context_, false, v8::MicrotasksScope::kRunMicrotasks},
context_scope_{context_} {}
PromiseBase::SettleScope::~SettleScope() = default;
diff --git a/shell/common/node_bindings.cc b/shell/common/node_bindings.cc
index bde4c3ca5d..8c682aba1c 100644
--- a/shell/common/node_bindings.cc
+++ b/shell/common/node_bindings.cc
@@ -288,8 +288,7 @@ void ErrorMessageListener(v8::Local<v8::Message> message,
node::Environment* env = node::Environment::GetCurrent(isolate);
if (env) {
gin_helper::MicrotasksScope microtasks_scope(
- isolate, env->context()->GetMicrotaskQueue(), false,
- v8::MicrotasksScope::kDoNotRunMicrotasks);
+ env->context(), false, v8::MicrotasksScope::kDoNotRunMicrotasks);
// Emit the after() hooks now that the exception has been handled.
// Analogous to node/lib/internal/process/execution.js#L176-L180
if (env->async_hooks()->fields()[node::AsyncHooks::kAfter]) {
diff --git a/shell/common/v8_util.cc b/shell/common/v8_util.cc
index 463ef545ed..85ed35cf1a 100644
--- a/shell/common/v8_util.cc
+++ b/shell/common/v8_util.cc
@@ -36,7 +36,7 @@ class V8Serializer : public v8::ValueSerializer::Delegate {
bool Serialize(v8::Local<v8::Value> value, blink::CloneableMessage* out) {
gin_helper::MicrotasksScope microtasks_scope{
- isolate_, isolate_->GetCurrentContext()->GetMicrotaskQueue(), false,
+ isolate_->GetCurrentContext(), false,
v8::MicrotasksScope::kDoNotRunMicrotasks};
WriteBlinkEnvelope(19);
diff --git a/shell/renderer/api/electron_api_spell_check_client.cc b/shell/renderer/api/electron_api_spell_check_client.cc
index 95e05ecccb..6626d8b2ce 100644
--- a/shell/renderer/api/electron_api_spell_check_client.cc
+++ b/shell/renderer/api/electron_api_spell_check_client.cc
@@ -217,8 +217,7 @@ void SpellCheckClient::SpellCheckWords(const SpellCheckScope& scope,
auto context = isolate_->GetCurrentContext();
gin_helper::MicrotasksScope microtasks_scope{
- isolate_, context->GetMicrotaskQueue(), false,
- v8::MicrotasksScope::kDoNotRunMicrotasks};
+ context, false, v8::MicrotasksScope::kDoNotRunMicrotasks};
v8::Local<v8::FunctionTemplate> templ = gin_helper::CreateFunctionTemplate(
isolate_, base::BindRepeating(&SpellCheckClient::OnSpellCheckDone,
diff --git a/shell/renderer/electron_render_frame_observer.cc b/shell/renderer/electron_render_frame_observer.cc
index 23b2b6698f..bf0045ae2d 100644
--- a/shell/renderer/electron_render_frame_observer.cc
+++ b/shell/renderer/electron_render_frame_observer.cc
@@ -81,8 +81,7 @@ void ElectronRenderFrameObserver::DidClearWindowObject() {
v8::HandleScope handle_scope{isolate};
v8::Local<v8::Context> context = web_frame->MainWorldScriptContext();
v8::MicrotasksScope microtasks_scope(
- isolate, context->GetMicrotaskQueue(),
- v8::MicrotasksScope::kDoNotRunMicrotasks);
+ context, v8::MicrotasksScope::kDoNotRunMicrotasks);
v8::Context::Scope context_scope(context);
// DidClearWindowObject only emits for the main world.
DidInstallConditionalFeatures(context, MAIN_WORLD_ID);
@@ -123,10 +122,8 @@ void ElectronRenderFrameObserver::DidInstallConditionalFeatures(
}
has_delayed_node_initialization_ = false;
- auto* isolate = context->GetIsolate();
v8::MicrotasksScope microtasks_scope(
- isolate, context->GetMicrotaskQueue(),
- v8::MicrotasksScope::kDoNotRunMicrotasks);
+ context, v8::MicrotasksScope::kDoNotRunMicrotasks);
if (ShouldNotifyClient(world_id))
renderer_client_->DidCreateScriptContext(context, render_frame_);
diff --git a/shell/renderer/electron_sandboxed_renderer_client.cc b/shell/renderer/electron_sandboxed_renderer_client.cc
index 398e861417..48aa42f6cd 100644
--- a/shell/renderer/electron_sandboxed_renderer_client.cc
+++ b/shell/renderer/electron_sandboxed_renderer_client.cc
@@ -149,8 +149,7 @@ void ElectronSandboxedRendererClient::WillReleaseScriptContext(
auto* isolate = context->GetIsolate();
gin_helper::MicrotasksScope microtasks_scope{
- isolate, context->GetMicrotaskQueue(), false,
- v8::MicrotasksScope::kDoNotRunMicrotasks};
+ context, false, v8::MicrotasksScope::kDoNotRunMicrotasks};
v8::HandleScope handle_scope(isolate);
v8::Context::Scope context_scope(context);
InvokeEmitProcessEvent(context, "exit");
@@ -168,8 +167,7 @@ void ElectronSandboxedRendererClient::EmitProcessEvent(
v8::Local<v8::Context> context = GetContext(frame, isolate);
gin_helper::MicrotasksScope microtasks_scope{
- isolate, context->GetMicrotaskQueue(), false,
- v8::MicrotasksScope::kDoNotRunMicrotasks};
+ context, false, v8::MicrotasksScope::kDoNotRunMicrotasks};
v8::Context::Scope context_scope(context);
InvokeEmitProcessEvent(context, event_name);
diff --git a/shell/renderer/web_worker_observer.cc b/shell/renderer/web_worker_observer.cc
index bd9eadf5e5..f157558fb7 100644
--- a/shell/renderer/web_worker_observer.cc
+++ b/shell/renderer/web_worker_observer.cc
@@ -48,8 +48,7 @@ void WebWorkerObserver::WorkerScriptReadyForEvaluation(
v8::Context::Scope context_scope(worker_context);
auto* isolate = worker_context->GetIsolate();
v8::MicrotasksScope microtasks_scope(
- isolate, worker_context->GetMicrotaskQueue(),
- v8::MicrotasksScope::kDoNotRunMicrotasks);
+ worker_context, v8::MicrotasksScope::kDoNotRunMicrotasks);
// Start the embed thread.
node_bindings_->PrepareEmbedThread();
|
refactor
|
3b018143b4c3c786f79f2b8a06daa2b955254c91
|
David Sanders
|
2023-01-20 13:02:50
|
ci: don't run stale workflow jobs in parallel (#36967)
|
diff --git a/.github/workflows/stale.yml b/.github/workflows/stale.yml
index b9a1248bf1..5720c6f249 100644
--- a/.github/workflows/stale.yml
+++ b/.github/workflows/stale.yml
@@ -25,6 +25,8 @@ jobs:
only-pr-labels: not-a-real-label
pending-repro:
runs-on: ubuntu-latest
+ if: ${{ always() }}
+ needs: stale
steps:
- uses: actions/stale@3de2653986ebd134983c79fe2be5d45cc3d9f4e1
with:
|
ci
|
b504f65acea54e485c692632851443089c9c1f70
|
Charles Kerr
|
2025-02-27 22:01:26
|
docs: update breaking-changes.md for 35.0.0 (#45822)
* docs: update breaking-changes.md for 35.0.0
* fixup! docs: update breaking-changes.md for 35.0.0
docs: make lint happy
|
diff --git a/docs/breaking-changes.md b/docs/breaking-changes.md
index eb7ad8219f..e7d3eeff07 100644
--- a/docs/breaking-changes.md
+++ b/docs/breaking-changes.md
@@ -35,6 +35,16 @@ https://learn.microsoft.com/en-us/windows/win32/dwm/composition-ovw#disabling-dw
## Planned Breaking API Changes (35.0)
+### Behavior Changed: Dialog API's `defaultPath` option on Linux
+
+On Linux, the required portal version for file dialogs has been reverted
+to 3 from 4. Using the `defaultPath` option of the Dialog API is not
+supported when using portal file chooser dialogs unless the portal
+backend is version 4 or higher. The `--xdg-portal-required-version`
+[command-line switch](/api/command-line-switches.md#--xdg-portal-required-versionversion)
+can be used to force a required version for your application.
+See [#44426](https://github.com/electron/electron/pull/44426) for more details.
+
### Deprecated: `getFromVersionID` on `session.serviceWorkers`
The `session.serviceWorkers.fromVersionID(versionId)` API has been deprecated
|
docs
|
8cf2e46c1f4b0b9bf74e5d41fc95e498612c091f
|
Niklas Wenzel
|
2025-01-29 12:50:20
|
docs: reference security guide in `ipcRenderer.on` docs (#45325)
|
diff --git a/docs/api/ipc-renderer.md b/docs/api/ipc-renderer.md
index 12273e9e1f..7f2afc41e7 100644
--- a/docs/api/ipc-renderer.md
+++ b/docs/api/ipc-renderer.md
@@ -41,6 +41,16 @@ The `ipcRenderer` module has the following method to listen for events and send
Listens to `channel`, when a new message arrives `listener` would be called with
`listener(event, args...)`.
+:::warning
+Do not expose the `event` argument to the renderer for security reasons! Wrap any
+callback that you receive from the renderer in another function like this:
+`ipcRenderer.on('my-channel', (event, ...args) => callback(...args))`.
+Not wrapping the callback in such a function would expose dangerous Electron APIs
+to the renderer process. See the
+[security guide](../tutorial/security.md#20-do-not-expose-electron-apis-to-untrusted-web-content)
+for more info.
+:::
+
### `ipcRenderer.off(channel, listener)`
* `channel` string
|
docs
|
daecbb90fe4587569bc3de83a7d6f472f2cd9096
|
Shelley Vohr
|
2024-03-19 10:49:24
|
test: modify remote specs to allow skip or only (#41620)
|
diff --git a/spec/lib/spec-helpers.ts b/spec/lib/spec-helpers.ts
index 9bad7f322a..b12ca77b55 100644
--- a/spec/lib/spec-helpers.ts
+++ b/spec/lib/spec-helpers.ts
@@ -176,8 +176,8 @@ export function useRemoteContext (opts?: any) {
});
}
-export async function itremote (name: string, fn: Function, args?: any[]) {
- it(name, async () => {
+async function runRemote (type: 'skip' | 'none' | 'only', name: string, fn: Function, args?: any[]) {
+ const wrapped = async () => {
const w = await getRemoteContext();
const { ok, message } = await w.webContents.executeJavaScript(`(async () => {
try {
@@ -192,9 +192,30 @@ export async function itremote (name: string, fn: Function, args?: any[]) {
}
})()`);
if (!ok) { throw new AssertionError(message); }
- });
+ };
+
+ let runFn: any = it;
+ if (type === 'only') {
+ runFn = it.only;
+ } else if (type === 'skip') {
+ runFn = it.skip;
+ }
+
+ runFn(name, wrapped);
}
+export const itremote = Object.assign(
+ (name: string, fn: Function, args?: any[]) => {
+ runRemote('none', name, fn, args);
+ }, {
+ only: (name: string, fn: Function, args?: any[]) => {
+ runRemote('only', name, fn, args);
+ },
+ skip: (name: string, fn: Function, args?: any[]) => {
+ runRemote('skip', name, fn, args);
+ }
+ });
+
export async function listen (server: http.Server | https.Server | http2.Http2SecureServer) {
const hostname = '127.0.0.1';
await new Promise<void>(resolve => server.listen(0, hostname, () => resolve()));
|
test
|
c894645ac68af14183d617570a2d51336a2578ad
|
Shelley Vohr
|
2024-02-09 22:44:24
|
fix: crash on macOS non-programmatic close (#41264)
|
diff --git a/shell/browser/native_window_mac.mm b/shell/browser/native_window_mac.mm
index 412f8a99f1..3a5b53690c 100644
--- a/shell/browser/native_window_mac.mm
+++ b/shell/browser/native_window_mac.mm
@@ -439,11 +439,14 @@ void NativeWindowMac::Close() {
if ([window_ attachedSheet])
[window_ endSheet:[window_ attachedSheet]];
+ // window_ could be nil after performClose.
+ bool should_notify = is_modal() && parent() && IsVisible();
+
[window_ performClose:nil];
// Closing a sheet doesn't trigger windowShouldClose,
// so we need to manually call it ourselves here.
- if (is_modal() && parent() && IsVisible()) {
+ if (should_notify) {
NotifyWindowCloseButtonClicked();
}
}
|
fix
|
8db1563d730c8f6a5ca38ad167c670195c553d26
|
Keeley Hammond
|
2024-07-27 09:44:22
|
fix: remove InspectableWebContentsViewMac (#43033)
* Revert "refactor: remove InspectableWebContentsViewMac in favor of the Views version (#41326)"
This reverts commit e67ab9a93dadccecff30de50ab4555191c30b6c4.
* build: fix gn check
* chore: implement setCornerRadii in inspectable_web_contents_view_mac
Co-authored-by: Shelley Vohr <[email protected]>
* fix: pass in cornerRadii value in setCornerRadii
Co-authored-by: Shelley Vohr <[email protected]>
* fix: forward declaration
* 5578714: Remove 0-arg (default) constructor for views::Widget::InitParams.
https://chromium-review.googlesource.com/c/chromium/src/+/5578714
* fix: contents_web_view_ -> contents_view_
* chore: remove extraneous includes
---------
Co-authored-by: Shelley Vohr <[email protected]>
|
diff --git a/filenames.gni b/filenames.gni
index 97b348cd7b..b8daa9a919 100644
--- a/filenames.gni
+++ b/filenames.gni
@@ -159,8 +159,12 @@ filenames = {
"shell/browser/osr/osr_web_contents_view_mac.mm",
"shell/browser/relauncher_mac.cc",
"shell/browser/ui/certificate_trust_mac.mm",
+ "shell/browser/ui/cocoa/delayed_native_view_host.h",
+ "shell/browser/ui/cocoa/delayed_native_view_host.mm",
"shell/browser/ui/cocoa/electron_bundle_mover.h",
"shell/browser/ui/cocoa/electron_bundle_mover.mm",
+ "shell/browser/ui/cocoa/electron_inspectable_web_contents_view.h",
+ "shell/browser/ui/cocoa/electron_inspectable_web_contents_view.mm",
"shell/browser/ui/cocoa/electron_menu_controller.h",
"shell/browser/ui/cocoa/electron_menu_controller.mm",
"shell/browser/ui/cocoa/electron_native_widget_mac.h",
@@ -187,6 +191,8 @@ filenames = {
"shell/browser/ui/cocoa/window_buttons_proxy.mm",
"shell/browser/ui/drag_util_mac.mm",
"shell/browser/ui/file_dialog_mac.mm",
+ "shell/browser/ui/inspectable_web_contents_view_mac.h",
+ "shell/browser/ui/inspectable_web_contents_view_mac.mm",
"shell/browser/ui/message_box_mac.mm",
"shell/browser/ui/tray_icon_cocoa.h",
"shell/browser/ui/tray_icon_cocoa.mm",
@@ -202,7 +208,6 @@ filenames = {
"shell/common/node_bindings_mac.cc",
"shell/common/node_bindings_mac.h",
"shell/common/platform_util_mac.mm",
- "shell/browser/ui/views/inspectable_web_contents_view_mac.mm",
]
lib_sources_views = [
@@ -217,6 +222,8 @@ filenames = {
"shell/browser/ui/views/electron_views_delegate.h",
"shell/browser/ui/views/frameless_view.cc",
"shell/browser/ui/views/frameless_view.h",
+ "shell/browser/ui/views/inspectable_web_contents_view_views.cc",
+ "shell/browser/ui/views/inspectable_web_contents_view_views.h",
"shell/browser/ui/views/menu_bar.cc",
"shell/browser/ui/views/menu_bar.h",
"shell/browser/ui/views/menu_delegate.cc",
diff --git a/shell/browser/api/electron_api_base_window.cc b/shell/browser/api/electron_api_base_window.cc
index 337c928889..c47fc24af1 100644
--- a/shell/browser/api/electron_api_base_window.cc
+++ b/shell/browser/api/electron_api_base_window.cc
@@ -121,6 +121,11 @@ BaseWindow::BaseWindow(gin_helper::Arguments* args,
BaseWindow::~BaseWindow() {
CloseImmediately();
+ // Destroy the native window in next tick because the native code might be
+ // iterating all windows.
+ base::SingleThreadTaskRunner::GetCurrentDefault()->DeleteSoon(
+ FROM_HERE, window_.release());
+
// Remove global reference so the JS object can be garbage collected.
self_ref_.Reset();
}
diff --git a/shell/browser/api/electron_api_web_contents_view.cc b/shell/browser/api/electron_api_web_contents_view.cc
index 092b60a7e9..a46f97d85d 100644
--- a/shell/browser/api/electron_api_web_contents_view.cc
+++ b/shell/browser/api/electron_api_web_contents_view.cc
@@ -26,14 +26,29 @@
#include "ui/views/view_class_properties.h"
#include "ui/views/widget/widget.h"
+#if BUILDFLAG(IS_MAC)
+#include "shell/browser/ui/cocoa/delayed_native_view_host.h"
+#endif
+
namespace electron::api {
WebContentsView::WebContentsView(v8::Isolate* isolate,
gin::Handle<WebContents> web_contents)
- : View(web_contents->inspectable_web_contents()->GetView()),
+#if BUILDFLAG(IS_MAC)
+ : View(new DelayedNativeViewHost(web_contents->inspectable_web_contents()
+ ->GetView()
+ ->GetNativeView())),
+#else
+ : View(web_contents->inspectable_web_contents()->GetView()->GetView()),
+#endif
web_contents_(isolate, web_contents.ToV8()),
api_web_contents_(web_contents.get()) {
+#if !BUILDFLAG(IS_MAC)
+ // On macOS the View is a newly-created |DelayedNativeViewHost| and it is our
+ // responsibility to delete it. On other platforms the View is created and
+ // managed by InspectableWebContents.
set_delete_view(false);
+#endif
view()->SetProperty(
views::kFlexBehaviorKey,
views::FlexSpecification(views::MinimumFlexSizeRule::kScaleToMinimum,
@@ -74,15 +89,8 @@ void WebContentsView::SetBorderRadius(int radius) {
void WebContentsView::ApplyBorderRadius() {
if (border_radius().has_value() && api_web_contents_ && view()->GetWidget()) {
- auto* web_view = api_web_contents_->inspectable_web_contents()
- ->GetView()
- ->contents_web_view();
-
- // WebView won't exist for offscreen rendering.
- if (web_view) {
- web_view->holder()->SetCornerRadii(
- gfx::RoundedCornersF(border_radius().value()));
- }
+ auto* view = api_web_contents_->inspectable_web_contents()->GetView();
+ view->SetCornerRadii(gfx::RoundedCornersF(border_radius().value()));
}
}
diff --git a/shell/browser/native_window_mac.mm b/shell/browser/native_window_mac.mm
index bdc02d2e1d..843f66c1ec 100644
--- a/shell/browser/native_window_mac.mm
+++ b/shell/browser/native_window_mac.mm
@@ -236,7 +236,7 @@ NativeWindowMac::NativeWindowMac(const gin_helper::Dictionary& options,
views::Widget::InitParams::TYPE_WINDOW);
params.bounds = bounds;
params.delegate = this;
- params.headless_mode = true;
+ params.type = views::Widget::InitParams::TYPE_WINDOW;
params.native_widget =
new ElectronNativeWidgetMac(this, windowType, styleMask, widget());
widget()->Init(std::move(params));
diff --git a/shell/browser/native_window_views.cc b/shell/browser/native_window_views.cc
index a5364f80e0..c5439cd0a9 100644
--- a/shell/browser/native_window_views.cc
+++ b/shell/browser/native_window_views.cc
@@ -27,6 +27,7 @@
#include "content/public/common/color_parser.h"
#include "shell/browser/api/electron_api_web_contents.h"
#include "shell/browser/ui/inspectable_web_contents.h"
+#include "shell/browser/ui/views/inspectable_web_contents_view_views.h"
#include "shell/browser/ui/views/root_view.h"
#include "shell/browser/web_contents_preferences.h"
#include "shell/browser/web_view_manager.h"
diff --git a/shell/browser/ui/cocoa/delayed_native_view_host.h b/shell/browser/ui/cocoa/delayed_native_view_host.h
new file mode 100644
index 0000000000..eb02826c2b
--- /dev/null
+++ b/shell/browser/ui/cocoa/delayed_native_view_host.h
@@ -0,0 +1,34 @@
+// Copyright (c) 2018 GitHub, Inc.
+// Use of this source code is governed by the MIT license that can be
+// found in the LICENSE file.
+
+#ifndef ELECTRON_SHELL_BROWSER_UI_COCOA_DELAYED_NATIVE_VIEW_HOST_H_
+#define ELECTRON_SHELL_BROWSER_UI_COCOA_DELAYED_NATIVE_VIEW_HOST_H_
+
+#include "ui/views/controls/native/native_view_host.h"
+
+namespace electron {
+
+// Automatically attach the native view after the NativeViewHost is attached to
+// a widget. (Attaching it directly would cause crash.)
+class DelayedNativeViewHost : public views::NativeViewHost {
+ public:
+ explicit DelayedNativeViewHost(gfx::NativeView native_view);
+ ~DelayedNativeViewHost() override;
+
+ // disable copy
+ DelayedNativeViewHost(const DelayedNativeViewHost&) = delete;
+ DelayedNativeViewHost& operator=(const DelayedNativeViewHost&) = delete;
+
+ // views::View:
+ void ViewHierarchyChanged(
+ const views::ViewHierarchyChangedDetails& details) override;
+ bool OnMousePressed(const ui::MouseEvent& event) override;
+
+ private:
+ gfx::NativeView native_view_;
+};
+
+} // namespace electron
+
+#endif // ELECTRON_SHELL_BROWSER_UI_COCOA_DELAYED_NATIVE_VIEW_HOST_H_
diff --git a/shell/browser/ui/cocoa/delayed_native_view_host.mm b/shell/browser/ui/cocoa/delayed_native_view_host.mm
new file mode 100644
index 0000000000..e8f4f0305d
--- /dev/null
+++ b/shell/browser/ui/cocoa/delayed_native_view_host.mm
@@ -0,0 +1,44 @@
+// Copyright (c) 2018 GitHub, Inc.
+// Use of this source code is governed by the MIT license that can be
+// found in the LICENSE file.
+
+#include "shell/browser/ui/cocoa/delayed_native_view_host.h"
+#include "base/apple/owned_objc.h"
+#include "shell/browser/ui/cocoa/electron_inspectable_web_contents_view.h"
+
+namespace electron {
+
+DelayedNativeViewHost::DelayedNativeViewHost(gfx::NativeView native_view)
+ : native_view_(native_view) {}
+
+DelayedNativeViewHost::~DelayedNativeViewHost() = default;
+
+void DelayedNativeViewHost::ViewHierarchyChanged(
+ const views::ViewHierarchyChangedDetails& details) {
+ // NativeViewHost doesn't expect to have children, so filter the
+ // ViewHierarchyChanged events before passing them on.
+ if (details.child == this) {
+ NativeViewHost::ViewHierarchyChanged(details);
+ if (details.is_add && GetWidget() && !native_view())
+ Attach(native_view_);
+ }
+}
+
+bool DelayedNativeViewHost::OnMousePressed(const ui::MouseEvent& ui_event) {
+ // NativeViewHost::OnMousePressed normally isn't called, but
+ // NativeWidgetMacNSWindow specifically carves out an event here for
+ // right-mouse-button clicks. We want to forward them to the web content, so
+ // handle them here.
+ // See:
+ // https://source.chromium.org/chromium/chromium/src/+/main:components/remote_cocoa/app_shim/native_widget_mac_nswindow.mm;l=415-421;drc=a5af91924bafb85426e091c6035801990a6dc697
+
+ ElectronInspectableWebContentsView* inspectable_web_contents_view =
+ (ElectronInspectableWebContentsView*)native_view_.GetNativeNSView();
+ [inspectable_web_contents_view
+ redispatchContextMenuEvent:base::apple::OwnedNSEvent(
+ ui_event.native_event())];
+
+ return true;
+}
+
+} // namespace electron
diff --git a/shell/browser/ui/cocoa/electron_inspectable_web_contents_view.h b/shell/browser/ui/cocoa/electron_inspectable_web_contents_view.h
new file mode 100644
index 0000000000..677e76db2a
--- /dev/null
+++ b/shell/browser/ui/cocoa/electron_inspectable_web_contents_view.h
@@ -0,0 +1,56 @@
+// Copyright (c) 2014 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE-CHROMIUM file.
+
+#ifndef ELECTRON_SHELL_BROWSER_UI_COCOA_ELECTRON_INSPECTABLE_WEB_CONTENTS_VIEW_H_
+#define ELECTRON_SHELL_BROWSER_UI_COCOA_ELECTRON_INSPECTABLE_WEB_CONTENTS_VIEW_H_
+
+#import <AppKit/AppKit.h>
+
+#include "base/apple/owned_objc.h"
+#include "base/memory/raw_ptr.h"
+#include "chrome/browser/devtools/devtools_contents_resizing_strategy.h"
+#include "ui/base/cocoa/base_view.h"
+
+namespace electron {
+class InspectableWebContentsViewMac;
+}
+
+using electron::InspectableWebContentsViewMac;
+
+@interface NSView (WebContentsView)
+- (void)setMouseDownCanMoveWindow:(BOOL)can_move;
+@end
+
+@interface ElectronInspectableWebContentsView : BaseView <NSWindowDelegate> {
+ @private
+ raw_ptr<electron::InspectableWebContentsViewMac> inspectableWebContentsView_;
+
+ NSView* __strong fake_view_;
+ NSWindow* __strong devtools_window_;
+ BOOL devtools_visible_;
+ BOOL devtools_docked_;
+ BOOL devtools_is_first_responder_;
+ BOOL attached_to_window_;
+
+ DevToolsContentsResizingStrategy strategy_;
+}
+
+- (instancetype)initWithInspectableWebContentsViewMac:
+ (InspectableWebContentsViewMac*)view;
+- (void)notifyDevToolsFocused;
+- (void)setCornerRadii:(CGFloat)cornerRadius;
+- (void)setDevToolsVisible:(BOOL)visible activate:(BOOL)activate;
+- (BOOL)isDevToolsVisible;
+- (BOOL)isDevToolsFocused;
+- (void)setIsDocked:(BOOL)docked activate:(BOOL)activate;
+- (void)setContentsResizingStrategy:
+ (const DevToolsContentsResizingStrategy&)strategy;
+- (void)setTitle:(NSString*)title;
+- (NSString*)getTitle;
+
+- (void)redispatchContextMenuEvent:(base::apple::OwnedNSEvent)theEvent;
+
+@end
+
+#endif // ELECTRON_SHELL_BROWSER_UI_COCOA_ELECTRON_INSPECTABLE_WEB_CONTENTS_VIEW_H_
diff --git a/shell/browser/ui/cocoa/electron_inspectable_web_contents_view.mm b/shell/browser/ui/cocoa/electron_inspectable_web_contents_view.mm
new file mode 100644
index 0000000000..9ac5e737b5
--- /dev/null
+++ b/shell/browser/ui/cocoa/electron_inspectable_web_contents_view.mm
@@ -0,0 +1,352 @@
+// Copyright (c) 2014 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE-CHROMIUM file.
+
+#include "shell/browser/ui/cocoa/electron_inspectable_web_contents_view.h"
+
+#include "content/public/browser/render_widget_host_view.h"
+#include "shell/browser/api/electron_api_web_contents.h"
+#include "shell/browser/ui/cocoa/event_dispatching_window.h"
+#include "shell/browser/ui/inspectable_web_contents.h"
+#include "shell/browser/ui/inspectable_web_contents_view_delegate.h"
+#include "shell/browser/ui/inspectable_web_contents_view_mac.h"
+#include "ui/base/cocoa/base_view.h"
+#include "ui/gfx/mac/scoped_cocoa_disable_screen_updates.h"
+
+@implementation ElectronInspectableWebContentsView
+
+- (instancetype)initWithInspectableWebContentsViewMac:
+ (InspectableWebContentsViewMac*)view {
+ self = [super init];
+ if (!self)
+ return nil;
+
+ inspectableWebContentsView_ = view;
+ devtools_visible_ = NO;
+ devtools_docked_ = NO;
+ devtools_is_first_responder_ = NO;
+ attached_to_window_ = NO;
+
+ if (inspectableWebContentsView_->inspectable_web_contents()->is_guest()) {
+ fake_view_ = [[NSView alloc] init];
+ [fake_view_ setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
+ [self addSubview:fake_view_];
+ } else {
+ auto* contents = inspectableWebContentsView_->inspectable_web_contents()
+ ->GetWebContents();
+ auto* contentsView = contents->GetNativeView().GetNativeNSView();
+ [contentsView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
+ [self addSubview:contentsView];
+ }
+
+ // See https://code.google.com/p/chromium/issues/detail?id=348490.
+ [self setWantsLayer:YES];
+
+ return self;
+}
+
+- (void)dealloc {
+ [[NSNotificationCenter defaultCenter] removeObserver:self];
+}
+
+- (void)resizeSubviewsWithOldSize:(NSSize)oldBoundsSize {
+ [self adjustSubviews];
+}
+
+- (void)viewDidMoveToWindow {
+ if (attached_to_window_ && !self.window) {
+ attached_to_window_ = NO;
+ [[NSNotificationCenter defaultCenter] removeObserver:self];
+ } else if (!attached_to_window_ && self.window) {
+ attached_to_window_ = YES;
+ [[NSNotificationCenter defaultCenter]
+ addObserver:self
+ selector:@selector(viewDidBecomeFirstResponder:)
+ name:kViewDidBecomeFirstResponder
+ object:nil];
+ [[NSNotificationCenter defaultCenter]
+ addObserver:self
+ selector:@selector(parentWindowBecameMain:)
+ name:NSWindowDidBecomeMainNotification
+ object:nil];
+ }
+}
+
+- (IBAction)showDevTools:(id)sender {
+ inspectableWebContentsView_->inspectable_web_contents()->ShowDevTools(true);
+}
+
+- (void)notifyDevToolsFocused {
+ if (inspectableWebContentsView_->GetDelegate())
+ inspectableWebContentsView_->GetDelegate()->DevToolsFocused();
+}
+
+- (void)setCornerRadii:(CGFloat)cornerRadius {
+ auto* inspectable_web_contents =
+ inspectableWebContentsView_->inspectable_web_contents();
+ DCHECK(inspectable_web_contents);
+ auto* webContents = inspectable_web_contents->GetWebContents();
+ if (!webContents)
+ return;
+ auto* webContentsView = webContents->GetNativeView().GetNativeNSView();
+ webContentsView.wantsLayer = YES;
+ webContentsView.layer.cornerRadius = cornerRadius;
+}
+
+- (void)notifyDevToolsResized {
+ // When devtools is opened, resizing devtools would not trigger
+ // UpdateDraggableRegions for WebContents, so we have to notify the window
+ // to do an update of draggable regions.
+ if (inspectableWebContentsView_->GetDelegate())
+ inspectableWebContentsView_->GetDelegate()->DevToolsResized();
+}
+
+- (void)setDevToolsVisible:(BOOL)visible activate:(BOOL)activate {
+ if (visible == devtools_visible_)
+ return;
+
+ auto* inspectable_web_contents =
+ inspectableWebContentsView_->inspectable_web_contents();
+ auto* devToolsWebContents =
+ inspectable_web_contents->GetDevToolsWebContents();
+ auto* devToolsView = devToolsWebContents->GetNativeView().GetNativeNSView();
+
+ devtools_visible_ = visible;
+ if (devtools_docked_) {
+ if (visible) {
+ // Place the devToolsView under contentsView, notice that we didn't set
+ // sizes for them until the setContentsResizingStrategy message.
+ [self addSubview:devToolsView positioned:NSWindowBelow relativeTo:nil];
+ [self adjustSubviews];
+
+ // Focus on web view.
+ devToolsWebContents->RestoreFocus();
+ } else {
+ gfx::ScopedCocoaDisableScreenUpdates disabler;
+ [devToolsView removeFromSuperview];
+ [self adjustSubviews];
+ [self notifyDevToolsResized];
+ }
+ } else {
+ if (visible) {
+ if (activate) {
+ [devtools_window_ makeKeyAndOrderFront:nil];
+ } else {
+ [devtools_window_ orderBack:nil];
+ }
+ } else {
+ [devtools_window_ setDelegate:nil];
+ [devtools_window_ close];
+ devtools_window_ = nil;
+ }
+ }
+}
+
+- (BOOL)isDevToolsVisible {
+ return devtools_visible_;
+}
+
+- (BOOL)isDevToolsFocused {
+ if (devtools_docked_) {
+ return [[self window] isKeyWindow] && devtools_is_first_responder_;
+ } else {
+ return [devtools_window_ isKeyWindow];
+ }
+}
+
+- (void)setIsDocked:(BOOL)docked activate:(BOOL)activate {
+ // Revert to no-devtools state.
+ [self setDevToolsVisible:NO activate:NO];
+
+ // Switch to new state.
+ devtools_docked_ = docked;
+ auto* inspectable_web_contents =
+ inspectableWebContentsView_->inspectable_web_contents();
+ auto* devToolsWebContents =
+ inspectable_web_contents->GetDevToolsWebContents();
+ auto devToolsView = devToolsWebContents->GetNativeView().GetNativeNSView();
+ if (!docked) {
+ auto styleMask = NSWindowStyleMaskTitled | NSWindowStyleMaskClosable |
+ NSWindowStyleMaskMiniaturizable |
+ NSWindowStyleMaskResizable |
+ NSWindowStyleMaskTexturedBackground |
+ NSWindowStyleMaskUnifiedTitleAndToolbar;
+ devtools_window_ = [[EventDispatchingWindow alloc]
+ initWithContentRect:NSMakeRect(0, 0, 800, 600)
+ styleMask:styleMask
+ backing:NSBackingStoreBuffered
+ defer:YES];
+ [devtools_window_ setDelegate:self];
+ [devtools_window_ setFrameAutosaveName:@"electron.devtools"];
+ [devtools_window_ setTitle:@"Developer Tools"];
+ [devtools_window_ setReleasedWhenClosed:NO];
+ [devtools_window_ setAutorecalculatesContentBorderThickness:NO
+ forEdge:NSMaxYEdge];
+ [devtools_window_ setContentBorderThickness:24 forEdge:NSMaxYEdge];
+
+ NSView* contentView = [devtools_window_ contentView];
+ devToolsView.frame = contentView.bounds;
+ devToolsView.autoresizingMask = NSViewWidthSizable | NSViewHeightSizable;
+
+ [contentView addSubview:devToolsView];
+ [devToolsView setMouseDownCanMoveWindow:NO];
+ } else {
+ [devToolsView setMouseDownCanMoveWindow:YES];
+ }
+ [self setDevToolsVisible:YES activate:activate];
+}
+
+- (void)setContentsResizingStrategy:
+ (const DevToolsContentsResizingStrategy&)strategy {
+ strategy_.CopyFrom(strategy);
+ [self adjustSubviews];
+}
+
+- (void)adjustSubviews {
+ if (![[self subviews] count])
+ return;
+
+ if (![self isDevToolsVisible] || devtools_window_) {
+ DCHECK_EQ(1u, [[self subviews] count]);
+ NSView* contents = [[self subviews] objectAtIndex:0];
+ [contents setFrame:[self bounds]];
+ return;
+ }
+
+ NSView* devToolsView = [[self subviews] objectAtIndex:0];
+ NSView* contentsView = [[self subviews] objectAtIndex:1];
+
+ DCHECK_EQ(2u, [[self subviews] count]);
+
+ gfx::Rect new_devtools_bounds;
+ gfx::Rect new_contents_bounds;
+ ApplyDevToolsContentsResizingStrategy(
+ strategy_, gfx::Size(NSSizeToCGSize([self bounds].size)),
+ &new_devtools_bounds, &new_contents_bounds);
+ [devToolsView setFrame:[self flipRectToNSRect:new_devtools_bounds]];
+ [contentsView setFrame:[self flipRectToNSRect:new_contents_bounds]];
+
+ // Move mask to the devtools area to exclude it from dragging.
+ NSRect cf = contentsView.frame;
+ NSRect sb = [self bounds];
+ NSRect devtools_frame;
+ if (cf.size.height < sb.size.height) { // bottom docked
+ devtools_frame.origin.x = 0;
+ devtools_frame.origin.y = 0;
+ devtools_frame.size.width = sb.size.width;
+ devtools_frame.size.height = sb.size.height - cf.size.height;
+ } else { // left or right docked
+ if (cf.origin.x > 0) // left docked
+ devtools_frame.origin.x = 0;
+ else // right docked.
+ devtools_frame.origin.x = cf.size.width;
+ devtools_frame.origin.y = 0;
+ devtools_frame.size.width = sb.size.width - cf.size.width;
+ devtools_frame.size.height = sb.size.height;
+ }
+
+ [self notifyDevToolsResized];
+}
+
+- (void)setTitle:(NSString*)title {
+ [devtools_window_ setTitle:title];
+}
+
+- (NSString*)getTitle {
+ return [devtools_window_ title];
+}
+
+- (void)viewDidBecomeFirstResponder:(NSNotification*)notification {
+ auto* inspectable_web_contents =
+ inspectableWebContentsView_->inspectable_web_contents();
+ DCHECK(inspectable_web_contents);
+ auto* webContents = inspectable_web_contents->GetWebContents();
+ if (!webContents)
+ return;
+ auto* webContentsView = webContents->GetNativeView().GetNativeNSView();
+
+ NSView* view = [notification object];
+ if ([[webContentsView subviews] containsObject:view]) {
+ devtools_is_first_responder_ = NO;
+ return;
+ }
+
+ auto* devToolsWebContents =
+ inspectable_web_contents->GetDevToolsWebContents();
+ if (!devToolsWebContents)
+ return;
+ auto devToolsView = devToolsWebContents->GetNativeView().GetNativeNSView();
+
+ if ([[devToolsView subviews] containsObject:view]) {
+ devtools_is_first_responder_ = YES;
+ [self notifyDevToolsFocused];
+ }
+}
+
+- (void)parentWindowBecameMain:(NSNotification*)notification {
+ NSWindow* parentWindow = [notification object];
+ if ([self window] == parentWindow && devtools_docked_ &&
+ devtools_is_first_responder_)
+ [self notifyDevToolsFocused];
+}
+
+- (void)redispatchContextMenuEvent:(base::apple::OwnedNSEvent)event {
+ DCHECK(event.Get().type == NSEventTypeRightMouseDown ||
+ (event.Get().type == NSEventTypeLeftMouseDown &&
+ (event.Get().modifierFlags & NSEventModifierFlagControl)));
+ content::WebContents* contents =
+ inspectableWebContentsView_->inspectable_web_contents()->GetWebContents();
+ electron::api::WebContents* api_contents =
+ electron::api::WebContents::From(contents);
+ if (api_contents) {
+ // Temporarily pretend that the WebContents is fully non-draggable while we
+ // re-send the mouse event. This allows the re-dispatched event to "land"
+ // on the WebContents, instead of "falling through" back to the window.
+ auto* rwhv = contents->GetRenderWidgetHostView();
+ if (rwhv) {
+ api_contents->SetForceNonDraggable(true);
+ BaseView* contentsView =
+ (BaseView*)rwhv->GetNativeView().GetNativeNSView();
+ [contentsView mouseEvent:event.Get()];
+ api_contents->SetForceNonDraggable(false);
+ }
+ }
+}
+
+#pragma mark - NSWindowDelegate
+
+- (void)windowWillClose:(NSNotification*)notification {
+ inspectableWebContentsView_->inspectable_web_contents()->CloseDevTools();
+}
+
+- (void)windowDidBecomeMain:(NSNotification*)notification {
+ content::WebContents* web_contents =
+ inspectableWebContentsView_->inspectable_web_contents()
+ ->GetDevToolsWebContents();
+ if (!web_contents)
+ return;
+
+ web_contents->RestoreFocus();
+
+ content::RenderWidgetHostView* rwhv = web_contents->GetRenderWidgetHostView();
+ if (rwhv)
+ rwhv->SetActive(true);
+
+ [self notifyDevToolsFocused];
+}
+
+- (void)windowDidResignMain:(NSNotification*)notification {
+ content::WebContents* web_contents =
+ inspectableWebContentsView_->inspectable_web_contents()
+ ->GetDevToolsWebContents();
+ if (!web_contents)
+ return;
+
+ web_contents->StoreFocus();
+
+ content::RenderWidgetHostView* rwhv = web_contents->GetRenderWidgetHostView();
+ if (rwhv)
+ rwhv->SetActive(false);
+}
+
+@end
diff --git a/shell/browser/ui/cocoa/electron_ns_window.mm b/shell/browser/ui/cocoa/electron_ns_window.mm
index 96d29893e0..17adef63de 100644
--- a/shell/browser/ui/cocoa/electron_ns_window.mm
+++ b/shell/browser/ui/cocoa/electron_ns_window.mm
@@ -200,11 +200,6 @@ void SwizzleSwipeWithEvent(NSView* view, SEL swiz_selector) {
}
- (NSRect)constrainFrameRect:(NSRect)frameRect toScreen:(NSScreen*)screen {
- // We initialize the window in headless mode to allow painting before it is
- // shown, but we don't want the headless behavior of allowing the window to be
- // placed unconstrained.
- self.isHeadless = false;
-
// Resizing is disabled.
if (electron::ScopedDisableResize::IsResizeDisabled())
return [self frame];
diff --git a/shell/browser/ui/inspectable_web_contents.cc b/shell/browser/ui/inspectable_web_contents.cc
index 2acff1b4c0..29a37d0d55 100644
--- a/shell/browser/ui/inspectable_web_contents.cc
+++ b/shell/browser/ui/inspectable_web_contents.cc
@@ -297,6 +297,11 @@ class InspectableWebContents::NetworkResourceLoader
base::TimeDelta retry_delay_;
};
+// Implemented separately on each platform.
+InspectableWebContentsView* CreateInspectableContentsView(
+ InspectableWebContents* inspectable_web_contents);
+
+// static
// static
void InspectableWebContents::RegisterPrefs(PrefRegistrySimple* registry) {
registry->RegisterDictionaryPref(kDevToolsBoundsPref,
@@ -312,7 +317,7 @@ InspectableWebContents::InspectableWebContents(
: pref_service_(pref_service),
web_contents_(std::move(web_contents)),
is_guest_(is_guest),
- view_(new InspectableWebContentsView(this)) {
+ view_(CreateInspectableContentsView(this)) {
const base::Value* bounds_dict =
&pref_service_->GetValue(kDevToolsBoundsPref);
if (bounds_dict->is_dict()) {
diff --git a/shell/browser/ui/inspectable_web_contents_view.cc b/shell/browser/ui/inspectable_web_contents_view.cc
index 2d21a8beb5..946b5071bc 100644
--- a/shell/browser/ui/inspectable_web_contents_view.cc
+++ b/shell/browser/ui/inspectable_web_contents_view.cc
@@ -5,234 +5,12 @@
#include "shell/browser/ui/inspectable_web_contents_view.h"
-#include <memory>
-#include <utility>
-
-#include "base/memory/raw_ptr.h"
-#include "shell/browser/ui/drag_util.h"
-#include "shell/browser/ui/inspectable_web_contents.h"
-#include "shell/browser/ui/inspectable_web_contents_delegate.h"
-#include "shell/browser/ui/inspectable_web_contents_view_delegate.h"
-#include "ui/base/models/image_model.h"
-#include "ui/views/controls/label.h"
-#include "ui/views/controls/webview/webview.h"
-#include "ui/views/widget/widget.h"
-#include "ui/views/widget/widget_delegate.h"
-#include "ui/views/window/client_view.h"
-
namespace electron {
-namespace {
-
-class DevToolsWindowDelegate : public views::ClientView,
- public views::WidgetDelegate {
- public:
- DevToolsWindowDelegate(InspectableWebContentsView* shell,
- views::View* view,
- views::Widget* widget)
- : views::ClientView(widget, view),
- shell_(shell),
- view_(view),
- widget_(widget) {
- SetOwnedByWidget(true);
- set_owned_by_client();
-
- if (shell->GetDelegate())
- icon_ = shell->GetDelegate()->GetDevToolsWindowIcon();
- }
- ~DevToolsWindowDelegate() override = default;
-
- // disable copy
- DevToolsWindowDelegate(const DevToolsWindowDelegate&) = delete;
- DevToolsWindowDelegate& operator=(const DevToolsWindowDelegate&) = delete;
-
- // views::WidgetDelegate:
- views::View* GetInitiallyFocusedView() override { return view_; }
- std::u16string GetWindowTitle() const override { return shell_->GetTitle(); }
- ui::ImageModel GetWindowAppIcon() override { return GetWindowIcon(); }
- ui::ImageModel GetWindowIcon() override { return icon_; }
- views::Widget* GetWidget() override { return widget_; }
- const views::Widget* GetWidget() const override { return widget_; }
- views::View* GetContentsView() override { return view_; }
- views::ClientView* CreateClientView(views::Widget* widget) override {
- return this;
- }
-
- // views::ClientView:
- views::CloseRequestResult OnWindowCloseRequested() override {
- shell_->inspectable_web_contents()->CloseDevTools();
- return views::CloseRequestResult::kCannotClose;
- }
-
- private:
- raw_ptr<InspectableWebContentsView> shell_;
- raw_ptr<views::View> view_;
- raw_ptr<views::Widget> widget_;
- ui::ImageModel icon_;
-};
-
-} // namespace
-
InspectableWebContentsView::InspectableWebContentsView(
InspectableWebContents* inspectable_web_contents)
- : inspectable_web_contents_(inspectable_web_contents),
- devtools_web_view_(new views::WebView(nullptr)),
- title_(u"Developer Tools") {
- if (!inspectable_web_contents_->is_guest() &&
- inspectable_web_contents_->GetWebContents()->GetNativeView()) {
- auto* contents_web_view = new views::WebView(nullptr);
- contents_web_view->SetWebContents(
- inspectable_web_contents_->GetWebContents());
- contents_view_ = contents_web_view_ = contents_web_view;
- } else {
- contents_view_ = new views::Label(u"No content under offscreen mode");
- }
-
- devtools_web_view_->SetVisible(false);
- AddChildView(devtools_web_view_.get());
- AddChildView(contents_view_.get());
-}
-
-InspectableWebContentsView::~InspectableWebContentsView() {
- if (devtools_window_)
- inspectable_web_contents()->SaveDevToolsBounds(
- devtools_window_->GetWindowBoundsInScreen());
-}
-
-void InspectableWebContentsView::ShowDevTools(bool activate) {
- if (devtools_visible_)
- return;
-
- devtools_visible_ = true;
- if (devtools_window_) {
- devtools_window_web_view_->SetWebContents(
- inspectable_web_contents_->GetDevToolsWebContents());
- devtools_window_->SetBounds(inspectable_web_contents()->dev_tools_bounds());
- if (activate) {
- devtools_window_->Show();
- } else {
- devtools_window_->ShowInactive();
- }
-
- // Update draggable regions to account for the new dock position.
- if (GetDelegate())
- GetDelegate()->DevToolsResized();
- } else {
- devtools_web_view_->SetVisible(true);
- devtools_web_view_->SetWebContents(
- inspectable_web_contents_->GetDevToolsWebContents());
- devtools_web_view_->RequestFocus();
- DeprecatedLayoutImmediately();
- }
-}
-
-void InspectableWebContentsView::CloseDevTools() {
- if (!devtools_visible_)
- return;
-
- devtools_visible_ = false;
- if (devtools_window_) {
- auto save_bounds = devtools_window_->IsMinimized()
- ? devtools_window_->GetRestoredBounds()
- : devtools_window_->GetWindowBoundsInScreen();
- inspectable_web_contents()->SaveDevToolsBounds(save_bounds);
-
- devtools_window_.reset();
- devtools_window_web_view_ = nullptr;
- devtools_window_delegate_ = nullptr;
- } else {
- devtools_web_view_->SetVisible(false);
- devtools_web_view_->SetWebContents(nullptr);
- DeprecatedLayoutImmediately();
- }
-}
-
-bool InspectableWebContentsView::IsDevToolsViewShowing() {
- return devtools_visible_;
-}
-
-bool InspectableWebContentsView::IsDevToolsViewFocused() {
- if (devtools_window_web_view_)
- return devtools_window_web_view_->HasFocus();
- else if (devtools_web_view_)
- return devtools_web_view_->HasFocus();
- else
- return false;
-}
-
-void InspectableWebContentsView::SetIsDocked(bool docked, bool activate) {
- CloseDevTools();
-
- if (!docked) {
- devtools_window_ = std::make_unique<views::Widget>();
- devtools_window_web_view_ = new views::WebView(nullptr);
- devtools_window_delegate_ = new DevToolsWindowDelegate(
- this, devtools_window_web_view_, devtools_window_.get());
-
- views::Widget::InitParams params{
- views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET};
- params.delegate = devtools_window_delegate_;
- params.bounds = inspectable_web_contents()->dev_tools_bounds();
-
-#if BUILDFLAG(IS_LINUX)
- params.wm_role_name = "devtools";
- if (GetDelegate())
- GetDelegate()->GetDevToolsWindowWMClass(¶ms.wm_class_name,
- ¶ms.wm_class_class);
-#endif
-
- devtools_window_->Init(std::move(params));
- devtools_window_->UpdateWindowIcon();
- devtools_window_->widget_delegate()->SetHasWindowSizeControls(true);
- }
-
- ShowDevTools(activate);
-}
-
-void InspectableWebContentsView::SetContentsResizingStrategy(
- const DevToolsContentsResizingStrategy& strategy) {
- strategy_.CopyFrom(strategy);
- DeprecatedLayoutImmediately();
-}
-
-void InspectableWebContentsView::SetTitle(const std::u16string& title) {
- if (devtools_window_) {
- title_ = title;
- devtools_window_->UpdateWindowTitle();
- }
-}
-
-const std::u16string InspectableWebContentsView::GetTitle() {
- return title_;
-}
-
-void InspectableWebContentsView::Layout(PassKey) {
- if (!devtools_web_view_->GetVisible()) {
- contents_view_->SetBoundsRect(GetContentsBounds());
- // Propagate layout call to all children, for example browser views.
- LayoutSuperclass<View>(this);
- return;
- }
-
- gfx::Size container_size(width(), height());
- gfx::Rect new_devtools_bounds;
- gfx::Rect new_contents_bounds;
- ApplyDevToolsContentsResizingStrategy(
- strategy_, container_size, &new_devtools_bounds, &new_contents_bounds);
-
- // DevTools cares about the specific position, so we have to compensate RTL
- // layout here.
- new_devtools_bounds.set_x(GetMirroredXForRect(new_devtools_bounds));
- new_contents_bounds.set_x(GetMirroredXForRect(new_contents_bounds));
-
- devtools_web_view_->SetBoundsRect(new_devtools_bounds);
- contents_view_->SetBoundsRect(new_contents_bounds);
-
- // Propagate layout call to all children, for example browser views.
- LayoutSuperclass<View>(this);
+ : inspectable_web_contents_(inspectable_web_contents) {}
- if (GetDelegate())
- GetDelegate()->DevToolsResized();
-}
+InspectableWebContentsView::~InspectableWebContentsView() = default;
} // namespace electron
diff --git a/shell/browser/ui/inspectable_web_contents_view.h b/shell/browser/ui/inspectable_web_contents_view.h
index bd279b4ae0..f7bb542743 100644
--- a/shell/browser/ui/inspectable_web_contents_view.h
+++ b/shell/browser/ui/inspectable_web_contents_view.h
@@ -9,74 +9,66 @@
#include <string>
#include "base/memory/raw_ptr.h"
-#include "chrome/browser/devtools/devtools_contents_resizing_strategy.h"
#include "electron/shell/common/api/api.mojom.h"
+#include "ui/gfx/geometry/rounded_corners_f.h"
#include "ui/gfx/native_widget_types.h"
-#include "ui/views/view.h"
class DevToolsContentsResizingStrategy;
+
+#if defined(TOOLKIT_VIEWS)
namespace views {
+class View;
class WebView;
-class Widget;
-class WidgetDelegate;
} // namespace views
+#endif
namespace electron {
class InspectableWebContents;
class InspectableWebContentsViewDelegate;
-class InspectableWebContentsView : public views::View {
+class InspectableWebContentsView {
public:
explicit InspectableWebContentsView(
InspectableWebContents* inspectable_web_contents);
- ~InspectableWebContentsView() override;
+ virtual ~InspectableWebContentsView();
InspectableWebContents* inspectable_web_contents() {
return inspectable_web_contents_;
}
- views::WebView* contents_web_view() const { return contents_web_view_; }
-
// The delegate manages its own life.
void SetDelegate(InspectableWebContentsViewDelegate* delegate) {
delegate_ = delegate;
}
InspectableWebContentsViewDelegate* GetDelegate() const { return delegate_; }
- void ShowDevTools(bool activate);
- void CloseDevTools();
- bool IsDevToolsViewShowing();
- bool IsDevToolsViewFocused();
- void SetIsDocked(bool docked, bool activate);
- void SetContentsResizingStrategy(
- const DevToolsContentsResizingStrategy& strategy);
- void SetTitle(const std::u16string& title);
- const std::u16string GetTitle();
-
- // views::View:
- void Layout(PassKey) override;
-#if BUILDFLAG(IS_MAC)
- bool OnMousePressed(const ui::MouseEvent& event) override;
+#if defined(TOOLKIT_VIEWS) && !BUILDFLAG(IS_MAC)
+ // Returns the container control, which has devtools view attached.
+ virtual views::View* GetView() = 0;
+#else
+ virtual gfx::NativeView GetNativeView() const = 0;
#endif
- private:
+ virtual void ShowDevTools(bool activate) = 0;
+ virtual void SetCornerRadii(const gfx::RoundedCornersF& corner_radii) = 0;
+ // Hide the DevTools view.
+ virtual void CloseDevTools() = 0;
+ virtual bool IsDevToolsViewShowing() = 0;
+ virtual bool IsDevToolsViewFocused() = 0;
+ virtual void SetIsDocked(bool docked, bool activate) = 0;
+ virtual void SetContentsResizingStrategy(
+ const DevToolsContentsResizingStrategy& strategy) = 0;
+ virtual void SetTitle(const std::u16string& title) = 0;
+ virtual const std::u16string GetTitle() = 0;
+
+ protected:
// Owns us.
raw_ptr<InspectableWebContents> inspectable_web_contents_;
+ private:
raw_ptr<InspectableWebContentsViewDelegate> delegate_ =
nullptr; // weak references.
-
- std::unique_ptr<views::Widget> devtools_window_;
- raw_ptr<views::WebView> devtools_window_web_view_ = nullptr;
- raw_ptr<views::WebView> devtools_web_view_ = nullptr;
- raw_ptr<views::WebView> contents_web_view_ = nullptr;
- raw_ptr<views::View> contents_view_ = nullptr;
-
- DevToolsContentsResizingStrategy strategy_;
- bool devtools_visible_ = false;
- raw_ptr<views::WidgetDelegate> devtools_window_delegate_ = nullptr;
- std::u16string title_;
};
} // namespace electron
diff --git a/shell/browser/ui/inspectable_web_contents_view_mac.h b/shell/browser/ui/inspectable_web_contents_view_mac.h
new file mode 100644
index 0000000000..88b4078614
--- /dev/null
+++ b/shell/browser/ui/inspectable_web_contents_view_mac.h
@@ -0,0 +1,42 @@
+// Copyright (c) 2012 The Chromium Authors. All rights reserved.
+// Copyright (c) 2013 Adam Roben <[email protected]>. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE-CHROMIUM file.
+
+#ifndef ELECTRON_SHELL_BROWSER_UI_INSPECTABLE_WEB_CONTENTS_VIEW_MAC_H_
+#define ELECTRON_SHELL_BROWSER_UI_INSPECTABLE_WEB_CONTENTS_VIEW_MAC_H_
+
+#include "shell/browser/ui/inspectable_web_contents_view.h"
+
+@class ElectronInspectableWebContentsView;
+
+namespace electron {
+
+class InspectableWebContentsViewMac : public InspectableWebContentsView {
+ public:
+ explicit InspectableWebContentsViewMac(
+ InspectableWebContents* inspectable_web_contents);
+ InspectableWebContentsViewMac(const InspectableWebContentsViewMac&) = delete;
+ InspectableWebContentsViewMac& operator=(
+ const InspectableWebContentsViewMac&) = delete;
+ ~InspectableWebContentsViewMac() override;
+
+ gfx::NativeView GetNativeView() const override;
+ void SetCornerRadii(const gfx::RoundedCornersF& corner_radii) override;
+ void ShowDevTools(bool activate) override;
+ void CloseDevTools() override;
+ bool IsDevToolsViewShowing() override;
+ bool IsDevToolsViewFocused() override;
+ void SetIsDocked(bool docked, bool activate) override;
+ void SetContentsResizingStrategy(
+ const DevToolsContentsResizingStrategy& strategy) override;
+ void SetTitle(const std::u16string& title) override;
+ const std::u16string GetTitle() override;
+
+ private:
+ ElectronInspectableWebContentsView* __strong view_;
+};
+
+} // namespace electron
+
+#endif // ELECTRON_SHELL_BROWSER_UI_INSPECTABLE_WEB_CONTENTS_VIEW_MAC_H_
diff --git a/shell/browser/ui/inspectable_web_contents_view_mac.mm b/shell/browser/ui/inspectable_web_contents_view_mac.mm
new file mode 100644
index 0000000000..091dc01731
--- /dev/null
+++ b/shell/browser/ui/inspectable_web_contents_view_mac.mm
@@ -0,0 +1,74 @@
+// Copyright (c) 2012 The Chromium Authors. All rights reserved.
+// Copyright (c) 2013 Adam Roben <[email protected]>. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE-CHROMIUM file.
+
+#include "shell/browser/ui/inspectable_web_contents_view_mac.h"
+
+#include "base/strings/sys_string_conversions.h"
+#import "shell/browser/ui/cocoa/electron_inspectable_web_contents_view.h"
+#include "shell/browser/ui/inspectable_web_contents.h"
+#include "shell/browser/ui/inspectable_web_contents_view_delegate.h"
+
+namespace electron {
+
+InspectableWebContentsView* CreateInspectableContentsView(
+ InspectableWebContents* inspectable_web_contents) {
+ return new InspectableWebContentsViewMac(inspectable_web_contents);
+}
+
+InspectableWebContentsViewMac::InspectableWebContentsViewMac(
+ InspectableWebContents* inspectable_web_contents)
+ : InspectableWebContentsView(inspectable_web_contents),
+ view_([[ElectronInspectableWebContentsView alloc]
+ initWithInspectableWebContentsViewMac:this]) {}
+
+InspectableWebContentsViewMac::~InspectableWebContentsViewMac() {
+ [[NSNotificationCenter defaultCenter] removeObserver:view_];
+ CloseDevTools();
+}
+
+gfx::NativeView InspectableWebContentsViewMac::GetNativeView() const {
+ return view_;
+}
+
+void InspectableWebContentsViewMac::SetCornerRadii(
+ const gfx::RoundedCornersF& corner_radii) {
+ // We can assume all four values are identical.
+ [view_ setCornerRadii:corner_radii.upper_left()];
+}
+
+void InspectableWebContentsViewMac::ShowDevTools(bool activate) {
+ [view_ setDevToolsVisible:YES activate:activate];
+}
+
+void InspectableWebContentsViewMac::CloseDevTools() {
+ [view_ setDevToolsVisible:NO activate:NO];
+}
+
+bool InspectableWebContentsViewMac::IsDevToolsViewShowing() {
+ return [view_ isDevToolsVisible];
+}
+
+bool InspectableWebContentsViewMac::IsDevToolsViewFocused() {
+ return [view_ isDevToolsFocused];
+}
+
+void InspectableWebContentsViewMac::SetIsDocked(bool docked, bool activate) {
+ [view_ setIsDocked:docked activate:activate];
+}
+
+void InspectableWebContentsViewMac::SetContentsResizingStrategy(
+ const DevToolsContentsResizingStrategy& strategy) {
+ [view_ setContentsResizingStrategy:strategy];
+}
+
+void InspectableWebContentsViewMac::SetTitle(const std::u16string& title) {
+ [view_ setTitle:base::SysUTF16ToNSString(title)];
+}
+
+const std::u16string InspectableWebContentsViewMac::GetTitle() {
+ return base::SysNSStringToUTF16([view_ getTitle]);
+}
+
+} // namespace electron
diff --git a/shell/browser/ui/views/inspectable_web_contents_view_mac.mm b/shell/browser/ui/views/inspectable_web_contents_view_mac.mm
deleted file mode 100644
index a98af7cf18..0000000000
--- a/shell/browser/ui/views/inspectable_web_contents_view_mac.mm
+++ /dev/null
@@ -1,34 +0,0 @@
-// Copyright (c) 2022 Salesforce, Inc.
-// Use of this source code is governed by the MIT license that can be
-// found in the LICENSE file.
-
-#include "shell/browser/ui/inspectable_web_contents_view.h"
-
-#include "content/public/browser/render_widget_host_view.h"
-#include "content/public/browser/web_contents.h"
-#include "shell/browser/api/electron_api_web_contents.h"
-#include "ui/base/cocoa/base_view.h"
-
-namespace electron {
-
-bool InspectableWebContentsView::OnMousePressed(const ui::MouseEvent& event) {
- DCHECK(event.IsRightMouseButton() ||
- (event.IsLeftMouseButton() && event.IsControlDown()));
- content::WebContents* contents = inspectable_web_contents()->GetWebContents();
- electron::api::WebContents* api_contents =
- electron::api::WebContents::From(contents);
- if (api_contents) {
- // Temporarily pretend that the WebContents is fully non-draggable while we
- // re-send the mouse event. This allows the re-dispatched event to "land"
- // on the WebContents, instead of "falling through" back to the window.
- api_contents->SetForceNonDraggable(true);
- BaseView* contentsView = (BaseView*)contents->GetRenderWidgetHostView()
- ->GetNativeView()
- .GetNativeNSView();
- [contentsView mouseEvent:event.native_event().Get()];
- api_contents->SetForceNonDraggable(false);
- }
- return true;
-}
-
-} // namespace electron
diff --git a/shell/browser/ui/views/inspectable_web_contents_view_views.cc b/shell/browser/ui/views/inspectable_web_contents_view_views.cc
new file mode 100644
index 0000000000..8180401283
--- /dev/null
+++ b/shell/browser/ui/views/inspectable_web_contents_view_views.cc
@@ -0,0 +1,257 @@
+// Copyright (c) 2014 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE-CHROMIUM file.
+
+#include "shell/browser/ui/views/inspectable_web_contents_view_views.h"
+
+#include <memory>
+#include <utility>
+
+#include "base/memory/raw_ptr.h"
+#include "base/strings/utf_string_conversions.h"
+#include "shell/browser/ui/drag_util.h"
+#include "shell/browser/ui/inspectable_web_contents.h"
+#include "shell/browser/ui/inspectable_web_contents_delegate.h"
+#include "shell/browser/ui/inspectable_web_contents_view_delegate.h"
+#include "ui/base/models/image_model.h"
+#include "ui/views/controls/label.h"
+#include "ui/views/controls/webview/webview.h"
+#include "ui/views/widget/widget.h"
+#include "ui/views/widget/widget_delegate.h"
+#include "ui/views/window/client_view.h"
+
+namespace electron {
+
+namespace {
+
+class DevToolsWindowDelegate : public views::ClientView,
+ public views::WidgetDelegate {
+ public:
+ DevToolsWindowDelegate(InspectableWebContentsViewViews* shell,
+ views::View* view,
+ views::Widget* widget)
+ : views::ClientView(widget, view),
+ shell_(shell),
+ view_(view),
+ widget_(widget) {
+ SetOwnedByWidget(true);
+ set_owned_by_client();
+
+ if (shell->GetDelegate())
+ icon_ = shell->GetDelegate()->GetDevToolsWindowIcon();
+ }
+ ~DevToolsWindowDelegate() override = default;
+
+ // disable copy
+ DevToolsWindowDelegate(const DevToolsWindowDelegate&) = delete;
+ DevToolsWindowDelegate& operator=(const DevToolsWindowDelegate&) = delete;
+
+ // views::WidgetDelegate:
+ views::View* GetInitiallyFocusedView() override { return view_; }
+ std::u16string GetWindowTitle() const override { return shell_->GetTitle(); }
+ ui::ImageModel GetWindowAppIcon() override { return GetWindowIcon(); }
+ ui::ImageModel GetWindowIcon() override { return icon_; }
+ views::Widget* GetWidget() override { return widget_; }
+ const views::Widget* GetWidget() const override { return widget_; }
+ views::View* GetContentsView() override { return view_; }
+ views::ClientView* CreateClientView(views::Widget* widget) override {
+ return this;
+ }
+
+ // views::ClientView:
+ views::CloseRequestResult OnWindowCloseRequested() override {
+ shell_->inspectable_web_contents()->CloseDevTools();
+ return views::CloseRequestResult::kCannotClose;
+ }
+
+ private:
+ raw_ptr<InspectableWebContentsViewViews> shell_;
+ raw_ptr<views::View> view_;
+ raw_ptr<views::Widget> widget_;
+ ui::ImageModel icon_;
+};
+
+} // namespace
+
+InspectableWebContentsView* CreateInspectableContentsView(
+ InspectableWebContents* inspectable_web_contents) {
+ return new InspectableWebContentsViewViews(inspectable_web_contents);
+}
+
+InspectableWebContentsViewViews::InspectableWebContentsViewViews(
+ InspectableWebContents* inspectable_web_contents)
+ : InspectableWebContentsView(inspectable_web_contents),
+ devtools_web_view_(new views::WebView(nullptr)),
+ title_(u"Developer Tools") {
+ if (!inspectable_web_contents_->is_guest() &&
+ inspectable_web_contents_->GetWebContents()->GetNativeView()) {
+ auto* contents_web_view = new views::WebView(nullptr);
+ contents_web_view->SetWebContents(
+ inspectable_web_contents_->GetWebContents());
+ contents_view_ = contents_web_view_ = contents_web_view;
+ } else {
+ contents_view_ = new views::Label(u"No content under offscreen mode");
+ }
+
+ devtools_web_view_->SetVisible(false);
+ AddChildView(devtools_web_view_.get());
+ AddChildView(contents_view_.get());
+}
+
+InspectableWebContentsViewViews::~InspectableWebContentsViewViews() {
+ if (devtools_window_)
+ inspectable_web_contents()->SaveDevToolsBounds(
+ devtools_window_->GetWindowBoundsInScreen());
+}
+
+views::View* InspectableWebContentsViewViews::GetView() {
+ return this;
+}
+
+void InspectableWebContentsViewViews::SetCornerRadii(
+ const gfx::RoundedCornersF& corner_radii) {
+ // WebView won't exist for offscreen rendering.
+ if (contents_web_view_) {
+ contents_web_view_->holder()->SetCornerRadii(
+ gfx::RoundedCornersF(corner_radii));
+ }
+}
+
+void InspectableWebContentsViewViews::ShowDevTools(bool activate) {
+ if (devtools_visible_)
+ return;
+
+ devtools_visible_ = true;
+ if (devtools_window_) {
+ devtools_window_web_view_->SetWebContents(
+ inspectable_web_contents_->GetDevToolsWebContents());
+ devtools_window_->SetBounds(inspectable_web_contents()->dev_tools_bounds());
+ if (activate) {
+ devtools_window_->Show();
+ } else {
+ devtools_window_->ShowInactive();
+ }
+
+ // Update draggable regions to account for the new dock position.
+ if (GetDelegate())
+ GetDelegate()->DevToolsResized();
+ } else {
+ devtools_web_view_->SetVisible(true);
+ devtools_web_view_->SetWebContents(
+ inspectable_web_contents_->GetDevToolsWebContents());
+ devtools_web_view_->RequestFocus();
+ DeprecatedLayoutImmediately();
+ }
+}
+
+void InspectableWebContentsViewViews::CloseDevTools() {
+ if (!devtools_visible_)
+ return;
+
+ devtools_visible_ = false;
+ if (devtools_window_) {
+ auto save_bounds = devtools_window_->IsMinimized()
+ ? devtools_window_->GetRestoredBounds()
+ : devtools_window_->GetWindowBoundsInScreen();
+ inspectable_web_contents()->SaveDevToolsBounds(save_bounds);
+
+ devtools_window_.reset();
+ devtools_window_web_view_ = nullptr;
+ devtools_window_delegate_ = nullptr;
+ } else {
+ devtools_web_view_->SetVisible(false);
+ devtools_web_view_->SetWebContents(nullptr);
+ DeprecatedLayoutImmediately();
+ }
+}
+
+bool InspectableWebContentsViewViews::IsDevToolsViewShowing() {
+ return devtools_visible_;
+}
+
+bool InspectableWebContentsViewViews::IsDevToolsViewFocused() {
+ if (devtools_window_web_view_)
+ return devtools_window_web_view_->HasFocus();
+ else if (devtools_web_view_)
+ return devtools_web_view_->HasFocus();
+ else
+ return false;
+}
+
+void InspectableWebContentsViewViews::SetIsDocked(bool docked, bool activate) {
+ CloseDevTools();
+
+ if (!docked) {
+ devtools_window_ = std::make_unique<views::Widget>();
+ devtools_window_web_view_ = new views::WebView(nullptr);
+ devtools_window_delegate_ = new DevToolsWindowDelegate(
+ this, devtools_window_web_view_, devtools_window_.get());
+
+ views::Widget::InitParams params{
+ views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET};
+ params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
+ params.delegate = devtools_window_delegate_;
+ params.bounds = inspectable_web_contents()->dev_tools_bounds();
+
+#if BUILDFLAG(IS_LINUX)
+ params.wm_role_name = "devtools";
+ if (GetDelegate())
+ GetDelegate()->GetDevToolsWindowWMClass(¶ms.wm_class_name,
+ ¶ms.wm_class_class);
+#endif
+
+ devtools_window_->Init(std::move(params));
+ devtools_window_->UpdateWindowIcon();
+ devtools_window_->widget_delegate()->SetHasWindowSizeControls(true);
+ }
+
+ ShowDevTools(activate);
+}
+
+void InspectableWebContentsViewViews::SetContentsResizingStrategy(
+ const DevToolsContentsResizingStrategy& strategy) {
+ strategy_.CopyFrom(strategy);
+ DeprecatedLayoutImmediately();
+}
+
+void InspectableWebContentsViewViews::SetTitle(const std::u16string& title) {
+ if (devtools_window_) {
+ title_ = title;
+ devtools_window_->UpdateWindowTitle();
+ }
+}
+
+const std::u16string InspectableWebContentsViewViews::GetTitle() {
+ return title_;
+}
+
+void InspectableWebContentsViewViews::Layout(PassKey) {
+ if (!devtools_web_view_->GetVisible()) {
+ contents_view_->SetBoundsRect(GetContentsBounds());
+ // Propagate layout call to all children, for example browser views.
+ LayoutSuperclass<View>(this);
+ return;
+ }
+
+ gfx::Size container_size(width(), height());
+ gfx::Rect new_devtools_bounds;
+ gfx::Rect new_contents_bounds;
+ ApplyDevToolsContentsResizingStrategy(
+ strategy_, container_size, &new_devtools_bounds, &new_contents_bounds);
+
+ // DevTools cares about the specific position, so we have to compensate RTL
+ // layout here.
+ new_devtools_bounds.set_x(GetMirroredXForRect(new_devtools_bounds));
+ new_contents_bounds.set_x(GetMirroredXForRect(new_contents_bounds));
+
+ devtools_web_view_->SetBoundsRect(new_devtools_bounds);
+ contents_view_->SetBoundsRect(new_contents_bounds);
+
+ // Propagate layout call to all children, for example browser views.
+ LayoutSuperclass<View>(this);
+
+ if (GetDelegate())
+ GetDelegate()->DevToolsResized();
+}
+
+} // namespace electron
diff --git a/shell/browser/ui/views/inspectable_web_contents_view_views.h b/shell/browser/ui/views/inspectable_web_contents_view_views.h
new file mode 100644
index 0000000000..36554a497d
--- /dev/null
+++ b/shell/browser/ui/views/inspectable_web_contents_view_views.h
@@ -0,0 +1,63 @@
+// Copyright (c) 2014 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE-CHROMIUM file.
+
+#ifndef ELECTRON_SHELL_BROWSER_UI_VIEWS_INSPECTABLE_WEB_CONTENTS_VIEW_VIEWS_H_
+#define ELECTRON_SHELL_BROWSER_UI_VIEWS_INSPECTABLE_WEB_CONTENTS_VIEW_VIEWS_H_
+
+#include <memory>
+
+#include "base/compiler_specific.h"
+#include "base/memory/raw_ptr.h"
+#include "chrome/browser/devtools/devtools_contents_resizing_strategy.h"
+#include "shell/browser/ui/inspectable_web_contents_view.h"
+#include "third_party/skia/include/core/SkRegion.h"
+#include "ui/views/view.h"
+
+namespace views {
+class WebView;
+class Widget;
+class WidgetDelegate;
+} // namespace views
+
+namespace electron {
+
+class InspectableWebContentsViewViews : public InspectableWebContentsView,
+ public views::View {
+ public:
+ explicit InspectableWebContentsViewViews(
+ InspectableWebContents* inspectable_web_contents);
+ ~InspectableWebContentsViewViews() override;
+
+ // InspectableWebContentsView:
+ views::View* GetView() override;
+ void ShowDevTools(bool activate) override;
+ void SetCornerRadii(const gfx::RoundedCornersF& corner_radii) override;
+ void CloseDevTools() override;
+ bool IsDevToolsViewShowing() override;
+ bool IsDevToolsViewFocused() override;
+ void SetIsDocked(bool docked, bool activate) override;
+ void SetContentsResizingStrategy(
+ const DevToolsContentsResizingStrategy& strategy) override;
+ void SetTitle(const std::u16string& title) override;
+ const std::u16string GetTitle() override;
+
+ // views::View:
+ void Layout(PassKey) override;
+
+ private:
+ std::unique_ptr<views::Widget> devtools_window_;
+ raw_ptr<views::WebView> devtools_window_web_view_ = nullptr;
+ raw_ptr<views::WebView> contents_web_view_ = nullptr;
+ raw_ptr<views::View> contents_view_ = nullptr;
+ raw_ptr<views::WebView> devtools_web_view_ = nullptr;
+
+ DevToolsContentsResizingStrategy strategy_;
+ bool devtools_visible_ = false;
+ raw_ptr<views::WidgetDelegate> devtools_window_delegate_ = nullptr;
+ std::u16string title_;
+};
+
+} // namespace electron
+
+#endif // ELECTRON_SHELL_BROWSER_UI_VIEWS_INSPECTABLE_WEB_CONTENTS_VIEW_VIEWS_H_
|
fix
|
a1b2dae68e8f16ce360f26e76e9a64a95124a6d5
|
Shelley Vohr
|
2023-05-15 16:52:25
|
build: add labels to appveyor update PR (#38292)
|
diff --git a/.github/workflows/update_appveyor_image.yml b/.github/workflows/update_appveyor_image.yml
index 05b84c5ec5..6b269da020 100644
--- a/.github/workflows/update_appveyor_image.yml
+++ b/.github/workflows/update_appveyor_image.yml
@@ -66,7 +66,9 @@ jobs:
signoff: false
branch: bump-appveyor-image
delete-branch: true
+ reviewers: electron/wg-releases
title: 'build: update appveyor image to latest version'
+ labels: semver-none,no-backport
body: |
This PR updates appveyor.yml to the latest baked image, ${{ env.APPVEYOR_IMAGE_VERSION }}.
Notes: none
\ No newline at end of file
|
build
|
0b44f433c8764e710ad5a36b8e82cc5720dd1be0
|
Samuel Attard
|
2023-09-07 15:55:17
|
fix: make titlebar opaque while fullscreen (#39759)
|
diff --git a/shell/browser/native_window_mac.mm b/shell/browser/native_window_mac.mm
index d3d0152497..e339366b05 100644
--- a/shell/browser/native_window_mac.mm
+++ b/shell/browser/native_window_mac.mm
@@ -1692,6 +1692,9 @@ void NativeWindowMac::NotifyWindowEnterFullScreen() {
// Restore the window title under fullscreen mode.
if (buttons_proxy_)
[window_ setTitleVisibility:NSWindowTitleVisible];
+
+ if (transparent() || !has_frame())
+ [window_ setTitlebarAppearsTransparent:NO];
}
void NativeWindowMac::NotifyWindowLeaveFullScreen() {
@@ -1701,6 +1704,9 @@ void NativeWindowMac::NotifyWindowLeaveFullScreen() {
[buttons_proxy_ redraw];
[buttons_proxy_ setVisible:YES];
}
+
+ if (transparent() || !has_frame())
+ [window_ setTitlebarAppearsTransparent:YES];
}
void NativeWindowMac::NotifyWindowWillEnterFullScreen() {
|
fix
|
2d868ecb8d0baecdda4fb2f80a0f3ef58690fb6c
|
Charles Kerr
|
2024-09-04 22:53:06
|
perf: use v8::Local<v8::Object> as the key in ObjectCache (#43519)
* perf: use v8::Object* as direct keys instead of using hash + a linked list
* refactor: use v8::Local<v8::Object> as the key
|
diff --git a/shell/renderer/api/context_bridge/object_cache.cc b/shell/renderer/api/context_bridge/object_cache.cc
index 5515584571..d7a21e655f 100644
--- a/shell/renderer/api/context_bridge/object_cache.cc
+++ b/shell/renderer/api/context_bridge/object_cache.cc
@@ -12,37 +12,22 @@ namespace electron::api::context_bridge {
ObjectCache::ObjectCache() = default;
ObjectCache::~ObjectCache() = default;
-void ObjectCache::CacheProxiedObject(v8::Local<v8::Value> from,
+void ObjectCache::CacheProxiedObject(const v8::Local<v8::Value> from,
v8::Local<v8::Value> proxy_value) {
- if (from->IsObject() && !from->IsNullOrUndefined()) {
- auto obj = from.As<v8::Object>();
- int hash = obj->GetIdentityHash();
-
- proxy_map_[hash].emplace_front(from, proxy_value);
- }
+ if (from->IsObject() && !from->IsNullOrUndefined())
+ proxy_map_.insert_or_assign(from.As<v8::Object>(), proxy_value);
}
v8::MaybeLocal<v8::Value> ObjectCache::GetCachedProxiedObject(
- v8::Local<v8::Value> from) const {
+ const v8::Local<v8::Value> from) const {
if (!from->IsObject() || from->IsNullOrUndefined())
- return v8::MaybeLocal<v8::Value>();
-
- auto obj = from.As<v8::Object>();
- int hash = obj->GetIdentityHash();
- auto iter = proxy_map_.find(hash);
- if (iter == proxy_map_.end())
- return v8::MaybeLocal<v8::Value>();
-
- auto& list = iter->second;
- for (const auto& pair : list) {
- auto from_cmp = pair.first;
- if (from_cmp == from) {
- if (pair.second.IsEmpty())
- return v8::MaybeLocal<v8::Value>();
- return pair.second;
- }
- }
- return v8::MaybeLocal<v8::Value>();
+ return {};
+
+ const auto iter = proxy_map_.find(from.As<v8::Object>());
+ if (iter == proxy_map_.end() || iter->second.IsEmpty())
+ return {};
+
+ return iter->second;
}
} // namespace electron::api::context_bridge
diff --git a/shell/renderer/api/context_bridge/object_cache.h b/shell/renderer/api/context_bridge/object_cache.h
index 680857f358..340d1bebc2 100644
--- a/shell/renderer/api/context_bridge/object_cache.h
+++ b/shell/renderer/api/context_bridge/object_cache.h
@@ -5,19 +5,18 @@
#ifndef ELECTRON_SHELL_RENDERER_API_CONTEXT_BRIDGE_OBJECT_CACHE_H_
#define ELECTRON_SHELL_RENDERER_API_CONTEXT_BRIDGE_OBJECT_CACHE_H_
-#include <forward_list>
#include <unordered_map>
-#include <utility>
-#include "content/public/renderer/render_frame.h"
-#include "content/public/renderer/render_frame_observer.h"
-#include "shell/renderer/electron_render_frame_observer.h"
-#include "third_party/blink/public/web/web_local_frame.h"
+#include "v8/include/v8-local-handle.h"
+#include "v8/include/v8-object.h"
namespace electron::api::context_bridge {
-using ObjectCachePair = std::pair<v8::Local<v8::Value>, v8::Local<v8::Value>>;
-
+/**
+ * NB: This is designed for context_bridge. Beware using it elsewhere!
+ * Since it's a v8::Local-to-v8::Local cache, be careful to destroy it
+ * before destroying the HandleScope that keeps the locals alive.
+ */
class ObjectCache final {
public:
ObjectCache();
@@ -29,8 +28,15 @@ class ObjectCache final {
v8::Local<v8::Value> from) const;
private:
- // object_identity ==> [from_value, proxy_value]
- std::unordered_map<int, std::forward_list<ObjectCachePair>> proxy_map_;
+ struct Hash {
+ std::size_t operator()(const v8::Local<v8::Object>& obj) const {
+ return obj->GetIdentityHash();
+ }
+ };
+
+ // from_object ==> proxy_value
+ std::unordered_map<v8::Local<v8::Object>, v8::Local<v8::Value>, Hash>
+ proxy_map_;
};
} // namespace electron::api::context_bridge
|
perf
|
532162d2b5b0e05c1bca3d08e30c4e2b9387ac04
|
marekharanczyk
|
2022-09-15 18:33:08
|
fix: EventEmitter is missing properties in sandbox preload script. (#35522)
|
diff --git a/package.json b/package.json
index cbeee0af1e..aedaa5ba0e 100644
--- a/package.json
+++ b/package.json
@@ -45,6 +45,7 @@
"eslint-plugin-node": "^11.1.0",
"eslint-plugin-standard": "^4.0.1",
"eslint-plugin-typescript": "^0.14.0",
+ "events": "^3.2.0",
"express": "^4.16.4",
"folder-hash": "^2.1.1",
"fs-extra": "^9.0.1",
diff --git a/spec/api-browser-window-spec.ts b/spec/api-browser-window-spec.ts
index a925e6bf06..de2330b923 100644
--- a/spec/api-browser-window-spec.ts
+++ b/spec/api-browser-window-spec.ts
@@ -2970,6 +2970,26 @@ describe('BrowserWindow module', () => {
expect(url).to.equal(expectedUrl);
});
+ it('exposes full EventEmitter object to preload script', async () => {
+ const w = new BrowserWindow({
+ show: false,
+ webPreferences: {
+ sandbox: true,
+ preload: path.join(fixtures, 'module', 'preload-eventemitter.js')
+ }
+ });
+ w.loadURL('about:blank');
+ const [, rendererEventEmitterProperties] = await emittedOnce(ipcMain, 'answer');
+ const { EventEmitter } = require('events');
+ const emitter = new EventEmitter();
+ const browserEventEmitterProperties = [];
+ let currentObj = emitter;
+ do {
+ browserEventEmitterProperties.push(...Object.getOwnPropertyNames(currentObj));
+ } while ((currentObj = Object.getPrototypeOf(currentObj)));
+ expect(rendererEventEmitterProperties).to.deep.equal(browserEventEmitterProperties);
+ });
+
it('should open windows in same domain with cross-scripting enabled', async () => {
const w = new BrowserWindow({
show: true,
diff --git a/spec/fixtures/module/preload-eventemitter.js b/spec/fixtures/module/preload-eventemitter.js
new file mode 100644
index 0000000000..26b5760de0
--- /dev/null
+++ b/spec/fixtures/module/preload-eventemitter.js
@@ -0,0 +1,11 @@
+(function () {
+ const { EventEmitter } = require('events');
+ const emitter = new EventEmitter();
+ const rendererEventEmitterProperties = [];
+ let currentObj = emitter;
+ do {
+ rendererEventEmitterProperties.push(...Object.getOwnPropertyNames(currentObj));
+ } while ((currentObj = Object.getPrototypeOf(currentObj)));
+ const { ipcRenderer } = require('electron');
+ ipcRenderer.send('answer', rendererEventEmitterProperties);
+})();
|
fix
|
6a68afdb8ad6e083f7d8cbb7111b4b9cb0c620ac
|
Calvin
|
2022-09-28 11:47:25
|
docs: update breaking changes for v21 (#35820)
|
diff --git a/docs/breaking-changes.md b/docs/breaking-changes.md
index 03d12a6232..b923254f6a 100644
--- a/docs/breaking-changes.md
+++ b/docs/breaking-changes.md
@@ -80,7 +80,7 @@ win.webContents.on('input-event', (_, event) => {
})
```
-## Planned Breaking API Changes (20.0)
+## Planned Breaking API Changes (21.0)
### Behavior Changed: V8 Memory Cage enabled
@@ -144,6 +144,8 @@ webContents.printToPDF({
})
```
+## Planned Breaking API Changes (20.0)
+
### Default Changed: renderers without `nodeIntegration: true` are sandboxed by default
Previously, renderers that specified a preload script defaulted to being
|
docs
|
32d5f9e3efb94c6ff85c2a2bc8c7c822026de21b
|
Kilian Valkhof
|
2024-09-05 22:48:22
|
docs: explain ipcRenderer behavior in context-bridge.md (#43455)
* docs: explain ipcRenderer behavior in context-bridge.md
* Update context-bridge.md
* Update context-bridge.md
* Update docs/api/context-bridge.md
Co-authored-by: Erik Moura <[email protected]>
* Update context-bridge.md
* Update context-bridge.md
* Update context-bridge.md
* Update docs/api/context-bridge.md
Co-authored-by: Erick Zhao <[email protected]>
* Update docs/api/context-bridge.md
Co-authored-by: David Sanders <[email protected]>
---------
Co-authored-by: Erik Moura <[email protected]>
Co-authored-by: Erick Zhao <[email protected]>
Co-authored-by: David Sanders <[email protected]>
|
diff --git a/docs/api/context-bridge.md b/docs/api/context-bridge.md
index b9eb55f8a9..59d8a0d363 100644
--- a/docs/api/context-bridge.md
+++ b/docs/api/context-bridge.md
@@ -147,6 +147,25 @@ has been included below for completeness:
If the type you care about is not in the above table, it is probably not supported.
+### Exposing ipcRenderer
+
+Attempting to send the entire `ipcRenderer` module as an object over the `contextBridge` will result in
+an empty object on the receiving side of the bridge. Sending over `ipcRenderer` in full can let any
+code send any message, which is a security footgun. To interact through `ipcRenderer`, provide a safe wrapper
+like below:
+
+```js
+// Preload (Isolated World)
+contextBridge.exposeInMainWorld('electron', {
+ onMyEventName: (callback) => ipcRenderer.on('MyEventName', (e, ...args) => callback(args))
+})
+```
+
+```js @ts-nocheck
+// Renderer (Main World)
+window.electron.onMyEventName(data => { /* ... */ })
+```
+
### Exposing Node Global Symbols
The `contextBridge` can be used by the preload script to give your renderer access to Node APIs.
|
docs
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.