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
170b72ccfacf4f46cc675fd5d246fd961699dde7
David Sanders
2024-07-08 18:38:05
ci: fix CircleCI config (#42829) * ci: fix CircleCI config * ci: fix syntax error
diff --git a/.circleci/config.yml b/.circleci/config.yml index 46f927cb42..2696006fbd 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -31,7 +31,6 @@ jobs: - path-filtering/set-parameters: base-revision: main mapping: | - ^((?!docs/).)*$ run-build-mac true ^((?!docs/).)*$ run-build-linux true docs/.* run-docs-only true ^((?!docs/).)*$ run-docs-only false diff --git a/.circleci/config/base.yml b/.circleci/config/base.yml index 95afdbd281..8fc2f94fa2 100644 --- a/.circleci/config/base.yml +++ b/.circleci/config/base.yml @@ -188,8 +188,7 @@ step-depot-tools-get: &step-depot-tools-get CipdDependency(parent=self, name=name, EOF - git apply --3way gclient.diff - fi + git apply --3way gclient.diff # Ensure depot_tools does not update. test -d depot_tools && cd depot_tools touch .disable_auto_update
ci
3c8321a9878a402395bb3f61d4817d3951988b4f
Shelley Vohr
2024-09-12 15:40:56
fix: EyeDropper working in devtools (#43685)
diff --git a/shell/browser/ui/inspectable_web_contents.cc b/shell/browser/ui/inspectable_web_contents.cc index 19c18f00a6..454544ed93 100644 --- a/shell/browser/ui/inspectable_web_contents.cc +++ b/shell/browser/ui/inspectable_web_contents.cc @@ -784,6 +784,7 @@ void InspectableWebContents::SetEyeDropperActive(bool active) { if (delegate_) delegate_->DevToolsSetEyeDropperActive(active); } + void InspectableWebContents::ZoomIn() { double new_level = GetNextZoomLevel(GetDevToolsZoomLevel(), false); SetZoomLevelForWebContents(GetDevToolsWebContents(), new_level); @@ -965,6 +966,13 @@ void InspectableWebContents::CloseContents(content::WebContents* source) { CloseDevTools(); } +std::unique_ptr<content::EyeDropper> InspectableWebContents::OpenEyeDropper( + content::RenderFrameHost* frame, + content::EyeDropperListener* listener) { + auto* delegate = web_contents_->GetDelegate(); + return delegate ? delegate->OpenEyeDropper(frame, listener) : nullptr; +} + void InspectableWebContents::RunFileChooser( content::RenderFrameHost* render_frame_host, scoped_refptr<content::FileSelectListener> listener, diff --git a/shell/browser/ui/inspectable_web_contents.h b/shell/browser/ui/inspectable_web_contents.h index c7f01159ca..029af15a42 100644 --- a/shell/browser/ui/inspectable_web_contents.h +++ b/shell/browser/ui/inspectable_web_contents.h @@ -208,6 +208,9 @@ class InspectableWebContents bool HandleKeyboardEvent(content::WebContents*, const input::NativeWebKeyboardEvent&) override; void CloseContents(content::WebContents* source) override; + std::unique_ptr<content::EyeDropper> OpenEyeDropper( + content::RenderFrameHost* frame, + content::EyeDropperListener* listener) override; void RunFileChooser(content::RenderFrameHost* render_frame_host, scoped_refptr<content::FileSelectListener> listener, const blink::mojom::FileChooserParams& params) override;
fix
663497dc6b70e1e07aad45eb021393f00e267a81
Shelley Vohr
2023-05-31 15:54:41
chore: make `contentTracing.stopRecording()` failure clearer (#38488) chore: make contentTracing.stopRecording() failure clearer
diff --git a/shell/browser/api/electron_api_content_tracing.cc b/shell/browser/api/electron_api_content_tracing.cc index f7e64cb2bb..f44f2d8494 100644 --- a/shell/browser/api/electron_api_content_tracing.cc +++ b/shell/browser/api/electron_api_content_tracing.cc @@ -77,15 +77,20 @@ void StopTracing(gin_helper::Promise<base::FilePath> promise, } }, std::move(promise), *file_path); - if (file_path) { + + auto* instance = TracingController::GetInstance(); + if (!instance->IsTracing()) { + std::move(resolve_or_reject) + .Run(absl::make_optional( + "Failed to stop tracing - no trace in progress")); + } else if (file_path) { auto split_callback = base::SplitOnceCallback(std::move(resolve_or_reject)); auto endpoint = TracingController::CreateFileEndpoint( *file_path, base::BindOnce(std::move(split_callback.first), absl::nullopt)); - if (!TracingController::GetInstance()->StopTracing(endpoint)) { + if (!instance->StopTracing(endpoint)) { std::move(split_callback.second) - .Run(absl::make_optional( - "Failed to stop tracing (was a trace in progress?)")); + .Run(absl::make_optional("Failed to stop tracing")); } } else { std::move(resolve_or_reject) diff --git a/spec/api-content-tracing-spec.ts b/spec/api-content-tracing-spec.ts index 38cc6ab8b3..2d43de3e90 100644 --- a/spec/api-content-tracing-spec.ts +++ b/spec/api-content-tracing-spec.ts @@ -114,7 +114,7 @@ ifdescribe(!(['arm', 'arm64', 'ia32'].includes(process.arch)))('contentTracing', }); it('rejects if no trace is happening', async () => { - await expect(contentTracing.stopRecording()).to.be.rejected(); + await expect(contentTracing.stopRecording()).to.be.rejectedWith('Failed to stop tracing - no trace in progress'); }); });
chore
ad077125618bb3dc93dd2a660bf6c6956204bae5
Shelley Vohr
2023-05-17 10:17:08
fix: `win.isMaximized()` for transparent windows on Windows (#38234)
diff --git a/shell/browser/native_window_views.cc b/shell/browser/native_window_views.cc index 364da7e824..f21ba2a8ee 100644 --- a/shell/browser/native_window_views.cc +++ b/shell/browser/native_window_views.cc @@ -656,7 +656,7 @@ bool NativeWindowViews::IsMaximized() { return true; } else { #if BUILDFLAG(IS_WIN) - if (transparent()) { + if (transparent() && !IsMinimized()) { // Compare the size of the window with the size of the display auto display = display::Screen::GetScreen()->GetDisplayNearestWindow( GetNativeWindow()); diff --git a/spec/api-browser-window-spec.ts b/spec/api-browser-window-spec.ts index 0e558e0b0e..fc37f7296b 100644 --- a/spec/api-browser-window-spec.ts +++ b/spec/api-browser-window-spec.ts @@ -6059,6 +6059,24 @@ describe('BrowserWindow module', () => { describe('"transparent" option', () => { afterEach(closeAllWindows); + ifit(process.platform !== 'linux')('correctly returns isMaximized() when the window is maximized then minimized', async () => { + const w = new BrowserWindow({ + frame: false, + transparent: true + }); + + const maximize = once(w, 'maximize'); + w.maximize(); + await maximize; + + const minimize = once(w, 'minimize'); + w.minimize(); + await minimize; + + expect(w.isMaximized()).to.be.false(); + expect(w.isMinimized()).to.be.true(); + }); + // Only applicable on Windows where transparent windows can't be maximized. ifit(process.platform === 'win32')('can show maximized frameless window', async () => { const display = screen.getPrimaryDisplay();
fix
70508b527357b60ef092adc9140e503ea2a692d4
Shelley Vohr
2023-08-09 16:38:13
chore: update `_api_features` manifest requirements (#39412) chore: update api_resources manifest requirements
diff --git a/shell/common/extensions/api/_api_features.json b/shell/common/extensions/api/_api_features.json index 2ee99309a6..11f019b57a 100644 --- a/shell/common/extensions/api/_api_features.json +++ b/shell/common/extensions/api/_api_features.json @@ -4,6 +4,15 @@ "extension_types": ["extension"], "contexts": ["blessed_extension"] }, + "tabs.executeScript": { + "max_manifest_version": 2 + }, + "tabs.insertCSS": { + "max_manifest_version": 2 + }, + "tabs.removeCSS": { + "max_manifest_version": 2 + }, "extension": { "channel": "stable", "extension_types": ["extension"], @@ -14,7 +23,8 @@ "disallow_for_service_workers": true }, "extension.getURL": { - "contexts": ["blessed_extension", "unblessed_extension", "content_script"] + "contexts": ["blessed_extension", "unblessed_extension", "content_script"], + "max_manifest_version": 2 }, "i18n": { "channel": "stable", diff --git a/shell/common/extensions/api/resources_private.idl b/shell/common/extensions/api/resources_private.idl index 836b366d0e..31a85ce5c1 100644 --- a/shell/common/extensions/api/resources_private.idl +++ b/shell/common/extensions/api/resources_private.idl @@ -1,4 +1,4 @@ -// Copyright 2015 The Chromium Authors. All rights reserved. +// Copyright 2015 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. @@ -15,9 +15,9 @@ namespace resourcesPrivate { // chrome/browser/extensions/api/resources_private/resources_private_api.cc // for instructions on adding a new component to this API. // - // |component| : Internal chrome component to get strings for. + // |component| : Internal Chrome component to get strings for. // |callback| : Called with a dictionary mapping names to strings. - static void getStrings(Component component, - GetStringsCallback callback); + [supportsPromises] static void getStrings(Component component, + GetStringsCallback callback); }; };
chore
422511753fd2c37b39ecc0c3b8011161ef89c176
Shelley Vohr
2024-06-14 06:47:18
build: use `BUILD_TYPE` from env (#42498) build: use BUILD_TYPE from env
diff --git a/.github/workflows/pipeline-segment-node-nan-test.yml b/.github/workflows/pipeline-segment-node-nan-test.yml index cd3002f461..72301752b9 100644 --- a/.github/workflows/pipeline-segment-node-nan-test.yml +++ b/.github/workflows/pipeline-segment-node-nan-test.yml @@ -41,6 +41,7 @@ jobs: timeout-minutes: 20 env: TARGET_ARCH: ${{ inputs.target-arch }} + BUILD_TYPE: linux container: ${{ fromJSON(inputs.test-container) }} steps: - name: Load Build Tools @@ -71,8 +72,8 @@ jobs: - name: Download Generated Artifacts uses: actions/download-artifact@65a9edc5881444af0b9093a5e628f2fe47ea3b2e with: - name: generated_artifacts_linux_${{ env.TARGET_ARCH }} - path: ./generated_artifacts_linux_${{ env.TARGET_ARCH }} + name: generated_artifacts_${{ env.BUILD_TYPE }}_${{ env.TARGET_ARCH }} + path: ./generated_artifacts_${{ env.BUILD_TYPE }}_${{ env.TARGET_ARCH }} - name: Download Src Artifacts uses: actions/download-artifact@65a9edc5881444af0b9093a5e628f2fe47ea3b2e with: @@ -103,6 +104,7 @@ jobs: timeout-minutes: 20 env: TARGET_ARCH: ${{ inputs.target-arch }} + BUILD_TYPE: linux container: ${{ fromJSON(inputs.test-container) }} steps: - name: Load Build Tools @@ -133,8 +135,8 @@ jobs: - name: Download Generated Artifacts uses: actions/download-artifact@65a9edc5881444af0b9093a5e628f2fe47ea3b2e with: - name: generated_artifacts_linux_${{ env.TARGET_ARCH }} - path: ./generated_artifacts_linux_${{ env.TARGET_ARCH }} + name: generated_artifacts_${{ env.BUILD_TYPE }}_${{ env.TARGET_ARCH }} + path: ./generated_artifacts_${{ env.BUILD_TYPE }}_${{ env.TARGET_ARCH }} - name: Download Src Artifacts uses: actions/download-artifact@65a9edc5881444af0b9093a5e628f2fe47ea3b2e with: diff --git a/script/actions/restore-artifacts.sh b/script/actions/restore-artifacts.sh index a4eed010d1..66a336c472 100755 --- a/script/actions/restore-artifacts.sh +++ b/script/actions/restore-artifacts.sh @@ -1,18 +1,5 @@ #!/bin/bash -if [ "`uname`" == "Darwin" ]; then - if [ -z "$MAS_BUILD" ]; then - BUILD_TYPE="darwin" - else - BUILD_TYPE="mas" - fi -elif [ "`uname`" == "Linux" ]; then - BUILD_TYPE="linux" -else - echo "Unsupported platform" - exit 1 -fi - GENERATED_ARTIFACTS="generated_artifacts_${BUILD_TYPE}_${TARGET_ARCH}" SRC_ARTIFACTS="src_artifacts_${BUILD_TYPE}_${TARGET_ARCH}"
build
2a383e9dddf8e675383aced1b8f5cc8687a9a40b
Charles Kerr
2025-02-21 17:33:43
refactor: use C++20's contains() method (#45742) * chore: use std::map<>::contains() instead of count() or find() * chore: use std::map<>::contains() instead of base::Contains()
diff --git a/shell/browser/api/electron_api_base_window.cc b/shell/browser/api/electron_api_base_window.cc index f4d2acd189..01800aab55 100644 --- a/shell/browser/api/electron_api_base_window.cc +++ b/shell/browser/api/electron_api_base_window.cc @@ -9,7 +9,6 @@ #include <utility> #include <vector> -#include "base/containers/contains.h" #include "base/task/single_thread_task_runner.h" #include "content/public/common/color_parser.h" #include "electron/buildflags/buildflags.h" @@ -1052,7 +1051,7 @@ void BaseWindow::UnhookWindowMessage(UINT message) { } bool BaseWindow::IsWindowMessageHooked(UINT message) { - return base::Contains(messages_callback_map_, message); + return messages_callback_map_.contains(message); } void BaseWindow::UnhookAllWindowMessages() { diff --git a/shell/browser/api/electron_api_global_shortcut.cc b/shell/browser/api/electron_api_global_shortcut.cc index a463909265..3834bf2474 100644 --- a/shell/browser/api/electron_api_global_shortcut.cc +++ b/shell/browser/api/electron_api_global_shortcut.cc @@ -7,7 +7,6 @@ #include <string> #include <vector> -#include "base/containers/contains.h" #include "base/strings/utf_string_conversions.h" #include "base/uuid.h" #include "components/prefs/pref_service.h" @@ -58,7 +57,7 @@ GlobalShortcut::~GlobalShortcut() { } void GlobalShortcut::OnKeyPressed(const ui::Accelerator& accelerator) { - if (!base::Contains(accelerator_callback_map_, accelerator)) { + if (!accelerator_callback_map_.contains(accelerator)) { // This should never occur, because if it does, // ui::GlobalAcceleratorListener notifies us with wrong accelerator. NOTREACHED(); @@ -68,7 +67,7 @@ void GlobalShortcut::OnKeyPressed(const ui::Accelerator& accelerator) { void GlobalShortcut::ExecuteCommand(const extensions::ExtensionId& extension_id, const std::string& command_id) { - if (!base::Contains(command_callback_map_, command_id)) { + if (!command_callback_map_.contains(command_id)) { // This should never occur, because if it does, GlobalAcceleratorListener // notifies us with wrong command. NOTREACHED(); @@ -195,12 +194,12 @@ void GlobalShortcut::UnregisterSome( } bool GlobalShortcut::IsRegistered(const ui::Accelerator& accelerator) { - if (base::Contains(accelerator_callback_map_, accelerator)) { + if (accelerator_callback_map_.contains(accelerator)) { return true; } const std::string command_str = extensions::Command::AcceleratorToString(accelerator); - return base::Contains(command_callback_map_, command_str); + return command_callback_map_.contains(command_str); } void GlobalShortcut::UnregisterAll() { diff --git a/shell/browser/api/electron_api_power_save_blocker.cc b/shell/browser/api/electron_api_power_save_blocker.cc index 91adc75f09..e3420e1e71 100644 --- a/shell/browser/api/electron_api_power_save_blocker.cc +++ b/shell/browser/api/electron_api_power_save_blocker.cc @@ -6,7 +6,6 @@ #include <string> -#include "base/containers/contains.h" #include "base/functional/callback_helpers.h" #include "content/public/browser/device_service.h" #include "gin/dictionary.h" @@ -110,7 +109,7 @@ bool PowerSaveBlocker::Stop(int id) { } bool PowerSaveBlocker::IsStarted(int id) const { - return base::Contains(wake_lock_types_, id); + return wake_lock_types_.contains(id); } // static diff --git a/shell/browser/api/electron_api_protocol.cc b/shell/browser/api/electron_api_protocol.cc index 628fc7aff5..9e630ba493 100644 --- a/shell/browser/api/electron_api_protocol.cc +++ b/shell/browser/api/electron_api_protocol.cc @@ -8,6 +8,7 @@ #include <vector> #include "base/command_line.h" +#include "base/containers/contains.h" #include "content/common/url_schemes.h" #include "content/public/browser/child_process_security_policy.h" #include "gin/handle.h" diff --git a/shell/browser/api/electron_api_session.cc b/shell/browser/api/electron_api_session.cc index 3691aa5047..571ba3a009 100644 --- a/shell/browser/api/electron_api_session.cc +++ b/shell/browser/api/electron_api_session.cc @@ -1523,7 +1523,7 @@ v8::Local<v8::Promise> Session::ClearCodeCaches( if (options.Get("urls", &url_list) && !url_list.empty()) { url_matcher = base::BindRepeating( [](const std::set<GURL>& url_list, const GURL& url) { - return base::Contains(url_list, url); + return url_list.contains(url); }, url_list); } diff --git a/shell/browser/api/electron_api_web_contents.cc b/shell/browser/api/electron_api_web_contents.cc index a18f580f92..08ce691479 100644 --- a/shell/browser/api/electron_api_web_contents.cc +++ b/shell/browser/api/electron_api_web_contents.cc @@ -15,7 +15,6 @@ #include <vector> #include "base/base64.h" -#include "base/containers/contains.h" #include "base/containers/fixed_flat_map.h" #include "base/containers/id_map.h" #include "base/files/file_util.h" @@ -692,8 +691,7 @@ std::map<std::string, std::string> GetAddedFileSystemPaths( bool IsDevToolsFileSystemAdded(content::WebContents* web_contents, const std::string& file_system_path) { - return base::Contains(GetAddedFileSystemPaths(web_contents), - file_system_path); + return GetAddedFileSystemPaths(web_contents).contains(file_system_path); } content::RenderFrameHost* GetRenderFrameHost( @@ -4117,7 +4115,7 @@ void WebContents::DevToolsIndexPath( OnDevToolsIndexingDone(request_id, file_system_path); return; } - if (devtools_indexing_jobs_.count(request_id) != 0) + if (devtools_indexing_jobs_.contains(request_id)) return; std::vector<std::string> excluded_folders; std::optional<base::Value> parsed_excluded_folders = diff --git a/shell/browser/api/electron_api_web_frame_main.cc b/shell/browser/api/electron_api_web_frame_main.cc index 4936dc7806..40e3d811ba 100644 --- a/shell/browser/api/electron_api_web_frame_main.cc +++ b/shell/browser/api/electron_api_web_frame_main.cc @@ -155,7 +155,7 @@ WebFrameMain::WebFrameMain(content::RenderFrameHost* rfh) if (!render_frame_detached_) GetFrameTreeNodeIdMap().emplace(frame_tree_node_id_, this); - DCHECK(GetFrameTokenMap().find(frame_token_) == GetFrameTokenMap().end()); + DCHECK(!GetFrameTokenMap().contains(frame_token_)); GetFrameTokenMap().emplace(frame_token_, this); // WebFrameMain should only be created for active or unloading frames. @@ -193,7 +193,7 @@ void WebFrameMain::UpdateRenderFrameHost(content::RenderFrameHost* rfh) { // Ensure that RFH being swapped in doesn't already exist as its own // WebFrameMain instance. frame_token_ = rfh->GetGlobalFrameToken(); - DCHECK(GetFrameTokenMap().find(frame_token_) == GetFrameTokenMap().end()); + DCHECK(!GetFrameTokenMap().contains(frame_token_)); GetFrameTokenMap().emplace(frame_token_, this); render_frame_disposed_ = false; diff --git a/shell/browser/api/electron_api_web_request.cc b/shell/browser/api/electron_api_web_request.cc index 0410c9683d..095f96397a 100644 --- a/shell/browser/api/electron_api_web_request.cc +++ b/shell/browser/api/electron_api_web_request.cc @@ -9,7 +9,6 @@ #include <string_view> #include <utility> -#include "base/containers/contains.h" #include "base/containers/fixed_flat_map.h" #include "base/memory/raw_ptr.h" #include "base/task/sequenced_task_runner.h" @@ -251,7 +250,7 @@ bool WebRequest::RequestFilter::MatchesURL( bool WebRequest::RequestFilter::MatchesType( extensions::WebRequestResourceType type) const { - return types_.empty() || base::Contains(types_, type); + return types_.empty() || types_.contains(type); } bool WebRequest::RequestFilter::MatchesRequest( diff --git a/shell/browser/api/message_port.cc b/shell/browser/api/message_port.cc index 3d56361fc7..a4ffcf5fe5 100644 --- a/shell/browser/api/message_port.cc +++ b/shell/browser/api/message_port.cc @@ -8,7 +8,6 @@ #include <unordered_set> #include <utility> -#include "base/containers/contains.h" #include "base/containers/to_vector.h" #include "base/task/single_thread_task_runner.h" #include "gin/arguments.h" @@ -233,7 +232,7 @@ std::vector<blink::MessagePortChannel> MessagePort::DisentanglePorts( // or cloned ports, throw an error (per section 8.3.3 of the HTML5 spec). for (unsigned i = 0; i < ports.size(); ++i) { auto* port = ports[i].get(); - if (!port || port->IsNeutered() || base::Contains(visited, port)) { + if (!port || port->IsNeutered() || visited.contains(port)) { std::string type; if (!port) type = "null"; diff --git a/shell/browser/electron_autofill_driver_factory.cc b/shell/browser/electron_autofill_driver_factory.cc index 2a6b0e0e87..b2a68d4ec0 100644 --- a/shell/browser/electron_autofill_driver_factory.cc +++ b/shell/browser/electron_autofill_driver_factory.cc @@ -83,7 +83,7 @@ AutofillDriver* AutofillDriverFactory::DriverForFrame( driver.get()); } else { driver_map_.erase(insertion_result.first); - DCHECK_EQ(driver_map_.count(render_frame_host), 0u); + DCHECK(!driver_map_.contains(render_frame_host)); return nullptr; } } diff --git a/shell/browser/electron_browser_client.cc b/shell/browser/electron_browser_client.cc index 4ea923440c..2766dc7b4e 100644 --- a/shell/browser/electron_browser_client.cc +++ b/shell/browser/electron_browser_client.cc @@ -379,7 +379,7 @@ content::SiteInstance* ElectronBrowserClient::GetSiteInstanceFromAffinity( bool ElectronBrowserClient::IsRendererSubFrame( content::ChildProcessId process_id) const { - return base::Contains(renderer_is_subframe_, process_id); + return renderer_is_subframe_.contains(process_id); } void ElectronBrowserClient::RenderProcessWillLaunch( diff --git a/shell/browser/extensions/api/scripting/scripting_api.cc b/shell/browser/extensions/api/scripting/scripting_api.cc index 2657446950..b8061016a2 100644 --- a/shell/browser/extensions/api/scripting/scripting_api.cc +++ b/shell/browser/extensions/api/scripting/scripting_api.cc @@ -7,7 +7,6 @@ #include <algorithm> #include "base/check.h" -#include "base/containers/contains.h" #include "base/json/json_writer.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" @@ -947,13 +946,13 @@ ScriptingGetRegisteredContentScriptsFunction::Run() { continue; } - if (!id_filter.empty() && !base::Contains(id_filter, script->id())) { + if (!id_filter.empty() && !id_filter.contains(script->id())) { continue; } auto registered_script = CreateRegisteredContentScriptInfo(*script); registered_script.persist_across_sessions = - base::Contains(persistent_script_ids, script->id()); + persistent_script_ids.contains(script->id()); // Remove the internally used prefix from the `script`'s ID before // returning. @@ -1123,7 +1122,7 @@ std::unique_ptr<UserScript> ScriptingUpdateContentScriptsFunction::ApplyUpdate( // original script is persisted and the flag is not specified. if (new_script.persist_across_sessions.value_or(false) || (!new_script.persist_across_sessions && - base::Contains(*script_ids_to_persist, new_script.id))) { + script_ids_to_persist->contains(new_script.id))) { script_ids_to_persist->insert(new_script.id); } diff --git a/shell/browser/extensions/api/tabs/tabs_api.cc b/shell/browser/extensions/api/tabs/tabs_api.cc index c1962e0b0d..50a8e2c371 100644 --- a/shell/browser/extensions/api/tabs/tabs_api.cc +++ b/shell/browser/extensions/api/tabs/tabs_api.cc @@ -11,6 +11,7 @@ #include <vector> #include "base/command_line.h" +#include "base/containers/contains.h" #include "base/strings/pattern.h" #include "base/types/expected_macros.h" #include "chrome/common/url_constants.h" diff --git a/shell/browser/extensions/electron_component_extension_resource_manager.cc b/shell/browser/extensions/electron_component_extension_resource_manager.cc index 66968ed0cb..d3ac6fd3ac 100644 --- a/shell/browser/extensions/electron_component_extension_resource_manager.cc +++ b/shell/browser/extensions/electron_component_extension_resource_manager.cc @@ -7,7 +7,6 @@ #include <string> #include <utility> -#include "base/containers/contains.h" #include "base/path_service.h" #include "base/values.h" #include "chrome/common/chrome_paths.h" @@ -89,7 +88,7 @@ void ElectronComponentExtensionResourceManager::AddComponentResourceEntries( resource_path = resource_path.NormalizePathSeparators(); if (!gen_folder_path.IsParent(resource_path)) { - DCHECK(!base::Contains(path_to_resource_id_, resource_path)); + DCHECK(!path_to_resource_id_.contains(resource_path)); path_to_resource_id_[resource_path] = entry.id; } else { // If the resource is a generated file, strip the generated folder's path, @@ -98,7 +97,7 @@ void ElectronComponentExtensionResourceManager::AddComponentResourceEntries( base::FilePath effective_path = base::FilePath().AppendASCII(resource_path.AsUTF8Unsafe().substr( gen_folder_path.value().length())); - DCHECK(!base::Contains(path_to_resource_id_, effective_path)); + DCHECK(!path_to_resource_id_.contains(effective_path)); path_to_resource_id_[effective_path] = entry.id; } } diff --git a/shell/browser/hid/electron_hid_delegate.cc b/shell/browser/hid/electron_hid_delegate.cc index 6f349d3d6d..1299da0a54 100644 --- a/shell/browser/hid/electron_hid_delegate.cc +++ b/shell/browser/hid/electron_hid_delegate.cc @@ -7,7 +7,6 @@ #include <string> #include <utility> -#include "base/containers/contains.h" #include "base/scoped_observation.h" #include "chrome/common/chrome_features.h" #include "content/public/browser/web_contents.h" @@ -118,7 +117,7 @@ std::unique_ptr<content::HidChooser> ElectronHidDelegate::RunChooser( // Start observing HidChooserContext for permission and device events. GetContextObserver(browser_context); - DCHECK(base::Contains(observations_, browser_context)); + DCHECK(observations_.contains(browser_context)); HidChooserController* controller = ControllerForFrame(render_frame_host); if (controller) { @@ -188,7 +187,7 @@ void ElectronHidDelegate::RemoveObserver( content::HidDelegate::Observer* observer) { if (!browser_context) return; - DCHECK(base::Contains(observations_, browser_context)); + DCHECK(observations_.contains(browser_context)); GetContextObserver(browser_context)->RemoveObserver(observer); } @@ -222,7 +221,7 @@ bool ElectronHidDelegate::IsServiceWorkerAllowedForOrigin( ElectronHidDelegate::ContextObservation* ElectronHidDelegate::GetContextObserver( content::BrowserContext* browser_context) { - if (!base::Contains(observations_, browser_context)) { + if (!observations_.contains(browser_context)) { observations_.emplace(browser_context, std::make_unique<ContextObservation>( this, browser_context)); } diff --git a/shell/browser/hid/hid_chooser_context.cc b/shell/browser/hid/hid_chooser_context.cc index 539b7c700f..e31d77267c 100644 --- a/shell/browser/hid/hid_chooser_context.cc +++ b/shell/browser/hid/hid_chooser_context.cc @@ -8,7 +8,6 @@ #include <utility> #include "base/command_line.h" -#include "base/containers/contains.h" #include "base/containers/map_util.h" #include "base/strings/utf_string_conversions.h" #include "base/values.h" @@ -94,7 +93,7 @@ base::Value HidChooserContext::DeviceInfoToValue( void HidChooserContext::GrantDevicePermission( const url::Origin& origin, const device::mojom::HidDeviceInfo& device) { - DCHECK(base::Contains(devices_, device.guid)); + DCHECK(devices_.contains(device.guid)); if (CanStorePersistentEntry(device)) { auto* permission_manager = static_cast<ElectronPermissionManager*>( browser_context_->GetPermissionControllerDelegate()); @@ -111,7 +110,7 @@ void HidChooserContext::GrantDevicePermission( void HidChooserContext::RevokeDevicePermission( const url::Origin& origin, const device::mojom::HidDeviceInfo& device) { - DCHECK(base::Contains(devices_, device.guid)); + DCHECK(devices_.contains(device.guid)); if (CanStorePersistentEntry(device)) { RevokePersistentDevicePermission(origin, device); } else { @@ -167,8 +166,7 @@ bool HidChooserContext::HasDevicePermission( return false; auto it = ephemeral_devices_.find(origin); - if (it != ephemeral_devices_.end() && - base::Contains(it->second, device.guid)) { + if (it != ephemeral_devices_.end() && it->second.contains(device.guid)) { return true; } @@ -189,7 +187,7 @@ bool HidChooserContext::IsFidoAllowedForOrigin(const url::Origin& origin) { }); if (origin.scheme() == extensions::kExtensionScheme && - base::Contains(kPrivilegedExtensionIds, origin.host())) { + kPrivilegedExtensionIds.contains(origin.host())) { return true; } #endif // BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) @@ -245,7 +243,7 @@ void HidChooserContext::DeviceAdded(device::mojom::HidDeviceInfoPtr device) { DCHECK(device); // Update the device list. - if (!base::Contains(devices_, device->guid)) + if (!devices_.contains(device->guid)) devices_.insert({device->guid, device->Clone()}); // Notify all observers. @@ -255,7 +253,7 @@ void HidChooserContext::DeviceAdded(device::mojom::HidDeviceInfoPtr device) { void HidChooserContext::DeviceRemoved(device::mojom::HidDeviceInfoPtr device) { DCHECK(device); - DCHECK(base::Contains(devices_, device->guid)); + DCHECK(devices_.contains(device->guid)); // Update the device list. devices_.erase(device->guid); @@ -276,7 +274,7 @@ void HidChooserContext::DeviceRemoved(device::mojom::HidDeviceInfoPtr device) { void HidChooserContext::DeviceChanged(device::mojom::HidDeviceInfoPtr device) { DCHECK(device); - DCHECK(base::Contains(devices_, device->guid)); + DCHECK(devices_.contains(device->guid)); // Update the device list. devices_[device->guid] = device->Clone(); diff --git a/shell/browser/plugins/plugin_utils.cc b/shell/browser/plugins/plugin_utils.cc index 68173a72e8..1da80c073d 100644 --- a/shell/browser/plugins/plugin_utils.cc +++ b/shell/browser/plugins/plugin_utils.cc @@ -6,7 +6,6 @@ #include <vector> -#include "base/containers/contains.h" #include "content/public/common/webplugininfo.h" #include "electron/buildflags/buildflags.h" #include "url/gurl.h" @@ -53,8 +52,7 @@ PluginUtils::GetMimeTypeToExtensionIdMap( if (MimeTypesHandler* handler = MimeTypesHandler::GetHandler(extension)) { for (const auto& supported_mime_type : handler->mime_type_set()) { - DCHECK(!base::Contains(mime_type_to_extension_id_map, - supported_mime_type)); + DCHECK(!mime_type_to_extension_id_map.contains(supported_mime_type)); mime_type_to_extension_id_map[supported_mime_type] = extension_id; } } diff --git a/shell/browser/serial/serial_chooser_context.cc b/shell/browser/serial/serial_chooser_context.cc index 8ef4c3f4e7..be387c644e 100644 --- a/shell/browser/serial/serial_chooser_context.cc +++ b/shell/browser/serial/serial_chooser_context.cc @@ -9,7 +9,6 @@ #include <utility> #include "base/base64.h" -#include "base/containers/contains.h" #include "base/values.h" #include "content/public/browser/device_service.h" #include "content/public/browser/web_contents.h" @@ -108,7 +107,7 @@ bool SerialChooserContext::HasPortPermission( auto it = ephemeral_ports_.find(origin); if (it != ephemeral_ports_.end()) { const std::set<base::UnguessableToken>& ports = it->second; - if (base::Contains(ports, port.token)) + if (ports.contains(port.token)) return true; } @@ -226,7 +225,7 @@ base::WeakPtr<SerialChooserContext> SerialChooserContext::AsWeakPtr() { } void SerialChooserContext::OnPortAdded(device::mojom::SerialPortInfoPtr port) { - if (!base::Contains(port_info_, port->token)) + if (!port_info_.contains(port->token)) port_info_.insert({port->token, port->Clone()}); for (auto& map_entry : ephemeral_ports_) { diff --git a/shell/browser/ui/cocoa/electron_touch_bar.mm b/shell/browser/ui/cocoa/electron_touch_bar.mm index 48913d74bd..39f8a53cb8 100644 --- a/shell/browser/ui/cocoa/electron_touch_bar.mm +++ b/shell/browser/ui/cocoa/electron_touch_bar.mm @@ -334,7 +334,7 @@ static NSString* const ImageScrubberItemIdentifier = @"scrubber.image.item"; } - (bool)hasItemWithID:(const std::string&)item_id { - return settings_.find(item_id) != settings_.end(); + return settings_.contains(item_id); } - (NSColor*)colorFromHexColorString:(const std::string&)colorString { diff --git a/shell/browser/ui/message_box_gtk.cc b/shell/browser/ui/message_box_gtk.cc index 2f2a5275a9..65498ae1a8 100644 --- a/shell/browser/ui/message_box_gtk.cc +++ b/shell/browser/ui/message_box_gtk.cc @@ -4,7 +4,6 @@ #include "shell/browser/ui/message_box.h" -#include "base/containers/contains.h" #include "base/containers/flat_map.h" #include "base/functional/bind.h" #include "base/memory/raw_ptr.h" @@ -232,7 +231,7 @@ int ShowMessageBoxSync(const MessageBoxSettings& settings) { void ShowMessageBox(const MessageBoxSettings& settings, MessageBoxCallback callback) { - if (settings.id && base::Contains(GetDialogsMap(), *settings.id)) + if (settings.id && GetDialogsMap().contains(*settings.id)) CloseMessageBox(*settings.id); (new GtkMessageBox(settings))->RunAsynchronous(std::move(callback)); } diff --git a/shell/browser/ui/message_box_mac.mm b/shell/browser/ui/message_box_mac.mm index e4e11946ad..3adf5f720e 100644 --- a/shell/browser/ui/message_box_mac.mm +++ b/shell/browser/ui/message_box_mac.mm @@ -8,7 +8,6 @@ #import <Cocoa/Cocoa.h> -#include "base/containers/contains.h" #include "base/containers/flat_map.h" #include "base/mac/mac_util.h" #include "base/no_destructor.h" @@ -146,7 +145,7 @@ void ShowMessageBox(const MessageBoxSettings& settings, ret, alert.suppressionButton.state == NSControlStateValueOn); } else { if (settings.id) { - if (base::Contains(GetDialogsMap(), *settings.id)) + if (GetDialogsMap().contains(*settings.id)) CloseMessageBox(*settings.id); GetDialogsMap()[*settings.id] = alert; } diff --git a/shell/browser/ui/message_box_win.cc b/shell/browser/ui/message_box_win.cc index 2b513e50c7..e8658938e5 100644 --- a/shell/browser/ui/message_box_win.cc +++ b/shell/browser/ui/message_box_win.cc @@ -10,7 +10,6 @@ #include <vector> -#include "base/containers/contains.h" #include "base/containers/flat_map.h" #include "base/no_destructor.h" #include "base/strings/string_util.h" @@ -242,7 +241,7 @@ DialogResult ShowTaskDialogWstr(gfx::AcceleratedWidget parent, TaskDialogIndirect(&config, &id, nullptr, &verification_flag_checked); int button_id; - if (base::Contains(id_map, id)) // common button. + if (id_map.contains(id)) // common button. button_id = id_map[id]; else if (id >= kIDStart) // custom button. button_id = id - kIDStart; @@ -289,7 +288,7 @@ void ShowMessageBox(const MessageBoxSettings& settings, // kHwndReserve in the dialogs map for now. HWND* hwnd = nullptr; if (settings.id) { - if (base::Contains(GetDialogsMap(), *settings.id)) + if (GetDialogsMap().contains(*settings.id)) CloseMessageBox(*settings.id); auto it = GetDialogsMap().emplace(*settings.id, std::make_unique<HWND>(kHwndReserve)); diff --git a/shell/browser/usb/electron_usb_delegate.cc b/shell/browser/usb/electron_usb_delegate.cc index 443dcd511e..4e3827d04f 100644 --- a/shell/browser/usb/electron_usb_delegate.cc +++ b/shell/browser/usb/electron_usb_delegate.cc @@ -7,7 +7,6 @@ #include <string_view> #include <utility> -#include "base/containers/contains.h" #include "base/observer_list.h" #include "base/scoped_observation.h" #include "content/public/browser/render_frame_host.h" @@ -72,7 +71,7 @@ bool IsDevicePermissionAutoGranted( // 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()) && + kSmartCardPrivilegedExtensionIds.contains(origin.host()) && DeviceHasInterfaceWithClass(device_info, device::mojom::kUsbSmartCardClass)) { return true; @@ -269,7 +268,7 @@ ElectronUsbDelegate::ContextObservation* ElectronUsbDelegate::GetContextObserver( content::BrowserContext* browser_context) { CHECK(browser_context); - if (!base::Contains(observations_, browser_context)) { + if (!observations_.contains(browser_context)) { observations_.emplace(browser_context, std::make_unique<ContextObservation>( this, browser_context)); } diff --git a/shell/browser/usb/usb_chooser_context.cc b/shell/browser/usb/usb_chooser_context.cc index 22c6bf80b0..3b5d26b5f7 100644 --- a/shell/browser/usb/usb_chooser_context.cc +++ b/shell/browser/usb/usb_chooser_context.cc @@ -8,7 +8,6 @@ #include <utility> #include <vector> -#include "base/containers/contains.h" #include "base/functional/bind.h" #include "base/task/sequenced_task_runner.h" #include "base/values.h" @@ -158,7 +157,7 @@ UsbChooserContext::~UsbChooserContext() { void UsbChooserContext::RevokeDevicePermissionWebInitiated( const url::Origin& origin, const device::mojom::UsbDeviceInfo& device) { - DCHECK(base::Contains(devices_, device.guid)); + DCHECK(devices_.contains(device.guid)); RevokeObjectPermissionInternal(origin, DeviceInfoToValue(device), /*revoked_by_website=*/true); } @@ -217,8 +216,7 @@ 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)) { + if (it != ephemeral_devices_.end() && it->second.contains(device_info.guid)) { return true; } @@ -284,7 +282,7 @@ void UsbChooserContext::OnDeviceAdded( device::mojom::UsbDeviceInfoPtr device_info) { DCHECK(device_info); // Update the device list. - DCHECK(!base::Contains(devices_, device_info->guid)); + DCHECK(!devices_.contains(device_info->guid)); if (!ShouldExposeDevice(*device_info)) return; devices_.insert(std::make_pair(device_info->guid, device_info->Clone())); @@ -299,12 +297,12 @@ void UsbChooserContext::OnDeviceRemoved( DCHECK(device_info); if (!ShouldExposeDevice(*device_info)) { - DCHECK(!base::Contains(devices_, device_info->guid)); + DCHECK(!devices_.contains(device_info->guid)); return; } // Update the device list. - DCHECK(base::Contains(devices_, device_info->guid)); + DCHECK(devices_.contains(device_info->guid)); devices_.erase(device_info->guid); // Notify all device observers. diff --git a/shell/common/api/electron_api_clipboard.cc b/shell/common/api/electron_api_clipboard.cc index 5f1e19775c..aad1d4eece 100644 --- a/shell/common/api/electron_api_clipboard.cc +++ b/shell/common/api/electron_api_clipboard.cc @@ -6,7 +6,6 @@ #include <map> -#include "base/containers/contains.h" #include "base/containers/to_vector.h" #include "base/run_loop.h" #include "base/strings/utf_string_conversions.h" @@ -76,7 +75,7 @@ std::string Clipboard::Read(const std::string& format_string) { clipboard->ExtractCustomPlatformNames(ui::ClipboardBuffer::kCopyPaste, /* data_dst = */ nullptr); #if BUILDFLAG(IS_LINUX) - if (!base::Contains(custom_format_names, format_string)) { + if (!custom_format_names.contains(format_string)) { custom_format_names = clipboard->ExtractCustomPlatformNames(ui::ClipboardBuffer::kSelection, /* data_dst = */ nullptr); @@ -84,7 +83,7 @@ std::string Clipboard::Read(const std::string& format_string) { #endif ui::ClipboardFormatType format; - if (base::Contains(custom_format_names, format_string)) { + if (custom_format_names.contains(format_string)) { format = ui::ClipboardFormatType(ui::ClipboardFormatType::CustomPlatformType( custom_format_names[format_string])); diff --git a/shell/renderer/api/electron_api_context_bridge.cc b/shell/renderer/api/electron_api_context_bridge.cc index 7de4a65456..016d377d13 100644 --- a/shell/renderer/api/electron_api_context_bridge.cc +++ b/shell/renderer/api/electron_api_context_bridge.cc @@ -11,7 +11,6 @@ #include <utility> #include <vector> -#include "base/containers/contains.h" #include "base/feature_list.h" #include "base/json/json_writer.h" #include "base/trace_event/trace_event.h" @@ -69,7 +68,7 @@ bool DeepFreeze(const v8::Local<v8::Object>& object, const v8::Local<v8::Context>& context, std::set<int> frozen = std::set<int>()) { int hash = object->GetIdentityHash(); - if (base::Contains(frozen, hash)) + if (frozen.contains(hash)) return true; frozen.insert(hash); diff --git a/shell/renderer/api/electron_api_spell_check_client.cc b/shell/renderer/api/electron_api_spell_check_client.cc index 6626d8b2ce..e3be831ee2 100644 --- a/shell/renderer/api/electron_api_spell_check_client.cc +++ b/shell/renderer/api/electron_api_spell_check_client.cc @@ -12,7 +12,6 @@ #include <utility> #include <vector> -#include "base/containers/contains.h" #include "base/logging.h" #include "base/numerics/safe_conversions.h" #include "base/strings/utf_string_conversion_utils.h" @@ -190,13 +189,13 @@ void SpellCheckClient::OnSpellCheckDone( auto& word_list = pending_request_param_->wordlist(); for (const auto& word : word_list) { - if (base::Contains(misspelled, word.text)) { + if (misspelled.contains(word.text)) { // If this is a contraction, iterate through parts and accept the word // if none of them are misspelled if (!word.contraction_words.empty()) { auto all_correct = true; for (const auto& contraction_word : word.contraction_words) { - if (base::Contains(misspelled, contraction_word)) { + if (misspelled.contains(contraction_word)) { all_correct = false; break; } diff --git a/shell/renderer/electron_renderer_client.cc b/shell/renderer/electron_renderer_client.cc index 1c7f79516c..c18b81d49d 100644 --- a/shell/renderer/electron_renderer_client.cc +++ b/shell/renderer/electron_renderer_client.cc @@ -238,7 +238,7 @@ void ElectronRendererClient::WillDestroyWorkerContextOnWorkerThread( node::Environment* ElectronRendererClient::GetEnvironment( content::RenderFrame* render_frame) const { - if (!base::Contains(injected_frames_, render_frame)) + if (!injected_frames_.contains(render_frame)) return nullptr; v8::HandleScope handle_scope(v8::Isolate::GetCurrent()); auto context = diff --git a/shell/renderer/electron_sandboxed_renderer_client.cc b/shell/renderer/electron_sandboxed_renderer_client.cc index 48aa42f6cd..d98e2b3275 100644 --- a/shell/renderer/electron_sandboxed_renderer_client.cc +++ b/shell/renderer/electron_sandboxed_renderer_client.cc @@ -10,7 +10,6 @@ #include "base/base_paths.h" #include "base/command_line.h" -#include "base/containers/contains.h" #include "base/process/process_metrics.h" #include "content/public/renderer/render_frame.h" #include "shell/common/api/electron_bindings.h" @@ -158,7 +157,7 @@ void ElectronSandboxedRendererClient::WillReleaseScriptContext( void ElectronSandboxedRendererClient::EmitProcessEvent( content::RenderFrame* render_frame, const char* event_name) { - if (!base::Contains(injected_frames_, render_frame)) + if (!injected_frames_.contains(render_frame)) return; blink::WebLocalFrame* frame = render_frame->GetWebFrame();
refactor
66b4b216468feab79c7527295f2485067ea2cf15
David Sanders
2023-12-04 07:18:14
ci: tweak new release board workflow (#40680) * ci: tweak new release board workflow * ci: fix workflow
diff --git a/.github/workflows/branch-created.yml b/.github/workflows/branch-created.yml index 3f5a6e1e1c..5498691903 100644 --- a/.github/workflows/branch-created.yml +++ b/.github/workflows/branch-created.yml @@ -8,7 +8,7 @@ permissions: {} jobs: release-branch-created: name: Release Branch Created - if: ${{ github.event.ref_type == 'branch' && endsWith(github.event.ref, '-x-y') }} + if: ${{ github.event.ref_type == 'branch' && endsWith(github.event.ref, '-x-y') && !startsWith(github.event.ref, 'roller') }} permissions: contents: read pull-requests: write @@ -87,6 +87,7 @@ jobs: - name: Create Release Project Board if: ${{ steps.check-major-version.outputs.MAJOR }} uses: dsanders11/project-actions/copy-project@3a81985616963f32fae17d1d1b406c631f3201a1 # v1.1.0 + id: create-release-board with: drafts: true project-number: 64 @@ -96,6 +97,11 @@ jobs: template-view: ${{ steps.generate-project-metadata.outputs.template-view }} title: ${{ steps.generate-project-metadata.outputs.major }}-x-y token: ${{ steps.generate-token.outputs.token }} + - name: Dump Release Project Board Contents + if: ${{ steps.check-major-version.outputs.MAJOR }} + run: gh project item-list ${{ steps.create-release-board.outputs.number }} --owner electron --format json | jq + env: + GITHUB_TOKEN: ${{ steps.generate-token.outputs.token }} - name: Find Previous Release Project Board if: ${{ steps.check-major-version.outputs.MAJOR }} uses: dsanders11/project-actions/find-project@3a81985616963f32fae17d1d1b406c631f3201a1 # v1.1.0
ci
bf754a3cae84fba9896011320c09c0fe554886b2
James Yuzawa
2024-04-17 12:42:34
fix: make window.flashFrame(bool) flash continuously on macOS (#41391) fix: window.flashFrame to flash continuously on mac This brings the behavior to parity with Windows and Linux. Prior behavior: The first `flashFrame(true)` bounces the dock icon only once (using the [NSInformationalRequest](https://developer.apple.com/documentation/appkit/nsrequestuserattentiontype/nsinformationalrequest) level) and `flashFrame(false)` does nothing. New behavior: Flash continuously until `flashFrame(false)` is called. This uses the [NSCriticalRequest](https://developer.apple.com/documentation/appkit/nsrequestuserattentiontype/nscriticalrequest) level instead. To explicitly use `NSInformationalRequest` to cause a single dock icon bounce, it is still possible to use [`dock.bounce('informational')`](https://www.electronjs.org/docs/latest/api/dock#dockbouncetype-macos).
diff --git a/docs/breaking-changes.md b/docs/breaking-changes.md index 6f8e3b19b6..dfc1798178 100644 --- a/docs/breaking-changes.md +++ b/docs/breaking-changes.md @@ -21,6 +21,10 @@ encoded data returned from this function now matches it. See [crbug.com/332584706](https://issues.chromium.org/issues/332584706) for more information. +### Behavior Changed: `window.flashFrame(bool)` will flash dock icon continuously on macOS + +This brings the behavior to parity with Windows and Linux. Prior behavior: The first `flashFrame(true)` bounces the dock icon only once (using the [NSInformationalRequest](https://developer.apple.com/documentation/appkit/nsrequestuserattentiontype/nsinformationalrequest) level) and `flashFrame(false)` does nothing. New behavior: Flash continuously until `flashFrame(false)` is called. This uses the [NSCriticalRequest](https://developer.apple.com/documentation/appkit/nsrequestuserattentiontype/nscriticalrequest) level instead. To explicitly use `NSInformationalRequest` to cause a single dock icon bounce, it is still possible to use [`dock.bounce('informational')`](https://www.electronjs.org/docs/latest/api/dock#dockbouncetype-macos). + ## Planned Breaking API Changes (30.0) ### Behavior Changed: cross-origin iframes now use Permission Policy to access features diff --git a/shell/browser/native_window_mac.mm b/shell/browser/native_window_mac.mm index 7fab6b14bd..e9909c0a53 100644 --- a/shell/browser/native_window_mac.mm +++ b/shell/browser/native_window_mac.mm @@ -1004,7 +1004,7 @@ std::string NativeWindowMac::GetTitle() const { void NativeWindowMac::FlashFrame(bool flash) { if (flash) { - attention_request_id_ = [NSApp requestUserAttention:NSInformationalRequest]; + attention_request_id_ = [NSApp requestUserAttention:NSCriticalRequest]; } else { [NSApp cancelUserAttentionRequest:attention_request_id_]; attention_request_id_ = 0;
fix
0fd16dc9e2a919da2a65cf890865cf4779a57404
Shelley Vohr
2024-11-13 15:11:58
fix: WCO buttons hidden on Linux in fullscreen (#44621) Closes https://github.com/electron/electron/issues/44569. Fixes an issue where the WCO buttons were hidden on Linux in fullscreen mode but not on Windows or macOS. The Windows behavior is the expected one, so this commit makes the Linux behavior consistent.
diff --git a/shell/browser/ui/views/opaque_frame_view.cc b/shell/browser/ui/views/opaque_frame_view.cc index 0207fb0dde..c30f37e9a0 100644 --- a/shell/browser/ui/views/opaque_frame_view.cc +++ b/shell/browser/ui/views/opaque_frame_view.cc @@ -255,14 +255,17 @@ void OpaqueFrameView::LayoutWindowControls() { buttons_not_shown.push_back(views::FrameButton::kMinimize); buttons_not_shown.push_back(views::FrameButton::kClose); - for (const auto& button : leading_buttons_) { - ConfigureButton(button, ALIGN_LEADING); - std::erase(buttons_not_shown, button); - } + // We do not want to show the buttons in fullscreen mode. + if (!frame()->IsFullscreen()) { + for (const auto& button : leading_buttons_) { + ConfigureButton(button, ALIGN_LEADING); + std::erase(buttons_not_shown, button); + } - for (const auto& button : base::Reversed(trailing_buttons_)) { - ConfigureButton(button, ALIGN_TRAILING); - std::erase(buttons_not_shown, button); + for (const auto& button : base::Reversed(trailing_buttons_)) { + ConfigureButton(button, ALIGN_TRAILING); + std::erase(buttons_not_shown, button); + } } for (const auto& button_id : buttons_not_shown) @@ -401,8 +404,7 @@ void OpaqueFrameView::ConfigureButton(views::FrameButton button_id, ButtonAlignment alignment) { switch (button_id) { case views::FrameButton::kMinimize: { - bool can_minimize = true; // delegate_->CanMinimize(); - if (can_minimize) { + if (window()->IsMinimizable()) { minimize_button_->SetVisible(true); SetBoundsForButton(button_id, minimize_button_, alignment); } else { @@ -411,8 +413,7 @@ void OpaqueFrameView::ConfigureButton(views::FrameButton button_id, break; } case views::FrameButton::kMaximize: { - bool can_maximize = true; // delegate_->CanMaximize(); - if (can_maximize) { + if (window()->IsMaximizable()) { // When the window is restored, we show a maximized button; otherwise, // we show a restore button. bool is_restored = !window()->IsMaximized() && !window()->IsMinimized(); @@ -430,8 +431,12 @@ void OpaqueFrameView::ConfigureButton(views::FrameButton button_id, break; } case views::FrameButton::kClose: { - close_button_->SetVisible(true); - SetBoundsForButton(button_id, close_button_, alignment); + if (window()->IsClosable()) { + close_button_->SetVisible(true); + SetBoundsForButton(button_id, close_button_, alignment); + } else { + HideButton(button_id); + } break; } }
fix
2191e9b8e1def50138f58811d822401bb1edbd6b
electron-appveyor-updater[bot]
2024-12-11 13:27:21
build: update appveyor image to latest version (#44992) Co-authored-by: electron-appveyor-updater[bot] <161660339+electron-appveyor-updater[bot]@users.noreply.github.com>
diff --git a/appveyor-woa.yml b/appveyor-woa.yml index f187be26ff..7dd4b3ca1d 100644 --- a/appveyor-woa.yml +++ b/appveyor-woa.yml @@ -29,7 +29,7 @@ version: 1.0.{build} build_cloud: electronhq-16-core -image: e-133.0.6852.0 +image: e-133.0.6878.0 environment: GIT_CACHE_PATH: C:\Users\appveyor\libcc_cache ELECTRON_OUT_DIR: Default diff --git a/appveyor.yml b/appveyor.yml index 62f4228f36..21d0698948 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -29,7 +29,7 @@ version: 1.0.{build} build_cloud: electronhq-16-core -image: e-133.0.6852.0 +image: e-133.0.6878.0 environment: GIT_CACHE_PATH: C:\Users\appveyor\libcc_cache ELECTRON_OUT_DIR: Default
build
f36ceae0242f3b54cfe7e7712219f410b7beff81
Charles Kerr
2024-01-10 19:00:37
chore: migrate base::StringPiece to std::string_view (#40915) * chore: migrate from base::StringPiece to std::string_view in keyboard_util.cc * chore: migrate from base::StringPiece to std::string_view in error_thrower.cc * chore: migrate from base::StringPiece to std::string_view in electron_api_web_contents.cc * chore: migrate from base::StringPiece to std::string_view in gin_helper/dictionary.h * chore: migrate from base::StringPiece to std::string_view in electron_api_url_loader.cc * chore: phase out internal use of base:::StringPiece `base::StringPiece` is being phased out upstream. Its code has been removed upstream and it's just a typedef for `std::string_view`. They haven't removed the typedef yet, so this PR tries to get ahead of future breakage by migrating "internal" use (i.e. leaving alone the places where the `base::StringPiece` name is coming from an upstream method that we override). Xref: https://bugs.chromium.org/p/chromium/issues/detail?id=691162 Xref: https://chromium-review.googlesource.com/c/chromium/src/+/4294483 Xref: https://docs.google.com/document/d/1d4RnD1uAE2t4iANR0nXy82ASIPGsPuw2mpO6v6T7JKs
diff --git a/shell/app/electron_content_client.cc b/shell/app/electron_content_client.cc index 7e6da642bb..79c3a352b9 100644 --- a/shell/app/electron_content_client.cc +++ b/shell/app/electron_content_client.cc @@ -5,6 +5,7 @@ #include "shell/app/electron_content_client.h" #include <string> +#include <string_view> #include <utility> #include <vector> @@ -106,12 +107,12 @@ bool IsWidevineAvailable( } #endif // BUILDFLAG(ENABLE_WIDEVINE) -void AppendDelimitedSwitchToVector(const base::StringPiece cmd_switch, +void AppendDelimitedSwitchToVector(const std::string_view cmd_switch, std::vector<std::string>* append_me) { auto* command_line = base::CommandLine::ForCurrentProcess(); auto switch_value = command_line->GetSwitchValueASCII(cmd_switch); if (!switch_value.empty()) { - constexpr base::StringPiece delimiter(",", 1); + constexpr std::string_view delimiter{",", 1}; auto tokens = base::SplitString(switch_value, delimiter, base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY); diff --git a/shell/app/electron_main_delegate.cc b/shell/app/electron_main_delegate.cc index 19d01f471e..a6f30149b4 100644 --- a/shell/app/electron_main_delegate.cc +++ b/shell/app/electron_main_delegate.cc @@ -7,6 +7,7 @@ #include <iostream> #include <memory> #include <string> +#include <string_view> #include <utility> #include "base/apple/bundle_locations.h" @@ -80,9 +81,9 @@ namespace { const char kRelauncherProcess[] = "relauncher"; -constexpr base::StringPiece kElectronDisableSandbox("ELECTRON_DISABLE_SANDBOX"); -constexpr base::StringPiece kElectronEnableStackDumping( - "ELECTRON_ENABLE_STACK_DUMPING"); +constexpr std::string_view kElectronDisableSandbox{"ELECTRON_DISABLE_SANDBOX"}; +constexpr std::string_view kElectronEnableStackDumping{ + "ELECTRON_ENABLE_STACK_DUMPING"}; // Returns true if this subprocess type needs the ResourceBundle initialized // and resources loaded. diff --git a/shell/app/node_main.cc b/shell/app/node_main.cc index 469b7e31c8..1d6af29d98 100644 --- a/shell/app/node_main.cc +++ b/shell/app/node_main.cc @@ -7,6 +7,7 @@ #include <map> #include <memory> #include <string> +#include <string_view> #include <utility> #include <vector> @@ -60,7 +61,7 @@ namespace { // See https://nodejs.org/api/cli.html#cli_options void ExitIfContainsDisallowedFlags(const std::vector<std::string>& argv) { // Options that are unilaterally disallowed. - static constexpr auto disallowed = base::MakeFixedFlatSet<base::StringPiece>({ + static constexpr auto disallowed = base::MakeFixedFlatSet<std::string_view>({ "--enable-fips", "--force-fips", "--openssl-config", @@ -69,7 +70,7 @@ void ExitIfContainsDisallowedFlags(const std::vector<std::string>& argv) { }); for (const auto& arg : argv) { - const auto key = base::StringPiece(arg).substr(0, arg.find('=')); + const auto key = std::string_view{arg}.substr(0, arg.find('=')); if (disallowed.contains(key)) { LOG(ERROR) << "The Node.js cli flag " << key << " is not supported in Electron"; diff --git a/shell/browser/api/electron_api_app.cc b/shell/browser/api/electron_api_app.cc index 1b3f213ff6..32f772fc54 100644 --- a/shell/browser/api/electron_api_app.cc +++ b/shell/browser/api/electron_api_app.cc @@ -7,6 +7,7 @@ #include <memory> #include <optional> #include <string> +#include <string_view> #include <utility> #include <vector> @@ -157,7 +158,7 @@ struct Converter<JumpListItem::Type> { private: static constexpr auto Lookup = - base::MakeFixedFlatMap<base::StringPiece, JumpListItem::Type>({ + base::MakeFixedFlatMap<std::string_view, JumpListItem::Type>({ {"file", JumpListItem::Type::kFile}, {"separator", JumpListItem::Type::kSeparator}, {"task", JumpListItem::Type::kTask}, @@ -248,7 +249,7 @@ struct Converter<JumpListCategory::Type> { private: static constexpr auto Lookup = - base::MakeFixedFlatMap<base::StringPiece, JumpListCategory::Type>({ + base::MakeFixedFlatMap<std::string_view, JumpListCategory::Type>({ {"custom", JumpListCategory::Type::kCustom}, {"frequent", JumpListCategory::Type::kFrequent}, {"recent", JumpListCategory::Type::kRecent}, @@ -414,7 +415,7 @@ struct Converter<net::SecureDnsMode> { v8::Local<v8::Value> val, net::SecureDnsMode* out) { static constexpr auto Lookup = - base::MakeFixedFlatMap<base::StringPiece, net::SecureDnsMode>({ + base::MakeFixedFlatMap<std::string_view, net::SecureDnsMode>({ {"automatic", net::SecureDnsMode::kAutomatic}, {"off", net::SecureDnsMode::kOff}, {"secure", net::SecureDnsMode::kSecure}, @@ -440,9 +441,9 @@ IconLoader::IconSize GetIconSizeByString(const std::string& size) { } // Return the path constant from string. -int GetPathConstant(base::StringPiece name) { +int GetPathConstant(std::string_view name) { // clang-format off - constexpr auto Lookup = base::MakeFixedFlatMap<base::StringPiece, int>({ + constexpr auto Lookup = base::MakeFixedFlatMap<std::string_view, int>({ {"appData", DIR_APP_DATA}, #if BUILDFLAG(IS_POSIX) {"cache", base::DIR_CACHE}, diff --git a/shell/browser/api/electron_api_base_window.h b/shell/browser/api/electron_api_base_window.h index 2c2d0fdf57..7bff94b776 100644 --- a/shell/browser/api/electron_api_base_window.h +++ b/shell/browser/api/electron_api_base_window.h @@ -9,6 +9,7 @@ #include <memory> #include <optional> #include <string> +#include <string_view> #include <vector> #include "content/public/browser/browser_task_traits.h" @@ -249,7 +250,7 @@ class BaseWindow : public gin_helper::TrackableObject<BaseWindow>, void RemoveFromParentChildWindows(); template <typename... Args> - void EmitEventSoon(base::StringPiece eventName) { + void EmitEventSoon(std::string_view eventName) { content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(base::IgnoreResult(&BaseWindow::Emit<Args...>), diff --git a/shell/browser/api/electron_api_cookies.cc b/shell/browser/api/electron_api_cookies.cc index d166af491a..e3dc8a05da 100644 --- a/shell/browser/api/electron_api_cookies.cc +++ b/shell/browser/api/electron_api_cookies.cc @@ -4,6 +4,8 @@ #include "shell/browser/api/electron_api_cookies.h" +#include <string> +#include <string_view> #include <utility> #include "base/time/time.h" @@ -169,7 +171,7 @@ base::Time ParseTimeProperty(const std::optional<double>& value) { return base::Time::FromSecondsSinceUnixEpoch(*value); } -base::StringPiece InclusionStatusToString(net::CookieInclusionStatus status) { +std::string_view InclusionStatusToString(net::CookieInclusionStatus status) { if (status.HasExclusionReason(net::CookieInclusionStatus::EXCLUDE_HTTP_ONLY)) return "Failed to create httponly cookie"; if (status.HasExclusionReason( diff --git a/shell/browser/api/electron_api_protocol.cc b/shell/browser/api/electron_api_protocol.cc index 24f2cf1e17..8d07bb4cc0 100644 --- a/shell/browser/api/electron_api_protocol.cc +++ b/shell/browser/api/electron_api_protocol.cc @@ -4,6 +4,7 @@ #include "shell/browser/api/electron_api_protocol.h" +#include <string_view> #include <vector> #include "base/command_line.h" @@ -193,7 +194,7 @@ const char* const kBuiltinSchemes[] = { }; // Convert error code to string. -constexpr base::StringPiece ErrorCodeToString(ProtocolError error) { +constexpr std::string_view ErrorCodeToString(ProtocolError error) { switch (error) { case ProtocolError::kRegistered: return "The scheme has been registered"; diff --git a/shell/browser/api/electron_api_screen.cc b/shell/browser/api/electron_api_screen.cc index 73e5c93597..ed88274205 100644 --- a/shell/browser/api/electron_api_screen.cc +++ b/shell/browser/api/electron_api_screen.cc @@ -5,6 +5,7 @@ #include "shell/browser/api/electron_api_screen.h" #include <string> +#include <string_view> #include "base/functional/bind.h" #include "gin/dictionary.h" @@ -49,13 +50,13 @@ std::vector<std::string> MetricsToArray(uint32_t metrics) { } void DelayEmit(Screen* screen, - base::StringPiece name, + const std::string_view name, const display::Display& display) { screen->Emit(name, display); } void DelayEmitWithMetrics(Screen* screen, - base::StringPiece name, + const std::string_view name, const display::Display& display, const std::vector<std::string>& metrics) { screen->Emit(name, display, metrics); diff --git a/shell/browser/api/electron_api_service_worker_context.cc b/shell/browser/api/electron_api_service_worker_context.cc index 0c910a618a..e11b9ce91c 100644 --- a/shell/browser/api/electron_api_service_worker_context.cc +++ b/shell/browser/api/electron_api_service_worker_context.cc @@ -4,6 +4,7 @@ #include "shell/browser/api/electron_api_service_worker_context.h" +#include <string_view> #include <utility> #include "chrome/browser/browser_process.h" @@ -24,7 +25,7 @@ namespace electron::api { namespace { -constexpr base::StringPiece MessageSourceToString( +constexpr std::string_view MessageSourceToString( const blink::mojom::ConsoleMessageSource source) { switch (source) { case blink::mojom::ConsoleMessageSource::kXml: diff --git a/shell/browser/api/electron_api_system_preferences_win.cc b/shell/browser/api/electron_api_system_preferences_win.cc index 4c96b86499..3ebeea4797 100644 --- a/shell/browser/api/electron_api_system_preferences_win.cc +++ b/shell/browser/api/electron_api_system_preferences_win.cc @@ -2,10 +2,12 @@ // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. +#include <iomanip> +#include <string_view> + #include <dwmapi.h> #include <windows.devices.enumeration.h> #include <wrl/client.h> -#include <iomanip> #include "shell/browser/api/electron_api_system_preferences.h" @@ -98,39 +100,38 @@ std::string SystemPreferences::GetAccentColor() { std::string SystemPreferences::GetColor(gin_helper::ErrorThrower thrower, const std::string& color) { - static constexpr auto Lookup = - base::MakeFixedFlatMap<base::StringPiece, int>({ - {"3d-dark-shadow", COLOR_3DDKSHADOW}, - {"3d-face", COLOR_3DFACE}, - {"3d-highlight", COLOR_3DHIGHLIGHT}, - {"3d-light", COLOR_3DLIGHT}, - {"3d-shadow", COLOR_3DSHADOW}, - {"active-border", COLOR_ACTIVEBORDER}, - {"active-caption", COLOR_ACTIVECAPTION}, - {"active-caption-gradient", COLOR_GRADIENTACTIVECAPTION}, - {"app-workspace", COLOR_APPWORKSPACE}, - {"button-text", COLOR_BTNTEXT}, - {"caption-text", COLOR_CAPTIONTEXT}, - {"desktop", COLOR_DESKTOP}, - {"disabled-text", COLOR_GRAYTEXT}, - {"highlight", COLOR_HIGHLIGHT}, - {"highlight-text", COLOR_HIGHLIGHTTEXT}, - {"hotlight", COLOR_HOTLIGHT}, - {"inactive-border", COLOR_INACTIVEBORDER}, - {"inactive-caption", COLOR_INACTIVECAPTION}, - {"inactive-caption-gradient", COLOR_GRADIENTINACTIVECAPTION}, - {"inactive-caption-text", COLOR_INACTIVECAPTIONTEXT}, - {"info-background", COLOR_INFOBK}, - {"info-text", COLOR_INFOTEXT}, - {"menu", COLOR_MENU}, - {"menu-highlight", COLOR_MENUHILIGHT}, - {"menu-text", COLOR_MENUTEXT}, - {"menubar", COLOR_MENUBAR}, - {"scrollbar", COLOR_SCROLLBAR}, - {"window", COLOR_WINDOW}, - {"window-frame", COLOR_WINDOWFRAME}, - {"window-text", COLOR_WINDOWTEXT}, - }); + static constexpr auto Lookup = base::MakeFixedFlatMap<std::string_view, int>({ + {"3d-dark-shadow", COLOR_3DDKSHADOW}, + {"3d-face", COLOR_3DFACE}, + {"3d-highlight", COLOR_3DHIGHLIGHT}, + {"3d-light", COLOR_3DLIGHT}, + {"3d-shadow", COLOR_3DSHADOW}, + {"active-border", COLOR_ACTIVEBORDER}, + {"active-caption", COLOR_ACTIVECAPTION}, + {"active-caption-gradient", COLOR_GRADIENTACTIVECAPTION}, + {"app-workspace", COLOR_APPWORKSPACE}, + {"button-text", COLOR_BTNTEXT}, + {"caption-text", COLOR_CAPTIONTEXT}, + {"desktop", COLOR_DESKTOP}, + {"disabled-text", COLOR_GRAYTEXT}, + {"highlight", COLOR_HIGHLIGHT}, + {"highlight-text", COLOR_HIGHLIGHTTEXT}, + {"hotlight", COLOR_HOTLIGHT}, + {"inactive-border", COLOR_INACTIVEBORDER}, + {"inactive-caption", COLOR_INACTIVECAPTION}, + {"inactive-caption-gradient", COLOR_GRADIENTINACTIVECAPTION}, + {"inactive-caption-text", COLOR_INACTIVECAPTIONTEXT}, + {"info-background", COLOR_INFOBK}, + {"info-text", COLOR_INFOTEXT}, + {"menu", COLOR_MENU}, + {"menu-highlight", COLOR_MENUHILIGHT}, + {"menu-text", COLOR_MENUTEXT}, + {"menubar", COLOR_MENUBAR}, + {"scrollbar", COLOR_SCROLLBAR}, + {"window", COLOR_WINDOW}, + {"window-frame", COLOR_WINDOWFRAME}, + {"window-text", COLOR_WINDOWTEXT}, + }); if (const auto* iter = Lookup.find(color); iter != Lookup.end()) return ToRGBAHex(color_utils::GetSysSkColor(iter->second)); diff --git a/shell/browser/api/electron_api_tray.cc b/shell/browser/api/electron_api_tray.cc index 5ecb4b851a..eaadc4b51a 100644 --- a/shell/browser/api/electron_api_tray.cc +++ b/shell/browser/api/electron_api_tray.cc @@ -5,6 +5,7 @@ #include "shell/browser/api/electron_api_tray.h" #include <string> +#include <string_view> #include "base/containers/fixed_flat_map.h" #include "gin/dictionary.h" @@ -32,7 +33,7 @@ struct Converter<electron::TrayIcon::IconType> { electron::TrayIcon::IconType* out) { using Val = electron::TrayIcon::IconType; static constexpr auto Lookup = - base::MakeFixedFlatMap<base::StringPiece, Val>({ + base::MakeFixedFlatMap<std::string_view, Val>({ {"custom", Val::kCustom}, {"error", Val::kError}, {"info", Val::kInfo}, diff --git a/shell/browser/api/electron_api_web_contents.cc b/shell/browser/api/electron_api_web_contents.cc index 893f51e7ba..9f8e304f0d 100644 --- a/shell/browser/api/electron_api_web_contents.cc +++ b/shell/browser/api/electron_api_web_contents.cc @@ -9,6 +9,7 @@ #include <optional> #include <set> #include <string> +#include <string_view> #include <utility> #include <vector> @@ -205,7 +206,7 @@ struct Converter<printing::mojom::MarginType> { printing::mojom::MarginType* out) { using Val = printing::mojom::MarginType; static constexpr auto Lookup = - base::MakeFixedFlatMap<base::StringPiece, Val>({ + base::MakeFixedFlatMap<std::string_view, Val>({ {"custom", Val::kCustomMargins}, {"default", Val::kDefaultMargins}, {"none", Val::kNoMargins}, @@ -222,7 +223,7 @@ struct Converter<printing::mojom::DuplexMode> { printing::mojom::DuplexMode* out) { using Val = printing::mojom::DuplexMode; static constexpr auto Lookup = - base::MakeFixedFlatMap<base::StringPiece, Val>({ + base::MakeFixedFlatMap<std::string_view, Val>({ {"longEdge", Val::kLongEdge}, {"shortEdge", Val::kShortEdge}, {"simplex", Val::kSimplex}, @@ -284,7 +285,7 @@ struct Converter<content::SavePageType> { content::SavePageType* out) { using Val = content::SavePageType; static constexpr auto Lookup = - base::MakeFixedFlatMap<base::StringPiece, Val>({ + base::MakeFixedFlatMap<std::string_view, Val>({ {"htmlcomplete", Val::SAVE_PAGE_TYPE_AS_COMPLETE_HTML}, {"htmlonly", Val::SAVE_PAGE_TYPE_AS_ONLY_HTML}, {"mhtml", Val::SAVE_PAGE_TYPE_AS_MHTML}, @@ -329,7 +330,7 @@ struct Converter<electron::api::WebContents::Type> { electron::api::WebContents::Type* out) { using Val = electron::api::WebContents::Type; static constexpr auto Lookup = - base::MakeFixedFlatMap<base::StringPiece, Val>({ + base::MakeFixedFlatMap<std::string_view, Val>({ {"backgroundPage", Val::kBackgroundPage}, {"browserView", Val::kBrowserView}, {"offscreen", Val::kOffScreen}, @@ -357,7 +358,7 @@ namespace electron::api { namespace { -constexpr base::StringPiece CursorTypeToString( +constexpr std::string_view CursorTypeToString( ui::mojom::CursorType cursor_type) { switch (cursor_type) { case ui::mojom::CursorType::kPointer: diff --git a/shell/browser/api/electron_api_web_contents.h b/shell/browser/api/electron_api_web_contents.h index 27f6d27640..b867dd6bdb 100644 --- a/shell/browser/api/electron_api_web_contents.h +++ b/shell/browser/api/electron_api_web_contents.h @@ -9,6 +9,7 @@ #include <memory> #include <optional> #include <string> +#include <string_view> #include <utility> #include <vector> @@ -371,7 +372,7 @@ class WebContents : public ExclusiveAccessContext, // this.emit(name, new Event(sender, message), args...); template <typename... Args> - bool EmitWithSender(base::StringPiece name, + bool EmitWithSender(const std::string_view name, content::RenderFrameHost* frame, electron::mojom::ElectronApiIPC::InvokeCallback callback, Args&&... args) { diff --git a/shell/browser/api/electron_api_web_request.cc b/shell/browser/api/electron_api_web_request.cc index 5acac865c3..3a592b5447 100644 --- a/shell/browser/api/electron_api_web_request.cc +++ b/shell/browser/api/electron_api_web_request.cc @@ -6,6 +6,7 @@ #include <memory> #include <string> +#include <string_view> #include <utility> #include "base/containers/contains.h" @@ -33,7 +34,7 @@ #include "shell/common/gin_helper/dictionary.h" static constexpr auto ResourceTypes = - base::MakeFixedFlatMap<base::StringPiece, + base::MakeFixedFlatMap<std::string_view, extensions::WebRequestResourceType>({ {"cspReport", extensions::WebRequestResourceType::CSP_REPORT}, {"font", extensions::WebRequestResourceType::FONT}, @@ -77,7 +78,7 @@ struct UserData : public base::SupportsUserData::Data { raw_ptr<WebRequest> data; }; -extensions::WebRequestResourceType ParseResourceType(base::StringPiece value) { +extensions::WebRequestResourceType ParseResourceType(std::string_view value) { if (const auto* iter = ResourceTypes.find(value); iter != ResourceTypes.end()) return iter->second; diff --git a/shell/browser/electron_browser_main_parts_linux.cc b/shell/browser/electron_browser_main_parts_linux.cc index 543887ffb1..dd44fe7f97 100644 --- a/shell/browser/electron_browser_main_parts_linux.cc +++ b/shell/browser/electron_browser_main_parts_linux.cc @@ -4,6 +4,8 @@ #include "shell/browser/electron_browser_main_parts.h" +#include <string_view> + #include "base/command_line.h" #include "base/environment.h" #include "ui/base/ozone_buildflags.h" @@ -16,8 +18,8 @@ #include "shell/common/thread_restrictions.h" #endif -constexpr base::StringPiece kElectronOzonePlatformHint( - "ELECTRON_OZONE_PLATFORM_HINT"); +constexpr std::string_view kElectronOzonePlatformHint{ + "ELECTRON_OZONE_PLATFORM_HINT"}; #if BUILDFLAG(IS_OZONE_WAYLAND) diff --git a/shell/browser/event_emitter_mixin.h b/shell/browser/event_emitter_mixin.h index 3719d3bed1..36a066ffed 100644 --- a/shell/browser/event_emitter_mixin.h +++ b/shell/browser/event_emitter_mixin.h @@ -5,6 +5,7 @@ #ifndef ELECTRON_SHELL_BROWSER_EVENT_EMITTER_MIXIN_H_ #define ELECTRON_SHELL_BROWSER_EVENT_EMITTER_MIXIN_H_ +#include <string_view> #include <utility> #include "gin/handle.h" @@ -25,7 +26,7 @@ class EventEmitterMixin { // this.emit(name, new Event(), args...); // Returns true if event.preventDefault() was called during processing. template <typename... Args> - bool Emit(base::StringPiece name, Args&&... args) { + bool Emit(const std::string_view name, Args&&... args) { v8::Isolate* isolate = electron::JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); v8::Local<v8::Object> wrapper; @@ -39,7 +40,7 @@ class EventEmitterMixin { // this.emit(name, args...); template <typename... Args> - void EmitWithoutEvent(base::StringPiece name, Args&&... args) { + void EmitWithoutEvent(const std::string_view name, Args&&... args) { v8::Isolate* isolate = electron::JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); v8::Local<v8::Object> wrapper; diff --git a/shell/browser/extensions/electron_extension_system.cc b/shell/browser/extensions/electron_extension_system.cc index 80d1bc0dfa..e74d55646f 100644 --- a/shell/browser/extensions/electron_extension_system.cc +++ b/shell/browser/extensions/electron_extension_system.cc @@ -6,6 +6,7 @@ #include <memory> #include <string> +#include <string_view> #include <utility> #include "base/files/file_path.h" @@ -93,7 +94,7 @@ void ElectronExtensionSystem::InitForRegularProfile(bool extensions_enabled) { } std::unique_ptr<base::Value::Dict> ParseManifest( - base::StringPiece manifest_contents) { + const std::string_view manifest_contents) { JSONStringValueDeserializer deserializer(manifest_contents); std::unique_ptr<base::Value> manifest = deserializer.Deserialize(nullptr, nullptr); diff --git a/shell/browser/hid/hid_chooser_context.cc b/shell/browser/hid/hid_chooser_context.cc index dad076e8e7..def10f400e 100644 --- a/shell/browser/hid/hid_chooser_context.cc +++ b/shell/browser/hid/hid_chooser_context.cc @@ -6,6 +6,10 @@ #include <utility> +#if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) +#include <string_view> +#endif // BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) + #include "base/command_line.h" #include "base/containers/contains.h" #include "base/strings/string_number_conversions.h" @@ -33,7 +37,6 @@ #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #include "base/containers/fixed_flat_set.h" -#include "base/strings/string_piece.h" #include "extensions/common/constants.h" #endif // BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) @@ -189,7 +192,7 @@ bool HidChooserContext::HasDevicePermission( bool HidChooserContext::IsFidoAllowedForOrigin(const url::Origin& origin) { #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) static constexpr auto kPrivilegedExtensionIds = - base::MakeFixedFlatSet<base::StringPiece>({ + base::MakeFixedFlatSet<std::string_view>({ "ckcendljdlmgnhghiaomidhiiclmapok", // gnubbyd-v3 dev "lfboplenmmjcmpbkeemecobbadnmpfhi", // gnubbyd-v3 prod }); diff --git a/shell/browser/net/electron_url_loader_factory.cc b/shell/browser/net/electron_url_loader_factory.cc index e07730ccde..9c74ad01af 100644 --- a/shell/browser/net/electron_url_loader_factory.cc +++ b/shell/browser/net/electron_url_loader_factory.cc @@ -7,6 +7,7 @@ #include <list> #include <memory> #include <string> +#include <string_view> #include <utility> #include "base/containers/fixed_flat_map.h" @@ -48,7 +49,7 @@ struct Converter<electron::ProtocolType> { electron::ProtocolType* out) { using Val = electron::ProtocolType; static constexpr auto Lookup = - base::MakeFixedFlatMap<base::StringPiece, Val>({ + base::MakeFixedFlatMap<std::string_view, Val>({ // note "free" is internal type, not allowed to be passed from user {"buffer", Val::kBuffer}, {"file", Val::kFile}, diff --git a/shell/browser/net/node_stream_loader.cc b/shell/browser/net/node_stream_loader.cc index d11e5eccba..ca7c6f9820 100644 --- a/shell/browser/net/node_stream_loader.cc +++ b/shell/browser/net/node_stream_loader.cc @@ -4,6 +4,7 @@ #include "shell/browser/net/node_stream_loader.h" +#include <string_view> #include <utility> #include "mojo/public/cpp/system/string_data_source.h" @@ -135,8 +136,8 @@ void NodeStreamLoader::ReadMore() { is_reading_ = false; is_writing_ = true; producer_->Write(std::make_unique<mojo::StringDataSource>( - base::StringPiece(node::Buffer::Data(buffer), - node::Buffer::Length(buffer)), + std::string_view{node::Buffer::Data(buffer), + node::Buffer::Length(buffer)}, mojo::StringDataSource::AsyncWritingMode:: STRING_STAYS_VALID_UNTIL_COMPLETION), base::BindOnce(&NodeStreamLoader::DidWrite, weak)); diff --git a/shell/browser/ui/file_dialog_mac.mm b/shell/browser/ui/file_dialog_mac.mm index c8d62c881d..e769a11be0 100644 --- a/shell/browser/ui/file_dialog_mac.mm +++ b/shell/browser/ui/file_dialog_mac.mm @@ -5,6 +5,7 @@ #include "shell/browser/ui/file_dialog.h" #include <string> +#include <string_view> #include <utility> #include <vector> @@ -441,7 +442,7 @@ void SaveDialogCompletion(int chosen, dict.Set("canceled", true); dict.Set("filePath", base::FilePath()); #if IS_MAS_BUILD() - dict.Set("bookmark", base::StringPiece()); + dict.Set("bookmark", std::string_view{}); #endif } else { std::string path = base::SysNSStringToUTF8([[dialog URL] path]); diff --git a/shell/browser/ui/inspectable_web_contents.cc b/shell/browser/ui/inspectable_web_contents.cc index c05601ce9d..50ea5917b5 100644 --- a/shell/browser/ui/inspectable_web_contents.cc +++ b/shell/browser/ui/inspectable_web_contents.cc @@ -6,6 +6,7 @@ #include "shell/browser/ui/inspectable_web_contents.h" #include <memory> +#include <string_view> #include <utility> #include "base/base64.h" @@ -959,8 +960,8 @@ void InspectableWebContents::DispatchProtocolMessage( if (!frontend_loaded_) return; - base::StringPiece str_message(reinterpret_cast<const char*>(message.data()), - message.size()); + const std::string_view str_message{ + reinterpret_cast<const char*>(message.data()), message.size()}; if (str_message.length() < kMaxMessageChunkSize) { CallClientFunction("DevToolsAPI", "dispatchMessage", base::Value(std::string(str_message))); diff --git a/shell/browser/usb/electron_usb_delegate.cc b/shell/browser/usb/electron_usb_delegate.cc index 31f834fa7f..d778a22691 100644 --- a/shell/browser/usb/electron_usb_delegate.cc +++ b/shell/browser/usb/electron_usb_delegate.cc @@ -4,6 +4,7 @@ #include "shell/browser/usb/electron_usb_delegate.h" +#include <string_view> #include <utility> #include "base/containers/contains.h" @@ -45,7 +46,7 @@ electron::UsbChooserContext* GetChooserContext( // 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>({ + base::MakeFixedFlatSet<std::string_view>({ // Smart Card Connector Extension and its Beta version, see // crbug.com/1233881. "khpfeaanjngmcnplbdlpegiifgpfgdco", diff --git a/shell/browser/web_contents_permission_helper.cc b/shell/browser/web_contents_permission_helper.cc index 43506d3513..df931403d3 100644 --- a/shell/browser/web_contents_permission_helper.cc +++ b/shell/browser/web_contents_permission_helper.cc @@ -4,6 +4,7 @@ #include "shell/browser/web_contents_permission_helper.h" +#include <string_view> #include <utility> #include "content/public/browser/browser_context.h" @@ -17,7 +18,7 @@ namespace { -constexpr base::StringPiece MediaStreamTypeToString( +constexpr std::string_view MediaStreamTypeToString( blink::mojom::MediaStreamType type) { switch (type) { case blink::mojom::MediaStreamType::DEVICE_AUDIO_CAPTURE: diff --git a/shell/browser/web_contents_preferences.cc b/shell/browser/web_contents_preferences.cc index 4a7ab22770..ee305da3c4 100644 --- a/shell/browser/web_contents_preferences.cc +++ b/shell/browser/web_contents_preferences.cc @@ -6,6 +6,7 @@ #include <algorithm> #include <string> +#include <string_view> #include <utility> #include <vector> @@ -46,7 +47,7 @@ struct Converter<blink::mojom::AutoplayPolicy> { blink::mojom::AutoplayPolicy* out) { using Val = blink::mojom::AutoplayPolicy; static constexpr auto Lookup = - base::MakeFixedFlatMap<base::StringPiece, Val>({ + base::MakeFixedFlatMap<std::string_view, Val>({ {"document-user-activation-required", Val::kDocumentUserActivationRequired}, {"no-user-gesture-required", Val::kNoUserGestureRequired}, @@ -63,7 +64,7 @@ struct Converter<blink::mojom::V8CacheOptions> { blink::mojom::V8CacheOptions* out) { using Val = blink::mojom::V8CacheOptions; static constexpr auto Lookup = - base::MakeFixedFlatMap<base::StringPiece, Val>({ + base::MakeFixedFlatMap<std::string_view, Val>({ {"bypassHeatCheck", Val::kCodeWithoutHeatCheck}, {"bypassHeatCheckAndEagerCompile", Val::kFullCodeWithoutHeatCheck}, {"code", Val::kCode}, diff --git a/shell/common/api/electron_api_url_loader.cc b/shell/common/api/electron_api_url_loader.cc index 975c571cd3..d8635393a1 100644 --- a/shell/common/api/electron_api_url_loader.cc +++ b/shell/common/api/electron_api_url_loader.cc @@ -7,6 +7,7 @@ #include <algorithm> #include <memory> #include <string> +#include <string_view> #include <utility> #include <vector> @@ -68,7 +69,7 @@ struct Converter<network::mojom::CredentialsMode> { network::mojom::CredentialsMode* out) { using Val = network::mojom::CredentialsMode; static constexpr auto Lookup = - base::MakeFixedFlatMap<base::StringPiece, Val>({ + base::MakeFixedFlatMap<std::string_view, Val>({ {"include", Val::kInclude}, {"omit", Val::kOmit}, // Note: This only makes sense if the request @@ -86,7 +87,7 @@ struct Converter<blink::mojom::FetchCacheMode> { blink::mojom::FetchCacheMode* out) { using Val = blink::mojom::FetchCacheMode; static constexpr auto Lookup = - base::MakeFixedFlatMap<base::StringPiece, Val>({ + base::MakeFixedFlatMap<std::string_view, Val>({ {"default", Val::kDefault}, {"force-cache", Val::kForceCache}, {"no-cache", Val::kValidateCache}, @@ -106,7 +107,7 @@ struct Converter<net::ReferrerPolicy> { using Val = net::ReferrerPolicy; // clang-format off static constexpr auto Lookup = - base::MakeFixedFlatMap<base::StringPiece, Val>({ + base::MakeFixedFlatMap<std::string_view, Val>({ {"", Val::REDUCE_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN}, {"no-referrer", Val::NO_REFERRER}, {"no-referrer-when-downgrade", Val::CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE}, @@ -546,7 +547,7 @@ gin::Handle<SimpleURLLoaderWrapper> SimpleURLLoaderWrapper::Create( if (std::string mode; opts.Get("mode", &mode)) { using Val = network::mojom::RequestMode; static constexpr auto Lookup = - base::MakeFixedFlatMap<base::StringPiece, Val>({ + base::MakeFixedFlatMap<std::string_view, Val>({ {"cors", Val::kCors}, {"navigate", Val::kNavigate}, {"no-cors", Val::kNoCors}, @@ -559,7 +560,7 @@ gin::Handle<SimpleURLLoaderWrapper> SimpleURLLoaderWrapper::Create( if (std::string destination; opts.Get("destination", &destination)) { using Val = network::mojom::RequestDestination; static constexpr auto Lookup = - base::MakeFixedFlatMap<base::StringPiece, Val>({ + base::MakeFixedFlatMap<std::string_view, Val>({ {"audio", Val::kAudio}, {"audioworklet", Val::kAudioWorklet}, {"document", Val::kDocument}, @@ -694,7 +695,7 @@ gin::Handle<SimpleURLLoaderWrapper> SimpleURLLoaderWrapper::Create( return ret; } -void SimpleURLLoaderWrapper::OnDataReceived(base::StringPiece string_piece, +void SimpleURLLoaderWrapper::OnDataReceived(std::string_view string_piece, base::OnceClosure resume) { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); diff --git a/shell/common/asar/archive.cc b/shell/common/asar/archive.cc index 578dd3b6a1..35a2c1c54d 100644 --- a/shell/common/asar/archive.cc +++ b/shell/common/asar/archive.cc @@ -5,6 +5,7 @@ #include "shell/common/asar/archive.h" #include <string> +#include <string_view> #include <utility> #include <vector> @@ -105,7 +106,7 @@ bool FillFileInfoWithNode(Archive::FileInfo* info, const std::string* offset = node->FindString("offset"); if (offset && - base::StringToUint64(base::StringPiece(*offset), &info->offset)) { + base::StringToUint64(std::string_view{*offset}, &info->offset)) { info->offset += header_size; } else { return false; diff --git a/shell/common/gin_converters/blink_converter.cc b/shell/common/gin_converters/blink_converter.cc index ae886e7d0a..e980f39f81 100644 --- a/shell/common/gin_converters/blink_converter.cc +++ b/shell/common/gin_converters/blink_converter.cc @@ -6,6 +6,7 @@ #include <algorithm> #include <string> +#include <string_view> #include <vector> #include "base/containers/fixed_flat_map.h" @@ -135,7 +136,7 @@ struct Converter<blink::WebMouseEvent::Button> { blink::WebMouseEvent::Button* out) { using Val = blink::WebMouseEvent::Button; static constexpr auto Lookup = - base::MakeFixedFlatMap<base::StringPiece, Val>({ + base::MakeFixedFlatMap<std::string_view, Val>({ {"left", Val::kLeft}, {"middle", Val::kMiddle}, {"right", Val::kRight}, @@ -148,7 +149,7 @@ struct Converter<blink::WebMouseEvent::Button> { // these are the modifier names we both accept and return static constexpr auto Modifiers = - base::MakeFixedFlatMap<base::StringPiece, blink::WebInputEvent::Modifiers>({ + base::MakeFixedFlatMap<std::string_view, blink::WebInputEvent::Modifiers>({ {"alt", blink::WebInputEvent::Modifiers::kAltKey}, {"capslock", blink::WebInputEvent::Modifiers::kCapsLockOn}, {"control", blink::WebInputEvent::Modifiers::kControlKey}, @@ -167,14 +168,14 @@ static constexpr auto Modifiers = // these are the modifier names we accept but do not return static constexpr auto ModifierAliases = - base::MakeFixedFlatMap<base::StringPiece, blink::WebInputEvent::Modifiers>({ + base::MakeFixedFlatMap<std::string_view, blink::WebInputEvent::Modifiers>({ {"cmd", blink::WebInputEvent::Modifiers::kMetaKey}, {"command", blink::WebInputEvent::Modifiers::kMetaKey}, {"ctrl", blink::WebInputEvent::Modifiers::kControlKey}, }); static constexpr auto ReferrerPolicies = - base::MakeFixedFlatMap<base::StringPiece, network::mojom::ReferrerPolicy>({ + base::MakeFixedFlatMap<std::string_view, network::mojom::ReferrerPolicy>({ {"default", network::mojom::ReferrerPolicy::kDefault}, {"no-referrer", network::mojom::ReferrerPolicy::kNever}, {"no-referrer-when-downgrade", network::mojom::ReferrerPolicy::kNoReferrerWhenDowngrade}, @@ -197,8 +198,8 @@ struct Converter<blink::WebInputEvent::Modifiers> { } }; -std::vector<base::StringPiece> ModifiersToArray(int modifiers) { - std::vector<base::StringPiece> modifier_strings; +std::vector<std::string_view> ModifiersToArray(int modifiers) { + std::vector<std::string_view> modifier_strings; for (const auto& [name, mask] : Modifiers) if (mask & modifiers) @@ -463,7 +464,7 @@ v8::Local<v8::Value> Converter<std::optional<blink::mojom::FormControlType>>::ToV8( v8::Isolate* isolate, const std::optional<blink::mojom::FormControlType>& in) { - base::StringPiece str{"none"}; + std::string_view str{"none"}; if (in.has_value()) { switch (*in) { case blink::mojom::FormControlType::kButtonButton: diff --git a/shell/common/gin_converters/content_converter.cc b/shell/common/gin_converters/content_converter.cc index 8b016584e5..206c91e40a 100644 --- a/shell/common/gin_converters/content_converter.cc +++ b/shell/common/gin_converters/content_converter.cc @@ -5,6 +5,7 @@ #include "shell/common/gin_converters/content_converter.h" #include <string> +#include <string_view> #include "base/containers/fixed_flat_map.h" #include "content/public/browser/context_menu_params.h" @@ -24,7 +25,7 @@ namespace { -[[nodiscard]] constexpr base::StringPiece FormControlToInputFieldTypeString( +[[nodiscard]] constexpr std::string_view FormControlToInputFieldTypeString( const std::optional<blink::mojom::FormControlType> form_control_type) { if (!form_control_type) return "none"; @@ -70,7 +71,7 @@ namespace { namespace gin { static constexpr auto MenuSourceTypes = - base::MakeFixedFlatMap<base::StringPiece, ui::MenuSourceType>({ + base::MakeFixedFlatMap<std::string_view, ui::MenuSourceType>({ {"adjustSelection", ui::MENU_SOURCE_ADJUST_SELECTION}, {"adjustSelectionReset", ui::MENU_SOURCE_ADJUST_SELECTION_RESET}, {"keyboard", ui::MENU_SOURCE_KEYBOARD}, @@ -285,12 +286,11 @@ bool Converter<content::StopFindAction>::FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, content::StopFindAction* out) { using Val = content::StopFindAction; - static constexpr auto Lookup = - base::MakeFixedFlatMap<base::StringPiece, Val>({ - {"activateSelection", Val::STOP_FIND_ACTION_ACTIVATE_SELECTION}, - {"clearSelection", Val::STOP_FIND_ACTION_CLEAR_SELECTION}, - {"keepSelection", Val::STOP_FIND_ACTION_KEEP_SELECTION}, - }); + static constexpr auto Lookup = base::MakeFixedFlatMap<std::string_view, Val>({ + {"activateSelection", Val::STOP_FIND_ACTION_ACTIVATE_SELECTION}, + {"clearSelection", Val::STOP_FIND_ACTION_CLEAR_SELECTION}, + {"keepSelection", Val::STOP_FIND_ACTION_KEEP_SELECTION}, + }); return FromV8WithLookup(isolate, val, Lookup, out); } diff --git a/shell/common/gin_converters/net_converter.cc b/shell/common/gin_converters/net_converter.cc index 888bc8ba0a..ec89a403e5 100644 --- a/shell/common/gin_converters/net_converter.cc +++ b/shell/common/gin_converters/net_converter.cc @@ -5,6 +5,7 @@ #include "shell/common/gin_converters/net_converter.h" #include <string> +#include <string_view> #include <utility> #include <vector> @@ -691,7 +692,7 @@ bool Converter<net::DnsQueryType>::FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, net::DnsQueryType* out) { static constexpr auto Lookup = - base::MakeFixedFlatMap<base::StringPiece, net::DnsQueryType>({ + base::MakeFixedFlatMap<std::string_view, net::DnsQueryType>({ {"A", net::DnsQueryType::A}, {"AAAA", net::DnsQueryType::AAAA}, }); @@ -703,14 +704,13 @@ bool Converter<net::HostResolverSource>::FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, net::HostResolverSource* out) { using Val = net::HostResolverSource; - static constexpr auto Lookup = - base::MakeFixedFlatMap<base::StringPiece, Val>({ - {"any", Val::ANY}, - {"dns", Val::DNS}, - {"localOnly", Val::LOCAL_ONLY}, - {"mdns", Val::MULTICAST_DNS}, - {"system", Val::SYSTEM}, - }); + static constexpr auto Lookup = base::MakeFixedFlatMap<std::string_view, Val>({ + {"any", Val::ANY}, + {"dns", Val::DNS}, + {"localOnly", Val::LOCAL_ONLY}, + {"mdns", Val::MULTICAST_DNS}, + {"system", Val::SYSTEM}, + }); return FromV8WithLookup(isolate, val, Lookup, out); } @@ -720,12 +720,11 @@ bool Converter<network::mojom::ResolveHostParameters::CacheUsage>::FromV8( v8::Local<v8::Value> val, network::mojom::ResolveHostParameters::CacheUsage* out) { using Val = network::mojom::ResolveHostParameters::CacheUsage; - static constexpr auto Lookup = - base::MakeFixedFlatMap<base::StringPiece, Val>({ - {"allowed", Val::ALLOWED}, - {"disallowed", Val::DISALLOWED}, - {"staleAllowed", Val::STALE_ALLOWED}, - }); + static constexpr auto Lookup = base::MakeFixedFlatMap<std::string_view, Val>({ + {"allowed", Val::ALLOWED}, + {"disallowed", Val::DISALLOWED}, + {"staleAllowed", Val::STALE_ALLOWED}, + }); return FromV8WithLookup(isolate, val, Lookup, out); } @@ -735,11 +734,10 @@ bool Converter<network::mojom::SecureDnsPolicy>::FromV8( v8::Local<v8::Value> val, network::mojom::SecureDnsPolicy* out) { using Val = network::mojom::SecureDnsPolicy; - static constexpr auto Lookup = - base::MakeFixedFlatMap<base::StringPiece, Val>({ - {"allow", Val::ALLOW}, - {"disable", Val::DISABLE}, - }); + static constexpr auto Lookup = base::MakeFixedFlatMap<std::string_view, Val>({ + {"allow", Val::ALLOW}, + {"disable", Val::DISABLE}, + }); return FromV8WithLookup(isolate, val, Lookup, out); } diff --git a/shell/common/gin_helper/arguments.cc b/shell/common/gin_helper/arguments.cc index 4e82443ca8..272aa7f01e 100644 --- a/shell/common/gin_helper/arguments.cc +++ b/shell/common/gin_helper/arguments.cc @@ -2,6 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE.chromium file. +#include <string_view> + #include "shell/common/gin_helper/arguments.h" #include "v8/include/v8-exception.h" @@ -15,7 +17,7 @@ void Arguments::ThrowError() const { gin::Arguments::ThrowError(); } -void Arguments::ThrowError(base::StringPiece message) const { +void Arguments::ThrowError(const std::string_view message) const { isolate()->ThrowException( v8::Exception::Error(gin::StringToV8(isolate(), message))); } diff --git a/shell/common/gin_helper/arguments.h b/shell/common/gin_helper/arguments.h index 81a37f8476..eb79200972 100644 --- a/shell/common/gin_helper/arguments.h +++ b/shell/common/gin_helper/arguments.h @@ -5,6 +5,8 @@ #ifndef ELECTRON_SHELL_COMMON_GIN_HELPER_ARGUMENTS_H_ #define ELECTRON_SHELL_COMMON_GIN_HELPER_ARGUMENTS_H_ +#include <string_view> + #include "gin/arguments.h" namespace gin_helper { @@ -40,7 +42,7 @@ class Arguments : public gin::Arguments { // Throw error with custom error message. void ThrowError() const; - void ThrowError(base::StringPiece message) const; + void ThrowError(std::string_view message) const; private: // MUST NOT ADD ANY DATA MEMBER. diff --git a/shell/common/gin_helper/dictionary.h b/shell/common/gin_helper/dictionary.h index b490e5d6d0..efe36fb099 100644 --- a/shell/common/gin_helper/dictionary.h +++ b/shell/common/gin_helper/dictionary.h @@ -6,6 +6,7 @@ #define ELECTRON_SHELL_COMMON_GIN_HELPER_DICTIONARY_H_ #include <optional> +#include <string_view> #include <type_traits> #include <utility> @@ -68,7 +69,7 @@ class Dictionary : public gin::Dictionary { // Like normal Get but put result in an std::optional. template <typename T> - bool GetOptional(base::StringPiece key, std::optional<T>* out) const { + bool GetOptional(const std::string_view key, std::optional<T>* out) const { T ret; if (Get(key, &ret)) { out->emplace(std::move(ret)); @@ -79,7 +80,7 @@ class Dictionary : public gin::Dictionary { } template <typename T> - bool GetHidden(base::StringPiece key, T* out) const { + bool GetHidden(std::string_view key, T* out) const { v8::Local<v8::Context> context = isolate()->GetCurrentContext(); v8::Local<v8::Private> privateKey = v8::Private::ForApi(isolate(), gin::StringToV8(isolate(), key)); @@ -92,7 +93,7 @@ class Dictionary : public gin::Dictionary { } template <typename T> - bool SetHidden(base::StringPiece key, T val) { + bool SetHidden(std::string_view key, T val) { v8::Local<v8::Value> v8_value; if (!gin::TryConvertToV8(isolate(), val, &v8_value)) return false; @@ -105,7 +106,7 @@ class Dictionary : public gin::Dictionary { } template <typename T> - bool SetMethod(base::StringPiece key, const T& callback) { + bool SetMethod(std::string_view key, const T& callback) { auto context = isolate()->GetCurrentContext(); auto templ = CallbackTraits<T>::CreateTemplate(isolate(), callback); return GetHandle() @@ -147,7 +148,7 @@ class Dictionary : public gin::Dictionary { } template <typename T> - bool SetReadOnly(base::StringPiece key, const T& val) { + bool SetReadOnly(std::string_view key, const T& val) { v8::Local<v8::Value> v8_value; if (!gin::TryConvertToV8(isolate(), val, &v8_value)) return false; @@ -160,7 +161,7 @@ class Dictionary : public gin::Dictionary { // Note: If we plan to add more Set methods, consider adding an option instead // of copying code. template <typename T> - bool SetReadOnlyNonConfigurable(base::StringPiece key, T val) { + bool SetReadOnlyNonConfigurable(std::string_view key, T val) { v8::Local<v8::Value> v8_value; if (!gin::TryConvertToV8(isolate(), val, &v8_value)) return false; @@ -171,13 +172,13 @@ class Dictionary : public gin::Dictionary { return !result.IsNothing() && result.FromJust(); } - bool Has(base::StringPiece key) const { + bool Has(std::string_view key) const { v8::Maybe<bool> result = GetHandle()->Has(isolate()->GetCurrentContext(), gin::StringToV8(isolate(), key)); return !result.IsNothing() && result.FromJust(); } - bool Delete(base::StringPiece key) { + bool Delete(std::string_view key) { v8::Maybe<bool> result = GetHandle()->Delete( isolate()->GetCurrentContext(), gin::StringToV8(isolate(), key)); return !result.IsNothing() && result.FromJust(); diff --git a/shell/common/gin_helper/error_thrower.cc b/shell/common/gin_helper/error_thrower.cc index 8e02e573af..0dbfce5cdf 100644 --- a/shell/common/gin_helper/error_thrower.cc +++ b/shell/common/gin_helper/error_thrower.cc @@ -2,6 +2,8 @@ // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. +#include <string_view> + #include "shell/common/gin_helper/error_thrower.h" #include "gin/converter.h" @@ -15,27 +17,28 @@ ErrorThrower::ErrorThrower(v8::Isolate* isolate) : isolate_(isolate) {} // costly to invoke ErrorThrower::ErrorThrower() : isolate_(v8::Isolate::GetCurrent()) {} -void ErrorThrower::ThrowError(base::StringPiece err_msg) const { +void ErrorThrower::ThrowError(const std::string_view err_msg) const { Throw(v8::Exception::Error, err_msg); } -void ErrorThrower::ThrowTypeError(base::StringPiece err_msg) const { +void ErrorThrower::ThrowTypeError(const std::string_view err_msg) const { Throw(v8::Exception::TypeError, err_msg); } -void ErrorThrower::ThrowRangeError(base::StringPiece err_msg) const { +void ErrorThrower::ThrowRangeError(const std::string_view err_msg) const { Throw(v8::Exception::RangeError, err_msg); } -void ErrorThrower::ThrowReferenceError(base::StringPiece err_msg) const { +void ErrorThrower::ThrowReferenceError(const std::string_view err_msg) const { Throw(v8::Exception::ReferenceError, err_msg); } -void ErrorThrower::ThrowSyntaxError(base::StringPiece err_msg) const { +void ErrorThrower::ThrowSyntaxError(const std::string_view err_msg) const { Throw(v8::Exception::SyntaxError, err_msg); } -void ErrorThrower::Throw(ErrorGenerator gen, base::StringPiece err_msg) const { +void ErrorThrower::Throw(ErrorGenerator gen, + const std::string_view err_msg) const { v8::Local<v8::Value> exception = gen(gin::StringToV8(isolate_, err_msg), {}); if (!isolate_->IsExecutionTerminating()) isolate_->ThrowException(exception); diff --git a/shell/common/gin_helper/error_thrower.h b/shell/common/gin_helper/error_thrower.h index e09072fba7..e5ace0a28f 100644 --- a/shell/common/gin_helper/error_thrower.h +++ b/shell/common/gin_helper/error_thrower.h @@ -5,8 +5,9 @@ #ifndef ELECTRON_SHELL_COMMON_GIN_HELPER_ERROR_THROWER_H_ #define ELECTRON_SHELL_COMMON_GIN_HELPER_ERROR_THROWER_H_ +#include <string_view> + #include "base/memory/raw_ptr.h" -#include "base/strings/string_piece.h" #include "v8/include/v8.h" namespace gin_helper { @@ -17,18 +18,18 @@ class ErrorThrower { ErrorThrower(); ~ErrorThrower() = default; - void ThrowError(base::StringPiece err_msg) const; - void ThrowTypeError(base::StringPiece err_msg) const; - void ThrowRangeError(base::StringPiece err_msg) const; - void ThrowReferenceError(base::StringPiece err_msg) const; - void ThrowSyntaxError(base::StringPiece err_msg) const; + void ThrowError(std::string_view err_msg) const; + void ThrowTypeError(std::string_view err_msg) const; + void ThrowRangeError(std::string_view err_msg) const; + void ThrowReferenceError(std::string_view err_msg) const; + void ThrowSyntaxError(std::string_view err_msg) const; v8::Isolate* isolate() const { return isolate_; } private: using ErrorGenerator = v8::Local<v8::Value> (*)(v8::Local<v8::String> err_msg, v8::Local<v8::Value> options); - void Throw(ErrorGenerator gen, base::StringPiece err_msg) const; + void Throw(ErrorGenerator gen, std::string_view err_msg) const; raw_ptr<v8::Isolate> isolate_; }; diff --git a/shell/common/gin_helper/event_emitter.h b/shell/common/gin_helper/event_emitter.h index 784dd539a8..cd53bfea36 100644 --- a/shell/common/gin_helper/event_emitter.h +++ b/shell/common/gin_helper/event_emitter.h @@ -5,6 +5,7 @@ #ifndef ELECTRON_SHELL_COMMON_GIN_HELPER_EVENT_EMITTER_H_ #define ELECTRON_SHELL_COMMON_GIN_HELPER_EVENT_EMITTER_H_ +#include <string_view> #include <utility> #include <vector> @@ -38,7 +39,7 @@ class EventEmitter : public gin_helper::Wrappable<T> { // this.emit(name, new Event(), args...); template <typename... Args> - bool Emit(base::StringPiece name, Args&&... args) { + bool Emit(const std::string_view name, Args&&... args) { v8::HandleScope handle_scope(isolate()); v8::Local<v8::Object> wrapper = GetWrapper(); if (wrapper.IsEmpty()) @@ -58,7 +59,7 @@ class EventEmitter : public gin_helper::Wrappable<T> { private: // this.emit(name, event, args...); template <typename... Args> - bool EmitWithEvent(base::StringPiece name, + bool EmitWithEvent(const std::string_view name, gin::Handle<gin_helper::internal::Event> event, Args&&... args) { // It's possible that |this| will be deleted by EmitEvent, so save anything diff --git a/shell/common/gin_helper/object_template_builder.cc b/shell/common/gin_helper/object_template_builder.cc index 832f09057f..e9f0f6c1dd 100644 --- a/shell/common/gin_helper/object_template_builder.cc +++ b/shell/common/gin_helper/object_template_builder.cc @@ -12,14 +12,14 @@ ObjectTemplateBuilder::ObjectTemplateBuilder( : isolate_(isolate), template_(templ) {} ObjectTemplateBuilder& ObjectTemplateBuilder::SetImpl( - const base::StringPiece& name, + const std::string_view name, v8::Local<v8::Data> val) { template_->Set(gin::StringToSymbol(isolate_, name), val); return *this; } ObjectTemplateBuilder& ObjectTemplateBuilder::SetPropertyImpl( - const base::StringPiece& name, + const std::string_view name, v8::Local<v8::FunctionTemplate> getter, v8::Local<v8::FunctionTemplate> setter) { template_->SetAccessorProperty(gin::StringToSymbol(isolate_, name), getter, diff --git a/shell/common/gin_helper/object_template_builder.h b/shell/common/gin_helper/object_template_builder.h index 05526043df..9efef8cc3f 100644 --- a/shell/common/gin_helper/object_template_builder.h +++ b/shell/common/gin_helper/object_template_builder.h @@ -5,6 +5,8 @@ #ifndef ELECTRON_SHELL_COMMON_GIN_HELPER_OBJECT_TEMPLATE_BUILDER_H_ #define ELECTRON_SHELL_COMMON_GIN_HELPER_OBJECT_TEMPLATE_BUILDER_H_ +#include <string_view> + #include "base/memory/raw_ptr.h" #include "shell/common/gin_helper/function_template.h" @@ -28,7 +30,7 @@ class ObjectTemplateBuilder { // poetic license here in order that all calls to Set() can be via the '.' // operator and line up nicely. template <typename T> - ObjectTemplateBuilder& SetValue(const base::StringPiece& name, T val) { + ObjectTemplateBuilder& SetValue(const std::string_view name, T val) { return SetImpl(name, ConvertToV8(isolate_, val)); } @@ -37,19 +39,19 @@ class ObjectTemplateBuilder { // will want to use one of the first two options. Also see // gin::CreateFunctionTemplate() for creating raw function templates. template <typename T> - ObjectTemplateBuilder& SetMethod(const base::StringPiece& name, + ObjectTemplateBuilder& SetMethod(const std::string_view name, const T& callback) { return SetImpl(name, CallbackTraits<T>::CreateTemplate(isolate_, callback)); } template <typename T> - ObjectTemplateBuilder& SetProperty(const base::StringPiece& name, + ObjectTemplateBuilder& SetProperty(const std::string_view name, const T& getter) { return SetPropertyImpl(name, CallbackTraits<T>::CreateTemplate(isolate_, getter), v8::Local<v8::FunctionTemplate>()); } template <typename T, typename U> - ObjectTemplateBuilder& SetProperty(const base::StringPiece& name, + ObjectTemplateBuilder& SetProperty(const std::string_view name, const T& getter, const U& setter) { return SetPropertyImpl(name, @@ -60,10 +62,10 @@ class ObjectTemplateBuilder { v8::Local<v8::ObjectTemplate> Build(); private: - ObjectTemplateBuilder& SetImpl(const base::StringPiece& name, + ObjectTemplateBuilder& SetImpl(const std::string_view name, v8::Local<v8::Data> val); ObjectTemplateBuilder& SetPropertyImpl( - const base::StringPiece& name, + const std::string_view name, v8::Local<v8::FunctionTemplate> getter, v8::Local<v8::FunctionTemplate> setter); diff --git a/shell/common/gin_helper/promise.cc b/shell/common/gin_helper/promise.cc index 7a4720a255..bc659c9c2f 100644 --- a/shell/common/gin_helper/promise.cc +++ b/shell/common/gin_helper/promise.cc @@ -2,6 +2,8 @@ // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. +#include <string_view> + #include "shell/common/gin_helper/promise.h" namespace gin_helper { @@ -43,7 +45,8 @@ v8::Maybe<bool> PromiseBase::Reject(v8::Local<v8::Value> except) { return GetInner()->Reject(GetContext(), except); } -v8::Maybe<bool> PromiseBase::RejectWithErrorMessage(base::StringPiece message) { +v8::Maybe<bool> PromiseBase::RejectWithErrorMessage( + const std::string_view message) { v8::HandleScope handle_scope(isolate()); gin_helper::MicrotasksScope microtasks_scope( isolate(), GetContext()->GetMicrotaskQueue()); diff --git a/shell/common/gin_helper/promise.h b/shell/common/gin_helper/promise.h index 6acf9b49ea..ee1b41b57c 100644 --- a/shell/common/gin_helper/promise.h +++ b/shell/common/gin_helper/promise.h @@ -6,12 +6,12 @@ #define ELECTRON_SHELL_COMMON_GIN_HELPER_PROMISE_H_ #include <string> +#include <string_view> #include <tuple> #include <type_traits> #include <utility> #include "base/memory/raw_ptr.h" -#include "base/strings/string_piece.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "shell/common/gin_converters/std_converter.h" @@ -47,19 +47,20 @@ class PromiseBase { // // Note: The parameter type is PromiseBase&& so it can take the instances of // Promise<T> type. - static void RejectPromise(PromiseBase&& promise, base::StringPiece errmsg) { + static void RejectPromise(PromiseBase&& promise, + const std::string_view errmsg) { if (electron::IsBrowserProcess() && !content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)) { content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce( - // Note that this callback can not take StringPiece, + // Note that this callback can not take std::string_view, // as StringPiece only references string internally and // will blow when a temporary string is passed. [](PromiseBase&& promise, std::string str) { promise.RejectWithErrorMessage(str); }, - std::move(promise), std::string(errmsg.data(), errmsg.size()))); + std::move(promise), std::string{errmsg})); } else { promise.RejectWithErrorMessage(errmsg); } @@ -67,7 +68,7 @@ class PromiseBase { v8::Maybe<bool> Reject(); v8::Maybe<bool> Reject(v8::Local<v8::Value> except); - v8::Maybe<bool> RejectWithErrorMessage(base::StringPiece message); + v8::Maybe<bool> RejectWithErrorMessage(std::string_view message); v8::Local<v8::Context> GetContext() const; v8::Local<v8::Promise> GetHandle() const; diff --git a/shell/common/keyboard_util.cc b/shell/common/keyboard_util.cc index d8d8d553d8..a055ffadf6 100644 --- a/shell/common/keyboard_util.cc +++ b/shell/common/keyboard_util.cc @@ -18,7 +18,7 @@ namespace { using CodeAndShiftedChar = std::pair<ui::KeyboardCode, std::optional<char16_t>>; constexpr CodeAndShiftedChar KeyboardCodeFromKeyIdentifier( - base::StringPiece str) { + const std::string_view str) { #if BUILDFLAG(IS_MAC) constexpr auto CommandOrControl = ui::VKEY_COMMAND; #else @@ -26,7 +26,7 @@ constexpr CodeAndShiftedChar KeyboardCodeFromKeyIdentifier( #endif constexpr auto Lookup = - base::MakeFixedFlatMap<base::StringPiece, CodeAndShiftedChar>({ + base::MakeFixedFlatMap<std::string_view, CodeAndShiftedChar>({ {"alt", {ui::VKEY_MENU, {}}}, {"altgr", {ui::VKEY_ALTGR, {}}}, {"backspace", {ui::VKEY_BACK, {}}}, @@ -272,7 +272,7 @@ constexpr CodeAndShiftedChar KeyboardCodeFromCharCode(char16_t c) { } // namespace -ui::KeyboardCode KeyboardCodeFromStr(base::StringPiece str, +ui::KeyboardCode KeyboardCodeFromStr(const std::string_view str, std::optional<char16_t>* shifted_char) { auto const [code, shifted] = str.size() == 1 ? KeyboardCodeFromCharCode(base::ToLowerASCII(str[0])) diff --git a/shell/common/keyboard_util.h b/shell/common/keyboard_util.h index 45cc80f264..e213e9bc0e 100644 --- a/shell/common/keyboard_util.h +++ b/shell/common/keyboard_util.h @@ -6,8 +6,8 @@ #define ELECTRON_SHELL_COMMON_KEYBOARD_UTIL_H_ #include <optional> +#include <string_view> -#include "base/strings/string_piece.h" #include "ui/events/keycodes/keyboard_codes.h" namespace electron { @@ -15,7 +15,7 @@ namespace electron { // Return key code of the |str|, if the original key is a shifted character, // for example + and /, set it in |shifted_char|. // pressed. -ui::KeyboardCode KeyboardCodeFromStr(base::StringPiece str, +ui::KeyboardCode KeyboardCodeFromStr(std::string_view str, std::optional<char16_t>* shifted_char); } // namespace electron diff --git a/shell/common/logging.cc b/shell/common/logging.cc index 5a109d9798..b9d58e187b 100644 --- a/shell/common/logging.cc +++ b/shell/common/logging.cc @@ -5,6 +5,7 @@ #include "shell/common/logging.h" #include <string> +#include <string_view> #include "base/base_switches.h" #include "base/command_line.h" @@ -19,8 +20,8 @@ namespace logging { -constexpr base::StringPiece kLogFileName("ELECTRON_LOG_FILE"); -constexpr base::StringPiece kElectronEnableLogging("ELECTRON_ENABLE_LOGGING"); +constexpr std::string_view kLogFileName{"ELECTRON_LOG_FILE"}; +constexpr std::string_view kElectronEnableLogging{"ELECTRON_ENABLE_LOGGING"}; base::FilePath GetLogFileName(const base::CommandLine& command_line) { std::string filename = command_line.GetSwitchValueASCII(switches::kLogFile); diff --git a/shell/common/node_bindings.cc b/shell/common/node_bindings.cc index 676c712371..ca02920f84 100644 --- a/shell/common/node_bindings.cc +++ b/shell/common/node_bindings.cc @@ -6,6 +6,7 @@ #include <algorithm> #include <string> +#include <string_view> #include <utility> #include <vector> @@ -293,9 +294,9 @@ void ErrorMessageListener(v8::Local<v8::Message> message, // Only allow a specific subset of options in non-ELECTRON_RUN_AS_NODE mode. // If node CLI inspect support is disabled, allow no debug options. -bool IsAllowedOption(base::StringPiece option) { +bool IsAllowedOption(const std::string_view option) { static constexpr auto debug_options = - base::MakeFixedFlatSet<base::StringPiece>({ + base::MakeFixedFlatSet<std::string_view>({ "--debug", "--debug-brk", "--debug-port", @@ -307,7 +308,7 @@ bool IsAllowedOption(base::StringPiece option) { }); // This should be aligned with what's possible to set via the process object. - static constexpr auto options = base::MakeFixedFlatSet<base::StringPiece>({ + static constexpr auto options = base::MakeFixedFlatSet<std::string_view>({ "--dns-result-order", "--no-deprecation", "--throw-deprecation", @@ -325,7 +326,7 @@ bool IsAllowedOption(base::StringPiece option) { // See https://nodejs.org/api/cli.html#cli_node_options_options void SetNodeOptions(base::Environment* env) { // Options that are unilaterally disallowed - static constexpr auto disallowed = base::MakeFixedFlatSet<base::StringPiece>({ + static constexpr auto disallowed = base::MakeFixedFlatSet<std::string_view>({ "--enable-fips", "--experimental-policy", "--force-fips", @@ -334,7 +335,7 @@ void SetNodeOptions(base::Environment* env) { "--use-openssl-ca", }); - static constexpr auto pkg_opts = base::MakeFixedFlatSet<base::StringPiece>({ + static constexpr auto pkg_opts = base::MakeFixedFlatSet<std::string_view>({ "--http-parser", "--max-http-header-size", }); @@ -475,7 +476,7 @@ std::vector<std::string> NodeBindings::ParseNodeCliFlags() { #else const auto& option = arg; #endif - const auto stripped = base::StringPiece(option).substr(0, option.find('=')); + const auto stripped = std::string_view{option}.substr(0, option.find('=')); // Only allow no-op or a small set of debug/trace related options. if (IsAllowedOption(stripped) || stripped == "--") args.push_back(option); diff --git a/shell/renderer/api/electron_api_web_frame.cc b/shell/renderer/api/electron_api_web_frame.cc index bbd5e8ef11..11a30d6f8d 100644 --- a/shell/renderer/api/electron_api_web_frame.cc +++ b/shell/renderer/api/electron_api_web_frame.cc @@ -5,6 +5,7 @@ #include <limits> #include <memory> #include <string> +#include <string_view> #include <utility> #include <vector> @@ -397,7 +398,7 @@ class WebFrameRenderer : public gin::Wrappable<WebFrameRenderer>, private: bool MaybeGetRenderFrame(v8::Isolate* isolate, - const base::StringPiece method_name, + const std::string_view method_name, content::RenderFrame** render_frame_ptr) { std::string error_msg; if (!MaybeGetRenderFrame(&error_msg, method_name, render_frame_ptr)) { @@ -408,7 +409,7 @@ class WebFrameRenderer : public gin::Wrappable<WebFrameRenderer>, } bool MaybeGetRenderFrame(std::string* error_msg, - const base::StringPiece method_name, + const std::string_view method_name, content::RenderFrame** render_frame_ptr) { auto* frame = render_frame(); if (!frame) {
chore
e1e66fc8ac52af3f951404a647cb82a8389528c3
Samuel Attard
2022-12-05 15:17:37
docs: link net.request options to ClientRequestConstructorOptions (#36556)
diff --git a/docs/api/net.md b/docs/api/net.md index ffbff49d05..2fcf307d75 100644 --- a/docs/api/net.md +++ b/docs/api/net.md @@ -54,7 +54,7 @@ The `net` module has the following methods: ### `net.request(options)` -* `options` (ClientRequestConstructorOptions | string) - The `ClientRequest` constructor options. +* `options` ([ClientRequestConstructorOptions](client-request.md#new-clientrequestoptions) | string) - The `ClientRequest` constructor options. Returns [`ClientRequest`](./client-request.md)
docs
ea848bc1c57cef75bd2e4424256bafb25758db2b
Milan Burda
2023-02-16 15:41:41
test: use webContents.create() in type-safe way (#37281) test: use (webContents as typeof ElectronInternal.WebContents).create() Co-authored-by: Milan Burda <[email protected]>
diff --git a/spec/api-browser-view-spec.ts b/spec/api-browser-view-spec.ts index 09a5a3f450..c4de3dff86 100644 --- a/spec/api-browser-view-spec.ts +++ b/spec/api-browser-view-spec.ts @@ -41,7 +41,7 @@ describe('BrowserView module', () => { }); it('can be created with an existing webContents', async () => { - const wc = (webContents as any).create({ sandbox: true }); + const wc = (webContents as typeof ElectronInternal.WebContents).create({ sandbox: true }); await wc.loadURL('about:blank'); view = new BrowserView({ webContents: wc } as any); diff --git a/spec/api-browser-window-spec.ts b/spec/api-browser-window-spec.ts index ca5bcadd65..32e8049f83 100644 --- a/spec/api-browser-window-spec.ts +++ b/spec/api-browser-window-spec.ts @@ -2184,7 +2184,7 @@ describe('BrowserWindow module', () => { }); it('returns null for webContents without a BrowserWindow', () => { - const contents = (webContents as any).create({}); + const contents = (webContents as typeof ElectronInternal.WebContents).create(); try { expect(BrowserWindow.fromWebContents(contents)).to.be.null('BrowserWindow.fromWebContents(contents)'); } finally { diff --git a/spec/api-ipc-renderer-spec.ts b/spec/api-ipc-renderer-spec.ts index 64639dade4..47271bbaa7 100644 --- a/spec/api-ipc-renderer-spec.ts +++ b/spec/api-ipc-renderer-spec.ts @@ -135,7 +135,7 @@ describe('ipcRenderer module', () => { const payload = 'Hello World!'; before(async () => { - contents = (webContents as any).create({ + contents = (webContents as typeof ElectronInternal.WebContents).create({ preload: path.join(fixtures, 'module', 'preload-ipc-ping-pong.js'), ...webPreferences }); diff --git a/spec/api-protocol-spec.ts b/spec/api-protocol-spec.ts index 057f556795..9c142731d1 100644 --- a/spec/api-protocol-spec.ts +++ b/spec/api-protocol-spec.ts @@ -72,7 +72,7 @@ function defer (): Promise<any> & {resolve: Function, reject: Function} { 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 }); }); + before(() => { contents = (webContents as typeof ElectronInternal.WebContents).create({ sandbox: true }); }); after(() => contents.destroy()); async function ajax (url: string, options = {}) { @@ -980,7 +980,10 @@ describe('protocol module', () => { callback(''); }); - const newContents: WebContents = (webContents as any).create({ nodeIntegration: true, contextIsolation: false }); + const newContents = (webContents as typeof ElectronInternal.WebContents).create({ + nodeIntegration: true, + contextIsolation: false + }); const consoleMessages: string[] = []; newContents.on('console-message', (e, level, message) => consoleMessages.push(message)); try { @@ -1081,7 +1084,11 @@ describe('protocol module', () => { await registerStreamProtocol(standardScheme, protocolHandler); await registerStreamProtocol('stream', protocolHandler); - const newContents: WebContents = (webContents as any).create({ nodeIntegration: true, contextIsolation: false }); + const newContents = (webContents as typeof ElectronInternal.WebContents).create({ + nodeIntegration: true, + contextIsolation: false + }); + try { newContents.loadURL(testingScheme + '://fake-host'); const [, response] = await emittedOnce(ipcMain, 'result'); diff --git a/spec/api-service-workers-spec.ts b/spec/api-service-workers-spec.ts index 1f7ec5e510..77bdd697a7 100644 --- a/spec/api-service-workers-spec.ts +++ b/spec/api-service-workers-spec.ts @@ -39,7 +39,7 @@ describe('session.serviceWorkers', () => { }); }); - w = (webContents as any).create({ session: ses }); + w = (webContents as typeof ElectronInternal.WebContents).create({ session: ses }); }); afterEach(async () => { diff --git a/spec/api-web-contents-spec.ts b/spec/api-web-contents-spec.ts index b3c517a2ee..a11e38ec5e 100644 --- a/spec/api-web-contents-spec.ts +++ b/spec/api-web-contents-spec.ts @@ -3,7 +3,7 @@ import { AddressInfo } from 'net'; import * as path from 'path'; import * as fs from 'fs'; import * as http from 'http'; -import { BrowserWindow, ipcMain, webContents, session, WebContents, app, BrowserView } from 'electron/main'; +import { BrowserWindow, ipcMain, webContents, session, app, BrowserView } from 'electron/main'; import { emittedOnce } from './lib/events-helpers'; import { closeAllWindows } from './lib/window-helpers'; import { ifdescribe, delay, defer, waitUntil } from './lib/spec-helpers'; @@ -48,11 +48,11 @@ describe('webContents module', () => { describe('fromFrame()', () => { it('returns WebContents for mainFrame', () => { - const contents = (webContents as any).create() as WebContents; + const contents = (webContents as typeof ElectronInternal.WebContents).create(); expect(webContents.fromFrame(contents.mainFrame)).to.equal(contents); }); it('returns undefined for disposed frame', async () => { - const contents = (webContents as any).create() as WebContents; + const contents = (webContents as typeof ElectronInternal.WebContents).create(); const { mainFrame } = contents; contents.destroy(); await waitUntil(() => typeof webContents.fromFrame(mainFrame) === 'undefined'); @@ -1549,7 +1549,7 @@ describe('webContents module', () => { // is fine to retry this test for a few times. this.retries(3); - const contents = (webContents as any).create() as WebContents; + const contents = (webContents as typeof ElectronInternal.WebContents).create(); const originalEmit = contents.emit.bind(contents); contents.emit = (...args) => { return originalEmit(...args); }; contents.once(e.name as any, () => contents.destroy()); @@ -2261,7 +2261,7 @@ describe('webContents module', () => { afterEach(closeAllWindows); it('closes when close() is called', async () => { - const w = (webContents as any).create() as WebContents; + const w = (webContents as typeof ElectronInternal.WebContents).create(); const destroyed = emittedOnce(w, 'destroyed'); w.close(); await destroyed; @@ -2269,7 +2269,7 @@ describe('webContents module', () => { }); it('closes when close() is called after loading a page', async () => { - const w = (webContents as any).create() as WebContents; + const w = (webContents as typeof ElectronInternal.WebContents).create(); await w.loadURL('about:blank'); const destroyed = emittedOnce(w, 'destroyed'); w.close(); @@ -2284,7 +2284,7 @@ describe('webContents module', () => { registry = new FinalizationRegistry(resolve as any); }); (() => { - const w = (webContents as any).create() as WebContents; + const w = (webContents as typeof ElectronInternal.WebContents).create(); registry!.register(w, 42); })(); const i = setInterval(() => v8Util.requestGarbageCollectionForTesting(), 100); @@ -2302,7 +2302,7 @@ describe('webContents module', () => { }); it('ignores beforeunload if waitForBeforeUnload not specified', async () => { - const w = (webContents as any).create() as WebContents; + const w = (webContents as typeof ElectronInternal.WebContents).create(); await w.loadURL('about:blank'); await w.executeJavaScript('window.onbeforeunload = () => "hello"; null'); w.on('will-prevent-unload', () => { throw new Error('unexpected will-prevent-unload'); }); @@ -2313,7 +2313,7 @@ describe('webContents module', () => { }); it('runs beforeunload if waitForBeforeUnload is specified', async () => { - const w = (webContents as any).create() as WebContents; + const w = (webContents as typeof ElectronInternal.WebContents).create(); await w.loadURL('about:blank'); await w.executeJavaScript('window.onbeforeunload = () => "hello"; null'); const willPreventUnload = emittedOnce(w, 'will-prevent-unload'); @@ -2323,7 +2323,7 @@ describe('webContents module', () => { }); it('overriding beforeunload prevention results in webcontents close', async () => { - const w = (webContents as any).create() as WebContents; + const w = (webContents as typeof ElectronInternal.WebContents).create(); await w.loadURL('about:blank'); await w.executeJavaScript('window.onbeforeunload = () => "hello"; null'); w.once('will-prevent-unload', e => e.preventDefault()); diff --git a/spec/api-web-request-spec.ts b/spec/api-web-request-spec.ts index d70635759e..dcdb4dbca1 100644 --- a/spec/api-web-request-spec.ts +++ b/spec/api-web-request-spec.ts @@ -52,7 +52,7 @@ describe('webRequest module', () => { let contents: WebContents = null as unknown as WebContents; // NB. sandbox: true is used because it makes navigations much (~8x) faster. before(async () => { - contents = (webContents as any).create({ sandbox: true }); + contents = (webContents as typeof ElectronInternal.WebContents).create({ sandbox: true }); await contents.loadFile(path.join(fixturesPath, 'pages', 'fetch.html')); }); after(() => contents.destroy()); @@ -529,7 +529,7 @@ describe('webRequest module', () => { } }); - const contents = (webContents as any).create({ + const contents = (webContents as typeof ElectronInternal.WebContents).create({ session: ses, nodeIntegration: true, webSecurity: false, diff --git a/spec/chromium-spec.ts b/spec/chromium-spec.ts index f77be84cea..013c5a1dd4 100644 --- a/spec/chromium-spec.ts +++ b/spec/chromium-spec.ts @@ -1472,7 +1472,7 @@ describe('chromium features', () => { }); beforeEach(() => { - contents = (webContents as any).create({ + contents = (webContents as typeof ElectronInternal.WebContents).create({ nodeIntegration: true, contextIsolation: false }); @@ -1603,7 +1603,7 @@ describe('chromium features', () => { }); it('default value allows websql', async () => { - contents = (webContents as any).create({ + contents = (webContents as typeof ElectronInternal.WebContents).create({ session: sqlSession, nodeIntegration: true, contextIsolation: false @@ -1614,7 +1614,7 @@ describe('chromium features', () => { }); it('when set to false can disallow websql', async () => { - contents = (webContents as any).create({ + contents = (webContents as typeof ElectronInternal.WebContents).create({ session: sqlSession, nodeIntegration: true, enableWebSQL: false, @@ -1626,7 +1626,7 @@ describe('chromium features', () => { }); it('when set to false does not disable indexedDB', async () => { - contents = (webContents as any).create({ + contents = (webContents as typeof ElectronInternal.WebContents).create({ session: sqlSession, nodeIntegration: true, enableWebSQL: false, diff --git a/spec/fixtures/crash-cases/webcontents-create-leak-exit/index.js b/spec/fixtures/crash-cases/webcontents-create-leak-exit/index.js index d601c18fc1..0059a5c3df 100644 --- a/spec/fixtures/crash-cases/webcontents-create-leak-exit/index.js +++ b/spec/fixtures/crash-cases/webcontents-create-leak-exit/index.js @@ -1,6 +1,6 @@ const { app, webContents } = require('electron'); app.whenReady().then(function () { - webContents.create({}); + webContents.create(); app.quit(); }); diff --git a/spec/node-spec.ts b/spec/node-spec.ts index 035a2923ea..df8b4f0cd3 100644 --- a/spec/node-spec.ts +++ b/spec/node-spec.ts @@ -5,7 +5,7 @@ import * as path from 'path'; import * as util from 'util'; import { emittedOnce } from './lib/events-helpers'; import { getRemoteContext, ifdescribe, ifit, itremote, useRemoteContext } from './lib/spec-helpers'; -import { webContents, WebContents } from 'electron/main'; +import { webContents } from 'electron/main'; import { EventEmitter } from 'stream'; const features = process._linkedBinding('electron_common_features'); @@ -780,7 +780,7 @@ describe('node feature', () => { // NOTE: temporary debug logging to try to catch flake. child.stderr.on('data', (m) => console.log(m.toString())); child.stdout.on('data', (m) => console.log(m.toString())); - const w = (webContents as any).create({}) as WebContents; + const w = (webContents as typeof ElectronInternal.WebContents).create(); w.loadURL('about:blank') .then(() => w.executeJavaScript(`new Promise(resolve => { const connection = new WebSocket(${JSON.stringify(match[1])}) diff --git a/typings/internal-electron.d.ts b/typings/internal-electron.d.ts index 38f412666f..93ab254b8e 100644 --- a/typings/internal-electron.d.ts +++ b/typings/internal-electron.d.ts @@ -280,7 +280,7 @@ declare namespace ElectronInternal { } class WebContents extends Electron.WebContents { - static create(opts: Electron.WebPreferences): Electron.WebContents; + static create(opts?: Electron.WebPreferences): Electron.WebContents; } }
test
a75b892e9080753dcc5e1344f2a59fa641a65be1
Samuel Attard
2023-03-31 03:20:25
build: remove request dependency (#37747) * build: remove request dependency * oops
diff --git a/appveyor-woa.yml b/appveyor-woa.yml index b05c6e1ee0..1b26dbf668 100644 --- a/appveyor-woa.yml +++ b/appveyor-woa.yml @@ -36,7 +36,7 @@ environment: ELECTRON_ENABLE_STACK_DUMPING: 1 ELECTRON_ALSO_LOG_TO_STDERR: 1 MOCHA_REPORTER: mocha-multi-reporters - MOCHA_MULTI_REPORTERS: mocha-appveyor-reporter, tap + MOCHA_MULTI_REPORTERS: "@marshallofsound/mocha-appveyor-reporter, tap" GOMA_FALLBACK_ON_AUTH_FAILURE: true DEPOT_TOOLS_WIN_TOOLCHAIN: 0 PYTHONIOENCODING: UTF-8 diff --git a/appveyor.yml b/appveyor.yml index 7c5352760b..da25117c18 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -36,7 +36,7 @@ environment: ELECTRON_ENABLE_STACK_DUMPING: 1 ELECTRON_ALSO_LOG_TO_STDERR: 1 MOCHA_REPORTER: mocha-multi-reporters - MOCHA_MULTI_REPORTERS: mocha-appveyor-reporter, tap + MOCHA_MULTI_REPORTERS: "@marshallofsound/mocha-appveyor-reporter, tap" GOMA_FALLBACK_ON_AUTH_FAILURE: true DEPOT_TOOLS_WIN_TOOLCHAIN: 0 PYTHONIOENCODING: UTF-8 diff --git a/spec/package.json b/spec/package.json index 4d68933221..f594e90a99 100644 --- a/spec/package.json +++ b/spec/package.json @@ -6,6 +6,7 @@ "devDependencies": { "@electron-ci/echo": "file:./fixtures/native-addon/echo", "@electron-ci/uv-dlopen": "file:./fixtures/native-addon/uv-dlopen/", + "@marshallofsound/mocha-appveyor-reporter": "^0.4.3", "@types/sinon": "^9.0.4", "@types/ws": "^7.2.0", "basic-auth": "^2.0.1", @@ -19,7 +20,6 @@ "is-valid-window": "0.0.5", "mkdirp": "^0.5.1", "mocha": "^10.0.0", - "mocha-appveyor-reporter": "^0.4.2", "mocha-junit-reporter": "^1.18.0", "mocha-multi-reporters": "^1.1.7", "pdfjs-dist": "^2.2.228", diff --git a/spec/yarn.lock b/spec/yarn.lock index 320d1475d0..fa92925623 100644 --- a/spec/yarn.lock +++ b/spec/yarn.lock @@ -8,11 +8,23 @@ "@electron-ci/uv-dlopen@file:./fixtures/native-addon/uv-dlopen": version "0.0.1" +"@marshallofsound/mocha-appveyor-reporter@^0.4.3": + version "0.4.3" + resolved "https://registry.yarnpkg.com/@marshallofsound/mocha-appveyor-reporter/-/mocha-appveyor-reporter-0.4.3.tgz#a9225224391a90e3c6bb48415d5015de895a7114" + integrity sha512-uKMY+VTNWQRcMr9P7ErRqi0TKAC6oceFs2Y6MDdXqDNxOU4AQYQ6WNrH8LuCQFeV9Y/vMU7wFJvD7oQeWsQzWQ== + dependencies: + got "^11.8.6" + "@nornagon/[email protected]": version "0.0.8" resolved "https://registry.yarnpkg.com/@nornagon/put/-/put-0.0.8.tgz#9d497ec46c9364acc3f8b59aa3cf8ee4134ae337" integrity sha512-ugvXJjwF5ldtUpa7D95kruNJ41yFQDEKyF5CW4TgKJnh+W/zmlBzXXeKTyqIgwMFrkePN2JqOBqcF0M0oOunow== +"@sindresorhus/is@^4.0.0": + version "4.6.0" + resolved "https://registry.yarnpkg.com/@sindresorhus/is/-/is-4.6.0.tgz#3c7c9c46e678feefe7a2e5bb609d3dbd665ffb3f" + integrity sha512-t09vSN3MdfsyCHoFcTRCH/iUtG7OJ0CsjzB8cjAmKc/va/kIgeDI/TxsigdncE/4be734m0cvIYwNaV4i2XqAw== + "@sinonjs/commons@^1", "@sinonjs/commons@^1.6.0", "@sinonjs/commons@^1.7.0", "@sinonjs/commons@^1.7.2": version "1.8.0" resolved "https://registry.yarnpkg.com/@sinonjs/commons/-/commons-1.8.0.tgz#c8d68821a854c555bba172f3b06959a0039b236d" @@ -49,11 +61,47 @@ resolved "https://registry.yarnpkg.com/@sinonjs/text-encoding/-/text-encoding-0.7.1.tgz#8da5c6530915653f3a1f38fd5f101d8c3f8079c5" integrity sha512-+iTbntw2IZPb/anVDbypzfQa+ay64MW0Zo8aJ8gZPWMMK6/OubMVb6lUPMagqjOPnmtauXnFCACVl3O7ogjeqQ== +"@szmarczak/http-timer@^4.0.5": + version "4.0.6" + resolved "https://registry.yarnpkg.com/@szmarczak/http-timer/-/http-timer-4.0.6.tgz#b4a914bb62e7c272d4e5989fe4440f812ab1d807" + integrity sha512-4BAffykYOgO+5nzBWYwE3W90sBgLJoUPRWWcL8wlyiM8IB8ipJz3UMJ9KXQd1RKQXpKp8Tutn80HZtWsu2u76w== + dependencies: + defer-to-connect "^2.0.0" + +"@types/cacheable-request@^6.0.1": + version "6.0.3" + resolved "https://registry.yarnpkg.com/@types/cacheable-request/-/cacheable-request-6.0.3.tgz#a430b3260466ca7b5ca5bfd735693b36e7a9d183" + integrity sha512-IQ3EbTzGxIigb1I3qPZc1rWJnH0BmSKv5QYTalEwweFvyBDLSAe24zP0le/hyi7ecGfZVlIVAg4BZqb8WBwKqw== + dependencies: + "@types/http-cache-semantics" "*" + "@types/keyv" "^3.1.4" + "@types/node" "*" + "@types/responselike" "^1.0.0" + +"@types/http-cache-semantics@*": + version "4.0.1" + resolved "https://registry.yarnpkg.com/@types/http-cache-semantics/-/http-cache-semantics-4.0.1.tgz#0ea7b61496902b95890dc4c3a116b60cb8dae812" + integrity sha512-SZs7ekbP8CN0txVG2xVRH6EgKmEm31BOxA07vkFaETzZz1xh+cbt8BcI0slpymvwhx5dlFnQG2rTlPVQn+iRPQ== + +"@types/keyv@^3.1.4": + version "3.1.4" + resolved "https://registry.yarnpkg.com/@types/keyv/-/keyv-3.1.4.tgz#3ccdb1c6751b0c7e52300bcdacd5bcbf8faa75b6" + integrity sha512-BQ5aZNSCpj7D6K2ksrRCTmKRLEpnPvWDiLPfoGyhZ++8YtiK9d/3DBKPJgry359X/P1PfruyYwvnvwFjuEiEIg== + dependencies: + "@types/node" "*" + "@types/node@*": version "13.7.0" resolved "https://registry.yarnpkg.com/@types/node/-/node-13.7.0.tgz#b417deda18cf8400f278733499ad5547ed1abec4" integrity sha512-GnZbirvmqZUzMgkFn70c74OQpTTUcCzlhQliTzYjQMqg+hVKcDnxdL19Ne3UdYzdMA/+W3eb646FWn/ZaT1NfQ== +"@types/responselike@^1.0.0": + version "1.0.0" + resolved "https://registry.yarnpkg.com/@types/responselike/-/responselike-1.0.0.tgz#251f4fe7d154d2bad125abe1b429b23afd262e29" + integrity sha512-85Y2BjiufFzaMIlvJDvTTB8Fxl2xfLo4HgmHzVBz08w4wDePCTjYw66PdrolO0kzli3yam/YCgRufyo1DdQVTA== + dependencies: + "@types/node" "*" + "@types/sinon@^9.0.4": version "9.0.4" resolved "https://registry.yarnpkg.com/@types/sinon/-/sinon-9.0.4.tgz#e934f904606632287a6e7f7ab0ce3f08a0dad4b1" @@ -86,7 +134,7 @@ ajv-keywords@^3.1.0: resolved "https://registry.yarnpkg.com/ajv-keywords/-/ajv-keywords-3.4.1.tgz#ef916e271c64ac12171fd8384eaae6b2345854da" integrity sha512-RO1ibKvd27e6FEShVFfPALuHI3WjSVNeK5FIsmme/LYRNxjKuNj+Dt7bucLa6NdSv3JcVTyMlm9kGR84z1XpaQ== -ajv@^6.1.0, ajv@^6.12.3: +ajv@^6.1.0: version "6.12.6" resolved "https://registry.yarnpkg.com/ajv/-/ajv-6.12.6.tgz#baf5a62e802b07d977034586f8c3baf5adf26df4" integrity sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g== @@ -131,38 +179,11 @@ argparse@^2.0.1: resolved "https://registry.yarnpkg.com/argparse/-/argparse-2.0.1.tgz#246f50f3ca78a3240f6c997e8a9bd1eac49e4b38" integrity sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q== -asn1@~0.2.3: - version "0.2.6" - resolved "https://registry.yarnpkg.com/asn1/-/asn1-0.2.6.tgz#0d3a7bb6e64e02a90c0303b31f292868ea09a08d" - integrity sha512-ix/FxPn0MDjeyJ7i/yoHGFt/EX6LyNbxSEhPPXODPL+KB0VPk86UYfL0lMdy+KCnv+fmvIzySwaK5COwqVbWTQ== - dependencies: - safer-buffer "~2.1.0" - [email protected], assert-plus@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/assert-plus/-/assert-plus-1.0.0.tgz#f12e0f3c5d77b0b1cdd9146942e4e96c1e4dd525" - integrity sha1-8S4PPF13sLHN2RRpQuTpbB5N1SU= - assertion-error@^1.1.0: version "1.1.0" resolved "https://registry.yarnpkg.com/assertion-error/-/assertion-error-1.1.0.tgz#e60b6b0e8f301bd97e5375215bda406c85118c0b" integrity sha512-jgsaNduz+ndvGyFt3uSuWqvy4lCnIJiovtouQN5JZHOKCS2QuhEdbcQHFhVksz2N2U9hXJo8odG7ETyWlEeuDw== -asynckit@^0.4.0: - version "0.4.0" - resolved "https://registry.yarnpkg.com/asynckit/-/asynckit-0.4.0.tgz#c79ed97f7f34cb8f2ba1bc9790bcc366474b4b79" - integrity sha1-x57Zf380y48robyXkLzDZkdLS3k= - -aws-sign2@~0.7.0: - version "0.7.0" - resolved "https://registry.yarnpkg.com/aws-sign2/-/aws-sign2-0.7.0.tgz#b46e890934a9591f2d2f6f86d7e6a9f1b3fe76a8" - integrity sha1-tG6JCTSpWR8tL2+G1+ap8bP+dqg= - -aws4@^1.8.0: - version "1.11.0" - resolved "https://registry.yarnpkg.com/aws4/-/aws4-1.11.0.tgz#d61f46d83b2519250e2784daf5b09479a8b41c59" - integrity sha512-xh1Rl34h6Fi1DC2WWKfxUTVqRsNnr6LsKz2+hfwDxQJWmrx8+c7ylaqBMcHfl1U1r2dsifOvKX3LQuLNZ+XSvA== - balanced-match@^1.0.0: version "1.0.2" resolved "https://registry.yarnpkg.com/balanced-match/-/balanced-match-1.0.2.tgz#e83e3a7e3f300b34cb9d87f615fa0cbf357690ee" @@ -175,13 +196,6 @@ basic-auth@^2.0.1: dependencies: safe-buffer "5.1.2" -bcrypt-pbkdf@^1.0.0: - version "1.0.2" - resolved "https://registry.yarnpkg.com/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.2.tgz#a4301d389b6a43f9b67ff3ca11a3f6637e360e9e" - integrity sha1-pDAdOJtqQ/m2f/PKEaP2Y342Dp4= - dependencies: - tweetnacl "^0.14.3" - big.js@^5.2.2: version "5.2.2" resolved "https://registry.yarnpkg.com/big.js/-/big.js-5.2.2.tgz#65f0af382f578bcdc742bd9c281e9cb2d7768328" @@ -233,16 +247,29 @@ busboy@^1.6.0: dependencies: streamsearch "^1.1.0" +cacheable-lookup@^5.0.3: + version "5.0.4" + resolved "https://registry.yarnpkg.com/cacheable-lookup/-/cacheable-lookup-5.0.4.tgz#5a6b865b2c44357be3d5ebc2a467b032719a7005" + integrity sha512-2/kNscPhpcxrOigMZzbiWF7dz8ilhb/nIHU3EyZiXWXpeq/au8qJ8VhdftMkty3n7Gj6HIGalQG8oiBNB3AJgA== + +cacheable-request@^7.0.2: + version "7.0.2" + resolved "https://registry.yarnpkg.com/cacheable-request/-/cacheable-request-7.0.2.tgz#ea0d0b889364a25854757301ca12b2da77f91d27" + integrity sha512-pouW8/FmiPQbuGpkXQ9BAPv/Mo5xDGANgSNXzTzJ8DrKGuXOssM4wIQRjfanNRh3Yu5cfYPvcorqbhg2KIJtew== + dependencies: + clone-response "^1.0.2" + get-stream "^5.1.0" + http-cache-semantics "^4.0.0" + keyv "^4.0.0" + lowercase-keys "^2.0.0" + normalize-url "^6.0.1" + responselike "^2.0.0" + camelcase@^6.0.0: version "6.3.0" resolved "https://registry.yarnpkg.com/camelcase/-/camelcase-6.3.0.tgz#5685b95eb209ac9c0c177467778c9c84df58ba9a" integrity sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA== -caseless@~0.12.0: - version "0.12.0" - resolved "https://registry.yarnpkg.com/caseless/-/caseless-0.12.0.tgz#1b681c21ff84033c826543090689420d187151dc" - integrity sha1-G2gcIf+EAzyCZUMJBolCDRhxUdw= - chai-as-promised@^7.1.1: version "7.1.1" resolved "https://registry.yarnpkg.com/chai-as-promised/-/chai-as-promised-7.1.1.tgz#08645d825deb8696ee61725dbf590c012eb00ca0" @@ -305,6 +332,13 @@ cliui@^7.0.2: strip-ansi "^6.0.0" wrap-ansi "^7.0.0" +clone-response@^1.0.2: + version "1.0.3" + resolved "https://registry.yarnpkg.com/clone-response/-/clone-response-1.0.3.tgz#af2032aa47816399cf5f0a1d0db902f517abb8c3" + integrity sha512-ROoL94jJH2dUVML2Y/5PEDNaSHgeOdSDicUyS7izcF63G6sTc/FTjLub4b8Il9S8S0beOfYt0TaA5qvFK+w0wA== + dependencies: + mimic-response "^1.0.0" + coffeescript@^2.4.1: version "2.7.0" resolved "https://registry.yarnpkg.com/coffeescript/-/coffeescript-2.7.0.tgz#a43ec03be6885d6d1454850ea70b9409c391279c" @@ -322,35 +356,16 @@ color-name@~1.1.4: resolved "https://registry.yarnpkg.com/color-name/-/color-name-1.1.4.tgz#c2a09a87acbde69543de6f63fa3995c826c536a2" integrity sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA== -combined-stream@^1.0.6, combined-stream@~1.0.6: - version "1.0.8" - resolved "https://registry.yarnpkg.com/combined-stream/-/combined-stream-1.0.8.tgz#c3d45a8b34fd730631a110a8a2520682b31d5a7f" - integrity sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg== - dependencies: - delayed-stream "~1.0.0" - [email protected]: version "0.0.1" resolved "https://registry.yarnpkg.com/concat-map/-/concat-map-0.0.1.tgz#d8a96bd77fd68df7793a73036a3ba0d5405d477b" integrity sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg== [email protected]: - version "1.0.2" - resolved "https://registry.yarnpkg.com/core-util-is/-/core-util-is-1.0.2.tgz#b5fd54220aa2bc5ab57aab7140c940754503c1a7" - integrity sha1-tf1UIgqivFq1eqtxQMlAdUUDwac= - [email protected]: version "0.0.2" resolved "https://registry.yarnpkg.com/crypt/-/crypt-0.0.2.tgz#88d7ff7ec0dfb86f713dc87bbb42d044d3e6c41b" integrity sha512-mCxBlsHFYh9C+HVpiEacem8FEBnMXgU9gy4zmNC+SXAZNB/1idgp/aulFJ4FgCi7GPEVbfyng092GqL2k2rmow== -dashdash@^1.12.0: - version "1.14.1" - resolved "https://registry.yarnpkg.com/dashdash/-/dashdash-1.14.1.tgz#853cfa0f7cbe2fed5de20326b8dd581035f6e2f0" - integrity sha1-hTz6D3y+L+1d4gMmuN1YEDX24vA= - dependencies: - assert-plus "^1.0.0" - "dbus-native@github:nornagon/dbus-native#master": version "0.4.0" resolved "https://codeload.github.com/nornagon/dbus-native/tar.gz/b90ed62d0b5cb93909173c3e0551d9bff0602a90" @@ -384,6 +399,13 @@ decamelize@^4.0.0: resolved "https://registry.yarnpkg.com/decamelize/-/decamelize-4.0.0.tgz#aa472d7bf660eb15f3494efd531cab7f2a709837" integrity sha512-9iE1PgSik9HeIIw2JO94IidnE3eBoQrFJ3w7sFuzSX4DpmZ3v5sZpUiV5Swcf6mQEF+Y0ru8Neo+p+nyh2J+hQ== +decompress-response@^6.0.0: + version "6.0.0" + resolved "https://registry.yarnpkg.com/decompress-response/-/decompress-response-6.0.0.tgz#ca387612ddb7e104bd16d85aab00d5ecf09c66fc" + integrity sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ== + dependencies: + mimic-response "^3.1.0" + deep-eql@^3.0.1: version "3.0.1" resolved "https://registry.yarnpkg.com/deep-eql/-/deep-eql-3.0.1.tgz#dfc9404400ad1c8fe023e7da1df1c147c4b444df" @@ -391,12 +413,12 @@ deep-eql@^3.0.1: dependencies: type-detect "^4.0.0" -delayed-stream@~1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/delayed-stream/-/delayed-stream-1.0.0.tgz#df3ae199acadfb7d440aaae0b29e2272b24ec619" - integrity sha1-3zrhmayt+31ECqrgsp4icrJOxhk= +defer-to-connect@^2.0.0: + version "2.0.1" + resolved "https://registry.yarnpkg.com/defer-to-connect/-/defer-to-connect-2.0.1.tgz#8016bdb4143e4632b77a3449c6236277de520587" + integrity sha512-4tvttepXG1VaYGrRibk5EwJd1t4udunSOVMdLSAL6mId1ix438oPwPZMALY41FCijukO1L0twNcGsdzS7dHgDg== [email protected], depd@~1.1.2: +depd@~1.1.2: version "1.1.2" resolved "https://registry.yarnpkg.com/depd/-/depd-1.1.2.tgz#9bcd52e14c097763e749b274c4346ed2e560b5a9" integrity sha512-7emPTl6Dpo6JRXOXjLRxck+FlLRX5847cLKEn00PLAgc3g2hTZZgr+e4c2v6QpSmLeFP3n5yUo7ft6avBK/5jQ== @@ -426,14 +448,6 @@ duplexer@^0.1.1, duplexer@~0.1.1: resolved "https://registry.yarnpkg.com/duplexer/-/duplexer-0.1.2.tgz#3abe43aef3835f8ae077d136ddce0f276b0400e6" integrity sha512-jtD6YG370ZCIi/9GTaJKQxWTZD045+4R4hTk/x1UyoqadyJ9x9CgSi1RlVDQF8U2sxLLSnFkCaMihqljHIWgMg== -ecc-jsbn@~0.1.1: - version "0.1.2" - resolved "https://registry.yarnpkg.com/ecc-jsbn/-/ecc-jsbn-0.1.2.tgz#3a83a904e54353287874c564b7549386849a98c9" - integrity sha1-OoOpBOVDUyh4dMVkt1SThoSamMk= - dependencies: - jsbn "~0.1.0" - safer-buffer "^2.1.0" - [email protected]: version "1.1.1" resolved "https://registry.yarnpkg.com/ee-first/-/ee-first-1.1.1.tgz#590c61156b0ae2f4f0255732a158b266bc56b21d" @@ -454,6 +468,13 @@ encodeurl@~1.0.2: resolved "https://registry.yarnpkg.com/encodeurl/-/encodeurl-1.0.2.tgz#ad3ff4c86ec2d029322f5a02c3a9a606c95b3f59" integrity sha512-TPJXq8JqFaVYm2CWmPvnP2Iyo4ZSM7/QKcSmuMLDObfpH5fi7RUGmd/rTDf+rut/saiDiQEeVTNgAmJEdAOx0w== +end-of-stream@^1.1.0: + version "1.4.4" + resolved "https://registry.yarnpkg.com/end-of-stream/-/end-of-stream-1.4.4.tgz#5ae64a5f45057baf3626ec14da0ca5e4b2431eb0" + integrity sha512-+uw1inIHVPQoaVuHzRyXd21icM+cnt4CzD5rW+NC1wjOUSTOs+Te7FOv7AhN7vS9x/oIyhLP5PR1H+phQAHu5Q== + dependencies: + once "^1.4.0" + escalade@^3.1.1: version "3.1.1" resolved "https://registry.yarnpkg.com/escalade/-/escalade-3.1.1.tgz#d8cfdc7000965c5a0174b4a82eaa5c0552742e40" @@ -487,21 +508,6 @@ event-stream@^4.0.0: stream-combiner "^0.2.2" through "^2.3.8" -extend@~3.0.2: - version "3.0.2" - resolved "https://registry.yarnpkg.com/extend/-/extend-3.0.2.tgz#f8b1136b4071fbd8eb140aff858b1019ec2915fa" - integrity sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g== - [email protected]: - version "1.3.0" - resolved "https://registry.yarnpkg.com/extsprintf/-/extsprintf-1.3.0.tgz#96918440e3041a7a414f8c52e3c574eb3c3e1e05" - integrity sha1-lpGEQOMEGnpBT4xS48V06zw+HgU= - -extsprintf@^1.2.0: - version "1.4.1" - resolved "https://registry.yarnpkg.com/extsprintf/-/extsprintf-1.4.1.tgz#8d172c064867f235c0c84a596806d279bf4bcc07" - integrity sha512-Wrk35e8ydCKDj/ArClo1VrPVmN8zph5V4AtHwIuHhvMXsKf73UT3BOD+azBIW+3wOJ4FhEH7zyaJCFvChjYvMA== - fast-deep-equal@^3.1.1: version "3.1.3" resolved "https://registry.yarnpkg.com/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz#3a7d56b559d6cbc3eb512325244e619a65c6c525" @@ -537,20 +543,6 @@ flat@^5.0.2: resolved "https://registry.yarnpkg.com/flat/-/flat-5.0.2.tgz#8ca6fe332069ffa9d324c327198c598259ceb241" integrity sha512-b6suED+5/3rTpUBdG1gupIl8MPFCAMA0QXwmljLhvCUKcUvdE4gWky9zpuGCcXHOsz4J9wPGNWq6OKpmIzz3hQ== -forever-agent@~0.6.1: - version "0.6.1" - resolved "https://registry.yarnpkg.com/forever-agent/-/forever-agent-0.6.1.tgz#fbc71f0c41adeb37f96c577ad1ed42d8fdacca91" - integrity sha1-+8cfDEGt6zf5bFd60e1C2P2sypE= - -form-data@~2.3.2: - version "2.3.3" - resolved "https://registry.yarnpkg.com/form-data/-/form-data-2.3.3.tgz#dcce52c05f644f298c6a7ab936bd724ceffbf3a6" - integrity sha512-1lLKB2Mu3aGP1Q/2eCOx0fNbRMe7XdwktwOruhfqqd0rIJWwN4Dh+E3hrPSlDCXnSR7UtZ1N38rVXm+6+MEhJQ== - dependencies: - asynckit "^0.4.0" - combined-stream "^1.0.6" - mime-types "^2.1.12" - [email protected]: version "0.5.2" resolved "https://registry.yarnpkg.com/fresh/-/fresh-0.5.2.tgz#3d8cadd90d976569fa835ab1f8e4b23a105605a7" @@ -581,12 +573,12 @@ get-func-name@^2.0.0: resolved "https://registry.yarnpkg.com/get-func-name/-/get-func-name-2.0.0.tgz#ead774abee72e20409433a066366023dd6887a41" integrity sha512-Hm0ixYtaSZ/V7C8FJrtZIuBBI+iSgL+1Aq82zSu8VQNB4S3Gk8e7Qs3VwBDJAhmRZcFqkl3tQu36g/Foh5I5ig== -getpass@^0.1.1: - version "0.1.7" - resolved "https://registry.yarnpkg.com/getpass/-/getpass-0.1.7.tgz#5eff8e3e684d569ae4cb2b1282604e8ba62149fa" - integrity sha1-Xv+OPmhNVprkyysSgmBOi6YhSfo= +get-stream@^5.1.0: + version "5.2.0" + resolved "https://registry.yarnpkg.com/get-stream/-/get-stream-5.2.0.tgz#4966a1795ee5ace65e706c4b7beb71257d6e22d3" + integrity sha512-nBF+F1rAZVCu/p7rjzgA+Yb4lfYXrpl7a6VmJrU8wF9I1CKvP/QwPNZHnOlwbTkY6dvtFIzFMSyQXbLoTQPRpA== dependencies: - assert-plus "^1.0.0" + pump "^3.0.0" glob-parent@~5.1.2: version "5.1.2" @@ -619,24 +611,28 @@ glob@^7.1.3: once "^1.3.0" path-is-absolute "^1.0.0" +got@^11.8.6: + version "11.8.6" + resolved "https://registry.yarnpkg.com/got/-/got-11.8.6.tgz#276e827ead8772eddbcfc97170590b841823233a" + integrity sha512-6tfZ91bOr7bOXnK7PRDCGBLa1H4U080YHNaAQ2KsMGlLEzRbk44nsZF2E1IeRc3vtJHPVbKCYgdFbaGO2ljd8g== + dependencies: + "@sindresorhus/is" "^4.0.0" + "@szmarczak/http-timer" "^4.0.5" + "@types/cacheable-request" "^6.0.1" + "@types/responselike" "^1.0.0" + cacheable-lookup "^5.0.3" + cacheable-request "^7.0.2" + decompress-response "^6.0.0" + http2-wrapper "^1.0.0-beta.5.2" + lowercase-keys "^2.0.0" + p-cancelable "^2.0.0" + responselike "^2.0.0" + graceful-fs@^4.1.15: version "4.2.10" resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.2.10.tgz#147d3a006da4ca3ce14728c7aefc287c367d7a6c" integrity sha512-9ByhssR2fPVsNZj478qUUbKfmL0+t5BDVyjShtyZZLiK7ZDAArFFfopyOTj0M05wE2tJPisA4iTnnXl2YoPvOA== -har-schema@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/har-schema/-/har-schema-2.0.0.tgz#a94c2224ebcac04782a0d9035521f24735b7ec92" - integrity sha1-qUwiJOvKwEeCoNkDVSHyRzW37JI= - -har-validator@~5.1.0: - version "5.1.5" - resolved "https://registry.yarnpkg.com/har-validator/-/har-validator-5.1.5.tgz#1f0803b9f8cb20c0fa13822df1ecddb36bde1efd" - integrity sha512-nmT2T0lljbxdQZfspsno9hgrG3Uir6Ks5afism62poxqBM6sDnMEuPmzTq8XN0OEwqKLLdh1jQI3qyE66Nzb3w== - dependencies: - ajv "^6.12.3" - har-schema "^2.0.0" - has-flag@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/has-flag/-/has-flag-4.0.0.tgz#944771fd9c81c81265c4d6941860da06bb59479b" @@ -652,6 +648,11 @@ hexy@^0.2.10: resolved "https://registry.yarnpkg.com/hexy/-/hexy-0.2.11.tgz#9939c25cb6f86a91302f22b8a8a72573518e25b4" integrity sha512-ciq6hFsSG/Bpt2DmrZJtv+56zpPdnq+NQ4ijEFrveKN0ZG1mhl/LdT1NQZ9se6ty1fACcI4d4vYqC9v8EYpH2A== +http-cache-semantics@^4.0.0: + version "4.1.1" + resolved "https://registry.yarnpkg.com/http-cache-semantics/-/http-cache-semantics-4.1.1.tgz#abe02fcb2985460bf0323be664436ec3476a6d5a" + integrity sha512-er295DKPVsV82j5kw1Gjt+ADA/XYHsajl82cGNQG2eyoPkvgUhX+nDIyelzhIWbbsXP39EHcI6l5tYs2FYqYXQ== + http-errors@~1.6.2: version "1.6.3" resolved "https://registry.yarnpkg.com/http-errors/-/http-errors-1.6.3.tgz#8b55680bb4be283a0b5bf4ea2e38580be1d9320d" @@ -662,14 +663,13 @@ http-errors@~1.6.2: setprototypeof "1.1.0" statuses ">= 1.4.0 < 2" -http-signature@~1.2.0: - version "1.2.0" - resolved "https://registry.yarnpkg.com/http-signature/-/http-signature-1.2.0.tgz#9aecd925114772f3d95b65a60abb8f7c18fbace1" - integrity sha1-muzZJRFHcvPZW2WmCruPfBj7rOE= +http2-wrapper@^1.0.0-beta.5.2: + version "1.0.3" + resolved "https://registry.yarnpkg.com/http2-wrapper/-/http2-wrapper-1.0.3.tgz#b8f55e0c1f25d4ebd08b3b0c2c079f9590800b3d" + integrity sha512-V+23sDMr12Wnz7iTcDeJr3O6AIxlnvT/bmaAAAP/Xda35C90p9599p0F1eHR/N1KILWSoWVAiOMFjBBXaXSMxg== dependencies: - assert-plus "^1.0.0" - jsprim "^1.2.2" - sshpk "^1.7.0" + quick-lru "^5.1.1" + resolve-alpn "^1.0.0" inflight@^1.0.4: version "1.0.6" @@ -728,11 +728,6 @@ is-plain-obj@^2.1.0: resolved "https://registry.yarnpkg.com/is-plain-obj/-/is-plain-obj-2.1.0.tgz#45e42e37fccf1f40da8e5f76ee21515840c09287" integrity sha512-YWnfyRwxL/+SsrWYfOpUtz5b3YD+nyfkHvjbcanzk8zgyO4ASD67uVMRt8k5bM4lLMDnXfriRhOpemw+NfT1eA== -is-typedarray@~1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/is-typedarray/-/is-typedarray-1.0.0.tgz#e479c80858df0c1b11ddda6940f96011fcda4a9a" - integrity sha1-5HnICFjfDBsR3dppQPlgEfzaSpo= - is-unicode-supported@^0.1.0: version "0.1.0" resolved "https://registry.yarnpkg.com/is-unicode-supported/-/is-unicode-supported-0.1.0.tgz#3f26c76a809593b52bfa2ecb5710ed2779b522a7" @@ -750,11 +745,6 @@ [email protected]: resolved "https://registry.yarnpkg.com/isarray/-/isarray-0.0.1.tgz#8a18acfca9a8f4177e09abfc6038939b05d1eedf" integrity sha1-ihis/Kmo9Bd+Cav8YDiTmwXR7t8= -isstream@~0.1.2: - version "0.1.2" - resolved "https://registry.yarnpkg.com/isstream/-/isstream-0.1.2.tgz#47e63f7af55afa6f92e1500e690eb8b8529c099a" - integrity sha1-R+Y/evVa+m+S4VAOaQ64uFKcCZo= - [email protected]: version "4.1.0" resolved "https://registry.yarnpkg.com/js-yaml/-/js-yaml-4.1.0.tgz#c1fb65f8f5017901cdd2c951864ba18458a10602" @@ -762,26 +752,16 @@ [email protected]: dependencies: argparse "^2.0.1" -jsbn@~0.1.0: - version "0.1.1" - resolved "https://registry.yarnpkg.com/jsbn/-/jsbn-0.1.1.tgz#a5e654c2e5a2deb5f201d96cefbca80c0ef2f513" - integrity sha1-peZUwuWi3rXyAdls77yoDA7y9RM= [email protected]: + version "3.0.1" + resolved "https://registry.yarnpkg.com/json-buffer/-/json-buffer-3.0.1.tgz#9338802a30d3b6605fbe0613e094008ca8c05a13" + integrity sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ== json-schema-traverse@^0.4.1: version "0.4.1" resolved "https://registry.yarnpkg.com/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz#69f6a87d9513ab8bb8fe63bdb0979c448e684660" integrity sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg== [email protected]: - version "0.4.0" - resolved "https://registry.yarnpkg.com/json-schema/-/json-schema-0.4.0.tgz#f7de4cf6efab838ebaeb3236474cbba5a1930ab5" - integrity sha512-es94M3nTIfsEPisRafak+HDLfHXnKBhV3vU5eqPcS3flIWqcxJWgXHXiey3YrpaNsanY5ei1VoYEbOzijuq9BA== - -json-stringify-safe@~5.0.1: - version "5.0.1" - resolved "https://registry.yarnpkg.com/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz#1296a2d58fd45f19a0f6ce01d65701e2c735b6eb" - integrity sha1-Epai1Y/UXxmg9s4B1lcB4sc1tus= - json5@^1.0.1: version "1.0.2" resolved "https://registry.yarnpkg.com/json5/-/json5-1.0.2.tgz#63d98d60f21b313b77c4d6da18bfa69d80e1d593" @@ -789,21 +769,18 @@ json5@^1.0.1: dependencies: minimist "^1.2.0" -jsprim@^1.2.2: - version "1.4.2" - resolved "https://registry.yarnpkg.com/jsprim/-/jsprim-1.4.2.tgz#712c65533a15c878ba59e9ed5f0e26d5b77c5feb" - integrity sha512-P2bSOMAc/ciLz6DzgjVlGJP9+BrJWu5UDGK70C2iweC5QBIeFf0ZXRvGjEj2uYgrY2MkAAhsSWHDWlFtEroZWw== - dependencies: - assert-plus "1.0.0" - extsprintf "1.3.0" - json-schema "0.4.0" - verror "1.10.0" - just-extend@^4.0.2: version "4.1.0" resolved "https://registry.yarnpkg.com/just-extend/-/just-extend-4.1.0.tgz#7278a4027d889601640ee0ce0e5a00b992467da4" integrity sha512-ApcjaOdVTJ7y4r08xI5wIqpvwS48Q0PBG4DJROcEkH1f8MdAiNFyFxz3xoL0LWAVwjrwPYZdVHHxhRHcx/uGLA== +keyv@^4.0.0: + version "4.5.2" + resolved "https://registry.yarnpkg.com/keyv/-/keyv-4.5.2.tgz#0e310ce73bf7851ec702f2eaf46ec4e3805cce56" + integrity sha512-5MHbFaKn8cNSmVW7BYnijeAVlE4cYA/SVkifVgrh7yotnfhKmjuXpDKjrABLnT0SfHWV21P8ow07OGfRrNDg8g== + dependencies: + json-buffer "3.0.1" + loader-utils@^1.0.0: version "1.4.2" resolved "https://registry.yarnpkg.com/loader-utils/-/loader-utils-1.4.2.tgz#29a957f3a63973883eb684f10ffd3d151fec01a3" @@ -850,6 +827,11 @@ loupe@^2.3.1: dependencies: get-func-name "^2.0.0" +lowercase-keys@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/lowercase-keys/-/lowercase-keys-2.0.0.tgz#2603e78b7b4b0006cbca2fbcc8a3202558ac9479" + integrity sha512-tqNXrS78oMOE73NMxK4EMLQsQowWf8jKooH9g7xPavRT706R6bkQJ6DY2Te7QukaZsulxa30wQ7bk0pm4XiHmA== + [email protected]: version "0.0.7" resolved "https://registry.yarnpkg.com/map-stream/-/map-stream-0.0.7.tgz#8a1f07896d82b10926bd3744a2420009f88974a8" @@ -864,23 +846,21 @@ md5@^2.1.0: crypt "0.0.2" is-buffer "~1.1.6" [email protected]: - version "1.51.0" - resolved "https://registry.yarnpkg.com/mime-db/-/mime-db-1.51.0.tgz#d9ff62451859b18342d960850dc3cfb77e63fb0c" - integrity sha512-5y8A56jg7XVQx2mbv1lu49NR4dokRnhZYTtL+KGfaa27uq4pSTXkwQkFJl4pkRMyNFz/EtYDSkiiEHx3F7UN6g== - -mime-types@^2.1.12, mime-types@~2.1.19: - version "2.1.34" - resolved "https://registry.yarnpkg.com/mime-types/-/mime-types-2.1.34.tgz#5a712f9ec1503511a945803640fafe09d3793c24" - integrity sha512-6cP692WwGIs9XXdOO4++N+7qjqv0rqxxVvJ3VHPh/Sc9mVZcQP+ZGhkKiTvWMQRr2tbHkJP/Yn7Y0npb3ZBs4A== - dependencies: - mime-db "1.51.0" - [email protected]: version "1.4.1" resolved "https://registry.yarnpkg.com/mime/-/mime-1.4.1.tgz#121f9ebc49e3766f311a76e1fa1c8003c4b03aa6" integrity sha512-KI1+qOZu5DcW6wayYHSzR/tXKCDC5Om4s1z2QJjDULzLcmf3DvzS7oluY4HCTrc+9FiKmWUgeNLg7W3uIQvxtQ== +mimic-response@^1.0.0: + version "1.0.1" + resolved "https://registry.yarnpkg.com/mimic-response/-/mimic-response-1.0.1.tgz#4923538878eef42063cb8a3e3b0798781487ab1b" + integrity sha512-j5EctnkH7amfV/q5Hgmoal1g2QHFJRraOtmx0JpIqkxhBhI/lJSl1nMpQ45hVarwNETOoWEimndZ4QK0RHxuxQ== + +mimic-response@^3.1.0: + version "3.1.0" + resolved "https://registry.yarnpkg.com/mimic-response/-/mimic-response-3.1.0.tgz#2d1d59af9c1b129815accc2c46a022a5ce1fa3c9" + integrity sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ== + [email protected]: version "5.0.1" resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-5.0.1.tgz#fb9022f7528125187c92bd9e9b6366be1cf3415b" @@ -907,13 +887,6 @@ mkdirp@^0.5.1, mkdirp@~0.5.1: dependencies: minimist "^1.2.6" -mocha-appveyor-reporter@^0.4.2: - version "0.4.2" - resolved "https://registry.yarnpkg.com/mocha-appveyor-reporter/-/mocha-appveyor-reporter-0.4.2.tgz#feb1dcc77ca0bd11cbda3fd72e5ff187d1e4758d" - integrity sha512-toYTeM5GI4DPghD0Fh17wCDEXvrUZLB5zUkBUORUxxAf/XxJPZmyMVw0Xaue3gFjdTE4eR4IOZO1wloR2Cfniw== - dependencies: - request-json "^0.6.4" - mocha-junit-reporter@^1.18.0: version "1.23.3" resolved "https://registry.yarnpkg.com/mocha-junit-reporter/-/mocha-junit-reporter-1.23.3.tgz#941e219dd759ed732f8641e165918aa8b167c981" @@ -1005,10 +978,10 @@ normalize-path@^3.0.0, normalize-path@~3.0.0: resolved "https://registry.yarnpkg.com/normalize-path/-/normalize-path-3.0.0.tgz#0dcd69ff23a1c9b11fd0978316644a0388216a65" integrity sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA== -oauth-sign@~0.9.0: - version "0.9.0" - resolved "https://registry.yarnpkg.com/oauth-sign/-/oauth-sign-0.9.0.tgz#47a7b016baa68b5fa0ecf3dee08a85c679ac6455" - integrity sha512-fexhUFFPTGV8ybAtSIGbV6gOkSv8UtRbDBnAyLQw4QPKkgNlsH2ByPGtMUqdWkos6YCRmAqViwgZrJc/mRDzZQ== +normalize-url@^6.0.1: + version "6.1.0" + resolved "https://registry.yarnpkg.com/normalize-url/-/normalize-url-6.1.0.tgz#40d0885b535deffe3f3147bec877d05fe4c5668a" + integrity sha512-DlL+XwOy3NxAQ8xuC0okPgK46iuVNAK01YN7RueYBqqFeGsBjV9XmCAzAdgt+667bCl5kPh9EqKKDwnaPG1I7A== on-finished@~2.3.0: version "2.3.0" @@ -1017,7 +990,7 @@ on-finished@~2.3.0: dependencies: ee-first "1.1.1" -once@^1.3.0: +once@^1.3.0, once@^1.3.1, once@^1.4.0: version "1.4.0" resolved "https://registry.yarnpkg.com/once/-/once-1.4.0.tgz#583b1aa775961d4b113ac17d9c50baef9dd76bd1" integrity sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w== @@ -1032,6 +1005,11 @@ optimist@^0.6.1: minimist "~0.0.1" wordwrap "~0.0.2" +p-cancelable@^2.0.0: + version "2.1.1" + resolved "https://registry.yarnpkg.com/p-cancelable/-/p-cancelable-2.1.1.tgz#aab7fbd416582fa32a3db49859c122487c5ed2cf" + integrity sha512-BZOr3nRQHOntUjTrH8+Lh54smKHoHyur8We1V8DSMVrl5A2malOOwuJRnKRDjSnkoeBh4at6BwEnb5I7Jl31wg== + p-limit@^3.0.2: version "3.1.0" resolved "https://registry.yarnpkg.com/p-limit/-/p-limit-3.1.0.tgz#e1daccbe78d0d1388ca18c64fea38e3e57e3706b" @@ -1083,11 +1061,6 @@ pdfjs-dist@^2.2.228: node-ensure "^0.0.0" worker-loader "^2.0.0" -performance-now@^2.1.0: - version "2.1.0" - resolved "https://registry.yarnpkg.com/performance-now/-/performance-now-2.1.0.tgz#6309f4e0e5fa913ec1c69307ae364b4b377c9e7b" - integrity sha1-Ywn04OX6kT7BxpMHrjZLSzd8nns= - picomatch@^2.0.4, picomatch@^2.2.1: version "2.3.1" resolved "https://registry.yarnpkg.com/picomatch/-/picomatch-2.3.1.tgz#3ba3833733646d9d3e4995946c1365a67fb07a42" @@ -1098,15 +1071,13 @@ ps-list@^7.0.0: resolved "https://registry.yarnpkg.com/ps-list/-/ps-list-7.2.0.tgz#3d110e1de8249a4b178c9b1cf2a215d1e4e42fc0" integrity sha512-v4Bl6I3f2kJfr5o80ShABNHAokIgY+wFDTQfE+X3zWYgSGQOCBeYptLZUpoOALBqO5EawmDN/tjTldJesd0ujQ== -psl@^1.1.24: - version "1.9.0" - resolved "https://registry.yarnpkg.com/psl/-/psl-1.9.0.tgz#d0df2a137f00794565fcaf3b2c00cd09f8d5a5a7" - integrity sha512-E/ZsdU4HLs/68gYzgGTkMicWTLPdAftJLfJFlLUAAKZGkStNU72sZjT66SnMDVOfOWY/YAoiD7Jxa9iHvngcag== - -punycode@^1.4.1: - version "1.4.1" - resolved "https://registry.yarnpkg.com/punycode/-/punycode-1.4.1.tgz#c0d5a63b2718800ad8e1eb0fa5269c84dd41845e" - integrity sha512-jmYNElW7yvO7TV33CjSmvSiE2yco3bV2czu/OzDKdMNVZQWfxCblURLhf+47syQRBntjfLdd/H0egrzIG+oaFQ== +pump@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/pump/-/pump-3.0.0.tgz#b4a2116815bde2f4e1ea602354e8c75565107a64" + integrity sha512-LwZy+p3SFs1Pytd/jYct4wpv49HiYCqd9Rlc5ZVdk0V+8Yzv6jR5Blk3TRmPL1ft69TxP0IMZGJ+WPFU2BFhww== + dependencies: + end-of-stream "^1.1.0" + once "^1.3.1" punycode@^2.1.0: version "2.1.1" @@ -1118,10 +1089,10 @@ q@^1.5.1: resolved "https://registry.yarnpkg.com/q/-/q-1.5.1.tgz#7e32f75b41381291d04611f1bf14109ac00651d7" integrity sha1-fjL3W0E4EpHQRhHxvxQQmsAGUdc= -qs@~6.5.2: - version "6.5.3" - resolved "https://registry.yarnpkg.com/qs/-/qs-6.5.3.tgz#3aeeffc91967ef6e35c0e488ef46fb296ab76aad" - integrity sha512-qxXIEh4pCGfHICj1mAJQ2/2XVZkjCDTcEgfoSQxc/fYivUZxTkk7L3bDBJSoNrEzXI17oUO5Dp07ktqE5KzczA== +quick-lru@^5.1.1: + version "5.1.1" + resolved "https://registry.yarnpkg.com/quick-lru/-/quick-lru-5.1.1.tgz#366493e6b3e42a3a6885e2e99d18f80fb7a8c932" + integrity sha512-WuyALRjWPDGtt/wzJiadO5AXY+8hZ80hVpe6MyivgraREW751X3SbhRvG3eLKOYN+8VEvqLcf3wdnt44Z4S4SA== randombytes@^2.1.0: version "2.1.0" @@ -1142,45 +1113,23 @@ readdirp@~3.6.0: dependencies: picomatch "^2.2.1" -request-json@^0.6.4: - version "0.6.5" - resolved "https://registry.yarnpkg.com/request-json/-/request-json-0.6.5.tgz#dda8c08245aca950f5f7842ae68495fd23df0ecb" - integrity sha512-bpJ0MZPeb3+/8ux/jM+CLRghTOQ8Oh2VuqtnrPu9ZnSIjr/77sOj/rSWfK9cPRpp3U0UWAIv7rsRvSlyRwbmsw== - dependencies: - depd "1.1.2" - request "2.88.0" - [email protected]: - version "2.88.0" - resolved "https://registry.yarnpkg.com/request/-/request-2.88.0.tgz#9c2fca4f7d35b592efe57c7f0a55e81052124fef" - integrity sha512-NAqBSrijGLZdM0WZNsInLJpkJokL72XYjUpnB0iwsRgxh7dB6COrHnTBNwN0E+lHDAJzu7kLAkDeY08z2/A0hg== - dependencies: - aws-sign2 "~0.7.0" - aws4 "^1.8.0" - caseless "~0.12.0" - combined-stream "~1.0.6" - extend "~3.0.2" - forever-agent "~0.6.1" - form-data "~2.3.2" - har-validator "~5.1.0" - http-signature "~1.2.0" - is-typedarray "~1.0.0" - isstream "~0.1.2" - json-stringify-safe "~5.0.1" - mime-types "~2.1.19" - oauth-sign "~0.9.0" - performance-now "^2.1.0" - qs "~6.5.2" - safe-buffer "^5.1.2" - tough-cookie "~2.4.3" - tunnel-agent "^0.6.0" - uuid "^3.3.2" - require-directory@^2.1.1: version "2.1.1" resolved "https://registry.yarnpkg.com/require-directory/-/require-directory-2.1.1.tgz#8c64ad5fd30dab1c976e2344ffe7f792a6a6df42" integrity sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q== +resolve-alpn@^1.0.0: + version "1.2.1" + resolved "https://registry.yarnpkg.com/resolve-alpn/-/resolve-alpn-1.2.1.tgz#b7adbdac3546aaaec20b45e7d8265927072726f9" + integrity sha512-0a1F4l73/ZFZOakJnQ3FvkJ2+gSTQWz/r2KE5OdDY0TxPm5h4GkqkWWfM47T7HsbnOtcJVEF4epCVy6u7Q3K+g== + +responselike@^2.0.0: + version "2.0.1" + resolved "https://registry.yarnpkg.com/responselike/-/responselike-2.0.1.tgz#9a0bc8fdc252f3fb1cca68b016591059ba1422bc" + integrity sha512-4gl03wn3hj1HP3yzgdI7d3lCkF95F21Pz4BPGvKHinyQzALR5CapwC8yIi0Rh58DEMQ/SguC03wFj2k0M/mHhw== + dependencies: + lowercase-keys "^2.0.0" + rimraf@~2.6.2: version "2.6.3" resolved "https://registry.yarnpkg.com/rimraf/-/rimraf-2.6.3.tgz#b2d104fe0d8fb27cf9e0a1cda8262dd3833c6cab" @@ -1193,16 +1142,11 @@ [email protected]: resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.1.2.tgz#991ec69d296e0313747d59bdfd2b745c35f8828d" integrity sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g== -safe-buffer@^5.0.1, safe-buffer@^5.1.0, safe-buffer@^5.1.1, safe-buffer@^5.1.2: +safe-buffer@^5.1.0, safe-buffer@^5.1.1: version "5.2.1" resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.2.1.tgz#1eaf9fa9bdb1fdd4ec75f58f9cdb4e6b7827eec6" integrity sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ== -safer-buffer@^2.0.2, safer-buffer@^2.1.0, safer-buffer@~2.1.0: - version "2.1.2" - resolved "https://registry.yarnpkg.com/safer-buffer/-/safer-buffer-2.1.2.tgz#44fa161b0187b9549dd84bb91802f9bd8385cd6a" - integrity sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg== - sax@>=0.6.0: version "1.2.4" resolved "https://registry.yarnpkg.com/sax/-/sax-1.2.4.tgz#2816234e2378bddc4e5354fab5caa895df7100d9" @@ -1267,21 +1211,6 @@ split@^1.0.1: dependencies: through "2" -sshpk@^1.7.0: - version "1.17.0" - resolved "https://registry.yarnpkg.com/sshpk/-/sshpk-1.17.0.tgz#578082d92d4fe612b13007496e543fa0fbcbe4c5" - integrity sha512-/9HIEs1ZXGhSPE8X6Ccm7Nam1z8KcoCqPdI7ecm1N33EzAetWahvQWVqLZtaZQ+IDKX4IyA2o0gBzqIMkAagHQ== - dependencies: - asn1 "~0.2.3" - assert-plus "^1.0.0" - bcrypt-pbkdf "^1.0.0" - dashdash "^1.12.0" - ecc-jsbn "~0.1.1" - getpass "^0.1.1" - jsbn "~0.1.0" - safer-buffer "^2.0.2" - tweetnacl "~0.14.0" - "statuses@>= 1.4.0 < 2": version "1.5.0" resolved "https://registry.yarnpkg.com/statuses/-/statuses-1.5.0.tgz#161c7dac177659fd9811f43771fa99381478628c" @@ -1367,26 +1296,6 @@ to-regex-range@^5.0.1: dependencies: is-number "^7.0.0" -tough-cookie@~2.4.3: - version "2.4.3" - resolved "https://registry.yarnpkg.com/tough-cookie/-/tough-cookie-2.4.3.tgz#53f36da3f47783b0925afa06ff9f3b165280f781" - integrity sha512-Q5srk/4vDM54WJsJio3XNn6K2sCG+CQ8G5Wz6bZhRZoAe/+TxjWB/GlFAnYEbkYVlON9FMk/fE3h2RLpPXo4lQ== - dependencies: - psl "^1.1.24" - punycode "^1.4.1" - -tunnel-agent@^0.6.0: - version "0.6.0" - resolved "https://registry.yarnpkg.com/tunnel-agent/-/tunnel-agent-0.6.0.tgz#27a5dea06b36b04a0a9966774b290868f0fc40fd" - integrity sha1-J6XeoGs2sEoKmWZ3SykIaPD8QP0= - dependencies: - safe-buffer "^5.0.1" - -tweetnacl@^0.14.3, tweetnacl@~0.14.0: - version "0.14.5" - resolved "https://registry.yarnpkg.com/tweetnacl/-/tweetnacl-0.14.5.tgz#5ae68177f192d4456269d108afa93ff8743f4f64" - integrity sha1-WuaBd/GS1EViadEIr6k/+HQ/T2Q= - [email protected], type-detect@^4.0.0, type-detect@^4.0.5, type-detect@^4.0.8: version "4.0.8" resolved "https://registry.yarnpkg.com/type-detect/-/type-detect-4.0.8.tgz#7646fb5f18871cfbb7749e69bd39a6388eb7450c" @@ -1399,20 +1308,11 @@ uri-js@^4.2.2: dependencies: punycode "^2.1.0" -uuid@^3.3.2, uuid@^3.3.3: +uuid@^3.3.3: version "3.4.0" resolved "https://registry.yarnpkg.com/uuid/-/uuid-3.4.0.tgz#b23e4358afa8a202fe7a100af1f5f883f02007ee" integrity sha512-HjSDRw6gZE5JMggctHBcjVak08+KEVhSIiDzFnT9S9aegmp85S/bReBVTb4QTFaRNptJ9kuYaNhnbNEOkbKb/A== [email protected]: - version "1.10.0" - resolved "https://registry.yarnpkg.com/verror/-/verror-1.10.0.tgz#3a105ca17053af55d6e270c1f8288682e18da400" - integrity sha1-OhBcoXBTr1XW4nDB+CiGguGNpAA= - dependencies: - assert-plus "^1.0.0" - core-util-is "1.0.2" - extsprintf "^1.2.0" - walkdir@^0.3.2: version "0.3.2" resolved "https://registry.yarnpkg.com/walkdir/-/walkdir-0.3.2.tgz#ac8437a288c295656848ebc19981ebc677a5f590"
build
62d4b21819ecee4f634731f7aad80da8abf2801e
Shelley Vohr
2024-03-28 22:37:14
test: disable flaky `<webview>.capturePage()` specs (#41713) test: disable flaky <webview>.capturePage() specs
diff --git a/spec/webview-spec.ts b/spec/webview-spec.ts index 81410162a6..fb3be78041 100644 --- a/spec/webview-spec.ts +++ b/spec/webview-spec.ts @@ -14,8 +14,6 @@ import { HexColors, ScreenCapture } from './lib/screen-helpers'; declare let WebView: any; const features = process._linkedBinding('electron_common_features'); -const isMacArm64 = (process.platform === 'darwin' && process.arch === 'arm64'); - async function loadWebView (w: WebContents, attributes: Record<string, string>, opts?: {openDevTools?: boolean}): Promise<void> { const { openDevTools } = { openDevTools: false, @@ -2107,9 +2105,8 @@ describe('<webview> tag', function () { } }); - // TODO(miniak): figure out why this is failing on windows - // TODO(vertedinde): figure out why this is failing on mac arm64 - ifdescribe(process.platform !== 'win32' && !isMacArm64)('<webview>.capturePage()', () => { + // FIXME: This test is flaking constantly on Linux and macOS. + xdescribe('<webview>.capturePage()', () => { it('returns a Promise with a NativeImage', async function () { this.retries(5);
test
ff4494c18fff3fbe01a52373f97172636308cf7d
Shelley Vohr
2024-06-10 11:55:16
build: allow kicking build with `workflow_dispatch` (#42420) * build: allow kicking build with workflow_dispatch * build: ensure macOS build works * fix: no upload in build * build: add target_cpu to MAS config --------- Co-authored-by: Keeley Hammond <[email protected]>
diff --git a/.github/workflows/config/testing/x64/evm.mas.json b/.github/workflows/config/testing/x64/evm.mas.json index 4d2ae3b327..bdc3a60ca0 100644 --- a/.github/workflows/config/testing/x64/evm.mas.json +++ b/.github/workflows/config/testing/x64/evm.mas.json @@ -9,6 +9,7 @@ "args": [ "import(\"//electron/build/args/testing.gn\")", "use_remoteexec = true", + "target_cpu = \"x64\"", "is_mas_build = true" ], "out": "Default" diff --git a/.github/workflows/macos-build.yml b/.github/workflows/macos-build.yml index 5df6fcf7a0..b1c058df22 100644 --- a/.github/workflows/macos-build.yml +++ b/.github/workflows/macos-build.yml @@ -1,765 +1,18 @@ name: Build MacOS -# TODO: change to 'pull_request' and 'push' -# when we are ready to enable this for PRs. on: - workflow_call: - inputs: - IS_RELEASE: - required: true - type: boolean - default: false - GN_CONFIG: - required: false - type: string - default: //electron/build/args/testing.gn - GN_BUILD_TYPE: - required: false - type: string - default: release - GENERATE_SYMBOLS: - required: false - type: boolean - default: false - UPLOAD_TO_STORAGE: - required: false - type: string - default: '0' - -concurrency: - group: ${{ github.workflow }}-${{ github.ref }} - cancel-in-progress: true - -env: - AZURE_STORAGE_ACCOUNT: ${{ secrets.AZURE_STORAGE_ACCOUNT }} - AZURE_STORAGE_KEY: ${{ secrets.AZURE_STORAGE_KEY }} - AZURE_STORAGE_CONTAINER_NAME: ${{ secrets.AZURE_STORAGE_CONTAINER_NAME }} - ELECTRON_ARTIFACTS_BLOB_STORAGE: ${{ secrets.ELECTRON_ARTIFACTS_BLOB_STORAGE }} - ELECTRON_RBE_JWT: ${{ secrets.ELECTRON_RBE_JWT }} - ELECTRON_GITHUB_TOKEN: ${{ secrets.ELECTRON_GITHUB_TOKEN }} - GN_CONFIG: ${{ inputs.GN_CONFIG }} - # Disable pre-compiled headers to reduce out size - only useful for rebuilds - GN_BUILDFLAG_ARGS: 'enable_precompiled_headers = false' - GCLIENT_EXTRA_ARGS: '--custom-var=checkout_mac=True --custom-var=host_os=mac' - CHECK_DIST_MANIFEST: '1' - IS_GHA_RELEASE: true - ELECTRON_OUT_DIR: Default + workflow_dispatch: + # push + # pull_request: jobs: - checkout: - runs-on: LargeLinuxRunner - steps: - - name: Checkout Electron - uses: actions/checkout@a5ac7e51b41094c92402da3b24376905380afc29 - with: - path: src/electron - fetch-depth: 0 - - name: Set GIT_CACHE_PATH to make gclient to use the cache - run: | - echo "GIT_CACHE_PATH=$(pwd)/git-cache" >> $GITHUB_ENV - - name: Setup Node.js/npm - uses: actions/setup-node@60edb5dd545a775178f52524783378180af0d1f8 - with: - node-version: 20.11.x - cache: yarn - cache-dependency-path: src/electron/yarn.lock - - name: Install Dependencies - run: | - cd src/electron - node script/yarn install - - name: Get Depot Tools - timeout-minutes: 5 - run: | - git clone --depth=1 https://chromium.googlesource.com/chromium/tools/depot_tools.git - if [ "`uname`" == "Darwin" ]; then - # remove ninjalog_uploader_wrapper.py from autoninja since we don't use it and it causes problems - sed -i '' '/ninjalog_uploader_wrapper.py/d' ./depot_tools/autoninja - else - sed -i '/ninjalog_uploader_wrapper.py/d' ./depot_tools/autoninja - # Remove swift-format dep from cipd on macOS until we send a patch upstream. - cd depot_tools - git apply --3way ../src/electron/.github/workflows/config/gclient.diff - fi - # Ensure depot_tools does not update. - test -d depot_tools && cd depot_tools - touch .disable_auto_update - - name: Add Depot Tools to PATH - run: echo "$(pwd)/depot_tools" >> $GITHUB_PATH - - name: Generate DEPS Hash - run: | - node src/electron/script/generate-deps-hash.js && cat src/electron/.depshash-target - echo "DEPSHASH=v1-src-cache-$(shasum src/electron/.depshash | cut -f1 -d' ')" >> $GITHUB_ENV - - name: Check If Cache Exists - id: check-cache - run: | - exists_json=$(az storage blob exists \ - --account-name $AZURE_STORAGE_ACCOUNT \ - --account-key $AZURE_STORAGE_KEY \ - --container-name $AZURE_STORAGE_CONTAINER_NAME \ - --name $DEPSHASH) - - cache_exists=$(echo $exists_json | jq -r '.exists') - echo "cache_exists=$cache_exists" >> $GITHUB_OUTPUT - - if (test "$cache_exists" = "true"); then - echo "Cache Exists for $DEPSHASH" - else - echo "Cache Does Not Exist for $DEPSHASH" - fi - - name: Gclient Sync - # If there is no existing src cache, we need to do a full gclient sync. - # TODO(codebytere): Add stale patch handling for non-release builds. - if: steps.check-cache.outputs.cache_exists == 'false' - run: | - gclient config \ - --name "src/electron" \ - --unmanaged \ - ${GCLIENT_EXTRA_ARGS} \ - "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY" - - ELECTRON_USE_THREE_WAY_MERGE_FOR_PATCHES=1 gclient sync --with_branch_heads --with_tags -vvvvv - if [ ${{ inputs.IS_RELEASE }} != "true" ]; then - # Re-export all the patches to check if there were changes. - python3 src/electron/script/export_all_patches.py src/electron/patches/config.json - cd src/electron - git update-index --refresh || true - if ! git diff-index --quiet HEAD --; then - # There are changes to the patches. Make a git commit with the updated patches - git add patches - GIT_COMMITTER_NAME="PatchUp" GIT_COMMITTER_EMAIL="73610968+patchup[bot]@users.noreply.github.com" git commit -m "chore: update patches" --author="PatchUp <73610968+patchup[bot]@users.noreply.github.com>" - # Export it - mkdir -p ../../patches - git format-patch -1 --stdout --keep-subject --no-stat --full-index > ../../patches/update-patches.patch - if (node ./script/push-patch.js 2> /dev/null > /dev/null); then - echo - echo "======================================================================" - echo "Changes to the patches when applying, we have auto-pushed the diff to the current branch" - echo "A new CI job will kick off shortly" - echo "======================================================================" - exit 1 - else - echo - echo "======================================================================" - echo "There were changes to the patches when applying." - echo "Check the CI artifacts for a patch you can apply to fix it." - echo "======================================================================" - exit 1 - fi - fi - fi - - # delete all .git directories under src/ except for - # third_party/angle/ and third_party/dawn/ because of build time generation of files - # gen/angle/commit.h depends on third_party/angle/.git/HEAD - # https://chromium-review.googlesource.com/c/angle/angle/+/2074924 - # and dawn/common/Version_autogen.h depends on third_party/dawn/.git/HEAD - # https://dawn-review.googlesource.com/c/dawn/+/83901 - # TODO: maybe better to always leave out */.git/HEAD file for all targets ? - - name: Delete .git directories under src to free space - if: steps.check-cache.outputs.cache_exists == 'false' - run: | - cd src - ( find . -type d -name ".git" -not -path "./third_party/angle/*" -not -path "./third_party/dawn/*" -not -path "./electron/*" ) | xargs rm -rf - - name: Minimize Cache Size for Upload - if: steps.check-cache.outputs.cache_exists == 'false' - run: | - rm -rf src/android_webview - rm -rf src/ios/chrome - rm -rf src/third_party/blink/web_tests - rm -rf src/third_party/blink/perf_tests - rm -rf src/chrome/test/data/xr/webvr_info - rm -rf src/third_party/angle/third_party/VK-GL-CTS/src - rm -rf src/third_party/swift-toolchain - rm -rf src/third_party/swiftshader/tests/regres/testlists - rm -rf src/electron - - name: Compress Src Directory - if: steps.check-cache.outputs.cache_exists == 'false' - run: | - echo "Uncompressed src size: $(du -sh src | cut -f1 -d' ')" - tar -cvf $DEPSHASH.tar src - echo "Compressed src to $(du -sh $DEPSHASH.tar | cut -f1 -d' ')" - - name: Upload Compressed Src Cache to Azure - if: steps.check-cache.outputs.cache_exists == 'false' - run: | - az storage blob upload \ - --account-name $AZURE_STORAGE_ACCOUNT \ - --account-key $AZURE_STORAGE_KEY \ - --container-name $AZURE_STORAGE_CONTAINER_NAME \ - --file $DEPSHASH.tar \ - --name $DEPSHASH \ - --debug build: - strategy: - fail-fast: false - matrix: - build-arch: [ arm64, x64 ] - # macos-large is x64, macos-xlarge is arm64 - # More runner information: https://github.com/actions/runner-images/blob/main/README.md#available-images - runs-on: macos-14-xlarge - needs: checkout - steps: - - name: Load Build Tools - run: | - export BUILD_TOOLS_SHA=2bb63e2e7877491b52f972532b52adc979a6ec2f - npm i -g @electron/build-tools - e init --root=$(pwd) --out=Default ${{ inputs.GN_BUILD_TYPE }} --import ${{ inputs.GN_BUILD_TYPE }} --target-cpu ${{ matrix.build-arch}} - e use ${{ inputs.GN_BUILD_TYPE }} - - name: Checkout Electron - uses: actions/checkout@a5ac7e51b41094c92402da3b24376905380afc29 - with: - path: src/electron - fetch-depth: 0 - - name: Setup Node.js/npm - uses: actions/setup-node@60edb5dd545a775178f52524783378180af0d1f8 - with: - node-version: 20.11.x - cache: yarn - cache-dependency-path: src/electron/yarn.lock - - name: Install Dependencies - run: | - cd src/electron - node script/yarn install - - name: Load Target Arch & CPU - run: | - echo "TARGET_ARCH=${{ matrix.build-arch }}" >> $GITHUB_ENV - echo "target_cpu=${{ matrix.build-arch }}" >> $GITHUB_ENV - echo "host_cpu=${{ matrix.build-arch }}" >> $GITHUB_ENV - - name: Get Depot Tools - timeout-minutes: 5 - run: | - git clone --depth=1 https://chromium.googlesource.com/chromium/tools/depot_tools.git - if [ "`uname`" == "Darwin" ]; then - # remove ninjalog_uploader_wrapper.py from autoninja since we don't use it and it causes problems - sed -i '' '/ninjalog_uploader_wrapper.py/d' ./depot_tools/autoninja - else - sed -i '/ninjalog_uploader_wrapper.py/d' ./depot_tools/autoninja - # Remove swift-format dep from cipd on macOS until we send a patch upstream. - cd depot_tools - git apply --3way ../src/electron/.github/workflows/config/gclient.diff - fi - # Ensure depot_tools does not update. - test -d depot_tools && cd depot_tools - touch .disable_auto_update - - name: Add Depot Tools to PATH - run: echo "$(pwd)/depot_tools" >> $GITHUB_PATH - - name: Generate DEPS Hash - run: | - node src/electron/script/generate-deps-hash.js && cat src/electron/.depshash-target - echo "DEPSHASH=v1-src-cache-$(shasum src/electron/.depshash | cut -f1 -d' ')" >> $GITHUB_ENV - - name: Download Src Cache - # The cache will always exist here as a result of the checkout job - # Either it was uploaded to Azure in the checkout job for this commit - # or it was uploaded in the checkout job for a previous commit. - uses: nick-fields/retry@7152eba30c6575329ac0576536151aca5a72780e # v3.0.0 - with: - timeout_minutes: 20 - max_attempts: 3 - retry_on: error - command: | - az storage blob download \ - --account-name $AZURE_STORAGE_ACCOUNT \ - --account-key $AZURE_STORAGE_KEY \ - --container-name $AZURE_STORAGE_CONTAINER_NAME \ - --name $DEPSHASH \ - --file $DEPSHASH.tar \ - - name: Unzip and Ensure Src Cache - run: | - echo "Downloaded cache is $(du -sh $DEPSHASH.tar | cut -f1)" - mkdir temp-cache - tar -xvf $DEPSHASH.tar -C temp-cache - echo "Unzipped cache is $(du -sh temp-cache/src | cut -f1)" - - if [ -d "temp-cache/src" ]; then - echo "Relocating Cache" - rm -rf src - mv temp-cache/src src - - echo "Deleting zip file" - rm -rf $DEPSHASH.tar - fi - - if [ ! -d "src/third_party/blink" ]; then - echo "Cache was not correctly restored - exiting" - exit 1 - fi - - echo "Wiping Electron Directory" - rm -rf src/electron - - name: Checkout Electron - uses: actions/checkout@a5ac7e51b41094c92402da3b24376905380afc29 - with: - path: src/electron - fetch-depth: 0 - - name: Run Electron Only Hooks - run: | - echo "Running Electron Only Hooks" - gclient runhooks --spec="solutions=[{'name':'src/electron','url':None,'deps_file':'DEPS','custom_vars':{'process_deps':False},'managed':False}]" - - name: Regenerate DEPS Hash - run: | - (cd src/electron && git checkout .) && node src/electron/script/generate-deps-hash.js && cat src/electron/.depshash-target - echo "DEPSHASH=$(shasum src/electron/.depshash | cut -f1 -d' ')" >> $GITHUB_ENV - - name: Add CHROMIUM_BUILDTOOLS_PATH to env - run: echo "CHROMIUM_BUILDTOOLS_PATH=$(pwd)/src/buildtools" >> $GITHUB_ENV - - name: Fix Sync - # This step is required to correct for differences between "gclient sync" - # on Linux and the expected state on macOS. This requires: - # 1. Fixing Clang Install (wrong binary) - # 2. Fixing esbuild (wrong binary) - # 3. Fixing rustc (wrong binary) - # 4. Fixing gn (wrong binary) - # 5. Fix reclient (wrong binary) - # 6. Fixing dsymutil (wrong binary) - # 7. Ensuring we are using the correct ninja and adding it to PATH - # 8. Fixing angle (wrong remote) - run : | - SEDOPTION="-i ''" - rm -rf src/third_party/llvm-build - python3 src/tools/clang/scripts/update.py - - echo 'infra/3pp/tools/esbuild/${platform}' `gclient getdep --deps-file=src/third_party/devtools-frontend/src/DEPS -r 'third_party/esbuild:infra/3pp/tools/esbuild/${platform}'` > esbuild_ensure_file - # Remove extra output from calling gclient getdep which always calls update_depot_tools - sed -i '' "s/Updating depot_tools... //g" esbuild_ensure_file - cipd ensure --root src/third_party/devtools-frontend/src/third_party/esbuild -ensure-file esbuild_ensure_file - - rm -rf src/third_party/rust-toolchain - python3 src/tools/rust/update_rust.py - - # Prevent calling gclient getdep which always calls update_depot_tools - echo 'gn/gn/mac-${arch}' `gclient getdep --deps-file=src/DEPS -r 'src/buildtools/mac:gn/gn/mac-${arch}'` > gn_ensure_file - sed -i '' "s/Updating depot_tools... //g" gn_ensure_file - cipd ensure --root src/buildtools/mac -ensure-file gn_ensure_file - - # Prevent calling gclient getdep which always calls update_depot_tools - echo 'infra/rbe/client/${platform}' `gclient getdep --deps-file=src/DEPS -r 'src/buildtools/reclient:infra/rbe/client/${platform}'` > gn_ensure_file - sed -i '' "s/Updating depot_tools... //g" gn_ensure_file - cipd ensure --root src/buildtools/reclient -ensure-file gn_ensure_file - python3 src/buildtools/reclient_cfgs/configure_reclient_cfgs.py --rbe_instance "projects/rbe-chrome-untrusted/instances/default_instance" --reproxy_cfg_template reproxy.cfg.template --rewrapper_cfg_project "" --skip_remoteexec_cfg_fetch - - if [ "$TARGET_ARCH" == "arm64" ]; then - DSYM_SHA_FILE=src/tools/clang/dsymutil/bin/dsymutil.arm64.sha1 - else - DSYM_SHA_FILE=src/tools/clang/dsymutil/bin/dsymutil.x64.sha1 - fi - python3 src/third_party/depot_tools/download_from_google_storage.py --no_resume --no_auth --bucket chromium-browser-clang -s $DSYM_SHA_FILE -o src/tools/clang/dsymutil/bin/dsymutil - - echo 'infra/3pp/tools/ninja/${platform}' `gclient getdep --deps-file=src/DEPS -r 'src/third_party/ninja:infra/3pp/tools/ninja/${platform}'` > ninja_ensure_file - sed $SEDOPTION "s/Updating depot_tools... //g" ninja_ensure_file - cipd ensure --root src/third_party/ninja -ensure-file ninja_ensure_file - - echo "$(pwd)/src/third_party/ninja" >> $GITHUB_PATH - - cd src/third_party/angle - rm -f .git/objects/info/alternates - git remote set-url origin https://chromium.googlesource.com/angle/angle.git - cp .git/config .git/config.backup - git remote remove origin - mv .git/config.backup .git/config - git fetch - - name: Install build-tools & Setup RBE - run: | - echo "NUMBER_OF_NINJA_PROCESSES=200" >> $GITHUB_ENV - cd ~/.electron_build_tools - npx yarn --ignore-engines - # Pull down credential helper and print status - node -e "require('./src/utils/reclient.js').downloadAndPrepare({})" - HELPER=$(node -p "require('./src/utils/reclient.js').helperPath({})") - $HELPER login - echo 'RBE_service='`node -e "console.log(require('./src/utils/reclient.js').serviceAddress)"` >> $GITHUB_ENV - echo 'RBE_experimental_credentials_helper='`node -e "console.log(require('./src/utils/reclient.js').helperPath({}))"` >> $GITHUB_ENV - echo 'RBE_experimental_credentials_helper_args=print' >> $GITHUB_ENV - - name: Free Space on MacOS - run: | - sudo mkdir -p $TMPDIR/del-target - - tmpify() { - if [ -d "$1" ]; then - sudo mv "$1" $TMPDIR/del-target/$(echo $1|shasum -a 256|head -n1|cut -d " " -f1) - fi - } - - strip_universal_deep() { - opwd=$(pwd) - cd $1 - f=$(find . -perm +111 -type f) - for fp in $f - do - if [[ $(file "$fp") == *"universal binary"* ]]; then - if [ "`arch`" == "arm64" ]; then - if [[ $(file "$fp") == *"x86_64"* ]]; then - sudo lipo -remove x86_64 "$fp" -o "$fp" || true - fi - else - if [[ $(file "$fp") == *"arm64e)"* ]]; then - sudo lipo -remove arm64e "$fp" -o "$fp" || true - fi - if [[ $(file "$fp") == *"arm64)"* ]]; then - sudo lipo -remove arm64 "$fp" -o "$fp" || true - fi - fi - fi - done - - cd $opwd - } - - tmpify /Library/Developer/CoreSimulator - tmpify ~/Library/Developer/CoreSimulator - tmpify $(xcode-select -p)/Platforms/AppleTVOS.platform - tmpify $(xcode-select -p)/Platforms/iPhoneOS.platform - tmpify $(xcode-select -p)/Platforms/WatchOS.platform - tmpify $(xcode-select -p)/Platforms/WatchSimulator.platform - tmpify $(xcode-select -p)/Platforms/AppleTVSimulator.platform - tmpify $(xcode-select -p)/Platforms/iPhoneSimulator.platform - tmpify $(xcode-select -p)/Toolchains/XcodeDefault.xctoolchain/usr/metal/ios - tmpify $(xcode-select -p)/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift - tmpify $(xcode-select -p)/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift-5.0 - tmpify ~/.rubies - tmpify ~/Library/Caches/Homebrew - tmpify /usr/local/Homebrew - - # the contents of build/linux/strip_binary.gni aren't used, but - # https://chromium-review.googlesource.com/c/chromium/src/+/4278307 - # needs the file to exist. - # mv ~/project/src/build/linux/strip_binary.gni "${TMPDIR}"/ - # tmpify ~/project/src/build/linux/ - # mkdir -p ~/project/src/build/linux - # mv "${TMPDIR}/strip_binary.gni" ~/project/src/build/linux/ - - sudo rm -rf $TMPDIR/del-target - - # sudo rm -rf "/System/Library/Desktop Pictures" - # sudo rm -rf /System/Library/Templates/Data - # sudo rm -rf /System/Library/Speech/Voices - # sudo rm -rf "/System/Library/Screen Savers" - # sudo rm -rf /System/Volumes/Data/Library/Developer/CommandLineTools/SDKs - # sudo rm -rf "/System/Volumes/Data/Library/Application Support/Apple/Photos/Print Products" - # sudo rm -rf /System/Volumes/Data/Library/Developer/CommandLineTools/SDKs/MacOSX10.15.sdk/ - # sudo rm -rf /System/Volumes/Data/Library/Java - # sudo rm -rf /System/Volumes/Data/Library/Ruby - # sudo rm -rf /System/Volumes/Data/Library/Printers - # sudo rm -rf /System/iOSSupport - # sudo rm -rf /System/Applications/*.app - # sudo rm -rf /System/Applications/Utilities/*.app - # sudo rm -rf /System/Library/LinguisticData - # sudo rm -rf /System/Volumes/Data/private/var/db/dyld/* - # sudo rm -rf /System/Library/Fonts/* - # sudo rm -rf /System/Library/PreferencePanes - # sudo rm -rf /System/Library/AssetsV2/* - sudo rm -rf /Applications/Safari.app - sudo rm -rf ~/project/src/third_party/catapult/tracing/test_data - sudo rm -rf ~/project/src/third_party/angle/third_party/VK-GL-CTS - - # lipo off some huge binaries arm64 versions to save space - strip_universal_deep $(xcode-select -p)/../SharedFrameworks - # strip_arm_deep /System/Volumes/Data/Library/Developer/CommandLineTools/usr - - name: Build Electron (darwin) - run: | - cd src/electron - # TODO(codebytere): remove this once we figure out why .git/packed-refs is initially missing - git pack-refs - cd .. - ulimit -n 10000 - sudo launchctl limit maxfiles 65536 200000 - - NINJA_SUMMARIZE_BUILD=1 e build -j $NUMBER_OF_NINJA_PROCESSES - cp out/Default/.ninja_log out/electron_ninja_log - node electron/script/check-symlinks.js - - name: Build Electron dist.zip (darwin) - run: | - cd src - e build electron:electron_dist_zip -j $NUMBER_OF_NINJA_PROCESSES - if [ "$CHECK_DIST_MANIFEST" == "1" ]; then - target_os=mac - electron/script/zip_manifests/check-zip-manifest.py out/Default/dist.zip electron/script/zip_manifests/dist_zip.$target_os.${{ env.TARGET_ARCH }}.manifest - fi - - name: Build Mksnapshot (darwin) - run: | - cd src - e build electron:electron_mksnapshot -j $NUMBER_OF_NINJA_PROCESSES - gn desc out/Default v8:run_mksnapshot_default args > out/Default/mksnapshot_args - # Remove unused args from mksnapshot_args - SEDOPTION="-i ''" - sed $SEDOPTION '/.*builtins-pgo/d' out/Default/mksnapshot_args - sed $SEDOPTION '/--turbo-profiling-input/d' out/Default/mksnapshot_args - sed $SEDOPTION '/The gn arg use_goma=true .*/d' out/Default/mksnapshot_args - e build electron:electron_mksnapshot_zip -j $NUMBER_OF_NINJA_PROCESSES - (cd out/Default; zip mksnapshot.zip mksnapshot_args gen/v8/embedded.S) - - name: Build Chromedriver (darwin) - run: | - cd src - e build electron:electron_chromedriver -j $NUMBER_OF_NINJA_PROCESSES - e build electron:electron_chromedriver_zip - # NOTE (vertedinde): We strip binaries/symbols on the Linux job, not the Mac job - - name: Generate & Zip Symbols (darwin) - run: | - # Generate breakpad symbols on release builds - if [ ${{ inputs.GENERATE_SYMBOLS }} == "true" ]; then - e build electron:electron_symbols - fi - cd src - export BUILD_PATH="$(pwd)/out/Default" - e build electron:licenses - e build electron:electron_version_file - if [ ${{ inputs.IS_RELEASE }} == "true" ]; then - DELETE_DSYMS_AFTER_ZIP=1 electron/script/zip-symbols.py -b $BUILD_PATH - else - electron/script/zip-symbols.py -b $BUILD_PATH - fi - - name: Generate FFMpeg - if: ${{ inputs.IS_RELEASE == true }} - run: | - cd src - gn gen out/ffmpeg --args="import(\"//electron/build/args/ffmpeg.gn\") use_remoteexec=true $GN_EXTRA_ARGS" - autoninja -C out/ffmpeg electron:electron_ffmpeg_zip -j $NUMBER_OF_NINJA_PROCESSES - - name: Generate Hunspell Dictionaries - if: ${{ inputs.IS_RELEASE == true }} - run: | - cd src - autoninja -C out/Default electron:hunspell_dictionaries_zip -j $NUMBER_OF_NINJA_PROCESSES - - name: Generate TypeScript Definitions - if: ${{ inputs.IS_RELEASE == true }} - run: | - cd src/electron - node script/yarn create-typescript-definitions - # TODO(vertedinde): These uploads currently point to a different Azure bucket & GitHub Repo - - name: Publish Electron Dist - run: | - rm -rf src/out/Default/obj - cd src/electron - if [ ${{ inputs.UPLOAD_TO_STORAGE }} == "1" ]; then - echo 'Uploading Electron release distribution to Azure' - script/release/uploaders/upload.py --verbose --upload_to_storage - else - echo 'Uploading Electron release distribution to GitHub releases' - script/release/uploaders/upload.py --verbose - fi - # 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 - run: ./src/electron/script/actions/move-artifacts.sh - - name: Upload Generated Artifacts - uses: actions/upload-artifact@65462800fd760344b1a7b4382951275a0abb4808 - with: - name: generated_artifacts_darwin_${{ env.TARGET_ARCH }} - path: ./generated_artifacts_darwin_${{ env.TARGET_ARCH }} - - name: Persist Build Artifacts - uses: actions/cache/save@0c45773b623bea8c8e75f6c82b208c3cf94ea4f9 - with: - path: | - src/out/Default/gen/node_headers - src/out/Default/overlapped-checker - src/electron - src/third_party/electron_node - src/third_party/nan - src/cross-arch-snapshots - src/third_party/llvm-build - src/build/linux - src/buildtools/mac - src/buildtools/third_party/libc++ - src/buildtools/third_party/libc++abi - src/third_party/libc++ - src/third_party/libc++abi - src/out/Default/obj/buildtools/third_party - src/v8/tools/builtins-pgo - key: ${{ runner.os }}-build-artifacts-darwin-${{ env.TARGET_ARCH }}-${{ github.sha }} - - name: Create MAS Config - run: | - mv src/electron/.github/workflows/config/${{ inputs.GN_BUILD_TYPE }}/${{ matrix.build-arch }}/evm.mas.json $HOME/.electron_build_tools/configs/evm.mas.json - echo "MAS_BUILD=true" >> $GITHUB_ENV - e use mas - - name: Build Electron (mas) - run: | - rm -rf "src/out/Default/Electron Framework.framework" - rm -rf src/out/Default/Electron*.app - - cd src/electron - # TODO(codebytere): remove this once we figure out why .git/packed-refs is initially missing - git pack-refs - cd .. - - ulimit -n 10000 - sudo launchctl limit maxfiles 65536 200000 - NINJA_SUMMARIZE_BUILD=1 e build -j $NUMBER_OF_NINJA_PROCESSES - cp out/Default/.ninja_log out/electron_ninja_log - node electron/script/check-symlinks.js - - name: Build Electron dist.zip (mas) - run: | - cd src - e build electron:electron_dist_zip -j $NUMBER_OF_NINJA_PROCESSES - if [ "$CHECK_DIST_MANIFEST" == "1" ]; then - target_os=mac_mas - electron/script/zip_manifests/check-zip-manifest.py out/Default/dist.zip electron/script/zip_manifests/dist_zip.$target_os.${{ env.TARGET_ARCH }}.manifest - fi - - name: Build Mksnapshot (mas) - run: | - cd src - e build electron:electron_mksnapshot -j $NUMBER_OF_NINJA_PROCESSES - gn desc out/Default v8:run_mksnapshot_default args > out/Default/mksnapshot_args - # Remove unused args from mksnapshot_args - SEDOPTION="-i ''" - sed $SEDOPTION '/.*builtins-pgo/d' out/Default/mksnapshot_args - sed $SEDOPTION '/--turbo-profiling-input/d' out/Default/mksnapshot_args - sed $SEDOPTION '/The gn arg use_goma=true .*/d' out/Default/mksnapshot_args - e build electron:electron_mksnapshot_zip -j $NUMBER_OF_NINJA_PROCESSES - (cd out/Default; zip mksnapshot.zip mksnapshot_args gen/v8/embedded.S) - - name: Build Chromedriver (mas) - run: | - cd src - e build electron:electron_chromedriver -j $NUMBER_OF_NINJA_PROCESSES - e build electron:electron_chromedriver_zip - - name: Build Node Headers - run: | - cd src - e build electron:node_headers - - name: Generate & Zip Symbols (mas) - run: | - if [ ${{ inputs.GENERATE_SYMBOLS }} == "true" ]; then - e build electron:electron_symbols - fi - cd src - export BUILD_PATH="$(pwd)/out/Default" - e build electron:licenses - e build electron:electron_version_file - if [ ${{ inputs.IS_RELEASE }} == "true" ]; then - DELETE_DSYMS_AFTER_ZIP=1 electron/script/zip-symbols.py -b $BUILD_PATH - else - electron/script/zip-symbols.py -b $BUILD_PATH - fi - # TODO(vertedinde): These uploads currently point to a different Azure bucket & GitHub Repo - - name: Publish Electron Dist - run: | - rm -rf src/out/Default/obj - cd src/electron - if [ ${{ inputs.UPLOAD_TO_STORAGE }} == "1" ]; then - echo 'Uploading Electron release distribution to Azure' - script/release/uploaders/upload.py --verbose --upload_to_storage - else - echo 'Uploading Electron release distribution to GitHub releases' - script/release/uploaders/upload.py --verbose - fi - - name: Move all Generated Artifacts to Upload Folder (mas) - run: ./src/electron/script/actions/move-artifacts.sh - - name: Upload Generated Artifacts - uses: actions/upload-artifact@65462800fd760344b1a7b4382951275a0abb4808 - with: - name: generated_artifacts_mas_${{ env.TARGET_ARCH }} - path: ./generated_artifacts_mas_${{ env.TARGET_ARCH }} - - name: Persist Build Artifacts - uses: actions/cache/save@0c45773b623bea8c8e75f6c82b208c3cf94ea4f9 - with: - path: | - src/out/Default/gen/node_headers - 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 - src/third_party/llvm-build - src/build/linux - src/buildtools/mac - src/buildtools/third_party/libc++ - src/buildtools/third_party/libc++abi - src/third_party/libc++ - src/third_party/libc++abi - src/out/Default/obj/buildtools/third_party - src/v8/tools/builtins-pgo - key: ${{ runner.os }}-build-artifacts-mas-${{ env.TARGET_ARCH }}-${{ github.sha }} - test: - if: ${{ inputs.IS_RELEASE == false }} - runs-on: macos-14-xlarge - needs: build - strategy: - fail-fast: false - matrix: - build-type: [ darwin, mas ] - env: - BUILD_TYPE: ${{ matrix.build-type }} - steps: - - name: Load Build Tools - run: | - export BUILD_TOOLS_SHA=2bb63e2e7877491b52f972532b52adc979a6ec2f - npm i -g @electron/build-tools - e init --root=$(pwd) --out=Default ${{ inputs.GN_BUILD_TYPE }} - - name: Checkout Electron - uses: actions/checkout@a5ac7e51b41094c92402da3b24376905380afc29 - with: - path: src/electron - fetch-depth: 0 - - name: Setup Node.js/npm - uses: actions/setup-node@60edb5dd545a775178f52524783378180af0d1f8 - with: - node-version: 20.11.x - cache: yarn - cache-dependency-path: src/electron/yarn.lock - - name: Install Dependencies - run: | - cd src/electron - node script/yarn install - - name: Get Depot Tools - timeout-minutes: 5 - run: | - git clone --depth=1 https://chromium.googlesource.com/chromium/tools/depot_tools.git - if [ "`uname`" == "Darwin" ]; then - # remove ninjalog_uploader_wrapper.py from autoninja since we don't use it and it causes problems - sed -i '' '/ninjalog_uploader_wrapper.py/d' ./depot_tools/autoninja - else - sed -i '/ninjalog_uploader_wrapper.py/d' ./depot_tools/autoninja - # Remove swift-format dep from cipd on macOS until we send a patch upstream. - cd depot_tools - git apply --3way ../src/electron/.github/workflows/config/gclient.diff - fi - # Ensure depot_tools does not update. - test -d depot_tools && cd depot_tools - touch .disable_auto_update - - name: Add Depot Tools to PATH - run: echo "$(pwd)/depot_tools" >> $GITHUB_PATH - - name: Download Generated Artifacts - uses: actions/download-artifact@65a9edc5881444af0b9093a5e628f2fe47ea3b2e - with: - name: generated_artifacts_${{ matrix.build-type }} - path: ./generated_artifacts_${{ matrix.build-type }} - - name: Restore Persisted Build Artifacts - uses: actions/cache/restore@0c45773b623bea8c8e75f6c82b208c3cf94ea4f9 - with: - path: | - src/out/Default/gen/node_headers - src/out/Default/overlapped-checker - src/electron - src/third_party/electron_node - src/third_party/nan - src/cross-arch-snapshots - src/third_party/llvm-build - src/build/linux - src/buildtools/mac - src/buildtools/third_party/libc++ - src/buildtools/third_party/libc++abi - src/third_party/libc++ - src/third_party/libc++abi - src/out/Default/obj/buildtools/third_party - src/v8/tools/builtins-pgo - key: ${{ runner.os }}-build-artifacts-${{ matrix.build-type }}-${{ github.sha }} - - name: Restore Generated Artifacts - run: ./src/electron/script/actions/restore-artifacts.sh - - name: Unzip Dist, Mksnapshot & Chromedriver - run: | - cd src/out/Default - unzip -:o dist.zip - unzip -:o chromedriver.zip - unzip -:o mksnapshot.zip - - name: Import & Trust Self-Signed Codesigning Cert on MacOS - run: | - sudo security authorizationdb write com.apple.trust-settings.admin allow - cd src/electron - ./script/codesign/generate-identity.sh - - name: Run Electron Tests - env: - MOCHA_REPORTER: mocha-multi-reporters - ELECTRON_TEST_RESULTS_DIR: junit - MOCHA_MULTI_REPORTERS: mocha-junit-reporter, tap - ELECTRON_DISABLE_SECURITY_WARNINGS: 1 - ELECTRON_SKIP_NATIVE_MODULE_TESTS: true - run: | - cd src/electron - node script/yarn test --runners=main --trace-uncaught --enable-logging + # TODO(vertedinde): Change this to main before merge + uses: electron/electron/.github/workflows/macos-pipeline.yml@main + with: + is-release: false + gn-config: //electron/build/args/testing.gn + gn-build-type: testing + generate-symbols: false + upload-to-storage: '0' + secrets: inherit diff --git a/.github/workflows/macos-pipeline.yml b/.github/workflows/macos-pipeline.yml new file mode 100644 index 0000000000..9cf75b7d5f --- /dev/null +++ b/.github/workflows/macos-pipeline.yml @@ -0,0 +1,772 @@ +name: Build MacOS + +on: + workflow_call: + inputs: + is-release: + description: 'Whether this build job is a release job' + required: true + type: boolean + default: false + gn-config: + description: 'The gn arg configuration to use' + required: true + type: string + default: //electron/build/args/testing.gn + gn-build-type: + description: 'The gn build type - testing or release' + required: true + type: string + default: testing + generate-symbols: + description: 'Whether or not to generate symbols' + required: true + type: boolean + default: false + upload-to-storage: + description: 'Whether or not to upload build artifacts to external storage' + required: true + type: string + default: '0' + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +env: + AZURE_STORAGE_ACCOUNT: ${{ secrets.AZURE_STORAGE_ACCOUNT }} + AZURE_STORAGE_KEY: ${{ secrets.AZURE_STORAGE_KEY }} + AZURE_STORAGE_CONTAINER_NAME: ${{ secrets.AZURE_STORAGE_CONTAINER_NAME }} + ELECTRON_ARTIFACTS_BLOB_STORAGE: ${{ secrets.ELECTRON_ARTIFACTS_BLOB_STORAGE }} + ELECTRON_RBE_JWT: ${{ secrets.ELECTRON_RBE_JWT }} + ELECTRON_GITHUB_TOKEN: ${{ secrets.ELECTRON_GITHUB_TOKEN }} + GN_CONFIG: ${{ inputs.gn-config }} + # Disable pre-compiled headers to reduce out size - only useful for rebuilds + GN_BUILDFLAG_ARGS: 'enable_precompiled_headers = false' + GCLIENT_EXTRA_ARGS: '--custom-var=checkout_mac=True --custom-var=host_os=mac' + CHECK_DIST_MANIFEST: '1' + IS_GHA_RELEASE: true + ELECTRON_OUT_DIR: Default + +jobs: + checkout: + runs-on: LargeLinuxRunner + steps: + - name: Checkout Electron + uses: actions/checkout@a5ac7e51b41094c92402da3b24376905380afc29 + with: + path: src/electron + fetch-depth: 0 + - name: Set GIT_CACHE_PATH to make gclient to use the cache + run: | + echo "GIT_CACHE_PATH=$(pwd)/git-cache" >> $GITHUB_ENV + - name: Setup Node.js/npm + uses: actions/setup-node@60edb5dd545a775178f52524783378180af0d1f8 + with: + node-version: 20.11.x + cache: yarn + cache-dependency-path: src/electron/yarn.lock + - name: Install Dependencies + run: | + cd src/electron + node script/yarn install + - name: Get Depot Tools + timeout-minutes: 5 + run: | + git clone --depth=1 https://chromium.googlesource.com/chromium/tools/depot_tools.git + if [ "`uname`" == "Darwin" ]; then + # remove ninjalog_uploader_wrapper.py from autoninja since we don't use it and it causes problems + sed -i '' '/ninjalog_uploader_wrapper.py/d' ./depot_tools/autoninja + else + sed -i '/ninjalog_uploader_wrapper.py/d' ./depot_tools/autoninja + # Remove swift-format dep from cipd on macOS until we send a patch upstream. + cd depot_tools + git apply --3way ../src/electron/.github/workflows/config/gclient.diff + fi + # Ensure depot_tools does not update. + test -d depot_tools && cd depot_tools + touch .disable_auto_update + - name: Add Depot Tools to PATH + run: echo "$(pwd)/depot_tools" >> $GITHUB_PATH + - name: Generate DEPS Hash + run: | + node src/electron/script/generate-deps-hash.js && cat src/electron/.depshash-target + echo "DEPSHASH=v1-src-cache-$(shasum src/electron/.depshash | cut -f1 -d' ')" >> $GITHUB_ENV + - name: Check If Cache Exists + id: check-cache + run: | + exists_json=$(az storage blob exists \ + --account-name $AZURE_STORAGE_ACCOUNT \ + --account-key $AZURE_STORAGE_KEY \ + --container-name $AZURE_STORAGE_CONTAINER_NAME \ + --name $DEPSHASH) + + cache_exists=$(echo $exists_json | jq -r '.exists') + echo "cache_exists=$cache_exists" >> $GITHUB_OUTPUT + + if (test "$cache_exists" = "true"); then + echo "Cache Exists for $DEPSHASH" + else + echo "Cache Does Not Exist for $DEPSHASH" + fi + - name: Gclient Sync + # If there is no existing src cache, we need to do a full gclient sync. + # TODO(codebytere): Add stale patch handling for non-release builds. + if: steps.check-cache.outputs.cache_exists == 'false' + run: | + gclient config \ + --name "src/electron" \ + --unmanaged \ + ${GCLIENT_EXTRA_ARGS} \ + "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY" + + ELECTRON_USE_THREE_WAY_MERGE_FOR_PATCHES=1 gclient sync --with_branch_heads --with_tags -vvvvv + if [ ${{ inputs.is-release != true }}]; then + # Re-export all the patches to check if there were changes. + python3 src/electron/script/export_all_patches.py src/electron/patches/config.json + cd src/electron + git update-index --refresh || true + if ! git diff-index --quiet HEAD --; then + # There are changes to the patches. Make a git commit with the updated patches + git add patches + GIT_COMMITTER_NAME="PatchUp" GIT_COMMITTER_EMAIL="73610968+patchup[bot]@users.noreply.github.com" git commit -m "chore: update patches" --author="PatchUp <73610968+patchup[bot]@users.noreply.github.com>" + # Export it + mkdir -p ../../patches + git format-patch -1 --stdout --keep-subject --no-stat --full-index > ../../patches/update-patches.patch + if (node ./script/push-patch.js 2> /dev/null > /dev/null); then + echo + echo "======================================================================" + echo "Changes to the patches when applying, we have auto-pushed the diff to the current branch" + echo "A new CI job will kick off shortly" + echo "======================================================================" + exit 1 + else + echo + echo "======================================================================" + echo "There were changes to the patches when applying." + echo "Check the CI artifacts for a patch you can apply to fix it." + echo "======================================================================" + exit 1 + fi + fi + fi + + # delete all .git directories under src/ except for + # third_party/angle/ and third_party/dawn/ because of build time generation of files + # gen/angle/commit.h depends on third_party/angle/.git/HEAD + # https://chromium-review.googlesource.com/c/angle/angle/+/2074924 + # and dawn/common/Version_autogen.h depends on third_party/dawn/.git/HEAD + # https://dawn-review.googlesource.com/c/dawn/+/83901 + # TODO: maybe better to always leave out */.git/HEAD file for all targets ? + - name: Delete .git directories under src to free space + if: steps.check-cache.outputs.cache_exists == 'false' + run: | + cd src + ( find . -type d -name ".git" -not -path "./third_party/angle/*" -not -path "./third_party/dawn/*" -not -path "./electron/*" ) | xargs rm -rf + - name: Minimize Cache Size for Upload + if: steps.check-cache.outputs.cache_exists == 'false' + run: | + rm -rf src/android_webview + rm -rf src/ios/chrome + rm -rf src/third_party/blink/web_tests + rm -rf src/third_party/blink/perf_tests + rm -rf src/chrome/test/data/xr/webvr_info + rm -rf src/third_party/angle/third_party/VK-GL-CTS/src + rm -rf src/third_party/swift-toolchain + rm -rf src/third_party/swiftshader/tests/regres/testlists + rm -rf src/electron + - name: Compress Src Directory + if: steps.check-cache.outputs.cache_exists == 'false' + run: | + echo "Uncompressed src size: $(du -sh src | cut -f1 -d' ')" + tar -cvf $DEPSHASH.tar src + echo "Compressed src to $(du -sh $DEPSHASH.tar | cut -f1 -d' ')" + - name: Upload Compressed Src Cache to Azure + if: steps.check-cache.outputs.cache_exists == 'false' + run: | + az storage blob upload \ + --account-name $AZURE_STORAGE_ACCOUNT \ + --account-key $AZURE_STORAGE_KEY \ + --container-name $AZURE_STORAGE_CONTAINER_NAME \ + --file $DEPSHASH.tar \ + --name $DEPSHASH \ + --debug + build: + strategy: + fail-fast: false + matrix: + build-arch: [ arm64, x64 ] + # macos-large is x64, macos-xlarge is arm64 + # More runner information: https://github.com/actions/runner-images/blob/main/README.md#available-images + runs-on: macos-14-xlarge + needs: checkout + steps: + - name: Load Build Tools + run: | + export BUILD_TOOLS_SHA=2bb63e2e7877491b52f972532b52adc979a6ec2f + npm i -g @electron/build-tools + e auto-update disable + e init --root=$(pwd) --out=Default ${{ inputs.gn-build-type }} --import ${{ inputs.gn-build-type }} --target-cpu ${{ matrix.build-arch }} + e use ${{ inputs.gn-build-type }} + - name: Checkout Electron + uses: actions/checkout@a5ac7e51b41094c92402da3b24376905380afc29 + with: + path: src/electron + fetch-depth: 0 + - name: Setup Node.js/npm + uses: actions/setup-node@60edb5dd545a775178f52524783378180af0d1f8 + with: + node-version: 20.11.x + cache: yarn + cache-dependency-path: src/electron/yarn.lock + - name: Install Dependencies + run: | + cd src/electron + node script/yarn install + - name: Load Target Arch & CPU + run: | + echo "TARGET_ARCH=${{ matrix.build-arch }}" >> $GITHUB_ENV + echo "target_cpu=${{ matrix.build-arch }}" >> $GITHUB_ENV + echo "host_cpu=${{ matrix.build-arch }}" >> $GITHUB_ENV + - name: Get Depot Tools + timeout-minutes: 5 + run: | + git clone --depth=1 https://chromium.googlesource.com/chromium/tools/depot_tools.git + if [ "`uname`" == "Darwin" ]; then + # remove ninjalog_uploader_wrapper.py from autoninja since we don't use it and it causes problems + sed -i '' '/ninjalog_uploader_wrapper.py/d' ./depot_tools/autoninja + else + sed -i '/ninjalog_uploader_wrapper.py/d' ./depot_tools/autoninja + # Remove swift-format dep from cipd on macOS until we send a patch upstream. + cd depot_tools + git apply --3way ../src/electron/.github/workflows/config/gclient.diff + fi + # Ensure depot_tools does not update. + test -d depot_tools && cd depot_tools + touch .disable_auto_update + - name: Add Depot Tools to PATH + run: echo "$(pwd)/depot_tools" >> $GITHUB_PATH + - name: Generate DEPS Hash + run: | + node src/electron/script/generate-deps-hash.js && cat src/electron/.depshash-target + echo "DEPSHASH=v1-src-cache-$(shasum src/electron/.depshash | cut -f1 -d' ')" >> $GITHUB_ENV + - name: Download Src Cache + # The cache will always exist here as a result of the checkout job + # Either it was uploaded to Azure in the checkout job for this commit + # or it was uploaded in the checkout job for a previous commit. + uses: nick-fields/retry@7152eba30c6575329ac0576536151aca5a72780e # v3.0.0 + with: + timeout_minutes: 20 + max_attempts: 3 + retry_on: error + command: | + az storage blob download \ + --account-name $AZURE_STORAGE_ACCOUNT \ + --account-key $AZURE_STORAGE_KEY \ + --container-name $AZURE_STORAGE_CONTAINER_NAME \ + --name $DEPSHASH \ + --file $DEPSHASH.tar \ + - name: Unzip and Ensure Src Cache + run: | + echo "Downloaded cache is $(du -sh $DEPSHASH.tar | cut -f1)" + mkdir temp-cache + tar -xvf $DEPSHASH.tar -C temp-cache + echo "Unzipped cache is $(du -sh temp-cache/src | cut -f1)" + + if [ -d "temp-cache/src" ]; then + echo "Relocating Cache" + rm -rf src + mv temp-cache/src src + + echo "Deleting zip file" + rm -rf $DEPSHASH.tar + fi + + if [ ! -d "src/third_party/blink" ]; then + echo "Cache was not correctly restored - exiting" + exit 1 + fi + + echo "Wiping Electron Directory" + rm -rf src/electron + - name: Checkout Electron + uses: actions/checkout@a5ac7e51b41094c92402da3b24376905380afc29 + with: + path: src/electron + fetch-depth: 0 + - name: Run Electron Only Hooks + run: | + echo "Running Electron Only Hooks" + gclient runhooks --spec="solutions=[{'name':'src/electron','url':None,'deps_file':'DEPS','custom_vars':{'process_deps':False},'managed':False}]" + - name: Regenerate DEPS Hash + run: | + (cd src/electron && git checkout .) && node src/electron/script/generate-deps-hash.js && cat src/electron/.depshash-target + echo "DEPSHASH=$(shasum src/electron/.depshash | cut -f1 -d' ')" >> $GITHUB_ENV + - name: Add CHROMIUM_BUILDTOOLS_PATH to env + run: echo "CHROMIUM_BUILDTOOLS_PATH=$(pwd)/src/buildtools" >> $GITHUB_ENV + - name: Fix Sync + # This step is required to correct for differences between "gclient sync" + # on Linux and the expected state on macOS. This requires: + # 1. Fixing Clang Install (wrong binary) + # 2. Fixing esbuild (wrong binary) + # 3. Fixing rustc (wrong binary) + # 4. Fixing gn (wrong binary) + # 5. Fix reclient (wrong binary) + # 6. Fixing dsymutil (wrong binary) + # 7. Ensuring we are using the correct ninja and adding it to PATH + # 8. Fixing angle (wrong remote) + run : | + SEDOPTION="-i ''" + rm -rf src/third_party/llvm-build + python3 src/tools/clang/scripts/update.py + + echo 'infra/3pp/tools/esbuild/${platform}' `gclient getdep --deps-file=src/third_party/devtools-frontend/src/DEPS -r 'third_party/esbuild:infra/3pp/tools/esbuild/${platform}'` > esbuild_ensure_file + # Remove extra output from calling gclient getdep which always calls update_depot_tools + sed -i '' "s/Updating depot_tools... //g" esbuild_ensure_file + cipd ensure --root src/third_party/devtools-frontend/src/third_party/esbuild -ensure-file esbuild_ensure_file + + rm -rf src/third_party/rust-toolchain + python3 src/tools/rust/update_rust.py + + # Prevent calling gclient getdep which always calls update_depot_tools + echo 'gn/gn/mac-${arch}' `gclient getdep --deps-file=src/DEPS -r 'src/buildtools/mac:gn/gn/mac-${arch}'` > gn_ensure_file + sed -i '' "s/Updating depot_tools... //g" gn_ensure_file + cipd ensure --root src/buildtools/mac -ensure-file gn_ensure_file + + # Prevent calling gclient getdep which always calls update_depot_tools + echo 'infra/rbe/client/${platform}' `gclient getdep --deps-file=src/DEPS -r 'src/buildtools/reclient:infra/rbe/client/${platform}'` > gn_ensure_file + sed -i '' "s/Updating depot_tools... //g" gn_ensure_file + cipd ensure --root src/buildtools/reclient -ensure-file gn_ensure_file + python3 src/buildtools/reclient_cfgs/configure_reclient_cfgs.py --rbe_instance "projects/rbe-chrome-untrusted/instances/default_instance" --reproxy_cfg_template reproxy.cfg.template --rewrapper_cfg_project "" --skip_remoteexec_cfg_fetch + + if [ "$TARGET_ARCH" == "arm64" ]; then + DSYM_SHA_FILE=src/tools/clang/dsymutil/bin/dsymutil.arm64.sha1 + else + DSYM_SHA_FILE=src/tools/clang/dsymutil/bin/dsymutil.x64.sha1 + fi + python3 src/third_party/depot_tools/download_from_google_storage.py --no_resume --no_auth --bucket chromium-browser-clang -s $DSYM_SHA_FILE -o src/tools/clang/dsymutil/bin/dsymutil + + echo 'infra/3pp/tools/ninja/${platform}' `gclient getdep --deps-file=src/DEPS -r 'src/third_party/ninja:infra/3pp/tools/ninja/${platform}'` > ninja_ensure_file + sed $SEDOPTION "s/Updating depot_tools... //g" ninja_ensure_file + cipd ensure --root src/third_party/ninja -ensure-file ninja_ensure_file + + echo "$(pwd)/src/third_party/ninja" >> $GITHUB_PATH + + cd src/third_party/angle + rm -f .git/objects/info/alternates + git remote set-url origin https://chromium.googlesource.com/angle/angle.git + cp .git/config .git/config.backup + git remote remove origin + mv .git/config.backup .git/config + git fetch + - name: Install build-tools & Setup RBE + run: | + echo "NUMBER_OF_NINJA_PROCESSES=200" >> $GITHUB_ENV + cd ~/.electron_build_tools + npx yarn --ignore-engines + # Pull down credential helper and print status + node -e "require('./src/utils/reclient.js').downloadAndPrepare({})" + HELPER=$(node -p "require('./src/utils/reclient.js').helperPath({})") + $HELPER login + echo 'RBE_service='`node -e "console.log(require('./src/utils/reclient.js').serviceAddress)"` >> $GITHUB_ENV + echo 'RBE_experimental_credentials_helper='`node -e "console.log(require('./src/utils/reclient.js').helperPath({}))"` >> $GITHUB_ENV + echo 'RBE_experimental_credentials_helper_args=print' >> $GITHUB_ENV + - name: Free Space on MacOS + run: | + sudo mkdir -p $TMPDIR/del-target + + tmpify() { + if [ -d "$1" ]; then + sudo mv "$1" $TMPDIR/del-target/$(echo $1|shasum -a 256|head -n1|cut -d " " -f1) + fi + } + + strip_universal_deep() { + opwd=$(pwd) + cd $1 + f=$(find . -perm +111 -type f) + for fp in $f + do + if [[ $(file "$fp") == *"universal binary"* ]]; then + if [ "`arch`" == "arm64" ]; then + if [[ $(file "$fp") == *"x86_64"* ]]; then + sudo lipo -remove x86_64 "$fp" -o "$fp" || true + fi + else + if [[ $(file "$fp") == *"arm64e)"* ]]; then + sudo lipo -remove arm64e "$fp" -o "$fp" || true + fi + if [[ $(file "$fp") == *"arm64)"* ]]; then + sudo lipo -remove arm64 "$fp" -o "$fp" || true + fi + fi + fi + done + + cd $opwd + } + + tmpify /Library/Developer/CoreSimulator + tmpify ~/Library/Developer/CoreSimulator + tmpify $(xcode-select -p)/Platforms/AppleTVOS.platform + tmpify $(xcode-select -p)/Platforms/iPhoneOS.platform + tmpify $(xcode-select -p)/Platforms/WatchOS.platform + tmpify $(xcode-select -p)/Platforms/WatchSimulator.platform + tmpify $(xcode-select -p)/Platforms/AppleTVSimulator.platform + tmpify $(xcode-select -p)/Platforms/iPhoneSimulator.platform + tmpify $(xcode-select -p)/Toolchains/XcodeDefault.xctoolchain/usr/metal/ios + tmpify $(xcode-select -p)/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift + tmpify $(xcode-select -p)/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift-5.0 + tmpify ~/.rubies + tmpify ~/Library/Caches/Homebrew + tmpify /usr/local/Homebrew + + # the contents of build/linux/strip_binary.gni aren't used, but + # https://chromium-review.googlesource.com/c/chromium/src/+/4278307 + # needs the file to exist. + # mv ~/project/src/build/linux/strip_binary.gni "${TMPDIR}"/ + # tmpify ~/project/src/build/linux/ + # mkdir -p ~/project/src/build/linux + # mv "${TMPDIR}/strip_binary.gni" ~/project/src/build/linux/ + + sudo rm -rf $TMPDIR/del-target + + # sudo rm -rf "/System/Library/Desktop Pictures" + # sudo rm -rf /System/Library/Templates/Data + # sudo rm -rf /System/Library/Speech/Voices + # sudo rm -rf "/System/Library/Screen Savers" + # sudo rm -rf /System/Volumes/Data/Library/Developer/CommandLineTools/SDKs + # sudo rm -rf "/System/Volumes/Data/Library/Application Support/Apple/Photos/Print Products" + # sudo rm -rf /System/Volumes/Data/Library/Developer/CommandLineTools/SDKs/MacOSX10.15.sdk/ + # sudo rm -rf /System/Volumes/Data/Library/Java + # sudo rm -rf /System/Volumes/Data/Library/Ruby + # sudo rm -rf /System/Volumes/Data/Library/Printers + # sudo rm -rf /System/iOSSupport + # sudo rm -rf /System/Applications/*.app + # sudo rm -rf /System/Applications/Utilities/*.app + # sudo rm -rf /System/Library/LinguisticData + # sudo rm -rf /System/Volumes/Data/private/var/db/dyld/* + # sudo rm -rf /System/Library/Fonts/* + # sudo rm -rf /System/Library/PreferencePanes + # sudo rm -rf /System/Library/AssetsV2/* + sudo rm -rf /Applications/Safari.app + sudo rm -rf ~/project/src/third_party/catapult/tracing/test_data + sudo rm -rf ~/project/src/third_party/angle/third_party/VK-GL-CTS + + # lipo off some huge binaries arm64 versions to save space + strip_universal_deep $(xcode-select -p)/../SharedFrameworks + # strip_arm_deep /System/Volumes/Data/Library/Developer/CommandLineTools/usr + - name: Build Electron (darwin) + run: | + cd src/electron + # TODO(codebytere): remove this once we figure out why .git/packed-refs is initially missing + git pack-refs + cd .. + ulimit -n 10000 + sudo launchctl limit maxfiles 65536 200000 + + NINJA_SUMMARIZE_BUILD=1 e build -j $NUMBER_OF_NINJA_PROCESSES + cp out/Default/.ninja_log out/electron_ninja_log + node electron/script/check-symlinks.js + - name: Build Electron dist.zip (darwin) + run: | + cd src + e build electron:electron_dist_zip -j $NUMBER_OF_NINJA_PROCESSES + if [ "$CHECK_DIST_MANIFEST" == "1" ]; then + target_os=mac + electron/script/zip_manifests/check-zip-manifest.py out/Default/dist.zip electron/script/zip_manifests/dist_zip.$target_os.${{ env.TARGET_ARCH }}.manifest + fi + - name: Build Mksnapshot (darwin) + run: | + cd src + e build electron:electron_mksnapshot -j $NUMBER_OF_NINJA_PROCESSES + gn desc out/Default v8:run_mksnapshot_default args > out/Default/mksnapshot_args + # Remove unused args from mksnapshot_args + SEDOPTION="-i ''" + sed $SEDOPTION '/.*builtins-pgo/d' out/Default/mksnapshot_args + sed $SEDOPTION '/--turbo-profiling-input/d' out/Default/mksnapshot_args + sed $SEDOPTION '/The gn arg use_goma=true .*/d' out/Default/mksnapshot_args + e build electron:electron_mksnapshot_zip -j $NUMBER_OF_NINJA_PROCESSES + (cd out/Default; zip mksnapshot.zip mksnapshot_args gen/v8/embedded.S) + - name: Build Chromedriver (darwin) + run: | + cd src + e build electron:electron_chromedriver -j $NUMBER_OF_NINJA_PROCESSES + e build electron:electron_chromedriver_zip + # NOTE (vertedinde): We strip binaries/symbols on the Linux job, not the Mac job + - name: Generate & Zip Symbols (darwin) + run: | + # Generate breakpad symbols on release builds + if [ ${{ inputs.generate-symbols }} ]; then + e build electron:electron_symbols + fi + cd src + export BUILD_PATH="$(pwd)/out/Default" + e build electron:licenses + e build electron:electron_version_file + if [ ${{ inputs.is-release }} ]; then + DELETE_DSYMS_AFTER_ZIP=1 electron/script/zip-symbols.py -b $BUILD_PATH + else + electron/script/zip-symbols.py -b $BUILD_PATH + fi + - name: Generate FFMpeg + if: ${{ inputs.is-release }} + run: | + cd src + gn gen out/ffmpeg --args="import(\"//electron/build/args/ffmpeg.gn\") use_remoteexec=true $GN_EXTRA_ARGS" + autoninja -C out/ffmpeg electron:electron_ffmpeg_zip -j $NUMBER_OF_NINJA_PROCESSES + - name: Generate Hunspell Dictionaries + if: ${{ inputs.is-release }} + run: | + cd src + autoninja -C out/Default electron:hunspell_dictionaries_zip -j $NUMBER_OF_NINJA_PROCESSES + - name: Generate TypeScript Definitions + if: ${{ inputs.is-release }} + run: | + cd src/electron + node script/yarn create-typescript-definitions + # TODO(vertedinde): These uploads currently point to a different Azure bucket & GitHub Repo + - name: Publish Electron Dist + if: ${{ inputs.is-release }} + run: | + rm -rf src/out/Default/obj + cd src/electron + if [ ${{ inputs.upload-to-storage == '1' }} ]; then + echo 'Uploading Electron release distribution to Azure' + script/release/uploaders/upload.py --verbose --upload_to_storage + else + echo 'Uploading Electron release distribution to GitHub releases' + script/release/uploaders/upload.py --verbose + fi + # 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 + run: ./src/electron/script/actions/move-artifacts.sh + - name: Upload Generated Artifacts + uses: actions/upload-artifact@65462800fd760344b1a7b4382951275a0abb4808 + with: + name: generated_artifacts_darwin_${{ env.TARGET_ARCH }} + path: ./generated_artifacts_darwin_${{ env.TARGET_ARCH }} + - name: Persist Build Artifacts + uses: actions/cache/save@0c45773b623bea8c8e75f6c82b208c3cf94ea4f9 + with: + path: | + src/out/Default/gen/node_headers + src/out/Default/overlapped-checker + src/electron + src/third_party/electron_node + src/third_party/nan + src/cross-arch-snapshots + src/third_party/llvm-build + src/build/linux + src/buildtools/mac + src/buildtools/third_party/libc++ + src/buildtools/third_party/libc++abi + src/third_party/libc++ + src/third_party/libc++abi + src/out/Default/obj/buildtools/third_party + src/v8/tools/builtins-pgo + key: ${{ runner.os }}-build-artifacts-darwin-${{ env.TARGET_ARCH }}-${{ github.sha }} + - name: Create MAS Config + run: | + mv src/electron/.github/workflows/config/${{ inputs.gn-build-type }}/${{ matrix.build-arch }}/evm.mas.json $HOME/.electron_build_tools/configs/evm.mas.json + echo "MAS_BUILD=true" >> $GITHUB_ENV + e use mas + - name: Build Electron (mas) + run: | + rm -rf "src/out/Default/Electron Framework.framework" + rm -rf src/out/Default/Electron*.app + + cd src/electron + # TODO(codebytere): remove this once we figure out why .git/packed-refs is initially missing + git pack-refs + cd .. + + ulimit -n 10000 + sudo launchctl limit maxfiles 65536 200000 + NINJA_SUMMARIZE_BUILD=1 e build -j $NUMBER_OF_NINJA_PROCESSES + cp out/Default/.ninja_log out/electron_ninja_log + node electron/script/check-symlinks.js + - name: Build Electron dist.zip (mas) + run: | + cd src + e build electron:electron_dist_zip -j $NUMBER_OF_NINJA_PROCESSES + if [ "$CHECK_DIST_MANIFEST" == "1" ]; then + target_os=mac_mas + electron/script/zip_manifests/check-zip-manifest.py out/Default/dist.zip electron/script/zip_manifests/dist_zip.$target_os.${{ env.TARGET_ARCH }}.manifest + fi + - name: Build Mksnapshot (mas) + run: | + cd src + e build electron:electron_mksnapshot -j $NUMBER_OF_NINJA_PROCESSES + gn desc out/Default v8:run_mksnapshot_default args > out/Default/mksnapshot_args + # Remove unused args from mksnapshot_args + SEDOPTION="-i ''" + sed $SEDOPTION '/.*builtins-pgo/d' out/Default/mksnapshot_args + sed $SEDOPTION '/--turbo-profiling-input/d' out/Default/mksnapshot_args + sed $SEDOPTION '/The gn arg use_goma=true .*/d' out/Default/mksnapshot_args + e build electron:electron_mksnapshot_zip -j $NUMBER_OF_NINJA_PROCESSES + (cd out/Default; zip mksnapshot.zip mksnapshot_args gen/v8/embedded.S) + - name: Build Chromedriver (mas) + run: | + cd src + e build electron:electron_chromedriver -j $NUMBER_OF_NINJA_PROCESSES + e build electron:electron_chromedriver_zip + - name: Build Node Headers + run: | + cd src + e build electron:node_headers + - name: Generate & Zip Symbols (mas) + run: | + if [ ${{ inputs.generate-symbols }} ]; then + e build electron:electron_symbols + fi + cd src + export BUILD_PATH="$(pwd)/out/Default" + e build electron:licenses + e build electron:electron_version_file + if [ ${{ inputs.is-release }}]; then + DELETE_DSYMS_AFTER_ZIP=1 electron/script/zip-symbols.py -b $BUILD_PATH + else + electron/script/zip-symbols.py -b $BUILD_PATH + fi + # TODO(vertedinde): These uploads currently point to a different Azure bucket & GitHub Repo + - name: Publish Electron Dist + if: ${{ inputs.is-release }} + run: | + rm -rf src/out/Default/obj + cd src/electron + if [ ${{ inputs.upload-to-storage == '1' }} ]; then + echo 'Uploading Electron release distribution to Azure' + script/release/uploaders/upload.py --verbose --upload_to_storage + else + echo 'Uploading Electron release distribution to GitHub releases' + script/release/uploaders/upload.py --verbose + fi + - name: Move all Generated Artifacts to Upload Folder (mas) + run: ./src/electron/script/actions/move-artifacts.sh + - name: Upload Generated Artifacts + uses: actions/upload-artifact@65462800fd760344b1a7b4382951275a0abb4808 + with: + name: generated_artifacts_mas_${{ env.TARGET_ARCH }} + path: ./generated_artifacts_mas_${{ env.TARGET_ARCH }} + - name: Persist Build Artifacts + uses: actions/cache/save@0c45773b623bea8c8e75f6c82b208c3cf94ea4f9 + with: + path: | + src/out/Default/gen/node_headers + 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 + src/third_party/llvm-build + src/build/linux + src/buildtools/mac + src/buildtools/third_party/libc++ + src/buildtools/third_party/libc++abi + src/third_party/libc++ + src/third_party/libc++abi + src/out/Default/obj/buildtools/third_party + src/v8/tools/builtins-pgo + key: ${{ runner.os }}-build-artifacts-mas-${{ env.TARGET_ARCH }}-${{ github.sha }} + test: + if: ${{ inputs.is-release == false }} + runs-on: macos-14-xlarge + needs: build + strategy: + fail-fast: false + matrix: + build-type: [ darwin, mas ] + env: + BUILD_TYPE: ${{ matrix.build-type }} + steps: + - name: Load Build Tools + run: | + export BUILD_TOOLS_SHA=2bb63e2e7877491b52f972532b52adc979a6ec2f + npm i -g @electron/build-tools + e auto-update disable + e init --root=$(pwd) --out=Default ${{ inputs.gn-build-type }} + - name: Checkout Electron + uses: actions/checkout@a5ac7e51b41094c92402da3b24376905380afc29 + with: + path: src/electron + fetch-depth: 0 + - name: Setup Node.js/npm + uses: actions/setup-node@60edb5dd545a775178f52524783378180af0d1f8 + with: + node-version: 20.11.x + cache: yarn + cache-dependency-path: src/electron/yarn.lock + - name: Install Dependencies + run: | + cd src/electron + node script/yarn install + - name: Get Depot Tools + timeout-minutes: 5 + run: | + git clone --depth=1 https://chromium.googlesource.com/chromium/tools/depot_tools.git + if [ "`uname`" == "Darwin" ]; then + # remove ninjalog_uploader_wrapper.py from autoninja since we don't use it and it causes problems + sed -i '' '/ninjalog_uploader_wrapper.py/d' ./depot_tools/autoninja + else + sed -i '/ninjalog_uploader_wrapper.py/d' ./depot_tools/autoninja + # Remove swift-format dep from cipd on macOS until we send a patch upstream. + cd depot_tools + git apply --3way ../src/electron/.github/workflows/config/gclient.diff + fi + # Ensure depot_tools does not update. + test -d depot_tools && cd depot_tools + touch .disable_auto_update + - name: Add Depot Tools to PATH + run: echo "$(pwd)/depot_tools" >> $GITHUB_PATH + - name: Download Generated Artifacts + uses: actions/download-artifact@65a9edc5881444af0b9093a5e628f2fe47ea3b2e + with: + name: generated_artifacts_${{ matrix.build-type }} + path: ./generated_artifacts_${{ matrix.build-type }} + - name: Restore Persisted Build Artifacts + uses: actions/cache/restore@0c45773b623bea8c8e75f6c82b208c3cf94ea4f9 + with: + path: | + src/out/Default/gen/node_headers + src/out/Default/overlapped-checker + src/electron + src/third_party/electron_node + src/third_party/nan + src/cross-arch-snapshots + src/third_party/llvm-build + src/build/linux + src/buildtools/mac + src/buildtools/third_party/libc++ + src/buildtools/third_party/libc++abi + src/third_party/libc++ + src/third_party/libc++abi + src/out/Default/obj/buildtools/third_party + src/v8/tools/builtins-pgo + key: ${{ runner.os }}-build-artifacts-${{ matrix.build-type }}-${{ github.sha }} + - name: Restore Generated Artifacts + run: ./src/electron/script/actions/restore-artifacts.sh + - name: Unzip Dist, Mksnapshot & Chromedriver + run: | + cd src/out/Default + unzip -:o dist.zip + unzip -:o chromedriver.zip + unzip -:o mksnapshot.zip + - name: Import & Trust Self-Signed Codesigning Cert on MacOS + run: | + sudo security authorizationdb write com.apple.trust-settings.admin allow + cd src/electron + ./script/codesign/generate-identity.sh + - name: Run Electron Tests + env: + MOCHA_REPORTER: mocha-multi-reporters + ELECTRON_TEST_RESULTS_DIR: junit + MOCHA_MULTI_REPORTERS: mocha-junit-reporter, tap + ELECTRON_DISABLE_SECURITY_WARNINGS: 1 + ELECTRON_SKIP_NATIVE_MODULE_TESTS: true + run: | + cd src/electron + node script/yarn test --runners=main --trace-uncaught --enable-logging diff --git a/.github/workflows/macos-publish.yml b/.github/workflows/macos-publish.yml index 06a5932f3c..5684f6742f 100644 --- a/.github/workflows/macos-publish.yml +++ b/.github/workflows/macos-publish.yml @@ -5,7 +5,7 @@ on: inputs: upload-to-storage: description: 'Uploads to Azure storage' - required: false + required: false default: '1' type: string run-macos-publish: @@ -16,11 +16,11 @@ on: jobs: publish: # TODO(vertedinde): Change this to main before merge - uses: electron/electron/.github/workflows/macos-build.yml@gh-actions-mac-publish + uses: electron/electron/.github/workflows/macos-pipeline.yml@main with: - IS_RELEASE: true - GN_CONFIG: //electron/build/args/release.gn - GN_BUILD_TYPE: release - GENERATE_SYMBOLS: true - UPLOAD_TO_STORAGE: ${{ inputs.upload-to-storage }} + is-release: true + gn-config: //electron/build/args/release.gn + gn-build-type: release + generate-symbols: true + upload-to-storage: ${{ inputs.upload-to-storage }} secrets: inherit
build
925e4f7d7474204095b1e12bc8c281c4e7a63852
Tomasz
2023-10-10 01:56:38
feat: Add 'mouse-enter' and 'mouse-leave' Tray events for Windows. (#40072)
diff --git a/docs/api/tray.md b/docs/api/tray.md index 487dcc025c..84e1b6bd30 100644 --- a/docs/api/tray.md +++ b/docs/api/tray.md @@ -187,7 +187,7 @@ Returns: Emitted when the mouse clicks the tray icon. -#### Event: 'mouse-enter' _macOS_ +#### Event: 'mouse-enter' _macOS_ _Windows_ Returns: @@ -196,7 +196,7 @@ Returns: Emitted when the mouse enters the tray icon. -#### Event: 'mouse-leave' _macOS_ +#### Event: 'mouse-leave' _macOS_ _Windows_ Returns: diff --git a/shell/browser/ui/win/notify_icon.cc b/shell/browser/ui/win/notify_icon.cc index 71a937a937..2c70659feb 100644 --- a/shell/browser/ui/win/notify_icon.cc +++ b/shell/browser/ui/win/notify_icon.cc @@ -102,6 +102,16 @@ void NotifyIcon::HandleMouseMoveEvent(int modifiers) { NotifyMouseMoved(cursorPos, modifiers); } +void NotifyIcon::HandleMouseEntered(int modifiers) { + gfx::Point cursor_pos = display::Screen::GetScreen()->GetCursorScreenPoint(); + NotifyMouseEntered(cursor_pos, modifiers); +} + +void NotifyIcon::HandleMouseExited(int modifiers) { + gfx::Point cursor_pos = display::Screen::GetScreen()->GetCursorScreenPoint(); + NotifyMouseExited(cursor_pos, modifiers); +} + void NotifyIcon::ResetIcon() { NOTIFYICONDATA icon_data; InitIconData(&icon_data); diff --git a/shell/browser/ui/win/notify_icon.h b/shell/browser/ui/win/notify_icon.h index fa3a3f3902..9649923811 100644 --- a/shell/browser/ui/win/notify_icon.h +++ b/shell/browser/ui/win/notify_icon.h @@ -50,6 +50,8 @@ class NotifyIcon : public TrayIcon { // Handles a mouse move event from the user. void HandleMouseMoveEvent(int modifiers); + void HandleMouseEntered(int modifiers); + void HandleMouseExited(int modifiers); // Re-creates the status tray icon now after the taskbar has been created. void ResetIcon(); diff --git a/shell/browser/ui/win/notify_icon_host.cc b/shell/browser/ui/win/notify_icon_host.cc index 389ebcc1ef..7cc95c85f7 100644 --- a/shell/browser/ui/win/notify_icon_host.cc +++ b/shell/browser/ui/win/notify_icon_host.cc @@ -11,11 +11,13 @@ #include "base/logging.h" #include "base/memory/weak_ptr.h" #include "base/stl_util.h" +#include "base/timer/timer.h" #include "base/win/win_util.h" #include "base/win/windows_types.h" #include "base/win/wrapped_window_proc.h" #include "content/public/browser/browser_thread.h" #include "shell/browser/ui/win/notify_icon.h" +#include "ui/display/screen.h" #include "ui/events/event_constants.h" #include "ui/events/win/system_event_state_lookup.h" #include "ui/gfx/win/hwnd_util.h" @@ -31,6 +33,8 @@ const UINT kBaseIconId = 2; const wchar_t kNotifyIconHostWindowClass[] = L"Electron_NotifyIconHostWindow"; +constexpr unsigned int kMouseLeaveCheckFrequency = 250; + bool IsWinPressed() { return ((::GetKeyState(VK_LWIN) & 0x8000) == 0x8000) || ((::GetKeyState(VK_RWIN) & 0x8000) == 0x8000); @@ -51,6 +55,103 @@ int GetKeyboardModifiers() { } // namespace +// Helper class used to detect mouse entered and mouse exited events based on +// mouse move event. +class NotifyIconHost::MouseEnteredExitedDetector { + public: + MouseEnteredExitedDetector() = default; + ~MouseEnteredExitedDetector() = default; + + // disallow copy + MouseEnteredExitedDetector(const MouseEnteredExitedDetector&) = delete; + MouseEnteredExitedDetector& operator=(const MouseEnteredExitedDetector&) = + delete; + + // disallow move + MouseEnteredExitedDetector(MouseEnteredExitedDetector&&) = delete; + MouseEnteredExitedDetector& operator=(MouseEnteredExitedDetector&&) = delete; + + void MouseMoveEvent(raw_ptr<NotifyIcon> icon) { + if (!icon) + return; + + // If cursor is out of icon then skip this move event. + if (!IsCursorOverIcon(icon)) + return; + + // If user moved cursor to other icon then send mouse exited event for + // old icon. + if (current_mouse_entered_ && + current_mouse_entered_->icon_id() != icon->icon_id()) { + SendExitedEvent(); + } + + // If timer is runnig then cursor is arelady over icon and + // CheckCursorPositionOverIcon will be repeadly checking when to send + // mouse exited event. + if (mouse_exit_timer_.IsRunning()) + return; + + SendEnteredEvent(icon); + + // Start repeadly checking when to send mouse exited event. + StartObservingIcon(icon); + } + + void IconRemoved(raw_ptr<NotifyIcon> icon) { + if (current_mouse_entered_ && + current_mouse_entered_->icon_id() == icon->icon_id()) { + SendExitedEvent(); + } + } + + private: + void SendEnteredEvent(raw_ptr<NotifyIcon> icon) { + content::GetUIThreadTaskRunner({})->PostTask( + FROM_HERE, base::BindOnce(&NotifyIcon::HandleMouseEntered, + icon->GetWeakPtr(), GetKeyboardModifiers())); + } + + void SendExitedEvent() { + mouse_exit_timer_.Stop(); + content::GetUIThreadTaskRunner({})->PostTask( + FROM_HERE, base::BindOnce(&NotifyIcon::HandleMouseExited, + std::move(current_mouse_entered_), + GetKeyboardModifiers())); + } + + bool IsCursorOverIcon(raw_ptr<NotifyIcon> icon) { + gfx::Point cursor_pos = + display::Screen::GetScreen()->GetCursorScreenPoint(); + return icon->GetBounds().Contains(cursor_pos); + } + + void CheckCursorPositionOverIcon() { + if (!current_mouse_entered_ || + IsCursorOverIcon(current_mouse_entered_.get())) + return; + + SendExitedEvent(); + } + + void StartObservingIcon(raw_ptr<NotifyIcon> icon) { + current_mouse_entered_ = icon->GetWeakPtr(); + mouse_exit_timer_.Start( + FROM_HERE, base::Milliseconds(kMouseLeaveCheckFrequency), + base::BindRepeating( + &MouseEnteredExitedDetector::CheckCursorPositionOverIcon, + weak_factory_.GetWeakPtr())); + } + + // Timer used to check if cursor is still over the icon. + base::MetronomeTimer mouse_exit_timer_; + + // Weak pointer to icon over which cursor is hovering. + base::WeakPtr<NotifyIcon> current_mouse_entered_; + + base::WeakPtrFactory<MouseEnteredExitedDetector> weak_factory_{this}; +}; + NotifyIconHost::NotifyIconHost() { // Register our window class WNDCLASSEX window_class; @@ -74,6 +175,9 @@ NotifyIconHost::NotifyIconHost() { instance_, 0); gfx::CheckWindowCreated(window_, ::GetLastError()); gfx::SetWindowUserData(window_, this); + + mouse_entered_exited_detector_ = + std::make_unique<MouseEnteredExitedDetector>(); } NotifyIconHost::~NotifyIconHost() { @@ -116,6 +220,8 @@ void NotifyIconHost::Remove(NotifyIcon* icon) { return; } + mouse_entered_exited_detector_->IconRemoved(*i); + notify_icons_.erase(i); } @@ -208,6 +314,8 @@ LRESULT CALLBACK NotifyIconHost::WndProc(HWND hwnd, return TRUE; case WM_MOUSEMOVE: + mouse_entered_exited_detector_->MouseMoveEvent(win_icon); + content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&NotifyIcon::HandleMouseMoveEvent, win_icon_weak, GetKeyboardModifiers())); diff --git a/shell/browser/ui/win/notify_icon_host.h b/shell/browser/ui/win/notify_icon_host.h index 85a7537a3e..3b5ce54626 100644 --- a/shell/browser/ui/win/notify_icon_host.h +++ b/shell/browser/ui/win/notify_icon_host.h @@ -64,6 +64,9 @@ class NotifyIconHost { // The message ID of the "TaskbarCreated" message, sent to us when we need to // reset our status icons. UINT taskbar_created_message_ = 0; + + class MouseEnteredExitedDetector; + std::unique_ptr<MouseEnteredExitedDetector> mouse_entered_exited_detector_; }; } // namespace electron
feat
233724fe00b25a1515fb011ca2b3052cf6f5620a
Charles Kerr
2024-09-17 14:58:56
chore: iwyu mojom-forward header files (#43741) * chore: iwyu mojom.h headers * fixup! chore: iwyu mojom.h headers make previously-indirect include dependency direct * fixup! fixup! chore: iwyu mojom.h headers make previously-indirect include dependency direct
diff --git a/shell/browser/api/electron_api_cookies.h b/shell/browser/api/electron_api_cookies.h index df509fdb1d..64b2417927 100644 --- a/shell/browser/api/electron_api_cookies.h +++ b/shell/browser/api/electron_api_cookies.h @@ -12,6 +12,8 @@ #include "base/values.h" #include "shell/browser/event_emitter_mixin.h" +class GURL; + namespace gin { template <typename T> class Handle; diff --git a/shell/browser/api/electron_api_power_monitor_win.cc b/shell/browser/api/electron_api_power_monitor_win.cc index e08e191b42..7668234bb3 100644 --- a/shell/browser/api/electron_api_power_monitor_win.cc +++ b/shell/browser/api/electron_api_power_monitor_win.cc @@ -7,6 +7,7 @@ #include <windows.h> #include <wtsapi32.h> +#include "base/logging.h" #include "base/win/windows_types.h" #include "base/win/wrapped_window_proc.h" #include "content/public/browser/browser_task_traits.h" diff --git a/shell/browser/api/electron_api_session.h b/shell/browser/api/electron_api_session.h index 8e921eb290..e603e77f36 100644 --- a/shell/browser/api/electron_api_session.h +++ b/shell/browser/api/electron_api_session.h @@ -16,8 +16,8 @@ #include "content/public/browser/download_manager.h" #include "electron/buildflags/buildflags.h" #include "gin/wrappable.h" -#include "services/network/public/mojom/host_resolver.mojom.h" -#include "services/network/public/mojom/ssl_config.mojom.h" +#include "services/network/public/mojom/host_resolver.mojom-forward.h" +#include "services/network/public/mojom/ssl_config.mojom-forward.h" #include "shell/browser/event_emitter_mixin.h" #include "shell/browser/net/resolve_proxy_helper.h" #include "shell/common/gin_helper/cleaned_up_at_exit.h" diff --git a/shell/browser/api/electron_api_web_contents.h b/shell/browser/api/electron_api_web_contents.h index 6c38316350..54aa02ef02 100644 --- a/shell/browser/api/electron_api_web_contents.h +++ b/shell/browser/api/electron_api_web_contents.h @@ -22,7 +22,7 @@ #include "chrome/browser/devtools/devtools_file_system_indexer.h" #include "chrome/browser/ui/exclusive_access/exclusive_access_context.h" // nogncheck #include "chrome/browser/ui/exclusive_access/exclusive_access_manager.h" -#include "content/common/frame.mojom.h" +#include "content/common/frame.mojom-forward.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/devtools_agent_host.h" #include "content/public/browser/javascript_dialog_manager.h" @@ -51,7 +51,7 @@ #endif #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) -#include "extensions/common/mojom/view_type.mojom.h" +#include "extensions/common/mojom/view_type.mojom-forward.h" namespace extensions { class ScriptExecutor; diff --git a/shell/browser/api/electron_api_web_frame_main.h b/shell/browser/api/electron_api_web_frame_main.h index ec86f3edcc..d6df233ea5 100644 --- a/shell/browser/api/electron_api_web_frame_main.h +++ b/shell/browser/api/electron_api_web_frame_main.h @@ -16,6 +16,7 @@ #include "mojo/public/cpp/bindings/pending_receiver.h" #include "mojo/public/cpp/bindings/remote.h" #include "shell/browser/event_emitter_mixin.h" +#include "shell/common/api/api.mojom.h" #include "shell/common/gin_helper/constructible.h" #include "shell/common/gin_helper/pinnable.h" #include "third_party/blink/public/mojom/page/page_visibility_state.mojom-forward.h" diff --git a/shell/browser/electron_browser_context.h b/shell/browser/electron_browser_context.h index 0a0698a23a..3088d98624 100644 --- a/shell/browser/electron_browser_context.h +++ b/shell/browser/electron_browser_context.h @@ -21,8 +21,7 @@ #include "electron/buildflags/buildflags.h" #include "electron/shell/browser/media/media_device_id_salt.h" #include "mojo/public/cpp/bindings/remote.h" -#include "services/network/public/mojom/network_context.mojom.h" -#include "services/network/public/mojom/url_loader_factory.mojom.h" +#include "services/network/public/mojom/ssl_config.mojom.h" #include "third_party/blink/public/common/permissions/permission_utils.h" class PrefService; diff --git a/shell/browser/electron_browser_main_parts.cc b/shell/browser/electron_browser_main_parts.cc index 504684f9a2..f8f87353b8 100644 --- a/shell/browser/electron_browser_main_parts.cc +++ b/shell/browser/electron_browser_main_parts.cc @@ -68,6 +68,7 @@ #include "ui/base/ui_base_switches.h" #include "ui/color/color_provider_manager.h" #include "ui/display/screen.h" +#include "ui/views/layout/layout_provider.h" #include "url/url_util.h" #if defined(USE_AURA) diff --git a/shell/browser/electron_browser_main_parts.h b/shell/browser/electron_browser_main_parts.h index 9cd21819e4..ebf3e10ff1 100644 --- a/shell/browser/electron_browser_main_parts.h +++ b/shell/browser/electron_browser_main_parts.h @@ -11,12 +11,10 @@ #include "base/functional/callback_forward.h" #include "base/task/single_thread_task_runner.h" -#include "content/public/browser/browser_context.h" #include "content/public/browser/browser_main_parts.h" #include "electron/buildflags/buildflags.h" #include "mojo/public/cpp/bindings/remote.h" #include "services/device/public/mojom/geolocation_control.mojom.h" -#include "ui/views/layout/layout_provider.h" class BrowserProcessImpl; class IconManager; @@ -49,6 +47,10 @@ class LinuxUiGetter; class DarkModeManagerLinux; } // namespace ui +namespace views { +class LayoutProvider; +} // namespace views + namespace electron { class Browser; diff --git a/shell/browser/extended_web_contents_observer.h b/shell/browser/extended_web_contents_observer.h index 9152559dd3..39b204d83f 100644 --- a/shell/browser/extended_web_contents_observer.h +++ b/shell/browser/extended_web_contents_observer.h @@ -8,7 +8,6 @@ #include <string> #include "base/observer_list_types.h" -#include "electron/shell/common/api/api.mojom.h" namespace gfx { class Rect; diff --git a/shell/browser/extensions/api/scripting/scripting_api.h b/shell/browser/extensions/api/scripting/scripting_api.h index 3b53f5e2e9..fb29103bbb 100644 --- a/shell/browser/extensions/api/scripting/scripting_api.h +++ b/shell/browser/extensions/api/scripting/scripting_api.h @@ -15,7 +15,7 @@ #include "extensions/browser/extension_function.h" #include "extensions/browser/script_executor.h" #include "extensions/browser/scripting_utils.h" -#include "extensions/common/mojom/code_injection.mojom.h" +#include "extensions/common/mojom/code_injection.mojom-forward.h" #include "extensions/common/user_script.h" namespace extensions { diff --git a/shell/browser/extensions/api/streams_private/streams_private_api.h b/shell/browser/extensions/api/streams_private/streams_private_api.h index 9e4467d056..92d0d3bc79 100644 --- a/shell/browser/extensions/api/streams_private/streams_private_api.h +++ b/shell/browser/extensions/api/streams_private/streams_private_api.h @@ -7,7 +7,9 @@ #include <string> -#include "third_party/blink/public/mojom/loader/transferrable_url_loader.mojom.h" +#include "third_party/blink/public/mojom/loader/transferrable_url_loader.mojom-forward.h" + +class GURL; namespace extensions { diff --git a/shell/browser/hid/electron_hid_delegate.cc b/shell/browser/hid/electron_hid_delegate.cc index 1058dc7897..6f349d3d6d 100644 --- a/shell/browser/hid/electron_hid_delegate.cc +++ b/shell/browser/hid/electron_hid_delegate.cc @@ -20,6 +20,7 @@ #include "shell/browser/hid/hid_chooser_controller.h" #include "shell/browser/web_contents_permission_helper.h" #include "third_party/blink/public/common/permissions/permission_utils.h" +#include "third_party/blink/public/mojom/hid/hid.mojom.h" #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #include "extensions/common/constants.h" diff --git a/shell/browser/hid/hid_chooser_controller.cc b/shell/browser/hid/hid_chooser_controller.cc index 25ec46b853..d7e229232f 100644 --- a/shell/browser/hid/hid_chooser_controller.cc +++ b/shell/browser/hid/hid_chooser_controller.cc @@ -25,6 +25,8 @@ #include "shell/common/gin_converters/hid_device_info_converter.h" #include "shell/common/gin_converters/value_converter.h" #include "shell/common/node_util.h" +#include "third_party/blink/public/mojom/devtools/console_message.mojom.h" +#include "third_party/blink/public/mojom/hid/hid.mojom.h" #include "ui/base/l10n/l10n_util.h" namespace { diff --git a/shell/browser/hid/hid_chooser_controller.h b/shell/browser/hid/hid_chooser_controller.h index 07a1f099b4..87ac13ca58 100644 --- a/shell/browser/hid/hid_chooser_controller.h +++ b/shell/browser/hid/hid_chooser_controller.h @@ -18,8 +18,8 @@ #include "services/device/public/mojom/hid.mojom-forward.h" #include "shell/browser/hid/hid_chooser_context.h" #include "shell/common/gin_converters/frame_converter.h" -#include "third_party/blink/public/mojom/devtools/console_message.mojom.h" -#include "third_party/blink/public/mojom/hid/hid.mojom.h" +#include "third_party/blink/public/mojom/devtools/console_message.mojom-forward.h" +#include "third_party/blink/public/mojom/hid/hid.mojom-forward.h" namespace content { class RenderFrameHost; diff --git a/shell/browser/media/media_capture_devices_dispatcher.h b/shell/browser/media/media_capture_devices_dispatcher.h index 0605622e9a..3fc609f299 100644 --- a/shell/browser/media/media_capture_devices_dispatcher.h +++ b/shell/browser/media/media_capture_devices_dispatcher.h @@ -5,10 +5,10 @@ #ifndef ELECTRON_SHELL_BROWSER_MEDIA_MEDIA_CAPTURE_DEVICES_DISPATCHER_H_ #define ELECTRON_SHELL_BROWSER_MEDIA_MEDIA_CAPTURE_DEVICES_DISPATCHER_H_ +#include "base/no_destructor.h" #include "components/webrtc/media_stream_device_enumerator_impl.h" #include "content/public/browser/media_observer.h" -#include "third_party/blink/public/common/mediastream/media_stream_request.h" -#include "third_party/blink/public/mojom/mediastream/media_stream.mojom.h" +#include "third_party/blink/public/mojom/mediastream/media_stream.mojom-forward.h" namespace electron { diff --git a/shell/browser/native_window.h b/shell/browser/native_window.h index a821fde6cc..3fdd983aad 100644 --- a/shell/browser/native_window.h +++ b/shell/browser/native_window.h @@ -18,7 +18,6 @@ #include "base/supports_user_data.h" #include "content/public/browser/desktop_media_id.h" #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/native_window_observer.h" #include "ui/views/widget/widget_delegate.h" diff --git a/shell/browser/native_window_mac.h b/shell/browser/native_window_mac.h index cb39aab484..a841f2dd5f 100644 --- a/shell/browser/native_window_mac.h +++ b/shell/browser/native_window_mac.h @@ -13,7 +13,6 @@ #include <vector> #include "base/memory/raw_ptr.h" -#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" diff --git a/shell/browser/net/electron_url_loader_factory.h b/shell/browser/net/electron_url_loader_factory.h index b9fc5d8c93..f73a8cd9ed 100644 --- a/shell/browser/net/electron_url_loader_factory.h +++ b/shell/browser/net/electron_url_loader_factory.h @@ -19,7 +19,7 @@ #include "services/network/public/cpp/self_deleting_url_loader_factory.h" #include "services/network/public/mojom/url_loader.mojom.h" #include "services/network/public/mojom/url_loader_factory.mojom.h" -#include "services/network/public/mojom/url_response_head.mojom.h" +#include "services/network/public/mojom/url_response_head.mojom-forward.h" #include "v8/include/v8-array-buffer.h" namespace gin { diff --git a/shell/browser/net/network_context_service.h b/shell/browser/net/network_context_service.h index b9542360dc..42efd6c212 100644 --- a/shell/browser/net/network_context_service.h +++ b/shell/browser/net/network_context_service.h @@ -8,8 +8,8 @@ #include "base/memory/raw_ptr.h" #include "chrome/browser/net/proxy_config_monitor.h" #include "components/keyed_service/core/keyed_service.h" -#include "services/cert_verifier/public/mojom/cert_verifier_service_factory.mojom.h" -#include "services/network/public/mojom/network_context.mojom.h" +#include "services/cert_verifier/public/mojom/cert_verifier_service_factory.mojom-forward.h" +#include "services/network/public/mojom/network_context.mojom-forward.h" namespace base { class FilePath; diff --git a/shell/browser/net/proxying_url_loader_factory.cc b/shell/browser/net/proxying_url_loader_factory.cc index 93f1fa5622..3bef7f74c9 100644 --- a/shell/browser/net/proxying_url_loader_factory.cc +++ b/shell/browser/net/proxying_url_loader_factory.cc @@ -22,6 +22,7 @@ #include "net/url_request/redirect_info.h" #include "services/network/public/cpp/features.h" #include "services/network/public/mojom/early_hints.mojom.h" +#include "services/network/public/mojom/url_response_head.mojom.h" #include "shell/browser/net/asar/asar_url_loader.h" #include "shell/common/options_switches.h" #include "url/origin.h" diff --git a/shell/browser/net/proxying_url_loader_factory.h b/shell/browser/net/proxying_url_loader_factory.h index 58add4c8f0..2426d9d8f1 100644 --- a/shell/browser/net/proxying_url_loader_factory.h +++ b/shell/browser/net/proxying_url_loader_factory.h @@ -27,7 +27,7 @@ #include "services/network/public/mojom/network_context.mojom.h" #include "services/network/public/mojom/url_loader.mojom.h" #include "services/network/public/mojom/url_loader_factory.mojom.h" -#include "services/network/public/mojom/url_response_head.mojom.h" +#include "services/network/public/mojom/url_response_head.mojom-forward.h" #include "services/network/url_loader_factory.h" #include "shell/browser/net/electron_url_loader_factory.h" #include "shell/browser/net/web_request_api_interface.h" diff --git a/shell/browser/net/resolve_host_function.h b/shell/browser/net/resolve_host_function.h index 37b5e5f806..56afad28bc 100644 --- a/shell/browser/net/resolve_host_function.h +++ b/shell/browser/net/resolve_host_function.h @@ -14,7 +14,6 @@ #include "mojo/public/cpp/bindings/receiver.h" #include "services/network/public/cpp/resolve_host_client_base.h" #include "services/network/public/mojom/host_resolver.mojom.h" -#include "services/network/public/mojom/network_context.mojom.h" namespace net { class AddressList; diff --git a/shell/browser/net/system_network_context_manager.cc b/shell/browser/net/system_network_context_manager.cc index 8b8beac393..016d1b2300 100644 --- a/shell/browser/net/system_network_context_manager.cc +++ b/shell/browser/net/system_network_context_manager.cc @@ -33,6 +33,7 @@ #include "services/network/public/cpp/features.h" #include "services/network/public/cpp/shared_url_loader_factory.h" #include "services/network/public/mojom/network_context.mojom.h" +#include "services/network/public/mojom/url_response_head.mojom.h" #include "shell/browser/browser.h" #include "shell/browser/electron_browser_client.h" #include "shell/common/application_info.h" diff --git a/shell/browser/net/system_network_context_manager.h b/shell/browser/net/system_network_context_manager.h index a8e9a6e554..3f0265dbad 100644 --- a/shell/browser/net/system_network_context_manager.h +++ b/shell/browser/net/system_network_context_manager.h @@ -10,9 +10,8 @@ #include "sandbox/policy/features.h" #include "services/network/public/cpp/shared_url_loader_factory.h" #include "services/network/public/mojom/network_context.mojom.h" -#include "services/network/public/mojom/network_service.mojom.h" -#include "services/network/public/mojom/url_loader.mojom.h" -#include "services/network/public/mojom/url_loader_factory.mojom.h" +#include "services/network/public/mojom/network_service.mojom-forward.h" +#include "services/network/public/mojom/url_loader_factory.mojom-forward.h" namespace electron { network::mojom::HttpAuthDynamicParamsPtr CreateHttpAuthDynamicParams(); diff --git a/shell/browser/serial/serial_chooser_controller.h b/shell/browser/serial/serial_chooser_controller.h index 2726422174..fd94ebe3da 100644 --- a/shell/browser/serial/serial_chooser_controller.h +++ b/shell/browser/serial/serial_chooser_controller.h @@ -15,7 +15,7 @@ #include "content/public/browser/web_contents_observer.h" #include "services/device/public/mojom/serial.mojom-forward.h" #include "shell/browser/serial/serial_chooser_context.h" -#include "third_party/blink/public/mojom/serial/serial.mojom.h" +#include "third_party/blink/public/mojom/serial/serial.mojom-forward.h" namespace content { class RenderFrameHost; diff --git a/shell/browser/ui/drag_util.h b/shell/browser/ui/drag_util.h index 0c7c35e7ba..55fed34ca0 100644 --- a/shell/browser/ui/drag_util.h +++ b/shell/browser/ui/drag_util.h @@ -8,7 +8,6 @@ #include <memory> #include <vector> -#include "electron/shell/common/api/api.mojom.h" #include "third_party/blink/public/mojom/page/draggable_region.mojom-forward.h" #include "ui/gfx/native_widget_types.h" diff --git a/shell/browser/ui/inspectable_web_contents.cc b/shell/browser/ui/inspectable_web_contents.cc index baf05dbda3..43f44c476d 100644 --- a/shell/browser/ui/inspectable_web_contents.cc +++ b/shell/browser/ui/inspectable_web_contents.cc @@ -41,6 +41,7 @@ #include "services/network/public/cpp/simple_url_loader.h" #include "services/network/public/cpp/simple_url_loader_stream_consumer.h" #include "services/network/public/cpp/wrapper_shared_url_loader_factory.h" +#include "services/network/public/mojom/url_response_head.mojom.h" #include "shell/browser/api/electron_api_web_contents.h" #include "shell/browser/native_window_views.h" #include "shell/browser/net/asar/asar_url_loader_factory.h" diff --git a/shell/browser/ui/inspectable_web_contents_view.h b/shell/browser/ui/inspectable_web_contents_view.h index 3155829377..a9c95d477e 100644 --- a/shell/browser/ui/inspectable_web_contents_view.h +++ b/shell/browser/ui/inspectable_web_contents_view.h @@ -9,7 +9,7 @@ #include <string> #include "base/memory/raw_ptr.h" -#include "electron/shell/common/api/api.mojom.h" +#include "build/build_config.h" #if defined(TOOLKIT_VIEWS) && !BUILDFLAG(IS_MAC) #include "ui/views/view.h" diff --git a/shell/browser/ui/win/taskbar_host.cc b/shell/browser/ui/win/taskbar_host.cc index e75211bce4..a4c6e988ff 100644 --- a/shell/browser/ui/win/taskbar_host.cc +++ b/shell/browser/ui/win/taskbar_host.cc @@ -13,6 +13,7 @@ #include "skia/ext/image_operations.h" #include "third_party/skia/include/core/SkBitmap.h" #include "third_party/skia/include/core/SkCanvas.h" +#include "third_party/skia/include/core/SkImage.h" #include "third_party/skia/include/core/SkRRect.h" #include "ui/display/win/screen_win.h" #include "ui/gfx/icon_util.h" diff --git a/shell/browser/usb/usb_chooser_controller.h b/shell/browser/usb/usb_chooser_controller.h index 1efc724462..e2eaa60354 100644 --- a/shell/browser/usb/usb_chooser_controller.h +++ b/shell/browser/usb/usb_chooser_controller.h @@ -10,7 +10,7 @@ #include "base/memory/weak_ptr.h" #include "base/scoped_observation.h" #include "content/public/browser/web_contents_observer.h" -#include "services/device/public/mojom/usb_device.mojom.h" +#include "services/device/public/mojom/usb_device.mojom-forward.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" diff --git a/shell/browser/web_contents_permission_helper.cc b/shell/browser/web_contents_permission_helper.cc index ff3c01c34b..81841dbbf5 100644 --- a/shell/browser/web_contents_permission_helper.cc +++ b/shell/browser/web_contents_permission_helper.cc @@ -15,6 +15,8 @@ #include "shell/browser/electron_browser_context.h" #include "shell/browser/electron_permission_manager.h" #include "shell/browser/media/media_capture_devices_dispatcher.h" +#include "third_party/blink/public/common/mediastream/media_stream_request.h" +#include "third_party/blink/public/mojom/mediastream/media_stream.mojom.h" #if BUILDFLAG(IS_MAC) #include "chrome/browser/media/webrtc/system_media_capture_permissions_mac.h" diff --git a/shell/common/gin_converters/content_converter.cc b/shell/common/gin_converters/content_converter.cc index 180cdbbad1..3505bf30da 100644 --- a/shell/common/gin_converters/content_converter.cc +++ b/shell/common/gin_converters/content_converter.cc @@ -20,6 +20,7 @@ #include "shell/common/gin_converters/gurl_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "third_party/blink/public/common/context_menu_data/untrustworthy_context_menu_params.h" +#include "third_party/blink/public/mojom/permissions/permission_status.mojom.h" #include "ui/events/keycodes/dom/keycode_converter.h" #include "ui/events/keycodes/keyboard_code_conversion.h" diff --git a/shell/common/gin_converters/content_converter.h b/shell/common/gin_converters/content_converter.h index 99f74e89b0..760fe41971 100644 --- a/shell/common/gin_converters/content_converter.h +++ b/shell/common/gin_converters/content_converter.h @@ -12,7 +12,7 @@ #include "gin/converter.h" #include "third_party/blink/public/common/permissions/permission_utils.h" #include "third_party/blink/public/mojom/choosers/popup_menu.mojom.h" -#include "third_party/blink/public/mojom/permissions/permission_status.mojom.h" +#include "third_party/blink/public/mojom/permissions/permission_status.mojom-forward.h" #include "ui/base/ui_base_types.h" namespace content { diff --git a/shell/common/gin_converters/net_converter.cc b/shell/common/gin_converters/net_converter.cc index 9ecee92920..5fdb730c0f 100644 --- a/shell/common/gin_converters/net_converter.cc +++ b/shell/common/gin_converters/net_converter.cc @@ -26,6 +26,8 @@ #include "services/network/public/cpp/resource_request.h" #include "services/network/public/cpp/resource_request_body.h" #include "services/network/public/mojom/chunked_data_pipe_getter.mojom.h" +#include "services/network/public/mojom/fetch_api.mojom.h" +#include "services/network/public/mojom/url_request.mojom.h" #include "shell/browser/api/electron_api_data_pipe_holder.h" #include "shell/common/gin_converters/gurl_converter.h" #include "shell/common/gin_converters/std_converter.h" diff --git a/shell/common/gin_converters/net_converter.h b/shell/common/gin_converters/net_converter.h index d14cfa4d67..6ba6fa413b 100644 --- a/shell/common/gin_converters/net_converter.h +++ b/shell/common/gin_converters/net_converter.h @@ -9,9 +9,8 @@ #include <vector> #include "gin/converter.h" -#include "services/network/public/mojom/fetch_api.mojom.h" +#include "services/network/public/mojom/host_resolver.mojom-forward.h" #include "services/network/public/mojom/host_resolver.mojom.h" -#include "services/network/public/mojom/url_request.mojom.h" #include "shell/browser/net/cert_verifier_client.h" namespace net { @@ -24,7 +23,8 @@ class HttpVersion; namespace network { struct ResourceRequest; -} +class ResourceRequestBody; +} // namespace network namespace gin { diff --git a/shell/common/gin_helper/event_emitter.h b/shell/common/gin_helper/event_emitter.h index 5b5fe86dd0..379181d79b 100644 --- a/shell/common/gin_helper/event_emitter.h +++ b/shell/common/gin_helper/event_emitter.h @@ -8,7 +8,6 @@ #include <string_view> #include <utility> -#include "electron/shell/common/api/api.mojom.h" #include "gin/handle.h" #include "shell/common/gin_helper/event.h" #include "shell/common/gin_helper/event_emitter_caller.h"
chore
2571396584b698ab30181e62cd444e29ac51dbee
Cheng Zhao
2024-01-29 10:42:59
fix: update osk patch to fix more corner cases (#41131) This is a follow up to https://github.com/electron/electron/pull/35921 that, it fixes more corner cases that on-screen-keyboard does not hide for webviews. This change has been applied in Teams for quite a while and should be reliable enough to introduce to Electron.
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 c9ed7308d2..9a44e9fcef 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 @@ -3,47 +3,89 @@ From: Kyrylo Hrechykhin <[email protected]> Date: Thu, 6 Oct 2022 18:30:53 +0200 Subject: fix: on-screen-keyboard hides on input blur in webview -Changes introduced by this patch fix issue where OSK does not hide on -input rendered inside webview is blurred. This patch should be removed -when proper fix in chromium repo is available. - -Note: the issue still occurs if input rendered in webview blurred due -to touch outside of webview. It is caused by webview implementation -details. Specificaly due to webview has its own tree nodes and focused -node does not change in this case. +Work around OSK not hiding by notifying RenderWidgetHostViewAura of +focus node change via TextInputManager. chromium-bug: https://crbug.com/1369605 -diff --git a/content/browser/renderer_host/render_widget_host_view_child_frame.cc b/content/browser/renderer_host/render_widget_host_view_child_frame.cc -index 090d9d58eddac80f8bd191ac4754d2e8d87c1b39..0c5c78020b98795f51f375a526f06599f9c9a273 100644 ---- a/content/browser/renderer_host/render_widget_host_view_child_frame.cc -+++ b/content/browser/renderer_host/render_widget_host_view_child_frame.cc -@@ -1039,6 +1039,12 @@ RenderWidgetHostViewChildFrame::DidUpdateVisualProperties( - return viz::ScopedSurfaceIdAllocator(std::move(allocation_task)); +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 +--- 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( + } + } + ++void RenderWidgetHostViewAura::OnFocusedInputElementChanged( ++ TextInputManager* text_input_manager, ++ RenderWidgetHostViewBase* view) { ++ FocusedNodeChanged(false, {}); ++} ++ + void RenderWidgetHostViewAura::SetPopupChild( + 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 +--- 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 + RenderWidgetHostViewBase* updated_view) override; + void OnTextSelectionChanged(TextInputManager* text_input_mangager, + RenderWidgetHostViewBase* updated_view) override; ++ void OnFocusedInputElementChanged(TextInputManager* text_input_manager, ++ RenderWidgetHostViewBase* view) override; + + // Detaches |this| from the input method object. + // is_removed flag is true if this is called while the window is +diff --git a/content/browser/renderer_host/text_input_manager.cc b/content/browser/renderer_host/text_input_manager.cc +index a73f08700e77443b1229ee35f99356be57d376f5..d37da7f122cdd326499d9e89fc83bef89d726014 100644 +--- a/content/browser/renderer_host/text_input_manager.cc ++++ b/content/browser/renderer_host/text_input_manager.cc +@@ -167,6 +167,7 @@ void TextInputManager::UpdateTextInputState( + + if (text_input_state.type == ui::TEXT_INPUT_TYPE_NONE && + active_view_ != view) { ++ NotifyFocusedInputElementChanged(active_view_); + // We reached here because an IPC is received to reset the TextInputState + // for |view|. But |view| != |active_view_|, which suggests that at least + // one other view has become active and we have received the corresponding +@@ -453,6 +454,12 @@ void TextInputManager::NotifyObserversAboutInputStateUpdate( + observer.OnUpdateTextInputStateCalled(this, updated_view, did_update_state); } -+void RenderWidgetHostViewChildFrame::FocusedNodeChanged( -+ bool is_editable_node, -+ const gfx::Rect& node_bounds_in_screen) { -+ NOTREACHED(); ++void TextInputManager::NotifyFocusedInputElementChanged( ++ RenderWidgetHostViewBase* view) { ++ for (auto& observer : observer_list_) ++ observer.OnFocusedInputElementChanged(this, view); +} + - ui::TextInputType RenderWidgetHostViewChildFrame::GetTextInputType() const { - if (!text_input_manager_) - return ui::TEXT_INPUT_TYPE_NONE; -diff --git a/content/browser/renderer_host/render_widget_host_view_child_frame.h b/content/browser/renderer_host/render_widget_host_view_child_frame.h -index 58b3038d3aa7ed6babab2e9f6ffe9e4670656243..b2adee153030e0e3c3bf8ae3c2877d78dce56929 100644 ---- a/content/browser/renderer_host/render_widget_host_view_child_frame.h -+++ b/content/browser/renderer_host/render_widget_host_view_child_frame.h -@@ -181,6 +181,8 @@ class CONTENT_EXPORT RenderWidgetHostViewChildFrame - void DisableAutoResize(const gfx::Size& new_size) override; - viz::ScopedSurfaceIdAllocator DidUpdateVisualProperties( - const cc::RenderFrameMetadata& metadata) override; -+ void FocusedNodeChanged(bool is_editable_node, -+ const gfx::Rect& node_bounds_in_screen) override; - - // RenderFrameMetadataProvider::Observer implementation. - void OnRenderFrameMetadataChangedBeforeActivation( + TextInputManager::SelectionRegion::SelectionRegion() = default; + + TextInputManager::SelectionRegion::SelectionRegion( +diff --git a/content/browser/renderer_host/text_input_manager.h b/content/browser/renderer_host/text_input_manager.h +index 01993347572548e46d8583c0bb568be4f12c7207..c679db5de0e2b60867b8f4b30c9b72b63420d694 100644 +--- a/content/browser/renderer_host/text_input_manager.h ++++ b/content/browser/renderer_host/text_input_manager.h +@@ -71,6 +71,10 @@ class CONTENT_EXPORT TextInputManager { + virtual void OnTextSelectionChanged( + TextInputManager* text_input_manager, + RenderWidgetHostViewBase* updated_view) {} ++ // Called when focused input element has changed ++ virtual void OnFocusedInputElementChanged( ++ TextInputManager* text_input_manager, ++ RenderWidgetHostViewBase* updated_view) {} + }; + + // Text selection bounds. +@@ -277,6 +281,7 @@ class CONTENT_EXPORT TextInputManager { + + void NotifyObserversAboutInputStateUpdate(RenderWidgetHostViewBase* view, + bool did_update_state); ++ void NotifyFocusedInputElementChanged(RenderWidgetHostViewBase* view); + + // The view with active text input state, i.e., a focused <input> element. + // It will be nullptr if no such view exists. Note that the active view diff --git a/content/browser/web_contents/web_contents_impl.cc b/content/browser/web_contents/web_contents_impl.cc index 1b1983d2ecdbd14bf4e897e43cce6f4182a842cb..28afdf5395ae78dd0c5c7612b8b47efae7e837a3 100644 --- a/content/browser/web_contents/web_contents_impl.cc
fix
141175c723faef132d2452f7b6669f90d5704627
Keeley Hammond
2023-05-10 20:53:18
build: disable v8 builtins pgo (#38252)
diff --git a/build/args/all.gn b/build/args/all.gn index 08f489d261..74769f6c97 100644 --- a/build/args/all.gn +++ b/build/args/all.gn @@ -52,3 +52,6 @@ use_perfetto_client_library = false # Ref: https://chromium-review.googlesource.com/c/chromium/src/+/4402277 enable_check_raw_ptr_fields = false + +# Disables the builtins PGO for V8 +v8_builtins_profiling_log_file = ""
build
73e7125041339bf0fc319242a00fdb75d4554895
Charles Kerr
2024-01-05 17:54:41
chore: do not inject DXVA_Decoding trace category (#40891) This doesn't need to be injected. Looks like it was an accident in 60ca38fb for https://github.com/electron/electron/pull/38465 .
diff --git a/patches/chromium/build_add_electron_tracing_category.patch b/patches/chromium/build_add_electron_tracing_category.patch index ab56f41b62..c640c61e27 100644 --- a/patches/chromium/build_add_electron_tracing_category.patch +++ b/patches/chromium/build_add_electron_tracing_category.patch @@ -8,14 +8,13 @@ categories in use are known / declared. This patch is required for us to introduce a new Electron category for Electron-specific tracing. diff --git a/base/trace_event/builtin_categories.h b/base/trace_event/builtin_categories.h -index 0cc26b32992cbbd5f599e0e062dd5b22bbf6d2dc..fd6a0eebd004f9e92ba577d73dfa75f685476288 100644 +index 0cc26b32992cbbd5f599e0e062dd5b22bbf6d2dc..2bc3fea0bc469a0cf26fa2a5af9c404294078f4a 100644 --- a/base/trace_event/builtin_categories.h +++ b/base/trace_event/builtin_categories.h -@@ -82,6 +82,8 @@ +@@ -82,6 +82,7 @@ X("drm") \ X("drmcursor") \ X("dwrite") \ -+ X("DXVA_Decoding") \ + X("electron") \ X("evdev") \ X("event") \
chore
45e5ccc55e8b13a45899bacff5cb98c9994446f2
Charles Kerr
2024-07-31 16:37:04
chore: remove unused KeyWeakMap JS bindings (#43111) The last three pieces of code that used it were removed in: - Oct 2020 (8df4faa8 #25711) - Jun 2020 (e1e73fa5 #24115) - Jun 2020 (c0182bca #24116).
diff --git a/filenames.gni b/filenames.gni index d637df042d..8837002243 100644 --- a/filenames.gni +++ b/filenames.gni @@ -550,7 +550,6 @@ filenames = { "shell/common/api/electron_api_clipboard.h", "shell/common/api/electron_api_command_line.cc", "shell/common/api/electron_api_environment.cc", - "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", diff --git a/shell/common/api/electron_api_key_weak_map.h b/shell/common/api/electron_api_key_weak_map.h deleted file mode 100644 index 2b9d1e92d5..0000000000 --- a/shell/common/api/electron_api_key_weak_map.h +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright (c) 2016 GitHub, Inc. -// Use of this source code is governed by the MIT license that can be -// found in the LICENSE file. - -#ifndef ELECTRON_SHELL_COMMON_API_ELECTRON_API_KEY_WEAK_MAP_H_ -#define ELECTRON_SHELL_COMMON_API_ELECTRON_API_KEY_WEAK_MAP_H_ - -#include "gin/handle.h" -#include "shell/common/gin_converters/std_converter.h" -#include "shell/common/gin_helper/object_template_builder.h" -#include "shell/common/gin_helper/wrappable.h" -#include "shell/common/key_weak_map.h" - -namespace electron::api { - -template <typename K> -class KeyWeakMap : public gin_helper::Wrappable<KeyWeakMap<K>> { - public: - static gin::Handle<KeyWeakMap<K>> Create(v8::Isolate* isolate) { - return gin::CreateHandle(isolate, new KeyWeakMap<K>(isolate)); - } - - static void BuildPrototype(v8::Isolate* isolate, - v8::Local<v8::FunctionTemplate> prototype) { - prototype->SetClassName(gin::StringToV8(isolate, "KeyWeakMap")); - gin_helper::ObjectTemplateBuilder(isolate, prototype->PrototypeTemplate()) - .SetMethod("set", &KeyWeakMap<K>::Set) - .SetMethod("get", &KeyWeakMap<K>::Get) - .SetMethod("has", &KeyWeakMap<K>::Has) - .SetMethod("remove", &KeyWeakMap<K>::Remove); - } - - // disable copy - KeyWeakMap(const KeyWeakMap&) = delete; - KeyWeakMap& operator=(const KeyWeakMap&) = delete; - - protected: - explicit KeyWeakMap(v8::Isolate* isolate) { - gin_helper::Wrappable<KeyWeakMap<K>>::Init(isolate); - } - ~KeyWeakMap() override {} - - private: - // API for KeyWeakMap. - void Set(v8::Isolate* isolate, const K& key, v8::Local<v8::Object> object) { - key_weak_map_.Set(isolate, key, object); - } - - v8::Local<v8::Object> Get(v8::Isolate* isolate, const K& key) { - return key_weak_map_.Get(isolate, key).ToLocalChecked(); - } - - bool Has(const K& key) { return key_weak_map_.Has(key); } - - void Remove(const K& key) { key_weak_map_.Remove(key); } - - electron::KeyWeakMap<K> key_weak_map_; -}; - -} // namespace electron::api - -#endif // ELECTRON_SHELL_COMMON_API_ELECTRON_API_KEY_WEAK_MAP_H_ diff --git a/shell/common/api/electron_api_v8_util.cc b/shell/common/api/electron_api_v8_util.cc index e709c5789c..c02e334897 100644 --- a/shell/common/api/electron_api_v8_util.cc +++ b/shell/common/api/electron_api_v8_util.cc @@ -7,7 +7,6 @@ #include "base/run_loop.h" #include "electron/buildflags/buildflags.h" -#include "shell/common/api/electron_api_key_weak_map.h" #include "shell/common/gin_converters/content_converter.h" #include "shell/common/gin_converters/gurl_converter.h" #include "shell/common/gin_converters/std_converter.h"
chore
54c315c9b0709e9b20c3f96e7b1afddc91841696
Shelley Vohr
2024-06-07 10:06:37
refactor: improve cookie failure rejection messages (#42362)
diff --git a/shell/browser/api/electron_api_cookies.cc b/shell/browser/api/electron_api_cookies.cc index 16522d3a15..98aa412f23 100644 --- a/shell/browser/api/electron_api_cookies.cc +++ b/shell/browser/api/electron_api_cookies.cc @@ -171,25 +171,96 @@ base::Time ParseTimeProperty(const std::optional<double>& value) { return base::Time::FromSecondsSinceUnixEpoch(*value); } -std::string_view InclusionStatusToString(net::CookieInclusionStatus status) { - if (status.HasExclusionReason(net::CookieInclusionStatus::EXCLUDE_HTTP_ONLY)) - return "Failed to create httponly cookie"; - if (status.HasExclusionReason( - net::CookieInclusionStatus::EXCLUDE_SECURE_ONLY)) - return "Cannot create a secure cookie from an insecure URL"; - if (status.HasExclusionReason( - net::CookieInclusionStatus::EXCLUDE_FAILURE_TO_STORE)) - return "Failed to parse cookie"; - if (status.HasExclusionReason( - net::CookieInclusionStatus::EXCLUDE_INVALID_DOMAIN)) - return "Failed to set cookie with an invalid domain attribute"; - if (status.HasExclusionReason( - net::CookieInclusionStatus::EXCLUDE_INVALID_PREFIX)) - return "Failed because the cookie violated prefix rules."; - if (status.HasExclusionReason( - net::CookieInclusionStatus::EXCLUDE_NONCOOKIEABLE_SCHEME)) - return "Cannot set cookie for current scheme"; - return "Setting cookie failed"; +const std::string InclusionStatusToString(net::CookieInclusionStatus status) { + // See net/cookies/cookie_inclusion_status.h for cookie error descriptions. + constexpr std::array< + std::pair<net::CookieInclusionStatus::ExclusionReason, std::string_view>, + net::CookieInclusionStatus::ExclusionReason::NUM_EXCLUSION_REASONS> + exclusion_reasons = { + {{net::CookieInclusionStatus::EXCLUDE_HTTP_ONLY, + "The cookie was HttpOnly, but the attempted access was through a " + "non-HTTP API."}, + {net::CookieInclusionStatus::EXCLUDE_SECURE_ONLY, + "The cookie was Secure, but the URL was not allowed to access " + "Secure cookies."}, + {net::CookieInclusionStatus::EXCLUDE_DOMAIN_MISMATCH, + "The cookie's domain attribute did not match the domain of the URL " + "attempting access."}, + {net::CookieInclusionStatus::EXCLUDE_NOT_ON_PATH, + "The cookie's path attribute did not match the path of the URL " + "attempting access."}, + {net::CookieInclusionStatus::EXCLUDE_SAMESITE_STRICT, + "The cookie had SameSite=Strict, and the attempted access did not " + "have an appropriate SameSiteCookieContext"}, + {net::CookieInclusionStatus::EXCLUDE_SAMESITE_LAX, + "The cookie had SameSite=Lax, and the attempted access did not " + "have " + "an appropriate SameSiteCookieContext"}, + {net::CookieInclusionStatus:: + EXCLUDE_SAMESITE_UNSPECIFIED_TREATED_AS_LAX, + "The cookie did not specify a SameSite attribute, and therefore " + "was " + "treated as if it were SameSite=Lax, and the attempted access did " + "not have an appropriate SameSiteCookieContext."}, + {net::CookieInclusionStatus::EXCLUDE_SAMESITE_NONE_INSECURE, + "The cookie specified SameSite=None, but it was not Secure."}, + {net::CookieInclusionStatus::EXCLUDE_USER_PREFERENCES, + "Caller did not allow access to the cookie."}, + {net::CookieInclusionStatus::EXCLUDE_FAILURE_TO_STORE, + "The cookie was malformed and could not be stored"}, + {net::CookieInclusionStatus::EXCLUDE_NONCOOKIEABLE_SCHEME, + "Attempted to set a cookie from a scheme that does not support " + "cookies."}, + {net::CookieInclusionStatus::EXCLUDE_OVERWRITE_SECURE, + "The cookie would have overwritten a Secure cookie, and was not " + "allowed to do so."}, + {net::CookieInclusionStatus::EXCLUDE_OVERWRITE_HTTP_ONLY, + "The cookie would have overwritten an HttpOnly cookie, and was not " + "allowed to do so."}, + {net::CookieInclusionStatus::EXCLUDE_INVALID_DOMAIN, + "The cookie was set with an invalid Domain attribute."}, + {net::CookieInclusionStatus::EXCLUDE_INVALID_PREFIX, + "The cookie was set with an invalid __Host- or __Secure- prefix."}, + {net::CookieInclusionStatus::EXCLUDE_INVALID_PARTITIONED, + "Cookie was set with an invalid Partitioned attribute, which is " + "only valid if the cookie has a __Host- prefix."}, + {net::CookieInclusionStatus:: + EXCLUDE_NAME_VALUE_PAIR_EXCEEDS_MAX_SIZE, + "The cookie exceeded the name/value pair size limit."}, + {net::CookieInclusionStatus:: + EXCLUDE_ATTRIBUTE_VALUE_EXCEEDS_MAX_SIZE, + "Cookie exceeded the attribute size limit."}, + {net::CookieInclusionStatus::EXCLUDE_DOMAIN_NON_ASCII, + "The cookie was set with a Domain attribute containing non ASCII " + "characters."}, + {net::CookieInclusionStatus:: + EXCLUDE_THIRD_PARTY_BLOCKED_WITHIN_FIRST_PARTY_SET, + "The cookie is blocked by third-party cookie blocking but the two " + "sites are in the same First-Party Set"}, + {net::CookieInclusionStatus::EXCLUDE_PORT_MISMATCH, + "The cookie's source_port did not match the port of the request."}, + {net::CookieInclusionStatus::EXCLUDE_SCHEME_MISMATCH, + "The cookie's source_scheme did not match the scheme of the " + "request."}, + {net::CookieInclusionStatus::EXCLUDE_SHADOWING_DOMAIN, + "The cookie is a domain cookie and has the same name as an origin " + "cookie on this origin."}, + {net::CookieInclusionStatus::EXCLUDE_DISALLOWED_CHARACTER, + "The cookie contains ASCII control characters"}, + {net::CookieInclusionStatus::EXCLUDE_THIRD_PARTY_PHASEOUT, + "The cookie is blocked for third-party cookie phaseout."}, + {net::CookieInclusionStatus::EXCLUDE_NO_COOKIE_CONTENT, + "The cookie contains no content or only whitespace."}}}; + + std::string reason = "Failed to set cookie - "; + for (const auto& [val, str] : exclusion_reasons) { + if (status.HasExclusionReason(val)) { + reason += str; + } + } + + reason += status.GetDebugString(); + return reason; } std::string StringToCookieSameSite(const std::string* str_ptr, diff --git a/spec/api-net-session-spec.ts b/spec/api-net-session-spec.ts index 9f17dc6cd4..82d6b5b985 100644 --- a/spec/api-net-session-spec.ts +++ b/spec/api-net-session-spec.ts @@ -378,7 +378,7 @@ describe('net module (session)', () => { url: 'https://electronjs.org', domain: 'wssss.iamabaddomain.fun', name: 'cookie1' - })).to.eventually.be.rejectedWith(/Failed to set cookie with an invalid domain attribute/); + })).to.eventually.be.rejectedWith(/Failed to set cookie - The cookie was set with an invalid Domain attribute./); }); it('should be able correctly filter out cookies that are session', async () => { diff --git a/spec/api-session-spec.ts b/spec/api-session-spec.ts index 732fae21ef..032e298aa7 100644 --- a/spec/api-session-spec.ts +++ b/spec/api-session-spec.ts @@ -126,24 +126,34 @@ describe('session module', () => { expect(cs.some(c => c.name === name && c.value === value)).to.equal(true); }); - it('yields an error when setting a cookie with missing required fields', async () => { + it('rejects when setting a cookie with missing required fields', async () => { const { cookies } = session.defaultSession; const name = '1'; const value = '1'; await expect( cookies.set({ url: '', name, value }) - ).to.eventually.be.rejectedWith('Failed to set cookie with an invalid domain attribute'); + ).to.eventually.be.rejectedWith('Failed to set cookie - The cookie was set with an invalid Domain attribute.'); }); - it('yields an error when setting a cookie with an invalid URL', async () => { + it('rejects when setting a cookie with an invalid URL', async () => { const { cookies } = session.defaultSession; const name = '1'; const value = '1'; await expect( cookies.set({ url: 'asdf', name, value }) - ).to.eventually.be.rejectedWith('Failed to set cookie with an invalid domain attribute'); + ).to.eventually.be.rejectedWith('Failed to set cookie - The cookie was set with an invalid Domain attribute.'); + }); + + it('rejects when setting a cookie with an invalid ASCII control character', async () => { + const { cookies } = session.defaultSession; + const name = 'BadCookie'; + const value = 'test;test'; + + await expect( + cookies.set({ url, name, value }) + ).to.eventually.be.rejectedWith('Failed to set cookie - The cookie contains ASCII control characters'); }); it('should overwrite previous cookies', async () => {
refactor
500d4f0d05130aeaf26c01da9dde72b5a9d0d65a
Charles Kerr
2024-09-24 15:41:24
fix: -Wunsafe-buffer-usage warning in asar_util's ReadFileToString() (#43896)
diff --git a/shell/common/asar/asar_util.cc b/shell/common/asar/asar_util.cc index cba95a00c4..9acf829392 100644 --- a/shell/common/asar/asar_util.cc +++ b/shell/common/asar/asar_util.cc @@ -126,11 +126,8 @@ bool ReadFileToString(const base::FilePath& path, std::string* contents) { return false; contents->resize(info.size); - if (static_cast<int>(info.size) != - src.Read(info.offset, const_cast<char*>(contents->data()), - contents->size())) { + if (!src.ReadAndCheck(info.offset, base::as_writable_byte_span(*contents))) return false; - } if (info.integrity) ValidateIntegrityOrDie(base::as_byte_span(*contents), *info.integrity);
fix
8eb580e79a55b0b96c6177584ee4ef8a8222b57d
Shelley Vohr
2024-02-08 14:59:46
docs: note EXIF data unsupported in `nativeImage` (#41261) * docs: note EXIF data unsupported in nativeImage * Update docs/api/native-image.md Co-authored-by: David Sanders <[email protected]> --------- Co-authored-by: David Sanders <[email protected]>
diff --git a/docs/api/native-image.md b/docs/api/native-image.md index 6563b67653..24d1d531de 100644 --- a/docs/api/native-image.md +++ b/docs/api/native-image.md @@ -51,6 +51,13 @@ Check the _Size requirements_ section in [this article][icons]. [icons]: https://learn.microsoft.com/en-us/windows/win32/uxguide/vis-icons +:::note + +EXIF metadata is currently not supported and will not be taken into account during +image encoding and decoding. + +::: + ## High Resolution Image On platforms that have high-DPI support such as Apple Retina displays, you can
docs
d069b8fc6611356d9a7d56f21b3221881385767a
Samuel Attard
2023-02-02 17:39:51
build: actually upload symbol zips (#37124)
diff --git a/script/release/uploaders/upload.py b/script/release/uploaders/upload.py index fa00ed397b..fca2f02f76 100755 --- a/script/release/uploaders/upload.py +++ b/script/release/uploaders/upload.py @@ -75,6 +75,11 @@ def main(): electron_zip = os.path.join(OUT_DIR, DIST_NAME) shutil.copy2(os.path.join(OUT_DIR, 'dist.zip'), electron_zip) upload_electron(release, electron_zip, args) + + symbols_zip = os.path.join(OUT_DIR, SYMBOLS_NAME) + shutil.copy2(os.path.join(OUT_DIR, 'symbols.zip'), symbols_zip) + upload_electron(release, symbols_zip, args) + if PLATFORM == 'darwin': if get_platform_key() == 'darwin' and get_target_arch() == 'x64': api_path = os.path.join(ELECTRON_DIR, 'electron-api.json')
build
813853297da17ea1d053a635e5e32f2732f983a9
David Sanders
2023-08-14 18:28:42
ci: automation for deprecation project board (#39477)
diff --git a/.github/workflows/pull-request-labeled.yml b/.github/workflows/pull-request-labeled.yml new file mode 100644 index 0000000000..a60279b5c3 --- /dev/null +++ b/.github/workflows/pull-request-labeled.yml @@ -0,0 +1,33 @@ +name: Pull Request Labeled + +on: + pull_request: + types: [labeled] + +permissions: + contents: read + +jobs: + pull-request-labeled-deprecation-review-complete: + name: deprecation-review/complete label added + if: github.event.label.name == 'deprecation-review/complete ✅' + runs-on: ubuntu-latest + steps: + - name: Generate GitHub App token + id: generate-token + env: + RELEASE_BOARD_GH_APP_CREDS: ${{ secrets.RELEASE_BOARD_GH_APP_CREDS }} + run: | + set -eo pipefail + TOKEN=$(npx @electron/github-app-auth --creds=$RELEASE_BOARD_GH_APP_CREDS --org electron) + echo "TOKEN=$TOKEN" >> "$GITHUB_OUTPUT" + - name: Set status + if: ${{ steps.generate-token.outputs.TOKEN }} + uses: github/update-project-action@2d475e08804f11f4022df7e21f5816531e97cb64 # v2 + with: + github_token: ${{ steps.generate-token.outputs.TOKEN }} + organization: electron + project_number: 94 + content_id: ${{ github.event.pull_request.node_id }} + field: Status + value: ✅ Reviewed
ci
752efddf893b619c09dfaf941136ff4b146e5361
Charles Kerr
2024-05-21 14:21:31
refactor: prefer to inherit observer classes privately (#41360) * refactor: use private inheritance in CookieChangeNotifier * refactor: use private inheritance in WebViewGuestDelegate * refactor: use private inheritance in UsbChooserController * refactor: use private inheritance in DesktopCapturer * refactor: use private inheritance in Browser * refactor: use private inheritance in WebContentsZoomController * refactor: use private inheritance in FrameSubscriber * refactor: use private inheritance in AutofillAgent * refactor: use private inheritance in HidChooserController * refactor: use private inheritance in PepperHelper * refactor: use private inheritance in AutofillPopup * refactor: use private inheritance in SerialChooserController * refactor: use private inheritance in MediaCaptureDevicesDispatcher * refactor: use private inheritance in electron::api::View * refactor: use private inheritance in AutofillDriverFactory * refactor: use private inheritance in GPUInfoManager * refactor: use private inheritance in SavePageHandler * refactor: use private inheritance in GlobalShortcut * refactor: use private inheritance in ElectronRenderFrameObserver
diff --git a/shell/browser/api/electron_api_desktop_capturer.h b/shell/browser/api/electron_api_desktop_capturer.h index 65285086a1..58927aad3d 100644 --- a/shell/browser/api/electron_api_desktop_capturer.h +++ b/shell/browser/api/electron_api_desktop_capturer.h @@ -19,7 +19,7 @@ namespace electron::api { class DesktopCapturer : public gin::Wrappable<DesktopCapturer>, public gin_helper::Pinnable<DesktopCapturer>, - public DesktopMediaListObserver { + private DesktopMediaListObserver { public: struct Source { DesktopMediaList::Source media_list_source; @@ -51,6 +51,7 @@ class DesktopCapturer : public gin::Wrappable<DesktopCapturer>, explicit DesktopCapturer(v8::Isolate* isolate); ~DesktopCapturer() override; + private: // DesktopMediaListObserver: void OnSourceAdded(int index) override {} void OnSourceRemoved(int index) override {} @@ -61,7 +62,6 @@ class DesktopCapturer : public gin::Wrappable<DesktopCapturer>, void OnDelegatedSourceListSelection() override {} void OnDelegatedSourceListDismissed() override {} - private: using OnceCallback = base::OnceClosure; class DesktopListListener : public DesktopMediaListObserver { diff --git a/shell/browser/api/electron_api_global_shortcut.h b/shell/browser/api/electron_api_global_shortcut.h index e5048c1826..b89b8bd4ad 100644 --- a/shell/browser/api/electron_api_global_shortcut.h +++ b/shell/browser/api/electron_api_global_shortcut.h @@ -16,7 +16,7 @@ namespace electron::api { -class GlobalShortcut : public extensions::GlobalShortcutListener::Observer, +class GlobalShortcut : private extensions::GlobalShortcutListener::Observer, public gin::Wrappable<GlobalShortcut> { public: static gin::Handle<GlobalShortcut> Create(v8::Isolate* isolate); diff --git a/shell/browser/api/electron_api_view.h b/shell/browser/api/electron_api_view.h index 708f966c6b..0475d5e6d1 100644 --- a/shell/browser/api/electron_api_view.h +++ b/shell/browser/api/electron_api_view.h @@ -17,7 +17,8 @@ namespace electron::api { -class View : public gin_helper::EventEmitter<View>, public views::ViewObserver { +class View : public gin_helper::EventEmitter<View>, + private views::ViewObserver { public: static gin_helper::WrappableBase* New(gin::Arguments* args); static gin::Handle<View> Create(v8::Isolate* isolate); diff --git a/shell/browser/api/frame_subscriber.h b/shell/browser/api/frame_subscriber.h index 2879ccad56..a4e707e9b7 100644 --- a/shell/browser/api/frame_subscriber.h +++ b/shell/browser/api/frame_subscriber.h @@ -27,8 +27,8 @@ namespace electron::api { class WebContents; -class FrameSubscriber : public content::WebContentsObserver, - public viz::mojom::FrameSinkVideoConsumer { +class FrameSubscriber : private content::WebContentsObserver, + private viz::mojom::FrameSinkVideoConsumer { public: using FrameCaptureCallback = base::RepeatingCallback<void(const gfx::Image&, const gfx::Rect&)>; diff --git a/shell/browser/api/gpuinfo_manager.h b/shell/browser/api/gpuinfo_manager.h index d048ee8a6e..0283c0d337 100644 --- a/shell/browser/api/gpuinfo_manager.h +++ b/shell/browser/api/gpuinfo_manager.h @@ -16,7 +16,7 @@ namespace electron { // GPUInfoManager is a singleton used to manage and fetch GPUInfo -class GPUInfoManager : public content::GpuDataManagerObserver { +class GPUInfoManager : private content::GpuDataManagerObserver { public: static GPUInfoManager* GetInstance(); @@ -29,9 +29,10 @@ class GPUInfoManager : public content::GpuDataManagerObserver { void FetchCompleteInfo(gin_helper::Promise<base::Value> promise); void FetchBasicInfo(gin_helper::Promise<base::Value> promise); - void OnGpuInfoUpdate() override; private: + void OnGpuInfoUpdate() override; + base::Value::Dict EnumerateGPUInfo(gpu::GPUInfo gpu_info) const; // These should be posted to the task queue diff --git a/shell/browser/api/save_page_handler.h b/shell/browser/api/save_page_handler.h index 33328e6c7d..898bdf2d3d 100644 --- a/shell/browser/api/save_page_handler.h +++ b/shell/browser/api/save_page_handler.h @@ -23,8 +23,8 @@ class WebContents; namespace electron::api { // A self-destroyed class for handling save page request. -class SavePageHandler : public content::DownloadManager::Observer, - public download::DownloadItem::Observer { +class SavePageHandler : private content::DownloadManager::Observer, + private download::DownloadItem::Observer { public: SavePageHandler(content::WebContents* web_contents, gin_helper::Promise<void> promise); diff --git a/shell/browser/browser.h b/shell/browser/browser.h index ea08eec4a1..ef5205b046 100644 --- a/shell/browser/browser.h +++ b/shell/browser/browser.h @@ -85,7 +85,7 @@ struct LoginItemSettings { }; // This class is used for control application-wide operations. -class Browser : public WindowListObserver { +class Browser : private WindowListObserver { public: Browser(); ~Browser() override; diff --git a/shell/browser/cookie_change_notifier.h b/shell/browser/cookie_change_notifier.h index 0f00938349..d2e4004616 100644 --- a/shell/browser/cookie_change_notifier.h +++ b/shell/browser/cookie_change_notifier.h @@ -16,7 +16,7 @@ namespace electron { class ElectronBrowserContext; // Sends cookie-change notifications on the UI thread. -class CookieChangeNotifier : public network::mojom::CookieChangeListener { +class CookieChangeNotifier : private network::mojom::CookieChangeListener { public: explicit CookieChangeNotifier(ElectronBrowserContext* browser_context); ~CookieChangeNotifier() override; diff --git a/shell/browser/electron_autofill_driver_factory.h b/shell/browser/electron_autofill_driver_factory.h index 92ca2067bd..84734411e5 100644 --- a/shell/browser/electron_autofill_driver_factory.h +++ b/shell/browser/electron_autofill_driver_factory.h @@ -18,7 +18,7 @@ namespace electron { class AutofillDriver; class AutofillDriverFactory - : public content::WebContentsObserver, + : private content::WebContentsObserver, public content::WebContentsUserData<AutofillDriverFactory> { public: typedef base::OnceCallback<std::unique_ptr<AutofillDriver>()> @@ -31,11 +31,6 @@ class AutofillDriverFactory pending_receiver, content::RenderFrameHost* render_frame_host); - // content::WebContentsObserver: - void RenderFrameDeleted(content::RenderFrameHost* render_frame_host) override; - void DidFinishNavigation( - content::NavigationHandle* navigation_handle) override; - AutofillDriver* DriverForFrame(content::RenderFrameHost* render_frame_host); void AddDriverForFrame(content::RenderFrameHost* render_frame_host, CreationCallback factory_method); @@ -46,6 +41,11 @@ class AutofillDriverFactory WEB_CONTENTS_USER_DATA_KEY_DECL(); private: + // content::WebContentsObserver: + void RenderFrameDeleted(content::RenderFrameHost* render_frame_host) override; + void DidFinishNavigation( + content::NavigationHandle* navigation_handle) override; + explicit AutofillDriverFactory(content::WebContents* web_contents); friend class content::WebContentsUserData<AutofillDriverFactory>; diff --git a/shell/browser/hid/hid_chooser_controller.h b/shell/browser/hid/hid_chooser_controller.h index 823f494df0..edc0c08b8c 100644 --- a/shell/browser/hid/hid_chooser_controller.h +++ b/shell/browser/hid/hid_chooser_controller.h @@ -36,8 +36,8 @@ class HidChooserContext; // HidChooserController provides data for the WebHID API permission prompt. class HidChooserController - : public content::WebContentsObserver, - public electron::HidChooserContext::DeviceObserver { + : private content::WebContentsObserver, + private electron::HidChooserContext::DeviceObserver { public: // Construct a chooser controller for Human Interface Devices (HID). // |render_frame_host| is used to initialize the chooser strings and to access diff --git a/shell/browser/serial/serial_chooser_controller.h b/shell/browser/serial/serial_chooser_controller.h index 1ca1f66d93..aff668edae 100644 --- a/shell/browser/serial/serial_chooser_controller.h +++ b/shell/browser/serial/serial_chooser_controller.h @@ -28,8 +28,9 @@ namespace electron { class ElectronSerialDelegate; // SerialChooserController provides data for the Serial API permission prompt. -class SerialChooserController final : public SerialChooserContext::PortObserver, - public content::WebContentsObserver { +class SerialChooserController final + : private SerialChooserContext::PortObserver, + private content::WebContentsObserver { public: SerialChooserController( content::RenderFrameHost* render_frame_host, diff --git a/shell/browser/ui/autofill_popup.h b/shell/browser/ui/autofill_popup.h index 88dadd3147..52ea7cff0e 100644 --- a/shell/browser/ui/autofill_popup.h +++ b/shell/browser/ui/autofill_popup.h @@ -19,7 +19,7 @@ namespace electron { class AutofillPopupView; -class AutofillPopup : public views::ViewObserver { +class AutofillPopup : private views::ViewObserver { public: AutofillPopup(); ~AutofillPopup() override; diff --git a/shell/browser/usb/usb_chooser_controller.h b/shell/browser/usb/usb_chooser_controller.h index f0219afc71..f2bab4ad28 100644 --- a/shell/browser/usb/usb_chooser_controller.h +++ b/shell/browser/usb/usb_chooser_controller.h @@ -27,8 +27,8 @@ class RenderFrameHost; namespace electron { // UsbChooserController creates a chooser for WebUSB. -class UsbChooserController final : public UsbChooserContext::DeviceObserver, - public content::WebContentsObserver { +class UsbChooserController final : private UsbChooserContext::DeviceObserver, + private content::WebContentsObserver { public: UsbChooserController( content::RenderFrameHost* render_frame_host, diff --git a/shell/browser/web_contents_zoom_controller.h b/shell/browser/web_contents_zoom_controller.h index 20b26c68ee..07cab5c3c5 100644 --- a/shell/browser/web_contents_zoom_controller.h +++ b/shell/browser/web_contents_zoom_controller.h @@ -18,7 +18,7 @@ class WebContentsZoomObserver; // Manages the zoom changes of WebContents. class WebContentsZoomController - : public content::WebContentsObserver, + : private content::WebContentsObserver, public content::WebContentsUserData<WebContentsZoomController> { public: // Defines how zoom changes are handled. diff --git a/shell/browser/web_view_guest_delegate.h b/shell/browser/web_view_guest_delegate.h index 9d7a968e83..8d60bcf654 100644 --- a/shell/browser/web_view_guest_delegate.h +++ b/shell/browser/web_view_guest_delegate.h @@ -19,7 +19,7 @@ class WebContents; } class WebViewGuestDelegate : public content::BrowserPluginGuestDelegate, - public WebContentsZoomObserver { + private WebContentsZoomObserver { public: WebViewGuestDelegate(content::WebContents* embedder, api::WebContents* api_web_contents); diff --git a/shell/renderer/electron_autofill_agent.h b/shell/renderer/electron_autofill_agent.h index a82312c3fc..b3e55f9227 100644 --- a/shell/renderer/electron_autofill_agent.h +++ b/shell/renderer/electron_autofill_agent.h @@ -21,9 +21,9 @@ namespace electron { -class AutofillAgent : public content::RenderFrameObserver, - public blink::WebAutofillClient, - public mojom::ElectronAutofillAgent { +class AutofillAgent : private content::RenderFrameObserver, + private blink::WebAutofillClient, + private mojom::ElectronAutofillAgent { public: explicit AutofillAgent(content::RenderFrame* frame, blink::AssociatedInterfaceRegistry* registry); diff --git a/shell/renderer/electron_render_frame_observer.h b/shell/renderer/electron_render_frame_observer.h index 29dd8fde02..3548be43df 100644 --- a/shell/renderer/electron_render_frame_observer.h +++ b/shell/renderer/electron_render_frame_observer.h @@ -16,7 +16,7 @@ namespace electron { class RendererClientBase; // Helper class to forward the messages to the client. -class ElectronRenderFrameObserver : public content::RenderFrameObserver { +class ElectronRenderFrameObserver : private content::RenderFrameObserver { public: ElectronRenderFrameObserver(content::RenderFrame* frame, RendererClientBase* renderer_client); @@ -26,6 +26,7 @@ class ElectronRenderFrameObserver : public content::RenderFrameObserver { ElectronRenderFrameObserver& operator=(const ElectronRenderFrameObserver&) = delete; + private: // content::RenderFrameObserver: void DidClearWindowObject() override; void DidInstallConditionalFeatures(v8::Handle<v8::Context> context, @@ -35,7 +36,6 @@ class ElectronRenderFrameObserver : public content::RenderFrameObserver { void OnDestruct() override; void DidMeaningfulLayout(blink::WebMeaningfulLayout layout_type) override; - private: [[nodiscard]] bool ShouldNotifyClient(int world_id) const; void CreateIsolatedWorldContext(); diff --git a/shell/renderer/pepper_helper.h b/shell/renderer/pepper_helper.h index a73aec8fdd..033a192fd4 100644 --- a/shell/renderer/pepper_helper.h +++ b/shell/renderer/pepper_helper.h @@ -11,7 +11,7 @@ // This class listens for Pepper creation events from the RenderFrame and // attaches the parts required for plugin support. -class PepperHelper : public content::RenderFrameObserver { +class PepperHelper : private content::RenderFrameObserver { public: explicit PepperHelper(content::RenderFrame* render_frame); ~PepperHelper() override; @@ -20,6 +20,7 @@ class PepperHelper : public content::RenderFrameObserver { PepperHelper(const PepperHelper&) = delete; PepperHelper& operator=(const PepperHelper&) = delete; + private: // RenderFrameObserver. void DidCreatePepperPlugin(content::RendererPpapiHost* host) override; void OnDestruct() override;
refactor
78995b956effdebb33b2f4ceed59ec7cb5b03b99
Shelley Vohr
2024-08-05 09:56:08
fix: potential draggable regions crash in DevTools (#43179)
diff --git a/patches/chromium/.patches b/patches/chromium/.patches index 5f85c678b5..3924ba4a93 100644 --- a/patches/chromium/.patches +++ b/patches/chromium/.patches @@ -130,3 +130,4 @@ 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 +fix_potential_draggable_region_crash_when_no_mainframeimpl.patch diff --git a/patches/chromium/fix_potential_draggable_region_crash_when_no_mainframeimpl.patch b/patches/chromium/fix_potential_draggable_region_crash_when_no_mainframeimpl.patch new file mode 100644 index 0000000000..8c01bb5c87 --- /dev/null +++ b/patches/chromium/fix_potential_draggable_region_crash_when_no_mainframeimpl.patch @@ -0,0 +1,35 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: Shelley Vohr <[email protected]> +Date: Thu, 1 Aug 2024 15:30:32 +0200 +Subject: Fix potential draggable region crash when no MainFrameImpl + +Fix a crash that can occur when SetSupportsDraggableRegions +is called with `true` and there is no MainFrameImpl. When MainFrameImpl +is nullptr, logic currently correctly returns early, but +supports_draggable_regions_ is set before that happens. As a +result, when SupportsDraggableRegions() is called, it will return +true, and thus LocalFrameView::UpdateDocumentDraggableRegions() will +call DraggableRegionsChanged(). This will trigger a crash in +WebViewImpl::DraggableRegionsChanged(), as it assumes that +MainFrameImpl is not null. + +Upstreamed in https://chromium-review.googlesource.com/c/chromium/src/+/5756619 + +diff --git a/third_party/blink/renderer/core/exported/web_view_impl.cc b/third_party/blink/renderer/core/exported/web_view_impl.cc +index ef68f9cbc63772f50269520fb0198a95e4270947..948cf94e2e4af0bbbf1f9c2322d00075bdaca0b2 100644 +--- a/third_party/blink/renderer/core/exported/web_view_impl.cc ++++ b/third_party/blink/renderer/core/exported/web_view_impl.cc +@@ -4073,11 +4073,12 @@ bool WebViewImpl::IsFencedFrameRoot() const { + } + + void WebViewImpl::SetSupportsDraggableRegions(bool supports_draggable_regions) { +- supports_draggable_regions_ = supports_draggable_regions; + if (!MainFrameImpl() || !MainFrameImpl()->GetFrame()) { + return; + } + ++ supports_draggable_regions_ = supports_draggable_regions; ++ + LocalFrame* local_frame = MainFrameImpl()->GetFrame(); + + if (supports_draggable_regions_) {
fix
93024be3b26ff66a7978ba278990a0a0f55bc9d3
Milan Burda
2023-06-19 14:19:11
build: rename spec/.eslintrc -> spec/.eslintrc.json (#38838) chore: rename spec/.eslintrc -> spec/.eslintrc.json
diff --git a/spec/.eslintrc b/spec/.eslintrc.json similarity index 100% rename from spec/.eslintrc rename to spec/.eslintrc.json
build
43104685130eede2db63feea0af9533759a77a0d
Shelley Vohr
2022-10-18 02:22:32
feat: support `serialPort.forget()` (#35310) feat: enable serialPort.revoke()
diff --git a/docs/api/session.md b/docs/api/session.md index 654fe3b751..a9867b4478 100644 --- a/docs/api/session.md +++ b/docs/api/session.md @@ -385,6 +385,50 @@ callback from `select-serial-port` is called. This event is intended for use when using a UI to ask users to pick a port so that the UI can be updated to remove the specified port. +#### Event: 'serial-port-revoked' + +Returns: + +* `event` Event +* `details` Object + * `port` [SerialPort](structures/serial-port.md) + * `frame` [WebFrameMain](web-frame-main.md) + * `origin` string - The origin that the device has been revoked from. + +Emitted after `SerialPort.forget()` has been called. This event can be used +to help maintain persistent storage of permissions when `setDevicePermissionHandler` is used. + +```js +// Browser Process +const { app, BrowserWindow } = require('electron') + +app.whenReady().then(() => { + const win = new BrowserWindow({ + width: 800, + height: 600 + }) + + win.webContents.session.on('serial-port-revoked', (event, details) => { + console.log(`Access revoked for serial device from origin ${details.origin}`) + }) +}) +``` + +```js +// Renderer Process + +const portConnect = async () => { + // Request a port. + const port = await navigator.serial.requestPort() + + // Wait for the serial port to open. + await port.open({ baudRate: 9600 }) + + // ...later, revoke access to the serial port. + await port.forget() +} +``` + ### Instance Methods The following methods are available on instances of `Session`: diff --git a/filenames.gni b/filenames.gni index a7dda9edca..994fc5275a 100644 --- a/filenames.gni +++ b/filenames.gni @@ -581,6 +581,7 @@ filenames = { "shell/common/gin_converters/native_window_converter.h", "shell/common/gin_converters/net_converter.cc", "shell/common/gin_converters/net_converter.h", + "shell/common/gin_converters/serial_port_info_converter.h", "shell/common/gin_converters/std_converter.h", "shell/common/gin_converters/time_converter.cc", "shell/common/gin_converters/time_converter.h", diff --git a/shell/browser/serial/electron_serial_delegate.cc b/shell/browser/serial/electron_serial_delegate.cc index 0c7f63d4ab..8430fce31b 100644 --- a/shell/browser/serial/electron_serial_delegate.cc +++ b/shell/browser/serial/electron_serial_delegate.cc @@ -61,6 +61,21 @@ bool ElectronSerialDelegate::HasPortPermission( frame); } +void ElectronSerialDelegate::RevokePortPermissionWebInitiated( + content::RenderFrameHost* frame, + const base::UnguessableToken& token) { + auto* web_contents = content::WebContents::FromRenderFrameHost(frame); + return GetChooserContext(frame)->RevokePortPermissionWebInitiated( + web_contents->GetPrimaryMainFrame()->GetLastCommittedOrigin(), token, + frame); +} + +const device::mojom::SerialPortInfo* ElectronSerialDelegate::GetPortInfo( + content::RenderFrameHost* frame, + const base::UnguessableToken& token) { + return GetChooserContext(frame)->GetPortInfo(token); +} + device::mojom::SerialPortManager* ElectronSerialDelegate::GetPortManager( content::RenderFrameHost* frame) { return GetChooserContext(frame)->GetPortManager(); @@ -81,18 +96,6 @@ void ElectronSerialDelegate::RemoveObserver( observer_list_.RemoveObserver(observer); } -void ElectronSerialDelegate::RevokePortPermissionWebInitiated( - content::RenderFrameHost* frame, - const base::UnguessableToken& token) { - // TODO(nornagon/jkleinsc): pass this on to the chooser context -} - -const device::mojom::SerialPortInfo* ElectronSerialDelegate::GetPortInfo( - content::RenderFrameHost* frame, - const base::UnguessableToken& token) { - return GetChooserContext(frame)->GetPortInfo(token); -} - SerialChooserController* ElectronSerialDelegate::ControllerForFrame( content::RenderFrameHost* render_frame_host) { auto mapping = controller_map_.find(render_frame_host); diff --git a/shell/browser/serial/electron_serial_delegate.h b/shell/browser/serial/electron_serial_delegate.h index 4f6559c28e..9ddbaa3aec 100644 --- a/shell/browser/serial/electron_serial_delegate.h +++ b/shell/browser/serial/electron_serial_delegate.h @@ -36,18 +36,18 @@ class ElectronSerialDelegate : public content::SerialDelegate, bool CanRequestPortPermission(content::RenderFrameHost* frame) override; bool HasPortPermission(content::RenderFrameHost* frame, const device::mojom::SerialPortInfo& port) override; - device::mojom::SerialPortManager* GetPortManager( - content::RenderFrameHost* frame) override; - void AddObserver(content::RenderFrameHost* frame, - content::SerialDelegate::Observer* observer) override; - void RemoveObserver(content::RenderFrameHost* frame, - content::SerialDelegate::Observer* observer) override; void RevokePortPermissionWebInitiated( content::RenderFrameHost* frame, const base::UnguessableToken& token) override; const device::mojom::SerialPortInfo* GetPortInfo( content::RenderFrameHost* frame, const base::UnguessableToken& token) override; + device::mojom::SerialPortManager* GetPortManager( + content::RenderFrameHost* frame) override; + void AddObserver(content::RenderFrameHost* frame, + Observer* observer) override; + void RemoveObserver(content::RenderFrameHost* frame, + Observer* observer) override; void DeleteControllerForFrame(content::RenderFrameHost* render_frame_host); diff --git a/shell/browser/serial/serial_chooser_context.cc b/shell/browser/serial/serial_chooser_context.cc index 080a1030d4..9301d75b15 100644 --- a/shell/browser/serial/serial_chooser_context.cc +++ b/shell/browser/serial/serial_chooser_context.cc @@ -15,14 +15,16 @@ #include "content/public/browser/device_service.h" #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_permission_manager.h" #include "shell/browser/web_contents_permission_helper.h" +#include "shell/common/gin_converters/frame_converter.h" +#include "shell/common/gin_converters/serial_port_info_converter.h" namespace electron { constexpr char kPortNameKey[] = "name"; constexpr char kTokenKey[] = "token"; - #if BUILDFLAG(IS_WIN) const char kDeviceInstanceIdKey[] = "device_instance_id"; #else @@ -56,35 +58,35 @@ base::UnguessableToken DecodeToken(base::StringPiece input) { } base::Value PortInfoToValue(const device::mojom::SerialPortInfo& port) { - base::Value value(base::Value::Type::DICTIONARY); + base::Value::Dict value; if (port.display_name && !port.display_name->empty()) - value.SetStringKey(kPortNameKey, *port.display_name); + value.Set(kPortNameKey, *port.display_name); else - value.SetStringKey(kPortNameKey, port.path.LossyDisplayName()); + value.Set(kPortNameKey, port.path.LossyDisplayName()); if (!SerialChooserContext::CanStorePersistentEntry(port)) { - value.SetStringKey(kTokenKey, EncodeToken(port.token)); - return value; + value.Set(kTokenKey, EncodeToken(port.token)); + return base::Value(std::move(value)); } #if BUILDFLAG(IS_WIN) // Windows provides a handy device identifier which we can rely on to be // sufficiently stable for identifying devices across restarts. - value.SetStringKey(kDeviceInstanceIdKey, port.device_instance_id); + value.Set(kDeviceInstanceIdKey, port.device_instance_id); #else DCHECK(port.has_vendor_id); - value.SetIntKey(kVendorIdKey, port.vendor_id); + value.Set(kVendorIdKey, port.vendor_id); DCHECK(port.has_product_id); - value.SetIntKey(kProductIdKey, port.product_id); + value.Set(kProductIdKey, port.product_id); DCHECK(port.serial_number); - value.SetStringKey(kSerialNumberKey, *port.serial_number); + value.Set(kSerialNumberKey, *port.serial_number); #if BUILDFLAG(IS_MAC) DCHECK(port.usb_driver_name && !port.usb_driver_name->empty()); - value.SetStringKey(kUsbDriverKey, *port.usb_driver_name); + value.Set(kUsbDriverKey, *port.usb_driver_name); #endif // BUILDFLAG(IS_MAC) #endif // BUILDFLAG(IS_WIN) - return value; + return base::Value(std::move(value)); } SerialChooserContext::SerialChooserContext(ElectronBrowserContext* context) @@ -105,18 +107,33 @@ void SerialChooserContext::GrantPortPermission( content::RenderFrameHost* render_frame_host) { port_info_.insert({port.token, port.Clone()}); - auto* permission_manager = static_cast<ElectronPermissionManager*>( - browser_context_->GetPermissionControllerDelegate()); - return permission_manager->GrantDevicePermission( - static_cast<blink::PermissionType>( - WebContentsPermissionHelper::PermissionType::SERIAL), - origin, PortInfoToValue(port), browser_context_); + if (CanStorePersistentEntry(port)) { + auto* permission_manager = static_cast<ElectronPermissionManager*>( + browser_context_->GetPermissionControllerDelegate()); + permission_manager->GrantDevicePermission( + static_cast<blink::PermissionType>( + WebContentsPermissionHelper::PermissionType::SERIAL), + origin, PortInfoToValue(port), browser_context_); + return; + } + + ephemeral_ports_[origin].insert(port.token); } bool SerialChooserContext::HasPortPermission( const url::Origin& origin, const device::mojom::SerialPortInfo& port, content::RenderFrameHost* render_frame_host) { + auto it = ephemeral_ports_.find(origin); + if (it != ephemeral_ports_.end()) { + const std::set<base::UnguessableToken>& ports = it->second; + if (base::Contains(ports, port.token)) + return true; + } + + if (!CanStorePersistentEntry(port)) + return false; + auto* permission_manager = static_cast<ElectronPermissionManager*>( browser_context_->GetPermissionControllerDelegate()); return permission_manager->CheckDevicePermission( @@ -127,10 +144,39 @@ bool SerialChooserContext::HasPortPermission( void SerialChooserContext::RevokePortPermissionWebInitiated( const url::Origin& origin, - const base::UnguessableToken& token) { + const base::UnguessableToken& token, + content::RenderFrameHost* render_frame_host) { auto it = port_info_.find(token); - if (it == port_info_.end()) - return; + if (it != port_info_.end()) { + auto* permission_manager = static_cast<ElectronPermissionManager*>( + browser_context_->GetPermissionControllerDelegate()); + permission_manager->RevokeDevicePermission( + static_cast<blink::PermissionType>( + WebContentsPermissionHelper::PermissionType::SERIAL), + origin, PortInfoToValue(*it->second), browser_context_); + } + + auto ephemeral = ephemeral_ports_.find(origin); + if (ephemeral != ephemeral_ports_.end()) { + std::set<base::UnguessableToken>& ports = ephemeral->second; + ports.erase(token); + } + + auto* web_contents = + content::WebContents::FromRenderFrameHost(render_frame_host); + api::Session* session = + api::Session::FromBrowserContext(web_contents->GetBrowserContext()); + + if (session) { + v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); + v8::HandleScope scope(isolate); + gin_helper::Dictionary details = + gin_helper::Dictionary::CreateEmpty(isolate); + details.Set("port", it->second); + details.SetGetter("frame", render_frame_host); + details.Set("origin", origin.Serialize()); + session->Emit("serial-port-revoked", details); + } } // static @@ -195,6 +241,11 @@ void SerialChooserContext::OnPortAdded(device::mojom::SerialPortInfoPtr port) { if (!base::Contains(port_info_, port->token)) port_info_.insert({port->token, port->Clone()}); + for (auto& map_entry : ephemeral_ports_) { + std::set<base::UnguessableToken>& ports = map_entry.second; + ports.erase(port->token); + } + for (auto& observer : port_observer_list_) observer.OnPortAdded(*port); } @@ -239,6 +290,8 @@ void SerialChooserContext::OnGetDevices( void SerialChooserContext::OnPortManagerConnectionError() { port_manager_.reset(); client_receiver_.reset(); -} + port_info_.clear(); + ephemeral_ports_.clear(); +} } // namespace electron diff --git a/shell/browser/serial/serial_chooser_context.h b/shell/browser/serial/serial_chooser_context.h index 148bf14996..1c3e2d7641 100644 --- a/shell/browser/serial/serial_chooser_context.h +++ b/shell/browser/serial/serial_chooser_context.h @@ -67,9 +67,19 @@ class SerialChooserContext : public KeyedService, bool HasPortPermission(const url::Origin& origin, const device::mojom::SerialPortInfo& port, content::RenderFrameHost* render_frame_host); + void RevokePortPermissionWebInitiated( + const url::Origin& origin, + const base::UnguessableToken& token, + content::RenderFrameHost* render_frame_host); static bool CanStorePersistentEntry( const device::mojom::SerialPortInfo& port); + // Only call this if you're sure |port_info_| has been initialized + // before-hand. The returned raw pointer is owned by |port_info_| and will be + // destroyed when the port is removed. + const device::mojom::SerialPortInfo* GetPortInfo( + const base::UnguessableToken& token); + device::mojom::SerialPortManager* GetPortManager(); void AddPortObserver(PortObserver* observer); @@ -77,21 +87,9 @@ class SerialChooserContext : public KeyedService, base::WeakPtr<SerialChooserContext> AsWeakPtr(); - bool is_initialized_ = false; - - // Map from port token to port info. - std::map<base::UnguessableToken, device::mojom::SerialPortInfoPtr> port_info_; - // SerialPortManagerClient implementation. void OnPortAdded(device::mojom::SerialPortInfoPtr port) override; void OnPortRemoved(device::mojom::SerialPortInfoPtr port) override; - void RevokePortPermissionWebInitiated(const url::Origin& origin, - const base::UnguessableToken& token); - // Only call this if you're sure |port_info_| has been initialized - // before-hand. The returned raw pointer is owned by |port_info_| and will be - // destroyed when the port is removed. - const device::mojom::SerialPortInfo* GetPortInfo( - const base::UnguessableToken& token); private: void EnsurePortManagerConnection(); @@ -99,9 +97,14 @@ class SerialChooserContext : public KeyedService, mojo::PendingRemote<device::mojom::SerialPortManager> manager); void OnGetDevices(std::vector<device::mojom::SerialPortInfoPtr> ports); void OnPortManagerConnectionError(); - void RevokeObjectPermissionInternal(const url::Origin& origin, - const base::Value& object, - bool revoked_by_website); + + bool is_initialized_ = false; + + // Tracks the set of ports to which an origin has access to. + std::map<url::Origin, std::set<base::UnguessableToken>> ephemeral_ports_; + + // Map from port token to port info. + std::map<base::UnguessableToken, device::mojom::SerialPortInfoPtr> port_info_; mojo::Remote<device::mojom::SerialPortManager> port_manager_; mojo::Receiver<device::mojom::SerialPortManagerClient> client_receiver_{this}; diff --git a/shell/common/gin_converters/serial_port_info_converter.h b/shell/common/gin_converters/serial_port_info_converter.h new file mode 100644 index 0000000000..c772967112 --- /dev/null +++ b/shell/common/gin_converters/serial_port_info_converter.h @@ -0,0 +1,43 @@ +// 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_SERIAL_PORT_INFO_CONVERTER_H_ +#define ELECTRON_SHELL_COMMON_GIN_CONVERTERS_SERIAL_PORT_INFO_CONVERTER_H_ + +#include "gin/converter.h" +#include "shell/common/gin_helper/dictionary.h" +#include "third_party/blink/public/mojom/serial/serial.mojom.h" + +namespace gin { + +template <> +struct Converter<device::mojom::SerialPortInfoPtr> { + static v8::Local<v8::Value> ToV8( + v8::Isolate* isolate, + const device::mojom::SerialPortInfoPtr& port) { + gin_helper::Dictionary dict = gin::Dictionary::CreateEmpty(isolate); + dict.Set("portId", port->token.ToString()); + dict.Set("portName", port->path.BaseName().LossyDisplayName()); + if (port->display_name && !port->display_name->empty()) + dict.Set("displayName", *port->display_name); + if (port->has_vendor_id) + dict.Set("vendorId", base::StringPrintf("%u", port->vendor_id)); + if (port->has_product_id) + dict.Set("productId", base::StringPrintf("%u", port->product_id)); + if (port->serial_number && !port->serial_number->empty()) + dict.Set("serialNumber", *port->serial_number); +#if BUILDFLAG(IS_MAC) + if (port->usb_driver_name && !port->usb_driver_name->empty()) + dict.Set("usbDriverName", *port->usb_driver_name); +#elif BUILDFLAG(IS_WIN) + if (!port->device_instance_id.empty()) + dict.Set("deviceInstanceId", port->device_instance_id); +#endif + return gin::ConvertToV8(isolate, dict); + } +}; + +} // namespace gin + +#endif // ELECTRON_SHELL_COMMON_GIN_CONVERTERS_SERIAL_PORT_INFO_CONVERTER_H_ diff --git a/spec/chromium-spec.ts b/spec/chromium-spec.ts index 9c7aae433f..244363c1e8 100644 --- a/spec/chromium-spec.ts +++ b/spec/chromium-spec.ts @@ -2423,6 +2423,50 @@ describe('navigator.serial', () => { expect(grantedPorts).to.not.be.empty(); } }); + + it('supports port.forget()', async () => { + let forgottenPortFromEvent = {}; + let havePorts = false; + + w.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => { + if (portList.length > 0) { + havePorts = true; + callback(portList[0].portId); + } else { + callback(''); + } + }); + + w.webContents.session.on('serial-port-revoked', (event, details) => { + forgottenPortFromEvent = details.port; + }); + + await getPorts(); + if (havePorts) { + const grantedPorts = await w.webContents.executeJavaScript('navigator.serial.getPorts()'); + if (grantedPorts.length > 0) { + const forgottenPort = await w.webContents.executeJavaScript(` + navigator.serial.getPorts().then(async(ports) => { + const portInfo = await ports[0].getInfo(); + await ports[0].forget(); + if (portInfo.usbVendorId && portInfo.usbProductId) { + return { + vendorId: '' + portInfo.usbVendorId, + productId: '' + portInfo.usbProductId + } + } else { + return {}; + } + }) + `); + const grantedPorts2 = await w.webContents.executeJavaScript('navigator.serial.getPorts()'); + expect(grantedPorts2.length).to.be.lessThan(grantedPorts.length); + if (forgottenPort.vendorId && forgottenPort.productId) { + expect(forgottenPortFromEvent).to.include(forgottenPort); + } + } + } + }); }); describe('navigator.clipboard', () => {
feat
d7b568a1c0ab276fdec59c386b32711c08f5fa2f
David Sanders
2025-01-22 00:40:10
ci: fix issue workflow failures (#45294)
diff --git a/.github/workflows/branch-created.yml b/.github/workflows/branch-created.yml index c9fa3ac4e4..c55d9b067e 100644 --- a/.github/workflows/branch-created.yml +++ b/.github/workflows/branch-created.yml @@ -94,7 +94,7 @@ jobs: })) - name: Create Release Project Board if: ${{ steps.check-major-version.outputs.MAJOR }} - uses: dsanders11/project-actions/copy-project@8bc0bd421be3a2f9e96e160c4cb703f97cd3be55 # v1.5.0 + uses: dsanders11/project-actions/copy-project@9c80cd31f58599941c64f74636bea95ba5d46090 # v1.5.1 id: create-release-board with: drafts: true @@ -114,14 +114,14 @@ jobs: GITHUB_TOKEN: ${{ steps.generate-token.outputs.token }} - name: Find Previous Release Project Board if: ${{ steps.check-major-version.outputs.MAJOR }} - uses: dsanders11/project-actions/find-project@8bc0bd421be3a2f9e96e160c4cb703f97cd3be55 # v1.5.0 + uses: dsanders11/project-actions/find-project@9c80cd31f58599941c64f74636bea95ba5d46090 # v1.5.1 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@8bc0bd421be3a2f9e96e160c4cb703f97cd3be55 # v1.5.0 + uses: dsanders11/project-actions/close-project@9c80cd31f58599941c64f74636bea95ba5d46090 # v1.5.1 with: project-number: ${{ steps.find-prev-release-board.outputs.number }} token: ${{ steps.generate-token.outputs.token }} diff --git a/.github/workflows/issue-labeled.yml b/.github/workflows/issue-labeled.yml index df4c4d4e22..11e46e58ea 100644 --- a/.github/workflows/issue-labeled.yml +++ b/.github/workflows/issue-labeled.yml @@ -20,7 +20,7 @@ jobs: creds: ${{ secrets.ISSUE_TRIAGE_GH_APP_CREDS }} org: electron - name: Set status - uses: dsanders11/project-actions/edit-item@8bc0bd421be3a2f9e96e160c4cb703f97cd3be55 # v1.5.0 + uses: dsanders11/project-actions/edit-item@9c80cd31f58599941c64f74636bea95ba5d46090 # v1.5.1 with: token: ${{ steps.generate-token.outputs.token }} project-number: 90 @@ -39,7 +39,7 @@ jobs: creds: ${{ secrets.ISSUE_TRIAGE_GH_APP_CREDS }} org: electron - name: Set status - uses: dsanders11/project-actions/edit-item@8bc0bd421be3a2f9e96e160c4cb703f97cd3be55 # v1.5.0 + uses: dsanders11/project-actions/edit-item@9c80cd31f58599941c64f74636bea95ba5d46090 # v1.5.1 with: token: ${{ steps.generate-token.outputs.token }} project-number: 90 diff --git a/.github/workflows/issue-opened.yml b/.github/workflows/issue-opened.yml index b181d6e0b7..bd8ec413f6 100644 --- a/.github/workflows/issue-opened.yml +++ b/.github/workflows/issue-opened.yml @@ -19,7 +19,7 @@ jobs: creds: ${{ secrets.ISSUE_TRIAGE_GH_APP_CREDS }} org: electron - name: Add to Issue Triage - uses: dsanders11/project-actions/add-item@8bc0bd421be3a2f9e96e160c4cb703f97cd3be55 # v1.5.0 + uses: dsanders11/project-actions/add-item@9c80cd31f58599941c64f74636bea95ba5d46090 # v1.5.1 with: field: Reporter field-value: ${{ github.event.issue.user.login }} diff --git a/.github/workflows/issue-transferred.yml b/.github/workflows/issue-transferred.yml index 3c4299c68d..824cb69a2c 100644 --- a/.github/workflows/issue-transferred.yml +++ b/.github/workflows/issue-transferred.yml @@ -10,6 +10,7 @@ jobs: issue-transferred: name: Issue Transferred runs-on: ubuntu-latest + if: ${{ !github.event.changes.new_repository.private }} steps: - name: Generate GitHub App token uses: electron/github-app-auth-action@384fd19694fe7b6dcc9a684746c6976ad78228ae # v1.1.1 @@ -18,8 +19,9 @@ jobs: creds: ${{ secrets.ISSUE_TRIAGE_GH_APP_CREDS }} org: electron - name: Remove from issue triage - uses: dsanders11/project-actions/delete-item@8bc0bd421be3a2f9e96e160c4cb703f97cd3be55 # v1.5.0 + uses: dsanders11/project-actions/delete-item@9c80cd31f58599941c64f74636bea95ba5d46090 # v1.5.1 with: token: ${{ steps.generate-token.outputs.token }} project-number: 90 + item: ${{ github.event.changes.new_issue.html_url }} fail-if-item-not-found: false diff --git a/.github/workflows/issue-unlabeled.yml b/.github/workflows/issue-unlabeled.yml index 4f14342720..6337e3d917 100644 --- a/.github/workflows/issue-unlabeled.yml +++ b/.github/workflows/issue-unlabeled.yml @@ -30,7 +30,7 @@ jobs: org: electron - name: Set status if: ${{ steps.check-for-blocked-labels.outputs.NOT_BLOCKED }} - uses: dsanders11/project-actions/edit-item@8bc0bd421be3a2f9e96e160c4cb703f97cd3be55 # v1.5.0 + uses: dsanders11/project-actions/edit-item@9c80cd31f58599941c64f74636bea95ba5d46090 # v1.5.1 with: token: ${{ steps.generate-token.outputs.token }} project-number: 90 diff --git a/.github/workflows/pull-request-labeled.yml b/.github/workflows/pull-request-labeled.yml index 92897ed0b1..f17524034e 100644 --- a/.github/workflows/pull-request-labeled.yml +++ b/.github/workflows/pull-request-labeled.yml @@ -33,7 +33,7 @@ jobs: creds: ${{ secrets.RELEASE_BOARD_GH_APP_CREDS }} org: electron - name: Set status - uses: dsanders11/project-actions/edit-item@8bc0bd421be3a2f9e96e160c4cb703f97cd3be55 # v1.5.0 + uses: dsanders11/project-actions/edit-item@9c80cd31f58599941c64f74636bea95ba5d46090 # v1.5.1 with: token: ${{ steps.generate-token.outputs.token }} project-number: 94 diff --git a/.github/workflows/stable-prep-items.yml b/.github/workflows/stable-prep-items.yml index 2dc8852e9e..64b463630d 100644 --- a/.github/workflows/stable-prep-items.yml +++ b/.github/workflows/stable-prep-items.yml @@ -27,7 +27,7 @@ jobs: PROJECT_NUMBER=$(gh project list --owner electron --format json | jq -r '.projects | map(select(.title | test("^[0-9]+-x-y$"))) | max_by(.number) | .number') echo "PROJECT_NUMBER=$PROJECT_NUMBER" >> "$GITHUB_OUTPUT" - name: Update Completed Stable Prep Items - uses: dsanders11/project-actions/completed-by@8bc0bd421be3a2f9e96e160c4cb703f97cd3be55 # v1.5.0 + uses: dsanders11/project-actions/completed-by@9c80cd31f58599941c64f74636bea95ba5d46090 # v1.5.1 with: field: Prep Status field-value: ✅ Complete
ci
3a6a20153429bf6b2712af91c970c56ea4d72173
John Kleinschmidt
2024-07-13 13:38:03
build: fixup GHA running on fork PRs (#42880) * chore: update build-tools for GHA * chore: don't rely on environment variables for source cache location
diff --git a/.github/actions/install-build-tools/action.yml b/.github/actions/install-build-tools/action.yml index 7d759ec4d8..0f274ad79d 100644 --- a/.github/actions/install-build-tools/action.yml +++ b/.github/actions/install-build-tools/action.yml @@ -6,6 +6,6 @@ runs: - name: Install Build Tools shell: bash run: | - export BUILD_TOOLS_SHA=47d4bb016f47d89938898c794db80b9f98d78ad7 + export BUILD_TOOLS_SHA=d5b87591842be19058e8d75d2c5b7f1fabe9f450 npm i -g @electron/build-tools e auto-update disable diff --git a/.github/actions/restore-cache-azcopy/action.yml b/.github/actions/restore-cache-azcopy/action.yml index 0d23a5f8c6..d41014b755 100644 --- a/.github/actions/restore-cache-azcopy/action.yml +++ b/.github/actions/restore-cache-azcopy/action.yml @@ -34,6 +34,9 @@ runs: fi azcopy copy --log-level=ERROR \ "https://${{ env.AZURE_AKS_CACHE_STORAGE_ACCOUNT }}.file.core.windows.net/${{ env.AZURE_AKS_CACHE_SHARE_NAME }}/${{ env.CACHE_PATH }}?$sas_token" $DEPSHASH.tar + env: + AZURE_AKS_CACHE_STORAGE_ACCOUNT: f723719aa87a34622b5f7f3 + AZURE_AKS_CACHE_SHARE_NAME: pvc-f6a4089f-b082-4bee-a3f9-c3e1c0c02d8f - name: Clean SAS Key shell: bash run: rm -f sas-token diff --git a/.github/workflows/pipeline-segment-electron-build.yml b/.github/workflows/pipeline-segment-electron-build.yml index a92366623b..c07a9317a6 100644 --- a/.github/workflows/pipeline-segment-electron-build.yml +++ b/.github/workflows/pipeline-segment-electron-build.yml @@ -61,8 +61,6 @@ concurrency: cancel-in-progress: ${{ github.ref != 'refs/heads/main' && !endsWith(github.ref, '-x-y') }} env: - AZURE_AKS_CACHE_STORAGE_ACCOUNT: ${{ secrets.AZURE_AKS_CACHE_STORAGE_ACCOUNT }} - AZURE_AKS_CACHE_SHARE_NAME: ${{ secrets.AZURE_AKS_CACHE_SHARE_NAME }} ELECTRON_ARTIFACTS_BLOB_STORAGE: ${{ secrets.ELECTRON_ARTIFACTS_BLOB_STORAGE }} ELECTRON_RBE_JWT: ${{ secrets.ELECTRON_RBE_JWT }} ELECTRON_GITHUB_TOKEN: ${{ secrets.ELECTRON_GITHUB_TOKEN }} diff --git a/.github/workflows/pipeline-segment-electron-gn-check.yml b/.github/workflows/pipeline-segment-electron-gn-check.yml index 378c5d320f..1efa05d69f 100644 --- a/.github/workflows/pipeline-segment-electron-gn-check.yml +++ b/.github/workflows/pipeline-segment-electron-gn-check.yml @@ -36,8 +36,6 @@ concurrency: cancel-in-progress: true env: - AZURE_AKS_CACHE_STORAGE_ACCOUNT: ${{ secrets.AZURE_AKS_CACHE_STORAGE_ACCOUNT }} - AZURE_AKS_CACHE_SHARE_NAME: ${{ secrets.AZURE_AKS_CACHE_SHARE_NAME }} ELECTRON_RBE_JWT: ${{ secrets.ELECTRON_RBE_JWT }} GCLIENT_EXTRA_ARGS: ${{ inputs.target-platform == 'macos' && '--custom-var=checkout_mac=True --custom-var=host_os=mac' || '--custom-var=checkout_arm=True --custom-var=checkout_arm64=True' }} ELECTRON_OUT_DIR: Default
build
9f8308907b9f5584b60e6d6199c3732dc45fc893
Jeremy Rose
2022-11-14 16:46:45
ci: pin version of actions/checkout (#36342)
diff --git a/.github/workflows/release_dependency_versions.yml b/.github/workflows/release_dependency_versions.yml index 00db1ba079..425f4ce4ab 100644 --- a/.github/workflows/release_dependency_versions.yml +++ b/.github/workflows/release_dependency_versions.yml @@ -11,7 +11,7 @@ jobs: check_tag: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@93ea575cb5d8a053eaa0ac8fa3b40d7e05a33cc8 # tag: v3 - name: Check Tag run: | if [[ ${{ github.event.release.tag_name }} =~ ^v[0-9]+\.0\.0$ ]]; then @@ -22,7 +22,7 @@ jobs: needs: check_tag if: needs.check_tag.outputs.should_release == 'true' steps: - - uses: actions/checkout@v3 + - 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 }}"}}'
ci
02be7c11858a172eb398ea0886a27a98d06384cc
Alice Zhao
2025-02-17 12:40:47
feat: add excludeUrls and modify urls in WebRequestFilter for better URL filtering (#44692) * feat: add excludeUrls to web request filter * refactor: add deprecated field * test: update tests * lint: newline * docs: improve API doc * fix: add is filter defined property to match all urls * refactor: remove includeUrls * refactor: remove typescript binding * refactor: all_url * refactor: remove isDefined methods * refactor: remove comment * fix: logic * docs: add to breaking changes
diff --git a/docs/api/structures/web-request-filter.md b/docs/api/structures/web-request-filter.md index 13a70663dd..480a94f7b9 100644 --- a/docs/api/structures/web-request-filter.md +++ b/docs/api/structures/web-request-filter.md @@ -1,4 +1,5 @@ # WebRequestFilter Object -* `urls` string[] - Array of [URL patterns](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Match_patterns) that will be used to filter out the requests that do not match the URL patterns. -* `types` String[] (optional) - Array of types that will be used to filter out the requests that do not match the types. When not specified, all types will be matched. Can be `mainFrame`, `subFrame`, `stylesheet`, `script`, `image`, `font`, `object`, `xhr`, `ping`, `cspReport`, `media` or `webSocket`. +* `urls` string[] - Array of [URL patterns](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Match_patterns) used to include requests that match these patterns. Use the pattern `<all_urls>` to match all URLs. +* `excludeUrls` string[] (optional) - Array of [URL patterns](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Match_patterns) used to exclude requests that match these patterns. +* `types` string[] (optional) - Array of types that will be used to filter out the requests that do not match the types. When not specified, all types will be matched. Can be `mainFrame`, `subFrame`, `stylesheet`, `script`, `image`, `font`, `object`, `xhr`, `ping`, `cspReport`, `media` or `webSocket`. diff --git a/docs/api/web-request.md b/docs/api/web-request.md index 062084831d..c8ee3cd1e4 100644 --- a/docs/api/web-request.md +++ b/docs/api/web-request.md @@ -73,6 +73,7 @@ The `callback` has to be called with an `response` object. Some examples of valid `urls`: ```js +'<all_urls>' 'http://foo:1234/' 'http://foo.com/' 'http://foo:1234/bar' diff --git a/docs/breaking-changes.md b/docs/breaking-changes.md index 9d832290b9..100f81f698 100644 --- a/docs/breaking-changes.md +++ b/docs/breaking-changes.md @@ -63,6 +63,22 @@ webContents.on('console-message', ({ level, message, lineNumber, sourceId, frame Additionally, `level` is now a string with possible values of `info`, `warning`, `error`, and `debug`. +### Behavior Changed: `urls` property of `WebRequestFilter`. + +Previously, an empty urls array was interpreted as including all URLs. To explicitly include all URLs, developers should now use the `<all_urls>` pattern, which is a [designated URL pattern](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Match_patterns#all_urls) that matches every possible URL. This change clarifies the intent and ensures more predictable behavior. + +```js +// Deprecated +const deprecatedFilter = { + urls: [] +} + +// Replace with +const newFilter = { + urls: ['<all_urls>'] +} +``` + ### Deprecated: `systemPreferences.isAeroGlassEnabled()` The `systemPreferences.isAeroGlassEnabled()` function has been deprecated without replacement. diff --git a/shell/browser/api/electron_api_web_request.cc b/shell/browser/api/electron_api_web_request.cc index e71f68f96a..0410c9683d 100644 --- a/shell/browser/api/electron_api_web_request.cc +++ b/shell/browser/api/electron_api_web_request.cc @@ -33,6 +33,7 @@ #include "shell/common/gin_converters/std_converter.h" #include "shell/common/gin_converters/value_converter.h" #include "shell/common/gin_helper/dictionary.h" +#include "shell/common/node_util.h" static constexpr auto ResourceTypes = base::MakeFixedFlatMap<std::string_view, @@ -211,15 +212,23 @@ CalculateOnBeforeSendHeadersDelta(const net::HttpRequestHeaders* old_headers, gin::WrapperInfo WebRequest::kWrapperInfo = {gin::kEmbedderNativeGin}; WebRequest::RequestFilter::RequestFilter( - std::set<URLPattern> url_patterns, + std::set<URLPattern> include_url_patterns, + std::set<URLPattern> exclude_url_patterns, std::set<extensions::WebRequestResourceType> types) - : url_patterns_(std::move(url_patterns)), types_(std::move(types)) {} + : include_url_patterns_(std::move(include_url_patterns)), + exclude_url_patterns_(std::move(exclude_url_patterns)), + types_(std::move(types)) {} WebRequest::RequestFilter::RequestFilter(const RequestFilter&) = default; WebRequest::RequestFilter::RequestFilter() = default; WebRequest::RequestFilter::~RequestFilter() = default; -void WebRequest::RequestFilter::AddUrlPattern(URLPattern pattern) { - url_patterns_.emplace(std::move(pattern)); +void WebRequest::RequestFilter::AddUrlPattern(URLPattern pattern, + bool is_match_pattern) { + if (is_match_pattern) { + include_url_patterns_.emplace(std::move(pattern)); + } else { + exclude_url_patterns_.emplace(std::move(pattern)); + } } void WebRequest::RequestFilter::AddType( @@ -227,11 +236,13 @@ void WebRequest::RequestFilter::AddType( types_.insert(type); } -bool WebRequest::RequestFilter::MatchesURL(const GURL& url) const { - if (url_patterns_.empty()) - return true; +bool WebRequest::RequestFilter::MatchesURL( + const GURL& url, + const std::set<URLPattern>& patterns) const { + if (patterns.empty()) + return false; - for (const auto& pattern : url_patterns_) { + for (const auto& pattern : patterns) { if (pattern.MatchesURL(url)) return true; } @@ -245,7 +256,29 @@ bool WebRequest::RequestFilter::MatchesType( bool WebRequest::RequestFilter::MatchesRequest( extensions::WebRequestInfo* info) const { - return MatchesURL(info->url) && MatchesType(info->web_request_type); + // Matches URL and type, and does not match exclude URL. + return MatchesURL(info->url, include_url_patterns_) && + !MatchesURL(info->url, exclude_url_patterns_) && + MatchesType(info->web_request_type); +} + +void WebRequest::RequestFilter::AddUrlPatterns( + const std::set<std::string>& filter_patterns, + RequestFilter* filter, + gin::Arguments* args, + bool is_match_pattern) { + for (const std::string& filter_pattern : filter_patterns) { + URLPattern pattern(URLPattern::SCHEME_ALL); + const URLPattern::ParseResult result = pattern.Parse(filter_pattern); + if (result == URLPattern::ParseResult::kSuccess) { + filter->AddUrlPattern(std::move(pattern), is_match_pattern); + } else { + const char* error_type = URLPattern::GetParseResultString(result); + args->ThrowTypeError("Invalid url pattern " + filter_pattern + ": " + + error_type); + return; + } + } } struct WebRequest::BlockedRequest { @@ -315,7 +348,7 @@ gin::ObjectTemplateBuilder WebRequest::GetObjectTemplateBuilder( } const char* WebRequest::GetTypeName() { - return "WebRequest"; + return GetClassName(); } bool WebRequest::HasListener() const { @@ -617,37 +650,44 @@ void WebRequest::SetListener(Event event, gin::Arguments* args) { v8::Local<v8::Value> arg; - // { urls, types }. - std::set<std::string> filter_patterns, filter_types; + // { urls, excludeUrls, types }. + std::set<std::string> filter_include_patterns, filter_exclude_patterns, + filter_types; + RequestFilter filter; + gin::Dictionary dict(args->isolate()); if (args->GetNext(&arg) && !arg->IsFunction()) { // Note that gin treats Function as Dictionary when doing conversions, so we // have to explicitly check if the argument is Function before trying to // convert it to Dictionary. if (gin::ConvertFromV8(args->isolate(), arg, &dict)) { - if (!dict.Get("urls", &filter_patterns)) { + if (!dict.Get("urls", &filter_include_patterns)) { args->ThrowTypeError("Parameter 'filter' must have property 'urls'."); return; } + + if (filter_include_patterns.empty()) { + util::EmitWarning( + "The urls array in WebRequestFilter is empty, which is deprecated. " + "Please use '<all_urls>' to match all URLs.", + "DeprecationWarning"); + filter_include_patterns.insert("<all_urls>"); + } + + dict.Get("excludeUrls", &filter_exclude_patterns); dict.Get("types", &filter_types); args->GetNext(&arg); } + } else { + // If no filter is defined, create one with <all_urls> so it matches all + // requests + dict = gin::Dictionary::CreateEmpty(args->isolate()); + filter_include_patterns.insert("<all_urls>"); + dict.Set("urls", filter_include_patterns); } - RequestFilter filter; - - for (const std::string& filter_pattern : filter_patterns) { - URLPattern pattern(URLPattern::SCHEME_ALL); - const URLPattern::ParseResult result = pattern.Parse(filter_pattern); - if (result == URLPattern::ParseResult::kSuccess) { - filter.AddUrlPattern(std::move(pattern)); - } else { - const char* error_type = URLPattern::GetParseResultString(result); - args->ThrowTypeError("Invalid url pattern " + filter_pattern + ": " + - error_type); - return; - } - } + filter.AddUrlPatterns(filter_include_patterns, &filter, args); + filter.AddUrlPatterns(filter_exclude_patterns, &filter, args, false); for (const std::string& filter_type : filter_types) { auto type = ParseResourceType(filter_type); diff --git a/shell/browser/api/electron_api_web_request.h b/shell/browser/api/electron_api_web_request.h index d7a78c3e59..2114444aae 100644 --- a/shell/browser/api/electron_api_web_request.h +++ b/shell/browser/api/electron_api_web_request.h @@ -51,6 +51,8 @@ class WebRequest final : public gin::Wrappable<WebRequest>, static gin::Handle<WebRequest> From(v8::Isolate* isolate, content::BrowserContext* browser_context); + static const char* GetClassName() { return "WebRequest"; } + // gin::Wrappable: static gin::WrapperInfo kWrapperInfo; gin::ObjectTemplateBuilder GetObjectTemplateBuilder( @@ -156,21 +158,28 @@ class WebRequest final : public gin::Wrappable<WebRequest>, class RequestFilter { public: RequestFilter(std::set<URLPattern>, + std::set<URLPattern>, std::set<extensions::WebRequestResourceType>); RequestFilter(const RequestFilter&); RequestFilter(); ~RequestFilter(); - void AddUrlPattern(URLPattern pattern); + void AddUrlPattern(URLPattern pattern, bool is_match_pattern); + void AddUrlPatterns(const std::set<std::string>& filter_patterns, + RequestFilter* filter, + gin::Arguments* args, + bool is_match_pattern = true); void AddType(extensions::WebRequestResourceType type); bool MatchesRequest(extensions::WebRequestInfo* info) const; private: - bool MatchesURL(const GURL& url) const; + bool MatchesURL(const GURL& url, + const std::set<URLPattern>& patterns) const; bool MatchesType(extensions::WebRequestResourceType type) const; - std::set<URLPattern> url_patterns_; + std::set<URLPattern> include_url_patterns_; + std::set<URLPattern> exclude_url_patterns_; std::set<extensions::WebRequestResourceType> types_; }; diff --git a/spec/api-web-request-spec.ts b/spec/api-web-request-spec.ts index 2a276afaff..b2792cf9a6 100644 --- a/spec/api-web-request-spec.ts +++ b/spec/api-web-request-spec.ts @@ -101,6 +101,12 @@ describe('webRequest module', () => { await expect(ajax(defaultURL)).to.eventually.be.rejected(); }); + it('matches all requests when no filters are defined', async () => { + ses.webRequest.onBeforeRequest(cancel); + await expect(ajax(`${defaultURL}nofilter/test`)).to.eventually.be.rejected(); + await expect(ajax(`${defaultURL}nofilter2/test`)).to.eventually.be.rejected(); + }); + it('can filter URLs', async () => { const filter = { urls: [defaultURL + 'filter/*'] }; ses.webRequest.onBeforeRequest(filter, cancel); @@ -109,6 +115,36 @@ describe('webRequest module', () => { await expect(ajax(`${defaultURL}filter/test`)).to.eventually.be.rejected(); }); + it('can filter all URLs with syntax <all_urls>', async () => { + const filter = { urls: ['<all_urls>'] }; + ses.webRequest.onBeforeRequest(filter, cancel); + await expect(ajax(`${defaultURL}filter/test`)).to.eventually.be.rejected(); + await expect(ajax(`${defaultURL}nofilter/test`)).to.eventually.be.rejected(); + }); + + it('can filter URLs with overlapping patterns of urls and excludeUrls', async () => { + // If filter matches both urls and excludeUrls, it should be excluded. + const filter = { urls: [defaultURL + 'filter/*'], excludeUrls: [defaultURL + 'filter/test'] }; + ses.webRequest.onBeforeRequest(filter, cancel); + const { data } = await ajax(`${defaultURL}filter/test`); + expect(data).to.equal('/filter/test'); + }); + + it('can filter URLs with multiple excludeUrls patterns', async () => { + const filter = { urls: [defaultURL + 'filter/*'], excludeUrls: [defaultURL + 'filter/exclude1/*', defaultURL + 'filter/exclude2/*'] }; + ses.webRequest.onBeforeRequest(filter, cancel); + expect((await ajax(`${defaultURL}filter/exclude1/test`)).data).to.equal('/filter/exclude1/test'); + expect((await ajax(`${defaultURL}filter/exclude2/test`)).data).to.equal('/filter/exclude2/test'); + // expect non-excluded URL to pass filter + await expect(ajax(`${defaultURL}filter/test`)).to.eventually.be.rejected(); + }); + + it('can filter URLs with empty excludeUrls', async () => { + const filter = { urls: [defaultURL + 'filter/*'], excludeUrls: [] }; + ses.webRequest.onBeforeRequest(filter, cancel); + await expect(ajax(`${defaultURL}filter/test`)).to.eventually.be.rejected(); + }); + it('can filter URLs and types', async () => { const filter1: Electron.WebRequestFilter = { urls: [defaultURL + 'filter/*'], types: ['xhr'] }; ses.webRequest.onBeforeRequest(filter1, cancel); @@ -122,6 +158,21 @@ describe('webRequest module', () => { expect((await ajax(`${defaultURL}filter/test`)).data).to.equal('/filter/test'); }); + it('can filter URLs, excludeUrls and types', async () => { + const filter1: Electron.WebRequestFilter = { urls: [defaultURL + 'filter/*'], excludeUrls: [defaultURL + 'exclude/*'], types: ['xhr'] }; + ses.webRequest.onBeforeRequest(filter1, cancel); + + expect((await ajax(`${defaultURL}nofilter/test`)).data).to.equal('/nofilter/test'); + expect((await ajax(`${defaultURL}exclude/test`)).data).to.equal('/exclude/test'); + await expect(ajax(`${defaultURL}filter/test`)).to.eventually.be.rejected(); + + const filter2: Electron.WebRequestFilter = { urls: [defaultURL + 'filter/*'], excludeUrls: [defaultURL + 'exclude/*'], types: ['stylesheet'] }; + ses.webRequest.onBeforeRequest(filter2, cancel); + expect((await ajax(`${defaultURL}nofilter/test`)).data).to.equal('/nofilter/test'); + expect((await ajax(`${defaultURL}filter/test`)).data).to.equal('/filter/test'); + expect((await ajax(`${defaultURL}exclude/test`)).data).to.equal('/exclude/test'); + }); + it('receives details object', async () => { ses.webRequest.onBeforeRequest((details, callback) => { expect(details.id).to.be.a('number');
feat
0b0707145b157343c42266d2586ed9413a1d54f5
Milan Burda
2023-08-31 16:36:43
refactor: replace `.forEach()` with `for-of` (#39691) * refactor: replace `.forEach()` with `for-of` * refactor docs/fiddles/features/web-hid/renderer.js
diff --git a/docs/fiddles/features/web-hid/renderer.js b/docs/fiddles/features/web-hid/renderer.js index cbb00ab08f..133beb520c 100644 --- a/docs/fiddles/features/web-hid/renderer.js +++ b/docs/fiddles/features/web-hid/renderer.js @@ -1,19 +1,10 @@ -async function testIt () { - const grantedDevices = await navigator.hid.getDevices() - let grantedDeviceList = '' - grantedDevices.forEach(device => { - grantedDeviceList += `<hr>${device.productName}</hr>` - }) - document.getElementById('granted-devices').innerHTML = grantedDeviceList - const grantedDevices2 = await navigator.hid.requestDevice({ - filters: [] - }) +function formatDevices (devices) { + return devices.map(device => device.productName).join('<hr>') +} - grantedDeviceList = '' - grantedDevices2.forEach(device => { - grantedDeviceList += `<hr>${device.productName}</hr>` - }) - document.getElementById('granted-devices2').innerHTML = grantedDeviceList +async function testIt () { + document.getElementById('granted-devices').innerHTML = formatDevices(await navigator.hid.getDevices()) + document.getElementById('granted-devices2').innerHTML = formatDevices(await navigator.hid.requestDevice({ filters: [] })) } document.getElementById('clickme').addEventListener('click', testIt) diff --git a/docs/fiddles/features/web-usb/renderer.js b/docs/fiddles/features/web-usb/renderer.js index cf20c24cc9..1c217d957d 100644 --- a/docs/fiddles/features/web-usb/renderer.js +++ b/docs/fiddles/features/web-usb/renderer.js @@ -7,9 +7,9 @@ async function testIt () { const grantedDevices = await navigator.usb.getDevices() let grantedDeviceList = '' if (grantedDevices.length > 0) { - grantedDevices.forEach(device => { + for (const device of grantedDevices) { grantedDeviceList += `<hr>${getDeviceDetails(device)}</hr>` - }) + } } else { grantedDeviceList = noDevicesFoundMsg } diff --git a/docs/fiddles/menus/customize-menus/main.js b/docs/fiddles/menus/customize-menus/main.js index 3fc16f847d..a93293afde 100644 --- a/docs/fiddles/menus/customize-menus/main.js +++ b/docs/fiddles/menus/customize-menus/main.js @@ -68,9 +68,9 @@ const template = [ // on reload, start fresh and close any old // open secondary windows if (focusedWindow.id === 1) { - BrowserWindow.getAllWindows().forEach(win => { + for (const win of BrowserWindow.getAllWindows()) { if (win.id > 1) win.close() - }) + } } focusedWindow.reload() } @@ -209,15 +209,15 @@ function findReopenMenuItem () { if (!menu) return let reopenMenuItem - menu.items.forEach(item => { + for (const item of menu.items) { if (item.submenu) { - item.submenu.items.forEach(item => { - if (item.key === 'reopenMenuItem') { - reopenMenuItem = item + for (const subitem of item.submenu.items) { + if (subitem.key === 'reopenMenuItem') { + reopenMenuItem = subitem } - }) + } } - }) + } return reopenMenuItem } diff --git a/docs/tutorial/code-signing.md b/docs/tutorial/code-signing.md index e4ac634260..1a35bb7071 100644 --- a/docs/tutorial/code-signing.md +++ b/docs/tutorial/code-signing.md @@ -167,11 +167,11 @@ const supportBinaries = await msiCreator.create() // 🆕 Step 2a: optionally sign support binaries if you // sign you binaries as part of of your packaging script -supportBinaries.forEach(async (binary) => { +for (const binary of supportBinaries) { // Binaries are the new stub executable and optionally // the Squirrel auto updater. await signFile(binary) -}) +} // Step 3: Compile the template to a .msi file await msiCreator.compile() diff --git a/docs/tutorial/in-app-purchases.md b/docs/tutorial/in-app-purchases.md index d913df5482..db781d57e0 100644 --- a/docs/tutorial/in-app-purchases.md +++ b/docs/tutorial/in-app-purchases.md @@ -46,7 +46,7 @@ inAppPurchase.on('transactions-updated', (event, transactions) => { } // Check each transaction. - transactions.forEach((transaction) => { + for (const transaction of transactions) { const payment = transaction.payment switch (transaction.transactionState) { @@ -95,7 +95,7 @@ inAppPurchase.on('transactions-updated', (event, transactions) => { default: break } - }) + } }) // Check if the user is allowed to make in-app purchase. @@ -112,9 +112,9 @@ inAppPurchase.getProducts(PRODUCT_IDS).then(products => { } // Display the name and price of each product. - products.forEach(product => { + for (const product of products) { console.log(`The price of ${product.localizedTitle} is ${product.formattedPrice}.`) - }) + } // Ask the user which product they want to purchase. const selectedProduct = products[0] diff --git a/lib/browser/api/menu-utils.ts b/lib/browser/api/menu-utils.ts index 084432a66f..4daa615aeb 100644 --- a/lib/browser/api/menu-utils.ts +++ b/lib/browser/api/menu-utils.ts @@ -57,12 +57,17 @@ function sortTopologically<T> (originalOrder: T[], edgesById: Map<T, T[]>) { marked.add(mark); const edges = edgesById.get(mark); if (edges != null) { - edges.forEach(visit); + for (const edge of edges) { + visit(edge); + } } sorted.push(mark); }; - originalOrder.forEach(visit); + for (const edge of originalOrder) { + visit(edge); + } + return sorted; } @@ -98,24 +103,24 @@ function sortItemsInGroup<T> (group: {before?: T[], after?: T[], id?: T}[]) { const edges = new Map(); const idToIndex = new Map(group.map((item, i) => [item.id, i])); - group.forEach((item, i) => { + for (const [i, item] of group.entries()) { if (item.before) { - item.before.forEach(toID => { + for (const toID of item.before) { const to = idToIndex.get(toID); if (to != null) { pushOntoMultiMap(edges, to, i); } - }); + } } if (item.after) { - item.after.forEach(toID => { + for (const toID of item.after) { const to = idToIndex.get(toID); if (to != null) { pushOntoMultiMap(edges, i, to); } - }); + } } - }); + } const sortedNodes = sortTopologically(originalOrder, edges); return sortedNodes.map(i => group[i]); diff --git a/lib/browser/api/menu.ts b/lib/browser/api/menu.ts index 3cd17a8ce7..abdf50bf6d 100644 --- a/lib/browser/api/menu.ts +++ b/lib/browser/api/menu.ts @@ -153,9 +153,9 @@ Menu.prototype.insert = function (pos, item) { Menu.prototype._callMenuWillShow = function () { if (this.delegate) this.delegate.menuWillShow(this); - this.items.forEach(item => { + for (const item of this.items) { if (item.submenu) item.submenu._callMenuWillShow(); - }); + } }; /* Static Methods */ @@ -196,13 +196,13 @@ Menu.buildFromTemplate = function (template) { const filtered = removeExtraSeparators(sorted); const menu = new Menu(); - filtered.forEach(item => { + for (const item of filtered) { if (item instanceof MenuItem) { menu.append(item); } else { menu.append(new MenuItem(item)); } - }); + } return menu; }; @@ -280,9 +280,9 @@ function insertItemByType (this: MenuType, item: MenuItem, pos: number) { enumerable: true, get: () => checked.get(item), set: () => { - this.groupsMap[item.groupId].forEach(other => { + for (const other of this.groupsMap[item.groupId]) { if (other !== item) checked.set(other, false); - }); + } checked.set(item, true); } }); diff --git a/lib/browser/api/net-client-request.ts b/lib/browser/api/net-client-request.ts index f4948b26ca..9332f86ce1 100644 --- a/lib/browser/api/net-client-request.ts +++ b/lib/browser/api/net-client-request.ts @@ -70,9 +70,9 @@ class IncomingMessage extends Readable { get rawHeaders () { const rawHeadersArr: string[] = []; const { rawHeaders } = this._responseHead; - rawHeaders.forEach(header => { + for (const header of rawHeaders) { rawHeadersArr.push(header.key, header.value); - }); + } return rawHeadersArr; } diff --git a/lib/browser/api/net-fetch.ts b/lib/browser/api/net-fetch.ts index b39f488fc7..b73512f43f 100644 --- a/lib/browser/api/net-fetch.ts +++ b/lib/browser/api/net-fetch.ts @@ -98,7 +98,9 @@ export function fetchWithSession (input: RequestInfo, init: (RequestInit & {bypa r.on('response', (resp: IncomingMessage) => { if (locallyAborted) return; const headers = new Headers(); - for (const [k, v] of Object.entries(resp.headers)) { headers.set(k, Array.isArray(v) ? v.join(', ') : v); } + for (const [k, v] of Object.entries(resp.headers)) { + headers.set(k, Array.isArray(v) ? v.join(', ') : v); + } const nullBodyStatus = [101, 204, 205, 304]; const body = nullBodyStatus.includes(resp.statusCode) || req.method === 'HEAD' ? null : Readable.toWeb(resp as unknown as Readable) as ReadableStream; const rResp = new Response(body, { diff --git a/lib/browser/api/touch-bar.ts b/lib/browser/api/touch-bar.ts index 5ec18e2c7c..8f1c244fd8 100644 --- a/lib/browser/api/touch-bar.ts +++ b/lib/browser/api/touch-bar.ts @@ -323,13 +323,15 @@ class TouchBar extends EventEmitter implements Electron.TouchBar { this.items.set(item.id, item); item.on('change', this.changeListener); if (item.child instanceof TouchBar) { - item.child.orderedItems.forEach(registerItem); + for (const child of item.child.orderedItems) { + registerItem(child); + } } }; let hasOtherItemsProxy = false; const idSet = new Set(); - items.forEach((item) => { + for (const item of items) { if (!(item instanceof TouchBarItem)) { throw new TypeError('Each item must be an instance of TouchBarItem'); } @@ -347,7 +349,7 @@ class TouchBar extends EventEmitter implements Electron.TouchBar { } else { throw new Error('Cannot add a single instance of TouchBarItem multiple times in a TouchBar'); } - }); + } // register in separate loop after all items are validated for (const item of (items as TouchBarItem<any>[])) { diff --git a/lib/browser/guest-view-manager.ts b/lib/browser/guest-view-manager.ts index eda3d9aff5..942163711c 100644 --- a/lib/browser/guest-view-manager.ts +++ b/lib/browser/guest-view-manager.ts @@ -140,9 +140,9 @@ const createGuest = function (embedder: Electron.WebContents, embedderFrameId: n const makeProps = (eventKey: string, args: any[]) => { const props: Record<string, any> = {}; - webViewEvents[eventKey].forEach((prop, index) => { + for (const [index, prop] of webViewEvents[eventKey].entries()) { props[prop] = args[index]; - }); + } return props; }; diff --git a/lib/browser/parse-features-string.ts b/lib/browser/parse-features-string.ts index a6d451ea93..4d54479c04 100644 --- a/lib/browser/parse-features-string.ts +++ b/lib/browser/parse-features-string.ts @@ -80,11 +80,11 @@ export function parseFeatures (features: string) { const parsed = parseCommaSeparatedKeyValue(features); const webPreferences: { [K in AllowedWebPreference]?: any } = {}; - allowedWebPreferences.forEach((key) => { - if (parsed[key] === undefined) return; + for (const key of allowedWebPreferences) { + if (parsed[key] === undefined) continue; webPreferences[key] = parsed[key]; delete parsed[key]; - }); + } if (parsed.left !== undefined) parsed.x = parsed.left; if (parsed.top !== undefined) parsed.y = parsed.top; diff --git a/script/prepare-appveyor.js b/script/prepare-appveyor.js index a08ce66e3f..b24cd89eae 100644 --- a/script/prepare-appveyor.js +++ b/script/prepare-appveyor.js @@ -94,7 +94,9 @@ function useAppVeyorImage (targetBranch, options) { assert(validJobs.includes(options.job), `Unknown AppVeyor CI job name: ${options.job}. Valid values are: ${validJobs}.`); callAppVeyorBuildJobs(targetBranch, options.job, options); } else { - validJobs.forEach((job) => callAppVeyorBuildJobs(targetBranch, job, options)); + for (const job of validJobs) { + callAppVeyorBuildJobs(targetBranch, job, options); + } } } diff --git a/script/release/ci-release-build.js b/script/release/ci-release-build.js index fce6510ab1..4d874201d6 100644 --- a/script/release/ci-release-build.js +++ b/script/release/ci-release-build.js @@ -193,7 +193,9 @@ function buildAppVeyor (targetBranch, options) { assert(validJobs.includes(options.job), `Unknown AppVeyor CI job name: ${options.job}. Valid values are: ${validJobs}.`); callAppVeyor(targetBranch, options.job, options); } else { - validJobs.forEach((job) => callAppVeyor(targetBranch, job, options)); + for (const job of validJobs) { + callAppVeyor(targetBranch, job, options); + } } } @@ -243,7 +245,9 @@ function buildCircleCI (targetBranch, options) { } else { assert(!options.arch, 'Cannot provide a single architecture while building all workflows, please specify a single workflow via --workflow'); options.runningPublishWorkflows = true; - circleCIPublishWorkflows.forEach((job) => circleCIcall(targetBranch, job, options)); + for (const job of circleCIPublishWorkflows) { + circleCIcall(targetBranch, job, options); + } } } diff --git a/script/release/notes/notes.js b/script/release/notes/notes.js index 9f68d9336d..282d502458 100644 --- a/script/release/notes/notes.js +++ b/script/release/notes/notes.js @@ -461,7 +461,7 @@ const getNotes = async (fromRef, toRef, newVersion) => { toBranch }; - pool.commits.forEach(commit => { + for (const commit of pool.commits) { const str = commit.semanticType; if (commit.isBreakingChange) { notes.breaking.push(commit); @@ -478,7 +478,7 @@ const getNotes = async (fromRef, toRef, newVersion) => { } else { notes.unknown.push(commit); } - }); + } return notes; }; diff --git a/script/release/publish-to-npm.js b/script/release/publish-to-npm.js index fda6db43f8..8f66278531 100644 --- a/script/release/publish-to-npm.js +++ b/script/release/publish-to-npm.js @@ -58,18 +58,18 @@ new Promise((resolve, reject) => { .then((dirPath) => { tempDir = dirPath; // copy files from `/npm` to temp directory - files.forEach((name) => { + for (const name of files) { const noThirdSegment = name === 'README.md' || name === 'LICENSE'; fs.writeFileSync( path.join(tempDir, name), fs.readFileSync(path.join(ELECTRON_DIR, noThirdSegment ? '' : 'npm', name)) ); - }); + } // copy from root package.json to temp/package.json const packageJson = require(path.join(tempDir, 'package.json')); - jsonFields.forEach((fieldName) => { + for (const fieldName of jsonFields) { packageJson[fieldName] = rootPackageJson[fieldName]; - }); + } packageJson.version = currentElectronVersion; fs.writeFileSync( path.join(tempDir, 'package.json'), diff --git a/script/release/release.js b/script/release/release.js index 148909e0fd..ac5ecafea7 100755 --- a/script/release/release.js +++ b/script/release/release.js @@ -65,9 +65,9 @@ async function validateReleaseAssets (release, validatingRelease) { const downloadUrls = release.assets.map(asset => ({ url: asset.browser_download_url, file: asset.name })).sort((a, b) => a.file.localeCompare(b.file)); failureCount = 0; - requiredAssets.forEach(asset => { + for (const asset of requiredAssets) { check(extantAssets.includes(asset), asset); - }); + } check((failureCount === 0), 'All required GitHub assets exist for release', true); if (!validatingRelease || !release.draft) { diff --git a/spec/api-app-spec.ts b/spec/api-app-spec.ts index 97857464ef..f77b73b56a 100644 --- a/spec/api-app-spec.ts +++ b/spec/api-app-spec.ts @@ -1229,9 +1229,9 @@ describe('app module', () => { 'http://', 'https://' ]; - protocols.forEach((protocol) => { + for (const protocol of protocols) { expect(app.getApplicationNameForProtocol(protocol)).to.not.equal(''); - }); + } }); it('returns an empty string for a bogus protocol', () => { diff --git a/spec/api-browser-window-spec.ts b/spec/api-browser-window-spec.ts index 404465b5e1..4b5c752404 100644 --- a/spec/api-browser-window-spec.ts +++ b/spec/api-browser-window-spec.ts @@ -276,9 +276,9 @@ describe('BrowserWindow module', () => { } }; const windows = Array.from(Array(windowCount)).map(() => new BrowserWindow(windowOptions)); - windows.forEach(win => win.show()); - windows.forEach(win => win.focus()); - windows.forEach(win => win.destroy()); + for (const win of windows) win.show(); + for (const win of windows) win.focus(); + for (const win of windows) win.destroy(); app.removeListener('browser-window-focus', focusListener); }); }); @@ -1342,31 +1342,31 @@ describe('BrowserWindow module', () => { const fakeSourceIds = [ 'none', 'screen:0', 'window:fake', 'window:1234', 'foobar:1:2' ]; - fakeSourceIds.forEach((sourceId) => { + for (const sourceId of fakeSourceIds) { expect(() => { w.moveAbove(sourceId); }).to.throw(/Invalid media source id/); - }); + } }); it('should throw an exception if wrong type', async () => { const fakeSourceIds = [null as any, 123 as any]; - fakeSourceIds.forEach((sourceId) => { + for (const sourceId of fakeSourceIds) { expect(() => { w.moveAbove(sourceId); }).to.throw(/Error processing argument at index 0 */); - }); + } }); it('should throw an exception if invalid window', async () => { // It is very unlikely that these window id exist. const fakeSourceIds = ['window:99999999:0', 'window:123456:1', 'window:123456:9']; - fakeSourceIds.forEach((sourceId) => { + for (const sourceId of fakeSourceIds) { expect(() => { w.moveAbove(sourceId); }).to.throw(/Invalid media source id/); - }); + } }); it('should not throw an exception', async () => { diff --git a/spec/api-context-bridge-spec.ts b/spec/api-context-bridge-spec.ts index c3f8ab3183..4b5952c55f 100644 --- a/spec/api-context-bridge-spec.ts +++ b/spec/api-context-bridge-spec.ts @@ -1006,10 +1006,10 @@ describe('contextBridge', () => { } }; const keys: string[] = []; - Object.entries(toExpose).forEach(([key, value]) => { + for (const [key, value] of Object.entries(toExpose)) { keys.push(key); contextBridge.exposeInMainWorld(key, value); - }); + } contextBridge.exposeInMainWorld('keys', keys); }); const result = await callWithBindings(async (root: any) => { diff --git a/spec/api-menu-item-spec.ts b/spec/api-menu-item-spec.ts index fc015da321..0071a3904e 100644 --- a/spec/api-menu-item-spec.ts +++ b/spec/api-menu-item-spec.ts @@ -136,9 +136,9 @@ describe('MenuItems', () => { const groups = findRadioGroups(template); - groups.forEach(g => { + for (const g of groups) { expect(findChecked(menu.items, g.begin!, g.end!)).to.deep.equal([g.begin]); - }); + } }); it('should assign groupId automatically', () => { @@ -146,7 +146,7 @@ describe('MenuItems', () => { const usedGroupIds = new Set(); const groups = findRadioGroups(template); - groups.forEach(g => { + for (const g of groups) { const groupId = (menu.items[g.begin!] as any).groupId; // groupId should be previously unused @@ -158,14 +158,14 @@ describe('MenuItems', () => { for (let i = g.begin!; i < g.end!; ++i) { expect((menu.items[i] as any).groupId).to.equal(groupId); } - }); + } }); it("setting 'checked' should flip other items' 'checked' property", () => { const menu = Menu.buildFromTemplate(template); const groups = findRadioGroups(template); - groups.forEach(g => { + for (const g of groups) { expect(findChecked(menu.items, g.begin!, g.end!)).to.deep.equal([]); menu.items[g.begin!].checked = true; @@ -173,7 +173,7 @@ describe('MenuItems', () => { menu.items[g.end! - 1].checked = true; expect(findChecked(menu.items, g.begin!, g.end!)).to.deep.equal([g.end! - 1]); - }); + } }); }); }); diff --git a/spec/api-net-spec.ts b/spec/api-net-spec.ts index 501dc6307a..882957db7f 100644 --- a/spec/api-net-spec.ts +++ b/spec/api-net-spec.ts @@ -68,7 +68,9 @@ async function respondNTimes (fn: http.RequestListener, n: number): Promise<stri server.on('connection', s => sockets.push(s)); defer(() => { server.close(); - sockets.forEach(s => s.destroy()); + for (const socket of sockets) { + socket.destroy(); + } }); return (await listen(server)).url; } @@ -771,7 +773,7 @@ describe('net module', () => { }); }); - ['Lax', 'Strict'].forEach((mode) => { + 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; @@ -812,7 +814,7 @@ describe('net module', () => { 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) => { @@ -1065,7 +1067,7 @@ describe('net module', () => { await collectStreamBody(await getResponse(urlRequest)); }); - ['navigate', 'cors', 'no-cors', 'same-origin'].forEach((mode) => { + for (const mode of ['navigate', 'cors', 'no-cors', 'same-origin']) { it(`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); @@ -1080,7 +1082,7 @@ describe('net module', () => { 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) => { @@ -1095,12 +1097,12 @@ describe('net module', () => { 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' - ].forEach((dest) => { + ]) { it(`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); @@ -1115,7 +1117,7 @@ describe('net module', () => { 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) => { @@ -1691,11 +1693,11 @@ describe('net module', () => { await once(urlRequest, 'close'); await new Promise((resolve, reject) => { - ['finish', 'abort', 'close', 'error'].forEach(evName => { + for (const evName of ['finish', 'abort', 'close', 'error']) { urlRequest.on(evName as any, () => { reject(new Error(`Unexpected ${evName} event`)); }); - }); + } setTimeout(50).then(resolve); }); }); @@ -1934,9 +1936,9 @@ describe('net module', () => { const serverUrl = await respondOnce.toSingleURL((request, response) => { response.statusCode = 200; response.statusMessage = 'OK'; - customHeaders.forEach((headerTuple) => { + for (const headerTuple of customHeaders) { response.setHeader(headerTuple[0], headerTuple[1]); - }); + } response.end(); }); const urlRequest = net.request(serverUrl); @@ -1948,15 +1950,15 @@ describe('net module', () => { expect(rawHeaders).to.be.an('array'); let rawHeadersIdx = 0; - customHeaders.forEach((headerTuple) => { + for (const headerTuple of customHeaders) { const headerKey = headerTuple[0]; const headerValues = Array.isArray(headerTuple[1]) ? headerTuple[1] : [headerTuple[1]]; - headerValues.forEach((headerValue) => { + for (const headerValue of headerValues) { expect(rawHeaders[rawHeadersIdx]).to.equal(headerKey); expect(rawHeaders[rawHeadersIdx + 1]).to.equal(headerValue); rawHeadersIdx += 2; - }); - }); + } + } await collectStreamBody(response); }); diff --git a/spec/api-subframe-spec.ts b/spec/api-subframe-spec.ts index 1a56612695..043141a12c 100644 --- a/spec/api-subframe-spec.ts +++ b/spec/api-subframe-spec.ts @@ -157,7 +157,7 @@ describe('renderer nodeIntegrationInSubFrames', () => { }); }; - generateConfigs( + const configs = generateConfigs( { preload: path.resolve(__dirname, 'fixtures/sub-frames/preload.js'), nodeIntegrationInSubFrames: true @@ -174,9 +174,11 @@ describe('renderer nodeIntegrationInSubFrames', () => { name: 'webview', webPreferences: { webviewTag: true, preload: false } } - ).forEach(config => { + ); + + for (const config of configs) { generateTests(config.title, config.webPreferences); - }); + } describe('internal <iframe> inside of <webview>', () => { let w: BrowserWindow; diff --git a/spec/api-system-preferences-spec.ts b/spec/api-system-preferences-spec.ts index ab4f33b171..27a73dfccc 100644 --- a/spec/api-system-preferences-spec.ts +++ b/spec/api-system-preferences-spec.ts @@ -32,7 +32,7 @@ describe('systemPreferences module', () => { ] as const; const defaultsDict: Record<string, any> = {}; - defaultsMap.forEach(row => { defaultsDict[row.key] = row.value; }); + for (const row of defaultsMap) { defaultsDict[row.key] = row.value; } systemPreferences.registerDefaults(defaultsDict); @@ -160,10 +160,10 @@ describe('systemPreferences module', () => { it('returns a valid system color', () => { const colors = ['blue', 'brown', 'gray', 'green', 'orange', 'pink', 'purple', 'red', 'yellow'] as const; - colors.forEach(color => { + for (const color of colors) { const sysColor = systemPreferences.getSystemColor(color); expect(sysColor).to.be.a('string'); - }); + } }); }); @@ -211,10 +211,10 @@ describe('systemPreferences module', () => { 'window-frame-text' ] as const; - colors.forEach(color => { + for (const color of colors) { const sysColor = systemPreferences.getColor(color); expect(sysColor).to.be.a('string'); - }); + } await expectDeprecationMessages( () => { diff --git a/spec/api-web-contents-spec.ts b/spec/api-web-contents-spec.ts index 161f515eb6..b440ef2b3e 100644 --- a/spec/api-web-contents-spec.ts +++ b/spec/api-web-contents-spec.ts @@ -1312,10 +1312,10 @@ describe('webContents module', () => { 'default_public_and_private_interfaces', 'disable_non_proxied_udp' ] as const; - policies.forEach((policy) => { + for (const policy of policies) { w.webContents.setWebRTCIPHandlingPolicy(policy); expect(w.webContents.getWebRTCIPHandlingPolicy()).to.equal(policy); - }); + } }); }); diff --git a/spec/chromium-spec.ts b/spec/chromium-spec.ts index c2b39e4337..c1ccab48bd 100644 --- a/spec/chromium-spec.ts +++ b/spec/chromium-spec.ts @@ -904,7 +904,7 @@ describe('chromium features', () => { await closeAllWindows(); }); - [true, false].forEach((isSandboxEnabled) => + for (const isSandboxEnabled of [true, false]) { describe(`sandbox=${isSandboxEnabled}`, () => { it('posts data in the same window', async () => { const w = new BrowserWindow({ @@ -954,8 +954,8 @@ describe('chromium features', () => { const res = await newWin.webContents.executeJavaScript('document.body.innerText'); expect(res).to.equal('body:greeting=hello'); }); - }) - ); + }); + } }); describe('window.open', () => { @@ -1913,7 +1913,7 @@ describe('chromium features', () => { }); describe('DOM storage quota increase', () => { - ['localStorage', 'sessionStorage'].forEach((storageName) => { + for (const storageName of ['localStorage', 'sessionStorage']) { it(`allows saving at least 40MiB in ${storageName}`, async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixturesPath, 'pages', 'blank.html')); @@ -1959,7 +1959,7 @@ describe('chromium features', () => { } })()).to.eventually.be.rejected(); }); - }); + } }); describe('persistent storage', () => { diff --git a/spec/extensions-spec.ts b/spec/extensions-spec.ts index c9cafe051e..05098f0dd1 100644 --- a/spec/extensions-spec.ts +++ b/spec/extensions-spec.ts @@ -44,9 +44,9 @@ describe('chrome extensions', () => { }); afterEach(closeAllWindows); afterEach(() => { - session.defaultSession.getAllExtensions().forEach((e: any) => { + for (const e of session.defaultSession.getAllExtensions()) { session.defaultSession.removeExtension(e.id); - }); + } }); it('does not crash when using chrome.management', async () => { @@ -759,9 +759,9 @@ describe('chrome extensions', () => { describe('extension ui pages', () => { afterEach(() => { - session.defaultSession.getAllExtensions().forEach(e => { + for (const e of session.defaultSession.getAllExtensions()) { session.defaultSession.removeExtension(e.id); - }); + } }); it('loads a ui page of an extension', async () => { diff --git a/spec/fixtures/pages/css-transparent.html b/spec/fixtures/pages/css-transparent.html index 7747eafc94..48e406c884 100644 --- a/spec/fixtures/pages/css-transparent.html +++ b/spec/fixtures/pages/css-transparent.html @@ -14,11 +14,11 @@ const { ipcRenderer } = require('electron'); const observer = new MutationObserver((mutationList, observer) => { - mutationList.forEach(({ type, attributeName }) => { + for (const { type, attributeName } of mutationList) { if (type === 'attributes' && attributeName === 'style') { ipcRenderer.send('set-transparent'); } - }); + } }); observer.observe(document.body, { attributes: true }); diff --git a/spec/guest-window-manager-spec.ts b/spec/guest-window-manager-spec.ts index 621de49122..8e4cffee3b 100644 --- a/spec/guest-window-manager-spec.ts +++ b/spec/guest-window-manager-spec.ts @@ -27,7 +27,9 @@ describe('webContents.setWindowOpenHandler', () => { done(e); } finally { process.removeAllListeners('uncaughtException'); - listeners.forEach((listener) => process.on('uncaughtException', listener)); + for (const listener of listeners) { + process.on('uncaughtException', listener); + } } }); diff --git a/spec/index.js b/spec/index.js index 47c7352da6..259bca132c 100644 --- a/spec/index.js +++ b/spec/index.js @@ -148,9 +148,9 @@ app.whenReady().then(async () => { const { getFiles } = require('./get-files'); const testFiles = await getFiles(__dirname, { filter }); - testFiles.sort().forEach((file) => { + for (const file of testFiles.sort()) { mocha.addFile(file); - }); + } if (validTestPaths && validTestPaths.length > 0 && testFiles.length === 0) { console.error('Test files were provided, but they did not match any searched files'); diff --git a/spec/node-spec.ts b/spec/node-spec.ts index 0168c1a6c9..1369b6957e 100644 --- a/spec/node-spec.ts +++ b/spec/node-spec.ts @@ -195,9 +195,9 @@ describe('node feature', () => { emitter.removeAllListeners(eventName); emitter.once(eventName, (...args) => { emitter.removeAllListeners(eventName); - listeners.forEach((listener) => { + for (const listener of listeners) { emitter.on(eventName, listener); - }); + } callback(...args); }); diff --git a/spec/webview-spec.ts b/spec/webview-spec.ts index aa91e56f7c..240de3c8d4 100644 --- a/spec/webview-spec.ts +++ b/spec/webview-spec.ts @@ -929,7 +929,7 @@ describe('<webview> tag', function () { }); afterEach(async () => { await w.executeJavaScript(`{ - document.querySelectorAll('webview').forEach(el => el.remove()) + for (const el of document.querySelectorAll('webview')) el.remove(); }`); }); after(closeAllWindows); @@ -1411,7 +1411,7 @@ describe('<webview> tag', function () { }); afterEach(async () => { await w.executeJavaScript(`{ - document.querySelectorAll('webview').forEach(el => el.remove()) + for (const el of document.querySelectorAll('webview')) el.remove(); }`); }); after(closeAllWindows); @@ -1791,7 +1791,7 @@ describe('<webview> tag', function () { }); afterEach(async () => { await w.executeJavaScript(`{ - document.querySelectorAll('webview').forEach(el => el.remove()) + for (const el of document.querySelectorAll('webview')) el.remove(); }`); }); after(closeAllWindows); @@ -2088,7 +2088,7 @@ describe('<webview> tag', function () { }); afterEach(async () => { await w.executeJavaScript(`{ - document.querySelectorAll('webview').forEach(el => el.remove()) + for (const el of document.querySelectorAll('webview')) el.remove(); }`); }); after(closeAllWindows);
refactor
8e8ea3ee8b0f45e8b28db3bb9eb77dcae0b37b1e
Shelley Vohr
2024-06-19 11:27:07
fix: MessagePort closing unexpectedly with non-cloneable objects (#42535) * fix: MessagePort closing unexpectedly with non-cloneable objects * fix: handle serialization failure in parentPort
diff --git a/shell/browser/api/message_port.cc b/shell/browser/api/message_port.cc index 6afeaa0c69..a81360b0f1 100644 --- a/shell/browser/api/message_port.cc +++ b/shell/browser/api/message_port.cc @@ -76,8 +76,11 @@ void MessagePort::PostMessage(gin::Arguments* args) { return; } - electron::SerializeV8Value(args->isolate(), message_value, - &transferable_message); + if (!electron::SerializeV8Value(args->isolate(), message_value, + &transferable_message)) { + // SerializeV8Value sets an exception. + return; + } v8::Local<v8::Value> transferables; std::vector<gin::Handle<MessagePort>> wrapped_ports; diff --git a/shell/services/node/parent_port.cc b/shell/services/node/parent_port.cc index 89cf18dcb5..13d9433f30 100644 --- a/shell/services/node/parent_port.cc +++ b/shell/services/node/parent_port.cc @@ -44,7 +44,13 @@ void ParentPort::PostMessage(v8::Local<v8::Value> message_value) { if (!connector_closed_ && connector_ && connector_->is_valid()) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); blink::TransferableMessage transferable_message; - electron::SerializeV8Value(isolate, message_value, &transferable_message); + + if (!electron::SerializeV8Value(isolate, message_value, + &transferable_message)) { + // SerializeV8Value sets an exception. + return; + } + mojo::Message mojo_message = blink::mojom::TransferableMessage::WrapAsMessage( std::move(transferable_message)); diff --git a/spec/api-utility-process-spec.ts b/spec/api-utility-process-spec.ts index ccc551bbac..3694e2c1ad 100644 --- a/spec/api-utility-process-spec.ts +++ b/spec/api-utility-process-spec.ts @@ -297,6 +297,17 @@ describe('utilityProcess module', () => { expect(child.kill()).to.be.true(); await exit; }); + + it('handles the parent port trying to send an non-clonable object', async () => { + const child = utilityProcess.fork(path.join(fixturesPath, 'non-cloneable.js')); + await once(child, 'spawn'); + child.postMessage('non-cloneable'); + const [data] = await once(child, 'message'); + expect(data).to.equal('caught-non-cloneable'); + const exit = once(child, 'exit'); + expect(child.kill()).to.be.true(); + await exit; + }); }); describe('behavior', () => { diff --git a/spec/fixtures/api/utility-process/non-cloneable.js b/spec/fixtures/api/utility-process/non-cloneable.js new file mode 100644 index 0000000000..fd416ee2be --- /dev/null +++ b/spec/fixtures/api/utility-process/non-cloneable.js @@ -0,0 +1,11 @@ +const nonClonableObject = () => {}; + +process.parentPort.on('message', () => { + try { + process.parentPort.postMessage(nonClonableObject); + } catch (error) { + if (/An object could not be cloned/.test(error.message)) { + process.parentPort.postMessage('caught-non-cloneable'); + } + } +});
fix
2caf08059e23b3a7a2af8d3fe1ef5ebfe3cdfbb9
David Sanders
2023-07-24 03:33:26
docs: update @electron/fuses code examples (#39175)
diff --git a/docs/tutorial/asar-integrity.md b/docs/tutorial/asar-integrity.md index 2bbf3ec840..7558890f93 100644 --- a/docs/tutorial/asar-integrity.md +++ b/docs/tutorial/asar-integrity.md @@ -41,7 +41,9 @@ Valid `algorithm` values are currently `SHA256` only. The `hash` is a hash of t ASAR integrity checking is currently disabled by default and can be enabled by toggling a fuse. See [Electron Fuses](fuses.md) for more information on what Electron Fuses are and how they work. When enabling this fuse you typically also want to enable the `onlyLoadAppFromAsar` fuse otherwise the validity checking can be bypassed via the Electron app code search path. ```js @ts-nocheck -require('@electron/fuses').flipFuses( +const { flipFuses, FuseVersion, FuseV1Options } = require('@electron/fuses') + +flipFuses( // E.g. /a/b/Foo.app pathToPackagedApp, { diff --git a/docs/tutorial/fuses.md b/docs/tutorial/fuses.md index ed39e7b267..ea5b8a3428 100644 --- a/docs/tutorial/fuses.md +++ b/docs/tutorial/fuses.md @@ -68,7 +68,9 @@ The loadBrowserProcessSpecificV8Snapshot fuse changes which V8 snapshot file is We've made a handy module, [`@electron/fuses`](https://npmjs.com/package/@electron/fuses), to make flipping these fuses easy. Check out the README of that module for more details on usage and potential error cases. ```js @ts-nocheck -require('@electron/fuses').flipFuses( +const { flipFuses, FuseVersion, FuseV1Options } = require('@electron/fuses') + +flipFuses( // Path to electron require('electron'), // Fuses to flip @@ -82,7 +84,7 @@ require('@electron/fuses').flipFuses( You can validate the fuses have been flipped or check the fuse status of an arbitrary Electron app using the fuses CLI. ```bash - npx @electron/fuses read --app /Applications/Foo.app +npx @electron/fuses read --app /Applications/Foo.app ``` ### The hard way
docs
ecd7eb36ac7ae4bc190d8bc12550cdc30c82e5d6
John Kleinschmidt
2025-02-18 15:04:47
build: remove appveyor bake (#45073)
null
build
9b166b3ed4185a69d5f5bab9d8498951f507d49b
Robo
2024-08-14 11:36:47
feat: support app#login event for utility process net requests (#42631) * feat: support app#login event for utility process net requests * chore: address review feedback * GlobalRequestID: Avoid unwanted inlining and narrowing int conversions Refs https://chromium-review.googlesource.com/c/chromium/src/+/5702737
diff --git a/docs/api/app.md b/docs/api/app.md index 5c84730313..2a137c2983 100755 --- a/docs/api/app.md +++ b/docs/api/app.md @@ -345,9 +345,10 @@ app.on('select-client-certificate', (event, webContents, url, list, callback) => Returns: * `event` Event -* `webContents` [WebContents](web-contents.md) +* `webContents` [WebContents](web-contents.md) (optional) * `authenticationResponseDetails` Object * `url` URL + * `pid` number * `authInfo` Object * `isProxy` boolean * `scheme` string @@ -358,7 +359,7 @@ Returns: * `username` string (optional) * `password` string (optional) -Emitted when `webContents` wants to do basic auth. +Emitted when `webContents` or [Utility process](../glossary.md#utility-process) wants to do basic auth. The default behavior is to cancel all authentications. To override this you should prevent the default behavior with `event.preventDefault()` and call diff --git a/docs/api/utility-process.md b/docs/api/utility-process.md index f628f4164d..100c3ead6d 100644 --- a/docs/api/utility-process.md +++ b/docs/api/utility-process.md @@ -36,6 +36,8 @@ Process: [Main](../glossary.md#main-process)<br /> `com.apple.security.cs.allow-unsigned-executable-memory` entitlements. This will allow the utility process to load unsigned libraries. Unless you specifically need this capability, it is best to leave this disabled. Default is `false`. + * `respondToAuthRequestsFromMainProcess` boolean (optional) - With this flag, all HTTP 401 and 407 network + requests created via the [net module](net.md) will allow responding to them via the [`app#login`](app.md#event-login) event in the main process instead of the default [`login`](client-request.md#event-login) event on the [`ClientRequest`](client-request.md) object. Returns [`UtilityProcess`](utility-process.md#class-utilityprocess) diff --git a/docs/breaking-changes.md b/docs/breaking-changes.md index 7a6e0df45f..58a39a99e5 100644 --- a/docs/breaking-changes.md +++ b/docs/breaking-changes.md @@ -14,6 +14,12 @@ This document uses the following convention to categorize breaking changes: ## Planned Breaking API Changes (33.0) +### Behavior Changed: `webContents` property on `login` on `app` + +The `webContents` property in the `login` event from `app` will be `null` +when the event is triggered for requests from the [utility process](api/utility-process.md) +created with `respondToAuthRequestsFromMainProcess` option. + ### Deprecated: `textured` option in `BrowserWindowConstructorOption.type` The `textured` option of `type` in `BrowserWindowConstructorOptions` has been deprecated with no replacement. This option relied on the [`NSWindowStyleMaskTexturedBackground`](https://developer.apple.com/documentation/appkit/nswindowstylemask/nswindowstylemasktexturedbackground) style mask on macOS, which has been deprecated with no alternative. diff --git a/filenames.gni b/filenames.gni index 8766b716f6..6ae9f9e70f 100644 --- a/filenames.gni +++ b/filenames.gni @@ -453,6 +453,8 @@ filenames = { "shell/browser/net/resolve_proxy_helper.h", "shell/browser/net/system_network_context_manager.cc", "shell/browser/net/system_network_context_manager.h", + "shell/browser/net/url_loader_network_observer.cc", + "shell/browser/net/url_loader_network_observer.h", "shell/browser/net/url_pipe_loader.cc", "shell/browser/net/url_pipe_loader.h", "shell/browser/net/web_request_api_interface.h", diff --git a/shell/browser/api/electron_api_utility_process.cc b/shell/browser/api/electron_api_utility_process.cc index 0d02fd3ada..10050210e2 100644 --- a/shell/browser/api/electron_api_utility_process.cc +++ b/shell/browser/api/electron_api_utility_process.cc @@ -63,7 +63,8 @@ UtilityProcessWrapper::UtilityProcessWrapper( std::map<IOHandle, IOType> stdio, base::EnvironmentMap env_map, base::FilePath current_working_directory, - bool use_plugin_helper) { + bool use_plugin_helper, + bool create_network_observer) { #if BUILDFLAG(IS_WIN) base::win::ScopedHandle stdout_write(nullptr); base::win::ScopedHandle stderr_write(nullptr); @@ -203,6 +204,11 @@ UtilityProcessWrapper::UtilityProcessWrapper( loader_params->process_id = pid_; loader_params->is_orb_enabled = false; loader_params->is_trusted = true; + if (create_network_observer) { + url_loader_network_observer_.emplace(); + loader_params->url_loader_network_observer = + url_loader_network_observer_->Bind(); + } network::mojom::NetworkContext* network_context = g_browser_process->system_network_context_manager()->GetContext(); network_context->CreateURLLoaderFactory( @@ -213,6 +219,8 @@ UtilityProcessWrapper::UtilityProcessWrapper( network_context->CreateHostResolver( {}, host_resolver.InitWithNewPipeAndPassReceiver()); params->host_resolver = std::move(host_resolver); + params->use_network_observer_from_url_loader_factory = + create_network_observer; node_service_remote_->Initialize(std::move(params)); } @@ -230,6 +238,9 @@ void UtilityProcessWrapper::OnServiceProcessLaunch( EmitWithoutEvent("stdout", stdout_read_fd_); if (stderr_read_fd_ != -1) EmitWithoutEvent("stderr", stderr_read_fd_); + if (url_loader_network_observer_.has_value()) { + url_loader_network_observer_->set_process_id(pid_); + } EmitWithoutEvent("spawn"); } @@ -378,6 +389,7 @@ gin::Handle<UtilityProcessWrapper> UtilityProcessWrapper::Create( std::u16string display_name; bool use_plugin_helper = false; + bool create_network_observer = false; std::map<IOHandle, IOType> stdio; base::FilePath current_working_directory; base::EnvironmentMap env_map; @@ -403,6 +415,7 @@ gin::Handle<UtilityProcessWrapper> UtilityProcessWrapper::Create( opts.Get("serviceName", &display_name); opts.Get("cwd", &current_working_directory); + opts.Get("respondToAuthRequestsFromMainProcess", &create_network_observer); std::vector<std::string> stdio_arr{"ignore", "inherit", "inherit"}; opts.Get("stdio", &stdio_arr); @@ -423,10 +436,10 @@ gin::Handle<UtilityProcessWrapper> UtilityProcessWrapper::Create( #endif } auto handle = gin::CreateHandle( - args->isolate(), - new UtilityProcessWrapper(std::move(params), display_name, - std::move(stdio), env_map, - current_working_directory, use_plugin_helper)); + args->isolate(), new UtilityProcessWrapper( + std::move(params), display_name, std::move(stdio), + env_map, current_working_directory, + use_plugin_helper, create_network_observer)); handle->Pin(args->isolate()); return handle; } diff --git a/shell/browser/api/electron_api_utility_process.h b/shell/browser/api/electron_api_utility_process.h index 9e5d40ea1c..767252d54f 100644 --- a/shell/browser/api/electron_api_utility_process.h +++ b/shell/browser/api/electron_api_utility_process.h @@ -18,6 +18,7 @@ #include "mojo/public/cpp/bindings/message.h" #include "mojo/public/cpp/bindings/remote.h" #include "shell/browser/event_emitter_mixin.h" +#include "shell/browser/net/url_loader_network_observer.h" #include "shell/common/gin_helper/pinnable.h" #include "shell/services/node/public/mojom/node_service.mojom.h" #include "v8/include/v8-forward.h" @@ -66,7 +67,8 @@ class UtilityProcessWrapper std::map<IOHandle, IOType> stdio, base::EnvironmentMap env_map, base::FilePath current_working_directory, - bool use_plugin_helper); + bool use_plugin_helper, + bool create_network_observer); void OnServiceProcessLaunch(const base::Process& process); void CloseConnectorPort(); @@ -101,6 +103,8 @@ class UtilityProcessWrapper std::unique_ptr<mojo::Connector> connector_; blink::MessagePortDescriptor host_port_; mojo::Remote<node::mojom::NodeService> node_service_remote_; + std::optional<electron::URLLoaderNetworkObserver> + url_loader_network_observer_; base::WeakPtrFactory<UtilityProcessWrapper> weak_factory_{this}; }; diff --git a/shell/browser/electron_browser_client.cc b/shell/browser/electron_browser_client.cc index 91dc148f67..9c04627f4c 100644 --- a/shell/browser/electron_browser_client.cc +++ b/shell/browser/electron_browser_client.cc @@ -1649,8 +1649,8 @@ ElectronBrowserClient::CreateLoginDelegate( bool first_auth_attempt, LoginAuthRequiredCallback auth_required_callback) { return std::make_unique<LoginHandler>( - auth_info, web_contents, is_main_frame, url, response_headers, - first_auth_attempt, std::move(auth_required_callback)); + auth_info, web_contents, is_main_frame, base::kNullProcessId, url, + response_headers, first_auth_attempt, std::move(auth_required_callback)); } std::vector<std::unique_ptr<blink::URLLoaderThrottle>> diff --git a/shell/browser/login_handler.cc b/shell/browser/login_handler.cc index 1000507731..3b92625ff4 100644 --- a/shell/browser/login_handler.cc +++ b/shell/browser/login_handler.cc @@ -9,6 +9,7 @@ #include "base/task/sequenced_task_runner.h" #include "gin/arguments.h" #include "gin/dictionary.h" +#include "shell/browser/api/electron_api_app.h" #include "shell/browser/api/electron_api_web_contents.h" #include "shell/browser/javascript_environment.h" #include "shell/common/gin_converters/callback_converter.h" @@ -24,39 +25,44 @@ LoginHandler::LoginHandler( const net::AuthChallengeInfo& auth_info, content::WebContents* web_contents, bool is_main_frame, + base::ProcessId process_id, const GURL& url, scoped_refptr<net::HttpResponseHeaders> response_headers, bool first_auth_attempt, LoginAuthRequiredCallback auth_required_callback) - - : WebContentsObserver(web_contents), - auth_required_callback_(std::move(auth_required_callback)) { + : auth_required_callback_(std::move(auth_required_callback)) { DCHECK_CURRENTLY_ON(BrowserThread::UI); base::SequencedTaskRunner::GetCurrentDefault()->PostTask( FROM_HERE, base::BindOnce(&LoginHandler::EmitEvent, weak_factory_.GetWeakPtr(), - auth_info, is_main_frame, url, response_headers, - first_auth_attempt)); + auth_info, web_contents, is_main_frame, process_id, url, + response_headers, first_auth_attempt)); } void LoginHandler::EmitEvent( net::AuthChallengeInfo auth_info, + content::WebContents* web_contents, bool is_main_frame, + base::ProcessId process_id, const GURL& url, scoped_refptr<net::HttpResponseHeaders> response_headers, bool first_auth_attempt) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); - api::WebContents* api_web_contents = api::WebContents::From(web_contents()); - if (!api_web_contents) { - std::move(auth_required_callback_).Run(std::nullopt); - return; + raw_ptr<api::WebContents> api_web_contents = nullptr; + if (web_contents) { + api_web_contents = api::WebContents::From(web_contents); + if (!api_web_contents) { + std::move(auth_required_callback_).Run(std::nullopt); + return; + } } auto details = gin::Dictionary::CreateEmpty(isolate); details.Set("url", url); + details.Set("pid", process_id); // These parameters aren't documented, and I'm not sure that they're useful, // but we might as well stick 'em on the details object. If it turns out they @@ -66,10 +72,18 @@ void LoginHandler::EmitEvent( details.Set("responseHeaders", response_headers.get()); auto weak_this = weak_factory_.GetWeakPtr(); - bool default_prevented = - api_web_contents->Emit("login", std::move(details), auth_info, - base::BindOnce(&LoginHandler::CallbackFromJS, - weak_factory_.GetWeakPtr())); + bool default_prevented = false; + if (api_web_contents) { + default_prevented = + api_web_contents->Emit("login", std::move(details), auth_info, + base::BindOnce(&LoginHandler::CallbackFromJS, + weak_factory_.GetWeakPtr())); + } else { + default_prevented = + api::App::Get()->Emit("login", nullptr, std::move(details), auth_info, + base::BindOnce(&LoginHandler::CallbackFromJS, + weak_factory_.GetWeakPtr())); + } // ⚠️ NB, if CallbackFromJS is called during Emit(), |this| will have been // deleted. Check the weak ptr before accessing any member variables to // prevent UAF. diff --git a/shell/browser/login_handler.h b/shell/browser/login_handler.h index b4456703ff..507483a63a 100644 --- a/shell/browser/login_handler.h +++ b/shell/browser/login_handler.h @@ -5,9 +5,9 @@ #ifndef ELECTRON_SHELL_BROWSER_LOGIN_HANDLER_H_ #define ELECTRON_SHELL_BROWSER_LOGIN_HANDLER_H_ +#include "base/process/process_handle.h" #include "content/public/browser/content_browser_client.h" #include "content/public/browser/login_delegate.h" -#include "content/public/browser/web_contents_observer.h" namespace content { class WebContents; @@ -20,12 +20,12 @@ class Arguments; namespace electron { // Handles HTTP basic auth. -class LoginHandler : public content::LoginDelegate, - private content::WebContentsObserver { +class LoginHandler : public content::LoginDelegate { public: LoginHandler(const net::AuthChallengeInfo& auth_info, content::WebContents* web_contents, bool is_main_frame, + base::ProcessId process_id, const GURL& url, scoped_refptr<net::HttpResponseHeaders> response_headers, bool first_auth_attempt, @@ -38,7 +38,9 @@ class LoginHandler : public content::LoginDelegate, private: void EmitEvent(net::AuthChallengeInfo auth_info, + content::WebContents* web_contents, bool is_main_frame, + base::ProcessId process_id, const GURL& url, scoped_refptr<net::HttpResponseHeaders> response_headers, bool first_auth_attempt); diff --git a/shell/browser/net/url_loader_network_observer.cc b/shell/browser/net/url_loader_network_observer.cc new file mode 100644 index 0000000000..0243dec186 --- /dev/null +++ b/shell/browser/net/url_loader_network_observer.cc @@ -0,0 +1,120 @@ +// Copyright (c) 2024 Microsoft, GmbH +// Use of this source code is governed by the MIT license that can be +// found in the LICENSE file. + +#include "shell/browser/net/url_loader_network_observer.h" + +#include "base/functional/bind.h" +#include "content/public/browser/browser_thread.h" +#include "shell/browser/login_handler.h" + +namespace electron { + +namespace { + +class LoginHandlerDelegate { + public: + LoginHandlerDelegate( + mojo::PendingRemote<network::mojom::AuthChallengeResponder> + auth_challenge_responder, + const net::AuthChallengeInfo& auth_info, + const GURL& url, + scoped_refptr<net::HttpResponseHeaders> response_headers, + base::ProcessId process_id, + bool first_auth_attempt) + : auth_challenge_responder_(std::move(auth_challenge_responder)) { + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + auth_challenge_responder_.set_disconnect_handler(base::BindOnce( + &LoginHandlerDelegate::OnRequestCancelled, base::Unretained(this))); + + login_handler_ = std::make_unique<LoginHandler>( + auth_info, nullptr, false, process_id, url, response_headers, + first_auth_attempt, + base::BindOnce(&LoginHandlerDelegate::OnAuthCredentials, + weak_factory_.GetWeakPtr())); + } + + private: + void OnRequestCancelled() { + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + delete this; + } + + void OnAuthCredentials( + const std::optional<net::AuthCredentials>& auth_credentials) { + DCHECK_CURRENTLY_ON(content::BrowserThread::UI); + auth_challenge_responder_->OnAuthCredentials(auth_credentials); + delete this; + } + + mojo::Remote<network::mojom::AuthChallengeResponder> + auth_challenge_responder_; + std::unique_ptr<LoginHandler> login_handler_; + base::WeakPtrFactory<LoginHandlerDelegate> weak_factory_{this}; +}; + +} // namespace + +URLLoaderNetworkObserver::URLLoaderNetworkObserver() = default; +URLLoaderNetworkObserver::~URLLoaderNetworkObserver() = default; + +mojo::PendingRemote<network::mojom::URLLoaderNetworkServiceObserver> +URLLoaderNetworkObserver::Bind() { + mojo::PendingRemote<network::mojom::URLLoaderNetworkServiceObserver> + pending_remote; + receivers_.Add(this, pending_remote.InitWithNewPipeAndPassReceiver()); + return pending_remote; +} + +void URLLoaderNetworkObserver::OnAuthRequired( + const std::optional<base::UnguessableToken>& window_id, + int32_t request_id, + const GURL& url, + bool first_auth_attempt, + const net::AuthChallengeInfo& auth_info, + const scoped_refptr<net::HttpResponseHeaders>& head_headers, + mojo::PendingRemote<network::mojom::AuthChallengeResponder> + auth_challenge_responder) { + new LoginHandlerDelegate(std::move(auth_challenge_responder), auth_info, url, + head_headers, process_id_, first_auth_attempt); +} + +void URLLoaderNetworkObserver::OnSSLCertificateError( + const GURL& url, + int net_error, + const net::SSLInfo& ssl_info, + bool fatal, + OnSSLCertificateErrorCallback response) { + std::move(response).Run(net_error); +} + +void URLLoaderNetworkObserver::OnClearSiteData( + const GURL& url, + const std::string& header_value, + int32_t load_flags, + const std::optional<net::CookiePartitionKey>& cookie_partition_key, + bool partitioned_state_allowed_only, + OnClearSiteDataCallback callback) { + std::move(callback).Run(); +} + +void URLLoaderNetworkObserver::OnLoadingStateUpdate( + network::mojom::LoadInfoPtr info, + OnLoadingStateUpdateCallback callback) { + std::move(callback).Run(); +} + +void URLLoaderNetworkObserver::OnSharedStorageHeaderReceived( + const url::Origin& request_origin, + std::vector<network::mojom::SharedStorageOperationPtr> operations, + OnSharedStorageHeaderReceivedCallback callback) { + std::move(callback).Run(); +} + +void URLLoaderNetworkObserver::Clone( + mojo::PendingReceiver<network::mojom::URLLoaderNetworkServiceObserver> + observer) { + receivers_.Add(this, std::move(observer)); +} + +} // namespace electron diff --git a/shell/browser/net/url_loader_network_observer.h b/shell/browser/net/url_loader_network_observer.h new file mode 100644 index 0000000000..93b3b4e352 --- /dev/null +++ b/shell/browser/net/url_loader_network_observer.h @@ -0,0 +1,82 @@ +// Copyright (c) 2024 Microsoft, GmbH +// Use of this source code is governed by the MIT license that can be +// found in the LICENSE file. + +#ifndef ELECTRON_SHELL_BROWSER_NET_URL_LOADER_NETWORK_OBSERVER_H_ +#define ELECTRON_SHELL_BROWSER_NET_URL_LOADER_NETWORK_OBSERVER_H_ + +#include "base/memory/weak_ptr.h" +#include "base/process/process_handle.h" +#include "mojo/public/cpp/bindings/receiver_set.h" +#include "services/network/public/mojom/url_loader_network_service_observer.mojom.h" + +namespace electron { + +class URLLoaderNetworkObserver + : public network::mojom::URLLoaderNetworkServiceObserver { + public: + URLLoaderNetworkObserver(); + ~URLLoaderNetworkObserver() override; + + URLLoaderNetworkObserver(const URLLoaderNetworkObserver&) = delete; + URLLoaderNetworkObserver& operator=(const URLLoaderNetworkObserver&) = delete; + + mojo::PendingRemote<network::mojom::URLLoaderNetworkServiceObserver> Bind(); + void set_process_id(base::ProcessId pid) { process_id_ = pid; } + + private: + void OnAuthRequired( + const std::optional<base::UnguessableToken>& window_id, + int32_t request_id, + const GURL& url, + bool first_auth_attempt, + const net::AuthChallengeInfo& auth_info, + const scoped_refptr<net::HttpResponseHeaders>& head_headers, + mojo::PendingRemote<network::mojom::AuthChallengeResponder> + auth_challenge_responder) override; + void OnSSLCertificateError(const GURL& url, + int net_error, + const net::SSLInfo& ssl_info, + bool fatal, + OnSSLCertificateErrorCallback response) override; + void OnClearSiteData( + const GURL& url, + const std::string& header_value, + int32_t load_flags, + const std::optional<net::CookiePartitionKey>& cookie_partition_key, + bool partitioned_state_allowed_only, + OnClearSiteDataCallback callback) override; + void OnLoadingStateUpdate(network::mojom::LoadInfoPtr info, + OnLoadingStateUpdateCallback callback) override; + void OnSharedStorageHeaderReceived( + const url::Origin& request_origin, + std::vector<network::mojom::SharedStorageOperationPtr> operations, + OnSharedStorageHeaderReceivedCallback callback) override; + void OnDataUseUpdate(int32_t network_traffic_annotation_id_hash, + int64_t recv_bytes, + int64_t sent_bytes) override {} + void OnWebSocketConnectedToPrivateNetwork( + network::mojom::IPAddressSpace ip_address_space) override {} + void OnCertificateRequested( + const std::optional<base::UnguessableToken>& window_id, + const scoped_refptr<net::SSLCertRequestInfo>& cert_info, + mojo::PendingRemote<network::mojom::ClientCertificateResponder> + client_cert_responder) override {} + void OnPrivateNetworkAccessPermissionRequired( + const GURL& url, + const net::IPAddress& ip_address, + const std::optional<std::string>& private_network_device_id, + const std::optional<std::string>& private_network_device_name, + OnPrivateNetworkAccessPermissionRequiredCallback callback) override {} + void Clone( + mojo::PendingReceiver<network::mojom::URLLoaderNetworkServiceObserver> + observer) override; + + mojo::ReceiverSet<network::mojom::URLLoaderNetworkServiceObserver> receivers_; + base::ProcessId process_id_ = base::kNullProcessId; + base::WeakPtrFactory<URLLoaderNetworkObserver> weak_factory_{this}; +}; + +} // namespace electron + +#endif // ELECTRON_SHELL_BROWSER_NET_URL_LOADER_NETWORK_OBSERVER_H_ diff --git a/shell/common/api/electron_api_url_loader.cc b/shell/common/api/electron_api_url_loader.cc index 32ce009342..212d133d6e 100644 --- a/shell/common/api/electron_api_url_loader.cc +++ b/shell/common/api/electron_api_url_loader.cc @@ -335,13 +335,21 @@ SimpleURLLoaderWrapper::SimpleURLLoaderWrapper( DETACH_FROM_SEQUENCE(sequence_checker_); if (!request_->trusted_params) request_->trusted_params = network::ResourceRequest::TrustedParams(); - mojo::PendingRemote<network::mojom::URLLoaderNetworkServiceObserver> - url_loader_network_observer_remote; - url_loader_network_observer_receivers_.Add( - this, - url_loader_network_observer_remote.InitWithNewPipeAndPassReceiver()); - request_->trusted_params->url_loader_network_observer = - std::move(url_loader_network_observer_remote); + bool create_network_observer = true; + if (electron::IsUtilityProcess()) { + create_network_observer = + !URLLoaderBundle::GetInstance() + ->ShouldUseNetworkObserverfromURLLoaderFactory(); + } + if (create_network_observer) { + mojo::PendingRemote<network::mojom::URLLoaderNetworkServiceObserver> + url_loader_network_observer_remote; + url_loader_network_observer_receivers_.Add( + this, + url_loader_network_observer_remote.InitWithNewPipeAndPassReceiver()); + request_->trusted_params->url_loader_network_observer = + std::move(url_loader_network_observer_remote); + } // 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. diff --git a/shell/services/node/node_service.cc b/shell/services/node/node_service.cc index 771ce35508..6d273119d0 100644 --- a/shell/services/node/node_service.cc +++ b/shell/services/node/node_service.cc @@ -33,11 +33,14 @@ URLLoaderBundle* URLLoaderBundle::GetInstance() { void URLLoaderBundle::SetURLLoaderFactory( mojo::PendingRemote<network::mojom::URLLoaderFactory> pending_factory, - mojo::Remote<network::mojom::HostResolver> host_resolver) { + mojo::Remote<network::mojom::HostResolver> host_resolver, + bool use_network_observer_from_url_loader_factory) { factory_ = network::SharedURLLoaderFactory::Create( std::make_unique<network::WrapperPendingSharedURLLoaderFactory>( std::move(pending_factory))); host_resolver_ = std::move(host_resolver); + should_use_network_observer_from_url_loader_factory_ = + use_network_observer_from_url_loader_factory; } scoped_refptr<network::SharedURLLoaderFactory> @@ -50,6 +53,10 @@ network::mojom::HostResolver* URLLoaderBundle::GetHostResolver() { return host_resolver_.get(); } +bool URLLoaderBundle::ShouldUseNetworkObserverfromURLLoaderFactory() const { + return should_use_network_observer_from_url_loader_factory_; +} + NodeService::NodeService( mojo::PendingReceiver<node::mojom::NodeService> receiver) : node_bindings_{NodeBindings::Create( @@ -76,7 +83,8 @@ void NodeService::Initialize(node::mojom::NodeServiceParamsPtr params) { URLLoaderBundle::GetInstance()->SetURLLoaderFactory( std::move(params->url_loader_factory), - mojo::Remote(std::move(params->host_resolver))); + mojo::Remote(std::move(params->host_resolver)), + params->use_network_observer_from_url_loader_factory); js_env_ = std::make_unique<JavascriptEnvironment>(node_bindings_->uv_loop()); diff --git a/shell/services/node/node_service.h b/shell/services/node/node_service.h index a7b87da804..b025ad233a 100644 --- a/shell/services/node/node_service.h +++ b/shell/services/node/node_service.h @@ -39,13 +39,16 @@ class URLLoaderBundle { static URLLoaderBundle* GetInstance(); void SetURLLoaderFactory( mojo::PendingRemote<network::mojom::URLLoaderFactory> factory, - mojo::Remote<network::mojom::HostResolver> host_resolver); + mojo::Remote<network::mojom::HostResolver> host_resolver, + bool use_network_observer_from_url_loader_factory); scoped_refptr<network::SharedURLLoaderFactory> GetSharedURLLoaderFactory(); network::mojom::HostResolver* GetHostResolver(); + bool ShouldUseNetworkObserverfromURLLoaderFactory() const; private: scoped_refptr<network::SharedURLLoaderFactory> factory_; mojo::Remote<network::mojom::HostResolver> host_resolver_; + bool should_use_network_observer_from_url_loader_factory_ = false; }; class NodeService : public node::mojom::NodeService { diff --git a/shell/services/node/public/mojom/node_service.mojom b/shell/services/node/public/mojom/node_service.mojom index 30ebcae92c..be9a0cb0ab 100644 --- a/shell/services/node/public/mojom/node_service.mojom +++ b/shell/services/node/public/mojom/node_service.mojom @@ -17,6 +17,7 @@ struct NodeServiceParams { blink.mojom.MessagePortDescriptor port; pending_remote<network.mojom.URLLoaderFactory> url_loader_factory; pending_remote<network.mojom.HostResolver> host_resolver; + bool use_network_observer_from_url_loader_factory = false; }; [ServiceSandbox=sandbox.mojom.Sandbox.kNoSandbox] diff --git a/spec/api-utility-process-spec.ts b/spec/api-utility-process-spec.ts index 9ee9a3595a..76d0e2d6e3 100644 --- a/spec/api-utility-process-spec.ts +++ b/spec/api-utility-process-spec.ts @@ -2,8 +2,9 @@ import { expect } from 'chai'; import * as childProcess from 'node:child_process'; import * as path from 'node:path'; import { BrowserWindow, MessageChannelMain, utilityProcess, app } from 'electron/main'; -import { ifit } from './lib/spec-helpers'; +import { ifit, startRemoteControlApp } from './lib/spec-helpers'; import { closeWindow } from './lib/window-helpers'; +import { respondOnce, randomString, kOneKiloByte } from './lib/net-helpers'; import { once } from 'node:events'; import { pathToFileURL } from 'node:url'; import { setImmediate } from 'node:timers/promises'; @@ -508,5 +509,193 @@ describe('utilityProcess module', () => { expect(child.kill()).to.be.true(); await exit; }); + + it('should emit the app#login event when 401', async () => { + const { remotely } = await startRemoteControlApp(); + 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'); + }); + const [loginAuthInfo, statusCode] = await remotely(async (serverUrl: string, fixture: string) => { + const { app, utilityProcess } = require('electron'); + const { once } = require('node:events'); + const child = utilityProcess.fork(fixture, [`--server-url=${serverUrl}`], { + stdio: 'ignore', + respondToAuthRequestsFromMainProcess: true + }); + await once(child, 'spawn'); + const [ev,,, authInfo, cb] = await once(app, 'login'); + ev.preventDefault(); + cb('dummy', 'pass'); + const [result] = await once(child, 'message'); + return [authInfo, ...result]; + }, serverUrl, path.join(fixturesPath, 'net.js')); + expect(statusCode).to.equal(200); + expect(loginAuthInfo!.realm).to.equal('Foo'); + expect(loginAuthInfo!.scheme).to.equal('basic'); + }); + + it('should receive 401 response when cancelling authentication via app#login event', async () => { + const { remotely } = await startRemoteControlApp(); + 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 [authDetails, responseBody, statusCode] = await remotely(async (serverUrl: string, fixture: string) => { + const { app, utilityProcess } = require('electron'); + const { once } = require('node:events'); + const child = utilityProcess.fork(fixture, [`--server-url=${serverUrl}`], { + stdio: 'ignore', + respondToAuthRequestsFromMainProcess: true + }); + await once(child, 'spawn'); + const [,, details,, cb] = await once(app, 'login'); + cb(); + const [response] = await once(child, 'message'); + const [responseBody] = await once(child, 'message'); + return [details, responseBody, ...response]; + }, serverUrl, path.join(fixturesPath, 'net.js')); + expect(authDetails.url).to.equal(serverUrl); + expect(statusCode).to.equal(401); + expect(responseBody).to.equal('unauthenticated'); + }); + + it('should upload body when 401', async () => { + const { remotely } = await startRemoteControlApp(); + 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 [authDetails, responseBody, statusCode] = await remotely(async (serverUrl: string, requestData: string, fixture: string) => { + const { app, utilityProcess } = require('electron'); + const { once } = require('node:events'); + const child = utilityProcess.fork(fixture, [`--server-url=${serverUrl}`, '--request-data'], { + stdio: 'ignore', + respondToAuthRequestsFromMainProcess: true + }); + await once(child, 'spawn'); + await once(child, 'message'); + child.postMessage(requestData); + const [,, details,, cb] = await once(app, 'login'); + cb('user', 'pass'); + const [response] = await once(child, 'message'); + const [responseBody] = await once(child, 'message'); + return [details, responseBody, ...response]; + }, serverUrl, requestData, path.join(fixturesPath, 'net.js')); + expect(authDetails.url).to.equal(serverUrl); + expect(statusCode).to.equal(200); + expect(responseBody).to.equal(requestData); + }); + + it('should not emit the app#login event when 401 with {"credentials":"omit"}', async () => { + const rc = await startRemoteControlApp(); + 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'); + }); + const [statusCode, responseHeaders] = await rc.remotely(async (serverUrl: string, fixture: string) => { + const { app, utilityProcess } = require('electron'); + const { once } = require('node:events'); + let gracefulExit = true; + const child = utilityProcess.fork(fixture, [`--server-url=${serverUrl}`, '--omit-credentials'], { + stdio: 'ignore', + respondToAuthRequestsFromMainProcess: true + }); + await once(child, 'spawn'); + app.on('login', () => { + gracefulExit = false; + }); + const [result] = await once(child, 'message'); + setTimeout(() => { + if (gracefulExit) { + app.quit(); + } else { + process.exit(1); + } + }); + return result; + }, serverUrl, path.join(fixturesPath, 'net.js')); + const [code] = await once(rc.process, 'exit'); + expect(code).to.equal(0); + expect(statusCode).to.equal(401); + expect(responseHeaders['www-authenticate']).to.equal('Basic realm="Foo"'); + }); + + it('should not emit the app#login event with default respondToAuthRequestsFromMainProcess', async () => { + const rc = await startRemoteControlApp(); + 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'); + }); + const [loginAuthInfo, statusCode] = await rc.remotely(async (serverUrl: string, fixture: string) => { + const { app, utilityProcess } = require('electron'); + const { once } = require('node:events'); + let gracefulExit = true; + const child = utilityProcess.fork(fixture, [`--server-url=${serverUrl}`, '--use-net-login-event'], { + stdio: 'ignore' + }); + await once(child, 'spawn'); + app.on('login', () => { + gracefulExit = false; + }); + const [authInfo] = await once(child, 'message'); + const [result] = await once(child, 'message'); + setTimeout(() => { + if (gracefulExit) { + app.quit(); + } else { + process.exit(1); + } + }); + return [authInfo, ...result]; + }, serverUrl, path.join(fixturesPath, 'net.js')); + const [code] = await once(rc.process, 'exit'); + expect(code).to.equal(0); + expect(statusCode).to.equal(200); + expect(loginAuthInfo!.realm).to.equal('Foo'); + expect(loginAuthInfo!.scheme).to.equal('basic'); + }); + + it('should emit the app#login event when creating requests with fetch API', async () => { + const { remotely } = await startRemoteControlApp(); + 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'); + }); + const [loginAuthInfo, statusCode] = await remotely(async (serverUrl: string, fixture: string) => { + const { app, utilityProcess } = require('electron'); + const { once } = require('node:events'); + const child = utilityProcess.fork(fixture, [`--server-url=${serverUrl}`, '--use-fetch-api'], { + stdio: 'ignore', + respondToAuthRequestsFromMainProcess: true + }); + await once(child, 'spawn'); + const [ev,,, authInfo, cb] = await once(app, 'login'); + ev.preventDefault(); + cb('dummy', 'pass'); + const [response] = await once(child, 'message'); + return [authInfo, ...response]; + }, serverUrl, path.join(fixturesPath, 'net.js')); + expect(statusCode).to.equal(200); + expect(loginAuthInfo!.realm).to.equal('Foo'); + expect(loginAuthInfo!.scheme).to.equal('basic'); + }); }); }); diff --git a/spec/fixtures/api/utility-process/net.js b/spec/fixtures/api/utility-process/net.js new file mode 100644 index 0000000000..697a3572b9 --- /dev/null +++ b/spec/fixtures/api/utility-process/net.js @@ -0,0 +1,44 @@ +const { net } = require('electron'); +const serverUrl = process.argv[2].split('=')[1]; +let configurableArg = null; +if (process.argv[3]) { + configurableArg = process.argv[3].split('=')[0]; +} +const data = []; + +let request = null; +if (configurableArg === '--omit-credentials') { + request = net.request({ method: 'GET', url: serverUrl, credentials: 'omit' }); +} else if (configurableArg === '--use-fetch-api') { + net.fetch(serverUrl).then((response) => { + process.parentPort.postMessage([response.status, response.headers]); + }); +} else { + request = net.request({ method: 'GET', url: serverUrl }); +} + +if (request) { + if (configurableArg === '--use-net-login-event') { + request.on('login', (authInfo, cb) => { + process.parentPort.postMessage(authInfo); + cb('user', 'pass'); + }); + } + request.on('response', (response) => { + process.parentPort.postMessage([response.statusCode, response.headers]); + response.on('data', (chunk) => data.push(chunk)); + response.on('end', (chunk) => { + if (chunk) data.push(chunk); + process.parentPort.postMessage(Buffer.concat(data).toString()); + }); + }); + if (configurableArg === '--request-data') { + process.parentPort.on('message', (e) => { + request.write(e.data); + request.end(); + }); + process.parentPort.postMessage('get-request-data'); + } else { + request.end(); + } +}
feat
435003566dbfe0aedbe52b39774f32148635ed00
Samuel Attard
2024-05-14 15:52:08
fix: restore non-panel focus behavior (#42180)
diff --git a/shell/browser/native_window_mac.mm b/shell/browser/native_window_mac.mm index e9909c0a53..abb02e9b75 100644 --- a/shell/browser/native_window_mac.mm +++ b/shell/browser/native_window_mac.mm @@ -426,20 +426,7 @@ void NativeWindowMac::Focus(bool focus) { // If we're a panel window, we do not want to activate the app, // which enables Electron-apps to build Spotlight-like experiences. if (!IsPanel()) { - // On macOS < Sonoma, "activateIgnoringOtherApps:NO" would not - // activate apps if focusing a window that is inActive. That - // changed with macOS Sonoma, which also deprecated - // "activateIgnoringOtherApps". - // - // There's a slim chance we should have never called - // activateIgnoringOtherApps, but we tried that many years ago - // and saw weird focus bugs on other macOS versions. So, to make - // this safe, we're gating by versions. - if (@available(macOS 14.0, *)) { - [[NSApplication sharedApplication] activate]; - } else { - [[NSApplication sharedApplication] activateIgnoringOtherApps:NO]; - } + [[NSApplication sharedApplication] activateIgnoringOtherApps:NO]; } [window_ makeKeyAndOrderFront:nil]; } else {
fix
35969939a1fe795d21c9e11ab2bd08b596b9fe64
Charles Kerr
2023-08-23 08:56:16
refactor: node::Environment self-cleanup (#39604) * chore: savepoint * chore: turn raw_ptr tests back off
diff --git a/shell/browser/electron_browser_main_parts.cc b/shell/browser/electron_browser_main_parts.cc index 61c0b3df01..1bfdb82e44 100644 --- a/shell/browser/electron_browser_main_parts.cc +++ b/shell/browser/electron_browser_main_parts.cc @@ -266,26 +266,25 @@ void ElectronBrowserMainParts::PostEarlyInitialization() { node_bindings_->Initialize(js_env_->isolate()->GetCurrentContext()); // Create the global environment. - node::Environment* env = node_bindings_->CreateEnvironment( + node_env_ = node_bindings_->CreateEnvironment( js_env_->isolate()->GetCurrentContext(), js_env_->platform()); - node_env_ = std::make_unique<NodeEnvironment>(env); - env->set_trace_sync_io(env->options()->trace_sync_io); + node_env_->set_trace_sync_io(node_env_->options()->trace_sync_io); // We do not want to crash the main process on unhandled rejections. - env->options()->unhandled_rejections = "warn-with-error-code"; + node_env_->options()->unhandled_rejections = "warn-with-error-code"; // Add Electron extended APIs. - electron_bindings_->BindTo(js_env_->isolate(), env->process_object()); + electron_bindings_->BindTo(js_env_->isolate(), node_env_->process_object()); // Create explicit microtasks runner. js_env_->CreateMicrotasksRunner(); // Wrap the uv loop with global env. - node_bindings_->set_uv_env(env); + node_bindings_->set_uv_env(node_env_.get()); // Load everything. - node_bindings_->LoadEnvironment(env); + node_bindings_->LoadEnvironment(node_env_.get()); // We already initialized the feature list in PreEarlyInitialization(), but // the user JS script would not have had a chance to alter the command-line @@ -627,9 +626,9 @@ void ElectronBrowserMainParts::PostMainMessageLoopRun() { // Destroy node platform after all destructors_ are executed, as they may // invoke Node/V8 APIs inside them. - node_env_->env()->set_trace_sync_io(false); + node_env_->set_trace_sync_io(false); js_env_->DestroyMicrotasksRunner(); - node::Stop(node_env_->env(), node::StopFlags::kDoNotTerminateIsolate); + node::Stop(node_env_.get(), node::StopFlags::kDoNotTerminateIsolate); node_env_.reset(); auto default_context_key = ElectronBrowserContext::PartitionKey("", false); diff --git a/shell/browser/electron_browser_main_parts.h b/shell/browser/electron_browser_main_parts.h index 69f4c32cd9..0e49e8a66d 100644 --- a/shell/browser/electron_browser_main_parts.h +++ b/shell/browser/electron_browser_main_parts.h @@ -37,6 +37,10 @@ class Screen; } #endif +namespace node { +class Environment; +} + namespace ui { class LinuxUiGetter; } @@ -47,7 +51,6 @@ class Browser; class ElectronBindings; class JavascriptEnvironment; class NodeBindings; -class NodeEnvironment; #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) class ElectronExtensionsClient; @@ -166,7 +169,7 @@ class ElectronBrowserMainParts : public content::BrowserMainParts { std::unique_ptr<JavascriptEnvironment> js_env_; // depends-on: js_env_'s isolate - std::unique_ptr<NodeEnvironment> node_env_; + std::shared_ptr<node::Environment> node_env_; // depends-on: js_env_'s isolate std::unique_ptr<Browser> browser_; diff --git a/shell/browser/javascript_environment.cc b/shell/browser/javascript_environment.cc index c176a589c7..98c6e12cac 100644 --- a/shell/browser/javascript_environment.cc +++ b/shell/browser/javascript_environment.cc @@ -340,12 +340,4 @@ void JavascriptEnvironment::DestroyMicrotasksRunner() { base::CurrentThread::Get()->RemoveTaskObserver(microtasks_runner_.get()); } -NodeEnvironment::NodeEnvironment(node::Environment* env) : env_(env) {} - -NodeEnvironment::~NodeEnvironment() { - auto* isolate_data = env_->isolate_data(); - node::FreeEnvironment(env_); - node::FreeIsolateData(isolate_data); -} - } // namespace electron diff --git a/shell/browser/javascript_environment.h b/shell/browser/javascript_environment.h index bb38e35945..937b0f9764 100644 --- a/shell/browser/javascript_environment.h +++ b/shell/browser/javascript_environment.h @@ -54,22 +54,6 @@ class JavascriptEnvironment { std::unique_ptr<MicrotasksRunner> microtasks_runner_; }; -// Manage the Node Environment automatically. -class NodeEnvironment { - public: - explicit NodeEnvironment(node::Environment* env); - ~NodeEnvironment(); - - // disable copy - NodeEnvironment(const NodeEnvironment&) = delete; - NodeEnvironment& operator=(const NodeEnvironment&) = delete; - - node::Environment* env() { return env_; } - - private: - raw_ptr<node::Environment> env_; -}; - } // namespace electron #endif // ELECTRON_SHELL_BROWSER_JAVASCRIPT_ENVIRONMENT_H_ diff --git a/shell/common/node_bindings.cc b/shell/common/node_bindings.cc index 4790b00e53..afa86048f3 100644 --- a/shell/common/node_bindings.cc +++ b/shell/common/node_bindings.cc @@ -477,7 +477,7 @@ void NodeBindings::Initialize(v8::Local<v8::Context> context) { g_is_initialized = true; } -node::Environment* NodeBindings::CreateEnvironment( +std::shared_ptr<node::Environment> NodeBindings::CreateEnvironment( v8::Handle<v8::Context> context, node::MultiIsolatePlatform* platform, std::vector<std::string> args, @@ -644,10 +644,25 @@ node::Environment* NodeBindings::CreateEnvironment( base::PathService::Get(content::CHILD_PROCESS_EXE, &helper_exec_path); process.Set("helperExecPath", helper_exec_path); - return env; + auto env_deleter = [isolate, isolate_data, + context = v8::Global<v8::Context>{isolate, context}]( + node::Environment* nenv) mutable { + // When `isolate_data` was created above, a pointer to it was kept + // in context's embedder_data[kElectronContextEmbedderDataIndex]. + // Since we're about to free `isolate_data`, clear that entry + v8::HandleScope handle_scope{isolate}; + context.Get(isolate)->SetAlignedPointerInEmbedderData( + kElectronContextEmbedderDataIndex, nullptr); + context.Reset(); + + node::FreeEnvironment(nenv); + node::FreeIsolateData(isolate_data); + }; + + return {env, std::move(env_deleter)}; } -node::Environment* NodeBindings::CreateEnvironment( +std::shared_ptr<node::Environment> NodeBindings::CreateEnvironment( v8::Handle<v8::Context> context, node::MultiIsolatePlatform* platform) { #if BUILDFLAG(IS_WIN) diff --git a/shell/common/node_bindings.h b/shell/common/node_bindings.h index 9182f5440b..c6e2a56f38 100644 --- a/shell/common/node_bindings.h +++ b/shell/common/node_bindings.h @@ -5,6 +5,7 @@ #ifndef ELECTRON_SHELL_COMMON_NODE_BINDINGS_H_ #define ELECTRON_SHELL_COMMON_NODE_BINDINGS_H_ +#include <memory> #include <string> #include <type_traits> #include <vector> @@ -25,12 +26,6 @@ class SingleThreadTaskRunner; namespace electron { -// Choose a reasonable unique index that's higher than any Blink uses -// and thus unlikely to collide with an existing index. -static constexpr int kElectronContextEmbedderDataIndex = - static_cast<int>(gin::kPerContextDataStartIndex) + - static_cast<int>(gin::kEmbedderElectron); - // A helper class to manage uv_handle_t types, e.g. uv_async_t. // // As per the uv docs: "uv_close() MUST be called on each handle before @@ -95,12 +90,15 @@ class NodeBindings { std::vector<std::string> ParseNodeCliFlags(); // Create the environment and load node.js. - node::Environment* CreateEnvironment(v8::Handle<v8::Context> context, - node::MultiIsolatePlatform* platform, - std::vector<std::string> args, - std::vector<std::string> exec_args); - node::Environment* CreateEnvironment(v8::Handle<v8::Context> context, - node::MultiIsolatePlatform* platform); + std::shared_ptr<node::Environment> CreateEnvironment( + v8::Handle<v8::Context> context, + node::MultiIsolatePlatform* platform, + std::vector<std::string> args, + std::vector<std::string> exec_args); + + std::shared_ptr<node::Environment> CreateEnvironment( + v8::Handle<v8::Context> context, + node::MultiIsolatePlatform* platform); // Load node.js in the environment. void LoadEnvironment(node::Environment* env); @@ -111,12 +109,6 @@ class NodeBindings { // Notify embed thread to start polling after environment is loaded. void StartPolling(); - // Clears the PerIsolateData. - void clear_isolate_data(v8::Local<v8::Context> context) { - context->SetAlignedPointerInEmbedderData(kElectronContextEmbedderDataIndex, - nullptr); - } - node::IsolateData* isolate_data(v8::Local<v8::Context> context) const { if (context->GetNumberOfEmbedderDataFields() <= kElectronContextEmbedderDataIndex) { @@ -167,6 +159,12 @@ class NodeBindings { raw_ptr<uv_loop_t> uv_loop_; private: + // Choose a reasonable unique index that's higher than any Blink uses + // and thus unlikely to collide with an existing index. + static constexpr int kElectronContextEmbedderDataIndex = + static_cast<int>(gin::kPerContextDataStartIndex) + + static_cast<int>(gin::kEmbedderElectron); + // Thread to poll uv events. static void EmbedThreadRunner(void* arg); diff --git a/shell/renderer/electron_renderer_client.cc b/shell/renderer/electron_renderer_client.cc index 04b9b0e03b..d33527ff84 100644 --- a/shell/renderer/electron_renderer_client.cc +++ b/shell/renderer/electron_renderer_client.cc @@ -88,7 +88,7 @@ void ElectronRendererClient::DidCreateScriptContext( v8::Maybe<bool> initialized = node::InitializeContext(renderer_context); CHECK(!initialized.IsNothing() && initialized.FromJust()); - node::Environment* env = + std::shared_ptr<node::Environment> env = node_bindings_->CreateEnvironment(renderer_context, nullptr); // If we have disabled the site instance overrides we should prevent loading @@ -106,11 +106,11 @@ void ElectronRendererClient::DidCreateScriptContext( BindProcess(env->isolate(), &process_dict, render_frame); // Load everything. - node_bindings_->LoadEnvironment(env); + node_bindings_->LoadEnvironment(env.get()); if (node_bindings_->uv_env() == nullptr) { // Make uv loop being wrapped by window context. - node_bindings_->set_uv_env(env); + node_bindings_->set_uv_env(env.get()); // Give the node loop a run to make sure everything is ready. node_bindings_->StartPolling(); @@ -124,7 +124,9 @@ void ElectronRendererClient::WillReleaseScriptContext( return; node::Environment* env = node::Environment::GetCurrent(context); - if (environments_.erase(env) == 0) + const auto iter = base::ranges::find_if( + environments_, [env](auto& item) { return env == item.get(); }); + if (iter == environments_.end()) return; gin_helper::EmitEvent(env->isolate(), env->process_object(), "exit"); @@ -143,9 +145,7 @@ void ElectronRendererClient::WillReleaseScriptContext( DCHECK_EQ(microtask_queue->GetMicrotasksScopeDepth(), 0); microtask_queue->set_microtasks_policy(v8::MicrotasksPolicy::kExplicit); - node::FreeEnvironment(env); - node::FreeIsolateData(node_bindings_->isolate_data(context)); - node_bindings_->clear_isolate_data(context); + environments_.erase(iter); microtask_queue->set_microtasks_policy(old_policy); @@ -201,7 +201,11 @@ node::Environment* ElectronRendererClient::GetEnvironment( auto context = GetContext(render_frame->GetWebFrame(), v8::Isolate::GetCurrent()); node::Environment* env = node::Environment::GetCurrent(context); - return base::Contains(environments_, env) ? env : nullptr; + + return base::Contains(environments_, env, + [](auto const& item) { return item.get(); }) + ? env + : nullptr; } } // namespace electron diff --git a/shell/renderer/electron_renderer_client.h b/shell/renderer/electron_renderer_client.h index c93d51e759..1e8318c4ca 100644 --- a/shell/renderer/electron_renderer_client.h +++ b/shell/renderer/electron_renderer_client.h @@ -55,7 +55,7 @@ class ElectronRendererClient : public RendererClientBase { // The node::Environment::GetCurrent API does not return nullptr when it // is called for a context without node::Environment, so we have to keep // a book of the environments created. - std::set<node::Environment*> environments_; + std::set<std::shared_ptr<node::Environment>> environments_; // Getting main script context from web frame would lazily initializes // its script context. Doing so in a web page without scripts would trigger diff --git a/shell/renderer/web_worker_observer.cc b/shell/renderer/web_worker_observer.cc index d738a10acf..ff2f9bbda8 100644 --- a/shell/renderer/web_worker_observer.cc +++ b/shell/renderer/web_worker_observer.cc @@ -6,7 +6,9 @@ #include <utility> +#include "base/containers/cxx20_erase_set.h" #include "base/no_destructor.h" +#include "base/ranges/algorithm.h" #include "base/threading/thread_local.h" #include "shell/common/api/electron_bindings.h" #include "shell/common/gin_helper/event_emitter_caller.h" @@ -61,20 +63,23 @@ void WebWorkerObserver::WorkerScriptReadyForEvaluation( // Setup node environment for each window. v8::Maybe<bool> initialized = node::InitializeContext(worker_context); CHECK(!initialized.IsNothing() && initialized.FromJust()); - node::Environment* env = + std::shared_ptr<node::Environment> env = node_bindings_->CreateEnvironment(worker_context, nullptr); // Add Electron extended APIs. electron_bindings_->BindTo(env->isolate(), env->process_object()); // Load everything. - node_bindings_->LoadEnvironment(env); + node_bindings_->LoadEnvironment(env.get()); // Make uv loop being wrapped by window context. - node_bindings_->set_uv_env(env); + node_bindings_->set_uv_env(env.get()); // Give the node loop a run to make sure everything is ready. node_bindings_->StartPolling(); + + // Keep the environment alive until we free it in ContextWillDestroy() + environments_.insert(std::move(env)); } void WebWorkerObserver::ContextWillDestroy(v8::Local<v8::Context> context) { @@ -91,9 +96,8 @@ void WebWorkerObserver::ContextWillDestroy(v8::Local<v8::Context> context) { DCHECK_EQ(microtask_queue->GetMicrotasksScopeDepth(), 0); microtask_queue->set_microtasks_policy(v8::MicrotasksPolicy::kExplicit); - node::FreeEnvironment(env); - node::FreeIsolateData(node_bindings_->isolate_data(context)); - node_bindings_->clear_isolate_data(context); + base::EraseIf(environments_, + [env](auto const& item) { return item.get() == env; }); microtask_queue->set_microtasks_policy(old_policy); diff --git a/shell/renderer/web_worker_observer.h b/shell/renderer/web_worker_observer.h index bba7ae7e61..897052a3c6 100644 --- a/shell/renderer/web_worker_observer.h +++ b/shell/renderer/web_worker_observer.h @@ -6,9 +6,16 @@ #define ELECTRON_SHELL_RENDERER_WEB_WORKER_OBSERVER_H_ #include <memory> +#include <set> #include "v8/include/v8.h" +namespace node { + +class Environment; + +} // namespace node + namespace electron { class ElectronBindings; @@ -35,6 +42,7 @@ class WebWorkerObserver { private: std::unique_ptr<NodeBindings> node_bindings_; std::unique_ptr<ElectronBindings> electron_bindings_; + std::set<std::shared_ptr<node::Environment>> environments_; }; } // namespace electron diff --git a/shell/services/node/node_service.cc b/shell/services/node/node_service.cc index 8aa7a4a618..ba86b8d27a 100644 --- a/shell/services/node/node_service.cc +++ b/shell/services/node/node_service.cc @@ -30,9 +30,9 @@ NodeService::NodeService( NodeService::~NodeService() { if (!node_env_stopped_) { - node_env_->env()->set_trace_sync_io(false); + node_env_->set_trace_sync_io(false); js_env_->DestroyMicrotasksRunner(); - node::Stop(node_env_->env(), node::StopFlags::kDoNotTerminateIsolate); + node::Stop(node_env_.get(), node::StopFlags::kDoNotTerminateIsolate); } } @@ -57,13 +57,12 @@ void NodeService::Initialize(node::mojom::NodeServiceParamsPtr params) { #endif // Create the global environment. - node::Environment* env = node_bindings_->CreateEnvironment( + node_env_ = node_bindings_->CreateEnvironment( js_env_->isolate()->GetCurrentContext(), js_env_->platform(), params->args, params->exec_args); - node_env_ = std::make_unique<NodeEnvironment>(env); node::SetProcessExitHandler( - env, [this](node::Environment* env, int exit_code) { + node_env_.get(), [this](node::Environment* env, int exit_code) { // Destroy node platform. env->set_trace_sync_io(false); js_env_->DestroyMicrotasksRunner(); @@ -72,20 +71,21 @@ void NodeService::Initialize(node::mojom::NodeServiceParamsPtr params) { receiver_.ResetWithReason(exit_code, ""); }); - env->set_trace_sync_io(env->options()->trace_sync_io); + node_env_->set_trace_sync_io(node_env_->options()->trace_sync_io); // Add Electron extended APIs. - electron_bindings_->BindTo(env->isolate(), env->process_object()); + electron_bindings_->BindTo(node_env_->isolate(), node_env_->process_object()); // Add entry script to process object. - gin_helper::Dictionary process(env->isolate(), env->process_object()); + gin_helper::Dictionary process(node_env_->isolate(), + node_env_->process_object()); process.SetHidden("_serviceStartupScript", params->script); // Setup microtask runner. js_env_->CreateMicrotasksRunner(); // Wrap the uv loop with global env. - node_bindings_->set_uv_env(env); + node_bindings_->set_uv_env(node_env_.get()); // LoadEnvironment should be called after setting up // JavaScriptEnvironment including the microtask runner @@ -94,7 +94,7 @@ void NodeService::Initialize(node::mojom::NodeServiceParamsPtr params) { // the exit handler set above will be triggered and it expects // both Node Env and JavaScriptEnviroment are setup to perform // a clean shutdown of this process. - node_bindings_->LoadEnvironment(env); + node_bindings_->LoadEnvironment(node_env_.get()); // Run entry script. node_bindings_->PrepareEmbedThread(); diff --git a/shell/services/node/node_service.h b/shell/services/node/node_service.h index 9683977595..ba5e95caf6 100644 --- a/shell/services/node/node_service.h +++ b/shell/services/node/node_service.h @@ -11,12 +11,17 @@ #include "mojo/public/cpp/bindings/receiver.h" #include "shell/services/node/public/mojom/node_service.mojom.h" +namespace node { + +class Environment; + +} // namespace node + namespace electron { class ElectronBindings; class JavascriptEnvironment; class NodeBindings; -class NodeEnvironment; class NodeService : public node::mojom::NodeService { public: @@ -35,7 +40,7 @@ class NodeService : public node::mojom::NodeService { std::unique_ptr<JavascriptEnvironment> js_env_; std::unique_ptr<NodeBindings> node_bindings_; std::unique_ptr<ElectronBindings> electron_bindings_; - std::unique_ptr<NodeEnvironment> node_env_; + std::shared_ptr<node::Environment> node_env_; mojo::Receiver<node::mojom::NodeService> receiver_{this}; };
refactor
998a0820d991aa494c6156583d7b92555fdd51be
James Cash
2022-09-27 11:40:44
fix: set display_id in desktop capturer on Linux (#33861) Previously, display_id was an empty string, pending Chrome support for sharing individual screens. Now that this has been added, it is desirable to have this property set correctly. Co-authored-by: John Kleinschmidt <[email protected]>
diff --git a/shell/browser/api/electron_api_desktop_capturer.cc b/shell/browser/api/electron_api_desktop_capturer.cc index 60a7b31b23..63fa340e27 100644 --- a/shell/browser/api/electron_api_desktop_capturer.cc +++ b/shell/browser/api/electron_api_desktop_capturer.cc @@ -4,6 +4,7 @@ #include "shell/browser/api/electron_api_desktop_capturer.h" +#include <map> #include <memory> #include <utility> #include <vector> @@ -24,12 +25,125 @@ #include "third_party/webrtc/modules/desktop_capture/desktop_capture_options.h" #include "third_party/webrtc/modules/desktop_capture/desktop_capturer.h" +#if defined(USE_OZONE) +#include "ui/ozone/buildflags.h" +#if BUILDFLAG(OZONE_PLATFORM_X11) +#define USE_OZONE_PLATFORM_X11 +#endif +#endif + #if BUILDFLAG(IS_WIN) #include "third_party/webrtc/modules/desktop_capture/win/dxgi_duplicator_controller.h" #include "third_party/webrtc/modules/desktop_capture/win/screen_capturer_win_directx.h" #include "ui/display/win/display_info.h" +#elif BUILDFLAG(IS_LINUX) +#if defined(USE_OZONE_PLATFORM_X11) +#include "base/logging.h" +#include "ui/base/x/x11_display_util.h" +#include "ui/base/x/x11_util.h" +#include "ui/display/util/edid_parser.h" // nogncheck +#include "ui/gfx/x/randr.h" +#include "ui/gfx/x/x11_atom_cache.h" +#include "ui/gfx/x/xproto_util.h" +#endif // defined(USE_OZONE_PLATFORM_X11) #endif // BUILDFLAG(IS_WIN) +#if BUILDFLAG(IS_LINUX) +// Private function in ui/base/x/x11_display_util.cc +std::map<x11::RandR::Output, int> GetMonitors(int version, + x11::RandR* randr, + x11::Window window) { + std::map<x11::RandR::Output, int> output_to_monitor; + if (version >= 105) { + if (auto reply = randr->GetMonitors({window}).Sync()) { + for (size_t monitor = 0; monitor < reply->monitors.size(); monitor++) { + for (x11::RandR::Output output : reply->monitors[monitor].outputs) + output_to_monitor[output] = monitor; + } + } + } + return output_to_monitor; +} +// Get the EDID data from the |output| and stores to |edid|. +// Private function in ui/base/x/x11_display_util.cc +std::vector<uint8_t> GetEDIDProperty(x11::RandR* randr, + x11::RandR::Output output) { + constexpr const char kRandrEdidProperty[] = "EDID"; + auto future = randr->GetOutputProperty(x11::RandR::GetOutputPropertyRequest{ + .output = output, + .property = x11::GetAtom(kRandrEdidProperty), + .long_length = 128}); + auto response = future.Sync(); + std::vector<uint8_t> edid; + if (response && response->format == 8 && response->type != x11::Atom::None) + edid = std::move(response->data); + return edid; +} + +// Find the mapping from monitor name atom to the display identifier +// that the screen API uses. Based on the logic in BuildDisplaysFromXRandRInfo +// in ui/base/x/x11_display_util.cc +std::map<int32_t, uint32_t> MonitorAtomIdToDisplayId() { + auto* connection = x11::Connection::Get(); + auto& randr = connection->randr(); + auto x_root_window = ui::GetX11RootWindow(); + int version = ui::GetXrandrVersion(); + + std::map<int32_t, uint32_t> monitor_atom_to_display; + + auto resources = randr.GetScreenResourcesCurrent({x_root_window}).Sync(); + if (!resources) { + LOG(ERROR) << "XRandR returned no displays; don't know how to map ids"; + return monitor_atom_to_display; + } + + std::map<x11::RandR::Output, int> output_to_monitor = + GetMonitors(version, &randr, x_root_window); + auto monitors_reply = randr.GetMonitors({x_root_window}).Sync(); + + for (size_t i = 0; i < resources->outputs.size(); i++) { + x11::RandR::Output output_id = resources->outputs[i]; + auto output_info = + randr.GetOutputInfo({output_id, resources->config_timestamp}).Sync(); + if (!output_info) + continue; + + if (output_info->connection != x11::RandR::RandRConnection::Connected) + continue; + + if (output_info->crtc == static_cast<x11::RandR::Crtc>(0)) + continue; + + auto crtc = + randr.GetCrtcInfo({output_info->crtc, resources->config_timestamp}) + .Sync(); + if (!crtc) + continue; + display::EdidParser edid_parser( + GetEDIDProperty(&randr, static_cast<x11::RandR::Output>(output_id))); + auto output_32 = static_cast<uint32_t>(output_id); + int64_t display_id = + output_32 > 0xff ? 0 : edid_parser.GetIndexBasedDisplayId(output_32); + // It isn't ideal, but if we can't parse the EDID data, fall back on the + // display number. + if (!display_id) + display_id = i; + + // Find the mapping between output identifier and the monitor name atom + // Note this isn't the atom string, but the numeric atom identifier, + // since this is what the WebRTC system uses as the display identifier + auto output_monitor_iter = output_to_monitor.find(output_id); + if (output_monitor_iter != output_to_monitor.end()) { + x11::Atom atom = + monitors_reply->monitors[output_monitor_iter->second].name; + monitor_atom_to_display[static_cast<int32_t>(atom)] = display_id; + } + } + + return monitor_atom_to_display; +} +#endif + namespace gin { template <> @@ -178,10 +292,22 @@ void DesktopCapturer::UpdateSourcesList(DesktopMediaList* list) { for (auto& source : screen_sources) { source.display_id = base::NumberToString(source.media_list_source.id.id); } +#elif BUILDFLAG(IS_LINUX) +#if defined(USE_OZONE_PLATFORM_X11) + // On Linux, with X11, the source id is the numeric value of the + // display name atom and the display id is either the EDID or the + // loop index when that display was found (see + // BuildDisplaysFromXRandRInfo in ui/base/x/x11_display_util.cc) + std::map<int32_t, uint32_t> monitor_atom_to_display_id = + MonitorAtomIdToDisplayId(); + for (auto& source : screen_sources) { + auto display_id_iter = + monitor_atom_to_display_id.find(source.media_list_source.id.id); + if (display_id_iter != monitor_atom_to_display_id.end()) + source.display_id = base::NumberToString(display_id_iter->second); + } +#endif // defined(USE_OZONE_PLATFORM_X11) #endif // BUILDFLAG(IS_WIN) - // TODO(ajmacd): Add Linux support. The IDs across APIs differ but Chrome - // only supports capturing the entire desktop on Linux. Revisit this if - // individual screen support is added. std::move(screen_sources.begin(), screen_sources.end(), std::back_inserter(captured_sources_)); }
fix
9ccf2275d2e021c44f51cc3719679e927fee10fa
David Sanders
2023-05-08 03:50:42
chore: migrate to @electron/lint-roller for Markdown linting (#38191)
diff --git a/.markdownlint.json b/.markdownlint.json index cda0fe5700..5336389f14 100644 --- a/.markdownlint.json +++ b/.markdownlint.json @@ -1,27 +1,3 @@ { - "commands-show-output": false, - "first-line-h1": false, - "header-increment": false, - "line-length": { - "code_blocks": false, - "tables": false, - "stern": true, - "line_length": -1 - }, - "no-bare-urls": false, - "no-blanks-blockquote": false, - "no-duplicate-header": { - "allow_different_nesting": true - }, - "no-emphasis-as-header": false, - "no-hard-tabs": { - "code_blocks": false - }, - "no-space-in-emphasis": false, - "no-trailing-punctuation": false, - "no-trailing-spaces": { - "br_spaces": 0 - }, - "single-h1": false, - "no-inline-html": false + "extends": "@electron/lint-roller/configs/markdownlint.json" } diff --git a/package.json b/package.json index 3566581fbd..8ce7c9ce55 100644 --- a/package.json +++ b/package.json @@ -5,11 +5,11 @@ "description": "Build cross platform desktop apps with JavaScript, HTML, and CSS", "devDependencies": { "@azure/storage-blob": "^12.9.0", - "@dsanders11/vscode-markdown-languageservice": "^0.3.0-alpha.4", "@electron/asar": "^3.2.1", "@electron/docs-parser": "^1.1.0", "@electron/fiddle-core": "^1.0.4", "@electron/github-app-auth": "^1.5.0", + "@electron/lint-roller": "^1.1.0", "@electron/typescript-definitions": "^8.14.0", "@octokit/rest": "^19.0.7", "@primer/octicons": "^10.0.0", @@ -55,8 +55,6 @@ "klaw": "^3.0.0", "lint": "^1.1.2", "lint-staged": "^10.2.11", - "markdownlint-cli": "^0.33.0", - "mdast-util-from-markdown": "^1.2.0", "minimist": "^1.2.6", "null-loader": "^4.0.0", "pre-flight": "^1.1.0", @@ -73,11 +71,7 @@ "ts-loader": "^8.0.2", "ts-node": "6.2.0", "typescript": "^4.5.5", - "unist-util-visit": "^4.1.1", "url": "^0.11.0", - "vscode-languageserver": "^8.0.2", - "vscode-languageserver-textdocument": "^1.0.7", - "vscode-uri": "^3.0.6", "webpack": "^5.76.0", "webpack-cli": "^4.10.0", "wrapper-webpack-plugin": "^2.2.0" @@ -96,8 +90,8 @@ "lint:gn": "node ./script/lint.js --gn", "lint:docs": "remark docs -qf && npm run lint:js-in-markdown && npm run create-typescript-definitions && npm run lint:docs-fiddles && npm run lint:docs-relative-links && npm run lint:markdownlint", "lint:docs-fiddles": "standard \"docs/fiddles/**/*.js\"", - "lint:docs-relative-links": "ts-node script/lint-docs-links.ts", - "lint:markdownlint": "markdownlint -r ./script/markdownlint-emd001.js \"*.md\" \"docs/**/*.md\"", + "lint:docs-relative-links": "electron-lint-markdown-links --root docs \"**/*.md\"", + "lint:markdownlint": "electron-markdownlint \"*.md\" \"docs/**/*.md\"", "lint:js-in-markdown": "standard-markdown docs", "create-api-json": "node script/create-api-json.js", "create-typescript-definitions": "npm run create-api-json && electron-typescript-definitions --api=electron-api.json && node spec/ts-smoke/runner.js", @@ -143,7 +137,7 @@ ], "docs/api/**/*.md": [ "ts-node script/gen-filenames.ts", - "markdownlint --config .markdownlint.autofix.json --fix", + "electron-markdownlint --config .markdownlint.autofix.json --fix", "git add filenames.auto.gni" ], "{*.patch,.patches}": [ diff --git a/script/lib/markdown.ts b/script/lib/markdown.ts deleted file mode 100644 index 4cd1a769b5..0000000000 --- a/script/lib/markdown.ts +++ /dev/null @@ -1,334 +0,0 @@ -import * as fs from 'fs'; -import * as path from 'path'; - -import * as MarkdownIt from 'markdown-it'; -import { - githubSlugifier, - resolveInternalDocumentLink, - ExternalHref, - FileStat, - HrefKind, - InternalHref, - IMdLinkComputer, - IMdParser, - ITextDocument, - IWorkspace, - MdLink, - MdLinkKind -} from '@dsanders11/vscode-markdown-languageservice'; -import { Emitter, Range } from 'vscode-languageserver'; -import { TextDocument } from 'vscode-languageserver-textdocument'; -import { URI } from 'vscode-uri'; - -import { findMatchingFiles } from './utils'; - -import type { Definition, ImageReference, Link, LinkReference } from 'mdast'; -import type { fromMarkdown as FromMarkdownFunction } from 'mdast-util-from-markdown'; -import type { Node, Position } from 'unist'; -import type { visit as VisitFunction } from 'unist-util-visit'; - -// Helper function to work around import issues with ESM modules and ts-node -// eslint-disable-next-line no-new-func -const dynamicImport = new Function('specifier', 'return import(specifier)'); - -// Helper function from `vscode-markdown-languageservice` codebase -function tryDecodeUri (str: string): string { - try { - return decodeURI(str); - } catch { - return str; - } -} - -// Helper function from `vscode-markdown-languageservice` codebase -function createHref ( - sourceDocUri: URI, - link: string, - workspace: IWorkspace -): ExternalHref | InternalHref | undefined { - if (/^[a-z-][a-z-]+:/i.test(link)) { - // Looks like a uri - return { kind: HrefKind.External, uri: URI.parse(tryDecodeUri(link)) }; - } - - const resolved = resolveInternalDocumentLink(sourceDocUri, link, workspace); - if (!resolved) { - return undefined; - } - - return { - kind: HrefKind.Internal, - path: resolved.resource, - fragment: resolved.linkFragment - }; -} - -function positionToRange (position: Position): Range { - return { - start: { - character: position.start.column - 1, - line: position.start.line - 1 - }, - end: { character: position.end.column - 1, line: position.end.line - 1 } - }; -} - -const mdIt = MarkdownIt({ html: true }); - -export class MarkdownParser implements IMdParser { - slugifier = githubSlugifier; - - async tokenize (document: TextDocument) { - return mdIt.parse(document.getText(), {}); - } -} - -export class DocsWorkspace implements IWorkspace { - private readonly documentCache: Map<string, TextDocument>; - readonly root: string; - - constructor (root: string) { - this.documentCache = new Map(); - this.root = root; - } - - get workspaceFolders () { - return [URI.file(this.root)]; - } - - async getAllMarkdownDocuments (): Promise<Iterable<ITextDocument>> { - const files = await findMatchingFiles(this.root, (file) => - file.endsWith('.md') - ); - - for (const file of files) { - const document = TextDocument.create( - URI.file(file).toString(), - 'markdown', - 1, - fs.readFileSync(file, 'utf8') - ); - - this.documentCache.set(file, document); - } - - return this.documentCache.values(); - } - - hasMarkdownDocument (resource: URI) { - const relativePath = path.relative(this.root, resource.path); - return ( - !relativePath.startsWith('..') && - !path.isAbsolute(relativePath) && - fs.existsSync(resource.path) - ); - } - - async openMarkdownDocument (resource: URI) { - if (!this.documentCache.has(resource.path)) { - const document = TextDocument.create( - resource.toString(), - 'markdown', - 1, - fs.readFileSync(resource.path, 'utf8') - ); - - this.documentCache.set(resource.path, document); - } - - return this.documentCache.get(resource.path); - } - - async stat (resource: URI): Promise<FileStat | undefined> { - if (this.hasMarkdownDocument(resource)) { - const stats = fs.statSync(resource.path); - return { isDirectory: stats.isDirectory() }; - } - - return undefined; - } - - async readDirectory (): Promise<Iterable<readonly [string, FileStat]>> { - throw new Error('Not implemented'); - } - - // - // These events are defined to fulfill the interface, but are never emitted - // by this implementation since it's not meant for watching a workspace - // - - #onDidChangeMarkdownDocument = new Emitter<ITextDocument>(); - onDidChangeMarkdownDocument = this.#onDidChangeMarkdownDocument.event; - - #onDidCreateMarkdownDocument = new Emitter<ITextDocument>(); - onDidCreateMarkdownDocument = this.#onDidCreateMarkdownDocument.event; - - #onDidDeleteMarkdownDocument = new Emitter<URI>(); - onDidDeleteMarkdownDocument = this.#onDidDeleteMarkdownDocument.event; -} - -export class MarkdownLinkComputer implements IMdLinkComputer { - private readonly workspace: IWorkspace; - - constructor (workspace: IWorkspace) { - this.workspace = workspace; - } - - async getAllLinks (document: ITextDocument): Promise<MdLink[]> { - const { fromMarkdown } = (await dynamicImport( - 'mdast-util-from-markdown' - )) as { fromMarkdown: typeof FromMarkdownFunction }; - - const tree = fromMarkdown(document.getText()); - - const links = [ - ...(await this.#getInlineLinks(document, tree)), - ...(await this.#getReferenceLinks(document, tree)), - ...(await this.#getLinkDefinitions(document, tree)) - ]; - - return links; - } - - async #getInlineLinks ( - document: ITextDocument, - tree: Node - ): Promise<MdLink[]> { - const { visit } = (await dynamicImport('unist-util-visit')) as { - visit: typeof VisitFunction; - }; - - const documentUri = URI.parse(document.uri); - const links: MdLink[] = []; - - visit( - tree, - (node) => node.type === 'link', - (node: Node) => { - const link = node as Link; - const href = createHref(documentUri, link.url, this.workspace); - - if (href) { - const range = positionToRange(link.position!); - - // NOTE - These haven't been implemented properly, but their - // values aren't used for the link linting use-case - const targetRange = range; - const hrefRange = range; - const fragmentRange = undefined; - - links.push({ - kind: MdLinkKind.Link, - href, - source: { - hrefText: link.url, - resource: documentUri, - range, - targetRange, - hrefRange, - fragmentRange, - pathText: link.url.split('#')[0] - } - }); - } - } - ); - - return links; - } - - async #getReferenceLinks ( - document: ITextDocument, - tree: Node - ): Promise<MdLink[]> { - const { visit } = (await dynamicImport('unist-util-visit')) as { - visit: typeof VisitFunction; - }; - - const links: MdLink[] = []; - - visit( - tree, - (node) => ['imageReference', 'linkReference'].includes(node.type), - (node: Node) => { - const link = node as ImageReference | LinkReference; - const range = positionToRange(link.position!); - - // NOTE - These haven't been implemented properly, but their - // values aren't used for the link linting use-case - const targetRange = range; - const hrefRange = range; - - links.push({ - kind: MdLinkKind.Link, - href: { - kind: HrefKind.Reference, - ref: link.label! - }, - source: { - hrefText: link.label!, - resource: URI.parse(document.uri), - range, - targetRange, - hrefRange, - fragmentRange: undefined, - pathText: link.label! - } - }); - } - ); - - return links; - } - - async #getLinkDefinitions ( - document: ITextDocument, - tree: Node - ): Promise<MdLink[]> { - const { visit } = (await dynamicImport('unist-util-visit')) as { - visit: typeof VisitFunction; - }; - - const documentUri = URI.parse(document.uri); - const links: MdLink[] = []; - - visit( - tree, - (node) => node.type === 'definition', - (node: Node) => { - const definition = node as Definition; - const href = createHref(documentUri, definition.url, this.workspace); - - if (href) { - const range = positionToRange(definition.position!); - - // NOTE - These haven't been implemented properly, but their - // values aren't used for the link linting use-case - const targetRange = range; - const hrefRange = range; - const fragmentRange = undefined; - - links.push({ - kind: MdLinkKind.Definition, - href, - ref: { - range, - text: definition.label! - }, - source: { - hrefText: definition.url, - resource: documentUri, - range, - targetRange, - hrefRange, - fragmentRange, - pathText: definition.url.split('#')[0] - } - }); - } - } - ); - - return links; - } -} diff --git a/script/lint-docs-links.ts b/script/lint-docs-links.ts deleted file mode 100755 index 97d738ca94..0000000000 --- a/script/lint-docs-links.ts +++ /dev/null @@ -1,177 +0,0 @@ -#!/usr/bin/env ts-node - -import * as path from 'path'; - -import { - createLanguageService, - DiagnosticLevel, - DiagnosticOptions, - ILogger -} from '@dsanders11/vscode-markdown-languageservice'; -import * as minimist from 'minimist'; -import fetch from 'node-fetch'; -import { CancellationTokenSource } from 'vscode-languageserver'; -import { URI } from 'vscode-uri'; - -import { - DocsWorkspace, - MarkdownLinkComputer, - MarkdownParser -} from './lib/markdown'; - -class NoOpLogger implements ILogger { - log (): void {} -} - -const diagnosticOptions: DiagnosticOptions = { - ignoreLinks: [], - validateDuplicateLinkDefinitions: DiagnosticLevel.error, - validateFileLinks: DiagnosticLevel.error, - validateFragmentLinks: DiagnosticLevel.error, - validateMarkdownFileLinkFragments: DiagnosticLevel.error, - validateReferences: DiagnosticLevel.error, - validateUnusedLinkDefinitions: DiagnosticLevel.error -}; - -async function fetchExternalLink (link: string, checkRedirects = false) { - try { - const response = await fetch(link); - if (response.status !== 200) { - console.log('Broken link', link, response.status, response.statusText); - } else { - if (checkRedirects && response.redirected) { - const wwwUrl = new URL(link); - wwwUrl.hostname = `www.${wwwUrl.hostname}`; - - // For now cut down on noise to find meaningful redirects - const wwwRedirect = wwwUrl.toString() === response.url; - const trailingSlashRedirect = `${link}/` === response.url; - - if (!wwwRedirect && !trailingSlashRedirect) { - console.log('Link redirection', link, '->', response.url); - } - } - - return true; - } - } catch { - console.log('Broken link', link); - } - - return false; -} - -async function main ({ fetchExternalLinks = false, checkRedirects = false }) { - const workspace = new DocsWorkspace(path.resolve(__dirname, '..', 'docs')); - const parser = new MarkdownParser(); - const linkComputer = new MarkdownLinkComputer(workspace); - const languageService = createLanguageService({ - workspace, - parser, - logger: new NoOpLogger(), - linkComputer - }); - - const cts = new CancellationTokenSource(); - let errors = false; - - const externalLinks = new Set<string>(); - - try { - // Collect diagnostics for all documents in the workspace - for (const document of await workspace.getAllMarkdownDocuments()) { - for (let link of await languageService.getDocumentLinks( - document, - cts.token - )) { - if (link.target === undefined) { - link = - (await languageService.resolveDocumentLink(link, cts.token)) ?? - link; - } - - if ( - link.target && - link.target.startsWith('http') && - new URL(link.target).hostname !== 'localhost' - ) { - externalLinks.add(link.target); - } - } - const diagnostics = await languageService.computeDiagnostics( - document, - diagnosticOptions, - cts.token - ); - - if (diagnostics.length) { - console.log( - 'File Location:', - path.relative(workspace.root, URI.parse(document.uri).path) - ); - } - - for (const diagnostic of diagnostics) { - console.log( - `\tBroken link on line ${diagnostic.range.start.line + 1}:`, - diagnostic.message - ); - errors = true; - } - } - } finally { - cts.dispose(); - } - - if (fetchExternalLinks) { - const externalLinkStates = await Promise.all( - Array.from(externalLinks).map((link) => - fetchExternalLink(link, checkRedirects) - ) - ); - - errors = errors || !externalLinkStates.every((x) => x); - } - - return errors; -} - -function parseCommandLine () { - const showUsage = (arg?: string): boolean => { - if (!arg || arg.startsWith('-')) { - console.log( - 'Usage: script/lint-docs-links.ts [-h|--help] [--fetch-external-links] ' + - '[--check-redirects]' - ); - process.exit(0); - } - - return true; - }; - - const opts = minimist(process.argv.slice(2), { - boolean: ['help', 'fetch-external-links', 'check-redirects'], - stopEarly: true, - unknown: showUsage - }); - - if (opts.help) showUsage(); - - return opts; -} - -if (process.mainModule === module) { - const opts = parseCommandLine(); - - main({ - fetchExternalLinks: opts['fetch-external-links'], - checkRedirects: opts['check-redirects'] - }) - .then((errors) => { - if (errors) process.exit(1); - }) - .catch((error) => { - console.error(error); - process.exit(1); - }); -} diff --git a/script/markdownlint-emd001.js b/script/markdownlint-emd001.js deleted file mode 100644 index a415ba503d..0000000000 --- a/script/markdownlint-emd001.js +++ /dev/null @@ -1,21 +0,0 @@ -const { addError, getLineMetadata, getReferenceLinkImageData } = require('markdownlint/helpers'); - -module.exports = { - names: ['EMD001', 'no-shortcut-reference-links'], - description: - 'Disallow shortcut reference links (those with no link label)', - tags: ['images', 'links'], - function: function EMD001 (params, onError) { - const lineMetadata = getLineMetadata(params); - const { shortcuts } = getReferenceLinkImageData(lineMetadata); - for (const [shortcut, occurrences] of shortcuts) { - for (const [lineNumber] of occurrences) { - addError( - onError, - lineNumber + 1, // human-friendly line numbers (1-based) - `Disallowed shortcut reference link: "${shortcut}"` - ); - } - } - } -}; diff --git a/yarn.lock b/yarn.lock index d7ddd31173..da5c5905ff 100644 --- a/yarn.lock +++ b/yarn.lock @@ -118,10 +118,10 @@ resolved "https://registry.yarnpkg.com/@discoveryjs/json-ext/-/json-ext-0.5.7.tgz#1d572bfbbe14b7704e0ba0f39b74815b84870d70" integrity sha512-dBVuXR082gk3jsFp7Rd/JI4kytwGHecnCoTtXFb7DB6CNHp4rg5k1bhg0nWdLGLnOV71lmDzGQaLMy8iPLY0pw== -"@dsanders11/vscode-markdown-languageservice@^0.3.0-alpha.4": - version "0.3.0-alpha.4" - resolved "https://registry.yarnpkg.com/@dsanders11/vscode-markdown-languageservice/-/vscode-markdown-languageservice-0.3.0-alpha.4.tgz#cd80b82142a2c10e09b5f36a93c3ea65b7d2a7f9" - integrity sha512-MHp/CniEkzJb1CAw/bHwucuImaICrcIuohEFamTW8sJC2jhKCnbYblwJFZ3OOS3wTYZbzFIa8WZ4Dn5yL2E7jg== +"@dsanders11/vscode-markdown-languageservice@^0.3.0": + version "0.3.0" + resolved "https://registry.yarnpkg.com/@dsanders11/vscode-markdown-languageservice/-/vscode-markdown-languageservice-0.3.0.tgz#18a561711609651371961b66db4cb8473ab25564" + integrity sha512-aFNWtK23dNicyLczBwIKkGUSVuMoZMzUovlwqj/hVZ3zRIBlXWYunByDxI67Pf1maA0TbxPjVfRqBQFALWjVHg== dependencies: "@vscode/l10n" "^0.0.10" picomatch "^2.3.1" @@ -194,6 +194,23 @@ "@octokit/auth-app" "^3.6.1" "@octokit/rest" "^18.12.0" +"@electron/lint-roller@^1.1.0": + version "1.1.0" + resolved "https://registry.yarnpkg.com/@electron/lint-roller/-/lint-roller-1.1.0.tgz#2b2ce1c9275fb052109b53990f3136f56c1df7be" + integrity sha512-5fDjEi7lXLgF8vAAIhMz7empABSSGQ61saZpQMA/qrigKd1CCkz7Kq/FCtQ8P94FhthlEw/bNE+AUBsHgyrUIQ== + dependencies: + "@dsanders11/vscode-markdown-languageservice" "^0.3.0" + glob "^8.1.0" + markdown-it "^13.0.1" + markdownlint-cli "^0.33.0" + mdast-util-from-markdown "^1.3.0" + minimist "^1.2.8" + node-fetch "^2.6.9" + unist-util-visit "^4.1.2" + vscode-languageserver "^8.1.0" + vscode-languageserver-textdocument "^1.0.8" + vscode-uri "^3.0.7" + "@electron/typescript-definitions@^8.14.0": version "8.14.0" resolved "https://registry.yarnpkg.com/@electron/typescript-definitions/-/typescript-definitions-8.14.0.tgz#a88f74e915317ba943b57ffe499b319d04f01ee3" @@ -3128,6 +3145,17 @@ glob@^7.0.0, glob@^7.0.5, glob@^7.1.3, glob@^7.1.6: once "^1.3.0" path-is-absolute "^1.0.0" +glob@^8.1.0: + version "8.1.0" + resolved "https://registry.yarnpkg.com/glob/-/glob-8.1.0.tgz#d388f656593ef708ee3e34640fdfb99a9fd1c33e" + integrity sha512-r8hpEjiQEYlF2QU0df3dS+nxxSIreXQS1qRhMJM0Q5NDdR386C7jb7Hwwod8Fgiuex+k0GFjgft18yvxm5XoCQ== + dependencies: + fs.realpath "^1.0.0" + inflight "^1.0.4" + inherits "2" + minimatch "^5.0.1" + once "^1.3.0" + glob@~8.0.3: version "8.0.3" resolved "https://registry.yarnpkg.com/glob/-/glob-8.0.3.tgz#415c6eb2deed9e502c68fa44a272e6da6eeca42e" @@ -3992,7 +4020,7 @@ make-error@^1.1.1: resolved "https://registry.yarnpkg.com/make-error/-/make-error-1.3.5.tgz#efe4e81f6db28cadd605c70f29c831b58ef776c8" integrity sha512-c3sIjNUow0+8swNwVpqoH4YCShKNFkMaw6oH1mNS2haDZQqkeZFlHS3dhoeEbKKmJB4vXpJucU6oH75aDYeE9g== [email protected]: [email protected], markdown-it@^13.0.1: version "13.0.1" resolved "https://registry.yarnpkg.com/markdown-it/-/markdown-it-13.0.1.tgz#c6ecc431cacf1a5da531423fc6a42807814af430" integrity sha512-lTlxriVoy2criHP0JKRhO2VDG9c2ypWCsT237eDiLqi09rmbKoUetyGHq2uOIRoRS//kfoJckS0eUzzkDR+k2Q== @@ -4071,10 +4099,10 @@ mdast-util-from-markdown@^1.0.0: parse-entities "^3.0.0" unist-util-stringify-position "^3.0.0" -mdast-util-from-markdown@^1.2.0: - version "1.2.0" - resolved "https://registry.yarnpkg.com/mdast-util-from-markdown/-/mdast-util-from-markdown-1.2.0.tgz#84df2924ccc6c995dec1e2368b2b208ad0a76268" - integrity sha512-iZJyyvKD1+K7QX1b5jXdE7Sc5dtoTry1vzV28UZZe8Z1xVnB/czKntJ7ZAkG0tANqRnBF6p3p7GpU1y19DTf2Q== +mdast-util-from-markdown@^1.3.0: + version "1.3.0" + resolved "https://registry.yarnpkg.com/mdast-util-from-markdown/-/mdast-util-from-markdown-1.3.0.tgz#0214124154f26154a2b3f9d401155509be45e894" + integrity sha512-HN3W1gRIuN/ZW295c7zi7g9lVBllMgZE40RxCX37wrTPWXCWtpvOZdfnuK+1WNpvZje6XuJeI3Wnb4TJEUem+g== dependencies: "@types/mdast" "^3.0.0" "@types/unist" "^2.0.0" @@ -4420,6 +4448,11 @@ minimist@^1.2.0: resolved "https://registry.yarnpkg.com/minimist/-/minimist-1.2.7.tgz#daa1c4d91f507390437c6a8bc01078e7000c4d18" integrity sha512-bzfL1YUZsP41gmu/qjrEk0Q6i2ix/cVeAhbCbqH9u3zYutS1cLg00qhrD0M2MVdCcx4Sc0UpP2eBWo9rotpq6g== +minimist@^1.2.8: + version "1.2.8" + resolved "https://registry.yarnpkg.com/minimist/-/minimist-1.2.8.tgz#c1a464e7693302e082a075cee0c057741ac4772c" + integrity sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA== + minipass@^3.0.0: version "3.3.6" resolved "https://registry.yarnpkg.com/minipass/-/minipass-3.3.6.tgz#7bba384db3a1520d18c9c0e5251c3444e95dd94a" @@ -4515,6 +4548,13 @@ node-fetch@^2.6.7: dependencies: whatwg-url "^5.0.0" +node-fetch@^2.6.9: + version "2.6.9" + resolved "https://registry.yarnpkg.com/node-fetch/-/node-fetch-2.6.9.tgz#7c7f744b5cc6eb5fd404e0c7a9fec630a55657e6" + integrity sha512-DJm/CJkZkRjKKj4Zi4BsKVZh3ValV5IR5s7LVZnW+6YMh0W1BfNA8XSs6DLMGYlId5F3KnA70uu2qepcR08Qqg== + dependencies: + whatwg-url "^5.0.0" + node-releases@^2.0.6: version "2.0.6" resolved "https://registry.yarnpkg.com/node-releases/-/node-releases-2.0.6.tgz#8a7088c63a55e493845683ebf3c828d8c51c5503" @@ -6761,10 +6801,10 @@ unist-util-visit@^2.0.0: unist-util-is "^4.0.0" unist-util-visit-parents "^3.0.0" -unist-util-visit@^4.1.1: - version "4.1.1" - resolved "https://registry.yarnpkg.com/unist-util-visit/-/unist-util-visit-4.1.1.tgz#1c4842d70bd3df6cc545276f5164f933390a9aad" - integrity sha512-n9KN3WV9k4h1DxYR1LoajgN93wpEi/7ZplVe02IoB4gH5ctI1AaF2670BLHQYbwj+pY83gFtyeySFiyMHJklrg== +unist-util-visit@^4.1.2: + version "4.1.2" + resolved "https://registry.yarnpkg.com/unist-util-visit/-/unist-util-visit-4.1.2.tgz#125a42d1eb876283715a3cb5cceaa531828c72e2" + integrity sha512-MSd8OUGISqHdVvfY9TPhyK2VdUrPgxkUtWSuMHF6XAAFuL4LokseigBnZtPnJMu+FbynTkFNnFlyjxpVKujMRg== dependencies: "@types/unist" "^2.0.0" unist-util-is "^5.0.0" @@ -6920,41 +6960,56 @@ vfile@^5.0.0: unist-util-stringify-position "^3.0.0" vfile-message "^3.0.0" [email protected]: - version "8.0.2" - resolved "https://registry.yarnpkg.com/vscode-jsonrpc/-/vscode-jsonrpc-8.0.2.tgz#f239ed2cd6004021b6550af9fd9d3e47eee3cac9" - integrity sha512-RY7HwI/ydoC1Wwg4gJ3y6LpU9FJRZAUnTYMXthqhFXXu77ErDd/xkREpGuk4MyYkk4a+XDWAMqe0S3KkelYQEQ== [email protected]: + version "8.1.0" + resolved "https://registry.yarnpkg.com/vscode-jsonrpc/-/vscode-jsonrpc-8.1.0.tgz#cb9989c65e219e18533cc38e767611272d274c94" + integrity sha512-6TDy/abTQk+zDGYazgbIPc+4JoXdwC8NHU9Pbn4UJP1fehUyZmM4RHp5IthX7A6L5KS30PRui+j+tbbMMMafdw== [email protected]: - version "3.17.2" - resolved "https://registry.yarnpkg.com/vscode-languageserver-protocol/-/vscode-languageserver-protocol-3.17.2.tgz#beaa46aea06ed061576586c5e11368a9afc1d378" - integrity sha512-8kYisQ3z/SQ2kyjlNeQxbkkTNmVFoQCqkmGrzLH6A9ecPlgTbp3wDTnUNqaUxYr4vlAcloxx8zwy7G5WdguYNg== [email protected]: + version "3.17.3" + resolved "https://registry.yarnpkg.com/vscode-languageserver-protocol/-/vscode-languageserver-protocol-3.17.3.tgz#6d0d54da093f0c0ee3060b81612cce0f11060d57" + integrity sha512-924/h0AqsMtA5yK22GgMtCYiMdCOtWTSGgUOkgEDX+wk2b0x4sAfLiO4NxBxqbiVtz7K7/1/RgVrVI0NClZwqA== dependencies: - vscode-jsonrpc "8.0.2" - vscode-languageserver-types "3.17.2" + vscode-jsonrpc "8.1.0" + vscode-languageserver-types "3.17.3" -vscode-languageserver-textdocument@^1.0.5, vscode-languageserver-textdocument@^1.0.7: +vscode-languageserver-textdocument@^1.0.5: version "1.0.7" resolved "https://registry.yarnpkg.com/vscode-languageserver-textdocument/-/vscode-languageserver-textdocument-1.0.7.tgz#16df468d5c2606103c90554ae05f9f3d335b771b" integrity sha512-bFJH7UQxlXT8kKeyiyu41r22jCZXG8kuuVVA33OEJn1diWOZK5n8zBSPZFHVBOu8kXZ6h0LIRhf5UnCo61J4Hg== [email protected], vscode-languageserver-types@^3.17.1: +vscode-languageserver-textdocument@^1.0.8: + version "1.0.8" + resolved "https://registry.yarnpkg.com/vscode-languageserver-textdocument/-/vscode-languageserver-textdocument-1.0.8.tgz#9eae94509cbd945ea44bca8dcfe4bb0c15bb3ac0" + integrity sha512-1bonkGqQs5/fxGT5UchTgjGVnfysL0O8v1AYMBjqTbWQTFn721zaPGDYFkOKtfDgFiSgXM3KwaG3FMGfW4Ed9Q== + [email protected]: + version "3.17.3" + resolved "https://registry.yarnpkg.com/vscode-languageserver-types/-/vscode-languageserver-types-3.17.3.tgz#72d05e47b73be93acb84d6e311b5786390f13f64" + integrity sha512-SYU4z1dL0PyIMd4Vj8YOqFvHu7Hz/enbWtpfnVbJHU4Nd1YNYx8u0ennumc6h48GQNeOLxmwySmnADouT/AuZA== + +vscode-languageserver-types@^3.17.1: version "3.17.2" resolved "https://registry.yarnpkg.com/vscode-languageserver-types/-/vscode-languageserver-types-3.17.2.tgz#b2c2e7de405ad3d73a883e91989b850170ffc4f2" integrity sha512-zHhCWatviizPIq9B7Vh9uvrH6x3sK8itC84HkamnBWoDFJtzBf7SWlpLCZUit72b3os45h6RWQNC9xHRDF8dRA== -vscode-languageserver@^8.0.2: - version "8.0.2" - resolved "https://registry.yarnpkg.com/vscode-languageserver/-/vscode-languageserver-8.0.2.tgz#cfe2f0996d9dfd40d3854e786b2821604dfec06d" - integrity sha512-bpEt2ggPxKzsAOZlXmCJ50bV7VrxwCS5BI4+egUmure/oI/t4OlFzi/YNtVvY24A2UDOZAgwFGgnZPwqSJubkA== +vscode-languageserver@^8.1.0: + version "8.1.0" + resolved "https://registry.yarnpkg.com/vscode-languageserver/-/vscode-languageserver-8.1.0.tgz#5024253718915d84576ce6662dd46a791498d827" + integrity sha512-eUt8f1z2N2IEUDBsKaNapkz7jl5QpskN2Y0G01T/ItMxBxw1fJwvtySGB9QMecatne8jFIWJGWI61dWjyTLQsw== dependencies: - vscode-languageserver-protocol "3.17.2" + vscode-languageserver-protocol "3.17.3" -vscode-uri@^3.0.3, vscode-uri@^3.0.6: +vscode-uri@^3.0.3: version "3.0.6" resolved "https://registry.yarnpkg.com/vscode-uri/-/vscode-uri-3.0.6.tgz#5e6e2e1a4170543af30151b561a41f71db1d6f91" integrity sha512-fmL7V1eiDBFRRnu+gfRWTzyPpNIHJTc4mWnFkwBUmO9U3KPgJAmTx7oxi2bl/Rh6HLdU7+4C9wlj0k2E4AdKFQ== +vscode-uri@^3.0.7: + version "3.0.7" + resolved "https://registry.yarnpkg.com/vscode-uri/-/vscode-uri-3.0.7.tgz#6d19fef387ee6b46c479e5fb00870e15e58c1eb8" + integrity sha512-eOpPHogvorZRobNqJGhapa0JdwaxpjVvyBp0QIUMRMSf8ZAlqOdEquKuRmw9Qwu0qXtJIWqFtMkmvJjUZmMjVA== + walk-sync@^0.3.2: version "0.3.4" resolved "https://registry.yarnpkg.com/walk-sync/-/walk-sync-0.3.4.tgz#cf78486cc567d3a96b5b2237c6108017a5ffb9a4"
chore
4085185e2dd56cd691ba3c8ece36f63c969563b0
Calvin
2025-02-10 08:12:17
docs: `transactions-updated` event type (#45527) fix: `transactions-updated` event type
diff --git a/docs/api/in-app-purchase.md b/docs/api/in-app-purchase.md index 38078ecf29..0fed7b8c2c 100644 --- a/docs/api/in-app-purchase.md +++ b/docs/api/in-app-purchase.md @@ -10,13 +10,13 @@ The `inAppPurchase` module emits the following events: ### Event: 'transactions-updated' -Emitted when one or more transactions have been updated. - Returns: * `event` Event * `transactions` Transaction[] - Array of [`Transaction`](structures/transaction.md) objects. +Emitted when one or more transactions have been updated. + ## Methods The `inAppPurchase` module has the following methods:
docs
e89da2bad2f4c449903de1edc7b8655320a6dadc
Charles Kerr
2024-07-08 05:55:48
fix: dangling raw_ptr<Session> in UserDataLink (#42786) * fix: dangling raw_ptr<Session> in UserDataLink * chore: make linter happy
diff --git a/shell/browser/api/electron_api_session.cc b/shell/browser/api/electron_api_session.cc index f1afe83824..d161a29a2b 100644 --- a/shell/browser/api/electron_api_session.cc +++ b/shell/browser/api/electron_api_session.cc @@ -530,9 +530,10 @@ class DictionaryObserver final : public SpellcheckCustomDictionary::Observer { #endif // BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) struct UserDataLink : base::SupportsUserData::Data { - explicit UserDataLink(Session* ses) : session(ses) {} + explicit UserDataLink(base::WeakPtr<Session> session_in) + : session{std::move(session_in)} {} - raw_ptr<Session> session; + base::WeakPtr<Session> session; }; const void* kElectronApiSessionKey = &kElectronApiSessionKey; @@ -553,8 +554,9 @@ Session::Session(v8::Isolate* isolate, ElectronBrowserContext* browser_context) protocol_.Reset(isolate, Protocol::Create(isolate, browser_context).ToV8()); - browser_context->SetUserData(kElectronApiSessionKey, - std::make_unique<UserDataLink>(this)); + browser_context->SetUserData( + kElectronApiSessionKey, + std::make_unique<UserDataLink>(weak_factory_.GetWeakPtr())); #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) if (auto* service = @@ -1511,7 +1513,7 @@ bool Session::IsSpellCheckerEnabled() const { Session* Session::FromBrowserContext(content::BrowserContext* context) { auto* data = static_cast<UserDataLink*>(context->GetUserData(kElectronApiSessionKey)); - return data ? data->session : nullptr; + return data ? data->session.get() : nullptr; } // static diff --git a/shell/browser/api/electron_api_session.h b/shell/browser/api/electron_api_session.h index b2ccd90e55..70972f83d0 100644 --- a/shell/browser/api/electron_api_session.h +++ b/shell/browser/api/electron_api_session.h @@ -10,6 +10,7 @@ #include <vector> #include "base/memory/raw_ptr.h" +#include "base/memory/weak_ptr.h" #include "base/values.h" #include "content/public/browser/download_manager.h" #include "electron/buildflags/buildflags.h" @@ -218,6 +219,8 @@ class Session : public gin::Wrappable<Session>, base::UnguessableToken network_emulation_token_; const raw_ref<ElectronBrowserContext> browser_context_; + + base::WeakPtrFactory<Session> weak_factory_{this}; }; } // namespace api
fix
c8f715f9a1c116ccb3796e3290fea89989cc0f6e
Calvin
2023-03-06 07:46:35
fix: Showing the about panel is async on all platforms (#37440) * fix: about panel is a base::Value::Dict * nix this test for a diff PR * what if the about dialog was not blocking * add this test back in * document synchronicity * github editor is a fan of spaces
diff --git a/docs/api/app.md b/docs/api/app.md index 1fd26f6839..cd6eb3aab9 100755 --- a/docs/api/app.md +++ b/docs/api/app.md @@ -1357,7 +1357,7 @@ This API must be called after the `ready` event is emitted. ### `app.showAboutPanel()` -Show the app's about panel options. These options can be overridden with `app.setAboutPanelOptions(options)`. +Show the app's about panel options. These options can be overridden with `app.setAboutPanelOptions(options)`. This function runs asynchronously. ### `app.setAboutPanelOptions(options)` diff --git a/shell/browser/browser_linux.cc b/shell/browser/browser_linux.cc index 1e70de2aa5..7eb093e3db 100644 --- a/shell/browser/browser_linux.cc +++ b/shell/browser/browser_linux.cc @@ -212,8 +212,11 @@ void Browser::ShowAboutPanel() { } } - gtk_dialog_run(GTK_DIALOG(dialog)); - gtk_widget_destroy(dialogWidget); + // destroy the widget when it closes + g_signal_connect_swapped(dialogWidget, "response", + G_CALLBACK(gtk_widget_destroy), dialogWidget); + + gtk_widget_show_all(dialogWidget); } void Browser::SetAboutPanelOptions(base::Value::Dict options) { diff --git a/shell/browser/browser_win.cc b/shell/browser/browser_win.cc index a451cbdef1..2a72e070f4 100644 --- a/shell/browser/browser_win.cc +++ b/shell/browser/browser_win.cc @@ -2,6 +2,7 @@ // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. +#include "base/functional/bind.h" #include "shell/browser/browser.h" // must come before other includes. fixes bad #defines from <shlwapi.h>. @@ -765,7 +766,8 @@ void Browser::ShowAboutPanel() { settings.message = aboutMessage; settings.icon = image; settings.type = electron::MessageBoxType::kInformation; - electron::ShowMessageBoxSync(settings); + electron::ShowMessageBox(settings, + base::BindOnce([](int, bool) { /* do nothing. */ })); } void Browser::SetAboutPanelOptions(base::Value::Dict options) { diff --git a/spec/api-app-spec.ts b/spec/api-app-spec.ts index fab10800bc..38ecb1c26f 100644 --- a/spec/api-app-spec.ts +++ b/spec/api-app-spec.ts @@ -1867,6 +1867,10 @@ describe('app module', () => { version: '1.2.3' }); }); + + it('app.showAboutPanel() does not crash & runs asynchronously', () => { + app.showAboutPanel(); + }); }); });
fix
bbfe809d02a09b924b0c3059dd7d378ae5280419
Samuel Attard
2024-01-12 13:50:20
docs: add reclient docs, remove goma docs (#40948) * docs: add reclient docs, remove goma docs * Apply suggestions from code review Co-authored-by: Charles Kerr <[email protected]> --------- Co-authored-by: Charles Kerr <[email protected]>
diff --git a/docs/development/goma.md b/docs/development/goma.md index 5c3f871ef8..21d6ed93ce 100644 --- a/docs/development/goma.md +++ b/docs/development/goma.md @@ -3,54 +3,4 @@ > Goma is a distributed compiler service for open-source projects such as > Chromium and Android. -Electron has a deployment of a custom Goma Backend that we make available to -all Electron Maintainers. See the [Access](#access) section below for details -on authentication. There is also a `cache-only` Goma endpoint that will be -used by default if you do not have credentials. Requests to the cache-only -Goma will not hit our cluster, but will read from our cache and should result -in significantly faster build times. - -## Enabling Goma - -Currently the only supported way to use Goma is to use our [Build Tools](https://github.com/electron/build-tools). -Goma configuration is automatically included when you set up `build-tools`. - -If you are a maintainer and have access to our cluster, please ensure that you run -`e init` with `--goma=cluster` in order to configure `build-tools` to use -the Goma cluster. If you have an existing config, you can just set `"goma": "cluster"` -in your config file. - -## Building with Goma - -When you are using Goma you can run `ninja` with a substantially higher `j` -value than would normally be supported by your machine. - -Please do not set a value higher than **200**. We monitor Goma system usage, and users -found to be abusing it with unreasonable concurrency will be de-activated. - -```bash -ninja -C out/Testing electron -j 200 -``` - -If you're using `build-tools`, appropriate `-j` values will automatically be used for you. - -## Monitoring Goma - -If you access [http://localhost:8088](http://localhost:8088) on your local -machine you can monitor compile jobs as they flow through the goma system. - -## Access - -For security and cost reasons, access to Electron's Goma cluster is currently restricted -to Electron Maintainers. If you want access please head to `#access-requests` in -Slack and ping `@goma-squad` to ask for access. Please be aware that being a -maintainer does not _automatically_ grant access and access is determined on a -case by case basis. - -## Uptime / Support - -We have automated monitoring of our Goma cluster and cache at https://status.notgoma.com - -We do not provide support for usage of Goma and any issues raised asking for help / having -issues will _probably_ be closed without much reason, we do not have the capacity to handle -that kind of support. +Electron's deployment of Goma is deprecated and we are gradually shifting all usage to the [reclient](reclient.md) system. At some point in 2024 the Goma backend will be shutdown. diff --git a/docs/development/reclient.md b/docs/development/reclient.md new file mode 100644 index 0000000000..f84b0515e0 --- /dev/null +++ b/docs/development/reclient.md @@ -0,0 +1,46 @@ +# Reclient + +> Reclient integrates with an existing build system to enable remote execution and caching of build actions. + +Electron has a deployment of a [reclient](https://github.com/bazelbuild/reclient) +compatible RBE Backend that is available to all Electron Maintainers. +See the [Access](#access) section below for details on authentication. Non-maintainers +will not have access to the cluster, but can sign in to receive a `Cache Only` token +that gives access to the cache-only CAS backend. Using this should result in +significantly faster build times . + +## Enabling Reclient + +Currently the only supported way to use Reclient is to use our [Build Tools](https://github.com/electron/build-tools). +Reclient configuration is automatically included when you set up `build-tools`. + +If you have an existing config, you can just set `"reclient": "remote_exec"` +in your config file. + +## Building with Reclient + +When you are using Reclient, you can run `autoninja` with a substantially higher `j` +value than would normally be supported by your machine. + +Please do not set a value higher than **200**. The RBE system is monitored. +Users found to be abusing it with unreasonable concurrency will be deactivated. + +```bash +autoninja -C out/Testing electron -j 200 +``` + +If you're using `build-tools`, appropriate `-j` values will automatically be used for you. + +## Access + +For security and cost reasons, access to Electron's RBE backend is currently restricted +to Electron Maintainers. If you want access, please head to `#access-requests` in +Slack and ping `@infra-wg` to ask for it. Please be aware that being a +maintainer does not _automatically_ grant access. Access is determined on a +case-by-case basis. + +## Support + +We do not provide support for usage of Reclient. Issues raised asking for help / having +issues will _probably_ be closed without much reason. We do not have the capacity to handle +that kind of support.
docs
77f7ba96ca8cb6248291cfb78bb66384d6e983b3
Charles Kerr
2024-09-30 08:09:36
fix: -Wunsafe-buffer-usage in electron::SetFontDefaults() (#44014) * refactor: reduce code duplication in WebContentsPreferences::OverrideWebkitPrefs() * refactor: limit scope of web_preferences temporary in ElectronBrowserClient::OverrideWebkitPrefs() * chore: savepoint * chore: savepoint * chore: savepoint * chore: savepoint * chore: remove logging * fix: unconditionally write * chore: naming * chore: add code comments * chore: more code comments * chore: remove unrelated changes * chore: remove redundant static keyword on function in anonymous namespace * refactor: naming * refactor: naming * refactor: naming * refactor: slightly more explicit typing * refactor: remove unnecessary utf16 -> utf8 -> utf16 conversion steps * chore: remove unused #includes
diff --git a/shell/browser/font_defaults.cc b/shell/browser/font_defaults.cc index a551b3d8d9..f5ebf2654e 100644 --- a/shell/browser/font_defaults.cc +++ b/shell/browser/font_defaults.cc @@ -4,12 +4,12 @@ #include "shell/browser/font_defaults.h" -#include <array> #include <string> #include <string_view> -#include "base/strings/strcat.h" -#include "base/strings/utf_string_conversions.h" +#include "base/containers/fixed_flat_map.h" +#include "base/containers/map_util.h" +#include "base/strings/string_split.h" #include "chrome/common/pref_names.h" #include "chrome/grit/platform_locale_settings.h" #include "third_party/blink/public/common/web_preferences/web_preferences.h" @@ -106,88 +106,60 @@ const FontDefault kFontDefaults[] = { // ^^^^^ DO NOT EDIT ^^^^^ -// Get `kFontDefault`'s default fontname for [font family, script]. -// e.g. ("webkit.webprefs.fonts.fixed", "Zyyy") -> "Monospace" -std::string GetDefaultFont(const std::string_view family_name, - const std::string_view script_name) { - const std::string pref_name = base::StrCat({family_name, ".", script_name}); - - for (const FontDefault& pref : kFontDefaults) { - if (pref_name == pref.pref_name) { - return l10n_util::GetStringUTF8(pref.resource_id); +auto MakeDefaultFontCopier() { + using namespace prefs; + using WP = blink::web_pref::WebPreferences; + using FamilyMap = blink::web_pref::ScriptFontFamilyMap; + + // Map from a family name (e.g. "webkit.webprefs.fonts.fixed") to a + // Pointer-to-Member of the location in WebPreferences of its + // ScriptFontFamilyMap (e.g. &WebPreferences::fixed_font_family_map) + static constexpr auto FamilyMapByName = + base::MakeFixedFlatMap<std::string_view, FamilyMap WP::*>({ + {kWebKitStandardFontFamilyMap, &WP::standard_font_family_map}, + {kWebKitFixedFontFamilyMap, &WP::fixed_font_family_map}, + {kWebKitSerifFontFamilyMap, &WP::serif_font_family_map}, + {kWebKitSansSerifFontFamilyMap, &WP::sans_serif_font_family_map}, + {kWebKitCursiveFontFamilyMap, &WP::cursive_font_family_map}, + }); + + WP defaults; + + // Populate `defaults`'s ScriptFontFamilyMaps with the values from + // the kFontDefaults array in the "DO NOT EDIT" section of this file. + // + // The kFontDefaults's `pref_name` field is built as `${family}.${script}`, + // so splitting on the last '.' gives the family and script: a pref key of + // "webkit.webprefs.fonts.fixed.Zyyy" splits into family name + // "webkit.webprefs.fonts.fixed" and script "Zyyy". (Yes, "Zyyy" is real. + // See pref_font_script_names-inl.h for the full list :) + for (const auto& [pref_name, resource_id] : kFontDefaults) { + const auto [family, script] = *base::RSplitStringOnce(pref_name, '.'); + if (auto* family_map_ptr = base::FindOrNull(FamilyMapByName, family)) { + FamilyMap& family_map = defaults.**family_map_ptr; + family_map[std::string{script}] = l10n_util::GetStringUTF16(resource_id); } } - return std::string{}; -} - -// Each font family has kWebKitScriptsForFontFamilyMapsLength scripts. -// This is a lookup array for script_index -> fontname -using PerFamilyFonts = - std::array<std::u16string, prefs::kWebKitScriptsForFontFamilyMapsLength>; - -PerFamilyFonts MakeCacheForFamily(const std::string_view family_name) { - PerFamilyFonts ret; - for (size_t i = 0; i < prefs::kWebKitScriptsForFontFamilyMapsLength; ++i) { - const char* script_name = prefs::kWebKitScriptsForFontFamilyMaps[i]; - ret[i] = base::UTF8ToUTF16(GetDefaultFont(family_name, script_name)); - } - return ret; -} - -void FillFontFamilyMap(const PerFamilyFonts& cache, - blink::web_pref::ScriptFontFamilyMap& font_family_map) { - for (size_t i = 0; i < prefs::kWebKitScriptsForFontFamilyMapsLength; ++i) { - if (const std::u16string& fontname = cache[i]; !fontname.empty()) { - char const* const script_name = prefs::kWebKitScriptsForFontFamilyMaps[i]; - font_family_map[script_name] = fontname; + // Lambda that copies all of `default`'s fonts into `prefs` + auto copy_default_fonts_to_web_prefs = [defaults](WP* prefs) { + for (const auto [_, family_map_ptr] : FamilyMapByName) { + const FamilyMap& src = defaults.*family_map_ptr; + FamilyMap& tgt = prefs->*family_map_ptr; + for (const auto& [key, val] : src) + tgt[key] = val; } - } -} + }; -struct FamilyCache { - std::string_view family_name; - - // where to find the font_family_map in a WebPreferences instance - blink::web_pref::ScriptFontFamilyMap blink::web_pref::WebPreferences::* - map_offset; - - PerFamilyFonts fonts = {}; -}; - -static auto MakeCache() { - // the font families whose defaults we want to cache - std::array<FamilyCache, 5> cache{{ - {prefs::kWebKitStandardFontFamilyMap, - &blink::web_pref::WebPreferences::standard_font_family_map}, - {prefs::kWebKitFixedFontFamilyMap, - &blink::web_pref::WebPreferences::fixed_font_family_map}, - {prefs::kWebKitSerifFontFamilyMap, - &blink::web_pref::WebPreferences::serif_font_family_map}, - {prefs::kWebKitSansSerifFontFamilyMap, - &blink::web_pref::WebPreferences::sans_serif_font_family_map}, - {prefs::kWebKitCursiveFontFamilyMap, - &blink::web_pref::WebPreferences::cursive_font_family_map}, - }}; - - // populate the cache - for (FamilyCache& row : cache) { - row.fonts = MakeCacheForFamily(row.family_name); - } - - return cache; + return copy_default_fonts_to_web_prefs; } - } // namespace namespace electron { void SetFontDefaults(blink::web_pref::WebPreferences* prefs) { - static auto const cache = MakeCache(); - - for (FamilyCache const& row : cache) { - FillFontFamilyMap(row.fonts, prefs->*row.map_offset); - } + static const auto copy_default_fonts_to_web_prefs = MakeDefaultFontCopier(); + copy_default_fonts_to_web_prefs(prefs); } } // namespace electron
fix
e4d5dc138fd909de288fde82ee5d03106fe092f2
Shelley Vohr
2024-01-31 15:53:30
fix: `select-usb-device` should respect `filters` option (#41166) fix: select-usb-device should respect filters option
diff --git a/shell/browser/usb/usb_chooser_controller.cc b/shell/browser/usb/usb_chooser_controller.cc index 992b9f7b32..b367626836 100644 --- a/shell/browser/usb/usb_chooser_controller.cc +++ b/shell/browser/usb/usb_chooser_controller.cc @@ -120,6 +120,14 @@ void UsbChooserController::GotUsbDeviceList( auto* rfh = content::RenderFrameHost::FromID(render_frame_host_id_); v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); + + // "select-usb-device" should respect |filters|. + devices.erase(std::remove_if(devices.begin(), devices.end(), + [this](const auto& device_info) { + return !DisplayDevice(*device_info); + }), + devices.end()); + v8::Local<v8::Object> details = gin::DataObjectBuilder(isolate) .Set("deviceList", devices) .Set("frame", rfh)
fix
14303a0a71cbd30d772e79209355db6f01dbd635
Anny Yang
2024-07-01 12:01:27
docs: grammar fix in isBeingCaptured docs (#42692)
diff --git a/docs/api/web-contents.md b/docs/api/web-contents.md index 9128e0f061..00c5663050 100644 --- a/docs/api/web-contents.md +++ b/docs/api/web-contents.md @@ -1566,7 +1566,7 @@ If you would like the page to stay hidden, you should ensure that `stayHidden` i #### `contents.isBeingCaptured()` Returns `boolean` - Whether this page is being captured. It returns true when the capturer count -is large then 0. +is greater than 0. #### `contents.getPrintersAsync()`
docs
cf4ab2186c6266d0942f3f91349ccbf49e76f14b
Samuel Attard
2024-09-17 14:49:59
build: improve logging on http errors during release process (again) (#43757)
diff --git a/script/release/get-asset.js b/script/release/get-asset.js index 3658530337..086e0bf540 100644 --- a/script/release/get-asset.js +++ b/script/release/get-asset.js @@ -26,9 +26,9 @@ async function getAssetContents (repo, assetId) { throwHttpErrors: false }); - if (response.status !== 302 && response.status !== 301) { + if (response.statusCode !== 302 && response.statusCode !== 301) { console.error('Failed to HEAD github asset contents for redirect: ' + url); - throw new Error('Unexpected status HEAD\'ing github asset: ' + response.status); + throw new Error('Unexpected status HEAD\'ing github asset for redirect: ' + response.statusCode); } if (!response.headers.location) { @@ -40,14 +40,9 @@ async function getAssetContents (repo, assetId) { throwHttpErrors: false }); - if (fileResponse.status !== 200) { - fileResponse.error(`Failed to download github asset contents: ${url} (via: ${response.headers.location})`); - throw new Error('Unexpected status fetching github asset: ' + fileResponse.status); - } - if (fileResponse.statusCode !== 200) { console.error(fileResponse.headers, `${fileResponse.body}`.slice(0, 300)); - throw new Error(`cannot download asset[${assetId}] from ${response.headers.location}, got status: ${fileResponse.status}`); + throw new Error(`cannot download asset[${assetId}] from ${response.headers.location}, got status: ${fileResponse.statusCode}`); } return fileResponse.body; diff --git a/script/release/release.js b/script/release/release.js index 8977ad49e2..f4ca11af7b 100755 --- a/script/release/release.js +++ b/script/release/release.js @@ -401,9 +401,9 @@ async function verifyDraftGitHubReleaseAssets (release) { throwHttpErrors: false }); - if (response.status !== 200) { + if (response.statusCode !== 200) { console.error('Failed to HEAD github asset: ' + url); - throw new Error('Unexpected status HEAD\'ing github asset: ' + response.status); + throw new Error('Unexpected status HEAD\'ing github asset: ' + response.statusCode); } return { url: response.headers.location, file: asset.name }; @@ -420,10 +420,10 @@ async function getShaSumMappingFromUrl (shaSumFileUrl, fileNamePrefix) { throwHttpErrors: false }); - if (response.status !== 200) { + if (response.statusCode !== 200) { console.error('Failed to fetch SHASUM mapping: ' + shaSumFileUrl); console.error('Bad SHASUM mapping response: ' + response.body.trim()); - throw new Error('Unexpected status fetching SHASUM mapping: ' + response.status); + throw new Error('Unexpected status fetching SHASUM mapping: ' + response.statusCode); } const raw = response.body;
build
305b28e9c7c3b60200d8e92540a0aa6fd790afef
Charles Kerr
2024-08-02 13:58:13
chore: bump chromium to 129.0.6632.0 (#43184) * chore: bump chromium in DEPS to 129.0.6632.0 * chore: update build_do_not_depend_on_packed_resource_integrity.patch apply patch manually due to context shear Xref: https://chromium-review.googlesource.com/c/chromium/src/+/5755242 * chore: e patches all
diff --git a/DEPS b/DEPS index ce79fb59cb..6a099660bd 100644 --- a/DEPS +++ b/DEPS @@ -2,7 +2,7 @@ gclient_gn_args_from = 'src' vars = { 'chromium_version': - '129.0.6630.0', + '129.0.6632.0', 'node_version': 'v20.16.0', 'nan_version': diff --git a/patches/chromium/adjust_accessibility_ui_for_electron.patch b/patches/chromium/adjust_accessibility_ui_for_electron.patch index 6a838f1ff7..0843467e8a 100644 --- a/patches/chromium/adjust_accessibility_ui_for_electron.patch +++ b/patches/chromium/adjust_accessibility_ui_for_electron.patch @@ -10,10 +10,10 @@ usage of BrowserList and Browser as we subclass related methods and use our WindowList. diff --git a/chrome/browser/ui/webui/accessibility/accessibility_ui.cc b/chrome/browser/ui/webui/accessibility/accessibility_ui.cc -index 8bf96dc519e1479d8986ff81c3c81641e5e7c58b..a2b70a26febcebedc125c4c83b662b3c77cb428b 100644 +index 125316ef23a7d82d778aca9e40c99144a6d29ba1..a2aa6da83f0d77fd0c1cba864578ff7bcb471510 100644 --- a/chrome/browser/ui/webui/accessibility/accessibility_ui.cc +++ b/chrome/browser/ui/webui/accessibility/accessibility_ui.cc -@@ -43,6 +43,7 @@ +@@ -48,6 +48,7 @@ #include "content/public/browser/web_contents.h" #include "content/public/browser/web_contents_delegate.h" #include "content/public/browser/web_ui_data_source.h" @@ -21,7 +21,7 @@ index 8bf96dc519e1479d8986ff81c3c81641e5e7c58b..a2b70a26febcebedc125c4c83b662b3c #include "ui/accessibility/accessibility_features.h" #include "ui/accessibility/ax_updates_and_events.h" #include "ui/accessibility/platform/ax_platform_node.h" -@@ -169,7 +170,7 @@ base::Value::Dict BuildTargetDescriptor(content::RenderViewHost* rvh) { +@@ -174,7 +175,7 @@ base::Value::Dict BuildTargetDescriptor(content::RenderViewHost* rvh) { accessibility_mode); } @@ -30,7 +30,7 @@ index 8bf96dc519e1479d8986ff81c3c81641e5e7c58b..a2b70a26febcebedc125c4c83b662b3c base::Value::Dict BuildTargetDescriptor(Browser* browser) { base::Value::Dict target_data; target_data.Set(kSessionIdField, browser->session_id().id()); -@@ -203,7 +204,7 @@ void HandleAccessibilityRequestCallback( +@@ -208,7 +209,7 @@ void HandleAccessibilityRequestCallback( DCHECK(ShouldHandleAccessibilityRequestCallback(path)); base::Value::Dict data; @@ -39,7 +39,7 @@ index 8bf96dc519e1479d8986ff81c3c81641e5e7c58b..a2b70a26febcebedc125c4c83b662b3c ui::AXMode mode = content::BrowserAccessibilityState::GetInstance()->GetAccessibilityMode(); bool is_native_enabled = content::BrowserAccessibilityState::GetInstance() -@@ -236,7 +237,7 @@ void HandleAccessibilityRequestCallback( +@@ -241,7 +242,7 @@ void HandleAccessibilityRequestCallback( data.Set(kViewsAccessibility, features::IsAccessibilityTreeForViewsEnabled()); std::string pref_api_type = @@ -48,7 +48,7 @@ index 8bf96dc519e1479d8986ff81c3c81641e5e7c58b..a2b70a26febcebedc125c4c83b662b3c bool pref_api_type_supported = false; std::vector<ui::AXApiType::Type> supported_api_types = -@@ -303,11 +304,11 @@ void HandleAccessibilityRequestCallback( +@@ -308,11 +309,11 @@ void HandleAccessibilityRequestCallback( data.Set(kPagesField, std::move(page_list)); base::Value::List browser_list; @@ -62,7 +62,7 @@ index 8bf96dc519e1479d8986ff81c3c81641e5e7c58b..a2b70a26febcebedc125c4c83b662b3c data.Set(kBrowsersField, std::move(browser_list)); base::Value::List widgets_list; -@@ -647,7 +648,8 @@ void AccessibilityUIMessageHandler::SetGlobalString( +@@ -652,7 +653,8 @@ void AccessibilityUIMessageHandler::SetGlobalString( const std::string value = CheckJSValue(data.FindString(kValueField)); if (string_name == kApiTypeField) { @@ -72,7 +72,7 @@ index 8bf96dc519e1479d8986ff81c3c81641e5e7c58b..a2b70a26febcebedc125c4c83b662b3c pref->SetString(prefs::kShownAccessibilityApiType, value); } } -@@ -700,7 +702,8 @@ void AccessibilityUIMessageHandler::RequestWebContentsTree( +@@ -705,7 +707,8 @@ void AccessibilityUIMessageHandler::RequestWebContentsTree( AXPropertyFilter::ALLOW_EMPTY); AddPropertyFilters(property_filters, deny, AXPropertyFilter::DENY); @@ -82,7 +82,7 @@ index 8bf96dc519e1479d8986ff81c3c81641e5e7c58b..a2b70a26febcebedc125c4c83b662b3c ui::AXApiType::Type api_type = ui::AXApiType::From(pref->GetString(prefs::kShownAccessibilityApiType)); std::string accessibility_contents = -@@ -727,6 +730,7 @@ void AccessibilityUIMessageHandler::RequestNativeUITree( +@@ -732,6 +735,7 @@ void AccessibilityUIMessageHandler::RequestNativeUITree( AXPropertyFilter::ALLOW_EMPTY); AddPropertyFilters(property_filters, deny, AXPropertyFilter::DENY); @@ -90,7 +90,7 @@ index 8bf96dc519e1479d8986ff81c3c81641e5e7c58b..a2b70a26febcebedc125c4c83b662b3c for (Browser* browser : *BrowserList::GetInstance()) { if (browser->session_id().id() == session_id) { base::Value::Dict result = BuildTargetDescriptor(browser); -@@ -739,6 +743,7 @@ void AccessibilityUIMessageHandler::RequestNativeUITree( +@@ -744,6 +748,7 @@ void AccessibilityUIMessageHandler::RequestNativeUITree( return; } } @@ -98,7 +98,7 @@ index 8bf96dc519e1479d8986ff81c3c81641e5e7c58b..a2b70a26febcebedc125c4c83b662b3c #endif // !BUILDFLAG(IS_ANDROID) // No browser with the specified |session_id| was found. base::Value::Dict result; -@@ -807,11 +812,13 @@ void AccessibilityUIMessageHandler::StopRecording( +@@ -812,11 +817,13 @@ void AccessibilityUIMessageHandler::StopRecording( } ui::AXApiType::Type AccessibilityUIMessageHandler::GetRecordingApiType() { @@ -115,7 +115,7 @@ index 8bf96dc519e1479d8986ff81c3c81641e5e7c58b..a2b70a26febcebedc125c4c83b662b3c // Check to see if it is in the supported types list. if (std::find(supported_types.begin(), supported_types.end(), api_type) == supported_types.end()) { -@@ -881,8 +888,11 @@ void AccessibilityUIMessageHandler::RequestAccessibilityEvents( +@@ -886,8 +893,11 @@ void AccessibilityUIMessageHandler::RequestAccessibilityEvents( // static void AccessibilityUIMessageHandler::RegisterProfilePrefs( user_prefs::PrefRegistrySyncable* registry) { diff --git a/patches/chromium/build_do_not_depend_on_packed_resource_integrity.patch b/patches/chromium/build_do_not_depend_on_packed_resource_integrity.patch index 450fe3e20f..324da04409 100644 --- a/patches/chromium/build_do_not_depend_on_packed_resource_integrity.patch +++ b/patches/chromium/build_do_not_depend_on_packed_resource_integrity.patch @@ -11,10 +11,10 @@ if we ever align our .pak file generation with Chrome we can remove this patch. diff --git a/chrome/BUILD.gn b/chrome/BUILD.gn -index 7ef8050aa89bb4132680c6d00d5d6ab3ecfdc713..bcf823da79171196447708b12c6bfd15cb15774b 100644 +index 74c16760fbd0ec88d8cd4e92a6fc9a68c0a3ebe3..f4907e0e2f491078a652baba8302181f090a4d84 100644 --- a/chrome/BUILD.gn +++ b/chrome/BUILD.gn -@@ -192,11 +192,16 @@ if (!is_android && !is_mac) { +@@ -196,11 +196,16 @@ if (!is_android && !is_mac) { "common/crash_keys.h", ] @@ -33,24 +33,24 @@ index 7ef8050aa89bb4132680c6d00d5d6ab3ecfdc713..bcf823da79171196447708b12c6bfd15 "//base", "//build:branding_buildflags", diff --git a/chrome/browser/BUILD.gn b/chrome/browser/BUILD.gn -index 61c43d1fbd0823dd818de119201856c6ead600ba..fbdd0eb1738e46d78083c0814c306fdee046c829 100644 +index 30fdf95e3a255cbbb05f4634c19cc192b4c72643..724354994e2cd38f9f04159c065282499d5e3f48 100644 --- a/chrome/browser/BUILD.gn +++ b/chrome/browser/BUILD.gn -@@ -4605,7 +4605,7 @@ static_library("browser") { +@@ -4567,7 +4567,7 @@ static_library("browser") { + ] + } - # On Windows, the hashes are embedded in //chrome:chrome_initial rather - # than here in :chrome_dll. - if (!is_win) { + if (!is_win && !is_electron_build) { + # On Windows, the hashes are embedded in //chrome:chrome_initial rather + # than here in :chrome_dll. deps += [ "//chrome:packed_resources_integrity_header" ] - sources += [ "certificate_viewer_stub.cc" ] - } diff --git a/chrome/test/BUILD.gn b/chrome/test/BUILD.gn -index d462dcaf73b0b35b2de4b5db06cef90e5e242ee6..6291442ad205a1af5d25d03e3ef65e285045f3bf 100644 +index a469562fbb3cee09500652b4c8873c9681bdca2a..7511bb15b9ec3006f963e272c55c4c0f244d808d 100644 --- a/chrome/test/BUILD.gn +++ b/chrome/test/BUILD.gn -@@ -7147,9 +7147,12 @@ test("unit_tests") { - "//chrome/browser/safe_browsing/incident_reporting/verifier_test:verifier_test_dll_2", +@@ -7155,9 +7155,12 @@ test("unit_tests") { + "//chrome/notification_helper", ] + if (!is_electron_build) { @@ -63,7 +63,7 @@ index d462dcaf73b0b35b2de4b5db06cef90e5e242ee6..6291442ad205a1af5d25d03e3ef65e28 "//chrome//services/util_win:unit_tests", "//chrome/app:chrome_dll_resources", "//chrome/app:win_unit_tests", -@@ -8176,6 +8179,10 @@ test("unit_tests") { +@@ -8186,6 +8189,10 @@ test("unit_tests") { "../browser/performance_manager/policies/background_tab_loading_policy_unittest.cc", ] @@ -74,7 +74,7 @@ index d462dcaf73b0b35b2de4b5db06cef90e5e242ee6..6291442ad205a1af5d25d03e3ef65e28 sources += [ # The importer code is not used on Android. "../common/importer/firefox_importer_utils_unittest.cc", -@@ -8248,7 +8255,6 @@ test("unit_tests") { +@@ -8258,7 +8265,6 @@ test("unit_tests") { # Non-android deps for "unit_tests" target. deps += [ diff --git a/patches/chromium/build_make_libcxx_abi_unstable_false_for_electron.patch b/patches/chromium/build_make_libcxx_abi_unstable_false_for_electron.patch index c266daafce..bfa7473aef 100644 --- a/patches/chromium/build_make_libcxx_abi_unstable_false_for_electron.patch +++ b/patches/chromium/build_make_libcxx_abi_unstable_false_for_electron.patch @@ -6,7 +6,7 @@ Subject: build: make libcxx_abi_unstable false for electron https://nornagon.medium.com/a-libc-odyssey-973e51649063 diff --git a/buildtools/third_party/libc++/__config_site b/buildtools/third_party/libc++/__config_site -index 0d8e1cbe3d59a77bbef5eef0c2fa438923df8a52..1ee58aecb0b95536c3fe922125d9891335d16a9c 100644 +index d5222dbaf15ab1ccebe7b65cb59cf55fdb92542f..dba4c1db441c35798bea61057a586a4b93e973d3 100644 --- a/buildtools/third_party/libc++/__config_site +++ b/buildtools/third_party/libc++/__config_site @@ -18,7 +18,9 @@ diff --git a/patches/chromium/chore_provide_iswebcontentscreationoverridden_with_full_params.patch b/patches/chromium/chore_provide_iswebcontentscreationoverridden_with_full_params.patch index 7dfc958997..1a6842cfcb 100644 --- a/patches/chromium/chore_provide_iswebcontentscreationoverridden_with_full_params.patch +++ b/patches/chromium/chore_provide_iswebcontentscreationoverridden_with_full_params.patch @@ -80,10 +80,10 @@ index 28cd699814f32a7a569d63936b9544567a66d9c4..fd461fa448d983481dc4c0c7d03b1945 } diff --git a/chrome/browser/ui/browser.cc b/chrome/browser/ui/browser.cc -index 92aa9eb2d38485a388cd6da519fa8feaf8ce0178..ad05a3c7fd5ac74d0af44fa55b83899e41c655e6 100644 +index 9477ad58da9934bc28bddd8bbaab9c7d5a5ff438..61dc5122a8ec925adada339f5c03773b49880591 100644 --- a/chrome/browser/ui/browser.cc +++ b/chrome/browser/ui/browser.cc -@@ -2117,12 +2117,11 @@ bool Browser::IsWebContentsCreationOverridden( +@@ -2121,12 +2121,11 @@ bool Browser::IsWebContentsCreationOverridden( content::SiteInstance* source_site_instance, content::mojom::WindowContainerType window_container_type, const GURL& opener_url, @@ -99,10 +99,10 @@ index 92aa9eb2d38485a388cd6da519fa8feaf8ce0178..ad05a3c7fd5ac74d0af44fa55b83899e WebContents* Browser::CreateCustomWebContents( diff --git a/chrome/browser/ui/browser.h b/chrome/browser/ui/browser.h -index dcd6b10b61f6afde1e8f46c75a83d7982766d8d9..7cf7c88602c9e1c8292cc8ba49150c663032a948 100644 +index 5e5cbb8a9c0916a558261bffa45d684feb0e0439..59b3d7d18cee6372aed19277a48445228d9c336b 100644 --- a/chrome/browser/ui/browser.h +++ b/chrome/browser/ui/browser.h -@@ -993,8 +993,7 @@ class Browser : public TabStripModelObserver, +@@ -994,8 +994,7 @@ class Browser : public TabStripModelObserver, content::SiteInstance* source_site_instance, content::mojom::WindowContainerType window_container_type, const GURL& opener_url, diff --git a/patches/chromium/desktop_media_list.patch b/patches/chromium/desktop_media_list.patch index 76e1cba8c7..2fe054f2aa 100644 --- a/patches/chromium/desktop_media_list.patch +++ b/patches/chromium/desktop_media_list.patch @@ -22,10 +22,10 @@ index 904c3a99c7d9ab7ffccf2de596950438b2225502..7a879b2f5332f98927c5e3858dd31c5d virtual int GetSourceCount() const = 0; virtual const Source& GetSource(int index) const = 0; diff --git a/chrome/browser/media/webrtc/desktop_media_list_base.cc b/chrome/browser/media/webrtc/desktop_media_list_base.cc -index 21c713b3b0f8efb17d704cd460ded4a5b15c52e4..d9943ec17ccec0220d4601ea8242ec3a9d8ba5be 100644 +index a1f5b5903d41befdd1f898ee276444edd0db8512..a4d9eaa18e9f7506332275c52bff6dad0639e2cf 100644 --- a/chrome/browser/media/webrtc/desktop_media_list_base.cc +++ b/chrome/browser/media/webrtc/desktop_media_list_base.cc -@@ -69,12 +69,12 @@ void DesktopMediaListBase::StartUpdating(DesktopMediaListObserver* observer) { +@@ -74,12 +74,12 @@ void DesktopMediaListBase::StartUpdating(DesktopMediaListObserver* observer) { Refresh(true); } @@ -82,10 +82,10 @@ index afc2cf89299315cca68b50196c2377a7d474883d..52bfd487d501ef895915800b9ee83a5b const Source& GetSource(int index) const override; DesktopMediaList::Type GetMediaListType() const override; diff --git a/chrome/browser/media/webrtc/native_desktop_media_list.cc b/chrome/browser/media/webrtc/native_desktop_media_list.cc -index 0ac5817b7e7839cae9caf0680fc128eb88ce95df..f03e7962617111d71c5e6f4ee684805f3da945de 100644 +index 49deff5a994658d7d4d0178573a869674aecc053..db2afc3cb111c83c01a44cc5aa0a8119a32a959e 100644 --- a/chrome/browser/media/webrtc/native_desktop_media_list.cc +++ b/chrome/browser/media/webrtc/native_desktop_media_list.cc -@@ -171,7 +171,7 @@ BOOL CALLBACK AllHwndCollector(HWND hwnd, LPARAM param) { +@@ -176,7 +176,7 @@ BOOL CALLBACK AllHwndCollector(HWND hwnd, LPARAM param) { #if BUILDFLAG(IS_MAC) BASE_FEATURE(kWindowCaptureMacV2, "WindowCaptureMacV2", @@ -94,7 +94,7 @@ index 0ac5817b7e7839cae9caf0680fc128eb88ce95df..f03e7962617111d71c5e6f4ee684805f #endif content::DesktopMediaID::Type ConvertToDesktopMediaIDType( -@@ -356,7 +356,7 @@ class NativeDesktopMediaList::Worker +@@ -361,7 +361,7 @@ class NativeDesktopMediaList::Worker base::WeakPtr<NativeDesktopMediaList> media_list_; DesktopMediaID::Type source_type_; @@ -103,7 +103,7 @@ index 0ac5817b7e7839cae9caf0680fc128eb88ce95df..f03e7962617111d71c5e6f4ee684805f const ThumbnailCapturer::FrameDeliveryMethod frame_delivery_method_; const bool add_current_process_windows_; -@@ -644,6 +644,12 @@ void NativeDesktopMediaList::Worker::RefreshNextThumbnail() { +@@ -649,6 +649,12 @@ void NativeDesktopMediaList::Worker::RefreshNextThumbnail() { FROM_HERE, base::BindOnce(&NativeDesktopMediaList::UpdateNativeThumbnailsFinished, media_list_)); @@ -116,7 +116,7 @@ index 0ac5817b7e7839cae9caf0680fc128eb88ce95df..f03e7962617111d71c5e6f4ee684805f } void NativeDesktopMediaList::Worker::OnCaptureResult( -@@ -1028,6 +1034,11 @@ void NativeDesktopMediaList::RefreshForVizFrameSinkWindows( +@@ -1033,6 +1039,11 @@ void NativeDesktopMediaList::RefreshForVizFrameSinkWindows( FROM_HERE, base::BindOnce(&Worker::RefreshThumbnails, base::Unretained(worker_.get()), std::move(native_ids), thumbnail_size_)); diff --git a/patches/chromium/disable_hidden.patch b/patches/chromium/disable_hidden.patch index 65eefeaf59..0d82147882 100644 --- a/patches/chromium/disable_hidden.patch +++ b/patches/chromium/disable_hidden.patch @@ -6,7 +6,7 @@ Subject: disable_hidden.patch Electron uses this to disable background throttling for hidden windows. diff --git a/content/browser/renderer_host/render_widget_host_impl.cc b/content/browser/renderer_host/render_widget_host_impl.cc -index daa7119d62f77f46b2e539a6eed99d204461dc32..872270420493edb219d724a412242b6a0db114af 100644 +index a3e64928c558f0959ff7aa3451f3898cf0d1fb18..389045f400ed0bc0af19047ad318f693a6006910 100644 --- a/content/browser/renderer_host/render_widget_host_impl.cc +++ b/content/browser/renderer_host/render_widget_host_impl.cc @@ -778,6 +778,9 @@ void RenderWidgetHostImpl::WasHidden() { @@ -20,10 +20,10 @@ index daa7119d62f77f46b2e539a6eed99d204461dc32..872270420493edb219d724a412242b6a blink::mojom::PointerLockResult::kWrongDocument); diff --git a/content/browser/renderer_host/render_widget_host_impl.h b/content/browser/renderer_host/render_widget_host_impl.h -index 6f4e44aba5c19fcc2865b070708ef310d6a78d18..b7daed50073b61bf9ceab2c001b52e32cff42bf7 100644 +index 42161abd764655cc753fffd8577a507955e72ce4..b222f105dbc13e726bbd70186a596dbb442c1aed 100644 --- a/content/browser/renderer_host/render_widget_host_impl.h +++ b/content/browser/renderer_host/render_widget_host_impl.h -@@ -1000,6 +1000,9 @@ class CONTENT_EXPORT RenderWidgetHostImpl +@@ -1001,6 +1001,9 @@ class CONTENT_EXPORT RenderWidgetHostImpl // Requests a commit and forced redraw in the renderer compositor. void ForceRedrawForTesting(); diff --git a/patches/chromium/feat_add_data_parameter_to_processsingleton.patch b/patches/chromium/feat_add_data_parameter_to_processsingleton.patch index a7b5f12e10..0b0f5bd234 100644 --- a/patches/chromium/feat_add_data_parameter_to_processsingleton.patch +++ b/patches/chromium/feat_add_data_parameter_to_processsingleton.patch @@ -63,10 +63,10 @@ index 31f5b160e4cd755cfb56a62b04261ee1bee80277..8dbc5ac458481d2f805f90101069f02a #if BUILDFLAG(IS_WIN) bool EscapeVirtualization(const base::FilePath& user_data_dir); diff --git a/chrome/browser/process_singleton_posix.cc b/chrome/browser/process_singleton_posix.cc -index 2205fa3ee2bd2611bad0594680a7cdee270f4f5e..b013b39c3278d539e4238fba1b143bac00c778f3 100644 +index f8cf2fb4ab66dae92b80c17cdda8b984fe4807c7..1a5d5323c0b37171b61f1fb2445dc18e1738f4ba 100644 --- a/chrome/browser/process_singleton_posix.cc +++ b/chrome/browser/process_singleton_posix.cc -@@ -610,6 +610,7 @@ class ProcessSingleton::LinuxWatcher +@@ -615,6 +615,7 @@ class ProcessSingleton::LinuxWatcher // |reader| is for sending back ACK message. void HandleMessage(const std::string& current_dir, const std::vector<std::string>& argv, @@ -74,7 +74,7 @@ index 2205fa3ee2bd2611bad0594680a7cdee270f4f5e..b013b39c3278d539e4238fba1b143bac SocketReader* reader); // Called when the ProcessSingleton that owns this class is about to be -@@ -669,13 +670,17 @@ void ProcessSingleton::LinuxWatcher::StartListening(int socket) { +@@ -674,13 +675,17 @@ void ProcessSingleton::LinuxWatcher::StartListening(int socket) { } void ProcessSingleton::LinuxWatcher::HandleMessage( @@ -94,7 +94,7 @@ index 2205fa3ee2bd2611bad0594680a7cdee270f4f5e..b013b39c3278d539e4238fba1b143bac // Send back "ACK" message to prevent the client process from starting up. reader->FinishWithACK(kACKToken, std::size(kACKToken) - 1); } else { -@@ -723,7 +728,8 @@ void ProcessSingleton::LinuxWatcher::SocketReader:: +@@ -728,7 +733,8 @@ void ProcessSingleton::LinuxWatcher::SocketReader:: } } @@ -104,7 +104,7 @@ index 2205fa3ee2bd2611bad0594680a7cdee270f4f5e..b013b39c3278d539e4238fba1b143bac const size_t kMinMessageLength = std::size(kStartToken) + 4; if (bytes_read_ < kMinMessageLength) { buf_[bytes_read_] = 0; -@@ -753,10 +759,28 @@ void ProcessSingleton::LinuxWatcher::SocketReader:: +@@ -758,10 +764,28 @@ void ProcessSingleton::LinuxWatcher::SocketReader:: tokens.erase(tokens.begin()); tokens.erase(tokens.begin()); @@ -134,7 +134,7 @@ index 2205fa3ee2bd2611bad0594680a7cdee270f4f5e..b013b39c3278d539e4238fba1b143bac fd_watch_controller_.reset(); // LinuxWatcher::HandleMessage() is in charge of destroying this SocketReader -@@ -785,8 +809,10 @@ void ProcessSingleton::LinuxWatcher::SocketReader::FinishWithACK( +@@ -790,8 +814,10 @@ void ProcessSingleton::LinuxWatcher::SocketReader::FinishWithACK( // ProcessSingleton::ProcessSingleton( const base::FilePath& user_data_dir, @@ -145,7 +145,7 @@ index 2205fa3ee2bd2611bad0594680a7cdee270f4f5e..b013b39c3278d539e4238fba1b143bac current_pid_(base::GetCurrentProcId()) { socket_path_ = user_data_dir.Append(chrome::kSingletonSocketFilename); lock_path_ = user_data_dir.Append(chrome::kSingletonLockFilename); -@@ -907,7 +933,8 @@ ProcessSingleton::NotifyResult ProcessSingleton::NotifyOtherProcessWithTimeout( +@@ -912,7 +938,8 @@ ProcessSingleton::NotifyResult ProcessSingleton::NotifyOtherProcessWithTimeout( sizeof(socket_timeout)); // Found another process, prepare our command line @@ -155,7 +155,7 @@ index 2205fa3ee2bd2611bad0594680a7cdee270f4f5e..b013b39c3278d539e4238fba1b143bac std::string to_send(kStartToken); to_send.push_back(kTokenDelimiter); -@@ -917,11 +944,21 @@ ProcessSingleton::NotifyResult ProcessSingleton::NotifyOtherProcessWithTimeout( +@@ -922,11 +949,21 @@ ProcessSingleton::NotifyResult ProcessSingleton::NotifyOtherProcessWithTimeout( to_send.append(current_dir.value()); const std::vector<std::string>& argv = cmd_line.argv(); diff --git a/patches/chromium/feat_enable_offscreen_rendering_with_viz_compositor.patch b/patches/chromium/feat_enable_offscreen_rendering_with_viz_compositor.patch index 61ecbc5991..70a853db25 100644 --- a/patches/chromium/feat_enable_offscreen_rendering_with_viz_compositor.patch +++ b/patches/chromium/feat_enable_offscreen_rendering_with_viz_compositor.patch @@ -90,10 +90,10 @@ index 8af69cac78b7488d28f1f05ccb174793fe5148cd..9f74e511c263d147b5fbe81fe100d217 private: const HWND hwnd_; diff --git a/components/viz/service/BUILD.gn b/components/viz/service/BUILD.gn -index 002b83ff8b81e485739658c8ae236b06b8d36c4d..256266d6e6c8bcd052fb075e2b9f83530174c057 100644 +index 1c5e059cee6593f61270559a58cee7450b52ab8c..d4ac7f62b59c1948b2ec341109d27422ca8dda04 100644 --- a/components/viz/service/BUILD.gn +++ b/components/viz/service/BUILD.gn -@@ -173,6 +173,8 @@ viz_component("service") { +@@ -172,6 +172,8 @@ viz_component("service") { "display_embedder/skia_output_surface_impl_on_gpu_debug_capture.h", "display_embedder/skia_render_copy_results.cc", "display_embedder/skia_render_copy_results.h", diff --git a/patches/chromium/fix_add_support_for_skipping_first_2_no-op_refreshes_in_thumb_cap.patch b/patches/chromium/fix_add_support_for_skipping_first_2_no-op_refreshes_in_thumb_cap.patch index f99318ef9f..d5592353a4 100644 --- a/patches/chromium/fix_add_support_for_skipping_first_2_no-op_refreshes_in_thumb_cap.patch +++ b/patches/chromium/fix_add_support_for_skipping_first_2_no-op_refreshes_in_thumb_cap.patch @@ -27,10 +27,10 @@ index 7a879b2f5332f98927c5e3858dd31c5de169e5ce..75191362088d2d875330fb2044a4682b #endif // CHROME_BROWSER_MEDIA_WEBRTC_DESKTOP_MEDIA_LIST_H_ diff --git a/chrome/browser/media/webrtc/desktop_media_list_base.cc b/chrome/browser/media/webrtc/desktop_media_list_base.cc -index d9943ec17ccec0220d4601ea8242ec3a9d8ba5be..5d9029538c690c3d904bd6b39949387931997fdc 100644 +index a4d9eaa18e9f7506332275c52bff6dad0639e2cf..54492210154e3b02e8640cd63b7ec428e81c85d7 100644 --- a/chrome/browser/media/webrtc/desktop_media_list_base.cc +++ b/chrome/browser/media/webrtc/desktop_media_list_base.cc -@@ -230,7 +230,11 @@ uint32_t DesktopMediaListBase::GetImageHash(const gfx::Image& image) { +@@ -235,7 +235,11 @@ uint32_t DesktopMediaListBase::GetImageHash(const gfx::Image& image) { void DesktopMediaListBase::OnRefreshComplete() { DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK(refresh_callback_); diff --git a/patches/chromium/fix_crash_loading_non-standard_schemes_in_iframes.patch b/patches/chromium/fix_crash_loading_non-standard_schemes_in_iframes.patch index ea1c6c7206..cdef9540a8 100644 --- a/patches/chromium/fix_crash_loading_non-standard_schemes_in_iframes.patch +++ b/patches/chromium/fix_crash_loading_non-standard_schemes_in_iframes.patch @@ -23,10 +23,10 @@ Upstream bug https://bugs.chromium.org/p/chromium/issues/detail?id=1081397. Upstreamed at https://chromium-review.googlesource.com/c/chromium/src/+/3856266. diff --git a/content/browser/renderer_host/navigation_request.cc b/content/browser/renderer_host/navigation_request.cc -index fae6cb2e6eeac865825bfcbc79f0fb96aa66d266..1ebc636d40543183d06f8623ae0698c4331a6609 100644 +index 70baa92dfb7782a9b5850f8fd246b0aa0ca46de6..1f4b8f68e2fc974cd8ceafb91916dd994349c69e 100644 --- a/content/browser/renderer_host/navigation_request.cc +++ b/content/browser/renderer_host/navigation_request.cc -@@ -10704,6 +10704,12 @@ NavigationRequest::GetOriginForURLLoaderFactoryUncheckedWithDebugInfo() { +@@ -10729,6 +10729,12 @@ NavigationRequest::GetOriginForURLLoaderFactoryUncheckedWithDebugInfo() { } } diff --git a/patches/chromium/fix_restore_original_resize_performance_on_macos.patch b/patches/chromium/fix_restore_original_resize_performance_on_macos.patch index 4d0b59a53b..327636bb0b 100644 --- a/patches/chromium/fix_restore_original_resize_performance_on_macos.patch +++ b/patches/chromium/fix_restore_original_resize_performance_on_macos.patch @@ -11,10 +11,10 @@ This patch should be upstreamed as a conditional revert of the logic in desktop vs mobile runtimes. i.e. restore the old logic only on desktop platforms diff --git a/content/browser/renderer_host/render_widget_host_impl.cc b/content/browser/renderer_host/render_widget_host_impl.cc -index ad8d5236fe2b9f55462445b2fc332a27e588a8e0..f392a2d3d4066deef9ea22a2affe098d95f64111 100644 +index a06a04c3e1c40370fa04b7bc34f0a3adc9832169..e3f5da2087616300d4765c23f7b8bc190deca4df 100644 --- a/content/browser/renderer_host/render_widget_host_impl.cc +++ b/content/browser/renderer_host/render_widget_host_impl.cc -@@ -2021,9 +2021,8 @@ RenderWidgetHostImpl::GetWidgetInputHandler() { +@@ -2026,9 +2026,8 @@ RenderWidgetHostImpl::GetWidgetInputHandler() { void RenderWidgetHostImpl::NotifyScreenInfoChanged() { // The resize message (which may not happen immediately) will carry with it // the screen info as well as the new size (if the screen has changed scale diff --git a/patches/chromium/fix_return_v8_value_from_localframe_requestexecutescript.patch b/patches/chromium/fix_return_v8_value_from_localframe_requestexecutescript.patch index 0504f13940..66363010f6 100644 --- a/patches/chromium/fix_return_v8_value_from_localframe_requestexecutescript.patch +++ b/patches/chromium/fix_return_v8_value_from_localframe_requestexecutescript.patch @@ -216,7 +216,7 @@ index db1cc198dfc40ce359bad4157a4aad396e1be1a0..424fa3415a9f7d44a8422ecf0eb3670b mojom::blink::WantResultOption::kWantResult, wait_for_promise); } diff --git a/third_party/blink/renderer/core/frame/web_local_frame_impl.cc b/third_party/blink/renderer/core/frame/web_local_frame_impl.cc -index e9b2bddc2bf046baa94273d9785087c9235bd7d1..56d5140360395c1bccb03136334fd95b3a5d6686 100644 +index 2079ffada65df5773909f25cb0c6645a3f6b3aab..e1dea864e10a106993d6d713f9b5db06c174adf0 100644 --- a/third_party/blink/renderer/core/frame/web_local_frame_impl.cc +++ b/third_party/blink/renderer/core/frame/web_local_frame_impl.cc @@ -1095,14 +1095,15 @@ void WebLocalFrameImpl::RequestExecuteScript( 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 a0824563f0..24c61512fb 100644 --- a/patches/chromium/mas_avoid_private_macos_api_usage.patch.patch +++ b/patches/chromium/mas_avoid_private_macos_api_usage.patch.patch @@ -35,7 +35,7 @@ system font by checking if it's kCTFontPriorityAttribute is set to system priority. diff --git a/base/BUILD.gn b/base/BUILD.gn -index dbaf22d68f67cb227a5fc2c774fd582af7715dcc..406bc05f8f4b368f18c6e8264fa5ad6e70d6fe1e 100644 +index f23f880efa562ed992eb9dc92946437b2151d1f1..848f860907f118a8f6cea188601e0873397265cd 100644 --- a/base/BUILD.gn +++ b/base/BUILD.gn @@ -1050,6 +1050,7 @@ component("base") { @@ -379,10 +379,10 @@ index b3c087eda0561d94d205ef0cbbb341a7e2a34638..035202378209e32e6f7c630140367cda // Beware: This view was briefly removed (in favor of a bare CALayer) in // https://crrev.com/c/1236675. The ordering of unassociated layers relative diff --git a/components/viz/service/BUILD.gn b/components/viz/service/BUILD.gn -index b5d3072f31aa3a07f5e650c3e0299c4e26e8113a..002b83ff8b81e485739658c8ae236b06b8d36c4d 100644 +index 5162f0de437618af7ce9de59209e090ac56881b9..1c5e059cee6593f61270559a58cee7450b52ab8c 100644 --- a/components/viz/service/BUILD.gn +++ b/components/viz/service/BUILD.gn -@@ -368,6 +368,7 @@ viz_component("service") { +@@ -367,6 +367,7 @@ viz_component("service") { "frame_sinks/external_begin_frame_source_mac.h", ] } @@ -390,7 +390,7 @@ index b5d3072f31aa3a07f5e650c3e0299c4e26e8113a..002b83ff8b81e485739658c8ae236b06 } if (is_android || use_ozone) { -@@ -641,6 +642,7 @@ viz_source_set("unit_tests") { +@@ -639,6 +640,7 @@ viz_source_set("unit_tests") { "display_embedder/software_output_device_mac_unittest.mm", ] frameworks = [ "IOSurface.framework" ] diff --git a/patches/chromium/notification_provenance.patch b/patches/chromium/notification_provenance.patch index 41d8414721..6a63377324 100644 --- a/patches/chromium/notification_provenance.patch +++ b/patches/chromium/notification_provenance.patch @@ -133,7 +133,7 @@ index 46b071609e56e8602b04d1cd9f5f4ebd7e4f4ae1..6092383e0f8f1c0d829a8ef8af53a786 const GURL& document_url, const WeakDocumentPtr& weak_document_ptr, diff --git a/content/browser/renderer_host/render_process_host_impl.cc b/content/browser/renderer_host/render_process_host_impl.cc -index dd2c6144fbc99a572282bdb8e0b5f0d9a169f308..bd77d2cf5018c453a753b2f160a382821c84ab78 100644 +index 7ac8e5e171c277a6452009ffadf09f5a685c584b..46b205e47314627bcc0ffd03a28a29c103e523ab 100644 --- a/content/browser/renderer_host/render_process_host_impl.cc +++ b/content/browser/renderer_host/render_process_host_impl.cc @@ -1975,7 +1975,7 @@ void RenderProcessHostImpl::CreateNotificationService( diff --git a/patches/chromium/pepper_plugin_support.patch b/patches/chromium/pepper_plugin_support.patch index 243b70cb25..d63a689988 100644 --- a/patches/chromium/pepper_plugin_support.patch +++ b/patches/chromium/pepper_plugin_support.patch @@ -7,10 +7,10 @@ This tweaks Chrome's pepper flash and PDF plugin support to make it usable from Electron. diff --git a/chrome/browser/renderer_host/pepper/pepper_isolated_file_system_message_filter.cc b/chrome/browser/renderer_host/pepper/pepper_isolated_file_system_message_filter.cc -index 6c0f86dc6f588891f9e4b2ff00f39727fd6e03ef..99b8a4d6fe607ce9b502985c971ce3888aee49b5 100644 +index 46513bf122445f822917a1a80d5d9079f288e1b4..7becf2e72ca677335dbd241fa0fef30768a3fc28 100644 --- a/chrome/browser/renderer_host/pepper/pepper_isolated_file_system_message_filter.cc +++ b/chrome/browser/renderer_host/pepper/pepper_isolated_file_system_message_filter.cc -@@ -7,17 +7,21 @@ +@@ -12,17 +12,21 @@ #include <stddef.h> #include "base/task/sequenced_task_runner.h" @@ -32,7 +32,7 @@ index 6c0f86dc6f588891f9e4b2ff00f39727fd6e03ef..99b8a4d6fe607ce9b502985c971ce388 #include "ppapi/c/pp_errors.h" #include "ppapi/host/dispatch_host_message.h" #include "ppapi/host/host_message_context.h" -@@ -26,12 +30,11 @@ +@@ -31,12 +35,11 @@ #include "ppapi/shared_impl/file_system_util.h" #include "storage/browser/file_system/isolated_context.h" @@ -46,7 +46,7 @@ index 6c0f86dc6f588891f9e4b2ff00f39727fd6e03ef..99b8a4d6fe607ce9b502985c971ce388 namespace { -@@ -41,6 +44,7 @@ const char* kPredefinedAllowedCrxFsOrigins[] = { +@@ -46,6 +49,7 @@ const char* kPredefinedAllowedCrxFsOrigins[] = { }; } // namespace @@ -54,7 +54,7 @@ index 6c0f86dc6f588891f9e4b2ff00f39727fd6e03ef..99b8a4d6fe607ce9b502985c971ce388 // static PepperIsolatedFileSystemMessageFilter* -@@ -64,11 +68,16 @@ PepperIsolatedFileSystemMessageFilter::PepperIsolatedFileSystemMessageFilter( +@@ -69,11 +73,16 @@ PepperIsolatedFileSystemMessageFilter::PepperIsolatedFileSystemMessageFilter( const base::FilePath& profile_directory, const GURL& document_url, ppapi::host::PpapiHost* ppapi_host) @@ -71,7 +71,7 @@ index 6c0f86dc6f588891f9e4b2ff00f39727fd6e03ef..99b8a4d6fe607ce9b502985c971ce388 } PepperIsolatedFileSystemMessageFilter:: -@@ -93,6 +102,7 @@ int32_t PepperIsolatedFileSystemMessageFilter::OnResourceMessageReceived( +@@ -98,6 +107,7 @@ int32_t PepperIsolatedFileSystemMessageFilter::OnResourceMessageReceived( return PP_ERROR_FAILED; } @@ -79,7 +79,7 @@ index 6c0f86dc6f588891f9e4b2ff00f39727fd6e03ef..99b8a4d6fe607ce9b502985c971ce388 Profile* PepperIsolatedFileSystemMessageFilter::GetProfile() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); ProfileManager* profile_manager = g_browser_process->profile_manager(); -@@ -117,6 +127,7 @@ PepperIsolatedFileSystemMessageFilter::CreateCrxFileSystem(Profile* profile) { +@@ -122,6 +132,7 @@ PepperIsolatedFileSystemMessageFilter::CreateCrxFileSystem(Profile* profile) { return storage::IsolatedContext::ScopedFSHandle(); #endif } @@ -87,7 +87,7 @@ index 6c0f86dc6f588891f9e4b2ff00f39727fd6e03ef..99b8a4d6fe607ce9b502985c971ce388 int32_t PepperIsolatedFileSystemMessageFilter::OnOpenFileSystem( ppapi::host::HostMessageContext* context, -@@ -125,7 +136,7 @@ int32_t PepperIsolatedFileSystemMessageFilter::OnOpenFileSystem( +@@ -130,7 +141,7 @@ int32_t PepperIsolatedFileSystemMessageFilter::OnOpenFileSystem( case PP_ISOLATEDFILESYSTEMTYPE_PRIVATE_INVALID: break; case PP_ISOLATEDFILESYSTEMTYPE_PRIVATE_CRX: @@ -96,7 +96,7 @@ index 6c0f86dc6f588891f9e4b2ff00f39727fd6e03ef..99b8a4d6fe607ce9b502985c971ce388 } NOTREACHED_IN_MIGRATION(); context->reply_msg = -@@ -133,6 +144,7 @@ int32_t PepperIsolatedFileSystemMessageFilter::OnOpenFileSystem( +@@ -138,6 +149,7 @@ int32_t PepperIsolatedFileSystemMessageFilter::OnOpenFileSystem( return PP_ERROR_FAILED; } @@ -104,7 +104,7 @@ index 6c0f86dc6f588891f9e4b2ff00f39727fd6e03ef..99b8a4d6fe607ce9b502985c971ce388 int32_t PepperIsolatedFileSystemMessageFilter::OpenCrxFileSystem( ppapi::host::HostMessageContext* context) { #if BUILDFLAG(ENABLE_EXTENSIONS) -@@ -173,3 +185,4 @@ int32_t PepperIsolatedFileSystemMessageFilter::OpenCrxFileSystem( +@@ -178,3 +190,4 @@ int32_t PepperIsolatedFileSystemMessageFilter::OpenCrxFileSystem( return PP_ERROR_NOTSUPPORTED; #endif } diff --git a/patches/chromium/process_singleton.patch b/patches/chromium/process_singleton.patch index 907ab3e5cb..0034bebda6 100644 --- a/patches/chromium/process_singleton.patch +++ b/patches/chromium/process_singleton.patch @@ -51,10 +51,10 @@ index 23a8257aa2a0a671cf7af35aff9906891091606d..31f5b160e4cd755cfb56a62b04261ee1 base::win::MessageWindow window_; // The message-only window. bool is_virtualized_; // Stuck inside Microsoft Softricity VM environment. diff --git a/chrome/browser/process_singleton_posix.cc b/chrome/browser/process_singleton_posix.cc -index c3cf6e083105159fbb815f3754423d276d416036..2205fa3ee2bd2611bad0594680a7cdee270f4f5e 100644 +index 14b9c99e81e0999d1a2e25557e6a731ec88f6a22..f8cf2fb4ab66dae92b80c17cdda8b984fe4807c7 100644 --- a/chrome/browser/process_singleton_posix.cc +++ b/chrome/browser/process_singleton_posix.cc -@@ -54,6 +54,7 @@ +@@ -59,6 +59,7 @@ #include <memory> #include <set> #include <string> @@ -62,7 +62,7 @@ index c3cf6e083105159fbb815f3754423d276d416036..2205fa3ee2bd2611bad0594680a7cdee #include <type_traits> #include "base/base_paths.h" -@@ -81,6 +82,7 @@ +@@ -86,6 +87,7 @@ #include "base/strings/utf_string_conversions.h" #include "base/task/sequenced_task_runner_helpers.h" #include "base/task/single_thread_task_runner.h" @@ -70,7 +70,7 @@ index c3cf6e083105159fbb815f3754423d276d416036..2205fa3ee2bd2611bad0594680a7cdee #include "base/threading/platform_thread.h" #include "base/time/time.h" #include "base/timer/timer.h" -@@ -97,7 +99,7 @@ +@@ -102,7 +104,7 @@ #include "ui/base/l10n/l10n_util.h" #include "ui/base/resource/scoped_startup_resource_bundle.h" @@ -79,7 +79,7 @@ index c3cf6e083105159fbb815f3754423d276d416036..2205fa3ee2bd2611bad0594680a7cdee #include "chrome/browser/ui/process_singleton_dialog_linux.h" #endif -@@ -343,6 +345,8 @@ bool SymlinkPath(const base::FilePath& target, const base::FilePath& path) { +@@ -348,6 +350,8 @@ bool SymlinkPath(const base::FilePath& target, const base::FilePath& path) { bool DisplayProfileInUseError(const base::FilePath& lock_path, const std::string& hostname, int pid) { @@ -88,7 +88,7 @@ index c3cf6e083105159fbb815f3754423d276d416036..2205fa3ee2bd2611bad0594680a7cdee // Ensure there is an instance of ResourceBundle that is initialized for // localized string resource accesses. ui::ScopedStartupResourceBundle ensure_startup_resource_bundle; -@@ -366,6 +370,7 @@ bool DisplayProfileInUseError(const base::FilePath& lock_path, +@@ -371,6 +375,7 @@ bool DisplayProfileInUseError(const base::FilePath& lock_path, NOTREACHED_IN_MIGRATION(); return false; @@ -96,7 +96,7 @@ index c3cf6e083105159fbb815f3754423d276d416036..2205fa3ee2bd2611bad0594680a7cdee } bool IsChromeProcess(pid_t pid) { -@@ -378,6 +383,21 @@ bool IsChromeProcess(pid_t pid) { +@@ -383,6 +388,21 @@ bool IsChromeProcess(pid_t pid) { base::FilePath(chrome::kBrowserProcessExecutableName)); } @@ -118,7 +118,7 @@ index c3cf6e083105159fbb815f3754423d276d416036..2205fa3ee2bd2611bad0594680a7cdee // A helper class to hold onto a socket. class ScopedSocket { public: -@@ -781,6 +801,10 @@ ProcessSingleton::~ProcessSingleton() { +@@ -786,6 +806,10 @@ ProcessSingleton::~ProcessSingleton() { if (watcher_) { watcher_->OnEminentProcessSingletonDestruction(); } @@ -129,7 +129,7 @@ index c3cf6e083105159fbb815f3754423d276d416036..2205fa3ee2bd2611bad0594680a7cdee } ProcessSingleton::NotifyResult ProcessSingleton::NotifyOtherProcess() { -@@ -1048,11 +1072,32 @@ bool ProcessSingleton::Create() { +@@ -1053,11 +1077,32 @@ bool ProcessSingleton::Create() { // Create the socket file somewhere in /tmp which is usually mounted as a // normal filesystem. Some network filesystems (notably AFS) are screwy and // do not support Unix domain sockets. diff --git a/patches/chromium/refactor_expose_cursor_changes_to_the_webcontentsobserver.patch b/patches/chromium/refactor_expose_cursor_changes_to_the_webcontentsobserver.patch index 118b9aeee6..c40abaec79 100644 --- a/patches/chromium/refactor_expose_cursor_changes_to_the_webcontentsobserver.patch +++ b/patches/chromium/refactor_expose_cursor_changes_to_the_webcontentsobserver.patch @@ -30,10 +30,10 @@ index eaca11c1b16ee0befe8f5bfd3735a582a63cbd81..9f042cd993e46993826634772714c4f2 // RenderWidgetHost on the primary main frame, and false otherwise. virtual bool IsWidgetForPrimaryMainFrame(RenderWidgetHostImpl*); diff --git a/content/browser/renderer_host/render_widget_host_impl.cc b/content/browser/renderer_host/render_widget_host_impl.cc -index 872270420493edb219d724a412242b6a0db114af..ad8d5236fe2b9f55462445b2fc332a27e588a8e0 100644 +index 389045f400ed0bc0af19047ad318f693a6006910..a06a04c3e1c40370fa04b7bc34f0a3adc9832169 100644 --- a/content/browser/renderer_host/render_widget_host_impl.cc +++ b/content/browser/renderer_host/render_widget_host_impl.cc -@@ -1955,6 +1955,9 @@ void RenderWidgetHostImpl::SetCursor(const ui::Cursor& cursor) { +@@ -1960,6 +1960,9 @@ void RenderWidgetHostImpl::SetCursor(const ui::Cursor& cursor) { if (view_) { view_->UpdateCursor(cursor); } diff --git a/patches/chromium/refactor_expose_hostimportmoduledynamically_and.patch b/patches/chromium/refactor_expose_hostimportmoduledynamically_and.patch index f3247884ab..8e3aaa9694 100644 --- a/patches/chromium/refactor_expose_hostimportmoduledynamically_and.patch +++ b/patches/chromium/refactor_expose_hostimportmoduledynamically_and.patch @@ -7,7 +7,7 @@ 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 c17479e167de17b4ed02be7934a7c3ac7a020ed1..a1d5426f62f24395a7304dce7b040755e7f7b941 100644 +index c7254525d2940f6f2603d208e26b2f22f75fe6f3..36f6e131ecb135d011b271d2cdbaebf5faeb883b 100644 --- a/third_party/blink/renderer/bindings/core/v8/v8_initializer.cc +++ b/third_party/blink/renderer/bindings/core/v8/v8_initializer.cc @@ -609,7 +609,9 @@ bool WasmJSPromiseIntegrationEnabledCallback(v8::Local<v8::Context> context) { diff --git a/patches/chromium/resource_file_conflict.patch b/patches/chromium/resource_file_conflict.patch index c4edc8649c..19f8c28e95 100644 --- a/patches/chromium/resource_file_conflict.patch +++ b/patches/chromium/resource_file_conflict.patch @@ -52,10 +52,10 @@ Some alternatives to this patch: None of these options seems like a substantial maintainability win over this patch to me (@nornagon). diff --git a/chrome/BUILD.gn b/chrome/BUILD.gn -index a8c87a5d595af314ff9592b5795346b6859ff60b..7ef8050aa89bb4132680c6d00d5d6ab3ecfdc713 100644 +index 373076ca15f7bc00f74990716c78a37e902c84b2..74c16760fbd0ec88d8cd4e92a6fc9a68c0a3ebe3 100644 --- a/chrome/BUILD.gn +++ b/chrome/BUILD.gn -@@ -1567,7 +1567,7 @@ if (is_chrome_branded && !is_android) { +@@ -1571,7 +1571,7 @@ if (is_chrome_branded && !is_android) { } } @@ -64,7 +64,7 @@ index a8c87a5d595af314ff9592b5795346b6859ff60b..7ef8050aa89bb4132680c6d00d5d6ab3 chrome_paks("packed_resources") { if (is_mac) { output_dir = "$root_gen_dir/repack" -@@ -1606,6 +1606,12 @@ if (!is_android) { +@@ -1610,6 +1610,12 @@ if (!is_android) { } } diff --git a/patches/chromium/support_mixed_sandbox_with_zygote.patch b/patches/chromium/support_mixed_sandbox_with_zygote.patch index fcb086678d..466fd4e5be 100644 --- a/patches/chromium/support_mixed_sandbox_with_zygote.patch +++ b/patches/chromium/support_mixed_sandbox_with_zygote.patch @@ -22,7 +22,7 @@ However, the patch would need to be reviewed by the security team, as it does touch a security-sensitive class. diff --git a/content/browser/renderer_host/render_process_host_impl.cc b/content/browser/renderer_host/render_process_host_impl.cc -index bd77d2cf5018c453a753b2f160a382821c84ab78..c916c631535cb428c31436bc54bfa2dff7cd8c71 100644 +index 46b205e47314627bcc0ffd03a28a29c103e523ab..0e82358006724f6eb2c12a400a877331fdbb5988 100644 --- a/content/browser/renderer_host/render_process_host_impl.cc +++ b/content/browser/renderer_host/render_process_host_impl.cc @@ -1612,9 +1612,15 @@ bool RenderProcessHostImpl::Init() { diff --git a/patches/devtools_frontend/chore_expose_ui_to_allow_electron_to_set_dock_side.patch b/patches/devtools_frontend/chore_expose_ui_to_allow_electron_to_set_dock_side.patch index f796159510..639e99b08c 100644 --- a/patches/devtools_frontend/chore_expose_ui_to_allow_electron_to_set_dock_side.patch +++ b/patches/devtools_frontend/chore_expose_ui_to_allow_electron_to_set_dock_side.patch @@ -10,10 +10,10 @@ to handle this without patching, but this is fairly clean for now and no longer patching legacy devtools code. diff --git a/front_end/entrypoints/main/MainImpl.ts b/front_end/entrypoints/main/MainImpl.ts -index fbded4d8e5cbe4b7134a1438799ee46800198113..bf713c9f4f168175e9de9e9c2a68b7df9c3eba06 100644 +index 5f03f3197a5302e76a396ce27dd7f95384a96250..3ae373b68b198d28d92b2227be07956e0673b504 100644 --- a/front_end/entrypoints/main/MainImpl.ts +++ b/front_end/entrypoints/main/MainImpl.ts -@@ -741,6 +741,8 @@ export class MainImpl { +@@ -746,6 +746,8 @@ export class MainImpl { globalThis.Main = globalThis.Main || {}; // @ts-ignore Exported for Tests.js globalThis.Main.Main = MainImpl; diff --git a/patches/v8/fix_disable_scope_reuse_associated_dchecks.patch b/patches/v8/fix_disable_scope_reuse_associated_dchecks.patch index bc107d1680..8aa02c517a 100644 --- a/patches/v8/fix_disable_scope_reuse_associated_dchecks.patch +++ b/patches/v8/fix_disable_scope_reuse_associated_dchecks.patch @@ -42,7 +42,7 @@ index 63595b84b71957a81c50d054b8db573be9d9d981..f23453f86cb0786d59328177be1a9bc6 #endif if (!scope->is_function_scope() || diff --git a/src/flags/flag-definitions.h b/src/flags/flag-definitions.h -index df04f66444cb4aee60244a19e38775033efe7fe8..b9414b7e830b4b1a102ed2b277a4aa8ab3cbc351 100644 +index 41dfc4f9ed0e17b3e808922c65167551a937d3df..5547c52e34d91fa2dcf122c3e1043829f345658b 100644 --- a/src/flags/flag-definitions.h +++ b/src/flags/flag-definitions.h @@ -979,7 +979,12 @@ DEFINE_BOOL(trace_track_allocation_sites, false,
chore
c57ce31e84120efc74125fd084931092c9a4d228
Alice Zhao
2024-03-26 21:49:11
test: fix flaky tests in `webContents.navigationHistory` (#41705) test: fix flaky tests by replacing real urls with data urls
diff --git a/spec/api-web-contents-spec.ts b/spec/api-web-contents-spec.ts index 7d53beaddc..71ee26eddd 100644 --- a/spec/api-web-contents-spec.ts +++ b/spec/api-web-contents-spec.ts @@ -548,6 +548,9 @@ describe('webContents module', () => { describe('navigationHistory', () => { let w: BrowserWindow; + const urlPage1 = 'data:text/html,<html><head><script>document.title = "Page 1";</script></head><body></body></html>'; + const urlPage2 = 'data:text/html,<html><head><script>document.title = "Page 2";</script></head><body></body></html>'; + const urlPage3 = 'data:text/html,<html><head><script>document.title = "Page 3";</script></head><body></body></html>'; beforeEach(async () => { w = new BrowserWindow({ show: false }); @@ -559,25 +562,19 @@ describe('webContents module', () => { expect(result).to.deep.equal({ url: '', title: '' }); }); it('should fetch navigation entry given a valid index', async () => { - await w.loadURL('https://www.google.com'); - w.webContents.on('did-finish-load', async () => { - const result = w.webContents.navigationHistory.getEntryAtIndex(0); - expect(result).to.deep.equal({ url: 'https://www.google.com/', title: 'Google' }); - }); + await w.loadURL(urlPage1); + const result = w.webContents.navigationHistory.getEntryAtIndex(0); + expect(result).to.deep.equal({ url: urlPage1, title: 'Page 1' }); }); it('should return null given an invalid index larger than history length', async () => { - await w.loadURL('https://www.google.com'); - w.webContents.on('did-finish-load', async () => { - const result = w.webContents.navigationHistory.getEntryAtIndex(5); - expect(result).to.be.null(); - }); + await w.loadURL(urlPage1); + const result = w.webContents.navigationHistory.getEntryAtIndex(5); + expect(result).to.be.null(); }); it('should return null given an invalid negative index', async () => { - await w.loadURL('https://www.google.com'); - w.webContents.on('did-finish-load', async () => { - const result = w.webContents.navigationHistory.getEntryAtIndex(-1); - expect(result).to.be.null(); - }); + await w.loadURL(urlPage1); + const result = w.webContents.navigationHistory.getEntryAtIndex(-1); + expect(result).to.be.null(); }); }); @@ -590,13 +587,9 @@ describe('webContents module', () => { }); it('should return valid active index after a multiple page visits', async () => { - const loadPromise = once(w.webContents, 'did-finish-load'); - await w.loadURL('https://www.github.com'); - await loadPromise; - await w.loadURL('https://www.google.com'); - await loadPromise; - await w.loadURL('about:blank'); - await loadPromise; + await w.loadURL(urlPage1); + await w.loadURL(urlPage2); + await w.loadURL(urlPage3); expect(w.webContents.navigationHistory.getActiveIndex()).to.equal(2); }); @@ -608,20 +601,14 @@ describe('webContents module', () => { describe('navigationHistory.length() API', () => { it('should return valid history length after a single page visit', async () => { - await w.loadURL('https://www.google.com'); - w.webContents.on('did-finish-load', async () => { - expect(w.webContents.navigationHistory.length()).to.equal(1); - }); + await w.loadURL(urlPage1); + expect(w.webContents.navigationHistory.length()).to.equal(1); }); it('should return valid history length after a multiple page visits', async () => { - const loadPromise = once(w.webContents, 'did-finish-load'); - await w.loadURL('https://www.github.com'); - await loadPromise; - await w.loadURL('https://www.google.com'); - await loadPromise; - await w.loadURL('about:blank'); - await loadPromise; + await w.loadURL(urlPage1); + await w.loadURL(urlPage2); + await w.loadURL(urlPage3); expect(w.webContents.navigationHistory.length()).to.equal(3); });
test
a3448376a1f9d3a381e03277fddf6c46b76c9104
Charles Kerr
2023-06-09 15:28:11
refactor: api web contents ownership (#38695) * refactor: aggregate api::WebContents::exclusive_access_manager_ directly * refactor: make WebContents::devtools_file_system_indexer_ scoped_refptr const * refactor: make WebContents::file_task_runner_ scoped_refptr const * refactor: make WebContents::print_task_runner_ scoped_refptr const
diff --git a/shell/browser/api/electron_api_web_contents.cc b/shell/browser/api/electron_api_web_contents.cc index 0980148cae..4a2e08a080 100644 --- a/shell/browser/api/electron_api_web_contents.cc +++ b/shell/browser/api/electron_api_web_contents.cc @@ -783,12 +783,7 @@ WebContents::WebContents(v8::Isolate* isolate, content::WebContents* web_contents) : content::WebContentsObserver(web_contents), type_(Type::kRemote), - id_(GetAllWebContents().Add(this)), - devtools_file_system_indexer_( - base::MakeRefCounted<DevToolsFileSystemIndexer>()), - exclusive_access_manager_(std::make_unique<ExclusiveAccessManager>(this)), - file_task_runner_( - base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()})) + id_(GetAllWebContents().Add(this)) #if BUILDFLAG(ENABLE_PRINTING) , print_task_runner_(CreatePrinterHandlerTaskRunner()) @@ -821,12 +816,7 @@ WebContents::WebContents(v8::Isolate* isolate, Type type) : content::WebContentsObserver(web_contents.get()), type_(type), - id_(GetAllWebContents().Add(this)), - devtools_file_system_indexer_( - base::MakeRefCounted<DevToolsFileSystemIndexer>()), - exclusive_access_manager_(std::make_unique<ExclusiveAccessManager>(this)), - file_task_runner_( - base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()})) + id_(GetAllWebContents().Add(this)) #if BUILDFLAG(ENABLE_PRINTING) , print_task_runner_(CreatePrinterHandlerTaskRunner()) @@ -842,12 +832,7 @@ WebContents::WebContents(v8::Isolate* isolate, WebContents::WebContents(v8::Isolate* isolate, const gin_helper::Dictionary& options) - : id_(GetAllWebContents().Add(this)), - devtools_file_system_indexer_( - base::MakeRefCounted<DevToolsFileSystemIndexer>()), - exclusive_access_manager_(std::make_unique<ExclusiveAccessManager>(this)), - file_task_runner_( - base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()})) + : id_(GetAllWebContents().Add(this)) #if BUILDFLAG(ENABLE_PRINTING) , print_task_runner_(CreatePrinterHandlerTaskRunner()) @@ -1409,7 +1394,7 @@ bool WebContents::PlatformHandleKeyboardEvent( content::KeyboardEventProcessingResult WebContents::PreHandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) { - if (exclusive_access_manager_->HandleUserKeyEvent(event)) + if (exclusive_access_manager_.HandleUserKeyEvent(event)) return content::KeyboardEventProcessingResult::HANDLED; if (event.GetType() == blink::WebInputEvent::Type::kRawKeyDown || @@ -1497,7 +1482,7 @@ void WebContents::OnEnterFullscreenModeForTab( owner_window()->set_fullscreen_transition_type( NativeWindow::FullScreenTransitionType::kHTML); - exclusive_access_manager_->fullscreen_controller()->EnterFullscreenModeForTab( + exclusive_access_manager_.fullscreen_controller()->EnterFullscreenModeForTab( requesting_frame, options.display_id); SetHtmlApiFullscreen(true); @@ -1515,7 +1500,7 @@ void WebContents::ExitFullscreenModeForTab(content::WebContents* source) { // This needs to be called before we exit fullscreen on the native window, // or the controller will incorrectly think we weren't fullscreen and bail. - exclusive_access_manager_->fullscreen_controller()->ExitFullscreenModeForTab( + exclusive_access_manager_.fullscreen_controller()->ExitFullscreenModeForTab( source); SetHtmlApiFullscreen(false); @@ -1574,7 +1559,7 @@ void WebContents::RequestExclusivePointerAccess( bool last_unlocked_by_target, bool allowed) { if (allowed) { - exclusive_access_manager_->mouse_lock_controller()->RequestToLockMouse( + exclusive_access_manager_.mouse_lock_controller()->RequestToLockMouse( web_contents, user_gesture, last_unlocked_by_target); } else { web_contents->GotResponseToLockMouseRequest( @@ -1594,18 +1579,18 @@ void WebContents::RequestToLockMouse(content::WebContents* web_contents, } void WebContents::LostMouseLock() { - exclusive_access_manager_->mouse_lock_controller()->LostMouseLock(); + exclusive_access_manager_.mouse_lock_controller()->LostMouseLock(); } void WebContents::RequestKeyboardLock(content::WebContents* web_contents, bool esc_key_locked) { - exclusive_access_manager_->keyboard_lock_controller()->RequestKeyboardLock( + exclusive_access_manager_.keyboard_lock_controller()->RequestKeyboardLock( web_contents, esc_key_locked); } void WebContents::CancelKeyboardLockRequest( content::WebContents* web_contents) { - exclusive_access_manager_->keyboard_lock_controller() + exclusive_access_manager_.keyboard_lock_controller() ->CancelKeyboardLockRequest(web_contents); } @@ -3875,8 +3860,10 @@ bool WebContents::IsFullscreenForTabOrPending( content::FullscreenState WebContents::GetFullscreenState( const content::WebContents* source) const { - return exclusive_access_manager_->fullscreen_controller()->GetFullscreenState( - source); + // `const_cast` here because EAM does not have const getters + return const_cast<ExclusiveAccessManager*>(&exclusive_access_manager_) + ->fullscreen_controller() + ->GetFullscreenState(source); } bool WebContents::TakeFocus(content::WebContents* source, bool reverse) { diff --git a/shell/browser/api/electron_api_web_contents.h b/shell/browser/api/electron_api_web_contents.h index d7424056b4..da2757f4d6 100644 --- a/shell/browser/api/electron_api_web_contents.h +++ b/shell/browser/api/electron_api_web_contents.h @@ -16,9 +16,11 @@ #include "base/memory/weak_ptr.h" #include "base/observer_list.h" #include "base/observer_list_types.h" +#include "base/task/thread_pool.h" #include "chrome/browser/devtools/devtools_eye_dropper.h" #include "chrome/browser/devtools/devtools_file_system_indexer.h" #include "chrome/browser/ui/exclusive_access/exclusive_access_context.h" // nogncheck +#include "chrome/browser/ui/exclusive_access/exclusive_access_manager.h" #include "content/common/frame.mojom.h" #include "content/public/browser/devtools_agent_host.h" #include "content/public/browser/keyboard_event_processing_result.h" @@ -77,8 +79,6 @@ namespace gin { class Arguments; } -class ExclusiveAccessManager; - class SkRegion; namespace electron { @@ -803,9 +803,10 @@ class WebContents : public ExclusiveAccessContext, // Whether window is fullscreened by window api. bool native_fullscreen_ = false; - scoped_refptr<DevToolsFileSystemIndexer> devtools_file_system_indexer_; + const scoped_refptr<DevToolsFileSystemIndexer> devtools_file_system_indexer_ = + base::MakeRefCounted<DevToolsFileSystemIndexer>(); - std::unique_ptr<ExclusiveAccessManager> exclusive_access_manager_; + ExclusiveAccessManager exclusive_access_manager_{this}; std::unique_ptr<DevToolsEyeDropper> eye_dropper_; @@ -832,10 +833,11 @@ class WebContents : public ExclusiveAccessContext, DevToolsIndexingJobsMap; DevToolsIndexingJobsMap devtools_indexing_jobs_; - scoped_refptr<base::SequencedTaskRunner> file_task_runner_; + const scoped_refptr<base::SequencedTaskRunner> file_task_runner_ = + base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()}); #if BUILDFLAG(ENABLE_PRINTING) - scoped_refptr<base::TaskRunner> print_task_runner_; + const scoped_refptr<base::TaskRunner> print_task_runner_; #endif // Stores the frame thats currently in fullscreen, nullptr if there is none.
refactor
713d8c4167a07971775db847adca880f49e8d381
Shelley Vohr
2023-10-03 21:27:40
feat: add `tabbingIdentifier` property to `BrowserWindow` (#39980) feat: add tabbingIdentifier property to BrowserWindow
diff --git a/docs/api/browser-window.md b/docs/api/browser-window.md index f3d621c995..283e958149 100644 --- a/docs/api/browser-window.md +++ b/docs/api/browser-window.md @@ -475,6 +475,10 @@ events. A `Integer` property representing the unique ID of the window. Each ID is unique among all `BrowserWindow` instances of the entire Electron application. +#### `win.tabbingIdentifier` _macOS_ _Readonly_ + +A `string` (optional) property that is equal to the `tabbingIdentifier` passed to the `BrowserWindow` constructor or `undefined` if none was set. + #### `win.autoHideMenuBar` A `boolean` property that determines whether the window menu bar should hide itself automatically. Once set, the menu bar will only show when users press the single `Alt` key. diff --git a/shell/browser/api/electron_api_base_window.cc b/shell/browser/api/electron_api_base_window.cc index 8bccf457a0..373a536a46 100644 --- a/shell/browser/api/electron_api_base_window.cc +++ b/shell/browser/api/electron_api_base_window.cc @@ -953,6 +953,14 @@ void BaseWindow::AddTabbedWindow(NativeWindow* window, args->ThrowError("AddTabbedWindow cannot be called by a window on itself."); } +v8::Local<v8::Value> BaseWindow::GetTabbingIdentifier() { + auto tabbing_id = window_->GetTabbingIdentifier(); + if (!tabbing_id.has_value()) + return v8::Undefined(isolate()); + + return gin::ConvertToV8(isolate(), tabbing_id.value()); +} + void BaseWindow::SetAutoHideMenuBar(bool auto_hide) { window_->SetAutoHideMenuBar(auto_hide); } @@ -1305,6 +1313,7 @@ void BaseWindow::BuildPrototype(v8::Isolate* isolate, .SetMethod("moveTabToNewWindow", &BaseWindow::MoveTabToNewWindow) .SetMethod("toggleTabBar", &BaseWindow::ToggleTabBar) .SetMethod("addTabbedWindow", &BaseWindow::AddTabbedWindow) + .SetProperty("tabbingIdentifier", &BaseWindow::GetTabbingIdentifier) .SetMethod("setWindowButtonVisibility", &BaseWindow::SetWindowButtonVisibility) .SetMethod("_getWindowButtonVisibility", diff --git a/shell/browser/api/electron_api_base_window.h b/shell/browser/api/electron_api_base_window.h index 3f2a02eb40..c3fd773bb0 100644 --- a/shell/browser/api/electron_api_base_window.h +++ b/shell/browser/api/electron_api_base_window.h @@ -198,9 +198,7 @@ class BaseWindow : public gin_helper::TrackableObject<BaseWindow>, bool GetWindowButtonVisibility() const; void SetWindowButtonPosition(absl::optional<gfx::Point> position); absl::optional<gfx::Point> GetWindowButtonPosition() const; -#endif -#if BUILDFLAG(IS_MAC) bool IsHiddenInMissionControl(); void SetHiddenInMissionControl(bool hidden); #endif @@ -215,6 +213,7 @@ class BaseWindow : public gin_helper::TrackableObject<BaseWindow>, void MoveTabToNewWindow(); void ToggleTabBar(); void AddTabbedWindow(NativeWindow* window, gin_helper::Arguments* args); + v8::Local<v8::Value> GetTabbingIdentifier(); void SetAutoHideMenuBar(bool auto_hide); bool IsMenuBarAutoHide(); void SetMenuBarVisibility(bool visible); diff --git a/shell/browser/native_window.cc b/shell/browser/native_window.cc index 469d9cd01a..d76b235027 100644 --- a/shell/browser/native_window.cc +++ b/shell/browser/native_window.cc @@ -481,6 +481,10 @@ bool NativeWindow::AddTabbedWindow(NativeWindow* window) { return true; // for non-Mac platforms } +absl::optional<std::string> NativeWindow::GetTabbingIdentifier() const { + return ""; // for non-Mac platforms +} + void NativeWindow::SetVibrancy(const std::string& type) { vibrancy_ = type; } diff --git a/shell/browser/native_window.h b/shell/browser/native_window.h index d2ec3c9fe9..79bc09f9c8 100644 --- a/shell/browser/native_window.h +++ b/shell/browser/native_window.h @@ -256,6 +256,7 @@ class NativeWindow : public base::SupportsUserData, virtual void MoveTabToNewWindow(); virtual void ToggleTabBar(); virtual bool AddTabbedWindow(NativeWindow* window); + virtual absl::optional<std::string> GetTabbingIdentifier() const; // Toggle the menu bar. virtual void SetAutoHideMenuBar(bool auto_hide); diff --git a/shell/browser/native_window_mac.h b/shell/browser/native_window_mac.h index a1c70ba2a0..238d4347f4 100644 --- a/shell/browser/native_window_mac.h +++ b/shell/browser/native_window_mac.h @@ -145,6 +145,7 @@ class NativeWindowMac : public NativeWindow, void MoveTabToNewWindow() override; void ToggleTabBar() override; bool AddTabbedWindow(NativeWindow* window) override; + absl::optional<std::string> GetTabbingIdentifier() const override; void SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) override; void PreviewFile(const std::string& path, diff --git a/shell/browser/native_window_mac.mm b/shell/browser/native_window_mac.mm index b8f660b6a0..5f39747fb1 100644 --- a/shell/browser/native_window_mac.mm +++ b/shell/browser/native_window_mac.mm @@ -1643,6 +1643,13 @@ bool NativeWindowMac::AddTabbedWindow(NativeWindow* window) { return true; } +absl::optional<std::string> NativeWindowMac::GetTabbingIdentifier() const { + if ([window_ tabbingMode] == NSWindowTabbingModeDisallowed) + return absl::nullopt; + + return base::SysNSStringToUTF8([window_ tabbingIdentifier]); +} + void NativeWindowMac::SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) { NativeWindow::SetAspectRatio(aspect_ratio, extra_size); diff --git a/spec/api-browser-window-spec.ts b/spec/api-browser-window-spec.ts index d194e7c385..37e0a19be7 100644 --- a/spec/api-browser-window-spec.ts +++ b/spec/api-browser-window-spec.ts @@ -2060,10 +2060,7 @@ describe('BrowserWindow module', () => { beforeEach(() => { w = new BrowserWindow({ show: false }); }); - afterEach(async () => { - await closeWindow(w); - w = null as unknown as BrowserWindow; - }); + afterEach(closeAllWindows); describe('BrowserWindow.selectPreviousTab()', () => { it('does not throw', () => { @@ -2132,6 +2129,18 @@ describe('BrowserWindow module', () => { }).to.throw('AddTabbedWindow cannot be called by a window on itself.'); }); }); + + describe('BrowserWindow.tabbingIdentifier', () => { + it('is undefined if no tabbingIdentifier was set', () => { + const w = new BrowserWindow({ show: false }); + expect(w.tabbingIdentifier).to.be.undefined('tabbingIdentifier'); + }); + + it('returns the window tabbingIdentifier', () => { + const w = new BrowserWindow({ show: false, tabbingIdentifier: 'group1' }); + expect(w.tabbingIdentifier).to.equal('group1'); + }); + }); }); describe('autoHideMenuBar state', () => {
feat
4d060afc98dd2eef076dd415f2a03ea642a5baa7
github-actions[bot]
2024-02-08 15:01:05
build: update appveyor image to latest version (#41206) Co-authored-by: jkleinsc <[email protected]>
diff --git a/appveyor-woa.yml b/appveyor-woa.yml index af71a178cf..691892ea6d 100644 --- a/appveyor-woa.yml +++ b/appveyor-woa.yml @@ -29,7 +29,7 @@ version: 1.0.{build} build_cloud: electronhq-16-core -image: e-123.0.6264.0 +image: e-123.0.6272.0 environment: GIT_CACHE_PATH: C:\Users\appveyor\libcc_cache ELECTRON_OUT_DIR: Default diff --git a/appveyor.yml b/appveyor.yml index 3ec6f67ef5..15a0d5e33a 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -29,7 +29,7 @@ version: 1.0.{build} build_cloud: electronhq-16-core -image: e-123.0.6264.0 +image: e-123.0.6272.0 environment: GIT_CACHE_PATH: C:\Users\appveyor\libcc_cache ELECTRON_OUT_DIR: Default
build
e14964ccd014e595da4cbaf8c73f0999948c6042
wanted002
2023-08-25 05:21:22
feat: add setter and getter apis to specify udp port range for webrtc (#39046) * feat:Add setter and getter apis to specify udp port range for webrtc (issue#9042) * lint error fix for PR#39046 * feat: add setter and getter apis to specify udp port range for webrtc (issue#9042) , changed for codereview * fix lint error * fix lint errors in file api-web-contents-spec.ts * feat: add setter and getter apis to specify udp port range for webrtc (issue#9042) , changed for review from itsananderson * feat: add setter and getter apis to specify udp port range for webrtc (issue#9042) , changed for review from jkleinsc * fix lint error * feat: add setter and getter apis to specify udp port range for webrtc (issue#9042) , changed for review from codebyter
diff --git a/docs/api/web-contents.md b/docs/api/web-contents.md index 035da986f9..b83b6d6c89 100644 --- a/docs/api/web-contents.md +++ b/docs/api/web-contents.md @@ -2069,6 +2069,24 @@ Setting the WebRTC IP handling policy allows you to control which IPs are exposed via WebRTC. See [BrowserLeaks](https://browserleaks.com/webrtc) for more details. +#### `contents.getWebRTCUDPPortRange()` + +Returns `Object`: + +* `min` Integer - The minimum UDP port number that WebRTC should use. +* `max` Integer - The maximum UDP port number that WebRTC should use. + +By default this value is `{ min: 0, max: 0 }` , which would apply no restriction on the udp port range. + +#### `contents.setWebRTCUDPPortRange(udpPortRange)` + +* `udpPortRange` Object + * `min` Integer - The minimum UDP port number that WebRTC should use. + * `max` Integer - The maximum UDP port number that WebRTC should use. + +Setting the WebRTC UDP Port Range allows you to restrict the udp port range used by WebRTC. By default the port range is unrestricted. +**Note:** To reset to an unrestricted port range this value should be set to `{ min: 0, max: 0 }`. + #### `contents.getMediaSourceId(requestWebContents)` * `requestWebContents` WebContents - Web contents that the id will be registered to. diff --git a/shell/browser/api/electron_api_web_contents.cc b/shell/browser/api/electron_api_web_contents.cc index 8e7db50616..4f946d1668 100644 --- a/shell/browser/api/electron_api_web_contents.cc +++ b/shell/browser/api/electron_api_web_contents.cc @@ -2552,6 +2552,52 @@ void WebContents::SetWebRTCIPHandlingPolicy( web_contents()->SyncRendererPrefs(); } +v8::Local<v8::Value> WebContents::GetWebRTCUDPPortRange( + v8::Isolate* isolate) const { + auto* prefs = web_contents()->GetMutableRendererPrefs(); + + gin_helper::Dictionary dict = gin::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(); +} + +void WebContents::SetWebRTCUDPPortRange(gin::Arguments* args) { + uint32_t min = 0, max = 0; + gin_helper::Dictionary range; + + if (!args->GetNext(&range) || !range.Get("min", &min) || + !range.Get("max", &max)) { + gin_helper::ErrorThrower(args->isolate()) + .ThrowError("'min' and 'max' are both required"); + return; + } + + if ((0 == min && 0 != max) || max > UINT16_MAX) { + gin_helper::ErrorThrower(args->isolate()) + .ThrowError( + "'min' and 'max' must be in the (0, 65535] range or [0, 0]"); + return; + } + if (min > max) { + gin_helper::ErrorThrower(args->isolate()) + .ThrowError("'max' must be greater than or equal to 'min'"); + return; + } + + auto* prefs = web_contents()->GetMutableRendererPrefs(); + + if (prefs->webrtc_udp_min_port == static_cast<uint16_t>(min) && + prefs->webrtc_udp_max_port == static_cast<uint16_t>(max)) { + return; + } + + prefs->webrtc_udp_min_port = min; + prefs->webrtc_udp_max_port = max; + + web_contents()->SyncRendererPrefs(); +} + std::string WebContents::GetMediaSourceID( content::WebContents* request_web_contents) { auto* frame_host = web_contents()->GetPrimaryMainFrame(); @@ -4319,9 +4365,11 @@ void WebContents::FillObjectTemplate(v8::Isolate* isolate, .SetMethod("isBeingCaptured", &WebContents::IsBeingCaptured) .SetMethod("setWebRTCIPHandlingPolicy", &WebContents::SetWebRTCIPHandlingPolicy) + .SetMethod("setWebRTCUDPPortRange", &WebContents::SetWebRTCUDPPortRange) .SetMethod("getMediaSourceId", &WebContents::GetMediaSourceID) .SetMethod("getWebRTCIPHandlingPolicy", &WebContents::GetWebRTCIPHandlingPolicy) + .SetMethod("getWebRTCUDPPortRange", &WebContents::GetWebRTCUDPPortRange) .SetMethod("takeHeapSnapshot", &WebContents::TakeHeapSnapshot) .SetMethod("setImageAnimationPolicy", &WebContents::SetImageAnimationPolicy) diff --git a/shell/browser/api/electron_api_web_contents.h b/shell/browser/api/electron_api_web_contents.h index d0c65fd4b4..e1fc66378b 100644 --- a/shell/browser/api/electron_api_web_contents.h +++ b/shell/browser/api/electron_api_web_contents.h @@ -189,6 +189,8 @@ class WebContents : public ExclusiveAccessContext, int GetHistoryLength() const; const std::string GetWebRTCIPHandlingPolicy() const; void SetWebRTCIPHandlingPolicy(const std::string& webrtc_ip_handling_policy); + v8::Local<v8::Value> GetWebRTCUDPPortRange(v8::Isolate* isolate) const; + void SetWebRTCUDPPortRange(gin::Arguments* args); std::string GetMediaSourceID(content::WebContents* request_web_contents); bool IsCrashed() const; void ForcefullyCrashRenderer(); diff --git a/spec/api-web-contents-spec.ts b/spec/api-web-contents-spec.ts index ac11521e98..d0f560b8bc 100644 --- a/spec/api-web-contents-spec.ts +++ b/spec/api-web-contents-spec.ts @@ -1309,6 +1309,47 @@ describe('webContents module', () => { }); }); + describe('webrtc udp port range policy api', () => { + let w: BrowserWindow; + beforeEach(() => { + w = new BrowserWindow({ show: false }); + }); + + afterEach(closeAllWindows); + + it('check default webrtc udp port range is { min: 0, max: 0 }', () => { + const settings = w.webContents.getWebRTCUDPPortRange(); + expect(settings).to.deep.equal({ min: 0, max: 0 }); + }); + + it('can set and get webrtc udp port range policy with correct arguments', () => { + w.webContents.setWebRTCUDPPortRange({ min: 1, max: 65535 }); + const settings = w.webContents.getWebRTCUDPPortRange(); + expect(settings).to.deep.equal({ min: 1, max: 65535 }); + }); + + it('can not set webrtc udp port range policy with invalid arguments', () => { + expect(() => { + w.webContents.setWebRTCUDPPortRange({ min: 0, max: 65535 }); + }).to.throw("'min' and 'max' must be in the (0, 65535] range or [0, 0]"); + expect(() => { + w.webContents.setWebRTCUDPPortRange({ min: 1, max: 65536 }); + }).to.throw("'min' and 'max' must be in the (0, 65535] range or [0, 0]"); + expect(() => { + w.webContents.setWebRTCUDPPortRange({ min: 60000, max: 56789 }); + }).to.throw("'max' must be greater than or equal to 'min'"); + }); + + it('can reset webrtc udp port range policy to default with { min: 0, max: 0 }', () => { + w.webContents.setWebRTCUDPPortRange({ min: 1, max: 65535 }); + const settings = w.webContents.getWebRTCUDPPortRange(); + expect(settings).to.deep.equal({ min: 1, max: 65535 }); + w.webContents.setWebRTCUDPPortRange({ min: 0, max: 0 }); + const defaultSetting = w.webContents.getWebRTCUDPPortRange(); + expect(defaultSetting).to.deep.equal({ min: 0, max: 0 }); + }); + }); + describe('opener api', () => { afterEach(closeAllWindows); it('can get opener with window.open()', async () => {
feat
36e1a0bf001d72f725297f43827d255b08c2e9b7
Robo
2024-11-18 23:57:06
fix: utility process exit code for graceful termination (#44698)
diff --git a/patches/chromium/feat_enable_passing_exit_code_on_service_process_crash.patch b/patches/chromium/feat_enable_passing_exit_code_on_service_process_crash.patch index 4d7eb0de3f..f9b2591d1e 100644 --- a/patches/chromium/feat_enable_passing_exit_code_on_service_process_crash.patch +++ b/patches/chromium/feat_enable_passing_exit_code_on_service_process_crash.patch @@ -11,7 +11,7 @@ ServiceProcessHost::Observer functions, but we need to pass the exit code to the observer. diff --git a/content/browser/service_process_host_impl.cc b/content/browser/service_process_host_impl.cc -index f6082bada22c5f4e70af60ea6f555b0f363919c5..228f947edbe04bce242df62080052d9c383f1709 100644 +index f6082bada22c5f4e70af60ea6f555b0f363919c5..f691676a629bf82f81117599ae0bd0a4870c9f61 100644 --- a/content/browser/service_process_host_impl.cc +++ b/content/browser/service_process_host_impl.cc @@ -73,12 +73,15 @@ class ServiceProcessTracker { @@ -33,19 +33,7 @@ index f6082bada22c5f4e70af60ea6f555b0f363919c5..228f947edbe04bce242df62080052d9c processes_.erase(iter); } -@@ -87,6 +90,11 @@ class ServiceProcessTracker { - observers_.AddObserver(observer); - } - -+ bool HasObserver(ServiceProcessHost::Observer* observer) { -+ DCHECK_CURRENTLY_ON(BrowserThread::UI); -+ return observers_.HasObserver(observer); -+ } -+ - void RemoveObserver(ServiceProcessHost::Observer* observer) { - // NOTE: Some tests may remove observers after BrowserThreads are shut down. - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI) || -@@ -154,7 +162,7 @@ class UtilityProcessClient : public UtilityProcessHost::Client { +@@ -154,7 +157,7 @@ class UtilityProcessClient : public UtilityProcessHost::Client { process_info_->service_process_id()); } @@ -54,7 +42,7 @@ index f6082bada22c5f4e70af60ea6f555b0f363919c5..228f947edbe04bce242df62080052d9c // TODO(crbug.com/40654042): It is unclear how we can observe // |OnProcessCrashed()| without observing |OnProcessLaunched()| first, but // it can happen on Android. Ignore the notification in this case. -@@ -162,7 +170,7 @@ class UtilityProcessClient : public UtilityProcessHost::Client { +@@ -162,7 +165,7 @@ class UtilityProcessClient : public UtilityProcessHost::Client { return; GetServiceProcessTracker().NotifyCrashed( @@ -63,18 +51,6 @@ index f6082bada22c5f4e70af60ea6f555b0f363919c5..228f947edbe04bce242df62080052d9c } private: -@@ -232,6 +240,11 @@ void ServiceProcessHost::AddObserver(Observer* observer) { - GetServiceProcessTracker().AddObserver(observer); - } - -+// static -+bool ServiceProcessHost::HasObserver(Observer* observer) { -+ return GetServiceProcessTracker().HasObserver(observer); -+} -+ - // static - void ServiceProcessHost::RemoveObserver(Observer* observer) { - GetServiceProcessTracker().RemoveObserver(observer); diff --git a/content/browser/utility_process_host.cc b/content/browser/utility_process_host.cc index cdc2046f465110b60285da81fb0db7cdce064a59..8feca9f1c294b3de15d74dfc94508ee2a43e5fc3 100644 --- a/content/browser/utility_process_host.cc @@ -101,23 +77,8 @@ index 66cbabae31236758eef35bab211d4874f8a5c699..88515741fa08176ba9e952759c3a52e1 }; // This class is self-owned. It must be instantiated using new, and shouldn't -diff --git a/content/public/browser/service_process_host.h b/content/public/browser/service_process_host.h -index 611a52e908f4cb70fbe5628e220a082e45320b70..d7fefab99f86515007aff5f523a423a421850c47 100644 ---- a/content/public/browser/service_process_host.h -+++ b/content/public/browser/service_process_host.h -@@ -235,6 +235,10 @@ class CONTENT_EXPORT ServiceProcessHost { - // removed before destruction. Must be called from the UI thread only. - static void AddObserver(Observer* observer); - -+ // Returns true if the given observer is currently registered. -+ // Must be called from the UI thread only. -+ static bool HasObserver(Observer* observer); -+ - // Removes a registered observer. This must be called some time before - // |*observer| is destroyed and must be called from the UI thread only. - static void RemoveObserver(Observer* observer); diff --git a/content/public/browser/service_process_info.h b/content/public/browser/service_process_info.h -index 1a8656aef341cd3b23af588fb00569b79d6cd100..f904af7ee6bbacf4474e0939855ecf9f2c9a5eaa 100644 +index 1a8656aef341cd3b23af588fb00569b79d6cd100..6af523eb27a8c1e5529721c029e5b3ba0708b9fc 100644 --- a/content/public/browser/service_process_info.h +++ b/content/public/browser/service_process_info.h @@ -64,7 +64,13 @@ class CONTENT_EXPORT ServiceProcessInfo { @@ -129,7 +90,7 @@ index 1a8656aef341cd3b23af588fb00569b79d6cd100..f904af7ee6bbacf4474e0939855ecf9f + private: + // The exit code of the process, if it has exited. -+ int exit_code_; ++ int exit_code_ = 0; + // The name of the service interface for which the process was launched. std::string service_interface_name_; diff --git a/patches/chromium/refactor_unfilter_unresponsive_events.patch b/patches/chromium/refactor_unfilter_unresponsive_events.patch index d2d360f52a..ec4fc07f74 100644 --- a/patches/chromium/refactor_unfilter_unresponsive_events.patch +++ b/patches/chromium/refactor_unfilter_unresponsive_events.patch @@ -15,10 +15,10 @@ This CL removes these filters so the unresponsive event can still be accessed from our JS event. The filtering is moved into Electron's code. diff --git a/content/browser/web_contents/web_contents_impl.cc b/content/browser/web_contents/web_contents_impl.cc -index 319800cec84a968b0e442fc760c8e1d701bda2ed..459663af86272fe1e23a6a163e01c67fc5f8a66d 100644 +index 0e742f196367bbbe8c4e147ef4db4f8dbbe4cbbe..7026b28c4f228971f74a706b6ad99777e4ca0773 100644 --- a/content/browser/web_contents/web_contents_impl.cc +++ b/content/browser/web_contents/web_contents_impl.cc -@@ -9464,25 +9464,13 @@ void WebContentsImpl::RendererUnresponsive( +@@ -9518,25 +9518,13 @@ void WebContentsImpl::RendererUnresponsive( base::RepeatingClosure hang_monitor_restarter) { OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::RendererUnresponsive", "render_widget_host", render_widget_host); diff --git a/shell/browser/api/electron_api_utility_process.cc b/shell/browser/api/electron_api_utility_process.cc index 5c1fd14be0..d1b2c3ae61 100644 --- a/shell/browser/api/electron_api_utility_process.cc +++ b/shell/browser/api/electron_api_utility_process.cc @@ -145,8 +145,8 @@ UtilityProcessWrapper::UtilityProcessWrapper( } } - if (!content::ServiceProcessHost::HasObserver(this)) - content::ServiceProcessHost::AddObserver(this); + // Watch for service process termination events. + content::ServiceProcessHost::AddObserver(this); mojo::PendingReceiver<node::mojom::NodeService> receiver = node_service_remote_.BindNewPipeAndPassReceiver(); diff --git a/spec/api-utility-process-spec.ts b/spec/api-utility-process-spec.ts index 9967303214..364b7e8648 100644 --- a/spec/api-utility-process-spec.ts +++ b/spec/api-utility-process-spec.ts @@ -215,7 +215,8 @@ describe('utilityProcess module', () => { }); await once(child, 'spawn'); expect(child.kill()).to.be.true(); - await once(child, 'exit'); + const [code] = await once(child, 'exit'); + expect(code).to.equal(0); }); });
fix
d0cb298f95c905ba78e4746c560b9be6a1d0208f
Shelley Vohr
2024-05-14 22:47:47
fix: `webContents.navigationHistory` should be enumerable (#42139) fix: webContents.navigationHistory should be enumerable
diff --git a/lib/browser/api/web-contents.ts b/lib/browser/api/web-contents.ts index a03306c9b3..97364de7a8 100644 --- a/lib/browser/api/web-contents.ts +++ b/lib/browser/api/web-contents.ts @@ -541,7 +541,8 @@ WebContents.prototype._init = function () { length: this._historyLength.bind(this), getEntryAtIndex: this._getNavigationEntryAtIndex.bind(this) }, - writable: false + writable: false, + enumerable: true }); // Dispatch IPC messages to the ipc module. diff --git a/spec/api-web-contents-spec.ts b/spec/api-web-contents-spec.ts index f5fd80061e..a54990fcb8 100644 --- a/spec/api-web-contents-spec.ts +++ b/spec/api-web-contents-spec.ts @@ -41,6 +41,17 @@ describe('webContents module', () => { }); }); + describe('webContents properties', () => { + afterEach(closeAllWindows); + + it('has expected additional enumerable properties', () => { + const w = new BrowserWindow({ show: false }); + const properties = Object.getOwnPropertyNames(w.webContents); + expect(properties).to.include('ipc'); + expect(properties).to.include('navigationHistory'); + }); + }); + describe('fromId()', () => { it('returns undefined for an unknown id', () => { expect(webContents.fromId(12345)).to.be.undefined();
fix
4e19321ba8591f963a9b41b14cb87995b8b9a2a8
github-actions[bot]
2024-01-29 14:12:59
build: update appveyor image to latest version (#41134) Co-authored-by: jkleinsc <[email protected]>
diff --git a/appveyor-woa.yml b/appveyor-woa.yml index fcb6690424..af71a178cf 100644 --- a/appveyor-woa.yml +++ b/appveyor-woa.yml @@ -29,7 +29,7 @@ version: 1.0.{build} build_cloud: electronhq-16-core -image: e-122.0.6236.2 +image: e-123.0.6264.0 environment: GIT_CACHE_PATH: C:\Users\appveyor\libcc_cache ELECTRON_OUT_DIR: Default diff --git a/appveyor.yml b/appveyor.yml index 5e4811c363..3ec6f67ef5 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -29,7 +29,7 @@ version: 1.0.{build} build_cloud: electronhq-16-core -image: e-122.0.6236.2 +image: e-123.0.6264.0 environment: GIT_CACHE_PATH: C:\Users\appveyor\libcc_cache ELECTRON_OUT_DIR: Default
build
8f23b1527b1d1055d675d04e7b3ee669947ccbd4
Jeremy Rose
2022-12-21 14:53:29
fix: use chrome headers in net.request for everything except cookie (#36666)
diff --git a/lib/browser/api/net.ts b/lib/browser/api/net.ts index 6438eb0230..31845c7daf 100644 --- a/lib/browser/api/net.ts +++ b/lib/browser/api/net.ts @@ -56,31 +56,14 @@ class IncomingMessage extends Readable { get headers () { const filteredHeaders: Record<string, string | string[]> = {}; - const { rawHeaders } = this._responseHead; - rawHeaders.forEach(header => { - const keyLowerCase = header.key.toLowerCase(); - if (Object.prototype.hasOwnProperty.call(filteredHeaders, keyLowerCase) && - discardableDuplicateHeaders.has(keyLowerCase)) { - // do nothing with discardable duplicate headers - } else { - if (keyLowerCase === 'set-cookie') { - // keep set-cookie as an array per Node.js rules - // see https://nodejs.org/api/http.html#http_message_headers - if (Object.prototype.hasOwnProperty.call(filteredHeaders, keyLowerCase)) { - (filteredHeaders[keyLowerCase] as string[]).push(header.value); - } else { - filteredHeaders[keyLowerCase] = [header.value]; - } - } else { - // for non-cookie headers, the values are joined together with ', ' - if (Object.prototype.hasOwnProperty.call(filteredHeaders, keyLowerCase)) { - filteredHeaders[keyLowerCase] += `, ${header.value}`; - } else { - filteredHeaders[keyLowerCase] = header.value; - } - } - } - }); + const { headers, rawHeaders } = this._responseHead; + for (const [name, values] of Object.entries(headers)) { + filteredHeaders[name] = discardableDuplicateHeaders.has(name) ? values[0] : values.join(', '); + } + const cookies = rawHeaders.filter(({ key }) => key.toLowerCase() === 'set-cookie').map(({ value }) => value); + // keep set-cookie as an array per Node.js rules + // see https://nodejs.org/api/http.html#http_message_headers + if (cookies.length) { filteredHeaders['set-cookie'] = cookies; } return filteredHeaders; } diff --git a/shell/browser/api/electron_api_url_loader.cc b/shell/browser/api/electron_api_url_loader.cc index 3a2d329738..6fed3bf105 100644 --- a/shell/browser/api/electron_api_url_loader.cc +++ b/shell/browser/api/electron_api_url_loader.cc @@ -577,9 +577,7 @@ void SimpleURLLoaderWrapper::OnResponseStarted( dict.Set("statusCode", response_head.headers->response_code()); dict.Set("statusMessage", response_head.headers->GetStatusText()); dict.Set("httpVersion", response_head.headers->GetHttpVersion()); - // Note that |response_head.headers| are filtered by Chromium and should not - // be used here. - DCHECK(!response_head.raw_response_headers.empty()); + dict.Set("headers", response_head.headers.get()); dict.Set("rawHeaders", response_head.raw_response_headers); Emit("response-started", final_url, dict); } diff --git a/spec/api-net-spec.ts b/spec/api-net-spec.ts index 97f7e5ca90..7e23afe2e8 100644 --- a/spec/api-net-spec.ts +++ b/spec/api-net-spec.ts @@ -623,6 +623,19 @@ describe('net module', () => { 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; diff --git a/typings/internal-ambient.d.ts b/typings/internal-ambient.d.ts index d972d03eda..580fec7688 100644 --- a/typings/internal-ambient.d.ts +++ b/typings/internal-ambient.d.ts @@ -145,6 +145,7 @@ declare namespace NodeJS { statusMessage: string; httpVersion: { major: number, minor: number }; rawHeaders: { key: string, value: string }[]; + headers: Record<string, string[]>; }; type RedirectInfo = {
fix
2e8114aea3658b440aaa3c87a0fa98ffe3ccd634
Shelley Vohr
2023-02-14 08:54:09
refactor: simplify Node.js event loop with `SpinEventLoop` (#34884) refactor: simplify Node.js event loop with SpinEventLoop
diff --git a/shell/app/node_main.cc b/shell/app/node_main.cc index bb025dbc5a..d7b785b02e 100644 --- a/shell/app/node_main.cc +++ b/shell/app/node_main.cc @@ -260,37 +260,9 @@ int NodeMain(int argc, char* argv[]) { v8::HandleScope scope(isolate); node::LoadEnvironment(env, node::StartExecutionCallback{}); - env->set_trace_sync_io(env->options()->trace_sync_io); - - { - v8::SealHandleScope seal(isolate); - bool more; - env->performance_state()->Mark( - node::performance::NODE_PERFORMANCE_MILESTONE_LOOP_START); - do { - uv_run(env->event_loop(), UV_RUN_DEFAULT); - - gin_env.platform()->DrainTasks(isolate); - - more = uv_loop_alive(env->event_loop()); - if (more && !env->is_stopping()) - continue; - - if (!uv_loop_alive(env->event_loop())) { - EmitBeforeExit(env); - } - - // Emit `beforeExit` if the loop became alive either after emitting - // event, or after running some callbacks. - more = uv_loop_alive(env->event_loop()); - } while (more && !env->is_stopping()); - env->performance_state()->Mark( - node::performance::NODE_PERFORMANCE_MILESTONE_LOOP_EXIT); - } - - env->set_trace_sync_io(false); - - exit_code = node::EmitExit(env); + // Potential reasons we get Nothing here may include: the env + // is stopping, or the user hooks process.emit('exit'). + exit_code = node::SpinEventLoop(env).FromMaybe(1); node::ResetStdio();
refactor
4cf6884dd418aa7d6e4dc549efc3db1ee2a67900
Cheng Zhao
2023-09-29 00:17:42
fix: detect screen readers by testing their existences (#39988)
diff --git a/shell/browser/native_window_views_win.cc b/shell/browser/native_window_views_win.cc index f782dbbbad..e5ea8d7a2a 100644 --- a/shell/browser/native_window_views_win.cc +++ b/shell/browser/native_window_views_win.cc @@ -7,6 +7,7 @@ #include <wrl/client.h> #include "base/win/atl.h" // Must be before UIAutomationCore.h +#include "base/win/scoped_handle.h" #include "content/public/browser/browser_accessibility_state.h" #include "shell/browser/browser.h" #include "shell/browser/native_window_views.h" @@ -165,10 +166,41 @@ gfx::ResizeEdge GetWindowResizeEdge(WPARAM param) { } } +bool IsMutexPresent(const wchar_t* name) { + base::win::ScopedHandle mutex_holder(::CreateMutex(nullptr, false, name)); + return ::GetLastError() == ERROR_ALREADY_EXISTS; +} + +bool IsLibraryLoaded(const wchar_t* name) { + HMODULE hmodule = nullptr; + ::GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, name, + &hmodule); + return hmodule != nullptr; +} + +// The official way to get screen reader status is to call: +// SystemParametersInfo(SPI_GETSCREENREADER) && UiaClientsAreListening() +// However it has false positives (for example when user is using touch screens) +// and will cause performance issues in some apps. bool IsScreenReaderActive() { - UINT screenReader = 0; - SystemParametersInfo(SPI_GETSCREENREADER, 0, &screenReader, 0); - return screenReader && UiaClientsAreListening(); + if (IsMutexPresent(L"NarratorRunning")) + return true; + + static const wchar_t* names[] = {// NVDA + L"nvdaHelperRemote.dll", + // JAWS + L"jhook.dll", + // Window-Eyes + L"gwhk64.dll", L"gwmhook.dll", + // ZoomText + L"AiSquared.Infuser.HookLib.dll"}; + + for (auto* name : names) { + if (IsLibraryLoaded(name)) + return true; + } + + return false; } } // namespace
fix
b27dc7514e639360812e534bd1d184e980bbe2ee
Alexander Cyon
2024-08-22 15:44:55
fix: documentation spelling errors (#43366) chore: fix typos in 'docs/' folder.
diff --git a/docs/api/session.md b/docs/api/session.md index 70217fac36..ad3c10515f 100644 --- a/docs/api/session.md +++ b/docs/api/session.md @@ -1511,7 +1511,7 @@ Returns `Promise<void>` - resolves when all data has been cleared. Clears various different types of data. -This method clears more types of data and is more thourough than the +This method clears more types of data and is more thorough than the `clearStorageData` method. **Note:** Cookies are stored at a broader scope than origins. When removing cookies and filtering by `origins` (or `excludeOrigins`), the cookies will be removed at the [registrable domain](https://url.spec.whatwg.org/#host-registrable-domain) level. For example, clearing cookies for the origin `https://really.specific.origin.example.com/` will end up clearing all cookies for `example.com`. Clearing cookies for the origin `https://my.website.example.co.uk/` will end up clearing all cookies for `example.co.uk`. diff --git a/docs/api/touch-bar-scrubber.md b/docs/api/touch-bar-scrubber.md index 59aa373f15..a64f309c38 100644 --- a/docs/api/touch-bar-scrubber.md +++ b/docs/api/touch-bar-scrubber.md @@ -39,7 +39,7 @@ updates the control in the touch bar. Possible values: #### `touchBarScrubber.overlayStyle` -A `string` representing the style that selected items in the scrubber should have. This style is overlayed on top +A `string` representing the style that selected items in the scrubber should have. This style is overlaid on top of the scrubber item instead of being placed behind it. Updating this value immediately updates the control in the touch bar. Possible values: diff --git a/docs/api/web-utils.md b/docs/api/web-utils.md index 4b0c7a0544..2162d9b36c 100644 --- a/docs/api/web-utils.md +++ b/docs/api/web-utils.md @@ -14,7 +14,7 @@ The `webUtils` module has the following methods: Returns `string` - The file system path that this `File` object points to. In the case where the object passed in is not a `File` object an exception is thrown. In the case where the File object passed in was constructed in JS and is not backed by a file on disk an empty string is returned. -This method superceded the previous augmentation to the `File` object with the `path` property. An example is included below. +This method superseded the previous augmentation to the `File` object with the `path` property. An example is included below. ```js // Before
fix
1aeca6fd0e988cfc4f82322a19da034f190134b3
reito
2024-08-23 08:23:13
feat: GPU shared texture offscreen rendering (#42953) * feat: GPU shared texture offscreen rendering * docs: clarify texture infos that passed by the paint event. * feat: make gpu osr spec test optional * fix: osr image compare * fix: remove duplicate test * fix: update patch file * fix: code review * feat: expose more metadata * feat: use better switch design * feat: add warning when user forget to release the texture. * fix: typo * chore: update patch * fix: update patch * fix: update patch description * fix: update docs * fix: apply suggestions from code review Co-authored-by: Charles Kerr <[email protected]> * fix: apply suggested fixes --------- Co-authored-by: Charles Kerr <[email protected]>
diff --git a/docs/api/structures/offscreen-shared-texture.md b/docs/api/structures/offscreen-shared-texture.md new file mode 100644 index 0000000000..0de21db133 --- /dev/null +++ b/docs/api/structures/offscreen-shared-texture.md @@ -0,0 +1,24 @@ +# OffscreenSharedTexture Object + +* `textureInfo` Object - The shared texture info. + * `widgetType` string - The widget type of the texture. Can be `popup` or `frame`. + * `pixelFormat` string - The pixel format of the texture. Can be `rgba` or `bgra`. + * `codedSize` [Size](size.md) - The full dimensions of the video frame. + * `visibleRect` [Rectangle](rectangle.md) - A subsection of [0, 0, codedSize.width(), codedSize.height()]. In OSR case, it is expected to have the full section area. + * `contentRect` [Rectangle](rectangle.md) - The region of the video frame that capturer would like to populate. In OSR case, it is the same with `dirtyRect` that needs to be painted. + * `timestamp` number - The time in microseconds since the capture start. + * `metadata` Object - Extra metadata. See comments in src\media\base\video_frame_metadata.h for accurate details. + * `captureUpdateRect` [Rectangle](rectangle.md) (optional) - Updated area of frame, can be considered as the `dirty` area. + * `regionCaptureRect` [Rectangle](rectangle.md) (optional) - May reflect the frame's contents origin if region capture is used internally. + * `sourceSize` [Rectangle](rectangle.md) (optional) - Full size of the source frame. + * `frameCount` number (optional) - The increasing count of captured frame. May contain gaps if frames are dropped between two consecutively received frames. + * `sharedTextureHandle` Buffer _Windows_ _macOS_ - The handle to the shared texture. + * `planes` Object[] _Linux_ - Each plane's info of the shared texture. + * `stride` number - The strides and offsets in bytes to be used when accessing the buffers via a memory mapping. One per plane per entry. + * `offset` number - The strides and offsets in bytes to be used when accessing the buffers via a memory mapping. One per plane per entry. + * `size` number - Size in bytes of the plane. This is necessary to map the buffers. + * `fd` number - File descriptor for the underlying memory object (usually dmabuf). + * `modifier` string _Linux_ - The modifier is retrieved from GBM library and passed to EGL driver. +* `release` Function - Release the resources. The `texture` cannot be directly passed to another process, users need to maintain texture lifecycles in + main process, but it is safe to pass the `textureInfo` to another process. Only a limited number of textures can exist at the same time, so it's important + that you call `texture.release()` as soon as you're done with the texture. diff --git a/docs/api/structures/web-preferences.md b/docs/api/structures/web-preferences.md index 044cd2b227..414d9c6c3b 100644 --- a/docs/api/structures/web-preferences.md +++ b/docs/api/structures/web-preferences.md @@ -79,10 +79,14 @@ [browserWindow](../browser-window.md) has disabled `backgroundThrottling` then frames will be drawn and swapped for the whole window and other [webContents](../web-contents.md) displayed by it. Defaults to `true`. -* `offscreen` boolean (optional) - Whether to enable offscreen rendering for the browser +* `offscreen` Object | boolean (optional) - Whether to enable offscreen rendering for the browser window. Defaults to `false`. See the [offscreen rendering tutorial](../../tutorial/offscreen-rendering.md) for more details. + * `useSharedTexture` boolean (optional) _Experimental_ - Whether to use GPU shared texture for accelerated + paint event. Defaults to `false`. See the + [offscreen rendering tutorial](../../tutorial/offscreen-rendering.md) for + more details. * `contextIsolation` boolean (optional) - Whether to run Electron APIs and the specified `preload` script in a separate JavaScript context. Defaults to `true`. The context that the `preload` script runs in will only have diff --git a/docs/api/web-contents.md b/docs/api/web-contents.md index e099cefe02..e0feef19d2 100644 --- a/docs/api/web-contents.md +++ b/docs/api/web-contents.md @@ -869,12 +869,12 @@ app.whenReady().then(() => { Returns: -* `event` Event +* `details` Event\<\> + * `texture` [OffscreenSharedTexture](structures/offscreen-shared-texture.md) (optional) _Experimental_ - The GPU shared texture of the frame, when `webPreferences.offscreen.useSharedTexture` is `true`. * `dirtyRect` [Rectangle](structures/rectangle.md) * `image` [NativeImage](native-image.md) - The image data of the whole frame. -Emitted when a new frame is generated. Only the dirty area is passed in the -buffer. +Emitted when a new frame is generated. Only the dirty area is passed in the buffer. ```js const { BrowserWindow } = require('electron') @@ -886,6 +886,33 @@ win.webContents.on('paint', (event, dirty, image) => { win.loadURL('https://github.com') ``` +When using shared texture (set `webPreferences.offscreen.useSharedTexture` to `true`) feature, you can pass the texture handle to external rendering pipeline without the overhead of +copying data between CPU and GPU memory, with Chromium's hardware acceleration support. This feature is helpful for high-performance rendering scenarios. + +Only a limited number of textures can exist at the same time, so it's important that you call `texture.release()` as soon as you're done with the texture. +By managing the texture lifecycle by yourself, you can safely pass the `texture.textureInfo` to other processes through IPC. + +```js +const { BrowserWindow } = require('electron') + +const win = new BrowserWindow({ webPreferences: { offscreen: { useSharedTexture: true } } }) +win.webContents.on('paint', async (e, dirty, image) => { + if (e.texture) { + // By managing lifecycle yourself, you can handle the event in async handler or pass the `e.texture.textureInfo` + // to other processes (not `e.texture`, the `e.texture.release` function is not passable through IPC). + await new Promise(resolve => setTimeout(resolve, 50)) + + // You can send the native texture handle to native code for importing into your rendering pipeline. + // For example: https://github.com/electron/electron/tree/main/spec/fixtures/native-addon/osr-gpu + // importTextureHandle(dirty, e.texture.textureInfo) + + // You must call `e.texture.release()` as soon as possible, before the underlying frame pool is drained. + e.texture.release() + } +}) +win.loadURL('https://github.com') +``` + #### Event: 'devtools-reload-page' Emitted when the devtools window instructs the webContents to reload diff --git a/docs/tutorial/offscreen-rendering.md b/docs/tutorial/offscreen-rendering.md index 5caab67ba1..06825fb13c 100644 --- a/docs/tutorial/offscreen-rendering.md +++ b/docs/tutorial/offscreen-rendering.md @@ -3,7 +3,8 @@ ## Overview Offscreen rendering lets you obtain the content of a `BrowserWindow` in a -bitmap, so it can be rendered anywhere, for example, on texture in a 3D scene. +bitmap or a shared GPU texture, so it can be rendered anywhere, for example, +on texture in a 3D scene. The offscreen rendering in Electron uses a similar approach to that of the [Chromium Embedded Framework](https://bitbucket.org/chromiumembedded/cef) project. @@ -17,22 +18,39 @@ the dirty area is passed to the `paint` event to be more efficient. losses with no benefits. * When nothing is happening on a webpage, no frames are generated. * An offscreen window is always created as a -[Frameless Window](../tutorial/window-customization.md).. +[Frameless Window](../tutorial/window-customization.md). ### Rendering Modes #### GPU accelerated -GPU accelerated rendering means that the GPU is used for composition. Because of -that, the frame has to be copied from the GPU which requires more resources, -thus this mode is slower than the Software output device. The benefit of this -mode is that WebGL and 3D CSS animations are supported. +GPU accelerated rendering means that the GPU is used for composition. The benefit +of this mode is that WebGL and 3D CSS animations are supported. There are two +different approaches depending on the `webPreferences.offscreen.useSharedTexture` +setting. + +1. Use GPU shared texture + + Used when `webPreferences.offscreen.useSharedTexture` is set to `true`. + + This is an advanced feature requiring a native node module to work with your own code. + The frames are directly copied in GPU textures, thus this mode is very fast because + there's no CPU-GPU memory copies overhead, and you can directly import the shared + texture to your own rendering program. + +2. Use CPU shared memory bitmap + + Used when `webPreferences.offscreen.useSharedTexture` is set to `false` (default behavior). + + The texture is accessible using the `NativeImage` API at the cost of performance. + The frame has to be copied from the GPU to the CPU bitmap which requires more system + resources, thus this mode is slower than the Software output device mode. But it supports + GPU related functionalities. #### Software output device This mode uses a software output device for rendering in the CPU, so the frame -generation is much faster. As a result, this mode is preferred over the GPU -accelerated one. +generation is faster than shared memory bitmap GPU accelerated mode. To enable this mode, GPU acceleration has to be disabled by calling the [`app.disableHardwareAcceleration()`][disablehardwareacceleration] API. diff --git a/filenames.auto.gni b/filenames.auto.gni index e4bbd4bd3c..9f70edb354 100644 --- a/filenames.auto.gni +++ b/filenames.auto.gni @@ -108,6 +108,7 @@ auto_filenames = { "docs/api/structures/navigation-entry.md", "docs/api/structures/notification-action.md", "docs/api/structures/notification-response.md", + "docs/api/structures/offscreen-shared-texture.md", "docs/api/structures/open-external-permission-request.md", "docs/api/structures/payment-discount.md", "docs/api/structures/permission-request.md", diff --git a/filenames.gni b/filenames.gni index 6ae9f9e70f..9a7e3d4e91 100644 --- a/filenames.gni +++ b/filenames.gni @@ -469,6 +469,8 @@ filenames = { "shell/browser/notifications/platform_notification_service.h", "shell/browser/osr/osr_host_display_client.cc", "shell/browser/osr/osr_host_display_client.h", + "shell/browser/osr/osr_paint_event.cc", + "shell/browser/osr/osr_paint_event.h", "shell/browser/osr/osr_render_widget_host_view.cc", "shell/browser/osr/osr_render_widget_host_view.h", "shell/browser/osr/osr_video_consumer.cc", @@ -612,6 +614,8 @@ filenames = { "shell/common/gin_converters/net_converter.cc", "shell/common/gin_converters/net_converter.h", "shell/common/gin_converters/optional_converter.h", + "shell/common/gin_converters/osr_converter.cc", + "shell/common/gin_converters/osr_converter.h", "shell/common/gin_converters/serial_port_info_converter.h", "shell/common/gin_converters/std_converter.h", "shell/common/gin_converters/time_converter.cc", diff --git a/patches/chromium/.patches b/patches/chromium/.patches index 4ed9630ec6..7c857e69b5 100644 --- a/patches/chromium/.patches +++ b/patches/chromium/.patches @@ -129,3 +129,4 @@ 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 +osr_shared_texture_remove_keyed_mutex_on_win_dxgi.patch diff --git a/patches/chromium/osr_shared_texture_remove_keyed_mutex_on_win_dxgi.patch b/patches/chromium/osr_shared_texture_remove_keyed_mutex_on_win_dxgi.patch new file mode 100644 index 0000000000..24104a6813 --- /dev/null +++ b/patches/chromium/osr_shared_texture_remove_keyed_mutex_on_win_dxgi.patch @@ -0,0 +1,97 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: reito <[email protected]> +Date: Thu, 15 Aug 2024 14:05:52 +0800 +Subject: Remove DXGI GMB keyed-mutex + +This patch removes the keyed mutex of the d3d11 texture only when the texture is requested by offscreen rendering and on Windows. + +The keyed mutex introduce extra performance cost and spikes. However, at offscreen rendering scenario, the shared resources will not be simultaneously read from & written to, typically just one reader, so it doesn't need such exclusive guarantee, and it's safe to remove this mutex for extra performance gain. + +For resolving complex conflict please pin @reitowo +For more reason please see: https://crrev.com/c/5465148 + +diff --git a/gpu/ipc/service/gpu_memory_buffer_factory_dxgi.cc b/gpu/ipc/service/gpu_memory_buffer_factory_dxgi.cc +index 2096591596a26464ab8f71a399ccb16a04edfd59..9eb966b3ddc3551d6beeff123071b2c99a576620 100644 +--- a/gpu/ipc/service/gpu_memory_buffer_factory_dxgi.cc ++++ b/gpu/ipc/service/gpu_memory_buffer_factory_dxgi.cc +@@ -179,7 +179,8 @@ gfx::GpuMemoryBufferHandle GpuMemoryBufferFactoryDXGI::CreateGpuMemoryBuffer( + // so make sure that the usage is one that we support. + DCHECK(usage == gfx::BufferUsage::GPU_READ || + usage == gfx::BufferUsage::SCANOUT || +- usage == gfx::BufferUsage::SCANOUT_CPU_READ_WRITE) ++ usage == gfx::BufferUsage::SCANOUT_CPU_READ_WRITE || ++ usage == gfx::BufferUsage::SCANOUT_VEA_CPU_READ) + << "Incorrect usage, usage=" << gfx::BufferUsageToString(usage); + + D3D11_TEXTURE2D_DESC desc = { +@@ -193,7 +194,9 @@ gfx::GpuMemoryBufferHandle GpuMemoryBufferFactoryDXGI::CreateGpuMemoryBuffer( + D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET, + 0, + D3D11_RESOURCE_MISC_SHARED_NTHANDLE | +- D3D11_RESOURCE_MISC_SHARED_KEYEDMUTEX}; ++ static_cast<UINT>(usage == gfx::BufferUsage::SCANOUT_VEA_CPU_READ ++ ? D3D11_RESOURCE_MISC_SHARED ++ : D3D11_RESOURCE_MISC_SHARED_KEYEDMUTEX)}; + + Microsoft::WRL::ComPtr<ID3D11Texture2D> d3d11_texture; + +diff --git a/media/video/renderable_gpu_memory_buffer_video_frame_pool.cc b/media/video/renderable_gpu_memory_buffer_video_frame_pool.cc +index 208d048ee68fd92d1fa7b5e8ad79e02e29b8be40..c8c8c32cd44a96dc6a476b8bc02bb13b02f86300 100644 +--- a/media/video/renderable_gpu_memory_buffer_video_frame_pool.cc ++++ b/media/video/renderable_gpu_memory_buffer_video_frame_pool.cc +@@ -205,7 +205,7 @@ gfx::Size GetBufferSizeInPixelsForVideoPixelFormat( + bool FrameResources::Initialize() { + auto* context = pool_->GetContext(); + +- constexpr gfx::BufferUsage kBufferUsage = ++ gfx::BufferUsage buffer_usage = + #if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_CHROMEOS) + gfx::BufferUsage::SCANOUT_VEA_CPU_READ + #else +@@ -219,6 +219,23 @@ bool FrameResources::Initialize() { + const gfx::Size buffer_size_in_pixels = + GetBufferSizeInPixelsForVideoPixelFormat(format_, coded_size_); + ++#if BUILDFLAG(IS_WIN) ++ // For CEF OSR feature, currently there's no other place in chromium use RGBA. ++ // If the format is RGBA, currently CEF do not write to the texture anymore ++ // once the GMB is returned from CopyRequest. So there will be no race ++ // condition on that texture. We can request a GMB without a keyed mutex to ++ // accelerate and probably prevent some driver deadlock. ++ if (format_ == PIXEL_FORMAT_ARGB || format_ == PIXEL_FORMAT_ABGR) { ++ // This value is 'borrowed', SCANOUT_VEA_CPU_READ is probably invalid ++ // cause there's no real SCANOUT on Windows. We simply use this enum as a ++ // flag to disable mutex in the GMBFactoryDXGI because this enum is also ++ // used above in macOS and CrOS for similar usage (claim no other one will ++ // concurrently use the resource). ++ // https://chromium-review.googlesource.com/c/chromium/src/+/5302103 ++ buffer_usage = gfx::BufferUsage::SCANOUT_VEA_CPU_READ; ++ } ++#endif ++ + // Create the GpuMemoryBuffer if MappableSharedImages is not enabled. When its + // enabled, clients only create a mappable shared image directly without + // needing to create a GMB. +@@ -226,11 +243,11 @@ bool FrameResources::Initialize() { + kUseMappableSIForRenderableGpuMemoryBufferVideoFramePool); + if (!is_mappable_si_enabled) { + gpu_memory_buffer_ = context->CreateGpuMemoryBuffer( +- buffer_size_in_pixels, buffer_format, kBufferUsage); ++ buffer_size_in_pixels, buffer_format, buffer_usage); + if (!gpu_memory_buffer_) { + LOG(ERROR) << "Failed to allocate GpuMemoryBuffer for frame: coded_size=" + << coded_size_.ToString() +- << ", usage=" << static_cast<int>(kBufferUsage); ++ << ", usage=" << static_cast<int>(buffer_usage); + return false; + } + +@@ -264,7 +281,7 @@ bool FrameResources::Initialize() { + + if (is_mappable_si_enabled) { + shared_image_ = context->CreateSharedImage( +- buffer_size_in_pixels, kBufferUsage, si_format, color_space_, ++ buffer_size_in_pixels, buffer_usage, si_format, color_space_, + kTopLeft_GrSurfaceOrigin, kPremul_SkAlphaType, kSharedImageUsage, + sync_token_); + } else { diff --git a/shell/browser/api/electron_api_web_contents.cc b/shell/browser/api/electron_api_web_contents.cc index c64a7f31b5..b4b067072f 100644 --- a/shell/browser/api/electron_api_web_contents.cc +++ b/shell/browser/api/electron_api_web_contents.cc @@ -121,6 +121,7 @@ #include "shell/common/gin_converters/image_converter.h" #include "shell/common/gin_converters/net_converter.h" #include "shell/common/gin_converters/optional_converter.h" +#include "shell/common/gin_converters/osr_converter.h" #include "shell/common/gin_converters/value_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/gin_helper/error_thrower.h" @@ -760,9 +761,23 @@ WebContents::WebContents(v8::Isolate* isolate, // Get transparent for guest view options.Get("transparent", &guest_transparent_); - bool b = false; - if (options.Get(options::kOffscreen, &b) && b) - type_ = Type::kOffScreen; + // Offscreen rendering + v8::Local<v8::Value> use_offscreen; + if (options.Get(options::kOffscreen, &use_offscreen)) { + if (use_offscreen->IsBoolean()) { + bool b = false; + if (options.Get(options::kOffscreen, &b) && b) { + type_ = Type::kOffScreen; + } + } else if (use_offscreen->IsObject()) { + type_ = Type::kOffScreen; + auto use_offscreen_dict = + gin_helper::Dictionary::CreateEmpty(options.isolate()); + options.Get(options::kOffscreen, &use_offscreen_dict); + use_offscreen_dict.Get(options::kUseSharedTexture, + &offscreen_use_shared_texture_); + } + } // Init embedder earlier options.Get("embedder", &embedder_); @@ -798,7 +813,7 @@ WebContents::WebContents(v8::Isolate* isolate, if (embedder_ && embedder_->IsOffScreen()) { auto* view = new OffScreenWebContentsView( - false, + false, offscreen_use_shared_texture_, base::BindRepeating(&WebContents::OnPaint, base::Unretained(this))); params.view = view; params.delegate_view = view; @@ -818,7 +833,7 @@ WebContents::WebContents(v8::Isolate* isolate, content::WebContents::CreateParams params(session->browser_context()); auto* view = new OffScreenWebContentsView( - transparent, + transparent, offscreen_use_shared_texture_, base::BindRepeating(&WebContents::OnPaint, base::Unretained(this))); params.view = view; params.delegate_view = view; @@ -3535,8 +3550,23 @@ bool WebContents::IsOffScreen() const { return type_ == Type::kOffScreen; } -void WebContents::OnPaint(const gfx::Rect& dirty_rect, const SkBitmap& bitmap) { - Emit("paint", dirty_rect, gfx::Image::CreateFrom1xBitmap(bitmap)); +void WebContents::OnPaint(const gfx::Rect& dirty_rect, + const SkBitmap& bitmap, + const OffscreenSharedTexture& tex) { + v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); + v8::HandleScope handle_scope(isolate); + + gin::Handle<gin_helper::internal::Event> event = + gin_helper::internal::Event::New(isolate); + v8::Local<v8::Object> event_object = event.ToV8().As<v8::Object>(); + gin_helper::Dictionary dict(isolate, event_object); + + if (offscreen_use_shared_texture_) { + dict.Set("texture", tex); + } + + EmitWithoutEvent("paint", event, dirty_rect, + gfx::Image::CreateFrom1xBitmap(bitmap)); } void WebContents::StartPainting() { diff --git a/shell/browser/api/electron_api_web_contents.h b/shell/browser/api/electron_api_web_contents.h index 90fd58fb68..50115824c8 100644 --- a/shell/browser/api/electron_api_web_contents.h +++ b/shell/browser/api/electron_api_web_contents.h @@ -37,6 +37,7 @@ #include "shell/browser/background_throttling_source.h" #include "shell/browser/event_emitter_mixin.h" #include "shell/browser/extended_web_contents_observer.h" +#include "shell/browser/osr/osr_paint_event.h" #include "shell/browser/ui/inspectable_web_contents_delegate.h" #include "shell/browser/ui/inspectable_web_contents_view_delegate.h" #include "shell/common/gin_helper/cleaned_up_at_exit.h" @@ -310,7 +311,9 @@ class WebContents : public ExclusiveAccessContext, // Methods for offscreen rendering bool IsOffScreen() const; - void OnPaint(const gfx::Rect& dirty_rect, const SkBitmap& bitmap); + void OnPaint(const gfx::Rect& dirty_rect, + const SkBitmap& bitmap, + const OffscreenSharedTexture& info); void StartPainting(); void StopPainting(); bool IsPainting() const; @@ -840,6 +843,9 @@ class WebContents : public ExclusiveAccessContext, bool offscreen_ = false; + // Whether offscreen rendering use gpu shared texture + bool offscreen_use_shared_texture_ = false; + // Whether window is fullscreened by HTML5 api. bool html_fullscreen_ = false; diff --git a/shell/browser/osr/osr_host_display_client.cc b/shell/browser/osr/osr_host_display_client.cc index 6311d21efb..6189efbe8e 100644 --- a/shell/browser/osr/osr_host_display_client.cc +++ b/shell/browser/osr/osr_host_display_client.cc @@ -69,7 +69,7 @@ void LayeredWindowUpdater::Draw(const gfx::Rect& damage_rect, if (active_ && canvas_->peekPixels(&pixmap)) { bitmap.installPixels(pixmap); - callback_.Run(damage_rect, bitmap); + callback_.Run(damage_rect, bitmap, {}); } std::move(draw_callback).Run(); diff --git a/shell/browser/osr/osr_host_display_client.h b/shell/browser/osr/osr_host_display_client.h index b0456ddb69..e95eb43bd1 100644 --- a/shell/browser/osr/osr_host_display_client.h +++ b/shell/browser/osr/osr_host_display_client.h @@ -11,15 +11,16 @@ #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 "shell/browser/osr/osr_paint_event.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&)> - OnPaintCallback; - class LayeredWindowUpdater : public viz::mojom::LayeredWindowUpdater { public: explicit LayeredWindowUpdater( diff --git a/shell/browser/osr/osr_host_display_client_mac.mm b/shell/browser/osr/osr_host_display_client_mac.mm index f171474323..406b07415a 100644 --- a/shell/browser/osr/osr_host_display_client_mac.mm +++ b/shell/browser/osr/osr_host_display_client_mac.mm @@ -32,7 +32,7 @@ void OffScreenHostDisplayClient::OnDisplayReceivedCALayerParams( kPremul_SkAlphaType), pixels, stride); bitmap.setImmutable(); - callback_.Run(ca_layer_params.damage, bitmap); + callback_.Run(ca_layer_params.damage, bitmap, {}); } } diff --git a/shell/browser/osr/osr_paint_event.cc b/shell/browser/osr/osr_paint_event.cc new file mode 100644 index 0000000000..505650f467 --- /dev/null +++ b/shell/browser/osr/osr_paint_event.cc @@ -0,0 +1,31 @@ + +// Copyright (c) 2024 GitHub, Inc. +// Use of this source code is governed by the MIT license that can be found in +// the LICENSE file. + +#include "shell/browser/osr/osr_paint_event.h" + +namespace electron { + +OffscreenNativePixmapPlaneInfo::~OffscreenNativePixmapPlaneInfo() = default; +OffscreenNativePixmapPlaneInfo::OffscreenNativePixmapPlaneInfo( + const OffscreenNativePixmapPlaneInfo& other) = default; +OffscreenNativePixmapPlaneInfo::OffscreenNativePixmapPlaneInfo(uint32_t stride, + uint64_t offset, + uint64_t size, + int fd) + : stride(stride), offset(offset), size(size), fd(fd) {} + +OffscreenReleaserHolder::~OffscreenReleaserHolder() = default; +OffscreenReleaserHolder::OffscreenReleaserHolder( + gfx::GpuMemoryBufferHandle gmb_handle, + mojo::PendingRemote<viz::mojom::FrameSinkVideoConsumerFrameCallbacks> + releaser) + : gmb_handle(std::move(gmb_handle)), releaser(std::move(releaser)) {} + +OffscreenSharedTextureValue::OffscreenSharedTextureValue() = default; +OffscreenSharedTextureValue::~OffscreenSharedTextureValue() = default; +OffscreenSharedTextureValue::OffscreenSharedTextureValue( + const OffscreenSharedTextureValue& other) = default; + +} // namespace electron diff --git a/shell/browser/osr/osr_paint_event.h b/shell/browser/osr/osr_paint_event.h new file mode 100644 index 0000000000..70985418fc --- /dev/null +++ b/shell/browser/osr/osr_paint_event.h @@ -0,0 +1,113 @@ + +// Copyright (c) 2024 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_OSR_OSR_PAINT_EVENT_H +#define ELECTRON_SHELL_BROWSER_OSR_OSR_PAINT_EVENT_H + +#include "base/functional/callback_helpers.h" +#include "content/public/common/widget_type.h" +#include "media/base/video_types.h" +#include "mojo/public/cpp/bindings/pending_remote.h" +#include "services/viz/privileged/mojom/compositing/frame_sink_video_capture.mojom.h" +#include "third_party/skia/include/core/SkCanvas.h" +#include "ui/gfx/canvas.h" +#include "ui/gfx/native_widget_types.h" + +#include <cstdint> + +namespace electron { + +struct OffscreenNativePixmapPlaneInfo { + // The strides and offsets in bytes to be used when accessing the buffers + // via a memory mapping. One per plane per entry. Size in bytes of the + // plane is necessary to map the buffers. + uint32_t stride; + uint64_t offset; + uint64_t size; + + // File descriptor for the underlying memory object (usually dmabuf). + int fd; + + OffscreenNativePixmapPlaneInfo() = delete; + ~OffscreenNativePixmapPlaneInfo(); + OffscreenNativePixmapPlaneInfo(const OffscreenNativePixmapPlaneInfo& other); + OffscreenNativePixmapPlaneInfo(uint32_t stride, + uint64_t offset, + uint64_t size, + int fd); +}; + +struct OffscreenReleaserHolder { + OffscreenReleaserHolder() = delete; + ~OffscreenReleaserHolder(); + OffscreenReleaserHolder( + gfx::GpuMemoryBufferHandle gmb_handle, + mojo::PendingRemote<viz::mojom::FrameSinkVideoConsumerFrameCallbacks> + releaser); + + // GpuMemoryBufferHandle, keep the scoped handle alive + gfx::GpuMemoryBufferHandle gmb_handle; + + // Releaser, hold this to prevent FrameSinkVideoCapturer recycle frame + mojo::PendingRemote<viz::mojom::FrameSinkVideoConsumerFrameCallbacks> + releaser; +}; + +struct OffscreenSharedTextureValue { + OffscreenSharedTextureValue(); + ~OffscreenSharedTextureValue(); + OffscreenSharedTextureValue(const OffscreenSharedTextureValue& other); + + // It is user's responsibility to compose popup widget textures. + content::WidgetType widget_type; + + // The pixel format of the shared texture, RGBA or BGRA depends on platform. + media::VideoPixelFormat pixel_format; + + // The full dimensions of the video frame data. + gfx::Size coded_size; + + // A subsection of [0, 0, coded_size().width(), coded_size.height()]. + // In OSR case, it is expected to have the full area of the section. + gfx::Rect visible_rect; + + // The region of the video frame that capturer would like to populate. + // In OSR case, it is the same with `dirtyRect` that needs to be painted. + gfx::Rect content_rect; + + // Extra metadata for the video frame. + // See comments in src\media\base\video_frame_metadata.h for more details. + std::optional<gfx::Rect> capture_update_rect; + std::optional<gfx::Size> source_size; + std::optional<gfx::Rect> region_capture_rect; + + // The capture timestamp, microseconds since capture start + int64_t timestamp; + + // The frame count + int64_t frame_count; + + // Releaser holder + raw_ptr<OffscreenReleaserHolder> releaser_holder; + +#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC) + // On Windows it is a HANDLE to the shared D3D11 texture. + // On macOS it is a IOSurface* to the shared IOSurface. + uintptr_t shared_texture_handle; +#elif BUILDFLAG(IS_LINUX) + std::vector<OffscreenNativePixmapPlaneInfo> planes; + uint64_t modifier; +#endif +}; + +typedef std::optional<OffscreenSharedTextureValue> OffscreenSharedTexture; + +typedef base::RepeatingCallback< + void(const gfx::Rect&, const SkBitmap&, const OffscreenSharedTexture&)> + OnPaintCallback; + +} // namespace electron + +#endif // ELECTRON_SHELL_BROWSER_OSR_OSR_PAINT_EVENT_H diff --git a/shell/browser/osr/osr_render_widget_host_view.cc b/shell/browser/osr/osr_render_widget_host_view.cc index 6b62ae3c5a..c7b0a1b6dc 100644 --- a/shell/browser/osr/osr_render_widget_host_view.cc +++ b/shell/browser/osr/osr_render_widget_host_view.cc @@ -177,6 +177,7 @@ class ElectronDelegatedFrameHostClient OffScreenRenderWidgetHostView::OffScreenRenderWidgetHostView( bool transparent, + bool offscreen_use_shared_texture, bool painting, int frame_rate, const OnPaintCallback& callback, @@ -187,6 +188,7 @@ OffScreenRenderWidgetHostView::OffScreenRenderWidgetHostView( render_widget_host_(content::RenderWidgetHostImpl::From(host)), parent_host_view_(parent_host_view), transparent_(transparent), + offscreen_use_shared_texture_(offscreen_use_shared_texture), callback_(callback), frame_rate_(frame_rate), size_(initial_size), @@ -544,8 +546,9 @@ OffScreenRenderWidgetHostView::CreateViewForWidget( } return new OffScreenRenderWidgetHostView( - transparent_, true, embedder_host_view->frame_rate(), callback_, - render_widget_host, embedder_host_view, size()); + transparent_, offscreen_use_shared_texture_, true, + embedder_host_view->frame_rate(), callback_, render_widget_host, + embedder_host_view, size()); } const viz::FrameSinkId& OffScreenRenderWidgetHostView::GetFrameSinkId() const { @@ -654,8 +657,15 @@ uint64_t OffScreenRenderWidgetHostView::GetNSViewId() const { } #endif -void OffScreenRenderWidgetHostView::OnPaint(const gfx::Rect& damage_rect, - const SkBitmap& bitmap) { +void OffScreenRenderWidgetHostView::OnPaint( + const gfx::Rect& damage_rect, + const SkBitmap& bitmap, + const OffscreenSharedTexture& texture) { + if (texture.has_value()) { + callback_.Run(damage_rect, {}, texture); + return; + } + backing_ = std::make_unique<SkBitmap>(); backing_->allocN32Pixels(bitmap.width(), bitmap.height(), !transparent_); bitmap.readPixels(backing_->pixmap()); @@ -711,7 +721,7 @@ void OffScreenRenderWidgetHostView::CompositeFrame( } callback_.Run(gfx::IntersectRects(gfx::Rect(size_in_pixels), damage_rect), - frame); + frame, {}); ReleaseResize(); } diff --git a/shell/browser/osr/osr_render_widget_host_view.h b/shell/browser/osr/osr_render_widget_host_view.h index ec63862c06..d258fad30e 100644 --- a/shell/browser/osr/osr_render_widget_host_view.h +++ b/shell/browser/osr/osr_render_widget_host_view.h @@ -25,14 +25,17 @@ #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" @@ -59,8 +62,6 @@ class ElectronCopyFrameGenerator; class ElectronDelegatedFrameHostClient; class OffScreenHostDisplayClient; -using OnPaintCallback = - base::RepeatingCallback<void(const gfx::Rect&, const SkBitmap&)>; using OnPopupPaintCallback = base::RepeatingCallback<void(const gfx::Rect&)>; class OffScreenRenderWidgetHostView @@ -70,6 +71,7 @@ class OffScreenRenderWidgetHostView private OffscreenViewProxyObserver { public: OffScreenRenderWidgetHostView(bool transparent, + bool offscreen_use_shared_texture, bool painting, int frame_rate, const OnPaintCallback& callback, @@ -204,7 +206,9 @@ class OffScreenRenderWidgetHostView void RemoveViewProxy(OffscreenViewProxy* proxy); void ProxyViewDestroyed(OffscreenViewProxy* proxy) override; - void OnPaint(const gfx::Rect& damage_rect, const SkBitmap& bitmap); + void OnPaint(const gfx::Rect& damage_rect, + const SkBitmap& bitmap, + const OffscreenSharedTexture& texture); void OnPopupPaint(const gfx::Rect& damage_rect); void OnProxyViewPaint(const gfx::Rect& damage_rect) override; @@ -231,6 +235,10 @@ class OffScreenRenderWidgetHostView void SetFrameRate(int frame_rate); int frame_rate() const { return frame_rate_; } + bool offscreen_use_shared_texture() const { + return offscreen_use_shared_texture_; + } + ui::Layer* root_layer() const { return root_layer_.get(); } content::DelegatedFrameHost* delegated_frame_host() const { @@ -274,6 +282,7 @@ class OffScreenRenderWidgetHostView std::set<OffscreenViewProxy*> proxy_views_; const bool transparent_; + const bool offscreen_use_shared_texture_; OnPaintCallback callback_; OnPopupPaintCallback parent_callback_; diff --git a/shell/browser/osr/osr_video_consumer.cc b/shell/browser/osr/osr_video_consumer.cc index 516b414e2d..62efaf6261 100644 --- a/shell/browser/osr/osr_video_consumer.cc +++ b/shell/browser/osr/osr_video_consumer.cc @@ -16,21 +16,6 @@ #include "third_party/skia/include/core/SkRegion.h" #include "ui/gfx/skbitmap_operations.h" -namespace { - -bool IsValidMinAndMaxFrameSize(gfx::Size min_frame_size, - gfx::Size max_frame_size) { - // Returns true if - // 0 < |min_frame_size| <= |max_frame_size| <= media::limits::kMaxDimension. - return 0 < min_frame_size.width() && 0 < min_frame_size.height() && - min_frame_size.width() <= max_frame_size.width() && - min_frame_size.height() <= max_frame_size.height() && - max_frame_size.width() <= media::limits::kMaxDimension && - max_frame_size.height() <= media::limits::kMaxDimension; -} - -} // namespace - namespace electron { OffScreenVideoConsumer::OffScreenVideoConsumer( @@ -43,7 +28,23 @@ OffScreenVideoConsumer::OffScreenVideoConsumer( video_capturer_->SetMinSizeChangePeriod(base::TimeDelta()); video_capturer_->SetFormat(media::PIXEL_FORMAT_ARGB); - SizeChanged(view_->SizeInPixels()); + // Previous design of OSR try to set the resolution constraint to match the + // view's size. It is actually not necessary and creates faulty textures + // when the window/view's size changes frequently. The constraint may not + // take effect before the internal frame size changes, and makes the capturer + // try to resize the new frame size to the old constraint size, which makes + // the output image blurry. (For example, small window suddenly expands to + // maximum size, will actually produce a small output image with maximized + // window resized to fit the small image, however, the expected output is + // a maximized image without resizing). + // So, we just set the constraint to no limit (1x1 to max). When the window + // size changed, a new frame with new size will be automatically generated. + // There's no need to manually set the constraint and request a new frame. + video_capturer_->SetResolutionConstraints( + gfx::Size(1, 1), + gfx::Size(media::limits::kMaxDimension, media::limits::kMaxDimension), + false); + SetFrameRate(view_->frame_rate()); } @@ -51,7 +52,10 @@ OffScreenVideoConsumer::~OffScreenVideoConsumer() = default; void OffScreenVideoConsumer::SetActive(bool active) { if (active) { - video_capturer_->Start(this, viz::mojom::BufferFormatPreference::kDefault); + video_capturer_->Start( + this, view_->offscreen_use_shared_texture() + ? viz::mojom::BufferFormatPreference::kPreferGpuMemoryBuffer + : viz::mojom::BufferFormatPreference::kDefault); } else { video_capturer_->Stop(); } @@ -61,43 +65,77 @@ void OffScreenVideoConsumer::SetFrameRate(int frame_rate) { video_capturer_->SetMinCapturePeriod(base::Seconds(1) / frame_rate); } -void OffScreenVideoConsumer::SizeChanged(const gfx::Size& size_in_pixels) { - DCHECK(IsValidMinAndMaxFrameSize(size_in_pixels, size_in_pixels)); - video_capturer_->SetResolutionConstraints(size_in_pixels, size_in_pixels, - true); - video_capturer_->RequestRefreshFrame(); -} - void OffScreenVideoConsumer::OnFrameCaptured( ::media::mojom::VideoBufferHandlePtr data, ::media::mojom::VideoFrameInfoPtr info, const gfx::Rect& content_rect, mojo::PendingRemote<viz::mojom::FrameSinkVideoConsumerFrameCallbacks> callbacks) { - auto& data_region = data->get_read_only_shmem_region(); - - if (!CheckContentRect(content_rect)) { - SizeChanged(view_->SizeInPixels()); + // Since we don't call ProvideFeedback, just need Done to release the frame, + // there's no need to call the callbacks, see in_flight_frame_delivery.cc + // The destructor will call Done for us once the pipe closed. + + // Offscreen using GPU shared texture + if (view_->offscreen_use_shared_texture()) { + CHECK(data->is_gpu_memory_buffer_handle()); + + auto& orig_handle = data->get_gpu_memory_buffer_handle(); + CHECK(!orig_handle.is_null()); + + // Clone the handle to support keep the handle alive after the callback + auto gmb_handle = orig_handle.Clone(); + + OffscreenSharedTextureValue texture; + texture.pixel_format = info->pixel_format; + texture.coded_size = info->coded_size; + texture.visible_rect = info->visible_rect; + texture.content_rect = content_rect; + texture.timestamp = info->timestamp.InMicroseconds(); + texture.frame_count = info->metadata.capture_counter.value_or(0); + texture.capture_update_rect = info->metadata.capture_update_rect; + texture.source_size = info->metadata.source_size; + texture.region_capture_rect = info->metadata.region_capture_rect; + texture.widget_type = view_->GetWidgetType(); + +#if BUILDFLAG(IS_WIN) + texture.shared_texture_handle = + reinterpret_cast<uintptr_t>(gmb_handle.dxgi_handle.Get()); +#elif BUILDFLAG(IS_APPLE) + texture.shared_texture_handle = + reinterpret_cast<uintptr_t>(gmb_handle.io_surface.get()); +#elif BUILDFLAG(IS_LINUX) + const auto& native_pixmap = gmb_handle.native_pixmap_handle; + texture.modifier = native_pixmap.modifier; + for (const auto& plane : native_pixmap.planes) { + texture.planes.emplace_back(plane.stride, plane.offset, plane.size, + plane.fd.get()); + } +#endif + + // The release holder will be released from JS side when `release` called + texture.releaser_holder = new OffscreenReleaserHolder(std::move(gmb_handle), + std::move(callbacks)); + + callback_.Run(content_rect, {}, std::move(texture)); return; } - mojo::Remote<viz::mojom::FrameSinkVideoConsumerFrameCallbacks> - callbacks_remote(std::move(callbacks)); + // Regular shared texture capture using shared memory + const auto& data_region = data->get_read_only_shmem_region(); if (!data_region.IsValid()) { - callbacks_remote->Done(); return; } + base::ReadOnlySharedMemoryMapping mapping = data_region.Map(); if (!mapping.IsValid()) { DLOG(ERROR) << "Shared memory mapping failed."; - callbacks_remote->Done(); return; } + if (mapping.size() < media::VideoFrame::AllocationSize(info->pixel_format, info->coded_size)) { DLOG(ERROR) << "Shared memory size was less than expected."; - callbacks_remote->Done(); return; } @@ -127,30 +165,17 @@ void OffScreenVideoConsumer::OnFrameCaptured( [](void* addr, void* context) { delete static_cast<FramePinner*>(context); }, - new FramePinner{std::move(mapping), callbacks_remote.Unbind()}); + new FramePinner{std::move(mapping), std::move(callbacks)}); bitmap.setImmutable(); + // Since update_rect is already offset-ed with same origin of content_rect, + // there's nothing more to do with the imported bitmap. std::optional<gfx::Rect> update_rect = info->metadata.capture_update_rect; if (!update_rect.has_value() || update_rect->IsEmpty()) { update_rect = content_rect; } - callback_.Run(*update_rect, bitmap); -} - -bool OffScreenVideoConsumer::CheckContentRect(const gfx::Rect& content_rect) { - gfx::Size view_size = view_->SizeInPixels(); - gfx::Size content_size = content_rect.size(); - - if (std::abs(view_size.width() - content_size.width()) > 2) { - return false; - } - - if (std::abs(view_size.height() - content_size.height()) > 2) { - return false; - } - - return true; + callback_.Run(*update_rect, bitmap, {}); } } // namespace electron diff --git a/shell/browser/osr/osr_video_consumer.h b/shell/browser/osr/osr_video_consumer.h index 0c3fc85afd..78dc1518f2 100644 --- a/shell/browser/osr/osr_video_consumer.h +++ b/shell/browser/osr/osr_video_consumer.h @@ -14,14 +14,12 @@ #include "components/viz/host/client_frame_sink_video_capturer.h" #include "media/capture/mojom/video_capture_buffer.mojom-forward.h" #include "media/capture/mojom/video_capture_types.mojom.h" +#include "shell/browser/osr/osr_paint_event.h" namespace electron { class OffScreenRenderWidgetHostView; -typedef base::RepeatingCallback<void(const gfx::Rect&, const SkBitmap&)> - OnPaintCallback; - class OffScreenVideoConsumer : public viz::mojom::FrameSinkVideoConsumer { public: OffScreenVideoConsumer(OffScreenRenderWidgetHostView* view, @@ -34,7 +32,6 @@ class OffScreenVideoConsumer : public viz::mojom::FrameSinkVideoConsumer { void SetActive(bool active); void SetFrameRate(int frame_rate); - void SizeChanged(const gfx::Size& size_in_pixels); private: // viz::mojom::FrameSinkVideoConsumer implementation. @@ -49,8 +46,6 @@ class OffScreenVideoConsumer : public viz::mojom::FrameSinkVideoConsumer { void OnStopped() override {} void OnLog(const std::string& message) override {} - bool CheckContentRect(const gfx::Rect& content_rect); - OnPaintCallback callback_; raw_ptr<OffScreenRenderWidgetHostView> view_; diff --git a/shell/browser/osr/osr_web_contents_view.cc b/shell/browser/osr/osr_web_contents_view.cc index f58285d2e1..08be98de29 100644 --- a/shell/browser/osr/osr_web_contents_view.cc +++ b/shell/browser/osr/osr_web_contents_view.cc @@ -15,8 +15,11 @@ namespace electron { OffScreenWebContentsView::OffScreenWebContentsView( bool transparent, + bool offscreen_use_shared_texture, const OnPaintCallback& callback) - : transparent_(transparent), callback_(callback) { + : transparent_(transparent), + offscreen_use_shared_texture_(offscreen_use_shared_texture), + callback_(callback) { #if BUILDFLAG(IS_MAC) PlatformCreate(); #endif @@ -109,8 +112,8 @@ OffScreenWebContentsView::CreateViewForWidget( return static_cast<content::RenderWidgetHostViewBase*>(rwhv); return new OffScreenRenderWidgetHostView( - transparent_, painting_, GetFrameRate(), callback_, render_widget_host, - nullptr, GetSize()); + transparent_, offscreen_use_shared_texture_, painting_, GetFrameRate(), + callback_, render_widget_host, nullptr, GetSize()); } content::RenderWidgetHostViewBase* @@ -124,9 +127,9 @@ OffScreenWebContentsView::CreateViewForChildWidget( ? web_contents_impl->GetOuterWebContents()->GetRenderWidgetHostView() : web_contents_impl->GetRenderWidgetHostView()); - return new OffScreenRenderWidgetHostView(transparent_, painting_, - view->frame_rate(), callback_, - render_widget_host, view, GetSize()); + return new OffScreenRenderWidgetHostView( + transparent_, offscreen_use_shared_texture_, painting_, + view->frame_rate(), callback_, render_widget_host, view, GetSize()); } void OffScreenWebContentsView::RenderViewReady() { diff --git a/shell/browser/osr/osr_web_contents_view.h b/shell/browser/osr/osr_web_contents_view.h index 463b7f5689..c66a95ddc5 100644 --- a/shell/browser/osr/osr_web_contents_view.h +++ b/shell/browser/osr/osr_web_contents_view.h @@ -34,7 +34,9 @@ class OffScreenWebContentsView : public content::WebContentsView, public content::RenderViewHostDelegateView, private NativeWindowObserver { public: - OffScreenWebContentsView(bool transparent, const OnPaintCallback& callback); + OffScreenWebContentsView(bool transparent, + bool offscreen_use_shared_texture, + const OnPaintCallback& callback); ~OffScreenWebContentsView() override; void SetWebContents(content::WebContents*); @@ -105,6 +107,7 @@ class OffScreenWebContentsView : public content::WebContentsView, raw_ptr<NativeWindow> native_window_ = nullptr; const bool transparent_; + const bool offscreen_use_shared_texture_; bool painting_ = true; int frame_rate_ = 60; OnPaintCallback callback_; diff --git a/shell/common/gin_converters/osr_converter.cc b/shell/common/gin_converters/osr_converter.cc new file mode 100644 index 0000000000..b0828832db --- /dev/null +++ b/shell/common/gin_converters/osr_converter.cc @@ -0,0 +1,176 @@ + +// Copyright (c) 2024 GitHub, Inc. +// Use of this source code is governed by the MIT license that can be found in +// the LICENSE file. + +#include "shell/common/gin_converters/osr_converter.h" + +#include "gin/dictionary.h" +#include "v8-external.h" +#include "v8-function.h" + +#include <string> + +#include "base/containers/to_vector.h" +#include "shell/common/gin_converters/gfx_converter.h" +#include "shell/common/gin_converters/optional_converter.h" +#include "shell/common/node_includes.h" +#include "shell/common/process_util.h" + +namespace gin { + +namespace { +std::string OsrVideoPixelFormatToString(media::VideoPixelFormat format) { + switch (format) { + case media::PIXEL_FORMAT_ARGB: + return "bgra"; + case media::PIXEL_FORMAT_ABGR: + return "rgba"; + default: + NOTREACHED_NORETURN(); + } +} + +std::string OsrWidgetTypeToString(content::WidgetType type) { + switch (type) { + case content::WidgetType::kPopup: + return "popup"; + case content::WidgetType::kFrame: + return "frame"; + default: + NOTREACHED_NORETURN(); + } +} + +struct OffscreenReleaseHolderMonitor { + explicit OffscreenReleaseHolderMonitor( + electron::OffscreenReleaserHolder* holder) + : holder_(holder) { + CHECK(holder); + } + + void ReleaseTexture() { + delete holder_; + holder_ = nullptr; + } + + bool IsTextureReleased() const { return holder_ == nullptr; } + + v8::Persistent<v8::Value>* CreatePersistent(v8::Isolate* isolate, + v8::Local<v8::Value> value) { + persistent_ = std::make_unique<v8::Persistent<v8::Value>>(isolate, value); + return persistent_.get(); + } + + void ResetPersistent() const { persistent_->Reset(); } + + private: + raw_ptr<electron::OffscreenReleaserHolder> holder_; + std::unique_ptr<v8::Persistent<v8::Value>> persistent_; +}; + +} // namespace + +// static +v8::Local<v8::Value> Converter<electron::OffscreenSharedTextureValue>::ToV8( + v8::Isolate* isolate, + const electron::OffscreenSharedTextureValue& val) { + gin::Dictionary root(isolate, v8::Object::New(isolate)); + + // Create a monitor to hold the releaser holder, which enables us to + // monitor whether the user explicitly released the texture before + // GC collects the object. + auto* monitor = new OffscreenReleaseHolderMonitor(val.releaser_holder); + + auto releaserHolder = v8::External::New(isolate, monitor); + auto releaserFunc = [](const v8::FunctionCallbackInfo<v8::Value>& info) { + auto* holder = static_cast<OffscreenReleaseHolderMonitor*>( + info.Data().As<v8::External>()->Value()); + // Release the shared texture, so that future frames can be generated. + holder->ReleaseTexture(); + }; + auto releaser = v8::Function::New(isolate->GetCurrentContext(), releaserFunc, + releaserHolder) + .ToLocalChecked(); + + root.Set("release", releaser); + + gin::Dictionary dict(isolate, v8::Object::New(isolate)); + dict.Set("pixelFormat", OsrVideoPixelFormatToString(val.pixel_format)); + dict.Set("codedSize", val.coded_size); + dict.Set("visibleRect", val.visible_rect); + dict.Set("contentRect", val.content_rect); + dict.Set("timestamp", val.timestamp); + dict.Set("widgetType", OsrWidgetTypeToString(val.widget_type)); + + gin::Dictionary metadata(isolate, v8::Object::New(isolate)); + metadata.Set("captureUpdateRect", val.capture_update_rect); + metadata.Set("regionCaptureRect", val.region_capture_rect); + metadata.Set("sourceSize", val.source_size); + metadata.Set("frameCount", val.frame_count); + dict.Set("metadata", ConvertToV8(isolate, metadata)); + +#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC) + auto handle_buf = node::Buffer::Copy( + isolate, + reinterpret_cast<char*>( + const_cast<uintptr_t*>(&val.shared_texture_handle)), + sizeof(val.shared_texture_handle)); + dict.Set("sharedTextureHandle", handle_buf.ToLocalChecked()); +#elif BUILDFLAG(IS_LINUX) + auto v8_planes = base::ToVector(val.planes, [isolate](const auto& plane) { + gin::Dictionary v8_plane(isolate, v8::Object::New(isolate)); + v8_plane.Set("stride", plane.stride); + v8_plane.Set("offset", plane.offset); + v8_plane.Set("size", plane.size); + v8_plane.Set("fd", plane.fd); + return v8_plane; + }); + dict.Set("planes", v8_planes); + dict.Set("modifier", base::NumberToString(val.modifier)); +#endif + + root.Set("textureInfo", ConvertToV8(isolate, dict)); + auto root_local = ConvertToV8(isolate, root); + + // Create a persistent reference of the object, so that we can check the + // monitor again when GC collects this object. + auto* tex_persistent = monitor->CreatePersistent(isolate, root_local); + tex_persistent->SetWeak( + monitor, + [](const v8::WeakCallbackInfo<OffscreenReleaseHolderMonitor>& data) { + auto* monitor = data.GetParameter(); + if (!monitor->IsTextureReleased()) { + // Emit a warning when user didn't properly manually release the + // texture, output it in second pass callback. + data.SetSecondPassCallback([](const v8::WeakCallbackInfo< + OffscreenReleaseHolderMonitor>& data) { + auto* iso = data.GetIsolate(); + node::Environment* env = node::Environment::GetCurrent(iso); + + // Emit warning only once + static std::once_flag flag; + std::call_once(flag, [=] { + electron::EmitWarning( + env, + "[OSR TEXTURE LEAKED] When using OSR with " + "`useSharedTexture`, `texture.release()` " + "must be called explicitly as soon as the texture is " + "copied to your rendering system. " + "Otherwise, it will soon drain the underlying " + "framebuffer and prevent future frames from being generated.", + "SharedTextureOSRNotReleased"); + }); + }); + } + // We are responsible for resetting the persistent handle. + monitor->ResetPersistent(); + // Finally, release the holder monitor. + delete monitor; + }, + v8::WeakCallbackType::kParameter); + + return root_local; +} + +} // namespace gin diff --git a/shell/common/gin_converters/osr_converter.h b/shell/common/gin_converters/osr_converter.h new file mode 100644 index 0000000000..05e767f20a --- /dev/null +++ b/shell/common/gin_converters/osr_converter.h @@ -0,0 +1,23 @@ + +// Copyright (c) 2024 GitHub, 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_OSR_CONVERTER_H_ +#define ELECTRON_SHELL_COMMON_GIN_CONVERTERS_OSR_CONVERTER_H_ + +#include "gin/converter.h" +#include "shell/browser/osr/osr_paint_event.h" + +namespace gin { + +template <> +struct Converter<electron::OffscreenSharedTextureValue> { + static v8::Local<v8::Value> ToV8( + v8::Isolate* isolate, + const electron::OffscreenSharedTextureValue& val); +}; + +} // namespace gin + +#endif // ELECTRON_SHELL_COMMON_GIN_CONVERTERS_OSR_CONVERTER_H_ diff --git a/shell/common/options_switches.cc b/shell/common/options_switches.cc index a0ecacd7d7..918d5faf36 100644 --- a/shell/common/options_switches.cc +++ b/shell/common/options_switches.cc @@ -153,6 +153,8 @@ const char kAllowRunningInsecureContent[] = "allowRunningInsecureContent"; const char kOffscreen[] = "offscreen"; +const char kUseSharedTexture[] = "useSharedTexture"; + const char kNodeIntegrationInSubFrames[] = "nodeIntegrationInSubFrames"; // Disable window resizing when HTML Fullscreen API is activated. diff --git a/shell/common/options_switches.h b/shell/common/options_switches.h index 5903291a4c..6b99e9e79d 100644 --- a/shell/common/options_switches.h +++ b/shell/common/options_switches.h @@ -79,6 +79,7 @@ extern const char kSandbox[]; extern const char kWebSecurity[]; extern const char kAllowRunningInsecureContent[]; extern const char kOffscreen[]; +extern const char kUseSharedTexture[]; extern const char kNodeIntegrationInSubFrames[]; extern const char kDisableHtmlFullscreenWindowResize[]; extern const char kJavaScript[]; diff --git a/spec/api-browser-window-spec.ts b/spec/api-browser-window-spec.ts index f0b6fb3600..91a55b9932 100644 --- a/spec/api-browser-window-spec.ts +++ b/spec/api-browser-window-spec.ts @@ -15,6 +15,7 @@ import { HexColors, hasCapturableScreen, ScreenCapture } from './lib/screen-help import { once } from 'node:events'; import { setTimeout } from 'node:timers/promises'; import { setTimeout as syncSetTimeout } from 'node:timers'; +import { nativeImage } from 'electron'; const fixtures = path.resolve(__dirname, 'fixtures'); const mainFixtures = path.resolve(__dirname, 'fixtures'); @@ -374,7 +375,7 @@ describe('BrowserWindow module', () => { it('should emit did-fail-load event for files that do not exist', async () => { const didFailLoad = once(w.webContents, 'did-fail-load'); w.loadURL('file://a.txt'); - const [, code, desc,, isMainFrame] = await didFailLoad; + const [, code, desc, , isMainFrame] = await didFailLoad; expect(code).to.equal(-6); expect(desc).to.equal('ERR_FILE_NOT_FOUND'); expect(isMainFrame).to.equal(true); @@ -382,7 +383,7 @@ describe('BrowserWindow module', () => { it('should emit did-fail-load event for invalid URL', async () => { const didFailLoad = once(w.webContents, 'did-fail-load'); w.loadURL('http://example:port'); - const [, code, desc,, isMainFrame] = await didFailLoad; + const [, code, desc, , isMainFrame] = await didFailLoad; expect(desc).to.equal('ERR_INVALID_URL'); expect(code).to.equal(-300); expect(isMainFrame).to.equal(true); @@ -399,7 +400,7 @@ describe('BrowserWindow module', () => { it('should set `mainFrame = false` on did-fail-load events in iframes', async () => { const didFailLoad = once(w.webContents, 'did-fail-load'); w.loadFile(path.join(fixtures, 'api', 'did-fail-load-iframe.html')); - const [,,,, isMainFrame] = await didFailLoad; + const [, , , , isMainFrame] = await didFailLoad; expect(isMainFrame).to.equal(false); }); it('does not crash in did-fail-provisional-load handler', (done) => { @@ -413,7 +414,7 @@ describe('BrowserWindow module', () => { const data = Buffer.alloc(2 * 1024 * 1024).toString('base64'); const didFailLoad = once(w.webContents, 'did-fail-load'); w.loadURL(`data:image/png;base64,${data}`); - const [, code, desc,, isMainFrame] = await didFailLoad; + const [, code, desc, , isMainFrame] = await didFailLoad; expect(desc).to.equal('ERR_INVALID_URL'); expect(code).to.equal(-300); expect(isMainFrame).to.equal(true); @@ -4542,7 +4543,7 @@ describe('BrowserWindow module', () => { fs.unlinkSync(savePageHtmlPath); fs.rmdirSync(path.join(savePageDir, 'save_page_files')); fs.rmdirSync(savePageDir); - } catch {} + } catch { } }); it('should throw when passing relative paths', async () => { @@ -4590,7 +4591,7 @@ describe('BrowserWindow module', () => { try { await fs.promises.unlink(savePageMHTMLPath); await fs.promises.rmdir(tmpDir); - } catch {} + } catch { } }); it('should save page to disk with HTMLComplete', async () => { @@ -6367,7 +6368,7 @@ describe('BrowserWindow module', () => { it('creates offscreen window with correct size', async () => { const paint = once(w.webContents, 'paint') as Promise<[any, Electron.Rectangle, Electron.NativeImage]>; w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); - const [,, data] = await paint; + const [, , data] = await paint; expect(data.constructor.name).to.equal('NativeImage'); expect(data.isEmpty()).to.be.false('data is empty'); const size = data.getSize(); @@ -6465,6 +6466,52 @@ describe('BrowserWindow module', () => { }); }); + describe('offscreen rendering image', () => { + afterEach(closeAllWindows); + + const imagePath = path.join(fixtures, 'assets', 'osr.png'); + const targetImage = nativeImage.createFromPath(imagePath); + const nativeModulesEnabled = !process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS; + ifit(nativeModulesEnabled && ['win32'].includes(process.platform))('use shared texture, hardware acceleration enabled', (done) => { + const { ExtractPixels, InitializeGpu } = require('@electron-ci/osr-gpu'); + + try { + InitializeGpu(); + } catch (e) { + console.log('Failed to initialize GPU, this spec needs a valid GPU device. Skipping...'); + console.error(e); + done(); + return; + } + + const w = new BrowserWindow({ + show: false, + webPreferences: { + offscreen: { + useSharedTexture: true + } + }, + transparent: true, + frame: false, + width: 128, + height: 128 + }); + + w.webContents.once('paint', async (e, dirtyRect) => { + try { + expect(e.texture).to.be.not.null(); + const pixels = ExtractPixels(e.texture!.textureInfo); + const img = nativeImage.createFromBitmap(pixels, { width: dirtyRect.width, height: dirtyRect.height, scaleFactor: 1 }); + expect(img.toBitmap().equals(targetImage.toBitmap())).to.equal(true); + done(); + } catch (e) { + done(e); + } + }); + w.loadFile(imagePath); + }); + }); + describe('"transparent" option', () => { afterEach(closeAllWindows); diff --git a/spec/fixtures/assets/osr.png b/spec/fixtures/assets/osr.png new file mode 100644 index 0000000000..0310fdcf74 Binary files /dev/null and b/spec/fixtures/assets/osr.png differ diff --git a/spec/fixtures/native-addon/osr-gpu/binding.gyp b/spec/fixtures/native-addon/osr-gpu/binding.gyp new file mode 100644 index 0000000000..21e840d092 --- /dev/null +++ b/spec/fixtures/native-addon/osr-gpu/binding.gyp @@ -0,0 +1,16 @@ +{ + "targets": [ + { + "target_name": "osr-gpu", + "sources": ['napi_utils.h'], + "conditions": [ + ['OS=="win"', { + 'sources': ['binding_win.cc'], + 'link_settings': { + 'libraries': ['dxgi.lib', 'd3d11.lib', 'dxguid.lib'], + } + }], + ], + } + ] +} diff --git a/spec/fixtures/native-addon/osr-gpu/binding_win.cc b/spec/fixtures/native-addon/osr-gpu/binding_win.cc new file mode 100644 index 0000000000..2545aade52 --- /dev/null +++ b/spec/fixtures/native-addon/osr-gpu/binding_win.cc @@ -0,0 +1,197 @@ +#include <d3d11_1.h> +#include <dxgi1_2.h> +#include <js_native_api.h> +#include <node_api.h> +#include <wrl/client.h> + +#include <iostream> +#include <string> + +#include "napi_utils.h" + +namespace { + +Microsoft::WRL::ComPtr<ID3D11Device> device = nullptr; +Microsoft::WRL::ComPtr<ID3D11Device1> device1 = nullptr; +Microsoft::WRL::ComPtr<ID3D11DeviceContext> context = nullptr; + +UINT cached_width = 0; +UINT cached_height = 0; +Microsoft::WRL::ComPtr<ID3D11Texture2D> cached_staging_texture = nullptr; + +napi_value ExtractPixels(napi_env env, napi_callback_info info) { + size_t argc = 1; + napi_value args[1]; + napi_status status; + + status = napi_get_cb_info(env, info, &argc, args, NULL, NULL); + if (status != napi_ok) + return nullptr; + + if (argc != 1) { + napi_throw_error(env, nullptr, + "Wrong number of arguments, expected textureInfo"); + } + + auto textureInfo = args[0]; + + auto widgetType = NAPI_GET_PROPERTY_VALUE_STRING(textureInfo, "widgetType"); + auto pixelFormat = NAPI_GET_PROPERTY_VALUE_STRING(textureInfo, "pixelFormat"); + auto sharedTextureHandle = + NAPI_GET_PROPERTY_VALUE(textureInfo, "sharedTextureHandle"); + + size_t handleBufferSize; + uint8_t* handleBufferData; + napi_get_buffer_info(env, sharedTextureHandle, + reinterpret_cast<void**>(&handleBufferData), + &handleBufferSize); + + auto handle = *reinterpret_cast<HANDLE*>(handleBufferData); + std::cout << "ExtractPixels widgetType=" << widgetType + << " pixelFormat=" << pixelFormat + << " sharedTextureHandle=" << handle << std::endl; + + Microsoft::WRL::ComPtr<ID3D11Texture2D> shared_texture = nullptr; + HRESULT hr = + device1->OpenSharedResource1(handle, IID_PPV_ARGS(&shared_texture)); + if (FAILED(hr)) { + napi_throw_error(env, "osr-gpu", "Failed to open shared texture resource"); + return nullptr; + } + + // Extract the texture description + D3D11_TEXTURE2D_DESC desc; + shared_texture->GetDesc(&desc); + + // Cache the staging texture if it does not exist or size has changed + if (!cached_staging_texture || cached_width != desc.Width || + cached_height != desc.Height) { + if (cached_staging_texture) { + cached_staging_texture->Release(); + } + + desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ; + desc.Usage = D3D11_USAGE_STAGING; + desc.BindFlags = 0; + desc.MiscFlags = 0; + + std::cout << "Create staging Texture2D width=" << desc.Width + << " height=" << desc.Height << std::endl; + hr = device->CreateTexture2D(&desc, nullptr, &cached_staging_texture); + if (FAILED(hr)) { + napi_throw_error(env, "osr-gpu", "Failed to create staging texture"); + return nullptr; + } + + cached_width = desc.Width; + cached_height = desc.Height; + } + + // Copy the shared texture to the staging texture + context->CopyResource(cached_staging_texture.Get(), shared_texture.Get()); + + // Calculate the size of the buffer needed to hold the pixel data + // 4 bytes per pixel + size_t bufferSize = desc.Width * desc.Height * 4; + + // Create a NAPI buffer to hold the pixel data + napi_value result; + void* resultData; + status = napi_create_buffer(env, bufferSize, &resultData, &result); + if (status != napi_ok) { + napi_throw_error(env, "osr-gpu", "Failed to create buffer"); + return nullptr; + } + + // Map the staging texture to read the pixel data + D3D11_MAPPED_SUBRESOURCE mappedResource; + hr = context->Map(cached_staging_texture.Get(), 0, D3D11_MAP_READ, 0, + &mappedResource); + if (FAILED(hr)) { + napi_throw_error(env, "osr-gpu", "Failed to map the staging texture"); + return nullptr; + } + + // Copy the pixel data from the mapped resource to the NAPI buffer + const uint8_t* srcData = static_cast<const uint8_t*>(mappedResource.pData); + uint8_t* destData = static_cast<uint8_t*>(resultData); + for (UINT row = 0; row < desc.Height; ++row) { + memcpy(destData + row * desc.Width * 4, + srcData + row * mappedResource.RowPitch, desc.Width * 4); + } + + // Unmap the staging texture + context->Unmap(cached_staging_texture.Get(), 0); + return result; +} + +napi_value InitializeGpu(napi_env env, napi_callback_info info) { + HRESULT hr; + + // Feature levels supported + D3D_FEATURE_LEVEL feature_levels[] = {D3D_FEATURE_LEVEL_11_1}; + UINT num_feature_levels = ARRAYSIZE(feature_levels); + D3D_FEATURE_LEVEL feature_level; + + // This flag adds support for surfaces with a different color channel ordering + // than the default. It is required for compatibility with Direct2D. + UINT creation_flags = + D3D11_CREATE_DEVICE_BGRA_SUPPORT | D3D11_CREATE_DEVICE_DEBUG; + + // We need dxgi to share texture + Microsoft::WRL::ComPtr<IDXGIFactory2> dxgi_factory = nullptr; + Microsoft::WRL::ComPtr<IDXGIAdapter> adapter = nullptr; + hr = CreateDXGIFactory(IID_IDXGIFactory2, (void**)&dxgi_factory); + if (FAILED(hr)) { + napi_throw_error(env, "osr-gpu", "CreateDXGIFactory failed"); + return nullptr; + } + + hr = dxgi_factory->EnumAdapters(0, &adapter); + if (FAILED(hr)) { + napi_throw_error(env, "osr-gpu", "EnumAdapters failed"); + return nullptr; + } + + DXGI_ADAPTER_DESC adapter_desc; + adapter->GetDesc(&adapter_desc); + std::wcout << "Initializing DirectX with adapter: " + << adapter_desc.Description << std::endl; + + hr = D3D11CreateDevice(adapter.Get(), D3D_DRIVER_TYPE_UNKNOWN, nullptr, + creation_flags, feature_levels, num_feature_levels, + D3D11_SDK_VERSION, &device, &feature_level, &context); + if (FAILED(hr)) { + napi_throw_error(env, "osr-gpu", "D3D11CreateDevice failed"); + return nullptr; + } + + hr = device->QueryInterface(IID_PPV_ARGS(&device1)); + if (FAILED(hr)) { + napi_throw_error(env, "osr-gpu", "Failed to open d3d11_1 device"); + return nullptr; + } + + return nullptr; +} + +napi_value Init(napi_env env, napi_value exports) { + napi_status status; + napi_property_descriptor descriptors[] = { + {"ExtractPixels", NULL, ExtractPixels, NULL, NULL, NULL, napi_default, + NULL}, + {"InitializeGpu", NULL, InitializeGpu, NULL, NULL, NULL, napi_default, + NULL}}; + + status = napi_define_properties( + env, exports, sizeof(descriptors) / sizeof(*descriptors), descriptors); + if (status != napi_ok) + return NULL; + + std::cout << "Initialized osr-gpu native module" << std::endl; + return exports; +} + +} // namespace + +NAPI_MODULE(NODE_GYP_MODULE_NAME, Init) diff --git a/spec/fixtures/native-addon/osr-gpu/lib/osr-gpu.js b/spec/fixtures/native-addon/osr-gpu/lib/osr-gpu.js new file mode 100644 index 0000000000..4f4ea51a8b --- /dev/null +++ b/spec/fixtures/native-addon/osr-gpu/lib/osr-gpu.js @@ -0,0 +1 @@ +module.exports = require('../build/Release/osr-gpu.node'); diff --git a/spec/fixtures/native-addon/osr-gpu/napi_utils.h b/spec/fixtures/native-addon/osr-gpu/napi_utils.h new file mode 100644 index 0000000000..40bcce30d9 --- /dev/null +++ b/spec/fixtures/native-addon/osr-gpu/napi_utils.h @@ -0,0 +1,33 @@ +#define NAPI_CREATE_STRING(str) \ + [&]() { \ + napi_value value; \ + napi_create_string_utf8(env, str, NAPI_AUTO_LENGTH, &value); \ + return value; \ + }() + +#define NAPI_GET_PROPERTY_VALUE(obj, field) \ + [&]() { \ + napi_value value; \ + napi_get_property(env, obj, NAPI_CREATE_STRING(field), &value); \ + return value; \ + }() + +#define NAPI_GET_PROPERTY_VALUE_STRING(obj, field) \ + [&]() { \ + auto val = NAPI_GET_PROPERTY_VALUE(obj, field); \ + size_t size; \ + napi_get_value_string_utf8(env, val, nullptr, 0, &size); \ + char* buffer = new char[size + 1]; \ + napi_get_value_string_utf8(env, val, buffer, size + 1, &size); \ + return std::string(buffer); \ + }() + +#define NAPI_GET_PROPERTY_VALUE_BUFFER(obj, field) \ + [&]() { \ + auto val = NAPI_GET_PROPERTY_VALUE(obj, field); \ + size_t size; \ + napi_create_buffer(env, val, nullptr, 0, &size); \ + char* buffer = new char[size + 1]; \ + napi_get_value_string_utf8(env, val, buffer, size + 1, &size); \ + return std::string(buffer); \ + }() \ No newline at end of file diff --git a/spec/fixtures/native-addon/osr-gpu/package.json b/spec/fixtures/native-addon/osr-gpu/package.json new file mode 100644 index 0000000000..13f78a53ba --- /dev/null +++ b/spec/fixtures/native-addon/osr-gpu/package.json @@ -0,0 +1,5 @@ +{ + "main": "./lib/osr-gpu.js", + "name": "@electron-ci/osr-gpu", + "version": "0.0.1" +} diff --git a/spec/package.json b/spec/package.json index 8455bdb996..2ac606b1b6 100644 --- a/spec/package.json +++ b/spec/package.json @@ -10,6 +10,7 @@ "@electron-ci/echo": "file:./fixtures/native-addon/echo", "@electron-ci/is-valid-window": "file:./is-valid-window", "@electron-ci/uv-dlopen": "file:./fixtures/native-addon/uv-dlopen/", + "@electron-ci/osr-gpu": "file:./fixtures/native-addon/osr-gpu/", "@electron/fuses": "^1.8.0", "@electron/packager": "^18.3.2", "@marshallofsound/mocha-appveyor-reporter": "^0.4.3", diff --git a/spec/yarn.lock b/spec/yarn.lock index d9bf04094c..a0dcd5a871 100644 --- a/spec/yarn.lock +++ b/spec/yarn.lock @@ -10,6 +10,9 @@ dependencies: nan "2.x" +"@electron-ci/osr-gpu@file:./fixtures/native-addon/osr-gpu": + version "0.0.1" + "@electron-ci/uv-dlopen@file:./fixtures/native-addon/uv-dlopen": version "0.0.1"
feat
44ebc1b1c2085486b321dd2f242ee60f4f75cf63
John Kleinschmidt
2024-05-13 18:46:59
chore: update patches after #42126 was merged (#42153)
diff --git a/patches/chromium/fix_partially_revert_invalidate_focusring.patch b/patches/chromium/fix_partially_revert_invalidate_focusring.patch index 614f42b4ac..3e61136b6c 100644 --- a/patches/chromium/fix_partially_revert_invalidate_focusring.patch +++ b/patches/chromium/fix_partially_revert_invalidate_focusring.patch @@ -10,10 +10,10 @@ distros. This patch can be reverted when the issue is fixed upstream, or when the crash is addressed. diff --git a/ui/views/view.cc b/ui/views/view.cc -index 94b026cda4738e489f1d7201c996f6db70d018ed..32ec794f4683be5ded78dcf310d3623b8748c236 100644 +index 4116b2a3fad02e1060bb7b137804753cf97dd7ca..46d3b426f54041efe4270bfda453358418fff160 100644 --- a/ui/views/view.cc +++ b/ui/views/view.cc -@@ -911,16 +911,6 @@ void View::Layout(PassKey) { +@@ -928,16 +928,6 @@ void View::Layout(PassKey) { } void View::InvalidateLayout() { @@ -30,7 +30,7 @@ index 94b026cda4738e489f1d7201c996f6db70d018ed..32ec794f4683be5ded78dcf310d3623b // We should never need to invalidate during a layout call; this tracks // how many times that is happening. ++invalidates_during_layout_; -@@ -928,11 +918,6 @@ void View::InvalidateLayout() { +@@ -945,11 +935,6 @@ void View::InvalidateLayout() { // Always invalidate up. This is needed to handle the case of us already being // valid, but not our parent. needs_layout_ = true; @@ -43,10 +43,10 @@ index 94b026cda4738e489f1d7201c996f6db70d018ed..32ec794f4683be5ded78dcf310d3623b GetLayoutManager()->InvalidateLayout(); } diff --git a/ui/views/view.h b/ui/views/view.h -index ea7d5441dbbfb713a6ffb57bcc07fb55fa574016..54b4c0a2871f214a4806fd863f32b8d010c09058 100644 +index 8f377e417231698b9146d5b79dc14730e34260f7..9936899e10505f57d3b465d5613d90df8d18ded3 100644 --- a/ui/views/view.h +++ b/ui/views/view.h -@@ -2343,9 +2343,6 @@ class VIEWS_EXPORT View : public ui::LayerDelegate, +@@ -2339,9 +2339,6 @@ class VIEWS_EXPORT View : public ui::LayerDelegate, // it is happening. int invalidates_during_layout_ = 0;
chore
85df2a86dda7b99af99310566601ee04b72e55c8
Krzysztof Halwa
2024-05-30 21:45:35
feat: Allow WebContentsView to accept webContents object. (#42086) feat: Allow WebContentsView to accept webContents object
diff --git a/docs/api/web-contents-view.md b/docs/api/web-contents-view.md index b4d6b4c93c..66bb257cf0 100644 --- a/docs/api/web-contents-view.md +++ b/docs/api/web-contents-view.md @@ -36,8 +36,9 @@ Process: [Main](../glossary.md#main-process) * `options` Object (optional) * `webPreferences` [WebPreferences](structures/web-preferences.md) (optional) - Settings of web page's features. + * `webContents` [WebContents](web-contents.md) (optional) - If present, the given WebContents will be adopted by the WebContentsView. A WebContents may only be presented in one WebContentsView at a time. -Creates an empty WebContentsView. +Creates a WebContentsView. ### Instance Properties diff --git a/shell/browser/api/electron_api_web_contents_view.cc b/shell/browser/api/electron_api_web_contents_view.cc index bb09e53515..0d1bdd5cb3 100644 --- a/shell/browser/api/electron_api_web_contents_view.cc +++ b/shell/browser/api/electron_api_web_contents_view.cc @@ -138,6 +138,7 @@ v8::Local<v8::Function> WebContentsView::GetConstructor(v8::Isolate* isolate) { // static gin_helper::WrappableBase* WebContentsView::New(gin_helper::Arguments* args) { gin_helper::Dictionary web_preferences; + v8::Local<v8::Value> existing_web_contents_value; { v8::Local<v8::Value> options_value; if (args->GetNext(&options_value)) { @@ -154,12 +155,33 @@ gin_helper::WrappableBase* WebContentsView::New(gin_helper::Arguments* args) { return nullptr; } } + + if (options.Get("webContents", &existing_web_contents_value)) { + gin::Handle<WebContents> existing_web_contents; + if (!gin::ConvertFromV8(args->isolate(), existing_web_contents_value, + &existing_web_contents)) { + args->ThrowError("options.webContents must be a WebContents"); + return nullptr; + } + + if (existing_web_contents->owner_window() != nullptr) { + args->ThrowError( + "options.webContents is already attached to a window"); + return nullptr; + } + } } } + if (web_preferences.IsEmpty()) web_preferences = gin_helper::Dictionary::CreateEmpty(args->isolate()); if (!web_preferences.Has(options::kShow)) web_preferences.Set(options::kShow, false); + + if (!existing_web_contents_value.IsEmpty()) { + web_preferences.SetHidden("webContents", existing_web_contents_value); + } + auto web_contents = WebContents::CreateFromWebPreferences(args->isolate(), web_preferences); diff --git a/spec/api-web-contents-view-spec.ts b/spec/api-web-contents-view-spec.ts index 70447ad399..dbfa1d17db 100644 --- a/spec/api-web-contents-view-spec.ts +++ b/spec/api-web-contents-view-spec.ts @@ -1,8 +1,10 @@ import { closeAllWindows } from './lib/window-helpers'; import { expect } from 'chai'; -import { BaseWindow, View, WebContentsView } from 'electron/main'; +import { BaseWindow, View, WebContentsView, webContents } from 'electron/main'; import { once } from 'node:events'; +import { defer } from './lib/spec-helpers'; +import { BrowserWindow } from 'electron'; describe('WebContentsView', () => { afterEach(closeAllWindows); @@ -17,6 +19,48 @@ describe('WebContentsView', () => { new WebContentsView({}); }); + it('accepts existing webContents object', async () => { + const currentWebContentsCount = webContents.getAllWebContents().length; + + const wc = (webContents as typeof ElectronInternal.WebContents).create({ sandbox: true }); + defer(() => wc.destroy()); + await wc.loadURL('about:blank'); + + const webContentsView = new WebContentsView({ + webContents: wc + }); + + expect(webContentsView.webContents).to.eq(wc); + expect(webContents.getAllWebContents().length).to.equal(currentWebContentsCount + 1, 'expected only single webcontents to be created'); + }); + + it('should throw error when created with already attached webContents to BrowserWindow', () => { + const browserWindow = new BrowserWindow(); + defer(() => browserWindow.webContents.destroy()); + + const webContentsView = new WebContentsView(); + defer(() => webContentsView.webContents.destroy()); + + browserWindow.contentView.addChildView(webContentsView); + defer(() => browserWindow.contentView.removeChildView(webContentsView)); + + expect(() => new WebContentsView({ + webContents: webContentsView.webContents + })).to.throw('options.webContents is already attached to a window'); + }); + + it('should throw error when created with already attached webContents to other WebContentsView', () => { + const browserWindow = new BrowserWindow(); + + const webContentsView = new WebContentsView(); + defer(() => webContentsView.webContents.destroy()); + webContentsView.webContents.loadURL('about:blank'); + + expect(() => new WebContentsView({ + webContents: browserWindow.webContents + })).to.throw('options.webContents is already attached to a window'); + }); + it('can be used as content view', () => { const w = new BaseWindow({ show: false }); w.setContentView(new WebContentsView());
feat
d7099b0ad4594284eb3143d6839e167c1a9b1a44
Keeley Hammond
2024-05-14 15:02:24
chore: cherry-pick b3c01ac1e60a from v8 (#42172) * chore: cherry-pick b3c01ac1e60a from v8 * chore: update patches --------- Co-authored-by: PatchUp <73610968+patchup[bot]@users.noreply.github.com>
diff --git a/patches/v8/.patches b/patches/v8/.patches index 02b472b1a7..7704cdbd32 100644 --- a/patches/v8/.patches +++ b/patches/v8/.patches @@ -2,3 +2,4 @@ chore_allow_customizing_microtask_policy_per_context.patch deps_add_v8_object_setinternalfieldfornodecore.patch revert_heap_add_checks_position_info.patch cherry-pick-f320600cd1f4.patch +cherry-pick-b3c01ac1e60a.patch diff --git a/patches/v8/cherry-pick-b3c01ac1e60a.patch b/patches/v8/cherry-pick-b3c01ac1e60a.patch new file mode 100644 index 0000000000..7b4ef2ad25 --- /dev/null +++ b/patches/v8/cherry-pick-b3c01ac1e60a.patch @@ -0,0 +1,76 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: Shu-yu Guo <[email protected]> +Date: Mon, 13 May 2024 11:23:20 -0700 +Subject: Don't build AccessInfo for storing to module exports + +Bug: 340221135 +Change-Id: I5af35be6ebf6a69db1c4687107503575b23973c4 +Reviewed-on: https://chromium-review.googlesource.com/c/v8/v8/+/5534518 +Reviewed-by: Adam Klein <[email protected]> +Commit-Queue: Shu-yu Guo <[email protected]> +Cr-Commit-Position: refs/heads/main@{#93872} + +diff --git a/src/compiler/access-info.cc b/src/compiler/access-info.cc +index 7cff878839c85cd9c6571ee48f1a0fce081f4471..9d022ba402d7bfdd5ca745a4193ee0de0e3d755e 100644 +--- a/src/compiler/access-info.cc ++++ b/src/compiler/access-info.cc +@@ -526,6 +526,14 @@ PropertyAccessInfo AccessorAccessInfoHelper( + Cell::cast(module_namespace->module()->exports()->Lookup( + isolate, name.object(), + Smi::ToInt(Object::GetHash(*name.object()))))); ++ if (IsAnyStore(access_mode)) { ++ // ES#sec-module-namespace-exotic-objects-set-p-v-receiver ++ // ES#sec-module-namespace-exotic-objects-defineownproperty-p-desc ++ // ++ // Storing to a module namespace object is always an error or a no-op in ++ // JS. ++ return PropertyAccessInfo::Invalid(zone); ++ } + if (IsTheHole(cell->value(kRelaxedLoad), isolate)) { + // This module has not been fully initialized yet. + return PropertyAccessInfo::Invalid(zone); +diff --git a/src/maglev/maglev-graph-builder.cc b/src/maglev/maglev-graph-builder.cc +index c5587be1e0b5d944d4b4b6f8d4f48f62c41db183..2a79c2bf27d18ee60b130bd0f8d6ff00493cab1e 100644 +--- a/src/maglev/maglev-graph-builder.cc ++++ b/src/maglev/maglev-graph-builder.cc +@@ -4116,19 +4116,28 @@ ReduceResult MaglevGraphBuilder::TryBuildPropertyStore( + access_info.holder().value()); + } + +- if (access_info.IsFastAccessorConstant()) { +- return TryBuildPropertySetterCall(access_info, receiver, +- GetAccumulatorTagged()); +- } else { +- DCHECK(access_info.IsDataField() || access_info.IsFastDataConstant()); +- ReduceResult res = TryBuildStoreField(access_info, receiver, access_mode); +- if (res.IsDone()) { +- RecordKnownProperty(receiver, name, +- current_interpreter_frame_.accumulator(), +- AccessInfoGuaranteedConst(access_info), access_mode); +- return res; ++ switch (access_info.kind()) { ++ case compiler::PropertyAccessInfo::kFastAccessorConstant: ++ return TryBuildPropertySetterCall(access_info, receiver, ++ GetAccumulatorTagged()); ++ case compiler::PropertyAccessInfo::kDataField: ++ case compiler::PropertyAccessInfo::kFastDataConstant: { ++ ReduceResult res = TryBuildStoreField(access_info, receiver, access_mode); ++ if (res.IsDone()) { ++ RecordKnownProperty( ++ receiver, name, current_interpreter_frame_.accumulator(), ++ AccessInfoGuaranteedConst(access_info), access_mode); ++ return res; ++ } ++ return ReduceResult::Fail(); + } +- return ReduceResult::Fail(); ++ case compiler::PropertyAccessInfo::kInvalid: ++ case compiler::PropertyAccessInfo::kNotFound: ++ case compiler::PropertyAccessInfo::kDictionaryProtoDataConstant: ++ case compiler::PropertyAccessInfo::kDictionaryProtoAccessorConstant: ++ case compiler::PropertyAccessInfo::kModuleExport: ++ case compiler::PropertyAccessInfo::kStringLength: ++ UNREACHABLE(); + } + } +
chore
80906c0adb1e1b8103dcdfb8340c4b660b330c25
Henrik Gaßmann
2024-02-16 20:29:29
fix: properly stream `uploadData` in `protocol.handle()` (#41052) * refactor(protocol): extract file stream factory Increase readability by moving the file stream creation logic out of the `uploadData` to request body conversion function. * fix: properly flatten streams in `protocol.handle()` Refs: electron/electron#39658 * fix: `protocol.handle()` filter null origin header Refs: electron/electron#40754 * fix: remove obsolete TODO comment Refs: electron/electron#38929 * fix: forward `Blob` parts in `protocol.handle()` Refs: electron/electron#40826 * fix: explicitly error out on unknown chunk parts
diff --git a/lib/browser/api/protocol.ts b/lib/browser/api/protocol.ts index 3d5f7cd96b..0bdec72983 100644 --- a/lib/browser/api/protocol.ts +++ b/lib/browser/api/protocol.ts @@ -29,6 +29,21 @@ function makeStreamFromPipe (pipe: any): ReadableStream { }); } +function makeStreamFromFileInfo ({ + filePath, + offset = 0, + length = -1 +}: { + filePath: string; + offset?: number; + length?: number; +}): ReadableStream { + return Readable.toWeb(createReadStream(filePath, { + start: offset, + end: length >= 0 ? offset + length : undefined + })); +} + function convertToRequestBody (uploadData: ProtocolRequest['uploadData']): RequestInit['body'] { if (!uploadData) return null; // Optimization: skip creating a stream if the request is just a single buffer. @@ -37,30 +52,42 @@ function convertToRequestBody (uploadData: ProtocolRequest['uploadData']): Reque const chunks = [...uploadData] as any[]; // TODO: types are wrong let current: ReadableStreamDefaultReader | null = null; return new ReadableStream({ - pull (controller) { + async pull (controller) { if (current) { - current.read().then(({ done, value }) => { + const { done, value } = await current.read(); + // (done => value === undefined) as per WHATWG spec + if (done) { + current = null; + return this.pull!(controller); + } else { controller.enqueue(value); - if (done) current = null; - }, (err) => { - controller.error(err); - }); + } } else { if (!chunks.length) { return controller.close(); } const chunk = chunks.shift()!; - if (chunk.type === 'rawData') { controller.enqueue(chunk.bytes); } else if (chunk.type === 'file') { - current = Readable.toWeb(createReadStream(chunk.filePath, { start: chunk.offset ?? 0, end: chunk.length >= 0 ? chunk.offset + chunk.length : undefined })).getReader(); - this.pull!(controller); + if (chunk.type === 'rawData') { + controller.enqueue(chunk.bytes); + } else if (chunk.type === 'file') { + current = makeStreamFromFileInfo(chunk).getReader(); + return this.pull!(controller); } else if (chunk.type === 'stream') { current = makeStreamFromPipe(chunk.body).getReader(); - this.pull!(controller); + return this.pull!(controller); + } else if (chunk.type === 'blob') { + // Note that even though `getBlobData()` is a `Session` API, it doesn't + // actually use the `Session` context. Its implementation solely relies + // on global variables which allows us to implement this feature without + // knowledge of the `Session` associated with the current request by + // always pulling `Blob` data out of the default `Session`. + controller.enqueue(await session.defaultSession.getBlobData(chunk.blobUUID)); + } else { + throw new Error(`Unknown upload data chunk type: ${chunk.type}`); } } } }) as RequestInit['body']; } -// TODO(codebytere): Use Object.hasOwn() once we update to ECMAScript 2022. function validateResponse (res: Response) { if (!res || typeof res !== 'object') return false; @@ -85,8 +112,12 @@ Protocol.prototype.handle = function (this: Electron.Protocol, scheme: string, h const success = register.call(this, scheme, async (preq: ProtocolRequest, cb: any) => { try { const body = convertToRequestBody(preq.uploadData); + const headers = new Headers(preq.headers); + if (headers.get('origin') === 'null') { + headers.delete('origin'); + } const req = new Request(preq.url, { - headers: preq.headers, + headers, method: preq.method, referrer: preq.referrer, body, diff --git a/spec/api-protocol-spec.ts b/spec/api-protocol-spec.ts index 19ba61de12..348f6c48e6 100644 --- a/spec/api-protocol-spec.ts +++ b/spec/api-protocol-spec.ts @@ -8,6 +8,8 @@ import * as http from 'node:http'; import * as fs from 'node:fs'; import * as qs from 'node:querystring'; import * as stream from 'node:stream'; +import * as streamConsumers from 'node:stream/consumers'; +import * as webStream from 'node:stream/web'; import { EventEmitter, once } from 'node:events'; import { closeAllWindows, closeWindow } from './lib/window-helpers'; import { WebmGenerator } from './lib/video-helpers'; @@ -1548,6 +1550,122 @@ describe('protocol module', () => { } }); + it('does not emit undefined chunks into the request body stream when uploading a stream', async () => { + protocol.handle('cors', async (request) => { + expect(request.body).to.be.an.instanceOf(webStream.ReadableStream); + for await (const value of request.body as webStream.ReadableStream<Uint8Array>) { + expect(value).to.not.be.undefined(); + } + return new Response(undefined, { status: 200 }); + }); + defer(() => { protocol.unhandle('cors'); }); + + await contents.loadFile(path.resolve(fixturesPath, 'pages', 'base-page.html')); + contents.on('console-message', (e, level, message) => console.log(message)); + const ok = await contents.executeJavaScript(`(async () => { + function wait(milliseconds) { + return new Promise((resolve) => setTimeout(resolve, milliseconds)); + } + + const stream = new ReadableStream({ + async start(controller) { + await wait(4); + controller.enqueue('This '); + await wait(4); + controller.enqueue('is '); + await wait(4); + controller.enqueue('a '); + await wait(4); + controller.enqueue('slow '); + await wait(4); + controller.enqueue('request.'); + controller.close(); + } + }).pipeThrough(new TextEncoderStream()); + return (await fetch('cors://url.invalid', { method: 'POST', body: stream, duplex: 'half' })).ok; + })()`); + expect(ok).to.be.true(); + }); + + it('does not emit undefined chunks into the request body stream when uploading a file', async () => { + protocol.handle('cors', async (request) => { + expect(request.body).to.be.an.instanceOf(webStream.ReadableStream); + for await (const value of request.body as webStream.ReadableStream<Uint8Array>) { + expect(value).to.not.be.undefined(); + } + return new Response(undefined, { status: 200 }); + }); + defer(() => { protocol.unhandle('cors'); }); + + await contents.loadFile(path.resolve(fixturesPath, 'pages', 'file-input.html')); + const { debugger: debug } = contents; + debug.attach(); + try { + const { root: { nodeId } } = await debug.sendCommand('DOM.getDocument'); + const { nodeId: inputNodeId } = await debug.sendCommand('DOM.querySelector', { nodeId, selector: 'input' }); + await debug.sendCommand('DOM.setFileInputFiles', { + files: [path.join(fixturesPath, 'cat-spin.mp4')], + nodeId: inputNodeId + }); + const ok = await contents.executeJavaScript(`(async () => { + const formData = new FormData(); + formData.append("data", document.getElementById("file").files[0]); + return (await fetch('cors://url.invalid', { method: 'POST', body: formData })).ok; + })()`); + expect(ok).to.be.true(); + } finally { + debug.detach(); + } + }); + + it('filters an illegal "origin: null" header', async () => { + protocol.handle('http', (req) => { + expect(new Headers(req.headers).get('origin')).to.not.equal('null'); + return new Response(); + }); + defer(() => { protocol.unhandle('http'); }); + + const filePath = path.join(fixturesPath, 'pages', 'form-with-data.html'); + await contents.loadFile(filePath); + + const loadPromise = new Promise((resolve, reject) => { + contents.once('did-finish-load', resolve); + contents.once('did-fail-load', (_, errorCode, errorDescription) => + reject(new Error(`did-fail-load: ${errorCode} ${errorDescription}. See AssertionError for details.`)) + ); + }); + await contents.executeJavaScript(` + const form = document.querySelector('form'); + form.action = 'http://cors.invalid'; + form.method = 'POST'; + form.submit(); + `); + await loadPromise; + }); + + it('does forward Blob chunks', async () => { + // we register the protocol on a separate session to validate the assumption + // that `getBlobData()` indeed returns the blob data from a global variable + const s = session.fromPartition('protocol-handle-forwards-blob-chunks'); + + s.protocol.handle('cors', async (request) => { + expect(request.body).to.be.an.instanceOf(webStream.ReadableStream); + return new Response( + `hello to ${await streamConsumers.text(request.body as webStream.ReadableStream<Uint8Array>)}`, + { status: 200 } + ); + }); + defer(() => { s.protocol.unhandle('cors'); }); + + const w = new BrowserWindow({ show: false, webPreferences: { session: s } }); + await w.webContents.loadFile(path.resolve(fixturesPath, 'pages', 'base-page.html')); + const response = await w.webContents.executeJavaScript(`(async () => { + const body = new Blob(["it's-a ", 'me! ', 'Mario!'], { type: 'text/plain' }); + return await (await fetch('cors://url.invalid', { method: 'POST', body })).text(); + })()`); + expect(response).to.be.string('hello to it\'s-a me! Mario!'); + }); + // TODO(nornagon): this test doesn't pass on Linux currently, investigate. ifit(process.platform !== 'linux')('is fast', async () => { // 128 MB of spaces.
fix
1486cbdf6410e569f619d1ca7ceea0dd3380bf02
Mikaël Barbero
2023-01-26 13:05:42
feat: add support for unlocking with Apple Watch (#36935)
diff --git a/shell/browser/api/electron_api_system_preferences_mac.mm b/shell/browser/api/electron_api_system_preferences_mac.mm index 3b881fc1d2..168ce0f6a1 100644 --- a/shell/browser/api/electron_api_system_preferences_mac.mm +++ b/shell/browser/api/electron_api_system_preferences_mac.mm @@ -425,9 +425,10 @@ std::string SystemPreferences::GetSystemColor(gin_helper::ErrorThrower thrower, bool SystemPreferences::CanPromptTouchID() { base::scoped_nsobject<LAContext> context([[LAContext alloc] init]); - if (![context - canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics - error:nil]) + LAPolicy auth_policy = LAPolicyDeviceOwnerAuthenticationWithBiometrics; + if (@available(macOS 10.15, *)) + auth_policy = LAPolicyDeviceOwnerAuthenticationWithBiometricsOrWatch; + if (![context canEvaluatePolicy:auth_policy error:nil]) return false; if (@available(macOS 10.13.2, *)) return [context biometryType] == LABiometryTypeTouchID;
feat
c953109f01ec595b5986542995fa7b86326e411d
Shelley Vohr
2023-01-12 18:05:26
build: remove older branch migration helpers (#36888) * build: remove older branch migration helpers * chore: fix typo
diff --git a/script/lib/utils.js b/script/lib/utils.js index b562b03faa..1ad06f4057 100644 --- a/script/lib/utils.js +++ b/script/lib/utils.js @@ -6,11 +6,6 @@ const path = require('path'); const ELECTRON_DIR = path.resolve(__dirname, '..', '..'); const SRC_DIR = path.resolve(ELECTRON_DIR, '..'); -const RELEASE_BRANCH_PATTERN = /(\d)+-(?:(?:[0-9]+-x$)|(?:x+-y$))/; -// TODO(main-migration): Simplify once main branch is renamed -const MAIN_BRANCH_PATTERN = /^(main|master)$/; -const ORIGIN_MAIN_BRANCH_PATTERN = /^origin\/(main|master)$/; - require('colors'); const pass = '✓'.green; const fail = '✗'.red; @@ -76,6 +71,10 @@ async function handleGitCall (args, gitDir) { } async function getCurrentBranch (gitDir) { + const RELEASE_BRANCH_PATTERN = /^\d+-x-y$/; + const MAIN_BRANCH_PATTERN = /^main$/; + const ORIGIN_MAIN_BRANCH_PATTERN = /^origin\/main$/; + let branch = await handleGitCall(['rev-parse', '--abbrev-ref', 'HEAD'], gitDir); if (!MAIN_BRANCH_PATTERN.test(branch) && !RELEASE_BRANCH_PATTERN.test(branch)) { const lastCommit = await handleGitCall(['rev-parse', 'HEAD'], gitDir); diff --git a/script/release/notes/index.js b/script/release/notes/index.js index a3ff8d267b..5923138502 100755 --- a/script/release/notes/index.js +++ b/script/release/notes/index.js @@ -76,8 +76,7 @@ const getAllBranches = async () => { return branches.split('\n') .map(branch => branch.trim()) .filter(branch => !!branch) - // TODO(main-migration): Simplify once branch rename is complete. - .filter(branch => branch !== 'origin/HEAD -> origin/master' && branch !== 'origin/HEAD -> origin/main') + .filter(branch => branch !== 'origin/HEAD -> origin/main') .sort(); } catch (err) { console.error('Failed to fetch all branches'); @@ -86,8 +85,7 @@ const getAllBranches = async () => { }; const getStabilizationBranches = async () => { - return (await getAllBranches()) - .filter(branch => /^origin\/\d+-\d+-x$/.test(branch) || /^origin\/\d+-x-y$/.test(branch)); + return (await getAllBranches()).filter(branch => /^origin\/\d+-x-y$/.test(branch)); }; const getPreviousStabilizationBranch = async (current) => { diff --git a/script/release/publish-to-npm.js b/script/release/publish-to-npm.js index cef87cb30c..dbf15a9f03 100644 --- a/script/release/publish-to-npm.js +++ b/script/release/publish-to-npm.js @@ -132,13 +132,8 @@ new Promise((resolve, reject) => { const currentBranch = await getCurrentBranch(); if (isNightlyElectronVersion) { - // TODO(main-migration): Simplify once main branch is renamed. - if (currentBranch === 'master' || currentBranch === 'main') { - // Nightlies get published to their own module, so they should be tagged as latest - npmTag = 'latest'; - } else { - npmTag = `nightly-${currentBranch}`; - } + // Nightlies get published to their own module, so they should be tagged as latest + npmTag = currentBranch === 'main' ? 'latest' : `nightly-${currentBranch}`; const currentJson = JSON.parse(fs.readFileSync(path.join(tempDir, 'package.json'), 'utf8')); currentJson.name = 'electron-nightly'; @@ -149,7 +144,7 @@ new Promise((resolve, reject) => { JSON.stringify(currentJson, null, 2) ); } else { - if (currentBranch === 'master' || currentBranch === 'main') { + if (currentBranch === 'main') { // This should never happen, main releases should be nightly releases // this is here just-in-case throw new Error('Unreachable release phase, can\'t tag a non-nightly release on the main branch'); diff --git a/script/release/version-utils.js b/script/release/version-utils.js index 1bd6668339..85e8f8f15a 100644 --- a/script/release/version-utils.js +++ b/script/release/version-utils.js @@ -73,8 +73,7 @@ async function nextNightly (v) { const pre = `nightly.${getCurrentDate()}`; const branch = (await GitProcess.exec(['rev-parse', '--abbrev-ref', 'HEAD'], ELECTRON_DIR)).stdout.trim(); - // TODO(main-migration): Simplify once main branch is renamed - if (branch === 'master' || branch === 'main') { + if (branch === 'main') { next = semver.inc(await getLastMajorForMain(), 'major'); } else if (isStable(v)) { next = semver.inc(next, 'patch');
build
c628de52d97dacd2e5e770d649b22c979d234884
Shelley Vohr
2024-06-27 11:07:26
fix: `defaultPath` should apply on all dialog types in Linux Portal (#42655) fix: defaultPath should apply on all dialog types in Linux Portal dialogs
diff --git a/patches/chromium/feat_add_support_for_missing_dialog_features_to_shell_dialogs.patch b/patches/chromium/feat_add_support_for_missing_dialog_features_to_shell_dialogs.patch index db9ffa0435..d73625513e 100644 --- a/patches/chromium/feat_add_support_for_missing_dialog_features_to_shell_dialogs.patch +++ b/patches/chromium/feat_add_support_for_missing_dialog_features_to_shell_dialogs.patch @@ -8,6 +8,9 @@ This CL adds support for the following features to //shell_dialogs: * showHiddenFiles - Show hidden files in dialog. * showOverwriteConfirmation - Whether the user will be presented a confirmation dialog if the user types a file name that already exists. +It also: +* Changes XDG Portal implementation behavior to set default path regardless of dialog type. + This may be partially upstreamed to Chromium in the future. diff --git a/ui/gtk/select_file_dialog_linux_gtk.cc b/ui/gtk/select_file_dialog_linux_gtk.cc @@ -269,7 +272,7 @@ index c79fb47bfba9233da7d2c1438d1e26600684fc78..d7cc7cd70653aaa5b628ef456dcb48a2 &SelectFileDialogLinuxKde::OnSelectSingleFolderDialogResponse, this, parent, params)); diff --git a/ui/shell_dialogs/select_file_dialog_linux_portal.cc b/ui/shell_dialogs/select_file_dialog_linux_portal.cc -index 65727489ddecb755eeabbd194ce843ca9eaa59c9..b15bace56639d2f914f8f76edfa1b28e33165b48 100644 +index 65727489ddecb755eeabbd194ce843ca9eaa59c9..38134183309f89b76e7d2a8cda0a11f530b79d44 100644 --- a/ui/shell_dialogs/select_file_dialog_linux_portal.cc +++ b/ui/shell_dialogs/select_file_dialog_linux_portal.cc @@ -219,6 +219,10 @@ void SelectFileDialogLinuxPortal::SelectFileImpl( @@ -360,7 +363,7 @@ index 65727489ddecb755eeabbd194ce843ca9eaa59c9..b15bace56639d2f914f8f76edfa1b28e IDS_SELECT_UPLOAD_FOLDER_DIALOG_UPLOAD_BUTTON)); } -@@ -563,6 +572,7 @@ void SelectFileDialogLinuxPortal::DialogInfo::AppendOptions( +@@ -563,12 +572,12 @@ void SelectFileDialogLinuxPortal::DialogInfo::AppendOptions( type == SelectFileDialog::Type::SELECT_UPLOAD_FOLDER || type == SelectFileDialog::Type::SELECT_EXISTING_FOLDER) { AppendBoolOption(&options_writer, kFileChooserOptionDirectory, true); @@ -368,6 +371,13 @@ index 65727489ddecb755eeabbd194ce843ca9eaa59c9..b15bace56639d2f914f8f76edfa1b28e } else if (type == SelectFileDialog::Type::SELECT_OPEN_MULTI_FILE) { AppendBoolOption(&options_writer, kFileChooserOptionMultiple, true); } + +- if (type == SelectFileDialog::Type::SELECT_SAVEAS_FILE && +- !default_path.empty()) { ++ if (!default_path.empty()) { + if (default_path_exists) { + // If this is an existing directory, navigate to that directory, with no + // filename. diff --git a/ui/shell_dialogs/select_file_dialog_linux_portal.h b/ui/shell_dialogs/select_file_dialog_linux_portal.h index c487f7da19e2d05696a8eb72f2fa3e12972149f3..02a40c571570974dcc61e1b1f7ed95fbfc2bedf2 100644 --- a/ui/shell_dialogs/select_file_dialog_linux_portal.h
fix
67d79442712898c357fcb1389c4880f4465c4965
electron-appveyor-updater[bot]
2024-07-02 10:38:43
build: update appveyor image to latest version (#42748) Co-authored-by: electron-appveyor-updater[bot] <161660339+electron-appveyor-updater[bot]@users.noreply.github.com>
diff --git a/appveyor-woa.yml b/appveyor-woa.yml index 5a3f921ec4..0b525168a3 100644 --- a/appveyor-woa.yml +++ b/appveyor-woa.yml @@ -29,7 +29,7 @@ version: 1.0.{build} build_cloud: electronhq-16-core -image: e-127.0.6521.0 +image: e-128.0.6558.0 environment: GIT_CACHE_PATH: C:\Users\appveyor\libcc_cache ELECTRON_OUT_DIR: Default diff --git a/appveyor.yml b/appveyor.yml index 517ccd036c..7f969ca1db 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -29,7 +29,7 @@ version: 1.0.{build} build_cloud: electronhq-16-core -image: e-127.0.6521.0 +image: e-128.0.6558.0 environment: GIT_CACHE_PATH: C:\Users\appveyor\libcc_cache ELECTRON_OUT_DIR: Default
build
d5c8f2d6d9d3029c4fe2daa42b6314e417cfbbc6
cptpcrd
2024-05-07 10:04:50
fix: avoid crash after upgrade on Linux (#41046)
diff --git a/shell/browser/electron_browser_client.cc b/shell/browser/electron_browser_client.cc index cdaa21c481..3a5388cda3 100644 --- a/shell/browser/electron_browser_client.cc +++ b/shell/browser/electron_browser_client.cc @@ -456,7 +456,15 @@ void ElectronBrowserClient::AppendExtraCommandLineSwitches( base::CommandLine* command_line, int process_id) { // Make sure we're about to launch a known executable +#if BUILDFLAG(IS_LINUX) + // On Linux, do not perform this check for /proc/self/exe. It will always + // point to the currently running executable so this check is not + // necessary, and if the executable has been deleted it will return a fake + // name that causes this check to fail. + if (command_line->GetProgram() != base::FilePath(base::kProcSelfExe)) { +#else { +#endif ScopedAllowBlockingForElectron allow_blocking; base::FilePath child_path; base::FilePath program =
fix
ef34892a7691f42819907f5012678686376be21b
Charles Kerr
2025-02-07 03:00:09
chore: bump chromium 134.0.6989.0 (#45506) * chore: bump chromium to 134.0.6989.0 * chore: update patches/chromium/cherry-pick-dd8e2822e507.patch * chore: e patches all
diff --git a/DEPS b/DEPS index 1c4c2e5169..4073f7ad7e 100644 --- a/DEPS +++ b/DEPS @@ -2,7 +2,7 @@ gclient_gn_args_from = 'src' vars = { 'chromium_version': - '134.0.6988.0', + '134.0.6989.0', 'node_version': 'v22.13.1', 'nan_version': diff --git a/patches/chromium/blink_local_frame.patch b/patches/chromium/blink_local_frame.patch index c67eae0fd7..b97745c42d 100644 --- a/patches/chromium/blink_local_frame.patch +++ b/patches/chromium/blink_local_frame.patch @@ -49,7 +49,7 @@ index e662d4d61595735a30d5c721147a95698d4da3d9..6a0388aad469422dd1c0c2164f8aa858 // its owning reference back to our owning LocalFrame. client_->Detached(type); diff --git a/third_party/blink/renderer/core/frame/local_frame.cc b/third_party/blink/renderer/core/frame/local_frame.cc -index 45f2159c6fdfc277850d10697aa1f42cd2f72095..137fd9845e72adbe8792207cb620caf7ec2a5bff 100644 +index 0222da2083719693d499223c16879fb762631f5a..62d2977d81f4d30aad1ddf41be524802876694d8 100644 --- a/third_party/blink/renderer/core/frame/local_frame.cc +++ b/third_party/blink/renderer/core/frame/local_frame.cc @@ -748,10 +748,6 @@ bool LocalFrame::DetachImpl(FrameDetachType type) { diff --git a/patches/chromium/build_do_not_depend_on_packed_resource_integrity.patch b/patches/chromium/build_do_not_depend_on_packed_resource_integrity.patch index fbe1dc0a26..2bf7d057b1 100644 --- a/patches/chromium/build_do_not_depend_on_packed_resource_integrity.patch +++ b/patches/chromium/build_do_not_depend_on_packed_resource_integrity.patch @@ -33,7 +33,7 @@ index c85316d1b75473e65e4b6de84a57ae91b6202a08..3033a50c2249c921d80e3ca0ca11baab "//base", "//build:branding_buildflags", diff --git a/chrome/browser/BUILD.gn b/chrome/browser/BUILD.gn -index 8e6410ecba1d70911a02e677569e462622912010..d19c6e180cc05e7dacd6d289088b157286c8c050 100644 +index b6f9a7c63721344cf3c9d3eb3a772c37788c0bcf..b3c2213f275f944ca3d4191ccb9b03e971b5fb6e 100644 --- a/chrome/browser/BUILD.gn +++ b/chrome/browser/BUILD.gn @@ -4522,7 +4522,7 @@ static_library("browser") { @@ -46,7 +46,7 @@ index 8e6410ecba1d70911a02e677569e462622912010..d19c6e180cc05e7dacd6d289088b1572 # than here in :chrome_dll. deps += [ "//chrome:packed_resources_integrity_header" ] diff --git a/chrome/test/BUILD.gn b/chrome/test/BUILD.gn -index 6278e6584c707a57a9f78521047b7752b99d0ba9..ac2da5587635f80089a5aa4fba002607b1306e2f 100644 +index 057a71a3884cc4cb44b875ee873361a9e0007f59..6d119f63e5cd332217fd4e9e5b9aec700aa88e93 100644 --- a/chrome/test/BUILD.gn +++ b/chrome/test/BUILD.gn @@ -6995,9 +6995,12 @@ test("unit_tests") { diff --git a/patches/chromium/can_create_window.patch b/patches/chromium/can_create_window.patch index 04a2b0fbe3..4a341fe342 100644 --- a/patches/chromium/can_create_window.patch +++ b/patches/chromium/can_create_window.patch @@ -9,10 +9,10 @@ potentially prevent a window from being created. TODO(loc): this patch is currently broken. diff --git a/content/browser/renderer_host/render_frame_host_impl.cc b/content/browser/renderer_host/render_frame_host_impl.cc -index a28f1825107b411e17a2a7e5fac38488afef0d37..999282378d149cb813ce615ba7bd59dbf888ffd1 100644 +index 7c0f64a475f379a9cff48a922d391d75122d8583..11345ff4c57b512d1aad114c4ee11a3652df6eeb 100644 --- a/content/browser/renderer_host/render_frame_host_impl.cc +++ b/content/browser/renderer_host/render_frame_host_impl.cc -@@ -9403,6 +9403,7 @@ void RenderFrameHostImpl::CreateNewWindow( +@@ -9401,6 +9401,7 @@ void RenderFrameHostImpl::CreateNewWindow( last_committed_origin_, params->window_container_type, params->target_url, params->referrer.To<Referrer>(), params->frame_name, params->disposition, *params->features, @@ -21,10 +21,10 @@ index a28f1825107b411e17a2a7e5fac38488afef0d37..999282378d149cb813ce615ba7bd59db &no_javascript_access); diff --git a/content/browser/web_contents/web_contents_impl.cc b/content/browser/web_contents/web_contents_impl.cc -index 9c957e02ff49742cc70c71316c2c695334317d0e..f9eddb8d8f482789da3d74abd298f7b39acea386 100644 +index db726f36b3d685a5563c5177a0e98b627abb30e6..c3388ade654b79df4c96e4867acd10abea89f096 100644 --- a/content/browser/web_contents/web_contents_impl.cc +++ b/content/browser/web_contents/web_contents_impl.cc -@@ -4976,6 +4976,12 @@ FrameTree* WebContentsImpl::CreateNewWindow( +@@ -4977,6 +4977,12 @@ FrameTree* WebContentsImpl::CreateNewWindow( SetPartitionedPopinOpenerOnNewWindowIfNeeded(new_contents_impl, params, opener); @@ -37,7 +37,7 @@ index 9c957e02ff49742cc70c71316c2c695334317d0e..f9eddb8d8f482789da3d74abd298f7b3 // If the new frame has a name, make sure any SiteInstances that can find // this named frame have proxies for it. Must be called after // SetSessionStorageNamespace, since this calls CreateRenderView, which uses -@@ -5017,12 +5023,6 @@ FrameTree* WebContentsImpl::CreateNewWindow( +@@ -5018,12 +5024,6 @@ FrameTree* WebContentsImpl::CreateNewWindow( AddWebContentsDestructionObserver(new_contents_impl); } diff --git a/patches/chromium/cherry-pick-dd8e2822e507.patch b/patches/chromium/cherry-pick-dd8e2822e507.patch index 88dd6cafd4..42200c0197 100644 --- a/patches/chromium/cherry-pick-dd8e2822e507.patch +++ b/patches/chromium/cherry-pick-dd8e2822e507.patch @@ -1,7 +1,7 @@ -From dd8e2822e507a24e1dd16306dca768d29333ba02 Mon Sep 17 00:00:00 2001 +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: Patrick Meenan <[email protected]> -Date: Thu, 06 Feb 2025 07:41:40 -0800 -Subject: [PATCH] Set is_web_secure_context when initializing Service Worker from disk +Date: Thu, 6 Feb 2025 07:41:40 -0800 +Subject: Set is_web_secure_context when initializing Service Worker from disk The value of is_web_secure_context is not serialized to disk when storing the service worker registration (only a few select policies @@ -23,14 +23,13 @@ Reviewed-by: Hiroki Nakagawa <[email protected]> Reviewed-by: Dave Tapuska <[email protected]> Commit-Queue: Patrick Meenan <[email protected]> Cr-Commit-Position: refs/heads/main@{#1416795} ---- diff --git a/content/browser/renderer_host/policy_container_host.cc b/content/browser/renderer_host/policy_container_host.cc -index 0b6509d..ad174110 100644 +index 5f62b1a274bab7028beb9836f88805e7b5a83e2c..f16f56d8d5f0c4e9bc164c546eee8c28f6856693 100644 --- a/content/browser/renderer_host/policy_container_host.cc +++ b/content/browser/renderer_host/policy_container_host.cc -@@ -143,9 +143,11 @@ - cross_origin_isolation_enabled_by_dip) {} +@@ -136,9 +136,11 @@ PolicyContainerPolicies::PolicyContainerPolicies( + allow_cross_origin_isolation(allow_cross_origin_isolation) {} PolicyContainerPolicies::PolicyContainerPolicies( - const blink::mojom::PolicyContainerPolicies& policies) @@ -43,11 +42,11 @@ index 0b6509d..ad174110 100644 mojo::Clone(policies.content_security_policies)), cross_origin_embedder_policy(policies.cross_origin_embedder_policy), diff --git a/content/browser/renderer_host/policy_container_host.h b/content/browser/renderer_host/policy_container_host.h -index 51d05d8..fc0ae74 100644 +index 394bd53bb5c1dfea5abe24b9047eb190884c2648..7add42348ef28079196b447feda78210815d1551 100644 --- a/content/browser/renderer_host/policy_container_host.h +++ b/content/browser/renderer_host/policy_container_host.h -@@ -50,7 +50,8 @@ - bool cross_origin_isolation_enabled_by_dip); +@@ -49,7 +49,8 @@ struct CONTENT_EXPORT PolicyContainerPolicies { + bool allow_cross_origin_isolation); explicit PolicyContainerPolicies( - const blink::mojom::PolicyContainerPolicies& policies); @@ -57,10 +56,10 @@ index 51d05d8..fc0ae74 100644 // Used when loading workers from network schemes. // WARNING: This does not populate referrer policy. diff --git a/content/browser/service_worker/service_worker_registry.cc b/content/browser/service_worker/service_worker_registry.cc -index aa1e8fb5..68b5c2b 100644 +index 930c7a0c51832f1577656357135a1cfd175839c6..429fe4e4fd632ee7eef04b483614b316c8cc2019 100644 --- a/content/browser/service_worker/service_worker_registry.cc +++ b/content/browser/service_worker/service_worker_registry.cc -@@ -1084,7 +1084,8 @@ +@@ -1069,7 +1069,8 @@ ServiceWorkerRegistry::GetOrCreateRegistration( if (data.policy_container_policies) { version->set_policy_container_host( base::MakeRefCounted<PolicyContainerHost>( diff --git a/patches/chromium/chore_partial_revert_of.patch b/patches/chromium/chore_partial_revert_of.patch index e8bd4a803c..133d5bb715 100644 --- a/patches/chromium/chore_partial_revert_of.patch +++ b/patches/chromium/chore_partial_revert_of.patch @@ -14,10 +14,10 @@ track down the source of this problem & figure out if we can fix it by changing something in Electron. diff --git a/content/browser/web_contents/web_contents_impl.cc b/content/browser/web_contents/web_contents_impl.cc -index f6053a947b07c8e1d60d33371cef35d2f35e7fae..0b93ebeca125529c9400f16de342cf96677290d4 100644 +index 92fdec43db9de93e6fb6ad842d936cdad5a2d04e..4292629633d4d27d2d955e71eec077898cef75a9 100644 --- a/content/browser/web_contents/web_contents_impl.cc +++ b/content/browser/web_contents/web_contents_impl.cc -@@ -4895,7 +4895,7 @@ FrameTree* WebContentsImpl::CreateNewWindow( +@@ -4896,7 +4896,7 @@ FrameTree* WebContentsImpl::CreateNewWindow( : IsGuest(); // While some guest types do not have a guest SiteInstance, the ones that // don't all override WebContents creation above. diff --git a/patches/chromium/chore_provide_iswebcontentscreationoverridden_with_full_params.patch b/patches/chromium/chore_provide_iswebcontentscreationoverridden_with_full_params.patch index d6c688b241..7fcf7aaf9b 100644 --- a/patches/chromium/chore_provide_iswebcontentscreationoverridden_with_full_params.patch +++ b/patches/chromium/chore_provide_iswebcontentscreationoverridden_with_full_params.patch @@ -218,10 +218,10 @@ index c6838c83ef971b88769b1f3fba8095025ae25464..2da6a4e08340e72ba7de5d03444c2f17 content::WebContents* AddNewContents( content::WebContents* source, diff --git a/content/browser/web_contents/web_contents_impl.cc b/content/browser/web_contents/web_contents_impl.cc -index e7583ddd3bd825e1ca68cbe19c6958b761742dd0..a024b3c7e78e7967aeebcd33932bb4e541378a6d 100644 +index ffcfe06f299f2a4d62f6a8edbde9df9d301d81fe..a439a65cba92b95f48c4a8e46c57e714a934d2fa 100644 --- a/content/browser/web_contents/web_contents_impl.cc +++ b/content/browser/web_contents/web_contents_impl.cc -@@ -4858,8 +4858,7 @@ FrameTree* WebContentsImpl::CreateNewWindow( +@@ -4859,8 +4859,7 @@ FrameTree* WebContentsImpl::CreateNewWindow( // TODO(crbug.com/40202416): Support a way for MPArch guests to support this. if (delegate_ && delegate_->IsWebContentsCreationOverridden( source_site_instance, params.window_container_type, diff --git a/patches/chromium/desktop_media_list.patch b/patches/chromium/desktop_media_list.patch index 0eb0629aed..26c97b6359 100644 --- a/patches/chromium/desktop_media_list.patch +++ b/patches/chromium/desktop_media_list.patch @@ -82,7 +82,7 @@ index 786c526588d81b8b5b1b5dd3760719a53e005995..f66b7d0b4dfcbb8ed3dde5a9ff463ae2 const Source& GetSource(int index) const override; DesktopMediaList::Type GetMediaListType() const override; diff --git a/chrome/browser/media/webrtc/native_desktop_media_list.cc b/chrome/browser/media/webrtc/native_desktop_media_list.cc -index 53873f1c82b16bcdb4643889823d1df436f640b8..b237354ba91be6b35a50fd379e69d76d68bb6c97 100644 +index 0827764fdeb59d339f304a20e53b01bb158104ee..3192a5b087bf88c57b77440455ae8d62edd58137 100644 --- a/chrome/browser/media/webrtc/native_desktop_media_list.cc +++ b/chrome/browser/media/webrtc/native_desktop_media_list.cc @@ -176,7 +176,7 @@ BOOL CALLBACK AllHwndCollector(HWND hwnd, LPARAM param) { @@ -116,7 +116,7 @@ index 53873f1c82b16bcdb4643889823d1df436f640b8..b237354ba91be6b35a50fd379e69d76d } void NativeDesktopMediaList::Worker::OnCaptureResult( -@@ -1058,6 +1064,11 @@ void NativeDesktopMediaList::RefreshForVizFrameSinkWindows( +@@ -1061,6 +1067,11 @@ void NativeDesktopMediaList::RefreshForVizFrameSinkWindows( FROM_HERE, base::BindOnce(&Worker::RefreshThumbnails, base::Unretained(worker_.get()), std::move(native_ids), thumbnail_size_)); diff --git a/patches/chromium/disable_hidden.patch b/patches/chromium/disable_hidden.patch index f0d13016cc..bd46ee535b 100644 --- a/patches/chromium/disable_hidden.patch +++ b/patches/chromium/disable_hidden.patch @@ -6,10 +6,10 @@ Subject: disable_hidden.patch Electron uses this to disable background throttling for hidden windows. diff --git a/content/browser/renderer_host/render_widget_host_impl.cc b/content/browser/renderer_host/render_widget_host_impl.cc -index 213b7ec788f59b649f19a702063307ad622ef462..69cce8cadec4ca2e5e5a6a17043df70846aa37bb 100644 +index 02d3a7ca666adcb723a1b64928258d1ecaed6a7a..86bd9d926dcf51d42ec716ccde47a77bcd4e8e1d 100644 --- a/content/browser/renderer_host/render_widget_host_impl.cc +++ b/content/browser/renderer_host/render_widget_host_impl.cc -@@ -814,6 +814,10 @@ void RenderWidgetHostImpl::WasHidden() { +@@ -818,6 +818,10 @@ void RenderWidgetHostImpl::WasHidden() { return; } 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 index b081ea522b..9e8f0ebd14 100644 --- 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 @@ -91,10 +91,10 @@ index 28f616f21f998c7cd1c794e58efaccf9e6c11e6e..c64896642209124e500db2ed6fe2357e // 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 +index c269698764bb8ae7f85c5d476436f5ae5209576d..65d7fd94128a755609192784722074c6c2b7b7cf 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, +@@ -122,7 +122,7 @@ bool ClipboardCommands::CanReadClipboard(LocalFrame& frame, return true; } return frame.GetContentSettingsClient() && @@ -103,7 +103,7 @@ index 271ca7ba88fc92b8f6bad5ee4cffedf7f1b05aee..d8d01062de4af45a59eb10a1c0fa046a } bool ClipboardCommands::CanWriteClipboard(LocalFrame& frame, -@@ -310,7 +310,7 @@ bool ClipboardCommands::PasteSupported(LocalFrame* frame) { +@@ -311,7 +311,7 @@ bool ClipboardCommands::PasteSupported(LocalFrame* frame) { return true; } return frame->GetContentSettingsClient() && 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 cf24b70902..b3be9f546d 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 @@ -87,10 +87,10 @@ index 51522e60d6dc14f1113cc438558b6b393c3fe73a..153ed02f493a83ef9ca354cc18736f93 // The view with active text input state, i.e., a focused <input> element. // It will be nullptr if no such view exists. Note that the active view diff --git a/content/browser/web_contents/web_contents_impl.cc b/content/browser/web_contents/web_contents_impl.cc -index 64dfb39220d2f660873a17ebb210bddde45c8a7f..f6053a947b07c8e1d60d33371cef35d2f35e7fae 100644 +index 5f7d2e165c9551a7cf965aaac196c9508eab22bb..92fdec43db9de93e6fb6ad842d936cdad5a2d04e 100644 --- a/content/browser/web_contents/web_contents_impl.cc +++ b/content/browser/web_contents/web_contents_impl.cc -@@ -9672,7 +9672,7 @@ void WebContentsImpl::OnFocusedElementChangedInFrame( +@@ -9673,7 +9673,7 @@ void WebContentsImpl::OnFocusedElementChangedInFrame( "WebContentsImpl::OnFocusedElementChangedInFrame", "render_frame_host", frame); RenderWidgetHostViewBase* root_view = diff --git a/patches/chromium/fix_restore_original_resize_performance_on_macos.patch b/patches/chromium/fix_restore_original_resize_performance_on_macos.patch index 423b90f25d..fab713dd96 100644 --- a/patches/chromium/fix_restore_original_resize_performance_on_macos.patch +++ b/patches/chromium/fix_restore_original_resize_performance_on_macos.patch @@ -11,10 +11,10 @@ This patch should be upstreamed as a conditional revert of the logic in desktop vs mobile runtimes. i.e. restore the old logic only on desktop platforms diff --git a/content/browser/renderer_host/render_widget_host_impl.cc b/content/browser/renderer_host/render_widget_host_impl.cc -index 1e070456871df94dc4d6d443f853b351495d27bd..9eb51022846be4e48e2f2841cb59e7d387ea72d3 100644 +index 4c6081970652f83382359623cc89ffd5f26b1c17..c8922367621362d3ae57399ef3712cef0a40a3d9 100644 --- a/content/browser/renderer_host/render_widget_host_impl.cc +++ b/content/browser/renderer_host/render_widget_host_impl.cc -@@ -2078,9 +2078,8 @@ RenderWidgetHostImpl::GetWidgetInputHandler() { +@@ -2085,9 +2085,8 @@ RenderWidgetHostImpl::GetWidgetInputHandler() { void RenderWidgetHostImpl::NotifyScreenInfoChanged() { // The resize message (which may not happen immediately) will carry with it // the screen info as well as the new size (if the screen has changed scale diff --git a/patches/chromium/fix_return_v8_value_from_localframe_requestexecutescript.patch b/patches/chromium/fix_return_v8_value_from_localframe_requestexecutescript.patch index 8baf530ff1..3920b3350a 100644 --- a/patches/chromium/fix_return_v8_value_from_localframe_requestexecutescript.patch +++ b/patches/chromium/fix_return_v8_value_from_localframe_requestexecutescript.patch @@ -59,7 +59,7 @@ index cba373664bec3a32abad6fe0396bd67b53b7e67f..a54f1b3351efd2d8f324436f7f35cd43 #endif // THIRD_PARTY_BLINK_PUBLIC_WEB_WEB_SCRIPT_EXECUTION_CALLBACK_H_ diff --git a/third_party/blink/renderer/core/frame/local_frame.cc b/third_party/blink/renderer/core/frame/local_frame.cc -index 137fd9845e72adbe8792207cb620caf7ec2a5bff..7a9dee2ca882b5abee8acd720face650150bd453 100644 +index 62d2977d81f4d30aad1ddf41be524802876694d8..95396ac102c1fb9f2e431bb52a7043d505f7ff4c 100644 --- a/third_party/blink/renderer/core/frame/local_frame.cc +++ b/third_party/blink/renderer/core/frame/local_frame.cc @@ -3136,6 +3136,7 @@ void LocalFrame::RequestExecuteScript( diff --git a/patches/chromium/gritsettings_resource_ids.patch b/patches/chromium/gritsettings_resource_ids.patch index 024c78ce87..20b3a7b895 100644 --- a/patches/chromium/gritsettings_resource_ids.patch +++ b/patches/chromium/gritsettings_resource_ids.patch @@ -6,10 +6,10 @@ Subject: gritsettings_resource_ids.patch Add electron resources file to the list of resource ids generation. diff --git a/tools/gritsettings/resource_ids.spec b/tools/gritsettings/resource_ids.spec -index fa55d3f60a0d4d2293409fd700365864908a76b7..259e2092676b5b75eafc9920f6d0cfe32b32cf4a 100644 +index c272cb9614cd8095c10ae2b1b2cab702a380a278..0ed8a5cc082b29d6b1c90c1ca02162b20f3f803b 100644 --- a/tools/gritsettings/resource_ids.spec +++ b/tools/gritsettings/resource_ids.spec -@@ -1451,6 +1451,11 @@ +@@ -1447,6 +1447,11 @@ "<(SHARED_INTERMEDIATE_DIR)/third_party/blink/public/strings/permission_element_generated_strings.grd": { "META": {"sizes": {"messages": [2000],}}, "messages": [10080], 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 de3c7e7c83..cbdc7edd86 100644 --- a/patches/chromium/mas_avoid_private_macos_api_usage.patch.patch +++ b/patches/chromium/mas_avoid_private_macos_api_usage.patch.patch @@ -792,7 +792,7 @@ index a1068589ad844518038ee7bc15a3de9bc5cba525..1ff781c49f086ec8015c7d3c44567dbe } // namespace content diff --git a/content/test/BUILD.gn b/content/test/BUILD.gn -index 4b521179af8722f0a9917d1f925d9223b46e2c73..b3532822184507a2d37af607bd09aaff65fcb30f 100644 +index 15a237fd7354b76fd6c67c3f7c77c75d8ef34b11..2cd888ea6f4b1f18ab65945dfb2814f0601f7b58 100644 --- a/content/test/BUILD.gn +++ b/content/test/BUILD.gn @@ -652,6 +652,7 @@ static_library("test_support") { @@ -819,7 +819,7 @@ index 4b521179af8722f0a9917d1f925d9223b46e2c73..b3532822184507a2d37af607bd09aaff ] if (!(is_chromeos && target_cpu == "arm64" && current_cpu == "arm")) { -@@ -3203,6 +3206,7 @@ test("content_unittests") { +@@ -3204,6 +3207,7 @@ test("content_unittests") { "//ui/latency:test_support", "//ui/shell_dialogs:shell_dialogs", "//ui/webui:test_support", @@ -932,7 +932,7 @@ index 36322ddd3047f96569f35807541a37d3c6672b09..0121a780cf3b79fc1120c1b85cd5cd30 namespace ui { diff --git a/media/audio/BUILD.gn b/media/audio/BUILD.gn -index 45847b155ec8fb197aadb479eca78154436cfa81..e5de2b90a4c7d8181408ddfa62057b977015cbb8 100644 +index 977aa5b452c882ee69690ba034ec00c9e7ff7e24..3ae3e2ead48ea1af9307dcd12647ca2a24b3a6f4 100644 --- a/media/audio/BUILD.gn +++ b/media/audio/BUILD.gn @@ -198,6 +198,7 @@ source_set("audio") { diff --git a/patches/chromium/notification_provenance.patch b/patches/chromium/notification_provenance.patch index 8d34e641ef..4422ebef8b 100644 --- a/patches/chromium/notification_provenance.patch +++ b/patches/chromium/notification_provenance.patch @@ -133,10 +133,10 @@ index 05d3a12dd84c7005d46cc73b312f97ef418d96f5..4765de982802541b3efc7211d106acc7 const GURL& document_url, const WeakDocumentPtr& weak_document_ptr, diff --git a/content/browser/renderer_host/render_process_host_impl.cc b/content/browser/renderer_host/render_process_host_impl.cc -index 2ad61dcfc289e20ee1c36540db17301450d37b8b..72f28e56f39561cb4832cb403d8e9c24e53ce133 100644 +index 9feaa88b28a0bf826813510524039cf21c89e0f5..160607287f4c780a7729c7e38c97bcdcd70751cc 100644 --- a/content/browser/renderer_host/render_process_host_impl.cc +++ b/content/browser/renderer_host/render_process_host_impl.cc -@@ -2156,7 +2156,7 @@ void RenderProcessHostImpl::CreateNotificationService( +@@ -2152,7 +2152,7 @@ void RenderProcessHostImpl::CreateNotificationService( case RenderProcessHost::NotificationServiceCreatorType::kSharedWorker: case RenderProcessHost::NotificationServiceCreatorType::kDedicatedWorker: { storage_partition_impl_->GetPlatformNotificationContext()->CreateService( @@ -145,7 +145,7 @@ index 2ad61dcfc289e20ee1c36540db17301450d37b8b..72f28e56f39561cb4832cb403d8e9c24 creator_type, std::move(receiver)); break; } -@@ -2164,7 +2164,7 @@ void RenderProcessHostImpl::CreateNotificationService( +@@ -2160,7 +2160,7 @@ void RenderProcessHostImpl::CreateNotificationService( CHECK(rfh); storage_partition_impl_->GetPlatformNotificationContext()->CreateService( diff --git a/patches/chromium/partially_revert_is_newly_created_to_allow_for_browser_initiated.patch b/patches/chromium/partially_revert_is_newly_created_to_allow_for_browser_initiated.patch index 89cc922161..4e5b4e91cc 100644 --- a/patches/chromium/partially_revert_is_newly_created_to_allow_for_browser_initiated.patch +++ b/patches/chromium/partially_revert_is_newly_created_to_allow_for_browser_initiated.patch @@ -10,10 +10,10 @@ an about:blank check to this area. Ref: https://chromium-review.googlesource.com/c/chromium/src/+/5403876 diff --git a/content/browser/renderer_host/render_frame_host_impl.cc b/content/browser/renderer_host/render_frame_host_impl.cc -index 05ea713db94ed47bc2717028265ab6fe9be83a45..0d1484ea53e72232ab192b966e293270ef7eea1d 100644 +index 074885f3f17f3838a61f1b6d7866e80c9eb8d644..2cf31c000cdc829d6b920f31977aeda826d0c070 100644 --- a/content/browser/renderer_host/render_frame_host_impl.cc +++ b/content/browser/renderer_host/render_frame_host_impl.cc -@@ -800,8 +800,8 @@ void VerifyThatBrowserAndRendererCalculatedOriginsToCommitMatch( +@@ -798,8 +798,8 @@ void VerifyThatBrowserAndRendererCalculatedOriginsToCommitMatch( // TODO(crbug.com/40092527): Consider adding a separate boolean that // tracks this instead of piggybacking `origin_calculation_debug_info`. if (renderer_side_origin.opaque() && diff --git a/patches/chromium/refactor_expose_cursor_changes_to_the_webcontentsobserver.patch b/patches/chromium/refactor_expose_cursor_changes_to_the_webcontentsobserver.patch index 408c0a3b3e..93ed9d2d2c 100644 --- a/patches/chromium/refactor_expose_cursor_changes_to_the_webcontentsobserver.patch +++ b/patches/chromium/refactor_expose_cursor_changes_to_the_webcontentsobserver.patch @@ -30,10 +30,10 @@ index ecb007b668458da1f8db4fca75f9c4428221dfbf..063007699b5b09ef8e6dbb39e044e4a1 // RenderWidgetHost on the primary main frame, and false otherwise. virtual bool IsWidgetForPrimaryMainFrame(RenderWidgetHostImpl*); diff --git a/content/browser/renderer_host/render_widget_host_impl.cc b/content/browser/renderer_host/render_widget_host_impl.cc -index 69cce8cadec4ca2e5e5a6a17043df70846aa37bb..1e070456871df94dc4d6d443f853b351495d27bd 100644 +index 86bd9d926dcf51d42ec716ccde47a77bcd4e8e1d..4c6081970652f83382359623cc89ffd5f26b1c17 100644 --- a/content/browser/renderer_host/render_widget_host_impl.cc +++ b/content/browser/renderer_host/render_widget_host_impl.cc -@@ -2012,6 +2012,9 @@ void RenderWidgetHostImpl::SetCursor(const ui::Cursor& cursor) { +@@ -2019,6 +2019,9 @@ void RenderWidgetHostImpl::SetCursor(const ui::Cursor& cursor) { if (view_) { view_->UpdateCursor(cursor); } @@ -44,10 +44,10 @@ index 69cce8cadec4ca2e5e5a6a17043df70846aa37bb..1e070456871df94dc4d6d443f853b351 void RenderWidgetHostImpl::ShowContextMenuAtPoint( diff --git a/content/browser/web_contents/web_contents_impl.cc b/content/browser/web_contents/web_contents_impl.cc -index f9eddb8d8f482789da3d74abd298f7b39acea386..e7583ddd3bd825e1ca68cbe19c6958b761742dd0 100644 +index c3388ade654b79df4c96e4867acd10abea89f096..ffcfe06f299f2a4d62f6a8edbde9df9d301d81fe 100644 --- a/content/browser/web_contents/web_contents_impl.cc +++ b/content/browser/web_contents/web_contents_impl.cc -@@ -5725,6 +5725,11 @@ TextInputManager* WebContentsImpl::GetTextInputManager() { +@@ -5726,6 +5726,11 @@ TextInputManager* WebContentsImpl::GetTextInputManager() { return text_input_manager_.get(); } @@ -60,10 +60,10 @@ index f9eddb8d8f482789da3d74abd298f7b39acea386..e7583ddd3bd825e1ca68cbe19c6958b7 RenderWidgetHostImpl* render_widget_host) { return render_widget_host == GetPrimaryMainFrame()->GetRenderWidgetHost(); diff --git a/content/browser/web_contents/web_contents_impl.h b/content/browser/web_contents/web_contents_impl.h -index 61df6566bd16f88787e4be0b6f93702acca883e5..478c9839916130a3aec9bb32b24e7ee723dcd4ed 100644 +index f68fb7f6b92a71cc4d52a2de5f86a7be808468d9..2eed7ca33168e88b0b677f759c48892238f97c15 100644 --- a/content/browser/web_contents/web_contents_impl.h +++ b/content/browser/web_contents/web_contents_impl.h -@@ -1164,6 +1164,7 @@ class CONTENT_EXPORT WebContentsImpl +@@ -1165,6 +1165,7 @@ class CONTENT_EXPORT WebContentsImpl void SendScreenRects() override; void SendActiveState(bool active) override; TextInputManager* GetTextInputManager() override; diff --git a/patches/chromium/refactor_unfilter_unresponsive_events.patch b/patches/chromium/refactor_unfilter_unresponsive_events.patch index e46421d199..cb1c04d882 100644 --- a/patches/chromium/refactor_unfilter_unresponsive_events.patch +++ b/patches/chromium/refactor_unfilter_unresponsive_events.patch @@ -15,10 +15,10 @@ This CL removes these filters so the unresponsive event can still be accessed from our JS event. The filtering is moved into Electron's code. diff --git a/content/browser/web_contents/web_contents_impl.cc b/content/browser/web_contents/web_contents_impl.cc -index 0b93ebeca125529c9400f16de342cf96677290d4..975c4c1a7f4724781f1dc54fa009cc55f7c5ce29 100644 +index 4292629633d4d27d2d955e71eec077898cef75a9..11310d464eb10479110c7910c9442b49260a45e1 100644 --- a/content/browser/web_contents/web_contents_impl.cc +++ b/content/browser/web_contents/web_contents_impl.cc -@@ -9809,25 +9809,13 @@ void WebContentsImpl::RendererUnresponsive( +@@ -9810,25 +9810,13 @@ void WebContentsImpl::RendererUnresponsive( base::RepeatingClosure hang_monitor_restarter) { OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::RendererUnresponsive", "render_widget_host", render_widget_host); diff --git a/patches/chromium/support_mixed_sandbox_with_zygote.patch b/patches/chromium/support_mixed_sandbox_with_zygote.patch index 5dce9afbe9..7480b480a2 100644 --- a/patches/chromium/support_mixed_sandbox_with_zygote.patch +++ b/patches/chromium/support_mixed_sandbox_with_zygote.patch @@ -22,10 +22,10 @@ However, the patch would need to be reviewed by the security team, as it does touch a security-sensitive class. diff --git a/content/browser/renderer_host/render_process_host_impl.cc b/content/browser/renderer_host/render_process_host_impl.cc -index 72f28e56f39561cb4832cb403d8e9c24e53ce133..ba74882cf6940c29d3326dc69e6be0ce7e754974 100644 +index 160607287f4c780a7729c7e38c97bcdcd70751cc..c9c2e50bd1847217330398c1b100ccc0b053db4e 100644 --- a/content/browser/renderer_host/render_process_host_impl.cc +++ b/content/browser/renderer_host/render_process_host_impl.cc -@@ -1766,6 +1766,10 @@ bool RenderProcessHostImpl::Init() { +@@ -1762,6 +1762,10 @@ bool RenderProcessHostImpl::Init() { std::unique_ptr<SandboxedProcessLauncherDelegate> sandbox_delegate = std::make_unique<RendererSandboxedProcessLauncherDelegateWin>( *cmd_line, IsPdf(), IsJitDisabled()); diff --git a/patches/chromium/web_contents.patch b/patches/chromium/web_contents.patch index 6197456bf1..6eea592207 100644 --- a/patches/chromium/web_contents.patch +++ b/patches/chromium/web_contents.patch @@ -9,10 +9,10 @@ is needed for OSR. Originally landed in https://github.com/electron/libchromiumcontent/pull/226. diff --git a/content/browser/web_contents/web_contents_impl.cc b/content/browser/web_contents/web_contents_impl.cc -index a024b3c7e78e7967aeebcd33932bb4e541378a6d..b31076e6fd2312af9dea269628642bec0b020d2f 100644 +index a439a65cba92b95f48c4a8e46c57e714a934d2fa..a4a5db4cf4dea358fb34d658a675be9e799e2ef1 100644 --- a/content/browser/web_contents/web_contents_impl.cc +++ b/content/browser/web_contents/web_contents_impl.cc -@@ -3808,6 +3808,13 @@ void WebContentsImpl::Init(const WebContents::CreateParams& params, +@@ -3809,6 +3809,13 @@ void WebContentsImpl::Init(const WebContents::CreateParams& params, params.main_frame_name, GetOpener(), primary_main_frame_policy, base::UnguessableToken::Create()); @@ -26,7 +26,7 @@ index a024b3c7e78e7967aeebcd33932bb4e541378a6d..b31076e6fd2312af9dea269628642bec std::unique_ptr<WebContentsViewDelegate> delegate = GetContentClient()->browser()->GetWebContentsViewDelegate(this); -@@ -3818,6 +3825,7 @@ void WebContentsImpl::Init(const WebContents::CreateParams& params, +@@ -3819,6 +3826,7 @@ void WebContentsImpl::Init(const WebContents::CreateParams& params, view_ = CreateWebContentsView(this, std::move(delegate), &render_view_host_delegate_view_); } diff --git a/patches/chromium/webview_fullscreen.patch b/patches/chromium/webview_fullscreen.patch index c9991f5b80..56d41348c6 100644 --- a/patches/chromium/webview_fullscreen.patch +++ b/patches/chromium/webview_fullscreen.patch @@ -15,10 +15,10 @@ Note that we also need to manually update embedder's `api::WebContents::IsFullscreenForTabOrPending` value. diff --git a/content/browser/renderer_host/render_frame_host_impl.cc b/content/browser/renderer_host/render_frame_host_impl.cc -index 999282378d149cb813ce615ba7bd59dbf888ffd1..05ea713db94ed47bc2717028265ab6fe9be83a45 100644 +index 11345ff4c57b512d1aad114c4ee11a3652df6eeb..074885f3f17f3838a61f1b6d7866e80c9eb8d644 100644 --- a/content/browser/renderer_host/render_frame_host_impl.cc +++ b/content/browser/renderer_host/render_frame_host_impl.cc -@@ -8512,6 +8512,17 @@ void RenderFrameHostImpl::EnterFullscreen( +@@ -8510,6 +8510,17 @@ void RenderFrameHostImpl::EnterFullscreen( } } @@ -37,10 +37,10 @@ index 999282378d149cb813ce615ba7bd59dbf888ffd1..05ea713db94ed47bc2717028265ab6fe if (had_fullscreen_token && !GetView()->HasFocus()) GetView()->Focus(); diff --git a/content/browser/web_contents/web_contents_impl.cc b/content/browser/web_contents/web_contents_impl.cc -index b31076e6fd2312af9dea269628642bec0b020d2f..64dfb39220d2f660873a17ebb210bddde45c8a7f 100644 +index a4a5db4cf4dea358fb34d658a675be9e799e2ef1..5f7d2e165c9551a7cf965aaac196c9508eab22bb 100644 --- a/content/browser/web_contents/web_contents_impl.cc +++ b/content/browser/web_contents/web_contents_impl.cc -@@ -4072,21 +4072,25 @@ KeyboardEventProcessingResult WebContentsImpl::PreHandleKeyboardEvent( +@@ -4073,21 +4073,25 @@ KeyboardEventProcessingResult WebContentsImpl::PreHandleKeyboardEvent( const input::NativeWebKeyboardEvent& event) { OPTIONAL_TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("content.verbose"), "WebContentsImpl::PreHandleKeyboardEvent"); @@ -78,7 +78,7 @@ index b31076e6fd2312af9dea269628642bec0b020d2f..64dfb39220d2f660873a17ebb210bddd } bool WebContentsImpl::HandleMouseEvent(const blink::WebMouseEvent& event) { -@@ -4245,7 +4249,7 @@ void WebContentsImpl::EnterFullscreenMode( +@@ -4246,7 +4250,7 @@ void WebContentsImpl::EnterFullscreenMode( OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::EnterFullscreenMode"); DCHECK(CanEnterFullscreenMode(requesting_frame)); DCHECK(requesting_frame->IsActive());
chore
9cd5de75888d67b20bb7faf59ca4272323895c62
Athul Iddya
2023-07-21 16:03:01
fix: use generic capturer to list both screens and windows when possible (#39111) Screensharing with PipeWire via XDG Desktop Portal requires explicit user permission via permission dialogs. Chromium has separate tabs for screens and windows and thus its portal implementation requests permissions separately for each. However, the screencast portal has no such limitation and supports both screens and windows in a single request. WebRTC now supports this type of capture in a new method called called `CreateGenericCapturer`. The `desktopCapturer` implementation has been modified to use it. Additionally, Chromium has been patched to use same generic capturer to ensure that the source IDs remain valid for `getUserMedia`.
diff --git a/patches/chromium/.patches b/patches/chromium/.patches index 72c5e85bef..767054b15c 100644 --- a/patches/chromium/.patches +++ b/patches/chromium/.patches @@ -131,3 +131,4 @@ fix_select_the_first_menu_item_when_opened_via_keyboard.patch fix_return_v8_value_from_localframe_requestexecutescript.patch fix_harden_blink_scriptstate_maybefrom.patch chore_add_buildflag_guard_around_new_include.patch +fix_use_delegated_generic_capturer_when_available.patch diff --git a/patches/chromium/fix_use_delegated_generic_capturer_when_available.patch b/patches/chromium/fix_use_delegated_generic_capturer_when_available.patch new file mode 100644 index 0000000000..79099b2382 --- /dev/null +++ b/patches/chromium/fix_use_delegated_generic_capturer_when_available.patch @@ -0,0 +1,54 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: Athul Iddya <[email protected]> +Date: Fri, 14 Jul 2023 08:03:37 -0700 +Subject: fix: use delegated generic capturer when available + +When the generic capturer is used to fetch capture sources, the returned +ID will be arbitrarily prefixed with "screen" or "window" regardless of +the source type. If the window capturer is used to stream video when the +source was a screen or vice-versa, the stream fails to restart in +delegated capturers like PipeWire. + +To fix this, use the generic capturer to fetch the media stream if it's +delegated and available. This does not cause any issues if the original +capturer was window or screen-specific, as the IDs remain valid for +generic capturer as well. + +diff --git a/content/browser/media/capture/desktop_capture_device.cc b/content/browser/media/capture/desktop_capture_device.cc +index b0c4efdd8a6401e09520bdfa96221e5addcfd829..f5b7447938f70dd4623a60fa6a856775b627f3d6 100644 +--- a/content/browser/media/capture/desktop_capture_device.cc ++++ b/content/browser/media/capture/desktop_capture_device.cc +@@ -794,8 +794,14 @@ std::unique_ptr<media::VideoCaptureDevice> DesktopCaptureDevice::Create( + DesktopCapturerLacros::CaptureType::kScreen, + webrtc::DesktopCaptureOptions()); + #else +- std::unique_ptr<webrtc::DesktopCapturer> screen_capturer( +- webrtc::DesktopCapturer::CreateScreenCapturer(options)); ++ std::unique_ptr<webrtc::DesktopCapturer> screen_capturer; ++ if (auto generic_capturer = ++ webrtc::DesktopCapturer::CreateGenericCapturer(options); ++ generic_capturer && generic_capturer->GetDelegatedSourceListController()) { ++ screen_capturer = std::move(generic_capturer); ++ } else { ++ screen_capturer = webrtc::DesktopCapturer::CreateScreenCapturer(options); ++ } + #endif + if (screen_capturer && screen_capturer->SelectSource(source.id)) { + capturer = std::make_unique<webrtc::DesktopAndCursorComposer>( +@@ -814,8 +820,14 @@ std::unique_ptr<media::VideoCaptureDevice> DesktopCaptureDevice::Create( + new DesktopCapturerLacros(DesktopCapturerLacros::CaptureType::kWindow, + webrtc::DesktopCaptureOptions())); + #else +- std::unique_ptr<webrtc::DesktopCapturer> window_capturer = +- webrtc::DesktopCapturer::CreateWindowCapturer(options); ++ std::unique_ptr<webrtc::DesktopCapturer> window_capturer; ++ if (auto generic_capturer = ++ webrtc::DesktopCapturer::CreateGenericCapturer(options); ++ generic_capturer && generic_capturer->GetDelegatedSourceListController()) { ++ window_capturer = std::move(generic_capturer); ++ } else { ++ window_capturer = webrtc::DesktopCapturer::CreateWindowCapturer(options); ++ } + #endif + if (window_capturer && window_capturer->SelectSource(source.id)) { + capturer = std::make_unique<webrtc::DesktopAndCursorComposer>( diff --git a/shell/browser/api/electron_api_desktop_capturer.cc b/shell/browser/api/electron_api_desktop_capturer.cc index 1e908db7c8..5cfe0fedb9 100644 --- a/shell/browser/api/electron_api_desktop_capturer.cc +++ b/shell/browser/api/electron_api_desktop_capturer.cc @@ -234,6 +234,33 @@ void DesktopCapturer::StartHandling(bool capture_window, // clear any existing captured sources. captured_sources_.clear(); + if (capture_window && capture_screen) { + // Some capturers like PipeWire suppport a single capturer for both screens + // and windows. Use it if possible, treating both as window capture + if (auto capturer = webrtc::DesktopCapturer::CreateGenericCapturer( + content::desktop_capture::CreateDesktopCaptureOptions()); + capturer && capturer->GetDelegatedSourceListController()) { + capture_screen_ = false; + capture_window_ = capture_window; + window_capturer_ = std::make_unique<NativeDesktopMediaList>( + DesktopMediaList::Type::kWindow, std::move(capturer)); + window_capturer_->SetThumbnailSize(thumbnail_size); + + OnceCallback update_callback = base::BindOnce( + &DesktopCapturer::UpdateSourcesList, weak_ptr_factory_.GetWeakPtr(), + window_capturer_.get()); + OnceCallback failure_callback = base::BindOnce( + &DesktopCapturer::HandleFailure, weak_ptr_factory_.GetWeakPtr()); + + window_listener_ = std::make_unique<DesktopListListener>( + std::move(update_callback), std::move(failure_callback), + thumbnail_size.IsEmpty()); + window_capturer_->StartUpdating(window_listener_.get()); + + return; + } + } + // Start listening for captured sources. capture_window_ = capture_window; capture_screen_ = capture_screen;
fix
2f2c43e5e513e65a0aabac62622d51a1dfe49357
Milan Burda
2022-11-01 00:18:15
build: fix building with enable_plugins = false (#36193) Co-authored-by: Milan Burda <[email protected]>
diff --git a/BUILD.gn b/BUILD.gn index 399e526ca6..070b4c3a93 100644 --- a/BUILD.gn +++ b/BUILD.gn @@ -665,6 +665,8 @@ source_set("electron_lib") { sources += [ "shell/common/plugin_info.cc", "shell/common/plugin_info.h", + "shell/renderer/electron_renderer_pepper_host_factory.cc", + "shell/renderer/electron_renderer_pepper_host_factory.h", "shell/renderer/pepper_helper.cc", "shell/renderer/pepper_helper.h", ] diff --git a/filenames.gni b/filenames.gni index da15f04d00..7f647d70a8 100644 --- a/filenames.gni +++ b/filenames.gni @@ -671,8 +671,6 @@ filenames = { "shell/renderer/electron_render_frame_observer.h", "shell/renderer/electron_renderer_client.cc", "shell/renderer/electron_renderer_client.h", - "shell/renderer/electron_renderer_pepper_host_factory.cc", - "shell/renderer/electron_renderer_pepper_host_factory.h", "shell/renderer/electron_sandboxed_renderer_client.cc", "shell/renderer/electron_sandboxed_renderer_client.h", "shell/renderer/renderer_client_base.cc",
build
909ee0ed6bbdf57ebaeda027b67a3a44185f6f7d
Milan Burda
2022-12-05 09:59:20
refactor: make StatusIconType an enum class (#36500) Co-authored-by: Milan Burda <[email protected]>
diff --git a/shell/browser/ui/tray_icon_gtk.cc b/shell/browser/ui/tray_icon_gtk.cc index 4302a45d2e..56b6e1bf1e 100644 --- a/shell/browser/ui/tray_icon_gtk.cc +++ b/shell/browser/ui/tray_icon_gtk.cc @@ -30,7 +30,8 @@ gfx::ImageSkia GetBestImageRep(const gfx::ImageSkia& image) { } // namespace TrayIconGtk::TrayIconGtk() - : status_icon_(new StatusIconLinuxDbus), status_icon_type_(kTypeDbus) { + : status_icon_(new StatusIconLinuxDbus), + status_icon_type_(StatusIconType::kDbus) { status_icon_->SetDelegate(this); } @@ -68,11 +69,11 @@ ui::MenuModel* TrayIconGtk::GetMenuModel() const { void TrayIconGtk::OnImplInitializationFailed() { switch (status_icon_type_) { - case kTypeDbus: + case StatusIconType::kDbus: status_icon_ = nullptr; - status_icon_type_ = kTypeNone; + status_icon_type_ = StatusIconType::kNone; return; - case kTypeNone: + case StatusIconType::kNone: NOTREACHED(); } } diff --git a/shell/browser/ui/tray_icon_gtk.h b/shell/browser/ui/tray_icon_gtk.h index 11feec449a..ccbcd99b29 100644 --- a/shell/browser/ui/tray_icon_gtk.h +++ b/shell/browser/ui/tray_icon_gtk.h @@ -36,9 +36,9 @@ class TrayIconGtk : public TrayIcon, public ui::StatusIconLinux::Delegate { void OnImplInitializationFailed() override; private: - enum StatusIconType { - kTypeDbus, - kTypeNone, + enum class StatusIconType { + kDbus, + kNone, }; scoped_refptr<StatusIconLinuxDbus> status_icon_;
refactor
23ae0dde17eb546dd0a1d8d570dbcec6cc06c064
David Sanders
2023-02-02 02:16:41
docs: use automatic link syntax for symbol server link (#37089)
diff --git a/docs/development/debugging-with-symbol-server.md b/docs/development/debugging-with-symbol-server.md index 336eb7a54f..0663675306 100644 --- a/docs/development/debugging-with-symbol-server.md +++ b/docs/development/debugging-with-symbol-server.md @@ -15,7 +15,7 @@ calls, and other compiler optimizations. The only workaround is to build an unoptimized local build. The official symbol server URL for Electron is -https://symbols.electronjs.org. +<https://symbols.electronjs.org>. You cannot visit this URL directly, you must add it to the symbol path of your debugging tool. In the examples below, a local cache directory is used to avoid repeatedly fetching the PDB from the server. Replace `c:\code\symbols` with an
docs
9c48992e21c64f25391b7057c85f35a61ba5ff08
hyrious
2022-11-19 07:21:11
chore: fix dangling promise in npm install (#36379) * Fix dangling promise introduced in #33979 * fix reject in callback * simplify code Co-authored-by: Black-Hole <[email protected]> Co-authored-by: Black-Hole <[email protected]>
diff --git a/npm/install.js b/npm/install.js index 864ca633fd..8fb438ecac 100755 --- a/npm/install.js +++ b/npm/install.js @@ -70,29 +70,21 @@ function isInstalled () { // unzips and makes path.txt point at the correct executable function extractFile (zipPath) { - return new Promise((resolve, reject) => { - const distPath = process.env.ELECTRON_OVERRIDE_DIST_PATH || path.join(__dirname, 'dist'); - - extract(zipPath, { dir: path.join(__dirname, 'dist') }) - .then(() => { - // If the zip contains an "electron.d.ts" file, - // move that up - const srcTypeDefPath = path.join(distPath, 'electron.d.ts'); - const targetTypeDefPath = path.join(__dirname, 'electron.d.ts'); - const hasTypeDefinitions = fs.existsSync(srcTypeDefPath); - - if (hasTypeDefinitions) { - try { - fs.renameSync(srcTypeDefPath, targetTypeDefPath); - } catch (err) { - reject(err); - } - } - - // Write a "path.txt" file. - return fs.promises.writeFile(path.join(__dirname, 'path.txt'), platformPath); - }) - .catch((err) => reject(err)); + const distPath = process.env.ELECTRON_OVERRIDE_DIST_PATH || path.join(__dirname, 'dist'); + + return extract(zipPath, { dir: path.join(__dirname, 'dist') }).then(() => { + // If the zip contains an "electron.d.ts" file, + // move that up + const srcTypeDefPath = path.join(distPath, 'electron.d.ts'); + const targetTypeDefPath = path.join(__dirname, 'electron.d.ts'); + const hasTypeDefinitions = fs.existsSync(srcTypeDefPath); + + if (hasTypeDefinitions) { + fs.renameSync(srcTypeDefPath, targetTypeDefPath); + } + + // Write a "path.txt" file. + return fs.promises.writeFile(path.join(__dirname, 'path.txt'), platformPath); }); }
chore
e73edb54817acb8f0e548916a97a9ed9340dfc3f
Shelley Vohr
2023-06-21 15:31:28
feat: allow headers to be sent with `session.downloadURL()` (#38785)
diff --git a/docs/api/session.md b/docs/api/session.md index e999a5207b..ed5ff247f9 100644 --- a/docs/api/session.md +++ b/docs/api/session.md @@ -1284,9 +1284,11 @@ reused for new connections. Returns `Promise<Buffer>` - resolves with blob data. -#### `ses.downloadURL(url)` +#### `ses.downloadURL(url[, options])` * `url` string +* `options` Object (optional) + * `headers` Record<string, string> (optional) - HTTP request headers. Initiates a download of the resource at `url`. The API will generate a [DownloadItem](download-item.md) that can be accessed diff --git a/shell/browser/api/electron_api_session.cc b/shell/browser/api/electron_api_session.cc index b78d0ee273..82594de091 100644 --- a/shell/browser/api/electron_api_session.cc +++ b/shell/browser/api/electron_api_session.cc @@ -804,10 +804,24 @@ v8::Local<v8::Promise> Session::GetBlobData(v8::Isolate* isolate, return holder->ReadAll(isolate); } -void Session::DownloadURL(const GURL& url) { - auto* download_manager = browser_context()->GetDownloadManager(); +void Session::DownloadURL(const GURL& url, gin::Arguments* args) { + std::map<std::string, std::string> headers; + gin_helper::Dictionary options; + if (args->GetNext(&options)) { + if (options.Has("headers") && !options.Get("headers", &headers)) { + args->ThrowTypeError("Invalid value for headers - must be an object"); + return; + } + } + auto download_params = std::make_unique<download::DownloadUrlParameters>( url, MISSING_TRAFFIC_ANNOTATION); + + for (const auto& [name, value] : headers) { + download_params->add_request_header(name, value); + } + + auto* download_manager = browser_context()->GetDownloadManager(); download_manager->DownloadUrl(std::move(download_params)); } diff --git a/shell/browser/api/electron_api_session.h b/shell/browser/api/electron_api_session.h index 1111017430..dec77b2c5e 100644 --- a/shell/browser/api/electron_api_session.h +++ b/shell/browser/api/electron_api_session.h @@ -131,7 +131,7 @@ class Session : public gin::Wrappable<Session>, bool IsPersistent(); v8::Local<v8::Promise> GetBlobData(v8::Isolate* isolate, const std::string& uuid); - void DownloadURL(const GURL& url); + void DownloadURL(const GURL& url, gin::Arguments* args); void CreateInterruptedDownload(const gin_helper::Dictionary& options); void SetPreloads(const std::vector<base::FilePath>& preloads); std::vector<base::FilePath> GetPreloads() const; diff --git a/spec/api-session-spec.ts b/spec/api-session-spec.ts index 5105574571..7d483e6f9b 100644 --- a/spec/api-session-spec.ts +++ b/spec/api-session-spec.ts @@ -788,6 +788,7 @@ describe('session module', () => { const contentDisposition = 'inline; filename="mock.pdf"'; let port: number; let downloadServer: http.Server; + before(async () => { downloadServer = http.createServer((req, res) => { res.writeHead(200, { @@ -799,9 +800,11 @@ describe('session module', () => { }); port = (await listen(downloadServer)).port; }); + after(async () => { await new Promise(resolve => downloadServer.close(resolve)); }); + afterEach(closeAllWindows); const isPathEqual = (path1: string, path2: string) => { @@ -840,6 +843,103 @@ describe('session module', () => { session.defaultSession.downloadURL(`${url}:${port}`); }); + it('can download using session.downloadURL with a valid auth header', async () => { + const server = http.createServer((req, res) => { + const { authorization } = req.headers; + if (!authorization || authorization !== 'Basic i-am-an-auth-header') { + res.statusCode = 401; + res.setHeader('WWW-Authenticate', 'Basic realm="Restricted"'); + res.end(); + } else { + res.writeHead(200, { + 'Content-Length': mockPDF.length, + 'Content-Type': 'application/pdf', + 'Content-Disposition': req.url === '/?testFilename' ? 'inline' : contentDisposition + }); + res.end(mockPDF); + } + }); + + const { port } = await listen(server); + + const downloadDone: Promise<Electron.DownloadItem> = new Promise((resolve) => { + session.defaultSession.once('will-download', (e, item) => { + item.savePath = downloadFilePath; + item.on('done', () => { + try { + resolve(item); + } catch {} + }); + }); + }); + + session.defaultSession.downloadURL(`${url}:${port}`, { + headers: { + Authorization: 'Basic i-am-an-auth-header' + } + }); + + const item = await downloadDone; + expect(item.getState()).to.equal('completed'); + expect(item.getFilename()).to.equal('mock.pdf'); + expect(item.getMimeType()).to.equal('application/pdf'); + expect(item.getReceivedBytes()).to.equal(mockPDF.length); + expect(item.getTotalBytes()).to.equal(mockPDF.length); + expect(item.getContentDisposition()).to.equal(contentDisposition); + }); + + it('throws when session.downloadURL is called with invalid headers', () => { + expect(() => { + session.defaultSession.downloadURL(`${url}:${port}`, { + // @ts-ignore this line is intentionally incorrect + headers: 'i-am-a-bad-header' + }); + }).to.throw(/Invalid value for headers - must be an object/); + }); + + it('can download using session.downloadURL with an invalid auth header', async () => { + const server = http.createServer((req, res) => { + const { authorization } = req.headers; + if (!authorization || authorization !== 'Basic i-am-an-auth-header') { + res.statusCode = 401; + res.setHeader('WWW-Authenticate', 'Basic realm="Restricted"'); + res.end(); + } else { + res.writeHead(200, { + 'Content-Length': mockPDF.length, + 'Content-Type': 'application/pdf', + 'Content-Disposition': req.url === '/?testFilename' ? 'inline' : contentDisposition + }); + res.end(mockPDF); + } + }); + + const { port } = await listen(server); + + const downloadFailed: Promise<Electron.DownloadItem> = new Promise((resolve) => { + session.defaultSession.once('will-download', (_, item) => { + item.savePath = downloadFilePath; + item.on('done', (e, state) => { + console.log(state); + try { + resolve(item); + } catch {} + }); + }); + }); + + session.defaultSession.downloadURL(`${url}:${port}`, { + headers: { + Authorization: 'wtf-is-this' + } + }); + + const item = await downloadFailed; + expect(item.getState()).to.equal('interrupted'); + expect(item.getReceivedBytes()).to.equal(0); + expect(item.getTotalBytes()).to.equal(0); + }); + it('can download using WebContents.downloadURL', (done) => { const w = new BrowserWindow({ show: false }); w.webContents.session.once('will-download', function (e, item) {
feat
666907d50d2d62e31e1c3e7329f45e8350fe73cd
Shelley Vohr
2023-10-18 01:33:00
fix: Windows Toast notification dismissal from Action Center (#40197) * fix: Windows Toast notification dismissal from Action Center * docs: note Toast behavior in event * chore: address feedback from review
diff --git a/docs/api/notification.md b/docs/api/notification.md index a758639a8c..fe12a9d050 100644 --- a/docs/api/notification.md +++ b/docs/api/notification.md @@ -85,6 +85,8 @@ Emitted when the notification is closed by manual intervention from the user. This event is not guaranteed to be emitted in all cases where the notification is closed. +On Windows, the `close` event can be emitted in one of three ways: programmatic dismissal with `notification.close()`, by the user closing the notification, or via system timeout. If a notification is in the Action Center after the initial `close` event is emitted, a call to `notification.close()` will remove the notification from the action center but the `close` event will not be emitted again. + #### Event: 'reply' _macOS_ Returns: @@ -127,6 +129,8 @@ shown notification and create a new one with identical properties. Dismisses the notification. +On Windows, calling `notification.close()` while the notification is visible on screen will dismiss the notification and remove it from the Action Center. If `notification.close()` is called after the notification is no longer visible on screen, calling `notification.close()` will try remove it from the Action Center. + ### Instance Properties #### `notification.title` diff --git a/shell/browser/api/electron_api_notification.cc b/shell/browser/api/electron_api_notification.cc index 0b3e574f6e..38d5571ff5 100644 --- a/shell/browser/api/electron_api_notification.cc +++ b/shell/browser/api/electron_api_notification.cc @@ -216,7 +216,11 @@ void Notification::NotificationClosed() { void Notification::Close() { if (notification_) { - notification_->Dismiss(); + if (notification_->is_dismissed()) { + notification_->Remove(); + } else { + notification_->Dismiss(); + } notification_->set_delegate(nullptr); notification_.reset(); } diff --git a/shell/browser/notifications/notification.cc b/shell/browser/notifications/notification.cc index 0b8a3407e5..40b5f846fd 100644 --- a/shell/browser/notifications/notification.cc +++ b/shell/browser/notifications/notification.cc @@ -27,10 +27,14 @@ void Notification::NotificationClicked() { Destroy(); } -void Notification::NotificationDismissed() { +void Notification::NotificationDismissed(bool should_destroy) { if (delegate()) delegate()->NotificationClosed(); - Destroy(); + + set_is_dismissed(true); + + if (should_destroy) + Destroy(); } void Notification::NotificationFailed(const std::string& error) { @@ -39,6 +43,8 @@ void Notification::NotificationFailed(const std::string& error) { Destroy(); } +void Notification::Remove() {} + void Notification::Destroy() { presenter()->RemoveNotification(this); } diff --git a/shell/browser/notifications/notification.h b/shell/browser/notifications/notification.h index e3c65090ce..391d0e26fd 100644 --- a/shell/browser/notifications/notification.h +++ b/shell/browser/notifications/notification.h @@ -50,13 +50,19 @@ class Notification { // Shows the notification. virtual void Show(const NotificationOptions& options) = 0; - // Closes the notification, this instance will be destroyed after the - // notification gets closed. + + // Dismisses the notification. On some platforms this will result in full + // removal and destruction of the notification, but if the initial dismissal + // does not fully get rid of the notification it will be destroyed in Remove. virtual void Dismiss() = 0; + // Removes the notification if it was not fully removed during dismissal, + // as can happen on some platforms including Windows. + virtual void Remove(); + // Should be called by derived classes. void NotificationClicked(); - void NotificationDismissed(); + void NotificationDismissed(bool should_destroy = true); void NotificationFailed(const std::string& error = ""); // delete this. @@ -68,10 +74,12 @@ class Notification { void set_delegate(NotificationDelegate* delegate) { delegate_ = delegate; } void set_notification_id(const std::string& id) { notification_id_ = id; } + void set_is_dismissed(bool dismissed) { is_dismissed_ = dismissed; } NotificationDelegate* delegate() const { return delegate_; } NotificationPresenter* presenter() const { return presenter_; } const std::string& notification_id() const { return notification_id_; } + bool is_dismissed() const { return is_dismissed_; } // disable copy Notification(const Notification&) = delete; @@ -85,6 +93,7 @@ class Notification { raw_ptr<NotificationDelegate> delegate_; raw_ptr<NotificationPresenter> presenter_; std::string notification_id_; + bool is_dismissed_ = false; base::WeakPtrFactory<Notification> weak_factory_{this}; }; diff --git a/shell/browser/notifications/win/windows_toast_notification.cc b/shell/browser/notifications/win/windows_toast_notification.cc index 05d508bbe5..ba64376c74 100644 --- a/shell/browser/notifications/win/windows_toast_notification.cc +++ b/shell/browser/notifications/win/windows_toast_notification.cc @@ -8,6 +8,8 @@ #include "shell/browser/notifications/win/windows_toast_notification.h" +#include <string_view> + #include <shlobj.h> #include <wrl\wrappers\corewrappers.h> @@ -34,6 +36,8 @@ using ABI::Windows::Data::Xml::Dom::IXmlNodeList; using ABI::Windows::Data::Xml::Dom::IXmlText; using Microsoft::WRL::Wrappers::HStringReference; +namespace winui = ABI::Windows::UI; + #define RETURN_IF_FAILED(hr) \ do { \ HRESULT _hrTemp = hr; \ @@ -47,8 +51,7 @@ using Microsoft::WRL::Wrappers::HStringReference; std::string _msgTemp = msg; \ if (FAILED(_hrTemp)) { \ std::string _err = _msgTemp + ",ERROR " + std::to_string(_hrTemp); \ - if (IsDebuggingNotifications()) \ - LOG(INFO) << _err; \ + DebugLog(_err); \ Notification::NotificationFailed(_err); \ return _hrTemp; \ } \ @@ -58,17 +61,23 @@ namespace electron { namespace { -bool IsDebuggingNotifications() { - return base::Environment::Create()->HasVar("ELECTRON_DEBUG_NOTIFICATIONS"); +// This string needs to be max 16 characters to work on Windows 10 prior to +// applying Creators Update (build 15063). +constexpr wchar_t kGroup[] = L"Notifications"; + +void DebugLog(std::string_view log_msg) { + if (base::Environment::Create()->HasVar("ELECTRON_DEBUG_NOTIFICATIONS")) + LOG(INFO) << log_msg; } + } // namespace // static -ComPtr<ABI::Windows::UI::Notifications::IToastNotificationManagerStatics> +ComPtr<winui::Notifications::IToastNotificationManagerStatics> WindowsToastNotification::toast_manager_; // static -ComPtr<ABI::Windows::UI::Notifications::IToastNotifier> +ComPtr<winui::Notifications::IToastNotifier> WindowsToastNotification::toast_notifier_; // static @@ -112,17 +121,37 @@ WindowsToastNotification::~WindowsToastNotification() { void WindowsToastNotification::Show(const NotificationOptions& options) { if (SUCCEEDED(ShowInternal(options))) { - if (IsDebuggingNotifications()) - LOG(INFO) << "Notification created"; + DebugLog("Notification created"); if (delegate()) delegate()->NotificationDisplayed(); } } +void WindowsToastNotification::Remove() { + DebugLog("Removing notification from action center"); + + ComPtr<winui::Notifications::IToastNotificationManagerStatics2> + toast_manager2; + if (FAILED(toast_manager_.As(&toast_manager2))) + return; + + ComPtr<winui::Notifications::IToastNotificationHistory> notification_history; + if (FAILED(toast_manager2->get_History(&notification_history))) + return; + + ScopedHString app_id; + if (!GetAppUserModelID(&app_id)) + return; + + ScopedHString group(kGroup); + ScopedHString tag(base::as_wcstr(base::UTF8ToUTF16(notification_id()))); + notification_history->RemoveGroupedTagWithId(tag, group, app_id); +} + void WindowsToastNotification::Dismiss() { - if (IsDebuggingNotifications()) - LOG(INFO) << "Hiding notification"; + DebugLog("Hiding notification"); + toast_notifier_->Hide(toast_notification_.Get()); } @@ -151,8 +180,7 @@ HRESULT WindowsToastNotification::ShowInternal( return E_FAIL; } - ComPtr<ABI::Windows::UI::Notifications::IToastNotificationFactory> - toast_factory; + ComPtr<winui::Notifications::IToastNotificationFactory> toast_factory; REPORT_AND_RETURN_IF_FAILED( Windows::Foundation::GetActivationFactory(toast_str, &toast_factory), "WinAPI: GetActivationFactory failed"); @@ -161,6 +189,19 @@ HRESULT WindowsToastNotification::ShowInternal( toast_xml.Get(), &toast_notification_), "WinAPI: CreateToastNotification failed"); + ComPtr<winui::Notifications::IToastNotification2> toast2; + REPORT_AND_RETURN_IF_FAILED( + toast_notification_->QueryInterface(IID_PPV_ARGS(&toast2)), + "WinAPI: Getting Notification interface failed"); + + ScopedHString group(kGroup); + REPORT_AND_RETURN_IF_FAILED(toast2->put_Group(group), + "WinAPI: Setting group failed"); + + ScopedHString tag(base::as_wcstr(base::UTF8ToUTF16(notification_id()))); + REPORT_AND_RETURN_IF_FAILED(toast2->put_Tag(tag), + "WinAPI: Setting tag failed"); + REPORT_AND_RETURN_IF_FAILED(SetupCallbacks(toast_notification_.Get()), "WinAPI: SetupCallbacks failed"); @@ -170,22 +211,20 @@ HRESULT WindowsToastNotification::ShowInternal( } HRESULT WindowsToastNotification::GetToastXml( - ABI::Windows::UI::Notifications::IToastNotificationManagerStatics* - toastManager, + winui::Notifications::IToastNotificationManagerStatics* toastManager, const std::u16string& title, const std::u16string& msg, const std::wstring& icon_path, const std::u16string& timeout_type, bool silent, IXmlDocument** toast_xml) { - ABI::Windows::UI::Notifications::ToastTemplateType template_type; + winui::Notifications::ToastTemplateType template_type; if (title.empty() || msg.empty()) { // Single line toast. template_type = icon_path.empty() - ? ABI::Windows::UI::Notifications::ToastTemplateType_ToastText01 - : ABI::Windows::UI::Notifications:: - ToastTemplateType_ToastImageAndText01; + ? winui::Notifications::ToastTemplateType_ToastText01 + : winui::Notifications::ToastTemplateType_ToastImageAndText01; REPORT_AND_RETURN_IF_FAILED( toast_manager_->GetTemplateContent(template_type, toast_xml), "XML: Fetching XML ToastImageAndText01 template failed"); @@ -199,9 +238,8 @@ HRESULT WindowsToastNotification::GetToastXml( // Title and body toast. template_type = icon_path.empty() - ? ABI::Windows::UI::Notifications::ToastTemplateType_ToastText02 - : ABI::Windows::UI::Notifications:: - ToastTemplateType_ToastImageAndText02; + ? winui::Notifications::ToastTemplateType_ToastText02 + : winui::Notifications::ToastTemplateType_ToastImageAndText02; REPORT_AND_RETURN_IF_FAILED( toastManager->GetTemplateContent(template_type, toast_xml), "XML: Fetching XML ToastImageAndText02 template failed"); @@ -567,7 +605,7 @@ HRESULT WindowsToastNotification::XmlDocumentFromString( } HRESULT WindowsToastNotification::SetupCallbacks( - ABI::Windows::UI::Notifications::IToastNotification* toast) { + winui::Notifications::IToastNotification* toast) { event_handler_ = Make<ToastEventHandler>(this); RETURN_IF_FAILED( toast->add_Activated(event_handler_.Get(), &activated_token_)); @@ -578,7 +616,7 @@ HRESULT WindowsToastNotification::SetupCallbacks( } bool WindowsToastNotification::RemoveCallbacks( - ABI::Windows::UI::Notifications::IToastNotification* toast) { + winui::Notifications::IToastNotification* toast) { if (FAILED(toast->remove_Activated(activated_token_))) return false; @@ -597,32 +635,29 @@ ToastEventHandler::ToastEventHandler(Notification* notification) ToastEventHandler::~ToastEventHandler() = default; IFACEMETHODIMP ToastEventHandler::Invoke( - ABI::Windows::UI::Notifications::IToastNotification* sender, + winui::Notifications::IToastNotification* sender, IInspectable* args) { content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&Notification::NotificationClicked, notification_)); - if (IsDebuggingNotifications()) - LOG(INFO) << "Notification clicked"; + DebugLog("Notification clicked"); return S_OK; } IFACEMETHODIMP ToastEventHandler::Invoke( - ABI::Windows::UI::Notifications::IToastNotification* sender, - ABI::Windows::UI::Notifications::IToastDismissedEventArgs* e) { + winui::Notifications::IToastNotification* sender, + winui::Notifications::IToastDismissedEventArgs* e) { content::GetUIThreadTaskRunner({})->PostTask( - FROM_HERE, - base::BindOnce(&Notification::NotificationDismissed, notification_)); - if (IsDebuggingNotifications()) - LOG(INFO) << "Notification dismissed"; - + FROM_HERE, base::BindOnce(&Notification::NotificationDismissed, + notification_, false)); + DebugLog("Notification dismissed"); return S_OK; } IFACEMETHODIMP ToastEventHandler::Invoke( - ABI::Windows::UI::Notifications::IToastNotification* sender, - ABI::Windows::UI::Notifications::IToastFailedEventArgs* e) { + winui::Notifications::IToastNotification* sender, + winui::Notifications::IToastFailedEventArgs* e) { HRESULT error; e->get_ErrorCode(&error); std::string errorMessage = @@ -630,8 +665,7 @@ IFACEMETHODIMP ToastEventHandler::Invoke( content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&Notification::NotificationFailed, notification_, errorMessage)); - if (IsDebuggingNotifications()) - LOG(INFO) << errorMessage; + DebugLog(errorMessage); return S_OK; } diff --git a/shell/browser/notifications/win/windows_toast_notification.h b/shell/browser/notifications/win/windows_toast_notification.h index 509f1c1259..3d3398ce0d 100644 --- a/shell/browser/notifications/win/windows_toast_notification.h +++ b/shell/browser/notifications/win/windows_toast_notification.h @@ -52,6 +52,7 @@ class WindowsToastNotification : public Notification { // Notification: void Show(const NotificationOptions& options) override; void Dismiss() override; + void Remove() override; private: friend class ToastEventHandler;
fix
a329024793fcdb388212d283166cccfc3a9817c9
John Kleinschmidt
2025-02-14 13:19:43
build: make sure chromium cookie is set everywhere (#45631)
diff --git a/.github/workflows/pipeline-electron-lint.yml b/.github/workflows/pipeline-electron-lint.yml index 38dac828ca..acbf2a6510 100644 --- a/.github/workflows/pipeline-electron-lint.yml +++ b/.github/workflows/pipeline-electron-lint.yml @@ -12,6 +12,9 @@ concurrency: group: electron-lint-${{ github.ref_protected == true && github.run_id || github.ref }} cancel-in-progress: ${{ github.ref_protected != true }} +env: + CHROMIUM_GIT_COOKIE: ${{ secrets.CHROMIUM_GIT_COOKIE }} + jobs: lint: name: Lint diff --git a/.github/workflows/pipeline-segment-node-nan-test.yml b/.github/workflows/pipeline-segment-node-nan-test.yml index f4f5fdd9c0..ab3e9d1186 100644 --- a/.github/workflows/pipeline-segment-node-nan-test.yml +++ b/.github/workflows/pipeline-segment-node-nan-test.yml @@ -31,6 +31,7 @@ concurrency: cancel-in-progress: ${{ github.ref_protected != true }} env: + CHROMIUM_GIT_COOKIE: ${{ secrets.CHROMIUM_GIT_COOKIE }} ELECTRON_OUT_DIR: Default ELECTRON_RBE_JWT: ${{ secrets.ELECTRON_RBE_JWT }}
build
08241669bc7a899142a7dbd48ee27dc5a9af5c12
Shelley Vohr
2024-03-27 19:52:24
test: add tests for Storage Access API (#41698)
diff --git a/docs/api/session.md b/docs/api/session.md index 54a1d160ea..ffd3ee33d9 100644 --- a/docs/api/session.md +++ b/docs/api/session.md @@ -814,6 +814,8 @@ win.webContents.session.setCertificateVerifyProc((request, callback) => { * `keyboardLock` - Request capture of keypresses for any or all of the keys on the physical keyboard via the [Keyboard Lock API](https://developer.mozilla.org/en-US/docs/Web/API/Keyboard/lock). These requests always appear to originate from the main frame. * `openExternal` - Request to open links in external applications. * `speaker-selection` - Request to enumerate and select audio output devices via the [speaker-selection permissions policy](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Permissions-Policy/speaker-selection). + * `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). * `window-management` - Request access to enumerate screens using the [`getScreenDetails`](https://developer.chrome.com/en/articles/multi-screen-window-placement/) API. * `unknown` - An unrecognized permission request. * `callback` Function @@ -862,6 +864,8 @@ session.fromPartition('some-partition').setPermissionRequestHandler((webContents * `openExternal` - Open links in external applications. * `pointerLock` - Directly interpret mouse movements as an input method via the [Pointer Lock API](https://developer.mozilla.org/en-US/docs/Web/API/Pointer_Lock_API). These requests always appear to originate from the main frame. * `serial` - Read from and write to serial devices with the [Web Serial API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Serial_API). + * `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). * `requestingOrigin` string - The origin URL of the permission check * `details` Object - Some properties are only available on certain permission types. diff --git a/spec/chromium-spec.ts b/spec/chromium-spec.ts index 7f64caad59..8cfc735e1d 100644 --- a/spec/chromium-spec.ts +++ b/spec/chromium-spec.ts @@ -1383,6 +1383,138 @@ describe('chromium features', () => { }); }); + describe('Storage Access API', () => { + afterEach(closeAllWindows); + afterEach(() => { + session.defaultSession.setPermissionCheckHandler(null); + session.defaultSession.setPermissionRequestHandler(null); + }); + + it('can determine if a permission is granted for "storage-access"', async () => { + session.defaultSession.setPermissionCheckHandler( + (_wc, permission) => permission === 'storage-access' + ); + + const w = new BrowserWindow({ show: false }); + await w.loadFile(path.join(fixturesPath, 'pages', 'a.html')); + + const permission = await w.webContents.executeJavaScript(` + navigator.permissions.query({ name: 'storage-access' }) + .then(permission => permission.state).catch(err => err.message); + `, true); + + expect(permission).to.eq('granted'); + }); + + it('can determine if a permission is denied for "storage-access"', async () => { + session.defaultSession.setPermissionCheckHandler( + (_wc, permission) => permission !== 'storage-access' + ); + + const w = new BrowserWindow({ show: false }); + await w.loadFile(path.join(fixturesPath, 'pages', 'a.html')); + + const permission = await w.webContents.executeJavaScript(` + navigator.permissions.query({ name: 'storage-access' }) + .then(permission => permission.state).catch(err => err.message); + `, true); + + expect(permission).to.eq('denied'); + }); + + it('can determine if a permission is granted for "top-level-storage-access"', async () => { + session.defaultSession.setPermissionCheckHandler( + (_wc, permission) => permission === 'top-level-storage-access' + ); + + const w = new BrowserWindow({ show: false }); + await w.loadFile(path.join(fixturesPath, 'pages', 'a.html')); + + const permission = await w.webContents.executeJavaScript(` + navigator.permissions.query({ + name: 'top-level-storage-access', + requestedOrigin: "https://www.example.com", + }).then(permission => permission.state).catch(err => err.message); + `, true); + + expect(permission).to.eq('granted'); + }); + + it('can determine if a permission is denied for "top-level-storage-access"', async () => { + session.defaultSession.setPermissionCheckHandler( + (_wc, permission) => permission !== 'top-level-storage-access' + ); + + const w = new BrowserWindow({ show: false }); + await w.loadFile(path.join(fixturesPath, 'pages', 'a.html')); + + const permission = await w.webContents.executeJavaScript(` + navigator.permissions.query({ + name: 'top-level-storage-access', + requestedOrigin: "https://www.example.com", + }).then(permission => permission.state).catch(err => err.message); + `, true); + + expect(permission).to.eq('denied'); + }); + + it('can grant a permission request for "top-level-storage-access"', async () => { + session.defaultSession.setPermissionRequestHandler( + (_wc, permission, callback) => { + callback(permission === 'top-level-storage-access'); + } + ); + + const w = new BrowserWindow({ show: false }); + await w.loadFile(path.join(fixturesPath, 'pages', 'button.html')); + + // requestStorageAccessFor returns a Promise that fulfills with undefined + // if the access to third-party cookies was granted and rejects if access was denied. + const permission = await w.webContents.executeJavaScript(` + new Promise((resolve, reject) => { + const button = document.getElementById('button'); + button.addEventListener("click", () => { + document.requestStorageAccessFor('https://myfakesite').then( + (res) => { resolve('granted') }, + (err) => { resolve('denied') }, + ); + }); + button.click(); + }); + `, true); + + expect(permission).to.eq('granted'); + }); + + it('can deny a permission request for "top-level-storage-access"', async () => { + session.defaultSession.setPermissionRequestHandler( + (_wc, permission, callback) => { + callback(permission !== 'top-level-storage-access'); + } + ); + + const w = new BrowserWindow({ show: false }); + await w.loadFile(path.join(fixturesPath, 'pages', 'button.html')); + + // requestStorageAccessFor returns a Promise that fulfills with undefined + // if the access to third-party cookies was granted and rejects if access was denied. + const permission = await w.webContents.executeJavaScript(` + new Promise((resolve, reject) => { + const button = document.getElementById('button'); + button.addEventListener("click", () => { + document.requestStorageAccessFor('https://myfakesite').then( + (res) => { resolve('granted') }, + (err) => { resolve('denied') }, + ); + }); + button.click(); + }); + `, true); + + expect(permission).to.eq('denied'); + }); + }); + describe('IdleDetection', () => { afterEach(closeAllWindows); afterEach(() => {
test
acd39bd077b28588e5b1488739f6f650b9b3c1b7
David Sanders
2024-08-05 06:52:49
ci: auto label bug issues with platform (#43198)
diff --git a/.github/workflows/issue-opened.yml b/.github/workflows/issue-opened.yml index 011a815101..b07387daf1 100644 --- a/.github/workflows/issue-opened.yml +++ b/.github/workflows/issue-opened.yml @@ -86,6 +86,29 @@ jobs: } } + const operatingSystems = select('heading:has(> text[value="What operating system(s) are you using?"]) + paragraph > text', tree)?.value.trim().split(', '); + const platformLabels = new Set(); + for (const operatingSystem of (operatingSystems ?? [])) { + switch (operatingSystem) { + case 'Windows': + platformLabels.add('platform/windows'); + break; + case 'macOS': + platformLabels.add('platform/macOS'); + break; + case 'Ubuntu': + case 'Other Linux': + platformLabels.add('platform/linux'); + break; + } + } + + if (platformLabels.size === 3) { + labels.push('platform/all'); + } else { + labels.push(...platformLabels); + } + const gistUrl = select('heading:has(> text[value="Testcase Gist URL"]) + paragraph > text', tree)?.value.trim(); if (gistUrl !== undefined && gistUrl.startsWith('https://gist.github.com/')) { labels.push('has-repro-gist');
ci
f9a04012b91539813b937b66c8998b4b068815f7
Keeley Hammond
2024-11-07 19:20:50
build: revert bump Node.js to v22.9.0 (#44596) * Revert "chore: bump Node.js to v22.9.0 (#44281)" This reverts commit c63d0d61e71f12d29efb1df885a0883ae76bb164. * chore: update patches
diff --git a/.github/workflows/pipeline-segment-electron-test.yml b/.github/workflows/pipeline-segment-electron-test.yml index 5e91be33db..ab850c0e77 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 detect_container_overflow=0" + 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 diff --git a/BUILD.gn b/BUILD.gn index aacd4bde19..91dd30d516 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/node.gni") +import("//third_party/electron_node/electron_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_external_config", + "//third_party/electron_node:node_internals", ] 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:libnode", + "//third_party/electron_node:node_lib", "//third_party/inspector_protocol:crdtp", "//third_party/leveldatabase", "//third_party/libyuv", @@ -868,7 +868,7 @@ if (is_mac) { ":electron_framework_resources", ":electron_swiftshader_library", ":electron_xibs", - "//third_party/electron_node:libnode", + "//third_party/electron_node:node_lib", ] if (!is_mas_build) { deps += [ ":electron_crashpad_helper" ] @@ -1192,7 +1192,7 @@ if (is_mac) { "//components/crash/core/app", "//content:sandbox_helper_win", "//electron/buildflags", - "//third_party/electron_node:libnode", + "//third_party/electron_node:node_lib", "//ui/strings", ] diff --git a/DEPS b/DEPS index ccc312f95c..a82794f41b 100644 --- a/DEPS +++ b/DEPS @@ -4,7 +4,7 @@ vars = { 'chromium_version': '132.0.6820.0', 'node_version': - 'v22.9.0', + 'v20.18.0', 'nan_version': 'e14bdcd1f72d62bca1d541b66da43130384ec213', 'squirrel.mac_version': diff --git a/docs/tutorial/multithreading.md b/docs/tutorial/multithreading.md index ab70b88a50..eb2bcc9e47 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 +```js @ts-expect-error=[1] 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 a46b97290f..aebd5b3021 100644 --- a/lib/node/asar-fs-wrapper.ts +++ b/lib/node/asar-fs-wrapper.ts @@ -841,27 +841,6 @@ 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 96fd3c3ad0..69015766c5 100644 --- a/npm/package.json +++ b/npm/package.json @@ -9,7 +9,7 @@ }, "dependencies": { "@electron/get": "^2.0.0", - "@types/node": "^22.7.7", + "@types/node": "^20.9.0", "extract-zip": "^2.0.1" }, "engines": { diff --git a/package.json b/package.json index 12b3f777d2..6b1f040c78 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": "^22.7.7", + "@types/node": "^20.9.0", "@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 ef798e6bf1..c8b4c3a439 100644 --- a/patches/chromium/build_allow_electron_to_use_exec_script.patch +++ b/patches/chromium/build_allow_electron_to_use_exec_script.patch @@ -6,34 +6,15 @@ 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..3e880eed02ca57db10d734d6a7566e0a977433a5 100644 +index 44a11ec90ec9b67cf22b6d529c6843e6b6af12bc..783dd77dcdf92ec32cc6594b739eab9738f3e3ba 100644 --- a/.gn +++ b/.gn -@@ -172,4 +172,27 @@ exec_script_whitelist = +@@ -172,4 +172,8 @@ 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 8d297c0fd3..8cf28d8d2b 100644 --- a/patches/config.json +++ b/patches/config.json @@ -11,6 +11,5 @@ { "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/sqlite", "repo": "src/third_party/sqlite/src" } + { "patch_dir": "src/electron/patches/reclient-configs", "repo": "src/third_party/engflow-reclient-configs" } ] diff --git a/patches/node/.patches b/patches/node/.patches index d8853df516..abdfda54fa 100644 --- a/patches/node/.patches +++ b/patches/node/.patches @@ -21,25 +21,37 @@ 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 -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 -chore_disable_deprecation_ftbfs_in_simdjson_header.patch +esm_drop_support_for_import_assertions.patch diff --git a/patches/node/build_add_gn_build_files.patch b/patches/node/build_add_gn_build_files.patch index 1fc6f58658..1cb0332f0c 100644 --- a/patches/node/build_add_gn_build_files.patch +++ b/patches/node/build_add_gn_build_files.patch @@ -10,58 +10,1268 @@ 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/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(); +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") - 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", +-# 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", + ] - if (is_win) { -- cflags_c = [ -+ cflags_c += [ - "-Wno-sign-compare", - "-Wno-unused-but-set-variable", - "-Wno-unused-function", ++ } ++ ++ 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 = "" ++} diff --git a/filenames.json b/filenames.json new file mode 100644 -index 0000000000000000000000000000000000000000..5af3886d8d3d74d31249a4d79030a8373b8dad52 +index 0000000000000000000000000000000000000000..889a487e24721a8ecfef91f5a655892a607bb12f --- /dev/null +++ b/filenames.json -@@ -0,0 +1,756 @@ +@@ -0,0 +1,741 @@ +// This file is automatically generated by generate_gn_filenames_json.py +// DO NOT EDIT +{ @@ -69,7 +1279,6 @@ index 0000000000000000000000000000000000000000..5af3886d8d3d74d31249a4d79030a837 + "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", @@ -272,10 +1481,7 @@ index 0000000000000000000000000000000000000000..5af3886d8d3d74d31249a4d79030a837 + "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", @@ -321,7 +1527,6 @@ index 0000000000000000000000000000000000000000..5af3886d8d3d74d31249a4d79030a837 + "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", @@ -377,6 +1582,7 @@ index 0000000000000000000000000000000000000000..5af3886d8d3d74d31249a4d79030a837 + "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", @@ -401,11 +1607,13 @@ index 0000000000000000000000000000000000000000..5af3886d8d3d74d31249a4d79030a837 + "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", @@ -429,7 +1637,6 @@ index 0000000000000000000000000000000000000000..5af3886d8d3d74d31249a4d79030a837 + "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", @@ -464,7 +1671,6 @@ index 0000000000000000000000000000000000000000..5af3886d8d3d74d31249a4d79030a837 + "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", @@ -478,8 +1684,10 @@ index 0000000000000000000000000000000000000000..5af3886d8d3d74d31249a4d79030a837 + "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", @@ -493,7 +1701,6 @@ index 0000000000000000000000000000000000000000..5af3886d8d3d74d31249a4d79030a837 + "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", @@ -506,7 +1713,6 @@ index 0000000000000000000000000000000000000000..5af3886d8d3d74d31249a4d79030a837 + "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", @@ -521,7 +1727,6 @@ index 0000000000000000000000000000000000000000..5af3886d8d3d74d31249a4d79030a837 + "lib/readline/promises.js", + "lib/repl.js", + "lib/sea.js", -+ "lib/sqlite.js", + "lib/stream.js", + "lib/stream/consumers.js", + "lib/stream/promises.js", @@ -570,12 +1775,10 @@ index 0000000000000000000000000000000000000000..5af3886d8d3d74d31249a4d79030a837 + "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", @@ -609,7 +1812,6 @@ index 0000000000000000000000000000000000000000..5af3886d8d3d74d31249a4d79030a837 + "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", @@ -622,7 +1824,6 @@ index 0000000000000000000000000000000000000000..5af3886d8d3d74d31249a4d79030a837 + "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", @@ -640,11 +1841,9 @@ index 0000000000000000000000000000000000000000..5af3886d8d3d74d31249a4d79030a837 + "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", @@ -653,7 +1852,6 @@ index 0000000000000000000000000000000000000000..5af3886d8d3d74d31249a4d79030a837 + "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", @@ -688,19 +1886,19 @@ index 0000000000000000000000000000000000000000..5af3886d8d3d74d31249a4d79030a837 + "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", @@ -731,7 +1929,6 @@ index 0000000000000000000000000000000000000000..5af3886d8d3d74d31249a4d79030a837 + "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", @@ -751,7 +1948,6 @@ index 0000000000000000000000000000000000000000..5af3886d8d3d74d31249a4d79030a837 + "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", @@ -771,7 +1967,6 @@ index 0000000000000000000000000000000000000000..5af3886d8d3d74d31249a4d79030a837 + "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", @@ -780,7 +1975,6 @@ index 0000000000000000000000000000000000000000..5af3886d8d3d74d31249a4d79030a837 + "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", @@ -800,6 +1994,7 @@ index 0000000000000000000000000000000000000000..5af3886d8d3d74d31249a4d79030a837 + "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", @@ -818,46 +2013,234 @@ index 0000000000000000000000000000000000000000..5af3886d8d3d74d31249a4d79030a837 + "deps/postject/postject-api.h" + ] +} -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" +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") - # The location of V8, use the one from node's deps by default. -- node_v8_path = "$node_path/deps/v8" -+ node_v8_path = "//v8" +-# 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 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 = "" +-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", ++] - # 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 +-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) } - - assert(!node_enable_inspector || node_use_openssl, diff --git a/src/node_builtins.cc b/src/node_builtins.cc -index 2bc7155f7c075e5a22ece7159a64a1c9ba3d8ac9..48d29a0d05538cd1d992f3f086d826e78d0d8882 100644 +index 706ea4f5cb90525c8ea56f794320a733c45a193f..c7ae7759595bfc7fdc31dab174a7514ddd8345e7 100644 --- a/src/node_builtins.cc +++ b/src/node_builtins.cc -@@ -775,6 +775,7 @@ void BuiltinLoader::RegisterExternalReferences( +@@ -773,6 +773,7 @@ void BuiltinLoader::RegisterExternalReferences( registry->Register(GetNatives); RegisterExternalReferencesForInternalizedBuiltinCode(registry); @@ -878,25 +2261,12 @@ 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..54b761d91734aead50aeeba8c91a1262531df713 +index 0000000000000000000000000000000000000000..37c16859003e61636fe2f1a4040b1e904c472d0b --- /dev/null +++ b/tools/generate_gn_filenames_json.py -@@ -0,0 +1,118 @@ +@@ -0,0 +1,117 @@ +#!/usr/bin/env python3 +import json +import os @@ -948,7 +2318,6 @@ index 0000000000000000000000000000000000000000..54b761d91734aead50aeeba8c91a1262 + '<@(deps_files)', + '<@(node_sources)', + 'common.gypi', -+ 'common_node.gypi', + '<(SHARED_INTERMEDIATE_DIR)/node_javascript.cc', + } + @@ -1016,10 +2385,27 @@ index 0000000000000000000000000000000000000000..54b761d91734aead50aeeba8c91a1262 + 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 bf54249b66c0d4e179deaae5a9fd55568e694fe0..57b51b03d237fba4b25aa69a663c88e9541b6cb5 100755 +index b132c7bf26c02886a7ab341a1973bf449744ba0f..757e3e60a7be01fac55c5fbb010dbbae00b1bfca 100755 --- a/tools/install.py +++ b/tools/install.py -@@ -392,7 +392,7 @@ def parse_options(args): +@@ -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): parser.add_argument('--build-dir', help='the location of built binaries', default='out/Release') parser.add_argument('--v8-dir', help='the location of V8', @@ -1031,7 +2417,7 @@ index bf54249b66c0d4e179deaae5a9fd55568e694fe0..57b51b03d237fba4b25aa69a663c88e9 diff --git a/tools/js2c.cc b/tools/js2c.cc old mode 100644 new mode 100755 -index a536b5dcd857275d3b02e361bd7d37a939f6b573..b2d5678d58a79774d5aeedc15ac5d5fd786f64bb +index e0f3d8844718ab8a6478c40ff713c1fd6bcff95a..c73a5b666dbaf555c749d836c20a7ae19a840847 --- a/tools/js2c.cc +++ b/tools/js2c.cc @@ -30,6 +30,7 @@ namespace js2c { @@ -1166,7 +2552,7 @@ index a536b5dcd857275d3b02e361bd7d37a939f6b573..b2d5678d58a79774d5aeedc15ac5d5fd // Should have exactly 3 types: `.js`, `.mjs` and `.gypi`. assert(file_map.size() == 3); auto gypi_it = file_map.find(".gypi"); -@@ -939,6 +996,7 @@ int Main(int argc, char* argv[]) { +@@ -932,6 +989,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); @@ -1174,171 +2560,10 @@ index a536b5dcd857275d3b02e361bd7d37a939f6b573..b2d5678d58a79774d5aeedc15ac5d5fd } } // namespace js2c } // namespace node -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") { +@@ -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/patches/node/build_compile_with_c_20_support.patch b/patches/node/build_compile_with_c_20_support.patch index c83de137e2..bef0bb28e9 100644 --- a/patches/node/build_compile_with_c_20_support.patch +++ b/patches/node/build_compile_with_c_20_support.patch @@ -10,19 +10,28 @@ 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 74616453e2e047acbb9e25f2f93ebeab06011669..bce15fc4a8b3f2fa0b5a588e6a2b28d2b8b6ac45 100644 +index bdf1a1f33f3ea09d933757c7fee87c563cc833ab..2eb62610db2f0ebf68fa9a55ffba98291ecfe451 100644 --- a/common.gypi +++ b/common.gypi -@@ -518,7 +518,7 @@ - '-fno-rtti', - '-fno-exceptions', - '-fno-strict-aliasing', -- '-std=gnu++17', -+ '-std=gnu++20', +@@ -305,7 +305,7 @@ + 'VCCLCompilerTool': { + 'AdditionalOptions': [ + '/Zc:__cplusplus', +- '-std:c++17' ++ '-std:c++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' ], -@@ -688,7 +688,7 @@ + 'target_conditions': [ +@@ -658,7 +658,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 0bfc4367eb..2d8e77f07f 100644 --- a/patches/node/build_enable_perfetto.patch +++ b/patches/node/build_enable_perfetto.patch @@ -12,19 +12,6 @@ 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 @@ -76,62 +63,11 @@ 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..30bff4272ed8eb5146e3b73a4849c187177fc3bd 100644 +index 7ce59674356f9743438350949be42fa7ead2afbe..c5fedc3be86a77730c57321b9c73cc8e94a001d7 100644 --- a/src/tracing/agent.cc +++ b/src/tracing/agent.cc -@@ -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; +@@ -50,7 +50,9 @@ using v8::platform::tracing::TraceWriter; using std::string; Agent::Agent() : tracing_controller_(new TracingController()) { @@ -141,7 +77,7 @@ index 7ce59674356f9743438350949be42fa7ead2afbe..30bff4272ed8eb5146e3b73a4849c187 CHECK_EQ(uv_loop_init(&tracing_loop_), 0); CHECK_EQ(uv_async_init(&tracing_loop_, -@@ -86,10 +90,14 @@ Agent::~Agent() { +@@ -86,10 +88,14 @@ Agent::~Agent() { void Agent::Start() { if (started_) return; @@ -157,7 +93,7 @@ index 7ce59674356f9743438350949be42fa7ead2afbe..30bff4272ed8eb5146e3b73a4849c187 // This thread should be created *after* async handles are created // (within NodeTraceWriter and NodeTraceBuffer constructors). -@@ -143,8 +151,10 @@ void Agent::StopTracing() { +@@ -143,8 +149,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. @@ -169,7 +105,7 @@ index 7ce59674356f9743438350949be42fa7ead2afbe..30bff4272ed8eb5146e3b73a4849c187 started_ = false; // Thread should finish when the tracing loop is stopped. -@@ -202,6 +212,7 @@ std::string Agent::GetEnabledCategories() const { +@@ -202,6 +210,7 @@ std::string Agent::GetEnabledCategories() const { return categories; } @@ -177,7 +113,7 @@ index 7ce59674356f9743438350949be42fa7ead2afbe..30bff4272ed8eb5146e3b73a4849c187 void Agent::AppendTraceEvent(TraceObject* trace_event) { for (const auto& id_writer : writers_) id_writer.second->AppendTraceEvent(trace_event); -@@ -211,18 +222,21 @@ void Agent::AddMetadataEvent(std::unique_ptr<TraceObject> event) { +@@ -211,18 +220,21 @@ void Agent::AddMetadataEvent(std::unique_ptr<TraceObject> event) { Mutex::ScopedLock lock(metadata_events_mutex_); metadata_events_.push_back(std::move(event)); } @@ -200,7 +136,7 @@ index 7ce59674356f9743438350949be42fa7ead2afbe..30bff4272ed8eb5146e3b73a4849c187 void TracingController::AddMetadataEvent( const unsigned char* category_group_enabled, const char* name, -@@ -246,6 +260,6 @@ void TracingController::AddMetadataEvent( +@@ -246,6 +258,6 @@ void TracingController::AddMetadataEvent( if (node_agent != nullptr) node_agent->AddMetadataEvent(std::move(trace_event)); } @@ -262,20 +198,26 @@ index b542a849fe8da7e8bbbcca7067b73dc32b18d6d3..059ce6f6ea17199ead09c6c13bcc680f }; void AgentWriterHandle::reset() { -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_; +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) { +#ifndef V8_USE_PERFETTO - std::vector<std::unique_ptr<TraceBufferChunk>> chunks_; + { + Mutex::ScopedLock scoped_lock(mutex_); + if (total_chunks_ > 0) { +@@ -75,6 +76,7 @@ void InternalTraceBuffer::Flush(bool blocking) { + flushing_ = false; + } + } +#endif - size_t total_chunks_ = 0; - uint32_t current_chunk_seq_ = 1; - uint32_t id_; + agent_->Flush(blocking); + } + 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 4001cf3cb6..ae020d1bb1 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 229cb96c1385c597138719f2b01f78bd54ad44ab..74616453e2e047acbb9e25f2f93ebeab06011669 100644 +index 697b8bba6a55358924d6986f2eb347a99ff73889..bdf1a1f33f3ea09d933757c7fee87c563cc833ab 100644 --- a/common.gypi +++ b/common.gypi @@ -86,6 +86,8 @@ @@ -19,7 +19,7 @@ index 229cb96c1385c597138719f2b01f78bd54ad44ab..74616453e2e047acbb9e25f2f93ebeab ##### end V8 defaults ##### # When building native modules using 'npm install' with the system npm, -@@ -291,6 +293,7 @@ +@@ -285,6 +287,7 @@ # Defines these mostly for node-gyp to pickup. 'defines': [ '_GLIBCXX_USE_CXX11_ABI=1', @@ -27,7 +27,7 @@ index 229cb96c1385c597138719f2b01f78bd54ad44ab..74616453e2e047acbb9e25f2f93ebeab ], # Forcibly disable -Werror. We support a wide range of compilers, it's -@@ -437,6 +440,11 @@ +@@ -414,6 +417,11 @@ }], ], }], @@ -40,19 +40,19 @@ index 229cb96c1385c597138719f2b01f78bd54ad44ab..74616453e2e047acbb9e25f2f93ebeab # list in v8/BUILD.gn. ['v8_enable_v8_checks == 1', { diff --git a/configure.py b/configure.py -index d03db1970fd7a1629a7a7719a5ff267402ab4a66..ce055fb5dfc84c75c486b99f01fea6b9531ff54b 100755 +index a6f66c41f75bffcfaf75d4415c694300b7624136..7ca0762fe3590fef7b88ba684de44d99aaecace4 100755 --- a/configure.py +++ b/configure.py -@@ -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) +@@ -1585,6 +1585,7 @@ def configure_library(lib, output, pkgname=None): + + 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 0fec9477fd0f2a3c2aa68284131c510b0da0e025..c16204ad2a4787eeffe61eedda254d3a5509df8c 100644 +index 4f2eb9d0aab88b70c86339e750799080e980d7da..df3fb3372d6357b5d77b4f683e309b8483998128 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 aaba7297e7..6c5aa02753 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 48d29a0d05538cd1d992f3f086d826e78d0d8882..8987234c2d08449242b5fd037ed314b725bc42a5 100644 +index c7ae7759595bfc7fdc31dab174a7514ddd8345e7..4bf80aa6cc6385dc376fd0a3538efc27fe5bd0a2 100644 --- a/src/node_builtins.cc +++ b/src/node_builtins.cc -@@ -34,6 +34,7 @@ using v8::Value; +@@ -35,6 +35,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 5cee2b1aef..0423182e8b 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 bce15fc4a8b3f2fa0b5a588e6a2b28d2b8b6ac45..289ab5d282e93c795eafb5fb992c3bbc4790a687 100644 +index 2eb62610db2f0ebf68fa9a55ffba98291ecfe451..3ec08ee144b586d05c4e49c2251416734cbc02c5 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 new file mode 100644 index 0000000000..2d33d6a273 --- /dev/null +++ b/patches/node/cherry-pick_src_remove_calls_to_recently_deprecated_v8_apis.patch @@ -0,0 +1,182 @@ +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, &current_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 c74109225a..b0119bd437 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 b5c0a93d83ab4d4f6792d0eb648e7198de874bcf..0fd01987c29b06b91944d18266ba67994c1fac45 100644 +index 4e750be66452de47040e3a46555c062dfccf7807..5e1caeee18e447cc76b980df712521cf8b60e8da 100644 --- a/src/node_binding.cc +++ b/src/node_binding.cc @@ -4,6 +4,7 @@ @@ -19,7 +19,7 @@ index b5c0a93d83ab4d4f6792d0eb648e7198de874bcf..0fd01987c29b06b91944d18266ba6799 #include "util.h" #include <string> -@@ -495,7 +496,12 @@ void DLOpen(const FunctionCallbackInfo<Value>& args) { +@@ -483,7 +484,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 23e2ee6694..db246d414e 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 d49941881e6cfd8647a6d44a57e0daaf1c874702..f696fb263b356a76b87cd4b6c4b1a0fd60a84afd 100644 +index 364469160af5e348f8890417de16a63c0d1dca67..75d5f58fe02fa8cfa7716ffaf761d567ab403a2c 100644 --- a/lib/internal/modules/cjs/loader.js +++ b/lib/internal/modules/cjs/loader.js -@@ -1518,6 +1518,13 @@ Module.prototype._compile = function(content, filename, format) { +@@ -1441,6 +1441,13 @@ Module.prototype._compile = function(content, filename, loadAsESM = false) { 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 d49941881e6cfd8647a6d44a57e0daaf1c874702..f696fb263b356a76b87cd4b6c4b1a0fd 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 cb96fd1bc4fcdce750ce241ee5f47f2ae39cfdc6..c46b270109697f7cc1683f8f9f463575e5040216 100644 +index ea7afd52fab1cf3fde1674be1429a00562b714c0..02cfc8b3328fedb6306abf6c738bea772c674458 100644 --- a/lib/internal/process/pre_execution.js +++ b/lib/internal/process/pre_execution.js -@@ -243,12 +243,14 @@ function patchProcessObject(expandArgv1) { +@@ -247,12 +247,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_disable_deprecation_ftbfs_in_simdjson_header.patch b/patches/node/chore_disable_deprecation_ftbfs_in_simdjson_header.patch deleted file mode 100644 index 266554c00c..0000000000 --- a/patches/node/chore_disable_deprecation_ftbfs_in_simdjson_header.patch +++ /dev/null @@ -1,60 +0,0 @@ -From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 -From: Charles Kerr <[email protected]> -Date: Mon, 4 Nov 2024 17:40:17 -0600 -Subject: chore: disable deprecation ftbfs in simdjson header - -Without this patch, building with simdjson fails with - -> error: identifier '_padded' preceded by whitespace in a literal operator -> declaration is deprecated [-Werror,-Wdeprecated-literal-operator] - -This patch can be removed once this is fixed upstream in simdjson. - -diff --git a/deps/simdjson/simdjson.h b/deps/simdjson/simdjson.h -index ddb6f2e4e0a6edd23d5e16db07bc4bb18974d4aa..533dfea4d5fd3c7f6f7fdf0ea525479b11634fd3 100644 ---- a/deps/simdjson/simdjson.h -+++ b/deps/simdjson/simdjson.h -@@ -3650,12 +3650,17 @@ inline std::ostream& operator<<(std::ostream& out, simdjson_result<padded_string - - } // namespace simdjson - -+#pragma clang diagnostic push -+#pragma clang diagnostic ignored "-Wdeprecated-literal-operator" -+ - // This is deliberately outside of simdjson so that people get it without having to use the namespace - inline simdjson::padded_string operator "" _padded(const char *str, size_t len); - #ifdef __cpp_char8_t - inline simdjson::padded_string operator "" _padded(const char8_t *str, size_t len); - #endif - -+#pragma clang diagnostic pop -+ - namespace simdjson { - namespace internal { - -@@ -4033,6 +4038,9 @@ inline simdjson_result<padded_string> padded_string::load(std::string_view filen - - } // namespace simdjson - -+#pragma clang diagnostic push -+#pragma clang diagnostic ignored "-Wdeprecated-literal-operator" -+ - inline simdjson::padded_string operator "" _padded(const char *str, size_t len) { - return simdjson::padded_string(str, len); - } -@@ -4041,6 +4049,8 @@ inline simdjson::padded_string operator "" _padded(const char8_t *str, size_t le - return simdjson::padded_string(reinterpret_cast<const char8_t *>(str), len); - } - #endif -+#pragma clang diagnostic pop -+ - #endif // SIMDJSON_PADDED_STRING_INL_H - /* end file simdjson/padded_string-inl.h */ - /* skipped duplicate #include "simdjson/padded_string_view.h" */ -@@ -118280,4 +118290,4 @@ namespace simdjson { - /* end file simdjson/ondemand.h */ - - #endif // SIMDJSON_H --/* end file simdjson.h */ -+/* end file simdjson.h */ -\ No newline at end of file diff --git a/patches/node/chore_expose_importmoduledynamically_and.patch b/patches/node/chore_expose_importmoduledynamically_and.patch index 53d3d0a6e0..18583f403a 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 d393d4336a0c1e681e4f6b4e5c7cf2bcc5fc287e..807cb5172e0c2178b6c20e81f8175141d3a0284f 100644 +index 150816057129c147c13ce044474f341581679f34..dd8627653265e22f55e67ec4a47641b20fba6c9d 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 d393d4336a0c1e681e4f6b4e5c7cf2bcc5fc287e..807cb5172e0c2178b6c20e81f8175141 /** diff --git a/src/module_wrap.cc b/src/module_wrap.cc -index 48b61e8b7600701c4992a98ff802614ce915faee..4e9835e502a8d078a448aa4253f37de0f49f4854 100644 +index eea74bed4bb8a980f99a9a1404c9a2df203ca09c..e862b51293135995c527c32aa3c3579780d7831c 100644 --- a/src/module_wrap.cc +++ b/src/module_wrap.cc -@@ -813,7 +813,7 @@ MaybeLocal<Module> ModuleWrap::ResolveModuleCallback( +@@ -752,7 +752,7 @@ MaybeLocal<Module> ModuleWrap::ResolveModuleCallback( return module->module_.Get(isolate); } @@ -52,7 +52,7 @@ index 48b61e8b7600701c4992a98ff802614ce915faee..4e9835e502a8d078a448aa4253f37de0 Local<Context> context, Local<v8::Data> host_defined_options, Local<Value> resource_name, -@@ -878,12 +878,13 @@ void ModuleWrap::SetImportModuleDynamicallyCallback( +@@ -817,12 +817,13 @@ void ModuleWrap::SetImportModuleDynamicallyCallback( Realm* realm = Realm::GetCurrent(args); HandleScope handle_scope(isolate); @@ -68,7 +68,7 @@ index 48b61e8b7600701c4992a98ff802614ce915faee..4e9835e502a8d078a448aa4253f37de0 } void ModuleWrap::HostInitializeImportMetaObjectCallback( -@@ -925,13 +926,14 @@ void ModuleWrap::SetInitializeImportMetaObjectCallback( +@@ -864,13 +865,14 @@ void ModuleWrap::SetInitializeImportMetaObjectCallback( Realm* realm = Realm::GetCurrent(args); Isolate* isolate = realm->isolate(); @@ -87,18 +87,18 @@ index 48b61e8b7600701c4992a98ff802614ce915faee..4e9835e502a8d078a448aa4253f37de0 MaybeLocal<Value> ModuleWrap::SyntheticModuleEvaluationStepsCallback( diff --git a/src/module_wrap.h b/src/module_wrap.h -index 83b5793013cbc453cf92c0a006fc7be3c06ad276..90353954bc497cb4ae413dc134850f8abb4efc7c 100644 +index 45a338b38e01c824f69ea59ee286130c67e9eddf..99bb079df11696fc3ba5e6bcca7e7a42818fe3d1 100644 --- a/src/module_wrap.h +++ b/src/module_wrap.h -@@ -8,6 +8,7 @@ - #include <unordered_map> +@@ -7,6 +7,7 @@ + #include <string> #include <vector> #include "base_object.h" +#include "node.h" - #include "v8-script.h" namespace node { -@@ -33,7 +34,14 @@ enum HostDefinedOptions : int { + +@@ -31,7 +32,14 @@ enum HostDefinedOptions : int { kLength = 9, }; @@ -114,20 +114,20 @@ index 83b5793013cbc453cf92c0a006fc7be3c06ad276..90353954bc497cb4ae413dc134850f8a public: enum InternalFields { kModuleSlot = BaseObject::kInternalFieldCount, -@@ -91,6 +99,8 @@ class ModuleWrap : public BaseObject { - static void CreateRequiredModuleFacade( - const v8::FunctionCallbackInfo<v8::Value>& args); +@@ -68,6 +76,8 @@ class ModuleWrap : public BaseObject { + return true; + } + static ModuleWrap* GetFromModule(node::Environment*, v8::Local<v8::Module>); + private: ModuleWrap(Realm* realm, v8::Local<v8::Object> object, -@@ -129,7 +139,6 @@ class ModuleWrap : public BaseObject { +@@ -110,7 +120,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::Object>> resolve_cache_; + std::unordered_map<std::string, v8::Global<v8::Promise>> 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 new file mode 100644 index 0000000000..cc52a3017c --- /dev/null +++ b/patches/node/chore_remove_--no-harmony-atomics_related_code.patch @@ -0,0 +1,52 @@ +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 new file mode 100644 index 0000000000..ded4d1f30d --- /dev/null +++ b/patches/node/chore_remove_use_of_deprecated_kmaxlength.patch @@ -0,0 +1,35 @@ +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 ef4d76a3e8..05a70dd710 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,6 +7,53 @@ 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 @@ -20,3 +67,32 @@ 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 8a9772f144..0a4e8eb25b 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 0cfed4a4a91a3d3fb5aee6c9a4db3405ba836565..61d980a12fcf7c799e726e1462c65ce478a8ed0c 100644 +index ed0a43306e87962cf0e756d9e059ec5c08ad674b..7ada2802b2590e78fa5b9847935866b743cf94ed 100644 --- a/doc/api/cli.md +++ b/doc/api/cli.md -@@ -3151,7 +3151,6 @@ V8 options that are allowed are: +@@ -2868,7 +2868,6 @@ V8 options that are allowed are: * `--disallow-code-generation-from-strings` * `--enable-etw-stack-walking` * `--expose-gc` @@ -30,10 +30,10 @@ index 0cfed4a4a91a3d3fb5aee6c9a4db3405ba836565..61d980a12fcf7c799e726e1462c65ce4 * `--jitless` * `--max-old-space-size` diff --git a/src/node_options.cc b/src/node_options.cc -index 4b3f7751db2871c8ce76b197a84a2417097030ea..21e53e1053fe2e4194d91b27a726d3a1306b1683 100644 +index 4e3c82e9528b04fd1a0cc99d30fb885e4b224bc9..38e173f72b446aa2db07f676b6ece26247bbf56b 100644 --- a/src/node_options.cc +++ b/src/node_options.cc -@@ -922,11 +922,6 @@ PerIsolateOptionsParser::PerIsolateOptionsParser( +@@ -866,11 +866,6 @@ PerIsolateOptionsParser::PerIsolateOptionsParser( "disallow eval and friends", V8Option{}, kAllowedInEnvvar); @@ -46,7 +46,7 @@ index 4b3f7751db2871c8ce76b197a84a2417097030ea..21e53e1053fe2e4194d91b27a726d3a1 "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 e898a81af09ca6852ddc866310e5b8e0dc82971b..22d5a342df5d55f065383a6ebe1aebe59dc0f8d2 100644 +index 8d614e607177cdd922fef65a85a2ccdcf54116c0..146df3a21a0551e910c46248d2fd97dde8896164 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 new file mode 100644 index 0000000000..7462efb97f --- /dev/null +++ b/patches/node/deprecate_vector_v8_local_in_v8.patch @@ -0,0 +1,25 @@ +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 6f403b6ac8..931c066507 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 580a441a803bdd0b57871c0cdd8af576f11609b1..755712d24219de7ffe491957d941df7c8cf7baad 100644 +index 48870b35ad0f3411f2d509b12d92a9e0d20046f9..e7ef454d2d71207ae7b2788a437b82bf7732716e 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 580a441a803bdd0b57871c0cdd8af576f11609b1..755712d24219de7ffe491957d941df7c const { AbortError, -@@ -153,7 +154,6 @@ function fork(modulePath, args = [], options) { +@@ -154,7 +155,6 @@ function fork(modulePath, args = [], options) { ArrayPrototypeSplice(execArgv, index - 1, 2); } } @@ -27,7 +27,7 @@ index 580a441a803bdd0b57871c0cdd8af576f11609b1..755712d24219de7ffe491957d941df7c args = [...execArgv, modulePath, ...args]; if (typeof options.stdio === 'string') { -@@ -617,6 +617,22 @@ function normalizeSpawnArguments(file, args, options) { +@@ -618,6 +618,22 @@ function normalizeSpawnArguments(file, args, options) { 'options.windowsVerbatimArguments'); } @@ -50,7 +50,7 @@ index 580a441a803bdd0b57871c0cdd8af576f11609b1..755712d24219de7ffe491957d941df7c if (options.shell) { validateArgumentNullCheck(options.shell, 'options.shell'); const command = ArrayPrototypeJoin([file, ...args], ' '); -@@ -650,7 +666,6 @@ function normalizeSpawnArguments(file, args, options) { +@@ -651,7 +667,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 new file mode 100644 index 0000000000..ff45e7c990 --- /dev/null +++ b/patches/node/esm_drop_support_for_import_assertions.patch @@ -0,0 +1,53 @@ +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 39d3c031d4..4a9b451241 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 c2ef9b36d5b2967c798c123b6cbbd099b15c2791..b5c0a93d83ab4d4f6792d0eb648e7198de874bcf 100644 +index 6b0297d8984ccb34b8d0019fedd1307d48cf49f8..4e750be66452de47040e3a46555c062dfccf7807 100644 --- a/src/node_binding.cc +++ b/src/node_binding.cc -@@ -653,6 +653,10 @@ void GetInternalBinding(const FunctionCallbackInfo<Value>& args) { +@@ -641,6 +641,10 @@ void GetInternalBinding(const FunctionCallbackInfo<Value>& args) { args.GetReturnValue().Set(exports); } @@ -24,10 +24,10 @@ index c2ef9b36d5b2967c798c123b6cbbd099b15c2791..b5c0a93d83ab4d4f6792d0eb648e7198 Environment* env = Environment::GetCurrent(args); diff --git a/src/node_binding.h b/src/node_binding.h -index eb1364cb01a2bea52bce768056e73b0f3a86ae35..d421a2773403e7b22fcca2fcf8275ef2d9654c55 100644 +index 7256bf2bbcf73214a25e61156305cc212b6f2451..d129981ad8588376eeee61155964062f624695d6 100644 --- a/src/node_binding.h +++ b/src/node_binding.h -@@ -146,6 +146,8 @@ void GetInternalBinding(const v8::FunctionCallbackInfo<v8::Value>& args); +@@ -137,6 +137,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 68284309f8..a1b2774b5c 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 a62b3fa69b1087847f37c7093954e19a07959b74..7f48b7daa87d1a5b14bc6f641b60f21263fa5ec3 100644 +index 02397dd0fdd43d51f86c0dde9a62046702f12bdb..3375600023e39ddacf62cc17deb4f206db942084 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 965e7f775250cf9899266bc3aaf62eda69367264..45b3dec662b093a61af356e431416530b35343d2 100644 +index 25c5181f370e94983e8a5f797f02f7a8dc207e00..f4d9059796d2c65339a5d48ecb273b09d9364d21 100644 --- a/deps/uv/src/unix/core.c +++ b/deps/uv/src/unix/core.c -@@ -927,6 +927,9 @@ void uv__io_start(uv_loop_t* loop, uv__io_t* w, unsigned int events) { +@@ -926,6 +926,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 965e7f775250cf9899266bc3aaf62eda69367264..45b3dec662b093a61af356e431416530 } -@@ -958,6 +961,9 @@ void uv__io_stop(uv_loop_t* loop, uv__io_t* w, unsigned int events) { +@@ -957,6 +960,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 965e7f775250cf9899266bc3aaf62eda69367264..45b3dec662b093a61af356e431416530 } -@@ -974,6 +980,9 @@ void uv__io_close(uv_loop_t* loop, uv__io_t* w) { +@@ -973,6 +979,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 6e9917239aa5626dd56fffd6eb2469d3e63224bf..b0da9d1cddc69428e9fb3379d1338cf893ab93d2 100644 +index bbe56e176db17a502d7f3864ba529212f553590a..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 6e9917239aa5626dd56fffd6eb2469d3e63224bf..b0da9d1cddc69428e9fb3379d1338cf8 -static void thread_main(void* arg) { - ASSERT_LE(0, uv_barrier_wait(&barrier)); - uv_sleep(250); -- ASSERT_OK(uv_async_send(&async)); +- ASSERT_EQ(0, uv_async_send(&async)); -} +static uv_timer_t main_timer; +static int main_timer_called; @@ -333,9 +333,9 @@ index 6e9917239aa5626dd56fffd6eb2469d3e63224bf..b0da9d1cddc69428e9fb3379d1338cf8 - uv_loop_t* loop; - - loop = uv_default_loop(); -- 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_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_LE(0, uv_barrier_wait(&barrier)); - - while (uv_loop_alive(loop)) { @@ -457,7 +457,7 @@ index 6e9917239aa5626dd56fffd6eb2469d3e63224bf..b0da9d1cddc69428e9fb3379d1338cf8 + uv_timer_init(&external_loop, &external_timer); + uv_timer_start(&external_timer, external_timer_cb, 100, 0); -- ASSERT_OK(uv_thread_join(&thread)); +- ASSERT_EQ(0, uv_thread_join(&thread)); - uv_barrier_destroy(&barrier); + run_loop(); + ASSERT_EQ(main_timer_called, 1); @@ -465,10 +465,10 @@ index 6e9917239aa5626dd56fffd6eb2469d3e63224bf..b0da9d1cddc69428e9fb3379d1338cf8 MAKE_VALGRIND_HAPPY(loop); return 0; diff --git a/deps/uv/test/test-list.h b/deps/uv/test/test-list.h -index d30f02faa8515ca3a995490d53f2e85fda11c6a2..a392f5e3d701b0d973db2bbc6553977ce55a8775 100644 +index 78ff9c2d1621676feab5d357609970cdf1ba5864..204160f324ad1a80c9b042e62c4bedcb745666ba 100644 --- a/deps/uv/test/test-list.h +++ b/deps/uv/test/test-list.h -@@ -276,6 +276,7 @@ TEST_DECLARE (process_priority) +@@ -273,6 +273,7 @@ TEST_DECLARE (process_priority) TEST_DECLARE (has_ref) TEST_DECLARE (active) TEST_DECLARE (embed) @@ -476,7 +476,7 @@ index d30f02faa8515ca3a995490d53f2e85fda11c6a2..a392f5e3d701b0d973db2bbc6553977c TEST_DECLARE (async) TEST_DECLARE (async_null_cb) TEST_DECLARE (eintr_handling) -@@ -906,6 +907,7 @@ TASK_LIST_START +@@ -894,6 +895,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 deleted file mode 100644 index 238db21385..0000000000 --- a/patches/node/fix_-wextra-semi_errors_in_nghttp2_helper_h.patch +++ /dev/null @@ -1,60 +0,0 @@ -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 new file mode 100644 index 0000000000..d0dc5f5e72 --- /dev/null +++ b/patches/node/fix_account_for_createexternalizablestring_v8_global.patch @@ -0,0 +1,23 @@ +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 new file mode 100644 index 0000000000..978b11d75f --- /dev/null +++ b/patches/node/fix_adapt_debugger_tests_for_upstream_v8_changes.patch @@ -0,0 +1,82 @@ +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 d7cf142afa..0c0aebff56 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 a97e77860e151f5126515d65ef99b34aa7301f76..229cb96c1385c597138719f2b01f78bd54ad44ab 100644 +index 1ece4f5e494533ea0fa25e0d35143fe424dbf70b..697b8bba6a55358924d6986f2eb347a99ff73889 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 new file mode 100644 index 0000000000..b0c4211c1c --- /dev/null +++ b/patches/node/fix_add_property_query_interceptors.patch @@ -0,0 +1,574 @@ +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 new file mode 100644 index 0000000000..311a90be6d --- /dev/null +++ b/patches/node/fix_add_trusted_space_and_trusted_lo_space_to_the_v8_heap.patch @@ -0,0 +1,23 @@ +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 8bceb9a241..b89325039f 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 f59abcb21d64b910d8d42eb23c03109f62558813..1b6613d1de8c89c8271066a652afd1024988362d 100644 +index b9098d102b40adad7fafcc331ac62870617019b9..cb9269a31e073caf86164aa39c0640370ade60fd 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 f59abcb21d64b910d8d42eb23c03109f62558813..1b6613d1de8c89c8271066a652afd102 } diff --git a/src/node_options.cc b/src/node_options.cc -index 29630fcccc3bd9d24ad6aec64bef2fedfc3c4031..4b3f7751db2871c8ce76b197a84a2417097030ea 100644 +index 818baf611fcab7838a339f3ea137467653e270d0..4e3c82e9528b04fd1a0cc99d30fb885e4b224bc9 100644 --- a/src/node_options.cc +++ b/src/node_options.cc -@@ -1464,14 +1464,16 @@ void GetEmbedderOptions(const FunctionCallbackInfo<Value>& args) { +@@ -1405,14 +1405,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 ac22a29a41..c2909b32d8 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 70db7ddbeab5963f1bdf6cb05ee2763d76011cec..6ffe2a2ad01f33ff68c6646df330ec3ac7781a19 100644 +index be02d4aaa04685cbd6a9ecfe082e38f179129ab5..277748a30bd97ae816d9ba1f2d73851a29b81010 100644 --- a/src/handle_wrap.cc +++ b/src/handle_wrap.cc @@ -148,6 +148,9 @@ void HandleWrap::OnClose(uv_handle_t* handle) { @@ -21,5 +21,62 @@ index 70db7ddbeab5963f1bdf6cb05ee2763d76011cec..6ffe2a2ad01f33ff68c6646df330ec3a + return; + if (!wrap->persistent().IsEmpty() && - wrap->object() - ->Has(env->context(), env->handle_onclose_symbol()) + 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; + } 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 544e4ef6af..83b02e0c3f 100644 --- a/patches/node/fix_crypto_tests_to_run_with_bssl.patch +++ b/patches/node/fix_crypto_tests_to_run_with_bssl.patch @@ -10,50 +10,15 @@ 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..29149838ca76986928c7649a5f60a0f5e22a0705 100644 +index 4e3c32fdcd23fbe3e74bd5e624b739d224689f33..19d65aae7fa8ec9f9b907733ead17a208ed47909 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 @@ -61,10 +26,145 @@ index 4e3c32fdcd23fbe3e74bd5e624b739d224689f33..29149838ca76986928c7649a5f60a0f5 // 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 @@ -94,6 +194,115 @@ 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 @@ -109,6 +318,21 @@ 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 @@ -157,7 +381,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 9ebe14011eed223994e0901bc22dcc582b4b0739..e78f90eb76380916ce7098fb517c83a954edb053 100644 +index 8ae0a002fec0944737d2c6ae73fc8956e41beb50..5b37236a6c2f1ec1761d8143c8ea6a7e2a837a7a 100644 --- a/test/parallel/test-crypto-dh.js +++ b/test/parallel/test-crypto-dh.js @@ -55,18 +55,17 @@ const crypto = require('crypto'); @@ -187,21 +411,13 @@ index 9ebe14011eed223994e0901bc22dcc582b4b0739..e78f90eb76380916ce7098fb517c83a9 }; } -@@ -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' }); - } - } - +@@ -100,10 +99,16 @@ const crypto = require('crypto'); // 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: /ERR_CRYPTO_OPERATION_FAILED/, ++ code: /INVALID_PARAMETERS/, + name: 'Error' + }); crypto.createDiffieHellman('abcdef', 'hex', g); @@ -210,28 +426,28 @@ index 9ebe14011eed223994e0901bc22dcc582b4b0739..e78f90eb76380916ce7098fb517c83a9 { - crypto.createDiffieHellman('abcdef', Buffer.from([2])); // OK + assert.throws(() => crypto.createDiffieHellman('abcdef', Buffer.from([2])), { -+ code: /ERR_CRYPTO_OPERATION_FAILED/, ++ code: /INVALID_PARAMETERS/, + name: 'Error' + }); } diff --git a/test/parallel/test-crypto-getcipherinfo.js b/test/parallel/test-crypto-getcipherinfo.js -index 64b79fc36ccf4d38f763fcd8c1930473c82cefd7..1c6717ebd46497384b9b13174b65894ca89e7f2d 100644 +index 64b79fc36ccf4d38f763fcd8c1930473c82cefd7..892490fc7dd8da09f8aa10a20bec69385c0fee28 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 @@ -255,7 +471,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 83218c105a4596e0ae0381136f176bb8d759899e..afb3c8c592d2a8e2a053fd44f455af06c592a85e 100644 +index af2146982c7a3bf7bd7527f44e4b17a3b605026e..f6b91f675cfea367c608892dee078b565814f2dd 100644 --- a/test/parallel/test-crypto-hash.js +++ b/test/parallel/test-crypto-hash.js @@ -182,6 +182,7 @@ assert.throws( @@ -333,7 +549,7 @@ index 1785f5eef3d202976666081d09850ed744d83446..e88227a215ba4f7fa196f7642ae694a5 }); diff --git a/test/parallel/test-crypto-rsa-dsa.js b/test/parallel/test-crypto-rsa-dsa.js -index 5f4fafdfffbf726b7cb39c472baa3df25c9794cf..d52376da2cddd90adcdf8a9b7dcd03e348d9f2b4 100644 +index 5f4fafdfffbf726b7cb39c472baa3df25c9794cf..73bb53b0405b20f51b13326cc70e52755c674366 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'); @@ -364,25 +580,22 @@ index 5f4fafdfffbf726b7cb39c472baa3df25c9794cf..d52376da2cddd90adcdf8a9b7dcd03e3 if (!process.config.variables.node_shared_openssl) { assert.throws(() => { crypto.privateDecrypt({ -@@ -466,10 +466,10 @@ assert.throws(() => { +@@ -466,7 +466,7 @@ 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 338a19b0e88ad6f08d2f6b6a5d38b9980996ce11..a4ee215575d072450ba66c558ddca88bfb23d85f 100644 +index 61bd65fc92678c24baa3c0eb9ffb1ead64ace70b..cb690351696a811210b9d990ee4cde3cfb2a3446 100644 --- a/test/parallel/test-crypto-scrypt.js +++ b/test/parallel/test-crypto-scrypt.js @@ -178,7 +178,7 @@ for (const options of bad) { @@ -395,19 +608,26 @@ index 338a19b0e88ad6f08d2f6b6a5d38b9980996ce11..a4ee215575d072450ba66c558ddca88b }; 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..a37e6d50914345829c8260a97949cee7d17ab676 100644 +index 9dd586a1a1f9a00d9bb0af5b0532e81e7b96a5ce..1a0d0cfc09fb61d65472723ba54e1d0be69b5c68 100644 --- a/test/parallel/test-crypto-sign-verify.js +++ b/test/parallel/test-crypto-sign-verify.js -@@ -29,7 +29,7 @@ const keySize = 2048; +@@ -28,6 +28,7 @@ const keySize = 2048; + 'instance when called without `new`'); } ++/* // Test handling of exceptional conditions --{ -+if (!common.openSSLIsBoringSSL) { + { const library = { - configurable: true, - set() { -@@ -341,15 +341,17 @@ assert.throws( +@@ -68,6 +69,7 @@ const keySize = 2048; + + delete Object.prototype.opensslErrorStack; + } ++*/ + + assert.throws( + () => crypto.createVerify('SHA256').verify({ +@@ -341,15 +343,17 @@ assert.throws( padding: crypto.constants.RSA_PKCS1_OAEP_PADDING }); }, common.hasOpenSSL3 ? { @@ -429,7 +649,7 @@ index 9dd586a1a1f9a00d9bb0af5b0532e81e7b96a5ce..a37e6d50914345829c8260a97949cee7 }); } -@@ -419,10 +421,12 @@ assert.throws( +@@ -419,10 +423,12 @@ assert.throws( public: fixtures.readKey('ed25519_public.pem', 'ascii'), algo: null, sigLen: 64 }, @@ -442,7 +662,7 @@ index 9dd586a1a1f9a00d9bb0af5b0532e81e7b96a5ce..a37e6d50914345829c8260a97949cee7 { private: fixtures.readKey('rsa_private_2048.pem', 'ascii'), public: fixtures.readKey('rsa_public_2048.pem', 'ascii'), algo: 'sha1', -@@ -493,7 +497,7 @@ assert.throws( +@@ -493,7 +499,7 @@ assert.throws( { const data = Buffer.from('Hello world'); @@ -556,10 +776,10 @@ index 89a7521544f7051edc1779138551bbad1972b3fb..91df6acc65d4003999f29f0fa5f63905 } +*/ diff --git a/test/parallel/test-crypto.js b/test/parallel/test-crypto.js -index 4271121881379b6c6892e89e520345f77e4181df..6c87a1ac687aa37d4ba245d1b6fc746a5f1eeffc 100644 +index a8ceb169de2b3de73f062083c42292babc673e73..8fb950d0814e5014faf5c1ef576b65795857da1b 100644 --- a/test/parallel/test-crypto.js +++ b/test/parallel/test-crypto.js -@@ -61,7 +61,7 @@ assert.throws(() => { +@@ -67,7 +67,7 @@ assert.throws(() => { // Throws general Error, so there is no opensslErrorStack property. return err instanceof Error && err.name === 'Error' && @@ -568,7 +788,7 @@ index 4271121881379b6c6892e89e520345f77e4181df..6c87a1ac687aa37d4ba245d1b6fc746a !('opensslErrorStack' in err); }); -@@ -71,7 +71,7 @@ assert.throws(() => { +@@ -77,7 +77,7 @@ assert.throws(() => { // Throws general Error, so there is no opensslErrorStack property. return err instanceof Error && err.name === 'Error' && @@ -577,7 +797,7 @@ index 4271121881379b6c6892e89e520345f77e4181df..6c87a1ac687aa37d4ba245d1b6fc746a !('opensslErrorStack' in err); }); -@@ -81,7 +81,7 @@ assert.throws(() => { +@@ -87,7 +87,7 @@ assert.throws(() => { // Throws general Error, so there is no opensslErrorStack property. return err instanceof Error && err.name === 'Error' && @@ -586,7 +806,7 @@ index 4271121881379b6c6892e89e520345f77e4181df..6c87a1ac687aa37d4ba245d1b6fc746a !('opensslErrorStack' in err); }); -@@ -144,8 +144,6 @@ assert(crypto.getHashes().includes('sha1')); +@@ -150,8 +150,6 @@ assert(crypto.getHashes().includes('sha1')); assert(crypto.getHashes().includes('sha256')); assert(!crypto.getHashes().includes('SHA1')); assert(!crypto.getHashes().includes('SHA256')); @@ -595,7 +815,16 @@ index 4271121881379b6c6892e89e520345f77e4181df..6c87a1ac687aa37d4ba245d1b6fc746a validateList(crypto.getHashes()); // Make sure all of the hashes are supported by OpenSSL for (const algo of crypto.getHashes()) -@@ -195,7 +193,7 @@ assert.throws( +@@ -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( return true; } ); @@ -604,7 +833,7 @@ index 4271121881379b6c6892e89e520345f77e4181df..6c87a1ac687aa37d4ba245d1b6fc746a assert.throws(() => { const priv = [ '-----BEGIN RSA PRIVATE KEY-----', -@@ -208,6 +206,7 @@ assert.throws(() => { +@@ -232,6 +230,7 @@ assert.throws(() => { ].join('\n'); crypto.createSign('SHA256').update('test').sign(priv); }, (err) => { @@ -612,7 +841,7 @@ index 4271121881379b6c6892e89e520345f77e4181df..6c87a1ac687aa37d4ba245d1b6fc746a if (!common.hasOpenSSL3) assert.ok(!('opensslErrorStack' in err)); assert.throws(() => { throw err; }, common.hasOpenSSL3 ? { -@@ -216,10 +215,10 @@ assert.throws(() => { +@@ -240,10 +239,10 @@ assert.throws(() => { library: 'rsa routines', } : { name: 'Error', @@ -627,7 +856,7 @@ index 4271121881379b6c6892e89e520345f77e4181df..6c87a1ac687aa37d4ba245d1b6fc746a code: 'ERR_OSSL_RSA_DIGEST_TOO_BIG_FOR_RSA_KEY' }); return true; -@@ -252,7 +251,7 @@ if (!common.hasOpenSSL3) { +@@ -276,7 +275,7 @@ if (!common.hasOpenSSL3) { return true; }); } @@ -725,62 +954,56 @@ 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..011990db171faa708c5211f6ab9ae1ac0e0ab90e 100644 +index eb09bc24f0cb8244b05987e3a7c1d203360d3a38..da891fffa29d5666d91e4445e54c43e3688b870a 100644 --- a/test/parallel/test-webcrypto-derivebits.js +++ b/test/parallel/test-webcrypto-derivebits.js -@@ -101,8 +101,9 @@ const { subtle } = globalThis.crypto; +@@ -101,6 +101,7 @@ 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..f42bf8f4be0b439dd7e7c8d0f6f8a41e01588870 100644 +index 558d37d90d5796b30101d1b512c9df3e7661d0db..c18f9670b10cb84c6902391f20e0ff75729cc960 100644 --- a/test/parallel/test-webcrypto-derivekey.js +++ b/test/parallel/test-webcrypto-derivekey.js -@@ -176,7 +176,7 @@ const { KeyObject } = require('crypto'); +@@ -175,6 +175,7 @@ const { KeyObject } = require('crypto'); + })().then(common.mustCall()); } ++/* // Test X25519 and X448 key derivation --{ -+if (!common.openSSLIsBoringSSL) { + { async function test(name) { - const [alice, bob] = await Promise.all([ - subtle.generateKey({ name }, true, ['deriveKey']), +@@ -209,3 +210,4 @@ const { KeyObject } = require('crypto'); + test('X25519').then(common.mustCall()); + test('X448').then(common.mustCall()); + } ++*/ diff --git a/test/parallel/test-webcrypto-sign-verify.js b/test/parallel/test-webcrypto-sign-verify.js -index de736102bdcb71a5560c95f7041537f25026aed4..12d7fa39446c196bdf1479dbe74c9ee8ab02f949 100644 +index de736102bdcb71a5560c95f7041537f25026aed4..638fdf0d798f3309528c63f0f8598f3df5528339 100644 --- a/test/parallel/test-webcrypto-sign-verify.js +++ b/test/parallel/test-webcrypto-sign-verify.js -@@ -105,8 +105,9 @@ const { subtle } = globalThis.crypto; +@@ -105,6 +105,7 @@ const { subtle } = globalThis.crypto; test('hello world').then(common.mustCall()); } -+ ++/* // Test Sign/Verify Ed25519 --{ -+if (!common.openSSLIsBoringSSL) { + { async function test(data) { - const ec = new TextEncoder(); - const { publicKey, privateKey } = await subtle.generateKey({ -@@ -126,7 +127,7 @@ const { subtle } = globalThis.crypto; - } +@@ -144,3 +145,4 @@ 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({ + test('hello world').then(common.mustCall()); + } ++*/ 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 fba87eb85f..e5177c8297 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 463e76cb1abc0c2fdddba4db2ca2e00f7c591e12..d7bc3c35c77b5bf9ec122b38248d0cf1f4d2a548 100644 +index 22248b753c14960122f1d6b9bfe6b89fdb8d2010..9d245a04fbcb98dcd1c61e60f7cfe528bd1c8af0 100644 --- a/lib/internal/modules/esm/load.js +++ b/lib/internal/modules/esm/load.js -@@ -111,7 +111,7 @@ async function defaultLoad(url, context = kEmptyObject) { +@@ -132,7 +132,7 @@ async function defaultLoad(url, context = kEmptyObject) { source = null; format ??= 'builtin'; } else if (format !== 'commonjs' || defaultType === 'module') { @@ -19,10 +19,10 @@ index 463e76cb1abc0c2fdddba4db2ca2e00f7c591e12..d7bc3c35c77b5bf9ec122b38248d0cf1 context = { __proto__: context, source }; } diff --git a/lib/internal/modules/esm/translators.js b/lib/internal/modules/esm/translators.js -index 06b31af80ebbfbf35ec787a94f345775eb512ebf..deca5aa4b8829ba9921440fcb5c285a10e40c8f0 100644 +index f3dfc69cd2cdec50bc3b3f7cb2d63349812d87dd..b6f2d7194cb75ecc8c47869761c63184707ade40 100644 --- a/lib/internal/modules/esm/translators.js +++ b/lib/internal/modules/esm/translators.js -@@ -354,6 +354,9 @@ function cjsPreparseModuleExports(filename, source) { +@@ -375,6 +375,9 @@ function cjsPreparseModuleExports(filename, source) { if (module && module[kModuleExportNames] !== undefined) { return { module, exportNames: module[kModuleExportNames] }; } @@ -33,7 +33,7 @@ index 06b31af80ebbfbf35ec787a94f345775eb512ebf..deca5aa4b8829ba9921440fcb5c285a1 if (!loaded) { module = new CJSModule(filename); diff --git a/lib/internal/modules/run_main.js b/lib/internal/modules/run_main.js -index 1e1a1ea46fc6c1b43cad4038ab0d9cdf21d6ba3d..95e2fa5479ea31559fdb5a2e03515f243b231b75 100644 +index ca401044c0178c46db9b439b27c440a5d7924c84..dc1a682f0a3cf1ba1095c60bf6a6ca992d6043b3 100644 --- a/lib/internal/modules/run_main.js +++ b/lib/internal/modules/run_main.js @@ -2,6 +2,7 @@ @@ -41,10 +41,10 @@ index 1e1a1ea46fc6c1b43cad4038ab0d9cdf21d6ba3d..95e2fa5479ea31559fdb5a2e03515f24 const { StringPrototypeEndsWith, + StringPrototypeStartsWith, - globalThis, } = primordials; -@@ -26,6 +27,13 @@ const { + const { containsModuleSyntax } = internalBinding('contextify'); +@@ -22,6 +23,13 @@ const { * @param {string} main - Entry point path */ function resolveMainPath(main) { @@ -58,7 +58,7 @@ index 1e1a1ea46fc6c1b43cad4038ab0d9cdf21d6ba3d..95e2fa5479ea31559fdb5a2e03515f24 const defaultType = getOptionValue('--experimental-default-type'); /** @type {string} */ let mainPath; -@@ -63,6 +71,13 @@ function resolveMainPath(main) { +@@ -59,6 +67,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 1f84223398..ee7a6cf34a 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 a89446df710a941390c15171fea63c551776fc93..912f03bfa96c3aa12bfa6e709746642452568bb7 100644 +index 1fe5564545dbc86d7f2968274a25ee1579bcbf28..b876af21a0e97ae06dc344d9f78c8f5c7e403d43 100644 --- a/lib/internal/modules/esm/get_format.js +++ b/lib/internal/modules/esm/get_format.js -@@ -26,6 +26,7 @@ const protocolHandlers = { - 'data:': getDataProtocolModuleFormat, - 'file:': getFileProtocolModuleFormat, +@@ -31,6 +31,7 @@ const protocolHandlers = { + 'http:': getHttpProtocolModuleFormat, + 'https:': getHttpProtocolModuleFormat, 'node:'() { return 'builtin'; }, + 'electron:'() { return 'electron'; }, }; /** diff --git a/lib/internal/modules/esm/load.js b/lib/internal/modules/esm/load.js -index 8b157f0f461c7b92c567fffe4d99357dbc09aee7..605e812d515fc467001e4ab88fc15b4af3fd4aa2 100644 +index 7b77af35a1dfebf6ad45ace521f1a55b5fa18293..ac24cf305bd5995ad13b37ee36f9e1fe3589c5d7 100644 --- a/lib/internal/modules/esm/load.js +++ b/lib/internal/modules/esm/load.js -@@ -121,7 +121,7 @@ async function defaultLoad(url, context = kEmptyObject) { +@@ -142,7 +142,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,35 +30,37 @@ index 8b157f0f461c7b92c567fffe4d99357dbc09aee7..605e812d515fc467001e4ab88fc15b4a // For backward compatibility reasons, we need to discard the source in // order for the CJS loader to re-fetch it. source = null; -@@ -218,12 +218,13 @@ function throwIfUnsupportedURLScheme(parsed) { +@@ -234,6 +234,7 @@ function throwIfUnsupportedURLScheme(parsed, experimentalNetworkImports) { protocol !== 'file:' && protocol !== 'data:' && protocol !== 'node:' && + protocol !== 'electron:' && ( - protocol !== 'https:' && - protocol !== 'http:' + !experimentalNetworkImports || + ( +@@ -242,7 +243,7 @@ function throwIfUnsupportedURLScheme(parsed, experimentalNetworkImports) { + ) ) ) { - const schemes = ['file', 'data', 'node']; + const schemes = ['file', 'data', 'node', 'electron']; - throw new ERR_UNSUPPORTED_ESM_URL_SCHEME(parsed, schemes); - } - } + if (experimentalNetworkImports) { + ArrayPrototypePush(schemes, 'https', 'http'); + } diff --git a/lib/internal/modules/esm/resolve.js b/lib/internal/modules/esm/resolve.js -index 1fbbb6773c9479128408fa1f27cf19f1a7786ba6..f05c6f99c0037193c5802024be46a967d6cf47a0 100644 +index e73a8ad60a13925d6773c32cead8d04ec9d96ee7..52cdb7d5e14a18ed7b1b65e429729cf47dce3f98 100644 --- a/lib/internal/modules/esm/resolve.js +++ b/lib/internal/modules/esm/resolve.js -@@ -772,6 +772,8 @@ function parsePackageName(specifier, base) { - return { packageName, packageSubpath, isScoped }; +@@ -741,6 +741,8 @@ function packageImportsResolve(name, base, conditions) { + throw importNotDefined(name, packageJSONUrl, base); } +const electronTypes = ['electron', 'electron/main', 'electron/common', 'electron/renderer']; + /** - * Resolves a package specifier to a URL. - * @param {string} specifier - The package specifier to resolve. -@@ -785,6 +787,11 @@ function packageResolve(specifier, base, conditions) { + * 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) { return new URL('node:' + specifier); } @@ -71,10 +73,10 @@ index 1fbbb6773c9479128408fa1f27cf19f1a7786ba6..f05c6f99c0037193c5802024be46a967 parsePackageName(specifier, base); diff --git a/lib/internal/modules/esm/translators.js b/lib/internal/modules/esm/translators.js -index 8f88214f558c52ef26000fb0e1ef4d391327e84e..d182eedf5e96039e0029d36e51f40b75c6fb2a39 100644 +index 8f4b6b25d8889686d00613fd9821b0aa822a946a..89ca269294ee1afa7f5aeb0ac6b8958f7a8b49d0 100644 --- a/lib/internal/modules/esm/translators.js +++ b/lib/internal/modules/esm/translators.js -@@ -246,7 +246,7 @@ function createCJSModuleWrap(url, source, isMain, loadCJS = loadCJSModule) { +@@ -272,7 +272,7 @@ function createCJSModuleWrap(url, source, isMain, loadCJS = loadCJSModule) { const { exportNames, module } = cjsPreparseModuleExports(filename, source); cjsCache.set(url, module); @@ -83,7 +85,7 @@ index 8f88214f558c52ef26000fb0e1ef4d391327e84e..d182eedf5e96039e0029d36e51f40b75 [...exportNames] : ['default', ...exportNames]; if (isMain) { -@@ -268,8 +268,8 @@ function createCJSModuleWrap(url, source, isMain, loadCJS = loadCJSModule) { +@@ -294,8 +294,8 @@ function createCJSModuleWrap(url, source, isMain, loadCJS = loadCJSModule) { ({ exports } = module); } for (const exportName of exportNames) { @@ -94,7 +96,7 @@ index 8f88214f558c52ef26000fb0e1ef4d391327e84e..d182eedf5e96039e0029d36e51f40b75 continue; } // We might trigger a getter -> dont fail. -@@ -304,6 +304,10 @@ translators.set('require-commonjs', (url, source, isMain) => { +@@ -329,6 +329,10 @@ translators.set('require-commonjs', (url, source, isMain) => { return createCJSModuleWrap(url, source); }); @@ -102,14 +104,14 @@ index 8f88214f558c52ef26000fb0e1ef4d391327e84e..d182eedf5e96039e0029d36e51f40b75 + return createCJSModuleWrap('electron', ''); +}); + - // 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) => { + // 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, diff --git a/lib/internal/url.js b/lib/internal/url.js -index 3cb186182947a14407e9d5c4d94ab0554298a658..e35ae9ac316ba2e5b8f562d353b2c5ae978abb63 100644 +index e6ed5466b8807a52633d8406824058bdc8c2ce13..e055facddf086eb8fb456b865ce006cdb7602b0a 100644 --- a/lib/internal/url.js +++ b/lib/internal/url.js -@@ -1495,6 +1495,8 @@ function fileURLToPath(path, options = kEmptyObject) { +@@ -1485,6 +1485,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 5f005aef01..cf1dc86655 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 77c20a4b6b9db414444974f68c5def8788386d2b..5fc1b6f2446d7c786024eb60800e2edab613dcd1 100644 +index 46106fa94b3055648e4f01cd28860d427268a253..e0bf37f09dceb93af58990438ab577a9d4b843e8 100644 --- a/src/api/environment.cc +++ b/src/api/environment.cc -@@ -564,6 +564,10 @@ MultiIsolatePlatform* GetMultiIsolatePlatform(IsolateData* env) { +@@ -557,6 +557,10 @@ MultiIsolatePlatform* GetMultiIsolatePlatform(IsolateData* env) { return env->platform(); } @@ -22,7 +22,7 @@ index 77c20a4b6b9db414444974f68c5def8788386d2b..5fc1b6f2446d7c786024eb60800e2eda int thread_pool_size, node::tracing::TracingController* tracing_controller) { diff --git a/src/node.h b/src/node.h -index 60598f54114b2424f10706e57d8aa50c4634bcb0..0fec9477fd0f2a3c2aa68284131c510b0da0e025 100644 +index 6373adacb628459a4c9d7237da2587aee318e2d8..4f2eb9d0aab88b70c86339e750799080e980d7da 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 0ffc9526e8..82c13656c6 100644 --- a/patches/node/fix_handle_boringssl_and_openssl_incompatibilities.patch +++ b/patches/node/fix_handle_boringssl_and_openssl_incompatibilities.patch @@ -16,125 +16,11 @@ 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 fe35a8e0f6bbb7ab515a0343a7ed046c44e86474..43a7abbf237d8d809953e302b83755a3283a1bf4 100644 +index 4f0637f9511d1b90ae9d33760428dceb772667bd..5aba390c49613816ac359dfe995dc2c0a93f2206 100644 --- a/src/crypto/crypto_cipher.cc +++ b/src/crypto/crypto_cipher.cc -@@ -1078,7 +1078,7 @@ void PublicKeyCipher::Cipher(const FunctionCallbackInfo<Value>& args) { +@@ -1088,7 +1088,7 @@ void PublicKeyCipher::Cipher(const FunctionCallbackInfo<Value>& args) { if (EVP_PKEY_decrypt_init(ctx.get()) <= 0) { return ThrowCryptoError(env, ERR_get_error()); } @@ -143,19 +29,19 @@ index fe35a8e0f6bbb7ab515a0343a7ed046c44e86474..43a7abbf237d8d809953e302b83755a3 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. -@@ -1094,6 +1094,7 @@ void PublicKeyCipher::Cipher(const FunctionCallbackInfo<Value>& args) { +@@ -1104,6 +1104,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-2024-PEND"); + " this can be reverted with --security-revert=CVE-2023-46809"); } +#endif } const EVP_MD* digest = nullptr; diff --git a/src/crypto/crypto_common.cc b/src/crypto/crypto_common.cc -index 6a967702b22df0eb8aa10e853fd232794955860d..31058cccc6ffeed6b09aaecda320ee2f15849ec8 100644 +index 85d48dfd2c15c453707bf6eb94e22f89b4f856b2..fe31a9a7f465a03d2de365cef392dfbb7c540156 100644 --- a/src/crypto/crypto_common.cc +++ b/src/crypto/crypto_common.cc -@@ -134,7 +134,7 @@ const char* GetClientHelloALPN(const SSLPointer& ssl) { +@@ -158,7 +158,7 @@ const char* GetClientHelloALPN(const SSLPointer& ssl) { const unsigned char* buf; size_t len; size_t rem; @@ -164,7 +50,7 @@ index 6a967702b22df0eb8aa10e853fd232794955860d..31058cccc6ffeed6b09aaecda320ee2f if (!SSL_client_hello_get0_ext( ssl.get(), TLSEXT_TYPE_application_layer_protocol_negotiation, -@@ -147,13 +147,15 @@ const char* GetClientHelloALPN(const SSLPointer& ssl) { +@@ -171,13 +171,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); @@ -181,7 +67,7 @@ index 6a967702b22df0eb8aa10e853fd232794955860d..31058cccc6ffeed6b09aaecda320ee2f if (!SSL_client_hello_get0_ext( ssl.get(), TLSEXT_TYPE_server_name, -@@ -175,6 +177,8 @@ const char* GetClientHelloServerName(const SSLPointer& ssl) { +@@ -199,6 +201,8 @@ const char* GetClientHelloServerName(const SSLPointer& ssl) { if (len + 2 > rem) return nullptr; return reinterpret_cast<const char*>(buf + 5); @@ -190,25 +76,7 @@ index 6a967702b22df0eb8aa10e853fd232794955860d..31058cccc6ffeed6b09aaecda320ee2f } const char* GetServerName(SSL* ssl) { -@@ -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( +@@ -1036,14 +1040,14 @@ MaybeLocal<Array> GetClientHelloCiphers( Environment* env, const SSLPointer& ssl) { EscapableHandleScope scope(env->isolate()); @@ -227,7 +95,7 @@ index 6a967702b22df0eb8aa10e853fd232794955860d..31058cccc6ffeed6b09aaecda320ee2f Local<Object> obj = Object::New(env->isolate()); if (!Set(env->context(), obj, -@@ -444,8 +448,11 @@ MaybeLocal<Object> GetEphemeralKey(Environment* env, const SSLPointer& ssl) { +@@ -1096,8 +1100,11 @@ MaybeLocal<Object> GetEphemeralKey(Environment* env, const SSLPointer& ssl) { EscapableHandleScope scope(env->isolate()); Local<Object> info = Object::New(env->isolate()); @@ -241,19 +109,19 @@ index 6a967702b22df0eb8aa10e853fd232794955860d..31058cccc6ffeed6b09aaecda320ee2f crypto::EVPKeyPointer key(raw_key); diff --git a/src/crypto/crypto_context.cc b/src/crypto/crypto_context.cc -index c924a54639e8c22d765dc240dffacfffb200ca0c..287afcc792a0a2b7e19126ee9a48ebe21cc8844e 100644 +index cef0c877c67643d47da787eddb95ed5a410a941b..1b8af49a48f1a34a92d4f0b502d435f3a4ab5d8e 100644 --- a/src/crypto/crypto_context.cc +++ b/src/crypto/crypto_context.cc -@@ -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) { +@@ -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) { // 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. @@ -262,106 +130,66 @@ index c924a54639e8c22d765dc240dffacfffb200ca0c..287afcc792a0a2b7e19126ee9a48ebe2 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 e5664dfa2bc7e11922fa965f28acdf21470d1147..33ffbbb85d05f5356183e3aa1ca23707c5629b5d 100644 +index dac37f52b9687cadfa2d02152241e9a6e4c16ddf..d47cfa4ad8707ed7f0a42e7fe176fec25be64305 100644 --- a/src/crypto/crypto_dh.cc +++ b/src/crypto/crypto_dh.cc -@@ -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"); - } +@@ -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; } -@@ -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"); + 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; + } + 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> +#ifndef OPENSSL_IS_BORINGSSL - 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"); + V("modp1", BN_get_rfc2409_prime_768); + V("modp2", BN_get_rfc2409_prime_1024); +#endif -+ 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) { + 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) { key_params = EVPKeyPointer(EVP_PKEY_new()); CHECK(key_params); CHECK_EQ(EVP_PKEY_assign_DH(key_params.get(), dh.release()), 1); @@ -374,7 +202,7 @@ index e5664dfa2bc7e11922fa965f28acdf21470d1147..33ffbbb85d05f5356183e3aa1ca23707 if (!param_ctx || EVP_PKEY_paramgen_init(param_ctx.get()) <= 0 || EVP_PKEY_CTX_set_dh_paramgen_prime_len( -@@ -414,6 +416,9 @@ EVPKeyCtxPointer DhKeyGenTraits::Setup(DhKeyPairGenConfig* params) { +@@ -581,6 +580,9 @@ EVPKeyCtxPointer DhKeyGenTraits::Setup(DhKeyPairGenConfig* params) { } key_params = EVPKeyPointer(raw_params); @@ -385,7 +213,7 @@ index e5664dfa2bc7e11922fa965f28acdf21470d1147..33ffbbb85d05f5356183e3aa1ca23707 UNREACHABLE(); } diff --git a/src/crypto/crypto_dsa.cc b/src/crypto/crypto_dsa.cc -index 5d081863cf2dcdcf8c2d09db6060eeb5e78c452f..67523ec1c406e345945e1dde663c784c43a1c624 100644 +index 3fa4a415dc911a13afd90dfb31c1ed4ad0fd268f..fa48dffc31342c44a1c1207b9d4c3dc72ed93b60 100644 --- a/src/crypto/crypto_dsa.cc +++ b/src/crypto/crypto_dsa.cc @@ -40,7 +40,7 @@ namespace crypto { @@ -409,18 +237,18 @@ index 5d081863cf2dcdcf8c2d09db6060eeb5e78c452f..67523ec1c406e345945e1dde663c784c return EVPKeyCtxPointer(); diff --git a/src/crypto/crypto_keys.cc b/src/crypto/crypto_keys.cc -index 8488fc57faaf722174032c5a927d150c76120d60..c51efc92d4818ee7701b4725585fb7e1d2d644ad 100644 +index 35474c31bfc2e3692b7ca10e4ed7026b9c275dfb..43c42c14f75018d4705f218fe4ed7e5dacb46bb8 100644 --- a/src/crypto/crypto_keys.cc +++ b/src/crypto/crypto_keys.cc -@@ -1204,6 +1204,7 @@ void KeyObjectHandle::GetAsymmetricKeyType( +@@ -1239,6 +1239,7 @@ void KeyObjectHandle::GetAsymmetricKeyType( } bool KeyObjectHandle::CheckEcKeyData() const { +#ifndef OPENSSL_IS_BORINGSSL MarkPopErrorOnReturn mark_pop_error_on_return; - const auto& key = data_.GetAsymmetricKey(); -@@ -1220,6 +1221,9 @@ bool KeyObjectHandle::CheckEcKeyData() const { + const ManagedEVPPKey& key = data_->GetAsymmetricKey(); +@@ -1257,6 +1258,9 @@ bool KeyObjectHandle::CheckEcKeyData() const { #else return EVP_PKEY_public_check(ctx.get()) == 1; #endif @@ -431,43 +259,43 @@ index 8488fc57faaf722174032c5a927d150c76120d60..c51efc92d4818ee7701b4725585fb7e1 void KeyObjectHandle::CheckEcKeyData(const FunctionCallbackInfo<Value>& args) { diff --git a/src/crypto/crypto_random.cc b/src/crypto/crypto_random.cc -index b59e394d9a7e2c19fdf1f2b0177753ff488da0fa..91218f49da5392c6f769495ee7f9275a47ce09b1 100644 +index 48154df7dc91ed7c0d65323199bc2f59dfc68135..6431e5c3062890975854780d15ecb84370b81770 100644 --- a/src/crypto/crypto_random.cc +++ b/src/crypto/crypto_random.cc -@@ -134,7 +134,7 @@ Maybe<void> RandomPrimeTraits::AdditionalConfig( +@@ -140,7 +140,7 @@ Maybe<bool> RandomPrimeTraits::AdditionalConfig( params->bits = bits; params->safe = safe; -- params->prime = BignumPointer::NewSecure(); -+ params->prime = BignumPointer::New(); +- params->prime.reset(BN_secure_new()); ++ params->prime.reset(BN_new()); if (!params->prime) { THROW_ERR_CRYPTO_OPERATION_FAILED(env, "could not generate prime"); - return Nothing<void>(); + return Nothing<bool>(); diff --git a/src/crypto/crypto_rsa.cc b/src/crypto/crypto_rsa.cc -index 02e8e24b4054afd4c3ca797c19a78927319a0d9e..d2a931a3f8f9490fe17ef8a82d0204ee2cca409d 100644 +index 23b2b8c56dec8ac600b8f14b78d9e80b7fa3ed3b..e7a8fe4181542252d9142ea9460cacc5b4acd00d 100644 --- a/src/crypto/crypto_rsa.cc +++ b/src/crypto/crypto_rsa.cc -@@ -608,10 +608,11 @@ Maybe<void> GetRsaKeyDetail(Environment* env, +@@ -616,10 +616,11 @@ Maybe<bool> GetRsaKeyDetail( } 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<void>(); +- return Nothing<bool>(); - } + // 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<void>(); ++ // return Nothing<bool>(); + // } } if (target diff --git a/src/crypto/crypto_util.cc b/src/crypto/crypto_util.cc -index 793c196f8ce538c66b20611d00e12392ff9e878b..ee81048caab4ccfe26ea9e677782c9c955d162a9 100644 +index 990638ec3993bde40ad3dd40d373d816ebc66a6a..63d971e1fe6b861e29c12f04563701b01fdfb976 100644 --- a/src/crypto/crypto_util.cc +++ b/src/crypto/crypto_util.cc -@@ -495,24 +495,15 @@ Maybe<void> Decorate(Environment* env, +@@ -518,24 +518,15 @@ Maybe<void> Decorate(Environment* env, V(BIO) \ V(PKCS7) \ V(X509V3) \ @@ -493,7 +321,7 @@ index 793c196f8ce538c66b20611d00e12392ff9e878b..ee81048caab4ccfe26ea9e677782c9c9 V(USER) \ #define V(name) case ERR_LIB_##name: lib = #name "_"; break; -@@ -654,7 +645,7 @@ void SecureBuffer(const FunctionCallbackInfo<Value>& args) { +@@ -716,7 +707,7 @@ void SecureBuffer(const FunctionCallbackInfo<Value>& args) { CHECK(args[0]->IsUint32()); Environment* env = Environment::GetCurrent(args); uint32_t len = args[0].As<Uint32>()->Value(); @@ -502,7 +330,7 @@ index 793c196f8ce538c66b20611d00e12392ff9e878b..ee81048caab4ccfe26ea9e677782c9c9 if (data == nullptr) { // There's no memory available for the allocation. // Return nothing. -@@ -665,7 +656,7 @@ void SecureBuffer(const FunctionCallbackInfo<Value>& args) { +@@ -727,7 +718,7 @@ void SecureBuffer(const FunctionCallbackInfo<Value>& args) { data, len, [](void* data, size_t len, void* deleter_data) { @@ -511,7 +339,7 @@ index 793c196f8ce538c66b20611d00e12392ff9e878b..ee81048caab4ccfe26ea9e677782c9c9 }, data); Local<ArrayBuffer> buffer = ArrayBuffer::New(env->isolate(), store); -@@ -673,10 +664,12 @@ void SecureBuffer(const FunctionCallbackInfo<Value>& args) { +@@ -735,10 +726,12 @@ void SecureBuffer(const FunctionCallbackInfo<Value>& args) { } void SecureHeapUsed(const FunctionCallbackInfo<Value>& args) { @@ -525,10 +353,10 @@ index 793c196f8ce538c66b20611d00e12392ff9e878b..ee81048caab4ccfe26ea9e677782c9c9 } // namespace diff --git a/src/env.h b/src/env.h -index fc8dbd615255851cad90e1d8ffe225f5e0c6a718..49ca9c0042ccf22ad1fffa54f05fd443cbc681ba 100644 +index 30561ab7a24c734be71ed29d963c11e2ea2c2b22..7cb77fb4f35a60fbda5b868798321ac8b6340bfa 100644 --- a/src/env.h +++ b/src/env.h -@@ -50,7 +50,7 @@ +@@ -49,7 +49,7 @@ #include "uv.h" #include "v8.h" @@ -537,7 +365,7 @@ index fc8dbd615255851cad90e1d8ffe225f5e0c6a718..49ca9c0042ccf22ad1fffa54f05fd443 #include <openssl/evp.h> #endif -@@ -1073,7 +1073,7 @@ class Environment final : public MemoryRetainer { +@@ -1065,7 +1065,7 @@ class Environment : public MemoryRetainer { kExitInfoFieldCount }; @@ -547,7 +375,7 @@ index fc8dbd615255851cad90e1d8ffe225f5e0c6a718..49ca9c0042ccf22ad1fffa54f05fd443 // 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 c59e65ad1fe3fac23f1fc25ca77e6133d1ccaccd..f2f07434e076e2977755ef7dac7d489aedb760b0 100644 +index cf051585e779e2b03bd7b95fe5008b89cc7f8162..9de49c6828468fdf846dcd4ad445390f14446099 100644 --- a/src/node_metadata.h +++ b/src/node_metadata.h @@ -6,7 +6,7 @@ @@ -560,7 +388,7 @@ index c59e65ad1fe3fac23f1fc25ca77e6133d1ccaccd..f2f07434e076e2977755ef7dac7d489a #if NODE_OPENSSL_HAS_QUIC #include <openssl/quic.h> diff --git a/src/node_options.cc b/src/node_options.cc -index cfc599ec9a6197231c3469d318f02c620cdb03a8..29630fcccc3bd9d24ad6aec64bef2fedfc3c4031 100644 +index dba59c5560c22899bd108789360f21fd85dd41bf..818baf611fcab7838a339f3ea137467653e270d0 100644 --- a/src/node_options.cc +++ b/src/node_options.cc @@ -6,7 +6,7 @@ @@ -573,7 +401,7 @@ index cfc599ec9a6197231c3469d318f02c620cdb03a8..29630fcccc3bd9d24ad6aec64bef2fed #endif diff --git a/src/node_options.h b/src/node_options.h -index 9e656a2815045aa5da7eb267708c03058be9f362..600e0850f01e01024414d42b25605f256200540a 100644 +index 10c220f66122336215f25b9674acfdfe6df82a8e..e8b2243d24fe95ff31254071133fb646e186c07e 100644 --- a/src/node_options.h +++ b/src/node_options.h @@ -11,7 +11,7 @@ @@ -585,37 +413,3 @@ index 9e656a2815045aa5da7eb267708c03058be9f362..600e0850f01e01024414d42b25605f25 #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 bc8e7cea5a..787043e5cc 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 605e812d515fc467001e4ab88fc15b4af3fd4aa2..463e76cb1abc0c2fdddba4db2ca2e00f7c591e12 100644 +index ac24cf305bd5995ad13b37ee36f9e1fe3589c5d7..22248b753c14960122f1d6b9bfe6b89fdb8d2010 100644 --- a/lib/internal/modules/esm/load.js +++ b/lib/internal/modules/esm/load.js -@@ -8,7 +8,7 @@ const { kEmptyObject } = require('internal/util'); +@@ -10,7 +10,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'); - const defaultType = - getOptionValue('--experimental-default-type'); -@@ -40,8 +40,7 @@ async function getSource(url, context) { - const responseURL = href; + // 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; 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 result = dataURLProcessor(url); - if (result === 'failure') { -@@ -65,7 +64,7 @@ function getSourceSync(url, context) { + const match = RegExpPrototypeExec(DATA_URL_PATTERN, url.pathname); + if (!match) { +@@ -82,7 +81,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 result = dataURLProcessor(url); - if (result === 'failure') { + 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 f05c6f99c0037193c5802024be46a967d6cf47a0..f3dad958b2ec275992554477b9344214c8c1e2c8 100644 +index 52cdb7d5e14a18ed7b1b65e429729cf47dce3f98..69f73f829706deddc4f328b78af9d58434af647d 100644 --- a/lib/internal/modules/esm/resolve.js +++ b/lib/internal/modules/esm/resolve.js @@ -24,7 +24,7 @@ const { @@ -49,8 +49,17 @@ index f05c6f99c0037193c5802024be46a967d6cf47a0..f3dad958b2ec275992554477b9344214 +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'); -@@ -259,7 +259,7 @@ function finalizeResolution(resolved, base, preserveSymlinks) { + 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) { } if (!preserveSymlinks) { @@ -59,11 +68,20 @@ index f05c6f99c0037193c5802024be46a967d6cf47a0..f3dad958b2ec275992554477b9344214 [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 d182eedf5e96039e0029d36e51f40b75c6fb2a39..06b31af80ebbfbf35ec787a94f345775eb512ebf 100644 +index 89ca269294ee1afa7f5aeb0ac6b8958f7a8b49d0..f3dfc69cd2cdec50bc3b3f7cb2d63349812d87dd 100644 --- a/lib/internal/modules/esm/translators.js +++ b/lib/internal/modules/esm/translators.js -@@ -34,7 +34,7 @@ const { +@@ -36,7 +36,7 @@ const { const { BuiltinModule } = require('internal/bootstrap/realm'); const assert = require('internal/assert'); @@ -72,7 +90,7 @@ index d182eedf5e96039e0029d36e51f40b75c6fb2a39..06b31af80ebbfbf35ec787a94f345775 const { dirname, extname, isAbsolute } = require('path'); const { loadBuiltinModule, -@@ -335,7 +335,7 @@ translators.set('commonjs', async function commonjsStrategy(url, source, +@@ -356,7 +356,7 @@ translators.set('commonjs', async function commonjsStrategy(url, source, try { // We still need to read the FS to detect the exports. @@ -81,7 +99,7 @@ index d182eedf5e96039e0029d36e51f40b75c6fb2a39..06b31af80ebbfbf35ec787a94f345775 } catch { // Continue regardless of error. } -@@ -403,7 +403,7 @@ function cjsPreparseModuleExports(filename, source) { +@@ -424,7 +424,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 e86a1fada5..cf9b4ec08c 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 7f48b7daa87d1a5b14bc6f641b60f21263fa5ec3..0be470c9139a6da19414295a59f1a237cc3a50d7 100644 +index 3375600023e39ddacf62cc17deb4f206db942084..cc106422dd36aa0564e74dd8a16eec496433d3bd 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 65f95c3157add2afca26a133183b65ccba6e9924..81091d364d32094dc91c7abb0c5fe9963d100a8b 100644 +index 69e474257b0427f894375fbc8a2c031f1b8e0c55..f0e968c0dfa8963404c3b87827b8d11a139051cc 100644 --- a/src/node_errors.cc +++ b/src/node_errors.cc -@@ -857,10 +857,6 @@ const char* errno_string(int errorno) { +@@ -855,10 +855,6 @@ const char* errno_string(int errorno) { ERRNO_CASE(ENOBUFS); #endif @@ -100,7 +100,7 @@ index 65f95c3157add2afca26a133183b65ccba6e9924..81091d364d32094dc91c7abb0c5fe996 #ifdef ENODEV ERRNO_CASE(ENODEV); #endif -@@ -899,14 +895,6 @@ const char* errno_string(int errorno) { +@@ -897,14 +893,6 @@ const char* errno_string(int errorno) { ERRNO_CASE(ENOSPC); #endif @@ -115,7 +115,7 @@ index 65f95c3157add2afca26a133183b65ccba6e9924..81091d364d32094dc91c7abb0c5fe996 #ifdef ENOSYS ERRNO_CASE(ENOSYS); #endif -@@ -989,10 +977,6 @@ const char* errno_string(int errorno) { +@@ -987,10 +975,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 deleted file mode 100644 index 0e7268f6cf..0000000000 --- a/patches/node/fix_remove_harmony-import-assertions_from_node_cc.patch +++ /dev/null @@ -1,25 +0,0 @@ -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 15039649de..831e237f29 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,27 +15,31 @@ 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 f3dad958b2ec275992554477b9344214c8c1e2c8..a086217046fd5ed7cfb09cfd2ed62f3987eb1f31 100644 +index 69f73f829706deddc4f328b78af9d58434af647d..1d53a2a47423150e822bb917b2725d3a6a794814 100644 --- a/lib/internal/modules/esm/resolve.js +++ b/lib/internal/modules/esm/resolve.js -@@ -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'); +@@ -36,10 +36,9 @@ const preserveSymlinksMain = getOptionValue('--preserve-symlinks-main'); + const experimentalNetworkImports = + getOptionValue('--experimental-network-imports'); const inputTypeFlag = getOptionValue('--input-type'); --const { URL, pathToFileURL, fileURLToPath, isURL, URLParse } = require('internal/url'); -+const { URL, pathToFileURL, fileURLToPath, isURL, URLParse, toPathIfFileURL } = require('internal/url'); +-const { URL, pathToFileURL, fileURLToPath, isURL } = require('internal/url'); ++const { URL, pathToFileURL, fileURLToPath, isURL, 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, -@@ -154,34 +153,13 @@ function emitLegacyIndexDeprecation(url, packageJSONUrl, base, main) { +@@ -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) { const realpathCache = new SafeMap(); @@ -77,7 +81,7 @@ index f3dad958b2ec275992554477b9344214c8c1e2c8..a086217046fd5ed7cfb09cfd2ed62f39 /** * Legacy CommonJS main resolution: -@@ -196,22 +174,44 @@ const legacyMainResolveExtensionsIndexes = { +@@ -204,22 +182,44 @@ const legacyMainResolveExtensionsIndexes = { * @returns {URL} */ function legacyMainResolve(packageJSONUrl, packageConfig, base) { @@ -138,10 +142,10 @@ index f3dad958b2ec275992554477b9344214c8c1e2c8..a086217046fd5ed7cfb09cfd2ed62f39 const encodedSepRegEx = /%2F|%5C/i; diff --git a/src/node_file.cc b/src/node_file.cc -index 0bb70eb0fcd42ddf4d5e585065cf1ad8e74faab3..b565beae625d970ba92ab667a145d8897d4e8a6e 100644 +index 73ad5a1a2c092d7f8dac84585fb9b13e76e84e13..039f693de14bec248f93262ad70f2736c24827e3 100644 --- a/src/node_file.cc +++ b/src/node_file.cc -@@ -19,14 +19,12 @@ +@@ -19,14 +19,11 @@ // 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) @@ -149,14 +153,14 @@ index 0bb70eb0fcd42ddf4d5e585065cf1ad8e74faab3..b565beae625d970ba92ab667a145d889 #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" -@@ -3208,146 +3206,6 @@ constexpr std::array<std::string_view, 10> legacy_main_extensions = { +@@ -3127,135 +3124,6 @@ constexpr std::array<std::string_view, 10> legacy_main_extensions = { } // namespace @@ -198,20 +202,14 @@ index 0bb70eb0fcd42ddf4d5e585065cf1ad8e74faab3..b565beae625d970ba92ab667a145d889 - return; - } - -- FromNamespacedPath(&initial_file_path.value()); +- node::url::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]); -- // 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())) { +- +- switch (FilePathIsFile(env, file_path)) { - case BindingData::FilePathIsFileReturnType::kIsFile: - return args.GetReturnValue().Set(i); - case BindingData::FilePathIsFileReturnType::kIsNotFile: @@ -241,20 +239,14 @@ index 0bb70eb0fcd42ddf4d5e585065cf1ad8e74faab3..b565beae625d970ba92ab667a145d889 - return; - } - -- FromNamespacedPath(&initial_file_path.value()); +- node::url::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]); -- // 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())) { +- +- switch (FilePathIsFile(env, file_path)) { - case BindingData::FilePathIsFileReturnType::kIsFile: - return args.GetReturnValue().Set(i); - case BindingData::FilePathIsFileReturnType::kIsNotFile: @@ -300,10 +292,11 @@ index 0bb70eb0fcd42ddf4d5e585065cf1ad8e74faab3..b565beae625d970ba92ab667a145d889 - package_initial_file, - *module_base); -} - +- void BindingData::MemoryInfo(MemoryTracker* tracker) const { tracker->TrackField("stats_field_array", stats_field_array); -@@ -3448,19 +3306,6 @@ InternalFieldInfoBase* BindingData::Serialize(int index) { + tracker->TrackField("stats_field_bigint_array", stats_field_bigint_array); +@@ -3355,19 +3223,6 @@ InternalFieldInfoBase* BindingData::Serialize(int index) { return info; } @@ -323,15 +316,15 @@ index 0bb70eb0fcd42ddf4d5e585065cf1ad8e74faab3..b565beae625d970ba92ab667a145d889 static void CreatePerIsolateProperties(IsolateData* isolate_data, Local<ObjectTemplate> target) { Isolate* isolate = isolate_data->isolate(); -@@ -3520,7 +3365,6 @@ static void CreatePerIsolateProperties(IsolateData* isolate_data, - SetMethod(isolate, target, "cpSyncCheckPaths", CpSyncCheckPaths); +@@ -3422,7 +3277,6 @@ static void CreatePerIsolateProperties(IsolateData* isolate_data, + SetMethod(isolate, target, "mkdtemp", Mkdtemp); StatWatcher::CreatePerIsolateProperties(isolate_data, target); - BindingData::CreatePerIsolateProperties(isolate_data, target); target->Set( FIXED_ONE_BYTE_STRING(isolate, "kFsStatsFieldsNumber"), -@@ -3593,7 +3437,6 @@ BindingData* FSReqBase::binding_data() { +@@ -3495,7 +3349,6 @@ BindingData* FSReqBase::binding_data() { void RegisterExternalReferences(ExternalReferenceRegistry* registry) { registry->Register(Access); StatWatcher::RegisterExternalReferences(registry); @@ -340,7 +333,7 @@ index 0bb70eb0fcd42ddf4d5e585065cf1ad8e74faab3..b565beae625d970ba92ab667a145d889 registry->Register(GetFormatOfExtensionlessFile); registry->Register(Close); diff --git a/src/node_file.h b/src/node_file.h -index bdad1ae25f4892cbbfd8cc30c4d8b4a6f600edbc..5a3c462853aa784d9ef61ff4f63010848c48b92c 100644 +index 6f1b55284db0f4f8c70081b4834a074c717f3cc9..a969fff32bd156aa9393c1db9eec474eb7432cea 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 0ff052ab11..391271a50f 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 a96cb915930a30a49ba55fd7d15ea48f0b471f89..3c15f348bd3a9a42afcf0e4d0182d2d6f3d05cb1 100644 +index f6ec79cd57b5010ed5fd6829d952bcdacc8b7671..5cda078a55f7825d135a107fa98e1aa3527dd147 100644 --- a/deps/uv/src/win/util.c +++ b/deps/uv/src/win/util.c -@@ -1537,10 +1537,17 @@ int uv_os_uname(uv_utsname_t* buffer) { +@@ -1685,10 +1685,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 d9d6dc91df..596b997812 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 451b7c2195e7ad3ab0bde95259e054dc431d7de9..d49941881e6cfd8647a6d44a57e0daaf1c874702 100644 +index c284b39b1ac13eaea8776b7b4f457c084dce5fb8..c794751ecd4448119ce33d661e694f83b3323f03 100644 --- a/lib/internal/modules/cjs/loader.js +++ b/lib/internal/modules/cjs/loader.js -@@ -182,6 +182,13 @@ const { +@@ -185,6 +185,13 @@ const { CHAR_FORWARD_SLASH, } = require('internal/constants'); @@ -23,7 +23,7 @@ index 451b7c2195e7ad3ab0bde95259e054dc431d7de9..d49941881e6cfd8647a6d44a57e0daaf const { isProxy, } = require('internal/util/types'); -@@ -1541,10 +1548,12 @@ Module.prototype._compile = function(content, filename, format) { +@@ -1464,10 +1471,12 @@ Module.prototype._compile = function(content, filename, loadAsESM = false) { 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 5e5b538818..f36422f981 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 f7a62364b6107ab0bad33ea2f745703c746991dc..bab2aaf3db66452216035db594dc3ebdc3606c8b 100644 +index 12262f40ce123440a9a0f974386cfbe8511f4459..f3c15b61d33bdae44de528e106fcc6f930f1c388 100644 --- a/lib/internal/bootstrap/node.js +++ b/lib/internal/bootstrap/node.js @@ -134,6 +134,10 @@ process.domain = null; @@ -21,3 +21,47 @@ index f7a62364b6107ab0bad33ea2f745703c746991dc..bab2aaf3db66452216035db594dc3ebd // 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 new file mode 100644 index 0000000000..45f3a8e62c --- /dev/null +++ b/patches/node/spec_add_iterator_to_global_intrinsics.patch @@ -0,0 +1,19 @@ +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 new file mode 100644 index 0000000000..7e2ac1f2eb --- /dev/null +++ b/patches/node/src_do_not_use_deprecated_v8_api.patch @@ -0,0 +1,118 @@ +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 ef2c934d36..78b759febc 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 28a15aa741ddd40c664aae641797e7cc2813442f..08fe98e10b7716c694bbc882299fe0ed9e282d73 100644 +index d98a32d6ec311459877bc3b0de33cca4766aeda7..9fc934975b015b97ddd84bf3eea5d53144130035 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 28a15aa741ddd40c664aae641797e7cc2813442f..08fe98e10b7716c694bbc882299fe0ed return &(wrapper_data_->cppgc_id); } diff --git a/src/env.cc b/src/env.cc -index 665b064091d4cc42a4dc9ee5b0ea9e2f190338ca..4c8cb75945d82544ce2237d94cd1406d15efe424 100644 +index 38802b1e9acf9b3e99fdc4f39770e896393befe3..e0433e29ca98c42a38d1da6d66085fdea1edde29 100644 --- a/src/env.cc +++ b/src/env.cc -@@ -23,6 +23,7 @@ +@@ -22,6 +22,7 @@ #include "util-inl.h" #include "v8-cppgc.h" #include "v8-profiler.h" @@ -63,7 +63,7 @@ index 665b064091d4cc42a4dc9ee5b0ea9e2f190338ca..4c8cb75945d82544ce2237d94cd1406d #include <algorithm> #include <atomic> -@@ -71,7 +72,6 @@ using v8::TryCatch; +@@ -68,7 +69,6 @@ using v8::TryCatch; using v8::Uint32; using v8::Undefined; using v8::Value; @@ -71,7 +71,7 @@ index 665b064091d4cc42a4dc9ee5b0ea9e2f190338ca..4c8cb75945d82544ce2237d94cd1406d using worker::Worker; int const ContextEmbedderTag::kNodeContextTag = 0x6e6f64; -@@ -532,6 +532,14 @@ void IsolateData::CreateProperties() { +@@ -530,6 +530,14 @@ void IsolateData::CreateProperties() { CreateEnvProxyTemplate(this); } @@ -86,7 +86,7 @@ index 665b064091d4cc42a4dc9ee5b0ea9e2f190338ca..4c8cb75945d82544ce2237d94cd1406d constexpr uint16_t kDefaultCppGCEmbedderID = 0x90de; Mutex IsolateData::isolate_data_mutex_; std::unordered_map<uint16_t, std::unique_ptr<PerIsolateWrapperData>> -@@ -569,36 +577,16 @@ IsolateData::IsolateData(Isolate* isolate, +@@ -567,36 +575,16 @@ IsolateData::IsolateData(Isolate* isolate, v8::CppHeap* cpp_heap = isolate->GetCppHeap(); uint16_t cppgc_id = kDefaultCppGCEmbedderID; @@ -130,7 +130,7 @@ index 665b064091d4cc42a4dc9ee5b0ea9e2f190338ca..4c8cb75945d82544ce2237d94cd1406d { // GC could still be run after the IsolateData is destroyed, so we store -@@ -630,11 +618,12 @@ IsolateData::~IsolateData() { +@@ -628,11 +616,12 @@ IsolateData::~IsolateData() { } } @@ -146,10 +146,10 @@ index 665b064091d4cc42a4dc9ee5b0ea9e2f190338ca..4c8cb75945d82544ce2237d94cd1406d void IsolateData::MemoryInfo(MemoryTracker* tracker) const { diff --git a/src/env.h b/src/env.h -index 49ca9c0042ccf22ad1fffa54f05fd443cbc681ba..945535d0dc40f1a32f7e3ecf7d50361e591ba6c8 100644 +index 7cb77fb4f35a60fbda5b868798321ac8b6340bfa..06746554e1d60a9377ff6d7d970220f3fa88e4ac 100644 --- a/src/env.h +++ b/src/env.h -@@ -175,10 +175,6 @@ class NODE_EXTERN_PRIVATE IsolateData : public MemoryRetainer { +@@ -174,10 +174,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 49ca9c0042ccf22ad1fffa54f05fd443cbc681ba..945535d0dc40f1a32f7e3ecf7d50361e inline MultiIsolatePlatform* platform() const; inline const SnapshotData* snapshot_data() const; diff --git a/src/node.h b/src/node.h -index c16204ad2a4787eeffe61eedda254d3a5509df8c..c39f586e9c5e7e9db75d922d244ea8e4d6d56841 100644 +index df3fb3372d6357b5d77b4f683e309b8483998128..01e8a4f2ed905bf5bbb803419012a014c204b460 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 861bd69338..6aa803f630 100644 --- a/patches/node/src_stop_using_deprecated_fields_of_fastapicallbackoptions.patch +++ b/patches/node/src_stop_using_deprecated_fields_of_fastapicallbackoptions.patch @@ -11,20 +11,6 @@ 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 @@ -39,36 +25,6 @@ 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 new file mode 100644 index 0000000000..8d576cc657 --- /dev/null +++ b/patches/node/src_update_default_v8_platform_to_override_functions_with_location.patch @@ -0,0 +1,87 @@ +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 new file mode 100644 index 0000000000..3688d4d252 --- /dev/null +++ b/patches/node/src_use_new_v8_api_to_define_stream_accessor.patch @@ -0,0 +1,153 @@ +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 new file mode 100644 index 0000000000..c4c302dc66 --- /dev/null +++ b/patches/node/src_use_supported_api_to_get_stalled_tla_messages.patch @@ -0,0 +1,27 @@ +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 40624c1ca8..abeae7e10d 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 5fc1b6f2446d7c786024eb60800e2edab613dcd1..f59abcb21d64b910d8d42eb23c03109f62558813 100644 +index e0bf37f09dceb93af58990438ab577a9d4b843e8..b9098d102b40adad7fafcc331ac62870617019b9 100644 --- a/src/api/environment.cc +++ b/src/api/environment.cc @@ -101,6 +101,14 @@ MaybeLocal<Value> PrepareStackTraceCallback(Local<Context> context, @@ -25,49 +25,11 @@ index 5fc1b6f2446d7c786024eb60800e2edab613dcd1..f59abcb21d64b910d8d42eb23c03109f 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 ee81048caab4ccfe26ea9e677782c9c955d162a9..643c9d31dc2737faa2ec51684ffceb35a1014a58 100644 +index 63d971e1fe6b861e29c12f04563701b01fdfb976..f39652a6f5196531cd78ce74e91076b1b9e970ca 100644 --- a/src/crypto/crypto_util.cc +++ b/src/crypto/crypto_util.cc -@@ -326,10 +326,35 @@ ByteSource& ByteSource::operator=(ByteSource&& other) noexcept { +@@ -348,10 +348,35 @@ ByteSource& ByteSource::operator=(ByteSource&& other) noexcept { return *this; } @@ -104,7 +66,7 @@ index ee81048caab4ccfe26ea9e677782c9c955d162a9..643c9d31dc2737faa2ec51684ffceb35 std::unique_ptr<BackingStore> ptr = ArrayBuffer::NewBackingStore( allocated_data_, size(), -@@ -341,10 +366,11 @@ std::unique_ptr<BackingStore> ByteSource::ReleaseToBackingStore() { +@@ -363,10 +388,11 @@ std::unique_ptr<BackingStore> ByteSource::ReleaseToBackingStore() { data_ = nullptr; size_ = 0; return ptr; @@ -117,7 +79,7 @@ index ee81048caab4ccfe26ea9e677782c9c955d162a9..643c9d31dc2737faa2ec51684ffceb35 return ArrayBuffer::New(env->isolate(), std::move(store)); } -@@ -641,6 +667,16 @@ namespace { +@@ -703,6 +729,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. @@ -134,7 +96,7 @@ index ee81048caab4ccfe26ea9e677782c9c955d162a9..643c9d31dc2737faa2ec51684ffceb35 void SecureBuffer(const FunctionCallbackInfo<Value>& args) { CHECK(args[0]->IsUint32()); Environment* env = Environment::GetCurrent(args); -@@ -662,6 +698,7 @@ void SecureBuffer(const FunctionCallbackInfo<Value>& args) { +@@ -724,6 +760,7 @@ void SecureBuffer(const FunctionCallbackInfo<Value>& args) { Local<ArrayBuffer> buffer = ArrayBuffer::New(env->isolate(), store); args.GetReturnValue().Set(Uint8Array::New(buffer, 0, len)); } @@ -143,10 +105,10 @@ index ee81048caab4ccfe26ea9e677782c9c955d162a9..643c9d31dc2737faa2ec51684ffceb35 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 922e77091d72172ed6cfc5e8477901e3608396c5..16a236c69caed6d60248c7973531a95adc8f2edb 100644 +index 4ba261014695cf1aa8eb53b21a2873f4c4ea8e43..b695d131bcdc331974f544924138bb5eedc50c9f 100644 --- a/src/crypto/crypto_util.h +++ b/src/crypto/crypto_util.h -@@ -268,7 +268,7 @@ class ByteSource { +@@ -285,7 +285,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. @@ -155,44 +117,11 @@ index 922e77091d72172ed6cfc5e8477901e3608396c5..16a236c69caed6d60248c7973531a95a 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 43bb68351bf0a68285e464601013bbdbd5d5df5f..4126bbff080548c91154a6dcc437359c82a6c771 100644 +index 2aa7cd98ecc179519a6bb1932dafa86a38bda4f5..79376bef2e674f05fd95380dd419e8778cb98623 100644 --- a/src/node_i18n.cc +++ b/src/node_i18n.cc -@@ -107,7 +107,7 @@ namespace { +@@ -106,7 +106,7 @@ namespace { template <typename T> MaybeLocal<Object> ToBufferEndian(Environment* env, MaybeStackBuffer<T>* buf) { @@ -201,7 +130,7 @@ index 43bb68351bf0a68285e464601013bbdbd5d5df5f..4126bbff080548c91154a6dcc437359c if (ret.IsEmpty()) return ret; -@@ -184,7 +184,7 @@ MaybeLocal<Object> TranscodeLatin1ToUcs2(Environment* env, +@@ -183,7 +183,7 @@ MaybeLocal<Object> TranscodeLatin1ToUcs2(Environment* env, return {}; } @@ -210,7 +139,7 @@ index 43bb68351bf0a68285e464601013bbdbd5d5df5f..4126bbff080548c91154a6dcc437359c } MaybeLocal<Object> TranscodeFromUcs2(Environment* env, -@@ -229,7 +229,7 @@ MaybeLocal<Object> TranscodeUcs2FromUtf8(Environment* env, +@@ -228,7 +228,7 @@ MaybeLocal<Object> TranscodeUcs2FromUtf8(Environment* env, return {}; } @@ -219,7 +148,7 @@ index 43bb68351bf0a68285e464601013bbdbd5d5df5f..4126bbff080548c91154a6dcc437359c } MaybeLocal<Object> TranscodeUtf8FromUcs2(Environment* env, -@@ -253,7 +253,7 @@ MaybeLocal<Object> TranscodeUtf8FromUcs2(Environment* env, +@@ -252,7 +252,7 @@ MaybeLocal<Object> TranscodeUtf8FromUcs2(Environment* env, return {}; } @@ -229,7 +158,7 @@ index 43bb68351bf0a68285e464601013bbdbd5d5df5f..4126bbff080548c91154a6dcc437359c constexpr const char* EncodingName(const enum encoding encoding) { diff --git a/src/node_internals.h b/src/node_internals.h -index fe2d25decd883085e4c3f368ab4acc01a7f66f6e..bcd5c87afcff9c56429443363c63fc8079521451 100644 +index 6264f23d54d6028bb0158f12a9296ba67a846358..613300215766aeb108219b0d1c3b95ee02db964f 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 5b01232074..79b02f4e85 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 24e1a74886bad536dc08df75fbdb0508e4e1420a..7f3be73474557788050a9110b0e29e602b7d6397 100644 +index 79a953df7da64b7d7580e099a5cc5160e7842999..94616df356cab50c8ef4099e7863f5986deed377 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 85e434f823..97df457cbd 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 309e904c49b7124b64831293e0473a5d35249081..6636144f5074811f95bbe53a62718c8084088bdc 100644 +index 8e497739d21c70d5c792f43c268746a200916063..cad1910e020b15775ee16122bc9d310680fed687 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 309e904c49b7124b64831293e0473a5d35249081..6636144f5074811f95bbe53a62718c80 + return str.replaceAll(`${baseName} --`, '* --'); +} + - describe('v8 output', { concurrency: !process.env.TEST_PARALLEL }, () => { + describe('v8 output', { concurrency: true }, () => { function normalize(str) { return str.replaceAll(snapshot.replaceWindowsPaths(process.cwd()), '') -@@ -15,10 +22,10 @@ describe('v8 output', { concurrency: !process.env.TEST_PARALLEL }, () => { +@@ -15,10 +22,10 @@ describe('v8 output', { concurrency: true }, () => { .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 new file mode 100644 index 0000000000..6a0a9f4b9d --- /dev/null +++ b/patches/node/test_match_wpt_streams_transferable_transform-stream-members_any_js.patch @@ -0,0 +1,23 @@ +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 671fcb14ed..1e0ac6eaca 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 bb954165f42c9de3db66bc5fdcac647654ad71ea..07be833e6e749a2bb68490c935c6791c178d126f 100644 +index 2366cbf716c11851bb3a759dce5db47d616516dc..9d2971ba9411bb98107f6a9acc8a07ec438b76e5 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 bb954165f42c9de3db66bc5fdcac647654ad71ea..07be833e6e749a2bb68490c935c6791c + '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 deleted file mode 100644 index 4a210d885a..0000000000 --- a/patches/node/win_almost_fix_race_detecting_esrch_in_uv_kill.patch +++ /dev/null @@ -1,70 +0,0 @@ -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 new file mode 100644 index 0000000000..ff3ed47f1d --- /dev/null +++ b/patches/node/win_process_avoid_assert_after_spawning_store_app_4152.patch @@ -0,0 +1,85 @@ +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 deleted file mode 100644 index ce35559581..0000000000 --- a/patches/sqlite/.patches +++ /dev/null @@ -1 +0,0 @@ -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 deleted file mode 100644 index 0978319495..0000000000 --- a/patches/sqlite/fix_rename_sqlite_win32_exports_to_avoid_conflicts_with_node_js.patch +++ /dev/null @@ -1,31 +0,0 @@ -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 e967f2e10c..e14cf2394a 100644 --- a/script/node-disabled-tests.json +++ b/script/node-disabled-tests.json @@ -1,14 +1,12 @@ [ "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", @@ -37,7 +35,6 @@ "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", @@ -63,7 +60,6 @@ "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 782357ac37..8db8d80c14 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::shared_ptr<node::InitializationResult> result = + std::unique_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 6e8d360982..4addf43708 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,10 +165,8 @@ bool ShouldBlockAccessToPath(const base::FilePath& path, ChromeFileSystemAccessPermissionContext::kBlockedPaths) { if (key == ChromeFileSystemAccessPermissionContext::kNoBasePathKey) { rules.emplace_back(base::FilePath{rule_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); + } else if (base::FilePath path; base::PathService::Get(key, &path)) { + rules.emplace_back(rule_path ? path.Append(rule_path) : path, type); } } diff --git a/shell/common/node_bindings.cc b/shell/common/node_bindings.cc index 5a0aaa6e96..b2b94d89e0 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::shared_ptr<node::InitializationResult> result = + std::unique_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 9e2dad10df..b17a6f70a8 100644 --- a/spec/api-utility-process-spec.ts +++ b/spec/api-utility-process-spec.ts @@ -510,8 +510,7 @@ describe('utilityProcess module', () => { expect(output).to.equal(result); }); - // 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 () => { + it('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 df1d52546c..277e13f97e 100644 --- a/spec/fixtures/native-addon/external-ab/binding.cc +++ b/spec/fixtures/native-addon/external-ab/binding.cc @@ -1,4 +1,5 @@ #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 ead2cb5539..2eca91da38 100644 --- a/spec/lib/events-helpers.ts +++ b/spec/lib/events-helpers.ts @@ -20,5 +20,4 @@ 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 cac51c4a3f..f7dc46f92f 100644 --- a/yarn.lock +++ b/yarn.lock @@ -997,12 +997,12 @@ dependencies: undici-types "~6.19.2" -"@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== +"@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== dependencies: - undici-types "~6.19.2" + undici-types "~5.26.4" "@types/normalize-package-data@^2.4.0": version "2.4.1" @@ -7042,7 +7042,14 @@ stringify-object@^3.3.0: is-obj "^1.0.1" is-regexp "^1.0.0" -"strip-ansi-cjs@npm:strip-ansi@^6.0.1", strip-ansi@^6.0.0, strip-ansi@^6.0.1: +"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: version "6.0.1" resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-6.0.1.tgz#9e26c63d30f53443e9489495b2105d37b67a85d9" integrity sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A== @@ -7434,6 +7441,11 @@ 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"
build
aa40e817c853a5e71ab59ce2cb29b8ee258c0d59
John Kleinschmidt
2024-10-07 18:51:23
ci: add datadog test logging (#44094)
diff --git a/.github/workflows/pipeline-segment-electron-test.yml b/.github/workflows/pipeline-segment-electron-test.yml index eb78dd0dd9..137fe91996 100644 --- a/.github/workflows/pipeline-segment-electron-test.yml +++ b/.github/workflows/pipeline-segment-electron-test.yml @@ -146,17 +146,21 @@ jobs: sudo security authorizationdb write com.apple.trust-settings.admin allow cd src/electron ./script/codesign/generate-identity.sh + - name: Install Datadog CLI + run: | + cd src/electron + node script/yarn global add @datadog/datadog-ci - name: Run Electron Tests shell: bash env: MOCHA_REPORTER: mocha-multi-reporters - ELECTRON_TEST_RESULTS_DIR: junit MOCHA_MULTI_REPORTERS: mocha-junit-reporter, tap ELECTRON_DISABLE_SECURITY_WARNINGS: 1 ELECTRON_SKIP_NATIVE_MODULE_TESTS: true DISPLAY: ':99.0' run: | cd src/electron + export ELECTRON_TEST_RESULTS_DIR=`pwd`/junit # Get which tests are on this shard tests_files=$(node script/split-tests ${{ matrix.shard }} ${{ inputs.target-platform == 'macos' && 2 || 3 }}) @@ -185,6 +189,15 @@ jobs: 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: Upload Test results to Datadog + env: + DD_ENV: ci + DD_SERVICE: electron + DD_API_KEY: ${{ secrets.DD_API_KEY }} + DD_CIVISIBILITY_LOGS_ENABLED: true + DD_TAGS: "os.architecture:${{ inputs.target-arch }},os.family:${{ inputs.target-platform }},os.platform:${{ inputs.target-platform }},asan:${{ inputs.is-asan }}" + run: datadog-ci junit upload src/electron/junit/test-results-main.xml + if: always() && !cancelled() - name: Upload Test Artifacts if: always() && !cancelled() uses: actions/upload-artifact@50769540e7f4bd5e21e526ee35c689e35e0d6874 diff --git a/appveyor-woa.yml b/appveyor-woa.yml index 97be324ae0..822381870a 100644 --- a/appveyor-woa.yml +++ b/appveyor-woa.yml @@ -36,7 +36,7 @@ environment: ELECTRON_ENABLE_STACK_DUMPING: 1 ELECTRON_ALSO_LOG_TO_STDERR: 1 MOCHA_REPORTER: mocha-multi-reporters - MOCHA_MULTI_REPORTERS: "@marshallofsound/mocha-appveyor-reporter, tap" + MOCHA_MULTI_REPORTERS: "@marshallofsound/mocha-appveyor-reporter, mocha-junit-reporter, tap" DEPOT_TOOLS_WIN_TOOLCHAIN: 1 DEPOT_TOOLS_WIN_TOOLCHAIN_BASE_URL: "https://dev-cdn.electronjs.org/windows-toolchains/_" GYP_MSVS_HASH_7393122652: 3ba76c5c20 @@ -258,10 +258,14 @@ for: environment: IGNORE_YARN_INSTALL_ERROR: 1 - ELECTRON_TEST_RESULTS_DIR: junit - MOCHA_MULTI_REPORTERS: 'mocha-junit-reporter, tap' + ELECTRON_TEST_RESULTS_DIR: C:\projects\src\electron\junit + MOCHA_MULTI_REPORTERS: "@marshallofsound/mocha-appveyor-reporter, mocha-junit-reporter, tap" MOCHA_REPORTER: mocha-multi-reporters ELECTRON_SKIP_NATIVE_MODULE_TESTS: true + DD_ENV: ci + DD_SERVICE: electron + DD_CIVISIBILITY_LOGS_ENABLED: true + DD_GIT_REPOSITORY_URL: "https://github.com/electron/electron.git" build_script: - ps: | @@ -273,6 +277,7 @@ for: } else { $global:LASTEXITCODE = 0 } + - ps: Invoke-WebRequest -Uri "https://github.com/DataDog/datadog-ci/releases/latest/download/datadog-ci_win-x64" -OutFile "C:\projects\src\electron\datadog-ci.exe" - cd .. - mkdir out\Default - cd .. @@ -328,3 +333,10 @@ for: on_finish: # Uncomment these lines to enable RDP # - ps: $blockRdp = $true; iex ((new-object net.webclient).DownloadString('https://raw.githubusercontent.com/appveyor/ci/master/scripts/enable-rdp.ps1')) + - if exist electron\junit\test-results-main.xml ( appveyor-retry appveyor PushArtifact electron\junit\test-results-main.xml ) + - ps: | + $env:DD_GIT_COMMIT_SHA = $env:APPVEYOR_REPO_COMMIT + $env:DD_GIT_BRANCH = $env:APPVEYOR_PULL_REQUEST_HEAD_REPO_BRANCH + $env:DD_TAGS = "os.architecture:$env:TARGET_ARCH,os.family:windows,os.platform:win32" + C:\projects\src\electron\datadog-ci.exe junit upload --verbose C:\projects\src\electron\junit\test-results-main.xml + diff --git a/appveyor.yml b/appveyor.yml index 88290d41ca..18055fb282 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -36,7 +36,7 @@ environment: ELECTRON_ENABLE_STACK_DUMPING: 1 ELECTRON_ALSO_LOG_TO_STDERR: 1 MOCHA_REPORTER: mocha-multi-reporters - MOCHA_MULTI_REPORTERS: "@marshallofsound/mocha-appveyor-reporter, tap" + MOCHA_MULTI_REPORTERS: "@marshallofsound/mocha-appveyor-reporter, mocha-junit-reporter, tap" DEPOT_TOOLS_WIN_TOOLCHAIN: 1 DEPOT_TOOLS_WIN_TOOLCHAIN_BASE_URL: "https://dev-cdn.electronjs.org/windows-toolchains/_" GYP_MSVS_HASH_7393122652: 3ba76c5c20 @@ -248,6 +248,13 @@ for: only: - job_name: Test + environment: + DD_ENV: ci + DD_SERVICE: electron + DD_CIVISIBILITY_LOGS_ENABLED: true + DD_GIT_REPOSITORY_URL: "https://github.com/electron/electron.git" + ELECTRON_TEST_RESULTS_DIR: C:\projects\src\electron\junit + init: - ps: | if ($env:RUN_TESTS -ne 'true') { @@ -263,6 +270,7 @@ for: } else { $global:LASTEXITCODE = 0 } + - npm install -g @datadog/datadog-ci - cd .. - mkdir out\Default - cd .. @@ -320,3 +328,9 @@ for: on_finish: # Uncomment these lines to enable RDP # - ps: $blockRdp = $true; iex ((new-object net.webclient).DownloadString('https://raw.githubusercontent.com/appveyor/ci/master/scripts/enable-rdp.ps1')) + - if exist electron\junit\test-results-main.xml ( appveyor-retry appveyor PushArtifact electron\junit\test-results-main.xml ) + - ps: | + $env:DD_GIT_COMMIT_SHA = $env:APPVEYOR_REPO_COMMIT + $env:DD_GIT_BRANCH = $env:APPVEYOR_PULL_REQUEST_HEAD_REPO_BRANCH + $env:DD_TAGS = "os.architecture:$env:TARGET_ARCH,os.family:windows,os.platform:win32" + C:\Users\appveyor\AppData\Roaming\npm\datadog-ci.ps1 junit upload --verbose C:\projects\src\electron\junit\test-results-main.xml
ci
24d6c28b5ac0dff74eceb805b9a0144abe4f51a3
Charles Kerr
2024-06-21 09:31:10
chore: remove walkdir dev dependency (#42591)
diff --git a/spec/get-files.ts b/spec/get-files.ts index e6e59c1da4..519f694278 100644 --- a/spec/get-files.ts +++ b/spec/get-files.ts @@ -1,14 +1,11 @@ -import { once } from 'node:events'; -import * as walkdir from 'walkdir'; +import * as fs from 'node:fs'; +import * as path from 'node:path'; -export async function getFiles (directoryPath: string, { filter = null }: {filter?: ((file: string) => boolean) | null} = {}) { - const files: string[] = []; - const walker = walkdir(directoryPath, { - no_recurse: true - }); - walker.on('file', (file) => { - if (!filter || filter(file)) { files.push(file); } - }); - await once(walker, 'end'); - return files; +export async function getFiles ( + dir: string, + test: ((file: string) => boolean) = (_: string) => true // eslint-disable-line @typescript-eslint/no-unused-vars +): Promise<string[]> { + return fs.promises.readdir(dir) + .then(files => files.map(file => path.join(dir, file))) + .then(files => files.filter(file => test(file))); } diff --git a/spec/index.js b/spec/index.js index 2082ea9b2a..34967e8f39 100644 --- a/spec/index.js +++ b/spec/index.js @@ -148,7 +148,7 @@ app.whenReady().then(async () => { }; const { getFiles } = require('./get-files'); - const testFiles = await getFiles(__dirname, { filter }); + const testFiles = await getFiles(__dirname, filter); for (const file of testFiles.sort()) { mocha.addFile(file); } diff --git a/spec/package.json b/spec/package.json index 94f0f54246..8455bdb996 100644 --- a/spec/package.json +++ b/spec/package.json @@ -35,7 +35,6 @@ "split": "^1.0.1", "temp": "^0.9.0", "uuid": "^3.3.3", - "walkdir": "^0.3.2", "winreg": "1.2.4", "ws": "^7.4.6", "yargs": "^16.0.3" diff --git a/spec/yarn.lock b/spec/yarn.lock index f833f786fe..d9bf04094c 100644 --- a/spec/yarn.lock +++ b/spec/yarn.lock @@ -2037,11 +2037,6 @@ validate-npm-package-license@^3.0.1: spdx-correct "^3.0.0" spdx-expression-parse "^3.0.0" -walkdir@^0.3.2: - version "0.3.2" - resolved "https://registry.yarnpkg.com/walkdir/-/walkdir-0.3.2.tgz#ac8437a288c295656848ebc19981ebc677a5f590" - integrity sha512-0Twghia4Z5wDGDYWURlhZmI47GvERMCsXIu0QZWVVZyW9ZjpbbZvD9Zy9M6cWiQQRRbAcYajIyKNavaZZDt1Uw== - web-streams-polyfill@^3.2.1: version "3.3.3" resolved "https://registry.yarnpkg.com/web-streams-polyfill/-/web-streams-polyfill-3.3.3.tgz#2073b91a2fdb1fbfbd401e7de0ac9f8214cecb4b"
chore
c4c17d75346c7187ae2b286c3ad7cd2d6d15e6ce
Alexey Kuzmin
2023-05-24 20:37:07
build: fix build with "enable_pdf_viewer=false" (#38421) * build: fix build with "enable_pdf_viewer=false" * fixup! build: fix build with "enable_pdf_viewer=false"
diff --git a/BUILD.gn b/BUILD.gn index 362716ac14..f3224fb1c7 100644 --- a/BUILD.gn +++ b/BUILD.gn @@ -773,6 +773,8 @@ source_set("electron_lib") { sources += [ "shell/browser/electron_pdf_web_contents_helper_client.cc", "shell/browser/electron_pdf_web_contents_helper_client.h", + "shell/browser/extensions/api/pdf_viewer_private/pdf_viewer_private_api.cc", + "shell/browser/extensions/api/pdf_viewer_private/pdf_viewer_private_api.h", ] } diff --git a/filenames.gni b/filenames.gni index b2d0125979..03bf12e1d0 100644 --- a/filenames.gni +++ b/filenames.gni @@ -695,8 +695,6 @@ filenames = { "shell/browser/extensions/api/management/electron_management_api_delegate.h", "shell/browser/extensions/api/resources_private/resources_private_api.cc", "shell/browser/extensions/api/resources_private/resources_private_api.h", - "shell/browser/extensions/api/pdf_viewer_private/pdf_viewer_private_api.cc", - "shell/browser/extensions/api/pdf_viewer_private/pdf_viewer_private_api.h", "shell/browser/extensions/api/runtime/electron_runtime_api_delegate.cc", "shell/browser/extensions/api/runtime/electron_runtime_api_delegate.h", "shell/browser/extensions/api/streams_private/streams_private_api.cc",
build
695fcf3cb265aa2b635e9bfdad4e0affe527c917
Shelley Vohr
2023-07-26 16:47:32
fix: reparenting after `BrowserWindow.destroy()` (#39062) fix: reparenting after BrowserWindow.destroy()
diff --git a/shell/browser/native_window.h b/shell/browser/native_window.h index ef3792300c..8ce8749458 100644 --- a/shell/browser/native_window.h +++ b/shell/browser/native_window.h @@ -149,6 +149,7 @@ class NativeWindow : public base::SupportsUserData, virtual std::string GetAlwaysOnTopLevel() = 0; virtual void SetActive(bool is_key) = 0; virtual bool IsActive() const = 0; + virtual void RemoveChildFromParentWindow() = 0; virtual void RemoveChildWindow(NativeWindow* child) = 0; virtual void AttachChildren() = 0; virtual void DetachChildren() = 0; diff --git a/shell/browser/native_window_mac.h b/shell/browser/native_window_mac.h index 39246fddb6..9b089c5264 100644 --- a/shell/browser/native_window_mac.h +++ b/shell/browser/native_window_mac.h @@ -157,7 +157,7 @@ class NativeWindowMac : public NativeWindow, bool IsActive() const override; // Remove the specified child window without closing it. void RemoveChildWindow(NativeWindow* child) override; - void RemoveChildFromParentWindow(NativeWindow* child); + void RemoveChildFromParentWindow() override; // Attach child windows, if the window is visible. void AttachChildren() override; // Detach window from parent without destroying it. diff --git a/shell/browser/native_window_mac.mm b/shell/browser/native_window_mac.mm index 7af696339e..7c44cfbed1 100644 --- a/shell/browser/native_window_mac.mm +++ b/shell/browser/native_window_mac.mm @@ -434,7 +434,12 @@ void NativeWindowMac::Close() { } // Ensure we're detached from the parent window before closing. - RemoveChildFromParentWindow(this); + RemoveChildFromParentWindow(); + + while (!child_windows_.empty()) { + auto* child = child_windows_.back(); + child->RemoveChildFromParentWindow(); + } // If a sheet is attached to the window when we call // [window_ performClose:nil], the window won't close properly @@ -453,7 +458,14 @@ void NativeWindowMac::Close() { } void NativeWindowMac::CloseImmediately() { - RemoveChildFromParentWindow(this); + // Ensure we're detached from the parent window before closing. + RemoveChildFromParentWindow(); + + while (!child_windows_.empty()) { + auto* child = child_windows_.back(); + child->RemoveChildFromParentWindow(); + } + [window_ close]; } @@ -642,9 +654,11 @@ void NativeWindowMac::RemoveChildWindow(NativeWindow* child) { [window_ removeChildWindow:child->GetNativeWindow().GetNativeNSWindow()]; } -void NativeWindowMac::RemoveChildFromParentWindow(NativeWindow* child) { - if (parent()) - parent()->RemoveChildWindow(child); +void NativeWindowMac::RemoveChildFromParentWindow() { + if (parent() && !is_modal()) { + parent()->RemoveChildWindow(this); + NativeWindow::SetParentWindow(nullptr); + } } void NativeWindowMac::AttachChildren() { @@ -1842,12 +1856,13 @@ void NativeWindowMac::InternalSetParentWindow(NativeWindow* new_parent, return; // Remove current parent window. - RemoveChildFromParentWindow(this); + RemoveChildFromParentWindow(); // Set new parent window. - if (new_parent && attach) { + if (new_parent) { new_parent->add_child_window(this); - new_parent->AttachChildren(); + if (attach) + new_parent->AttachChildren(); } NativeWindow::SetParentWindow(new_parent); diff --git a/spec/api-browser-window-spec.ts b/spec/api-browser-window-spec.ts index 25071881ff..ed55d9af8b 100644 --- a/spec/api-browser-window-spec.ts +++ b/spec/api-browser-window-spec.ts @@ -4797,6 +4797,7 @@ describe('BrowserWindow module', () => { c.setParentWindow(null); expect(c.getParentWindow()).to.be.null('c.parent'); }); + it('adds window to child windows of parent', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); @@ -4806,6 +4807,7 @@ describe('BrowserWindow module', () => { c.setParentWindow(null); expect(w.getChildWindows()).to.deep.equal([]); }); + it('removes from child windows of parent when window is closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); @@ -4817,6 +4819,25 @@ describe('BrowserWindow module', () => { await setTimeout(); expect(w.getChildWindows().length).to.equal(0); }); + + ifit(process.platform === 'darwin')('can reparent when the first parent is destroyed', async () => { + const w1 = new BrowserWindow({ show: false }); + const w2 = new BrowserWindow({ show: false }); + const c = new BrowserWindow({ show: false }); + + c.setParentWindow(w1); + expect(w1.getChildWindows().length).to.equal(1); + + const closed = once(w1, 'closed'); + w1.destroy(); + await closed; + + c.setParentWindow(w2); + await setTimeout(); + + const children = w2.getChildWindows(); + expect(children[0]).to.equal(c); + }); }); describe('modal option', () => {
fix
4e10eeb87e8ad361ef497d3e40ab435d8504d4c9
Shelley Vohr
2024-07-11 01:32:29
fix: `desktopCapturer` and `screen` source ids should match screen ids (#42781) * fix: desktopCapturer screen source ids should match screen ids * test: add a regression test
diff --git a/shell/browser/api/electron_api_desktop_capturer.cc b/shell/browser/api/electron_api_desktop_capturer.cc index 5d9bc96a03..b2001bbe0c 100644 --- a/shell/browser/api/electron_api_desktop_capturer.cc +++ b/shell/browser/api/electron_api_desktop_capturer.cc @@ -167,6 +167,16 @@ std::unique_ptr<ThumbnailCapturer> MakeScreenCapturer() { : nullptr; } +#if BUILDFLAG(IS_WIN) +BOOL CALLBACK EnumDisplayMonitorsCallback(HMONITOR monitor, + HDC hdc, + LPRECT rect, + LPARAM data) { + reinterpret_cast<std::vector<HMONITOR>*>(data)->push_back(monitor); + return TRUE; +} +#endif + } // namespace namespace gin { @@ -396,11 +406,22 @@ void DesktopCapturer::UpdateSourcesList(DesktopMediaList* list) { return; } - int device_name_index = 0; - for (auto& source : screen_sources) { - const auto& device_name = device_names[device_name_index++]; - const int64_t device_id = base::PersistentHash(device_name); - source.display_id = base::NumberToString(device_id); + std::vector<HMONITOR> monitors; + EnumDisplayMonitors(nullptr, nullptr, EnumDisplayMonitorsCallback, + reinterpret_cast<LPARAM>(&monitors)); + + std::vector<std::pair<std::string, MONITORINFOEX>> pairs; + for (const auto& device_name : device_names) { + std::wstring wide_device_name; + base::UTF8ToWide(device_name.c_str(), device_name.size(), + &wide_device_name); + for (const auto monitor : monitors) { + MONITORINFOEX monitorInfo{{sizeof(MONITORINFOEX)}}; + if (GetMonitorInfo(monitor, &monitorInfo)) { + if (wide_device_name == monitorInfo.szDevice) + pairs.push_back(std::make_pair(device_name, monitorInfo)); + } + } } } #elif BUILDFLAG(IS_MAC) diff --git a/spec/api-screen-spec.ts b/spec/api-screen-spec.ts index 78bb542e05..e5e09cbef6 100644 --- a/spec/api-screen-spec.ts +++ b/spec/api-screen-spec.ts @@ -1,5 +1,6 @@ import { expect } from 'chai'; -import { Display, screen } from 'electron/main'; +import { Display, screen, desktopCapturer } from 'electron/main'; +import { ifit } from './lib/spec-helpers'; describe('screen module', () => { describe('methods reassignment', () => { @@ -14,6 +15,26 @@ describe('screen module', () => { }); }); + describe('screen.getAllDisplays', () => { + it('returns an array of displays', () => { + const displays = screen.getAllDisplays(); + expect(displays).to.be.an('array').with.lengthOf.at.least(1); + for (const display of displays) { + expect(display).to.be.an('object'); + } + }); + + // desktopCapturer.getSources does not work as expected in Windows CI. + ifit(process.platform !== 'win32')('returns displays with IDs matching desktopCapturer source display IDs', async () => { + const displayIds = screen.getAllDisplays().map(d => `${d.id}`); + + const sources = await desktopCapturer.getSources({ types: ['screen'] }); + const sourceIds = sources.map(s => s.display_id); + + expect(displayIds).to.have.members(sourceIds); + }); + }); + describe('screen.getCursorScreenPoint()', () => { it('returns a point object', () => { const point = screen.getCursorScreenPoint();
fix
74d73166d93e569e96721fa4aaeac03698844240
Milan Burda
2023-06-20 23:19:33
chore: remove deleted guest-window-proxy.ts from CODEOWNERS (#38848) chore: remove deleted /lib/browser/guest-window-proxy.ts from CODEOWNERS
diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index f16741b734..1f871bf8a4 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -15,6 +15,5 @@ DEPS @electron/wg-upgrades # Security WG /lib/browser/devtools.ts @electron/wg-security /lib/browser/guest-view-manager.ts @electron/wg-security -/lib/browser/guest-window-proxy.ts @electron/wg-security /lib/browser/rpc-server.ts @electron/wg-security /lib/renderer/security-warnings.ts @electron/wg-security
chore
5643e86956e10bdda8bbbbc85905ac897910b98a
Shelley Vohr
2023-10-02 10:35:00
chore: update extensions url handling to match upstream (#40038) - https://chromium-review.googlesource.com/c/chromium/src/+/4772028 - https://chromium-review.googlesource.com/c/chromium/src/+/4264656 - https://chromium-review.googlesource.com/c/chromium/src/+/4712150
diff --git a/shell/browser/extensions/api/tabs/tabs_api.cc b/shell/browser/extensions/api/tabs/tabs_api.cc index 59a019bf99..53a6b7a32c 100644 --- a/shell/browser/extensions/api/tabs/tabs_api.cc +++ b/shell/browser/extensions/api/tabs/tabs_api.cc @@ -7,20 +7,27 @@ #include <memory> #include <utility> +#include "base/command_line.h" #include "base/strings/pattern.h" +#include "base/types/expected_macros.h" #include "chrome/common/url_constants.h" #include "components/url_formatter/url_fixer.h" #include "content/public/browser/navigation_entry.h" #include "extensions/browser/extension_api_frame_id_map.h" +#include "extensions/browser/extension_prefs.h" #include "extensions/common/error_utils.h" +#include "extensions/common/extension_features.h" +#include "extensions/common/feature_switch.h" #include "extensions/common/manifest_constants.h" #include "extensions/common/mojom/host_id.mojom.h" #include "extensions/common/permissions/permissions_data.h" +#include "extensions/common/switches.h" #include "shell/browser/api/electron_api_web_contents.h" #include "shell/browser/native_window.h" #include "shell/browser/web_contents_zoom_controller.h" #include "shell/browser/window_list.h" #include "shell/common/extensions/api/tabs.h" +#include "third_party/blink/public/common/chrome_debug_urls.h" #include "third_party/blink/public/common/page/page_zoom.h" #include "url/gurl.h" @@ -468,17 +475,25 @@ bool IsKillURL(const GURL& url) { DCHECK(url.IsAboutBlank() || url.IsAboutSrcdoc()); #endif - static const char* const kill_hosts[] = { - chrome::kChromeUICrashHost, chrome::kChromeUIDelayedHangUIHost, - chrome::kChromeUIHangUIHost, chrome::kChromeUIKillHost, + // Disallow common renderer debug URLs. + // Note: this would also disallow JavaScript URLs, but we already explicitly + // check for those before calling into here from PrepareURLForNavigation. + if (blink::IsRendererDebugURL(url)) { + return true; + } + + if (!url.SchemeIs(content::kChromeUIScheme)) { + return false; + } + + // Also disallow a few more hosts which are not covered by the check above. + static const char* const kKillHosts[] = { + chrome::kChromeUIDelayedHangUIHost, chrome::kChromeUIHangUIHost, chrome::kChromeUIQuitHost, chrome::kChromeUIRestartHost, content::kChromeUIBrowserCrashHost, content::kChromeUIMemoryExhaustHost, }; - if (!url.SchemeIs(content::kChromeUIScheme)) - return false; - - return base::Contains(kill_hosts, url.host_piece()); + return base::Contains(kKillHosts, url.host_piece()); } GURL ResolvePossiblyRelativeURL(const std::string& url_string, @@ -489,10 +504,18 @@ GURL ResolvePossiblyRelativeURL(const std::string& url_string, return url; } -bool PrepareURLForNavigation(const std::string& url_string, - const Extension* extension, - GURL* return_url, - std::string* error) { + +bool AllowFileAccess(const ExtensionId& extension_id, + content::BrowserContext* context) { + return base::CommandLine::ForCurrentProcess()->HasSwitch( + switches::kDisableExtensionsFileAccessCheck) || + ExtensionPrefs::Get(context)->AllowFileAccess(extension_id); +} + +base::expected<GURL, std::string> PrepareURLForNavigation( + const std::string& url_string, + const Extension* extension, + content::BrowserContext* browser_context) { GURL url = ResolvePossiblyRelativeURL(url_string, extension); // Ideally, the URL would only be "fixed" for user input (e.g. for URLs @@ -504,34 +527,62 @@ bool PrepareURLForNavigation(const std::string& url_string, // Reject invalid URLs. if (!url.is_valid()) { const char kInvalidUrlError[] = "Invalid url: \"*\"."; - *error = ErrorUtils::FormatErrorMessage(kInvalidUrlError, url_string); - return false; + return base::unexpected( + ErrorUtils::FormatErrorMessage(kInvalidUrlError, url_string)); + } + + // Don't let the extension use JavaScript URLs in API triggered navigations. + if (url.SchemeIs(url::kJavaScriptScheme)) { + const char kJavaScriptUrlsNotAllowedInExtensionNavigations[] = + "JavaScript URLs are not allowed in API based extension navigations. " + "Use " + "chrome.scripting.executeScript instead."; + return base::unexpected(kJavaScriptUrlsNotAllowedInExtensionNavigations); } // Don't let the extension crash the browser or renderers. if (IsKillURL(url)) { const char kNoCrashBrowserError[] = "I'm sorry. I'm afraid I can't do that."; - *error = kNoCrashBrowserError; - return false; + return base::unexpected(kNoCrashBrowserError); } // Don't let the extension navigate directly to devtools scheme pages, unless // they have applicable permissions. - if (url.SchemeIs(content::kChromeDevToolsScheme) && - !(extension->permissions_data()->HasAPIPermission( - extensions::mojom::APIPermissionID::kDevtools) || - extension->permissions_data()->HasAPIPermission( - extensions::mojom::APIPermissionID::kDebugger))) { - const char kCannotNavigateToDevtools[] = - "Cannot navigate to a devtools:// page without either the devtools or " - "debugger permission."; - *error = kCannotNavigateToDevtools; - return false; + if (url.SchemeIs(content::kChromeDevToolsScheme)) { + bool has_permission = + extension && (extension->permissions_data()->HasAPIPermission( + mojom::APIPermissionID::kDevtools) || + extension->permissions_data()->HasAPIPermission( + mojom::APIPermissionID::kDebugger)); + if (!has_permission) { + const char kCannotNavigateToDevtools[] = + "Cannot navigate to a devtools:// page without either the devtools " + "or " + "debugger permission."; + return base::unexpected(kCannotNavigateToDevtools); + } } - return_url->Swap(&url); - return true; + // Don't let the extension navigate directly to chrome-untrusted scheme pages. + if (url.SchemeIs(content::kChromeUIUntrustedScheme)) { + const char kCannotNavigateToChromeUntrusted[] = + "Cannot navigate to a chrome-untrusted:// page."; + return base::unexpected(kCannotNavigateToChromeUntrusted); + } + + // Don't let the extension navigate directly to file scheme pages, unless + // they have file access. + if (url.SchemeIsFile() && + !AllowFileAccess(extension->id(), browser_context) && + base::FeatureList::IsEnabled( + extensions_features::kRestrictFileURLNavigation)) { + const char kFileUrlsNotAllowedInExtensionNavigations[] = + "Cannot navigate to a file URL without local file access."; + return base::unexpected(kFileUrlsNotAllowedInExtensionNavigations); + } + + return url; } TabsUpdateFunction::TabsUpdateFunction() : web_contents_(nullptr) {} @@ -566,22 +617,14 @@ ExtensionFunction::ResponseAction TabsUpdateFunction::Run() { bool TabsUpdateFunction::UpdateURL(const std::string& url_string, int tab_id, std::string* error) { - GURL url; - if (!PrepareURLForNavigation(url_string, extension(), &url, error)) { - return false; - } - - const bool is_javascript_scheme = url.SchemeIs(url::kJavaScriptScheme); - // JavaScript URLs are forbidden in chrome.tabs.update(). - if (is_javascript_scheme) { - const char kJavaScriptUrlsNotAllowedInTabsUpdate[] = - "JavaScript URLs are not allowed in chrome.tabs.update. Use " - "chrome.tabs.executeScript instead."; - *error = kJavaScriptUrlsNotAllowedInTabsUpdate; + auto url = + PrepareURLForNavigation(url_string, extension(), browser_context()); + if (!url.has_value()) { + *error = std::move(url.error()); return false; } - content::NavigationController::LoadURLParams load_params(url); + content::NavigationController::LoadURLParams load_params(*url); // Treat extension-initiated navigations as renderer-initiated so that the URL // does not show in the omnibox until it commits. This avoids URL spoofs diff --git a/spec/extensions-spec.ts b/spec/extensions-spec.ts index 05098f0dd1..148dd8c6c8 100644 --- a/spec/extensions-spec.ts +++ b/spec/extensions-spec.ts @@ -1039,33 +1039,77 @@ describe('chrome extensions', () => { }); }); - it('update', async () => { - await w.loadURL(url); + describe('update', () => { + it('can update muted status', async () => { + await w.loadURL(url); - const message = { method: 'update', args: [{ muted: true }] }; - w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`); + const message = { method: 'update', args: [{ muted: true }] }; + w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`); - const [,, responseString] = await once(w.webContents, 'console-message'); - const response = JSON.parse(responseString); + const [,, responseString] = await once(w.webContents, 'console-message'); + const response = JSON.parse(responseString); + + expect(response).to.have.property('mutedInfo').that.is.a('object'); + const { mutedInfo } = response; + expect(mutedInfo).to.deep.eq({ + muted: true, + reason: 'user' + }); + }); + + it('fails when navigating to an invalid url', async () => { + await w.loadURL(url); + + const message = { method: 'update', args: [{ url: 'chrome://crash' }] }; + w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`); + + const [,, responseString] = await once(w.webContents, 'console-message'); + const { error } = JSON.parse(responseString); + expect(error).to.eq('I\'m sorry. I\'m afraid I can\'t do that.'); + }); + + it('fails when navigating to prohibited url', async () => { + await w.loadURL(url); + + const message = { method: 'update', args: [{ url: 'chrome://crash' }] }; + w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`); + + const [,, responseString] = await once(w.webContents, 'console-message'); + const { error } = JSON.parse(responseString); + expect(error).to.eq('I\'m sorry. I\'m afraid I can\'t do that.'); + }); + + it('fails when navigating to a devtools url without permission', async () => { + await w.loadURL(url); - expect(response).to.have.property('url').that.is.a('string'); - expect(response).to.have.property('title').that.is.a('string'); - 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('windowId').that.is.a('number'); - expect(response).to.have.property('mutedInfo').that.is.a('object'); - const { mutedInfo } = response; - expect(mutedInfo).to.deep.eq({ - muted: true, - reason: 'user' + const message = { method: 'update', args: [{ url: 'devtools://blah' }] }; + w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`); + + const [, , responseString] = await once(w.webContents, 'console-message'); + const { error } = JSON.parse(responseString); + expect(error).to.eq('Cannot navigate to a devtools:// page without either the devtools or debugger permission.'); + }); + + it('fails when navigating to a chrome-untrusted url', async () => { + await w.loadURL(url); + + const message = { method: 'update', args: [{ url: 'chrome-untrusted://blah' }] }; + w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`); + + const [, , responseString] = await once(w.webContents, 'console-message'); + const { error } = JSON.parse(responseString); + expect(error).to.eq('Cannot navigate to a chrome-untrusted:// page.'); + }); + + it('fails when navigating to a file url withotut file access', async () => { + await w.loadURL(url); + + const message = { method: 'update', args: [{ url: 'file://blah' }] }; + w.webContents.executeJavaScript(`window.postMessage('${JSON.stringify(message)}', '*')`); + + const [, , responseString] = await once(w.webContents, 'console-message'); + const { error } = JSON.parse(responseString); + expect(error).to.eq('Cannot navigate to a file URL without local file access.'); }); }); diff --git a/spec/fixtures/extensions/chrome-tabs/api-async/background.js b/spec/fixtures/extensions/chrome-tabs/api-async/background.js index 9133bd4fb6..5b6a0d1b9e 100644 --- a/spec/fixtures/extensions/chrome-tabs/api-async/background.js +++ b/spec/fixtures/extensions/chrome-tabs/api-async/background.js @@ -1,6 +1,6 @@ /* global chrome */ -const handleRequest = (request, sender, sendResponse) => { +const handleRequest = async (request, sender, sendResponse) => { const { method, args = [] } = request; const tabId = sender.tab.id; @@ -53,7 +53,12 @@ const handleRequest = (request, sender, sendResponse) => { case 'update': { const [params] = args; - chrome.tabs.update(tabId, params).then(sendResponse); + try { + const response = await chrome.tabs.update(tabId, params); + sendResponse(response); + } catch (error) { + sendResponse({ error: error.message }); + } break; } }
chore
fdf1ecec47732c2af7ae4abcb3b58d2337622cf0
Leon
2023-09-25 14:03:29
docs: correct v24 Alpha date (#39963)
diff --git a/docs/tutorial/electron-timelines.md b/docs/tutorial/electron-timelines.md index bcabbfc984..bd16cef9a5 100644 --- a/docs/tutorial/electron-timelines.md +++ b/docs/tutorial/electron-timelines.md @@ -12,7 +12,7 @@ check out our [Electron Versioning](./electron-versioning.md) doc. | 27.0.0 | 2023-Aug-17 | 2023-Sep-13 | 2023-Oct-10 | TBD | M118 | TBD | ✅ | | 26.0.0 | 2023-Jun-01 | 2023-Jun-27 | 2023-Aug-15 | 2024-Feb-27 | M116 | v18.16 | ✅ | | 25.0.0 | 2023-Apr-10 | 2023-May-02 | 2023-May-30 | 2024-Jan-02 | M114 | v18.15 | ✅ | -| 24.0.0 | 2022-Feb-09 | 2023-Mar-07 | 2023-Apr-04 | 2023-Oct-10 | M112 | v18.14 | ✅ | +| 24.0.0 | 2023-Feb-09 | 2023-Mar-07 | 2023-Apr-04 | 2023-Oct-10 | M112 | v18.14 | ✅ | | 23.0.0 | 2022-Dec-01 | 2023-Jan-10 | 2023-Feb-07 | 2023-Aug-15 | M110 | v18.12 | 🚫 | | 22.0.0 | 2022-Sep-29 | 2022-Oct-25 | 2022-Nov-29 | 2023-Oct-10 | M108 | v16.17 | ✅ | | 21.0.0 | 2022-Aug-04 | 2022-Aug-30 | 2022-Sep-27 | 2023-Apr-04 | M106 | v16.16 | 🚫 |
docs
784201ecee06252b63ac1e1a2478f9c974bcc85d
Shelley Vohr
2025-01-31 10:29:34
build: try removing `Read/WriteBarrier` patch (#45393) build: try removing Read/WriteBarrier patch
diff --git a/patches/node/.patches b/patches/node/.patches index 82a7440b8e..ea2f73fabe 100644 --- a/patches/node/.patches +++ b/patches/node/.patches @@ -9,7 +9,6 @@ chore_allow_the_node_entrypoint_to_be_a_builtin_module.patch fix_handle_boringssl_and_openssl_incompatibilities.patch fix_crypto_tests_to_run_with_bssl.patch fix_account_for_debugger_agent_race_condition.patch -fix_readbarrier_undefined_symbol_error_on_woa_arm64.patch fix_serdes_test.patch feat_add_uv_loop_interrupt_on_io_change_option_to_uv_loop_configure.patch support_v8_sandboxed_pointers.patch diff --git a/patches/node/fix_readbarrier_undefined_symbol_error_on_woa_arm64.patch b/patches/node/fix_readbarrier_undefined_symbol_error_on_woa_arm64.patch deleted file mode 100644 index 2b9cf7f550..0000000000 --- a/patches/node/fix_readbarrier_undefined_symbol_error_on_woa_arm64.patch +++ /dev/null @@ -1,29 +0,0 @@ -From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 -From: Shelley Vohr <[email protected]> -Date: Wed, 18 Aug 2021 11:25:39 +0200 -Subject: fix: _ReadBarrier undefined symbol error on WOA arm64 - -The _ReadBarrier compiler intrinsic isn't present on WOA arm64 devices -and as such is crashing in CI. This fixes the issue by defining them -if they're missing. - -We should upstream or otherwise handle this. - -diff --git a/deps/histogram/src/hdr_atomic.h b/deps/histogram/src/hdr_atomic.h -index 11b0cbd3facfdce648d7cf59ef3418e4e1049090..e1dfeaed6f0dd38aed5a0ddd5660d5b4ba4f46ab 100644 ---- a/deps/histogram/src/hdr_atomic.h -+++ b/deps/histogram/src/hdr_atomic.h -@@ -14,6 +14,13 @@ - #include <intrin.h> - #include <stdbool.h> - -+#if !defined(_ReadBarrier) || !defined(_WriteBarrier) -+ -+#define _ReadBarrier() __asm__ __volatile__("" ::: "memory") -+#define _WriteBarrier() __asm__ __volatile__("" ::: "memory") -+ -+#endif -+ - static void __inline * hdr_atomic_load_pointer(void** pointer) - { - _ReadBarrier();
build
330c775252670a4e3a912d05871da1d5a3eab1e5
David Sanders
2023-08-07 00:56:36
docs: fix description of pageRanges (#39378) Co-authored-by: Alain BUFERNE <[email protected]>
diff --git a/docs/api/web-contents.md b/docs/api/web-contents.md index cb046fb8fd..0b4cdfe4a0 100644 --- a/docs/api/web-contents.md +++ b/docs/api/web-contents.md @@ -1631,7 +1631,7 @@ win.webContents.print(options, (success, errorType) => { * `bottom` number (optional) - Bottom margin in inches. Defaults to 1cm (~0.4 inches). * `left` number (optional) - Left margin in inches. Defaults to 1cm (~0.4 inches). * `right` number (optional) - Right margin in inches. Defaults to 1cm (~0.4 inches). - * `pageRanges` string (optional) - Paper ranges to print, e.g., '1-5, 8, 11-13'. Defaults to the empty string, which means print all pages. + * `pageRanges` string (optional) - Page ranges to print, e.g., '1-5, 8, 11-13'. Defaults to the empty string, which means print all pages. * `headerTemplate` string (optional) - HTML template for the print header. Should be valid HTML markup with following classes used to inject printing values into them: `date` (formatted print date), `title` (document title), `url` (document location), `pageNumber` (current page number) and `totalPages` (total pages in the document). For example, `<span class=title></span>` would generate span containing the title. * `footerTemplate` string (optional) - HTML template for the print footer. Should use the same format as the `headerTemplate`. * `preferCSSPageSize` boolean (optional) - Whether or not to prefer page size as defined by css. Defaults to false, in which case the content will be scaled to fit the paper size. diff --git a/docs/api/webview-tag.md b/docs/api/webview-tag.md index 74b8c1519d..322a5b6d39 100644 --- a/docs/api/webview-tag.md +++ b/docs/api/webview-tag.md @@ -601,7 +601,7 @@ Prints `webview`'s web page. Same as `webContents.print([options])`. * `bottom` number (optional) - Bottom margin in inches. Defaults to 1cm (~0.4 inches). * `left` number (optional) - Left margin in inches. Defaults to 1cm (~0.4 inches). * `right` number (optional) - Right margin in inches. Defaults to 1cm (~0.4 inches). - * `pageRanges` string (optional) - Paper ranges to print, e.g., '1-5, 8, 11-13'. Defaults to the empty string, which means print all pages. + * `pageRanges` string (optional) - Page ranges to print, e.g., '1-5, 8, 11-13'. Defaults to the empty string, which means print all pages. * `headerTemplate` string (optional) - HTML template for the print header. Should be valid HTML markup with following classes used to inject printing values into them: `date` (formatted print date), `title` (document title), `url` (document location), `pageNumber` (current page number) and `totalPages` (total pages in the document). For example, `<span class=title></span>` would generate span containing the title. * `footerTemplate` string (optional) - HTML template for the print footer. Should use the same format as the `headerTemplate`. * `preferCSSPageSize` boolean (optional) - Whether or not to prefer page size as defined by css. Defaults to false, in which case the content will be scaled to fit the paper size.
docs
08d315da14615d6e4a096199156e94e76597abec
Keeley Hammond
2024-10-08 18:39:37
refactor: revert url::DomainIs() for cookie domains (#44153) build: revert DomainIs refactor
diff --git a/docs/api/cookies.md b/docs/api/cookies.md index 5bca7b570f..8a3576d3fc 100644 --- a/docs/api/cookies.md +++ b/docs/api/cookies.md @@ -74,7 +74,7 @@ The following methods are available on instances of `Cookies`: `url`. Empty implies retrieving cookies of all URLs. * `name` string (optional) - Filters cookies by name. * `domain` string (optional) - Retrieves cookies whose domains match or are - subdomains of `domain`. + subdomains of `domains`. * `path` string (optional) - Retrieves cookies whose path matches `path`. * `secure` boolean (optional) - Filters cookies by their Secure property. * `session` boolean (optional) - Filters out session or persistent cookies. diff --git a/shell/browser/api/electron_api_cookies.cc b/shell/browser/api/electron_api_cookies.cc index 7873b817c5..8870355084 100644 --- a/shell/browser/api/electron_api_cookies.cc +++ b/shell/browser/api/electron_api_cookies.cc @@ -30,7 +30,6 @@ #include "shell/common/gin_helper/dictionary.h" #include "shell/common/gin_helper/object_template_builder.h" #include "shell/common/gin_helper/promise.h" -#include "url/url_util.h" namespace gin { @@ -101,12 +100,25 @@ namespace electron::api { namespace { -bool DomainIs(std::string_view host, const std::string_view domain) { - // Strip any leading '.' character from the input cookie domain. - if (host.starts_with('.')) - host.remove_prefix(1); +// Returns whether |domain| matches |filter|. +bool MatchesDomain(std::string filter, const std::string& domain) { + // Add a leading '.' character to the filter domain if it doesn't exist. + if (net::cookie_util::DomainIsHostOnly(filter)) + filter.insert(0, "."); - return url::DomainIs(host, domain); + std::string sub_domain(domain); + // Strip any leading '.' character from the input cookie domain. + if (!net::cookie_util::DomainIsHostOnly(sub_domain)) + sub_domain = sub_domain.substr(1); + + // Now check whether the domain argument is a subdomain of the filter domain. + for (sub_domain.insert(0, "."); sub_domain.length() >= filter.length();) { + if (sub_domain == filter) + return true; + const size_t next_dot = sub_domain.find('.', 1); // Skip over leading dot. + sub_domain.erase(0, next_dot); + } + return false; } // Returns whether |cookie| matches |filter|. @@ -117,7 +129,8 @@ bool MatchesCookie(const base::Value::Dict& filter, return false; if ((str = filter.FindString("path")) && *str != cookie.Path()) return false; - if ((str = filter.FindString("domain")) && !DomainIs(cookie.Domain(), *str)) + if ((str = filter.FindString("domain")) && + !MatchesDomain(*str, cookie.Domain())) return false; std::optional<bool> secure_filter = filter.FindBool("secure"); if (secure_filter && *secure_filter != cookie.SecureAttribute()) diff --git a/spec/api-session-spec.ts b/spec/api-session-spec.ts index aa7cf11836..d4754ceec6 100644 --- a/spec/api-session-spec.ts +++ b/spec/api-session-spec.ts @@ -5,7 +5,6 @@ import { expect } from 'chai'; import * as send from 'send'; import * as ChildProcess from 'node:child_process'; -import * as crypto from 'node:crypto'; import { once } from 'node:events'; import * as fs from 'node:fs'; import * as http from 'node:http'; @@ -130,54 +129,6 @@ describe('session module', () => { expect(cs.some(c => c.name === name && c.value === value)).to.equal(true); }); - it('does not match on empty domain filter strings', async () => { - const { cookies } = session.defaultSession; - const name = crypto.randomBytes(20).toString('hex'); - const value = '1'; - const url = 'https://microsoft.com/'; - - await cookies.set({ url, name, value }); - const cs = await cookies.get({ domain: '' }); - expect(cs.some(c => c.name === name && c.value === value)).to.equal(false); - cookies.remove(url, name); - }); - - it('gets domain-equal cookies', async () => { - const { cookies } = session.defaultSession; - const name = crypto.randomBytes(20).toString('hex'); - const value = '1'; - const url = 'https://microsoft.com/'; - - await cookies.set({ url, name, value }); - const cs = await cookies.get({ domain: 'microsoft.com' }); - expect(cs.some(c => c.name === name && c.value === value)).to.equal(true); - cookies.remove(url, name); - }); - - it('gets domain-inclusive cookies', async () => { - const { cookies } = session.defaultSession; - const name = crypto.randomBytes(20).toString('hex'); - const value = '1'; - const url = 'https://subdomain.microsoft.com/'; - - await cookies.set({ url, name, value }); - const cs = await cookies.get({ domain: 'microsoft.com' }); - expect(cs.some(c => c.name === name && c.value === value)).to.equal(true); - cookies.remove(url, name); - }); - - it('omits domain-exclusive cookies', async () => { - const { cookies } = session.defaultSession; - const name = crypto.randomBytes(20).toString('hex'); - const value = '1'; - const url = 'https://microsoft.com'; - - await cookies.set({ url, name, value }); - const cs = await cookies.get({ domain: 'subdomain.microsoft.com' }); - expect(cs.some(c => c.name === name && c.value === value)).to.equal(false); - cookies.remove(url, name); - }); - it('rejects when setting a cookie with missing required fields', async () => { const { cookies } = session.defaultSession; const name = '1';
refactor
8397fef3ef5bebb8a4ee7bb50d8ce6a4b19c5fdc
Charles Kerr
2024-09-26 17:09:42
chore: remove unused nogncheck includes (#43964)
diff --git a/shell/app/electron_content_client.cc b/shell/app/electron_content_client.cc index 5693a5353a..8e8b18c17c 100644 --- a/shell/app/electron_content_client.cc +++ b/shell/app/electron_content_client.cc @@ -35,7 +35,6 @@ #if BUILDFLAG(ENABLE_PDF_VIEWER) #include "components/pdf/common/constants.h" // nogncheck -#include "pdf/pdf.h" // nogncheck #include "shell/common/electron_constants.h" #endif // BUILDFLAG(ENABLE_PDF_VIEWER) diff --git a/shell/browser/api/electron_api_web_contents.cc b/shell/browser/api/electron_api_web_contents.cc index a3091fcf57..530b1ac5dc 100644 --- a/shell/browser/api/electron_api_web_contents.cc +++ b/shell/browser/api/electron_api_web_contents.cc @@ -185,10 +185,6 @@ #endif #endif // BUILDFLAG(ENABLE_PRINTING) -#if BUILDFLAG(ENABLE_PDF_VIEWER) -#include "components/pdf/browser/pdf_document_helper.h" // nogncheck -#endif - #if BUILDFLAG(ENABLE_PLUGINS) #include "content/public/browser/plugin_service.h" #endif diff --git a/shell/browser/browser_linux.cc b/shell/browser/browser_linux.cc index 13fb661b14..b61a4a4340 100644 --- a/shell/browser/browser_linux.cc +++ b/shell/browser/browser_linux.cc @@ -7,6 +7,10 @@ #include <fcntl.h> #include <stdlib.h> +#if BUILDFLAG(IS_LINUX) +#include <gtk/gtk.h> +#endif + #include "base/command_line.h" #include "base/environment.h" #include "base/process/launch.h" @@ -21,7 +25,6 @@ #if BUILDFLAG(IS_LINUX) #include "shell/browser/linux/unity_service.h" -#include "ui/gtk/gtk_util.h" // nogncheck #endif namespace electron { diff --git a/shell/browser/electron_browser_client.cc b/shell/browser/electron_browser_client.cc index 360e110d90..e657d0c8ff 100644 --- a/shell/browser/electron_browser_client.cc +++ b/shell/browser/electron_browser_client.cc @@ -31,7 +31,6 @@ #include "components/net_log/chrome_net_log.h" #include "components/network_hints/common/network_hints.mojom.h" #include "content/browser/keyboard_lock/keyboard_lock_service_impl.h" // nogncheck -#include "content/browser/site_instance_impl.h" // nogncheck #include "content/public/browser/browser_main_runner.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/client_certificate_delegate.h" diff --git a/shell/browser/extensions/electron_extensions_api_client.cc b/shell/browser/extensions/electron_extensions_api_client.cc index 1b24519e42..d2bb0c8879 100644 --- a/shell/browser/extensions/electron_extensions_api_client.cc +++ b/shell/browser/extensions/electron_extensions_api_client.cc @@ -22,10 +22,6 @@ #include "shell/browser/printing/print_view_manager_electron.h" #endif -#if BUILDFLAG(ENABLE_PDF_VIEWER) -#include "components/pdf/browser/pdf_document_helper.h" // nogncheck -#endif - namespace extensions { class ElectronGuestViewManagerDelegate diff --git a/shell/browser/notifications/linux/libnotify_notification.cc b/shell/browser/notifications/linux/libnotify_notification.cc index c931328924..231ba25485 100644 --- a/shell/browser/notifications/linux/libnotify_notification.cc +++ b/shell/browser/notifications/linux/libnotify_notification.cc @@ -17,7 +17,6 @@ #include "shell/common/application_info.h" #include "shell/common/platform_util.h" #include "third_party/skia/include/core/SkBitmap.h" -#include "ui/gtk/gtk_util.h" // nogncheck namespace electron { diff --git a/shell/browser/ui/file_dialog_linux.cc b/shell/browser/ui/file_dialog_linux.cc index 0185e0ca19..befbac20fe 100644 --- a/shell/browser/ui/file_dialog_linux.cc +++ b/shell/browser/ui/file_dialog_linux.cc @@ -17,8 +17,8 @@ #include "shell/common/gin_converters/file_path_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/gin_helper/promise.h" -#include "ui/gtk/select_file_dialog_linux_gtk.h" // nogncheck #include "ui/shell_dialogs/select_file_dialog.h" +#include "ui/shell_dialogs/select_file_policy.h" #include "ui/shell_dialogs/selected_file_info.h" namespace file_dialog { diff --git a/shell/common/application_info_linux.cc b/shell/common/application_info_linux.cc index f1f4e55ce0..d2cab19597 100644 --- a/shell/common/application_info_linux.cc +++ b/shell/common/application_info_linux.cc @@ -12,7 +12,6 @@ #include "base/logging.h" #include "electron/electron_version.h" #include "shell/common/platform_util.h" -#include "ui/gtk/gtk_util.h" // nogncheck namespace { diff --git a/shell/common/platform_util_linux.cc b/shell/common/platform_util_linux.cc index 820135237e..6bd80cc15b 100644 --- a/shell/common/platform_util_linux.cc +++ b/shell/common/platform_util_linux.cc @@ -33,7 +33,6 @@ #include "dbus/message.h" #include "dbus/object_proxy.h" #include "shell/common/platform_util_internal.h" -#include "ui/gtk/gtk_util.h" // nogncheck #include "url/gurl.h" #define ELECTRON_TRASH "ELECTRON_TRASH"
chore