Просмотр исходного кода

Merge branch 'master' into imprv/171534-improve-knowledge-assistant-chat-ui

satof3 6 месяцев назад
Родитель
Сommit
ad1ac3d869
81 измененных файлов с 1180 добавлено и 835 удалено
  1. 7 0
      apps/app/.eslintrc.js
  2. 40 40
      apps/app/public/images/icons/favicon/manifest.json
  3. 1 1
      apps/app/public/static/locales/en_US/admin.json
  4. 1 1
      apps/app/public/static/locales/en_US/translation.json
  5. 1 1
      apps/app/public/static/locales/fr_FR/admin.json
  6. 1 1
      apps/app/public/static/locales/fr_FR/translation.json
  7. 1 1
      apps/app/public/static/locales/ja_JP/admin.json
  8. 1 1
      apps/app/public/static/locales/ja_JP/translation.json
  9. 1 1
      apps/app/public/static/locales/ko_KR/admin.json
  10. 1 1
      apps/app/public/static/locales/ko_KR/translation.json
  11. 1 1
      apps/app/public/static/locales/zh_CN/admin.json
  12. 1 1
      apps/app/public/static/locales/zh_CN/translation.json
  13. 3 0
      apps/app/src/client/components/PageEditor/PageEditor.tsx
  14. 2 0
      apps/app/src/client/services/side-effects/drawio-modal-launcher-for-view.ts
  15. 2 0
      apps/app/src/client/services/side-effects/handsontable-modal-launcher-for-view.ts
  16. 18 23
      apps/app/src/features/growi-plugin/client/components/Admin/PluginsExtensionPageContents/PluginCard.tsx
  17. 22 14
      apps/app/src/features/growi-plugin/client/components/Admin/PluginsExtensionPageContents/PluginDeleteModal.tsx
  18. 49 33
      apps/app/src/features/growi-plugin/client/components/Admin/PluginsExtensionPageContents/PluginInstallerForm.tsx
  19. 38 28
      apps/app/src/features/growi-plugin/client/components/Admin/PluginsExtensionPageContents/PluginsExtensionPageContents.tsx
  20. 11 8
      apps/app/src/features/growi-plugin/client/components/GrowiPluginsActivator.tsx
  21. 30 26
      apps/app/src/features/growi-plugin/client/stores/admin-plugins.tsx
  22. 1 5
      apps/app/src/features/growi-plugin/client/utils/growi-facade-utils.ts
  23. 30 25
      apps/app/src/features/growi-plugin/interfaces/growi-plugin.ts
  24. 19 18
      apps/app/src/features/growi-plugin/server/models/growi-plugin.integ.ts
  25. 45 20
      apps/app/src/features/growi-plugin/server/models/growi-plugin.ts
  26. 11 9
      apps/app/src/features/growi-plugin/server/models/vo/github-url.spec.ts
  27. 13 10
      apps/app/src/features/growi-plugin/server/models/vo/github-url.ts
  28. 62 36
      apps/app/src/features/growi-plugin/server/routes/apiv3/admin/index.ts
  29. 11 3
      apps/app/src/features/growi-plugin/server/services/growi-plugin/generate-template-plugin-meta.ts
  30. 4 1
      apps/app/src/features/growi-plugin/server/services/growi-plugin/generate-theme-plugin-meta.ts
  31. 42 25
      apps/app/src/features/growi-plugin/server/services/growi-plugin/growi-plugin.integ.ts
  32. 190 123
      apps/app/src/features/growi-plugin/server/services/growi-plugin/growi-plugin.ts
  33. 14 12
      apps/app/src/features/rate-limiter/config/index.ts
  34. 10 8
      apps/app/src/features/rate-limiter/middleware/consume-points.integ.ts
  35. 15 5
      apps/app/src/features/rate-limiter/middleware/consume-points.ts
  36. 26 22
      apps/app/src/features/rate-limiter/middleware/factory.ts
  37. 4 3
      apps/app/src/features/rate-limiter/middleware/rate-limiter-factory.ts
  38. 30 17
      apps/app/src/features/rate-limiter/utils/config-generator.ts
  39. 5 3
      apps/app/src/models/admin/growi-archive-import-option.ts
  40. 1 1
      apps/app/src/models/admin/import-mode.ts
  41. 8 4
      apps/app/src/models/admin/import-option-for-pages.ts
  42. 5 3
      apps/app/src/models/admin/import-option-for-revisions.ts
  43. 0 2
      apps/app/src/models/cdn-resource.js
  44. 0 4
      apps/app/src/models/linked-page-path.js
  45. 8 4
      apps/app/src/models/serializers/in-app-notification-snapshot/page-bulk-export-job.ts
  46. 2 2
      apps/app/src/models/serializers/in-app-notification-snapshot/page.ts
  47. 1 1
      apps/app/src/models/serializers/in-app-notification-snapshot/user.ts
  48. 0 2
      apps/app/src/models/vo/external-account-login-error.ts
  49. 7 5
      apps/app/src/pages/[[...path]].page.tsx
  50. 3 0
      apps/app/src/server/routes/apiv3/page/update-page.ts
  51. 1 1
      apps/app/src/server/service/customize.ts
  52. 7 2
      apps/app/src/server/service/page/index.ts
  53. 3 3
      apps/app/src/services/general-xss-filter/general-xss-filter.spec.ts
  54. 4 5
      apps/app/src/services/general-xss-filter/general-xss-filter.ts
  55. 6 2
      apps/app/src/services/layout/use-should-expand-content.ts
  56. 6 5
      apps/app/src/services/renderer/markdown-it/PreProcessor/EasyGrid.js
  57. 13 6
      apps/app/src/services/renderer/recommended-whitelist.spec.ts
  58. 31 20
      apps/app/src/services/renderer/recommended-whitelist.ts
  59. 6 3
      apps/app/src/services/renderer/rehype-plugins/add-class.ts
  60. 4 1
      apps/app/src/services/renderer/rehype-plugins/add-inline-code-property.ts
  61. 4 2
      apps/app/src/services/renderer/rehype-plugins/add-line-number-attribute.ts
  62. 21 11
      apps/app/src/services/renderer/rehype-plugins/keyword-highlighter.ts
  63. 45 39
      apps/app/src/services/renderer/rehype-plugins/relative-links-by-pukiwiki-like-linker.spec.ts
  64. 6 2
      apps/app/src/services/renderer/rehype-plugins/relative-links-by-pukiwiki-like-linker.ts
  65. 31 33
      apps/app/src/services/renderer/rehype-plugins/relative-links.spec.ts
  66. 14 8
      apps/app/src/services/renderer/rehype-plugins/relative-links.ts
  67. 8 7
      apps/app/src/services/renderer/rehype-plugins/relocate-toc.ts
  68. 10 6
      apps/app/src/services/renderer/remark-plugins/attachment.ts
  69. 4 2
      apps/app/src/services/renderer/remark-plugins/codeblock.ts
  70. 11 6
      apps/app/src/services/renderer/remark-plugins/echo-directive.ts
  71. 2 3
      apps/app/src/services/renderer/remark-plugins/emoji.ts
  72. 13 16
      apps/app/src/services/renderer/remark-plugins/pukiwiki-like-linker.spec.ts
  73. 34 26
      apps/app/src/services/renderer/remark-plugins/pukiwiki-like-linker.ts
  74. 6 8
      apps/app/src/services/renderer/remark-plugins/xsv-to-table.ts
  75. 53 39
      apps/app/src/services/renderer/renderer.tsx
  76. 26 8
      apps/app/src/stores/websocket.tsx
  77. 3 1
      apps/app/src/stores/yjs.ts
  78. 1 3
      apps/app/test-with-vite/.eslintrc.cjs
  79. 2 3
      apps/app/test-with-vite/setup/mongoms.ts
  80. 1 1
      apps/app/test-with-vite/tsconfig.json
  81. 5 8
      biome.json

+ 7 - 0
apps/app/.eslintrc.js

@@ -27,10 +27,14 @@ module.exports = {
     'test/integration/models/**',
     'test/integration/service/**',
     'test/integration/setup.js',
+    'test-with-vite/**',
+    'public/**',
     'bin/**',
     'config/**',
+    'src/styles/**',
     'src/linter-checker/**',
     'src/migrations/**',
+    'src/models/**',
     'src/features/callout/**',
     'src/features/comment/**',
     'src/features/templates/**',
@@ -39,10 +43,13 @@ module.exports = {
     'src/features/plantuml/**',
     'src/features/external-user-group/**',
     'src/features/page-bulk-export/**',
+    'src/features/growi-plugin/**',
     'src/features/opentelemetry/**',
+    'src/features/rate-limiter/**',
     'src/stores-universal/**',
     'src/interfaces/**',
     'src/utils/**',
+    'src/services/**',
   ],
   settings: {
     // resolve path aliases by eslint-import-resolver-typescript

+ 40 - 40
apps/app/public/images/icons/favicon/manifest.json

@@ -1,41 +1,41 @@
 {
- "name": "App",
- "icons": [
-  {
-   "src": "\/android-icon-36x36.png",
-   "sizes": "36x36",
-   "type": "image\/png",
-   "density": "0.75"
-  },
-  {
-   "src": "\/android-icon-48x48.png",
-   "sizes": "48x48",
-   "type": "image\/png",
-   "density": "1.0"
-  },
-  {
-   "src": "\/android-icon-72x72.png",
-   "sizes": "72x72",
-   "type": "image\/png",
-   "density": "1.5"
-  },
-  {
-   "src": "\/android-icon-96x96.png",
-   "sizes": "96x96",
-   "type": "image\/png",
-   "density": "2.0"
-  },
-  {
-   "src": "\/android-icon-144x144.png",
-   "sizes": "144x144",
-   "type": "image\/png",
-   "density": "3.0"
-  },
-  {
-   "src": "\/android-icon-192x192.png",
-   "sizes": "192x192",
-   "type": "image\/png",
-   "density": "4.0"
-  }
- ]
-}
+  "name": "App",
+  "icons": [
+    {
+      "src": "\/android-icon-36x36.png",
+      "sizes": "36x36",
+      "type": "image\/png",
+      "density": "0.75"
+    },
+    {
+      "src": "\/android-icon-48x48.png",
+      "sizes": "48x48",
+      "type": "image\/png",
+      "density": "1.0"
+    },
+    {
+      "src": "\/android-icon-72x72.png",
+      "sizes": "72x72",
+      "type": "image\/png",
+      "density": "1.5"
+    },
+    {
+      "src": "\/android-icon-96x96.png",
+      "sizes": "96x96",
+      "type": "image\/png",
+      "density": "2.0"
+    },
+    {
+      "src": "\/android-icon-144x144.png",
+      "sizes": "144x144",
+      "type": "image\/png",
+      "density": "3.0"
+    },
+    {
+      "src": "\/android-icon-192x192.png",
+      "sizes": "192x192",
+      "type": "image\/png",
+      "density": "4.0"
+    }
+  ]
+}

+ 1 - 1
apps/app/public/static/locales/en_US/admin.json

@@ -1139,4 +1139,4 @@
     "disable_mode_explanation": "Currently, AI integration is disabled. To enable it, configure the <code>AI_ENABLED</code> environment variable along with the required additional variables.<br><br>For details, please refer to the <a target='blank' rel='noopener noreferrer' href={{documentationUrl}}en/guide/features/ai-knowledge-assistant.html>documentation</a>.",
     "ai_search_management": "AI search management"
   }
-}
+}

+ 1 - 1
apps/app/public/static/locales/en_US/translation.json

@@ -1062,4 +1062,4 @@
     "skipped-toaster": "Skipped synchronizing since the editor is not activated. Please open the editor and try again.",
     "error-toaster": "Synchronization of the latest text failed"
   }
-}
+}

+ 1 - 1
apps/app/public/static/locales/fr_FR/admin.json

@@ -1138,4 +1138,4 @@
     "disable_mode_explanation": "Actuellement, l'intégration AI est désactivée. Pour l'activer, configurez la variable d'environnement <code>AI_ENABLED</code> ainsi que les autres variables nécessaires.<br><br>Pour plus de détails, veuillez consulter la <a target='blank' rel='noopener noreferrer' href={{documentationUrl}}en/guide/features/ai-knowledge-assistant.html>documentation</a>.",
     "ai_search_management": "Gestion de la recherche par l'IA"
   }
-}
+}

+ 1 - 1
apps/app/public/static/locales/fr_FR/translation.json

@@ -1053,4 +1053,4 @@
     "skipped-toaster": "L'éditeur n'est pas actif. Synchronisation annulée.",
     "error-toaster": "Synchronisation échouée"
   }
-}
+}

+ 1 - 1
apps/app/public/static/locales/ja_JP/admin.json

@@ -1148,4 +1148,4 @@
     "disable_mode_explanation": "現在、AI 連携は無効になっています。有効にする場合は環境変数 <code>AI_ENABLED</code> の他、必要な環境変数を設定してください。<br><br>詳細は<a target='blank' rel='noopener noreferrer' href={{documentationUrl}}ja/guide/features/ai-knowledge-assistant.html>ドキュメント</a>を参照してください。",
     "ai_search_management": "AI 検索管理"
   }
-}
+}

+ 1 - 1
apps/app/public/static/locales/ja_JP/translation.json

@@ -1095,4 +1095,4 @@
     "skipped-toaster": "エディターがアクティブではないため、同期をスキップしました。エディターを開いて再度お試しください。",
     "error-toaster": "最新の本文の同期に失敗しました"
   }
-}
+}

+ 1 - 1
apps/app/public/static/locales/ko_KR/admin.json

@@ -1139,4 +1139,4 @@
     "disable_mode_explanation": "현재 AI 통합이 비활성화되어 있습니다. 활성화하려면 <code>AI_ENABLED</code> 환경 변수와 필요한 추가 변수를 구성하십시오.<br><br>자세한 내용은 <a target='blank' rel='noopener noreferrer' href={{documentationUrl}}en/guide/features/ai-knowledge-assistant.html>문서</a>를 참조하십시오.",
     "ai_search_management": "AI 검색 관리"
   }
-}
+}

+ 1 - 1
apps/app/public/static/locales/ko_KR/translation.json

@@ -1022,4 +1022,4 @@
     "skipped-toaster": "편집기가 활성화되지 않아 동기화 건너뜀. 편집기를 열고 다시 시도하십시오.",
     "error-toaster": "최신 텍스트 동기화 실패"
   }
-}
+}

+ 1 - 1
apps/app/public/static/locales/zh_CN/admin.json

@@ -1148,4 +1148,4 @@
     "disable_mode_explanation": "目前,AI 集成已被禁用。若要启用,请配置 <code>AI_ENABLED</code> 环境变量以及其他必要的变量。<br><br>详细信息请参考<a target='blank' rel='noopener noreferrer' href={{documentationUrl}}en/guide/features/ai-knowledge-assistant.html>文档</a>。",
     "ai_search_management": "AI 搜索管理"
   }
-}
+}

+ 1 - 1
apps/app/public/static/locales/zh_CN/translation.json

@@ -1067,4 +1067,4 @@
     "skipped-toaster": "由于编辑器未激活,因此跳过同步。 请打开编辑器并重试。",
     "error-toaster": "同步最新文本失败"
   }
-}
+}

+ 3 - 0
apps/app/src/client/components/PageEditor/PageEditor.tsx

@@ -128,6 +128,9 @@ export const PageEditorSubstance = (props: Props): JSX.Element => {
   mutateResolvedTheme({ themeData: resolvedTheme });
 
   const currentRevisionId = currentPage?.revision?._id;
+
+  // There are cases where "revisionId" is not required for revision updates
+  // See: https://dev.growi.org/651a6f4a008fee2f99187431#origin-%E3%81%AE%E5%BC%B7%E5%BC%B1
   const isRevisionIdRequiredForPageUpdate = currentPage?.revision?.origin === undefined;
 
   const initialValueRef = useRef('');

+ 2 - 0
apps/app/src/client/services/side-effects/drawio-modal-launcher-for-view.ts

@@ -46,6 +46,8 @@ export const useDrawioModalLauncherForView = (opts?: {
       return;
     }
 
+    // There are cases where "revisionId" is not required for revision updates
+    // See: https://dev.growi.org/651a6f4a008fee2f99187431#origin-%E3%81%AE%E5%BC%B7%E5%BC%B1
     try {
       await _updatePage({
         pageId: currentPage._id,

+ 2 - 0
apps/app/src/client/services/side-effects/handsontable-modal-launcher-for-view.ts

@@ -47,6 +47,8 @@ export const useHandsontableModalLauncherForView = (opts?: {
     }
 
     try {
+      // There are cases where "revisionId" is not required for revision updates
+      // See: https://dev.growi.org/651a6f4a008fee2f99187431#origin-%E3%81%AE%E5%BC%B7%E5%BC%B1
       await _updatePage({
         pageId: currentPage._id,
         revisionId,

+ 18 - 23
apps/app/src/features/growi-plugin/client/components/Admin/PluginsExtensionPageContents/PluginCard.tsx

@@ -1,34 +1,31 @@
-import React, { useState, type JSX } from 'react';
+import Link from 'next/link';
 
 import { useTranslation } from 'next-i18next';
-import Link from 'next/link';
+import React, { type JSX, useState } from 'react';
 
 import { apiv3Put } from '~/client/util/apiv3-client';
-import { toastSuccess, toastError } from '~/client/util/toastr';
+import { toastError, toastSuccess } from '~/client/util/toastr';
 
 import styles from './PluginCard.module.scss';
 
 type Props = {
-  id: string,
-  name: string,
-  url: string,
-  isEnabled: boolean,
-  desc?: string,
-  onDelete: () => void,
-}
+  id: string;
+  name: string;
+  url: string;
+  isEnabled: boolean;
+  desc?: string;
+  onDelete: () => void;
+};
 
 export const PluginCard = (props: Props): JSX.Element => {
-
-  const {
-    id, name, url, isEnabled, desc,
-  } = props;
+  const { id, name, url, isEnabled, desc } = props;
 
   const { t } = useTranslation('admin');
 
   const PluginCardButton = (): JSX.Element => {
     const [_isEnabled, setIsEnabled] = useState<boolean>(isEnabled);
 
-    const onChangeHandler = async() => {
+    const onChangeHandler = async () => {
       try {
         if (_isEnabled) {
           const reqUrl = `/plugins/${id}/deactivate`;
@@ -36,16 +33,14 @@ export const PluginCard = (props: Props): JSX.Element => {
           setIsEnabled(!_isEnabled);
           const pluginName = res.data.pluginName;
           toastSuccess(t('toaster.deactivate_plugin_success', { pluginName }));
-        }
-        else {
+        } else {
           const reqUrl = `/plugins/${id}/activate`;
           const res = await apiv3Put(reqUrl);
           setIsEnabled(!_isEnabled);
           const pluginName = res.data.pluginName;
           toastSuccess(t('toaster.activate_plugin_success', { pluginName }));
         }
-      }
-      catch (err) {
+      } catch (err) {
         toastError(err);
       }
     };
@@ -69,7 +64,6 @@ export const PluginCard = (props: Props): JSX.Element => {
   };
 
   const PluginDeleteButton = (): JSX.Element => {
-
     return (
       <div>
         <button
@@ -89,7 +83,9 @@ export const PluginCard = (props: Props): JSX.Element => {
         <div className="row mb-3">
           <div className="col-9">
             <h2 className="card-title h3 border-bottom pb-2 mb-3">
-              <Link href={`${url}`} legacyBehavior>{name}</Link>
+              <Link href={`${url}`} legacyBehavior>
+                {name}
+              </Link>
             </h2>
             <p className="card-text text-muted">{desc}</p>
           </div>
@@ -104,8 +100,7 @@ export const PluginCard = (props: Props): JSX.Element => {
         </div>
       </div>
       <div className="card-footer px-5 border-top-0">
-        <p className="d-flex justify-content-between align-self-center mb-0">
-        </p>
+        <p className="d-flex justify-content-between align-self-center mb-0"></p>
       </div>
     </div>
   );

+ 22 - 14
apps/app/src/features/growi-plugin/client/components/Admin/PluginsExtensionPageContents/PluginDeleteModal.tsx

@@ -1,21 +1,23 @@
-import React, { useCallback } from 'react';
+import Link from 'next/link';
 
 import { useTranslation } from 'next-i18next';
-import Link from 'next/link';
-import {
-  Button, Modal, ModalHeader, ModalBody, ModalFooter,
-} from 'reactstrap';
+import type React from 'react';
+import { useCallback } from 'react';
+import { Button, Modal, ModalBody, ModalFooter, ModalHeader } from 'reactstrap';
 
 import { apiv3Delete } from '~/client/util/apiv3-client';
-import { toastSuccess, toastError } from '~/client/util/toastr';
+import { toastError, toastSuccess } from '~/client/util/toastr';
 
-import { useSWRxAdminPlugins, usePluginDeleteModal } from '../../../stores/admin-plugins';
+import {
+  usePluginDeleteModal,
+  useSWRxAdminPlugins,
+} from '../../../stores/admin-plugins';
 
 export const PluginDeleteModal: React.FC = () => {
-
   const { t } = useTranslation('admin');
   const { mutate } = useSWRxAdminPlugins();
-  const { data: pluginDeleteModalData, close: closePluginDeleteModal } = usePluginDeleteModal();
+  const { data: pluginDeleteModalData, close: closePluginDeleteModal } =
+    usePluginDeleteModal();
   const isOpen = pluginDeleteModalData?.isOpen;
   const id = pluginDeleteModalData?.id;
   const name = pluginDeleteModalData?.name;
@@ -25,7 +27,7 @@ export const PluginDeleteModal: React.FC = () => {
     closePluginDeleteModal();
   }, [closePluginDeleteModal]);
 
-  const onClickDeleteButtonHandler = useCallback(async() => {
+  const onClickDeleteButtonHandler = useCallback(async () => {
     const reqUrl = `/plugins/${id}/remove`;
 
     try {
@@ -34,15 +36,19 @@ export const PluginDeleteModal: React.FC = () => {
       closePluginDeleteModal();
       toastSuccess(t('toaster.remove_plugin_success', { pluginName }));
       mutate();
-    }
-    catch (err) {
+    } catch (err) {
       toastError(err);
     }
   }, [id, closePluginDeleteModal, t, mutate]);
 
   return (
     <Modal isOpen={isOpen} toggle={toggleHandler}>
-      <ModalHeader tag="h4" toggle={toggleHandler} className="text-danger" name={name}>
+      <ModalHeader
+        tag="h4"
+        toggle={toggleHandler}
+        className="text-danger"
+        name={name}
+      >
         <span>
           <span className="material-symbols-outlined">delete_forever</span>
           {t('plugins.confirm')}
@@ -50,7 +56,9 @@ export const PluginDeleteModal: React.FC = () => {
       </ModalHeader>
       <ModalBody>
         <div className="card well mt-2 p-2" key={id}>
-          <Link href={`${url}`} legacyBehavior>{name}</Link>
+          <Link href={`${url}`} legacyBehavior>
+            {name}
+          </Link>
         </div>
       </ModalBody>
       <ModalFooter>

+ 49 - 33
apps/app/src/features/growi-plugin/client/components/Admin/PluginsExtensionPageContents/PluginInstallerForm.tsx

@@ -1,9 +1,8 @@
-import React, { useCallback, type JSX } from 'react';
-
 import { useTranslation } from 'next-i18next';
+import React, { type JSX, useCallback } from 'react';
 
 import { apiv3Post } from '~/client/util/apiv3-client';
-import { toastSuccess, toastError } from '~/client/util/toastr';
+import { toastError, toastSuccess } from '~/client/util/toastr';
 
 import type { IGrowiPluginOrigin } from '../../../../interfaces';
 import { useSWRxAdminPlugins } from '../../../stores/admin-plugins';
@@ -12,40 +11,46 @@ export const PluginInstallerForm = (): JSX.Element => {
   const { mutate } = useSWRxAdminPlugins();
   const { t } = useTranslation('admin');
 
-  const submitHandler = useCallback(async(e) => {
-    e.preventDefault();
+  const submitHandler = useCallback(
+    async (e) => {
+      e.preventDefault();
 
-    const formData = e.target.elements;
+      const formData = e.target.elements;
 
-    const {
-      'pluginInstallerForm[url]': { value: url },
-      'pluginInstallerForm[ghBranch]': { value: ghBranch },
-      // 'pluginInstallerForm[ghTag]': { value: ghTag },
-    } = formData;
+      const {
+        'pluginInstallerForm[url]': { value: url },
+        'pluginInstallerForm[ghBranch]': { value: ghBranch },
+        // 'pluginInstallerForm[ghTag]': { value: ghTag },
+      } = formData;
 
-    const pluginInstallerForm: IGrowiPluginOrigin = {
-      url,
-      ghBranch: ghBranch || 'main',
-      // ghTag,
-    };
+      const pluginInstallerForm: IGrowiPluginOrigin = {
+        url,
+        ghBranch: ghBranch || 'main',
+        // ghTag,
+      };
 
-    try {
-      const res = await apiv3Post('/plugins', { pluginInstallerForm });
-      const pluginName = res.data.pluginName;
-      toastSuccess(t('toaster.install_plugin_success', { pluginName }));
-    }
-    catch (e) {
-      toastError(e);
-    }
-    finally {
-      mutate();
-    }
-  }, [mutate, t]);
+      try {
+        const res = await apiv3Post('/plugins', { pluginInstallerForm });
+        const pluginName = res.data.pluginName;
+        toastSuccess(t('toaster.install_plugin_success', { pluginName }));
+      } catch (e) {
+        toastError(e);
+      } finally {
+        mutate();
+      }
+    },
+    [mutate, t],
+  );
 
   return (
-    <form role="form" onSubmit={submitHandler}>
+    <form onSubmit={submitHandler}>
       <div className="row">
-        <label className="text-start text-md-end col-md-3 col-form-label">{t('plugins.form.label_url')}</label>
+        <label
+          className="text-start text-md-end col-md-3 col-form-label"
+          htmlFor="repoUrl"
+        >
+          {t('plugins.form.label_url')}
+        </label>
         <div className="col-md-6">
           <input
             className="form-control"
@@ -53,26 +58,37 @@ export const PluginInstallerForm = (): JSX.Element => {
             name="pluginInstallerForm[url]"
             placeholder="https://github.com/growilabs/growi-plugins-example"
             required
+            id="repoUrl"
           />
           <p className="form-text text-muted">{t('plugins.form.desc_url')}</p>
         </div>
       </div>
       <div className="row">
-        <label className="text-start text-md-end col-md-3 col-form-label">{t('plugins.form.label_branch')}</label>
+        <label
+          className="text-start text-md-end col-md-3 col-form-label"
+          htmlFor="branchName"
+        >
+          {t('plugins.form.label_branch')}
+        </label>
         <div className="col-md-6">
           <input
             className="form-control col-md-3"
             type="text"
             name="pluginInstallerForm[ghBranch]"
             placeholder="main"
+            id="branchName"
           />
-          <p className="form-text text-muted">{t('plugins.form.desc_branch')}</p>
+          <p className="form-text text-muted">
+            {t('plugins.form.desc_branch')}
+          </p>
         </div>
       </div>
 
       <div className="row my-3">
         <div className="mx-auto">
-          <button type="submit" className="btn btn-primary">{t('plugins.install')}</button>
+          <button type="submit" className="btn btn-primary">
+            {t('plugins.install')}
+          </button>
         </div>
       </div>
     </form>

+ 38 - 28
apps/app/src/features/growi-plugin/client/components/Admin/PluginsExtensionPageContents/PluginsExtensionPageContents.tsx

@@ -1,10 +1,13 @@
-import React, { type JSX } from 'react';
+import dynamic from 'next/dynamic';
 
 import { useTranslation } from 'next-i18next';
-import dynamic from 'next/dynamic';
+import React, { type JSX } from 'react';
 import { Spinner } from 'reactstrap';
 
-import { useSWRxAdminPlugins, usePluginDeleteModal } from '../../../stores/admin-plugins';
+import {
+  usePluginDeleteModal,
+  useSWRxAdminPlugins,
+} from '../../../stores/admin-plugins';
 
 import { PluginCard } from './PluginCard';
 import { PluginInstallerForm } from './PluginInstallerForm';
@@ -19,8 +22,10 @@ const Loading = (): JSX.Element => {
 
 export const PluginsExtensionPageContents = (): JSX.Element => {
   const { t } = useTranslation('admin');
-  const PluginDeleteModal = dynamic(() => import('./PluginDeleteModal')
-    .then(mod => mod.PluginDeleteModal), { ssr: false });
+  const PluginDeleteModal = dynamic(
+    () => import('./PluginDeleteModal').then((mod) => mod.PluginDeleteModal),
+    { ssr: false },
+  );
   const { data, mutate } = useSWRxAdminPlugins();
   const { open: openPluginDeleteModal } = usePluginDeleteModal();
 
@@ -28,7 +33,9 @@ export const PluginsExtensionPageContents = (): JSX.Element => {
     <div>
       <div className="row mb-5">
         <div className="col-lg-12">
-          <h2 className="admin-setting-header">{t('plugins.plugin_installer')}</h2>
+          <h2 className="admin-setting-header">
+            {t('plugins.plugin_installer')}
+          </h2>
           <PluginInstallerForm />
         </div>
       </div>
@@ -37,34 +44,37 @@ export const PluginsExtensionPageContents = (): JSX.Element => {
         <div className="col-lg-12">
           <h2 className="admin-setting-header">
             {t('plugins.plugin_card')}
-            <button type="button" className="btn btn-sm ms-auto grw-btn-reload" onClick={() => mutate()}>
+            <button
+              type="button"
+              className="btn btn-sm ms-auto grw-btn-reload"
+              onClick={() => mutate()}
+            >
               <span className="material-symbols-outlined">refresh</span>
             </button>
           </h2>
-          {data?.plugins == null
-            ? <Loading />
-            : (
-              <div className="d-grid gap-5">
-                { data.plugins.length === 0 && (
-                  <div>{t('plugins.plugin_is_not_installed')}</div>
-                )}
-                {data.plugins.map(plugin => (
-                  <PluginCard
-                    key={plugin._id}
-                    id={plugin._id}
-                    name={plugin.meta.name}
-                    url={plugin.origin.url}
-                    isEnabled={plugin.isEnabled}
-                    desc={plugin.meta.desc}
-                    onDelete={() => openPluginDeleteModal(plugin)}
-                  />
-                ))}
-              </div>
-            )}
+          {data?.plugins == null ? (
+            <Loading />
+          ) : (
+            <div className="d-grid gap-5">
+              {data.plugins.length === 0 && (
+                <div>{t('plugins.plugin_is_not_installed')}</div>
+              )}
+              {data.plugins.map((plugin) => (
+                <PluginCard
+                  key={plugin._id}
+                  id={plugin._id}
+                  name={plugin.meta.name}
+                  url={plugin.origin.url}
+                  isEnabled={plugin.isEnabled}
+                  desc={plugin.meta.desc}
+                  onDelete={() => openPluginDeleteModal(plugin)}
+                />
+              ))}
+            </div>
+          )}
         </div>
       </div>
       <PluginDeleteModal />
-
     </div>
   );
 };

+ 11 - 8
apps/app/src/features/growi-plugin/client/components/GrowiPluginsActivator.tsx

@@ -1,14 +1,17 @@
-import React, { useEffect, type JSX } from 'react';
+import React, { type JSX, useEffect } from 'react';
 
-import { initializeGrowiFacade, registerGrowiFacade } from '../utils/growi-facade-utils';
+import {
+  initializeGrowiFacade,
+  registerGrowiFacade,
+} from '../utils/growi-facade-utils';
 
 declare global {
   // eslint-disable-next-line vars-on-top, no-var
   var pluginActivators: {
     [key: string]: {
-      activate: () => void,
-      deactivate: () => void,
-    },
+      activate: () => void;
+      deactivate: () => void;
+    };
   };
 }
 
@@ -16,7 +19,9 @@ async function activateAll(): Promise<void> {
   initializeGrowiFacade();
 
   // register renderer options to facade
-  const { generateViewOptions, generatePreviewOptions } = await import('~/client/services/renderer/renderer');
+  const { generateViewOptions, generatePreviewOptions } = await import(
+    '~/client/services/renderer/renderer'
+  );
   registerGrowiFacade({
     markdownRenderer: {
       optionsGenerators: {
@@ -36,9 +41,7 @@ async function activateAll(): Promise<void> {
   });
 }
 
-
 export const GrowiPluginsActivator = (): JSX.Element => {
-
   useEffect(() => {
     activateAll();
   }, []);

+ 30 - 26
apps/app/src/features/growi-plugin/client/stores/admin-plugins.tsx

@@ -7,40 +7,40 @@ import { useStaticSWR } from '~/stores/use-static-swr';
 import type { IGrowiPluginHasId } from '../../interfaces';
 
 type Plugins = {
-  plugins: IGrowiPluginHasId[]
-}
+  plugins: IGrowiPluginHasId[];
+};
 
 export const useSWRxAdminPlugins = (): SWRResponse<Plugins, Error> => {
-  return useSWR(
-    '/plugins',
-    async(endpoint) => {
-      try {
-        const res = await apiv3Get<Plugins>(endpoint);
-        return res.data;
-      }
-      catch (err) {
-        throw new Error(err);
-      }
-    },
-  );
+  return useSWR('/plugins', async (endpoint) => {
+    try {
+      const res = await apiv3Get<Plugins>(endpoint);
+      return res.data;
+    } catch (err) {
+      throw new Error(err);
+    }
+  });
 };
 
 /*
  * PluginDeleteModal
  */
 type PluginDeleteModalStatus = {
-  isOpen: boolean,
-  id: string,
-  name: string,
-  url: string,
-}
+  isOpen: boolean;
+  id: string;
+  name: string;
+  url: string;
+};
 
 type PluginDeleteModalUtils = {
-  open(plugin: IGrowiPluginHasId): Promise<void>,
-  close(): Promise<void>,
-}
+  open(plugin: IGrowiPluginHasId): Promise<void>;
+  close(): Promise<void>;
+};
 
-export const usePluginDeleteModal = (): SWRResponse<PluginDeleteModalStatus, Error> & PluginDeleteModalUtils => {
+export const usePluginDeleteModal = (): SWRResponse<
+  PluginDeleteModalStatus,
+  Error
+> &
+  PluginDeleteModalUtils => {
   const initialStatus: PluginDeleteModalStatus = {
     isOpen: false,
     id: '',
@@ -48,10 +48,14 @@ export const usePluginDeleteModal = (): SWRResponse<PluginDeleteModalStatus, Err
     url: '',
   };
 
-  const swrResponse = useStaticSWR<PluginDeleteModalStatus, Error>('pluginDeleteModal', undefined, { fallbackData: initialStatus });
+  const swrResponse = useStaticSWR<PluginDeleteModalStatus, Error>(
+    'pluginDeleteModal',
+    undefined,
+    { fallbackData: initialStatus },
+  );
   const { mutate } = swrResponse;
 
-  const open = async(plugin) => {
+  const open = async (plugin) => {
     mutate({
       isOpen: true,
       id: plugin._id,
@@ -60,7 +64,7 @@ export const usePluginDeleteModal = (): SWRResponse<PluginDeleteModalStatus, Err
     });
   };
 
-  const close = async() => {
+  const close = async () => {
     mutate(initialStatus);
   };
 

+ 1 - 5
apps/app/src/features/growi-plugin/client/utils/growi-facade-utils.ts

@@ -7,7 +7,6 @@ declare global {
   var growiFacade: GrowiFacade;
 }
 
-
 export const initializeGrowiFacade = (): void => {
   if (isServer()) {
     return;
@@ -33,8 +32,5 @@ export const registerGrowiFacade = (addedFacade: GrowiFacade): void => {
     throw new Error('This method is available only in client.');
   }
 
-  window.growiFacade = deepmerge(
-    getGrowiFacade(),
-    addedFacade,
-  );
+  window.growiFacade = deepmerge(getGrowiFacade(), addedFacade);
 };

+ 30 - 25
apps/app/src/features/growi-plugin/interfaces/growi-plugin.ts

@@ -1,39 +1,44 @@
-import type { GrowiPluginType, GrowiThemeMetadata, HasObjectId } from '@growi/core';
+import type {
+  GrowiPluginType,
+  GrowiThemeMetadata,
+  HasObjectId,
+} from '@growi/core';
 import type { TemplateSummary } from '@growi/pluginkit/dist/v4';
 
 export type IGrowiPluginOrigin = {
-  url: string,
-  ghBranch?: string,
-  ghTag?: string,
-}
+  url: string;
+  ghBranch?: string;
+  ghTag?: string;
+};
 
 export type IGrowiPlugin<M extends IGrowiPluginMeta = IGrowiPluginMeta> = {
-  isEnabled: boolean,
-  installedPath: string,
-  organizationName: string,
-  origin: IGrowiPluginOrigin,
-  meta: M,
-}
+  isEnabled: boolean;
+  installedPath: string;
+  organizationName: string;
+  origin: IGrowiPluginOrigin;
+  meta: M;
+};
 
 export type IGrowiPluginMeta = {
-  name: string,
-  types: GrowiPluginType[],
-  desc?: string,
-  author?: string,
-}
+  name: string;
+  types: GrowiPluginType[];
+  desc?: string;
+  author?: string;
+};
 
 export type IGrowiThemePluginMeta = IGrowiPluginMeta & {
-  themes: GrowiThemeMetadata[],
-}
+  themes: GrowiThemeMetadata[];
+};
 
 export type IGrowiTemplatePluginMeta = IGrowiPluginMeta & {
-  templateSummaries: TemplateSummary[],
-}
+  templateSummaries: TemplateSummary[];
+};
 
-export type IGrowiPluginMetaByType<T extends GrowiPluginType = any> = T extends 'theme'
-  ? IGrowiThemePluginMeta
-  : T extends 'template'
-    ? IGrowiTemplatePluginMeta
-    : IGrowiPluginMeta;
+export type IGrowiPluginMetaByType<T extends GrowiPluginType = any> =
+  T extends 'theme'
+    ? IGrowiThemePluginMeta
+    : T extends 'template'
+      ? IGrowiTemplatePluginMeta
+      : IGrowiPluginMeta;
 
 export type IGrowiPluginHasId = IGrowiPlugin & HasObjectId;

+ 19 - 18
apps/app/src/features/growi-plugin/server/models/growi-plugin.integ.ts

@@ -3,8 +3,7 @@ import { GrowiPluginType } from '@growi/core';
 import { GrowiPlugin } from './growi-plugin';
 
 describe('GrowiPlugin find methods', () => {
-
-  beforeAll(async() => {
+  beforeAll(async () => {
     await GrowiPlugin.insertMany([
       {
         isEnabled: false,
@@ -57,16 +56,16 @@ describe('GrowiPlugin find methods', () => {
     ]);
   });
 
-  afterAll(async() => {
+  afterAll(async () => {
     await GrowiPlugin.deleteMany({});
   });
 
   describe.concurrent('.findEnabledPlugins', () => {
-    it('shoud returns documents which isEnabled is true', async() => {
+    it('shoud returns documents which isEnabled is true', async () => {
       // when
       const results = await GrowiPlugin.findEnabledPlugins();
 
-      const pluginNames = results.map(p => p.meta.name);
+      const pluginNames = results.map((p) => p.meta.name);
 
       // then
       expect(results.length === 2).toBeTruthy();
@@ -76,24 +75,23 @@ describe('GrowiPlugin find methods', () => {
   });
 
   describe.concurrent('.findEnabledPluginsByType', () => {
-    it("shoud returns documents which type is 'template'", async() => {
+    it("shoud returns documents which type is 'template'", async () => {
       // when
-      const results = await GrowiPlugin.findEnabledPluginsByType(GrowiPluginType.Template);
+      const results = await GrowiPlugin.findEnabledPluginsByType(
+        GrowiPluginType.Template,
+      );
 
-      const pluginNames = results.map(p => p.meta.name);
+      const pluginNames = results.map((p) => p.meta.name);
 
       // then
       expect(results.length === 1).toBeTruthy();
       expect(pluginNames.includes('@growi/growi-plugin-example2')).toBeTruthy();
     });
   });
-
 });
 
-
 describe('GrowiPlugin activate/deactivate', () => {
-
-  beforeAll(async() => {
+  beforeAll(async () => {
     await GrowiPlugin.insertMany([
       {
         isEnabled: false,
@@ -110,12 +108,12 @@ describe('GrowiPlugin activate/deactivate', () => {
     ]);
   });
 
-  afterAll(async() => {
+  afterAll(async () => {
     await GrowiPlugin.deleteMany({});
   });
 
   describe('.activatePlugin', () => {
-    it('shoud update the property "isEnabled" to true', async() => {
+    it('shoud update the property "isEnabled" to true', async () => {
       // setup
       const plugin = await GrowiPlugin.findOne({});
       assert(plugin != null);
@@ -124,7 +122,9 @@ describe('GrowiPlugin activate/deactivate', () => {
 
       // when
       const result = await GrowiPlugin.activatePlugin(plugin._id);
-      const pluginAfterActivated = await GrowiPlugin.findOne({ _id: plugin._id });
+      const pluginAfterActivated = await GrowiPlugin.findOne({
+        _id: plugin._id,
+      });
 
       // then
       expect(result).toEqual('@growi/growi-plugin-example1'); // equals to meta.name
@@ -135,7 +135,7 @@ describe('GrowiPlugin activate/deactivate', () => {
   });
 
   describe('.deactivatePlugin', () => {
-    it('shoud update the property "isEnabled" to true', async() => {
+    it('shoud update the property "isEnabled" to true', async () => {
       // setup
       const plugin = await GrowiPlugin.findOne({});
       assert(plugin != null);
@@ -144,7 +144,9 @@ describe('GrowiPlugin activate/deactivate', () => {
 
       // when
       const result = await GrowiPlugin.deactivatePlugin(plugin._id);
-      const pluginAfterActivated = await GrowiPlugin.findOne({ _id: plugin._id });
+      const pluginAfterActivated = await GrowiPlugin.findOne({
+        _id: plugin._id,
+      });
 
       // then
       expect(result).toEqual('@growi/growi-plugin-example1'); // equals to meta.name
@@ -153,5 +155,4 @@ describe('GrowiPlugin activate/deactivate', () => {
       expect(pluginAfterActivated.isEnabled).toBeFalsy(); // isEnabled: false
     });
   });
-
 });

+ 45 - 20
apps/app/src/features/growi-plugin/server/models/growi-plugin.ts

@@ -1,25 +1,35 @@
 import { GrowiPluginType } from '@growi/core';
-import {
-  Schema, type Model, type Document, type Types,
-} from 'mongoose';
+import { type Document, type Model, Schema, type Types } from 'mongoose';
 
 import { getOrCreateModel } from '~/server/util/mongoose-utils';
 
 import type {
-  IGrowiPlugin, IGrowiPluginMeta, IGrowiPluginMetaByType, IGrowiPluginOrigin, IGrowiTemplatePluginMeta, IGrowiThemePluginMeta,
+  IGrowiPlugin,
+  IGrowiPluginMeta,
+  IGrowiPluginMetaByType,
+  IGrowiPluginOrigin,
+  IGrowiTemplatePluginMeta,
+  IGrowiThemePluginMeta,
 } from '../../interfaces';
 
-export interface IGrowiPluginDocument<M extends IGrowiPluginMeta = IGrowiPluginMeta> extends IGrowiPlugin<M>, Document {
-  metaJson: IGrowiPluginMeta & IGrowiThemePluginMeta & IGrowiTemplatePluginMeta,
+export interface IGrowiPluginDocument<
+  M extends IGrowiPluginMeta = IGrowiPluginMeta,
+> extends IGrowiPlugin<M>,
+    Document {
+  metaJson: IGrowiPluginMeta & IGrowiThemePluginMeta & IGrowiTemplatePluginMeta;
 }
 export interface IGrowiPluginModel extends Model<IGrowiPluginDocument> {
-  findEnabledPlugins(): Promise<IGrowiPluginDocument[]>
-  findEnabledPluginsByType<T extends GrowiPluginType>(type: T): Promise<IGrowiPluginDocument<IGrowiPluginMetaByType<T>>[]>
-  activatePlugin(id: Types.ObjectId): Promise<string>
-  deactivatePlugin(id: Types.ObjectId): Promise<string>
+  findEnabledPlugins(): Promise<IGrowiPluginDocument[]>;
+  findEnabledPluginsByType<T extends GrowiPluginType>(
+    type: T,
+  ): Promise<IGrowiPluginDocument<IGrowiPluginMetaByType<T>>[]>;
+  activatePlugin(id: Types.ObjectId): Promise<string>;
+  deactivatePlugin(id: Types.ObjectId): Promise<string>;
 }
 
-const growiPluginMetaSchema = new Schema<IGrowiPluginMeta & IGrowiThemePluginMeta & IGrowiTemplatePluginMeta>({
+const growiPluginMetaSchema = new Schema<
+  IGrowiPluginMeta & IGrowiThemePluginMeta & IGrowiTemplatePluginMeta
+>({
   name: { type: String, required: true },
   types: {
     type: [String],
@@ -46,21 +56,28 @@ const growiPluginSchema = new Schema<IGrowiPluginDocument, IGrowiPluginModel>({
   meta: growiPluginMetaSchema,
 });
 
-growiPluginSchema.statics.findEnabledPlugins = async function(): Promise<IGrowiPlugin[]> {
+growiPluginSchema.statics.findEnabledPlugins = async function (): Promise<
+  IGrowiPlugin[]
+> {
   return this.find({ isEnabled: true }).lean();
 };
 
-growiPluginSchema.statics.findEnabledPluginsByType = async function<T extends GrowiPluginType>(
-    type: T,
-): Promise<IGrowiPlugin<IGrowiPluginMetaByType<T>>[]> {
+growiPluginSchema.statics.findEnabledPluginsByType = async function <
+  T extends GrowiPluginType,
+>(type: T): Promise<IGrowiPlugin<IGrowiPluginMetaByType<T>>[]> {
   return this.find({
     isEnabled: true,
     'meta.types': { $in: type },
   }).lean();
 };
 
-growiPluginSchema.statics.activatePlugin = async function(id: Types.ObjectId): Promise<string> {
-  const growiPlugin = await this.findOneAndUpdate({ _id: id }, { isEnabled: true });
+growiPluginSchema.statics.activatePlugin = async function (
+  id: Types.ObjectId,
+): Promise<string> {
+  const growiPlugin = await this.findOneAndUpdate(
+    { _id: id },
+    { isEnabled: true },
+  );
   if (growiPlugin == null) {
     const message = 'No plugin found for this ID.';
     throw new Error(message);
@@ -69,8 +86,13 @@ growiPluginSchema.statics.activatePlugin = async function(id: Types.ObjectId): P
   return pluginName;
 };
 
-growiPluginSchema.statics.deactivatePlugin = async function(id: Types.ObjectId): Promise<string> {
-  const growiPlugin = await this.findOneAndUpdate({ _id: id }, { isEnabled: false });
+growiPluginSchema.statics.deactivatePlugin = async function (
+  id: Types.ObjectId,
+): Promise<string> {
+  const growiPlugin = await this.findOneAndUpdate(
+    { _id: id },
+    { isEnabled: false },
+  );
   if (growiPlugin == null) {
     const message = 'No plugin found for this ID.';
     throw new Error(message);
@@ -79,4 +101,7 @@ growiPluginSchema.statics.deactivatePlugin = async function(id: Types.ObjectId):
   return pluginName;
 };
 
-export const GrowiPlugin = getOrCreateModel<IGrowiPluginDocument, IGrowiPluginModel>('GrowiPlugin', growiPluginSchema);
+export const GrowiPlugin = getOrCreateModel<
+  IGrowiPluginDocument,
+  IGrowiPluginModel
+>('GrowiPlugin', growiPluginSchema);

+ 11 - 9
apps/app/src/features/growi-plugin/server/models/vo/github-url.spec.ts

@@ -1,7 +1,6 @@
 import { GitHubUrl } from './github-url';
 
 describe('GitHubUrl Constructor throws an error when the url string is', () => {
-
   it.concurrent.each`
     url
     ${'//example.com/org/repos'}
@@ -14,11 +13,9 @@ describe('GitHubUrl Constructor throws an error when the url string is', () => {
     // then
     expect(caller).toThrowError(`The specified URL is invalid. : url='${url}'`);
   });
-
 });
 
 describe('The constructor is successfully processed', () => {
-
   it('with http schemed url', () => {
     // when
     const githubUrl = new GitHubUrl('http://github.com/org/repos');
@@ -51,7 +48,6 @@ describe('The constructor is successfully processed', () => {
     expect(githubUrl.reposName).toEqual('repos');
     expect(githubUrl.branchName).toEqual('fix/bug');
   });
-
 });
 
 describe('archiveUrl()', () => {
@@ -63,12 +59,13 @@ describe('archiveUrl()', () => {
     const { archiveUrl } = githubUrl;
 
     // then
-    expect(archiveUrl).toEqual('https://github.com/org/repos/archive/refs/heads/fix%2Fbug.zip');
+    expect(archiveUrl).toEqual(
+      'https://github.com/org/repos/archive/refs/heads/fix%2Fbug.zip',
+    );
   });
 });
 
 describe('extractedArchiveDirName()', () => {
-
   describe('certain characters in the branch name are converted to slashes, and if they are consecutive, they become a single hyphen', () => {
     it.concurrent.each`
       branchName
@@ -76,7 +73,10 @@ describe('extractedArchiveDirName()', () => {
       ${'a---b'}
     `("'$branchName'", ({ branchName }) => {
       // setup
-      const githubUrl = new GitHubUrl('https://github.com/org/repos', branchName);
+      const githubUrl = new GitHubUrl(
+        'https://github.com/org/repos',
+        branchName,
+      );
 
       // when
       const { extractedArchiveDirName } = githubUrl;
@@ -93,7 +93,10 @@ describe('extractedArchiveDirName()', () => {
       ${'a_b'}
     `("'$branchName'", ({ branchName }) => {
       // setup
-      const githubUrl = new GitHubUrl('https://github.com/org/repos', branchName);
+      const githubUrl = new GitHubUrl(
+        'https://github.com/org/repos',
+        branchName,
+      );
 
       // when
       const { extractedArchiveDirName } = githubUrl;
@@ -102,5 +105,4 @@ describe('extractedArchiveDirName()', () => {
       expect(extractedArchiveDirName).toEqual(branchName);
     });
   });
-
 });

+ 13 - 10
apps/app/src/features/growi-plugin/server/models/vo/github-url.ts

@@ -1,4 +1,3 @@
-
 import sanitize from 'sanitize-filename';
 
 // https://regex101.com/r/fK2rV3/1
@@ -11,7 +10,6 @@ const sanitizeSymbolsChars = new RegExp(/[^a-zA-Z0-9_.]+/g);
 const sanitizeVersionChars = new RegExp(/^v[\d]/gi);
 
 export class GitHubUrl {
-
   private _organizationName: string;
 
   private _reposName: string;
@@ -39,19 +37,26 @@ export class GitHubUrl {
   get archiveUrl(): string {
     const encodedBranchName = encodeURIComponent(this.branchName);
     const encodedTagName = encodeURIComponent(this.tagName);
-    const zipUrl = encodedTagName !== '' ? `tags/${encodedTagName}` : `heads/${encodedBranchName}`;
-    const ghUrl = new URL(`/${this.organizationName}/${this.reposName}/archive/refs/${zipUrl}.zip`, 'https://github.com');
+    const zipUrl =
+      encodedTagName !== ''
+        ? `tags/${encodedTagName}`
+        : `heads/${encodedBranchName}`;
+    const ghUrl = new URL(
+      `/${this.organizationName}/${this.reposName}/archive/refs/${zipUrl}.zip`,
+      'https://github.com',
+    );
     return ghUrl.toString();
   }
 
   get extractedArchiveDirName(): string {
     const name = this._tagName !== '' ? this._tagName : this._branchName;
-    return name.replace(sanitizeVersionChars, m => m.substring(1)).replaceAll(sanitizeSymbolsChars, '-');
+    return name
+      .replace(sanitizeVersionChars, (m) => m.substring(1))
+      .replaceAll(sanitizeSymbolsChars, '-');
   }
 
   constructor(url: string, branchName = 'main', tagName = '') {
-
-    let matched;
+    let matched: RegExpMatchArray | null;
     try {
       const ghUrl = new URL(url);
 
@@ -60,8 +65,7 @@ export class GitHubUrl {
       if (ghUrl.hostname !== 'github.com' || matched == null) {
         throw new Error();
       }
-    }
-    catch (err) {
+    } catch (err) {
       throw new Error(`The specified URL is invalid. : url='${url}'`);
     }
 
@@ -71,5 +75,4 @@ export class GitHubUrl {
     this._organizationName = sanitize(matched[1]);
     this._reposName = sanitize(matched[2]);
   }
-
 }

+ 62 - 36
apps/app/src/features/growi-plugin/server/routes/apiv3/admin/index.ts

@@ -1,9 +1,8 @@
+import { SCOPE } from '@growi/core/dist/interfaces';
 import type { Request, Router } from 'express';
 import express from 'express';
 import { body, query } from 'express-validator';
 import mongoose from 'mongoose';
-
-import { SCOPE } from '@growi/core/dist/interfaces';
 import type Crowi from '~/server/crowi';
 import { accessTokenParser } from '~/server/middlewares/access-token-parser';
 import type { ApiV3Response } from '~/server/routes/apiv3/interfaces/apiv3-response';
@@ -11,7 +10,6 @@ import type { ApiV3Response } from '~/server/routes/apiv3/interfaces/apiv3-respo
 import { GrowiPlugin } from '../../../models';
 import { growiPluginService } from '../../../services';
 
-
 const ObjectID = mongoose.Types.ObjectId;
 
 /*
@@ -22,26 +20,34 @@ const validator = {
     query('id').isMongoId().withMessage('pluginId is required'),
   ],
   pluginFormValueisRequired: [
-    body('pluginInstallerForm').isString().withMessage('pluginFormValue is required'),
+    body('pluginInstallerForm')
+      .isString()
+      .withMessage('pluginFormValue is required'),
   ],
 };
 
 module.exports = (crowi: Crowi): Router => {
-  const loginRequiredStrictly = require('~/server/middlewares/login-required')(crowi);
+  const loginRequiredStrictly = require('~/server/middlewares/login-required')(
+    crowi,
+  );
   const adminRequired = require('~/server/middlewares/admin-required')(crowi);
 
   const router = express.Router();
 
-  router.get('/', accessTokenParser([SCOPE.READ.ADMIN.PLUGIN]), loginRequiredStrictly, adminRequired, async(req: Request, res: ApiV3Response) => {
-    try {
-      const data = await GrowiPlugin.find({});
-      return res.apiv3({ plugins: data });
-    }
-    catch (err) {
-      return res.apiv3Err(err);
-    }
-  });
-
+  router.get(
+    '/',
+    accessTokenParser([SCOPE.READ.ADMIN.PLUGIN]),
+    loginRequiredStrictly,
+    adminRequired,
+    async (req: Request, res: ApiV3Response) => {
+      try {
+        const data = await GrowiPlugin.find({});
+        return res.apiv3({ plugins: data });
+      } catch (err) {
+        return res.apiv3Err(err);
+      }
+    },
+  );
 
   /**
    * @swagger
@@ -82,18 +88,23 @@ module.exports = (crowi: Crowi): Router => {
    *                   description: The name of the installed plugin
    *
    */
-  router.post('/', accessTokenParser([SCOPE.WRITE.ADMIN.PLUGIN]), loginRequiredStrictly, adminRequired, validator.pluginFormValueisRequired,
-    async(req: Request, res: ApiV3Response) => {
+  router.post(
+    '/',
+    accessTokenParser([SCOPE.WRITE.ADMIN.PLUGIN]),
+    loginRequiredStrictly,
+    adminRequired,
+    validator.pluginFormValueisRequired,
+    async (req: Request, res: ApiV3Response) => {
       const { pluginInstallerForm: formValue } = req.body;
 
       try {
         const pluginName = await growiPluginService.install(formValue);
         return res.apiv3({ pluginName });
-      }
-      catch (err) {
+      } catch (err) {
         return res.apiv3Err(err);
       }
-    });
+    },
+  );
 
   /**
    * @swagger
@@ -123,33 +134,43 @@ module.exports = (crowi: Crowi): Router => {
    *                   type: string
    *                   description: The name of the activated plugin
    */
-  router.put('/:id/activate', accessTokenParser([SCOPE.WRITE.ADMIN.PLUGIN]), loginRequiredStrictly, adminRequired, validator.pluginIdisRequired,
-    async(req: Request, res: ApiV3Response) => {
+  router.put(
+    '/:id/activate',
+    accessTokenParser([SCOPE.WRITE.ADMIN.PLUGIN]),
+    loginRequiredStrictly,
+    adminRequired,
+    validator.pluginIdisRequired,
+    async (req: Request, res: ApiV3Response) => {
       const { id } = req.params;
       const pluginId = new ObjectID(id);
 
       try {
         const pluginName = await GrowiPlugin.activatePlugin(pluginId);
         return res.apiv3({ pluginName });
-      }
-      catch (err) {
+      } catch (err) {
         return res.apiv3Err(err);
       }
-    });
-
-  router.put('/:id/deactivate', accessTokenParser([SCOPE.WRITE.ADMIN.PLUGIN]), loginRequiredStrictly, adminRequired, validator.pluginIdisRequired,
-    async(req: Request, res: ApiV3Response) => {
+    },
+  );
+
+  router.put(
+    '/:id/deactivate',
+    accessTokenParser([SCOPE.WRITE.ADMIN.PLUGIN]),
+    loginRequiredStrictly,
+    adminRequired,
+    validator.pluginIdisRequired,
+    async (req: Request, res: ApiV3Response) => {
       const { id } = req.params;
       const pluginId = new ObjectID(id);
 
       try {
         const pluginName = await GrowiPlugin.deactivatePlugin(pluginId);
         return res.apiv3({ pluginName });
-      }
-      catch (err) {
+      } catch (err) {
         return res.apiv3Err(err);
       }
-    });
+    },
+  );
 
   /**
    * @swagger
@@ -179,19 +200,24 @@ module.exports = (crowi: Crowi): Router => {
    *                   type: string
    *                   description: The name of the removed plugin
    */
-  router.delete('/:id/remove', accessTokenParser([SCOPE.WRITE.ADMIN.PLUGIN]), loginRequiredStrictly, adminRequired, validator.pluginIdisRequired,
-    async(req: Request, res: ApiV3Response) => {
+  router.delete(
+    '/:id/remove',
+    accessTokenParser([SCOPE.WRITE.ADMIN.PLUGIN]),
+    loginRequiredStrictly,
+    adminRequired,
+    validator.pluginIdisRequired,
+    async (req: Request, res: ApiV3Response) => {
       const { id } = req.params;
       const pluginId = new ObjectID(id);
 
       try {
         const pluginName = await growiPluginService.deletePlugin(pluginId);
         return res.apiv3({ pluginName });
-      }
-      catch (err) {
+      } catch (err) {
         return res.apiv3Err(err);
       }
-    });
+    },
+  );
 
   return router;
 };

+ 11 - 3
apps/app/src/features/growi-plugin/server/services/growi-plugin/generate-template-plugin-meta.ts

@@ -1,11 +1,19 @@
 import type { GrowiPluginValidationData } from '@growi/pluginkit';
 import { scanAllTemplates } from '@growi/pluginkit/dist/v4/server/index.cjs';
 
-import type { IGrowiPlugin, IGrowiTemplatePluginMeta } from '../../../interfaces';
+import type {
+  IGrowiPlugin,
+  IGrowiTemplatePluginMeta,
+} from '../../../interfaces';
 
-export const generateTemplatePluginMeta = async(plugin: IGrowiPlugin, validationData: GrowiPluginValidationData): Promise<IGrowiTemplatePluginMeta> => {
+export const generateTemplatePluginMeta = async (
+  plugin: IGrowiPlugin,
+  validationData: GrowiPluginValidationData,
+): Promise<IGrowiTemplatePluginMeta> => {
   return {
     ...plugin.meta,
-    templateSummaries: await scanAllTemplates(validationData.projectDirRoot, { pluginId: plugin.installedPath }),
+    templateSummaries: await scanAllTemplates(validationData.projectDirRoot, {
+      pluginId: plugin.installedPath,
+    }),
   };
 };

+ 4 - 1
apps/app/src/features/growi-plugin/server/services/growi-plugin/generate-theme-plugin-meta.ts

@@ -2,7 +2,10 @@ import type { GrowiPluginValidationData } from '@growi/pluginkit';
 
 import type { IGrowiPlugin, IGrowiThemePluginMeta } from '../../../interfaces';
 
-export const generateThemePluginMeta = async(plugin: IGrowiPlugin, validationData: GrowiPluginValidationData): Promise<IGrowiThemePluginMeta> => {
+export const generateThemePluginMeta = async (
+  plugin: IGrowiPlugin,
+  validationData: GrowiPluginValidationData,
+): Promise<IGrowiThemePluginMeta> => {
   // TODO: validate as a theme plugin
 
   return {

+ 42 - 25
apps/app/src/features/growi-plugin/server/services/growi-plugin/growi-plugin.integ.ts

@@ -7,27 +7,34 @@ import { GrowiPlugin } from '../../models';
 import { growiPluginService } from './growi-plugin';
 
 describe('Installing a GROWI template plugin', () => {
-
-  it('install() should success', async() => {
+  it('install() should success', async () => {
     // when
     const result = await growiPluginService.install({
       url: 'https://github.com/growilabs/growi-plugin-templates-for-office',
     });
-    const count = await GrowiPlugin.count({ 'meta.name': 'growi-plugin-templates-for-office' });
+    const count = await GrowiPlugin.count({
+      'meta.name': 'growi-plugin-templates-for-office',
+    });
 
     // expect
     expect(result).toEqual('growi-plugin-templates-for-office');
     expect(count).toBe(1);
-    expect(fs.existsSync(path.join(
-      PLUGIN_STORING_PATH,
-      'growilabs',
-      'growi-plugin-templates-for-office',
-    ))).toBeTruthy();
+    expect(
+      fs.existsSync(
+        path.join(
+          PLUGIN_STORING_PATH,
+          'growilabs',
+          'growi-plugin-templates-for-office',
+        ),
+      ),
+    ).toBeTruthy();
   });
 
-  it('install() should success (re-install)', async() => {
+  it('install() should success (re-install)', async () => {
     // confirm
-    const count1 = await GrowiPlugin.count({ 'meta.name': 'growi-plugin-templates-for-office' });
+    const count1 = await GrowiPlugin.count({
+      'meta.name': 'growi-plugin-templates-for-office',
+    });
     expect(count1).toBe(1);
 
     // setup
@@ -44,38 +51,46 @@ describe('Installing a GROWI template plugin', () => {
     const result = await growiPluginService.install({
       url: 'https://github.com/growilabs/growi-plugin-templates-for-office',
     });
-    const count2 = await GrowiPlugin.count({ 'meta.name': 'growi-plugin-templates-for-office' });
+    const count2 = await GrowiPlugin.count({
+      'meta.name': 'growi-plugin-templates-for-office',
+    });
 
     // expect
     expect(result).toEqual('growi-plugin-templates-for-office');
     expect(count2).toBe(1);
     expect(fs.existsSync(dummyFilePath)).toBeFalsy(); // the dummy file should be removed
   });
-
 });
 
 describe('Installing a GROWI theme plugin', () => {
-
-  it('install() should success', async() => {
+  it('install() should success', async () => {
     // when
     const result = await growiPluginService.install({
       url: 'https://github.com/growilabs/growi-plugin-theme-vivid-internet',
     });
-    const count = await GrowiPlugin.count({ 'meta.name': 'growi-plugin-theme-vivid-internet' });
+    const count = await GrowiPlugin.count({
+      'meta.name': 'growi-plugin-theme-vivid-internet',
+    });
 
     // expect
     expect(result).toEqual('growi-plugin-theme-vivid-internet');
     expect(count).toBe(1);
-    expect(fs.existsSync(path.join(
-      PLUGIN_STORING_PATH,
-      'growilabs',
-      'growi-plugin-theme-vivid-internet',
-    ))).toBeTruthy();
+    expect(
+      fs.existsSync(
+        path.join(
+          PLUGIN_STORING_PATH,
+          'growilabs',
+          'growi-plugin-theme-vivid-internet',
+        ),
+      ),
+    ).toBeTruthy();
   });
 
-  it('findThemePlugin() should return data with metadata and manifest', async() => {
+  it('findThemePlugin() should return data with metadata and manifest', async () => {
     // confirm
-    const count = await GrowiPlugin.count({ 'meta.name': 'growi-plugin-theme-vivid-internet' });
+    const count = await GrowiPlugin.count({
+      'meta.name': 'growi-plugin-theme-vivid-internet',
+    });
     expect(count).toBe(1);
 
     // when
@@ -87,8 +102,10 @@ describe('Installing a GROWI theme plugin', () => {
     expect(results.growiPlugin).not.toBeNull();
     expect(results.themeMetadata).not.toBeNull();
     expect(results.themeHref).not.toBeNull();
-    expect(results.themeHref
-      .startsWith('/static/plugins/growilabs/growi-plugin-theme-vivid-internet/dist/assets/style-')).toBeTruthy();
+    expect(
+      results.themeHref?.startsWith(
+        '/static/plugins/growilabs/growi-plugin-theme-vivid-internet/dist/assets/style-',
+      ),
+    ).toBeTruthy();
   });
-
 });

+ 190 - 123
apps/app/src/features/growi-plugin/server/services/growi-plugin/growi-plugin.ts

@@ -1,20 +1,24 @@
-import fs, { readFileSync } from 'fs';
-import path from 'path';
-import { pipeline } from 'stream/promises';
-
-import { GrowiPluginType } from '@growi/core';
 import type { GrowiThemeMetadata, ViteManifest } from '@growi/core';
+import { GrowiPluginType } from '@growi/core';
 import type { GrowiPluginPackageData } from '@growi/pluginkit';
-import { importPackageJson, validateGrowiDirective } from '@growi/pluginkit/dist/v4/server/index.cjs';
+import {
+  importPackageJson,
+  validateGrowiDirective,
+} from '@growi/pluginkit/dist/v4/server/index.cjs';
 // eslint-disable-next-line no-restricted-imports
 import axios from 'axios';
+import fs, { readFileSync } from 'fs';
 import type mongoose from 'mongoose';
+import path from 'path';
+import { pipeline } from 'stream/promises';
 import unzipStream from 'unzip-stream';
 
 import loggerFactory from '~/utils/logger';
 
 import type {
-  IGrowiPlugin, IGrowiPluginOrigin, IGrowiPluginMeta,
+  IGrowiPlugin,
+  IGrowiPluginMeta,
+  IGrowiPluginOrigin,
 } from '../../../interfaces';
 import { PLUGIN_EXPRESS_STATIC_DIR, PLUGIN_STORING_PATH } from '../../consts';
 import { GrowiPlugin } from '../../models';
@@ -25,12 +29,25 @@ import { generateThemePluginMeta } from './generate-theme-plugin-meta';
 
 const logger = loggerFactory('growi:plugins:plugin-utils');
 
-export type GrowiPluginResourceEntries = [installedPath: string, href: string][];
+export type GrowiPluginResourceEntries = [
+  installedPath: string,
+  href: string,
+][];
 
-function retrievePluginManifest(growiPlugin: IGrowiPlugin): ViteManifest | undefined {
+function retrievePluginManifest(
+  growiPlugin: IGrowiPlugin,
+): ViteManifest | undefined {
   // ref: https://vitejs.dev/guide/migration.html#manifest-files-are-now-generated-in-vite-directory-by-default
-  const manifestPathByVite4 = path.join(PLUGIN_STORING_PATH, growiPlugin.installedPath, 'dist/manifest.json');
-  const manifestPath = path.join(PLUGIN_STORING_PATH, growiPlugin.installedPath, 'dist/.vite/manifest.json');
+  const manifestPathByVite4 = path.join(
+    PLUGIN_STORING_PATH,
+    growiPlugin.installedPath,
+    'dist/manifest.json',
+  );
+  const manifestPath = path.join(
+    PLUGIN_STORING_PATH,
+    growiPlugin.installedPath,
+    'dist/.vite/manifest.json',
+  );
 
   const isManifestByVite4Exists = fs.existsSync(manifestPathByVite4);
   const isManifestExists = fs.existsSync(manifestPath);
@@ -46,25 +63,23 @@ function retrievePluginManifest(growiPlugin: IGrowiPlugin): ViteManifest | undef
   return JSON.parse(manifestStr);
 }
 
-
 type FindThemePluginResult = {
-  growiPlugin: IGrowiPlugin,
-  themeMetadata: GrowiThemeMetadata,
-  themeHref: string,
-}
+  growiPlugin: IGrowiPlugin;
+  themeMetadata: GrowiThemeMetadata;
+  themeHref: string | undefined;
+};
 
 export interface IGrowiPluginService {
-  install(origin: IGrowiPluginOrigin): Promise<string>
-  findThemePlugin(theme: string): Promise<FindThemePluginResult | null>
-  retrieveAllPluginResourceEntries(): Promise<GrowiPluginResourceEntries>
-  downloadNotExistPluginRepositories(): Promise<void>
+  install(origin: IGrowiPluginOrigin): Promise<string>;
+  findThemePlugin(theme: string): Promise<FindThemePluginResult | null>;
+  retrieveAllPluginResourceEntries(): Promise<GrowiPluginResourceEntries>;
+  downloadNotExistPluginRepositories(): Promise<void>;
 }
 
 export class GrowiPluginService implements IGrowiPluginService {
-
   /*
-  * Downloading a non-existent repository to the file system
-  */
+   * Downloading a non-existent repository to the file system
+   */
   async downloadNotExistPluginRepositories(): Promise<void> {
     try {
       // find all growi plugin documents
@@ -72,69 +87,93 @@ export class GrowiPluginService implements IGrowiPluginService {
 
       // if not exists repository in file system, download latest plugin repository
       for await (const growiPlugin of growiPlugins) {
-        let pluginPath :fs.PathLike|undefined;
-        let organizationName :fs.PathLike|undefined;
+        let pluginPath: fs.PathLike | undefined;
+        let organizationName: fs.PathLike | undefined;
         try {
-          pluginPath = this.joinAndValidatePath(PLUGIN_STORING_PATH, growiPlugin.installedPath);
-          organizationName = this.joinAndValidatePath(PLUGIN_STORING_PATH, growiPlugin.organizationName);
-        }
-        catch (err) {
+          pluginPath = this.joinAndValidatePath(
+            PLUGIN_STORING_PATH,
+            growiPlugin.installedPath,
+          );
+          organizationName = this.joinAndValidatePath(
+            PLUGIN_STORING_PATH,
+            growiPlugin.organizationName,
+          );
+        } catch (err) {
           logger.error(err);
           continue;
         }
         if (fs.existsSync(pluginPath)) {
-          continue;
-        }
-        else {
+        } else {
           if (!fs.existsSync(organizationName)) {
             fs.mkdirSync(organizationName);
           }
 
           // TODO: imprv Document version and repository version possibly different.
-          const ghUrl = new GitHubUrl(growiPlugin.origin.url, growiPlugin.origin.ghBranch);
+          const ghUrl = new GitHubUrl(
+            growiPlugin.origin.url,
+            growiPlugin.origin.ghBranch,
+          );
           const { reposName, archiveUrl, extractedArchiveDirName } = ghUrl;
 
-          const zipFilePath = path.join(PLUGIN_STORING_PATH, `${extractedArchiveDirName}.zip`);
+          const zipFilePath = path.join(
+            PLUGIN_STORING_PATH,
+            `${extractedArchiveDirName}.zip`,
+          );
           const unzippedPath = PLUGIN_STORING_PATH;
-          const unzippedReposPath = path.join(PLUGIN_STORING_PATH, `${reposName}-${extractedArchiveDirName}`);
+          const unzippedReposPath = path.join(
+            PLUGIN_STORING_PATH,
+            `${reposName}-${extractedArchiveDirName}`,
+          );
 
           try {
             // download github repository to local file system
             await this.download(archiveUrl, zipFilePath);
             await this.unzip(zipFilePath, unzippedPath);
             fs.renameSync(unzippedReposPath, pluginPath);
-          }
-          catch (err) {
+          } catch (err) {
             // clean up, documents are not operated
-            if (fs.existsSync(unzippedReposPath)) await fs.promises.rm(unzippedReposPath, { recursive: true });
-            if (fs.existsSync(pluginPath)) await fs.promises.rm(pluginPath, { recursive: true });
+            if (fs.existsSync(unzippedReposPath))
+              await fs.promises.rm(unzippedReposPath, { recursive: true });
+            if (fs.existsSync(pluginPath))
+              await fs.promises.rm(pluginPath, { recursive: true });
             logger.error(err);
           }
-
-          continue;
         }
       }
-    }
-    catch (err) {
+    } catch (err) {
       logger.error(err);
     }
   }
 
   /*
-  * Install a plugin from URL and save it in the DB and file system.
-  */
+   * Install a plugin from URL and save it in the DB and file system.
+   */
   async install(origin: IGrowiPluginOrigin): Promise<string> {
     const ghUrl = new GitHubUrl(origin.url, origin.ghBranch);
-    const {
-      organizationName, reposName, archiveUrl, extractedArchiveDirName,
-    } = ghUrl;
+    const { organizationName, reposName, archiveUrl, extractedArchiveDirName } =
+      ghUrl;
 
     const installedPath = `${organizationName}/${reposName}`;
 
-    const organizationPath = path.join(PLUGIN_STORING_PATH, organizationName);
-    const zipFilePath = path.join(organizationPath, `${reposName}-${extractedArchiveDirName}.zip`);
-    const temporaryReposPath = path.join(organizationPath, `${reposName}-${extractedArchiveDirName}`);
-    const reposPath = path.join(organizationPath, reposName);
+    const organizationPath = this.joinAndValidatePath(
+      PLUGIN_STORING_PATH,
+      organizationName,
+    );
+    const zipFilePath = this.joinAndValidatePath(
+      PLUGIN_STORING_PATH,
+      organizationName,
+      `${reposName}-${extractedArchiveDirName}.zip`,
+    );
+    const temporaryReposPath = this.joinAndValidatePath(
+      PLUGIN_STORING_PATH,
+      organizationName,
+      `${reposName}-${extractedArchiveDirName}`,
+    );
+    const reposPath = this.joinAndValidatePath(
+      PLUGIN_STORING_PATH,
+      organizationName,
+      reposName,
+    );
 
     if (!fs.existsSync(organizationPath)) fs.mkdirSync(organizationPath);
 
@@ -146,22 +185,27 @@ export class GrowiPluginService implements IGrowiPluginService {
       await this.unzip(zipFilePath, organizationPath);
 
       // detect plugins
-      plugins = await GrowiPluginService.detectPlugins(origin, organizationName, reposName, { packageRootPath: temporaryReposPath });
+      plugins = await GrowiPluginService.detectPlugins(
+        origin,
+        organizationName,
+        reposName,
+        { packageRootPath: temporaryReposPath },
+      );
 
       // remove the old repository from the storing path
-      if (fs.existsSync(reposPath)) await fs.promises.rm(reposPath, { recursive: true });
+      if (fs.existsSync(reposPath))
+        await fs.promises.rm(reposPath, { recursive: true });
 
       // move new repository from temporary path to storing path.
       fs.renameSync(temporaryReposPath, reposPath);
-    }
-    catch (err) {
+    } catch (err) {
       logger.error(err);
       throw err;
-    }
-    finally {
+    } finally {
       // clean up
       if (fs.existsSync(zipFilePath)) await fs.promises.rm(zipFilePath);
-      if (fs.existsSync(temporaryReposPath)) await fs.promises.rm(temporaryReposPath, { recursive: true });
+      if (fs.existsSync(temporaryReposPath))
+        await fs.promises.rm(temporaryReposPath, { recursive: true });
     }
 
     try {
@@ -172,10 +216,10 @@ export class GrowiPluginService implements IGrowiPluginService {
       await this.savePluginMetaData(plugins);
 
       return plugins[0].meta.name;
-    }
-    catch (err) {
+    } catch (err) {
       // uninstall
-      if (fs.existsSync(reposPath)) await fs.promises.rm(reposPath, { recursive: true });
+      if (fs.existsSync(reposPath))
+        await fs.promises.rm(reposPath, { recursive: true });
       await this.deleteOldPluginDocument(installedPath);
 
       logger.error(err);
@@ -198,16 +242,17 @@ export class GrowiPluginService implements IGrowiPluginService {
         .then((res) => {
           if (res.status === 200) {
             const file = fs.createWriteStream(filePath);
-            res.data.pipe(file)
+            res.data
+              .pipe(file)
               .on('close', () => file.close())
               .on('finish', () => {
                 return resolve();
               });
-          }
-          else {
+          } else {
             rejects(res.status);
           }
-        }).catch((err) => {
+        })
+        .catch((err) => {
           logger.error(err);
           // eslint-disable-next-line prefer-promise-reject-errors
           rejects('Failed to download file.');
@@ -215,12 +260,17 @@ export class GrowiPluginService implements IGrowiPluginService {
     });
   }
 
-  private async unzip(zipFilePath: fs.PathLike, destPath: fs.PathLike): Promise<void> {
+  private async unzip(
+    zipFilePath: fs.PathLike,
+    destPath: fs.PathLike,
+  ): Promise<void> {
     try {
       const readZipStream = fs.createReadStream(zipFilePath);
-      await pipeline(readZipStream, unzipStream.Extract({ path: destPath.toString() }));
-    }
-    catch (err) {
+      await pipeline(
+        readZipStream,
+        unzipStream.Extract({ path: destPath.toString() }),
+      );
+    } catch (err) {
       logger.error(err);
       throw new Error('Failed to unzip.');
     }
@@ -232,32 +282,44 @@ export class GrowiPluginService implements IGrowiPluginService {
 
   // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, max-len
   private static async detectPlugins(
-      origin: IGrowiPluginOrigin, ghOrganizationName: string, ghReposName: string,
-      opts?: {
-        packageRootPath?: string,
-        parentPackageData?: GrowiPluginPackageData,
-      },
+    origin: IGrowiPluginOrigin,
+    ghOrganizationName: string,
+    ghReposName: string,
+    opts?: {
+      packageRootPath?: string;
+      parentPackageData?: GrowiPluginPackageData;
+    },
   ): Promise<IGrowiPlugin[]> {
-    const packageRootPath = opts?.packageRootPath ?? path.resolve(PLUGIN_STORING_PATH, ghOrganizationName, ghReposName);
+    const packageRootPath =
+      opts?.packageRootPath ??
+      path.resolve(PLUGIN_STORING_PATH, ghOrganizationName, ghReposName);
 
     // validate
     const validationData = await validateGrowiDirective(packageRootPath);
 
-    const packageData = opts?.parentPackageData ?? importPackageJson(packageRootPath);
+    const packageData =
+      opts?.parentPackageData ?? importPackageJson(packageRootPath);
 
     const { growiPlugin } = validationData;
     const {
-      name: packageName, description: packageDesc, author: packageAuthor,
+      name: packageName,
+      description: packageDesc,
+      author: packageAuthor,
     } = packageData;
 
     // detect sub plugins for monorepo
     if (growiPlugin.isMonorepo && growiPlugin.packages != null) {
       const plugins = await Promise.all(
-        growiPlugin.packages.map(async(subPackagePath) => {
-          return this.detectPlugins(origin, ghOrganizationName, ghReposName, {
-            packageRootPath: path.join(packageRootPath, subPackagePath),
-            parentPackageData: packageData,
-          });
+        growiPlugin.packages.map(async (subPackagePath) => {
+          return GrowiPluginService.detectPlugins(
+            origin,
+            ghOrganizationName,
+            ghReposName,
+            {
+              packageRootPath: path.join(packageRootPath, subPackagePath),
+              parentPackageData: packageData,
+            },
+          );
         }),
       );
       return plugins.flat();
@@ -310,31 +372,32 @@ export class GrowiPluginService implements IGrowiPluginService {
 
     try {
       await GrowiPlugin.deleteOne({ _id: pluginId });
-    }
-    catch (err) {
+    } catch (err) {
       logger.error(err);
       throw new Error('Failed to delete plugin from GrowiPlugin documents.');
     }
 
     let growiPluginsPath: fs.PathLike | undefined;
     try {
-      growiPluginsPath = this.joinAndValidatePath(PLUGIN_STORING_PATH, growiPlugins.installedPath);
-    }
-    catch (err) {
+      growiPluginsPath = this.joinAndValidatePath(
+        PLUGIN_STORING_PATH,
+        growiPlugins.installedPath,
+      );
+    } catch (err) {
       logger.error(err);
-      throw new Error('The installedPath for the plugin is invalid, and the plugin has already been removed.');
+      throw new Error(
+        'The installedPath for the plugin is invalid, and the plugin has already been removed.',
+      );
     }
 
     if (growiPluginsPath && fs.existsSync(growiPluginsPath)) {
       try {
         await deleteFolder(growiPluginsPath);
-      }
-      catch (err) {
+      } catch (err) {
         logger.error(err);
         throw new Error('Failed to delete plugin repository.');
       }
-    }
-    else {
+    } else {
       logger.warn(`Plugin path does not exist : ${growiPluginsPath}`);
     }
     return growiPlugins.meta.name;
@@ -346,51 +409,56 @@ export class GrowiPluginService implements IGrowiPluginService {
 
     try {
       // retrieve plugin manifests
-      const growiPlugins = await GrowiPlugin.findEnabledPluginsByType(GrowiPluginType.Theme);
+      const growiPlugins = await GrowiPlugin.findEnabledPluginsByType(
+        GrowiPluginType.Theme,
+      );
 
-      growiPlugins
-        .forEach((growiPlugin) => {
-          const themeMetadatas = growiPlugin.meta.themes;
-          const themeMetadata = themeMetadatas.find(t => t.name === theme);
+      growiPlugins.forEach((growiPlugin) => {
+        const themeMetadatas = growiPlugin.meta.themes;
+        const themeMetadata = themeMetadatas.find((t) => t.name === theme);
 
-          // found
-          if (themeMetadata != null) {
-            matchedPlugin = growiPlugin;
-            matchedThemeMetadata = themeMetadata;
-          }
-        });
-    }
-    catch (e) {
-      logger.error(`Could not find the theme '${theme}' from GrowiPlugin documents.`, e);
+        // found
+        if (themeMetadata != null) {
+          matchedPlugin = growiPlugin;
+          matchedThemeMetadata = themeMetadata;
+        }
+      });
+    } catch (e) {
+      logger.error(
+        `Could not find the theme '${theme}' from GrowiPlugin documents.`,
+        e,
+      );
     }
 
     if (matchedPlugin == null || matchedThemeMetadata == null) {
       return null;
     }
 
-    let themeHref;
+    let themeHref: string | undefined;
     try {
       const manifest = retrievePluginManifest(matchedPlugin);
       if (manifest == null) {
         throw new Error('The manifest file does not exists');
       }
       themeHref = `${PLUGIN_EXPRESS_STATIC_DIR}/${matchedPlugin.installedPath}/dist/${manifest[matchedThemeMetadata.manifestKey].file}`;
-    }
-    catch (e) {
+    } catch (e) {
       logger.error(`Could not read manifest file for the theme '${theme}'`, e);
     }
 
-    return { growiPlugin: matchedPlugin, themeMetadata: matchedThemeMetadata, themeHref };
+    return {
+      growiPlugin: matchedPlugin,
+      themeMetadata: matchedThemeMetadata,
+      themeHref,
+    };
   }
 
   async retrieveAllPluginResourceEntries(): Promise<GrowiPluginResourceEntries> {
-
     const entries: GrowiPluginResourceEntries = [];
 
     try {
       const growiPlugins = await GrowiPlugin.findEnabledPlugins();
 
-      growiPlugins.forEach(async(growiPlugin) => {
+      growiPlugins.forEach(async (growiPlugin) => {
         try {
           const { types } = growiPlugin.meta;
           const manifest = await retrievePluginManifest(growiPlugin);
@@ -405,35 +473,34 @@ export class GrowiPluginService implements IGrowiPluginService {
             entries.push([growiPlugin.installedPath, href]);
           }
           // add link
-          if (types.includes(GrowiPluginType.Script) || types.includes(GrowiPluginType.Style)) {
+          if (
+            types.includes(GrowiPluginType.Script) ||
+            types.includes(GrowiPluginType.Style)
+          ) {
             const href = `${PLUGIN_EXPRESS_STATIC_DIR}/${growiPlugin.installedPath}/dist/${manifest['client-entry.tsx'].css}`;
             entries.push([growiPlugin.installedPath, href]);
           }
-        }
-        catch (e) {
+        } catch (e) {
           logger.warn(e);
         }
       });
-    }
-    catch (e) {
+    } catch (e) {
       logger.error('Could not retrieve GrowiPlugin documents.', e);
     }
 
     return entries;
   }
 
-  private joinAndValidatePath(baseDir: string, ...paths: string[]):fs.PathLike {
+  private joinAndValidatePath(baseDir: string, ...paths: string[]): string {
     const joinedPath = path.join(baseDir, ...paths);
     if (!joinedPath.startsWith(baseDir)) {
       throw new Error(
-        'Invalid plugin path detected! Access outside of the allowed directory is not permitted.'
-        + `\nAttempted Path: ${joinedPath}`,
+        'Invalid plugin path detected! Access outside of the allowed directory is not permitted.' +
+          `\nAttempted Path: ${joinedPath}`,
       );
     }
     return joinedPath;
   }
-
 }
 
-
 export const growiPluginService = new GrowiPluginService();

+ 14 - 12
apps/app/src/features/rate-limiter/config/index.ts

@@ -1,11 +1,11 @@
 export type IApiRateLimitConfig = {
-  method: string,
-  maxRequests: number,
-  usersPerIpProspection?: number,
-}
+  method: string;
+  maxRequests: number;
+  usersPerIpProspection?: number;
+};
 export type IApiRateLimitEndpointMap = {
-  [endpoint: string]: IApiRateLimitConfig
-}
+  [endpoint: string]: IApiRateLimitConfig;
+};
 
 export const DEFAULT_MAX_REQUESTS = 500;
 export const DEFAULT_DURATION_SEC = 60;
@@ -59,12 +59,14 @@ export const defaultConfig: IApiRateLimitEndpointMap = {
 };
 
 const isDev = process.env.NODE_ENV === 'development';
-const defaultConfigWithRegExpForDev: IApiRateLimitEndpointMap = isDev ? {
-  '/__nextjs_original-stack-frame': {
-    method: 'GET',
-    maxRequests: Infinity,
-  },
-} : {};
+const defaultConfigWithRegExpForDev: IApiRateLimitEndpointMap = isDev
+  ? {
+      '/__nextjs_original-stack-frame': {
+        method: 'GET',
+        maxRequests: Infinity,
+      },
+    }
+  : {};
 
 // default config with reg exp
 export const defaultConfigWithRegExp: IApiRateLimitEndpointMap = {

+ 10 - 8
apps/app/src/features/rate-limiter/middleware/consume-points.integ.ts

@@ -1,6 +1,10 @@
 import { faker } from '@faker-js/faker';
 
-const testRateLimitErrorWhenExceedingMaxRequests = async(method: string, key: string, maxRequests: number): Promise<void> => {
+const testRateLimitErrorWhenExceedingMaxRequests = async (
+  method: string,
+  key: string,
+  maxRequests: number,
+): Promise<void> => {
   // dynamic import is used because rateLimiterMongo needs to be initialized after connecting to DB
   // Issue: https://github.com/animir/node-rate-limiter-flexible/issues/216
   const { consumePoints } = await import('./consume-points');
@@ -20,8 +24,7 @@ const testRateLimitErrorWhenExceedingMaxRequests = async(method: string, key: st
         throw new Error('Exception occurred');
       }
     }
-  }
-  catch (err) {
+  } catch (err) {
     // Expect rate limit error to be called
     expect(err.message).not.toBe('Exception occurred');
     // Expect rate limit error at maxRequest + 1
@@ -29,9 +32,8 @@ const testRateLimitErrorWhenExceedingMaxRequests = async(method: string, key: st
   }
 };
 
-
-describe('consume-points.ts', async() => {
-  it('Should trigger a rate limit error when maxRequest is exceeded (maxRequest: 1)', async() => {
+describe('consume-points.ts', async () => {
+  it('Should trigger a rate limit error when maxRequest is exceeded (maxRequest: 1)', async () => {
     // setup
     const method = 'GET';
     const key = 'test-key-1';
@@ -40,7 +42,7 @@ describe('consume-points.ts', async() => {
     await testRateLimitErrorWhenExceedingMaxRequests(method, key, maxRequests);
   });
 
-  it('Should trigger a rate limit error when maxRequest is exceeded (maxRequest: 500)', async() => {
+  it('Should trigger a rate limit error when maxRequest is exceeded (maxRequest: 500)', async () => {
     // setup
     const method = 'GET';
     const key = 'test-key-2';
@@ -49,7 +51,7 @@ describe('consume-points.ts', async() => {
     await testRateLimitErrorWhenExceedingMaxRequests(method, key, maxRequests);
   });
 
-  it('Should trigger a rate limit error when maxRequest is exceeded (maxRequest: {random integer between 1 and 1000})', async() => {
+  it('Should trigger a rate limit error when maxRequest is exceeded (maxRequest: {random integer between 1 and 1000})', async () => {
     // setup
     const method = 'GET';
     const key = 'test-key-3';

+ 15 - 5
apps/app/src/features/rate-limiter/middleware/consume-points.ts

@@ -1,11 +1,14 @@
-import { type RateLimiterRes } from 'rate-limiter-flexible';
+import type { RateLimiterRes } from 'rate-limiter-flexible';
 
 import { DEFAULT_MAX_REQUESTS, type IApiRateLimitConfig } from '../config';
 
 import { rateLimiterFactory } from './rate-limiter-factory';
 
-export const consumePoints = async(
-    method: string, key: string | null, customizedConfig?: IApiRateLimitConfig, maxRequestsMultiplier?: number,
+export const consumePoints = async (
+  method: string,
+  key: string | null,
+  customizedConfig?: IApiRateLimitConfig,
+  maxRequestsMultiplier?: number,
 ): Promise<RateLimiterRes | undefined> => {
   if (key == null) {
     return;
@@ -14,7 +17,11 @@ export const consumePoints = async(
   let maxRequests = DEFAULT_MAX_REQUESTS;
 
   // use customizedConfig
-  if (customizedConfig != null && (customizedConfig.method.includes(method) || customizedConfig.method === 'ALL')) {
+  if (
+    customizedConfig != null &&
+    (customizedConfig.method.includes(method) ||
+      customizedConfig.method === 'ALL')
+  ) {
     maxRequests = customizedConfig.maxRequests;
   }
 
@@ -23,7 +30,10 @@ export const consumePoints = async(
     maxRequests *= maxRequestsMultiplier;
   }
 
-  const rateLimiter = rateLimiterFactory.getOrCreateRateLimiter(key, maxRequests);
+  const rateLimiter = rateLimiterFactory.getOrCreateRateLimiter(
+    key,
+    maxRequests,
+  );
 
   const pointsToConsume = 1;
   const rateLimiterRes = await rateLimiter.consume(key, pointsToConsume);

+ 26 - 22
apps/app/src/features/rate-limiter/middleware/factory.ts

@@ -1,11 +1,14 @@
 import type { IUserHasId } from '@growi/core';
 import type { Handler, Request } from 'express';
 import md5 from 'md5';
-import { type RateLimiterRes } from 'rate-limiter-flexible';
+import type { RateLimiterRes } from 'rate-limiter-flexible';
 
 import loggerFactory from '~/utils/logger';
 
-import { DEFAULT_USERS_PER_IP_PROSPECTION, type IApiRateLimitConfig } from '../config';
+import {
+  DEFAULT_USERS_PER_IP_PROSPECTION,
+  type IApiRateLimitConfig,
+} from '../config';
 import { generateApiRateLimitConfig } from '../utils/config-generator';
 
 import { consumePoints } from './consume-points';
@@ -22,10 +25,11 @@ const apiRateLimitConfig = generateApiRateLimitConfig();
 const configWithoutRegExp = apiRateLimitConfig.withoutRegExp;
 const configWithRegExp = apiRateLimitConfig.withRegExp;
 const allRegExp = new RegExp(Object.keys(configWithRegExp).join('|'));
-const keysWithRegExp = Object.keys(configWithRegExp).map(key => new RegExp(`^${key}`));
+const keysWithRegExp = Object.keys(configWithRegExp).map(
+  (key) => new RegExp(`^${key}`),
+);
 const valuesWithRegExp = Object.values(configWithRegExp);
 
-
 /**
  * consume per user per endpoint
  * @param method
@@ -33,8 +37,10 @@ const valuesWithRegExp = Object.values(configWithRegExp);
  * @param customizedConfig
  * @returns
  */
-const consumePointsByUser = async(
-    method: string, key: string | null, customizedConfig?: IApiRateLimitConfig,
+const consumePointsByUser = async (
+  method: string,
+  key: string | null,
+  customizedConfig?: IApiRateLimitConfig,
 ): Promise<RateLimiterRes | undefined> => {
   return consumePoints(method, key, customizedConfig);
 };
@@ -46,24 +52,25 @@ const consumePointsByUser = async(
  * @param customizedConfig
  * @returns
  */
-const consumePointsByIp = async(
-    method: string, key: string | null, customizedConfig?: IApiRateLimitConfig,
+const consumePointsByIp = async (
+  method: string,
+  key: string | null,
+  customizedConfig?: IApiRateLimitConfig,
 ): Promise<RateLimiterRes | undefined> => {
-  const maxRequestsMultiplier = customizedConfig?.usersPerIpProspection ?? DEFAULT_USERS_PER_IP_PROSPECTION;
+  const maxRequestsMultiplier =
+    customizedConfig?.usersPerIpProspection ?? DEFAULT_USERS_PER_IP_PROSPECTION;
   return consumePoints(method, key, customizedConfig, maxRequestsMultiplier);
 };
 
-
 export const middlewareFactory = (): Handler => {
-
-  return async(req: Request & { user?: IUserHasId }, res, next) => {
-
+  return async (req: Request & { user?: IUserHasId }, res, next) => {
     const endpoint = req.path;
 
     // determine keys
-    const keyForUser: string | null = req.user != null
-      ? md5(`${req.user._id}_${endpoint}_${req.method}`)
-      : null;
+    const keyForUser: string | null =
+      req.user != null
+        ? md5(`${req.user._id}_${endpoint}_${req.method}`)
+        : null;
     const keyForIp: string = md5(`${req.ip}_${endpoint}_${req.method}`);
 
     // determine customized config
@@ -71,8 +78,7 @@ export const middlewareFactory = (): Handler => {
     const configForEndpoint = configWithoutRegExp[endpoint];
     if (configForEndpoint) {
       customizedConfig = configForEndpoint;
-    }
-    else if (allRegExp.test(endpoint)) {
+    } else if (allRegExp.test(endpoint)) {
       keysWithRegExp.forEach((key, index) => {
         if (key.test(endpoint)) {
           customizedConfig = valuesWithRegExp[index];
@@ -84,8 +90,7 @@ export const middlewareFactory = (): Handler => {
     if (req.user != null) {
       try {
         await consumePointsByUser(req.method, keyForUser, customizedConfig);
-      }
-      catch {
+      } catch {
         logger.error(`${req.user._id}: too many request at ${endpoint}`);
         return res.sendStatus(429);
       }
@@ -94,8 +99,7 @@ export const middlewareFactory = (): Handler => {
     // check for ip
     try {
       await consumePointsByIp(req.method, keyForIp, customizedConfig);
-    }
-    catch {
+    } catch {
       logger.error(`${req.ip}: too many request at ${endpoint}`);
       return res.sendStatus(429);
     }

+ 4 - 3
apps/app/src/features/rate-limiter/middleware/rate-limiter-factory.ts

@@ -1,10 +1,12 @@
 import { connection } from 'mongoose';
-import { type IRateLimiterMongoOptions, RateLimiterMongo } from 'rate-limiter-flexible';
+import {
+  type IRateLimiterMongoOptions,
+  RateLimiterMongo,
+} from 'rate-limiter-flexible';
 
 import { DEFAULT_DURATION_SEC } from '../config';
 
 class RateLimiterFactory {
-
   private rateLimiters: Map<string, RateLimiterMongo> = new Map();
 
   getOrCreateRateLimiter(key: string, maxRequests: number): RateLimiterMongo {
@@ -24,7 +26,6 @@ class RateLimiterFactory {
 
     return rateLimiter;
   }
-
 }
 
 export const rateLimiterFactory = new RateLimiterFactory();

+ 30 - 17
apps/app/src/features/rate-limiter/utils/config-generator.ts

@@ -1,18 +1,21 @@
 import type { IApiRateLimitEndpointMap } from '../config';
-import {
-  defaultConfig, defaultConfigWithRegExp,
-} from '../config';
+import { defaultConfig, defaultConfigWithRegExp } from '../config';
 
 const envVar = process.env;
 
 // https://regex101.com/r/aNDjmI/1
 const regExp = /^API_RATE_LIMIT_(\w+)_ENDPOINT(_WITH_REGEXP)?$/;
 
-const generateApiRateLimitConfigFromEndpoint = (envVar: NodeJS.ProcessEnv, targets: string[], withRegExp: boolean): IApiRateLimitEndpointMap => {
+const generateApiRateLimitConfigFromEndpoint = (
+  envVar: NodeJS.ProcessEnv,
+  targets: string[],
+  withRegExp: boolean,
+): IApiRateLimitEndpointMap => {
   const apiRateLimitConfig: IApiRateLimitEndpointMap = {};
   targets.forEach((target) => {
-
-    const endpointKey = withRegExp ? `API_RATE_LIMIT_${target}_ENDPOINT_WITH_REGEXP` : `API_RATE_LIMIT_${target}_ENDPOINT`;
+    const endpointKey = withRegExp
+      ? `API_RATE_LIMIT_${target}_ENDPOINT_WITH_REGEXP`
+      : `API_RATE_LIMIT_${target}_ENDPOINT`;
 
     const endpoint = envVar[endpointKey];
 
@@ -43,26 +46,26 @@ const generateApiRateLimitConfigFromEndpoint = (envVar: NodeJS.ProcessEnv, targe
 };
 
 type ApiRateLimitConfigResult = {
-  'withoutRegExp': IApiRateLimitEndpointMap,
-  'withRegExp': IApiRateLimitEndpointMap
-}
+  withoutRegExp: IApiRateLimitEndpointMap;
+  withRegExp: IApiRateLimitEndpointMap;
+};
 
 export const generateApiRateLimitConfig = (): ApiRateLimitConfigResult => {
-
   const apiRateConfigTargets: string[] = [];
   const apiRateConfigTargetsWithRegExp: string[] = [];
   Object.keys(envVar).forEach((key) => {
     const result = key.match(regExp);
 
-    if (result == null) { return null }
+    if (result == null) {
+      return null;
+    }
 
     const target = result[1];
     const isWithRegExp = result[2] != null;
 
     if (isWithRegExp) {
       apiRateConfigTargetsWithRegExp.push(target);
-    }
-    else {
+    } else {
       apiRateConfigTargets.push(target);
     }
   });
@@ -72,17 +75,27 @@ export const generateApiRateLimitConfig = (): ApiRateLimitConfigResult => {
   apiRateConfigTargetsWithRegExp.sort();
 
   // get config
-  const apiRateLimitConfig = generateApiRateLimitConfigFromEndpoint(envVar, apiRateConfigTargets, false);
-  const apiRateLimitConfigWithRegExp = generateApiRateLimitConfigFromEndpoint(envVar, apiRateConfigTargetsWithRegExp, true);
+  const apiRateLimitConfig = generateApiRateLimitConfigFromEndpoint(
+    envVar,
+    apiRateConfigTargets,
+    false,
+  );
+  const apiRateLimitConfigWithRegExp = generateApiRateLimitConfigFromEndpoint(
+    envVar,
+    apiRateConfigTargetsWithRegExp,
+    true,
+  );
 
   const config = { ...defaultConfig, ...apiRateLimitConfig };
-  const configWithRegExp = { ...defaultConfigWithRegExp, ...apiRateLimitConfigWithRegExp };
+  const configWithRegExp = {
+    ...defaultConfigWithRegExp,
+    ...apiRateLimitConfigWithRegExp,
+  };
 
   const result: ApiRateLimitConfigResult = {
     withoutRegExp: config,
     withRegExp: configWithRegExp,
   };
 
-
   return result;
 };

+ 5 - 3
apps/app/src/models/admin/growi-archive-import-option.ts

@@ -1,12 +1,15 @@
 import { ImportMode } from './import-mode';
 
 export class GrowiArchiveImportOption {
-
   collectionName: string;
 
   mode: ImportMode;
 
-  constructor(collectionName: string, mode: ImportMode = ImportMode.insert, initProps = {}) {
+  constructor(
+    collectionName: string,
+    mode: ImportMode = ImportMode.insert,
+    initProps = {},
+  ) {
     this.collectionName = collectionName;
     this.mode = mode;
 
@@ -14,5 +17,4 @@ export class GrowiArchiveImportOption {
       this[key] = value;
     });
   }
-
 }

+ 1 - 1
apps/app/src/models/admin/import-mode.ts

@@ -3,4 +3,4 @@ export const ImportMode = {
   upsert: 'upsert',
   flushAndInsert: 'flushAndInsert',
 } as const;
-export type ImportMode = typeof ImportMode[keyof typeof ImportMode];
+export type ImportMode = (typeof ImportMode)[keyof typeof ImportMode];

+ 8 - 4
apps/app/src/models/admin/import-option-for-pages.ts

@@ -11,7 +11,6 @@ const DEFAULT_PROPS = {
 };
 
 export class ImportOptionForPages extends GrowiArchiveImportOption {
-
   isOverwriteAuthorWithCurrentUser;
 
   makePublicForGrant2;
@@ -22,12 +21,17 @@ export class ImportOptionForPages extends GrowiArchiveImportOption {
 
   initPageMetadatas;
 
-  constructor(collectionName: string, mode: ImportMode = ImportMode.insert, initProps = DEFAULT_PROPS) {
+  constructor(
+    collectionName: string,
+    mode: ImportMode = ImportMode.insert,
+    initProps = DEFAULT_PROPS,
+  ) {
     super(collectionName, mode, initProps);
   }
-
 }
 
-export const isImportOptionForPages = (opt: GrowiArchiveImportOption): opt is ImportOptionForPages => {
+export const isImportOptionForPages = (
+  opt: GrowiArchiveImportOption,
+): opt is ImportOptionForPages => {
   return 'isOverwriteAuthorWithCurrentUser' in opt;
 };

+ 5 - 3
apps/app/src/models/admin/import-option-for-revisions.ts

@@ -7,9 +7,11 @@ const DEFAULT_PROPS = {
 };
 
 export class ImportOptionForRevisions extends GrowiArchiveImportOption {
-
-  constructor(collectionName: string, mode: ImportMode = ImportMode.insert, initProps = DEFAULT_PROPS) {
+  constructor(
+    collectionName: string,
+    mode: ImportMode = ImportMode.insert,
+    initProps = DEFAULT_PROPS,
+  ) {
     super(collectionName, mode, initProps);
   }
-
 }

+ 0 - 2
apps/app/src/models/cdn-resource.js

@@ -2,13 +2,11 @@
  * Value Object
  */
 class CdnResource {
-
   constructor(name, url, outDir) {
     this.name = name;
     this.url = url;
     this.outDir = outDir;
   }
-
 }
 
 module.exports = CdnResource;

+ 0 - 4
apps/app/src/models/linked-page-path.js

@@ -7,9 +7,7 @@ const { isTrashPage } = pagePathUtils;
  * Linked Array Structured PagePath Model
  */
 export default class LinkedPagePath {
-
   constructor(path) {
-
     const pagePath = new DevidedPagePath(path);
 
     this.path = path;
@@ -18,7 +16,6 @@ export default class LinkedPagePath {
     this.parent = pagePath.isRoot
       ? null
       : new LinkedPagePath(pagePath.former, true);
-
   }
 
   get href() {
@@ -32,5 +29,4 @@ export default class LinkedPagePath {
   get isInTrash() {
     return isTrashPage(this.path);
   }
-
 }

+ 8 - 4
apps/app/src/models/serializers/in-app-notification-snapshot/page-bulk-export-job.ts

@@ -1,17 +1,21 @@
-import { isPopulated } from '@growi/core';
 import type { IPage } from '@growi/core';
+import { isPopulated } from '@growi/core';
 import mongoose from 'mongoose';
 
 import type { IPageBulkExportJob } from '~/features/page-bulk-export/interfaces/page-bulk-export';
 import type { PageModel } from '~/server/models/page';
 
 export interface IPageBulkExportJobSnapshot {
-  path: string
+  path: string;
 }
 
-export const stringifySnapshot = async(exportJob: IPageBulkExportJob): Promise<string | undefined> => {
+export const stringifySnapshot = async (
+  exportJob: IPageBulkExportJob,
+): Promise<string | undefined> => {
   const Page = mongoose.model<IPage, PageModel>('Page');
-  const page = isPopulated(exportJob.page) ? exportJob.page : (await Page.findById(exportJob.page));
+  const page = isPopulated(exportJob.page)
+    ? exportJob.page
+    : await Page.findById(exportJob.page);
 
   if (page != null) {
     return JSON.stringify({

+ 2 - 2
apps/app/src/models/serializers/in-app-notification-snapshot/page.ts

@@ -1,8 +1,8 @@
 import type { IPage, IUser } from '@growi/core';
 
 export interface IPageSnapshot {
-  path: string
-  creator: IUser
+  path: string;
+  creator: IUser;
 }
 
 export const stringifySnapshot = (page: IPage): string => {

+ 1 - 1
apps/app/src/models/serializers/in-app-notification-snapshot/user.ts

@@ -1,7 +1,7 @@
 import type { IUser } from '@growi/core';
 
 export interface IUserSnapshot {
-  username: string
+  username: string;
 }
 
 export const stringifySnapshot = (user: IUser): string => {

+ 0 - 2
apps/app/src/models/vo/external-account-login-error.ts

@@ -1,5 +1,4 @@
 export class ExternalAccountLoginError extends Error {
-
   args?: any;
 
   constructor(message = '', args = undefined) {
@@ -7,5 +6,4 @@ export class ExternalAccountLoginError extends Error {
     this.message = message;
     this.args = args;
   }
-
 }

+ 7 - 5
apps/app/src/pages/[[...path]].page.tsx

@@ -47,7 +47,7 @@ import {
   useIsLocalAccountRegistrationEnabled,
   useIsRomUserAllowedToComment,
   useIsPdfBulkExportEnabled,
-  useIsAiEnabled, useLimitLearnablePageCountPerAssistant, useIsUsersHomepageDeletionEnabled,
+  useIsAiEnabled, useLimitLearnablePageCountPerAssistant, useIsUsersHomepageDeletionEnabled, useIsGuestUser,
 } from '~/stores-universal/context';
 import { useEditingMarkdown } from '~/stores/editor';
 import {
@@ -276,6 +276,7 @@ const Page: NextPageWithLayout<Props> = (props: Props) => {
 
   const { mutate: mutateEditingMarkdown } = useEditingMarkdown();
   const { data: currentPageId, mutate: mutateCurrentPageId } = useCurrentPageId();
+  const { data: isGuestUser } = useIsGuestUser();
 
   const { mutate: mutateIsNotFound } = useIsNotFound();
 
@@ -308,16 +309,17 @@ const Page: NextPageWithLayout<Props> = (props: Props) => {
       mutatePageData();
     }
   }, [
-    revisionId, currentPageId, mutateCurrentPage,
-    mutateCurrentPageYjsDataFromApi, mutateEditingMarkdown, props.isNotFound, props.skipSSR,
+    revisionId, currentPageId,
+    mutateCurrentPage, mutateEditingMarkdown,
+    props.isNotFound, props.skipSSR,
   ]);
 
   // Load current yjs data
   useEffect(() => {
-    if (currentPageId != null && revisionId != null && !props.isNotFound) {
+    if (!isGuestUser && currentPageId != null && revisionId != null && mutateCurrentPageYjsDataFromApi != null && !props.isNotFound) {
       mutateCurrentPageYjsDataFromApi();
     }
-  }, [currentPageId, mutateCurrentPageYjsDataFromApi, props.isNotFound, revisionId]);
+  }, [isGuestUser, currentPageId, mutateCurrentPageYjsDataFromApi, props.isNotFound, revisionId]);
 
   // sync pathname by Shallow Routing https://nextjs.org/docs/routing/shallow-routing
   useEffect(() => {

+ 3 - 0
apps/app/src/server/routes/apiv3/page/update-page.ts

@@ -196,6 +196,9 @@ export const updatePageHandlersFactory: UpdatePageHandlersFactory = (crowi) => {
           options.userRelatedGrantUserGroupIds = userRelatedGrantUserGroupIds;
         }
         previousRevision = await Revision.findById(sanitizeRevisionId);
+
+        // There are cases where "revisionId" is not required for revision updates
+        // See: https://dev.growi.org/651a6f4a008fee2f99187431#origin-%E3%81%AE%E5%BC%B7%E5%BC%B1
         updatedPage = await crowi.pageService.updatePage(currentPage, body, previousRevision?.body ?? null, req.user, options);
       }
       catch (err) {

+ 1 - 1
apps/app/src/server/service/customize.ts

@@ -36,7 +36,7 @@ class CustomizeService implements S2sMessageHandlable {
 
   theme: string;
 
-  themeHref: string;
+  themeHref: string | undefined;
 
   forcedColorScheme?: ColorScheme;
 

+ 7 - 2
apps/app/src/server/service/page/index.ts

@@ -4122,6 +4122,9 @@ class PageService implements IPageService {
     return [...userUnrelatedPreviousGrantedGroups, ...userRelatedGrantedGroups];
   }
 
+
+  // There are cases where "revisionId" is not required for revision updates
+  // See: https://dev.growi.org/651a6f4a008fee2f99187431#origin-%E3%81%AE%E5%BC%B7%E5%BC%B1
   async updatePage(
       pageData: HydratedDocument<PageDocument>,
       body: string | null,
@@ -4271,6 +4274,8 @@ class PageService implements IPageService {
   }
 
 
+  // There are cases where "revisionId" is not required for revision updates
+  // See: https://dev.growi.org/651a6f4a008fee2f99187431#origin-%E3%81%AE%E5%BC%B7%E5%BC%B1
   async updatePageV4(
       pageData: HydratedDocument<PageDocument>, body, previousBody, user, options: IOptionsForUpdate = {},
   ): Promise<HydratedDocument<PageDocument>> {
@@ -4291,10 +4296,10 @@ class PageService implements IPageService {
     let savedPage = await pageData.save();
 
     // Update revision
-    const isBodyPresent = body != null && previousBody != null;
+    const isBodyPresent = body != null;
     const shouldUpdateBody = isBodyPresent;
     if (shouldUpdateBody) {
-      const newRevision = await Revision.prepareRevision(pageData, body, previousBody, user);
+      const newRevision = await Revision.prepareRevision(pageData, body, previousBody, user, options.origin);
       savedPage = await pushRevision(savedPage, newRevision, user);
       await savedPage.populateDataToShowRevision();
     }

+ 3 - 3
apps/app/src/services/general-xss-filter/general-xss-filter.spec.ts

@@ -1,7 +1,6 @@
 import { generalXssFilter } from './general-xss-filter';
 
 describe('generalXssFilter', () => {
-
   test('should be sanitize script tag', () => {
     // Act
     const result = generalXssFilter.process('<script>alert("XSS")</script>');
@@ -12,7 +11,9 @@ describe('generalXssFilter', () => {
 
   test('should be sanitize nested script tag recursively', () => {
     // Act
-    const result = generalXssFilter.process('<scr<script>ipt>alert("XSS")</scr<script>ipt>');
+    const result = generalXssFilter.process(
+      '<scr<script>ipt>alert("XSS")</scr<script>ipt>',
+    );
 
     // Assert
     expect(result).toBe('alert("XSS")');
@@ -35,5 +36,4 @@ describe('generalXssFilter', () => {
     // Assert
     expect(result).toBe('<span>text</span>');
   });
-
 });

+ 4 - 5
apps/app/src/services/general-xss-filter/general-xss-filter.ts

@@ -7,11 +7,12 @@ const option: IFilterXSSOptions = {
   stripIgnoreTag: true,
   stripIgnoreTagBody: false, // see https://github.com/growilabs/growi/pull/505
   css: false,
-  escapeHtml: (html) => { return html }, // resolve https://github.com/growilabs/growi/issues/221
+  escapeHtml: (html) => {
+    return html;
+  }, // resolve https://github.com/growilabs/growi/issues/221
 };
 
 class GeneralXssFilter extends FilterXSS {
-
   override process(document: string | undefined): string {
     let count = 0;
     let currDoc = document;
@@ -26,12 +27,10 @@ class GeneralXssFilter extends FilterXSS {
 
       prevDoc = currDoc;
       currDoc = super.process(currDoc ?? '');
-    }
-    while (currDoc !== prevDoc);
+    } while (currDoc !== prevDoc);
 
     return currDoc;
   }
-
 }
 
 export const generalXssFilter = new GeneralXssFilter(option);

+ 6 - 2
apps/app/src/services/layout/use-should-expand-content.ts

@@ -2,14 +2,18 @@ import type { IPage, IPagePopulatedToShowRevision } from '@growi/core';
 
 import { useIsContainerFluid } from '~/stores-universal/context';
 
-const useDetermineExpandContent = (expandContentWidth?: boolean | null): boolean => {
+const useDetermineExpandContent = (
+  expandContentWidth?: boolean | null,
+): boolean => {
   const { data: dataIsContainerFluid } = useIsContainerFluid();
 
   const isContainerFluidDefault = dataIsContainerFluid;
   return expandContentWidth ?? isContainerFluidDefault ?? false;
 };
 
-export const useShouldExpandContent = (data?: IPage | IPagePopulatedToShowRevision | boolean | null): boolean => {
+export const useShouldExpandContent = (
+  data?: IPage | IPagePopulatedToShowRevision | boolean | null,
+): boolean => {
   const expandContentWidth = (() => {
     // when data is null
     if (data == null) {

+ 6 - 5
apps/app/src/services/renderer/markdown-it/PreProcessor/EasyGrid.js

@@ -1,10 +1,11 @@
 export default class EasyGrid {
-
   process(markdown) {
     // see: https://regex101.com/r/7NWvUU/2
-    return markdown.replace(/:::\s*editable-row[\r\n]((.|[\r\n])*?)[\r\n]:::/gm, (all, group) => {
-      return group;
-    });
+    return markdown.replace(
+      /:::\s*editable-row[\r\n]((.|[\r\n])*?)[\r\n]:::/gm,
+      (all, group) => {
+        return group;
+      },
+    );
   }
-
 }

+ 13 - 6
apps/app/src/services/renderer/recommended-whitelist.spec.ts

@@ -1,9 +1,8 @@
 import { notDeepEqual } from 'assert';
 
-import { tagNames, attributes } from './recommended-whitelist';
+import { attributes, tagNames } from './recommended-whitelist';
 
 describe('recommended-whitelist', () => {
-
   test('.tagNames should return iframe tag', () => {
     expect(tagNames).not.toBeNull();
     expect(tagNames).includes('iframe');
@@ -52,7 +51,10 @@ describe('recommended-whitelist', () => {
     assert(attributes != null);
 
     expect(Object.keys(attributes)).includes('a');
-    expect(attributes.a).not.toContainEqual(['className', 'data-footnote-backref']);
+    expect(attributes.a).not.toContainEqual([
+      'className',
+      'data-footnote-backref',
+    ]);
   });
 
   test('.attributes.ul should allow class and className by excluding partial className specification', () => {
@@ -61,7 +63,10 @@ describe('recommended-whitelist', () => {
     assert(attributes != null);
 
     expect(Object.keys(attributes)).includes('a');
-    expect(attributes.a).not.toContainEqual(['className', 'data-footnote-backref']);
+    expect(attributes.a).not.toContainEqual([
+      'className',
+      'data-footnote-backref',
+    ]);
   });
 
   test('.attributes.li should allow class and className by excluding partial className specification', () => {
@@ -70,7 +75,9 @@ describe('recommended-whitelist', () => {
     assert(attributes != null);
 
     expect(Object.keys(attributes)).includes('a');
-    expect(attributes.a).not.toContainEqual(['className', 'data-footnote-backref']);
+    expect(attributes.a).not.toContainEqual([
+      'className',
+      'data-footnote-backref',
+    ]);
   });
-
 });

+ 31 - 20
apps/app/src/services/renderer/recommended-whitelist.ts

@@ -9,7 +9,9 @@ type ExtractPropertyDefinition<T> = T extends Record<string, (infer U)[]>
 
 type PropertyDefinition = ExtractPropertyDefinition<NonNullable<Attributes>>;
 
-const excludeRestrictedClassAttributes = (propertyDefinitions: PropertyDefinition[]): PropertyDefinition[] => {
+const excludeRestrictedClassAttributes = (
+  propertyDefinitions: PropertyDefinition[],
+): PropertyDefinition[] => {
   if (propertyDefinitions == null) {
     return propertyDefinitions;
   }
@@ -18,15 +20,24 @@ const excludeRestrictedClassAttributes = (propertyDefinitions: PropertyDefinitio
     if (!Array.isArray(propertyDefinition)) {
       return true;
     }
-    return propertyDefinition[0] !== 'class' && propertyDefinition[0] !== 'className';
+    return (
+      propertyDefinition[0] !== 'class' && propertyDefinition[0] !== 'className'
+    );
   });
 };
 
 // generate relaxed schema
-const relaxedSchemaAttributes: Record<string, PropertyDefinition[]> = structuredClone(defaultSchema.attributes) ?? {};
-relaxedSchemaAttributes.a = excludeRestrictedClassAttributes(relaxedSchemaAttributes.a);
-relaxedSchemaAttributes.ul = excludeRestrictedClassAttributes(relaxedSchemaAttributes.ul);
-relaxedSchemaAttributes.li = excludeRestrictedClassAttributes(relaxedSchemaAttributes.li);
+const relaxedSchemaAttributes: Record<string, PropertyDefinition[]> =
+  structuredClone(defaultSchema.attributes) ?? {};
+relaxedSchemaAttributes.a = excludeRestrictedClassAttributes(
+  relaxedSchemaAttributes.a,
+);
+relaxedSchemaAttributes.ul = excludeRestrictedClassAttributes(
+  relaxedSchemaAttributes.ul,
+);
+relaxedSchemaAttributes.li = excludeRestrictedClassAttributes(
+  relaxedSchemaAttributes.li,
+);
 
 /**
  * reference: https://meta.stackexchange.com/questions/1777/what-html-tags-are-allowed-on-stack-exchange-sites,
@@ -34,23 +45,23 @@ relaxedSchemaAttributes.li = excludeRestrictedClassAttributes(relaxedSchemaAttri
  */
 
 export const tagNames: Array<string> = [
-  ...defaultSchema.tagNames ?? [],
-  '-', 'bdi',
+  ...(defaultSchema.tagNames ?? []),
+  '-',
+  'bdi',
   'button',
-  'col', 'colgroup',
+  'col',
+  'colgroup',
   'data',
   'iframe',
   'video',
-  'rb', 'u',
+  'rb',
+  'u',
 ];
 
-export const attributes: Attributes = deepmerge(
-  relaxedSchemaAttributes,
-  {
-    iframe: ['allow', 'referrerpolicy', 'sandbox', 'src'],
-    video: ['controls', 'src', 'muted', 'preload', 'width', 'height', 'autoplay'],
-    // The special value 'data*' as a property name can be used to allow all data properties.
-    // see: https://github.com/syntax-tree/hast-util-sanitize/
-    '*': ['key', 'class', 'className', 'style', 'role', 'data*'],
-  },
-);
+export const attributes: Attributes = deepmerge(relaxedSchemaAttributes, {
+  iframe: ['allow', 'referrerpolicy', 'sandbox', 'src'],
+  video: ['controls', 'src', 'muted', 'preload', 'width', 'height', 'autoplay'],
+  // The special value 'data*' as a property name can be used to allow all data properties.
+  // see: https://github.com/syntax-tree/hast-util-sanitize/
+  '*': ['key', 'class', 'className', 'style', 'role', 'data*'],
+});

+ 6 - 3
apps/app/src/services/renderer/rehype-plugins/add-class.ts

@@ -1,6 +1,6 @@
 // See: https://github.com/martypdx/rehype-add-classes for the original implementation.
 // Re-implemeted in TypeScript.
-import type { Nodes as HastNode, Element, Properties } from 'hast';
+import type { Element, Nodes as HastNode, Properties } from 'hast';
 import { selectAll } from 'hast-util-select';
 import type { Plugin } from 'unified';
 
@@ -9,7 +9,10 @@ export type ClassName = string; // e.g. 'header'
 export type Additions = Record<SelectorName, ClassName>;
 export type AdditionsEntry = [SelectorName, ClassName];
 
-export const addClassToProperties = (properties: Properties | undefined, className: string): void => {
+export const addClassToProperties = (
+  properties: Properties | undefined,
+  className: string,
+): void => {
   if (properties == null) {
     return;
   }
@@ -42,5 +45,5 @@ const adder = (entry: AdditionsEntry) => {
 export const rehypePlugin: Plugin<[Additions]> = (additions) => {
   const adders = Object.entries(additions).map(adder);
 
-  return node => adders.forEach(a => a(node as HastNode));
+  return (node) => adders.forEach((a) => a(node as HastNode));
 };

+ 4 - 1
apps/app/src/services/renderer/rehype-plugins/add-inline-code-property.ts

@@ -3,7 +3,10 @@ import type { Plugin } from 'unified';
 import { is } from 'unist-util-is';
 import { visitParents } from 'unist-util-visit-parents';
 
-const isInlineCodeTag = (node: Element, parent: Element | Root | null): boolean => {
+const isInlineCodeTag = (
+  node: Element,
+  parent: Element | Root | null,
+): boolean => {
   if (node.tagName !== 'code') {
     return false;
   }

+ 4 - 2
apps/app/src/services/renderer/rehype-plugins/add-line-number-attribute.ts

@@ -1,11 +1,13 @@
 import type { Element } from 'hast';
 import type { Schema as SanitizeOption } from 'hast-util-sanitize';
 import type { Plugin } from 'unified';
-import { visit, EXIT, CONTINUE } from 'unist-util-visit';
+import { CONTINUE, EXIT, visit } from 'unist-util-visit';
 
 import { addClassToProperties } from './add-class';
 
-const REGEXP_TARGET_TAGNAMES = new RegExp(/^(h1|h2|h3|h4|h5|h6|p|img|pre|blockquote|hr|ol|ul|table)$/);
+const REGEXP_TARGET_TAGNAMES = new RegExp(
+  /^(h1|h2|h3|h4|h5|h6|p|img|pre|blockquote|hr|ol|ul|table)$/,
+);
 
 export const rehypePlugin: Plugin = () => {
   return (tree) => {

+ 21 - 11
apps/app/src/services/renderer/rehype-plugins/keyword-highlighter.ts

@@ -1,8 +1,7 @@
-import type { Root, Element, Text } from 'hast';
+import type { Element, Root, Text } from 'hast';
 import rehypeRewrite from 'rehype-rewrite';
 import type { Plugin } from 'unified';
 
-
 /**
  * This method returns ['foo', 'bar', 'foo']
  *  when the arguments are { keyword: 'foo', value: 'foobarfoo' }
@@ -50,7 +49,12 @@ function wrapWithEm(textElement: Text): Element {
   };
 }
 
-function highlight(lowercasedKeyword: string, node: Text, index: number, parent: Root | Element): void {
+function highlight(
+  lowercasedKeyword: string,
+  node: Text,
+  index: number,
+  parent: Root | Element,
+): void {
   if (node.value.toLowerCase().includes(lowercasedKeyword)) {
     const splitted = splitWithKeyword(lowercasedKeyword, node.value);
 
@@ -67,25 +71,31 @@ function highlight(lowercasedKeyword: string, node: Text, index: number, parent:
   }
 }
 
-
 export type KeywordHighlighterPluginParams = {
-  keywords?: string | string[],
-}
+  keywords?: string | string[];
+};
 
-export const rehypePlugin: Plugin<[KeywordHighlighterPluginParams]> = (options) => {
+export const rehypePlugin: Plugin<[KeywordHighlighterPluginParams]> = (
+  options,
+) => {
   if (options?.keywords == null) {
-    return node => node;
+    return (node) => node;
   }
 
-  const keywords = (typeof options.keywords === 'string') ? [options.keywords] : options.keywords;
+  const keywords =
+    typeof options.keywords === 'string'
+      ? [options.keywords]
+      : options.keywords;
 
-  const lowercasedKeywords = keywords.map(keyword => keyword.toLowerCase());
+  const lowercasedKeywords = keywords.map((keyword) => keyword.toLowerCase());
 
   // return rehype-rewrite with hithlighter
   return rehypeRewrite.bind(this)({
     rewrite: (node, index, parent) => {
       if (parent != null && index != null && node.type === 'text') {
-        lowercasedKeywords.forEach(keyword => highlight(keyword, node, index, parent));
+        lowercasedKeywords.forEach((keyword) =>
+          highlight(keyword, node, index, parent),
+        );
       }
     },
   });

+ 45 - 39
apps/app/src/services/renderer/rehype-plugins/relative-links-by-pukiwiki-like-linker.spec.ts

@@ -9,45 +9,51 @@ import { pukiwikiLikeLinker } from '../remark-plugins/pukiwiki-like-linker';
 import { relativeLinksByPukiwikiLikeLinker } from './relative-links-by-pukiwiki-like-linker';
 
 describe('relativeLinksByPukiwikiLikeLinker', () => {
-
   /* eslint-disable indent */
   describe.each`
-    input                                   | expectedHref                        | expectedValue
-    ${'[[/page]]'}                          | ${'/page'}                          | ${'/page'}
-    ${'[[./page]]'}                         | ${'/user/admin/page'}               | ${'./page'}
-    ${'[[Title>./page]]'}                   | ${'/user/admin/page'}               | ${'Title'}
-    ${'[[Title>https://example.com]]'}      | ${'https://example.com'}            | ${'Title'}
-    ${'[[/page?q=foo#header]]'}             | ${'/page?q=foo#header'}             | ${'/page?q=foo#header'}
-    ${'[[./page?q=foo#header]]'}            | ${'/user/admin/page?q=foo#header'}  | ${'./page?q=foo#header'}
-    ${'[[Title>./page?q=foo#header]]'}      | ${'/user/admin/page?q=foo#header'}  | ${'Title'}
-    ${'[[Title>https://example.com]]'}      | ${'https://example.com'}            | ${'Title'}
-  `('should convert relative links correctly', ({ input, expectedHref, expectedValue }) => {
-  /* eslint-enable indent */
-
-    test(`when the input is '${input}'`, () => {
-      // setup:
-      const processor = unified()
-        .use(parse)
-        .use(pukiwikiLikeLinker)
-        .use(rehype)
-        .use(relativeLinksByPukiwikiLikeLinker, { pagePath: '/user/admin' });
-
-      // when:
-      const mdast = processor.parse(input);
-      const hast = processor.runSync(mdast) as HastNode;
-      const anchorElement = select('a', hast);
-
-      // then
-      expect(anchorElement).not.toBeNull();
-      expect(anchorElement?.properties).not.toBeNull();
-      expect((anchorElement?.properties?.className as string).startsWith('pukiwiki-like-linker')).toBeTruthy();
-      expect(anchorElement?.properties?.href).toEqual(expectedHref);
-
-      expect(anchorElement?.children[0]).not.toBeNull();
-      expect(anchorElement?.children[0].type).toEqual('text');
-      expect((anchorElement?.children[0] as HastNode as Text).value).toEqual(expectedValue);
-
-    });
-  });
-
+    input                              | expectedHref                       | expectedValue
+    ${'[[/page]]'}                     | ${'/page'}                         | ${'/page'}
+    ${'[[./page]]'}                    | ${'/user/admin/page'}              | ${'./page'}
+    ${'[[Title>./page]]'}              | ${'/user/admin/page'}              | ${'Title'}
+    ${'[[Title>https://example.com]]'} | ${'https://example.com'}           | ${'Title'}
+    ${'[[/page?q=foo#header]]'}        | ${'/page?q=foo#header'}            | ${'/page?q=foo#header'}
+    ${'[[./page?q=foo#header]]'}       | ${'/user/admin/page?q=foo#header'} | ${'./page?q=foo#header'}
+    ${'[[Title>./page?q=foo#header]]'} | ${'/user/admin/page?q=foo#header'} | ${'Title'}
+    ${'[[Title>https://example.com]]'} | ${'https://example.com'}           | ${'Title'}
+  `(
+    'should convert relative links correctly',
+    ({ input, expectedHref, expectedValue }) => {
+      /* eslint-enable indent */
+
+      test(`when the input is '${input}'`, () => {
+        // setup:
+        const processor = unified()
+          .use(parse)
+          .use(pukiwikiLikeLinker)
+          .use(rehype)
+          .use(relativeLinksByPukiwikiLikeLinker, { pagePath: '/user/admin' });
+
+        // when:
+        const mdast = processor.parse(input);
+        const hast = processor.runSync(mdast) as HastNode;
+        const anchorElement = select('a', hast);
+
+        // then
+        expect(anchorElement).not.toBeNull();
+        expect(anchorElement?.properties).not.toBeNull();
+        expect(
+          (anchorElement?.properties?.className as string).startsWith(
+            'pukiwiki-like-linker',
+          ),
+        ).toBeTruthy();
+        expect(anchorElement?.properties?.href).toEqual(expectedHref);
+
+        expect(anchorElement?.children[0]).not.toBeNull();
+        expect(anchorElement?.children[0].type).toEqual('text');
+        expect((anchorElement?.children[0] as HastNode as Text).value).toEqual(
+          expectedValue,
+        );
+      });
+    },
+  );
 });

+ 6 - 2
apps/app/src/services/renderer/rehype-plugins/relative-links-by-pukiwiki-like-linker.ts

@@ -3,8 +3,10 @@ import { selectAll } from 'hast-util-select';
 import type { Plugin } from 'unified';
 
 import {
+  type IAnchorsSelector,
+  type IUrlResolver,
+  type RelativeLinksPluginParams,
   relativeLinks,
-  type IAnchorsSelector, type IUrlResolver, type RelativeLinksPluginParams,
 } from './relative-links';
 
 const customAnchorsSelector: IAnchorsSelector = (node) => {
@@ -17,7 +19,9 @@ const customUrlResolver: IUrlResolver = (relativeHref, basePath) => {
   return new URL(relativeHref, baseUrl);
 };
 
-export const relativeLinksByPukiwikiLikeLinker: Plugin<[RelativeLinksPluginParams]> = (options = {}) => {
+export const relativeLinksByPukiwikiLikeLinker: Plugin<
+  [RelativeLinksPluginParams]
+> = (options = {}) => {
   return relativeLinks.bind(this)({
     ...options,
     anchorsSelector: customAnchorsSelector,

+ 31 - 33
apps/app/src/services/renderer/rehype-plugins/relative-links.spec.ts

@@ -1,4 +1,3 @@
-
 import type { Nodes as HastNode } from 'hast';
 import { select } from 'hast-util-select';
 import parse from 'remark-parse';
@@ -8,7 +7,6 @@ import { unified } from 'unified';
 import { relativeLinks } from './relative-links';
 
 describe('relativeLinks', () => {
-
   test('do nothing when the options does not have pagePath', () => {
     // setup
     const processor = unified()
@@ -27,10 +25,9 @@ describe('relativeLinks', () => {
 
   test.concurrent.each`
     originalHref
-      ${'http://example.com/Sandbox'}
-      ${'#header'}
-    `('leaves the original href \'$originalHref\' as-is', ({ originalHref }) => {
-
+    ${'http://example.com/Sandbox'}
+    ${'#header'}
+  `("leaves the original href '$originalHref' as-is", ({ originalHref }) => {
     // setup
     const pagePath = '/foo/bar/baz';
     const processor = unified()
@@ -48,33 +45,34 @@ describe('relativeLinks', () => {
   });
 
   test.concurrent.each`
-    originalHref                        | expectedHref
-      ${'/Sandbox'}                     | ${'/Sandbox'}
-      ${'/Sandbox?q=foo'}               | ${'/Sandbox?q=foo'}
-      ${'/Sandbox#header'}              | ${'/Sandbox#header'}
-      ${'/Sandbox?q=foo#header'}        | ${'/Sandbox?q=foo#header'}
-      ${'./Sandbox'}                    | ${'/foo/bar/Sandbox'}
-      ${'./Sandbox?q=foo'}              | ${'/foo/bar/Sandbox?q=foo'}
-      ${'./Sandbox#header'}             | ${'/foo/bar/Sandbox#header'}
-      ${'./Sandbox?q=foo#header'}       | ${'/foo/bar/Sandbox?q=foo#header'}
-    `('rewrites the original href \'$originalHref\' to \'$expectedHref\'', ({ originalHref, expectedHref }) => {
+    originalHref                | expectedHref
+    ${'/Sandbox'}               | ${'/Sandbox'}
+    ${'/Sandbox?q=foo'}         | ${'/Sandbox?q=foo'}
+    ${'/Sandbox#header'}        | ${'/Sandbox#header'}
+    ${'/Sandbox?q=foo#header'}  | ${'/Sandbox?q=foo#header'}
+    ${'./Sandbox'}              | ${'/foo/bar/Sandbox'}
+    ${'./Sandbox?q=foo'}        | ${'/foo/bar/Sandbox?q=foo'}
+    ${'./Sandbox#header'}       | ${'/foo/bar/Sandbox#header'}
+    ${'./Sandbox?q=foo#header'} | ${'/foo/bar/Sandbox?q=foo#header'}
+  `(
+    "rewrites the original href '$originalHref' to '$expectedHref'",
+    ({ originalHref, expectedHref }) => {
+      // setup
+      const pagePath = '/foo/bar/baz';
+      const processor = unified()
+        .use(parse)
+        .use(remarkRehype)
+        .use(relativeLinks, { pagePath });
 
-    // setup
-    const pagePath = '/foo/bar/baz';
-    const processor = unified()
-      .use(parse)
-      .use(remarkRehype)
-      .use(relativeLinks, { pagePath });
-
-    // when
-    const mdastTree = processor.parse(`[link](${originalHref})`);
-    const hastTree = processor.runSync(mdastTree) as HastNode;
-
-    // then
-    const anchorElement = select('a', hastTree);
-    expect(anchorElement).not.toBeNull();
-    expect(anchorElement?.properties).not.toBeNull();
-    expect(anchorElement?.properties?.href).toBe(expectedHref);
-  });
+      // when
+      const mdastTree = processor.parse(`[link](${originalHref})`);
+      const hastTree = processor.runSync(mdastTree) as HastNode;
 
+      // then
+      const anchorElement = select('a', hastTree);
+      expect(anchorElement).not.toBeNull();
+      expect(anchorElement?.properties).not.toBeNull();
+      expect(anchorElement?.properties?.href).toBe(expectedHref);
+    },
+  );
 });

+ 14 - 8
apps/app/src/services/renderer/rehype-plugins/relative-links.ts

@@ -1,11 +1,10 @@
 import assert from 'assert';
 
-import type { Nodes as HastNode, Element } from 'hast';
+import type { Element, Nodes as HastNode } from 'hast';
 import { selectAll } from 'hast-util-select';
 import isAbsolute from 'is-absolute-url';
 import type { Plugin } from 'unified';
 
-
 export type IAnchorsSelector = (node: HastNode) => Element[];
 export type IUrlResolver = (relativeHref: string, basePath: string) => URL;
 
@@ -29,12 +28,14 @@ const isAnchorLink = (href: string): boolean => {
 };
 
 export type RelativeLinksPluginParams = {
-  pagePath?: string,
-  anchorsSelector?: IAnchorsSelector,
-  urlResolver?: IUrlResolver,
-}
+  pagePath?: string;
+  anchorsSelector?: IAnchorsSelector;
+  urlResolver?: IUrlResolver;
+};
 
-export const relativeLinks: Plugin<[RelativeLinksPluginParams]> = (options = {}) => {
+export const relativeLinks: Plugin<[RelativeLinksPluginParams]> = (
+  options = {},
+) => {
   const anchorsSelector = options.anchorsSelector ?? defaultAnchorsSelector;
   const urlResolver = options.urlResolver ?? defaultUrlResolver;
 
@@ -50,7 +51,12 @@ export const relativeLinks: Plugin<[RelativeLinksPluginParams]> = (options = {})
       assert(anchor.properties != null);
 
       const href = anchor.properties.href;
-      if (href == null || typeof href !== 'string' || isAbsolute(href) || isAnchorLink(href)) {
+      if (
+        href == null ||
+        typeof href !== 'string' ||
+        isAbsolute(href) ||
+        isAnchorLink(href)
+      ) {
         return;
       }
 

+ 8 - 7
apps/app/src/services/renderer/rehype-plugins/relocate-toc.ts

@@ -1,11 +1,11 @@
-import rehypeToc from 'rehype-toc';
 import type { HtmlElementNode } from 'rehype-toc';
+import rehypeToc from 'rehype-toc';
 import type { Plugin } from 'unified';
 import { visit } from 'unist-util-visit';
 
 type StoreTocPluginParams = {
-  storeTocNode: (toc: HtmlElementNode) => void,
-}
+  storeTocNode: (toc: HtmlElementNode) => void;
+};
 
 export const rehypePluginStore: Plugin<[StoreTocPluginParams]> = (options) => {
   return rehypeToc.bind(this)({
@@ -21,7 +21,6 @@ export const rehypePluginStore: Plugin<[StoreTocPluginParams]> = (options) => {
   });
 };
 
-
 // method for replace <ol> to <ul>
 const replaceOlToUl = (tree: HtmlElementNode) => {
   visit(tree, 'element', (node: HtmlElementNode) => {
@@ -32,10 +31,12 @@ const replaceOlToUl = (tree: HtmlElementNode) => {
 };
 
 type RestoreTocPluginParams = {
-  tocNode?: HtmlElementNode,
-}
+  tocNode?: HtmlElementNode;
+};
 
-export const rehypePluginRestore: Plugin<[RestoreTocPluginParams]> = (options) => {
+export const rehypePluginRestore: Plugin<[RestoreTocPluginParams]> = (
+  options,
+) => {
   const { tocNode } = options;
 
   return rehypeToc.bind(this)({

+ 10 - 6
apps/app/src/services/renderer/remark-plugins/attachment.ts

@@ -1,7 +1,6 @@
-import path from 'path';
-
 import type { Schema as SanitizeOption } from 'hast-util-sanitize';
 import type { Link } from 'mdast';
+import path from 'path';
 import type { Plugin } from 'unified';
 import { visit } from 'unist-util-visit';
 
@@ -15,9 +14,15 @@ const isAttachmentLink = (url: string): boolean => {
 
 const rewriteNode = (node: Link) => {
   const attachmentId = path.basename(node.url);
-  const attachmentName = node.children[0] != null && node.children[0].type === 'text' ? node.children[0].value : '';
-
-  const data = node.data ?? (node.data = {});
+  const attachmentName =
+    node.children[0] != null && node.children[0].type === 'text'
+      ? node.children[0].value
+      : '';
+
+  if (node.data == null) {
+    node.data = {};
+  }
+  const data = node.data;
   data.hName = 'attachment';
   data.hProperties = {
     attachmentId,
@@ -26,7 +31,6 @@ const rewriteNode = (node: Link) => {
   };
 };
 
-
 export const remarkPlugin: Plugin = () => {
   return (tree) => {
     visit(tree, 'link', (node: Link) => {

+ 4 - 2
apps/app/src/services/renderer/remark-plugins/codeblock.ts

@@ -3,13 +3,15 @@ import type { InlineCode } from 'mdast';
 import type { Plugin } from 'unified';
 import { visit } from 'unist-util-visit';
 
-
 const SUPPORTED_CODE = ['inline'];
 
 export const remarkPlugin: Plugin = () => {
   return (tree) => {
     visit(tree, 'inlineCode', (node: InlineCode) => {
-      const data = node.data || (node.data = {});
+      if (node.data == null) {
+        node.data = {};
+      }
+      const data = node.data;
       data.hProperties = { inline: 'true' }; // set 'true' explicitly because the empty string is evaluated as false for `if (inline) { ... }`
     });
   };

+ 11 - 6
apps/app/src/services/renderer/remark-plugins/echo-directive.ts

@@ -5,23 +5,26 @@ import type { LeafDirective, TextDirective } from 'mdast-util-directive';
 import type { Plugin } from 'unified';
 import { visit } from 'unist-util-visit';
 
-
 function echoDirective(node: TextDirective | LeafDirective): ElementContent[] {
   const mark = node.type === 'textDirective' ? ':' : '::';
 
   return [
     h('span', `${mark}${node.name}`),
-    ...(node.children ?? []).map((child: Text) => h('span', `[${child.value}]`)),
+    ...(node.children ?? []).map((child: Text) =>
+      h('span', `[${child.value}]`),
+    ),
   ];
 }
 
 export const remarkPlugin: Plugin = () => {
   return (tree) => {
-
     visit(tree, 'textDirective', (node: TextDirective) => {
       const tagName = 'span';
 
-      const data = node.data ?? (node.data = {});
+      if (node.data == null) {
+        node.data = {};
+      }
+      const data = node.data;
       data.hName = tagName;
       data.hProperties = h(tagName, node.attributes ?? {}).properties;
       data.hChildren = echoDirective(node);
@@ -30,11 +33,13 @@ export const remarkPlugin: Plugin = () => {
     visit(tree, 'leafDirective', (node: LeafDirective) => {
       const tagName = 'div';
 
-      const data = node.data ?? (node.data = {});
+      if (node.data == null) {
+        node.data = {};
+      }
+      const data = node.data;
       data.hName = tagName;
       data.hProperties = h(tagName, node.attributes ?? {}).properties;
       data.hChildren = echoDirective(node);
     });
-
   };
 };

+ 2 - 3
apps/app/src/services/renderer/remark-plugins/emoji.ts

@@ -4,13 +4,12 @@ import { findAndReplace } from 'mdast-util-find-and-replace';
 import type { Plugin } from 'unified';
 
 export const remarkPlugin: Plugin = () => {
-  return function(tree: Root) {
+  return (tree: Root) => {
     findAndReplace(tree, [
-
       // Ref: https://github.com/remarkjs/remark-gemoji/blob/fb4d8a5021f02384e180c17f72f40d8dc698bd46/lib/index.js
       /:(\+1|[-\w]+):/g,
 
-      function(_, $1: string) {
+      (_, $1: string) => {
         const emoji = emojiData.emojis[$1]?.skins[0].native;
         return emoji ?? false;
       },

+ 13 - 16
apps/app/src/services/renderer/remark-plugins/pukiwiki-like-linker.spec.ts

@@ -5,24 +5,20 @@ import { visit } from 'unist-util-visit';
 import { pukiwikiLikeLinker } from './pukiwiki-like-linker';
 
 describe('pukiwikiLikeLinker', () => {
-
   describe.each`
-    input                                   | expectedHref                    | expectedValue
-    ${'[[/page]]'}                          | ${'/page'}                      | ${'/page'}
-    ${'[[./page]]'}                         | ${'./page'}                     | ${'./page'}
-    ${'[[Title>./page]]'}                   | ${'./page'}                     | ${'Title'}
-    ${'[[Title>https://example.com]]'}      | ${'https://example.com'}        | ${'Title'}
-    ${'[[/page?q=foo#header]]'}             | ${'/page?q=foo#header'}         | ${'/page?q=foo#header'}
-    ${'[[./page?q=foo#header]]'}            | ${'./page?q=foo#header'}        | ${'./page?q=foo#header'}
-    ${'[[Title>./page?q=foo#header]]'}      | ${'./page?q=foo#header'}        | ${'Title'}
-    ${'[[Title>https://example.com]]'}      | ${'https://example.com'}        | ${'Title'}
+    input                              | expectedHref             | expectedValue
+    ${'[[/page]]'}                     | ${'/page'}               | ${'/page'}
+    ${'[[./page]]'}                    | ${'./page'}              | ${'./page'}
+    ${'[[Title>./page]]'}              | ${'./page'}              | ${'Title'}
+    ${'[[Title>https://example.com]]'} | ${'https://example.com'} | ${'Title'}
+    ${'[[/page?q=foo#header]]'}        | ${'/page?q=foo#header'}  | ${'/page?q=foo#header'}
+    ${'[[./page?q=foo#header]]'}       | ${'./page?q=foo#header'} | ${'./page?q=foo#header'}
+    ${'[[Title>./page?q=foo#header]]'} | ${'./page?q=foo#header'} | ${'Title'}
+    ${'[[Title>https://example.com]]'} | ${'https://example.com'} | ${'Title'}
   `('should parse correctly', ({ input, expectedHref, expectedValue }) => {
-
     test(`when the input is '${input}'`, () => {
       // setup:
-      const processor = unified()
-        .use(parse)
-        .use(pukiwikiLikeLinker);
+      const processor = unified().use(parse).use(pukiwikiLikeLinker);
 
       // when:
       const ast = processor.parse(input);
@@ -33,11 +29,12 @@ describe('pukiwikiLikeLinker', () => {
         expect(node.data.alias).toEqual(expectedValue);
         expect(node.data.permalink).toEqual(expectedHref);
         expect(node.data.hName).toEqual('a');
-        expect(node.data.hProperties.className.startsWith('pukiwiki-like-linker')).toBeTruthy();
+        expect(
+          node.data.hProperties.className.startsWith('pukiwiki-like-linker'),
+        ).toBeTruthy();
         expect(node.data.hProperties.href).toEqual(expectedHref);
         expect(node.data.hChildren[0].value).toEqual(expectedValue);
       });
     });
   });
-
 });

+ 34 - 26
apps/app/src/services/renderer/remark-plugins/pukiwiki-like-linker.ts

@@ -2,27 +2,28 @@ import { fromMarkdown, toMarkdown } from 'mdast-util-wiki-link';
 import { syntax } from 'micromark-extension-wiki-link';
 import type { Plugin } from 'unified';
 
-
 type FromMarkdownExtension = {
   enter: {
-    wikiLink: (token: string) => void,
-  },
+    wikiLink: (token: string) => void;
+  };
   exit: {
-    wikiLinkTarget: (token: string) => void,
-    wikiLinkAlias: (token: string) => void,
-    wikiLink: (token: string) => void,
-  }
-}
+    wikiLinkTarget: (token: string) => void;
+    wikiLinkAlias: (token: string) => void;
+    wikiLink: (token: string) => void;
+  };
+};
 
 type FromMarkdownData = {
-  value: string | null,
+  value: string | null;
   data: {
-    alias: string | null,
-    hProperties: Record<string, unknown>,
-  }
-}
+    alias: string | null;
+    hProperties: Record<string, unknown>;
+  };
+};
 
-function swapTargetAndAlias(fromMarkdownExtension: FromMarkdownExtension): FromMarkdownExtension {
+function swapTargetAndAlias(
+  fromMarkdownExtension: FromMarkdownExtension,
+): FromMarkdownExtension {
   return {
     enter: fromMarkdownExtension.enter,
     exit: {
@@ -52,7 +53,7 @@ function swapTargetAndAlias(fromMarkdownExtension: FromMarkdownExtension): FromM
 /**
  * Implemented with reference to https://github.com/landakram/remark-wiki-link/blob/master/src/index.js
  */
-export const pukiwikiLikeLinker: Plugin = function() {
+export const pukiwikiLikeLinker: Plugin = function () {
   const data = this.data();
 
   function add(field: string, value) {
@@ -61,20 +62,27 @@ export const pukiwikiLikeLinker: Plugin = function() {
       if (Array.isArray(array)) {
         array.push(value);
       }
-    }
-    else {
+    } else {
       data[field] = [value];
     }
   }
 
-  add('micromarkExtensions', syntax({
-    aliasDivider: '>',
-  }));
-  add('fromMarkdownExtensions', swapTargetAndAlias(fromMarkdown({
-    wikiLinkClassName: 'pukiwiki-like-linker',
-    newClassName: ' ',
-    pageResolver: value => [value],
-    hrefTemplate: permalink => permalink,
-  })));
+  add(
+    'micromarkExtensions',
+    syntax({
+      aliasDivider: '>',
+    }),
+  );
+  add(
+    'fromMarkdownExtensions',
+    swapTargetAndAlias(
+      fromMarkdown({
+        wikiLinkClassName: 'pukiwiki-like-linker',
+        newClassName: ' ',
+        pageResolver: (value) => [value],
+        hrefTemplate: (permalink) => permalink,
+      }),
+    ),
+  );
   add('toMarkdownExtensions', toMarkdown({}));
 };

+ 6 - 8
apps/app/src/services/renderer/remark-plugins/xsv-to-table.ts

@@ -33,12 +33,10 @@ function rewriteNode(node: Node, lang: Lang) {
   }
 }
 
-export const remarkPlugin: Plugin = function() {
-  return (tree) => {
-    visit(tree, 'code', (node: Code) => {
-      if (isXsv(node.lang)) {
-        rewriteNode(node, node.lang);
-      }
-    });
-  };
+export const remarkPlugin: Plugin = () => (tree) => {
+  visit(tree, 'code', (node: Code) => {
+    if (isXsv(node.lang)) {
+      rewriteNode(node, node.lang);
+    }
+  });
 };

+ 53 - 39
apps/app/src/services/renderer/renderer.tsx

@@ -19,7 +19,10 @@ import { RehypeSanitizeType } from '~/interfaces/services/rehype-sanitize';
 import type { RendererConfig } from '~/interfaces/services/renderer';
 import loggerFactory from '~/utils/logger';
 
-import { tagNames as recommendedTagNames, attributes as recommendedAttributes } from './recommended-whitelist';
+import {
+  attributes as recommendedAttributes,
+  tagNames as recommendedTagNames,
+} from './recommended-whitelist';
 import * as addClass from './rehype-plugins/add-class';
 import * as addInlineProperty from './rehype-plugins/add-inline-code-property';
 import { relativeLinks } from './rehype-plugins/relative-links';
@@ -30,29 +33,34 @@ import * as emoji from './remark-plugins/emoji';
 import { pukiwikiLikeLinker } from './remark-plugins/pukiwiki-like-linker';
 import * as xsvToTable from './remark-plugins/xsv-to-table';
 
-
 // import EasyGrid from './PreProcessor/EasyGrid';
 
-
 // eslint-disable-next-line @typescript-eslint/no-unused-vars
 const logger = loggerFactory('growi:services:renderer');
 
-
 type SanitizePlugin = PluginTuple<[SanitizeOption]>;
 
-let currentInitializedSanitizeType: RehypeSanitizeType = RehypeSanitizeType.RECOMMENDED;
+let currentInitializedSanitizeType: RehypeSanitizeType =
+  RehypeSanitizeType.RECOMMENDED;
 let commonSanitizeOption: SanitizeOption;
-export const getCommonSanitizeOption = (config:RendererConfig): SanitizeOption => {
-  if (commonSanitizeOption == null || config.sanitizeType !== currentInitializedSanitizeType) {
+export const getCommonSanitizeOption = (
+  config: RendererConfig,
+): SanitizeOption => {
+  if (
+    commonSanitizeOption == null ||
+    config.sanitizeType !== currentInitializedSanitizeType
+  ) {
     // initialize
     commonSanitizeOption = deepmerge(
       {
-        tagNames: config.sanitizeType === RehypeSanitizeType.RECOMMENDED
-          ? recommendedTagNames
-          : config.customTagWhitelist ?? recommendedTagNames,
-        attributes: config.sanitizeType === RehypeSanitizeType.RECOMMENDED
-          ? recommendedAttributes
-          : config.customAttrWhitelist ?? recommendedAttributes,
+        tagNames:
+          config.sanitizeType === RehypeSanitizeType.RECOMMENDED
+            ? recommendedTagNames
+            : (config.customTagWhitelist ?? recommendedTagNames),
+        attributes:
+          config.sanitizeType === RehypeSanitizeType.RECOMMENDED
+            ? recommendedAttributes
+            : (config.customAttrWhitelist ?? recommendedAttributes),
         clobberPrefix: '', // remove clobber prefix
       },
       codeBlock.sanitizeOption,
@@ -64,8 +72,9 @@ export const getCommonSanitizeOption = (config:RendererConfig): SanitizeOption =
   return commonSanitizeOption;
 };
 
-
-const isSanitizePlugin = (pluggable: Pluggable): pluggable is SanitizePlugin => {
+const isSanitizePlugin = (
+  pluggable: Pluggable,
+): pluggable is SanitizePlugin => {
   if (!Array.isArray(pluggable) || pluggable.length < 2) {
     return false;
   }
@@ -73,7 +82,10 @@ const isSanitizePlugin = (pluggable: Pluggable): pluggable is SanitizePlugin =>
   return 'tagNames' in sanitizeOption && 'attributes' in sanitizeOption;
 };
 
-const hasSanitizePlugin = (options: RendererOptions, shouldBeTheLastItem: boolean): boolean => {
+const hasSanitizePlugin = (
+  options: RendererOptions,
+  shouldBeTheLastItem: boolean,
+): boolean => {
   const { rehypePlugins } = options;
   if (rehypePlugins == null || rehypePlugins.length === 0) {
     return false;
@@ -81,18 +93,25 @@ const hasSanitizePlugin = (options: RendererOptions, shouldBeTheLastItem: boolea
 
   return shouldBeTheLastItem
     ? isSanitizePlugin(rehypePlugins.slice(-1)[0]) // evaluate the last one
-    : rehypePlugins.some(rehypePlugin => isSanitizePlugin(rehypePlugin));
+    : rehypePlugins.some((rehypePlugin) => isSanitizePlugin(rehypePlugin));
 };
 
-export const verifySanitizePlugin = (options: RendererOptions, shouldBeTheLastItem = true): void => {
+export const verifySanitizePlugin = (
+  options: RendererOptions,
+  shouldBeTheLastItem = true,
+): void => {
   if (hasSanitizePlugin(options, shouldBeTheLastItem)) {
     return;
   }
 
-  throw new Error('The specified options does not have sanitize plugin in \'rehypePlugins\'');
+  throw new Error(
+    "The specified options does not have sanitize plugin in 'rehypePlugins'",
+  );
 };
 
-export const generateCommonOptions = (pagePath: string|undefined): RendererOptions => {
+export const generateCommonOptions = (
+  pagePath: string | undefined,
+): RendererOptions => {
   return {
     remarkPlugins: [
       gfm,
@@ -112,9 +131,12 @@ export const generateCommonOptions = (pagePath: string|undefined): RendererOptio
       [relativeLinksByPukiwikiLikeLinker, { pagePath }],
       [relativeLinks, { pagePath }],
       raw,
-      [addClass.rehypePlugin, {
-        table: 'table table-bordered',
-      }],
+      [
+        addClass.rehypePlugin,
+        {
+          table: 'table table-bordered',
+        },
+      ],
       addInlineProperty.rehypePlugin,
     ],
     components: {
@@ -124,21 +146,16 @@ export const generateCommonOptions = (pagePath: string|undefined): RendererOptio
   };
 };
 
-
 export const generateSSRViewOptions = (
-    config: RendererConfig,
-    pagePath: string,
+  config: RendererConfig,
+  pagePath: string,
 ): RendererOptions => {
-
   const options = generateCommonOptions(pagePath);
 
   const { remarkPlugins, rehypePlugins } = options;
 
   // add remark plugins
-  remarkPlugins.push(
-    math,
-    xsvToTable.remarkPlugin,
-  );
+  remarkPlugins.push(math, xsvToTable.remarkPlugin);
 
   const isEnabledLinebreaks = config.isEnabledLinebreaks;
 
@@ -146,16 +163,13 @@ export const generateSSRViewOptions = (
     remarkPlugins.push(breaks);
   }
 
-  const rehypeSanitizePlugin: Pluggable | (() => void) = config.isEnabledXssPrevention
-    ? [sanitize, getCommonSanitizeOption(config)]
-    : () => {};
+  const rehypeSanitizePlugin: Pluggable | (() => void) =
+    config.isEnabledXssPrevention
+      ? [sanitize, getCommonSanitizeOption(config)]
+      : () => {};
 
   // add rehype plugins
-  rehypePlugins.push(
-    slug,
-    rehypeSanitizePlugin,
-    katex,
-  );
+  rehypePlugins.push(slug, rehypeSanitizePlugin, katex);
 
   // add components
   // if (components != null) {

+ 26 - 8
apps/app/src/stores/websocket.tsx

@@ -1,12 +1,13 @@
 import { useEffect } from 'react';
 
 import {
-  useGlobalSocket, GLOBAL_SOCKET_KEY, GLOBAL_SOCKET_NS, useSWRStatic,
+  useGlobalSocket, GLOBAL_SOCKET_NS, useSWRStatic,
 } from '@growi/core/dist/swr';
 import type { Socket } from 'socket.io-client';
 import type { SWRResponse } from 'swr';
 
 import { SocketEventName } from '~/interfaces/websocket';
+import { useIsGuestUser } from '~/stores-universal/context';
 import loggerFactory from '~/utils/logger';
 
 const logger = loggerFactory('growi:stores:ui');
@@ -19,25 +20,42 @@ export const GLOBAL_ADMIN_SOCKET_KEY = 'globalAdminSocket';
  */
 export const useSetupGlobalSocket = (): void => {
 
-  const { data, mutate } = useSWRStatic(GLOBAL_SOCKET_KEY);
+  const { data: socket, mutate } = useGlobalSocket();
+  const { data: isGuestUser } = useIsGuestUser();
 
   useEffect(() => {
-    if (data != null) {
+    // Skip Socket.IO connection for guest users (not logged in)
+    // Guest users don't need real-time updates as they can only read pages
+    if (isGuestUser) {
+      logger.debug('Socket.IO connection skipped for guest user');
+      return;
+    }
+
+    if (socket != null) {
       return;
     }
 
     mutate(async() => {
       const { io } = await import('socket.io-client');
-      const socket = io(GLOBAL_SOCKET_NS, {
+      const newSocket = io(GLOBAL_SOCKET_NS, {
         transports: ['websocket'],
       });
 
-      socket.on('error', (err) => { logger.error(err) });
-      socket.on('connect_error', (err) => { logger.error('Failed to connect with websocket.', err) });
+      newSocket.on('error', (err) => { logger.error(err) });
+      newSocket.on('connect_error', (err) => { logger.error('Failed to connect with websocket.', err) });
 
-      return socket;
+      return newSocket;
     });
-  }, [data, mutate]);
+
+    // Cleanup function to disconnect socket when component unmounts or user logs out
+    return () => {
+      if (socket != null && typeof socket === 'object' && 'disconnect' in socket) {
+        logger.debug('Disconnecting Socket.IO connection');
+        (socket as Socket).disconnect();
+        mutate(undefined, false); // Clear the SWR cache without revalidation
+      }
+    };
+  }, [socket, isGuestUser, mutate]);
 };
 
 // comment out for porduction build error: https://github.com/growilabs/growi/pull/7131

+ 3 - 1
apps/app/src/stores/yjs.ts

@@ -6,6 +6,7 @@ import useSWRMutation, { type SWRMutationResponse } from 'swr/mutation';
 
 import { apiv3Get } from '~/client/util/apiv3-client';
 import type { CurrentPageYjsData } from '~/interfaces/yjs';
+import { useIsGuestUser } from '~/stores-universal/context';
 
 import { useCurrentPageId } from './page';
 
@@ -16,8 +17,9 @@ type CurrentPageYjsDataUtils = {
 
 export const useCurrentPageYjsData = (): SWRResponse<CurrentPageYjsData, Error> & CurrentPageYjsDataUtils => {
   const { data: currentPageId } = useCurrentPageId();
+  const { data: isGuestUser } = useIsGuestUser();
 
-  const key = currentPageId != null
+  const key = !isGuestUser && currentPageId != null
     ? `/page/${currentPageId}/yjs-data`
     : null;
 

+ 1 - 3
apps/app/test-with-vite/.eslintrc.cjs

@@ -1,5 +1,3 @@
 module.exports = {
-  extends: [
-    'plugin:vitest/recommended',
-  ],
+  extends: ['plugin:vitest/recommended'],
 };

+ 2 - 3
apps/app/test-with-vite/setup/mongoms.ts

@@ -3,8 +3,7 @@ import mongoose from 'mongoose';
 
 import { mongoOptions } from '~/server/util/mongoose-utils';
 
-
-beforeAll(async() => {
+beforeAll(async () => {
   // set debug flag
   process.env.MONGOMS_DEBUG = process.env.VITE_MONGOMS_DEBUG;
 
@@ -25,6 +24,6 @@ beforeAll(async() => {
   await mongoose.connect(mongoServer.getUri(), mongoOptions);
 });
 
-afterAll(async() => {
+afterAll(async () => {
   await mongoose.disconnect();
 });

+ 1 - 1
apps/app/test-with-vite/tsconfig.json

@@ -5,7 +5,7 @@
     "baseUrl": "../",
     "paths": {
       "~/*": ["./src/*"],
-      "^/*": ["./*"],
+      "^/*": ["./*"]
     }
   }
 }

+ 5 - 8
biome.json

@@ -5,6 +5,7 @@
       "**",
       "!**/dist/**",
       "!**/node_modules/**",
+      "!**/.pnpm-store/**",
       "!**/coverage/**",
       "!**/vite.config.ts.timestamp-*",
       "!**/vite.server.config.ts.timestamp-*",
@@ -21,17 +22,16 @@
       "!**/.eslintrc.js",
       "!**/.stylelintrc.json",
       "!**/package.json",
+      "!apps/app/src/styles/prebuilt/**",
+      "!apps/app/tmp/**",
       "!apps/slackbot-proxy/src/public/bootstrap/**",
       "!packages/editor/**",
       "!packages/pdf-converter-client/src/index.ts",
+      "!packages/pdf-converter-client/specs/**",
       "!apps/app/playwright/**",
-      "!apps/app/public/**",
       "!apps/app/src/client/**",
       "!apps/app/src/components/**",
-      "!apps/app/src/features/growi-plugin/**",
       "!apps/app/src/features/openai/**",
-      "!apps/app/src/features/rate-limiter/**",
-      "!apps/app/src/models/**",
       "!apps/app/src/pages/**",
       "!apps/app/src/server/**",
       "!apps/app/src/services/**",
@@ -68,10 +68,7 @@
   },
   "overrides": [
     {
-      "includes": [
-        "apps/pdf-converter/**",
-        "./apps/slackbot-proxy/**"
-      ],
+      "includes": ["apps/pdf-converter/**", "./apps/slackbot-proxy/**"],
       "linter": {
         "rules": {
           "style": {