Browse Source

Merge branch 'master' into support/150156-sidebar-header-text-size

satof3 1 year ago
parent
commit
5d930fa513
38 changed files with 392 additions and 205 deletions
  1. 1 0
      .devcontainer/devcontainer.json
  2. 23 1
      CHANGELOG.md
  3. 1 1
      apps/app/docker/README.md
  4. 1 1
      apps/app/package.json
  5. 4 2
      apps/app/public/static/locales/en_US/translation.json
  6. 4 2
      apps/app/public/static/locales/fr_FR/translation.json
  7. 4 2
      apps/app/public/static/locales/ja_JP/translation.json
  8. 4 2
      apps/app/public/static/locales/zh_CN/translation.json
  9. 24 7
      apps/app/src/client/components/Navbar/GrowiContextualSubNavigation.tsx
  10. 0 1
      apps/app/src/client/components/PageControls/PageControls.tsx
  11. 10 1
      apps/app/src/client/components/ReactMarkdownComponents/DrawioViewerWithEditButton.tsx
  12. 9 1
      apps/app/src/client/components/ReactMarkdownComponents/TableWithEditButton.tsx
  13. 4 3
      apps/app/src/client/services/page-operation.ts
  14. 5 0
      apps/app/src/interfaces/yjs.ts
  15. 2 4
      apps/app/src/server/crowi/index.js
  16. 2 0
      apps/app/src/server/models/revision.ts
  17. 9 4
      apps/app/src/server/routes/apiv3/page/sync-latest-revision-body-to-yjs-draft.ts
  18. 1 1
      apps/app/src/server/service/config-manager.ts
  19. 28 23
      apps/app/src/server/service/file-uploader/aws.ts
  20. 32 24
      apps/app/src/server/service/file-uploader/azure.ts
  21. 4 0
      apps/app/src/server/service/file-uploader/file-uploader.ts
  22. 24 19
      apps/app/src/server/service/file-uploader/gcs.ts
  23. 30 24
      apps/app/src/server/service/file-uploader/gridfs.ts
  24. 9 1
      apps/app/src/server/service/file-uploader/local.ts
  25. 24 24
      apps/app/src/server/service/g2g-transfer.ts
  26. 2 1
      apps/app/src/server/service/in-app-notification.ts
  27. 29 0
      apps/app/src/server/service/normalize-data/convert-revision-page-id-to-string.ts
  28. 2 0
      apps/app/src/server/service/normalize-data/index.ts
  29. 23 2
      apps/app/src/server/service/search-delegator/aggregate-to-index.ts
  30. 0 0
      apps/app/src/server/service/socket-io/helper.ts
  31. 1 0
      apps/app/src/server/service/socket-io/index.ts
  32. 13 23
      apps/app/src/server/service/socket-io/socket-io.ts
  33. 3 3
      apps/app/src/server/service/system-events/sync-page-status.ts
  34. 14 4
      apps/app/src/server/service/yjs/yjs.ts
  35. 1 1
      apps/slackbot-proxy/package.json
  36. 1 1
      package.json
  37. 4 1
      packages/core/src/interfaces/page.ts
  38. 40 21
      packages/editor/src/client/services/use-codemirror-editor/utils/fold-drawio.ts

+ 1 - 0
.devcontainer/devcontainer.json

@@ -19,6 +19,7 @@
     "eamodio.gitlens",
     "eamodio.gitlens",
     "github.vscode-pull-request-github",
     "github.vscode-pull-request-github",
     "cschleiden.vscode-github-actions",
     "cschleiden.vscode-github-actions",
+    "cweijan.vscode-database-client2",
     "mongodb.mongodb-vscode",
     "mongodb.mongodb-vscode",
     "msjsdiag.debugger-for-chrome",
     "msjsdiag.debugger-for-chrome",
     "firefox-devtools.vscode-firefox-debug",
     "firefox-devtools.vscode-firefox-debug",

+ 23 - 1
CHANGELOG.md

@@ -1,9 +1,31 @@
 # Changelog
 # Changelog
 
 
-## [Unreleased](https://github.com/weseek/growi/compare/v7.0.13...HEAD)
+## [Unreleased](https://github.com/weseek/growi/compare/v7.0.14...HEAD)
 
 
 *Please do not manually update this file. We've automated the process.*
 *Please do not manually update this file. We've automated the process.*
 
 
+## [v7.0.14](https://github.com/weseek/growi/compare/v7.0.13...v7.0.14) - 2024-07-19
+
+### 🐛 Bug Fixes
+
+### 💎 Features
+
+* feat: Alerts when trying to sync with latest revision when yjs data is corrupt (#8971) @miya
+
+### 🚀 Improvement
+
+* imprv: Restrict use of the editing UI from View if there is at least one user currently editing (#8966) @miya
+
+### 🐛 Bug Fixes
+
+* fix: Handle error when folding drawio blocks (#8977) @yuki-takei
+* fix: Sync the editor text with the latest revision menu (1) (#8975) @yuki-takei
+* fix: Sync the editor text with the latest revision menu (2) (#8978) @yuki-takei
+
+### 🧰 Maintenance
+
+* support: Normalize Revision.pageId (for #8954) (#8973) @miya
+
 ## [v7.0.13](https://github.com/weseek/growi/compare/v7.0.12...v7.0.13) - 2024-07-16
 ## [v7.0.13](https://github.com/weseek/growi/compare/v7.0.12...v7.0.13) - 2024-07-16
 
 
 ### 💎 Features
 ### 💎 Features

+ 1 - 1
apps/app/docker/README.md

@@ -10,7 +10,7 @@ GROWI Official docker image
 Supported tags and respective Dockerfile links
 Supported tags and respective Dockerfile links
 ------------------------------------------------
 ------------------------------------------------
 
 
-* [`7.0.13`, `7.0`, `7`, `latest` (Dockerfile)](https://github.com/weseek/growi/blob/v7.0.13/apps/app/docker/Dockerfile)
+* [`7.0.14`, `7.0`, `7`, `latest` (Dockerfile)](https://github.com/weseek/growi/blob/v7.0.14/apps/app/docker/Dockerfile)
 * [`6.3.2`, `6.3`, `6` (Dockerfile)](https://github.com/weseek/growi/blob/v6.3.2/apps/app/docker/Dockerfile)
 * [`6.3.2`, `6.3`, `6` (Dockerfile)](https://github.com/weseek/growi/blob/v6.3.2/apps/app/docker/Dockerfile)
 * [`6.2.4`, `6.2` (Dockerfile)](https://github.com/weseek/growi/blob/v6.2.4/apps/app/docker/Dockerfile)
 * [`6.2.4`, `6.2` (Dockerfile)](https://github.com/weseek/growi/blob/v6.2.4/apps/app/docker/Dockerfile)
 * [`6.1.15`, `6.1` (Dockerfile)](https://github.com/weseek/growi/blob/v6.1.15/apps/app/docker/Dockerfile)
 * [`6.1.15`, `6.1` (Dockerfile)](https://github.com/weseek/growi/blob/v6.1.15/apps/app/docker/Dockerfile)

+ 1 - 1
apps/app/package.json

@@ -1,6 +1,6 @@
 {
 {
   "name": "@growi/app",
   "name": "@growi/app",
-  "version": "7.0.14-RC.0",
+  "version": "7.0.15-RC.0",
   "license": "MIT",
   "license": "MIT",
   "private": "true",
   "private": "true",
   "scripts": {
   "scripts": {

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

@@ -9,7 +9,6 @@
   "delete_all": "Delete all",
   "delete_all": "Delete all",
   "Duplicate": "Duplicate",
   "Duplicate": "Duplicate",
   "PathRecovery": "Path recovery",
   "PathRecovery": "Path recovery",
-  "SyncLatestRevisionBody": "Sync editor with latest body",
   "Copy": "Copy",
   "Copy": "Copy",
   "preview": "Preview",
   "preview": "Preview",
   "desktop": "Desktop",
   "desktop": "Desktop",
@@ -851,9 +850,12 @@
   "create_page": {
   "create_page": {
     "untitled": "Untitled"
     "untitled": "Untitled"
   },
   },
-  "sync-latest-reevision-body": {
+  "sync-latest-revision-body": {
+    "menuitem": "Sync the editor text with the latest revision body",
     "confirm": "Delete the draft data being entered into the editor and synchronize the latest text. Are you sure you want to run it?",
     "confirm": "Delete the draft data being entered into the editor and synchronize the latest text. Are you sure you want to run it?",
+    "alert": "The latest text may not have been synchronized. Please reload and check again.",
     "success-toaster": "Latest text synchronized",
     "success-toaster": "Latest text synchronized",
+    "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"
     "error-toaster": "Synchronization of the latest text failed"
   }
   }
 }
 }

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

@@ -9,7 +9,6 @@
   "delete_all": "Tout supprimer",
   "delete_all": "Tout supprimer",
   "Duplicate": "Dupliquer",
   "Duplicate": "Dupliquer",
   "PathRecovery": "Récupération de chemin",
   "PathRecovery": "Récupération de chemin",
-  "SyncLatestRevisionBody": "Synchroniser l'éditeur avec le dernier corps",
   "Copy": "Copier",
   "Copy": "Copier",
   "preview": "Prévisualiser",
   "preview": "Prévisualiser",
   "desktop": "Ordinateur",
   "desktop": "Ordinateur",
@@ -842,9 +841,12 @@
     "size_s": "Taille: P",
     "size_s": "Taille: P",
     "size_l": "Taille: G"
     "size_l": "Taille: G"
   },
   },
-  "sync-latest-reevision-body": {
+  "sync-latest-revision-body": {
+    "menuitem": "Synchroniser le texte de l'éditeur avec le corps de la dernière révision",
     "confirm": "Delete the draft data being entered into the editor and synchronize the latest text. Are you sure you want to run it?",
     "confirm": "Delete the draft data being entered into the editor and synchronize the latest text. Are you sure you want to run it?",
+    "alert": "Il se peut que le texte le plus récent n'ait pas été synchronisé. Veuillez recharger et vérifier à nouveau.",
     "success-toaster": "Dernier texte synchronisé",
     "success-toaster": "Dernier texte synchronisé",
+    "skipped-toaster": "Synchronisation ignorée car l'éditeur n'est pas activé. Ouvrir l'éditeur et réessayer.",
     "error-toaster": "La synchronisation du dernier texte a échoué"
     "error-toaster": "La synchronisation du dernier texte a échoué"
   }
   }
 }
 }

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

@@ -9,7 +9,6 @@
   "delete_all": "全て削除",
   "delete_all": "全て削除",
   "Duplicate": "複製",
   "Duplicate": "複製",
   "PathRecovery": "パスを修復",
   "PathRecovery": "パスを修復",
-  "SyncLatestRevisionBody": "エディターを最新の本文に同期",
   "Copy": "コピー",
   "Copy": "コピー",
   "preview": "プレビュー",
   "preview": "プレビュー",
   "desktop": "パソコン",
   "desktop": "パソコン",
@@ -884,9 +883,12 @@
   "create_page": {
   "create_page": {
     "untitled": "無題のページ"
     "untitled": "無題のページ"
   },
   },
-  "sync-latest-reevision-body": {
+  "sync-latest-revision-body": {
+    "menuitem": "最新のリビジョンの本文とエディタのテキストを同期",
     "confirm": "エディターに入力中のドラフトデータを削除して最新の本文を同期します。実行しますか?",
     "confirm": "エディターに入力中のドラフトデータを削除して最新の本文を同期します。実行しますか?",
+    "alert": "最新の本文が同期されていない可能性があります。リロードして再度ご確認ください。",
     "success-toaster": "最新の本文を同期しました",
     "success-toaster": "最新の本文を同期しました",
+    "skipped-toaster": "エディターがアクティブではないため、同期をスキップしました。エディターを開いて再度お試しください。",
     "error-toaster": "最新の本文の同期に失敗しました"
     "error-toaster": "最新の本文の同期に失敗しました"
   }
   }
 }
 }

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

@@ -9,7 +9,6 @@
   "delete_all": "删除所有",
   "delete_all": "删除所有",
   "Duplicate": "复制",
   "Duplicate": "复制",
   "PathRecovery": "路径恢复",
   "PathRecovery": "路径恢复",
-  "SyncLatestRevisionBody": "将编辑器与最新机身同步",
   "Copy": "复制",
   "Copy": "复制",
   "preview": "预览",
   "preview": "预览",
   "desktop": "电脑",
   "desktop": "电脑",
@@ -854,9 +853,12 @@
   "create_page": {
   "create_page": {
     "untitled": "Untitled"
     "untitled": "Untitled"
   },
   },
-  "sync-latest-reevision-body": {
+  "sync-latest-revision-body": {
+    "menuitem": "同步编辑器文本与最新修订正文",
     "confirm": "删除输入编辑器的草稿数据,同步最新文本。 您真的想运行它吗?",
     "confirm": "删除输入编辑器的草稿数据,同步最新文本。 您真的想运行它吗?",
+    "alert": "最新文本可能尚未同步。 请重新加载并再次检查。",
     "success-toaster": "同步最新文本",
     "success-toaster": "同步最新文本",
+    "skipped-toaster": "由于编辑器未激活,因此跳过同步。 请打开编辑器并重试。",
     "error-toaster": "同步最新文本失败"
     "error-toaster": "同步最新文本失败"
   }
   }
 }
 }

+ 24 - 7
apps/app/src/client/components/Navbar/GrowiContextualSubNavigation.tsx

@@ -7,6 +7,8 @@ import type {
   IPageToRenameWithMeta, IPageWithMeta, IPageInfoForEntity,
   IPageToRenameWithMeta, IPageWithMeta, IPageInfoForEntity,
 } from '@growi/core';
 } from '@growi/core';
 import { pagePathUtils } from '@growi/core/dist/utils';
 import { pagePathUtils } from '@growi/core/dist/utils';
+import { GlobalCodeMirrorEditorKey } from '@growi/editor';
+import { useCodeMirrorEditorIsolated } from '@growi/editor/dist/client/stores/codemirror-editor';
 import { useTranslation } from 'next-i18next';
 import { useTranslation } from 'next-i18next';
 import dynamic from 'next/dynamic';
 import dynamic from 'next/dynamic';
 import Link from 'next/link';
 import Link from 'next/link';
@@ -15,7 +17,7 @@ import Sticky from 'react-stickynode';
 import { DropdownItem } from 'reactstrap';
 import { DropdownItem } from 'reactstrap';
 
 
 import { exportAsMarkdown, updateContentWidth, syncLatestRevisionBody } from '~/client/services/page-operation';
 import { exportAsMarkdown, updateContentWidth, syncLatestRevisionBody } from '~/client/services/page-operation';
-import { toastSuccess, toastError } from '~/client/util/toastr';
+import { toastSuccess, toastError, toastWarning } from '~/client/util/toastr';
 import { GroundGlassBar } from '~/components/Navbar/GroundGlassBar';
 import { GroundGlassBar } from '~/components/Navbar/GroundGlassBar';
 import type { OnDuplicatedFunction, OnRenamedFunction, OnDeletedFunction } from '~/interfaces/ui';
 import type { OnDuplicatedFunction, OnRenamedFunction, OnDeletedFunction } from '~/interfaces/ui';
 import { useShouldExpandContent } from '~/services/layout/use-should-expand-content';
 import { useShouldExpandContent } from '~/services/layout/use-should-expand-content';
@@ -77,19 +79,34 @@ const PageOperationMenuItems = (props: PageOperationMenuItemsProps): JSX.Element
   const { open: openPresentationModal } = usePagePresentationModal();
   const { open: openPresentationModal } = usePagePresentationModal();
   const { open: openAccessoriesModal } = usePageAccessoriesModal();
   const { open: openAccessoriesModal } = usePageAccessoriesModal();
 
 
+  const { data: codeMirrorEditor } = useCodeMirrorEditorIsolated(GlobalCodeMirrorEditorKey.MAIN);
+
   const syncLatestRevisionBodyHandler = useCallback(async() => {
   const syncLatestRevisionBodyHandler = useCallback(async() => {
     // eslint-disable-next-line no-alert
     // eslint-disable-next-line no-alert
-    const answer = window.confirm(t('sync-latest-reevision-body.confirm'));
+    const answer = window.confirm(t('sync-latest-revision-body.confirm'));
     if (answer) {
     if (answer) {
       try {
       try {
-        await syncLatestRevisionBody(pageId);
-        toastSuccess(t('sync-latest-reevision-body.success-toaster'));
+        const editingMarkdownLength = codeMirrorEditor?.getDoc().length;
+        const res = await syncLatestRevisionBody(pageId, editingMarkdownLength);
+
+        if (!res.synced) {
+          toastWarning(t('sync-latest-revision-body.skipped-toaster'));
+          return;
+        }
+
+        if (res?.isYjsDataBroken) {
+          // eslint-disable-next-line no-alert
+          window.alert(t('sync-latest-revision-body.alert'));
+          return;
+        }
+
+        toastSuccess(t('sync-latest-revision-body.success-toaster'));
       }
       }
       catch {
       catch {
-        toastError(t('sync-latest-reevision-body.error-toaster'));
+        toastError(t('sync-latest-revision-body.error-toaster'));
       }
       }
     }
     }
-  }, [pageId, t]);
+  }, [codeMirrorEditor, pageId, t]);
 
 
   return (
   return (
     <>
     <>
@@ -98,7 +115,7 @@ const PageOperationMenuItems = (props: PageOperationMenuItemsProps): JSX.Element
         className="grw-page-control-dropdown-item"
         className="grw-page-control-dropdown-item"
       >
       >
         <span className="material-symbols-outlined me-1 grw-page-control-dropdown-icon">sync</span>
         <span className="material-symbols-outlined me-1 grw-page-control-dropdown-icon">sync</span>
-        {t('SyncLatestRevisionBody')}
+        {t('sync-latest-revision-body.menuitem')}
       </DropdownItem>
       </DropdownItem>
 
 
       {/* Presentation */}
       {/* Presentation */}

+ 0 - 1
apps/app/src/client/components/PageControls/PageControls.tsx

@@ -1,4 +1,3 @@
-import type { MouseEventHandler } from 'react';
 import React, {
 import React, {
   memo, useCallback, useEffect, useMemo, useRef,
   memo, useCallback, useEffect, useMemo, useRef,
 } from 'react';
 } from 'react';

+ 10 - 1
apps/app/src/client/components/ReactMarkdownComponents/DrawioViewerWithEditButton.tsx

@@ -13,6 +13,7 @@ import {
   useIsGuestUser, useIsReadOnlyUser, useIsSharedUser, useShareLinkId,
   useIsGuestUser, useIsReadOnlyUser, useIsSharedUser, useShareLinkId,
 } from '~/stores-universal/context';
 } from '~/stores-universal/context';
 import { useIsRevisionOutdated } from '~/stores/page';
 import { useIsRevisionOutdated } from '~/stores/page';
+import { useCurrentPageYjsData } from '~/stores/yjs';
 
 
 import '@growi/remark-drawio/dist/style.css';
 import '@growi/remark-drawio/dist/style.css';
 import styles from './DrawioViewerWithEditButton.module.scss';
 import styles from './DrawioViewerWithEditButton.module.scss';
@@ -34,6 +35,7 @@ export const DrawioViewerWithEditButton = React.memo((props: DrawioViewerProps):
   const { data: isSharedUser } = useIsSharedUser();
   const { data: isSharedUser } = useIsSharedUser();
   const { data: shareLinkId } = useShareLinkId();
   const { data: shareLinkId } = useShareLinkId();
   const { data: isRevisionOutdated } = useIsRevisionOutdated();
   const { data: isRevisionOutdated } = useIsRevisionOutdated();
+  const { data: currentPageYjsData } = useCurrentPageYjsData();
 
 
   const [isRendered, setRendered] = useState(false);
   const [isRendered, setRendered] = useState(false);
   const [mxfile, setMxfile] = useState('');
   const [mxfile, setMxfile] = useState('');
@@ -57,7 +59,14 @@ export const DrawioViewerWithEditButton = React.memo((props: DrawioViewerProps):
     }
     }
   }, []);
   }, []);
 
 
-  const showEditButton = !isRevisionOutdated && isRendered && !isGuestUser && !isReadOnlyUser && !isSharedUser && shareLinkId == null;
+  const isNoEditingUsers = currentPageYjsData?.awarenessStateSize == null || currentPageYjsData?.awarenessStateSize === 0;
+  const showEditButton = isNoEditingUsers
+     && !isRevisionOutdated
+     && isRendered
+     && !isGuestUser
+     && !isReadOnlyUser
+     && !isSharedUser
+     && shareLinkId == null;
 
 
   return (
   return (
     <div className={`drawio-viewer-with-edit-button ${styles['drawio-viewer-with-edit-button']}`}>
     <div className={`drawio-viewer-with-edit-button ${styles['drawio-viewer-with-edit-button']}`}>

+ 9 - 1
apps/app/src/client/components/ReactMarkdownComponents/TableWithEditButton.tsx

@@ -8,6 +8,7 @@ import {
   useIsGuestUser, useIsReadOnlyUser, useIsSharedUser, useShareLinkId,
   useIsGuestUser, useIsReadOnlyUser, useIsSharedUser, useShareLinkId,
 } from '~/stores-universal/context';
 } from '~/stores-universal/context';
 import { useIsRevisionOutdated } from '~/stores/page';
 import { useIsRevisionOutdated } from '~/stores/page';
+import { useCurrentPageYjsData } from '~/stores/yjs';
 
 
 import styles from './TableWithEditButton.module.scss';
 import styles from './TableWithEditButton.module.scss';
 
 
@@ -31,6 +32,7 @@ export const TableWithEditButton = React.memo((props: TableWithEditButtonProps):
   const { data: isSharedUser } = useIsSharedUser();
   const { data: isSharedUser } = useIsSharedUser();
   const { data: shareLinkId } = useShareLinkId();
   const { data: shareLinkId } = useShareLinkId();
   const { data: isRevisionOutdated } = useIsRevisionOutdated();
   const { data: isRevisionOutdated } = useIsRevisionOutdated();
+  const { data: currentPageYjsData } = useCurrentPageYjsData();
 
 
   const bol = node.position?.start.line;
   const bol = node.position?.start.line;
   const eol = node.position?.end.line;
   const eol = node.position?.end.line;
@@ -39,7 +41,13 @@ export const TableWithEditButton = React.memo((props: TableWithEditButtonProps):
     globalEmitter.emit('launchHandsonTableModal', bol, eol);
     globalEmitter.emit('launchHandsonTableModal', bol, eol);
   }, [bol, eol]);
   }, [bol, eol]);
 
 
-  const showEditButton = !isRevisionOutdated && !isGuestUser && !isReadOnlyUser && !isSharedUser && shareLinkId == null;
+  const isNoEditingUsers = currentPageYjsData?.awarenessStateSize == null || currentPageYjsData?.awarenessStateSize === 0;
+  const showEditButton = isNoEditingUsers
+    && !isRevisionOutdated
+    && !isGuestUser
+    && !isReadOnlyUser
+    && !isSharedUser
+    && shareLinkId == null;
 
 
   return (
   return (
     <div className={`editable-with-handsontable ${styles['editable-with-handsontable']}`}>
     <div className={`editable-with-handsontable ${styles['editable-with-handsontable']}`}>

+ 4 - 3
apps/app/src/client/services/page-operation.ts

@@ -4,6 +4,7 @@ import type { IPageHasId } from '@growi/core';
 import { SubscriptionStatusType } from '@growi/core';
 import { SubscriptionStatusType } from '@growi/core';
 import urljoin from 'url-join';
 import urljoin from 'url-join';
 
 
+import type { SyncLatestRevisionBody } from '~/interfaces/yjs';
 import { useEditingMarkdown, usePageTagsForEditors } from '~/stores/editor';
 import { useEditingMarkdown, usePageTagsForEditors } from '~/stores/editor';
 import {
 import {
   useCurrentPageId, useSWRMUTxCurrentPage, useSWRxApplicableGrant, useSWRxTagsInfo,
   useCurrentPageId, useSWRMUTxCurrentPage, useSWRxApplicableGrant, useSWRxTagsInfo,
@@ -175,7 +176,7 @@ export const unpublish = async(pageId: string): Promise<IPageHasId> => {
   return res.data;
   return res.data;
 };
 };
 
 
-export const syncLatestRevisionBody = async(pageId: string): Promise<void> => {
-  await apiv3Put(`/page/${pageId}/sync-latest-revision-body-to-yjs-draft`);
-  return;
+export const syncLatestRevisionBody = async(pageId: string, editingMarkdownLength?: number): Promise<SyncLatestRevisionBody> => {
+  const res = await apiv3Put(`/page/${pageId}/sync-latest-revision-body-to-yjs-draft`, { editingMarkdownLength });
+  return res.data;
 };
 };

+ 5 - 0
apps/app/src/interfaces/yjs.ts

@@ -2,3 +2,8 @@ export type CurrentPageYjsData = {
   hasYdocsNewerThanLatestRevision?: boolean,
   hasYdocsNewerThanLatestRevision?: boolean,
   awarenessStateSize?: number,
   awarenessStateSize?: number,
 }
 }
+
+export type SyncLatestRevisionBody = {
+  synced: boolean,
+  isYjsDataBroken?: boolean,
+}

+ 2 - 4
apps/app/src/server/crowi/index.js

@@ -34,6 +34,7 @@ import PageOperationService from '../service/page-operation';
 import PassportService from '../service/passport';
 import PassportService from '../service/passport';
 import SearchService from '../service/search';
 import SearchService from '../service/search';
 import { SlackIntegrationService } from '../service/slack-integration';
 import { SlackIntegrationService } from '../service/slack-integration';
+import { SocketIoService } from '../service/socket-io';
 import UserGroupService from '../service/user-group';
 import UserGroupService from '../service/user-group';
 import { UserNotificationService } from '../service/user-notification';
 import { UserNotificationService } from '../service/user-notification';
 import { initializeYjsService } from '../service/yjs';
 import { initializeYjsService } from '../service/yjs';
@@ -301,10 +302,7 @@ Crowi.prototype.setupS2sMessagingService = async function() {
 };
 };
 
 
 Crowi.prototype.setupSocketIoService = async function() {
 Crowi.prototype.setupSocketIoService = async function() {
-  const SocketIoService = require('../service/socket-io');
-  if (this.socketIoService == null) {
-    this.socketIoService = new SocketIoService(this);
-  }
+  this.socketIoService = new SocketIoService(this);
 };
 };
 
 
 Crowi.prototype.setupModels = async function() {
 Crowi.prototype.setupModels = async function() {

+ 2 - 0
apps/app/src/server/models/revision.ts

@@ -34,6 +34,8 @@ export interface IRevisionModel extends Model<IRevisionDocument> {
 Schema.Types.String.checkRequired(v => typeof v === 'string');
 Schema.Types.String.checkRequired(v => typeof v === 'string');
 
 
 const revisionSchema = new Schema<IRevisionDocument, IRevisionModel>({
 const revisionSchema = new Schema<IRevisionDocument, IRevisionModel>({
+  // The type of pageId is always converted to String at server startup
+  // Refer to this method (/src/server/service/normalize-data/convert-revision-page-id-to-string.ts) to change the pageId type
   pageId: {
   pageId: {
     type: String, required: true, index: true,
     type: String, required: true, index: true,
   },
   },

+ 9 - 4
apps/app/src/server/routes/apiv3/page/sync-latest-revision-body-to-yjs-draft.ts

@@ -2,7 +2,7 @@ import type { IPage, IUserHasId } from '@growi/core';
 import { ErrorV3 } from '@growi/core/dist/models';
 import { ErrorV3 } from '@growi/core/dist/models';
 import type { Request, RequestHandler } from 'express';
 import type { Request, RequestHandler } from 'express';
 import type { ValidationChain } from 'express-validator';
 import type { ValidationChain } from 'express-validator';
-import { param } from 'express-validator';
+import { param, body } from 'express-validator';
 import mongoose from 'mongoose';
 import mongoose from 'mongoose';
 
 
 import type Crowi from '~/server/crowi';
 import type Crowi from '~/server/crowi';
@@ -21,7 +21,10 @@ type SyncLatestRevisionBodyToYjsDraftHandlerFactory = (crowi: Crowi) => RequestH
 type ReqParams = {
 type ReqParams = {
   pageId: string,
   pageId: string,
 }
 }
-interface Req extends Request<ReqParams, ApiV3Response> {
+type ReqBody = {
+  editingMarkdownLength?: number,
+}
+interface Req extends Request<ReqParams, ApiV3Response, ReqBody> {
   user: IUserHasId,
   user: IUserHasId,
 }
 }
 export const syncLatestRevisionBodyToYjsDraftHandlerFactory: SyncLatestRevisionBodyToYjsDraftHandlerFactory = (crowi) => {
 export const syncLatestRevisionBodyToYjsDraftHandlerFactory: SyncLatestRevisionBodyToYjsDraftHandlerFactory = (crowi) => {
@@ -32,6 +35,7 @@ export const syncLatestRevisionBodyToYjsDraftHandlerFactory: SyncLatestRevisionB
   // define validators for req.params
   // define validators for req.params
   const validator: ValidationChain[] = [
   const validator: ValidationChain[] = [
     param('pageId').isMongoId().withMessage('The param "pageId" must be specified'),
     param('pageId').isMongoId().withMessage('The param "pageId" must be specified'),
+    body('editingMarkdownLength').optional().isInt().withMessage('The body "editingMarkdownLength" must be integer'),
   ];
   ];
 
 
   return [
   return [
@@ -39,6 +43,7 @@ export const syncLatestRevisionBodyToYjsDraftHandlerFactory: SyncLatestRevisionB
     validator, apiV3FormValidator,
     validator, apiV3FormValidator,
     async(req: Req, res: ApiV3Response) => {
     async(req: Req, res: ApiV3Response) => {
       const { pageId } = req.params;
       const { pageId } = req.params;
+      const { editingMarkdownLength } = req.body;
 
 
       // check whether accessible
       // check whether accessible
       if (!(await Page.isAccessiblePageByViewer(pageId, req.user))) {
       if (!(await Page.isAccessiblePageByViewer(pageId, req.user))) {
@@ -47,8 +52,8 @@ export const syncLatestRevisionBodyToYjsDraftHandlerFactory: SyncLatestRevisionB
 
 
       try {
       try {
         const yjsService = getYjsService();
         const yjsService = getYjsService();
-        await yjsService.syncWithTheLatestRevisionForce(pageId);
-        return res.apiv3({ });
+        const result = await yjsService.syncWithTheLatestRevisionForce(pageId, editingMarkdownLength);
+        return res.apiv3(result);
       }
       }
       catch (err) {
       catch (err) {
         logger.error(err);
         logger.error(err);

+ 1 - 1
apps/app/src/server/service/config-manager.ts

@@ -214,7 +214,7 @@ class ConfigManagerImpl implements ConfigManager, S2sMessageHandlable {
     }
     }
   }
   }
 
 
-  async removeConfigsInTheSameNamespace(namespace, configKeys: string[], withoutPublishingS2sMessage?) {
+  async removeConfigsInTheSameNamespace(namespace, configKeys: readonly string[], withoutPublishingS2sMessage?) {
     const queries: any[] = [];
     const queries: any[] = [];
     for (const key of configKeys) {
     for (const key of configKeys) {
       queries.push({
       queries.push({

+ 28 - 23
apps/app/src/server/service/file-uploader/aws.ts

@@ -1,3 +1,5 @@
+import type { ReadStream } from 'fs';
+
 import type { GetObjectCommandInput, HeadObjectCommandInput } from '@aws-sdk/client-s3';
 import type { GetObjectCommandInput, HeadObjectCommandInput } from '@aws-sdk/client-s3';
 import {
 import {
   S3Client,
   S3Client,
@@ -142,6 +144,32 @@ class AwsFileUploader extends AbstractFileUploader {
       : ResponseMode.REDIRECT;
       : ResponseMode.REDIRECT;
   }
   }
 
 
+  /**
+   * @inheritdoc
+   */
+  override async uploadAttachment(readStream: ReadStream, attachment: IAttachmentDocument): Promise<void> {
+    if (!this.getIsUploadable()) {
+      throw new Error('AWS is not configured.');
+    }
+
+    logger.debug(`File uploading: fileName=${attachment.fileName}`);
+
+    const s3 = S3Factory();
+
+    const filePath = getFilePathOnStorage(attachment);
+    const contentHeaders = new ContentHeaders(attachment);
+
+    await s3.send(new PutObjectCommand({
+      Bucket: getS3Bucket(),
+      Key: filePath,
+      Body: readStream,
+      ACL: getS3PutObjectCannedAcl(),
+      // put type and the file name for reference information when uploading
+      ContentType: contentHeaders.contentType?.value.toString(),
+      ContentDisposition: contentHeaders.contentDisposition?.value.toString(),
+    }));
+  }
+
   /**
   /**
    * @inheritdoc
    * @inheritdoc
    */
    */
@@ -280,29 +308,6 @@ module.exports = (crowi) => {
     return s3.send(new DeleteObjectCommand(params));
     return s3.send(new DeleteObjectCommand(params));
   };
   };
 
 
-  (lib as any).uploadAttachment = async function(fileStream, attachment) {
-    if (!lib.getIsUploadable()) {
-      throw new Error('AWS is not configured.');
-    }
-
-    logger.debug(`File uploading: fileName=${attachment.fileName}`);
-
-    const s3 = S3Factory();
-
-    const filePath = getFilePathOnStorage(attachment);
-    const contentHeaders = new ContentHeaders(attachment);
-
-    return s3.send(new PutObjectCommand({
-      Bucket: getS3Bucket(),
-      Key: filePath,
-      Body: fileStream,
-      ACL: getS3PutObjectCannedAcl(),
-      // put type and the file name for reference information when uploading
-      ContentType: contentHeaders.contentType?.value.toString(),
-      ContentDisposition: contentHeaders.contentDisposition?.value.toString(),
-    }));
-  };
-
   lib.saveFile = async function({ filePath, contentType, data }) {
   lib.saveFile = async function({ filePath, contentType, data }) {
     const s3 = S3Factory();
     const s3 = S3Factory();
 
 

+ 32 - 24
apps/app/src/server/service/file-uploader/azure.ts

@@ -1,11 +1,16 @@
-import { ClientSecretCredential, TokenCredential } from '@azure/identity';
-import {
-  generateBlobSASQueryParameters,
-  BlobServiceClient,
+import type { ReadStream } from 'fs';
+
+import type { TokenCredential } from '@azure/identity';
+import { ClientSecretCredential } from '@azure/identity';
+import type {
   BlobClient,
   BlobClient,
   BlockBlobClient,
   BlockBlobClient,
   BlobDeleteOptions,
   BlobDeleteOptions,
   ContainerClient,
   ContainerClient,
+} from '@azure/storage-blob';
+import {
+  generateBlobSASQueryParameters,
+  BlobServiceClient,
   ContainerSASPermissions,
   ContainerSASPermissions,
   SASProtocol,
   SASProtocol,
   type BlobDeleteIfExistsResponse,
   type BlobDeleteIfExistsResponse,
@@ -94,6 +99,29 @@ class AzureFileUploader extends AbstractFileUploader {
     throw new Error('Method not implemented.');
     throw new Error('Method not implemented.');
   }
   }
 
 
+  /**
+   * @inheritdoc
+   */
+  override async uploadAttachment(readStream: ReadStream, attachment: IAttachmentDocument): Promise<void> {
+    if (!this.getIsUploadable()) {
+      throw new Error('Azure is not configured.');
+    }
+
+    logger.debug(`File uploading: fileName=${attachment.fileName}`);
+    const filePath = getFilePathOnStorage(attachment);
+    const containerClient = await getContainerClient();
+    const blockBlobClient: BlockBlobClient = containerClient.getBlockBlobClient(filePath);
+    const contentHeaders = new ContentHeaders(attachment);
+
+    await blockBlobClient.uploadStream(readStream, undefined, undefined, {
+      blobHTTPHeaders: {
+        // put type and the file name for reference information when uploading
+        blobContentType: contentHeaders.contentType?.value.toString(),
+        blobContentDisposition: contentHeaders.contentDisposition?.value.toString(),
+      },
+    });
+  }
+
   /**
   /**
    * @inheritdoc
    * @inheritdoc
    */
    */
@@ -218,26 +246,6 @@ module.exports = (crowi) => {
     }
     }
   };
   };
 
 
-  (lib as any).uploadAttachment = async function(readStream, attachment) {
-    if (!lib.getIsUploadable()) {
-      throw new Error('Azure is not configured.');
-    }
-
-    logger.debug(`File uploading: fileName=${attachment.fileName}`);
-    const filePath = getFilePathOnStorage(attachment);
-    const containerClient = await getContainerClient();
-    const blockBlobClient: BlockBlobClient = containerClient.getBlockBlobClient(filePath);
-    const contentHeaders = new ContentHeaders(attachment);
-
-    return blockBlobClient.uploadStream(readStream, undefined, undefined, {
-      blobHTTPHeaders: {
-        // put type and the file name for reference information when uploading
-        blobContentType: contentHeaders.contentType?.value.toString(),
-        blobContentDisposition: contentHeaders.contentDisposition?.value.toString(),
-      },
-    });
-  };
-
   lib.saveFile = async function({ filePath, contentType, data }) {
   lib.saveFile = async function({ filePath, contentType, data }) {
     const containerClient = await getContainerClient();
     const containerClient = await getContainerClient();
     const blockBlobClient: BlockBlobClient = containerClient.getBlockBlobClient(filePath);
     const blockBlobClient: BlockBlobClient = containerClient.getBlockBlobClient(filePath);

+ 4 - 0
apps/app/src/server/service/file-uploader/file-uploader.ts

@@ -1,4 +1,5 @@
 import { randomUUID } from 'crypto';
 import { randomUUID } from 'crypto';
+import type { ReadStream } from 'fs';
 
 
 import type { Response } from 'express';
 import type { Response } from 'express';
 
 
@@ -36,6 +37,7 @@ export interface FileUploader {
   getTotalFileSize(): Promise<number>,
   getTotalFileSize(): Promise<number>,
   doCheckLimit(uploadFileSize: number, maxFileSize: number, totalLimit: number): Promise<ICheckLimitResult>,
   doCheckLimit(uploadFileSize: number, maxFileSize: number, totalLimit: number): Promise<ICheckLimitResult>,
   determineResponseMode(): ResponseMode,
   determineResponseMode(): ResponseMode,
+  uploadAttachment(readStream: ReadStream, attachment: IAttachmentDocument): Promise<void>,
   respond(res: Response, attachment: IAttachmentDocument, opts?: RespondOptions): void,
   respond(res: Response, attachment: IAttachmentDocument, opts?: RespondOptions): void,
   findDeliveryFile(attachment: IAttachmentDocument): Promise<NodeJS.ReadableStream>,
   findDeliveryFile(attachment: IAttachmentDocument): Promise<NodeJS.ReadableStream>,
   generateTemporaryUrl(attachment: IAttachmentDocument, opts?: RespondOptions): Promise<TemporaryUrl>,
   generateTemporaryUrl(attachment: IAttachmentDocument, opts?: RespondOptions): Promise<TemporaryUrl>,
@@ -151,6 +153,8 @@ export abstract class AbstractFileUploader implements FileUploader {
     return ResponseMode.RELAY;
     return ResponseMode.RELAY;
   }
   }
 
 
+ abstract uploadAttachment(readStream: ReadStream, attachment: IAttachmentDocument): Promise<void>;
+
   /**
   /**
    * Respond to the HTTP request.
    * Respond to the HTTP request.
    */
    */

+ 24 - 19
apps/app/src/server/service/file-uploader/gcs.ts

@@ -1,3 +1,5 @@
+import type { ReadStream } from 'fs';
+
 import { Storage } from '@google-cloud/storage';
 import { Storage } from '@google-cloud/storage';
 import urljoin from 'url-join';
 import urljoin from 'url-join';
 
 
@@ -94,6 +96,28 @@ class GcsFileUploader extends AbstractFileUploader {
       : ResponseMode.REDIRECT;
       : ResponseMode.REDIRECT;
   }
   }
 
 
+  /**
+   * @inheritdoc
+   */
+  override async uploadAttachment(readStream: ReadStream, attachment: IAttachmentDocument): Promise<void> {
+    if (!this.getIsUploadable()) {
+      throw new Error('GCS is not configured.');
+    }
+
+    logger.debug(`File uploading: fileName=${attachment.fileName}`);
+
+    const gcs = getGcsInstance();
+    const myBucket = gcs.bucket(getGcsBucket());
+    const filePath = getFilePathOnStorage(attachment);
+    const contentHeaders = new ContentHeaders(attachment);
+
+    await myBucket.upload(readStream.path.toString(), {
+      destination: filePath,
+      // put type and the file name for reference information when uploading
+      contentType: contentHeaders.contentType?.value.toString(),
+    });
+  }
+
   /**
   /**
    * @inheritdoc
    * @inheritdoc
    */
    */
@@ -201,25 +225,6 @@ module.exports = function(crowi: Crowi) {
     });
     });
   };
   };
 
 
-  (lib as any).uploadAttachment = function(fileStream, attachment) {
-    if (!lib.getIsUploadable()) {
-      throw new Error('GCS is not configured.');
-    }
-
-    logger.debug(`File uploading: fileName=${attachment.fileName}`);
-
-    const gcs = getGcsInstance();
-    const myBucket = gcs.bucket(getGcsBucket());
-    const filePath = getFilePathOnStorage(attachment);
-    const contentHeaders = new ContentHeaders(attachment);
-
-    return myBucket.upload(fileStream.path, {
-      destination: filePath,
-      // put type and the file name for reference information when uploading
-      contentType: contentHeaders.contentType?.value.toString(),
-    });
-  };
-
   lib.saveFile = async function({ filePath, contentType, data }) {
   lib.saveFile = async function({ filePath, contentType, data }) {
     const gcs = getGcsInstance();
     const gcs = getGcsInstance();
     const myBucket = gcs.bucket(getGcsBucket());
     const myBucket = gcs.bucket(getGcsBucket());

+ 30 - 24
apps/app/src/server/service/file-uploader/gridfs.ts

@@ -1,3 +1,4 @@
+import type { ReadStream } from 'fs';
 import { Readable } from 'stream';
 import { Readable } from 'stream';
 import util from 'util';
 import util from 'util';
 
 
@@ -16,6 +17,17 @@ import { ContentHeaders } from './utils';
 const logger = loggerFactory('growi:service:fileUploaderGridfs');
 const logger = loggerFactory('growi:service:fileUploaderGridfs');
 
 
 
 
+const COLLECTION_NAME = 'attachmentFiles';
+const CHUNK_COLLECTION_NAME = `${COLLECTION_NAME}.chunks`;
+
+// instantiate mongoose-gridfs
+const AttachmentFile = createModel({
+  modelName: COLLECTION_NAME,
+  bucketName: COLLECTION_NAME,
+  connection: mongoose.connection,
+});
+
+
 // TODO: rewrite this module to be a type-safe implementation
 // TODO: rewrite this module to be a type-safe implementation
 class GridfsFileUploader extends AbstractFileUploader {
 class GridfsFileUploader extends AbstractFileUploader {
 
 
@@ -47,6 +59,24 @@ class GridfsFileUploader extends AbstractFileUploader {
     throw new Error('Method not implemented.');
     throw new Error('Method not implemented.');
   }
   }
 
 
+  /**
+   * @inheritdoc
+   */
+  override async uploadAttachment(readStream: ReadStream, attachment: IAttachmentDocument): Promise<void> {
+    logger.debug(`File uploading: fileName=${attachment.fileName}`);
+
+    const contentHeaders = new ContentHeaders(attachment);
+
+    return AttachmentFile.promisifiedWrite(
+      {
+        // put type and the file name for reference information when uploading
+        filename: attachment.fileName,
+        contentType: contentHeaders.contentType?.value.toString(),
+      },
+      readStream,
+    );
+  }
+
   /**
   /**
    * @inheritdoc
    * @inheritdoc
    */
    */
@@ -73,15 +103,6 @@ class GridfsFileUploader extends AbstractFileUploader {
 
 
 module.exports = function(crowi) {
 module.exports = function(crowi) {
   const lib = new GridfsFileUploader(crowi);
   const lib = new GridfsFileUploader(crowi);
-  const COLLECTION_NAME = 'attachmentFiles';
-  const CHUNK_COLLECTION_NAME = `${COLLECTION_NAME}.chunks`;
-
-  // instantiate mongoose-gridfs
-  const AttachmentFile = createModel({
-    modelName: COLLECTION_NAME,
-    bucketName: COLLECTION_NAME,
-    connection: mongoose.connection,
-  });
 
 
   // get Collection instance of chunk
   // get Collection instance of chunk
   const chunkCollection = mongoose.connection.collection(CHUNK_COLLECTION_NAME);
   const chunkCollection = mongoose.connection.collection(CHUNK_COLLECTION_NAME);
@@ -150,21 +171,6 @@ module.exports = function(crowi) {
     return lib.doCheckLimit(uploadFileSize, maxFileSize, totalLimit);
     return lib.doCheckLimit(uploadFileSize, maxFileSize, totalLimit);
   };
   };
 
 
-  (lib as any).uploadAttachment = async function(fileStream, attachment) {
-    logger.debug(`File uploading: fileName=${attachment.fileName}`);
-
-    const contentHeaders = new ContentHeaders(attachment);
-
-    return AttachmentFile.promisifiedWrite(
-      {
-        // put type and the file name for reference information when uploading
-        filename: attachment.fileName,
-        contentType: contentHeaders.contentType?.value.toString(),
-      },
-      fileStream,
-    );
-  };
-
   lib.saveFile = async function({ filePath, contentType, data }) {
   lib.saveFile = async function({ filePath, contentType, data }) {
     const readable = new Readable();
     const readable = new Readable();
     readable.push(data);
     readable.push(data);

+ 9 - 1
apps/app/src/server/service/file-uploader/local.ts

@@ -1,3 +1,4 @@
+import type { ReadStream } from 'fs';
 import { Readable } from 'stream';
 import { Readable } from 'stream';
 
 
 import type { Response } from 'express';
 import type { Response } from 'express';
@@ -71,6 +72,13 @@ class LocalFileUploader extends AbstractFileUploader {
       : ResponseMode.RELAY;
       : ResponseMode.RELAY;
   }
   }
 
 
+  /**
+   * @inheritdoc
+   */
+  override async uploadAttachment(readStream: ReadStream, attachment: IAttachmentDocument): Promise<void> {
+    throw new Error('Method not implemented.');
+  }
+
   /**
   /**
    * @inheritdoc
    * @inheritdoc
    */
    */
@@ -146,7 +154,7 @@ module.exports = function(crowi) {
     return fs.unlinkSync(filePath);
     return fs.unlinkSync(filePath);
   };
   };
 
 
-  (lib as any).uploadAttachment = async function(fileStream, attachment) {
+  lib.uploadAttachment = async function(fileStream, attachment) {
     logger.debug(`File uploading: fileName=${attachment.fileName}`);
     logger.debug(`File uploading: fileName=${attachment.fileName}`);
 
 
     const filePath = getFilePathOnStorage(attachment);
     const filePath = getFilePathOnStorage(attachment);

+ 24 - 24
apps/app/src/server/service/g2g-transfer.ts

@@ -1,6 +1,7 @@
-import { createReadStream, ReadStream } from 'fs';
+import type { ReadStream } from 'fs';
+import { createReadStream } from 'fs';
 import { basename } from 'path';
 import { basename } from 'path';
-import { Readable } from 'stream';
+import type { Readable } from 'stream';
 
 
 // eslint-disable-next-line no-restricted-imports
 // eslint-disable-next-line no-restricted-imports
 import rawAxios, { type AxiosRequestConfig } from 'axios';
 import rawAxios, { type AxiosRequestConfig } from 'axios';
@@ -201,10 +202,10 @@ interface Receiver {
   updateFileUploadConfigs(fileUploadConfigs: FileUploadConfigs): Promise<void>
   updateFileUploadConfigs(fileUploadConfigs: FileUploadConfigs): Promise<void>
   /**
   /**
    * Upload attachment file
    * Upload attachment file
-   * @param {Readable} content Pushed attachment data from source GROWI
+   * @param {ReadStream} content Pushed attachment data from source GROWI
    * @param {any} attachmentMap Map-ped Attachment instance
    * @param {any} attachmentMap Map-ped Attachment instance
    */
    */
-  receiveAttachment(content: Readable, attachmentMap: any): Promise<void>
+  receiveAttachment(content: ReadStream, attachmentMap: any): Promise<void>
 }
 }
 
 
 /**
 /**
@@ -325,7 +326,7 @@ export class G2GTransferPusherService implements Pusher {
   public async transferAttachments(tk: TransferKey): Promise<void> {
   public async transferAttachments(tk: TransferKey): Promise<void> {
     const BATCH_SIZE = 100;
     const BATCH_SIZE = 100;
     const { fileUploadService, socketIoService } = this.crowi;
     const { fileUploadService, socketIoService } = this.crowi;
-    const socket = socketIoService.getAdminSocket();
+    const socket = socketIoService?.getAdminSocket();
     const filesFromSrcGROWI = await this.listFilesInStorage(tk);
     const filesFromSrcGROWI = await this.listFilesInStorage(tk);
 
 
     /**
     /**
@@ -390,7 +391,7 @@ export class G2GTransferPusherService implements Pusher {
         }
         }
         catch (err) {
         catch (err) {
           logger.warn(`Error occured when getting Attachment(ID=${attachment.id}), skipping: `, err);
           logger.warn(`Error occured when getting Attachment(ID=${attachment.id}), skipping: `, err);
-          socket.emit('admin:g2gError', {
+          socket?.emit('admin:g2gError', {
             message: `Error occured when uploading Attachment(ID=${attachment.id})`,
             message: `Error occured when uploading Attachment(ID=${attachment.id})`,
             key: `Error occured when uploading Attachment(ID=${attachment.id})`,
             key: `Error occured when uploading Attachment(ID=${attachment.id})`,
             // TODO: emit error with params
             // TODO: emit error with params
@@ -404,7 +405,7 @@ export class G2GTransferPusherService implements Pusher {
         }
         }
         catch (err) {
         catch (err) {
           logger.error(`Error occured when uploading attachment(ID=${attachment.id})`, err);
           logger.error(`Error occured when uploading attachment(ID=${attachment.id})`, err);
-          socket.emit('admin:g2gError', {
+          socket?.emit('admin:g2gError', {
             message: `Error occured when uploading Attachment(ID=${attachment.id})`,
             message: `Error occured when uploading Attachment(ID=${attachment.id})`,
             key: `Error occured when uploading Attachment(ID=${attachment.id})`,
             key: `Error occured when uploading Attachment(ID=${attachment.id})`,
             // TODO: emit error with params
             // TODO: emit error with params
@@ -417,9 +418,9 @@ export class G2GTransferPusherService implements Pusher {
 
 
   // eslint-disable-next-line max-len
   // eslint-disable-next-line max-len
   public async startTransfer(tk: TransferKey, user: any, collections: string[], optionsMap: any, destGROWIInfo: IDataGROWIInfo): Promise<void> {
   public async startTransfer(tk: TransferKey, user: any, collections: string[], optionsMap: any, destGROWIInfo: IDataGROWIInfo): Promise<void> {
-    const socket = this.crowi.socketIoService.getAdminSocket();
+    const socket = this.crowi.socketIoService?.getAdminSocket();
 
 
-    socket.emit('admin:g2gProgress', {
+    socket?.emit('admin:g2gProgress', {
       mongo: G2G_PROGRESS_STATUS.IN_PROGRESS,
       mongo: G2G_PROGRESS_STATUS.IN_PROGRESS,
       attachments: G2G_PROGRESS_STATUS.PENDING,
       attachments: G2G_PROGRESS_STATUS.PENDING,
     });
     });
@@ -439,11 +440,11 @@ export class G2GTransferPusherService implements Pusher {
     }
     }
     catch (err) {
     catch (err) {
       logger.error(err);
       logger.error(err);
-      socket.emit('admin:g2gProgress', {
+      socket?.emit('admin:g2gProgress', {
         mongo: G2G_PROGRESS_STATUS.ERROR,
         mongo: G2G_PROGRESS_STATUS.ERROR,
         attachments: G2G_PROGRESS_STATUS.PENDING,
         attachments: G2G_PROGRESS_STATUS.PENDING,
       });
       });
-      socket.emit('admin:g2gError', { message: 'Failed to generate GROWI archive file', key: 'admin:g2g:error_generate_growi_archive' });
+      socket?.emit('admin:g2gError', { message: 'Failed to generate GROWI archive file', key: 'admin:g2g:error_generate_growi_archive' });
       throw err;
       throw err;
     }
     }
 
 
@@ -462,15 +463,15 @@ export class G2GTransferPusherService implements Pusher {
     }
     }
     catch (err) {
     catch (err) {
       logger.error(err);
       logger.error(err);
-      socket.emit('admin:g2gProgress', {
+      socket?.emit('admin:g2gProgress', {
         mongo: G2G_PROGRESS_STATUS.ERROR,
         mongo: G2G_PROGRESS_STATUS.ERROR,
         attachments: G2G_PROGRESS_STATUS.PENDING,
         attachments: G2G_PROGRESS_STATUS.PENDING,
       });
       });
-      socket.emit('admin:g2gError', { message: 'Failed to send GROWI archive file to the destination GROWI', key: 'admin:g2g:error_send_growi_archive' });
+      socket?.emit('admin:g2gError', { message: 'Failed to send GROWI archive file to the destination GROWI', key: 'admin:g2g:error_send_growi_archive' });
       throw err;
       throw err;
     }
     }
 
 
-    socket.emit('admin:g2gProgress', {
+    socket?.emit('admin:g2gProgress', {
       mongo: G2G_PROGRESS_STATUS.COMPLETED,
       mongo: G2G_PROGRESS_STATUS.COMPLETED,
       attachments: G2G_PROGRESS_STATUS.IN_PROGRESS,
       attachments: G2G_PROGRESS_STATUS.IN_PROGRESS,
     });
     });
@@ -480,15 +481,15 @@ export class G2GTransferPusherService implements Pusher {
     }
     }
     catch (err) {
     catch (err) {
       logger.error(err);
       logger.error(err);
-      socket.emit('admin:g2gProgress', {
+      socket?.emit('admin:g2gProgress', {
         mongo: G2G_PROGRESS_STATUS.COMPLETED,
         mongo: G2G_PROGRESS_STATUS.COMPLETED,
         attachments: G2G_PROGRESS_STATUS.ERROR,
         attachments: G2G_PROGRESS_STATUS.ERROR,
       });
       });
-      socket.emit('admin:g2gError', { message: 'Failed to transfer attachments', key: 'admin:g2g:error_upload_attachment' });
+      socket?.emit('admin:g2gError', { message: 'Failed to transfer attachments', key: 'admin:g2g:error_upload_attachment' });
       throw err;
       throw err;
     }
     }
 
 
-    socket.emit('admin:g2gProgress', {
+    socket?.emit('admin:g2gProgress', {
       mongo: G2G_PROGRESS_STATUS.COMPLETED,
       mongo: G2G_PROGRESS_STATUS.COMPLETED,
       attachments: G2G_PROGRESS_STATUS.COMPLETED,
       attachments: G2G_PROGRESS_STATUS.COMPLETED,
     });
     });
@@ -516,9 +517,9 @@ export class G2GTransferPusherService implements Pusher {
  */
  */
 export class G2GTransferReceiverService implements Receiver {
 export class G2GTransferReceiverService implements Receiver {
 
 
-  crowi: any;
+  crowi: Crowi;
 
 
-  constructor(crowi: any) {
+  constructor(crowi: Crowi) {
     this.crowi = crowi;
     this.crowi = crowi;
   }
   }
 
 
@@ -539,7 +540,7 @@ export class G2GTransferReceiverService implements Receiver {
   }
   }
 
 
   public async answerGROWIInfo(): Promise<IDataGROWIInfo> {
   public async answerGROWIInfo(): Promise<IDataGROWIInfo> {
-    const { version, configManager, fileUploadService } = this.crowi;
+    const { version, fileUploadService } = this.crowi;
     const userUpperLimit = configManager.getConfig('crowi', 'security:userUpperLimit');
     const userUpperLimit = configManager.getConfig('crowi', 'security:userUpperLimit');
     const fileUploadDisabled = configManager.getConfig('crowi', 'app:fileUploadDisabled');
     const fileUploadDisabled = configManager.getConfig('crowi', 'app:fileUploadDisabled');
     const fileUploadTotalLimit = fileUploadService.getFileUploadTotalLimit();
     const fileUploadTotalLimit = fileUploadService.getFileUploadTotalLimit();
@@ -636,7 +637,7 @@ export class G2GTransferReceiverService implements Receiver {
       importSettingsMap: { [key: string]: ImportSettings; },
       importSettingsMap: { [key: string]: ImportSettings; },
       sourceGROWIUploadConfigs: FileUploadConfigs,
       sourceGROWIUploadConfigs: FileUploadConfigs,
   ): Promise<void> {
   ): Promise<void> {
-    const { configManager, importService, appService } = this.crowi;
+    const { importService, appService } = this.crowi;
     /** whether to keep current file upload configs */
     /** whether to keep current file upload configs */
     const shouldKeepUploadConfigs = configManager.getConfig('crowi', 'app:fileUploadType') !== 'none';
     const shouldKeepUploadConfigs = configManager.getConfig('crowi', 'app:fileUploadType') !== 'none';
 
 
@@ -664,7 +665,6 @@ export class G2GTransferReceiverService implements Receiver {
   }
   }
 
 
   public async getFileUploadConfigs(): Promise<FileUploadConfigs> {
   public async getFileUploadConfigs(): Promise<FileUploadConfigs> {
-    const { configManager } = this.crowi;
     const fileUploadConfigs = Object.fromEntries(UPLOAD_CONFIG_KEYS.map((key) => {
     const fileUploadConfigs = Object.fromEntries(UPLOAD_CONFIG_KEYS.map((key) => {
       return [key, configManager.getConfigFromDB('crowi', key)];
       return [key, configManager.getConfigFromDB('crowi', key)];
     })) as FileUploadConfigs;
     })) as FileUploadConfigs;
@@ -673,7 +673,7 @@ export class G2GTransferReceiverService implements Receiver {
   }
   }
 
 
   public async updateFileUploadConfigs(fileUploadConfigs: FileUploadConfigs): Promise<void> {
   public async updateFileUploadConfigs(fileUploadConfigs: FileUploadConfigs): Promise<void> {
-    const { appService, configManager } = this.crowi;
+    const { appService } = this.crowi;
 
 
     await configManager.removeConfigsInTheSameNamespace('crowi', Object.keys(fileUploadConfigs));
     await configManager.removeConfigsInTheSameNamespace('crowi', Object.keys(fileUploadConfigs));
     await configManager.updateConfigsInTheSameNamespace('crowi', fileUploadConfigs);
     await configManager.updateConfigsInTheSameNamespace('crowi', fileUploadConfigs);
@@ -681,7 +681,7 @@ export class G2GTransferReceiverService implements Receiver {
     await appService.setupAfterInstall();
     await appService.setupAfterInstall();
   }
   }
 
 
-  public async receiveAttachment(content: Readable, attachmentMap): Promise<void> {
+  public async receiveAttachment(content: ReadStream, attachmentMap): Promise<void> {
     const { fileUploadService } = this.crowi;
     const { fileUploadService } = this.crowi;
     return fileUploadService.uploadAttachment(content, attachmentMap);
     return fileUploadService.uploadAttachment(content, attachmentMap);
   }
   }

+ 2 - 1
apps/app/src/server/service/in-app-notification.ts

@@ -18,10 +18,11 @@ import Subscription from '~/server/models/subscription';
 import loggerFactory from '~/utils/logger';
 import loggerFactory from '~/utils/logger';
 
 
 import type Crowi from '../crowi';
 import type Crowi from '../crowi';
-import { RoomPrefix, getRoomNameWithId } from '../util/socket-io-helpers';
+
 
 
 import { generateSnapshot } from './in-app-notification/in-app-notification-utils';
 import { generateSnapshot } from './in-app-notification/in-app-notification-utils';
 import { preNotifyService, type PreNotify } from './pre-notify';
 import { preNotifyService, type PreNotify } from './pre-notify';
+import { RoomPrefix, getRoomNameWithId } from './socket-io/helper';
 
 
 
 
 const { STATUS_UNREAD, STATUS_UNOPENED, STATUS_OPENED } = InAppNotificationStatuses;
 const { STATUS_UNREAD, STATUS_UNOPENED, STATUS_OPENED } = InAppNotificationStatuses;

+ 29 - 0
apps/app/src/server/service/normalize-data/convert-revision-page-id-to-string.ts

@@ -0,0 +1,29 @@
+// see: https://redmine.weseek.co.jp/issues/150649
+
+import { type IRevisionHasId } from '@growi/core';
+import mongoose from 'mongoose';
+
+import { type IRevisionModel } from '~/server/models/revision';
+import loggerFactory from '~/utils/logger';
+
+const logger = loggerFactory('growi:service:NormalizeData:convert-revision-page-id-to-string');
+
+export const convertRevisionPageIdToString = async(): Promise<void> => {
+  const Revision = mongoose.model<IRevisionHasId, IRevisionModel>('Revision');
+
+  const filter = { pageId: { $type: 'objectId' } };
+  const update = [
+    {
+      $set: {
+        pageId: {
+          $toString: '$pageId',
+        },
+      },
+    },
+  ];
+
+  await Revision.updateMany(filter, update);
+
+  const explain = await Revision.updateMany(filter, update).explain('queryPlanner');
+  logger.debug(explain);
+};

+ 2 - 0
apps/app/src/server/service/normalize-data/index.ts

@@ -1,11 +1,13 @@
 import loggerFactory from '~/utils/logger';
 import loggerFactory from '~/utils/logger';
 
 
+import { convertRevisionPageIdToString } from './convert-revision-page-id-to-string';
 import { renameDuplicateRootPages } from './rename-duplicate-root-pages';
 import { renameDuplicateRootPages } from './rename-duplicate-root-pages';
 
 
 const logger = loggerFactory('growi:service:NormalizeData');
 const logger = loggerFactory('growi:service:NormalizeData');
 
 
 export const normalizeData = async(): Promise<void> => {
 export const normalizeData = async(): Promise<void> => {
   await renameDuplicateRootPages();
   await renameDuplicateRootPages();
+  await convertRevisionPageIdToString();
 
 
   logger.info('normalizeData has been executed');
   logger.info('normalizeData has been executed');
   return;
   return;

+ 23 - 2
apps/app/src/server/service/search-delegator/aggregate-to-index.ts

@@ -51,11 +51,32 @@ export const aggregatePipelineToIndex = (maxBodyLengthToIndex: number, query?: Q
 
 
     // join Comment
     // join Comment
     {
     {
+      // MongoDB 5.0 or later can use concise syntax
+      // https://www.mongodb.com/docs/v6.0/reference/operator/aggregation/lookup/#correlated-subqueries-using-concise-syntax
+      // $lookup: {
+      //   from: 'comments',
+      //   localField: '_id',
+      //   foreignField: 'page',
+      //   pipeline: [
+      //     {
+      //       $addFields: {
+      //         commentLength: { $strLenCP: '$comment' },
+      //       },
+      //     },
+      //   ],
+      //   as: 'comments',
+      // },
       $lookup: {
       $lookup: {
         from: 'comments',
         from: 'comments',
-        localField: '_id',
-        foreignField: 'page',
+        let: { pageId: '$_id' },
         pipeline: [
         pipeline: [
+          {
+            $match: {
+              $expr: {
+                $eq: ['$page', '$$pageId'],
+              },
+            },
+          },
           {
           {
             $addFields: {
             $addFields: {
               commentLength: { $strLenCP: '$comment' },
               commentLength: { $strLenCP: '$comment' },

+ 0 - 0
apps/app/src/server/util/socket-io-helpers.ts → apps/app/src/server/service/socket-io/helper.ts


+ 1 - 0
apps/app/src/server/service/socket-io/index.ts

@@ -0,0 +1 @@
+export * from './socket-io';

+ 13 - 23
apps/app/src/server/service/socket-io.ts → apps/app/src/server/service/socket-io/socket-io.ts

@@ -9,10 +9,10 @@ import { Server } from 'socket.io';
 import { SocketEventName } from '~/interfaces/websocket';
 import { SocketEventName } from '~/interfaces/websocket';
 import loggerFactory from '~/utils/logger';
 import loggerFactory from '~/utils/logger';
 
 
-import type Crowi from '../crowi';
-import { RoomPrefix, getRoomNameWithId } from '../util/socket-io-helpers';
+import type Crowi from '../../crowi';
+import { configManager } from '../config-manager';
 
 
-import { configManager } from './config-manager';
+import { RoomPrefix, getRoomNameWithId } from './helper';
 
 
 
 
 const logger = loggerFactory('growi:service:socket-io');
 const logger = loggerFactory('growi:service:socket-io');
@@ -23,7 +23,7 @@ type RequestWithUser = IncomingMessage & { user: IUserHasId };
 /**
 /**
  * Serve socket.io for server-to-client messaging
  * Serve socket.io for server-to-client messaging
  */
  */
-class SocketIoService {
+export class SocketIoService {
 
 
   crowi: Crowi;
   crowi: Crowi;
 
 
@@ -34,12 +34,12 @@ class SocketIoService {
   adminNamespace: Namespace;
   adminNamespace: Namespace;
 
 
 
 
-  constructor(crowi) {
+  constructor(crowi: Crowi) {
     this.crowi = crowi;
     this.crowi = crowi;
     this.guestClients = new Set();
     this.guestClients = new Set();
   }
   }
 
 
-  get isInitialized() {
+  get isInitialized(): boolean {
     return (this.io != null);
     return (this.io != null);
   }
   }
 
 
@@ -83,27 +83,19 @@ class SocketIoService {
 
 
   /**
   /**
    * use passport session
    * use passport session
-   * @see https://socket.io/docs/v4/middlewares/#Compatibility-with-Express-middleware
+   * @see https://socket.io/docs/v4/middlewares/#compatibility-with-express-middleware
    */
    */
-  setupSessionMiddleware() {
-    const wrap = middleware => (socket, next) => middleware(socket.request, {}, next);
-
-    this.io.use(wrap(expressSession(this.crowi.sessionConfig)));
-    this.io.use(wrap(passport.initialize()));
-    this.io.use(wrap(passport.session()));
-
-    // express and passport session on main socket doesn't shared to child namespace socket
-    // need to define the session for specific namespace
-    this.getAdminSocket().use(wrap(expressSession(this.crowi.sessionConfig)));
-    this.getAdminSocket().use(wrap(passport.initialize()));
-    this.getAdminSocket().use(wrap(passport.session()));
+  setupSessionMiddleware(): void {
+    this.io.engine.use(expressSession(this.crowi.sessionConfig));
+    this.io.engine.use(passport.initialize());
+    this.io.engine.use(passport.session());
   }
   }
 
 
   /**
   /**
    * use loginRequired middleware
    * use loginRequired middleware
    */
    */
   setupLoginRequiredMiddleware() {
   setupLoginRequiredMiddleware() {
-    const loginRequired = require('../middlewares/login-required')(this.crowi, true, (req, res, next) => {
+    const loginRequired = require('../../middlewares/login-required')(this.crowi, true, (req, res, next) => {
       next(new Error('Login is required to connect.'));
       next(new Error('Login is required to connect.'));
     });
     });
 
 
@@ -117,7 +109,7 @@ class SocketIoService {
    * use adminRequired middleware
    * use adminRequired middleware
    */
    */
   setupAdminRequiredMiddleware() {
   setupAdminRequiredMiddleware() {
-    const adminRequired = require('../middlewares/admin-required')(this.crowi, (req, res, next) => {
+    const adminRequired = require('../../middlewares/admin-required')(this.crowi, (req, res, next) => {
       next(new Error('Admin priviledge is required to connect.'));
       next(new Error('Admin priviledge is required to connect.'));
     });
     });
 
 
@@ -243,5 +235,3 @@ class SocketIoService {
   }
   }
 
 
 }
 }
-
-module.exports = SocketIoService;

+ 3 - 3
apps/app/src/server/service/system-events/sync-page-status.ts

@@ -2,9 +2,9 @@ import loggerFactory from '~/utils/logger';
 
 
 import { S2cMessagePageUpdated } from '../../models/vo/s2c-message';
 import { S2cMessagePageUpdated } from '../../models/vo/s2c-message';
 import S2sMessage from '../../models/vo/s2s-message';
 import S2sMessage from '../../models/vo/s2s-message';
-import { RoomPrefix, getRoomNameWithId } from '../../util/socket-io-helpers';
-import { S2sMessagingService } from '../s2s-messaging/base';
-import { S2sMessageHandlable } from '../s2s-messaging/handlable';
+import type { S2sMessagingService } from '../s2s-messaging/base';
+import type { S2sMessageHandlable } from '../s2s-messaging/handlable';
+import { RoomPrefix, getRoomNameWithId } from '../socket-io/helper';
 
 
 const logger = loggerFactory('growi:service:system-events:SyncPageStatusService');
 const logger = loggerFactory('growi:service:system-events:SyncPageStatusService');
 
 

+ 14 - 4
apps/app/src/server/service/yjs/yjs.ts

@@ -1,5 +1,6 @@
 import type { IncomingMessage } from 'http';
 import type { IncomingMessage } from 'http';
 
 
+
 import type { IPage, IUserHasId } from '@growi/core';
 import type { IPage, IUserHasId } from '@growi/core';
 import { YDocStatus } from '@growi/core/dist/consts';
 import { YDocStatus } from '@growi/core/dist/consts';
 import mongoose from 'mongoose';
 import mongoose from 'mongoose';
@@ -8,7 +9,8 @@ import type { Document } from 'y-socket.io/dist/server';
 import { YSocketIO, type Document as Ydoc } from 'y-socket.io/dist/server';
 import { YSocketIO, type Document as Ydoc } from 'y-socket.io/dist/server';
 
 
 import { SocketEventName } from '~/interfaces/websocket';
 import { SocketEventName } from '~/interfaces/websocket';
-import { RoomPrefix, getRoomNameWithId } from '~/server/util/socket-io-helpers';
+import type { SyncLatestRevisionBody } from '~/interfaces/yjs';
+import { RoomPrefix, getRoomNameWithId } from '~/server/service/socket-io/helper';
 import loggerFactory from '~/utils/logger';
 import loggerFactory from '~/utils/logger';
 
 
 import type { PageModel } from '../../models/page';
 import type { PageModel } from '../../models/page';
@@ -32,7 +34,7 @@ type RequestWithUser = IncomingMessage & { user: IUserHasId };
 
 
 export interface IYjsService {
 export interface IYjsService {
   getYDocStatus(pageId: string): Promise<YDocStatus>;
   getYDocStatus(pageId: string): Promise<YDocStatus>;
-  syncWithTheLatestRevisionForce(pageId: string): Promise<void>;
+  syncWithTheLatestRevisionForce(pageId: string, editingMarkdownLength?: number): Promise<SyncLatestRevisionBody>
   getCurrentYdoc(pageId: string): Ydoc | undefined;
   getCurrentYdoc(pageId: string): Ydoc | undefined;
 }
 }
 
 
@@ -180,14 +182,22 @@ class YjsService implements IYjsService {
     return YDocStatus.OUTDATED;
     return YDocStatus.OUTDATED;
   }
   }
 
 
-  public async syncWithTheLatestRevisionForce(pageId: string): Promise<void> {
+  public async syncWithTheLatestRevisionForce(pageId: string, editingMarkdownLength?: number): Promise<SyncLatestRevisionBody> {
     const doc = this.ysocketio.documents.get(pageId);
     const doc = this.ysocketio.documents.get(pageId);
 
 
     if (doc == null) {
     if (doc == null) {
-      return;
+      return { synced: false };
     }
     }
 
 
+    const ytextLength = doc?.getText('codemirror').length;
     syncYDoc(this.mdb, doc, true);
     syncYDoc(this.mdb, doc, true);
+
+    return {
+      synced: true,
+      isYjsDataBroken: editingMarkdownLength != null
+        ? editingMarkdownLength !== ytextLength
+        : undefined,
+    };
   }
   }
 
 
   public getCurrentYdoc(pageId: string): Ydoc | undefined {
   public getCurrentYdoc(pageId: string): Ydoc | undefined {

+ 1 - 1
apps/slackbot-proxy/package.json

@@ -1,6 +1,6 @@
 {
 {
   "name": "@growi/slackbot-proxy",
   "name": "@growi/slackbot-proxy",
-  "version": "7.0.14-slackbot-proxy.0",
+  "version": "7.0.15-slackbot-proxy.0",
   "license": "MIT",
   "license": "MIT",
   "private": "true",
   "private": "true",
   "scripts": {
   "scripts": {

+ 1 - 1
package.json

@@ -1,6 +1,6 @@
 {
 {
   "name": "growi",
   "name": "growi",
-  "version": "7.0.14-RC.0",
+  "version": "7.0.15-RC.0",
   "description": "Team collaboration software using markdown",
   "description": "Team collaboration software using markdown",
   "license": "MIT",
   "license": "MIT",
   "private": "true",
   "private": "true",

+ 4 - 1
packages/core/src/interfaces/page.ts

@@ -102,7 +102,10 @@ export type IPageInfoAll = IPageInfo | IPageInfoForEntity | IPageInfoForOperatio
 
 
 // eslint-disable-next-line @typescript-eslint/no-explicit-any
 // eslint-disable-next-line @typescript-eslint/no-explicit-any
 export const isIPageInfoForEntity = (pageInfo: any | undefined): pageInfo is IPageInfoForEntity => {
 export const isIPageInfoForEntity = (pageInfo: any | undefined): pageInfo is IPageInfoForEntity => {
-  return pageInfo != null;
+  return pageInfo != null && pageInfo instanceof Object
+    && ('commentCount' in pageInfo)
+    && ('bookmarkCount' in pageInfo)
+    && ('descendantCount' in pageInfo);
 };
 };
 
 
 // eslint-disable-next-line @typescript-eslint/no-explicit-any
 // eslint-disable-next-line @typescript-eslint/no-explicit-any

+ 40 - 21
packages/editor/src/client/services/use-codemirror-editor/utils/fold-drawio.ts

@@ -3,42 +3,61 @@ import { useEffect } from 'react';
 import { foldEffect } from '@codemirror/language';
 import { foldEffect } from '@codemirror/language';
 import type { EditorView } from '@codemirror/view';
 import type { EditorView } from '@codemirror/view';
 
 
+
 export type FoldDrawio = void;
 export type FoldDrawio = void;
 
 
 const findAllDrawioSection = (view?: EditorView) => {
 const findAllDrawioSection = (view?: EditorView) => {
   if (view == null) {
   if (view == null) {
     return;
     return;
   }
   }
-  const lineBeginPartOfDrawioRE = /^```(\s.*)drawio$/;
-  const lineNumbers: number[] = [];
-  // repeat the process in each line from the top to the bottom in the editor
-  for (let i = 1, e = view.state.doc.lines; i <= e; i++) {
-    // get each line text
-    const lineTxt = view.state.doc.line(i).text;
-    const match = lineBeginPartOfDrawioRE.exec(lineTxt);
-    if (match) {
-      lineNumbers.push(i);
+
+  try {
+    const lineBeginPartOfDrawioRE = /^```(\s.*)drawio$/;
+    const lineNumbers: number[] = [];
+    // repeat the process in each line from the top to the bottom in the editor
+    for (let i = 1, e = view.state.doc.lines; i <= e; i++) {
+      // get each line text
+      const lineTxt = view.state.doc.line(i).text;
+      const match = lineBeginPartOfDrawioRE.exec(lineTxt);
+      if (match) {
+        lineNumbers.push(i);
+      }
+    }
+    return lineNumbers;
+  }
+  catch (err) {
+    if (err instanceof Error) {
+      // eslint-disable-next-line no-console
+      console.warn(err.toString());
     }
     }
   }
   }
-  return lineNumbers;
 };
 };
 
 
 const foldDrawioSection = (lineNumbers?: number[], view?: EditorView) => {
 const foldDrawioSection = (lineNumbers?: number[], view?: EditorView) => {
   if (view == null || lineNumbers == null) {
   if (view == null || lineNumbers == null) {
     return;
     return;
   }
   }
-  lineNumbers.forEach((lineNumber) => {
-    // get the end of the lines containing '''drawio
-    const from = view.state.doc.line(lineNumber).to;
-    // get the end of the lines containing '''
-    const to = view.state.doc.line(lineNumber + 2).to;
-    view?.dispatch({
-      effects: foldEffect.of({
-        from,
-        to,
-      }),
+
+  try {
+    lineNumbers.forEach((lineNumber) => {
+      // get the end of the lines containing '''drawio
+      const from = view.state.doc.line(lineNumber).to;
+      // get the end of the lines containing '''
+      const to = view.state.doc.line(lineNumber + 2).to;
+      view?.dispatch({
+        effects: foldEffect.of({
+          from,
+          to,
+        }),
+      });
     });
     });
-  });
+  }
+  catch (err) {
+    if (err instanceof Error) {
+    // eslint-disable-next-line no-console
+      console.warn(err.toString());
+    }
+  }
 };
 };
 
 
 export const useFoldDrawio = (view?: EditorView): FoldDrawio => {
 export const useFoldDrawio = (view?: EditorView): FoldDrawio => {