Skip to content

Commit

Permalink
refactor: logger is enabled if dev and debug mode
Browse files Browse the repository at this point in the history
  • Loading branch information
azu committed Apr 18, 2021
1 parent 58f08f5 commit a65599a
Show file tree
Hide file tree
Showing 11 changed files with 67 additions and 27 deletions.
3 changes: 1 addition & 2 deletions packages/webextension/app/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,13 +38,12 @@
],
"permissions": [
"activeTab",
"contextMenus",
"webRequest",
"webRequestBlocking",
"tabs",
"<all_urls>"
],
"applications": {
"__firefox__applications": {
"gecko": {
"id": "editor@textlint.github.com"
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { ActionGroup, Flex, Item, ListBox, Text } from "@adobe/react-spectrum";
import { usePort } from "../StateContext";
import { Script } from "../../background/database";
import FileCode from "@spectrum-icons/workflow/FileCode";
import { logger } from "../../utils/logger";

export type InstalledTextlintListProps = {
url: string;
Expand All @@ -18,7 +19,7 @@ export const InstalledTextlintList = (props: InstalledTextlintListProps) => {
items: res
};
} catch (error) {
console.error(error);
logger.error(error);
return {
items: []
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { usePort } from "../StateContext";
import { ScriptMeta } from "../component/ScriptMeta";
import "./EditPage.css";
import { Flex } from "@adobe/react-spectrum";
import { logger } from "../../utils/logger";

export type EditPageProps = {
name?: string;
Expand All @@ -21,7 +22,7 @@ export const EditPage = (props: EditPageProps) => {
const port = usePort();
const onSave = (textlintrc: string) => {
if (!props.name || !props.namespace) {
console.error("props is wrong", props);
logger.error("props is wrong", props);
return;
}
port.updateScript({
Expand All @@ -33,14 +34,13 @@ export const EditPage = (props: EditPageProps) => {
useEffect(() => {
(async function loadScript() {
if (!props.name || !props.namespace) {
console.error("props is wrong", props);
logger.error("props is wrong", props);
return;
}
const script = await port.findScriptsWithName({ name: props.name, namespace: props.namespace });
if (!script) {
return console.error("script is not found", props);
return logger.error("script is not found", props);
}
console.log();
setMeta({
name: script.name,
namespace: script.namespace,
Expand Down
19 changes: 10 additions & 9 deletions packages/webextension/app/scripts/background.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,10 @@ import { openDatabase } from "./background/database";
import { LintEngineAPI } from "textchecker-element";
import { TextlintResult } from "@textlint/types";
import { scriptWorkerSet } from "./background/scriptWorkerSet";
import { logger } from "./utils/logger";

// browser.runtime.onInstalled.addListener((details) => {
// // console.log("previousVersion", details.previousVersion);
// // logger.log("previousVersion", details.previousVersion);
// });
//
// browser.tabs.onUpdated.addListener(async (tabId) => {
Expand Down Expand Up @@ -50,7 +51,7 @@ async function openInstallDialog(url: string) {

browser.webRequest.onHeadersReceived.addListener(
(details) => {
if (details.method != "GET") return {};
if (details.method !== "GET") return {};
if (!responseHasUserScriptType(details.responseHeaders)) return {};
openInstallDialog(details.url);
// https://stackoverflow.com/a/18684302
Expand Down Expand Up @@ -79,7 +80,7 @@ browser.runtime.onConnect.addListener(async (port) => {
}
const db = await openDatabase();
const originUrl = port.sender?.url;
console.log("[background] originUrl", originUrl);
logger.log("originUrl", originUrl);
if (!originUrl) {
return;
}
Expand All @@ -101,7 +102,7 @@ browser.runtime.onConnect.addListener(async (port) => {
return Comlink.expose(exports, createBackgroundEndpoint(port));
}
const scripts = await db.findScriptsWithPatten(originUrl);
console.log("scripts", scripts);
logger.log("scripts", scripts);
const scriptWorkers = scripts.map((script) => {
const runningWorker = scriptWorkerSet.get(script);
if (runningWorker) {
Expand All @@ -118,17 +119,17 @@ browser.runtime.onConnect.addListener(async (port) => {
ext: script.ext
};
});
console.log("[Background] workers started", scriptWorkers);
logger.log("workers started", scriptWorkers);
// Support multiple workers
const lintEngine: LintEngineAPI = {
async lintText({ text }: { text: string }): Promise<TextlintResult[]> {
console.log("[Background] text:", text);
logger.log("text:", text);
const allLintResults = await Promise.all(
scriptWorkers.map(({ worker, ext }) => {
return worker.createLintEngine({ ext }).lintText({ text });
})
);
console.log("[Background] lintText", allLintResults);
logger.log("lintText", allLintResults);
return allLintResults.flat();
},
async fixText({ text }): Promise<{ output: string }> {
Expand Down Expand Up @@ -157,13 +158,13 @@ browser.runtime.onConnect.addListener(async (port) => {
}
};
port.onDisconnect.addListener(async () => {
console.log("[Background] dispose worker");
logger.log("dispose worker");
const scripts = await db.findScriptsWithPatten(originUrl);
scripts.forEach((script) => {
scriptWorkerSet.delete({ script: script, url: originUrl });
});
});
console.log("[Background] content port", port);
logger.log("content port", port);
scriptWorkerSet.dump();
Comlink.expose(backgroundExposedObject, createBackgroundEndpoint(port));
await Promise.all(scriptWorkers.map(({ worker }) => worker.ready()));
Expand Down
4 changes: 4 additions & 0 deletions packages/webextension/app/scripts/background/database.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@ export type Script = {
export type TextlintDBSchema = {
scripts: Script[];
};
/**
* Create unique key of Script
* @param script
*/
export const keyOfScript = (script: { name: string; namespace: string }): string => {
return `${script.namespace}@${script.name}`;
};
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { TextlintWorker } from "./textlint";
import { keyOfScript, Script } from "./database";
import { logger } from "../utils/logger";

// worker: Set<url>
const _workerRunningUrlMap = new Map<TextlintWorker, Set<string>>();
Expand Down Expand Up @@ -30,7 +31,7 @@ export const scriptWorkerSet = {
return _scriptRunningWorkerMap.delete(keyOfScript(script));
},
dump() {
console.log("Running Scripts: ", _scriptRunningWorkerMap.keys());
console.log("Running Workers x URLs: ", _workerRunningUrlMap.entries());
logger.log("Running Scripts: ", _scriptRunningWorkerMap.keys());
logger.log("Running Workers x URLs: ", _workerRunningUrlMap.entries());
}
};
4 changes: 3 additions & 1 deletion packages/webextension/app/scripts/background/textlint.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import {
} from "@textlint/script-compiler";
import type { TextlintRcConfig } from "@textlint/config-loader";
import { Script } from "./database";
import { logger } from "../utils/logger";

const waiterForInit = (worker: Worker) => {
let initialized = false;
let _resolve: null | ((init: boolean) => void) = null;
Expand Down Expand Up @@ -118,7 +120,7 @@ export const createTextlintWorker = (script: Script) => {
});
};
const log = (...args: any[]) => {
console.log("[Background]", ...args);
logger.log(...args);
};
return {
createLintEngine({ ext }: { ext: string }) {
Expand Down
5 changes: 3 additions & 2 deletions packages/webextension/app/scripts/contentScript.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,22 @@ import { createEndpoint } from "comlink-extension";
import * as Comlink from "comlink";
import type { backgroundExposedObject } from "./background";
import { nonRandomKey } from "./shared/page-contents-shared";
import { logger } from "./utils/logger";

const rawPort = browser.runtime.connect();
// content-script <-> background page
const port = Comlink.wrap<backgroundExposedObject>(createEndpoint(rawPort));
rawPort.onMessage.addListener((event) => {
if (event === "textlint-editor-boot") {
console.log("[ContentScript]", "boot event received");
logger.log("[ContentScript]", "boot event received");
// Inject page-script
try {
const script = browser.extension.getURL("scripts/pageScript.js");
const pageScript = document.createElement("script");
pageScript.src = script;
document.body.append(pageScript);
} catch (error) {
console.error(error);
logger.error(error);
}
}
});
Expand Down
3 changes: 2 additions & 1 deletion packages/webextension/app/scripts/install-dialog.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import * as Comlink from "comlink";
import type { backgroundExposedObject } from "./background";
import { browser } from "webextension-polyfill-ts";
import { parseMetadata, TextlintScriptMetadata } from "@textlint/script-parser";
import { logger } from "./utils/logger";

const port = Comlink.wrap<backgroundExposedObject>(createEndpoint(browser.runtime.connect()));

Expand All @@ -29,7 +30,7 @@ async function installHandler({
textlintrc: JSON.stringify(metadata.config, null, 4)
});
} catch (error) {
console.error("[InstallDialog]", error);
logger.error("[InstallDialog]", error);
}
}

Expand Down
11 changes: 6 additions & 5 deletions packages/webextension/app/scripts/pageScript.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@ import { attachToTextArea, LintEngineAPI } from "textchecker-element";
import { nonRandomKey } from "./shared/page-contents-shared";
import type { TextlintMessage } from "@textlint/types";
import { applyFixesToText } from "@textlint/source-code-fixer";
import { logger } from "./utils/logger";

const commandHandler = <R>(command: string, args: any): Promise<R> => {
return new Promise<R>((resolve) => {
console.log("[PageScript]", command, args);
logger.log("[PageScript]", command, args);
const listener = (message: MessageEvent) => {
if (
message.data &&
Expand Down Expand Up @@ -45,7 +46,7 @@ const isIgnored = ({ text, message }: { text: string; message: TextlintMessage }
const lintEngine: LintEngineAPI = {
async lintText({ text }) {
const results = await commandHandler<ReturnType<LintEngineAPI["lintText"]>>("lintText", { text });
console.log("results", results);
logger.log("results", results);
return results.map((result) => {
return {
filePath: result.filePath,
Expand Down Expand Up @@ -78,7 +79,7 @@ async function contentScriptMain() {
if (set.has(textAreaElement)) {
return;
}
console.log("[contentScript] attach textarea", textAreaElement);
logger.log("[contentScript] attach textarea", textAreaElement);
attachToTextArea({
textAreaElement: textAreaElement,
lintingDebounceMs: 200,
Expand Down Expand Up @@ -106,7 +107,7 @@ async function contentScriptMain() {
});
}

console.log("[PageScript]", "main loaded");
logger.log("[PageScript]", "main loaded");
contentScriptMain().catch((error) => {
console.error("[PageScript] Error", error);
logger.error("[PageScript] Error", error);
});
29 changes: 29 additions & 0 deletions packages/webextension/app/scripts/utils/logger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// contentScript does not loggin in production by default
const canLog = () => {
// localStorage.setItem("DEBUG", "@textlint/editor");
const enabledDebugStorage =
typeof window !== "undefined" &&
typeof window.localStorage !== "undefined" &&
(window.localStorage.getItem("DEBUG")?.includes("@textlint") || window.localStorage.getItem("DEBUG") === "*");
// ?debug_textlint
const enabledDebugLocation =
typeof window !== "undefined" &&
typeof window.location !== "undefined" &&
new URL(window.location.href).searchParams.has("debug_textlint");

return process.env.NODE_ENV === "development" || enabledDebugLocation || enabledDebugStorage;
};
export const logger = {
log(...args: any[]) {
if (!canLog()) {
return;
}
console.log("[@textlint/editor]", ...args);
},
error(...args: any[]) {
if (!canLog()) {
return;
}
console.error("[@textlint/editor]", ...args);
}
};

0 comments on commit a65599a

Please sign in to comment.