From 97c9b265db16bfe410710ad18ca28a88cd377873 Mon Sep 17 00:00:00 2001 From: hesprs <190185753+hesprs@users.noreply.github.com> Date: Fri, 13 Nov 2026 20:16:58 +0800 Subject: [PATCH 1/3] fix(various): fix plugin and gdrive bugs, implement webdav digest auth --- .github/ISSUE_TEMPLATE/bug-report.yml | 4 +- bun.lock | 2 + docs/src/pages/en/deep-dive/extensibility.md | 6 +- .../en/deep-dive/module-management-page.md | 10 +- docs/src/pages/en/deep-dive/modules/webdav.md | 6 +- .../pages/en/development/develop-a-module.md | 5 +- docs/src/pages/en/development/distribution.md | 4 +- docs/src/pages/en/development/events.md | 2 +- docs/src/pages/en/usage/permissions.md | 2 +- docs/src/pages/en/usage/settings.md | 11 +- modules.json | 24 +- packages/dropbox/tsdown.config.ts | 1 + packages/encryption/src/wrapper/path.ts | 5 +- packages/encryption/tsdown.config.ts | 3 +- packages/gdrive/src/gdrive/fs.ts | 16 +- packages/gdrive/test/fs-gdrive.test.ts | 63 +++- packages/gdrive/tsdown.config.ts | 1 + packages/i18n/src/ru/translations.ts | 5 +- packages/i18n/src/zh-TW/translations.ts | 4 +- packages/i18n/src/zh/translations.ts | 4 +- packages/i18n/tsdown.config.ts | 1 + packages/plugin/dist/dev.spec.d.ts | 2 +- ...XqQ.spec.d.ts => index-CgW2TrzR.spec.d.ts} | 24 +- packages/plugin/dist/index.spec.d.ts | 2 +- .../src/components/module-management/App.tsx | 268 +++++++++++------ .../src/components/module-management/Card.tsx | 49 ++-- .../src/components/module-management/index.ts | 25 +- packages/plugin/src/en.ts | 5 +- packages/plugin/src/modules/EventBus.ts | 4 +- packages/plugin/src/modules/Extensibility.ts | 39 ++- packages/plugin/src/modules/I18n.ts | 7 +- packages/plugin/src/settings/head.ts | 3 +- .../plugin/src/settings/module-management.ts | 157 +--------- packages/rclone-s3-timestamp/tsdown.config.ts | 1 + packages/s3/tsdown.config.ts | 3 +- packages/smart-merge/tsdown.config.ts | 1 + packages/webdav/package.json | 4 +- packages/webdav/src/index.ts | 15 +- packages/webdav/src/webdav/auth.ts | 146 ++++++++- packages/webdav/test/auth.test.ts | 276 ++++++++++++++++++ packages/webdav/tsdown.config.ts | 2 + 41 files changed, 855 insertions(+), 357 deletions(-) rename packages/plugin/dist/{index-r0HV0XqQ.spec.d.ts => index-CgW2TrzR.spec.d.ts} (99%) create mode 100644 packages/webdav/test/auth.test.ts diff --git a/.github/ISSUE_TEMPLATE/bug-report.yml b/.github/ISSUE_TEMPLATE/bug-report.yml index ea612d0b..fa0ee69f 100644 --- a/.github/ISSUE_TEMPLATE/bug-report.yml +++ b/.github/ISSUE_TEMPLATE/bug-report.yml @@ -47,7 +47,7 @@ body: label: Logs description: Please go to plugin settings - `Development` - `Export logs`, click `Export`, copy and paste the content of the full log. This will be automatically formatted into code, so no need for backticks. render: shell - placeholder: If the log contains information that you think is improper to disclose, it's OK to only paste sections with `ERROR` labels. + placeholder: If the log contains information that is improper to disclose, it's OK to only paste "General logs" and sections with "ERROR" labels. - type: checkboxes id: terms @@ -61,7 +61,7 @@ body: - type: markdown attributes: value: | - - I have updated Sync Engine to the latest version but the bug persists. + - I have updated Sync Engine and its modules to latest versions but the bug persists. The latest version of Sync Engine can be found in the [GitHub releases page](https://github.com/hesprs/sync-engine/releases/latest) and modules versions are in [the module catalog in the documentation website](https://sync.consensia.cc/usage/modules). - I have provided clear and reproducible information about the bug. - I have ensured that this issue only contains one bug. - I have checked historical bugs and there's no entry fitting this scenario. diff --git a/bun.lock b/bun.lock index fd513d25..60d456ae 100644 --- a/bun.lock +++ b/bun.lock @@ -123,6 +123,8 @@ "devDependencies": { "@hesprs/sync-engine-sdk": "workspace:*", "@repo/shared": "workspace:*", + "hash-wasm": "catalog:", + "uni-kv": "catalog:", }, }, }, diff --git a/docs/src/pages/en/deep-dive/extensibility.md b/docs/src/pages/en/deep-dive/extensibility.md index 241c15e6..198fcc65 100644 --- a/docs/src/pages/en/deep-dive/extensibility.md +++ b/docs/src/pages/en/deep-dive/extensibility.md @@ -108,7 +108,11 @@ New modules are disabled by default. The downloaded text is integrity-checked be ### Install From File -The module management menu also offers **Install module from file**. The user picks a `.js` file (other extensions are rejected with a notice), and the module editor opens with metadata prefilled from the file's magic bytes, a leading `/*! ... */` comment of `key: value` lines embedded at build time. On save, `installModule()` writes the file to the module directory, stores the confirmed metadata, and loads the module when it is enabled. No source is involved in this path. +The module management menu also offers **Install module from file**. The user picks a `.js` or `.mjs` file (other extensions are rejected with a notice), and the module editor opens with metadata prefilled from the file's magic bytes, a leading `/*! ... */` comment of `key: value` lines embedded at build time. On save, `installModule()` writes the file to the module directory, stores the confirmed metadata, and loads the module when it is enabled. No source is involved in this path. + +### Install From Code + +The module management menu also offers **Install module from code**. The user pastes module code into a code input modal, and the module editor opens with metadata prefilled from the code's magic bytes. On save, `installModule()` writes the code to the module directory, stores the confirmed metadata, and loads the module when it is enabled. No source is involved in this path. ### Automatic Update diff --git a/docs/src/pages/en/deep-dive/module-management-page.md b/docs/src/pages/en/deep-dive/module-management-page.md index 14c7e09e..70af2995 100644 --- a/docs/src/pages/en/deep-dive/module-management-page.md +++ b/docs/src/pages/en/deep-dive/module-management-page.md @@ -7,14 +7,14 @@ Sync Engine uses a native Obsidian settings page to manage executable modules fr `ModuleManagement` extends Obsidian's `SettingPage`. Its page contains: - a full-width search field; -- an icon button that opens a menu with the **Show installed only** toggle and **Install module from file**; -- a Solid.js module-card list. +- an icon button that opens a menu with the **Show installed only** toggle, **Install module from file**, **Install module from code**, and **Refresh sources**; +- a Solid.js module-card grid. Module source URLs are edited separately on **Settings > Sync Engine > Development > Module sources**. Returning to Module management creates a new source snapshot and refreshes the catalog. -The search field uses Obsidian's `SearchComponent`. An empty query sorts modules alphabetically. A non-empty query uses `prepareFuzzySearch()` against module names and descriptions, then sorts by match score and name. +The search field uses Obsidian's `SearchComponent`. An empty query sorts modules alphabetically by module ID. A non-empty query uses `prepareFuzzySearch()` against module names and descriptions, then sorts by match score and module ID. -**Install module from file** opens a file picker that only accepts `.js` files; other extensions are rejected with a notice. The chosen file opens the module editor with metadata prefilled from the file's magic bytes, see [extensibility: install from file](./extensibility#install-from-file). +**Install module from file** opens a file picker that accepts `.js` and `.mjs` files; other extensions are rejected with a notice. The chosen file opens the module editor with metadata prefilled from the file's magic bytes, see [extensibility: install from file](./extensibility#install-from-file). **Install module from code** opens a code input modal where the user pastes module code, then follows the same editor flow. ## Module Cards @@ -31,7 +31,7 @@ Actions are disabled while another action for the same module is running. Runnin ## Source And Compatibility State -`fetchSources()` reads every configured source. Source responses are cached for automatic update checks and can be forced to refresh for manual operations. Duplicate IDs within a source are ignored. +`fetchSources()` reads every configured source. Source responses are cached for automatic update checks. The **Refresh sources** menu item forces a refresh and shows a notice with the number of discovered modules and sources. Duplicate IDs within a source are ignored. If a source entry declares a `minPluginVersion` newer than the running plugin, the catalog marks the plugin as outdated. Update Sync Engine before installing modules that require the newer version. diff --git a/docs/src/pages/en/deep-dive/modules/webdav.md b/docs/src/pages/en/deep-dive/modules/webdav.md index d176b817..e22babd7 100644 --- a/docs/src/pages/en/deep-dive/modules/webdav.md +++ b/docs/src/pages/en/deep-dive/modules/webdav.md @@ -4,7 +4,7 @@ The WebDAV module registers the `webdav` remote file system. It implements the [ ## Supported Backends -The standard mode can theoretically work with any WebDAV service that supports HTTP(S), Basic authentication, ranged `GET`, `PROPFIND`, `PUT`, `DELETE`, `MOVE`, and `MKCOL`. This includes WebDAV installations based on: +The standard mode can theoretically work with any WebDAV service that supports HTTP(S), Basic or Digest (MD5) authentication, ranged `GET`, `PROPFIND`, `PUT`, `DELETE`, `MOVE`, and `MKCOL`. This includes WebDAV installations based on: - Nextcloud - ownCloud @@ -20,6 +20,10 @@ The standard mode can theoretically work with any WebDAV service that supports H The optional chunked-upload mode requires Nextcloud's upload protocol and is not standard WebDAV. Enable it only for compatible Nextcloud servers. +## Authentication + +The module sends Basic credentials first. When the server answers with `401` and a Digest challenge, it switches to Digest (MD5 with `qop=auth`, or the legacy scheme without `qop`) and caches the challenge state in the in-memory database, keyed by endpoint, username, and password. Challenges naming other algorithms are declined, and the module keeps sending Basic credentials. + ## Settings The module registers these settings: diff --git a/docs/src/pages/en/development/develop-a-module.md b/docs/src/pages/en/development/develop-a-module.md index 08970419..9fd5584e 100644 --- a/docs/src/pages/en/development/develop-a-module.md +++ b/docs/src/pages/en/development/develop-a-module.md @@ -55,11 +55,12 @@ export default defineConfig({ minify: true, outExtensions: () => ({ js: '.js' }), outputOptions: { codeSplitting: false }, + platform: 'browser', plugins: [syncEngineModule()], }); ``` -This config makes Tsdown output a single minified JavaScript file, which can be directly loaded by Sync Engine core. The `syncEngineModule` plugin bridges Obsidian API imports and can embed module metadata as magic bytes, see [Tsdown Plugin](#tsdown-plugin). +This config makes Tsdown output a single minified JavaScript file, which can be directly loaded by Sync Engine core. The `syncEngineModule` plugin bridges Obsidian API imports and can embed module metadata as magic bytes, see [Tsdown Plugin](#tsdown-plugin). `platform: 'browser'` targets the browser runtime that loads modules inside Obsidian's renderer. Finally add following commands to your `package.json`: @@ -163,7 +164,7 @@ You can found abundant module examples in Sync Engine monorepo: - [Encryption](https://github.com/hesprs/sync-engine/tree/main/packages/encryption): uses settings, i18n, file system, and in-memory database API. - [Smart Merge](https://github.com/hesprs/sync-engine/tree/main/packages/smart-merge): uses settings, i18n, file system, IndexedDB, and conflict resolution API. -- [WebDAV](ttps://github.com/hesprs/sync-engine/tree/main/packages/webdav): great example of how to add a backend to Sync Engine. +- [WebDAV](https://github.com/hesprs/sync-engine/tree/main/packages/webdav): great example of how to add a backend to Sync Engine. ## Build A Feedback Loop diff --git a/docs/src/pages/en/development/distribution.md b/docs/src/pages/en/development/distribution.md index 41b29bb7..79481c6b 100644 --- a/docs/src/pages/en/development/distribution.md +++ b/docs/src/pages/en/development/distribution.md @@ -72,12 +72,14 @@ Version and metadata are persisted in IndexedDB (`AugmentedModuleMeta`). For det When `Auto update modules` is enabled, on plugin load the plugin: -1. Waits 200 milliseconds. +1. Waits 500 milliseconds. 2. Fetches all configured source URLs. 3. For each installed module, compares the remote version with the local version. 4. If the remote version is newer, queues a download. 5. Waits for the sync engine to be idle, then downloads and replaces the module file. +The update check is skipped while the device reports being offline. + Only already-installed modules are auto-updated. New modules must be manually installed via the Module Management UI. ## Publishing a Module diff --git a/docs/src/pages/en/development/events.md b/docs/src/pages/en/development/events.md index c831cf4e..b3d8e21a 100644 --- a/docs/src/pages/en/development/events.md +++ b/docs/src/pages/en/development/events.md @@ -45,7 +45,7 @@ unsubscribe(); | `logGeneral` | `string` general log message | | `errorSync` | `Error` sync error | | `errorGeneral` | `Error` general error | -| `moduleLoaded` | `string` module name | +| `moduleLoaded` | `AugmentedModuleMeta` module metadata | | `moduleUnloaded` | `string` module name | | `syncStarted` | `{ isCancelled: Ref; trigger: string }` | | `syncInitialized` | `Infras & { match: (path: string) => GlobMatchResult }`: the run's file systems, record store, and compiled matcher | diff --git a/docs/src/pages/en/usage/permissions.md b/docs/src/pages/en/usage/permissions.md index 9aafbf4f..7d89e1fb 100644 --- a/docs/src/pages/en/usage/permissions.md +++ b/docs/src/pages/en/usage/permissions.md @@ -40,7 +40,7 @@ Sync Engine plugin and `sync.consensia.cc` don't contain any type of telemetry. Obsidian secret storage is shown as "Keychain" in Obsidian settings. Sync Engine and official modules acquire secrets in following scenarios: - Plugin core: reads the configured [secret headers](./settings#custom-headers) at the start of a sync run -- [WebDAV](../deep-dive/modules/webdav) module: reads the configured WebDAV token secret at the start of a sync run for service authentication +- [WebDAV](../deep-dive/modules/webdav) module: reads the configured WebDAV password secret at the start of a sync run for service authentication - [S3](../deep-dive/modules/s3) module: reads the configured secret access key when resolving S3 credentials for connection checks or sync operations - [Google Drive](../deep-dive/modules/gdrive) module: manages a secret named `sync-engine-gdrive-refresh-token` automatically and uses that for authorizing connection checks and sync operations. - [Dropbox](../deep-dive/modules/dropbox) module: manages a secret named `sync-engine-dropbox-refresh-token` automatically and uses that for authorizing connection checks and sync operations. diff --git a/docs/src/pages/en/usage/settings.md b/docs/src/pages/en/usage/settings.md index 01068443..62397da3 100644 --- a/docs/src/pages/en/usage/settings.md +++ b/docs/src/pages/en/usage/settings.md @@ -12,9 +12,9 @@ Choose the installed module that connects Sync Engine to your storage service. T ### Module Management -Open the module management page. From there, you can install modules from sources or local files, and update, enable, disable, remove, or edit modules. Modules provide storage backends and extra sync strategies. Review [Security](./security) before installing modules from sources you do not control. +Open the module management page. From there, you can install modules from sources, local files, or pasted code, and update, enable, disable, remove, or edit modules. Modules provide storage backends and extra sync strategies. Review [Security](./security) before installing modules from sources you do not control. -The [module management page](../deep-dive/module-management-page) contains a search bar, an installed-only filter, an install-from-file entry, and module cards. Module source URLs are edited in the **Module sources** page under Development. +The [module management page](../deep-dive/module-management-page) contains a search bar, an installed-only filter, install-from-file and install-from-code entries, a refresh-sources entry, and module cards. Module source URLs are edited in the **Module sources** page under Development. ### Auto-Update Modules @@ -163,9 +163,10 @@ Rules use [`glob` expressions](/Sync Engine Logs/` folder. U Edit the URLs Sync Engine uses to obtain the module catalog. URLs must use `http:` or `https:` and invalid entries are marked until corrected; use HTTPS whenever possible. -The default source is `https://sync.consensia.cc/modules.json`. An alternative GitHub-hosted source `https://raw.githubusercontent.com/hesprs/sync-engine/refs/heads/gh-pages/modules-alternative.json` is available for networks that cannot reach the default source. Use one official source at a time to avoid duplicate module entries. +The default source is `https://sync.consensia.cc/modules.json`. An alternative GitHub-hosted source `https://raw.githubusercontent.com/hesprs/sync-engine/refs/heads/gh-pages/modules-alternative.json` is available for networks that cannot reach the default source. Use one official source at a time to avoid duplicating module entries. diff --git a/modules.json b/modules.json index b623cb34..b242bfc5 100644 --- a/modules.json +++ b/modules.json @@ -2,31 +2,31 @@ { "id": "webdav", "name": "WebDAV", - "version": "1.0.0", + "version": "1.1.0", "description": "WebDAV backend support.", "icon": "server", "main": "https://sync.consensia.cc/modules/webdav.js", - "minPluginVersion": "3.4.0", + "minPluginVersion": "3.4.2", "readme": "https://sync.consensia.cc/deep-dive/modules/webdav" }, { "id": "s3", "name": "S3", - "version": "1.0.0", + "version": "1.0.1", "description": "S3 and S3-compatible backend support.", "icon": "server", "main": "https://sync.consensia.cc/modules/s3.js", - "minPluginVersion": "3.4.0", + "minPluginVersion": "3.4.2", "readme": "https://sync.consensia.cc/deep-dive/modules/s3" }, { "id": "gdrive", "name": "Google Drive", - "version": "1.0.1", + "version": "1.0.2", "description": "Google Drive backend support.", "icon": "server", "main": "https://sync.consensia.cc/modules/gdrive.js", - "minPluginVersion": "3.4.0", + "minPluginVersion": "3.4.2", "readme": "https://sync.consensia.cc/deep-dive/modules/gdrive" }, { @@ -42,7 +42,7 @@ { "id": "encryption", "name": "Encryption", - "version": "1.0.0", + "version": "1.0.1", "description": "Client-side encrypt vault files before uploading to backend.", "icon": "key-round", "main": "https://sync.consensia.cc/modules/encryption.js", @@ -52,7 +52,7 @@ { "id": "i18n-zh", "name": "I18n 简体中文", - "version": "1.0.0", + "version": "1.0.1", "description": "Simplified Chinese UI language pack. / 简体中文介面语言包。", "icon": "languages", "main": "https://sync.consensia.cc/modules/i18n-zh.js", @@ -61,7 +61,7 @@ { "id": "i18n-zh-TW", "name": "I18n 繁體中文", - "version": "1.0.0", + "version": "1.0.1", "description": "Traditional Chinese UI language pack. / 繁體中文介面語言包。", "icon": "languages", "main": "https://sync.consensia.cc/modules/i18n-zh-TW.js", @@ -70,7 +70,7 @@ { "id": "i18n-ru", "name": "I18n Русский", - "version": "1.0.0", + "version": "1.0.1", "description": "Russian UI language pack. / Пакет русского интерфейса.", "icon": "languages", "main": "https://sync.consensia.cc/modules/i18n-ru.js", @@ -89,11 +89,11 @@ { "id": "rclone-s3-timestamp", "name": "Rclone S3 Timestamp", - "version": "0.1.0", + "version": "0.1.1", "description": "Preserves file modification times at server side if you are using \"Rclone serve S3\". This module depends on the S3 module.", "icon": "bandage", "main": "https://sync.consensia.cc/modules/rclone-s3-timestamp.js", - "minPluginVersion": "3.3.0", + "minPluginVersion": "3.4.2", "readme": "https://sync.consensia.cc/deep-dive/modules/rclone-s3-timestamp" } ] diff --git a/packages/dropbox/tsdown.config.ts b/packages/dropbox/tsdown.config.ts index 7a1f1469..3a3cfe32 100644 --- a/packages/dropbox/tsdown.config.ts +++ b/packages/dropbox/tsdown.config.ts @@ -15,5 +15,6 @@ export default defineConfig({ minify: true, outExtensions: () => ({ js: '.js' }), outputOptions: { codeSplitting: false }, + platform: 'browser', plugins: [syncEngineModule(moduleCatalog)], }); diff --git a/packages/encryption/src/wrapper/path.ts b/packages/encryption/src/wrapper/path.ts index d79cae8d..03e5bd6d 100644 --- a/packages/encryption/src/wrapper/path.ts +++ b/packages/encryption/src/wrapper/path.ts @@ -5,6 +5,7 @@ import { textToUint8Array, uint8ArrayToText, } from '@repo/shared/binary'; +import { describeError, toError } from '@repo/shared/error'; import type { Binary, StoreSync } from '@hesprs/sync-engine-sdk'; export type EncryptionStores = { @@ -71,8 +72,8 @@ function decryptBasename(nameKey: Binary, encryptedBasename: string): string { decodeBase64Url(encryptedBasename), ); return normalizeBasename(uint8ArrayToText(plaintext)); - } catch { - throw new Error('Encrypted file name is malformed'); + } catch (error) { + throw describeError(toError(error), 'File name decryption failed'); } } diff --git a/packages/encryption/tsdown.config.ts b/packages/encryption/tsdown.config.ts index 7f361ba6..f42bb380 100644 --- a/packages/encryption/tsdown.config.ts +++ b/packages/encryption/tsdown.config.ts @@ -6,9 +6,10 @@ export default defineConfig({ clean: process.env.MODE !== 'dev', dts: false, entry: { encryption: 'src/index.ts' }, - inputOptions: { resolve: { alias: { 'hash-wasm': 'hash-wasm/dist/index.esm.js' } } }, minify: true, outExtensions: () => ({ js: '.js' }), outputOptions: { codeSplitting: false }, + platform: 'browser', plugins: [syncEngineModule(moduleCatalog)], + treeshake: { manualPureFunctions: ['Mutex'] }, // Removes the dead Mutexes in hash-wasm }); diff --git a/packages/gdrive/src/gdrive/fs.ts b/packages/gdrive/src/gdrive/fs.ts index 99a84234..a8027436 100644 --- a/packages/gdrive/src/gdrive/fs.ts +++ b/packages/gdrive/src/gdrive/fs.ts @@ -350,7 +350,6 @@ export default class GdriveFs implements RootFs { if (siblings) siblings.push(file); else childrenByParent.set(parent, [file]); } - const results: Array = []; const total = all.length; let completed = 0; @@ -366,7 +365,20 @@ export default class GdriveFs implements RootFs { if (verdict === 'advance') await walk(entry.id, childKey); } }; - await walk(startId, key === '/' ? '' : key); + // Drive resolves the `root` alias in requests but never echoes it back in responses, so a root listing must walk from every parent that is not itself a listed file. + const getWalkRoot = () => { + if (key !== '/') return [startId]; + const idSet = new Set(all.map((file) => file.id)); + const orphanRoots = new Set(); + for (const { parents } of all) { + const root = parents[0]; + if (root && !idSet.has(root)) orphanRoots.add(root); + } + return [...orphanRoots]; + }; + const walkKey = key === '/' ? '' : key; + const walkRoots = getWalkRoot(); + await Promise.all(walkRoots.map((walkRoot) => walk(walkRoot, walkKey))); return results; } } diff --git a/packages/gdrive/test/fs-gdrive.test.ts b/packages/gdrive/test/fs-gdrive.test.ts index 258a8e9f..4e193b00 100644 --- a/packages/gdrive/test/fs-gdrive.test.ts +++ b/packages/gdrive/test/fs-gdrive.test.ts @@ -79,7 +79,7 @@ test('creates folders, lists visible descendants, and honors excluded subtrees', return response({ id: 'folder-1' }); return response({ files: [ - { id: 'folder-1', mimeType: FOLDER_MIME, name: 'notes', parents: ['root'] }, + { id: 'folder-1', mimeType: FOLDER_MIME, name: 'notes', parents: ['root-0AAK'] }, { id: 'file-1', md5Checksum: 'uid', @@ -210,7 +210,7 @@ test('list returns meta for included files without extra requests', async () => mimeType: 'text/markdown', modifiedTime: new Date(1000).toISOString(), name: 'note.md', - parents: ['root'], + parents: ['root-0AAK'], size: '5', }, ], @@ -221,3 +221,62 @@ test('list returns meta for included files without extra requests', async () => expect(await stat.meta()).toStrictEqual({ custom: 'value', mtime: '1000' }); expect(calls.map(({ method }) => method)).toStrictEqual(['GET']); }); + +test('lists and descends top-level items when Drive echoes real root parent ids', async () => { + const { fs } = createFs(() => + response({ + files: [ + { id: 'folder-1', mimeType: FOLDER_MIME, name: 'notes', parents: ['root-0AAK'] }, + { + id: 'file-1', + md5Checksum: 'uid', + mimeType: 'text/markdown', + modifiedTime: new Date(1000).toISOString(), + name: 'note.md', + parents: ['folder-1'], + size: '5', + }, + ], + }), + ); + const result = await fs.list('/', () => 'advance' as const); + expect(result.map(({ key }) => key)).toStrictEqual(['notes/', 'notes/note.md']); +}); + +test('list covers every unlisted parent and dedupes shared parents', async () => { + const { fs } = createFs(() => + response({ + files: [ + { + id: 'file-1', + md5Checksum: 'uid', + mimeType: 'text/markdown', + modifiedTime: new Date(1000).toISOString(), + name: 'a.md', + parents: ['root-0AAK'], + size: '5', + }, + { + id: 'file-2', + md5Checksum: 'uid', + mimeType: 'text/markdown', + modifiedTime: new Date(1000).toISOString(), + name: 'b.md', + parents: ['root-0AAK'], + size: '5', + }, + { + id: 'file-3', + md5Checksum: 'uid', + mimeType: 'text/markdown', + modifiedTime: new Date(1000).toISOString(), + name: 'moved.md', + parents: ['folder-foreign'], + size: '5', + }, + ], + }), + ); + const result = await fs.list('/', () => 'include' as const); + expect(result.map(({ key }) => key).sort()).toStrictEqual(['a.md', 'b.md', 'moved.md']); +}); diff --git a/packages/gdrive/tsdown.config.ts b/packages/gdrive/tsdown.config.ts index 78fe69e2..b9d21bf4 100644 --- a/packages/gdrive/tsdown.config.ts +++ b/packages/gdrive/tsdown.config.ts @@ -20,5 +20,6 @@ export default defineConfig({ minify: true, outExtensions: () => ({ js: '.js' }), outputOptions: { codeSplitting: false }, + platform: 'browser', plugins: [syncEngineModule(moduleCatalog)], }); diff --git a/packages/i18n/src/ru/translations.ts b/packages/i18n/src/ru/translations.ts index 1d9ec7c3..8f468c0e 100644 --- a/packages/i18n/src/ru/translations.ts +++ b/packages/i18n/src/ru/translations.ts @@ -133,6 +133,8 @@ const ru: Translations = { development: 'Разработка', diffMatchPatch: 'Объединить', disableModule: 'Отключить модуль', + discoveredModules: ({ module, source }) => + `Найдено ${pc(module, 'модуль', 'модуля', 'модулей')} из ${pc(source, 'источника', 'источников', 'источников')}.`, done: 'Готово', dontSync: 'Не синхронизировать', download: 'Скачать', @@ -260,7 +262,7 @@ const ru: Translations = { noticeStatusOnMobileDescription: 'Отображать всплывающее уведомление на мобильных устройствах во время синхронизации. Заменяет строку состояния, используемую на ПК.', official: 'Официальный', - openReadme: 'Открыть страницу README модуля.', + openReadme: 'Открыть страницу README модуля', pleaseSetBackend: 'Пожалуйста, выберите бэкенд!', readmePage: 'Страница README', readmePageDescription: @@ -274,6 +276,7 @@ const ru: Translations = { 'Ускорить синхронизацию в реальном времени, повторно используя кэшированные данные и избегая лишней проверки удалённых файлов.', realtimeSyncPlaceholder: 'Введите задержку (например, 500ms, 5s)', recordsCleared: 'Записи очищены', + refreshSources: 'Обновить источники', remoteMigration: 'Миграция удалённого хранилища', removeLocal: 'Удалить локальный файл', removeRecord: 'Удалить запись', diff --git a/packages/i18n/src/zh-TW/translations.ts b/packages/i18n/src/zh-TW/translations.ts index 98f2fe2f..90435848 100644 --- a/packages/i18n/src/zh-TW/translations.ts +++ b/packages/i18n/src/zh-TW/translations.ts @@ -99,6 +99,7 @@ const zhTW: Translations = { development: '開發者選項', diffMatchPatch: '文字合併', disableModule: '停用模組', + discoveredModules: ({ module, source }) => `已從 ${source} 個來源找到 ${module} 個模組。`, done: '完成', dontSync: '不同步', download: '下載', @@ -220,7 +221,7 @@ const zhTW: Translations = { noticeStatusOnMobile: '行動裝置同步狀態通知', noticeStatusOnMobileDescription: '同步進行時於行動裝置上顯示通知訊息(取代桌面版的狀態列)。', official: '官方', - openReadme: '開啟模組的 README 頁面。', + openReadme: '開啟模組的 README 頁面', pleaseSetBackend: '請先設定後端!', readmePage: 'README 頁面', readmePageDescription: '設定模組的選用 README 頁面,留空表示無 README。', @@ -232,6 +233,7 @@ const zhTW: Translations = { realtimeSyncFastModeDescription: '透過重複使用快取資料來加速即時同步,並跳過不必要的遠端掃描。', realtimeSyncPlaceholder: '輸入同步延遲(例如 500ms, 5s)', recordsCleared: '紀錄已清除', + refreshSources: '重新整理來源', remoteMigration: '遠端遷移', removeLocal: '移除本地', removeRecord: '移除紀錄', diff --git a/packages/i18n/src/zh/translations.ts b/packages/i18n/src/zh/translations.ts index 07f72dd6..af1a2c70 100644 --- a/packages/i18n/src/zh/translations.ts +++ b/packages/i18n/src/zh/translations.ts @@ -97,6 +97,7 @@ const zh: Translations = { development: '开发', diffMatchPatch: '合并', disableModule: '禁用模块', + discoveredModules: ({ module, source }) => `已从 ${source} 个源发现 ${module} 个模块。`, done: '完成', dontSync: '不同步', download: '下载', @@ -219,7 +220,7 @@ const zh: Translations = { noticeStatusOnMobileDescription: '同步进行时在移动设备上显示通知提示。在桌面端则会替换状态栏显示。', official: '官方', - openReadme: '打开模块的 README 页面。', + openReadme: '打开模块的 README 页面', pleaseSetBackend: '请先设置后端!', readmePage: 'README 页面', readmePageDescription: '设置模块的可选 README 页面,留空表示无 README。', @@ -231,6 +232,7 @@ const zh: Translations = { realtimeSyncFastModeDescription: '通过复用缓存数据来加速实时同步,并避免不必要的远程探测。', realtimeSyncPlaceholder: '输入同步延迟(例如 500ms, 5s)', recordsCleared: '记录已清除', + refreshSources: '刷新源', remoteMigration: '远程迁移', removeLocal: '移除本地', removeRecord: '移除记录', diff --git a/packages/i18n/tsdown.config.ts b/packages/i18n/tsdown.config.ts index 51788b74..916d596d 100644 --- a/packages/i18n/tsdown.config.ts +++ b/packages/i18n/tsdown.config.ts @@ -12,5 +12,6 @@ export default defineConfig({ }, minify: true, outExtensions: () => ({ js: '.js' }), + platform: 'browser', plugins: [syncEngineModule(moduleCatalog)], }); diff --git a/packages/plugin/dist/dev.spec.d.ts b/packages/plugin/dist/dev.spec.d.ts index 7f137b6f..7a3719f2 100644 --- a/packages/plugin/dist/dev.spec.d.ts +++ b/packages/plugin/dist/dev.spec.d.ts @@ -1,4 +1,4 @@ -import { Bt as Binary, Ft as RecordStat, It as RecordStatsMap, K as TaskNames, Lt as Stat, Mt as FolderStat, Nt as MaybePromise, Ot as RootFs, Rt as StatsMap, d as RequestResponse, jt as FileStat, kt as WrappedFs, l as Request, u as RequestParam, yt as Fs, z as Decider, zt as StringKV } from "./index-r0HV0XqQ.spec.js"; +import { Bt as Binary, Ft as RecordStat, It as RecordStatsMap, K as TaskNames, Lt as Stat, Mt as FolderStat, Nt as MaybePromise, Ot as RootFs, Rt as StatsMap, d as RequestResponse, jt as FileStat, kt as WrappedFs, l as Request, u as RequestParam, yt as Fs, z as Decider, zt as StringKV } from "./index-CgW2TrzR.spec.js"; declare function debugWrapper(original: Fs, log: (content: string) => void): WrappedFs; type FsCalls = { delete: Array; diff --git a/packages/plugin/dist/index-r0HV0XqQ.spec.d.ts b/packages/plugin/dist/index-CgW2TrzR.spec.d.ts similarity index 99% rename from packages/plugin/dist/index-r0HV0XqQ.spec.d.ts rename to packages/plugin/dist/index-CgW2TrzR.spec.d.ts index 4e2c3ef3..5401d62c 100644 --- a/packages/plugin/dist/index-r0HV0XqQ.spec.d.ts +++ b/packages/plugin/dist/index-CgW2TrzR.spec.d.ts @@ -231,7 +231,7 @@ type TranslateParams = R extends Factory ? type Translate = (key: K, ...arg: TranslateParams) => O[K] extends string | Snippet ? string : DocumentFragment; declare class I18n { private readonly targetLangs; - readonly i18n: TranslationResource; + readonly i18n: {}; private readonly registerI18n; private readonly translate; root: { @@ -464,10 +464,14 @@ declare class Extensibility { failedToLoadModule: Snippet; failedToDownloadModule: Snippet; failedToFetchSource: Snippet; + discoveredModules: Snippet<{ + module: number; + source: number; + }>; integrityCheckFailed: string; }; readonly events: { - moduleLoaded: string; + moduleLoaded: AugmentedModuleMeta; moduleUnloaded: string; }; constructor(ctx: { @@ -778,6 +782,13 @@ type ModuleManagementTranslations = { official: string; someModulesHidden: string; openReadme: string; + searchModules: string; + moduleManagement: string; + showInstalledOnly: string; + installModuleFromFile: string; + installModuleFromCode: string; + moduleExtensionWarning: Fragment; + refreshSources: string; }; type ModuleEditorTranslations = { editModuleInformation: string; @@ -803,14 +814,7 @@ type ModuleEditorTranslations = { readmePageDescription: string; readmePagePlaceholder: string; }; -type ModulesTranslations = ModuleEditorTranslations & ModuleManagementTranslations & CodeInputTranslations & { - searchModules: string; - moduleManagement: string; - showInstalledOnly: string; - installModuleFromFile: string; - installModuleFromCode: string; - moduleExtensionWarning: Fragment; -}; +type ModulesTranslations = ModuleEditorTranslations & ModuleManagementTranslations & CodeInputTranslations; type CustomHeaders = Array<{ type: 'plaintext' | 'secret'; value: string; diff --git a/packages/plugin/dist/index.spec.d.ts b/packages/plugin/dist/index.spec.d.ts index 62c5ee87..5c2f6a3d 100644 --- a/packages/plugin/dist/index.spec.d.ts +++ b/packages/plugin/dist/index.spec.d.ts @@ -1,2 +1,2 @@ -import { $ as MoveLocal, A as setNeedMigration, At as WriteAtom, B as DeciderInput, Bt as Binary, C as REGRET_ERROR_MESSAGE, Ct as MkdirAtom, D as readWithSize, Dt as OutputAtom, E as pipe, Et as OptimizerOutput, F as CallableOrObjectTree, Ft as RecordStat, G as Task, H as AddRecord, I as SettingEntry, It as RecordStatsMap, J as ResolveConflict, K as TaskNames, L as AugmentedModuleMeta, Lt as Stat, M as generateEditableList, Mt as FolderStat, N as reactivelyValidate, Nt as MaybePromise, O as writeWithSize, Ot as RootFs, P as settingEntry, Pt as Progress, Q as MoveRemote, R as ModuleMeta, Rt as StatsMap, S as digOriginal, St as ListReporter, T as concurrency, Tt as OptimizerInput, U as ConflictResolver, V as TaskFactory, W as ConflictResolverPayload, X as RemoveRecord, Y as RemoveRemote, Z as RemoveLocal, _ as Events, _t as CustomAtom, a as LocalRequestMiddlewareEntry, at as ObsidianLanguageCode, b as ExistingMemoryDB, bt as InputAtom, c as RemoteRequestMiddlewareEntry, ct as TranslationResource, d as RequestResponse, dt as DatabaseAsync, et as Download, f as TriggerEntry, ft as DatabaseSync, g as Context, gt as BatchOptimizer, h as SyncTerminateReason, ht as StoreSync, i as FsWrapperEntry, it as Fragment, j as LabelDefinition, jt as FileStat, k as prefixWrapper, kt as WrappedFs, l as Request, lt as Dispatch, m as SyncOptions, mt as StoreOperations, n as ConflictResolverEntry, nt as CreateLocalDir, o as OptimizerEntry, ot as Snippet, p as RemoteLister, pt as StoreAsync, q as Upload, r as DeciderEntry, rt as RecordStore, s as RemoteFsEntry, st as Translate, t as VaultRequest, tt as CreateRemoteDir, u as RequestParam, ut as On, v as Settings, vt as DeleteAtom, w as chunkSize, wt as MoveAtom, x as SelectFromContext, xt as ListOptions, y as Translations, yt as Fs, z as Decider, zt as StringKV } from "./index-r0HV0XqQ.spec.js"; +import { $ as MoveLocal, A as setNeedMigration, At as WriteAtom, B as DeciderInput, Bt as Binary, C as REGRET_ERROR_MESSAGE, Ct as MkdirAtom, D as readWithSize, Dt as OutputAtom, E as pipe, Et as OptimizerOutput, F as CallableOrObjectTree, Ft as RecordStat, G as Task, H as AddRecord, I as SettingEntry, It as RecordStatsMap, J as ResolveConflict, K as TaskNames, L as AugmentedModuleMeta, Lt as Stat, M as generateEditableList, Mt as FolderStat, N as reactivelyValidate, Nt as MaybePromise, O as writeWithSize, Ot as RootFs, P as settingEntry, Pt as Progress, Q as MoveRemote, R as ModuleMeta, Rt as StatsMap, S as digOriginal, St as ListReporter, T as concurrency, Tt as OptimizerInput, U as ConflictResolver, V as TaskFactory, W as ConflictResolverPayload, X as RemoveRecord, Y as RemoveRemote, Z as RemoveLocal, _ as Events, _t as CustomAtom, a as LocalRequestMiddlewareEntry, at as ObsidianLanguageCode, b as ExistingMemoryDB, bt as InputAtom, c as RemoteRequestMiddlewareEntry, ct as TranslationResource, d as RequestResponse, dt as DatabaseAsync, et as Download, f as TriggerEntry, ft as DatabaseSync, g as Context, gt as BatchOptimizer, h as SyncTerminateReason, ht as StoreSync, i as FsWrapperEntry, it as Fragment, j as LabelDefinition, jt as FileStat, k as prefixWrapper, kt as WrappedFs, l as Request, lt as Dispatch, m as SyncOptions, mt as StoreOperations, n as ConflictResolverEntry, nt as CreateLocalDir, o as OptimizerEntry, ot as Snippet, p as RemoteLister, pt as StoreAsync, q as Upload, r as DeciderEntry, rt as RecordStore, s as RemoteFsEntry, st as Translate, t as VaultRequest, tt as CreateRemoteDir, u as RequestParam, ut as On, v as Settings, vt as DeleteAtom, w as chunkSize, wt as MoveAtom, x as SelectFromContext, xt as ListOptions, y as Translations, yt as Fs, z as Decider, zt as StringKV } from "./index-CgW2TrzR.spec.js"; export { type AddRecord, type AugmentedModuleMeta, type BatchOptimizer, type Binary, type CallableOrObjectTree, type ConflictResolver, type ConflictResolverEntry, type ConflictResolverPayload, type Context, type CreateLocalDir, type CreateRemoteDir, type CustomAtom, type DatabaseAsync, type DatabaseSync, type Decider, type DeciderEntry, type DeciderInput, type DeleteAtom, type Dispatch, type Download, type Events, type ExistingMemoryDB, type FileStat, type FolderStat, type Fragment, type Fs, type FsWrapperEntry, type InputAtom, type LabelDefinition, type ListOptions, type ListReporter, type LocalRequestMiddlewareEntry, type MaybePromise, type MkdirAtom, type ModuleMeta, type MoveAtom, type MoveLocal, type MoveRemote, type ObsidianLanguageCode, type On, type OptimizerEntry, type OptimizerInput, type OptimizerOutput, type OutputAtom, type Progress, REGRET_ERROR_MESSAGE, type RecordStat, type RecordStatsMap, type RecordStore, type RemoteFsEntry, type RemoteLister, type RemoteRequestMiddlewareEntry, type RemoveLocal, type RemoveRecord, type RemoveRemote, type Request, type RequestParam, type RequestResponse, type ResolveConflict, type RootFs, SelectFromContext, type SettingEntry, type Settings, type Snippet, type Stat, type StatsMap, type StoreAsync, type StoreOperations, type StoreSync, type StringKV, type SyncOptions, type SyncTerminateReason, type Task, type TaskFactory, type TaskNames, type Translate, type TranslationResource, type Translations, type TriggerEntry, type Upload, type VaultRequest, type WrappedFs, type WriteAtom, chunkSize, concurrency, digOriginal, generateEditableList, pipe, prefixWrapper, reactivelyValidate, readWithSize, setNeedMigration, settingEntry, writeWithSize }; \ No newline at end of file diff --git a/packages/plugin/src/components/module-management/App.tsx b/packages/plugin/src/components/module-management/App.tsx index 2d190b30..8c62ab0e 100644 --- a/packages/plugin/src/components/module-management/App.tsx +++ b/packages/plugin/src/components/module-management/App.tsx @@ -1,22 +1,27 @@ +import CodeInputModal from '../CodeInputModal'; +import ModuleEditorModal from '../ModuleEditorModal'; import Card from './Card'; -import { prepareFuzzySearch } from 'obsidian'; -import { For, Show, createMemo, createSignal, onCleanup, onMount } from 'solid-js'; -import type { ModuleManagementContext, ModuleManagementHooks, PendingAction } from './index'; +import { MODULE_EXTENSION } from '@/modules/Extensibility'; +import { Menu, prepareFuzzySearch, SearchComponent, Notice, ExtraButtonComponent } from 'obsidian'; +import { For, Show, createEffect, createMemo, createSignal, onMount } from 'solid-js'; +import type { ModuleManagementContext, PendingAction } from './index'; import type { AugmentedModuleMeta } from '@/modules/Extensibility'; import type { MaybePromise } from '@/types'; -import type { SearchResult } from 'obsidian'; +import type { MenuItem, SearchResult } from 'obsidian'; + +const ALTERNATIVE_MODULE_EXTENSION = '.mjs'; export default function App(props: { + el: Element; ctx: ModuleManagementContext; - hooks: ModuleManagementHooks; isUnmounted: () => boolean; }) { const t = props.ctx.translate; - const [sourceModules, setSourceModules] = createSignal>([]); - const [installedModules, setInstalledModules] = createSignal< - Record - >({}); - const [loadedIds, setLoadedIds] = createSignal>(new Set()); + const [sourceModules, setSourceModules] = createSignal(new Map()); + const [installedModules, setInstalledModules] = createSignal(props.ctx.discoveredModules, { + equals: () => false, + }); + const [loadedIds, setLoadedIds] = createSignal(new Set()); const [query, setQuerySignal] = createSignal(''); const [showInstalledOnly, setShowInstalledOnlySignal] = createSignal(false); const [hasLoaded, setHasLoaded] = createSignal(false); @@ -28,20 +33,24 @@ export default function App(props: { const syncSnapshots = () => { if (props.isUnmounted()) return; - setInstalledModules(Object.fromEntries(props.ctx.discoveredModules)); + setInstalledModules(props.ctx.discoveredModules); setLoadedIds(new Set(props.ctx.loadedModules.keys())); }; - const refreshSources = async () => { - if (props.isUnmounted()) return; + const refreshSources = async (manual = false) => { + if (props.isUnmounted() || isLoading()) return; setIsLoading(true); try { const seen = new Set(); - const modules = (await props.ctx.fetchSources()).filter(({ id }) => { - if (seen.has(id)) return false; - seen.add(id); - return true; - }); + const modules = new Map( + (await props.ctx.fetchSources(manual)) + .filter(({ id }) => { + if (seen.has(id)) return false; + seen.add(id); + return true; + }) + .map((module) => [module.id, module]), + ); if (props.isUnmounted()) return; setSourceModules(modules); syncSnapshots(); @@ -52,28 +61,32 @@ export default function App(props: { } }; - const mergedModules = createMemo>(() => - mergeModules(sourceModules(), installedModules()), - ); + const mergedModules = createMemo>(() => [ + ...new Set([...sourceModules().keys(), ...installedModules().keys()]), + ]); + + const getCanonicalMeta = (id: string) => + (installedModules().get(id) ?? sourceModules().get(id)) as AugmentedModuleMeta; - const visibleModules = createMemo>(() => { + const visibleModules = createMemo>(() => { const normalizedQuery = query().trim(); - const filtered = mergedModules().filter((module) => { + const filtered = mergedModules().filter((id) => { if (!showInstalledOnly()) return true; - return module.id in installedModules(); + return installedModules().has(id); }); - if (!normalizedQuery) return filtered.sort(sortModulesAlphabetically); + if (!normalizedQuery) return filtered.sort((a, b) => a.localeCompare(b)); const match = prepareFuzzySearch(normalizedQuery); return filtered + .map(getCanonicalMeta) .map((module) => ({ module, score: getModuleScore(match, module) })) .filter( (entry): entry is { module: AugmentedModuleMeta; score: number } => entry.score !== undefined, ) - .sort((a, b) => b.score - a.score || sortModulesAlphabetically(a.module, b.module)) - .map(({ module }) => module); + .sort((a, b) => b.score - a.score || a.module.id.localeCompare(b.module.id)) + .map(({ module: { id } }) => id); }); const runAction = async (id: string, action: PendingAction, op: () => MaybePromise) => { @@ -88,18 +101,9 @@ export default function App(props: { } }; - const unsubscribeQuery = props.hooks.onQuery.subscribe((nextQuery) => - setQuerySignal(nextQuery), - ); - const unsubscribeShowInstalledOnly = props.hooks.onShowInstalledOnlyChange.subscribe( - (enabled) => setShowInstalledOnlySignal(enabled), - ); - const unsubscribeInstallFromFile = props.hooks.onInstallModuleFromFile.subscribe(syncSnapshots); - - onCleanup(() => { - unsubscribeQuery(); - unsubscribeShowInstalledOnly(); - unsubscribeInstallFromFile(); + createEffect(() => { + if (isLoading()) props.el.addClass('is-loading'); + else props.el.removeClass('is-loading'); }); onMount(() => { @@ -108,49 +112,128 @@ export default function App(props: { }); return ( -
- 0} - fallback={ -
- {getEmptyStateText({ - hasLoaded: hasLoaded(), - isLoading: isLoading(), - query: query(), - showInstalledOnly: showInstalledOnly(), - translate: t, - })} -
- } - > -
+
{ + new SearchComponent(controls) + .setPlaceholder(t('searchModules')) + .onChange(setQuerySignal) + .setClass('grow').inputEl.spellcheck = false; + const menu = new Menu() + .addItem((item) => + item + .setIcon('hard-drive-download') + .setTitle(t('showInstalledOnly')) + .setChecked(showInstalledOnly()) + .onClick(() => { + setShowInstalledOnlySignal(!showInstalledOnly()); + item.setChecked(showInstalledOnly()); + }), + ) + .addItem((item) => + pickFile( + item.setIcon('package').setTitle(t('installModuleFromFile')), + async (fileObj) => { + let extension: string; + if (fileObj.name.endsWith(MODULE_EXTENSION)) + extension = MODULE_EXTENSION; + else if (fileObj.name.endsWith(ALTERNATIVE_MODULE_EXTENSION)) + extension = ALTERNATIVE_MODULE_EXTENSION; + else { + new Notice(t('moduleExtensionWarning')); + return; + } + const file = await fileObj.text(); + new ModuleEditorModal(props.ctx, { + file, + initial: { + id: fileObj.name + .slice(0, -extension.length) + .normalize('NFC'), + }, + onSave: async (meta) => { + await props.ctx.installModule(meta, file); + syncSnapshots(); + }, + }).open(); + }, + ), + ) + .addItem((item) => + item + .setIcon('code-xml') + .setTitle(t('installModuleFromCode')) + .onClick(() => { + new CodeInputModal(props.ctx, (file) => + new ModuleEditorModal(props.ctx, { + file, + onSave: async (meta) => { + await props.ctx.installModule(meta, file); + syncSnapshots(); + }, + }).open(), + ).open(); + }), + ) + .addItem((item) => + item + .setIcon('rotate-cw') + .setTitle(t('refreshSources')) + .onClick(() => refreshSources(true)), + ); + + new ExtraButtonComponent(controls) + .setIcon('settings') + .extraSettingsEl.onClickEvent((event) => menu.showAtMouseEvent(event)); + }} + /> +
+ 0} + fallback={ +
+ {getEmptyStateText({ + hasLoaded: hasLoaded(), + isLoading: isLoading(), + query: query(), + showInstalledOnly: showInstalledOnly(), + translate: t, + })} +
+ } > - - {(module) => ( - { - void runAction(module.id, action, op); - }} - /> - )} - -
- - -
- {props.ctx.translate('someModulesHidden')} -
-
-
+
+ + {(id) => ( + { + void runAction(id, action, op); + }} + /> + )} + +
+ + +
+ {props.ctx.translate('someModulesHidden')} +
+
+
+ ); } @@ -176,16 +259,15 @@ function getModuleScore(match: (text: string) => SearchResult | null, module: Au return (nameScore ?? 0) + (descriptionScore ?? 0); } -function mergeModules( - sourceModules: Array, - installedModules: Record, -): Array { - const merged = new Map(); - for (const module of sourceModules) merged.set(module.id, module); - for (const module of Object.values(installedModules)) merged.set(module.id, module); - return [...merged.values()]; -} - -function sortModulesAlphabetically(a: AugmentedModuleMeta, b: AugmentedModuleMeta) { - return a.name.localeCompare(b.name); +function pickFile({ dom }: MenuItem, handler: (file: File) => MaybePromise) { + dom.addClass('relative'); + dom.createEl('input', { + attr: { accept: '.js,.mjs', title: '' }, + cls: 'absolute inset-0 opacity-0', + type: 'file', + }).addEventListener('change', (e) => { + const file = (e.target as HTMLInputElement).files?.[0]; + if (!file) return; + void handler(file); + }); } diff --git a/packages/plugin/src/components/module-management/Card.tsx b/packages/plugin/src/components/module-management/Card.tsx index e2b8a790..3d7b2dcb 100644 --- a/packages/plugin/src/components/module-management/Card.tsx +++ b/packages/plugin/src/components/module-management/Card.tsx @@ -18,22 +18,23 @@ export default function Card(props: { | 'updateModuleMeta' | 'app' >; - installedMeta?: AugmentedModuleMeta; + sourceMeta?: AugmentedModuleMeta; + canonical: AugmentedModuleMeta; isLoaded: boolean; - module: AugmentedModuleMeta; + installedMeta?: AugmentedModuleMeta; pendingAction?: PendingAction; runAction: (action: PendingAction, op: () => MaybePromise) => void; }) { - const isInstalled = () => props.installedMeta !== undefined; + const isInstalled = () => Boolean(props.installedMeta); const hasUpdate = () => - props.installedMeta !== undefined && - compare(props.module.version, props.installedMeta.version) === 1; + props.sourceMeta && + props.installedMeta && + compare(props.sourceMeta.version, props.installedMeta.version) === 1; const busy = () => props.pendingAction !== undefined; const versionLabel = () => { - const currentVersion = props.installedMeta?.version; - if (currentVersion !== undefined && compare(props.module.version, currentVersion) === 1) - return `v${currentVersion} -> v${props.module.version}`; - return `v${currentVersion ?? props.module.version}`; + if (hasUpdate()) + return `v${(props.installedMeta as AugmentedModuleMeta).version}\u00A0\u00A0→\u00A0\u00A0v${(props.sourceMeta as AugmentedModuleMeta).version}`; + return `v${props.canonical.version}`; }; return ( @@ -42,16 +43,16 @@ export default function Card(props: {
setIcon(el, props.module.icon)} + ref={(el) => setIcon(el, props.canonical.icon)} /> - {props.module.name} + {props.canonical.name}
{versionLabel()}
- + {props.ctx.translate('official')} @@ -64,25 +65,25 @@ export default function Card(props: {
- {props.module.description} + {props.canonical.description}
- + { setIcon(ref, 'book-open-text'); setTooltip(ref, props.ctx.translate('openReadme')); }} /> - + props.runAction('download', () => - props.ctx.downloadModule(props.module), + props.ctx.downloadModule(props.sourceMeta ?? props.canonical), ) } /> @@ -103,7 +104,9 @@ export default function Card(props: { pending={props.pendingAction === 'delete'} tooltip={props.ctx.translate('deleteModule')} onClick={() => - props.runAction('delete', () => props.ctx.deleteModule(props.module.id)) + props.runAction('delete', () => + props.ctx.deleteModule(props.canonical.id), + ) } /> new ModuleEditorModal(props.ctx, { - initial: props.module, + initial: props.canonical, onSave: (newMeta) => props.runAction('editInfo', () => props.ctx.updateModuleMeta(newMeta), @@ -126,11 +129,13 @@ export default function Card(props: { enabled={props.isLoaded} translate={props.ctx.translate} onEnable={() => - props.runAction('enable', () => props.ctx.enableModule(props.module.id)) + props.runAction('enable', () => + props.ctx.enableModule(props.canonical.id), + ) } onDisable={() => props.runAction('disable', () => - props.ctx.disableModule(props.module.id), + props.ctx.disableModule(props.canonical.id), ) } /> diff --git a/packages/plugin/src/components/module-management/index.ts b/packages/plugin/src/components/module-management/index.ts index b57c099a..7a2471a2 100644 --- a/packages/plugin/src/components/module-management/index.ts +++ b/packages/plugin/src/components/module-management/index.ts @@ -1,9 +1,8 @@ import App from './App'; import { render } from 'solid-js/web'; import type { AugmentedModuleMeta } from '@/modules/Extensibility'; -import type { Translate } from '@/modules/I18n'; +import type { Fragment, Translate } from '@/modules/I18n'; import type { App as ObsidianApp } from 'obsidian'; -import type { Hook } from 'synthkernel'; export type PendingAction = 'delete' | 'disable' | 'download' | 'enable' | 'editInfo'; @@ -23,15 +22,17 @@ export type ModuleManagementTranslations = { official: string; someModulesHidden: string; openReadme: string; -}; - -export type ModuleManagementHooks = { - onQuery: Hook<[string]>; - onShowInstalledOnlyChange: Hook<[boolean]>; - onInstallModuleFromFile: Hook; + searchModules: string; + moduleManagement: string; + showInstalledOnly: string; + installModuleFromFile: string; + installModuleFromCode: string; + moduleExtensionWarning: Fragment; + refreshSources: string; }; export type ModuleManagementContext = { + installModule: (meta: AugmentedModuleMeta, module: string) => Promise; fetchSources: (manual?: boolean) => Promise>; discoveredModules: Map; loadedModules: Map; @@ -47,13 +48,9 @@ export type ModuleManagementContext = { pluginOutdated: boolean; }; -export function mountModuleManagementList( - el: Element, - ctx: ModuleManagementContext, - hooks: ModuleManagementHooks, -) { +export function mountModuleManagement(el: Element, ctx: ModuleManagementContext) { let isUnmounted = false; - const unmount = render(() => App({ ctx, hooks, isUnmounted: () => isUnmounted }), el); + const unmount = render(() => App({ ctx, el, isUnmounted: () => isUnmounted }), el); return () => { isUnmounted = true; unmount(); diff --git a/packages/plugin/src/en.ts b/packages/plugin/src/en.ts index 567f0731..9c54de83 100644 --- a/packages/plugin/src/en.ts +++ b/packages/plugin/src/en.ts @@ -119,6 +119,8 @@ const en: Translations = { development: 'Development', diffMatchPatch: 'Merge', disableModule: 'Disable module', + discoveredModules: ({ module, source }) => + `Discovered ${pc(module, 'module', 'modules')} from ${pc(source, 'source', 'sources')}.`, done: 'Done', dontSync: "Don't sync", download: 'Download', @@ -247,7 +249,7 @@ const en: Translations = { noticeStatusOnMobileDescription: 'Display a notice on mobile devices when synchronization is in progress. Replaces the status bar on desktop.', official: 'Official', - openReadme: "Open the module's README page.", + openReadme: "Open the module's README page", pleaseSetBackend: 'Please set a backend!', readmePage: 'README page', readmePageDescription: @@ -261,6 +263,7 @@ const en: Translations = { 'Speed up realtime sync by reusing cached data and avoid unnecessary remote discovery.', realtimeSyncPlaceholder: 'Enter sync delay (e.g. 500ms, 5s)', recordsCleared: 'Records cleared', + refreshSources: 'Refresh sources', remoteMigration: 'Remote migration', removeLocal: 'Remove local', removeRecord: 'Remove record', diff --git a/packages/plugin/src/modules/EventBus.ts b/packages/plugin/src/modules/EventBus.ts index e543b72b..7e8fb1f3 100644 --- a/packages/plugin/src/modules/EventBus.ts +++ b/packages/plugin/src/modules/EventBus.ts @@ -105,7 +105,9 @@ export default class EventBus { else putSyncLog(`Sync ended with result: \`${result}\`.`); isIdle(true); }), - on('moduleLoaded', (name) => putGeneralLog(`Module \`${name}\` loaded.`)), + on('moduleLoaded', ({ id, version }) => + putGeneralLog(`Module \`${id}@${version}\` loaded.`), + ), on('moduleUnloaded', (name) => putGeneralLog(`Module \`${name}\` unloaded.`)), ); } diff --git a/packages/plugin/src/modules/Extensibility.ts b/packages/plugin/src/modules/Extensibility.ts index efb6310a..89e3a21a 100644 --- a/packages/plugin/src/modules/Extensibility.ts +++ b/packages/plugin/src/modules/Extensibility.ts @@ -55,9 +55,10 @@ export default class Extensibility { failedToLoadModule: Snippet; failedToDownloadModule: Snippet; failedToFetchSource: Snippet; + discoveredModules: Snippet<{ module: number; source: number }>; integrityCheckFailed: string; }; - declare readonly events: { moduleLoaded: string; moduleUnloaded: string }; + declare readonly events: { moduleLoaded: AugmentedModuleMeta; moduleUnloaded: string }; constructor( private readonly ctx: { @@ -149,8 +150,7 @@ export default class Extensibility { ) => { const { id, integrity, name, enabled } = meta; if (this.loadedModules.get(id)) return; - const { dispatch, translate, app, __addModule__, __getModule__, allModules, saveSettings } = - this.ctx; + const { dispatch, translate, app, __addModule__, __getModule__, allModules } = this.ctx; const { adapter } = app.vault; try { const file = module ?? (await adapter.read(this.getModulePath(id))); @@ -161,17 +161,14 @@ export default class Extensibility { if (typeof ctor !== 'function') throw new TypeError(`Invalid module!`); __addModule__(ctor); const instance: ModuleInstance = __getModule__(ctor as never); - const modules = this.settings.modules; + const { modules } = this.settings; const moduleSettings = modules[id]; - if (moduleSettings) { - Object.assign(instance.moduleSettings, moduleSettings); - modules[id] = instance.moduleSettings; - } else modules[id] = instance.moduleSettings; - void saveSettings(); + if (moduleSettings) Object.assign(instance.moduleSettings, moduleSettings); + modules[id] = instance.moduleSettings; if (start) instance.start?.(); allModules.add(ctor); this.loadedModules.set(id, ctor); - dispatch('moduleLoaded', id); + dispatch('moduleLoaded', meta); } catch (error) { if (enabled) { const discoveredMeta = this.discoveredModules.get(id); @@ -239,11 +236,14 @@ export default class Extensibility { private readonly deleteModule = async (id: string) => { const version = this.discoveredModules.get(id); if (!version) return; + const { app, saveSettings } = this.ctx; + const adapter = app.vault.adapter; this.unloadModule(id); - await this.ctx.app.vault.adapter.remove(this.getModulePath(id)); + const path = this.getModulePath(id); + if (await adapter.exists(path)) await adapter.remove(path); this.discoveredModules.delete(id); void this.moduleStore.delete(id); - void this.ctx.saveSettings(); + void saveSettings(); }; private readonly fetchSources = async (manual = false) => { @@ -293,6 +293,13 @@ export default class Extensibility { }); }), ); + if (manual) + new Notice( + translate('discoveredModules', { + module: modules.length, + source: moduleSources.length, + }), + ); dispatch( 'logGeneral', `Discovered ${modules.length} module(s) from ${moduleSources.length} source(s).`, @@ -301,20 +308,22 @@ export default class Extensibility { }; private readonly updateModules = async () => { - if (!this.discoveredModules.size) return; + if (!this.discoveredModules.size || !navigator.onLine) return; const { execute, factory, operations } = this.createOperationFactory(); - const { isIdle } = this.ctx; + const { isIdle, dispatch } = this.ctx; (await this.fetchSources()).forEach((meta) => { const { id, source, version } = meta; const existing = this.discoveredModules.get(id); if (!existing || source !== existing.source) return; if (compare(version, existing.version) === 1) factory.download(meta); }); - if (!operations.length) return; + const updatedModules = operations.length; + if (!updatedModules) return; await untilTrue(isIdle, 'stop'); isIdle(false); await execute(); isIdle(true); + dispatch('logGeneral', `Auto-updated ${updatedModules} module(s).`); }; private readonly updateModuleMeta = async (meta: AugmentedModuleMeta) => { diff --git a/packages/plugin/src/modules/I18n.ts b/packages/plugin/src/modules/I18n.ts index 36e5341b..cb971e71 100644 --- a/packages/plugin/src/modules/I18n.ts +++ b/packages/plugin/src/modules/I18n.ts @@ -99,16 +99,17 @@ export default class I18n { getLanguage(), getLanguage().split('-')[0], ] as Array); - readonly i18n: TranslationResource = {}; + readonly i18n = {}; private readonly registerI18n = (code: ObsidianLanguageCode, resource: TranslationResource) => { if (code === DEFAULT_LANGUAGE && !this.targetLangs.has(DEFAULT_LANGUAGE)) - for (const [key, value] of Object.entries(resource)) this.i18n[key] ??= value; + for (const [key, value] of Object.entries(resource)) + (this.i18n as TranslationResource)[key] ??= value; else if (this.targetLangs.has(code)) Object.assign(this.i18n, resource); }; private readonly translate = ((key: string, arg: unknown) => { - const value = this.i18n[key]; + const value = (this.i18n as TranslationResource)[key]; if (typeof value === 'string') return value; // Handle missing keys and argument mismatch due to stale i18n modules try { diff --git a/packages/plugin/src/settings/head.ts b/packages/plugin/src/settings/head.ts index 2061bea9..edf453e0 100644 --- a/packages/plugin/src/settings/head.ts +++ b/packages/plugin/src/settings/head.ts @@ -37,7 +37,7 @@ export type HeadSettingTranslations = { noStrategyConfigured: string; }; -type CheckConnectionDB = DatabaseSync; +type CheckConnectionDB = DatabaseSync; export default function headSettings( ctx: { @@ -290,6 +290,7 @@ function setupCheckConnection({ setError(); if (force) new Notice(`${translate('checkConnectionFailed')}: ${error.message}`, 5000); logError(describeError(error, `Check connection to \`${settings.remoteFs}\` failed`)); + memoryDB.setMeta('lastCheckedFs', undefined); cleanup(); scheduleCheckConnection(); }; diff --git a/packages/plugin/src/settings/module-management.ts b/packages/plugin/src/settings/module-management.ts index 801f50b0..aacb4a27 100644 --- a/packages/plugin/src/settings/module-management.ts +++ b/packages/plugin/src/settings/module-management.ts @@ -1,165 +1,30 @@ -import CodeInputModal from '@/components/CodeInputModal'; -import { mountModuleManagementList } from '@/components/module-management'; -import ModuleEditorModal from '@/components/ModuleEditorModal'; -import { MODULE_EXTENSION } from '@/modules/Extensibility'; -import { App, Menu, SearchComponent, setIcon, SettingPage, Notice, MenuItem } from 'obsidian'; -import { hook } from 'synthkernel'; -import type { Settings } from '@'; +import { mountModuleManagement } from '@/components/module-management'; +import { SettingPage } from 'obsidian'; import type { CodeInputTranslations } from '@/components/CodeInputModal'; -import type { ModuleManagementTranslations } from '@/components/module-management'; +import type { + ModuleManagementContext, + ModuleManagementTranslations, +} from '@/components/module-management'; import type { ModuleEditorTranslations } from '@/components/ModuleEditorModal'; -import type { AugmentedModuleMeta } from '@/modules/Extensibility'; -import type { Fragment, Translate } from '@/modules/I18n'; -import type { MaybePromise } from '@/types'; - -const ALTERNATIVE_MODULE_EXTENSION = '.mjs'; export type ModulesTranslations = ModuleEditorTranslations & ModuleManagementTranslations & - CodeInputTranslations & { - searchModules: string; - moduleManagement: string; - showInstalledOnly: string; - installModuleFromFile: string; - installModuleFromCode: string; - moduleExtensionWarning: Fragment; - }; + CodeInputTranslations; export default class ModuleManagement extends SettingPage { - private readonly t: Translate; - private readonly cleanup: Array<() => void> = []; - private showInstalledOnly = false; + private cleanup?: () => void; - constructor( - private readonly ctx: { - app: App; - translate: Translate; - saveSettings: () => Promise; - fetchSources: (manual?: boolean) => Promise>; - discoveredModules: Map; - loadedModules: Map; - downloadModule: (meta: AugmentedModuleMeta) => Promise; - deleteModule: (id: string) => Promise; - loadModule: (meta: AugmentedModuleMeta, start?: boolean) => Promise; - unloadModule: (id: string) => void; - enableModule: (id: string) => Promise; - disableModule: (id: string) => void; - updateModuleMeta: (meta: AugmentedModuleMeta) => Promise; - installModule: (meta: AugmentedModuleMeta, module: string) => Promise; - settings: Settings; - pluginOutdated: boolean; - }, - ) { + constructor(private readonly ctx: ModuleManagementContext) { super(); this.title = ctx.translate('moduleManagement'); - this.t = ctx.translate; } display() { - const { containerEl, t, ctx, cleanup } = this; - const { installModule } = ctx; - const controlsEl = containerEl.createDiv('flex items-center gap-2 pb-4'); - const searchEl = controlsEl.createDiv('min-w-0 flex-1'); - const listEl = containerEl.createDiv('min-h-0 overflow-y-auto'); - const onQuery = hook<[string]>(); - const onShowInstalledOnlyChange = hook<[boolean]>(); - const onInstallModuleFromFile = hook(); - - const search = new SearchComponent(searchEl) - .setPlaceholder(t('searchModules')) - .onChange(onQuery); - search.inputEl.addClass('w-full'); - search.inputEl.spellcheck = false; - - const menuButton = controlsEl.createEl('button', 'clickable-icon flex-shrink-0 rounded-md'); - setIcon(menuButton, 'settings'); - - const menu = new Menu() - .addItem((item) => - item - .setIcon('hard-drive-download') - .setTitle(t('showInstalledOnly')) - .setChecked(this.showInstalledOnly) - .onClick(() => { - this.showInstalledOnly = !this.showInstalledOnly; - item.setChecked(this.showInstalledOnly); - onShowInstalledOnlyChange(this.showInstalledOnly); - }), - ) - .addItem((item) => - pickFile( - item.setIcon('package').setTitle(t('installModuleFromFile')), - async (fileObj) => { - let extension: string; - if (fileObj.name.endsWith(MODULE_EXTENSION)) extension = MODULE_EXTENSION; - else if (fileObj.name.endsWith(ALTERNATIVE_MODULE_EXTENSION)) - extension = ALTERNATIVE_MODULE_EXTENSION; - else { - new Notice(t('moduleExtensionWarning')); - return; - } - const file = await fileObj.text(); - new ModuleEditorModal(ctx, { - file, - initial: { - id: fileObj.name.slice(0, -extension.length).normalize('NFC'), - }, - onSave: async (meta) => { - await installModule(meta, file); - onInstallModuleFromFile(); - }, - }).open(); - }, - ), - ) - .addItem((item) => - item - .setIcon('code-xml') - .setTitle(t('installModuleFromCode')) - .onClick(() => { - new CodeInputModal(ctx, (file) => - new ModuleEditorModal(ctx, { - file, - onSave: async (meta) => { - await installModule(meta, file); - onInstallModuleFromFile(); - }, - }).open(), - ).open(); - }), - ); - menuButton.onClickEvent((event) => menu.showAtMouseEvent(event)); - - cleanup.push( - mountModuleManagementList(listEl, ctx, { - onInstallModuleFromFile, - onQuery, - onShowInstalledOnlyChange, - }), - () => { - onQuery.clear(); - onShowInstalledOnlyChange.clear(); - }, - ); - onShowInstalledOnlyChange(this.showInstalledOnly); + this.cleanup = mountModuleManagement(this.containerEl, this.ctx); } hide() { - this.cleanup.splice(0).forEach((fn) => fn()); + this.cleanup?.(); this.containerEl.empty(); } } - -function pickFile(item: MenuItem, handler: (file: File) => MaybePromise) { - item.dom.addClass('relative'); - const input = item.dom.createEl('input', { - attr: { accept: '.js,.mjs', title: '' }, - cls: 'absolute top-0 bottom-0 left-0 right-0 opacity-0', - type: 'file', - }); - input.addEventListener('change', (e) => { - const file = (e.target as HTMLInputElement).files?.[0]; - if (!file) return; - void handler(file); - }); -} diff --git a/packages/rclone-s3-timestamp/tsdown.config.ts b/packages/rclone-s3-timestamp/tsdown.config.ts index 250dd5fa..4891b3c2 100644 --- a/packages/rclone-s3-timestamp/tsdown.config.ts +++ b/packages/rclone-s3-timestamp/tsdown.config.ts @@ -9,5 +9,6 @@ export default defineConfig({ minify: true, outExtensions: () => ({ js: '.js' }), outputOptions: { codeSplitting: false }, + platform: 'browser', plugins: [syncEngineModule(moduleCatalog)], }); diff --git a/packages/s3/tsdown.config.ts b/packages/s3/tsdown.config.ts index 503e017b..523a520d 100644 --- a/packages/s3/tsdown.config.ts +++ b/packages/s3/tsdown.config.ts @@ -6,9 +6,10 @@ export default defineConfig({ clean: process.env.MODE !== 'dev', dts: false, entry: { s3: 'src/index.ts' }, - inputOptions: { resolve: { alias: { 'hash-wasm': 'hash-wasm/dist/index.esm.js' } } }, minify: true, outExtensions: () => ({ js: '.js' }), outputOptions: { codeSplitting: false }, + platform: 'browser', plugins: [syncEngineModule(moduleCatalog)], + treeshake: { manualPureFunctions: ['Mutex'] }, // Removes the dead Mutexes in hash-wasm }); diff --git a/packages/smart-merge/tsdown.config.ts b/packages/smart-merge/tsdown.config.ts index b83febb2..50df7984 100644 --- a/packages/smart-merge/tsdown.config.ts +++ b/packages/smart-merge/tsdown.config.ts @@ -9,5 +9,6 @@ export default defineConfig({ minify: true, outExtensions: () => ({ js: '.js' }), outputOptions: { codeSplitting: false }, + platform: 'browser', plugins: [syncEngineModule(moduleCatalog)], }); diff --git a/packages/webdav/package.json b/packages/webdav/package.json index e1ec850c..44a647b3 100644 --- a/packages/webdav/package.json +++ b/packages/webdav/package.json @@ -19,6 +19,8 @@ }, "devDependencies": { "@hesprs/sync-engine-sdk": "workspace:*", - "@repo/shared": "workspace:*" + "@repo/shared": "workspace:*", + "hash-wasm": "catalog:", + "uni-kv": "catalog:" } } diff --git a/packages/webdav/src/index.ts b/packages/webdav/src/index.ts index 1e511579..ac4d0857 100644 --- a/packages/webdav/src/index.ts +++ b/packages/webdav/src/index.ts @@ -6,6 +6,7 @@ import WebdavFs from '@/webdav/fs'; import { digOriginal, prefixWrapper } from '@hesprs/sync-engine-sdk'; import { parseUrl } from '@repo/shared/path'; import type { WebdavTranslations } from '@/setting'; +import type { DigestInfo } from '@/webdav/auth'; import type { RemoteFsEntry, FsWrapperEntry, @@ -19,6 +20,7 @@ import type { Context, RemoteRequestMiddlewareEntry, DatabaseAsync, + DatabaseSync, RecordStat, } from '@hesprs/sync-engine-sdk'; import type { App } from 'obsidian'; @@ -35,6 +37,11 @@ export type WebdavSettings = { timestampHeaders: boolean; }; +export type WebdavDB = DatabaseSync< + Record, + { authMarker?: string; digest?: DigestInfo } +>; + export default class Webdav { private readonly cleanup: Array<() => void> = []; @@ -47,6 +54,7 @@ export default class Webdav { registerSetting: (entry: SettingEntry) => () => void; registerI18n: (lang: ObsidianLanguageCode, translations: TranslationResource) => void; registerRemoteRequestMiddleware: (entry: RemoteRequestMiddlewareEntry) => () => void; + memoryDB: WebdavDB; settings: Settings; // TODO: remove after November 17, 2026 getNamespace: () => string | Error; @@ -82,6 +90,7 @@ export default class Webdav { registerRemoteFsWrapper, registerSetting, registerRemoteRequestMiddleware, + memoryDB, } = this.ctx; const guardEndpoint = () => { if (!this.moduleSettings.endpoint) throw new Error(translate('pleaseConfigureAccount')); @@ -99,7 +108,11 @@ export default class Webdav { const { username, password: pwd } = this.moduleSettings; const password = secretStorage.getSecret(pwd); if (password === null) throw new Error(translate('pleaseConfigureAccount')); - return authorizationMiddleware(request, { password, username }); + return authorizationMiddleware( + request, + { endpoint: this.moduleSettings.endpoint, password, username }, + memoryDB, + ); }, priority: 692, }), diff --git a/packages/webdav/src/webdav/auth.ts b/packages/webdav/src/webdav/auth.ts index c5f55d27..10bb7a86 100644 --- a/packages/webdav/src/webdav/auth.ts +++ b/packages/webdav/src/webdav/auth.ts @@ -1,10 +1,146 @@ -import type { Request } from '@hesprs/sync-engine-sdk'; +import { md5 } from 'hash-wasm'; +import type { WebdavDB } from '@'; +import type { Request, RequestResponse, StringKV } from '@hesprs/sync-engine-sdk'; + +type DigestChallenge = { + algorithm?: string; + nonce: string; + opaque?: string; + // Normalized to 'auth' when the server offers it, or omitted for legacy challenges without qop. + qop?: 'auth'; + realm: string; +}; + +export type DigestInfo = DigestChallenge & { + // MD5(username:realm:password) cached at challenge-parse time, so requests only hash HA2 and the response. + ha1: string; + // RFC 7616 nonce count, formatted as 8 lowercase hex digits per request. + nc: number; +}; export default function authorizationMiddleware( request: Request, - { username, password }: { username: string; password: string }, + { username, password, endpoint }: { username: string; password: string; endpoint: string }, + db: WebdavDB, ): Request { - const Authorization = `Basic ${btoa(`${username}:${password}`)}`; - return async (url, params) => - request(url, { ...params, headers: { ...params?.headers, Authorization } }); + const authMarker = `${endpoint}~${username}~${password}`; + const basic = `Basic ${btoa(`${username}:${password}`)}`; + const loadDigest = (): DigestInfo | undefined => + db.getMeta('authMarker') === authMarker ? db.getMeta('digest') : undefined; + return async (url, params) => { + const send = async (): Promise => { + const digest = loadDigest(); + if (digest) digest.nc += 1; + // The spread freezes the drawn count: the stored entry keeps mutating in place, and a + // concurrent request starting during the md5 awaits below must not shift this one's count. + const snapshot = digest && { ...digest }; + return request(url, { + ...params, + headers: { + ...params?.headers, + Authorization: snapshot + ? await digestAuthorization( + snapshot, + username, + params?.method ?? 'GET', + url, + ) + : basic, + }, + }); + }; + const response = await send(); + const header = response.headers['www-authenticate']; + if (response.status !== 401 || !header) return response; + const challenge = parseDigestChallenge(header); + if (!challenge) return response; + db.setMeta('authMarker', authMarker); + db.setMeta('digest', { + ...challenge, + ha1: await md5(`${username}:${challenge.realm}:${password}`), + nc: 0, + }); + return send(); + }; +} + +async function digestAuthorization( + digest: DigestInfo, + username: string, + method: string, + url: string, +): Promise { + const { pathname, search } = new URL(url); + const uri = `${pathname}${search}`; + const ha2 = await md5(`${method}:${uri}`); + const directives = [ + `username="${quote(username)}"`, + `realm="${quote(digest.realm)}"`, + `nonce="${quote(digest.nonce)}"`, + `uri="${uri}"`, + ]; + let hash: string; + if (digest.qop) { + const nc = digest.nc.toString(16).padStart(8, '0'); + const cnonce = crypto.randomUUID(); + hash = await md5(`${digest.ha1}:${digest.nonce}:${nc}:${cnonce}:${digest.qop}:${ha2}`); + directives.push(`qop=${digest.qop}`, `nc=${nc}`, `cnonce="${cnonce}"`); + } else hash = await md5(`${digest.ha1}:${digest.nonce}:${ha2}`); + directives.push(`response="${hash}"`); + if (digest.opaque) directives.push(`opaque="${quote(digest.opaque)}"`); + if (digest.algorithm) directives.push(`algorithm=${digest.algorithm}`); + return `Digest ${directives.join(', ')}`; +} + +function quote(value: string) { + return value.replaceAll(/["\\]/gu, String.raw`\$&`); +} + +function parseDigestChallenge(header: string): DigestChallenge | undefined { + const params: StringKV = {}; + let inDigest = false; + for (const segment of splitUnquoted(header)) { + const trimmed = segment.trim(); + const param = parseParam(trimmed); + if (param) { + if (inDigest) params[param.name] = param.value; + continue; + } + const scheme = /^(?[A-Za-z]+)(?:\s+(?.+))?$/u.exec(trimmed); + if (!scheme) continue; + inDigest = scheme.groups?.scheme?.toLowerCase() === 'digest'; + if (!inDigest) continue; + // The first parameter shares the scheme's segment, as in `Digest realm="x", nonce="y"`. + const first = scheme.groups?.rest ? parseParam(scheme.groups.rest.trim()) : undefined; + if (first) params[first.name] = first.value; + } + if (!inDigest || !params.nonce || !params.realm) return; + if (params.algorithm && params.algorithm.toLowerCase() !== 'md5') return; + const options = params.qop?.split(',').map((option) => option.trim()); + if (options && !options.includes('auth')) return; + return { + algorithm: params.algorithm, + nonce: params.nonce, + opaque: params.opaque, + qop: options ? 'auth' : undefined, + realm: params.realm, + }; +} + +function parseParam(input: string): { name: string; value: string } | undefined { + const match = /^(?[\w~-]+)=(?.*)$/u.exec(input); + if (!match) return; + const { name = '', value = '' } = match.groups ?? {}; + return { name: name.toLowerCase(), value: unquote(value.trim()) }; +} + +function unquote(value: string) { + if (value.length < 2 || !value.startsWith('"') || !value.endsWith('"')) return value; + return value.slice(1, -1).replaceAll(/\\(?.)/gu, '$'); +} + +// Splits on commas outside quoted strings, so values like qop="auth,auth-int" stay whole. +// Each match is a run of bare characters or complete quoted strings; commas fall between runs. +function splitUnquoted(header: string): Array { + return header.match(/(?:[^",]|"(?:[^"\\]|\\.)*")+/gu) ?? []; } diff --git a/packages/webdav/test/auth.test.ts b/packages/webdav/test/auth.test.ts new file mode 100644 index 00000000..eae8aa3c --- /dev/null +++ b/packages/webdav/test/auth.test.ts @@ -0,0 +1,276 @@ +import authorizationMiddleware from '@/webdav/auth'; +import { testKit } from '@hesprs/sync-engine-sdk/dev'; +import { beforeEach, expect, test } from 'bun:test'; +import { md5 } from 'hash-wasm'; +import { openMemoryDB } from 'uni-kv'; +import type { DigestInfo } from '@/webdav/auth'; +import type { + MaybePromise, + RequestParam, + RequestResponse, + StringKV, +} from '@hesprs/sync-engine-sdk'; + +const { request } = testKit; + +const credentials = { + endpoint: 'https://dav.example.com/dav', + password: 'secret', + username: 'alice', +}; +const realm = 'sync'; + +const CHALLENGE = + `Digest realm="${realm}", nonce="abc123", qop="auth,auth-int", ` + + 'opaque="opaque-token", algorithm=MD5'; + +const memoryDB = openMemoryDB< + Record, + { authMarker?: string; digest?: DigestInfo } +>('webdav-test'); + +type Control = (url: string, params: RequestParam) => MaybePromise>; + +beforeEach(() => { + memoryDB.setMeta('authMarker', undefined); + memoryDB.setMeta('digest', undefined); +}); + +function createAuthorization(control: Control, overrides: Partial = {}) { + const harness = request(control); + return { + calls: harness.calls, + request: authorizationMiddleware( + harness.request, + { ...credentials, ...overrides }, + memoryDB, + ), + }; +} + +function parseDirectives(authorization: string): StringKV { + const directives: StringKV = {}; + for (const segment of authorization.slice('Digest '.length).split(', ')) { + const index = segment.indexOf('='); + directives[segment.slice(0, index)] = segment.slice(index + 1).replaceAll(/^"|"$/gu, ''); + } + return directives; +} + +// RFC 7616: response = MD5(HA1:nonce[:nc:cnonce:qop]:HA2) with HA1/HA2 as below. +async function expectedResponse( + { cnonce, nc, nonce, qop }: StringKV, + { method, uri }: { method: string; uri: string }, +) { + const ha1 = await md5(`${credentials.username}:${realm}:${credentials.password}`); + const ha2 = await md5(`${method}:${uri}`); + if (qop) return md5(`${ha1}:${nonce}:${nc}:${cnonce}:${qop}:${ha2}`); + return md5(`${ha1}:${nonce}:${ha2}`); +} + +// First call gets the challenge, later calls succeed. +function challengeOnce(challenge: string = CHALLENGE): Control { + let challenged = false; + return () => { + if (challenged) return {}; + challenged = true; + return { headers: { 'www-authenticate': challenge }, status: 401 }; + }; +} + +test('sends Basic auth while the server accepts it', async () => { + const auth = createAuthorization(() => ({})); + const response = await auth.request('https://dav.example.com/dav/Notes/', { + method: 'PROPFIND', + }); + expect(response.status).toBe(200); + expect(auth.calls).toHaveLength(1); + expect(auth.calls[0]?.headers?.Authorization).toBe(`Basic ${btoa('alice:secret')}`); +}); + +test('retries with a Digest header built from the 401 challenge', async () => { + const auth = createAuthorization(challengeOnce()); + const response = await auth.request('https://dav.example.com/dav/Notes/file.md', { + method: 'PROPFIND', + }); + expect(response.status).toBe(200); + expect(auth.calls).toHaveLength(2); + expect(auth.calls[0]?.headers?.Authorization).toBe(`Basic ${btoa('alice:secret')}`); + const directives = parseDirectives(auth.calls[1]?.headers?.Authorization ?? ''); + expect(directives).toMatchObject({ + algorithm: 'MD5', + nc: '00000001', + nonce: 'abc123', + opaque: 'opaque-token', + qop: 'auth', + realm, + uri: '/dav/Notes/file.md', + username: 'alice', + }); + expect(directives.response).toBe( + await expectedResponse(directives, { method: 'PROPFIND', uri: '/dav/Notes/file.md' }), + ); + expect(memoryDB.getMeta('authMarker')).toBe(`${credentials.endpoint}~alice~secret`); + expect(memoryDB.getMeta('digest')).toMatchObject({ + ha1: await md5(`alice:${realm}:secret`), + nc: 1, + }); +}); + +test('keeps using Digest for later requests and increments the nonce count', async () => { + const auth = createAuthorization(challengeOnce()); + await auth.request('https://dav.example.com/dav/Notes/file.md', { method: 'GET' }); + const response = await auth.request('https://dav.example.com/dav/Other/file.md', { + method: 'PUT', + }); + expect(response.status).toBe(200); + expect(auth.calls).toHaveLength(3); + const directives = parseDirectives(auth.calls[2]?.headers?.Authorization ?? ''); + expect(directives.nc).toBe('00000002'); + expect(directives.nonce).toBe('abc123'); + expect(directives.uri).toBe('/dav/Other/file.md'); + expect(directives.response).toBe( + await expectedResponse(directives, { method: 'PUT', uri: '/dav/Other/file.md' }), + ); +}); + +test('draws distinct nonce counts for concurrent requests', async () => { + const auth = createAuthorization(challengeOnce()); + await auth.request('https://dav.example.com/dav/Notes/seed.md', { method: 'GET' }); + const [first, second] = await Promise.all([ + auth.request('https://dav.example.com/dav/Notes/a.md', { method: 'GET' }), + auth.request('https://dav.example.com/dav/Notes/b.md', { method: 'GET' }), + ]); + expect(first.status).toBe(200); + expect(second.status).toBe(200); + const counts = auth.calls + .slice(2) + .map((call) => parseDirectives(call.headers?.Authorization ?? '').nc) + .sort(); + expect(counts).toEqual(['00000002', '00000003']); +}); + +test('carries the Digest state across middleware instances through the memory DB', async () => { + const first = createAuthorization(challengeOnce()); + await first.request('https://dav.example.com/dav/Notes/file.md', { method: 'GET' }); + await first.request('https://dav.example.com/dav/Notes/other.md', { method: 'GET' }); + + // A fresh middleware instance (the store replaces the former in-closure state) goes straight to Digest. + const second = createAuthorization(() => ({})); + const response = await second.request('https://dav.example.com/dav/Notes/third.md', { + method: 'GET', + }); + expect(response.status).toBe(200); + expect(second.calls).toHaveLength(1); + const directives = parseDirectives(second.calls[0]?.headers?.Authorization ?? ''); + expect(directives.nonce).toBe('abc123'); + expect(directives.nc).toBe('00000003'); + expect(directives.response).toBe( + await expectedResponse(directives, { method: 'GET', uri: '/dav/Notes/third.md' }), + ); +}); + +test('falls back to Basic when the auth marker no longer matches the credentials', async () => { + const auth = createAuthorization(challengeOnce()); + await auth.request('https://dav.example.com/dav/Notes/file.md', { method: 'GET' }); + + const rotated = createAuthorization(() => ({}), { password: 'rotated' }); + const response = await rotated.request('https://dav.example.com/dav/Notes/file.md', { + method: 'GET', + }); + expect(response.status).toBe(200); + expect(rotated.calls).toHaveLength(1); + expect(rotated.calls[0]?.headers?.Authorization).toBe(`Basic ${btoa('alice:rotated')}`); + expect(memoryDB.getMeta('authMarker')).toBe(`${credentials.endpoint}~alice~secret`); +}); + +test('renews the stored challenge when the server re-challenges a Digest request', async () => { + let attempts = 0; + const auth = createAuthorization(() => { + attempts += 1; + // Attempt 1 rejects Basic with nonce abc123; attempt 3 rejects the stale abc123 with fresh99. + if (attempts !== 1 && attempts !== 3) return {}; + const nonce = attempts === 1 ? 'abc123' : 'fresh99'; + return { + headers: { + 'www-authenticate': `Digest realm="${realm}", nonce="${nonce}", qop="auth"`, + }, + status: 401, + }; + }); + const url = 'https://dav.example.com/dav/Notes/file.md'; + expect((await auth.request(url, { method: 'PROPFIND' })).status).toBe(200); + const second = await auth.request(url, { method: 'PROPFIND' }); + expect(second.status).toBe(200); + expect(auth.calls).toHaveLength(4); + const stale = parseDirectives(auth.calls[2]?.headers?.Authorization ?? ''); + const renewed = parseDirectives(auth.calls[3]?.headers?.Authorization ?? ''); + expect(stale.nonce).toBe('abc123'); + expect(renewed.nonce).toBe('fresh99'); + expect(renewed.nc).toBe('00000001'); + expect(renewed.response).toBe( + await expectedResponse(renewed, { method: 'PROPFIND', uri: '/dav/Notes/file.md' }), + ); +}); + +test('supports challenges without qop using the legacy response formula', async () => { + const auth = createAuthorization(challengeOnce(`Digest realm="${realm}", nonce="legacy"`)); + const response = await auth.request('https://dav.example.com/dav/Notes/', { method: 'GET' }); + expect(response.status).toBe(200); + expect(auth.calls).toHaveLength(2); + const directives = parseDirectives(auth.calls[1]?.headers?.Authorization ?? ''); + expect(directives.nonce).toBe('legacy'); + expect(directives.qop).toBeUndefined(); + expect(directives.nc).toBeUndefined(); + expect(directives.response).toBe( + await expectedResponse(directives, { method: 'GET', uri: '/dav/Notes/' }), + ); +}); + +test('parses the Digest challenge when the server offers Basic and Digest together', async () => { + const auth = createAuthorization( + challengeOnce( + `Basic realm="basic-realm", Digest realm="${realm}", nonce="abc123", qop="auth"`, + ), + ); + const response = await auth.request('https://dav.example.com/dav/Notes/', { + method: 'PROPFIND', + }); + expect(response.status).toBe(200); + expect(auth.calls).toHaveLength(2); + const directives = parseDirectives(auth.calls[1]?.headers?.Authorization ?? ''); + expect(directives.realm).toBe(realm); + expect(directives.nonce).toBe('abc123'); + expect(directives.response).toBe( + await expectedResponse(directives, { method: 'PROPFIND', uri: '/dav/Notes/' }), + ); +}); + +test('returns the 401 response when the challenge only offers Basic', async () => { + const auth = createAuthorization(() => ({ + headers: { 'www-authenticate': `Basic realm="${realm}"` }, + status: 401, + })); + const response = await auth.request('https://dav.example.com/dav/', { method: 'PROPFIND' }); + expect(response.status).toBe(401); + expect(auth.calls).toHaveLength(1); +}); + +test('returns the 401 response when the challenge requires an unsupported algorithm', async () => { + const auth = createAuthorization(() => ({ + headers: { + 'www-authenticate': `Digest realm="${realm}", nonce="abc123", algorithm=SHA-256, qop="auth"`, + }, + status: 401, + })); + const response = await auth.request('https://dav.example.com/dav/', { method: 'PROPFIND' }); + expect(response.status).toBe(401); + expect(auth.calls).toHaveLength(1); +}); + +test('returns 401 responses that carry no challenge header', async () => { + const auth = createAuthorization(() => ({ status: 401 })); + const response = await auth.request('https://dav.example.com/dav/', { method: 'PROPFIND' }); + expect(response.status).toBe(401); + expect(auth.calls).toHaveLength(1); +}); diff --git a/packages/webdav/tsdown.config.ts b/packages/webdav/tsdown.config.ts index 07fdb8f3..6babaae6 100644 --- a/packages/webdav/tsdown.config.ts +++ b/packages/webdav/tsdown.config.ts @@ -9,5 +9,7 @@ export default defineConfig({ minify: true, outExtensions: () => ({ js: '.js' }), outputOptions: { codeSplitting: false }, + platform: 'browser', plugins: [syncEngineModule(moduleCatalog)], + treeshake: { manualPureFunctions: ['Mutex'] }, // Removes the dead Mutexes in hash-wasm }); From 8c442122ca973e8aa17335baab8f0144cb6c1a7c Mon Sep 17 00:00:00 2001 From: hesprs <190185753+hesprs@users.noreply.github.com> Date: Fri, 13 Nov 2026 21:14:29 +0800 Subject: [PATCH 2/3] fix(gdrive&dropbox): reject missing account ID --- packages/dropbox/src/dropbox/auth.ts | 3 ++- .../dropbox/src/dropbox/check-connection.ts | 7 +++++- packages/dropbox/src/dropbox/fs.ts | 2 ++ packages/dropbox/src/index.ts | 22 ++++++++----------- packages/dropbox/src/setting.ts | 4 ++-- packages/dropbox/test/fs-dropbox.test.ts | 4 ++-- packages/gdrive/src/gdrive/auth.ts | 3 ++- .../gdrive/src/gdrive/check-connection.ts | 7 +++++- packages/gdrive/src/gdrive/fs.ts | 2 ++ packages/gdrive/src/gdrive/upload.ts | 4 ++-- packages/gdrive/src/index.ts | 17 +++++++------- packages/gdrive/src/setting.ts | 4 ++-- 12 files changed, 46 insertions(+), 33 deletions(-) diff --git a/packages/dropbox/src/dropbox/auth.ts b/packages/dropbox/src/dropbox/auth.ts index 9b39c1f8..a9b358ee 100644 --- a/packages/dropbox/src/dropbox/auth.ts +++ b/packages/dropbox/src/dropbox/auth.ts @@ -6,6 +6,7 @@ import { requestUrl } from 'obsidian'; import type { Binary, Request, StringKV } from '@hesprs/sync-engine-sdk'; import type { ObsidianProtocolData, SecretStorage } from 'obsidian'; +export const AUTH_ERROR_MESSAGE = 'Please authenticate the Dropbox account!'; export const APP_KEY = atob(process.env.DROPBOX_APP_KEY ?? ''); export const REDIRECT_URI = 'obsidian://sync-engine-dropbox-auth'; export const OAUTH_SCOPE = 'files.content.read files.content.write files.metadata.read'; @@ -134,7 +135,7 @@ export class TokenManager { private async refresh(): Promise { const refresh_token = this.getRefreshToken(); - if (!refresh_token) throw new Error('Please authorize the Dropbox account!'); + if (!refresh_token) throw new Error(AUTH_ERROR_MESSAGE); const response = await requestUrl({ body: formEncode({ client_id: APP_KEY, grant_type: 'refresh_token', refresh_token }), contentType: FORM_CONTENT_TYPE, diff --git a/packages/dropbox/src/dropbox/check-connection.ts b/packages/dropbox/src/dropbox/check-connection.ts index 14382542..6c98e2d0 100644 --- a/packages/dropbox/src/dropbox/check-connection.ts +++ b/packages/dropbox/src/dropbox/check-connection.ts @@ -1,9 +1,14 @@ import { rpc } from './api'; +import { AUTH_ERROR_MESSAGE } from './auth'; import { toError } from '@repo/shared/error'; import type { Request } from '@hesprs/sync-engine-sdk'; /** Validates the token by listing the app folder root, the lightest permission-honoring call. */ -export default async function checkConnection(request: Request): Promise { +export default async function checkConnection( + request: Request, + accountId: string, +): Promise { + if (!accountId) return new Error(AUTH_ERROR_MESSAGE); try { await rpc(request, '/2/files/list_folder', { path: '' }); } catch (error) { diff --git a/packages/dropbox/src/dropbox/fs.ts b/packages/dropbox/src/dropbox/fs.ts index cb8af53c..172c907e 100644 --- a/packages/dropbox/src/dropbox/fs.ts +++ b/packages/dropbox/src/dropbox/fs.ts @@ -12,6 +12,7 @@ import { uidOf, verifyEntries, } from './api'; +import { AUTH_ERROR_MESSAGE } from './auth'; import UploadSessions from './sessions'; import { SESSION_CHUNK_SIZE, appendSession, concurrentUploadSession, read2xx } from './upload'; import { chunkSize, concurrency } from '@hesprs/sync-engine-sdk'; @@ -89,6 +90,7 @@ export default class DropboxFs implements RootFs { private readonly request: Request, private readonly options: DropboxFsOptions, ) { + if (!options.accountId) throw new Error(AUTH_ERROR_MESSAGE); this.uploadSessions = new UploadSessions(request); } diff --git a/packages/dropbox/src/index.ts b/packages/dropbox/src/index.ts index 9b69f5aa..165ec827 100644 --- a/packages/dropbox/src/index.ts +++ b/packages/dropbox/src/index.ts @@ -64,6 +64,7 @@ export default class Dropbox { declare settings: Settings; readonly start = () => { + const { ctx, cleanup, tokenManager, pending, moduleSettings, settings } = this; const { translate, registerRemoteFs, @@ -74,38 +75,33 @@ export default class Dropbox { registerCss, registerObsidianProtocolHandler, } = this.ctx; - this.cleanup.push( + cleanup.push( registerCss(styles), registerRemoteFs('dropbox', { - checkConnection, - instantiate: (request) => new DropboxFs(request, this.moduleSettings), + checkConnection: (req) => checkConnection(req, moduleSettings.accountId), + instantiate: (request) => new DropboxFs(request, moduleSettings), prettyName: () => translate('dropbox'), }), registerRemoteFsWrapper({ apply: (fs) => { if (digOriginal(fs) instanceof DropboxFs) - return prefixWrapper(fs, this.moduleSettings.baseDirectory); + return prefixWrapper(fs, moduleSettings.baseDirectory); }, priority: 6418, }), registerRemoteRequestMiddleware({ apply: (request) => { - if (this.settings.remoteFs === 'dropbox') - return bearerMiddleware(request, this.tokenManager); + if (settings.remoteFs === 'dropbox') + return bearerMiddleware(request, tokenManager); }, priority: 306, }), registerRemoteOptimizer({ apply: dropboxOptimizer, priority: 3342 }), registerSetting({ - apply: dropboxSetting( - this.ctx as Context, - this.moduleSettings, - this.tokenManager, - this.pending, - ), + apply: dropboxSetting(ctx as Context, moduleSettings, tokenManager, pending), priority: 803, }), - registerObsidianProtocolHandler('sync-engine-dropbox-auth', this.pending.notify), + registerObsidianProtocolHandler('sync-engine-dropbox-auth', pending.notify), ); }; diff --git a/packages/dropbox/src/setting.ts b/packages/dropbox/src/setting.ts index 648b6505..5e6310a3 100644 --- a/packages/dropbox/src/setting.ts +++ b/packages/dropbox/src/setting.ts @@ -158,7 +158,7 @@ export default function dropboxSetting( .onClick(() => connectDropbox()), ); }, - visible: () => !tokenManager.getRefreshToken(), + visible: () => !settings.accountId || !tokenManager.getRefreshToken(), })), 1100: s(() => ({ desc: translate('connectSuccess'), @@ -179,7 +179,7 @@ export default function dropboxSetting( }), ); }, - visible: () => Boolean(tokenManager.getRefreshToken()), + visible: () => Boolean(tokenManager.getRefreshToken() && settings.accountId), })), 2000: s(() => ({ desc: translate('baseDirectoryDescription'), diff --git a/packages/dropbox/test/fs-dropbox.test.ts b/packages/dropbox/test/fs-dropbox.test.ts index 1c79f689..00d0b284 100644 --- a/packages/dropbox/test/fs-dropbox.test.ts +++ b/packages/dropbox/test/fs-dropbox.test.ts @@ -1128,7 +1128,7 @@ test('the commit-ready callback reports ready writes until cleared', async () => test('checkConnection validates the token through a root listing', async () => { const failing = createFs(() => json({ error: { '.tag': 'invalid_access_token' } }, 401)); - const failure = await checkConnection(failing.request); + const failure = await checkConnection(failing.request, 'id'); expect(failure).toBeInstanceOf(Error); expect(String(failure)).toContain('invalid_access_token'); @@ -1136,5 +1136,5 @@ test('checkConnection validates the token through a root listing', async () => { expect(url).toBe(`${API_RPC}/2/files/list_folder`); return json({ cursor: '', entries: [], has_more: false }); }); - expect(await checkConnection(passing.request)).toBeUndefined(); + expect(await checkConnection(passing.request, 'id')).toBeUndefined(); }); diff --git a/packages/gdrive/src/gdrive/auth.ts b/packages/gdrive/src/gdrive/auth.ts index eaea7e97..b75315ce 100644 --- a/packages/gdrive/src/gdrive/auth.ts +++ b/packages/gdrive/src/gdrive/auth.ts @@ -10,6 +10,7 @@ import { getStatus } from '@repo/shared/error'; import { Platform, requestUrl, SecretStorage } from 'obsidian'; import type { Request, StringKV } from '@hesprs/sync-engine-sdk'; +export const AUTH_ERROR_MESSAGE = 'Please authenticate the Google Account!'; export const CLIENT_ID = atob(process.env.CLIENT_ID ?? ''); export const CLIENT_SECRET = atob(process.env.CLIENT_SECRET ?? ''); // Not really a secret const KEYCHAIN_SECRET_ID = 'sync-engine-gdrive-refresh-token'; // Secret storage id under which the Google refresh token is stored. @@ -218,7 +219,7 @@ export class TokenManager { private async refresh(): Promise { const refresh_token = this.getRefreshToken(); - if (!refresh_token) throw new Error('Please authorize Google Account!'); + if (!refresh_token) throw new Error(AUTH_ERROR_MESSAGE); const response = await requestUrl({ body: formEncode({ client_id: CLIENT_ID, diff --git a/packages/gdrive/src/gdrive/check-connection.ts b/packages/gdrive/src/gdrive/check-connection.ts index 6be7114a..e3cfd414 100644 --- a/packages/gdrive/src/gdrive/check-connection.ts +++ b/packages/gdrive/src/gdrive/check-connection.ts @@ -1,8 +1,13 @@ import { DRIVE_API, buildUrl, parseDriveError } from './api'; +import { AUTH_ERROR_MESSAGE } from './auth'; import { toError } from '@repo/shared/error'; import type { Request } from '@hesprs/sync-engine-sdk'; -export default async function checkConnection(request: Request): Promise { +export default async function checkConnection( + request: Request, + userId: string, +): Promise { + if (!userId) return new Error(AUTH_ERROR_MESSAGE); try { const response = await request(buildUrl(DRIVE_API, '/about', { fields: 'storageQuota' }), { method: 'GET', diff --git a/packages/gdrive/src/gdrive/fs.ts b/packages/gdrive/src/gdrive/fs.ts index a8027436..59932412 100644 --- a/packages/gdrive/src/gdrive/fs.ts +++ b/packages/gdrive/src/gdrive/fs.ts @@ -8,6 +8,7 @@ import { parseDriveError, toStat, } from './api'; +import { AUTH_ERROR_MESSAGE } from './auth'; import { guessMimeType, resumableUpload, singleUpload } from './upload'; import { chunkSize, concurrency } from '@hesprs/sync-engine-sdk'; import { textToUint8Array } from '@repo/shared/binary'; @@ -62,6 +63,7 @@ export default class GdriveFs implements RootFs { private readonly options: GdriveFsOptions, memoryDB: GdriveDB, ) { + if (!options.userId) throw new Error(AUTH_ERROR_MESSAGE); this.ids = memoryDB.getStore('gdriveIds'); if (memoryDB.getMeta('gdriveIdsMarker') !== this.getUid()) { this.ids.clear(); diff --git a/packages/gdrive/src/gdrive/upload.ts b/packages/gdrive/src/gdrive/upload.ts index 746a3a43..86cb67bf 100644 --- a/packages/gdrive/src/gdrive/upload.ts +++ b/packages/gdrive/src/gdrive/upload.ts @@ -1,12 +1,12 @@ import { parseDriveError } from './api'; import { concatBinary, PartBuffer, textToUint8Array } from '@repo/shared/binary'; import type { DriveFile } from './api'; -import type { Binary, Request, RequestResponse, StringKV } from '@hesprs/sync-engine-sdk'; +import type { Binary, Request, RequestResponse } from '@hesprs/sync-engine-sdk'; // Resumable uploads must be sequential (Drive rejects chunks that skip ahead of the uploaded size), so the SDK's memory-tuned chunk size does not apply here. const GDRIVE_CHUNK_SIZE = 8 * 1024 ** 2; -const MIME_BY_EXTENSION: Partial = { +const MIME_BY_EXTENSION: Dict = { base: 'text/yaml', canvas: 'application/json', css: 'text/css', diff --git a/packages/gdrive/src/index.ts b/packages/gdrive/src/index.ts index 79104259..bd615e1d 100644 --- a/packages/gdrive/src/index.ts +++ b/packages/gdrive/src/index.ts @@ -55,6 +55,7 @@ export default class Gdrive { declare settings: Settings; readonly start = () => { + const { moduleSettings, ctx, cleanup, settings, tokenManager } = this; const { translate, registerRemoteFs, @@ -63,30 +64,30 @@ export default class Gdrive { registerRemoteRequestMiddleware, registerSetting, registerCss, - } = this.ctx; - this.cleanup.push( + } = ctx; + cleanup.push( registerCss(styles), registerRemoteFs('gdrive', { - checkConnection, - instantiate: (request) => new GdriveFs(request, this.moduleSettings, memoryDB), + checkConnection: (req) => checkConnection(req, moduleSettings.userId), + instantiate: (request) => new GdriveFs(request, moduleSettings, memoryDB), prettyName: () => translate('gdrive'), }), registerRemoteFsWrapper({ apply: (fs) => { if (digOriginal(fs) instanceof GdriveFs) - return prefixWrapper(fs, this.moduleSettings.baseDirectory); + return prefixWrapper(fs, moduleSettings.baseDirectory); }, priority: 5998, }), registerRemoteRequestMiddleware({ apply: (request) => { - if (this.settings.remoteFs === 'gdrive') - return bearerMiddleware(request, this.tokenManager); + if (settings.remoteFs === 'gdrive') + return bearerMiddleware(request, tokenManager); }, priority: 305, }), registerSetting({ - apply: gdriveSetting(this.ctx as Context, this.moduleSettings, this.tokenManager), + apply: gdriveSetting(ctx as Context, moduleSettings, tokenManager), priority: 683, }), ); diff --git a/packages/gdrive/src/setting.ts b/packages/gdrive/src/setting.ts index 003db8e9..482d7ed9 100644 --- a/packages/gdrive/src/setting.ts +++ b/packages/gdrive/src/setting.ts @@ -168,7 +168,7 @@ export default function gdriveSetting( ), ); }, - visible: () => !tokenManager.getRefreshToken(), + visible: () => !settings.userId || !tokenManager.getRefreshToken(), })), 1100: s(() => ({ desc: translate('connectSuccess'), @@ -190,7 +190,7 @@ export default function gdriveSetting( }), ); }, - visible: () => Boolean(tokenManager.getRefreshToken()), + visible: () => Boolean(tokenManager.getRefreshToken() && settings.userId), })), 2000: s(() => ({ desc: translate('baseDirectoryDescription'), From 2c8a95b6387df074f05e756c087afd193abd3738 Mon Sep 17 00:00:00 2001 From: hesprs <190185753+hesprs@users.noreply.github.com> Date: Fri, 13 Nov 2026 22:37:44 +0800 Subject: [PATCH 3/3] feat(module editor): edit module versions --- CHANGELOG.md | 31 +++++ manifest.json | 2 +- modules.json | 2 +- packages/i18n/src/ru/translations.ts | 4 + packages/i18n/src/zh-TW/translations.ts | 3 + packages/i18n/src/zh/translations.ts | 3 + packages/plugin/dist/dev.spec.d.ts | 2 +- ...rzR.spec.d.ts => index-CepCHOJ3.spec.d.ts} | 5 +- packages/plugin/dist/index.spec.d.ts | 2 +- packages/plugin/package.json | 2 +- .../src/components/ModuleEditorModal.ts | 123 ++++++++++-------- packages/plugin/src/en.ts | 4 + packages/plugin/src/modules/I18n.ts | 7 +- versions.json | 3 +- 14 files changed, 125 insertions(+), 68 deletions(-) rename packages/plugin/dist/{index-CgW2TrzR.spec.d.ts => index-CepCHOJ3.spec.d.ts} (99%) diff --git a/CHANGELOG.md b/CHANGELOG.md index 949656ed..6f606775 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,37 @@ All notable changes to this project will be documented in this file. +## Sync Engine v3.4.2 - 2026-11-13 + +### Core + +- Supported editing module version in the module editor. +- Fixed the bug that causes module update button to never show when auto-update is disabled. +- Added module management menu item to manually refresh sources. +- Add a loading indicator when module sources are being loaded. +- Ensured network response headers are always normalized to lowercase. + +### WebDAV Module + +- Implemented support for digest authorization and automatic digest authorization detection. + +### Google Drive Module + +- Fixed the bug that when base directory is `/`, sync planning reports to delete all local files after upload. +- Missing account ID is now treated as not authenticated to prevent mysterious record mismatch and decryption error. + +### Rclone S3 Timestamp Module + +- Implement the module to transform `x-amz-meta-mtime` header to second precision to make Rclone parse and apply modification time to server files. + +### Dropbox Module + +- Missing account ID is now treated as not authenticated to prevent mysterious record mismatch and decryption error. + +### Contributors + +@alan16742, @hesprs + ## Sync Engine v3.4.1 - 2026-11-08 ### Core diff --git a/manifest.json b/manifest.json index b840b47a..e643d813 100644 --- a/manifest.json +++ b/manifest.json @@ -1,7 +1,7 @@ { "id": "sync-engine", "name": "Sync Engine", - "version": "3.4.1", + "version": "3.4.2", "minAppVersion": "1.13.0", "authorUrl": "https://hesprs.github.io", "description": "The extensible vault synchronization engine: Fast · Free · Reliable. Supports WebDAV, S3, Google Drive, and Dropbox.", diff --git a/modules.json b/modules.json index b242bfc5..a1b78daf 100644 --- a/modules.json +++ b/modules.json @@ -32,7 +32,7 @@ { "id": "dropbox", "name": "Dropbox", - "version": "0.1.0", + "version": "0.1.1", "description": "[Beta] Dropbox backend support.", "icon": "server", "main": "https://sync.consensia.cc/modules/dropbox.js", diff --git a/packages/i18n/src/ru/translations.ts b/packages/i18n/src/ru/translations.ts index 8f468c0e..216d42dd 100644 --- a/packages/i18n/src/ru/translations.ts +++ b/packages/i18n/src/ru/translations.ts @@ -387,6 +387,10 @@ const ru: Translations = { updateModule: 'Обновить модуль', updatePlaceholder: 'https://example.com/modules.json', upload: 'Загрузить', + version: 'Версия', + versionDescription: + 'Укажите версию модуля, используемую при сравнении обновлений и отображении в карточке модуля.', + versionPlaceholder: 'Введите версию (например, 0.0.1)', walkingRemote: 'Сканирование удалённых файлов', writeCode: 'Написать код', writeCodeDescription: 'Напишите код своего модуля здесь на JavaScript', diff --git a/packages/i18n/src/zh-TW/translations.ts b/packages/i18n/src/zh-TW/translations.ts index 90435848..2fe87120 100644 --- a/packages/i18n/src/zh-TW/translations.ts +++ b/packages/i18n/src/zh-TW/translations.ts @@ -337,6 +337,9 @@ const zhTW: Translations = { updateModule: '更新模組', updatePlaceholder: 'https://example.com/modules.json', upload: '上傳', + version: '版本', + versionDescription: '設定用於更新比較與模組卡片顯示的模組版本。', + versionPlaceholder: '輸入版本(例如 0.0.1)', walkingRemote: '正在掃描遠端檔案', writeCode: '撰寫程式碼', writeCodeDescription: '在此處以 JavaScript 撰寫您的模組程式碼', diff --git a/packages/i18n/src/zh/translations.ts b/packages/i18n/src/zh/translations.ts index af1a2c70..3e00f12c 100644 --- a/packages/i18n/src/zh/translations.ts +++ b/packages/i18n/src/zh/translations.ts @@ -336,6 +336,9 @@ const zh: Translations = { updateModule: '更新模块', updatePlaceholder: 'https://example.com/modules.json', upload: '上传', + version: '版本', + versionDescription: '设置用于更新比较和模块卡片显示的模块版本。', + versionPlaceholder: '输入版本(例如 0.0.1)', walkingRemote: '正在探测远程文件', writeCode: '编写代码', writeCodeDescription: '在此处使用 JavaScript 编写您的模块代码', diff --git a/packages/plugin/dist/dev.spec.d.ts b/packages/plugin/dist/dev.spec.d.ts index 7a3719f2..7376ae6a 100644 --- a/packages/plugin/dist/dev.spec.d.ts +++ b/packages/plugin/dist/dev.spec.d.ts @@ -1,4 +1,4 @@ -import { Bt as Binary, Ft as RecordStat, It as RecordStatsMap, K as TaskNames, Lt as Stat, Mt as FolderStat, Nt as MaybePromise, Ot as RootFs, Rt as StatsMap, d as RequestResponse, jt as FileStat, kt as WrappedFs, l as Request, u as RequestParam, yt as Fs, z as Decider, zt as StringKV } from "./index-CgW2TrzR.spec.js"; +import { Bt as Binary, Ft as RecordStat, It as RecordStatsMap, K as TaskNames, Lt as Stat, Mt as FolderStat, Nt as MaybePromise, Ot as RootFs, Rt as StatsMap, d as RequestResponse, jt as FileStat, kt as WrappedFs, l as Request, u as RequestParam, yt as Fs, z as Decider, zt as StringKV } from "./index-CepCHOJ3.spec.js"; declare function debugWrapper(original: Fs, log: (content: string) => void): WrappedFs; type FsCalls = { delete: Array; diff --git a/packages/plugin/dist/index-CgW2TrzR.spec.d.ts b/packages/plugin/dist/index-CepCHOJ3.spec.d.ts similarity index 99% rename from packages/plugin/dist/index-CgW2TrzR.spec.d.ts rename to packages/plugin/dist/index-CepCHOJ3.spec.d.ts index 5401d62c..5d2e3bb6 100644 --- a/packages/plugin/dist/index-CgW2TrzR.spec.d.ts +++ b/packages/plugin/dist/index-CepCHOJ3.spec.d.ts @@ -231,7 +231,7 @@ type TranslateParams = R extends Factory ? type Translate = (key: K, ...arg: TranslateParams) => O[K] extends string | Snippet ? string : DocumentFragment; declare class I18n { private readonly targetLangs; - readonly i18n: {}; + readonly i18n: TranslationResource; private readonly registerI18n; private readonly translate; root: { @@ -813,6 +813,9 @@ type ModuleEditorTranslations = { readmePage: string; readmePageDescription: string; readmePagePlaceholder: string; + version: string; + versionDescription: string; + versionPlaceholder: string; }; type ModulesTranslations = ModuleEditorTranslations & ModuleManagementTranslations & CodeInputTranslations; type CustomHeaders = Array<{ diff --git a/packages/plugin/dist/index.spec.d.ts b/packages/plugin/dist/index.spec.d.ts index 5c2f6a3d..c902883a 100644 --- a/packages/plugin/dist/index.spec.d.ts +++ b/packages/plugin/dist/index.spec.d.ts @@ -1,2 +1,2 @@ -import { $ as MoveLocal, A as setNeedMigration, At as WriteAtom, B as DeciderInput, Bt as Binary, C as REGRET_ERROR_MESSAGE, Ct as MkdirAtom, D as readWithSize, Dt as OutputAtom, E as pipe, Et as OptimizerOutput, F as CallableOrObjectTree, Ft as RecordStat, G as Task, H as AddRecord, I as SettingEntry, It as RecordStatsMap, J as ResolveConflict, K as TaskNames, L as AugmentedModuleMeta, Lt as Stat, M as generateEditableList, Mt as FolderStat, N as reactivelyValidate, Nt as MaybePromise, O as writeWithSize, Ot as RootFs, P as settingEntry, Pt as Progress, Q as MoveRemote, R as ModuleMeta, Rt as StatsMap, S as digOriginal, St as ListReporter, T as concurrency, Tt as OptimizerInput, U as ConflictResolver, V as TaskFactory, W as ConflictResolverPayload, X as RemoveRecord, Y as RemoveRemote, Z as RemoveLocal, _ as Events, _t as CustomAtom, a as LocalRequestMiddlewareEntry, at as ObsidianLanguageCode, b as ExistingMemoryDB, bt as InputAtom, c as RemoteRequestMiddlewareEntry, ct as TranslationResource, d as RequestResponse, dt as DatabaseAsync, et as Download, f as TriggerEntry, ft as DatabaseSync, g as Context, gt as BatchOptimizer, h as SyncTerminateReason, ht as StoreSync, i as FsWrapperEntry, it as Fragment, j as LabelDefinition, jt as FileStat, k as prefixWrapper, kt as WrappedFs, l as Request, lt as Dispatch, m as SyncOptions, mt as StoreOperations, n as ConflictResolverEntry, nt as CreateLocalDir, o as OptimizerEntry, ot as Snippet, p as RemoteLister, pt as StoreAsync, q as Upload, r as DeciderEntry, rt as RecordStore, s as RemoteFsEntry, st as Translate, t as VaultRequest, tt as CreateRemoteDir, u as RequestParam, ut as On, v as Settings, vt as DeleteAtom, w as chunkSize, wt as MoveAtom, x as SelectFromContext, xt as ListOptions, y as Translations, yt as Fs, z as Decider, zt as StringKV } from "./index-CgW2TrzR.spec.js"; +import { $ as MoveLocal, A as setNeedMigration, At as WriteAtom, B as DeciderInput, Bt as Binary, C as REGRET_ERROR_MESSAGE, Ct as MkdirAtom, D as readWithSize, Dt as OutputAtom, E as pipe, Et as OptimizerOutput, F as CallableOrObjectTree, Ft as RecordStat, G as Task, H as AddRecord, I as SettingEntry, It as RecordStatsMap, J as ResolveConflict, K as TaskNames, L as AugmentedModuleMeta, Lt as Stat, M as generateEditableList, Mt as FolderStat, N as reactivelyValidate, Nt as MaybePromise, O as writeWithSize, Ot as RootFs, P as settingEntry, Pt as Progress, Q as MoveRemote, R as ModuleMeta, Rt as StatsMap, S as digOriginal, St as ListReporter, T as concurrency, Tt as OptimizerInput, U as ConflictResolver, V as TaskFactory, W as ConflictResolverPayload, X as RemoveRecord, Y as RemoveRemote, Z as RemoveLocal, _ as Events, _t as CustomAtom, a as LocalRequestMiddlewareEntry, at as ObsidianLanguageCode, b as ExistingMemoryDB, bt as InputAtom, c as RemoteRequestMiddlewareEntry, ct as TranslationResource, d as RequestResponse, dt as DatabaseAsync, et as Download, f as TriggerEntry, ft as DatabaseSync, g as Context, gt as BatchOptimizer, h as SyncTerminateReason, ht as StoreSync, i as FsWrapperEntry, it as Fragment, j as LabelDefinition, jt as FileStat, k as prefixWrapper, kt as WrappedFs, l as Request, lt as Dispatch, m as SyncOptions, mt as StoreOperations, n as ConflictResolverEntry, nt as CreateLocalDir, o as OptimizerEntry, ot as Snippet, p as RemoteLister, pt as StoreAsync, q as Upload, r as DeciderEntry, rt as RecordStore, s as RemoteFsEntry, st as Translate, t as VaultRequest, tt as CreateRemoteDir, u as RequestParam, ut as On, v as Settings, vt as DeleteAtom, w as chunkSize, wt as MoveAtom, x as SelectFromContext, xt as ListOptions, y as Translations, yt as Fs, z as Decider, zt as StringKV } from "./index-CepCHOJ3.spec.js"; export { type AddRecord, type AugmentedModuleMeta, type BatchOptimizer, type Binary, type CallableOrObjectTree, type ConflictResolver, type ConflictResolverEntry, type ConflictResolverPayload, type Context, type CreateLocalDir, type CreateRemoteDir, type CustomAtom, type DatabaseAsync, type DatabaseSync, type Decider, type DeciderEntry, type DeciderInput, type DeleteAtom, type Dispatch, type Download, type Events, type ExistingMemoryDB, type FileStat, type FolderStat, type Fragment, type Fs, type FsWrapperEntry, type InputAtom, type LabelDefinition, type ListOptions, type ListReporter, type LocalRequestMiddlewareEntry, type MaybePromise, type MkdirAtom, type ModuleMeta, type MoveAtom, type MoveLocal, type MoveRemote, type ObsidianLanguageCode, type On, type OptimizerEntry, type OptimizerInput, type OptimizerOutput, type OutputAtom, type Progress, REGRET_ERROR_MESSAGE, type RecordStat, type RecordStatsMap, type RecordStore, type RemoteFsEntry, type RemoteLister, type RemoteRequestMiddlewareEntry, type RemoveLocal, type RemoveRecord, type RemoveRemote, type Request, type RequestParam, type RequestResponse, type ResolveConflict, type RootFs, SelectFromContext, type SettingEntry, type Settings, type Snippet, type Stat, type StatsMap, type StoreAsync, type StoreOperations, type StoreSync, type StringKV, type SyncOptions, type SyncTerminateReason, type Task, type TaskFactory, type TaskNames, type Translate, type TranslationResource, type Translations, type TriggerEntry, type Upload, type VaultRequest, type WrappedFs, type WriteAtom, chunkSize, concurrency, digOriginal, generateEditableList, pipe, prefixWrapper, reactivelyValidate, readWithSize, setNeedMigration, settingEntry, writeWithSize }; \ No newline at end of file diff --git a/packages/plugin/package.json b/packages/plugin/package.json index b96ace37..e890fd40 100644 --- a/packages/plugin/package.json +++ b/packages/plugin/package.json @@ -1,6 +1,6 @@ { "name": "@hesprs/sync-engine-sdk", - "version": "3.4.1", + "version": "3.4.2", "description": "Official SDK for developing modules targeting Sync Engine, the extensible Obsidian syncing plugin.", "keywords": [ "obsidian-plugin", diff --git a/packages/plugin/src/components/ModuleEditorModal.ts b/packages/plugin/src/components/ModuleEditorModal.ts index 4e14eda6..abdc3049 100644 --- a/packages/plugin/src/components/ModuleEditorModal.ts +++ b/packages/plugin/src/components/ModuleEditorModal.ts @@ -1,7 +1,7 @@ import { reactivelyValidate } from '@/settings/utils'; import sha256 from '@/utils/sha-256'; import { formatUrl, parseUrl } from '@repo/shared/path'; -import { App, Modal, Setting } from 'obsidian'; +import { App, Modal, Setting, TextAreaComponent, TextComponent } from 'obsidian'; import type { AugmentedModuleMeta } from '@/modules/Extensibility'; import type { Fragment, Translate } from '@/modules/I18n'; import type { MaybePromise, StringKV } from '@/types'; @@ -29,6 +29,9 @@ export type ModuleEditorTranslations = { readmePage: string; readmePageDescription: string; readmePagePlaceholder: string; + version: string; + versionDescription: string; + versionPlaceholder: string; }; export default class ModuleEditorModal extends Modal { @@ -81,6 +84,29 @@ export default class ModuleEditorModal extends Modal { let integrityEnabled = integrity !== ''; this.setTitle(translate('editModuleInformation')); + const saveOnBlur = ( + text: TextComponent | TextAreaComponent, + key: 'name' | 'description' | 'version' | 'icon', + ) => + text.inputEl.addEventListener('blur', () => { + const trimmed = text.getValue().trim(); + text.setValue(trimmed); + updated[key] = trimmed; + }); + const validateUrl = (text: TextComponent, key: 'readme' | 'source') => + reactivelyValidate({ + format: formatUrl, + onSave: (value) => (updated[key] = value), + parse: (value) => { + if (!value.trim()) return ''; + try { + return parseUrl(value); + } catch { + // Return undefined + } + }, + text, + }); new Setting(this.contentEl) .setName(translate('enable')) @@ -93,27 +119,33 @@ export default class ModuleEditorModal extends Modal { .setName(translate('name')) .setDesc(translate('nameDescription')) .addText((text) => - text - .setValue(updated.name) - .setPlaceholder(translate('namePlaceholder')) - .inputEl.addEventListener('blur', () => { - const trimmed = text.getValue().trim(); - text.setValue(trimmed); - updated.name = trimmed; - }), + saveOnBlur( + text.setValue(updated.name).setPlaceholder(translate('namePlaceholder')), + 'name', + ), ); new Setting(this.contentEl) .setName(translate('description')) .setDesc(translate('descriptionDescription')) .addTextArea((text) => { - text.setValue(updated.description) - .setPlaceholder(translate('descriptionPlaceholder')) - .inputEl.addEventListener('blur', () => { - const trimmed = text.getValue().trim(); - text.setValue(trimmed); - updated.description = trimmed; - }); + saveOnBlur( + text + .setValue(updated.description) + .setPlaceholder(translate('descriptionPlaceholder')), + 'description', + ); + text.inputEl.addClass('min-w-100%'); + }); + + new Setting(this.contentEl) + .setName(translate('version')) + .setDesc(translate('versionDescription')) + .addText((text) => { + saveOnBlur( + text.setValue(updated.version).setPlaceholder(translate('versionPlaceholder')), + 'version', + ); text.inputEl.addClass('min-w-100%'); }); @@ -121,56 +153,33 @@ export default class ModuleEditorModal extends Modal { .setName(translate('icon')) .setDesc(translate('iconDescription')) .addText((text) => - text - .setValue(updated.icon) - .setPlaceholder(translate('iconPlaceholder')) - .inputEl.addEventListener('blur', () => { - const trimmed = text.getValue().trim(); - text.setValue(trimmed); - updated.icon = trimmed; - }), + saveOnBlur( + text.setValue(updated.icon).setPlaceholder(translate('iconPlaceholder')), + 'icon', + ), ); new Setting(this.contentEl) .setName(translate('update')) .setDesc(translate('updateDescription')) - .addText((text) => { - text.setPlaceholder(translate('updatePlaceholder')).setValue(updated.source); - reactivelyValidate({ - onSave: (value) => (updated.source = value), - parse: (value) => { - if (!value.trim()) return ''; - try { - return parseUrl(value); - } catch { - // Return undefined - } - }, - text, - }); - }); + .addText((text) => + validateUrl( + text.setPlaceholder(translate('updatePlaceholder')).setValue(updated.source), + 'source', + ), + ); new Setting(this.contentEl) .setName(translate('readmePage')) .setDesc(translate('readmePageDescription')) - .addText((text) => { - text.setValue(formatUrl(updated.readme ?? '')).setPlaceholder( - translate('readmePagePlaceholder'), - ); - reactivelyValidate({ - format: formatUrl, - onSave: (value) => (updated.source = value), - parse: (value) => { - if (!value.trim()) return ''; - try { - return parseUrl(value); - } catch { - // Return undefined - } - }, - text, - }); - }); + .addText((text) => + validateUrl( + text + .setValue(formatUrl(updated.readme ?? '')) + .setPlaceholder(translate('readmePagePlaceholder')), + 'readme', + ), + ); new Setting(this.contentEl) .setName(translate('integrityVerification')) diff --git a/packages/plugin/src/en.ts b/packages/plugin/src/en.ts index 9c54de83..99031baa 100644 --- a/packages/plugin/src/en.ts +++ b/packages/plugin/src/en.ts @@ -375,6 +375,10 @@ const en: Translations = { updateModule: 'Update module', updatePlaceholder: 'https://example.com/modules.json', upload: 'Upload', + version: 'Version', + versionDescription: + 'Set the version of the module used in update comparison and module card display.', + versionPlaceholder: 'Enter version (e.g. 0.0.1)', walkingRemote: 'Discovering remote files', writeCode: 'Write code', writeCodeDescription: 'Write your module code here as JavaScript', diff --git a/packages/plugin/src/modules/I18n.ts b/packages/plugin/src/modules/I18n.ts index cb971e71..36e5341b 100644 --- a/packages/plugin/src/modules/I18n.ts +++ b/packages/plugin/src/modules/I18n.ts @@ -99,17 +99,16 @@ export default class I18n { getLanguage(), getLanguage().split('-')[0], ] as Array); - readonly i18n = {}; + readonly i18n: TranslationResource = {}; private readonly registerI18n = (code: ObsidianLanguageCode, resource: TranslationResource) => { if (code === DEFAULT_LANGUAGE && !this.targetLangs.has(DEFAULT_LANGUAGE)) - for (const [key, value] of Object.entries(resource)) - (this.i18n as TranslationResource)[key] ??= value; + for (const [key, value] of Object.entries(resource)) this.i18n[key] ??= value; else if (this.targetLangs.has(code)) Object.assign(this.i18n, resource); }; private readonly translate = ((key: string, arg: unknown) => { - const value = (this.i18n as TranslationResource)[key]; + const value = this.i18n[key]; if (typeof value === 'string') return value; // Handle missing keys and argument mismatch due to stale i18n modules try { diff --git a/versions.json b/versions.json index 998497a0..68c38bd5 100644 --- a/versions.json +++ b/versions.json @@ -23,5 +23,6 @@ "3.3.3": "1.13.0", "3.3.4": "1.13.0", "3.4.0": "1.13.0", - "3.4.1": "1.13.0" + "3.4.1": "1.13.0", + "3.4.2": "1.13.0" }