From 7446696d3324bbeadb5489b9d22c75edfeedb401 Mon Sep 17 00:00:00 2001 From: ttsukagoshi Date: Tue, 6 Feb 2024 05:33:36 +0900 Subject: [PATCH 1/3] Update `trailingComma` from `es5` to `all` in .prettierrc to reflect the default setting in Prettier v3 resolve #126 --- .prettierrc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.prettierrc b/.prettierrc index c3ee367..522fc89 100644 --- a/.prettierrc +++ b/.prettierrc @@ -1,7 +1,7 @@ { "tabWidth": 2, "semi": true, - "trailingComma": "es5", + "trailingComma": "all", "singleQuote": true, "endOfLine": "lf" } From 96072a7fe69fad777ba37d2d1e7a23b9a5381f00 Mon Sep 17 00:00:00 2001 From: ttsukagoshi Date: Tue, 6 Feb 2024 05:33:55 +0900 Subject: [PATCH 2/3] Add `node_modules/` to .prettierignore --- .prettierignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.prettierignore b/.prettierignore index 6b1d0bf..7597ab8 100644 --- a/.prettierignore +++ b/.prettierignore @@ -1 +1,2 @@ LICENSE +node_modules/ From 9b19f4f300440c8fe38338342f585c0837dac5c7 Mon Sep 17 00:00:00 2001 From: ttsukagoshi Date: Tue, 6 Feb 2024 05:34:11 +0900 Subject: [PATCH 3/3] Re-format code based on Prettier v3 settings --- .github/workflows/codeql.yml | 30 ++++++------ __tests__/deepL.test.ts | 20 +++++--- __tests__/getDeepLApiBaseUrl.test.ts | 2 +- __tests__/handleDeepLErrors.test.ts | 2 +- __tests__/verifyAuthKeyPrompt.test.ts | 8 +-- src/sheetsl.ts | 70 +++++++++++++-------------- 6 files changed, 68 insertions(+), 64 deletions(-) diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index 630719a..eba8115 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -1,11 +1,11 @@ -name: "CodeQL" +name: 'CodeQL' on: push: - branches: [ "main" ] + branches: ['main'] pull_request: # The branches below must be a subset of the branches above - branches: [ "main" ] + branches: ['main'] jobs: analyze: @@ -19,19 +19,19 @@ jobs: strategy: fail-fast: false matrix: - language: [ 'javascript' ] + language: ['javascript'] steps: - - name: Checkout repository - uses: actions/checkout@v4 + - name: Checkout repository + uses: actions/checkout@v4 - # Initializes the CodeQL tools for scanning. - - name: Initialize CodeQL - uses: github/codeql-action/init@v3 - with: - languages: ${{ matrix.language }} + # Initializes the CodeQL tools for scanning. + - name: Initialize CodeQL + uses: github/codeql-action/init@v3 + with: + languages: ${{ matrix.language }} - - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@v3 - with: - category: "/language:${{matrix.language}}" + - name: Perform CodeQL Analysis + uses: github/codeql-action/analyze@v3 + with: + category: '/language:${{matrix.language}}' diff --git a/__tests__/deepL.test.ts b/__tests__/deepL.test.ts index 6b57ba6..d7ccd65 100644 --- a/__tests__/deepL.test.ts +++ b/__tests__/deepL.test.ts @@ -90,7 +90,7 @@ const deepLTranslatePatterns: DeepLTranslatePattern[] = [ }, expectedOutput: [ `${translateUrl}?auth_key=${mockApiKey}&target_lang=EN-US&text=${encodeURIComponent( - 'text to translate' + 'text to translate', )}&source_lang=JA`, ], }, @@ -107,9 +107,9 @@ const deepLTranslatePatterns: DeepLTranslatePattern[] = [ }, expectedOutput: [ `${translateUrl}?auth_key=${mockApiKey}&target_lang=EN-US&text=${encodeURIComponent( - 'text to translate 1' + 'text to translate 1', )}&text=${encodeURIComponent( - 'text to translate 2' + 'text to translate 2', )}&text=${encodeURIComponent('text to translate 3')}&source_lang=JA`, ], }, @@ -177,10 +177,14 @@ describe.each(deepLTranslatePatterns)( ({ title, input, expectedOutput }) => { test(`deepLTranslate test: ${title}`, () => { expect( - deepLTranslate(input.sourceText, input.sourceLocale, input.targetLocale) + deepLTranslate( + input.sourceText, + input.sourceLocale, + input.targetLocale, + ), ).toEqual(expectedOutput); }); - } + }, ); // Error patterns in deepLTranslate @@ -192,11 +196,11 @@ describe.each(deepLTranslatePatternsWithErrors)( deepLTranslate( input.sourceText, input.sourceLocale, - input.targetLocale + input.targetLocale, ); }).toThrowError(new Error(`[${ADDON_NAME}] Empty input.`)); }); - } + }, ); describe.each(deepLGetLanguagesPatterns)( @@ -205,5 +209,5 @@ describe.each(deepLGetLanguagesPatterns)( test(`deepLGetLanguages test: ${title}`, () => { expect(deepLGetLanguages(input)).toEqual(expectedOutput); }); - } + }, ); diff --git a/__tests__/getDeepLApiBaseUrl.test.ts b/__tests__/getDeepLApiBaseUrl.test.ts index 2a8b75f..43d7bb1 100644 --- a/__tests__/getDeepLApiBaseUrl.test.ts +++ b/__tests__/getDeepLApiBaseUrl.test.ts @@ -23,5 +23,5 @@ describe.each(patterns)( test(`getDeepLApiBaseUrl test: ${title}`, () => { expect(getDeepLApiBaseUrl(input)).toBe(expectedOutput); }); - } + }, ); diff --git a/__tests__/handleDeepLErrors.test.ts b/__tests__/handleDeepLErrors.test.ts index dd78f2e..fc4de09 100644 --- a/__tests__/handleDeepLErrors.test.ts +++ b/__tests__/handleDeepLErrors.test.ts @@ -66,5 +66,5 @@ describe.each(errorPatterns)( handleDeepLErrors(inputResponse); }).toThrowError(new Error(expectedErrorMessage)); }); - } + }, ); diff --git a/__tests__/verifyAuthKeyPrompt.test.ts b/__tests__/verifyAuthKeyPrompt.test.ts index dbbc441..fbd7642 100644 --- a/__tests__/verifyAuthKeyPrompt.test.ts +++ b/__tests__/verifyAuthKeyPrompt.test.ts @@ -77,15 +77,15 @@ describe.each(verifyAuthKeyPromptSuccessPatterns)( ({ testName, input, expectedOutput }) => { test(`${testName}: getSelectedButton`, () => { expect( - verifyAuthKeyPrompt(input.promptResponse, input.ui).getSelectedButton() + verifyAuthKeyPrompt(input.promptResponse, input.ui).getSelectedButton(), ).toBe(expectedOutput.getSelectedButton()); }); test(`${testName}: getResponseText`, () => { expect( - verifyAuthKeyPrompt(input.promptResponse, input.ui).getResponseText() + verifyAuthKeyPrompt(input.promptResponse, input.ui).getResponseText(), ).toBe(expectedOutput.getResponseText()); }); - } + }, ); describe.each(verifyAuthKeyPromptErrorPatterns)( @@ -96,5 +96,5 @@ describe.each(verifyAuthKeyPromptErrorPatterns)( verifyAuthKeyPrompt(input.promptResponse, input.ui); }).toThrowError(new Error(expectedErrorMessage)); }); - } + }, ); diff --git a/src/sheetsl.ts b/src/sheetsl.ts index ebe833d..cb3d37c 100644 --- a/src/sheetsl.ts +++ b/src/sheetsl.ts @@ -72,7 +72,7 @@ function onOpen(): void { .addItem('Set Auth Key', 'setDeeplAuthKey') .addItem('Delete Auth Key', 'deleteDeeplAuthKey') .addSeparator() - .addItem('Set Language', 'setLanguage') + .addItem('Set Language', 'setLanguage'), ) .addSeparator() .addItem('Translate', 'translateRange') @@ -94,15 +94,15 @@ export function setDeeplAuthKey(): void { try { const promptResponse = ui.prompt( 'Enter your DeepL API Authentication Key', - ui.ButtonSet.OK_CANCEL + ui.ButtonSet.OK_CANCEL, ); const apiKey = verifyAuthKeyPrompt(promptResponse, ui).getResponseText(); PropertiesService.getUserProperties().setProperty( UP_KEY_DEEPL_API_KEY, - apiKey + apiKey, ); ui.alert( - `[${ADDON_NAME}] Completed: Your DeepL API Authentication Key has been saved as a user property.` + `[${ADDON_NAME}] Completed: Your DeepL API Authentication Key has been saved as a user property.`, ); } catch (error) { console.error(error.stack); @@ -120,17 +120,17 @@ export function setDeeplAuthKey(): void { */ export function verifyAuthKeyPrompt( promptResponse: GoogleAppsScript.Base.PromptResponse, - ui: GoogleAppsScript.Base.Ui + ui: GoogleAppsScript.Base.Ui, ): GoogleAppsScript.Base.PromptResponse { if (promptResponse.getSelectedButton() !== ui.Button.OK) { throw new Error( - `[${ADDON_NAME}] Canceled: Setting of DeepL Authentication Key has been canceled.` + `[${ADDON_NAME}] Canceled: Setting of DeepL Authentication Key has been canceled.`, ); } const apiKey = promptResponse.getResponseText(); if (!apiKey || apiKey === '') { throw new Error( - `[${ADDON_NAME}] You must enter a valid DeepL API Authentication Key.` + `[${ADDON_NAME}] You must enter a valid DeepL API Authentication Key.`, ); } return promptResponse; @@ -144,7 +144,7 @@ export function deleteDeeplAuthKey(): void { try { PropertiesService.getUserProperties().deleteProperty(UP_KEY_DEEPL_API_KEY); ui.alert( - `[${ADDON_NAME}] Complete: DeepL API Authentication Key has been deleted from your user property.` + `[${ADDON_NAME}] Complete: DeepL API Authentication Key has been deleted from your user property.`, ); } catch (error) { console.error(error.stack); @@ -165,11 +165,11 @@ export function setLanguage(): void { // Ask user whether to proceed if a target language is already set const alertProceed = ui.alert( `There is an existing language setting:\n - Source Language: ${userProperties[UP_KEY_SOURCE_LOCALE]}\n - Target Language: ${userProperties[UP_KEY_TARGET_LOCALE]}\n\nDo you want to update these values?`, - ui.ButtonSet.YES_NO + ui.ButtonSet.YES_NO, ); if (alertProceed !== ui.Button.YES) { throw new Error( - `[${ADDON_NAME}] Canceled: Language setting has been canceled.` + `[${ADDON_NAME}] Canceled: Language setting has been canceled.`, ); } } @@ -182,14 +182,14 @@ export function setLanguage(): void { `In which language is the source text written? Enter the two-letter language code. Leave this value empty to use DeepL's language auto detection.\n\nAvailable values:\n${availableLocaleSource .map( (langObj: DeepLSupportedLanguages) => - `- ${langObj.language} (${langObj.name})` + `- ${langObj.language} (${langObj.name})`, ) .join('\n')}`, - ui.ButtonSet.OK_CANCEL + ui.ButtonSet.OK_CANCEL, ); if (promptSourceLocale.getSelectedButton() !== ui.Button.OK) { throw new Error( - `[${ADDON_NAME}] Canceled: Language setting has been canceled.` + `[${ADDON_NAME}] Canceled: Language setting has been canceled.`, ); } const responseSourceLocale = promptSourceLocale @@ -202,7 +202,7 @@ export function setLanguage(): void { responseSourceLocale != '' ) { throw new Error( - `[${ADDON_NAME}] Invalid Value (${responseSourceLocale}): Enter a valid value.` + `[${ADDON_NAME}] Invalid Value (${responseSourceLocale}): Enter a valid value.`, ); } // Target language @@ -210,14 +210,14 @@ export function setLanguage(): void { `Into which language should the text be translated? Enter the two- or four-letter language code.\n\nAvailable values:\n${availableLocaleTarget .map( (langObj: DeepLSupportedLanguages) => - `- ${langObj.language} (${langObj.name})` + `- ${langObj.language} (${langObj.name})`, ) .join('\n')}`, - ui.ButtonSet.OK_CANCEL + ui.ButtonSet.OK_CANCEL, ); if (promptTargetLocale.getSelectedButton() !== ui.Button.OK) { throw new Error( - `[${ADDON_NAME}] Canceled: Language setting has been canceled.` + `[${ADDON_NAME}] Canceled: Language setting has been canceled.`, ); } const responseTargetLocale = promptTargetLocale @@ -229,7 +229,7 @@ export function setLanguage(): void { .includes(responseTargetLocale) ) { throw new Error( - `[${ADDON_NAME}] Invalid Value (${responseTargetLocale}): Enter a valid value.` + `[${ADDON_NAME}] Invalid Value (${responseTargetLocale}): Enter a valid value.`, ); } // Set the values as user properties @@ -257,7 +257,7 @@ export function translateRange(): void { try { if (!userProperties[UP_KEY_TARGET_LOCALE]) { throw new Error( - `[${ADDON_NAME}] Target Language Unavailable: Set the target language in Settings > Set Language of the add-on menu.` + `[${ADDON_NAME}] Target Language Unavailable: Set the target language in Settings > Set Language of the add-on menu.`, ); } if (!selectedRange) { @@ -269,12 +269,12 @@ export function translateRange(): void { selectedRange.getRow(), selectedRange.getColumn() + selectedRangeNumCol, selectedRange.getNumRows(), - selectedRangeNumCol + selectedRangeNumCol, ); if (!targetRange.isBlank()) { const alertOverwrite = ui.alert( 'Translated text(s) will be pasted in the cell(s) to the right of the currently selected range. This target area is not empty.\nContinuing this process will overwrite the contents.\n\nAre you sure you want to continue?', - ui.ButtonSet.OK_CANCEL + ui.ButtonSet.OK_CANCEL, ); if (alertOverwrite !== ui.Button.OK) { throw new Error(`[${ADDON_NAME}] Translation canceled.`); @@ -295,10 +295,10 @@ export function translateRange(): void { const cellValueString = cellValue.toString(); const truncatedCellValue = cellValueString.slice( 0, - Math.floor((cellValueString.length * THRESHOLD_BYTES) / textBytes) + Math.floor((cellValueString.length * THRESHOLD_BYTES) / textBytes), ); throw new Error( - `[${ADDON_NAME}] Cell content length exceeds Google's limits. Please consider splitting the content into multiple cells. The following is the estimated maximum length of the cell in question:\n${truncatedCellValue}\n\nPlease note that this is a rough estimate and that the actual acceptable text length might differ slightly.` + `[${ADDON_NAME}] Cell content length exceeds Google's limits. Please consider splitting the content into multiple cells. The following is the estimated maximum length of the cell in question:\n${truncatedCellValue}\n\nPlease note that this is a rough estimate and that the actual acceptable text length might differ slightly.`, ); } else { Utilities.sleep(1000); // Interval to avoid concentrated access to API @@ -306,10 +306,10 @@ export function translateRange(): void { return deepLTranslate( cellValue.toString(), userProperties[UP_KEY_SOURCE_LOCALE], - userProperties[UP_KEY_TARGET_LOCALE] + userProperties[UP_KEY_TARGET_LOCALE], )[0]; } - }) + }), ); // console.log(`translatedText: ${JSON.stringify(translatedText)}`); @@ -334,7 +334,7 @@ export function translateRange(): void { export function deepLTranslate( sourceText: string | string[], sourceLocale: string | null | undefined, - targetLocale: string + targetLocale: string, ): string[] { const endpoint = 'translate'; let sourceTextCasted: string; @@ -370,11 +370,11 @@ export function deepLTranslate( handleDeepLErrors(response); const translatedTextObj: DeepLTranslationResponse = JSON.parse( - response.getContentText() + response.getContentText(), ); const translatedText: string[] = translatedTextObj.translations.map( (translationsResponse: DeepLTranslationObj): string => - translationsResponse.text + translationsResponse.text, ); // console.log(`translatedText: ${JSON.stringify(translatedText)}`); @@ -389,7 +389,7 @@ export function deepLTranslate( * @see https://www.deepl.com/docs-api/general/get-languages/ */ export function deepLGetLanguages( - type: DeepLLanguageType = 'source' + type: DeepLLanguageType = 'source', ): DeepLSupportedLanguages[] { const endpoint = 'languages'; // API key @@ -420,24 +420,24 @@ export function getBlobBytes(text: string): number { * @see https://www.deepl.com/docs-api/api-access/error-handling/ */ export function handleDeepLErrors( - response: GoogleAppsScript.URL_Fetch.HTTPResponse + response: GoogleAppsScript.URL_Fetch.HTTPResponse, ): void { const responseCode = response.getResponseCode(); if (responseCode === 429) { throw new Error( - `[${ADDON_NAME}] Too Many Requests: Try again after some time.` + `[${ADDON_NAME}] Too Many Requests: Try again after some time.`, ); } else if (responseCode === 456) { throw new Error( - `[${ADDON_NAME}] Quota Exceeded: The translation limit of your account has been reached.` + `[${ADDON_NAME}] Quota Exceeded: The translation limit of your account has been reached.`, ); } else if (responseCode >= 500) { throw new Error( - `[${ADDON_NAME}] Temporary errors in the DeepL service. Please retry after waiting for a while.` + `[${ADDON_NAME}] Temporary errors in the DeepL service. Please retry after waiting for a while.`, ); } else if (responseCode !== 200) { throw new Error( - `[${ADDON_NAME}] Error on Calling DeepL API: ${response.getContentText()}` + `[${ADDON_NAME}] Error on Calling DeepL API: ${response.getContentText()}`, ); } } @@ -452,7 +452,7 @@ export function getDeepLApiKey(): string { PropertiesService.getUserProperties().getProperty(UP_KEY_DEEPL_API_KEY); if (!apiKey) { throw new Error( - `[${ADDON_NAME}] API Key Unavailable: Set the DeepL API Authentication Key from the Settings > Set Auth Key of the add-on menu.` + `[${ADDON_NAME}] API Key Unavailable: Set the DeepL API Authentication Key from the Settings > Set Auth Key of the add-on menu.`, ); } else { return apiKey;