From 86610e756126a388f6b3394130f9d3553a98bdf7 Mon Sep 17 00:00:00 2001 From: Laurent Cozic Date: Fri, 22 Jan 2021 17:41:11 +0000 Subject: [PATCH] Converted models and services to TypeScript --- .eslintignore | 69 +++++++ .gitignore | 69 +++++++ packages/app-cli/app/app-gui.js | 12 +- packages/app-cli/app/app.js | 10 +- packages/app-cli/app/autocompletion.js | 6 +- packages/app-cli/app/cli-integration-tests.js | 4 +- packages/app-cli/app/command-apidoc.js | 2 +- packages/app-cli/app/command-cat.js | 4 +- packages/app-cli/app/command-cp.js | 2 +- packages/app-cli/app/command-done.js | 2 +- packages/app-cli/app/command-dump.js | 6 +- packages/app-cli/app/command-e2ee.js | 6 +- packages/app-cli/app/command-edit.js | 2 +- .../app-cli/app/command-export-sync-status.js | 2 +- packages/app-cli/app/command-geoloc.js | 2 +- packages/app-cli/app/command-ls.js | 4 +- packages/app-cli/app/command-mkbook.js | 2 +- packages/app-cli/app/command-mknote.js | 2 +- packages/app-cli/app/command-mktodo.js | 2 +- packages/app-cli/app/command-mv.js | 4 +- packages/app-cli/app/command-ren.js | 4 +- packages/app-cli/app/command-rmbook.js | 2 +- packages/app-cli/app/command-rmnote.js | 2 +- packages/app-cli/app/command-search.js | 2 +- packages/app-cli/app/command-set.js | 2 +- packages/app-cli/app/command-status.js | 2 +- packages/app-cli/app/command-sync.js | 2 +- packages/app-cli/app/command-tag.js | 2 +- packages/app-cli/app/command-todo.js | 2 +- packages/app-cli/app/fuzzing.js | 2 +- packages/app-cli/app/gui/FolderListWidget.js | 4 +- packages/app-cli/app/gui/NoteListWidget.js | 2 +- .../app-cli/app/gui/NoteMetadataWidget.js | 2 +- packages/app-cli/app/gui/NoteWidget.js | 2 +- packages/app-cli/app/main.js | 18 +- packages/app-cli/tests/EnexToMd.ts | 6 +- packages/app-cli/tests/HtmlToHtml.js | 4 +- packages/app-cli/tests/InMemoryCache.ts | 2 +- packages/app-cli/tests/MdToHtml.ts | 2 +- packages/app-cli/tests/MdToMd.js | 2 +- packages/app-cli/tests/Synchronizer.basics.ts | 6 +- .../app-cli/tests/Synchronizer.conflicts.ts | 6 +- packages/app-cli/tests/Synchronizer.e2ee.ts | 12 +- .../app-cli/tests/Synchronizer.resources.ts | 10 +- .../app-cli/tests/Synchronizer.revisions.ts | 4 +- packages/app-cli/tests/Synchronizer.tags.ts | 8 +- packages/app-cli/tests/database.js | 4 +- packages/app-cli/tests/feature_NoteHistory.js | 4 +- packages/app-cli/tests/feature_NoteList.js | 6 +- .../app-cli/tests/feature_ShowAllNotes.js | 6 +- packages/app-cli/tests/feature_TagList.js | 6 +- packages/app-cli/tests/models_BaseItem.js | 8 +- packages/app-cli/tests/models_Folder.ts | 12 +- packages/app-cli/tests/models_ItemChange.js | 8 +- packages/app-cli/tests/models_Note.ts | 20 +- .../tests/models_Note_CustomSortOrder.js | 4 +- packages/app-cli/tests/models_Resource.js | 6 +- packages/app-cli/tests/models_Revision.js | 10 +- packages/app-cli/tests/models_Tag.js | 8 +- packages/app-cli/tests/reducer.js | 6 +- .../services/plugins/api/JoplinSettings.ts | 2 +- .../services/plugins/api/JoplinWorkspace.ts | 6 +- .../tests/services_EncryptionService.js | 12 +- .../app-cli/tests/services_InteropService.ts | 8 +- .../services_InteropService_Exporter_Md.js | 6 +- .../app-cli/tests/services_PluginService.ts | 4 +- .../app-cli/tests/services_ResourceService.ts | 8 +- packages/app-cli/tests/services_Revision.js | 14 +- .../app-cli/tests/services_SearchEngine.js | 6 +- .../app-cli/tests/services_SearchFilter.js | 12 +- packages/app-cli/tests/services_rest_Api.ts | 30 +-- .../app-cli/tests/support/syncTargetUtils.js | 8 +- .../tests/synchronizer_MigrationHandler.ts | 4 +- .../app-cli/tests/test-utils-synchronizer.ts | 6 +- packages/app-cli/tests/test-utils.ts | 30 +-- packages/app-desktop/InteropServiceHelper.ts | 6 +- packages/app-desktop/app.ts | 18 +- .../commands/startExternalEditing.ts | 2 +- .../gui/EncryptionConfigScreen.jsx | 2 +- packages/app-desktop/gui/ImportScreen.jsx | 2 +- .../gui/KeymapConfig/KeymapConfigScreen.tsx | 2 +- .../app-desktop/gui/MainScreen/MainScreen.tsx | 2 +- .../gui/MainScreen/commands/editAlarm.ts | 4 +- .../gui/MainScreen/commands/exportPdf.ts | 2 +- .../gui/MainScreen/commands/moveToFolder.ts | 4 +- .../gui/MainScreen/commands/newFolder.ts | 2 +- .../gui/MainScreen/commands/newNote.ts | 4 +- .../gui/MainScreen/commands/openNote.ts | 4 +- .../gui/MainScreen/commands/renameFolder.ts | 2 +- .../gui/MainScreen/commands/renameTag.ts | 2 +- .../gui/MainScreen/commands/setTags.ts | 2 +- .../commands/showNoteContentProperties.ts | 2 +- .../gui/NoteContentPropertiesDialog.tsx | 2 +- .../NoteBody/CodeMirror/CodeMirror.tsx | 7 +- .../NoteBody/CodeMirror/utils/useListIdent.ts | 22 +-- .../NoteEditor/NoteBody/TinyMCE/TinyMCE.tsx | 2 +- .../NoteBody/TinyMCE/utils/useContextMenu.ts | 2 +- .../app-desktop/gui/NoteEditor/NoteEditor.tsx | 4 +- .../gui/NoteEditor/utils/contextMenu.ts | 2 +- .../app-desktop/gui/NoteEditor/utils/index.ts | 2 +- .../gui/NoteEditor/utils/resourceHandling.ts | 10 +- .../gui/NoteEditor/utils/useDropHandler.ts | 2 +- .../gui/NoteEditor/utils/useFolder.ts | 2 +- .../gui/NoteEditor/utils/useFormNote.ts | 6 +- .../gui/NoteEditor/utils/useMarkupToHtml.ts | 2 +- .../gui/NoteEditor/utils/useMessageHandler.ts | 10 +- .../utils/useWindowCommandHandler.ts | 2 +- .../app-desktop/gui/NoteList/NoteList.tsx | 8 +- packages/app-desktop/gui/NoteListItem.tsx | 2 +- .../app-desktop/gui/NotePropertiesDialog.jsx | 2 +- .../app-desktop/gui/NoteRevisionViewer.jsx | 4 +- .../app-desktop/gui/OneDriveLoginScreen.tsx | 2 +- packages/app-desktop/gui/ResourceScreen.tsx | 2 +- packages/app-desktop/gui/Root.tsx | 4 +- .../gui/Root_UpgradeSyncTarget.tsx | 2 +- .../app-desktop/gui/SearchBar/SearchBar.tsx | 2 +- packages/app-desktop/gui/ShareNoteDialog.tsx | 6 +- packages/app-desktop/gui/Sidebar/Sidebar.tsx | 8 +- .../gui/StatusScreen/StatusScreen.tsx | 4 +- .../app-desktop/gui/utils/NoteListUtils.ts | 4 +- packages/app-desktop/main-html.js | 18 +- packages/app-desktop/plugins/GotoAnything.tsx | 12 +- .../services/plugins/hooks/useThemeCss.ts | 2 +- packages/app-mobile/PluginAssetsLoader.ts | 6 +- .../components/BackButtonDialogBox.ts | 4 +- packages/app-mobile/components/CameraView.tsx | 4 +- .../NoteBodyViewer/NoteBodyViewer.tsx | 6 +- .../hooks/useOnResourceLongPress.ts | 2 +- .../NoteBodyViewer/hooks/useSource.ts | 2 +- .../components/SelectDateTimeDialog.tsx | 2 +- .../app-mobile/components/action-button.js | 2 +- packages/app-mobile/components/note-item.js | 2 +- .../app-mobile/components/screen-header.js | 6 +- .../app-mobile/components/screens/Note.tsx | 24 +-- .../components/screens/NoteTagsDialog.js | 2 +- .../app-mobile/components/screens/config.js | 6 +- .../components/screens/encryption-config.js | 2 +- .../app-mobile/components/screens/folder.js | 2 +- .../app-mobile/components/screens/notes.js | 6 +- .../app-mobile/components/screens/search.js | 4 +- .../app-mobile/components/screens/status.js | 2 +- .../app-mobile/components/screens/tags.js | 2 +- .../components/side-menu-content.js | 4 +- packages/app-mobile/root.tsx | 44 ++--- packages/app-mobile/setUpQuickActions.ts | 4 +- packages/app-mobile/utils/shareHandler.ts | 4 +- packages/app-mobile/utils/shim-init-react.js | 2 +- packages/lib/BaseApplication.ts | 43 ++-- packages/lib/BaseModel.ts | 12 +- packages/lib/BaseSyncTarget.js | 2 +- packages/lib/JoplinServerApi.ts | 2 +- packages/lib/Logger.ts | 2 +- packages/lib/ModelCache.js | 37 ---- packages/lib/PoorManIntervals.ts | 2 +- packages/lib/Synchronizer.ts | 18 +- packages/lib/WelcomeUtils.js | 6 +- .../shared/encryption-config-shared.js | 6 +- .../components/shared/note-screen-shared.js | 10 +- .../shared/reduxSharedMiddleware.js | 8 +- .../lib/components/shared/side-menu-shared.js | 2 +- packages/lib/file-api.js | 2 +- packages/lib/folders-screen-utils.js | 2 +- packages/lib/import-enex.js | 6 +- packages/lib/joplin-database.js | 2 +- packages/lib/markupLanguageUtils.ts | 2 +- packages/lib/migrations/20.js | 2 +- packages/lib/migrations/33.js | 2 +- packages/lib/models/Alarm.ts | 4 +- .../lib/models/{BaseItem.js => BaseItem.ts} | 174 ++++++++-------- packages/lib/models/{Folder.js => Folder.ts} | 101 +++++----- .../models/{ItemChange.js => ItemChange.ts} | 39 ++-- .../lib/models/{MasterKey.js => MasterKey.ts} | 13 +- .../lib/models/{Migration.js => Migration.ts} | 10 +- packages/lib/models/{Note.js => Note.ts} | 145 +++++++------- .../lib/models/{NoteTag.js => NoteTag.ts} | 12 +- .../lib/models/{Resource.js => Resource.ts} | 104 +++++----- ...rceLocalState.js => ResourceLocalState.ts} | 13 +- .../lib/models/{Revision.js => Revision.ts} | 47 +++-- packages/lib/models/Search.js | 20 -- packages/lib/models/Search.ts | 20 ++ packages/lib/models/Setting.ts | 158 +++++++-------- packages/lib/models/SmartFilter.js | 13 -- packages/lib/models/SmartFilter.ts | 13 ++ packages/lib/models/{Tag.js => Tag.ts} | 52 ++--- packages/lib/ntpDate.ts | 2 +- packages/lib/reducer.ts | 6 +- packages/lib/services/AlarmService.ts | 2 +- ...ecryptionWorker.js => DecryptionWorker.ts} | 73 +++---- ...ryptionService.js => EncryptionService.ts} | 185 ++++++++++-------- .../services/EncryptionServiceDriverNode.js | 0 packages/lib/services/ExternalEditWatcher.ts | 2 +- ...{ItemChangeUtils.js => ItemChangeUtils.ts} | 8 +- packages/lib/services/KeymapService.ts | 3 +- ...igrationService.js => MigrationService.ts} | 15 +- packages/lib/services/ModelCache.js | 36 ---- .../services/{NavService.js => NavService.ts} | 18 +- .../services/{report.js => ReportService.ts} | 50 +++-- .../lib/services/ResourceEditWatcher/index.ts | 6 +- ...{ResourceFetcher.js => ResourceFetcher.ts} | 78 ++++---- packages/lib/services/ResourceService.ts | 14 +- ...{RevisionService.js => RevisionService.ts} | 89 +++++---- packages/lib/services/SettingUtils.ts | 4 +- .../commands/stateToWhenClauseContext.ts | 6 +- .../lib/services/debug/populateDatabase.ts | 6 +- .../lib/services/interop/InteropService.ts | 14 +- .../interop/InteropService_Exporter_Base.ts | 2 +- .../interop/InteropService_Exporter_Html.ts | 27 ++- .../interop/InteropService_Exporter_Md.ts | 23 ++- .../interop/InteropService_Exporter_Raw.ts | 10 +- .../interop/InteropService_Importer_Base.ts | 4 +- .../interop/InteropService_Importer_Custom.ts | 2 +- .../InteropService_Importer_EnexToHtml.ts | 7 +- .../InteropService_Importer_EnexToMd.ts | 4 +- .../interop/InteropService_Importer_Jex.ts | 4 +- .../interop/InteropService_Importer_Md.ts | 12 +- .../interop/InteropService_Importer_Raw.ts | 20 +- packages/lib/services/interop/types.ts | 2 +- .../lib/services/keychain/KeychainService.ts | 4 +- .../services/plugins/api/JoplinWorkspace.ts | 4 +- packages/lib/services/rest/routes/folders.ts | 2 +- packages/lib/services/rest/routes/notes.ts | 10 +- .../lib/services/rest/routes/resources.ts | 4 +- packages/lib/services/rest/routes/search.ts | 4 +- packages/lib/services/rest/routes/tags.ts | 4 +- .../lib/services/rest/utils/defaultAction.ts | 2 +- .../services/rest/utils/paginatedResults.ts | 2 +- .../lib/services/rest/utils/requestFields.ts | 2 +- .../{SearchEngine.js => SearchEngine.ts} | 144 +++++++------- ...rchEngineUtils.js => SearchEngineUtils.ts} | 12 +- .../lib/services/searchengine/queryBuilder.ts | 2 +- .../lib/services/synchronizer/LockHandler.ts | 2 +- .../services/synchronizer/MigrationHandler.ts | 4 +- .../synchronizer/gui/useSyncTargetUpgrade.ts | 2 +- packages/lib/shim-init-node.js | 4 +- packages/lib/shim.ts | 4 +- packages/lib/versionInfo.ts | 2 +- packages/renderer/HtmlToHtml.ts | 4 +- 237 files changed, 1568 insertions(+), 1443 deletions(-) delete mode 100644 packages/lib/ModelCache.js rename packages/lib/models/{BaseItem.js => BaseItem.ts} (85%) rename packages/lib/models/{Folder.js => Folder.ts} (82%) rename packages/lib/models/{ItemChange.js => ItemChange.ts} (70%) rename packages/lib/models/{MasterKey.js => MasterKey.ts} (61%) rename packages/lib/models/{Migration.js => Migration.ts} (74%) rename packages/lib/models/{Note.js => Note.ts} (87%) rename packages/lib/models/{NoteTag.js => NoteTag.ts} (67%) rename packages/lib/models/{Resource.js => Resource.ts} (83%) rename packages/lib/models/{ResourceLocalState.js => ResourceLocalState.ts} (74%) rename packages/lib/models/{Revision.js => Revision.ts} (85%) delete mode 100644 packages/lib/models/Search.js create mode 100644 packages/lib/models/Search.ts delete mode 100644 packages/lib/models/SmartFilter.js create mode 100644 packages/lib/models/SmartFilter.ts rename packages/lib/models/{Tag.js => Tag.ts} (79%) rename packages/lib/services/{DecryptionWorker.js => DecryptionWorker.ts} (86%) rename packages/lib/services/{EncryptionService.js => EncryptionService.ts} (79%) delete mode 100644 packages/lib/services/EncryptionServiceDriverNode.js rename packages/lib/services/{ItemChangeUtils.js => ItemChangeUtils.ts} (68%) rename packages/lib/services/{MigrationService.js => MigrationService.ts} (71%) delete mode 100644 packages/lib/services/ModelCache.js rename packages/lib/services/{NavService.js => NavService.ts} (62%) rename packages/lib/services/{report.js => ReportService.ts} (89%) rename packages/lib/services/{ResourceFetcher.js => ResourceFetcher.ts} (84%) rename packages/lib/services/{RevisionService.js => RevisionService.ts} (80%) rename packages/lib/services/searchengine/{SearchEngine.js => SearchEngine.ts} (86%) rename packages/lib/services/searchengine/{SearchEngineUtils.js => SearchEngineUtils.ts} (87%) diff --git a/.eslintignore b/.eslintignore index d4d2f34e2..b319b59ee 100644 --- a/.eslintignore +++ b/.eslintignore @@ -981,12 +981,51 @@ packages/lib/markupLanguageUtils.js.map packages/lib/models/Alarm.d.ts packages/lib/models/Alarm.js packages/lib/models/Alarm.js.map +packages/lib/models/BaseItem.d.ts +packages/lib/models/BaseItem.js +packages/lib/models/BaseItem.js.map +packages/lib/models/Folder.d.ts +packages/lib/models/Folder.js +packages/lib/models/Folder.js.map +packages/lib/models/ItemChange.d.ts +packages/lib/models/ItemChange.js +packages/lib/models/ItemChange.js.map +packages/lib/models/MasterKey.d.ts +packages/lib/models/MasterKey.js +packages/lib/models/MasterKey.js.map +packages/lib/models/Migration.d.ts +packages/lib/models/Migration.js +packages/lib/models/Migration.js.map +packages/lib/models/Note.d.ts +packages/lib/models/Note.js +packages/lib/models/Note.js.map packages/lib/models/NoteResource.d.ts packages/lib/models/NoteResource.js packages/lib/models/NoteResource.js.map +packages/lib/models/NoteTag.d.ts +packages/lib/models/NoteTag.js +packages/lib/models/NoteTag.js.map +packages/lib/models/Resource.d.ts +packages/lib/models/Resource.js +packages/lib/models/Resource.js.map +packages/lib/models/ResourceLocalState.d.ts +packages/lib/models/ResourceLocalState.js +packages/lib/models/ResourceLocalState.js.map +packages/lib/models/Revision.d.ts +packages/lib/models/Revision.js +packages/lib/models/Revision.js.map +packages/lib/models/Search.d.ts +packages/lib/models/Search.js +packages/lib/models/Search.js.map packages/lib/models/Setting.d.ts packages/lib/models/Setting.js packages/lib/models/Setting.js.map +packages/lib/models/SmartFilter.d.ts +packages/lib/models/SmartFilter.js +packages/lib/models/SmartFilter.js.map +packages/lib/models/Tag.d.ts +packages/lib/models/Tag.js +packages/lib/models/Tag.js.map packages/lib/models/utils/paginatedFeed.d.ts packages/lib/models/utils/paginatedFeed.js packages/lib/models/utils/paginatedFeed.js.map @@ -1020,9 +1059,18 @@ packages/lib/services/BaseService.js.map packages/lib/services/CommandService.d.ts packages/lib/services/CommandService.js packages/lib/services/CommandService.js.map +packages/lib/services/DecryptionWorker.d.ts +packages/lib/services/DecryptionWorker.js +packages/lib/services/DecryptionWorker.js.map +packages/lib/services/EncryptionService.d.ts +packages/lib/services/EncryptionService.js +packages/lib/services/EncryptionService.js.map packages/lib/services/ExternalEditWatcher.d.ts packages/lib/services/ExternalEditWatcher.js packages/lib/services/ExternalEditWatcher.js.map +packages/lib/services/ItemChangeUtils.d.ts +packages/lib/services/ItemChangeUtils.js +packages/lib/services/ItemChangeUtils.js.map packages/lib/services/KeymapService.d.ts packages/lib/services/KeymapService.js packages/lib/services/KeymapService.js.map @@ -1035,18 +1083,33 @@ packages/lib/services/KeymapService_keysRegExp.js.map packages/lib/services/KvStore.d.ts packages/lib/services/KvStore.js packages/lib/services/KvStore.js.map +packages/lib/services/MigrationService.d.ts +packages/lib/services/MigrationService.js +packages/lib/services/MigrationService.js.map +packages/lib/services/NavService.d.ts +packages/lib/services/NavService.js +packages/lib/services/NavService.js.map packages/lib/services/PostMessageService.d.ts packages/lib/services/PostMessageService.js packages/lib/services/PostMessageService.js.map +packages/lib/services/ReportService.d.ts +packages/lib/services/ReportService.js +packages/lib/services/ReportService.js.map packages/lib/services/ResourceEditWatcher/index.d.ts packages/lib/services/ResourceEditWatcher/index.js packages/lib/services/ResourceEditWatcher/index.js.map packages/lib/services/ResourceEditWatcher/reducer.d.ts packages/lib/services/ResourceEditWatcher/reducer.js packages/lib/services/ResourceEditWatcher/reducer.js.map +packages/lib/services/ResourceFetcher.d.ts +packages/lib/services/ResourceFetcher.js +packages/lib/services/ResourceFetcher.js.map packages/lib/services/ResourceService.d.ts packages/lib/services/ResourceService.js packages/lib/services/ResourceService.js.map +packages/lib/services/RevisionService.d.ts +packages/lib/services/RevisionService.js +packages/lib/services/RevisionService.js.map packages/lib/services/SettingUtils.d.ts packages/lib/services/SettingUtils.js packages/lib/services/SettingUtils.js.map @@ -1308,6 +1371,12 @@ packages/lib/services/rest/utils/requestFields.js.map packages/lib/services/rest/utils/requestPaginationOptions.d.ts packages/lib/services/rest/utils/requestPaginationOptions.js packages/lib/services/rest/utils/requestPaginationOptions.js.map +packages/lib/services/searchengine/SearchEngine.d.ts +packages/lib/services/searchengine/SearchEngine.js +packages/lib/services/searchengine/SearchEngine.js.map +packages/lib/services/searchengine/SearchEngineUtils.d.ts +packages/lib/services/searchengine/SearchEngineUtils.js +packages/lib/services/searchengine/SearchEngineUtils.js.map packages/lib/services/searchengine/filterParser.d.ts packages/lib/services/searchengine/filterParser.js packages/lib/services/searchengine/filterParser.js.map diff --git a/.gitignore b/.gitignore index dee32f073..e3096b189 100644 --- a/.gitignore +++ b/.gitignore @@ -969,12 +969,51 @@ packages/lib/markupLanguageUtils.js.map packages/lib/models/Alarm.d.ts packages/lib/models/Alarm.js packages/lib/models/Alarm.js.map +packages/lib/models/BaseItem.d.ts +packages/lib/models/BaseItem.js +packages/lib/models/BaseItem.js.map +packages/lib/models/Folder.d.ts +packages/lib/models/Folder.js +packages/lib/models/Folder.js.map +packages/lib/models/ItemChange.d.ts +packages/lib/models/ItemChange.js +packages/lib/models/ItemChange.js.map +packages/lib/models/MasterKey.d.ts +packages/lib/models/MasterKey.js +packages/lib/models/MasterKey.js.map +packages/lib/models/Migration.d.ts +packages/lib/models/Migration.js +packages/lib/models/Migration.js.map +packages/lib/models/Note.d.ts +packages/lib/models/Note.js +packages/lib/models/Note.js.map packages/lib/models/NoteResource.d.ts packages/lib/models/NoteResource.js packages/lib/models/NoteResource.js.map +packages/lib/models/NoteTag.d.ts +packages/lib/models/NoteTag.js +packages/lib/models/NoteTag.js.map +packages/lib/models/Resource.d.ts +packages/lib/models/Resource.js +packages/lib/models/Resource.js.map +packages/lib/models/ResourceLocalState.d.ts +packages/lib/models/ResourceLocalState.js +packages/lib/models/ResourceLocalState.js.map +packages/lib/models/Revision.d.ts +packages/lib/models/Revision.js +packages/lib/models/Revision.js.map +packages/lib/models/Search.d.ts +packages/lib/models/Search.js +packages/lib/models/Search.js.map packages/lib/models/Setting.d.ts packages/lib/models/Setting.js packages/lib/models/Setting.js.map +packages/lib/models/SmartFilter.d.ts +packages/lib/models/SmartFilter.js +packages/lib/models/SmartFilter.js.map +packages/lib/models/Tag.d.ts +packages/lib/models/Tag.js +packages/lib/models/Tag.js.map packages/lib/models/utils/paginatedFeed.d.ts packages/lib/models/utils/paginatedFeed.js packages/lib/models/utils/paginatedFeed.js.map @@ -1008,9 +1047,18 @@ packages/lib/services/BaseService.js.map packages/lib/services/CommandService.d.ts packages/lib/services/CommandService.js packages/lib/services/CommandService.js.map +packages/lib/services/DecryptionWorker.d.ts +packages/lib/services/DecryptionWorker.js +packages/lib/services/DecryptionWorker.js.map +packages/lib/services/EncryptionService.d.ts +packages/lib/services/EncryptionService.js +packages/lib/services/EncryptionService.js.map packages/lib/services/ExternalEditWatcher.d.ts packages/lib/services/ExternalEditWatcher.js packages/lib/services/ExternalEditWatcher.js.map +packages/lib/services/ItemChangeUtils.d.ts +packages/lib/services/ItemChangeUtils.js +packages/lib/services/ItemChangeUtils.js.map packages/lib/services/KeymapService.d.ts packages/lib/services/KeymapService.js packages/lib/services/KeymapService.js.map @@ -1023,18 +1071,33 @@ packages/lib/services/KeymapService_keysRegExp.js.map packages/lib/services/KvStore.d.ts packages/lib/services/KvStore.js packages/lib/services/KvStore.js.map +packages/lib/services/MigrationService.d.ts +packages/lib/services/MigrationService.js +packages/lib/services/MigrationService.js.map +packages/lib/services/NavService.d.ts +packages/lib/services/NavService.js +packages/lib/services/NavService.js.map packages/lib/services/PostMessageService.d.ts packages/lib/services/PostMessageService.js packages/lib/services/PostMessageService.js.map +packages/lib/services/ReportService.d.ts +packages/lib/services/ReportService.js +packages/lib/services/ReportService.js.map packages/lib/services/ResourceEditWatcher/index.d.ts packages/lib/services/ResourceEditWatcher/index.js packages/lib/services/ResourceEditWatcher/index.js.map packages/lib/services/ResourceEditWatcher/reducer.d.ts packages/lib/services/ResourceEditWatcher/reducer.js packages/lib/services/ResourceEditWatcher/reducer.js.map +packages/lib/services/ResourceFetcher.d.ts +packages/lib/services/ResourceFetcher.js +packages/lib/services/ResourceFetcher.js.map packages/lib/services/ResourceService.d.ts packages/lib/services/ResourceService.js packages/lib/services/ResourceService.js.map +packages/lib/services/RevisionService.d.ts +packages/lib/services/RevisionService.js +packages/lib/services/RevisionService.js.map packages/lib/services/SettingUtils.d.ts packages/lib/services/SettingUtils.js packages/lib/services/SettingUtils.js.map @@ -1296,6 +1359,12 @@ packages/lib/services/rest/utils/requestFields.js.map packages/lib/services/rest/utils/requestPaginationOptions.d.ts packages/lib/services/rest/utils/requestPaginationOptions.js packages/lib/services/rest/utils/requestPaginationOptions.js.map +packages/lib/services/searchengine/SearchEngine.d.ts +packages/lib/services/searchengine/SearchEngine.js +packages/lib/services/searchengine/SearchEngine.js.map +packages/lib/services/searchengine/SearchEngineUtils.d.ts +packages/lib/services/searchengine/SearchEngineUtils.js +packages/lib/services/searchengine/SearchEngineUtils.js.map packages/lib/services/searchengine/filterParser.d.ts packages/lib/services/searchengine/filterParser.js packages/lib/services/searchengine/filterParser.js.map diff --git a/packages/app-cli/app/app-gui.js b/packages/app-cli/app/app-gui.js index 91af6d618..a85ab91b2 100644 --- a/packages/app-cli/app/app-gui.js +++ b/packages/app-cli/app/app-gui.js @@ -1,10 +1,10 @@ const Logger = require('@joplin/lib/Logger').default; -const Folder = require('@joplin/lib/models/Folder.js'); -const BaseItem = require('@joplin/lib/models/BaseItem.js'); -const Tag = require('@joplin/lib/models/Tag.js'); +const Folder = require('@joplin/lib/models/Folder').default; +const BaseItem = require('@joplin/lib/models/BaseItem').default; +const Tag = require('@joplin/lib/models/Tag').default; const BaseModel = require('@joplin/lib/BaseModel').default; -const Note = require('@joplin/lib/models/Note.js'); -const Resource = require('@joplin/lib/models/Resource.js'); +const Note = require('@joplin/lib/models/Note').default; +const Resource = require('@joplin/lib/models/Resource').default; const Setting = require('@joplin/lib/models/Setting').default; const reducer = require('@joplin/lib/reducer').default; const { defaultState } = require('@joplin/lib/reducer'); @@ -19,7 +19,7 @@ const chalk = require('chalk'); const tk = require('terminal-kit'); const TermWrapper = require('tkwidgets/framework/TermWrapper.js'); const Renderer = require('tkwidgets/framework/Renderer.js'); -const DecryptionWorker = require('@joplin/lib/services/DecryptionWorker'); +const DecryptionWorker = require('@joplin/lib/services/DecryptionWorker').default; const BaseWidget = require('tkwidgets/BaseWidget.js'); const TextWidget = require('tkwidgets/TextWidget.js'); diff --git a/packages/app-cli/app/app.js b/packages/app-cli/app/app.js index 87098e3d2..9d3749d25 100644 --- a/packages/app-cli/app/app.js +++ b/packages/app-cli/app/app.js @@ -2,10 +2,10 @@ const BaseApplication = require('@joplin/lib/BaseApplication').default; const { FoldersScreenUtils } = require('@joplin/lib/folders-screen-utils.js'); const ResourceService = require('@joplin/lib/services/ResourceService').default; const BaseModel = require('@joplin/lib/BaseModel').default; -const Folder = require('@joplin/lib/models/Folder.js'); -const BaseItem = require('@joplin/lib/models/BaseItem.js'); -const Note = require('@joplin/lib/models/Note.js'); -const Tag = require('@joplin/lib/models/Tag.js'); +const Folder = require('@joplin/lib/models/Folder').default; +const BaseItem = require('@joplin/lib/models/BaseItem').default; +const Note = require('@joplin/lib/models/Note').default; +const Tag = require('@joplin/lib/models/Tag').default; const Setting = require('@joplin/lib/models/Setting').default; const { reg } = require('@joplin/lib/registry.js'); const { fileExtension } = require('@joplin/lib/path-utils'); @@ -13,7 +13,7 @@ const { _ } = require('@joplin/lib/locale'); const fs = require('fs-extra'); const { cliUtils } = require('./cli-utils.js'); const Cache = require('@joplin/lib/Cache'); -const RevisionService = require('@joplin/lib/services/RevisionService'); +const RevisionService = require('@joplin/lib/services/RevisionService').default; const shim = require('@joplin/lib/shim').default; class Application extends BaseApplication { diff --git a/packages/app-cli/app/autocompletion.js b/packages/app-cli/app/autocompletion.js index eb255480f..d197378a4 100644 --- a/packages/app-cli/app/autocompletion.js +++ b/packages/app-cli/app/autocompletion.js @@ -1,7 +1,7 @@ const { app } = require('./app.js'); -const Note = require('@joplin/lib/models/Note.js'); -const Folder = require('@joplin/lib/models/Folder.js'); -const Tag = require('@joplin/lib/models/Tag.js'); +const Note = require('@joplin/lib/models/Note').default; +const Folder = require('@joplin/lib/models/Folder').default; +const Tag = require('@joplin/lib/models/Tag').default; const { cliUtils } = require('./cli-utils.js'); const yargParser = require('yargs-parser'); const fs = require('fs-extra'); diff --git a/packages/app-cli/app/cli-integration-tests.js b/packages/app-cli/app/cli-integration-tests.js index ff4b99053..e88e033c9 100644 --- a/packages/app-cli/app/cli-integration-tests.js +++ b/packages/app-cli/app/cli-integration-tests.js @@ -6,8 +6,8 @@ const { dirname } = require('@joplin/lib/path-utils'); const { DatabaseDriverNode } = require('@joplin/lib/database-driver-node.js'); const { JoplinDatabase } = require('@joplin/lib/joplin-database.js'); const BaseModel = require('@joplin/lib/BaseModel').default; -const Folder = require('@joplin/lib/models/Folder.js'); -const Note = require('@joplin/lib/models/Note.js'); +const Folder = require('@joplin/lib/models/Folder').default; +const Note = require('@joplin/lib/models/Note').default; const Setting = require('@joplin/lib/models/Setting').default; const { sprintf } = require('sprintf-js'); const exec = require('child_process').exec; diff --git a/packages/app-cli/app/command-apidoc.js b/packages/app-cli/app/command-apidoc.js index 86062a48a..10ececd7d 100644 --- a/packages/app-cli/app/command-apidoc.js +++ b/packages/app-cli/app/command-apidoc.js @@ -1,5 +1,5 @@ const { BaseCommand } = require('./base-command.js'); -const BaseItem = require('@joplin/lib/models/BaseItem'); +const BaseItem = require('@joplin/lib/models/BaseItem').default; const BaseModel = require('@joplin/lib/BaseModel').default; const { toTitleCase } = require('@joplin/lib/string-utils.js'); const { reg } = require('@joplin/lib/registry.js'); diff --git a/packages/app-cli/app/command-cat.js b/packages/app-cli/app/command-cat.js index 1ce8ba806..fb86fec07 100644 --- a/packages/app-cli/app/command-cat.js +++ b/packages/app-cli/app/command-cat.js @@ -2,8 +2,8 @@ const { BaseCommand } = require('./base-command.js'); const { app } = require('./app.js'); const { _ } = require('@joplin/lib/locale'); const BaseModel = require('@joplin/lib/BaseModel').default; -const BaseItem = require('@joplin/lib/models/BaseItem.js'); -const Note = require('@joplin/lib/models/Note.js'); +const BaseItem = require('@joplin/lib/models/BaseItem').default; +const Note = require('@joplin/lib/models/Note').default; class Command extends BaseCommand { usage() { diff --git a/packages/app-cli/app/command-cp.js b/packages/app-cli/app/command-cp.js index 72e253cc5..d687bca91 100644 --- a/packages/app-cli/app/command-cp.js +++ b/packages/app-cli/app/command-cp.js @@ -2,7 +2,7 @@ const { BaseCommand } = require('./base-command.js'); const { app } = require('./app.js'); const { _ } = require('@joplin/lib/locale'); const BaseModel = require('@joplin/lib/BaseModel').default; -const Note = require('@joplin/lib/models/Note.js'); +const Note = require('@joplin/lib/models/Note').default; class Command extends BaseCommand { usage() { diff --git a/packages/app-cli/app/command-done.js b/packages/app-cli/app/command-done.js index 16b8ad180..04cbdf4e9 100644 --- a/packages/app-cli/app/command-done.js +++ b/packages/app-cli/app/command-done.js @@ -2,7 +2,7 @@ const { BaseCommand } = require('./base-command.js'); const { app } = require('./app.js'); const { _ } = require('@joplin/lib/locale'); const BaseModel = require('@joplin/lib/BaseModel').default; -const Note = require('@joplin/lib/models/Note.js'); +const Note = require('@joplin/lib/models/Note').default; const time = require('@joplin/lib/time').default; class Command extends BaseCommand { diff --git a/packages/app-cli/app/command-dump.js b/packages/app-cli/app/command-dump.js index 0f1a72264..f166226e2 100644 --- a/packages/app-cli/app/command-dump.js +++ b/packages/app-cli/app/command-dump.js @@ -1,7 +1,7 @@ const { BaseCommand } = require('./base-command.js'); -const Folder = require('@joplin/lib/models/Folder.js'); -const Note = require('@joplin/lib/models/Note.js'); -const Tag = require('@joplin/lib/models/Tag.js'); +const Folder = require('@joplin/lib/models/Folder').default; +const Note = require('@joplin/lib/models/Note').default; +const Tag = require('@joplin/lib/models/Tag').default; class Command extends BaseCommand { usage() { diff --git a/packages/app-cli/app/command-e2ee.js b/packages/app-cli/app/command-e2ee.js index d566690bb..46c836358 100644 --- a/packages/app-cli/app/command-e2ee.js +++ b/packages/app-cli/app/command-e2ee.js @@ -1,8 +1,8 @@ const { BaseCommand } = require('./base-command.js'); const { _ } = require('@joplin/lib/locale'); -const EncryptionService = require('@joplin/lib/services/EncryptionService'); -const DecryptionWorker = require('@joplin/lib/services/DecryptionWorker'); -const BaseItem = require('@joplin/lib/models/BaseItem'); +const EncryptionService = require('@joplin/lib/services/EncryptionService').default; +const DecryptionWorker = require('@joplin/lib/services/DecryptionWorker').default; +const BaseItem = require('@joplin/lib/models/BaseItem').default; const Setting = require('@joplin/lib/models/Setting').default; const shim = require('@joplin/lib/shim').default; const pathUtils = require('@joplin/lib/path-utils'); diff --git a/packages/app-cli/app/command-edit.js b/packages/app-cli/app/command-edit.js index d2807bf5e..bbb57e66a 100644 --- a/packages/app-cli/app/command-edit.js +++ b/packages/app-cli/app/command-edit.js @@ -4,7 +4,7 @@ const { splitCommandString } = require('@joplin/lib/string-utils.js'); const uuid = require('@joplin/lib/uuid').default; const { app } = require('./app.js'); const { _ } = require('@joplin/lib/locale'); -const Note = require('@joplin/lib/models/Note.js'); +const Note = require('@joplin/lib/models/Note').default; const Setting = require('@joplin/lib/models/Setting').default; const BaseModel = require('@joplin/lib/BaseModel').default; diff --git a/packages/app-cli/app/command-export-sync-status.js b/packages/app-cli/app/command-export-sync-status.js index 44f258bfc..dde09fb67 100644 --- a/packages/app-cli/app/command-export-sync-status.js +++ b/packages/app-cli/app/command-export-sync-status.js @@ -1,7 +1,7 @@ const { BaseCommand } = require('./base-command.js'); const { app } = require('./app.js'); const Setting = require('@joplin/lib/models/Setting').default; -const { ReportService } = require('@joplin/lib/services/report.js'); +const ReportService = require('@joplin/lib/services/ReportService').default; const fs = require('fs-extra'); class Command extends BaseCommand { diff --git a/packages/app-cli/app/command-geoloc.js b/packages/app-cli/app/command-geoloc.js index e97000124..e504ea701 100644 --- a/packages/app-cli/app/command-geoloc.js +++ b/packages/app-cli/app/command-geoloc.js @@ -2,7 +2,7 @@ const { BaseCommand } = require('./base-command.js'); const { app } = require('./app.js'); const { _ } = require('@joplin/lib/locale'); const BaseModel = require('@joplin/lib/BaseModel').default; -const Note = require('@joplin/lib/models/Note.js'); +const Note = require('@joplin/lib/models/Note').default; class Command extends BaseCommand { usage() { diff --git a/packages/app-cli/app/command-ls.js b/packages/app-cli/app/command-ls.js index d7dd75f6a..a9f2898a0 100644 --- a/packages/app-cli/app/command-ls.js +++ b/packages/app-cli/app/command-ls.js @@ -2,9 +2,9 @@ const { BaseCommand } = require('./base-command.js'); const { app } = require('./app.js'); const { _ } = require('@joplin/lib/locale'); const BaseModel = require('@joplin/lib/BaseModel').default; -const Folder = require('@joplin/lib/models/Folder.js'); +const Folder = require('@joplin/lib/models/Folder').default; const Setting = require('@joplin/lib/models/Setting').default; -const Note = require('@joplin/lib/models/Note.js'); +const Note = require('@joplin/lib/models/Note').default; const { sprintf } = require('sprintf-js'); const time = require('@joplin/lib/time').default; const { cliUtils } = require('./cli-utils.js'); diff --git a/packages/app-cli/app/command-mkbook.js b/packages/app-cli/app/command-mkbook.js index 790822cc7..5a472e50e 100644 --- a/packages/app-cli/app/command-mkbook.js +++ b/packages/app-cli/app/command-mkbook.js @@ -1,7 +1,7 @@ const { BaseCommand } = require('./base-command.js'); const { app } = require('./app.js'); const { _ } = require('@joplin/lib/locale'); -const Folder = require('@joplin/lib/models/Folder.js'); +const Folder = require('@joplin/lib/models/Folder').default; class Command extends BaseCommand { usage() { diff --git a/packages/app-cli/app/command-mknote.js b/packages/app-cli/app/command-mknote.js index 496693de1..6dabb5348 100644 --- a/packages/app-cli/app/command-mknote.js +++ b/packages/app-cli/app/command-mknote.js @@ -1,7 +1,7 @@ const { BaseCommand } = require('./base-command.js'); const { app } = require('./app.js'); const { _ } = require('@joplin/lib/locale'); -const Note = require('@joplin/lib/models/Note.js'); +const Note = require('@joplin/lib/models/Note').default; class Command extends BaseCommand { usage() { diff --git a/packages/app-cli/app/command-mktodo.js b/packages/app-cli/app/command-mktodo.js index fc010b6c4..37bf42f13 100644 --- a/packages/app-cli/app/command-mktodo.js +++ b/packages/app-cli/app/command-mktodo.js @@ -1,7 +1,7 @@ const { BaseCommand } = require('./base-command.js'); const { app } = require('./app.js'); const { _ } = require('@joplin/lib/locale'); -const Note = require('@joplin/lib/models/Note.js'); +const Note = require('@joplin/lib/models/Note').default; class Command extends BaseCommand { usage() { diff --git a/packages/app-cli/app/command-mv.js b/packages/app-cli/app/command-mv.js index 4bbd42f14..4879e38f8 100644 --- a/packages/app-cli/app/command-mv.js +++ b/packages/app-cli/app/command-mv.js @@ -2,8 +2,8 @@ const { BaseCommand } = require('./base-command.js'); const { app } = require('./app.js'); const { _ } = require('@joplin/lib/locale'); const BaseModel = require('@joplin/lib/BaseModel').default; -const Folder = require('@joplin/lib/models/Folder.js'); -const Note = require('@joplin/lib/models/Note.js'); +const Folder = require('@joplin/lib/models/Folder').default; +const Note = require('@joplin/lib/models/Note').default; class Command extends BaseCommand { usage() { diff --git a/packages/app-cli/app/command-ren.js b/packages/app-cli/app/command-ren.js index 87beee797..72f3a02be 100644 --- a/packages/app-cli/app/command-ren.js +++ b/packages/app-cli/app/command-ren.js @@ -2,8 +2,8 @@ const { BaseCommand } = require('./base-command.js'); const { app } = require('./app.js'); const { _ } = require('@joplin/lib/locale'); const BaseModel = require('@joplin/lib/BaseModel').default; -const Folder = require('@joplin/lib/models/Folder.js'); -const Note = require('@joplin/lib/models/Note.js'); +const Folder = require('@joplin/lib/models/Folder').default; +const Note = require('@joplin/lib/models/Note').default; class Command extends BaseCommand { usage() { diff --git a/packages/app-cli/app/command-rmbook.js b/packages/app-cli/app/command-rmbook.js index 9ac7a02b4..7dd65c866 100644 --- a/packages/app-cli/app/command-rmbook.js +++ b/packages/app-cli/app/command-rmbook.js @@ -1,7 +1,7 @@ const { BaseCommand } = require('./base-command.js'); const { app } = require('./app.js'); const { _ } = require('@joplin/lib/locale'); -const Folder = require('@joplin/lib/models/Folder.js'); +const Folder = require('@joplin/lib/models/Folder').default; const BaseModel = require('@joplin/lib/BaseModel').default; class Command extends BaseCommand { diff --git a/packages/app-cli/app/command-rmnote.js b/packages/app-cli/app/command-rmnote.js index 803a6eecb..cfa422708 100644 --- a/packages/app-cli/app/command-rmnote.js +++ b/packages/app-cli/app/command-rmnote.js @@ -1,7 +1,7 @@ const { BaseCommand } = require('./base-command.js'); const { app } = require('./app.js'); const { _ } = require('@joplin/lib/locale'); -const Note = require('@joplin/lib/models/Note.js'); +const Note = require('@joplin/lib/models/Note').default; const BaseModel = require('@joplin/lib/BaseModel').default; class Command extends BaseCommand { diff --git a/packages/app-cli/app/command-search.js b/packages/app-cli/app/command-search.js index 69be13be0..1efca2cfc 100644 --- a/packages/app-cli/app/command-search.js +++ b/packages/app-cli/app/command-search.js @@ -1,7 +1,7 @@ const { BaseCommand } = require('./base-command.js'); const { _ } = require('@joplin/lib/locale'); const BaseModel = require('@joplin/lib/BaseModel').default; -const Folder = require('@joplin/lib/models/Folder.js'); +const Folder = require('@joplin/lib/models/Folder').default; const uuid = require('@joplin/lib/uuid').default; class Command extends BaseCommand { diff --git a/packages/app-cli/app/command-set.js b/packages/app-cli/app/command-set.js index 976b7258e..4063f6c72 100644 --- a/packages/app-cli/app/command-set.js +++ b/packages/app-cli/app/command-set.js @@ -3,7 +3,7 @@ const { app } = require('./app.js'); const { _ } = require('@joplin/lib/locale'); const BaseModel = require('@joplin/lib/BaseModel').default; const { Database } = require('@joplin/lib/database.js'); -const Note = require('@joplin/lib/models/Note.js'); +const Note = require('@joplin/lib/models/Note').default; class Command extends BaseCommand { usage() { diff --git a/packages/app-cli/app/command-status.js b/packages/app-cli/app/command-status.js index f40e2dd72..6ee4f9854 100644 --- a/packages/app-cli/app/command-status.js +++ b/packages/app-cli/app/command-status.js @@ -2,7 +2,7 @@ const { BaseCommand } = require('./base-command.js'); const { app } = require('./app.js'); const Setting = require('@joplin/lib/models/Setting').default; const { _ } = require('@joplin/lib/locale'); -const { ReportService } = require('@joplin/lib/services/report.js'); +const ReportService = require('@joplin/lib/services/ReportService').default; class Command extends BaseCommand { usage() { diff --git a/packages/app-cli/app/command-sync.js b/packages/app-cli/app/command-sync.js index 2a97ae4fb..d0a2bb08a 100644 --- a/packages/app-cli/app/command-sync.js +++ b/packages/app-cli/app/command-sync.js @@ -3,7 +3,7 @@ const { app } = require('./app.js'); const { _ } = require('@joplin/lib/locale'); const { OneDriveApiNodeUtils } = require('@joplin/lib/onedrive-api-node-utils.js'); const Setting = require('@joplin/lib/models/Setting').default; -const ResourceFetcher = require('@joplin/lib/services/ResourceFetcher'); +const ResourceFetcher = require('@joplin/lib/services/ResourceFetcher').default; const Synchronizer = require('@joplin/lib/Synchronizer').default; const { reg } = require('@joplin/lib/registry.js'); const { cliUtils } = require('./cli-utils.js'); diff --git a/packages/app-cli/app/command-tag.js b/packages/app-cli/app/command-tag.js index 1a5b1c807..e979b6f7e 100644 --- a/packages/app-cli/app/command-tag.js +++ b/packages/app-cli/app/command-tag.js @@ -1,7 +1,7 @@ const { BaseCommand } = require('./base-command.js'); const { app } = require('./app.js'); const { _ } = require('@joplin/lib/locale'); -const Tag = require('@joplin/lib/models/Tag.js'); +const Tag = require('@joplin/lib/models/Tag').default; const BaseModel = require('@joplin/lib/BaseModel').default; const time = require('@joplin/lib/time').default; diff --git a/packages/app-cli/app/command-todo.js b/packages/app-cli/app/command-todo.js index cf3793bdd..2d50e8f0c 100644 --- a/packages/app-cli/app/command-todo.js +++ b/packages/app-cli/app/command-todo.js @@ -2,7 +2,7 @@ const { BaseCommand } = require('./base-command.js'); const { app } = require('./app.js'); const { _ } = require('@joplin/lib/locale'); const BaseModel = require('@joplin/lib/BaseModel').default; -const Note = require('@joplin/lib/models/Note.js'); +const Note = require('@joplin/lib/models/Note').default; const time = require('@joplin/lib/time').default; class Command extends BaseCommand { diff --git a/packages/app-cli/app/fuzzing.js b/packages/app-cli/app/fuzzing.js index abf3e3ae1..2b9150554 100644 --- a/packages/app-cli/app/fuzzing.js +++ b/packages/app-cli/app/fuzzing.js @@ -2,7 +2,7 @@ const time = require('@joplin/lib/time').default; const Logger = require('@joplin/lib/Logger').default; -const Resource = require('@joplin/lib/models/Resource.js'); +const Resource = require('@joplin/lib/models/Resource').default; const { dirname } = require('@joplin/lib/path-utils'); const FsDriverNode = require('@joplin/lib/fs-driver-node').default; const lodash = require('lodash'); diff --git a/packages/app-cli/app/gui/FolderListWidget.js b/packages/app-cli/app/gui/FolderListWidget.js index 6e0e8276a..c87e75872 100644 --- a/packages/app-cli/app/gui/FolderListWidget.js +++ b/packages/app-cli/app/gui/FolderListWidget.js @@ -1,5 +1,5 @@ -const Folder = require('@joplin/lib/models/Folder.js'); -const Tag = require('@joplin/lib/models/Tag.js'); +const Folder = require('@joplin/lib/models/Folder').default; +const Tag = require('@joplin/lib/models/Tag').default; const BaseModel = require('@joplin/lib/BaseModel').default; const ListWidget = require('tkwidgets/ListWidget.js'); const _ = require('@joplin/lib/locale')._; diff --git a/packages/app-cli/app/gui/NoteListWidget.js b/packages/app-cli/app/gui/NoteListWidget.js index 62d9cf444..2d2166613 100644 --- a/packages/app-cli/app/gui/NoteListWidget.js +++ b/packages/app-cli/app/gui/NoteListWidget.js @@ -1,4 +1,4 @@ -const Note = require('@joplin/lib/models/Note.js'); +const Note = require('@joplin/lib/models/Note').default; const ListWidget = require('tkwidgets/ListWidget.js'); class NoteListWidget extends ListWidget { diff --git a/packages/app-cli/app/gui/NoteMetadataWidget.js b/packages/app-cli/app/gui/NoteMetadataWidget.js index 29d44e340..81eae4792 100644 --- a/packages/app-cli/app/gui/NoteMetadataWidget.js +++ b/packages/app-cli/app/gui/NoteMetadataWidget.js @@ -1,4 +1,4 @@ -const Note = require('@joplin/lib/models/Note.js'); +const Note = require('@joplin/lib/models/Note').default; const TextWidget = require('tkwidgets/TextWidget.js'); class NoteMetadataWidget extends TextWidget { diff --git a/packages/app-cli/app/gui/NoteWidget.js b/packages/app-cli/app/gui/NoteWidget.js index 0e5c112a7..6c0e3c6d2 100644 --- a/packages/app-cli/app/gui/NoteWidget.js +++ b/packages/app-cli/app/gui/NoteWidget.js @@ -1,4 +1,4 @@ -const Note = require('@joplin/lib/models/Note.js'); +const Note = require('@joplin/lib/models/Note').default; const TextWidget = require('tkwidgets/TextWidget.js'); const { _ } = require('@joplin/lib/locale'); diff --git a/packages/app-cli/app/main.js b/packages/app-cli/app/main.js index 268378c24..ba51809fc 100644 --- a/packages/app-cli/app/main.js +++ b/packages/app-cli/app/main.js @@ -11,15 +11,15 @@ if (compareVersion(nodeVersion, '10.0.0') < 0) { } const { app } = require('./app.js'); -const Folder = require('@joplin/lib/models/Folder.js'); -const Resource = require('@joplin/lib/models/Resource.js'); -const BaseItem = require('@joplin/lib/models/BaseItem.js'); -const Note = require('@joplin/lib/models/Note.js'); -const Tag = require('@joplin/lib/models/Tag.js'); -const NoteTag = require('@joplin/lib/models/NoteTag.js'); -const MasterKey = require('@joplin/lib/models/MasterKey'); +const Folder = require('@joplin/lib/models/Folder').default; +const Resource = require('@joplin/lib/models/Resource').default; +const BaseItem = require('@joplin/lib/models/BaseItem').default; +const Note = require('@joplin/lib/models/Note').default; +const Tag = require('@joplin/lib/models/Tag').default; +const NoteTag = require('@joplin/lib/models/NoteTag').default; +const MasterKey = require('@joplin/lib/models/MasterKey').default; const Setting = require('@joplin/lib/models/Setting').default; -const Revision = require('@joplin/lib/models/Revision.js'); +const Revision = require('@joplin/lib/models/Revision').default; const Logger = require('@joplin/lib/Logger').default; const FsDriverNode = require('@joplin/lib/fs-driver-node').default; const sharp = require('sharp'); @@ -27,7 +27,7 @@ const { shimInit } = require('@joplin/lib/shim-init-node.js'); const shim = require('@joplin/lib/shim').default; const { _ } = require('@joplin/lib/locale'); const { FileApiDriverLocal } = require('@joplin/lib/file-api-driver-local.js'); -const EncryptionService = require('@joplin/lib/services/EncryptionService'); +const EncryptionService = require('@joplin/lib/services/EncryptionService').default; const envFromArgs = require('@joplin/lib/envFromArgs'); const env = envFromArgs(process.argv); diff --git a/packages/app-cli/tests/EnexToMd.ts b/packages/app-cli/tests/EnexToMd.ts index a640665f9..1260d69dd 100644 --- a/packages/app-cli/tests/EnexToMd.ts +++ b/packages/app-cli/tests/EnexToMd.ts @@ -7,9 +7,9 @@ const { filename } = require('@joplin/lib/path-utils'); const { setupDatabaseAndSynchronizer, switchClient, expectNotThrow } = require('./test-utils.js'); const { enexXmlToMd } = require('@joplin/lib/import-enex-md-gen.js'); const { importEnex } = require('@joplin/lib/import-enex'); -const Note = require('@joplin/lib/models/Note'); -const Tag = require('@joplin/lib/models/Tag'); -const Resource = require('@joplin/lib/models/Resource'); +import Note from '@joplin/lib/models/Note'; +import Tag from '@joplin/lib/models/Tag'; +import Resource from '@joplin/lib/models/Resource'; const enexSampleBaseDir = `${__dirname}/enex_to_md`; diff --git a/packages/app-cli/tests/HtmlToHtml.js b/packages/app-cli/tests/HtmlToHtml.js index 7badad2e6..d54224d92 100644 --- a/packages/app-cli/tests/HtmlToHtml.js +++ b/packages/app-cli/tests/HtmlToHtml.js @@ -5,8 +5,8 @@ const os = require('os'); const time = require('@joplin/lib/time').default; const { filename } = require('@joplin/lib/path-utils'); const { fileContentEqual, setupDatabase, setupDatabaseAndSynchronizer, db, synchronizer, fileApi, sleep, clearDatabase, switchClient, syncTargetId, objectsEqual, checkThrowAsync } = require('./test-utils.js'); -const Folder = require('@joplin/lib/models/Folder.js'); -const Note = require('@joplin/lib/models/Note.js'); +const Folder = require('@joplin/lib/models/Folder').default; +const Note = require('@joplin/lib/models/Note').default; const BaseModel = require('@joplin/lib/BaseModel').default; const shim = require('@joplin/lib/shim').default; const HtmlToHtml = require('@joplin/renderer/HtmlToHtml').default; diff --git a/packages/app-cli/tests/InMemoryCache.ts b/packages/app-cli/tests/InMemoryCache.ts index ab7ba6933..a8a73606a 100644 --- a/packages/app-cli/tests/InMemoryCache.ts +++ b/packages/app-cli/tests/InMemoryCache.ts @@ -1,5 +1,5 @@ import InMemoryCache from '@joplin/lib/InMemoryCache'; -const time = require('@joplin/lib/time').default; +import time from '@joplin/lib/time'; describe('InMemoryCache', function() { diff --git a/packages/app-cli/tests/MdToHtml.ts b/packages/app-cli/tests/MdToHtml.ts index 610a44f9f..c21751655 100644 --- a/packages/app-cli/tests/MdToHtml.ts +++ b/packages/app-cli/tests/MdToHtml.ts @@ -2,7 +2,7 @@ import MdToHtml from '@joplin/renderer/MdToHtml'; const os = require('os'); const { filename } = require('@joplin/lib/path-utils'); const { setupDatabaseAndSynchronizer, switchClient } = require('./test-utils.js'); -const shim = require('@joplin/lib/shim').default; +import shim from '@joplin/lib/shim'; const { themeStyle } = require('@joplin/lib/theme'); function newTestMdToHtml(options: any = null) { diff --git a/packages/app-cli/tests/MdToMd.js b/packages/app-cli/tests/MdToMd.js index aa69ca57b..4873d3e32 100644 --- a/packages/app-cli/tests/MdToMd.js +++ b/packages/app-cli/tests/MdToMd.js @@ -1,5 +1,5 @@ const mdImporterService = require('@joplin/lib/services/interop/InteropService_Importer_Md').default; -const Note = require('@joplin/lib/models/Note.js'); +const Note = require('@joplin/lib/models/Note').default; const { setupDatabaseAndSynchronizer, switchClient } = require('./test-utils.js'); const importer = new mdImporterService(); diff --git a/packages/app-cli/tests/Synchronizer.basics.ts b/packages/app-cli/tests/Synchronizer.basics.ts index a5a19eb69..0fdfcdcf3 100644 --- a/packages/app-cli/tests/Synchronizer.basics.ts +++ b/packages/app-cli/tests/Synchronizer.basics.ts @@ -2,9 +2,9 @@ import Setting from '@joplin/lib/models/Setting'; import { allNotesFolders, remoteNotesAndFolders, localNotesFoldersSameAsRemote } from './test-utils-synchronizer'; const { syncTargetName, afterAllCleanUp, synchronizerStart, setupDatabaseAndSynchronizer, synchronizer, sleep, switchClient, syncTargetId, fileApi } = require('./test-utils.js'); -const Folder = require('@joplin/lib/models/Folder.js'); -const Note = require('@joplin/lib/models/Note.js'); -const BaseItem = require('@joplin/lib/models/BaseItem.js'); +import Folder from '@joplin/lib/models/Folder'; +import Note from '@joplin/lib/models/Note'; +import BaseItem from '@joplin/lib/models/BaseItem'; const WelcomeUtils = require('@joplin/lib/WelcomeUtils'); describe('Synchronizer.basics', function() { diff --git a/packages/app-cli/tests/Synchronizer.conflicts.ts b/packages/app-cli/tests/Synchronizer.conflicts.ts index 356467ee7..7491d3f36 100644 --- a/packages/app-cli/tests/Synchronizer.conflicts.ts +++ b/packages/app-cli/tests/Synchronizer.conflicts.ts @@ -3,9 +3,9 @@ import Setting from '@joplin/lib/models/Setting'; import { allNotesFolders, localNotesFoldersSameAsRemote } from './test-utils-synchronizer'; const { synchronizerStart, setupDatabaseAndSynchronizer, sleep, switchClient, syncTargetId, loadEncryptionMasterKey, decryptionWorker } = require('./test-utils.js'); -const Folder = require('@joplin/lib/models/Folder.js'); -const Note = require('@joplin/lib/models/Note.js'); -const BaseItem = require('@joplin/lib/models/BaseItem.js'); +import Folder from '@joplin/lib/models/Folder'; +import Note from '@joplin/lib/models/Note'; +import BaseItem from '@joplin/lib/models/BaseItem'; describe('Synchronizer.conflicts', function() { diff --git a/packages/app-cli/tests/Synchronizer.e2ee.ts b/packages/app-cli/tests/Synchronizer.e2ee.ts index 19959ef6f..a45ed4ab0 100644 --- a/packages/app-cli/tests/Synchronizer.e2ee.ts +++ b/packages/app-cli/tests/Synchronizer.e2ee.ts @@ -3,12 +3,12 @@ import shim from '@joplin/lib/shim'; import Setting from '@joplin/lib/models/Setting'; const { synchronizerStart, allSyncTargetItemsEncrypted, kvStore, setupDatabaseAndSynchronizer, synchronizer, fileApi, switchClient, encryptionService, loadEncryptionMasterKey, decryptionWorker, checkThrowAsync } = require('./test-utils.js'); -const Folder = require('@joplin/lib/models/Folder.js'); -const Note = require('@joplin/lib/models/Note.js'); -const Resource = require('@joplin/lib/models/Resource.js'); -const ResourceFetcher = require('@joplin/lib/services/ResourceFetcher'); -const MasterKey = require('@joplin/lib/models/MasterKey'); -const BaseItem = require('@joplin/lib/models/BaseItem.js'); +import Folder from '@joplin/lib/models/Folder'; +import Note from '@joplin/lib/models/Note'; +import Resource from '@joplin/lib/models/Resource'; +import ResourceFetcher from '@joplin/lib/services/ResourceFetcher'; +import MasterKey from '@joplin/lib/models/MasterKey'; +import BaseItem from '@joplin/lib/models/BaseItem'; let insideBeforeEach = false; diff --git a/packages/app-cli/tests/Synchronizer.resources.ts b/packages/app-cli/tests/Synchronizer.resources.ts index 90323ca94..d63259005 100644 --- a/packages/app-cli/tests/Synchronizer.resources.ts +++ b/packages/app-cli/tests/Synchronizer.resources.ts @@ -5,11 +5,11 @@ import { NoteEntity } from '@joplin/lib/services/database/types'; import { remoteNotesFoldersResources, remoteResources } from './test-utils-synchronizer'; const { synchronizerStart, tempFilePath, resourceFetcher, setupDatabaseAndSynchronizer, synchronizer, fileApi, switchClient, syncTargetId, encryptionService, loadEncryptionMasterKey, fileContentEqual, checkThrowAsync } = require('./test-utils.js'); -const Folder = require('@joplin/lib/models/Folder.js'); -const Note = require('@joplin/lib/models/Note.js'); -const Resource = require('@joplin/lib/models/Resource.js'); -const ResourceFetcher = require('@joplin/lib/services/ResourceFetcher'); -const BaseItem = require('@joplin/lib/models/BaseItem.js'); +import Folder from '@joplin/lib/models/Folder'; +import Note from '@joplin/lib/models/Note'; +import Resource from '@joplin/lib/models/Resource'; +import ResourceFetcher from '@joplin/lib/services/ResourceFetcher'; +import BaseItem from '@joplin/lib/models/BaseItem'; let insideBeforeEach = false; diff --git a/packages/app-cli/tests/Synchronizer.revisions.ts b/packages/app-cli/tests/Synchronizer.revisions.ts index 021e1e610..7c108bd59 100644 --- a/packages/app-cli/tests/Synchronizer.revisions.ts +++ b/packages/app-cli/tests/Synchronizer.revisions.ts @@ -2,8 +2,8 @@ import Setting from '@joplin/lib/models/Setting'; import BaseModel from '@joplin/lib/BaseModel'; const { synchronizerStart, revisionService, setupDatabaseAndSynchronizer, synchronizer, switchClient, encryptionService, loadEncryptionMasterKey, decryptionWorker } = require('./test-utils.js'); -const Note = require('@joplin/lib/models/Note.js'); -const Revision = require('@joplin/lib/models/Revision.js'); +import Note from '@joplin/lib/models/Note'; +import Revision from '@joplin/lib/models/Revision'; describe('Synchronizer.revisions', function() { diff --git a/packages/app-cli/tests/Synchronizer.tags.ts b/packages/app-cli/tests/Synchronizer.tags.ts index 1df563763..2c1b897af 100644 --- a/packages/app-cli/tests/Synchronizer.tags.ts +++ b/packages/app-cli/tests/Synchronizer.tags.ts @@ -1,10 +1,10 @@ import Setting from '@joplin/lib/models/Setting'; const { synchronizerStart, setupDatabaseAndSynchronizer, switchClient, encryptionService, loadEncryptionMasterKey } = require('./test-utils.js'); -const Folder = require('@joplin/lib/models/Folder.js'); -const Note = require('@joplin/lib/models/Note.js'); -const Tag = require('@joplin/lib/models/Tag.js'); -const MasterKey = require('@joplin/lib/models/MasterKey'); +import Folder from '@joplin/lib/models/Folder'; +import Note from '@joplin/lib/models/Note'; +import Tag from '@joplin/lib/models/Tag'; +import MasterKey from '@joplin/lib/models/MasterKey'; describe('Synchronizer.tags', function() { diff --git a/packages/app-cli/tests/database.js b/packages/app-cli/tests/database.js index c01eb1cbe..4b95c03bb 100644 --- a/packages/app-cli/tests/database.js +++ b/packages/app-cli/tests/database.js @@ -3,8 +3,8 @@ const time = require('@joplin/lib/time').default; const { sortedIds, createNTestNotes, fileContentEqual, setupDatabase, setupDatabaseAndSynchronizer, db, synchronizer, fileApi, sleep, clearDatabase, switchClient, syncTargetId, objectsEqual, checkThrowAsync } = require('./test-utils.js'); -const Folder = require('@joplin/lib/models/Folder.js'); -const Note = require('@joplin/lib/models/Note.js'); +const Folder = require('@joplin/lib/models/Folder').default; +const Note = require('@joplin/lib/models/Note').default; const Setting = require('@joplin/lib/models/Setting').default; const BaseModel = require('@joplin/lib/BaseModel').default; const ArrayUtils = require('@joplin/lib/ArrayUtils.js'); diff --git a/packages/app-cli/tests/feature_NoteHistory.js b/packages/app-cli/tests/feature_NoteHistory.js index d0eae4fa7..0867e90c7 100644 --- a/packages/app-cli/tests/feature_NoteHistory.js +++ b/packages/app-cli/tests/feature_NoteHistory.js @@ -1,8 +1,8 @@ const { id, ids, createNTestFolders, sortedIds, createNTestNotes, TestApp } = require('./test-utils.js'); const BaseModel = require('@joplin/lib/BaseModel').default; const uuid = require('@joplin/lib/uuid').default; -const Note = require('@joplin/lib/models/Note.js'); -const Folder = require('@joplin/lib/models/Folder.js'); +const Note = require('@joplin/lib/models/Note').default; +const Folder = require('@joplin/lib/models/Folder').default; const { ALL_NOTES_FILTER_ID } = require('@joplin/lib/reserved-ids.js'); diff --git a/packages/app-cli/tests/feature_NoteList.js b/packages/app-cli/tests/feature_NoteList.js index 147f27179..c72988007 100644 --- a/packages/app-cli/tests/feature_NoteList.js +++ b/packages/app-cli/tests/feature_NoteList.js @@ -1,9 +1,9 @@ /* eslint-disable no-unused-vars */ const { setupDatabaseAndSynchronizer, switchClient, createNTestFolders, createNTestNotes, createNTestTags, TestApp } = require('./test-utils.js'); const Setting = require('@joplin/lib/models/Setting').default; -const Folder = require('@joplin/lib/models/Folder.js'); -const Note = require('@joplin/lib/models/Note.js'); -const Tag = require('@joplin/lib/models/Tag.js'); +const Folder = require('@joplin/lib/models/Folder').default; +const Note = require('@joplin/lib/models/Note').default; +const Tag = require('@joplin/lib/models/Tag').default; const time = require('@joplin/lib/time').default; let testApp = null; diff --git a/packages/app-cli/tests/feature_ShowAllNotes.js b/packages/app-cli/tests/feature_ShowAllNotes.js index 756359854..051afd5cc 100644 --- a/packages/app-cli/tests/feature_ShowAllNotes.js +++ b/packages/app-cli/tests/feature_ShowAllNotes.js @@ -1,9 +1,9 @@ /* eslint-disable no-unused-vars */ const { setupDatabaseAndSynchronizer, switchClient, id, ids, sortedIds, at, createNTestFolders, createNTestNotes, createNTestTags, TestApp } = require('./test-utils.js'); const Setting = require('@joplin/lib/models/Setting').default; -const Folder = require('@joplin/lib/models/Folder.js'); -const Note = require('@joplin/lib/models/Note.js'); -const Tag = require('@joplin/lib/models/Tag.js'); +const Folder = require('@joplin/lib/models/Folder').default; +const Note = require('@joplin/lib/models/Note').default; +const Tag = require('@joplin/lib/models/Tag').default; const time = require('@joplin/lib/time').default; const { ALL_NOTES_FILTER_ID } = require('@joplin/lib/reserved-ids.js'); diff --git a/packages/app-cli/tests/feature_TagList.js b/packages/app-cli/tests/feature_TagList.js index 407cd5737..9e39dafb6 100644 --- a/packages/app-cli/tests/feature_TagList.js +++ b/packages/app-cli/tests/feature_TagList.js @@ -1,9 +1,9 @@ /* eslint-disable no-unused-vars */ const { setupDatabaseAndSynchronizer, switchClient, createNTestFolders, createNTestNotes, createNTestTags, TestApp } = require('./test-utils.js'); const Setting = require('@joplin/lib/models/Setting').default; -const Folder = require('@joplin/lib/models/Folder.js'); -const Note = require('@joplin/lib/models/Note.js'); -const Tag = require('@joplin/lib/models/Tag.js'); +const Folder = require('@joplin/lib/models/Folder').default; +const Note = require('@joplin/lib/models/Note').default; +const Tag = require('@joplin/lib/models/Tag').default; const time = require('@joplin/lib/time').default; let testApp = null; diff --git a/packages/app-cli/tests/models_BaseItem.js b/packages/app-cli/tests/models_BaseItem.js index 7da25f55a..1c0b84531 100644 --- a/packages/app-cli/tests/models_BaseItem.js +++ b/packages/app-cli/tests/models_BaseItem.js @@ -3,10 +3,10 @@ const time = require('@joplin/lib/time').default; const { fileContentEqual, setupDatabase, setupDatabaseAndSynchronizer, db, synchronizer, fileApi, sleep, clearDatabase, switchClient, syncTargetId, objectsEqual, checkThrowAsync } = require('./test-utils.js'); -const Folder = require('@joplin/lib/models/Folder.js'); -const Note = require('@joplin/lib/models/Note.js'); -const BaseItem = require('@joplin/lib/models/BaseItem.js'); -const Resource = require('@joplin/lib/models/Resource.js'); +const Folder = require('@joplin/lib/models/Folder').default; +const Note = require('@joplin/lib/models/Note').default; +const BaseItem = require('@joplin/lib/models/BaseItem').default; +const Resource = require('@joplin/lib/models/Resource').default; const BaseModel = require('@joplin/lib/BaseModel').default; const shim = require('@joplin/lib/shim').default; diff --git a/packages/app-cli/tests/models_Folder.ts b/packages/app-cli/tests/models_Folder.ts index 74394dd4f..19ec4b2e2 100644 --- a/packages/app-cli/tests/models_Folder.ts +++ b/packages/app-cli/tests/models_Folder.ts @@ -1,7 +1,7 @@ import { FolderEntity } from '@joplin/lib/services/database/types'; -const { createNTestNotes, setupDatabaseAndSynchronizer, sleep, switchClient, checkThrowAsync } = require('./test-utils.js'); -const Folder = require('@joplin/lib/models/Folder.js'); -const Note = require('@joplin/lib/models/Note.js'); +import { createNTestNotes, setupDatabaseAndSynchronizer, sleep, switchClient, checkThrowAsync } from './test-utils'; +import Folder from '@joplin/lib/models/Folder'; +import Note from '@joplin/lib/models/Note'; async function allItems() { const folders = await Folder.all(); @@ -169,9 +169,9 @@ describe('models_Folder', function() { await Note.save({ title: 'note1', parent_id: f3.id }); await Note.save({ title: 'note2', parent_id: f3.id }); await Note.save({ title: 'note3', parent_id: f1.id }); - await Note.save({ title: 'note4', parent_id: f3.id, is_todo: true, todo_completed: 0 }); - await Note.save({ title: 'note5', parent_id: f3.id, is_todo: true, todo_completed: 999 }); - await Note.save({ title: 'note6', parent_id: f3.id, is_todo: true, todo_completed: 999 }); + await Note.save({ title: 'note4', parent_id: f3.id, is_todo: 1, todo_completed: 0 }); + await Note.save({ title: 'note5', parent_id: f3.id, is_todo: 1, todo_completed: 999 }); + await Note.save({ title: 'note6', parent_id: f3.id, is_todo: 1, todo_completed: 999 }); const folders = await Folder.all(); await Folder.addNoteCounts(folders, false); diff --git a/packages/app-cli/tests/models_ItemChange.js b/packages/app-cli/tests/models_ItemChange.js index 8036be12c..4fef3244a 100644 --- a/packages/app-cli/tests/models_ItemChange.js +++ b/packages/app-cli/tests/models_ItemChange.js @@ -3,12 +3,12 @@ const time = require('@joplin/lib/time').default; const { fileContentEqual, revisionService, setupDatabase, setupDatabaseAndSynchronizer, db, synchronizer, fileApi, sleep, clearDatabase, switchClient, syncTargetId, objectsEqual, checkThrowAsync } = require('./test-utils.js'); -const SearchEngine = require('@joplin/lib/services/searchengine/SearchEngine'); +const SearchEngine = require('@joplin/lib/services/searchengine/SearchEngine').default; const ResourceService = require('@joplin/lib/services/ResourceService').default; -const ItemChangeUtils = require('@joplin/lib/services/ItemChangeUtils'); -const Note = require('@joplin/lib/models/Note'); +const ItemChangeUtils = require('@joplin/lib/services/ItemChangeUtils').default; +const Note = require('@joplin/lib/models/Note').default; const Setting = require('@joplin/lib/models/Setting').default; -const ItemChange = require('@joplin/lib/models/ItemChange'); +const ItemChange = require('@joplin/lib/models/ItemChange').default; let searchEngine = null; diff --git a/packages/app-cli/tests/models_Note.ts b/packages/app-cli/tests/models_Note.ts index 86c048e95..0058f58f4 100644 --- a/packages/app-cli/tests/models_Note.ts +++ b/packages/app-cli/tests/models_Note.ts @@ -3,8 +3,8 @@ import BaseModel from '@joplin/lib/BaseModel'; import shim from '@joplin/lib/shim'; import markdownUtils from '@joplin/lib/markdownUtils'; const { sortedIds, createNTestNotes, setupDatabaseAndSynchronizer, switchClient, checkThrowAsync } = require('./test-utils.js'); -const Folder = require('@joplin/lib/models/Folder.js'); -const Note = require('@joplin/lib/models/Note.js'); +import Folder from '@joplin/lib/models/Folder'; +import Note from '@joplin/lib/models/Note'; const ArrayUtils = require('@joplin/lib/ArrayUtils.js'); async function allItems() { @@ -55,7 +55,7 @@ describe('models_Note', function() { for (let i = 0; i < testCases.length; i++) { const t = testCases[i]; - const input = t[0]; + const input = t[0] as string; const expected = t[1]; const actual = Note.linkedItemIds(input); const contentEquals = ArrayUtils.contentEquals(actual, expected); @@ -204,7 +204,7 @@ describe('models_Note', function() { const folder2 = await Folder.save({ title: Folder.conflictFolderTitle(), id: Folder.conflictFolderId() }); const note1 = await Note.save({ title: 'note', parent_id: folder1.id }); - const hasThrown = await checkThrowAsync(async () => await Folder.copyToFolder(note1.id, folder2.id)); + const hasThrown = await checkThrowAsync(async () => await Note.copyToFolder(note1.id, folder2.id)); expect(hasThrown).toBe(true); })); @@ -260,7 +260,7 @@ describe('models_Note', function() { for (const testCase of testCases) { const [useAbsolutePaths, input, expected] = testCase; - const internalToExternal = await Note.replaceResourceInternalToExternalLinks(input, { useAbsolutePaths }); + const internalToExternal = await Note.replaceResourceInternalToExternalLinks(input as string, { useAbsolutePaths }); expect(internalToExternal).toBe(expected); const externalToInternal = await Note.replaceResourceExternalToInternalLinks(internalToExternal, { useAbsolutePaths }); @@ -280,11 +280,11 @@ describe('models_Note', function() { }); expect(sortedNotes.length).toBe(0); - const note0 = await Note.save({ title: 'A3', parent_id: folder1.id, is_todo: false }); - const note1 = await Note.save({ title: 'A20', parent_id: folder1.id, is_todo: false }); - const note2 = await Note.save({ title: 'A100', parent_id: folder1.id, is_todo: false }); - const note3 = await Note.save({ title: 'égalité', parent_id: folder1.id, is_todo: false }); - const note4 = await Note.save({ title: 'z', parent_id: folder1.id, is_todo: false }); + const note0 = await Note.save({ title: 'A3', parent_id: folder1.id, is_todo: 0 }); + const note1 = await Note.save({ title: 'A20', parent_id: folder1.id, is_todo: 0 }); + const note2 = await Note.save({ title: 'A100', parent_id: folder1.id, is_todo: 0 }); + const note3 = await Note.save({ title: 'égalité', parent_id: folder1.id, is_todo: 0 }); + const note4 = await Note.save({ title: 'z', parent_id: folder1.id, is_todo: 0 }); const sortedNotes2 = await Note.previews(folder1.id, { fields: ['id', 'title'], diff --git a/packages/app-cli/tests/models_Note_CustomSortOrder.js b/packages/app-cli/tests/models_Note_CustomSortOrder.js index c794e7371..5f28eed8b 100644 --- a/packages/app-cli/tests/models_Note_CustomSortOrder.js +++ b/packages/app-cli/tests/models_Note_CustomSortOrder.js @@ -3,8 +3,8 @@ const time = require('@joplin/lib/time').default; const { sortedIds, createNTestNotes, fileContentEqual, setupDatabase, setupDatabaseAndSynchronizer, db, synchronizer, fileApi, sleep, clearDatabase, switchClient, syncTargetId, objectsEqual, checkThrowAsync } = require('./test-utils.js'); -const Folder = require('@joplin/lib/models/Folder.js'); -const Note = require('@joplin/lib/models/Note.js'); +const Folder = require('@joplin/lib/models/Folder').default; +const Note = require('@joplin/lib/models/Note').default; const Setting = require('@joplin/lib/models/Setting').default; const BaseModel = require('@joplin/lib/BaseModel').default; const ArrayUtils = require('@joplin/lib/ArrayUtils.js'); diff --git a/packages/app-cli/tests/models_Resource.js b/packages/app-cli/tests/models_Resource.js index 3a38a5987..13c80b533 100644 --- a/packages/app-cli/tests/models_Resource.js +++ b/packages/app-cli/tests/models_Resource.js @@ -3,9 +3,9 @@ const time = require('@joplin/lib/time').default; const { fileContentEqual, setupDatabase, setupDatabaseAndSynchronizer, db, synchronizer, fileApi, sleep, clearDatabase, switchClient, syncTargetId, objectsEqual, checkThrowAsync } = require('./test-utils.js'); -const Folder = require('@joplin/lib/models/Folder.js'); -const Note = require('@joplin/lib/models/Note.js'); -const Resource = require('@joplin/lib/models/Resource.js'); +const Folder = require('@joplin/lib/models/Folder').default; +const Note = require('@joplin/lib/models/Note').default; +const Resource = require('@joplin/lib/models/Resource').default; const BaseModel = require('@joplin/lib/BaseModel').default; const shim = require('@joplin/lib/shim').default; diff --git a/packages/app-cli/tests/models_Revision.js b/packages/app-cli/tests/models_Revision.js index ec8026cbf..1ffd6129e 100644 --- a/packages/app-cli/tests/models_Revision.js +++ b/packages/app-cli/tests/models_Revision.js @@ -3,11 +3,11 @@ const time = require('@joplin/lib/time').default; const { fileContentEqual, setupDatabase, setupDatabaseAndSynchronizer, db, synchronizer, fileApi, sleep, clearDatabase, switchClient, syncTargetId, objectsEqual, checkThrowAsync } = require('./test-utils.js'); -const Folder = require('@joplin/lib/models/Folder.js'); -const Note = require('@joplin/lib/models/Note.js'); -const NoteTag = require('@joplin/lib/models/NoteTag.js'); -const Tag = require('@joplin/lib/models/Tag.js'); -const Revision = require('@joplin/lib/models/Revision.js'); +const Folder = require('@joplin/lib/models/Folder').default; +const Note = require('@joplin/lib/models/Note').default; +const NoteTag = require('@joplin/lib/models/NoteTag').default; +const Tag = require('@joplin/lib/models/Tag').default; +const Revision = require('@joplin/lib/models/Revision').default; const BaseModel = require('@joplin/lib/BaseModel').default; const shim = require('@joplin/lib/shim').default; diff --git a/packages/app-cli/tests/models_Tag.js b/packages/app-cli/tests/models_Tag.js index 687325f92..ac86124f3 100644 --- a/packages/app-cli/tests/models_Tag.js +++ b/packages/app-cli/tests/models_Tag.js @@ -3,10 +3,10 @@ const time = require('@joplin/lib/time').default; const { fileContentEqual, setupDatabase, setupDatabaseAndSynchronizer, db, synchronizer, fileApi, sleep, clearDatabase, switchClient, syncTargetId, objectsEqual, checkThrowAsync } = require('./test-utils.js'); -const Folder = require('@joplin/lib/models/Folder.js'); -const Note = require('@joplin/lib/models/Note.js'); -const NoteTag = require('@joplin/lib/models/NoteTag.js'); -const Tag = require('@joplin/lib/models/Tag.js'); +const Folder = require('@joplin/lib/models/Folder').default; +const Note = require('@joplin/lib/models/Note').default; +const NoteTag = require('@joplin/lib/models/NoteTag').default; +const Tag = require('@joplin/lib/models/Tag').default; const BaseModel = require('@joplin/lib/BaseModel').default; const shim = require('@joplin/lib/shim').default; diff --git a/packages/app-cli/tests/reducer.js b/packages/app-cli/tests/reducer.js index 3c53faea6..3e2489b64 100644 --- a/packages/app-cli/tests/reducer.js +++ b/packages/app-cli/tests/reducer.js @@ -1,9 +1,9 @@ /* eslint-disable no-unused-vars */ const { setupDatabaseAndSynchronizer, switchClient, createNTestNotes, createNTestFolders, createNTestTags } = require('./test-utils.js'); -const Folder = require('@joplin/lib/models/Folder.js'); -const Note = require('@joplin/lib/models/Note.js'); -const Tag = require('@joplin/lib/models/Tag.js'); +const Folder = require('@joplin/lib/models/Folder').default; +const Note = require('@joplin/lib/models/Note').default; +const Tag = require('@joplin/lib/models/Tag').default; const reducer = require('@joplin/lib/reducer').default; const { defaultState, stateUtils, MAX_HISTORY } = require('@joplin/lib/reducer'); diff --git a/packages/app-cli/tests/services/plugins/api/JoplinSettings.ts b/packages/app-cli/tests/services/plugins/api/JoplinSettings.ts index 12eee95a5..9507147d1 100644 --- a/packages/app-cli/tests/services/plugins/api/JoplinSettings.ts +++ b/packages/app-cli/tests/services/plugins/api/JoplinSettings.ts @@ -1,7 +1,7 @@ import Setting from '@joplin/lib/models/Setting'; import PluginService from '@joplin/lib/services/plugins/PluginService'; const { waitForFolderCount, newPluginService, newPluginScript, setupDatabaseAndSynchronizer, switchClient, afterEachCleanUp } = require('../../../test-utils'); -const Folder = require('@joplin/lib/models/Folder'); +import Folder from '@joplin/lib/models/Folder'; describe('JoplinSettings', () => { diff --git a/packages/app-cli/tests/services/plugins/api/JoplinWorkspace.ts b/packages/app-cli/tests/services/plugins/api/JoplinWorkspace.ts index b4f0d7eb4..f8476cd96 100644 --- a/packages/app-cli/tests/services/plugins/api/JoplinWorkspace.ts +++ b/packages/app-cli/tests/services/plugins/api/JoplinWorkspace.ts @@ -2,9 +2,9 @@ import Setting from '@joplin/lib/models/Setting'; import PluginService from '@joplin/lib/services/plugins/PluginService'; const { newPluginService, newPluginScript, setupDatabaseAndSynchronizer, switchClient, afterEachCleanUp } = require('../../../test-utils'); -const Note = require('@joplin/lib/models/Note'); -const Folder = require('@joplin/lib/models/Folder'); -const ItemChange = require('@joplin/lib/models/ItemChange'); +import Note from '@joplin/lib/models/Note'; +import Folder from '@joplin/lib/models/Folder'; +import ItemChange from '@joplin/lib/models/ItemChange'; describe('JoplinWorkspace', () => { diff --git a/packages/app-cli/tests/services_EncryptionService.js b/packages/app-cli/tests/services_EncryptionService.js index 372307bd6..faf863990 100644 --- a/packages/app-cli/tests/services_EncryptionService.js +++ b/packages/app-cli/tests/services_EncryptionService.js @@ -3,16 +3,16 @@ const time = require('@joplin/lib/time').default; const { fileContentEqual, setupDatabase, setupDatabaseAndSynchronizer, db, synchronizer, fileApi, sleep, clearDatabase, switchClient, syncTargetId, objectsEqual, checkThrowAsync } = require('./test-utils.js'); -const Folder = require('@joplin/lib/models/Folder.js'); -const Note = require('@joplin/lib/models/Note.js'); -const Tag = require('@joplin/lib/models/Tag.js'); +const Folder = require('@joplin/lib/models/Folder').default; +const Note = require('@joplin/lib/models/Note').default; +const Tag = require('@joplin/lib/models/Tag').default; const { Database } = require('@joplin/lib/database.js'); const Setting = require('@joplin/lib/models/Setting').default; -const BaseItem = require('@joplin/lib/models/BaseItem.js'); +const BaseItem = require('@joplin/lib/models/BaseItem').default; const BaseModel = require('@joplin/lib/BaseModel').default; -const MasterKey = require('@joplin/lib/models/MasterKey'); +const MasterKey = require('@joplin/lib/models/MasterKey').default; const SyncTargetRegistry = require('@joplin/lib/SyncTargetRegistry.js'); -const EncryptionService = require('@joplin/lib/services/EncryptionService.js'); +const EncryptionService = require('@joplin/lib/services/EncryptionService').default; let service = null; diff --git a/packages/app-cli/tests/services_InteropService.ts b/packages/app-cli/tests/services_InteropService.ts index 534d7c165..2a7b3bf25 100644 --- a/packages/app-cli/tests/services_InteropService.ts +++ b/packages/app-cli/tests/services_InteropService.ts @@ -3,10 +3,10 @@ import { CustomExportContext, CustomImportContext, Module, ModuleType } from '@j import shim from '@joplin/lib/shim'; const { fileContentEqual, setupDatabaseAndSynchronizer, switchClient, checkThrowAsync, exportDir } = require('./test-utils.js'); -const Folder = require('@joplin/lib/models/Folder.js'); -const Note = require('@joplin/lib/models/Note.js'); -const Tag = require('@joplin/lib/models/Tag.js'); -const Resource = require('@joplin/lib/models/Resource.js'); +import Folder from '@joplin/lib/models/Folder'; +import Note from '@joplin/lib/models/Note'; +import Tag from '@joplin/lib/models/Tag'; +import Resource from '@joplin/lib/models/Resource'; const fs = require('fs-extra'); const ArrayUtils = require('@joplin/lib/ArrayUtils'); diff --git a/packages/app-cli/tests/services_InteropService_Exporter_Md.js b/packages/app-cli/tests/services_InteropService_Exporter_Md.js index 6a8a66b44..54f6d268c 100644 --- a/packages/app-cli/tests/services_InteropService_Exporter_Md.js +++ b/packages/app-cli/tests/services_InteropService_Exporter_Md.js @@ -5,9 +5,9 @@ const fs = require('fs-extra'); const { setupDatabaseAndSynchronizer, switchClient, exportDir } = require('./test-utils.js'); const InteropService_Exporter_Md = require('@joplin/lib/services/interop/InteropService_Exporter_Md').default; const BaseModel = require('@joplin/lib/BaseModel').default; -const Folder = require('@joplin/lib/models/Folder.js'); -const Resource = require('@joplin/lib/models/Resource.js'); -const Note = require('@joplin/lib/models/Note.js'); +const Folder = require('@joplin/lib/models/Folder').default; +const Resource = require('@joplin/lib/models/Resource').default; +const Note = require('@joplin/lib/models/Note').default; const shim = require('@joplin/lib/shim').default; describe('services_InteropService_Exporter_Md', function() { diff --git a/packages/app-cli/tests/services_PluginService.ts b/packages/app-cli/tests/services_PluginService.ts index 2f27e19a7..3a4530bd7 100644 --- a/packages/app-cli/tests/services_PluginService.ts +++ b/packages/app-cli/tests/services_PluginService.ts @@ -7,8 +7,8 @@ import Setting from '@joplin/lib/models/Setting'; const fs = require('fs-extra'); const { expectNotThrow, setupDatabaseAndSynchronizer, switchClient, expectThrow, createTempDir } = require('./test-utils.js'); -const Note = require('@joplin/lib/models/Note'); -const Folder = require('@joplin/lib/models/Folder'); +import Note from '@joplin/lib/models/Note'; +import Folder from '@joplin/lib/models/Folder'; const testPluginDir = `${__dirname}/../tests/support/plugins`; diff --git a/packages/app-cli/tests/services_ResourceService.ts b/packages/app-cli/tests/services_ResourceService.ts index a08384294..b1f674943 100644 --- a/packages/app-cli/tests/services_ResourceService.ts +++ b/packages/app-cli/tests/services_ResourceService.ts @@ -4,10 +4,10 @@ import ResourceService from '@joplin/lib/services/ResourceService'; import shim from '@joplin/lib/shim'; const { resourceService, decryptionWorker, encryptionService, loadEncryptionMasterKey, allSyncTargetItemsEncrypted, setupDatabaseAndSynchronizer, db, synchronizer, switchClient } = require('./test-utils.js'); -const Folder = require('@joplin/lib/models/Folder.js'); -const Note = require('@joplin/lib/models/Note.js'); -const Resource = require('@joplin/lib/models/Resource.js'); -const SearchEngine = require('@joplin/lib/services/searchengine/SearchEngine'); +import Folder from '@joplin/lib/models/Folder'; +import Note from '@joplin/lib/models/Note'; +import Resource from '@joplin/lib/models/Resource'; +import SearchEngine from '@joplin/lib/services/searchengine/SearchEngine'; describe('services_ResourceService', function() { diff --git a/packages/app-cli/tests/services_Revision.js b/packages/app-cli/tests/services_Revision.js index 9f83ec145..5d968f933 100644 --- a/packages/app-cli/tests/services_Revision.js +++ b/packages/app-cli/tests/services_Revision.js @@ -3,15 +3,15 @@ const time = require('@joplin/lib/time').default; const { fileContentEqual, setupDatabase, revisionService, setupDatabaseAndSynchronizer, db, synchronizer, fileApi, sleep, clearDatabase, switchClient, syncTargetId, objectsEqual, checkThrowAsync } = require('./test-utils.js'); -const Folder = require('@joplin/lib/models/Folder.js'); +const Folder = require('@joplin/lib/models/Folder').default; const Setting = require('@joplin/lib/models/Setting').default; -const Note = require('@joplin/lib/models/Note.js'); -const NoteTag = require('@joplin/lib/models/NoteTag.js'); -const ItemChange = require('@joplin/lib/models/ItemChange.js'); -const Tag = require('@joplin/lib/models/Tag.js'); -const Revision = require('@joplin/lib/models/Revision.js'); +const Note = require('@joplin/lib/models/Note').default; +const NoteTag = require('@joplin/lib/models/NoteTag').default; +const ItemChange = require('@joplin/lib/models/ItemChange').default; +const Tag = require('@joplin/lib/models/Tag').default; +const Revision = require('@joplin/lib/models/Revision').default; const BaseModel = require('@joplin/lib/BaseModel').default; -const RevisionService = require('@joplin/lib/services/RevisionService.js'); +const RevisionService = require('@joplin/lib/services/RevisionService').default; const shim = require('@joplin/lib/shim').default; describe('services_Revision', function() { diff --git a/packages/app-cli/tests/services_SearchEngine.js b/packages/app-cli/tests/services_SearchEngine.js index 57871e995..09cd36ac5 100644 --- a/packages/app-cli/tests/services_SearchEngine.js +++ b/packages/app-cli/tests/services_SearchEngine.js @@ -4,9 +4,9 @@ const time = require('@joplin/lib/time').default; const { fileContentEqual, setupDatabase, setupDatabaseAndSynchronizer, db, synchronizer, fileApi, sleep, clearDatabase, switchClient, syncTargetId, objectsEqual, checkThrowAsync, restoreDate } = require('./test-utils.js'); -const SearchEngine = require('@joplin/lib/services/searchengine/SearchEngine'); -const Note = require('@joplin/lib/models/Note'); -const ItemChange = require('@joplin/lib/models/ItemChange'); +const SearchEngine = require('@joplin/lib/services/searchengine/SearchEngine').default; +const Note = require('@joplin/lib/models/Note').default; +const ItemChange = require('@joplin/lib/models/ItemChange').default; const Setting = require('@joplin/lib/models/Setting').default; let engine = null; diff --git a/packages/app-cli/tests/services_SearchFilter.js b/packages/app-cli/tests/services_SearchFilter.js index 4397c3d77..96a00835b 100644 --- a/packages/app-cli/tests/services_SearchFilter.js +++ b/packages/app-cli/tests/services_SearchFilter.js @@ -4,13 +4,13 @@ const time = require('@joplin/lib/time').default; const { fileContentEqual, setupDatabase, setupDatabaseAndSynchronizer, db, synchronizer, fileApi, sleep, createNTestNotes, switchClient, createNTestFolders } = require('./test-utils.js'); -const SearchEngine = require('@joplin/lib/services/searchengine/SearchEngine'); -const Note = require('@joplin/lib/models/Note'); -const Folder = require('@joplin/lib/models/Folder'); -const Tag = require('@joplin/lib/models/Tag'); -const ItemChange = require('@joplin/lib/models/ItemChange'); +const SearchEngine = require('@joplin/lib/services/searchengine/SearchEngine').default; +const Note = require('@joplin/lib/models/Note').default; +const Folder = require('@joplin/lib/models/Folder').default; +const Tag = require('@joplin/lib/models/Tag').default; +const ItemChange = require('@joplin/lib/models/ItemChange').default; const Setting = require('@joplin/lib/models/Setting').default; -const Resource = require('@joplin/lib/models/Resource.js'); +const Resource = require('@joplin/lib/models/Resource').default; const shim = require('@joplin/lib/shim').default; const ResourceService = require('@joplin/lib/services/ResourceService').default; diff --git a/packages/app-cli/tests/services_rest_Api.ts b/packages/app-cli/tests/services_rest_Api.ts index 34e9557a5..18eea4956 100644 --- a/packages/app-cli/tests/services_rest_Api.ts +++ b/packages/app-cli/tests/services_rest_Api.ts @@ -3,13 +3,13 @@ import Api, { RequestMethod } from '@joplin/lib/services/rest/Api'; import shim from '@joplin/lib/shim'; const { setupDatabaseAndSynchronizer, switchClient, checkThrowAsync, db, msleep } = require('./test-utils.js'); -const Folder = require('@joplin/lib/models/Folder'); -const Resource = require('@joplin/lib/models/Resource'); -const Note = require('@joplin/lib/models/Note'); -const Tag = require('@joplin/lib/models/Tag'); -const NoteTag = require('@joplin/lib/models/NoteTag'); -const ResourceService = require('@joplin/lib/services/ResourceService').default; -const SearchEngine = require('@joplin/lib/services/searchengine/SearchEngine'); +import Folder from '@joplin/lib/models/Folder'; +import Resource from '@joplin/lib/models/Resource'; +import Note from '@joplin/lib/models/Note'; +import Tag from '@joplin/lib/models/Tag'; +import NoteTag from '@joplin/lib/models/NoteTag'; +import ResourceService from '@joplin/lib/services/ResourceService'; +import SearchEngine from '@joplin/lib/services/searchengine/SearchEngine'; const createFolderForPagination = async (num: number, time: number) => { await Folder.save({ @@ -422,8 +422,8 @@ describe('services_rest_Api', function() { const note = await Note.save({ title: 'ma note un', }); - Tag.addNote(tag1.id, note.id); - Tag.addNote(tag2.id, note.id); + await Tag.addNote(tag1.id, note.id); + await Tag.addNote(tag2.id, note.id); const response = await api.route(RequestMethod.PUT, `notes/${note.id}`, null, JSON.stringify({ tags: `${tag1.title},${tag3.title}`, @@ -443,8 +443,8 @@ describe('services_rest_Api', function() { const note = await Note.save({ title: 'ma note un', }); - Tag.addNote(tag1.id, note.id); - Tag.addNote(tag2.id, note.id); + await Tag.addNote(tag1.id, note.id); + await Tag.addNote(tag2.id, note.id); const response = await api.route(RequestMethod.PUT, `notes/${note.id}`, null, JSON.stringify({ tags: `${tag1.title},${newTagTitle}`, @@ -464,8 +464,8 @@ describe('services_rest_Api', function() { const note = await Note.save({ title: 'ma note un', }); - Tag.addNote(tag1.id, note.id); - Tag.addNote(tag2.id, note.id); + await Tag.addNote(tag1.id, note.id); + await Tag.addNote(tag2.id, note.id); const response = await api.route(RequestMethod.PUT, `notes/${note.id}`, null, JSON.stringify({ title: 'Some other title', @@ -484,8 +484,8 @@ describe('services_rest_Api', function() { const note = await Note.save({ title: 'ma note un', }); - Tag.addNote(tag1.id, note.id); - Tag.addNote(tag2.id, note.id); + await Tag.addNote(tag1.id, note.id); + await Tag.addNote(tag2.id, note.id); const response = await api.route(RequestMethod.PUT, `notes/${note.id}`, null, JSON.stringify({ tags: '', diff --git a/packages/app-cli/tests/support/syncTargetUtils.js b/packages/app-cli/tests/support/syncTargetUtils.js index 86635bb09..b68e539a0 100644 --- a/packages/app-cli/tests/support/syncTargetUtils.js +++ b/packages/app-cli/tests/support/syncTargetUtils.js @@ -1,9 +1,9 @@ const { syncDir, fileApi, synchronizer, createSyncTargetSnapshot, loadEncryptionMasterKey, decryptionWorker, encryptionService, setupDatabaseAndSynchronizer, switchClient, expectThrow, expectNotThrow } = require('../test-utils.js'); const Setting = require('@joplin/lib/models/Setting').default; -const Folder = require('@joplin/lib/models/Folder'); -const Note = require('@joplin/lib/models/Note'); -const Tag = require('@joplin/lib/models/Tag'); -const Resource = require('@joplin/lib/models/Resource'); +const Folder = require('@joplin/lib/models/Folder').default; +const Note = require('@joplin/lib/models/Note').default; +const Tag = require('@joplin/lib/models/Tag').default; +const Resource = require('@joplin/lib/models/Resource').default; const markdownUtils = require('@joplin/lib/markdownUtils').default;; const shim = require('@joplin/lib/shim').default; const fs = require('fs-extra'); diff --git a/packages/app-cli/tests/synchronizer_MigrationHandler.ts b/packages/app-cli/tests/synchronizer_MigrationHandler.ts index 98d9bc780..8e92d4ed8 100644 --- a/packages/app-cli/tests/synchronizer_MigrationHandler.ts +++ b/packages/app-cli/tests/synchronizer_MigrationHandler.ts @@ -10,8 +10,8 @@ import { Dirnames } from '@joplin/lib/services/synchronizer/utils/types'; const { setSyncTargetName, fileApi, synchronizer, decryptionWorker, encryptionService, setupDatabaseAndSynchronizer, switchClient, expectThrow, expectNotThrow } = require('./test-utils.js'); const { deploySyncTargetSnapshot, testData, checkTestData } = require('./support/syncTargetUtils'); -const Setting = require('@joplin/lib/models/Setting').default; -const MasterKey = require('@joplin/lib/models/MasterKey'); +import Setting from '@joplin/lib/models/Setting'; +import MasterKey from '@joplin/lib/models/MasterKey'; const specTimeout = 60000 * 10; // Nextcloud tests can be slow diff --git a/packages/app-cli/tests/test-utils-synchronizer.ts b/packages/app-cli/tests/test-utils-synchronizer.ts index 327ff016f..43ed8f2cd 100644 --- a/packages/app-cli/tests/test-utils-synchronizer.ts +++ b/packages/app-cli/tests/test-utils-synchronizer.ts @@ -1,9 +1,9 @@ import BaseModel from '@joplin/lib/BaseModel'; const { fileApi } = require('./test-utils.js'); -const Folder = require('@joplin/lib/models/Folder.js'); -const Note = require('@joplin/lib/models/Note.js'); -const BaseItem = require('@joplin/lib/models/BaseItem.js'); +import Folder from '@joplin/lib/models/Folder'; +import Note from '@joplin/lib/models/Note'; +import BaseItem from '@joplin/lib/models/BaseItem'; export async function allNotesFolders() { const folders = await Folder.all(); diff --git a/packages/app-cli/tests/test-utils.ts b/packages/app-cli/tests/test-utils.ts index 4bc16acc9..1582b3169 100644 --- a/packages/app-cli/tests/test-utils.ts +++ b/packages/app-cli/tests/test-utils.ts @@ -22,15 +22,15 @@ import SyncTargetOneDrive from '@joplin/lib/SyncTargetOneDrive'; const fs = require('fs-extra'); const { JoplinDatabase } = require('@joplin/lib/joplin-database.js'); const { DatabaseDriverNode } = require('@joplin/lib/database-driver-node.js'); -const Folder = require('@joplin/lib/models/Folder.js'); -const Note = require('@joplin/lib/models/Note.js'); -const ItemChange = require('@joplin/lib/models/ItemChange.js'); -const Resource = require('@joplin/lib/models/Resource.js'); -const Tag = require('@joplin/lib/models/Tag.js'); -const NoteTag = require('@joplin/lib/models/NoteTag.js'); -const Revision = require('@joplin/lib/models/Revision.js'); -const MasterKey = require('@joplin/lib/models/MasterKey'); -const BaseItem = require('@joplin/lib/models/BaseItem.js'); +import Folder from '@joplin/lib/models/Folder'; +import Note from '@joplin/lib/models/Note'; +import ItemChange from '@joplin/lib/models/ItemChange'; +import Resource from '@joplin/lib/models/Resource'; +import Tag from '@joplin/lib/models/Tag'; +import NoteTag from '@joplin/lib/models/NoteTag'; +import Revision from '@joplin/lib/models/Revision'; +import MasterKey from '@joplin/lib/models/MasterKey'; +import BaseItem from '@joplin/lib/models/BaseItem'; const { FileApi } = require('@joplin/lib/file-api.js'); const { FileApiDriverMemory } = require('@joplin/lib/file-api-driver-memory.js'); const { FileApiDriverLocal } = require('@joplin/lib/file-api-driver-local.js'); @@ -45,14 +45,14 @@ const SyncTargetFilesystem = require('@joplin/lib/SyncTargetFilesystem.js'); const SyncTargetNextcloud = require('@joplin/lib/SyncTargetNextcloud.js'); const SyncTargetDropbox = require('@joplin/lib/SyncTargetDropbox.js'); const SyncTargetAmazonS3 = require('@joplin/lib/SyncTargetAmazonS3.js'); -const SyncTargetJoplinServer = require('@joplin/lib/SyncTargetJoplinServer').default; -const EncryptionService = require('@joplin/lib/services/EncryptionService.js'); -const DecryptionWorker = require('@joplin/lib/services/DecryptionWorker.js'); -const RevisionService = require('@joplin/lib/services/RevisionService.js'); -const ResourceFetcher = require('@joplin/lib/services/ResourceFetcher.js'); +import SyncTargetJoplinServer from '@joplin/lib/SyncTargetJoplinServer'; +import EncryptionService from '@joplin/lib/services/EncryptionService'; +import DecryptionWorker from '@joplin/lib/services/DecryptionWorker'; +import RevisionService from '@joplin/lib/services/RevisionService'; +import ResourceFetcher from '@joplin/lib/services/ResourceFetcher'; const WebDavApi = require('@joplin/lib/WebDavApi'); const DropboxApi = require('@joplin/lib/DropboxApi'); -const JoplinServerApi = require('@joplin/lib/JoplinServerApi2').default; +import JoplinServerApi from '@joplin/lib/JoplinServerApi2'; const { loadKeychainServiceAndSettings } = require('@joplin/lib/services/SettingUtils'); const md5 = require('md5'); const S3 = require('aws-sdk/clients/s3'); diff --git a/packages/app-desktop/InteropServiceHelper.ts b/packages/app-desktop/InteropServiceHelper.ts index faeba5b36..7fc027f15 100644 --- a/packages/app-desktop/InteropServiceHelper.ts +++ b/packages/app-desktop/InteropServiceHelper.ts @@ -6,10 +6,10 @@ import { ExportOptions, FileSystemItem, Module } from '@joplin/lib/services/inte import { _ } from '@joplin/lib/locale'; import { PluginStates } from '@joplin/lib/services/plugins/reducer'; const bridge = require('electron').remote.require('./bridge').default; -const Setting = require('@joplin/lib/models/Setting').default; -const Note = require('@joplin/lib/models/Note.js'); +import Setting from '@joplin/lib/models/Setting'; +import Note from '@joplin/lib/models/Note'; const { friendlySafeFilename } = require('@joplin/lib/path-utils'); -const time = require('@joplin/lib/time').default; +import time from '@joplin/lib/time'; const md5 = require('md5'); const url = require('url'); diff --git a/packages/app-desktop/app.ts b/packages/app-desktop/app.ts index 396cbebbd..d87de2050 100644 --- a/packages/app-desktop/app.ts +++ b/packages/app-desktop/app.ts @@ -27,22 +27,22 @@ import iterateItems from './gui/ResizableLayout/utils/iterateItems'; import validateLayout from './gui/ResizableLayout/utils/validateLayout'; const { FoldersScreenUtils } = require('@joplin/lib/folders-screen-utils.js'); -const MasterKey = require('@joplin/lib/models/MasterKey'); -const Folder = require('@joplin/lib/models/Folder'); +import MasterKey from '@joplin/lib/models/MasterKey'; +import Folder from '@joplin/lib/models/Folder'; const fs = require('fs-extra'); -const Tag = require('@joplin/lib/models/Tag.js'); +import Tag from '@joplin/lib/models/Tag'; const { reg } = require('@joplin/lib/registry.js'); const packageInfo = require('./packageInfo.js'); -const DecryptionWorker = require('@joplin/lib/services/DecryptionWorker'); +import DecryptionWorker from '@joplin/lib/services/DecryptionWorker'; const ClipperServer = require('@joplin/lib/ClipperServer'); const { webFrame } = require('electron'); const Menu = bridge().Menu; const PluginManager = require('@joplin/lib/services/PluginManager'); -const RevisionService = require('@joplin/lib/services/RevisionService'); -const MigrationService = require('@joplin/lib/services/MigrationService'); +import RevisionService from '@joplin/lib/services/RevisionService'; +import MigrationService from '@joplin/lib/services/MigrationService'; const TemplateUtils = require('@joplin/lib/TemplateUtils'); const CssUtils = require('@joplin/lib/CssUtils'); -// const populateDatabase = require('@joplin/lib/services/debug/populateDatabase').default; +// import populateDatabase from '@joplin/lib/services/debug/populateDatabase'; const commands = [ require('./gui/MainScreen/commands/editAlarm'), @@ -97,7 +97,7 @@ const globalCommands = [ require('@joplin/lib/commands/synchronize'), ]; -const editorCommandDeclarations = require('./gui/NoteEditor/commands/editorCommandDeclarations').default; +import editorCommandDeclarations from './gui/NoteEditor/commands/editorCommandDeclarations'; const pluginClasses = [ require('./plugins/GotoAnything').default, @@ -709,7 +709,7 @@ class Application extends BaseApplication { // might change the notifications. void AlarmService.updateAllNotifications(); - DecryptionWorker.instance().scheduleStart(); + void DecryptionWorker.instance().scheduleStart(); }); } diff --git a/packages/app-desktop/commands/startExternalEditing.ts b/packages/app-desktop/commands/startExternalEditing.ts index 7d7ce11c1..b2189ca69 100644 --- a/packages/app-desktop/commands/startExternalEditing.ts +++ b/packages/app-desktop/commands/startExternalEditing.ts @@ -2,7 +2,7 @@ import { CommandRuntime, CommandDeclaration, CommandContext } from '@joplin/lib/ import { _ } from '@joplin/lib/locale'; import { stateUtils } from '@joplin/lib/reducer'; import ExternalEditWatcher from '@joplin/lib/services/ExternalEditWatcher'; -const Note = require('@joplin/lib/models/Note'); +import Note from '@joplin/lib/models/Note'; const bridge = require('electron').remote.require('./bridge').default; export const declaration: CommandDeclaration = { diff --git a/packages/app-desktop/gui/EncryptionConfigScreen.jsx b/packages/app-desktop/gui/EncryptionConfigScreen.jsx index 91449367a..2c3f6ee78 100644 --- a/packages/app-desktop/gui/EncryptionConfigScreen.jsx +++ b/packages/app-desktop/gui/EncryptionConfigScreen.jsx @@ -1,7 +1,7 @@ const React = require('react'); const { connect } = require('react-redux'); const Setting = require('@joplin/lib/models/Setting').default; -const EncryptionService = require('@joplin/lib/services/EncryptionService'); +const EncryptionService = require('@joplin/lib/services/EncryptionService').default; const { themeStyle } = require('@joplin/lib/theme'); const { _ } = require('@joplin/lib/locale'); const time = require('@joplin/lib/time').default; diff --git a/packages/app-desktop/gui/ImportScreen.jsx b/packages/app-desktop/gui/ImportScreen.jsx index d125d9eb1..60db8fd0f 100644 --- a/packages/app-desktop/gui/ImportScreen.jsx +++ b/packages/app-desktop/gui/ImportScreen.jsx @@ -1,6 +1,6 @@ const React = require('react'); const { connect } = require('react-redux'); -const Folder = require('@joplin/lib/models/Folder.js'); +const Folder = require('@joplin/lib/models/Folder').default; const { themeStyle } = require('@joplin/lib/theme'); const { _ } = require('@joplin/lib/locale'); const { filename, basename } = require('@joplin/lib/path-utils'); diff --git a/packages/app-desktop/gui/KeymapConfig/KeymapConfigScreen.tsx b/packages/app-desktop/gui/KeymapConfig/KeymapConfigScreen.tsx index 83a01a17f..f3c8af8fe 100644 --- a/packages/app-desktop/gui/KeymapConfig/KeymapConfigScreen.tsx +++ b/packages/app-desktop/gui/KeymapConfig/KeymapConfigScreen.tsx @@ -10,7 +10,7 @@ import styles_ from './styles'; import { _ } from '@joplin/lib/locale'; const bridge = require('electron').remote.require('./bridge').default; -const shim = require('@joplin/lib/shim').default; +import shim from '@joplin/lib/shim'; const keymapService = KeymapService.instance(); diff --git a/packages/app-desktop/gui/MainScreen/MainScreen.tsx b/packages/app-desktop/gui/MainScreen/MainScreen.tsx index 7bdf18a45..b3c7daf03 100644 --- a/packages/app-desktop/gui/MainScreen/MainScreen.tsx +++ b/packages/app-desktop/gui/MainScreen/MainScreen.tsx @@ -34,7 +34,7 @@ const { connect } = require('react-redux'); const { PromptDialog } = require('../PromptDialog.min.js'); const NotePropertiesDialog = require('../NotePropertiesDialog.min.js'); const PluginManager = require('@joplin/lib/services/PluginManager'); -const EncryptionService = require('@joplin/lib/services/EncryptionService'); +import EncryptionService from '@joplin/lib/services/EncryptionService'; const ipcRenderer = require('electron').ipcRenderer; interface LayerModalState { diff --git a/packages/app-desktop/gui/MainScreen/commands/editAlarm.ts b/packages/app-desktop/gui/MainScreen/commands/editAlarm.ts index 02c523065..40cff368a 100644 --- a/packages/app-desktop/gui/MainScreen/commands/editAlarm.ts +++ b/packages/app-desktop/gui/MainScreen/commands/editAlarm.ts @@ -2,8 +2,8 @@ import { CommandRuntime, CommandDeclaration, CommandContext } from '@joplin/lib/ import eventManager from '@joplin/lib/eventManager'; import { _ } from '@joplin/lib/locale'; import { stateUtils } from '@joplin/lib/reducer'; -const Note = require('@joplin/lib/models/Note'); -const time = require('@joplin/lib/time').default; +import Note from '@joplin/lib/models/Note'; +import time from '@joplin/lib/time'; export const declaration: CommandDeclaration = { name: 'editAlarm', diff --git a/packages/app-desktop/gui/MainScreen/commands/exportPdf.ts b/packages/app-desktop/gui/MainScreen/commands/exportPdf.ts index 58a62a080..5894a1f81 100644 --- a/packages/app-desktop/gui/MainScreen/commands/exportPdf.ts +++ b/packages/app-desktop/gui/MainScreen/commands/exportPdf.ts @@ -2,7 +2,7 @@ import { CommandRuntime, CommandDeclaration, CommandContext } from '@joplin/lib/ import shim from '@joplin/lib/shim'; import InteropServiceHelper from '../../../InteropServiceHelper'; import { _ } from '@joplin/lib/locale'; -const Note = require('@joplin/lib/models/Note'); +import Note from '@joplin/lib/models/Note'; const bridge = require('electron').remote.require('./bridge').default; export const declaration: CommandDeclaration = { diff --git a/packages/app-desktop/gui/MainScreen/commands/moveToFolder.ts b/packages/app-desktop/gui/MainScreen/commands/moveToFolder.ts index ec85179ad..637cd1ad4 100644 --- a/packages/app-desktop/gui/MainScreen/commands/moveToFolder.ts +++ b/packages/app-desktop/gui/MainScreen/commands/moveToFolder.ts @@ -1,7 +1,7 @@ import { CommandRuntime, CommandDeclaration, CommandContext } from '@joplin/lib/services/CommandService'; import { _ } from '@joplin/lib/locale'; -const Folder = require('@joplin/lib/models/Folder'); -const Note = require('@joplin/lib/models/Note'); +import Folder from '@joplin/lib/models/Folder'; +import Note from '@joplin/lib/models/Note'; export const declaration: CommandDeclaration = { name: 'moveToFolder', diff --git a/packages/app-desktop/gui/MainScreen/commands/newFolder.ts b/packages/app-desktop/gui/MainScreen/commands/newFolder.ts index 14aff89b3..05f2ba806 100644 --- a/packages/app-desktop/gui/MainScreen/commands/newFolder.ts +++ b/packages/app-desktop/gui/MainScreen/commands/newFolder.ts @@ -1,6 +1,6 @@ import { CommandContext, CommandDeclaration, CommandRuntime } from '@joplin/lib/services/CommandService'; import { _ } from '@joplin/lib/locale'; -const Folder = require('@joplin/lib/models/Folder'); +import Folder from '@joplin/lib/models/Folder'; const bridge = require('electron').remote.require('./bridge').default; export const declaration: CommandDeclaration = { diff --git a/packages/app-desktop/gui/MainScreen/commands/newNote.ts b/packages/app-desktop/gui/MainScreen/commands/newNote.ts index 64bc23036..278d34852 100644 --- a/packages/app-desktop/gui/MainScreen/commands/newNote.ts +++ b/packages/app-desktop/gui/MainScreen/commands/newNote.ts @@ -1,7 +1,7 @@ import { utils, CommandRuntime, CommandDeclaration, CommandContext } from '@joplin/lib/services/CommandService'; import { _ } from '@joplin/lib/locale'; -const Setting = require('@joplin/lib/models/Setting').default; -const Note = require('@joplin/lib/models/Note'); +import Setting from '@joplin/lib/models/Setting'; +import Note from '@joplin/lib/models/Note'; const TemplateUtils = require('@joplin/lib/TemplateUtils'); export const declaration: CommandDeclaration = { diff --git a/packages/app-desktop/gui/MainScreen/commands/openNote.ts b/packages/app-desktop/gui/MainScreen/commands/openNote.ts index 77447ba91..29a42f8e6 100644 --- a/packages/app-desktop/gui/MainScreen/commands/openNote.ts +++ b/packages/app-desktop/gui/MainScreen/commands/openNote.ts @@ -1,6 +1,6 @@ import { CommandRuntime, CommandDeclaration, CommandContext } from '@joplin/lib/services/CommandService'; -const Note = require('@joplin/lib/models/Note'); -const Folder = require('@joplin/lib/models/Folder'); +import Note from '@joplin/lib/models/Note'; +import Folder from '@joplin/lib/models/Folder'; export const declaration: CommandDeclaration = { name: 'openNote', diff --git a/packages/app-desktop/gui/MainScreen/commands/renameFolder.ts b/packages/app-desktop/gui/MainScreen/commands/renameFolder.ts index f4e996229..e34e259c5 100644 --- a/packages/app-desktop/gui/MainScreen/commands/renameFolder.ts +++ b/packages/app-desktop/gui/MainScreen/commands/renameFolder.ts @@ -1,6 +1,6 @@ import { CommandRuntime, CommandDeclaration, CommandContext } from '@joplin/lib/services/CommandService'; import { _ } from '@joplin/lib/locale'; -const Folder = require('@joplin/lib/models/Folder'); +import Folder from '@joplin/lib/models/Folder'; const bridge = require('electron').remote.require('./bridge').default; export const declaration: CommandDeclaration = { diff --git a/packages/app-desktop/gui/MainScreen/commands/renameTag.ts b/packages/app-desktop/gui/MainScreen/commands/renameTag.ts index 9741e150e..bec776025 100644 --- a/packages/app-desktop/gui/MainScreen/commands/renameTag.ts +++ b/packages/app-desktop/gui/MainScreen/commands/renameTag.ts @@ -1,6 +1,6 @@ import { CommandRuntime, CommandDeclaration, CommandContext } from '@joplin/lib/services/CommandService'; import { _ } from '@joplin/lib/locale'; -const Tag = require('@joplin/lib/models/Tag'); +import Tag from '@joplin/lib/models/Tag'; const bridge = require('electron').remote.require('./bridge').default; export const declaration: CommandDeclaration = { diff --git a/packages/app-desktop/gui/MainScreen/commands/setTags.ts b/packages/app-desktop/gui/MainScreen/commands/setTags.ts index 053ea1877..494bf1311 100644 --- a/packages/app-desktop/gui/MainScreen/commands/setTags.ts +++ b/packages/app-desktop/gui/MainScreen/commands/setTags.ts @@ -1,6 +1,6 @@ import { CommandRuntime, CommandDeclaration, CommandContext } from '@joplin/lib/services/CommandService'; import { _ } from '@joplin/lib/locale'; -const Tag = require('@joplin/lib/models/Tag'); +import Tag from '@joplin/lib/models/Tag'; export const declaration: CommandDeclaration = { name: 'setTags', diff --git a/packages/app-desktop/gui/MainScreen/commands/showNoteContentProperties.ts b/packages/app-desktop/gui/MainScreen/commands/showNoteContentProperties.ts index 20812dc17..61b0a0cd8 100644 --- a/packages/app-desktop/gui/MainScreen/commands/showNoteContentProperties.ts +++ b/packages/app-desktop/gui/MainScreen/commands/showNoteContentProperties.ts @@ -1,7 +1,7 @@ import { CommandRuntime, CommandDeclaration, CommandContext } from '@joplin/lib/services/CommandService'; import { _ } from '@joplin/lib/locale'; import { stateUtils } from '@joplin/lib/reducer'; -const Note = require('@joplin/lib/models/Note'); +import Note from '@joplin/lib/models/Note'; export const declaration: CommandDeclaration = { name: 'showNoteContentProperties', diff --git a/packages/app-desktop/gui/NoteContentPropertiesDialog.tsx b/packages/app-desktop/gui/NoteContentPropertiesDialog.tsx index 08805ffaf..7f37fe737 100644 --- a/packages/app-desktop/gui/NoteContentPropertiesDialog.tsx +++ b/packages/app-desktop/gui/NoteContentPropertiesDialog.tsx @@ -4,7 +4,7 @@ import { _ } from '@joplin/lib/locale'; const { themeStyle } = require('@joplin/lib/theme'); const DialogButtonRow = require('./DialogButtonRow.min'); const Countable = require('countable'); -const markupLanguageUtils = require('@joplin/lib/markupLanguageUtils').default; +import markupLanguageUtils from '@joplin/lib/markupLanguageUtils'; interface NoteContentPropertiesDialogProps { themeId: number; diff --git a/packages/app-desktop/gui/NoteEditor/NoteBody/CodeMirror/CodeMirror.tsx b/packages/app-desktop/gui/NoteEditor/NoteBody/CodeMirror/CodeMirror.tsx index 66a567198..84fac7769 100644 --- a/packages/app-desktop/gui/NoteEditor/NoteBody/CodeMirror/CodeMirror.tsx +++ b/packages/app-desktop/gui/NoteEditor/NoteBody/CodeMirror/CodeMirror.tsx @@ -25,8 +25,7 @@ import { ThemeAppearance } from '@joplin/lib/themes/type'; import SpellCheckerService from '@joplin/lib/services/spellChecker/SpellCheckerService'; import dialogs from '../../../dialogs'; import convertToScreenCoordinates from '../../../utils/convertToScreenCoordinates'; - -const Note = require('@joplin/lib/models/Note.js'); +import { MarkupToHtml } from '@joplin/renderer'; const { clipboard } = require('electron'); const shared = require('@joplin/lib/components/shared/note-screen-shared.js'); const Menu = bridge().Menu; @@ -301,7 +300,7 @@ function CodeMirror(props: NoteBodyEditorProps, ref: any) { element.id = script.id; element.onload = () => { - resolve(); + resolve(null); }; document.getElementsByTagName('head')[0].appendChild(element); @@ -700,7 +699,7 @@ function CodeMirror(props: NoteBodyEditorProps, ref: any) { value={props.content} searchMarkers={props.searchMarkers} ref={editorRef} - mode={props.contentMarkupLanguage === Note.MARKUP_LANGUAGE_HTML ? 'xml' : 'joplin-markdown'} + mode={props.contentMarkupLanguage === MarkupToHtml.MARKUP_LANGUAGE_HTML ? 'xml' : 'joplin-markdown'} codeMirrorTheme={styles.editor.codeMirrorTheme} style={styles.editor} readOnly={props.visiblePanes.indexOf('editor') < 0} diff --git a/packages/app-desktop/gui/NoteEditor/NoteBody/CodeMirror/utils/useListIdent.ts b/packages/app-desktop/gui/NoteEditor/NoteBody/CodeMirror/utils/useListIdent.ts index 4006ddf4f..1f3c19303 100644 --- a/packages/app-desktop/gui/NoteEditor/NoteBody/CodeMirror/utils/useListIdent.ts +++ b/packages/app-desktop/gui/NoteEditor/NoteBody/CodeMirror/utils/useListIdent.ts @@ -1,4 +1,4 @@ -const { isListItem, isEmptyListItem, extractListToken, olLineNumber } = require('@joplin/lib/markdownUtils').default; +import markdownUtils from '@joplin/lib/markdownUtils'; // Markdown list indentation. // If the current line starts with `markup.list` token, @@ -21,22 +21,22 @@ export default function useListIdent(CodeMirror: any) { } function newListToken(cm: any, line: number) { - const currentToken = extractListToken(cm.getLine(line)); + const currentToken = markdownUtils.extractListToken(cm.getLine(line)); const indentLevel = getIndentLevel(cm, line); while (--line > 0) { const currentLine = cm.getLine(line); - if (!isListItem(currentLine)) return currentToken; + if (!markdownUtils.isListItem(currentLine)) return currentToken; const indent = getIndentLevel(cm, line); if (indent < indentLevel - 1) return currentToken; if (indent === indentLevel - 1) { - if (olLineNumber(currentLine)) { - return `${olLineNumber(currentLine) + 1}. `; + if (markdownUtils.olLineNumber(currentLine)) { + return `${markdownUtils.olLineNumber(currentLine) + 1}. `; } - const token = extractListToken(currentLine); + const token = markdownUtils.extractListToken(currentLine); if (token.match(/x/)) { return '- [ ] '; } @@ -50,7 +50,7 @@ export default function useListIdent(CodeMirror: any) { // Gets the character coordinates of the start and end of a list token function getListSpan(listTokens: any, line: string) { let start = listTokens[0].start; - const token = extractListToken(line); + const token = markdownUtils.extractListToken(line); if (listTokens.length > 1 && listTokens[0].string.match(/^\s/)) { start = listTokens[1].start; @@ -77,10 +77,10 @@ export default function useListIdent(CodeMirror: any) { // this is an edge case for users because there is no clear intended behavior // if the use multicursor with a mix of selected and not selected break; - } else if (!isListItem(line) || !isEmptyListItem(line)) { + } else if (!markdownUtils.isListItem(line) || !markdownUtils.isEmptyListItem(line)) { cm.replaceRange('\t', anchor, head); } else { - if (olLineNumber(line)) { + if (markdownUtils.olLineNumber(line)) { const tokens = cm.getLineTokens(anchor.line); const { start, end } = getListSpan(tokens, line); // Resets numbered list to 1. @@ -111,7 +111,7 @@ export default function useListIdent(CodeMirror: any) { // this is an edge case for users because there is no clear intended behavior // if the use multicursor with a mix of selected and not selected break; - } else if (!isListItem(line) || !isEmptyListItem(line)) { + } else if (!markdownUtils.isListItem(line) || !markdownUtils.isEmptyListItem(line)) { cm.indentLine(anchor.line, 'subtract'); } else { const newToken = newListToken(cm, anchor.line); @@ -156,7 +156,7 @@ export default function useListIdent(CodeMirror: any) { if (ranges.length === 1) { const line = cm.getLine(anchor.line); - if (isEmptyListItem(line)) { + if (markdownUtils.isEmptyListItem(line)) { const tokens = cm.getLineTokens(anchor.line); // A empty list item with an indent will have whitespace as the first token if (tokens.length > 1 && tokens[0].string.match(/^\s/)) { diff --git a/packages/app-desktop/gui/NoteEditor/NoteBody/TinyMCE/TinyMCE.tsx b/packages/app-desktop/gui/NoteEditor/NoteBody/TinyMCE/TinyMCE.tsx index 31e2187dd..adbf3d1e1 100644 --- a/packages/app-desktop/gui/NoteEditor/NoteBody/TinyMCE/TinyMCE.tsx +++ b/packages/app-desktop/gui/NoteEditor/NoteBody/TinyMCE/TinyMCE.tsx @@ -17,7 +17,7 @@ import shim from '@joplin/lib/shim'; const { MarkupToHtml } = require('@joplin/renderer'); const taboverride = require('taboverride'); const { reg } = require('@joplin/lib/registry.js'); -const BaseItem = require('@joplin/lib/models/BaseItem'); +import BaseItem from '@joplin/lib/models/BaseItem'; const { themeStyle } = require('@joplin/lib/theme'); const { clipboard } = require('electron'); const supportedLocales = require('./supportedLocales'); diff --git a/packages/app-desktop/gui/NoteEditor/NoteBody/TinyMCE/utils/useContextMenu.ts b/packages/app-desktop/gui/NoteEditor/NoteBody/TinyMCE/utils/useContextMenu.ts index 4ad661e19..38201fc23 100644 --- a/packages/app-desktop/gui/NoteEditor/NoteBody/TinyMCE/utils/useContextMenu.ts +++ b/packages/app-desktop/gui/NoteEditor/NoteBody/TinyMCE/utils/useContextMenu.ts @@ -9,7 +9,7 @@ import CommandService from '@joplin/lib/services/CommandService'; import convertToScreenCoordinates from '../../../../utils/convertToScreenCoordinates'; import Setting from '@joplin/lib/models/Setting'; -const Resource = require('@joplin/lib/models/Resource'); +import Resource from '@joplin/lib/models/Resource'; const menuUtils = new MenuUtils(CommandService.instance()); diff --git a/packages/app-desktop/gui/NoteEditor/NoteEditor.tsx b/packages/app-desktop/gui/NoteEditor/NoteEditor.tsx index 430e43908..4fd0e3ed6 100644 --- a/packages/app-desktop/gui/NoteEditor/NoteEditor.tsx +++ b/packages/app-desktop/gui/NoteEditor/NoteEditor.tsx @@ -35,8 +35,8 @@ const { themeStyle } = require('@joplin/lib/theme'); const { substrWithEllipsis } = require('@joplin/lib/string-utils'); const NoteSearchBar = require('../NoteSearchBar.min.js'); const { reg } = require('@joplin/lib/registry.js'); -const Note = require('@joplin/lib/models/Note.js'); -const Folder = require('@joplin/lib/models/Folder.js'); +import Note from '@joplin/lib/models/Note'; +import Folder from '@joplin/lib/models/Folder'; const bridge = require('electron').remote.require('./bridge').default; const NoteRevisionViewer = require('../NoteRevisionViewer.min'); diff --git a/packages/app-desktop/gui/NoteEditor/utils/contextMenu.ts b/packages/app-desktop/gui/NoteEditor/utils/contextMenu.ts index 722a236bf..f65048e53 100644 --- a/packages/app-desktop/gui/NoteEditor/utils/contextMenu.ts +++ b/packages/app-desktop/gui/NoteEditor/utils/contextMenu.ts @@ -4,7 +4,7 @@ import { _ } from '@joplin/lib/locale'; const bridge = require('electron').remote.require('./bridge').default; const Menu = bridge().Menu; const MenuItem = bridge().MenuItem; -const Resource = require('@joplin/lib/models/Resource.js'); +import Resource from '@joplin/lib/models/Resource'; const fs = require('fs-extra'); const { clipboard } = require('electron'); const { toSystemSlashes } = require('@joplin/lib/path-utils'); diff --git a/packages/app-desktop/gui/NoteEditor/utils/index.ts b/packages/app-desktop/gui/NoteEditor/utils/index.ts index ec6381856..c5eda3ada 100644 --- a/packages/app-desktop/gui/NoteEditor/utils/index.ts +++ b/packages/app-desktop/gui/NoteEditor/utils/index.ts @@ -1,7 +1,7 @@ import { FormNote } from './types'; const HtmlToMd = require('@joplin/lib/HtmlToMd'); -const Note = require('@joplin/lib/models/Note'); +import Note from '@joplin/lib/models/Note'; const { MarkupToHtml } = require('@joplin/renderer'); export async function htmlToMarkdown(markupLanguage: number, html: string, originalCss: string): Promise { diff --git a/packages/app-desktop/gui/NoteEditor/utils/resourceHandling.ts b/packages/app-desktop/gui/NoteEditor/utils/resourceHandling.ts index a39dc451a..07c8d6eeb 100644 --- a/packages/app-desktop/gui/NoteEditor/utils/resourceHandling.ts +++ b/packages/app-desktop/gui/NoteEditor/utils/resourceHandling.ts @@ -1,10 +1,10 @@ import shim from '@joplin/lib/shim'; -const Setting = require('@joplin/lib/models/Setting').default; -const Note = require('@joplin/lib/models/Note.js'); -const BaseModel = require('@joplin/lib/BaseModel').default; -const Resource = require('@joplin/lib/models/Resource.js'); +import Setting from '@joplin/lib/models/Setting'; +import Note from '@joplin/lib/models/Note'; +import BaseModel from '@joplin/lib/BaseModel'; +import Resource from '@joplin/lib/models/Resource'; const bridge = require('electron').remote.require('./bridge').default; -const ResourceFetcher = require('@joplin/lib/services/ResourceFetcher.js'); +import ResourceFetcher from '@joplin/lib/services/ResourceFetcher'; const { reg } = require('@joplin/lib/registry.js'); const joplinRendererUtils = require('@joplin/renderer').utils; const { clipboard } = require('electron'); diff --git a/packages/app-desktop/gui/NoteEditor/utils/useDropHandler.ts b/packages/app-desktop/gui/NoteEditor/utils/useDropHandler.ts index 5c7f4e471..bb5fccf91 100644 --- a/packages/app-desktop/gui/NoteEditor/utils/useDropHandler.ts +++ b/packages/app-desktop/gui/NoteEditor/utils/useDropHandler.ts @@ -1,5 +1,5 @@ import { useCallback } from 'react'; -const Note = require('@joplin/lib/models/Note.js'); +import Note from '@joplin/lib/models/Note'; interface HookDependencies { editorRef: any; diff --git a/packages/app-desktop/gui/NoteEditor/utils/useFolder.ts b/packages/app-desktop/gui/NoteEditor/utils/useFolder.ts index db448460c..31ac3076a 100644 --- a/packages/app-desktop/gui/NoteEditor/utils/useFolder.ts +++ b/packages/app-desktop/gui/NoteEditor/utils/useFolder.ts @@ -1,5 +1,5 @@ import { useState, useEffect } from 'react'; -const Folder = require('@joplin/lib/models/Folder'); +import Folder from '@joplin/lib/models/Folder'; interface HookDependencies { folderId: string; diff --git a/packages/app-desktop/gui/NoteEditor/utils/useFormNote.ts b/packages/app-desktop/gui/NoteEditor/utils/useFormNote.ts index 931179070..38eb11469 100644 --- a/packages/app-desktop/gui/NoteEditor/utils/useFormNote.ts +++ b/packages/app-desktop/gui/NoteEditor/utils/useFormNote.ts @@ -9,10 +9,10 @@ import usePrevious from '../../hooks/usePrevious'; import ResourceEditWatcher from '@joplin/lib/services/ResourceEditWatcher/index'; const { MarkupToHtml } = require('@joplin/renderer'); -const Note = require('@joplin/lib/models/Note'); +import Note from '@joplin/lib/models/Note'; const { reg } = require('@joplin/lib/registry.js'); -const ResourceFetcher = require('@joplin/lib/services/ResourceFetcher.js'); -const DecryptionWorker = require('@joplin/lib/services/DecryptionWorker.js'); +import ResourceFetcher from '@joplin/lib/services/ResourceFetcher'; +import DecryptionWorker from '@joplin/lib/services/DecryptionWorker'; export interface OnLoadEvent { formNote: FormNote; diff --git a/packages/app-desktop/gui/NoteEditor/utils/useMarkupToHtml.ts b/packages/app-desktop/gui/NoteEditor/utils/useMarkupToHtml.ts index a56829052..361e39375 100644 --- a/packages/app-desktop/gui/NoteEditor/utils/useMarkupToHtml.ts +++ b/packages/app-desktop/gui/NoteEditor/utils/useMarkupToHtml.ts @@ -5,7 +5,7 @@ import markupLanguageUtils from '@joplin/lib/markupLanguageUtils'; import Setting from '@joplin/lib/models/Setting'; const { themeStyle } = require('@joplin/lib/theme'); -const Note = require('@joplin/lib/models/Note'); +import Note from '@joplin/lib/models/Note'; interface HookDependencies { themeId: number; diff --git a/packages/app-desktop/gui/NoteEditor/utils/useMessageHandler.ts b/packages/app-desktop/gui/NoteEditor/utils/useMessageHandler.ts index 0437c55da..f21bfb18f 100644 --- a/packages/app-desktop/gui/NoteEditor/utils/useMessageHandler.ts +++ b/packages/app-desktop/gui/NoteEditor/utils/useMessageHandler.ts @@ -5,13 +5,13 @@ import ResourceEditWatcher from '@joplin/lib/services/ResourceEditWatcher/index' import { _ } from '@joplin/lib/locale'; import CommandService from '@joplin/lib/services/CommandService'; import PostMessageService from '@joplin/lib/services/PostMessageService'; -const BaseItem = require('@joplin/lib/models/BaseItem'); -const BaseModel = require('@joplin/lib/BaseModel').default; -const Resource = require('@joplin/lib/models/Resource.js'); +import BaseItem from '@joplin/lib/models/BaseItem'; +import BaseModel from '@joplin/lib/BaseModel'; +import Resource from '@joplin/lib/models/Resource'; const bridge = require('electron').remote.require('./bridge').default; const { urlDecode } = require('@joplin/lib/string-utils'); const urlUtils = require('@joplin/lib/urlUtils'); -const ResourceFetcher = require('@joplin/lib/services/ResourceFetcher.js'); +import ResourceFetcher from '@joplin/lib/services/ResourceFetcher'; const { reg } = require('@joplin/lib/registry.js'); export default function useMessageHandler(scrollWhenReady: any, setScrollWhenReady: Function, editorRef: any, setLocalSearchResultCount: Function, dispatch: Function, formNote: FormNote) { @@ -37,7 +37,7 @@ export default function useMessageHandler(scrollWhenReady: any, setScrollWhenRea } else if (msg.indexOf('markForDownload:') === 0) { const s = msg.split(':'); if (s.length < 2) throw new Error(`Invalid message: ${msg}`); - ResourceFetcher.instance().markForDownload(s[1]); + void ResourceFetcher.instance().markForDownload(s[1]); } else if (msg === 'contextMenu') { const menu = await contextMenu({ itemType: arg0 && arg0.type, diff --git a/packages/app-desktop/gui/NoteEditor/utils/useWindowCommandHandler.ts b/packages/app-desktop/gui/NoteEditor/utils/useWindowCommandHandler.ts index e06d7ccd0..54d4a6ec8 100644 --- a/packages/app-desktop/gui/NoteEditor/utils/useWindowCommandHandler.ts +++ b/packages/app-desktop/gui/NoteEditor/utils/useWindowCommandHandler.ts @@ -1,7 +1,7 @@ import { useEffect } from 'react'; import { FormNote, ScrollOptionTypes } from './types'; import CommandService, { CommandDeclaration, CommandRuntime, CommandContext } from '@joplin/lib/services/CommandService'; -const time = require('@joplin/lib/time').default; +import time from '@joplin/lib/time'; const { reg } = require('@joplin/lib/registry.js'); const commandsWithDependencies = [ diff --git a/packages/app-desktop/gui/NoteList/NoteList.tsx b/packages/app-desktop/gui/NoteList/NoteList.tsx index d1e40ba04..cf7ff2e8c 100644 --- a/packages/app-desktop/gui/NoteList/NoteList.tsx +++ b/packages/app-desktop/gui/NoteList/NoteList.tsx @@ -7,7 +7,7 @@ import BaseModel from '@joplin/lib/BaseModel'; import bridge from '../../services/bridge'; import Setting from '@joplin/lib/models/Setting'; import NoteListItem from '../NoteListItem'; -import CommandService from '@joplin/lib/services/CommandService.js'; +import CommandService from '@joplin/lib/services/CommandService'; import shim from '@joplin/lib/shim'; import styled from 'styled-components'; import { themeStyle } from '@joplin/lib/theme'; @@ -15,8 +15,8 @@ const React = require('react'); const { ItemList } = require('../ItemList.min.js'); const { connect } = require('react-redux'); -const Note = require('@joplin/lib/models/Note'); -const Folder = require('@joplin/lib/models/Folder'); +import Note from '@joplin/lib/models/Note'; +import Folder from '@joplin/lib/models/Folder'; const commands = [ require('./commands/focusElementNoteList'), @@ -186,7 +186,7 @@ class NoteListComponent extends React.Component { const targetNoteIndex = this.dragTargetNoteIndex_(event); const noteIds = JSON.parse(dt.getData('text/x-jop-note-ids')); - Note.insertNotesAt(this.props.selectedFolderId, noteIds, targetNoteIndex); + void Note.insertNotesAt(this.props.selectedFolderId, noteIds, targetNoteIndex); } diff --git a/packages/app-desktop/gui/NoteListItem.tsx b/packages/app-desktop/gui/NoteListItem.tsx index d770e4237..4517ea207 100644 --- a/packages/app-desktop/gui/NoteListItem.tsx +++ b/packages/app-desktop/gui/NoteListItem.tsx @@ -3,7 +3,7 @@ import { useRef, forwardRef, useImperativeHandle, useCallback } from 'react'; const { themeStyle } = require('@joplin/lib/theme'); const Mark = require('mark.js/dist/mark.min.js'); const markJsUtils = require('@joplin/lib/markJsUtils'); -const Note = require('@joplin/lib/models/Note'); +import Note from '@joplin/lib/models/Note'; const { replaceRegexDiacritics, pregQuote } = require('@joplin/lib/string-utils'); const styled = require('styled-components').default; diff --git a/packages/app-desktop/gui/NotePropertiesDialog.jsx b/packages/app-desktop/gui/NotePropertiesDialog.jsx index 0d5983019..ceae53c9f 100644 --- a/packages/app-desktop/gui/NotePropertiesDialog.jsx +++ b/packages/app-desktop/gui/NotePropertiesDialog.jsx @@ -4,7 +4,7 @@ const { themeStyle } = require('@joplin/lib/theme'); const time = require('@joplin/lib/time').default; const DialogButtonRow = require('./DialogButtonRow.min'); const Datetime = require('react-datetime'); -const Note = require('@joplin/lib/models/Note'); +const Note = require('@joplin/lib/models/Note').default; const formatcoords = require('formatcoords'); const bridge = require('electron').remote.require('./bridge').default; const shim = require('@joplin/lib/shim').default; diff --git a/packages/app-desktop/gui/NoteRevisionViewer.jsx b/packages/app-desktop/gui/NoteRevisionViewer.jsx index b2bfb38b6..c446eb40d 100644 --- a/packages/app-desktop/gui/NoteRevisionViewer.jsx +++ b/packages/app-desktop/gui/NoteRevisionViewer.jsx @@ -5,10 +5,10 @@ const { _ } = require('@joplin/lib/locale'); const NoteTextViewer = require('./NoteTextViewer').default; const HelpButton = require('./HelpButton.min'); const BaseModel = require('@joplin/lib/BaseModel').default; -const Revision = require('@joplin/lib/models/Revision'); +const Revision = require('@joplin/lib/models/Revision').default; const urlUtils = require('@joplin/lib/urlUtils'); const Setting = require('@joplin/lib/models/Setting').default; -const RevisionService = require('@joplin/lib/services/RevisionService'); +const RevisionService = require('@joplin/lib/services/RevisionService').default; const shared = require('@joplin/lib/components/shared/note-screen-shared.js'); const { MarkupToHtml } = require('@joplin/renderer'); const time = require('@joplin/lib/time').default; diff --git a/packages/app-desktop/gui/OneDriveLoginScreen.tsx b/packages/app-desktop/gui/OneDriveLoginScreen.tsx index c404f5cfa..524f42f29 100644 --- a/packages/app-desktop/gui/OneDriveLoginScreen.tsx +++ b/packages/app-desktop/gui/OneDriveLoginScreen.tsx @@ -4,7 +4,7 @@ import { _ } from '@joplin/lib/locale'; const { connect } = require('react-redux'); const { reg } = require('@joplin/lib/registry.js'); -const Setting = require('@joplin/lib/models/Setting').default; +import Setting from '@joplin/lib/models/Setting'; const bridge = require('electron').remote.require('./bridge').default; const { themeStyle } = require('@joplin/lib/theme'); const { OneDriveApiNodeUtils } = require('@joplin/lib/onedrive-api-node-utils.js'); diff --git a/packages/app-desktop/gui/ResourceScreen.tsx b/packages/app-desktop/gui/ResourceScreen.tsx index b0d20552a..ec47eb134 100644 --- a/packages/app-desktop/gui/ResourceScreen.tsx +++ b/packages/app-desktop/gui/ResourceScreen.tsx @@ -6,7 +6,7 @@ const { connect } = require('react-redux'); const { themeStyle } = require('@joplin/lib/theme'); const bridge = require('electron').remote.require('./bridge').default; const prettyBytes = require('pretty-bytes'); -const Resource = require('@joplin/lib/models/Resource.js'); +import Resource from '@joplin/lib/models/Resource'; interface Style { width: number; diff --git a/packages/app-desktop/gui/Root.tsx b/packages/app-desktop/gui/Root.tsx index b1c2a7b77..ee7fc054d 100644 --- a/packages/app-desktop/gui/Root.tsx +++ b/packages/app-desktop/gui/Root.tsx @@ -13,8 +13,8 @@ const React = require('react'); const { render } = require('react-dom'); const { connect, Provider } = require('react-redux'); -const Setting = require('@joplin/lib/models/Setting').default; -const shim = require('@joplin/lib/shim').default; +import Setting from '@joplin/lib/models/Setting'; +import shim from '@joplin/lib/shim'; const { ImportScreen } = require('./ImportScreen.min.js'); const { ResourceScreen } = require('./ResourceScreen.js'); const { Navigator } = require('./Navigator.min.js'); diff --git a/packages/app-desktop/gui/Root_UpgradeSyncTarget.tsx b/packages/app-desktop/gui/Root_UpgradeSyncTarget.tsx index 323974325..192ea6b8a 100644 --- a/packages/app-desktop/gui/Root_UpgradeSyncTarget.tsx +++ b/packages/app-desktop/gui/Root_UpgradeSyncTarget.tsx @@ -4,7 +4,7 @@ import useSyncTargetUpgrade, { SyncTargetUpgradeResult } from '@joplin/lib/servi const { render } = require('react-dom'); const ipcRenderer = require('electron').ipcRenderer; -const Setting = require('@joplin/lib/models/Setting').default; +import Setting from '@joplin/lib/models/Setting'; const bridge = require('electron').remote.require('./bridge').default; function useAppCloseHandler(upgradeResult: SyncTargetUpgradeResult) { diff --git a/packages/app-desktop/gui/SearchBar/SearchBar.tsx b/packages/app-desktop/gui/SearchBar/SearchBar.tsx index fe8ec951f..232b324b2 100644 --- a/packages/app-desktop/gui/SearchBar/SearchBar.tsx +++ b/packages/app-desktop/gui/SearchBar/SearchBar.tsx @@ -6,7 +6,7 @@ import { stateUtils } from '@joplin/lib/reducer'; import BaseModel from '@joplin/lib/BaseModel'; import uuid from '@joplin/lib/uuid'; const { connect } = require('react-redux'); -const Note = require('@joplin/lib/models/Note'); +import Note from '@joplin/lib/models/Note'; const debounce = require('debounce'); const styled = require('styled-components').default; diff --git a/packages/app-desktop/gui/ShareNoteDialog.tsx b/packages/app-desktop/gui/ShareNoteDialog.tsx index 13fa92952..068bb2ded 100644 --- a/packages/app-desktop/gui/ShareNoteDialog.tsx +++ b/packages/app-desktop/gui/ShareNoteDialog.tsx @@ -5,9 +5,9 @@ import JoplinServerApi from '@joplin/lib/JoplinServerApi'; import { _, _n } from '@joplin/lib/locale'; const { themeStyle, buildStyle } = require('@joplin/lib/theme'); const DialogButtonRow = require('./DialogButtonRow.min'); -const Note = require('@joplin/lib/models/Note'); -const Setting = require('@joplin/lib/models/Setting').default; -const BaseItem = require('@joplin/lib/models/BaseItem'); +import Note from '@joplin/lib/models/Note'; +import Setting from '@joplin/lib/models/Setting'; +import BaseItem from '@joplin/lib/models/BaseItem'; const { reg } = require('@joplin/lib/registry.js'); const { clipboard } = require('electron'); diff --git a/packages/app-desktop/gui/Sidebar/Sidebar.tsx b/packages/app-desktop/gui/Sidebar/Sidebar.tsx index 9d747ad35..f6ddf93d6 100644 --- a/packages/app-desktop/gui/Sidebar/Sidebar.tsx +++ b/packages/app-desktop/gui/Sidebar/Sidebar.tsx @@ -15,10 +15,10 @@ import { ModelType } from '@joplin/lib/BaseModel'; const { connect } = require('react-redux'); const shared = require('@joplin/lib/components/shared/side-menu-shared.js'); -const BaseModel = require('@joplin/lib/BaseModel').default; -const Folder = require('@joplin/lib/models/Folder.js'); -const Note = require('@joplin/lib/models/Note.js'); -const Tag = require('@joplin/lib/models/Tag.js'); +import BaseModel from '@joplin/lib/BaseModel'; +import Folder from '@joplin/lib/models/Folder'; +import Note from '@joplin/lib/models/Note'; +import Tag from '@joplin/lib/models/Tag'; const { themeStyle } = require('@joplin/lib/theme'); const bridge = require('electron').remote.require('./bridge').default; const Menu = bridge().Menu; diff --git a/packages/app-desktop/gui/StatusScreen/StatusScreen.tsx b/packages/app-desktop/gui/StatusScreen/StatusScreen.tsx index ef2cb0019..26802a229 100644 --- a/packages/app-desktop/gui/StatusScreen/StatusScreen.tsx +++ b/packages/app-desktop/gui/StatusScreen/StatusScreen.tsx @@ -4,10 +4,10 @@ import ButtonBar from '../ConfigScreen/ButtonBar'; import { _ } from '@joplin/lib/locale'; const { connect } = require('react-redux'); -const Setting = require('@joplin/lib/models/Setting').default; +import Setting from '@joplin/lib/models/Setting'; const bridge = require('electron').remote.require('./bridge').default; const { themeStyle } = require('@joplin/lib/theme'); -const { ReportService } = require('@joplin/lib/services/report.js'); +import ReportService from '@joplin/lib/services/ReportService'; const fs = require('fs-extra'); interface Props { diff --git a/packages/app-desktop/gui/utils/NoteListUtils.ts b/packages/app-desktop/gui/utils/NoteListUtils.ts index 2207e141a..709388a18 100644 --- a/packages/app-desktop/gui/utils/NoteListUtils.ts +++ b/packages/app-desktop/gui/utils/NoteListUtils.ts @@ -7,11 +7,11 @@ import InteropServiceHelper from '../../InteropServiceHelper'; import { _ } from '@joplin/lib/locale'; import { MenuItemLocation } from '@joplin/lib/services/plugins/api/types'; -const BaseModel = require('@joplin/lib/BaseModel').default; +import BaseModel from '@joplin/lib/BaseModel'; const bridge = require('electron').remote.require('./bridge').default; const Menu = bridge().Menu; const MenuItem = bridge().MenuItem; -const Note = require('@joplin/lib/models/Note'); +import Note from '@joplin/lib/models/Note'; const { substrWithEllipsis } = require('@joplin/lib/string-utils'); interface ContextMenuProps { diff --git a/packages/app-desktop/main-html.js b/packages/app-desktop/main-html.js index 1c3c0e86a..cb032c654 100644 --- a/packages/app-desktop/main-html.js +++ b/packages/app-desktop/main-html.js @@ -11,20 +11,20 @@ __REACT_DEVTOOLS_GLOBAL_HOOK__ = { }; const app = require('./app').default; -const Folder = require('@joplin/lib/models/Folder.js'); -const Resource = require('@joplin/lib/models/Resource.js'); -const BaseItem = require('@joplin/lib/models/BaseItem.js'); -const Note = require('@joplin/lib/models/Note.js'); -const Tag = require('@joplin/lib/models/Tag.js'); -const NoteTag = require('@joplin/lib/models/NoteTag.js'); -const MasterKey = require('@joplin/lib/models/MasterKey'); +const Folder = require('@joplin/lib/models/Folder').default; +const Resource = require('@joplin/lib/models/Resource').default; +const BaseItem = require('@joplin/lib/models/BaseItem').default; +const Note = require('@joplin/lib/models/Note').default; +const Tag = require('@joplin/lib/models/Tag').default; +const NoteTag = require('@joplin/lib/models/NoteTag').default; +const MasterKey = require('@joplin/lib/models/MasterKey').default; const Setting = require('@joplin/lib/models/Setting').default; -const Revision = require('@joplin/lib/models/Revision.js'); +const Revision = require('@joplin/lib/models/Revision').default; const Logger = require('@joplin/lib/Logger').default; const FsDriverNode = require('@joplin/lib/fs-driver-node').default; const shim = require('@joplin/lib/shim').default; const { shimInit } = require('@joplin/lib/shim-init-node.js'); -const EncryptionService = require('@joplin/lib/services/EncryptionService'); +const EncryptionService = require('@joplin/lib/services/EncryptionService').default; const bridge = require('electron').remote.require('./bridge').default; const { FileApiDriverLocal } = require('@joplin/lib/file-api-driver-local.js'); const React = require('react'); diff --git a/packages/app-desktop/plugins/GotoAnything.tsx b/packages/app-desktop/plugins/GotoAnything.tsx index feaac20e4..45d61cbea 100644 --- a/packages/app-desktop/plugins/GotoAnything.tsx +++ b/packages/app-desktop/plugins/GotoAnything.tsx @@ -7,16 +7,16 @@ import shim from '@joplin/lib/shim'; const { connect } = require('react-redux'); const { _ } = require('@joplin/lib/locale'); const { themeStyle } = require('@joplin/lib/theme'); -const SearchEngine = require('@joplin/lib/services/searchengine/SearchEngine'); -const BaseModel = require('@joplin/lib/BaseModel').default; -const Tag = require('@joplin/lib/models/Tag'); -const Folder = require('@joplin/lib/models/Folder'); -const Note = require('@joplin/lib/models/Note'); +import SearchEngine from '@joplin/lib/services/searchengine/SearchEngine'; +import BaseModel from '@joplin/lib/BaseModel'; +import Tag from '@joplin/lib/models/Tag'; +import Folder from '@joplin/lib/models/Folder'; +import Note from '@joplin/lib/models/Note'; const { ItemList } = require('../gui/ItemList.min'); const HelpButton = require('../gui/HelpButton.min'); const { surroundKeywords, nextWhitespaceIndex, removeDiacritics } = require('@joplin/lib/string-utils.js'); const { mergeOverlappingIntervals } = require('@joplin/lib/ArrayUtils.js'); -const markupLanguageUtils = require('@joplin/lib/markupLanguageUtils').default; +import markupLanguageUtils from '@joplin/lib/markupLanguageUtils'; const PLUGIN_NAME = 'gotoAnything'; diff --git a/packages/app-desktop/services/plugins/hooks/useThemeCss.ts b/packages/app-desktop/services/plugins/hooks/useThemeCss.ts index 4e2c11af5..102a32b24 100644 --- a/packages/app-desktop/services/plugins/hooks/useThemeCss.ts +++ b/packages/app-desktop/services/plugins/hooks/useThemeCss.ts @@ -1,7 +1,7 @@ import { useEffect, useState } from 'react'; import { themeStyle } from '@joplin/lib/theme'; import shim from '@joplin/lib/shim'; -const Setting = require('@joplin/lib/models/Setting').default; +import Setting from '@joplin/lib/models/Setting'; const { camelCaseToDash, formatCssSize } = require('@joplin/lib/string-utils'); interface HookDependencies { diff --git a/packages/app-mobile/PluginAssetsLoader.ts b/packages/app-mobile/PluginAssetsLoader.ts index ab331fe8c..dd005a35d 100644 --- a/packages/app-mobile/PluginAssetsLoader.ts +++ b/packages/app-mobile/PluginAssetsLoader.ts @@ -1,8 +1,8 @@ import shim from '@joplin/lib/shim'; const { dirname } = require('@joplin/lib/path-utils'); -const Setting = require('@joplin/lib/models/Setting').default; +import Setting from '@joplin/lib/models/Setting'; const pluginAssets = require('./pluginAssets/index'); -const KvStore = require('@joplin/lib/services/KvStore').default; +import KvStore from '@joplin/lib/services/KvStore'; export default class PluginAssetsLoader { @@ -49,7 +49,7 @@ export default class PluginAssetsLoader { this.logger().error(error); } - KvStore.instance().setValue('PluginAssetsLoader.lastHash', hash); + await KvStore.instance().setValue('PluginAssetsLoader.lastHash', hash); } } diff --git a/packages/app-mobile/components/BackButtonDialogBox.ts b/packages/app-mobile/components/BackButtonDialogBox.ts index 64799f529..eae80a725 100644 --- a/packages/app-mobile/components/BackButtonDialogBox.ts +++ b/packages/app-mobile/components/BackButtonDialogBox.ts @@ -2,8 +2,8 @@ const { BackButtonService } = require('../services/back-button.js'); const DialogBox = require('react-native-dialogbox').default; export default class BackButtonDialogBox extends DialogBox { - constructor() { - super(); + constructor(props: any) { + super(props); this.backHandler_ = () => { if (this.state.isVisible) { diff --git a/packages/app-mobile/components/CameraView.tsx b/packages/app-mobile/components/CameraView.tsx index cd5435641..0da8f60e5 100644 --- a/packages/app-mobile/components/CameraView.tsx +++ b/packages/app-mobile/components/CameraView.tsx @@ -5,8 +5,8 @@ const { connect } = require('react-redux'); const { View, TouchableOpacity, Text, Dimensions } = require('react-native'); const Icon = require('react-native-vector-icons/Ionicons').default; const { _ } = require('@joplin/lib/locale'); -const shim = require('@joplin/lib/shim').default; -const Setting = require('@joplin/lib/models/Setting').default; +import shim from '@joplin/lib/shim'; +import Setting from '@joplin/lib/models/Setting'; Icon.loadFont(); diff --git a/packages/app-mobile/components/NoteBodyViewer/NoteBodyViewer.tsx b/packages/app-mobile/components/NoteBodyViewer/NoteBodyViewer.tsx index 8178bea8b..415c1b370 100644 --- a/packages/app-mobile/components/NoteBodyViewer/NoteBodyViewer.tsx +++ b/packages/app-mobile/components/NoteBodyViewer/NoteBodyViewer.tsx @@ -9,7 +9,7 @@ const React = require('react'); const { View } = require('react-native'); const { WebView } = require('react-native-webview'); const { themeStyle } = require('../global-style.js'); -const BackButtonDialogBox = require('../BackButtonDialogBox').default; +import BackButtonDialogBox from '../BackButtonDialogBox'; const { reg } = require('@joplin/lib/registry.js'); interface Props { @@ -89,6 +89,8 @@ export default function NoteBodyViewer(props: Props) { // since the WebView package went through many versions it's possible that // the above no longer applies. + const BackButtonDialogBox_ = BackButtonDialogBox as any; + return ( - + ); } diff --git a/packages/app-mobile/components/NoteBodyViewer/hooks/useOnResourceLongPress.ts b/packages/app-mobile/components/NoteBodyViewer/hooks/useOnResourceLongPress.ts index 44d6faccb..64c1bb22b 100644 --- a/packages/app-mobile/components/NoteBodyViewer/hooks/useOnResourceLongPress.ts +++ b/packages/app-mobile/components/NoteBodyViewer/hooks/useOnResourceLongPress.ts @@ -6,7 +6,7 @@ const { ToastAndroid } = require('react-native'); const { _ } = require('@joplin/lib/locale.js'); const { reg } = require('@joplin/lib/registry.js'); const { dialogs } = require('../../../utils/dialogs.js'); -const Resource = require('@joplin/lib/models/Resource.js'); +import Resource from '@joplin/lib/models/Resource'; const Share = require('react-native-share').default; export default function useOnResourceLongPress(onJoplinLinkClick: Function, dialogBoxRef: any) { diff --git a/packages/app-mobile/components/NoteBodyViewer/hooks/useSource.ts b/packages/app-mobile/components/NoteBodyViewer/hooks/useSource.ts index 20ee3c38c..16bb1f95c 100644 --- a/packages/app-mobile/components/NoteBodyViewer/hooks/useSource.ts +++ b/packages/app-mobile/components/NoteBodyViewer/hooks/useSource.ts @@ -2,7 +2,7 @@ import { useEffect, useState, useMemo, useRef } from 'react'; import shim from '@joplin/lib/shim'; import Setting from '@joplin/lib/models/Setting'; const { themeStyle } = require('../../global-style.js'); -const markupLanguageUtils = require('@joplin/lib/markupLanguageUtils').default; +import markupLanguageUtils from '@joplin/lib/markupLanguageUtils'; const { assetsToHeaders } = require('@joplin/renderer'); interface Source { diff --git a/packages/app-mobile/components/SelectDateTimeDialog.tsx b/packages/app-mobile/components/SelectDateTimeDialog.tsx index ec1c34c58..f68fe6b24 100644 --- a/packages/app-mobile/components/SelectDateTimeDialog.tsx +++ b/packages/app-mobile/components/SelectDateTimeDialog.tsx @@ -5,7 +5,7 @@ const { View, Button, Text } = require('react-native'); const PopupDialog = require('react-native-popup-dialog').default; const { DialogTitle, DialogButton } = require('react-native-popup-dialog'); -const time = require('@joplin/lib/time').default; +import time from '@joplin/lib/time'; const DateTimePickerModal = require('react-native-modal-datetime-picker').default; export default class SelectDateTimeDialog extends React.PureComponent { diff --git a/packages/app-mobile/components/action-button.js b/packages/app-mobile/components/action-button.js index ec9d32237..02173dc3b 100644 --- a/packages/app-mobile/components/action-button.js +++ b/packages/app-mobile/components/action-button.js @@ -1,7 +1,7 @@ const React = require('react'); const { StyleSheet } = require('react-native'); -const Note = require('@joplin/lib/models/Note'); +const Note = require('@joplin/lib/models/Note').default; const Icon = require('react-native-vector-icons/Ionicons').default; const ReactNativeActionButton = require('react-native-action-button').default; const { connect } = require('react-redux'); diff --git a/packages/app-mobile/components/note-item.js b/packages/app-mobile/components/note-item.js index 9a61c35eb..c85359900 100644 --- a/packages/app-mobile/components/note-item.js +++ b/packages/app-mobile/components/note-item.js @@ -3,7 +3,7 @@ const Component = React.Component; const { connect } = require('react-redux'); const { Text, TouchableOpacity, View, StyleSheet } = require('react-native'); const { Checkbox } = require('./checkbox.js'); -const Note = require('@joplin/lib/models/Note.js'); +const Note = require('@joplin/lib/models/Note').default; const time = require('@joplin/lib/time').default; const { themeStyle } = require('./global-style.js'); diff --git a/packages/app-mobile/components/screen-header.js b/packages/app-mobile/components/screen-header.js index 406147ca1..4704f9b02 100644 --- a/packages/app-mobile/components/screen-header.js +++ b/packages/app-mobile/components/screen-header.js @@ -4,12 +4,12 @@ const { connect } = require('react-redux'); const { View, Text, StyleSheet, TouchableOpacity, Image, ScrollView, Dimensions } = require('react-native'); const Icon = require('react-native-vector-icons/Ionicons').default; const { BackButtonService } = require('../services/back-button.js'); -const NavService = require('@joplin/lib/services/NavService.js'); +const NavService = require('@joplin/lib/services/NavService').default; const { Menu, MenuOptions, MenuOption, MenuTrigger } = require('react-native-popup-menu'); const { _ } = require('@joplin/lib/locale'); const Setting = require('@joplin/lib/models/Setting').default; -const Note = require('@joplin/lib/models/Note.js'); -const Folder = require('@joplin/lib/models/Folder.js'); +const Note = require('@joplin/lib/models/Note').default; +const Folder = require('@joplin/lib/models/Folder').default; const { themeStyle } = require('./global-style.js'); const { Dropdown } = require('./Dropdown.js'); const { dialogs } = require('../utils/dialogs.js'); diff --git a/packages/app-mobile/components/screens/Note.tsx b/packages/app-mobile/components/screens/Note.tsx index 5143d17ac..177aaac26 100644 --- a/packages/app-mobile/components/screens/Note.tsx +++ b/packages/app-mobile/components/screens/Note.tsx @@ -12,25 +12,25 @@ const { Platform, Keyboard, View, TextInput, StyleSheet, Linking, Image, Share, const { connect } = require('react-redux'); // const { MarkdownEditor } = require('@joplin/lib/../MarkdownEditor/index.js'); const RNFS = require('react-native-fs'); -const Note = require('@joplin/lib/models/Note.js'); -const BaseItem = require('@joplin/lib/models/BaseItem.js'); -const Resource = require('@joplin/lib/models/Resource.js'); -const Folder = require('@joplin/lib/models/Folder.js'); +import Note from '@joplin/lib/models/Note'; +import BaseItem from '@joplin/lib/models/BaseItem'; +import Resource from '@joplin/lib/models/Resource'; +import Folder from '@joplin/lib/models/Folder'; const Clipboard = require('@react-native-community/clipboard').default; const md5 = require('md5'); const { BackButtonService } = require('../../services/back-button.js'); -const NavService = require('@joplin/lib/services/NavService.js'); -const BaseModel = require('@joplin/lib/BaseModel').default; +import NavService from '@joplin/lib/services/NavService'; +import BaseModel from '@joplin/lib/BaseModel'; const { ActionButton } = require('../action-button.js'); const { fileExtension, safeFileExtension } = require('@joplin/lib/path-utils'); const mimeUtils = require('@joplin/lib/mime-utils.js').mime; const { ScreenHeader } = require('../screen-header.js'); const NoteTagsDialog = require('./NoteTagsDialog'); -const time = require('@joplin/lib/time').default; +import time from '@joplin/lib/time'; const { Checkbox } = require('../checkbox.js'); const { _ } = require('@joplin/lib/locale'); const { reg } = require('@joplin/lib/registry.js'); -const ResourceFetcher = require('@joplin/lib/services/ResourceFetcher'); +import ResourceFetcher from '@joplin/lib/services/ResourceFetcher'; const { BaseScreenComponent } = require('../base-screen.js'); const { themeStyle, editorFont } = require('../global-style.js'); const { dialogs } = require('../../utils/dialogs.js'); @@ -39,9 +39,9 @@ const DocumentPicker = require('react-native-document-picker').default; const ImageResizer = require('react-native-image-resizer').default; const shared = require('@joplin/lib/components/shared/note-screen-shared.js'); const ImagePicker = require('react-native-image-picker').default; -const SelectDateTimeDialog = require('../SelectDateTimeDialog').default; -const ShareExtension = require('../../utils/ShareExtension.js').default; -const CameraView = require('../CameraView').default; +import SelectDateTimeDialog from '../SelectDateTimeDialog'; +import ShareExtension from '../../utils/ShareExtension.js'; +import CameraView from '../CameraView'; const urlUtils = require('@joplin/lib/urlUtils'); const emptyArray: any[] = []; @@ -408,7 +408,7 @@ class NoteScreenComponent extends BaseScreenComponent { } onMarkForDownload(event: any) { - ResourceFetcher.instance().markForDownload(event.resourceId); + void ResourceFetcher.instance().markForDownload(event.resourceId); } componentDidUpdate(prevProps: any) { diff --git a/packages/app-mobile/components/screens/NoteTagsDialog.js b/packages/app-mobile/components/screens/NoteTagsDialog.js index 319aee27b..75c22413b 100644 --- a/packages/app-mobile/components/screens/NoteTagsDialog.js +++ b/packages/app-mobile/components/screens/NoteTagsDialog.js @@ -2,7 +2,7 @@ const React = require('react'); const { StyleSheet, View, Text, FlatList, TouchableOpacity, TextInput } = require('react-native'); const { connect } = require('react-redux'); -const Tag = require('@joplin/lib/models/Tag.js'); +const Tag = require('@joplin/lib/models/Tag').default; const { _ } = require('@joplin/lib/locale'); const { themeStyle } = require('../global-style.js'); const Icon = require('react-native-vector-icons/Ionicons').default; diff --git a/packages/app-mobile/components/screens/config.js b/packages/app-mobile/components/screens/config.js index 52f54eafe..4f68c7f06 100644 --- a/packages/app-mobile/components/screens/config.js +++ b/packages/app-mobile/components/screens/config.js @@ -11,12 +11,12 @@ const Setting = require('@joplin/lib/models/Setting').default; const shared = require('@joplin/lib/components/shared/config-shared.js'); const SyncTargetRegistry = require('@joplin/lib/SyncTargetRegistry'); const { reg } = require('@joplin/lib/registry.js'); -const NavService = require('@joplin/lib/services/NavService.js'); +const NavService = require('@joplin/lib/services/NavService').default; const VersionInfo = require('react-native-version-info').default; -const { ReportService } = require('@joplin/lib/services/report.js'); +const ReportService = require('@joplin/lib/services/ReportService').default; const time = require('@joplin/lib/time').default; const shim = require('@joplin/lib/shim').default; -const SearchEngine = require('@joplin/lib/services/searchengine/SearchEngine'); +const SearchEngine = require('@joplin/lib/services/searchengine/SearchEngine').default; const RNFS = require('react-native-fs'); const checkPermissions = require('../../utils/checkPermissions.js').default; diff --git a/packages/app-mobile/components/screens/encryption-config.js b/packages/app-mobile/components/screens/encryption-config.js index d915d2b90..5eb646a34 100644 --- a/packages/app-mobile/components/screens/encryption-config.js +++ b/packages/app-mobile/components/screens/encryption-config.js @@ -1,7 +1,7 @@ const React = require('react'); const { TextInput, TouchableOpacity, Linking, View, StyleSheet, Text, Button, ScrollView } = require('react-native'); -const EncryptionService = require('@joplin/lib/services/EncryptionService'); +const EncryptionService = require('@joplin/lib/services/EncryptionService').default; const { connect } = require('react-redux'); const { ScreenHeader } = require('../screen-header.js'); const { _ } = require('@joplin/lib/locale'); diff --git a/packages/app-mobile/components/screens/folder.js b/packages/app-mobile/components/screens/folder.js index a43a65a06..2026afcea 100644 --- a/packages/app-mobile/components/screens/folder.js +++ b/packages/app-mobile/components/screens/folder.js @@ -2,7 +2,7 @@ const React = require('react'); const { View, TextInput, StyleSheet } = require('react-native'); const { connect } = require('react-redux'); -const Folder = require('@joplin/lib/models/Folder.js'); +const Folder = require('@joplin/lib/models/Folder').default; const BaseModel = require('@joplin/lib/BaseModel').default; const { ScreenHeader } = require('../screen-header.js'); const { BaseScreenComponent } = require('../base-screen.js'); diff --git a/packages/app-mobile/components/screens/notes.js b/packages/app-mobile/components/screens/notes.js index 55875c497..85912fb20 100644 --- a/packages/app-mobile/components/screens/notes.js +++ b/packages/app-mobile/components/screens/notes.js @@ -4,9 +4,9 @@ const { AppState, View, StyleSheet } = require('react-native'); const { stateUtils } = require('@joplin/lib/reducer'); const { connect } = require('react-redux'); const { NoteList } = require('../note-list.js'); -const Folder = require('@joplin/lib/models/Folder.js'); -const Tag = require('@joplin/lib/models/Tag.js'); -const Note = require('@joplin/lib/models/Note.js'); +const Folder = require('@joplin/lib/models/Folder').default; +const Tag = require('@joplin/lib/models/Tag').default; +const Note = require('@joplin/lib/models/Note').default; const Setting = require('@joplin/lib/models/Setting').default; const { themeStyle } = require('../global-style.js'); const { ScreenHeader } = require('../screen-header.js'); diff --git a/packages/app-mobile/components/screens/search.js b/packages/app-mobile/components/screens/search.js index 12e269c7e..ee228d78a 100644 --- a/packages/app-mobile/components/screens/search.js +++ b/packages/app-mobile/components/screens/search.js @@ -5,13 +5,13 @@ const { connect } = require('react-redux'); const { ScreenHeader } = require('../screen-header.js'); const Icon = require('react-native-vector-icons/Ionicons').default; const { _ } = require('@joplin/lib/locale'); -const Note = require('@joplin/lib/models/Note.js'); +const Note = require('@joplin/lib/models/Note').default; const { NoteItem } = require('../note-item.js'); const { BaseScreenComponent } = require('../base-screen.js'); const { themeStyle } = require('../global-style.js'); const DialogBox = require('react-native-dialogbox').default; const SearchEngineUtils = require('@joplin/lib/services/searchengine/SearchEngineUtils'); -const SearchEngine = require('@joplin/lib/services/searchengine/SearchEngine'); +const SearchEngine = require('@joplin/lib/services/searchengine/SearchEngine').default; Icon.loadFont(); diff --git a/packages/app-mobile/components/screens/status.js b/packages/app-mobile/components/screens/status.js index 3a4a46605..04d03a423 100644 --- a/packages/app-mobile/components/screens/status.js +++ b/packages/app-mobile/components/screens/status.js @@ -4,7 +4,7 @@ const { View, Text, Button, FlatList } = require('react-native'); const Setting = require('@joplin/lib/models/Setting').default; const { connect } = require('react-redux'); const { ScreenHeader } = require('../screen-header.js'); -const { ReportService } = require('@joplin/lib/services/report.js'); +const ReportService = require('@joplin/lib/services/ReportService').default; const { _ } = require('@joplin/lib/locale'); const { BaseScreenComponent } = require('../base-screen.js'); const { themeStyle } = require('../global-style.js'); diff --git a/packages/app-mobile/components/screens/tags.js b/packages/app-mobile/components/screens/tags.js index aa44978fa..6e966310b 100644 --- a/packages/app-mobile/components/screens/tags.js +++ b/packages/app-mobile/components/screens/tags.js @@ -2,7 +2,7 @@ const React = require('react'); const { View, Text, FlatList, StyleSheet, TouchableOpacity } = require('react-native'); const { connect } = require('react-redux'); -const Tag = require('@joplin/lib/models/Tag.js'); +const Tag = require('@joplin/lib/models/Tag').default; const { themeStyle } = require('../global-style.js'); const { ScreenHeader } = require('../screen-header.js'); const { _ } = require('@joplin/lib/locale'); diff --git a/packages/app-mobile/components/side-menu-content.js b/packages/app-mobile/components/side-menu-content.js index 4a5fd90e1..7dc364803 100644 --- a/packages/app-mobile/components/side-menu-content.js +++ b/packages/app-mobile/components/side-menu-content.js @@ -3,9 +3,9 @@ const Component = React.Component; const { Easing, Animated, TouchableOpacity, Text, StyleSheet, ScrollView, View, Alert } = require('react-native'); const { connect } = require('react-redux'); const Icon = require('react-native-vector-icons/Ionicons').default; -const Folder = require('@joplin/lib/models/Folder.js'); +const Folder = require('@joplin/lib/models/Folder').default; const Synchronizer = require('@joplin/lib/Synchronizer').default; -const NavService = require('@joplin/lib/services/NavService.js'); +const NavService = require('@joplin/lib/services/NavService').default; const { _ } = require('@joplin/lib/locale'); const { themeStyle } = require('./global-style.js'); const shared = require('@joplin/lib/components/shared/side-menu-shared.js'); diff --git a/packages/app-mobile/root.tsx b/packages/app-mobile/root.tsx index e3be1f080..2e476be17 100644 --- a/packages/app-mobile/root.tsx +++ b/packages/app-mobile/root.tsx @@ -30,26 +30,26 @@ import SyncTargetOneDrive from '@joplin/lib/SyncTargetOneDrive'; const { AppState, Keyboard, NativeModules, BackHandler, Animated, View, StatusBar } = require('react-native'); const DropdownAlert = require('react-native-dropdownalert').default; -const AlarmServiceDriver = require('./services/AlarmServiceDriver').default; +const AlarmServiceDriver = require('./services/AlarmServiceDriver'); const SafeAreaView = require('./components/SafeAreaView'); const { connect, Provider } = require('react-redux'); const { BackButtonService } = require('./services/back-button.js'); -const NavService = require('@joplin/lib/services/NavService.js'); +import NavService from '@joplin/lib/services/NavService'; const { createStore, applyMiddleware } = require('redux'); const reduxSharedMiddleware = require('@joplin/lib/components/shared/reduxSharedMiddleware'); const { shimInit } = require('./utils/shim-init-react.js'); const { AppNav } = require('./components/app-nav.js'); -const Note = require('@joplin/lib/models/Note.js'); -const Folder = require('@joplin/lib/models/Folder.js'); +import Note from '@joplin/lib/models/Note'; +import Folder from '@joplin/lib/models/Folder'; const BaseSyncTarget = require('@joplin/lib/BaseSyncTarget.js'); const { FoldersScreenUtils } = require('@joplin/lib/folders-screen-utils.js'); -const Resource = require('@joplin/lib/models/Resource.js'); -const Tag = require('@joplin/lib/models/Tag.js'); -const NoteTag = require('@joplin/lib/models/NoteTag.js'); -const BaseItem = require('@joplin/lib/models/BaseItem.js'); -const MasterKey = require('@joplin/lib/models/MasterKey.js'); -const Revision = require('@joplin/lib/models/Revision.js'); -const RevisionService = require('@joplin/lib/services/RevisionService'); +import Resource from '@joplin/lib/models/Resource'; +import Tag from '@joplin/lib/models/Tag'; +import NoteTag from '@joplin/lib/models/NoteTag'; +import BaseItem from '@joplin/lib/models/BaseItem'; +import MasterKey from '@joplin/lib/models/MasterKey'; +import Revision from '@joplin/lib/models/Revision'; +import RevisionService from '@joplin/lib/services/RevisionService'; const { JoplinDatabase } = require('@joplin/lib/joplin-database.js'); const { Database } = require('@joplin/lib/database.js'); const { NotesScreen } = require('./components/screens/notes.js'); @@ -70,8 +70,8 @@ const { DatabaseDriverReactNative } = require('./utils/database-driver-react-nat const { reg } = require('@joplin/lib/registry.js'); const { defaultState } = require('@joplin/lib/reducer'); const { FileApiDriverLocal } = require('@joplin/lib/file-api-driver-local.js'); -const ResourceFetcher = require('@joplin/lib/services/ResourceFetcher'); -const SearchEngine = require('@joplin/lib/services/searchengine/SearchEngine'); +import ResourceFetcher from '@joplin/lib/services/ResourceFetcher'; +import SearchEngine from '@joplin/lib/services/searchengine/SearchEngine'; const WelcomeUtils = require('@joplin/lib/WelcomeUtils'); const { themeStyle } = require('./components/global-style.js'); @@ -91,9 +91,9 @@ SyncTargetRegistry.addClass(SyncTargetAmazonS3); SyncTargetRegistry.addClass(SyncTargetJoplinServer); const FsDriverRN = require('./utils/fs-driver-rn.js').FsDriverRN; -const DecryptionWorker = require('@joplin/lib/services/DecryptionWorker'); -const EncryptionService = require('@joplin/lib/services/EncryptionService'); -const MigrationService = require('@joplin/lib/services/MigrationService'); +import DecryptionWorker from '@joplin/lib/services/DecryptionWorker'; +import EncryptionService from '@joplin/lib/services/EncryptionService'; +import MigrationService from '@joplin/lib/services/MigrationService'; let storeDispatch = function(_action: any) {}; @@ -141,7 +141,7 @@ const generalMiddleware = (store: any) => (next: any) => async (action: any) => if ((action.type == 'SETTING_UPDATE_ONE' && (action.key.indexOf('encryption.') === 0)) || (action.type == 'SETTING_UPDATE_ALL')) { await EncryptionService.instance().loadMasterKeysFromSettings(); - DecryptionWorker.instance().scheduleStart(); + void DecryptionWorker.instance().scheduleStart(); const loadedMasterKeyIds = EncryptionService.instance().loadedMasterKeyIds(); storeDispatch({ @@ -159,11 +159,11 @@ const generalMiddleware = (store: any) => (next: any) => async (action: any) => } if (action.type === 'SYNC_GOT_ENCRYPTED_ITEM') { - DecryptionWorker.instance().scheduleStart(); + void DecryptionWorker.instance().scheduleStart(); } if (action.type === 'SYNC_CREATED_OR_UPDATED_RESOURCE') { - ResourceFetcher.instance().autoAddResources(); + void ResourceFetcher.instance().autoAddResources(); } return result; @@ -373,7 +373,7 @@ storeDispatch = store.dispatch; function resourceFetcher_downloadComplete(event: any) { if (event.encrypted) { - DecryptionWorker.instance().scheduleStart(); + void DecryptionWorker.instance().scheduleStart(); } } @@ -575,7 +575,7 @@ async function initialize(dispatch: Function) { ResourceFetcher.instance().setLogger(reg.logger()); ResourceFetcher.instance().dispatch = dispatch; ResourceFetcher.instance().on('downloadComplete', resourceFetcher_downloadComplete); - ResourceFetcher.instance().start(); + void ResourceFetcher.instance().start(); SearchEngine.instance().setDb(reg.db()); SearchEngine.instance().setLogger(reg.logger()); @@ -590,7 +590,7 @@ async function initialize(dispatch: Function) { // might change the notifications. void AlarmService.updateAllNotifications(); - DecryptionWorker.instance().scheduleStart(); + void DecryptionWorker.instance().scheduleStart(); }); await WelcomeUtils.install(dispatch); diff --git a/packages/app-mobile/setUpQuickActions.ts b/packages/app-mobile/setUpQuickActions.ts index 86bd5e055..ec48b67e8 100644 --- a/packages/app-mobile/setUpQuickActions.ts +++ b/packages/app-mobile/setUpQuickActions.ts @@ -4,7 +4,7 @@ import * as QuickActions from 'react-native-quick-actions'; import { _ } from '@joplin/lib/locale'; const { DeviceEventEmitter } = require('react-native'); -const Note = require('@joplin/lib/models/Note.js'); +import Note from '@joplin/lib/models/Note'; const { reg } = require('@joplin/lib/registry.js'); type TData = { @@ -36,7 +36,7 @@ export default (dispatch: Function, folderId: string) => { const isTodo = data.type === 'New to-do' ? 1 : 0; - Note.save({ + void Note.save({ parent_id: folderId, is_todo: isTodo, }, { provisional: true }).then((newNote: any) => { diff --git a/packages/app-mobile/utils/shareHandler.ts b/packages/app-mobile/utils/shareHandler.ts index 790a5943b..21eec8ed6 100644 --- a/packages/app-mobile/utils/shareHandler.ts +++ b/packages/app-mobile/utils/shareHandler.ts @@ -1,8 +1,8 @@ import ShareExtension, { SharedData } from './ShareExtension'; import shim from '@joplin/lib/shim'; -const Note = require('@joplin/lib/models/Note.js'); -const checkPermissions = require('./checkPermissions.js').default; +import Note from '@joplin/lib/models/Note'; +import checkPermissions from './checkPermissions.js'; const { ToastAndroid } = require('react-native'); const { PermissionsAndroid } = require('react-native'); diff --git a/packages/app-mobile/utils/shim-init-react.js b/packages/app-mobile/utils/shim-init-react.js index 210a19b19..b5f727317 100644 --- a/packages/app-mobile/utils/shim-init-react.js +++ b/packages/app-mobile/utils/shim-init-react.js @@ -10,7 +10,7 @@ const { Linking, Platform } = require('react-native'); const mimeUtils = require('@joplin/lib/mime-utils.js').mime; const { basename, fileExtension } = require('@joplin/lib/path-utils'); const uuid = require('@joplin/lib/uuid').default; -const Resource = require('@joplin/lib/models/Resource'); +const Resource = require('@joplin/lib/models/Resource').default; const injectedJs = { webviewLib: require('@joplin/lib/rnInjectedJs/webviewLib'), diff --git a/packages/lib/BaseApplication.ts b/packages/lib/BaseApplication.ts index e2b102c96..97f3294d0 100644 --- a/packages/lib/BaseApplication.ts +++ b/packages/lib/BaseApplication.ts @@ -14,14 +14,14 @@ const { defaultState, stateUtils } = require('./reducer'); const { JoplinDatabase } = require('./joplin-database.js'); const { FoldersScreenUtils } = require('./folders-screen-utils.js'); const { DatabaseDriverNode } = require('./database-driver-node.js'); -const BaseModel = require('./BaseModel').default; -const Folder = require('./models/Folder.js'); -const BaseItem = require('./models/BaseItem.js'); -const Note = require('./models/Note.js'); -const Tag = require('./models/Tag.js'); +import BaseModel from './BaseModel'; +import Folder from './models/Folder'; +import BaseItem from './models/BaseItem'; +import Note from './models/Note'; +import Tag from './models/Tag'; const { splitCommandString } = require('./string-utils.js'); const { reg } = require('./registry.js'); -const time = require('./time').default; +import time from './time'; const BaseSyncTarget = require('./BaseSyncTarget.js'); const reduxSharedMiddleware = require('./components/shared/reduxSharedMiddleware'); const os = require('os'); @@ -35,15 +35,15 @@ const SyncTargetNextcloud = require('./SyncTargetNextcloud.js'); const SyncTargetWebDAV = require('./SyncTargetWebDAV.js'); const SyncTargetDropbox = require('./SyncTargetDropbox.js'); const SyncTargetAmazonS3 = require('./SyncTargetAmazonS3.js'); -const EncryptionService = require('./services/EncryptionService'); -const ResourceFetcher = require('./services/ResourceFetcher'); -const SearchEngineUtils = require('./services/searchengine/SearchEngineUtils'); -const SearchEngine = require('./services/searchengine/SearchEngine'); -const RevisionService = require('./services/RevisionService'); -const ResourceService = require('./services/RevisionService'); -const DecryptionWorker = require('./services/DecryptionWorker'); +import EncryptionService from './services/EncryptionService'; +import ResourceFetcher from './services/ResourceFetcher'; +import SearchEngineUtils from './services/searchengine/SearchEngineUtils'; +import SearchEngine from './services/searchengine/SearchEngine'; +import RevisionService from './services/RevisionService'; +import ResourceService from './services/ResourceService'; +import DecryptionWorker from './services/DecryptionWorker'; const { loadKeychainServiceAndSettings } = require('./services/SettingUtils'); -const MigrationService = require('./services/MigrationService'); +import MigrationService from './services/MigrationService'; const { toSystemSlashes } = require('./path-utils'); const { setAutoFreeze } = require('immer'); @@ -94,7 +94,8 @@ export default class BaseApplication { BaseItem.revisionService_ = null; RevisionService.instance_ = null; ResourceService.instance_ = null; - ResourceService.isRunningInBackground = false; + ResourceService.isRunningInBackground_ = false; + // ResourceService.isRunningInBackground_ = false; ResourceFetcher.instance_ = null; EncryptionService.instance_ = null; DecryptionWorker.instance_ = null; @@ -365,7 +366,7 @@ export default class BaseApplication { resourceFetcher_downloadComplete(event: any) { if (event.encrypted) { - DecryptionWorker.instance().scheduleStart(); + void DecryptionWorker.instance().scheduleStart(); } } @@ -422,7 +423,7 @@ export default class BaseApplication { 'encryption.enabled': async () => { if (this.hasGui()) { await EncryptionService.instance().loadMasterKeysFromSettings(); - DecryptionWorker.instance().scheduleStart(); + void DecryptionWorker.instance().scheduleStart(); const loadedMasterKeyIds = EncryptionService.instance().loadedMasterKeyIds(); this.dispatch({ @@ -568,11 +569,11 @@ export default class BaseApplication { } if (this.hasGui() && action.type === 'SYNC_GOT_ENCRYPTED_ITEM') { - DecryptionWorker.instance().scheduleStart(); + void DecryptionWorker.instance().scheduleStart(); } if (this.hasGui() && action.type === 'SYNC_CREATED_OR_UPDATED_RESOURCE') { - ResourceFetcher.instance().autoAddResources(); + void ResourceFetcher.instance().autoAddResources(); } if (action.type == 'SETTING_UPDATE_ONE') { @@ -802,7 +803,7 @@ export default class BaseApplication { if ('welcomeDisabled' in initArgs) Setting.setValue('welcome.enabled', !initArgs.welcomeDisabled); if (!Setting.value('api.token')) { - EncryptionService.instance() + void EncryptionService.instance() .randomHexString(64) .then((token: string) => { Setting.setValue('api.token', token); @@ -829,7 +830,7 @@ export default class BaseApplication { }); ResourceFetcher.instance().setLogger(globalLogger); ResourceFetcher.instance().on('downloadComplete', this.resourceFetcher_downloadComplete); - ResourceFetcher.instance().start(); + void ResourceFetcher.instance().start(); SearchEngine.instance().setDb(reg.db()); SearchEngine.instance().setLogger(reg.logger()); diff --git a/packages/lib/BaseModel.ts b/packages/lib/BaseModel.ts index c5b56b862..a05a32f57 100644 --- a/packages/lib/BaseModel.ts +++ b/packages/lib/BaseModel.ts @@ -1,8 +1,8 @@ import paginationToSql from './models/utils/paginationToSql'; const { Database } = require('./database.js'); -const uuid = require('./uuid').default; -const time = require('./time').default; +import uuid from './uuid'; +import time from './time'; const Mutex = require('async-mutex').Mutex; // New code should make use of this enum @@ -344,7 +344,7 @@ class BaseModel { return this.modelSelectOne(sql, [fieldValue]); } - static loadByFields(fields: string[], options: any = null) { + static loadByFields(fields: any, options: any = null) { if (!options) options = {}; if (!('caseInsensitive' in options)) options.caseInsensitive = false; if (!options.fields) options.fields = '*'; @@ -644,9 +644,9 @@ class BaseModel { return this.db_; } - static isReady() { - return !!this.db_; - } + // static isReady() { + // return !!this.db_; + // } } for (let i = 0; i < BaseModel.typeEnum_.length; i++) { diff --git a/packages/lib/BaseSyncTarget.js b/packages/lib/BaseSyncTarget.js index 384279c61..840b6b3aa 100644 --- a/packages/lib/BaseSyncTarget.js +++ b/packages/lib/BaseSyncTarget.js @@ -1,4 +1,4 @@ -const EncryptionService = require('./services/EncryptionService.js'); +const EncryptionService = require('./services/EncryptionService').default; const shim = require('./shim').default; class BaseSyncTarget { diff --git a/packages/lib/JoplinServerApi.ts b/packages/lib/JoplinServerApi.ts index 0992030f6..08bd462c8 100644 --- a/packages/lib/JoplinServerApi.ts +++ b/packages/lib/JoplinServerApi.ts @@ -1,6 +1,6 @@ import shim from './shim'; import { _ } from './locale'; -const Logger = require('./Logger').default; +import Logger from './Logger'; const JoplinError = require('./JoplinError'); const { rtrimSlashes } = require('./path-utils'); const base64 = require('base-64'); diff --git a/packages/lib/Logger.ts b/packages/lib/Logger.ts index e2edb3a6d..85877dcbe 100644 --- a/packages/lib/Logger.ts +++ b/packages/lib/Logger.ts @@ -1,5 +1,5 @@ const moment = require('moment'); -const time = require('./time').default; +import time from './time'; const { FsDriverDummy } = require('./fs-driver-dummy.js'); const { sprintf } = require('sprintf-js'); const Mutex = require('async-mutex').Mutex; diff --git a/packages/lib/ModelCache.js b/packages/lib/ModelCache.js deleted file mode 100644 index 32fb765c8..000000000 --- a/packages/lib/ModelCache.js +++ /dev/null @@ -1,37 +0,0 @@ -class ModelCache { - constructor(maxSize) { - this.cache_ = []; - this.maxSize_ = maxSize; - } - - fromCache(ModelClass, id) { - for (let i = 0; i < this.cache_.length; i++) { - const c = this.cache_[i]; - if (c.id === id && c.modelType === ModelClass.modelType()) return c; - } - return null; - } - - cache(ModelClass, id, model) { - if (this.fromCache(ModelClass, model.id)) return; - this.cache_.push({ - id: id, - model: model, - modelType: ModelClass.modelType(), - }); - - if (this.cache_.length > this.maxSize_) { - this.cache_.splice(0, 1); - } - } - - async load(ModelClass, id) { - const cached = this.fromCache(ModelClass, id); - if (cached) return cached.model; - const output = await ModelClass.load(id); - this.cache(ModelClass, id, output); - return output; - } -} - -module.exports = ModelCache; diff --git a/packages/lib/PoorManIntervals.ts b/packages/lib/PoorManIntervals.ts index 3e9f1412b..e9f1af3a8 100644 --- a/packages/lib/PoorManIntervals.ts +++ b/packages/lib/PoorManIntervals.ts @@ -6,7 +6,7 @@ // whenever the update() function is called, and in mobile it's called for // example on the Redux action middleware or when the app gets focus. -const time = require('./time').default; +import time from './time'; type IntervalId = number; diff --git a/packages/lib/Synchronizer.ts b/packages/lib/Synchronizer.ts index 28dac7426..60629edba 100644 --- a/packages/lib/Synchronizer.ts +++ b/packages/lib/Synchronizer.ts @@ -6,16 +6,16 @@ import MigrationHandler from './services/synchronizer/MigrationHandler'; import eventManager from './eventManager'; import { _ } from './locale'; -const BaseItem = require('./models/BaseItem.js'); -const Folder = require('./models/Folder.js'); -const Note = require('./models/Note.js'); -const Resource = require('./models/Resource.js'); -const ItemChange = require('./models/ItemChange.js'); -const ResourceLocalState = require('./models/ResourceLocalState.js'); -const MasterKey = require('./models/MasterKey.js'); -const BaseModel = require('./BaseModel').default; +import BaseItem from './models/BaseItem'; +import Folder from './models/Folder'; +import Note from './models/Note'; +import Resource from './models/Resource'; +import ItemChange from './models/ItemChange'; +import ResourceLocalState from './models/ResourceLocalState'; +import MasterKey from './models/MasterKey'; +import BaseModel from './BaseModel'; const { sprintf } = require('sprintf-js'); -const time = require('./time').default; +import time from './time'; const JoplinError = require('./JoplinError'); const TaskQueue = require('./TaskQueue'); const { Dirnames } = require('./services/synchronizer/utils/types'); diff --git a/packages/lib/WelcomeUtils.js b/packages/lib/WelcomeUtils.js index 7df5ca73c..1e5469976 100644 --- a/packages/lib/WelcomeUtils.js +++ b/packages/lib/WelcomeUtils.js @@ -1,8 +1,8 @@ const welcomeAssets = require('./welcomeAssets'); -const Note = require('./models/Note'); +const Note = require('./models/Note').default; const Setting = require('./models/Setting').default; -const Folder = require('./models/Folder'); -const Tag = require('./models/Tag'); +const Folder = require('./models/Folder').default; +const Tag = require('./models/Tag').default; const shim = require('./shim').default; const uuid = require('./uuid').default; const { fileExtension, basename } = require('./path-utils'); diff --git a/packages/lib/components/shared/encryption-config-shared.js b/packages/lib/components/shared/encryption-config-shared.js index 72c019835..bf53693d4 100644 --- a/packages/lib/components/shared/encryption-config-shared.js +++ b/packages/lib/components/shared/encryption-config-shared.js @@ -1,8 +1,8 @@ -const EncryptionService = require('../../services/EncryptionService'); +const EncryptionService = require('../../services/EncryptionService').default; const { _ } = require('../../locale'); -const BaseItem = require('../../models/BaseItem.js'); +const BaseItem = require('../../models/BaseItem').default; const Setting = require('../../models/Setting').default; -const MasterKey = require('../../models/MasterKey.js'); +const MasterKey = require('../../models/MasterKey').default; const { reg } = require('../../registry.js'); const shim = require('../../shim').default; diff --git a/packages/lib/components/shared/note-screen-shared.js b/packages/lib/components/shared/note-screen-shared.js index 8bf74c5c6..b86f5e739 100644 --- a/packages/lib/components/shared/note-screen-shared.js +++ b/packages/lib/components/shared/note-screen-shared.js @@ -1,10 +1,10 @@ const { reg } = require('../../registry.js'); -const Folder = require('../../models/Folder.js'); +const Folder = require('../../models/Folder').default; const BaseModel = require('../../BaseModel').default; -const Note = require('../../models/Note.js'); -const Resource = require('../../models/Resource.js'); -const ResourceFetcher = require('../../services/ResourceFetcher.js'); -const DecryptionWorker = require('../../services/DecryptionWorker.js'); +const Note = require('../../models/Note').default; +const Resource = require('../../models/Resource').default; +const ResourceFetcher = require('../../services/ResourceFetcher').default; +const DecryptionWorker = require('../../services/DecryptionWorker').default; const Setting = require('../../models/Setting').default; const Mutex = require('async-mutex').Mutex; diff --git a/packages/lib/components/shared/reduxSharedMiddleware.js b/packages/lib/components/shared/reduxSharedMiddleware.js index 3eb9cf802..dde294bb4 100644 --- a/packages/lib/components/shared/reduxSharedMiddleware.js +++ b/packages/lib/components/shared/reduxSharedMiddleware.js @@ -1,10 +1,10 @@ const Setting = require('../../models/Setting').default; -const Tag = require('../../models/Tag'); +const Tag = require('../../models/Tag').default; const BaseModel = require('../../BaseModel').default; -const Note = require('../../models/Note'); +const Note = require('../../models/Note').default; const { reg } = require('../../registry.js'); -const ResourceFetcher = require('../../services/ResourceFetcher'); -const DecryptionWorker = require('../../services/DecryptionWorker'); +const ResourceFetcher = require('../../services/ResourceFetcher').default; +const DecryptionWorker = require('../../services/DecryptionWorker').default; const eventManager = require('../../eventManager').default; const reduxSharedMiddleware = async function(store, next, action) { diff --git a/packages/lib/components/shared/side-menu-shared.js b/packages/lib/components/shared/side-menu-shared.js index a3015a335..b5481b46d 100644 --- a/packages/lib/components/shared/side-menu-shared.js +++ b/packages/lib/components/shared/side-menu-shared.js @@ -1,4 +1,4 @@ -const Folder = require('../../models/Folder'); +const Folder = require('../../models/Folder').default; const BaseModel = require('../../BaseModel').default; const shared = {}; diff --git a/packages/lib/file-api.js b/packages/lib/file-api.js index e77cfce41..0a6eada8b 100644 --- a/packages/lib/file-api.js +++ b/packages/lib/file-api.js @@ -1,7 +1,7 @@ const { isHidden } = require('./path-utils'); const Logger = require('./Logger').default; const shim = require('./shim').default; -const BaseItem = require('./models/BaseItem.js'); +const BaseItem = require('./models/BaseItem').default; const JoplinError = require('./JoplinError'); const ArrayUtils = require('./ArrayUtils'); const time = require('./time').default; diff --git a/packages/lib/folders-screen-utils.js b/packages/lib/folders-screen-utils.js index 93789c440..47edb7164 100644 --- a/packages/lib/folders-screen-utils.js +++ b/packages/lib/folders-screen-utils.js @@ -1,4 +1,4 @@ -const Folder = require('./models/Folder.js'); +const Folder = require('./models/Folder').default; const Setting = require('./models/Setting').default; const shim = require('./shim').default; diff --git a/packages/lib/import-enex.js b/packages/lib/import-enex.js index e381723aa..7503335c7 100644 --- a/packages/lib/import-enex.js +++ b/packages/lib/import-enex.js @@ -1,9 +1,9 @@ const uuid = require('./uuid').default; const moment = require('moment'); const BaseModel = require('./BaseModel').default; -const Note = require('./models/Note.js'); -const Tag = require('./models/Tag.js'); -const Resource = require('./models/Resource.js'); +const Note = require('./models/Note').default; +const Tag = require('./models/Tag').default; +const Resource = require('./models/Resource').default; const Setting = require('./models/Setting').default; const { MarkupToHtml } = require('@joplin/renderer'); const { wrapError } = require('./errorUtils'); diff --git a/packages/lib/joplin-database.js b/packages/lib/joplin-database.js index 5de19ad6b..0af941585 100644 --- a/packages/lib/joplin-database.js +++ b/packages/lib/joplin-database.js @@ -1,7 +1,7 @@ const { promiseChain } = require('./promise-utils.js'); const { Database } = require('./database.js'); const { sprintf } = require('sprintf-js'); -const Resource = require('./models/Resource'); +const Resource = require('./models/Resource').default; const shim = require('./shim').default; const structureSql = ` diff --git a/packages/lib/markupLanguageUtils.ts b/packages/lib/markupLanguageUtils.ts index 1cb1db071..0179d9191 100644 --- a/packages/lib/markupLanguageUtils.ts +++ b/packages/lib/markupLanguageUtils.ts @@ -6,7 +6,7 @@ import { PluginStates } from './services/plugins/reducer'; import { contentScriptsToRendererRules } from './services/plugins/utils/loadContentScripts'; const htmlUtils = require('./htmlUtils'); -const Resource = require('./models/Resource'); +import Resource from './models/Resource'; class MarkupLanguageUtils { lib_(language: MarkupLanguage) { diff --git a/packages/lib/migrations/20.js b/packages/lib/migrations/20.js index 87630fe5f..218139c3f 100644 --- a/packages/lib/migrations/20.js +++ b/packages/lib/migrations/20.js @@ -1,4 +1,4 @@ -const Resource = require('../models/Resource'); +const Resource = require('../models/Resource').default; const Setting = require('../models/Setting').default; const shim = require('../shim').default; const { reg } = require('../registry.js'); diff --git a/packages/lib/migrations/33.js b/packages/lib/migrations/33.js index 576801a2b..96d34ab3f 100644 --- a/packages/lib/migrations/33.js +++ b/packages/lib/migrations/33.js @@ -1,4 +1,4 @@ -const SearchEngine = require('../services/searchengine/SearchEngine'); +const SearchEngine = require('../services/searchengine/SearchEngine').default; const script = {}; diff --git a/packages/lib/models/Alarm.ts b/packages/lib/models/Alarm.ts index 42d41560e..3050cb782 100644 --- a/packages/lib/models/Alarm.ts +++ b/packages/lib/models/Alarm.ts @@ -1,5 +1,5 @@ -const BaseModel = require('../BaseModel').default; -const Note = require('./Note.js'); +import BaseModel from '../BaseModel'; +import Note from './Note'; export interface Notification { id: number; diff --git a/packages/lib/models/BaseItem.js b/packages/lib/models/BaseItem.ts similarity index 85% rename from packages/lib/models/BaseItem.js rename to packages/lib/models/BaseItem.ts index 3125dee99..24aa1c10e 100644 --- a/packages/lib/models/BaseItem.js +++ b/packages/lib/models/BaseItem.ts @@ -1,15 +1,45 @@ -const BaseModel = require('../BaseModel').default; -const { Database } = require('../database.js'); -const Setting = require('./Setting').default; -const ItemChange = require('./ItemChange.js'); -const JoplinError = require('../JoplinError.js'); -const time = require('../time').default; -const { sprintf } = require('sprintf-js'); -const { _ } = require('../locale'); -const moment = require('moment'); -const markdownUtils = require('../markdownUtils').default; +import { ModelType } from '../BaseModel'; +import { NoteEntity } from '../services/database/types'; +import Setting from './Setting'; +import BaseModel from '../BaseModel'; +import time from '../time'; +import markdownUtils from '../markdownUtils'; +import { _ } from '../locale'; + +const { Database } = require('../database.js'); +import ItemChange from './ItemChange'; +const JoplinError = require('../JoplinError.js'); +const { sprintf } = require('sprintf-js'); +const moment = require('moment'); + +export interface ItemsThatNeedDecryptionResult { + hasMore: boolean; + items: any[]; +} + +export default class BaseItem extends BaseModel { + + public static encryptionService_: any = null; + public static revisionService_: any = null; + + // Also update: + // - itemsThatNeedSync() + // - syncedItems() + + public static syncItemDefinitions_: any[] = [ + { type: BaseModel.TYPE_NOTE, className: 'Note' }, + { type: BaseModel.TYPE_FOLDER, className: 'Folder' }, + { type: BaseModel.TYPE_RESOURCE, className: 'Resource' }, + { type: BaseModel.TYPE_TAG, className: 'Tag' }, + { type: BaseModel.TYPE_NOTE_TAG, className: 'NoteTag' }, + { type: BaseModel.TYPE_MASTER_KEY, className: 'MasterKey' }, + { type: BaseModel.TYPE_REVISION, className: 'Revision' }, + ]; + + public static SYNC_ITEM_LOCATION_LOCAL = 1; + public static SYNC_ITEM_LOCATION_REMOTE = 2; + -class BaseItem extends BaseModel { static useUuid() { return true; } @@ -18,7 +48,7 @@ class BaseItem extends BaseModel { return true; } - static loadClass(className, classRef) { + static loadClass(className: string, classRef: any) { for (let i = 0; i < BaseItem.syncItemDefinitions_.length; i++) { if (BaseItem.syncItemDefinitions_[i].className == className) { BaseItem.syncItemDefinitions_[i].classRef = classRef; @@ -29,7 +59,7 @@ class BaseItem extends BaseModel { throw new Error(`Invalid class name: ${className}`); } - static async findUniqueItemTitle(title, parentId = null) { + static async findUniqueItemTitle(title: string, parentId: string = null) { let counter = 1; let titleToTry = title; while (true) { @@ -53,7 +83,7 @@ class BaseItem extends BaseModel { } // Need to dynamically load the classes like this to avoid circular dependencies - static getClass(name) { + static getClass(name: string) { for (let i = 0; i < BaseItem.syncItemDefinitions_.length; i++) { if (BaseItem.syncItemDefinitions_[i].className == name) { const classRef = BaseItem.syncItemDefinitions_[i].classRef; @@ -65,7 +95,7 @@ class BaseItem extends BaseModel { throw new Error(`Invalid class name: ${name}`); } - static getClassByItemType(itemType) { + static getClassByItemType(itemType: ModelType) { for (let i = 0; i < BaseItem.syncItemDefinitions_.length; i++) { if (BaseItem.syncItemDefinitions_[i].type == itemType) { return BaseItem.syncItemDefinitions_[i].classRef; @@ -75,7 +105,7 @@ class BaseItem extends BaseModel { throw new Error(`Invalid item type: ${itemType}`); } - static async syncedCount(syncTarget) { + static async syncedCount(syncTarget: number) { const ItemClass = this.itemClass(this.modelType()); const itemType = ItemClass.modelType(); // The fact that we don't check if the item_id still exist in the corresponding item table, means @@ -85,24 +115,24 @@ class BaseItem extends BaseModel { return r.total; } - static systemPath(itemOrId, extension = null) { + static systemPath(itemOrId: any, extension: string = null) { if (extension === null) extension = 'md'; if (typeof itemOrId === 'string') return `${itemOrId}.${extension}`; else return `${itemOrId.id}.${extension}`; } - static isSystemPath(path) { + static isSystemPath(path: string) { // 1b175bb38bba47baac22b0b47f778113.md if (!path || !path.length) return false; - let p = path.split('/'); + let p: any = path.split('/'); p = p[p.length - 1]; p = p.split('.'); if (p.length != 2) return false; return p[0].length == 32 && p[1] == 'md'; } - static itemClass(item) { + static itemClass(item: any): any { if (!item) throw new Error('Item cannot be null'); if (typeof item === 'object') { @@ -118,7 +148,7 @@ class BaseItem extends BaseModel { } // Returns the IDs of the items that have been synced at least once - static async syncedItemIds(syncTarget) { + static async syncedItemIds(syncTarget: number) { if (!syncTarget) throw new Error('No syncTarget specified'); const temp = await this.db().selectAll('SELECT item_id FROM sync_items WHERE sync_time > 0 AND sync_target = ?', [syncTarget]); const output = []; @@ -128,25 +158,25 @@ class BaseItem extends BaseModel { return output; } - static async allSyncItems(syncTarget) { + static async allSyncItems(syncTarget: number) { const output = await this.db().selectAll('SELECT * FROM sync_items WHERE sync_target = ?', [syncTarget]); return output; } - static pathToId(path) { + static pathToId(path: string) { const p = path.split('/'); const s = p[p.length - 1].split('.'); - let name = s[0]; + let name: any = s[0]; if (!name) return name; name = name.split('-'); return name[name.length - 1]; } - static loadItemByPath(path) { + static loadItemByPath(path: string) { return this.loadItemById(this.pathToId(path)); } - static async loadItemById(id) { + static async loadItemById(id: string) { const classes = this.syncItemClassNames(); for (let i = 0; i < classes.length; i++) { const item = await this.getClass(classes[i]).load(id); @@ -155,11 +185,11 @@ class BaseItem extends BaseModel { return null; } - static async loadItemsByIds(ids) { + static async loadItemsByIds(ids: string[]) { if (!ids.length) return []; const classes = this.syncItemClassNames(); - let output = []; + let output: any[] = []; for (let i = 0; i < classes.length; i++) { const ItemClass = this.getClass(classes[i]); const sql = `SELECT * FROM ${ItemClass.tableName()} WHERE id IN ("${ids.join('","')}")`; @@ -169,26 +199,26 @@ class BaseItem extends BaseModel { return output; } - static loadItemByField(itemType, field, value) { + static loadItemByField(itemType: number, field: string, value: any) { const ItemClass = this.itemClass(itemType); return ItemClass.loadByField(field, value); } - static loadItem(itemType, id) { + static loadItem(itemType: ModelType, id: string) { const ItemClass = this.itemClass(itemType); return ItemClass.load(id); } - static deleteItem(itemType, id) { + static deleteItem(itemType: ModelType, id: string) { const ItemClass = this.itemClass(itemType); return ItemClass.delete(id); } - static async delete(id, options = null) { + static async delete(id: string, options: any = null) { return this.batchDelete([id], options); } - static async batchDelete(ids, options = null) { + static async batchDelete(ids: string[], options: any = null) { if (!options) options = {}; let trackDeleted = true; if (options && options.trackDeleted !== null && options.trackDeleted !== undefined) trackDeleted = options.trackDeleted; @@ -198,7 +228,7 @@ class BaseItem extends BaseModel { let conflictNoteIds = []; if (this.modelType() == BaseModel.TYPE_NOTE) { const conflictNotes = await this.db().selectAll(`SELECT id FROM notes WHERE id IN ("${ids.join('","')}") AND is_conflict = 1`); - conflictNoteIds = conflictNotes.map(n => { + conflictNoteIds = conflictNotes.map((n: NoteEntity) => { return n.id; }); } @@ -234,20 +264,20 @@ class BaseItem extends BaseModel { // - Client 1 syncs with target 2 only => the note is *not* deleted from target 2 because no information // that it was previously deleted exist (deleted_items entry has been deleted). // The solution would be to permanently store the list of deleted items on each client. - static deletedItems(syncTarget) { + static deletedItems(syncTarget: number) { return this.db().selectAll('SELECT * FROM deleted_items WHERE sync_target = ?', [syncTarget]); } - static async deletedItemCount(syncTarget) { + static async deletedItemCount(syncTarget: number) { const r = await this.db().selectOne('SELECT count(*) as total FROM deleted_items WHERE sync_target = ?', [syncTarget]); return r['total']; } - static remoteDeletedItem(syncTarget, itemId) { + static remoteDeletedItem(syncTarget: number, itemId: string) { return this.db().exec('DELETE FROM deleted_items WHERE item_id = ? AND sync_target = ?', [itemId, syncTarget]); } - static serialize_format(propName, propValue) { + static serialize_format(propName: string, propValue: any) { if (['created_time', 'updated_time', 'sync_time', 'user_updated_time', 'user_created_time'].indexOf(propName) >= 0) { if (!propValue) return ''; propValue = `${moment.unix(propValue / 1000).utc().format('YYYY-MM-DDTHH:mm:ss.SSS')}Z`; @@ -269,7 +299,7 @@ class BaseItem extends BaseModel { .replace(/\r/g, '\\r'); } - static unserialize_format(type, propName, propValue) { + static unserialize_format(type: ModelType, propName: string, propValue: any) { if (propName[propName.length - 1] == '_') return propValue; // Private property const ItemClass = this.itemClass(type); @@ -297,7 +327,7 @@ class BaseItem extends BaseModel { : propValue; } - static async serialize(item, shownKeys = null) { + static async serialize(item: any, shownKeys: any[] = null) { if (shownKeys === null) { shownKeys = this.itemClass(item).fieldNames(); shownKeys.push('type_'); @@ -305,7 +335,7 @@ class BaseItem extends BaseModel { item = this.filter(item); - const output = {}; + const output: any = {}; if ('title' in item && shownKeys.indexOf('title') >= 0) { output.title = item.title; @@ -352,7 +382,7 @@ class BaseItem extends BaseModel { return this.revisionService_; } - static async serializeForSync(item) { + static async serializeForSync(item: any) { const ItemClass = this.itemClass(item); const shownKeys = ItemClass.fieldNames(); shownKeys.push('type_'); @@ -366,7 +396,7 @@ class BaseItem extends BaseModel { } if (item.encryption_applied) { - const e = new Error('Trying to encrypt item that is already encrypted'); + const e: any = new Error('Trying to encrypt item that is already encrypted'); e.code = 'cannotEncryptEncrypted'; throw e; } @@ -386,7 +416,7 @@ class BaseItem extends BaseModel { // List of keys that won't be encrypted - mostly foreign keys required to link items // with each others and timestamp required for synchronisation. const keepKeys = ['id', 'note_id', 'tag_id', 'parent_id', 'updated_time', 'type_']; - const reducedItem = {}; + const reducedItem: any = {}; for (let i = 0; i < keepKeys.length; i++) { const n = keepKeys[i]; @@ -399,7 +429,7 @@ class BaseItem extends BaseModel { return ItemClass.serialize(reducedItem); } - static async decrypt(item) { + static async decrypt(item: any) { if (!item.encryption_cipher_text) throw new Error(`Item is not encrypted: ${item.id}`); const ItemClass = this.itemClass(item); @@ -413,11 +443,11 @@ class BaseItem extends BaseModel { return ItemClass.save(plainItem, { autoTimestamp: false, changeSource: ItemChange.SOURCE_DECRYPTION }); } - static async unserialize(content) { + static async unserialize(content: string) { const lines = content.split('\n'); - let output = {}; + let output: any = {}; let state = 'readingProps'; - const body = []; + const body: string[] = []; for (let i = lines.length - 1; i >= 0; i--) { let line = lines[i]; @@ -506,7 +536,7 @@ class BaseItem extends BaseModel { return false; } - static async itemsThatNeedDecryption(exclusions = [], limit = 100) { + static async itemsThatNeedDecryption(exclusions: string[] = [], limit = 100): Promise { const classNames = this.encryptableItemClassNames(); for (let i = 0; i < classNames.length; i++) { @@ -546,7 +576,7 @@ class BaseItem extends BaseModel { throw new Error('Unreachable'); } - static async itemsThatNeedSync(syncTarget, limit = 100) { + static async itemsThatNeedSync(syncTarget: number, limit = 100) { const classNames = this.syncItemClassNames(); for (let i = 0; i < classNames.length; i++) { @@ -560,7 +590,7 @@ class BaseItem extends BaseModel { // // CHANGED: // 'SELECT * FROM [ITEMS] items JOIN sync_items s ON s.item_id = items.id WHERE sync_target = ? AND' - let extraWhere = []; + let extraWhere: any = []; if (className == 'Note') extraWhere.push('is_conflict = 0'); if (className == 'Resource') extraWhere.push('encryption_blob_encrypted = 0'); if (ItemClass.encryptionSupported()) extraWhere.push('encryption_applied = 0'); @@ -636,7 +666,7 @@ class BaseItem extends BaseModel { } static syncItemClassNames() { - return BaseItem.syncItemDefinitions_.map(def => { + return BaseItem.syncItemDefinitions_.map((def: any) => { return def.className; }); } @@ -652,19 +682,19 @@ class BaseItem extends BaseModel { } static syncItemTypes() { - return BaseItem.syncItemDefinitions_.map(def => { + return BaseItem.syncItemDefinitions_.map((def: any) => { return def.type; }); } - static modelTypeToClassName(type) { + static modelTypeToClassName(type: number) { for (let i = 0; i < BaseItem.syncItemDefinitions_.length; i++) { if (BaseItem.syncItemDefinitions_[i].type == type) return BaseItem.syncItemDefinitions_[i].className; } throw new Error(`Invalid type: ${type}`); } - static async syncDisabledItems(syncTargetId) { + static async syncDisabledItems(syncTargetId: number) { const rows = await this.db().selectAll('SELECT * FROM sync_items WHERE sync_disabled = 1 AND sync_target = ?', [syncTargetId]); const output = []; for (let i = 0; i < rows.length; i++) { @@ -681,7 +711,7 @@ class BaseItem extends BaseModel { return output; } - static updateSyncTimeQueries(syncTarget, item, syncTime, syncDisabled = false, syncDisabledReason = '', itemLocation = null) { + static updateSyncTimeQueries(syncTarget: number, item: any, syncTime: number, syncDisabled = false, syncDisabledReason = '', itemLocation: number = null) { const itemType = item.type_; const itemId = item.id; if (!itemType || !itemId || syncTime === undefined) throw new Error(sprintf('Invalid parameters in updateSyncTimeQueries(): %d, %s, %d', syncTarget, JSON.stringify(item), syncTime)); @@ -700,12 +730,12 @@ class BaseItem extends BaseModel { ]; } - static async saveSyncTime(syncTarget, item, syncTime) { + static async saveSyncTime(syncTarget: number, item: any, syncTime: number) { const queries = this.updateSyncTimeQueries(syncTarget, item, syncTime); return this.db().transactionExecBatch(queries); } - static async saveSyncDisabled(syncTargetId, item, syncDisabledReason, itemLocation = null) { + static async saveSyncDisabled(syncTargetId: number, item: any, syncDisabledReason: string, itemLocation: number = null) { const syncTime = 'sync_time' in item ? item.sync_time : 0; const queries = this.updateSyncTimeQueries(syncTargetId, item, syncTime, true, syncDisabledReason, itemLocation); return this.db().transactionExecBatch(queries); @@ -731,7 +761,7 @@ class BaseItem extends BaseModel { await this.db().transactionExecBatch(queries); } - static displayTitle(item) { + static displayTitle(item: any) { if (!item) return ''; if (item.encryption_applied) return `🔑 ${_('Encrypted')}`; return item.title ? item.title : _('Untitled'); @@ -753,7 +783,7 @@ class BaseItem extends BaseModel { ); const items = await ItemClass.modelSelectAll(sql); - const ids = items.map(item => { + const ids = items.map((item: any) => { return item.id; }); if (!ids.length) continue; @@ -762,7 +792,7 @@ class BaseItem extends BaseModel { } } - static async updateShareStatus(item, isShared) { + static async updateShareStatus(item: any, isShared: boolean) { if (!item.id || !item.type_) throw new Error('Item must have an ID and a type'); if (!!item.is_shared === !!isShared) return false; const ItemClass = this.getClassByItemType(item.type_); @@ -781,7 +811,7 @@ class BaseItem extends BaseModel { return true; } - static async forceSync(itemId) { + static async forceSync(itemId: string) { await this.db().exec('UPDATE sync_items SET force_sync = 1 WHERE item_id = ?', [itemId]); } @@ -789,7 +819,7 @@ class BaseItem extends BaseModel { await this.db().exec('UPDATE sync_items SET force_sync = 1'); } - static async save(o, options = null) { + static async save(o: any, options: any = null) { if (!options) options = {}; if (options.userSideValidation === true) { @@ -799,7 +829,7 @@ class BaseItem extends BaseModel { return super.save(o, options); } - static markdownTag(itemOrId) { + static markdownTag(itemOrId: any) { const item = typeof itemOrId === 'object' ? itemOrId : { id: itemOrId, title: '', @@ -813,23 +843,9 @@ class BaseItem extends BaseModel { return output.join(''); } - static isMarkdownTag(md) { + static isMarkdownTag(md: any) { if (!md) return false; return !!md.match(/^\[.*?\]\(:\/[0-9a-zA-Z]{32}\)$/); } } - -BaseItem.encryptionService_ = null; -BaseItem.revisionService_ = null; - -// Also update: -// - itemsThatNeedSync() -// - syncedItems() - -BaseItem.syncItemDefinitions_ = [{ type: BaseModel.TYPE_NOTE, className: 'Note' }, { type: BaseModel.TYPE_FOLDER, className: 'Folder' }, { type: BaseModel.TYPE_RESOURCE, className: 'Resource' }, { type: BaseModel.TYPE_TAG, className: 'Tag' }, { type: BaseModel.TYPE_NOTE_TAG, className: 'NoteTag' }, { type: BaseModel.TYPE_MASTER_KEY, className: 'MasterKey' }, { type: BaseModel.TYPE_REVISION, className: 'Revision' }]; - -BaseItem.SYNC_ITEM_LOCATION_LOCAL = 1; -BaseItem.SYNC_ITEM_LOCATION_REMOTE = 2; - -module.exports = BaseItem; diff --git a/packages/lib/models/Folder.js b/packages/lib/models/Folder.ts similarity index 82% rename from packages/lib/models/Folder.js rename to packages/lib/models/Folder.ts index b70714d14..db2a96b42 100644 --- a/packages/lib/models/Folder.js +++ b/packages/lib/models/Folder.ts @@ -1,12 +1,18 @@ -const BaseModel = require('../BaseModel').default; -const time = require('../time').default; -const Note = require('./Note.js'); +import { FolderEntity } from '../services/database/types'; +import BaseModel from '../BaseModel'; +import time from '../time'; +import { _ } from '../locale'; + +import Note from './Note'; const { Database } = require('../database.js'); -const { _ } = require('../locale'); -const BaseItem = require('./BaseItem.js'); +import BaseItem from './BaseItem'; const { substrWithEllipsis } = require('../string-utils.js'); -class Folder extends BaseItem { +interface FolderEntityWithChildren extends FolderEntity { + children?: FolderEntity[]; +} + +export default class Folder extends BaseItem { static tableName() { return 'folders'; } @@ -15,15 +21,15 @@ class Folder extends BaseItem { return BaseModel.TYPE_FOLDER; } - static newFolder() { + static newFolder(): FolderEntity { return { id: null, title: '', }; } - static fieldToLabel(field) { - const fieldsToLabels = { + static fieldToLabel(field: string) { + const fieldsToLabels: any = { title: _('title'), last_note_user_updated_time: _('updated date'), }; @@ -31,7 +37,7 @@ class Folder extends BaseItem { return field in fieldsToLabels ? fieldsToLabels[field] : field; } - static noteIds(parentId, options = null) { + static noteIds(parentId: string, options: any = null) { options = Object.assign({}, { includeConflicts: false, }, options); @@ -43,7 +49,7 @@ class Folder extends BaseItem { return this.db() .selectAll(`SELECT id FROM notes WHERE ${where.join(' AND ')}`, [parentId]) - .then(rows => { + .then((rows: any[]) => { const output = []; for (let i = 0; i < rows.length; i++) { const row = rows[i]; @@ -53,22 +59,22 @@ class Folder extends BaseItem { }); } - static async subFolderIds(parentId) { + static async subFolderIds(parentId: string) { const rows = await this.db().selectAll('SELECT id FROM folders WHERE parent_id = ?', [parentId]); - return rows.map(r => r.id); + return rows.map((r: FolderEntity) => r.id); } - static async noteCount(parentId) { + static async noteCount(parentId: string) { const r = await this.db().selectOne('SELECT count(*) as total FROM notes WHERE is_conflict = 0 AND parent_id = ?', [parentId]); return r ? r.total : 0; } - static markNotesAsConflict(parentId) { + static markNotesAsConflict(parentId: string) { const query = Database.updateQuery('notes', { is_conflict: 1 }, { parent_id: parentId }); return this.db().exec(query); } - static async delete(folderId, options = null) { + static async delete(folderId: string, options: any = null) { if (!options) options = {}; if (!('deleteChildren' in options)) options.deleteChildren = true; @@ -114,8 +120,8 @@ class Folder extends BaseItem { // Calculates note counts for all folders and adds the note_count attribute to each folder // Note: this only calculates the overall number of nodes for this folder and all its descendants - static async addNoteCounts(folders, includeCompletedTodos = true) { - const foldersById = {}; + static async addNoteCounts(folders: any[], includeCompletedTodos = true) { + const foldersById: any = {}; for (const f of folders) { foldersById[f.id] = f; @@ -137,7 +143,7 @@ class Folder extends BaseItem { `; const noteCounts = await this.db().selectAll(sql); - noteCounts.forEach((noteCount) => { + noteCounts.forEach((noteCount: any) => { let parentId = noteCount.folder_id; do { const folder = foldersById[parentId]; @@ -155,18 +161,18 @@ class Folder extends BaseItem { // Folders that contain notes that have been modified recently go on top. // The remaining folders, that don't contain any notes are sorted by their own user_updated_time - static async orderByLastModified(folders, dir = 'DESC') { + static async orderByLastModified(folders: FolderEntity[], dir = 'DESC') { dir = dir.toUpperCase(); const sql = 'select parent_id, max(user_updated_time) content_updated_time from notes where parent_id != "" group by parent_id'; const rows = await this.db().selectAll(sql); - const folderIdToTime = {}; + const folderIdToTime: Record = {}; for (let i = 0; i < rows.length; i++) { const row = rows[i]; folderIdToTime[row.parent_id] = row.content_updated_time; } - const findFolderParent = folderId => { + const findFolderParent = (folderId: string) => { const folder = BaseModel.byId(folders, folderId); if (!folder) return null; // For the rare case of notes that are associated with a no longer existing folder if (!folder.parent_id) return null; @@ -180,7 +186,7 @@ class Folder extends BaseItem { return null; }; - const applyChildTimeToParent = folderId => { + const applyChildTimeToParent = (folderId: string) => { const parent = findFolderParent(folderId); if (!parent) return; @@ -213,7 +219,7 @@ class Folder extends BaseItem { return output; } - static async all(options = null) { + static async all(options: any = null) { const output = await super.all(options); if (options && options.includeConflictFolder) { const conflictCount = await Note.conflictedCount(); @@ -222,24 +228,22 @@ class Folder extends BaseItem { return output; } - static async childrenIds(folderId, recursive) { - if (recursive === false) throw new Error('Not implemented'); - + static async childrenIds(folderId: string) { const folders = await this.db().selectAll('SELECT id FROM folders WHERE parent_id = ?', [folderId]); - let output = []; + let output: string[] = []; for (let i = 0; i < folders.length; i++) { const f = folders[i]; output.push(f.id); - const subChildrenIds = await this.childrenIds(f.id, true); + const subChildrenIds = await this.childrenIds(f.id); output = output.concat(subChildrenIds); } return output; } - static async expandTree(folders, parentId) { + static async expandTree(folders: FolderEntity[], parentId: string) { const folderPath = await this.folderPath(folders, parentId); folderPath.pop(); // We don't expand the leaft notebook @@ -252,11 +256,11 @@ class Folder extends BaseItem { } } - static async allAsTree(folders = null, options = null) { + static async allAsTree(folders: FolderEntity[] = null, options: any = null) { const all = folders ? folders : await this.all(options); // https://stackoverflow.com/a/49387427/561309 - function getNestedChildren(models, parentId) { + function getNestedChildren(models: FolderEntityWithChildren[], parentId: string) { const nestedTreeStructure = []; const length = models.length; @@ -280,8 +284,8 @@ class Folder extends BaseItem { return getNestedChildren(all, ''); } - static folderPath(folders, folderId) { - const idToFolders = {}; + static folderPath(folders: FolderEntity[], folderId: string) { + const idToFolders: Record = {}; for (let i = 0; i < folders.length; i++) { idToFolders[folders[i].id] = folders[i]; } @@ -299,7 +303,7 @@ class Folder extends BaseItem { return path; } - static folderPathString(folders, folderId, maxTotalLength = 80) { + static folderPathString(folders: FolderEntity[], folderId: string, maxTotalLength = 80) { const path = this.folderPath(folders, folderId); let currentTotalLength = 0; @@ -320,8 +324,8 @@ class Folder extends BaseItem { return output.join(' / '); } - static buildTree(folders) { - const idToFolders = {}; + static buildTree(folders: FolderEntity[]) { + const idToFolders: Record = {}; for (let i = 0; i < folders.length; i++) { idToFolders[folders[i].id] = Object.assign({}, folders[i]); idToFolders[folders[i].id].children = []; @@ -348,19 +352,20 @@ class Folder extends BaseItem { return rootFolders; } - static async sortFolderTree(folders) { + static async sortFolderTree(folders: FolderEntityWithChildren[] = null) { const output = folders ? folders : await this.allAsTree(); - const sortFoldersAlphabetically = (folders) => { - folders.sort((a, b) => { - if (a.parentId === b.parentId) { + const sortFoldersAlphabetically = (folders: FolderEntityWithChildren[]) => { + folders.sort((a: FolderEntityWithChildren, b: FolderEntityWithChildren) => { + if (a.parent_id === b.parent_id) { return a.title.localeCompare(b.title, undefined, { sensitivity: 'accent' }); } + return 0; }); return folders; }; - const sortFolders = (folders) => { + const sortFolders = (folders: FolderEntityWithChildren[]) => { for (let i = 0; i < folders.length; i++) { const folder = folders[i]; if (folder.children) { @@ -375,7 +380,7 @@ class Folder extends BaseItem { return output; } - static load(id) { + static load(id: string) { if (id == this.conflictFolderId()) return this.conflictFolder(); return super.load(id); } @@ -384,7 +389,7 @@ class Folder extends BaseItem { return this.modelSelectOne('SELECT * FROM folders ORDER BY created_time DESC LIMIT 1'); } - static async canNestUnder(folderId, targetFolderId) { + static async canNestUnder(folderId: string, targetFolderId: string) { if (folderId === targetFolderId) return false; const conflictFolderId = Folder.conflictFolderId(); @@ -402,7 +407,7 @@ class Folder extends BaseItem { return true; } - static async moveToFolder(folderId, targetFolderId) { + static async moveToFolder(folderId: string, targetFolderId: string) { if (!(await this.canNestUnder(folderId, targetFolderId))) throw new Error(_('Cannot move notebook to this location')); // When moving a note to a different folder, the user timestamp is not updated. @@ -421,7 +426,7 @@ class Folder extends BaseItem { // manually creating a folder. They shouldn't be done for example when the folders // are being synced to avoid any strange side-effects. Technically it's possible to // have folders and notes with duplicate titles (or no title), or with reserved words. - static async save(o, options = null) { + static async save(o: FolderEntity, options: any = null) { if (!options) options = {}; if (options.userSideValidation === true) { @@ -458,7 +463,7 @@ class Folder extends BaseItem { if (o.title == Folder.conflictFolderTitle()) throw new Error(_('Notebooks cannot be named "%s", which is a reserved title.', o.title)); } - return super.save(o, options).then(folder => { + return super.save(o, options).then((folder: FolderEntity) => { this.dispatch({ type: 'FOLDER_UPDATE_ONE', item: folder, @@ -467,5 +472,3 @@ class Folder extends BaseItem { }); } } - -module.exports = Folder; diff --git a/packages/lib/models/ItemChange.js b/packages/lib/models/ItemChange.ts similarity index 70% rename from packages/lib/models/ItemChange.js rename to packages/lib/models/ItemChange.ts index ad122e2b6..3ce8ff553 100644 --- a/packages/lib/models/ItemChange.js +++ b/packages/lib/models/ItemChange.ts @@ -1,9 +1,21 @@ -const BaseModel = require('../BaseModel').default; +import BaseModel, { ModelType } from '../BaseModel'; +import shim from '../shim'; +import eventManager from '../eventManager'; const Mutex = require('async-mutex').Mutex; -const shim = require('../shim').default; -const eventManager = require('../eventManager').default; -class ItemChange extends BaseModel { +export default class ItemChange extends BaseModel { + + private static addChangeMutex_: any = new Mutex(); + private static saveCalls_: any[] = []; + + public static TYPE_CREATE = 1; + public static TYPE_UPDATE = 2; + public static TYPE_DELETE = 3; + + public static SOURCE_UNSPECIFIED = 1; + public static SOURCE_SYNC = 2; + public static SOURCE_DECRYPTION = 2; // CAREFUL - SAME ID AS SOURCE_SYNC! + static tableName() { return 'item_changes'; } @@ -12,7 +24,7 @@ class ItemChange extends BaseModel { return BaseModel.TYPE_ITEM_CHANGE; } - static async add(itemType, itemId, type, changeSource = null, beforeChangeItemJson = null) { + static async add(itemType: ModelType, itemId: string, type: number, changeSource: any = null, beforeChangeItemJson: string = null) { if (changeSource === null) changeSource = ItemChange.SOURCE_UNSPECIFIED; if (!beforeChangeItemJson) beforeChangeItemJson = ''; @@ -57,27 +69,14 @@ class ItemChange extends BaseModel { const iid = shim.setInterval(() => { if (!ItemChange.saveCalls_.length) { shim.clearInterval(iid); - resolve(); + resolve(null); } }, 100); }); } - static async deleteOldChanges(lowestChangeId) { + static async deleteOldChanges(lowestChangeId: number) { if (!lowestChangeId) return; return this.db().exec('DELETE FROM item_changes WHERE id <= ?', [lowestChangeId]); } } - -ItemChange.addChangeMutex_ = new Mutex(); -ItemChange.saveCalls_ = []; - -ItemChange.TYPE_CREATE = 1; -ItemChange.TYPE_UPDATE = 2; -ItemChange.TYPE_DELETE = 3; - -ItemChange.SOURCE_UNSPECIFIED = 1; -ItemChange.SOURCE_SYNC = 2; -ItemChange.SOURCE_DECRYPTION = 2; // CAREFUL - SAME ID AS SOURCE_SYNC! - -module.exports = ItemChange; diff --git a/packages/lib/models/MasterKey.js b/packages/lib/models/MasterKey.ts similarity index 61% rename from packages/lib/models/MasterKey.js rename to packages/lib/models/MasterKey.ts index 68f6ff3ac..cad44c834 100644 --- a/packages/lib/models/MasterKey.js +++ b/packages/lib/models/MasterKey.ts @@ -1,7 +1,8 @@ -const BaseModel = require('../BaseModel').default; -const BaseItem = require('./BaseItem.js'); +import BaseModel from '../BaseModel'; +import { MasterKeyEntity } from '../services/database/types'; +import BaseItem from './BaseItem'; -class MasterKey extends BaseItem { +export default class MasterKey extends BaseItem { static tableName() { return 'master_keys'; } @@ -18,11 +19,11 @@ class MasterKey extends BaseItem { return this.modelSelectOne('SELECT * FROM master_keys WHERE created_time >= (SELECT max(created_time) FROM master_keys)'); } - static allWithoutEncryptionMethod(masterKeys, method) { + static allWithoutEncryptionMethod(masterKeys: MasterKeyEntity[], method: number) { return masterKeys.filter(m => m.encryption_method !== method); } - static async save(o, options = null) { + static async save(o: MasterKeyEntity, options: any = null) { return super.save(o, options).then(item => { this.dispatch({ type: 'MASTERKEY_UPDATE_ONE', @@ -32,5 +33,3 @@ class MasterKey extends BaseItem { }); } } - -module.exports = MasterKey; diff --git a/packages/lib/models/Migration.js b/packages/lib/models/Migration.ts similarity index 74% rename from packages/lib/models/Migration.js rename to packages/lib/models/Migration.ts index 06a852df8..9ecb1b190 100644 --- a/packages/lib/models/Migration.js +++ b/packages/lib/models/Migration.ts @@ -1,12 +1,12 @@ -const BaseModel = require('../BaseModel').default; +import BaseModel from '../BaseModel'; -const migrationScripts = { +const migrationScripts: Record = { 20: require('../migrations/20.js'), 27: require('../migrations/27.js'), 33: require('../migrations/33.js'), }; -class Migration extends BaseModel { +export default class Migration extends BaseModel { static tableName() { return 'migrations'; } @@ -19,10 +19,8 @@ class Migration extends BaseModel { return this.modelSelectAll('SELECT * FROM migrations ORDER BY number ASC'); } - static script(number) { + static script(number: number) { if (!migrationScripts[number]) throw new Error('Migration script has not been added to "migrationScripts" array'); return migrationScripts[number]; } } - -module.exports = Migration; diff --git a/packages/lib/models/Note.js b/packages/lib/models/Note.ts similarity index 87% rename from packages/lib/models/Note.js rename to packages/lib/models/Note.ts index e0ab13181..403a7a23f 100644 --- a/packages/lib/models/Note.js +++ b/packages/lib/models/Note.ts @@ -1,28 +1,36 @@ -const BaseModel = require('../BaseModel').default; +import BaseModel, { ModelType } from '../BaseModel'; +import BaseItem from './BaseItem'; +import ItemChange from './ItemChange'; +import Setting from './Setting'; +import shim from '../shim'; +import time from '../time'; +import markdownUtils from '../markdownUtils'; +import { NoteEntity } from '../services/database/types'; + const { sprintf } = require('sprintf-js'); -const BaseItem = require('./BaseItem.js'); -const ItemChange = require('./ItemChange.js'); -const Resource = require('./Resource.js'); -const Setting = require('./Setting').default; -const shim = require('../shim').default; +import Resource from './Resource'; const { pregQuote } = require('../string-utils.js'); -const time = require('../time').default; const { _ } = require('../locale'); const ArrayUtils = require('../ArrayUtils.js'); const lodash = require('lodash'); const urlUtils = require('../urlUtils.js'); -const markdownUtils = require('../markdownUtils').default; const { isImageMimeType } = require('../resourceUtils'); const { MarkupToHtml } = require('@joplin/renderer'); const { ALL_NOTES_FILTER_ID } = require('../reserved-ids'); -class Note extends BaseItem { +export default class Note extends BaseItem { + + public static updateGeolocationEnabled_ = true; + private static geolocationUpdating_ = false; + private static geolocationCache_: any; + private static dueDateObjects_: any; + static tableName() { return 'notes'; } - static fieldToLabel(field) { - const fieldsToLabels = { + static fieldToLabel(field: string) { + const fieldsToLabels: Record = { title: _('title'), user_updated_time: _('updated date'), user_created_time: _('created date'), @@ -32,11 +40,11 @@ class Note extends BaseItem { return field in fieldsToLabels ? fieldsToLabels[field] : field; } - static async serializeForEdit(note) { + static async serializeForEdit(note: NoteEntity) { return this.replaceResourceInternalToExternalLinks(await super.serialize(note, ['title', 'body'])); } - static async unserializeForEdit(content) { + static async unserializeForEdit(content: string) { content += `\n\ntype_: ${BaseModel.TYPE_NOTE}`; const output = await super.unserialize(content); if (!output.title) output.title = ''; @@ -45,14 +53,14 @@ class Note extends BaseItem { return output; } - static async serializeAllProps(note) { + static async serializeAllProps(note: NoteEntity) { const fieldNames = this.fieldNames(); fieldNames.push('type_'); lodash.pull(fieldNames, 'title', 'body'); return super.serialize(note, fieldNames); } - static minimalSerializeForDisplay(note) { + static minimalSerializeForDisplay(note: NoteEntity) { const n = Object.assign({}, note); const fieldNames = this.fieldNames(); @@ -80,21 +88,21 @@ class Note extends BaseItem { return super.serialize(n, fieldNames); } - static defaultTitle(noteBody) { + static defaultTitle(noteBody: string) { return this.defaultTitleFromBody(noteBody); } - static defaultTitleFromBody(body) { + static defaultTitleFromBody(body: string) { return markdownUtils.titleFromBody(body); } - static geolocationUrl(note) { + static geolocationUrl(note: NoteEntity) { if (!('latitude' in note) || !('longitude' in note)) throw new Error('Latitude or longitude is missing'); if (!Number(note.latitude) && !Number(note.longitude)) throw new Error(_('This note does not have geolocation information.')); return this.geoLocationUrlFromLatLong(note.latitude, note.longitude); } - static geoLocationUrlFromLatLong(lat, long) { + static geoLocationUrlFromLatLong(lat: number, long: number) { return sprintf('https://www.openstreetmap.org/?lat=%s&lon=%s&zoom=20', lat, long); } @@ -102,21 +110,21 @@ class Note extends BaseItem { return BaseModel.TYPE_NOTE; } - static linkedItemIds(body) { + static linkedItemIds(body: string) { if (!body || body.length <= 32) return []; const links = urlUtils.extractResourceUrls(body); - const itemIds = links.map(l => l.itemId); + const itemIds = links.map((l: any) => l.itemId); return ArrayUtils.unique(itemIds); } - static async linkedItems(body) { + static async linkedItems(body: string) { const itemIds = this.linkedItemIds(body); const r = await BaseItem.loadItemsByIds(itemIds); return r; } - static async linkedItemIdsByType(type, body) { + static async linkedItemIdsByType(type: ModelType, body: string) { const items = await this.linkedItems(body); const output = []; @@ -128,15 +136,15 @@ class Note extends BaseItem { return output; } - static async linkedResourceIds(body) { + static async linkedResourceIds(body: string) { return this.linkedItemIdsByType(BaseModel.TYPE_RESOURCE, body); } - static async linkedNoteIds(body) { + static async linkedNoteIds(body: string) { return this.linkedItemIdsByType(BaseModel.TYPE_NOTE, body); } - static async replaceResourceInternalToExternalLinks(body, options = null) { + static async replaceResourceInternalToExternalLinks(body: string, options: any = null) { options = Object.assign({}, { useAbsolutePaths: false, }, options); @@ -166,7 +174,7 @@ class Note extends BaseItem { return body; } - static async replaceResourceExternalToInternalLinks(body, options = null) { + static async replaceResourceExternalToInternalLinks(body: string, options: any = null) { options = Object.assign({}, { useAbsolutePaths: false, }, options); @@ -233,19 +241,19 @@ class Note extends BaseItem { } // Note: sort logic must be duplicated in previews(); - static sortNotes(notes, orders, uncompletedTodosOnTop) { - const noteOnTop = note => { + static sortNotes(notes: NoteEntity[], orders: any[], uncompletedTodosOnTop: boolean) { + const noteOnTop = (note: NoteEntity) => { return uncompletedTodosOnTop && note.is_todo && !note.todo_completed; }; - const noteFieldComp = (f1, f2) => { + const noteFieldComp = (f1: any, f2: any) => { if (f1 === f2) return 0; return f1 < f2 ? -1 : +1; }; // Makes the sort deterministic, so that if, for example, a and b have the // same updated_time, they aren't swapped every time a list is refreshed. - const sortIdenticalNotes = (a, b) => { + const sortIdenticalNotes = (a: NoteEntity, b: NoteEntity) => { let r = null; r = noteFieldComp(a.user_updated_time, b.user_updated_time); if (r) return r; @@ -262,7 +270,7 @@ class Note extends BaseItem { const collator = this.getNaturalSortingCollator(); - return notes.sort((a, b) => { + return notes.sort((a: NoteEntity, b: NoteEntity) => { if (noteOnTop(a) && !noteOnTop(b)) return -1; if (!noteOnTop(a) && noteOnTop(b)) return +1; @@ -270,8 +278,8 @@ class Note extends BaseItem { for (let i = 0; i < orders.length; i++) { const order = orders[i]; - let aProp = a[order.by]; - let bProp = b[order.by]; + let aProp = (a as any)[order.by]; + let bProp = (b as any)[order.by]; if (typeof aProp === 'string') aProp = aProp.toLowerCase(); if (typeof bProp === 'string') bProp = bProp.toLowerCase(); @@ -289,11 +297,11 @@ class Note extends BaseItem { }); } - static previewFieldsWithDefaultValues(options = null) { + static previewFieldsWithDefaultValues(options: any = null) { return Note.defaultValues(this.previewFields(options)); } - static previewFields(options = null) { + static previewFields(options: any = null) { options = Object.assign({ includeTimestamps: true, }, options); @@ -309,12 +317,12 @@ class Note extends BaseItem { return output; } - static previewFieldsSql(fields = null) { + static previewFieldsSql(fields: string[] = null) { if (fields === null) fields = this.previewFields(); return this.db().escapeFields(fields).join(','); } - static async loadFolderNoteByField(folderId, field, value) { + static async loadFolderNoteByField(folderId: string, field: string, value: any) { if (!folderId) throw new Error('folderId is undefined'); const options = { @@ -327,7 +335,7 @@ class Note extends BaseItem { return results.length ? results[0] : null; } - static async previews(parentId, options = null) { + static async previews(parentId: string, options: any = null) { // Note: ordering logic must be duplicated in sortNotes(), which is used // to sort already loaded notes. @@ -416,12 +424,12 @@ class Note extends BaseItem { return results; } - static preview(noteId, options = null) { + static preview(noteId: string, options: any = null) { if (!options) options = { fields: null }; return this.modelSelectOne(`SELECT ${this.previewFieldsSql(options.fields)} FROM notes WHERE is_conflict = 0 AND id = ?`, [noteId]); } - static async search(options = null) { + static async search(options: any = null) { if (!options) options = {}; if (!options.conditions) options.conditions = []; if (!options.conditionsParams) options.conditionsParams = []; @@ -448,7 +456,7 @@ class Note extends BaseItem { return this.modelSelectAll('SELECT * FROM notes WHERE is_conflict = 0'); } - static async updateGeolocation(noteId) { + static async updateGeolocation(noteId: string) { if (!Setting.value('trackLocation')) return; if (!Note.updateGeolocationEnabled_) return; @@ -496,7 +504,7 @@ class Note extends BaseItem { return Note.save(note); } - static filter(note) { + static filter(note: NoteEntity) { if (!note) return note; const output = super.filter(note); @@ -506,7 +514,7 @@ class Note extends BaseItem { return output; } - static async copyToFolder(noteId, folderId) { + static async copyToFolder(noteId: string, folderId: string) { if (folderId == this.getClass('Folder').conflictFolderId()) throw new Error(_('Cannot copy note to "%s" notebook', this.getClass('Folder').conflictFolderTitle())); return Note.duplicate(noteId, { @@ -517,7 +525,7 @@ class Note extends BaseItem { }); } - static async moveToFolder(noteId, folderId) { + static async moveToFolder(noteId: string, folderId: string) { if (folderId == this.getClass('Folder').conflictFolderId()) throw new Error(_('Cannot move note to "%s" notebook', this.getClass('Folder').conflictFolderTitle())); // When moving a note to a different folder, the user timestamp is not updated. @@ -533,7 +541,7 @@ class Note extends BaseItem { return Note.save(modifiedNote, { autoTimestamp: false }); } - static changeNoteType(note, type) { + static changeNoteType(note: NoteEntity, type: string) { if (!('is_todo' in note)) throw new Error('Missing "is_todo" property'); const newIsTodo = type === 'todo' ? 1 : 0; @@ -548,11 +556,11 @@ class Note extends BaseItem { return output; } - static toggleIsTodo(note) { + static toggleIsTodo(note: NoteEntity) { return this.changeNoteType(note, note.is_todo ? 'note' : 'todo'); } - static toggleTodoCompleted(note) { + static toggleTodoCompleted(note: NoteEntity) { if (!('todo_completed' in note)) throw new Error('Missing "todo_completed" property'); note = Object.assign({}, note); @@ -565,12 +573,12 @@ class Note extends BaseItem { return note; } - static async duplicateMultipleNotes(noteIds, options = null) { + static async duplicateMultipleNotes(noteIds: string[], options: any = null) { // if options.uniqueTitle is true, a unique title for the duplicated file will be assigned. const ensureUniqueTitle = options && options.ensureUniqueTitle; for (const noteId of noteIds) { - const noteOptions = {}; + const noteOptions: any = {}; // If ensureUniqueTitle is truthy, set the original note's name as root for the unique title. if (ensureUniqueTitle) { @@ -582,7 +590,7 @@ class Note extends BaseItem { } } - static async duplicate(noteId, options = null) { + static async duplicate(noteId: string, options: any = null) { const changes = options && options.changes; const uniqueTitle = options && options.uniqueTitle; @@ -609,13 +617,13 @@ class Note extends BaseItem { return this.save(newNote); } - static async noteIsOlderThan(noteId, date) { + static async noteIsOlderThan(noteId: string, date: number) { const n = await this.db().selectOne('SELECT updated_time FROM notes WHERE id = ?', [noteId]); if (!n) throw new Error(`No such note: ${noteId}`); return n.updated_time < date; } - static async save(o, options = null) { + static async save(o: NoteEntity, options: any = null) { const isNew = this.isNew(o, options); const isProvisional = options && !!options.provisional; const dispatchUpdateAction = options ? options.dispatchUpdateAction !== false : true; @@ -647,7 +655,7 @@ class Note extends BaseItem { if (oldNote) { for (const field in o) { if (!o.hasOwnProperty(field)) continue; - if (o[field] !== oldNote[field]) { + if ((o as any)[field] !== oldNote[field]) { changedFields.push(field); } } @@ -656,7 +664,7 @@ class Note extends BaseItem { const note = await super.save(o, options); const changeSource = options && options.changeSource ? options.changeSource : null; - ItemChange.add(BaseModel.TYPE_NOTE, note.id, isNew ? ItemChange.TYPE_CREATE : ItemChange.TYPE_UPDATE, changeSource, beforeNoteJson); + void ItemChange.add(BaseModel.TYPE_NOTE, note.id, isNew ? ItemChange.TYPE_CREATE : ItemChange.TYPE_UPDATE, changeSource, beforeNoteJson); if (dispatchUpdateAction) { this.dispatch({ @@ -677,14 +685,14 @@ class Note extends BaseItem { return note; } - static async batchDelete(ids, options = null) { + static async batchDelete(ids: string[], options: any = null) { ids = ids.slice(); while (ids.length) { const processIds = ids.splice(0, 50); const notes = await Note.byIds(processIds); - const beforeChangeItems = {}; + const beforeChangeItems: any = {}; for (const note of notes) { beforeChangeItems[note.id] = JSON.stringify(note); } @@ -693,7 +701,7 @@ class Note extends BaseItem { const changeSource = options && options.changeSource ? options.changeSource : null; for (let i = 0; i < processIds.length; i++) { const id = processIds[i]; - ItemChange.add(BaseModel.TYPE_NOTE, id, ItemChange.TYPE_DELETE, changeSource, beforeChangeItems[id]); + void ItemChange.add(BaseModel.TYPE_NOTE, id, ItemChange.TYPE_DELETE, changeSource, beforeChangeItems[id]); this.dispatch({ type: 'NOTE_DELETE', @@ -707,11 +715,11 @@ class Note extends BaseItem { return this.modelSelectAll('SELECT id, title, body, is_todo, todo_due, todo_completed, is_conflict FROM notes WHERE is_conflict = 0 AND is_todo = 1 AND todo_completed = 0 AND todo_due > ?', [time.unixMs()]); } - static needAlarm(note) { + static needAlarm(note: NoteEntity) { return note.is_todo && !note.todo_completed && note.todo_due >= time.unixMs() && !note.is_conflict; } - static dueDateObject(note) { + static dueDateObject(note: NoteEntity) { if (!!note.is_todo && note.todo_due) { if (!this.dueDateObjects_) this.dueDateObjects_ = {}; if (this.dueDateObjects_[note.todo_due]) return this.dueDateObjects_[note.todo_due]; @@ -723,7 +731,7 @@ class Note extends BaseItem { } // Tells whether the conflict between the local and remote note can be ignored. - static mustHandleConflict(localNote, remoteNote) { + static mustHandleConflict(localNote: NoteEntity, remoteNote: NoteEntity) { // That shouldn't happen so throw an exception if (localNote.id !== remoteNote.id) throw new Error('Cannot handle conflict for two different notes'); @@ -737,7 +745,7 @@ class Note extends BaseItem { return false; } - static markupLanguageToLabel(markupLanguageId) { + static markupLanguageToLabel(markupLanguageId: number) { if (markupLanguageId === MarkupToHtml.MARKUP_LANGUAGE_MARKDOWN) return 'Markdown'; if (markupLanguageId === MarkupToHtml.MARKUP_LANGUAGE_HTML) return 'HTML'; throw new Error(`Invalid markup language ID: ${markupLanguageId}`); @@ -745,7 +753,7 @@ class Note extends BaseItem { // When notes are sorted in "custom order", they are sorted by the "order" field first and, // in those cases, where the order field is the same for some notes, by created time. - static customOrderByColumns(type = null) { + static customOrderByColumns(type: string = null) { if (!type) type = 'object'; if (type === 'object') return [{ by: 'order', dir: 'DESC' }, { by: 'user_created_time', dir: 'DESC' }]; if (type === 'string') return 'ORDER BY `order` DESC, user_created_time DESC'; @@ -754,7 +762,7 @@ class Note extends BaseItem { // Update the note "order" field without changing the user timestamps, // which is generally what we want. - static async updateNoteOrder_(note, order) { + static async updateNoteOrder_(note: NoteEntity, order: any) { return Note.save(Object.assign({}, note, { order: order, user_updated_time: note.user_updated_time, @@ -765,7 +773,7 @@ class Note extends BaseItem { // of unecessary updates, so it's the caller's responsability to update // the UI once the call is finished. This is done by listening to the // NOTE_IS_INSERTING_NOTES action in the application middleware. - static async insertNotesAt(folderId, noteIds, index) { + static async insertNotesAt(folderId: string, noteIds: string[], index: number) { if (!noteIds.length) return; const defer = () => { @@ -874,7 +882,7 @@ class Note extends BaseItem { } } - static handleTitleNaturalSorting(items, options) { + static handleTitleNaturalSorting(items: NoteEntity[], options: any) { if (options.order.length > 0 && options.order[0].by === 'title') { const collator = this.getNaturalSortingCollator(); items.sort((a, b) => ((options.order[0].dir === 'ASC') ? 1 : -1) * collator.compare(a.title, b.title)); @@ -886,8 +894,3 @@ class Note extends BaseItem { } } - -Note.updateGeolocationEnabled_ = true; -Note.geolocationUpdating_ = false; - -module.exports = Note; diff --git a/packages/lib/models/NoteTag.js b/packages/lib/models/NoteTag.ts similarity index 67% rename from packages/lib/models/NoteTag.js rename to packages/lib/models/NoteTag.ts index ace90d2b2..354c4945b 100644 --- a/packages/lib/models/NoteTag.js +++ b/packages/lib/models/NoteTag.ts @@ -1,7 +1,7 @@ -const BaseItem = require('./BaseItem.js'); -const BaseModel = require('../BaseModel').default; +import BaseItem from './BaseItem'; +import BaseModel from '../BaseModel'; -class NoteTag extends BaseItem { +export default class NoteTag extends BaseItem { static tableName() { return 'note_tags'; } @@ -10,12 +10,12 @@ class NoteTag extends BaseItem { return BaseModel.TYPE_NOTE_TAG; } - static async byNoteIds(noteIds) { + static async byNoteIds(noteIds: string[]) { if (!noteIds.length) return []; return this.modelSelectAll(`SELECT * FROM note_tags WHERE note_id IN ("${noteIds.join('","')}")`); } - static async tagIdsByNoteId(noteId) { + static async tagIdsByNoteId(noteId: string) { const rows = await this.db().selectAll('SELECT tag_id FROM note_tags WHERE note_id = ?', [noteId]); const output = []; for (let i = 0; i < rows.length; i++) { @@ -24,5 +24,3 @@ class NoteTag extends BaseItem { return output; } } - -module.exports = NoteTag; diff --git a/packages/lib/models/Resource.js b/packages/lib/models/Resource.ts similarity index 83% rename from packages/lib/models/Resource.js rename to packages/lib/models/Resource.ts index 20b9db4cd..474a59235 100644 --- a/packages/lib/models/Resource.js +++ b/packages/lib/models/Resource.ts @@ -1,18 +1,29 @@ -const BaseModel = require('../BaseModel').default; -const BaseItem = require('./BaseItem.js'); -const ItemChange = require('./ItemChange.js'); -const NoteResource = require('./NoteResource').default; -const ResourceLocalState = require('./ResourceLocalState.js'); -const Setting = require('./Setting').default; +import BaseModel from '../BaseModel'; +import BaseItem from './BaseItem'; +import ItemChange from './ItemChange'; +import NoteResource from './NoteResource'; +import Setting from './Setting'; +import markdownUtils from '../markdownUtils'; +import { _ } from '../locale'; +import { ResourceEntity, ResourceLocalStateEntity } from '../services/database/types'; +import ResourceLocalState from './ResourceLocalState'; const pathUtils = require('../path-utils'); const { mime } = require('../mime-utils.js'); const { filename, safeFilename } = require('../path-utils'); const { FsDriverDummy } = require('../fs-driver-dummy.js'); -const markdownUtils = require('../markdownUtils').default; const JoplinError = require('../JoplinError'); -const { _ } = require('../locale'); -class Resource extends BaseItem { +export default class Resource extends BaseItem { + + public static IMAGE_MAX_DIMENSION = 1920; + + public static FETCH_STATUS_IDLE = 0; + public static FETCH_STATUS_STARTED = 1; + public static FETCH_STATUS_DONE = 2; + public static FETCH_STATUS_ERROR = 3; + + public static fsDriver_: any; + static tableName() { return 'resources'; } @@ -26,12 +37,12 @@ class Resource extends BaseItem { return this.encryptionService_; } - static isSupportedImageMimeType(type) { + static isSupportedImageMimeType(type: string) { const imageMimeTypes = ['image/jpg', 'image/jpeg', 'image/png', 'image/gif', 'image/svg+xml', 'image/webp']; return imageMimeTypes.indexOf(type.toLowerCase()) >= 0; } - static fetchStatuses(resourceIds) { + static fetchStatuses(resourceIds: string[]) { if (!resourceIds.length) return []; return this.db().selectAll(`SELECT resource_id, fetch_status FROM resource_local_states WHERE resource_id IN ("${resourceIds.join('","')}")`); } @@ -45,7 +56,7 @@ class Resource extends BaseItem { `, [Resource.FETCH_STATUS_ERROR]); } - static needToBeFetched(resourceDownloadMode = null, limit = null) { + static needToBeFetched(resourceDownloadMode: string = null, limit: number = null) { const sql = ['SELECT * FROM resources WHERE encryption_applied = 0 AND id IN (SELECT resource_id FROM resource_local_states WHERE fetch_status = ?)']; if (resourceDownloadMode !== 'always') { sql.push('AND resources.id IN (SELECT resource_id FROM resources_to_download)'); @@ -59,7 +70,7 @@ class Resource extends BaseItem { return await this.db().exec('UPDATE resource_local_states SET fetch_status = ? WHERE fetch_status = ?', [Resource.FETCH_STATUS_IDLE, Resource.FETCH_STATUS_STARTED]); } - static resetErrorStatus(resourceId) { + static resetErrorStatus(resourceId: string) { return this.db().exec('UPDATE resource_local_states SET fetch_status = ?, fetch_error = "" WHERE resource_id = ?', [Resource.FETCH_STATUS_IDLE, resourceId]); } @@ -69,7 +80,7 @@ class Resource extends BaseItem { } // DEPRECATED IN FAVOUR OF friendlySafeFilename() - static friendlyFilename(resource) { + static friendlyFilename(resource: ResourceEntity) { let output = safeFilename(resource.title); // Make sure not to allow spaces or any special characters as it's not supported in HTTP headers if (!output) output = resource.id; let extension = resource.file_extension; @@ -86,14 +97,14 @@ class Resource extends BaseItem { return Setting.value('resourceDirName'); } - static filename(resource, encryptedBlob = false) { + static filename(resource: ResourceEntity, encryptedBlob = false) { let extension = encryptedBlob ? 'crypted' : resource.file_extension; if (!extension) extension = resource.mime ? mime.toFileExtension(resource.mime) : ''; extension = extension ? `.${extension}` : ''; return resource.id + extension; } - static friendlySafeFilename(resource) { + static friendlySafeFilename(resource: ResourceEntity) { let ext = resource.file_extension; if (!ext) ext = resource.mime ? mime.toFileExtension(resource.mime) : ''; const safeExt = ext ? pathUtils.safeFileExtension(ext).toLowerCase() : ''; @@ -102,20 +113,20 @@ class Resource extends BaseItem { return pathUtils.friendlySafeFilename(title) + (safeExt ? `.${safeExt}` : ''); } - static relativePath(resource, encryptedBlob = false) { + static relativePath(resource: ResourceEntity, encryptedBlob = false) { return `${Setting.value('resourceDirName')}/${this.filename(resource, encryptedBlob)}`; } - static fullPath(resource, encryptedBlob = false) { + static fullPath(resource: ResourceEntity, encryptedBlob = false) { return `${Setting.value('resourceDir')}/${this.filename(resource, encryptedBlob)}`; } - static async isReady(resource) { + static async isReady(resource: ResourceEntity) { const r = await this.readyStatus(resource); return r === 'ok'; } - static async readyStatus(resource) { + static async readyStatus(resource: ResourceEntity) { const ls = await this.localState(resource); if (!resource) return 'notFound'; if (ls.fetch_status !== Resource.FETCH_STATUS_DONE) return 'notDownloaded'; @@ -123,13 +134,13 @@ class Resource extends BaseItem { return 'ok'; } - static async requireIsReady(resource) { + static async requireIsReady(resource: ResourceEntity) { const readyStatus = await Resource.readyStatus(resource); if (readyStatus !== 'ok') throw new Error(`Resource is not ready. Status: ${readyStatus}`); } // For resources, we need to decrypt the item (metadata) and the resource binary blob. - static async decrypt(item) { + static async decrypt(item: ResourceEntity) { // The item might already be decrypted but not the blob (for instance if it crashes while // decrypting the blob or was otherwise interrupted). const decryptedItem = item.encryption_cipher_text ? await super.decrypt(item) : Object.assign({}, item); @@ -177,7 +188,7 @@ class Resource extends BaseItem { // as it should be uploaded to the sync target. Note that this may be different from what is stored // in the database. In particular, the flag encryption_blob_encrypted might be 1 on the sync target // if the resource is encrypted, but will be 0 locally because the device has the decrypted resource. - static async fullPathForSyncUpload(resource) { + static async fullPathForSyncUpload(resource: ResourceEntity) { const plainTextPath = this.fullPath(resource); if (!Setting.value('encryption.enabled')) { @@ -201,7 +212,7 @@ class Resource extends BaseItem { return { path: encryptedPath, resource: resourceCopy }; } - static markdownTag(resource) { + static markdownTag(resource: any) { let tagAlt = resource.alt ? resource.alt : resource.title; if (!tagAlt) tagAlt = ''; const lines = []; @@ -217,36 +228,36 @@ class Resource extends BaseItem { return lines.join(''); } - static internalUrl(resource) { + static internalUrl(resource: ResourceEntity) { return `:/${resource.id}`; } - static pathToId(path) { + static pathToId(path: string) { return filename(path); } - static async content(resource) { + static async content(resource: ResourceEntity) { return this.fsDriver().readFile(this.fullPath(resource), 'Buffer'); } - static setContent(resource, content) { + static setContent(resource: ResourceEntity, content: any) { return this.fsDriver().writeBinaryFile(this.fullPath(resource), content); } - static isResourceUrl(url) { + static isResourceUrl(url: string) { return url && url.length === 34 && url[0] === ':' && url[1] === '/'; } - static urlToId(url) { + static urlToId(url: string) { if (!this.isResourceUrl(url)) throw new Error(`Not a valid resource URL: ${url}`); return url.substr(2); } - static async localState(resourceOrId) { + static async localState(resourceOrId: any) { return ResourceLocalState.byResourceId(typeof resourceOrId === 'object' ? resourceOrId.id : resourceOrId); } - static async setLocalState(resourceOrId, state) { + static async setLocalState(resourceOrId: any, state: ResourceLocalStateEntity) { const id = typeof resourceOrId === 'object' ? resourceOrId.id : resourceOrId; await ResourceLocalState.save(Object.assign({}, state, { resource_id: id })); } @@ -258,11 +269,11 @@ class Resource extends BaseItem { // Only set the `size` field and nothing else, not even the update_time // This is because it's only necessary to do it once after migration 20 // and each client does it so there's no need to sync the resource. - static async setFileSizeOnly(resourceId, fileSize) { + static async setFileSizeOnly(resourceId: string, fileSize: number) { return this.db().exec('UPDATE resources set `size` = ? WHERE id = ?', [fileSize, resourceId]); } - static async batchDelete(ids, options = null) { + static async batchDelete(ids: string[], options: any = null) { // For resources, there's not really batch deleting since there's the file data to delete // too, so each is processed one by one with the item being deleted last (since the db // call is the less likely to fail). @@ -280,13 +291,13 @@ class Resource extends BaseItem { await ResourceLocalState.batchDelete(ids); } - static async markForDownload(resourceId) { + static async markForDownload(resourceId: string) { // Insert the row only if it's not already there const t = Date.now(); await this.db().exec('INSERT INTO resources_to_download (resource_id, updated_time, created_time) SELECT ?, ?, ? WHERE NOT EXISTS (SELECT 1 FROM resources_to_download WHERE resource_id = ?)', [resourceId, t, t, resourceId]); } - static async downloadedButEncryptedBlobCount(excludedIds = null) { + static async downloadedButEncryptedBlobCount(excludedIds: string[] = null) { let excludedSql = ''; if (excludedIds && excludedIds.length) { excludedSql = `AND resource_id NOT IN ("${excludedIds.join('","')}")`; @@ -303,7 +314,7 @@ class Resource extends BaseItem { return r ? r.total : 0; } - static async downloadStatusCounts(status) { + static async downloadStatusCounts(status: number) { const r = await this.db().selectOne(` SELECT count(*) as total FROM resource_local_states @@ -324,7 +335,7 @@ class Resource extends BaseItem { return r ? r.total : 0; } - static fetchStatusToLabel(status) { + static fetchStatusToLabel(status: number) { if (status === Resource.FETCH_STATUS_IDLE) return _('Not downloaded'); if (status === Resource.FETCH_STATUS_STARTED) return _('Downloading'); if (status === Resource.FETCH_STATUS_DONE) return _('Downloaded'); @@ -332,7 +343,7 @@ class Resource extends BaseItem { throw new Error(`Invalid status: ${status}`); } - static async updateResourceBlobContent(resourceId, newBlobFilePath) { + static async updateResourceBlobContent(resourceId: string, newBlobFilePath: string) { const resource = await Resource.load(resourceId); await this.requireIsReady(resource); @@ -345,13 +356,13 @@ class Resource extends BaseItem { }); } - static async resourceBlobContent(resourceId, encoding = 'Buffer') { + static async resourceBlobContent(resourceId: string, encoding = 'Buffer') { const resource = await Resource.load(resourceId); await this.requireIsReady(resource); return await this.fsDriver().readFile(Resource.fullPath(resource), encoding); } - static async duplicateResource(resourceId) { + static async duplicateResource(resourceId: string) { const resource = await Resource.load(resourceId); const localState = await Resource.localState(resource); @@ -373,7 +384,7 @@ class Resource extends BaseItem { return newResource; } - static async createConflictResourceNote(resource) { + static async createConflictResourceNote(resource: ResourceEntity) { const Note = this.getClass('Note'); const conflictResource = await Resource.duplicateResource(resource.id); @@ -386,12 +397,3 @@ class Resource extends BaseItem { } } - -Resource.IMAGE_MAX_DIMENSION = 1920; - -Resource.FETCH_STATUS_IDLE = 0; -Resource.FETCH_STATUS_STARTED = 1; -Resource.FETCH_STATUS_DONE = 2; -Resource.FETCH_STATUS_ERROR = 3; - -module.exports = Resource; diff --git a/packages/lib/models/ResourceLocalState.js b/packages/lib/models/ResourceLocalState.ts similarity index 74% rename from packages/lib/models/ResourceLocalState.js rename to packages/lib/models/ResourceLocalState.ts index 2edb60478..7439ea2c3 100644 --- a/packages/lib/models/ResourceLocalState.js +++ b/packages/lib/models/ResourceLocalState.ts @@ -1,7 +1,8 @@ -const BaseModel = require('../BaseModel').default; +import BaseModel from '../BaseModel'; +import { ResourceLocalStateEntity } from '../services/database/types'; const { Database } = require('../database.js'); -class ResourceLocalState extends BaseModel { +export default class ResourceLocalState extends BaseModel { static tableName() { return 'resource_local_states'; } @@ -10,7 +11,7 @@ class ResourceLocalState extends BaseModel { return BaseModel.TYPE_RESOURCE_LOCAL_STATE; } - static async byResourceId(resourceId) { + static async byResourceId(resourceId: string) { if (!resourceId) throw new Error('Resource ID not provided'); // Sanity check const result = await this.modelSelectOne('SELECT * FROM resource_local_states WHERE resource_id = ?', [resourceId]); @@ -25,17 +26,15 @@ class ResourceLocalState extends BaseModel { return result; } - static async save(o) { + static async save(o: ResourceLocalStateEntity) { const queries = [{ sql: 'DELETE FROM resource_local_states WHERE resource_id = ?', params: [o.resource_id] }, Database.insertQuery(this.tableName(), o)]; return this.db().transactionExecBatch(queries); } - static batchDelete(ids, options = null) { + static batchDelete(ids: string[], options: any = null) { options = options ? Object.assign({}, options) : {}; options.idFieldName = 'resource_id'; return super.batchDelete(ids, options); } } - -module.exports = ResourceLocalState; diff --git a/packages/lib/models/Revision.js b/packages/lib/models/Revision.ts similarity index 85% rename from packages/lib/models/Revision.js rename to packages/lib/models/Revision.ts index d69a835ee..2d53e92ad 100644 --- a/packages/lib/models/Revision.js +++ b/packages/lib/models/Revision.ts @@ -1,5 +1,6 @@ -const BaseModel = require('../BaseModel').default; -const BaseItem = require('./BaseItem.js'); +import BaseModel, { ModelType } from '../BaseModel'; +import { RevisionEntity } from '../services/database/types'; +import BaseItem from './BaseItem'; const DiffMatchPatch = require('diff-match-patch'); const ArrayUtils = require('../ArrayUtils.js'); const JoplinError = require('../JoplinError'); @@ -7,7 +8,7 @@ const { sprintf } = require('sprintf-js'); const dmp = new DiffMatchPatch(); -class Revision extends BaseItem { +export default class Revision extends BaseItem { static tableName() { return 'revisions'; } @@ -16,21 +17,21 @@ class Revision extends BaseItem { return BaseModel.TYPE_REVISION; } - static createTextPatch(oldText, newText) { + static createTextPatch(oldText: string, newText: string) { return dmp.patch_toText(dmp.patch_make(oldText, newText)); } - static applyTextPatch(text, patch) { + static applyTextPatch(text: string, patch: string) { patch = dmp.patch_fromText(patch); const result = dmp.patch_apply(patch, text); if (!result || !result.length) throw new Error('Could not apply patch'); return result[0]; } - static createObjectPatch(oldObject, newObject) { + static createObjectPatch(oldObject: any, newObject: any) { if (!oldObject) oldObject = {}; - const output = { + const output: any = { new: {}, deleted: [], }; @@ -49,7 +50,7 @@ class Revision extends BaseItem { return JSON.stringify(output); } - static applyObjectPatch(object, patch) { + static applyObjectPatch(object: any, patch: any) { patch = JSON.parse(patch); const output = Object.assign({}, object); @@ -64,10 +65,10 @@ class Revision extends BaseItem { return output; } - static patchStats(patch) { + static patchStats(patch: string) { if (typeof patch === 'object') throw new Error('Not implemented'); - const countChars = diffLine => { + const countChars = (diffLine: string) => { return unescape(diffLine).length - 1; }; @@ -93,7 +94,7 @@ class Revision extends BaseItem { }; } - static revisionPatchStatsText(rev) { + static revisionPatchStatsText(rev: RevisionEntity) { const titleStats = this.patchStats(rev.title_diff); const bodyStats = this.patchStats(rev.body_diff); const total = { @@ -107,28 +108,28 @@ class Revision extends BaseItem { return output.join(', '); } - static async countRevisions(itemType, itemId) { + static async countRevisions(itemType: ModelType, itemId: string) { const r = await this.db().selectOne('SELECT count(*) as total FROM revisions WHERE item_type = ? AND item_id = ?', [itemType, itemId]); return r ? r.total : 0; } - static latestRevision(itemType, itemId) { + static latestRevision(itemType: ModelType, itemId: string) { return this.modelSelectOne('SELECT * FROM revisions WHERE item_type = ? AND item_id = ? ORDER BY item_updated_time DESC LIMIT 1', [itemType, itemId]); } - static allByType(itemType, itemId) { + static allByType(itemType: ModelType, itemId: string) { return this.modelSelectAll('SELECT * FROM revisions WHERE item_type = ? AND item_id = ? ORDER BY item_updated_time ASC', [itemType, itemId]); } - static async itemsWithRevisions(itemType, itemIds) { + static async itemsWithRevisions(itemType: ModelType, itemIds: string[]) { if (!itemIds.length) return []; const rows = await this.db().selectAll(`SELECT distinct item_id FROM revisions WHERE item_type = ? AND item_id IN ("${itemIds.join('","')}")`, [itemType]); - return rows.map(r => r.item_id); + return rows.map((r: RevisionEntity) => r.item_id); } - static async itemsWithNoRevisions(itemType, itemIds) { + static async itemsWithNoRevisions(itemType: ModelType, itemIds: string[]) { const withRevs = await this.itemsWithRevisions(itemType, itemIds); const output = []; for (let i = 0; i < itemIds.length; i++) { @@ -137,7 +138,7 @@ class Revision extends BaseItem { return ArrayUtils.unique(output); } - static moveRevisionToTop(revision, revs) { + static moveRevisionToTop(revision: RevisionEntity, revs: RevisionEntity[]) { let targetIndex = -1; for (let i = revs.length - 1; i >= 0; i--) { const rev = revs[i]; @@ -160,7 +161,7 @@ class Revision extends BaseItem { } // Note: revs must be sorted by update_time ASC (as returned by allByType) - static async mergeDiffs(revision, revs = null) { + static async mergeDiffs(revision: RevisionEntity, revs: RevisionEntity[] = null) { if (!('encryption_applied' in revision) || !!revision.encryption_applied) throw new JoplinError('Target revision is encrypted', 'revision_encrypted'); if (!revs) { @@ -202,7 +203,7 @@ class Revision extends BaseItem { return output; } - static async deleteOldRevisions(ttl) { + static async deleteOldRevisions(ttl: number) { // When deleting old revisions, we need to make sure that the oldest surviving revision // is a "merged" one (as opposed to a diff from a now deleted revision). So every time // we deleted a revision, we need to find if there's a corresponding surviving revision @@ -210,7 +211,7 @@ class Revision extends BaseItem { const cutOffDate = Date.now() - ttl; const revisions = await this.modelSelectAll('SELECT * FROM revisions WHERE item_updated_time < ? ORDER BY item_updated_time DESC', [cutOffDate]); - const doneItems = {}; + const doneItems: Record = {}; for (const rev of revisions) { const doneKey = `${rev.item_type}_${rev.item_id}`; @@ -249,10 +250,8 @@ class Revision extends BaseItem { } } - static async revisionExists(itemType, itemId, updatedTime) { + static async revisionExists(itemType: ModelType, itemId: string, updatedTime: number) { const existingRev = await Revision.latestRevision(itemType, itemId); return existingRev && existingRev.item_updated_time === updatedTime; } } - -module.exports = Revision; diff --git a/packages/lib/models/Search.js b/packages/lib/models/Search.js deleted file mode 100644 index 0cf545702..000000000 --- a/packages/lib/models/Search.js +++ /dev/null @@ -1,20 +0,0 @@ -const BaseModel = require('../BaseModel').default; - -class Search extends BaseModel { - static tableName() { - throw new Error('Not using database'); - } - - static modelType() { - return BaseModel.TYPE_SEARCH; - } - - static keywords(query) { - let output = query.trim(); - output = output.split(/[\s\t\n]+/); - output = output.filter(o => !!o); - return output; - } -} - -module.exports = Search; diff --git a/packages/lib/models/Search.ts b/packages/lib/models/Search.ts new file mode 100644 index 000000000..bcf6714f1 --- /dev/null +++ b/packages/lib/models/Search.ts @@ -0,0 +1,20 @@ +// This class doesn't appear to be used at all + +import BaseModel from '../BaseModel'; + +export default class Search extends BaseModel { + static tableName(): string { + throw new Error('Not using database'); + } + + static modelType() { + return BaseModel.TYPE_SEARCH; + } + + static keywords(query: string) { + let output: any = query.trim(); + output = output.split(/[\s\t\n]+/); + output = output.filter((o: any) => !!o); + return output; + } +} diff --git a/packages/lib/models/Setting.ts b/packages/lib/models/Setting.ts index 1198502ce..f2df41ec9 100644 --- a/packages/lib/models/Setting.ts +++ b/packages/lib/models/Setting.ts @@ -2,10 +2,10 @@ import shim from '../shim'; import { _, supportedLocalesToLanguages, defaultLocale } from '../locale'; import { ltrimSlashes } from '../path-utils'; import eventManager from '../eventManager'; -const BaseModel = require('../BaseModel').default; +import BaseModel from '../BaseModel'; const { Database } = require('../database.js'); const SyncTargetRegistry = require('../SyncTargetRegistry.js'); -const time = require('../time').default; +import time from '../time'; const { sprintf } = require('sprintf-js'); const ObjectUtils = require('../ObjectUtils'); const { toTitleCase } = require('../string-utils.js'); @@ -81,6 +81,81 @@ interface SettingSections { class Setting extends BaseModel { + // For backward compatibility + public static TYPE_INT = SettingItemType.Int; + public static TYPE_STRING = SettingItemType.String; + public static TYPE_BOOL = SettingItemType.Bool; + public static TYPE_ARRAY = SettingItemType.Array; + public static TYPE_OBJECT = SettingItemType.Object; + public static TYPE_BUTTON = SettingItemType.Button; + + public static THEME_LIGHT = 1; + public static THEME_DARK = 2; + public static THEME_OLED_DARK = 22; + public static THEME_SOLARIZED_LIGHT = 3; + public static THEME_SOLARIZED_DARK = 4; + public static THEME_DRACULA = 5; + public static THEME_NORD = 6; + public static THEME_ARITIM_DARK = 7; + + public static FONT_DEFAULT = 0; + public static FONT_MENLO = 1; + public static FONT_COURIER_NEW = 2; + public static FONT_AVENIR = 3; + public static FONT_MONOSPACE = 4; + + public static LAYOUT_ALL = 0; + public static LAYOUT_EDITOR_VIEWER = 1; + public static LAYOUT_EDITOR_SPLIT = 2; + public static LAYOUT_VIEWER_SPLIT = 3; + + public static DATE_FORMAT_1 = 'DD/MM/YYYY'; + public static DATE_FORMAT_2 = 'DD/MM/YY'; + public static DATE_FORMAT_3 = 'MM/DD/YYYY'; + public static DATE_FORMAT_4 = 'MM/DD/YY'; + public static DATE_FORMAT_5 = 'YYYY-MM-DD'; + public static DATE_FORMAT_6 = 'DD.MM.YYYY'; + public static DATE_FORMAT_7 = 'YYYY.MM.DD'; + + public static TIME_FORMAT_1 = 'HH:mm'; + public static TIME_FORMAT_2 = 'h:mm A'; + + public static SHOULD_REENCRYPT_NO = 0; // Data doesn't need to be re-encrypted + public static SHOULD_REENCRYPT_YES = 1; // Data should be re-encrypted + public static SHOULD_REENCRYPT_NOTIFIED = 2; // Data should be re-encrypted, and user has been notified + + public static SYNC_UPGRADE_STATE_IDLE = 0; // Doesn't need to be upgraded + public static SYNC_UPGRADE_STATE_SHOULD_DO = 1; // Should be upgraded, but waiting for user to confirm + public static SYNC_UPGRADE_STATE_MUST_DO = 2; // Must be upgraded - on next restart, the upgrade will start + + public static custom_css_files = { + JOPLIN_APP: 'userchrome.css', + RENDERED_MARKDOWN: 'userstyle.css', + }; + + + // Contains constants that are set by the application and + // cannot be modified by the user: + public static constants_: any = { + env: 'SET_ME', + isDemo: false, + appName: 'joplin', + appId: 'SET_ME', // Each app should set this identifier + appType: 'SET_ME', // 'cli' or 'mobile' + resourceDirName: '', + resourceDir: '', + profileDir: '', + templateDir: '', + tempDir: '', + cacheDir: '', + pluginDir: '', + flagOpenDevTools: false, + syncVersion: 2, + startupDevPlugins: [], + }; + + public static autoSaveEnabled = true; + private static metadata_: SettingItems = null; private static keychainService_: any = null; private static keys_: string[] = null; @@ -540,7 +615,7 @@ class Setting extends BaseModel { appTypes: ['cli'], label: () => _('Sort notes by'), options: () => { - const Note = require('./Note'); + const Note = require('./Note').default; const noteSortFields = ['user_updated_time', 'user_created_time', 'title', 'order']; const options: any = {}; for (let i = 0; i < noteSortFields.length; i++) { @@ -566,7 +641,7 @@ class Setting extends BaseModel { appTypes: ['cli'], label: () => _('Sort notebooks by'), options: () => { - const Folder = require('./Folder'); + const Folder = require('./Folder').default; const folderSortFields = ['title', 'last_note_user_updated_time']; const options: any = {}; for (let i = 0; i < folderSortFields.length; i++) { @@ -1609,79 +1684,4 @@ class Setting extends BaseModel { } } -// For backward compatibility -Setting.TYPE_INT = SettingItemType.Int; -Setting.TYPE_STRING = SettingItemType.String; -Setting.TYPE_BOOL = SettingItemType.Bool; -Setting.TYPE_ARRAY = SettingItemType.Array; -Setting.TYPE_OBJECT = SettingItemType.Object; -Setting.TYPE_BUTTON = SettingItemType.Button; - -Setting.THEME_LIGHT = 1; -Setting.THEME_DARK = 2; -Setting.THEME_OLED_DARK = 22; -Setting.THEME_SOLARIZED_LIGHT = 3; -Setting.THEME_SOLARIZED_DARK = 4; -Setting.THEME_DRACULA = 5; -Setting.THEME_NORD = 6; -Setting.THEME_ARITIM_DARK = 7; - -Setting.FONT_DEFAULT = 0; -Setting.FONT_MENLO = 1; -Setting.FONT_COURIER_NEW = 2; -Setting.FONT_AVENIR = 3; -Setting.FONT_MONOSPACE = 4; - -Setting.LAYOUT_ALL = 0; -Setting.LAYOUT_EDITOR_VIEWER = 1; -Setting.LAYOUT_EDITOR_SPLIT = 2; -Setting.LAYOUT_VIEWER_SPLIT = 3; - -Setting.DATE_FORMAT_1 = 'DD/MM/YYYY'; -Setting.DATE_FORMAT_2 = 'DD/MM/YY'; -Setting.DATE_FORMAT_3 = 'MM/DD/YYYY'; -Setting.DATE_FORMAT_4 = 'MM/DD/YY'; -Setting.DATE_FORMAT_5 = 'YYYY-MM-DD'; -Setting.DATE_FORMAT_6 = 'DD.MM.YYYY'; -Setting.DATE_FORMAT_7 = 'YYYY.MM.DD'; - -Setting.TIME_FORMAT_1 = 'HH:mm'; -Setting.TIME_FORMAT_2 = 'h:mm A'; - -Setting.SHOULD_REENCRYPT_NO = 0; // Data doesn't need to be re-encrypted -Setting.SHOULD_REENCRYPT_YES = 1; // Data should be re-encrypted -Setting.SHOULD_REENCRYPT_NOTIFIED = 2; // Data should be re-encrypted, and user has been notified - -Setting.SYNC_UPGRADE_STATE_IDLE = 0; // Doesn't need to be upgraded -Setting.SYNC_UPGRADE_STATE_SHOULD_DO = 1; // Should be upgraded, but waiting for user to confirm -Setting.SYNC_UPGRADE_STATE_MUST_DO = 2; // Must be upgraded - on next restart, the upgrade will start - -Setting.custom_css_files = { - JOPLIN_APP: 'userchrome.css', - RENDERED_MARKDOWN: 'userstyle.css', -}; - - -// Contains constants that are set by the application and -// cannot be modified by the user: -Setting.constants_ = { - env: 'SET_ME', - isDemo: false, - appName: 'joplin', - appId: 'SET_ME', // Each app should set this identifier - appType: 'SET_ME', // 'cli' or 'mobile' - resourceDirName: '', - resourceDir: '', - profileDir: '', - templateDir: '', - tempDir: '', - cacheDir: '', - pluginDir: '', - flagOpenDevTools: false, - syncVersion: 2, - startupDevPlugins: [], -}; - -Setting.autoSaveEnabled = true; - export default Setting; diff --git a/packages/lib/models/SmartFilter.js b/packages/lib/models/SmartFilter.js deleted file mode 100644 index e04b72486..000000000 --- a/packages/lib/models/SmartFilter.js +++ /dev/null @@ -1,13 +0,0 @@ -const BaseModel = require('../BaseModel').default; - -class SmartFilter extends BaseModel { - static tableName() { - throw new Error('Not using database'); - } - - static modelType() { - return BaseModel.TYPE_SMART_FILTER; - } -} - -module.exports = SmartFilter; diff --git a/packages/lib/models/SmartFilter.ts b/packages/lib/models/SmartFilter.ts new file mode 100644 index 000000000..8e0ce98ab --- /dev/null +++ b/packages/lib/models/SmartFilter.ts @@ -0,0 +1,13 @@ +// Not used?? + +import BaseModel from '../BaseModel'; + +export default class SmartFilter extends BaseModel { + static tableName(): string { + throw new Error('Not using database'); + } + + static modelType() { + return BaseModel.TYPE_SMART_FILTER; + } +} diff --git a/packages/lib/models/Tag.js b/packages/lib/models/Tag.ts similarity index 79% rename from packages/lib/models/Tag.js rename to packages/lib/models/Tag.ts index d28ce89e1..a25916dc1 100644 --- a/packages/lib/models/Tag.js +++ b/packages/lib/models/Tag.ts @@ -1,10 +1,12 @@ -const BaseModel = require('../BaseModel').default; -const BaseItem = require('./BaseItem.js'); -const NoteTag = require('./NoteTag.js'); -const Note = require('./Note.js'); -const { _ } = require('../locale'); +import { TagEntity } from '../services/database/types'; -class Tag extends BaseItem { +import BaseModel from '../BaseModel'; +import BaseItem from './BaseItem'; +import NoteTag from './NoteTag'; +import Note from './Note'; +import { _ } from '../locale'; + +export default class Tag extends BaseItem { static tableName() { return 'tags'; } @@ -13,7 +15,7 @@ class Tag extends BaseItem { return BaseModel.TYPE_TAG; } - static async noteIds(tagId) { + static async noteIds(tagId: string) { const rows = await this.db().selectAll('SELECT note_id FROM note_tags WHERE tag_id = ?', [tagId]); const output = []; for (let i = 0; i < rows.length; i++) { @@ -22,7 +24,7 @@ class Tag extends BaseItem { return output; } - static async notes(tagId, options = null) { + static async notes(tagId: string, options: any = null) { if (options === null) options = {}; const noteIds = await this.noteIds(tagId); @@ -37,7 +39,7 @@ class Tag extends BaseItem { } // Untag all the notes and delete tag - static async untagAll(tagId) { + static async untagAll(tagId: string) { const noteTags = await NoteTag.modelSelectAll('SELECT id FROM note_tags WHERE tag_id = ?', [tagId]); for (let i = 0; i < noteTags.length; i++) { await NoteTag.delete(noteTags[i].id); @@ -46,7 +48,7 @@ class Tag extends BaseItem { await Tag.delete(tagId); } - static async delete(id, options = null) { + static async delete(id: string, options: any = null) { if (!options) options = {}; await super.delete(id, options); @@ -57,7 +59,7 @@ class Tag extends BaseItem { }); } - static async addNote(tagId, noteId) { + static async addNote(tagId: string, noteId: string) { const hasIt = await this.hasNote(tagId, noteId); if (hasIt) return; @@ -87,7 +89,7 @@ class Tag extends BaseItem { return output; } - static async removeNote(tagId, noteId) { + static async removeNote(tagId: string, noteId: string) { const noteTags = await NoteTag.modelSelectAll('SELECT id FROM note_tags WHERE tag_id = ? and note_id = ?', [tagId, noteId]); for (let i = 0; i < noteTags.length; i++) { await NoteTag.delete(noteTags[i].id); @@ -99,12 +101,12 @@ class Tag extends BaseItem { }); } - static loadWithCount(tagId) { + static loadWithCount(tagId: string) { const sql = 'SELECT * FROM tags_with_note_count WHERE id = ?'; return this.modelSelectOne(sql, [tagId]); } - static async hasNote(tagId, noteId) { + static async hasNote(tagId: string, noteId: string) { const r = await this.db().selectOne('SELECT note_id FROM note_tags WHERE tag_id = ? AND note_id = ? LIMIT 1', [tagId, noteId]); return !!r; } @@ -113,24 +115,24 @@ class Tag extends BaseItem { return await Tag.modelSelectAll('SELECT * FROM tags_with_note_count'); } - static async searchAllWithNotes(options) { + static async searchAllWithNotes(options: any) { if (!options) options = {}; if (!options.conditions) options.conditions = []; options.conditions.push('id IN (SELECT distinct id FROM tags_with_note_count)'); return this.search(options); } - static async tagsByNoteId(noteId) { + static async tagsByNoteId(noteId: string) { const tagIds = await NoteTag.tagIdsByNoteId(noteId); if (!tagIds.length) return []; return this.modelSelectAll(`SELECT * FROM tags WHERE id IN ("${tagIds.join('","')}")`); } - static async commonTagsByNoteIds(noteIds) { + static async commonTagsByNoteIds(noteIds: string[]) { if (!noteIds || noteIds.length === 0) { return []; } - let commonTagIds = await NoteTag.tagIdsByNoteId(noteIds[0]); + let commonTagIds: string[] = await NoteTag.tagIdsByNoteId(noteIds[0]); for (let i = 1; i < noteIds.length; i++) { const tagIds = await NoteTag.tagIdsByNoteId(noteIds[i]); commonTagIds = commonTagIds.filter(value => tagIds.includes(value)); @@ -141,17 +143,17 @@ class Tag extends BaseItem { return this.modelSelectAll(`SELECT * FROM tags WHERE id IN ("${commonTagIds.join('","')}")`); } - static async loadByTitle(title) { + static async loadByTitle(title: string) { return this.loadByField('title', title, { caseInsensitive: true }); } - static async addNoteTagByTitle(noteId, tagTitle) { + static async addNoteTagByTitle(noteId: string, tagTitle: string) { let tag = await this.loadByTitle(tagTitle); if (!tag) tag = await Tag.save({ title: tagTitle }, { userSideValidation: true }); return await this.addNote(tag.id, noteId); } - static async setNoteTagsByTitles(noteId, tagTitles) { + static async setNoteTagsByTitles(noteId: string, tagTitles: string[]) { const previousTags = await this.tagsByNoteId(noteId); const addedTitles = []; @@ -171,7 +173,7 @@ class Tag extends BaseItem { } } - static async setNoteTagsByIds(noteId, tagIds) { + static async setNoteTagsByIds(noteId: string, tagIds: string[]) { const previousTags = await this.tagsByNoteId(noteId); const addedIds = []; @@ -188,7 +190,7 @@ class Tag extends BaseItem { } } - static async save(o, options = null) { + static async save(o: TagEntity, options: any = null) { options = Object.assign({}, { dispatchUpdateAction: true, userSideValidation: false, @@ -203,7 +205,7 @@ class Tag extends BaseItem { } } - return super.save(o, options).then(tag => { + return super.save(o, options).then((tag: TagEntity) => { if (options.dispatchUpdateAction) { this.dispatch({ type: 'TAG_UPDATE_ONE', @@ -215,5 +217,3 @@ class Tag extends BaseItem { }); } } - -module.exports = Tag; diff --git a/packages/lib/ntpDate.ts b/packages/lib/ntpDate.ts index 71d11edb9..d78cf7a7e 100644 --- a/packages/lib/ntpDate.ts +++ b/packages/lib/ntpDate.ts @@ -1,5 +1,5 @@ const ntpClient = require('./vendor/ntp-client'); -const Logger = require('./Logger').default; +import Logger from './Logger'; const Mutex = require('async-mutex').Mutex; let nextSyncTime = 0; diff --git a/packages/lib/reducer.ts b/packages/lib/reducer.ts index c7cdac740..e0c0687b2 100644 --- a/packages/lib/reducer.ts +++ b/packages/lib/reducer.ts @@ -1,8 +1,8 @@ import produce, { Draft } from 'immer'; import pluginServiceReducer, { stateRootKey as pluginServiceStateRootKey, defaultState as pluginServiceDefaultState, State as PluginServiceState } from './services/plugins/reducer'; -const Note = require('./models/Note.js'); -const Folder = require('./models/Folder.js'); -const BaseModel = require('./BaseModel').default; +import Note from './models/Note'; +import Folder from './models/Folder'; +import BaseModel from './BaseModel'; const ArrayUtils = require('./ArrayUtils.js'); const { ALL_NOTES_FILTER_ID } = require('./reserved-ids'); const { createSelectorCreator, defaultMemoize } = require('reselect'); diff --git a/packages/lib/services/AlarmService.ts b/packages/lib/services/AlarmService.ts index e395b28ca..b23e8cc15 100644 --- a/packages/lib/services/AlarmService.ts +++ b/packages/lib/services/AlarmService.ts @@ -1,7 +1,7 @@ import Logger from '../Logger'; import Alarm from '../models/Alarm'; -const Note = require('../models/Note.js'); +import Note from '../models/Note'; export default class AlarmService { diff --git a/packages/lib/services/DecryptionWorker.js b/packages/lib/services/DecryptionWorker.ts similarity index 86% rename from packages/lib/services/DecryptionWorker.js rename to packages/lib/services/DecryptionWorker.ts index 5c8b14c54..4a3a27a87 100644 --- a/packages/lib/services/DecryptionWorker.js +++ b/packages/lib/services/DecryptionWorker.ts @@ -1,28 +1,35 @@ -const BaseItem = require('../models/BaseItem'); -const BaseModel = require('../BaseModel').default; -const MasterKey = require('../models/MasterKey'); -const Resource = require('../models/Resource'); -const ResourceService = require('./ResourceService').default; -const Logger = require('../Logger').default; -const EventEmitter = require('events'); -const shim = require('../shim').default; +import BaseItem, { ItemsThatNeedDecryptionResult } from '../models/BaseItem'; +import BaseModel from '../BaseModel'; +import MasterKey from '../models/MasterKey'; +import Resource from '../models/Resource'; +import ResourceService from './ResourceService'; +import Logger from '../Logger'; +import shim from '../shim'; +import KvStore from './KvStore'; + +const EventEmitter = require('events'); + +export default class DecryptionWorker { + + public static instance_: DecryptionWorker = null; + + private state_: string = 'idle'; + private logger_: Logger; + public dispatch: Function = () => {}; + private scheduleId_: any = null; + private eventEmitter_: any; + private kvStore_: KvStore = null; + private maxDecryptionAttempts_ = 2; + private startCalls_: boolean[] = []; + private encryptionService_: any = null; -class DecryptionWorker { constructor() { this.state_ = 'idle'; this.logger_ = new Logger(); - - this.dispatch = () => {}; - - this.scheduleId_ = null; this.eventEmitter_ = new EventEmitter(); - this.kvStore_ = null; - this.maxDecryptionAttempts_ = 2; - - this.startCalls_ = []; } - setLogger(l) { + setLogger(l: Logger) { this.logger_ = l; } @@ -30,11 +37,11 @@ class DecryptionWorker { return this.logger_; } - on(eventName, callback) { + on(eventName: string, callback: Function) { return this.eventEmitter_.on(eventName, callback); } - off(eventName, callback) { + off(eventName: string, callback: Function) { return this.eventEmitter_.removeListener(eventName, callback); } @@ -44,11 +51,11 @@ class DecryptionWorker { return DecryptionWorker.instance_; } - setEncryptionService(v) { + setEncryptionService(v: any) { this.encryptionService_ = v; } - setKvStore(v) { + setKvStore(v: KvStore) { this.kvStore_ = v; } @@ -67,7 +74,7 @@ class DecryptionWorker { this.scheduleId_ = shim.setTimeout(() => { this.scheduleId_ = null; - this.start({ + void this.start({ masterKeyNotLoadedHandler: 'dispatch', }); }, 1000); @@ -86,7 +93,7 @@ class DecryptionWorker { return items; } - async clearDisabledItem(typeId, itemId) { + async clearDisabledItem(typeId: string, itemId: string) { await this.kvStore().deleteValue(`decrypt:${typeId}:${itemId}`); } @@ -94,13 +101,13 @@ class DecryptionWorker { await this.kvStore().deleteByPrefix('decrypt:'); } - dispatchReport(report) { + dispatchReport(report: any) { const action = Object.assign({}, report); action.type = 'DECRYPTION_WORKER_SET'; this.dispatch(action); } - async start_(options = null) { + async start_(options: any = null) { if (options === null) options = {}; if (!('masterKeyNotLoadedHandler' in options)) options.masterKeyNotLoadedHandler = 'throw'; if (!('errorHandler' in options)) options.errorHandler = 'log'; @@ -140,7 +147,7 @@ class DecryptionWorker { this.state_ = 'started'; const excludedIds = []; - const decryptedItemCounts = {}; + const decryptedItemCounts: any = {}; let skippedItemCount = 0; this.dispatch({ type: 'ENCRYPTION_HAS_DISABLED_ITEMS', value: false }); @@ -150,7 +157,7 @@ class DecryptionWorker { const notLoadedMasterKeyDisptaches = []; while (true) { - const result = await BaseItem.itemsThatNeedDecryption(excludedIds); + const result: ItemsThatNeedDecryptionResult = await BaseItem.itemsThatNeedDecryption(excludedIds); const items = result.items; for (let i = 0; i < items.length; i++) { @@ -263,13 +270,13 @@ class DecryptionWorker { if (downloadedButEncryptedBlobCount) { this.logger().info(`DecryptionWorker: Some resources have been downloaded but are not decrypted yet. Scheduling another decryption. Resource count: ${downloadedButEncryptedBlobCount}`); - this.scheduleStart(); + void this.scheduleStart(); } return finalReport; } - async start(options) { + async start(options: any) { this.startCalls_.push(true); let output = null; try { @@ -293,13 +300,9 @@ class DecryptionWorker { const iid = shim.setInterval(() => { if (!this.startCalls_.length) { shim.clearInterval(iid); - resolve(); + resolve(null); } }, 100); }); } } - -DecryptionWorker.instance_ = null; - -module.exports = DecryptionWorker; diff --git a/packages/lib/services/EncryptionService.js b/packages/lib/services/EncryptionService.ts similarity index 79% rename from packages/lib/services/EncryptionService.js rename to packages/lib/services/EncryptionService.ts index 196cf8848..3751f4b51 100644 --- a/packages/lib/services/EncryptionService.js +++ b/packages/lib/services/EncryptionService.ts @@ -1,16 +1,57 @@ +import { MasterKeyEntity } from './database/types'; +import Logger from '../Logger'; +import shim from '../shim'; +import Setting from '../models/Setting'; +import MasterKey from '../models/MasterKey'; +import BaseItem from '../models/BaseItem'; + const { padLeft } = require('../string-utils.js'); -const Logger = require('../Logger').default; -const shim = require('../shim').default; -const Setting = require('../models/Setting').default; -const MasterKey = require('../models/MasterKey'); -const BaseItem = require('../models/BaseItem'); const JoplinError = require('../JoplinError'); -function hexPad(s, length) { +function hexPad(s: string, length: number) { return padLeft(s, length, '0'); } -class EncryptionService { +export default class EncryptionService { + + public static instance_: EncryptionService = null; + + public static METHOD_SJCL_2 = 2; + public static METHOD_SJCL_3 = 3; + public static METHOD_SJCL_4 = 4; + public static METHOD_SJCL_1A = 5; + public static METHOD_SJCL = 1; + + public static fsDriver_: any = null; + + // Note: 1 MB is very slow with Node and probably even worse on mobile. + // + // On mobile the time it takes to decrypt increases exponentially for some reason, so it's important + // to have a relatively small size so as not to freeze the app. For example, on Android 7.1 simulator + // with 4.1 GB RAM, it takes this much to decrypt a block; + // + // 50KB => 1000 ms + // 25KB => 250ms + // 10KB => 200ms + // 5KB => 10ms + // + // So making the block 10 times smaller make it 100 times faster! So for now using 5KB. This can be + // changed easily since the chunk size is incorporated into the encrypted data. + private chunkSize_ = 5000; + private loadedMasterKeys_: Record = {}; + private activeMasterKeyId_: string = null; + private defaultEncryptionMethod_ = EncryptionService.METHOD_SJCL_1A; + private defaultMasterKeyEncryptionMethod_ = EncryptionService.METHOD_SJCL_4; + private logger_ = new Logger(); + + private headerTemplates_ = { + // Template version 1 + 1: { + // Fields are defined as [name, valueSize, valueType] + fields: [['encryptionMethod', 2, 'int'], ['masterKeyId', 32, 'hex']], + }, + }; + constructor() { // Note: 1 MB is very slow with Node and probably even worse on mobile. // @@ -41,13 +82,13 @@ class EncryptionService { }; } - static instance() { + public static instance() { if (this.instance_) return this.instance_; this.instance_ = new EncryptionService(); return this.instance_; } - setLogger(l) { + setLogger(l: Logger) { this.logger_ = l; } @@ -55,7 +96,7 @@ class EncryptionService { return this.logger_; } - async generateMasterKeyAndEnableEncryption(password) { + async generateMasterKeyAndEnableEncryption(password: string) { let masterKey = await this.generateMasterKey(password); masterKey = await MasterKey.save(masterKey); await this.enableEncryption(masterKey, password); @@ -63,7 +104,7 @@ class EncryptionService { return masterKey; } - async enableEncryption(masterKey, password = null) { + async enableEncryption(masterKey: MasterKeyEntity, password: string = null) { Setting.setValue('encryption.enabled', true); Setting.setValue('encryption.activeMasterKeyId', masterKey.id); @@ -133,43 +174,43 @@ class EncryptionService { return this.defaultEncryptionMethod_; } - setActiveMasterKeyId(id) { + setActiveMasterKeyId(id: string) { this.activeMasterKeyId_ = id; } activeMasterKeyId() { if (!this.activeMasterKeyId_) { - const error = new Error('No master key is defined as active. Check this: Either one or more master keys exist but no password was provided for any of them. Or no master key exist. Or master keys and password exist, but none was set as active.'); + const error: any = new Error('No master key is defined as active. Check this: Either one or more master keys exist but no password was provided for any of them. Or no master key exist. Or master keys and password exist, but none was set as active.'); error.code = 'noActiveMasterKey'; throw error; } return this.activeMasterKeyId_; } - isMasterKeyLoaded(id) { + isMasterKeyLoaded(id: string) { return !!this.loadedMasterKeys_[id]; } - async loadMasterKey_(model, password, makeActive = false) { + async loadMasterKey_(model: MasterKeyEntity, password: string, makeActive = false) { if (!model.id) throw new Error('Master key does not have an ID - save it first'); this.loadedMasterKeys_[model.id] = await this.decryptMasterKey_(model, password); if (makeActive) this.setActiveMasterKeyId(model.id); } - unloadMasterKey(model) { + unloadMasterKey(model: MasterKeyEntity) { delete this.loadedMasterKeys_[model.id]; } - unloadAllMasterKeys() { - for (const id in this.loadedMasterKeys_) { - if (!this.loadedMasterKeys_.hasOwnProperty(id)) continue; - this.unloadMasterKey(this.loadedMasterKeys_[id]); - } - } + // unloadAllMasterKeys() { + // for (const id in this.loadedMasterKeys_) { + // if (!this.loadedMasterKeys_.hasOwnProperty(id)) continue; + // this.unloadMasterKey(this.loadedMasterKeys_[id]); + // } + // } - loadedMasterKey(id) { + loadedMasterKey(id: string) { if (!this.loadedMasterKeys_[id]) { - const error = new Error(`Master key is not loaded: ${id}`); + const error: any = new Error(`Master key is not loaded: ${id}`); error.code = 'masterKeyNotLoaded'; error.masterKeyId = id; throw error; @@ -191,7 +232,7 @@ class EncryptionService { return EncryptionService.fsDriver_; } - sha256(string) { + sha256(string: string) { const sjcl = shim.sjclModule; const bitArray = sjcl.hash.sha256.hash(string); return sjcl.codec.hex.fromBits(bitArray); @@ -213,8 +254,8 @@ class EncryptionService { // sjcl.random.addEntropy(hexSeed, 1024, 'shim.randomBytes'); // } - async randomHexString(byteCount) { - const bytes = await shim.randomBytes(byteCount); + async randomHexString(byteCount: number) { + const bytes: any[] = await shim.randomBytes(byteCount); return bytes .map(a => { return hexPad(a.toString(16), 2); @@ -222,18 +263,18 @@ class EncryptionService { .join(''); } - masterKeysThatNeedUpgrading(masterKeys) { + masterKeysThatNeedUpgrading(masterKeys: MasterKeyEntity[]) { return MasterKey.allWithoutEncryptionMethod(masterKeys, this.defaultMasterKeyEncryptionMethod_); } - async upgradeMasterKey(model, decryptionPassword) { + async upgradeMasterKey(model: MasterKeyEntity, decryptionPassword: string) { const newEncryptionMethod = this.defaultMasterKeyEncryptionMethod_; const plainText = await this.decryptMasterKey_(model, decryptionPassword); const newContent = await this.encryptMasterKeyContent_(newEncryptionMethod, plainText, decryptionPassword); return { ...model, ...newContent }; } - async encryptMasterKeyContent_(encryptionMethod, hexaBytes, password) { + async encryptMasterKeyContent_(encryptionMethod: number, hexaBytes: any, password: string): Promise { // Checksum is not necessary since decryption will already fail if data is invalid const checksum = encryptionMethod === EncryptionService.METHOD_SJCL_2 ? this.sha256(hexaBytes) : ''; const cipherText = await this.encrypt(encryptionMethod, password, hexaBytes); @@ -245,18 +286,18 @@ class EncryptionService { }; } - async generateMasterKeyContent_(password, options = null) { + async generateMasterKeyContent_(password: string, options: any = null) { options = Object.assign({}, { encryptionMethod: this.defaultMasterKeyEncryptionMethod_, }, options); - const bytes = await shim.randomBytes(256); + const bytes: any[] = await shim.randomBytes(256); const hexaBytes = bytes.map(a => hexPad(a.toString(16), 2)).join(''); return this.encryptMasterKeyContent_(options.encryptionMethod, hexaBytes, password); } - async generateMasterKey(password, options = null) { + async generateMasterKey(password: string, options: any = null) { const model = await this.generateMasterKeyContent_(password, options); const now = Date.now(); @@ -267,7 +308,7 @@ class EncryptionService { return model; } - async decryptMasterKey_(model, password) { + async decryptMasterKey_(model: MasterKeyEntity, password: string) { const plainText = await this.decrypt(model.encryption_method, password, model.content); if (model.encryption_method === EncryptionService.METHOD_SJCL_2) { const checksum = this.sha256(plainText); @@ -276,7 +317,7 @@ class EncryptionService { return plainText; } - async checkMasterKeyPassword(model, password) { + async checkMasterKeyPassword(model: MasterKeyEntity, password: string) { try { await this.decryptMasterKey_(model, password); } catch (error) { @@ -286,13 +327,13 @@ class EncryptionService { return true; } - wrapSjclError(sjclError) { + wrapSjclError(sjclError: any) { const error = new Error(sjclError.message); error.stack = sjclError.stack; return error; } - async encrypt(method, key, plainText) { + async encrypt(method: number, key: string, plainText: string) { if (!method) throw new Error('Encryption method is required'); if (!key) throw new Error('Encryption key is required'); @@ -390,7 +431,7 @@ class EncryptionService { throw new Error(`Unknown encryption method: ${method}`); } - async decrypt(method, key, cipherText) { + async decrypt(method: number, key: string, cipherText: string) { if (!method) throw new Error('Encryption method is required'); if (!key) throw new Error('Encryption key is required'); @@ -411,7 +452,7 @@ class EncryptionService { } } - async encryptAbstract_(source, destination, options = null) { + async encryptAbstract_(source: any, destination: any, options: any = null) { options = Object.assign({}, { encryptionMethod: this.defaultEncryptionMethod(), }, options); @@ -447,10 +488,10 @@ class EncryptionService { } } - async decryptAbstract_(source, destination, options = null) { + async decryptAbstract_(source: any, destination: any, options: any = null) { if (!options) options = {}; - const header = await this.decodeHeaderSource_(source); + const header: any = await this.decodeHeaderSource_(source); const masterKeyPlainText = this.loadedMasterKey(header.masterKeyId); let doneSize = 0; @@ -474,10 +515,10 @@ class EncryptionService { } } - stringReader_(string, sync = false) { + stringReader_(string: string, sync = false) { const reader = { index: 0, - read: function(size) { + read: function(size: number) { const output = string.substr(reader.index, size); reader.index += size; return !sync ? Promise.resolve(output) : output; @@ -488,9 +529,9 @@ class EncryptionService { } stringWriter_() { - const output = { + const output: any = { data: [], - append: async function(data) { + append: async function(data: any) { output.data.push(data); }, result: function() { @@ -501,11 +542,11 @@ class EncryptionService { return output; } - async fileReader_(path, encoding) { + async fileReader_(path: string, encoding: any) { const handle = await this.fsDriver().open(path, 'r'); const reader = { handle: handle, - read: async size => { + read: async (size: number) => { return this.fsDriver().readFileChunk(reader.handle, size, encoding); }, close: async () => { @@ -515,30 +556,30 @@ class EncryptionService { return reader; } - async fileWriter_(path, encoding) { + async fileWriter_(path: string, encoding: any) { return { - append: async data => { + append: async (data: any) => { return this.fsDriver().appendFile(path, data, encoding); }, close: function() {}, }; } - async encryptString(plainText, options = null) { + async encryptString(plainText: any, options: any = null) { const source = this.stringReader_(plainText); const destination = this.stringWriter_(); await this.encryptAbstract_(source, destination, options); return destination.result(); } - async decryptString(cipherText, options = null) { + async decryptString(cipherText: any, options: any = null) { const source = this.stringReader_(cipherText); const destination = this.stringWriter_(); await this.decryptAbstract_(source, destination, options); return destination.data.join(''); } - async encryptFile(srcPath, destPath, options = null) { + async encryptFile(srcPath: string, destPath: string, options: any = null) { let source = await this.fileReader_(srcPath, 'base64'); let destination = await this.fileWriter_(destPath, 'ascii'); @@ -555,7 +596,7 @@ class EncryptionService { await this.fsDriver().unlink(destPath); await this.encryptAbstract_(source, destination, options); } catch (error) { - cleanUp(); + await cleanUp(); await this.fsDriver().unlink(destPath); throw error; } @@ -563,7 +604,7 @@ class EncryptionService { await cleanUp(); } - async decryptFile(srcPath, destPath, options = null) { + async decryptFile(srcPath: string, destPath: string, options: any = null) { let source = await this.fileReader_(srcPath, 'ascii'); let destination = await this.fileWriter_(destPath, 'base64'); @@ -580,7 +621,7 @@ class EncryptionService { await this.fsDriver().unlink(destPath); await this.decryptAbstract_(source, destination, options); } catch (error) { - cleanUp(); + await cleanUp(); await this.fsDriver().unlink(destPath); throw error; } @@ -588,13 +629,13 @@ class EncryptionService { await cleanUp(); } - headerTemplate(version) { - const r = this.headerTemplates_[version]; + headerTemplate(version: number) { + const r = (this.headerTemplates_ as any)[version]; if (!r) throw new Error(`Unknown header version: ${version}`); return r; } - encodeHeader_(header) { + encodeHeader_(header: any) { // Sanity check if (header.masterKeyId.length !== 32) throw new Error(`Invalid master key ID size: ${header.masterKeyId}`); @@ -605,12 +646,12 @@ class EncryptionService { return `JED01${encryptionMetadata}`; } - async decodeHeaderString(cipherText) { + async decodeHeaderString(cipherText: any) { const source = this.stringReader_(cipherText); return this.decodeHeaderSource_(source); } - async decodeHeaderSource_(source) { + async decodeHeaderSource_(source: any) { const identifier = await source.read(5); if (!this.isValidHeaderIdentifier(identifier)) throw new JoplinError(`Invalid encryption identifier. Data is not actually encrypted? ID was: ${identifier}`, 'invalidIdentifier'); const mdSizeHex = await source.read(6); @@ -620,8 +661,8 @@ class EncryptionService { return this.decodeHeaderBytes_(identifier + mdSizeHex + md); } - decodeHeaderBytes_(headerHexaBytes) { - const reader = this.stringReader_(headerHexaBytes, true); + decodeHeaderBytes_(headerHexaBytes: any) { + const reader: any = this.stringReader_(headerHexaBytes, true); const identifier = reader.read(3); const version = parseInt(reader.read(2), 16); if (identifier !== 'JED') throw new Error(`Invalid header (missing identifier): ${headerHexaBytes.substr(0, 64)}`); @@ -629,7 +670,7 @@ class EncryptionService { parseInt(reader.read(6), 16); // Read the size and move the reader pointer forward - const output = {}; + const output: any = {}; for (let i = 0; i < template.fields.length; i++) { const m = template.fields[i]; @@ -652,37 +693,27 @@ class EncryptionService { return output; } - isValidHeaderIdentifier(id, ignoreTooLongLength = false) { + isValidHeaderIdentifier(id: string, ignoreTooLongLength = false) { if (!id) return false; if (!ignoreTooLongLength && id.length !== 5) return false; return /JED\d\d/.test(id); } - isValidEncryptionMethod(method) { + isValidEncryptionMethod(method: number) { return [EncryptionService.METHOD_SJCL, EncryptionService.METHOD_SJCL_1A, EncryptionService.METHOD_SJCL_2, EncryptionService.METHOD_SJCL_3, EncryptionService.METHOD_SJCL_4].indexOf(method) >= 0; } - async itemIsEncrypted(item) { + async itemIsEncrypted(item: any) { if (!item) throw new Error('No item'); const ItemClass = BaseItem.itemClass(item); if (!ItemClass.encryptionSupported()) return false; return item.encryption_applied && this.isValidHeaderIdentifier(item.encryption_cipher_text, true); } - async fileIsEncrypted(path) { + async fileIsEncrypted(path: string) { const handle = await this.fsDriver().open(path, 'r'); const headerIdentifier = await this.fsDriver().readFileChunk(handle, 5, 'ascii'); await this.fsDriver().close(handle); return this.isValidHeaderIdentifier(headerIdentifier); } } - -EncryptionService.METHOD_SJCL = 1; -EncryptionService.METHOD_SJCL_2 = 2; -EncryptionService.METHOD_SJCL_3 = 3; -EncryptionService.METHOD_SJCL_4 = 4; -EncryptionService.METHOD_SJCL_1A = 5; - -EncryptionService.fsDriver_ = null; - -module.exports = EncryptionService; diff --git a/packages/lib/services/EncryptionServiceDriverNode.js b/packages/lib/services/EncryptionServiceDriverNode.js deleted file mode 100644 index e69de29bb..000000000 diff --git a/packages/lib/services/ExternalEditWatcher.ts b/packages/lib/services/ExternalEditWatcher.ts index 24cca435d..a227eed6d 100644 --- a/packages/lib/services/ExternalEditWatcher.ts +++ b/packages/lib/services/ExternalEditWatcher.ts @@ -5,7 +5,7 @@ import { fileExtension, basename, toSystemSlashes } from '../path-utils'; import time from '../time'; import { NoteEntity } from './database/types'; -const Note = require('../models/Note'); +import Note from '../models/Note'; const EventEmitter = require('events'); const { splitCommandString } = require('../string-utils'); const spawn = require('child_process').spawn; diff --git a/packages/lib/services/ItemChangeUtils.js b/packages/lib/services/ItemChangeUtils.ts similarity index 68% rename from packages/lib/services/ItemChangeUtils.js rename to packages/lib/services/ItemChangeUtils.ts index 3e044ba17..469aad32b 100644 --- a/packages/lib/services/ItemChangeUtils.js +++ b/packages/lib/services/ItemChangeUtils.ts @@ -1,7 +1,7 @@ -const Setting = require('../models/Setting').default; -const ItemChange = require('../models/ItemChange'); +import Setting from '../models/Setting'; +import ItemChange from '../models/ItemChange'; -class ItemChangeUtils { +export default class ItemChangeUtils { static async deleteProcessedChanges() { const lastProcessedChangeIds = [Setting.value('resourceService.lastProcessedChangeId'), Setting.value('searchEngine.lastProcessedChangeId'), Setting.value('revisionService.lastProcessedChangeId')]; @@ -9,5 +9,3 @@ class ItemChangeUtils { await ItemChange.deleteOldChanges(lowestChangeId); } } - -module.exports = ItemChangeUtils; diff --git a/packages/lib/services/KeymapService.ts b/packages/lib/services/KeymapService.ts index afa3f475d..3ecb38698 100644 --- a/packages/lib/services/KeymapService.ts +++ b/packages/lib/services/KeymapService.ts @@ -4,7 +4,7 @@ import { _ } from '../locale'; import keysRegExp from './KeymapService_keysRegExp'; import keycodeToElectronMap from './KeymapService_keycodeToElectronMap'; -const BaseService = require('./BaseService').default; +import BaseService from './BaseService'; const modifiersRegExp = { darwin: /^(Ctrl|Option|Shift|Cmd)$/, @@ -114,6 +114,7 @@ export default class KeymapService extends BaseService { private customKeymapPath: string; private defaultKeymapItems: KeymapItem[]; private lastSaveTime_: number; + private modifiersRegExp: any; public constructor() { super(); diff --git a/packages/lib/services/MigrationService.js b/packages/lib/services/MigrationService.ts similarity index 71% rename from packages/lib/services/MigrationService.js rename to packages/lib/services/MigrationService.ts index 6c3db29d1..30aab7d4d 100644 --- a/packages/lib/services/MigrationService.js +++ b/packages/lib/services/MigrationService.ts @@ -1,10 +1,9 @@ -const BaseService = require('./BaseService').default; -const Migration = require('../models/Migration'); +import BaseService from './BaseService'; +import Migration from '../models/Migration'; -class MigrationService extends BaseService { - constructor() { - super(); - } +export default class MigrationService extends BaseService { + + private static instance_: MigrationService; static instance() { if (this.instance_) return this.instance_; @@ -12,7 +11,7 @@ class MigrationService extends BaseService { return this.instance_; } - async runScript(num) { + async runScript(num: number) { const script = Migration.script(num); await script.exec(); } @@ -33,5 +32,3 @@ class MigrationService extends BaseService { } } } - -module.exports = MigrationService; diff --git a/packages/lib/services/ModelCache.js b/packages/lib/services/ModelCache.js deleted file mode 100644 index 75fbfe782..000000000 --- a/packages/lib/services/ModelCache.js +++ /dev/null @@ -1,36 +0,0 @@ -const BaseItem = require('../models/BaseItem'); - -class ModelCache { - constructor() { - this.cache_ = {}; - } - - async byIds(itemType, ids) { - const ModelClass = BaseItem.getClassByItemType(itemType); - const output = []; - - const remainingIds = []; - for (let i = 0; i < ids.length; i++) { - const id = ids[i]; - if (!this.cache_[id]) { - remainingIds.push(id); - } else { - output.push(this.cache_[id].model); - } - } - - const models = await ModelClass.byIds(remainingIds); - for (let i = 0; i < models.length; i++) { - this.cache_[models[i].id] = { - model: models[i], - timestamp: Date.now(), - }; - - output.push(models[i]); - } - - return output; - } -} - -module.exports = ModelCache; diff --git a/packages/lib/services/NavService.js b/packages/lib/services/NavService.ts similarity index 62% rename from packages/lib/services/NavService.js rename to packages/lib/services/NavService.ts index 417301fbf..b9d921fcf 100644 --- a/packages/lib/services/NavService.js +++ b/packages/lib/services/NavService.ts @@ -1,5 +1,9 @@ -class NavService { - static async go(routeName) { +export default class NavService { + + public static dispatch: Function = () => {}; + private static handlers_: Function[] = []; + + static async go(routeName: string) { if (this.handlers_.length) { const r = await this.handlers_[this.handlers_.length - 1](); if (r) return r; @@ -11,23 +15,19 @@ class NavService { }); } - static addHandler(handler) { + static addHandler(handler: Function) { for (let i = this.handlers_.length - 1; i >= 0; i--) { const h = this.handlers_[i]; if (h === handler) return; } - return this.handlers_.push(handler); + this.handlers_.push(handler); } - static removeHandler(hanlder) { + static removeHandler(hanlder: Function) { for (let i = this.handlers_.length - 1; i >= 0; i--) { const h = this.handlers_[i]; if (h === hanlder) this.handlers_.splice(i, 1); } } } - -NavService.handlers_ = []; - -module.exports = NavService; diff --git a/packages/lib/services/report.js b/packages/lib/services/ReportService.ts similarity index 89% rename from packages/lib/services/report.js rename to packages/lib/services/ReportService.ts index 1694431fa..e1efe0732 100644 --- a/packages/lib/services/report.js +++ b/packages/lib/services/ReportService.ts @@ -1,17 +1,17 @@ -const time = require('../time').default; -const BaseItem = require('../models/BaseItem.js'); -const Alarm = require('../models/Alarm').default; -const Folder = require('../models/Folder.js'); -const Note = require('../models/Note.js'); -const BaseModel = require('../BaseModel').default; -const DecryptionWorker = require('./DecryptionWorker'); -const ResourceFetcher = require('./ResourceFetcher'); -const Resource = require('../models/Resource'); -const { _ } = require('../locale'); +import time from '../time'; +import BaseItem from '../models/BaseItem'; +import Alarm from '../models/Alarm'; +import Folder from '../models/Folder'; +import Note from '../models/Note'; +import BaseModel from '../BaseModel'; +import DecryptionWorker from './DecryptionWorker'; +import ResourceFetcher from './ResourceFetcher'; +import Resource from '../models/Resource'; +import { _ } from '../locale'; const { toTitleCase } = require('../string-utils.js'); -class ReportService { - csvEscapeCell(cell) { +export default class ReportService { + csvEscapeCell(cell: string) { cell = this.csvValueToString(cell); const output = cell.replace(/"/, '""'); if (this.csvCellRequiresQuotes(cell, ',')) { @@ -20,26 +20,26 @@ class ReportService { return output; } - csvCellRequiresQuotes(cell, delimiter) { + csvCellRequiresQuotes(cell: string, delimiter: string) { if (cell.indexOf('\n') >= 0) return true; if (cell.indexOf('"') >= 0) return true; if (cell.indexOf(delimiter) >= 0) return true; return false; } - csvValueToString(v) { + csvValueToString(v: string) { if (v === undefined || v === null) return ''; return v.toString(); } - csvCreateLine(row) { + csvCreateLine(row: string[]) { for (let i = 0; i < row.length; i++) { row[i] = this.csvEscapeCell(row[i]); } return row.join(','); } - csvCreate(rows) { + csvCreate(rows: any[]) { const output = []; for (let i = 0; i < rows.length; i++) { output.push(this.csvCreateLine(rows[i])); @@ -47,7 +47,7 @@ class ReportService { return output.join('\n'); } - async basicItemList(option = null) { + async basicItemList(option: any = null) { if (!option) option = {}; if (!option.format) option.format = 'array'; @@ -70,8 +70,8 @@ class ReportService { return option.format === 'csv' ? this.csvCreate(output) : output; } - async syncStatus(syncTarget) { - const output = { + async syncStatus(syncTarget: number) { + const output: any = { items: {}, total: {}, }; @@ -110,10 +110,10 @@ class ReportService { return output; } - async status(syncTarget) { + async status(syncTarget: number) { const r = await this.syncStatus(syncTarget); const sections = []; - let section = null; + let section: any = null; const disabledItems = await BaseItem.syncDisabledItems(syncTarget); @@ -153,12 +153,12 @@ class ReportService { canRetryType: 'e2ee', retryHandler: async () => { await DecryptionWorker.instance().clearDisabledItem(row.type_, row.id); - DecryptionWorker.instance().scheduleStart(); + void DecryptionWorker.instance().scheduleStart(); }, }); } - const retryHandlers = []; + const retryHandlers: any[] = []; for (let i = 0; i < section.body.length; i++) { if (section.body[i].canRetry) { @@ -213,7 +213,7 @@ class ReportService { canRetryType: 'resourceDownload', retryHandler: async () => { await Resource.resetErrorStatus(row.resource_id); - ResourceFetcher.instance().autoAddResources(); + void ResourceFetcher.instance().autoAddResources(); }, }); } @@ -265,5 +265,3 @@ class ReportService { return sections; } } - -module.exports = { ReportService }; diff --git a/packages/lib/services/ResourceEditWatcher/index.ts b/packages/lib/services/ResourceEditWatcher/index.ts index 5ea019d78..e73ad523a 100644 --- a/packages/lib/services/ResourceEditWatcher/index.ts +++ b/packages/lib/services/ResourceEditWatcher/index.ts @@ -2,9 +2,9 @@ import AsyncActionQueue from '../../AsyncActionQueue'; import shim from '../../shim'; import { _ } from '../../locale'; import { toSystemSlashes } from '../../path-utils'; -const Logger = require('../../Logger').default; -const Setting = require('../../models/Setting').default; -const Resource = require('../../models/Resource'); +import Logger from '../../Logger'; +import Setting from '../../models/Setting'; +import Resource from '../../models/Resource'; const EventEmitter = require('events'); const chokidar = require('chokidar'); const bridge = require('electron').remote.require('./bridge').default; diff --git a/packages/lib/services/ResourceFetcher.js b/packages/lib/services/ResourceFetcher.ts similarity index 84% rename from packages/lib/services/ResourceFetcher.js rename to packages/lib/services/ResourceFetcher.ts index afa05800d..bd19a42dc 100644 --- a/packages/lib/services/ResourceFetcher.js +++ b/packages/lib/services/ResourceFetcher.ts @@ -1,26 +1,32 @@ -const Resource = require('../models/Resource'); -const Setting = require('../models/Setting').default; -const BaseService = require('./BaseService').default; -const ResourceService = require('./ResourceService').default; +import Resource from '../models/Resource'; +import Setting from '../models/Setting'; +import BaseService from './BaseService'; +import ResourceService from './ResourceService'; +import Logger from '../Logger'; +import shim from '../shim'; const { Dirnames } = require('./synchronizer/utils/types'); -const Logger = require('../Logger').default; const EventEmitter = require('events'); -const shim = require('../shim').default; -class ResourceFetcher extends BaseService { - constructor(fileApi = null) { +export default class ResourceFetcher extends BaseService { + + public static instance_: ResourceFetcher; + + public dispatch: Function = (_o: any) => {}; + private logger_: Logger = new Logger(); + private queue_: any[] = []; + private fetchingItems_: any = {}; + private maxDownloads_ = 3; + private addingResources_ = false; + private eventEmitter_ = new EventEmitter(); + private autoAddResourcesCalls_: any[] = []; + private fileApi_: any; + private updateReportIID_: any; + private scheduleQueueProcessIID_: any; + private scheduleAutoAddResourcesIID_: any; + + constructor(fileApi: any = null) { super(); - - this.dispatch = () => {}; - this.setFileApi(fileApi); - this.logger_ = new Logger(); - this.queue_ = []; - this.fetchingItems_ = {}; - this.maxDownloads_ = 3; - this.addingResources_ = false; - this.eventEmitter_ = new EventEmitter(); - this.autoAddResourcesCalls_ = []; } static instance() { @@ -29,15 +35,15 @@ class ResourceFetcher extends BaseService { return ResourceFetcher.instance_; } - on(eventName, callback) { + on(eventName: string, callback: Function) { return this.eventEmitter_.on(eventName, callback); } - off(eventName, callback) { + off(eventName: string, callback: Function) { return this.eventEmitter_.removeListener(eventName, callback); } - setLogger(logger) { + setLogger(logger: Logger) { this.logger_ = logger; } @@ -45,7 +51,7 @@ class ResourceFetcher extends BaseService { return this.logger_; } - setFileApi(v) { + setFileApi(v: any) { if (v !== null && typeof v !== 'function') throw new Error(`fileApi must be a function that returns the API. Type is ${typeof v}`); this.fileApi_ = v; } @@ -54,7 +60,7 @@ class ResourceFetcher extends BaseService { return this.fileApi_(); } - queuedItemIndex_(resourceId) { + queuedItemIndex_(resourceId: string) { for (let i = 0; i < this.fetchingItems_.length; i++) { const item = this.fetchingItems_[i]; if (item.id === resourceId) return i; @@ -71,7 +77,7 @@ class ResourceFetcher extends BaseService { }); } - async markForDownload(resourceIds) { + async markForDownload(resourceIds: string[]) { if (!Array.isArray(resourceIds)) resourceIds = [resourceIds]; const fetchStatuses = await Resource.fetchStatuses(resourceIds); @@ -91,7 +97,7 @@ class ResourceFetcher extends BaseService { } } - queueDownload_(resourceId, priority = null) { + queueDownload_(resourceId: string, priority: string = null) { if (priority === null) priority = 'normal'; const index = this.queuedItemIndex_(resourceId); @@ -112,7 +118,7 @@ class ResourceFetcher extends BaseService { return true; } - async startDownload_(resourceId) { + async startDownload_(resourceId: string) { if (this.fetchingItems_[resourceId]) return; this.fetchingItems_[resourceId] = true; @@ -175,7 +181,7 @@ class ResourceFetcher extends BaseService { this.logger().debug(`ResourceFetcher: Resource downloaded: ${resource.id}`); await completeDownload(true, localResourceContentPath); }) - .catch(async error => { + .catch(async (error: any) => { this.logger().error(`ResourceFetcher: Could not download resource: ${resource.id}`, error); await Resource.setLocalState(resource, { fetch_status: Resource.FETCH_STATUS_ERROR, fetch_error: error.message }); await completeDownload(); @@ -186,11 +192,11 @@ class ResourceFetcher extends BaseService { while (Object.getOwnPropertyNames(this.fetchingItems_).length < this.maxDownloads_) { if (!this.queue_.length) break; const item = this.queue_.splice(0, 1)[0]; - this.startDownload_(item.id); + void this.startDownload_(item.id); } if (!this.queue_.length) { - this.autoAddResources(10); + void this.autoAddResources(10); } } @@ -204,13 +210,13 @@ class ResourceFetcher extends BaseService { !Object.getOwnPropertyNames(this.fetchingItems_).length) { shim.clearInterval(iid); - resolve(); + resolve(null); } }, 100); }); } - async autoAddResources(limit = null) { + async autoAddResources(limit: number = null) { this.autoAddResourcesCalls_.push(true); try { if (limit === null) limit = 10; @@ -240,7 +246,7 @@ class ResourceFetcher extends BaseService { async start() { await Resource.resetStartedFetchStatus(); - this.autoAddResources(10); + void this.autoAddResources(10); } scheduleQueueProcess() { @@ -260,13 +266,13 @@ class ResourceFetcher extends BaseService { this.scheduleAutoAddResourcesIID_ = shim.setTimeout(() => { this.scheduleAutoAddResourcesIID_ = null; - ResourceFetcher.instance().autoAddResources(); + void ResourceFetcher.instance().autoAddResources(); }, 1000); } async fetchAll() { await Resource.resetStartedFetchStatus(); - this.autoAddResources(null); + void this.autoAddResources(null); } async destroy() { @@ -284,7 +290,3 @@ class ResourceFetcher extends BaseService { ResourceFetcher.instance_ = null; } } - -ResourceFetcher.instance_ = null; - -module.exports = ResourceFetcher; diff --git a/packages/lib/services/ResourceService.ts b/packages/lib/services/ResourceService.ts index 5782e6f06..6424ece50 100644 --- a/packages/lib/services/ResourceService.ts +++ b/packages/lib/services/ResourceService.ts @@ -3,16 +3,16 @@ import BaseModel from '../BaseModel'; import BaseService from './BaseService'; import Setting from '../models/Setting'; import shim from '../shim'; -const ItemChange = require('../models/ItemChange'); -const Note = require('../models/Note'); -const Resource = require('../models/Resource'); -const SearchEngine = require('./searchengine/SearchEngine'); -const ItemChangeUtils = require('./ItemChangeUtils'); +import ItemChange from '../models/ItemChange'; +import Note from '../models/Note'; +import Resource from '../models/Resource'; +import SearchEngine from './searchengine/SearchEngine'; +import ItemChangeUtils from './ItemChangeUtils'; const { sprintf } = require('sprintf-js'); export default class ResourceService extends BaseService { - private static isRunningInBackground_: boolean = false; + public static isRunningInBackground_: boolean = false; private maintenanceCalls_: boolean[] = []; private maintenanceTimer1_: any = null; @@ -182,7 +182,7 @@ export default class ResourceService extends BaseService { }); } - private static instance_: ResourceService = null; + public static instance_: ResourceService = null; public static instance() { if (this.instance_) return this.instance_; diff --git a/packages/lib/services/RevisionService.js b/packages/lib/services/RevisionService.ts similarity index 80% rename from packages/lib/services/RevisionService.js rename to packages/lib/services/RevisionService.ts index e2fcbb0e6..808122725 100644 --- a/packages/lib/services/RevisionService.js +++ b/packages/lib/services/RevisionService.ts @@ -1,30 +1,31 @@ -const ItemChange = require('../models/ItemChange'); -const Note = require('../models/Note'); -const Folder = require('../models/Folder'); -const Setting = require('../models/Setting').default; -const Revision = require('../models/Revision'); -const BaseModel = require('../BaseModel').default; -const ItemChangeUtils = require('./ItemChangeUtils'); -const shim = require('../shim').default; -const BaseService = require('./BaseService').default; -const { _ } = require('../locale'); +import ItemChange from '../models/ItemChange'; +import Note from '../models/Note'; +import Folder from '../models/Folder'; +import Setting from '../models/Setting'; +import Revision from '../models/Revision'; +import BaseModel from '../BaseModel'; +import ItemChangeUtils from './ItemChangeUtils'; +import shim from '../shim'; +import BaseService from './BaseService'; +import { _ } from '../locale'; +import { ItemChangeEntity, NoteEntity, RevisionEntity } from './database/types'; const { sprintf } = require('sprintf-js'); const { wrapError } = require('../errorUtils'); -class RevisionService extends BaseService { - constructor() { - super(); +export default class RevisionService extends BaseService { - // An "old note" is one that has been created before the revision service existed. These - // notes never benefited from revisions so the first time they are modified, a copy of - // the original note is saved. The goal is to have at least one revision in case the note - // is deleted or modified as a result of a bug or user mistake. - this.isOldNotesCache_ = {}; + public static instance_: RevisionService; - this.maintenanceCalls_ = []; - this.maintenanceTimer1_ = null; - this.maintenanceTimer2_ = null; - } + // An "old note" is one that has been created before the revision service existed. These + // notes never benefited from revisions so the first time they are modified, a copy of + // the original note is saved. The goal is to have at least one revision in case the note + // is deleted or modified as a result of a bug or user mistake. + private isOldNotesCache_: any = {}; + private maintenanceCalls_: any[] = []; + private maintenanceTimer1_: any = null; + private maintenanceTimer2_: any = null; + private isCollecting_ = false; + public isRunningInBackground_ = false; static instance() { if (this.instance_) return this.instance_; @@ -36,7 +37,7 @@ class RevisionService extends BaseService { return Date.now() - Setting.value('revisionService.oldNoteInterval'); } - async isOldNote(noteId) { + async isOldNote(noteId: string) { if (noteId in this.isOldNotesCache_) return this.isOldNotesCache_[noteId]; const isOld = await Note.noteIsOlderThan(noteId, this.oldNoteCutOffDate_()); @@ -44,12 +45,12 @@ class RevisionService extends BaseService { return isOld; } - noteMetadata_(note) { + noteMetadata_(note: NoteEntity) { const excludedFields = ['type_', 'title', 'body', 'created_time', 'updated_time', 'encryption_applied', 'encryption_cipher_text', 'is_conflict']; - const md = {}; + const md: any = {}; for (const k in note) { if (excludedFields.indexOf(k) >= 0) continue; - md[k] = note[k]; + md[k] = (note as any)[k]; } if (note.user_updated_time === note.updated_time) delete md.user_updated_time; @@ -58,7 +59,7 @@ class RevisionService extends BaseService { return md; } - isEmptyRevision_(rev) { + isEmptyRevision_(rev: RevisionEntity) { if (rev.title_diff) return false; if (rev.body_diff) return false; @@ -69,11 +70,11 @@ class RevisionService extends BaseService { return true; } - async createNoteRevision_(note, parentRevId = null) { + async createNoteRevision_(note: NoteEntity, parentRevId: string = null) { try { const parentRev = parentRevId ? await Revision.load(parentRevId) : await Revision.latestRevision(BaseModel.TYPE_NOTE, note.id); - const output = { + const output: RevisionEntity = { parent_id: '', item_type: BaseModel.TYPE_NOTE, item_id: note.id, @@ -120,7 +121,7 @@ class RevisionService extends BaseService { while (true) { // See synchronizer test units to see why changes coming // from sync are skipped. - const changes = await ItemChange.modelSelectAll( + const changes: ItemChangeEntity[] = await ItemChange.modelSelectAll( ` SELECT id, item_id, type, before_change_item FROM item_changes @@ -136,7 +137,7 @@ class RevisionService extends BaseService { if (!changes.length) break; - const noteIds = changes.map(a => a.item_id); + const noteIds = changes.map((a) => a.item_id); const notes = await Note.modelSelectAll(`SELECT * FROM notes WHERE is_conflict = 0 AND encryption_applied = 0 AND id IN ("${noteIds.join('","')}")`); for (let i = 0; i < changes.length; i++) { @@ -193,17 +194,17 @@ class RevisionService extends BaseService { this.logger().info(`RevisionService::collectRevisions: Created revisions for ${doneNoteIds.length} notes`); } - async deleteOldRevisions(ttl) { + async deleteOldRevisions(ttl: number) { return Revision.deleteOldRevisions(ttl); } - async revisionNote(revisions, index) { + async revisionNote(revisions: RevisionEntity[], index: number) { if (index < 0 || index >= revisions.length) throw new Error(`Invalid revision index: ${index}`); const rev = revisions[index]; const merged = await Revision.mergeDiffs(rev, revisions); - const output = Object.assign( + const output: NoteEntity = Object.assign( { title: merged.title, body: merged.body, @@ -212,7 +213,7 @@ class RevisionService extends BaseService { ); output.updated_time = output.user_updated_time; output.created_time = output.user_created_time; - output.type_ = BaseModel.TYPE_NOTE; + (output as any).type_ = BaseModel.TYPE_NOTE; return output; } @@ -229,7 +230,7 @@ class RevisionService extends BaseService { return folder; } - async importRevisionNote(note) { + async importRevisionNote(note: NoteEntity) { const toImport = Object.assign({}, note); delete toImport.id; delete toImport.updated_time; @@ -268,7 +269,7 @@ class RevisionService extends BaseService { } } - runInBackground(collectRevisionInterval = null) { + runInBackground(collectRevisionInterval: number = null) { if (this.isRunningInBackground_) return; this.isRunningInBackground_ = true; @@ -277,21 +278,21 @@ class RevisionService extends BaseService { this.logger().info(`RevisionService::runInBackground: Starting background service with revision collection interval ${collectRevisionInterval}`); this.maintenanceTimer1_ = shim.setTimeout(() => { - this.maintenance(); + void this.maintenance(); }, 1000 * 4); - this.maintenanceTImer2_ = shim.setInterval(() => { - this.maintenance(); + this.maintenanceTimer2_ = shim.setInterval(() => { + void this.maintenance(); }, collectRevisionInterval); } async cancelTimers() { if (this.maintenanceTimer1_) { - shim.clearTimeout(this.maintenanceTimer1); + shim.clearTimeout(this.maintenanceTimer1_); this.maintenanceTimer1_ = null; } if (this.maintenanceTimer2_) { - shim.clearInterval(this.maintenanceTimer2); + shim.clearInterval(this.maintenanceTimer2_); this.maintenanceTimer2_ = null; } @@ -299,11 +300,9 @@ class RevisionService extends BaseService { const iid = shim.setInterval(() => { if (!this.maintenanceCalls_.length) { shim.clearInterval(iid); - resolve(); + resolve(null); } }, 100); }); } } - -module.exports = RevisionService; diff --git a/packages/lib/services/SettingUtils.ts b/packages/lib/services/SettingUtils.ts index 8f6fd0f3b..4e5e11992 100644 --- a/packages/lib/services/SettingUtils.ts +++ b/packages/lib/services/SettingUtils.ts @@ -1,8 +1,8 @@ /* eslint-disable import/prefer-default-export */ import KeychainService from './keychain/KeychainService'; -const Setting = require('../models/Setting').default; -const uuid = require('../uuid').default; +import Setting from '../models/Setting'; +import uuid from '../uuid'; // This function takes care of initialising both the keychain service and settings. // diff --git a/packages/lib/services/commands/stateToWhenClauseContext.ts b/packages/lib/services/commands/stateToWhenClauseContext.ts index 84d97a25f..7a9c7d7f3 100644 --- a/packages/lib/services/commands/stateToWhenClauseContext.ts +++ b/packages/lib/services/commands/stateToWhenClauseContext.ts @@ -1,8 +1,8 @@ import { State, stateUtils } from '../../reducer'; -const BaseModel = require('../../BaseModel').default; -const Folder = require('../../models/Folder'); -const MarkupToHtml = require('@joplin/renderer/MarkupToHtml').default; +import BaseModel from '../../BaseModel'; +import Folder from '../../models/Folder'; +import MarkupToHtml from '@joplin/renderer/MarkupToHtml'; export default function stateToWhenClauseContext(state: State) { const noteId = state.selectedNoteIds.length === 1 ? state.selectedNoteIds[0] : null; diff --git a/packages/lib/services/debug/populateDatabase.ts b/packages/lib/services/debug/populateDatabase.ts index 025bcf87e..c666328a6 100644 --- a/packages/lib/services/debug/populateDatabase.ts +++ b/packages/lib/services/debug/populateDatabase.ts @@ -1,6 +1,6 @@ -const Folder = require('../../models/Folder'); -const Note = require('../../models/Note'); -const Tag = require('../../models/Tag'); +import Folder from '../../models/Folder'; +import Note from '../../models/Note'; +import Tag from '../../models/Tag'; function randomIndex(array: any[]): number { return Math.round(Math.random() * (array.length - 1)); diff --git a/packages/lib/services/interop/InteropService.ts b/packages/lib/services/interop/InteropService.ts index 9baf82c5c..c645330e6 100644 --- a/packages/lib/services/interop/InteropService.ts +++ b/packages/lib/services/interop/InteropService.ts @@ -3,12 +3,12 @@ import InteropService_Importer_Custom from './InteropService_Importer_Custom'; import InteropService_Exporter_Custom from './InteropService_Exporter_Custom'; import shim from '../../shim'; import { _ } from '../../locale'; -const BaseItem = require('../../models/BaseItem.js'); -const BaseModel = require('../../BaseModel').default; -const Resource = require('../../models/Resource.js'); -const Folder = require('../../models/Folder.js'); -const NoteTag = require('../../models/NoteTag.js'); -const Note = require('../../models/Note.js'); +import BaseItem from '../../models/BaseItem'; +import BaseModel from '../../BaseModel'; +import Resource from '../../models/Resource'; +import Folder from '../../models/Folder'; +import NoteTag from '../../models/NoteTag'; +import Note from '../../models/Note'; const ArrayUtils = require('../../ArrayUtils'); const { sprintf } = require('sprintf-js'); const { fileExtension } = require('../../path-utils'); @@ -338,7 +338,7 @@ export default class InteropService { let resourceIds: string[] = []; // Recursively get all the folders that have valid parents - const folderIds = await Folder.childrenIds('', true); + const folderIds = await Folder.childrenIds(''); if (options.includeConflicts) folderIds.push(Folder.conflictFolderId()); diff --git a/packages/lib/services/interop/InteropService_Exporter_Base.ts b/packages/lib/services/interop/InteropService_Exporter_Base.ts index c2fdd8993..c09e29fcd 100644 --- a/packages/lib/services/interop/InteropService_Exporter_Base.ts +++ b/packages/lib/services/interop/InteropService_Exporter_Base.ts @@ -1,6 +1,6 @@ /* eslint @typescript-eslint/no-unused-vars: 0, no-unused-vars: ["error", { "argsIgnorePattern": ".*" }], */ -const Setting = require('../../models/Setting').default; +import Setting from '../../models/Setting'; export default class InteropService_Exporter_Base { private context_: any = {}; diff --git a/packages/lib/services/interop/InteropService_Exporter_Html.ts b/packages/lib/services/interop/InteropService_Exporter_Html.ts index 016b1aae2..7ae8b5d62 100644 --- a/packages/lib/services/interop/InteropService_Exporter_Html.ts +++ b/packages/lib/services/interop/InteropService_Exporter_Html.ts @@ -1,18 +1,29 @@ -const InteropService_Exporter_Base = require('./InteropService_Exporter_Base').default; +import InteropService_Exporter_Base from './InteropService_Exporter_Base'; +import BaseModel from '../../BaseModel'; +import shim from '../../shim'; +import markupLanguageUtils from '../../markupLanguageUtils'; +import Folder from '../../models/Folder'; +import Note from '../../models/Note'; +import Setting from '../../models/Setting'; +import { MarkupToHtml } from '@joplin/renderer'; +import { ResourceEntity } from '../database/types'; const { basename, friendlySafeFilename, rtrimSlashes } = require('../../path-utils'); -const BaseModel = require('../../BaseModel').default; -const Folder = require('../../models/Folder'); -const Note = require('../../models/Note'); -const Setting = require('../../models/Setting').default; -const shim = require('../../shim').default; const { themeStyle } = require('../../theme'); const { dirname } = require('../../path-utils'); const { escapeHtml } = require('../../string-utils.js'); -const markupLanguageUtils = require('../../markupLanguageUtils').default; const { assetsToHeaders } = require('@joplin/renderer'); export default class InteropService_Exporter_Html extends InteropService_Exporter_Base { + private customCss_: string; + private destDir_: string; + private filePath_: string; + private createdDirs_: string[] = []; + private resourceDir_: string; + private markupToHtml_: MarkupToHtml; + private resources_: ResourceEntity[] = []; + private style_: any; + async init(path: string, options: any = {}) { this.customCss_ = options.customCss ? options.customCss : ''; @@ -24,12 +35,10 @@ export default class InteropService_Exporter_Html extends InteropService_Exporte this.filePath_ = null; } - this.createdDirs_ = []; this.resourceDir_ = this.destDir_ ? `${this.destDir_}/_resources` : null; await shim.fsDriver().mkdir(this.destDir_); this.markupToHtml_ = markupLanguageUtils.newMarkupToHtml(options.plugins); - this.resources_ = []; this.style_ = themeStyle(Setting.THEME_LIGHT); } diff --git a/packages/lib/services/interop/InteropService_Exporter_Md.ts b/packages/lib/services/interop/InteropService_Exporter_Md.ts index 7d8b84ab3..0af87ea89 100644 --- a/packages/lib/services/interop/InteropService_Exporter_Md.ts +++ b/packages/lib/services/interop/InteropService_Exporter_Md.ts @@ -1,12 +1,17 @@ -const InteropService_Exporter_Base = require('./InteropService_Exporter_Base').default; -const { basename, dirname, friendlySafeFilename } = require('../../path-utils'); -const BaseModel = require('../../BaseModel').default; -const Folder = require('../../models/Folder'); -const Note = require('../../models/Note'); -const shim = require('../../shim').default; -const markdownUtils = require('../../markdownUtils').default; +import InteropService_Exporter_Base from './InteropService_Exporter_Base'; +import BaseModel from '../../BaseModel'; +import shim from '../../shim'; +import markdownUtils from '../../markdownUtils'; +import Folder from '../../models/Folder'; +import Note from '../../models/Note'; +import { basename, dirname, friendlySafeFilename } from '../../path-utils'; export default class InteropService_Exporter_Md extends InteropService_Exporter_Base { + + private destDir_: string; + private resourceDir_: string; + private createdDirs_: string[]; + async init(destDir: string) { this.destDir_ = destDir; this.resourceDir_ = destDir ? `${destDir}/_resources` : null; @@ -23,7 +28,7 @@ export default class InteropService_Exporter_Md extends InteropService_Exporter_ if (pathPart) { output = `${pathPart}/${output}`; } else { - output = `${friendlySafeFilename(item.title, null, true)}/${output}`; + output = `${friendlySafeFilename(item.title, null)}/${output}`; if (findUniqueFilename) output = await shim.fsDriver().findUniqueFilename(output); } } @@ -87,7 +92,7 @@ export default class InteropService_Exporter_Md extends InteropService_Exporter_ if (!note) continue; - let notePath = `${await this.makeDirPath_(note, null, false)}${friendlySafeFilename(note.title, null, true)}.md`; + let notePath = `${await this.makeDirPath_(note, null, false)}${friendlySafeFilename(note.title, null)}.md`; notePath = await shim.fsDriver().findUniqueFilename(`${this.destDir_}/${notePath}`, Object.values(context.notePaths)); context.notePaths[note.id] = notePath; } diff --git a/packages/lib/services/interop/InteropService_Exporter_Raw.ts b/packages/lib/services/interop/InteropService_Exporter_Raw.ts index 1c38e4831..e34838d8f 100644 --- a/packages/lib/services/interop/InteropService_Exporter_Raw.ts +++ b/packages/lib/services/interop/InteropService_Exporter_Raw.ts @@ -1,9 +1,13 @@ -const InteropService_Exporter_Base = require('./InteropService_Exporter_Base').default; -const BaseItem = require('../../models/BaseItem.js'); +import InteropService_Exporter_Base from './InteropService_Exporter_Base'; +import BaseItem from '../../models/BaseItem'; const { basename } = require('../../path-utils'); -const shim = require('../../shim').default; +import shim from '../../shim'; export default class InteropService_Exporter_Raw extends InteropService_Exporter_Base { + + private destDir_: string; + private resourceDir_: string; + async init(destDir: string) { this.destDir_ = destDir; this.resourceDir_ = destDir ? `${destDir}/resources` : null; diff --git a/packages/lib/services/interop/InteropService_Importer_Base.ts b/packages/lib/services/interop/InteropService_Importer_Base.ts index a18334634..199ca6360 100644 --- a/packages/lib/services/interop/InteropService_Importer_Base.ts +++ b/packages/lib/services/interop/InteropService_Importer_Base.ts @@ -2,7 +2,7 @@ import { ImportExportResult } from './types'; -const Setting = require('../../models/Setting').default; +import Setting from '../../models/Setting'; export default class InteropService_Importer_Base { private metadata_: any = null; @@ -23,7 +23,7 @@ export default class InteropService_Importer_Base { } // @ts-ignore - async exec(result: ImportExportResult) {} + async exec(result: ImportExportResult): Promise {} async temporaryDirectory_(createIt: boolean) { const md5 = require('md5'); diff --git a/packages/lib/services/interop/InteropService_Importer_Custom.ts b/packages/lib/services/interop/InteropService_Importer_Custom.ts index b7c078028..e289b2e8e 100644 --- a/packages/lib/services/interop/InteropService_Importer_Custom.ts +++ b/packages/lib/services/interop/InteropService_Importer_Custom.ts @@ -10,7 +10,7 @@ export default class InteropService_Importer_Custom extends InteropService_Impor this.module_ = handler; } - async exec(result: ImportExportResult) { + async exec(result: ImportExportResult): Promise { return this.module_.onExec({ sourcePath: this.sourcePath_, options: this.options_, diff --git a/packages/lib/services/interop/InteropService_Importer_EnexToHtml.ts b/packages/lib/services/interop/InteropService_Importer_EnexToHtml.ts index 321ce103b..3fce7e03d 100644 --- a/packages/lib/services/interop/InteropService_Importer_EnexToHtml.ts +++ b/packages/lib/services/interop/InteropService_Importer_EnexToHtml.ts @@ -1,11 +1,10 @@ import { ImportExportResult } from './types'; - -const InteropService_Importer_Base = require('./InteropService_Importer_Base').default; -const Folder = require('../../models/Folder.js'); +import InteropService_Importer_Base from './InteropService_Importer_Base'; +import Folder from '../../models/Folder'; const { filename } = require('../../path-utils'); export default class InteropService_Importer_EnexToHtml extends InteropService_Importer_Base { - async exec(result: ImportExportResult) { + async exec(result: ImportExportResult): Promise { const { importEnex } = require('../../import-enex'); let folder = this.options_.destinationFolder; diff --git a/packages/lib/services/interop/InteropService_Importer_EnexToMd.ts b/packages/lib/services/interop/InteropService_Importer_EnexToMd.ts index 5a29bde3b..06a1776af 100644 --- a/packages/lib/services/interop/InteropService_Importer_EnexToMd.ts +++ b/packages/lib/services/interop/InteropService_Importer_EnexToMd.ts @@ -1,7 +1,7 @@ import { ImportExportResult } from './types'; -const InteropService_Importer_Base = require('./InteropService_Importer_Base').default; -const Folder = require('../../models/Folder.js'); +import InteropService_Importer_Base from './InteropService_Importer_Base'; +import Folder from '../../models/Folder'; const { filename } = require('../../path-utils'); export default class InteropService_Importer_EnexToMd extends InteropService_Importer_Base { diff --git a/packages/lib/services/interop/InteropService_Importer_Jex.ts b/packages/lib/services/interop/InteropService_Importer_Jex.ts index 6db664a2e..097ac9a15 100644 --- a/packages/lib/services/interop/InteropService_Importer_Jex.ts +++ b/packages/lib/services/interop/InteropService_Importer_Jex.ts @@ -1,7 +1,7 @@ import { ImportExportResult } from './types'; -const InteropService_Importer_Base = require('./InteropService_Importer_Base').default; -const InteropService_Importer_Raw = require('./InteropService_Importer_Raw').default; +import InteropService_Importer_Base from './InteropService_Importer_Base'; +import InteropService_Importer_Raw from './InteropService_Importer_Raw'; const { filename } = require('../../path-utils'); const fs = require('fs-extra'); diff --git a/packages/lib/services/interop/InteropService_Importer_Md.ts b/packages/lib/services/interop/InteropService_Importer_Md.ts index ef007974e..4bb576ed1 100644 --- a/packages/lib/services/interop/InteropService_Importer_Md.ts +++ b/packages/lib/services/interop/InteropService_Importer_Md.ts @@ -1,12 +1,12 @@ import { ImportExportResult } from './types'; import { _ } from '../../locale'; -const InteropService_Importer_Base = require('./InteropService_Importer_Base').default; -const Folder = require('../../models/Folder.js'); -const Note = require('../../models/Note.js'); +import InteropService_Importer_Base from './InteropService_Importer_Base'; +import Folder from '../../models/Folder'; +import Note from '../../models/Note'; const { basename, filename, rtrimSlashes, fileExtension, dirname } = require('../../path-utils'); -const shim = require('../../shim').default; -const { extractImageUrls } = require('../../markdownUtils').default; +import shim from '../../shim'; +import markdownUtils from '../../markdownUtils'; const { unique } = require('../../ArrayUtils'); const { pregQuote } = require('../../string-utils-common'); const { MarkupToHtml } = require('@joplin/renderer'); @@ -65,7 +65,7 @@ export default class InteropService_Importer_Md extends InteropService_Importer_ */ async importLocalImages(filePath: string, md: string) { let updated = md; - const imageLinks = unique(extractImageUrls(md)); + const imageLinks = unique(markdownUtils.extractImageUrls(md)); await Promise.all(imageLinks.map(async (encodedLink: string) => { const link = decodeURI(encodedLink); const attachmentPath = filename(`${dirname(filePath)}/${link}`, true); diff --git a/packages/lib/services/interop/InteropService_Importer_Raw.ts b/packages/lib/services/interop/InteropService_Importer_Raw.ts index ee01294ff..7f1cd4390 100644 --- a/packages/lib/services/interop/InteropService_Importer_Raw.ts +++ b/packages/lib/services/interop/InteropService_Importer_Raw.ts @@ -1,17 +1,17 @@ import { ImportExportResult } from './types'; -const InteropService_Importer_Base = require('./InteropService_Importer_Base').default; -const BaseItem = require('../../models/BaseItem.js'); -const BaseModel = require('../../BaseModel').default; -const Resource = require('../../models/Resource.js'); -const Folder = require('../../models/Folder.js'); -const NoteTag = require('../../models/NoteTag.js'); -const Note = require('../../models/Note.js'); -const Tag = require('../../models/Tag.js'); +import InteropService_Importer_Base from './InteropService_Importer_Base'; +import BaseItem from '../../models/BaseItem'; +import BaseModel from '../../BaseModel'; +import Resource from '../../models/Resource'; +import Folder from '../../models/Folder'; +import NoteTag from '../../models/NoteTag'; +import Note from '../../models/Note'; +import Tag from '../../models/Tag'; const { sprintf } = require('sprintf-js'); -const shim = require('../../shim').default; +import shim from '../../shim'; const { fileExtension } = require('../../path-utils'); -const uuid = require('../../uuid').default; +import uuid from '../../uuid'; export default class InteropService_Importer_Raw extends InteropService_Importer_Base { async exec(result: ImportExportResult) { diff --git a/packages/lib/services/interop/types.ts b/packages/lib/services/interop/types.ts index b54bb765b..f2d4546d3 100644 --- a/packages/lib/services/interop/types.ts +++ b/packages/lib/services/interop/types.ts @@ -63,7 +63,7 @@ export interface Module { fullLabel?: Function; // Used only if `isCustom` is true - onExec?(context: any): Promise; + onExec?(context: any): Promise; // --------------------------------------- // Export-only properties diff --git a/packages/lib/services/keychain/KeychainService.ts b/packages/lib/services/keychain/KeychainService.ts index 4b21b1aa1..85911bdff 100644 --- a/packages/lib/services/keychain/KeychainService.ts +++ b/packages/lib/services/keychain/KeychainService.ts @@ -1,6 +1,6 @@ import KeychainServiceDriverBase from './KeychainServiceDriverBase'; -const Setting = require('../../models/Setting').default; -const BaseService = require('../BaseService').default; +import Setting from '../../models/Setting'; +import BaseService from '../BaseService'; export default class KeychainService extends BaseService { diff --git a/packages/lib/services/plugins/api/JoplinWorkspace.ts b/packages/lib/services/plugins/api/JoplinWorkspace.ts index e2ce89f4c..f2dbbaca4 100644 --- a/packages/lib/services/plugins/api/JoplinWorkspace.ts +++ b/packages/lib/services/plugins/api/JoplinWorkspace.ts @@ -8,12 +8,12 @@ import { Disposable } from './types'; /** * @ignore */ -const Note = require('../../../models/Note'); +import Note from '../../../models/Note'; /** * @ignore */ -const Folder = require('../../../models/Folder'); +import Folder from '../../../models/Folder'; enum ItemChangeEventType { Create = 1, diff --git a/packages/lib/services/rest/routes/folders.ts b/packages/lib/services/rest/routes/folders.ts index 99b28952f..889e1f4f5 100644 --- a/packages/lib/services/rest/routes/folders.ts +++ b/packages/lib/services/rest/routes/folders.ts @@ -4,7 +4,7 @@ import defaultAction from '../utils/defaultAction'; import paginatedResults from '../utils/paginatedResults'; import BaseModel from '../../../BaseModel'; import requestFields from '../utils/requestFields'; -const Folder = require('../../../models/Folder'); +import Folder from '../../../models/Folder'; const { FoldersScreenUtils } = require('../../../folders-screen-utils.js'); const { ErrorNotFound } = require('../utils/errors'); diff --git a/packages/lib/services/rest/routes/notes.ts b/packages/lib/services/rest/routes/notes.ts index 6a1c57089..9453a9115 100644 --- a/packages/lib/services/rest/routes/notes.ts +++ b/packages/lib/services/rest/routes/notes.ts @@ -12,12 +12,12 @@ import collectionToPaginatedResults from '../utils/collectionToPaginatedResults' const { reg } = require('../../../registry.js'); const { Database } = require('../../../database.js'); -const Folder = require('../../../models/Folder'); -const Note = require('../../../models/Note'); -const Tag = require('../../../models/Tag'); -const Resource = require('../../../models/Resource'); +import Folder from '../../../models/Folder'; +import Note from '../../../models/Note'; +import Tag from '../../../models/Tag'; +import Resource from '../../../models/Resource'; const htmlUtils = require('../../../htmlUtils'); -const markupLanguageUtils = require('../../../markupLanguageUtils').default; +import markupLanguageUtils from '../../../markupLanguageUtils'; const mimeUtils = require('../../../mime-utils.js').mime; const md5 = require('md5'); const HtmlToMd = require('../../../HtmlToMd'); diff --git a/packages/lib/services/rest/routes/resources.ts b/packages/lib/services/rest/routes/resources.ts index 0b00bb9d3..c70671853 100644 --- a/packages/lib/services/rest/routes/resources.ts +++ b/packages/lib/services/rest/routes/resources.ts @@ -8,8 +8,8 @@ import ApiResponse from '../ApiResponse'; import NoteResource from '../../../models/NoteResource'; import collectionToPaginatedResults from '../utils/collectionToPaginatedResults'; import defaultLoadOptions from '../utils/defaultLoadOptions'; -const Resource = require('../../../models/Resource'); -const Note = require('../../../models/Note'); +import Resource from '../../../models/Resource'; +import Note from '../../../models/Note'; export default async function(request: Request, id: string = null, link: string = null) { // fieldName: "data" diff --git a/packages/lib/services/rest/routes/search.ts b/packages/lib/services/rest/routes/search.ts index 3b81c7850..1b1427d81 100644 --- a/packages/lib/services/rest/routes/search.ts +++ b/packages/lib/services/rest/routes/search.ts @@ -4,8 +4,8 @@ import defaultLoadOptions from '../utils/defaultLoadOptions'; import { ErrorBadRequest, ErrorMethodNotAllowed } from '../utils/errors'; import requestFields from '../utils/requestFields'; import collectionToPaginatedResults from '../utils/collectionToPaginatedResults'; -const BaseItem = require('../../../models/BaseItem'); -const SearchEngineUtils = require('../../searchengine/SearchEngineUtils'); +import BaseItem from '../../../models/BaseItem'; +import SearchEngineUtils from '../../searchengine/SearchEngineUtils'; export default async function(request: Request) { if (request.method !== 'GET') throw new ErrorMethodNotAllowed(); diff --git a/packages/lib/services/rest/routes/tags.ts b/packages/lib/services/rest/routes/tags.ts index 6acddbd95..7ea1fb5e3 100644 --- a/packages/lib/services/rest/routes/tags.ts +++ b/packages/lib/services/rest/routes/tags.ts @@ -3,8 +3,8 @@ import BaseModel, { ModelType } from '../../../BaseModel'; import defaultLoadOptions from '../utils/defaultLoadOptions'; import { Request, RequestMethod } from '../Api'; import collectionToPaginatedResults from '../utils/collectionToPaginatedResults'; -const Note = require('../../../models/Note'); -const Tag = require('../../../models/Tag'); +import Note from '../../../models/Note'; +import Tag from '../../../models/Tag'; const { ErrorBadRequest, ErrorNotFound } = require('../utils/errors'); export default async function(request: Request, id: string = null, link: string = null) { diff --git a/packages/lib/services/rest/utils/defaultAction.ts b/packages/lib/services/rest/utils/defaultAction.ts index b17707e08..b364ab486 100644 --- a/packages/lib/services/rest/utils/defaultAction.ts +++ b/packages/lib/services/rest/utils/defaultAction.ts @@ -4,7 +4,7 @@ import { ErrorMethodNotAllowed, ErrorNotFound } from './errors'; import paginatedResults from './paginatedResults'; import readonlyProperties from './readonlyProperties'; import requestFields from './requestFields'; -const BaseItem = require('../../../models/BaseItem'); +import BaseItem from '../../../models/BaseItem'; export default async function(modelType: number, request: Request, id: string = null, link: string = null) { if (link) throw new ErrorNotFound(); // Default action doesn't support links at all for now diff --git a/packages/lib/services/rest/utils/paginatedResults.ts b/packages/lib/services/rest/utils/paginatedResults.ts index f3462ee94..a8f245208 100644 --- a/packages/lib/services/rest/utils/paginatedResults.ts +++ b/packages/lib/services/rest/utils/paginatedResults.ts @@ -3,7 +3,7 @@ import requestFields from './requestFields'; import BaseModel from '../../../BaseModel'; import requestPaginationOptions from './requestPaginationOptions'; import paginatedFeed, { WhereQuery, ModelFeedPage } from '../../../models/utils/paginatedFeed'; -const BaseItem = require('../../../models/BaseItem'); +import BaseItem from '../../../models/BaseItem'; export default async function(modelType: number, request: Request, whereQuery: WhereQuery = null): Promise { const ModelClass = BaseItem.getClassByItemType(modelType); diff --git a/packages/lib/services/rest/utils/requestFields.ts b/packages/lib/services/rest/utils/requestFields.ts index d8b27df7b..6b830f301 100644 --- a/packages/lib/services/rest/utils/requestFields.ts +++ b/packages/lib/services/rest/utils/requestFields.ts @@ -1,5 +1,5 @@ import { Request } from '../Api'; -const BaseItem = require('../../../models/BaseItem'); +import BaseItem from '../../../models/BaseItem'; function defaultFieldsByModelType(modelType: number): string[] { const ModelClass = BaseItem.getClassByItemType(modelType); diff --git a/packages/lib/services/searchengine/SearchEngine.js b/packages/lib/services/searchengine/SearchEngine.ts similarity index 86% rename from packages/lib/services/searchengine/SearchEngine.js rename to packages/lib/services/searchengine/SearchEngine.ts index 825aa6705..bc28c9c77 100644 --- a/packages/lib/services/searchengine/SearchEngine.js +++ b/packages/lib/services/searchengine/SearchEngine.ts @@ -1,24 +1,31 @@ -const Logger = require('../../Logger').default; -const ItemChange = require('../../models/ItemChange.js'); -const Setting = require('../../models/Setting').default; -const Note = require('../../models/Note.js'); -const BaseModel = require('../../BaseModel').default; -const ItemChangeUtils = require('../ItemChangeUtils'); -const { pregQuote, scriptType, removeDiacritics } = require('../../string-utils.js'); +import Logger from '../../Logger'; +import ItemChange from '../../models/ItemChange'; +import Setting from '../../models/Setting'; +import Note from '../../models/Note'; +import BaseModel from '../../BaseModel'; +import ItemChangeUtils from '../ItemChangeUtils'; +import shim from '../../shim'; +import filterParser from './filterParser'; +import queryBuilder from './queryBuilder'; +import { ItemChangeEntity, NoteEntity } from '../database/types'; const { sprintf } = require('sprintf-js'); -const filterParser = require('./filterParser').default; -const queryBuilder = require('./queryBuilder').default; -const shim = require('../../shim').default; +const { pregQuote, scriptType, removeDiacritics } = require('../../string-utils.js'); -class SearchEngine { +export default class SearchEngine { - constructor() { - this.dispatch = () => {}; - this.logger_ = new Logger(); - this.db_ = null; - this.isIndexing_ = false; - this.syncCalls_ = []; - } + public static instance_: SearchEngine = null; + public static relevantFields = 'id, title, body, user_created_time, user_updated_time, is_todo, todo_completed, parent_id, latitude, longitude, altitude, source_url'; + public static SEARCH_TYPE_AUTO = 'auto'; + public static SEARCH_TYPE_BASIC = 'basic'; + public static SEARCH_TYPE_FTS = 'fts'; + public static SEARCH_TYPE_FTS_FUZZY = 'fts_fuzzy'; + + public dispatch: Function = (_o: any) => {}; + private logger_ = new Logger(); + private db_: any = null; + private isIndexing_ = false; + private syncCalls_: any[] = []; + private scheduleSyncTablesIID_: any; static instance() { if (SearchEngine.instance_) return SearchEngine.instance_; @@ -26,7 +33,7 @@ class SearchEngine { return SearchEngine.instance_; } - setLogger(logger) { + setLogger(logger: Logger) { this.logger_ = logger; } @@ -34,7 +41,7 @@ class SearchEngine { return this.logger_; } - setDb(db) { + setDb(db: any) { this.db_ = db; } @@ -42,7 +49,7 @@ class SearchEngine { return this.db_; } - noteById_(notes, noteId) { + noteById_(notes: NoteEntity[], noteId: string) { for (let i = 0; i < notes.length; i++) { if (notes[i].id === noteId) return notes[i]; } @@ -55,8 +62,8 @@ class SearchEngine { } async rebuildIndex_() { - let noteIds = await this.db().selectAll('SELECT id FROM notes WHERE is_conflict = 0 AND encryption_applied = 0'); - noteIds = noteIds.map(n => n.id); + let noteIds: string[] = await this.db().selectAll('SELECT id FROM notes WHERE is_conflict = 0 AND encryption_applied = 0'); + noteIds = noteIds.map((n: any) => n.id); const lastChangeId = await ItemChange.lastChangeId(); @@ -138,7 +145,7 @@ class SearchEngine { try { while (true) { - const changes = await ItemChange.modelSelectAll( + const changes: ItemChangeEntity[] = await ItemChange.modelSelectAll( ` SELECT id, item_id, type FROM item_changes @@ -221,10 +228,10 @@ class SearchEngine { return row && row['total'] ? row['total'] : 0; } - fieldNamesFromOffsets_(offsets) { + fieldNamesFromOffsets_(offsets: any[]) { const notesNormalizedFieldNames = this.db().tableFieldNames('notes_normalized'); const occurenceCount = Math.floor(offsets.length / 4); - const output = []; + const output: string[] = []; for (let i = 0; i < occurenceCount; i++) { const colIndex = offsets[i * 4]; const fieldName = notesNormalizedFieldNames[colIndex]; @@ -234,7 +241,7 @@ class SearchEngine { return output; } - calculateWeight_(offsets, termCount) { + calculateWeight_(offsets: any[], termCount: number) { // Offset doc: https://www.sqlite.org/fts3.html#offsets // - If there's only one term in the query string, the content with the most matches goes on top @@ -266,7 +273,7 @@ class SearchEngine { - calculateWeightBM25_(rows, fuzzyScore) { + calculateWeightBM25_(rows: any[], fuzzyScore: any) { // https://www.sqlite.org/fts3.html#matchinfo // pcnalx are the arguments passed to matchinfo // p - The number of matchable phrases in the query. @@ -308,19 +315,19 @@ class SearchEngine { const X = matchInfo.map(m => m.slice(27)); // x - const hitsThisRow = (array, c, p) => array[3 * (c + p * numColumns) + 0]; + const hitsThisRow = (array: any, c: number, p: number) => array[3 * (c + p * numColumns) + 0]; // const hitsAllRows = (array, c, p) => array[3 * (c + p*NUM_COLS) + 1]; - const docsWithHits = (array, c, p) => array[3 * (c + p * numColumns) + 2]; + const docsWithHits = (array: any, c: number, p: number) => array[3 * (c + p * numColumns) + 2]; // if a term occurs in over half the documents in the collection // then this model gives a negative term weight, which is presumably undesirable. // But, assuming the use of a stop list, this normally doesn't happen, // and the value for each summand can be given a floor of 0. - const IDF = (n, N) => Math.max(Math.log((N - n + 0.5) / (n + 0.5)), 0); + const IDF = (n: number, N: number) => Math.max(Math.log((N - n + 0.5) / (n + 0.5)), 0); // https://en.wikipedia.org/wiki/Okapi_BM25 - const BM25 = (idf, freq, numTokens, avgTokens) => { + const BM25 = (idf: any, freq: any, numTokens: number, avgTokens: any) => { if (avgTokens === 0) { return 0; // To prevent division by zero } @@ -329,7 +336,7 @@ class SearchEngine { const msSinceEpoch = Math.round(new Date().getTime()); const msPerDay = 86400000; - const weightForDaysSinceLastUpdate = (row) => { + const weightForDaysSinceLastUpdate = (row: any) => { // BM25 weights typically range 0-10, and last updated date should weight similarly, though prioritizing recency logarithmically. // An alpha of 200 ensures matches in the last week will show up front (11.59) and often so for matches within 2 weeks (5.99), // but is much less of a factor at 30 days (2.84) or very little after 90 days (0.95), focusing mostly on content at that point. @@ -365,32 +372,32 @@ class SearchEngine { } } - processBasicSearchResults_(rows, parsedQuery) { - const valueRegexs = parsedQuery.keys.includes('_') ? parsedQuery.terms['_'].map(term => term.valueRegex || term.value) : []; + processBasicSearchResults_(rows: any[], parsedQuery: any) { + const valueRegexs = parsedQuery.keys.includes('_') ? parsedQuery.terms['_'].map((term: any) => term.valueRegex || term.value) : []; const isTitleSearch = parsedQuery.keys.includes('title'); const isOnlyTitle = parsedQuery.keys.length === 1 && isTitleSearch; for (let i = 0; i < rows.length; i++) { const row = rows[i]; - const testTitle = regex => new RegExp(regex, 'ig').test(row.title); - const matchedFields = { + const testTitle = (regex: any) => new RegExp(regex, 'ig').test(row.title); + const matchedFields: any = { title: isTitleSearch || valueRegexs.some(testTitle), body: !isOnlyTitle, }; - row.fields = Object.keys(matchedFields).filter(key => matchedFields[key]); + row.fields = Object.keys(matchedFields).filter((key: any) => matchedFields[key]); row.weight = 0; row.fuzziness = 0; } } - processResults_(rows, parsedQuery, isBasicSearchResults = false) { - const rowContainsAllWords = (wordsFound, numFuzzyMatches) => { + processResults_(rows: any[], parsedQuery: any, isBasicSearchResults = false) { + const rowContainsAllWords = (wordsFound: any, numFuzzyMatches: any) => { let start = 0; let end = 0; for (let i = 0; i < numFuzzyMatches.length; i++) { end = end + numFuzzyMatches[i]; - if (!(wordsFound.slice(start, end).find(x => x))) { + if (!(wordsFound.slice(start, end).find((x: any) => x))) { // This note doesn't contain any fuzzy matches for the word return false; } @@ -406,7 +413,7 @@ class SearchEngine { for (let i = 0; i < rows.length; i++) { const row = rows[i]; row.include = (parsedQuery.fuzzy && !parsedQuery.any) ? rowContainsAllWords(row.wordFound, parsedQuery.numFuzzyMatches) : true; - const offsets = row.offsets.split(' ').map(o => Number(o)); + const offsets = row.offsets.split(' ').map((o: any) => Number(o)); row.fields = this.fieldNamesFromOffsets_(offsets); } } @@ -427,7 +434,7 @@ class SearchEngine { } // https://stackoverflow.com/a/13818704/561309 - queryTermToRegex(term) { + queryTermToRegex(term: any) { while (term.length && term.indexOf('*') === 0) { term = term.substr(1); } @@ -441,8 +448,8 @@ class SearchEngine { return regexString; } - async fuzzifier(words) { - const fuzzyMatches = []; + async fuzzifier(words: string[]) { + const fuzzyMatches: any[] = []; words.forEach(word => { const fuzzyWords = this.db().selectAll('SELECT word, score FROM notes_spellfix WHERE word MATCH ? AND top=3', [word]); fuzzyMatches.push(fuzzyWords); @@ -450,12 +457,12 @@ class SearchEngine { return await Promise.all(fuzzyMatches); } - async parseQuery(query, fuzzy = null) { + async parseQuery(query: string, fuzzy: any = null) { if (fuzzy === null) fuzzy = Setting.value('db.fuzzySearchEnabled') === 1; - const trimQuotes = (str) => str.startsWith('"') ? str.substr(1, str.length - 2) : str; + const trimQuotes = (str: string) => str.startsWith('"') ? str.substr(1, str.length - 2) : str; - let allTerms = []; + let allTerms: any[] = []; let allFuzzyTerms = []; try { @@ -470,7 +477,7 @@ class SearchEngine { const fuzzyScore = []; let numFuzzyMatches = []; - let terms = null; + let terms: any = null; if (fuzzy) { const fuzzyText = await this.fuzzifier(textTerms.filter(x => !(x.quoted || x.wildcard)).map(x => trimQuotes(x.value))); @@ -478,7 +485,7 @@ class SearchEngine { const fuzzyBody = await this.fuzzifier(bodyTerms.filter(x => !x.wildcard).map(x => trimQuotes(x.value))); // Floor the fuzzy scores to 0, 1 and 2. - const floorFuzzyScore = (matches) => { + const floorFuzzyScore = (matches: any) => { for (let i = 0; i < matches.length; i++) matches[i].score = i; }; @@ -604,10 +611,10 @@ class SearchEngine { }; } - allParsedQueryTerms(parsedQuery) { + allParsedQueryTerms(parsedQuery: any) { if (!parsedQuery || !parsedQuery.termCount) return []; - let output = []; + let output: any[] = []; for (const col in parsedQuery.terms) { if (!parsedQuery.terms.hasOwnProperty(col)) continue; output = output.concat(parsedQuery.terms[col]); @@ -615,27 +622,27 @@ class SearchEngine { return output; } - normalizeText_(text) { + normalizeText_(text: string) { const normalizedText = text.normalize ? text.normalize() : text; return removeDiacritics(normalizedText.toLowerCase()); } - normalizeNote_(note) { + normalizeNote_(note: NoteEntity) { const n = Object.assign({}, note); n.title = this.normalizeText_(n.title); n.body = this.normalizeText_(n.body); return n; } - async basicSearch(query) { + async basicSearch(query: string) { query = query.replace(/\*/, ''); const parsedQuery = await this.parseQuery(query); - const searchOptions = {}; + const searchOptions: any = {}; for (const key of parsedQuery.keys) { if (parsedQuery.terms[key].length === 0) continue; - const term = parsedQuery.terms[key].map(x => x.value).join(' '); + const term = parsedQuery.terms[key].map((x: any) => x.value).join(' '); if (key === '_') searchOptions.anywherePattern = `*${term}*`; if (key === 'title') searchOptions.titlePattern = `*${term}*`; if (key === 'body') searchOptions.bodyPattern = `*${term}*`; @@ -644,13 +651,13 @@ class SearchEngine { return Note.previews(null, searchOptions); } - determineSearchType_(query, options) { + determineSearchType_(query: string, options: any) { if (options.searchType === SearchEngine.SEARCH_TYPE_BASIC) return SearchEngine.SEARCH_TYPE_BASIC; // If preferredSearchType is "fts" we auto-detect anyway // because it's not always supported. - let allTerms = []; + let allTerms: any[] = []; try { allTerms = filterParser(query); } catch (error) { @@ -670,7 +677,7 @@ class SearchEngine { } - async search(searchString, options = null) { + async search(searchString: string, options: any = null) { if (!searchString) return []; options = Object.assign({}, { @@ -702,7 +709,7 @@ class SearchEngine { const rows = await this.db().selectAll(query, params); this.processResults_(rows, parsedQuery); if (searchType === SearchEngine.SEARCH_TYPE_FTS_FUZZY && !parsedQuery.any) { - return rows.filter(row => row.include); + return rows.filter((row: any) => row.include); } return rows; } catch (error) { @@ -723,21 +730,10 @@ class SearchEngine { const iid = shim.setInterval(() => { if (!this.syncCalls_.length) { shim.clearInterval(iid); - this.instance_ = null; - resolve(); + SearchEngine.instance_ = null; + resolve(null); } }, 100); }); } } - -SearchEngine.relevantFields = 'id, title, body, user_created_time, user_updated_time, is_todo, todo_completed, parent_id, latitude, longitude, altitude, source_url'; - -SearchEngine.instance_ = null; - -SearchEngine.SEARCH_TYPE_AUTO = 'auto'; -SearchEngine.SEARCH_TYPE_BASIC = 'basic'; -SearchEngine.SEARCH_TYPE_FTS = 'fts'; -SearchEngine.SEARCH_TYPE_FTS_FUZZY = 'fts_fuzzy'; - -module.exports = SearchEngine; diff --git a/packages/lib/services/searchengine/SearchEngineUtils.js b/packages/lib/services/searchengine/SearchEngineUtils.ts similarity index 87% rename from packages/lib/services/searchengine/SearchEngineUtils.js rename to packages/lib/services/searchengine/SearchEngineUtils.ts index 6fe435fcb..494f851da 100644 --- a/packages/lib/services/searchengine/SearchEngineUtils.js +++ b/packages/lib/services/searchengine/SearchEngineUtils.ts @@ -1,8 +1,8 @@ -const SearchEngine = require('./SearchEngine'); -const Note = require('../../models/Note'); +import SearchEngine from './SearchEngine'; +import Note from '../../models/Note'; -class SearchEngineUtils { - static async notesForQuery(query, options = null) { +export default class SearchEngineUtils { + static async notesForQuery(query: string, options: any = null) { if (!options) options = {}; let searchType = SearchEngine.SEARCH_TYPE_FTS; @@ -12,7 +12,7 @@ class SearchEngineUtils { } const results = await SearchEngine.instance().search(query, { searchType }); - const noteIds = results.map(n => n.id); + const noteIds = results.map((n: any) => n.id); // We need at least the note ID to be able to sort them below so if not // present in field list, add it.L Also remember it was auto-added so that @@ -56,5 +56,3 @@ class SearchEngineUtils { } } - -module.exports = SearchEngineUtils; diff --git a/packages/lib/services/searchengine/queryBuilder.ts b/packages/lib/services/searchengine/queryBuilder.ts index 643f8a2db..974a32dbb 100644 --- a/packages/lib/services/searchengine/queryBuilder.ts +++ b/packages/lib/services/searchengine/queryBuilder.ts @@ -1,4 +1,4 @@ -const time = require('../../time').default; +import time from '../../time'; interface Term { name: string; diff --git a/packages/lib/services/synchronizer/LockHandler.ts b/packages/lib/services/synchronizer/LockHandler.ts index bf3ba008f..06bca5770 100644 --- a/packages/lib/services/synchronizer/LockHandler.ts +++ b/packages/lib/services/synchronizer/LockHandler.ts @@ -2,7 +2,7 @@ import { Dirnames } from './utils/types'; import shim from '../../shim'; const JoplinError = require('../../JoplinError'); -const time = require('../../time').default; +import time from '../../time'; const { fileExtension, filename } = require('../../path-utils'); export enum LockType { diff --git a/packages/lib/services/synchronizer/MigrationHandler.ts b/packages/lib/services/synchronizer/MigrationHandler.ts index 6960532cc..270f76b7d 100644 --- a/packages/lib/services/synchronizer/MigrationHandler.ts +++ b/packages/lib/services/synchronizer/MigrationHandler.ts @@ -1,6 +1,6 @@ import LockHandler, { LockType } from './LockHandler'; import { Dirnames } from './utils/types'; -const BaseService = require('../BaseService').default; +import BaseService from '../BaseService'; // To add a new migration: // - Add the migration logic in ./migrations/VERSION_NUM.js @@ -13,7 +13,7 @@ const migrations = [ require('./migrations/2.js').default, ]; -const Setting = require('../../models/Setting').default; +import Setting from '../../models/Setting'; const { sprintf } = require('sprintf-js'); const JoplinError = require('../../JoplinError'); diff --git a/packages/lib/services/synchronizer/gui/useSyncTargetUpgrade.ts b/packages/lib/services/synchronizer/gui/useSyncTargetUpgrade.ts index 9d840235f..ffd678034 100644 --- a/packages/lib/services/synchronizer/gui/useSyncTargetUpgrade.ts +++ b/packages/lib/services/synchronizer/gui/useSyncTargetUpgrade.ts @@ -1,7 +1,7 @@ import shim from '../../../shim'; import MigrationHandler from '../MigrationHandler'; const { useEffect, useState } = shim.react(); -const Setting = require('../../../models/Setting').default; +import Setting from '../../../models/Setting'; const { reg } = require('../../../registry'); export interface SyncTargetUpgradeResult { diff --git a/packages/lib/shim-init-node.js b/packages/lib/shim-init-node.js index 2632d61ae..84cf9fe15 100644 --- a/packages/lib/shim-init-node.js +++ b/packages/lib/shim-init-node.js @@ -5,8 +5,8 @@ const { FileApiDriverLocal } = require('./file-api-driver-local.js'); const { setLocale, defaultLocale, closestSupportedLocale } = require('./locale'); const FsDriverNode = require('./fs-driver-node').default; const mimeUtils = require('./mime-utils.js').mime; -const Note = require('./models/Note.js'); -const Resource = require('./models/Resource.js'); +const Note = require('./models/Note').default; +const Resource = require('./models/Resource').default; const urlValidator = require('valid-url'); const { _ } = require('./locale'); const http = require('http'); diff --git a/packages/lib/shim.ts b/packages/lib/shim.ts index b8ca1e3b8..b5ae64793 100644 --- a/packages/lib/shim.ts +++ b/packages/lib/shim.ts @@ -19,6 +19,8 @@ let isTestingEnv_ = false; let react_: any = null; const shim = { + Geolocation: null as any, + isNode: () => { if (typeof process === 'undefined') return false; if (shim.isElectron()) return true; @@ -138,7 +140,7 @@ const shim = { }, fetchWithRetry: async function(fetchFn: Function, options: any = null) { - const time = require('./time').default; + const time = require('./time'); if (!options) options = {}; if (!options.timeout) options.timeout = 1000 * 120; // ms diff --git a/packages/lib/versionInfo.ts b/packages/lib/versionInfo.ts index 9a93c21cd..45362750d 100644 --- a/packages/lib/versionInfo.ts +++ b/packages/lib/versionInfo.ts @@ -1,5 +1,5 @@ import { _ } from './locale'; -const Setting = require('./models/Setting').default; +import Setting from './models/Setting'; const { reg } = require('./registry.js'); export default function versionInfo(packageInfo: any) { diff --git a/packages/renderer/HtmlToHtml.ts b/packages/renderer/HtmlToHtml.ts index 02b73cb98..b91cb7d5c 100644 --- a/packages/renderer/HtmlToHtml.ts +++ b/packages/renderer/HtmlToHtml.ts @@ -3,9 +3,9 @@ import linkReplacement from './MdToHtml/linkReplacement'; import utils from './utils'; // TODO: fix -// const Setting = require('@joplin/lib/models/Setting').default; +// import Setting from '@joplin/lib/models/Setting'; // const { themeStyle } = require('@joplin/lib/theme'); -const InMemoryCache = require('./InMemoryCache').default; +import InMemoryCache from './InMemoryCache'; const md5 = require('md5'); // Renderered notes can potentially be quite large (for example