Skip to content

Commit

Permalink
#6132: refactor the utils/helpers/chrome top-level files (#6189)
Browse files Browse the repository at this point in the history
  • Loading branch information
twschiller authored Jul 31, 2023
1 parent c67fa2b commit 2160f05
Show file tree
Hide file tree
Showing 309 changed files with 2,345 additions and 1,911 deletions.
10 changes: 5 additions & 5 deletions src/activation/useActivateRecipeWizard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,10 @@ import { useSelector } from "react-redux";
import { selectExtensions } from "@/store/extensionsSelectors";
import type React from "react";
import { isEmpty, mapValues, uniq } from "lodash";
import { PIXIEBRIX_SERVICE_ID } from "@/services/constants";
import { isPrimitive } from "@/utils";
import { PIXIEBRIX_INTEGRATION_ID } from "@/services/constants";
import OptionsBody from "@/extensionConsole/pages/activateRecipe/OptionsBody";
import ServicesBody from "@/extensionConsole/pages/activateRecipe/ServicesBody";
import PermissionsBody from "@/extensionConsole/pages/activateRecipe/PermissionsBody";
import { inputProperties } from "@/helpers";
import * as Yup from "yup";
import { type AnyObjectSchema } from "yup";
import useAsyncRecipeOptionsValidationSchema from "@/hooks/useAsyncRecipeOptionsValidationSchema";
Expand All @@ -41,6 +39,8 @@ import useMergeAsyncState from "@/hooks/useMergeAsyncState";
import { type Option } from "@/components/form/widgets/SelectWidget";
import { type FetchableAsyncState } from "@/types/sliceTypes";
import { type UnresolvedModComponent } from "@/types/modComponentTypes";
import { isPrimitive } from "@/utils/typeUtils";
import { inputProperties } from "@/utils/schemaUtils";

const STEPS: WizardStep[] = [
// OptionsBody takes only a slice of the ModDefinition, however the types aren't set up in a way for TypeScript
Expand Down Expand Up @@ -106,7 +106,7 @@ export function wizardStateFactory({
switch (step.key) {
case "services": {
return serviceIds.some(
(serviceId) => serviceId !== PIXIEBRIX_SERVICE_ID
(serviceId) => serviceId !== PIXIEBRIX_INTEGRATION_ID
);
}

Expand Down Expand Up @@ -169,7 +169,7 @@ export function wizardStateFactory({
Yup.object().test(
"servicesRequired",
"Please select a configuration",
(value) => value.id === PIXIEBRIX_SERVICE_ID || value.config != null
(value) => value.id === PIXIEBRIX_INTEGRATION_ID || value.config != null
)
),
optionsArgs: optionsValidationSchema,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,9 @@ import {
type AnalysisAnnotation,
} from "@/analysis/analysisTypes";
import { type ModComponentFormState } from "@/pageEditor/starterBricks/formStateTypes";
import { joinPathParts } from "@/utils";
import { get, isEmpty } from "lodash";
import { AnnotationType } from "@/types/annotationTypes";
import { joinPathParts } from "@/utils/formUtils";

// See URL patterns at https://developer.chrome.com/docs/extensions/mv3/match_patterns/
const urlRegexp = /^(?<scheme>.*):\/\/(?<host>[^/]*)?(?<path>.*)?$/;
Expand Down
2 changes: 1 addition & 1 deletion src/analysis/analysisVisitors/httpRequestAnalysis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,12 @@
import { AnalysisVisitorABC } from "./baseAnalysisVisitors";
import { type BrickConfig, type BrickPosition } from "@/bricks/types";
import { type VisitBlockExtra } from "@/bricks/PipelineVisitor";
import { joinPathParts } from "@/utils";
import { AnnotationType } from "@/types/annotationTypes";
import { castTextLiteralOrThrow } from "@/utils/expressionUtils";
import { RemoteMethod } from "@/bricks/transformers/remoteMethod";
import { isEmpty } from "lodash";
import { type JsonObject } from "type-fest";
import { joinPathParts } from "@/utils/formUtils";

function tryParse(value: unknown): JsonObject | null {
if (typeof value === "string") {
Expand Down
2 changes: 1 addition & 1 deletion src/analysis/analysisVisitors/regexAnalysis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,12 @@ import { type BrickConfig, type BrickPosition } from "@/bricks/types";
import { type VisitBlockExtra } from "@/bricks/PipelineVisitor";
import { validateRegistryId } from "@/types/helpers";
import { getErrorMessage } from "@/errors/errorHelpers";
import { joinPathParts } from "@/utils";
import { AnnotationType } from "@/types/annotationTypes";
import {
containsTemplateExpression,
isTemplateExpression,
} from "@/utils/expressionUtils";
import { joinPathParts } from "@/utils/formUtils";

/**
* Returns the regex literal pattern, or null if the regex is a variable or template expression
Expand Down
2 changes: 1 addition & 1 deletion src/analysis/analysisVisitors/requestPermissionAnalysis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,12 @@ import { type BrickConfig, type BrickPosition } from "@/bricks/types";
import { type ModComponentFormState } from "@/pageEditor/starterBricks/formStateTypes";
import { isTemplateString } from "@/pageEditor/starterBricks/upgrade";
import { AnalysisVisitorABC } from "./baseAnalysisVisitors";
import { isAbsoluteUrl } from "@/utils";
import { getErrorMessage } from "@/errors/errorHelpers";
import { AnnotationType } from "@/types/annotationTypes";
import { AnalysisAnnotationActionType } from "@/analysis/analysisTypes";
import { ensurePermissionsFromUserGesture } from "@/permissions/permissionsUtils";
import { isTemplateExpression, isVarExpression } from "@/utils/expressionUtils";
import { isAbsoluteUrl } from "@/utils/urlUtils";

/**
* Checks permission for RemoteMethod and GetAPITransformer bricks to make a remote call
Expand Down
2 changes: 1 addition & 1 deletion src/analysis/analysisVisitors/varAnalysis/varAnalysis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@ import { type TraceRecord } from "@/telemetry/trace";
import parseTemplateVariables from "./parseTemplateVariables";
import recipesRegistry from "@/modDefinitions/registry";
import blockRegistry, { type TypedBlockMap } from "@/bricks/registry";
import { joinPathParts } from "@/utils";
import { type ListDocumentElement } from "@/components/documentBuilder/documentBuilderTypes";
import { ADAPTERS } from "@/pageEditor/starterBricks/adapter";
import { fromJS } from "@/starterBricks/factory";
Expand All @@ -52,6 +51,7 @@ import {
} from "@/utils/expressionUtils";
import { type UnknownObject } from "@/types/objectTypes";
import { MOD_VARIABLE_REFERENCE } from "@/runtime/extendModVariableContext";
import { joinPathParts } from "@/utils/formUtils";

export const INVALID_VARIABLE_GENERIC_MESSAGE = "Invalid variable name";

Expand Down
8 changes: 6 additions & 2 deletions src/auth/token.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
*/

import Cookies from "js-cookie";
import { type ManualStorageKey, readStorage, setStorage } from "@/chrome";
import {
type PartnerAuthData,
type TokenAuthData,
Expand All @@ -28,7 +27,12 @@ import { isExtensionContext } from "webext-detect-page";
import { expectContext } from "@/utils/expectContext";
import { isEmpty, omit, remove } from "lodash";
import { type UnknownObject } from "@/types/objectTypes";
import { syncRemotePackages } from "@/baseRegistry";
import { syncRemotePackages } from "@/registry/memoryRegistry";
import {
type ManualStorageKey,
readStorage,
setStorage,
} from "@/utils/storageUtils";

// `chrome.storage.local` keys
const STORAGE_EXTENSION_KEY = "extensionKey" as ManualStorageKey;
Expand Down
6 changes: 3 additions & 3 deletions src/auth/useRequiredPartnerAuth.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ import { type AuthState } from "@/auth/authTypes";
import settingsSlice from "@/store/settingsSlice";
import { type SettingsState } from "@/store/settingsTypes";

import { CONTROL_ROOM_OAUTH_SERVICE_ID } from "@/services/constants";
import { CONTROL_ROOM_OAUTH_INTEGRATION_ID } from "@/services/constants";
import { type Me } from "@/types/contract";
import useManagedStorageState from "@/store/enterprise/useManagedStorageState";
import { type IntegrationConfig } from "@/types/integrationTypes";
Expand Down Expand Up @@ -127,7 +127,7 @@ describe("useRequiredPartnerAuth", () => {
services: servicesSlice.getInitialState(),
settings: {
...settingsSlice.getInitialState(),
authServiceId: CONTROL_ROOM_OAUTH_SERVICE_ID,
authServiceId: CONTROL_ROOM_OAUTH_INTEGRATION_ID,
authMethod: "partner-oauth2",
},
});
Expand Down Expand Up @@ -294,7 +294,7 @@ describe("useRequiredPartnerAuth", () => {
...servicesSlice.getInitialState(),
configured: {
[uuidv4()]: {
serviceId: CONTROL_ROOM_OAUTH_SERVICE_ID,
serviceId: CONTROL_ROOM_OAUTH_INTEGRATION_ID,
} as IntegrationConfig,
},
},
Expand Down
13 changes: 8 additions & 5 deletions src/auth/useRequiredPartnerAuth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,8 @@ import {
import { useEffect } from "react";
import {
AUTOMATION_ANYWHERE_PARTNER_KEY,
CONTROL_ROOM_OAUTH_SERVICE_ID,
CONTROL_ROOM_TOKEN_SERVICE_ID,
CONTROL_ROOM_OAUTH_INTEGRATION_ID,
CONTROL_ROOM_TOKEN_INTEGRATION_ID,
} from "@/services/constants";
import { type AuthState } from "@/auth/authTypes";
import { type SettingsState } from "@/store/settingsTypes";
Expand All @@ -43,7 +43,10 @@ import { type RegistryId } from "@/types/registryTypes";
const PARTNER_MAP = new Map<string, Set<RegistryId>>([
[
AUTOMATION_ANYWHERE_PARTNER_KEY,
new Set([CONTROL_ROOM_TOKEN_SERVICE_ID, CONTROL_ROOM_OAUTH_SERVICE_ID]),
new Set([
CONTROL_ROOM_TOKEN_INTEGRATION_ID,
CONTROL_ROOM_OAUTH_INTEGRATION_ID,
]),
],
]);

Expand Down Expand Up @@ -98,11 +101,11 @@ function decidePartnerServiceIds({
}

if (authMethodOverride === "partner-oauth2") {
return new Set<RegistryId>([CONTROL_ROOM_OAUTH_SERVICE_ID]);
return new Set<RegistryId>([CONTROL_ROOM_OAUTH_INTEGRATION_ID]);
}

if (authMethodOverride === "partner-token") {
return new Set<RegistryId>([CONTROL_ROOM_TOKEN_SERVICE_ID]);
return new Set<RegistryId>([CONTROL_ROOM_TOKEN_INTEGRATION_ID]);
}

return PARTNER_MAP.get(partnerId) ?? new Set();
Expand Down
8 changes: 6 additions & 2 deletions src/background/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
*/

import axios, { type AxiosResponse } from "axios";
import { type ManualStorageKey, readStorage, setStorage } from "@/chrome";
import {
computeChallenge,
generateVerifier,
Expand All @@ -25,7 +24,6 @@ import {
import { getErrorMessage } from "@/errors/errorHelpers";
import { expectContext } from "@/utils/expectContext";
import { BusinessError } from "@/errors/businessErrors";
import { memoizeUntilSettled } from "@/utils";
import { type UUID } from "@/types/stringTypes";
import {
type AuthData,
Expand All @@ -34,6 +32,12 @@ import {
type IntegrationConfig,
} from "@/types/integrationTypes";
import { type UnknownObject } from "@/types/objectTypes";
import { memoizeUntilSettled } from "@/utils/promiseUtils";
import {
type ManualStorageKey,
readStorage,
setStorage,
} from "@/utils/storageUtils";

const OAUTH2_STORAGE_KEY = "OAUTH2" as ManualStorageKey;

Expand Down
3 changes: 2 additions & 1 deletion src/background/browserAction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,11 @@
import { ensureContentScript } from "@/background/contentScript";
import { rehydrateSidebar } from "@/contentScript/messenger/api";
import webextAlert from "./webextAlert";
import { memoizeUntilSettled, isMac } from "@/utils";
import { notify } from "@/extensionConsole/messenger/api";
import { browserAction, type Tab } from "@/mv3/api";
import { isScriptableUrl } from "@/permissions/permissionsUtils";
import { memoizeUntilSettled } from "@/utils/promiseUtils";
import { isMac } from "@/utils/browserUtils";

const ERR_UNABLE_TO_OPEN =
"PixieBrix was unable to open the Sidebar. Try refreshing the page.";
Expand Down
2 changes: 1 addition & 1 deletion src/background/contentScript.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,9 @@ import {
ENSURE_CONTENT_SCRIPT_READY,
getTargetState,
} from "@/contentScript/ready";
import { memoizeUntilSettled } from "@/utils";
import { Runtime } from "webextension-polyfill";
import MessageSender = Runtime.MessageSender;
import { memoizeUntilSettled } from "@/utils/promiseUtils";

const debug = console.debug.bind(console, "ensureContentScript:");

Expand Down
2 changes: 1 addition & 1 deletion src/background/contextMenus.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,12 @@ import {
} from "@/starterBricks/contextMenu";
import { loadOptions } from "@/store/extensionsStorage";
import { resolveExtensionInnerDefinitions } from "@/registry/internal";
import { allSettledValues, memoizeUntilSettled } from "@/utils";
import { type UUID } from "@/types/stringTypes";
import {
type ModComponentBase,
type ResolvedModComponent,
} from "@/types/modComponentTypes";
import { allSettledValues, memoizeUntilSettled } from "@/utils/promiseUtils";

const MENU_PREFIX = "pixiebrix-";

Expand Down
6 changes: 5 additions & 1 deletion src/background/dataStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,12 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

import { type ManualStorageKey, readStorage, setStorage } from "@/chrome";
import { type JsonObject } from "type-fest";
import {
type ManualStorageKey,
readStorage,
setStorage,
} from "@/utils/storageUtils";

const LOCAL_DATA_STORE = "LOCAL_DATA_STORE" as ManualStorageKey;
const KEY_PREFIX = "@@";
Expand Down
3 changes: 2 additions & 1 deletion src/background/deploymentUpdater.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ import { type Deployment, type Me } from "@/types/contract";
import { isEmpty, partition } from "lodash";
import reportError from "@/telemetry/reportError";
import { getUID } from "@/background/messenger/api";
import { getExtensionVersion } from "@/chrome";
import { isLinked, readAuthData, updateUserData } from "@/auth/token";
import reportEvent from "@/telemetry/reportEvent";
import { refreshRegistries } from "@/hooks/useRefreshRegistries";
Expand Down Expand Up @@ -62,6 +61,8 @@ import { type OptionsArgs } from "@/types/runtimeTypes";
import { checkDeploymentPermissions } from "@/permissions/deploymentPermissionsHelpers";
import { Events } from "@/telemetry/events";

import { getExtensionVersion } from "@/utils/extensionUtils";

const { reducer: optionsReducer, actions: optionsActions } = extensionsSlice;
const { reducer: editorReducer, actions: editorActions } = editorSlice;
const locateAllForService = locator.locateAllForService.bind(locator);
Expand Down
33 changes: 33 additions & 0 deletions src/background/eventUtils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/*
* Copyright (C) 2023 PixieBrix, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

import { expectContext } from "@/utils/expectContext";

export async function onTabClose(watchedTabId: number): Promise<void> {
expectContext("background");

await new Promise<void>((resolve) => {
const listener = (closedTabId: number) => {
if (closedTabId === watchedTabId) {
resolve();
browser.tabs.onRemoved.removeListener(listener);
}
};

browser.tabs.onRemoved.addListener(listener);
});
}
2 changes: 1 addition & 1 deletion src/background/executor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@

import { type Tabs } from "webextension-polyfill";
import { expectContext } from "@/utils/expectContext";
import { asyncForEach } from "@/utils";
import {
errorTabDoesntExist,
errorTargetClosedEarly,
Expand All @@ -31,6 +30,7 @@ import type { RunBlock } from "@/contentScript/runBlockTypes";
import { BusinessError } from "@/errors/businessErrors";
import { canAccessTab } from "@/permissions/permissionsUtils";
import { SessionMap } from "@/mv3/SessionStorage";
import { asyncForEach } from "@/utils/promiseUtils";

type TabId = number;

Expand Down
3 changes: 2 additions & 1 deletion src/background/externalProtocol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
*/

import { uuidv4 } from "@/types/helpers";
import { getChromeExtensionId, RuntimeNotFoundError } from "@/chrome";
import { type Runtime } from "webextension-polyfill";
import { patternToRegex } from "webext-patterns";
import chromeP from "webext-polyfill-kinda";
Expand All @@ -32,6 +31,8 @@ import {
isErrorResponse,
type RemoteProcedureCallRequest,
} from "@/pageScript/messenger/pigeon";
import { RuntimeNotFoundError } from "@/utils/extensionUtils";
import { getChromeExtensionId } from "@/store/browserExtensionIdStorage";

type ChromeMessageSender = chrome.runtime.MessageSender;

Expand Down
11 changes: 4 additions & 7 deletions src/background/installer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,7 @@ import { AUTOMATION_ANYWHERE_SERVICE_ID } from "@/contrib/automationanywhere/con
import { readManagedStorage } from "@/store/enterprise/managedStorage";
import { Events } from "@/telemetry/events";

const UNINSTALL_URL = "https://www.pixiebrix.com/uninstall/";

// eslint-disable-next-line prefer-destructuring -- It breaks EnvironmentPlugin
const SERVICE_URL = process.env.SERVICE_URL;
import { DEFAULT_SERVICE_URL, UNINSTALL_URL } from "@/urlConstants";

/**
* The latest version of PixieBrix available in the Chrome Web Store, or null if the version hasn't been fetched.
Expand All @@ -56,8 +53,8 @@ export async function openInstallPage() {
// Can't use SERVICE_URL directly because it contains a port number during development, resulting in an
// invalid URL match pattern
url: [
new URL("setup", SERVICE_URL).href,
`${new URL("start", SERVICE_URL).href}?*`,
new URL("setup", DEFAULT_SERVICE_URL).href,
`${new URL("start", DEFAULT_SERVICE_URL).href}?*`,
],
}),
]);
Expand Down Expand Up @@ -167,7 +164,7 @@ export async function requirePartnerAuth(): Promise<void> {
const [adminConsoleTab] = await browser.tabs.query({
// Can't use SERVICE_URL directly because it contains a port number during development, resulting in an
// invalid URL match pattern
url: [new URL(SERVICE_URL).href],
url: [new URL(DEFAULT_SERVICE_URL).href],
});

if (adminConsoleTab) {
Expand Down
Loading

0 comments on commit 2160f05

Please sign in to comment.