📧✨ Beautiful email. For everyone.
feat: initial commit
Paul Koeck67cff3f1a7ef
diff --git a/.claude/launch.json b/.claude/launch.jsonnew file mode 100644index 0000000..ff0c825--- /dev/null+++ b/.claude/launch.json@@ -0,0 +1,11 @@+{+ "version": "0.0.1",+ "configurations": [+ {+ "name": "inlark-web",+ "runtimeExecutable": "pnpm",+ "runtimeArgs": ["dev:web"],+ "port": 5173+ }+ ]+}diff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlnew file mode 100644index 0000000..255fadf--- /dev/null+++ b/.github/workflows/release.yml@@ -0,0 +1,134 @@+name: Release desktop app++on:+ push:+ tags:+ - 'v*'++permissions:+ contents: read++concurrency:+ group: release-${{ github.ref }}+ cancel-in-progress: false++jobs:+ validate-tag:+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v7+ - name: Check tag against desktop version+ shell: bash+ run: |+ node -e 'const version = require("./apps/desktop/package.json").version; const tag = process.env.GITHUB_REF_NAME; if (tag !== "v" + version) { console.error("Expected tag v" + version + ", got " + tag); process.exit(1) }'++ build:+ needs: validate-tag+ strategy:+ fail-fast: false+ matrix:+ include:+ - runner: ubuntu-24.04+ name: linux-x64+ args: --linux AppImage deb rpm --x64+ expected: 3+ - runner: windows-2025+ name: windows-x64+ args: --win nsis --x64+ expected: 1+ - runner: macos-15-intel+ name: macos-x64+ args: --mac dmg zip --x64+ expected: 2+ - runner: macos-15+ name: macos-arm64+ args: --mac dmg zip --arm64+ expected: 2+ runs-on: ${{ matrix.runner }}+ env:+ CSC_IDENTITY_AUTO_DISCOVERY: 'false'+ steps:+ - uses: actions/checkout@v7+ - uses: actions/setup-node@v7+ with:+ node-version: '24'+ - uses: pnpm/action-setup@v6+ with:+ run_install: false+ - name: Install dependencies+ run: pnpm install --frozen-lockfile+ - name: Install RPM packaging tools+ if: runner.os == 'Linux'+ run: sudo apt-get update && sudo apt-get install -y rpm+ - name: Build desktop app+ run: pnpm build+ - name: Package desktop app+ run: pnpm --filter @inlark/desktop exec electron-builder ${{ matrix.args }} --publish never+ - name: Collect installers+ shell: bash+ run: |+ mkdir release-assets+ for file in apps/desktop/release/*; do+ case "$file" in+ *.AppImage|*.deb|*.rpm|*.exe|*.dmg|*.zip) cp "$file" release-assets/ ;;+ esac+ done+ count=$(find release-assets -type f | wc -l)+ expected=${{ matrix.expected }}+ if [ "$count" -ne "$expected" ]; then+ echo "Expected $expected installers, found $count" >&2+ exit 1+ fi+ ls -lh release-assets+ - uses: actions/upload-artifact@v7+ with:+ name: desktop-${{ matrix.name }}+ path: release-assets/+ if-no-files-found: error++ nix:+ needs: validate-tag+ runs-on: ubuntu-24.04+ steps:+ - uses: actions/checkout@v7+ - uses: cachix/install-nix-action@v31+ with:+ github_access_token: ${{ github.token }}+ - name: Check flake and build Nix package+ run: nix flake check --no-write-lock-file+ - name: Check profile installation+ run: |+ nix profile install --profile "$RUNNER_TEMP/inlark-profile" .#inlark+ test -x "$RUNNER_TEMP/inlark-profile/bin/inlark"+ test -f "$RUNNER_TEMP/inlark-profile/share/applications/inlark.desktop"+ test -f "$RUNNER_TEMP/inlark-profile/share/icons/hicolor/512x512/apps/inlark.png"++ release:+ needs: [build, nix]+ runs-on: ubuntu-latest+ permissions:+ contents: write+ steps:+ - uses: actions/download-artifact@v7+ with:+ pattern: desktop-*+ path: release-assets+ merge-multiple: true+ - name: Publish GitHub Release+ shell: bash+ env:+ GH_TOKEN: ${{ github.token }}+ GH_REPO: ${{ github.repository }}+ RELEASE_TAG: ${{ github.ref_name }}+ run: |+ count=$(find release-assets -maxdepth 1 -type f | wc -l)+ if [ "$count" -ne 8 ]; then+ echo "Expected 8 installers, found $count" >&2+ exit 1+ fi+ options=()+ if [[ "$RELEASE_TAG" == *-* ]]; then+ options+=(--prerelease)+ fi+ gh release create "$RELEASE_TAG" release-assets/* \+ --verify-tag --generate-notes "${options[@]}"diff --git a/.gitignore b/.gitignorenew file mode 100644index 0000000..e77ea4a--- /dev/null+++ b/.gitignore@@ -0,0 +1,14 @@+node_modules/+.pnpm-store/+.turbo/+out/+dist/+release/+coverage/+test-results/+.env+.env.*+!.env.example+*.log+.test-data/+resultdiff --git a/.prettierignore b/.prettierignorenew file mode 100644index 0000000..1c36ffb--- /dev/null+++ b/.prettierignore@@ -0,0 +1,8 @@+node_modules+.pnpm-store+.turbo+**/out+**/release+result+pnpm-lock.yaml+flake.lockdiff --git a/.prettierrc.json b/.prettierrc.jsonnew file mode 100644index 0000000..17d99c4--- /dev/null+++ b/.prettierrc.json@@ -0,0 +1 @@+{ "singleQuote": true, "semi": false, "printWidth": 100 }diff --git a/AGENTS.md b/AGENTS.mdnew file mode 100644index 0000000..c3f7c43--- /dev/null+++ b/AGENTS.md@@ -0,0 +1,36 @@+# Inlark++## Overall goal++Build an exceptional email client that makes everyday email feel fast, clear, and effortless. Inlark should become a dependable personal daily driver, with the visual quality and thoughtful interactions of the best modern productivity apps.++Linux users deserve a beautiful email client with excellent usability and reliable account connections. This project exists because existing options too often combine dated interfaces, awkward workflows, or connection problems, while appealing alternatives are unavailable on Linux or expensive.++## Design direction++- **Linear is the primary reference for visual design and interaction quality.** Aim for its restraint, consistency, clear hierarchy, and attention to detail. Every screen should feel intentional and polished.+- **Superhuman is the primary reference for email workflows.** Draw inspiration from its speed, focused reading experience, efficient navigation, and keyboard-friendly interactions.+- **Notion Mail is an additional source of inspiration** for thoughtful email organization and approachable design.++Use these references to inform a coherent product with its own identity. Favor calm surfaces, readable typography, subtle emphasis, and purposeful spacing. Start with an excellent dark appearance and give light mode the same care.++Good design includes behavior: predictable navigation, useful feedback, accessible controls, and remembering where the user left off. Essential actions must work comfortably with either a keyboard or a mouse.++## Product priorities++- Make reading, searching, organizing, and writing email excellent before expanding the feature set.+- Support several accounts comfortably, with a unified inbox and clear account identity throughout.+- Stay responsive with large inboxes and years of archived mail.+- Make connections dependable and explain interruptions clearly.+- Protect the user's work. Drafts should survive failures, sending status should be unambiguous, and recoverable mistakes should be easy to undo.+- Respect message readability, privacy, and the user's control over their accounts. Require no hosted service and include no telemetry.++## Scope++Build the desktop experience first, with Linux as the priority. A future mobile app should feel like part of the same product, but mobile is outside the initial release.++The first version should be a complete, straightforward email client: conversations, folders, search, attachments, drafts, replies, forwarding, and everyday organization. Most initial accounts are self-hosted.++Favor depth and polish over novelty. AI features, automatic categorization, advanced automation, snooze, scheduled sending, calendars, and a full address book are deferred.++When making product decisions, ask whether the change makes everyday email clearer, faster, more reliable, or more enjoyable. Keep the experience focused and give small details the care needed for a daily-use application.diff --git a/LICENSE b/LICENSEnew file mode 100644index 0000000..19bae35--- /dev/null+++ b/LICENSE@@ -0,0 +1,661 @@+ GNU AFFERO GENERAL PUBLIC LICENSE+ Version 3, 19 November 2007++Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>+Everyone is permitted to copy and distribute verbatim copies+of this license document, but changing it is not allowed.++ Preamble++The GNU Affero General Public License is a free, copyleft license for+software and other kinds of works, specifically designed to ensure+cooperation with the community in the case of network server software.++The licenses for most software and other practical works are designed+to take away your freedom to share and change the works. By contrast,+our General Public Licenses are intended to guarantee your freedom to+share and change all versions of a program--to make sure it remains free+software for all its users.++When we speak of free software, we are referring to freedom, not+price. Our General Public Licenses are designed to make sure that you+have the freedom to distribute copies of free software (and charge for+them if you wish), that you receive source code or can get it if you+want it, that you can change the software or use pieces of it in new+free programs, and that you know you can do these things.++Developers that use our General Public Licenses protect your rights+with two steps: (1) assert copyright on the software, and (2) offer+you this License which gives you legal permission to copy, distribute+and/or modify the software.++A secondary benefit of defending all users' freedom is that+improvements made in alternate versions of the program, if they+receive widespread use, become available for other developers to+incorporate. Many developers of free software are heartened and+encouraged by the resulting cooperation. However, in the case of+software used on network servers, this result may fail to come about.+The GNU General Public License permits making a modified version and+letting the public access it on a server without ever releasing its+source code to the public.++The GNU Affero General Public License is designed specifically to+ensure that, in such cases, the modified source code becomes available+to the community. It requires the operator of a network server to+provide the source code of the modified version running there to the+users of that server. Therefore, public use of a modified version, on+a publicly accessible server, gives the public access to the source+code of the modified version.++An older license, called the Affero General Public License and+published by Affero, was designed to accomplish similar goals. This is+a different license, not a version of the Affero GPL, but Affero has+released a new version of the Affero GPL which permits relicensing under+this license.++The precise terms and conditions for copying, distribution and+modification follow.++ TERMS AND CONDITIONS++0. Definitions.++"This License" refers to version 3 of the GNU Affero General Public License.++"Copyright" also means copyright-like laws that apply to other kinds of+works, such as semiconductor masks.++"The Program" refers to any copyrightable work licensed under this+License. Each licensee is addressed as "you". "Licensees" and+"recipients" may be individuals or organizations.++To "modify" a work means to copy from or adapt all or part of the work+in a fashion requiring copyright permission, other than the making of an+exact copy. The resulting work is called a "modified version" of the+earlier work or a work "based on" the earlier work.++A "covered work" means either the unmodified Program or a work based+on the Program.++To "propagate" a work means to do anything with it that, without+permission, would make you directly or secondarily liable for+infringement under applicable copyright law, except executing it on a+computer or modifying a private copy. Propagation includes copying,+distribution (with or without modification), making available to the+public, and in some countries other activities as well.++To "convey" a work means any kind of propagation that enables other+parties to make or receive copies. Mere interaction with a user through+a computer network, with no transfer of a copy, is not conveying.++An interactive user interface displays "Appropriate Legal Notices"+to the extent that it includes a convenient and prominently visible+feature that (1) displays an appropriate copyright notice, and (2)+tells the user that there is no warranty for the work (except to the+extent that warranties are provided), that licensees may convey the+work under this License, and how to view a copy of this License. If+the interface presents a list of user commands or options, such as a+menu, a prominent item in the list meets this criterion.++1. Source Code.++The "source code" for a work means the preferred form of the work+for making modifications to it. "Object code" means any non-source+form of a work.++A "Standard Interface" means an interface that either is an official+standard defined by a recognized standards body, or, in the case of+interfaces specified for a particular programming language, one that+is widely used among developers working in that language.++The "System Libraries" of an executable work include anything, other+than the work as a whole, that (a) is included in the normal form of+packaging a Major Component, but which is not part of that Major+Component, and (b) serves only to enable use of the work with that+Major Component, or to implement a Standard Interface for which an+implementation is available to the public in source code form. A+"Major Component", in this context, means a major essential component+(kernel, window system, and so on) of the specific operating system+(if any) on which the executable work runs, or a compiler used to+produce the work, or an object code interpreter used to run it.++The "Corresponding Source" for a work in object code form means all+the source code needed to generate, install, and (for an executable+work) run the object code and to modify the work, including scripts to+control those activities. However, it does not include the work's+System Libraries, or general-purpose tools or generally available free+programs which are used unmodified in performing those activities but+which are not part of the work. For example, Corresponding Source+includes interface definition files associated with source files for+the work, and the source code for shared libraries and dynamically+linked subprograms that the work is specifically designed to require,+such as by intimate data communication or control flow between those+subprograms and other parts of the work.++The Corresponding Source need not include anything that users+can regenerate automatically from other parts of the Corresponding+Source.++The Corresponding Source for a work in source code form is that+same work.++2. Basic Permissions.++All rights granted under this License are granted for the term of+copyright on the Program, and are irrevocable provided the stated+conditions are met. This License explicitly affirms your unlimited+permission to run the unmodified Program. The output from running a+covered work is covered by this License only if the output, given its+content, constitutes a covered work. This License acknowledges your+rights of fair use or other equivalent, as provided by copyright law.++You may make, run and propagate covered works that you do not+convey, without conditions so long as your license otherwise remains+in force. You may convey covered works to others for the sole purpose+of having them make modifications exclusively for you, or provide you+with facilities for running those works, provided that you comply with+the terms of this License in conveying all material for which you do+not control copyright. Those thus making or running the covered works+for you must do so exclusively on your behalf, under your direction+and control, on terms that prohibit them from making any copies of+your copyrighted material outside their relationship with you.++Conveying under any other circumstances is permitted solely under+the conditions stated below. Sublicensing is not allowed; section 10+makes it unnecessary.++3. Protecting Users' Legal Rights From Anti-Circumvention Law.++No covered work shall be deemed part of an effective technological+measure under any applicable law fulfilling obligations under article+11 of the WIPO copyright treaty adopted on 20 December 1996, or+similar laws prohibiting or restricting circumvention of such+measures.++When you convey a covered work, you waive any legal power to forbid+circumvention of technological measures to the extent such circumvention+is effected by exercising rights under this License with respect to+the covered work, and you disclaim any intention to limit operation or+modification of the work as a means of enforcing, against the work's+users, your or third parties' legal rights to forbid circumvention of+technological measures.++4. Conveying Verbatim Copies.++You may convey verbatim copies of the Program's source code as you+receive it, in any medium, provided that you conspicuously and+appropriately publish on each copy an appropriate copyright notice;+keep intact all notices stating that this License and any+non-permissive terms added in accord with section 7 apply to the code;+keep intact all notices of the absence of any warranty; and give all+recipients a copy of this License along with the Program.++You may charge any price or no price for each copy that you convey,+and you may offer support or warranty protection for a fee.++5. Conveying Modified Source Versions.++You may convey a work based on the Program, or the modifications to+produce it from the Program, in the form of source code under the+terms of section 4, provided that you also meet all of these conditions:++ a) The work must carry prominent notices stating that you modified+ it, and giving a relevant date.++ b) The work must carry prominent notices stating that it is+ released under this License and any conditions added under section+ 7. This requirement modifies the requirement in section 4 to+ "keep intact all notices".++ c) You must license the entire work, as a whole, under this+ License to anyone who comes into possession of a copy. This+ License will therefore apply, along with any applicable section 7+ additional terms, to the whole of the work, and all its parts,+ regardless of how they are packaged. This License gives no+ permission to license the work in any other way, but it does not+ invalidate such permission if you have separately received it.++ d) If the work has interactive user interfaces, each must display+ Appropriate Legal Notices; however, if the Program has interactive+ interfaces that do not display Appropriate Legal Notices, your+ work need not make them do so.++A compilation of a covered work with other separate and independent+works, which are not by their nature extensions of the covered work,+and which are not combined with it such as to form a larger program,+in or on a volume of a storage or distribution medium, is called an+"aggregate" if the compilation and its resulting copyright are not+used to limit the access or legal rights of the compilation's users+beyond what the individual works permit. Inclusion of a covered work+in an aggregate does not cause this License to apply to the other+parts of the aggregate.++6. Conveying Non-Source Forms.++You may convey a covered work in object code form under the terms+of sections 4 and 5, provided that you also convey the+machine-readable Corresponding Source under the terms of this License,+in one of these ways:++ a) Convey the object code in, or embodied in, a physical product+ (including a physical distribution medium), accompanied by the+ Corresponding Source fixed on a durable physical medium+ customarily used for software interchange.++ b) Convey the object code in, or embodied in, a physical product+ (including a physical distribution medium), accompanied by a+ written offer, valid for at least three years and valid for as+ long as you offer spare parts or customer support for that product+ model, to give anyone who possesses the object code either (1) a+ copy of the Corresponding Source for all the software in the+ product that is covered by this License, on a durable physical+ medium customarily used for software interchange, for a price no+ more than your reasonable cost of physically performing this+ conveying of source, or (2) access to copy the+ Corresponding Source from a network server at no charge.++ c) Convey individual copies of the object code with a copy of the+ written offer to provide the Corresponding Source. This+ alternative is allowed only occasionally and noncommercially, and+ only if you received the object code with such an offer, in accord+ with subsection 6b.++ d) Convey the object code by offering access from a designated+ place (gratis or for a charge), and offer equivalent access to the+ Corresponding Source in the same way through the same place at no+ further charge. You need not require recipients to copy the+ Corresponding Source along with the object code. If the place to+ copy the object code is a network server, the Corresponding Source+ may be on a different server (operated by you or a third party)+ that supports equivalent copying facilities, provided you maintain+ clear directions next to the object code saying where to find the+ Corresponding Source. Regardless of what server hosts the+ Corresponding Source, you remain obligated to ensure that it is+ available for as long as needed to satisfy these requirements.++ e) Convey the object code using peer-to-peer transmission, provided+ you inform other peers where the object code and Corresponding+ Source of the work are being offered to the general public at no+ charge under subsection 6d.++A separable portion of the object code, whose source code is excluded+from the Corresponding Source as a System Library, need not be+included in conveying the object code work.++A "User Product" is either (1) a "consumer product", which means any+tangible personal property which is normally used for personal, family,+or household purposes, or (2) anything designed or sold for incorporation+into a dwelling. In determining whether a product is a consumer product,+doubtful cases shall be resolved in favor of coverage. For a particular+product received by a particular user, "normally used" refers to a+typical or common use of that class of product, regardless of the status+of the particular user or of the way in which the particular user+actually uses, or expects or is expected to use, the product. A product+is a consumer product regardless of whether the product has substantial+commercial, industrial or non-consumer uses, unless such uses represent+the only significant mode of use of the product.++"Installation Information" for a User Product means any methods,+procedures, authorization keys, or other information required to install+and execute modified versions of a covered work in that User Product from+a modified version of its Corresponding Source. The information must+suffice to ensure that the continued functioning of the modified object+code is in no case prevented or interfered with solely because+modification has been made.++If you convey an object code work under this section in, or with, or+specifically for use in, a User Product, and the conveying occurs as+part of a transaction in which the right of possession and use of the+User Product is transferred to the recipient in perpetuity or for a+fixed term (regardless of how the transaction is characterized), the+Corresponding Source conveyed under this section must be accompanied+by the Installation Information. But this requirement does not apply+if neither you nor any third party retains the ability to install+modified object code on the User Product (for example, the work has+been installed in ROM).++The requirement to provide Installation Information does not include a+requirement to continue to provide support service, warranty, or updates+for a work that has been modified or installed by the recipient, or for+the User Product in which it has been modified or installed. Access to a+network may be denied when the modification itself materially and+adversely affects the operation of the network or violates the rules and+protocols for communication across the network.++Corresponding Source conveyed, and Installation Information provided,+in accord with this section must be in a format that is publicly+documented (and with an implementation available to the public in+source code form), and must require no special password or key for+unpacking, reading or copying.++7. Additional Terms.++"Additional permissions" are terms that supplement the terms of this+License by making exceptions from one or more of its conditions.+Additional permissions that are applicable to the entire Program shall+be treated as though they were included in this License, to the extent+that they are valid under applicable law. If additional permissions+apply only to part of the Program, that part may be used separately+under those permissions, but the entire Program remains governed by+this License without regard to the additional permissions.++When you convey a copy of a covered work, you may at your option+remove any additional permissions from that copy, or from any part of+it. (Additional permissions may be written to require their own+removal in certain cases when you modify the work.) You may place+additional permissions on material, added by you to a covered work,+for which you have or can give appropriate copyright permission.++Notwithstanding any other provision of this License, for material you+add to a covered work, you may (if authorized by the copyright holders of+that material) supplement the terms of this License with terms:++ a) Disclaiming warranty or limiting liability differently from the+ terms of sections 15 and 16 of this License; or++ b) Requiring preservation of specified reasonable legal notices or+ author attributions in that material or in the Appropriate Legal+ Notices displayed by works containing it; or++ c) Prohibiting misrepresentation of the origin of that material, or+ requiring that modified versions of such material be marked in+ reasonable ways as different from the original version; or++ d) Limiting the use for publicity purposes of names of licensors or+ authors of the material; or++ e) Declining to grant rights under trademark law for use of some+ trade names, trademarks, or service marks; or++ f) Requiring indemnification of licensors and authors of that+ material by anyone who conveys the material (or modified versions of+ it) with contractual assumptions of liability to the recipient, for+ any liability that these contractual assumptions directly impose on+ those licensors and authors.++All other non-permissive additional terms are considered "further+restrictions" within the meaning of section 10. If the Program as you+received it, or any part of it, contains a notice stating that it is+governed by this License along with a term that is a further+restriction, you may remove that term. If a license document contains+a further restriction but permits relicensing or conveying under this+License, you may add to a covered work material governed by the terms+of that license document, provided that the further restriction does+not survive such relicensing or conveying.++If you add terms to a covered work in accord with this section, you+must place, in the relevant source files, a statement of the+additional terms that apply to those files, or a notice indicating+where to find the applicable terms.++Additional terms, permissive or non-permissive, may be stated in the+form of a separately written license, or stated as exceptions;+the above requirements apply either way.++8. Termination.++You may not propagate or modify a covered work except as expressly+provided under this License. Any attempt otherwise to propagate or+modify it is void, and will automatically terminate your rights under+this License (including any patent licenses granted under the third+paragraph of section 11).++However, if you cease all violation of this License, then your+license from a particular copyright holder is reinstated (a)+provisionally, unless and until the copyright holder explicitly and+finally terminates your license, and (b) permanently, if the copyright+holder fails to notify you of the violation by some reasonable means+prior to 60 days after the cessation.++Moreover, your license from a particular copyright holder is+reinstated permanently if the copyright holder notifies you of the+violation by some reasonable means, this is the first time you have+received notice of violation of this License (for any work) from that+copyright holder, and you cure the violation prior to 30 days after+your receipt of the notice.++Termination of your rights under this section does not terminate the+licenses of parties who have received copies or rights from you under+this License. If your rights have been terminated and not permanently+reinstated, you do not qualify to receive new licenses for the same+material under section 10.++9. Acceptance Not Required for Having Copies.++You are not required to accept this License in order to receive or+run a copy of the Program. Ancillary propagation of a covered work+occurring solely as a consequence of using peer-to-peer transmission+to receive a copy likewise does not require acceptance. However,+nothing other than this License grants you permission to propagate or+modify any covered work. These actions infringe copyright if you do+not accept this License. Therefore, by modifying or propagating a+covered work, you indicate your acceptance of this License to do so.++10. Automatic Licensing of Downstream Recipients.++Each time you convey a covered work, the recipient automatically+receives a license from the original licensors, to run, modify and+propagate that work, subject to this License. You are not responsible+for enforcing compliance by third parties with this License.++An "entity transaction" is a transaction transferring control of an+organization, or substantially all assets of one, or subdividing an+organization, or merging organizations. If propagation of a covered+work results from an entity transaction, each party to that+transaction who receives a copy of the work also receives whatever+licenses to the work the party's predecessor in interest had or could+give under the previous paragraph, plus a right to possession of the+Corresponding Source of the work from the predecessor in interest, if+the predecessor has it or can get it with reasonable efforts.++You may not impose any further restrictions on the exercise of the+rights granted or affirmed under this License. For example, you may+not impose a license fee, royalty, or other charge for exercise of+rights granted under this License, and you may not initiate litigation+(including a cross-claim or counterclaim in a lawsuit) alleging that+any patent claim is infringed by making, using, selling, offering for+sale, or importing the Program or any portion of it.++11. Patents.++A "contributor" is a copyright holder who authorizes use under this+License of the Program or a work on which the Program is based. The+work thus licensed is called the contributor's "contributor version".++A contributor's "essential patent claims" are all patent claims+owned or controlled by the contributor, whether already acquired or+hereafter acquired, that would be infringed by some manner, permitted+by this License, of making, using, or selling its contributor version,+but do not include claims that would be infringed only as a+consequence of further modification of the contributor version. For+purposes of this definition, "control" includes the right to grant+patent sublicenses in a manner consistent with the requirements of+this License.++Each contributor grants you a non-exclusive, worldwide, royalty-free+patent license under the contributor's essential patent claims, to+make, use, sell, offer for sale, import and otherwise run, modify and+propagate the contents of its contributor version.++In the following three paragraphs, a "patent license" is any express+agreement or commitment, however denominated, not to enforce a patent+(such as an express permission to practice a patent or covenant not to+sue for patent infringement). To "grant" such a patent license to a+party means to make such an agreement or commitment not to enforce a+patent against the party.++If you convey a covered work, knowingly relying on a patent license,+and the Corresponding Source of the work is not available for anyone+to copy, free of charge and under the terms of this License, through a+publicly available network server or other readily accessible means,+then you must either (1) cause the Corresponding Source to be so+available, or (2) arrange to deprive yourself of the benefit of the+patent license for this particular work, or (3) arrange, in a manner+consistent with the requirements of this License, to extend the patent+license to downstream recipients. "Knowingly relying" means you have+actual knowledge that, but for the patent license, your conveying the+covered work in a country, or your recipient's use of the covered work+in a country, would infringe one or more identifiable patents in that+country that you have reason to believe are valid.++If, pursuant to or in connection with a single transaction or+arrangement, you convey, or propagate by procuring conveyance of, a+covered work, and grant a patent license to some of the parties+receiving the covered work authorizing them to use, propagate, modify+or convey a specific copy of the covered work, then the patent license+you grant is automatically extended to all recipients of the covered+work and works based on it.++A patent license is "discriminatory" if it does not include within+the scope of its coverage, prohibits the exercise of, or is+conditioned on the non-exercise of one or more of the rights that are+specifically granted under this License. You may not convey a covered+work if you are a party to an arrangement with a third party that is+in the business of distributing software, under which you make payment+to the third party based on the extent of your activity of conveying+the work, and under which the third party grants, to any of the+parties who would receive the covered work from you, a discriminatory+patent license (a) in connection with copies of the covered work+conveyed by you (or copies made from those copies), or (b) primarily+for and in connection with specific products or compilations that+contain the covered work, unless you entered into that arrangement,+or that patent license was granted, prior to 28 March 2007.++Nothing in this License shall be construed as excluding or limiting+any implied license or other defenses to infringement that may+otherwise be available to you under applicable patent law.++12. No Surrender of Others' Freedom.++If conditions are imposed on you (whether by court order, agreement or+otherwise) that contradict the conditions of this License, they do not+excuse you from the conditions of this License. If you cannot convey a+covered work so as to satisfy simultaneously your obligations under this+License and any other pertinent obligations, then as a consequence you may+not convey it at all. For example, if you agree to terms that obligate you+to collect a royalty for further conveying from those to whom you convey+the Program, the only way you could satisfy both those terms and this+License would be to refrain entirely from conveying the Program.++13. Remote Network Interaction; Use with the GNU General Public License.++Notwithstanding any other provision of this License, if you modify the+Program, your modified version must prominently offer all users+interacting with it remotely through a computer network (if your version+supports such interaction) an opportunity to receive the Corresponding+Source of your version by providing access to the Corresponding Source+from a network server at no charge, through some standard or customary+means of facilitating copying of software. This Corresponding Source+shall include the Corresponding Source for any work covered by version 3+of the GNU General Public License that is incorporated pursuant to the+following paragraph.++Notwithstanding any other provision of this License, you have+permission to link or combine any covered work with a work licensed+under version 3 of the GNU General Public License into a single+combined work, and to convey the resulting work. The terms of this+License will continue to apply to the part which is the covered work,+but the work with which it is combined will remain governed by version+3 of the GNU General Public License.++14. Revised Versions of this License.++The Free Software Foundation may publish revised and/or new versions of+the GNU Affero General Public License from time to time. Such new versions+will be similar in spirit to the present version, but may differ in detail to+address new problems or concerns.++Each version is given a distinguishing version number. If the+Program specifies that a certain numbered version of the GNU Affero General+Public License "or any later version" applies to it, you have the+option of following the terms and conditions either of that numbered+version or of any later version published by the Free Software+Foundation. If the Program does not specify a version number of the+GNU Affero General Public License, you may choose any version ever published+by the Free Software Foundation.++If the Program specifies that a proxy can decide which future+versions of the GNU Affero General Public License can be used, that proxy's+public statement of acceptance of a version permanently authorizes you+to choose that version for the Program.++Later license versions may give you additional or different+permissions. However, no additional obligations are imposed on any+author or copyright holder as a result of your choosing to follow a+later version.++15. Disclaimer of Warranty.++THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.++16. Limitation of Liability.++IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF+SUCH DAMAGES.++17. Interpretation of Sections 15 and 16.++If the disclaimer of warranty and limitation of liability provided+above cannot be given local legal effect according to their terms,+reviewing courts shall apply local law that most closely approximates+an absolute waiver of all civil liability in connection with the+Program, unless a warranty or assumption of liability accompanies a+copy of the Program in return for a fee.++ END OF TERMS AND CONDITIONS++ How to Apply These Terms to Your New Programs++If you develop a new program, and you want it to be of the greatest+possible use to the public, the best way to achieve this is to make it+free software which everyone can redistribute and change under these terms.++To do so, attach the following notices to the program. It is safest+to attach them to the start of each source file to most effectively+state the exclusion of warranty; and each file should have at least+the "copyright" line and a pointer to where the full notice is found.++ <one line to give the program's name and a brief idea of what it does.>+ Copyright (C) <year> <name of author>++ This program is free software: you can redistribute it and/or modify+ it under the terms of the GNU Affero General Public License as published by+ the Free Software Foundation, either version 3 of the License, or+ (at your option) any later version.++ This program is distributed in the hope that it will be useful,+ but WITHOUT ANY WARRANTY; without even the implied warranty of+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ GNU Affero General Public License for more details.++ You should have received a copy of the GNU Affero General Public License+ along with this program. If not, see <https://www.gnu.org/licenses/>.++Also add information on how to contact you by electronic and paper mail.++If your software can interact with users remotely through a computer+network, you should also make sure that it provides a way for users to+get its source. For example, if your program is a web application, its+interface could display a "Source" link that leads users to an archive+of the code. There are many ways you could offer source, and different+solutions will be better for different programs; see section 13 for the+specific requirements.++You should also get your employer (if you work as a programmer) or school,+if any, to sign a "copyright disclaimer" for the program, if necessary.+For more information on this, and how to apply and follow the GNU AGPL, see+<https://www.gnu.org/licenses/>.diff --git a/README.md b/README.mdnew file mode 100644index 0000000..0eed1c3--- /dev/null+++ b/README.md@@ -0,0 +1,111 @@+# Inlark++A focused, Linux-first email client for JMAP and IMAP/SMTP accounts. Built with Electron, React, TypeScript, Tailwind CSS, Base UI, TanStack libraries, and Turborepo. Connects directly to your server; no hosted account or telemetry.++This is an initial implementation, not a claim of production readiness. The working client includes account setup, a unified inbox, server search, conversation reading, organization and undo, folders, composition, attachments, local/server drafts, sending, themes, keyboard navigation, notifications, and a tray. See [validation and remaining acceptance work](docs/validation.md) before adopting it as your only mail client.++## Run++To install the desktop app from this checkout on NixOS or another Linux system with Nix:++```sh+nix profile install path:.#inlark+inlark+```++The flake provides x86_64 and aarch64 Linux packages, including the application launcher, desktop entry, icon, and `mailto:` handler. To add it declaratively to a NixOS flake configuration, add Inlark as an input and enable its module:++```nix+{+ inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";+ inputs.inlark.url = "github:inlark/inlark/v0.1.0";++ outputs = { nixpkgs, inlark, ... }: {+ nixosConfigurations.my-host = nixpkgs.lib.nixosSystem {+ system = "x86_64-linux";+ modules = [+ inlark.nixosModules.default+ ./configuration.nix+ { programs.inlark.enable = true; }+ ];+ };+ };+}+```++Replace `my-host` with your NixOS host name. The `v0.1.0` segment pins the installation to that release; omit it to follow the default branch. For a direct profile install from the release tag, run `nix profile install 'github:inlark/inlark/v0.1.0#inlark'`. For development on NixOS:++```sh+nix develop path:.+pnpm install --frozen-lockfile+pnpm dev+```++The shell selects Nix's Electron executable and skips the incompatible downloaded binary. On a conventional Linux distribution, install Node 24 and pnpm 12.3.4, then run `pnpm install --frozen-lockfile` and `pnpm dev`.++For a browser preview with sample mail:++```sh+pnpm dev:web+```++Open the printed localhost URL. Append `?stress=1` for five synthetic 50,000-message inboxes. The browser preview cannot connect to real accounts, access native files, or send email. Demo storage is separate from real account storage. A native sample workspace is available with `pnpm dev -- --demo` (or run the packaged app with `--demo`).++Sample messages use fictional content with real sender domains, so both demo modes can show sender pictures when **Load remote images** is enabled. The browser preview resolves pictures through its local development server; the native demo uses the same resolver as connected mail.++## Connect your account++Open **Settings → Accounts → Add account** and enter your email address. Inlark looks up the settings your domain publishes and shows the protocol, servers, ports and security before asking for a password. It checks JMAP (DNS SRV, then `/.well-known/jmap`) first and prefers it; IMAP/SMTP comes from your domain's Thunderbird-style configuration file or DNS SRV records. Only when your domain publishes nothing does it ask Thunderbird's public settings directory, and then only the domain is sent. Discovery never carries credentials. **Set up manually** is always available.++For JMAP, enter your server URL or session endpoint. Use the canonical origin advertised by your server: authenticated endpoints on a different origin are deliberately rejected so credentials are never sent to another host.++For IMAP/SMTP, incoming and outgoing servers have their own host, port, username and password; the outgoing login defaults to the incoming one. Security is implicit TLS or required STARTTLS, always with certificate verification, never a plaintext fallback. Inlark signs in to both servers separately, without sending a message, and only saves the account when both succeed. If Sent, Drafts, Archive, Junk or Trash cannot be identified from the server's special-use flags, you choose or create them; **Folders…** and **Edit connection…** in the account menu change them later. An authentication failure is shown on the settings you chose; no other candidate is tried with your password.++IMAP mail is read from a local metadata index built in the background, newest Inbox mail first. While it catches up, lists say that older mail may be missing, and searches still run on the server. Message bodies and attachments are fetched when opened. Actions a server cannot do safely (moving without MOVE or UIDPLUS, permanent deletion without UIDPLUS) are turned off with an explanation.++When an OS keyring is available, remembered passwords use Electron's secure storage. Without a keyring, you can explicitly choose to remember a login on this device; its password is then stored unencrypted in the app's owner-only local data file. Leave **Remember this login** unchecked for session-only login. Set up GNOME Keyring or another Secret Service provider on Hyprland if you prefer encrypted storage. A locally stored password moves to secure storage on the next successful reconnect when a keyring becomes available.++Mail organization and sending require a connection. Previously fetched pages and messages can be read from the bounded cache. Local drafts and staged attachments persist independently of the read cache. A send whose response was lost stays **unconfirmed** until reconciled; it is never automatically retried. For IMAP accounts the SMTP acceptance is recorded before the Sent copy is filed, so a failed copy shows as “Sent · Sent copy pending” and only the copy is retried. A partially accepted message lists the refused recipients and offers a new draft addressed only to them.++## Build and verify++```sh+pnpm check # Formatting, TypeScript, deterministic tests, production build+pnpm test:stalwart # disposable Stalwart 0.16.23 over JMAP, IMAP and SMTP; requires Podman (or CONTAINER_RUNTIME=docker)+nix build path:. # Nix package; ./result/bin/inlark+pnpm package:linux # AppImage + .deb + .rpm in apps/desktop/release+pnpm test:deb # isolated Debian packaging smoke; requires Podman+```++The Nix build is pinned by `flake.lock`, `pnpm-lock.yaml`, and the dependency-store hash. It runs typechecking and deterministic tests offline during the build. After changing dependencies, update the hash in `nix/package.nix` using the mismatch reported by Nix.++The Linux packaging script selects a Nix-compatible `fpm` on NixOS. Packages currently contain reserved `.localhost`/`.invalid` development metadata. Replace that metadata before public distribution.++Pushing a `v<version>` tag matching `apps/desktop/package.json` runs the [desktop release workflow](.github/workflows/release.yml). It builds x64 Windows installer, Intel and Apple Silicon macOS DMG/ZIP files, and x64 Linux AppImage, Debian, and RPM packages. It also checks that the Nix flake builds and installs before publishing the GitHub Release. The macOS and Windows builds are unsigned; they may require the user to approve them through the operating system's security prompts until signing and macOS notarization are configured.++To check native preload/IPC and SQLite-worker startup without opening a window:++```sh+INLARK_DATA_DIR="$(mktemp -d)" ./result/bin/inlark --smoke-test --ozone-platform=wayland+```++Only use `INLARK_DATA_DIR` for a separate test profile. Normal application storage lives in Electron's `userData` directory, typically `~/.config/Inlark`. [Troubleshooting](docs/troubleshooting.md) explains recovery and diagnostics.++## Workspace++| Location | Responsibility |+| --------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |+| `apps/desktop/src/main` | Authenticated network access, credentials, drafts/submission journal, discovery, IMAP index worker, files, notifications, and native lifecycle |+| `apps/desktop/src/preload` | Fixed, validated `DesktopMailAPI` bridge |+| `apps/desktop/src/renderer` | React application, typed routes, query cache, virtual list, reader, composer, preferences |+| `packages/core` | Platform-independent domain types, validation, search, identity selection, provider contract, merge logic |+| `packages/jmap` | JMAP provider; injectable fetch and no Electron/DOM/filesystem dependency |+| `packages/imap` | IMAP/SMTP provider (ImapFlow, Nodemailer, MailParser); injected index and attachment access |+| `packages/ui` | Customized Base UI components and shared Tailwind theme |+| `tests` | Domain, protocol, storage/submission, network-boundary, and real-server tests |++Read [architecture](docs/architecture.md) for extension points. Mobile, OAuth sign-in (Gmail, Microsoft), sending aliases, full offline downloads, offline change queues, AI, scheduling, snooze, rules, calendar, and a full address book are outside this version.++## License++Copyright (C) 2026 Paul Koeck. Inlark is licensed under the [GNU Affero General Public License version 3](LICENSE) (`AGPL-3.0-only`). The bundled Inter font retains its [SIL Open Font License](packages/ui/src/fonts/OFL.txt).diff --git a/apps/desktop/components.json b/apps/desktop/components.jsonnew file mode 100644index 0000000..4e9652e--- /dev/null+++ b/apps/desktop/components.json@@ -0,0 +1,21 @@+{+ "$schema": "https://ui.shadcn.com/schema.json",+ "style": "base-nova",+ "rsc": false,+ "tsx": true,+ "tailwind": {+ "config": "",+ "css": "src/renderer/src/styles.css",+ "baseColor": "neutral",+ "cssVariables": true,+ "prefix": ""+ },+ "iconLibrary": "hugeicons",+ "aliases": {+ "components": "@/components",+ "ui": "@inlark/ui/components",+ "lib": "@/lib",+ "hooks": "@/hooks",+ "utils": "@inlark/ui/lib/utils"+ }+}diff --git a/apps/desktop/electron-builder.yml b/apps/desktop/electron-builder.ymlnew file mode 100644index 0000000..9ff0841--- /dev/null+++ b/apps/desktop/electron-builder.yml@@ -0,0 +1,50 @@+appId: app.inlark.desktop+productName: Inlark+directories:+ output: release+files:+ - out/**+ - resources/**+ - '!node_modules/**'+ - package.json+linux:+ target:+ - AppImage+ - deb+ - rpm+ category: Network+ executableName: inlark+ syncDesktopName: true+ artifactName: 'Inlark-${version}-${arch}.${ext}'+ icon: resources/icon.png+ desktop:+ entry:+ MimeType: x-scheme-handler/mailto;+ StartupWMClass: inlark+protocols:+ - name: Email+ schemes: [mailto]+mac:+ icon: resources/icon.png+ artifactName: 'Inlark-${version}-${arch}.${ext}'+win:+ icon: resources/icon.png+ artifactName: 'Inlark-${version}-${arch}-setup.${ext}'+deb:+ packageName: inlark+ depends:+ [+ 'libgtk-3-0 | libgtk-3-0t64',+ 'libasound2 | libasound2t64',+ libgbm1,+ libdrm2,+ libxkbcommon0,+ libnotify4,+ libnss3,+ libxss1,+ libxtst6,+ xdg-utils,+ libsecret-1-0,+ ]+rpm:+ packageName: inlarkdiff --git a/apps/desktop/electron.vite.config.ts b/apps/desktop/electron.vite.config.tsnew file mode 100644index 0000000..aeb3cd7--- /dev/null+++ b/apps/desktop/electron.vite.config.ts@@ -0,0 +1,18 @@+import { fileURLToPath } from 'node:url'+import { defineConfig } from 'electron-vite'+import react from '@vitejs/plugin-react'+import tailwindcss from '@tailwindcss/vite'+export default defineConfig({+ main: { build: { externalizeDeps: false } },+ preload: {+ build: {+ externalizeDeps: false,+ rollupOptions: { output: { format: 'cjs', entryFileNames: 'index.cjs' } },+ },+ },+ renderer: {+ resolve: { alias: { '@': fileURLToPath(new URL('./src/renderer/src', import.meta.url)) } },+ plugins: [react(), tailwindcss()],+ build: { minify: 'esbuild' },+ },+})diff --git a/apps/desktop/package.json b/apps/desktop/package.jsonnew file mode 100644index 0000000..4a5c003--- /dev/null+++ b/apps/desktop/package.json@@ -0,0 +1,55 @@+{+ "name": "@inlark/desktop",+ "version": "0.1.0",+ "private": true,+ "license": "AGPL-3.0-only",+ "description": "A considered home for your email.",+ "author": {+ "name": "Paul Koeck",+ "email": "[email protected]"+ },+ "type": "module",+ "main": "out/main/index.js",+ "scripts": {+ "dev": "electron-vite dev",+ "dev:web": "vite --config vite.web.config.ts --host 127.0.0.1",+ "build": "electron-vite build",+ "typecheck": "tsc -p tsconfig.json",+ "package:linux": "electron-builder --linux AppImage deb rpm --publish never"+ },+ "dependencies": {+ "@base-ui/react": "^1.8.0",+ "@inlark/core": "workspace:*",+ "@inlark/imap": "workspace:*",+ "@inlark/jmap": "workspace:*",+ "@inlark/ui": "workspace:*",+ "@tanstack/react-form": "^1.0.0",+ "@tanstack/react-hotkeys": "^0.11.0",+ "@tanstack/react-query": "^5.80.0",+ "@tanstack/react-router": "^1.120.0",+ "@tanstack/react-virtual": "^3.13.0",+ "@tiptap/extension-image": "^3.0.0",+ "@tiptap/extension-placeholder": "^3.0.0",+ "@tiptap/react": "^3.0.0",+ "@tiptap/starter-kit": "^3.0.0",+ "boring-avatars": "^2.0.4",+ "dompurify": "^3.2.0",+ "idb": "^8.0.0",+ "react": "^19.0.0",+ "react-dom": "^19.0.0",+ "zod": "^4.0.0"+ },+ "devDependencies": {+ "@tailwindcss/vite": "^4.1.0",+ "@types/react": "^19.0.0",+ "@types/react-dom": "^19.0.0",+ "@vitejs/plugin-react": "^5.0.0",+ "electron": "^44.4.5",+ "electron-builder": "^26.0.0",+ "electron-vite": "^5.0.0",+ "tailwindcss": "^4.1.0",+ "vite": "^7.0.0"+ },+ "desktopName": "inlark.desktop",+ "homepage": "https://github.com/inlark/inlark"+}diff --git a/apps/desktop/resources/LICENSE b/apps/desktop/resources/LICENSEnew file mode 100644index 0000000..19bae35--- /dev/null+++ b/apps/desktop/resources/LICENSE@@ -0,0 +1,661 @@+ GNU AFFERO GENERAL PUBLIC LICENSE+ Version 3, 19 November 2007++Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>+Everyone is permitted to copy and distribute verbatim copies+of this license document, but changing it is not allowed.++ Preamble++The GNU Affero General Public License is a free, copyleft license for+software and other kinds of works, specifically designed to ensure+cooperation with the community in the case of network server software.++The licenses for most software and other practical works are designed+to take away your freedom to share and change the works. By contrast,+our General Public Licenses are intended to guarantee your freedom to+share and change all versions of a program--to make sure it remains free+software for all its users.++When we speak of free software, we are referring to freedom, not+price. Our General Public Licenses are designed to make sure that you+have the freedom to distribute copies of free software (and charge for+them if you wish), that you receive source code or can get it if you+want it, that you can change the software or use pieces of it in new+free programs, and that you know you can do these things.++Developers that use our General Public Licenses protect your rights+with two steps: (1) assert copyright on the software, and (2) offer+you this License which gives you legal permission to copy, distribute+and/or modify the software.++A secondary benefit of defending all users' freedom is that+improvements made in alternate versions of the program, if they+receive widespread use, become available for other developers to+incorporate. Many developers of free software are heartened and+encouraged by the resulting cooperation. However, in the case of+software used on network servers, this result may fail to come about.+The GNU General Public License permits making a modified version and+letting the public access it on a server without ever releasing its+source code to the public.++The GNU Affero General Public License is designed specifically to+ensure that, in such cases, the modified source code becomes available+to the community. It requires the operator of a network server to+provide the source code of the modified version running there to the+users of that server. Therefore, public use of a modified version, on+a publicly accessible server, gives the public access to the source+code of the modified version.++An older license, called the Affero General Public License and+published by Affero, was designed to accomplish similar goals. This is+a different license, not a version of the Affero GPL, but Affero has+released a new version of the Affero GPL which permits relicensing under+this license.++The precise terms and conditions for copying, distribution and+modification follow.++ TERMS AND CONDITIONS++0. Definitions.++"This License" refers to version 3 of the GNU Affero General Public License.++"Copyright" also means copyright-like laws that apply to other kinds of+works, such as semiconductor masks.++"The Program" refers to any copyrightable work licensed under this+License. Each licensee is addressed as "you". "Licensees" and+"recipients" may be individuals or organizations.++To "modify" a work means to copy from or adapt all or part of the work+in a fashion requiring copyright permission, other than the making of an+exact copy. The resulting work is called a "modified version" of the+earlier work or a work "based on" the earlier work.++A "covered work" means either the unmodified Program or a work based+on the Program.++To "propagate" a work means to do anything with it that, without+permission, would make you directly or secondarily liable for+infringement under applicable copyright law, except executing it on a+computer or modifying a private copy. Propagation includes copying,+distribution (with or without modification), making available to the+public, and in some countries other activities as well.++To "convey" a work means any kind of propagation that enables other+parties to make or receive copies. Mere interaction with a user through+a computer network, with no transfer of a copy, is not conveying.++An interactive user interface displays "Appropriate Legal Notices"+to the extent that it includes a convenient and prominently visible+feature that (1) displays an appropriate copyright notice, and (2)+tells the user that there is no warranty for the work (except to the+extent that warranties are provided), that licensees may convey the+work under this License, and how to view a copy of this License. If+the interface presents a list of user commands or options, such as a+menu, a prominent item in the list meets this criterion.++1. Source Code.++The "source code" for a work means the preferred form of the work+for making modifications to it. "Object code" means any non-source+form of a work.++A "Standard Interface" means an interface that either is an official+standard defined by a recognized standards body, or, in the case of+interfaces specified for a particular programming language, one that+is widely used among developers working in that language.++The "System Libraries" of an executable work include anything, other+than the work as a whole, that (a) is included in the normal form of+packaging a Major Component, but which is not part of that Major+Component, and (b) serves only to enable use of the work with that+Major Component, or to implement a Standard Interface for which an+implementation is available to the public in source code form. A+"Major Component", in this context, means a major essential component+(kernel, window system, and so on) of the specific operating system+(if any) on which the executable work runs, or a compiler used to+produce the work, or an object code interpreter used to run it.++The "Corresponding Source" for a work in object code form means all+the source code needed to generate, install, and (for an executable+work) run the object code and to modify the work, including scripts to+control those activities. However, it does not include the work's+System Libraries, or general-purpose tools or generally available free+programs which are used unmodified in performing those activities but+which are not part of the work. For example, Corresponding Source+includes interface definition files associated with source files for+the work, and the source code for shared libraries and dynamically+linked subprograms that the work is specifically designed to require,+such as by intimate data communication or control flow between those+subprograms and other parts of the work.++The Corresponding Source need not include anything that users+can regenerate automatically from other parts of the Corresponding+Source.++The Corresponding Source for a work in source code form is that+same work.++2. Basic Permissions.++All rights granted under this License are granted for the term of+copyright on the Program, and are irrevocable provided the stated+conditions are met. This License explicitly affirms your unlimited+permission to run the unmodified Program. The output from running a+covered work is covered by this License only if the output, given its+content, constitutes a covered work. This License acknowledges your+rights of fair use or other equivalent, as provided by copyright law.++You may make, run and propagate covered works that you do not+convey, without conditions so long as your license otherwise remains+in force. You may convey covered works to others for the sole purpose+of having them make modifications exclusively for you, or provide you+with facilities for running those works, provided that you comply with+the terms of this License in conveying all material for which you do+not control copyright. Those thus making or running the covered works+for you must do so exclusively on your behalf, under your direction+and control, on terms that prohibit them from making any copies of+your copyrighted material outside their relationship with you.++Conveying under any other circumstances is permitted solely under+the conditions stated below. Sublicensing is not allowed; section 10+makes it unnecessary.++3. Protecting Users' Legal Rights From Anti-Circumvention Law.++No covered work shall be deemed part of an effective technological+measure under any applicable law fulfilling obligations under article+11 of the WIPO copyright treaty adopted on 20 December 1996, or+similar laws prohibiting or restricting circumvention of such+measures.++When you convey a covered work, you waive any legal power to forbid+circumvention of technological measures to the extent such circumvention+is effected by exercising rights under this License with respect to+the covered work, and you disclaim any intention to limit operation or+modification of the work as a means of enforcing, against the work's+users, your or third parties' legal rights to forbid circumvention of+technological measures.++4. Conveying Verbatim Copies.++You may convey verbatim copies of the Program's source code as you+receive it, in any medium, provided that you conspicuously and+appropriately publish on each copy an appropriate copyright notice;+keep intact all notices stating that this License and any+non-permissive terms added in accord with section 7 apply to the code;+keep intact all notices of the absence of any warranty; and give all+recipients a copy of this License along with the Program.++You may charge any price or no price for each copy that you convey,+and you may offer support or warranty protection for a fee.++5. Conveying Modified Source Versions.++You may convey a work based on the Program, or the modifications to+produce it from the Program, in the form of source code under the+terms of section 4, provided that you also meet all of these conditions:++ a) The work must carry prominent notices stating that you modified+ it, and giving a relevant date.++ b) The work must carry prominent notices stating that it is+ released under this License and any conditions added under section+ 7. This requirement modifies the requirement in section 4 to+ "keep intact all notices".++ c) You must license the entire work, as a whole, under this+ License to anyone who comes into possession of a copy. This+ License will therefore apply, along with any applicable section 7+ additional terms, to the whole of the work, and all its parts,+ regardless of how they are packaged. This License gives no+ permission to license the work in any other way, but it does not+ invalidate such permission if you have separately received it.++ d) If the work has interactive user interfaces, each must display+ Appropriate Legal Notices; however, if the Program has interactive+ interfaces that do not display Appropriate Legal Notices, your+ work need not make them do so.++A compilation of a covered work with other separate and independent+works, which are not by their nature extensions of the covered work,+and which are not combined with it such as to form a larger program,+in or on a volume of a storage or distribution medium, is called an+"aggregate" if the compilation and its resulting copyright are not+used to limit the access or legal rights of the compilation's users+beyond what the individual works permit. Inclusion of a covered work+in an aggregate does not cause this License to apply to the other+parts of the aggregate.++6. Conveying Non-Source Forms.++You may convey a covered work in object code form under the terms+of sections 4 and 5, provided that you also convey the+machine-readable Corresponding Source under the terms of this License,+in one of these ways:++ a) Convey the object code in, or embodied in, a physical product+ (including a physical distribution medium), accompanied by the+ Corresponding Source fixed on a durable physical medium+ customarily used for software interchange.++ b) Convey the object code in, or embodied in, a physical product+ (including a physical distribution medium), accompanied by a+ written offer, valid for at least three years and valid for as+ long as you offer spare parts or customer support for that product+ model, to give anyone who possesses the object code either (1) a+ copy of the Corresponding Source for all the software in the+ product that is covered by this License, on a durable physical+ medium customarily used for software interchange, for a price no+ more than your reasonable cost of physically performing this+ conveying of source, or (2) access to copy the+ Corresponding Source from a network server at no charge.++ c) Convey individual copies of the object code with a copy of the+ written offer to provide the Corresponding Source. This+ alternative is allowed only occasionally and noncommercially, and+ only if you received the object code with such an offer, in accord+ with subsection 6b.++ d) Convey the object code by offering access from a designated+ place (gratis or for a charge), and offer equivalent access to the+ Corresponding Source in the same way through the same place at no+ further charge. You need not require recipients to copy the+ Corresponding Source along with the object code. If the place to+ copy the object code is a network server, the Corresponding Source+ may be on a different server (operated by you or a third party)+ that supports equivalent copying facilities, provided you maintain+ clear directions next to the object code saying where to find the+ Corresponding Source. Regardless of what server hosts the+ Corresponding Source, you remain obligated to ensure that it is+ available for as long as needed to satisfy these requirements.++ e) Convey the object code using peer-to-peer transmission, provided+ you inform other peers where the object code and Corresponding+ Source of the work are being offered to the general public at no+ charge under subsection 6d.++A separable portion of the object code, whose source code is excluded+from the Corresponding Source as a System Library, need not be+included in conveying the object code work.++A "User Product" is either (1) a "consumer product", which means any+tangible personal property which is normally used for personal, family,+or household purposes, or (2) anything designed or sold for incorporation+into a dwelling. In determining whether a product is a consumer product,+doubtful cases shall be resolved in favor of coverage. For a particular+product received by a particular user, "normally used" refers to a+typical or common use of that class of product, regardless of the status+of the particular user or of the way in which the particular user+actually uses, or expects or is expected to use, the product. A product+is a consumer product regardless of whether the product has substantial+commercial, industrial or non-consumer uses, unless such uses represent+the only significant mode of use of the product.++"Installation Information" for a User Product means any methods,+procedures, authorization keys, or other information required to install+and execute modified versions of a covered work in that User Product from+a modified version of its Corresponding Source. The information must+suffice to ensure that the continued functioning of the modified object+code is in no case prevented or interfered with solely because+modification has been made.++If you convey an object code work under this section in, or with, or+specifically for use in, a User Product, and the conveying occurs as+part of a transaction in which the right of possession and use of the+User Product is transferred to the recipient in perpetuity or for a+fixed term (regardless of how the transaction is characterized), the+Corresponding Source conveyed under this section must be accompanied+by the Installation Information. But this requirement does not apply+if neither you nor any third party retains the ability to install+modified object code on the User Product (for example, the work has+been installed in ROM).++The requirement to provide Installation Information does not include a+requirement to continue to provide support service, warranty, or updates+for a work that has been modified or installed by the recipient, or for+the User Product in which it has been modified or installed. Access to a+network may be denied when the modification itself materially and+adversely affects the operation of the network or violates the rules and+protocols for communication across the network.++Corresponding Source conveyed, and Installation Information provided,+in accord with this section must be in a format that is publicly+documented (and with an implementation available to the public in+source code form), and must require no special password or key for+unpacking, reading or copying.++7. Additional Terms.++"Additional permissions" are terms that supplement the terms of this+License by making exceptions from one or more of its conditions.+Additional permissions that are applicable to the entire Program shall+be treated as though they were included in this License, to the extent+that they are valid under applicable law. If additional permissions+apply only to part of the Program, that part may be used separately+under those permissions, but the entire Program remains governed by+this License without regard to the additional permissions.++When you convey a copy of a covered work, you may at your option+remove any additional permissions from that copy, or from any part of+it. (Additional permissions may be written to require their own+removal in certain cases when you modify the work.) You may place+additional permissions on material, added by you to a covered work,+for which you have or can give appropriate copyright permission.++Notwithstanding any other provision of this License, for material you+add to a covered work, you may (if authorized by the copyright holders of+that material) supplement the terms of this License with terms:++ a) Disclaiming warranty or limiting liability differently from the+ terms of sections 15 and 16 of this License; or++ b) Requiring preservation of specified reasonable legal notices or+ author attributions in that material or in the Appropriate Legal+ Notices displayed by works containing it; or++ c) Prohibiting misrepresentation of the origin of that material, or+ requiring that modified versions of such material be marked in+ reasonable ways as different from the original version; or++ d) Limiting the use for publicity purposes of names of licensors or+ authors of the material; or++ e) Declining to grant rights under trademark law for use of some+ trade names, trademarks, or service marks; or++ f) Requiring indemnification of licensors and authors of that+ material by anyone who conveys the material (or modified versions of+ it) with contractual assumptions of liability to the recipient, for+ any liability that these contractual assumptions directly impose on+ those licensors and authors.++All other non-permissive additional terms are considered "further+restrictions" within the meaning of section 10. If the Program as you+received it, or any part of it, contains a notice stating that it is+governed by this License along with a term that is a further+restriction, you may remove that term. If a license document contains+a further restriction but permits relicensing or conveying under this+License, you may add to a covered work material governed by the terms+of that license document, provided that the further restriction does+not survive such relicensing or conveying.++If you add terms to a covered work in accord with this section, you+must place, in the relevant source files, a statement of the+additional terms that apply to those files, or a notice indicating+where to find the applicable terms.++Additional terms, permissive or non-permissive, may be stated in the+form of a separately written license, or stated as exceptions;+the above requirements apply either way.++8. Termination.++You may not propagate or modify a covered work except as expressly+provided under this License. Any attempt otherwise to propagate or+modify it is void, and will automatically terminate your rights under+this License (including any patent licenses granted under the third+paragraph of section 11).++However, if you cease all violation of this License, then your+license from a particular copyright holder is reinstated (a)+provisionally, unless and until the copyright holder explicitly and+finally terminates your license, and (b) permanently, if the copyright+holder fails to notify you of the violation by some reasonable means+prior to 60 days after the cessation.++Moreover, your license from a particular copyright holder is+reinstated permanently if the copyright holder notifies you of the+violation by some reasonable means, this is the first time you have+received notice of violation of this License (for any work) from that+copyright holder, and you cure the violation prior to 30 days after+your receipt of the notice.++Termination of your rights under this section does not terminate the+licenses of parties who have received copies or rights from you under+this License. If your rights have been terminated and not permanently+reinstated, you do not qualify to receive new licenses for the same+material under section 10.++9. Acceptance Not Required for Having Copies.++You are not required to accept this License in order to receive or+run a copy of the Program. Ancillary propagation of a covered work+occurring solely as a consequence of using peer-to-peer transmission+to receive a copy likewise does not require acceptance. However,+nothing other than this License grants you permission to propagate or+modify any covered work. These actions infringe copyright if you do+not accept this License. Therefore, by modifying or propagating a+covered work, you indicate your acceptance of this License to do so.++10. Automatic Licensing of Downstream Recipients.++Each time you convey a covered work, the recipient automatically+receives a license from the original licensors, to run, modify and+propagate that work, subject to this License. You are not responsible+for enforcing compliance by third parties with this License.++An "entity transaction" is a transaction transferring control of an+organization, or substantially all assets of one, or subdividing an+organization, or merging organizations. If propagation of a covered+work results from an entity transaction, each party to that+transaction who receives a copy of the work also receives whatever+licenses to the work the party's predecessor in interest had or could+give under the previous paragraph, plus a right to possession of the+Corresponding Source of the work from the predecessor in interest, if+the predecessor has it or can get it with reasonable efforts.++You may not impose any further restrictions on the exercise of the+rights granted or affirmed under this License. For example, you may+not impose a license fee, royalty, or other charge for exercise of+rights granted under this License, and you may not initiate litigation+(including a cross-claim or counterclaim in a lawsuit) alleging that+any patent claim is infringed by making, using, selling, offering for+sale, or importing the Program or any portion of it.++11. Patents.++A "contributor" is a copyright holder who authorizes use under this+License of the Program or a work on which the Program is based. The+work thus licensed is called the contributor's "contributor version".++A contributor's "essential patent claims" are all patent claims+owned or controlled by the contributor, whether already acquired or+hereafter acquired, that would be infringed by some manner, permitted+by this License, of making, using, or selling its contributor version,+but do not include claims that would be infringed only as a+consequence of further modification of the contributor version. For+purposes of this definition, "control" includes the right to grant+patent sublicenses in a manner consistent with the requirements of+this License.++Each contributor grants you a non-exclusive, worldwide, royalty-free+patent license under the contributor's essential patent claims, to+make, use, sell, offer for sale, import and otherwise run, modify and+propagate the contents of its contributor version.++In the following three paragraphs, a "patent license" is any express+agreement or commitment, however denominated, not to enforce a patent+(such as an express permission to practice a patent or covenant not to+sue for patent infringement). To "grant" such a patent license to a+party means to make such an agreement or commitment not to enforce a+patent against the party.++If you convey a covered work, knowingly relying on a patent license,+and the Corresponding Source of the work is not available for anyone+to copy, free of charge and under the terms of this License, through a+publicly available network server or other readily accessible means,+then you must either (1) cause the Corresponding Source to be so+available, or (2) arrange to deprive yourself of the benefit of the+patent license for this particular work, or (3) arrange, in a manner+consistent with the requirements of this License, to extend the patent+license to downstream recipients. "Knowingly relying" means you have+actual knowledge that, but for the patent license, your conveying the+covered work in a country, or your recipient's use of the covered work+in a country, would infringe one or more identifiable patents in that+country that you have reason to believe are valid.++If, pursuant to or in connection with a single transaction or+arrangement, you convey, or propagate by procuring conveyance of, a+covered work, and grant a patent license to some of the parties+receiving the covered work authorizing them to use, propagate, modify+or convey a specific copy of the covered work, then the patent license+you grant is automatically extended to all recipients of the covered+work and works based on it.++A patent license is "discriminatory" if it does not include within+the scope of its coverage, prohibits the exercise of, or is+conditioned on the non-exercise of one or more of the rights that are+specifically granted under this License. You may not convey a covered+work if you are a party to an arrangement with a third party that is+in the business of distributing software, under which you make payment+to the third party based on the extent of your activity of conveying+the work, and under which the third party grants, to any of the+parties who would receive the covered work from you, a discriminatory+patent license (a) in connection with copies of the covered work+conveyed by you (or copies made from those copies), or (b) primarily+for and in connection with specific products or compilations that+contain the covered work, unless you entered into that arrangement,+or that patent license was granted, prior to 28 March 2007.++Nothing in this License shall be construed as excluding or limiting+any implied license or other defenses to infringement that may+otherwise be available to you under applicable patent law.++12. No Surrender of Others' Freedom.++If conditions are imposed on you (whether by court order, agreement or+otherwise) that contradict the conditions of this License, they do not+excuse you from the conditions of this License. If you cannot convey a+covered work so as to satisfy simultaneously your obligations under this+License and any other pertinent obligations, then as a consequence you may+not convey it at all. For example, if you agree to terms that obligate you+to collect a royalty for further conveying from those to whom you convey+the Program, the only way you could satisfy both those terms and this+License would be to refrain entirely from conveying the Program.++13. Remote Network Interaction; Use with the GNU General Public License.++Notwithstanding any other provision of this License, if you modify the+Program, your modified version must prominently offer all users+interacting with it remotely through a computer network (if your version+supports such interaction) an opportunity to receive the Corresponding+Source of your version by providing access to the Corresponding Source+from a network server at no charge, through some standard or customary+means of facilitating copying of software. This Corresponding Source+shall include the Corresponding Source for any work covered by version 3+of the GNU General Public License that is incorporated pursuant to the+following paragraph.++Notwithstanding any other provision of this License, you have+permission to link or combine any covered work with a work licensed+under version 3 of the GNU General Public License into a single+combined work, and to convey the resulting work. The terms of this+License will continue to apply to the part which is the covered work,+but the work with which it is combined will remain governed by version+3 of the GNU General Public License.++14. Revised Versions of this License.++The Free Software Foundation may publish revised and/or new versions of+the GNU Affero General Public License from time to time. Such new versions+will be similar in spirit to the present version, but may differ in detail to+address new problems or concerns.++Each version is given a distinguishing version number. If the+Program specifies that a certain numbered version of the GNU Affero General+Public License "or any later version" applies to it, you have the+option of following the terms and conditions either of that numbered+version or of any later version published by the Free Software+Foundation. If the Program does not specify a version number of the+GNU Affero General Public License, you may choose any version ever published+by the Free Software Foundation.++If the Program specifies that a proxy can decide which future+versions of the GNU Affero General Public License can be used, that proxy's+public statement of acceptance of a version permanently authorizes you+to choose that version for the Program.++Later license versions may give you additional or different+permissions. However, no additional obligations are imposed on any+author or copyright holder as a result of your choosing to follow a+later version.++15. Disclaimer of Warranty.++THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.++16. Limitation of Liability.++IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF+SUCH DAMAGES.++17. Interpretation of Sections 15 and 16.++If the disclaimer of warranty and limitation of liability provided+above cannot be given local legal effect according to their terms,+reviewing courts shall apply local law that most closely approximates+an absolute waiver of all civil liability in connection with the+Program, unless a warranty or assumption of liability accompanies a+copy of the Program in return for a fee.++ END OF TERMS AND CONDITIONS++ How to Apply These Terms to Your New Programs++If you develop a new program, and you want it to be of the greatest+possible use to the public, the best way to achieve this is to make it+free software which everyone can redistribute and change under these terms.++To do so, attach the following notices to the program. It is safest+to attach them to the start of each source file to most effectively+state the exclusion of warranty; and each file should have at least+the "copyright" line and a pointer to where the full notice is found.++ <one line to give the program's name and a brief idea of what it does.>+ Copyright (C) <year> <name of author>++ This program is free software: you can redistribute it and/or modify+ it under the terms of the GNU Affero General Public License as published by+ the Free Software Foundation, either version 3 of the License, or+ (at your option) any later version.++ This program is distributed in the hope that it will be useful,+ but WITHOUT ANY WARRANTY; without even the implied warranty of+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ GNU Affero General Public License for more details.++ You should have received a copy of the GNU Affero General Public License+ along with this program. If not, see <https://www.gnu.org/licenses/>.++Also add information on how to contact you by electronic and paper mail.++If your software can interact with users remotely through a computer+network, you should also make sure that it provides a way for users to+get its source. For example, if your program is a web application, its+interface could display a "Source" link that leads users to an archive+of the code. There are many ways you could offer source, and different+solutions will be better for different programs; see section 13 for the+specific requirements.++You should also get your employer (if you work as a programmer) or school,+if any, to sign a "copyright disclaimer" for the program, if necessary.+For more information on this, and how to apply and follow the GNU AGPL, see+<https://www.gnu.org/licenses/>.diff --git a/apps/desktop/resources/README.md b/apps/desktop/resources/README.mdnew file mode 100644index 0000000..cf1ded5--- /dev/null+++ b/apps/desktop/resources/README.md@@ -0,0 +1,26 @@+# App icon++`icon.svg` is the source for the Relay II app icon. The About screen and favicon reference it directly.+It combines the selected Relay II silhouette with a blue-violet rounded tile, lavender and white+raised faces, and soft shadows. The SVG has a 512 × 512 viewBox and a transparent outer canvas.+All artwork, lighting, and shadows remain vector SVG elements; there are no embedded raster images.++The sidebar uses `icon-mark.svg`, the same silhouette with no tile or shadows. The icon and wordmark+are white in dark mode and black in light mode; the light theme recolours the SVG image with CSS.+A colour-inheriting version is in `design/brand/relay-ii/mark.svg`.++The desktop window and Linux package use `icon.png`. The tray uses `tray.png`+and `tray-unread.png`, with matching `@2x` assets for high-density displays.+These are generated from the same SVG; the unread variant adds a pale badge with an indigo outline.+The badge is positioned relative to the SVG viewBox.++After editing the SVG, regenerate the PNGs from the repository root with+Python 3 and librsvg's `rsvg-convert` installed:++```sh+python scripts/icon.py+```++Use `--renderer /path/to/rsvg-convert` if the converter is not on `PATH`.++`LICENSE` is a verbatim copy of the repository-root license so desktop packages include it. Keep the copies identical.diff --git a/apps/desktop/resources/icon-mark.svg b/apps/desktop/resources/icon-mark.svgnew file mode 100644index 0000000..304b67e--- /dev/null+++ b/apps/desktop/resources/icon-mark.svg@@ -0,0 +1,4 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 96 96" fill="#ffffff">+ <path d="M8 20h21l21 28-21 28H8l23-28Z"/>+ <path d="M37 20h22c12 0 24 11 29 28-5 17-17 28-29 28H37l21-28Z"/>+</svg>diff --git a/apps/desktop/resources/icon.png b/apps/desktop/resources/icon.pngnew file mode 100644index 0000000..cea1ad1Binary files /dev/null and b/apps/desktop/resources/icon.png differdiff --git a/apps/desktop/resources/icon.svg b/apps/desktop/resources/icon.svgnew file mode 100644index 0000000..d7e14c4--- /dev/null+++ b/apps/desktop/resources/icon.svg@@ -0,0 +1,81 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" fill="none">+ <defs>+ <path id="tile" d="M154 32h204c78 0 114 36 114 114v204c0 78-36 114-114 114H154c-78 0-114-36-114-114V146C40 68 76 32 154 32Z"/>+ <path id="rear" d="M8 20h21l21 28-21 28H8l23-28Z"/>+ <path id="front" d="M37 20h22c12 0 24 11 29 28-5 17-17 28-29 28H37l21-28Z"/>+ <linearGradient id="tile-colour" x1="122" y1="32" x2="351" y2="466" gradientUnits="userSpaceOnUse">+ <stop stop-color="#6268ef"/>+ <stop offset=".42" stop-color="#484bd3"/>+ <stop offset="1" stop-color="#292397"/>+ </linearGradient>+ <radialGradient id="tile-light" cx=".43" cy=".08" r=".85">+ <stop stop-color="#a9b2ff" stop-opacity=".28"/>+ <stop offset=".7" stop-color="#737bff" stop-opacity="0"/>+ </radialGradient>+ <linearGradient id="tile-rim" x1="200" y1="32" x2="270" y2="464" gradientUnits="userSpaceOnUse">+ <stop stop-color="#e4e7ff" stop-opacity=".42"/>+ <stop offset=".4" stop-color="#959bf5" stop-opacity=".08"/>+ <stop offset="1" stop-color="#131064" stop-opacity=".48"/>+ </linearGradient>+ <linearGradient id="rear-face" x1="20" y1="20" x2="39" y2="80" gradientUnits="userSpaceOnUse">+ <stop stop-color="#eeefff"/>+ <stop offset=".47" stop-color="#c4c8ff"/>+ <stop offset="1" stop-color="#8d91ed"/>+ </linearGradient>+ <linearGradient id="front-face" x1="48" y1="20" x2="81" y2="80" gradientUnits="userSpaceOnUse">+ <stop stop-color="#ffffff"/>+ <stop offset=".34" stop-color="#f5f7ff"/>+ <stop offset=".68" stop-color="#d5dcff"/>+ <stop offset="1" stop-color="#abb4f8"/>+ </linearGradient>+ <linearGradient id="rear-side" x1="9" y1="34" x2="33" y2="80" gradientUnits="userSpaceOnUse">+ <stop stop-color="#777be1"/>+ <stop offset="1" stop-color="#5e5cc9"/>+ </linearGradient>+ <linearGradient id="front-side" x1="38" y1="30" x2="75" y2="81" gradientUnits="userSpaceOnUse">+ <stop stop-color="#c0c9ff"/>+ <stop offset="1" stop-color="#797bd5"/>+ </linearGradient>+ <linearGradient id="face-rim" x1="48" y1="20" x2="48" y2="76" gradientUnits="userSpaceOnUse">+ <stop stop-color="#fff" stop-opacity=".8"/>+ <stop offset=".5" stop-color="#f4f7ff" stop-opacity=".25"/>+ <stop offset="1" stop-color="#7679d6" stop-opacity=".25"/>+ </linearGradient>+ <linearGradient id="polish" x1="49" y1="24" x2="67" y2="68" gradientUnits="userSpaceOnUse">+ <stop stop-color="#fff" stop-opacity="0"/>+ <stop offset=".48" stop-color="#fff" stop-opacity=".18"/>+ <stop offset="1" stop-color="#fff" stop-opacity="0"/>+ </linearGradient>+ <clipPath id="front-clip"><use href="#front"/></clipPath>+ <filter id="tile-shadow" x="-25%" y="-25%" width="150%" height="160%" color-interpolation-filters="sRGB">+ <feGaussianBlur stdDeviation="12"/>+ </filter>+ <filter id="mark-shadow" x="-30%" y="-35%" width="160%" height="180%" color-interpolation-filters="sRGB">+ <feGaussianBlur stdDeviation="1.6"/>+ </filter>+ <filter id="contact-shadow" x="-20%" y="-20%" width="140%" height="150%" color-interpolation-filters="sRGB">+ <feGaussianBlur stdDeviation=".45"/>+ </filter>+ </defs>+ <use href="#tile" transform="translate(0 15)" fill="#24206b" opacity=".26" filter="url(#tile-shadow)"/>+ <use href="#tile" transform="translate(0 3)" fill="#251e86"/>+ <use href="#tile" fill="url(#tile-colour)"/>+ <use href="#tile" fill="url(#tile-light)"/>+ <use href="#tile" stroke="url(#tile-rim)" stroke-width="1.5"/>+ <g transform="translate(88 80) scale(3.5)">+ <g transform="translate(.5 3.7)" fill="#17115d" opacity=".55" filter="url(#mark-shadow)">+ <use href="#rear"/><use href="#front"/>+ </g>+ <g transform="translate(.15 2.25)" fill="#21196e" opacity=".55" filter="url(#contact-shadow)">+ <use href="#rear"/><use href="#front"/>+ </g>+ <use href="#rear" transform="translate(0 1.65)" fill="url(#rear-side)"/>+ <use href="#front" transform="translate(0 1.65)" fill="url(#front-side)"/>+ <use href="#rear" fill="url(#rear-face)"/>+ <use href="#front" fill="url(#front-face)"/>+ <path d="m35 20 53 36v16L35 36Z" fill="url(#polish)" clip-path="url(#front-clip)"/>+ <g stroke="url(#face-rim)" stroke-width=".28" stroke-linejoin="round">+ <use href="#rear"/><use href="#front"/>+ </g>+ </g>+</svg>diff --git a/apps/desktop/resources/tray-unread.png b/apps/desktop/resources/tray-unread.pngnew file mode 100644index 0000000..5fa7568Binary files /dev/null and b/apps/desktop/resources/tray-unread.png differdiff --git a/apps/desktop/resources/[email protected] b/apps/desktop/resources/[email protected]new file mode 100644index 0000000..3cd66c2Binary files /dev/null and b/apps/desktop/resources/[email protected] differdiff --git a/apps/desktop/resources/tray.png b/apps/desktop/resources/tray.pngnew file mode 100644index 0000000..1caacd4Binary files /dev/null and b/apps/desktop/resources/tray.png differdiff --git a/apps/desktop/resources/[email protected] b/apps/desktop/resources/[email protected]new file mode 100644index 0000000..36d586eBinary files /dev/null and b/apps/desktop/resources/[email protected] differdiff --git a/apps/desktop/src/main/discovery-transport.ts b/apps/desktop/src/main/discovery-transport.tsnew file mode 100644index 0000000..62d5784--- /dev/null+++ b/apps/desktop/src/main/discovery-transport.ts@@ -0,0 +1,51 @@+import { resolveSrv } from 'node:dns/promises'+import { discoverAccount, type DiscoveryTransport } from '@inlark/core'++const missing = new Set(['ENOTFOUND', 'ENODATA', 'NXDOMAIN', 'ENONAME'])++/** Anonymous, bounded requests for account discovery: no cookies, credentials, or redirects. */+export const nodeDiscoveryTransport: DiscoveryTransport = {+ async resolveSrv(name) {+ try {+ return await resolveSrv(name)+ } catch (error) {+ if (missing.has((error as NodeJS.ErrnoException).code || '')) return []+ throw error+ }+ },+ async get(value, { timeoutMs, maxBytes }) {+ const url = new URL(value)+ if (url.protocol !== 'https:' || url.username || url.password)+ throw new Error('Discovery only uses HTTPS.')+ const response = await fetch(url, {+ redirect: 'manual',+ credentials: 'omit',+ cache: 'no-store',+ referrerPolicy: 'no-referrer',+ signal: AbortSignal.timeout(timeoutMs),+ })+ const headers = Object.fromEntries(+ [...response.headers].map(([key, header]) => [key.toLowerCase(), header]),+ )+ if (Number(headers['content-length']) > maxBytes) {+ await response.body?.cancel()+ throw new Error('Discovery response is too large.')+ }+ const decoder = new TextDecoder()+ let body = ''+ let size = 0+ const reader = response.body?.getReader()+ while (reader) {+ const { done, value } = await reader.read()+ if (done) break+ size += value.byteLength+ if (size > maxBytes) {+ await reader.cancel()+ throw new Error('Discovery response is too large.')+ }+ body += decoder.decode(value, { stream: true })+ }+ return { status: response.status, headers, body: body + decoder.decode() }+ },+}+export const discover = (email: string) => discoverAccount(email, nodeDiscoveryTransport)diff --git a/apps/desktop/src/main/imap-accounts.ts b/apps/desktop/src/main/imap-accounts.tsnew file mode 100644index 0000000..e6cfbbd--- /dev/null+++ b/apps/desktop/src/main/imap-accounts.ts@@ -0,0 +1,24 @@+import { join } from 'node:path'+import { ImapProvider } from '@inlark/imap'+import { openWorkerIndex } from './imap-index/open'+import { openInProcessIndex } from './imap-index/sqlite-index'+import type { ProviderFactory } from './service'++/** Creates IMAP providers whose metadata index lives in a worker thread beside the connection. */+export const imapProviders: ProviderFactory = (input) => {+ if (input.config.protocol !== 'imap') throw new Error('Not an IMAP connection.')+ return new ImapProvider({+ connectionId: input.connectionId,+ name: input.name,+ config: input.config,+ password: input.secrets.password,+ outgoingPassword: input.secrets.outgoingPassword,+ folders: input.folders,+ // A connection test keeps nothing: its index lives only in memory.+ index: input.temporary+ ? openInProcessIndex(':memory:')+ : openWorkerIndex(join(input.directory, 'metadata.sqlite')),+ readAttachment: input.readAttachment,+ background: !input.temporary,+ })+}diff --git a/apps/desktop/src/main/imap-index/client.ts b/apps/desktop/src/main/imap-index/client.tsnew file mode 100644index 0000000..7cab749--- /dev/null+++ b/apps/desktop/src/main/imap-index/client.ts@@ -0,0 +1,135 @@+import type { MetadataIndex } from '@inlark/imap'++/** The part of `worker_threads.Worker` the client uses, so tests can supply a fake. */+export interface IndexPort {+ postMessage(value: unknown): void+ on(event: 'message', listener: (value: any) => void): unknown+ on(event: 'error', listener: (error: Error) => void): unknown+ on(event: 'exit', listener: (code: number) => void): unknown+ terminate(): Promise<number>+}++type Reply = { id: number; result?: unknown; error?: { message: string } }+type Args<K extends keyof MetadataIndex> = Parameters<MetadataIndex[K]>++/** Forwards every index call to the worker that owns the SQLite database. */+export class WorkerMetadataIndex implements MetadataIndex {+ private next = 1+ private readonly pending = new Map<+ number,+ { resolve: (value: unknown) => void; reject: (error: Error) => void }+ >()+ private failure: Error | undefined+ private closing: Promise<void> | undefined++ constructor(private readonly port: IndexPort) {+ port.on('message', (reply: Reply) => {+ const call = this.pending.get(reply.id)+ if (!call) return+ this.pending.delete(reply.id)+ if (reply.error) call.reject(new Error(reply.error.message))+ else call.resolve(reply.result)+ })+ port.on('error', (error) => this.fail(new Error(error.message || 'The mail index failed.')))+ port.on('exit', (code) =>+ this.fail(new Error('The mail index stopped unexpectedly (exit code ' + code + ').')),+ )+ }++ private fail(error: Error) {+ this.failure ??= error+ for (const call of this.pending.values()) call.reject(this.failure)+ this.pending.clear()+ }++ private call<K extends keyof MetadataIndex>(method: K, args: Args<K>) {+ return new Promise<unknown>((resolve, reject) => {+ if (this.failure) return reject(this.failure)+ if (this.closing && method !== 'close') return reject(new Error('The mail index is closed.'))+ const id = this.next+++ this.pending.set(id, { resolve, reject })+ try {+ this.port.postMessage({ id, method, args })+ } catch (error) {+ this.pending.delete(id)+ reject(error)+ }+ }) as ReturnType<MetadataIndex[K]>+ }++ close() {+ this.closing ??= (async () => {+ try {+ if (!this.failure) await this.call('close', [])+ } finally {+ this.failure ??= new Error('The mail index is closed.')+ await this.port.terminate()+ }+ })()+ return this.closing+ }++ syncMailboxes(...args: Args<'syncMailboxes'>) {+ return this.call('syncMailboxes', args)+ }+ listMailboxes(...args: Args<'listMailboxes'>) {+ return this.call('listMailboxes', args)+ }+ renameMailbox(...args: Args<'renameMailbox'>) {+ return this.call('renameMailbox', args)+ }+ updateMailbox(...args: Args<'updateMailbox'>) {+ return this.call('updateMailbox', args)+ }+ resetMailbox(...args: Args<'resetMailbox'>) {+ return this.call('resetMailbox', args)+ }+ upsertMessages(...args: Args<'upsertMessages'>) {+ return this.call('upsertMessages', args)+ }+ updateFlags(...args: Args<'updateFlags'>) {+ return this.call('updateFlags', args)+ }+ removeUids(...args: Args<'removeUids'>) {+ return this.call('removeUids', args)+ }+ removeMessages(...args: Args<'removeMessages'>) {+ return this.call('removeMessages', args)+ }+ knownUids(...args: Args<'knownUids'>) {+ return this.call('knownUids', args)+ }+ relocate(...args: Args<'relocate'>) {+ return this.call('relocate', args)+ }+ setPreview(...args: Args<'setPreview'>) {+ return this.call('setPreview', args)+ }+ messages(...args: Args<'messages'>) {+ return this.call('messages', args)+ }+ messagesAt(...args: Args<'messagesAt'>) {+ return this.call('messagesAt', args)+ }+ threadMessages(...args: Args<'threadMessages'>) {+ return this.call('threadMessages', args)+ }+ resolveThread(...args: Args<'resolveThread'>) {+ return this.call('resolveThread', args)+ }+ findByMessageId(...args: Args<'findByMessageId'>) {+ return this.call('findByMessageId', args)+ }+ conversations(...args: Args<'conversations'>) {+ return this.call('conversations', args)+ }+ counts(...args: Args<'counts'>) {+ return this.call('counts', args)+ }+ getMeta(...args: Args<'getMeta'>) {+ return this.call('getMeta', args)+ }+ setMeta(...args: Args<'setMeta'>) {+ return this.call('setMeta', args)+ }+}diff --git a/apps/desktop/src/main/imap-index/env.d.ts b/apps/desktop/src/main/imap-index/env.d.tsnew file mode 100644index 0000000..bf6bc62--- /dev/null+++ b/apps/desktop/src/main/imap-index/env.d.ts@@ -0,0 +1,5 @@+// electron-vite bundles `?modulePath` imports as separate entry chunks and yields their path.+declare module '*?modulePath' {+ const path: string+ export default path+}diff --git a/apps/desktop/src/main/imap-index/open.ts b/apps/desktop/src/main/imap-index/open.tsnew file mode 100644index 0000000..2f16207--- /dev/null+++ b/apps/desktop/src/main/imap-index/open.ts@@ -0,0 +1,9 @@+import { Worker } from 'node:worker_threads'+import type { MetadataIndex } from '@inlark/imap'+import { WorkerMetadataIndex } from './client'+import workerPath from './worker?modulePath'++/** Opens the IMAP metadata index in its own worker thread so SQLite never blocks the main process. */+export function openWorkerIndex(path: string): MetadataIndex {+ return new WorkerMetadataIndex(new Worker(workerPath, { workerData: { path } }))+}diff --git a/apps/desktop/src/main/imap-index/sqlite-index.ts b/apps/desktop/src/main/imap-index/sqlite-index.tsnew file mode 100644index 0000000..4e8a396--- /dev/null+++ b/apps/desktop/src/main/imap-index/sqlite-index.ts@@ -0,0 +1,971 @@+import { DatabaseSync, type SQLInputValue, type StatementSync } from 'node:sqlite'+import { chmodSync, closeSync, mkdirSync, openSync } from 'node:fs'+import { dirname } from 'node:path'+import { randomUUID } from 'node:crypto'+import type {+ ConversationCursor,+ ConversationFilter,+ ConversationRow,+ FolderListing,+ IndexedMailbox,+ IndexedMessage,+ MailboxStatePatch,+ MessageLocation,+ MetadataIndex,+ NewMessage,+} from '@inlark/imap'++/** The synchronous shape of `MetadataIndex`, as run inside the worker. */+export type SyncMetadataIndex = {+ [K in keyof MetadataIndex]: MetadataIndex[K] extends (...args: infer A) => Promise<infer R>+ ? (...args: A) => R+ : never+}++// A record forces this list to stay complete when the interface grows.+const methodTable: Record<keyof MetadataIndex, true> = {+ close: true,+ syncMailboxes: true,+ listMailboxes: true,+ renameMailbox: true,+ updateMailbox: true,+ resetMailbox: true,+ upsertMessages: true,+ updateFlags: true,+ removeUids: true,+ removeMessages: true,+ knownUids: true,+ relocate: true,+ setPreview: true,+ messages: true,+ messagesAt: true,+ threadMessages: true,+ resolveThread: true,+ findByMessageId: true,+ conversations: true,+ counts: true,+ getMeta: true,+ setMeta: true,+}+export const indexMethods = Object.keys(methodTable) as (keyof MetadataIndex)[]++export const SCHEMA_VERSION = 1+const MAX_REFERENCES = 50++const migrations = [+ `CREATE TABLE mailboxes (+ id TEXT PRIMARY KEY,+ account_id TEXT NOT NULL,+ path TEXT NOT NULL,+ name TEXT NOT NULL,+ delimiter TEXT NOT NULL,+ parent_path TEXT,+ special_use TEXT,+ guessed_special_use TEXT,+ no_select INTEGER NOT NULL,+ position INTEGER NOT NULL,+ uid_validity TEXT,+ uid_next INTEGER,+ highest_modseq TEXT,+ total INTEGER NOT NULL DEFAULT 0,+ unread INTEGER NOT NULL DEFAULT 0,+ indexed_from INTEGER,+ complete INTEGER NOT NULL DEFAULT 0,+ UNIQUE (account_id, path),+ UNIQUE (account_id, id)+ );+ CREATE TABLE messages (+ seq INTEGER PRIMARY KEY,+ id TEXT NOT NULL UNIQUE,+ account_id TEXT NOT NULL,+ mailbox_id TEXT NOT NULL,+ uid_validity TEXT NOT NULL,+ uid INTEGER NOT NULL,+ modseq TEXT,+ message_id TEXT,+ in_reply_to TEXT NOT NULL,+ refs TEXT NOT NULL,+ thread_id TEXT NOT NULL,+ subject TEXT NOT NULL,+ from_addr TEXT NOT NULL,+ to_addr TEXT NOT NULL,+ cc_addr TEXT NOT NULL,+ bcc_addr TEXT NOT NULL,+ reply_to TEXT NOT NULL,+ received_at TEXT NOT NULL,+ received_ms INTEGER NOT NULL,+ sent_at TEXT,+ size INTEGER NOT NULL,+ flags TEXT NOT NULL,+ seen INTEGER NOT NULL,+ flagged INTEGER NOT NULL,+ has_attachment INTEGER NOT NULL,+ preview TEXT NOT NULL,+ body_structure TEXT,+ unsubscribe TEXT,+ UNIQUE (account_id, mailbox_id, uid, uid_validity),+ FOREIGN KEY (account_id, mailbox_id) REFERENCES mailboxes (account_id, id) ON DELETE CASCADE+ );+ CREATE INDEX messages_mailbox_thread ON messages (account_id, mailbox_id, thread_id, received_ms);+ CREATE INDEX messages_thread ON messages (account_id, thread_id, received_ms, mailbox_id);+ CREATE INDEX messages_message_id ON messages (account_id, message_id) WHERE message_id IS NOT NULL;+ CREATE INDEX messages_unseen ON messages (account_id, thread_id, received_ms) WHERE seen = 0;+ CREATE INDEX messages_flagged ON messages (account_id, thread_id, received_ms) WHERE flagged = 1;+ CREATE TABLE threads (+ seq INTEGER PRIMARY KEY,+ account_id TEXT NOT NULL,+ id TEXT NOT NULL,+ UNIQUE (account_id, id)+ );+ CREATE TABLE thread_refs (+ account_id TEXT NOT NULL,+ message_id TEXT NOT NULL,+ thread_id TEXT NOT NULL,+ PRIMARY KEY (account_id, message_id)+ ) WITHOUT ROWID;+ CREATE INDEX thread_refs_thread ON thread_refs (account_id, thread_id);+ CREATE TABLE thread_aliases (+ account_id TEXT NOT NULL,+ alias TEXT NOT NULL,+ thread_id TEXT NOT NULL,+ PRIMARY KEY (account_id, alias)+ ) WITHOUT ROWID;+ CREATE INDEX thread_aliases_thread ON thread_aliases (account_id, thread_id);+ CREATE TABLE meta (+ account_id TEXT NOT NULL,+ key TEXT NOT NULL,+ value TEXT NOT NULL,+ PRIMARY KEY (account_id, key)+ ) WITHOUT ROWID;`,+]++interface MailboxRow {+ id: string+ path: string+ name: string+ delimiter: string+ parent_path: string | null+ special_use: string | null+ guessed_special_use: string | null+ no_select: number+ uid_validity: string | null+ uid_next: number | null+ highest_modseq: string | null+ total: number+ unread: number+ indexed_from: number | null+ complete: number+}++interface MessageRow {+ seq: number+ id: string+ mailbox_id: string+ uid_validity: string+ uid: number+ modseq: string | null+ message_id: string | null+ in_reply_to: string+ refs: string+ thread_id: string+ subject: string+ from_addr: string+ to_addr: string+ cc_addr: string+ bcc_addr: string+ reply_to: string+ received_at: string+ sent_at: string | null+ size: number+ flags: string+ has_attachment: number+ preview: string+ body_structure: string | null+ unsubscribe: string | null+}++/** Message-IDs without brackets or whitespace; a header value may hold several. */+function messageIds(values: (string | null | undefined)[]) {+ const ids: string[] = []+ for (const value of values)+ if (value) for (const id of value.split(/[\s<>]+/)) if (id && !ids.includes(id)) ids.push(id)+ return ids+}++function hasFlag(flags: string[], flag: string) {+ return flags.some((value) => value.toLowerCase() === flag) ? 1 : 0+}++function time(value: string) {+ const ms = Date.parse(value)+ return Number.isFinite(ms) ? ms : 0+}++const json = (value: unknown) => JSON.stringify(value)+const list = (values: readonly unknown[]) => JSON.stringify(values)++function toMailbox(row: MailboxRow): IndexedMailbox {+ return {+ id: row.id,+ path: row.path,+ name: row.name,+ delimiter: row.delimiter,+ parentPath: row.parent_path,+ specialUse: row.special_use,+ guessedSpecialUse: row.guessed_special_use,+ noSelect: row.no_select === 1,+ uidValidity: row.uid_validity,+ uidNext: row.uid_next,+ highestModseq: row.highest_modseq,+ total: row.total,+ unread: row.unread,+ indexedFrom: row.indexed_from,+ complete: row.complete === 1,+ }+}++function toMessage(row: MessageRow): IndexedMessage {+ const message: IndexedMessage = {+ id: row.id,+ threadId: row.thread_id,+ mailboxId: row.mailbox_id,+ uidValidity: row.uid_validity,+ uid: row.uid,+ messageId: row.message_id,+ inReplyTo: JSON.parse(row.in_reply_to),+ references: JSON.parse(row.refs),+ subject: row.subject,+ from: JSON.parse(row.from_addr),+ to: JSON.parse(row.to_addr),+ cc: JSON.parse(row.cc_addr),+ bcc: JSON.parse(row.bcc_addr),+ replyTo: JSON.parse(row.reply_to),+ receivedAt: row.received_at,+ size: row.size,+ flags: JSON.parse(row.flags),+ hasAttachment: row.has_attachment === 1,+ preview: row.preview,+ }+ if (row.modseq !== null) message.modseq = row.modseq+ if (row.sent_at !== null) message.sentAt = row.sent_at+ if (row.body_structure !== null) message.bodyStructure = JSON.parse(row.body_structure)+ if (row.unsubscribe !== null) message.unsubscribe = JSON.parse(row.unsubscribe)+ return message+}++const MESSAGE_COLUMNS = `seq, id, mailbox_id, uid_validity, uid, modseq, message_id, in_reply_to, refs,+ thread_id, subject, from_addr, to_addr, cc_addr, bcc_addr, reply_to, received_at, sent_at, size,+ flags, has_attachment, preview, body_structure, unsubscribe`++function prepareFile(path: string) {+ if (path === ':memory:') return+ // A new directory and file are private; an existing directory is left as the caller made it.+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 })+ closeSync(openSync(path, 'a', 0o600))+ chmodSync(path, 0o600)+}++/**+ * The SQLite IMAP metadata index. All methods are synchronous; the desktop app runs this in a+ * worker thread so large transactions never block the main process.+ */+export class SqliteMetadataIndex implements SyncMetadataIndex {+ private readonly db: DatabaseSync+ private readonly statements = new Map<string, StatementSync>()+ private closed = false++ constructor(path: string) {+ prepareFile(path)+ const db = new DatabaseSync(path, { timeout: 5000 })+ try {+ // Checked before any pragma that writes, so a newer file is never modified.+ const version = Number(+ (db.prepare('PRAGMA user_version').get() as { user_version: number }).user_version,+ )+ if (version > SCHEMA_VERSION)+ throw new Error(+ 'The mail index was created by a newer version of Inlark (schema ' ++ version ++ '). It has been left unchanged.',+ )+ db.exec(+ `PRAGMA journal_mode = WAL; PRAGMA synchronous = NORMAL; PRAGMA foreign_keys = ON;+ PRAGMA cache_size = -32768; PRAGMA temp_store = MEMORY`,+ )+ for (let from = version; from < SCHEMA_VERSION; from++) {+ db.exec('BEGIN IMMEDIATE')+ try {+ db.exec(migrations[from]!)+ db.exec('PRAGMA user_version = ' + (from + 1))+ db.exec('COMMIT')+ } catch (error) {+ if (db.isTransaction) db.exec('ROLLBACK')+ throw error+ }+ }+ } catch (error) {+ db.close()+ throw error+ }+ this.db = db+ }++ private stmt(sql: string) {+ let statement = this.statements.get(sql)+ if (!statement) {+ if (this.closed) throw new Error('The mail index is closed.')+ statement = this.db.prepare(sql)+ this.statements.set(sql, statement)+ }+ return statement+ }+ private run(sql: string, ...params: SQLInputValue[]) {+ return this.stmt(sql).run(...params)+ }+ private get<T>(sql: string, ...params: SQLInputValue[]) {+ return this.stmt(sql).get(...params) as T | undefined+ }+ private all<T>(sql: string, ...params: SQLInputValue[]) {+ return this.stmt(sql).all(...params) as T[]+ }+ private tx<T>(fn: () => T): T {+ if (this.closed) throw new Error('The mail index is closed.')+ this.db.exec('BEGIN IMMEDIATE')+ try {+ const result = fn()+ this.db.exec('COMMIT')+ return result+ } catch (error) {+ if (this.db.isTransaction) this.db.exec('ROLLBACK')+ throw error+ }+ }++ close() {+ if (this.closed) return+ this.closed = true+ this.statements.clear()+ this.db.close()+ }++ syncMailboxes(accountId: string, folders: FolderListing[]) {+ this.tx(() => {+ const known = new Map(+ this.all<{ id: string; path: string }>(+ 'SELECT id, path FROM mailboxes WHERE account_id = ?',+ accountId,+ ).map((row) => [row.path, row.id]),+ )+ const listed = new Set<string>()+ folders.forEach((folder, position) => {+ if (listed.has(folder.path)) return+ listed.add(folder.path)+ const fields = [+ folder.name,+ folder.delimiter,+ folder.parentPath,+ folder.specialUse,+ folder.guessedSpecialUse,+ folder.noSelect ? 1 : 0,+ position,+ ]+ const id = known.get(folder.path)+ if (id)+ this.run(+ `UPDATE mailboxes SET name = ?, delimiter = ?, parent_path = ?, special_use = ?,+ guessed_special_use = ?, no_select = ?, position = ? WHERE account_id = ? AND id = ?`,+ ...fields,+ accountId,+ id,+ )+ else+ this.run(+ `INSERT INTO mailboxes (id, account_id, path, name, delimiter, parent_path, special_use,+ guessed_special_use, no_select, position) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,+ randomUUID(),+ accountId,+ folder.path,+ ...fields,+ )+ })+ for (const [path, id] of known)+ if (!listed.has(path))+ this.run('DELETE FROM mailboxes WHERE account_id = ? AND id = ?', accountId, id)+ })+ return this.listMailboxes(accountId)+ }++ listMailboxes(accountId: string) {+ return this.all<MailboxRow>(+ 'SELECT * FROM mailboxes WHERE account_id = ? ORDER BY position, path',+ accountId,+ ).map(toMailbox)+ }++ private mailbox(accountId: string, mailboxId: string) {+ const row = this.get<MailboxRow>(+ 'SELECT * FROM mailboxes WHERE account_id = ? AND id = ?',+ accountId,+ mailboxId,+ )+ if (!row) throw new Error('Unknown mailbox in the mail index.')+ return row+ }++ renameMailbox(accountId: string, mailboxId: string, path: string, name: string) {+ this.tx(() => {+ const mailbox = this.mailbox(accountId, mailboxId)+ if (mailbox.path === path) {+ this.run('UPDATE mailboxes SET name = ? WHERE id = ?', name, mailboxId)+ return+ }+ if (this.get('SELECT 1 FROM mailboxes WHERE account_id = ? AND path = ?', accountId, path))+ throw new Error('Another mailbox already uses this path.')+ const separator = mailbox.delimiter ? path.lastIndexOf(mailbox.delimiter) : -1+ this.run(+ 'UPDATE mailboxes SET path = ?, name = ?, parent_path = ? WHERE id = ?',+ path,+ name,+ separator > 0 ? path.slice(0, separator) : null,+ mailboxId,+ )+ // IMAP renames descendants with their parent; keeping their IDs keeps their messages.+ if (!mailbox.delimiter) return+ const prefix = mailbox.path + mailbox.delimiter+ for (const child of this.all<{ id: string; path: string; parent_path: string | null }>(+ 'SELECT id, path, parent_path FROM mailboxes WHERE account_id = ? AND substr(path, 1, ?) = ?',+ accountId,+ prefix.length,+ prefix,+ )) {+ const rewrite = (value: string) => path + value.slice(mailbox.path.length)+ this.run(+ 'UPDATE mailboxes SET path = ?, parent_path = ? WHERE id = ?',+ rewrite(child.path),+ child.parent_path === mailbox.path || child.parent_path?.startsWith(prefix)+ ? rewrite(child.parent_path)+ : child.parent_path,+ child.id,+ )+ }+ })+ }++ updateMailbox(accountId: string, mailboxId: string, patch: MailboxStatePatch) {+ this.tx(() => {+ this.mailbox(accountId, mailboxId)+ if (+ patch.uidValidity != null &&+ this.get(+ 'SELECT 1 FROM messages WHERE account_id = ? AND mailbox_id = ? AND uid_validity <> ? LIMIT 1',+ accountId,+ mailboxId,+ patch.uidValidity,+ )+ )+ throw new Error('The mailbox UIDVALIDITY changed; reset the mailbox before indexing it.')+ const columns: Record<keyof MailboxStatePatch, string> = {+ uidValidity: 'uid_validity',+ uidNext: 'uid_next',+ highestModseq: 'highest_modseq',+ total: 'total',+ unread: 'unread',+ indexedFrom: 'indexed_from',+ complete: 'complete',+ }+ const sets: string[] = []+ const params: SQLInputValue[] = []+ for (const key of Object.keys(columns) as (keyof MailboxStatePatch)[]) {+ const value = patch[key]+ if (value === undefined) continue+ sets.push(columns[key] + ' = ?')+ params.push(typeof value === 'boolean' ? (value ? 1 : 0) : value)+ }+ if (sets.length)+ this.run('UPDATE mailboxes SET ' + sets.join(', ') + ' WHERE id = ?', ...params, mailboxId)+ })+ }++ resetMailbox(accountId: string, mailboxId: string, uidValidity: string) {+ this.tx(() => {+ this.mailbox(accountId, mailboxId)+ this.run('DELETE FROM messages WHERE account_id = ? AND mailbox_id = ?', accountId, mailboxId)+ this.run(+ `UPDATE mailboxes SET uid_validity = ?, uid_next = NULL, highest_modseq = NULL,+ indexed_from = NULL, complete = 0 WHERE id = ?`,+ uidValidity,+ mailboxId,+ )+ })+ }++ /**+ * Every stored location in a mailbox carries the mailbox's current UIDVALIDITY, so a stale+ * location can never be written. `validities` caches the answer for one transaction.+ */+ private checkLocation(+ accountId: string,+ location: MessageLocation,+ validities: Map<string, string>,+ ) {+ let current = validities.get(location.mailboxId)+ if (current === undefined) {+ current =+ this.mailbox(accountId, location.mailboxId).uid_validity ??+ this.get<{ v: string }>(+ 'SELECT uid_validity AS v FROM messages WHERE account_id = ? AND mailbox_id = ? LIMIT 1',+ accountId,+ location.mailboxId,+ )?.v ??+ location.uidValidity+ validities.set(location.mailboxId, current)+ }+ if (current !== location.uidValidity)+ throw new Error('The message location has a stale UIDVALIDITY for its mailbox.')+ }++ private newThread(accountId: string) {+ const id = randomUUID()+ this.run('INSERT INTO threads (account_id, id) VALUES (?, ?)', accountId, id)+ return id+ }++ /**+ * Finds every thread already known for the message's own ID or its parents. Several threads+ * mean the message links them, so they merge into the oldest; the others become aliases.+ */+ private assignThread(accountId: string, keys: string[]) {+ if (!keys.length) return this.newThread(accountId)+ const found = this.all<{ id: string; seq: number | null }>(+ `SELECT DISTINCT r.thread_id AS id, t.seq AS seq FROM json_each(?) j+ CROSS JOIN thread_refs r ON r.account_id = ? AND r.message_id = j.value+ LEFT JOIN threads t ON t.account_id = r.account_id AND t.id = r.thread_id`,+ list(keys),+ accountId,+ )+ found.sort((a, b) => (a.seq ?? Infinity) - (b.seq ?? Infinity) || (a.id < b.id ? -1 : 1))+ const thread = found[0]?.id ?? this.newThread(accountId)+ for (const { id: loser } of found.slice(1)) {+ this.run(+ 'UPDATE messages SET thread_id = ? WHERE account_id = ? AND thread_id = ?',+ thread,+ accountId,+ loser,+ )+ this.run(+ 'UPDATE thread_refs SET thread_id = ? WHERE account_id = ? AND thread_id = ?',+ thread,+ accountId,+ loser,+ )+ this.run(+ 'UPDATE thread_aliases SET thread_id = ? WHERE account_id = ? AND thread_id = ?',+ thread,+ accountId,+ loser,+ )+ this.run(+ `INSERT INTO thread_aliases (account_id, alias, thread_id) VALUES (?, ?, ?)+ ON CONFLICT DO UPDATE SET thread_id = excluded.thread_id`,+ accountId,+ loser,+ thread,+ )+ this.run('DELETE FROM threads WHERE account_id = ? AND id = ?', accountId, loser)+ }+ this.run(+ `INSERT INTO thread_refs (account_id, message_id, thread_id)+ SELECT ?, value, ? FROM json_each(?) WHERE true ON CONFLICT DO NOTHING`,+ accountId,+ thread,+ list(keys),+ )+ return thread+ }++ upsertMessages(accountId: string, messages: NewMessage[]) {+ return this.tx(() => {+ const validities = new Map<string, string>()+ return messages.map((message) => {+ this.checkLocation(accountId, message, validities)+ const seen = hasFlag(message.flags, '\\seen')+ const flagged = hasFlag(message.flags, '\\flagged')+ const existing = this.get<{ id: string }>(+ `SELECT id FROM messages+ WHERE account_id = ? AND mailbox_id = ? AND uid = ? AND uid_validity = ?`,+ accountId,+ message.mailboxId,+ message.uid,+ message.uidValidity,+ )+ if (existing) {+ this.run(+ `UPDATE messages SET flags = ?, seen = ?, flagged = ?, modseq = coalesce(?, modseq),+ preview = CASE WHEN ? <> '' THEN ? ELSE preview END WHERE id = ?`,+ list(message.flags),+ seen,+ flagged,+ message.modseq ?? null,+ message.preview,+ message.preview,+ existing.id,+ )+ return existing.id+ }+ const [messageId = null] = messageIds([message.messageId])+ const references = message.references.slice(-MAX_REFERENCES)+ const parents = messageIds([...message.inReplyTo, ...references]).filter(+ (id) => id !== messageId,+ )+ const threadId = this.assignThread(accountId, messageId ? [messageId, ...parents] : parents)+ const id = randomUUID()+ this.run(+ `INSERT INTO messages (id, account_id, mailbox_id, uid_validity, uid, modseq, message_id,+ in_reply_to, refs, thread_id, subject, from_addr, to_addr, cc_addr, bcc_addr, reply_to,+ received_at, received_ms, sent_at, size, flags, seen, flagged, has_attachment, preview,+ body_structure, unsubscribe)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,+ id,+ accountId,+ message.mailboxId,+ message.uidValidity,+ message.uid,+ message.modseq ?? null,+ messageId,+ list(message.inReplyTo),+ list(references),+ threadId,+ message.subject,+ list(message.from),+ list(message.to),+ list(message.cc),+ list(message.bcc),+ list(message.replyTo),+ message.receivedAt,+ time(message.receivedAt),+ message.sentAt ?? null,+ message.size,+ list(message.flags),+ seen,+ flagged,+ message.hasAttachment ? 1 : 0,+ message.preview,+ message.bodyStructure ? json(message.bodyStructure) : null,+ message.unsubscribe ? json(message.unsubscribe) : null,+ )+ return id+ })+ })+ }++ updateFlags(+ accountId: string,+ mailboxId: string,+ updates: { uid: number; flags: string[]; modseq?: string }[],+ ) {+ this.tx(() => {+ for (const update of updates)+ this.run(+ `UPDATE messages SET flags = ?, seen = ?, flagged = ?, modseq = coalesce(?, modseq)+ WHERE account_id = ? AND mailbox_id = ? AND uid = ?`,+ list(update.flags),+ hasFlag(update.flags, '\\seen'),+ hasFlag(update.flags, '\\flagged'),+ update.modseq ?? null,+ accountId,+ mailboxId,+ update.uid,+ )+ })+ }++ removeUids(accountId: string, mailboxId: string, uids: number[]) {+ if (!uids.length) return+ this.tx(() => {+ this.run(+ `DELETE FROM messages WHERE account_id = ? AND mailbox_id = ?+ AND uid IN (SELECT value FROM json_each(?))`,+ accountId,+ mailboxId,+ list(uids),+ )+ })+ }++ removeMessages(accountId: string, ids: string[]) {+ if (!ids.length) return+ this.tx(() => {+ this.run(+ 'DELETE FROM messages WHERE +account_id = ? AND id IN (SELECT value FROM json_each(?))',+ accountId,+ list(ids),+ )+ })+ }++ knownUids(accountId: string, mailboxId: string) {+ return this.all<{ uid: number }>(+ 'SELECT uid FROM messages WHERE account_id = ? AND mailbox_id = ? ORDER BY uid',+ accountId,+ mailboxId,+ ).map((row) => row.uid)+ }++ relocate(accountId: string, id: string, location: MessageLocation) {+ this.tx(() => {+ this.checkLocation(accountId, location, new Map())+ if (!this.get('SELECT 1 FROM messages WHERE account_id = ? AND id = ?', accountId, id))+ throw new Error('Unknown message in the mail index.')+ // The confirmed move identifies this message; a copy indexed there meanwhile is the same one.+ this.run(+ `DELETE FROM messages WHERE account_id = ? AND mailbox_id = ? AND uid = ?+ AND uid_validity = ? AND id <> ?`,+ accountId,+ location.mailboxId,+ location.uid,+ location.uidValidity,+ id,+ )+ this.run(+ `UPDATE messages SET mailbox_id = ?, uid_validity = ?, uid = ?, modseq = NULL+ WHERE account_id = ? AND id = ?`,+ location.mailboxId,+ location.uidValidity,+ location.uid,+ accountId,+ id,+ )+ })+ }++ setPreview(accountId: string, id: string, preview: string) {+ this.run(+ 'UPDATE messages SET preview = ? WHERE account_id = ? AND id = ?',+ preview,+ accountId,+ id,+ )+ }++ messages(accountId: string, ids: string[]) {+ if (!ids.length) return []+ // The unary plus keeps the planner on the ID index instead of scanning the account.+ return this.all<MessageRow>(+ `SELECT ${MESSAGE_COLUMNS} FROM messages+ WHERE +account_id = ? AND id IN (SELECT value FROM json_each(?))`,+ accountId,+ list(ids),+ ).map(toMessage)+ }++ messagesAt(accountId: string, mailboxId: string, uids: number[]) {+ if (!uids.length) return []+ return this.all<MessageRow>(+ `SELECT ${MESSAGE_COLUMNS} FROM messages WHERE account_id = ? AND mailbox_id = ?+ AND uid IN (SELECT value FROM json_each(?)) ORDER BY uid`,+ accountId,+ mailboxId,+ list(uids),+ ).map(toMessage)+ }++ threadMessages(accountId: string, threadIds: string[]) {+ if (!threadIds.length) return []+ return this.all<MessageRow>(+ `SELECT ${MESSAGE_COLUMNS} FROM messages WHERE account_id = ? AND thread_id IN (+ SELECT coalesce(a.thread_id, t.value) FROM json_each(?) t+ LEFT JOIN thread_aliases a ON a.account_id = ? AND a.alias = t.value)+ ORDER BY received_ms, seq`,+ accountId,+ list(threadIds),+ accountId,+ ).map(toMessage)+ }++ resolveThread(accountId: string, threadId: string) {+ return (+ this.get<{ thread_id: string }>(+ 'SELECT thread_id FROM thread_aliases WHERE account_id = ? AND alias = ?',+ accountId,+ threadId,+ )?.thread_id ?? threadId+ )+ }++ findByMessageId(accountId: string, messageId: string, mailboxId?: string) {+ const [id] = messageIds([messageId])+ if (!id) return []+ return (+ mailboxId === undefined+ ? this.all<MessageRow>(+ `SELECT ${MESSAGE_COLUMNS} FROM messages WHERE account_id = ? AND message_id = ?+ ORDER BY received_ms, seq`,+ accountId,+ id,+ )+ : this.all<MessageRow>(+ `SELECT ${MESSAGE_COLUMNS} FROM messages+ WHERE account_id = ? AND message_id = ? AND mailbox_id = ? ORDER BY received_ms, seq`,+ accountId,+ id,+ mailboxId,+ )+ ).map(toMessage)+ }++ /** The grouped, filtered conversation set, or `null` when the filter cannot match. */+ private conversationSource(accountId: string, filter: ConversationFilter) {+ const mailboxIds = filter.mailboxIds && [...new Set(filter.mailboxIds)]+ if (mailboxIds?.length === 0 || filter.ids?.length === 0) return null+ const where: string[] = []+ const params: SQLInputValue[] = []+ let from: string+ // SQLite cannot estimate json_each sizes; CROSS JOIN makes the given list drive the lookup.+ if (filter.ids) {+ from = 'json_each(?) j CROSS JOIN messages m ON m.id = j.value'+ params.push(list(filter.ids))+ where.push('m.account_id = ?')+ params.push(accountId)+ } else if (mailboxIds && mailboxIds.length > 1) {+ from = 'json_each(?) j CROSS JOIN messages m ON m.account_id = ? AND m.mailbox_id = j.value'+ params.push(list(mailboxIds), accountId)+ } else {+ from = 'messages m'+ where.push('m.account_id = ?')+ params.push(accountId)+ }+ if (mailboxIds && !filter.ids && mailboxIds.length === 1) {+ where.push('m.mailbox_id = ?')+ params.push(mailboxIds[0]!)+ } else if (mailboxIds && filter.ids) {+ where.push('m.mailbox_id IN (SELECT value FROM json_each(?))')+ params.push(list(mailboxIds))+ }+ if (filter.excludeMailboxIds?.length) {+ where.push('m.mailbox_id NOT IN (SELECT value FROM json_each(?))')+ params.push(list(filter.excludeMailboxIds))+ }+ // Literals, not parameters, so the partial indexes on these columns apply.+ if (filter.flagged !== undefined) where.push('m.flagged = ' + (filter.flagged ? 1 : 0))+ if (filter.unseen !== undefined) where.push('m.seen = ' + (filter.unseen ? 0 : 1))+ if (filter.hasAttachment !== undefined)+ where.push('m.has_attachment = ' + (filter.hasAttachment ? 1 : 0))+ if (filter.after !== undefined) {+ where.push('m.received_ms >= ?')+ params.push(time(filter.after))+ }+ if (filter.before !== undefined) {+ where.push('m.received_ms < ?')+ params.push(time(filter.before))+ }+ // With a single max() aggregate, SQLite takes the bare `seq` from the row holding the max.+ return {+ sql: `SELECT m.thread_id AS t, max(m.received_ms) AS r, m.seq AS s FROM ${from}+ ${where.length ? 'WHERE ' + where.join(' AND ') : ''} GROUP BY m.thread_id`,+ params,+ }+ }++ conversations(+ accountId: string,+ filter: ConversationFilter,+ page: { limit: number; offset?: number; after?: ConversationCursor },+ ) {+ const source = this.conversationSource(accountId, filter)+ if (!source) return { items: [], total: 0 }+ const params = [...source.params]+ let keyset = ''+ if (page.after) {+ const r = time(page.after.receivedAt)+ keyset = 'WHERE r < ? OR (r = ? AND t > ?)'+ params.push(r, r, page.after.threadId)+ }+ params.push(Math.max(0, Math.floor(page.limit)))+ params.push(page.after ? 0 : Math.max(0, Math.floor(page.offset ?? 0)))+ const row = this.get<{ total: number; page: string }>(+ `WITH g AS MATERIALIZED (${source.sql})+ SELECT (SELECT count(*) FROM g) AS total,+ (SELECT json_group_array(json_array(t, s) ORDER BY r DESC, t) FROM (+ SELECT t, r, s FROM g ${keyset} ORDER BY r DESC, t LIMIT ? OFFSET ?)) AS page`,+ ...params,+ )!+ const picked = JSON.parse(row.page) as [string, number][]+ if (!picked.length) return { items: [], total: row.total }+ const latest = new Map(+ this.all<MessageRow>(+ `SELECT ${MESSAGE_COLUMNS} FROM messages WHERE seq IN (SELECT value FROM json_each(?))`,+ list(picked.map(([, seq]) => seq)),+ ).map((message) => [message.seq, toMessage(message)]),+ )+ const counts = new Map(+ this.all<{ thread_id: string; n: number }>(+ `SELECT thread_id, count(*) AS n FROM messages WHERE account_id = ?+ AND thread_id IN (SELECT value FROM json_each(?)) GROUP BY thread_id`,+ accountId,+ list(picked.map(([thread]) => thread)),+ ).map((count) => [count.thread_id, count.n]),+ )+ const items: ConversationRow[] = picked.map(([threadId, seq]) => ({+ threadId,+ latest: latest.get(seq)!,+ count: counts.get(threadId) ?? 1,+ }))+ return { items, total: row.total }+ }++ /** `EXPLAIN QUERY PLAN` details for a conversation filter; used to keep queries indexed. */+ explainConversations(accountId: string, filter: ConversationFilter) {+ const source = this.conversationSource(accountId, filter)+ if (!source) return []+ return this.all<{ detail: string }>('EXPLAIN QUERY PLAN ' + source.sql, ...source.params).map(+ (row) => row.detail,+ )+ }++ counts(accountId: string) {+ const row = this.get<{ n: number }>(+ 'SELECT count(*) AS n FROM messages WHERE account_id = ?',+ accountId,+ )+ return { messages: row?.n ?? 0 }+ }++ getMeta(accountId: string, key: string) {+ return this.get<{ value: string }>(+ 'SELECT value FROM meta WHERE account_id = ? AND key = ?',+ accountId,+ key,+ )?.value+ }++ setMeta(accountId: string, key: string, value: string | undefined) {+ if (value === undefined)+ this.run('DELETE FROM meta WHERE account_id = ? AND key = ?', accountId, key)+ else+ this.run(+ `INSERT INTO meta (account_id, key, value) VALUES (?, ?, ?)+ ON CONFLICT DO UPDATE SET value = excluded.value`,+ accountId,+ key,+ value,+ )+ }+}++/** Wraps a synchronous index in the async interface, for tests and in-process use. */+export function asyncIndex(index: SyncMetadataIndex): MetadataIndex {+ const wrapped: Partial<Record<keyof MetadataIndex, unknown>> = {}+ for (const method of indexMethods)+ wrapped[method] = (...args: unknown[]) => {+ try {+ return Promise.resolve((index[method] as (...values: unknown[]) => unknown)(...args))+ } catch (error) {+ return Promise.reject(error)+ }+ }+ return wrapped as MetadataIndex+}++export function openInProcessIndex(path: string): MetadataIndex {+ return asyncIndex(new SqliteMetadataIndex(path))+}diff --git a/apps/desktop/src/main/imap-index/worker.ts b/apps/desktop/src/main/imap-index/worker.tsnew file mode 100644index 0000000..2e1f8fd--- /dev/null+++ b/apps/desktop/src/main/imap-index/worker.ts@@ -0,0 +1,22 @@+import { parentPort, workerData } from 'node:worker_threads'+import { SqliteMetadataIndex, indexMethods } from './sqlite-index'++// An open failure (e.g. a newer schema) throws here and reaches the client as the worker error.+const index = new SqliteMetadataIndex((workerData as { path: string }).path)+const methods = new Set<string>(indexMethods)+const port = parentPort!++port.on('message', (request: { id: number; method: string; args: unknown[] }) => {+ try {+ if (!methods.has(request.method)) throw new Error('Unknown mail index method.')+ const method = index[request.method as keyof SqliteMetadataIndex] as (+ ...args: unknown[]+ ) => unknown+ port.postMessage({ id: request.id, result: method.apply(index, request.args) })+ } catch (error) {+ port.postMessage({+ id: request.id,+ error: { message: error instanceof Error ? error.message : String(error) },+ })+ }+})diff --git a/apps/desktop/src/main/index.ts b/apps/desktop/src/main/index.tsnew file mode 100644index 0000000..1a256b5--- /dev/null+++ b/apps/desktop/src/main/index.ts@@ -0,0 +1,312 @@+import {+ app,+ BrowserWindow,+ ipcMain,+ protocol,+ net,+ Tray,+ Menu,+ nativeImage,+ powerMonitor,+} from 'electron'+import { join, resolve, sep } from 'node:path'+import { pathToFileURL, fileURLToPath } from 'node:url'+import { ipcSchemas, type AppEvent } from '@inlark/core'+import { JsonStore } from './storage'+import { MailService } from './service'+import { imapProviders } from './imap-accounts'+import { openWorkerIndex } from './imap-index/open'+import { discover } from './discovery-transport'+import { SenderAvatarResolver } from './sender-avatar'++const here = fileURLToPath(new URL('.', import.meta.url))+protocol.registerSchemesAsPrivileged([+ {+ scheme: 'inlark',+ privileges: {+ standard: true,+ secure: true,+ supportFetchAPI: true,+ stream: true,+ corsEnabled: true,+ },+ },+])+app.setName('Inlark')+if (process.env.INLARK_DATA_DIR) app.setPath('userData', process.env.INLARK_DATA_DIR)+let window: BrowserWindow | null = null,+ tray: Tray | null = null,+ quitting = false+let unreadCount = 0,+ rendererReady = false+let service: MailService+const pendingEvents: AppEvent[] = []+const demo = process.argv.includes('--demo')+const demoAvatars = demo ? new SenderAvatarResolver() : null+const smoke = process.argv.includes('--smoke-test')+if (smoke && !process.env.INLARK_DATA_DIR)+ throw new Error('Smoke tests require a separate INLARK_DATA_DIR.')+const devURL = process.env.ELECTRON_RENDERER_URL+function send(event: AppEvent) {+ if (event.type === 'open' || event.type === 'mailto') show()+ if (window && rendererReady) window.webContents.send('mail:event', event)+ else if (event.type === 'open' || event.type === 'mailto') pendingEvents.push(event)+ if (event.type === 'unread' && tray) {+ unreadCount = event.count+ tray.setImage(trayImage(unreadCount > 0))+ tray.setToolTip('Inlark · ' + unreadCount + ' unread messages')+ tray.setTitle(unreadCount ? String(unreadCount) : '')+ }+ if (event.type === 'accounts' && tray) {+ const connected = event.accounts.filter((a) => a.status === 'connected').length+ tray.setToolTip(+ 'Inlark · ' ++ unreadCount ++ ' unread · ' ++ connected ++ '/' ++ event.accounts.length ++ ' accounts connected',+ )+ }+}+function show() {+ if (!window) createWindow()+ window?.show()+ window?.focus()+}+function trusted(event: Electron.IpcMainInvokeEvent): boolean {+ const frame = event.senderFrame+ if (!window || event.sender !== window.webContents || frame !== window.webContents.mainFrame)+ return false+ try {+ return frame?.origin === (devURL ? new URL(devURL).origin : 'inlark://mail')+ } catch {+ return false+ }+}+function createWindow() {+ rendererReady = false+ window = new BrowserWindow({+ width: 1380,+ height: 900,+ minWidth: 900,+ minHeight: 620,+ show: false,+ icon: join(here, '../../resources/icon.png'),+ backgroundColor: '#121214',+ title: 'Inlark',+ autoHideMenuBar: true,+ webPreferences: {+ preload: join(here, '../preload/index.cjs'),+ contextIsolation: true,+ sandbox: true,+ nodeIntegration: false,+ webSecurity: true,+ spellcheck: true,+ },+ })+ window.on('ready-to-show', () => {+ if (!smoke) window?.show()+ })+ window.on('close', (event) => {+ if (!quitting && service?.settings.closeToTray && tray) {+ event.preventDefault()+ window?.hide()+ }+ })+ window.on('closed', () => {+ window = null+ })+ window.webContents.setWindowOpenHandler(({ url }) => {+ void service.openExternal(url).catch(() => {})+ return { action: 'deny' }+ })+ // Vite reloads the page after some edits; keep those reloads in the app window.+ const isDevReload = (event: { url: string; isMainFrame: boolean }) =>+ !!devURL && event.isMainFrame && new URL(event.url).origin === new URL(devURL).origin+ window.webContents.on('will-navigate', (event) => {+ if (!isDevReload(event)) event.preventDefault()+ })+ window.webContents.on('will-frame-navigate', (event) => {+ if (isDevReload(event)) return+ event.preventDefault()+ if (/^https?:|^mailto:/.test(event.url)) void service.openExternal(event.url).catch(() => {})+ })+ window.webContents.session.setPermissionRequestHandler((_wc, _permission, callback) =>+ callback(false),+ )+ window.webContents.session.setPermissionCheckHandler(() => false)+ window.webContents.on('did-finish-load', () => {+ if (smoke)+ void window!.webContents+ .executeJavaScript(+ 'window.mail.bootstrap().then(value => ({ accounts: value.accounts.length, version: value.version, secureStorage: value.secureStorage }))',+ )+ .then(async (result) => {+ // The IMAP index runs SQLite in a worker thread; prove both start in this build.+ const index = openWorkerIndex(+ join(app.getPath('userData'), 'smoke-index', 'metadata.sqlite'),+ )+ await index.syncMailboxes('smoke', [])+ await index.close()+ console.log(+ 'Native IPC smoke test passed:',+ JSON.stringify({ ...result, index: 'sqlite-worker' }),+ )+ quitting = true+ app.exit(0)+ })+ .catch(() => {+ console.error('Native IPC smoke test failed.')+ quitting = true+ app.exit(1)+ })+ })+ if (devURL) void window.loadURL(devURL + (demo ? '?demo=1' : ''))+ else void window.loadURL('inlark://mail/index.html' + (demo ? '?demo=1' : ''))+}+function trayImage(unread = false) {+ return nativeImage.createFromPath(+ join(here, unread ? '../../resources/tray-unread.png' : '../../resources/tray.png'),+ )+}+function mailtoFromArgs(args: string[]) {+ const url = args.find((a) => a.startsWith('mailto:'))+ if (url) send({ type: 'mailto', url })+}+const lock = app.requestSingleInstanceLock()+if (!lock) app.quit()+else {+ app.on('second-instance', (_event, args) => {+ show()+ mailtoFromArgs(args)+ })+ app.on('open-url', (event, url) => {+ event.preventDefault()+ send({ type: 'mailto', url })+ })+ app+ .whenReady()+ .then(async () => {+ const rendererRoot = resolve(here, '../renderer')+ protocol.handle('inlark', (request) => {+ const url = new URL(request.url)+ if (url.hostname !== 'mail') return new Response('Not found', { status: 404 })+ let path: string+ try {+ path = resolve(+ rendererRoot,+ '.' + decodeURIComponent(url.pathname === '/' ? '/index.html' : url.pathname),+ )+ } catch {+ return new Response('Bad request', { status: 400 })+ }+ if (!path.startsWith(rendererRoot + sep)) return new Response('Not found', { status: 404 })+ return net.fetch(pathToFileURL(path).toString())+ })+ service = new MailService(new JsonStore(join(app.getPath('userData'), 'mail')), send, {+ providers: imapProviders,+ discover,+ })+ await service.init()+ const handlers: Record<keyof typeof ipcSchemas, (...args: any[]) => unknown> = {+ ready: () => {+ rendererReady = true+ for (const event of pendingEvents.splice(0)) window?.webContents.send('mail:event', event)+ },+ bootstrap: service.bootstrap,+ discover: service.discover,+ testConnection: service.testConnection,+ connect: service.connect,+ connectionSettings: service.connectionSettings,+ folderMappings: service.folderMappings,+ setFolderMappings: service.setFolderMappings,+ disconnect: service.disconnect,+ reconnect: service.reconnect,+ updateAccount: service.updateAccount,+ updateAccountDetails: service.updateAccountDetails,+ mailboxes: service.mailboxes,+ identities: service.identities,+ query: service.query,+ conversation: service.conversation,+ mutate: service.mutate,+ mutateAll: service.mutateAll,+ undo: service.undo,+ folder: service.folder,+ drafts: service.drafts,+ resumeDraft: service.resumeDraft,+ stageRemoteAttachments: service.stageRemoteAttachments,+ saveDraft: service.saveDraft,+ syncDraft: service.syncDraft,+ deleteDraft: service.deleteDraft,+ deleteServerDraft: service.deleteServerDraft,+ send: service.send,+ reconcile: service.reconcile,+ submissions: service.submissions,+ retrySentCopy: service.retrySentCopy,+ recoverRejected: service.recoverRejected,+ replaceUncertain: service.replaceUncertain,+ dismissSubmission: service.dismissSubmission,+ stageAttachments: service.stageAttachments,+ attachment: service.attachment,+ inlineImage: service.inlineImage,+ remoteImage: service.remoteImage,+ senderAvatar: demoAvatars+ ? (email: string) => demoAvatars.get(email)+ : service.senderAvatar,+ unsubscribe: service.unsubscribe,+ openExternal: service.openExternal,+ settings: service.setSettings,+ diagnostics: service.diagnostics,+ }+ for (const [name, schema] of Object.entries(ipcSchemas))+ ipcMain.handle('mail:' + name, async (event, ...args: unknown[]) => {+ if (!trusted(event)) throw new Error('Untrusted application frame.')+ const parsed = schema.safeParse(args)+ if (!parsed.success) throw new Error('Invalid input. Check the fields and try again.')+ return handlers[name as keyof typeof ipcSchemas](...parsed.data)+ })+ createWindow()+ try {+ tray = new Tray(trayImage())+ tray.setToolTip('Inlark')+ tray.setContextMenu(+ Menu.buildFromTemplate([+ { label: 'Open Inlark', click: show },+ { label: 'Check for new mail', click: () => void service.refresh() },+ { type: 'separator' },+ {+ label: 'Quit',+ click: () => {+ quitting = true+ app.quit()+ },+ },+ ]),+ )+ tray.on('click', show)+ } catch {+ tray = null+ }+ powerMonitor.on('resume', () => void service.refresh())+ app.on('activate', show)+ mailtoFromArgs(process.argv)+ // The packaged desktop entry lets the user choose Inlark as their mailto handler.+ })+ .catch((error) => {+ // Avoid dumping potentially private protocol data into application logs.+ console.error(+ 'Inlark failed to start:',+ error instanceof Error ? error.message : 'unknown error',+ )+ app.quit()+ })+}+app.on('before-quit', () => {+ quitting = true+ service?.dispose()+})+app.on('window-all-closed', () => {+ if (!tray || !service?.settings.closeToTray) app.quit()+})diff --git a/apps/desktop/src/main/mail-mutations.ts b/apps/desktop/src/main/mail-mutations.tsnew file mode 100644index 0000000..fd4e2d5--- /dev/null+++ b/apps/desktop/src/main/mail-mutations.ts@@ -0,0 +1,163 @@+import type { MailAction, Mailbox, Message, MessageChange, MessageChanges } from '@inlark/core'++export interface UndoEntry {+ accountId: string+ changes: MessageChanges+ /** The state each changed field had right after the action; undo only reverses matching fields. */+ expected: MessageChanges+}++export interface MutationPlan {+ changes: MessageChanges+ inverse: MessageChanges+ destroy: string[]+}++export interface PlanOptions {+ /**+ * A message lives in exactly one folder (IMAP). Adding a folder without leaving one would+ * copy the message, so such changes are skipped: archiving a conversation moves its Inbox+ * messages and leaves replies in Sent where they are.+ */+ exclusiveMailboxes?: boolean+}++function diff(before: Record<string, boolean>, after: Record<string, boolean>) {+ return Object.fromEntries(+ [...new Set([...Object.keys(before), ...Object.keys(after)])]+ .filter((key) => !!before[key] !== !!after[key])+ .map((key) => [key, !!after[key]]),+ )+}++function change(mailboxes: Record<string, boolean>, keywords: Record<string, boolean>) {+ const result: MessageChange = {}+ if (Object.keys(mailboxes).length) result.mailboxes = mailboxes+ if (Object.keys(keywords).length) result.keywords = keywords+ return result+}++const destinationRole: Partial<Record<MailAction, string>> = {+ archive: 'archive',+ trash: 'trash',+ restore: 'inbox',+ spam: 'junk',+ notSpam: 'inbox',+}++export function planMutation(+ messages: Message[],+ boxes: Mailbox[],+ action: MailAction,+ mailboxId?: string,+ options: PlanOptions = {},+): MutationPlan {+ const unique = [...new Map(messages.map((message) => [message.id, message])).values()]+ if (+ action === 'destroy' &&+ unique.some(+ (message) => !boxes.some((box) => box.role === 'trash' && message.mailboxIds[box.id]),+ )+ )+ throw new Error('Only messages already in Trash can be permanently deleted.')++ const role = destinationRole[action]+ const destination =+ action === 'move'+ ? boxes.find((box) => box.id === mailboxId)+ : role+ ? boxes.find((box) => box.role === role)+ : undefined+ if (role && !destination)+ throw new Error(+ 'Your account needs a ' ++ role ++ ' folder. Choose one in Settings → Accounts → Folders, or configure its role on the server.',+ )+ if ((role || action === 'move') && !destination?.rights.mayAddItems)+ throw new Error('The destination folder is not writable.')++ const changes: MessageChanges = {}+ const inverse: MessageChanges = {}+ for (const message of unique) {+ const memberships = { ...message.mailboxIds }+ const keywords = { ...message.keywords }+ const sourceBoxes = boxes.filter((box) => memberships[box.id])+ if (['read', 'unread'].includes(action) && sourceBoxes.some((box) => !box.rights.maySetSeen))+ throw new Error('Some messages are read-only.')+ if (+ ['star', 'unstar'].includes(action) &&+ sourceBoxes.some((box) => !box.rights.maySetKeywords)+ )+ throw new Error('Some messages cannot be starred.')++ if (action === 'read') keywords.$seen = true+ if (action === 'unread') delete keywords.$seen+ if (action === 'star') keywords.$flagged = true+ if (action === 'unstar') delete keywords.$flagged+ if (destination) {+ if (action === 'archive') {+ for (const box of boxes) if (box.role === 'inbox') delete memberships[box.id]+ } else if (action === 'restore' || action === 'notSpam') {+ for (const box of boxes)+ if (box.role === 'trash' || box.role === 'junk') delete memberships[box.id]+ } else {+ for (const key of Object.keys(memberships)) delete memberships[key]+ }+ memberships[destination.id] = true+ }+ let mailboxChange = diff(message.mailboxIds, memberships)+ if (options.exclusiveMailboxes && !Object.values(mailboxChange).includes(false))+ mailboxChange = {}+ if (+ Object.values(mailboxChange).includes(false) &&+ sourceBoxes.some((box) => mailboxChange[box.id] === false && !box.rights.mayRemoveItems)+ )+ throw new Error('Some messages cannot be moved.')+ const keywordChange = diff(message.keywords, keywords)+ const forward = change(mailboxChange, keywordChange)+ if (!forward.mailboxes && !forward.keywords) continue+ changes[message.id] = forward+ inverse[message.id] = change(+ Object.fromEntries(Object.keys(mailboxChange).map((k) => [k, !!message.mailboxIds[k]])),+ Object.fromEntries(Object.keys(keywordChange).map((k) => [k, !!message.keywords[k]])),+ )+ }+ return {+ changes,+ inverse,+ destroy: action === 'destroy' ? unique.map((message) => message.id) : [],+ }+}++export function undoForUpdated(+ accountId: string,+ plan: MutationPlan,+ updated: string[],+): UndoEntry {+ return {+ accountId,+ changes: Object.fromEntries(+ updated.filter((id) => plan.inverse[id]).map((id) => [id, plan.inverse[id]]),+ ),+ expected: Object.fromEntries(+ updated.filter((id) => plan.changes[id]).map((id) => [id, plan.changes[id]]),+ ),+ }+}++/** Keeps only reversals whose fields still hold the value the action left behind. */+export function safeUndoUpdates(entry: UndoEntry, current: Message[]): MessageChanges {+ const matches = (actual: Record<string, boolean>, expected: Record<string, boolean> = {}) =>+ Object.entries(expected).every(([key, value]) => !!actual[key] === value)+ return Object.fromEntries(+ current+ .filter(+ (message) =>+ entry.changes[message.id] &&+ matches(message.mailboxIds, entry.expected[message.id]?.mailboxes) &&+ matches(message.keywords, entry.expected[message.id]?.keywords),+ )+ .map((message) => [message.id, entry.changes[message.id]]),+ )+}diff --git a/apps/desktop/src/main/public-fetch.ts b/apps/desktop/src/main/public-fetch.tsnew file mode 100644index 0000000..445914b--- /dev/null+++ b/apps/desktop/src/main/public-fetch.ts@@ -0,0 +1,130 @@+import { request as httpsRequest } from 'node:https'+import { request as httpRequest } from 'node:http'+import { lookup } from 'node:dns/promises'+import { isIP } from 'node:net'++export function publicAddress(address: string): boolean {+ if (isIP(address) === 4) {+ const [a, b] = address.split('.').map(Number)+ return !(+ a === 0 ||+ a === 10 ||+ a === 127 ||+ a >= 224 ||+ (a === 169 && b === 254) ||+ (a === 172 && b >= 16 && b <= 31) ||+ (a === 192 && [0, 168].includes(b)) ||+ (a === 198 && [18, 19, 51].includes(b)) ||+ (a === 203 && b === 0) ||+ (a === 100 && b >= 64 && b <= 127)+ )+ }+ // Permit global unicast IPv6 only; mapped, local, multicast, and transition ranges stay blocked.+ if (isIP(address) === 6)+ return (+ /^[23]/.test(address) &&+ !/^2001:(?:0:|db8:|10:|20:)/i.test(address) &&+ !/^2002:/i.test(address)+ )+ return false+}+/** Fetch untrusted message resources without cookies, credentials, redirects, or private-network access. */+export async function publicFetch(+ value: string,+ options: {+ method?: 'GET' | 'POST'+ body?: string+ maxBytes?: number+ timeoutMs?: number+ headersOnly?: boolean+ allowPartial?: boolean+ userAgent?: string+ } = {},+): Promise<{ status: number; type: string; bytes: Buffer; location?: string }> {+ const url = new URL(value)+ if (+ !['https:', 'http:'].includes(url.protocol) ||+ url.username ||+ url.password ||+ (url.port && !['80', '443'].includes(url.port))+ )+ throw new Error('Unsupported public resource URL.')+ const host = url.hostname.replace(/^\[|\]$/g, '')+ const addresses = isIP(host)+ ? [{ address: host, family: isIP(host) }]+ : await lookup(host, { all: true })+ if (!addresses.length || addresses.some((a) => !publicAddress(a.address)))+ throw new Error('Private network resources are not loaded from email.')+ const chosen = addresses[0]+ return new Promise((resolve, reject) => {+ const timer = setTimeout(+ () => request.destroy(new Error('Resource request timed out.')),+ options.timeoutMs ?? 15000,+ )+ const request = (url.protocol === 'https:' ? httpsRequest : httpRequest)(+ url,+ {+ method: options.method || 'GET',+ // Pin the validated address for this connection, including against DNS rebinding.+ lookup: (_hostname, lookupOptions, callback) =>+ lookupOptions.all+ ? callback(null, [{ address: chosen.address, family: chosen.family }])+ : callback(null, chosen.address, chosen.family),+ headers: {+ ...(options.body+ ? {+ 'Content-Type': 'application/x-www-form-urlencoded',+ 'Content-Length': Buffer.byteLength(options.body),+ }+ : {}),+ ...(options.userAgent ? { 'User-Agent': options.userAgent } : {}),+ },+ },+ (response) => {+ const result = {+ status: response.statusCode || 500,+ type: String(response.headers['content-type'] || '')+ .split(';')[0]+ .trim(),+ bytes: Buffer.alloc(0),+ location:+ typeof response.headers.location === 'string' ? response.headers.location : undefined,+ }+ if (options.headersOnly) {+ clearTimeout(timer)+ resolve(result)+ response.destroy()+ return+ }+ const chunks: Buffer[] = []+ let length = 0+ response.on('data', (chunk: Buffer) => {+ const maxBytes = options.maxBytes || 10_000_000+ if (length + chunk.length > maxBytes) {+ if (!options.allowPartial) {+ request.destroy(new Error('Resource is too large.'))+ return+ }+ chunks.push(chunk.subarray(0, maxBytes - length))+ clearTimeout(timer)+ resolve({ ...result, bytes: Buffer.concat(chunks) })+ response.destroy()+ return+ }+ length += chunk.length+ chunks.push(chunk)+ })+ response.on('error', reject)+ response.on('end', () => {+ clearTimeout(timer)+ resolve({ ...result, bytes: Buffer.concat(chunks) })+ })+ },+ )+ request.on('error', (error) => {+ clearTimeout(timer)+ reject(error)+ })+ request.end(options.body)+ })+}diff --git a/apps/desktop/src/main/remote-image.ts b/apps/desktop/src/main/remote-image.tsnew file mode 100644index 0000000..c05a84e--- /dev/null+++ b/apps/desktop/src/main/remote-image.ts@@ -0,0 +1,33 @@+import { publicFetch } from './public-fetch'+import { rasterType } from './sender-avatar'++type FetchResource = typeof publicFetch++export async function remoteImageData(+ value: string,+ fetchResource: FetchResource = publicFetch,+): Promise<string | null> {+ try {+ let url = new URL(value)+ for (let redirects = 0; redirects <= 5; redirects++) {+ if (+ !['http:', 'https:'].includes(url.protocol) ||+ url.username ||+ url.password ||+ (url.port && !['80', '443'].includes(url.port))+ )+ return null+ const response = await fetchResource(url.toString(), { userAgent: 'Mozilla/5.0' })+ if ([301, 302, 303, 307, 308].includes(response.status) && response.location) {+ url = new URL(response.location, url)+ continue+ }+ if (response.status !== 200) return null+ const type = rasterType(response.bytes)+ return type ? `data:${type};base64,${response.bytes.toString('base64')}` : null+ }+ } catch {+ // Broken and blocked remote resources are normal in old email.+ }+ return null+}diff --git a/apps/desktop/src/main/sender-avatar.ts b/apps/desktop/src/main/sender-avatar.tsnew file mode 100644index 0000000..eb930b2--- /dev/null+++ b/apps/desktop/src/main/sender-avatar.ts@@ -0,0 +1,276 @@+import { createHash } from 'node:crypto'+import { isIP } from 'node:net'+import { publicFetch } from './public-fetch'++type Resource = Awaited<ReturnType<typeof publicFetch>>+type FetchResource = (+ url: string,+ options?: { maxBytes?: number; timeoutMs?: number; allowPartial?: boolean; userAgent?: string },+) => Promise<Resource>++const PNG = Buffer.from('89504e470d0a1a0a', 'hex')+const JPEG = Buffer.from('ffd8ff', 'hex')+const ICO = Buffer.from('00000100', 'hex')++export function rasterType(bytes: Buffer): string | null {+ if (bytes.subarray(0, 8).equals(PNG)) return 'image/png'+ if (bytes.subarray(0, 3).equals(JPEG)) return 'image/jpeg'+ if (/^(GIF87a|GIF89a)$/.test(bytes.toString('ascii', 0, 6))) return 'image/gif'+ if (bytes.toString('ascii', 0, 4) === 'RIFF' && bytes.toString('ascii', 8, 12) === 'WEBP')+ return 'image/webp'+ if (+ bytes.toString('ascii', 4, 8) === 'ftyp' &&+ /^(avif|avis)$/.test(bytes.toString('ascii', 8, 12))+ )+ return 'image/avif'+ if (bytes.subarray(0, 4).equals(ICO)) return 'image/x-icon'+ return null+}++function imageData(resource: Resource): string | null {+ if (resource.status !== 200 || !resource.bytes.length) return null+ const type = rasterType(resource.bytes)+ if (!type) return null+ return `data:${type};base64,${resource.bytes.toString('base64')}`+}++export function parentBrandDomain(domain: string): string | null {+ const labels = domain.split('.')+ if (labels.length < 3) return null+ const parent = labels.slice(1)+ // Do not request a registry or public suffix such as co.uk.+ if (+ parent.length === 2 &&+ parent[1].length === 2 &&+ /^(?:ac|co|com|edu|gov|net|org)$/.test(parent[0])+ )+ return null+ return parent.join('.')+}++function attributes(tag: string): Record<string, string> {+ const result: Record<string, string> = {}+ for (const match of tag.matchAll(/([\w-]+)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/g))+ result[match[1].toLowerCase()] = match[2] ?? match[3] ?? match[4]+ return result+}++export function advertisedIcons(html: string, pageUrl: string): string[] {+ const logos: string[] = []+ const icons: string[] = []+ for (const match of html.matchAll(/<link\b[^>]*>/gi)) {+ const { rel = '', href } = attributes(match[0])+ if (!href) continue+ const destination = /(?:^|\s)apple-touch-icon(?:-precomposed)?(?:\s|$)/i.test(rel)+ ? logos+ : /(?:^|\s)icon(?:\s|$)/i.test(rel)+ ? icons+ : null+ if (!destination) continue+ try {+ const url = new URL(href.replace(/&/gi, '&'), pageUrl)+ if (+ url.protocol === 'https:' &&+ !url.username &&+ !url.password &&+ (!url.port || url.port === '443') &&+ !url.pathname.toLowerCase().endsWith('.svg')+ )+ destination.push(url.toString())+ } catch {+ // A malformed icon hint should not prevent the remaining fallbacks.+ }+ }+ return [...new Set([...logos, ...icons])].slice(0, 5)+}++export class SenderAvatarResolver {+ private cache = new Map<string, { image: string | null; expires: number }>()+ private pending = new Map<string, Promise<string | null>>()+ private brandCache = new Map<string, { image: string | null; expires: number }>()+ private brandPending = new Map<string, Promise<string | null>>()+ private providerCache = new Map<string, { image: string | null; expires: number }>()+ private providerPending = new Map<string, Promise<string | null>>()+ private active = 0+ private waiting: (() => void)[] = []++ constructor(private fetchResource: FetchResource = publicFetch) {}++ async get(email: string): Promise<string | null> {+ const normalized = email.trim().toLowerCase()+ const domain = normalized.split('@')[1]+ if (+ !domain ||+ !domain.includes('.') ||+ !/^[a-z0-9.-]+$/.test(domain) ||+ domain.startsWith('.') ||+ domain.endsWith('.') ||+ isIP(domain) ||+ /\.(?:example|invalid|localhost|local|test|onion)$/.test(domain)+ )+ return null+ const cached = this.cache.get(normalized)+ if (cached && cached.expires > Date.now()) return cached.image+ const pending = this.pending.get(normalized)+ if (pending) return pending+ const job = this.limit(() => this.lookup(normalized, domain))+ .catch(() => null)+ .then((image) => {+ this.cache.delete(normalized)+ this.cache.set(normalized, {+ image,+ expires: Date.now() + (image ? 7 * 24 * 60 : 15) * 60_000,+ })+ if (this.cache.size > 200) this.cache.delete(this.cache.keys().next().value!)+ return image+ })+ .finally(() => this.pending.delete(normalized))+ this.pending.set(normalized, job)+ return job+ }++ clear() {+ this.cache.clear()+ this.pending.clear()+ this.brandCache.clear()+ this.brandPending.clear()+ this.providerCache.clear()+ this.providerPending.clear()+ }++ private async limit<T>(run: () => Promise<T>): Promise<T> {+ if (this.active >= 4) await new Promise<void>((resolve) => this.waiting.push(resolve))+ else this.active+++ try {+ return await run()+ } finally {+ const next = this.waiting.shift()+ if (next) next()+ else this.active--+ }+ }++ private async tryImage(url: string): Promise<string | null> {+ try {+ const { resource } = await this.fetchAvatarResource(url, 512_000)+ return imageData(resource)+ } catch {+ return null+ }+ }++ private async fetchAvatarResource(+ value: string,+ maxBytes: number,+ allowPartial = false,+ ): Promise<{ resource: Resource; url: string }> {+ let url = new URL(value)+ for (let redirects = 0; redirects <= 5; redirects++) {+ if (+ url.protocol !== 'https:' ||+ url.username ||+ url.password ||+ (url.port && url.port !== '443')+ )+ throw new Error('Unsupported sender image URL.')+ const resource = await this.fetchResource(url.toString(), {+ maxBytes,+ timeoutMs: 5000,+ allowPartial,+ userAgent: 'Mozilla/5.0',+ })+ if (![301, 302, 303, 307, 308].includes(resource.status) || !resource.location)+ return { resource, url: url.toString() }+ url = new URL(resource.location, url)+ }+ throw new Error('Too many sender image redirects.')+ }++ private async lookup(email: string, domain: string): Promise<string | null> {+ // Gravatar returns 404 when an address has no published portrait.+ const hash = createHash('sha256').update(email).digest('hex')+ const portrait = await this.tryImage(`https://gravatar.com/avatar/${hash}?s=96&d=404`)+ if (portrait) return portrait++ let brandDomain = domain+ for (let depth = 0; depth < 5; depth++) {+ const image = await this.brand(brandDomain)+ if (image) return image+ const parent = parentBrandDomain(brandDomain)+ if (!parent) break+ brandDomain = parent+ }+ return this.providerBrand(brandDomain)+ }++ private async providerBrand(domain: string): Promise<string | null> {+ const cached = this.providerCache.get(domain)+ if (cached && cached.expires > Date.now()) return cached.image+ const pending = this.providerPending.get(domain)+ if (pending) return pending+ const job = (async () =>+ (await this.tryImage(`https://twenty-icons.com/${domain}`)) ||+ this.tryImage(`https://icons.duckduckgo.com/ip3/${domain}.ico`))()+ .then((image) => {+ this.providerCache.delete(domain)+ this.providerCache.set(domain, {+ image,+ expires: Date.now() + (image ? 7 * 24 * 60 : 15) * 60_000,+ })+ if (this.providerCache.size > 100)+ this.providerCache.delete(this.providerCache.keys().next().value!)+ return image+ })+ .finally(() => this.providerPending.delete(domain))+ this.providerPending.set(domain, job)+ return job+ }++ private async brand(domain: string): Promise<string | null> {+ const cached = this.brandCache.get(domain)+ if (cached && cached.expires > Date.now()) return cached.image+ const pending = this.brandPending.get(domain)+ if (pending) return pending+ const job = this.lookupBrand(domain)+ .then((image) => {+ this.brandCache.delete(domain)+ this.brandCache.set(domain, {+ image,+ expires: Date.now() + (image ? 7 * 24 * 60 : 15) * 60_000,+ })+ if (this.brandCache.size > 100) this.brandCache.delete(this.brandCache.keys().next().value!)+ return image+ })+ .finally(() => this.brandPending.delete(domain))+ this.brandPending.set(domain, job)+ return job+ }++ private async lookupBrand(domain: string): Promise<string | null> {+ const origin = `https://${domain}`+ // Apple touch icons are normally large brand marks, suitable for an avatar.+ const touchIcon = await this.tryImage(`${origin}/apple-touch-icon.png`)+ if (touchIcon) return touchIcon++ try {+ const { resource: page, url: pageUrl } = await this.fetchAvatarResource(+ `${origin}/`,+ 512_000,+ true,+ )+ if (page.status === 200 && page.type.toLowerCase() === 'text/html') {+ for (const url of advertisedIcons(page.bytes.toString('utf8'), pageUrl)) {+ const image = await this.tryImage(url)+ if (image) return image+ }+ }+ } catch {+ // Sites without a homepage can still have a conventional favicon.+ }+ return (+ (await this.tryImage(`${origin}/favicon.ico`)) ||+ (await this.tryImage(`${origin}/favicon.png`)) ||+ this.tryImage(`${origin}/favicon-32x32.png`)+ )+ }+}diff --git a/apps/desktop/src/main/service.ts b/apps/desktop/src/main/service.tsnew file mode 100644index 0000000..f9fe330--- /dev/null+++ b/apps/desktop/src/main/service.ts@@ -0,0 +1,1618 @@+import { randomUUID } from 'node:crypto'+import { mkdir, readFile, writeFile, copyFile, rm, stat, chmod, open } from 'node:fs/promises'+import { join, basename, extname } from 'node:path'+import { app, dialog, shell, Notification } from 'electron'+import {+ defaultSettings,+ mergePages,+ nextAccountColor,+ sendDraftSchema,+ friendlyError,+ draftFingerprint,+ connectionErrorCodes,+ ProviderError,+ type Account,+ type AccountAppearance,+ type Address,+ type Settings,+ type ConnectInput,+ type ConnectionConfig,+ type ConnectionSettings,+ type ConnectionTest,+ type AccountDetails,+ type MailQuery,+ type QueryPage,+ type MailAction,+ type MutationInput,+ type MutationResult,+ type Draft,+ type DraftErrorKind,+ type Attachment,+ type StagedAttachment,+ type AppEvent,+ type MailProvider,+ type FolderMappings,+ type DiscoveryResult,+ type OutgoingMessage,+ type SendResult,+ type SubmissionSummary,+} from '@inlark/core'+import { JmapProvider } from '@inlark/jmap'+import { publicFetch } from './public-fetch'+import { remoteImageData } from './remote-image'+import { SenderAvatarResolver, rasterType } from './sender-avatar'+import { planMutation, safeUndoUpdates, undoForUpdated, type UndoEntry } from './mail-mutations'+import { JsonStore, encryptSecret, decryptSecret, secureStorageAvailable } from './storage'++export type Connection = {+ id: string+ name: string+ config: ConnectionConfig+ secret?: string+ localSecret?: string+ /** Only present when the outgoing server has its own password. */+ outgoingSecret?: string+ outgoingLocalSecret?: string+ folders?: FolderMappings+ accounts: Account[]+}+/** The version 1 record, from before IMAP support. Every such connection was JMAP. */+type LegacyConnection = {+ id: string+ serverUrl: string+ username: string+ name: string+ secret?: string+ localSecret?: string+ accounts: Account[]+}+export function migrateConnections(data: unknown, version: number): Connection[] {+ if (version !== 1 || !Array.isArray(data)) throw new Error('Unsupported connections data.')+ return (data as LegacyConnection[]).map((legacy) => {+ if (+ typeof legacy?.id !== 'string' ||+ typeof legacy.serverUrl !== 'string' ||+ typeof legacy.username !== 'string' ||+ !Array.isArray(legacy.accounts)+ )+ throw new Error('Malformed connection record.')+ const { serverUrl, username, ...rest } = legacy+ return {+ ...rest,+ config: { protocol: 'jmap', serverUrl, username },+ accounts: legacy.accounts.map((a) => ({ ...a, protocol: 'jmap' as const })),+ }+ })+}+export const CONNECTIONS_VERSION = 2++type Secrets = { password: string; outgoingPassword?: string }+type Journal = {+ draftId: string+ accountId: string+ /** JMAP: the server email being submitted. */+ emailId?: string+ /** The Message-ID of this attempt, without angle brackets. */+ messageId?: string+ envelope?: OutgoingMessage['envelope']+ /** The prepared MIME is stored beside the journal until its Sent copy is filed. */+ mime?: boolean+ subject?: string+ state: 'preparing' | 'submitting' | 'sent' | 'partial' | 'uncertain' | 'rejected'+ accepted?: string[]+ rejected?: { email: string; reason: string }[]+ /**+ * Only for providers that file their own Sent copy. `appending` is written before APPEND, so+ * a crash in between is recovered as `uncertain` and reconciled by Message-ID before retrying.+ */+ sentCopy?: 'pending' | 'appending' | 'uncertain' | 'failed' | 'filed' | 'server' | 'dismissed'+ sentCopyError?: string+ /** The user has seen and resolved this attempt. */+ dismissed?: boolean+ at: string+}+/** Errors that prove nothing left for recipients during submission. */+const definiteSubmissionCodes = [+ 'submissionRejected',+ 'authentication',+ 'outgoingAuthentication',+ 'outgoingNetwork',+ 'tls',+ 'capability',+ 'mailboxes',+ 'submission',+ 'unsupported',+ 'identity',+]+/** Creates the provider for a non-JMAP connection. Replaced in tests. */+export type ProviderFactory = (input: {+ connectionId: string+ config: ConnectionConfig+ secrets: Secrets+ name: string+ folders?: FolderMappings+ /** A test connection must leave nothing behind on disk. */+ temporary?: boolean+ /** Where this connection may keep local data, removed when it is disconnected. */+ directory: string+ readAttachment: (id: string) => Promise<Uint8Array>+}) => MailProvider+export interface ServiceOptions {+ providers?: ProviderFactory+ discover?: (email: string) => Promise<DiscoveryResult>+}+const errorKind = (error: unknown): DraftErrorKind | undefined =>+ error instanceof ProviderError+ ? error.code === 'outgoingAuthentication'+ ? 'outgoingAuthentication'+ : error.code === 'submissionRejected'+ ? 'rejected'+ : error.code === 'conflict'+ ? 'conflict'+ : connectionErrorCodes.includes(error.code) || error.code === 'outgoingNetwork'+ ? 'connection'+ : undefined+ : error instanceof Error && error.message.includes('another client')+ ? 'conflict'+ : undefined++export class MailService {+ settings: Settings = defaultSettings+ accounts: Account[] = []+ private connections: Connection[] = []+ private providers = new Map<string, MailProvider>()+ private sessionSecrets = new Map<string, Secrets>()+ private localDrafts = new Map<string, Draft>()+ private journals = new Map<string, Journal>()+ private staging = new Map<string, StagedAttachment>()+ private undos = new Map<string, UndoEntry[]>()+ private writes = new Map<string, Promise<unknown>>()+ private busyDrafts = new Set<string>()+ private refreshing = new Set<string>()+ private filing = new Set<string>()+ private unreadCounts = new Map<string, number>()+ private notificationBaseline = new Map<string, string>()+ private indexingEmit?: ReturnType<typeof setTimeout>+ private timer?: ReturnType<typeof setInterval>+ private logs: { at: string; event: string; state?: string }[] = []+ private senderAvatars = new SenderAvatarResolver()+ constructor(+ private store: JsonStore,+ private emit: (event: AppEvent) => void,+ private options: ServiceOptions = {},+ ) {}+ private log(event: string, state?: string) {+ this.logs.push({ at: new Date().toISOString(), event, state })+ this.logs = this.logs.slice(-200)+ }+ async init() {+ await this.store.init()+ this.settings = await this.store.read('settings', defaultSettings)+ this.connections = await this.store.read<Connection[]>('connections', [], {+ version: CONNECTIONS_VERSION,+ migrate: migrateConnections,+ })+ this.accounts = this.connections.flatMap((c) =>+ c.accounts.map((a) => ({+ ...a,+ protocol: c.config.protocol,+ status: 'connecting' as const,+ })),+ )+ this.localDrafts = new Map((await this.store.read<Draft[]>('drafts', [])).map((d) => [d.id, d]))+ this.journals = new Map(+ (await this.store.read<Journal[]>('submissions', [])).map((j) => [j.draftId, j]),+ )+ this.staging = new Map(+ (await this.store.read<StagedAttachment[]>('staging', [])).map((a) => [a.id, a]),+ )+ for (const journal of this.journals.values()) {+ const draft = this.localDrafts.get(journal.draftId)+ if (journal.state === 'sent' && draft && (draft.status !== 'sent' || this.hasContent(draft)))+ await this.completeDraft(draft)+ if (journal.state === 'preparing') {+ // Submission only starts after `submitting` is durable, so nothing left the device.+ this.journals.delete(journal.draftId)+ await this.removeMime(journal.draftId)+ if (draft)+ this.localDrafts.set(draft.id, {+ ...draft,+ status: 'local',+ error: 'Sending was interrupted before the message left. Review it and send again.',+ errorKind: 'connection',+ })+ }+ if (journal.state === 'submitting') {+ journal.state = 'uncertain'+ if (draft)+ this.localDrafts.set(draft.id, {+ ...draft,+ status: 'uncertain',+ error: 'The app closed during sending. Check delivery before retrying.',+ })+ }+ if (journal.sentCopy === 'appending') journal.sentCopy = 'uncertain'+ }+ await this.persistDrafts()+ await this.persistJournal()+ void Promise.allSettled(this.connections.map((c) => this.reconnect(c.id)))+ this.timer = setInterval(() => void this.refresh(), 60_000)+ }+ bootstrap = async () => ({+ accounts: this.accounts,+ settings: this.settings,+ secureStorage: secureStorageAvailable(),+ demo: false,+ version: app.getVersion(),+ })+ private hasContent(draft: Draft) {+ return !!(draft.text || draft.html || draft.attachments.length)+ }+ private saveConnections() {+ return this.store.write('connections', this.connections, CONNECTIONS_VERSION)+ }+ private persistDrafts() {+ return this.store.write('drafts', [...this.localDrafts.values()])+ }+ private async persistJournal() {+ await this.store.write('submissions', [...this.journals.values()])+ this.emit({ type: 'submissions', submissions: this.summaries() })+ }+ private account(id: string): Account {+ const a = this.accounts.find((a) => a.id === id)+ if (!a) throw new Error('Account not found.')+ return a+ }+ private provider(accountId: string) {+ const account = this.account(accountId),+ provider = this.providers.get(account.connectionId)+ if (!provider) throw new Error('This account is disconnected. Reconnect it in Settings.')+ return { account, provider }+ }+ private patchAccounts(connectionId: string, patch: Partial<Account>) {+ this.accounts = this.accounts.map((a) =>+ a.connectionId === connectionId ? { ...a, ...patch } : a,+ )+ this.emit({ type: 'accounts', accounts: this.accounts })+ }+ private status(connectionId: string, state: Account['status'], error?: string) {+ this.patchAccounts(connectionId, { status: state, error })+ }+ /** Outgoing problems are tracked apart from incoming ones: reading can still work. */+ private outgoing(connectionId: string, error?: string) {+ const current = this.accounts.find((a) => a.connectionId === connectionId)+ if (current && current.outgoingError !== error)+ this.patchAccounts(connectionId, { outgoingError: error })+ }+ private async guard<T>(+ accountId: string,+ fn: (provider: MailProvider, account: Account) => Promise<T>,+ ): Promise<T> {+ const { provider, account } = this.provider(accountId)+ try {+ const result = await fn(provider, account)+ if (account.status !== 'connected') this.status(account.connectionId, 'connected')+ return result+ } catch (error) {+ if (error instanceof ProviderError && connectionErrorCodes.includes(error.code))+ this.status(+ account.connectionId,+ error.code === 'authentication' ? 'authentication' : 'offline',+ friendlyError(error),+ )+ if (error instanceof ProviderError && error.code === 'outgoingAuthentication')+ this.outgoing(account.connectionId, friendlyError(error))+ this.log('request-failed', error instanceof ProviderError ? error.code : 'local')+ throw error+ }+ }+ private createProvider(+ id: string,+ input: Pick<ConnectInput, 'config' | 'name' | 'password' | 'outgoingPassword' | 'folders'>,+ temporary = false,+ ): MailProvider {+ const config = input.config+ if (config.protocol === 'jmap')+ return new JmapProvider({+ serverUrl: config.serverUrl,+ authorization:+ 'Basic ' + Buffer.from(config.username + ':' + input.password).toString('base64'),+ connectionId: id,+ name: input.name,+ })+ if (!this.options.providers) throw new Error('IMAP accounts are not available in this build.')+ return this.options.providers({+ connectionId: id,+ config,+ name: input.name,+ folders: input.folders,+ secrets: { password: input.password, outgoingPassword: input.outgoingPassword },+ temporary,+ directory: join(this.store.directory, 'index', id),+ readAttachment: this.readStagedAttachment,+ })+ }+ discover = async (email: string): Promise<DiscoveryResult> => {+ if (!this.options.discover) throw new Error('Automatic setup is not available in this build.')+ return this.options.discover(email)+ }+ /** Signs in to each server separately and reports each result. Nothing is saved or sent. */+ testConnection = async (input: ConnectInput): Promise<ConnectionTest> => {+ const provider = this.createProvider('test-' + randomUUID(), input, true)+ const result: ConnectionTest = { incoming: { ok: false } }+ try {+ const [accounts] = await Promise.allSettled([provider.connect()])+ if (accounts.status === 'fulfilled') {+ result.incoming = accounts.value.length+ ? { ok: true }+ : { ok: false, error: 'This login does not provide an accessible mail account.' }+ if (accounts.value[0] && provider.folderMappings)+ result.folders = await provider.folderMappings(accounts.value[0]).catch(() => undefined)+ } else result.incoming = { ok: false, error: friendlyError(accounts.reason) }+ if (provider.verifyOutgoing)+ result.outgoing = await provider.verifyOutgoing().then(+ () => ({ ok: true }),+ (error) => ({ ok: false, error: friendlyError(error) }),+ )+ return result+ } finally {+ provider.dispose()+ await provider.close?.()+ }+ }+ /** `reconnecting` restores a saved login, so labels and names edited since then are kept. */+ connect = async (input: ConnectInput, reconnecting = false): Promise<Account[]> => {+ const id = input.connectionId || randomUUID()+ const previous = this.connections.find((c) => c.id === id)+ if (previous && previous.config.protocol !== input.config.protocol)+ throw new Error('Remove this account and add it again to change its protocol.')+ const outgoingPassword =+ input.config.protocol === 'imap' && !input.config.outgoingSameCredentials+ ? input.outgoingPassword+ : undefined+ const provider = this.createProvider(id, { ...input, outgoingPassword })+ let accounts: Account[]+ let folders = input.folders ?? previous?.folders+ try {+ accounts = await provider.connect()+ if (!accounts.length)+ throw new Error('This login does not provide an accessible mail account.')+ // A new or edited IMAP login must reach both servers. Restoring one only needs incoming mail.+ if (!reconnecting && provider.verifyOutgoing) await provider.verifyOutgoing()+ if (input.folders && provider.setFolderMappings) {+ const review = await provider.setFolderMappings(accounts[0], input.folders)+ // Saved as plain paths, as the server named them, so a reconnect never creates them again.+ folders = Object.fromEntries(+ Object.keys(input.folders).map((role) => {+ const value = review.mappings[role as keyof typeof review.mappings]+ return [role, value ? { path: value.path } : null]+ }),+ )+ }+ const used = this.accounts.filter((a) => a.connectionId !== id).map((a) => a.color)+ for (const account of accounts) {+ const identities = await provider.identities(account)+ account.email =+ identities[0]?.email ||+ (input.config.protocol === 'imap' ? input.config.email : input.config.username)+ account.sessionOnly = !input.remember+ account.protocol = input.config.protocol+ // Reconnecting must never reset what the user picked for this account.+ const known = this.accounts.find((a) => a.id === account.id)+ account.color = known?.color || nextAccountColor(used)+ account.seed = known?.seed+ account.image = known?.image+ if (reconnecting && known) {+ account.name = known.name+ account.senderName = known.senderName+ } else account.senderName = input.senderName?.trim() || undefined+ used.push(account.color)+ }+ const keep = (value?: string) =>+ input.remember && secureStorageAvailable() && value ? encryptSecret(value) : undefined+ const local = (value: string | undefined, encrypted?: string) =>+ input.remember && !encrypted ? value : undefined+ const secret = keep(input.password)+ const outgoingSecret = keep(outgoingPassword)+ const connection: Connection = {+ id,+ name: input.name,+ config: input.config,+ secret,+ localSecret: local(input.password, secret),+ outgoingSecret,+ outgoingLocalSecret: outgoingPassword ? local(outgoingPassword, outgoingSecret) : undefined,+ folders,+ accounts,+ }+ this.connections = [...this.connections.filter((c) => c.id !== id), connection]+ await this.saveConnections()+ } catch (error) {+ provider.dispose()+ void provider.close?.()+ if (previous) this.status(id, 'authentication', friendlyError(error))+ throw error+ }+ const old = this.providers.get(id)+ if (old) {+ old.dispose()+ await old.close?.()+ }+ this.providers.set(id, provider)+ this.sessionSecrets.set(id, { password: input.password, outgoingPassword })+ this.accounts = [...this.accounts.filter((a) => a.connectionId !== id), ...accounts]+ provider.subscribe((event) => {+ if (event.type === 'indexing' && event.accountId && event.indexing) {+ this.accounts = this.accounts.map((a) =>+ a.id === event.accountId+ ? { ...a, indexing: event.indexing!.complete ? undefined : event.indexing }+ : a,+ )+ this.emitAccountsSoon()+ return+ }+ if (event.type === 'status' && event.state) {+ this.status(id, event.state, event.message)+ return+ }+ this.emit({ type: 'changed', accountId: event.accountId })+ // Historical indexing adds older mail; only live changes may produce notifications.+ if (!event.historical) void this.refreshConnection(id)+ })+ this.status(id, 'connected')+ if (!reconnecting) this.outgoing(id, undefined)+ void this.refreshConnection(id)+ this.log('connected', input.config.protocol)+ void this.syncPendingDrafts()+ void this.retrySentCopies(id)+ return accounts+ }+ private emitAccountsSoon() {+ if (this.indexingEmit) return+ this.indexingEmit = setTimeout(() => {+ this.indexingEmit = undefined+ this.emit({ type: 'accounts', accounts: this.accounts })+ }, 1000)+ }+ private secrets(connection: Connection): Secrets | undefined {+ const session = this.sessionSecrets.get(connection.id)+ if (session) return session+ const password = connection.secret ? decryptSecret(connection.secret) : connection.localSecret+ if (!password) return undefined+ const outgoingPassword = connection.outgoingSecret+ ? decryptSecret(connection.outgoingSecret)+ : connection.outgoingLocalSecret+ return { password, outgoingPassword }+ }+ reconnect = async (id: string): Promise<void> => {+ const connection = this.connections.find((c) => c.id === id)+ if (!connection) throw new Error('Connection not found.')+ this.status(id, 'connecting')+ try {+ const secrets = this.secrets(connection)+ if (!secrets) throw new Error('This was a session-only login. Sign in again to reconnect.')+ await this.connect(+ {+ config: connection.config,+ name: connection.name,+ password: secrets.password,+ outgoingPassword: secrets.outgoingPassword,+ remember: !!(connection.secret || connection.localSecret),+ connectionId: id,+ },+ true,+ )+ } catch (error) {+ this.status(+ id,+ error instanceof ProviderError && error.code !== 'authentication'+ ? 'offline'+ : 'authentication',+ friendlyError(error),+ )+ this.log('reconnect-failed')+ throw error+ }+ }+ connectionSettings = async (connectionId: string): Promise<ConnectionSettings> => {+ const connection = this.connections.find((c) => c.id === connectionId)+ if (!connection) throw new Error('Connection not found.')+ return {+ connectionId,+ name: connection.name,+ config: connection.config,+ remember: !!(connection.secret || connection.localSecret),+ folders: connection.folders,+ }+ }+ folderMappings = async (accountId: string) =>+ this.guard(accountId, async (p, a) => {+ if (!p.folderMappings) throw new Error('This server defines its special folders itself.')+ return p.folderMappings(a)+ })+ setFolderMappings = async (accountId: string, mappings: FolderMappings) => {+ const account = this.account(accountId)+ const review = await this.guard(accountId, async (p, a) => {+ if (!p.setFolderMappings) throw new Error('This server defines its special folders itself.')+ return p.setFolderMappings(a, mappings)+ })+ this.connections = this.connections.map((c) =>+ c.id === account.connectionId+ ? {+ ...c,+ folders: Object.fromEntries(+ Object.entries(review.mappings).map(([role, value]) => [+ role,+ value ? { path: value.path } : null,+ ]),+ ),+ }+ : c,+ )+ await this.saveConnections()+ this.emit({ type: 'changed', accountId })+ return review+ }+ updateAccount = async (accountId: string, appearance: AccountAppearance): Promise<Account[]> => {+ const account = this.account(accountId)+ if (appearance.image) {+ const [, type, data] = appearance.image.match(/^data:([^;]+);base64,(.*)$/)!+ if (rasterType(Buffer.from(data, 'base64')) !== type)+ throw new Error('This picture could not be read. Choose a PNG, JPEG or WebP image.')+ }+ const apply = (a: Account): Account =>+ a.id === accountId ? { ...a, seed: appearance.seed, image: appearance.image } : a+ this.accounts = this.accounts.map(apply)+ this.connections = this.connections.map((c) =>+ c.id === account.connectionId ? { ...c, accounts: c.accounts.map(apply) } : c,+ )+ await this.saveConnections()+ this.emit({ type: 'accounts', accounts: this.accounts })+ return this.accounts+ }+ updateAccountDetails = async (accountId: string, details: AccountDetails): Promise<Account[]> => {+ const account = this.account(accountId)+ const apply = (a: Account): Account =>+ a.id === accountId+ ? {+ ...a,+ name: details.name.trim() || a.name,+ senderName: details.senderName.trim() || undefined,+ }+ : a+ this.accounts = this.accounts.map(apply)+ this.connections = this.connections.map((c) =>+ c.id === account.connectionId ? { ...c, accounts: c.accounts.map(apply) } : c,+ )+ await this.saveConnections()+ this.emit({ type: 'accounts', accounts: this.accounts })+ return this.accounts+ }+ disconnect = async (id: string): Promise<void> => {+ const accountIds = new Set(this.accounts.filter((a) => a.connectionId === id).map((a) => a.id))+ const provider = this.providers.get(id)+ provider?.dispose()+ await provider?.close?.()+ this.providers.delete(id)+ this.sessionSecrets.delete(id)+ this.connections = this.connections.filter((c) => c.id !== id)+ this.accounts = this.accounts.filter((a) => a.connectionId !== id)+ for (const draft of this.localDrafts.values())+ if (accountIds.has(draft.accountId)) await this.deleteDraftLocal(draft.id)+ for (const [key, journal] of this.journals)+ if (accountIds.has(journal.accountId)) {+ this.journals.delete(key)+ await this.removeMime(key)+ }+ for (const key of accountIds) {+ this.notificationBaseline.delete(key)+ this.unreadCounts.delete(key)+ }+ // The local message index belongs to this connection only.+ await rm(join(this.store.directory, 'index', id), { recursive: true, force: true })+ this.emit({+ type: 'unread',+ count: [...this.unreadCounts.values()].reduce((sum, n) => sum + n, 0),+ })+ this.undos.clear()+ await this.saveConnections()+ await this.persistDrafts()+ await this.persistJournal()+ this.emit({ type: 'accounts', accounts: this.accounts })+ this.emit({ type: 'changed' })+ }+ mailboxes = (id: string) => this.guard(id, (p, a) => p.mailboxes(a))+ identities = (id: string) => this.guard(id, (p, a) => p.identities(a))+ conversation = (id: string, threadId: string) =>+ this.guard(id, (p, a) => p.conversation(a, threadId))+ query = async (query: MailQuery, cursor?: Record<string, number>): Promise<QueryPage> => {+ const accounts = this.accounts.filter(+ (a) => (!query.accountId || query.accountId === a.id) && (!cursor || a.id in cursor),+ )+ if (!accounts.length) return { items: [], total: 0, failedAccounts: [] }+ const settled = await Promise.allSettled(+ accounts.map(async (a) => ({+ accountId: a.id,+ position: cursor?.[a.id] || 0,+ page: await this.guard(a.id, (p, account) =>+ p.query(account, query, cursor?.[a.id] || 0, 50),+ ),+ })),+ )+ const pages = settled.flatMap((s) => (s.status === 'fulfilled' ? [s.value] : []))+ if (!pages.length)+ throw new Error(+ 'Mail is unavailable. Reconnect an account or try again shortly. Previously opened messages remain in your cache.',+ )+ const result = mergePages(pages, 50)+ result.failedAccounts = accounts+ .filter((_, i) => settled[i].status === 'rejected')+ .map((a) => a.id)+ return result+ }+ /**+ * Runs one read-plan-write cycle at a time per account. Each cycle checks the server state it+ * read, so two overlapping cycles (archive while the next conversation is marked read) would+ * otherwise make the later one fail with a state mismatch.+ */+ private exclusive<T>(accountId: string, task: () => Promise<T>): Promise<T> {+ const run = (this.writes.get(accountId) || Promise.resolve()).then(task, task)+ const settled = run.catch(() => {})+ this.writes.set(accountId, settled)+ void settled.then(() => {+ if (this.writes.get(accountId) === settled) this.writes.delete(accountId)+ })+ return run+ }+ mutate = async (input: MutationInput): Promise<MutationResult> => {+ const result: MutationResult = { changed: 0, failures: [] },+ undo: UndoEntry[] = []+ for (const accountId of [...new Set(input.targets.map((t) => t.accountId))]) {+ try {+ await this.exclusive(accountId, async () => {+ const { provider, account } = this.provider(accountId)+ const boxes = await provider.mailboxes(account)+ const messages = await provider.conversationMetadata(+ account,+ input.targets.filter((t) => t.accountId === accountId).map((t) => t.threadId),+ )+ const expectedState = provider.getStateToken(account)+ const plan = planMutation(messages, boxes, input.action, input.mailboxId, {+ exclusiveMailboxes: provider.capabilities.exclusiveMailboxes,+ })+ const changed = await provider.update(+ account,+ input.action === 'destroy' ? {} : plan.changes,+ plan.destroy,+ expectedState,+ )+ result.changed += changed.updated.length+ result.failures.push(...changed.failures)+ if (input.action !== 'destroy')+ undo.push(undoForUpdated(accountId, plan, changed.updated))+ })+ this.emit({ type: 'changed', accountId })+ } catch (error) {+ result.failures.push(friendlyError(error))+ }+ }+ if (undo.length) {+ result.undoId = randomUUID()+ this.undos.set(result.undoId, undo)+ if (this.undos.size > 20) this.undos.delete(this.undos.keys().next().value!)+ }+ return result+ }+ mutateAll = async (query: MailQuery, action: MailAction): Promise<MutationResult> => {+ if (!['archive', 'trash', 'spam', 'read', 'unread', 'star', 'unstar'].includes(action))+ throw new Error('This action is not supported for all matching conversations.')+ // Snapshot IDs before changing membership so pagination cannot skip shifted rows.+ const targets: MutationInput['targets'] = []+ let matchingTotal = 0+ let cursor: Record<string, number> | undefined+ do {+ const page = await this.query(query, cursor)+ matchingTotal = Math.max(matchingTotal, page.total)+ if (page.failedAccounts.length)+ throw new Error('All accounts must be reachable before applying an action to all results.')+ if (page.incompleteAccounts?.length)+ throw new Error(+ 'Some accounts are still indexing, so not every match is known yet. Try again when indexing finishes.',+ )+ targets.push(...page.items.map((c) => ({ accountId: c.accountId, threadId: c.id })))+ cursor = page.next+ if (targets.length > 250_000)+ throw new Error('Narrow your search to fewer than 250,000 conversations.')+ this.emit({+ type: 'progress',+ completed: targets.length,+ total: Math.max(matchingTotal, targets.length),+ })+ } while (cursor)+ const result: MutationResult = { changed: 0, failures: [] },+ combined: UndoEntry[] = []+ for (let i = 0; i < targets.length; i += 50) {+ const part = await this.mutate({ targets: targets.slice(i, i + 50), action })+ result.changed += part.changed+ result.failures.push(...part.failures)+ if (part.undoId) {+ combined.push(...(this.undos.get(part.undoId) || []))+ this.undos.delete(part.undoId)+ }+ this.emit({+ type: 'progress',+ completed: Math.min(i + 50, targets.length),+ total: targets.length,+ })+ }+ if (combined.length) {+ result.undoId = randomUUID()+ this.undos.set(result.undoId, combined)+ if (this.undos.size > 20) this.undos.delete(this.undos.keys().next().value!)+ }+ return result+ }+ undo = async (id: string): Promise<MutationResult> => {+ const entries = this.undos.get(id)+ if (!entries) throw new Error('This undo action has expired.')+ const result: MutationResult = { changed: 0, failures: [] }+ for (const entry of entries) {+ try {+ await this.exclusive(entry.accountId, async () => {+ const { current, state } = await this.guard(entry.accountId, async (p, a) => ({+ current: await p.messages(a, Object.keys(entry.changes)),+ state: p.getStateToken(a),+ }))+ const safe = safeUndoUpdates(entry, current)+ if (Object.keys(safe).length !== Object.keys(entry.changes).length)+ result.failures.push('Some messages changed since this action and were not undone.')+ const changed = await this.guard(entry.accountId, (p, a) => p.update(a, safe, [], state))+ result.changed += changed.updated.length+ result.failures.push(...changed.failures)+ })+ this.emit({ type: 'changed', accountId: entry.accountId })+ } catch (error) {+ result.failures.push(friendlyError(error))+ }+ }+ this.undos.delete(id)+ return result+ }+ folder = async (input: {+ accountId: string+ operation: 'create' | 'rename' | 'delete'+ id?: string+ name?: string+ parentId?: string+ }) => {+ await this.guard(input.accountId, (p, a) =>+ p.folder(a, input.operation, input.id, input.name, input.parentId),+ )+ this.emit({ type: 'changed', accountId: input.accountId })+ }+ // Sent records also serve as tombstones for a stale renderer draft after a crash.+ drafts = async () => [...this.localDrafts.values()]+ stageRemoteAttachments = async (+ accountId: string,+ attachments: Attachment[],+ ): Promise<StagedAttachment[]> => {+ const directory = join(this.store.directory, 'attachments')+ await mkdir(directory, { recursive: true, mode: 0o700 })+ const staged: StagedAttachment[] = []+ for (const attachment of attachments) {+ const bytes = await this.guard(accountId, (p, a) => p.download(a, attachment))+ const item: StagedAttachment = {+ id: randomUUID(),+ name: attachment.name,+ type: attachment.type,+ size: bytes.length,+ cid: attachment.cid,+ }+ await writeFile(join(directory, item.id), bytes, { mode: 0o600 })+ this.staging.set(item.id, item)+ staged.push(item)+ await this.store.write('staging', [...this.staging.values()])+ }+ return staged+ }+ /** Reads a staged attachment. Only IDs recorded by this service resolve to files. */+ readStagedAttachment = async (id: string): Promise<Uint8Array> => {+ if (!this.staging.has(id))+ throw new Error('An attachment is missing. Remove it and attach the file again.')+ return readFile(join(this.store.directory, 'attachments', id))+ }+ resumeDraft = async (accountId: string, messageId: string): Promise<Draft> => {+ const existing = [...this.localDrafts.values()].find(+ (d) => d.accountId === accountId && d.serverId === messageId,+ )+ if (existing) return existing+ const [message] = await this.guard(accountId, (p, a) => p.messages(a, [messageId], true))+ if (!message?.keywords.$draft) throw new Error('This message is no longer a draft.')+ const identities = await this.identities(accountId)+ const identity =+ identities.find((i) =>+ message.from.some((f) => f.email.toLowerCase() === i.email.toLowerCase()),+ ) || identities[0]+ if (!identity) throw new Error('No sending identity is available for this account.')+ const attachments = await this.stageRemoteAttachments(accountId, message.attachments || [])+ const draft: Draft = {+ id: randomUUID(),+ accountId,+ identityId: identity.id,+ to: message.to,+ cc: message.cc,+ bcc: message.bcc,+ subject: message.subject,+ html: message.html || '',+ text: message.text || '',+ attachments,+ updatedAt: new Date().toISOString(),+ status: 'synced',+ serverId: message.id,+ serverFingerprint: draftFingerprint(message),+ references: message.references,+ inReplyTo: message.inReplyTo,+ }+ return this.saveDraft(draft)+ }+ saveDraft = async (draft: Draft): Promise<Draft> => {+ this.account(draft.accountId)+ const old = this.localDrafts.get(draft.id)+ if (this.busyDrafts.has(draft.id) || old?.status === 'uncertain' || old?.status === 'sent')+ return old || draft+ if (old && old.updatedAt > draft.updatedAt) return old+ this.localDrafts.set(draft.id, draft)+ await this.persistDrafts()+ return draft+ }+ /** Uploads attachments for providers that reference server blobs. Others read staged files. */+ private async uploadDraft(draft: Draft): Promise<Draft> {+ const { provider, account } = this.provider(draft.accountId)+ const attachments: StagedAttachment[] = []+ for (const attachment of draft.attachments) {+ const staged = this.staging.get(attachment.id)+ if (!staged) throw new Error('An attachment is missing. Remove it and attach the file again.')+ if (!provider.capabilities.blobUpload) {+ attachments.push({ ...staged, cid: attachment.cid ?? staged.cid })+ continue+ }+ const data = await readFile(join(this.store.directory, 'attachments', attachment.id))+ const blobId = await provider.upload(account, data, staged.type)+ attachments.push({ ...staged, blobId })+ }+ return { ...draft, attachments }+ }+ syncDraft = async (input: Draft): Promise<Draft> => {+ if (this.busyDrafts.has(input.id)) return this.localDrafts.get(input.id) || input+ this.busyDrafts.add(input.id)+ let committed: Draft | undefined+ try {+ const { provider, account } = this.provider(input.accountId)+ const current = this.localDrafts.get(input.id)+ if (current && current.updatedAt > input.updatedAt) return current+ if (current && ['uncertain', 'sent'].includes(current.status)) return current+ if (input.serverId) {+ const [remote] = await provider.messages(account, [input.serverId], true)+ if (!remote || !remote.keywords.$draft)+ throw new ProviderError(+ 'conflict',+ 'This draft was sent or removed in another client. Your local copy is safe; keep both versions to start a separate draft.',+ )+ if (+ remote &&+ input.serverFingerprint &&+ draftFingerprint(remote) !== input.serverFingerprint+ )+ throw new ProviderError(+ 'conflict',+ 'This draft changed in another client. Your local copy is safe; save it as a new draft to keep both versions.',+ )+ }+ const draft = await this.uploadDraft(input)+ const serverId = await provider.createDraft(account, draft)+ const [remote] = await provider.messages(account, [serverId], true)+ const saved: Draft = {+ ...draft,+ serverId,+ serverFingerprint: remote ? draftFingerprint(remote) : undefined,+ status: 'synced',+ error: undefined,+ errorKind: undefined,+ }+ committed = saved+ this.localDrafts.set(saved.id, saved)+ await this.persistDrafts()+ if (input.serverId && input.serverId !== serverId)+ await this.removePreviousDraft(provider, account, input)+ this.emit({ type: 'changed', accountId: account.id })+ return saved+ } catch (error) {+ const saved: Draft = {+ ...(committed || input),+ status: 'error',+ error: friendlyError(error),+ errorKind: errorKind(error),+ }+ this.localDrafts.set(saved.id, saved)+ await this.persistDrafts()+ return saved+ } finally {+ this.busyDrafts.delete(input.id)+ }+ }+ /** Removes a replaced server draft only if nobody else changed it since it was read. */+ private async removePreviousDraft(provider: MailProvider, account: Account, draft: Draft) {+ const [remote] = await provider.messages(account, [draft.serverId!], true)+ const state = provider.getStateToken(account)+ if (!remote) return+ if (+ !remote.keywords.$draft ||+ !draft.serverFingerprint ||+ draftFingerprint(remote) !== draft.serverFingerprint+ )+ throw new ProviderError(+ 'conflict',+ 'The previous draft changed in another client and was preserved. Your new copy is saved.',+ )+ const result = await provider.update(account, {}, [draft.serverId!], state)+ if (result.failures.length)+ throw new Error('Your new draft is saved. The previous server copy could not be removed.')+ }+ private async completeDraft(draft: Draft) {+ // Keep a minimal tombstone so a stale renderer copy cannot reappear after a crash.+ this.localDrafts.set(draft.id, {+ id: draft.id,+ accountId: draft.accountId,+ identityId: draft.identityId,+ to: [],+ cc: [],+ bcc: [],+ subject: '',+ html: '',+ text: '',+ attachments: [],+ updatedAt: draft.updatedAt,+ status: 'sent',+ })+ await this.persistDrafts()+ await this.releaseAttachments(draft)+ }+ private async releaseAttachments(draft: Draft) {+ for (const attachment of draft.attachments) {+ if (+ ![...this.localDrafts.values()].some((d) =>+ d.attachments.some((a) => a.id === attachment.id),+ )+ ) {+ await rm(join(this.store.directory, 'attachments', attachment.id), { force: true })+ this.staging.delete(attachment.id)+ }+ }+ if (draft.attachments.length) await this.store.write('staging', [...this.staging.values()])+ }+ private async deleteDraftLocal(id: string) {+ const draft = this.localDrafts.get(id)+ this.localDrafts.delete(id)+ if (draft) await this.releaseAttachments(draft)+ }+ deleteDraft = async (id: string) => {+ if (this.busyDrafts.has(id)) throw new Error('Wait for this draft to finish saving.')+ const draft = this.localDrafts.get(id)+ if (draft?.status === 'uncertain')+ throw new Error('Check this message’s delivery status before deleting the draft.')+ if (draft?.serverId) {+ const result = await this.guard(draft.accountId, async (p, a) => {+ const [remote] = await p.messages(a, [draft.serverId!], true)+ const state = p.getStateToken(a)+ // Discarding a local copy must never remove mail already sent or changed elsewhere.+ if (+ !remote?.keywords.$draft ||+ !draft.serverFingerprint ||+ draftFingerprint(remote) !== draft.serverFingerprint+ )+ return { updated: [], failures: [] }+ return p.update(a, {}, [draft.serverId!], state)+ })+ if (result.failures.length)+ throw new Error('The server draft could not be deleted. Your local draft is preserved.')+ }+ await this.deleteDraftLocal(id)+ await this.persistDrafts()+ this.emit({ type: 'changed' })+ }+ deleteServerDraft = async (accountId: string, messageId: string) => {+ const linked = [...this.localDrafts.values()].find(+ (d) => d.accountId === accountId && d.serverId === messageId,+ )+ if (linked) return this.deleteDraft(linked.id)+ const result = await this.exclusive(accountId, () =>+ this.guard(accountId, async (p, a) => {+ const [message] = await p.messages(a, [messageId])+ const state = p.getStateToken(a)+ if (!message) return { updated: [], failures: [] }+ // Only a message that is still a draft may be removed; one sent meanwhile stays.+ if (!message.keywords.$draft) throw new Error('This message is no longer a draft.')+ return p.update(a, {}, [messageId], state)+ }),+ )+ if (result.failures.length) throw new Error('The server draft could not be deleted.')+ this.emit({ type: 'changed', accountId })+ }+ private mimePath(draftId: string) {+ return join(this.store.directory, 'outgoing', draftId + '.eml')+ }+ private async writeMime(draftId: string, mime: Uint8Array) {+ const directory = join(this.store.directory, 'outgoing')+ await mkdir(directory, { recursive: true, mode: 0o700 })+ const file = await open(this.mimePath(draftId), 'w', 0o600)+ try {+ await file.writeFile(mime)+ await file.sync()+ } finally {+ await file.close()+ }+ }+ private removeMime(draftId: string) {+ return rm(this.mimePath(draftId), { force: true })+ }+ private async outgoingMessage(journal: Journal): Promise<OutgoingMessage> {+ return {+ messageId: journal.messageId || journal.draftId + '@inlark.local',+ emailId: journal.emailId,+ envelope: journal.envelope || { from: '', to: [] },+ mime: journal.mime ? await readFile(this.mimePath(journal.draftId)) : undefined,+ }+ }+ /** A unique Message-ID per attempt, on the sender's own domain. */+ private messageIdFor(account: Account) {+ const domain = account.email+ .split('@')[1]+ ?.toLowerCase()+ .replace(/[^a-z0-9.-]/g, '')+ return randomUUID() + '@' + (domain || 'inlark.invalid')+ }+ private rejectedAddresses(draft: Draft, journal: Journal): Address[] {+ const refused = new Set((journal.rejected || []).map((r) => r.email.toLowerCase()))+ return [...draft.to, ...draft.cc, ...draft.bcc].filter((a) =>+ refused.has(a.email.toLowerCase()),+ )+ }+ private sendResult(journal: Journal, draft?: Draft): SendResult {+ const pending = ['pending', 'appending', 'uncertain', 'failed'].includes(journal.sentCopy || '')+ if (journal.state === 'partial') {+ const rejected = draft ? this.rejectedAddresses(draft, journal) : []+ return {+ status: 'partial',+ message:+ 'Sent to some recipients. ' ++ (journal.rejected?.length || rejected.length) ++ ' refused the message.' ++ (pending ? ' Sent copy pending.' : ''),+ rejected,+ sentCopy: pending ? 'pending' : 'filed',+ }+ }+ return {+ status: 'sent',+ message: pending ? 'Message sent. Sent copy pending.' : 'Message sent.',+ sentCopy: pending ? 'pending' : 'filed',+ }+ }+ send = async (input: Draft): Promise<SendResult> => {+ const draft = sendDraftSchema.parse(input)+ if (!draft.to.length && !draft.cc.length && !draft.bcc.length)+ throw new Error('Add at least one recipient.')+ if (this.busyDrafts.has(draft.id))+ throw new Error('This draft is still saving. Try again in a moment.')+ const existing = this.journals.get(draft.id)+ if (existing && existing.state !== 'rejected') return this.reconcile(draft.id)+ const { provider, account } = this.provider(draft.accountId)+ await this.saveDraft(draft)+ this.busyDrafts.add(draft.id)+ const journal: Journal = {+ draftId: draft.id,+ accountId: draft.accountId,+ subject: draft.subject,+ messageId:+ provider.capabilities.sentCopy === 'client'+ ? this.messageIdFor(account)+ : draft.id + '@inlark.local',+ state: 'preparing',+ at: new Date().toISOString(),+ }+ this.journals.set(draft.id, journal)+ let accepted = false+ // Only set once the durable journal says `submitting` and the network call begins.+ let attempted = false+ let uploaded = draft+ try {+ await this.persistJournal()+ if (draft.serverId) {+ const [remote] = await provider.messages(account, [draft.serverId], true)+ if (!remote || !remote.keywords.$draft)+ throw new ProviderError(+ 'conflict',+ 'This draft was sent or removed in another client. Review it before creating a separate draft.',+ )+ if (remote && draftFingerprint(remote) !== draft.serverFingerprint)+ throw new ProviderError(+ 'conflict',+ 'This draft changed in another client. Save a separate copy before sending.',+ )+ }+ uploaded = await this.uploadDraft(draft)+ const outgoing = await provider.prepareSubmission(account, uploaded, journal.messageId!)+ journal.emailId = outgoing.emailId+ journal.envelope = outgoing.envelope+ if (outgoing.mime) {+ await this.writeMime(draft.id, outgoing.mime)+ journal.mime = true+ }+ if (provider.capabilities.sentCopy === 'client') journal.sentCopy = 'pending'+ // Everything needed to recover must be durable before anything leaves the device.+ journal.state = 'submitting'+ await this.persistJournal()+ this.localDrafts.set(draft.id, { ...uploaded, status: 'sending' })+ await this.persistDrafts()+ attempted = true+ const outcome = await this.guard(account.id, (p, a) =>+ p.submit(a, outgoing, draft.identityId),+ )+ accepted = true+ this.outgoing(account.connectionId, undefined)+ journal.accepted = outcome.accepted+ journal.rejected = outcome.rejected+ journal.state = outcome.rejected.length ? 'partial' : 'sent'+ // Acceptance is recorded before filing or cleanup, which may fail independently.+ await this.persistJournal()+ if (journal.sentCopy) await this.fileSentCopy(journal, outgoing)+ // A partial send keeps its content so the refused recipients can be recovered.+ if (journal.state === 'sent') await this.completeDraft(uploaded)+ else this.localDrafts.set(draft.id, { ...uploaded, status: 'sent' })+ await this.persistDrafts()+ if (draft.serverId && draft.serverId !== journal.emailId)+ await this.removePreviousDraft(provider, account, draft).catch(() =>+ this.log('old-draft-cleanup-failed'),+ )+ this.emit({ type: 'changed', accountId: draft.accountId })+ return this.sendResult(journal, uploaded)+ } catch (error) {+ if (accepted) {+ this.localDrafts.set(draft.id, { ...uploaded, status: 'sent' })+ this.log('sent-local-save-failed')+ return {+ ...this.sendResult(journal, uploaded),+ message:+ 'Message sent. Local status could not be saved; delivery will be reconciled after restart.',+ }+ }+ const ambiguous =+ attempted &&+ !(error instanceof ProviderError && definiteSubmissionCodes.includes(error.code))+ journal.state = ambiguous ? 'uncertain' : 'rejected'+ if (!ambiguous) {+ journal.sentCopy = undefined+ await this.removeMime(draft.id)+ journal.mime = undefined+ }+ await this.persistJournal()+ this.localDrafts.set(draft.id, {+ ...draft,+ status: ambiguous ? 'uncertain' : 'error',+ error: friendlyError(error),+ errorKind: ambiguous ? undefined : errorKind(error),+ })+ await this.persistDrafts()+ if (ambiguous)+ return {+ status: 'uncertain',+ message:+ 'Delivery is not confirmed. Your draft is safe. Check status before trying again.',+ }+ throw error+ } finally {+ this.busyDrafts.delete(draft.id)+ }+ }+ /**+ * Files the Sent copy of an accepted message. Only filing is ever retried: the provider+ * looks for this attempt's Message-ID first, so an earlier unconfirmed append is never+ * duplicated and the message itself is never sent again.+ */+ private async fileSentCopy(journal: Journal, outgoing?: OutgoingMessage) {+ if (!['pending', 'uncertain', 'failed'].includes(journal.sentCopy || '')) return+ if (this.filing.has(journal.draftId)) return+ this.filing.add(journal.draftId)+ try {+ const { provider, account } = this.provider(journal.accountId)+ if (!provider.fileSentCopy) return+ const message = outgoing?.mime ? outgoing : await this.outgoingMessage(journal)+ journal.sentCopy = 'appending'+ await this.persistJournal()+ try {+ journal.sentCopy = await provider.fileSentCopy(account, message)+ journal.sentCopyError = undefined+ await this.persistJournal()+ await this.removeMime(journal.draftId)+ } catch (error) {+ journal.sentCopy =+ error instanceof ProviderError && error.code === 'filingUncertain'+ ? 'uncertain'+ : 'failed'+ journal.sentCopyError = friendlyError(error)+ this.log('sent-copy-failed', journal.sentCopy)+ await this.persistJournal()+ }+ } catch {+ this.log('sent-copy-deferred')+ } finally {+ this.filing.delete(journal.draftId)+ }+ }+ private async retrySentCopies(connectionId: string) {+ const accountIds = new Set(+ this.accounts.filter((a) => a.connectionId === connectionId).map((a) => a.id),+ )+ for (const journal of this.journals.values())+ if (+ accountIds.has(journal.accountId) &&+ ['sent', 'partial'].includes(journal.state) &&+ !journal.dismissed+ )+ await this.fileSentCopy(journal)+ }+ reconcile = async (id: string): Promise<SendResult> => {+ const journal = this.journals.get(id)+ if (!journal) throw new Error('No send attempt found.')+ const draft = this.localDrafts.get(id)+ if (journal.state === 'sent' || journal.state === 'partial') {+ if (journal.state === 'sent' && draft && (draft.status !== 'sent' || this.hasContent(draft)))+ await this.completeDraft(draft)+ return {+ ...this.sendResult(journal, draft),+ message: 'This message has already been sent.',+ }+ }+ if (journal.state === 'uncertain') {+ const message = await this.outgoingMessage(journal).catch(() => undefined)+ // Only server submission records prove delivery. A Sent copy alone does not.+ if (+ message &&+ (await this.guard(journal.accountId, (p, a) => p.submissionExists(a, message)))+ ) {+ journal.state = 'sent'+ await this.persistJournal()+ if (draft) await this.completeDraft(draft)+ this.emit({ type: 'changed', accountId: journal.accountId })+ return { status: 'sent', message: 'Delivery confirmed.', sentCopy: 'filed' }+ }+ }+ return {+ status: 'uncertain',+ message:+ 'Delivery is still unconfirmed. Check Sent or the server before creating a replacement message.',+ }+ }+ private summaries(): SubmissionSummary[] {+ return [...this.journals.values()]+ .filter((j) => !j.dismissed)+ .flatMap((j): SubmissionSummary[] => {+ const draft = this.localDrafts.get(j.draftId)+ const copy: SubmissionSummary['sentCopy'] =+ j.sentCopy === 'pending' || j.sentCopy === 'appending'+ ? 'pending'+ : j.sentCopy === 'uncertain' || j.sentCopy === 'failed'+ ? j.sentCopy+ : undefined+ const base = {+ draftId: j.draftId,+ accountId: j.accountId,+ subject: j.subject ?? draft?.subject ?? '',+ at: j.at,+ ...(copy ? { sentCopy: copy } : {}),+ ...(j.sentCopyError ? { error: j.sentCopyError } : {}),+ }+ if (j.state === 'uncertain') return [{ ...base, state: 'uncertain' }]+ if (j.state === 'partial')+ return [+ {+ ...base,+ state: 'partial',+ rejected: draft+ ? this.rejectedAddresses(draft, j)+ : (j.rejected || []).map((r) => ({ name: '', email: r.email })),+ },+ ]+ if (j.state === 'sent' && copy) return [{ ...base, state: 'sent' }]+ return []+ })+ }+ submissions = async () => this.summaries()+ retrySentCopy = async (id: string): Promise<SendResult> => {+ const journal = this.journals.get(id)+ if (!journal || !['sent', 'partial'].includes(journal.state))+ throw new Error('Only a sent message can have its Sent copy filed again.')+ await this.fileSentCopy(journal)+ return this.sendResult(journal, this.localDrafts.get(id))+ }+ private copyDraft(source: Draft, patch: Partial<Draft>): Draft {+ return {+ ...source,+ id: randomUUID(),+ serverId: undefined,+ serverFingerprint: undefined,+ status: 'local',+ error: undefined,+ errorKind: undefined,+ updatedAt: new Date().toISOString(),+ ...patch,+ }+ }+ recoverRejected = async (id: string): Promise<Draft> => {+ const journal = this.journals.get(id)+ const draft = this.localDrafts.get(id)+ if (journal?.state !== 'partial' || journal.dismissed || !draft)+ throw new Error('There are no refused recipients to recover for this message.')+ const refused = new Set(+ this.rejectedAddresses(draft, journal).map((a) => a.email.toLowerCase()),+ )+ const only = (list: Address[]) => list.filter((a) => refused.has(a.email.toLowerCase()))+ const recovery = this.copyDraft(draft, {+ to: only(draft.to),+ cc: only(draft.cc),+ bcc: only(draft.bcc),+ })+ this.localDrafts.set(recovery.id, recovery)+ journal.dismissed = true+ await this.completeDraft(draft)+ await this.persistJournal()+ return recovery+ }+ replaceUncertain = async (id: string): Promise<Draft> => {+ const journal = this.journals.get(id)+ const draft = this.localDrafts.get(id)+ if (journal?.state !== 'uncertain' || !draft)+ throw new Error('Only an unconfirmed message can be replaced.')+ // The unconfirmed record stays, so its evidence remains available for later checks.+ const replacement = this.copyDraft(draft, {})+ this.localDrafts.set(replacement.id, replacement)+ await this.persistDrafts()+ return replacement+ }+ dismissSubmission = async (id: string): Promise<void> => {+ const journal = this.journals.get(id)+ if (!journal) return+ journal.dismissed = true+ if (journal.sentCopy && journal.sentCopy !== 'filed' && journal.sentCopy !== 'server')+ journal.sentCopy = 'dismissed'+ const draft = this.localDrafts.get(id)+ if (draft && ['partial', 'uncertain'].includes(journal.state)) await this.completeDraft(draft)+ await this.removeMime(id)+ journal.mime = undefined+ await this.persistJournal()+ }+ stageAttachments = async (): Promise<StagedAttachment[]> => {+ const result = await dialog.showOpenDialog({+ title: 'Attach files',+ properties: ['openFile', 'multiSelections'],+ })+ if (result.canceled) return []+ const directory = join(this.store.directory, 'attachments')+ await mkdir(directory, { recursive: true, mode: 0o700 })+ const attachments: StagedAttachment[] = []+ const types: Record<string, string> = {+ '.pdf': 'application/pdf',+ '.png': 'image/png',+ '.jpg': 'image/jpeg',+ '.jpeg': 'image/jpeg',+ '.gif': 'image/gif',+ '.webp': 'image/webp',+ '.txt': 'text/plain',+ '.csv': 'text/csv',+ '.zip': 'application/zip',+ '.ics': 'text/calendar',+ }+ for (const path of result.filePaths) {+ const size = (await stat(path)).size+ if (size > 100_000_000) throw new Error('Files over 100 MB cannot be attached.')+ const a = {+ id: randomUUID(),+ name: basename(path),+ size,+ type: types[extname(path).toLowerCase()] || 'application/octet-stream',+ }+ await copyFile(path, join(directory, a.id))+ await chmod(join(directory, a.id), 0o600)+ this.staging.set(a.id, a)+ attachments.push(a)+ }+ await this.store.write('staging', [...this.staging.values()])+ return attachments+ }+ attachment = async (accountId: string, attachment: Attachment, open: boolean): Promise<void> => {+ const result = await dialog.showSaveDialog({+ title: open ? 'Save and open attachment' : 'Save attachment',+ defaultPath: basename(attachment.name),+ })+ if (result.canceled || !result.filePath) return+ const bytes = await this.guard(accountId, (p, a) => p.download(a, attachment))+ await writeFile(result.filePath, bytes, { mode: 0o600 })+ if (open) {+ const error = await shell.openPath(result.filePath)+ if (error) throw new Error('The file was saved, but no application could open it.')+ }+ }+ inlineImage = async (accountId: string, attachment: Attachment): Promise<string> => {+ if (!/^image\/(png|jpeg|gif|webp|avif)$/i.test(attachment.type) || attachment.size > 10_000_000)+ throw new Error('Unsupported inline image.')+ const bytes = await this.guard(accountId, (p, a) => p.download(a, attachment))+ return 'data:' + attachment.type + ';base64,' + Buffer.from(bytes).toString('base64')+ }+ remoteImage = async (value: string): Promise<string | null> =>+ this.settings.remoteImages ? remoteImageData(value) : null+ senderAvatar = async (email: string): Promise<string | null> => {+ if (!this.settings.remoteImages) return null+ return this.senderAvatars.get(email)+ }+ unsubscribe = async (accountId: string, messageId: string) => {+ const [message] = await this.guard(accountId, (p, a) => p.messages(a, [messageId], true))+ const info = message?.unsubscribe+ if (!info) throw new Error('This message has no supported unsubscribe method.')+ if (info.url.startsWith('mailto:')) return { kind: 'mailto' as const, url: info.url }+ if (info.oneClick) {+ const response = await publicFetch(info.url, {+ method: 'POST',+ body: 'List-Unsubscribe=One-Click',+ headersOnly: true,+ })+ if (response.status < 200 || response.status >= 300)+ throw new Error('The unsubscribe request failed. Try the link in the message.')+ return { kind: 'done' as const }+ }+ await this.openExternal(info.url)+ return { kind: 'browser' as const }+ }+ openExternal = async (value: string): Promise<void> => {+ const url = new URL(value)+ if (!['http:', 'https:', 'mailto:'].includes(url.protocol) || url.username || url.password)+ throw new Error('This link type is not supported.')+ if (url.protocol === 'mailto:') this.emit({ type: 'mailto', url: value })+ else await shell.openExternal(url.toString())+ }+ setSettings = async (settings: Settings) => {+ await this.store.write('settings', settings)+ if (!settings.remoteImages) this.senderAvatars.clear()+ this.settings = settings+ return settings+ }+ diagnostics = async () =>+ JSON.stringify(+ {+ version: app.getVersion(),+ platform: process.platform,+ electron: process.versions.electron,+ secureStorage: secureStorageAvailable(),+ accounts: this.accounts.map((a, index) => ({+ index,+ protocol: a.protocol || 'jmap',+ status: a.status,+ outgoing: a.outgoingError ? 'error' : 'ok',+ indexing: a.indexing+ ? { indexed: a.indexing.indexed, total: a.indexing.total }+ : undefined,+ })),+ submissions: [...this.journals.values()].map((j) => ({+ state: j.state,+ sentCopy: j.sentCopy,+ })),+ events: this.logs,+ },+ null,+ 2,+ )+ async refreshConnection(id: string) {+ if (this.refreshing.has(id)) return+ this.refreshing.add(id)+ try {+ for (const account of this.accounts.filter((a) => a.connectionId === id)) {+ try {+ const { provider } = this.provider(account.id)+ const mailboxes = await provider.mailboxes(account)+ this.unreadCounts.set(+ account.id,+ mailboxes.filter((b) => b.role === 'inbox').reduce((sum, b) => sum + b.unreadEmails, 0),+ )+ this.emit({+ type: 'unread',+ count: [...this.unreadCounts.values()].reduce((sum, n) => sum + n, 0),+ })+ const page = await provider.query(account, { view: 'inbox' }, 0, 25)+ const current = page.items[0]?.receivedAt || new Date().toISOString(),+ previous = this.notificationBaseline.get(account.id)+ const newItems = previous+ ? page.items.filter((c) => c.receivedAt > previous && c.unread)+ : []+ this.notificationBaseline.set(+ account.id,+ previous && previous > current ? previous : current,+ )+ if (+ previous &&+ newItems.length &&+ this.settings.notifications &&+ Notification.isSupported()+ ) {+ const notification = new Notification({+ title:+ newItems.length === 1+ ? newItems[0].from[0]?.name || 'New email'+ : newItems.length + ' new conversations',+ body: newItems.length === 1 ? newItems[0].subject : account.name,+ silent: false,+ })+ notification.on('click', () =>+ this.emit({ type: 'open', accountId: account.id, threadId: newItems[0].id }),+ )+ notification.show()+ }+ this.status(id, 'connected')+ this.emit({ type: 'changed', accountId: account.id })+ } catch (error) {+ this.status(+ id,+ error instanceof ProviderError && error.code === 'authentication'+ ? 'authentication'+ : 'offline',+ friendlyError(error),+ )+ }+ }+ } finally {+ this.refreshing.delete(id)+ }+ }+ private async syncPendingDrafts() {+ const pending = [...this.localDrafts.values()]+ .filter(+ (d) =>+ ['local', 'error'].includes(d.status) &&+ d.identityId &&+ d.errorKind !== 'conflict' &&+ !d.error?.includes('another client') &&+ this.accounts.some((a) => a.id === d.accountId && a.status === 'connected') &&+ Date.now() - Date.parse(d.updatedAt) > 2500,+ )+ .slice(0, 20)+ for (const draft of pending) {+ try {+ await this.syncDraft(draft)+ } catch {+ this.log('background-draft-sync-failed')+ }+ }+ }+ async refresh() {+ await Promise.allSettled(+ this.connections.map(async (c) => {+ const connected = this.accounts.some(+ (a) => a.connectionId === c.id && a.status === 'connected',+ )+ // Rediscover advertised endpoints after outages or session changes. Never replay writes.+ if (this.providers.has(c.id) && connected) {+ await this.refreshConnection(c.id)+ await this.retrySentCopies(c.id)+ } else if (c.secret || c.localSecret || this.sessionSecrets.has(c.id))+ await this.reconnect(c.id)+ }),+ )+ await this.syncPendingDrafts()+ }+ dispose() {+ if (this.timer) clearInterval(this.timer)+ if (this.indexingEmit) clearTimeout(this.indexingEmit)+ for (const provider of this.providers.values()) {+ provider.dispose()+ void provider.close?.()+ }+ }+}diff --git a/apps/desktop/src/main/storage.ts b/apps/desktop/src/main/storage.tsnew file mode 100644index 0000000..eedcaaf--- /dev/null+++ b/apps/desktop/src/main/storage.ts@@ -0,0 +1,118 @@+import { chmod, mkdir, readFile, open, rename, rm } from 'node:fs/promises'+import { join } from 'node:path'+import { randomUUID } from 'node:crypto'+import { safeStorage } from 'electron'++export class JsonStore {+ private queue = Promise.resolve()+ constructor(readonly directory: string) {}+ async init() {+ await mkdir(this.directory, { recursive: true, mode: 0o700 })+ await chmod(this.directory, 0o700)+ }+ private path(name: string) {+ if (!/^[a-z0-9-]+$/.test(name)) throw new Error('Invalid storage key.')+ return join(this.directory, name + '.json')+ }+ /**+ * Reads a versioned envelope. Older versions pass through `migrate`; the original file is+ * copied to `<name>.v<version>.backup.json` before the migrated data atomically replaces it.+ * Unknown, newer, or malformed files fail closed and are never modified.+ */+ async read<T>(+ name: string,+ fallback: T,+ options: { version?: number; migrate?: (data: unknown, version: number) => T } = {},+ ): Promise<T> {+ const current = options.version ?? 1+ let value: { version: unknown; data: unknown }+ let text: string+ try {+ text = await readFile(this.path(name), 'utf8')+ value = JSON.parse(text)+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return fallback+ throw new Error('Could not read local ' + name + ' data. Your files have been preserved.')+ }+ if (value?.version === current) return value.data as T+ const version = value?.version+ if (+ !options.migrate ||+ typeof version !== 'number' ||+ !Number.isInteger(version) ||+ version < 1 ||+ version > current+ )+ throw new Error(+ 'Could not read local ' ++ name ++ ' data: unsupported data version. Your files have been preserved.',+ )+ let migrated: T+ try {+ migrated = options.migrate(value.data, version)+ } catch {+ throw new Error('Could not upgrade local ' + name + ' data. Your files have been preserved.')+ }+ // The backup must be durable before the original is replaced.+ const backup = await open(+ join(this.directory, name + '.v' + version + '.backup.json'),+ 'w',+ 0o600,+ )+ try {+ await backup.writeFile(text)+ await backup.sync()+ } finally {+ await backup.close()+ }+ await this.write(name, migrated, current)+ return migrated+ }+ write(name: string, data: unknown, version = 1): Promise<void> {+ const serialized = JSON.stringify({ version, data })+ const operation = this.queue.then(async () => {+ const target = this.path(name),+ temporary = target + '.' + randomUUID() + '.tmp'+ try {+ const file = await open(temporary, 'wx', 0o600)+ try {+ await file.writeFile(serialized)+ await file.sync()+ } finally {+ await file.close()+ }+ await rename(temporary, target)+ const dir = await open(this.directory, 'r')+ try {+ await dir.sync()+ } finally {+ await dir.close()+ }+ } catch (error) {+ await rm(temporary, { force: true })+ throw error+ }+ })+ this.queue = operation.catch(() => {})+ return operation+ }+}+export function secureStorageAvailable(): boolean {+ return (+ safeStorage.isEncryptionAvailable() &&+ (process.platform !== 'linux' || safeStorage.getSelectedStorageBackend() !== 'basic_text')+ )+}+export function encryptSecret(value: string): string {+ if (!secureStorageAvailable())+ throw new Error(+ 'Secure credential storage is unavailable. Use session-only login or enable a Secret Service provider.',+ )+ return safeStorage.encryptString(value).toString('base64')+}+export function decryptSecret(value: string): string {+ if (!secureStorageAvailable())+ throw new Error('Unlock your OS keyring to reconnect this account.')+ return safeStorage.decryptString(Buffer.from(value, 'base64'))+}diff --git a/apps/desktop/src/preload/index.ts b/apps/desktop/src/preload/index.tsnew file mode 100644index 0000000..78fbe15--- /dev/null+++ b/apps/desktop/src/preload/index.ts@@ -0,0 +1,67 @@+import { contextBridge, ipcRenderer } from 'electron'+import type { DesktopMailAPI, AppEvent } from '@inlark/core'+const methods = [+ 'bootstrap',+ 'ready',+ 'discover',+ 'testConnection',+ 'connect',+ 'connectionSettings',+ 'folderMappings',+ 'setFolderMappings',+ 'disconnect',+ 'reconnect',+ 'updateAccount',+ 'updateAccountDetails',+ 'mailboxes',+ 'identities',+ 'query',+ 'conversation',+ 'mutate',+ 'mutateAll',+ 'undo',+ 'folder',+ 'drafts',+ 'resumeDraft',+ 'stageRemoteAttachments',+ 'saveDraft',+ 'syncDraft',+ 'deleteDraft',+ 'deleteServerDraft',+ 'send',+ 'reconcile',+ 'submissions',+ 'retrySentCopy',+ 'recoverRejected',+ 'replaceUncertain',+ 'dismissSubmission',+ 'stageAttachments',+ 'attachment',+ 'inlineImage',+ 'remoteImage',+ 'senderAvatar',+ 'unsubscribe',+ 'openExternal',+ 'settings',+ 'diagnostics',+] as const satisfies readonly (keyof DesktopMailAPI)[]+// Fails to compile when an API method is missing from the allowlist above.+type Missing = Exclude<keyof DesktopMailAPI, 'onEvent' | (typeof methods)[number]>+const complete: Missing extends never ? true : Missing = true+void complete+const api = Object.fromEntries(+ methods.map((name) => [+ name,+ (...args: unknown[]) => ipcRenderer.invoke('mail:' + name, ...args),+ ]),+)+contextBridge.exposeInMainWorld('mail', {+ ...api,+ onEvent: (callback: (event: AppEvent) => void) => {+ const listener = (_event: Electron.IpcRendererEvent, data: AppEvent) => callback(data)+ ipcRenderer.on('mail:event', listener)+ return () => {+ ipcRenderer.removeListener('mail:event', listener)+ }+ },+} as unknown as DesktopMailAPI)diff --git a/apps/desktop/src/renderer/index.html b/apps/desktop/src/renderer/index.htmlnew file mode 100644index 0000000..ab0f7ac--- /dev/null+++ b/apps/desktop/src/renderer/index.html@@ -0,0 +1,17 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width,initial-scale=1.0" />+ <meta+ http-equiv="Content-Security-Policy"+ content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self'; frame-src 'self' blob:; connect-src 'self' ws://127.0.0.1:* http://127.0.0.1:*; object-src 'none'; base-uri 'none'"+ />+ <link rel="icon" type="image/svg+xml" href="../../resources/icon.svg?no-inline" />+ <title>Inlark</title>+ </head>+ <body>+ <div id="root"></div>+ <script type="module" src="./src/main.tsx"></script>+ </body>+</html>diff --git a/apps/desktop/src/renderer/public/licenses/Inter-OFL.txt b/apps/desktop/src/renderer/public/licenses/Inter-OFL.txtnew file mode 100644index 0000000..9b2ca37--- /dev/null+++ b/apps/desktop/src/renderer/public/licenses/Inter-OFL.txt@@ -0,0 +1,92 @@+Copyright (c) 2016 The Inter Project Authors (https://github.com/rsms/inter)++This Font Software is licensed under the SIL Open Font License, Version 1.1.+This license is copied below, and is also available with a FAQ at:+http://scripts.sil.org/OFL++-----------------------------------------------------------+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007+-----------------------------------------------------------++PREAMBLE+The goals of the Open Font License (OFL) are to stimulate worldwide+development of collaborative font projects, to support the font creation+efforts of academic and linguistic communities, and to provide a free and+open framework in which fonts may be shared and improved in partnership+with others.++The OFL allows the licensed fonts to be used, studied, modified and+redistributed freely as long as they are not sold by themselves. The+fonts, including any derivative works, can be bundled, embedded,+redistributed and/or sold with any software provided that any reserved+names are not used by derivative works. The fonts and derivatives,+however, cannot be released under any other type of license. The+requirement for fonts to remain under this license does not apply+to any document created using the fonts or their derivatives.++DEFINITIONS+"Font Software" refers to the set of files released by the Copyright+Holder(s) under this license and clearly marked as such. This may+include source files, build scripts and documentation.++"Reserved Font Name" refers to any names specified as such after the+copyright statement(s).++"Original Version" refers to the collection of Font Software components as+distributed by the Copyright Holder(s).++"Modified Version" refers to any derivative made by adding to, deleting,+or substituting -- in part or in whole -- any of the components of the+Original Version, by changing formats or by porting the Font Software to a+new environment.++"Author" refers to any designer, engineer, programmer, technical+writer or other person who contributed to the Font Software.++PERMISSION AND CONDITIONS+Permission is hereby granted, free of charge, to any person obtaining+a copy of the Font Software, to use, study, copy, merge, embed, modify,+redistribute, and sell modified and unmodified copies of the Font+Software, subject to the following conditions:++1) Neither the Font Software nor any of its individual components,+in Original or Modified Versions, may be sold by itself.++2) Original or Modified Versions of the Font Software may be bundled,+redistributed and/or sold with any software, provided that each copy+contains the above copyright notice and this license. These can be+included either as stand-alone text files, human-readable headers or+in the appropriate machine-readable metadata fields within text or+binary files as long as those fields can be easily viewed by the user.++3) No Modified Version of the Font Software may use the Reserved Font+Name(s) unless explicit written permission is granted by the corresponding+Copyright Holder. This restriction only applies to the primary font name as+presented to the users.++4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font+Software shall not be used to promote, endorse or advertise any+Modified Version, except to acknowledge the contribution(s) of the+Copyright Holder(s) and the Author(s) or with their explicit written+permission.++5) The Font Software, modified or unmodified, in part or in whole,+must be distributed entirely under this license, and must not be+distributed under any other license. The requirement for fonts to+remain under this license does not apply to any document created+using the Font Software.++TERMINATION+This license becomes null and void if any of the above conditions are+not met.++DISCLAIMER+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM+OTHER DEALINGS IN THE FONT SOFTWARE.diff --git a/apps/desktop/src/renderer/src/AccountAvatarPicker.tsx b/apps/desktop/src/renderer/src/AccountAvatarPicker.tsxnew file mode 100644index 0000000..695f61f--- /dev/null+++ b/apps/desktop/src/renderer/src/AccountAvatarPicker.tsx@@ -0,0 +1,96 @@+import { useRef, useState, type RefObject } from 'react'+import { Menu } from '@base-ui/react/menu'+import { ImageRemove, ImageUpload, Shuffle } from '@inlark/ui/icons'+import { MenuItem, cn } from '@inlark/ui'+import type { AccountAppearance } from '@inlark/core'+import { AccountTile } from './AccountMark'+import { accountImage, accountImageTypes } from './account-image'++/**+ * Lets the user replace an account's generated avatar with a picture of their own, or shuffle the+ * pattern. A picture can also be dropped onto the avatar.+ */+export function AccountAvatarPicker({+ name,+ email,+ value,+ onChange,+ onError,+ portalContainer,+}: {+ name: string+ email: string+ value: AccountAppearance+ onChange: (appearance: AccountAppearance) => void+ onError: (error: unknown) => void+ portalContainer?: RefObject<HTMLElement | null>+}) {+ const input = useRef<HTMLInputElement>(null)+ const [dragging, setDragging] = useState(false)+ const choose = (file?: File) => {+ if (file) accountImage(file).then((image) => onChange({ ...value, image }), onError)+ }+ return (+ <>+ <Menu.Root>+ <Menu.Trigger+ render={+ <button+ type="button"+ className={cn('account-tile-button', dragging && 'dragging')}+ aria-label={'Change avatar for ' + name}+ title="Change avatar"+ onDragOver={(e) => {+ if (![...e.dataTransfer.items].some((item) => item.kind === 'file')) return+ e.preventDefault()+ e.dataTransfer.dropEffect = 'copy'+ setDragging(true)+ }}+ onDragLeave={() => setDragging(false)}+ onDrop={(e) => {+ e.preventDefault()+ setDragging(false)+ choose(e.dataTransfer.files[0])+ }}+ />+ }+ >+ <AccountTile account={{ ...value, email }} />+ </Menu.Trigger>+ <Menu.Portal container={portalContainer}>+ <Menu.Positioner sideOffset={6} align="start" className="account-avatar-menu">+ <Menu.Popup className="dropdown">+ <MenuItem onClick={() => input.current?.click()}>+ <ImageUpload size={15} />+ {value.image ? 'Replace picture…' : 'Upload picture…'}+ </MenuItem>+ {value.image ? (+ <MenuItem onClick={() => onChange({ ...value, image: undefined })}>+ <ImageRemove size={15} />+ Remove picture+ </MenuItem>+ ) : (+ <MenuItem+ onClick={() => onChange({ ...value, seed: crypto.randomUUID().slice(0, 8) })}+ >+ <Shuffle size={15} />+ Shuffle pattern+ </MenuItem>+ )}+ </Menu.Popup>+ </Menu.Positioner>+ </Menu.Portal>+ </Menu.Root>+ <input+ ref={input}+ type="file"+ accept={accountImageTypes}+ hidden+ onChange={(e) => {+ choose(e.target.files?.[0])+ e.target.value = ''+ }}+ />+ </>+ )+}diff --git a/apps/desktop/src/renderer/src/AccountMark.tsx b/apps/desktop/src/renderer/src/AccountMark.tsxnew file mode 100644index 0000000..9afa555--- /dev/null+++ b/apps/desktop/src/renderer/src/AccountMark.tsx@@ -0,0 +1,47 @@+import { useEffect, useState, type CSSProperties } from 'react'+import BoringAvatar from 'boring-avatars'+import { avatarColors, type AccountAppearance } from '@inlark/core'+import { cn } from '@inlark/ui'++type Appearance = AccountAppearance & { email: string }++/** The account's picture, or a marble pattern generated from its address until one is chosen. */+export function AccountMark({+ account,+ size = 16,+ className,+ title,+}: {+ account: Appearance+ size?: number+ className?: string+ title?: string+}) {+ const [imageFailed, setImageFailed] = useState(false)+ useEffect(() => setImageFailed(false), [account.image])+ return (+ <span+ className={cn('account-mark', className)}+ title={title}+ style={{ '--mark-size': size + 'px' } as CSSProperties}+ >+ {account.image && !imageFailed ? (+ <img src={account.image} alt="" draggable={false} onError={() => setImageFailed(true)} />+ ) : (+ <BoringAvatar+ variant="marble"+ name={account.seed || account.email}+ colors={avatarColors}+ size={size}+ square+ aria-hidden+ />+ )}+ </span>+ )+}++/** The larger avatar used in settings. */+export function AccountTile({ account, size = 34 }: { account: Appearance; size?: number }) {+ return <AccountMark account={account} size={size} />+}diff --git a/apps/desktop/src/renderer/src/AccountSetup.tsx b/apps/desktop/src/renderer/src/AccountSetup.tsxnew file mode 100644index 0000000..a505085--- /dev/null+++ b/apps/desktop/src/renderer/src/AccountSetup.tsx@@ -0,0 +1,1013 @@+import {+ useEffect,+ useId,+ useRef,+ useState,+ type FormEvent,+ type InputHTMLAttributes,+ type ReactNode,+} from 'react'+import { useQuery } from '@tanstack/react-query'+import { z } from 'zod'+import { AlertCircle, ArrowLeft, Check, LockKeyhole, PenLine, X as Cross } from '@inlark/ui/icons'+import { Button, Checkbox, Spinner } from '@inlark/ui'+import {+ accountSchema,+ friendlyError,+ type Account,+ type Bootstrap,+ type ConnectInput,+ type ConnectionCheck,+ type ConnectionConfig,+ type ConnectionSettings,+ type ConnectionTest,+ type DiscoveryCandidate,+ type DiscoveryResult,+ type DiscoverySource,+ type FolderMappingReview,+ type FolderMappings,+ type Protocol,+ type ServerSettings,+ type TransportSecurity,+} from '@inlark/core'+import { api, isDemo } from './api'+import { queryClient } from './cache'+import { SegmentedControl } from './SegmentedControl'+import { FolderMappingEditor, initialFolderChoices, needsFolderReview } from './FolderMappings'++/** `signIn` repeats a saved connection's login; `edit` opens its server settings for changes. */+export type SetupMode = 'add' | 'signIn' | 'edit'+type ServerKind = 'incoming' | 'outgoing'+type ServerFields = { host: string; port: string; security: TransportSecurity }+interface Fields {+ protocol: Protocol+ serverUrl: string+ incoming: ServerFields+ outgoing: ServerFields+ username: string+ outgoingUsername: string+ sameLogin: boolean+}+/** Where the settings on screen came from, so the user can judge them before signing in. */+type Origin = { kind: 'candidate'; index: number } | { kind: 'saved' } | { kind: 'manual' }++const defaultPorts = {+ incoming: { tls: 993, starttls: 143 },+ outgoing: { tls: 465, starttls: 587 },+} as const+const securityOptions = [+ { value: 'tls', label: 'SSL/TLS' },+ { value: 'starttls', label: 'STARTTLS' },+] as const+const protocolOptions = [+ { value: 'imap', label: 'IMAP and SMTP' },+ { value: 'jmap', label: 'JMAP' },+] as const+const securityLabel = { tls: 'SSL/TLS', starttls: 'STARTTLS' } as const+const sourceLabels: Record<DiscoverySource, string> = {+ 'jmap-srv': 'Found in the domain’s DNS records',+ 'jmap-well-known': 'Found at the domain’s JMAP address',+ autoconfig: 'From the domain’s published configuration',+ 'imap-srv': 'Found in the domain’s DNS records',+ directory: 'From a public directory of mail providers',+}+const sourceLabel = (candidate: DiscoveryCandidate) =>+ candidate.protocol === 'imap' && candidate.provider && candidate.source !== 'directory'+ ? 'From ' + candidate.provider + '’s published configuration'+ : sourceLabels[candidate.source]++const blankServer = (kind: ServerKind): ServerFields => ({+ host: '',+ port: String(defaultPorts[kind].tls),+ security: 'tls',+})+const blankFields = (email: string): Fields => ({+ protocol: 'imap',+ serverUrl: '',+ incoming: blankServer('incoming'),+ outgoing: blankServer('outgoing'),+ username: email,+ outgoingUsername: email,+ sameLogin: true,+})+function fieldsFrom(source: ConnectionConfig | DiscoveryCandidate, email: string): Fields {+ if (source.protocol === 'jmap')+ return {+ ...blankFields(email),+ protocol: 'jmap',+ serverUrl: source.serverUrl,+ username: source.username || email,+ outgoingUsername: source.username || email,+ }+ const server = (s: ServerSettings): ServerFields => ({+ host: s.host,+ port: String(s.port),+ security: s.security,+ })+ const username = source.incoming.username || email+ const outgoingUsername = source.outgoing.username || username+ return {+ protocol: 'imap',+ serverUrl: '',+ incoming: server(source.incoming),+ outgoing: server(source.outgoing),+ username,+ outgoingUsername,+ sameLogin:+ 'outgoingSameCredentials' in source+ ? source.outgoingSameCredentials+ : outgoingUsername === username,+ }+}+const hostOf = (url: string) => {+ try {+ return new URL(url).host+ } catch {+ return url+ }+}+const candidateTitle = (c: DiscoveryCandidate) =>+ c.protocol === 'jmap' ? hostOf(c.serverUrl) : c.provider || c.incoming.host+const emailSchema = z.email()++function TextField({+ label,+ error,+ hint,+ className,+ ...props+}: InputHTMLAttributes<HTMLInputElement> & {+ label: string+ error?: string+ hint?: ReactNode+}) {+ const id = useId()+ return (+ <label className={'form-field' + (className ? ' ' + className : '')}>+ {label}+ <input+ aria-invalid={error ? true : undefined}+ aria-describedby={error || hint ? id : undefined}+ {...props}+ />+ {error ? (+ <span id={id} className="field-error">+ {error}+ </span>+ ) : (+ hint && (+ <span id={id} className="field-hint">+ {hint}+ </span>+ )+ )}+ </label>+ )+}++function CheckRow({+ label,+ host,+ check,+ pending,+}: {+ label: string+ host: string+ check?: ConnectionCheck+ pending: boolean+}) {+ return (+ <li className={'connection-check ' + (check ? (check.ok ? 'ok' : 'failed') : 'pending')}>+ <span className="connection-check-icon">+ {check ? (+ check.ok ? (+ <Check size={13} />+ ) : (+ <Cross size={13} />+ )+ ) : pending ? (+ <Spinner size={12} />+ ) : null}+ </span>+ <strong>{label}</strong>+ <span className="connection-check-host">{host}</span>+ <span className="connection-check-result">+ {check+ ? check.ok+ ? 'Signed in'+ : check.error || 'Sign-in failed'+ : pending+ ? 'Checking…'+ : 'Not checked'}+ </span>+ </li>+ )+}++/** The server settings of a discovered or saved configuration, shown before any password is sent. */+function ServerSummary({ fields }: { fields: Fields }) {+ return fields.protocol === 'jmap' ? (+ <dl className="server-summary">+ <div>+ <dt>Server · JMAP</dt>+ <dd>+ <span className="server-host">{fields.serverUrl}</span>+ </dd>+ </div>+ </dl>+ ) : (+ <dl className="server-summary">+ {(['incoming', 'outgoing'] as const).map((kind) => (+ <div key={kind}>+ <dt>{kind === 'incoming' ? 'Incoming · IMAP' : 'Outgoing · SMTP'}</dt>+ <dd>+ <span className="server-host">{fields[kind].host}</span>+ <span className="server-meta">+ Port {fields[kind].port} · {securityLabel[fields[kind].security]}+ </span>+ </dd>+ </div>+ ))}+ </dl>+ )+}++export function AccountSetup({+ bootstrap,+ existing,+ mode = existing ? 'signIn' : 'add',+ onDone,+ onBack,+}: {+ bootstrap: Bootstrap+ existing?: Account+ mode?: SetupMode+ onDone: (message: string) => void+ onBack: () => void+}) {+ const [phase, setPhase] = useState<'email' | 'server' | 'folders'>(existing ? 'server' : 'email')+ const [email, setEmail] = useState(existing?.email || '')+ const [emailError, setEmailError] = useState('')+ const [discovering, setDiscovering] = useState(false)+ const [discovery, setDiscovery] = useState<DiscoveryResult>()+ const [notice, setNotice] = useState('')+ const [origin, setOrigin] = useState<Origin>({ kind: 'manual' })+ const [editing, setEditing] = useState(mode === 'edit')+ const [fields, setFields] = useState<Fields>(() => blankFields(existing?.email || ''))+ const [password, setPassword] = useState('')+ const [outgoingPassword, setOutgoingPassword] = useState('')+ const [remember, setRemember] = useState(bootstrap.secureStorage)+ const [name, setName] = useState(existing?.name || '')+ const [senderName, setSenderName] = useState(existing?.senderName || '')+ const [errors, setErrors] = useState<Record<string, string>>({})+ const [error, setError] = useState('')+ const [busy, setBusy] = useState<'testing' | 'connecting'>()+ const [test, setTest] = useState<ConnectionTest>()+ const [review, setReview] = useState<FolderMappingReview>()+ const [choices, setChoices] = useState<FolderMappings>({})+ const pending = useRef<ConnectInput>(undefined)+ const lookup = useRef(0)+ const form = useRef<HTMLFormElement>(null)+ const saved = useQuery({+ queryKey: ['connection-settings', existing?.connectionId],+ queryFn: () => api.connectionSettings(existing!.connectionId),+ enabled: !!existing,+ staleTime: 0,+ gcTime: 0,+ retry: false,+ })+ const savedSettings: ConnectionSettings | undefined = saved.data+ useEffect(() => {+ if (!existing) return+ if (savedSettings) {+ const address =+ savedSettings.config.protocol === 'imap' ? savedSettings.config.email : existing.email+ setEmail(address)+ setFields(fieldsFrom(savedSettings.config, address))+ setOrigin({ kind: 'saved' })+ setRemember(savedSettings.remember)+ setName(savedSettings.name || existing.name)+ } else if (saved.isError) {+ // Without saved settings, the user can still enter them again.+ setFields({ ...blankFields(existing.email), protocol: existing.protocol || 'jmap' })+ setEditing(true)+ setNotice('The saved server settings couldn’t be loaded. Enter them again below.')+ }+ }, [savedSettings, saved.isError])+ const loadingSaved = !!existing && saved.isPending+ useEffect(() => {+ // The folder step replaces the focused button, so move focus to its first choice.+ if (phase === 'folders')+ requestAnimationFrame(() => document.getElementById('folder-role-sent')?.focus())+ }, [phase])+ const domain = email.split('@')[1] || 'example.com'+ const candidates = discovery?.candidates || []++ /** Any change invalidates an earlier connection check and the message it produced. */+ const changed = (...keys: string[]) => {+ setTest(undefined)+ setError('')+ if (keys.some((key) => errors[key]))+ setErrors((current) => {+ const next = { ...current }+ for (const key of keys) delete next[key]+ return next+ })+ }+ const update = (patch: Partial<Fields>, ...keys: string[]) => {+ setFields((current) => ({ ...current, ...patch }))+ changed(...keys)+ }+ const updateServer = (kind: ServerKind, patch: Partial<ServerFields>, ...keys: string[]) => {+ setFields((current) => ({ ...current, [kind]: { ...current[kind], ...patch } }))+ changed(...keys.map((key) => 'config.' + kind + '.' + key))+ }+ const setSecurity = (kind: ServerKind, security: TransportSecurity) =>+ setFields((current) => {+ const server = current[kind]+ // Follow the standard port unless the user entered their own.+ const standard =+ !server.port.trim() || Number(server.port) === defaultPorts[kind][server.security]+ return {+ ...current,+ [kind]: {+ ...server,+ security,+ port: standard ? String(defaultPorts[kind][security]) : server.port,+ },+ }+ })+ const choose = (index: number, result = discovery) => {+ const candidate = result?.candidates[index]+ if (!candidate) return+ setOrigin({ kind: 'candidate', index })+ setFields((current) => {+ const next = fieldsFrom(candidate, email.trim())+ // A username the user already typed is kept, since they know their login best.+ return current.username && current.username !== email.trim()+ ? { ...next, username: current.username }+ : next+ })+ setEditing(false)+ setErrors({})+ changed()+ }+ const manual = () => {+ setEditing(true)+ setOrigin({ kind: 'manual' })+ setErrors({})+ changed()+ }+ const findSettings = async () => {+ const address = email.trim().toLowerCase()+ if (!emailSchema.safeParse(address).success) {+ setEmailError('Enter a valid email address.')+ return+ }+ const token = ++lookup.current+ setDiscovering(true)+ setEmailError('')+ setNotice('')+ setError('')+ try {+ const result = await api.discover(address)+ if (token !== lookup.current) return+ setDiscovery(result)+ setEmail(result.email)+ if (result.candidates.length) {+ setFields(fieldsFrom(result.candidates[0], result.email))+ setOrigin({ kind: 'candidate', index: 0 })+ setEditing(false)+ } else {+ setFields(blankFields(result.email))+ setOrigin({ kind: 'manual' })+ setEditing(true)+ setNotice(+ 'No settings are published for ' + result.domain + '. Enter your server details below.',+ )+ }+ } catch (e) {+ if (token !== lookup.current) return+ setDiscovery(undefined)+ setFields(blankFields(address))+ setOrigin({ kind: 'manual' })+ setEditing(true)+ setNotice(+ 'Settings for ' ++ (address.split('@')[1] || 'this address') ++ ' couldn’t be looked up. ' ++ friendlyError(e) ++ ' Enter your server details below.',+ )+ } finally {+ if (token === lookup.current) setDiscovering(false)+ }+ setTest(undefined)+ setErrors({})+ setPhase('server')+ }+ const setUpManually = () => {+ const address = email.trim().toLowerCase()+ lookup.current+++ setDiscovering(false)+ setDiscovery(undefined)+ setNotice('')+ setFields((current) => ({+ ...current,+ username: current.username || address,+ outgoingUsername: current.outgoingUsername || address,+ }))+ manual()+ setPhase('server')+ }++ /** Builds and validates the request, marking any field the schema rejects. */+ const validate = (): ConnectInput | undefined => {+ const address = email.trim()+ const config =+ fields.protocol === 'jmap'+ ? {+ protocol: 'jmap' as const,+ serverUrl: fields.serverUrl.trim(),+ username: fields.username.trim(),+ }+ : {+ protocol: 'imap' as const,+ email: address,+ incoming: {+ host: fields.incoming.host,+ port: Number(fields.incoming.port.trim()) || 0,+ security: fields.incoming.security,+ username: fields.username.trim(),+ },+ outgoing: {+ host: fields.outgoing.host,+ port: Number(fields.outgoing.port.trim()) || 0,+ security: fields.outgoing.security,+ username: (fields.sameLogin ? fields.username : fields.outgoingUsername).trim(),+ },+ outgoingSameCredentials: fields.sameLogin,+ }+ const separate = fields.protocol === 'imap' && !fields.sameLogin+ const parsed = accountSchema.safeParse({+ config,+ password,+ ...(separate && outgoingPassword ? { outgoingPassword } : {}),+ name: name.trim(),+ ...(senderName.trim() ? { senderName: senderName.trim() } : {}),+ remember,+ ...(existing ? { connectionId: existing.connectionId } : {}),+ ...(savedSettings?.folders ? { folders: savedSettings.folders } : {}),+ })+ if (parsed.success) {+ setErrors({})+ return parsed.data+ }+ const found: Record<string, string> = {}+ for (const issue of parsed.error.issues) {+ const key = issue.path.join('.')+ found[key] ??= issue.message+ }+ setErrors(found)+ // Server fields can only show their errors while they are editable.+ if (Object.keys(found).some((key) => key.startsWith('config.'))) setEditing(true)+ requestAnimationFrame(() =>+ form.current?.querySelector<HTMLElement>('[aria-invalid="true"]')?.focus(),+ )+ return undefined+ }+ const connect = async (input: ConnectInput) => {+ setBusy('connecting')+ setError('')+ try {+ await api.connect(input)+ await queryClient.invalidateQueries({ queryKey: ['bootstrap'] })+ onDone(+ mode === 'add'+ ? 'Account connected.'+ : mode === 'edit'+ ? 'Connection updated.'+ : 'Signed in.',+ )+ } catch (e) {+ setError(friendlyError(e))+ setBusy(undefined)+ }+ }+ const submit = async (event: FormEvent) => {+ event.preventDefault()+ if (busy || discovering) return+ if (phase === 'email') return void findSettings()+ if (phase === 'folders') {+ if (pending.current) await connect({ ...pending.current, folders: choices })+ return+ }+ const input = validate()+ if (!input) return+ if (input.config.protocol === 'jmap') return connect(input)+ // IMAP checks both servers first, so a failure names the server that needs attention.+ setBusy('testing')+ setError('')+ setTest(undefined)+ try {+ const result = await api.testConnection(input)+ setTest(result)+ if (!result.incoming.ok || (result.outgoing && !result.outgoing.ok)) {+ setBusy(undefined)+ return+ }+ pending.current = input+ if (result.folders) {+ // Earlier choices for this connection count as confirmed.+ const known: FolderMappingReview = {+ ...result.folders,+ mappings: { ...result.folders.mappings },+ }+ for (const [role, choice] of Object.entries(savedSettings?.folders || {}))+ known.mappings[role as keyof FolderMappings] = choice && {+ path: choice.path,+ source: 'user',+ }+ if (needsFolderReview(known)) {+ setReview(known)+ setChoices(initialFolderChoices(known))+ setBusy(undefined)+ setPhase('folders')+ return+ }+ }+ await connect(input)+ } catch (e) {+ setError(friendlyError(e))+ setBusy(undefined)+ }+ }++ const title =+ mode === 'edit' ? 'Edit connection' : mode === 'signIn' ? 'Sign in again' : 'Connect an account'+ const accountProblem = existing?.outgoingError+ ? 'Sending unavailable: ' + existing.outgoingError+ : existing && existing.status !== 'connected'+ ? existing.error+ : undefined+ const primaryLabel =+ phase === 'email'+ ? 'Continue'+ : phase === 'folders'+ ? mode === 'add'+ ? 'Connect account'+ : 'Save and sign in'+ : mode === 'add'+ ? 'Connect account'+ : mode === 'edit'+ ? 'Save and sign in'+ : 'Sign in'+ const busyLabel =+ phase === 'email' ? 'Continue' : busy === 'testing' ? 'Checking servers…' : 'Connecting…'+ const isBusy = discovering || !!busy+ const selected = origin.kind === 'candidate' ? candidates[origin.index] : undefined+ const failed = test && (!test.incoming.ok || (test.outgoing && !test.outgoing.ok))++ return (+ <form className="account-form" ref={form} onSubmit={(e) => void submit(e)} noValidate>+ <Button variant="ghost" size="small" className="account-form-back" onClick={onBack}>+ <ArrowLeft size={13} />+ Back to accounts+ </Button>+ <header className="account-form-title">+ <h3>{phase === 'folders' ? 'Check folders' : title}</h3>+ {phase === 'email' ? (+ <p>+ Enter your email address and Inlark looks up your server settings. You’ll see them+ before your password is sent anywhere.+ </p>+ ) : phase === 'folders' ? (+ <p>+ Some folders on {review && fields.incoming.host} couldn’t be confirmed. Choose where+ Inlark keeps sent mail and drafts, and where Archive, Mark as spam and Move to trash put+ conversations. You can change this later.+ </p>+ ) : (+ <p className="account-form-address">+ <span>{email}</span>+ {mode === 'add' && (+ <button+ type="button"+ className="text-action"+ onClick={() => {+ setPhase('email')+ setError('')+ }}+ >+ Change+ </button>+ )}+ </p>+ )}+ </header>+ {accountProblem && phase === 'server' && (+ <div className="form-error account-form-problem">+ <AlertCircle size={14} />+ <span>{accountProblem}</span>+ </div>+ )}++ {phase === 'email' && (+ <section className="account-form-section">+ <TextField+ label="Email address"+ type="email"+ autoFocus+ autoComplete="email"+ spellCheck={false}+ placeholder="[email protected]"+ value={email}+ error={emailError}+ onChange={(e) => {+ setEmail(e.target.value)+ setEmailError('')+ }}+ />+ <div className="setup-lookup" role="status">+ {discovering && (+ <>+ <Spinner size={12} />+ Looking up settings for {email.split('@')[1] || 'your address'}…+ </>+ )}+ </div>+ </section>+ )}++ {phase === 'server' &&+ (loadingSaved ? (+ <div className="setup-lookup" role="status">+ <Spinner size={12} />+ Loading saved settings…+ </div>+ ) : (+ <>+ <section className="account-form-section">+ <div className="account-form-section-heading">+ <h4>Server</h4>+ {editing ? (+ (candidates.length > 0 || savedSettings) &&+ mode !== 'edit' && (+ <Button+ variant="ghost"+ size="small"+ onClick={() => {+ if (savedSettings && !candidates.length) {+ setFields(fieldsFrom(savedSettings.config, email))+ setOrigin({ kind: 'saved' })+ setEditing(false)+ setErrors({})+ changed()+ } else choose(origin.kind === 'candidate' ? origin.index : 0)+ }}+ >+ {savedSettings && !candidates.length+ ? 'Use saved settings'+ : 'Use found settings'}+ </Button>+ )+ ) : (+ <Button variant="ghost" size="small" onClick={() => setEditing(true)}>+ <PenLine size={12} />+ Edit settings+ </Button>+ )}+ </div>+ {notice && (+ <div className="form-notice setup-notice" role="status">+ <AlertCircle size={14} />+ <span>{notice}</span>+ </div>+ )}+ {!editing && candidates.length > 1 && (+ <div+ className="server-options"+ role="radiogroup"+ aria-label="Server settings found"+ >+ {candidates.map((candidate, index) => (+ <label+ key={index}+ className={+ 'server-option' ++ (origin.kind === 'candidate' && origin.index === index ? ' chosen' : '')+ }+ >+ <input+ type="radio"+ className="sr-only"+ name="server-candidate"+ checked={origin.kind === 'candidate' && origin.index === index}+ onChange={() => choose(index)}+ />+ <span className="theme-radio" aria-hidden="true" />+ <span className="protocol-tag">{candidate.protocol.toUpperCase()}</span>+ <span className="server-option-title">{candidateTitle(candidate)}</span>+ <span className="server-option-source">{sourceLabel(candidate)}</span>+ </label>+ ))}+ </div>+ )}+ {!editing && (+ <div className="server-card">+ {candidates.length < 2 && (+ <div className="server-card-heading">+ <span className="protocol-tag">+ {fields.protocol === 'jmap' ? 'JMAP' : 'IMAP · SMTP'}+ </span>+ <span className="server-card-source">+ {selected+ ? sourceLabel(selected)+ : origin.kind === 'saved'+ ? 'Saved settings'+ : 'Entered manually'}+ </span>+ </div>+ )}+ <ServerSummary fields={fields} />+ </div>+ )}+ {editing && (+ <div className="server-fields">+ <div className="form-field">+ <span className="form-label">Protocol</span>+ <SegmentedControl+ label="Protocol"+ value={fields.protocol}+ options={protocolOptions}+ onChange={(protocol) => update({ protocol })}+ />+ </div>+ {fields.protocol === 'jmap' ? (+ <TextField+ label="Server URL"+ type="url"+ autoFocus={mode !== 'edit'}+ spellCheck={false}+ placeholder={'https://mail.' + domain}+ value={fields.serverUrl}+ error={errors['config.serverUrl']}+ hint="A server address or a full JMAP session URL."+ onChange={(e) => update({ serverUrl: e.target.value }, 'config.serverUrl')}+ />+ ) : (+ (['incoming', 'outgoing'] as const).map((kind) => (+ <fieldset className="server-group" key={kind}>+ <legend>+ {kind === 'incoming' ? 'Incoming mail · IMAP' : 'Outgoing mail · SMTP'}+ </legend>+ <div className="server-row">+ <TextField+ label="Server"+ autoFocus={kind === 'incoming' && mode !== 'edit'}+ spellCheck={false}+ autoCapitalize="off"+ placeholder={(kind === 'incoming' ? 'imap.' : 'smtp.') + domain}+ value={fields[kind].host}+ error={errors['config.' + kind + '.host']}+ onChange={(e) => updateServer(kind, { host: e.target.value }, 'host')}+ />+ <TextField+ label="Port"+ inputMode="numeric"+ className="port-field"+ value={fields[kind].port}+ error={errors['config.' + kind + '.port']}+ onChange={(e) =>+ updateServer(+ kind,+ { port: e.target.value.replace(/\D/g, '').slice(0, 5) },+ 'port',+ )+ }+ />+ <div className="form-field">+ <span className="form-label">Security</span>+ <SegmentedControl+ label={+ (kind === 'incoming' ? 'Incoming' : 'Outgoing') + ' server security'+ }+ value={fields[kind].security}+ options={securityOptions}+ onChange={(security) => {+ setSecurity(kind, security)+ changed('config.' + kind + '.port')+ }}+ />+ </div>+ </div>+ </fieldset>+ ))+ )}+ </div>+ )}+ </section>++ <section className="account-form-section">+ <h4>Sign in</h4>+ <div className="form-row">+ <TextField+ label="Username"+ autoComplete="username"+ spellCheck={false}+ autoCapitalize="off"+ value={fields.username}+ error={+ errors['config.username'] ||+ errors['config.incoming.username'] ||+ (fields.sameLogin ? errors['config.outgoing.username'] : undefined)+ }+ onChange={(e) =>+ update(+ { username: e.target.value },+ 'config.username',+ 'config.incoming.username',+ 'config.outgoing.username',+ )+ }+ />+ <TextField+ label="Password or app password"+ type="password"+ autoComplete="current-password"+ autoFocus={!editing}+ placeholder="Your password"+ value={password}+ error={errors.password}+ onChange={(e) => {+ setPassword(e.target.value)+ changed('password')+ }}+ />+ </div>+ {fields.protocol === 'imap' && (+ <>+ <label className="checkbox-label">+ <Checkbox+ checked={fields.sameLogin}+ onCheckedChange={(sameLogin) =>+ update({ sameLogin }, 'outgoingPassword', 'config.outgoing.username')+ }+ />+ Outgoing server uses the same login+ </label>+ {!fields.sameLogin && (+ <div className="form-row">+ <TextField+ label="Outgoing username"+ autoComplete="off"+ spellCheck={false}+ autoCapitalize="off"+ value={fields.outgoingUsername}+ error={errors['config.outgoing.username']}+ onChange={(e) =>+ update({ outgoingUsername: e.target.value }, 'config.outgoing.username')+ }+ />+ <TextField+ label="Outgoing password"+ type="password"+ autoComplete="off"+ placeholder="Outgoing server password"+ value={outgoingPassword}+ error={errors.outgoingPassword}+ onChange={(e) => {+ setOutgoingPassword(e.target.value)+ changed('outgoingPassword')+ }}+ />+ </div>+ )}+ </>+ )}+ <label className="checkbox-label">+ <Checkbox+ checked={remember}+ disabled={isDemo}+ onCheckedChange={(checked) => setRemember(checked)}+ />+ {bootstrap.secureStorage+ ? 'Remember this login in the OS keyring'+ : 'Remember this login on this device'}+ </label>+ {!bootstrap.secureStorage && (+ <div className="form-notice">+ <LockKeyhole size={14} />+ <span>+ {isDemo+ ? 'Demo accounts stay in this window and never connect to a server.'+ : 'No OS keyring is available. If you remember this login, your password will be saved unencrypted in a file accessible to your user account. Leave the box unchecked for session-only login.'}+ </span>+ </div>+ )}+ </section>++ {mode === 'add' && (+ <section className="account-form-section">+ <h4>How it appears</h4>+ <div className="form-row">+ <TextField+ label="Label"+ placeholder="Personal"+ maxLength={100}+ hint="Only you see this."+ value={name}+ onChange={(e) => setName(e.target.value)}+ />+ <TextField+ label="Your name"+ placeholder="Jane Doe"+ autoComplete="name"+ maxLength={100}+ value={senderName}+ onChange={(e) => setSenderName(e.target.value)}+ hint={+ <>+ Recipients see{' '}+ <span className="sender-preview">+ {(senderName.trim() || 'your server’s name') + ' <' + email + '>'}+ </span>+ </>+ }+ />+ </div>+ </section>+ )}++ {fields.protocol === 'imap' && (busy === 'testing' || test) && (+ <section className="account-form-section" aria-live="polite">+ <h4>Connection check</h4>+ <ul className="connection-checks">+ <CheckRow+ label="Incoming"+ host={fields.incoming.host}+ check={test?.incoming}+ pending={busy === 'testing'}+ />+ <CheckRow+ label="Outgoing"+ host={fields.outgoing.host}+ check={test?.outgoing}+ pending={busy === 'testing'}+ />+ </ul>+ {failed && (+ <p className="connection-check-hint">+ Nothing was saved. Check the password or the server settings above, then try+ again.+ </p>+ )}+ </section>+ )}+ </>+ ))}++ {phase === 'folders' && review && (+ <section className="account-form-section">+ <FolderMappingEditor+ review={review}+ value={choices}+ onChange={setChoices}+ disabled={!!busy}+ />+ </section>+ )}++ {error && (+ <div role="alert" className="form-error">+ <AlertCircle size={14} />+ <span>{error}</span>+ </div>+ )}+ <footer className="account-form-footer">+ {phase === 'email' && (+ <Button variant="ghost" className="account-form-manual" onClick={setUpManually}>+ Set up manually+ </Button>+ )}+ {phase === 'folders' ? (+ <Button onClick={() => setPhase('server')} disabled={!!busy}>+ Back+ </Button>+ ) : (+ <Button onClick={onBack}>Cancel</Button>+ )}+ <Button type="submit" variant="primary" disabled={isBusy || loadingSaved}>+ {isBusy ? (+ <>+ <Spinner size={14} />+ {busyLabel}+ </>+ ) : (+ primaryLabel+ )}+ </Button>+ </footer>+ </form>+ )+}diff --git a/apps/desktop/src/renderer/src/App.tsx b/apps/desktop/src/renderer/src/App.tsxnew file mode 100644index 0000000..21122d9--- /dev/null+++ b/apps/desktop/src/renderer/src/App.tsx@@ -0,0 +1,1990 @@+import { useEffect, useMemo, useRef, useState, lazy, Suspense } from 'react'+import { useInfiniteQuery, useQueries, useQuery } from '@tanstack/react-query'+import { useNavigate, useSearch } from '@tanstack/react-router'+import { useHotkey, useHotkeySequence } from '@tanstack/react-hotkeys'+import {+ Inbox,+ Search,+ PenLine,+ Archive,+ FileText,+ Trash2,+ Mail,+ Plus,+ Settings as SettingsIcon,+ ChevronRight,+ ChevronDown,+ Keyboard,+ SlidersHorizontal,+ MoreHorizontal,+ Check,+ X,+ RefreshCw,+ WifiOff,+ Rows3,+ AlertCircle,+ Star,+ MailOpen,+ FolderInput,+ ShieldX,+ Reply,+ ReplyAll,+ Forward,+ Undo2,+ Folder,+ FolderPlus,+ Moon,+ Sun,+ Monitor,+ PanelLeftOpen,+ PanelLeftClose,+ UserRound,+ Info,+} from '@inlark/ui/icons'+import { Button, Checkbox, Dropdown, MenuItem, IconButton, EmptyState, Spinner } from '@inlark/ui'+import {+ defaultSettings,+ scopeKey,+ unlinkedServerDrafts,+ friendlyError,+ identityKey,+ mailtoDraft,+ replyRecipients,+ type Address,+ type Bootstrap,+ type Conversation,+ type Draft,+ type MailAction,+ type Mailbox,+ type MailQuery,+ type Message,+ type MutationTarget,+ type QueryPage,+ type SubmissionSummary,+ type View,+} from '@inlark/core'+import { api, isDemo } from './api'+import {+ queryClient,+ localDrafts,+ localSaveDraft,+ localDeleteDraft,+ suspendPersistence,+ resumePersistence,+} from './cache'+import { Reader } from './Reader'+import { MoveDialog } from './MoveDialog'+import { CommandPalette, type Command } from './CommandPalette'+import { Sidebar, views } from './Sidebar'+import { ConversationList, type ConversationListHandle } from './ConversationList'+import { DraftRows, DraftSelectionBar, deletable, type DraftItem } from './DraftList'+import { longDate } from './mail-date'+import {+ ShortcutDialog,+ FilterDialog,+ FolderDialog,+ ConfirmActionDialog,+ type FolderDialogState,+} from './AppDialogs'+import { messageText } from './message-text'+import { selectConversation } from './selection'+import { useCharacterKey } from './character-key'+import { emptyListState } from './empty-states'+import { AccountMark } from './AccountMark'+import { HintIconButton } from './HintIconButton'+import { targetAccounts, targetLimit } from './account-limits'+import { SubmissionList } from './SendingStatus'+import { IndexingMeter } from './IndexingMeter'+const Composer = lazy(() => import('./Composer').then((m) => ({ default: m.Composer })))+const SettingsPanel = lazy(() => import('./Settings').then((m) => ({ default: m.SettingsPanel })))++type Toast = {+ text: string+ undoId?: string+ /** Undoes a change the client has not committed yet. */+ onUndo?: () => void+ tone?: 'error' | 'info'+}+let toastSequence = 0+const discardKeys = (item: DraftItem) =>+ item.kind === 'local' && item.draft.serverId+ ? [item.key, 'server:' + scopeKey(item.draft.accountId, item.draft.serverId)]+ : [item.key]+const escapeHtml = (s: string) =>+ s.replace(+ /[&<>"']/g,+ (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]!,+ )+export function App() {+ const route = useSearch({ from: '/' }),+ navigate = useNavigate()+ const boot = useQuery({ queryKey: ['bootstrap'], queryFn: () => api.bootstrap() })+ const bootstrap: Bootstrap = boot.data || {+ accounts: [],+ settings: defaultSettings,+ secureStorage: false,+ demo: isDemo,+ version: '0.1.0',+ }+ const { accounts, settings } = bootstrap+ const view = (+ views.some((v) => v.id === route.view) || route.view === 'all' ? route.view : 'inbox'+ ) as View+ const [collapsed, setCollapsed] = useState(localStorage.getItem('sidebar-collapsed') === 'true')+ const [density, setDensity] = useState<'compact' | 'comfortable'>(() =>+ localStorage.getItem('mail-density') === 'comfortable' ? 'comfortable' : 'compact',+ )+ const [settingsOpen, setSettingsOpen] = useState(false),+ [settingsTab, setSettingsTab] = useState('general')+ const [composer, setComposer] = useState<Draft>(),+ [paletteOpen, setPaletteOpen] = useState(false),+ [help, setHelp] = useState(false)+ const [searchOpen, setSearchOpen] = useState(!!route.q),+ [search, setSearch] = useState(route.q || '')+ const [filters, setFilters] = useState<Partial<MailQuery>>({}),+ [filterOpen, setFilterOpen] = useState(false)+ const [selected, setSelected] = useState(new Set<string>()),+ [focused, setFocused] = useState(''),+ [allMatching, setAllMatching] = useState(false)+ const [toast, setToastState] = useState<Toast & { id: number }>(),+ [busy, setBusy] = useState(false),+ [progress, setProgress] = useState('')+ const [folderDialog, setFolderDialog] = useState<FolderDialogState>()+ const [moveTargets, setMoveTargets] = useState<MutationTarget[]>(),+ [confirmAction, setConfirmAction] = useState<MailAction>()+ const listRef = useRef<HTMLDivElement>(null),+ listHandle = useRef<ConversationListHandle>(null),+ offsets = useRef(new Map<string, number>()),+ lastRead = useRef(''),+ searchInput = useRef<HTMLInputElement>(null)+ const selectionAnchor = useRef<string | undefined>(undefined)+ const [draftSelected, setDraftSelected] = useState(new Set<string>()),+ draftAnchor = useRef<string | undefined>(undefined)+ // Keep successful deletions hidden for this session; delayed server results can still be stale.+ const [discarding, setDiscarding] = useState(new Set<string>()),+ pendingDiscard = useRef<{ toastId: number; items: DraftItem[] } | undefined>(undefined)+ const pendingMailto = useRef<string | undefined>(undefined)+ const setToast = (next?: Toast) => {+ const id = ++toastSequence+ setToastState(next && { ...next, id })+ return id+ }+ const notify = (text: string, tone?: Toast['tone']) => setToast({ text, tone })+ const fail = (error: unknown) => notify(friendlyError(error), 'error')+ const explain = ({ account, reason }: { account: { name: string }; reason: string }) =>+ notify((accounts.length > 1 ? account.name + ' · ' : '') + reason, 'info')+ const account = accounts.find((a) => a.id === route.account),+ folderAccountId = account?.id || accounts[0]?.id || ''+ const boxes = useQuery({+ queryKey: ['mailboxes', folderAccountId],+ queryFn: () => api.mailboxes(folderAccountId),+ enabled: !!folderAccountId,+ })+ const mailboxCounts = useQueries({+ queries: accounts.map((a) => ({+ queryKey: ['mailboxes', a.id],+ queryFn: () => api.mailboxes(a.id),+ enabled: a.status === 'connected',+ })),+ combine: (results) =>+ results.reduce(+ (counts, result, index) => {+ const account = accounts[index]+ if (account) counts.boxesByAccount[account.id] = result.data || []+ if (account?.status !== 'connected') return counts+ for (const box of result.data || []) {+ if (box.role === 'inbox') {+ counts.unread += box.unreadEmails+ counts.byAccount[box.accountId] = box.unreadEmails+ }+ if (box.role === 'drafts') counts.drafts += box.totalEmails+ }+ return counts+ },+ {+ unread: 0,+ drafts: 0,+ byAccount: {} as Record<string, number>,+ boxesByAccount: {} as Record<string, Mailbox[]>,+ },+ ),+ })+ const currentFolder = boxes.data?.find((b) => b.id === route.folder)+ const query: MailQuery = useMemo(+ () => ({+ view: route.q ? 'all' : view,+ // A remembered location can name an account that was removed since; show all mail instead.+ accountId: accounts.some((a) => a.id === route.account) ? route.account : undefined,+ mailboxId: route.folder,+ text: route.q || undefined,+ ...filters,+ }),+ [view, route.account, route.folder, route.q, filters, accounts],+ )+ const queryId = JSON.stringify(query)+ useEffect(() => {+ setSelected(new Set())+ setAllMatching(false)+ setFocused('')+ selectionAnchor.current = undefined+ }, [queryId])+ const mail = useInfiniteQuery({+ queryKey: ['mail', query],+ queryFn: ({ pageParam }) => api.query(query, pageParam),+ initialPageParam: undefined as Record<string, number> | undefined,+ getNextPageParam: (last) => last.next,+ enabled: accounts.length > 0,+ })+ const conversations = useMemo(+ () => [+ ...new Map((mail.data?.pages.flatMap((p) => p.items) || []).map((c) => [c.key, c])).values(),+ ],+ [mail.data],+ )+ const total = mail.data?.pages[0]?.total || 0+ // Accounts still indexing may be missing older mail, so their results are never the whole story.+ const incomplete = useMemo(+ () =>+ [...new Set(mail.data?.pages.flatMap((p) => p.incompleteAccounts || []) || [])]+ .map((id) => accounts.find((a) => a.id === id))+ .filter((a): a is (typeof accounts)[number] => !!a),+ [mail.data, accounts],+ )+ const drafts = useQuery({+ queryKey: ['drafts'],+ queryFn: async () => {+ const values = await Promise.all([api.drafts(), localDrafts()])+ const merged = new Map<string, Draft>()+ for (const draft of values.flat()) {+ const old = merged.get(draft.id)+ if (+ !old ||+ (old.status !== 'sent' && old.status !== 'uncertain' && old.updatedAt < draft.updatedAt)+ )+ merged.set(draft.id, draft)+ }+ return [...merged.values()]+ .filter((d) => accounts.some((a) => a.id === d.accountId) && d.status !== 'sent')+ .sort((a, b) => b.updatedAt.localeCompare(a.updatedAt))+ },+ enabled: !!accounts.length,+ })+ const allDraftItems = useMemo<DraftItem[]>(+ () => [+ ...unlinkedServerDrafts(conversations, drafts.data || []).map((message) => ({+ kind: 'server' as const,+ key: 'server:' + scopeKey(message.accountId, message.id),+ message,+ })),+ ...(drafts.data || [])+ .filter((draft) => !route.account || draft.accountId === route.account)+ .map((draft) => ({ kind: 'local' as const, key: 'local:' + draft.id, draft })),+ ],+ [conversations, drafts.data, route.account],+ )+ const draftItems = allDraftItems.filter((item) => !discarding.has(item.key))+ const submissions = useQuery({+ queryKey: ['submissions'],+ queryFn: () => api.submissions(),+ enabled: !!accounts.length,+ })+ const pendingSends = (submissions.data || []).filter((s) =>+ accounts.some((a) => a.id === s.accountId),+ )+ const readerAccount = accounts.find((a) => a.id === route.threadAccount)+ const listed = conversations.find(+ (c) => c.id === route.thread && c.accountId === route.threadAccount,+ )+ const thread = useQuery({+ queryKey: ['thread', route.threadAccount, route.thread],+ queryFn: () => api.conversation(route.threadAccount!, route.thread!),+ enabled: !!route.thread && !!readerAccount,+ // Open instantly from the list summary; bodies arrive a moment later.+ placeholderData: listed+ ? [...listed.messages].sort((a, b) => a.receivedAt.localeCompare(b.receivedAt))+ : undefined,+ })+ useEffect(() => {+ localStorage.setItem('mail-density', density)+ }, [density])+ const blocked =+ !!composer ||+ settingsOpen ||+ paletteOpen ||+ help ||+ filterOpen ||+ !!folderDialog ||+ !!moveTargets ||+ !!confirmAction+ const go = (next: Partial<typeof route>, reset = true) => {+ if (reset) {+ setSelected(new Set())+ setDraftSelected(new Set())+ setAllMatching(false)+ setFilters({})+ }+ void navigate({ to: '/', search: reset ? next : { ...route, ...next } })+ }+ const back = () => {+ go({ thread: undefined, threadAccount: undefined }, false)+ lastRead.current = ''+ }+ const open = (c: Conversation) => {+ if (listRef.current) offsets.current.set(queryId, listRef.current.scrollTop)+ setFocused(c.key)+ go({ thread: c.id, threadAccount: c.accountId }, false)+ }+ const targets = (): MutationTarget[] =>+ route.thread+ ? [{ accountId: route.threadAccount!, threadId: route.thread }]+ : conversations+ .filter((c) => selected.has(c.key) || (!selected.size && c.key === focused))+ .map((c) => ({ accountId: c.accountId, threadId: c.id }))+ const refresh = async () => {+ await Promise.all(+ ['mail', 'thread', 'mailboxes', 'drafts', 'submissions'].map((key) =>+ queryClient.invalidateQueries({ queryKey: [key] }),+ ),+ )+ }+ const act = async (+ action: MailAction,+ explicit?: MutationTarget[],+ mailboxId?: string,+ confirmed = false,+ ) => {+ if (busy) return+ // A server that can't do this safely explains why instead of failing halfway.+ const limit = targetLimit(+ accounts,+ allMatching && !explicit+ ? route.account+ ? [route.account]+ : accounts.map((a) => a.id)+ : targetAccounts(explicit || targets()),+ action,+ )+ if (limit) {+ explain(limit)+ return+ }+ if (!confirmed && ((allMatching && !explicit) || action === 'destroy')) {+ setConfirmAction(action)+ return+ }+ const chosen = explicit || targets()+ if (!chosen.length && !allMatching) return+ const leaves = ['archive', 'trash', 'spam', 'move', 'destroy'].includes(action)+ // Triage flows straight into the next conversation instead of bouncing to the list.+ const current = conversations.findIndex(+ (c) => c.id === route.thread && c.accountId === route.threadAccount,+ )+ const preference = settings.afterArchive || 'next'+ const neighbor =+ route.thread && leaves && current >= 0 && preference !== 'list'+ ? preference === 'next'+ ? (conversations[current + 1] ?? conversations[current - 1])+ : (conversations[current - 1] ?? conversations[current + 1])+ : undefined+ setBusy(true)+ suspendPersistence()+ const saved = queryClient.getQueriesData({ queryKey: ['mail'] })+ await queryClient.cancelQueries({ queryKey: ['mail'] })+ if (!allMatching)+ queryClient.setQueriesData<{ pages: QueryPage[] }>(+ { queryKey: ['mail'] },+ (current) =>+ current && {+ ...current,+ pages: current.pages.map((p) => ({+ ...p,+ items: p.items.flatMap((c) => {+ if (!chosen.some((t) => t.accountId === c.accountId && t.threadId === c.id))+ return [c]+ if (leaves) return []+ return [+ {+ ...c,+ ...(action === 'read' || action === 'unread'+ ? { unread: action === 'unread' }+ : {}),+ ...(action === 'star' || action === 'unstar'+ ? { starred: action === 'star' }+ : {}),+ },+ ]+ }),+ })),+ },+ )+ if (route.thread && (leaves || action === 'unread')) {+ if (neighbor) open(neighbor)+ else back()+ }+ try {+ const result =+ allMatching && !explicit+ ? await api.mutateAll(query, action)+ : await api.mutate({ targets: chosen, action, mailboxId })+ const count = allMatching && !explicit ? result.changed : chosen.length+ setToast({+ tone: result.failures.length ? 'error' : undefined,+ text: result.failures.length+ ? result.changed + ' updated · ' + result.failures[0]+ : (count > 1 ? count.toLocaleString() + ' conversations · ' : '') ++ {+ archive: 'Archived',+ trash: 'Moved to trash',+ spam: 'Marked as spam',+ read: 'Marked as read',+ unread: 'Marked as unread',+ star: 'Starred',+ unstar: 'Star removed',+ move: 'Moved',+ restore: 'Restored to inbox',+ notSpam: 'Moved to inbox',+ destroy: 'Permanently deleted',+ }[action],+ undoId: result.undoId,+ })+ setSelected(new Set())+ setAllMatching(false)+ } catch (e) {+ saved.forEach(([key, value]) => queryClient.setQueryData(key, value))+ fail(e)+ } finally {+ resumePersistence()+ setBusy(false)+ setProgress('')+ await refresh()+ }+ }+ const openMove = (chosen: MutationTarget[]) => {+ const limit = targetLimit(accounts, targetAccounts(chosen), 'move')+ if (limit) explain(limit)+ else if (chosen.length) setMoveTargets(chosen)+ }+ /** Why the current conversation or selection can't take this action, if it can't. */+ const unavailable = (action: MailAction) =>+ targetLimit(+ accounts,+ allMatching+ ? route.account+ ? [route.account]+ : accounts.map((a) => a.id)+ : targetAccounts(targets()),+ action,+ )?.reason+ const compose = async (+ message?: Message,+ kind: 'reply' | 'replyAll' | 'forward' = 'reply',+ partial: Partial<Draft> = {},+ ) => {+ const id = message?.accountId || route.account || settings.defaultAccountId || accounts[0]?.id+ if (!id) {+ setSettingsTab('accounts')+ setSettingsOpen(true)+ return+ }+ try {+ const identities = await queryClient.fetchQuery({+ queryKey: ['identities', id],+ queryFn: () => api.identities(id),+ })+ if (!identities.length) {+ notify('This account has no permitted sending identities.')+ return+ }+ const recipients = message+ ? replyRecipients(message, identities, kind === 'replyAll')+ : undefined+ const identity = recipients?.identity || identities[0]+ const signature =+ settings.signatures[identityKey(id, identity.id)] ?? identity.textSignature ?? ''+ const who = (list: Address[]) =>+ list.map((a) => (a.name ? a.name + ' <' + a.email + '>' : a.email)).join(', ')+ const header = !message+ ? []+ : kind === 'forward'+ ? [+ '---------- Forwarded message ----------',+ 'From: ' + who(message.from),+ 'Date: ' + longDate(message.receivedAt),+ 'Subject: ' + (message.subject || '(No subject)'),+ 'To: ' + who(message.to),+ ...(message.cc.length ? ['Cc: ' + who(message.cc)] : []),+ ]+ : ['On ' + longDate(message.receivedAt) + ', ' + who(message.from) + ' wrote:']+ const body = message ? messageText(message) : ''+ const quote = message+ ? kind === 'forward'+ ? '<p>' ++ header.map(escapeHtml).join('<br/>') ++ '</p><p>' ++ escapeHtml(body).replace(/\n/g, '<br/>') ++ '</p>'+ : '<p>' ++ escapeHtml(header[0]) ++ '</p><blockquote><p>' ++ escapeHtml(body).replace(/\n/g, '<br/>') ++ '</p></blockquote>'+ : ''+ const html =+ '<p>' ++ escapeHtml(partial.text || '').replace(/\n/g, '<br/>') ++ '</p>' ++ (signature ? '<p><br/>' + escapeHtml(signature).replace(/\n/g, '<br/>') + '</p>' : '') ++ quote+ const text = [+ partial.text || '',+ signature,+ message+ ? header.join('\n') + '\n' + (kind === 'forward' ? body : body.replace(/^/gm, '> '))+ : '',+ ]+ .filter(Boolean)+ .join('\n\n')+ const draft: Draft = {+ id: crypto.randomUUID(),+ accountId: id,+ identityId: identity.id,+ to: kind === 'forward' ? [] : recipients?.to || [],+ cc: recipients?.cc || [],+ bcc: [],+ subject: message+ ? (kind === 'forward' ? 'Fwd: ' : /^re:/i.test(message.subject) ? '' : 'Re: ') ++ message.subject+ : '',+ attachments: [],+ updatedAt: new Date().toISOString(),+ status: 'local',+ ...(message && kind !== 'forward'+ ? {+ inReplyTo: message.messageId,+ references: [...(message.references || []), ...(message.messageId || [])],+ replyThreadId: message.threadId,+ }+ : {}),+ ...partial,+ html,+ text,+ }+ if (kind === 'forward' && message?.attachments?.length)+ draft.attachments = (await api.stageRemoteAttachments(id, message.attachments)).map(+ (a) => ({ ...a, cid: undefined }),+ )+ await localSaveDraft(draft)+ setComposer(draft)+ } catch (e) {+ fail(e)+ }+ }+ const onMailto = (url: string) => {+ try {+ if (!accounts.length) {+ pendingMailto.current = url+ setSettingsTab('accounts')+ setSettingsOpen(true)+ return+ }+ void compose(undefined, 'reply', mailtoDraft(url))+ } catch (e) {+ fail(e)+ }+ }+ const step = (delta: number) => {+ if (+ route.thread &&+ delta > 0 &&+ conversations.at(-1)?.id === route.thread &&+ conversations.at(-1)?.accountId === route.threadAccount &&+ mail.hasNextPage+ ) {+ void mail+ .fetchNextPage()+ .then((result) => {+ const next = result.data?.pages+ .flatMap((p) => p.items)+ .find((c) => !conversations.some((old) => old.key === c.key))+ if (next) open(next)+ })+ .catch((e) => fail(e))+ return+ }+ const current = conversations.findIndex((c) =>+ route.thread+ ? c.id === route.thread && c.accountId === route.threadAccount+ : c.key === focused,+ )+ const next = conversations[Math.max(0, Math.min(conversations.length - 1, current + delta))]+ if (next) {+ if (route.thread) open(next)+ else {+ setFocused(next.key)+ listHandle.current?.scrollToConversation(next.key)+ }+ }+ }+ const toggle = (key: string, range = false) => {+ setAllMatching(false)+ setSelected((previous) =>+ selectConversation(+ conversations.map((c) => c.key),+ allMatching ? new Set(conversations.map((c) => c.key)) : previous,+ key,+ range ? selectionAnchor.current : undefined,+ ),+ )+ if (!range || !selectionAnchor.current) selectionAnchor.current = key+ }+ const toggleDraft = (key: string, range = false) => {+ setDraftSelected((previous) =>+ selectConversation(+ draftItems.filter(deletable).map((item) => item.key),+ previous,+ key,+ range ? draftAnchor.current : undefined,+ ),+ )+ if (!range || !draftAnchor.current) draftAnchor.current = key+ }+ const openDraft = async (item: DraftItem) => {+ if (item.kind === 'local') return setComposer(item.draft)+ try {+ const draft = await api.resumeDraft(item.message.accountId, item.message.id)+ await localSaveDraft(draft)+ setComposer(draft)+ } catch (e) {+ fail(e)+ }+ }+ const commitDiscard = async (items: DraftItem[]) => {+ const failures: string[] = []+ const failedKeys: string[] = []+ for (const item of items) {+ try {+ if (item.kind === 'server')+ await api.deleteServerDraft(item.message.accountId, item.message.id)+ else {+ await api.deleteDraft(item.draft.id)+ await localDeleteDraft(item.draft.id)+ }+ } catch (e) {+ failures.push(friendlyError(e))+ failedKeys.push(...discardKeys(item))+ }+ }+ await refresh()+ setDiscarding((current) => {+ const next = new Set(current)+ for (const key of failedKeys) next.delete(key)+ return next+ })+ if (failures.length)+ notify(+ (failures.length > 1 ? failures.length + ' drafts' : 'A draft') ++ ' could not be deleted · ' ++ failures[0],+ 'error',+ )+ }+ const discardDrafts = (keys: Iterable<string>) => {+ const chosen = new Set(keys)+ const items = draftItems.filter((item) => chosen.has(item.key) && deletable(item))+ if (!items.length) return+ // Only one deletion waits for undo at a time; an earlier one is committed right away.+ if (pendingDiscard.current) void commitDiscard(pendingDiscard.current.items)+ setDiscarding((current) => new Set([...current, ...items.flatMap(discardKeys)]))+ setDraftSelected(new Set())+ const toastId = setToast({+ text: items.length > 1 ? items.length + ' drafts deleted' : 'Draft deleted',+ onUndo: () => {+ if (pendingDiscard.current?.items !== items) return+ pendingDiscard.current = undefined+ setDiscarding((current) => {+ const next = new Set(current)+ for (const item of items) for (const key of discardKeys(item)) next.delete(key)+ return next+ })+ notify(items.length > 1 ? 'Drafts restored' : 'Draft restored')+ },+ })+ pendingDiscard.current = { toastId, items }+ }+ useEffect(() => {+ const media = matchMedia('(prefers-color-scheme: light)')+ const apply = () =>+ (document.documentElement.dataset.theme =+ settings.theme === 'system' ? (media.matches ? 'light' : 'dark') : settings.theme)+ apply()+ media.addEventListener('change', apply)+ return () => media.removeEventListener('change', apply)+ }, [settings.theme])+ useEffect(() => {+ localStorage.setItem('sidebar-collapsed', String(collapsed))+ }, [collapsed])+ useEffect(() => {+ setSearch(route.q || '')+ }, [route.q])+ useEffect(() => {+ const unread = mailboxCounts.unread+ document.title =+ (route.thread && thread.data?.at(-1)?.subject+ ? thread.data.at(-1)!.subject + ' · '+ : route.q+ ? 'Search · '+ : '') ++ (unread ? 'Inbox (' + unread.toLocaleString() + ') · ' : '') ++ 'Inlark'+ }, [route.thread, route.q, thread.data, mailboxCounts.unread])+ useEffect(() => {+ // Reopen where you left off: the same view, account and folder (not a stale conversation).+ try {+ localStorage.setItem(+ 'last-location',+ JSON.stringify({ view: route.view, account: route.account, folder: route.folder }),+ )+ } catch {+ /* Remembering the location is a convenience only. */+ }+ }, [route.view, route.account, route.folder])+ useEffect(() => {+ const key = route.threadAccount + ':' + route.thread+ if (+ route.thread &&+ thread.data &&+ readerAccount?.status === 'connected' &&+ lastRead.current !== key+ ) {+ lastRead.current = key+ if (thread.data.some((m) => !m.keywords.$seen))+ void api+ .mutate({+ targets: [{ accountId: readerAccount.id, threadId: route.thread }],+ action: 'read',+ })+ .then(refresh)+ .catch((e) => fail(e))+ }+ }, [route.thread, route.threadAccount, thread.data, readerAccount?.status])+ useEffect(() => {+ const unsubscribe = api.onEvent((event) => {+ if (event.type === 'changed') void refresh()+ if (event.type === 'accounts') {+ queryClient.setQueryData<Bootstrap>(+ ['bootstrap'],+ (old) => old && { ...old, accounts: event.accounts },+ )+ void refresh()+ }+ if (event.type === 'mailto') onMailto(event.url)+ if (event.type === 'open')+ go({ thread: event.threadId, threadAccount: event.accountId }, false)+ if (event.type === 'progress')+ setProgress(event.completed.toLocaleString() + ' of ' + event.total.toLocaleString())+ if (event.type === 'submissions')+ // A pushed list is newer than any fetch still in flight, so that fetch must not win.+ void queryClient+ .cancelQueries({ queryKey: ['submissions'] })+ .then(() =>+ queryClient.setQueryData<SubmissionSummary[]>(['submissions'], event.submissions),+ )+ })+ if (boot.data) void api.ready().catch((e) => fail(e))+ return unsubscribe+ }, [accounts, queryId, !!boot.data])+ useEffect(() => {+ if (accounts.length && pendingMailto.current) {+ const url = pendingMailto.current+ pendingMailto.current = undefined+ setSettingsOpen(false)+ onMailto(url)+ }+ }, [accounts.length])+ useEffect(() => {+ if (!route.thread) return+ const index = conversations.findIndex(+ (c) => c.id === route.thread && c.accountId === route.threadAccount,+ )+ for (const nearby of [conversations[index - 1], conversations[index + 1]]) {+ if (nearby && accounts.some((a) => a.id === nearby.accountId && a.status === 'connected'))+ void queryClient.prefetchQuery({+ queryKey: ['thread', nearby.accountId, nearby.id],+ queryFn: () => api.conversation(nearby.accountId, nearby.id),+ staleTime: 60_000,+ })+ }+ }, [route.thread, route.threadAccount, conversations])+ const [toastHeld, setToastHeld] = useState(false)+ const canUndo = !!toast?.undoId || !!toast?.onUndo+ const toastDuration = canUndo ? 9000 : toast?.tone === 'error' ? 8000 : 5000+ useEffect(() => {+ if (!toast || toastHeld) return+ const timer = setTimeout(() => setToast(undefined), toastDuration)+ return () => clearTimeout(timer)+ }, [toast, toastHeld])+ useEffect(() => {+ const pending = pendingDiscard.current+ if (!pending || pending.toastId === toast?.id) return+ pendingDiscard.current = undefined+ void commitDiscard(pending.items)+ }, [toast?.id])+ const undo = async (id = toast?.undoId) => {+ if (toast?.onUndo) return toast.onUndo()+ if (!id) return+ setToast({ text: 'Undoing…' })+ try {+ const result = await api.undo(id)+ if (result.failures.length) notify(result.failures[0], 'error')+ else notify('Undone.')+ await refresh()+ } catch (e) {+ fail(e)+ }+ }+ const openSettings = (tab = 'general') => {+ setSettingsTab(tab)+ setSettingsOpen(true)+ }+ const focusSearch = () => {+ setSearchOpen(true)+ requestAnimationFrame(() => searchInput.current?.select())+ }+ const latest = thread.data?.at(-1)+ const toggleStar = () =>+ void act(+ (+ route.thread+ ? thread.data?.some((m) => m.keywords.$flagged)+ : conversations.find((c) => c.key === focused)?.starred+ )+ ? 'unstar'+ : 'star',+ )+ const hasTarget = !!route.thread || !!selected.size || !!focused+ const on = { conflictBehavior: 'replace', enabled: !blocked } as const+ useHotkey('Mod+K', () => setPaletteOpen((p) => !p), {+ conflictBehavior: 'replace',+ enabled: !composer,+ ignoreInputs: false,+ })+ useHotkey('Mod+,', () => openSettings(), { ...on, ignoreInputs: false })+ useHotkey('[', () => setCollapsed((c) => !c), on)+ useHotkey('C', () => void compose(), on)+ useHotkey('/', focusSearch, on)+ useHotkey('J', () => step(1), on)+ useHotkey('K', () => step(-1), on)+ useHotkey('ArrowDown', () => step(1), on)+ useHotkey('ArrowUp', () => step(-1), on)+ useHotkey(+ 'Enter',+ () => {+ const c = conversations.find((c) => c.key === focused) || conversations[0]+ if (c && !route.thread) open(c)+ },+ on,+ )+ useHotkey(+ 'O',+ () => {+ const c = conversations.find((c) => c.key === focused) || conversations[0]+ if (c && !route.thread) open(c)+ },+ on,+ )+ useHotkey(+ 'Escape',+ () => {+ if (route.thread) back()+ else if (draftSelected.size) setDraftSelected(new Set())+ else if (selected.size || allMatching) {+ setSelected(new Set())+ setAllMatching(false)+ } else if (searchOpen || route.q) {+ setSearch('')+ setSearchOpen(false)+ if (route.q) go({ q: undefined }, false)+ }+ },+ on,+ )+ useHotkey(+ 'X',+ () => {+ if (focused) toggle(focused)+ },+ { ...on, enabled: !blocked && !route.thread },+ )+ useHotkey(+ 'Shift+X',+ () => {+ if (focused) toggle(focused, true)+ },+ { ...on, enabled: !blocked && !route.thread },+ )+ useHotkey(+ 'Mod+A',+ () => {+ if (view === 'drafts')+ return setDraftSelected(new Set(draftItems.filter(deletable).map((item) => item.key)))+ setSelected(new Set(conversations.map((c) => c.key)))+ setAllMatching(false)+ },+ { ...on, enabled: !blocked && !route.thread },+ )+ // In Drafts, the trash keys delete the selected drafts rather than moving conversations.+ const trashKey = () => (view === 'drafts' ? discardDrafts(draftSelected) : void act('trash'))+ const canTrash = !blocked && (view === 'drafts' ? !!draftSelected.size : hasTarget)+ useHotkey('E', () => void act('archive'), { ...on, enabled: !blocked && hasTarget })+ useHotkey('Backspace', trashKey, { ...on, enabled: canTrash })+ useHotkey('Delete', trashKey, { ...on, enabled: canTrash })+ useCharacterKey('#', trashKey, canTrash)+ useCharacterKey('!', () => void act('spam'), !blocked && hasTarget)+ useCharacterKey('?', () => setHelp(true), !blocked)+ useHotkey('U', () => void act('unread'), { ...on, enabled: !blocked && hasTarget })+ useHotkey('Shift+U', () => void act('unread'), { ...on, enabled: !blocked && hasTarget })+ useHotkey('Shift+I', () => void act('read'), { ...on, enabled: !blocked && hasTarget })+ useHotkey('S', toggleStar, { ...on, enabled: !blocked && hasTarget })+ useHotkey('V', () => openMove(targets()), {+ ...on,+ enabled: !blocked && hasTarget && !allMatching,+ })+ useHotkey('Z', () => void undo(), { ...on, enabled: !blocked && canUndo })+ useHotkey('Mod+Z', () => void undo(), { ...on, enabled: !blocked && canUndo })+ useHotkey(+ 'R',+ () => {+ if (latest) void compose(latest)+ },+ { ...on, enabled: !blocked && !!route.thread },+ )+ useHotkey(+ 'A',+ () => {+ if (latest) void compose(latest, 'replyAll')+ },+ { ...on, enabled: !blocked && !!route.thread },+ )+ useHotkey(+ 'F',+ () => {+ if (latest) void compose(latest, 'forward')+ },+ { ...on, enabled: !blocked && !!route.thread },+ )+ useHotkeySequence(['G', 'I'], () => go({ view: 'inbox' }), on)+ useHotkeySequence(['G', 'S'], () => go({ view: 'starred' }), on)+ useHotkeySequence(['G', 'T'], () => go({ view: 'sent' }), on)+ useHotkeySequence(['G', 'D'], () => go({ view: 'drafts' }), on)+ useHotkeySequence(['G', 'A'], () => go({ view: 'archive' }), on)+ const suggestions = useMemo(() => {+ // People you hear from most come first; your own addresses never appear.+ const own = new Set(accounts.map((a) => a.email.toLowerCase()))+ const seen = new Map<string, { address: Address; count: number }>()+ for (const c of conversations)+ for (const m of c.messages)+ for (const address of [...m.from, ...m.to, ...m.cc]) {+ const key = address.email.toLowerCase()+ if (own.has(key)) continue+ const entry = seen.get(key)+ if (entry) {+ entry.count+++ if (!entry.address.name && address.name) entry.address = address+ } else seen.set(key, { address, count: 1 })+ }+ return [...seen.values()].sort((a, b) => b.count - a.count).map((entry) => entry.address)+ }, [conversations, accounts])+ const savePreferences = async (patch: Partial<typeof settings>) => {+ try {+ const next = await api.settings({ ...settings, ...patch })+ queryClient.setQueryData<Bootstrap>(['bootstrap'], (old) => old && { ...old, settings: next })+ } catch (e) {+ fail(e)+ }+ }+ const commandTarget = route.thread || selected.size || focused+ const limited = (action: MailAction) => {+ const reason = commandTarget ? unavailable(action) : undefined+ return reason ? { disabled: true, description: reason } : {}+ }+ const conversationCommands: Command[] = commandTarget+ ? [+ {+ id: 'archive',+ label: 'Archive',+ icon: Archive,+ key: 'E',+ run: () => void act('archive'),+ ...limited('archive'),+ },+ {+ id: 'trash',+ label: 'Move to trash',+ icon: Trash2,+ key: '#',+ keywords: 'delete',+ run: () => void act('trash'),+ ...limited('trash'),+ },+ {+ id: 'read',+ label: 'Mark as read',+ icon: MailOpen,+ key: 'Shift I',+ run: () => void act('read'),+ },+ {+ id: 'unread',+ label: 'Mark as unread',+ icon: Mail,+ key: 'U',+ run: () => void act('unread'),+ },+ {+ id: 'star',+ label: 'Star or unstar',+ icon: Star,+ key: 'S',+ keywords: 'flag favorite',+ run: toggleStar,+ },+ ...(!allMatching+ ? [+ {+ id: 'move',+ label: 'Move to folder…',+ icon: FolderInput,+ key: 'V',+ keywords: 'label file',+ run: () => openMove(targets()),+ ...limited('move'),+ },+ ]+ : []),+ {+ id: 'spam',+ label: 'Mark as spam',+ icon: ShieldX,+ key: '!',+ keywords: 'junk',+ run: () => void act('spam'),+ ...limited('spam'),+ },+ ...(latest && route.thread+ ? [+ {+ id: 'reply',+ label: 'Reply',+ icon: Reply,+ key: 'R',+ run: () => void compose(latest),+ },+ {+ id: 'reply-all',+ label: 'Reply all',+ icon: ReplyAll,+ key: 'A',+ run: () => void compose(latest, 'replyAll'),+ },+ {+ id: 'forward',+ label: 'Forward',+ icon: Forward,+ key: 'F',+ run: () => void compose(latest, 'forward'),+ },+ ]+ : []),+ ].map((c) => ({+ ...c,+ group: route.thread ? 'Conversation' : selected.size > 1 ? 'Selection' : 'Conversation',+ }))+ : []+ const commands: Command[] = [+ ...(toast && canUndo+ ? [+ {+ id: 'undo',+ group: 'Suggested',+ label: 'Undo “' + toast.text + '”',+ icon: Undo2,+ key: 'Z',+ run: () => void undo(),+ },+ ]+ : []),+ ...conversationCommands,+ {+ id: 'compose',+ group: 'Mail',+ label: 'Compose a message',+ icon: PenLine,+ key: 'C',+ keywords: 'new write email',+ run: () => void compose(),+ },+ {+ id: 'search-mail',+ group: 'Mail',+ label: 'Search mail',+ icon: Search,+ key: '/',+ keywords: 'find',+ run: focusSearch,+ },+ {+ id: 'refresh',+ group: 'Mail',+ label: 'Check for new mail',+ icon: RefreshCw,+ keywords: 'refresh sync reload',+ run: () => void refresh(),+ },+ ...views.map((v) => ({+ id: 'view-' + v.id,+ group: 'Go to',+ label: v.title,+ icon: v.icon,+ key: v.key,+ keywords: 'go open view ' + (v.id === 'junk' ? 'junk' : ''),+ run: () => go({ view: v.id }),+ })),+ ...(accounts.length > 1+ ? [+ {+ id: 'account-all',+ group: 'Accounts',+ label: 'All accounts',+ icon: Inbox,+ keywords: 'unified switch account',+ checked: !account,+ run: () => go({ view: 'inbox' }),+ },+ ...accounts.map((a) => ({+ id: 'account-' + a.id,+ group: 'Accounts',+ label: a.name,+ icon: Inbox,+ account: a,+ keywords: a.email + ' switch account',+ checked: account?.id === a.id,+ run: () => go({ view: 'inbox', account: a.id }),+ })),+ ]+ : []),+ ...(boxes.data || [])+ .filter((b) => !b.role)+ .map((b) => ({+ id: 'folder-' + b.id,+ group: 'Folders',+ label: b.name,+ icon: Folder,+ keywords: 'folder open go',+ run: () => go({ view: 'all', account: b.accountId, folder: b.id }),+ })),+ {+ id: 'folder-new',+ group: 'Folders',+ label: 'Create a folder…',+ icon: FolderPlus,+ keywords: 'new folder',+ run: () => setFolderDialog({ operation: 'create' }),+ },+ ...(['dark', 'light', 'system'] as const).map((theme) => ({+ id: 'theme-' + theme,+ group: 'Preferences',+ label: { dark: 'Dark theme', light: 'Light theme', system: 'Match system theme' }[theme],+ icon: { dark: Moon, light: Sun, system: Monitor }[theme],+ keywords: 'appearance theme mode colour color',+ checked: settings.theme === theme,+ run: () => void savePreferences({ theme }),+ })),+ {+ id: 'density',+ group: 'Preferences',+ label: density === 'compact' ? 'Comfortable density' : 'Compact density',+ icon: Rows3,+ keywords: 'display rows spacing list',+ run: () => setDensity(density === 'compact' ? 'comfortable' : 'compact'),+ },+ {+ id: 'sidebar',+ group: 'Preferences',+ label: collapsed ? 'Expand sidebar' : 'Collapse sidebar',+ icon: collapsed ? PanelLeftOpen : PanelLeftClose,+ key: '[',+ keywords: 'navigation panel hide show',+ run: () => setCollapsed(!collapsed),+ },+ {+ id: 'settings',+ group: 'Preferences',+ label: 'Settings',+ icon: SettingsIcon,+ key: 'Ctrl ,',+ keywords: 'preferences options',+ run: () => openSettings(),+ },+ {+ id: 'accounts',+ group: 'Preferences',+ label: 'Manage accounts',+ icon: UserRound,+ keywords: 'add connect sign in',+ run: () => openSettings('accounts'),+ },+ {+ id: 'signatures',+ group: 'Preferences',+ label: 'Edit signatures',+ icon: PenLine,+ keywords: 'sign-off',+ run: () => openSettings('signatures'),+ },+ {+ id: 'shortcuts',+ group: 'Help',+ label: 'Keyboard shortcuts',+ icon: Keyboard,+ key: '?',+ keywords: 'help keys hotkeys',+ run: () => setHelp(true),+ },+ ]+ const activeIndex = conversations.findIndex(+ (c) => c.id === route.thread && c.accountId === route.threadAccount,+ )+ const title = route.q+ ? 'Search results'+ : currentFolder?.name || views.find((v) => v.id === view)?.title || 'All mail'+ const hasFilters = Object.values(filters).some(Boolean)+ // The Unread tab is a filter too, but an empty Unread list isn't a failed search.+ const hasSearchFilters = Object.entries(filters).some(([key, value]) => key !== 'unread' && value)+ const filterLabels: Record<string, string> = {+ from: 'From',+ to: 'To',+ subject: 'Subject',+ after: 'After',+ before: 'Before',+ hasAttachment: 'Has attachments',+ }+ const filterChips = Object.entries(filters).filter(([key, value]) => key !== 'unread' && value)+ const selectedCount = allMatching ? total : selected.size+ const changeFolder = async (name: string) => {+ if (!folderDialog) return+ const accountId = folderDialog.accountId || folderDialog.folder?.accountId || folderAccountId+ try {+ await api.folder({+ accountId,+ operation: folderDialog.operation,+ id: folderDialog.folder?.id,+ name,+ })+ setFolderDialog(undefined)+ await refresh()+ if (+ folderDialog.operation === 'delete' &&+ route.account === accountId &&+ route.folder === folderDialog.folder?.id+ )+ go({ view: 'inbox', account: accountId })+ notify(+ 'Folder ' ++ (folderDialog.operation === 'create'+ ? 'created'+ : folderDialog.operation === 'rename'+ ? 'renamed'+ : 'deleted') ++ '.',+ )+ } catch (e) {+ fail(e)+ }+ }+ return (+ <div className={'app-shell ' + (collapsed ? 'sidebar-collapsed ' : '') + 'density-' + density}>+ <Sidebar+ accounts={accounts}+ boxesByAccount={mailboxCounts.boxesByAccount}+ route={route}+ view={view}+ draftCount={drafts.data?.filter((d) => !discarding.has('local:' + d.id)).length || 0}+ hasServerDrafts={mailboxCounts.drafts > 0}+ sendingIssues={pendingSends.length}+ unreadCount={mailboxCounts.unread}+ accountUnread={mailboxCounts.byAccount}+ collapsed={collapsed}+ onToggleCollapsed={() => setCollapsed(!collapsed)}+ onSearch={() => setPaletteOpen(true)}+ onCompose={() => void compose()}+ onNavigate={go}+ onSettings={(tab) => {+ setSettingsTab(tab)+ setSettingsOpen(true)+ }}+ onFolderAction={(operation, accountId, folder) =>+ setFolderDialog({ operation, accountId, folder })+ }+ />+ <main className="main-content">+ {!boot.data ? (+ <EmptyState+ icon={Mail}+ title={boot.isError ? 'Inlark couldn’t start' : 'Starting Inlark'}+ description={boot.isError ? friendlyError(boot.error) : undefined}+ >+ {!boot.isError && <Spinner />}+ </EmptyState>+ ) : !accounts.length ? (+ <EmptyState+ icon={Inbox}+ title="Welcome to Inlark"+ description="Connect your email account to get started."+ >+ <Button+ variant="primary"+ onClick={() => {+ setSettingsTab('accounts')+ setSettingsOpen(true)+ }}+ >+ <Plus size={14} />+ Connect an account+ </Button>+ </EmptyState>+ ) : route.thread && readerAccount ? (+ thread.data ? (+ <Reader+ key={scopeKey(readerAccount.id, route.thread!)}+ messages={thread.data}+ backLabel={title}+ busy={busy}+ account={readerAccount}+ settings={settings}+ onBack={back}+ onPrevious={activeIndex > 0 ? () => step(-1) : undefined}+ onNext={+ activeIndex >= 0 &&+ (activeIndex < conversations.length - 1 || mail.hasNextPage) &&+ !mail.isFetchingNextPage+ ? () => step(1)+ : undefined+ }+ position={activeIndex >= 0 ? activeIndex + 1 + ' of ' + total.toLocaleString() : ''}+ loading={thread.isPlaceholderData}+ onAction={(action) => void act(action)}+ onMove={() => openMove(targets())}+ onReply={(message, kind) => void compose(message, kind)}+ notify={notify}+ onMailto={onMailto}+ />+ ) : (+ <EmptyState+ icon={thread.isError ? WifiOff : Mail}+ title={thread.isError ? 'This conversation is unavailable' : 'Opening conversation'}+ description={thread.isError ? friendlyError(thread.error) : undefined}+ >+ <Button onClick={back}>Back to inbox</Button>+ </EmptyState>+ )+ ) : (+ <>+ <div className="list-heading">+ <div className="list-title">+ <div className="list-eyebrow">+ Mail <ChevronRight size={10} />+ <Dropdown+ trigger={+ <button className="account-switcher" aria-label="Switch account">+ {account && <AccountMark account={account} size={16} />}+ <span>{account?.name || 'All accounts'}</span>+ <ChevronDown size={11} />+ </button>+ }+ >+ <div className="account-menu">+ <div className="menu-label">Mail accounts</div>+ <MenuItem onClick={() => go({ view, q: route.q })}>+ <Inbox size={15} />+ <span className="account-menu-label">+ <strong>All accounts</strong>+ <small>Unified inbox</small>+ </span>+ {!account && <Check size={14} className="account-menu-check" />}+ </MenuItem>+ <div className="account-menu-divider" />+ {accounts.map((item) => (+ <MenuItem+ key={item.id}+ onClick={() => go({ view, q: route.q, account: item.id })}+ >+ <AccountMark account={item} size={28} />+ <span className="account-menu-label">+ <strong>{item.name}</strong>+ <small>{item.email}</small>+ </span>+ {item.id === account?.id && (+ <Check size={14} className="account-menu-check" />+ )}+ </MenuItem>+ ))}+ </div>+ </Dropdown>+ </div>+ <h1>+ {title}+ <span>+ {view === 'drafts'+ ? (+ total ++ (drafts.data?.filter(+ (d) => (!route.account || d.accountId === route.account) && !d.serverId,+ ).length || 0) -+ (allDraftItems.length - draftItems.length)+ ).toLocaleString()+ : total.toLocaleString() + (incomplete.length ? '+' : '')}+ </span>+ </h1>+ {route.q && <p>Results for “{route.q}”</p>}+ </div>+ <div className="list-heading-actions">+ <IconButton label="Refresh mail" onClick={() => void refresh()}>+ <RefreshCw+ size={15}+ className={mail.isFetching && !mail.isFetchingNextPage ? 'spin' : ''}+ />+ </IconButton>+ <IconButton+ label="Search mail"+ shortcut="/"+ onClick={() => {+ setSearchOpen(!searchOpen)+ requestAnimationFrame(() => searchInput.current?.focus())+ }}+ >+ <Search size={16} />+ </IconButton>+ {view !== 'drafts' && (+ <Dropdown+ trigger={+ <IconButton label="Display options">+ <Rows3 size={15} />+ </IconButton>+ }+ >+ <div className="menu-label">Message density</div>+ <MenuItem onClick={() => setDensity('comfortable')}>+ <span className="menu-check">+ {density === 'comfortable' && <Check size={14} />}+ </span>+ Comfortable+ </MenuItem>+ <MenuItem onClick={() => setDensity('compact')}>+ <span className="menu-check">+ {density === 'compact' && <Check size={14} />}+ </span>+ Compact+ </MenuItem>+ </Dropdown>+ )}+ </div>+ </div>+ {searchOpen && (+ <form+ className="mail-search"+ onSubmit={(e) => {+ e.preventDefault()+ go({ q: search || undefined, ...(search ? { view: 'all' } : {}) }, false)+ }}+ >+ <Search size={16} />+ <input+ ref={searchInput}+ placeholder="Search mail"+ aria-label="Search email"+ value={search}+ onChange={(e) => setSearch(e.target.value)}+ />+ <kbd>Enter</kbd>+ <IconButton+ label="Clear search"+ onClick={() => {+ setSearch('')+ setSearchOpen(false)+ go({ q: undefined }, false)+ }}+ >+ <X size={14} />+ </IconButton>+ </form>+ )}+ {!!filterChips.length && (+ <div className="active-filters" aria-label="Active filters">+ {filterChips.map(([key, value]) => (+ <button+ key={key}+ className="filter-chip"+ aria-label={'Remove ' + (filterLabels[key] || key) + ' filter'}+ onClick={() => setFilters((current) => ({ ...current, [key]: undefined }))}+ >+ <span>+ {filterLabels[key] || key}+ {typeof value === 'string' &&+ ': ' + (key === 'after' || key === 'before' ? value.slice(0, 10) : value)}+ </span>+ <X size={12} />+ </button>+ ))}+ <button className="clear-filters" onClick={() => setFilters({})}>+ Clear all+ </button>+ </div>+ )}+ {view !== 'drafts' && (+ <div className="list-toolbar">+ <Checkbox+ aria-label={selected.size ? 'Deselect all' : 'Select loaded conversations'}+ checked={+ allMatching ||+ (conversations.length > 0 && selected.size === conversations.length)+ }+ indeterminate={+ !allMatching && selected.size > 0 && selected.size < conversations.length+ }+ disabled={!conversations.length || busy}+ onCheckedChange={() => {+ setSelected(+ selected.size ? new Set() : new Set(conversations.map((c) => c.key)),+ )+ setAllMatching(false)+ }}+ />+ <div className="list-tabs">+ <button+ aria-pressed={!filters.unread}+ className={!filters.unread ? 'active' : ''}+ onClick={() => setFilters((f) => ({ ...f, unread: undefined }))}+ >+ All messages+ </button>+ <button+ aria-pressed={!!filters.unread}+ className={filters.unread ? 'active' : ''}+ onClick={() => setFilters((f) => ({ ...f, unread: true }))}+ >+ Unread+ </button>+ </div>+ <div className="list-toolbar-actions">+ <Button variant="ghost" size="small" onClick={() => setFilterOpen(true)}>+ <SlidersHorizontal size={13} />+ Filter{hasFilters && <span className="filter-dot" />}+ </Button>+ </div>+ </div>+ )}+ {!!selected.size && view !== 'drafts' && (+ <div className="selection-bar" role="region" aria-label="Selection actions">+ <div className="selection-summary">+ <span className="selection-count" role="status">+ {selectedCount.toLocaleString()} selected+ </span>+ {!allMatching && total > selected.size && (+ <button+ className="text-action"+ disabled={busy}+ onClick={() => setAllMatching(true)}+ >+ Select all {total.toLocaleString()}+ </button>+ )}+ </div>+ <span className="toolbar-divider" />+ <HintIconButton+ label="Archive selected"+ shortcut="E"+ disabled={busy}+ hint={unavailable('archive')}+ onClick={() => void act('archive')}+ >+ <Archive size={16} />+ </HintIconButton>+ <IconButton+ label="Mark selected read"+ disabled={busy}+ onClick={() => void act('read')}+ >+ <Check size={16} />+ </IconButton>+ <HintIconButton+ label="Trash selected"+ disabled={busy}+ hint={unavailable('trash')}+ onClick={() => void act('trash')}+ >+ <Trash2 size={16} />+ </HintIconButton>+ <Dropdown+ trigger={+ <Button+ variant="ghost"+ size="icon"+ disabled={busy}+ aria-label="More selection actions"+ >+ <MoreHorizontal size={16} />+ </Button>+ }+ >+ <MenuItem onClick={() => void act('unread')}>Mark unread</MenuItem>+ <MenuItem onClick={() => void act('star')}>Star</MenuItem>+ <MenuItem+ onClick={() => openMove(targets())}+ disabled={allMatching || !!unavailable('move')}+ >+ Move to folder+ </MenuItem>+ <MenuItem onClick={() => void act('spam')} disabled={!!unavailable('spam')}>+ Mark spam+ </MenuItem>+ <MenuItem onClick={() => void act('restore')} disabled={!!unavailable('restore')}>+ Restore to inbox+ </MenuItem>+ {view === 'trash' && (+ <MenuItem+ danger+ onClick={() => void act('destroy')}+ disabled={!!unavailable('destroy')}+ >+ Delete permanently+ </MenuItem>+ )}+ {[...new Set([unavailable('move'), view === 'trash' && unavailable('destroy')])]+ .filter(Boolean)+ .map((reason) => (+ <p className="menu-note" key={String(reason)}>+ {reason}+ </p>+ ))}+ </Dropdown>+ <span className="toolbar-divider" />+ <IconButton+ label="Clear selection"+ shortcut="Esc"+ disabled={busy}+ onClick={() => {+ setSelected(new Set())+ setAllMatching(false)+ listRef.current?.focus()+ }}+ >+ <X size={14} />+ </IconButton>+ </div>+ )}+ {view === 'drafts' && !!draftSelected.size && (+ <DraftSelectionBar+ count={draftSelected.size}+ total={draftItems.filter(deletable).length}+ onSelectAll={() =>+ setDraftSelected(new Set(draftItems.filter(deletable).map((item) => item.key)))+ }+ onDelete={() => discardDrafts(draftSelected)}+ onClear={() => setDraftSelected(new Set())}+ />+ )}+ {(mail.isError || mail.data?.pages.some((p) => p.failedAccounts.length)) && (+ <div className="connection-banner">+ <WifiOff size={13} />+ {mail.isError+ ? friendlyError(mail.error)+ : 'Some accounts are unavailable. Showing mail from connected accounts.'}+ <button onClick={() => void refresh()}>Retry</button>+ </div>+ )}+ {!!incomplete.length && view !== 'drafts' && (+ <div className="indexing-notice" role="status">+ <span>+ Still indexing {incomplete.map((a) => a.name).join(' and ')} — older mail may be+ missing+ </span>+ {incomplete.length === 1 && incomplete[0].indexing && (+ <IndexingMeter indexing={incomplete[0].indexing} label="Indexed" />+ )}+ </div>+ )}+ {view === 'drafts' ? (+ <div className="draft-list">+ <SubmissionList+ submissions={pendingSends.filter(+ (s) => !route.account || s.accountId === route.account,+ )}+ accounts={accounts}+ onOpenDraft={setComposer}+ notify={notify}+ />+ {!!pendingSends.length && !!draftItems.length && (+ <h2 className="draft-section-label">Drafts</h2>+ )}+ <DraftRows+ items={draftItems}+ accounts={accounts}+ selected={draftSelected}+ onOpen={(item) => void openDraft(item)}+ onSelect={toggleDraft}+ onDelete={discardDrafts}+ />+ {mail.hasNextPage && (+ <div className="load-more">+ <Button+ disabled={mail.isFetchingNextPage}+ onClick={() => void mail.fetchNextPage()}+ >+ {mail.isFetchingNextPage ? 'Loading…' : 'Load more server drafts'}+ </Button>+ </div>+ )}+ {!draftItems.length && !pendingSends.length && (+ <EmptyState+ icon={FileText}+ title="No drafts"+ description="Messages you start writing are saved here automatically."+ >+ <Button onClick={() => void compose()}>Write a message</Button>+ </EmptyState>+ )}+ </div>+ ) : !conversations.length && mail.isLoading ? (+ <div className="mail-list list-skeleton" aria-busy="true" aria-label="Loading mail">+ {Array.from({ length: 9 }, (_, i) => (+ <div className="mail-row skeleton-row" key={i}>+ <span className="row-selector" />+ <span className="skeleton-avatar" />+ <span className="skeleton-line" style={{ width: 120 + ((i * 37) % 50) }} />+ <span className="row-content">+ <span+ className="skeleton-line"+ style={{ width: 40 + ((i * 23) % 35) + '%' }}+ />+ <span+ className="skeleton-line faint"+ style={{ width: 55 + ((i * 17) % 30) + '%' }}+ />+ </span>+ <span className="skeleton-line" style={{ width: 44 }} />+ </div>+ ))}+ </div>+ ) : !conversations.length ? (+ mail.isLoading ? (+ <EmptyState icon={Mail} title="Loading mail">+ <Spinner />+ </EmptyState>+ ) : (+ <EmptyState+ {...emptyListState(view, {+ searching: !!route.q || hasSearchFilters,+ unreadOnly: !!filters.unread,+ })}+ >+ {hasSearchFilters && (+ <Button onClick={() => setFilters({})}>Clear filters</Button>+ )}+ {view === 'inbox' && !route.q && !hasFilters && (+ <span className="empty-hint">+ <kbd>C</kbd> Write a message+ </span>+ )}+ </EmptyState>+ )+ ) : (+ <ConversationList+ conversations={conversations}+ accounts={accounts}+ queryId={queryId}+ total={total}+ density={density}+ selected={selected}+ allMatching={allMatching}+ focused={focused}+ busy={busy}+ remoteImages={settings.remoteImages}+ view={view}+ hasNextPage={!!mail.hasNextPage}+ isFetchingNextPage={mail.isFetchingNextPage}+ listRef={listRef}+ handleRef={listHandle}+ offsets={offsets}+ onFetchNextPage={() => void mail.fetchNextPage()}+ onOpen={open}+ onFocus={setFocused}+ onSelect={toggle}+ onAction={(action, conversation) =>+ void act(action, [+ { accountId: conversation.accountId, threadId: conversation.id },+ ])+ }+ />+ )}+ <footer className="list-footer">+ <span role="status">+ {busy ? (+ <>+ <Spinner size={11} />+ {progress || 'Updating…'}+ </>+ ) : (+ <>+ <span+ className={+ 'connection-dot ' ++ (accounts.some((a) => a.status !== 'connected') ? 'connection-pending' : '')+ }+ />+ {accounts.every((a) => a.status === 'connected')+ ? 'All accounts connected'+ : accounts.filter((a) => a.status === 'connected').length ++ ' of ' ++ accounts.length ++ ' connected'}+ </>+ )}+ </span>+ <button+ className="footer-shortcuts"+ onClick={() => setHelp(true)}+ aria-label="Show keyboard shortcuts"+ >+ <kbd>J</kbd>+ <kbd>K</kbd>+ <span>Navigate</span>+ <kbd>↵</kbd>+ <span>Open</span>+ <kbd>?</kbd>+ <span>Shortcuts</span>+ </button>+ </footer>+ </>+ )}+ </main>+ {toast && (+ <div+ className={'toast' + (toast.tone === 'error' ? ' toast-error' : '')}+ role={toast.tone === 'error' ? 'alert' : 'status'}+ onMouseEnter={() => setToastHeld(true)}+ onMouseLeave={() => setToastHeld(false)}+ key={toast.id}+ >+ {toast.tone === 'error' ? (+ <AlertCircle size={15} />+ ) : toast.tone === 'info' ? (+ <Info size={15} />+ ) : (+ <Check size={15} />+ )}+ <span>{toast.text}</span>+ {canUndo && (+ <button className="toast-undo" onClick={() => void undo()}>+ Undo <kbd>Z</kbd>+ </button>+ )}+ <button+ className="toast-dismiss"+ aria-label="Dismiss notification"+ onClick={() => setToast(undefined)}+ >+ <X size={13} />+ </button>+ {!toastHeld && (+ <span+ className="toast-timer"+ style={{ animationDuration: toastDuration + 'ms' }}+ aria-hidden="true"+ />+ )}+ </div>+ )}+ <Suspense+ fallback={+ <div className="toast" role="status">+ <Spinner />+ Opening…+ </div>+ }+ >+ {composer && (+ <Composer+ key={composer.id}+ initial={composer}+ suggestions={suggestions}+ accounts={accounts}+ onClose={() => setComposer(undefined)}+ onOpenAccounts={() => openSettings('accounts')}+ notify={notify}+ onSaved={() => void queryClient.invalidateQueries({ queryKey: ['drafts'] })}+ />+ )}+ {settingsOpen && (+ <SettingsPanel+ open={settingsOpen}+ onClose={() => setSettingsOpen(false)}+ bootstrap={bootstrap}+ onChange={(settings) =>+ queryClient.setQueryData(['bootstrap'], { ...bootstrap, settings })+ }+ notify={notify}+ initialTab={settingsTab}+ />+ )}+ </Suspense>+ <CommandPalette+ open={paletteOpen}+ onClose={() => setPaletteOpen(false)}+ onSearch={(q) => {+ setSearchOpen(true)+ go({ q, view: 'all' })+ }}+ commands={commands}+ />+ <ShortcutDialog open={help} onClose={() => setHelp(false)} />+ <FilterDialog+ key={filterOpen ? 'filter-open' : 'filter-closed'}+ open={filterOpen}+ filters={filters}+ onClose={() => setFilterOpen(false)}+ onApply={(next) => {+ setFilters(next)+ setFilterOpen(false)+ }}+ />+ <FolderDialog+ key={+ folderDialog+ ? 'folder-' + folderDialog.operation + ':' + (folderDialog.folder?.id || '')+ : 'folder-closed'+ }+ dialog={folderDialog}+ onClose={() => setFolderDialog(undefined)}+ onSave={(name) => void changeFolder(name)}+ />+ <MoveDialog+ targets={moveTargets}+ accounts={accounts}+ onClose={() => setMoveTargets(undefined)}+ onMove={(id) => {+ void act('move', moveTargets, id)+ setMoveTargets(undefined)+ }}+ />+ <ConfirmActionDialog+ action={confirmAction}+ total={total}+ onClose={() => setConfirmAction(undefined)}+ onConfirm={(action) => {+ setConfirmAction(undefined)+ void act(action, undefined, undefined, true)+ }}+ />+ </div>+ )+}diff --git a/apps/desktop/src/renderer/src/AppDialogs.tsx b/apps/desktop/src/renderer/src/AppDialogs.tsxnew file mode 100644index 0000000..8055fc4--- /dev/null+++ b/apps/desktop/src/renderer/src/AppDialogs.tsx@@ -0,0 +1,308 @@+import { Fragment, useState } from 'react'+import { Button, DatePicker, Modal, Switch } from '@inlark/ui'+import type { MailAction, Mailbox, MailQuery } from '@inlark/core'++const shortcutSections: [string, [string, string][]][] = [+ [+ 'Navigate',+ [+ ['Next / previous conversation', 'J K'],+ ['Open conversation', 'Enter'],+ ['Back to list', 'Esc'],+ ['Search mail', '/'],+ ['Command menu', 'Ctrl K'],+ ['Toggle sidebar', '['],+ ],+ ],+ [+ 'Go to',+ [+ ['Inbox', 'G I'],+ ['Starred', 'G S'],+ ['Sent', 'G T'],+ ['Drafts', 'G D'],+ ['Archive', 'G A'],+ ],+ ],+ [+ 'Organize',+ [+ ['Archive', 'E'],+ ['Move to trash', '#'],+ ['Delete selected drafts', '#'],+ ['Mark as spam', '!'],+ ['Move to folder', 'V'],+ ['Star or unstar', 'S'],+ ['Mark unread / read', 'U ⇧I'],+ ['Undo last action', 'Z'],+ ],+ ],+ [+ 'Select',+ [+ ['Select conversation', 'X'],+ ['Select a range', '⇧X'],+ ['Select all loaded', 'Ctrl A'],+ ['Clear selection', 'Esc'],+ ],+ ],+ [+ 'Write',+ [+ ['Compose', 'C'],+ ['Reply', 'R'],+ ['Reply all', 'A'],+ ['Forward', 'F'],+ ['Send message', 'Ctrl ↵'],+ ],+ ],+]++export function ShortcutDialog({ open, onClose }: { open: boolean; onClose: () => void }) {+ return (+ <Modal+ open={open}+ onOpenChange={(value) => {+ if (!value) onClose()+ }}+ title="Keyboard shortcuts"+ description="Shortcuts are paused while you type in a field."+ className="shortcut-modal"+ >+ <div className="shortcut-sections">+ {shortcutSections.map(([section, items]) => (+ <section key={section}>+ <h3>{section}</h3>+ {items.map(([label, keys]) => (+ <div className="shortcut-row" key={label}>+ <span>{label}</span>+ <span className="shortcut-keys">+ {keys.split(' ').map((key) => (+ <kbd key={key}>{key}</kbd>+ ))}+ </span>+ </div>+ ))}+ </section>+ ))}+ </div>+ </Modal>+ )+}++const filterKeys = ['from', 'to', 'subject', 'after', 'before', 'hasAttachment'] as const++export function FilterDialog({+ open,+ filters,+ onClose,+ onApply,+}: {+ open: boolean+ filters: Partial<MailQuery>+ onClose: () => void+ onApply: (filters: Partial<MailQuery>) => void+}) {+ const [values, setValues] = useState<Partial<MailQuery>>(filters)+ return (+ <Modal+ open={open}+ onOpenChange={(value) => {+ if (!value) onClose()+ }}+ title="Filter conversations"+ description="Searches your whole mailbox on the server, not just what’s loaded."+ className="filter-modal"+ >+ <form+ onSubmit={(event) => {+ event.preventDefault()+ onApply(values)+ }}+ >+ <div className="filter-fields">+ {(['from', 'to'] as const).map((key) => (+ <label key={key}>+ {{ from: 'From', to: 'To' }[key]}+ <input+ value={values[key] || ''}+ placeholder="Name or address"+ onChange={(event) =>+ setValues((current) => ({ ...current, [key]: event.target.value || undefined }))+ }+ />+ </label>+ ))}+ <label className="filter-wide">+ Subject+ <input+ value={values.subject || ''}+ placeholder="Contains these words"+ onChange={(event) =>+ setValues((current) => ({ ...current, subject: event.target.value || undefined }))+ }+ />+ </label>+ <div className="filter-field filter-wide">+ <span>Date</span>+ <div className="filter-date-range">+ {(['after', 'before'] as const).map((key, index) => (+ <Fragment key={key}>+ {index > 0 && <span className="filter-date-separator">to</span>}+ <DatePicker+ aria-label={{ after: 'After', before: 'Before' }[key]}+ placeholder={{ after: 'Start date', before: 'End date' }[key]}+ value={values[key]?.slice(0, 10)}+ onValueChange={(day) =>+ setValues((current) => ({+ ...current,+ [key]: day ? new Date(day).toISOString() : undefined,+ }))+ }+ />+ </Fragment>+ ))}+ </div>+ </div>+ <div className="filter-switch filter-wide">+ <span>+ <strong>Has attachments</strong>+ <small>Only show conversations with files attached.</small>+ </span>+ <Switch+ aria-label="Has attachments"+ checked={!!values.hasAttachment}+ onCheckedChange={(checked) =>+ setValues((current) => ({ ...current, hasAttachment: checked || undefined }))+ }+ />+ </div>+ </div>+ <div className="modal-actions filter-actions">+ <Button+ variant="ghost"+ disabled={!filterKeys.some((key) => values[key])}+ onClick={() =>+ setValues((current) => ({+ ...current,+ ...Object.fromEntries(filterKeys.map((key) => [key, undefined])),+ }))+ }+ >+ Clear all+ </Button>+ <Button variant="primary" type="submit">+ Show results+ </Button>+ </div>+ </form>+ </Modal>+ )+}++export type FolderDialogState = {+ operation: 'create' | 'rename' | 'delete'+ accountId?: string+ folder?: Mailbox+}++export function FolderDialog({+ dialog,+ onClose,+ onSave,+}: {+ dialog?: FolderDialogState+ onClose: () => void+ onSave: (name: string) => void+}) {+ const [name, setName] = useState(dialog?.folder?.name || '')+ return (+ <Modal+ open={!!dialog}+ onOpenChange={(open) => {+ if (!open) onClose()+ }}+ title={+ dialog?.operation === 'delete'+ ? 'Delete “' + name + '”?'+ : dialog?.operation === 'rename'+ ? 'Rename folder'+ : 'Create a folder'+ }+ description={+ dialog?.operation === 'delete'+ ? 'The folder is deleted on the server. Messages that are also in other folders stay there.'+ : undefined+ }+ >+ {dialog?.operation !== 'delete' && (+ <label>+ Folder name+ <input+ autoFocus+ value={name}+ onChange={(event) => setName(event.target.value)}+ onKeyDown={(event) => {+ if (event.key === 'Enter' && name.trim()) onSave(name)+ }}+ />+ </label>+ )}+ <div className="modal-actions">+ <Button onClick={onClose}>Cancel</Button>+ <Button+ variant={dialog?.operation === 'delete' ? 'danger' : 'primary'}+ disabled={!name.trim()}+ onClick={() => onSave(name)}+ >+ {dialog?.operation === 'delete' ? 'Delete folder' : 'Save folder'}+ </Button>+ </div>+ </Modal>+ )+}++export function ConfirmActionDialog({+ action,+ total,+ onClose,+ onConfirm,+}: {+ action?: MailAction+ total: number+ onClose: () => void+ onConfirm: (action: MailAction) => void+}) {+ return (+ <Modal+ open={!!action}+ onOpenChange={(open) => {+ if (!open) onClose()+ }}+ title={+ action === 'destroy'+ ? 'Permanently delete these conversations?'+ : 'Update all matching conversations?'+ }+ description={+ action === 'destroy'+ ? 'This removes messages from the server permanently and cannot be undone.'+ : 'This applies to all ' ++ total.toLocaleString() ++ ' matching conversations, including those beyond the loaded page. Partial failures will be reported.'+ }+ >+ <div className="modal-actions">+ <Button onClick={onClose}>Cancel</Button>+ <Button+ variant={action === 'destroy' ? 'danger' : 'primary'}+ onClick={() => {+ if (action) onConfirm(action)+ }}+ >+ Confirm+ </Button>+ </div>+ </Modal>+ )+}diff --git a/apps/desktop/src/renderer/src/CommandPalette.tsx b/apps/desktop/src/renderer/src/CommandPalette.tsxnew file mode 100644index 0000000..42cf1c7--- /dev/null+++ b/apps/desktop/src/renderer/src/CommandPalette.tsx@@ -0,0 +1,222 @@+import { Fragment, useEffect, useId, useRef, useState } from 'react'+import { ArrowDown, ArrowUp, Check, CornerDownLeft, Inbox, Search } from '@inlark/ui/icons'+import { Modal } from '@inlark/ui'+import type { Account } from '@inlark/core'+import { AccountMark } from './AccountMark'++export interface Command {+ id: string+ label: string+ group: string+ icon: typeof Inbox+ key?: string+ /** Extra words that should find this command, e.g. “dark” for the theme. */+ keywords?: string+ /** Marks the current choice among alternatives such as themes. */+ checked?: boolean+ /** Shown in place of the icon for account commands. */+ account?: Account+ /** A short explanation below the label, e.g. why the command is unavailable. */+ description?: string+ /** Shown dimmed; running it should explain why rather than act. */+ disabled?: boolean+ run: () => void+}++/**+ * Every typed word must start a word in the label or keywords (or appear inside one, for+ * longer words). Label matches outrank keyword matches, and earlier matches rank higher.+ */+export function rank(command: Pick<Command, 'label' | 'keywords'>, query: string): number {+ const words = query.toLowerCase().split(/\s+/).filter(Boolean)+ if (!words.length) return 1+ const label = command.label.toLowerCase()+ const extra = (command.keywords || '').toLowerCase()+ let score = 0+ for (const word of words) {+ const starts = (text: string) => {+ const at = text.search(+ new RegExp('(^|[\\s/·“-])' + word.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')),+ )+ return at < 0 ? -1 : at+ }+ const inLabel = starts(label)+ if (inLabel >= 0) score += 100 - Math.min(inLabel, 60)+ else if (starts(extra) >= 0) score += 30+ else if (word.length >= 3 && (label.includes(word) || extra.includes(word))) score += 10+ else return 0+ }+ return score + (label.startsWith(words[0]) ? 50 : 0)+}++export function CommandPalette({+ open,+ onClose,+ onSearch,+ commands,+}: {+ open: boolean+ onClose: () => void+ onSearch: (text: string) => void+ commands: Command[]+}) {+ const [value, setValue] = useState(''),+ [index, setIndex] = useState(0)+ const listId = useId()+ const results = useRef<HTMLDivElement>(null)+ useEffect(() => {+ if (open) {+ setValue('')+ setIndex(0)+ }+ }, [open])+ const query = value.trim()+ const matched = query+ ? commands+ .map((command, order) => ({ command, order, score: rank(command, query) }))+ .filter((entry) => entry.score > 0)+ .sort((a, b) => b.score - a.score || a.order - b.order)+ .map((entry) => entry.command)+ : commands+ const options: Command[] = [+ ...matched,+ ...(query+ ? [+ {+ id: 'search',+ group: 'Mail',+ label: 'Search all mail for “' + query + '”',+ icon: Search,+ key: '↵',+ run: () => onSearch(query),+ },+ ]+ : []),+ ]+ const activeIndex = Math.max(0, Math.min(index, options.length - 1))+ useEffect(() => {+ results.current?.querySelector('[aria-selected="true"]')?.scrollIntoView({ block: 'nearest' })+ }, [activeIndex, query])+ const run = (i: number) => {+ if (!options[i]) return+ onClose()+ options[i].run()+ }+ return (+ <Modal+ open={open}+ onOpenChange={(open) => {+ if (!open) onClose()+ }}+ title="Search & commands"+ className="command-modal"+ >+ <div className="command-input">+ <Search size={18} />+ <input+ autoFocus+ placeholder="Type a command or search your mail…"+ value={value}+ aria-label="Search commands or mail"+ role="combobox"+ aria-autocomplete="list"+ aria-expanded={open}+ aria-controls={listId}+ aria-activedescendant={options.length ? listId + '-' + activeIndex : undefined}+ onChange={(e) => {+ setValue(e.target.value)+ setIndex(0)+ }}+ onKeyDown={(e) => {+ const step =+ e.key === 'ArrowDown' || (e.ctrlKey && e.key === 'n')+ ? 1+ : e.key === 'ArrowUp' || (e.ctrlKey && e.key === 'p')+ ? -1+ : 0+ if (step) {+ e.preventDefault()+ setIndex(options.length ? (activeIndex + step + options.length) % options.length : 0)+ }+ if (e.key === 'Home' && !value) setIndex(0)+ if (e.key === 'End' && !value) setIndex(options.length - 1)+ if (e.key === 'Enter') {+ e.preventDefault()+ run(activeIndex)+ }+ }}+ />+ <button className="command-dismiss" onClick={onClose} aria-label="Close search">+ <kbd>Esc</kbd>+ </button>+ </div>+ <div+ className="command-results"+ id={listId}+ role="listbox"+ aria-label="Commands and mail search"+ ref={results}+ >+ {options.map((c, i) => (+ <Fragment key={c.id}>+ {(query ? i === 0 && c.id !== 'search' : options[i - 1]?.group !== c.group) && (+ <div className="command-label" role="presentation">+ {query ? 'Best matches' : c.group}+ </div>+ )}+ {query && c.id === 'search' && i > 0 && (+ <div className="command-label" role="presentation">+ </div>+ )}+ <button+ id={listId + '-' + i}+ role="option"+ aria-selected={activeIndex === i}+ aria-disabled={c.disabled || undefined}+ tabIndex={-1}+ className={(activeIndex === i ? 'active' : '') + (c.disabled ? ' unavailable' : '')}+ onMouseMove={() => activeIndex !== i && setIndex(i)}+ onMouseDown={(event) => event.preventDefault()}+ onClick={() => run(i)}+ >+ <span className="command-icon">+ {c.account ? <AccountMark account={c.account} size={26} /> : <c.icon size={15} />}+ </span>+ <span className="command-text">+ {c.label}+ {c.description && <small className="command-description">{c.description}</small>}+ </span>+ {query && c.id !== 'search' && <span className="command-group">{c.group}</span>}+ {c.checked && <Check size={14} className="command-check" />}+ {c.key && (+ <span className="command-keys">+ {c.key.split(' ').map((k) => (+ <kbd key={k}>{k}</kbd>+ ))}+ </span>+ )}+ </button>+ </Fragment>+ ))}+ {!options.length && <div className="command-empty">No commands</div>}+ </div>+ <div className="command-footer">+ <kbd>+ <ArrowUp size={11} />+ </kbd>+ <kbd>+ <ArrowDown size={11} />+ </kbd>{' '}+ Navigate+ <span className="command-enter">+ <kbd>+ <CornerDownLeft size={11} />+ </kbd>{' '}+ Run+ </span>+ <span className="command-footer-brand">Inlark</span>+ </div>+ </Modal>+ )+}diff --git a/apps/desktop/src/renderer/src/Composer.tsx b/apps/desktop/src/renderer/src/Composer.tsxnew file mode 100644index 0000000..ec4cc95--- /dev/null+++ b/apps/desktop/src/renderer/src/Composer.tsx@@ -0,0 +1,675 @@+import { useEffect, useRef, useState } from 'react'+import { useQuery } from '@tanstack/react-query'+import { useForm } from '@tanstack/react-form'+import { Dialog } from '@base-ui/react/dialog'+import { useHotkey } from '@tanstack/react-hotkeys'+import { useEditor, useEditorState, EditorContent } from '@tiptap/react'+import StarterKit from '@tiptap/starter-kit'+import Placeholder from '@tiptap/extension-placeholder'+import {+ X,+ Send,+ Paperclip,+ Bold,+ Italic,+ BulletList,+ Link2,+ Trash2,+ Check,+ AlertCircle,+ ArrowUpRight,+ FileText,+} from '@inlark/ui/icons'+import { Modal, Button, IconButton, Select, Spinner } from '@inlark/ui'+import {+ friendlyError,+ type Address,+ type Account,+ type Draft,+ type SendResult,+} from '@inlark/core'+import { api, isDemo } from './api'+import { localSaveDraft, localDeleteDraft } from './cache'+import { RecipientField } from './RecipientField'+import { formatBytes } from './mail-date'++/** Plain wording for a finished send; the Drafts view offers recovery for anything left over. */+function sentMessage(result: SendResult): string {+ const copy = result.sentCopy === 'pending' ? ' Its copy in Sent isn’t saved yet.' : ''+ if (result.status === 'partial') {+ const refused = result.rejected || []+ return (+ (refused.length+ ? 'Sent, but refused by ' ++ (refused.length === 1 ? refused[0].email : refused.length + ' recipients') ++ '.'+ : 'Sent, but some recipients refused it.') ++ copy ++ ' Drafts has the details.'+ )+ }+ return copy ? 'Message sent.' + copy + ' Drafts shows its status.' : result.message+}++/** What went wrong with a draft, in terms of what the user can do next. */+function draftProblem(draft: Draft): { text: string; detail?: string } | undefined {+ if (!draft.error) return undefined+ const detail = draft.error+ switch (draft.errorKind) {+ case 'conflict':+ return {+ text: 'This draft was changed in another app. Keep both to save your version as a separate draft.',+ }+ case 'outgoingAuthentication':+ return { text: 'The outgoing server rejected your login. Nothing was sent.', detail }+ case 'connection':+ return {+ text: 'The server couldn’t be reached. Nothing was sent; your draft is saved.',+ detail,+ }+ case 'rejected':+ return {+ text: 'The server refused this message. Nothing was sent. Check the recipients and attachments, then try again.',+ detail,+ }+ default:+ return { text: detail }+ }+}++export function Composer({+ initial,+ accounts,+ suggestions,+ onClose,+ onOpenAccounts,+ notify,+ onSaved,+}: {+ initial: Draft+ suggestions: Address[]+ accounts: Account[]+ onClose: () => void+ /** Opens Settings → Accounts, e.g. to sign in to the outgoing server again. */+ onOpenAccounts: () => void+ notify: (message: string, tone?: 'error' | 'info') => void+ onSaved: () => void+}) {+ const [draft, setDraft] = useState(initial),+ [state, setState] = useState(+ initial.status === 'uncertain'+ ? 'Delivery unconfirmed'+ : initial.status === 'error'+ ? 'Saved locally · sync failed'+ : 'Saved on this device',+ ),+ [sending, setSending] = useState(false),+ [showCc, setShowCc] = useState(initial.cc.length > 0 || initial.bcc.length > 0),+ [expanded, setExpanded] = useState(false),+ [linkOpen, setLinkOpen] = useState(false),+ [linkValue, setLinkValue] = useState(''),+ [discardOpen, setDiscardOpen] = useState(false)+ const latest = useRef(draft),+ sync = useRef<Promise<unknown>>(Promise.resolve()),+ alive = useRef(true)+ const account = accounts.find((a) => a.id === draft.accountId)!+ const identities = useQuery({+ queryKey: ['identities', draft.accountId],+ queryFn: () => api.identities(draft.accountId),+ })+ const locked = sending || draft.status === 'uncertain' || draft.status === 'sent'+ // A failed send is kept apart from the draft, so a later autosave can't clear the explanation.+ const [sendError, setSendError] = useState<Pick<Draft, 'error' | 'errorKind'>>()+ const shown = sendError ? { ...draft, ...sendError } : draft+ const problem = draftProblem(shown)+ const update = (patch: Partial<Draft>) => {+ setSendError(undefined)+ change(patch)+ }+ const change = (patch: Partial<Draft>) =>+ setDraft((current) => {+ if (['uncertain', 'sent'].includes(current.status)) return current+ const next = {+ ...current,+ ...patch,+ updatedAt: new Date().toISOString(),+ status: 'local' as const,+ error: undefined,+ errorKind: undefined,+ }+ latest.current = next+ return next+ })+ const form = useForm({ defaultValues: { subject: initial.subject } })+ const editor = useEditor({+ extensions: [+ StarterKit.configure({+ heading: false,+ codeBlock: false,+ horizontalRule: false,+ link: { openOnClick: false },+ }),+ Placeholder.configure({ placeholder: 'Write your message…' }),+ ],+ content:+ initial.html ||+ '<p>' ++ initial.text+ .replace(/&/g, '&')+ .replace(/</g, '<')+ .replace(/>/g, '>')+ .replace(/\n/g, '<br/>') ++ '</p>',+ editorProps: {+ attributes: { class: 'compose-editor', 'aria-label': 'Message body', spellcheck: 'true' },+ },+ onUpdate: ({ editor }) => update({ html: editor.getHTML(), text: editor.getText() }),+ })+ const formatting = useEditorState({+ editor,+ selector: ({ editor }) => ({+ bold: editor?.isActive('bold') || false,+ italic: editor?.isActive('italic') || false,+ bulletList: editor?.isActive('bulletList') || false,+ link: editor?.isActive('link') || false,+ }),+ })+ useEffect(() => {+ // Locking for a send is not an edit, so it must not reset the draft or its error.+ editor?.setEditable(!locked, false)+ }, [editor, locked])+ useEffect(() => {+ alive.current = true+ return () => {+ alive.current = false+ }+ }, [])+ useEffect(() => {+ latest.current = draft+ if (['uncertain', 'sent', 'sending'].includes(draft.status)) return+ setState('Saving…')+ const localTimer = setTimeout(() => {+ void localSaveDraft(latest.current)+ .then(() => api.saveDraft(latest.current))+ .then(() => {+ if (alive.current)+ setState((current) =>+ current === 'All changes saved' ? current : 'Saved on this device',+ )+ onSaved()+ })+ .catch((e) => {+ if (alive.current) setState('Could not save: ' + friendlyError(e))+ })+ }, 350)+ const serverTimer = setTimeout(() => {+ const captured = latest.current+ if (!captured.identityId || account.status !== 'connected') return+ sync.current = sync.current+ .then(() =>+ api.syncDraft({+ ...captured,+ serverId: latest.current.serverId,+ serverFingerprint: latest.current.serverFingerprint,+ }),+ )+ .then((saved) => {+ const result = saved as Draft+ if (!alive.current) return+ const current = latest.current+ const merged = {+ ...current,+ serverId: result.serverId || current.serverId,+ serverFingerprint: result.serverFingerprint || current.serverFingerprint,+ ...(current.updatedAt === captured.updatedAt+ ? { status: result.status, error: result.error }+ : {}),+ }+ latest.current = merged+ setDraft(merged)+ if (current.updatedAt === captured.updatedAt)+ setState(+ result.status === 'synced'+ ? 'All changes saved'+ : 'Saved locally · server sync failed',+ )+ void localSaveDraft(merged)+ })+ .catch(() => {+ if (alive.current) setState('Saved locally · waiting for connection')+ })+ }, 2200)+ return () => {+ clearTimeout(localTimer)+ clearTimeout(serverTimer)+ }+ }, [draft.updatedAt])+ const close = async () => {+ try {+ await sync.current+ await localSaveDraft(latest.current)+ await api.saveDraft(latest.current)+ onSaved()+ onClose()+ } catch (e) {+ notify('Your draft could not be saved. ' + friendlyError(e))+ }+ }+ const send = async () => {+ if (sending || account.status !== 'connected') return+ const recipients = [...latest.current.to, ...latest.current.cc, ...latest.current.bcc]+ if (!recipients.length || recipients.some((a) => !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(a.email))) {+ notify('Add valid email addresses before sending.')+ return+ }+ if (!latest.current.identityId) {+ notify('Select a sending identity.')+ return+ }+ setSending(true)+ setSendError(undefined)+ try {+ await sync.current+ await localSaveDraft(latest.current)+ const result =+ latest.current.status === 'uncertain'+ ? await api.reconcile(latest.current.id)+ : await api.send(latest.current)+ if (result.status === 'sent' || result.status === 'partial') {+ notify(sentMessage(result))+ await localDeleteDraft(latest.current.id).catch(() =>+ notify('Message sent. The local draft cache could not be cleaned up.'),+ )+ onSaved()+ onClose()+ } else {+ notify(result.message)+ const uncertain = { ...latest.current, status: 'uncertain' as const }+ latest.current = uncertain+ setDraft(uncertain)+ await localSaveDraft(uncertain)+ setState('Delivery unconfirmed')+ }+ } catch (error) {+ notify(friendlyError(error), 'error')+ setState('Not sent · draft preserved')+ const saved = await api+ .drafts()+ .then((values) => values.find((d) => d.id === latest.current.id))+ .catch(() => undefined)+ if (saved?.status === 'sent') {+ notify('Delivery confirmed.')+ onSaved()+ onClose()+ return+ }+ if (saved?.status === 'uncertain') setState('Delivery unconfirmed')+ if (saved?.status !== 'uncertain')+ setSendError({+ error: saved?.error || friendlyError(error),+ errorKind: saved?.errorKind,+ })+ if (saved) {+ latest.current = saved+ setDraft(saved)+ await localSaveDraft(saved).catch(() => {})+ }+ } finally {+ setSending(false)+ }+ }+ useHotkey('Mod+Enter', () => void send(), {+ conflictBehavior: 'replace',+ ignoreInputs: false,+ enabled: !linkOpen && !discardOpen,+ })+ const addressField = (name: 'to' | 'cc' | 'bcc', label: string) => (+ <RecipientField+ id={'compose-' + name}+ label={label}+ defaultValue={initial[name]}+ suggestions={suggestions}+ disabled={locked}+ autoFocus={name === 'to' && !initial.to.length}+ placeholder={name === 'to' ? 'Name or email address' : ''}+ onChange={(addresses) => update({ [name]: addresses })}+ >+ {name === 'to' && !showCc && (+ <button+ type="button"+ className="compose-cc-toggle"+ onClick={(event) => {+ event.stopPropagation()+ setShowCc(true)+ requestAnimationFrame(() => document.getElementById('compose-cc')?.focus())+ }}+ >+ Cc / Bcc+ </button>+ )}+ </RecipientField>+ )+ return (+ <Dialog.Root+ open+ disablePointerDismissal+ onOpenChange={(open) => {+ if (!open && !sending) void close()+ }}+ >+ <Dialog.Portal>+ <Dialog.Backdrop className="compose-backdrop" />+ <Dialog.Popup+ className={'composer ' + (expanded ? 'composer-expanded' : '')}+ initialFocus={() =>+ initial.to.length && initial.subject && !locked+ ? document.querySelector<HTMLElement>('.compose-editor')+ : document.getElementById(initial.to.length ? 'compose-subject' : 'compose-to')+ }+ >+ <Dialog.Title className="sr-only">Compose email</Dialog.Title>+ <div className="compose-heading">+ <span>+ <span className="compose-dot" />{' '}+ {initial.replyThreadId+ ? 'Reply'+ : /^fwd:/i.test(initial.subject)+ ? 'Forward'+ : 'New message'}+ </span>+ <div>+ <span className="draft-state" role="status">+ {sending || state === 'Saving…' ? (+ <Spinner size={11} />+ ) : state.startsWith('Sav') || state === 'All changes saved' ? (+ <Check size={11} />+ ) : (+ <AlertCircle size={11} />+ )}{' '}+ {sending+ ? draft.status === 'uncertain'+ ? 'Checking delivery…'+ : 'Sending…'+ : state}+ </span>+ <IconButton+ label={expanded ? 'Restore composer size' : 'Expand composer'}+ onClick={() => setExpanded(!expanded)}+ >+ <ArrowUpRight size={14} />+ </IconButton>+ <Dialog.Close+ render={+ <Button+ variant="ghost"+ size="icon"+ aria-label="Save and close"+ disabled={sending}+ />+ }+ >+ <X size={15} />+ </Dialog.Close>+ </div>+ </div>+ <div className="compose-addresses">+ <div className="compose-field">+ <label htmlFor="compose-from">From</label>+ <Select+ id="compose-from"+ value={draft.accountId}+ disabled={locked || !!draft.serverId}+ options={accounts.map((a) => ({ value: a.id, label: a.name + ' · ' + a.email }))}+ onValueChange={async (accountId) => {+ try {+ const identities = await api.identities(accountId)+ update({+ accountId,+ identityId: identities[0]?.id || '',+ serverId: undefined,+ serverFingerprint: undefined,+ })+ } catch (error) {+ notify(friendlyError(error))+ }+ }}+ />+ </div>+ {(identities.data?.length || 0) > 1 && (+ <div className="compose-field">+ <label htmlFor="compose-identity">Identity</label>+ <Select+ disabled={locked}+ id="compose-identity"+ value={draft.identityId}+ options={(identities.data || []).map((i) => ({+ value: i.id,+ label: i.name + ' <' + i.email + '>',+ }))}+ onValueChange={(identityId) => update({ identityId })}+ />+ </div>+ )}+ {addressField('to', 'To')}+ {showCc && (+ <>+ {addressField('cc', 'Cc')}+ {addressField('bcc', 'Bcc')}+ </>+ )}+ <form.Field name="subject">+ {(field) => (+ <div className="compose-field compose-subject">+ <label htmlFor="compose-subject">Subject</label>+ <input+ disabled={locked}+ id="compose-subject"+ value={field.state.value}+ placeholder="Subject"+ onChange={(e) => {+ field.handleChange(e.target.value)+ update({ subject: e.target.value })+ }}+ />+ </div>+ )}+ </form.Field>+ </div>+ <div className="compose-body">+ <EditorContent editor={editor} />+ {draft.attachments.length > 0 && (+ <div className="compose-attachments">+ {draft.attachments.map((a) => (+ <div className="compose-attachment" key={a.id}>+ <FileText size={14} />+ <span>{a.name}</span>+ <small>{formatBytes(a.size)}</small>+ <button+ disabled={locked}+ aria-label={'Remove ' + a.name}+ onClick={() =>+ update({+ attachments: latest.current.attachments.filter(+ (item) => item.id !== a.id,+ ),+ })+ }+ >+ <X size={12} />+ </button>+ </div>+ ))}+ </div>+ )}+ </div>+ {problem && draft.status !== 'uncertain' && (+ <div className="compose-warning" role="status">+ <AlertCircle size={15} />+ <span>+ {problem.text}+ {problem.detail && problem.detail !== problem.text && (+ <small className="compose-warning-detail">{problem.detail}</small>+ )}+ </span>+ {(shown.errorKind === 'conflict' || shown.error?.includes('another client')) && (+ <Button+ size="small"+ onClick={() => update({ serverId: undefined, serverFingerprint: undefined })}+ >+ Keep both versions+ </Button>+ )}+ {shown.errorKind === 'outgoingAuthentication' && (+ <Button+ size="small"+ onClick={async () => {+ await close()+ onOpenAccounts()+ }}+ >+ Account settings+ </Button>+ )}+ </div>+ )}+ {draft.status === 'uncertain' && (+ <div className="compose-warning">+ <AlertCircle size={15} />+ The server may have accepted this message. Check delivery to avoid sending it twice.+ </div>+ )}+ <fieldset className="compose-format" disabled={locked}>+ <IconButton+ label="Bold"+ shortcut="Ctrl B"+ onClick={() => editor?.chain().focus().toggleBold().run()}+ className={formatting?.bold ? 'active-format' : ''}+ aria-pressed={formatting?.bold || false}+ >+ <Bold size={14} />+ </IconButton>+ <IconButton+ label="Italic"+ className={formatting?.italic ? 'active-format' : ''}+ aria-pressed={formatting?.italic || false}+ shortcut="Ctrl I"+ onClick={() => editor?.chain().focus().toggleItalic().run()}+ >+ <Italic size={14} />+ </IconButton>+ <IconButton+ label="Bulleted list"+ className={formatting?.bulletList ? 'active-format' : ''}+ aria-pressed={formatting?.bulletList || false}+ onClick={() => editor?.chain().focus().toggleBulletList().run()}+ >+ <BulletList size={15} />+ </IconButton>+ <IconButton+ label="Add link"+ className={formatting?.link ? 'active-format' : ''}+ aria-pressed={formatting?.link || false}+ onClick={() => {+ setLinkValue(editor?.getAttributes('link').href || '')+ setLinkOpen(true)+ }}+ >+ <Link2 size={15} />+ </IconButton>+ <span className="toolbar-divider" />+ <IconButton+ label="Attach files"+ onClick={async () => {+ try {+ const attachments = await api.stageAttachments()+ update({ attachments: [...latest.current.attachments, ...attachments] })+ } catch (error) {+ notify(friendlyError(error))+ }+ }}+ >+ <Paperclip size={15} />+ </IconButton>+ </fieldset>+ <div className="compose-footer">+ <Button+ variant="primary"+ onClick={() => void send()}+ disabled={sending || account.status !== 'connected'}+ >+ {sending ? <Spinner size={14} /> : <Send size={13} />}{' '}+ {sending+ ? draft.status === 'uncertain'+ ? 'Checking delivery…'+ : 'Sending…'+ : draft.status === 'uncertain'+ ? 'Check delivery'+ : isDemo+ ? 'Simulate send'+ : 'Send message'}+ <span className="send-shortcut">Ctrl ↵</span>+ </Button>+ <span className="compose-account">{account.email}</span>+ <IconButton+ label="Discard draft"+ onClick={() => setDiscardOpen(true)}+ disabled={locked}+ >+ <Trash2 size={15} />+ </IconButton>+ </div>+ </Dialog.Popup>+ </Dialog.Portal>+ <Modal+ open={discardOpen}+ onOpenChange={setDiscardOpen}+ title="Discard this draft?"+ description="This deletes the saved draft and its attachments."+ >+ <div className="modal-actions">+ <Button onClick={() => setDiscardOpen(false)}>Keep writing</Button>+ <Button+ variant="danger"+ onClick={async () => {+ try {+ await sync.current+ await api.deleteDraft(draft.id)+ await localDeleteDraft(draft.id)+ onSaved()+ onClose()+ } catch (e) {+ notify(friendlyError(e))+ }+ }}+ >+ Discard draft+ </Button>+ </div>+ </Modal>+ <Modal open={linkOpen} onOpenChange={setLinkOpen} title="Add a link">+ <label>+ URL+ <input+ value={linkValue}+ placeholder="https://…"+ onChange={(e) => setLinkValue(e.target.value)}+ />+ </label>+ <div className="modal-actions">+ <Button onClick={() => setLinkOpen(false)}>Cancel</Button>+ <Button+ variant="primary"+ onClick={() => {+ if (/^https?:\/\//.test(linkValue)) {+ editor?.chain().focus().extendMarkRange('link').setLink({ href: linkValue }).run()+ setLinkOpen(false)+ }+ }}+ >+ Insert link+ </Button>+ </div>+ </Modal>+ </Dialog.Root>+ )+}diff --git a/apps/desktop/src/renderer/src/ConversationList.tsx b/apps/desktop/src/renderer/src/ConversationList.tsxnew file mode 100644index 0000000..e379888--- /dev/null+++ b/apps/desktop/src/renderer/src/ConversationList.tsx@@ -0,0 +1,309 @@+import {+ useCallback,+ useEffect,+ useImperativeHandle,+ useLayoutEffect,+ useMemo,+ useRef,+ memo,+} from 'react'+import type { Ref, RefObject } from 'react'+import { useVirtualizer } from '@tanstack/react-virtual'+import type { Account, Conversation, MailAction } from '@inlark/core'+import { Spinner } from '@inlark/ui'+import { ConversationRow, senderLabel } from './ConversationRow'+import { day } from './mail-date'++export type ConversationListHandle = {+ scrollToConversation: (key: string) => void+}++type Row = { group: string } | { conversation: Conversation }++const ListConversationRow = memo(function ListConversationRow({+ conversation,+ account,+ selected,+ focused,+ busy,+ remoteImages,+ view,+ onOpen,+ onFocus,+ onSelect,+ onAction,+}: {+ conversation: Conversation+ account?: Account+ selected: boolean+ focused: boolean+ busy: boolean+ remoteImages: boolean+ view: string+ onOpen: (conversation: Conversation) => void+ onFocus: (key: string) => void+ onSelect: (key: string, range: boolean) => void+ onAction: (action: MailAction, conversation: Conversation) => void+}) {+ return (+ <ConversationRow+ conversation={conversation}+ account={account}+ selected={selected}+ focused={focused}+ onOpen={() => onOpen(conversation)}+ onFocus={() => onFocus(conversation.key)}+ onSelect={(range) => onSelect(conversation.key, range)}+ busy={busy}+ remoteImages={remoteImages}+ onArchive={view === 'archive' ? undefined : () => onAction('archive', conversation)}+ onTrash={view === 'trash' ? undefined : () => onAction('trash', conversation)}+ onToggleRead={() => onAction(conversation.unread ? 'read' : 'unread', conversation)}+ onStar={() => onAction(conversation.starred ? 'unstar' : 'star', conversation)}+ />+ )+})++export function ConversationList({+ conversations,+ accounts,+ queryId,+ total,+ density,+ selected,+ allMatching,+ focused,+ busy,+ remoteImages,+ view,+ hasNextPage,+ isFetchingNextPage,+ listRef,+ handleRef,+ offsets,+ onFetchNextPage,+ onOpen,+ onFocus,+ onSelect,+ onAction,+}: {+ conversations: Conversation[]+ accounts: Account[]+ queryId: string+ total: number+ density: 'compact' | 'comfortable'+ selected: Set<string>+ allMatching: boolean+ focused: string+ busy: boolean+ remoteImages: boolean+ view: string+ hasNextPage: boolean+ isFetchingNextPage: boolean+ listRef: RefObject<HTMLDivElement | null>+ handleRef: Ref<ConversationListHandle>+ offsets: RefObject<Map<string, number>>+ onFetchNextPage: () => void+ onOpen: (conversation: Conversation) => void+ onFocus: (key: string) => void+ onSelect: (key: string, range: boolean) => void+ onAction: (action: MailAction, conversation: Conversation) => void+}) {+ const rowHeight = density === 'compact' ? 44 : 64+ const groupHeight = 36+ const scrollAnchor = useRef<{ query: string; key: string; delta: number } | undefined>(undefined)+ const accountById = useMemo(+ () => new Map(accounts.map((account) => [account.id, account])),+ [accounts],+ )+ const rows = useMemo(() => {+ const result: Row[] = []+ let previous = ''+ for (const conversation of conversations) {+ const group = day(conversation.receivedAt)+ if (group !== previous) {+ result.push({ group })+ previous = group+ }+ result.push({ conversation })+ }+ return result+ }, [conversations])+ const senderCounts = useMemo(() => {+ const counts = new Map<string, number>()+ for (const conversation of conversations) {+ const label = senderLabel(conversation)+ counts.set(label, Math.max(counts.get(label) || 0, conversation.count))+ }+ return counts+ }, [conversations])+ const estimateSize = useCallback(+ (index: number) => ('group' in rows[index] ? groupHeight : rowHeight),+ [rows, rowHeight],+ )+ const getItemKey = useCallback(+ (index: number) =>+ 'group' in rows[index] ? 'group-' + rows[index].group : rows[index].conversation.key,+ [rows],+ )+ const virtual = useVirtualizer({+ initialOffset: () => offsets.current.get(queryId) || 0,+ count: rows.length,+ getScrollElement: () => listRef.current,+ estimateSize,+ getItemKey,+ overscan: 6,+ })+ const items = virtual.getVirtualItems()+ useLayoutEffect(() => {+ const list = listRef.current+ if (!list || !conversations.length || !items.length) return++ const canvas = document.createElement('canvas')+ const context = canvas.getContext('2d')+ if (!context) return+ const measure = () => {+ const sender = list.querySelector<HTMLElement>('.row-sender')+ if (!sender) return+ const style = getComputedStyle(sender)+ context.font = `550 ${style.fontSize} ${style.fontFamily}`+ const gap = parseFloat(style.columnGap) || 0+ const avatar = sender.querySelector<HTMLElement>('.avatar')+ const avatarWidth =+ avatar && getComputedStyle(avatar).display !== 'none' ? avatar.offsetWidth : 0+ let widest = 0+ for (const [label, count] of senderCounts) {+ const nameWidth = context.measureText(label).width+ const countWidth = count > 1 ? gap + 8 + String(count).length * 6 : 0+ widest = Math.max(widest, avatarWidth + (avatarWidth ? gap : 0) + nameWidth + countWidth)+ if (widest >= 224) break+ }+ list.style.setProperty('--sender-width', `${Math.min(224, Math.ceil(widest + 2))}px`)+ }++ measure()+ const observer = new ResizeObserver(measure)+ observer.observe(list)+ let active = true+ void document.fonts.ready.then(() => {+ if (active) measure()+ })+ return () => {+ active = false+ observer.disconnect()+ }+ }, [senderCounts, density, items.length, listRef])+ useImperativeHandle(handleRef, () => ({+ scrollToConversation: (key) => {+ const index = rows.findIndex((row) => 'conversation' in row && row.conversation.key === key)+ if (index >= 0) virtual.scrollToIndex(index, { align: 'auto' })+ },+ }))+ useLayoutEffect(() => {+ virtual.measure()+ }, [density])+ useLayoutEffect(() => {+ const anchor = scrollAnchor.current+ if (anchor?.query !== queryId || !listRef.current) return+ let offset = 0+ for (const row of rows) {+ if ('conversation' in row && row.conversation.key === anchor.key) {+ listRef.current.scrollTop = offset + Math.min(anchor.delta, rowHeight - 1)+ break+ }+ offset += 'group' in row ? groupHeight : rowHeight+ }+ }, [rows, rowHeight, queryId])+ useLayoutEffect(() => {+ virtual.scrollToOffset(offsets.current.get(queryId) || 0, { align: 'start' })+ if (focused) {+ const index = rows.findIndex(+ (row) => 'conversation' in row && row.conversation.key === focused,+ )+ if (index >= 0) virtual.scrollToIndex(index, { align: 'auto' })+ }+ listRef.current?.focus({ preventScroll: true })+ }, [queryId])+ const lastVisibleIndex = items.at(-1)?.index+ useEffect(() => {+ if (+ lastVisibleIndex !== undefined &&+ lastVisibleIndex > rows.length - 12 &&+ hasNextPage &&+ !isFetchingNextPage+ )+ onFetchNextPage()+ }, [lastVisibleIndex, rows.length, hasNextPage, isFetchingNextPage, onFetchNextPage])++ return (+ <div+ className="mail-list"+ ref={listRef}+ tabIndex={0}+ role="grid"+ aria-label="Conversations"+ aria-activedescendant={focused ? 'mail-' + encodeURIComponent(focused) : undefined}+ aria-rowcount={total}+ aria-multiselectable="true"+ onScroll={() => {+ const top = listRef.current?.scrollTop || 0+ offsets.current.set(queryId, top)+ const visible = items.find(+ (item) => item.start + item.size > top && 'conversation' in rows[item.index],+ )+ if (visible) {+ const row = rows[visible.index]+ if ('conversation' in row)+ scrollAnchor.current = {+ query: queryId,+ key: row.conversation.key,+ delta: top - visible.start,+ }+ }+ }}+ >+ <div style={{ height: virtual.getTotalSize(), position: 'relative', width: '100%' }}>+ {items.map((item) => {+ const row = rows[item.index]+ return (+ <div+ key={item.key}+ style={{+ position: 'absolute',+ top: 0,+ left: 0,+ width: '100%',+ height: item.size,+ transform: 'translateY(' + item.start + 'px)',+ }}+ >+ {'group' in row ? (+ <div className="date-group">{row.group}</div>+ ) : (+ <ListConversationRow+ conversation={row.conversation}+ account={accountById.get(row.conversation.accountId)}+ selected={allMatching || selected.has(row.conversation.key)}+ focused={focused === row.conversation.key}+ busy={busy}+ remoteImages={remoteImages}+ view={view}+ onOpen={onOpen}+ onFocus={onFocus}+ onSelect={onSelect}+ onAction={onAction}+ />+ )}+ </div>+ )+ })}+ </div>+ {isFetchingNextPage && (+ <div className="load-more">+ <Spinner size={14} />+ Loading more conversations…+ </div>+ )}+ </div>+ )+}diff --git a/apps/desktop/src/renderer/src/ConversationRow.tsx b/apps/desktop/src/renderer/src/ConversationRow.tsxnew file mode 100644index 0000000..69de3a9--- /dev/null+++ b/apps/desktop/src/renderer/src/ConversationRow.tsx@@ -0,0 +1,137 @@+import { Archive, Mail, MailOpen, Paperclip, Star, Trash2 } from '@inlark/ui/icons'+import { Checkbox, IconButton } from '@inlark/ui'+import type { Account, Conversation } from '@inlark/core'+import { shortDate } from './mail-date'+import { SenderAvatar } from './SenderAvatar'+import { AccountMark } from './AccountMark'+import { HintIconButton } from './HintIconButton'+import { actionLimit } from './account-limits'++export function senderLabel(conversation: Conversation) {+ return conversation.from.map((sender) => sender.name || sender.email.split('@')[0]).join(', ')+}++export function ConversationRow({+ conversation: c,+ account: a,+ selected,+ focused,+ busy,+ remoteImages,+ onOpen,+ onFocus,+ onSelect,+ onStar,+ onArchive,+ onTrash,+ onToggleRead,+}: {+ conversation: Conversation+ account?: Account+ selected: boolean+ focused: boolean+ busy: boolean+ remoteImages: boolean+ onOpen: () => void+ onFocus: () => void+ onSelect: (range: boolean) => void+ onStar: () => void+ onArchive?: () => void+ onTrash?: () => void+ onToggleRead: () => void+}) {+ const moveLimit = actionLimit(a, 'move')+ return (+ <div+ className={+ 'mail-row ' ++ (c.unread ? 'unread ' : '') ++ (selected ? 'selected ' : '') ++ (focused ? 'focused' : '')+ }+ role="row"+ id={'mail-' + encodeURIComponent(c.key)}+ aria-selected={selected}+ onClick={onOpen}+ onMouseDown={onFocus}+ >+ <div className="row-selector" role="gridcell" onClick={(event) => event.stopPropagation()}>+ <Checkbox+ aria-label={'Select ' + c.subject}+ checked={selected}+ disabled={busy}+ onCheckedChange={(_, event) => onSelect(!!(event as MouseEvent).shiftKey)}+ />+ <span className={'unread-dot ' + (c.unread ? 'visible' : '')} />+ </div>+ <div className="row-sender" role="gridcell">+ <SenderAvatar+ name={c.from[0]?.name || c.from[0]?.email || '?'}+ email={c.from[0]?.email}+ color={a?.color}+ size={28}+ remoteImages={remoteImages}+ />+ <span title={c.from.map((sender) => sender.email).join(', ')}>{senderLabel(c)}</span>+ {c.count > 1 && <small>{c.count}</small>}+ </div>+ <div className="row-content" role="gridcell">+ <span className="row-subject">{c.subject || '(No subject)'}</span>+ <span className="row-preview">{c.preview}</span>+ </div>+ <div className="row-meta" role="gridcell">+ <span className="row-attachment">+ {c.hasAttachment && <Paperclip size={13} aria-label="Has attachments" />}+ </span>+ {a && <AccountMark account={a} size={22} title={a.name} />}+ <time dateTime={c.receivedAt} title={new Date(c.receivedAt).toLocaleString()}>+ {shortDate(c.receivedAt)}+ </time>+ <button+ className={'row-star ' + (c.starred ? 'starred' : '')}+ aria-label={c.starred ? 'Unstar ' + c.subject : 'Star ' + c.subject}+ aria-pressed={c.starred}+ disabled={busy}+ onClick={(event) => {+ event.stopPropagation()+ onStar()+ }}+ >+ <Star size={14} />+ </button>+ <div className="row-quick-actions" onClick={(event) => event.stopPropagation()}>+ <IconButton+ label={c.unread ? 'Mark as read' : 'Mark as unread'}+ shortcut={c.unread ? 'Shift I' : 'U'}+ disabled={busy}+ onClick={onToggleRead}+ >+ {c.unread ? <MailOpen size={15} /> : <Mail size={15} />}+ </IconButton>+ {onArchive && (+ <HintIconButton+ label="Archive"+ shortcut="E"+ disabled={busy}+ hint={moveLimit}+ onClick={onArchive}+ >+ <Archive size={15} />+ </HintIconButton>+ )}+ {onTrash && (+ <HintIconButton+ label="Move to trash"+ shortcut="#"+ disabled={busy}+ hint={moveLimit}+ onClick={onTrash}+ >+ <Trash2 size={15} />+ </HintIconButton>+ )}+ </div>+ </div>+ </div>+ )+}diff --git a/apps/desktop/src/renderer/src/DraftList.tsx b/apps/desktop/src/renderer/src/DraftList.tsxnew file mode 100644index 0000000..93768ca--- /dev/null+++ b/apps/desktop/src/renderer/src/DraftList.tsx@@ -0,0 +1,119 @@+import { ArrowUpRight, FileText, Trash2, X } from '@inlark/ui/icons'+import { Checkbox, IconButton } from '@inlark/ui'+import type { Account, Draft, Message } from '@inlark/core'+import { shortDate } from './mail-date'++export type DraftItem =+ { kind: 'local'; key: string; draft: Draft } | { kind: 'server'; key: string; message: Message }++/** A send whose delivery is unconfirmed must be resolved before its draft can go. */+export const deletable = (item: DraftItem) =>+ item.kind === 'server' || item.draft.status !== 'uncertain'++export function DraftRows({+ items,+ accounts,+ selected,+ onOpen,+ onSelect,+ onDelete,+}: {+ items: DraftItem[]+ accounts: Account[]+ selected: ReadonlySet<string>+ onOpen: (item: DraftItem) => void+ onSelect: (key: string, range: boolean) => void+ onDelete: (keys: string[]) => void+}) {+ return (+ <div className={'draft-rows' + (selected.size ? ' selecting' : '')}>+ {items.map((item) => {+ const subject =+ item.kind === 'server' ? item.message.subject : item.draft.subject || 'New message'+ const canDelete = deletable(item)+ return (+ <div className={'draft-row' + (selected.has(item.key) ? ' selected' : '')} key={item.key}>+ <span className="draft-selector">+ <FileText size={17} />+ <Checkbox+ aria-label={'Select ' + subject}+ checked={selected.has(item.key)}+ disabled={!canDelete}+ onCheckedChange={(_, event) => onSelect(item.key, !!(event as MouseEvent).shiftKey)}+ />+ </span>+ <button className="draft-open" onClick={() => onOpen(item)}>+ <div>+ <strong>{subject}</strong>+ <span>+ {item.kind === 'server'+ ? accounts.find((a) => a.id === item.message.accountId)?.email+ : item.draft.to.map((a) => a.email).join(', ') || 'No recipients yet'}+ </span>+ </div>+ <small>+ {item.kind === 'server'+ ? 'Server draft'+ : item.draft.status === 'uncertain'+ ? 'Delivery unconfirmed'+ : 'Saved draft'}+ </small>+ <time>+ {shortDate(item.kind === 'server' ? item.message.receivedAt : item.draft.updatedAt)}+ </time>+ </button>+ <span className="draft-actions">+ <ArrowUpRight size={14} aria-hidden="true" />+ {canDelete && (+ <IconButton label="Delete draft" shortcut="#" onClick={() => onDelete([item.key])}>+ <Trash2 size={15} />+ </IconButton>+ )}+ </span>+ </div>+ )+ })}+ </div>+ )+}++export function DraftSelectionBar({+ count,+ total,+ onSelectAll,+ onDelete,+ onClear,+}: {+ count: number+ total: number+ onSelectAll: () => void+ onDelete: () => void+ onClear: () => void+}) {+ return (+ <div className="selection-bar" role="region" aria-label="Selection actions">+ <div className="selection-summary">+ <span className="selection-count" role="status">+ {count.toLocaleString()} selected+ </span>+ {total > count && (+ <button className="text-action" onClick={onSelectAll}>+ Select all {total.toLocaleString()}+ </button>+ )}+ </div>+ <span className="toolbar-divider" />+ <IconButton+ label={count > 1 ? 'Delete drafts' : 'Delete draft'}+ shortcut="#"+ onClick={onDelete}+ >+ <Trash2 size={16} />+ </IconButton>+ <span className="toolbar-divider" />+ <IconButton label="Clear selection" shortcut="Esc" onClick={onClear}>+ <X size={14} />+ </IconButton>+ </div>+ )+}diff --git a/apps/desktop/src/renderer/src/FolderMappings.tsx b/apps/desktop/src/renderer/src/FolderMappings.tsxnew file mode 100644index 0000000..89109cf--- /dev/null+++ b/apps/desktop/src/renderer/src/FolderMappings.tsx@@ -0,0 +1,241 @@+import { useEffect, useMemo, useState } from 'react'+import { useQuery } from '@tanstack/react-query'+import { AlertCircle, Check } from '@inlark/ui/icons'+import { Button, Modal, Select, Spinner } from '@inlark/ui'+import {+ folderRoles,+ friendlyError,+ type Account,+ type FolderMappingReview,+ type FolderMappings,+ type FolderRole,+} from '@inlark/core'+import { api } from './api'+import { queryClient } from './cache'++const roles: Record<FolderRole, { label: string; description: string; create: string }> = {+ sent: { label: 'Sent', description: 'Copies of messages you send.', create: 'Sent' },+ drafts: { label: 'Drafts', description: 'Messages you haven’t sent yet.', create: 'Drafts' },+ archive: {+ label: 'Archive',+ description: 'Where Archive moves conversations.',+ create: 'Archive',+ },+ junk: { label: 'Spam', description: 'Where Mark as spam moves conversations.', create: 'Junk' },+ trash: {+ label: 'Trash',+ description: 'Where Move to trash puts conversations.',+ create: 'Trash',+ },+}++/** A role is settled when the server declared it, the user chose it, or it is explicitly none. */+const settled = (review: FolderMappingReview, role: FolderRole) => {+ const mapping = review.mappings[role]+ return mapping === null || (!!mapping && mapping.source !== 'name')+}++export const needsFolderReview = (review: FolderMappingReview) =>+ folderRoles.some((role) => !settled(review, role))++/** What the review proposes: known folders as they are, a new folder for each missing role. */+export function initialFolderChoices(review: FolderMappingReview): FolderMappings {+ const choices: FolderMappings = {}+ for (const role of folderRoles) {+ const mapping = review.mappings[role]+ if (mapping === null) choices[role] = null+ else if (mapping) choices[role] = { path: mapping.path }+ else {+ const name = roles[role].create+ const existing = review.folders.find((f) => f.path.toLowerCase() === name.toLowerCase())+ choices[role] = existing ? { path: existing.path } : { path: name, create: true }+ }+ }+ return choices+}++const encode = (choice: FolderMappings[FolderRole]) =>+ choice === null || choice === undefined+ ? 'none'+ : choice.create+ ? 'create:' + choice.path+ : 'path:' + choice.path++/** One row per folder role: pick an existing folder, create one, or use none. */+export function FolderMappingEditor({+ review,+ value,+ onChange,+ disabled,+}: {+ review: FolderMappingReview+ value: FolderMappings+ onChange: (next: FolderMappings) => void+ disabled?: boolean+}) {+ // The server's Inbox can't hold any of these roles.+ const folders = review.folders.filter((f) => f.path.toUpperCase() !== 'INBOX')+ const proposal = useMemo(() => initialFolderChoices(review), [review])+ return (+ <div className="folder-roles">+ {folderRoles.map((role) => {+ const info = roles[role]+ const mapping = review.mappings[role]+ const choice = value[role]+ const createName = choice?.create ? choice.path : info.create+ const canCreate = !folders.some((f) => f.path.toLowerCase() === createName.toLowerCase())+ const options = [+ ...folders.map((f) => ({+ value: 'path:' + f.path,+ label: f.path === f.name ? f.name : f.path,+ })),+ ...(canCreate+ ? [{ value: 'create:' + createName, label: 'Create “' + createName + '”' }]+ : []),+ { value: 'none', label: 'None' },+ ]+ const changed = encode(choice) !== encode(proposal[role])+ const status = changed+ ? { text: 'Your choice', tone: 'confirmed' }+ : mapping?.source === 'server'+ ? { text: 'Set by the server', tone: 'confirmed' }+ : mapping?.source === 'user'+ ? { text: 'Your choice', tone: 'confirmed' }+ : mapping === null+ ? { text: 'Not used', tone: '' }+ : mapping?.source === 'name' || !proposal[role]?.create+ ? { text: 'Guessed from the name · check this', tone: 'uncertain' }+ : { text: 'Not found on the server · check this', tone: 'uncertain' }+ const id = 'folder-role-' + role+ return (+ <div className="folder-role" key={role}>+ <div className="folder-role-text">+ <label htmlFor={id}>+ <strong>{info.label}</strong>+ </label>+ <span className={'folder-role-status ' + status.tone}>+ {status.tone === 'confirmed' ? (+ <Check size={11} />+ ) : status.tone === 'uncertain' ? (+ <span className="folder-role-dot" aria-hidden="true" />+ ) : null}+ {status.text}+ </span>+ <p>{info.description}</p>+ </div>+ <Select+ id={id}+ aria-label={info.label + ' folder'}+ className="folder-role-select"+ disabled={disabled}+ value={encode(choice)}+ options={options}+ onValueChange={(next) =>+ onChange({+ ...value,+ [role]:+ next === 'none'+ ? null+ : next.startsWith('create:')+ ? { path: next.slice(7), create: true }+ : { path: next.slice(5) },+ })+ }+ />+ </div>+ )+ })}+ </div>+ )+}++/** Settings → Accounts → Folders…: the same editor as setup, saved straight to the account. */+export function FolderMappingsDialog({+ account,+ onClose,+ notify,+}: {+ account?: Account+ onClose: () => void+ notify: (message: string) => void+}) {+ const accountId = account?.id || ''+ const review = useQuery({+ queryKey: ['folder-mappings', accountId],+ queryFn: () => api.folderMappings(accountId),+ enabled: !!account,+ staleTime: 0,+ })+ const [choices, setChoices] = useState<FolderMappings>()+ const [saving, setSaving] = useState(false)+ const [error, setError] = useState('')+ useEffect(() => {+ setChoices(review.data ? initialFolderChoices(review.data) : undefined)+ setError('')+ }, [review.data])+ return (+ <Modal+ open={!!account}+ onOpenChange={(open) => {+ if (!open && !saving) onClose()+ }}+ title={'Folders for ' + (account?.name || 'this account')}+ description="Choose where Inlark keeps sent mail and drafts, and where Archive, Mark as spam and Move to trash put conversations."+ className="folder-modal"+ >+ <form+ onSubmit={async (e) => {+ e.preventDefault()+ if (!choices || !account) return+ setSaving(true)+ setError('')+ try {+ const saved = await api.setFolderMappings(account.id, choices)+ queryClient.setQueryData(['folder-mappings', account.id], saved)+ await queryClient.invalidateQueries({ queryKey: ['mailboxes', account.id] })+ notify('Folder settings saved.')+ onClose()+ } catch (e) {+ setError(friendlyError(e))+ } finally {+ setSaving(false)+ }+ }}+ >+ {review.isError ? (+ <div role="alert" className="form-error">+ <AlertCircle size={14} />+ {friendlyError(review.error)}+ </div>+ ) : review.data && choices ? (+ <FolderMappingEditor+ review={review.data}+ value={choices}+ onChange={setChoices}+ disabled={saving}+ />+ ) : (+ <div className="folder-roles-loading" role="status">+ <Spinner size={14} />+ Loading folders…+ </div>+ )}+ {error && (+ <div role="alert" className="form-error">+ <AlertCircle size={14} />+ {error}+ </div>+ )}+ <div className="modal-actions">+ <Button onClick={onClose} disabled={saving}>+ Cancel+ </Button>+ <Button type="submit" variant="primary" disabled={!choices || saving}>+ {saving && <Spinner size={14} />}+ {saving ? 'Saving…' : 'Save folders'}+ </Button>+ </div>+ </form>+ </Modal>+ )+}diff --git a/apps/desktop/src/renderer/src/HintIconButton.tsx b/apps/desktop/src/renderer/src/HintIconButton.tsxnew file mode 100644index 0000000..5b4329a--- /dev/null+++ b/apps/desktop/src/renderer/src/HintIconButton.tsx@@ -0,0 +1,55 @@+import type { ButtonHTMLAttributes } from 'react'+import { Tooltip } from '@base-ui/react/tooltip'+import { Button, IconButton } from '@inlark/ui'++/**+ * An icon button that can explain why its action is unavailable. When `hint` is set the button+ * stays focusable (so the tooltip still shows) but is marked unavailable; its click handler+ * still runs, so the caller can repeat the explanation as a toast.+ */+export function HintIconButton({+ label,+ shortcut,+ hint,+ children,+ ...props+}: ButtonHTMLAttributes<HTMLButtonElement> & {+ label: string+ shortcut?: string+ hint?: string+}) {+ if (!hint)+ return (+ <IconButton label={label} shortcut={shortcut} {...props}>+ {children}+ </IconButton>+ )+ return (+ <Tooltip.Root>+ <Tooltip.Trigger+ render={+ <Button+ size="icon"+ variant="ghost"+ aria-label={label + '. ' + hint}+ aria-disabled+ {...props}+ />+ }+ >+ {children}+ </Tooltip.Trigger>+ <Tooltip.Portal>+ <Tooltip.Positioner sideOffset={7}>+ <Tooltip.Popup className="tooltip tooltip-with-hint">+ <span className="tooltip-text">+ {label}+ <span className="tooltip-hint">{hint}</span>+ </span>+ {shortcut && <kbd>{shortcut}</kbd>}+ </Tooltip.Popup>+ </Tooltip.Positioner>+ </Tooltip.Portal>+ </Tooltip.Root>+ )+}diff --git a/apps/desktop/src/renderer/src/IndexingMeter.tsx b/apps/desktop/src/renderer/src/IndexingMeter.tsxnew file mode 100644index 0000000..cbe6d56--- /dev/null+++ b/apps/desktop/src/renderer/src/IndexingMeter.tsx@@ -0,0 +1,30 @@+import type { IndexingProgress } from '@inlark/core'++/** “Indexing mail · 12,340 of 50,000” with a slim bar; quiet, since indexing needs no action. */+export function IndexingMeter({+ indexing,+ label = 'Indexing mail',+}: {+ indexing: IndexingProgress+ label?: string+}) {+ const total = Math.max(indexing.total, indexing.indexed)+ const ratio = total ? indexing.indexed / total : 0+ return (+ <span className="indexing-meter">+ <span>+ {label} · {indexing.indexed.toLocaleString()} of {total.toLocaleString()}+ </span>+ <span+ className="indexing-bar"+ role="progressbar"+ aria-label={label}+ aria-valuemin={0}+ aria-valuemax={total}+ aria-valuenow={indexing.indexed}+ >+ <span style={{ width: Math.round(ratio * 100) + '%' }} />+ </span>+ </span>+ )+}diff --git a/apps/desktop/src/renderer/src/MoveDialog.tsx b/apps/desktop/src/renderer/src/MoveDialog.tsxnew file mode 100644index 0000000..a754f95--- /dev/null+++ b/apps/desktop/src/renderer/src/MoveDialog.tsx@@ -0,0 +1,59 @@+import { useQuery } from '@tanstack/react-query'+import { ChevronRight, Folder } from '@inlark/ui/icons'+import { Modal } from '@inlark/ui'+import type { Bootstrap, MutationTarget } from '@inlark/core'+import { api } from './api'+import { actionLimit } from './account-limits'++export function MoveDialog({+ targets,+ accounts,+ onClose,+ onMove,+}: {+ targets?: MutationTarget[]+ accounts: Bootstrap['accounts']+ onClose: () => void+ onMove: (id: string) => void+}) {+ const ids = new Set(targets?.map((t) => t.accountId))+ const accountId = targets?.[0]?.accountId || ''+ const limit = actionLimit(+ accounts.find((a) => a.id === accountId),+ 'move',+ )+ const boxes = useQuery({+ queryKey: ['mailboxes', accountId],+ queryFn: () => api.mailboxes(accountId),+ enabled: !!targets && ids.size === 1,+ })+ return (+ <Modal+ open={!!targets}+ onOpenChange={(open) => {+ if (!open) onClose()+ }}+ title="Move to folder"+ description={+ ids.size > 1+ ? 'Select conversations within one account to move them to a folder.'+ : accounts.find((a) => a.id === accountId)?.email+ }+ >+ {limit && <p className="modal-body-text">{limit}</p>}+ <div className="folder-picker">+ {ids.size === 1 &&+ !limit &&+ boxes.data+ ?.filter((b) => b.rights.mayAddItems && b.role !== 'drafts' && b.role !== 'sent')+ .map((b) => (+ <button key={b.id} onClick={() => onMove(b.id)}>+ <Folder size={15} />+ {b.name}+ <ChevronRight size={13} />+ </button>+ ))}+ </div>+ </Modal>+ )+}diff --git a/apps/desktop/src/renderer/src/Reader.tsx b/apps/desktop/src/renderer/src/Reader.tsxnew file mode 100644index 0000000..4c3935c--- /dev/null+++ b/apps/desktop/src/renderer/src/Reader.tsx@@ -0,0 +1,894 @@+import { useEffect, useLayoutEffect, useRef, useState } from 'react'+import DOMPurify from 'dompurify'+import {+ ArrowLeft,+ Archive,+ Trash2,+ Star,+ MoreHorizontal,+ ChevronUp,+ ChevronDown,+ Reply,+ ReplyAll,+ Forward,+ Download,+ ExternalLink,+ ImageOff,+ ChevronRight,+ ShieldX,+ Mail,+ FileText,+ File,+ FileImage,+ FileArchive,+ FileSpreadsheet,+ FolderInput,+ Inbox,+ Paperclip,+ ShieldCheck,+} from '@inlark/ui/icons'+import { Button, IconButton, Dropdown, MenuItem } from '@inlark/ui'+import {+ friendlyError,+ type Account,+ type Message,+ type Settings,+ type MailAction,+} from '@inlark/core'+import { api } from './api'+import { SenderAvatar } from './SenderAvatar'+import { useResolvedTheme, token } from './theme'+import { formatBytes, longDate, messageDate } from './mail-date'+import { AccountMark } from './AccountMark'+import { HintIconButton } from './HintIconButton'+import { actionLimit } from './account-limits'++const formatAddress = (a: { name: string; email: string }) =>+ a.name ? a.name + ' <' + a.email + '>' : a.email++const linkPattern = /\b(https?:\/\/[^\s<>"']+[^\s<>"'.,;:!?)\]])/g+const escapeText = (value: string) => {+ const holder = document.createElement('div')+ holder.textContent = value+ return holder.innerHTML+}+/** Plain text as HTML with web addresses made clickable. */+const plainHtml = (value: string) =>+ '<div style="white-space:pre-wrap">' ++ escapeText(value).replace(linkPattern, (url) => '<a href="' + url + '">' + url + '</a>') ++ '</div>'+/**+ * Mail that paints its own backgrounds, lays itself out with tables, or carries images (logos+ * are usually drawn for white) is shown on white paper, as its sender designed it. Everything+ * else adopts the app theme, so a short note reads like part of the app.+ */+const hasOwnStyling = (root: DocumentFragment) =>+ !!root.querySelector('[bgcolor],[background],table table,img') ||+ [...root.querySelectorAll('[style]')].some((element) =>+ /(?:^|;)\s*background(?:-color|-image)?\s*:/i.test(element.getAttribute('style') || ''),+ )+const luminance = (color: string) => {+ const [r, g, b] = (color.match(/[\d.]+/g) || []).slice(0, 3).map((value) => {+ const channel = Number(value) / 255+ return channel <= 0.03928 ? channel / 12.92 : ((channel + 0.055) / 1.055) ** 2.4+ })+ return r === undefined ? null : 0.2126 * r + 0.7152 * g + 0.0722 * b+}+/** Sender text colours stay unless they would be hard to read on the theme background. */+const softenColors = (doc: Document, background: string) => {+ const base = luminance(background)+ if (base === null) return+ for (const element of doc.body.querySelectorAll<HTMLElement>('[style*="color"],font[color]')) {+ const value = luminance(getComputedStyle(element).color)+ if (value === null) continue+ const contrast = (Math.max(base, value) + 0.05) / (Math.min(base, value) + 0.05)+ if (contrast < 3.2) {+ element.style.color = 'inherit'+ element.removeAttribute('color')+ }+ }+}+const fontStack = "Inter,-apple-system,BlinkMacSystemFont,'Segoe UI',sans-serif"+const paperStyles =+ 'html,body{margin:0;background:#fff;color:#24262b;font:16px/1.75 ' ++ fontStack ++ ';overflow-wrap:anywhere}body{padding:22px 24px 26px}p{margin:0 0 16px}a{color:#5a4fb0}blockquote{margin:16px 0;padding-left:16px;border-left:2px solid #d5d5dc;color:#5d6068}hr{border:0;border-top:1px solid #e3e3e8;margin:24px 0}summary{color:#70737d}summary:hover{background:#f0f0f3}'+const adaptiveStyles = (theme: 'light' | 'dark') =>+ 'html,body{margin:0;background:transparent;color:' ++ token('--text') ++ ';font:15px/1.7 ' ++ fontStack ++ ';overflow-wrap:anywhere;color-scheme:' ++ theme ++ '}body{padding:2px 0 4px}p{margin:0 0 14px}a{color:' ++ token('--accent') ++ ';text-decoration:underline;text-decoration-color:' ++ token('--border-strong') ++ ';text-underline-offset:3px}a:hover{text-decoration-color:currentColor}blockquote{margin:14px 0;padding-left:14px;border-left:2px solid ' ++ token('--border-strong') ++ ';color:' ++ token('--muted') ++ '}hr{border:0;border-top:1px solid ' ++ token('--border-strong') ++ ';margin:22px 0}summary{color:' ++ token('--muted') ++ ';border-color:' ++ token('--border-strong') ++ '}summary:hover{color:' ++ token('--text') ++ '}::selection{background:' ++ token('--accent') ++ '44}'+const sharedStyles =+ 'img{max-width:100%;height:auto}table{max-width:100%}pre{white-space:pre-wrap}details{margin-top:14px}summary{display:inline-flex;align-items:center;height:18px;padding:0 8px;border:1px solid #d5d5dc;border-radius:9px;cursor:pointer;font-size:11px;letter-spacing:1px;list-style:none;user-select:none}summary::-webkit-details-marker{display:none}details[open]>summary{margin-bottom:10px}'++export function EmailBody({+ message,+ remoteImages,+ loading = false,+ onLinkHover,+ onMailto,+}: {+ message: Message+ remoteImages: boolean+ /** The message body is still being fetched; show its shape instead of the preview. */+ loading?: boolean+ onLinkHover?: (href: string | null) => void+ onMailto?: (url: string) => void+}) {+ const frame = useRef<HTMLIFrameElement>(null)+ const observer = useRef<ResizeObserver | null>(null)+ const linkedDocument = useRef<Document | null>(null)+ const writtenSource = useRef<string | null>(null)+ const [source, setSource] = useState('')+ const [adaptive, setAdaptive] = useState(false)+ const adaptiveFrame = useRef(false)+ const [blocked, setBlocked] = useState(false)+ const [frameReady, setFrameReady] = useState(false)+ const [renderIssue, setRenderIssue] = useState<string | null>(null)+ const [copyStatus, setCopyStatus] = useState('')+ const theme = useResolvedTheme()+ const hover = useRef(onLinkHover)+ hover.current = onLinkHover+ const mailto = useRef(onMailto)+ mailto.current = onMailto+ const describeIssue = (stage: string, error: string, currentSource = source) =>+ JSON.stringify(+ {+ stage,+ error,+ htmlChars: message.html?.length ?? 0,+ textChars: message.text?.length ?? 0,+ sourceChars: currentSource.length,+ sourceWritten: writtenSource.current === currentSource,+ frame: (() => {+ try {+ const doc = frame.current?.contentDocument+ return {+ present: !!frame.current,+ documentAccessible: !!doc,+ documentKind: doc?.URL.startsWith('blob:')+ ? 'blob'+ : doc?.URL.startsWith('about:')+ ? doc.URL+ : doc+ ? 'other'+ : null,+ readyState: doc?.readyState ?? null,+ bodyPresent: !!doc?.body,+ bodyTextChars: doc?.body?.textContent?.length ?? null,+ bodyHtmlChars: doc?.body?.innerHTML.length ?? null,+ }+ } catch (cause) {+ return {+ inspectionError:+ cause instanceof Error ? `${cause.name}: ${cause.message}` : String(cause),+ }+ }+ })(),+ },+ null,+ 2,+ )+ useEffect(() => {+ let active = true+ const run = async () => {+ const template = document.createElement('template')+ const plain = plainHtml(+ (message.text?.trim() ? message.text : message.preview) ||+ 'No readable message body is available.',+ )+ template.innerHTML = DOMPurify.sanitize((message.html?.trim() ? message.html : '') || plain, {+ FORBID_TAGS: [+ 'script',+ 'style',+ 'iframe',+ 'frame',+ 'object',+ 'embed',+ 'form',+ 'input',+ 'button',+ 'textarea',+ 'select',+ 'meta',+ 'base',+ 'link',+ 'svg',+ 'math',+ 'video',+ 'audio',+ 'source',+ ],+ FORBID_ATTR: ['srcset', 'action', 'formaction', 'ping', 'autofocus', 'contenteditable'],+ })+ if (+ !template.content.textContent?.trim() &&+ (message.text?.trim() || message.preview?.trim())+ )+ template.innerHTML = DOMPurify.sanitize(plain)+ const imageJobs = [...template.content.querySelectorAll('img')].map(async (image) => {+ const original = image.getAttribute('src') || ''+ image.removeAttribute('src')+ if (+ image.hidden ||+ image.style.display === 'none' ||+ image.style.visibility === 'hidden' ||+ (image.style.width === '1px' && image.style.height === '1px') ||+ (image.getAttribute('width') === '1' && image.getAttribute('height') === '1')+ ) {+ image.remove()+ return+ }+ image.setAttribute('referrerpolicy', 'no-referrer')+ image.style.maxWidth = '100%'+ try {+ if (original.startsWith('cid:')) {+ const attachment = message.attachments?.find(+ (a) => a.cid?.replace(/^<|>$/g, '') === original.slice(4),+ )+ if (attachment) image.src = await api.inlineImage(message.accountId, attachment)+ else image.replaceWith(document.createTextNode(image.alt || ''))+ } else if (/^https?:/.test(original) && remoteImages) {+ const source = await api.remoteImage(original)+ if (source) image.src = source+ else image.replaceWith(document.createTextNode(image.alt || ''))+ } else if (/^https?:/.test(original) && active) setBlocked(true)+ } catch {+ image.replaceWith(document.createTextNode(image.alt || ''))+ }+ })+ // Tracking pixels were removed synchronously above, so they do not count as images.+ const ownStyling = hasOwnStyling(template.content)+ const html = () =>+ '<!doctype html><html><head><meta charset="utf-8"><meta name="color-scheme" content="' ++ (ownStyling ? 'light' : theme) ++ '"><meta http-equiv="Content-Security-Policy" content="default-src \'none\'; img-src data: blob:; style-src \'unsafe-inline\'; base-uri \'none\'; form-action \'none\'"><meta name="referrer" content="no-referrer"><style>' ++ sharedStyles ++ (ownStyling ? paperStyles : adaptiveStyles(theme)) ++ '</style></head><body>' ++ template.innerHTML ++ '</body></html>'+ for (const quote of template.content.querySelectorAll('blockquote')) {+ const details = document.createElement('details'),+ summary = document.createElement('summary')+ summary.textContent = '•••'+ summary.title = 'Show quoted text'+ details.append(summary)+ quote.replaceWith(details)+ details.append(quote)+ }+ if (active) {+ adaptiveFrame.current = !ownStyling+ setAdaptive(!ownStyling)+ setSource(html())+ }+ await Promise.allSettled(imageJobs)+ if (active) setSource(html())+ }+ setBlocked(false)+ setFrameReady(false)+ setRenderIssue(null)+ setCopyStatus('')+ writtenSource.current = null+ setSource('')+ if (loading) return+ void run().catch((cause: unknown) => {+ if (!active) return+ const error =+ cause instanceof Error ? (cause.stack ?? `${cause.name}: ${cause.message}`) : String(cause)+ setRenderIssue(describeIssue('Preparing HTML', error))+ })+ return () => {+ active = false+ }+ }, [message.id, message.html, message.text, remoteImages, theme, loading])+ useEffect(() => {+ if (!source || frameReady || renderIssue) return+ const timeout = window.setTimeout(() => {+ setRenderIssue(+ (current) =>+ current ??+ describeIssue('Loading HTML frame', 'No readable frame content after 3 seconds.', source),+ )+ }, 3000)+ return () => window.clearTimeout(timeout)+ }, [source, frameReady, renderIssue])+ const resizeFrame = () => {+ try {+ const element = frame.current+ const body = element?.contentDocument?.body+ if (element && body)+ element.style.height = Math.min(30000, Math.max(80, body.scrollHeight + 8)) + 'px'+ } catch (cause) {+ setFrameReady(false)+ const error =+ cause instanceof Error ? (cause.stack ?? `${cause.name}: ${cause.message}`) : String(cause)+ setRenderIssue(describeIssue('Resizing HTML frame', error))+ }+ }+ const onFrameLoad = () => {+ observer.current?.disconnect()+ if (!source || writtenSource.current !== source) return+ try {+ const doc = frame.current?.contentDocument+ if (!doc?.body) {+ setFrameReady(false)+ setRenderIssue(+ describeIssue('Loading HTML frame', 'The frame loaded without an accessible body.'),+ )+ return+ }+ const hasContent = !!(doc.body.textContent?.trim() || doc.body.querySelector('img'))+ setFrameReady(hasContent)+ if (!hasContent) {+ setRenderIssue(+ describeIssue(+ 'Loading HTML frame',+ 'The frame body contains no readable text or images.',+ ),+ )+ return+ }+ setRenderIssue(null)+ if (adaptiveFrame.current) softenColors(doc, getComputedStyle(document.body).backgroundColor)+ resizeFrame()+ observer.current = new ResizeObserver(resizeFrame)+ observer.current.observe(doc.body)+ if (linkedDocument.current !== doc) {+ linkedDocument.current = doc+ doc.addEventListener('click', (event) => {+ const link = (event.target as Element).closest('a')+ if (link) {+ event.preventDefault()+ const href = link.getAttribute('href')+ if (!href || href.startsWith('#')) return+ if (/^mailto:/i.test(href) && mailto.current) mailto.current(href)+ else void api.openExternal(href).catch(() => {})+ }+ })+ doc.addEventListener('mouseover', (event) => {+ const href = (event.target as Element).closest?.('a')?.getAttribute('href')+ hover.current?.(href && !href.startsWith('#') ? href : null)+ })+ doc.addEventListener('mouseleave', () => hover.current?.(null))+ // Keep app shortcuts working after clicking into the message body.+ doc.addEventListener('keydown', (event) => {+ const forwarded = new KeyboardEvent('keydown', {+ key: event.key,+ code: event.code,+ shiftKey: event.shiftKey,+ ctrlKey: event.ctrlKey,+ altKey: event.altKey,+ metaKey: event.metaKey,+ repeat: event.repeat,+ bubbles: true,+ cancelable: true,+ })+ document.dispatchEvent(forwarded)+ if (forwarded.defaultPrevented) event.preventDefault()+ })+ }+ } catch (cause) {+ setFrameReady(false)+ const error =+ cause instanceof Error ? (cause.stack ?? `${cause.name}: ${cause.message}`) : String(cause)+ setRenderIssue(describeIssue('Inspecting HTML frame', error))+ }+ }+ useLayoutEffect(() => {+ if (!source) {+ observer.current?.disconnect()+ return+ }+ try {+ const doc = frame.current?.contentDocument+ if (!doc) {+ setRenderIssue(+ describeIssue('Writing HTML frame', 'The blank frame document is inaccessible.', source),+ )+ return+ }+ observer.current?.disconnect()+ setFrameReady(false)+ setRenderIssue(null)+ writtenSource.current = null+ linkedDocument.current = null+ doc.open()+ doc.write(source)+ doc.close()+ writtenSource.current = source+ onFrameLoad()+ } catch (cause) {+ setFrameReady(false)+ const error =+ cause instanceof Error ? (cause.stack ?? `${cause.name}: ${cause.message}`) : String(cause)+ setRenderIssue(describeIssue('Writing HTML frame', error, source))+ }+ }, [source])+ useLayoutEffect(() => {+ if (frameReady) resizeFrame()+ }, [frameReady, source])+ useEffect(() => () => observer.current?.disconnect(), [])+ return (+ <>+ {blocked && (+ <div className="image-notice">+ <ImageOff size={13} />+ Remote images are off. You can enable them in Settings.+ </div>+ )}+ {source && (+ <iframe+ ref={frame}+ title={'Message from ' + (message.from[0]?.name || message.from[0]?.email || 'sender')}+ sandbox="allow-same-origin"+ className={'email-frame' + (adaptive ? ' email-frame-adaptive' : '')}+ referrerPolicy="no-referrer"+ onLoad={onFrameLoad}+ onError={() => {+ setFrameReady(false)+ setRenderIssue(describeIssue('Loading HTML frame', 'The frame emitted an error event.'))+ }}+ style={{ display: frameReady ? 'block' : 'none' }}+ />+ )}+ {loading && (+ <div className="body-skeleton" aria-label="Loading message" role="status">+ <span />+ <span />+ <span />+ <span />+ </div>+ )}+ {!frameReady && !loading && (+ <>+ <div className="email-fallback">+ {(message.text?.trim() ? message.text : message.preview?.trim()) ||+ 'No readable message body is available.'}+ </div>+ {renderIssue && (+ <details className="email-render-details">+ <summary>HTML rendering details</summary>+ <p>+ Review these details before sharing them. Error text can contain message+ information.+ </p>+ <pre>{renderIssue}</pre>+ <button+ type="button"+ onClick={() => {+ void navigator.clipboard.writeText(renderIssue).then(+ () => setCopyStatus('Copied render details.'),+ () => setCopyStatus('Could not copy. Select the details above instead.'),+ )+ }}+ >+ Copy render details+ </button>+ {copyStatus && <span role="status">{copyStatus}</span>}+ </details>+ )}+ </>+ )}+ </>+ )+}+interface ReaderProps {+ messages: Message[]+ account: Account+ settings: Settings+ backLabel: string+ busy: boolean+ onBack: () => void+ onPrevious?: () => void+ onNext?: () => void+ position?: string+ onAction: (action: MailAction) => void+ onMove: () => void+ onReply: (message: Message, kind: 'reply' | 'replyAll' | 'forward') => void+ notify: (message: string) => void+ onMailto: (url: string) => void+ /** Messages are list summaries while the full conversation loads. */+ loading?: boolean+}+const attachmentIcon = (type: string, name: string) =>+ type.startsWith('image/')+ ? FileImage+ : /zip|compressed|tar|gzip|x-7z|rar/.test(type) || /\.(zip|tar|gz|7z|rar)$/i.test(name)+ ? FileArchive+ : /spreadsheet|excel|csv/.test(type) || /\.(xlsx?|csv|ods)$/i.test(name)+ ? FileSpreadsheet+ : type === 'application/pdf' || /^text\//.test(type) || /word|document/.test(type)+ ? FileText+ : File+const extension = (name: string) => {+ const match = /\.([a-z0-9]{1,5})$/i.exec(name)+ return match ? match[1].toUpperCase() : 'File'+}+export function Reader({+ messages,+ account,+ settings,+ backLabel,+ busy,+ onBack,+ onPrevious,+ onNext,+ position,+ onAction,+ onMove,+ onReply,+ notify,+ onMailto,+ loading = false,+}: ReaderProps) {+ const last = messages[messages.length - 1]+ const initiallyExpanded = () =>+ new Set(+ messages+ .filter((m) => !m.keywords.$seen)+ .map((m) => m.id)+ .concat(last?.id || ''),+ )+ const [expanded, setExpanded] = useState<Set<string>>(initiallyExpanded)+ const [details, setDetails] = useState<Set<string>>(new Set())+ const [link, setLink] = useState<string | null>(null)+ const messageIds = messages.map((m) => m.id).join()+ const firstIds = useRef(messageIds)+ useEffect(() => {+ // A newly arrived reply (or the full thread replacing its summary) opens unread messages.+ if (firstIds.current !== messageIds) {+ firstIds.current = messageIds+ setExpanded(initiallyExpanded())+ }+ }, [messageIds])+ const starred = messages.some((m) => m.keywords.$flagged)+ const moveLimit = actionLimit(account, 'move')+ const toggle = (id: string, setter: typeof setExpanded) =>+ setter((current) => {+ const next = new Set(current)+ next.has(id) ? next.delete(id) : next.add(id)+ return next+ })+ const [showAll, setShowAll] = useState(false)+ if (!last) return null+ // Long threads show their first message and the latest few; the middle folds into one row.+ const folded =+ !showAll && messages.length > 4+ ? messages.slice(1, -2).filter((m) => !expanded.has(m.id) || m.id === last.id)+ : []+ const foldedIds = new Set(folded.length > 1 ? folded.map((m) => m.id) : [])+ const participants = [+ ...new Set(messages.flatMap((m) => m.from.map((a) => a.name || a.email.split('@')[0]))),+ ]+ return (+ <div className="reader-page">+ <div className="reader-toolbar">+ <Button+ variant="ghost"+ className="reader-back"+ aria-label={'Back to ' + backLabel.toLowerCase()}+ onClick={onBack}+ title="Back · Esc"+ >+ <ArrowLeft size={16} />+ <span>{backLabel}</span>+ </Button>+ <span className="toolbar-divider" />+ <HintIconButton+ disabled={busy}+ label="Archive"+ shortcut="E"+ hint={moveLimit}+ onClick={() => onAction('archive')}+ >+ <Archive size={16} />+ </HintIconButton>+ <HintIconButton+ disabled={busy}+ label="Move to trash"+ shortcut="#"+ hint={moveLimit}+ onClick={() => onAction('trash')}+ >+ <Trash2 size={16} />+ </HintIconButton>+ <IconButton+ disabled={busy}+ label="Mark unread"+ shortcut="U"+ onClick={() => onAction('unread')}+ >+ <Mail size={16} />+ </IconButton>+ <IconButton+ disabled={busy}+ aria-pressed={starred}+ label={starred ? 'Remove star' : 'Star conversation'}+ shortcut="S"+ onClick={() => onAction(starred ? 'unstar' : 'star')}+ >+ <Star size={16} className={starred ? 'starred' : ''} />+ </IconButton>+ <Dropdown+ trigger={+ <Button+ variant="ghost"+ size="icon"+ disabled={busy}+ aria-label="More conversation actions"+ >+ <MoreHorizontal size={17} />+ </Button>+ }+ >+ <MenuItem onClick={onMove} disabled={!!moveLimit}>+ <FolderInput size={14} />+ Move to folder+ <kbd className="menu-shortcut">V</kbd>+ </MenuItem>+ <MenuItem onClick={() => onAction('spam')} disabled={!!moveLimit}>+ <ShieldX size={14} />+ Mark as spam+ <kbd className="menu-shortcut">!</kbd>+ </MenuItem>+ <MenuItem onClick={() => onAction('notSpam')} disabled={!!moveLimit}>+ <ShieldCheck size={14} />+ Not spam+ </MenuItem>+ <MenuItem onClick={() => onAction('restore')} disabled={!!moveLimit}>+ <Inbox size={14} />+ Restore to inbox+ </MenuItem>+ {moveLimit && <p className="menu-note">{moveLimit}</p>}+ </Dropdown>+ <div className="reader-navigation">+ <span role="status">{busy ? 'Updating…' : position}</span>+ <IconButton+ label="Previous conversation"+ shortcut="K"+ onClick={onPrevious}+ disabled={!onPrevious}+ >+ <ChevronUp size={16} />+ </IconButton>+ <IconButton label="Next conversation" shortcut="J" onClick={onNext} disabled={!onNext}>+ <ChevronDown size={16} />+ </IconButton>+ </div>+ </div>+ <div className="reader-scroll">+ <div className="reader-content">+ <div className="reader-eyebrow">+ <AccountMark account={account} size={16} />+ <span title={account.email}>{account.name}</span>+ <ChevronRight size={11} />+ <span>+ {messages.length > 1+ ? messages.length ++ ' messages · ' ++ participants.slice(0, 3).join(', ') ++ (participants.length > 3 ? ' +' + (participants.length - 3) : '')+ : 'Conversation'}+ </span>+ </div>+ <h1>{last.subject || '(No subject)'}</h1>+ <div className="conversation-messages">+ {messages.map((message) => {+ if (foldedIds.has(message.id))+ return message.id === folded[0].id ? (+ <button key="folded" className="folded-messages" onClick={() => setShowAll(true)}>+ <span>{folded.length} earlier messages</span>+ </button>+ ) : null+ const open = expanded.has(message.id) || messages.length === 1+ const sender = message.from[0]+ const when = messageDate(message.receivedAt)+ const attachments =+ message.attachments?.filter((a) => !a.cid || a.disposition === 'attachment') || []+ return (+ <article+ className={'message-card ' + (!open ? 'collapsed-message' : '')}+ key={message.id}+ >+ <div className="message-heading">+ <SenderAvatar+ name={sender?.name || sender?.email || '?'}+ email={sender?.email}+ color={account.color}+ size={35}+ remoteImages={settings.remoteImages}+ />+ <button+ className="message-person"+ onClick={() => toggle(message.id, setExpanded)}+ aria-expanded={open}+ disabled={messages.length === 1}+ >+ <span className="sender-name">+ {sender?.name || sender?.email}+ <span className="sender-address">{sender?.name ? sender.email : ''}</span>+ </span>+ <span className="message-to">+ {open+ ? 'to ' ++ ([...message.to, ...message.cc]+ .map((a) => a.name || a.email)+ .join(', ') || 'undisclosed recipients')+ : message.preview}+ </span>+ </button>+ {!!message.attachments?.length && !open && (+ <Paperclip size={13} className="message-attachment-hint" />+ )}+ <time dateTime={message.receivedAt} title={longDate(message.receivedAt)}>+ {when.date}+ <span> · {when.time}</span>+ </time>+ <IconButton+ label="Message details"+ aria-expanded={details.has(message.id)}+ onClick={() => toggle(message.id, setDetails)}+ >+ <ChevronDown+ size={13}+ className={'details-chevron' + (details.has(message.id) ? ' open' : '')}+ />+ </IconButton>+ </div>+ {details.has(message.id) && (+ <dl className="message-details">+ <dt>From</dt>+ <dd>{message.from.map(formatAddress).join(', ')}</dd>+ {message.replyTo.length > 0 && (+ <>+ <dt>Reply to</dt>+ <dd>{message.replyTo.map(formatAddress).join(', ')}</dd>+ </>+ )}+ <dt>To</dt>+ <dd>{message.to.map(formatAddress).join(', ') || '—'}</dd>+ {message.cc.length > 0 && (+ <>+ <dt>Cc</dt>+ <dd>{message.cc.map(formatAddress).join(', ')}</dd>+ </>+ )}+ <dt>Date</dt>+ <dd>{longDate(message.receivedAt)}</dd>+ <dt>Account</dt>+ <dd>+ {account.name} · {account.email}+ </dd>+ <dt>Message ID</dt>+ <dd>{message.messageId?.join(', ') || message.id}</dd>+ </dl>+ )}+ {open && (+ <div className="message-content">+ {message.unsubscribe && (+ <button+ className="unsubscribe-link"+ onClick={async () => {+ try {+ const result = await api.unsubscribe(account.id, message.id)+ if (result.kind === 'mailto' && result.url) onMailto(result.url)+ else+ notify(+ result.kind === 'done'+ ? 'Unsubscribe request sent.'+ : 'Unsubscribe page opened.',+ )+ } catch (error) {+ notify(friendlyError(error))+ }+ }}+ >+ Unsubscribe from this mailing list <ExternalLink size={11} />+ </button>+ )}+ <EmailBody+ message={message}+ remoteImages={settings.remoteImages}+ loading={loading && !message.html && !message.text}+ onLinkHover={setLink}+ onMailto={onMailto}+ />+ {attachments.length > 0 && (+ <div className="attachment-list">+ {attachments.map((attachment) => {+ const Icon = attachmentIcon(attachment.type, attachment.name)+ return (+ <div className="attachment-card" key={attachment.blobId}>+ <button+ className="attachment-open"+ title={'Open ' + attachment.name}+ onClick={() =>+ void api+ .attachment(account.id, attachment, true)+ .catch((e) => notify(friendlyError(e)))+ }+ >+ <span className="attachment-icon">+ <Icon size={18} strokeWidth={1.6} />+ </span>+ <span className="attachment-label">+ <strong>{attachment.name}</strong>+ <span>+ {extension(attachment.name)} · {formatBytes(attachment.size)}+ </span>+ </span>+ </button>+ <IconButton+ label={'Save ' + attachment.name}+ onClick={() =>+ void api+ .attachment(account.id, attachment, false)+ .catch((e) => notify(friendlyError(e)))+ }+ >+ <Download size={14} />+ </IconButton>+ </div>+ )+ })}+ </div>+ )}+ </div>+ )}+ </article>+ )+ })}+ </div>+ <div className="reply-panel">+ <button className="reply-prompt" onClick={() => onReply(last, 'reply')}>+ <Reply size={17} />+ <span>+ <strong>Reply to {last.from[0]?.name || last.from[0]?.email || 'sender'}</strong>+ </span>+ <kbd>R</kbd>+ </button>+ <div className="reply-bar">+ <Button variant="ghost" onClick={() => onReply(last, 'replyAll')}>+ <ReplyAll size={14} />+ Reply all+ <kbd>A</kbd>+ </Button>+ <Button variant="ghost" onClick={() => onReply(last, 'forward')}>+ <Forward size={14} />+ Forward+ <kbd>F</kbd>+ </Button>+ </div>+ </div>+ </div>+ </div>+ {link && (+ <div className="link-status" aria-hidden="true">+ {link}+ </div>+ )}+ </div>+ )+}diff --git a/apps/desktop/src/renderer/src/RecipientField.tsx b/apps/desktop/src/renderer/src/RecipientField.tsxnew file mode 100644index 0000000..2c04bb2--- /dev/null+++ b/apps/desktop/src/renderer/src/RecipientField.tsx@@ -0,0 +1,199 @@+import { useId, useRef, useState, type ReactNode } from 'react'+import { X } from '@inlark/ui/icons'+import { parseAddresses, type Address } from '@inlark/core'+import { Avatar } from '@inlark/ui'++const valid = (email: string) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)+const same = (a: Address, b: Address) => a.email.toLowerCase() === b.email.toLowerCase()+const format = (a: Address) => (a.name ? a.name + ' <' + a.email + '>' : a.email)++/**+ * Recipients as removable chips with keyboard autocomplete. Text that has been typed but not yet+ * committed is still reported, so autosave and sending never lose an address.+ */+export function RecipientField({+ id,+ label,+ defaultValue,+ suggestions,+ disabled,+ autoFocus,+ placeholder,+ onChange,+ children,+}: {+ id: string+ label: string+ defaultValue: Address[]+ suggestions: Address[]+ disabled?: boolean+ autoFocus?: boolean+ placeholder?: string+ onChange: (addresses: Address[]) => void+ children?: ReactNode+}) {+ const [chips, setChips] = useState(defaultValue)+ const [text, setText] = useState('')+ const [open, setOpen] = useState(false)+ const [active, setActive] = useState(0)+ const input = useRef<HTMLInputElement>(null)+ const listId = useId()+ const set = (nextChips: Address[], nextText: string) => {+ setChips(nextChips)+ setText(nextText)+ onChange([...nextChips, ...parseAddresses(nextText)])+ }+ const add = (addresses: Address[]) => {+ const next = [...chips]+ for (const address of addresses) if (!next.some((c) => same(c, address))) next.push(address)+ set(next, '')+ setOpen(false)+ }+ const commit = () => {+ const parsed = parseAddresses(text)+ if (parsed.length) add(parsed)+ return parsed.length > 0+ }+ const query = text.trim().toLowerCase()+ const matches = query+ ? suggestions+ .filter(+ (a) =>+ !chips.some((c) => same(c, a)) &&+ ((a.name || '')+ .toLowerCase()+ .split(/\s+/)+ .some((word) => word.startsWith(query)) ||+ a.email.toLowerCase().startsWith(query) ||+ (query.length > 2 && (a.name + ' ' + a.email).toLowerCase().includes(query))),+ )+ .slice(0, 6)+ : []+ const showing = open && matches.length > 0+ const highlighted = Math.min(active, matches.length - 1)+ return (+ <div className="compose-field recipient-field" onClick={() => input.current?.focus()}>+ <label htmlFor={id}>{label}</label>+ <div className="recipient-chips">+ {chips.map((chip, i) => (+ <span+ key={chip.email + i}+ className={'recipient-chip' + (valid(chip.email) ? '' : ' invalid')}+ title={valid(chip.email) ? chip.email : chip.email + ' is not a valid address'}+ onDoubleClick={() => {+ if (disabled) return+ set(+ chips.filter((_, index) => index !== i),+ format(chip),+ )+ input.current?.focus()+ }}+ >+ {chip.name || chip.email}+ {!disabled && (+ <button+ type="button"+ tabIndex={-1}+ aria-label={'Remove ' + (chip.name || chip.email)}+ onClick={(event) => {+ event.stopPropagation()+ set(+ chips.filter((_, index) => index !== i),+ text,+ )+ }}+ >+ <X size={11} />+ </button>+ )}+ </span>+ ))}+ <input+ ref={input}+ id={id}+ disabled={disabled}+ autoFocus={autoFocus}+ autoComplete="off"+ spellCheck={false}+ placeholder={chips.length ? '' : placeholder}+ value={text}+ role="combobox"+ aria-expanded={showing}+ aria-controls={listId}+ aria-autocomplete="list"+ aria-activedescendant={showing ? listId + '-' + highlighted : undefined}+ onChange={(event) => {+ set(chips, event.target.value)+ setOpen(true)+ setActive(0)+ }}+ onBlur={() => {+ commit()+ setOpen(false)+ }}+ onPaste={(event) => {+ const pasted = event.clipboardData.getData('text')+ if (/[,;\n]/.test(pasted)) {+ event.preventDefault()+ add(parseAddresses(text + pasted.replace(/\n/g, ',')))+ }+ }}+ onKeyDown={(event) => {+ if (event.ctrlKey || event.metaKey || event.altKey) return+ if (showing && (event.key === 'ArrowDown' || event.key === 'ArrowUp')) {+ event.preventDefault()+ const step = event.key === 'ArrowDown' ? 1 : -1+ setActive((highlighted + step + matches.length) % matches.length)+ } else if ((event.key === 'Enter' || event.key === 'Tab') && showing) {+ event.preventDefault()+ add([matches[highlighted]])+ } else if (event.key === 'Enter' || event.key === ',' || event.key === ';') {+ if (text.trim()) {+ event.preventDefault()+ commit()+ }+ } else if (event.key === 'Tab' && text.trim()) {+ commit()+ } else if (event.key === 'Backspace' && !text && chips.length) {+ event.preventDefault()+ const last = chips[chips.length - 1]+ set(chips.slice(0, -1), format(last))+ } else if (event.key === 'Escape' && showing) {+ event.stopPropagation()+ event.preventDefault()+ setOpen(false)+ }+ }}+ />+ </div>+ {children}+ {showing && (+ <div className="recipient-suggestions" role="listbox" id={listId}>+ {matches.map((match, i) => (+ <button+ type="button"+ key={match.email}+ id={listId + '-' + i}+ role="option"+ aria-selected={i === highlighted}+ className={i === highlighted ? 'active' : ''}+ tabIndex={-1}+ onMouseDown={(event) => event.preventDefault()}+ onMouseMove={() => setActive(i)}+ onClick={() => {+ add([match])+ input.current?.focus()+ }}+ >+ <Avatar name={match.name || match.email} size={24} />+ <span>+ <strong>{match.name || match.email}</strong>+ {match.name && <small>{match.email}</small>}+ </span>+ </button>+ ))}+ </div>+ )}+ </div>+ )+}diff --git a/apps/desktop/src/renderer/src/SegmentedControl.tsx b/apps/desktop/src/renderer/src/SegmentedControl.tsxnew file mode 100644index 0000000..563b6d8--- /dev/null+++ b/apps/desktop/src/renderer/src/SegmentedControl.tsx@@ -0,0 +1,49 @@+import { useId } from 'react'++/**+ * A compact choice between a few options. Native radios give the expected keyboard behaviour:+ * Tab reaches the group once and the arrow keys move between options.+ */+export function SegmentedControl<Value extends string>({+ value,+ options,+ onChange,+ label,+ disabled,+ className,+}: {+ value: Value+ options: readonly { value: Value; label: string }[]+ onChange: (value: Value) => void+ label: string+ disabled?: boolean+ className?: string+}) {+ const name = useId()+ return (+ <div+ role="radiogroup"+ aria-label={label}+ className={'segmented' + (className ? ' ' + className : '')}+ data-disabled={disabled || undefined}+ >+ {options.map((option) => (+ <label+ key={option.value}+ className={'segmented-option' + (option.value === value ? ' chosen' : '')}+ >+ <input+ type="radio"+ className="sr-only"+ name={name}+ value={option.value}+ checked={option.value === value}+ disabled={disabled}+ onChange={() => onChange(option.value)}+ />+ {option.label}+ </label>+ ))}+ </div>+ )+}diff --git a/apps/desktop/src/renderer/src/SenderAvatar.tsx b/apps/desktop/src/renderer/src/SenderAvatar.tsxnew file mode 100644index 0000000..65ec222--- /dev/null+++ b/apps/desktop/src/renderer/src/SenderAvatar.tsx@@ -0,0 +1,28 @@+import { useQuery } from '@tanstack/react-query'+import { Avatar } from '@inlark/ui'+import { api } from './api'++export function SenderAvatar({+ name,+ email,+ color,+ size,+ remoteImages,+}: {+ name: string+ email?: string+ color?: string+ size: number+ remoteImages: boolean+}) {+ const address = email?.trim().toLowerCase() || ''+ const { data } = useQuery({+ queryKey: ['sender-avatar', address],+ queryFn: () => api.senderAvatar(address),+ enabled: !!address && remoteImages,+ staleTime: 15 * 60 * 1000,+ gcTime: 30 * 60 * 1000,+ retry: false,+ })+ return <Avatar name={name} color={color} size={size} image={remoteImages ? data : null} />+}diff --git a/apps/desktop/src/renderer/src/SendingStatus.tsx b/apps/desktop/src/renderer/src/SendingStatus.tsxnew file mode 100644index 0000000..b63f72b--- /dev/null+++ b/apps/desktop/src/renderer/src/SendingStatus.tsx@@ -0,0 +1,286 @@+import { useState } from 'react'+import { AlertCircle, Check, RefreshCw, Send } from '@inlark/ui/icons'+import { Button, Modal, Spinner } from '@inlark/ui'+import {+ friendlyError,+ type Account,+ type Address,+ type Draft,+ type SubmissionSummary,+} from '@inlark/core'+import { api } from './api'+import { queryClient, localSaveDraft } from './cache'+import { AccountMark } from './AccountMark'+import { shortDate } from './mail-date'++const who = (list: Address[]) =>+ list.map((a) => (a.name ? a.name + ' <' + a.email + '>' : a.email)).join(', ')++const copyState = {+ pending: 'Copy in Sent pending',+ uncertain: 'Copy in Sent not confirmed',+ failed: 'Copy in Sent failed',+} as const++/** What happened to a send, in words, and how much it needs the user. */+function describe(s: SubmissionSummary): { state: string; detail: string; tone: string } {+ if (s.state === 'uncertain')+ return {+ state: 'Delivery unconfirmed',+ detail:+ 'The server may have accepted this message. Check again before sending a replacement, or recipients may get it twice.',+ tone: 'attention',+ }+ if (s.state === 'partial')+ return {+ state: 'Partially sent' + (s.sentCopy ? ' · ' + copyState[s.sentCopy] : ''),+ detail: s.rejected?.length+ ? 'Not delivered to ' + who(s.rejected) + '. Everyone else received it.'+ : 'Some recipients refused the message. Everyone else received it.',+ tone: 'attention',+ }+ return {+ state: 'Sent · ' + copyState[s.sentCopy || 'pending'],+ detail:+ s.sentCopy === 'failed'+ ? 'Delivered, but its copy couldn’t be saved in Sent' + (s.error ? ': ' + s.error : '.')+ : s.sentCopy === 'uncertain'+ ? 'Delivered. Saving its copy in Sent may not have finished; retrying checks for it first.'+ : 'Delivered. Its copy in Sent hasn’t been saved yet.',+ tone: 'quiet',+ }+}++/** Sends that still need a decision: filing retries, refused recipients, unconfirmed delivery. */+export function SubmissionList({+ submissions,+ accounts,+ onOpenDraft,+ notify,+}: {+ submissions: SubmissionSummary[]+ accounts: Account[]+ onOpenDraft: (draft: Draft) => void+ notify: (message: string, tone?: 'error') => void+}) {+ const [working, setWorking] = useState<Record<string, string>>({})+ const [replace, setReplace] = useState<SubmissionSummary>()+ const [dismiss, setDismiss] = useState<SubmissionSummary>()+ if (!submissions.length) return null+ const run = async (s: SubmissionSummary, action: string, task: () => Promise<void>) => {+ setWorking((current) => ({ ...current, [s.draftId]: action }))+ try {+ await task()+ } catch (e) {+ notify(friendlyError(e), 'error')+ } finally {+ setWorking(({ [s.draftId]: _done, ...rest }) => rest)+ await Promise.all([+ queryClient.invalidateQueries({ queryKey: ['submissions'] }),+ queryClient.invalidateQueries({ queryKey: ['drafts'] }),+ ])+ }+ }+ const openDraft = async (draft: Draft) => {+ await localSaveDraft(draft)+ onOpenDraft(draft)+ }+ const actions = (s: SubmissionSummary) => {+ const busy = working[s.draftId]+ const label = (action: string, text: string) =>+ busy === action ? (+ <>+ <Spinner size={12} />+ {text}+ </>+ ) : (+ text+ )+ const retryFiling = s.sentCopy && (+ <Button+ size="small"+ disabled={!!busy}+ title="Saves the copy in Sent again. The message is not sent again."+ onClick={() =>+ void run(s, 'filing', async () => {+ const result = await api.retrySentCopy(s.draftId)+ notify(+ result.sentCopy === 'pending'+ ? 'The copy still couldn’t be saved in Sent. The message itself was delivered.'+ : 'Copy saved in Sent.',+ result.sentCopy === 'pending' ? 'error' : undefined,+ )+ })+ }+ >+ {label('filing', 'Retry filing')}+ </Button>+ )+ const dismissButton = (+ <Button+ size="small"+ variant="ghost"+ disabled={!!busy}+ onClick={() =>+ s.state === 'uncertain'+ ? setDismiss(s)+ : void run(s, 'dismiss', () => api.dismissSubmission(s.draftId))+ }+ >+ Dismiss+ </Button>+ )+ if (s.state === 'uncertain')+ return (+ <>+ <Button+ size="small"+ disabled={!!busy}+ onClick={() =>+ void run(s, 'check', async () => {+ const result = await api.reconcile(s.draftId)+ notify(+ result.status === 'sent' ? 'Delivery confirmed.' : result.message,+ result.status === 'uncertain' ? 'error' : undefined,+ )+ })+ }+ >+ {label('check', 'Check again')}+ </Button>+ <Button size="small" disabled={!!busy} onClick={() => setReplace(s)}>+ Send a replacement…+ </Button>+ {dismissButton}+ </>+ )+ if (s.state === 'partial')+ return (+ <>+ {!!s.rejected?.length && (+ <Button+ size="small"+ disabled={!!busy}+ onClick={() =>+ void run(s, 'recover', async () => {+ await openDraft(await api.recoverRejected(s.draftId))+ })+ }+ >+ {label('recover', 'Create draft to refused recipients')}+ </Button>+ )}+ {retryFiling}+ {dismissButton}+ </>+ )+ return (+ <>+ {retryFiling}+ {dismissButton}+ </>+ )+ }+ return (+ <section className="submissions" aria-labelledby="submissions-title">+ <h2 className="draft-section-label" id="submissions-title">+ Needs attention+ </h2>+ {submissions.map((s) => {+ const account = accounts.find((a) => a.id === s.accountId)+ const text = describe(s)+ return (+ <div className={'submission submission-' + text.tone} key={s.draftId}>+ <span className="submission-icon" aria-hidden="true">+ {s.state === 'uncertain' ? (+ <AlertCircle size={16} />+ ) : s.state === 'partial' ? (+ <Send size={16} />+ ) : s.sentCopy === 'failed' ? (+ <RefreshCw size={15} />+ ) : (+ <Check size={16} />+ )}+ </span>+ <div className="submission-text">+ <strong>{s.subject || '(No subject)'}</strong>+ <span className="submission-state">+ {text.state}+ {account && (+ <span className="submission-account">+ <AccountMark account={account} size={14} />+ {account.name}+ </span>+ )}+ </span>+ <span className="submission-detail">{text.detail}</span>+ <div className="submission-actions">{actions(s)}</div>+ </div>+ <time dateTime={s.at} title={new Date(s.at).toLocaleString()}>+ {shortDate(s.at)}+ </time>+ </div>+ )+ })}+ <Modal+ open={!!replace}+ onOpenChange={(open) => {+ if (!open) setReplace(undefined)+ }}+ title="Send a replacement?"+ description={+ 'Inlark couldn’t confirm whether “' ++ (replace?.subject || '(No subject)') ++ '” was delivered. If it was, recipients will receive it twice.'+ }+ >+ <p className="modal-body-text">+ The replacement opens as a new draft for you to review. Nothing is sent until you choose+ Send. The unconfirmed message stays listed here, so you can still check it.+ </p>+ <div className="modal-actions">+ <Button onClick={() => setReplace(undefined)}>Cancel</Button>+ <Button+ variant="primary"+ onClick={() => {+ const s = replace+ setReplace(undefined)+ if (s)+ void run(s, 'replace', async () => {+ await openDraft(await api.replaceUncertain(s.draftId))+ })+ }}+ >+ Create replacement draft+ </Button>+ </div>+ </Modal>+ <Modal+ open={!!dismiss}+ onOpenChange={(open) => {+ if (!open) setDismiss(undefined)+ }}+ title="Stop tracking this message?"+ description={+ 'Inlark will stop checking whether “' ++ (dismiss?.subject || '(No subject)') ++ '” was delivered and remove its unconfirmed draft from this device. Look in Sent first if you’re unsure.'+ }+ >+ <div className="modal-actions">+ <Button onClick={() => setDismiss(undefined)}>Keep tracking</Button>+ <Button+ variant="danger"+ onClick={() => {+ const s = dismiss+ setDismiss(undefined)+ if (s) void run(s, 'dismiss', () => api.dismissSubmission(s.draftId))+ }}+ >+ Dismiss+ </Button>+ </div>+ </Modal>+ </section>+ )+}diff --git a/apps/desktop/src/renderer/src/Settings.tsx b/apps/desktop/src/renderer/src/Settings.tsxnew file mode 100644index 0000000..15b26e5--- /dev/null+++ b/apps/desktop/src/renderer/src/Settings.tsx@@ -0,0 +1,657 @@+import { useEffect, useRef, useState } from 'react'+import appIcon from '../../../resources/icon.svg?no-inline'+import {+ Plus,+ ChevronDown,+ Mail,+ RefreshCw,+ Trash2,+ Copy,+ SlidersHorizontal,+ PenLine,+ Info,+ SettingsIcon,+ Folder,+ Send,+ SquarePen,+} from '@inlark/ui/icons'+import { Button, Dropdown, EmptyState, MenuItem, Modal, Select, Switch } from '@inlark/ui'+import {+ friendlyError,+ type Account,+ type AccountAppearance,+ type Settings as Preferences,+ type Bootstrap,+} from '@inlark/core'+import { api } from './api'+import { queryClient, purgeAccountCache } from './cache'+import { AccountAvatarPicker } from './AccountAvatarPicker'+import { SignatureSettings } from './SignatureSettings'+import { AccountSetup, type SetupMode } from './AccountSetup'+import { FolderMappingsDialog } from './FolderMappings'+import { IndexingMeter } from './IndexingMeter'++/** A miniature of the app window in one theme. */+function ThemePreview({ theme, className }: { theme: 'dark' | 'light'; className?: string }) {+ return (+ <span className={'mini-window mini-window-' + theme + (className ? ' ' + className : '')}>+ <span className="mini-sidebar">+ <span className="mini-nav active" />+ <span className="mini-nav" />+ <span className="mini-nav" />+ </span>+ <span className="mini-list">+ {[0, 1, 2].map((row) => (+ <span className="mini-row" key={row}>+ <span className="mini-avatar" />+ <span className="mini-line" />+ </span>+ ))}+ </span>+ </span>+ )+}++/** Edits the parts of an account that don't need signing in again. */+function AccountDetailsForm({+ account,+ onDone,+ notify,+}: {+ account: Account+ onDone: () => void+ notify: (message: string) => void+}) {+ const [name, setName] = useState(account.name)+ const [senderName, setSenderName] = useState(account.senderName || '')+ const [saving, setSaving] = useState(false)+ return (+ <form+ className="account-details-form"+ onSubmit={async (e) => {+ e.preventDefault()+ setSaving(true)+ try {+ await api.updateAccountDetails(account.id, { name, senderName })+ await Promise.all([+ queryClient.invalidateQueries({ queryKey: ['bootstrap'] }),+ // Identities carry the sending name, so the composer picks up the change.+ queryClient.invalidateQueries({ queryKey: ['identities', account.id] }),+ ])+ onDone()+ } catch (error) {+ notify(friendlyError(error))+ } finally {+ setSaving(false)+ }+ }}+ >+ <label className="form-field">+ Label+ <input+ autoFocus+ value={name}+ maxLength={100}+ placeholder="Personal"+ onChange={(e) => setName(e.target.value)}+ />+ <span className="field-hint">Only you see this.</span>+ </label>+ <label className="form-field">+ Your name+ <input+ value={senderName}+ maxLength={100}+ autoComplete="name"+ placeholder="Jane Doe"+ onChange={(e) => setSenderName(e.target.value)}+ />+ <span className="field-hint">+ Recipients see{' '}+ <span className="sender-preview">+ {(senderName.trim() || 'Your server’s name') + ' <' + account.email + '>'}+ </span>+ </span>+ </label>+ <div className="account-details-actions">+ <Button size="small" onClick={onDone}>+ Cancel+ </Button>+ <Button size="small" variant="primary" type="submit" disabled={saving}>+ Save+ </Button>+ </div>+ </form>+ )+}++const afterArchiveOptions: { value: NonNullable<Preferences['afterArchive']>; label: string }[] = [+ { value: 'next', label: 'Open the next conversation' },+ { value: 'previous', label: 'Open the previous conversation' },+ { value: 'list', label: 'Return to the list' },+]++export function SettingsPanel({+ open,+ onClose,+ bootstrap,+ onChange,+ notify,+ initialTab = 'general',+}: {+ open: boolean+ onClose: () => void+ bootstrap: Bootstrap+ onChange: (settings: Preferences) => void+ notify: (message: string) => void+ initialTab?: string+}) {+ // With nothing connected yet, opening Accounts can only mean adding one.+ const initialSetup = (): { mode: SetupMode } | undefined =>+ initialTab === 'accounts' && !bootstrap.accounts.length ? { mode: 'add' } : undefined+ const [tab, setTab] = useState(initialTab),+ [setup, setSetup] = useState<{ mode: SetupMode; account?: Account } | undefined>(initialSetup),+ [remove, setRemove] = useState<Account>(),+ [editing, setEditing] = useState<string>(),+ [folders, setFolders] = useState<Account>()+ const modalRef = useRef<HTMLDivElement>(null)+ /** Leaves setup and puts focus back where the account list starts. */+ const closeSetup = () => {+ setSetup(undefined)+ requestAnimationFrame(() => document.getElementById('settings-add-account')?.focus())+ }+ useEffect(() => {+ if (open) {+ setTab(initialTab)+ setSetup(initialSetup())+ }+ }, [open, initialTab])+ const updateAppearance = (account: Account, appearance: AccountAppearance) => {+ // Show the change everywhere at once, and put it back if it cannot be saved.+ queryClient.setQueryData<Bootstrap>(+ ['bootstrap'],+ (old) =>+ old && {+ ...old,+ accounts: old.accounts.map((a) => (a.id === account.id ? { ...a, ...appearance } : a)),+ },+ )+ api.updateAccount(account.id, appearance).catch((e) => {+ notify(friendlyError(e))+ void queryClient.invalidateQueries({ queryKey: ['bootstrap'] })+ })+ }+ const update = async (patch: Partial<Preferences>) => {+ try {+ const next = await api.settings({ ...bootstrap.settings, ...patch })+ onChange(next)+ return true+ } catch (e) {+ notify(friendlyError(e))+ return false+ }+ }+ return (+ <>+ <Modal+ open={open}+ onOpenChange={(value) => {+ if (!value) onClose()+ }}+ title="Settings"+ className="settings-modal"+ popupRef={modalRef}+ >+ <div className="settings-layout">+ <nav className="settings-nav" aria-label="Settings sections">+ {[+ ['general', 'General', SlidersHorizontal],+ ['accounts', 'Accounts', Mail],+ ['signatures', 'Signatures', PenLine],+ ['about', 'About', Info],+ ].map(([id, name, Icon]) => {+ const Component = Icon as typeof Mail+ return (+ <button+ key={String(id)}+ aria-current={tab === id ? 'page' : undefined}+ className={tab === id ? 'active' : ''}+ onClick={() => {+ setTab(String(id))+ setSetup(undefined)+ }}+ >+ <Component size={15} />+ {String(name)}+ </button>+ )+ })}+ </nav>+ <div className="settings-content">+ {tab === 'general' && (+ <>+ <h3>General</h3>+ <div className="setting-section">+ <h4>Appearance</h4>+ <div className="theme-options">+ {(+ [+ ['dark', 'Dark'],+ ['light', 'Light'],+ ['system', 'System'],+ ] as const+ ).map(([id, label]) => (+ <button+ key={id}+ className={+ 'theme-option' + (bootstrap.settings.theme === id ? ' chosen' : '')+ }+ aria-pressed={bootstrap.settings.theme === id}+ onClick={() => void update({ theme: id })}+ >+ <span className="theme-preview" aria-hidden="true">+ {id === 'system' ? (+ <>+ <ThemePreview theme="dark" />+ <ThemePreview theme="light" className="theme-split" />+ </>+ ) : (+ <ThemePreview theme={id} />+ )}+ </span>+ <span className="theme-option-label">+ <span className="theme-radio" />+ {label}+ </span>+ </button>+ ))}+ </div>+ </div>+ <div className="setting-section">+ <h4>Reading</h4>+ <div className="setting-row">+ <div>+ <strong>After archiving or deleting</strong>+ <p>Where to go when a conversation leaves the list you’re reading.</p>+ </div>+ <Select+ aria-label="After archiving or deleting"+ className="setting-select"+ value={bootstrap.settings.afterArchive || 'next'}+ options={afterArchiveOptions}+ onValueChange={(afterArchive) => void update({ afterArchive })}+ />+ </div>+ </div>+ <div className="setting-section">+ <h4>Privacy</h4>+ <div className="setting-row">+ <div>+ <strong>Load remote images</strong>+ <p>Display images in incoming email and sender pictures automatically.</p>+ </div>+ <Switch+ aria-label="Load remote images"+ checked={bootstrap.settings.remoteImages}+ onCheckedChange={(remoteImages) => void update({ remoteImages })}+ />+ </div>+ <p className="setting-footnote">+ Email images are requested directly, so senders may know when you read a+ message. Gravatar receives a hash of each sender’s address; sender websites or+ their icon hosts receive icon requests. If those fail, Twenty Icons receives the+ sender’s root domain. DuckDuckGo receives it only if Twenty has no icon.+ </p>+ </div>+ <div className="setting-section">+ <h4>Desktop</h4>+ <div className="setting-row">+ <div>+ <strong>New mail notifications</strong>+ <p>Get notified when new conversations arrive.</p>+ </div>+ <Switch+ aria-label="New mail notifications"+ checked={bootstrap.settings.notifications}+ onCheckedChange={(notifications) => void update({ notifications })}+ />+ </div>+ <div className="setting-row">+ <div>+ <strong>Keep running in the tray</strong>+ <p>Keep checking for new mail after the window is closed.</p>+ </div>+ <Switch+ aria-label="Keep running in the tray"+ checked={bootstrap.settings.closeToTray}+ onCheckedChange={(closeToTray) => void update({ closeToTray })}+ />+ </div>+ </div>+ <div className="setting-section">+ <h4>Default sending account</h4>+ <Select+ aria-label="Default sending account"+ value={bootstrap.settings.defaultAccountId || bootstrap.accounts[0]?.id || ''}+ options={bootstrap.accounts.map((a) => ({+ value: a.id,+ label: a.name + ' · ' + a.email,+ }))}+ onValueChange={(defaultAccountId) => void update({ defaultAccountId })}+ />+ </div>+ </>+ )}+ {tab === 'accounts' &&+ (setup ? (+ <AccountSetup+ key={setup.mode + ':' + (setup.account?.id || 'new')}+ bootstrap={bootstrap}+ existing={setup.account}+ mode={setup.mode}+ onBack={closeSetup}+ onDone={(message) => {+ closeSetup()+ notify(message)+ }}+ />+ ) : (+ <>+ <div className="settings-section-heading">+ <div>+ <h3>Accounts</h3>+ </div>+ {!!bootstrap.accounts.length && (+ <Button+ size="small"+ id="settings-add-account"+ onClick={() => setSetup({ mode: 'add' })}+ >+ <Plus size={13} />+ Add account+ </Button>+ )}+ </div>+ <div className="settings-accounts">+ {bootstrap.accounts.map((account) => {+ const protocol = account.protocol || 'jmap'+ const needsSignIn =+ (account.status !== 'connected' && account.status !== 'connecting') ||+ !!account.outgoingError+ return (+ <div className="settings-account-entry" key={account.id}>+ <div className="settings-account">+ <AccountAvatarPicker+ name={account.name}+ email={account.email}+ value={{ seed: account.seed, image: account.image }}+ portalContainer={modalRef}+ onChange={(appearance) => updateAppearance(account, appearance)}+ onError={(e) => notify(friendlyError(e))}+ />+ <div className="settings-account-text">+ <strong>+ {account.name}+ <span+ className="protocol-tag"+ title={+ protocol === 'imap'+ ? 'Connected with IMAP and SMTP'+ : 'Connected with JMAP'+ }+ >+ {protocol.toUpperCase()}+ </span>+ </strong>+ <span className="settings-account-email">{account.email}</span>+ <small+ className={+ account.status === 'connected' ? 'connected' : 'connection-error'+ }+ >+ <span className="connection-dot" />+ {account.status === 'connected'+ ? account.outgoingError+ ? 'Receiving mail'+ : account.sessionOnly+ ? 'Connected · session only'+ : 'Connected'+ : account.status === 'connecting'+ ? 'Connecting…'+ : account.error || 'Disconnected'}+ </small>+ {account.outgoingError && (+ <small className="connection-error outgoing-error">+ <Send size={11} />+ <span>Sending unavailable: {account.outgoingError}</span>+ </small>+ )}+ {account.indexing && !account.indexing.complete && (+ <small className="account-indexing">+ <IndexingMeter indexing={account.indexing} />+ </small>+ )}+ </div>+ <div className="account-actions">+ {needsSignIn && (+ <Button+ size="small"+ onClick={() => setSetup({ mode: 'signIn', account })}+ >+ Sign in again+ </Button>+ )}+ <Dropdown+ container={modalRef}+ className="settings-account-menu"+ trigger={+ <Button+ size="small"+ className="account-manage-trigger"+ aria-label={'Manage ' + account.name + ' account'}+ >+ Manage+ <ChevronDown size={13} />+ </Button>+ }+ >+ <MenuItem+ onClick={() =>+ setEditing(editing === account.id ? undefined : account.id)+ }+ >+ <SquarePen size={14} />+ Edit label and name+ </MenuItem>+ <MenuItem onClick={() => setSetup({ mode: 'edit', account })}>+ <SettingsIcon size={14} />+ Edit connection…+ </MenuItem>+ {protocol === 'imap' && (+ <MenuItem onClick={() => setFolders(account)}>+ <Folder size={14} />+ Folders…+ </MenuItem>+ )}+ <MenuItem+ onClick={() =>+ void api+ .reconnect(account.connectionId)+ .then(() => notify('Reconnected.'))+ .catch((e) => notify(friendlyError(e)))+ }+ >+ <RefreshCw size={14} />+ Reconnect+ </MenuItem>+ <div className="account-menu-divider" />+ <MenuItem danger onClick={() => setRemove(account)}>+ <Trash2 size={14} />+ Remove account…+ </MenuItem>+ </Dropdown>+ </div>+ </div>+ {editing === account.id && (+ <AccountDetailsForm+ account={account}+ onDone={() => setEditing(undefined)}+ notify={notify}+ />+ )}+ </div>+ )+ })}+ </div>+ {!bootstrap.accounts.length && (+ <div className="no-accounts">+ <EmptyState+ icon={Mail}+ title="No accounts yet"+ description="Connect a JMAP or IMAP account to start reading and sending mail."+ >+ <Button onClick={() => setSetup({ mode: 'add' })} variant="primary">+ <Plus size={13} />+ Connect an account+ </Button>+ </EmptyState>+ </div>+ )}+ </>+ ))}+ {tab === 'signatures' && (+ <>+ <h3>Signatures</h3>+ {bootstrap.accounts.length ? (+ <>+ <p className="settings-lead">+ Added to new messages, replies and forwards. Changes save as you type.+ </p>+ <SignatureSettings+ accounts={bootstrap.accounts}+ signatures={bootstrap.settings.signatures}+ onSave={(signatures) => update({ signatures })}+ />+ </>+ ) : (+ <div className="no-accounts">+ <EmptyState+ icon={PenLine}+ title="No signatures yet"+ description="Each account has its own signature. Connect an account to write one."+ >+ <Button+ onClick={() => {+ setTab('accounts')+ setSetup({ mode: 'add' })+ }}+ variant="primary"+ >+ <Plus size={13} />+ Connect an account+ </Button>+ </EmptyState>+ </div>+ )}+ </>+ )}+ {tab === 'about' && (+ <>+ <div className="about-hero">+ <img className="about-mark" src={appIcon} alt="" width={52} height={52} />+ <div>+ <h3>Inlark</h3>+ <p>A desktop email client for JMAP and IMAP servers.</p>+ </div>+ <span className="about-version">Version {bootstrap.version}</span>+ </div>+ <div className="setting-section">+ <h4>Privacy</h4>+ <div className="setting-row">+ <div>+ <strong>Direct connection</strong>+ <p>+ Inlark connects straight to your mail server. No account or cloud service in+ between.+ </p>+ </div>+ </div>+ <div className="setting-row">+ <div>+ <strong>No telemetry</strong>+ <p>Inlark collects no usage data or analytics.</p>+ </div>+ </div>+ </div>+ <div className="setting-section">+ <h4>Troubleshooting</h4>+ <div className="setting-row">+ <div>+ <strong>Diagnostics</strong>+ <p>+ Includes the app version and connection states. Excludes credentials,+ addresses, and message content.+ </p>+ </div>+ <Button+ onClick={async () => {+ try {+ const diagnostics = await api.diagnostics()+ await navigator.clipboard.writeText(diagnostics)+ notify('Redacted diagnostics copied.')+ } catch (e) {+ notify(friendlyError(e))+ }+ }}+ >+ <Copy size={14} />+ Copy diagnostics+ </Button>+ </div>+ </div>+ </>+ )}+ </div>+ </div>+ </Modal>+ <FolderMappingsDialog+ key={folders?.id || 'folders-closed'}+ account={folders}+ onClose={() => setFolders(undefined)}+ notify={notify}+ />+ <Modal+ open={!!remove}+ onOpenChange={(value) => {+ if (!value) setRemove(undefined)+ }}+ title="Remove this account?"+ description="This removes the connection, local cached mail, and local drafts for this connection. Mail on the server stays where it is."+ >+ <div className="modal-actions">+ <Button onClick={() => setRemove(undefined)}>Keep account</Button>+ <Button+ variant="danger"+ onClick={async () => {+ if (!remove) return+ try {+ const ids = bootstrap.accounts+ .filter((a) => a.connectionId === remove.connectionId)+ .map((a) => a.id)+ await api.disconnect(remove.connectionId)+ await purgeAccountCache(ids)+ await queryClient.invalidateQueries({ queryKey: ['bootstrap'] })+ setRemove(undefined)+ notify('Account removed from this device.')+ } catch (e) {+ notify(friendlyError(e))+ }+ }}+ >+ Remove account+ </Button>+ </div>+ </Modal>+ </>+ )+}diff --git a/apps/desktop/src/renderer/src/Sidebar.tsx b/apps/desktop/src/renderer/src/Sidebar.tsxnew file mode 100644index 0000000..b046875--- /dev/null+++ b/apps/desktop/src/renderer/src/Sidebar.tsx@@ -0,0 +1,375 @@+import { useEffect, useState } from 'react'+import {+ Archive,+ ChevronDown,+ Folder,+ Inbox,+ MoreHorizontal,+ PanelLeftClose,+ PanelLeftOpen,+ Plus,+ Search,+ Send,+ SquarePen,+ Settings as SettingsIcon,+ ShieldX,+ Star,+ Trash2,+ FileText,+ WifiOff,+} from '@inlark/ui/icons'+import { Button, Dropdown, IconButton, MenuItem, Spinner } from '@inlark/ui'+import type { Account, Mailbox, View } from '@inlark/core'+import appIcon from '../../../resources/icon-mark.svg?no-inline'+import { AccountMark } from './AccountMark'++export const views: { id: View; title: string; icon: typeof Inbox; key?: string }[] = [+ { id: 'inbox', title: 'Inbox', icon: Inbox, key: 'G I' },+ { id: 'starred', title: 'Starred', icon: Star, key: 'G S' },+ { id: 'sent', title: 'Sent', icon: Send, key: 'G T' },+ { id: 'drafts', title: 'Drafts', icon: FileText, key: 'G D' },+ { id: 'archive', title: 'Archive', icon: Archive, key: 'G A' },+ { id: 'junk', title: 'Spam', icon: ShieldX },+ { id: 'trash', title: 'Trash', icon: Trash2 },+]+const statusLabel: Record<Account['status'], string> = {+ connecting: 'connecting',+ connected: 'connected',+ offline: 'offline',+ authentication: 'needs sign-in',+ error: 'unavailable',+}+export function Sidebar({+ accounts,+ boxesByAccount,+ route,+ view,+ draftCount,+ hasServerDrafts,+ sendingIssues,+ unreadCount,+ accountUnread,+ collapsed,+ onToggleCollapsed,+ onSearch,+ onCompose,+ onNavigate,+ onSettings,+ onFolderAction,+}: {+ accounts: Account[]+ boxesByAccount: Record<string, Mailbox[]>+ route: { account?: string; folder?: string; q?: string }+ view: View+ draftCount: number+ hasServerDrafts: boolean+ /** Sends that still need a decision, shown in Drafts. */+ sendingIssues: number+ unreadCount: number+ accountUnread: Record<string, number>+ collapsed: boolean+ onToggleCollapsed: () => void+ onSearch: () => void+ onCompose: () => void+ onNavigate: (next: { view: View; account?: string; folder?: string }) => void+ onSettings: (tab: 'accounts' | 'general') => void+ onFolderAction: (+ operation: 'create' | 'rename' | 'delete',+ accountId: string,+ folder?: Mailbox,+ ) => void+}) {+ const go = onNavigate+ // Transient connecting states already show a spinner on the account row.+ const unavailable = accounts.filter((a) => a.status !== 'connected' && a.status !== 'connecting')+ const statusText =+ unavailable.length === 1+ ? unavailable[0].name + ' ' + statusLabel[unavailable[0].status]+ : unavailable.length + ' accounts unavailable'+ const sendingText =+ sendingIssues === 1+ ? '1 sent message needs attention'+ : sendingIssues + ' sent messages need attention'+ const [accountsExpanded, setAccountsExpanded] = useState(+ () => localStorage.getItem('sidebar-accounts-expanded') !== 'false',+ )+ const [accountExpanded, setAccountExpanded] = useState<Record<string, boolean>>(() => {+ try {+ const saved = JSON.parse(localStorage.getItem('sidebar-account-expanded') || '{}')+ return saved && typeof saved === 'object' && !Array.isArray(saved) ? saved : {}+ } catch {+ return {}+ }+ })+ useEffect(() => {+ localStorage.setItem('sidebar-accounts-expanded', String(accountsExpanded))+ }, [accountsExpanded])+ useEffect(() => {+ localStorage.setItem('sidebar-account-expanded', JSON.stringify(accountExpanded))+ }, [accountExpanded])+ return (+ <aside className="sidebar">+ <div className="sidebar-brand">+ <img className="brand-mark" src={appIcon} alt="" width={24} height={24} />+ {!collapsed && <strong>Inlark</strong>}+ </div>+ <div className="sidebar-tools">+ <IconButton label="Search and commands" shortcut="Ctrl K" onClick={onSearch}>+ <Search size={14} />+ </IconButton>+ <IconButton className="sidebar-compose" label="Compose" shortcut="C" onClick={onCompose}>+ <SquarePen size={16} />+ </IconButton>+ </div>+ <div className="sidebar-scroll">+ <nav className="main-nav" aria-label="Mail views">+ {views+ .filter(+ (v) =>+ v.id !== 'drafts' ||+ draftCount > 0 ||+ hasServerDrafts ||+ sendingIssues > 0 ||+ view === 'drafts',+ )+ .map((v) => (+ <button+ key={v.id}+ title={+ v.title ++ (v.id === 'inbox' ? ' · ' + unreadCount + ' unread' : '') ++ (v.key ? ' · ' + v.key : '')+ }+ aria-current={+ view === v.id && !route.account && !route.folder && !route.q ? 'page' : undefined+ }+ className={+ 'nav-item ' ++ (v.id === 'archive' ? 'nav-secondary-start ' : '') ++ (view === v.id && !route.account && !route.folder && !route.q ? 'active' : '')+ }+ onClick={() => go({ view: v.id })}+ >+ <v.icon size={16} strokeWidth={1.65} />+ {!collapsed && (+ <>+ <span>{v.title}</span>+ {v.id === 'drafts' && draftCount > 0 && <small>{draftCount}</small>}+ {v.id === 'inbox' && unreadCount > 0 && (+ <small>{unreadCount.toLocaleString()}</small>+ )}+ </>+ )}+ </button>+ ))}+ </nav>+ {accounts.length > 0 && (+ <div className="sidebar-section-label">+ {!collapsed && (+ <button+ className="sidebar-section-toggle"+ aria-expanded={accountsExpanded}+ onClick={() => setAccountsExpanded((open) => !open)}+ >+ <span>Accounts</span>+ <ChevronDown size={12} className={accountsExpanded ? '' : 'closed'} />+ </button>+ )}+ </div>+ )}+ {accounts.length > 0 && (accountsExpanded || collapsed) && (+ <nav className="account-nav" id="sidebar-accounts" aria-label="Accounts">+ {accounts.map((a) => {+ const expanded = accountExpanded[a.id] !== false+ return (+ <div className="account-tree" key={a.id}>+ <button+ className={+ 'nav-item account-toggle ' + (route.account === a.id ? 'account-current' : '')+ }+ title={+ a.email ++ ' · ' ++ (a.status === 'connected' ? (accountUnread[a.id] || 0) + ' unread' : a.status)+ }+ aria-expanded={collapsed ? undefined : expanded}+ aria-label={collapsed ? a.name + ' inbox' : undefined}+ onClick={() => {+ if (collapsed) go({ view: 'inbox', account: a.id })+ else setAccountExpanded((state) => ({ ...state, [a.id]: !expanded }))+ }}+ >+ <AccountMark+ account={a}+ size={18}+ className={a.status !== 'connected' ? 'disconnected' : undefined}+ />+ {!collapsed && (+ <>+ <span>{a.name}</span>+ {a.status === 'connecting' ? (+ <Spinner size={11} />+ ) : a.status !== 'connected' ? (+ <WifiOff+ size={12}+ className="account-offline"+ aria-label="Not connected"+ />+ ) : accountUnread[a.id] ? (+ <small>{accountUnread[a.id].toLocaleString()}</small>+ ) : null}+ <ChevronDown+ size={12}+ className={'account-chevron ' + (expanded ? '' : 'closed')}+ />+ </>+ )}+ </button>+ {!collapsed && expanded && (+ <div+ className="account-children"+ id={'account-folders-' + a.id}+ role="group"+ aria-label={a.name + ' folders'}+ >+ {views+ .filter((v) => v.id !== 'drafts')+ .map((v) => (+ <button+ key={v.id}+ className={+ 'nav-item ' ++ (route.account === a.id && !route.folder && !route.q && view === v.id+ ? 'active'+ : '')+ }+ aria-current={+ route.account === a.id && !route.folder && !route.q && view === v.id+ ? 'page'+ : undefined+ }+ onClick={() => go({ view: v.id, account: a.id })}+ >+ <v.icon size={15} strokeWidth={1.65} />+ <span>{v.title}</span>+ {v.id === 'inbox' && accountUnread[a.id] > 0 && (+ <small>{accountUnread[a.id].toLocaleString()}</small>+ )}+ </button>+ ))}+ {(boxesByAccount[a.id] || [])+ .filter((b) => !b.role)+ .map((b) => (+ <div className="folder-nav-row" key={b.id}>+ <button+ className={+ 'nav-item ' ++ (route.folder === b.id && route.account === a.id ? 'active' : '')+ }+ aria-current={+ route.folder === b.id && route.account === a.id ? 'page' : undefined+ }+ onClick={() => go({ view: 'all', account: a.id, folder: b.id })}+ >+ <Folder size={14} />+ <span>{b.name}</span>+ {b.unreadEmails > 0 && (+ <small>{b.unreadEmails.toLocaleString()}</small>+ )}+ </button>+ <Dropdown+ trigger={+ <Button variant="ghost" size="icon" aria-label={'Manage ' + b.name}>+ <MoreHorizontal size={13} />+ </Button>+ }+ >+ <MenuItem+ disabled={!b.rights.mayRename}+ onClick={() => onFolderAction('rename', a.id, b)}+ >+ Rename folder+ </MenuItem>+ <MenuItem+ danger+ disabled={!b.rights.mayDelete}+ onClick={() => onFolderAction('delete', a.id, b)}+ >+ Delete folder+ </MenuItem>+ </Dropdown>+ </div>+ ))}+ <button+ className="nav-item account-create-folder"+ onClick={() => onFolderAction('create', a.id)}+ >+ <Plus size={14} />+ <span>New folder</span>+ </button>+ </div>+ )}+ </div>+ )+ })}+ </nav>+ )}+ </div>+ <div className="sidebar-bottom">+ {sendingIssues > 0 && (+ <button+ className={'nav-item sidebar-sending' + (view === 'drafts' ? ' active' : '')}+ title={sendingText + ' · review in Drafts'}+ aria-label={sendingText + '. Review in Drafts.'}+ onClick={() => go({ view: 'drafts' })}+ >+ <Send size={15} strokeWidth={1.65} />+ {!collapsed && (+ <>+ <span>Send status</span>+ <small>{sendingIssues}</small>+ </>+ )}+ </button>+ )}+ {unavailable.length > 0 && (+ <button+ className="nav-item sidebar-status"+ title={unavailable.map((a) => a.email + ' · ' + statusLabel[a.status]).join('\n')}+ aria-label={statusText}+ onClick={() => onSettings('accounts')}+ >+ <WifiOff size={15} strokeWidth={1.65} />+ {!collapsed && <span>{statusText}</span>}+ </button>+ )}+ <div className="sidebar-footer">+ {collapsed && (+ <IconButton label="Expand sidebar" shortcut="[" onClick={onToggleCollapsed}>+ <PanelLeftOpen size={15} />+ </IconButton>+ )}+ <button+ className="nav-item"+ title="Settings · Ctrl ,"+ aria-label="Settings"+ onClick={() => onSettings('general')}+ >+ <SettingsIcon size={16} strokeWidth={1.65} />+ {!collapsed && (+ <>+ <span>Settings</span>+ <kbd>Ctrl ,</kbd>+ </>+ )}+ </button>+ {!collapsed && (+ <IconButton label="Collapse sidebar" shortcut="[" onClick={onToggleCollapsed}>+ <PanelLeftClose size={15} />+ </IconButton>+ )}+ </div>+ </div>+ </aside>+ )+}diff --git a/apps/desktop/src/renderer/src/SignatureSettings.tsx b/apps/desktop/src/renderer/src/SignatureSettings.tsxnew file mode 100644index 0000000..985f1ee--- /dev/null+++ b/apps/desktop/src/renderer/src/SignatureSettings.tsx@@ -0,0 +1,119 @@+import { useEffect, useRef, useState } from 'react'+import { useQueries } from '@tanstack/react-query'+import { Check } from '@inlark/ui/icons'+import { Spinner } from '@inlark/ui'+import { identityKey, type Account, type Settings as Preferences } from '@inlark/core'+import { api } from './api'+import { AccountMark } from './AccountMark'++type Signatures = Preferences['signatures']++const same = (a: Signatures, b: Signatures) =>+ Object.keys({ ...a, ...b }).every((key) => (a[key] ?? '') === (b[key] ?? ''))++/** Every account's signatures on one page, saved automatically as they're typed. */+export function SignatureSettings({+ accounts,+ signatures,+ onSave,+}: {+ accounts: Account[]+ signatures: Signatures+ onSave: (signatures: Signatures) => Promise<boolean>+}) {+ const identities = useQueries({+ queries: accounts.map((account) => ({+ queryKey: ['identities', account.id],+ queryFn: () => api.identities(account.id),+ enabled: account.status === 'connected',+ })),+ })+ const [values, setValues] = useState(signatures)+ const [savedKey, setSavedKey] = useState<string>()+ const latest = useRef(values)+ const saved = useRef(signatures)+ const edited = useRef<string>(undefined)+ latest.current = values+ const save = async (next: Signatures) => {+ if (same(next, saved.current)) return+ if (await onSave(next)) {+ saved.current = next+ setSavedKey(edited.current)+ }+ }+ // Save shortly after typing stops, and flush anything pending when the page closes.+ useEffect(() => {+ const timer = setTimeout(() => void save(values), 700)+ return () => clearTimeout(timer)+ }, [values])+ useEffect(() => () => void save(latest.current), [])+ useEffect(() => {+ if (!savedKey) return+ const timer = setTimeout(() => setSavedKey(undefined), 1800)+ return () => clearTimeout(timer)+ }, [savedKey])++ return (+ <div className="signature-accounts">+ {accounts.map((account, index) => {+ const query = identities[index]+ return (+ <section className="signature-account" key={account.id}>+ <header>+ <AccountMark account={account} size={20} />+ <strong>{account.name}</strong>+ <span>{account.email}</span>+ </header>+ {account.status !== 'connected' ? (+ <p className="signature-note">Reconnect this account to edit its signatures.</p>+ ) : query.isPending ? (+ <p className="signature-note">+ <Spinner size={12} /> Loading addresses…+ </p>+ ) : query.isError ? (+ <p className="signature-note">Couldn’t load this account’s addresses.</p>+ ) : (+ query.data.map((identity) => {+ const key = identityKey(account.id, identity.id)+ const id = 'signature-' + key+ return (+ <div className="signature-identity" key={key}>+ {/* The address only needs naming when it isn't obvious from the header. */}+ {(query.data.length > 1 || identity.email !== account.email) && (+ <label htmlFor={id}>+ {identity.name ? identity.name + ' · ' : ''}+ {identity.email}+ </label>+ )}+ <textarea+ id={id}+ rows={3}+ aria-label={query.data.length > 1 ? undefined : account.name + ' signature'}+ value={values[key] ?? identity.textSignature ?? ''}+ placeholder="No signature"+ onChange={(e) => {+ edited.current = key+ setValues((current) => ({ ...current, [key]: e.target.value }))+ }}+ onBlur={() => void save(latest.current)}+ />+ <span+ className={'signature-saved' + (savedKey === key ? ' visible' : '')}+ aria-live="polite"+ >+ {savedKey === key && (+ <>+ <Check size={11} /> Saved+ </>+ )}+ </span>+ </div>+ )+ })+ )}+ </section>+ )+ })}+ </div>+ )+}diff --git a/apps/desktop/src/renderer/src/account-image.ts b/apps/desktop/src/renderer/src/account-image.tsnew file mode 100644index 0000000..6098052--- /dev/null+++ b/apps/desktop/src/renderer/src/account-image.ts@@ -0,0 +1,35 @@+/** Twice the largest avatar, so pictures stay sharp on high-density screens. */+const SIZE = 128+const MAX_BYTES = 25 * 1024 * 1024+export const accountImageTypes = 'image/png,image/jpeg,image/webp,image/gif,image/avif'++/** Crops a chosen picture to its centre square and shrinks it, so it can be kept with the account. */+export async function accountImage(file: Blob): Promise<string> {+ if (!accountImageTypes.split(',').includes(file.type))+ throw new Error('Choose a PNG, JPEG, WebP, GIF or AVIF picture.')+ if (file.size > MAX_BYTES) throw new Error('This picture is too large. Choose one under 25 MB.')+ let bitmap: ImageBitmap+ try {+ bitmap = await createImageBitmap(file)+ } catch {+ throw new Error('This picture could not be read. Try a different file.')+ }+ const side = Math.min(bitmap.width, bitmap.height)+ const canvas = document.createElement('canvas')+ canvas.width = canvas.height = Math.min(SIZE, side)+ const context = canvas.getContext('2d')!+ context.imageSmoothingQuality = 'high'+ context.drawImage(+ bitmap,+ (bitmap.width - side) / 2,+ (bitmap.height - side) / 2,+ side,+ side,+ 0,+ 0,+ canvas.width,+ canvas.height,+ )+ bitmap.close()+ return canvas.toDataURL('image/webp', 0.92)+}diff --git a/apps/desktop/src/renderer/src/account-limits.ts b/apps/desktop/src/renderer/src/account-limits.tsnew file mode 100644index 0000000..9fa00bb--- /dev/null+++ b/apps/desktop/src/renderer/src/account-limits.ts@@ -0,0 +1,30 @@+import type { Account, MailAction, MutationTarget } from '@inlark/core'++/** Actions that move messages between folders, which `limits.move` rules out. */+const moving: readonly MailAction[] = ['archive', 'trash', 'spam', 'notSpam', 'restore', 'move']++/** Why this account's server can't perform the action safely, if it can't. */+export function actionLimit(account: Account | undefined, action: MailAction): string | undefined {+ if (!account?.limits) return undefined+ if (action === 'destroy') return account.limits.destroy+ return moving.includes(action) ? account.limits.move : undefined+}++/**+ * The first account among the targets that can't perform the action, with its explanation.+ * One limited account blocks the whole action, so a mixed selection never half-completes.+ */+export function targetLimit(+ accounts: Account[],+ accountIds: Iterable<string>,+ action: MailAction,+): { account: Account; reason: string } | undefined {+ for (const id of new Set(accountIds)) {+ const account = accounts.find((a) => a.id === id)+ const reason = actionLimit(account, action)+ if (account && reason) return { account, reason }+ }+ return undefined+}++export const targetAccounts = (targets: MutationTarget[]) => targets.map((t) => t.accountId)diff --git a/apps/desktop/src/renderer/src/api.ts b/apps/desktop/src/renderer/src/api.tsnew file mode 100644index 0000000..d233b22--- /dev/null+++ b/apps/desktop/src/renderer/src/api.ts@@ -0,0 +1,21 @@+import type { DesktopMailAPI } from '@inlark/core'+import { demoAPI } from './demo'+declare global {+ interface Window {+ mail?: DesktopMailAPI+ }+}+export const isDemo =+ new URLSearchParams(location.search).has('demo') ||+ (!window.mail && location.protocol !== 'inlark:')+const unavailable = new Proxy({} as DesktopMailAPI, {+ get: (_target, method) =>+ method === 'onEvent'+ ? () => () => {}+ : async () => {+ throw new Error(+ 'The desktop connection could not start. Restart Inlark or reinstall the application.',+ )+ },+})+export const api: DesktopMailAPI = isDemo ? demoAPI : window.mail || unavailablediff --git a/apps/desktop/src/renderer/src/cache.ts b/apps/desktop/src/renderer/src/cache.tsnew file mode 100644index 0000000..2e39870--- /dev/null+++ b/apps/desktop/src/renderer/src/cache.ts@@ -0,0 +1,103 @@+import { openDB } from 'idb'+import { QueryClient, dehydrate, hydrate } from '@tanstack/react-query'+import type { Draft } from '@inlark/core'+import { isDemo } from './api'++const database = openDB(+ 'inlark-' ++ (isDemo+ ? new URLSearchParams(location.search).has('stress')+ ? 'demo-stress'+ : 'demo'+ : 'mail'),+ 1,+ {+ upgrade(db) {+ db.createObjectStore('cache')+ db.createObjectStore('drafts', { keyPath: 'id' })+ },+ },+)+export const queryClient = new QueryClient({+ defaultOptions: {+ queries: {+ staleTime: 30_000,+ gcTime: 30 * 60_000,+ retry: 1,+ networkMode: 'always',+ refetchOnWindowFocus: false,+ },+ mutations: { networkMode: 'always', retry: false },+ },+})+let suspended = 0,+ timer: ReturnType<typeof setTimeout> | undefined+export function suspendPersistence() {+ suspended+++ if (timer) clearTimeout(timer)+}+export function resumePersistence() {+ suspended = Math.max(0, suspended - 1)+}+export async function restoreCache() {+ try {+ const value = await (await database).get('cache', 'queries-v1')+ if (value && Date.now() - value.at < 7 * 86400_000) hydrate(queryClient, value.state)+ } catch {+ /* A cache failure must not prevent the mail client starting. */+ }+ queryClient.getQueryCache().subscribe((event) => {+ if (+ suspended ||+ event.type !== 'updated' ||+ event.action.type !== 'success' ||+ event.action.manual+ )+ return+ if (timer) clearTimeout(timer)+ timer = setTimeout(() => {+ if (suspended) return+ const state = dehydrate(queryClient, {+ shouldDehydrateMutation: () => false,+ shouldDehydrateQuery: (q) =>+ ['mail', 'thread', 'mailboxes', 'identities'].includes(String(q.queryKey[0])) &&+ q.state.status === 'success',+ })+ // Keep recent windows, not an ever-growing mailbox snapshot.+ state.queries.sort((a, b) => b.state.dataUpdatedAt - a.state.dataUpdatedAt)+ state.queries = state.queries.slice(0, 80)+ for (const q of state.queries) {+ const data = q.state.data as { pages?: unknown[]; pageParams?: unknown[] } | undefined+ if (data?.pages && data.pageParams)+ q.state = {+ ...q.state,+ data: {+ ...data,+ pages: data.pages.slice(0, 3),+ pageParams: data.pageParams.slice(0, 3),+ },+ }+ }+ while (JSON.stringify(state).length > 25_000_000 && state.queries.length) state.queries.pop()+ void database+ .then((db) => db.put('cache', { at: Date.now(), state }, 'queries-v1'))+ .catch(() => {})+ }, 500)+ })+}+export async function localSaveDraft(draft: Draft) {+ await (await database).put('drafts', draft)+}+export async function localDrafts(): Promise<Draft[]> {+ return (await database).getAll('drafts')+}+export async function localDeleteDraft(id: string) {+ await (await database).delete('drafts', id)+}+export async function purgeAccountCache(ids: string[]) {+ queryClient.removeQueries({ predicate: (q) => q.queryKey[0] !== 'bootstrap' })+ const db = await database+ await db.clear('cache')+ for (const draft of await db.getAll('drafts'))+ if (ids.includes(draft.accountId)) await db.delete('drafts', draft.id)+}diff --git a/apps/desktop/src/renderer/src/character-key.ts b/apps/desktop/src/renderer/src/character-key.tsnew file mode 100644index 0000000..1b00a52--- /dev/null+++ b/apps/desktop/src/renderer/src/character-key.ts@@ -0,0 +1,34 @@+import { useEffect, useRef } from 'react'++const typing = (element: Element | null) =>+ element instanceof HTMLInputElement ||+ element instanceof HTMLTextAreaElement ||+ element instanceof HTMLSelectElement ||+ (element instanceof HTMLElement && element.isContentEditable)++/**+ * Binds a shortcut to the character a key produces rather than its position, so `?`, `#` and+ * `!` work on every keyboard layout whether or not they need Shift.+ */+export function useCharacterKey(characters: string, handler: () => void, enabled = true) {+ const latest = useRef(handler)+ latest.current = handler+ useEffect(() => {+ if (!enabled) return+ const listener = (event: KeyboardEvent) => {+ if (+ event.defaultPrevented ||+ event.ctrlKey ||+ event.metaKey ||+ event.altKey ||+ !characters.includes(event.key) ||+ typing(document.activeElement)+ )+ return+ event.preventDefault()+ latest.current()+ }+ document.addEventListener('keydown', listener)+ return () => document.removeEventListener('keydown', listener)+ }, [characters, enabled])+}diff --git a/apps/desktop/src/renderer/src/demo.ts b/apps/desktop/src/renderer/src/demo.tsnew file mode 100644index 0000000..45f1551--- /dev/null+++ b/apps/desktop/src/renderer/src/demo.ts@@ -0,0 +1,1001 @@+import {+ accountKey,+ conversationFromMessages,+ defaultSettings,+ folderRoles,+ mergePages,+ nextAccountColor,+ type Account,+ type AppEvent,+ type ConnectInput,+ type ConnectionConfig,+ type ConnectionTest,+ type DesktopMailAPI,+ type DiscoveryCandidate,+ type Draft,+ type FolderMappingReview,+ type FolderMappings,+ type Mailbox,+ type Message,+ type MailQuery,+ type MutationInput,+ type SubmissionSummary,+} from '@inlark/core'++const names = ['Personal', 'Studio', 'Projects', 'Community', 'Archive']+const emails = [+ '[email protected]',+ '[email protected]',+ '[email protected]',+ '[email protected]',+ '[email protected]',+]+const palette = ['#a69aef', '#83bba8', '#e7ae7c', '#7caee4', '#d491ac']+/**+ * The sample accounts cover the states the account settings must explain: a JMAP account, an+ * IMAP account still indexing, one whose server can't delete permanently, one whose outgoing+ * login failed, and a legacy record saved before the protocol was stored.+ */+const demoStates: Partial<Account>[] = [+ { protocol: 'jmap' },+ { protocol: 'imap', indexing: { indexed: 12_340, total: 50_000, complete: false } },+ {+ protocol: 'imap',+ limits: {+ move: 'This server can’t move messages between folders without risking duplicates.',+ destroy:+ 'This server can’t delete messages permanently without affecting other messages in the folder.',+ },+ },+ { protocol: 'imap', outgoingError: 'The outgoing server rejected the username or password.' },+ {},+]+export const demoAccounts: Account[] = names.map((name, i) => ({+ id: accountKey('demo-' + i, 'mail'),+ connectionId: 'demo-' + i,+ remoteId: 'mail',+ name,+ email: emails[i],+ color: palette[i],+ status: 'connected',+ ...demoStates[i],+}))+const catalog = [+ [+ 'GitHub',+ '[email protected]',+ 'Your weekly development digest',+ 'A little progress, every day. Here’s what happened in your repositories this week.',+ 'notifications',+ ],+ [+ 'Hetzner',+ '[email protected]',+ 'Your invoice for September is ready',+ 'Your monthly invoice is now available. Thank you for building with us.',+ 'invoice',+ ],+ [+ 'Maya Chen',+ '[email protected]',+ 'A few thoughts on the new direction',+ 'Hey Paul, I took another look at the explorations. The quieter direction feels right.',+ 'personal',+ ],+ [+ 'Vercel',+ '[email protected]',+ 'Production deployment completed',+ 'Everything is looking good. Your latest deployment is now live.',+ 'deployment',+ ],+ [+ 'Stripe',+ '[email protected]',+ 'Your receipt from Linear',+ 'Thanks for your payment. Your receipt is attached for your records.',+ 'invoice',+ ],+ [+ 'Figma',+ '[email protected]',+ 'Alex left a comment in Brand explorations',+ '“Really like where this is going. Let’s try the second variation with a little more space.”',+ 'personal',+ ],+ [+ 'Plausible',+ '[email protected]',+ 'Your weekly website report',+ 'A quick look at how your website did this week. 1,284 visitors, up 12% from last week.',+ 'report',+ ],+ [+ 'Cal.com',+ '[email protected]',+ 'Confirmed: Catch-up with Alex',+ 'Thursday, September 24 at 10:00 AM. The details are inside.',+ 'calendar',+ ],+ [+ 'Resend',+ '[email protected]',+ 'Your domain has been verified',+ 'You’re all set. You can now send emails from your custom domain.',+ 'deployment',+ ],+ [+ 'GitLab',+ '[email protected]',+ 'Pipeline passed · update dependencies',+ 'All checks passed for your latest commit on the main branch.',+ 'deployment',+ ],+ [+ 'Daniel Fischer',+ '[email protected]',+ 'Re: Coffee sometime next week?',+ 'Tuesday works for me! There’s a new place around the corner I’ve been meaning to try.',+ 'personal',+ ],+ [+ 'Cloudflare',+ '[email protected]',+ 'Monthly security overview',+ 'Your sites stayed protected this month. Here’s your September overview.',+ 'report',+ ],+ [+ 'Medium',+ '[email protected]',+ 'A few things worth reading',+ 'This week: thoughtful interfaces, small tools, and making room for better work.',+ 'newsletter',+ ],+ [+ 'Lena Weber',+ '[email protected]',+ 'The final files are in the folder',+ 'Just uploaded the final exports. Everything should be ready for tomorrow.',+ 'personal',+ ],+ [+ 'Proton',+ '[email protected]',+ 'Your account recovery details',+ 'A reminder to keep your recovery information somewhere safe.',+ 'notifications',+ ],+ [+ 'Amazon',+ '[email protected]',+ 'Your order is on its way',+ 'Good news, your package has shipped. You can follow its journey inside.',+ 'invoice',+ ],+ [+ 'Linear',+ '[email protected]',+ 'September workspace summary',+ 'A look back at what your team shipped, and what’s coming next.',+ 'report',+ ],+ [+ 'Notion',+ '[email protected]',+ 'You were mentioned in Project notes',+ 'A new comment is waiting for you in your shared workspace.',+ 'personal',+ ],+ [+ 'Buttondown',+ '[email protected]',+ 'Notes on building things slowly',+ 'A small collection of ideas, tools, and things that caught our attention.',+ 'newsletter',+ ],+ [+ 'DigitalOcean',+ '[email protected]',+ 'Your account balance has been updated',+ 'We’ve received your payment. No further action is needed.',+ 'invoice',+ ],+ [+ 'OpenAI',+ '[email protected]',+ 'New research and product updates',+ 'A short roundup of the latest tools, research, and product news.',+ 'newsletter',+ ],+]+const referenceTime = new Date()+referenceTime.setHours(11, 42, 0, 0)+const listeners = new Set<(event: AppEvent) => void>()+const changes = new Map<string, Message | null>()+const undoStack = new Map<string, [string, Message | null | undefined][]>()+const drafts = new Map<string, Draft>()+let settings = { ...defaultSettings }+const rights = {+ mayReadItems: true,+ mayAddItems: true,+ mayRemoveItems: true,+ maySetSeen: true,+ maySetKeywords: true,+ mayCreateChild: true,+ mayRename: true,+ mayDelete: true,+}+const folders = new Map<string, Mailbox[]>()+const stress = typeof location !== 'undefined' && new URLSearchParams(location.search).has('stress')+const perAccount = stress ? 50_000 : 36+function body(name: string, subject: string, preview: string, type: string) {+ if (type === 'personal')+ return (+ '<p>Hey Paul,</p><p>' ++ preview ++ '</p><p>I’ve put a few notes together so we can pick this up when you have a moment. No rush — let me know what you think.</p><p>Talk soon,<br/>' ++ name.split(' ')[0] ++ '</p>'+ )+ if (type === 'invoice')+ return (+ '<div style="max-width:560px;margin:auto;padding:28px 32px;background:#fff;color:#34343a;border-radius:8px;font-family:Arial,sans-serif"><p style="color:#8a74b6;font-size:13px;font-weight:bold;letter-spacing:2px">' ++ name.toUpperCase() ++ '</p><h2 style="font-size:25px;font-weight:500;margin:36px 0 18px">' ++ subject ++ '</h2><p style="color:#73737c;line-height:1.8">Hi Paul,<br/>' ++ preview ++ '</p></div>'+ )+ return (+ '<p>Hi Paul,</p><p>' ++ preview ++ '</p><p>You can find the full details in your dashboard. If you have any questions, we’re always happy to help.</p><p>Best,<br/>The ' ++ name ++ ' team</p>'+ )+}+function message(accountIndex: number, index: number, bodies = true): Message {+ const entry = catalog[(index + accountIndex * 3) % catalog.length]+ const [name, email, subject, preview, type] = entry+ const account = demoAccounts[accountIndex]+ const date = new Date(referenceTime.getTime() - index * 47 * 60_000 - accountIndex * 13 * 60_000)+ const id = 'message-' + index+ return {+ id,+ accountId: account.id,+ threadId: 'thread-' + index,+ subject,+ from: [{ name, email }],+ to: [{ name: 'Paul', email: account.email }],+ cc: [],+ bcc: [],+ replyTo: [],+ receivedAt: date.toISOString(),+ preview,+ size: 4300,+ hasAttachment: type === 'invoice',+ keywords: {+ ...(index < 3 && accountIndex < 3 ? {} : { $seen: true }),+ ...(index === 2 || index === 10 ? { $flagged: true } : {}),+ },+ mailboxIds: { [index < (stress ? 50_000 : 28) ? 'inbox' : 'archive']: true },+ html: bodies ? body(name, subject, preview, type) : undefined,+ text: preview,+ messageId: [id + '@demo.example'],+ attachments:+ type === 'invoice'+ ? [+ {+ blobId: 'demo-pdf',+ name: 'Invoice-September.pdf',+ type: 'application/pdf',+ size: 84210,+ },+ ]+ : [],+ ...(type === 'newsletter'+ ? { unsubscribe: { url: 'https://example.com/unsubscribe', oneClick: false } }+ : {}),+ }+}+function get(accountIndex: number, index: number, bodies = true): Message | null {+ const key = accountIndex + ':' + index+ return changes.has(key) ? changes.get(key)! : message(accountIndex, index, bodies)+}+function matches(m: Message, q: MailQuery): boolean {+ if (q.mailboxId && !m.mailboxIds[q.mailboxId]) return false+ if (+ !q.mailboxId &&+ ['inbox', 'archive', 'sent', 'drafts', 'junk', 'trash'].includes(q.view) &&+ !m.mailboxIds[q.view]+ )+ return false+ if (q.unread && m.keywords.$seen) return false+ if (q.view === 'starred' && !m.keywords.$flagged) return false+ if (+ q.text &&+ !(m.subject + ' ' + m.preview + ' ' + m.from.map((a) => a.name + ' ' + a.email).join(' '))+ .toLowerCase()+ .includes(q.text.toLowerCase())+ )+ return false+ if (+ q.from &&+ !m.from.some((a) => (a.name + a.email).toLowerCase().includes(q.from!.toLowerCase()))+ )+ return false+ if (q.to && !m.to.some((a) => a.email.toLowerCase().includes(q.to!.toLowerCase()))) return false+ if (q.subject && !m.subject.toLowerCase().includes(q.subject.toLowerCase())) return false+ if (q.hasAttachment && !m.hasAttachment) return false+ if (q.after && m.receivedAt < q.after) return false+ if (q.before && m.receivedAt > q.before) return false+ return true+}+const indexing = (account: Account) => !!account.indexing && !account.indexing.complete+function changed() {+ listeners.forEach((fn) => fn({ type: 'changed' }))+}++/* ——— Account setup: simulated locally, nothing leaves the browser ——— */+const pause = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))+const emitAccounts = () => {+ const accounts = demoAccounts.map((a) => ({ ...a }))+ listeners.forEach((fn) => fn({ type: 'accounts', accounts }))+ return accounts+}+const demoConnections = new Map<string, { config: ConnectionConfig; remember: boolean }>()+const demoFolderChoices = new Map<string, FolderMappings>()+const imapCandidate = (domain: string, provider?: string): DiscoveryCandidate => ({+ protocol: 'imap',+ source: 'autoconfig',+ incoming: { host: 'imap.' + domain, port: 993, security: 'tls', username: '' },+ outgoing: { host: 'smtp.' + domain, port: 465, security: 'tls', username: '' },+ provider,+})+const providerName = (domain: string) => {+ const base = domain.split('.').slice(-2, -1)[0] || domain+ return base[0].toUpperCase() + base.slice(1) + ' Mail'+}+function configFor(account: Account): ConnectionConfig {+ const saved = demoConnections.get(account.connectionId)+ if (saved) return saved.config+ const domain = account.email.split('@')[1]+ if (account.protocol === 'imap') {+ const candidate = imapCandidate(domain) as Extract<DiscoveryCandidate, { protocol: 'imap' }>+ return {+ protocol: 'imap',+ email: account.email,+ incoming: { ...candidate.incoming, username: account.email },+ outgoing: { ...candidate.outgoing, username: account.email },+ outgoingSameCredentials: true,+ }+ }+ return { protocol: 'jmap', serverUrl: 'https://mail.' + domain, username: account.email }+}+const demoFolders = [+ { path: 'INBOX', name: 'Inbox' },+ { path: 'Sent', name: 'Sent' },+ { path: 'Drafts', name: 'Drafts' },+ { path: 'Archive', name: 'Archive' },+ { path: 'Trash', name: 'Trash' },+ { path: 'Receipts', name: 'Receipts' },+ { path: 'Projects/2026', name: '2026' },+]+/** The server flags Sent, Drafts and Trash; Archive is only a guess by name and Junk is missing. */+function folderReview(choices?: FolderMappings): FolderMappingReview {+ const review: FolderMappingReview = {+ folders: [...demoFolders],+ mappings: {+ sent: { path: 'Sent', source: 'server' },+ drafts: { path: 'Drafts', source: 'server' },+ trash: { path: 'Trash', source: 'server' },+ archive: { path: 'Archive', source: 'name' },+ },+ }+ for (const role of folderRoles) {+ const choice = choices?.[role]+ if (choice === undefined) continue+ if (choice?.create && !review.folders.some((f) => f.path === choice.path))+ review.folders.push({ path: choice.path, name: choice.path })+ review.mappings[role] = choice && { path: choice.path, source: 'user' }+ }+ return review+}+const loginError = 'The server rejected the username or password.'+function demoTest(input: ConnectInput): ConnectionTest {+ const incoming = input.password === 'wrong' ? { ok: false, error: loginError } : { ok: true }+ if (input.config.protocol === 'jmap') return { incoming }+ const outgoingPassword = input.config.outgoingSameCredentials+ ? input.password+ : input.outgoingPassword+ const outgoing =+ outgoingPassword === 'nosmtp' || outgoingPassword === 'wrong'+ ? { ok: false, error: 'The outgoing server rejected the username or password.' }+ : { ok: true }+ return { incoming, outgoing, ...(incoming.ok ? { folders: folderReview() } : {}) }+}++/* ——— Sending status: one example of each state that needs attention ——— */+const minutesAgo = (minutes: number) => new Date(Date.now() - minutes * 60_000).toISOString()+const submissionDrafts = new Map<string, Draft>()+function sampleDraft(+ accountIndex: number,+ subject: string,+ to: Message['to'],+ text: string,+): Draft {+ return {+ id: crypto.randomUUID(),+ accountId: demoAccounts[accountIndex].id,+ identityId: 'identity',+ to,+ cc: [],+ bcc: [],+ subject,+ html: '<p>' + text + '</p>',+ text,+ attachments: [],+ updatedAt: new Date().toISOString(),+ status: 'sent',+ }+}+let submissions: SubmissionSummary[] = (() => {+ const filed = sampleDraft(+ 0,+ 'Quarterly figures',+ [{ name: 'Maya Chen', email: '[email protected]' }],+ 'Here are the figures we talked about.',+ )+ const partial = sampleDraft(+ 1,+ 'Studio schedule for October',+ [+ { name: 'Lena Weber', email: '[email protected]' },+ { name: 'Jonas', email: '[email protected]' },+ ],+ 'The October schedule is attached. Let me know if anything clashes.',+ )+ const uncertain = sampleDraft(+ 2,+ 'Re: Final files',+ [{ name: 'Daniel Fischer', email: '[email protected]' }],+ 'Thanks, everything arrived. I’ll send feedback tomorrow.',+ )+ for (const draft of [filed, partial, uncertain]) submissionDrafts.set(draft.id, draft)+ return [+ {+ draftId: filed.id,+ accountId: filed.accountId,+ subject: filed.subject,+ at: minutesAgo(18),+ state: 'sent',+ sentCopy: 'failed',+ error: 'The Sent folder is over its storage quota.',+ },+ {+ draftId: partial.id,+ accountId: partial.accountId,+ subject: partial.subject,+ at: minutesAgo(42),+ state: 'partial',+ rejected: [{ name: 'Jonas', email: '[email protected]' }],+ },+ {+ draftId: uncertain.id,+ accountId: uncertain.accountId,+ subject: uncertain.subject,+ at: minutesAgo(95),+ state: 'uncertain',+ },+ ]+})()+const emitSubmissions = () =>+ listeners.forEach((fn) => fn({ type: 'submissions', submissions: [...submissions] }))+const submissionFor = (draftId: string) => {+ const found = submissions.find((s) => s.draftId === draftId)+ if (!found) throw new Error('This send is no longer tracked.')+ return found+}+const copyOf = (source: Draft, patch: Partial<Draft>): Draft => ({+ ...source,+ id: crypto.randomUUID(),+ status: 'local',+ updatedAt: new Date().toISOString(),+ ...patch,+})+export const demoAPI: DesktopMailAPI = {+ bootstrap: async () => ({+ accounts: demoAccounts,+ settings,+ secureStorage: false,+ demo: true,+ version: '0.1.0',+ }),+ discover: async (email) => {+ await pause(700)+ const address = email.trim().toLowerCase()+ const domain = address.split('@')[1] || ''+ // Try “@fastmail.com” for JMAP, “@nothing.test” for no result, anything else for IMAP.+ const candidates: DiscoveryCandidate[] = /(^|\.)(fastmail\.com|jmap\.test)$/.test(domain)+ ? [+ {+ protocol: 'jmap',+ source: 'jmap-well-known',+ serverUrl: 'https://api.' + domain + '/jmap/session',+ username: address,+ },+ imapCandidate(domain, 'Fastmail'),+ ]+ : /(^|\.)nothing\.test$/.test(domain)+ ? []+ : [imapCandidate(domain, providerName(domain))]+ return {+ email: address,+ domain,+ candidates: candidates.map((c) =>+ c.protocol === 'imap'+ ? {+ ...c,+ incoming: { ...c.incoming, username: address },+ outgoing: { ...c.outgoing, username: address },+ }+ : c,+ ),+ }+ },+ testConnection: async (input) => {+ await pause(900)+ return demoTest(input)+ },+ connect: async (input) => {+ await pause(600)+ const test = demoTest(input)+ if (!test.incoming.ok) throw new Error(test.incoming.error)+ if (test.outgoing && !test.outgoing.ok) throw new Error(test.outgoing.error)+ const email = input.config.protocol === 'imap' ? input.config.email : input.config.username+ const existing = demoAccounts.find((a) => a.connectionId === input.connectionId)+ // Demo only: the account is added in memory and shows the same sample mail as the others.+ const account: Account = existing || {+ id: accountKey('demo-added-' + demoAccounts.length, 'mail'),+ connectionId: 'demo-added-' + demoAccounts.length,+ remoteId: 'mail',+ name: '',+ email,+ color: nextAccountColor(demoAccounts.map((a) => a.color)),+ status: 'connected',+ }+ Object.assign(account, {+ name: input.name.trim() || existing?.name || email.split('@')[1].split('.')[0],+ senderName: input.senderName?.trim() || undefined,+ protocol: input.config.protocol,+ status: 'connected',+ error: undefined,+ outgoingError: undefined,+ sessionOnly: !input.remember,+ })+ if (!existing) demoAccounts.push(account)+ demoConnections.set(account.connectionId, { config: input.config, remember: input.remember })+ if (input.folders) demoFolderChoices.set(account.id, input.folders)+ return emitAccounts()+ },+ connectionSettings: async (connectionId) => {+ const account = demoAccounts.find((a) => a.connectionId === connectionId)+ if (!account) throw new Error('This connection no longer exists.')+ return {+ connectionId,+ name: account.name,+ config: configFor(account),+ remember: demoConnections.get(connectionId)?.remember ?? !account.sessionOnly,+ folders: demoFolderChoices.get(account.id),+ }+ },+ folderMappings: async (accountId) => {+ const account = demoAccounts.find((a) => a.id === accountId)+ if (account?.protocol !== 'imap') throw new Error('This account manages its folders itself.')+ await pause(300)+ return folderReview(demoFolderChoices.get(accountId))+ },+ setFolderMappings: async (accountId, mappings) => {+ await pause(300)+ demoFolderChoices.set(accountId, { ...demoFolderChoices.get(accountId), ...mappings })+ return folderReview(demoFolderChoices.get(accountId))+ },+ disconnect: async () => {},+ reconnect: async () => {},+ updateAccount: async (accountId, appearance) => {+ const account = demoAccounts.find((a) => a.id === accountId)+ if (!account) throw new Error('Account not found.')+ account.seed = appearance.seed+ account.image = appearance.image+ const accounts = demoAccounts.map((a) => ({ ...a }))+ listeners.forEach((fn) => fn({ type: 'accounts', accounts }))+ return accounts+ },+ updateAccountDetails: async (accountId, details) => {+ const account = demoAccounts.find((a) => a.id === accountId)+ if (!account) throw new Error('Account not found.')+ account.name = details.name.trim() || account.name+ account.senderName = details.senderName.trim() || undefined+ const accounts = demoAccounts.map((a) => ({ ...a }))+ listeners.forEach((fn) => fn({ type: 'accounts', accounts }))+ return accounts+ },+ mailboxes: async (accountId) => {+ if (!folders.has(accountId))+ folders.set(+ accountId,+ ['inbox', 'archive', 'sent', 'drafts', 'junk', 'trash', 'Receipts', 'Projects'].map(+ (name, i) => ({+ id: name,+ name: name[0].toUpperCase() + name.slice(1),+ accountId,+ parentId: null,+ role: i < 6 ? name : null,+ unreadEmails: i === 0 ? 3 : 0,+ totalEmails: i === 0 ? perAccount : i === 3 ? 0 : 8,+ rights,+ }),+ ),+ )+ const accountIndex = demoAccounts.findIndex((a) => a.id === accountId)+ let unreadCount = accountIndex < 3 ? 3 : 0+ for (const [key, current] of changes) {+ const [changedAccount, index] = key.split(':').map(Number)+ if (changedAccount !== accountIndex) continue+ unreadCount -= Number(accountIndex < 3 && index < 3)+ unreadCount += Number(!!current?.mailboxIds.inbox && !current.keywords.$seen)+ }+ return folders+ .get(accountId)!+ .map((box) => (box.role === 'inbox' ? { ...box, unreadEmails: unreadCount } : box))+ },+ identities: async (id) => [+ {+ id: 'identity',+ accountId: id,+ name: demoAccounts.find((a) => a.id === id)!.senderName || 'Paul',+ email: demoAccounts.find((a) => a.id === id)!.email,+ },+ ],+ query: async (query, cursor) => {+ const pages = demoAccounts.flatMap((account, accountIndex) => {+ if (+ (query.accountId && query.accountId !== account.id) ||+ (cursor && !(account.id in cursor))+ )+ return []+ const position = cursor?.[account.id] || 0+ if (+ stress &&+ ['inbox', 'all'].includes(query.view) &&+ !Object.entries(query).some(+ ([key, value]) => !['view', 'accountId'].includes(key) && value !== undefined,+ )+ ) {+ const removed = [...changes]+ .filter(([key, m]) => key.startsWith(accountIndex + ':') && (!m || !matches(m, query)))+ .map(([key]) => Number(key.split(':')[1]))+ .sort((a, b) => a - b)+ let index = position+ for (const excluded of removed) if (excluded <= index) index+++ const omitted = new Set(removed),+ items = []+ while (index < perAccount && items.length < 50) {+ const current = index+++ if (omitted.has(current)) continue+ const m = get(accountIndex, current, false)+ if (m) items.push(conversationFromMessages(account.id, m.threadId, [m]))+ }+ const total = perAccount - removed.length+ return [+ {+ accountId: account.id,+ position,+ page: {+ items,+ total,+ next: position + 50 < total ? position + 50 : undefined,+ incomplete: indexing(account),+ },+ },+ ]+ }+ const selected: Message[] = []+ let total = 0+ for (let index = 0; index < perAccount; index++) {+ const m = get(accountIndex, index, false)+ if (!m || !matches(m, query)) continue+ if (total >= position && selected.length < 50) selected.push(m)+ total+++ }+ return [+ {+ accountId: account.id,+ position,+ page: {+ items: selected.map((m) => ({+ ...conversationFromMessages(account.id, m.threadId, [m]),+ count: 1,+ })),+ total,+ next: position + 50 < total ? position + 50 : undefined,+ incomplete: indexing(account),+ },+ },+ ]+ })+ return mergePages(pages, 50)+ },+ conversation: async (accountId, threadId) => {+ const accountIndex = demoAccounts.findIndex((a) => a.id === accountId)+ const m = get(accountIndex, Number(threadId.replace('thread-', '')))+ if (!m) throw new Error('Conversation not found.')+ return [m]+ },+ mutate: async (input) => {+ const saved: [string, Message | null | undefined][] = []+ for (const target of input.targets) {+ const accountIndex = demoAccounts.findIndex((a) => a.id === target.accountId),+ index = Number(target.threadId.replace('thread-', ''))+ const key = accountIndex + ':' + index,+ m = get(accountIndex, index)+ if (!m) continue+ saved.push([key, changes.get(key)])+ const next = structuredClone(m)+ if (input.action === 'read') next.keywords.$seen = true+ if (input.action === 'unread') delete next.keywords.$seen+ if (input.action === 'star') next.keywords.$flagged = true+ if (input.action === 'unstar') delete next.keywords.$flagged+ const destination = (+ {+ archive: 'archive',+ trash: 'trash',+ spam: 'junk',+ restore: 'inbox',+ notSpam: 'inbox',+ move: input.mailboxId,+ } as Record<string, string | undefined>+ )[input.action]+ if (destination) next.mailboxIds = { [destination]: true }+ changes.set(key, input.action === 'destroy' ? null : next)+ }+ const undoId = crypto.randomUUID()+ undoStack.set(undoId, saved)+ changed()+ return { changed: saved.length, failures: [], undoId }+ },+ mutateAll: async (query, action) => {+ const targets: MutationInput['targets'] = []+ let cursor: Record<string, number> | undefined+ do {+ const page = await demoAPI.query(query, cursor)+ targets.push(...page.items.map((c) => ({ accountId: c.accountId, threadId: c.id })))+ cursor = page.next+ } while (cursor)+ return demoAPI.mutate({ targets, action })+ },+ undo: async (id) => {+ const entries = undoStack.get(id) || []+ for (const [key, value] of entries) {+ if (value === undefined) changes.delete(key)+ else changes.set(key, value)+ }+ changed()+ return { changed: entries.length, failures: [] }+ },+ folder: async (input) => {+ await demoAPI.mailboxes(input.accountId)+ const boxes = folders.get(input.accountId)!+ if (input.operation === 'create')+ boxes.push({+ id: crypto.randomUUID(),+ name: input.name!,+ accountId: input.accountId,+ parentId: input.parentId || null,+ role: null,+ unreadEmails: 0,+ totalEmails: 0,+ rights,+ })+ if (input.operation === 'rename') {+ const b = boxes.find((b) => b.id === input.id)+ if (b) b.name = input.name!+ }+ if (input.operation === 'delete')+ folders.set(+ input.accountId,+ boxes.filter((b) => b.id !== input.id),+ )+ changed()+ },+ resumeDraft: async () => {+ throw new Error('No server draft is available.')+ },+ stageRemoteAttachments: async () => [],+ drafts: async () => [...drafts.values()],+ saveDraft: async (draft) => {+ drafts.set(draft.id, draft)+ return draft+ },+ syncDraft: async (draft) => {+ const result = { ...draft, status: 'synced' as const }+ drafts.set(draft.id, result)+ return result+ },+ deleteDraft: async (id) => {+ drafts.delete(id)+ changed()+ },+ deleteServerDraft: async (accountId, messageId) => {+ const accountIndex = demoAccounts.findIndex((a) => a.id === accountId)+ changes.set(accountIndex + ':' + messageId.replace('message-', ''), null)+ changed()+ },+ send: async (draft) => {+ await pause(500)+ // Recipient addresses choose an outcome, so every result can be reviewed without a server.+ const recipients = [...draft.to, ...draft.cc, ...draft.bcc]+ const has = (word: string) => recipients.some((a) => a.email.toLowerCase().includes(word))+ if (has('nologin')) {+ drafts.set(draft.id, {+ ...draft,+ status: 'error',+ error: 'The outgoing server rejected the username or password.',+ errorKind: 'outgoingAuthentication',+ })+ throw new Error('The outgoing server rejected the username or password. Nothing was sent.')+ }+ if (has('unconfirmed')) {+ drafts.set(draft.id, { ...draft, status: 'uncertain' })+ submissionDrafts.set(draft.id, draft)+ submissions = [+ {+ draftId: draft.id,+ accountId: draft.accountId,+ subject: draft.subject,+ at: new Date().toISOString(),+ state: 'uncertain',+ },+ ...submissions,+ ]+ emitSubmissions()+ return {+ status: 'uncertain',+ message: 'Delivery is not confirmed. Your draft is safe. Check status before trying again.',+ }+ }+ drafts.delete(draft.id)+ // Record the outcome before announcing the change, as the desktop app does.+ queueMicrotask(changed)+ if (has('refused')) {+ const rejected = recipients.filter((a) => a.email.toLowerCase().includes('refused'))+ submissionDrafts.set(draft.id, draft)+ submissions = [+ {+ draftId: draft.id,+ accountId: draft.accountId,+ subject: draft.subject,+ at: new Date().toISOString(),+ state: 'partial',+ rejected,+ },+ ...submissions,+ ]+ emitSubmissions()+ return { status: 'partial', message: 'Sent to some recipients.', rejected, sentCopy: 'filed' }+ }+ if (has('nocopy')) {+ submissions = [+ {+ draftId: draft.id,+ accountId: draft.accountId,+ subject: draft.subject,+ at: new Date().toISOString(),+ state: 'sent',+ sentCopy: 'pending',+ },+ ...submissions,+ ]+ emitSubmissions()+ return { status: 'sent', message: 'Message sent. Sent copy pending.', sentCopy: 'pending' }+ }+ return { status: 'sent', message: 'Demo · no email was sent.', sentCopy: 'filed' }+ },+ reconcile: async (draftId) => {+ await pause(600)+ const submission = submissions.find((s) => s.draftId === draftId)+ if (submission?.state === 'uncertain')+ return {+ status: 'uncertain',+ message:+ 'Delivery is still unconfirmed. Check Sent or the server before creating a replacement message.',+ }+ return { status: 'sent', message: 'This message has already been sent.' }+ },+ submissions: async () => [...submissions],+ retrySentCopy: async (draftId) => {+ await pause(500)+ submissionFor(draftId)+ submissions = submissions.filter((s) => s.draftId !== draftId)+ emitSubmissions()+ return { status: 'sent', message: 'Copy saved to Sent.', sentCopy: 'filed' }+ },+ recoverRejected: async (draftId) => {+ const submission = submissionFor(draftId)+ const source = submissionDrafts.get(draftId)+ if (submission.state !== 'partial' || !source)+ throw new Error('There are no refused recipients to recover for this message.')+ const refused = new Set(submission.rejected?.map((a) => a.email.toLowerCase()))+ const only = (list: Draft['to']) => list.filter((a) => refused.has(a.email.toLowerCase()))+ const recovery = copyOf(source, {+ to: only(source.to),+ cc: only(source.cc),+ bcc: only(source.bcc),+ })+ drafts.set(recovery.id, recovery)+ submissions = submissions.filter((s) => s.draftId !== draftId)+ emitSubmissions()+ changed()+ return recovery+ },+ replaceUncertain: async (draftId) => {+ const submission = submissionFor(draftId)+ const source = submissionDrafts.get(draftId)+ if (submission.state !== 'uncertain' || !source)+ throw new Error('Only an unconfirmed message can be replaced.')+ const replacement = copyOf(source, {})+ drafts.set(replacement.id, replacement)+ changed()+ return replacement+ },+ dismissSubmission: async (draftId) => {+ submissions = submissions.filter((s) => s.draftId !== draftId)+ const draft = drafts.get(draftId)+ if (draft?.status === 'uncertain') drafts.delete(draftId)+ emitSubmissions()+ changed()+ },+ stageAttachments: async () => {+ throw new Error('Native file attachments are available in the desktop app.')+ },+ attachment: async () => {+ throw new Error('Attachment downloads require the desktop app.')+ },+ inlineImage: async () => '',+ remoteImage: async () => '',+ senderAvatar: async (email) => {+ if (!settings.remoteImages) return null+ // Medium's fetched icon can render as an empty dark tile; show the sender initial instead.+ if (email.trim().toLowerCase() === '[email protected]') return null+ try {+ if (window.mail) return window.mail.senderAvatar(email)+ const response = await fetch(`/__demo/avatar?email=${encodeURIComponent(email)}`, {+ credentials: 'omit',+ })+ if (!response.ok) return null+ const result: { image: string | null } = await response.json()+ return result.image+ } catch {+ return null+ }+ },+ unsubscribe: async () => ({ kind: 'done' }),+ openExternal: async (url) => {+ if (/^https?:/.test(url)) window.open(url, '_blank', 'noopener,noreferrer')+ },+ settings: async (value) => {+ settings = value+ return value+ },+ diagnostics: async () =>+ JSON.stringify({ mode: 'demo', message: 'Mail data is generated locally.' }, null, 2),+ ready: async () => {},+ onEvent: (listener) => {+ listeners.add(listener)+ return () => {+ listeners.delete(listener)+ }+ },+}diff --git a/apps/desktop/src/renderer/src/empty-states.ts b/apps/desktop/src/renderer/src/empty-states.tsnew file mode 100644index 0000000..8de038c--- /dev/null+++ b/apps/desktop/src/renderer/src/empty-states.ts@@ -0,0 +1,39 @@+import { Folder, Search, type IconComponent } from '@inlark/ui/icons'+import type { View } from '@inlark/core'+import { views } from './Sidebar'++const copy: Record<Exclude<View, 'drafts'>, { title: string; description: string }> = {+ inbox: { title: 'You’re all caught up', description: 'New mail will show up here.' },+ starred: {+ title: 'No starred conversations',+ description: 'Press S to star the selected conversation.',+ },+ sent: { title: 'Nothing sent yet', description: 'Messages you send will appear here.' },+ archive: {+ title: 'Your archive is empty',+ description: 'Archived conversations stay here and in search.',+ },+ junk: { title: 'No spam', description: 'Messages marked as spam will land here.' },+ trash: { title: 'Trash is empty', description: 'Deleted conversations will show up here.' },+ all: {+ title: 'This folder is empty',+ description: 'Press V to move conversations here.',+ },+}++/** What an empty conversation list says, depending on where the user is and why it's empty. */+export function emptyListState(+ view: View,+ { searching, unreadOnly }: { searching: boolean; unreadOnly: boolean },+): { icon: IconComponent; title: string; description: string } {+ if (searching)+ return {+ icon: Search,+ title: 'No conversations found',+ description: 'Try a different search or adjust your filters.',+ }+ const icon = views.find((v) => v.id === view)?.icon || Folder+ if (unreadOnly)+ return { icon, title: 'No unread conversations', description: 'You’ve read everything here.' }+ return { icon, ...copy[view === 'drafts' ? 'all' : view] }+}diff --git a/apps/desktop/src/renderer/src/mail-date.ts b/apps/desktop/src/renderer/src/mail-date.tsnew file mode 100644index 0000000..1e5ccf5--- /dev/null+++ b/apps/desktop/src/renderer/src/mail-date.ts@@ -0,0 +1,66 @@+const sameYear = (d: Date) => d.getFullYear() === new Date().getFullYear()+const timeFormatter = new Intl.DateTimeFormat(undefined, { hour: 'numeric', minute: '2-digit' })+const currentYearFormatter = new Intl.DateTimeFormat(undefined, { month: 'short', day: 'numeric' })+const otherYearFormatter = new Intl.DateTimeFormat(undefined, {+ year: '2-digit',+ month: 'numeric',+ day: 'numeric',+})++export const day = (date: string) => {+ const d = new Date(date)+ const today = new Date()+ if (d.toDateString() === today.toDateString()) return 'Today'+ today.setDate(today.getDate() - 1)+ return d.toDateString() === today.toDateString()+ ? 'Yesterday'+ : d.toLocaleDateString(undefined, {+ weekday: 'long',+ month: 'short',+ day: 'numeric',+ ...(sameYear(d) ? {} : { year: 'numeric' }),+ })+}++export const shortDate = (date: string) => {+ const d = new Date(date)+ if (d.toDateString() === new Date().toDateString()) return timeFormatter.format(d)+ return sameYear(d) ? currentYearFormatter.format(d) : otherYearFormatter.format(d)+}++/** “Thu, Sep 25, 2026 at 10:16 AM”, as used in reply attributions and message details. */+export const longDate = (date: string) => {+ const d = new Date(date)+ return (+ d.toLocaleDateString(undefined, {+ weekday: 'short',+ month: 'short',+ day: 'numeric',+ year: 'numeric',+ }) ++ ' at ' ++ d.toLocaleTimeString(undefined, { hour: 'numeric', minute: '2-digit' })+ )+}++/** Reader timestamp: time only today, otherwise date and time. */+export const messageDate = (date: string) => {+ const d = new Date(date)+ const time = d.toLocaleTimeString(undefined, { hour: 'numeric', minute: '2-digit' })+ if (d.toDateString() === new Date().toDateString()) return { date: 'Today', time }+ return {+ date: d.toLocaleDateString(undefined, {+ month: 'short',+ day: 'numeric',+ ...(sameYear(d) ? {} : { year: 'numeric' }),+ }),+ time,+ }+}++export const formatBytes = (bytes: number) =>+ bytes < 1024+ ? bytes + ' B'+ : bytes < 1024 * 1024+ ? Math.max(1, Math.round(bytes / 1024)).toLocaleString() + ' KB'+ : (bytes / 1024 / 1024).toLocaleString(undefined, { maximumFractionDigits: 1 }) + ' MB'diff --git a/apps/desktop/src/renderer/src/main.tsx b/apps/desktop/src/renderer/src/main.tsxnew file mode 100644index 0000000..f7a7503--- /dev/null+++ b/apps/desktop/src/renderer/src/main.tsx@@ -0,0 +1,92 @@+import React from 'react'+import { createRoot } from 'react-dom/client'+import { QueryClientProvider } from '@tanstack/react-query'+import {+ createRootRoute,+ createRoute,+ createRouter,+ createHashHistory,+ RouterProvider,+} from '@tanstack/react-router'+import { TooltipProvider } from '@inlark/ui'+import { queryClient, restoreCache } from './cache'+import { App } from './App'+import '@inlark/ui/styles.css'+import './styles.css'++export interface RouteSearch {+ view?: string+ account?: string+ folder?: string+ thread?: string+ threadAccount?: string+ q?: string+}+const rootRoute = createRootRoute()+const indexRoute = createRoute({+ getParentRoute: () => rootRoute,+ path: '/',+ validateSearch: (input: Record<string, unknown>): RouteSearch =>+ Object.fromEntries(+ Object.entries(input).filter(+ ([key, value]) =>+ ['view', 'account', 'folder', 'thread', 'threadAccount', 'q'].includes(key) &&+ typeof value === 'string',+ ),+ ),+ component: App,+})+const router = createRouter({+ routeTree: rootRoute.addChildren([indexRoute]),+ history: createHashHistory(),+})+if (!location.hash || location.hash === '#/') {+ try {+ const saved = JSON.parse(localStorage.getItem('last-location') || 'null') as RouteSearch | null+ const search = Object.fromEntries(+ Object.entries(saved || {}).filter(+ ([key, value]) => ['view', 'account', 'folder'].includes(key) && typeof value === 'string',+ ),+ )+ if (Object.keys(search).length) void router.navigate({ to: '/', search, replace: true })+ } catch {+ /* Start in the inbox when there is nothing valid to restore. */+ }+}+declare module '@tanstack/react-router' {+ interface Register {+ router: typeof router+ }+}+class ErrorBoundary extends React.Component<{ children: React.ReactNode }, { error: boolean }> {+ state = { error: false }+ static getDerivedStateFromError() {+ return { error: true }+ }+ render() {+ return this.state.error ? (+ <div className="startup-error">+ <h1>Something went wrong</h1>+ <p>Inlark ran into an unexpected problem. Your saved drafts are safe on this device.</p>+ <button className="button" onClick={() => location.reload()}>+ Reload Inlark+ </button>+ </div>+ ) : (+ this.props.children+ )+ }+}+void restoreCache().finally(() =>+ createRoot(document.getElementById('root')!).render(+ <React.StrictMode>+ <ErrorBoundary>+ <QueryClientProvider client={queryClient}>+ <TooltipProvider delay={500}>+ <RouterProvider router={router} />+ </TooltipProvider>+ </QueryClientProvider>+ </ErrorBoundary>+ </React.StrictMode>,+ ),+)diff --git a/apps/desktop/src/renderer/src/message-text.ts b/apps/desktop/src/renderer/src/message-text.tsnew file mode 100644index 0000000..1144c12--- /dev/null+++ b/apps/desktop/src/renderer/src/message-text.ts@@ -0,0 +1,13 @@+import DOMPurify from 'dompurify'+import type { Message } from '@inlark/core'++/** Preserve an HTML-only message's complete text when quoting it in the basic editor. */+export function messageText(message: Message): string {+ if (message.text) return message.text+ if (!message.html) return message.preview+ const separated = message.html.replace(/<br\s*\/?\s*>|<\/(?:p|div|li|h[1-6]|tr)>/gi, '$&\n')+ const text = DOMPurify.sanitize(separated, { ALLOWED_TAGS: [], ALLOWED_ATTR: [] })+ const decoded = document.createElement('textarea')+ decoded.innerHTML = text+ return decoded.value.trim() || message.preview+}diff --git a/apps/desktop/src/renderer/src/selection.ts b/apps/desktop/src/renderer/src/selection.tsnew file mode 100644index 0000000..0aa526f--- /dev/null+++ b/apps/desktop/src/renderer/src/selection.ts@@ -0,0 +1,17 @@+/** Select a visible range while retaining selections outside that range. */+export function selectConversation(+ keys: string[],+ selected: ReadonlySet<string>,+ key: string,+ anchor?: string,+): Set<string> {+ const next = new Set(selected)+ const end = keys.indexOf(key)+ if (end < 0) return next+ const start = anchor ? keys.indexOf(anchor) : -1+ if (start >= 0) {+ for (const item of keys.slice(Math.min(start, end), Math.max(start, end) + 1)) next.add(item)+ } else if (next.has(key)) next.delete(key)+ else next.add(key)+ return next+}diff --git a/apps/desktop/src/renderer/src/styles.css b/apps/desktop/src/renderer/src/styles.cssnew file mode 100644index 0000000..d3a0555--- /dev/null+++ b/apps/desktop/src/renderer/src/styles.css@@ -0,0 +1,3769 @@+#root {+ height: 100vh;+}+.app-shell {+ display: flex;+ height: 100%;+ min-width: 0;+ padding: 8px 8px 8px 0;+ background: var(--sidebar);+ --row-height: 64px;+ /* Width of the navigation rail; overlays such as the toast centre on the content beside it. */+ --rail: 224px;+}+.app-shell.sidebar-collapsed {+ --rail: 64px;+}+.app-shell.density-compact {+ --row-height: 44px;+}+.sidebar {+ position: relative;+ width: 224px;+ flex-shrink: 0;+ display: flex;+ flex-direction: column;+ padding: 0 12px;+ overflow: hidden;+}+.sidebar-brand {+ height: 56px;+ display: flex;+ align-items: center;+ gap: 10px;+ padding: 0 8px;+ flex-shrink: 0;+}+.brand-mark {+ height: 24px;+ width: 24px;+ display: block;+ flex-shrink: 0;+}+.sidebar-brand strong {+ color: #fff;+ font-size: 15px;+ line-height: 1;+ letter-spacing: -0.045em;+ font-weight: 650;+ white-space: nowrap;+}+:root[data-theme='light'] .brand-mark {+ filter: brightness(0);+}+:root[data-theme='light'] .sidebar-brand strong {+ color: #000;+}+.sidebar-tools {+ position: absolute;+ top: 14px;+ right: 12px;+ display: flex;+ align-items: center;+ gap: 4px;+ flex-shrink: 0;+}+.sidebar-tools .button {+ width: 27px;+ height: 27px;+ min-height: 27px;+ padding: 0;+ color: var(--muted);+}+.sidebar-tools .sidebar-compose {+ border-radius: 7px;+ background: var(--raised);+ color: var(--text-strong);+}+.sidebar-scroll {+ flex: 1;+ min-height: 0;+ /* The scrollbar appears on hover; toggling overflow (rather than the thumb colour) makes+ Chromium repaint it, and the stable gutter keeps the items from shifting. */+ overflow-y: hidden;+ scrollbar-gutter: stable;+ /* Pull the scrollbar into the sidebar's edge padding so it never crowds the items. */+ margin-right: -9px;+ padding: 0 3px 16px 0;+}+.sidebar-scroll:hover,+.sidebar-scroll:focus-within {+ overflow-y: auto;+}+.nav-item {+ display: flex;+ gap: 10px;+ align-items: center;+ width: 100%;+ height: 34px;+ padding: 0 10px;+ border: 0;+ background: none;+ border-radius: 6px;+ color: var(--secondary);+ font-size: 13px;+ text-align: left;+ margin: 2px 0;+ transition:+ color 120ms,+ background 120ms;+}+/* The scroll area clips anything outside it, so draw the ring inside the item. */+.nav-item:focus-visible {+ outline-offset: -2px;+}+.nav-item > svg {+ color: var(--muted);+}+.nav-item > span:not(.account-mark) {+ flex: 1;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.nav-item > span:not(.account-mark),+.nav-item > small {+ position: relative;+ top: 1px;+}+.nav-item:hover {+ background: var(--hover);+ color: var(--text);+}+.nav-item.active {+ background: var(--selected);+ color: var(--text-strong);+ font-weight: 500;+}+.nav-item.active svg {+ color: var(--text-strong);+}+.nav-item small {+ font-size: 11px;+ color: var(--muted);+ font-variant-numeric: tabular-nums;+}+.nav-secondary-start {+ margin-top: 13px;+}+.sidebar-section-label {+ margin: 23px 3px 5px 10px;+ display: flex;+ justify-content: space-between;+ align-items: center;+ color: var(--muted);+ font-size: 11px;+ font-weight: 500;+ height: 24px;+}+.sidebar-section-toggle {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ min-width: 0;+ padding: 0;+ border: 0;+ background: none;+ color: inherit;+ font: inherit;+ cursor: pointer;+}+.sidebar-section-toggle:hover {+ color: var(--text);+}+.sidebar-section-toggle svg,+.account-chevron {+ flex-shrink: 0;+ transition: transform 120ms;+}+.sidebar-section-toggle svg.closed,+.account-chevron.closed {+ transform: rotate(-90deg);+}+.account-toggle.account-current {+ color: var(--text);+}+.account-toggle .account-chevron {+ margin-left: auto;+ color: var(--faint);+}+.account-children {+ margin: 1px 0 8px 18px;+ padding-left: 5px;+ border-left: 1px solid var(--border);+}+.account-children .nav-item {+ height: 30px;+ font-size: 12px;+}+.account-children .nav-item > svg {+ flex-shrink: 0;+}+.account-create-folder {+ color: var(--muted);+}+/* A round avatar: the account's picture, or its generated marble pattern. */+.account-mark {+ --mark-size: 16px;+ --mark-ring: rgb(255 255 255 / 0.08);+ position: relative;+ width: var(--mark-size);+ height: var(--mark-size);+ flex-shrink: 0;+ display: inline-flex;+ border-radius: 50%;+ overflow: hidden;+}+:root[data-theme='light'] .account-mark {+ --mark-ring: rgb(0 0 0 / 0.08);+}+/* A hairline keeps pictures with a background like the surface from blending into it. */+.account-mark::after {+ content: '';+ position: absolute;+ inset: 0;+ border-radius: inherit;+ box-shadow: inset 0 0 0 1px var(--mark-ring);+ pointer-events: none;+}+.account-mark > svg,+.account-mark > img {+ display: block;+ width: 100%;+ height: 100%;+ object-fit: cover;+}+/* Wider than the 16px nav icons, so pull it in to keep the labels aligned. */+.nav-item > .account-mark {+ margin: 0 -1px;+}+.account-mark.disconnected {+ opacity: 0.4;+}+.folder-nav-row {+ display: flex;+ align-items: center;+}+.folder-nav-row .nav-item {+ flex: 1;+ min-width: 0;+}+.folder-nav-row > .button {+ opacity: 0;+}+.folder-nav-row:hover > .button,+.folder-nav-row:focus-within > .button {+ opacity: 1;+}+.sidebar-bottom {+ position: relative;+ margin-top: auto;+ padding-top: 16px;+ flex-shrink: 0;+}+/* Fade scrolled items out above the footer instead of cutting them off. */+.sidebar-bottom::before {+ content: '';+ position: absolute;+ bottom: 100%;+ left: 0;+ right: 0;+ height: 28px;+ background: linear-gradient(transparent, var(--sidebar));+ pointer-events: none;+}+.connection-dot {+ width: 5px;+ height: 5px;+ border-radius: 50%;+ background: var(--green);+ display: inline-block;+ flex-shrink: 0;+}+.sidebar-footer {+ display: flex;+ align-items: center;+ gap: 4px;+ border-top: 1px solid var(--border);+ padding: 8px 0 10px;+}+.sidebar-footer > .nav-item {+ flex: 1;+ min-width: 0;+}+.sidebar-footer > .nav-item kbd {+ opacity: 0;+ transition: opacity 120ms;+}+.sidebar-footer > .nav-item:hover kbd,+.sidebar-footer > .nav-item:focus-visible kbd {+ opacity: 1;+}+.sidebar-footer > .button {+ color: var(--muted);+}+.sidebar-status,+.sidebar-status > svg {+ color: var(--red);+}+.sidebar-status:hover {+ color: var(--red);+ background: color-mix(in srgb, var(--red) 10%, transparent);+}+.sidebar-collapsed .sidebar {+ width: 64px;+ padding: 0 9px;+}+.sidebar-collapsed .sidebar-brand {+ justify-content: center;+ padding: 5px;+}+.sidebar-collapsed .sidebar-tools {+ position: static;+ flex-direction: column;+ gap: 6px;+ padding: 0 0 15px;+}+.sidebar-collapsed .nav-item {+ justify-content: center;+ padding: 7px;+}+/* The label is empty when collapsed; keep only the same gap as between the view groups. */+.sidebar-collapsed .sidebar-section-label {+ height: 0;+ margin: 13px 0 0;+}+.sidebar-collapsed .sidebar-footer {+ flex-direction: column;+ align-items: stretch;+}+.sidebar-collapsed .sidebar-footer > .button {+ align-self: center;+}+.main-content {+ container-type: inline-size;+ position: relative;+ flex: 1;+ min-width: 0;+ display: flex;+ flex-direction: column;+ background: var(--bg);+ border: 1px solid var(--border-strong);+ border-radius: 10px;+ overflow: hidden;+ box-shadow: 0 2px 8px #0000000a;+}+.list-heading {+ display: flex;+ align-items: center;+ justify-content: space-between;+ padding: 21px 28px 19px;+ flex-shrink: 0;+ gap: 16px;+}+.list-heading h1 {+ margin: 0;+ display: flex;+ align-items: center;+ gap: 10px;+ font-size: 22px;+ letter-spacing: -0.65px;+ line-height: 1.3;+ font-weight: 600;+}+.list-heading h1 > span {+ font-size: 12px;+ letter-spacing: 0;+ font-weight: 500;+ color: var(--muted);+ background: var(--surface);+ border: 1px solid var(--border);+ padding: 2px 7px;+ border-radius: 6px;+ font-variant-numeric: tabular-nums;+}+.list-heading p {+ color: var(--muted);+ font-size: 12px;+ margin: 7px 0 0;+}+.list-heading-actions {+ display: flex;+ align-items: center;+ gap: 5px;+}+.filter-dot {+ background: var(--accent);+ width: 5px;+ height: 5px;+ border-radius: 50%;+}+.menu-label {+ padding: 7px 10px;+ font-size: 11px;+ color: var(--muted);+}+.menu-check {+ width: 15px;+ display: inline-flex;+ color: var(--accent);+}+.list-toolbar {+ display: flex;+ align-items: center;+ gap: 16px;+ height: 46px;+ padding: 0 28px;+ border-bottom: 1px solid var(--border);+ flex-shrink: 0;+}+.list-tabs {+ display: flex;+ gap: 20px;+ height: 100%;+}+.list-tabs button {+ background: none;+ border: 0;+ border-bottom: 2px solid transparent;+ padding: 0 1px;+ font-size: 12px;+ color: var(--muted);+}+.list-tabs button:hover {+ color: var(--text);+}+.list-tabs button.active {+ color: var(--text);+ border-bottom-color: var(--accent);+ font-weight: 500;+}+.selection-count {+ font-size: 12px;+ color: var(--text);+}+.text-action {+ border: 0;+ background: none;+ color: var(--accent);+ font-size: 10px;+ padding: 0;+ text-align: left;+}+.text-action:hover {+ text-decoration: underline;+}+.mail-search {+ margin: 0 28px 16px;+ display: flex;+ align-items: center;+ gap: 10px;+ border: 1px solid var(--border-strong);+ background: var(--surface);+ padding: 3px 8px 3px 13px;+ border-radius: 7px;+ color: var(--muted);+}+.mail-search input {+ border: 0;+ background: none;+ padding: 7px 0;+ font-size: 13px;+}+.mail-search:focus-within {+ border-color: var(--accent-solid);+ box-shadow: 0 0 0 3px var(--accent-tint);+}+.mail-list {+ flex: 1;+ overflow: auto;+ min-height: 0;+ outline: none;+ overflow-anchor: none;+ scrollbar-gutter: stable;+ padding-bottom: 16px;+}+.mail-list:focus-visible {+ box-shadow: inset 0 0 0 1px var(--border-strong);+ border-radius: 0;+}+.date-group {+ height: 36px;+ display: flex;+ align-items: center;+ padding: 0 28px;+ color: var(--muted);+ font-size: 11px;+ font-weight: 500;+ background: var(--bg);+ border-bottom: 1px solid var(--border);+}+.mail-row {+ display: flex;+ align-items: center;+ height: var(--row-height);+ padding: 0 20px 0 28px;+ gap: 16px;+ cursor: pointer;+ border-bottom: 1px solid var(--border);+ font-size: 13px;+ position: relative;+}+.mail-row.unread {+ background: color-mix(in srgb, var(--surface) 32%, var(--bg));+}+.mail-row:hover {+ background: var(--hover);+}+.mail-row.focused {+ box-shadow: inset 2px 0 var(--accent);+ background: var(--selected);+}+.mail-row.selected {+ background: var(--selected);+}+.mail-list:has(.selected) {+ padding-bottom: 88px;+}+.row-selector {+ position: relative;+ width: 16px;+ flex-shrink: 0;+ height: 24px;+ display: flex;+ align-items: center;+ justify-content: center;+}+.row-selector .checkbox {+ position: absolute;+ opacity: 0;+}+.unread-dot {+ width: 5px;+ height: 5px;+ border-radius: 50%;+ background: var(--accent);+ opacity: 0;+ pointer-events: none;+}+.unread-dot.visible {+ opacity: 1;+}+.mail-list:has(.selected) .row-selector .checkbox,+.mail-row:hover .row-selector .checkbox,+.mail-row.selected .row-selector .checkbox,+.row-selector:focus-within .checkbox {+ opacity: 1;+}+.mail-list:has(.selected) .unread-dot,+.mail-row:hover .unread-dot,+.mail-row.selected .unread-dot,+.row-selector:focus-within .unread-dot {+ opacity: 0;+}+.row-sender {+ display: flex;+ align-items: center;+ gap: 10px;+ width: min(var(--sender-width, 180px), 38%);+ flex-shrink: 0;+ color: var(--secondary);+}+.row-sender > span:not(.avatar) {+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.row-sender small {+ color: var(--muted);+ font-size: 10px;+ padding: 0 4px;+ background: var(--surface);+ border-radius: 4px;+}+.row-sender .avatar {+ border-radius: 7px;+ font-size: 10px !important;+ box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--avatar-color) 9%, transparent);+}+.row-content {+ flex: 1;+ min-width: 0;+ display: flex;+ flex-direction: column;+ gap: 3px;+ overflow: hidden;+ white-space: nowrap;+}+.row-subject,+.row-preview {+ overflow: hidden;+ text-overflow: ellipsis;+}+.row-subject {+ color: var(--secondary);+ line-height: 20px;+}+.row-preview {+ color: var(--muted);+ font-size: 12px;+ line-height: 18px;+}+.unread .row-subject,+.unread .row-sender {+ color: var(--text-strong);+ font-weight: 550;+}+.row-meta {+ display: flex;+ align-items: center;+ gap: 9px;+ color: var(--muted);+ flex-shrink: 0;+ position: relative;+}+.row-meta time {+ width: 58px;+ text-align: right;+ font-size: 11px;+ font-variant-numeric: tabular-nums;+}+.row-attachment {+ width: 13px;+}+.row-star {+ display: grid;+ place-items: center;+ background: none;+ border: 0;+ border-radius: 5px;+ padding: 5px;+ color: var(--faint);+ opacity: 0;+ transition:+ opacity 120ms ease,+ color 120ms ease,+ background-color 120ms ease;+}+.row-star svg {+ transition:+ fill 120ms ease,+ transform 160ms cubic-bezier(0.3, 1.5, 0.6, 1);+}+.mail-row:hover .row-star,+.mail-row:focus-within .row-star,+.row-star.starred {+ opacity: 1;+}+.row-star:hover:not(:disabled) {+ color: var(--secondary);+ background: color-mix(in srgb, var(--text-strong) 8%, transparent);+}+.row-star:active:not(:disabled) svg {+ transform: scale(0.85);+}+.row-star.starred,+.row-star.starred:hover:not(:disabled) {+ color: var(--star);+}+.row-star.starred svg,+svg.starred {+ fill: currentColor;+}+.starred {+ color: var(--star);+}+.row-quick-actions {+ position: absolute;+ right: 30px;+ display: flex;+ gap: 2px;+ padding: 2px;+ border: 1px solid var(--border-strong);+ border-radius: 6px;+ background: var(--raised);+ box-shadow: 0 2px 6px #0002;+ opacity: 0;+ pointer-events: none;+}+.mail-row:hover .row-quick-actions,+.mail-row:focus-within .row-quick-actions {+ opacity: 1;+ pointer-events: auto;+}+.density-compact .row-content {+ flex-direction: row;+ gap: 12px;+ align-items: baseline;+}+.density-compact .row-subject {+ max-width: 75%;+ flex-shrink: 0;+}+.density-compact .row-sender .avatar {+ width: 24px !important;+ height: 24px !important;+}+.list-footer {+ display: flex;+ align-items: center;+ justify-content: space-between;+ border-top: 1px solid var(--border);+ min-height: 33px;+ padding: 0 24px;+ color: var(--muted);+ font-size: 10px;+ gap: 16px;+}+.list-footer > span,+.footer-shortcuts {+ display: flex;+ align-items: center;+ gap: 6px;+}+.footer-shortcuts {+ background: none;+ border: 0;+ color: var(--muted);+ font-size: 10px;+ padding: 4px 0;+}+.footer-shortcuts:hover {+ color: var(--text);+}+.footer-shortcuts span {+ margin-right: 9px;+}+.list-footer kbd {+ height: 17px;+ min-width: 17px;+ padding: 0 3px;+ font-size: 9px;+}+.load-more {+ display: flex;+ align-items: center;+ justify-content: center;+ gap: 8px;+ font-size: 12px;+ color: var(--muted);+ padding: 15px;+}+.connection-banner {+ padding: 9px 30px;+ font-size: 11px;+ display: flex;+ align-items: center;+ gap: 9px;+ color: var(--secondary);+ background: var(--accent-tint);+}+.connection-banner button {+ margin-left: auto;+ border: 0;+ background: none;+ color: var(--accent);+}+.reader-page {+ flex: 1;+ display: flex;+ flex-direction: column;+ min-height: 0;+}+.reader-toolbar {+ height: 57px;+ border-bottom: 1px solid var(--border);+ display: flex;+ align-items: center;+ padding: 0 20px;+ gap: 5px;+ flex-shrink: 0;+}+.toolbar-divider {+ width: 1px;+ height: 17px;+ background: var(--border-strong);+ margin: 0 4px;+}+.reader-navigation {+ margin-left: auto;+ display: flex;+ gap: 6px;+ align-items: center;+}+.reader-navigation > span {+ font-size: 11px;+ color: var(--muted);+ margin-right: 10px;+}+.reader-scroll {+ flex: 1;+ overflow: auto;+}+.reader-content {+ width: min(840px, 100%);+ margin: 0 auto;+ padding: 40px 40px 48px;+}+.reader-eyebrow {+ display: flex;+ gap: 9px;+ align-items: center;+ font-size: 11px;+ color: var(--secondary);+}+.reader-eyebrow > span:last-child {+ color: var(--muted);+}+.reader-content h1 {+ font-size: 27px;+ font-weight: 550;+ letter-spacing: -0.7px;+ line-height: 1.4;+ margin: 14px 0 30px;+ overflow-wrap: anywhere;+}+.message-card {+ padding: 24px 0;+ border-top: 1px solid var(--border-strong);+}+.message-heading {+ display: flex;+ gap: 12px;+ align-items: center;+}+.message-person {+ display: flex;+ flex-direction: column;+ min-width: 0;+ flex: 1;+ align-items: flex-start;+ text-align: left;+ background: none;+ border: 0;+ padding: 0;+}+.sender-name {+ font-size: 13px;+ font-weight: 550;+ max-width: 100%;+ overflow: hidden;+ text-overflow: ellipsis;+}+.sender-address {+ font-weight: 400;+ font-size: 11px;+ color: var(--muted);+ margin-left: 8px;+}+.message-to {+ color: var(--muted);+ font-size: 11px;+ margin-top: 3px;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+ max-width: 100%;+}+.message-heading time {+ color: var(--muted);+ font-size: 11px;+ white-space: nowrap;+}+.message-content {+ padding: 24px 0 2px 47px;+}+.email-frame {+ width: 100%;+ border: 0;+ border-radius: 8px;+ display: block;+ min-height: 40px;+ background: #fff;+ color-scheme: light;+}+.email-frame-adaptive {+ background: transparent;+ border-radius: 0;+ color-scheme: inherit;+}+.email-fallback {+ padding: 2px 0 4px;+ color: var(--text);+ font:+ 15px/1.7 Inter,+ -apple-system,+ BlinkMacSystemFont,+ 'Segoe UI',+ sans-serif;+ overflow-wrap: anywhere;+ white-space: pre-wrap;+}+.email-render-details {+ margin-top: 12px;+ color: var(--muted);+ font-size: 12px;+}+.email-render-details summary {+ cursor: pointer;+}+.email-render-details p {+ margin: 8px 0;+}+.email-render-details pre {+ max-height: 220px;+ padding: 12px;+ overflow: auto;+ border: 1px solid var(--border);+ border-radius: 6px;+ user-select: text;+ white-space: pre-wrap;+}+.email-render-details button {+ margin-right: 10px;+ padding: 5px 8px;+ border: 1px solid var(--border);+ border-radius: 5px;+ background: transparent;+ color: inherit;+ cursor: pointer;+}+.image-notice {+ display: flex;+ gap: 7px;+ align-items: center;+ color: var(--muted);+ font-size: 11px;+ padding: 8px 0 17px;+}+.message-details {+ display: grid;+ grid-template-columns: 70px 1fr;+ gap: 6px;+ padding: 14px 16px;+ margin: 16px 0 0 47px;+ background: var(--surface);+ border-radius: 7px;+ font-size: 11px;+}+.message-details dt {+ color: var(--muted);+}+.message-details dd {+ margin: 0;+ overflow-wrap: anywhere;+}+.collapsed-message .message-heading {+ opacity: 0.7;+}+.unsubscribe-link {+ display: flex;+ gap: 6px;+ align-items: center;+ background: none;+ border: 0;+ font-size: 11px;+ color: var(--muted);+ padding: 0 0 16px;+}+.attachment-list {+ display: flex;+ gap: 10px;+ flex-wrap: wrap;+ margin-top: 20px;+}+.attachment-card {+ display: flex;+ align-items: center;+ gap: 10px;+ border: 1px solid var(--border-strong);+ border-radius: 8px;+ padding: 11px;+ max-width: 100%;+ background: var(--surface);+}+.attachment-icon {+ color: var(--muted);+ padding: 0 4px;+}+.attachment-card > button:not(.button) {+ border: 0;+ background: none;+ text-align: left;+ padding: 0;+ min-width: 0;+}+.attachment-card strong {+ display: block;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ font-size: 11px;+ font-weight: 500;+}+.attachment-card span {+ color: var(--muted);+ font-size: 11px;+}+.reply-bar {+ display: flex;+ gap: 10px;+ padding: 0 14px 12px 45px;+}+.toast {+ position: fixed;+ bottom: 23px;+ left: calc(50% + var(--rail) / 2 - 4px);+ transform: translateX(-50%);+ z-index: 150;+ display: flex;+ gap: 13px;+ align-items: center;+ max-width: 75vw;+ background: var(--raised);+ border: 1px solid var(--border-strong);+ box-shadow: var(--shadow);+ padding: 11px 15px;+ border-radius: 8px;+ font-size: 12px;+}+.toast > svg {+ color: var(--accent);+}+.toast > span {+ max-width: 600px;+}+.toast button {+ border: 0;+ background: none;+ color: var(--accent);+ font-size: 11px;+ padding: 3px;+}+.toast button:last-child {+ color: var(--muted);+}+.modal-actions {+ display: flex;+ justify-content: flex-end;+ gap: 8px;+ margin-top: 24px;+}+.checkbox-label {+ display: flex;+ align-items: center;+ gap: 9px;+ font-size: 12px;+}+.form-field {+ margin-top: 15px;+}+.form-field input {+ margin-top: 6px;+ font-size: 12px;+}+.field-hint {+ color: var(--muted);+ font-size: 11px;+ display: block;+ margin-top: 5px;+}+.form-error,+.form-notice {+ display: flex;+ gap: 8px;+ font-size: 11px;+ line-height: 1.6;+ margin: 15px 0;+ color: var(--red);+}+.form-notice {+ color: var(--muted);+}+.form-notice svg,+.form-error svg {+ flex-shrink: 0;+ margin-top: 3px;+}+.settings-modal {+ width: min(880px, calc(100vw - 40px));+ padding: 0;+ overflow: visible;+}+/* No title bar: the title labels the navigation column and the close button floats in the corner. */+.settings-modal > .modal-heading {+ position: absolute;+ inset: 0 0 auto;+ z-index: 1;+ align-items: center;+ margin: 0;+ padding: 14px 14px 0 20px;+ pointer-events: none;+}+.settings-modal > .modal-heading > * {+ pointer-events: auto;+}+.settings-modal .modal-title {+ font-size: 12px;+ font-weight: 500;+ letter-spacing: 0;+ color: var(--muted);+}+.settings-modal > .modal-heading > .button {+ color: var(--muted);+}+.settings-layout {+ display: flex;+ min-height: 0;+ height: min(620px, calc(100dvh - 80px));+ overflow: hidden;+ border-radius: inherit;+}+.settings-nav {+ width: 200px;+ flex-shrink: 0;+ background: var(--sidebar);+ padding: 50px 10px 12px;+ display: flex;+ flex-direction: column;+ gap: 2px;+ border-right: 1px solid var(--border);+}+.settings-nav button {+ display: flex;+ gap: 10px;+ align-items: center;+ height: 32px;+ background: none;+ border: 0;+ padding: 0 10px;+ text-align: left;+ font-size: 12px;+ color: var(--secondary);+ border-radius: 6px;+ transition:+ color 120ms,+ background 120ms;+}+.settings-nav button svg {+ color: var(--muted);+}+.settings-nav button:hover {+ background: var(--hover);+ color: var(--text);+}+.settings-nav button.active {+ background: var(--selected);+ color: var(--text-strong);+ font-weight: 500;+}+.settings-nav button.active svg {+ color: var(--text-strong);+}+.settings-content {+ flex: 1;+ overflow: auto;+ padding: 48px 48px 40px;+ min-width: 0;+}+.settings-content h3 {+ font-size: 17px;+ letter-spacing: -0.4px;+ margin: 0;+ font-weight: 500;+}+.settings-lead {+ color: var(--muted);+ font-size: 11px;+ margin: 6px 0 24px;+}+.setting-section {+ margin: 25px 0;+}+.setting-section h4 {+ font-size: 11px;+ font-weight: 500;+ margin: 0 0 12px;+ color: var(--secondary);+}+.theme-options {+ display: grid;+ grid-template-columns: repeat(3, 1fr);+ gap: 14px;+}+.theme-option {+ display: flex;+ flex-direction: column;+ gap: 10px;+ min-width: 0;+ padding: 0;+ border: 0;+ background: none;+ color: var(--secondary);+ font-size: 12px;+ text-align: left;+}+.theme-option:focus-visible {+ outline: none;+}+.theme-preview {+ position: relative;+ display: block;+ aspect-ratio: 16 / 10;+ border-radius: 8px;+ overflow: hidden;+ box-shadow: 0 0 0 1px var(--border-strong);+ transition: box-shadow 120ms;+}+.theme-option:hover .theme-preview {+ box-shadow: 0 0 0 1px var(--faint);+}+.theme-option.chosen .theme-preview,+.theme-option:focus-visible .theme-preview {+ box-shadow:+ 0 0 0 2px var(--surface),+ 0 0 0 4px var(--accent-solid);+}+.theme-option-label {+ display: flex;+ align-items: center;+ gap: 8px;+ padding-left: 2px;+}+.theme-option.chosen .theme-option-label {+ color: var(--text-strong);+}+.theme-radio {+ width: 14px;+ height: 14px;+ flex-shrink: 0;+ border-radius: 50%;+ box-shadow: inset 0 0 0 1px var(--faint);+ transition: box-shadow 120ms;+}+.theme-option.chosen .theme-radio {+ box-shadow: inset 0 0 0 4px var(--accent-solid);+}+/* Miniature windows use fixed palettes so each shows its theme regardless of the current one. */+.mini-window {+ --w-bg: #171718;+ --w-sidebar: #111112;+ --w-border: #ffffff12;+ --w-line: #ffffff17;+ --w-nav: #ffffff12;+ --w-accent: #aaa6ec;+ position: absolute;+ inset: 0;+ display: grid;+ grid-template-columns: 30% 1fr;+ background: var(--w-sidebar);+}+.mini-window-light {+ --w-bg: #ffffff;+ --w-sidebar: #f2f3f5;+ --w-border: #17191f14;+ --w-line: #17191f17;+ --w-nav: #17191f12;+ --w-accent: #6962c1;+}+.theme-split {+ clip-path: inset(0 0 0 50%);+}+.mini-sidebar {+ display: flex;+ flex-direction: column;+ gap: 7%;+ padding: 18% 14%;+}+.mini-nav {+ height: 5px;+ border-radius: 2px;+ background: var(--w-nav);+}+.mini-nav.active {+ background: color-mix(in srgb, var(--w-accent) 45%, transparent);+}+.mini-nav:last-child {+ width: 70%;+}+.mini-list {+ display: flex;+ flex-direction: column;+ gap: 12%;+ margin-top: 10%;+ padding: 12% 12% 0;+ border-top-left-radius: 6px;+ background: var(--w-bg);+ box-shadow: 0 0 0 1px var(--w-border);+}+.mini-row {+ display: flex;+ align-items: center;+ gap: 8%;+}+.mini-avatar {+ width: 9px;+ height: 9px;+ flex-shrink: 0;+ border-radius: 50%;+ background: color-mix(in srgb, var(--w-accent) 60%, transparent);+}+.mini-line {+ flex: 1;+ height: 5px;+ border-radius: 2px;+ background: var(--w-line);+}+.mini-row:nth-child(2) .mini-line {+ flex: 0 1 70%;+}+.mini-row:nth-child(3) .mini-line {+ flex: 0 1 85%;+}+.setting-row {+ display: flex;+ align-items: center;+ justify-content: space-between;+ margin: 14px 0;+ gap: 24px;+}+.setting-row strong {+ font-size: 12px;+ font-weight: 400;+}+.setting-row p {+ color: var(--muted);+ font-size: 11px;+ margin: 3px 0;+}+.setting-row input {+ flex-shrink: 0;+}+.setting-footnote {+ font-size: 11px;+ color: var(--faint);+ line-height: 1.6;+}+.settings-section-heading {+ display: flex;+ justify-content: space-between;+ align-items: flex-start;+ gap: 10px;+}+.settings-section-heading h3 {+ font-size: 16px;+}+.settings-account-entry {+ border-bottom: 1px solid var(--border);+}+.settings-account {+ display: flex;+ align-items: center;+ gap: 10px;+ padding: 18px 0;+}+.account-details-form {+ display: grid;+ grid-template-columns: 1fr 1fr;+ gap: 0 14px;+ margin: -4px 0 0;+ padding: 0 0 18px 46px;+}+.account-details-form .form-field {+ margin-top: 0;+}+.sender-preview {+ color: var(--secondary);+ overflow-wrap: anywhere;+}+.account-details-actions {+ grid-column: 1 / -1;+ display: flex;+ justify-content: flex-end;+ gap: 8px;+ margin-top: 14px;+}+.settings-account-text {+ flex: 1;+ min-width: 0;+}+.settings-account strong {+ display: block;+ font-size: 12px;+ font-weight: 500;+}+.settings-account-email {+ display: block;+ font-size: 11px;+ color: var(--muted);+}+.settings-account small {+ display: flex;+ gap: 5px;+ align-items: center;+ font-size: 11px;+ margin-top: 4px;+}+.connected {+ color: var(--green);+}+.connection-error {+ color: var(--red);+}+.connection-error .connection-dot {+ background: var(--red);+}+.account-actions {+ display: flex;+ gap: 4px;+}+.account-manage-trigger[data-popup-open] {+ background: var(--hover);+ color: var(--text-strong);+}+.account-manage-trigger[data-popup-open] svg {+ transform: rotate(180deg);+}+.settings-account-menu {+ width: 220px;+}+.settings-account-menu .menu-item {+ min-height: 31px;+}+.account-form {+ max-width: 560px;+}+/* Pull the ghost button's padding into the margin so its text lines up with the form. */+.account-form-back {+ margin-left: -10px;+ color: var(--muted);+}+.account-form-title {+ margin: 18px 0 8px;+}+.account-form-title p {+ color: var(--muted);+ font-size: 12px;+ line-height: 1.6;+ margin: 6px 0 0;+}+.account-form-section {+ padding: 22px 0 4px;+}+.account-form-section + .account-form-section {+ border-top: 1px solid var(--border);+ margin-top: 18px;+}+.account-form-section h4 {+ font-size: 11px;+ font-weight: 500;+ margin: 0 0 2px;+ color: var(--secondary);+}+.form-row {+ display: grid;+ grid-template-columns: 1fr 1fr;+ gap: 0 14px;+ align-items: start;+}+.account-form-section > .checkbox-label {+ margin-top: 18px;+}+.account-form-footer {+ display: flex;+ justify-content: flex-end;+ gap: 8px;+ margin-top: 22px;+ padding-top: 18px;+ border-top: 1px solid var(--border);+}+/* Fill the pane so the empty state centres in it rather than hugging the heading. */+.no-accounts {+ display: flex;+ min-height: 360px;+}+.no-accounts .empty-state {+ padding-bottom: 48px;+}+.signature-account {+ padding: 20px 0;+ border-top: 1px solid var(--border);+}+.signature-account > header {+ display: flex;+ align-items: center;+ gap: 10px;+ margin-bottom: 12px;+ min-width: 0;+}+.signature-account > header strong {+ font-size: 13px;+ font-weight: 500;+ color: var(--text-strong);+ white-space: nowrap;+}+.signature-account > header span {+ font-size: 12px;+ color: var(--muted);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.signature-identity {+ position: relative;+}+.signature-identity + .signature-identity {+ margin-top: 14px;+}+.signature-identity label {+ margin-bottom: 6px;+ color: var(--secondary);+}+.signature-identity textarea {+ display: block;+ min-height: 76px;+ font-size: 12px;+ line-height: 1.6;+ resize: vertical;+}+.signature-saved {+ position: absolute;+ right: 10px;+ bottom: 8px;+ display: inline-flex;+ align-items: center;+ gap: 4px;+ font-size: 11px;+ color: var(--muted);+ opacity: 0;+ transition: opacity 160ms ease;+ pointer-events: none;+}+.signature-saved.visible {+ opacity: 1;+}+.signature-note {+ display: flex;+ align-items: center;+ gap: 8px;+ margin: 0;+ font-size: 12px;+ color: var(--muted);+}+.about-hero {+ display: flex;+ align-items: center;+ gap: 16px;+ padding-bottom: 26px;+ border-bottom: 1px solid var(--border);+}+.about-mark {+ width: 52px;+ height: 52px;+ display: block;+ flex-shrink: 0;+}+.about-hero > div {+ flex: 1;+ min-width: 0;+}+.about-hero p {+ color: var(--muted);+ font-size: 12px;+ margin: 3px 0 0;+}+.about-version {+ flex-shrink: 0;+ padding: 3px 8px;+ border: 1px solid var(--border-strong);+ border-radius: 20px;+ color: var(--secondary);+ font-size: 11px;+ font-variant-numeric: tabular-nums;+}+.setting-row > .button {+ flex-shrink: 0;+}+.compose-backdrop {+ position: fixed;+ inset: 0;+ background: #0004;+ z-index: 70;+}+.composer {+ position: fixed;+ right: 24px;+ bottom: 24px;+ width: min(660px, calc(100vw - 48px));+ height: min(700px, calc(100vh - 48px));+ background: var(--surface);+ border: 1px solid var(--border-strong);+ border-radius: 12px;+ box-shadow: var(--shadow);+ z-index: 71;+ display: flex;+ flex-direction: column;+ overflow: hidden;+}+.composer-expanded {+ top: 50%;+ left: 50%;+ right: auto;+ bottom: auto;+ transform: translate(-50%, -50%);+ height: 85vh;+ width: min(900px, 90vw);+ border-radius: 11px;+}+.compose-header {+ display: flex;+ align-items: center;+ gap: 9px;+ height: 48px;+ padding: 0 19px;+ background: var(--raised);+ border-bottom: 1px solid var(--border);+ flex-shrink: 0;+}+.compose-header strong {+ font-size: 12px;+ font-weight: 500;+}+.compose-header > span {+ margin-left: auto;+ font-size: 11px;+ color: var(--muted);+}+.compose-header .compose-window-actions {+ display: flex;+ gap: 3px;+}+.compose-fields {+ padding: 6px 23px;+}+.compose-field {+ display: flex;+ align-items: center;+ min-height: 42px;+ border-bottom: 1px solid var(--border);+ gap: 11px;+}+.compose-field > label,+.compose-field > span {+ width: 43px;+ flex-shrink: 0;+ font-size: 11px;+ color: var(--muted);+}+.compose-field input {+ flex: 1;+ border: 0;+ padding: 7px 0;+ background: none;+ font-size: 12px;+ min-width: 0;+}+/* Borderless pickers that read as part of the address block. */+.compose-field > .select-trigger {+ flex: 1;+ height: 32px;+ padding: 0 4px 0 0;+ border: 0;+ background: none;+ color: var(--text);+ font-size: 12px;+ white-space: normal;+}+.compose-field > .select-trigger:hover:not([data-disabled]) {+ background: none;+}+.compose-field > button {+ font-size: 11px;+ background: none;+ border: 0;+ color: var(--muted);+ white-space: nowrap;+}+.compose-field .subject-input {+ font-weight: 500;+}+.compose-body {+ flex: 1;+ overflow: auto;+ padding: 20px 24px;+ min-height: 0;+}+.compose-editor {+ min-height: 180px;+ outline: none;+ font-size: 15px;+ line-height: 1.8;+ color: var(--text);+}+.compose-editor p {+ margin: 0 0 13px;+}+.compose-editor ul,+.compose-editor ol {+ padding-left: 25px;+}+.compose-editor ul {+ list-style: disc;+}+.compose-editor ol {+ list-style: decimal;+}+.compose-editor blockquote {+ border-left: 2px solid var(--border-strong);+ padding-left: 16px;+ color: var(--muted);+}+.compose-editor p.is-editor-empty:first-child:before {+ content: attr(data-placeholder);+ color: var(--faint);+ float: left;+ height: 0;+ pointer-events: none;+}+.compose-format {+ display: flex;+ gap: 5px;+ align-items: center;+ padding: 7px 18px;+ border-top: 1px solid var(--border);+}+.active-format {+ background: var(--hover);+ color: var(--accent);+}+.compose-footer {+ display: flex;+ align-items: center;+ gap: 10px;+ padding: 13px 20px;+ border-top: 1px solid var(--border);+}+.send-shortcut {+ font-size: 11px;+ opacity: 0.6;+ margin-left: 10px;+}+.compose-account {+ flex: 1;+ text-align: right;+ color: var(--muted);+ font-size: 11px;+}+.compose-warning {+ display: flex;+ align-items: center;+ gap: 8px;+ padding: 10px 22px;+ font-size: 11px;+ color: var(--red);+ background: var(--accent-tint);+}+.compose-attachments {+ display: flex;+ gap: 7px;+ flex-wrap: wrap;+ margin-top: 15px;+}+.compose-attachment {+ display: flex;+ gap: 7px;+ align-items: center;+ padding: 7px 9px;+ border: 1px solid var(--border-strong);+ border-radius: 6px;+ font-size: 11px;+}+.compose-attachment small {+ color: var(--muted);+}+.compose-attachment button {+ border: 0;+ background: none;+ padding: 0;+ color: var(--muted);+}+.draft-list {+ flex: 1;+ overflow: auto;+}+.draft-rows:has(.selected) {+ padding-bottom: 88px;+}+.draft-row {+ display: flex;+ gap: 16px;+ align-items: center;+ border-bottom: 1px solid var(--border);+ padding: 0 26px 0 32px;+ color: var(--secondary);+}+.draft-row:hover {+ background: var(--hover);+}+.draft-row.selected {+ background: var(--selected);+}+.draft-selector {+ position: relative;+ display: grid;+ place-items: center;+ flex-shrink: 0;+ width: 17px;+ height: 17px;+}+.draft-selector .checkbox {+ position: absolute;+ opacity: 0;+}+.draft-rows.selecting .draft-selector:not(:has([data-disabled])) .checkbox,+.draft-row:hover .draft-selector:not(:has([data-disabled])) .checkbox,+.draft-selector:focus-within .checkbox {+ opacity: 1;+}+.draft-rows.selecting .draft-selector:not(:has([data-disabled])) > svg,+.draft-row:hover .draft-selector:not(:has([data-disabled])) > svg,+.draft-selector:focus-within > svg {+ opacity: 0;+}+.draft-open {+ display: flex;+ flex: 1;+ gap: 16px;+ align-items: center;+ min-width: 0;+ padding: 19px 0;+ background: none;+ border: 0;+ text-align: left;+}+.draft-open > div {+ flex: 1;+ min-width: 0;+}+.draft-open strong {+ display: block;+ font-weight: 500;+ font-size: 13px;+ color: var(--text);+}+.draft-open span {+ display: block;+ font-size: 11px;+ color: var(--muted);+ margin-top: 4px;+}+.draft-open small,+.draft-open time {+ font-size: 11px;+ color: var(--muted);+}+.draft-actions {+ position: relative;+ display: grid;+ place-items: center;+ flex-shrink: 0;+ width: 28px;+ height: 28px;+}+.draft-actions .button {+ position: absolute;+ inset: 0;+ opacity: 0;+}+.draft-row:hover .draft-actions .button,+.draft-actions:focus-within .button {+ opacity: 1;+}+.draft-row:hover .draft-actions:has(.button) > svg,+.draft-actions:focus-within > svg {+ opacity: 0;+}+.command-modal {+ padding: 0;+ width: 610px;+}+.command-modal > .modal-heading {+ position: absolute;+ width: 1px;+ height: 1px;+ overflow: hidden;+ clip-path: inset(50%);+}+.command-modal > .modal-heading .button {+ display: none;+}+.command-input {+ display: flex;+ gap: 13px;+ align-items: center;+ padding: 18px 21px;+ border-bottom: 1px solid var(--border-strong);+ color: var(--muted);+}+.command-input input {+ border: 0;+ padding: 3px 0;+ background: none;+ font-size: 14px;+}+.command-results {+ padding: 9px;+ max-height: min(430px, calc(100vh - 260px));+ overflow: auto;+}+.command-label {+ padding: 16px 22px 3px;+ font-size: 11px;+ color: var(--muted);+}+.command-results button {+ width: 100%;+ display: flex;+ gap: 12px;+ align-items: center;+ padding: 11px 13px;+ background: none;+ border: 0;+ border-radius: 6px;+ font-size: 12px;+ color: var(--secondary);+ text-align: left;+}++.command-results button.active,+.command-results button:hover {+ background: var(--hover);+ color: var(--text);+}+.command-results button.active svg {+ color: var(--accent);+}+.command-footer {+ border-top: 1px solid var(--border);+ padding: 12px 21px;+ display: flex;+ gap: 8px;+ align-items: center;+ font-size: 11px;+ color: var(--muted);+}+.shortcut-grid {+ display: grid;+ grid-template-columns: 1fr 1fr;+ gap: 16px 30px;+}+.shortcut-grid > div {+ display: flex;+ justify-content: space-between;+ align-items: center;+ font-size: 11px;+ color: var(--secondary);+}+.filter-modal {+ width: min(520px, calc(100vw - 40px));+}+.filter-fields {+ display: grid;+ grid-template-columns: 1fr 1fr;+ gap: 16px 12px;+}+.filter-wide {+ grid-column: 1 / -1;+}+.filter-fields input,+.filter-field .filter-date-range {+ margin-top: 6px;+ font-size: 12px;+}+.filter-field > span {+ display: block;+ font-size: 12px;+ color: var(--secondary);+}+.filter-date-range {+ display: grid;+ grid-template-columns: 1fr auto 1fr;+ align-items: center;+ gap: 8px;+}+.filter-date-separator {+ font-size: 12px;+ color: var(--faint);+}+.filter-switch {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 16px;+ padding-top: 16px;+ border-top: 1px solid var(--border);+}+.filter-switch strong {+ display: block;+ font-size: 12px;+ font-weight: 400;+ color: var(--text);+}+.filter-switch small {+ display: block;+ margin-top: 2px;+ font-size: 11px;+ color: var(--muted);+}+/* Clearing sits apart from the main action so it isn't hit by accident. */+.filter-actions {+ justify-content: space-between;+ margin-top: 22px;+}+.filter-actions > .button-ghost {+ margin-left: -10px;+ color: var(--muted);+}+.folder-picker button {+ width: 100%;+ display: flex;+ align-items: center;+ gap: 12px;+ background: none;+ border: 0;+ padding: 12px;+ border-radius: 6px;+ font-size: 12px;+ text-align: left;+}+.folder-picker button svg:last-child {+ margin-left: auto;+}+.folder-picker button:hover {+ background: var(--hover);+}+.startup-error {+ max-width: 520px;+ margin: 20vh auto;+ padding: 25px;+}+.startup-error h1 {+ font-size: 23px;+}+.startup-error p {+ color: var(--muted);+ line-height: 1.8;+}+.compose-heading {+ display: flex;+ align-items: center;+ justify-content: space-between;+ height: 48px;+ padding: 0 17px 0 24px;+ background: var(--raised);+ border-bottom: 1px solid var(--border);+ flex-shrink: 0;+}+.compose-heading > span {+ font-size: 12px;+ font-weight: 500;+}+.compose-dot {+ width: 5px;+ height: 5px;+ border-radius: 50%;+ display: inline-block;+ background: var(--accent);+ margin-right: 6px;+}+.compose-heading > div {+ display: flex;+ align-items: center;+ gap: 5px;+}+.draft-state {+ display: flex;+ align-items: center;+ gap: 5px;+ color: var(--muted);+ font-size: 11px;+ margin-right: 12px;+}+.compose-addresses {+ padding: 5px 24px;+}+fieldset.compose-format {+ margin: 0;+ min-width: 0;+ border-left: 0;+ border-right: 0;+ border-bottom: 0;+}+fieldset.compose-format:disabled {+ opacity: 0.5;+}+.compose-warning span {+ flex: 1;+}+.compose-warning .button {+ flex-shrink: 0;+}++.command-results button {+ padding: 8px 12px;+ font-size: 13px;+}+.command-icon {+ width: 28px;+ height: 28px;+ display: grid;+ place-items: center;+ border: 1px solid var(--border-strong);+ border-radius: 6px;+ background: var(--surface);+}+.command-dismiss {+ border: 0;+ background: none;+ padding: 0;+}+.command-enter {+ display: flex;+ align-items: center;+ gap: 7px;+ margin-left: 12px;+}+.command-footer-brand {+ margin-left: auto;+ color: var(--faint);+}+.setting-section + .setting-section {+ border-top: 1px solid var(--border);+ padding-top: 22px;+}+.command-input input:focus-visible,+.mail-search input:focus-visible {+ outline: none;+}+.command-input:focus-within {+ border-bottom-color: var(--accent-solid);+}+.settings-content h3 {+ font-size: 20px;+ font-weight: 550;+ letter-spacing: -0.5px;+}+.settings-lead,+.setting-row p,+.setting-footnote,+.settings-account-email {+ font-size: 12px;+ line-height: 1.6;+}+.setting-row strong,+.settings-nav button,+.settings-account strong {+ font-size: 13px;+}++.active-filters {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 6px;+ padding: 0 28px 14px;+}+.filter-chip {+ display: inline-flex;+ align-items: center;+ gap: 8px;+ max-width: 260px;+ padding: 4px 8px;+ font-size: 11px;+ color: var(--accent);+ border: 1px solid color-mix(in srgb, var(--accent) 25%, transparent);+ background: var(--accent-tint);+ border-radius: 5px;+}+.filter-chip span {+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.clear-filters {+ border: 0;+ background: none;+ color: var(--muted);+ font-size: 11px;+ padding: 4px 8px;+}+.clear-filters:hover {+ color: var(--text);+}++.compose-field input:focus-visible,+.compose-field > .select-trigger:focus-visible {+ outline: none;+}+.compose-field:focus-within {+ border-bottom-color: var(--accent-solid);+}+.compose-backdrop {+ transition: opacity 160ms ease;+}+.composer {+ transition:+ opacity 160ms ease,+ transform 160ms ease;+}+.compose-backdrop[data-starting-style],+.compose-backdrop[data-ending-style] {+ opacity: 0;+}+.composer[data-starting-style],+.composer[data-ending-style] {+ opacity: 0;+ transform: translateY(10px) scale(0.99);+}+.composer-expanded[data-starting-style],+.composer-expanded[data-ending-style] {+ transform: translate(-50%, -48%) scale(0.99);+}++/* Inbox chrome stays compact so the messages remain the primary surface. */+.list-title {+ min-width: 0;+}+.list-eyebrow {+ display: flex;+ align-items: center;+ gap: 7px;+ font-size: 11px;+ color: var(--muted);+ margin-bottom: 6px;+}+.list-eyebrow svg {+ color: var(--faint);+}+.account-switcher {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ padding: 2px 5px;+ margin: -2px -5px;+ border: 0;+ border-radius: 4px;+ background: none;+ color: inherit;+ font-size: inherit;+ min-width: 0;+}+.account-switcher > span:not(.account-mark) {+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.account-switcher:hover,+.account-switcher[data-popup-open] {+ color: var(--text);+ background: var(--hover);+}+.account-menu {+ width: 250px;+ max-width: calc(100vw - 40px);+ max-height: min(420px, 65vh);+ overflow-y: auto;+}+.account-menu .menu-item {+ min-height: 48px;+ gap: 12px;+}+.account-menu-label {+ flex: 1;+ min-width: 0;+}+.account-menu-label strong,+.account-menu-label small {+ display: block;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.account-menu-label strong {+ font-weight: 500;+}+.account-menu-label small {+ color: var(--muted);+ font-size: 10px;+ margin-top: 2px;+}+.account-menu-check {+ color: var(--accent);+}+.account-menu-divider {+ height: 1px;+ margin: 5px;+ background: var(--border);+}+.list-toolbar-actions {+ display: flex;+ align-items: center;+ gap: 18px;+ margin-left: auto;+}+.list-toolbar-actions > .button {+ font-weight: 400;+}+.selection-bar {+ position: absolute;+ z-index: 10;+ bottom: 50px;+ left: 50%;+ transform: translateX(-50%);+ display: flex;+ align-items: center;+ gap: 5px;+ padding: 10px 12px;+ max-width: calc(100% - 24px);+ white-space: nowrap;+ border: 1px solid var(--border-strong);+ border-radius: 10px;+ background: var(--raised);+ box-shadow:+ 0 8px 28px #0003,+ 0 2px 5px #0002;+ animation: selection-appear 140ms ease-out;+}+.selection-summary {+ display: flex;+ flex-direction: column;+ gap: 2px;+ min-width: 82px;+ padding: 0 6px;+}+.selection-count {+ font-weight: 500;+ font-variant-numeric: tabular-nums;+}+@keyframes selection-appear {+ from {+ opacity: 0;+ transform: translate(-50%, 5px);+ }+ to {+ opacity: 1;+ transform: translate(-50%, 0);+ }+}+.connection-pending {+ background: var(--red);+}+.reader-back {+ max-width: 180px;+ margin-left: -6px;+}+.reader-back span {+ overflow: hidden;+ text-overflow: ellipsis;+}+.reader-navigation > span {+ font-variant-numeric: tabular-nums;+ white-space: nowrap;+}+.reply-panel {+ margin: 12px 0 0 47px;+ border: 1px solid var(--border-strong);+ border-radius: 10px;+ background: color-mix(in srgb, var(--surface) 45%, var(--bg));+ overflow: hidden;+}+.reply-prompt {+ display: flex;+ align-items: center;+ gap: 13px;+ width: 100%;+ background: none;+ border: 0;+ text-align: left;+ padding: 20px;+ color: var(--muted);+}+.reply-prompt:hover {+ background: var(--hover);+}+.reply-prompt > span {+ flex: 1;+ min-width: 0;+}+.reply-prompt strong {+ display: block;+ color: var(--text);+ font-size: 13px;+ font-weight: 500;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.reply-prompt span span {+ display: block;+ font-size: 12px;+ margin-top: 4px;+}+.reply-bar .button {+ font-size: 11px;+}+.collapsed-message {+ padding: 18px 0;+}+.collapsed-message:hover .message-heading {+ opacity: 1;+}+.message-details + .message-content {+ padding-top: 18px;+}+.compose-format {+ margin: 0;+ border-right: 0;+ border-left: 0;+ border-bottom: 0;+ min-width: 0;+}+.compose-format .active-format {+ background: var(--accent-tint);+ color: var(--accent);+}+.compose-addresses {+ flex-shrink: 0;+}++@media (max-width: 1100px) {+ .app-shell:not(.sidebar-collapsed) {+ --rail: 204px;+ }+ .sidebar {+ width: 204px;+ }+ .sidebar-brand {+ gap: 7px;+ padding: 0 5px;+ }+ .sidebar-brand strong {+ font-size: 14px;+ }+}+/* Container queries also respond when the navigation rail is collapsed. */+@container (max-width: 900px) {+ .mail-row {+ gap: 12px;+ padding-left: 22px;+ padding-right: 14px;+ }+ .list-heading,+ .list-toolbar,+ .date-group {+ padding-left: 22px;+ padding-right: 22px;+ }+ .row-sender .avatar {+ display: none;+ }+ .density-compact .row-preview {+ display: none;+ }+ .density-compact .row-subject {+ max-width: 100%;+ }+ .sender-address {+ display: none;+ }+ .list-footer {+ padding: 0 20px;+ }+ .footer-shortcuts span {+ display: none;+ }+}+@container (max-width: 680px) {+ .list-heading {+ padding: 20px 20px 17px;+ }+ .list-toolbar {+ padding: 0 20px;+ gap: 14px;+ }+ .list-toolbar-actions {+ gap: 10px;+ }+ .list-heading-actions {+ gap: 2px;+ }+ .date-group {+ padding: 0 20px;+ }+ .mail-row {+ padding: 0 16px 0 20px;+ gap: 12px;+ }+ .density-comfortable .mail-row {+ display: grid;+ grid-template-columns: 16px minmax(0, 1fr) auto;+ grid-template-rows: 22px 20px;+ gap: 2px 12px;+ align-content: center;+ }+ .density-comfortable .row-selector {+ grid-column: 1;+ grid-row: 1 / 3;+ }+ .density-comfortable .row-sender {+ grid-column: 2;+ grid-row: 1;+ width: auto;+ min-width: 0;+ }+ .density-comfortable .row-meta {+ grid-column: 3;+ grid-row: 1;+ gap: 7px;+ }+ .density-comfortable .row-content {+ grid-column: 2 / 4;+ grid-row: 2;+ flex-direction: row;+ gap: 10px;+ align-items: baseline;+ }+ .density-comfortable .row-subject {+ flex-shrink: 0;+ max-width: 75%;+ font-size: 12px;+ }+ .row-meta time {+ font-size: 10px;+ width: 54px;+ }+ .row-star {+ padding: 3px;+ }+ .row-meta {+ gap: 6px;+ }+ .reader-toolbar {+ padding: 0 16px;+ gap: 2px;+ }+ .reader-back span {+ display: none;+ }+ .reader-navigation {+ gap: 2px;+ }+ .reader-navigation > span {+ margin-right: 4px;+ }+ .reader-content {+ padding: 28px 26px;+ }+ .reader-content h1 {+ font-size: 24px;+ margin-bottom: 24px;+ }+ .message-content {+ padding-left: 0;+ }+ .message-details {+ margin-left: 0;+ }+ .reply-panel {+ margin-left: 0;+ }+ .reply-bar {+ padding-left: 44px;+ }+ .message-heading {+ gap: 9px;+ }+ .message-heading time span {+ display: none;+ }+ .mail-search {+ margin-left: 20px;+ margin-right: 20px;+ }+ .active-filters {+ padding-left: 20px;+ padding-right: 20px;+ }+}+@container (max-width: 440px) {+ .list-tabs {+ gap: 16px;+ }+ .list-heading h1 {+ font-size: 21px;+ }+ .density-comfortable .row-preview {+ display: none;+ }+ .density-comfortable .row-subject {+ max-width: 100%;+ }+ .density-compact .row-sender {+ font-size: 11px;+ }+ .density-compact .row-meta time {+ display: none;+ }+ .density-compact .row-subject {+ font-size: 12px;+ }+ .footer-shortcuts kbd:not(:last-of-type) {+ display: none;+ }+ .reader-toolbar {+ padding: 0 10px;+ }+ .reader-toolbar > .toolbar-divider {+ margin: 0 2px;+ }+ .reader-navigation > span {+ font-size: 10px;+ }+ .reader-content {+ padding: 26px 20px;+ }+ .selection-bar {+ gap: 2px;+ padding: 8px;+ }+ .selection-summary {+ min-width: 74px;+ padding: 0 4px;+ }+ .selection-bar .toolbar-divider {+ margin: 0 2px;+ }+}+@media (max-width: 700px) {+ .app-shell:not(.sidebar-collapsed) {+ --rail: 188px;+ }+ .sidebar {+ width: 188px;+ padding: 0 10px;+ }+ .sidebar-tools {+ right: 7px;+ gap: 2px;+ }+ .sidebar-tools .button {+ width: 24px;+ height: 24px;+ min-height: 24px;+ }+ .sidebar-brand {+ gap: 6px;+ padding: 0 3px;+ }+ .sidebar-brand strong {+ font-size: 13px;+ }+ .brand-mark {+ width: 24px;+ height: 24px;+ }+ .settings-modal > .modal-heading {+ padding-left: 16px;+ }+ .settings-nav {+ width: 136px;+ padding: 50px 8px 12px;+ }+ .settings-nav button {+ padding: 0 8px;+ font-size: 12px;+ gap: 7px;+ }+ .settings-content {+ padding: 48px 20px 20px;+ }+ .theme-options {+ gap: 10px;+ }+ .setting-row {+ gap: 14px;+ }+ .compose-account {+ font-size: 10px;+ }+ .toast {+ max-width: calc(100vw - var(--rail) - 32px);+ width: max-content;+ }+}+@media (max-height: 700px) {+ .sidebar-collapsed .sidebar-tools {+ padding-bottom: 12px;+ }+ .sidebar-bottom {+ padding-top: 8px;+ }+ .sidebar-footer {+ padding: 4px 0 6px;+ }+}++/* ——— Reader ——— */+.reader-page {+ position: relative;+}+.body-skeleton {+ display: grid;+ gap: 12px;+ padding: 6px 0 10px;+}+.body-skeleton span,+.skeleton-line,+.skeleton-avatar {+ display: block;+ height: 10px;+ border-radius: 5px;+ background: linear-gradient(+ 90deg,+ var(--skeleton) 0%,+ color-mix(in srgb, var(--skeleton) 45%, transparent) 50%,+ var(--skeleton) 100%+ );+ background-size: 200% 100%;+ animation: shimmer 1.4s ease-in-out infinite;+}+.body-skeleton span:nth-child(1) {+ width: 32%;+}+.body-skeleton span:nth-child(2) {+ width: 92%;+}+.body-skeleton span:nth-child(3) {+ width: 84%;+}+.body-skeleton span:nth-child(4) {+ width: 58%;+}+@keyframes shimmer {+ from {+ background-position: 100% 0;+ }+ to {+ background-position: -100% 0;+ }+}+.link-status {+ position: absolute;+ left: 12px;+ bottom: 12px;+ max-width: min(640px, calc(100% - 24px));+ padding: 5px 9px;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ font-size: 11px;+ color: var(--secondary);+ background: var(--raised);+ border: 1px solid var(--border-strong);+ border-radius: 6px;+ box-shadow: 0 4px 14px #0003;+ pointer-events: none;+ z-index: 5;+}+.folded-messages {+ position: relative;+ display: flex;+ justify-content: center;+ width: 100%;+ height: 34px;+ margin: 0;+ padding: 0;+ border: 0;+ border-top: 1px solid var(--border-strong);+ background: none;+}+.folded-messages span {+ position: absolute;+ top: -11px;+ padding: 2px 10px;+ font-size: 11px;+ color: var(--muted);+ background: var(--bg);+ border: 1px solid var(--border-strong);+ border-radius: 11px;+ transition:+ color 120ms,+ border-color 120ms;+}+.folded-messages:hover span {+ color: var(--text);+ border-color: color-mix(in srgb, var(--text) 30%, transparent);+}+.folded-messages + .message-card {+ border-top: 0;+ padding-top: 0;+}+.message-person:disabled {+ cursor: default;+ opacity: 1;+}+.message-attachment-hint {+ color: var(--muted);+ flex-shrink: 0;+}+.details-chevron {+ transition: transform 140ms ease;+}+.details-chevron.open {+ transform: rotate(180deg);+}+.attachment-card {+ padding: 6px 6px 6px 8px;+ gap: 4px;+ transition: border-color 120ms;+}+.attachment-card:hover {+ border-color: color-mix(in srgb, var(--text) 22%, transparent);+}+.attachment-open {+ display: flex;+ align-items: center;+ gap: 10px;+ min-width: 0;+ max-width: 260px;+ padding: 3px 4px 3px 0;+ border: 0;+ background: none;+ text-align: left;+}+.attachment-icon {+ display: grid;+ place-items: center;+ width: 34px;+ height: 34px;+ flex-shrink: 0;+ padding: 0;+ border-radius: 7px;+ color: var(--accent);+ background: var(--accent-tint);+}+.attachment-label {+ min-width: 0;+}+.attachment-label > span {+ display: block;+ margin-top: 1px;+}+.menu-item kbd,+.menu-shortcut {+ margin-left: auto;+}+.reply-bar kbd {+ margin-left: 2px;+ height: 16px;+ min-width: 16px;+ font-size: 9px;+}++/* ——— List ——— */+.skeleton-row {+ cursor: default;+ pointer-events: none;+}+.skeleton-row:hover {+ background: none;+}+.skeleton-row > .skeleton-line:first-of-type {+ flex-shrink: 0;+ width: 120px;+}+.skeleton-row .row-content {+ gap: 9px;+}+.skeleton-avatar {+ width: 28px;+ height: 28px;+ border-radius: 7px;+ flex-shrink: 0;+ margin-right: -6px;+}+.skeleton-line.faint {+ opacity: 0.55;+}+.density-compact .skeleton-row .skeleton-line.faint {+ display: none;+}+.list-skeleton .skeleton-row:nth-child(n + 6) {+ opacity: 0.6;+}+.list-skeleton .skeleton-row:nth-child(n + 8) {+ opacity: 0.3;+}+.account-offline {+ color: var(--faint);+}++/* ——— Toast ——— */+.toast {+ overflow: hidden;+ animation: toast-in 180ms cubic-bezier(0.2, 0.9, 0.3, 1.2);+}+.toast-error > svg:first-child {+ color: var(--red);+}+.toast .toast-undo {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ padding: 3px 4px 3px 8px;+ border-radius: 5px;+ font-weight: 500;+}+.toast .toast-undo:hover {+ background: var(--accent-tint);+}+.toast-undo kbd {+ height: 16px;+ min-width: 16px;+ font-size: 9px;+ color: var(--accent);+ border-color: color-mix(in srgb, var(--accent) 35%, transparent);+}+.toast .toast-dismiss {+ display: grid;+ place-items: center;+ border-radius: 5px;+ color: var(--muted);+}+.toast .toast-dismiss:hover {+ color: var(--text);+ background: var(--hover);+}+.toast-timer {+ position: absolute;+ left: 0;+ bottom: 0;+ height: 2px;+ width: 100%;+ background: color-mix(in srgb, var(--accent) 45%, transparent);+ transform-origin: left;+ animation: toast-timer linear forwards;+}+.toast-error .toast-timer {+ background: color-mix(in srgb, var(--red) 45%, transparent);+}+@keyframes toast-in {+ from {+ opacity: 0;+ transform: translate(-50%, 8px) scale(0.98);+ }+}+@keyframes toast-timer {+ to {+ transform: scaleX(0);+ }+}++/* ——— Command menu ——— */+.command-results {+ padding: 4px 8px 8px;+}+.command-label {+ padding: 12px 12px 5px;+}+.command-results button {+ gap: 11px;+ padding: 7px 10px;+}+.command-icon {+ width: 26px;+ height: 26px;+ color: var(--muted);+}+/* An account's avatar stands in for the icon frame. */+.command-icon:has(> .account-mark) {+ border: 0;+ background: none;+}+.command-results button.active .command-icon {+ color: var(--text-strong);+ border-color: color-mix(in srgb, var(--text) 22%, transparent);+}+.command-text {+ flex: 1;+ min-width: 0;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.command-group {+ font-size: 11px;+ color: var(--faint);+}+.command-check {+ color: var(--accent);+}+.command-keys {+ display: flex;+ gap: 3px;+}+.command-empty {+ padding: 22px 12px;+ text-align: center;+ font-size: 12px;+ color: var(--muted);+}++/* ——— Shortcut sheet ——— */+.shortcut-modal {+ width: min(720px, calc(100vw - 40px));+}+.shortcut-sections {+ columns: 2 280px;+ column-gap: 36px;+}+.shortcut-sections section {+ break-inside: avoid;+ margin-bottom: 22px;+}+.shortcut-sections h3 {+ margin: 0 0 8px;+ font-size: 11px;+ font-weight: 500;+ color: var(--muted);+}+.shortcut-row {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 16px;+ min-height: 30px;+ font-size: 12px;+ color: var(--secondary);+ border-bottom: 1px solid var(--border);+}+.shortcut-keys {+ display: flex;+ gap: 4px;+}++/* ——— Settings ——— */+.setting-select {+ width: auto;+ min-width: 240px;+ flex-shrink: 0;+}+/* Anchored near the top so the input stays put while results change height. */+.command-modal {+ top: min(16vh, 140px);+ transform: translate(-50%, 0);+}+.command-modal[data-starting-style],+.command-modal[data-ending-style] {+ transform: translate(-50%, -6px) scale(0.985);+}++/* ——— Recipients ——— */+.recipient-field {+ position: relative;+ cursor: text;+ padding: 4px 0;+}+.recipient-chips {+ flex: 1;+ min-width: 0;+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 4px;+}+.recipient-chips input {+ flex: 1;+ min-width: 120px;+ padding: 5px 0;+}+.recipient-chip {+ display: inline-flex;+ align-items: center;+ gap: 3px;+ height: 24px;+ max-width: 260px;+ padding: 0 4px 0 8px;+ overflow: hidden;+ font-size: 12px;+ white-space: nowrap;+ text-overflow: ellipsis;+ color: var(--text);+ background: var(--hover);+ border: 1px solid var(--border-strong);+ border-radius: 12px;+ cursor: default;+}+.recipient-chip.invalid {+ color: var(--red);+ border-color: color-mix(in srgb, var(--red) 45%, transparent);+ background: color-mix(in srgb, var(--red) 8%, transparent);+}+.recipient-chip button {+ display: grid;+ place-items: center;+ width: 16px;+ height: 16px;+ padding: 0;+ border: 0;+ border-radius: 50%;+ background: none;+ color: var(--muted);+}+.recipient-chip button:hover {+ color: var(--text-strong);+ background: var(--border-strong);+}+.compose-field > .compose-cc-toggle {+ align-self: flex-start;+ margin-top: 9px;+ padding: 0 2px;+}+.compose-field > .compose-cc-toggle:hover {+ color: var(--text);+}+.recipient-suggestions {+ position: absolute;+ z-index: 5;+ top: calc(100% + 4px);+ left: 43px;+ width: min(360px, calc(100% - 43px));+ padding: 4px;+ background: var(--raised);+ border: 1px solid var(--border-strong);+ border-radius: 8px;+ box-shadow: var(--shadow);+}+.recipient-suggestions button {+ display: flex;+ align-items: center;+ gap: 10px;+ width: 100%;+ padding: 6px 8px;+ text-align: left;+ border: 0;+ border-radius: 5px;+ background: none;+}+.recipient-suggestions button.active {+ background: var(--hover);+}+.recipient-suggestions span:not(.avatar) {+ min-width: 0;+}+.recipient-suggestions strong,+.recipient-suggestions small {+ display: block;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.recipient-suggestions strong {+ font-size: 12px;+ font-weight: 500;+}+.recipient-suggestions small {+ font-size: 11px;+ color: var(--muted);+}++.account-tile-button {+ display: inline-flex;+ padding: 0;+ border: 0;+ border-radius: 50%;+ background: none;+ transition: box-shadow 120ms;+}+.account-tile-button:hover,+.account-tile-button[data-popup-open] {+ box-shadow: 0 0 0 1px var(--border-strong);+}+.account-tile-button.dragging {+ box-shadow: 0 0 0 2px var(--accent-solid);+}+/* Opens from the settings dialog, so it has to sit above it. */+.account-avatar-menu {+ z-index: 130;+}++/* ——— Account setup ——— */+.form-label {+ display: block;+ margin-bottom: 6px;+ font-size: 12px;+ color: var(--secondary);+}+.field-error {+ display: block;+ margin-top: 5px;+ font-size: 11px;+ color: var(--red);+}+.form-field input[aria-invalid='true'] {+ border-color: color-mix(in srgb, var(--red) 70%, transparent);+}+.account-form-address {+ display: flex;+ align-items: baseline;+ gap: 10px;+}+.account-form-address > span {+ color: var(--secondary);+ overflow-wrap: anywhere;+}+.account-form-address .text-action {+ font-size: 12px;+}+.account-form-problem {+ margin: 14px 0 0;+}+.account-form-section-heading {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 12px;+ min-height: 26px;+}+.account-form-section-heading h4 {+ margin: 0;+}+.account-form-section-heading .button {+ margin-right: -8px;+ color: var(--muted);+}+.account-form-manual {+ margin-right: auto;+ margin-left: -10px;+ color: var(--muted);+}+.setup-lookup {+ display: flex;+ align-items: center;+ gap: 8px;+ min-height: 18px;+ margin-top: 12px;+ font-size: 12px;+ color: var(--muted);+}+.setup-notice {+ margin: 10px 0 4px;+}+.protocol-tag {+ display: inline-flex;+ align-items: center;+ height: 18px;+ padding: 0 6px;+ border: 1px solid var(--border-strong);+ border-radius: 4px;+ font-size: 10px;+ font-weight: 500;+ letter-spacing: 0.3px;+ color: var(--muted);+ white-space: nowrap;+ flex-shrink: 0;+}+.server-options {+ display: grid;+ gap: 6px;+ margin: 12px 0 10px;+}+.server-option {+ display: flex;+ align-items: center;+ gap: 10px;+ min-width: 0;+ padding: 9px 12px;+ border: 1px solid var(--border-strong);+ border-radius: 8px;+ font-size: 12px;+ color: var(--secondary);+ cursor: pointer;+ transition:+ border-color 120ms,+ background 120ms;+}+.server-option:hover {+ background: var(--hover);+}+.server-option.chosen {+ border-color: color-mix(in srgb, var(--accent-solid) 60%, transparent);+ background: var(--accent-tint);+ color: var(--text-strong);+}+.server-option.chosen .theme-radio {+ box-shadow: inset 0 0 0 4px var(--accent-solid);+}+.server-option:has(input:focus-visible),+.segmented-option:has(input:focus-visible) {+ outline: 2px solid var(--accent);+ outline-offset: 2px;+}+.server-option-title {+ min-width: 0;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.server-option-source {+ margin-left: auto;+ flex-shrink: 0;+ font-size: 11px;+ color: var(--muted);+}+.server-card {+ margin-top: 12px;+ padding: 12px 14px 4px;+ border: 1px solid var(--border-strong);+ border-radius: 8px;+ background: var(--field);+}+.server-card-heading {+ display: flex;+ align-items: center;+ gap: 10px;+ margin-bottom: 4px;+}+.server-card-source {+ font-size: 11px;+ color: var(--muted);+}+.server-summary {+ margin: 0;+ font-size: 12px;+}+.server-summary > div {+ display: grid;+ grid-template-columns: 118px minmax(0, 1fr);+ gap: 12px;+ padding: 8px 0;+}+.server-summary > div + div {+ border-top: 1px solid var(--border);+}+.server-summary dt {+ color: var(--muted);+}+.server-summary dd {+ display: flex;+ flex-wrap: wrap;+ gap: 4px 14px;+ margin: 0;+ min-width: 0;+ color: var(--text);+ overflow-wrap: anywhere;+}+.server-host {+ font-weight: 500;+ color: var(--text-strong);+}+.server-meta {+ color: var(--secondary);+ font-variant-numeric: tabular-nums;+}+.server-fields .form-field {+ margin-top: 14px;+}+.server-group {+ margin: 18px 0 0;+ padding: 0;+ border: 0;+ min-width: 0;+}+.server-group legend {+ padding: 0;+ font-size: 11px;+ font-weight: 500;+ color: var(--secondary);+}+.server-row {+ display: grid;+ grid-template-columns: minmax(0, 1fr) 76px auto;+ gap: 0 12px;+ align-items: start;+}+.server-row .form-field {+ margin-top: 8px;+}+.segmented {+ display: inline-flex;+ padding: 2px;+ gap: 2px;+ border: 1px solid var(--border-strong);+ border-radius: 7px;+ background: var(--field);+}+.segmented[data-disabled] {+ opacity: 0.5;+}+.segmented-option {+ display: inline-flex;+ align-items: center;+ height: 30px;+ padding: 0 11px;+ border-radius: 5px;+ font-size: 12px;+ color: var(--muted);+ white-space: nowrap;+ cursor: pointer;+ transition:+ background 120ms,+ color 120ms;+}+.segmented-option:hover {+ color: var(--text);+}+.segmented-option.chosen {+ background: var(--selected);+ color: var(--text-strong);+ font-weight: 500;+ box-shadow: 0 1px 2px #0000001a;+}+.connection-checks {+ list-style: none;+ margin: 10px 0 0;+ padding: 0;+ border: 1px solid var(--border-strong);+ border-radius: 8px;+}+.connection-check {+ display: grid;+ grid-template-columns: 16px 64px minmax(0, auto) minmax(0, 1fr);+ gap: 10px;+ align-items: baseline;+ padding: 10px 14px;+ font-size: 12px;+}+.connection-check + .connection-check {+ border-top: 1px solid var(--border);+}+.connection-check strong {+ font-weight: 500;+}+.connection-check-icon {+ display: flex;+ align-self: center;+ color: var(--muted);+}+.connection-check.ok .connection-check-icon,+.connection-check.ok .connection-check-result {+ color: var(--green);+}+.connection-check.failed .connection-check-icon,+.connection-check.failed .connection-check-result {+ color: var(--red);+}+.connection-check-host {+ color: var(--muted);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.connection-check-result {+ color: var(--muted);+ line-height: 1.5;+}+.connection-check-hint {+ margin: 10px 0 0;+ font-size: 11px;+ color: var(--muted);+}+.modal-body-text {+ margin: 0;+ font-size: 12px;+ line-height: 1.6;+ color: var(--secondary);+}++/* ——— Folder roles ——— */+.folder-modal {+ width: min(600px, calc(100vw - 40px));+}+.folder-roles {+ display: grid;+}+.folder-role {+ display: grid;+ grid-template-columns: minmax(0, 1fr) 220px;+ gap: 16px;+ align-items: center;+ padding: 12px 0;+}+.folder-role + .folder-role {+ border-top: 1px solid var(--border);+}+.folder-role-text {+ display: flex;+ flex-wrap: wrap;+ align-items: baseline;+ gap: 2px 10px;+ min-width: 0;+}+.folder-role-text label {+ color: var(--text);+}+.folder-role-text strong {+ font-size: 13px;+ font-weight: 500;+}+.folder-role-text p {+ flex-basis: 100%;+ margin: 0;+ font-size: 11px;+ color: var(--muted);+}+.folder-role-status {+ display: inline-flex;+ align-items: center;+ gap: 5px;+ font-size: 11px;+ color: var(--muted);+}+.folder-role-status.confirmed svg {+ color: var(--green);+}+.folder-role-status.uncertain {+ color: var(--accent);+}+.folder-role-dot {+ width: 6px;+ height: 6px;+ border-radius: 50%;+ background: var(--accent);+}+.folder-roles-loading {+ display: flex;+ align-items: center;+ gap: 8px;+ padding: 20px 0;+ font-size: 12px;+ color: var(--muted);+}++/* ——— Account list additions ——— */+.settings-account strong .protocol-tag {+ margin-left: 8px;+ vertical-align: 1px;+ height: 16px;+ font-size: 9px;+}+.settings-account small.outgoing-error {+ align-items: flex-start;+ margin-top: 3px;+}+.settings-account small.outgoing-error svg {+ flex-shrink: 0;+ margin-top: 2px;+}+.account-indexing {+ color: var(--muted);+}+.indexing-meter {+ display: inline-flex;+ align-items: center;+ gap: 10px;+ font-variant-numeric: tabular-nums;+}+.indexing-bar {+ position: relative;+ width: 72px;+ height: 3px;+ flex-shrink: 0;+ border-radius: 2px;+ background: var(--border-strong);+ overflow: hidden;+}+.indexing-bar > span {+ position: absolute;+ inset: 0 auto 0 0;+ border-radius: inherit;+ background: var(--accent);+ transition: width 400ms ease;+}++/* ——— Incomplete results ——— */+.indexing-notice {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ justify-content: space-between;+ gap: 4px 14px;+ padding: 8px 28px;+ border-bottom: 1px solid var(--border);+ font-size: 11px;+ color: var(--muted);+}++/* ——— Sending status ——— */+.draft-section-label {+ margin: 0;+ padding: 18px 32px 6px;+ font-size: 11px;+ font-weight: 500;+ color: var(--muted);+}+.submissions {+ border-bottom: 1px solid var(--border);+ padding-bottom: 6px;+}+.submission {+ display: flex;+ gap: 16px;+ align-items: flex-start;+ padding: 14px 32px;+}+.submission + .submission {+ border-top: 1px solid var(--border);+}+.submission-icon {+ display: flex;+ margin-top: 1px;+ color: var(--muted);+}+.submission-attention .submission-icon {+ color: var(--accent);+}+.submission-text {+ flex: 1;+ min-width: 0;+}+.submission-text strong {+ display: block;+ font-size: 13px;+ font-weight: 500;+ color: var(--text);+}+.submission-state {+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ gap: 4px 12px;+ margin-top: 3px;+ font-size: 12px;+ color: var(--secondary);+}+.submission-attention .submission-state {+ color: var(--text-strong);+}+.submission-account {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ font-size: 11px;+ color: var(--muted);+}+.submission-detail {+ display: block;+ margin-top: 4px;+ max-width: 560px;+ font-size: 11px;+ line-height: 1.6;+ color: var(--muted);+ overflow-wrap: anywhere;+}+.submission-actions {+ display: flex;+ flex-wrap: wrap;+ gap: 6px;+ margin-top: 10px;+}+.submission time {+ flex-shrink: 0;+ font-size: 11px;+ color: var(--muted);+}+.sidebar-sending > svg,+.sidebar-sending > span {+ color: var(--accent);+}+.sidebar-sending small {+ margin-left: auto;+}++/* ——— Unavailable actions ——— */+.menu-note {+ max-width: 240px;+ margin: 4px 0 0;+ padding: 7px 10px 5px;+ border-top: 1px solid var(--border);+ font-size: 11px;+ line-height: 1.5;+ color: var(--muted);+}+.command-text {+ min-width: 0;+}+.command-description {+ display: block;+ margin-top: 2px;+ font-size: 11px;+ color: var(--muted);+ white-space: normal;+}+.command-results button.unavailable .command-text > :first-child,+.command-results button.unavailable .command-icon,+.command-results button.unavailable .command-keys {+ opacity: 0.55;+}+.compose-warning-detail {+ display: block;+ margin-top: 2px;+ color: var(--muted);+}+@container (max-width: 680px) {+ .indexing-notice {+ padding-left: 20px;+ padding-right: 20px;+ }+ .submission,+ .draft-section-label {+ padding-left: 20px;+ padding-right: 20px;+ }+}+@media (max-width: 700px) {+ .server-row {+ grid-template-columns: minmax(0, 1fr) 76px;+ }+ .server-row > :last-child {+ grid-column: 1 / -1;+ }+ .folder-role {+ grid-template-columns: minmax(0, 1fr) 180px;+ }+ .server-option-source {+ display: none;+ }+}+.tooltip-with-hint {+ align-items: flex-start;+ max-width: 280px;+}+.tooltip-text {+ display: flex;+ flex-direction: column;+ gap: 2px;+}+.tooltip-hint {+ color: var(--muted);+ line-height: 1.5;+}+/* Unavailable but still focusable, so the tooltip can explain why. */+.button[aria-disabled='true'] {+ opacity: 0.4;+ cursor: default;+}+.button-ghost[aria-disabled='true']:hover {+ background: transparent;+ color: var(--secondary);+}diff --git a/apps/desktop/src/renderer/src/theme.ts b/apps/desktop/src/renderer/src/theme.tsnew file mode 100644index 0000000..4ba3f88--- /dev/null+++ b/apps/desktop/src/renderer/src/theme.ts@@ -0,0 +1,17 @@+import { useSyncExternalStore } from 'react'++const subscribe = (callback: () => void) => {+ const observer = new MutationObserver(callback)+ observer.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] })+ return () => observer.disconnect()+}+const snapshot = () => (document.documentElement.dataset.theme === 'light' ? 'light' : 'dark')++/** The theme actually applied to the document, after resolving “System”. */+export function useResolvedTheme(): 'light' | 'dark' {+ return useSyncExternalStore(subscribe, snapshot, () => 'dark')+}++/** Reads the current value of a theme token such as `--text`. */+export const token = (name: string) =>+ getComputedStyle(document.documentElement).getPropertyValue(name).trim()diff --git a/apps/desktop/src/renderer/src/vite-env.d.ts b/apps/desktop/src/renderer/src/vite-env.d.tsnew file mode 100644index 0000000..11f02fe--- /dev/null+++ b/apps/desktop/src/renderer/src/vite-env.d.ts@@ -0,0 +1 @@+/// <reference types="vite/client" />diff --git a/apps/desktop/tsconfig.json b/apps/desktop/tsconfig.jsonnew file mode 100644index 0000000..bb89615--- /dev/null+++ b/apps/desktop/tsconfig.json@@ -0,0 +1,9 @@+{+ "extends": "../../tsconfig.json",+ "include": ["src", "*.ts"],+ "compilerOptions": {+ "paths": {+ "@/*": ["./src/renderer/src/*"]+ }+ }+}diff --git a/apps/desktop/vite.web.config.ts b/apps/desktop/vite.web.config.tsnew file mode 100644index 0000000..be24dbb--- /dev/null+++ b/apps/desktop/vite.web.config.ts@@ -0,0 +1,44 @@+import { fileURLToPath } from 'node:url'+import { defineConfig } from 'vite'+import react from '@vitejs/plugin-react'+import tailwindcss from '@tailwindcss/vite'+import { SenderAvatarResolver } from './src/main/sender-avatar'++const avatars = new SenderAvatarResolver()++export default defineConfig({+ root: 'src/renderer',+ resolve: { alias: { '@': fileURLToPath(new URL('./src/renderer/src', import.meta.url)) } },+ plugins: [+ react(),+ tailwindcss(),+ {+ name: 'demo-sender-avatars',+ configureServer(server) {+ server.middlewares.use('/__demo/avatar', async (request, response) => {+ if (request.method !== 'GET') {+ response.statusCode = 405+ response.end()+ return+ }+ const email = new URL(request.url || '/', 'http://localhost').searchParams.get('email')+ if (!email || email.length > 320 || !/^[^@\s]+@[^@\s]+$/.test(email)) {+ response.statusCode = 400+ response.end()+ return+ }+ try {+ const image = await avatars.get(email)+ response.setHeader('Content-Type', 'application/json; charset=utf-8')+ response.setHeader('Cache-Control', 'private, max-age=900')+ response.end(JSON.stringify({ image }))+ } catch {+ response.statusCode = 500+ response.end()+ }+ })+ },+ },+ ],+ server: { port: 5173, fs: { allow: [fileURLToPath(new URL('../..', import.meta.url))] } },+})diff --git a/design/brand/relay-ii/README.md b/design/brand/relay-ii/README.mdnew file mode 100644index 0000000..2edefcb--- /dev/null+++ b/design/brand/relay-ii/README.md@@ -0,0 +1,17 @@+# Relay II++Selected logo: Relay II. This directory contains the retained brand artwork and exports.++- `mark.svg`: original single-colour mark with a transparent background; uses `currentColor`.+- `icon-1024.png`: 1024 × 1024 app icon with transparency outside the rounded tile.+- `preview.svg` / `preview.png`: presentation on a pale lavender background.++The editable app icon source is `apps/desktop/resources/icon.svg` at the repository root.+It uses SVG paths, gradients and shadows, with the original Relay II silhouette preserved.+The desktop icon, sidebar mark, favicon, About image and tray assets use this selected direction.++Regenerate desktop and tray PNGs with `python scripts/icon.py`. Regenerate the large export with:++```sh+rsvg-convert --width 1024 --height 1024 apps/desktop/resources/icon.svg -o design/brand/relay-ii/icon-1024.png+```diff --git a/design/brand/relay-ii/icon-1024.png b/design/brand/relay-ii/icon-1024.pngnew file mode 100644index 0000000..0e38c1fBinary files /dev/null and b/design/brand/relay-ii/icon-1024.png differdiff --git a/design/brand/relay-ii/mark.svg b/design/brand/relay-ii/mark.svgnew file mode 100644index 0000000..127e14a--- /dev/null+++ b/design/brand/relay-ii/mark.svg@@ -0,0 +1,3 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 96 96" fill="currentColor">+ <path d="M8 20h21l21 28-21 28H8l23-28Z"/><path d="M37 20h22c12 0 24 11 29 28-5 17-17 28-29 28H37l21-28Z"/>+</svg>diff --git a/design/brand/relay-ii/preview.png b/design/brand/relay-ii/preview.pngnew file mode 100644index 0000000..98a2e18Binary files /dev/null and b/design/brand/relay-ii/preview.png differdiff --git a/design/brand/relay-ii/preview.svg b/design/brand/relay-ii/preview.svgnew file mode 100644index 0000000..c9ae57a--- /dev/null+++ b/design/brand/relay-ii/preview.svg@@ -0,0 +1,85 @@+<svg xmlns="http://www.w3.org/2000/svg" width="800" height="760" viewBox="0 0 800 760">+<defs><linearGradient id="backdrop" x2="0" y2="1"><stop stop-color="#dfe3ff"/><stop offset="1" stop-color="#fff"/></linearGradient><radialGradient id="aura"><stop stop-color="#bdc3ff" stop-opacity=".35"/><stop offset="1" stop-color="#d8dcff" stop-opacity="0"/></radialGradient></defs>+<rect width="800" height="760" fill="url(#backdrop)"/>+<ellipse cx="400" cy="480" rx="355" ry="235" fill="url(#aura)"/>+<svg x="112" y="70" width="576" height="576" viewBox="0 0 512 512" fill="none">+ <defs>+ <path id="tile" d="M154 32h204c78 0 114 36 114 114v204c0 78-36 114-114 114H154c-78 0-114-36-114-114V146C40 68 76 32 154 32Z"/>+ <path id="rear" d="M8 20h21l21 28-21 28H8l23-28Z"/>+ <path id="front" d="M37 20h22c12 0 24 11 29 28-5 17-17 28-29 28H37l21-28Z"/>+ <linearGradient id="tile-colour" x1="122" y1="32" x2="351" y2="466" gradientUnits="userSpaceOnUse">+ <stop stop-color="#6268ef"/>+ <stop offset=".42" stop-color="#484bd3"/>+ <stop offset="1" stop-color="#292397"/>+ </linearGradient>+ <radialGradient id="tile-light" cx=".43" cy=".08" r=".85">+ <stop stop-color="#a9b2ff" stop-opacity=".28"/>+ <stop offset=".7" stop-color="#737bff" stop-opacity="0"/>+ </radialGradient>+ <linearGradient id="tile-rim" x1="200" y1="32" x2="270" y2="464" gradientUnits="userSpaceOnUse">+ <stop stop-color="#e4e7ff" stop-opacity=".42"/>+ <stop offset=".4" stop-color="#959bf5" stop-opacity=".08"/>+ <stop offset="1" stop-color="#131064" stop-opacity=".48"/>+ </linearGradient>+ <linearGradient id="rear-face" x1="20" y1="20" x2="39" y2="80" gradientUnits="userSpaceOnUse">+ <stop stop-color="#eeefff"/>+ <stop offset=".47" stop-color="#c4c8ff"/>+ <stop offset="1" stop-color="#8d91ed"/>+ </linearGradient>+ <linearGradient id="front-face" x1="48" y1="20" x2="81" y2="80" gradientUnits="userSpaceOnUse">+ <stop stop-color="#ffffff"/>+ <stop offset=".34" stop-color="#f5f7ff"/>+ <stop offset=".68" stop-color="#d5dcff"/>+ <stop offset="1" stop-color="#abb4f8"/>+ </linearGradient>+ <linearGradient id="rear-side" x1="9" y1="34" x2="33" y2="80" gradientUnits="userSpaceOnUse">+ <stop stop-color="#777be1"/>+ <stop offset="1" stop-color="#5e5cc9"/>+ </linearGradient>+ <linearGradient id="front-side" x1="38" y1="30" x2="75" y2="81" gradientUnits="userSpaceOnUse">+ <stop stop-color="#c0c9ff"/>+ <stop offset="1" stop-color="#797bd5"/>+ </linearGradient>+ <linearGradient id="face-rim" x1="48" y1="20" x2="48" y2="76" gradientUnits="userSpaceOnUse">+ <stop stop-color="#fff" stop-opacity=".8"/>+ <stop offset=".5" stop-color="#f4f7ff" stop-opacity=".25"/>+ <stop offset="1" stop-color="#7679d6" stop-opacity=".25"/>+ </linearGradient>+ <linearGradient id="polish" x1="49" y1="24" x2="67" y2="68" gradientUnits="userSpaceOnUse">+ <stop stop-color="#fff" stop-opacity="0"/>+ <stop offset=".48" stop-color="#fff" stop-opacity=".18"/>+ <stop offset="1" stop-color="#fff" stop-opacity="0"/>+ </linearGradient>+ <clipPath id="front-clip"><use href="#front"/></clipPath>+ <filter id="tile-shadow" x="-25%" y="-25%" width="150%" height="160%" color-interpolation-filters="sRGB">+ <feGaussianBlur stdDeviation="12"/>+ </filter>+ <filter id="mark-shadow" x="-30%" y="-35%" width="160%" height="180%" color-interpolation-filters="sRGB">+ <feGaussianBlur stdDeviation="1.6"/>+ </filter>+ <filter id="contact-shadow" x="-20%" y="-20%" width="140%" height="150%" color-interpolation-filters="sRGB">+ <feGaussianBlur stdDeviation=".45"/>+ </filter>+ </defs>+ <use href="#tile" transform="translate(0 15)" fill="#24206b" opacity=".26" filter="url(#tile-shadow)"/>+ <use href="#tile" transform="translate(0 3)" fill="#251e86"/>+ <use href="#tile" fill="url(#tile-colour)"/>+ <use href="#tile" fill="url(#tile-light)"/>+ <use href="#tile" stroke="url(#tile-rim)" stroke-width="1.5"/>+ <g transform="translate(88 80) scale(3.5)">+ <g transform="translate(.5 3.7)" fill="#17115d" opacity=".55" filter="url(#mark-shadow)">+ <use href="#rear"/><use href="#front"/>+ </g>+ <g transform="translate(.15 2.25)" fill="#21196e" opacity=".55" filter="url(#contact-shadow)">+ <use href="#rear"/><use href="#front"/>+ </g>+ <use href="#rear" transform="translate(0 1.65)" fill="url(#rear-side)"/>+ <use href="#front" transform="translate(0 1.65)" fill="url(#front-side)"/>+ <use href="#rear" fill="url(#rear-face)"/>+ <use href="#front" fill="url(#front-face)"/>+ <path d="m35 20 53 36v16L35 36Z" fill="url(#polish)" clip-path="url(#front-clip)"/>+ <g stroke="url(#face-rim)" stroke-width=".28" stroke-linejoin="round">+ <use href="#rear"/><use href="#front"/>+ </g>+ </g>+</svg></svg>\ No newline at end of filediff --git a/docs/architecture.md b/docs/architecture.mdnew file mode 100644index 0000000..29faca1--- /dev/null+++ b/docs/architecture.md@@ -0,0 +1,33 @@+# Architecture++`packages/core/src/model.ts` defines the shared domain and IPC contract, `mail.ts` holds pure mail helpers, and `schemas.ts` validates IPC arguments. The package index re-exports these modules so callers use one stable entry point. In the desktop main process, `MailService` coordinates providers and persistence; `mail-mutations.ts` plans folder and keyword patches and checks whether an undo is still safe after a concurrent change. The renderer's `App` coordinates route, query, selection, and action state. Sidebar, conversation rows, and independent dialogs live in their own components.++The renderer never receives passwords, authenticated fetch access, filesystem paths, or Node primitives. The main process exposes a fixed method list through a CommonJS sandbox-compatible preload. Each invocation must originate in the main application frame and pass its Zod tuple schema. The production renderer uses an application-specific secure scheme and a restrictive CSP.++`MailProvider` is the platform-independent boundary, implemented by `packages/jmap` and `packages/imap`. Saved connections are a discriminated JMAP/IMAP union (`ConnectionConfig`); records from before IMAP support are migrated explicitly to version 2 of the connections file, with the version 1 file kept as `connections.v1.backup.json`. Providers share `ProviderError` codes from core, so the service can tell incoming connection failures, outgoing login failures, conflicts, uncertain submissions and filing failures apart without knowing the protocol. Organization is planned as typed `MessageChange`s (folders and keywords to add or remove); JMAP turns them into patch paths, IMAP into STORE, MOVE, or COPY followed by UID EXPUNGE. On IMAP a message lives in one folder, so the planner never adds a folder without leaving one — archiving moves Inbox messages and leaves replies in Sent alone. Domain objects are scoped by connection, account, and remote ID. Equal subjects or remote IDs never merge across accounts. JMAP capability discovery, account capabilities, mailbox rights, object failures, state conflicts, upload limits, and sending identities are checked. The current provider deliberately accepts authenticated endpoints only on the configured origin. Read discovery redirects are bounded and same-origin.++JMAP mail lists use `Email/query` with `collapseThreads`, a 50-conversation window, and descending received time. Thread metadata is loaded only for that page; body values are fetched on demand. Unified pages independently fetch account windows and advance each cursor only by the items consumed from that account. An unavailable account is explicitly reported. A new search runs on the server, not merely over cached messages. Very long individual threads still require their metadata to establish whole-conversation read/star state.++TanStack Router carries mailbox, account, search text, and conversation navigation. Advanced filters remain in the current list's React state. TanStack Query wraps promise-returning IPC and owns async caching. Mutations use `networkMode: always` and no retry, so they fail explicitly instead of silently replaying later. TanStack Virtual limits DOM rows. TanStack Hotkeys owns input-safe keyboard commands. TanStack Form handles account/recipient fields; Tiptap owns rich text. DB, Store, and Table are not included.++Confirmed read results persist in IndexedDB, bounded to 80 recent query records, three initial pages per list, approximately 25 MB serialized, and seven days. Optimistic manual updates are not persisted. IndexedDB drafts have no cache eviction policy. The main process also durably saves drafts, staged attachments, and submission attempts with owner-only permissions and atomic file replacement. Storage envelopes carry version 1; unknown versions and malformed records fail closed and preserve the original files. Future schema changes require explicit migrations rather than silently clearing data.++Organization creates granular JMAP patches. Archive removes Inbox and adds Archive while keeping unrelated memberships. A JMAP state mismatch reports a conflict. Undo checks that the fields it would reverse still match the operation; concurrent changes are preserved and reported. Large operations collect matching conversation IDs before modifying membership so changes do not shift their own pagination. They report progress and partial failures. There is a 250,000-conversation safety bound and a bounded number of undo operations in memory.++Drafts save locally first. Server synchronization preserves local copies and compares a remote fingerprint before replacing an existing draft. A concurrent remote edit is reported. Submission records are persisted before the network submission call. Lost responses yield an uncertain state; retry checks existing submission records and Sent membership instead of resending. Staged files stay available after failures. Confirmed sends retain a small tombstone and submission record; their local body copies and unused staged files are released. A definitive rejection permits a subsequent deliberate retry.++Incoming HTML passes DOMPurify and is rendered inside a sandboxed frame with scripts, forms, navigation, and network access blocked by CSP. Main-frame validation rejects IPC from child frames. Ordinary links open externally. Inline image blobs and optional remote images are returned as raster data URLs. Remote resource requests have no login headers, cookies, or redirects; DNS results are checked and pinned to prevent private-network access. Remote images start enabled, as requested, and can be disabled in preferences.++Sender avatars use the same guarded public-resource path. A lookup tries a Gravatar portrait by SHA256 email hash, then the sender domain's HTTPS touch icon or advertised icon, then its favicon, and finally the initials avatar. Icon lookups follow at most three HTTPS redirects; every hop repeats public-address validation. Mail subdomains can fall back to their parent domain. Results and misses have bounded in-memory caches. Turning off remote images also disables sender image lookup.++Push uses authenticated JMAP event-source streams, bounded reconnection backoff, and independent periodic polling. Resume triggers reconciliation. The first mailbox refresh establishes a notification baseline; older messages newly entering the visible window do not produce notifications. Closing hides the window when a tray object exists and the preference is enabled; Quit exits. On desktops without a visible StatusNotifier host, disable the tray preference until a tray host is running.++## IMAP and SMTP++Discovery (`packages/core/src/discovery.ts`) is platform-independent with an injected transport: JMAP SRV and well-known first, then the domain's autoconfig files and RFC 6186 SRV, and the public Thunderbird directory only when the domain publishes nothing. Requests are unauthenticated, HTTPS-only, bounded in time, size and redirects; configuration XML goes through a small parser that rejects DTDs and entities.++Each IMAP connection keeps two connections: one idles on Inbox, one runs commands one at a time, with user actions ahead of background work. `ImapFlowPort` is the only code that talks to ImapFlow. It requires TLS or STARTTLS with verified certificates and refuses MOVE emulation and plain EXPUNGE, which would remove other clients' pending deletions. Tests replace it with an in-memory server (`tests/support/fake-imap.ts`).++Metadata lives in a SQLite index (`node:sqlite`) owned by a worker thread (`apps/desktop/src/main/imap-index`), one file per connection, owner-only. It stores folders with UIDVALIDITY, UIDNEXT, HIGHESTMODSEQ and indexing checkpoints, and messages with location, flags, headers, body structure and thread. Application IDs map to mailbox/UIDVALIDITY/UID and move with confirmed moves (COPYUID, or a Message-ID lookup in the destination); a UIDVALIDITY change discards that folder's locations. Conversations are grouped per account from Message-ID, References and In-Reply-To, never by subject; when a late ancestor joins two conversations the older ID survives and the other becomes an alias. Lists use keyset pagination, so indexing cannot shift what was already shown. Recent Inbox mail is indexed first, then the rest in bounded batches that never trigger notifications. Changes arrive through IDLE, CONDSTORE when available, and periodic reconciliation otherwise. Searches run on the server in each relevant folder and index unseen matches on the way.++Drafts are appended with `\Draft`; a replaced draft is removed only after the new copy is confirmed and the old one still matches what was read. Sending builds MIME without Bcc headers (Bcc recipients stay in the SMTP envelope and the local record), persists it with the envelope, Message-ID and journal, and only then submits. SMTP acceptance is recorded before the Sent copy is filed. Filing first looks for the attempt's Message-ID — both in server search and in recent envelopes, because search indexes can lag — so a server-created or earlier ambiguous copy is never duplicated, and only filing is retried. Lost final SMTP responses are uncertain and never resent; a Sent copy alone does not prove submission.diff --git a/docs/troubleshooting.md b/docs/troubleshooting.mdnew file mode 100644index 0000000..f0ef130--- /dev/null+++ b/docs/troubleshooting.md@@ -0,0 +1,39 @@+# Troubleshooting++## Connection++Use an HTTPS server URL reachable from this desktop. HTTP is accepted only for localhost test servers. Verify that Stalwart advertises the same public origin as the URL you entered, including its port. On current Stalwart, `STALWART_PUBLIC_URL` controls advertised endpoints behind a proxy. Configure the server; do not disable TLS verification or forward passwords to an unexpected origin.++Settings → Accounts shows each account's connection state and offers reconnect/sign-in. A failed account does not block successful accounts. “Mail changed on the server” means the write's state token no longer matches; refresh before trying again. Rate limits and per-message failures are displayed. A missing special-folder role must be configured on a JMAP server before the associated operation works; for IMAP accounts choose it under **Folders…**.++## IMAP and SMTP++If discovery finds nothing, use **Set up manually** with the settings from your provider. Inlark offers only implicit TLS (usually ports 993 and 465) and STARTTLS (usually 143 and 587). A certificate error means the server's certificate does not match its name or is not trusted by this system; fix the certificate or trust its CA system-wide rather than looking for a way to disable verification.++The connection check reports the incoming and outgoing servers separately. “Sending unavailable” on an account means only the outgoing login failed: mail can still be read, and **Sign in again** updates the outgoing password. Many providers need an app password when two-factor authentication is on.++“Still indexing — older mail may be missing” is expected after adding a large account; progress is shown in Settings → Accounts. Removing the account deletes its local index. If moving or permanent deletion is turned off for an account, the server lacks MOVE/UIDPLUS; ask its administrator, because the alternative could erase messages another app marked for deletion.++## NixOS and Wayland++Use `nix develop path:.` and the supplied `ELECTRON_EXEC_PATH`, or the Nix package. npm's generic Linux Electron binary usually needs a conventional Linux runtime. The Nix package uses the Nixpkgs Electron runtime and adapts to Wayland; pass `--ozone-platform=wayland` to force it for testing.++Use a StatusNotifier tray host (for example, a configured Waybar tray module) for close-to-tray. If a desktop accepts a tray object but has no visible tray host, disable “Keep running in the tray” in Settings. Without a Secret Service provider, you can choose to remember a password in the app's owner-only local data file; it is unencrypted. Leave the option unchecked for session-only login.++The `.deb` builder's downloaded Ruby/fpm may not execute on NixOS. `pnpm package:linux` uses Nix's fpm automatically. AppImage and `.deb` are intended for conventional Linux distributions; the Nix package is the preferred NixOS installation.++A NixOS AppImage `binfmt_misc` handler also applies to containers using the same kernel. If a present, executable AppImage reports “not found” inside a conventional Linux container, inspect the registered interpreter path: the container may not contain that host path. The native Nix package or the configured host AppImage handler avoids that container mismatch.++## Drafts and sending++Never delete the application storage directory to fix a draft or delivery problem. Local drafts, staged attachment files, outgoing MIME awaiting its Sent copy, submission records, and IMAP indexes live under the `mail` subdirectory of Electron's `userData`. The renderer keeps a separate IndexedDB copy of drafts. Cached mail can expire; drafts do not expire with it.++If sending fails, reopen the draft. Unresolved sends are listed under **Send status** in the sidebar. If delivery is **unconfirmed**, use **Check again**; SMTP servers cannot confirm delivery later, so for IMAP accounts check with a recipient or the server log. **Send a replacement…** creates a new draft and keeps the unconfirmed record. The app will not send that attempt again automatically. “Sent · Sent copy pending” means the outgoing server accepted the message; **Retry filing** only saves the copy. For a partial send, **Create draft to refused recipients** addresses only the refused recipients. If the server no longer retains enough evidence, inspect Sent and server logs before deliberately creating a replacement. Local drafts that conflict with a remote edit are kept; resolve the conflict before syncing over the server version.++If a storage file cannot be read or has a newer version, the application preserves it and refuses to overwrite it. Make a private backup of the complete profile before repair. Do not paste that backup into an issue: it contains mail and draft content.++## Diagnostics++Settings → About → Copy diagnostics includes application/runtime versions, connection statuses, and generic event codes. It excludes credentials, server addresses, email addresses, and message content. Review even redacted diagnostics before sharing. Main-process stderr may include a generic failed IPC method, but protocol bodies are not logged.++A native smoke test needs a fresh, explicitly separate `INLARK_DATA_DIR`. `--smoke-test` tests renderer-to-main IPC and starts the SQLite index worker, prints a compact result, and exits; it does not connect accounts or send mail.diff --git a/docs/validation.md b/docs/validation.mdnew file mode 100644index 0000000..b91e7ff--- /dev/null+++ b/docs/validation.md@@ -0,0 +1,58 @@+# Validation record++This is an initial working implementation. The checks below establish a reproducible development baseline; they do not establish that every daily-driver acceptance criterion has passed.++## Automated checks++Verified on September 23, 2026, on x86_64 NixOS/Hyprland:++- TypeScript checks across all four workspaces and a production Electron build.+- 32 deterministic tests: domain isolation, identity selection, draft/send validation, full pagination and chronological merging of five 50,000-conversation accounts, bounded JMAP pages, full-history search filters, same-origin discovery, rate limits, per-object failures, stale state, private storage, interrupted sends, failure of local persistence after successful sending, submission reconciliation, draft conflicts, background draft synchronization, undo after external changes, one unavailable account, and anonymous resource boundaries.+- Real Stalwart 0.16.23 integration: provision a disposable server, create 61 messages, verify 50 + 11 pagination and ordering, fetch Unicode body content, search, change flags, upload/download an attachment, save and submit a draft to the same disposable account, reconcile delivery, rename/delete a folder, restart the server, and rediscover the same account. The script removes its exact container and anonymous volumes afterward.+- A pinned Nix package build, including offline typechecks, tests, and bundling.+- AppImage and `.deb` generation with electron-builder. These packages are unsigned development artifacts with reserved development metadata.+- AppImage extraction and native startup/IPC through this machine’s configured NixOS AppImage handler, with an isolated profile.+- Packaged `.deb` startup and IPC in the isolated Debian 12 smoke harness described below.+- Native Electron startup and sandboxed preload-to-main IPC on NixOS/Wayland, using an isolated profile. The available credential backend reported unavailable; the app correctly offered session-only login.++Run `pnpm check`, `pnpm test:stalwart`, `nix build path:.`, and `pnpm package:linux` to reproduce the respective checks. Integration tests are intentionally skipped during the normal deterministic suite. They never target your live mail unless you explicitly replace the disposable-server configuration.++The conventional-Linux smoke harness is `bash scripts/test-deb.sh`. It extracts the generated `.deb` in a non-root Debian 12 container and checks packaged renderer/preload/main startup under Xvfb. The runtime container has no network and mounts only release artifacts, read-only. Its test-only Chromium `--no-sandbox` flag accommodates nested container namespaces; this is not a substitute for testing normal desktop sandboxing on a Debian installation. Production launchers do not include that flag. Direct AppImage execution inside that container was blocked by the host’s registered `/run/binfmt/appimage_type_2` handler, which is not present in the container; the exact AppImage instead passed through the configured handler on the NixOS host. Normal FUSE-based launch on a conventional desktop remains unverified.++## IMAP/SMTP and automatic setup++Verified on September 26, 2026, on x86_64 NixOS/Hyprland:++- `pnpm check`: formatting, TypeScript in all five workspaces, 192 deterministic tests, production build.+- Deterministic coverage added for discovery precedence and privacy (directory only as a fallback, domain only), bounded redirects/sizes and hostile XML; TLS/STARTTLS policy with no plaintext fallback; separate incoming/outgoing credentials and checks; secret-free connection settings; the version 1 → 2 connections migration (backup kept, malformed or newer files untouched); folder mapping review, creation under the server's layout, and user overrides; UIDVALIDITY resets, relocation across confirmed moves (COPYUID and Message-ID fallback), threading across folders and late ancestors with alias resolution, keyset pagination during indexing, server search, CONDSTORE and non-CONDSTORE flag reconciliation, IDLE, reconnection, concurrent flag changes, MOVE/UIDPLUS fallbacks and refusal, exact UID EXPUNGE; MIME round trips with Unicode, inline images and attachments; Bcc only in the envelope; draft replacement and conflicts; SMTP rejection, partial acceptance, lost final responses, crashes around journal writes, and failed or ambiguous Sent APPENDs, with no automatic resend of accepted or uncertain mail. A SQLite index fixture of 50,000 messages checks query plans and paging.+- `pnpm test:stalwart` against disposable Stalwart 0.16.23 with a test CA certificate: implicit TLS and STARTTLS on both IMAP and SMTP, rejection of an untrusted certificate and wrong passwords, indexing and threading of 61 messages, Unicode bodies, server search, flags/moves/permanent deletion observed through JMAP, drafts, a real partial SMTP acceptance (unknown Bcc recipient), duplicate-free Sent filing, delivery back into Inbox without a Bcc header, plus the existing JMAP suite. This run found that Stalwart's header search lags behind a fresh APPEND; filing now also compares recent envelopes.+- `nix build path:.` with the updated dependency hash; native `--smoke-test` of the Nix package, and of the `.deb` in the Debian 12 harness, both starting the SQLite index worker.+- The setup, account, indexing, recovery and limited-action flows in the browser fixture at 900px in both themes, mostly by keyboard.++Not yet verified: providers other than Stalwart (Dovecot, Cyrus, hosted services with app passwords), real accounts with years of mail across many folders, IDLE across sleep/resume and flaky networks, IMAP servers without IDLE/CONDSTORE/MOVE/UIDPLUS (covered only by the fake server), and the setup flow in the native window with a Secret Service keyring.++## Interactive checks++Checked in the browser fixture workspace at the desktop's 1380 × 900 default size:++- Dark and light themes, collapsible navigation, account identity, a white transactional email inside the dark reader, conversation navigation, and reply identity/recipient selection.+- A 250,000-conversation unified inbox renders roughly 27–41 conversation rows for the viewport and overscan. It does not create 250,000 DOM rows.+- Pointer-opened conversation → next conversation → Escape restored the exact recorded list offset and keyboard focus. Rows are marked read on opening, not by keyboard focus alone.+- Composer initial focus, To/Subject/body editing, local draft save and reopening, Unicode, shortcut-safe text inputs, dialog controls, and keyboard return to the list.++One warm stress-preview sample reported first meaningful paint about 236 ms after navigation and approximately 25 MB JavaScript heap. This was a browser development build with cached modules and synthetic mail. It is not a cold-start benchmark, a sustained-memory measurement, or a five-live-account timing guarantee. The native empty-profile smoke finished in approximately one second; that does not measure an authenticated cached inbox.++## Before relying on it as your only mail client++The remaining acceptance work needs realistic live-account and desktop conditions:++- Sustained use with five accounts, cold/cached startup and navigation measurements, long scrolling sessions, huge conversations, and bulk changes while other clients modify the same mailbox.+- Sleep/resume, network flapping, changed credentials, missed push events, server throttling, initial notification suppression, real notification/tray interaction, and OS `mailto:` registration on the actual desktop.+- A secure Secret Service backend: remember, lock/unlock, restart, and reconnect. Only the unavailable-backend path was exercised on this machine.+- Broad rendering checks for newsletters, malformed HTML, inline images, quoted content, and large attachments; actual screen-reader and contrast auditing in both themes, plus reduced-motion operation.+- Failure injection for interrupted uploads and filesystem exhaustion, and draft conflict/recovery exercises across two independently running clients.+- Normal installed `.deb` and AppImage sessions on a conventional Linux desktop, including its Chromium sandbox and tray integration. ARM64 is declared in the Nix flake but has not been built here.++Current deliberate limits: authenticated JMAP endpoints must share the configured origin; IMAP accounts use password or app-password login and one sending address, and read mail from a local index that fills in over time; files over 100 MB cannot be attached/downloaded; server body values are capped at 5 MB; only previously fetched mail is available offline; and all-matching operations are limited to 250,000 conversations. Remote-image fetching blocks private-network resources and redirects. Search excludes junk/trash unless that folder is selected. Folder deletion does not implicitly delete contained messages; a server can refuse deletion of a populated folder.++Future schema versions need explicit migrations. Version 1 currently preserves and refuses unsupported/corrupt storage rather than attempting destructive repair. Ambiguous sends may remain unconfirmed if the server cannot provide evidence; inspect Sent/server logs before deliberately creating another message.diff --git a/flake.lock b/flake.locknew file mode 100644index 0000000..631dde9--- /dev/null+++ b/flake.lock@@ -0,0 +1,27 @@+{+ "nodes": {+ "nixpkgs": {+ "locked": {+ "lastModified": 1790046670,+ "narHash": "sha256-MYiI+CzL0tuWgRPjGsKCDHqYs2T3OzMlMQWOYWG0qso=",+ "owner": "NixOS",+ "repo": "nixpkgs",+ "rev": "6774f7bc253789b113a4f39285dc0fa100abeacc",+ "type": "github"+ },+ "original": {+ "owner": "NixOS",+ "ref": "nixos-unstable",+ "repo": "nixpkgs",+ "type": "github"+ }+ },+ "root": {+ "inputs": {+ "nixpkgs": "nixpkgs"+ }+ }+ },+ "root": "root",+ "version": 7+}diff --git a/flake.nix b/flake.nixnew file mode 100644index 0000000..d2e7241--- /dev/null+++ b/flake.nix@@ -0,0 +1,26 @@+{+ description = "Inlark — a considered home for your email";+ inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";+ outputs = { self, nixpkgs }:+ let+ systems = [ "x86_64-linux" "aarch64-linux" ];+ eachSystem = f: nixpkgs.lib.genAttrs systems (system: f (import nixpkgs { inherit system; }));+ in {+ packages = eachSystem (pkgs: rec {+ inlark = pkgs.callPackage ./nix/package.nix { };+ default = inlark;+ });+ nixosModules.default = import ./nix/module.nix self;+ devShells = eachSystem (pkgs: {+ default = pkgs.mkShell {+ packages = with pkgs; [ nodejs_24 pnpm_12 electron_44 python3 ];+ ELECTRON_SKIP_BINARY_DOWNLOAD = "1";+ ELECTRON_EXEC_PATH = "${pkgs.electron_44}/bin/electron";+ shellHook = ''+ export ELECTRON_OZONE_PLATFORM_HINT=auto+ '';+ };+ });+ checks = eachSystem (pkgs: { build = self.packages.${pkgs.stdenv.hostPlatform.system}.default; });+ };+}diff --git a/nix/module.nix b/nix/module.nixnew file mode 100644index 0000000..6b42727--- /dev/null+++ b/nix/module.nix@@ -0,0 +1,10 @@+self: { config, lib, pkgs, ... }:+let+ cfg = config.programs.inlark;+in {+ options.programs.inlark.enable = lib.mkEnableOption "Inlark email client";++ config = lib.mkIf cfg.enable {+ environment.systemPackages = [ self.packages.${pkgs.stdenv.hostPlatform.system}.default ];+ };+}diff --git a/nix/package.nix b/nix/package.nixnew file mode 100644index 0000000..11ed074--- /dev/null+++ b/nix/package.nix@@ -0,0 +1,53 @@+{ lib, stdenv, nodejs_24, pnpm_12, fetchPnpmDeps, pnpmConfigHook, makeWrapper, makeDesktopItem, copyDesktopItems, electron_44 }:+stdenv.mkDerivation (finalAttrs: {+ pname = "inlark";+ version = "0.1.0";+ src = lib.cleanSourceWith {+ src = ../.;+ filter = path: type: !(builtins.elem (baseNameOf path) [ "node_modules" ".pnpm-store" ".turbo" "out" "release" ".git" ".test-data" "result" "test-results" ]);+ };+ nativeBuildInputs = [ nodejs_24 pnpm_12 pnpmConfigHook makeWrapper copyDesktopItems ];+ pnpmDeps = fetchPnpmDeps {+ inherit (finalAttrs) pname version src;+ pnpm = pnpm_12;+ fetcherVersion = 4;+ postPatch = "sed -i /storeDir:/d pnpm-workspace.yaml";+ hash = "sha256-Y9UxkC2iCNqaNUB9l+BaaMQu8NJ3Pw1iTK/bTYDUR9g=";+ };+ postPatch = "sed -i /storeDir:/d pnpm-workspace.yaml";+ ELECTRON_SKIP_BINARY_DOWNLOAD = "1";+ buildPhase = ''+ runHook preBuild+ pnpm typecheck+ pnpm test+ pnpm --filter @inlark/desktop build+ runHook postBuild+ '';+ desktopItems = [ (makeDesktopItem {+ name = "inlark";+ desktopName = "Inlark";+ genericName = "Email client";+ exec = "inlark %U";+ icon = "inlark";+ categories = [ "Network" "Email" ];+ mimeTypes = [ "x-scheme-handler/mailto" ];+ startupWMClass = "inlark";+ }) ];+ installPhase = ''+ runHook preInstall+ mkdir -p $out/share/inlark $out/share/icons/hicolor/512x512/apps+ cp -r apps/desktop/out apps/desktop/resources $out/share/inlark/+ cp apps/desktop/package.json $out/share/inlark/+ cp apps/desktop/resources/icon.png $out/share/icons/hicolor/512x512/apps/inlark.png+ makeWrapper ${electron_44}/bin/electron $out/bin/inlark \+ --add-flags "$out/share/inlark" \+ --set-default ELECTRON_OZONE_PLATFORM_HINT auto+ runHook postInstall+ '';+ meta = {+ description = "Keyboard-friendly JMAP and IMAP email client for Linux";+ license = lib.licenses.agpl3Only;+ mainProgram = "inlark";+ platforms = lib.platforms.linux;+ };+})diff --git a/package.json b/package.jsonnew file mode 100644index 0000000..77decf1--- /dev/null+++ b/package.json@@ -0,0 +1,29 @@+{+ "name": "inlark",+ "private": true,+ "license": "AGPL-3.0-only",+ "packageManager": "[email protected]",+ "scripts": {+ "dev": "pnpm --filter @inlark/desktop dev",+ "dev:web": "pnpm --filter @inlark/desktop dev:web",+ "build": "turbo build",+ "typecheck": "turbo typecheck",+ "test": "vitest run",+ "check": "pnpm format:check && pnpm typecheck && pnpm test && pnpm build",+ "package:linux": "bash scripts/package-linux.sh",+ "test:integration": "vitest run --no-file-parallelism tests/stalwart.integration.test.ts tests/stalwart-imap.integration.test.ts",+ "test:stalwart": "node scripts/stalwart-test.mjs",+ "format": "prettier --write .",+ "format:check": "prettier --check .",+ "test:deb": "bash scripts/test-deb.sh"+ },+ "devDependencies": {+ "@types/node": "^24.0.0",+ "@types/smtp-server": "^3.5.13",+ "prettier": "^3.9.8",+ "smtp-server": "^3.19.13",+ "turbo": "^2.5.0",+ "typescript": "^5.9.0",+ "vitest": "^3.2.0"+ }+}diff --git a/packages/core/package.json b/packages/core/package.jsonnew file mode 100644index 0000000..57466ab--- /dev/null+++ b/packages/core/package.json@@ -0,0 +1,16 @@+{+ "name": "@inlark/core",+ "version": "0.1.0",+ "private": true,+ "license": "AGPL-3.0-only",+ "type": "module",+ "exports": {+ ".": "./src/index.ts"+ },+ "scripts": {+ "typecheck": "tsc -p tsconfig.json"+ },+ "dependencies": {+ "zod": "^4.0.0"+ }+}diff --git a/packages/core/src/discovery.ts b/packages/core/src/discovery.tsnew file mode 100644index 0000000..a6d019d--- /dev/null+++ b/packages/core/src/discovery.ts@@ -0,0 +1,419 @@+import type { DiscoveryCandidate, DiscoveryResult, DiscoverySource, ServerSettings } from './model'+import { serverSettingsSchema, serverUrlSchema } from './schemas'++export interface SrvRecord {+ name: string+ port: number+ priority: number+ weight: number+}+export interface DiscoveryResponse {+ status: number+ /** Lowercase header names. */+ headers: Record<string, string>+ body: string+}+/** Platform adapter for discovery. It never receives credentials, cookies, or the address itself. */+export interface DiscoveryTransport {+ /** Resolves SRV records. Resolves [] when none exist (NXDOMAIN/NODATA). */+ resolveSrv(name: string): Promise<SrvRecord[]>+ /** One unauthenticated GET. Never follows redirects, never sends credentials or cookies, and stops reading after maxBytes (reject). */+ get(url: string, options: { timeoutMs: number; maxBytes: number }): Promise<DiscoveryResponse>+}+export interface DiscoveryOptions {+ /** Discovery returns whatever it found by then. */+ deadlineMs?: number+ requestTimeoutMs?: number+}++const maxBytes = 256 * 1024+const maxRedirects = 3+const dnsName = /^(?!-)[a-z0-9-]{1,63}(?<!-)(\.(?!-)[a-z0-9-]{1,63}(?<!-))*$/+const ipv4 = /^\d{1,3}(\.\d{1,3}){3}$/++/**+ * Finds likely server settings for an address. Only the domain leaves the device: requests are+ * unauthenticated, bounded, HTTPS-only, and the public directory is only consulted, with the+ * domain alone, when the domain publishes no settings itself.+ * Throws for a malformed address; an IP-literal domain has nothing to discover and yields no+ * candidates. Individual sources that fail, time out, or return malformed data are skipped.+ */+export async function discoverAccount(+ email: string,+ transport: DiscoveryTransport,+ options: DiscoveryOptions = {},+): Promise<DiscoveryResult> {+ const address = email.trim()+ const at = address.lastIndexOf('@')+ const local = address.slice(0, at)+ const rawDomain = address+ .slice(at + 1)+ .trim()+ .toLowerCase()+ .replace(/\.$/, '')+ if (at < 1 || !rawDomain || address.length > 320 || /\s/.test(local))+ throw new Error('Enter a valid email address.')+ if (rawDomain.startsWith('[') || ipv4.test(rawDomain))+ return { email: address, domain: rawDomain, candidates: [] }+ const domain = asciiDomain(rawDomain)+ if (!domain) throw new Error('Enter a valid email address.')+ if (ipv4.test(domain)) return { email: address, domain, candidates: [] }++ const timeoutMs = options.requestTimeoutMs ?? 6000+ const context: Context = { transport, timeoutMs, email: address }+ const autoconfigUrls = [+ `https://autoconfig.${domain}/mail/config-v1.1.xml`,+ `https://${domain}/.well-known/autoconfig/mail/config-v1.1.xml`,+ ]+ // Listed in order of preference; they run concurrently and are ordered afterwards.+ const sources: (() => Promise<DiscoveryCandidate[]>)[] = [+ () => jmapSrv(context, domain),+ () => jmapWellKnown(context, domain),+ ...autoconfigUrls.map((url) => () => autoconfig(context, url, 'autoconfig')),+ () => imapSrv(context, domain),+ ]+ const deadline = Date.now() + (options.deadlineMs ?? 15000)+ const run = async (list: (() => Promise<DiscoveryCandidate[]>)[]) => {+ const found: (DiscoveryCandidate[] | undefined)[] = list.map(() => undefined)+ const all = Promise.allSettled(+ list.map(async (source, index) => {+ found[index] = await source()+ }),+ )+ let timer: ReturnType<typeof setTimeout> | undefined+ await Promise.race([+ all,+ new Promise<void>(+ (resolve) => (timer = setTimeout(resolve, Math.max(0, deadline - Date.now()))),+ ),+ ])+ clearTimeout(timer)+ return found.flatMap((c) => c || [])+ }+ let found = await run(sources)+ // The public directory learns which domain is being set up, so it is only asked when the+ // domain itself publishes nothing. Self-hosted domains are never disclosed to it.+ if (!found.length && Date.now() < deadline)+ found = await run([+ () =>+ autoconfig(+ context,+ `https://autoconfig.thunderbird.net/v1.1/${encodeURIComponent(domain)}`,+ 'directory',+ ),+ ])+ const seen = new Set<string>()+ const candidates = found.filter((c) => {+ const key = candidateKey(c)+ if (seen.has(key)) return false+ seen.add(key)+ return true+ })+ return {+ email: address,+ domain,+ candidates: [+ ...candidates.filter((c) => c.protocol === 'jmap'),+ ...candidates.filter((c) => c.protocol === 'imap'),+ ],+ }+}++interface Context {+ transport: DiscoveryTransport+ timeoutMs: number+ email: string+}++function asciiDomain(value: string): string | undefined {+ if (/[/?#@:\\%\s]/.test(value)) return undefined+ try {+ // URL applies IDNA, so internationalised domains are looked up in their ASCII form.+ const host = new URL(`https://${value}/`).hostname+ return dnsName.test(host) ? host : undefined+ } catch {+ return undefined+ }+}+function candidateKey(c: DiscoveryCandidate): string {+ const server = (s: ServerSettings) => [s.host, s.port, s.security, s.username]+ return JSON.stringify(+ c.protocol === 'jmap'+ ? ['jmap', c.serverUrl, c.username]+ : ['imap', server(c.incoming), server(c.outgoing)],+ )+}+/** Guards against transports that ignore their own timeout. */+function bounded<T>(promise: Promise<T>, ms: number): Promise<T> {+ let timer: ReturnType<typeof setTimeout> | undefined+ return Promise.race([+ promise,+ new Promise<never>(+ (_, reject) => (timer = setTimeout(() => reject(new Error('Request timed out.')), ms)),+ ),+ ]).finally(() => clearTimeout(timer))+}+async function srv(context: Context, name: string): Promise<SrvRecord | undefined> {+ const records = await bounded(context.transport.resolveSrv(name), context.timeoutMs)+ // RFC 2782: a lone "." target means the service is deliberately not offered.+ return records+ .map((r) => ({ ...r, name: r.name.toLowerCase().replace(/\.$/, '') }))+ .filter((r) => dnsName.test(r.name) && Number.isInteger(r.port) && r.port > 0 && r.port < 65536)+ .sort((a, b) => a.priority - b.priority || b.weight - a.weight)[0]+}+/** Follows up to three HTTPS redirects itself, so every hop is checked before it is requested. */+async function fetchFollowing(+ context: Context,+ start: string,+): Promise<{ url: URL; response: DiscoveryResponse }> {+ let url = new URL(start)+ for (let hop = 0; ; hop++) {+ if (url.protocol !== 'https:' || url.username || url.password)+ throw new Error('Discovery only follows HTTPS addresses.')+ url.hash = ''+ const response = await bounded(+ context.transport.get(url.toString(), { timeoutMs: context.timeoutMs, maxBytes }),+ context.timeoutMs,+ )+ if (response.body.length > maxBytes) throw new Error('Discovery response is too large.')+ const location = response.headers.location+ if (![301, 302, 303, 307, 308].includes(response.status) || !location) return { url, response }+ if (hop >= maxRedirects) throw new Error('Too many redirects.')+ url = new URL(location, url)+ }+}+async function jmapSrv(context: Context, domain: string): Promise<DiscoveryCandidate[]> {+ const record = await srv(context, `_jmap._tcp.${domain}`)+ if (!record) return []+ const serverUrl = `https://${record.name}${record.port === 443 ? '' : `:${record.port}`}`+ return [{ protocol: 'jmap', source: 'jmap-srv', serverUrl, username: context.email }]+}+async function jmapWellKnown(context: Context, domain: string): Promise<DiscoveryCandidate[]> {+ const { url, response } = await fetchFollowing(context, `https://${domain}/.well-known/jmap`)+ const evidence =+ // RFC 8620 requires authentication here. A 403 is too often a blanket firewall answer.+ response.status === 401 || (response.status === 200 && hasCapabilities(response.body))+ if (!evidence) return []+ // The provider only authenticates to the configured origin, so show where the redirects ended.+ const serverUrl = url.pathname === '/.well-known/jmap' ? url.origin : url.toString()+ if (!serverUrlSchema.safeParse(serverUrl).success) return []+ return [{ protocol: 'jmap', source: 'jmap-well-known', serverUrl, username: context.email }]+}+function hasCapabilities(body: string): boolean {+ try {+ const session: unknown = JSON.parse(body)+ return (+ typeof session === 'object' &&+ session !== null &&+ typeof (session as { capabilities?: unknown }).capabilities === 'object' &&+ (session as { capabilities?: unknown }).capabilities !== null+ )+ } catch {+ return false+ }+}+async function autoconfig(+ context: Context,+ url: string,+ source: DiscoverySource,+): Promise<DiscoveryCandidate[]> {+ const { response } = await fetchFollowing(context, url)+ if (response.status !== 200) return []+ const config = parseAutoconfig(response.body, context.email)+ const incoming = preferTls(config.incoming)+ const outgoing = preferTls(config.outgoing)+ if (!incoming || !outgoing) return []+ return [+ {+ protocol: 'imap',+ source,+ incoming,+ outgoing,+ ...(config.provider ? { provider: config.provider } : {}),+ },+ ]+}+const preferTls = (servers: ServerSettings[]) =>+ servers.find((s) => s.security === 'tls') || servers[0]+async function imapSrv(context: Context, domain: string): Promise<DiscoveryCandidate[]> {+ const lookup = async (service: string, security: ServerSettings['security']) => {+ const record = await srv(context, `_${service}._tcp.${domain}`).catch(() => undefined)+ if (!record) return undefined+ const settings = { host: record.name, port: record.port, security, username: context.email }+ return serverSettingsSchema.safeParse(settings).success ? settings : undefined+ }+ // RFC 8314 prefers implicit TLS over STARTTLS when both are published.+ const [imaps, imap, submissions, submission] = await Promise.all([+ lookup('imaps', 'tls'),+ lookup('imap', 'starttls'),+ lookup('submissions', 'tls'),+ lookup('submission', 'starttls'),+ ])+ const incoming = imaps || imap+ const outgoing = submissions || submission+ return incoming && outgoing ? [{ protocol: 'imap', source: 'imap-srv', incoming, outgoing }] : []+}++const passwordAuth = new Set([+ 'password-cleartext',+ 'password-encrypted',+ // Older configuration files use these names for the same methods.+ 'plain',+ 'secure',+])+/**+ * Reads the IMAP and SMTP servers from a Thunderbird autoconfig file. Plaintext connections and+ * servers that only offer OAuth, Kerberos, NTLM, client certificates, or no authentication are+ * left out. Throws when the XML is malformed or uses constructs outside the tiny safe subset.+ */+export function parseAutoconfig(+ xml: string,+ email: string,+): { provider?: string; incoming: ServerSettings[]; outgoing: ServerSettings[] } {+ const root = parseXml(xml)+ if (root.name !== 'clientConfig') throw new Error('Not an autoconfig file.')+ const provider = root.children.find((c) => c.name === 'emailProvider')+ if (!provider) return { incoming: [], outgoing: [] }+ const at = email.lastIndexOf('@')+ const substitute = (value: string) =>+ value+ .replace(/%EMAILADDRESS%/g, email)+ .replace(/%EMAILLOCALPART%/g, email.slice(0, at))+ .replace(/%EMAILDOMAIN%/g, email.slice(at + 1).toLowerCase())+ const servers = (tag: string, type: string) =>+ provider.children+ .filter((c) => c.name === tag && c.attributes.type?.toLowerCase() === type)+ .flatMap((server): ServerSettings[] => {+ const text = (name: string) =>+ server.children.find((c) => c.name === name)?.text.trim() || ''+ const socket = text('socketType').toUpperCase()+ const security = socket === 'SSL' ? 'tls' : socket === 'STARTTLS' ? 'starttls' : undefined+ const auth = server.children+ .filter((c) => c.name === 'authentication')+ .map((c) => c.text.trim().toLowerCase())+ if (!security || (auth.length && !auth.some((a) => passwordAuth.has(a)))) return []+ const port = text('port')+ const settings = {+ host: substitute(text('hostname')).toLowerCase().replace(/\.$/, ''),+ port: /^\d{1,5}$/.test(port) ? Number(port) : 0,+ security,+ username: substitute(text('username')) || email,+ }+ const parsed = serverSettingsSchema.safeParse(settings)+ return parsed.success ? [parsed.data] : []+ })+ const name = ['displayName', 'displayShortName']+ .map((n) =>+ provider.children+ .find((c) => c.name === n)+ ?.text.replace(/\s+/g, ' ')+ .trim(),+ )+ .find(Boolean)+ return {+ ...(name ? { provider: name.slice(0, 100) } : {}),+ incoming: servers('incomingServer', 'imap'),+ outgoing: servers('outgoingServer', 'smtp'),+ }+}++interface XmlElement {+ name: string+ attributes: Record<string, string>+ children: XmlElement[]+ text: string+}+const xmlName = /^[A-Za-z_][\w.-]*(:[A-Za-z_][\w.-]*)?$/+const entities: Record<string, string> = { lt: '<', gt: '>', amp: '&', quot: '"', apos: "'" }+function invalid(): never {+ throw new Error('The configuration file is not valid.')+}+/**+ * A deliberately small XML reader for configuration files: no DTDs, no custom entities, no+ * processing instructions, bounded size, depth, and element count. Anything else is rejected.+ */+function parseXml(input: string): XmlElement {+ if (input.length > maxBytes) throw new Error('The configuration file is too large.')+ let xml = input.replace(/^\uFEFF/, '')+ const declaration = /^\s*<\?xml\s[^<>?]*\?>/.exec(xml)+ if (declaration) xml = xml.slice(declaration[0].length)+ const stack: XmlElement[] = []+ let root: XmlElement | undefined+ let count = 0+ let i = 0+ const addText = (value: string) => {+ const parent = stack[stack.length - 1]+ if (parent) parent.text += value+ else if (value.trim()) invalid()+ }+ while (i < xml.length) {+ const lt = xml.indexOf('<', i)+ if (lt === -1) {+ addText(decode(xml.slice(i)))+ break+ }+ if (lt > i) addText(decode(xml.slice(i, lt)))+ if (xml.startsWith('<!--', lt)) {+ const end = xml.indexOf('-->', lt + 4)+ if (end === -1) invalid()+ i = end + 3+ } else if (xml.startsWith('<![CDATA[', lt)) {+ const end = xml.indexOf(']]>', lt + 9)+ if (end === -1 || !stack.length) invalid()+ addText(xml.slice(lt + 9, end))+ i = end + 3+ } else if (xml[lt + 1] === '!' || xml[lt + 1] === '?') {+ // DOCTYPE, ENTITY, and processing instructions are where XML parsers get into trouble.+ invalid()+ } else {+ const end = xml.indexOf('>', lt)+ if (end === -1) invalid()+ i = end + 1+ if (xml[lt + 1] === '/') {+ if (stack.pop()?.name !== xml.slice(lt + 2, end).trim()) invalid()+ continue+ }+ let tag = xml.slice(lt + 1, end)+ const selfClosing = tag.endsWith('/')+ if (selfClosing) tag = tag.slice(0, -1)+ const name = /^\S*/.exec(tag)![0]+ if (!xmlName.test(name) || (root && !stack.length)) invalid()+ if (++count > 4096 || stack.length >= 32) invalid()+ const element: XmlElement = {+ name,+ attributes: parseAttributes(tag.slice(name.length)),+ children: [],+ text: '',+ }+ if (stack.length) stack[stack.length - 1].children.push(element)+ else root = element+ if (!selfClosing) stack.push(element)+ }+ }+ if (!root || stack.length) invalid()+ return root+}+function parseAttributes(source: string): Record<string, string> {+ const attributes: Record<string, string> = Object.create(null)+ const pattern = /\s+([A-Za-z_][\w.:-]*)\s*=\s*(?:"([^"<]*)"|'([^'<]*)')/y+ let index = 0+ while (source.slice(index).trim()) {+ pattern.lastIndex = index+ const match = pattern.exec(source)+ if (!match || match[1] in attributes) invalid()+ attributes[match[1]] = decode(match[2] ?? match[3])+ index = pattern.lastIndex+ }+ return attributes+}+/** Only the five predefined entities and numeric character references exist here. */+function decode(value: string): string {+ return value.replace(/&([^;&\s]{0,10});?/g, (reference, body: string) => {+ if (!reference.endsWith(';')) invalid()+ if (Object.hasOwn(entities, body)) return entities[body]+ const numeric = /^#(?:x([0-9a-fA-F]{1,6})|(\d{1,7}))$/.exec(body)+ const code = numeric ? parseInt(numeric[1] ?? numeric[2], numeric[1] ? 16 : 10) : NaN+ if (!(code > 0 && code <= 0x10ffff) || (code >= 0xd800 && code <= 0xdfff)) invalid()+ return String.fromCodePoint(code)+ })+}diff --git a/packages/core/src/errors.ts b/packages/core/src/errors.tsnew file mode 100644index 0000000..09c0023--- /dev/null+++ b/packages/core/src/errors.ts@@ -0,0 +1,45 @@+/**+ * Codes shared by every provider so the service can react without knowing the protocol.+ *+ * - `network` / `authentication` / `tls`: the incoming connection is unavailable.+ * - `outgoingNetwork` / `outgoingAuthentication`: the outgoing server is unavailable; nothing was sent.+ * - `submissionRejected`: the server refused the message; nothing was sent.+ * - `submissionUncertain`: the message may have been sent. Never retry automatically.+ * - `filing` / `filingUncertain`: the message was sent, but its Sent copy is not confirmed.+ * - `conflict` / `stateMismatch`: mail changed elsewhere since it was read.+ * - `unsupported`: the server lacks a capability this action needs to be safe.+ */+export type ProviderErrorCode =+ | 'network'+ | 'authentication'+ | 'tls'+ | 'outgoingNetwork'+ | 'outgoingAuthentication'+ | 'submissionRejected'+ | 'submissionUncertain'+ | 'filing'+ | 'filingUncertain'+ | 'conflict'+ | 'stateMismatch'+ | 'unsupported'+ | 'rateLimit'+ | 'notFound'+ | 'permission'+ | (string & {})++export class ProviderError extends Error {+ constructor(+ public code: ProviderErrorCode,+ message: string,+ public retryAfter?: number,+ ) {+ super(message)+ this.name = 'ProviderError'+ }+}++/** Errors meaning the incoming server cannot currently be used at all. */+export const connectionErrorCodes: readonly string[] = ['network', 'authentication', 'http', 'tls']++export const isProviderError = (error: unknown, ...codes: string[]): error is ProviderError =>+ error instanceof ProviderError && (!codes.length || codes.includes(error.code))diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsnew file mode 100644index 0000000..b5f3e34--- /dev/null+++ b/packages/core/src/index.ts@@ -0,0 +1,5 @@+export * from './model'+export * from './mail'+export * from './errors'+export * from './schemas'+export * from './discovery'diff --git a/packages/core/src/mail.ts b/packages/core/src/mail.tsnew file mode 100644index 0000000..6e61732--- /dev/null+++ b/packages/core/src/mail.ts@@ -0,0 +1,160 @@+import type {+ Address,+ Conversation,+ Draft,+ Identity,+ Message,+ ProviderPage,+ QueryPage,+} from './model'++export const scopeKey = (accountId: string, id: string) => JSON.stringify([accountId, id])+export const accountKey = (connectionId: string, remoteId: string) =>+ JSON.stringify([connectionId, remoteId])+export const identityKey = (accountId: string, id: string) => scopeKey(accountId, id)+export function conversationFromMessages(+ accountId: string,+ threadId: string,+ messages: Message[],+): Conversation {+ const sorted = [...messages].sort((a, b) => b.receivedAt.localeCompare(a.receivedAt))+ const latest = sorted[0]+ return {+ id: threadId,+ accountId,+ key: scopeKey(accountId, threadId),+ subject: latest?.subject || '(No subject)',+ from: [+ ...new Map(sorted.flatMap((m) => m.from).map((a) => [a.email.toLowerCase(), a])).values(),+ ],+ preview: latest?.preview || '',+ receivedAt: latest?.receivedAt || '',+ unread: messages.some((m) => !m.keywords.$seen),+ starred: messages.some((m) => m.keywords.$flagged),+ hasAttachment: messages.some((m) => m.hasAttachment),+ count: messages.length,+ messages,+ }+}+export function mergePages(+ pages: { accountId: string; page: ProviderPage; position: number }[],+ limit: number,+): QueryPage {+ const all = pages+ .flatMap((p) => p.page.items)+ .sort((a, b) => b.receivedAt.localeCompare(a.receivedAt) || a.key.localeCompare(b.key))+ const items = all.slice(0, limit)+ const next: Record<string, number> = {}+ for (const p of pages) {+ const consumed = items.filter((i) => i.accountId === p.accountId).length+ if (consumed < p.page.items.length || p.page.next !== undefined)+ next[p.accountId] = p.position + consumed+ }+ const incomplete = pages.filter((p) => p.page.incomplete).map((p) => p.accountId)+ return {+ items,+ total: pages.reduce((n, p) => n + p.page.total, 0),+ next: Object.keys(next).length ? next : undefined,+ failedAccounts: [],+ ...(incomplete.length ? { incompleteAccounts: incomplete } : {}),+ }+}+/** Identifies a server draft's content, to detect edits made by another client. */+export function draftFingerprint(message: Message): string {+ return JSON.stringify([+ message.subject,+ message.to,+ message.cc,+ message.bcc,+ message.html,+ message.text,+ message.attachments?.map((a) => a.blobId),+ ])+}+export function unlinkedServerDrafts(conversations: Conversation[], local: Draft[]): Message[] {+ const linked = new Set(+ local.filter((d) => d.serverId).map((d) => scopeKey(d.accountId, d.serverId!)),+ )+ return [+ ...new Map(+ conversations+ .flatMap((c) => c.messages)+ .filter((m) => m.keywords.$draft && !linked.has(scopeKey(m.accountId, m.id)))+ .map((m) => [scopeKey(m.accountId, m.id), m]),+ ).values(),+ ].sort((a, b) => b.receivedAt.localeCompare(a.receivedAt))+}+export function parseAddresses(value: string): Address[] {+ return (value.match(/(?:[^,;"<]|"[^"]*"|<[^>]*>)+/g) || [])+ .map((s) => s.trim())+ .filter(Boolean)+ .map((s) => {+ const match = s.match(/^(.*?)\s*<([^>]+)>$/)+ return {+ name: match ? match[1].replace(/^"|"$/g, '').trim() : '',+ email: match ? match[2].trim() : s,+ }+ })+}+export function replyRecipients(+ message: Message,+ identities: Identity[],+ all: boolean,+): { to: Address[]; cc: Address[]; identity?: Identity } {+ const own = new Set(identities.map((i) => i.email.toLowerCase()))+ const identity =+ identities.find((i) =>+ message.to.some((a) => a.email.toLowerCase() === i.email.toLowerCase()),+ ) ||+ identities.find((i) =>+ message.cc.some((a) => a.email.toLowerCase() === i.email.toLowerCase()),+ ) ||+ identities[0]+ const sender = message.replyTo.length ? message.replyTo : message.from+ const to = sender.filter((a) => !own.has(a.email.toLowerCase()))+ if (!to.length) to.push(...message.to.filter((a) => !own.has(a.email.toLowerCase())))+ const seen = new Set(to.map((a) => a.email.toLowerCase()))+ const cc = all+ ? [...message.to, ...message.cc].filter((a) => {+ const key = a.email.toLowerCase()+ if (own.has(key) || seen.has(key)) return false+ seen.add(key)+ return true+ })+ : []+ return { to, cc, identity }+}+export function mailtoDraft(url: string): Partial<Draft> {+ const parsed = new URL(url)+ if (parsed.protocol !== 'mailto:') throw new Error('Only email links are supported.')+ return {+ to: parseAddresses(decodeURIComponent(parsed.pathname)),+ cc: parseAddresses(parsed.searchParams.get('cc') || ''),+ bcc: parseAddresses(parsed.searchParams.get('bcc') || ''),+ subject: parsed.searchParams.get('subject') || '',+ text: parsed.searchParams.get('body') || '',+ }+}+export function friendlyError(error: unknown): string {+ return error instanceof Error+ ? error.message.replace(/^Error invoking remote method '[^']+': Error: /, '')+ : 'Something went wrong. Please try again.'+}+/** The first HTTPS (or else mailto) List-Unsubscribe target, never one carrying credentials. */+export function parseUnsubscribe(value?: string, post?: string): Message['unsubscribe'] {+ if (!value) return+ const matches = [...value.matchAll(/<([^>]+)>/g)].map((m) => m[1])+ const url =+ matches.find((s) => s.startsWith('https://')) || matches.find((s) => s.startsWith('mailto:'))+ if (!url) return+ try {+ const u = new URL(url)+ if (u.username || u.password) return+ return {+ url,+ oneClick: u.protocol === 'https:' && /List-Unsubscribe=One-Click/i.test(post || ''),+ }+ } catch {+ return+ }+}diff --git a/packages/core/src/model.ts b/packages/core/src/model.tsnew file mode 100644index 0000000..33c9df0--- /dev/null+++ b/packages/core/src/model.ts@@ -0,0 +1,527 @@+export type View = 'inbox' | 'starred' | 'archive' | 'sent' | 'drafts' | 'junk' | 'trash' | 'all'+export type ConnectionState = 'connecting' | 'connected' | 'offline' | 'authentication' | 'error'+/** How an account's avatar looks: a generated marble pattern, or a picture the user chose. */+export interface AccountAppearance {+ /** Varies the generated pattern; the account's address stands in until the user shuffles. */+ seed?: string+ /** A small square picture kept on this device, as a data URL. */+ image?: string+}+/** Colours for the generated account avatars, tuned to sit calmly on dark and light surfaces. */+export const avatarColors = ['#4b3fb5', '#a69aef', '#e7ae7c', '#d491ac', '#7caee4']+/** Tuned to read well as text and as a soft tint in both themes. */+export const accountColors = [+ '#a3a3ad',+ '#a69aef',+ '#7caee4',+ '#6fc0cc',+ '#83bba8',+ '#d9bd6a',+ '#e7ae7c',+ '#d491ac',+ '#e58f8f',+] as const+/** The first palette colour no other account uses, so new accounts stay distinguishable. */+export function nextAccountColor(used: string[]): string {+ const taken = new Set(used.map((c) => c.toLowerCase()))+ const free = accountColors.slice(1).find((c) => !taken.has(c))+ return free || accountColors[1 + (used.length % (accountColors.length - 1))]+}+export interface Account {+ id: string+ connectionId: string+ remoteId: string+ /** A private label shown only in this app, never sent to anyone. */+ name: string+ email: string+ /** The name recipients see in the From header; falls back to the server identity's name. */+ senderName?: string+ color: string+ seed?: string+ image?: string+ status: ConnectionState+ /** Why incoming mail is unavailable, when it is. */+ error?: string+ /** Set when the outgoing server rejected its login; incoming mail can still work. */+ outgoingError?: string+ sessionOnly?: boolean+ /** Absent on records saved before IMAP support, which were always JMAP. */+ protocol?: Protocol+ /** Actions this server cannot perform safely, each with an explanation to show instead. */+ limits?: AccountLimits+ /** Present while the local index is still catching up with the server. */+ indexing?: IndexingProgress+}+export interface AccountLimits {+ move?: string+ destroy?: string+}+export interface IndexingProgress {+ indexed: number+ /** Messages the server reports; can grow while indexing. */+ total: number+ complete: boolean+}+export interface Mailbox {+ id: string+ accountId: string+ name: string+ role: string | null+ parentId: string | null+ totalEmails: number+ unreadEmails: number+ rights: {+ mayReadItems: boolean+ mayAddItems: boolean+ mayRemoveItems: boolean+ maySetSeen: boolean+ maySetKeywords: boolean+ mayCreateChild: boolean+ mayRename: boolean+ mayDelete: boolean+ }+}+export interface Address {+ name: string+ email: string+}+export interface Attachment {+ blobId: string+ name: string+ type: string+ size: number+ cid?: string+ disposition?: string+}+export interface Message {+ id: string+ accountId: string+ threadId: string+ subject: string+ from: Address[]+ to: Address[]+ cc: Address[]+ bcc: Address[]+ replyTo: Address[]+ receivedAt: string+ sentAt?: string+ preview: string+ keywords: Record<string, boolean>+ mailboxIds: Record<string, boolean>+ size: number+ hasAttachment: boolean+ html?: string+ text?: string+ attachments?: Attachment[]+ messageId?: string[]+ inReplyTo?: string[]+ references?: string[]+ unsubscribe?: { url: string; oneClick: boolean }+}+export interface Conversation {+ id: string+ accountId: string+ key: string+ subject: string+ from: Address[]+ preview: string+ receivedAt: string+ unread: boolean+ starred: boolean+ hasAttachment: boolean+ count: number+ messages: Message[]+}+export interface Identity {+ id: string+ accountId: string+ name: string+ email: string+ mayDelete?: boolean+ textSignature?: string+ htmlSignature?: string+}+export interface MailQuery {+ view: View+ accountId?: string+ mailboxId?: string+ text?: string+ from?: string+ to?: string+ subject?: string+ after?: string+ before?: string+ hasAttachment?: boolean+ unread?: boolean+}+export interface QueryPage {+ items: Conversation[]+ next?: Record<string, number>+ total: number+ failedAccounts: string[]+ /** Accounts whose local index is still catching up; their results may be partial. */+ incompleteAccounts?: string[]+}+export interface StagedAttachment {+ id: string+ name: string+ type: string+ size: number+ blobId?: string+ cid?: string+}+export interface Draft {+ id: string+ accountId: string+ identityId: string+ to: Address[]+ cc: Address[]+ bcc: Address[]+ subject: string+ html: string+ text: string+ attachments: StagedAttachment[]+ updatedAt: string+ inReplyTo?: string[]+ references?: string[]+ replyThreadId?: string+ serverId?: string+ serverFingerprint?: string+ status: 'local' | 'saving' | 'synced' | 'error' | 'sending' | 'uncertain' | 'sent'+ error?: string+ /** What kind of problem `error` describes, so the composer can offer the right recovery. */+ errorKind?: DraftErrorKind+}+export type DraftErrorKind = 'conflict' | 'connection' | 'outgoingAuthentication' | 'rejected'+export interface Settings {+ theme: 'dark' | 'light' | 'system'+ remoteImages: boolean+ notifications: boolean+ closeToTray: boolean+ defaultAccountId?: string+ signatures: Record<string, string>+ /** Where the reader goes after a conversation leaves the current view. */+ afterArchive?: 'next' | 'previous' | 'list'+}+export const defaultSettings: Settings = {+ theme: 'dark',+ remoteImages: true,+ notifications: true,+ closeToTray: true,+ signatures: {},+}+export type MailAction =+ | 'archive'+ | 'trash'+ | 'restore'+ | 'spam'+ | 'notSpam'+ | 'read'+ | 'unread'+ | 'star'+ | 'unstar'+ | 'move'+ | 'destroy'+export interface MutationTarget {+ accountId: string+ threadId: string+}+export interface MutationInput {+ targets: MutationTarget[]+ action: MailAction+ mailboxId?: string+}+export interface MutationResult {+ changed: number+ failures: string[]+ undoId?: string+}+export interface AccountDetails {+ name: string+ senderName: string+}+export type Protocol = 'jmap' | 'imap'+/** Implicit TLS from the first byte, or a plain connection that must upgrade with STARTTLS. */+export type TransportSecurity = 'tls' | 'starttls'+export interface ServerSettings {+ host: string+ port: number+ security: TransportSecurity+ username: string+}+export interface JmapConnectionConfig {+ protocol: 'jmap'+ serverUrl: string+ username: string+}+export interface ImapConnectionConfig {+ protocol: 'imap'+ /** The single address this account sends from. */+ email: string+ incoming: ServerSettings+ outgoing: ServerSettings+ /** When true the outgoing server uses the incoming password. */+ outgoingSameCredentials: boolean+}+export type ConnectionConfig = JmapConnectionConfig | ImapConnectionConfig+export type FolderRole = 'sent' | 'drafts' | 'archive' | 'junk' | 'trash'+export const folderRoles: FolderRole[] = ['sent', 'drafts', 'archive', 'junk', 'trash']+/** An existing folder for a role, or one Inlark should create. `null` means none. */+export type FolderMappings = Partial<Record<FolderRole, { path: string; create?: boolean } | null>>+export interface FolderMappingReview {+ folders: { path: string; name: string }[]+ /**+ * `server` came from the server's special-use flags, `user` from an earlier choice. `name`+ * is only a guess from the folder's name and should be confirmed.+ */+ mappings: Partial<Record<FolderRole, { path: string; source: 'server' | 'user' | 'name' } | null>>+}+export interface ConnectInput {+ config: ConnectionConfig+ password: string+ /** Only used when the outgoing server has its own credentials. */+ outgoingPassword?: string+ name: string+ senderName?: string+ remember: boolean+ connectionId?: string+ folders?: FolderMappings+}+/** A saved connection as the renderer may see it: never includes passwords. */+export interface ConnectionSettings {+ connectionId: string+ name: string+ config: ConnectionConfig+ remember: boolean+ folders?: FolderMappings+}+export type DiscoverySource =+ 'jmap-srv' | 'jmap-well-known' | 'autoconfig' | 'imap-srv' | 'directory'+export type DiscoveryCandidate =+ | { protocol: 'jmap'; source: DiscoverySource; serverUrl: string; username: string }+ | {+ protocol: 'imap'+ source: DiscoverySource+ incoming: ServerSettings+ outgoing: ServerSettings+ /** The provider name from a configuration file, shown for recognition only. */+ provider?: string+ }+export interface DiscoveryResult {+ email: string+ domain: string+ /** In order of preference; JMAP always precedes IMAP. */+ candidates: DiscoveryCandidate[]+}+export interface ConnectionCheck {+ ok: boolean+ error?: string+}+export interface ConnectionTest {+ incoming: ConnectionCheck+ /** Absent for JMAP, which submits through the same connection. */+ outgoing?: ConnectionCheck+ folders?: FolderMappingReview+}+export interface ProviderCapabilities {+ mail: boolean+ submission: boolean+ push: boolean+ maxObjectsInGet: number+ maxObjectsInSet: number+ maxUploadSize: number+ /** Attachments must be uploaded before a draft can reference them (JMAP blobs). */+ blobUpload?: boolean+ /** A message lives in exactly one folder, so adding a folder without removing one copies it. */+ exclusiveMailboxes?: boolean+ /** `client` means the app must file its own Sent copy after submission. */+ sentCopy?: 'server' | 'client'+}+export interface ProviderPage {+ items: Conversation[]+ total: number+ next?: number+ /** The local index has not caught up yet, so this page may miss older mail. */+ incomplete?: boolean+}+/**+ * A provider-neutral change to one message. `true` adds a folder or keyword, `false` removes it.+ * Each provider translates this into its own protocol operations.+ */+export interface MessageChange {+ mailboxes?: Record<string, boolean>+ keywords?: Record<string, boolean>+}+export type MessageChanges = Record<string, MessageChange>+/** A message ready for submission, persisted before any network send. */+export interface OutgoingMessage {+ /** The RFC 5322 Message-ID, without angle brackets. Unique per send attempt. */+ messageId: string+ /** The server-side email, for providers that submit stored messages (JMAP). */+ emailId?: string+ /** Complete MIME without Bcc headers, for providers that transmit it themselves (SMTP). */+ mime?: Uint8Array+ envelope: { from: string; to: string[] }+}+export interface SubmissionOutcome {+ accepted: string[]+ rejected: { email: string; reason: string }[]+}+export interface ProviderEvent {+ type: 'changed' | 'status' | 'indexing'+ accountId?: string+ state?: ConnectionState+ message?: string+ indexing?: IndexingProgress+ /** Set for changes found by historical indexing, which must never notify. */+ historical?: boolean+}+export interface MailProvider {+ readonly capabilities: ProviderCapabilities+ connect(): Promise<Account[]>+ /** Signs in to the outgoing server without sending anything (SMTP providers only). */+ verifyOutgoing?(): Promise<void>+ /** Releases resources asynchronously, e.g. closing a local index before its files are removed. */+ close?(): Promise<void>+ mailboxes(account: Account): Promise<Mailbox[]>+ identities(account: Account): Promise<Identity[]>+ query(+ account: Account,+ query: MailQuery,+ position?: number,+ limit?: number,+ ): Promise<ProviderPage>+ conversation(account: Account, threadId: string): Promise<Message[]>+ getStateToken(account: Account): string | undefined+ update(+ account: Account,+ changes: MessageChanges,+ destroy?: string[],+ expectedState?: string,+ ): Promise<{ updated: string[]; failures: string[] }>+ conversationMetadata(account: Account, threadIds: string[]): Promise<Message[]>+ messages(account: Account, ids: string[], bodies?: boolean): Promise<Message[]>+ folder(+ account: Account,+ operation: 'create' | 'rename' | 'delete',+ id?: string,+ name?: string,+ parentId?: string,+ ): Promise<void>+ upload(account: Account, data: Uint8Array, type: string): Promise<string>+ download(account: Account, attachment: Attachment): Promise<Uint8Array>+ createDraft(account: Account, draft: Draft, messageId?: string): Promise<string>+ /** Builds or stores the message to send. Must not transmit anything to recipients. */+ prepareSubmission(account: Account, draft: Draft, messageId: string): Promise<OutgoingMessage>+ /**+ * Sends a prepared message once. Throws `submissionRejected` when nothing was accepted,+ * `submissionUncertain` when the outcome is unknown, and other codes when sending never began.+ */+ submit(account: Account, message: OutgoingMessage, identityId: string): Promise<SubmissionOutcome>+ /** Whether the server proves this message was submitted. A Sent copy alone is not proof. */+ submissionExists(account: Account, message: OutgoingMessage): Promise<boolean>+ /**+ * Files a Sent copy for providers that do not do so themselves. Returns `server` when a copy+ * with the same Message-ID already exists. Throws `filingUncertain` when an append may have+ * completed without confirmation.+ */+ fileSentCopy?(account: Account, message: OutgoingMessage): Promise<'filed' | 'server'>+ folderMappings?(account: Account): Promise<FolderMappingReview>+ setFolderMappings?(account: Account, mappings: FolderMappings): Promise<FolderMappingReview>+ subscribe(listener: (event: ProviderEvent) => void): () => void+ dispose(): void+}+export type AppEvent =+ | { type: 'unread'; count: number }+ | { type: 'changed'; accountId?: string }+ | { type: 'accounts'; accounts: Account[] }+ | { type: 'mailto'; url: string }+ | { type: 'open'; accountId: string; threadId: string }+ | { type: 'progress'; completed: number; total: number }+ | { type: 'submissions'; submissions: SubmissionSummary[] }+export interface SendResult {+ status: 'sent' | 'partial' | 'uncertain'+ message: string+ /** `pending` means the message was sent but its Sent copy is not filed yet. */+ sentCopy?: 'filed' | 'pending'+ /** Recipients the server refused while accepting others. */+ rejected?: Address[]+}+/** The state of a send that still needs the user's attention. Contains no message body. */+export interface SubmissionSummary {+ draftId: string+ accountId: string+ subject: string+ at: string+ state: 'sent' | 'partial' | 'uncertain'+ sentCopy?: 'pending' | 'uncertain' | 'failed'+ rejected?: Address[]+ error?: string+}+export interface Bootstrap {+ accounts: Account[]+ settings: Settings+ secureStorage: boolean+ demo: boolean+ version: string+}+export interface DesktopMailAPI {+ bootstrap(): Promise<Bootstrap>+ ready(): Promise<void>+ discover(email: string): Promise<DiscoveryResult>+ /** Checks a login without saving it. Nothing is sent to any recipient. */+ testConnection(input: ConnectInput): Promise<ConnectionTest>+ connect(input: ConnectInput): Promise<Account[]>+ connectionSettings(connectionId: string): Promise<ConnectionSettings>+ folderMappings(accountId: string): Promise<FolderMappingReview>+ setFolderMappings(accountId: string, mappings: FolderMappings): Promise<FolderMappingReview>+ disconnect(connectionId: string): Promise<void>+ reconnect(connectionId: string): Promise<void>+ updateAccount(accountId: string, appearance: AccountAppearance): Promise<Account[]>+ updateAccountDetails(accountId: string, details: AccountDetails): Promise<Account[]>+ mailboxes(accountId: string): Promise<Mailbox[]>+ identities(accountId: string): Promise<Identity[]>+ query(query: MailQuery, cursor?: Record<string, number>): Promise<QueryPage>+ conversation(accountId: string, threadId: string): Promise<Message[]>+ mutate(input: MutationInput): Promise<MutationResult>+ mutateAll(query: MailQuery, action: MailAction): Promise<MutationResult>+ undo(id: string): Promise<MutationResult>+ folder(input: {+ accountId: string+ operation: 'create' | 'rename' | 'delete'+ id?: string+ name?: string+ parentId?: string+ }): Promise<void>+ drafts(): Promise<Draft[]>+ resumeDraft(accountId: string, messageId: string): Promise<Draft>+ stageRemoteAttachments(accountId: string, attachments: Attachment[]): Promise<StagedAttachment[]>+ saveDraft(draft: Draft): Promise<Draft>+ syncDraft(draft: Draft): Promise<Draft>+ deleteDraft(id: string): Promise<void>+ /** Deletes a draft that exists only on the server, such as one started in another client. */+ deleteServerDraft(accountId: string, messageId: string): Promise<void>+ send(draft: Draft): Promise<SendResult>+ reconcile(draftId: string): Promise<SendResult>+ submissions(): Promise<SubmissionSummary[]>+ /** Retries only the Sent copy of a message that was already sent. */+ retrySentCopy(draftId: string): Promise<SendResult>+ /** Starts a new draft addressed only to the recipients a partial send refused. */+ recoverRejected(draftId: string): Promise<Draft>+ /** Starts a new draft from an unconfirmed send; the unconfirmed record is kept. */+ replaceUncertain(draftId: string): Promise<Draft>+ dismissSubmission(draftId: string): Promise<void>+ stageAttachments(): Promise<StagedAttachment[]>+ attachment(accountId: string, attachment: Attachment, open: boolean): Promise<void>+ inlineImage(accountId: string, attachment: Attachment): Promise<string>+ remoteImage(url: string): Promise<string | null>+ senderAvatar(email: string): Promise<string | null>+ unsubscribe(+ accountId: string,+ messageId: string,+ ): Promise<{ kind: 'done' | 'mailto' | 'browser'; url?: string }>+ openExternal(url: string): Promise<void>+ settings(settings: Settings): Promise<Settings>+ diagnostics(): Promise<string>+ onEvent(listener: (event: AppEvent) => void): () => void+}diff --git a/packages/core/src/schemas.ts b/packages/core/src/schemas.tsnew file mode 100644index 0000000..86d8a16--- /dev/null+++ b/packages/core/src/schemas.ts@@ -0,0 +1,227 @@+import { z } from 'zod'+import type { DesktopMailAPI } from './model'++const id = z.string().min(1).max(2048)+const address = z.object({ name: z.string().max(1000), email: z.string().max(320) })+export const serverUrlSchema = z+ .string()+ .url()+ .max(2048)+ .refine((value) => {+ const u = new URL(value)+ return (+ !u.username &&+ !u.password &&+ !u.hash &&+ (u.protocol === 'https:' ||+ (u.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(u.hostname)))+ )+ }, 'Use HTTPS, or HTTP on localhost for development.')+/** A DNS name, IPv4 address, or IPv6 address. Never a URL, so no scheme or path can sneak in. */+export const hostSchema = z+ .string()+ .trim()+ .toLowerCase()+ .min(1, 'Enter a server name.')+ .max(253)+ .refine(+ (value) =>+ /^(?!-)[a-z0-9-]{1,63}(?<!-)(\.(?!-)[a-z0-9-]{1,63}(?<!-))*\.?$/.test(value) ||+ /^\[?[0-9a-f:]+(:\d{1,3}(\.\d{1,3}){3})?\]?$/.test(value),+ 'Enter a server name such as imap.example.com, without https:// or a port.',+ )+export const serverSettingsSchema = z.object({+ host: hostSchema,+ port: z.number().int().min(1, 'Enter a port.').max(65535, 'Enter a port up to 65535.'),+ security: z.enum(['tls', 'starttls']),+ username: z.string().min(1, 'Enter a username.').max(320),+})+export const connectionConfigSchema = z.discriminatedUnion('protocol', [+ z.object({+ protocol: z.literal('jmap'),+ serverUrl: serverUrlSchema,+ username: z.string().min(1, 'Enter a username.').max(320),+ }),+ z.object({+ protocol: z.literal('imap'),+ email: z.email('Enter a valid email address.').max(320),+ incoming: serverSettingsSchema,+ outgoing: serverSettingsSchema,+ outgoingSameCredentials: z.boolean(),+ }),+])+const folderRole = z.enum(['sent', 'drafts', 'archive', 'junk', 'trash'])+export const folderMappingsSchema = z.partialRecord(+ folderRole,+ z.object({ path: z.string().min(1).max(1024), create: z.boolean().optional() }).nullable(),+)+export const accountSchema = z+ .object({+ config: connectionConfigSchema,+ password: z.string().min(1, 'Enter your password.').max(4096),+ outgoingPassword: z.string().min(1).max(4096).optional(),+ name: z.string().max(100),+ senderName: z.string().max(100).optional(),+ remember: z.boolean(),+ connectionId: id.optional(),+ folders: folderMappingsSchema.optional(),+ })+ .refine(+ (input) =>+ input.config.protocol !== 'imap' ||+ input.config.outgoingSameCredentials ||+ !!input.outgoingPassword,+ { message: 'Enter the outgoing server password.', path: ['outgoingPassword'] },+ )+export const accountDetailsSchema = z.object({+ name: z.string().max(100),+ senderName: z.string().max(100),+})+export const appearanceSchema = z.object({+ seed: z.string().min(1).max(64).optional(),+ image: z+ .string()+ .max(256 * 1024)+ .regex(/^data:image\/(?:png|jpeg|webp);base64,[a-z0-9+/]+={0,2}$/i)+ .optional(),+})+export const querySchema = z.object({+ view: z.enum(['inbox', 'starred', 'archive', 'sent', 'drafts', 'junk', 'trash', 'all']),+ accountId: id.optional(),+ mailboxId: id.optional(),+ text: z.string().max(2000).optional(),+ from: z.string().max(320).optional(),+ to: z.string().max(320).optional(),+ subject: z.string().max(1000).optional(),+ after: z.string().max(40).optional(),+ before: z.string().max(40).optional(),+ hasAttachment: z.boolean().optional(),+ unread: z.boolean().optional(),+})+export const actionSchema = z.enum([+ 'archive',+ 'trash',+ 'restore',+ 'spam',+ 'notSpam',+ 'read',+ 'unread',+ 'star',+ 'unstar',+ 'move',+ 'destroy',+])+export const mutationSchema = z.object({+ targets: z.array(z.object({ accountId: id, threadId: id })).max(500),+ action: actionSchema,+ mailboxId: id.optional(),+})+export const attachmentSchema = z.object({+ blobId: id,+ name: z.string().max(1024),+ type: z.string().max(256),+ size: z.number().nonnegative(),+ cid: z.string().optional(),+ disposition: z.string().optional(),+})+export const stagedSchema = z.object({+ id: z.string().uuid(),+ name: z.string().max(1024),+ type: z.string().max(256),+ size: z.number().nonnegative(),+ blobId: id.optional(),+ cid: z.string().optional(),+})+export const draftSchema = z.object({+ id: z.string().uuid(),+ accountId: id,+ identityId: id,+ to: z.array(address).max(200),+ cc: z.array(address).max(200),+ bcc: z.array(address).max(200),+ subject: z.string().max(998),+ html: z.string().max(5_000_000),+ text: z.string().max(5_000_000),+ attachments: z.array(stagedSchema).max(100),+ updatedAt: z.string().datetime(),+ inReplyTo: z.array(z.string()).optional(),+ references: z.array(z.string()).optional(),+ replyThreadId: id.optional(),+ serverId: id.optional(),+ serverFingerprint: z.string().optional(),+ status: z.enum(['local', 'saving', 'synced', 'error', 'sending', 'uncertain', 'sent']),+ error: z.string().optional(),+ errorKind: z.enum(['conflict', 'connection', 'outgoingAuthentication', 'rejected']).optional(),+})+export const sendDraftSchema = draftSchema+ .refine(+ (d) =>+ [...d.to, ...d.cc, ...d.bcc].length > 0 &&+ [...d.to, ...d.cc, ...d.bcc].every(+ (a) => z.email().safeParse(a.email).success && !/[\r\n]/.test(a.name),+ ),+ 'Add valid recipients before sending.',+ )+ .refine((d) => !/[\r\n]/.test(d.subject), 'The subject must be a single line.')+export const settingsSchema = z.object({+ theme: z.enum(['dark', 'light', 'system']),+ remoteImages: z.boolean(),+ notifications: z.boolean(),+ closeToTray: z.boolean(),+ defaultAccountId: id.optional(),+ signatures: z.record(z.string(), z.string().max(100_000)),+ afterArchive: z.enum(['next', 'previous', 'list']).optional(),+})+export const ipcSchemas = {+ bootstrap: z.tuple([]),+ ready: z.tuple([]),+ discover: z.tuple([z.string().trim().toLowerCase().pipe(z.email().max(320))]),+ testConnection: z.tuple([accountSchema]),+ connect: z.tuple([accountSchema]),+ connectionSettings: z.tuple([id]),+ folderMappings: z.tuple([id]),+ setFolderMappings: z.tuple([id, folderMappingsSchema]),+ disconnect: z.tuple([id]),+ reconnect: z.tuple([id]),+ updateAccount: z.tuple([id, appearanceSchema]),+ updateAccountDetails: z.tuple([id, accountDetailsSchema]),+ mailboxes: z.tuple([id]),+ identities: z.tuple([id]),+ query: z.tuple([querySchema, z.record(z.string(), z.number().int().nonnegative()).optional()]),+ conversation: z.tuple([id, id]),+ mutate: z.tuple([mutationSchema]),+ mutateAll: z.tuple([querySchema, actionSchema]),+ undo: z.tuple([id]),+ folder: z.tuple([+ z.object({+ accountId: id,+ operation: z.enum(['create', 'rename', 'delete']),+ id: id.optional(),+ name: z.string().trim().min(1).max(255).optional(),+ parentId: id.optional(),+ }),+ ]),+ resumeDraft: z.tuple([id, id]),+ stageRemoteAttachments: z.tuple([id, z.array(attachmentSchema).max(100)]),+ drafts: z.tuple([]),+ saveDraft: z.tuple([draftSchema]),+ syncDraft: z.tuple([draftSchema]),+ deleteDraft: z.tuple([z.string().uuid()]),+ deleteServerDraft: z.tuple([id, id]),+ send: z.tuple([sendDraftSchema]),+ reconcile: z.tuple([z.string().uuid()]),+ submissions: z.tuple([]),+ retrySentCopy: z.tuple([z.string().uuid()]),+ recoverRejected: z.tuple([z.string().uuid()]),+ replaceUncertain: z.tuple([z.string().uuid()]),+ dismissSubmission: z.tuple([z.string().uuid()]),+ stageAttachments: z.tuple([]),+ attachment: z.tuple([id, attachmentSchema, z.boolean()]),+ inlineImage: z.tuple([id, attachmentSchema]),+ remoteImage: z.tuple([z.string().url().max(8192)]),+ senderAvatar: z.tuple([z.string().trim().email().max(320)]),+ unsubscribe: z.tuple([id, id]),+ openExternal: z.tuple([z.string().max(8192)]),+ settings: z.tuple([settingsSchema]),+ diagnostics: z.tuple([]),+} satisfies Record<Exclude<keyof DesktopMailAPI, 'onEvent'>, z.ZodType>diff --git a/packages/core/tsconfig.json b/packages/core/tsconfig.jsonnew file mode 100644index 0000000..f46ada1--- /dev/null+++ b/packages/core/tsconfig.json@@ -0,0 +1 @@+{ "extends": "../../tsconfig.json", "include": ["src"] }diff --git a/packages/imap/package.json b/packages/imap/package.jsonnew file mode 100644index 0000000..a4b8598--- /dev/null+++ b/packages/imap/package.json@@ -0,0 +1,23 @@+{+ "name": "@inlark/imap",+ "version": "0.1.0",+ "private": true,+ "license": "AGPL-3.0-only",+ "type": "module",+ "exports": {+ ".": "./src/index.ts"+ },+ "scripts": {+ "typecheck": "tsc -p tsconfig.json"+ },+ "dependencies": {+ "@inlark/core": "workspace:*",+ "imapflow": "^2.0.6",+ "mailparser": "^3.9.28",+ "nodemailer": "^10.0.10"+ },+ "devDependencies": {+ "@types/mailparser": "^3.4.6",+ "@types/nodemailer": "^8.0.2"+ }+}diff --git a/packages/imap/src/convert.ts b/packages/imap/src/convert.tsnew file mode 100644index 0000000..6652fa2--- /dev/null+++ b/packages/imap/src/convert.ts@@ -0,0 +1,209 @@+import { parseUnsubscribe, type Attachment, type Message } from '@inlark/core'+import type { BodyPart, IndexedMessage, NewMessage } from './metadata-index'+import type { FetchedMessage } from './port'++const systemFlags: Record<string, string> = {+ '\\seen': '$seen',+ '\\flagged': '$flagged',+ '\\draft': '$draft',+ '\\answered': '$answered',+ '\\deleted': '$deleted',+}+const flagFor: Record<string, string> = Object.fromEntries(+ Object.entries(systemFlags).map(([flag, keyword]) => [+ keyword,+ flag.replace(/^\\(.)/, (_, c) => '\\' + c.toUpperCase()),+ ]),+)++/** IMAP flags → JMAP-style keywords. System flags get their `$` names; keywords are lowercased. */+export function keywordsFromFlags(flags: string[]): Record<string, boolean> {+ const keywords: Record<string, boolean> = {}+ for (const flag of flags) {+ const lower = flag.toLowerCase()+ if (systemFlags[lower]) keywords[systemFlags[lower]] = true+ else if (!lower.startsWith('\\')) keywords[lower] = true+ }+ return keywords+}+export function flagFromKeyword(keyword: string): string {+ return flagFor[keyword.toLowerCase()] || keyword+}++/** Every `<id>` in a header value, without brackets, in order. */+export function messageIds(value?: string | null): string[] {+ if (!value) return []+ const ids = [...value.matchAll(/<([^<>\s]{1,998})>/g)].map((m) => m[1])+ // Some mailers omit brackets for a single ID.+ if (!ids.length && /^[^<>\s@]+@[^<>\s@]+$/.test(value.trim())) return [value.trim()]+ return ids+}++/** Unfolded values of the requested header lines, keyed by lower-case name. */+export function parseHeaderLines(raw?: string): Record<string, string> {+ const result: Record<string, string> = {}+ if (!raw) return result+ for (const line of raw.replace(/\r?\n[ \t]+/g, ' ').split(/\r?\n/)) {+ const colon = line.indexOf(':')+ if (colon < 1) continue+ const name = line.slice(0, colon).trim().toLowerCase()+ if (!(name in result)) result[name] = line.slice(colon + 1).trim()+ }+ return result+}++const filename = (part: BodyPart) =>+ part.dispositionParameters?.filename || part.parameters?.name || undefined+const contentId = (part: BodyPart) => part.id?.replace(/^<|>$/g, '') || undefined++export function leaves(part?: BodyPart): BodyPart[] {+ if (!part) return []+ if (part.childNodes?.length) return part.childNodes.flatMap(leaves)+ return [part]+}+/** IMAP names a single-part message's body `1` in FETCH BODY[...]; ImapFlow may omit it. */+const section = (part: BodyPart) => part.part || '1'++const isText = (part: BodyPart) => part.type === 'text/plain' || part.type === 'text/html'+export function isAttachmentPart(part: BodyPart): boolean {+ if (part.type.startsWith('multipart/')) return false+ if (part.disposition === 'attachment') return true+ if (isText(part) && !filename(part)) return false+ // Inline images referenced by Content-ID are part of the body, not attachments.+ if (part.disposition === 'inline' && contentId(part)) return false+ return !!filename(part) || !isText(part)+}+export function hasAttachment(structure?: BodyPart): boolean {+ return leaves(structure).some(isAttachmentPart)+}++/** Parts to show and download: attachments plus inline images referenced by Content-ID. */+export function attachmentsOf(message: IndexedMessage): Attachment[] {+ return leaves(message.bodyStructure)+ .filter((part) => isAttachmentPart(part) || (contentId(part) && !isText(part)))+ .map((part) => ({+ blobId: blobId(message.id, section(part)),+ name: filename(part) || (part.type.startsWith('image/') ? 'image' : 'attachment'),+ type: part.type,+ size: part.size || 0,+ ...(contentId(part) ? { cid: contentId(part) } : {}),+ ...(part.disposition ? { disposition: part.disposition } : {}),+ }))+}+/** The body parts to render, preferring those not marked as attachments. */+export function textParts(structure?: BodyPart): { html?: BodyPart; text?: BodyPart } {+ const candidates = leaves(structure).filter((p) => isText(p) && p.disposition !== 'attachment')+ return {+ html: candidates.find((p) => p.type === 'text/html'),+ text: candidates.find((p) => p.type === 'text/plain'),+ }+}+export { section as partSection }++/** An attachment is addressed by its message's ID and IMAP section, never by Message-ID. */+export const blobId = (messageId: string, part: string) => messageId + '/' + part+export function parseBlobId(value: string): { messageId: string; part: string } | undefined {+ const slash = value.lastIndexOf('/')+ if (slash < 1 || !/^[0-9.]+$|^TEXT$/.test(value.slice(slash + 1))) return undefined+ return { messageId: value.slice(0, slash), part: value.slice(slash + 1) }+}++export function previewText(value: string, html = false): string {+ const text = html+ ? value+ .replace(/<(style|script|head)[\s\S]*?<\/\1>/gi, ' ')+ .replace(/<[^>]+>/g, ' ')+ .replace(/ /gi, ' ')+ .replace(/&/gi, '&')+ .replace(/</gi, '<')+ .replace(/>/gi, '>')+ .replace(/'|'/gi, "'")+ .replace(/"/gi, '"')+ : value+ return text+ .split(/\r?\n/)+ .filter((line) => !/^\s*>/.test(line))+ .join(' ')+ .replace(/\s+/g, ' ')+ .trim()+ .slice(0, 256)+}++export const metadataQuery = {+ flags: true,+ envelope: true,+ bodyStructure: true,+ internalDate: true,+ size: true,+ headers: ['references', 'in-reply-to', 'list-unsubscribe', 'list-unsubscribe-post'],+}++export function toNewMessage(+ fetched: FetchedMessage,+ location: { mailboxId: string; uidValidity: string },+): NewMessage {+ const env = fetched.envelope || {}+ const headers = parseHeaderLines(fetched.headers)+ const references = messageIds(headers.references).slice(-50)+ const inReplyTo = messageIds(headers['in-reply-to'] || env.inReplyTo)+ const receivedAt = fetched.internalDate || env.date || new Date(0).toISOString()+ return {+ ...location,+ uid: fetched.uid,+ modseq: fetched.modseq,+ messageId: messageIds(env.messageId)[0] ?? null,+ inReplyTo,+ references,+ subject: env.subject || '',+ from: env.from?.length ? env.from : env.sender || [],+ to: env.to || [],+ cc: env.cc || [],+ bcc: env.bcc || [],+ replyTo: env.replyTo || [],+ receivedAt,+ sentAt: env.date,+ size: fetched.size || 0,+ flags: fetched.flags || [],+ hasAttachment: hasAttachment(fetched.bodyStructure),+ preview: '',+ bodyStructure: fetched.bodyStructure,+ unsubscribe: parseUnsubscribe(headers['list-unsubscribe'], headers['list-unsubscribe-post']),+ }+}++export function toMessage(accountId: string, m: IndexedMessage): Message {+ return {+ id: m.id,+ accountId,+ threadId: m.threadId,+ subject: m.subject,+ from: m.from,+ to: m.to,+ cc: m.cc,+ bcc: m.bcc,+ replyTo: m.replyTo,+ receivedAt: m.receivedAt,+ sentAt: m.sentAt,+ preview: m.preview,+ keywords: keywordsFromFlags(m.flags),+ mailboxIds: { [m.mailboxId]: true },+ size: m.size,+ hasAttachment: m.hasAttachment,+ messageId: m.messageId ? [m.messageId] : [],+ inReplyTo: m.inReplyTo,+ references: m.references,+ ...(m.unsubscribe ? { unsubscribe: m.unsubscribe } : {}),+ }+}++/** Compresses sorted UIDs into an IMAP set such as `1:4,9,12:13`. */+export function uidSet(uids: number[]): string {+ const sorted = [...new Set(uids)].sort((a, b) => a - b)+ const ranges: string[] = []+ for (let i = 0; i < sorted.length; i++) {+ const start = sorted[i]+ while (i + 1 < sorted.length && sorted[i + 1] === sorted[i] + 1) i+++ ranges.push(start === sorted[i] ? String(start) : start + ':' + sorted[i])+ }+ return ranges.join(',')+}diff --git a/packages/imap/src/folders.ts b/packages/imap/src/folders.tsnew file mode 100644index 0000000..5fac562--- /dev/null+++ b/packages/imap/src/folders.ts@@ -0,0 +1,59 @@+import {+ folderRoles,+ type FolderMappingReview,+ type FolderMappings,+ type FolderRole,+} from '@inlark/core'+import type { FolderListing } from './metadata-index'++const specialUse: Record<FolderRole, string> = {+ sent: '\\Sent',+ drafts: '\\Drafts',+ archive: '\\Archive',+ junk: '\\Junk',+ trash: '\\Trash',+}+export const isInbox = (path: string) => path.toUpperCase() === 'INBOX'++/**+ * Chooses the folder for each role: an explicit choice by the user wins, then the server's+ * special-use flag, then a guess from the folder's name. Guesses are marked so they can be+ * reviewed; a role explicitly set to `null` stays empty.+ */+export function reviewFolders(+ folders: FolderListing[],+ chosen: FolderMappings = {},+): FolderMappingReview {+ const selectable = folders.filter((f) => !f.noSelect)+ const byPath = new Map(selectable.map((f) => [f.path, f]))+ const mappings: FolderMappingReview['mappings'] = {}+ for (const role of folderRoles) {+ const choice = chosen[role]+ if (choice === null) {+ mappings[role] = null+ continue+ }+ if (choice && byPath.has(choice.path)) {+ mappings[role] = { path: choice.path, source: 'user' }+ continue+ }+ const declared = selectable.find((f) => f.specialUse === specialUse[role])+ const guessed = selectable.find((f) => f.guessedSpecialUse === specialUse[role])+ const found = declared || guessed+ if (found) mappings[role] = { path: found.path, source: declared ? 'server' : 'name' }+ }+ return {+ folders: selectable.map((f) => ({ path: f.path, name: f.name })),+ mappings,+ }+}++/** Role by folder path, as used for views and actions. */+export function rolesByPath(review: FolderMappingReview): Map<string, string> {+ const roles = new Map<string, string>()+ for (const role of folderRoles) {+ const mapping = review.mappings[role]+ if (mapping && !roles.has(mapping.path) && !isInbox(mapping.path)) roles.set(mapping.path, role)+ }+ return roles+}diff --git a/packages/imap/src/imapflow-port.ts b/packages/imap/src/imapflow-port.tsnew file mode 100644index 0000000..99ae743--- /dev/null+++ b/packages/imap/src/imapflow-port.ts@@ -0,0 +1,365 @@+import { isIP } from 'node:net'+import {+ ImapFlow,+ type ImapFlowOptions,+ type ListResponse,+ type MessageStructureObject,+} from 'imapflow'+import { ProviderError, type Address } from '@inlark/core'+import type { BodyPart, FolderListing } from './metadata-index'+import type {+ AppendResult,+ CopyResult,+ Envelope,+ FetchQuery,+ FetchedMessage,+ ImapPort,+ ImapServerOptions,+ MailboxStatus,+ SearchCriteria,+ SelectedMailbox,+} from './port'++const tlsCodes = new Set([+ 'CERT_HAS_EXPIRED',+ 'CERT_NOT_YET_VALID',+ 'DEPTH_ZERO_SELF_SIGNED_CERT',+ 'SELF_SIGNED_CERT_IN_CHAIN',+ 'UNABLE_TO_VERIFY_LEAF_SIGNATURE',+ 'UNABLE_TO_GET_ISSUER_CERT_LOCALLY',+ 'ERR_TLS_CERT_ALTNAME_INVALID',+ 'ERR_SSL_WRONG_VERSION_NUMBER',+ 'EPROTO',+])++/** Maps a connection-phase failure to a calm, specific error. Never includes the password. */+export function connectionError(error: unknown, host: string): ProviderError {+ const e = error as {+ code?: string+ authenticationFailed?: boolean+ tlsFailed?: boolean+ message?: string+ }+ if (e?.authenticationFailed)+ return new ProviderError(+ 'authentication',+ 'The incoming server rejected this login. Check the username and password, or create an app password.',+ )+ if (+ e?.tlsFailed ||+ (e?.code && tlsCodes.has(e.code)) ||+ /certificate|TLS|SSL/i.test(e?.message || '')+ )+ return new ProviderError(+ 'tls',+ 'A secure connection to ' ++ host ++ ' could not be established or its certificate could not be verified. Inlark never falls back to an unencrypted connection.',+ )+ if (e?.code === 'ENOTFOUND' || e?.code === 'EAI_AGAIN')+ return new ProviderError(+ 'network',+ 'The server ' + host + ' could not be found. Check its name.',+ )+ if (e?.code === 'ECONNREFUSED')+ return new ProviderError(+ 'network',+ host + ' refused the connection. Check the port and security setting.',+ )+ return new ProviderError(+ 'network',+ 'The incoming server could not be reached. Check your connection and the server settings.',+ )+}++/** The exact ImapFlow options, exported so tests can assert the TLS policy. */+export function imapFlowOptions(+ options: ImapServerOptions,+ purpose: 'command' | 'idle',+): ImapFlowOptions {+ const implicit = options.security === 'tls'+ return {+ host: options.host,+ port: options.port,+ secure: implicit,+ // STARTTLS is required, never opportunistic: without it the login is not sent at all.+ doSTARTTLS: implicit ? undefined : true,+ ...(isIP(options.host.replace(/^\[|\]$/g, '')) ? {} : { servername: options.host }),+ auth: { user: options.username, pass: options.password },+ tls: {+ rejectUnauthorized: true,+ minVersion: 'TLSv1.2',+ ...(options.tls?.ca ? { ca: Buffer.from(options.tls.ca) } : {}),+ },+ logger: false,+ // No client identification is sent to the server.+ clientInfo: { name: false },+ disableAutoIdle: purpose === 'command',+ maxIdleTime: purpose === 'idle' ? 25 * 60_000 : undefined,+ connectionTimeout: options.timeoutMs ?? 30_000,+ greetingTimeout: options.timeoutMs ?? 16_000,+ socketTimeout: purpose === 'idle' ? 30 * 60_000 : 5 * 60_000,+ // Bound memory against a broken or hostile server.+ maxLiteralSize: 200_000_000,+ maxResponseSize: 250_000_000,+ }+}++const address = (list?: { name?: string; address?: string }[]): Address[] =>+ (list || []).filter((a) => a.address).map((a) => ({ name: a.name || '', email: a.address! }))++function bodyPart(node: MessageStructureObject): BodyPart {+ return {+ part: node.part,+ type: (node.type || 'application/octet-stream').toLowerCase(),+ ...(node.parameters ? { parameters: node.parameters } : {}),+ ...(node.id ? { id: node.id } : {}),+ ...(node.encoding ? { encoding: node.encoding } : {}),+ ...(node.size !== undefined ? { size: node.size } : {}),+ ...(node.disposition ? { disposition: node.disposition.toLowerCase() } : {}),+ ...(node.dispositionParameters ? { dispositionParameters: node.dispositionParameters } : {}),+ ...(node.childNodes ? { childNodes: node.childNodes.map(bodyPart) } : {}),+ }+}++const iso = (value?: Date | string) => {+ if (!value) return undefined+ const date = new Date(value)+ return Number.isNaN(date.getTime()) ? undefined : date.toISOString()+}++async function bytes(+ stream: AsyncIterable<Buffer | Uint8Array>,+ maxBytes: number,+ truncate: boolean,+) {+ const chunks: Uint8Array[] = []+ let size = 0+ for await (const chunk of stream) {+ size += chunk.byteLength+ chunks.push(chunk)+ if (size > maxBytes) {+ if (truncate) break+ throw new ProviderError(+ 'tooLarge',+ 'Attachments over 100 MB are not supported in this version.',+ )+ }+ }+ return new Uint8Array(Buffer.concat(chunks)).subarray(0, maxBytes)+}++export class ImapFlowPort implements ImapPort {+ private client: ImapFlow+ constructor(+ private options: ImapServerOptions,+ purpose: 'command' | 'idle',+ ) {+ this.client = new ImapFlow(imapFlowOptions(options, purpose))+ // Errors also surface as rejected commands and a `close` event; never crash the process.+ this.client.on('error', () => {})+ }+ get capabilities(): ReadonlySet<string> {+ return new Set([...this.client.capabilities.keys()].map((c) => c.toUpperCase()))+ }+ get condstore() {+ return this.client.enabled.has('CONDSTORE')+ }+ private can(name: string) {+ return this.client.capabilities.has(name)+ }+ async connect() {+ try {+ await this.client.connect()+ } catch (error) {+ throw connectionError(error, this.options.host)+ }+ }+ async close() {+ try {+ await this.client.logout()+ } catch {+ this.client.close()+ }+ }+ on(event: 'close' | 'exists' | 'expunge' | 'flags', listener: (path: string) => void) {+ if (event === 'close') this.client.on('close', () => listener(''))+ else this.client.on(event, (data: { path: string }) => listener(data.path))+ }+ /** Commands on a closed connection become `network` errors so callers can reconnect. */+ private async wrap<T>(task: () => Promise<T>): Promise<T> {+ try {+ return await task()+ } catch (error) {+ if (error instanceof ProviderError) throw error+ const e = error as { code?: string; responseStatus?: string; responseText?: string }+ if (e?.code === 'NoConnection' || e?.code === 'EConnectionClosed' || !this.client.usable)+ throw new ProviderError('network', 'The connection to the incoming server was interrupted.')+ throw new ProviderError(+ 'command',+ 'The server refused the request' + (e?.responseText ? ': ' + e.responseText : '.'),+ )+ }+ }+ list(): Promise<FolderListing[]> {+ return this.wrap(async () =>+ (await this.client.list()).map((entry: ListResponse) => ({+ path: entry.path,+ name: entry.name,+ delimiter: entry.delimiter || '/',+ parentPath: entry.parentPath || null,+ specialUse:+ entry.specialUseSource === 'extension' && entry.specialUse !== '\\Inbox'+ ? entry.specialUse || null+ : null,+ guessedSpecialUse:+ entry.specialUseSource === 'name' && entry.specialUse !== '\\Inbox'+ ? entry.specialUse || null+ : null,+ noSelect: [...entry.flags].some((f) => /^\\(noselect|nonexistent)$/i.test(f)),+ })),+ )+ }+ status(path: string): Promise<MailboxStatus> {+ return this.wrap(async () => {+ const s = await this.client.status(path, {+ messages: true,+ unseen: true,+ uidNext: true,+ uidValidity: true,+ ...(this.condstore || this.can('CONDSTORE') ? { highestModseq: true } : {}),+ })+ return {+ messages: s.messages ?? 0,+ unseen: s.unseen ?? 0,+ uidNext: s.uidNext,+ uidValidity: s.uidValidity?.toString(),+ highestModseq: s.highestModseq?.toString(),+ }+ })+ }+ select(path: string): Promise<SelectedMailbox> {+ return this.wrap(async () => {+ const box = await this.client.mailboxOpen(path)+ return {+ path: box.path,+ uidValidity: box.uidValidity.toString(),+ uidNext: box.uidNext,+ exists: box.exists,+ highestModseq: box.noModseq ? undefined : box.highestModseq?.toString(),+ }+ })+ }+ search(criteria: SearchCriteria): Promise<number[]> {+ return this.wrap(async () => {+ const result = await this.client.search(criteria, { uid: true })+ return result ? [...result].sort((a, b) => a - b) : []+ })+ }+ fetch(range: string, query: FetchQuery, changedSince?: string): Promise<FetchedMessage[]> {+ return this.wrap(async () => {+ const result: FetchedMessage[] = []+ for await (const m of this.client.fetch(+ range,+ { uid: true, ...query },+ {+ uid: true,+ ...(changedSince && this.condstore ? { changedSince: BigInt(changedSince) } : {}),+ },+ )) {+ const env = m.envelope+ const envelope: Envelope | undefined = env+ ? {+ date: iso(env.date),+ subject: env.subject,+ messageId: env.messageId,+ inReplyTo: env.inReplyTo,+ from: address(env.from),+ sender: address(env.sender),+ replyTo: address(env.replyTo),+ to: address(env.to),+ cc: address(env.cc),+ bcc: address(env.bcc),+ }+ : undefined+ result.push({+ uid: m.uid,+ modseq: m.modseq?.toString(),+ flags: m.flags ? [...m.flags] : undefined,+ envelope,+ bodyStructure: m.bodyStructure ? bodyPart(m.bodyStructure) : undefined,+ internalDate: iso(m.internalDate),+ size: m.size,+ headers: m.headers?.toString('utf8'),+ })+ }+ return result+ })+ }+ source(uid: number, maxBytes: number): Promise<Uint8Array | undefined> {+ return this.wrap(async () => {+ const [size] = await this.fetch(String(uid), { size: true })+ if (!size || (size.size ?? 0) > maxBytes) return undefined+ const message = await this.client.fetchOne(String(uid), { source: true }, { uid: true })+ return message && message.source ? new Uint8Array(message.source) : undefined+ })+ }+ download(uid: number, part: string, maxBytes: number, truncate = false): Promise<Uint8Array> {+ return this.wrap(async () => {+ const { content } = await this.client.download(String(uid), part, {+ uid: true,+ maxBytes: maxBytes + 1,+ ...(truncate ? { chunkSize: Math.min(65536, Math.max(1024, maxBytes)) } : {}),+ })+ return bytes(content, maxBytes, truncate)+ })+ }+ store(uids: number[], operation: 'add' | 'remove', flags: string[], unchangedSince?: string) {+ return this.wrap(async () => {+ const options = {+ uid: true,+ ...(unchangedSince && this.condstore ? { unchangedSince: BigInt(unchangedSince) } : {}),+ }+ return operation === 'add'+ ? this.client.messageFlagsAdd(uids.join(','), flags, options)+ : this.client.messageFlagsRemove(uids.join(','), flags, options)+ })+ }+ move(uids: number[], destination: string): Promise<CopyResult | false> {+ // ImapFlow would emulate a missing MOVE with COPY and a mailbox-wide EXPUNGE.+ if (!this.can('MOVE'))+ throw new ProviderError('unsupported', 'This server does not support MOVE.')+ return this.wrap(async () => {+ const result = await this.client.messageMove(uids.join(','), destination, { uid: true })+ return result ? { uidValidity: result.uidValidity?.toString(), uidMap: result.uidMap } : false+ })+ }+ copy(uids: number[], destination: string): Promise<CopyResult | false> {+ return this.wrap(async () => {+ const result = await this.client.messageCopy(uids.join(','), destination, { uid: true })+ return result ? { uidValidity: result.uidValidity?.toString(), uidMap: result.uidMap } : false+ })+ }+ expunge(uids: number[]): Promise<boolean> {+ // Without UIDPLUS ImapFlow issues a plain EXPUNGE, which removes every \Deleted message.+ if (!this.can('UIDPLUS'))+ throw new ProviderError('unsupported', 'This server does not support UIDPLUS.')+ return this.wrap(async () => this.client.messageDelete(uids.join(','), { uid: true }))+ }+ append(path: string, content: Uint8Array, flags: string[], date?: Date): Promise<AppendResult> {+ return this.wrap(async () => {+ const result = await this.client.append(path, Buffer.from(content), flags, date)+ if (!result) throw new ProviderError('command', 'The server did not store the message.')+ return { uid: result.uid, uidValidity: result.uidValidity?.toString() }+ })+ }+ createMailbox(path: string) {+ return this.wrap(async () => void (await this.client.mailboxCreate(path)))+ }+ renameMailbox(path: string, newPath: string) {+ return this.wrap(async () => void (await this.client.mailboxRename(path, newPath)))+ }+ deleteMailbox(path: string) {+ return this.wrap(async () => void (await this.client.mailboxDelete(path)))+ }+}diff --git a/packages/imap/src/index.ts b/packages/imap/src/index.tsnew file mode 100644index 0000000..67d7101--- /dev/null+++ b/packages/imap/src/index.ts@@ -0,0 +1,8 @@+export * from './metadata-index'+export * from './port'+export * from './convert'+export * from './folders'+export * from './imapflow-port'+export * from './mime'+export * from './smtp'+export * from './provider'diff --git a/packages/imap/src/metadata-index.ts b/packages/imap/src/metadata-index.tsnew file mode 100644index 0000000..750a974--- /dev/null+++ b/packages/imap/src/metadata-index.ts@@ -0,0 +1,196 @@+import type { Address } from '@inlark/core'++/**+ * Persistent IMAP metadata, injected into the provider. The desktop app implements this with+ * SQLite in a worker thread; tests may run the same implementation in-process.+ *+ * Every method is scoped by `accountId`. Rows from different accounts never interact: threads,+ * Message-ID lookups and aliases are all per account.+ *+ * IDs are opaque, stable application IDs. A message ID identifies one message at one location+ * (mailbox + UIDVALIDITY + UID); `relocate` moves an ID after a confirmed server move. A+ * Message-ID header is never used to locate a message for a mutation.+ */+export interface MetadataIndex {+ close(): Promise<void>++ /**+ * Reconciles the server's folder list. Existing paths keep their IDs; new paths get new IDs;+ * paths no longer listed are removed together with their messages. Returns all mailboxes.+ */+ syncMailboxes(accountId: string, folders: FolderListing[]): Promise<IndexedMailbox[]>+ listMailboxes(accountId: string): Promise<IndexedMailbox[]>+ /** Keeps the mailbox ID (and its messages) when this app renames a folder. */+ renameMailbox(accountId: string, mailboxId: string, path: string, name: string): Promise<void>+ updateMailbox(accountId: string, mailboxId: string, patch: MailboxStatePatch): Promise<void>+ /**+ * Called when UIDVALIDITY changed: every stored location in the mailbox is stale, so its+ * messages are removed and indexing restarts. Threads and aliases stay.+ */+ resetMailbox(accountId: string, mailboxId: string, uidValidity: string): Promise<void>++ /**+ * Inserts or updates messages by location. A new location gets a new ID and a thread; an+ * existing location keeps its ID and only has flags, modseq and preview refreshed.+ * Returns the ID for each input, in order.+ */+ upsertMessages(accountId: string, messages: NewMessage[]): Promise<string[]>+ updateFlags(+ accountId: string,+ mailboxId: string,+ updates: { uid: number; flags: string[]; modseq?: string }[],+ ): Promise<void>+ /** Removes messages that no longer exist at these UIDs (expunged or vanished). */+ removeUids(accountId: string, mailboxId: string, uids: number[]): Promise<void>+ /** Removes messages by ID, e.g. after a confirmed deletion. */+ removeMessages(accountId: string, ids: string[]): Promise<void>+ /** All stored UIDs for a mailbox, ascending. Used to detect expunges during reconciliation. */+ knownUids(accountId: string, mailboxId: string): Promise<number[]>+ /** Moves an existing ID to a new location after the server confirmed the move. */+ relocate(accountId: string, id: string, location: MessageLocation): Promise<void>+ setPreview(accountId: string, id: string, preview: string): Promise<void>++ /** Messages by ID, in no particular order. Unknown IDs are skipped. */+ messages(accountId: string, ids: string[]): Promise<IndexedMessage[]>+ /** Messages at these UIDs of one mailbox. */+ messagesAt(accountId: string, mailboxId: string, uids: number[]): Promise<IndexedMessage[]>+ /** Every message of these conversations, following aliases of merged threads. */+ threadMessages(accountId: string, threadIds: string[]): Promise<IndexedMessage[]>+ /** The current ID for a thread ID that may have been merged into another. */+ resolveThread(accountId: string, threadId: string): Promise<string>+ /** Messages whose Message-ID header matches, optionally within one mailbox. */+ findByMessageId(+ accountId: string,+ messageId: string,+ mailboxId?: string,+ ): Promise<IndexedMessage[]>++ /**+ * Conversations with at least one message matching `filter`, newest first by the latest+ * matching message. `after` continues from the last item of a previous page (keyset+ * pagination), so rows indexed meanwhile cannot shift or duplicate what was already shown.+ */+ conversations(+ accountId: string,+ filter: ConversationFilter,+ page: { limit: number; offset?: number; after?: ConversationCursor },+ ): Promise<{ items: ConversationRow[]; total: number }>+ /** Total and unread message counts stored for the account, for progress reporting. */+ counts(accountId: string): Promise<{ messages: number }>++ getMeta(accountId: string, key: string): Promise<string | undefined>+ setMeta(accountId: string, key: string, value: string | undefined): Promise<void>+}++export interface FolderListing {+ path: string+ name: string+ delimiter: string+ parentPath: string | null+ /** The server-declared special-use flag, e.g. `\\Sent`. Never guessed from a name. */+ specialUse: string | null+ /** A flag the client library guessed from the name; kept separate so it can be reviewed. */+ guessedSpecialUse: string | null+ /** The folder cannot hold messages (`\\Noselect` / `\\NonExistent`). */+ noSelect: boolean+}++export interface IndexedMailbox extends FolderListing {+ id: string+ uidValidity: string | null+ uidNext: number | null+ highestModseq: string | null+ total: number+ unread: number+ /**+ * Every UID at or above this, up to `uidNext` at the last sync, is indexed. `null` means+ * nothing is indexed yet. Historical indexing walks this down towards 1.+ */+ indexedFrom: number | null+ /** Historical indexing reached UID 1. */+ complete: boolean+}++export type MailboxStatePatch = Partial<+ Pick<+ IndexedMailbox,+ 'uidValidity' | 'uidNext' | 'highestModseq' | 'total' | 'unread' | 'indexedFrom' | 'complete'+ >+>++export interface MessageLocation {+ mailboxId: string+ uidValidity: string+ uid: number+}++export interface NewMessage extends MessageLocation {+ modseq?: string+ /** Without angle brackets. `null` when the header is missing or unusable. */+ messageId: string | null+ inReplyTo: string[]+ /** Oldest first, as in the header; the index may keep only the most recent entries. */+ references: string[]+ subject: string+ from: Address[]+ to: Address[]+ cc: Address[]+ bcc: Address[]+ replyTo: Address[]+ /** ISO 8601 INTERNALDATE. */+ receivedAt: string+ sentAt?: string+ size: number+ flags: string[]+ hasAttachment: boolean+ preview: string+ /** The server's BODYSTRUCTURE, kept to find body parts and attachments later. */+ bodyStructure?: BodyPart+ unsubscribe?: { url: string; oneClick: boolean }+}++export interface IndexedMessage extends NewMessage {+ id: string+ threadId: string+}++/** A trimmed BODYSTRUCTURE node. `part` is the IMAP section number, e.g. `1.2`. */+export interface BodyPart {+ part?: string+ type: string+ parameters?: Record<string, string>+ id?: string+ encoding?: string+ size?: number+ disposition?: string+ dispositionParameters?: Record<string, string>+ childNodes?: BodyPart[]+}++export interface ConversationFilter {+ /** Only messages in these mailboxes. */+ mailboxIds?: string[]+ /** Never messages in these mailboxes (e.g. Junk and Trash for “All mail”). */+ excludeMailboxIds?: string[]+ /** Only these message IDs, e.g. server search results. */+ ids?: string[]+ flagged?: boolean+ unseen?: boolean+ hasAttachment?: boolean+ /** ISO dates, inclusive lower and exclusive upper bound on `receivedAt`. */+ after?: string+ before?: string+}++export interface ConversationCursor {+ receivedAt: string+ threadId: string+}++export interface ConversationRow {+ threadId: string+ /** The newest message matching the filter, which represents the conversation in lists. */+ latest: IndexedMessage+ /** Messages in the whole conversation, matching or not. */+ count: number+}diff --git a/packages/imap/src/mime.ts b/packages/imap/src/mime.tsnew file mode 100644index 0000000..e975a99--- /dev/null+++ b/packages/imap/src/mime.ts@@ -0,0 +1,150 @@+import MailComposer from 'nodemailer/lib/mail-composer'+import { simpleParser, type AddressObject } from 'mailparser'+import { parseUnsubscribe, ProviderError, type Address } from '@inlark/core'++export interface ComposeInput {+ from: Address+ to: Address[]+ cc: Address[]+ bcc: Address[]+ subject: string+ html: string+ text: string+ /** Without angle brackets. */+ messageId: string+ inReplyTo?: string[]+ references?: string[]+ date?: Date+ attachments: { name: string; type: string; cid?: string; content: Uint8Array }[]+ /** Drafts keep Bcc so another client resuming the draft sees it; transmitted/Sent copies never do. */+ keepBcc?: boolean+}++export interface ParsedMime {+ subject: string+ from: Address[]+ to: Address[]+ cc: Address[]+ bcc: Address[]+ replyTo: Address[]+ date?: string+ /** Message ids are returned without angle brackets. */+ messageId?: string+ inReplyTo: string[]+ references: string[]+ /** '' when the message has no HTML part; never generated from the text. */+ html: string+ text: string+ attachments: {+ name: string+ type: string+ size: number+ cid?: string+ disposition?: string+ content: Uint8Array+ }[]+ unsubscribe?: { url: string; oneClick: boolean }+}++export const defaultMaxMimeBytes = 64 * 1024 * 1024++const bracketed = (id: string) => `<${id.trim().replace(/^<|>$/g, '')}>`+const addresses = (list: Address[]) =>+ list.length ? list.map((a) => ({ name: a.name, address: a.email })) : undefined+// A copy, so the result never shares a pooled ArrayBuffer with unrelated memory.+const plain = (bytes: Uint8Array) => new Uint8Array(bytes)++export async function composeMime(input: ComposeInput): Promise<Uint8Array> {+ const node = new MailComposer({+ from: { name: input.from.name, address: input.from.email },+ to: addresses(input.to),+ cc: addresses(input.cc),+ bcc: addresses(input.bcc),+ subject: input.subject,+ text: input.text || undefined,+ html: input.html || undefined,+ messageId: bracketed(input.messageId),+ inReplyTo: input.inReplyTo?.length ? input.inReplyTo.map(bracketed).join(' ') : undefined,+ references: input.references?.length ? input.references.map(bracketed) : undefined,+ date: input.date ?? new Date(),+ attachments: input.attachments.map((a) => ({+ filename: a.name,+ contentType: a.type || 'application/octet-stream',+ content: Buffer.from(a.content.buffer, a.content.byteOffset, a.content.byteLength),+ contentDisposition: a.cid ? 'inline' : 'attachment',+ ...(a.cid ? { cid: a.cid } : {}),+ })),+ // Content is always supplied in memory; never let a value be read as a path or URL.+ disableFileAccess: true,+ disableUrlAccess: true,+ // The default prefix names the library; boundaries should not identify the client.+ boundaryPrefix: '--',+ // Canonical CRLF, so the bytes stored as a Sent copy are exactly the bytes transmitted.+ newline: 'windows',+ }).compile()+ node.keepBcc = !!input.keepBcc+ return plain(await node.build())+}++const ids = (value: unknown): string[] =>+ [value ?? []]+ .flat()+ .flatMap((v) => String(v).match(/<[^<>]+>/g) ?? (String(v).trim() ? [String(v).trim()] : []))+ .map((id) => id.replace(/^<|>$/g, '').trim())+ .filter(Boolean)++const addressList = (value?: AddressObject | AddressObject[]): Address[] =>+ [value ?? []].flat().flatMap((object) =>+ object.value+ .flatMap((a) => (a.group ? a.group : [a]))+ .filter((a) => a.address)+ .map((a) => ({ name: a.name || '', email: a.address! })),+ )++/** Mirrors the JMAP provider: https or mailto only, never credentials in the URL. */++export async function parseMime(+ source: Uint8Array,+ options: { maxBytes?: number } = {},+): Promise<ParsedMime> {+ const maxBytes = options.maxBytes ?? defaultMaxMimeBytes+ if (source.byteLength > maxBytes)+ throw new ProviderError('tooLarge', 'This message is too large to open.')+ const mail = await simpleParser(+ Buffer.from(source.buffer, source.byteOffset, source.byteLength),+ { skipTextToHtml: true, skipTextLinks: true, skipImageLinks: true, keepCidLinks: true },+ )+ const header = (key: string) => {+ const line = mail.headerLines?.find((h) => h.key === key)?.line+ return line+ ?.slice(line.indexOf(':') + 1)+ .replace(/\r?\n[ \t]+/g, ' ')+ .trim()+ }+ const date = mail.date && !Number.isNaN(mail.date.getTime()) ? mail.date.toISOString() : undefined+ const messageId = ids(mail.messageId)[0]+ const unsubscribe = parseUnsubscribe(header('list-unsubscribe'), header('list-unsubscribe-post'))+ return {+ subject: mail.subject ?? '',+ from: addressList(mail.from),+ to: addressList(mail.to),+ cc: addressList(mail.cc),+ bcc: addressList(mail.bcc),+ replyTo: addressList(mail.replyTo),+ ...(date ? { date } : {}),+ ...(messageId ? { messageId } : {}),+ inReplyTo: ids(mail.inReplyTo),+ references: ids(mail.references),+ html: typeof mail.html === 'string' ? mail.html : '',+ text: mail.text ?? '',+ attachments: mail.attachments.map((a) => ({+ name: a.filename || 'attachment',+ type: a.contentType || 'application/octet-stream',+ size: a.content.byteLength,+ ...(a.cid ? { cid: a.cid.replace(/^<|>$/g, '') } : {}),+ ...(a.contentDisposition ? { disposition: a.contentDisposition } : {}),+ content: plain(a.content),+ })),+ ...(unsubscribe ? { unsubscribe } : {}),+ }+}diff --git a/packages/imap/src/port.ts b/packages/imap/src/port.tsnew file mode 100644index 0000000..3910240--- /dev/null+++ b/packages/imap/src/port.ts@@ -0,0 +1,137 @@+import type { Address, ServerSettings } from '@inlark/core'+import type { BodyPart, FolderListing } from './metadata-index'++/**+ * The small part of IMAP the provider needs, on one connection. The production adapter wraps+ * ImapFlow; tests use an in-memory server. UIDs are always used, never sequence numbers.+ *+ * Safety rules every implementation must keep:+ * - `move` only runs with the MOVE extension and never falls back to COPY + EXPUNGE itself.+ * - `expunge` only runs `UID EXPUNGE` (UIDPLUS). A plain `EXPUNGE` would also remove messages+ * another client flagged for deletion, so it is never issued.+ */+export interface ImapPort {+ /** Upper-case capability names, available after `connect`. */+ readonly capabilities: ReadonlySet<string>+ /** CONDSTORE is enabled, so modseqs and conditional stores work. */+ readonly condstore: boolean+ connect(): Promise<void>+ close(): Promise<void>+ /** `close` fires once when the connection ends for any reason. */+ on(event: 'close', listener: () => void): void+ /** Unsolicited changes in the selected mailbox (used by the IDLE connection). */+ on(event: 'exists' | 'expunge' | 'flags', listener: (path: string) => void): void+ list(): Promise<FolderListing[]>+ status(path: string): Promise<MailboxStatus>+ select(path: string): Promise<SelectedMailbox>+ /** UID SEARCH in the selected mailbox. */+ search(criteria: SearchCriteria): Promise<number[]>+ /** UID FETCH in the selected mailbox. `range` is a UID set such as `1:*` or `4,8,15`. */+ fetch(range: string, query: FetchQuery, changedSince?: string): Promise<FetchedMessage[]>+ /** The complete message, or undefined if it no longer exists or exceeds `maxBytes`. */+ source(uid: number, maxBytes: number): Promise<Uint8Array | undefined>+ /**+ * One body part, with transfer encoding decoded and text converted to UTF-8. Larger parts+ * fail unless `truncate` is set, which returns the first `maxBytes` (for previews).+ */+ download(uid: number, part: string, maxBytes: number, truncate?: boolean): Promise<Uint8Array>+ /** UID STORE ±FLAGS, conditional on UNCHANGEDSINCE when given and CONDSTORE is enabled. */+ store(+ uids: number[],+ operation: 'add' | 'remove',+ flags: string[],+ unchangedSince?: string,+ ): Promise<boolean>+ move(uids: number[], destination: string): Promise<CopyResult | false>+ copy(uids: number[], destination: string): Promise<CopyResult | false>+ /** Flags the UIDs \Deleted and removes exactly them with UID EXPUNGE. */+ expunge(uids: number[]): Promise<boolean>+ append(path: string, content: Uint8Array, flags: string[], date?: Date): Promise<AppendResult>+ createMailbox(path: string): Promise<void>+ renameMailbox(path: string, newPath: string): Promise<void>+ deleteMailbox(path: string): Promise<void>+}++export interface ImapServerOptions extends ServerSettings {+ password: string+ timeoutMs?: number+ /** Tests only: trust an extra certificate authority. */+ tls?: { ca?: string | Uint8Array }+}++export interface MailboxStatus {+ messages: number+ unseen: number+ uidNext?: number+ uidValidity?: string+ highestModseq?: string+}++export interface SelectedMailbox {+ path: string+ uidValidity: string+ uidNext: number+ exists: number+ highestModseq?: string+}++export interface SearchCriteria {+ all?: boolean+ uid?: string+ text?: string+ from?: string+ to?: string+ subject?: string+ since?: Date+ before?: Date+ seen?: boolean+ flagged?: boolean+ deleted?: boolean+ header?: Record<string, string>+}++export interface FetchQuery {+ flags?: boolean+ envelope?: boolean+ bodyStructure?: boolean+ internalDate?: boolean+ size?: boolean+ /** Raw header lines for these header names. */+ headers?: string[]+}++export interface Envelope {+ date?: string+ subject?: string+ messageId?: string+ inReplyTo?: string+ from?: Address[]+ sender?: Address[]+ replyTo?: Address[]+ to?: Address[]+ cc?: Address[]+ bcc?: Address[]+}++export interface FetchedMessage {+ uid: number+ modseq?: string+ flags?: string[]+ envelope?: Envelope+ bodyStructure?: BodyPart+ internalDate?: string+ size?: number+ /** The requested header lines, unparsed. */+ headers?: string+}++export interface CopyResult {+ uidValidity?: string+ /** Source UID → destination UID, when the server reports COPYUID (UIDPLUS). */+ uidMap?: Map<number, number>+}++/** `uid` is known when the server reports APPENDUID (UIDPLUS). */+export type AppendResult = { uid?: number; uidValidity?: string }++export type PortFactory = (options: ImapServerOptions, purpose: 'command' | 'idle') => ImapPortdiff --git a/packages/imap/src/provider.ts b/packages/imap/src/provider.tsnew file mode 100644index 0000000..96d4e68--- /dev/null+++ b/packages/imap/src/provider.ts@@ -0,0 +1,1315 @@+import { randomUUID } from 'node:crypto'+import {+ accountKey,+ accountColors,+ conversationFromMessages,+ isProviderError,+ ProviderError,+ type Account,+ type AccountLimits,+ type Attachment,+ type Draft,+ type FolderMappingReview,+ type FolderMappings,+ type Identity,+ type ImapConnectionConfig,+ type Mailbox,+ type MailProvider,+ type MailQuery,+ type Message,+ type MessageChanges,+ type OutgoingMessage,+ type ProviderCapabilities,+ type ProviderEvent,+ type ProviderPage,+ type SubmissionOutcome,+} from '@inlark/core'+import {+ attachmentsOf,+ flagFromKeyword,+ messageIds,+ metadataQuery,+ parseBlobId,+ partSection,+ previewText,+ textParts,+ toMessage,+ toNewMessage,+ uidSet,+} from './convert'+import { isInbox, reviewFolders, rolesByPath } from './folders'+import { ImapFlowPort } from './imapflow-port'+import type {+ ConversationCursor,+ ConversationFilter,+ IndexedMailbox,+ IndexedMessage,+ MetadataIndex,+} from './metadata-index'+import { composeMime, parseMime } from './mime'+import type { ImapPort, ImapServerOptions, PortFactory, SearchCriteria } from './port'+import { submitSmtp, verifySmtp, type SmtpSettings } from './smtp'++export interface ImapProviderOptions {+ connectionId: string+ name: string+ config: ImapConnectionConfig+ password: string+ /** Only when the outgoing server has its own credentials. */+ outgoingPassword?: string+ folders?: FolderMappings+ index: MetadataIndex+ /** Reads a staged attachment by its ID; the desktop app owns the files. */+ readAttachment(id: string): Promise<Uint8Array>+ /** Keeps the index current in the background. Off for temporary connection tests. */+ background?: boolean+ ports?: PortFactory+ smtp?: {+ verify: (settings: SmtpSettings) => Promise<void>+ submit: (+ settings: SmtpSettings,+ envelope: OutgoingMessage['envelope'],+ mime: Uint8Array,+ ) => Promise<SubmissionOutcome>+ }+ /** Tests only: trust an extra certificate authority. */+ tls?: { ca?: string | Uint8Array }+ timing?: Partial<Timing>+}+interface Timing {+ /** How often every folder is checked when nothing prompts it. */+ reconcileMs: number+ /** How often expunges and flags are fully compared even without a visible change. */+ fullReconcileMs: number+ initialBatch: number+ historicalBatch: number+ previews: number+ /** Grace period for a server that files its own Sent copy after submission. */+ sentCopyGraceMs: number+}+const defaultTiming: Timing = {+ reconcileMs: 120_000,+ fullReconcileMs: 15 * 60_000,+ initialBatch: 200,+ historicalBatch: 500,+ previews: 30,+ sentCopyGraceMs: 1500,+}+type Task = {+ run: (port: ImapPort) => Promise<unknown>+ resolve: (value: unknown) => void+ reject: (error: unknown) => void+ background: boolean+}+const roleViews = ['inbox', 'archive', 'sent', 'drafts', 'junk', 'trash']+const bodyLimit = 10_000_000+const partLimit = 5_000_000+const byMailbox = <T extends { mailboxId: string }>(items: T[]) => {+ const groups = new Map<string, T[]>()+ for (const item of items)+ groups.set(item.mailboxId, [...(groups.get(item.mailboxId) || []), item])+ return groups+}+const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))++export class ImapProvider implements MailProvider {+ readonly capabilities: ProviderCapabilities = {+ mail: true,+ submission: true,+ push: true,+ maxObjectsInGet: 500,+ maxObjectsInSet: 500,+ maxUploadSize: 100_000_000,+ blobUpload: false,+ exclusiveMailboxes: true,+ sentCopy: 'client',+ }+ private readonly accountId: string+ private readonly timing: Timing+ private readonly ports: PortFactory+ private folders: FolderMappings+ private command?: ImapPort+ private connecting?: Promise<ImapPort>+ private idle?: ImapPort+ private queue: Task[] = []+ private pumping = false+ private listeners = new Set<(event: ProviderEvent) => void>()+ private disposed = false+ private started = false+ private wakeLoop?: () => void+ private pending: 'none' | 'inbox' | 'all' = 'none'+ private lastSync = 0+ private lastFull = new Map<string, number>()+ private uidLists = new Map<string, number[]>()+ private searches = new Map<string, { ids: string[]; incomplete: boolean; at: number }>()+ private cursors = new Map<string, ConversationCursor>()+ private bodies = new Map<string, { html: string; text: string }>()+ private state: 'connected' | 'offline' | 'authentication' = 'connected'+ private lastFailure?: { at: number; error: unknown }+ private limits: AccountLimits = {}+ constructor(private options: ImapProviderOptions) {+ this.accountId = accountKey(options.connectionId, 'imap')+ this.timing = { ...defaultTiming, ...options.timing }+ this.ports = options.ports || ((settings, purpose) => new ImapFlowPort(settings, purpose))+ this.folders = options.folders || {}+ }+ private get index() {+ return this.options.index+ }+ private emit(event: ProviderEvent) {+ for (const listener of this.listeners) listener(event)+ }+ private imapSettings(): ImapServerOptions {+ return {+ ...this.options.config.incoming,+ password: this.options.password,+ tls: this.options.tls,+ }+ }+ private smtpSettings(): SmtpSettings {+ const { config } = this.options+ return {+ ...config.outgoing,+ username: config.outgoingSameCredentials+ ? config.incoming.username+ : config.outgoing.username,+ password: config.outgoingSameCredentials+ ? this.options.password+ : this.options.outgoingPassword || '',+ tls: this.options.tls,+ }+ }++ // Connection and command queue++ /** Runs one task at a time on the command connection. User work goes before background work. */+ private run<T>(task: (port: ImapPort) => Promise<T>, background = false): Promise<T> {+ return new Promise<T>((resolve, reject) => {+ const entry: Task = {+ run: task,+ resolve: resolve as (v: unknown) => void,+ reject,+ background,+ }+ const firstBackground = this.queue.findIndex((t) => t.background)+ if (background || firstBackground < 0) this.queue.push(entry)+ else this.queue.splice(firstBackground, 0, entry)+ void this.pump()+ })+ }+ private async pump() {+ if (this.pumping) return+ this.pumping = true+ try {+ while (this.queue.length) {+ const task = this.queue.shift()!+ try {+ task.resolve(await task.run(await this.commandPort()))+ } catch (error) {+ task.reject(error)+ }+ }+ } finally {+ this.pumping = false+ }+ }+ private commandPort(): Promise<ImapPort> {+ if (this.disposed) return Promise.reject(new ProviderError('offline', 'Account disconnected.'))+ if (this.command) return Promise.resolve(this.command)+ // While the server is unreachable, fail at once instead of waiting out another timeout.+ if (this.lastFailure && Date.now() - this.lastFailure.at < 5000)+ return Promise.reject(this.lastFailure.error)+ this.connecting ??= (async () => {+ const port = this.ports(this.imapSettings(), 'command')+ port.on('close', () => {+ if (this.command === port) this.command = undefined+ })+ try {+ await port.connect()+ } catch (error) {+ this.lastFailure = { at: Date.now(), error }+ void port.close().catch(() => {})+ throw error+ }+ this.lastFailure = undefined+ if (this.disposed) {+ void port.close().catch(() => {})+ throw new ProviderError('offline', 'Account disconnected.')+ }+ this.command = port+ this.limits = limitsFor(port.capabilities)+ return port+ })().finally(() => (this.connecting = undefined))+ return this.connecting+ }+ private setState(state: 'connected' | 'offline' | 'authentication', message?: string) {+ if (this.state === state) return+ this.state = state+ this.emit({ type: 'status', accountId: this.accountId, state, message })+ }++ async connect(): Promise<Account[]> {+ this.disposed = false+ await this.run(async (port) => {+ const boxes = await this.refreshFolders(port)+ // Counts for the folders shown first; the rest arrive with the first background pass.+ const roles = rolesByPath(reviewFolders(boxes, this.folders))+ for (const box of boxes.filter(+ (b) => !b.noSelect && (isInbox(b.path) || roles.has(b.path)),+ )) {+ const status = await port.status(box.path)+ await this.index.updateMailbox(this.accountId, box.id, {+ total: status.messages,+ unread: status.unseen,+ })+ }+ })+ if (this.options.background !== false && !this.started) {+ this.started = true+ void this.syncLoop()+ void this.idleLoop()+ }+ this.state = 'connected'+ return [this.account()]+ }+ private account(): Account {+ return {+ id: this.accountId,+ connectionId: this.options.connectionId,+ remoteId: 'imap',+ name: this.options.name || this.options.config.email,+ email: this.options.config.email,+ color: accountColors[1],+ status: 'connected',+ protocol: 'imap',+ ...(Object.keys(this.limits).length ? { limits: this.limits } : {}),+ }+ }+ verifyOutgoing(): Promise<void> {+ return (this.options.smtp?.verify || verifySmtp)(this.smtpSettings())+ }++ // Folders++ private async refreshFolders(port: ImapPort): Promise<IndexedMailbox[]> {+ return this.index.syncMailboxes(this.accountId, await port.list())+ }+ private review(boxes: IndexedMailbox[]): FolderMappingReview {+ return reviewFolders(boxes, this.folders)+ }+ private async roleBox(role: string): Promise<IndexedMailbox | undefined> {+ const boxes = await this.index.listMailboxes(this.accountId)+ if (role === 'inbox') return boxes.find((b) => isInbox(b.path))+ const path = this.review(boxes).mappings[role as keyof FolderMappingReview['mappings']]?.path+ return boxes.find((b) => b.path === path)+ }+ async mailboxes(account: Account): Promise<Mailbox[]> {+ const boxes = await this.index.listMailboxes(this.accountId)+ // The service asks for folders on every refresh and after resume; reconcile when due.+ if (Date.now() - this.lastSync > 45_000) this.requestSync('all')+ const roles = rolesByPath(this.review(boxes))+ const byPath = new Map(boxes.map((b) => [b.path, b]))+ const move = !this.limits.move+ return boxes.map((box) => {+ const role = isInbox(box.path) ? 'inbox' : roles.get(box.path) || null+ return {+ id: box.id,+ accountId: account.id,+ name: isInbox(box.path) ? 'Inbox' : box.name,+ role,+ parentId: (box.parentPath && byPath.get(box.parentPath)?.id) || null,+ totalEmails: box.total,+ unreadEmails: box.unread,+ rights: {+ mayReadItems: !box.noSelect,+ mayAddItems: !box.noSelect,+ mayRemoveItems: !box.noSelect && move,+ maySetSeen: !box.noSelect,+ maySetKeywords: !box.noSelect,+ mayCreateChild: true,+ mayRename: !role,+ mayDelete: !role,+ },+ }+ })+ }+ async folderMappings(): Promise<FolderMappingReview> {+ return this.review(await this.index.listMailboxes(this.accountId))+ }+ async setFolderMappings(+ _account: Account,+ requested: FolderMappings,+ ): Promise<FolderMappingReview> {+ const mappings: FolderMappings = { ...requested }+ const boxes = await this.run(async (port) => {+ let boxes = await this.refreshFolders(port)+ for (const [role, mapping] of Object.entries(mappings) as [+ keyof FolderMappings,+ FolderMappings[keyof FolderMappings],+ ][])+ if (mapping?.create && !boxes.some((b) => b.path === mapping.path)) {+ const path = newFolderPath(boxes, mapping.path)+ if (!boxes.some((b) => b.path === path)) await port.createMailbox(path)+ mappings[role] = { path }+ boxes = await this.refreshFolders(port)+ }+ return boxes+ })+ for (const [role, mapping] of Object.entries(mappings))+ if (mapping && !boxes.some((b) => b.path === mapping.path && !b.noSelect))+ throw new ProviderError(+ 'notFound',+ 'The folder “' + mapping.path + '” for ' + role + ' does not exist.',+ )+ this.folders = Object.fromEntries(+ Object.entries(mappings).map(([role, value]) => [role, value ? { path: value.path } : null]),+ )+ return this.review(boxes)+ }+ async folder(+ _account: Account,+ operation: 'create' | 'rename' | 'delete',+ id?: string,+ name?: string,+ parentId?: string,+ ): Promise<void> {+ const boxes = await this.index.listMailboxes(this.accountId)+ const roles = rolesByPath(this.review(boxes))+ const box = boxes.find((b) => b.id === id)+ const delimiter = boxes.find((b) => b.delimiter)?.delimiter || '/'+ if (operation !== 'create' && (!box || isInbox(box.path) || roles.has(box.path)))+ throw new ProviderError('permission', 'Special folders cannot be renamed or deleted.')+ if (name && name.includes(box?.delimiter || delimiter))+ throw new ProviderError('invalid', 'Folder names cannot contain “' + delimiter + '”.')+ await this.run(async (port) => {+ if (operation === 'create') {+ const parent = boxes.find((b) => b.id === parentId)+ await port.createMailbox(+ parent ? parent.path + parent.delimiter + name : newFolderPath(boxes, name!),+ )+ } else if (operation === 'rename') {+ const target = box!.parentPath ? box!.parentPath + box!.delimiter + name : name!+ await port.renameMailbox(box!.path, target)+ // Keep IDs and indexed mail for the folder and everything below it.+ await this.index.renameMailbox(this.accountId, box!.id, target, name!)+ for (const child of boxes.filter((b) => b.path.startsWith(box!.path + box!.delimiter)))+ await this.index.renameMailbox(+ this.accountId,+ child.id,+ target + child.path.slice(box!.path.length),+ child.name,+ )+ } else {+ // IMAP DELETE removes the messages too; like JMAP here, a folder must be empty first.+ if (boxes.some((b) => b.parentPath === box!.path))+ throw new ProviderError('folder', 'Delete or move the folders inside it first.')+ if ((await port.status(box!.path)).messages > 0)+ throw new ProviderError(+ 'folder',+ 'This folder still contains messages. Move or delete them first.',+ )+ await port.deleteMailbox(box!.path)+ }+ await this.refreshFolders(port)+ })+ }++ // Synchronization++ requestSync(scope: 'inbox' | 'all') {+ if (this.pending !== 'all') this.pending = scope+ this.wakeLoop?.()+ }+ private wait(ms: number) {+ return new Promise<void>((resolve) => {+ const timer = setTimeout(done, ms)+ function done() {+ clearTimeout(timer)+ resolve()+ }+ this.wakeLoop = done+ }).finally(() => (this.wakeLoop = undefined))+ }+ private async syncLoop() {+ let failures = 0+ while (!this.disposed) {+ try {+ const scope = this.pending === 'none' ? 'all' : this.pending+ this.pending = 'none'+ await this.syncPass(scope)+ failures = 0+ this.setState('connected')+ let more = true+ while (!this.disposed && more && this.pending === 'none')+ more = await this.historicalBatch()+ if (!this.disposed && this.pending === 'none') await this.wait(this.timing.reconcileMs)+ } catch (error) {+ if (this.disposed) break+ if (isProviderError(error, 'authentication')) this.setState('authentication', error.message)+ else if (isProviderError(error, 'network', 'tls')) this.setState('offline', error.message)+ failures+++ await this.wait(Math.min(60_000, 1000 * 2 ** Math.min(failures, 6)))+ }+ }+ }+ /** Keeps a second connection idling on Inbox so new mail arrives without polling. */+ private async idleLoop() {+ let attempt = 0+ while (!this.disposed) {+ const port = this.ports(this.imapSettings(), 'idle')+ try {+ const closed = new Promise<void>((resolve) => port.on('close', resolve))+ for (const event of ['exists', 'expunge', 'flags'] as const)+ port.on(event, () => this.requestSync('inbox'))+ await port.connect()+ await port.select('INBOX')+ if (this.disposed) break+ this.idle = port+ attempt = 0+ await closed+ } catch {+ void port.close().catch(() => {})+ } finally {+ if (this.idle === port) this.idle = undefined+ }+ if (this.disposed) break+ // Changes may have been missed while disconnected.+ this.requestSync('inbox')+ await sleep(Math.min(60_000, 1000 * 2 ** Math.min(attempt++, 6)))+ }+ }+ private ordered(boxes: IndexedMailbox[]) {+ const roles = rolesByPath(this.review(boxes))+ const rank = (b: IndexedMailbox) => (isInbox(b.path) ? 0 : roles.has(b.path) ? 1 : 2)+ return boxes.filter((b) => !b.noSelect).sort((a, b) => rank(a) - rank(b))+ }+ private async syncPass(scope: 'inbox' | 'all') {+ const boxes = await this.run(async (port) => this.refreshFolders(port), true)+ let changed = false+ for (const box of this.ordered(boxes)) {+ if (this.disposed) return+ if (scope === 'inbox' && !isInbox(box.path)) continue+ changed = (await this.run((port) => this.syncMailbox(port, box), true)) || changed+ }+ this.lastSync = Date.now()+ if (changed) this.emit({ type: 'changed', accountId: this.accountId })+ await this.emitProgress()+ }+ private async emitProgress() {+ const boxes = (await this.index.listMailboxes(this.accountId)).filter((b) => !b.noSelect)+ const { messages } = await this.index.counts(this.accountId)+ this.emit({+ type: 'indexing',+ accountId: this.accountId,+ indexing: {+ indexed: messages,+ total: Math.max(+ messages,+ boxes.reduce((sum, b) => sum + b.total, 0),+ ),+ complete: boxes.every((b) => b.complete),+ },+ })+ }+ /** Brings one folder up to date. Returns whether anything visible changed. */+ private async syncMailbox(port: ImapPort, stored: IndexedMailbox): Promise<boolean> {+ let box = stored+ const status = await port.status(box.path)+ let changed = false+ if (box.uidValidity && status.uidValidity && status.uidValidity !== box.uidValidity) {+ // Every stored UID in this folder is meaningless now.+ await this.index.resetMailbox(this.accountId, box.id, status.uidValidity)+ this.uidLists.delete(box.id)+ box = {+ ...box,+ uidValidity: status.uidValidity,+ uidNext: null,+ highestModseq: null,+ indexedFrom: null,+ complete: false,+ }+ changed = true+ }+ const full = Date.now() - (this.lastFull.get(box.id) || 0) > this.timing.fullReconcileMs+ const same =+ box.uidNext !== null &&+ status.uidNext === box.uidNext &&+ status.messages === box.total &&+ status.unseen === box.unread &&+ (!status.highestModseq || status.highestModseq === box.highestModseq)+ if (same && !full) return changed+ const selected = await port.select(box.path)+ if (box.uidValidity && selected.uidValidity !== box.uidValidity) return changed+ const location = { mailboxId: box.id, uidValidity: selected.uidValidity }+ if (box.uidNext === null || box.indexedFrom === null) {+ const uids = await port.search({ all: true })+ this.uidLists.set(box.id, uids)+ const newest = uids.slice(-this.timing.initialBatch)+ const ids = await this.store(port, newest, location)+ await this.index.updateMailbox(this.accountId, box.id, {+ uidValidity: selected.uidValidity,+ uidNext: selected.uidNext,+ highestModseq: selected.highestModseq ?? null,+ total: status.messages,+ unread: status.unseen,+ indexedFrom: newest[0] ?? 1,+ complete: newest.length === uids.length,+ })+ this.lastFull.set(box.id, Date.now())+ void this.fillPreviews(ids.slice(-this.timing.previews))+ return true+ }+ let added: string[] = []+ if (selected.uidNext > box.uidNext) {+ const fetched = (await port.fetch(box.uidNext + ':*', metadataQuery)).filter(+ (m) => m.uid >= box.uidNext!,+ )+ added = await this.index.upsertMessages(+ this.accountId,+ fetched.map((m) => toNewMessage(m, location)),+ )+ changed ||= added.length > 0+ }+ if (port.condstore && box.highestModseq && selected.highestModseq !== box.highestModseq) {+ const flags = await port.fetch(+ (box.indexedFrom || 1) + ':*',+ { flags: true },+ box.highestModseq,+ )+ await this.index.updateFlags(+ this.accountId,+ box.id,+ flags.map((m) => ({ uid: m.uid, flags: m.flags || [], modseq: m.modseq })),+ )+ changed ||= flags.length > 0+ } else if (!port.condstore && (status.unseen !== box.unread || full)) {+ // Without CONDSTORE, compare flags for the most recent part of the folder.+ const known = (await this.index.knownUids(this.accountId, box.id)).slice(full ? -5000 : -500)+ if (known.length) {+ const flags = await port.fetch(uidSet(known), { flags: true })+ await this.index.updateFlags(+ this.accountId,+ box.id,+ flags.map((m) => ({ uid: m.uid, flags: m.flags || [] })),+ )+ changed = true+ }+ }+ // Arrivals alone explain a count change; anything else means messages were expunged.+ if (full || status.messages !== box.total + added.length) {+ const present = await port.search({ all: true })+ this.uidLists.set(box.id, present)+ const set = new Set(present)+ const gone = (await this.index.knownUids(this.accountId, box.id)).filter(+ (uid) => !set.has(uid),+ )+ if (gone.length) {+ await this.index.removeUids(this.accountId, box.id, gone)+ changed = true+ }+ this.lastFull.set(box.id, Date.now())+ }+ await this.index.updateMailbox(this.accountId, box.id, {+ uidValidity: selected.uidValidity,+ uidNext: selected.uidNext,+ highestModseq: selected.highestModseq ?? null,+ total: status.messages,+ unread: status.unseen,+ })+ if (added.length) void this.fillPreviews(added)+ return changed || status.unseen !== box.unread || status.messages !== box.total+ }+ private async store(+ port: ImapPort,+ uids: number[],+ location: { mailboxId: string; uidValidity: string },+ ) {+ const ids: string[] = []+ for (let i = 0; i < uids.length; i += 250) {+ const fetched = await port.fetch(uidSet(uids.slice(i, i + 250)), metadataQuery)+ ids.push(+ ...(await this.index.upsertMessages(+ this.accountId,+ fetched.map((m) => toNewMessage(m, location)),+ )),+ )+ }+ return ids+ }+ /** Indexes one batch of older mail. Returns whether any folder still has older mail. */+ private async historicalBatch(): Promise<boolean> {+ const boxes = await this.index.listMailboxes(this.accountId)+ const box = this.ordered(boxes).find(+ (b) => !b.complete && b.indexedFrom !== null && b.uidValidity,+ )+ if (!box) return false+ await this.run(async (port) => {+ const selected = await port.select(box.path)+ if (selected.uidValidity !== box.uidValidity) return+ let uids = this.uidLists.get(box.id)+ if (!uids) {+ uids = box.indexedFrom! > 1 ? await port.search({ uid: '1:' + (box.indexedFrom! - 1) }) : []+ this.uidLists.set(box.id, uids)+ }+ const below = uids.filter((uid) => uid < box.indexedFrom!)+ const batch = below.slice(-this.timing.historicalBatch)+ if (batch.length)+ await this.store(port, batch, { mailboxId: box.id, uidValidity: selected.uidValidity })+ await this.index.updateMailbox(this.accountId, box.id, {+ indexedFrom: batch[0] ?? box.indexedFrom,+ complete: batch.length === below.length,+ })+ if (batch.length === below.length) this.uidLists.delete(box.id)+ }, true)+ // Older mail must never look like new mail.+ this.emit({ type: 'changed', accountId: this.accountId, historical: true })+ await this.emitProgress()+ return true+ }+ private async fillPreviews(ids: string[]) {+ if (!ids.length || this.disposed) return+ const rows = await this.index.messages(this.accountId, ids)+ for (const [mailboxId, items] of byMailbox(rows)) {+ const box = (await this.index.listMailboxes(this.accountId)).find((b) => b.id === mailboxId)+ if (!box) continue+ await this.run(async (port) => {+ const selected = await port.select(box.path)+ for (const row of items) {+ if (row.preview || selected.uidValidity !== row.uidValidity) continue+ const { text, html } = textParts(row.bodyStructure)+ const part = text || html+ if (!part) continue+ try {+ const bytes = await port.download(row.uid, partSection(part), 4096, true)+ const preview = previewText(new TextDecoder().decode(bytes), part === html)+ if (preview) await this.index.setPreview(this.accountId, row.id, preview)+ } catch {+ // A missing preview is harmless; the body loads when the message opens.+ }+ }+ }, true).catch(() => {})+ }+ this.emit({ type: 'changed', accountId: this.accountId, historical: true })+ }++ // Reading++ private async scope(query: MailQuery, boxes: IndexedMailbox[]) {+ const roles = rolesByPath(this.review(boxes))+ const roleOf = (b: IndexedMailbox) => (isInbox(b.path) ? 'inbox' : roles.get(b.path))+ const selectable = boxes.filter((b) => !b.noSelect)+ if (query.mailboxId) {+ const box = selectable.find((b) => b.id === query.mailboxId)+ return box ? { boxes: [box], filter: { mailboxIds: [box.id] } } : undefined+ }+ if (roleViews.includes(query.view)) {+ const box = selectable.find((b) => roleOf(b) === query.view)+ // A missing role yields no messages, never the entire account.+ return box ? { boxes: [box], filter: { mailboxIds: [box.id] } } : undefined+ }+ const excluded = selectable.filter((b) => ['junk', 'trash'].includes(roleOf(b) || ''))+ return {+ boxes: selectable.filter((b) => !excluded.includes(b)),+ filter: excluded.length ? { excludeMailboxIds: excluded.map((b) => b.id) } : {},+ }+ }+ async query(account: Account, query: MailQuery, position = 0, limit = 50): Promise<ProviderPage> {+ const boxes = await this.index.listMailboxes(this.accountId)+ const scope = await this.scope(query, boxes)+ if (!scope) return { items: [], total: 0 }+ const filter: ConversationFilter = {+ ...scope.filter,+ ...(query.view === 'starred' ? { flagged: true } : {}),+ ...(query.unread ? { unseen: true } : {}),+ ...(query.hasAttachment ? { hasAttachment: true } : {}),+ ...(query.after ? { after: query.after } : {}),+ ...(query.before ? { before: query.before } : {}),+ }+ let incomplete = scope.boxes.some((b) => !b.complete)+ if (query.text || query.from || query.to || query.subject) {+ const found = await this.search(query, scope.boxes)+ filter.ids = found.ids+ incomplete = found.incomplete+ }+ const key = JSON.stringify(query)+ const after = position ? this.cursors.get(key + '@' + position) : undefined+ const page = await this.index.conversations(this.accountId, filter, {+ limit,+ ...(after ? { after } : { offset: position }),+ })+ const threads = await this.index.threadMessages(+ this.accountId,+ page.items.map((i) => i.threadId),+ )+ const items = page.items.map((row) => {+ const messages = threads.filter((m) => m.threadId === row.threadId)+ const c = conversationFromMessages(+ account.id,+ row.threadId,+ (messages.length ? messages : [row.latest]).map((m) => toMessage(account.id, m)),+ )+ // Display the matching representative, even if the thread has newer mail elsewhere.+ c.receivedAt = row.latest.receivedAt+ c.subject = row.latest.subject || '(No subject)'+ c.preview = row.latest.preview+ c.count = row.count+ return c+ })+ const end = position + items.length+ const last = page.items.at(-1)+ if (last) {+ this.cursors.set(key + '@' + end, {+ receivedAt: last.latest.receivedAt,+ threadId: last.threadId,+ })+ if (this.cursors.size > 500) this.cursors.delete(this.cursors.keys().next().value!)+ }+ return {+ items,+ total: page.total,+ next: items.length === limit && end < page.total ? end : undefined,+ ...(incomplete ? { incomplete: true } : {}),+ }+ }+ /** Server search in each relevant folder; matches not yet indexed are indexed on the way. */+ private async search(query: MailQuery, boxes: IndexedMailbox[]) {+ const key = JSON.stringify([query, boxes.map((b) => b.id)])+ const cached = this.searches.get(key)+ if (cached && Date.now() - cached.at < 60_000) return cached+ const criteria: SearchCriteria = {+ ...(query.text ? { text: query.text } : {}),+ ...(query.from ? { from: query.from } : {}),+ ...(query.to ? { to: query.to } : {}),+ ...(query.subject ? { subject: query.subject } : {}),+ ...(query.after ? { since: new Date(query.after) } : {}),+ ...(query.before ? { before: new Date(query.before) } : {}),+ ...(query.unread ? { seen: false } : {}),+ ...(query.view === 'starred' ? { flagged: true } : {}),+ }+ const ids: string[] = []+ let incomplete = false+ for (const box of boxes)+ await this.run(async (port) => {+ const selected = await port.select(box.path)+ const uids = await port.search(criteria)+ const capped = uids.slice(-5000)+ incomplete ||= capped.length < uids.length+ if (box.uidValidity && selected.uidValidity !== box.uidValidity) {+ incomplete = true+ return+ }+ const known = await this.index.messagesAt(this.accountId, box.id, capped)+ const have = new Set(known.map((m) => m.uid))+ ids.push(...known.map((m) => m.id))+ ids.push(+ ...(await this.store(+ port,+ capped.filter((uid) => !have.has(uid)),+ { mailboxId: box.id, uidValidity: selected.uidValidity },+ )),+ )+ })+ const result = { ids, incomplete, at: Date.now() }+ this.searches.set(key, result)+ if (this.searches.size > 20) this.searches.delete(this.searches.keys().next().value!)+ return result+ }+ /** Re-reads flags from the server so decisions use current remote state. */+ private async current(rows: IndexedMessage[]): Promise<IndexedMessage[]> {+ const boxes = await this.index.listMailboxes(this.accountId)+ for (const [mailboxId, items] of byMailbox(rows)) {+ const box = boxes.find((b) => b.id === mailboxId)+ if (!box) continue+ await this.run(async (port) => {+ const selected = await port.select(box.path)+ const valid = items.filter((m) => m.uidValidity === selected.uidValidity)+ const fetched = valid.length+ ? await port.fetch(uidSet(valid.map((m) => m.uid)), { flags: true })+ : []+ await this.index.updateFlags(+ this.accountId,+ box.id,+ fetched.map((m) => ({ uid: m.uid, flags: m.flags || [], modseq: m.modseq })),+ )+ const present = new Set(fetched.map((m) => m.uid))+ const gone = valid.filter((m) => !present.has(m.uid))+ if (gone.length)+ await this.index.removeUids(+ this.accountId,+ box.id,+ gone.map((m) => m.uid),+ )+ const stale = items.filter((m) => m.uidValidity !== selected.uidValidity)+ if (stale.length)+ await this.index.removeMessages(+ this.accountId,+ stale.map((m) => m.id),+ )+ })+ }+ return this.index.messages(+ this.accountId,+ rows.map((r) => r.id),+ )+ }+ async conversationMetadata(account: Account, threadIds: string[]): Promise<Message[]> {+ const rows = await this.index.threadMessages(this.accountId, threadIds)+ return (await this.current(rows)).map((m) => toMessage(account.id, m))+ }+ async messages(account: Account, ids: string[], bodies = false): Promise<Message[]> {+ const rows = await this.current(await this.index.messages(this.accountId, [...new Set(ids)]))+ if (!bodies) return rows.map((m) => toMessage(account.id, m))+ return this.withBodies(account, rows)+ }+ async conversation(account: Account, threadId: string): Promise<Message[]> {+ const rows = await this.index.threadMessages(this.accountId, [threadId])+ if (!rows.length)+ throw new ProviderError('notFound', 'This conversation is no longer available.')+ const messages = await this.withBodies(account, rows)+ if (!messages.length)+ throw new ProviderError('notFound', 'This conversation is no longer available.')+ return messages.sort((a, b) => a.receivedAt.localeCompare(b.receivedAt))+ }+ private async withBodies(account: Account, rows: IndexedMessage[]): Promise<Message[]> {+ const boxes = await this.index.listMailboxes(this.accountId)+ const result: Message[] = []+ for (const [mailboxId, items] of byMailbox(rows)) {+ const box = boxes.find((b) => b.id === mailboxId)+ if (!box) continue+ await this.run(async (port) => {+ const selected = await port.select(box.path)+ for (const row of items) {+ if (row.uidValidity !== selected.uidValidity) continue+ const body = await this.body(port, row)+ if (!body) {+ await this.index.removeMessages(this.accountId, [row.id])+ continue+ }+ const preview = row.preview || previewText(body.text || body.html, !body.text)+ if (preview && !row.preview) await this.index.setPreview(this.accountId, row.id, preview)+ result.push({+ ...toMessage(account.id, { ...row, preview }),+ html: body.html,+ text: body.text,+ attachments: attachmentsOf(row),+ })+ }+ })+ }+ return result+ }+ private async body(port: ImapPort, row: IndexedMessage) {+ const cached = this.bodies.get(row.id)+ if (cached) return cached+ let body: { html: string; text: string } | undefined+ if (row.size <= bodyLimit) {+ const source = await port.source(row.uid, bodyLimit)+ if (!source) return undefined+ const parsed = await parseMime(source, { maxBytes: bodyLimit })+ body = { html: parsed.html, text: parsed.text }+ } else {+ // Large messages: fetch only the readable parts, never the attachments.+ const { html, text } = textParts(row.bodyStructure)+ const read = async (part?: typeof html) =>+ part+ ? new TextDecoder().decode(+ await port.download(row.uid, partSection(part), partLimit, true),+ )+ : ''+ body = { html: await read(html), text: await read(text) }+ }+ this.bodies.set(row.id, body)+ if (this.bodies.size > 40) this.bodies.delete(this.bodies.keys().next().value!)+ return body+ }+ async identities(account: Account): Promise<Identity[]> {+ return [+ {+ id: 'default',+ accountId: account.id,+ name: account.senderName || '',+ email: this.options.config.email,+ mayDelete: false,+ },+ ]+ }+ getStateToken() {+ return undefined+ }+ async download(_account: Account, attachment: Attachment): Promise<Uint8Array> {+ const blob = parseBlobId(attachment.blobId)+ const [row] = blob ? await this.index.messages(this.accountId, [blob.messageId]) : []+ if (!blob || !row)+ throw new ProviderError('notFound', 'This attachment is no longer available.')+ const box = (await this.index.listMailboxes(this.accountId)).find((b) => b.id === row.mailboxId)+ if (!box) throw new ProviderError('notFound', 'This attachment is no longer available.')+ return this.run(async (port) => {+ const selected = await port.select(box.path)+ if (selected.uidValidity !== row.uidValidity)+ throw new ProviderError(+ 'notFound',+ 'This message changed on the server. Reopen it and try again.',+ )+ return port.download(row.uid, blob.part, 100_000_000)+ })+ }+ async upload(): Promise<string> {+ throw new ProviderError('unsupported', 'IMAP attachments are read from local files.')+ }++ // Organizing++ async update(+ _account: Account,+ changes: MessageChanges,+ destroy: string[] = [],+ ): Promise<{ updated: string[]; failures: string[] }> {+ const updated: string[] = []+ const failures: string[] = []+ const rows = new Map(+ (await this.index.messages(this.accountId, [...Object.keys(changes), ...destroy])).map(+ (m) => [m.id, m],+ ),+ )+ const boxes = new Map((await this.index.listMailboxes(this.accountId)).map((b) => [b.id, b]))+ for (const id of [...Object.keys(changes), ...destroy])+ if (!rows.has(id)) failures.push(id + ': no longer exists')+ const moves = Object.entries(changes).filter(+ ([id, c]) => rows.has(id) && c.mailboxes && Object.keys(c.mailboxes).length,+ )+ if (moves.length && this.limits.move) throw new ProviderError('unsupported', this.limits.move)+ if (destroy.length && this.limits.destroy)+ throw new ProviderError('unsupported', this.limits.destroy)++ // Flags first: a move changes the UID the flags would have to be set on.+ const flagged = Object.entries(changes).filter(+ ([id, c]) => rows.has(id) && c.keywords && Object.keys(c.keywords).length,+ )+ for (const [mailboxId, items] of byMailbox(+ flagged.map(([id, c]) => ({ ...rows.get(id)!, change: c.keywords! })),+ )) {+ const box = boxes.get(mailboxId)+ if (!box) continue+ await this.run(async (port) => {+ const selected = await port.select(box.path)+ const valid = items.filter((m) => m.uidValidity === selected.uidValidity)+ for (const m of items.filter((m) => !valid.includes(m)))+ failures.push(m.id + ': changed on the server')+ // Each message's first store is conditional on the modseq just read, when supported.+ const operations = new Map<string, { uids: number[]; modseq?: string }>()+ for (const m of valid)+ Object.entries(m.change).forEach(([keyword, add], i) => {+ const modseq = i === 0 && port.condstore ? m.modseq : undefined+ const key = JSON.stringify([add, flagFromKeyword(keyword), modseq])+ operations.set(key, { uids: [...(operations.get(key)?.uids || []), m.uid], modseq })+ })+ for (const [key, operation] of operations) {+ const [add, flag] = JSON.parse(key) as [boolean, string]+ await port.store(operation.uids, add ? 'add' : 'remove', [flag], operation.modseq)+ }+ const after = valid.length+ ? await port.fetch(uidSet(valid.map((m) => m.uid)), { flags: true })+ : []+ await this.index.updateFlags(+ this.accountId,+ box.id,+ after.map((m) => ({ uid: m.uid, flags: m.flags || [], modseq: m.modseq })),+ )+ for (const m of valid) {+ const flags = after.find((a) => a.uid === m.uid)?.flags?.map((f) => f.toLowerCase())+ const applied =+ flags &&+ Object.entries(m.change).every(+ ([keyword, add]) => flags.includes(flagFromKeyword(keyword).toLowerCase()) === add,+ )+ if (applied) updated.push(m.id)+ else failures.push(m.id + (flags ? ': changed on the server' : ': no longer exists'))+ }+ })+ }++ const groups = new Map<+ string,+ { source: IndexedMailbox; target: IndexedMailbox; items: IndexedMessage[] }+ >()+ for (const [id, change] of moves) {+ const row = rows.get(id)!+ const target = Object.entries(change.mailboxes!).find(([, add]) => add)?.[0]+ const leaves = change.mailboxes![row.mailboxId] === false+ const source = boxes.get(row.mailboxId)+ const destination = target && boxes.get(target)+ if (!leaves || !source || !destination) {+ failures.push(id + ': a message can only be in one folder')+ continue+ }+ const key = source.id + '→' + destination.id+ groups.set(key, {+ source,+ target: destination,+ items: [...(groups.get(key)?.items || []), row],+ })+ }+ for (const { source, target, items } of groups.values())+ await this.run(async (port) => {+ const selected = await port.select(source.path)+ const valid = items.filter((m) => m.uidValidity === selected.uidValidity)+ for (const m of items.filter((m) => !valid.includes(m)))+ failures.push(m.id + ': changed on the server')+ if (!valid.length) return+ const uids = valid.map((m) => m.uid)+ const result = port.capabilities.has('MOVE')+ ? await port.move(uids, target.path)+ : await port.copy(uids, target.path)+ if (result && !port.capabilities.has('MOVE') && !(await port.expunge(uids))) {+ failures.push(+ ...valid.map((m) => m.id + ': copied, but the original could not be removed'),+ )+ return+ }+ if (!result) {+ failures.push(...valid.map((m) => m.id + ': the server refused the move'))+ return+ }+ const unmapped: IndexedMessage[] = []+ for (const m of valid) {+ const uid = result.uidMap?.get(m.uid)+ // Keep the message's ID across the confirmed move, so undo and selection still work.+ if (uid && result.uidValidity)+ await this.index.relocate(this.accountId, m.id, {+ mailboxId: target.id,+ uidValidity: result.uidValidity,+ uid,+ })+ else unmapped.push(m)+ updated.push(m.id)+ }+ if (unmapped.length) await this.relocateBySearch(port, target, unmapped)+ })+ this.searches.clear()++ for (const [mailboxId, items] of byMailbox(+ destroy.filter((id) => rows.has(id)).map((id) => rows.get(id)!),+ )) {+ const box = boxes.get(mailboxId)+ if (!box) continue+ await this.run(async (port) => {+ const selected = await port.select(box.path)+ const valid = items.filter((m) => m.uidValidity === selected.uidValidity)+ for (const m of items.filter((m) => !valid.includes(m)))+ failures.push(m.id + ': changed on the server')+ if (!valid.length) return+ // UID EXPUNGE removes exactly these messages, never another client's pending deletions.+ if (await port.expunge(valid.map((m) => m.uid))) {+ await this.index.removeMessages(+ this.accountId,+ valid.map((m) => m.id),+ )+ updated.push(...valid.map((m) => m.id))+ } else failures.push(...valid.map((m) => m.id + ': the server refused the deletion'))+ })+ }+ if (moves.length || destroy.length) this.requestSync('all')+ return { updated, failures }+ }+ /**+ * UIDs in the selected folder whose Message-ID matches. Server search indexes can lag behind+ * a fresh APPEND, so the newest messages' envelopes are compared as well.+ */+ private async withMessageId(+ port: ImapPort,+ messageId: string,+ uidNext: number,+ ): Promise<number[]> {+ const found = new Set(await port.search({ header: { 'message-id': '<' + messageId + '>' } }))+ const recent = await port.fetch(Math.max(1, uidNext - 200) + ':*', { envelope: true })+ for (const m of recent) if (messageIds(m.envelope?.messageId)[0] === messageId) found.add(m.uid)+ return [...found].sort((a, b) => a - b)+ }+ /** Without COPYUID, finds moved messages by Message-ID in the destination to keep their IDs. */+ private async relocateBySearch(port: ImapPort, target: IndexedMailbox, items: IndexedMessage[]) {+ const selected = await port.select(target.path)+ const lost: string[] = []+ for (const m of items) {+ const uids = m.messageId ? await this.withMessageId(port, m.messageId, selected.uidNext) : []+ const known = new Set(+ (await this.index.messagesAt(this.accountId, target.id, uids)).map((k) => k.uid),+ )+ const candidates = uids.filter((uid) => !known.has(uid))+ if (candidates.length === 1)+ await this.index.relocate(this.accountId, m.id, {+ mailboxId: target.id,+ uidValidity: selected.uidValidity,+ uid: candidates[0],+ })+ else lost.push(m.id)+ }+ // The next sync indexes them again under new IDs.+ if (lost.length) await this.index.removeMessages(this.accountId, lost)+ }++ // Drafts and sending++ private async compose(account: Account, draft: Draft, messageId: string, keepBcc: boolean) {+ return composeMime({+ from: { name: account.senderName || '', email: this.options.config.email },+ to: draft.to,+ cc: draft.cc,+ bcc: draft.bcc,+ subject: draft.subject,+ html: draft.html,+ text: draft.text,+ messageId,+ inReplyTo: draft.inReplyTo,+ references: draft.references,+ date: new Date(),+ attachments: await Promise.all(+ draft.attachments.map(async (a) => ({+ name: a.name,+ type: a.type,+ cid: a.cid,+ content: await this.options.readAttachment(a.id),+ })),+ ),+ keepBcc,+ })+ }+ private messageId() {+ const domain = this.options.config.email+ .split('@')[1]+ ?.toLowerCase()+ .replace(/[^a-z0-9.-]/g, '')+ return randomUUID() + '@' + (domain || 'inlark.invalid')+ }+ async createDraft(account: Account, draft: Draft, messageId?: string): Promise<string> {+ const drafts = await this.roleBox('drafts')+ if (!drafts)+ throw new ProviderError(+ 'drafts',+ 'Choose a Drafts folder in Settings → Accounts → Folders to save drafts on the server.',+ )+ // Every saved revision gets its own Message-ID so it can be found unambiguously.+ const id = messageId || this.messageId()+ const mime = await this.compose(account, draft, id, true)+ return this.run(async (port) => {+ // APPEND flags are checked against the selected folder's permanent flags.+ const selected = await port.select(drafts.path)+ const appended = await port.append(drafts.path, mime, ['\\Draft', '\\Seen'], new Date())+ let uid = appended.uid+ if (!uid) {+ const found = await this.withMessageId(port, id, (await port.select(drafts.path)).uidNext)+ if (found.length !== 1)+ throw new ProviderError('draft', 'The server did not confirm the saved draft.')+ uid = found[0]+ }+ const [fetched] = await port.fetch(String(uid), metadataQuery)+ if (!fetched) throw new ProviderError('draft', 'The server did not confirm the saved draft.')+ const [saved] = await this.index.upsertMessages(this.accountId, [+ toNewMessage(fetched, {+ mailboxId: drafts.id,+ uidValidity: appended.uidValidity || selected.uidValidity,+ }),+ ])+ return saved+ })+ }+ async prepareSubmission(+ account: Account,+ draft: Draft,+ messageId: string,+ ): Promise<OutgoingMessage> {+ const recipients = [...new Set([...draft.to, ...draft.cc, ...draft.bcc].map((a) => a.email))]+ // Bcc recipients are only in the envelope, never in the transmitted headers.+ const mime = await this.compose(account, draft, messageId, false)+ return { messageId, mime, envelope: { from: this.options.config.email, to: recipients } }+ }+ async submit(_account: Account, message: OutgoingMessage): Promise<SubmissionOutcome> {+ if (!message.mime) throw new ProviderError('submission', 'The message was not prepared.')+ return (this.options.smtp?.submit || submitSmtp)(+ this.smtpSettings(),+ message.envelope,+ message.mime,+ )+ }+ /** SMTP gives no later proof of submission; only the recorded acceptance counts. */+ async submissionExists(): Promise<boolean> {+ return false+ }+ async fileSentCopy(_account: Account, message: OutgoingMessage): Promise<'filed' | 'server'> {+ const sent = await this.roleBox('sent')+ if (!sent)+ throw new ProviderError(+ 'filing',+ 'Choose a Sent folder in Settings → Accounts → Folders to keep a copy.',+ )+ if (!message.mime)+ throw new ProviderError('filing', 'The sent message is no longer available locally.')+ const filed = async (port: ImapPort) =>+ (await this.withMessageId(port, message.messageId, (await port.select(sent.path)).uidNext))+ .length > 0+ const result = await this.run(async (port) =>+ (await filed(port)) ? ('server' as const) : undefined,+ )+ if (result) return result+ // Some servers file their own copy shortly after accepting the message.+ await sleep(this.timing.sentCopyGraceMs)+ return this.run(async (port) => {+ if (await filed(port)) return 'server' as const+ try {+ await port.append(sent.path, message.mime!, ['\\Seen'], new Date())+ } catch (error) {+ if (isProviderError(error, 'network'))+ throw new ProviderError(+ 'filingUncertain',+ 'The connection dropped while saving the Sent copy. It will be checked before trying again.',+ )+ throw new ProviderError('filing', 'The server did not accept the Sent copy.')+ }+ this.requestSync('all')+ return 'filed' as const+ })+ }++ subscribe(listener: (event: ProviderEvent) => void): () => void {+ this.listeners.add(listener)+ return () => this.listeners.delete(listener)+ }+ dispose() {+ this.disposed = true+ this.wakeLoop?.()+ for (const task of this.queue.splice(0))+ task.reject(new ProviderError('offline', 'Account disconnected.'))+ for (const port of [this.command, this.idle]) void port?.close().catch(() => {})+ this.command = this.idle = undefined+ this.listeners.clear()+ }+ async close() {+ this.dispose()+ // Let a running command finish before the index closes underneath it.+ for (let i = 0; this.pumping && i < 100; i++) await sleep(20)+ await this.index.close()+ }+}++/**+ * Where a new top-level folder goes. Servers that keep every folder below INBOX (`INBOX.Sent`)+ * get the new one there too, with the server's own delimiter.+ */+export function newFolderPath(boxes: { path: string; delimiter: string }[], name: string): string {+ const delimiter = boxes.find((b) => b.delimiter)?.delimiter || '/'+ const others = boxes.filter((b) => !isInbox(b.path))+ const underInbox =+ others.length > 0 && others.every((b) => b.path.toUpperCase().startsWith('INBOX' + delimiter))+ return underInbox && !name.toUpperCase().startsWith('INBOX' + delimiter)+ ? 'INBOX' + delimiter + name+ : name+}+export function limitsFor(capabilities: ReadonlySet<string>): AccountLimits {+ const limits: AccountLimits = {}+ if (!capabilities.has('MOVE') && !capabilities.has('UIDPLUS'))+ limits.move =+ 'This server supports neither MOVE nor UIDPLUS, so moving mail could also erase messages another app marked for deletion. Moving, archiving and deleting are off for this account.'+ if (!capabilities.has('UIDPLUS'))+ limits.destroy =+ 'This server lacks UIDPLUS, so permanent deletion could also erase messages another app marked for deletion. Move messages to Trash instead.'+ return limits+}diff --git a/packages/imap/src/smtp.ts b/packages/imap/src/smtp.tsnew file mode 100644index 0000000..7137c66--- /dev/null+++ b/packages/imap/src/smtp.ts@@ -0,0 +1,335 @@+import SMTPConnection from 'nodemailer/lib/smtp-connection'+import { isIP } from 'node:net'+import { Readable } from 'node:stream'+import { TLSSocket } from 'node:tls'+import { ProviderError, type ServerSettings, type SubmissionOutcome } from '@inlark/core'++export interface SmtpSettings extends ServerSettings {+ password: string+ timeoutMs?: number+ /** Tests only: trust this CA instead of the system roots. */+ tls?: { ca?: string | Uint8Array }+}++/** The fields nodemailer puts on its errors (see smtp-connection `_formatError`). */+type SmtpFailure = Error & {+ code?: string+ command?: string+ responseCode?: number+ response?: string+ recipient?: string+}+/**+ * `connect` covers connect, TLS, greeting, EHLO, STARTTLS and AUTH; `envelope` covers MAIL FROM, RCPT TO and+ * the DATA command; `data` starts when nodemailer first reads the message, i.e. after the server's 354.+ */+type Phase = 'connect' | 'envelope' | 'data'+interface State {+ phase: Phase+ startTlsMissing?: boolean+}+/** smtp-connection internals this module relies on; covered by tests/smtp.test.ts. */+interface Internals {+ _ehloLines?: string[]+ _supportedAuth?: string[]+ _actionSTARTTLS(this: Internals, response: string): void+ _onError(error: Error, code: string, response: string | false, command: string): void+}++const passwordMethods = ['PLAIN', 'LOGIN', 'CRAM-MD5']++export function smtpOptions(settings: SmtpSettings): SMTPConnection.Options {+ const ca = settings.tls?.ca+ const timeout = settings.timeoutMs+ return {+ host: settings.host,+ port: settings.port,+ secure: settings.security === 'tls',+ requireTLS: settings.security === 'starttls',+ ignoreTLS: false,+ opportunisticTLS: false,+ // A neutral EHLO name, so the local hostname never reaches the server.+ name: '[127.0.0.1]',+ connectionTimeout: timeout ?? 30_000,+ greetingTimeout: timeout ?? 30_000,+ dnsTimeout: timeout ?? 30_000,+ // Servers may scan a message for a while before answering the end of DATA.+ socketTimeout: timeout ?? 120_000,+ logger: false,+ debug: false,+ transactionLog: false,+ lmtp: false,+ tls: {+ rejectUnauthorized: true,+ minVersion: 'TLSv1.2',+ ...(isIP(settings.host) ? {} : { servername: settings.host }),+ ...(ca ? { ca: typeof ca === 'string' ? ca : Buffer.from(ca) } : {}),+ },+ }+}++/** Connects, secures the connection and signs in, then quits. Never sends a message. */+export async function verifySmtp(settings: SmtpSettings): Promise<void> {+ await session(settings, async () => undefined)+}++/**+ * Transmits exactly `mime` to `envelope.to`. Throws `submissionUncertain` whenever the message may have reached the+ * server without a definitive reply; callers must never retry that automatically.+ */+export async function submitSmtp(+ settings: SmtpSettings,+ envelope: { from: string; to: string[] },+ mime: Uint8Array,+): Promise<SubmissionOutcome> {+ const to = [...new Map(envelope.to.map((a) => [a.trim().toLowerCase(), a.trim()])).values()]+ const invalid = [envelope.from, ...to].find((a) => !a || /[\s<>]/.test(a))+ const problem = !envelope.from+ ? 'The sender address is missing.'+ : !to.length+ ? 'The message has no recipients.'+ : invalid !== undefined+ ? `“${clean(invalid)}” isn't a valid address.`+ : !mime.byteLength+ ? 'The message is empty.'+ : undefined+ if (problem) throw new ProviderError('submissionRejected', `${problem} Nothing was sent.`)+ return session(+ settings,+ (conn, state) =>+ new Promise<SubmissionOutcome>((resolve, reject) => {+ state.phase = 'envelope'+ const body = new Readable({+ read() {+ state.phase = 'data'+ this.push(Buffer.from(mime.buffer, mime.byteOffset, mime.byteLength))+ this.push(null)+ },+ })+ conn.send({ from: envelope.from, to, size: mime.byteLength }, body, (error, info) => {+ if (error || !info) return reject(sendFailure(settings, state, error ?? undefined))+ const reasons = new Map(+ (info.rejectedErrors ?? []).map((e) => [+ (e as SmtpFailure).recipient,+ (e as SmtpFailure).response,+ ]),+ )+ resolve({+ accepted: [...info.accepted],+ rejected: info.rejected.map((email) => ({+ email,+ reason: clean(reasons.get(email) ?? '') || 'Rejected by the outgoing server',+ })),+ })+ })+ }),+ )+}++async function session<T>(+ settings: SmtpSettings,+ work: (conn: SMTPConnection, state: State) => Promise<T>,+): Promise<T> {+ if (+ !settings.host?.trim() ||+ !Number.isInteger(settings.port) ||+ settings.port < 1 ||+ settings.port > 65535+ )+ throw new ProviderError('outgoingNetwork', 'The outgoing server address or port is missing.')+ if (settings.security !== 'tls' && settings.security !== 'starttls')+ throw new ProviderError('outgoingNetwork', 'The outgoing server security setting is invalid.')+ const conn = new SMTPConnection(smtpOptions(settings))+ const state: State = { phase: 'connect' }+ requireOfferedStartTls(conn, state)+ let drop!: (error: ProviderError) => void+ const dropped = new Promise<never>((_, reject) => (drop = reject))+ dropped.catch(() => undefined)+ // Socket failures and timeouts are only emitted here; send() never calls back for them.+ conn.on('error', (error: SmtpFailure) => drop(connectionLost(settings, state, conn, error)))+ conn.on('end', () => drop(connectionLost(settings, state, conn)))+ let done = false+ try {+ await Promise.race([+ new Promise<void>((resolve, reject) => conn.connect((e) => (e ? reject(e) : resolve()))),+ dropped,+ ])+ // Defense in depth: nodemailer's requireTLS already refuses to continue unencrypted.+ if (!conn.secure)+ throw new ProviderError(+ 'outgoingNetwork',+ `The connection to ${settings.host} isn't encrypted, so no password was sent. Check the security setting.`,+ )+ await Promise.race([login(conn, settings), dropped])+ const result = await Promise.race([work(conn, state), dropped])+ done = true+ return result+ } catch (error) {+ throw error instanceof ProviderError+ ? error+ : connectionLost(settings, state, conn, error as SmtpFailure)+ } finally {+ if (done) {+ conn.quit()+ setTimeout(() => conn.close(), 5000).unref()+ } else conn.close()+ }+}++/**+ * With requireTLS nodemailer sends STARTTLS even when the plaintext EHLO did not offer it. Treat a missing offer as+ * a failed upgrade instead, before anything else is sent.+ */+function requireOfferedStartTls(conn: SMTPConnection, state: State) {+ const internals = conn as unknown as Internals+ const upgrade = internals._actionSTARTTLS+ internals._actionSTARTTLS = function (response) {+ if (!this._ehloLines?.some((line) => /^STARTTLS$/i.test(line.trim()))) {+ state.startTlsMissing = true+ this._onError(new Error('STARTTLS was not offered'), 'ETLS', false, 'STARTTLS')+ return+ }+ upgrade.call(this, response)+ }+}++async function login(conn: SMTPConnection, settings: SmtpSettings): Promise<void> {+ const host = settings.host+ if (!conn.allowsAuth)+ throw new ProviderError(+ 'outgoingNetwork',+ `${host} doesn't offer password sign-in on this connection, so nothing can be sent. Check the port and security settings.`,+ )+ const offered = (conn as unknown as Internals)._supportedAuth ?? []+ // No listed mechanism means nodemailer inferred AUTH (HELO fallback); PLAIN is its default there too.+ const method = offered.length ? passwordMethods.find((m) => offered.includes(m)) : 'PLAIN'+ if (!method)+ throw new ProviderError(+ 'outgoingNetwork',+ `${host} doesn't offer a supported password sign-in method.`,+ )+ await new Promise<void>((resolve, reject) =>+ conn.login({ user: settings.username, pass: settings.password, method }, (error) => {+ if (!error) return resolve()+ const failure = error as SmtpFailure+ if (failure.code !== 'EAUTH') return reject(failure)+ reject(+ failure.responseCode && failure.responseCode < 500+ ? new ProviderError(+ 'outgoingNetwork',+ `${host} couldn't check the sign-in right now. Try again in a moment.`,+ )+ : new ProviderError(+ 'outgoingAuthentication',+ `${host} didn't accept the username or password for sending mail. Check them in the account settings.`,+ ),+ )+ }),+ )+}++function connectionLost(+ settings: SmtpSettings,+ state: State,+ conn: SMTPConnection,+ error?: SmtpFailure,+): ProviderError {+ const host = settings.host+ if (state.phase === 'data') return uncertain(host)+ if (state.phase === 'envelope') return interrupted(host)+ const text = error?.message ?? ''+ const socket = conn._socket+ const hint = 'Check the port and security settings.'+ if (state.startTlsMissing)+ return new ProviderError(+ 'outgoingNetwork',+ `${host} didn't offer an encrypted connection (STARTTLS), so no password was sent. ${hint}`,+ )+ if (+ (socket instanceof TLSSocket && socket.authorizationError) ||+ /certificate|altnames|self[- ]signed/i.test(text)+ )+ return new ProviderError(+ 'outgoingNetwork',+ `The certificate of ${host} couldn't be verified, so the connection was stopped before signing in. Check the server name, or ask the server's administrator about its certificate.`,+ )+ if (error?.command === 'STARTTLS' && error.responseCode)+ return new ProviderError(+ 'outgoingNetwork',+ `${host} refused to start an encrypted connection, so no password was sent. ${hint}`,+ )+ if (error?.code === 'ETLS' || /\b(ssl|tls)\b|handshake|wrong version/i.test(text))+ return new ProviderError(+ 'outgoingNetwork',+ `A secure connection to ${host} couldn't be established. ${hint}`,+ )+ if (error?.code === 'ETIMEDOUT')+ return new ProviderError(+ 'outgoingNetwork',+ `${host} didn't respond in time. Check your connection, the port and the security setting.`,+ )+ if (error?.code === 'EDNS' || /ENOTFOUND|EAI_AGAIN/.test(text))+ return new ProviderError(+ 'outgoingNetwork',+ `${host} couldn't be found. Check the server name and your connection.`,+ )+ if (/ECONNREFUSED/.test(text))+ return new ProviderError(+ 'outgoingNetwork',+ `${host} refused the connection on port ${settings.port}. ${hint}`,+ )+ return new ProviderError(+ 'outgoingNetwork',+ `Couldn't connect to the outgoing server ${host}. Check your connection and the server settings, then try again.`,+ )+}++function sendFailure(settings: SmtpSettings, state: State, error?: SmtpFailure): ProviderError {+ const host = settings.host+ const code = error?.responseCode || 0+ const said = error?.response ? ` The server said: “${clean(error.response)}”` : ''+ const temporary = code >= 400 && code < 500+ if (error?.code === 'EENVELOPE') {+ const message =+ error.command === 'MAIL FROM'+ ? `${host} refused the sender address, so nothing was sent.`+ : error.command === 'RCPT TO'+ ? `${host} ${temporary ? 'temporarily ' : ''}rejected every recipient, so nothing was sent.`+ : error.command === 'DATA'+ ? `${host} refused the message before it was transmitted, so nothing was sent.`+ : `The message couldn't be addressed, so nothing was sent.`+ return new ProviderError('submissionRejected', message + said)+ }+ // The server's reply to the end of DATA: definitive either way.+ if (error?.code === 'EMESSAGE' && error.command === 'DATA' && code >= 400 && code < 600)+ return new ProviderError(+ 'submissionRejected',+ (temporary+ ? `${host} temporarily refused the message, so it wasn't sent. Try again later.`+ : `${host} rejected the message, so it wasn't sent.`) + said,+ )+ // Anything else once the message started flowing: the server may have it.+ if (state.phase === 'data') return uncertain(host)+ if (error?.code === 'EMESSAGE')+ return new ProviderError(+ 'submissionRejected',+ `The message is larger than ${host} accepts, so nothing was sent.`,+ )+ return interrupted(host)+}++const uncertain = (host: string) =>+ new ProviderError(+ 'submissionUncertain',+ `The connection to ${host} ended while the message was being sent, so it's not known whether it went out. Check your Sent folder or ask a recipient before sending it again.`,+ )+const interrupted = (host: string) =>+ new ProviderError(+ 'outgoingNetwork',+ `The connection to ${host} was interrupted before the message was transmitted. Nothing was sent; you can try again.`,+ )+const clean = (text: string) =>+ text+ .replace(/[\x00-\x1f\x7f]+/g, ' ')+ .trim()+ .slice(0, 300)diff --git a/packages/imap/tsconfig.json b/packages/imap/tsconfig.jsonnew file mode 100644index 0000000..4b7d0d2--- /dev/null+++ b/packages/imap/tsconfig.json@@ -0,0 +1 @@+{ "extends": "../../tsconfig.json", "include": ["src"], "compilerOptions": { "types": ["node"] } }diff --git a/packages/jmap/package.json b/packages/jmap/package.jsonnew file mode 100644index 0000000..c05220b--- /dev/null+++ b/packages/jmap/package.json@@ -0,0 +1,16 @@+{+ "name": "@inlark/jmap",+ "version": "0.1.0",+ "private": true,+ "license": "AGPL-3.0-only",+ "type": "module",+ "exports": {+ ".": "./src/index.ts"+ },+ "scripts": {+ "typecheck": "tsc -p tsconfig.json"+ },+ "dependencies": {+ "@inlark/core": "workspace:*"+ }+}diff --git a/packages/jmap/src/index.ts b/packages/jmap/src/index.tsnew file mode 100644index 0000000..1f88657--- /dev/null+++ b/packages/jmap/src/index.ts@@ -0,0 +1,864 @@+import {+ accountKey,+ accountColors,+ conversationFromMessages,+ draftFingerprint,+ parseUnsubscribe,+ ProviderError,+ type Account,+ type Address,+ type Mailbox,+ type Identity,+ type Message,+ type MailQuery,+ type ProviderPage,+ type ProviderCapabilities,+ type ProviderEvent,+ type MailProvider,+ type Draft,+ type Attachment,+ type MessageChanges,+ type OutgoingMessage,+ type SubmissionOutcome,+} from '@inlark/core'++export { draftFingerprint, parseUnsubscribe }++const CORE = 'urn:ietf:params:jmap:core'+const MAIL = 'urn:ietf:params:jmap:mail'+const SUBMISSION = 'urn:ietf:params:jmap:submission'+type Json = Record<string, any>+type Call = [string, Json, string]+type Session = {+ apiUrl: string+ downloadUrl: string+ uploadUrl: string+ eventSourceUrl?: string+ username: string+ accounts: Record<string, Json>+ capabilities: Record<string, Json>+ primaryAccounts: Record<string, string>+ state: string+}+export class JmapError extends ProviderError {+ constructor(code: string, message: string, retryAfter?: number) {+ super(code, message, retryAfter)+ this.name = 'JmapError'+ }+}+const pointer = (value: string) => value.replace(/~/g, '~0').replace(/\//g, '~1')+/** Translates provider-neutral changes into JMAP patch paths. */+export function jmapPatch(change: MessageChanges[string]): Json {+ const patch: Json = {}+ for (const [field, values] of [+ ['mailboxIds', change.mailboxes],+ ['keywords', change.keywords],+ ] as const)+ for (const [key, value] of Object.entries(values || {}))+ patch[field + '/' + pointer(key)] = value || null+ return patch+}+export interface JmapOptions {+ serverUrl: string+ authorization: string+ connectionId: string+ name: string+ fetch?: typeof fetch+ timeoutMs?: number+}+const summaryProperties = [+ 'id',+ 'threadId',+ 'mailboxIds',+ 'keywords',+ 'size',+ 'receivedAt',+ 'sentAt',+ 'from',+ 'to',+ 'cc',+ 'bcc',+ 'replyTo',+ 'subject',+ 'preview',+ 'hasAttachment',+ 'messageId',+ 'inReplyTo',+ 'references',+]+function batches<T>(items: T[], size: number): T[][] {+ const result: T[][] = []+ for (let i = 0; i < items.length; i += Math.max(1, size))+ result.push(items.slice(i, i + Math.max(1, size)))+ return result+}+export function jmapFilter(query: MailQuery, mailboxes: Mailbox[]): Json {+ const role = (name: string) => mailboxes.find((m) => m.role === name)?.id+ const filters: Json[] = []+ if (query.mailboxId) filters.push({ inMailbox: query.mailboxId })+ else if (['inbox', 'archive', 'sent', 'drafts', 'junk', 'trash'].includes(query.view)) {+ const mailbox = role(query.view)+ // A nonexistent role must yield no messages, never the entire account.+ filters.push({ inMailbox: mailbox || '__inlark_missing_mailbox__' })+ } else {+ const excluded = ['junk', 'trash'].map(role).filter(Boolean)+ if (excluded.length) filters.push({ inMailboxOtherThan: excluded })+ }+ if (query.unread) filters.push({ notKeyword: '$seen' })+ if (query.view === 'starred') filters.push({ hasKeyword: '$flagged' })+ for (const key of ['text', 'from', 'to', 'subject', 'after', 'before'] as const)+ if (query[key]) filters.push({ [key]: query[key] })+ if (query.hasAttachment) filters.push({ hasAttachment: true })+ return filters.length === 0+ ? {}+ : filters.length === 1+ ? filters[0]+ : { operator: 'AND', conditions: filters }+}+function structuredBodyParts(part: Json | undefined, type: string): Json[] {+ if (!part || part.disposition?.toLowerCase() === 'attachment') return []+ return [+ ...(part.type?.toLowerCase() === type ? [part] : []),+ ...(part.subParts || []).flatMap((child: Json) => structuredBodyParts(child, type)),+ ]+}+function bodyParts(raw: Json, type: 'text/plain' | 'text/html'): Json[] {+ return type === 'text/html' ? raw.htmlBody || [] : raw.textBody || []+}+function bodyValue(raw: Json, type: 'text/plain' | 'text/html'): string {+ const value = (parts: Json[]) =>+ parts+ .map((part) => raw.bodyValues?.[part.partId]?.value || '')+ .filter((content) => content.trim())+ .join('\n')+ return value(bodyParts(raw, type)) || value(structuredBodyParts(raw.bodyStructure, type))+}+function addressList(value?: Json[] | null): Address[] {+ return (value || []).map((address) => ({ name: address.name || '', email: address.email }))+}+function asMessage(account: Account, raw: Json, bodies: boolean): Message {+ const result: Message = {+ id: raw.id,+ accountId: account.id,+ threadId: raw.threadId,+ subject: raw.subject || '',+ from: addressList(raw.from),+ to: addressList(raw.to),+ cc: addressList(raw.cc),+ bcc: addressList(raw.bcc),+ replyTo: addressList(raw.replyTo),+ receivedAt: raw.receivedAt,+ sentAt: raw.sentAt,+ preview: raw.preview || '',+ keywords: raw.keywords || {},+ mailboxIds: raw.mailboxIds || {},+ size: raw.size || 0,+ hasAttachment: !!raw.hasAttachment,+ messageId: raw.messageId || [],+ inReplyTo: raw.inReplyTo || [],+ references: raw.references || [],+ }+ if (bodies) {+ result.html = bodyValue(raw, 'text/html')+ result.text = bodyValue(raw, 'text/plain')+ const attachments = new Map<string, Attachment>()+ const visit = (part: Json) => {+ if (part.blobId && (part.disposition === 'attachment' || part.cid || part.name))+ attachments.set(part.blobId, {+ blobId: part.blobId,+ name: part.name || 'attachment',+ type: part.type || 'application/octet-stream',+ size: part.size || 0,+ ...(part.cid ? { cid: part.cid } : {}),+ ...(part.disposition ? { disposition: part.disposition } : {}),+ })+ for (const child of part.subParts || []) visit(child)+ }+ if (raw.bodyStructure) visit(raw.bodyStructure)+ for (const part of raw.attachments || []) visit(part)+ result.attachments = [...attachments.values()]+ result.unsubscribe = parseUnsubscribe(+ raw['header:List-Unsubscribe:asText'],+ raw['header:List-Unsubscribe-Post:asText'],+ )+ }+ return result+}+export class JmapProvider implements MailProvider {+ capabilities: ProviderCapabilities = {+ mail: false,+ submission: false,+ push: false,+ maxObjectsInGet: 100,+ maxObjectsInSet: 100,+ maxUploadSize: 50_000_000,+ blobUpload: true,+ sentCopy: 'server',+ }+ private session?: Session+ private emailState = new Map<string, string>()+ private mailboxCache = new Map<string, Mailbox[]>()+ private listeners = new Set<(event: ProviderEvent) => void>()+ private controller?: AbortController+ private disposed = false+ private cooldownUntil = 0+ private requestFetch: typeof fetch+ constructor(private options: JmapOptions) {+ this.requestFetch = options.fetch || fetch+ }+ private emit(event: ProviderEvent) {+ for (const listener of this.listeners) listener(event)+ }+ private endpoint(value: string): string {+ const url = new URL(value, this.options.serverUrl)+ const origin = new URL(this.options.serverUrl)+ if (url.origin !== origin.origin || url.username || url.password)+ throw new JmapError(+ 'endpoint',+ 'The server advertised an endpoint on another origin. Cross-origin authentication is not enabled.',+ )+ return url.toString()+ }+ private async request(url: string, init: RequestInit = {}, redirects = 0): Promise<Response> {+ if (Date.now() < this.cooldownUntil)+ throw new JmapError(+ 'rateLimit',+ 'The server requested a pause. Please try again shortly.',+ Math.ceil((this.cooldownUntil - Date.now()) / 1000),+ )+ let response: Response+ try {+ response = await this.requestFetch(this.endpoint(url), {+ ...init,+ redirect: 'manual',+ headers: { ...init.headers, Authorization: this.options.authorization },+ signal: init.signal || AbortSignal.timeout(this.options.timeoutMs || 20_000),+ })+ } catch (error) {+ if (this.disposed) throw new JmapError('offline', 'Account disconnected.')+ throw new JmapError(+ 'network',+ 'The mail server could not be reached. Check your connection and server URL.',+ )+ }+ if ([301, 302, 303, 307, 308].includes(response.status)) {+ if (+ (init.method && init.method !== 'GET') ||+ redirects >= 4 ||+ !response.headers.get('location')+ )+ throw new JmapError(+ 'redirect',+ 'The server redirected an operation. Reconnect with its canonical URL.',+ )+ const target = this.endpoint(new URL(response.headers.get('location')!, url).toString())+ return this.request(target, init, redirects + 1)+ }+ if (response.status === 401 || response.status === 403)+ throw new JmapError(+ 'authentication',+ 'Sign in again. The server rejected these credentials or permissions.',+ )+ if (response.status === 429) {+ const header = response.headers.get('retry-after') || '30'+ const delay = /^\d+$/.test(header) ? Number(header) : (Date.parse(header) - Date.now()) / 1000+ const seconds = Number.isFinite(delay) ? Math.max(1, Math.min(3600, delay)) : 30+ this.cooldownUntil = Date.now() + seconds * 1000+ throw new JmapError('rateLimit', 'The server is busy. Please try again shortly.', seconds)+ }+ if (!response.ok)+ throw new JmapError('http', 'The mail server returned HTTP ' + response.status + '.')+ return response+ }+ async connect(): Promise<Account[]> {+ this.disposed = false+ const base = new URL(this.options.serverUrl)+ const url =+ base.pathname === '/' || !base.pathname+ ? new URL('/.well-known/jmap', base).toString()+ : base.toString()+ let response = await this.request(url)+ this.session = (await response.json()) as Session+ if (!this.session.apiUrl || !this.session.accounts || !this.session.capabilities?.[MAIL])+ throw new JmapError('capability', 'This endpoint does not provide JMAP Mail.')+ this.endpoint(this.session.apiUrl)+ this.endpoint(this.session.uploadUrl)+ this.endpoint(this.session.downloadUrl)+ const core = this.session.capabilities[CORE] || {}+ this.capabilities = {+ mail: true,+ submission: !!this.session.capabilities[SUBMISSION],+ push: !!this.session.eventSourceUrl,+ maxObjectsInGet: core.maxObjectsInGet || 100,+ maxObjectsInSet: core.maxObjectsInSet || 100,+ maxUploadSize: core.maxSizeUpload || 50_000_000,+ blobUpload: true,+ sentCopy: 'server',+ }+ return Object.entries(this.session.accounts)+ .filter(([, a]) => a.accountCapabilities?.[MAIL])+ .map(([remoteId, a], index) => ({+ id: accountKey(this.options.connectionId, remoteId),+ connectionId: this.options.connectionId,+ remoteId,+ name: this.options.name || a.name || this.session!.username,+ email: this.session!.username,+ color: accountColors[1 + (index % (accountColors.length - 1))],+ status: 'connected',+ protocol: 'jmap',+ }))+ }+ async call(calls: Call[], submission = false): Promise<Json[]> {+ if (!this.session) throw new JmapError('session', 'Reconnect this account first.')+ const response = await this.request(this.session.apiUrl, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ using: submission ? [CORE, MAIL, SUBMISSION] : [CORE, MAIL],+ methodCalls: calls,+ }),+ })+ const body = (await response.json()) as Json+ if (!Array.isArray(body.methodResponses))+ throw new JmapError('response', 'The server returned an invalid JMAP response.')+ for (const [method, result] of body.methodResponses as Call[])+ if (method === 'Email/set' && result.newState && result.accountId) {+ this.emailState.set(+ accountKey(this.options.connectionId, result.accountId),+ result.newState,+ )+ }+ return calls.map(([name, , tag]) => {+ const match = (body.methodResponses as Call[]).find(+ (r) => r[2] === tag && (r[0] === name || r[0] === 'error'),+ )+ if (!match)+ throw new JmapError('response', 'The server did not return the requested operation.')+ if (match[0] === 'error' && match[1].type === 'stateMismatch')+ throw new JmapError(+ 'stateMismatch',+ 'Mail changed on the server. Refresh and try the action again.',+ )+ if (match[0] === 'error')+ throw new JmapError(match[1].type, name + ' failed (' + (match[1].type || 'unknown') + ').')+ return match[1]+ })+ }+ async mailboxes(account: Account): Promise<Mailbox[]> {+ const [result] = await this.call([['Mailbox/get', { accountId: account.remoteId }, 'm']])+ const boxes = result.list.map((m: Json): Mailbox => ({+ id: m.id,+ accountId: account.id,+ name: m.name,+ role: m.role,+ parentId: m.parentId,+ totalEmails: m.totalEmails,+ unreadEmails: m.unreadEmails,+ rights: m.myRights,+ }))+ this.mailboxCache.set(account.id, boxes)+ return boxes+ }+ async identities(account: Account): Promise<Identity[]> {+ if (+ !this.capabilities.submission ||+ !this.session?.accounts[account.remoteId]?.accountCapabilities?.[SUBMISSION]+ )+ return []+ const [result] = await this.call([['Identity/get', { accountId: account.remoteId }, 'i']], true)+ // The name the user chose in Inlark wins over the one configured on the server.+ return result.list.map((i: Json) => ({+ ...i,+ name: account.senderName || i.name,+ accountId: account.id,+ }))+ }+ async messages(account: Account, ids: string[], bodies = false): Promise<Message[]> {+ const result: Message[] = []+ for (const batch of batches([...new Set(ids)], this.capabilities.maxObjectsInGet)) {+ if (!batch.length) continue+ const [data] = await this.call([+ [+ 'Email/get',+ {+ accountId: account.remoteId,+ ids: batch,+ properties: bodies+ ? [+ ...summaryProperties,+ 'bodyStructure',+ 'bodyValues',+ 'textBody',+ 'htmlBody',+ 'attachments',+ 'header:List-Unsubscribe:asText',+ 'header:List-Unsubscribe-Post:asText',+ ]+ : summaryProperties,+ ...(bodies+ ? {+ fetchAllBodyValues: true,+ maxBodyValueBytes: 5_000_000,+ bodyProperties: [+ 'partId',+ 'blobId',+ 'size',+ 'name',+ 'type',+ 'charset',+ 'disposition',+ 'cid',+ 'subParts',+ ],+ }+ : {}),+ },+ 'e',+ ],+ ])+ if (data.state) this.emailState.set(account.id, data.state)+ for (const raw of data.list) {+ const message = asMessage(account, raw, bodies)+ if (bodies) {+ for (const [type, field] of [+ ['text/html', 'html'],+ ['text/plain', 'text'],+ ] as const) {+ if (message[field]?.trim()) continue+ const part = [+ ...bodyParts(raw, type),+ ...structuredBodyParts(raw.bodyStructure, type),+ ].find((part) => part.blobId && (!part.size || part.size <= 5_000_000))+ if (!part) continue+ try {+ const bytes = await this.download(account, {+ blobId: part.blobId,+ name: 'body',+ type,+ size: part.size || 0,+ })+ message[field] = new TextDecoder(part.charset || 'utf-8').decode(bytes)+ } catch {+ // Keep the other body representation or the message preview available.+ }+ }+ }+ result.push(message)+ }+ }+ return result+ }+ async query(account: Account, query: MailQuery, position = 0, limit = 50): Promise<ProviderPage> {+ const boxes = this.mailboxCache.get(account.id) || (await this.mailboxes(account))+ if (query.mailboxId && !boxes.some((b) => b.id === query.mailboxId))+ return { items: [], total: 0 }+ if (+ !query.mailboxId &&+ ['inbox', 'archive', 'sent', 'drafts', 'junk', 'trash'].includes(query.view) &&+ !boxes.some((b) => b.role === query.view)+ )+ return { items: [], total: 0 }+ const [result] = await this.call([+ [+ 'Email/query',+ {+ accountId: account.remoteId,+ filter: jmapFilter(query, boxes),+ sort: [{ property: 'receivedAt', isAscending: false }],+ collapseThreads: true,+ position,+ limit,+ calculateTotal: true,+ },+ 'q',+ ],+ ])+ const fetched = new Map((await this.messages(account, result.ids)).map((m) => [m.id, m]))+ const messages: Message[] = result.ids.flatMap((id: string) =>+ fetched.has(id) ? [fetched.get(id)!] : [],+ )+ // Only fetch thread metadata for this page, never all IDs in the mailbox.+ const threads: Json[] = []+ for (const ids of batches(+ [...new Set(messages.map((m) => m.threadId))],+ this.capabilities.maxObjectsInGet,+ )) {+ const [data] = await this.call([['Thread/get', { accountId: account.remoteId, ids }, 't']])+ threads.push(...data.list)+ }+ const otherIds = threads+ .flatMap((t) => t.emailIds)+ .filter((id: string) => !messages.some((m) => m.id === id))+ const threadMessages = [...messages, ...(await this.messages(account, otherIds))]+ const items = messages.map((m) => {+ const c = conversationFromMessages(+ account.id,+ m.threadId,+ threadMessages.filter((item) => item.threadId === m.threadId),+ )+ // Sort and display according to the matching representative, even if the thread has newer messages outside this folder.+ c.receivedAt = m.receivedAt+ c.subject = m.subject || '(No subject)'+ c.preview = m.preview+ c.count = threads.find((t) => t.id === m.threadId)?.emailIds.length || 1+ return c+ })+ return {+ items,+ total: result.total ?? position + result.ids.length,+ next:+ result.ids.length === limit &&+ (result.total === undefined || position + limit < result.total)+ ? position + result.ids.length+ : undefined,+ }+ }+ async conversationMetadata(account: Account, threadIds: string[]): Promise<Message[]> {+ const ids: string[] = []+ for (const batch of batches([...new Set(threadIds)], this.capabilities.maxObjectsInGet)) {+ const [data] = await this.call([+ ['Thread/get', { accountId: account.remoteId, ids: batch }, 't'],+ ])+ ids.push(...data.list.flatMap((t: Json) => t.emailIds))+ }+ return this.messages(account, ids)+ }+ async conversation(account: Account, threadId: string): Promise<Message[]> {+ const [result] = await this.call([+ ['Thread/get', { accountId: account.remoteId, ids: [threadId] }, 't'],+ ])+ if (!result.list.length)+ throw new JmapError('notFound', 'This conversation is no longer available.')+ return (await this.messages(account, result.list[0].emailIds, true)).sort((a, b) =>+ a.receivedAt.localeCompare(b.receivedAt),+ )+ }+ getStateToken(account: Account) {+ return this.emailState.get(account.id)+ }+ async update(+ account: Account,+ changes: MessageChanges,+ destroy: string[] = [],+ expectedState = this.getStateToken(account),+ ): Promise<{ updated: string[]; failures: string[] }> {+ const updated: string[] = [],+ failures: string[] = []+ const updates = Object.entries(changes)+ .map(([id, change]) => [id, jmapPatch(change)] as const)+ .filter(([, patch]) => Object.keys(patch).length)+ for (const entries of batches(updates, this.capabilities.maxObjectsInSet)) {+ const [result] = await this.call([+ [+ 'Email/set',+ {+ accountId: account.remoteId,+ ifInState: expectedState,+ update: Object.fromEntries(entries),+ },+ 's',+ ],+ ])+ if (result.newState) {+ this.emailState.set(account.id, result.newState)+ expectedState = result.newState+ }+ updated.push(...Object.keys(result.updated || {}))+ failures.push(+ ...Object.entries(result.notUpdated || {}).map(([id, e]) => id + ': ' + (e as Json).type),+ )+ }+ for (const ids of batches(destroy, this.capabilities.maxObjectsInSet)) {+ const [result] = await this.call([+ ['Email/set', { accountId: account.remoteId, ifInState: expectedState, destroy: ids }, 's'],+ ])+ if (result.newState) {+ this.emailState.set(account.id, result.newState)+ expectedState = result.newState+ }+ updated.push(...(result.destroyed || []))+ failures.push(+ ...Object.entries(result.notDestroyed || {}).map(([id, e]) => id + ': ' + (e as Json).type),+ )+ }+ return { updated, failures }+ }+ async folder(+ account: Account,+ operation: 'create' | 'rename' | 'delete',+ id?: string,+ name?: string,+ parentId?: string,+ ): Promise<void> {+ const boxes = await this.mailboxes(account)+ const box = boxes.find((b) => b.id === id)+ if (operation !== 'create' && (!box || box.role))+ throw new JmapError('permission', 'Special folders cannot be renamed or deleted.')+ if (operation === 'rename' && !box?.rights.mayRename)+ throw new JmapError('permission', 'You cannot rename this folder.')+ if (operation === 'delete' && !box?.rights.mayDelete)+ throw new JmapError('permission', 'You cannot delete this folder.')+ const args =+ operation === 'create'+ ? { create: { new: { name, parentId: parentId || null } } }+ : operation === 'rename'+ ? { update: { [id!]: { name } } }+ : { destroy: [id], onDestroyRemoveEmails: false }+ const [result] = await this.call([+ ['Mailbox/set', { accountId: account.remoteId, ...args }, 'm'],+ ])+ const errors = { ...result.notCreated, ...result.notUpdated, ...result.notDestroyed }+ if (Object.keys(errors).length)+ throw new JmapError(+ 'folder',+ 'Folder change failed (' ++ Object.values<Json>(errors)[0].type ++ '). The folder may still contain messages.',+ )+ this.mailboxCache.delete(account.id)+ }+ async upload(account: Account, data: Uint8Array, type: string): Promise<string> {+ if (!this.session) throw new JmapError('session', 'Reconnect the account.')+ if (data.byteLength > this.capabilities.maxUploadSize)+ throw new JmapError('tooLarge', 'This attachment exceeds the server upload limit.')+ const url = this.session.uploadUrl.replace('{accountId}', encodeURIComponent(account.remoteId))+ const response = await this.request(url, {+ method: 'POST',+ headers: { 'Content-Type': type },+ body: data as BodyInit,+ signal: AbortSignal.timeout(120_000),+ })+ const result = (await response.json()) as Json+ if (result.accountId !== account.remoteId || !result.blobId)+ throw new JmapError('upload', 'The upload could not be verified.')+ return result.blobId+ }+ async download(account: Account, attachment: Attachment): Promise<Uint8Array> {+ if (!this.session) throw new JmapError('session', 'Reconnect the account.')+ let url = this.session.downloadUrl+ for (const [key, value] of Object.entries({+ accountId: account.remoteId,+ blobId: attachment.blobId,+ type: attachment.type,+ name: attachment.name,+ }))+ url = url.replace('{' + key + '}', encodeURIComponent(value))+ const response = await this.request(url, { signal: AbortSignal.timeout(120_000) })+ const reader = response.body?.getReader()+ if (!reader) throw new JmapError('download', 'Empty attachment response.')+ const chunks: Uint8Array[] = []+ let size = 0+ while (true) {+ const part = await reader.read()+ if (part.done) break+ size += part.value.byteLength+ if (size > 100_000_000) {+ await reader.cancel()+ throw new JmapError(+ 'tooLarge',+ 'Attachments over 100 MB are not supported in this version.',+ )+ }+ chunks.push(part.value)+ }+ const bytes = new Uint8Array(size)+ let offset = 0+ for (const chunk of chunks) {+ bytes.set(chunk, offset)+ offset += chunk.byteLength+ }+ return bytes+ }+ async createDraft(account: Account, draft: Draft, messageId?: string): Promise<string> {+ const boxes = await this.mailboxes(account)+ const drafts = boxes.find((b) => b.role === 'drafts')+ if (!drafts?.rights.mayAddItems)+ throw new JmapError('drafts', 'A writable Drafts folder is required.')+ const identity = (await this.identities(account)).find((i) => i.id === draft.identityId)+ if (!identity) throw new JmapError('identity', 'Choose a valid sending identity.')+ const [result] = await this.call([+ [+ 'Email/set',+ {+ accountId: account.remoteId,+ create: {+ draft: {+ mailboxIds: { [drafts.id]: true },+ keywords: { $draft: true, $seen: true },+ from: [{ name: identity.name, email: identity.email }],+ to: draft.to,+ cc: draft.cc,+ bcc: draft.bcc,+ subject: draft.subject,+ ...(messageId ? { messageId: [messageId] } : {}),+ ...(draft.inReplyTo?.length ? { inReplyTo: draft.inReplyTo } : {}),+ ...(draft.references?.length ? { references: draft.references } : {}),+ textBody: [{ partId: 'text', type: 'text/plain' }],+ htmlBody: [{ partId: 'html', type: 'text/html' }],+ bodyValues: { text: { value: draft.text }, html: { value: draft.html } },+ attachments: draft.attachments.map((a) => ({+ blobId: a.blobId,+ type: a.type,+ name: a.name,+ disposition: a.cid ? 'inline' : 'attachment',+ ...(a.cid ? { cid: a.cid } : {}),+ })),+ },+ },+ },+ 'd',+ ],+ ])+ if (!result.created?.draft?.id)+ throw new JmapError(+ 'draft',+ 'The server could not save the draft (' ++ (result.notCreated?.draft?.type || 'unknown') ++ ').',+ )+ return result.created.draft.id+ }+ async prepareSubmission(+ account: Account,+ draft: Draft,+ messageId: string,+ ): Promise<OutgoingMessage> {+ const emailId = await this.createDraft(account, draft, messageId)+ const identity = (await this.identities(account)).find((i) => i.id === draft.identityId)+ return {+ messageId,+ emailId,+ envelope: {+ from: identity?.email || account.email,+ to: [...draft.to, ...draft.cc, ...draft.bcc].map((a) => a.email),+ },+ }+ }+ async submit(+ account: Account,+ message: OutgoingMessage,+ identityId: string,+ ): Promise<SubmissionOutcome> {+ if (!this.capabilities.submission)+ throw new JmapError('submission', 'This account does not support sending through JMAP.')+ if (!message.emailId) throw new JmapError('submission', 'The message was not prepared.')+ const boxes = await this.mailboxes(account)+ const sent = boxes.find((b) => b.role === 'sent'),+ drafts = boxes.find((b) => b.role === 'drafts')+ if (!sent || !drafts)+ throw new JmapError('mailboxes', 'Sent and Drafts folders are required for sending.')+ const patch: Json = {+ 'keywords/$draft': null,+ ['mailboxIds/' + pointer(drafts.id)]: null,+ ['mailboxIds/' + pointer(sent.id)]: true,+ }+ let result: Json+ try {+ ;[result] = await this.call(+ [+ [+ 'EmailSubmission/set',+ {+ accountId: account.remoteId,+ create: { send: { emailId: message.emailId, identityId } },+ onSuccessUpdateEmail: { '#send': patch },+ },+ 's',+ ],+ ],+ true,+ )+ } catch (error) {+ // A lost response after the request left may still have been processed.+ if (error instanceof JmapError && ['network', 'http', 'response'].includes(error.code))+ throw new JmapError('submissionUncertain', error.message)+ throw error+ }+ if (!result.created?.send?.id)+ throw new JmapError(+ 'submissionRejected',+ 'The server rejected the message (' + (result.notCreated?.send?.type || 'unknown') + ').',+ )+ return { accepted: message.envelope.to, rejected: [] }+ }+ async submissionExists(account: Account, message: OutgoingMessage): Promise<boolean> {+ const emailId = message.emailId+ if (!emailId) return false+ const [result] = await this.call(+ [+ [+ 'EmailSubmission/query',+ { accountId: account.remoteId, filter: { emailIds: [emailId] }, limit: 1 },+ 'q',+ ],+ ],+ true,+ )+ if (result.ids?.length) return true+ const [email] = await this.messages(account, [emailId])+ const sent = (await this.mailboxes(account)).find((b) => b.role === 'sent')+ return !!(email && sent && email.mailboxIds[sent.id] && !email.keywords.$draft)+ }+ subscribe(listener: (event: ProviderEvent) => void): () => void {+ this.listeners.add(listener)+ if (this.listeners.size === 1 && this.session?.eventSourceUrl) void this.push()+ return () => {+ this.listeners.delete(listener)+ if (!this.listeners.size) this.controller?.abort()+ }+ }+ private async push() {+ let attempt = 0+ while (!this.disposed && this.listeners.size && this.session?.eventSourceUrl) {+ this.controller = new AbortController()+ const timer = setTimeout(() => this.controller?.abort(), 130_000)+ try {+ const url = this.session.eventSourceUrl+ .replace('{types}', 'Email,Mailbox,Thread,EmailSubmission')+ .replace('{closeafter}', 'no')+ .replace('{ping}', '30')+ const response = await this.request(url, {+ headers: { Accept: 'text/event-stream' },+ signal: this.controller.signal,+ })+ if (!response.body) throw new Error('No stream')+ attempt = 0+ const reader = response.body.getReader(),+ decoder = new TextDecoder()+ let buffer = ''+ while (!this.disposed) {+ const { value, done } = await reader.read()+ if (done) break+ buffer += decoder.decode(value, { stream: true }).replace(/\r\n/g, '\n')+ if (buffer.length > 1_000_000) throw new Error('Invalid event stream')+ let boundary: number+ while ((boundary = buffer.indexOf('\n\n')) !== -1) {+ const event = buffer.slice(0, boundary)+ buffer = buffer.slice(boundary + 2)+ if (+ event.includes('event: state') ||+ event.includes('"@type":"StateChange"') ||+ event.includes('"changed"')+ )+ this.emit({ type: 'changed' })+ }+ }+ } catch {+ /* Main service polls independently and reports actual account reachability. */+ } finally {+ clearTimeout(timer)+ this.controller?.abort()+ }+ if (!this.disposed && this.listeners.size)+ await new Promise((r) =>+ setTimeout(r, Math.min(60_000, 1000 * 2 ** Math.min(attempt++, 6))),+ )+ }+ }+ dispose() {+ this.disposed = true+ this.controller?.abort()+ this.listeners.clear()+ this.mailboxCache.clear()+ }+}diff --git a/packages/jmap/tsconfig.json b/packages/jmap/tsconfig.jsonnew file mode 100644index 0000000..f46ada1--- /dev/null+++ b/packages/jmap/tsconfig.json@@ -0,0 +1 @@+{ "extends": "../../tsconfig.json", "include": ["src"] }diff --git a/packages/ui/components.json b/packages/ui/components.jsonnew file mode 100644index 0000000..624906c--- /dev/null+++ b/packages/ui/components.json@@ -0,0 +1,21 @@+{+ "$schema": "https://ui.shadcn.com/schema.json",+ "style": "base-nova",+ "rsc": false,+ "tsx": true,+ "tailwind": {+ "config": "",+ "css": "src/styles.css",+ "baseColor": "neutral",+ "cssVariables": true,+ "prefix": ""+ },+ "iconLibrary": "hugeicons",+ "aliases": {+ "components": "#components",+ "ui": "#components",+ "lib": "#lib",+ "hooks": "#hooks",+ "utils": "#lib/utils"+ }+}diff --git a/packages/ui/package.json b/packages/ui/package.jsonnew file mode 100644index 0000000..7f8c157--- /dev/null+++ b/packages/ui/package.json@@ -0,0 +1,39 @@+{+ "name": "@inlark/ui",+ "version": "0.1.0",+ "private": true,+ "license": "AGPL-3.0-only",+ "type": "module",+ "exports": {+ ".": "./src/index.tsx",+ "./icons": "./src/icons.tsx",+ "./styles.css": "./src/styles.css",+ "./components/*": "./src/components/*.tsx",+ "./lib/*": "./src/lib/*.ts",+ "./hooks/*": "./src/hooks/*.ts"+ },+ "scripts": {+ "typecheck": "tsc -p tsconfig.json"+ },+ "dependencies": {+ "@base-ui/react": "^1.8.0",+ "@hugeicons/core-free-icons": "^4.3.5",+ "@hugeicons/react": "^1.1.10",+ "clsx": "^2.1.1",+ "react-day-picker": "^9.14.0",+ "tailwind-merge": "^3.0.0"+ },+ "peerDependencies": {+ "react": "^19.0.0",+ "react-dom": "^19.0.0"+ },+ "devDependencies": {+ "@types/react": "^19.0.0",+ "@types/react-dom": "^19.0.0"+ },+ "imports": {+ "#components/*": "./src/components/*.tsx",+ "#lib/*": "./src/lib/*.ts",+ "#hooks/*": "./src/hooks/*.ts"+ }+}diff --git a/packages/ui/src/components/checkbox.tsx b/packages/ui/src/components/checkbox.tsxnew file mode 100644index 0000000..0714710--- /dev/null+++ b/packages/ui/src/components/checkbox.tsx@@ -0,0 +1,39 @@+import { Checkbox as BaseCheckbox } from '@base-ui/react/checkbox'+import { cn } from '../lib/utils'+import { Check, Minus } from '../icons'++export function Checkbox({+ checked,+ indeterminate,+ onCheckedChange,+ disabled,+ className,+ 'aria-label': ariaLabel,+}: {+ checked: boolean+ indeterminate?: boolean+ /** `event` is the click or key event, so callers can read modifier keys. */+ onCheckedChange: (checked: boolean, event: Event) => void+ disabled?: boolean+ className?: string+ 'aria-label'?: string+}) {+ return (+ <BaseCheckbox.Root+ checked={checked}+ indeterminate={indeterminate}+ disabled={disabled}+ aria-label={ariaLabel}+ className={cn('checkbox', className)}+ onCheckedChange={(next, details) => onCheckedChange(next, details.event)}+ >+ <BaseCheckbox.Indicator className="checkbox-indicator">+ {indeterminate ? (+ <Minus size={11} strokeWidth={2.5} />+ ) : (+ <Check size={11} strokeWidth={2.5} />+ )}+ </BaseCheckbox.Indicator>+ </BaseCheckbox.Root>+ )+}diff --git a/packages/ui/src/components/date-picker.tsx b/packages/ui/src/components/date-picker.tsxnew file mode 100644index 0000000..1e657a6--- /dev/null+++ b/packages/ui/src/components/date-picker.tsx@@ -0,0 +1,101 @@+import * as React from 'react'+import { Popover } from '@base-ui/react/popover'+import { DayPicker } from 'react-day-picker'+import { cn } from '../lib/utils'+import { Calendar, ChevronLeft, ChevronRight, X } from '../icons'++/** Parses a `yyyy-mm-dd` string as a local calendar day. */+const parseDay = (value?: string) => {+ const match = value && /^(\d{4})-(\d{2})-(\d{2})/.exec(value)+ return match ? new Date(Number(match[1]), Number(match[2]) - 1, Number(match[3])) : undefined+}+const formatDay = (date: Date) =>+ [+ date.getFullYear(),+ String(date.getMonth() + 1).padStart(2, '0'),+ String(date.getDate()).padStart(2, '0'),+ ].join('-')++/** Picks a calendar day; the value is a `yyyy-mm-dd` string, like a native date input. */+export function DatePicker({+ value,+ onValueChange,+ placeholder = 'Any date',+ className,+ 'aria-label': ariaLabel,+}: {+ value?: string+ onValueChange: (value: string | undefined) => void+ placeholder?: string+ className?: string+ 'aria-label'?: string+}) {+ const [open, setOpen] = React.useState(false)+ const selected = parseDay(value)+ return (+ <Popover.Root open={open} onOpenChange={setOpen}>+ <div className={cn('date-picker', className)}>+ <Popover.Trigger className="select-trigger date-trigger" aria-label={ariaLabel}>+ <Calendar size={14} className="date-trigger-icon" />+ <span className={cn('select-value', !selected && 'placeholder')}>+ {selected+ ? selected.toLocaleDateString(undefined, { dateStyle: 'medium' })+ : placeholder}+ </span>+ </Popover.Trigger>+ {selected && (+ <button+ type="button"+ className="date-clear"+ aria-label={'Clear ' + (ariaLabel || 'date')}+ onClick={() => onValueChange(undefined)}+ >+ <X size={12} />+ </button>+ )}+ </div>+ <Popover.Portal>+ <Popover.Positioner sideOffset={6} align="start" className="date-positioner">+ <Popover.Popup className="dropdown date-popup">+ <DayPicker+ mode="single"+ autoFocus+ showOutsideDays+ selected={selected}+ defaultMonth={selected}+ onSelect={(date) => {+ onValueChange(date ? formatDay(date) : undefined)+ setOpen(false)+ }}+ components={{+ Chevron: ({ orientation }) =>+ orientation === 'left' ? <ChevronLeft size={14} /> : <ChevronRight size={14} />,+ }}+ classNames={{+ root: 'calendar',+ months: 'calendar-months',+ month: 'calendar-month',+ month_caption: 'calendar-caption',+ caption_label: 'calendar-caption-label',+ nav: 'calendar-nav',+ button_previous: 'button button-ghost button-icon calendar-nav-button',+ button_next: 'button button-ghost button-icon calendar-nav-button',+ month_grid: 'calendar-grid',+ weekdays: 'calendar-weekdays',+ weekday: 'calendar-weekday',+ week: 'calendar-week',+ day: 'calendar-day',+ day_button: 'calendar-day-button',+ selected: 'selected',+ today: 'today',+ outside: 'outside',+ disabled: 'disabled',+ hidden: 'hidden',+ }}+ />+ </Popover.Popup>+ </Popover.Positioner>+ </Popover.Portal>+ </Popover.Root>+ )+}diff --git a/packages/ui/src/components/select.tsx b/packages/ui/src/components/select.tsxnew file mode 100644index 0000000..4f293ae--- /dev/null+++ b/packages/ui/src/components/select.tsx@@ -0,0 +1,70 @@+import { Select as BaseSelect } from '@base-ui/react/select'+import { cn } from '../lib/utils'+import { Check, ChevronDown } from '../icons'++export type SelectOption<Value extends string> = { value: Value; label: string }++/** A single-choice picker that opens a menu styled like the app's dropdowns. */+export function Select<Value extends string>({+ value,+ options,+ onValueChange,+ disabled,+ id,+ className,+ 'aria-label': ariaLabel,+}: {+ value: Value+ options: readonly SelectOption<Value>[]+ onValueChange: (value: Value) => void+ disabled?: boolean+ id?: string+ className?: string+ 'aria-label'?: string+}) {+ return (+ <BaseSelect.Root+ value={value}+ items={options}+ disabled={disabled}+ onValueChange={(next) => {+ if (next !== null) onValueChange(next)+ }}+ >+ <BaseSelect.Trigger+ id={id}+ aria-label={ariaLabel}+ className={cn('select-trigger', className)}+ >+ <BaseSelect.Value className="select-value" />+ <BaseSelect.Icon className="select-icon">+ <ChevronDown size={13} />+ </BaseSelect.Icon>+ </BaseSelect.Trigger>+ <BaseSelect.Portal>+ <BaseSelect.Positioner+ className="select-positioner"+ sideOffset={6}+ alignItemWithTrigger={false}+ >+ <BaseSelect.Popup className="dropdown select-popup">+ <BaseSelect.List>+ {options.map((option) => (+ <BaseSelect.Item+ key={option.value}+ value={option.value}+ className="menu-item select-item"+ >+ <BaseSelect.ItemText>{option.label}</BaseSelect.ItemText>+ <BaseSelect.ItemIndicator className="select-item-indicator">+ <Check size={13} />+ </BaseSelect.ItemIndicator>+ </BaseSelect.Item>+ ))}+ </BaseSelect.List>+ </BaseSelect.Popup>+ </BaseSelect.Positioner>+ </BaseSelect.Portal>+ </BaseSelect.Root>+ )+}diff --git a/packages/ui/src/components/switch.tsx b/packages/ui/src/components/switch.tsxnew file mode 100644index 0000000..3a0343d--- /dev/null+++ b/packages/ui/src/components/switch.tsx@@ -0,0 +1,28 @@+import { Switch as BaseSwitch } from '@base-ui/react/switch'+import { cn } from '../lib/utils'++export function Switch({+ checked,+ onCheckedChange,+ disabled,+ className,+ 'aria-label': ariaLabel,+}: {+ checked: boolean+ onCheckedChange: (checked: boolean) => void+ disabled?: boolean+ className?: string+ 'aria-label'?: string+}) {+ return (+ <BaseSwitch.Root+ checked={checked}+ disabled={disabled}+ aria-label={ariaLabel}+ className={cn('switch', className)}+ onCheckedChange={(next) => onCheckedChange(next)}+ >+ <BaseSwitch.Thumb className="switch-thumb" />+ </BaseSwitch.Root>+ )+}diff --git a/packages/ui/src/fonts/InterVariable.woff2 b/packages/ui/src/fonts/InterVariable.woff2new file mode 100644index 0000000..5a8d3e7Binary files /dev/null and b/packages/ui/src/fonts/InterVariable.woff2 differdiff --git a/packages/ui/src/fonts/OFL.txt b/packages/ui/src/fonts/OFL.txtnew file mode 100644index 0000000..9b2ca37--- /dev/null+++ b/packages/ui/src/fonts/OFL.txt@@ -0,0 +1,92 @@+Copyright (c) 2016 The Inter Project Authors (https://github.com/rsms/inter)++This Font Software is licensed under the SIL Open Font License, Version 1.1.+This license is copied below, and is also available with a FAQ at:+http://scripts.sil.org/OFL++-----------------------------------------------------------+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007+-----------------------------------------------------------++PREAMBLE+The goals of the Open Font License (OFL) are to stimulate worldwide+development of collaborative font projects, to support the font creation+efforts of academic and linguistic communities, and to provide a free and+open framework in which fonts may be shared and improved in partnership+with others.++The OFL allows the licensed fonts to be used, studied, modified and+redistributed freely as long as they are not sold by themselves. The+fonts, including any derivative works, can be bundled, embedded,+redistributed and/or sold with any software provided that any reserved+names are not used by derivative works. The fonts and derivatives,+however, cannot be released under any other type of license. The+requirement for fonts to remain under this license does not apply+to any document created using the fonts or their derivatives.++DEFINITIONS+"Font Software" refers to the set of files released by the Copyright+Holder(s) under this license and clearly marked as such. This may+include source files, build scripts and documentation.++"Reserved Font Name" refers to any names specified as such after the+copyright statement(s).++"Original Version" refers to the collection of Font Software components as+distributed by the Copyright Holder(s).++"Modified Version" refers to any derivative made by adding to, deleting,+or substituting -- in part or in whole -- any of the components of the+Original Version, by changing formats or by porting the Font Software to a+new environment.++"Author" refers to any designer, engineer, programmer, technical+writer or other person who contributed to the Font Software.++PERMISSION AND CONDITIONS+Permission is hereby granted, free of charge, to any person obtaining+a copy of the Font Software, to use, study, copy, merge, embed, modify,+redistribute, and sell modified and unmodified copies of the Font+Software, subject to the following conditions:++1) Neither the Font Software nor any of its individual components,+in Original or Modified Versions, may be sold by itself.++2) Original or Modified Versions of the Font Software may be bundled,+redistributed and/or sold with any software, provided that each copy+contains the above copyright notice and this license. These can be+included either as stand-alone text files, human-readable headers or+in the appropriate machine-readable metadata fields within text or+binary files as long as those fields can be easily viewed by the user.++3) No Modified Version of the Font Software may use the Reserved Font+Name(s) unless explicit written permission is granted by the corresponding+Copyright Holder. This restriction only applies to the primary font name as+presented to the users.++4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font+Software shall not be used to promote, endorse or advertise any+Modified Version, except to acknowledge the contribution(s) of the+Copyright Holder(s) and the Author(s) or with their explicit written+permission.++5) The Font Software, modified or unmodified, in part or in whole,+must be distributed entirely under this license, and must not be+distributed under any other license. The requirement for fonts to+remain under this license does not apply to any document created+using the Font Software.++TERMINATION+This license becomes null and void if any of the above conditions are+not met.++DISCLAIMER+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM+OTHER DEALINGS IN THE FONT SOFTWARE.diff --git a/packages/ui/src/fonts/README.md b/packages/ui/src/fonts/README.mdnew file mode 100644index 0000000..d116b9c--- /dev/null+++ b/packages/ui/src/fonts/README.md@@ -0,0 +1,5 @@+Inter Variable 4.1, from the [Inter project](https://rsms.me/inter/).++`InterVariable.woff2` is bundled locally for consistent, offline typography. It is+licensed under the SIL Open Font License in `OFL.txt`. The desktop renderer also+ships that license from `public/licenses/Inter-OFL.txt`.diff --git a/packages/ui/src/icons.tsx b/packages/ui/src/icons.tsxnew file mode 100644index 0000000..02798c4--- /dev/null+++ b/packages/ui/src/icons.tsx@@ -0,0 +1,149 @@+import type { ComponentType } from 'react'+import { HugeiconsIcon, type HugeiconsIconProps, type IconSvgElement } from '@hugeicons/react'+import {+ AlertCircle as AlertCircleGlyph,+ Archive as ArchiveGlyph,+ ArrowDown as ArrowDownGlyph,+ ArrowLeft as ArrowLeftGlyph,+ ArrowUp as ArrowUpGlyph,+ ArrowUpRight as ArrowUpRightGlyph,+ Bold as BoldGlyph,+ Calendar as CalendarGlyph,+ Check as CheckGlyph,+ ChevronDown as ChevronDownGlyph,+ ChevronLeft as ChevronLeftGlyph,+ ChevronRight as ChevronRightGlyph,+ ChevronUp as ChevronUpGlyph,+ Copy as CopyGlyph,+ CornerDownLeft as CornerDownLeftGlyph,+ Download as DownloadGlyph,+ ExternalLink as ExternalLinkGlyph,+ File as FileGlyph,+ FileArchive as FileArchiveGlyph,+ FileImage as FileImageGlyph,+ FileSpreadsheetIcon as FileSpreadsheetIconGlyph,+ FileText as FileTextGlyph,+ Folder as FolderGlyph,+ FolderInputIcon as FolderInputIconGlyph,+ FolderPlus as FolderPlusGlyph,+ Forward as ForwardGlyph,+ ImageRemove01Icon as ImageRemoveGlyph,+ ImageUpload01Icon as ImageUploadGlyph,+ ImageOff as ImageOffGlyph,+ Inbox as InboxGlyph,+ Info as InfoGlyph,+ Italic as ItalicGlyph,+ Keyboard as KeyboardGlyph,+ Link2 as Link2Glyph,+ List as ListGlyph,+ LoaderCircle as LoaderCircleGlyph,+ LockKeyhole as LockKeyholeGlyph,+ Mail as MailGlyph,+ MailOpen as MailOpenGlyph,+ Minus as MinusGlyph,+ Monitor as MonitorGlyph,+ Moon as MoonGlyph,+ MoreHorizontal as MoreHorizontalGlyph,+ PanelLeftClose as PanelLeftCloseGlyph,+ PanelLeftOpen as PanelLeftOpenGlyph,+ ParagraphBulletsPoint02Icon as BulletListGlyph,+ Paperclip as PaperclipGlyph,+ PenLine as PenLineGlyph,+ Plus as PlusGlyph,+ RefreshCw as RefreshCwGlyph,+ Reply as ReplyGlyph,+ ReplyAll as ReplyAllGlyph,+ Rows3 as Rows3Glyph,+ Search as SearchGlyph,+ Send as SendGlyph,+ Settings as SettingsGlyph,+ SettingsIcon as SettingsIconGlyph,+ ShieldCheck as ShieldCheckGlyph,+ ShieldX as ShieldXGlyph,+ Shuffle as ShuffleGlyph,+ SlidersHorizontal as SlidersHorizontalGlyph,+ SquarePenIcon as SquarePenGlyph,+ Star as StarGlyph,+ Sun as SunGlyph,+ Trash2 as Trash2Glyph,+ Undo2 as Undo2Glyph,+ UserRound as UserRoundGlyph,+ WifiOff as WifiOffGlyph,+ X as XGlyph,+} from '@hugeicons/core-free-icons'++export type IconComponent = ComponentType<Omit<HugeiconsIconProps, 'icon'>>++const icon =+ (glyph: IconSvgElement): IconComponent =>+ (props) => <HugeiconsIcon icon={glyph} color="currentColor" {...props} />++export const AlertCircle = icon(AlertCircleGlyph)+export const Archive = icon(ArchiveGlyph)+export const ArrowDown = icon(ArrowDownGlyph)+export const ArrowLeft = icon(ArrowLeftGlyph)+export const ArrowUp = icon(ArrowUpGlyph)+export const ArrowUpRight = icon(ArrowUpRightGlyph)+export const Bold = icon(BoldGlyph)+export const Calendar = icon(CalendarGlyph)+export const Check = icon(CheckGlyph)+export const ChevronDown = icon(ChevronDownGlyph)+export const ChevronLeft = icon(ChevronLeftGlyph)+export const ChevronRight = icon(ChevronRightGlyph)+export const ChevronUp = icon(ChevronUpGlyph)+export const Copy = icon(CopyGlyph)+export const CornerDownLeft = icon(CornerDownLeftGlyph)+export const Download = icon(DownloadGlyph)+export const ExternalLink = icon(ExternalLinkGlyph)+export const File = icon(FileGlyph)+export const FileArchive = icon(FileArchiveGlyph)+export const FileImage = icon(FileImageGlyph)+export const FileSpreadsheet = icon(FileSpreadsheetIconGlyph)+export const FileText = icon(FileTextGlyph)+export const Folder = icon(FolderGlyph)+export const FolderInput = icon(FolderInputIconGlyph)+export const FolderPlus = icon(FolderPlusGlyph)+export const Forward = icon(ForwardGlyph)+export const ImageRemove = icon(ImageRemoveGlyph)+export const ImageUpload = icon(ImageUploadGlyph)+export const ImageOff = icon(ImageOffGlyph)+export const Inbox = icon(InboxGlyph)+export const Info = icon(InfoGlyph)+export const Italic = icon(ItalicGlyph)+export const Keyboard = icon(KeyboardGlyph)+export const Link2 = icon(Link2Glyph)+export const List = icon(ListGlyph)+export const LoaderCircle = icon(LoaderCircleGlyph)+export const LockKeyhole = icon(LockKeyholeGlyph)+export const Mail = icon(MailGlyph)+export const MailOpen = icon(MailOpenGlyph)+export const Minus = icon(MinusGlyph)+export const Monitor = icon(MonitorGlyph)+export const Moon = icon(MoonGlyph)+export const MoreHorizontal = icon(MoreHorizontalGlyph)+export const PanelLeftClose = icon(PanelLeftCloseGlyph)+export const PanelLeftOpen = icon(PanelLeftOpenGlyph)+export const BulletList = icon(BulletListGlyph)+export const Paperclip = icon(PaperclipGlyph)+export const PenLine = icon(PenLineGlyph)+export const Plus = icon(PlusGlyph)+export const RefreshCw = icon(RefreshCwGlyph)+export const Reply = icon(ReplyGlyph)+export const ReplyAll = icon(ReplyAllGlyph)+export const Rows3 = icon(Rows3Glyph)+export const Search = icon(SearchGlyph)+export const Send = icon(SendGlyph)+export const Settings = icon(SettingsGlyph)+export const SettingsIcon = icon(SettingsIconGlyph)+export const ShieldCheck = icon(ShieldCheckGlyph)+export const ShieldX = icon(ShieldXGlyph)+export const Shuffle = icon(ShuffleGlyph)+export const SlidersHorizontal = icon(SlidersHorizontalGlyph)+export const SquarePen = icon(SquarePenGlyph)+export const Star = icon(StarGlyph)+export const Sun = icon(SunGlyph)+export const Trash2 = icon(Trash2Glyph)+export const Undo2 = icon(Undo2Glyph)+export const UserRound = icon(UserRoundGlyph)+export const WifiOff = icon(WifiOffGlyph)+export const X = icon(XGlyph)diff --git a/packages/ui/src/index.tsx b/packages/ui/src/index.tsxnew file mode 100644index 0000000..dc4d629--- /dev/null+++ b/packages/ui/src/index.tsx@@ -0,0 +1,201 @@+import * as React from 'react'+import { Dialog } from '@base-ui/react/dialog'+import { Tooltip } from '@base-ui/react/tooltip'+import { Menu } from '@base-ui/react/menu'+import { cn } from './lib/utils'+export { cn } from './lib/utils'+import { X, LoaderCircle } from './icons'+export function Button({+ className,+ variant = 'default',+ size = 'default',+ ...props+}: React.ButtonHTMLAttributes<HTMLButtonElement> & {+ variant?: 'default' | 'primary' | 'ghost' | 'danger'+ size?: 'default' | 'icon' | 'small'+}) {+ return (+ <button+ type="button"+ className={cn('button', 'button-' + variant, 'button-' + size, className)}+ {...props}+ />+ )+}+export function IconButton({+ label,+ shortcut,+ children,+ ...props+}: React.ButtonHTMLAttributes<HTMLButtonElement> & { label: string; shortcut?: string }) {+ return (+ <Tooltip.Root>+ <Tooltip.Trigger+ render={<Button size="icon" variant="ghost" aria-label={label} {...props} />}+ >+ {children}+ </Tooltip.Trigger>+ <Tooltip.Portal>+ <Tooltip.Positioner sideOffset={7}>+ <Tooltip.Popup className="tooltip">+ {label}+ {shortcut && <kbd>{shortcut}</kbd>}+ </Tooltip.Popup>+ </Tooltip.Positioner>+ </Tooltip.Portal>+ </Tooltip.Root>+ )+}+export function Modal({+ open,+ onOpenChange,+ title,+ description,+ children,+ className,+ popupRef,+}: {+ open: boolean+ onOpenChange: (open: boolean) => void+ title: string+ description?: string+ children: React.ReactNode+ className?: string+ popupRef?: React.Ref<HTMLDivElement>+}) {+ return (+ <Dialog.Root open={open} onOpenChange={onOpenChange}>+ <Dialog.Portal>+ <Dialog.Backdrop className="modal-backdrop" />+ <Dialog.Popup ref={popupRef} className={cn('modal', className)}>+ <div className="modal-heading">+ <div>+ <Dialog.Title className="modal-title">{title}</Dialog.Title>+ {description && (+ <Dialog.Description className="modal-description">{description}</Dialog.Description>+ )}+ </div>+ <Dialog.Close render={<Button variant="ghost" size="icon" aria-label="Close dialog" />}>+ <X size={16} />+ </Dialog.Close>+ </div>+ {children}+ </Dialog.Popup>+ </Dialog.Portal>+ </Dialog.Root>+ )+}+export function Dropdown({+ trigger,+ children,+ container,+ className,+}: {+ trigger: React.ReactElement+ children: React.ReactNode+ container?: React.RefObject<HTMLElement | null>+ className?: string+}) {+ return (+ <Menu.Root>+ <Menu.Trigger render={trigger} />+ <Menu.Portal container={container}>+ <Menu.Positioner sideOffset={6} align="end">+ <Menu.Popup className={cn('dropdown', className)}>{children}</Menu.Popup>+ </Menu.Positioner>+ </Menu.Portal>+ </Menu.Root>+ )+}+export function MenuItem({+ children,+ onClick,+ danger,+ disabled,+}: {+ children: React.ReactNode+ onClick?: () => void+ danger?: boolean+ disabled?: boolean+}) {+ return (+ <Menu.Item+ className={cn('menu-item', danger && 'danger')}+ onClick={onClick}+ disabled={disabled}+ >+ {children}+ </Menu.Item>+ )+}+export const TooltipProvider = Tooltip.Provider+export function Spinner({ size = 16 }: { size?: number }) {+ return <LoaderCircle className="spin" size={size} aria-label="Loading" />+}+export function EmptyState({+ icon: Icon,+ title,+ description,+ children,+}: {+ icon: React.ElementType+ title: string+ description?: string+ children?: React.ReactNode+}) {+ return (+ <div className="empty-state">+ <div className="empty-icon">+ <Icon size={26} strokeWidth={1.4} />+ </div>+ <h2>{title}</h2>+ {description && <p>{description}</p>}+ {children}+ </div>+ )+}+export function Avatar({+ name,+ color,+ size = 32,+ image,+}: {+ name: string+ color?: string+ size?: number+ image?: string | null+}) {+ const [imageFailed, setImageFailed] = React.useState(false)+ React.useEffect(() => setImageFailed(false), [image])+ const letters =+ name+ .trim()+ .split(/[\s@.]+/)+ .slice(0, 2)+ .map((s) => s[0])+ .join('')+ .toUpperCase() || '?'+ return (+ <span+ className="avatar"+ style={+ {+ '--avatar-color': color || '#a69aef',+ width: size,+ height: size,+ fontSize: size < 30 ? 10 : 12,+ } as React.CSSProperties+ }+ >+ {image && !imageFailed ? (+ <img src={image} alt="" onError={() => setImageFailed(true)} />+ ) : (+ letters+ )}+ </span>+ )+}+export { Select, type SelectOption } from './components/select'+export { Checkbox } from './components/checkbox'+export { Switch } from './components/switch'+export { DatePicker } from './components/date-picker'diff --git a/packages/ui/src/lib/utils.ts b/packages/ui/src/lib/utils.tsnew file mode 100644index 0000000..de6131a--- /dev/null+++ b/packages/ui/src/lib/utils.ts@@ -0,0 +1,3 @@+import { clsx, type ClassValue } from 'clsx'+import { twMerge } from 'tailwind-merge'+export const cn = (...inputs: ClassValue[]) => twMerge(clsx(inputs))diff --git a/packages/ui/src/styles.css b/packages/ui/src/styles.cssnew file mode 100644index 0000000..368a84b--- /dev/null+++ b/packages/ui/src/styles.css@@ -0,0 +1,677 @@+@import 'tailwindcss';+@source "./";+@source "../../../apps/desktop/src/renderer";++/* Bundled locally: no font service or network request is needed at runtime. */+@font-face {+ font-family: 'Inter';+ font-style: normal;+ font-weight: 100 900;+ font-display: swap;+ src: url('./fonts/InterVariable.woff2') format('woff2');+}++@theme inline {+ --color-background: var(--bg);+ --color-foreground: var(--text);+ --color-muted: var(--muted);+ --color-border: var(--border);+ --color-primary: var(--accent);+}+:root {+ color-scheme: dark;+ --bg: #171718;+ --sidebar: #111112;+ --surface: #1e1e20;+ --raised: #252527;+ /* Form fields sit slightly above the surface they're on, so they read as places to type. */+ --field: #ffffff08;+ --field-hover: #ffffff0d;+ --hover: #242426;+ --selected: #2a2a2c;+ --accent: #aaa6ec;+ --accent-solid: #6d67cb;+ --accent-tint: #aaa6ec12;+ --text: #dedee1;+ --text-strong: #f2f2f3;+ --secondary: #b7b7bd;+ --muted: #96969e;+ --faint: #77777f;+ --border: #ffffff0b;+ --border-strong: #ffffff1a;+ --green: #76bc9a;+ --red: #ea9198;+ --star: #d4b36e;+ --skeleton: #ffffff0d;+ --shadow: 0 24px 80px #0005, 0 4px 16px #0003;+ font-family:+ Inter,+ -apple-system,+ BlinkMacSystemFont,+ 'Segoe UI',+ sans-serif;+ font-synthesis: none;+ text-rendering: optimizeLegibility;+ font-size: 14px;+ line-height: 1.5;+ font-weight: 400;+ -webkit-font-smoothing: antialiased;+}+:root[data-theme='light'] {+ color-scheme: light;+ --bg: #fcfcfd;+ --sidebar: #f7f8fa;+ --surface: #ffffff;+ --raised: #ffffff;+ --field: #ffffff;+ --field-hover: #fbfbfc;+ --hover: #eff0f2;+ --selected: #e8e9ec;+ --accent: #635db5;+ --accent-solid: #6962c1;+ --accent-tint: #6962c10c;+ --text: #383a40;+ --text-strong: #202127;+ --secondary: #5d6068;+ --muted: #70737d;+ --faint: #838691;+ --border: #17191f0b;+ --border-strong: #17191f1d;+ --green: #3d9066;+ --red: #b94d55;+ --star: #b8892c;+ --skeleton: #17191f0e;+ --shadow: 0 18px 70px #10121a1a;+}+* {+ box-sizing: border-box;+}+body {+ margin: 0;+ overflow: hidden;+ background: var(--bg);+ color: var(--text);+}+button,+input,+textarea {+ font: inherit;+}+button {+ cursor: pointer;+ color: inherit;+}+button:disabled {+ cursor: default;+ opacity: 0.4;+}+button,+a,+input,+textarea,+[tabindex] {+ outline: none;+}+:focus-visible {+ outline: 2px solid var(--accent);+ outline-offset: 3px;+ border-radius: 5px;+}+::selection {+ background: color-mix(in srgb, var(--accent) 28%, transparent);+}+input,+textarea {+ color: var(--text);+ background: var(--field);+ border: 1px solid var(--border-strong);+ border-radius: 6px;+ padding: 9px 11px;+ width: 100%;+}+input::placeholder,+textarea::placeholder {+ color: var(--muted);+}+input:focus,+textarea:focus {+ border-color: var(--accent-solid);+}+label {+ display: block;+ font-size: 12px;+ color: var(--secondary);+}+a {+ color: var(--accent);+ text-decoration: none;+}+button svg {+ flex-shrink: 0;+}+svg {+ vertical-align: middle;+}+::-webkit-scrollbar {+ width: 6px;+ height: 6px;+}+/* The transparent border keeps the grab area at 6px while the thumb looks 4px wide. */+::-webkit-scrollbar-thumb {+ background: var(--border-strong);+ background-clip: padding-box;+ border: 1px solid transparent;+ border-radius: 20px;+}+::-webkit-scrollbar-thumb:hover {+ background-color: var(--faint);+}+::-webkit-scrollbar-thumb:active {+ background-color: var(--muted);+}+::-webkit-scrollbar-corner {+ background: transparent;+}+::-webkit-scrollbar-track {+ background: transparent;+}+.button {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ gap: 7px;+ border: 1px solid var(--border-strong);+ background: var(--surface);+ border-radius: 6px;+ padding: 6px 11px;+ font-size: 12px;+ font-weight: 500;+ white-space: nowrap;+ transition:+ background 0.12s,+ color 0.12s;+ min-height: 32px;+}+.button:hover:not(:disabled) {+ background: var(--hover);+ border-color: color-mix(in srgb, var(--text) 24%, transparent);+}+.button-primary {+ background: var(--accent-solid);+ border-color: transparent;+ color: #fff;+ box-shadow: inset 0 1px #ffffff12;+}+.button-primary:hover:not(:disabled) {+ background: color-mix(in srgb, var(--accent-solid) 85%, white);+ border-color: transparent;+}+.button-ghost {+ background: transparent;+ border-color: transparent;+ color: var(--secondary);+}+.button-ghost:hover:not(:disabled) {+ border-color: transparent;+ color: var(--text-strong);+}+.button-danger {+ color: var(--red);+}+.button-icon {+ padding: 5px;+ width: 29px;+ height: 29px;+ min-height: 29px;+}+.button-small {+ min-height: 26px;+ padding: 3px 8px;+ font-size: 11px;+}+.tooltip {+ display: flex;+ gap: 12px;+ align-items: center;+ padding: 6px 9px;+ background: var(--raised);+ border: 1px solid var(--border-strong);+ border-radius: 6px;+ font-size: 11px;+ box-shadow: var(--shadow);+ z-index: 200;+}+kbd {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ min-width: 17px;+ height: 18px;+ padding: 0 4px;+ font-family: inherit;+ font-size: 10px;+ line-height: 1;+ color: var(--muted);+ border: 1px solid var(--border-strong);+ border-radius: 4px;+}+.modal-backdrop {+ position: fixed;+ inset: 0;+ background: #0505079c;+ backdrop-filter: blur(5px);+ transition: opacity 160ms ease;+ z-index: 100;+}+.modal {+ position: fixed;+ top: 50%;+ left: 50%;+ transform: translate(-50%, -50%);+ width: min(560px, calc(100vw - 40px));+ max-height: calc(100vh - 70px);+ overflow-y: auto;+ background: var(--surface);+ border: 1px solid var(--border-strong);+ border-radius: 12px;+ box-shadow: var(--shadow);+ padding: 23px;+ z-index: 101;+ max-width: calc(100vw - 40px);+ transition:+ opacity 160ms ease,+ transform 160ms ease;+}+.modal-heading {+ display: flex;+ align-items: flex-start;+ justify-content: space-between;+ gap: 15px;+ margin-bottom: 22px;+}+.modal-title {+ font-size: 16px;+ font-weight: 550;+ margin: 0;+ letter-spacing: -0.3px;+}+.modal-description {+ font-size: 12px;+ line-height: 1.6;+ color: var(--secondary);+ margin: 5px 0 0;+}+.dropdown {+ min-width: 180px;+ background: var(--raised);+ border: 1px solid var(--border-strong);+ border-radius: 8px;+ box-shadow: var(--shadow);+ padding: 5px;+ z-index: 120;+ transform-origin: var(--transform-origin);+ transition:+ opacity 100ms ease,+ transform 100ms ease;+}+.menu-item {+ display: flex;+ align-items: center;+ gap: 9px;+ font-size: 12px;+ padding: 7px 10px;+ border-radius: 4px;+ outline: none;+ cursor: pointer;+}+.menu-item[data-highlighted] {+ background: var(--hover);+ color: var(--text-strong);+}+.menu-item[data-disabled] {+ opacity: 0.4;+}+.menu-item.danger {+ color: var(--red);+}+/* ——— Form controls (Base UI) ——— */+.select-trigger {+ display: flex;+ align-items: center;+ gap: 8px;+ width: 100%;+ min-width: 0;+ height: 36px;+ padding: 0 10px 0 11px;+ color: var(--text);+ background: var(--field);+ border: 1px solid var(--border-strong);+ border-radius: 6px;+ font-size: 12px;+ text-align: left;+ transition:+ border-color 120ms,+ background 120ms;+}+.select-trigger:hover:not([data-disabled]) {+ background: var(--field-hover);+}+.select-trigger[data-popup-open],+.select-trigger:focus-visible {+ border-color: var(--accent-solid);+ outline: none;+}+.select-trigger[data-disabled] {+ opacity: 0.5;+ cursor: default;+}+.select-value {+ flex: 1;+ min-width: 0;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.select-value.placeholder {+ color: var(--muted);+}+.select-icon {+ display: flex;+ color: var(--muted);+}+.select-positioner,+.date-positioner {+ z-index: 120;+}+.select-popup {+ min-width: var(--anchor-width);+ max-height: min(320px, var(--available-height));+ overflow-y: auto;+}+.select-item {+ justify-content: space-between;+}+.select-item-indicator {+ display: flex;+ color: var(--accent);+}+.checkbox {+ display: inline-grid;+ place-content: center;+ flex-shrink: 0;+ width: 15px;+ height: 15px;+ border: 1px solid var(--faint);+ border-radius: 4px;+ background: transparent;+ color: #fff;+ cursor: pointer;+ transition:+ background 100ms,+ border-color 100ms;+}+.checkbox:hover:not([data-disabled]) {+ border-color: var(--muted);+}+.checkbox[data-checked],+.checkbox[data-indeterminate] {+ background: var(--accent-solid);+ border-color: var(--accent-solid);+}+.checkbox[data-disabled] {+ opacity: 0.4;+ cursor: default;+}+.checkbox-indicator {+ display: flex;+}+.checkbox-indicator[data-unchecked] {+ display: none;+}+.switch {+ position: relative;+ display: inline-flex;+ flex-shrink: 0;+ width: 30px;+ height: 18px;+ padding: 2px;+ border-radius: 20px;+ background: var(--hover);+ box-shadow: inset 0 0 0 1px var(--border-strong);+ cursor: pointer;+ transition: background 120ms;+}+.switch[data-checked] {+ background: var(--accent-solid);+ box-shadow: none;+}+.switch[data-disabled] {+ opacity: 0.4;+ cursor: default;+}+.switch-thumb {+ width: 14px;+ height: 14px;+ border-radius: 50%;+ background: var(--muted);+ transition:+ transform 140ms ease,+ background 120ms;+}+.switch[data-checked] .switch-thumb {+ background: #fff;+ transform: translateX(12px);+}+.date-picker {+ position: relative;+}+.date-trigger-icon {+ color: var(--muted);+}+.date-picker:has(.date-clear) .date-trigger {+ padding-right: 32px;+}+.date-clear {+ position: absolute;+ top: 50%;+ right: 7px;+ transform: translateY(-50%);+ display: grid;+ place-content: center;+ width: 22px;+ height: 22px;+ padding: 0;+ border: 0;+ border-radius: 5px;+ background: none;+ color: var(--muted);+}+.date-clear:hover {+ background: var(--hover);+ color: var(--text);+}+.date-popup {+ min-width: 0;+ padding: 12px;+}+.calendar {+ position: relative;+ font-size: 12px;+}+.calendar-caption {+ display: flex;+ align-items: center;+ height: 28px;+ padding: 0 4px;+}+.calendar-caption-label {+ font-weight: 500;+ color: var(--text-strong);+}+.calendar-nav {+ position: absolute;+ top: 0;+ right: 0;+ display: flex;+ gap: 2px;+}+.calendar-nav-button {+ width: 28px;+ height: 28px;+ min-height: 28px;+ padding: 0;+ color: var(--muted);+}+.calendar-grid {+ border-collapse: collapse;+ margin-top: 6px;+}+.calendar-weekday {+ width: 34px;+ height: 28px;+ font-size: 11px;+ font-weight: 400;+ color: var(--faint);+}+.calendar-day {+ padding: 1px;+ text-align: center;+}+.calendar-day-button {+ width: 32px;+ height: 32px;+ padding: 0;+ border: 0;+ border-radius: 6px;+ background: none;+ color: var(--text);+ font-variant-numeric: tabular-nums;+ transition: background 100ms;+}+.calendar-day-button:hover {+ background: var(--hover);+}+.calendar-day.today .calendar-day-button {+ color: var(--accent);+ font-weight: 600;+}+.calendar-day.outside .calendar-day-button {+ color: var(--faint);+}+.calendar-day.selected .calendar-day-button {+ background: var(--accent-solid);+ color: #fff;+ font-weight: 500;+}+.calendar-day.disabled .calendar-day-button {+ opacity: 0.4;+}+.calendar-day.hidden {+ visibility: hidden;+}+.avatar {+ display: inline-flex;+ flex-shrink: 0;+ align-items: center;+ justify-content: center;+ border-radius: 8px;+ background: color-mix(in srgb, var(--avatar-color) 12%, transparent);+ color: var(--avatar-color);+ font-weight: 600;+ letter-spacing: -0.4px;+ overflow: hidden;+}+.avatar img {+ display: block;+ width: 100%;+ height: 100%;+ object-fit: cover;+}+.spin {+ animation: spin 1s linear infinite;+}+@keyframes spin {+ to {+ transform: rotate(360deg);+ }+}+.empty-state {+ flex: 1;+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ /* Sit slightly above the true centre, where the eye expects it. */+ padding: 48px 32px 12vh;+ text-align: center;+}+/* A soft halo instead of a boxed tile keeps the icon quiet but present. */+.empty-icon {+ display: grid;+ place-items: center;+ width: 64px;+ height: 64px;+ margin-bottom: 14px;+ border-radius: 50%;+ color: var(--muted);+ background: radial-gradient(+ circle,+ color-mix(in srgb, var(--accent) 12%, transparent) 0,+ transparent 70%+ );+}+.empty-state h2 {+ font-size: 15px;+ font-weight: 550;+ color: var(--text-strong);+ margin: 0 0 6px;+ letter-spacing: -0.2px;+}+/* Without a description, give the title the same room above a spinner or button. */+.empty-state h2 + :not(p) {+ margin-top: 14px;+}+.empty-state p {+ font-size: 13px;+ color: var(--muted);+ max-width: 300px;+ margin: 0 0 20px;+ line-height: 1.6;+ text-wrap: balance;+}+.empty-state > .button {+ margin-top: 2px;+}+.empty-hint {+ display: inline-flex;+ align-items: center;+ gap: 8px;+ font-size: 12px;+ color: var(--faint);+}+.modal-backdrop[data-starting-style],+.modal-backdrop[data-ending-style] {+ opacity: 0;+}+.modal[data-starting-style],+.modal[data-ending-style] {+ opacity: 0;+ transform: translate(-50%, -48%) scale(0.98);+}+.dropdown[data-starting-style],+.dropdown[data-ending-style] {+ opacity: 0;+ transform: scale(0.98);+}+button:active:not(:disabled) {+ transition-duration: 60ms;+}+@media (prefers-reduced-motion: reduce) {+ *,+ *::before,+ *::after {+ animation-duration: 0.01ms !important;+ transition-duration: 0.01ms !important;+ scroll-behavior: auto !important;+ }+}diff --git a/packages/ui/tsconfig.json b/packages/ui/tsconfig.jsonnew file mode 100644index 0000000..f46ada1--- /dev/null+++ b/packages/ui/tsconfig.json@@ -0,0 +1 @@+{ "extends": "../../tsconfig.json", "include": ["src"] }diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlnew file mode 100644index 0000000..3a6dfdc--- /dev/null+++ b/pnpm-lock.yaml@@ -0,0 +1,5763 @@+---+lockfileVersion: '9.0'++importers:++ .:+ configDependencies: {}+ packageManagerDependencies:+ pnpm:+ specifier: 12.3.4+ version: 12.3.4++packages:++ '@pnpm/[email protected]':+ resolution: {integrity: sha512-PAyUol8T1+/+ViOiXAt51ECA+QnfXCqz6foL4bW+LsoX0NcVd5XVEM2mRQu+LV4oc7uRz9zf9U0P+XFfuQeDAw==}+ cpu: [arm64]+ os: [darwin]++ '@pnpm/[email protected]':+ resolution: {integrity: sha512-fxP9JCk0Cdye+ePuj+GJJLMUMTqHGWRdb1dtv4How876uQ2ehxvenpgiYAir/ceO9PsYUZkFTtyZdx+rRu5QOA==}+ cpu: [x64]+ os: [darwin]++ '@pnpm/[email protected]':+ resolution: {integrity: sha512-FBOt0/7ye6O6q4AllVV5QMviB6qE6fqkeczV/+MDWQsmo+QJrlfsh6X7CpH/tClVpBZEyIbjpUoT8bNhCYBxEg==}+ cpu: [arm64]+ os: [linux]+ libc: [musl]++ '@pnpm/[email protected]':+ resolution: {integrity: sha512-t71AVA7LRqiKTyZ5xMYaZc2n5DfdpMbfokZuiIOXHBOM03ECnF0t4iYwaBDqJgVjlKYUOwaF/bRQajGNA4cJ4w==}+ cpu: [arm64]+ os: [linux]+ libc: [glibc]++ '@pnpm/[email protected]':+ resolution: {integrity: sha512-RPmk7Jb/aYaFvL2iyDN/AtMY+hUEsue732WmXpcuQ9tBpMnGyA5py7Z3+e+qmQaJ0zY/4ni9jJiyPBQHujmv6w==}+ cpu: [x64]+ os: [linux]+ libc: [musl]++ '@pnpm/[email protected]':+ resolution: {integrity: sha512-2ZqOlSPkfwX1h5cR+FPiWf8+F+2hZT/3TvhUK5sigHqwaQCIiq8R7CGxhndKs63JtcLi2a1Qpo+wX/EoyfjyJQ==}+ cpu: [x64]+ os: [linux]+ libc: [glibc]++ '@pnpm/[email protected]':+ resolution: {integrity: sha512-ANyrHqyqco6SXBysUTRF74itDyyraea7IbFsKFdNXTjcFnfycTDx37EwuhdpPYFNSIh2JhUG4fByclsRfiHX7w==}+ cpu: [arm64]+ os: [win32]++ '@pnpm/[email protected]':+ resolution: {integrity: sha512-WH/KqBPY/hq2Tb7SgQltEZytimcjgKRaCRL/aM9CI0c67iKc5TVmHUhIiL3Ux9FB4bWn36i6XewUcScQI+zG8w==}+ cpu: [x64]+ os: [win32]++ resolution: {integrity: sha512-lhqkH7B32joEpEHZ+OFevAyW2o73ELLrZ7+e58sGEOq9SPH9hfUc/+c4RnhfoPh8VqOocqHYk/hEZ0G1zORUVw==}+ engines: {node: '>=18.*'}+ hasBin: true++snapshots:++ '@pnpm/[email protected]':+ optional: true++ '@pnpm/[email protected]':+ optional: true++ '@pnpm/[email protected]':+ optional: true++ '@pnpm/[email protected]':+ optional: true++ '@pnpm/[email protected]':+ optional: true++ '@pnpm/[email protected]':+ optional: true++ '@pnpm/[email protected]':+ optional: true++ '@pnpm/[email protected]':+ optional: true++ optionalDependencies:+ '@pnpm/exe.darwin-arm64': 12.3.4+ '@pnpm/exe.darwin-x64': 12.3.4+ '@pnpm/exe.linux-arm64': 12.3.4+ '@pnpm/exe.linux-arm64-musl': 12.3.4+ '@pnpm/exe.linux-x64': 12.3.4+ '@pnpm/exe.linux-x64-musl': 12.3.4+ '@pnpm/exe.win32-arm64': 12.3.4+ '@pnpm/exe.win32-x64': 12.3.4++---+lockfileVersion: '9.0'++settings:+ autoInstallPeers: true+ excludeLinksFromLockfile: false++importers:++ .:+ devDependencies:+ '@types/node':+ specifier: ^24.0.0+ version: 24.13.6+ '@types/smtp-server':+ specifier: ^3.5.13+ version: 3.5.13+ prettier:+ specifier: ^3.9.8+ version: 3.9.8+ smtp-server:+ specifier: ^3.19.13+ version: 3.19.13+ turbo:+ specifier: ^2.5.0+ version: 2.11.2+ typescript:+ specifier: ^5.9.0+ version: 5.9.3+ vitest:+ specifier: ^3.2.0+ version: 3.2.7(@types/[email protected])(@types/[email protected])([email protected])([email protected])([email protected])++ apps/desktop:+ dependencies:+ '@base-ui/react':+ specifier: ^1.8.0+ version: 1.8.0(@date-fns/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected])+ '@inlark/core':+ specifier: workspace:*+ version: link:../../packages/core+ '@inlark/imap':+ specifier: workspace:*+ version: link:../../packages/imap+ '@inlark/jmap':+ specifier: workspace:*+ version: link:../../packages/jmap+ '@inlark/ui':+ specifier: workspace:*+ version: link:../../packages/ui+ '@tanstack/react-form':+ specifier: ^1.0.0+ '@tanstack/react-hotkeys':+ specifier: ^0.11.0+ '@tanstack/react-query':+ specifier: ^5.80.0+ version: 5.103.2([email protected])+ '@tanstack/react-router':+ specifier: ^1.120.0+ '@tanstack/react-virtual':+ specifier: ^3.13.0+ '@tiptap/extension-image':+ specifier: ^3.0.0+ version: 3.31.3(@tiptap/[email protected](@tiptap/[email protected]))+ '@tiptap/extension-placeholder':+ specifier: ^3.0.0+ version: 3.31.3(@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected]))+ '@tiptap/react':+ specifier: ^3.0.0+ version: 3.31.3(@floating-ui/[email protected])(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])+ '@tiptap/starter-kit':+ specifier: ^3.0.0+ version: 3.31.3+ boring-avatars:+ specifier: ^2.0.4+ dompurify:+ specifier: ^3.2.0+ version: 3.4.15+ idb:+ specifier: ^8.0.0+ version: 8.0.3+ react:+ specifier: ^19.0.0+ version: 19.3.0+ react-dom:+ specifier: ^19.0.0+ version: 19.3.0([email protected])+ zod:+ specifier: ^4.0.0+ version: 4.6.5+ devDependencies:+ '@tailwindcss/vite':+ specifier: ^4.1.0+ '@types/react':+ specifier: ^19.0.0+ version: 19.3.0+ '@types/react-dom':+ specifier: ^19.0.0+ version: 19.3.0(@types/[email protected])+ '@vitejs/plugin-react':+ specifier: ^5.0.0+ version: 5.2.0([email protected])([email protected](@types/[email protected])([email protected])([email protected]))+ electron:+ specifier: ^44.4.5+ version: 44.4.5([email protected])+ electron-builder:+ specifier: ^26.0.0+ version: 26.15.3([email protected])([email protected])+ electron-vite:+ specifier: ^5.0.0+ version: 5.0.0([email protected])([email protected](@types/[email protected])([email protected])([email protected]))+ tailwindcss:+ specifier: ^4.1.0+ version: 4.3.3+ vite:+ specifier: ^7.0.0++ packages/core:+ dependencies:+ zod:+ specifier: ^4.0.0+ version: 4.6.5++ packages/imap:+ dependencies:+ '@inlark/core':+ specifier: workspace:*+ version: link:../core+ imapflow:+ specifier: ^2.0.6+ version: 2.0.6+ mailparser:+ specifier: ^3.9.28+ version: 3.9.28+ nodemailer:+ specifier: ^10.0.10+ version: 10.0.10+ devDependencies:+ '@types/mailparser':+ specifier: ^3.4.6+ version: 3.4.6+ '@types/nodemailer':+ specifier: ^8.0.2+ version: 8.0.2++ packages/jmap:+ dependencies:+ '@inlark/core':+ specifier: workspace:*+ version: link:../core++ packages/ui:+ dependencies:+ '@base-ui/react':+ specifier: ^1.8.0+ version: 1.8.0(@date-fns/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected])+ '@hugeicons/core-free-icons':+ specifier: ^4.3.5+ version: 4.3.5+ '@hugeicons/react':+ specifier: ^1.1.10+ version: 1.1.10([email protected])+ clsx:+ specifier: ^2.1.1+ version: 2.1.1+ react:+ specifier: ^19.0.0+ version: 19.3.0+ react-day-picker:+ specifier: ^9.14.0+ version: 9.14.0([email protected])+ react-dom:+ specifier: ^19.0.0+ version: 19.3.0([email protected])+ tailwind-merge:+ specifier: ^3.0.0+ version: 3.7.0+ devDependencies:+ '@types/react':+ specifier: ^19.0.0+ version: 19.3.0+ '@types/react-dom':+ specifier: ^19.0.0+ version: 19.3.0(@types/[email protected])++packages:++ '@babel/[email protected]':+ resolution: {integrity: sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==}+ engines: {node: '>=6.9.0'}++ '@babel/[email protected]':+ resolution: {integrity: sha512-locTkQyKvwIEgBzVrn8693ebc97F2U8ZHjbXwDXJ5Fn2TCpNwTlKcaKLkdHop5c/icOFE7qt7Q9JC5hnKNa6Gg==}+ engines: {node: '>=6.9.0'}++ '@babel/[email protected]':+ resolution: {integrity: sha512-RgHBCvtjbOK2gXSNBNIkNoEc9qoVEtau3hj8gEqKQuL3HZAibKarWFEI3Lfm6EYKkLalOh8eSrj9b+ch9H/VBA==}+ engines: {node: '>=6.9.0'}++ '@babel/[email protected]':+ resolution: {integrity: sha512-gZbepsdh3WDtgZKWL+vTPh71LSBrm/Y4/QDZBVCcYfmeTEEuoOYwlSy+G1StfJg+/Zy550u/3TATbm7qDbbMtg==}+ engines: {node: '>=6.9.0'}++ '@babel/[email protected]':+ resolution: {integrity: sha512-wem6WaBj4NaVYVdNhLPPVacES6ZJ+KBBfSkTMD3YZxbP3rm3Di85tJU5ljaUNhaOynt+Aj0xruhYuzQBt8n71g==}+ engines: {node: '>=6.9.0'}++ '@babel/[email protected]':+ resolution: {integrity: sha512-3nQVUAtvkKH9zahfWgw96Jc/uFOmjACE1kQz82E2lqWmHBgjzbNlsC22nuQTfahmWeQtTq5nQ/4Nnd2A1wj4zA==}+ engines: {node: '>=6.9.0'}++ '@babel/[email protected]':+ resolution: {integrity: sha512-ejHwrQQYcm9xnTivShn2IDOlIzInN34AXskvq9QicvCtEzq1Vzclu/tKF8Jq1Cg8JG2GL6/EmjgsCT7lXepE3g==}+ engines: {node: '>=6.9.0'}++ '@babel/[email protected]':+ resolution: {integrity: sha512-UPUVSyXbOh627KiCIGQSgwWzGeBKLkaJ9PJEdrngIwMSzxLR4jS4+f1f1jb7VzBbg8nFLaYotvVPFCTqdrmTAg==}+ engines: {node: '>=6.9.0'}+ peerDependencies:+ '@babel/core': ^7.0.0++ '@babel/[email protected]':+ resolution: {integrity: sha512-G7sHYigPY17oO5SYWnfD/0MTBwVR781S/JI643e/JhUYgVgWE/61SoW3NH9KWUKyKq5LVh3npif99Wkt6j86Jw==}+ engines: {node: '>=6.9.0'}++ '@babel/[email protected]':+ resolution: {integrity: sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw==}+ engines: {node: '>=6.9.0'}++ '@babel/[email protected]':+ resolution: {integrity: sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==}+ engines: {node: '>=6.9.0'}++ '@babel/[email protected]':+ resolution: {integrity: sha512-N9ZErrD+yW5geCDtBqnOoxmR8+tNKiGuxKlDpuJxfsqpa2dFcexaziGAE/qoHLiDDreVNMupxGmSoNlyvsA3gw==}+ engines: {node: '>=6.9.0'}++ '@babel/[email protected]':+ resolution: {integrity: sha512-1k2lAGRMfHTcwuNYcCNUmaUffmQv8KWMfh2iJUUeRlwlwH4FdNG7mfPI10NPfLHJFThE4Tyr4mv7kTNZOiPuBg==}+ engines: {node: '>=6.9.0'}++ '@babel/[email protected]':+ resolution: {integrity: sha512-CjXrNHTnvqBVqHgdBysY3vk2T8tpJHb5/RMeHJBTyVa9xgugCB0CJTx/3oO8RV2QRQP391RWpB7D6hLjm8V9uA==}+ engines: {node: '>=6.0.0'}+ hasBin: true++ '@babel/[email protected]':+ resolution: {integrity: sha512-N7zArUXWzAMzm+/N0uPBeVB3Fam5lMxtUwMmDK5f/IBBS7a7p1qeUoxd/6CckXoxUdgsntq1Dh8xNW06maZbDQ==}+ engines: {node: '>=6.9.0'}+ peerDependencies:+ '@babel/core': ^7.0.0-0++ '@babel/[email protected]':+ resolution: {integrity: sha512-TL0hMc9xzy86VD31nUiwzd5otRAcyEPcsegCxolO0PvcXuH1v0kECe/UIznYFihpkvU5wg/jk4v0TTEFfm53fw==}+ engines: {node: '>=6.9.0'}+ peerDependencies:+ '@babel/core': ^7.0.0-0++ '@babel/[email protected]':+ resolution: {integrity: sha512-06IyK09H3wi4cGbhDBwp5gUGo0IKtnYa8tyTiephirPCK6fbobVGiXMMI5zLQ4aKEYP3wZ3ArU44o+8KMrSG/Q==}+ engines: {node: '>=6.9.0'}+ peerDependencies:+ '@babel/core': ^7.0.0-0++ '@babel/[email protected]':+ resolution: {integrity: sha512-Nq8OhGWiZIZGV6hLHoyAKLLcJihP/xFeBMGJoUrxTX2psI8dCifzLhZISFb+VWS3wFMRDmCGw5R+dOySCqPLhw==}+ engines: {node: '>=6.9.0'}++ '@babel/[email protected]':+ resolution: {integrity: sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg==}+ engines: {node: '>=6.9.0'}++ '@babel/[email protected]':+ resolution: {integrity: sha512-I5z7H3bf/41ktsNVLtpN0wAa336HkqIHQ5BuPLEhTkt1jVSyZpeNKIzTgEWmlxjdg81R0IgUCcaE+Ok3NvrfZg==}+ engines: {node: '>=6.9.0'}++ '@babel/[email protected]':+ resolution: {integrity: sha512-Vj1jF3cPfxg7OAfoI7QnVKLoILlm2JF9pnVHrX8qx7AHMiYWT+NDAA7jChlNgRS4WTLc/fD1lXLmPixluj+3Gg==}+ engines: {node: '>=6.9.0'}++ '@base-ui/[email protected]':+ resolution: {integrity: sha512-P0/1sxo6SBVZOklKMIedvTWqw2s2IQzi9x5bIVsXu980cuSOD4NeuRSs+/L7LZQfDkZP/uRZyGPyfFl/B1oH+Q==}+ engines: {node: '>=14.0.0'}+ peerDependencies:+ '@date-fns/tz': ^1.2.0+ '@types/react': ^17 || ^18 || ^19+ date-fns: ^4.0.0+ react: ^17 || ^18 || ^19+ react-dom: ^17 || ^18 || ^19+ peerDependenciesMeta:+ '@date-fns/tz':+ optional: true+ '@types/react':+ optional: true+ date-fns:+ optional: true++ '@base-ui/[email protected]':+ resolution: {integrity: sha512-bO9fz25kKtPf+aZVyfQrC0PDmJdmVni31W2hCS5/Owb+inwdIL3XU26pCPRPlt4LSxZrBgLwubXQXQlKaFEZzw==}+ peerDependencies:+ '@types/react': ^17 || ^18 || ^19+ react: ^17 || ^18 || ^19+ react-dom: ^17 || ^18 || ^19+ peerDependenciesMeta:+ '@types/react':+ optional: true++ '@date-fns/[email protected]':+ resolution: {integrity: sha512-lwYN/vDPeNRULcepoE/LO2Pgx+7/RV+S9ARfbc9lr2DtGkOD7pAiruHvbR1RX3Qyf6ja47EWJDMsNK5vK08DJg==}++ '@electron-internal/[email protected]':+ resolution: {integrity: sha512-+bqFCP98pLI0Tt0XQo1TmlXtwjWchISndDOxCkEcIuUgXWpBnLyRI+2DU+mesvnMMX6L1XDqYNA0lXNDHd/yiA==}+ engines: {node: '>=22.12.0'}++ '@electron/[email protected]':+ resolution: {integrity: sha512-i4/rNPRS84t0vSRa2HorerGRXWyF4vThfHesw0dmcWHp+cspK743UanA0suA5Q5y8kzY2y6YKrvbIUn69BCAiA==}+ engines: {node: '>=10.12.0'}+ hasBin: true++ '@electron/[email protected]':+ resolution: {integrity: sha512-zx0EIq78WlY/lBb1uXlziZmDZI4ubcCXIMJ4uGjXzZW0nS19TjSPeXPAjzzTmKQlJUZm0SbmZhPKP7tuQ1SsEw==}+ hasBin: true++ '@electron/[email protected]':+ resolution: {integrity: sha512-F+nKc0xW+kVbBRhFzaMgPy3KwmuNTYX1fx6+FxxoSnNgwYX6LD7AKBTWkU0MQ6IBoe7dz069CNkR673sPAgkCQ==}+ engines: {node: '>=14'}++ '@electron/[email protected]':+ resolution: {integrity: sha512-3kSBtG8ObcTVfXanm5vVJ6UnBLEVmVsRk1M+vGqCuMBV+XLCbJYuWQful+yIy0GQDsSlK0kHEriEHn7SPk4EnA==}+ engines: {node: '>=22.12.0'}++ '@electron/[email protected]':+ resolution: {integrity: sha512-jNT8nwH1f9X5GEITXaQ8IF/KdskvIkOFfB2CvwumsveVidzpSc+mvhhTMdAGSYF3O+Nq49lJ7y+ssODRXu06+A==}+ engines: {node: '>= 10.0.0'}++ '@electron/[email protected]':+ resolution: {integrity: sha512-KZ8mhXvWv2rIEgMbWZ4y33bDHyUKMXnx4M0sTyPNK/vcB81ImdeY9Ggdqy0SWbMDgmbqyQ+phgejh6V3R2QuSg==}+ engines: {node: '>=12.0.0'}+ hasBin: true++ '@electron/[email protected]':+ resolution: {integrity: sha512-RKL/O+jGoXJMxrx/5771y1n0xTKmFuOYGO3gMmwypBM6rsH0kou0mswwdXA2JrhIkE4xyC7v9vGk0n6NPzgOxQ==}+ engines: {node: '>=22.12.0'}+ hasBin: true++ '@electron/[email protected]':+ resolution: {integrity: sha512-Wn9sPYIVFRFl5HmwMJkARCCf7rqK/EurkfQ/rJZ14mHP3iYTjZSIOSVonEAnhWeAXwtw7zOekGRlc6yTtZ0t+g==}+ engines: {node: '>=16.4'}++ '@electron/[email protected]':+ resolution: {integrity: sha512-dfZeox66AvdPtb2lD8OsIIQh12Tp0GNCRUDfBHIKGpbmopZto2/A8nSpYYLoedPIHpqkeblZ/k8OV0Gy7PYuyQ==}+ engines: {node: '>=14.14'}+ hasBin: true++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==}+ engines: {node: '>=18'}+ cpu: [ppc64]+ os: [aix]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==}+ engines: {node: '>=18'}+ cpu: [ppc64]+ os: [aix]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [android]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [android]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==}+ engines: {node: '>=18'}+ cpu: [arm]+ os: [android]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==}+ engines: {node: '>=18'}+ cpu: [arm]+ os: [android]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [android]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [android]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [darwin]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [darwin]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [darwin]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [darwin]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [freebsd]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [freebsd]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [freebsd]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [freebsd]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==}+ engines: {node: '>=18'}+ cpu: [arm]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==}+ engines: {node: '>=18'}+ cpu: [arm]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==}+ engines: {node: '>=18'}+ cpu: [ia32]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==}+ engines: {node: '>=18'}+ cpu: [ia32]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==}+ engines: {node: '>=18'}+ cpu: [loong64]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==}+ engines: {node: '>=18'}+ cpu: [loong64]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==}+ engines: {node: '>=18'}+ cpu: [mips64el]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==}+ engines: {node: '>=18'}+ cpu: [mips64el]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==}+ engines: {node: '>=18'}+ cpu: [ppc64]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==}+ engines: {node: '>=18'}+ cpu: [ppc64]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==}+ engines: {node: '>=18'}+ cpu: [riscv64]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==}+ engines: {node: '>=18'}+ cpu: [riscv64]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==}+ engines: {node: '>=18'}+ cpu: [s390x]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==}+ engines: {node: '>=18'}+ cpu: [s390x]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [netbsd]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [netbsd]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [netbsd]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [netbsd]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [openbsd]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [openbsd]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [openbsd]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [openbsd]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [openharmony]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [openharmony]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [sunos]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [sunos]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [win32]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [win32]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==}+ engines: {node: '>=18'}+ cpu: [ia32]+ os: [win32]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==}+ engines: {node: '>=18'}+ cpu: [ia32]+ os: [win32]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [win32]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [win32]++ '@floating-ui/[email protected]':+ resolution: {integrity: sha512-0CIZ5itps/8x7BG8dEIhs53BvCUH2PCoogtakwRTut+Arm58sJooJ0AuZhLw2HJYIR5cMLNPBSS728sPho2khQ==}++ '@floating-ui/[email protected]':+ resolution: {integrity: sha512-yXSrzeHZBTZadLOlfyhCkJHNeLJnHRnRInwdZ40L7ZiaAtrBwoYlsDrX3v5zB1Utk7CLfzcOVnVVWoXEky7Ceg==}++ '@floating-ui/[email protected]':+ resolution: {integrity: sha512-JDjEFGCpImxDCA7JJKviA0M9+RtmJdj0m/NVU5IMgBK+AmZouAQQ7/+2GLH0GXXY0YMw9oXPB8hKdbPYg5QLYg==}+ peerDependencies:+ react: '>=16.8.0'+ react-dom: '>=16.8.0'++ '@floating-ui/[email protected]':+ resolution: {integrity: sha512-HpCo8tmWzLVad5s2d19EhAz5zqrrQ6s69qd6moPMQvkOuSwDT1YgRfWSVuc4ennqrgv3OHppiOGMQ7oC13yIww==}++ '@hugeicons/[email protected]':+ resolution: {integrity: sha512-Sv+NjHRPnQk+yZsGCMcGznCHdTfJR9PMMOEKcJYAQU4gy90dmlc9PwdtvYOImBZIjiheMsTLL5eMn2DmHxUiUg==}++ '@hugeicons/[email protected]':+ resolution: {integrity: sha512-9tAsd92yMVVGP+E+d8cM+wc0VnXuYZHNbWQi7TOe8k2neawmhiaFmVFbzyruejhOMa197/LbgvSED32ayUo3ZA==}+ peerDependencies:+ react: '>=16.0.0'++ '@isaacs/[email protected]':+ resolution: {integrity: sha512-wgm9Ehl2jpeqP3zw/7mo3kRHFp5MEDhqAdwy1fTGkHAwnkGOVsgpvQhL8B5n1qlb01jV3n/bI0ZfZp5lWA1k4w==}+ engines: {node: '>=18.0.0'}++ '@jridgewell/[email protected]':+ resolution: {integrity: sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==}++ '@jridgewell/[email protected]':+ resolution: {integrity: sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==}++ '@jridgewell/[email protected]':+ resolution: {integrity: sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==}+ engines: {node: '>=6.0.0'}++ '@jridgewell/[email protected]':+ resolution: {integrity: sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==}++ '@jridgewell/[email protected]':+ resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==}++ '@malept/[email protected]':+ resolution: {integrity: sha512-1DpKU0Z5ThltBwjNySMC14g0CkbyhCaz9FkhxqNsZI6uAPJXFS8cMXlBKo26FJ8ZuW6S9GCMcR9IO5k2X5/9Fg==}+ engines: {node: '>= 12.13.0'}++ '@malept/[email protected]':+ resolution: {integrity: sha512-9QOtNffcOF/c1seMCDnjckb3R9WHcG34tky+FHpNKKCW0wc/scYLwMtO+ptyGUfMW0/b/n4qRiALlaFHc9Oj7Q==}+ engines: {node: '>= 10.0.0'}++ '@napi-rs/[email protected]':+ resolution: {integrity: sha512-oTXEIha4SsuXdTA4Iyskj0kpdx2yVXdhd75c2v3xGrHFfVMsbhTPZU/nMPL4sWKo4pBHm3aucLaqGlF696dTyQ==}+ engines: {node: ^22.20 || ^24.12 || >=25}+ cpu: [x64]+ os: [linux]+ libc: [glibc]++ '@noble/[email protected]':+ resolution: {integrity: sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==}+ engines: {node: ^14.21.3 || >=16}++ '@noble/[email protected]':+ resolution: {integrity: sha512-X5XaVWZIBCT7HHZGm5I7ZQXDwLG+bGXuSrMQAW+7Zvl87h1kmc1ZB1VSRJcpUfoUrGQp4Fkoxm5kZ+Ms+aW+eA==}+ engines: {node: '>= 20.19.0'}++ '@peculiar/[email protected]':+ resolution: {integrity: sha512-Ez3wLKVjaxdsLcgeWN4OE31QkM7oBOgKuuBJxldRYAkfYw2C+8zJPcSd/SThnbhszsEOlAmoaS5kIIkN29fGKQ==}+ engines: {node: '>=14'}++ '@peculiar/[email protected]':+ resolution: {integrity: sha512-coUfuoMeIB7B8/NMekxaDzLhaYmp0HZNPEjYRm9goRou8UZIC3z21s0sL9AWoCw4EG876QyO3kYrc61WNF9B/w==}+ engines: {node: '>=8.0.0'}++ '@peculiar/[email protected]':+ resolution: {integrity: sha512-+oL3HPFRIZ1St2K50lWCXiioIgSoxzz7R1J3uF6neO2yl1sgmpgY6XXJH4BdpoDkMWznQTeYF6oWNDZLCdQ4eQ==}++ '@peculiar/[email protected]':+ resolution: {integrity: sha512-ODOov0sGMJMf3jPonOkgGqPknTsu+DdQ7kD++gz8aI+aFMOMHFbWAA2taqXXVTdP+OTOQR/znGvSpmkeI0WTYQ==}+ engines: {node: '>=14.18.0'}++ '@pinojs/[email protected]':+ resolution: {integrity: sha512-k2ENnmBugE/rzQfEcdWHcCY+/FM3VLzH9cYEsbdsoqrvzAKRhUZeRNhAZvB8OitQJ1TBed3yqWtdjzS6wJKBwg==}++ '@rolldown/[email protected]':+ resolution: {integrity: sha512-eybk3TjzzzV97Dlj5c+XrBFW57eTNhzod66y9HrBlzJ6NsCrWCp/2kaPS3K9wJmurBC0Tdw4yPjXKZqlznim3Q==}++ '@rollup/[email protected]':+ resolution: {integrity: sha512-I+BSHzTAhKN2n7ZwGZsegGcZjDpLqFOMAtJz/u6uFGe0pUFbq56dEHjqJV/ZUdRJtNXNxA+hREUatZBvMR3Oiw==}+ cpu: [arm]+ os: [android]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-pu3BdjS2LtEzRu2elmGzS3fIeWSZy4BMDIaLNwjorO76+k2d0LMluijhsDx3KQyQBQ/lLUZCQA9/s6csvUfuhw==}+ cpu: [arm64]+ os: [android]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-xfSrj9MHnWK9GaSqT9U0ImHtH/N8WZlHLx4cZHiuLcqs640hvZ3hLPd5UR2AZS57FaE8HrRUSpltbZdWRxHiDA==}+ cpu: [arm64]+ os: [darwin]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-bqU99PLJb/dqb3S0GIMdeuyAEETSUgZBoqXYd3Sd+WCsV+MmPhnN6JrotWyir31+QgH7EvvE5/mwGJlEoci8Fw==}+ cpu: [x64]+ os: [darwin]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-JinsFZ5G40oXQb+sUuiA5x689vhr6dDYK0H0NL+rwKdL6CqnmYN8PE4ZwfRSoIjrCxqTQG/SLfTtSvHeGxoVlw==}+ cpu: [arm64]+ os: [freebsd]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-GAdA4UxpiNm27cLHr2GqXBpAD0x9FqwYBY7/YSP0Ss0/PNi4k8gbviqpIpYbVSRBaS2ZcegXEzgTQMbRNCwxCw==}+ cpu: [x64]+ os: [freebsd]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-qDd6NoA1znaLjp4jR5U/KWCdLAKDJNB8W9ChbbDaKbo0xA+Atln5HK6LFCZ4oJQpemtRZA288DCirFRjrspptw==}+ cpu: [arm]+ os: [linux]+ libc: [glibc]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-WtB5Tz5KTNINb8ZA+8sQ7bmjuS1JrRT7YverYIhUGdWWDlpzVWmIwuZE+jidkEXUn1l0zrEkaIMa8dHF3NGcsA==}+ cpu: [arm]+ os: [linux]+ libc: [musl]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-VcQ3L1tjnkKzWjryAVaFhHEWcqOfICX9uxVVoDzm2t0DpgKRHd2zOpVrJc0xsWeBZcBFyYROCIBdyR/fS174pg==}+ cpu: [arm64]+ os: [linux]+ libc: [glibc]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-6+ZQX6P5s0cMDN2Ypb8Lbm2+/sZYmZjdaYny992ujUU9UKi/4CWoJWsl1pNvjWJHNHGK51m+jKGLlh1ylb2ifQ==}+ cpu: [arm64]+ os: [linux]+ libc: [musl]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-D72ZnvkFkBXOfzMMQLcwfPLyGkKb7HZ9/mf97B7v6/P5Lbv4oFOtSY/uHbS8lH6uKUOxoKiuokdb50XZSzzbJw==}+ cpu: [loong64]+ os: [linux]+ libc: [glibc]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-piU6BxeqA3O9KSu3kRCIQQtNqFFaTu21SEV4FwaRZowpnj3bLaWPZHw+xFqCs0XlJ+aOH3PTRWGoglH+mKA/OA==}+ cpu: [loong64]+ os: [linux]+ libc: [musl]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-/5PGpHwqt2EEEOUs1XwzubE/ucr0dWDQ+to3zqi4Ds7EWpwtQ79wXc4JBoxqj/OwpawTsKWzJxHfSuBOq3DrWA==}+ cpu: [ppc64]+ os: [linux]+ libc: [glibc]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-cX3beZDLWt7G2oJF+nhChiT+qtaihs+S2xi7ziGmVB+2pwPng6D0Ed0HmElQOgv2UsUmSJJLGwpBao/3TDx3VA==}+ cpu: [ppc64]+ os: [linux]+ libc: [musl]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-1uz2mGWHyptR7DgHHrlbdRAjXK7v7elGZ9lMja910/RP+ZYbX6xAmCiU9UZSX4hqmgtHMv6lr5l3kq1HIOpcag==}+ cpu: [riscv64]+ os: [linux]+ libc: [glibc]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-nLS8topojxyz7SRpKR2IODRpQ0XPZ+xaOXvT3+hqK/Uy8Lo5HFgkkIBiIrCu5tL5YqzTvgovGw55PwpahTAGig==}+ cpu: [riscv64]+ os: [linux]+ libc: [musl]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-gs7DRKotr3l3q+jGPQBjH0ng1FjlEDm5ueQrkw5JtQvtLyEIcLASqAEaor56BhkKRzk+IcQzrcanBdb/bBQn8g==}+ cpu: [s390x]+ os: [linux]+ libc: [glibc]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-791ET7W17NnScOZM7h4dX5hYspxE28htPFsb1awY/NRR8+PRNkS53e475rDdxXXDrP+kwnCcNWg9CX5ztn/Aqw==}+ cpu: [x64]+ os: [linux]+ libc: [glibc]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-iwZQRcmj7g88g3tzefIrQY7qvmuA/cfYwhrDtTBhsmukO4U2huVO5W+86XacUMRvdSFVAc6kZUZy21JaRwiB9w==}+ cpu: [x64]+ os: [linux]+ libc: [musl]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-dVHFp9gRWrdTpnqQuGfCwd7hOQDatK1VCP2iWhLY/cGrOQs/ucFzJ6A5SRqbXX12ZDI8EUuejSM5kwg+ja7Png==}+ cpu: [x64]+ os: [openbsd]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-t3NlauOW6gxZVVFcBEnO62Cb4wbyDFL416gTg1uFI/2tgqYQlf69FbSE115Ajre9I+c26Lk4mcmdFUsS/DGifQ==}+ cpu: [arm64]+ os: [openharmony]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-xWuIaSye5FWZF8+UYtVEcHtRJDN5kN9Kfgxx3Kq8XIov9KSKbc1fiqQCm90SKrgQbUXZelbnUhnlUJmfSE7P9A==}+ cpu: [arm64]+ os: [win32]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-9ALJJUOg/ZflMJepVo2PlgsGxSaxN7SQ4Z8GoZfVlarWr6r3rkHUNsd/zAio7p4YMtChSMXPionxej4Hkf6CXQ==}+ cpu: [ia32]+ os: [win32]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-blj9z5qx/Pv4WU0W1NMFDB97e0JH5ed+aZGywW8WCvp/NhWX/4PFAq5uu6Q0AebNn+Vo6KzUYDT++JzTT5ojlQ==}+ cpu: [x64]+ os: [win32]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-Erx822VRBwLa124shbj+wNXe//BOgMEctDV0m1aqTQdNO1S69DgNUCFKC1RCeZfixs1J31l6igk1ziyXErbigQ==}+ cpu: [x64]+ os: [win32]++ '@selderee/[email protected]':+ resolution: {integrity: sha512-oELmoyA6ML9jDRMV3kgcMQFKxUfBU0yFVn6yTctVaLT5ygXnxH52I3TZEgV9EhXJC68/uFvE5Daj1/25c0Xa/A==}+ peerDependencies:+ selderee: ~0.12.0++ '@sindresorhus/[email protected]':+ resolution: {integrity: sha512-t09vSN3MdfsyCHoFcTRCH/iUtG7OJ0CsjzB8cjAmKc/va/kIgeDI/TxsigdncE/4be734m0cvIYwNaV4i2XqAw==}+ engines: {node: '>=10'}++ '@szmarczak/[email protected]':+ resolution: {integrity: sha512-4BAffykYOgO+5nzBWYwE3W90sBgLJoUPRWWcL8wlyiM8IB8ipJz3UMJ9KXQd1RKQXpKp8Tutn80HZtWsu2u76w==}+ engines: {node: '>=10'}++ '@tabby_ai/[email protected]':+ resolution: {integrity: sha512-r5bClKrcIusDoo049dSL8CawnHR6mRdDwhlQuIgZRNty68q0x8k3Lf1BtPAMxRf/GgnHBnIO4ujd3+GQdLWzxQ==}+ engines: {node: '>=16.0.0'}++ '@tailwindcss/[email protected]':+ resolution: {integrity: sha512-/T8IKEsf9VTU6tLjgC7+sv2mOPtQxzE2jMw7u4Tt40Tx+QSZxpzh95/H6cMKoja9XuW7iMdLJYBB0o9G1CaAgg==}++ '@tailwindcss/[email protected]':+ resolution: {integrity: sha512-Y85A2gmPSkl5Ve5qR86GL4HT509cFqQh1aes9p3sSkyTPwt0Pppf3GkwGe4JPACcRYjgJIEhQgM6dBClnr0NYw==}+ engines: {node: '>= 20'}+ cpu: [arm64]+ os: [android]++ '@tailwindcss/[email protected]':+ resolution: {integrity: sha512-BiaWatpBcERQFDlOjRDpIVXuFK5PJez5SA4JMg6VYZdBYU+qKfV/vqjcIs+IYmtitf1xYQZTwXvU/8y4lfZUGw==}+ engines: {node: '>= 20'}+ cpu: [arm64]+ os: [darwin]++ '@tailwindcss/[email protected]':+ resolution: {integrity: sha512-fAeUqfV5ndhxRwai8cXGzdLvul9utWOmeTkv69unv4ZXixjn61Z+p9lCWdwOwA3TYboG3BwdVuN/RDjhBRl0mw==}+ engines: {node: '>= 20'}+ cpu: [x64]+ os: [darwin]++ '@tailwindcss/[email protected]':+ resolution: {integrity: sha512-iyf5bV6+wnAlflVeEy7R25dupxTNECZN5QMI0qNT6eT+EgaGdZcKhGkr5SdoaWiLJ3spLqIY9VCeSGrwmtg4kw==}+ engines: {node: '>= 20'}+ cpu: [x64]+ os: [freebsd]++ '@tailwindcss/[email protected]':+ resolution: {integrity: sha512-aAYUprJAJQWWbRrPvtjdroZ56Md+JM8pMiopS6xGEwDfLhqj+2ver2p4nU4Mb3CRqcMmNBjo8KkUgcxhkzVQGQ==}+ engines: {node: '>= 20'}+ cpu: [arm]+ os: [linux]++ '@tailwindcss/[email protected]':+ resolution: {integrity: sha512-nDxldcEENOxZRzC2uu9jrutZdAAQtb+8WWDCSnWL1zvBk1+FN+x6MtDViPB5AJMfttVCUhehGWus3XBPgatM/w==}+ engines: {node: '>= 20'}+ cpu: [arm64]+ os: [linux]+ libc: [glibc]++ '@tailwindcss/[email protected]':+ resolution: {integrity: sha512-Md44bD6veX/PC5iyF8cDVnw4HBIANZepRZZ7a8DQOvkfo5WUBwcp6iAuCUz23u+4SUkhJlD3eL7hNdW8ezd/kA==}+ engines: {node: '>= 20'}+ cpu: [arm64]+ os: [linux]+ libc: [musl]++ '@tailwindcss/[email protected]':+ resolution: {integrity: sha512-tx7us1muwOKAKWao2v/GaafFeQboE6aj88vC6ziN2NCGcRm8gWUhwjzg+YdVB1e4boAtdtma4L43onunI6NS4w==}+ engines: {node: '>= 20'}+ cpu: [x64]+ os: [linux]+ libc: [glibc]++ '@tailwindcss/[email protected]':+ resolution: {integrity: sha512-SJxX60smvHgasZoBy11dX6YRjXJFovwWBoedhbQPOBzgFWBHGB+TVPWB9BxzR7TTxU8FQZAI2AyiNCMzFm8Img==}+ engines: {node: '>= 20'}+ cpu: [x64]+ os: [linux]+ libc: [musl]++ '@tailwindcss/[email protected]':+ resolution: {integrity: sha512-jx1+rPhY/5Ympkktd656HBWEBLxP7dH06losBLjjf5vgCODXvi9KhtftWcMIwTFIDqBr7cRnQkdLnAG+IOlGvQ==}+ engines: {node: '>=14.0.0'}+ cpu: [wasm32]+ bundledDependencies:+ - '@napi-rs/wasm-runtime'+ - '@emnapi/core'+ - '@emnapi/runtime'+ - '@tybys/wasm-util'+ - '@emnapi/wasi-threads'+ - tslib++ '@tailwindcss/[email protected]':+ resolution: {integrity: sha512-3rc292Ca2ceK6Ulcc/bAVnTs/3nDtoPhyEKlgPv+yQJQi/JS/AMJlqzxvlDacL1nekbrcf6bTqp/jV4qgnPxNQ==}+ engines: {node: '>= 20'}+ cpu: [arm64]+ os: [win32]++ '@tailwindcss/[email protected]':+ resolution: {integrity: sha512-yJ0pwIVc/nYeGoV02WtsN8KYyLQv7kyI2wDnkezyJlGGjkd4QLwDGAwl47YpPJeuI0M0ObaXGSPjvWDPeTPggw==}+ engines: {node: '>= 20'}+ cpu: [x64]+ os: [win32]++ '@tailwindcss/[email protected]':+ resolution: {integrity: sha512-krXjAikiaFSPaK/FkAQT5UTx3VormQaiZ5hBFlJZ9UFQGB/rwg1MZIhHAG9smMQRTdyJxP6Qt5MwMtdyU5FWrA==}+ engines: {node: '>= 20'}++ '@tailwindcss/[email protected]':+ resolution: {integrity: sha512-yYU8cogLeSh/ms2jh8Fj7jaba/EWa7Ja6GoUqYZaraEuCI5YS6ms6ObZgjjedm+jm6XZjdNRWBpPP6Z86oOxcw==}+ peerDependencies:+ vite: ^5.2.0 || ^6 || ^7 || ^8++ '@tanstack/[email protected]':+ resolution: {integrity: sha512-6T5Yop/793YI+H+5J8Hsyj4kCih9sl4t3ElLgKioW5hk3ocn+ZdSJ94tT7vL7uabxSugWYBZlOTMPzEw2puvQw==}+ engines: {node: '>=18'}+ hasBin: true++ '@tanstack/[email protected]':+ resolution: {integrity: sha512-3dfx9MBP0aq5sXKteikG629X9oviptrQj0IFRk9YGcb+lB7Kv5x8S17oOSk1wUWgjQZ4xVJEMbKwOAODymocgA==}++ '@tanstack/[email protected]':+ resolution: {integrity: sha512-utTS5L2OkeYUzXGohL1Z8sefu1GLNOJcxe8Hd6iIdc/Xo1K1nDB2JEp4iSFhvYh33xKC9V91TxrS8qfrpoKobQ==}+ engines: {node: '>=20.19'}++ '@tanstack/[email protected]':+ resolution: {integrity: sha512-y6zHjzDPTQZZ0OEtUujmGpq3TAFafgs6dCMlnTVoKJXZm3Eda0EhLuMdtb1lDdGc6/cSdEi1eptfh27mZkFzMQ==}+ engines: {node: '>=18'}++ '@tanstack/[email protected]':+ resolution: {integrity: sha512-y/xtNPNt/YeyoVxE/JCx+T7yjEzpezmbb+toK8DDD1P4m7Kzs5YR956+7OKexG3f8aXgC3rLZl7b1V+yNUSy5w==}+ engines: {node: '>=18'}++ '@tanstack/[email protected]':+ resolution: {integrity: sha512-I8DkFXls5jXLqtm8+QpOhEmG07hIblhSZFzafg9wHsMSEvMzULy9hK17wU1T/ahfhMbtITJhbxutwwCoihkR7A==}++ '@tanstack/[email protected]':+ resolution: {integrity: sha512-LlRB28qJwO/QCGaHvWnbdh4haBgTFiZVmzA2uzxSBS3YA7/IqrQ6HOBK70CkFQ+DbflZ7NawsmSln13h5iIdTA==}+ peerDependencies:+ '@tanstack/react-start': '*'+ react: ^17.0.0 || ^18.0.0 || ^19.0.0+ peerDependenciesMeta:+ '@tanstack/react-start':+ optional: true++ '@tanstack/[email protected]':+ resolution: {integrity: sha512-VAtY6AW6SEAxwBT5PZ415Qg+ozi9BHjiYGVTUmHuwK/0QLE9Giyj/f4iu8bm+sX7gwjtn9LlbV1A2YfxLYiNrg==}+ engines: {node: '>=18'}+ peerDependencies:+ react: '>=16.8'+ react-dom: '>=16.8'++ '@tanstack/[email protected]':+ resolution: {integrity: sha512-B+fWiYZBc+0uUD5zDZAeLw9dKj7XEsdnuu6zRZ+no6LNKpeE3P3bJ+N6HINjcIlWR6fW3vUoTneEaGa2V6ehqw==}+ peerDependencies:+ react: ^18 || ^19++ '@tanstack/[email protected]':+ resolution: {integrity: sha512-iHM9b0aDJbuvftmkiQXawzoqsdV68p2Re2safbVLCnxafe+iLKV++2i3hI/BMAP6uR92/Mjw94JKJJfD7pbwHQ==}+ engines: {node: '>=20.19'}+ peerDependencies:+ react: '>=18.0.0 || >=19.0.0'+ react-dom: '>=18.0.0 || >=19.0.0'++ '@tanstack/[email protected]':+ resolution: {integrity: sha512-HaIGKI3YLmjBYIvy5DFDY23oNaYZIsTZfngey07Uh5iLVJgM3bIGCnZeOFOqzjFld9JHWcaHJnasD/bKoGKwJQ==}+ peerDependencies:+ react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0+ react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0++ '@tanstack/[email protected]':+ resolution: {integrity: sha512-JbDTAwtzZ99aOeCrAfW5EsE5KSq5RWh6Af2dtFwyLIIk48Ja7vm6n4axu/43T3vfjFnEGJalxJ1wyYjSQD6bSg==}+ peerDependencies:+ react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0+ react-dom: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0++ '@tanstack/[email protected]':+ resolution: {integrity: sha512-X86Jqk3vB2KJcUfS6oLi7B7yxbaa59QEhZRPPP1fRx3k+Jw/Fu1UYVBcRtdwK/OccQnrlQdVoKvNO3QXmyEBOw==}+ engines: {node: '>=20.19'}++ '@tanstack/[email protected]':+ resolution: {integrity: sha512-mzTOBhypOuDJAy/D8n2MfUZ1HFkXnmSETviRyhqEC8LUE7/IZQExOTxMANj3KjTofYTkFNpBY67qaVrT41YccA==}++ '@tanstack/[email protected]':+ resolution: {integrity: sha512-+ILjvtHup6Y2hzQ6YzwMgX1Q+oQpxEGOXCEsCNaPoIP0VxMbizIBTmYTDtkerkIQS8/CbP1BRuyt8V/8BCsy1g==}++ '@tiptap/[email protected]':+ resolution: {integrity: sha512-Cz50pvciQrxdSxgTkHOVz0uD0Yl/8Xt0QatGD6ILm47jW8EzyHR9RkUGs/D5IqzXKuVPntfw1ttaT926vXfiRg==}+ peerDependencies:+ '@tiptap/pm': 3.31.3++ '@tiptap/[email protected]':+ resolution: {integrity: sha512-fyY2XMbyDDDfOTQ1Qdrnqa1qwC9DWE4n7AfE0EKQI0G8MfLV8RaDlLDcOZDJ9JbMPY7/Gx7EjyK4NKxSW9n2hQ==}+ peerDependencies:+ '@tiptap/core': 3.31.3+ '@tiptap/pm': 3.31.3++ '@tiptap/[email protected]':+ resolution: {integrity: sha512-dIuYhKk8TitKU/FeDpoTeWZhU42YgDN5npgWNjAmMmRktPdoxnH3/wGSiwXlqZgJWjehN7kPWDePWpJeAImGpQ==}+ peerDependencies:+ '@tiptap/core': 3.31.3++ '@tiptap/[email protected]':+ resolution: {integrity: sha512-EV6ZnwKc++2OM/OcD54n8s1B7C9LP7GKAtdEPwu0t3BYJf3sG8Ueoinf7SgGPO9oMPg96GneOkDNm1urMV167g==}+ peerDependencies:+ '@tiptap/core': 3.31.3+ '@tiptap/pm': 3.31.3++ '@tiptap/[email protected]':+ resolution: {integrity: sha512-qEyyoPapPef4LO8XKaN83bxtaNzkJ4kFn/IxLnEKd4BJ3Mvi4MH2yJYlyDqwFnMoev4pMA1zBHRAt/C0THRmZw==}+ peerDependencies:+ '@tiptap/extension-list': 3.31.3++ '@tiptap/[email protected]':+ resolution: {integrity: sha512-nvknt4FhyJQjYcvxptmeUlFsIAc8ibua3E5BN4Pim374/9RWepH4cdE9X0/qUTtguHElLx0iKtSIY3rW2qGTFA==}+ peerDependencies:+ '@tiptap/core': 3.31.3+ '@tiptap/pm': 3.31.3++ '@tiptap/[email protected]':+ resolution: {integrity: sha512-SzxOqchrD2AcN3uT67PjKmRFEMOU3vNNiwNaamZJUbZrI6Hmy+bvdHJrc3jrIddyyCrAtsnAfRI0cmorW1jGfg==}+ peerDependencies:+ '@tiptap/core': 3.31.3++ '@tiptap/[email protected]':+ resolution: {integrity: sha512-EexgmqnyDNyGlISxo7SMrp5MygpJYmqD+0cY5jB6L1U6L4CpKKRWUt8OO1sWzEHDE1+TTvwt+WIFoIWAziOtEA==}+ peerDependencies:+ '@tiptap/core': 3.31.3++ '@tiptap/[email protected]':+ resolution: {integrity: sha512-NWomSfu5CSC7VacnMSDzKT8qm66SzMfZwVPEtwY5bPpRTJgTiT1rNK0neDrrzfMN27MfylGyKWWf7Q5Qf8w/fg==}+ peerDependencies:+ '@tiptap/extensions': 3.31.3++ '@tiptap/[email protected]':+ resolution: {integrity: sha512-rd4VJ9PGSP9Eop8ZTEwaLZcMzMXLuJKe3hUNf58rq+zANpwM+9fI+vB7g9MAc3eXwUNDxNDVACFIL2oeBqpQ3A==}+ peerDependencies:+ '@floating-ui/dom': ^1.0.0+ '@tiptap/core': 3.31.3+ '@tiptap/pm': 3.31.3++ '@tiptap/[email protected]':+ resolution: {integrity: sha512-EBXKb1FrVStsNYCcRGtd9jmzveCvR+eqgg1rVqoONrqFK6U7bga6LN+1dMKroP1kliDVgveYkP3vRYxqw+rFqg==}+ peerDependencies:+ '@tiptap/extensions': 3.31.3++ '@tiptap/[email protected]':+ resolution: {integrity: sha512-QAdCvNO4+yW9ATwsrej11NTkDYFqPLIEQr3ARNrKOK1qaiS7A0fia2SEukb/hrkP3A6mbozhoQt2r2RGUf/DpQ==}+ peerDependencies:+ '@tiptap/core': 3.31.3++ '@tiptap/[email protected]':+ resolution: {integrity: sha512-rk5VHMAeQcg06SLauN6EGdD2jc0O2qY8QkZYPd0LxNvLblw2BxBx+lxUQSYwLAT9Ie5914gKIK2YbRyO2Ts3ig==}+ peerDependencies:+ '@tiptap/core': 3.31.3++ '@tiptap/[email protected]':+ resolution: {integrity: sha512-YnHGy2KShRwvCseAmmxl9VP7R0qaj8QMp3DA6DJWZqp7r5gLGvDkAqhedxqqefqsE4Y43hjkBdjtB9Ce78LkIw==}+ peerDependencies:+ '@tiptap/core': 3.31.3+ '@tiptap/pm': 3.31.3++ '@tiptap/[email protected]':+ resolution: {integrity: sha512-wWNG9BOtx2Cg4vwxPVGDIJ5DGX+ETkldeoaFJLB1NXUL4OPUiVTf8cHZ+hdYgJWP704BEB7jQgjlpvdi6VigTg==}+ peerDependencies:+ '@tiptap/core': 3.31.3++ '@tiptap/[email protected]':+ resolution: {integrity: sha512-ibGvdvAPyfxBMUVNRI43eb9h2/Jka1MRG5GtnGqbcCX/2+Y/y0EOfFrPQPkuYphiWQYyu9+FzPKMB/pjuaLuKQ==}+ peerDependencies:+ '@tiptap/core': 3.31.3++ '@tiptap/[email protected]':+ resolution: {integrity: sha512-986wOQzTL9Zr5lf84LCLpm+YOms8A0K39/8DVoqRfebqcOe0/eq4bnztmAlfabOd+kJY92g3AgZERFUx/w+dcw==}+ peerDependencies:+ '@tiptap/core': 3.31.3+ '@tiptap/pm': 3.31.3++ '@tiptap/[email protected]':+ resolution: {integrity: sha512-4QlKOriJJMvg95QJTEsy9BUYPBQ6UvJyb8WURRwdUtQUkkqb8h32lg/eyQUv2FzW9IT1AdUyNZfVaxH64kRfQA==}+ peerDependencies:+ '@tiptap/extension-list': 3.31.3++ '@tiptap/[email protected]':+ resolution: {integrity: sha512-If8UOEdDZbPJU6iYTvLtH6DOp2KBy6BKxg9UELL1AevVetGHEF/7lW8hP50Gn1tHMVpPRqmhSzVrJRpEJJgb/Q==}+ peerDependencies:+ '@tiptap/extension-list': 3.31.3++ '@tiptap/[email protected]':+ resolution: {integrity: sha512-LoveGnC0FVdCV4jUNBaG1ZA+KWE07+adzV3kGy6uUYFcJEjbVUHTnPDrBOob3IwOSO3sCwIkvQb6EVYeXn/4yg==}+ peerDependencies:+ '@tiptap/core': 3.31.3+ '@tiptap/pm': 3.31.3++ '@tiptap/[email protected]':+ resolution: {integrity: sha512-mp3g11NgA/PYu8rj7J7Ez3l4qBy6WfTSmHIG4PZvEGG5w2oUAIkgb9DU7nPPzjmeme27oazFYZw+AtZA0+u4tw==}+ peerDependencies:+ '@tiptap/extension-list': 3.31.3++ '@tiptap/[email protected]':+ resolution: {integrity: sha512-+iPku7wJfy5hbNDNLX8dveFtYVsZMmh7vztjuq8hT3mipSC4IByDehDbU8fzUCjfXiEzmI7mQn7c8LGmHULuzA==}+ peerDependencies:+ '@tiptap/core': 3.31.3++ '@tiptap/[email protected]':+ resolution: {integrity: sha512-9jYtR8ELEw7GVaruyrm4oFkPcjig9Q+crc+dpmarhBNXUmxagCdlhVzNwCJ2WJRzvBAtx59sEYqNTU38Wx8S3A==}+ peerDependencies:+ '@tiptap/extensions': 3.31.3++ '@tiptap/[email protected]':+ resolution: {integrity: sha512-G29bhKttYwcKHT+BI6emWVFol3RO/gUXxQVcmr/iT8LXXy7j8J6HFUnsKM+Kg5YlP1rxMRgsa65dbrQVahZi0A==}+ peerDependencies:+ '@tiptap/core': 3.31.3++ '@tiptap/[email protected]':+ resolution: {integrity: sha512-gdsWtF+taeaCu6V+5Ct10fGo0ACUy1GnYtbb+mcathBt8OqbT+Ws60p/yEmKesBDz2Hn+B5IcWy6+2BBZl5ZTg==}+ peerDependencies:+ '@tiptap/core': 3.31.3++ '@tiptap/[email protected]':+ resolution: {integrity: sha512-HghdJaOwRqYzsAxqSyNyb+IWyOMcdCl8IoiBETA9BZCJAqdXzFLcuWp7CqCqJPam9dgkWosSoHqTCAO4nTBfpw==}+ peerDependencies:+ '@tiptap/core': 3.31.3++ '@tiptap/[email protected]':+ resolution: {integrity: sha512-8sJNPGGUe8f3aDojcOW5cfVL7I5NrBbE0UWxG08qoi9Tea6qWbvQJsCR9tsrOapr/DaLr3kpbGZ9s1gEEfcNcA==}+ peerDependencies:+ '@tiptap/core': 3.31.3+ '@tiptap/pm': 3.31.3++ '@tiptap/[email protected]':+ resolution: {integrity: sha512-sZime0SWsz/k62W2WvHx5Ig7G2h7kVhrrmnqy+wEgIHfDwEfOlelRjaWCiBCFlF7dxGUntJusCh9FxlLhni0Ag==}++ '@tiptap/[email protected]':+ resolution: {integrity: sha512-QiwQqvaLFLm5EMFu5tg7nAgXJxCUiUTLD8EsK+TqVV5P4bqOoMOCM39khbhXTJyahCuYpiFWx5YOSDtC/JiPtg==}+ peerDependencies:+ '@tiptap/core': 3.31.3+ '@tiptap/pm': 3.31.3+ '@types/react': ^17.0.0 || ^18.0.0 || ^19.0.0+ '@types/react-dom': ^17.0.0 || ^18.0.0 || ^19.0.0+ react: ^17.0.0 || ^18.0.0 || ^19.0.0+ react-dom: ^17.0.0 || ^18.0.0 || ^19.0.0++ '@tiptap/[email protected]':+ resolution: {integrity: sha512-WKof9RewdmGHvWJ1wn0/HVNG2mV+HOgVRyJkKekuM9fgr6BZAAH/xZsWE1eon+94JnQ+KtK2ThydXQM/qc6b2A==}++ '@turbo/[email protected]':+ resolution: {integrity: sha512-0pGfE4Lpxrbd+6gUD9z025Tn4z9uMaSNZ3VX0H/hkUPZkjY5xrCa1NfTqocs09NM5NiYE3wEVcoYBadrhayRCA==}+ cpu: [x64]+ os: [darwin]++ '@turbo/[email protected]':+ resolution: {integrity: sha512-Ub7hTbu0bPSiW156ciuLCexG5/SfuZM/QWeBBh9o8P4XyKiZwKqubT6Y9DdJjdp4ZY2wS47Prdl06Xxzt0q6zw==}+ cpu: [arm64]+ os: [darwin]++ '@turbo/[email protected]':+ resolution: {integrity: sha512-8ipdmgmvSomfQ8E9afUsefO+BLO6QMW7srrHqMOCXD3BPX4FlYqqWAJY1GvbQotZMWKzNohdVkevrUYM6ZzYKA==}+ cpu: [x64]+ os: [android, linux]++ '@turbo/[email protected]':+ resolution: {integrity: sha512-tsftYXAzgc+GdosqyRP8+Zzk2evJ8ej7Otal7/DU+6GVekVZ3kqM/z7zlGuF4TSHeetWxX04KN1I64LkmvYzgg==}+ cpu: [arm64]+ os: [android, linux]++ '@turbo/[email protected]':+ resolution: {integrity: sha512-p5LDVcGmC8W6FCrJPehr1t0ZvYqM8xvG3Va+LkwtDMK3Rl0NhSsJOYbYZVBfMbkm+9RKcCvekFCbSVtQ9Eyuqg==}+ cpu: [x64]+ os: [win32]++ '@turbo/[email protected]':+ resolution: {integrity: sha512-u0M3m1aXo9lpDM/2iQhxlGzgWjHFq/MC4TqHn1YAvxk8g1wGtzRB2QBx/SLqRChhPhC29mzaB8eLcxKh/pcM1g==}+ cpu: [arm64]+ os: [win32]++ '@types/[email protected]':+ resolution: {integrity: sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA==}++ '@types/[email protected]':+ resolution: {integrity: sha512-ufFd2Xi92OAVPYsy+P4n7/U7e68fex0+Ee8gSG9KX7eo084CWiQ4sdxktvdl0bOPupXtVJPY19zk6EwWqUQ8lg==}++ '@types/[email protected]':+ resolution: {integrity: sha512-h/NUaSyG5EyxBIp8YRxo4RMe2/qQgvyowRwVMzhYhBCONbW8PUsg4lkFMrhgZhUe5z3L3MiLDuvyJ/CaPa2A8A==}++ '@types/[email protected]':+ resolution: {integrity: sha512-8PvcXf70gTDZBgt9ptxJ8elBeBjcLOAcOtoO/mPJjtji1+CdGbHgm77om1GrsPxsiE+uXIpNSK64UYaIwQXd4Q==}++ '@types/[email protected]':+ resolution: {integrity: sha512-IQ3EbTzGxIigb1I3qPZc1rWJnH0BmSKv5QYTalEwweFvyBDLSAe24zP0le/hyi7ecGfZVlIVAg4BZqb8WBwKqw==}++ '@types/[email protected]':+ resolution: {integrity: sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==}++ '@types/[email protected]':+ resolution: {integrity: sha512-KSVgmQmzMwPlmtljOomayoR89W4FynCAi3E8PPs7vmDVPe84hT+vGPKkJfThkmXs0x0jAaa9U8uW8bbfyS2fWw==}++ '@types/[email protected]':+ resolution: {integrity: sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==}++ '@types/[email protected]':+ resolution: {integrity: sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==}++ '@types/[email protected]':+ resolution: {integrity: sha512-nEnwB++1u5lVDM2UI4c1+5R+FYaKfaAzS4OococimjVm3nQw3TuzH5UNsocrcTBbhnerblyHj4A49qXbIiZdpA==}++ '@types/[email protected]':+ resolution: {integrity: sha512-L3LgimLHXtGkWikKnsPg0/VFx9OGZaC+eN1u4r+OB1XRqH3meBIAVC2zr1WdMH+RHmnRkqliQAOHNJ/E0j/e0Q==}++ '@types/[email protected]':+ resolution: {integrity: sha512-BQ5aZNSCpj7D6K2ksrRCTmKRLEpnPvWDiLPfoGyhZ++8YtiK9d/3DBKPJgry359X/P1PfruyYwvnvwFjuEiEIg==}++ '@types/[email protected]':+ resolution: {integrity: sha512-wVV3cnIKzxTffaPH8iRnddX1zahbYB1ZEoAxyhoBo3TBCBuK6nZ8M8JYO/RhsCuuBVOw/DEN/t/ENbruwlxn6Q==}++ '@types/[email protected]':+ resolution: {integrity: sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA==}++ '@types/[email protected]':+ resolution: {integrity: sha512-SGrw/h3KPFshy3OE6ZL53LMBG5vGQQ8/gIpiqz/kRZhPJ7HgwCEs8LBuNtWLa8dvGZVpSF7+Bf+c11HUrCb/yg==}++ '@types/[email protected]':+ resolution: {integrity: sha512-c7M5ox8p0nEOfbJ2E9Qcmt8/QCu/VzsiAhzBiZbvky2PhKZDHpKB3sQHBM5MEZNkCfBOaS6S9//AGPRTNB7IaA==}++ '@types/[email protected]':+ resolution: {integrity: sha512-ZI7bU42mZXXKHn/qNLEw2IrbiINU7X5+vfgdixBHkCNpYWXjKgfQ/P+uyGb5CjOLB9UcnTeg3rylQtV2hym44Q==}+ peerDependencies:+ '@types/react': ^19.3.0++ '@types/[email protected]':+ resolution: {integrity: sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==}++ '@types/[email protected]':+ resolution: {integrity: sha512-H/+L+UkTV33uf49PH5pCAUBVPNj2nDBXTN+qS1dOwyyg24l3CcicicCA7ca+HMvJBZcFgl5r8e+RR6elsb4Lyw==}++ '@types/[email protected]':+ resolution: {integrity: sha512-S3rGl2KbViH+98/CgHipPIWgtAFnjxLsppxIRbgJHNuZL7Y+py+7kZjT7xS+wOmCxYTn4O7IqLqkvekg99MDVQ==}++ '@types/[email protected]':+ resolution: {integrity: sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==}++ '@types/[email protected]':+ resolution: {integrity: sha512-zFDAD+tlpf2r4asuHEj0XH6pY6i0g5NeAHPn+15wk3BV6JA69eERFXC1gyGThDkVa1zCyKr5jox1+2LbV/AMLg==}++ '@vitejs/[email protected]':+ resolution: {integrity: sha512-YmKkfhOAi3wsB1PhJq5Scj3GXMn3WvtQ/JC0xoopuHoXSdmtdStOpFrYaT1kie2YgFBcIe64ROzMYRjCrYOdYw==}+ engines: {node: ^20.19.0 || >=22.12.0}+ peerDependencies:+ vite: ^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0++ '@vitest/[email protected]':+ resolution: {integrity: sha512-E8eBXaKibuvH2pSZErOjdVb5vF4PbKYcrnluBTYxEk1l/VhhwZg1kZQsdtjq+CsF5CFydf2Rdkz7jDHKSisi3w==}++ '@vitest/[email protected]':+ resolution: {integrity: sha512-Trr0hYO9CM3Wj6ksWHRhK9IZpIY6wTMO5u/MqXurMxT57sWBaOPEtP3Oq60ihZuh5JsiagKfz95OcxdEP6dBrA==}+ peerDependencies:+ msw: ^2.4.9+ vite: ^5.0.0 || ^6.0.0 || ^7.0.0-0+ peerDependenciesMeta:+ msw:+ optional: true+ vite:+ optional: true++ '@vitest/[email protected]':+ resolution: {integrity: sha512-KUHlwqVu0sRlhCdyPdQ/wBoTfRahjUky1MubOmYw9fWfIZy1gNoHpuaaQBPAaMaVYdQYHJLurzj8ECCj5OwTqA==}++ '@vitest/[email protected]':+ resolution: {integrity: sha512-sB9y4ovltoQP+WaUPwmSxO9WIg9Ig694Di5PalVPsYHklAdE027mehpWF2SQSVq+k6sFgaivbTjTJwZLSHbedA==}++ '@vitest/[email protected]':+ resolution: {integrity: sha512-7C+MwShwtBSI5Buwoyg3s/iY1eHL9PKAf+O1wVh/TdnjXUtkoL/9YQtre90i4MtNXM6edP1wJ2zOBpfCyhIS7g==}++ '@vitest/[email protected]':+ resolution: {integrity: sha512-Q2eQGI6d2L/hBtZ0qNuKcAGid68XK6cv1xsoaIma6PaJhHPoqcEJhYpXZ/5myCMqkNgtP6UKuBhbc0nHKnrkuQ==}++ '@vitest/[email protected]':+ resolution: {integrity: sha512-x6BDOd7dyo3PFLY3I9/HJ25X/6OurhGXk2/B9gOZNPF7XDVjeBK4k01lQE5uvDpbuheErh91qYuE1E2OEjK3Rw==}++ '@xmldom/[email protected]':+ resolution: {integrity: sha512-/5NV/vDALVFDXgLmfsy9TRCBlKwO2LNBFzpzvb9iIj+jR+eSc6DLYYvVOdivT/jm7MtU6TebYuRmzEOI7w40UA==}+ engines: {node: '>=10.0.0'}++ '@zone-eu/[email protected]':+ resolution: {integrity: sha512-LOMzdrKRVgaghLaezIPdHRhsGpfDiWNQo1RptWc84CRllI4dWLwqX/L4x1iTt1CaeyvyUfMXM/6mjIsEisT3Tg==}++ resolution: {integrity: sha512-a1wflyaL0tHtJSmLSOVybYhy22vRih4eduhhrkcjgrWGnRfrZtovJ2FRjxuTtkkj47O/baf0R86QU5OuYpz8fA==}+ engines: {node: ^20.17.0 || >=22.9.0}++ resolution: {integrity: sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==}+ engines: {node: '>= 14'}++ resolution: {integrity: sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==}++ resolution: {integrity: sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-2VnyWkqsP5v5XbBhL3tD5Syx8iNPBYsoU7kY4S2fz7wg8Rj/nztWKCUzGKaFRTv0Xwf3/H058CR1Kvtd/3lRow==}+ engines: {node: '>=14.0.0'}+ peerDependencies:+ dmg-builder: 26.15.3+ electron-builder-squirrel-windows: 26.15.3++ resolution: {integrity: sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==}++ resolution: {integrity: sha512-S2s3aOytiKdFRdulw2qPE51MzjzVOisppcVv7jVFR+Kw0kxwvFrDcYA0h7Ndqbmj0HkMIXYWaoj7fli8kgx1eg==}+ engines: {node: '>=12.0.0'}++ resolution: {integrity: sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==}+ engines: {node: '>=12'}++ resolution: {integrity: sha512-NW2cX8m1Q7KPA7a5M2ULQeZ2wR5qI5PAbw5L0UOMxdioVk9PMZ0h1TmyZEkPYrCvYjDlFICusOu1dlEKAAeXBw==}+ engines: {node: '>=0.12.0'}++ resolution: {integrity: sha512-htCUDlxyyCLMgaM3xXg0C0LW2xqfuQ6p05pCEIsXuyQ+a1koYKTuBMzRNwmybfLgvJDMd0r1LTn4+E0Ti6C2AA==}++ resolution: {integrity: sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==}++ resolution: {integrity: sha512-+q/t7Ekv1EDY2l6Gda6LLiX14rU9TV20Wa3ofeQmwPFZbOMo9DXrLbOjFaaclkXKWidIaopwAObQDqwWtGUjqg==}+ engines: {node: '>= 4.0.0'}++ resolution: {integrity: sha512-kNOjDqAh7px0XWNI+4QbzoiR/nTkHAWNud2uvnJquD1/x5a7EQZMJT0AczqK0Qn67oY/TTQ1LbUKajZpp3I9tQ==}+ engines: {node: '>=8.0.0'}++ resolution: {integrity: sha512-lHe62zvbTB5eEABUVi/AwVh0ZKY9rMMDhmm+eeyuuUQbQ3+J+fONVQOZyj+DdrvD4BY33uYniyRJ4UJIaSKAfw==}++ resolution: {integrity: sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==}++ resolution: {integrity: sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==}+ engines: {node: 18 || 20 || >=22}++ resolution: {integrity: sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==}++ resolution: {integrity: sha512-gMmEShwwq7FJqMwvfRwvCl00v4kN+KOfJqXn+f4nrufak5gNHJOksd/60Dvjuz7sI8Y5WiSFBa8FEYr+zoyqCw==}+ engines: {node: '>=6.0.0'}+ hasBin: true++ resolution: {integrity: sha512-XpNj6GDQzdfW+r2Wnn7xiSAd7TM3jzkxGXBGTtWKuSXv1xUV+azxAm8jdWZN06QTQk+2N2XB9jRDkvbmQmcRtg==}++ resolution: {integrity: sha512-d0II/GO9uf9lfUHH2BQsjxzRJZBdsjgsBiW4BvhWk/3qoKwQFjIDVN19PfX8F2D/r9PCMTtLWjYVCFrpeYUzsw==}+ deprecated: Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.++ resolution: {integrity: sha512-xhZO/w/6aFmRfkaWohcl2NfyIy87gK5SBbys8kctZeTGF1Apjpv/10pfUuv+YEfVPkESU/h2Y6tt/Dwp+bIZPw==}+ peerDependencies:+ react: '>=18.0.0'+ react-dom: '>=18.0.0'++ resolution: {integrity: sha512-9zeA+KLZNNzglF2TPKRQEDyx6Yby7daAkuy8MiPzpXPsYDWi/DRM8jmwUDxokQjYqBpv5DgPiwD4h4ZZSy1Ujw==}++ resolution: {integrity: sha512-uZbew1NqdmPDTMJ8ah1y+b+9QEJrfkXFk3RcTQw3X0jW/xRUvFKsg1CfQdSYGdTbXZWExtU3J3ccxtnfw1Fi0g==}++ resolution: {integrity: sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==}+ engines: {node: 20 || >=22}++ resolution: {integrity: sha512-3GSvyjvDI4Dur1Meg2BekJquu5uF+9R9a1+5M1Mde192eZoXbeXjzgOsgqPS2V8D5wrrip0gR5Hf/GhWQ9ZzaA==}+ engines: {node: ^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7}+ hasBin: true++ resolution: {integrity: sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==}++ resolution: {integrity: sha512-g/kR520giAFYkSXTzcmF3kqQq7wi8F6N6SzeDgZrqTBN+VHdmgWOyTdD1yD7AATDId/yXLvuP34CxW46/BwCdw==}+ engines: {node: '>=12.0.0'}++ resolution: {integrity: sha512-q2hn7Mbo2nFNkVekPiHFx6Nfo3hURmES3tfBn+k5Pqxl2RkmP3QGqZUhH/q9Pch/4G05NRhPjDlVj1O8q4Txvw==}+ engines: {node: '>=14.0.0'}++ resolution: {integrity: sha512-U1Z/ob71V/bXfVABvNr/Kumf5VyeQRBEm6Txb0PQ6S7V5GpBM3w4Cbqz/xPDicR5tN0uvDifng8C+5qECeGwyQ==}+ engines: {node: '>=6.0.0'}++ resolution: {integrity: sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-2/kNscPhpcxrOigMZzbiWF7dz8ilhb/nIHU3EyZiXWXpeq/au8qJ8VhdftMkty3n7Gj6HIGalQG8oiBNB3AJgA==}+ engines: {node: '>=10.6.0'}++ resolution: {integrity: sha512-v+p6ongsrp0yTGbJXjgxPow2+DL93DASP4kXCDKb8/bwRtt9OEF3whggkkDkGNzgcWy2XaF4a8nZglC7uElscg==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==}+ engines: {node: '>= 0.4'}++ resolution: {integrity: sha512-TITQPUkaz+aVk5GL6NhOdwk1aEaNTSDPsGFWrTuhKGtjTF70jL/Oht2W4c6rXUe5fu7Ie19VIahAXHIIiWWNeg==}++ resolution: {integrity: sha512-4zNhdJD/iOjSH0A05ea+Ke6MU5mmpQcbQsSOkgdaUMJ9zTlDTD/GYlwohmIE2u0gaxHYiVHEn1Fw9mZ/ktJWgw==}+ engines: {node: '>=18'}++ resolution: {integrity: sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==}+ engines: {node: '>=10'}++ resolution: {integrity: sha512-PAJdDJusoxnwm1VwW07VWwUN1sl7smmC3OKggvndJFadxxDRyFJBX/ggnu/KE4kQAB7a3Dp8f/YXC1FlUprWmA==}+ engines: {node: '>= 16'}++ resolution: {integrity: sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g==}+ engines: {node: '>=18'}++ resolution: {integrity: sha512-1R5Fho+jBq0DDydt+/vHWj5KJNJCKdARKOCwZUen84I5BreWoLqRLANH1U87eJy1tiASPtMnGqJJq0ZsLoRPOw==}++ resolution: {integrity: sha512-Wdy2Igu8OcBpI2pZePZ5oWjPC38tmDVx5WKUXKwlLYkA0ozo85sLsLvkBbBn/sZaSCMFOGZJ14fvW9t5/d7kdA==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-77PSwercCZU2Fc4sX94eF8k8Pxte6JAwL4/ICZLFjJLqegs7kCuAsqqj/70NQF6TvDpgFjkubQB2FW2ZZddvQg==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==}+ engines: {node: '>=12'}++ resolution: {integrity: sha512-ROoL94jJH2dUVML2Y/5PEDNaSHgeOdSDicUyS7izcF63G6sTc/FTjLub4b8Il9S8S0beOfYt0TaA5qvFK+w0wA==}++ resolution: {integrity: sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==}+ engines: {node: '>=6'}++ resolution: {integrity: sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==}+ engines: {node: '>=7.0.0'}++ resolution: {integrity: sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==}++ resolution: {integrity: sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==}+ engines: {node: '>= 0.8'}++ resolution: {integrity: sha512-P0CysNDQ7rtVw4QIQtm+MRxV66vKFSvlsQvGYXZWR3qFU0jlMKHZZZgw8e+8DSah4UDKMqnknRDQz+xuQXQ/Zg==}+ engines: {node: '>= 6'}++ resolution: {integrity: sha512-KRs7WVDKg86PWiuAqhDrAQnTXZKraVcCc6vFdL14qrZ/DcWwuRo7VoiYXalXO7S5GKpqYiVEwCbgFDfxNHKJBQ==}+ engines: {node: ^12.20.0 || >=14}++ resolution: {integrity: sha512-pJDh5/4wrEnXX/VWRZvruAGHkzKdr46z11OlTPN+VrATlWWhSKewNCJ1futCO5C7eJB3nPMFZA1LeYtcFboZ2A==}+ engines: {node: '>=0.10.0'}++ resolution: {integrity: sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==}++ resolution: {integrity: sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==}++ resolution: {integrity: sha512-UaXxwISYJPTr9hwQxMFYZ7kNhSXboMXP+Z3TRX6f1/NyaGPfuNUZOWP1pUEb75B2HjfklIYLVRfWiFZJyC6Npg==}++ resolution: {integrity: sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==}++ resolution: {integrity: sha512-+R08/oI0nl3vfPcqftZRpytksBXDzOUveBq/NBVx0sUp1axwzPQrKinNx5yd5sxPu8j1wIy8AfnVQ+5eFdha6Q==}++ resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==}+ engines: {node: '>= 8'}++ resolution: {integrity: sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==}++ resolution: {integrity: sha512-hTIP/z+t+qKwBDcmmsnmjWTduxCg+5KfdqWQvb2X/8C9+knYY6epN/pfxdDuyVlSVeFz0sM5eEfwIUQ70U4ckg==}++ resolution: {integrity: sha512-+1UMbeh68lH1SegH83CGWwpb6OHHbpSgr3+s5Eww5M4CAgswBpoWS0AjTOfEJ33HiYKz1hdj/KTFprzXHmq/6w==}++ resolution: {integrity: sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==}+ engines: {node: '>=6.0'}+ peerDependencies:+ supports-color: '*'+ peerDependenciesMeta:+ supports-color:+ optional: true++ resolution: {integrity: sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==}+ engines: {node: '>=10'}++ resolution: {integrity: sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q==}+ engines: {node: '>=6'}++ resolution: {integrity: sha512-uqbvqLUMrc6p0MO+WBRtTxY55hmyh94WRwI5a++PZe54X+bfVh59FSN7uWCBCW1CCVjzjnrwzfI8zidE2obMMw==}+ engines: {node: '>=16.9.0'}++ resolution: {integrity: sha512-4tvttepXG1VaYGrRibk5EwJd1t4udunSOVMdLSAL6mId1ix438oPwPZMALY41FCijukO1L0twNcGsdzS7dHgDg==}+ engines: {node: '>=10'}++ resolution: {integrity: sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==}+ engines: {node: '>= 0.4'}++ resolution: {integrity: sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg==}+ engines: {node: '>= 0.4'}++ resolution: {integrity: sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==}+ engines: {node: '>=0.4.0'}++ resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-T0NIuQpnTvFDATNuHN5roPwSBG83rFsuO+MXXH9/3N1eFbn4wcPjttvjMLEPWJ0RGUYgQE7cGgS3tNxbqCGM7g==}++ resolution: {integrity: sha512-2xMCmOoMrdQIPHdsTawECdNPwlVFB9zGcz3kuhmBO6U3oU+UQjsue0i8ayLKpgBcm+hcXPMVSGUN9d+pvJ6+VQ==}++ resolution: {integrity: sha512-O3zJUFUYHJKgzPqioHxfxzBzlSC1eXCSr79gMSBKBP5AgjjpmrydMsMLotEg9fAJF36vdUncb+4ndRNxoPdlSQ==}++ resolution: {integrity: sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg==}++ resolution: {integrity: sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw==}++ resolution: {integrity: sha512-cgwlv/1iFQiFnU96XXgROh8xTeetsnJiDsTc7TYCLFd9+/WNkIqPTxiM/8pSd8VIrhXGTf1Ny1q1hquVqDJB5w==}+ engines: {node: '>= 4'}++ resolution: {integrity: sha512-EUBjM+B+lkDE41iE82DDSCfkoPGfXx8IxFxPMjNzm/Uk4xDet77rTN9wqlxlVg71kK7XGuUMv6wUxJUwwv+Xyw==}++ resolution: {integrity: sha512-6kZKyUajlDuqlHKVX1w7gyslj9MPIXzIFiz/rGu35uC1wMi+kMhQwGhl4lt9unC9Vb9INnY9Z3/ZA3+FhASLaw==}++ resolution: {integrity: sha512-zIHwmZPRshsCdpMDyVsqGmgyP0yT8GAgXUnkdAoJisxvf33k7yO6OuoKmcTGuXPWSsm8Oh88nZicRLA9Y0rUeA==}+ engines: {node: '>=12'}++ resolution: {integrity: sha512-uBq4egWHTcTt33a72vpSG0z3HnPuIl6NqYcTrKEg2azoEyl2hpW0zqlxysq2pK9HlDIHyHyakeYaYnSAwd8bow==}+ engines: {node: '>=12'}++ resolution: {integrity: sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==}+ engines: {node: '>= 0.4'}++ resolution: {integrity: sha512-asLFVfWWtJ90ZyOUHMqk7/S2w2guQKxUI2itj3d92ADHhxUSbCMGi1f1cBcJ7xM1To+pE/Khbwo1yuNbMEPKeA==}++ resolution: {integrity: sha512-UeJmFfOrAQS8OJWPZ4qtgHyWExa088/MtK5UEyoJGFH67cDEXkZSviOiKRCZ4Xij0zxI3JECgYs3oKx+AizQBA==}+ engines: {node: '>=0.10.0'}+ hasBin: true++ resolution: {integrity: sha512-Jc19XPV9y9+2bAdZPkXuVNGNIEFBq9poHC61l8Kv6FdK7DRG3+Ic0rerC0DXOaeHNz8yW0fg/JnF8GQROOF5MA==}++ resolution: {integrity: sha512-a1KM5heqS3gQCZzizXEI8RjJy3QVogULPdeSknt76uLDpBIW/HDGsMg/XgP0riP6PI9COsRvFITKKGDqA8fJxA==}+ engines: {node: '>=14.0.0'}+ hasBin: true++ resolution: {integrity: sha512-g/2bn8YTavY4cuS5F+jOS7zmZbXXBV8KZ8yHKfJjFPoKtzBqrpCdNPxBd3tqdBwP7BVd0lGzf7Bk2s0KesWZ4Q==}++ resolution: {integrity: sha512-7EeFW9OLf1NN9NKQP9xdOE/XKqjxv7JDPP6AEAkHli11+Fae1OaLoNuAf13hQv1PPNtuES0pLQSPk2+fS3s8ww==}++ resolution: {integrity: sha512-OHp/vjdlubNlhNkPkL/+3JD34ii5ov7M0GpuXEVdQeqdQ3ulvVR7Dg/rNBLfS5XPIFwgoBLDf9sjjrL+CuDyRQ==}+ engines: {node: ^20.19.0 || >=22.12.0}+ hasBin: true+ peerDependencies:+ '@swc/core': ^1.0.0+ vite: ^5.0.0 || ^6.0.0 || ^7.0.0+ peerDependenciesMeta:+ '@swc/core':+ optional: true++ resolution: {integrity: sha512-bO3y10YikuUwUuDUQRM4KfwNkKhnpVO7IPdbsrejwN9/AABJzzTQ4GeHwyzNSrVO+tEH3/Np255a3sVZpZDjvg==}+ engines: {node: '>=8.0.0'}++ resolution: {integrity: sha512-SjgoaeYsSWZfJzubgQU7juvuXMTvn6/e1gAHdGFA/yuMbpF+I+skYqIJ6DdXBXHeWbkbpNpmwZCTpiivtlWZSw==}+ engines: {node: '>= 22.12.0'}+ hasBin: true++ resolution: {integrity: sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==}++ resolution: {integrity: sha512-PE0KjlsDy9JSsoU4C2Q8NXb1kC4c+bZRac9ZvHXUE4q1Ht63gScKMdEy9jst9+Fi3M4eDkqzkEhBZvix4blP2A==}+ engines: {node: '>=18.0.0'}++ resolution: {integrity: sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==}++ resolution: {integrity: sha512-nGXts5znJzmWPu+mIE9izCOzdg63oJca2mDzGWWTth7sr4aCToKcoyFVBQwN75Ij5Pf6p510EwkTqViTRzDV+w==}+ engines: {node: '>=10.13.0'}++ resolution: {integrity: sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==}+ engines: {node: '>=0.12'}++ resolution: {integrity: sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==}+ engines: {node: '>=0.12'}++ resolution: {integrity: sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A==}+ engines: {node: '>=6'}++ resolution: {integrity: sha512-dtJUTepzMW3Lm/NPxRf3wP4642UWhjL2sQxc+ym2YMj1m/H2zDNQOlezafzkHwn6sMstjHTwG6iQQsctDW/b1A==}+ engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0}++ resolution: {integrity: sha512-2bmlRpNKBxT/CRmPOlyISQpNj+qSeYvcym/uT0Jx2bMOlKLtSy1ZmLuVxSEKKyor/N5yhvp/ZiG1oE3DEYMSFA==}++ resolution: {integrity: sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==}+ engines: {node: '>= 0.4'}++ resolution: {integrity: sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==}+ engines: {node: '>= 0.4'}++ resolution: {integrity: sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==}++ resolution: {integrity: sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==}+ engines: {node: '>= 0.4'}++ resolution: {integrity: sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==}+ engines: {node: '>= 0.4'}++ resolution: {integrity: sha512-Um/+FxMr9CISWh0bi5Zv0iOD+4cFh5qLeks1qhAopKVAJw3drgKbKySikp7wGhDL0HPeaja0P5ULZrxLkniUVg==}++ resolution: {integrity: sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==}+ engines: {node: '>=18'}+ hasBin: true++ resolution: {integrity: sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==}+ engines: {node: '>=18'}+ hasBin: true++ resolution: {integrity: sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==}+ engines: {node: '>=6'}++ resolution: {integrity: sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==}+ engines: {node: '>=10'}++ resolution: {integrity: sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==}++ resolution: {integrity: sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==}+ engines: {node: '>=12.0.0'}++ resolution: {integrity: sha512-ZgEeZXj30q+I0EN+CbSSpIyPaJ5HVQD18Z1m+u1FXbAeT94mr1zw50q4q6jiiC447Nl/YTcIYSAftiGqetwXCA==}++ resolution: {integrity: sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==}++ resolution: {integrity: sha512-8unmvA0qrfpFWBYUate9BTGtQdKHWBYt+KdAIkag7Vvxe7wz8Q2nJg7fLMC0bJqe0bjP31kca7Ckaawrs4Istg==}+ engines: {node: '>=6.0.0'}++ resolution: {integrity: sha512-GZMtZUTNRpOVIECoXwLNZS5xUGE+mVNbTB8h/7Rwh2TFWcBQiPzTgyZi05BF9UMZKkLJv8XBRJTlU7zg8+ZfMg==}++ resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==}+ engines: {node: '>=12.0.0'}+ peerDependencies:+ picomatch: ^3 || ^4+ peerDependenciesMeta:+ picomatch:+ optional: true++ resolution: {integrity: sha512-5giy2PkLYY1cP39p17Ech+2xlpTRL9HLspOfEgm0L6CwBXBTgsK5ou0JtzYuepxkaQ/tvhCFIJ5uXo0OrM2DxA==}++ resolution: {integrity: sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ==}+ engines: {node: '>= 6'}++ resolution: {integrity: sha512-oRXApq54ETRj4eMiFzGnHWGy+zo5raudjuxN0b8H7s/RU2oW0Wvsx9O0ACRN/kRq9E8Vu/ReskGB5o3ji+FzHQ==}+ engines: {node: '>=12'}++ resolution: {integrity: sha512-eXvGGwZ5CL17ZSwHWd3bbgk7UUpF6IFHtP57NYYakPvHOs8GDgDe5KJI36jIJzDkJ6eJjuzRA8eBQb6SkKue0g==}+ engines: {node: '>=14.14'}++ resolution: {integrity: sha512-EQsFzMUJkCKGr1ePqlYADkIUmHW1s3ZXr5Yqy6wbGrfUCphpl2maM/kyOIRA2HpP3AaFQTZXD4ldjek+nccddA==}+ engines: {node: '>=14.14'}++ resolution: {integrity: sha512-YJDaCJZEnBmcbw13fvdAM9AwNOJwOzrE4pqMqBq5nFiEqXUqHwlK4B+3pUw6JNvfSPtX05xFHtYy/1ni01eGCw==}+ engines: {node: '>=6 <7 || >=8'}++ resolution: {integrity: sha512-yhlQgA6mnOJUKOsRUFsgJdQCvkKhcz8tlZG5HBQfReYZy46OwLcY+Zia0mtdHsOo9y/hP+CxMN0TU9QxoOtG4g==}+ engines: {node: '>=6 <7 || >=8'}++ resolution: {integrity: sha512-hcg3ZmepS30/7BSFqRvoo3DOMQu7IjqxO5nCDt+zM9XWjb33Wg7ziNT+Qvqbuc3+gWpzO02JubVyk2G4Zvo1OQ==}+ engines: {node: '>=10'}++ resolution: {integrity: sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==}++ resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==}+ engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0}+ os: [darwin]++ resolution: {integrity: sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==}++ resolution: {integrity: sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==}+ engines: {node: '>=6.9.0'}++ resolution: {integrity: sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==}+ engines: {node: 6.* || 8.* || >= 10.*}++ resolution: {integrity: sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==}+ engines: {node: '>= 0.4'}++ resolution: {integrity: sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==}+ engines: {node: '>= 0.4'}++ resolution: {integrity: sha512-nBF+F1rAZVCu/p7rjzgA+Yb4lfYXrpl7a6VmJrU8wF9I1CKvP/QwPNZHnOlwbTkY6dvtFIzFMSyQXbLoTQPRpA==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==}+ deprecated: Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting [email protected]++ resolution: {integrity: sha512-PT6XReJ+D07JvGoxQMkT6qji/jVNfX/h364XHZOWeRzy64sSFr+xJ5OX7LI3b4MPQzdL4H8Y8M0xzPpsVMwA8Q==}+ engines: {node: '>=10.0'}++ resolution: {integrity: sha512-DpLKbNU4WylpxJykQujfCcwYWiV/Jhm50Goo0wrVILAv5jOr9d+H+UR3PhSCD2rCCEIg0uc+G+muBTwD54JhDQ==}+ engines: {node: '>= 0.4'}++ resolution: {integrity: sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==}+ engines: {node: '>= 0.4'}++ resolution: {integrity: sha512-6tfZ91bOr7bOXnK7PRDCGBLa1H4U080YHNaAQ2KsMGlLEzRbk44nsZF2E1IeRc3vtJHPVbKCYgdFbaGO2ljd8g==}+ engines: {node: '>=10.19.0'}++ resolution: {integrity: sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==}++ resolution: {integrity: sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==}++ resolution: {integrity: sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==}+ engines: {node: '>= 0.4'}++ resolution: {integrity: sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==}+ engines: {node: '>= 0.4'}++ resolution: {integrity: sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==}+ engines: {node: '>= 0.4'}++ resolution: {integrity: sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw==}+ hasBin: true++ resolution: {integrity: sha512-kyCuEOWjJqZuDbRHzL8V93NzQhwIB71oFWSyzVo+KPZI+pnQPPxucdkrOZvkLRnrf5URsQM+IJ09Dw29cRALIA==}+ engines: {node: '>=10'}++ resolution: {integrity: sha512-GiVhRI1BatGARSCmlXWNCjDT0cWrwBWoeduLoV0WSKAgaV/wa+hUWy5LiQLUs4UwiUrE52ZCMfBGiKD87TDPrg==}+ engines: {node: '>=20.19.0'}++ resolution: {integrity: sha512-VTZkM9GWRAtEpveh7MSF6SjjrpNVNNVJfFup7xTY3UpFtm67foy9HDVXneLtFVt4pMz5kZtgNcvCniNFb1hlEQ==}++ resolution: {integrity: sha512-dTxcvPXqPvXBQpq5dUr6mEMJX4oIEFv6bwom3FDwKRDsuIjjJGANqhBuoAn9c1RQJIdAKav33ED65E2ys+87QQ==}++ resolution: {integrity: sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==}+ engines: {node: '>= 14'}++ resolution: {integrity: sha512-V+23sDMr12Wnz7iTcDeJr3O6AIxlnvT/bmaAAAP/Xda35C90p9599p0F1eHR/N1KILWSoWVAiOMFjBBXaXSMxg==}+ engines: {node: '>=10.19.0'}++ resolution: {integrity: sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==}+ engines: {node: '>= 14'}++ resolution: {integrity: sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==}+ engines: {node: '>=0.10.0'}++ resolution: {integrity: sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==}+ engines: {node: '>=0.10.0'}++ resolution: {integrity: sha512-LtwtVyVYO5BqRvcsKuB2iUMnHwPVByPCXFXOpuU96IZPPoPN6xjOGxZQ74pgSVVLQWtUOYgyeL4GE98BY5D3wg==}++ resolution: {integrity: sha512-CBkIFs1za9CW3TIe/x9DSVibN4iEXIMStfOyJIOPCys2MO5Y/9efVF9L//Bb/2RKSFWlnbYRqRBLU3RUm+yJZg==}+ engines: {node: '>=20.0.0'}++ resolution: {integrity: sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==}+ deprecated: This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.++ resolution: {integrity: sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==}++ resolution: {integrity: sha512-7H/2gFSIitxc0hG3nOI1glS8QLo/EHBFFLk8vEUjXY/xu0AdL8jZ9U1IzO2PUm0d2D/ofQcAifb0g6OBkt8U7w==}+ engines: {node: '>= 12'}++ resolution: {integrity: sha512-Bm6H79i01DjgGTCWjUuCjJ6QDo1HB96PT/xCYuyJUP9WFbVDrLSbG4EZCvOCun2rNswZb0c3e4Jt/ws795esHA==}++ resolution: {integrity: sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==}++ resolution: {integrity: sha512-iHrqe5shvBUcFbmZq9zOQHBoeOhZJu6RQGrDpBgenUm/Am+F3JM2MgQj+rK3Z601fzrL5gLZWtAPH2OBaSVcyw==}+ engines: {node: '>= 8.0.0'}++ resolution: {integrity: sha512-gnWD14Jh3FzS3CPhF0AxNOJ8CxqeblPTADzI38r0wt8ZyQl5edpy75myt08EG2oKvpyiqSqsx+Wkz9vtkbTqYQ==}+ engines: {node: '>= 18.0.0'}++ resolution: {integrity: sha512-iQcBXcd+Rv/pkubRyGh2utW2j1oPG5hZY6TUhVPpqK4G+o3IbxpJNx04hgksjc/N7GK5pEorUxDeg31cFgEk/w==}+ engines: {node: '>=18'}++ resolution: {integrity: sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==}++ resolution: {integrity: sha512-6B3tLtFqtQS4ekarvLVMZ+X+VlvQekbe4taUkf/rhVO3d/h0M2rfARm/pXLcPEsjjMsFgrFgSrhQIxcSVrBz8w==}+ engines: {node: '>=18'}++ resolution: {integrity: sha512-FFUtZMpoZ8RqHS3XeXEmHWLA4thH+ZxCv2lOiPIn1Xc7CxrqhWzNSDzD+/chS/zbYezmiwWLdQC09JdQKmthOw==}+ engines: {node: '>=20'}++ resolution: {integrity: sha512-wpHYzhxiVQL+IV05BLE2Xn34zW1S223hvjtqk0+gsPrwd/8JNLXJgZZM/iPFsYc1xyphF+6M6EvdE5E9MBGkDA==}+ engines: {node: '>=10'}+ hasBin: true++ resolution: {integrity: sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==}+ hasBin: true++ resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==}++ resolution: {integrity: sha512-mxa9E9ITFOt0ban3j6L5MpjwegGz6lBQmM1IJkWeBZGcMxto50+eWdjC/52xDbS2vy0k7vIMK0Fe2wfL9OQSpQ==}++ resolution: {integrity: sha512-SFNOvSJ+Dgf/9An904Yx+CgSlIPCkIpao4qo51lpee25TIRejdH3rhR4EZMGoNx3/TP3O+wzWuiTFl4sqbltzA==}+ hasBin: true++ resolution: {integrity: sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==}+ engines: {node: '>=6'}+ hasBin: true++ resolution: {integrity: sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==}++ resolution: {integrity: sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==}++ resolution: {integrity: sha512-ZClg6AaYvamvYEE82d3Iyd3vSSIjQ+odgjaTzRuO3s7toCdFKczob2i0zCh7JE8kWn17yvAWhUVxvqGwUalsRA==}++ resolution: {integrity: sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==}+ engines: {node: '>=6'}+ hasBin: true++ resolution: {integrity: sha512-m6F1R3z8jjlf2imQHS2Qez5sjKWQzbuuhuJ/FKYFRZvPE3PuHcSMVZzfsLhGVOkfd20obL5SWEBew5ShlquNxg==}++ resolution: {integrity: sha512-zwOTdL3rFQ/lRdBnntKVOX6k5cKJwEc1HdilT71BWEu7J41gXIB2MRp+vxduPSwZJPWBxEzv4yH1wYLJGUHX4Q==}++ resolution: {integrity: sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==}++ resolution: {integrity: sha512-0/BnGCCfyUMkBpeDgWihanIAF9JmZhHBgUhEqzvf+adhNGLoP6TaiI5oF8oyb3I45P+PcnrqihSf01M0l0G5+Q==}++ resolution: {integrity: sha512-qMrZeyEekgdRQ9o6a4NAB2EQZrv827GJdn1vnapwSJ90hWRB4TzUSunvacPkxQ2TnNqHNI1/zSt0hlo0crG8Jw==}++ resolution: {integrity: sha512-GgOXd0Eo6phYgh0DJtjQ2tO8dc0IVINtZJeARPeiIJqge+HdsWSuaDTe8ztQ7j/cONByDZ3zeB325AHiv5O0dg==}++ resolution: {integrity: sha512-d3zZ2k8s6iO+8u9Vfkl6HfhD5lSVocGcmOViTz/i0CJcwhJADyubEJ/+TkBhuLDUSIBOiG+D8G5kJKwXwKbXXA==}++ resolution: {integrity: sha512-0Wd+GPz1O134cP62YU2GTOPNA7Qgl09XwCqM5zpBv87ERCXdfDtyKXvV7c9U22yWJh44QZqBocFnXN11K96qow==}++ resolution: {integrity: sha512-YK7/ClTt4kAK0vo6w3X+Pnm0D2cf2vPHbhOXdoNti1Ga0al1P4TBZhwjATvjNwLEBCnKvjJc2jQgHXH0NEwlAg==}+ engines: {node: '>= 12.0.0'}+ cpu: [arm64]+ os: [android]++ resolution: {integrity: sha512-RzeG9Ju5bag2Bv1/lwlVJvBE3q6TtXskdZLLCyfg5pt+HLz9BqlICO7LZM7VHNTTn/5PRhHFBSjk5lc4cmscPQ==}+ engines: {node: '>= 12.0.0'}+ cpu: [arm64]+ os: [darwin]++ resolution: {integrity: sha512-U+QsBp2m/s2wqpUYT/6wnlagdZbtZdndSmut/NJqlCcMLTWp5muCrID+K5UJ6jqD2BFshejCYXniPDbNh73V8w==}+ engines: {node: '>= 12.0.0'}+ cpu: [x64]+ os: [darwin]++ resolution: {integrity: sha512-JCTigedEksZk3tHTTthnMdVfGf61Fky8Ji2E4YjUTEQX14xiy/lTzXnu1vwiZe3bYe0q+SpsSH/CTeDXK6WHig==}+ engines: {node: '>= 12.0.0'}+ cpu: [x64]+ os: [freebsd]++ resolution: {integrity: sha512-x6rnnpRa2GL0zQOkt6rts3YDPzduLpWvwAF6EMhXFVZXD4tPrBkEFqzGowzCsIWsPjqSK+tyNEODUBXeeVHSkw==}+ engines: {node: '>= 12.0.0'}+ cpu: [arm]+ os: [linux]++ resolution: {integrity: sha512-0nnMyoyOLRJXfbMOilaSRcLH3Jw5z9HDNGfT/gwCPgaDjnx0i8w7vBzFLFR1f6CMLKF8gVbebmkUN3fa/kQJpQ==}+ engines: {node: '>= 12.0.0'}+ cpu: [arm64]+ os: [linux]+ libc: [glibc]++ resolution: {integrity: sha512-UpQkoenr4UJEzgVIYpI80lDFvRmPVg6oqboNHfoH4CQIfNA+HOrZ7Mo7KZP02dC6LjghPQJeBsvXhJod/wnIBg==}+ engines: {node: '>= 12.0.0'}+ cpu: [arm64]+ os: [linux]+ libc: [musl]++ resolution: {integrity: sha512-V7Qr52IhZmdKPVr+Vtw8o+WLsQJYCTd8loIfpDaMRWGUZfBOYEJeyJIkqGIDMZPwPx24pUMfwSxxI8phr/MbOA==}+ engines: {node: '>= 12.0.0'}+ cpu: [x64]+ os: [linux]+ libc: [glibc]++ resolution: {integrity: sha512-bYcLp+Vb0awsiXg/80uCRezCYHNg1/l3mt0gzHnWV9XP1W5sKa5/TCdGWaR/zBM2PeF/HbsQv/j2URNOiVuxWg==}+ engines: {node: '>= 12.0.0'}+ cpu: [x64]+ os: [linux]+ libc: [musl]++ resolution: {integrity: sha512-8SbC8BR40pS6baCM8sbtYDSwEVQd4JlFTOlaD3gWGHfThTcABnNDBda6eTZeqbofalIJhFx0qKzgHJmcPTnGdw==}+ engines: {node: '>= 12.0.0'}+ cpu: [arm64]+ os: [win32]++ resolution: {integrity: sha512-Amq9B/SoZYdDi1kFrojnoqPLxYhQ4Wo5XiL8EVJrVsB8ARoC1PWW6VGtT0WKCemjy8aC+louJnjS7U18x3b06Q==}+ engines: {node: '>= 12.0.0'}+ cpu: [x64]+ os: [win32]++ resolution: {integrity: sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ==}+ engines: {node: '>= 12.0.0'}++ resolution: {integrity: sha512-ONTm2jCMAVZjgQa/Fy1kScXsuOoF5NPTsoFBdE1KVIZ2vAh/r9+Bqo+0jINCBYnavTPQZz38QzFTme79ENoN3Q==}++ resolution: {integrity: sha512-P8aEP5U/D1/IlTY2OeYsErdwh9bGuLE30NcXtKEjgdHcahveQoQwM2yZNsioQHsWFz0P7KKudisbrzCgR0sDHg==}++ resolution: {integrity: sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==}++ resolution: {integrity: sha512-CdzqowRJCeLU72bHvWqwRBBlLcMEtIvGrlvef74kMnV2AolS9Y8xUv1I0U/MNAWMhBlKIoyuEgoJ0t/bbwHbLQ==}++ resolution: {integrity: sha512-tqNXrS78oMOE73NMxK4EMLQsQowWf8jKooH9g7xPavRT706R6bkQJ6DY2Te7QukaZsulxa30wQ7bk0pm4XiHmA==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==}++ resolution: {integrity: sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==}+ engines: {node: '>=10'}++ resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==}++ resolution: {integrity: sha512-O7oCYzWW9YH5lHk/y3Z8R8dFnUq8wqaH146BuU2NDt/3MGjdfMLzGF2Ft7WksTCeq00covNKpwxQabcG3zJFqQ==}+ engines: {node: '>=20.0.0'}++ resolution: {integrity: sha512-OkeDaAZ/bQCxeFAozM55PKcKU0yJMPGifLwV4Qgjitu+5MoAfSQN4lsLJeXZ1b8w0x+/Emda6MZgXS1jvsapng==}+ engines: {node: '>=10'}++ resolution: {integrity: sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==}+ engines: {node: '>= 0.4'}++ resolution: {integrity: sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==}+ engines: {node: '>= 0.6'}++ resolution: {integrity: sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==}+ engines: {node: '>= 0.6'}++ resolution: {integrity: sha512-USPkMeET31rOMiarsBNIHZKLGgvKc/LrjofAnBlOttf5ajRvqiRA8QsenbcooctK6d6Ts6aqZXBA+XbkKthiQg==}+ engines: {node: '>=4.0.0'}+ hasBin: true++ resolution: {integrity: sha512-j5EctnkH7amfV/q5Hgmoal1g2QHFJRraOtmx0JpIqkxhBhI/lJSl1nMpQ45hVarwNETOoWEimndZ4QK0RHxuxQ==}+ engines: {node: '>=4'}++ resolution: {integrity: sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==}+ engines: {node: '>=10'}++ resolution: {integrity: sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==}+ engines: {node: 18 || 20 || >=22}++ resolution: {integrity: sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==}++ resolution: {integrity: sha512-7o1wEA2RyMP7Iu7GNba9vc0RWWGACJOCZBJX2GJWip0ikV+wcOsgVuY9uE8CPiyQhkGFSlhuSkZPavN7u1c2Fw==}+ engines: {node: '>=10'}++ resolution: {integrity: sha512-OBwBN9AL4dqmETlpS2zasx+vTeWclWzkblfZk7KTA5j3jeOONz/tRCnZomUyvNg83wL5Zv9Ss6HMJXAgL8R2Yg==}+ engines: {node: '>=16 || 14 >=14.17'}++ resolution: {integrity: sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==}++ resolution: {integrity: sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==}+ engines: {node: '>=16 || 14 >=14.17'}++ resolution: {integrity: sha512-KZxYo1BUkWD2TVFLr0MQoM8vUUigWD3LlD83a/75BqC+4qE0Hb1Vo5v1FgcfaNXvfXzr+5EhQ6ing/CaBijTlw==}+ engines: {node: '>= 18'}++ resolution: {integrity: sha512-FP+p8RB8OWpF3YZBCrP5gtADmtXApB5AMLn+vdyA+PyxCjrCs00mjyUozssO33cwDeT3wNGdLxJ5M//YqtHAJw==}+ hasBin: true++ resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==}++ resolution: {integrity: sha512-Y2tUNy4ouw6tq5oDSKeQYGOyhkUBhNOcGV/02KC+6kd9eDGqdZd++mjMiIDilrBYvjEnCYvVtsuHCuP+okSfug==}+ engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}+ hasBin: true++ resolution: {integrity: sha512-ymk4aIzxdPopw2giv8Fs1Ec6vybGkjmyxUwVqhkI4MCy2tVfXdkOGGWieWVjL0THgH+7a8lRdevyupoYj3Js/Q==}+ engines: {node: '>=22.12.0'}++ resolution: {integrity: sha512-2xP/IGGMmmSQpI1+O/k72jF/ykvZ89JeuKX3TLJAYPDVLUalrshrLHkeVcCCZqG/eEa635cr8IBYzgnDvM2O8Q==}++ resolution: {integrity: sha512-OMcPNvqTCFUnNaBlmdgq+lfNqY7gTiSmNRDjY3uAXRyudeKZEZxu3CLtjMQrx4zZxCX2b/mpNqTtwuCJgXhHkw==}+ engines: {node: ^20.17.0 || >=22.9.0}+ hasBin: true++ resolution: {integrity: sha512-O5lz91xSOeoXP6DulyHfllpq+Eg00MWitZIbtPfoSEvqIHdl5gfcY6hYzDWnj0qD5tz52PI08u9qUvSVeUBeHw==}++ resolution: {integrity: sha512-x0InOIyzgdk+eyaWaRJFH5snEtiImgBgblZ2CyPrLmqqcuMQkEvcDPHbzqbD8eDsSeJbVOjn+crzyzHaM4D+/A==}+ engines: {node: '>=18'}++ resolution: {integrity: sha512-He9XskOFms62SyAKkLu8CcGcYHAo+BSHSsORI8s4PJH8qZgZY4L4lDfvyN0twvmbpyG+eGrxpyBlskj9d9rJ8A==}+ engines: {node: '>=20.0.0'}++ resolution: {integrity: sha512-Zhq3a+yFKrYwSBluL4H9XP3m3y5uvQkB/09CwDruCiRmR/UJYnn9W4R48ry0uGC70aeTPKLynBtscP9efFFcPw==}+ engines: {node: ^20.17.0 || >=22.9.0}+ hasBin: true++ resolution: {integrity: sha512-DlL+XwOy3NxAQ8xuC0okPgK46iuVNAK01YN7RueYBqqFeGsBjV9XmCAzAdgt+667bCl5kPh9EqKKDwnaPG1I7A==}+ engines: {node: '>=10'}++ resolution: {integrity: sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==}+ engines: {node: '>= 0.4'}++ resolution: {integrity: sha512-0eJJY6hXLGf1udHwfNftBqH+g73EU4B504nZeKpz1sYRKafAghwxEJunB2O7rDZkL4PGfsMVnTXZ2EjibbqcsA==}+ engines: {node: '>=14.0.0'}++ resolution: {integrity: sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==}++ resolution: {integrity: sha512-TvAWxi0nDe1j/rtMcWcIj94+Ffe6n7zhow33h40SKxmsmozs6dz/e+EajymfoFcHd7sxNn8yHM8839uixMOV6g==}++ resolution: {integrity: sha512-BZOr3nRQHOntUjTrH8+Lh54smKHoHyur8We1V8DSMVrl5A2malOOwuJRnKRDjSnkoeBh4at6BwEnb5I7Jl31wg==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==}+ engines: {node: '>=10'}++ resolution: {integrity: sha512-uNBJZzmb60l6p6VWLTmevizNAGnE0xoSf1n0B4q3ntegDNzcS68NRCcBDZTcyXHxt2XhBChsCuqj4M+nChvE/A==}++ resolution: {integrity: sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==}+ engines: {node: '>=0.10.0'}++ resolution: {integrity: sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==}++ resolution: {integrity: sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ==}+ engines: {node: '>= 14.16'}++ resolution: {integrity: sha512-eRWB5LBz7PpDu4PUlwT0PhnQfTQJlDDdPa35urV4Osrm0t0AqQFGn+UIkU3klZvwJ8KPO3VbBFsXquA6p6kqZw==}+ engines: {node: '>=12', npm: '>=6'}++ resolution: {integrity: sha512-80B2AsU+I4Qdb0ZAPSfe9UwvGzwkM37IKIFEvdS3D/3Ndgv2bsuJ0bfG1+iEYO+l7Gfd4EUJmuRyq7efLgRMzQ==}++ resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==}++ resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==}+ engines: {node: '>=12'}++ resolution: {integrity: sha512-wlfUczU+n7Hy/Ha5j9a/gZNy7We5+cXp8YL+X+PG8S0KXxw7n/JXA3c46Y0zQznIJ83URJiwy7Lh56WLokNuxg==}++ resolution: {integrity: sha512-BndPH67/JxGExRgiX1dX0w1FvZck5Wa4aal9198SrRhZjH3GxKQUKIBnYJTdj2HDN3UQAS06HlfcSbQj2OHmaw==}++ resolution: {integrity: sha512-r34yH/GlQpKZbU1BvFFqOjhISRo1MNx1tWYsYvmj6KIRHSPMT2+yHOEb1SG6NMvRoHRF0a07kCOox/9yakl1vg==}+ hasBin: true++ resolution: {integrity: sha512-Oo/NZcSWccq8KyoG7gLE9fnltgHns+pNCjCAp/WmjsUySi+sX7y4z4Xqu4fVb42CDHzRPl33fjzT15V1wvcyhA==}+ engines: {node: '>=16.0.0'}++ resolution: {integrity: sha512-uysumyrvkUX0rX/dEVqt8gC3sTBzd4zoWfLeS29nb53imdaXVvLINYXTI2GNqzaMuvacNx4uJQ8+b3zXR0pkgQ==}+ engines: {node: '>=10.4.0'}++ resolution: {integrity: sha512-RRuzqDtt5Y9h3quz5hWhK+TPnsmVs6WwSU6LkJMeY4HstUEDuYTG8UJSdawMRzmzAtV+KEoG8N3Qg2qLy5vM/A==}+ engines: {node: ^10 || ^12 || >=14}++ resolution: {integrity: sha512-b9Eb8h2eVqNE8edvKdwqkrY6O7kAwmI8kcnBv1NScolYJbo59XUF0noFq+lxbC1yN20bmC0WBEbDC5H/7ASb0A==}+ engines: {node: '>=14.0.0'}+ hasBin: true++ resolution: {integrity: sha512-WRFq3Wn3WId7LLROfMLdH7xaFr2jR62wU8nLO6rQUOLOxNZUviyJQs1M0iIhLexSFy+L+w0ch66wtoO2jRjG0A==}+ engines: {node: '>=14'}+ hasBin: true++ resolution: {integrity: sha512-iG+GYldRf2BQ0UDUAd6JQ/RwzaQy6mXmsk/IzlYyal4A4SNFw54MeH4/tLkF4I5WoWG9SQwuqWzS99jaFQHBuQ==}+ engines: {node: ^20.17.0 || >=22.9.0}++ resolution: {integrity: sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==}++ resolution: {integrity: sha512-jQSaVHsPgtyw60e1rQ/A+/ArPEj/S8pS/vFnyGa/gYFXrKk/6RuDkoqVDQ5NI5MmS01698ltlAk0NoDBNLujRw==}++ resolution: {integrity: sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA==}+ engines: {node: '>=0.4.0'}++ resolution: {integrity: sha512-y+WKFlBR8BGXnsNlIHFGPZmyDf3DFMoLhaflAnyZgV6rG6xu+JwesTo2Q9R6XwYmtmwAFCkAk3e35jEdoeh/3g==}+ engines: {node: '>=10'}++ resolution: {integrity: sha512-TjNPblN4BwAWMXU8s9AEz4JmQxnD1NNL7bNOY/AKUzyamc379FWASUhc/K1pL2noVb+XmZKLL68cjzLsiOAMaA==}++ resolution: {integrity: sha512-J8jqUZ1xybXKY44v3K0c8m8ZTIqJPVT34t2UVyxv4VEWoNd5C9t5Y52GNuMriRJ3IpNxOSE2R60vN4qBrTMcyQ==}++ resolution: {integrity: sha512-q6Q6szxqdu9Xd6EcdKsqXghu5nQdZTpB4Q9yd04WRc7/jt763e/rT60Owh0L1GYY+T46o5rD+9lEN36dZS43tw==}++ resolution: {integrity: sha512-FoYbsJR8gK+DGlqhNoE29Loa38eIZPzQRIb1VMaDNBoo4OLP6vVof/jR8qFY/6XvUd6Dhug8MDCHl2a/h8RTfQ==}++ resolution: {integrity: sha512-pMdYaEnjNMSwl11yjEGtgTmLkR08m/Vl+Jj443167p9eB3HVQKhYCc4gmHVDsLPODfZfjr/MmirsdyZziXbQKw==}++ resolution: {integrity: sha512-zlzTiH01eKA55UAf1MEjtssJeHnGxO0j4K4Dpx+gnmX9n+SHNlDqI2oO1Kv1iPN5B1dm5fsljCfqKF9nFL6HRg==}++ resolution: {integrity: sha512-7wj4uMjKaXWAQ1CDgxNzNtR9AlsuwzHfdFH1ygEHA2KHF2DOEaXl1CJfNPAKCg9qNEh4rum975QLaCiQPyY6Fw==}++ resolution: {integrity: sha512-4HucRlpiLd1IPQQXNqeo81BGtkY8Ai5smHhKW9jjPKRc2wQIxksg7Hl1tTI2IfT2B/LgX6bfYvXxEpJl7aKYKw==}++ resolution: {integrity: sha512-Ue2gTmXMa7EhpLNhC7J+h4+ykD8ha12K6rrZFFKKJHBForfIStw5gJ6Zrf1mqqAa9NmpmEB4wp9bKmA4eUVjWg==}++ resolution: {integrity: sha512-927lFx/uwyQaGwJxLWCZRkjXG0p48KpMj6ueoYiu4JX05GGuGcgzAy62dfiV8eFZftgyBUvLx76RsMe20fJl+Q==}++ resolution: {integrity: sha512-6jiYHH2CIGbCfnxdHbXZ12gySFY/fz/ulZE333G6bPqIZ4F+TXo9ifiR86nAHpWnfoNjOb3o5ESi7J8Uz1jXHw==}++ resolution: {integrity: sha512-V/0cDCsHKHe/tfWkeCmthNUcEp1IVO3p6vwN8XtwE9PZQLAZJigbw3QoraAdfJPir4NKJtNvOB8oYGKRl+t0Dw==}++ resolution: {integrity: sha512-t4F5615FycnCqsX7ShTUs8+jfnwcf46kuFRvSl/3qFx2QTZ4DjgowesLHQXcFP7G//TjesqZG3WtgL7vdyVJyA==}++ resolution: {integrity: sha512-7qcRaCWM48NC4utNQnx5Obvvs48/jMHXXvOXHH6WlBojmiK15eyxoHYlv5aJARHJHiFccSuWZ7ULW2SPrFAS/g==}++ resolution: {integrity: sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==}++ resolution: {integrity: sha512-uxFIHU0YlHYhDQtV4R9J6a52SLx28BCjT+4ieh7IGbgwVJWO+km431c4yRlREUAsAmt/uMjQUyQHNEPf0M39CA==}+ engines: {node: '>=6'}++ resolution: {integrity: sha512-PLgQXQ6H2FWCaeRak8vvk1GW462lMxB5s3Jm673N82zI4vqtVUPuZdffdZbPDFRoU8kAhItWFtPCWiPpp4/EDg==}++ resolution: {integrity: sha512-BbubeCEyTuQjVMakvJQ/Sxbc93F2pwmbsxONT/ZRrwU7Ua38d8unYTwXpTVLAKJ4BDuH9IGztCjQcd/N/39Dvg==}+ engines: {node: '>=16.0.0'}++ resolution: {integrity: sha512-tYC1Q1hgyRuHgloV/YXs2w15unPVh8qfu/qCTfhTYamaw7fyhumKa2yGpdSo87vY32rIclj+4fWYQXUMs9EHvg==}++ resolution: {integrity: sha512-WuyALRjWPDGtt/wzJiadO5AXY+8hZ80hVpe6MyivgraREW751X3SbhRvG3eLKOYN+8VEvqLcf3wdnt44Z4S4SA==}+ engines: {node: '>=10'}++ resolution: {integrity: sha512-tBaoDWjPwe0M5pGrum4H0SR6Lyk+BO9oHnp9JbKpGKW2mlraNPgP9BMfsg5pWpwrssARmeqk7YBl2oXutZTaHA==}+ engines: {node: '>=18'}+ peerDependencies:+ react: '>=16.8.0'++ resolution: {integrity: sha512-JDk8dgif51OjFoDE70+OT9ICyYr+69HlmihNwp1+Nsfbna3t5sIiCa9ZJktDmQ4/1b/rn26hIAR2uYXDMr5r0Q==}+ peerDependencies:+ react: ^19.3.0++ resolution: {integrity: sha512-QgT5//D3jfjJb6Gsjxv0Slpj23ip+HtOpnNgnb2S5zU3CB26G/IDPGoy4RJB42wzFE46DRsstbW6tKHoKbhAxw==}+ engines: {node: '>=0.10.0'}++ resolution: {integrity: sha512-E8LUcbtBWt20bbl2YoHfx4ZDBdxVTfOKtCZn9cDSJ4l6/nuoApcpIBcj47t2wZoVX8g2ZHuMHbiShgCR1T5Sog==}+ engines: {node: '>=0.10.0'}++ resolution: {integrity: sha512-BNg9EN3DD3GsDXX7Aa8O4p92sryjkmzYYgmgTAc6CA4uGLEDzFfxOxugu21akOxpcXHiEgsYkC6nPsQvLLLmEg==}+ hasBin: true++ resolution: {integrity: sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==}++ resolution: {integrity: sha512-57frrGM/OCTLqLOAh0mhVA9VBMHd+9U7Zb2THMGdBUoZVOtGbJzjxsYGDJ3A9AYYCP4hn6y1TVbaOfzWtm5GFg==}+ engines: {node: '>= 12.13.0'}++ resolution: {integrity: sha512-P4nbQYQfePJxRSmY+v/KINxVucm4NF3p3s7pJveMTtom52FR4YGltUQLB8idDXwDDWW+eYrWDFbuzUnjoWHF7g==}++ resolution: {integrity: sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==}+ engines: {node: '>=0.10.0'}++ resolution: {integrity: sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==}+ engines: {node: '>=0.10.0'}++ resolution: {integrity: sha512-vHjcY2MlAITJhC0eRD/Vv8Vlgmu9Sd3LX9zZvtGzU5ZImdTN3+d6e/4mnTyV8vEbyf1sgNIrWxhWlrys52OkEA==}+ engines: {node: '>=12', npm: '>=6'}++ resolution: {integrity: sha512-XGoLeRAVzUTcJ1qkxPQhDJyIZ5d6zzZD9nT7AEZOaaU9UbWclhycElmhO+VD5bFeLuzhPBaOV2oXC8uG35ZSpg==}++ resolution: {integrity: sha512-0a1F4l73/ZFZOakJnQ3FvkJ2+gSTQWz/r2KE5OdDY0TxPm5h4GkqkWWfM47T7HsbnOtcJVEF4epCVy6u7Q3K+g==}++ resolution: {integrity: sha512-4gl03wn3hj1HP3yzgdI7d3lCkF95F21Pz4BPGvKHinyQzALR5CapwC8yIi0Rh58DEMQ/SguC03wFj2k0M/mHhw==}++ resolution: {integrity: sha512-9LkiTwjUh6rT555DtE9rTX+BKByPfrMzEAtnlEtdEwr3Nkffwiihqe2bWADg+OQRjt9gl6ICdmB/ZFDCGAtSow==}+ engines: {node: '>= 4'}++ resolution: {integrity: sha512-mwqeW5XsA2qAejG46gYdENaxXjx9onRNCfn7L0duuP4hCuTIi/QO7PDK07KJfp1d+izWPrzEJDcSqBa0OZQriA==}+ deprecated: Rimraf versions prior to v4 are no longer supported+ hasBin: true++ resolution: {integrity: sha512-CHhPh+UNHD2GTXNYhPWLnU8ONHdI+5DI+4EYIAOaiD63rHeYlZvyh8P+in5999TTSFgUYuKUAjzRI4mdh/p+2A==}+ engines: {node: '>=8.0'}++ resolution: {integrity: sha512-4U0liVayNIoLp3GFl1FcI8561WepLnZ1rqfraGh7S9B3Ur5F9S283y8Futii7RUU2C/97tOBmBy7nYvhoiOpbQ==}+ engines: {node: '>=18.0.0', npm: '>=8.0.0'}+ hasBin: true++ resolution: {integrity: sha512-UT5EDe2cu2E/6O4igUr5PSFs23nvvukicWHx6GnOPlHAiiYbzNuCRQCuiUdHJQcqKalLKlrYJnjY0ySGsXNQXQ==}++ resolution: {integrity: sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==}++ resolution: {integrity: sha512-b3rppTKm9T+PsVCBEOUR46GWI7fdOs00VKZ1+9c1EWDaDMvjQc6tUwuFyIprgGgTcWoVHSKrU8H31ZHA2e0RHA==}+ engines: {node: '>=10'}++ resolution: {integrity: sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==}++ resolution: {integrity: sha512-9ZyI08PsvdQl2r/bBIGubpVdR3RR9sY6RDiWFPreA21C/EFlQhmgo20UZlNjZMMZNubusLhAQozkA0Od5J21Eg==}++ resolution: {integrity: sha512-42tBVwLWnaQvW5zc4HbZrTuWccECCZfBi92FDuwtqxasH+JbPB3/FOKb1m222K42R4WxuxzzMsTswfzgtSu64Q==}+ engines: {node: '>=11.0.0'}++ resolution: {integrity: sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw==}++ resolution: {integrity: sha512-b1YMh3+DHZp59DLna3qVwQ5iOla/nrI6mLBNW02XxU77M3046Df6VLkoaJyFz20VsGIG5kkp+FK0kg4K4HnUFw==}++ resolution: {integrity: sha512-YM3/ITh2MJ5MtzaM429anh+x2jiLVjqILF4m4oyQB18W7Ggea7BfqdH/wGMK7dDiMghv/6WG7znWMwUDzJiXow==}++ resolution: {integrity: sha512-cBznnQ9KjJqU67B52RMC65CMarK2600WFnbkcaiwWq3xy/5haFJlshgnpjovMVJ+Hff49d8GEn0b87C5pDQ10g==}+ hasBin: true++ resolution: {integrity: sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==}+ hasBin: true++ resolution: {integrity: sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==}+ engines: {node: '>=10'}+ hasBin: true++ resolution: {integrity: sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==}+ engines: {node: '>=10'}+ hasBin: true++ resolution: {integrity: sha512-8I8TjW5KMOKsZQTvoxjuSIa7foAwPWGOts+6o7sgjz41/qMD9VQHEDxi6PBvK2l0MXUmqZyNpUK+T2tQaaElvw==}+ engines: {node: '>=10'}++ resolution: {integrity: sha512-4Nk35ttD3DTDJW4hgw5StsVAPeU6qnDFnULAouw6tQ7oLTV/ICXrWpsXo2EE52eSP2joUMazbVf52mFEcADqRw==}+ engines: {node: '>=10'}+ peerDependencies:+ seroval: ^1.0++ resolution: {integrity: sha512-AeDcLh0yO2SFm9W71essgnSzLV9DI8ZH0x0knXn2DMnUZj728mpLbxjlbB6IqKCmqh8JA3cEqRyGoNkt584JcQ==}+ engines: {node: '>=10'}++ resolution: {integrity: sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==}++ resolution: {integrity: sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==}++ resolution: {integrity: sha512-a2B9Y0KlNXl9u/vsW6sTIu9vGEpfKu2wRV6l1H3XEas/0gUIzGzBoP/IouTcUQbm9JWZLH3COxyn03TYlFax6w==}+ engines: {node: '>=10'}++ resolution: {integrity: sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg==}+ engines: {node: '>= 6.0.0', npm: '>= 3.0.0'}++ resolution: {integrity: sha512-W1CjNcrPqW4+1gUOYRyjPvTOxu7GgKR9+7l50yQBF0GM8v8jpYwheHFCHX7s+p7pYI8iXKQQZiF2Rv2Na/3i2g==}+ engines: {node: '>=20.0.0'}++ resolution: {integrity: sha512-e0VyvkVTwVYViNovRkZ9aodhxVlyoMn7eJhVUPxZ+eK9P/7CBkxvvsBOHqFPEH416726W8tLXXXjKwqgTErrCQ==}+ engines: {node: '>= 10.0.0', npm: '>= 3.0.0'}++ resolution: {integrity: sha512-w6AxtubXa2wTXAUsZMMWERrsIRAdrK0Sc+FUytWvYAhBJLyuI4llrMIC1DtlNSdI99EI86KZum2MMq3EAZlF9Q==}++ resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==}+ engines: {node: '>=0.10.0'}++ resolution: {integrity: sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==}++ resolution: {integrity: sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==}+ engines: {node: '>=0.10.0'}++ resolution: {integrity: sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==}+ engines: {node: '>= 10.x'}++ resolution: {integrity: sha512-Oo+0REFV59/rz3gfJNKQiBlwfHaSESl1pcGyABQsnnIfWOFt6JNj5gCog2U6MLZ//IGYD+nA8nI+mTShREReaA==}++ resolution: {integrity: sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==}++ resolution: {integrity: sha512-jH9EhtKIjuXZ2cWxmXS8ZP80XyC3iasQxMDV8jzhNJpfDb7VbQLVW4Wvsxz9QZvzV+G4YoSfBUVKDOyxLzi/sg==}+ engines: {node: '>= 6'}++ resolution: {integrity: sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==}++ resolution: {integrity: sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==}++ resolution: {integrity: sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-8r3mkIM/2+PpjHoOtiAW8Rg3jJLHaV7xPwG+YRGrv6FP0wwk/toTpATxWYOW0BKdWwl82VT2tFYi5DlROa0Mxg==}++ resolution: {integrity: sha512-MvjXzkz/BOfyVDkG0oFOtBxHX2u3gKbMHIF/dXblZsgD3BWOFLmHovIpZY7BykJdAjcqRCBi1WYBNdEC9yI7vg==}+ engines: {node: '>= 8.0'}++ resolution: {integrity: sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-XPPUyAc+cvspz3lHTcR/QgPfW2A0lv/xQNIjX3HGhLR+Nq2lHaLq5MtTesHn8GUr3W3DguT2KT5x3NVgRtYwmA==}++ resolution: {integrity: sha512-gOhV3P7ufE62QDGg1zVaTgCR+EtPv92k2nIhVcVKcLmxT1sUBsQGhnZj175j+MqRt4zLF7ic+sCYjfhxMxj7YQ==}++ resolution: {integrity: sha512-uxc/zpqFg6x7C8vOE7lh6Lbda8eEL9zmVm/PLeTPBRhh1xCgdWaQ+J1CUieGpIfm2HdtsUpRv+HshiasBMcc6A==}+ engines: {node: '>=6'}++ resolution: {integrity: sha512-MFO/QzvtAOmJbkhOaCTvbGcFN9L9b+JunIsDwaKljSOdcLMea3NJ1k9Usz/rjdfSXTq4dfzfeS7W4p4YOAAHeA==}+ engines: {node: '>=18'}++ resolution: {integrity: sha512-C5tjlC/HCtVUOi3KWVokd4vHVViOmGjtLwIh4MuzPo/nMYTV/p1urt3RnMz2IWXDdKEGJH3k5+KPxtqRsUYGtg==}++ resolution: {integrity: sha512-yYrrsWnrXMcdsnu/7YMYAofM1ktpL5By7vZhf15CrXijWWrEYZks5AXBudalfSWJLlnen/QUJUB5aoB0kqZUGA==}+ engines: {node: '>=6.0.0'}++ resolution: {integrity: sha512-e2zZ96wSChazBsbENf/Pcm/4swHt2cEKQ92rhUjkL9GCKiTDJIaTBenjE/m9DXi0QBmTMDkFDdOomUy20A1tDQ==}+ engines: {node: '>=20'}++ resolution: {integrity: sha512-01EAw5EDrcVrdgyCLgoSPvqznC0sVxDSVeiOz09FUpjh71G79VCqneOr+xvt7T1r76CF6ZZfPjHorN2+d+3mqA==}++ resolution: {integrity: sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==}++ resolution: {integrity: sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA==}++ resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==}+ engines: {node: '>=12.0.0'}++ resolution: {integrity: sha512-Zba82s87IFq9A9XmjiX5uZA/ARWDrB03OHlq+Vw1fSdt0I+4/Kutwy8BP4Y/y/aORMo61FQ0vIb5j44vSo5Pkg==}+ engines: {node: ^18.0.0 || >=20.0.0}++ resolution: {integrity: sha512-op4nsTR47R6p0vMUUoYl/a+ljLFVtlfaXkLQmqfLR1qHma1h/ysYk4hEXZ880bf2CYgTskvTa/e196Vd5dDQXw==}+ engines: {node: '>=14.0.0'}++ resolution: {integrity: sha512-u8KszXvGfU68hVcZpRHKG28T0krMuv2G5nDhiHaMLen/gIuFEgIJhaJuO69qjnXg5paSrbPMFfx3brNuN8eVSg==}+ engines: {node: '>=14.0.0'}++ resolution: {integrity: sha512-QXqwfEl9ddlGBaRFXIvNKK6OhipSiLXuRuLJX5DErz0o0Q0rYxulWLdFryTkV5PkdZct5iMInwYEGe/eR++1AA==}+ hasBin: true++ resolution: {integrity: sha512-RwM7MoPojPxsOBYnyd2hy0bxtIlVrihNs9pj5SUvY8Zz1sQcQG2tG1hSr8PDxfgEB8RNKDhqbIlroIarSNDNsQ==}++ resolution: {integrity: sha512-e0votIpp4Uo2AJYSzVHV6xCcawuiez3DzqDAbrTc3YxBkplN6e+dM13ZeIcZnDg/QpSuU2zfZ3rzwY8ukEnaXw==}+ engines: {node: '>=14.14'}++ resolution: {integrity: sha512-95Pu1QXQvruGEhv62XCMO3Mm90GscOCClvrIUwCM0PYOXK3kaF3l3sIHxx71ThJfcbM2O5Au6SO3AWCSEfW4mQ==}++ resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==}++ resolution: {integrity: sha512-s0GhnWXlAAN+wb2GRMQxnZgFweRWTAceRWW/4Lk9iHj7QuLZMjDxQQqu+Xoh7Nckuy8UiSim520w6yqP2+ertw==}+ hasBin: true++ resolution: {integrity: sha512-34R7HTnG0XIJcBSn5XhDd7nNFPRcXYRZrBB2O2jdKqYODldSzBAqzsWoZYYvduky73toYS/ESqxPvkDf/F0XMg==}+ engines: {node: '>=10'}++ resolution: {integrity: sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==}+ engines: {node: '>=14.17'}+ hasBin: true++ resolution: {integrity: sha512-ARDJmphmdvUk6Glw7y9DQ2bFkKBHwQHLi2lsaH6PPmz/Ka9sFOBsBluozhDltWmnv9u/cF6Rt87znRTPV+yp/A==}++ resolution: {integrity: sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w==}++ resolution: {integrity: sha512-zWpdTVD54H48CIybL0rWQ3ukpb9d23wM7eH5RtfdmeP70cWHNjtfo7P4vZX+5CoDcO53J4Pu5uXp7lNfjc6DRA==}+ engines: {node: '>=18.17'}++ resolution: {integrity: sha512-RYONW2MeafgYlkVOKYKkA/Ag7BmXqgIWCa8t1m0JcxrQg9pI9lEqRhAOruOBCbAohOa/gkCF+iPi9hrgvTzu6Q==}+ engines: {node: '>=20.18.1'}++ resolution: {integrity: sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg==}+ engines: {node: '>= 4.0.0'}++ resolution: {integrity: sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==}+ engines: {node: '>= 10.0.0'}++ resolution: {integrity: sha512-tXYOi9R57Uj/2Z25SOs5RRSzq886MBQj2gY8dPL+xl/kv6s6SvByoKfAtvfVeEuhntWDgjd2o9p2lb4TVPAz0A==}++ resolution: {integrity: sha512-pJ2sYawQS0R/WI928Gj5GlPhTGzbMelq0+4INtSYNDV9ErKJcX6xjGWkoG/VnB3dpUm00zALaqkrUD77pO5TDQ==}+ hasBin: true+ peerDependencies:+ browserslist: '>= 4.21.0'++ resolution: {integrity: sha512-6L+EeigHMQhdaIPNIFUKwfWJSwWFQ8gJbJ2DLOs5sDIegTwR9fRxvnM3uciHKjIZhFz+KAv2emhWMRvDmMcY8A==}+ peerDependencies:+ react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0++ resolution: {integrity: sha512-Xn0w3MtiQ6zoz2vFyUVruaCL53O/DwUvkEeOvj+uulMm0BkUGYWmBYVyElqZaSLhY6ZD0ulfU3aBra2aVT4xfA==}++ resolution: {integrity: sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==}++ resolution: {integrity: sha512-EbKSKh+bh1E1IFxeO0pg1n4dvoOTt0UDiXMd/qn++r98+jPO1xtJilvXldeuQ8giIB5IkpjCgMleHMNEsGH6pg==}+ engines: {node: ^18.0.0 || ^20.0.0 || >=22.0.0}+ hasBin: true++ resolution: {integrity: sha512-4XP60spRGjSZFf1qYH+dJIkK2znL3zQfl9KkOV9MkkRR/3Dls0dxaBsQPTloEc5BLXWPL9vsOxopxyKoMmDueg==}+ engines: {node: ^20.19.0 || >=22.12.0}+ hasBin: true+ peerDependencies:+ '@types/node': ^20.19.0 || >=22.12.0+ jiti: '>=1.21.0'+ less: ^4.0.0+ lightningcss: ^1.21.0+ sass: ^1.70.0+ sass-embedded: ^1.70.0+ stylus: '>=0.54.8'+ sugarss: ^5.0.0+ terser: ^5.16.0+ tsx: ^4.8.1+ yaml: ^2.4.2+ peerDependenciesMeta:+ '@types/node':+ optional: true+ jiti:+ optional: true+ less:+ optional: true+ lightningcss:+ optional: true+ sass:+ optional: true+ sass-embedded:+ optional: true+ stylus:+ optional: true+ sugarss:+ optional: true+ terser:+ optional: true+ tsx:+ optional: true+ yaml:+ optional: true++ resolution: {integrity: sha512-KrxIJ62Fd89gfysR4WotlgZABiz2dqFPgqGzX7s+CwsqLFomRH7777ZcrOD6+WVAh7khPQP41A+BKbpcJFrdEg==}+ engines: {node: ^18.0.0 || ^20.0.0 || >=22.0.0}+ hasBin: true+ peerDependencies:+ '@edge-runtime/vm': '*'+ '@types/debug': ^4.1.12+ '@types/node': ^18.0.0 || ^20.0.0 || >=22.0.0+ '@vitest/browser': 3.2.7+ '@vitest/ui': 3.2.7+ happy-dom: '*'+ jsdom: '*'+ peerDependenciesMeta:+ '@edge-runtime/vm':+ optional: true+ '@types/debug':+ optional: true+ '@types/node':+ optional: true+ '@vitest/browser':+ optional: true+ '@vitest/ui':+ optional: true+ happy-dom:+ optional: true+ jsdom:+ optional: true++ resolution: {integrity: sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ==}++ resolution: {integrity: sha512-gsXecm82UQNlTBURJGuqOWy1Ww08S3kZUcr3aOJS02Pk0xLtkfeUAVC0u0xhgdonFme80edSJUIJyuvL/7250Q==}++ resolution: {integrity: sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==}+ engines: {node: '>= 8'}+ hasBin: true++ resolution: {integrity: sha512-JEdGzHwwkrbWoGOlIHqQ5gtprKGOenpDHpxE9zVR1bWbOtYRyPPHMe9FaP6x61CmNaTThSkb0DAJte5jD+DmzQ==}+ engines: {node: ^18.17.0 || >=20.5.0}+ hasBin: true++ resolution: {integrity: sha512-oGLe46MIrCRqX7ytPUf66EAYvdeMIZYn3WaocqqKZAxrBpkqHfL/qvTyJ/bTk5+AqHCjXmrv3CEWgy368zhRUg==}+ engines: {node: ^20.17.0 || >=22.9.0}+ hasBin: true++ resolution: {integrity: sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==}+ engines: {node: '>=8'}+ hasBin: true++ resolution: {integrity: sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==}+ engines: {node: '>=10'}++ resolution: {integrity: sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==}++ resolution: {integrity: sha512-yMqGBqtXyeN1e3TGYvgNgDVZ3j84W4cwkOXQswghol6APgZWaff9lnbvN7MHYJOiXsvGPXtjTYJEiC9J2wv9Eg==}+ engines: {node: '>=8.0'}++ resolution: {integrity: sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==}+ engines: {node: '>=10'}++ resolution: {integrity: sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==}++ resolution: {integrity: sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==}++ resolution: {integrity: sha512-YgvUTfwqyc7UXVMrB+SImsVYSmTS8X/tSrtdNZMImM+n7+QTriRXyXim0mBrTXNeqzVF0KWGgHPeiyViFFrNDw==}+ engines: {node: '>=18'}++ resolution: {integrity: sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==}+ engines: {node: '>=12'}++ resolution: {integrity: sha512-GZtjxm/J/4TSxuL3FNYjCmLktBTnIw/rVmKSIyKeYAZpmJB2ig9VauCC5xsa82GNKVKDAqpOn3KVzNt0zmrU0g==}+ engines: {node: '>=12'}++ resolution: {integrity: sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==}+ engines: {node: '>=10'}++ resolution: {integrity: sha512-v5l/aFXZQeai4awLbOpSoHecE9UiMrnfx75tEXLjNonXVARxQ5mOeipTjROUchszUNCqnE+hqAMujRsRHsut2Q==}++snapshots:++ '@babel/[email protected]':+ dependencies:+ '@babel/helper-validator-identifier': 7.29.7+ js-tokens: 4.0.0+ picocolors: 1.1.1++ '@babel/[email protected]': {}++ '@babel/[email protected]([email protected])':+ dependencies:+ '@babel/code-frame': 7.29.7+ '@babel/generator': 7.29.8+ '@babel/helper-compilation-targets': 7.29.7+ '@babel/helper-module-transforms': 7.29.7(@babel/[email protected]([email protected]))([email protected])+ '@babel/helpers': 7.29.7+ '@babel/parser': 7.29.9+ '@babel/template': 7.29.7+ '@babel/traverse': 7.29.8([email protected])+ '@babel/types': 7.29.8+ '@jridgewell/remapping': 2.3.5+ convert-source-map: 2.0.0+ debug: 4.4.3([email protected])+ gensync: 1.0.0-beta.2+ json5: 2.2.3+ semver: 6.3.1+ transitivePeerDependencies:+ - supports-color++ '@babel/[email protected]':+ dependencies:+ '@babel/parser': 7.29.9+ '@babel/types': 7.29.8+ '@jridgewell/gen-mapping': 0.3.13+ '@jridgewell/trace-mapping': 0.3.31+ jsesc: 3.1.0++ '@babel/[email protected]':+ dependencies:+ '@babel/compat-data': 7.29.7+ '@babel/helper-validator-option': 7.29.7+ browserslist: 4.29.0+ lru-cache: 5.1.1+ semver: 6.3.1++ '@babel/[email protected]': {}++ '@babel/[email protected]([email protected])':+ dependencies:+ '@babel/traverse': 7.29.8([email protected])+ '@babel/types': 7.29.8+ transitivePeerDependencies:+ - supports-color++ dependencies:+ '@babel/core': 7.29.7([email protected])+ '@babel/helper-module-imports': 7.29.7([email protected])+ '@babel/helper-validator-identifier': 7.29.7+ '@babel/traverse': 7.29.8([email protected])+ transitivePeerDependencies:+ - supports-color++ '@babel/[email protected]': {}++ '@babel/[email protected]': {}++ '@babel/[email protected]': {}++ '@babel/[email protected]': {}++ '@babel/[email protected]':+ dependencies:+ '@babel/template': 7.29.7+ '@babel/types': 7.29.8++ '@babel/[email protected]':+ dependencies:+ '@babel/types': 7.29.8++ dependencies:+ '@babel/core': 7.29.7([email protected])+ '@babel/helper-plugin-utils': 7.29.7++ dependencies:+ '@babel/core': 7.29.7([email protected])+ '@babel/helper-plugin-utils': 7.29.7++ dependencies:+ '@babel/core': 7.29.7([email protected])+ '@babel/helper-plugin-utils': 7.29.7++ '@babel/[email protected]': {}++ '@babel/[email protected]':+ dependencies:+ '@babel/code-frame': 7.29.7+ '@babel/parser': 7.29.9+ '@babel/types': 7.29.8++ '@babel/[email protected]([email protected])':+ dependencies:+ '@babel/code-frame': 7.29.7+ '@babel/generator': 7.29.8+ '@babel/helper-globals': 7.29.7+ '@babel/parser': 7.29.9+ '@babel/template': 7.29.7+ '@babel/types': 7.29.8+ debug: 4.4.3([email protected])+ transitivePeerDependencies:+ - supports-color++ '@babel/[email protected]':+ dependencies:+ '@babel/helper-string-parser': 7.29.7+ '@babel/helper-validator-identifier': 7.29.7++ '@base-ui/[email protected](@date-fns/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected])':+ dependencies:+ '@babel/runtime': 7.29.7+ '@base-ui/utils': 0.4.0(@types/[email protected])([email protected]([email protected]))([email protected])+ '@floating-ui/utils': 0.2.12+ react: 19.3.0+ react-dom: 19.3.0([email protected])+ use-sync-external-store: 1.7.0([email protected])+ optionalDependencies:+ '@date-fns/tz': 1.5.0+ '@types/react': 19.3.0+ date-fns: 4.4.0++ '@base-ui/[email protected](@types/[email protected])([email protected]([email protected]))([email protected])':+ dependencies:+ '@babel/runtime': 7.29.7+ '@floating-ui/utils': 0.2.12+ react: 19.3.0+ react-dom: 19.3.0([email protected])+ reselect: 5.3.0+ use-sync-external-store: 1.7.0([email protected])+ optionalDependencies:+ '@types/react': 19.3.0++ '@date-fns/[email protected]': {}++ '@electron-internal/[email protected]': {}++ '@electron/[email protected]':+ dependencies:+ commander: 5.1.0+ glob: 7.2.3+ minimatch: 3.1.5++ '@electron/[email protected]':+ dependencies:+ chalk: 4.1.2+ fs-extra: 9.1.0+ minimist: 1.2.8++ '@electron/[email protected]([email protected])':+ dependencies:+ debug: 4.4.3([email protected])+ env-paths: 2.2.1+ fs-extra: 8.1.0+ got: 11.8.6+ progress: 2.0.3+ semver: 6.3.1+ sumchecker: 3.0.1([email protected])+ optionalDependencies:+ global-agent: 3.0.0+ transitivePeerDependencies:+ - supports-color++ '@electron/[email protected]([email protected])':+ dependencies:+ debug: 4.4.3([email protected])+ env-paths: 3.0.0+ graceful-fs: 4.2.11+ progress: 2.0.3+ semver: 7.8.5+ sumchecker: 3.0.1([email protected])+ optionalDependencies:+ undici: 7.29.1+ transitivePeerDependencies:+ - supports-color++ '@electron/[email protected]([email protected])':+ dependencies:+ debug: 4.4.3([email protected])+ fs-extra: 9.1.0+ promise-retry: 2.0.1+ transitivePeerDependencies:+ - supports-color++ '@electron/[email protected]([email protected])':+ dependencies:+ compare-version: 0.1.2+ debug: 4.4.3([email protected])+ fs-extra: 10.1.0+ isbinaryfile: 4.0.10+ minimist: 1.2.8+ plist: 3.1.0+ transitivePeerDependencies:+ - supports-color++ '@electron/[email protected]([email protected])':+ dependencies:+ '@malept/cross-spawn-promise': 2.0.0+ debug: 4.4.3([email protected])+ node-abi: 4.35.0+ node-api-version: 0.2.1+ node-gyp: 12.4.0+ read-binary-file-arch: 1.0.6([email protected])+ transitivePeerDependencies:+ - supports-color++ '@electron/[email protected]([email protected])':+ dependencies:+ '@electron/asar': 3.4.1+ '@malept/cross-spawn-promise': 2.0.0+ debug: 4.4.3([email protected])+ dir-compare: 4.2.0+ fs-extra: 11.4.0+ minimatch: 9.0.9+ plist: 3.1.0+ transitivePeerDependencies:+ - supports-color++ '@electron/[email protected]([email protected])':+ dependencies:+ cross-dirname: 0.1.0+ debug: 4.4.3([email protected])+ fs-extra: 11.4.0+ minimist: 1.2.8+ postject: 1.0.0-alpha.6+ transitivePeerDependencies:+ - supports-color+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@floating-ui/[email protected]':+ dependencies:+ '@floating-ui/utils': 0.2.12++ '@floating-ui/[email protected]':+ dependencies:+ '@floating-ui/core': 1.8.0+ '@floating-ui/utils': 0.2.12++ dependencies:+ '@floating-ui/dom': 1.8.0+ react: 19.3.0+ react-dom: 19.3.0([email protected])++ '@floating-ui/[email protected]': {}++ '@hugeicons/[email protected]': {}++ '@hugeicons/[email protected]([email protected])':+ dependencies:+ react: 19.3.0++ '@isaacs/[email protected]':+ dependencies:+ minipass: 7.1.3++ '@jridgewell/[email protected]':+ dependencies:+ '@jridgewell/sourcemap-codec': 1.6.0+ '@jridgewell/trace-mapping': 0.3.31++ '@jridgewell/[email protected]':+ dependencies:+ '@jridgewell/gen-mapping': 0.3.13+ '@jridgewell/trace-mapping': 0.3.31++ '@jridgewell/[email protected]': {}++ '@jridgewell/[email protected]': {}++ '@jridgewell/[email protected]':+ dependencies:+ '@jridgewell/resolve-uri': 3.1.2+ '@jridgewell/sourcemap-codec': 1.6.0++ '@malept/[email protected]':+ dependencies:+ cross-spawn: 7.0.6++ '@malept/[email protected]([email protected])':+ dependencies:+ debug: 4.4.3([email protected])+ fs-extra: 9.1.0+ lodash: 4.18.1+ tmp-promise: 3.0.3+ transitivePeerDependencies:+ - supports-color++ '@napi-rs/[email protected]':+ optional: true++ '@noble/[email protected]': {}++ '@noble/[email protected]': {}++ '@peculiar/[email protected]':+ dependencies:+ '@peculiar/utils': 2.0.3+ asn1js: 3.0.10+ tslib: 2.8.1++ '@peculiar/[email protected]':+ dependencies:+ tslib: 2.8.1++ '@peculiar/[email protected]':+ dependencies:+ tslib: 2.8.1++ '@peculiar/[email protected]':+ dependencies:+ '@peculiar/asn1-schema': 2.9.5+ '@peculiar/json-schema': 1.1.12+ '@peculiar/utils': 2.0.3+ tslib: 2.8.1+ webcrypto-core: 1.9.2++ '@pinojs/[email protected]': {}++ '@rolldown/[email protected]': {}++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@selderee/[email protected]([email protected])':+ dependencies:+ domelementtype: 2.3.0+ domhandler: 5.0.3+ selderee: 0.12.0++ '@sindresorhus/[email protected]': {}++ '@szmarczak/[email protected]':+ dependencies:+ defer-to-connect: 2.0.1++ '@tabby_ai/[email protected]': {}++ '@tailwindcss/[email protected]':+ dependencies:+ '@jridgewell/remapping': 2.3.5+ enhanced-resolve: 5.25.1+ jiti: 2.7.0+ lightningcss: 1.32.0+ magic-string: 0.30.21+ source-map-js: 1.2.1+ tailwindcss: 4.3.3++ '@tailwindcss/[email protected]':+ optional: true++ '@tailwindcss/[email protected]':+ optional: true++ '@tailwindcss/[email protected]':+ optional: true++ '@tailwindcss/[email protected]':+ optional: true++ '@tailwindcss/[email protected]':+ optional: true++ '@tailwindcss/[email protected]':+ optional: true++ '@tailwindcss/[email protected]':+ optional: true++ '@tailwindcss/[email protected]':+ optional: true++ '@tailwindcss/[email protected]':+ optional: true++ '@tailwindcss/[email protected]':+ optional: true++ '@tailwindcss/[email protected]':+ optional: true++ '@tailwindcss/[email protected]':+ optional: true++ '@tailwindcss/[email protected]':+ optionalDependencies:+ '@tailwindcss/oxide-android-arm64': 4.3.3+ '@tailwindcss/oxide-darwin-arm64': 4.3.3+ '@tailwindcss/oxide-darwin-x64': 4.3.3+ '@tailwindcss/oxide-freebsd-x64': 4.3.3+ '@tailwindcss/oxide-linux-arm-gnueabihf': 4.3.3+ '@tailwindcss/oxide-linux-arm64-gnu': 4.3.3+ '@tailwindcss/oxide-linux-arm64-musl': 4.3.3+ '@tailwindcss/oxide-linux-x64-gnu': 4.3.3+ '@tailwindcss/oxide-linux-x64-musl': 4.3.3+ '@tailwindcss/oxide-wasm32-wasi': 4.3.3+ '@tailwindcss/oxide-win32-arm64-msvc': 4.3.3+ '@tailwindcss/oxide-win32-x64-msvc': 4.3.3++ '@tailwindcss/[email protected]([email protected](@types/[email protected])([email protected])([email protected]))':+ dependencies:+ '@tailwindcss/node': 4.3.3+ '@tailwindcss/oxide': 4.3.3+ tailwindcss: 4.3.3++ '@tanstack/[email protected]': {}++ '@tanstack/[email protected]':+ dependencies:+ '@tanstack/devtools-event-client': 0.4.4+ '@tanstack/pacer-lite': 0.1.1+ '@tanstack/store': 0.11.1++ '@tanstack/[email protected]': {}++ '@tanstack/[email protected]':+ dependencies:+ '@tanstack/store': 0.11.1++ '@tanstack/[email protected]': {}++ '@tanstack/[email protected]': {}++ dependencies:+ '@tanstack/form-core': 1.33.5+ react: 19.3.0+ transitivePeerDependencies:+ - react-dom++ dependencies:+ '@tanstack/hotkeys': 0.9.0+ react: 19.3.0+ react-dom: 19.3.0([email protected])++ '@tanstack/[email protected]([email protected])':+ dependencies:+ '@tanstack/query-core': 5.103.2+ react: 19.3.0++ dependencies:+ '@tanstack/history': 1.162.4+ '@tanstack/router-core': 1.171.32+ isbot: 5.2.2+ react: 19.3.0+ react-dom: 19.3.0([email protected])++ dependencies:+ '@tanstack/store': 0.11.1+ react: 19.3.0+ react-dom: 19.3.0([email protected])+ use-sync-external-store: 1.7.0([email protected])++ dependencies:+ '@tanstack/virtual-core': 3.17.11+ react: 19.3.0+ react-dom: 19.3.0([email protected])++ '@tanstack/[email protected]':+ dependencies:+ '@tanstack/history': 1.162.4+ cookie-es: 3.1.1+ seroval: 1.6.7+ seroval-plugins: 1.6.7([email protected])++ '@tanstack/[email protected]': {}++ '@tanstack/[email protected]': {}++ '@tiptap/[email protected](@tiptap/[email protected])':+ dependencies:+ '@tiptap/pm': 3.31.3++ '@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])':+ dependencies:+ '@tiptap/core': 3.31.3(@tiptap/[email protected])+ '@tiptap/pm': 3.31.3++ dependencies:+ '@tiptap/core': 3.31.3(@tiptap/[email protected])++ '@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])':+ dependencies:+ '@floating-ui/dom': 1.8.0+ '@tiptap/core': 3.31.3(@tiptap/[email protected])+ '@tiptap/pm': 3.31.3+ optional: true++ '@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected]))':+ dependencies:+ '@tiptap/extension-list': 3.31.3(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])++ '@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])':+ dependencies:+ '@tiptap/core': 3.31.3(@tiptap/[email protected])+ '@tiptap/pm': 3.31.3++ dependencies:+ '@tiptap/core': 3.31.3(@tiptap/[email protected])++ dependencies:+ '@tiptap/core': 3.31.3(@tiptap/[email protected])++ '@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected]))':+ dependencies:+ '@tiptap/extensions': 3.31.3(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])++ '@tiptap/[email protected](@floating-ui/[email protected])(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])':+ dependencies:+ '@floating-ui/dom': 1.8.0+ '@tiptap/core': 3.31.3(@tiptap/[email protected])+ '@tiptap/pm': 3.31.3+ optional: true++ '@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected]))':+ dependencies:+ '@tiptap/extensions': 3.31.3(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])++ dependencies:+ '@tiptap/core': 3.31.3(@tiptap/[email protected])++ dependencies:+ '@tiptap/core': 3.31.3(@tiptap/[email protected])++ '@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])':+ dependencies:+ '@tiptap/core': 3.31.3(@tiptap/[email protected])+ '@tiptap/pm': 3.31.3++ dependencies:+ '@tiptap/core': 3.31.3(@tiptap/[email protected])++ dependencies:+ '@tiptap/core': 3.31.3(@tiptap/[email protected])++ '@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])':+ dependencies:+ '@tiptap/core': 3.31.3(@tiptap/[email protected])+ '@tiptap/pm': 3.31.3+ linkifyjs: 4.3.3++ '@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected]))':+ dependencies:+ '@tiptap/extension-list': 3.31.3(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])++ '@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected]))':+ dependencies:+ '@tiptap/extension-list': 3.31.3(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])++ '@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])':+ dependencies:+ '@tiptap/core': 3.31.3(@tiptap/[email protected])+ '@tiptap/pm': 3.31.3++ '@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected]))':+ dependencies:+ '@tiptap/extension-list': 3.31.3(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])++ dependencies:+ '@tiptap/core': 3.31.3(@tiptap/[email protected])++ '@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected]))':+ dependencies:+ '@tiptap/extensions': 3.31.3(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])++ dependencies:+ '@tiptap/core': 3.31.3(@tiptap/[email protected])++ dependencies:+ '@tiptap/core': 3.31.3(@tiptap/[email protected])++ dependencies:+ '@tiptap/core': 3.31.3(@tiptap/[email protected])++ '@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])':+ dependencies:+ '@tiptap/core': 3.31.3(@tiptap/[email protected])+ '@tiptap/pm': 3.31.3++ '@tiptap/[email protected]':+ dependencies:+ prosemirror-changeset: 2.4.3+ prosemirror-commands: 1.7.2+ prosemirror-dropcursor: 1.8.3+ prosemirror-gapcursor: 1.4.1+ prosemirror-history: 1.5.0+ prosemirror-inputrules: 1.5.1+ prosemirror-keymap: 1.2.3+ prosemirror-model: 1.25.12+ prosemirror-schema-list: 1.5.1+ prosemirror-state: 1.4.4+ prosemirror-tables: 1.8.5+ prosemirror-transform: 1.12.1+ prosemirror-view: 1.42.5++ '@tiptap/[email protected](@floating-ui/[email protected])(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])':+ dependencies:+ '@tiptap/core': 3.31.3(@tiptap/[email protected])+ '@tiptap/pm': 3.31.3+ '@types/react': 19.3.0+ '@types/react-dom': 19.3.0(@types/[email protected])+ '@types/use-sync-external-store': 0.0.6+ fast-equals: 5.4.3+ react: 19.3.0+ react-dom: 19.3.0([email protected])+ use-sync-external-store: 1.7.0([email protected])+ optionalDependencies:+ '@tiptap/extension-bubble-menu': 3.31.3(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])+ '@tiptap/extension-floating-menu': 3.31.3(@floating-ui/[email protected])(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])+ transitivePeerDependencies:+ - '@floating-ui/dom'++ '@tiptap/[email protected]':+ dependencies:+ '@tiptap/core': 3.31.3(@tiptap/[email protected])+ '@tiptap/extension-blockquote': 3.31.3(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])+ '@tiptap/extension-bold': 3.31.3(@tiptap/[email protected](@tiptap/[email protected]))+ '@tiptap/extension-bullet-list': 3.31.3(@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected]))+ '@tiptap/extension-code': 3.31.3(@tiptap/[email protected](@tiptap/[email protected]))+ '@tiptap/extension-code-block': 3.31.3(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])+ '@tiptap/extension-document': 3.31.3(@tiptap/[email protected](@tiptap/[email protected]))+ '@tiptap/extension-dropcursor': 3.31.3(@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected]))+ '@tiptap/extension-gapcursor': 3.31.3(@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected]))+ '@tiptap/extension-hard-break': 3.31.3(@tiptap/[email protected](@tiptap/[email protected]))+ '@tiptap/extension-heading': 3.31.3(@tiptap/[email protected](@tiptap/[email protected]))+ '@tiptap/extension-horizontal-rule': 3.31.3(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])+ '@tiptap/extension-italic': 3.31.3(@tiptap/[email protected](@tiptap/[email protected]))+ '@tiptap/extension-link': 3.31.3(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])+ '@tiptap/extension-list': 3.31.3(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])+ '@tiptap/extension-list-item': 3.31.3(@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected]))+ '@tiptap/extension-list-keymap': 3.31.3(@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected]))+ '@tiptap/extension-ordered-list': 3.31.3(@tiptap/[email protected](@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected]))+ '@tiptap/extension-paragraph': 3.31.3(@tiptap/[email protected](@tiptap/[email protected]))+ '@tiptap/extension-strike': 3.31.3(@tiptap/[email protected](@tiptap/[email protected]))+ '@tiptap/extension-text': 3.31.3(@tiptap/[email protected](@tiptap/[email protected]))+ '@tiptap/extension-underline': 3.31.3(@tiptap/[email protected](@tiptap/[email protected]))+ '@tiptap/extensions': 3.31.3(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])+ '@tiptap/pm': 3.31.3++ '@turbo/[email protected]':+ optional: true++ '@turbo/[email protected]':+ optional: true++ '@turbo/[email protected]':+ optional: true++ '@turbo/[email protected]':+ optional: true++ '@turbo/[email protected]':+ optional: true++ '@turbo/[email protected]':+ optional: true++ '@types/[email protected]':+ dependencies:+ '@babel/parser': 7.29.9+ '@babel/types': 7.29.8+ '@types/babel__generator': 7.27.0+ '@types/babel__template': 7.4.4+ '@types/babel__traverse': 7.28.0++ '@types/[email protected]':+ dependencies:+ '@babel/types': 7.29.8++ '@types/[email protected]':+ dependencies:+ '@babel/parser': 7.29.9+ '@babel/types': 7.29.8++ '@types/[email protected]':+ dependencies:+ '@babel/types': 7.29.8++ '@types/[email protected]':+ dependencies:+ '@types/http-cache-semantics': 4.2.0+ '@types/keyv': 3.1.4+ '@types/node': 24.13.6+ '@types/responselike': 1.0.3++ '@types/[email protected]':+ dependencies:+ '@types/deep-eql': 4.0.2+ assertion-error: 2.0.1++ '@types/[email protected]':+ dependencies:+ '@types/ms': 2.1.0++ '@types/[email protected]': {}++ '@types/[email protected]': {}++ '@types/[email protected]':+ dependencies:+ '@types/node': 24.13.6++ '@types/[email protected]': {}++ '@types/[email protected]':+ dependencies:+ '@types/node': 24.13.6++ '@types/[email protected]':+ dependencies:+ '@types/node': 24.13.6+ iconv-lite: 0.6.3++ '@types/[email protected]': {}++ '@types/[email protected]':+ dependencies:+ undici-types: 7.18.2++ '@types/[email protected]':+ dependencies:+ '@types/node': 24.13.6++ '@types/[email protected](@types/[email protected])':+ dependencies:+ '@types/react': 19.3.0++ '@types/[email protected]':+ dependencies:+ csstype: 3.2.3++ '@types/[email protected]':+ dependencies:+ '@types/node': 24.13.6++ '@types/[email protected]':+ dependencies:+ '@types/node': 24.13.6+ '@types/nodemailer': 8.0.2++ '@types/[email protected]':+ optional: true++ '@types/[email protected]': {}++ '@vitejs/[email protected]([email protected])([email protected](@types/[email protected])([email protected])([email protected]))':+ dependencies:+ '@babel/core': 7.29.7([email protected])+ '@babel/plugin-transform-react-jsx-self': 7.29.7(@babel/[email protected]([email protected]))+ '@babel/plugin-transform-react-jsx-source': 7.29.7(@babel/[email protected]([email protected]))+ '@rolldown/pluginutils': 1.0.0-rc.3+ '@types/babel__core': 7.20.5+ react-refresh: 0.18.0+ transitivePeerDependencies:+ - supports-color++ '@vitest/[email protected]':+ dependencies:+ '@types/chai': 5.2.3+ '@vitest/spy': 3.2.7+ '@vitest/utils': 3.2.7+ chai: 5.3.3+ tinyrainbow: 2.0.0++ '@vitest/[email protected]([email protected](@types/[email protected])([email protected])([email protected]))':+ dependencies:+ '@vitest/spy': 3.2.7+ estree-walker: 3.0.3+ magic-string: 0.30.21+ optionalDependencies:++ '@vitest/[email protected]':+ dependencies:+ tinyrainbow: 2.0.0++ '@vitest/[email protected]':+ dependencies:+ '@vitest/utils': 3.2.7+ pathe: 2.0.3+ strip-literal: 3.1.0++ '@vitest/[email protected]':+ dependencies:+ '@vitest/pretty-format': 3.2.7+ magic-string: 0.30.21+ pathe: 2.0.3++ '@vitest/[email protected]':+ dependencies:+ tinyspy: 4.0.6++ '@vitest/[email protected]':+ dependencies:+ '@vitest/pretty-format': 3.2.7+ loupe: 3.2.1+ tinyrainbow: 2.0.0++ '@xmldom/[email protected]': {}++ '@zone-eu/[email protected]':+ dependencies:+ libbase64: 1.3.0+ libmime: 5.4.4+ libqp: 2.1.1++ [email protected]: {}++ [email protected]: {}++ dependencies:+ fast-deep-equal: 3.1.3+ fast-uri: 3.1.8+ json-schema-traverse: 1.0.0+ require-from-string: 2.0.2++ [email protected]: {}++ dependencies:+ color-convert: 2.0.1++ dependencies:+ '@electron/asar': 3.4.1+ '@electron/fuses': 1.8.0+ '@electron/get': 3.1.0([email protected])+ '@electron/notarize': 2.5.0([email protected])+ '@electron/osx-sign': 1.3.3([email protected])+ '@electron/rebuild': 4.2.0([email protected])+ '@electron/universal': 2.0.3([email protected])+ '@malept/flatpak-bundler': 0.4.0([email protected])+ '@noble/hashes': 2.4.0+ '@peculiar/webcrypto': 1.7.1+ '@types/fs-extra': 9.0.13+ ajv: 8.20.0+ asn1js: 3.0.10+ async-exit-hook: 2.0.1+ builder-util: 26.15.3([email protected])+ builder-util-runtime: 9.7.0([email protected])+ chromium-pickle-js: 0.2.0+ ci-info: 4.3.1+ debug: 4.4.3([email protected])+ dmg-builder: 26.15.3([email protected])([email protected])+ dotenv: 16.6.1+ dotenv-expand: 11.0.7+ ejs: 3.1.10+ electron-builder-squirrel-windows: 26.15.3([email protected])([email protected])+ electron-publish: 26.15.3([email protected])+ fs-extra: 10.1.0+ hosted-git-info: 4.1.0+ isbinaryfile: 5.0.7+ jiti: 2.7.0+ js-yaml: 4.3.2+ json5: 2.2.3+ lazy-val: 1.0.5+ minimatch: 10.2.6+ pkijs: 3.4.1+ plist: 3.1.0+ proper-lockfile: 4.1.2+ resedit: 1.7.2+ semver: 7.7.4+ tar: 7.5.22+ temp-file: 3.4.0+ tiny-async-pool: 1.3.0+ unzipper: 0.12.5+ which: 5.0.0+ transitivePeerDependencies:+ - supports-color++ [email protected]: {}++ dependencies:+ pvtsutils: 1.3.6+ pvutils: 1.2.0+ tslib: 2.8.1++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ optional: true++ dependencies:+ react: 19.3.0+ react-dom: 19.3.0([email protected])++ dependencies:+ balanced-match: 1.0.2+ concat-map: 0.0.1++ dependencies:+ balanced-match: 1.0.2++ dependencies:+ balanced-match: 4.0.4++ dependencies:+ baseline-browser-mapping: 2.11.25+ caniuse-lite: 1.0.30001810+ electron-to-chromium: 1.5.434+ node-releases: 2.0.56+ update-browserslist-db: 1.3.3([email protected])++ [email protected]: {}++ dependencies:+ debug: 4.4.3([email protected])+ sax: 1.6.1+ transitivePeerDependencies:+ - supports-color++ dependencies:+ '@types/debug': 4.1.13+ builder-util-runtime: 9.7.0([email protected])+ chalk: 4.1.2+ cross-spawn: 7.0.6+ debug: 4.4.3([email protected])+ fs-extra: 10.1.0+ http-proxy-agent: 7.0.2([email protected])+ https-proxy-agent: 7.0.6([email protected])+ js-yaml: 4.3.2+ sanitize-filename: 1.6.4+ source-map-support: 0.5.21+ stat-mode: 1.0.0+ temp-file: 3.4.0+ tiny-async-pool: 1.3.0+ transitivePeerDependencies:+ - supports-color++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ clone-response: 1.0.3+ get-stream: 5.2.0+ http-cache-semantics: 4.2.0+ keyv: 4.5.4+ lowercase-keys: 2.0.0+ normalize-url: 6.1.0+ responselike: 2.0.1++ dependencies:+ es-errors: 1.3.0+ function-bind: 1.1.2++ [email protected]: {}++ dependencies:+ assertion-error: 2.0.1+ check-error: 2.1.3+ deep-eql: 5.0.2+ loupe: 3.2.1+ pathval: 2.0.1++ dependencies:+ ansi-styles: 4.3.0+ supports-color: 7.2.0++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ string-width: 4.2.3+ strip-ansi: 6.0.1+ wrap-ansi: 7.0.0++ dependencies:+ mimic-response: 1.0.1++ [email protected]: {}++ dependencies:+ color-name: 1.1.4++ [email protected]: {}++ dependencies:+ delayed-stream: 1.0.0++ [email protected]: {}++ optional: true++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ optional: true++ dependencies:+ path-key: 3.1.1+ shebang-command: 2.0.0+ which: 2.0.2++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ ms: 2.1.3+ optionalDependencies:+ supports-color: 7.2.0++ dependencies:+ mimic-response: 3.1.0++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ es-define-property: 1.0.1+ es-errors: 1.3.0+ gopd: 1.2.0+ optional: true++ dependencies:+ define-data-property: 1.1.4+ has-property-descriptors: 1.0.2+ object-keys: 1.1.1+ optional: true++ [email protected]: {}++ [email protected]: {}++ optional: true++ dependencies:+ minimatch: 3.1.5+ p-limit: 3.1.0++ dependencies:+ builder-util: 26.15.3([email protected])+ fs-extra: 10.1.0+ js-yaml: 4.3.2+ transitivePeerDependencies:+ - electron-builder-squirrel-windows+ - supports-color++ dependencies:+ domelementtype: 2.3.0+ domhandler: 5.0.3+ entities: 4.5.0++ [email protected]: {}++ dependencies:+ domelementtype: 2.3.0++ optionalDependencies:+ '@types/trusted-types': 2.0.7++ dependencies:+ dom-serializer: 2.0.0+ domelementtype: 2.3.0+ domhandler: 5.0.3++ dependencies:+ dotenv: 16.6.1++ [email protected]: {}++ dependencies:+ call-bind-apply-helpers: 1.0.2+ es-errors: 1.3.0+ gopd: 1.2.0++ dependencies:+ readable-stream: 2.3.8++ dependencies:+ jake: 10.9.4++ dependencies:+ builder-util: 26.15.3([email protected])+ electron-winstaller: 5.4.0([email protected])+ transitivePeerDependencies:+ - dmg-builder+ - supports-color++ dependencies:+ builder-util: 26.15.3([email protected])+ builder-util-runtime: 9.7.0([email protected])+ chalk: 4.1.2+ ci-info: 4.4.0+ dmg-builder: 26.15.3([email protected])([email protected])+ fs-extra: 10.1.0+ lazy-val: 1.0.5+ simple-update-notifier: 2.0.0+ yargs: 17.7.3+ transitivePeerDependencies:+ - electron-builder-squirrel-windows+ - supports-color++ dependencies:+ '@types/fs-extra': 9.0.13+ aws4: 1.13.2+ builder-util: 26.15.3([email protected])+ builder-util-runtime: 9.7.0([email protected])+ chalk: 4.1.2+ form-data: 4.0.6+ fs-extra: 10.1.0+ lazy-val: 1.0.5+ mime: 2.6.0+ transitivePeerDependencies:+ - supports-color++ [email protected]: {}++ [email protected]([email protected])([email protected](@types/[email protected])([email protected])([email protected])):+ dependencies:+ '@babel/core': 7.29.7([email protected])+ '@babel/plugin-transform-arrow-functions': 7.29.7(@babel/[email protected]([email protected]))+ cac: 6.7.14+ esbuild: 0.25.12+ magic-string: 0.30.21+ picocolors: 1.1.1+ transitivePeerDependencies:+ - supports-color++ dependencies:+ '@electron/asar': 3.4.1+ debug: 4.4.3([email protected])+ fs-extra: 7.0.1+ lodash: 4.18.1+ temp: 0.9.4+ optionalDependencies:+ '@electron/windows-sign': 1.2.2([email protected])+ transitivePeerDependencies:+ - supports-color++ dependencies:+ '@electron-internal/extract-zip': 1.0.5+ '@electron/get': 5.1.0([email protected])+ '@types/node': 24.13.6+ transitivePeerDependencies:+ - supports-color++ [email protected]: {}++ [email protected]: {}++ dependencies:+ once: 1.4.0++ dependencies:+ graceful-fs: 4.2.11+ tapable: 2.3.3++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ es-errors: 1.3.0++ dependencies:+ es-errors: 1.3.0+ get-intrinsic: 1.3.0+ has-tostringtag: 1.0.2+ hasown: 2.0.4++ optional: true++ optionalDependencies:+ '@esbuild/aix-ppc64': 0.25.12+ '@esbuild/android-arm': 0.25.12+ '@esbuild/android-arm64': 0.25.12+ '@esbuild/android-x64': 0.25.12+ '@esbuild/darwin-arm64': 0.25.12+ '@esbuild/darwin-x64': 0.25.12+ '@esbuild/freebsd-arm64': 0.25.12+ '@esbuild/freebsd-x64': 0.25.12+ '@esbuild/linux-arm': 0.25.12+ '@esbuild/linux-arm64': 0.25.12+ '@esbuild/linux-ia32': 0.25.12+ '@esbuild/linux-loong64': 0.25.12+ '@esbuild/linux-mips64el': 0.25.12+ '@esbuild/linux-ppc64': 0.25.12+ '@esbuild/linux-riscv64': 0.25.12+ '@esbuild/linux-s390x': 0.25.12+ '@esbuild/linux-x64': 0.25.12+ '@esbuild/netbsd-arm64': 0.25.12+ '@esbuild/netbsd-x64': 0.25.12+ '@esbuild/openbsd-arm64': 0.25.12+ '@esbuild/openbsd-x64': 0.25.12+ '@esbuild/openharmony-arm64': 0.25.12+ '@esbuild/sunos-x64': 0.25.12+ '@esbuild/win32-arm64': 0.25.12+ '@esbuild/win32-ia32': 0.25.12+ '@esbuild/win32-x64': 0.25.12++ optionalDependencies:+ '@esbuild/aix-ppc64': 0.28.2+ '@esbuild/android-arm': 0.28.2+ '@esbuild/android-arm64': 0.28.2+ '@esbuild/android-x64': 0.28.2+ '@esbuild/darwin-arm64': 0.28.2+ '@esbuild/darwin-x64': 0.28.2+ '@esbuild/freebsd-arm64': 0.28.2+ '@esbuild/freebsd-x64': 0.28.2+ '@esbuild/linux-arm': 0.28.2+ '@esbuild/linux-arm64': 0.28.2+ '@esbuild/linux-ia32': 0.28.2+ '@esbuild/linux-loong64': 0.28.2+ '@esbuild/linux-mips64el': 0.28.2+ '@esbuild/linux-ppc64': 0.28.2+ '@esbuild/linux-riscv64': 0.28.2+ '@esbuild/linux-s390x': 0.28.2+ '@esbuild/linux-x64': 0.28.2+ '@esbuild/netbsd-arm64': 0.28.2+ '@esbuild/netbsd-x64': 0.28.2+ '@esbuild/openbsd-arm64': 0.28.2+ '@esbuild/openbsd-x64': 0.28.2+ '@esbuild/openharmony-arm64': 0.28.2+ '@esbuild/sunos-x64': 0.28.2+ '@esbuild/win32-arm64': 0.28.2+ '@esbuild/win32-ia32': 0.28.2+ '@esbuild/win32-x64': 0.28.2++ [email protected]: {}++ optional: true++ dependencies:+ '@types/estree': 1.0.9++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ optionalDependencies:+ picomatch: 4.0.7++ dependencies:+ minimatch: 5.1.9++ dependencies:+ asynckit: 0.4.0+ combined-stream: 1.0.8+ es-set-tostringtag: 2.1.0+ hasown: 2.0.4+ mime-types: 2.1.35++ dependencies:+ graceful-fs: 4.2.11+ jsonfile: 6.2.1+ universalify: 2.0.1++ dependencies:+ graceful-fs: 4.2.11+ jsonfile: 6.2.1+ universalify: 2.0.1++ dependencies:+ graceful-fs: 4.2.11+ jsonfile: 6.2.1+ universalify: 2.0.1++ dependencies:+ graceful-fs: 4.2.11+ jsonfile: 4.0.0+ universalify: 0.1.2++ dependencies:+ graceful-fs: 4.2.11+ jsonfile: 4.0.0+ universalify: 0.1.2++ dependencies:+ at-least-node: 1.0.0+ graceful-fs: 4.2.11+ jsonfile: 6.2.1+ universalify: 2.0.1++ [email protected]: {}++ optional: true++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ call-bind-apply-helpers: 1.0.2+ es-define-property: 1.0.1+ es-errors: 1.3.0+ es-object-atoms: 1.1.2+ function-bind: 1.1.2+ get-proto: 1.0.1+ gopd: 1.2.0+ has-symbols: 1.1.0+ hasown: 2.0.4+ math-intrinsics: 1.1.0++ dependencies:+ dunder-proto: 1.0.1+ es-object-atoms: 1.1.2++ dependencies:+ pump: 3.0.4++ dependencies:+ fs.realpath: 1.0.0+ inflight: 1.0.6+ inherits: 2.0.4+ minimatch: 3.1.5+ once: 1.4.0+ path-is-absolute: 1.0.1++ dependencies:+ boolean: 3.2.0+ es6-error: 4.1.1+ matcher: 3.0.0+ roarr: 2.15.4+ semver: 7.7.4+ serialize-error: 7.0.1+ optional: true++ dependencies:+ define-properties: 1.2.1+ gopd: 1.2.0+ optional: true++ [email protected]: {}++ dependencies:+ '@sindresorhus/is': 4.6.0+ '@szmarczak/http-timer': 4.0.6+ '@types/cacheable-request': 6.0.3+ '@types/responselike': 1.0.3+ cacheable-lookup: 5.0.4+ cacheable-request: 7.0.4+ decompress-response: 6.0.0+ http2-wrapper: 1.0.3+ lowercase-keys: 2.0.0+ p-cancelable: 2.1.1+ responselike: 2.0.1++ [email protected]: {}++ [email protected]: {}++ dependencies:+ es-define-property: 1.0.1+ optional: true++ [email protected]: {}++ dependencies:+ has-symbols: 1.1.0++ dependencies:+ function-bind: 1.1.2++ [email protected]: {}++ dependencies:+ lru-cache: 6.0.0++ dependencies:+ '@selderee/plugin-htmlparser2': 0.12.0([email protected])+ deepmerge-ts: 8.0.2+ dom-serializer: 2.0.0+ htmlparser2: 10.1.0+ selderee: 0.12.0++ dependencies:+ domelementtype: 2.3.0+ domhandler: 5.0.3+ domutils: 3.2.2+ entities: 7.0.1++ [email protected]: {}++ dependencies:+ agent-base: 7.1.4+ debug: 4.4.3([email protected])+ transitivePeerDependencies:+ - supports-color++ dependencies:+ quick-lru: 5.1.1+ resolve-alpn: 1.2.1++ dependencies:+ agent-base: 7.1.4+ debug: 4.4.3([email protected])+ transitivePeerDependencies:+ - supports-color++ dependencies:+ safer-buffer: 2.1.2++ dependencies:+ safer-buffer: 2.1.2++ [email protected]: {}++ dependencies:+ '@zone-eu/mailsplit': 5.4.17+ encoding-japanese: 2.4.0+ iconv-lite: 0.7.3+ libbase64: 1.3.0+ libmime: 5.4.4+ libqp: 2.1.1+ pino: 10.3.1+ socks: 2.8.10++ dependencies:+ once: 1.4.0+ wrappy: 1.0.2++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ async: 3.2.6+ filelist: 1.0.6+ picocolors: 1.1.1++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ argparse: 2.0.1++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ optional: true++ [email protected]: {}++ optionalDependencies:+ graceful-fs: 4.2.11++ dependencies:+ universalify: 2.0.1+ optionalDependencies:+ graceful-fs: 4.2.11++ dependencies:+ json-buffer: 3.0.1++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ encoding-japanese: 2.4.0+ iconv-lite: 0.7.3+ libbase64: 1.3.0+ libqp: 2.1.1++ [email protected]: {}++ optional: true++ optional: true++ optional: true++ optional: true++ optional: true++ optional: true++ optional: true++ optional: true++ optional: true++ optional: true++ optional: true++ dependencies:+ detect-libc: 2.1.2+ optionalDependencies:+ lightningcss-android-arm64: 1.32.0+ lightningcss-darwin-arm64: 1.32.0+ lightningcss-darwin-x64: 1.32.0+ lightningcss-freebsd-x64: 1.32.0+ lightningcss-linux-arm-gnueabihf: 1.32.0+ lightningcss-linux-arm64-gnu: 1.32.0+ lightningcss-linux-arm64-musl: 1.32.0+ lightningcss-linux-x64-gnu: 1.32.0+ lightningcss-linux-x64-musl: 1.32.0+ lightningcss-win32-arm64-msvc: 1.32.0+ lightningcss-win32-x64-msvc: 1.32.0++ dependencies:+ uc.micro: 2.1.0++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ yallist: 3.1.1++ dependencies:+ yallist: 4.0.0++ dependencies:+ '@jridgewell/sourcemap-codec': 1.6.0++ dependencies:+ '@zone-eu/mailsplit': 5.4.17+ encoding-japanese: 2.4.0+ he: 1.2.0+ html-to-text: 10.0.1+ iconv-lite: 0.7.3+ libmime: 5.4.4+ linkify-it: 5.0.2+ nodemailer: 10.0.10+ punycode.js: 2.3.1+ tlds: 1.261.0++ dependencies:+ escape-string-regexp: 4.0.0+ optional: true++ [email protected]: {}++ [email protected]: {}++ dependencies:+ mime-db: 1.52.0++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ brace-expansion: 5.0.12++ dependencies:+ brace-expansion: 1.1.21++ dependencies:+ brace-expansion: 2.1.7++ dependencies:+ brace-expansion: 2.1.7++ [email protected]: {}++ [email protected]: {}++ dependencies:+ minipass: 7.1.3++ dependencies:+ minimist: 1.2.8++ [email protected]: {}++ [email protected]: {}++ dependencies:+ semver: 7.7.4++ dependencies:+ semver: 7.7.4++ dependencies:+ env-paths: 2.2.1+ exponential-backoff: 3.1.3+ graceful-fs: 4.2.11+ nopt: 9.0.0+ proc-log: 6.1.0+ semver: 7.7.4+ tar: 7.5.22+ tinyglobby: 0.2.17+ undici: 6.28.1+ which: 6.0.1++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ abbrev: 4.0.0++ [email protected]: {}++ optional: true++ [email protected]: {}++ dependencies:+ wrappy: 1.0.2++ [email protected]: {}++ [email protected]: {}++ dependencies:+ yocto-queue: 0.1.0++ dependencies:+ leac: 0.7.0+ peberminta: 0.10.0++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ split2: 4.2.0++ [email protected]: {}++ dependencies:+ '@pinojs/redact': 0.4.0+ atomic-sleep: 1.0.0+ on-exit-leak-free: 2.1.2+ pino-abstract-transport: 3.0.0+ pino-std-serializers: 7.1.0+ process-warning: 5.1.0+ quick-format-unescaped: 4.0.4+ real-require: 0.2.0+ safe-stable-stringify: 2.5.0+ sonic-boom: 4.2.1+ thread-stream: 4.2.0++ dependencies:+ '@noble/hashes': 1.8.0+ asn1js: 3.0.10+ bytestreamjs: 2.0.1+ pvtsutils: 1.3.6+ pvutils: 1.2.0+ tslib: 2.8.1++ dependencies:+ '@xmldom/xmldom': 0.8.15+ base64-js: 1.5.1+ xmlbuilder: 15.1.1++ dependencies:+ nanoid: 3.3.19+ picocolors: 1.1.1+ source-map-js: 1.2.1++ dependencies:+ commander: 9.5.0+ optional: true++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ err-code: 2.0.3+ retry: 0.12.0++ dependencies:+ graceful-fs: 4.2.11+ retry: 0.12.0+ signal-exit: 3.0.7++ dependencies:+ prosemirror-transform: 1.12.1++ dependencies:+ prosemirror-model: 1.25.12+ prosemirror-state: 1.4.4+ prosemirror-transform: 1.12.1++ dependencies:+ prosemirror-state: 1.4.4+ prosemirror-transform: 1.12.1+ prosemirror-view: 1.42.5++ dependencies:+ prosemirror-keymap: 1.2.3+ prosemirror-model: 1.25.12+ prosemirror-state: 1.4.4+ prosemirror-view: 1.42.5++ dependencies:+ prosemirror-state: 1.4.4+ prosemirror-transform: 1.12.1+ prosemirror-view: 1.42.5+ rope-sequence: 1.3.4++ dependencies:+ prosemirror-state: 1.4.4+ prosemirror-transform: 1.12.1++ dependencies:+ prosemirror-state: 1.4.4+ w3c-keyname: 2.2.8++ dependencies:+ orderedmap: 2.1.1++ dependencies:+ prosemirror-model: 1.25.12+ prosemirror-state: 1.4.4+ prosemirror-transform: 1.12.1++ dependencies:+ prosemirror-model: 1.25.12+ prosemirror-transform: 1.12.1+ prosemirror-view: 1.42.5++ dependencies:+ prosemirror-keymap: 1.2.3+ prosemirror-model: 1.25.12+ prosemirror-state: 1.4.4+ prosemirror-transform: 1.12.1+ prosemirror-view: 1.42.5++ dependencies:+ prosemirror-model: 1.25.12++ dependencies:+ prosemirror-model: 1.25.12+ prosemirror-state: 1.4.4+ prosemirror-transform: 1.12.1++ dependencies:+ end-of-stream: 1.4.5+ once: 1.4.0++ [email protected]: {}++ dependencies:+ tslib: 2.8.1++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ '@date-fns/tz': 1.5.0+ '@tabby_ai/hijri-converter': 1.0.5+ date-fns: 4.4.0+ date-fns-jalali: 4.1.0-0+ react: 19.3.0++ dependencies:+ react: 19.3.0+ scheduler: 0.28.0++ [email protected]: {}++ [email protected]: {}++ dependencies:+ debug: 4.4.3([email protected])+ transitivePeerDependencies:+ - supports-color++ dependencies:+ core-util-is: 1.0.3+ inherits: 2.0.4+ isarray: 1.0.0+ process-nextick-args: 2.0.1+ safe-buffer: 5.1.2+ string_decoder: 1.1.1+ util-deprecate: 1.0.2++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ pe-library: 0.4.1++ [email protected]: {}++ [email protected]: {}++ dependencies:+ lowercase-keys: 2.0.0++ [email protected]: {}++ dependencies:+ glob: 7.2.3++ dependencies:+ boolean: 3.2.0+ detect-node: 2.1.0+ globalthis: 1.0.4+ json-stringify-safe: 5.0.1+ semver-compare: 1.0.0+ sprintf-js: 1.1.3+ optional: true++ dependencies:+ '@types/estree': 1.0.9+ optionalDependencies:+ '@napi-rs/lzma-linux-x64-gnu': 1.5.1+ '@rollup/rollup-android-arm-eabi': 4.63.4+ '@rollup/rollup-android-arm64': 4.63.4+ '@rollup/rollup-darwin-arm64': 4.63.4+ '@rollup/rollup-darwin-x64': 4.63.4+ '@rollup/rollup-freebsd-arm64': 4.63.4+ '@rollup/rollup-freebsd-x64': 4.63.4+ '@rollup/rollup-linux-arm-gnueabihf': 4.63.4+ '@rollup/rollup-linux-arm-musleabihf': 4.63.4+ '@rollup/rollup-linux-arm64-gnu': 4.63.4+ '@rollup/rollup-linux-arm64-musl': 4.63.4+ '@rollup/rollup-linux-loong64-gnu': 4.63.4+ '@rollup/rollup-linux-loong64-musl': 4.63.4+ '@rollup/rollup-linux-ppc64-gnu': 4.63.4+ '@rollup/rollup-linux-ppc64-musl': 4.63.4+ '@rollup/rollup-linux-riscv64-gnu': 4.63.4+ '@rollup/rollup-linux-riscv64-musl': 4.63.4+ '@rollup/rollup-linux-s390x-gnu': 4.63.4+ '@rollup/rollup-linux-x64-gnu': 4.63.4+ '@rollup/rollup-linux-x64-musl': 4.63.4+ '@rollup/rollup-openbsd-x64': 4.63.4+ '@rollup/rollup-openharmony-arm64': 4.63.4+ '@rollup/rollup-win32-arm64-msvc': 4.63.4+ '@rollup/rollup-win32-ia32-msvc': 4.63.4+ '@rollup/rollup-win32-x64-gnu': 4.63.4+ '@rollup/rollup-win32-x64-msvc': 4.63.4+ fsevents: 2.3.3++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ truncate-utf8-bytes: 1.0.2++ [email protected]: {}++ [email protected]: {}++ dependencies:+ parseley: 0.13.1++ optional: true++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ type-fest: 0.13.1+ optional: true++ dependencies:+ seroval: 1.6.7++ [email protected]: {}++ dependencies:+ shebang-regex: 3.0.0++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ semver: 7.8.5++ [email protected]: {}++ dependencies:+ ipv6-normalize: 1.0.1+ nodemailer: 10.0.10+ punycode.js: 2.3.1++ dependencies:+ ip-address: 10.7.2+ smart-buffer: 4.2.0++ dependencies:+ atomic-sleep: 1.0.0++ [email protected]: {}++ dependencies:+ buffer-from: 1.1.2+ source-map: 0.6.1++ [email protected]: {}++ [email protected]: {}++ optional: true++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ emoji-regex: 8.0.0+ is-fullwidth-code-point: 3.0.0+ strip-ansi: 6.0.1++ dependencies:+ safe-buffer: 5.1.2++ dependencies:+ ansi-regex: 5.0.1++ dependencies:+ js-tokens: 9.0.1++ dependencies:+ debug: 4.4.3([email protected])+ transitivePeerDependencies:+ - supports-color++ dependencies:+ has-flag: 4.0.0++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ '@isaacs/fs-minipass': 4.0.1+ chownr: 3.0.0+ minipass: 7.1.3+ minizlib: 3.1.0+ yallist: 5.0.0++ dependencies:+ async-exit-hook: 2.0.1+ fs-extra: 10.1.0++ dependencies:+ mkdirp: 0.5.6+ rimraf: 2.6.3++ dependencies:+ real-require: 1.0.0++ dependencies:+ semver: 5.7.2++ [email protected]: {}++ [email protected]: {}++ dependencies:+ fdir: 6.5.0([email protected])+ picomatch: 4.0.7++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ tmp: 0.2.7++ [email protected]: {}++ dependencies:+ utf8-byte-length: 1.0.5++ [email protected]: {}++ optionalDependencies:+ '@turbo/darwin-64': 2.11.2+ '@turbo/darwin-arm64': 2.11.2+ '@turbo/linux-64': 2.11.2+ '@turbo/linux-arm64': 2.11.2+ '@turbo/windows-64': 2.11.2+ '@turbo/windows-arm64': 2.11.2++ optional: true++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ optional: true++ [email protected]: {}++ [email protected]: {}++ dependencies:+ bluebird: 3.7.2+ duplexer2: 0.1.4+ fs-extra: 11.3.1+ graceful-fs: 4.2.11+ node-int64: 0.4.0++ dependencies:+ browserslist: 4.29.0+ escalade: 3.2.0+ picocolors: 1.1.1++ dependencies:+ react: 19.3.0++ [email protected]: {}++ [email protected]: {}++ [email protected](@types/[email protected])([email protected])([email protected])([email protected]):+ dependencies:+ cac: 6.7.14+ debug: 4.4.3([email protected])+ es-module-lexer: 1.7.0+ pathe: 2.0.3+ transitivePeerDependencies:+ - '@types/node'+ - jiti+ - less+ - lightningcss+ - sass+ - sass-embedded+ - stylus+ - sugarss+ - supports-color+ - terser+ - tsx+ - yaml++ dependencies:+ esbuild: 0.28.2+ fdir: 6.5.0([email protected])+ picomatch: 4.0.7+ postcss: 8.5.28+ rollup: 4.63.4+ tinyglobby: 0.2.17+ optionalDependencies:+ '@types/node': 24.13.6+ fsevents: 2.3.3+ jiti: 2.7.0+ lightningcss: 1.32.0++ [email protected](@types/[email protected])(@types/[email protected])([email protected])([email protected])([email protected]):+ dependencies:+ '@types/chai': 5.2.3+ '@vitest/expect': 3.2.7+ '@vitest/mocker': 3.2.7([email protected](@types/[email protected])([email protected])([email protected]))+ '@vitest/pretty-format': 3.2.7+ '@vitest/runner': 3.2.7+ '@vitest/snapshot': 3.2.7+ '@vitest/spy': 3.2.7+ '@vitest/utils': 3.2.7+ chai: 5.3.3+ debug: 4.4.3([email protected])+ expect-type: 1.4.0+ magic-string: 0.30.21+ pathe: 2.0.3+ picomatch: 4.0.7+ std-env: 3.10.0+ tinybench: 2.9.0+ tinyexec: 0.3.2+ tinyglobby: 0.2.17+ tinypool: 1.1.1+ tinyrainbow: 2.0.0+ vite-node: 3.2.4(@types/[email protected])([email protected])([email protected])([email protected])+ why-is-node-running: 2.3.0+ optionalDependencies:+ '@types/debug': 4.1.13+ '@types/node': 24.13.6+ transitivePeerDependencies:+ - jiti+ - less+ - lightningcss+ - msw+ - sass+ - sass-embedded+ - stylus+ - sugarss+ - supports-color+ - terser+ - tsx+ - yaml++ [email protected]: {}++ dependencies:+ '@peculiar/asn1-schema': 2.9.5+ '@peculiar/json-schema': 1.1.12+ '@peculiar/utils': 2.0.3+ asn1js: 3.0.10+ tslib: 2.8.1++ dependencies:+ isexe: 2.0.0++ dependencies:+ isexe: 3.1.5++ dependencies:+ isexe: 4.0.0++ dependencies:+ siginfo: 2.0.0+ stackback: 0.0.2++ dependencies:+ ansi-styles: 4.3.0+ string-width: 4.2.3+ strip-ansi: 6.0.1++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ cliui: 8.0.1+ escalade: 3.2.0+ get-caller-file: 2.0.5+ require-directory: 2.1.1+ string-width: 4.2.3+ y18n: 5.0.8+ yargs-parser: 21.1.1++ [email protected]: {}++ [email protected]: {}diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yamlnew file mode 100644index 0000000..07814ee--- /dev/null+++ b/pnpm-workspace.yaml@@ -0,0 +1,10 @@+packages:+ - apps/*+ - packages/*+storeDir: .pnpm-store+allowBuilds:+ electron: true+ esbuild: true+ electron-winstaller: false+minimumReleaseAgeExclude:diff --git a/scripts/Containerfile.smoke b/scripts/Containerfile.smokenew file mode 100644index 0000000..38538ab--- /dev/null+++ b/scripts/Containerfile.smoke@@ -0,0 +1,8 @@+FROM docker.io/debian:bookworm-slim+RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates xvfb xauth libgtk-3-0 libnss3 libasound2 libgbm1 libxss1 libxtst6 libdrm2 libxkbcommon0 libsecret-1-0 libnotify4 xdg-utils libatspi2.0-0 && rm -rf /var/lib/apt/lists/*+RUN useradd --create-home app+USER app+ENV INLARK_DATA_DIR=/tmp/inlark-smoke+# Nested Chromium namespaces are unavailable in many rootless container hosts.+# Only this isolated, network-disabled packaging smoke uses --no-sandbox.+CMD ["sh", "-c", "dpkg-deb -x /release/Inlark-0.1.0-amd64.deb /tmp/package && xvfb-run -a /tmp/package/opt/Inlark/inlark --smoke-test --no-sandbox --disable-gpu"]diff --git a/scripts/icon.py b/scripts/icon.pynew file mode 100644index 0000000..8d7bd1d--- /dev/null+++ b/scripts/icon.py@@ -0,0 +1,40 @@+"""Export desktop PNGs from resources/icon.svg. Requires librsvg's rsvg-convert."""+import argparse+from pathlib import Path+import subprocess+import xml.etree.ElementTree as ET+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument('--renderer', default='rsvg-convert', help='Path to rsvg-convert')+ args = parser.parse_args()+ root = Path(__file__).resolve().parents[1] / 'apps/desktop/resources'+ source = (root / 'icon.svg').read_bytes()+ unread = ET.fromstring(source)+ x, y, width, height = map(float, unread.attrib['viewBox'].split())+ size = min(width, height)+ # Keep the badge proportional to the artwork's viewBox. Explicit colours+ # also allow the source SVG to contain gradient and filter definitions.+ ET.SubElement(unread, '{http://www.w3.org/2000/svg}circle', {+ 'cx': str(x + width * 103 / 128),+ 'cy': str(y + height * 25 / 128),+ 'r': str(size * 17 / 128),+ 'fill': '#f5f7ff',+ 'stroke': '#484bd3', 'stroke-width': str(size * 6 / 128),+ })+ for name, size, svg in [+ ('icon.png', 512, source),+ ('tray.png', 24, source),+ ('[email protected]', 48, source),+ ('tray-unread.png', 24, ET.tostring(unread)),+ ('[email protected]', 48, ET.tostring(unread)),+ ]:+ subprocess.run([+ args.renderer, '--width', str(size), '--height', str(size),+ '--output', str(root / name),+ ], input=svg, check=True)+++if __name__ == '__main__':+ main()diff --git a/scripts/package-linux.sh b/scripts/package-linux.shnew file mode 100755index 0000000..2768db8--- /dev/null+++ b/scripts/package-linux.sh@@ -0,0 +1,11 @@+#!/usr/bin/env bash+set -euo pipefail+cd "$(dirname "$0")/.."+pnpm build+if [[ -f /etc/os-release ]] && (source /etc/os-release && [[ "${ID:-}" == nixos ]]); then+ nix shell github:NixOS/nixpkgs/6774f7bc253789b113a4f39285dc0fa100abeacc#fpm \+ github:NixOS/nixpkgs/6774f7bc253789b113a4f39285dc0fa100abeacc#rpm \+ --command env USE_SYSTEM_FPM=true pnpm --filter @inlark/desktop package:linux+else+ pnpm --filter @inlark/desktop package:linux+fidiff --git a/scripts/stalwart-test.mjs b/scripts/stalwart-test.mjsnew file mode 100644index 0000000..2de9ef2--- /dev/null+++ b/scripts/stalwart-test.mjs@@ -0,0 +1,163 @@+import { spawnSync } from 'node:child_process'+import { randomUUID } from 'node:crypto'+import { readFileSync } from 'node:fs'+import { fileURLToPath } from 'node:url'+const runtime = process.env.CONTAINER_RUNTIME || 'podman'+const name = 'inlark-test-' + randomUUID().slice(0, 8)+const port = process.env.STALWART_TEST_PORT || '18081'+// IMAP/SMTP listeners, published on consecutive ports after the HTTP port.+const mailPorts = { imaps: 993, imap: 143, submissions: 465, submission: 587 }+const published = Object.fromEntries(+ Object.entries(mailPorts).map(([name], i) => [name, String(Number(port) + 1 + i)]),+)+// Test-only certificate for localhost/127.0.0.1, signed by tests/fixtures/tls/ca.crt.+const tls = fileURLToPath(new URL('../tests/fixtures/tls/', import.meta.url))+const url = 'http://127.0.0.1:' + port+const password = randomUUID()+const run = (args, extra = {}) => {+ const result = spawnSync(runtime, args, { encoding: 'utf8', ...extra })+ if (result.status) throw new Error(result.stderr || 'Container command failed')+ return result.stdout.trim()+}+try {+ run([+ 'run',+ '-d',+ '--name',+ name,+ '--label',+ 'app.inlark.test=true',+ '-p',+ '127.0.0.1:' + port + ':8080',+ ...Object.entries(mailPorts).flatMap(([name, inner]) => [+ '-p',+ '127.0.0.1:' + published[name] + ':' + inner,+ ]),+ '-e',+ 'STALWART_PUBLIC_URL=' + url,+ '-e',+ 'STALWART_RECOVERY_ADMIN=admin:' + password,+ 'docker.io/stalwartlabs/stalwart:v0.16.23',+ ])+ const auth = 'Basic ' + Buffer.from('admin:' + password).toString('base64')+ for (let i = 0; i < 60; i++) {+ try {+ const r = await fetch(url + '/jmap/session', { headers: { Authorization: auth } })+ if (r.ok) break+ } catch {}+ await new Promise((r) => setTimeout(r, 500))+ }+ const response = await fetch(url + '/jmap/', {+ method: 'POST',+ headers: { Authorization: auth, 'Content-Type': 'application/json' },+ body: JSON.stringify({+ using: ['urn:ietf:params:jmap:core', 'urn:stalwart:jmap'],+ methodCalls: [+ [+ 'x:Bootstrap/set',+ {+ update: {+ singleton: {+ serverHostname: 'mail.inlark.test',+ defaultDomain: 'inlark.test',+ requestTlsCertificate: false,+ generateDkimKeys: false,+ },+ },+ },+ 'setup',+ ],+ ],+ }),+ })+ const body = await response.json(),+ account = body.methodResponses?.[0]?.[1]?.updated?.singleton+ if (!account?.secret)+ throw new Error('Stalwart bootstrap failed. No account secret was returned.')+ // Serve a certificate the tests trust explicitly, and add the STARTTLS listeners.+ const adminCall = (methodCalls) =>+ fetch(url + '/jmap/', {+ method: 'POST',+ headers: { Authorization: auth, 'Content-Type': 'application/json' },+ body: JSON.stringify({+ using: ['urn:ietf:params:jmap:core', 'urn:stalwart:jmap'],+ methodCalls,+ }),+ }).then((r) => r.json())+ run(['restart', name])+ for (let i = 0; i < 60; i++) {+ try {+ const r = await fetch(url + '/jmap/session', { headers: { Authorization: auth } })+ if (r.ok) break+ } catch {}+ await new Promise((r) => setTimeout(r, 500))+ }+ const configured = await adminCall([+ [+ 'x:Certificate/set',+ {+ create: {+ test: {+ certificate: { '@type': 'Text', value: readFileSync(tls + 'server.crt', 'utf8') },+ privateKey: { '@type': 'Text', secret: readFileSync(tls + 'server.key', 'utf8') },+ },+ },+ },+ 'certificate',+ ],+ [+ 'x:NetworkListener/set',+ {+ create: {+ imap: {+ name: 'imap',+ bind: { '[::]:143': true },+ protocol: 'imap',+ useTls: true,+ tlsImplicit: false,+ },+ submission: {+ name: 'submission',+ bind: { '[::]:587': true },+ protocol: 'smtp',+ useTls: true,+ tlsImplicit: false,+ },+ },+ },+ 'listeners',+ ],+ ])+ for (const [, result] of configured.methodResponses || [])+ if (!result?.created || result.notCreated)+ throw new Error('Stalwart TLS configuration failed: ' + JSON.stringify(result))+ run(['restart', name])+ const login = 'Basic ' + Buffer.from(account.username + ':' + account.secret).toString('base64')+ for (let i = 0; i < 60; i++) {+ try {+ const r = await fetch(url + '/jmap/session', { headers: { Authorization: login } })+ if (r.ok) break+ } catch {}+ await new Promise((r) => setTimeout(r, 500))+ }+ const tests = spawnSync('pnpm', ['test:integration'], {+ stdio: 'inherit',+ env: {+ ...process.env,+ STALWART_TEST_CONTAINER: name,+ STALWART_TEST_RUNTIME: runtime,+ STALWART_TEST_URL: url,+ STALWART_TEST_USERNAME: account.username,+ STALWART_TEST_PASSWORD: account.secret,+ STALWART_TEST_IMAPS_PORT: published.imaps,+ STALWART_TEST_IMAP_PORT: published.imap,+ STALWART_TEST_SUBMISSIONS_PORT: published.submissions,+ STALWART_TEST_SUBMISSION_PORT: published.submission,+ STALWART_TEST_CA: tls + 'ca.crt',+ },+ })+ process.exitCode = tests.status || 0+} finally {+ // This exact container and its anonymous volumes belong only to this invocation.+ spawnSync(runtime, ['rm', '-f', '-v', name], { stdio: 'ignore' })+}diff --git a/scripts/test-deb.sh b/scripts/test-deb.shnew file mode 100755index 0000000..ce8ef18--- /dev/null+++ b/scripts/test-deb.sh@@ -0,0 +1,7 @@+#!/usr/bin/env bash+set -euo pipefail+cd "$(dirname "$0")/.."+runtime="${CONTAINER_RUNTIME:-podman}"+image="localhost/inlark-deb-smoke:bookworm"+"$runtime" build -t "$image" -f scripts/Containerfile.smoke scripts+"$runtime" run --rm --network=none -v "$PWD/apps/desktop/release:/release:ro" "$image"diff --git a/tests/command-rank.test.ts b/tests/command-rank.test.tsnew file mode 100644index 0000000..6eacd38--- /dev/null+++ b/tests/command-rank.test.ts@@ -0,0 +1,26 @@+import { describe, expect, it, vi } from 'vitest'++describe('command menu ranking', async () => {+ vi.stubGlobal('location', { search: '', protocol: 'file:' })+ vi.stubGlobal('window', {})+ const { rank } = await import('../apps/desktop/src/renderer/src/CommandPalette')+ vi.unstubAllGlobals()+ const command = (label: string, keywords?: string) => ({ label, keywords })++ it('matches word starts in the label and keywords', () => {+ expect(rank(command('Dark theme', 'appearance'), 'dark')).toBeGreaterThan(0)+ expect(rank(command('Dark theme', 'appearance'), 'appear')).toBeGreaterThan(0)+ expect(rank(command('Move to trash'), 'tra')).toBeGreaterThan(0)+ })++ it('prefers label matches that start earlier', () => {+ expect(rank(command('Archive'), 'arc')).toBeGreaterThan(rank(command('Go to archive'), 'arc'))+ expect(rank(command('Inbox'), 'in')).toBeGreaterThan(rank(command('Other', 'inbox'), 'in'))+ })++ it('does not match scattered letters, so typed searches fall through to mail search', () => {+ expect(rank(command('Mark as read'), 'mr')).toBe(0)+ expect(rank(command('Compose a message'), 'invoice')).toBe(0)+ expect(rank(command('Archive'), 'archive september')).toBe(0)+ })+})diff --git a/tests/connection-config.test.ts b/tests/connection-config.test.tsnew file mode 100644index 0000000..86ff479--- /dev/null+++ b/tests/connection-config.test.ts@@ -0,0 +1,61 @@+import { describe, it, expect } from 'vitest'+import { accountSchema, hostSchema, ipcSchemas } from '../packages/core/src'++const imap = {+ password: 'disposable',+ name: '',+ remember: false,+ config: {+ protocol: 'imap',+ email: '[email protected]',+ incoming: { host: 'imap.example.com', port: 993, security: 'tls', username: 'me' },+ outgoing: { host: 'smtp.example.com', port: 465, security: 'tls', username: 'me' },+ outgoingSameCredentials: true,+ },+} as const++describe('connection configuration validation', () => {+ it('accepts server names and addresses, never URLs or embedded ports', () => {+ for (const host of ['imap.example.com', 'mail.inlark.test', '127.0.0.1', '::1', 'localhost'])+ expect(hostSchema.safeParse(host).success, host).toBe(true)+ for (const host of ['https://example.com', 'example.com:993', 'a b', '-a.com', 'x.com/p', ''])+ expect(hostSchema.safeParse(host).success, host).toBe(false)+ })+ it('offers only TLS and required STARTTLS, with no plaintext option', () => {+ expect(accountSchema.safeParse(imap).success).toBe(true)+ for (const security of ['none', 'plain', 'opportunistic'])+ expect(+ accountSchema.safeParse({+ ...imap,+ config: { ...imap.config, incoming: { ...imap.config.incoming, security } },+ }).success,+ ).toBe(false)+ })+ it('requires a separate outgoing password only when credentials differ', () => {+ const separate = { ...imap, config: { ...imap.config, outgoingSameCredentials: false } }+ expect(accountSchema.safeParse(separate).success).toBe(false)+ expect(accountSchema.safeParse({ ...separate, outgoingPassword: 'other' }).success).toBe(true)+ })+ it('keeps legacy JMAP input shape out of the connect contract', () => {+ const legacy = {+ serverUrl: 'https://mail.example',+ username: 'me',+ password: 'x',+ name: '',+ remember: false,+ }+ expect(ipcSchemas.connect.safeParse([legacy]).success).toBe(false)+ expect(+ ipcSchemas.connect.safeParse([+ {+ ...legacy,+ config: { protocol: 'jmap', serverUrl: 'https://mail.example', username: 'me' },+ },+ ]).success,+ ).toBe(true)+ })+ it('validates discovery input as an address only', () => {+ expect(ipcSchemas.discover.safeParse([' [email protected] ']).data).toEqual(['[email protected]'])+ expect(ipcSchemas.discover.safeParse(['https://example.com']).success).toBe(false)+ })+})diff --git a/tests/core.test.ts b/tests/core.test.tsnew file mode 100644index 0000000..8eced81--- /dev/null+++ b/tests/core.test.ts@@ -0,0 +1,213 @@+import { describe, it, expect } from 'vitest'+import {+ accountKey,+ unlinkedServerDrafts,+ scopeKey,+ conversationFromMessages,+ mergePages,+ replyRecipients,+ parseAddresses,+ mailtoDraft,+ draftSchema,+ sendDraftSchema,+ defaultSettings,+ appearanceSchema,+ nextAccountColor,+ accountColors,+ type Message,+ type Draft,+} from '../packages/core/src'+export const message = (overrides: Partial<Message> = {}): Message => ({+ id: 'message',+ accountId: 'account',+ threadId: 'thread',+ subject: 'Hello',+ from: [{ name: 'Friend', email: '[email protected]' }],+ to: [{ name: 'Me', email: '[email protected]' }],+ cc: [],+ bcc: [],+ replyTo: [],+ receivedAt: '2026-09-23T10:00:00Z',+ preview: 'Hello',+ keywords: {},+ mailboxIds: { inbox: true },+ size: 100,+ hasAttachment: false,+ ...overrides,+})+export const draft = (overrides: Partial<Draft> = {}): Draft => ({+ id: 'fb4c0a00-254f-4fb1-965e-96d56ca9ef17',+ accountId: 'account',+ identityId: 'identity',+ to: [{ name: 'Friend', email: '[email protected]' }],+ cc: [],+ bcc: [],+ subject: 'Hello',+ html: '<p>Hello</p>',+ text: 'Hello',+ attachments: [],+ updatedAt: '2026-09-23T10:00:00.000Z',+ status: 'local',+ ...overrides,+})+describe('mail domain', () => {+ it('keeps identical remote IDs in different connections and accounts separate', () => {+ const a = accountKey('connection-a', 'same'),+ b = accountKey('connection-b', 'same')+ expect(scopeKey(a, 'same')).not.toBe(scopeKey(b, 'same'))+ expect(scopeKey('a,b', 'c')).not.toBe(scopeKey('a', 'b,c'))+ })+ it('offers every remote draft version without opening a related sent message', () => {+ const local = message({ id: 'local', keywords: { $draft: true } })+ const conflict = message({ id: 'conflict', keywords: { $draft: true } })+ const sent = message({ id: 'sent', keywords: { $seen: true } })+ const other = message({ id: 'local', accountId: 'other', keywords: { $draft: true } })+ const conversations = [+ conversationFromMessages('account', 'thread', [sent, local, conflict]),+ conversationFromMessages('other', 'thread', [other]),+ ]+ expect(+ unlinkedServerDrafts(conversations, [draft({ serverId: 'local' })]).map((m) =>+ scopeKey(m.accountId, m.id),+ ),+ ).toEqual([scopeKey('account', 'conflict'), scopeKey('other', 'local')])+ })+ it('merges pages without skipping unconsumed messages from another account', () => {+ const conv = (a: string, id: string, time: string) =>+ conversationFromMessages(a, id, [message({ accountId: a, threadId: id, receivedAt: time })])+ const page = mergePages(+ [+ {+ accountId: 'a',+ position: 0,+ page: {+ items: [+ conv('a', 'a1', '2026-09-23T11:00:00Z'),+ conv('a', 'a2', '2026-09-23T09:00:00Z'),+ ],+ total: 2,+ },+ },+ {+ accountId: 'b',+ position: 0,+ page: {+ items: [+ conv('b', 'b1', '2026-09-23T10:00:00Z'),+ conv('b', 'b2', '2026-09-23T08:00:00Z'),+ ],+ total: 2,+ },+ },+ ],+ 2,+ )+ expect(page.items.map((c) => c.id)).toEqual(['a1', 'b1'])+ expect(page.next).toEqual({ a: 1, b: 1 })+ })+ it('derives unread/starred state from the entire conversation', () => {+ const c = conversationFromMessages('a', 't', [+ message({ keywords: { $seen: true }, receivedAt: '2026-09-23T12:00:00Z' }),+ message({ keywords: { $flagged: true }, receivedAt: '2026-09-22T12:00:00Z' }),+ ])+ expect(c.unread).toBe(true)+ expect(c.starred).toBe(true)+ expect(c.count).toBe(2)+ })+ it('selects the receiving identity and excludes own aliases from reply-all', () => {+ const m = message({+ to: [+ { name: '', email: '[email protected]' },+ { name: '', email: '[email protected]' },+ ],+ cc: [{ name: '', email: '[email protected]' }],+ })+ const result = replyRecipients(+ m,+ [+ { id: 'main', accountId: 'account', name: 'Me', email: '[email protected]' },+ { id: 'alias', accountId: 'account', name: 'Me', email: '[email protected]' },+ ],+ true,+ )+ expect(result.identity?.id).toBe('alias')+ expect(result.cc.map((a) => a.email)).toEqual(['[email protected]'])+ })+ it('parses quoted recipient names and mailto fields', () => {+ expect(parseAddresses('"Chen, Maya" <[email protected]>; [email protected]')).toEqual([+ { name: 'Chen, Maya', email: '[email protected]' },+ { name: '', email: '[email protected]' },+ ])+ expect(+ mailtoDraft('mailto:[email protected]?subject=Hello%20world&body=Line%201%0ALine%202').text,+ ).toBe('Line 1\nLine 2')+ })+ it('autosaves incomplete addresses but disallows sending them', () => {+ const incomplete = draft({ to: [{ name: '', email: 'typing@' }] })+ expect(draftSchema.safeParse(incomplete).success).toBe(true)+ expect(sendDraftSchema.safeParse(incomplete).success).toBe(false)+ expect(sendDraftSchema.safeParse(draft()).success).toBe(true)+ })+})++describe('five-account pagination acceptance fixture', () => {+ it('visits 250,000 distinct conversations in globally descending order with bounded per-account windows', () => {+ const count = 50_000,+ accounts = ['a', 'b', 'c', 'd', 'e']+ let cursor: Record<string, number> | undefined+ let seen = 0+ let previous = '9999'+ const ids = new Set<string>()+ do {+ const pages = accounts+ .filter((a) => !cursor || a in cursor)+ .map((a, accountIndex) => {+ const position = cursor?.[a] || 0+ const items = Array.from({ length: Math.min(50, count - position) }, (_, offset) => {+ const index = position + offset,+ time = new Date(+ Date.UTC(2026, 8, 23) - index * 60_000 - accountIndex * 1000,+ ).toISOString()+ return conversationFromMessages(a, String(index), [+ message({ accountId: a, threadId: String(index), receivedAt: time }),+ ])+ })+ return {+ accountId: a,+ position,+ page: { items, total: count, next: position + 50 < count ? position + 50 : undefined },+ }+ })+ const page = mergePages(pages, 50)+ for (const item of page.items) {+ expect(item.receivedAt <= previous).toBe(true)+ previous = item.receivedAt+ ids.add(item.key)+ }+ seen += page.items.length+ cursor = page.next+ } while (cursor)+ expect(seen).toBe(250_000)+ expect(ids.size).toBe(250_000)+ }, 15000)+})++describe('account appearance', () => {+ it('accepts a pattern seed and a small raster picture and rejects anything else', () => {+ const png = 'data:image/png;base64,iVBORw0KGgo='+ expect(appearanceSchema.safeParse({}).success).toBe(true)+ expect(appearanceSchema.safeParse({ seed: 'a1b2c3d4', image: png }).success).toBe(true)+ expect(appearanceSchema.safeParse({ seed: '' }).success).toBe(false)+ expect(+ appearanceSchema.safeParse({ image: 'data:image/svg+xml;base64,PHN2Zz4=' }).success,+ ).toBe(false)+ expect(appearanceSchema.safeParse({ image: 'https://example.com/me.png' }).success).toBe(false)+ expect(appearanceSchema.safeParse({ image: png + 'A'.repeat(256 * 1024) }).success).toBe(false)+ })+ it('gives new accounts a colour no other account uses yet', () => {+ expect(nextAccountColor([])).toBe(accountColors[1])+ expect(nextAccountColor([accountColors[1], accountColors[2].toUpperCase()])).toBe(+ accountColors[3],+ )+ })+})diff --git a/tests/demo-avatars.test.ts b/tests/demo-avatars.test.tsnew file mode 100644index 0000000..087782c--- /dev/null+++ b/tests/demo-avatars.test.ts@@ -0,0 +1,41 @@+import { afterEach, describe, expect, it, vi } from 'vitest'+import { demoAccounts, demoAPI } from '../apps/desktop/src/renderer/src/demo'++afterEach(() => vi.unstubAllGlobals())++describe('demo sender pictures', () => {+ it('uses the initials fallback for Medium instead of an invisible icon', async () => {+ expect(await demoAPI.senderAvatar('[email protected]')).toBeNull()+ })++ it('uses real sender domains throughout the sample catalog', async () => {+ for (let index = 0; index < 21; index++) {+ const [message] = await demoAPI.conversation(demoAccounts[0].id, `thread-${index}`)+ const domain = message.from[0].email.split('@')[1]+ expect(domain).toMatch(/\.[a-z]{2,}$/)+ expect(domain.endsWith('.example')).toBe(false)+ }+ })++ it('loads pictures from the local resolver in the browser demo', async () => {+ const image = 'data:image/png;base64,aWNvbg=='+ const fetch = vi.fn(async () => new Response(JSON.stringify({ image })))+ vi.stubGlobal('window', {})+ vi.stubGlobal('fetch', fetch)++ expect(await demoAPI.senderAvatar('[email protected]')).toBe(image)+ expect(fetch).toHaveBeenCalledWith('/__demo/avatar?email=updates%40tm.openai.com', {+ credentials: 'omit',+ })+ })++ it('uses the desktop resolver in the native demo', async () => {+ const senderAvatar = vi.fn(async () => 'data:image/png;base64,aWNvbg==')+ vi.stubGlobal('window', { mail: { senderAvatar } })++ expect(await demoAPI.senderAvatar('[email protected]')).toBe(+ 'data:image/png;base64,aWNvbg==',+ )+ expect(senderAvatar).toHaveBeenCalledWith('[email protected]')+ })+})diff --git a/tests/discovery.test.ts b/tests/discovery.test.tsnew file mode 100644index 0000000..cfb75ec--- /dev/null+++ b/tests/discovery.test.ts@@ -0,0 +1,499 @@+import { describe, expect, it } from 'vitest'+import {+ discoverAccount,+ parseAutoconfig,+ serverSettingsSchema,+ serverUrlSchema,+ type DiscoveryResponse,+ type DiscoveryTransport,+ type SrvRecord,+} from '@inlark/core'++type Reply =+ Partial<DiscoveryResponse> | SrvRecord[] | Error | 'hang' | { delay: number; reply: Reply }+const hang = new Promise<never>(() => {})+function fakeTransport(http: Record<string, Reply> = {}, srv: Record<string, Reply> = {}) {+ const gets: { url: string; options: unknown }[] = []+ const lookups: string[] = []+ const settle = async <T>(reply: unknown, map: (r: never) => T): Promise<T> => {+ if (reply === 'hang') return hang+ if (reply instanceof Error) throw reply+ if (reply && typeof reply === 'object' && 'delay' in reply) {+ const { delay, reply: next } = reply as { delay: number; reply: unknown }+ await new Promise((resolve) => setTimeout(resolve, delay))+ return settle(next, map)+ }+ return map(reply as never)+ }+ const transport: DiscoveryTransport = {+ resolveSrv(name) {+ lookups.push(name)+ return settle(srv[name] ?? [], (r: SrvRecord[]) => r)+ },+ get(url, ...rest) {+ expect(rest).toHaveLength(1)+ gets.push({ url, options: rest[0] })+ return settle(http[url] ?? { status: 404 }, (r: Partial<DiscoveryResponse>) => ({+ status: 200,+ headers: {},+ body: '',+ ...r,+ }))+ },+ }+ return { transport, gets, lookups, urls: () => gets.map((g) => g.url) }+}++const email = '[email protected]'+const wellKnown = 'https://example.com/.well-known/jmap'+const autoconfigUrl = 'https://autoconfig.example.com/mail/config-v1.1.xml'+const wellKnownAutoconfig = 'https://example.com/.well-known/autoconfig/mail/config-v1.1.xml'+const directory = 'https://autoconfig.thunderbird.net/v1.1/example.com'+const srvRecord = (name: string, port: number, priority = 0, weight = 0) => ({+ name,+ port,+ priority,+ weight,+})+const server = (+ tag: string,+ type: string,+ host: string,+ port: number,+ socket: string,+ extra = '',+) =>+ `<${tag} type="${type}"><hostname>${host}</hostname><port>${port}</port><socketType>${socket}</socketType>${extra}</${tag}>`+function config(host: string, body?: string, name = 'Example Mail') {+ return `<?xml version="1.0" encoding="UTF-8"?>+<clientConfig version="1.1">+ <emailProvider id="example.com">+ <domain>example.com</domain>+ <displayName>${name}</displayName>+ ${+ body ??+ server(+ 'incomingServer',+ 'imap',+ host,+ 993,+ 'SSL',+ '<username>%EMAILADDRESS%</username><authentication>password-cleartext</authentication>',+ ) ++ server(+ 'outgoingServer',+ 'smtp',+ host,+ 465,+ 'SSL',+ '<username>%EMAILADDRESS%</username><authentication>password-cleartext</authentication>',+ )+ }+ </emailProvider>+</clientConfig>`+}+const hosts = (result: Awaited<ReturnType<typeof discoverAccount>>) =>+ result.candidates.map((c) =>+ c.protocol === 'jmap' ? `${c.source} ${c.serverUrl}` : `${c.source} ${c.incoming.host}`,+ )++describe('account discovery order', () => {+ it('lists JMAP before IMAP and IMAP sources in fixed order, whichever answers first', async () => {+ const fake = fakeTransport(+ {+ [wellKnown]: { delay: 15, reply: { status: 401 } },+ [autoconfigUrl]: { body: config('autoconfig.example.com') },+ [wellKnownAutoconfig]: { delay: 5, reply: { body: config('wellknown.example.com') } },+ [directory]: { body: config('directory.example.com') },+ },+ {+ '_jmap._tcp.example.com': { delay: 25, reply: [srvRecord('jmap.example.com', 443)] },+ '_imaps._tcp.example.com': [srvRecord('srv.example.com', 993)],+ '_submissions._tcp.example.com': [srvRecord('srv.example.com', 465)],+ },+ )+ const result = await discoverAccount(email, fake.transport)+ expect(result.domain).toBe('example.com')+ expect(hosts(result)).toEqual([+ 'jmap-srv https://jmap.example.com',+ 'jmap-well-known https://example.com',+ 'autoconfig autoconfig.example.com',+ 'autoconfig wellknown.example.com',+ 'imap-srv srv.example.com',+ ])+ // The domain published settings, so the public directory was never asked.+ expect(fake.urls()).not.toContain(directory)+ for (const c of result.candidates) {+ if (c.protocol === 'jmap') expect(serverUrlSchema.safeParse(c.serverUrl).success).toBe(true)+ else {+ expect(serverSettingsSchema.parse(c.incoming)).toEqual(c.incoming)+ expect(serverSettingsSchema.parse(c.outgoing)).toEqual(c.outgoing)+ }+ }+ })++ it('keeps only the earliest of identical candidates', async () => {+ const fake = fakeTransport(+ {+ [wellKnown]: { status: 401 },+ [autoconfigUrl]: { body: config('mail.example.com') },+ [wellKnownAutoconfig]: { body: config('mail.example.com') },+ [directory]: { body: config('mail.example.com', undefined, 'Directory name') },+ },+ { '_jmap._tcp.example.com': [srvRecord('example.com', 443)] },+ )+ const result = await discoverAccount(email, fake.transport)+ expect(result.candidates).toEqual([+ { protocol: 'jmap', source: 'jmap-srv', serverUrl: 'https://example.com', username: email },+ {+ protocol: 'imap',+ source: 'autoconfig',+ provider: 'Example Mail',+ incoming: { host: 'mail.example.com', port: 993, security: 'tls', username: email },+ outgoing: { host: 'mail.example.com', port: 465, security: 'tls', username: email },+ },+ ])+ })+})++describe('account discovery privacy and bounds', () => {+ it('sends only the domain, anonymously, over HTTPS', async () => {+ const fake = fakeTransport()+ await discoverAccount(` ${email.replace('example.com', 'Example.COM')} `, fake.transport)+ expect(fake.urls().sort()).toEqual(+ [wellKnown, autoconfigUrl, wellKnownAutoconfig, directory].sort(),+ )+ expect(fake.lookups.sort()).toEqual(+ [+ '_jmap._tcp.example.com',+ '_imaps._tcp.example.com',+ '_imap._tcp.example.com',+ '_submissions._tcp.example.com',+ '_submission._tcp.example.com',+ ].sort(),+ )+ for (const { url, options } of fake.gets) {+ expect(url.startsWith('https://')).toBe(true)+ expect(url).not.toMatch(/paul|private|@|emailaddress/i)+ expect(options).toEqual({ timeoutMs: 6000, maxBytes: 256 * 1024 })+ }+ for (const name of fake.lookups) expect(name).not.toMatch(/paul|private|@/)+ })++ it('rejects malformed addresses and skips IP-literal domains without any request', async () => {+ const fake = fakeTransport()+ await expect(discoverAccount('no-at-sign', fake.transport)).rejects.toThrow(/valid email/)+ await expect(discoverAccount('@example.com', fake.transport)).rejects.toThrow(/valid email/)+ await expect(discoverAccount('a@exa mple.com', fake.transport)).rejects.toThrow(/valid email/)+ await expect(discoverAccount('[email protected]/x', fake.transport)).rejects.toThrow(/valid email/)+ expect((await discoverAccount('a@[192.0.2.1]', fake.transport)).candidates).toEqual([])+ expect((await discoverAccount('[email protected]', fake.transport)).candidates).toEqual([])+ expect(fake.gets).toEqual([])+ expect(fake.lookups).toEqual([])+ })++ it('ignores oversized responses', async () => {+ const huge = config('mail.example.com').replace(+ '<domain>',+ `<!-- ${'x'.repeat(256 * 1024)} --><domain>`,+ )+ const fake = fakeTransport({ [autoconfigUrl]: { body: huge } })+ expect((await discoverAccount(email, fake.transport)).candidates).toEqual([])+ expect(() => parseAutoconfig(huge, email)).toThrow(/too large/)+ })++ it('keeps other sources when one fails or never answers', async () => {+ const fake = fakeTransport(+ {+ [wellKnown]: new Error('connection reset'),+ [autoconfigUrl]: 'hang',+ [wellKnownAutoconfig]: { body: '<clientConfig><broken' },+ [directory]: { body: config('directory.example.com') },+ },+ {+ '_jmap._tcp.example.com': new Error('SERVFAIL'),+ '_imaps._tcp.example.com': 'hang',+ '_imap._tcp.example.com': [srvRecord('imap.example.com', 143)],+ '_submission._tcp.example.com': [srvRecord('smtp.example.com', 587)],+ },+ )+ const result = await discoverAccount(email, fake.transport, { requestTimeoutMs: 20 })+ expect(result.candidates).toEqual([+ {+ protocol: 'imap',+ source: 'imap-srv',+ incoming: { host: 'imap.example.com', port: 143, security: 'starttls', username: email },+ outgoing: { host: 'smtp.example.com', port: 587, security: 'starttls', username: email },+ },+ ])+ })++ it('asks the public directory only when the domain publishes nothing', async () => {+ const fake = fakeTransport({ [directory]: { body: config('directory.example.com') } })+ const result = await discoverAccount(email, fake.transport)+ expect(result.candidates).toEqual([+ expect.objectContaining({ source: 'directory', provider: 'Example Mail' }),+ ])+ expect(fake.urls()).toContain(directory)+ })++ it('returns what it found by the deadline', async () => {+ const fake = fakeTransport(+ { [wellKnown]: { status: 401 }, [autoconfigUrl]: 'hang', [directory]: 'hang' },+ { '_jmap._tcp.example.com': 'hang' },+ )+ const started = Date.now()+ const result = await discoverAccount(email, fake.transport, {+ deadlineMs: 30,+ requestTimeoutMs: 1000,+ })+ expect(Date.now() - started).toBeLessThan(500)+ expect(hosts(result)).toEqual(['jmap-well-known https://example.com'])+ })+})++describe('JMAP discovery', () => {+ it('uses the best SRV record and ignores "." targets', async () => {+ const pick = async (records: SrvRecord[]) =>+ hosts(+ await discoverAccount(+ email,+ fakeTransport({}, { '_jmap._tcp.example.com': records }).transport,+ ),+ )+ expect(await pick([srvRecord('.', 0)])).toEqual([])+ expect(+ await pick([+ srvRecord('backup.example.net.', 443, 20, 100),+ srvRecord('light.example.net.', 443, 10, 1),+ srvRecord('Heavy.Example.NET.', 8443, 10, 50),+ srvRecord('.', 443, 0, 0),+ ]),+ ).toEqual(['jmap-srv https://heavy.example.net:8443'])+ })++ it('treats a session or an authentication challenge as evidence', async () => {+ const found = async (reply: Reply) =>+ hosts(await discoverAccount(email, fakeTransport({ [wellKnown]: reply }).transport))+ expect(await found({ status: 401 })).toEqual(['jmap-well-known https://example.com'])+ // A blanket firewall 403 must not outrank real IMAP settings.+ expect(await found({ status: 403 })).toEqual([])+ expect(await found({ body: '{"capabilities":{"urn:ietf:params:jmap:core":{}}}' })).toEqual([+ 'jmap-well-known https://example.com',+ ])+ expect(await found({ status: 404 })).toEqual([])+ expect(await found({ body: '<html>Welcome</html>' })).toEqual([])+ expect(await found({ body: '{"capabilities":null}' })).toEqual([])+ expect(await found({ status: 500 })).toEqual([])+ })++ it('follows HTTPS redirects and reports the final origin', async () => {+ const crossHost = fakeTransport({+ [wellKnown]: {+ status: 301,+ headers: { location: 'https://jmap.example.net/.well-known/jmap' },+ },+ 'https://jmap.example.net/.well-known/jmap': { status: 401 },+ })+ expect(hosts(await discoverAccount(email, crossHost.transport))).toEqual([+ 'jmap-well-known https://jmap.example.net',+ ])+ const relative = fakeTransport({+ [wellKnown]: { status: 307, headers: { location: '/jmap/session#ignored' } },+ 'https://example.com/jmap/session': { body: '{"capabilities":{}}' },+ })+ expect(hosts(await discoverAccount(email, relative.transport))).toEqual([+ 'jmap-well-known https://example.com/jmap/session',+ ])+ })++ it('stops after three redirects and never downgrades to HTTP', async () => {+ const chain = fakeTransport({+ [wellKnown]: { status: 302, headers: { location: 'https://a.example.com/' } },+ 'https://a.example.com/': { status: 302, headers: { location: 'https://b.example.com/' } },+ 'https://b.example.com/': { status: 302, headers: { location: 'https://c.example.com/' } },+ 'https://c.example.com/': { status: 302, headers: { location: 'https://d.example.com/' } },+ 'https://d.example.com/': { status: 401 },+ })+ expect((await discoverAccount(email, chain.transport)).candidates).toEqual([])+ expect(chain.urls()).not.toContain('https://d.example.com/')+ expect(chain.urls()).toContain('https://c.example.com/')++ const threeHops = fakeTransport({+ [wellKnown]: { status: 302, headers: { location: 'https://a.example.com/' } },+ 'https://a.example.com/': { status: 302, headers: { location: 'https://b.example.com/' } },+ 'https://b.example.com/': { status: 308, headers: { location: 'https://c.example.com/x' } },+ 'https://c.example.com/x': { status: 401 },+ })+ expect(hosts(await discoverAccount(email, threeHops.transport))).toEqual([+ 'jmap-well-known https://c.example.com/x',+ ])++ const downgrade = fakeTransport({+ [wellKnown]: { status: 301, headers: { location: 'http://example.com/.well-known/jmap' } },+ [autoconfigUrl]: { status: 302, headers: { location: 'http://autoconfig.example.com/' } },+ 'http://example.com/.well-known/jmap': { status: 401 },+ })+ expect((await discoverAccount(email, downgrade.transport)).candidates).toEqual([])+ expect(downgrade.urls().every((url) => url.startsWith('https://'))).toBe(true)+ })+})++describe('IMAP SRV discovery', () => {+ it('prefers implicit TLS and needs both directions', async () => {+ const both = fakeTransport(+ {},+ {+ '_imaps._tcp.example.com': [srvRecord('imap.example.com.', 993)],+ '_imap._tcp.example.com': [srvRecord('imap.example.com.', 143)],+ '_submissions._tcp.example.com': [srvRecord('.', 0)],+ '_submission._tcp.example.com': [srvRecord('smtp.example.com.', 587)],+ },+ )+ expect((await discoverAccount(email, both.transport)).candidates).toEqual([+ {+ protocol: 'imap',+ source: 'imap-srv',+ incoming: { host: 'imap.example.com', port: 993, security: 'tls', username: email },+ outgoing: { host: 'smtp.example.com', port: 587, security: 'starttls', username: email },+ },+ ])+ const incomingOnly = fakeTransport(+ {},+ { '_imaps._tcp.example.com': [srvRecord('imap.example.com', 993)] },+ )+ expect((await discoverAccount(email, incomingOnly.transport)).candidates).toEqual([])+ })+})++describe('autoconfig parsing', () => {+ const auth = (...methods: string[]) =>+ methods.map((m) => `<authentication>${m}</authentication>`).join('')+ const smtp = server('outgoingServer', 'smtp', 'smtp.example.com', 587, 'STARTTLS')++ it('substitutes placeholders and prefers TLS entries', () => {+ const parsed = parseAutoconfig(+ config(+ '',+ server(+ 'incomingServer',+ 'imap',+ 'imap.%EMAILDOMAIN%',+ 143,+ 'STARTTLS',+ '<username>%EMAILLOCALPART%</username>',+ ) ++ server('incomingServer', 'pop3', 'pop.example.com', 995, 'SSL') ++ server(+ 'incomingServer',+ 'IMAP',+ 'IMAP.%EMAILDOMAIN%.',+ 993,+ 'SSL',+ `<username>%EMAILADDRESS%</username>${auth('OAuth2', 'password-encrypted')}`,+ ) ++ smtp,+ ),+ '[email protected]',+ )+ expect(parsed).toEqual({+ provider: 'Example Mail',+ incoming: [+ { host: 'imap.example.com', port: 143, security: 'starttls', username: 'Paul' },+ { host: 'imap.example.com', port: 993, security: 'tls', username: '[email protected]' },+ ],+ outgoing: [+ { host: 'smtp.example.com', port: 587, security: 'starttls', username: '[email protected]' },+ ],+ })+ })++ it('drops plaintext, OAuth-only, and invalid servers', () => {+ const parsed = parseAutoconfig(+ config(+ '',+ server('incomingServer', 'imap', 'plain.example.com', 143, 'plain') ++ server('incomingServer', 'imap', 'oauth.example.com', 993, 'SSL', auth('OAuth2')) ++ server('incomingServer', 'imap', 'krb.example.com', 993, 'SSL', auth('GSSAPI', 'NTLM')) ++ server(+ 'incomingServer',+ 'imap',+ 'cert.example.com',+ 993,+ 'SSL',+ auth('client-IP-address', 'TLS-client-cert'),+ ) ++ server('incomingServer', 'imap', 'bad_host!.example.com', 993, 'SSL') ++ server('incomingServer', 'imap', 'https://imap.example.com', 993, 'SSL') ++ server('incomingServer', 'imap', 'port.example.com', 99999, 'SSL') ++ server('incomingServer', 'imap', 'port.example.com', 0, 'SSL') ++ server('outgoingServer', 'smtp', 'open.example.com', 25, 'STARTTLS', auth('none')),+ ),+ email,+ )+ expect(parsed.incoming).toEqual([])+ expect(parsed.outgoing).toEqual([])+ })++ it('needs an incoming and an outgoing server for a candidate', async () => {+ const fake = fakeTransport({+ [autoconfigUrl]: {+ body: config('', server('incomingServer', 'imap', 'imap.example.com', 993, 'SSL')),+ },+ })+ expect((await discoverAccount(email, fake.transport)).candidates).toEqual([])+ })++ it('decodes predefined and numeric entities, comments, and CDATA', () => {+ const parsed = parseAutoconfig(+ `<clientConfig><!-- note --><emailProvider id='x'>+ <displayName>A & B Mail M<![CDATA[ <co> ]]>${'x'.repeat(200)}</displayName>+ ${server('incomingServer', 'imap', 'imap.example.com', 993, 'SSL', '<username>a'b</username>')}+ <outgoingServer type="smtp"/>+ </emailProvider></clientConfig>`,+ email,+ )+ expect(parsed.provider).toBe(`A & B Mail M <co> ${'x'.repeat(200)}`.slice(0, 100))+ expect(parsed.incoming[0].username).toBe("a'b")+ expect(parsed.outgoing).toEqual([])+ })++ it('rejects DTDs, entities, processing instructions, and malformed XML', () => {+ const laughs = `<?xml version="1.0"?>+<!DOCTYPE lolz [<!ENTITY lol "lol"><!ENTITY lol2 "&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;">]>+<clientConfig><emailProvider><displayName>&lol2;</displayName></emailProvider></clientConfig>`+ const deep = `<clientConfig>${'<a>'.repeat(40)}${'</a>'.repeat(40)}</clientConfig>`+ const many = `<clientConfig>${'<a/>'.repeat(5000)}</clientConfig>`+ for (const xml of [+ laughs,+ '<!ENTITY x "y"><clientConfig/>',+ '<clientConfig><?php echo 1 ?></clientConfig>',+ '<?xml-stylesheet href="x"?><clientConfig/>',+ '<clientConfig><displayName>&custom;</displayName></clientConfig>',+ '<clientConfig><displayName>�</displayName></clientConfig>',+ '<clientConfig><displayName>a & b</displayName></clientConfig>',+ '<clientConfig><emailProvider></clientConfig>',+ '<clientConfig a="1" a="2"/>',+ '<clientConfig/><clientConfig/>',+ '<clientConfig/>trailing',+ '<clientConfig><!-- unterminated </clientConfig>',+ deep,+ many,+ '',+ ])+ expect(() => parseAutoconfig(xml, email), xml.slice(0, 60)).toThrow()+ expect(() => parseAutoconfig('<other/>', email)).toThrow(/autoconfig/)+ })++ it('never lets a malicious file escape discovery', async () => {+ const fake = fakeTransport({+ [autoconfigUrl]: {+ body: `<!DOCTYPE x [<!ENTITY a "${'a'.repeat(1000)}">]><clientConfig/>`,+ },+ [directory]: { body: config('directory.example.com') },+ })+ expect(hosts(await discoverAccount(email, fake.transport))).toEqual([+ 'directory directory.example.com',+ ])+ })+})diff --git a/tests/electron.stub.ts b/tests/electron.stub.tsnew file mode 100644index 0000000..60c1bcc--- /dev/null+++ b/tests/electron.stub.ts@@ -0,0 +1,8 @@+export const app = { getVersion: () => 'test' }+export const safeStorage = {+ isEncryptionAvailable: () => false,+ getSelectedStorageBackend: () => 'basic_text',+}+export const dialog = {}+export const shell = {}+export const Notification = { isSupported: () => false }diff --git a/tests/fixtures/tls/README.md b/tests/fixtures/tls/README.mdnew file mode 100644index 0000000..23fd9da--- /dev/null+++ b/tests/fixtures/tls/README.md@@ -0,0 +1,9 @@+# Test TLS fixtures++These certificates and private keys exist only for the automated tests. The keys are public, so never trust `ca.crt` or use any of these files outside tests.++- `ca.crt` / `ca.key`: the test certificate authority.+- `server.crt` / `server.key`: `localhost` and `127.0.0.1`, signed by the test CA.+- `untrusted.crt` / `untrusted.key`: a self-signed certificate for the same names that no test trusts.++Run `generate.sh` to recreate them (valid for 20 years).diff --git a/tests/fixtures/tls/ca.crt b/tests/fixtures/tls/ca.crtnew file mode 100644index 0000000..16f4b4b--- /dev/null+++ b/tests/fixtures/tls/ca.crt@@ -0,0 +1,11 @@+-----BEGIN CERTIFICATE-----+MIIBljCCAT2gAwIBAgIUUWUPp4ugv3oanm5/4vTR6D0ORqYwCgYIKoZIzj0EAwIw+GTEXMBUGA1UEAwwOSW5sYXJrIFRlc3QgQ0EwHhcNMjYwOTI2MTExMjUyWhcNNDYw+OTIxMTExMjUyWjAZMRcwFQYDVQQDDA5JbmxhcmsgVGVzdCBDQTBZMBMGByqGSM49+AgEGCCqGSM49AwEHA0IABB0NQ2qTQ0aIIclZYqbNouwGU0g0t/FcIFHtdHTyaz+s+iosy8wlq+yY+aHBbPkndtjnXIDJa4RMofAmDho3V/VCjYzBhMB0GA1UdDgQWBBQ9+LQ6MfnsuAYvuiE59slIxEvS+njAfBgNVHSMEGDAWgBQ9LQ6MfnsuAYvuiE59slIx+EvS+njAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAKBggqhkjOPQQD+AgNHADBEAiBhofVFfdv1itoaLuKz1LCzkhFETAK0A6nhby5Uqv2SiAIgZN38vVX8+vs2iSPmApifXtqRxOU/WcgBSpd0fVaSN9As=+-----END CERTIFICATE-----diff --git a/tests/fixtures/tls/ca.key b/tests/fixtures/tls/ca.keynew file mode 100644index 0000000..2b6c3b1--- /dev/null+++ b/tests/fixtures/tls/ca.key@@ -0,0 +1,5 @@+-----BEGIN PRIVATE KEY-----+MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg4P/9g58hpCAC05D8+/NmRwD+UZoXdSMBSlCc9vrNeoSWhRANCAAQdDUNqk0NGiCHJWWKmzaLsBlNINLfx+XCBR7XR08ms/rIqLMvMJavsmPmhwWz5J3bY51yAyWuETKHwJg4aN1f1Q+-----END PRIVATE KEY-----diff --git a/tests/fixtures/tls/generate.sh b/tests/fixtures/tls/generate.shnew file mode 100755index 0000000..da3fa5f--- /dev/null+++ b/tests/fixtures/tls/generate.sh@@ -0,0 +1,30 @@+#!/usr/bin/env bash+# Regenerates the test-only TLS fixtures. The keys are public and must never be trusted outside tests.+set -euo pipefail+cd "$(dirname "$0")"+days=7300+tmp=$(mktemp -d)+trap 'rm -rf "$tmp"' EXIT++# Test CA+openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:P-256 -nodes -days "$days" \+ -subj '/CN=Inlark Test CA' -keyout ca.key -out ca.crt \+ -addext 'basicConstraints=critical,CA:TRUE' -addext 'keyUsage=critical,keyCertSign,cRLSign'++# Server certificate for localhost and 127.0.0.1, signed by the test CA+openssl req -newkey ec -pkeyopt ec_paramgen_curve:P-256 -nodes -subj '/CN=localhost' \+ -keyout server.key -out "$tmp/server.csr"+cat > "$tmp/server.ext" <<'EXT'+basicConstraints=critical,CA:FALSE+keyUsage=critical,digitalSignature+extendedKeyUsage=serverAuth+subjectAltName=DNS:localhost,IP:127.0.0.1+EXT+openssl x509 -req -in "$tmp/server.csr" -CA ca.crt -CAkey ca.key -CAcreateserial -days "$days" \+ -extfile "$tmp/server.ext" -out server.crt+rm -f ca.srl++# Self-signed certificate for the same names that no test trusts+openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:P-256 -nodes -days "$days" \+ -subj '/CN=localhost' -keyout untrusted.key -out untrusted.crt \+ -addext 'subjectAltName=DNS:localhost,IP:127.0.0.1' -addext 'extendedKeyUsage=serverAuth'diff --git a/tests/fixtures/tls/server.crt b/tests/fixtures/tls/server.crtnew file mode 100644index 0000000..a392424--- /dev/null+++ b/tests/fixtures/tls/server.crt@@ -0,0 +1,12 @@+-----BEGIN CERTIFICATE-----+MIIBwjCCAWigAwIBAgIUTA6GizeBYvBXyuuDuOZhuxav92swCgYIKoZIzj0EAwIw+GTEXMBUGA1UEAwwOSW5sYXJrIFRlc3QgQ0EwHhcNMjYwOTI2MTExMjUyWhcNNDYw+OTIxMTExMjUyWjAUMRIwEAYDVQQDDAlsb2NhbGhvc3QwWTATBgcqhkjOPQIBBggq+hkjOPQMBBwNCAASHQThY/J9mv7vJbG3jBtXWQEE7bMPGeVCY8SNbbbBMme7jUxZS+XTPcXN6wEJBWC4/XuVw/NqCva2Wmu014gyZzo4GSMIGPMAwGA1UdEwEB/wQCMAAw+DgYDVR0PAQH/BAQDAgeAMBMGA1UdJQQMMAoGCCsGAQUFBwMBMBoGA1UdEQQTMBGC+CWxvY2FsaG9zdIcEfwAAATAdBgNVHQ4EFgQU1BSkcLCfjcPhIP2BMG/e27jGibYw+HwYDVR0jBBgwFoAUPS0OjH57LgGL7ohOfbJSMRL0vp4wCgYIKoZIzj0EAwIDSAAw+RQIhAJw9kJ1puHRBR7cprsI0nZCQAaVyzorH8DhNdFlqKc57AiA8lBoSTYvXUrKk+Xubzs2ToVfv+sAIvfxDR1jkwYR2YcA==+-----END CERTIFICATE-----diff --git a/tests/fixtures/tls/server.key b/tests/fixtures/tls/server.keynew file mode 100644index 0000000..f2bdaea--- /dev/null+++ b/tests/fixtures/tls/server.key@@ -0,0 +1,5 @@+-----BEGIN PRIVATE KEY-----+MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgt0zLU4bbMzjEvwyn+bi+EX8/3nG0NNLNq97QlePc2c/uhRANCAASHQThY/J9mv7vJbG3jBtXWQEE7bMPG+eVCY8SNbbbBMme7jUxZSXTPcXN6wEJBWC4/XuVw/NqCva2Wmu014gyZz+-----END PRIVATE KEY-----diff --git a/tests/fixtures/tls/untrusted.crt b/tests/fixtures/tls/untrusted.crtnew file mode 100644index 0000000..dc770c6--- /dev/null+++ b/tests/fixtures/tls/untrusted.crt@@ -0,0 +1,12 @@+-----BEGIN CERTIFICATE-----+MIIBrzCCAVagAwIBAgIULKx4ck6DCv6hznOToUrILz0Qs98wCgYIKoZIzj0EAwIw+FDESMBAGA1UEAwwJbG9jYWxob3N0MB4XDTI2MDkyNjExMTI1MloXDTQ2MDkyMTEx+MTI1MlowFDESMBAGA1UEAwwJbG9jYWxob3N0MFkwEwYHKoZIzj0CAQYIKoZIzj0D+AQcDQgAEJ5JbI+yixLr+3ByCHuzD/aExmVOnrJ9FEx32Gq7m0qEeuWvOD6OX6AsL+/nH1wH/BRgaJVzvTBLRXkwG344qRd6OBhTCBgjAdBgNVHQ4EFgQUnHBvZVD4UJFi+HPgV7/a6P0f6G9IwHwYDVR0jBBgwFoAUnHBvZVD4UJFiHPgV7/a6P0f6G9IwDwYD+VR0TAQH/BAUwAwEB/zAaBgNVHREEEzARgglsb2NhbGhvc3SHBH8AAAEwEwYDVR0l+BAwwCgYIKwYBBQUHAwEwCgYIKoZIzj0EAwIDRwAwRAIgN5IZCplPPhLygOZUgdY5+HyZVXsdq3XYafxvYL4fcACQCIEs7EHQ+PmXF7iD9pOMpGBfyFvdquOswa+Dn9WWI+JD1l+-----END CERTIFICATE-----diff --git a/tests/fixtures/tls/untrusted.key b/tests/fixtures/tls/untrusted.keynew file mode 100644index 0000000..232de99--- /dev/null+++ b/tests/fixtures/tls/untrusted.key@@ -0,0 +1,5 @@+-----BEGIN PRIVATE KEY-----+MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgjynDrHWxBjZnxKHB+cc1p72L7XG6FPQkRwp2Oqr3eRRChRANCAAQnklsj7KLEuv7cHIIe7MP9oTGZU6es+n0UTHfYarubSoR65a84Po5foCwv+cfXAf8FGBolXO9MEtFeTAbfjipF3+-----END PRIVATE KEY-----diff --git a/tests/imap-index.test.ts b/tests/imap-index.test.tsnew file mode 100644index 0000000..037789d--- /dev/null+++ b/tests/imap-index.test.ts@@ -0,0 +1,615 @@+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import { mkdtemp, readFile, rm, stat } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { fileURLToPath, pathToFileURL } from 'node:url'+import { Worker } from 'node:worker_threads'+import { DatabaseSync } from 'node:sqlite'+import {+ SqliteMetadataIndex,+ asyncIndex,+ openInProcessIndex,+} from '../apps/desktop/src/main/imap-index/sqlite-index'+import { WorkerMetadataIndex, type IndexPort } from '../apps/desktop/src/main/imap-index/client'+import type { FolderListing, IndexedMessage, MetadataIndex, NewMessage } from '@inlark/imap'++let directory: string+let path: string+let index: MetadataIndex++const folder = (path: string, extra: Partial<FolderListing> = {}): FolderListing => ({+ path,+ name: path.split('/').at(-1)!,+ delimiter: '/',+ parentPath: path.includes('/') ? path.slice(0, path.lastIndexOf('/')) : null,+ specialUse: null,+ guessedSpecialUse: null,+ noSelect: false,+ ...extra,+})++const day = (n: number) => new Date(Date.UTC(2024, 0, 1) + n * 3600_000).toISOString()++function message(mailboxId: string, uid: number, extra: Partial<NewMessage> = {}): NewMessage {+ return {+ mailboxId,+ uidValidity: '1',+ uid,+ messageId: 'm' + uid + '@example.com',+ inReplyTo: [],+ references: [],+ subject: 'Subject ' + uid,+ from: [{ name: 'Ada', email: '[email protected]' }],+ to: [{ name: '', email: '[email protected]' }],+ cc: [],+ bcc: [],+ replyTo: [],+ receivedAt: day(uid),+ size: 1000 + uid,+ flags: [],+ hasAttachment: false,+ preview: 'Preview ' + uid,+ ...extra,+ }+}++async function mailboxes(accountId = 'a', paths = ['INBOX', 'Archive', 'Sent', 'Junk']) {+ const list = await index.syncMailboxes(+ accountId,+ paths.map((path) => folder(path)),+ )+ return Object.fromEntries(list.map((mailbox) => [mailbox.path, mailbox.id]))+}++async function one(accountId: string, id: string) {+ const [found] = await index.messages(accountId, [id])+ return found!+}++beforeEach(async () => {+ directory = await mkdtemp(join(tmpdir(), 'inlark-index-'))+ path = join(directory, 'index', 'imap.sqlite')+ index = openInProcessIndex(path)+})+afterEach(async () => {+ await index.close()+ await rm(directory, { recursive: true, force: true })+})++describe('SQLite metadata index', () => {+ it('creates a private database and round-trips every stored field', async () => {+ expect((await stat(path)).mode & 0o777).toBe(0o600)+ expect((await stat(join(directory, 'index'))).mode & 0o777).toBe(0o700)+ const { INBOX } = await mailboxes()+ const input = message(INBOX!, 5, {+ modseq: '18446744073709551615',+ inReplyTo: ['[email protected]'],+ references: ['[email protected]', '[email protected]'],+ cc: [{ name: 'Grace "G" Hopper', email: '[email protected]' }],+ replyTo: [{ name: 'List', email: '[email protected]' }],+ sentAt: '2024-01-01T03:00:00.000Z',+ flags: ['\\Seen', '$Forwarded'],+ hasAttachment: true,+ bodyStructure: {+ type: 'multipart/mixed',+ childNodes: [+ { part: '1', type: 'text/plain', parameters: { charset: 'utf-8' }, size: 12 },+ {+ part: '2',+ type: 'application/pdf',+ disposition: 'attachment',+ dispositionParameters: { filename: 'ü.pdf' },+ encoding: 'base64',+ id: '<cid@x>',+ },+ ],+ },+ unsubscribe: { url: 'https://example.com/u', oneClick: true },+ })+ const [id] = await index.upsertMessages('a', [input])+ const stored = await one('a', id!)+ expect(stored).toEqual({ ...input, id, threadId: stored.threadId })+ // WAL and shared-memory files inherit the database's owner-only mode.+ for (const suffix of ['-wal', '-shm'])+ expect((await stat(path + suffix)).mode & 0o777).toBe(0o600)+ })++ it('keeps IDs and threads on re-upsert and refreshes only flags, modseq and preview', async () => {+ const { INBOX } = await mailboxes()+ const [id] = await index.upsertMessages('a', [message(INBOX!, 1, { modseq: '5' })])+ const before = await one('a', id!)+ const again = await index.upsertMessages('a', [+ message(INBOX!, 1, {+ modseq: '9',+ flags: ['\\Flagged'],+ preview: '',+ subject: 'Changed',+ messageId: '[email protected]',+ }),+ ])+ expect(again).toEqual([id])+ const after = await one('a', id!)+ expect(after).toMatchObject({+ threadId: before.threadId,+ modseq: '9',+ flags: ['\\Flagged'],+ preview: 'Preview 1',+ subject: 'Subject 1',+ })+ await index.upsertMessages('a', [message(INBOX!, 1, { preview: 'Fresh' })])+ expect((await one('a', id!)).preview).toBe('Fresh')+ await index.setPreview('a', id!, 'Set')+ expect((await one('a', id!)).preview).toBe('Set')+ expect(await index.counts('a')).toEqual({ messages: 1 })+ })++ it('relocates an ID after a confirmed move and keeps its thread', async () => {+ const { INBOX, Archive } = await mailboxes()+ const [root, reply] = await index.upsertMessages('a', [+ message(INBOX!, 1),+ message(INBOX!, 2, { inReplyTo: ['[email protected]'] }),+ ])+ const thread = (await one('a', root!)).threadId+ await index.updateMailbox('a', Archive!, { uidValidity: '7' })+ await index.relocate('a', reply!, { mailboxId: Archive!, uidValidity: '7', uid: 40 })+ expect(await one('a', reply!)).toMatchObject({ mailboxId: Archive, uid: 40, threadId: thread })+ expect(await index.knownUids('a', INBOX!)).toEqual([1])+ expect((await index.messagesAt('a', Archive!, [40])).map((m) => m.id)).toEqual([reply])+ await expect(+ index.relocate('a', reply!, { mailboxId: Archive!, uidValidity: '8', uid: 41 }),+ ).rejects.toThrow(/stale UIDVALIDITY/)+ await expect(+ index.relocate('a', 'missing', { mailboxId: Archive!, uidValidity: '7', uid: 41 }),+ ).rejects.toThrow(/Unknown message/)+ })++ it('invalidates stale locations after a UIDVALIDITY change', async () => {+ const { INBOX, Archive } = await mailboxes()+ await index.updateMailbox('a', INBOX!, {+ uidValidity: '1',+ uidNext: 4,+ highestModseq: '9',+ indexedFrom: 1,+ complete: true,+ total: 3,+ })+ await index.upsertMessages('a', [+ message(INBOX!, 1),+ message(INBOX!, 2),+ message(Archive!, 3, { inReplyTo: ['[email protected]'] }),+ ])+ await expect(index.updateMailbox('a', INBOX!, { uidValidity: '2' })).rejects.toThrow(+ /reset the mailbox/,+ )+ await expect(+ index.upsertMessages('a', [message(INBOX!, 9, { uidValidity: '2' })]),+ ).rejects.toThrow(/stale UIDVALIDITY/)+ await index.resetMailbox('a', INBOX!, '2')+ expect(await index.messagesAt('a', INBOX!, [1, 2])).toEqual([])+ expect(await index.knownUids('a', INBOX!)).toEqual([])+ expect(await index.knownUids('a', Archive!)).toEqual([3])+ const inbox = (await index.listMailboxes('a')).find((m) => m.id === INBOX)!+ expect(inbox).toMatchObject({+ uidValidity: '2',+ uidNext: null,+ highestModseq: null,+ indexedFrom: null,+ complete: false,+ })+ await expect(index.upsertMessages('a', [message(INBOX!, 1)])).rejects.toThrow(/stale/)+ const [fresh] = await index.upsertMessages('a', [message(INBOX!, 1, { uidValidity: '2' })])+ // The re-indexed message rejoins the conversation its reply already belongs to.+ const archived = (await index.messagesAt('a', Archive!, [3]))[0]!+ expect((await one('a', fresh!)).threadId).toBe(archived.threadId)+ })++ it('threads by References and In-Reply-To, never by subject or missing IDs', async () => {+ const { INBOX, Sent } = await mailboxes()+ const ids = await index.upsertMessages('a', [+ message(INBOX!, 1, { messageId: '<root@x>' }),+ message(INBOX!, 2, { messageId: 'r1@x', references: ['<root@x>'] }),+ message(INBOX!, 3, { messageId: 'r2@x', references: ['root@x', 'r1@x'] }),+ message(Sent!, 4, { messageId: 'r3@x', inReplyTo: ['r2@x'] }),+ message(INBOX!, 5, { messageId: 'lonely@x', subject: 'Subject 1' }),+ message(INBOX!, 6, { messageId: null, subject: 'Same' }),+ message(INBOX!, 7, { messageId: null, subject: 'Same' }),+ message(INBOX!, 8, { messageId: 'same-a@x', subject: 'Same' }),+ message(INBOX!, 9, { messageId: 'same-b@x', subject: 'Same' }),+ ])+ const threads = await Promise.all(ids.map(async (id) => (await one('a', id)).threadId))+ expect(new Set(threads.slice(0, 4)).size).toBe(1)+ expect(new Set(threads).size).toBe(6)+ expect((await one('a', ids[0]!)).messageId).toBe('root@x')+ // The same Message-ID in two folders (Sent and Inbox) is one conversation.+ const [copy] = await index.upsertMessages('a', [message(Sent!, 10, { messageId: 'r1@x' })])+ expect((await one('a', copy!)).threadId).toBe(threads[0])+ expect((await index.findByMessageId('a', '<r1@x>')).map((m) => m.id).sort()).toEqual(+ [ids[1], copy].sort(),+ )+ expect((await index.findByMessageId('a', 'r1@x', Sent!)).map((m) => m.id)).toEqual([copy])+ expect(+ (await index.threadMessages('a', [threads[0]!])).map((m: IndexedMessage) => m.uid),+ ).toEqual([1, 2, 3, 4, 10])+ })++ it('merges conversations when a newly indexed message links them and keeps old IDs', async () => {+ const { INBOX } = await mailboxes()+ // Only the reply to a missing parent, and a separate thread, are known at first.+ const [c, d] = await index.upsertMessages('a', [+ message(INBOX!, 3, { messageId: 'c@x', inReplyTo: ['b@x'] }),+ message(INBOX!, 4, { messageId: 'd@x' }),+ ])+ const [e] = await index.upsertMessages('a', [message(INBOX!, 5, { messageId: 'e@x' })])+ const threadC = (await one('a', c!)).threadId+ const threadD = (await one('a', d!)).threadId+ const threadE = (await one('a', e!)).threadId+ expect(new Set([threadC, threadD, threadE]).size).toBe(3)+ // `d` turns out to answer `e`: thread E merges into the older D.+ const [e2] = await index.upsertMessages('a', [+ message(INBOX!, 6, { messageId: 'e2@x', references: ['e@x', 'd@x'] }),+ ])+ expect((await one('a', e2!)).threadId).toBe(threadD)+ expect(await index.resolveThread('a', threadE)).toBe(threadD)+ // A late ancestor references both remaining threads; D (and alias E) merge into C.+ const [b] = await index.upsertMessages('a', [+ message(INBOX!, 2, { messageId: 'b@x', references: ['d@x'] }),+ ])+ const all = await index.messages('a', [b!, c!, d!, e!, e2!])+ expect(new Set(all.map((m) => m.threadId))).toEqual(new Set([threadC]))+ for (const old of [threadC, threadD, threadE])+ expect(await index.resolveThread('a', old)).toBe(threadC)+ for (const old of [threadD, threadE])+ expect((await index.threadMessages('a', [old])).map((m) => m.uid)).toEqual([2, 3, 4, 5, 6])+ expect(await index.resolveThread('a', 'unknown')).toBe('unknown')+ const { items } = await index.conversations('a', {}, { limit: 10 })+ expect(items).toHaveLength(1)+ expect(items[0]).toMatchObject({ threadId: threadC, count: 5 })+ })++ it('isolates accounts', async () => {+ const a = await mailboxes('a')+ const b = await mailboxes('b')+ const [ma] = await index.upsertMessages('a', [message(a.INBOX!, 1, { messageId: 'x@x' })])+ const [mb] = await index.upsertMessages('b', [+ message(b.INBOX!, 1, { messageId: 'y@x', references: ['x@x'] }),+ ])+ expect((await one('a', ma!)).threadId).not.toBe((await one('b', mb!)).threadId)+ expect(await index.messages('a', [mb!])).toEqual([])+ expect(await index.findByMessageId('b', 'x@x')).toEqual([])+ expect(await index.threadMessages('a', [(await one('b', mb!)).threadId])).toEqual([])+ expect(+ (await index.conversations('a', {}, { limit: 10 })).items.map((i) => i.latest.id),+ ).toEqual([ma])+ expect((await index.conversations('a', { mailboxIds: [b.INBOX!] }, { limit: 10 })).total).toBe(+ 0,+ )+ await expect(index.upsertMessages('a', [message(b.INBOX!, 2)])).rejects.toThrow(+ /Unknown mailbox/,+ )+ await expect(+ index.relocate('a', mb!, { mailboxId: a.Archive!, uidValidity: '1', uid: 9 }),+ ).rejects.toThrow(/Unknown message/)+ await index.removeMessages('a', [mb!])+ await index.removeUids('a', b.INBOX!, [1])+ expect(await index.counts('b')).toEqual({ messages: 1 })+ await index.setMeta('a', 'cursor', '1')+ expect(await index.getMeta('b', 'cursor')).toBeUndefined()+ expect(await index.listMailboxes('c')).toEqual([])+ })++ it('filters conversations and represents each by its newest matching message', async () => {+ const { INBOX, Archive, Junk } = await mailboxes()+ await index.upsertMessages('a', [+ message(INBOX!, 1, { messageId: 't1a', flags: ['\\Seen'] }),+ message(Archive!, 2, {+ messageId: 't1b',+ inReplyTo: ['t1a'],+ flags: ['\\Seen', '\\Flagged'],+ }),+ message(INBOX!, 3, { messageId: 't1c', inReplyTo: ['t1b'], flags: ['\\Seen'] }),+ message(INBOX!, 4, { messageId: 't2a', hasAttachment: true }),+ message(Junk!, 5, { messageId: 't3a', flags: ['\\Seen'] }),+ message(Archive!, 6, { messageId: 't4a', flags: ['\\seen'] }),+ ])+ const uids = async (filter: Parameters<MetadataIndex['conversations']>[1]) => {+ const result = await index.conversations('a', filter, { limit: 50 })+ return { uids: result.items.map((item) => item.latest.uid), total: result.total }+ }+ expect(await uids({})).toEqual({ uids: [6, 5, 4, 3], total: 4 })+ expect(await uids({ mailboxIds: [INBOX!] })).toEqual({ uids: [4, 3], total: 2 })+ expect(await uids({ mailboxIds: [Archive!] })).toEqual({ uids: [6, 2], total: 2 })+ expect(await uids({ mailboxIds: [Archive!, Junk!] })).toEqual({ uids: [6, 5, 2], total: 3 })+ expect(await uids({ mailboxIds: [] })).toEqual({ uids: [], total: 0 })+ expect(await uids({ excludeMailboxIds: [Junk!] })).toEqual({ uids: [6, 4, 3], total: 3 })+ expect(await uids({ excludeMailboxIds: [Junk!, INBOX!] })).toEqual({ uids: [6, 2], total: 2 })+ expect(await uids({ flagged: true })).toEqual({ uids: [2], total: 1 })+ expect(await uids({ unseen: true })).toEqual({ uids: [4], total: 1 })+ expect(await uids({ unseen: false, mailboxIds: [INBOX!] })).toEqual({ uids: [3], total: 1 })+ expect(await uids({ hasAttachment: true })).toEqual({ uids: [4], total: 1 })+ expect(await uids({ after: day(2), before: day(5) })).toEqual({ uids: [4, 3], total: 2 })+ expect(await uids({ before: day(3) })).toEqual({ uids: [2], total: 1 })+ const ids = (await index.messagesAt('a', INBOX!, [1, 4])).map((m) => m.id)+ expect(await uids({ ids })).toEqual({ uids: [4, 1], total: 2 })+ expect(await uids({ ids: [] })).toEqual({ uids: [], total: 0 })+ const first = (await index.conversations('a', { mailboxIds: [INBOX!] }, { limit: 50 })).items+ expect(first.map((item) => item.count)).toEqual([1, 3])+ expect(first[1]!.latest.mailboxId).toBe(INBOX)+ const offset = await index.conversations('a', {}, { limit: 2, offset: 1 })+ expect(offset.items.map((i) => i.latest.uid)).toEqual([5, 4])+ expect(offset.total).toBe(4)+ })++ it('pages with a keyset that ignores rows indexed between pages', async () => {+ const { INBOX } = await mailboxes()+ const batch: NewMessage[] = []+ for (let uid = 1; uid <= 60; uid++)+ // Pairs share a timestamp so the thread ID tie-break is exercised.+ batch.push(+ message(INBOX!, uid, {+ receivedAt: day(1000 + Math.floor(uid / 2)),+ inReplyTo: uid % 3 === 0 ? ['m' + (uid - 1) + '@example.com'] : [],+ }),+ )+ await index.upsertMessages('a', batch)+ const existing = (await index.conversations('a', {}, { limit: 1000 })).items.map(+ (i) => i.threadId,+ )+ const seen: string[] = []+ let after: { receivedAt: string; threadId: string } | undefined+ let uid = 100+ for (let pageNumber = 0; pageNumber < 100; pageNumber++) {+ const page = await index.conversations('a', {}, { limit: 7, after })+ if (!page.items.length) break+ seen.push(...page.items.map((i) => i.threadId))+ const last = page.items.at(-1)!+ after = { receivedAt: last.latest.receivedAt, threadId: last.threadId }+ // Newer and older new conversations, and an older reply into an already shown one.+ await index.upsertMessages('a', [+ message(INBOX!, uid++, { receivedAt: day(5000 + uid) }),+ message(INBOX!, uid++, { receivedAt: day(uid) }),+ message(INBOX!, uid++, {+ receivedAt: last.latest.receivedAt,+ inReplyTo: [last.latest.messageId!],+ }),+ ])+ }+ expect(new Set(seen).size).toBe(seen.length)+ for (const thread of existing) expect(seen).toContain(thread)+ })++ it('reconciles mailbox listings and renames', async () => {+ const first = await mailboxes('a', ['INBOX', 'Work', 'Work/2023', 'Old'])+ await index.upsertMessages('a', [message(first.Old!, 1), message(first['Work/2023']!, 2)])+ await index.updateMailbox('a', first.INBOX!, { total: 10, unread: 2, uidNext: 50 })+ const second = await index.syncMailboxes('a', [+ folder('INBOX', { specialUse: null, name: 'Inbox' }),+ folder('Work'),+ folder('Work/2023'),+ folder('Sent', { specialUse: '\\Sent', guessedSpecialUse: '\\Sent', noSelect: false }),+ ])+ const byPath = Object.fromEntries(second.map((m) => [m.path, m]))+ expect(second.map((m) => m.path)).toEqual(['INBOX', 'Work', 'Work/2023', 'Sent'])+ expect(byPath.INBOX).toMatchObject({ id: first.INBOX, name: 'Inbox', total: 10, uidNext: 50 })+ expect(byPath.Sent).toMatchObject({ specialUse: '\\Sent', uidValidity: null, complete: false })+ expect(Object.values(first)).not.toContain(byPath.Sent!.id)+ expect(await index.counts('a')).toEqual({ messages: 1 })+ await index.renameMailbox('a', first.Work!, 'Projects', 'Projects')+ const renamed = Object.fromEntries((await index.listMailboxes('a')).map((m) => [m.id, m]))+ expect(renamed[first.Work!]).toMatchObject({ path: 'Projects', parentPath: null })+ expect(renamed[first['Work/2023']!]).toMatchObject({+ path: 'Projects/2023',+ parentPath: 'Projects',+ })+ expect(await index.knownUids('a', first['Work/2023']!)).toEqual([2])+ await expect(index.renameMailbox('a', first.Work!, 'INBOX', 'INBOX')).rejects.toThrow(+ /already uses/,+ )+ })++ it('removes messages by UID and ID and stores metadata', async () => {+ const { INBOX } = await mailboxes()+ const ids = await index.upsertMessages(+ 'a',+ [5, 3, 9, 7].map((uid) => message(INBOX!, uid)),+ )+ expect(await index.knownUids('a', INBOX!)).toEqual([3, 5, 7, 9])+ await index.removeUids('a', INBOX!, [3, 4])+ await index.removeMessages('a', [ids[2]!])+ expect(await index.knownUids('a', INBOX!)).toEqual([5, 7])+ await index.updateFlags('a', INBOX!, [{ uid: 7, flags: ['\\Seen'], modseq: '12' }])+ expect((await index.messagesAt('a', INBOX!, [7]))[0]).toMatchObject({+ flags: ['\\Seen'],+ modseq: '12',+ })+ expect((await index.conversations('a', { unseen: true }, { limit: 5 })).total).toBe(1)+ await index.setMeta('a', 'k', 'one')+ await index.setMeta('a', 'k', 'two')+ expect(await index.getMeta('a', 'k')).toBe('two')+ await index.setMeta('a', 'k', undefined)+ expect(await index.getMeta('a', 'k')).toBeUndefined()+ })++ it('persists across reopening and fails closed on a newer schema', async () => {+ const { INBOX } = await mailboxes()+ const [id] = await index.upsertMessages('a', [message(INBOX!, 1)])+ await index.setMeta('a', 'state', 's1')+ await index.close()+ index = openInProcessIndex(path)+ expect(await index.getMeta('a', 'state')).toBe('s1')+ expect((await one('a', id!)).uid).toBe(1)+ const future = join(directory, 'future.sqlite')+ const db = new DatabaseSync(future)+ db.exec('CREATE TABLE unknown (x); PRAGMA user_version = 99')+ db.close()+ const bytes = await readFile(future)+ expect(() => new SqliteMetadataIndex(future)).toThrow(/newer version/)+ expect(await readFile(future)).toEqual(bytes)+ })++ it('answers conversation pages quickly on a large mailbox', async () => {+ const sync = new SqliteMetadataIndex(join(directory, 'large.sqlite'))+ const [inbox, archive] = sync.syncMailboxes('a', [folder('INBOX'), folder('Archive')])+ const started = performance.now()+ for (let start = 0; start < 50_000; start += 500) {+ const batch: NewMessage[] = []+ for (let uid = start + 1; uid <= start + 500; uid++)+ batch.push(+ message(uid % 10 === 0 ? archive!.id : inbox!.id, uid, {+ references: uid % 5 ? ['m' + (uid - (uid % 5)) + '@example.com'] : [],+ flags: uid % 7 ? ['\\Seen'] : [],+ }),+ )+ sync.upsertMessages('a', batch)+ }+ const built = performance.now()+ const page = sync.conversations('a', { mailboxIds: [inbox!.id] }, { limit: 50 })+ const next = sync.conversations(+ 'a',+ { mailboxIds: [inbox!.id] },+ {+ limit: 50,+ after: {+ receivedAt: page.items.at(-1)!.latest.receivedAt,+ threadId: page.items.at(-1)!.threadId,+ },+ },+ )+ const unread = sync.conversations('a', { unseen: true }, { limit: 50 })+ const done = performance.now()+ expect(page.items).toHaveLength(50)+ expect(page.total).toBe(10_000)+ expect(next.items[0]!.latest.receivedAt < page.items.at(-1)!.latest.receivedAt).toBe(true)+ expect(unread.items).toHaveLength(50)+ const ids = sync.messagesAt(+ 'a',+ inbox!.id,+ Array.from({ length: 3000 }, (_, i) => i * 3 + 1),+ )+ const searched = sync.conversations('a', { ids: ids.map((m) => m.id) }, { limit: 50 })+ expect(searched.items).toHaveLength(50)+ // Generous bounds keep CI stable; typical runs are several times faster.+ expect(built - started).toBeLessThan(10_000)+ expect(done - built).toBeLessThan(1_500)+ for (const filter of [+ { mailboxIds: [inbox!.id] },+ { mailboxIds: [inbox!.id, archive!.id] },+ { ids: ['x', 'y'] },+ { unseen: true },+ { flagged: true },+ {},+ ])+ for (const detail of sync.explainConversations('a', filter))+ expect(detail).not.toMatch(/^SCAN m\b/)+ sync.close()+ }, 60_000)+})++describe('worker metadata index client', () => {+ function fakePort(target: SqliteMetadataIndex) {+ const listeners: Record<string, ((value: never) => void)[]> = {}+ let terminated = false+ const emit = (event: string, value: unknown) =>+ listeners[event]?.forEach((listener) => listener(value as never))+ const port: IndexPort & { emit: typeof emit; hold: boolean; held: unknown[] } = {+ hold: false,+ held: [],+ emit,+ on(event: string, listener: (value: never) => void) {+ ;(listeners[event] ??= []).push(listener)+ return port+ },+ postMessage(value) {+ if (port.hold) return void port.held.push(value)+ // Structured cloning mirrors what crosses a real worker boundary.+ const { id, method, args } = structuredClone(value) as {+ id: number+ method: keyof SqliteMetadataIndex+ args: unknown[]+ }+ queueMicrotask(() => {+ try {+ const result = (target[method] as (...values: unknown[]) => unknown)(...args)+ emit('message', structuredClone({ id, result }))+ } catch (error) {+ emit('message', { id, error: { message: (error as Error).message } })+ }+ })+ },+ async terminate() {+ terminated = true+ emit('exit', 1)+ return 1+ },+ }+ return { port, terminated: () => terminated }+ }++ it('round-trips results and errors and closes the database', async () => {+ const target = new SqliteMetadataIndex(join(directory, 'rpc.sqlite'))+ const { port, terminated } = fakePort(target)+ const client = new WorkerMetadataIndex(port)+ const [inbox] = await client.syncMailboxes('a', [folder('INBOX')])+ const [id] = await client.upsertMessages('a', [message(inbox!.id, 1)])+ expect((await client.messages('a', [id!]))[0]).toMatchObject({ id, uid: 1 })+ await expect(client.updateMailbox('a', 'nope', {})).rejects.toThrow(/Unknown mailbox/)+ await client.close()+ expect(terminated()).toBe(true)+ await expect(client.counts('a')).rejects.toThrow(/closed/)+ expect(() => target.counts('a')).toThrow()+ })++ it('rejects pending calls when the worker exits or fails', async () => {+ const target = new SqliteMetadataIndex(join(directory, 'rpc.sqlite'))+ const { port } = fakePort(target)+ const client = new WorkerMetadataIndex(port)+ port.hold = true+ const pending = client.counts('a')+ port.emit('exit', 3)+ await expect(pending).rejects.toThrow(/stopped unexpectedly \(exit code 3\)/)+ await expect(client.getMeta('a', 'k')).rejects.toThrow(/stopped unexpectedly/)+ await client.close()+ const second = fakePort(target)+ const other = new WorkerMetadataIndex(second.port)+ second.port.hold = true+ const waiting = other.counts('a')+ second.port.emit('error', new Error('disk I/O error'))+ await expect(waiting).rejects.toThrow('disk I/O error')+ target.close()+ })++ it('runs the real worker entry in a worker thread', async () => {+ // Node strips the TypeScript types itself; the hook adds the extension the bundler would.+ const entry = fileURLToPath(+ new URL('../apps/desktop/src/main/imap-index/worker.ts', import.meta.url),+ )+ const shim = `+ const { registerHooks } = require('node:module')+ registerHooks({ resolve(specifier, context, next) {+ if (/^\\.\\.?\\//.test(specifier) && !/\\.[cm]?[jt]s$/.test(specifier)) specifier += '.ts'+ return next(specifier, context)+ } })+ import(${JSON.stringify(pathToFileURL(entry).href)})`+ const spawn = (file: string) =>+ new WorkerMetadataIndex(new Worker(shim, { eval: true, workerData: { path: file } }))+ const worker = spawn(join(directory, 'worker', 'real.sqlite'))+ const [inbox] = await worker.syncMailboxes('a', [folder('INBOX')])+ const [id] = await worker.upsertMessages('a', [message(inbox!.id, 1)])+ expect((await worker.conversations('a', {}, { limit: 5 })).items[0]!.latest.id).toBe(id)+ await expect(+ worker.relocate('a', 'nope', { mailboxId: inbox!.id, uidValidity: '1', uid: 2 }),+ ).rejects.toThrow(/Unknown message/)+ await worker.close()+ await expect(worker.counts('a')).rejects.toThrow(/closed/)+ const future = join(directory, 'future.sqlite')+ const db = new DatabaseSync(future)+ db.exec('PRAGMA user_version = 99')+ db.close()+ const failing = spawn(future)+ await expect(failing.counts('a')).rejects.toThrow(/newer version/)+ await failing.close()+ // Reopening in-process sees what the worker wrote.+ const reopened = asyncIndex(new SqliteMetadataIndex(join(directory, 'worker', 'real.sqlite')))+ expect(await reopened.counts('a')).toEqual({ messages: 1 })+ await reopened.close()+ })+})diff --git a/tests/imap-provider.test.ts b/tests/imap-provider.test.tsnew file mode 100644index 0000000..ae54483--- /dev/null+++ b/tests/imap-provider.test.ts@@ -0,0 +1,579 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { mkdtemp, rm } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { ProviderError, type Account, type ImapConnectionConfig } from '../packages/core/src'+import { ImapProvider, limitsFor, imapFlowOptions, ImapFlowPort } from '../packages/imap/src'+import { openInProcessIndex } from '../apps/desktop/src/main/imap-index/sqlite-index'+import { FakeImapServer } from './support/fake-imap'++const config: ImapConnectionConfig = {+ protocol: 'imap',+ email: '[email protected]',+ incoming: { host: 'imap.example.com', port: 993, security: 'tls', username: 'me' },+ outgoing: { host: 'smtp.example.com', port: 465, security: 'tls', username: 'me' },+ outgoingSameCredentials: true,+}+const me = { name: 'Me', email: '[email protected]' }+const alex = { name: 'Alex', email: '[email protected]' }+let directory: string+let server: FakeImapServer+let providers: ImapProvider[] = []+let account: Account++function provider(options: Partial<ConstructorParameters<typeof ImapProvider>[0]> = {}) {+ const p = new ImapProvider({+ connectionId: 'c1',+ name: 'Work',+ config,+ password: 'disposable',+ index: openInProcessIndex(join(directory, 'index-' + providers.length + '.sqlite')),+ readAttachment: async () => new TextEncoder().encode('attached'),+ background: false,+ ports: server.port,+ timing: { sentCopyGraceMs: 0, initialBatch: 5, historicalBatch: 5, previews: 0 },+ ...options,+ })+ providers.push(p)+ return p+}+async function connected(options: Parameters<typeof provider>[0] = {}) {+ const p = provider(options)+ ;[account] = await p.connect()+ return p+}+/** Runs the provider's background synchronization once, as the loop would. */+const sync = (p: ImapProvider) => (p as any).syncPass('all') as Promise<void>+const historical = async (p: ImapProvider) => {+ while (await (p as any).historicalBatch());+}+const at = (minute: number) => new Date(Date.UTC(2026, 8, 20, 10, minute)).toISOString()++beforeEach(async () => {+ directory = await mkdtemp(join(tmpdir(), 'inlark-imap-'))+ server = new FakeImapServer()+ providers = []+})+afterEach(async () => {+ for (const p of providers) await p.close()+ await rm(directory, { recursive: true, force: true })+})++describe('IMAP connection and folders', () => {+ it('uses server-declared special folders and marks name guesses for review', async () => {+ server.boxes.delete('Archive')+ server.addMailbox('Archives', null, '\\Archive')+ const p = await connected()+ const review = await p.folderMappings()+ expect(review.mappings.sent).toEqual({ path: 'Sent', source: 'server' })+ expect(review.mappings.archive).toEqual({ path: 'Archives', source: 'name' })+ const boxes = await p.mailboxes(account)+ expect(boxes.find((b) => b.name === 'Inbox')?.role).toBe('inbox')+ expect(boxes.find((b) => b.name === 'Sent')?.role).toBe('sent')+ })+ it('lets the user choose or create a missing folder, and that choice wins', async () => {+ server.boxes.delete('Archive')+ const p = await connected()+ expect((await p.folderMappings()).mappings.archive).toBeUndefined()+ const review = await p.setFolderMappings(account, {+ archive: { path: 'Old mail', create: true },+ junk: null,+ })+ expect(server.boxes.has('Old mail')).toBe(true)+ expect(review.mappings.archive).toEqual({ path: 'Old mail', source: 'user' })+ expect(review.mappings.junk).toBeNull()+ expect((await p.mailboxes(account)).find((b) => b.name === 'Junk')?.role).toBeNull()+ })+ it('creates a missing folder where the server keeps its folders', async () => {+ for (const path of ['Sent', 'Drafts', 'Trash', 'Archive', 'Junk']) server.boxes.delete(path)+ server.addMailbox('INBOX/Sent', '\\Sent')+ const p = await connected()+ const review = await p.setFolderMappings(account, {+ archive: { path: 'Archive', create: true },+ })+ expect(review.mappings.archive).toEqual({ path: 'INBOX/Archive', source: 'user' })+ expect(server.boxes.has('INBOX/Archive')).toBe(true)+ expect(server.boxes.has('Archive')).toBe(false)+ })+ it('reports incoming authentication failures without trying anything else', async () => {+ const p = provider({ password: 'wrong' })+ await expect(p.connect()).rejects.toMatchObject({ code: 'authentication' })+ expect(server.commands).toEqual([])+ })+ it('explains and disables unsafe actions when capabilities are missing', () => {+ expect(limitsFor(new Set(['MOVE', 'UIDPLUS']))).toEqual({})+ expect(limitsFor(new Set(['MOVE'])).destroy).toContain('UIDPLUS')+ expect(limitsFor(new Set(['MOVE'])).move).toBeUndefined()+ expect(limitsFor(new Set([])).move).toContain('MOVE nor UIDPLUS')+ })+})++describe('IMAP TLS policy', () => {+ it('verifies certificates and never falls back to plaintext', () => {+ const tls = imapFlowOptions({ ...config.incoming, password: 'x' }, 'command')+ expect(tls).toMatchObject({+ secure: true,+ tls: { rejectUnauthorized: true, minVersion: 'TLSv1.2' },+ })+ const starttls = imapFlowOptions(+ { ...config.incoming, port: 143, security: 'starttls', password: 'x' },+ 'idle',+ )+ expect(starttls).toMatchObject({+ secure: false,+ doSTARTTLS: true,+ tls: { rejectUnauthorized: true },+ })+ expect(starttls.servername).toBe('imap.example.com')+ expect(+ imapFlowOptions({ ...config.incoming, host: '127.0.0.1', password: 'x' }, 'command')+ .servername,+ ).toBeUndefined()+ })+ it('refuses a mailbox-wide EXPUNGE and a MOVE emulation in the adapter itself', async () => {+ const port = new ImapFlowPort({ ...config.incoming, password: 'x' }, 'command')+ ;(port as any).client.capabilities = new Map([['IMAP4rev1', true]])+ const expunge = vi.spyOn((port as any).client, 'messageDelete')+ const move = vi.spyOn((port as any).client, 'messageMove')+ expect(() => port.expunge([1])).toThrow(ProviderError)+ expect(() => port.move([1], 'Archive')).toThrow(ProviderError)+ expect(expunge).not.toHaveBeenCalled()+ expect(move).not.toHaveBeenCalled()+ })+})++describe('IMAP indexing and reading', () => {+ it('indexes recent Inbox mail first and reports incomplete results until history is indexed', async () => {+ for (let i = 0; i < 12; i++)+ server.deliver('INBOX', {+ messageId: 'm' + i + '@x',+ subject: 'Message ' + i,+ from: [alex],+ date: at(i),+ })+ const p = await connected()+ const events: any[] = []+ p.subscribe((e) => events.push(e))+ await sync(p)+ let page = await p.query(account, { view: 'inbox' })+ expect(page.items.map((c) => c.subject)).toEqual([+ 'Message 11',+ 'Message 10',+ 'Message 9',+ 'Message 8',+ 'Message 7',+ ])+ expect(page.incomplete).toBe(true)+ expect(events.find((e) => e.type === 'indexing').indexing).toMatchObject({+ indexed: 5,+ total: 12,+ complete: false,+ })+ await historical(p)+ // Historical indexing never looks like new mail.+ expect(events.filter((e) => e.type === 'changed' && !e.historical)).toHaveLength(1)+ expect(events.filter((e) => e.type === 'changed' && e.historical).length).toBeGreaterThan(0)+ page = await p.query(account, { view: 'inbox' })+ expect(page.total).toBe(12)+ expect(page.incomplete).toBeUndefined()+ expect(events.at(-1).indexing).toMatchObject({ indexed: 12, total: 12, complete: true })+ })+ it('paginates without duplicates while older mail is still being indexed', async () => {+ for (let i = 0; i < 12; i++)+ server.deliver('INBOX', { messageId: 'm' + i + '@x', subject: 'M' + i, date: at(i) })+ const p = await connected()+ await sync(p)+ const first = await p.query(account, { view: 'inbox' }, 0, 3)+ await historical(p)+ const second = await p.query(account, { view: 'inbox' }, first.next!, 3)+ const seen = [...first.items, ...second.items].map((c) => c.subject)+ expect(new Set(seen).size).toBe(6)+ expect(seen).toEqual(['M11', 'M10', 'M9', 'M8', 'M7', 'M6'])+ })+ it('groups a conversation across folders by Message-ID and References, never by subject alone', async () => {+ server.deliver('INBOX', {+ messageId: 'root@x',+ subject: 'Plans',+ from: [alex],+ date: at(1),+ text: 'Shall we?',+ })+ server.deliver('Sent', {+ messageId: 'reply@x',+ inReplyTo: 'root@x',+ references: ['root@x'],+ subject: 'Re: Plans',+ from: [me],+ date: at(2),+ text: 'Yes.',+ })+ server.deliver('INBOX', { messageId: 'other@x', subject: 'Plans', from: [alex], date: at(3) })+ const p = await connected()+ await sync(p)+ const page = await p.query(account, { view: 'all' })+ const plans = page.items.find((c) => c.count === 2)!+ expect(plans.messages.map((m) => m.subject).sort()).toEqual(['Plans', 'Re: Plans'])+ expect(page.items).toHaveLength(2)+ const messages = await p.conversation(account, plans.id)+ expect(messages.map((m) => m.text?.trim())).toEqual(['Shall we?', 'Yes.'])+ })+ it('joins a reply indexed before its ancestor and keeps the old conversation ID working', async () => {+ const p = await connected()+ server.deliver('INBOX', {+ messageId: 'b@x',+ references: ['a@x'],+ inReplyTo: 'a@x',+ subject: 'Re: A',+ date: at(2),+ })+ server.deliver('INBOX', {+ messageId: 'c@x',+ references: ['z@x'],+ subject: 'Re: A',+ date: at(3),+ })+ await sync(p)+ const before = (await p.query(account, { view: 'inbox' })).items+ expect(before).toHaveLength(2)+ // The shared ancestor arrives (e.g. from a folder indexed later) and references both lines.+ server.deliver('Archive', { messageId: 'a@x', references: ['z@x'], subject: 'A', date: at(1) })+ await sync(p)+ const after = (await p.query(account, { view: 'all' })).items+ expect(after).toHaveLength(1)+ for (const old of before) expect((await p.conversation(account, old.id)).length).toBe(3)+ })+ it('discards stale locations after a UIDVALIDITY change and reindexes', async () => {+ server.deliver('INBOX', { messageId: 'a@x', subject: 'A', date: at(1) })+ const p = await connected()+ await sync(p)+ const [before] = (await p.query(account, { view: 'inbox' })).items+ server.resetUidValidity('INBOX')+ server.deliver('INBOX', { messageId: 'b@x', subject: 'B', date: at(2) })+ await sync(p)+ const after = await p.query(account, { view: 'inbox' })+ expect(after.items.map((c) => c.subject)).toEqual(['B', 'A'])+ expect(after.items.find((c) => c.subject === 'A')!.messages[0].id).not.toBe(+ before.messages[0].id,+ )+ expect(await p.messages(account, [before.messages[0].id])).toEqual([])+ })+ it('notices messages expunged by another client', async () => {+ const uid = server.deliver('INBOX', { messageId: 'a@x', subject: 'A', date: at(1) })+ server.deliver('INBOX', { messageId: 'b@x', subject: 'B', date: at(2) })+ const p = await connected()+ await sync(p)+ server.remove('INBOX', uid)+ await sync(p)+ expect((await p.query(account, { view: 'inbox' })).items.map((c) => c.subject)).toEqual(['B'])+ })+ it('falls back to comparing flags when the server lacks CONDSTORE', async () => {+ server.capabilities.delete('CONDSTORE')+ const uid = server.deliver('INBOX', { messageId: 'a@x', subject: 'A', date: at(1) })+ const p = await connected()+ await sync(p)+ expect((await p.query(account, { view: 'inbox' })).items[0].unread).toBe(true)+ server.setFlags('INBOX', uid, ['\\Seen'])+ await sync(p)+ expect((await p.query(account, { view: 'inbox' })).items[0].unread).toBe(false)+ })+ it('searches on the server across folders and indexes matches it had not seen yet', async () => {+ for (let i = 0; i < 8; i++)+ server.deliver('Archive', { messageId: 'a' + i + '@x', subject: 'Old ' + i, date: at(i) })+ server.deliver('Archive', {+ messageId: 'needle@x',+ subject: 'Invoice',+ date: at(0),+ text: 'Needle inside',+ attachments: [{ name: 'invoice.pdf', type: 'application/pdf', content: 'pdf' }],+ })+ server.deliver('Junk', { messageId: 'spam@x', subject: 'Needle spam', date: at(9) })+ const p = await connected()+ await sync(p)+ const found = await p.query(account, { view: 'all', text: 'needle' })+ expect(found.items.map((c) => c.subject)).toEqual(['Invoice'])+ expect(found.items[0].hasAttachment).toBe(true)+ expect(+ (await p.query(account, { view: 'all', text: 'needle', hasAttachment: true })).items,+ ).toHaveLength(1)+ const [message] = await p.conversation(account, found.items[0].id)+ expect(message.attachments).toMatchObject([{ name: 'invoice.pdf', type: 'application/pdf' }])+ const bytes = await p.download(account, message.attachments![0])+ expect(new TextDecoder().decode(bytes)).toBe('pdf')+ })+ it('picks up new Inbox mail announced on the IDLE connection', async () => {+ const p = await connected({+ background: true,+ timing: { reconcileMs: 60_000, sentCopyGraceMs: 0, previews: 0 },+ })+ const changed = vi.fn()+ p.subscribe((e) => e.type === 'changed' && !e.historical && changed())+ await vi.waitFor(() => expect(server.ports.some((port) => port.purpose === 'idle')).toBe(true))+ await vi.waitFor(() => expect(server.commands).toContain('SEARCH'))+ server.deliver('INBOX', { messageId: 'new@x', subject: 'Fresh', date: at(5) })+ await vi.waitFor(async () =>+ expect((await p.query(account, { view: 'inbox' })).items.map((c) => c.subject)).toEqual([+ 'Fresh',+ ]),+ )+ expect(changed).toHaveBeenCalled()+ })+ it('reconnects the command connection after it drops', async () => {+ server.deliver('INBOX', { messageId: 'a@x', subject: 'A', date: at(1) })+ const p = await connected()+ await sync(p)+ server.commandPorts[0].drop()+ expect(+ (+ await p.conversationMetadata(account, [+ (await p.query(account, { view: 'inbox' })).items[0].id,+ ])+ ).length,+ ).toBe(1)+ expect(server.commandPorts).toHaveLength(2)+ })+})++describe('IMAP organization', () => {+ async function inboxMessage(p: ImapProvider) {+ await sync(p)+ const [conversation] = (await p.query(account, { view: 'inbox' })).items+ return conversation.messages[0]+ }+ it('moves with MOVE and keeps the message ID through the confirmed move', async () => {+ server.deliver('INBOX', { messageId: 'a@x', subject: 'A', date: at(1) })+ const p = await connected()+ const message = await inboxMessage(p)+ const boxes = await p.mailboxes(account)+ const inbox = boxes.find((b) => b.role === 'inbox')!.id+ const archive = boxes.find((b) => b.role === 'archive')!.id+ const result = await p.update(account, {+ [message.id]: { mailboxes: { [inbox]: false, [archive]: true } },+ })+ expect(result).toEqual({ updated: [message.id], failures: [] })+ expect(server.box('Archive').messages).toHaveLength(1)+ const [moved] = await p.messages(account, [message.id])+ expect(moved.mailboxIds).toEqual({ [archive]: true })+ })+ it('finds a moved message by Message-ID when the server does not report new UIDs', async () => {+ server.capabilities.delete('UIDPLUS')+ server.deliver('INBOX', { messageId: 'a@x', subject: 'A', date: at(1) })+ const p = await connected()+ const message = await inboxMessage(p)+ const boxes = await p.mailboxes(account)+ const [inbox, archive] = ['inbox', 'archive'].map((r) => boxes.find((b) => b.role === r)!.id)+ await p.update(account, { [message.id]: { mailboxes: { [inbox]: false, [archive]: true } } })+ expect((await p.messages(account, [message.id]))[0].mailboxIds).toEqual({ [archive]: true })+ })+ it('emulates MOVE only with UID EXPUNGE, leaving other clients’ pending deletions alone', async () => {+ server.capabilities.delete('MOVE')+ server.deliver('INBOX', { messageId: 'a@x', subject: 'A', date: at(1) })+ server.deliver('INBOX', {+ messageId: 'pending@x',+ subject: 'Pending',+ date: at(0),+ flags: ['\\Deleted'],+ })+ const p = await connected()+ await sync(p)+ const message = (await p.query(account, { view: 'inbox' })).items.find(+ (c) => c.subject === 'A',+ )!.messages[0]+ const boxes = await p.mailboxes(account)+ const [inbox, archive] = ['inbox', 'archive'].map((r) => boxes.find((b) => b.role === r)!.id)+ await p.update(account, { [message.id]: { mailboxes: { [inbox]: false, [archive]: true } } })+ expect(server.commands).toContain('COPY')+ expect(server.commands).toContain('UID EXPUNGE')+ expect(server.box('INBOX').messages.map((m) => m.input.subject)).toEqual(['Pending'])+ })+ it('refuses to move or permanently delete when that cannot be done safely', async () => {+ server.capabilities.delete('MOVE')+ server.capabilities.delete('UIDPLUS')+ server.deliver('INBOX', { messageId: 'a@x', subject: 'A', date: at(1) })+ const p = await connected()+ expect(account.limits?.move).toBeTruthy()+ const message = await inboxMessage(p)+ const boxes = await p.mailboxes(account)+ expect(boxes.every((b) => !b.rights.mayRemoveItems)).toBe(true)+ const [inbox, archive] = ['inbox', 'archive'].map((r) => boxes.find((b) => b.role === r)!.id)+ await expect(+ p.update(account, { [message.id]: { mailboxes: { [inbox]: false, [archive]: true } } }),+ ).rejects.toMatchObject({ code: 'unsupported' })+ await expect(p.update(account, {}, [message.id])).rejects.toMatchObject({ code: 'unsupported' })+ expect(server.box('INBOX').messages).toHaveLength(1)+ expect(server.commands).not.toContain('COPY')+ })+ it('permanently deletes exactly the chosen messages', async () => {+ server.deliver('Trash', { messageId: 'a@x', subject: 'A', date: at(1) })+ server.deliver('Trash', { messageId: 'b@x', subject: 'B', date: at(2), flags: ['\\Deleted'] })+ const p = await connected()+ await sync(p)+ const a = (await p.query(account, { view: 'trash' })).items.find((c) => c.subject === 'A')!+ .messages[0]+ expect(await p.update(account, {}, [a.id])).toEqual({ updated: [a.id], failures: [] })+ expect(server.box('Trash').messages.map((m) => m.input.subject)).toEqual(['B'])+ })+ it('reads current flags before acting and reports a concurrent change as a failure', async () => {+ const uid = server.deliver('INBOX', { messageId: 'a@x', subject: 'A', date: at(1) })+ const p = await connected()+ const message = await inboxMessage(p)+ // Another client flags the message between our read and our write.+ server.hooks.set('STORE:before', () => server.setFlags('INBOX', uid, ['\\Flagged']))+ const result = await p.update(account, { [message.id]: { keywords: { $seen: true } } })+ expect(result.failures).toEqual([message.id + ': changed on the server'])+ expect([...server.box('INBOX').messages[0].flags]).toEqual(['\\Flagged'])+ const [current] = await p.messages(account, [message.id])+ expect(current.keywords).toEqual({ $flagged: true })+ })+ it('refuses to delete a folder that still has messages', async () => {+ server.addMailbox('Projects')+ server.deliver('Projects', { messageId: 'p@x', subject: 'P', date: at(1) })+ const p = await connected()+ const id = (await p.mailboxes(account)).find((b) => b.name === 'Projects')!.id+ await expect(p.folder(account, 'delete', id)).rejects.toThrow('still contains messages')+ await p.folder(account, 'rename', id, 'Clients')+ expect(server.boxes.has('Clients')).toBe(true)+ expect((await p.mailboxes(account)).find((b) => b.name === 'Clients')?.id).toBe(id)+ })+})++describe('IMAP drafts and sending', () => {+ const draft = {+ id: 'fb4c0a00-254f-4fb1-965e-96d56ca9ef17',+ accountId: '',+ identityId: 'default',+ to: [alex],+ cc: [],+ bcc: [{ name: 'Secret', email: '[email protected]' }],+ subject: 'Grüße',+ html: '<p>Hallo</p>',+ text: 'Hallo',+ attachments: [],+ updatedAt: '2026-09-23T10:00:00.000Z',+ status: 'local' as const,+ }+ it('appends drafts with the Draft flag and confirms them before returning an ID', async () => {+ const p = await connected()+ const id = await p.createDraft(account, {+ ...draft,+ accountId: account.id,+ inReplyTo: ['root@x'],+ references: ['root@x'],+ })+ const stored = server.box('Drafts').messages[0]+ expect([...stored.flags].sort()).toEqual(['\\Draft', '\\Seen'])+ const [message] = await p.messages(account, [id], true)+ expect(message.keywords.$draft).toBe(true)+ expect(message.subject).toBe('Grüße')+ const raw = new TextDecoder().decode(stored.raw)+ expect(raw).toMatch(/^In-Reply-To: <root@x>/m)+ // Drafts keep Bcc so another client resuming the draft still sees it.+ expect(raw).toMatch(/^Bcc:/m)+ })+ it('keeps Bcc recipients in the envelope only', async () => {+ const p = await connected()+ const outgoing = await p.prepareSubmission(+ account,+ { ...draft, accountId: account.id },+ '[email protected]',+ )+ expect(outgoing.envelope).toEqual({+ from: '[email protected]',+ to: ['[email protected]', '[email protected]'],+ })+ const raw = new TextDecoder().decode(outgoing.mime)+ expect(raw).not.toMatch(/^Bcc:/im)+ expect(raw).not.toContain('[email protected]')+ expect(raw).toMatch(/^Message-ID: <[email protected]>/m)+ expect(server.commands).not.toContain('APPEND')+ })+ it('does not duplicate a Sent copy the server already filed', async () => {+ const p = await connected()+ const outgoing = await p.prepareSubmission(+ account,+ { ...draft, accountId: account.id },+ '[email protected]',+ )+ server.deliver('Sent', { messageId: '[email protected]', subject: 'Grüße' })+ expect(await p.fileSentCopy(account, outgoing)).toBe('server')+ expect(server.box('Sent').messages).toHaveLength(1)+ })+ it('reports an ambiguous append and reconciles it before appending again', async () => {+ const p = await connected()+ const outgoing = await p.prepareSubmission(+ account,+ { ...draft, accountId: account.id },+ '[email protected]',+ )+ // The server stores the copy but the response is lost.+ server.hooks.set('APPEND:after', () => {+ server.commandPorts.at(-1)!.drop()+ throw new ProviderError('network', 'Connection lost.')+ })+ await expect(p.fileSentCopy(account, outgoing)).rejects.toMatchObject({+ code: 'filingUncertain',+ })+ expect(await p.fileSentCopy(account, outgoing)).toBe('server')+ expect(server.box('Sent').messages).toHaveLength(1)+ })+ it('finds its own Sent copy even when the server search index lags behind', async () => {+ server.laggingSearch = true+ const p = await connected()+ const outgoing = await p.prepareSubmission(+ account,+ { ...draft, accountId: account.id },+ '[email protected]',+ )+ expect(await p.fileSentCopy(account, outgoing)).toBe('filed')+ expect(await p.fileSentCopy(account, outgoing)).toBe('server')+ expect(server.box('Sent').messages).toHaveLength(1)+ })+ it('asks for a Sent folder instead of guessing when none is mapped', async () => {+ server.boxes.delete('Sent')+ const p = await connected()+ const outgoing = await p.prepareSubmission(+ account,+ { ...draft, accountId: account.id },+ '[email protected]',+ )+ await expect(p.fileSentCopy(account, outgoing)).rejects.toMatchObject({ code: 'filing' })+ })+ it('submits through SMTP with the incoming login by default and never claims later proof', async () => {+ const submit = vi.fn().mockResolvedValue({ accepted: ['[email protected]'], rejected: [] })+ const verify = vi.fn().mockResolvedValue(undefined)+ const p = await connected({ smtp: { submit, verify } })+ await p.verifyOutgoing()+ const outgoing = await p.prepareSubmission(+ account,+ { ...draft, accountId: account.id },+ '[email protected]',+ )+ await p.submit(account, outgoing)+ expect(submit.mock.calls[0][0]).toMatchObject({+ host: 'smtp.example.com',+ username: 'me',+ password: 'disposable',+ })+ expect(verify).toHaveBeenCalledTimes(1)+ expect(await p.submissionExists()).toBe(false)+ })+ it('uses separate outgoing credentials when configured', async () => {+ const submit = vi.fn().mockResolvedValue({ accepted: [], rejected: [] })+ const p = await connected({+ config: {+ ...config,+ outgoingSameCredentials: false,+ outgoing: { ...config.outgoing, username: 'smtp-user' },+ },+ outgoingPassword: 'smtp-secret',+ smtp: { submit, verify: vi.fn() },+ })+ await p.submit(+ account,+ await p.prepareSubmission(account, { ...draft, accountId: account.id }, '[email protected]'),+ )+ expect(submit.mock.calls[0][0]).toMatchObject({+ username: 'smtp-user',+ password: 'smtp-secret',+ })+ })+})diff --git a/tests/jmap.test.ts b/tests/jmap.test.tsnew file mode 100644index 0000000..866b0fa--- /dev/null+++ b/tests/jmap.test.ts@@ -0,0 +1,352 @@+import { describe, it, expect, vi } from 'vitest'+import { JmapProvider, jmapFilter, jmapPatch, parseUnsubscribe } from '../packages/jmap/src'+import { ipcSchemas } from '../packages/core/src'+const core = 'urn:ietf:params:jmap:core',+ mail = 'urn:ietf:params:jmap:mail',+ submission = 'urn:ietf:params:jmap:submission'+const session = {+ apiUrl: 'https://mail.example/jmap',+ uploadUrl: 'https://mail.example/upload/{accountId}',+ downloadUrl: 'https://mail.example/download/{accountId}/{blobId}/{name}?type={type}',+ username: '[email protected]',+ accounts: { a: { name: 'Personal', accountCapabilities: { [mail]: {}, [submission]: {} } } },+ capabilities: {+ [core]: { maxObjectsInGet: 100, maxObjectsInSet: 100 },+ [mail]: {},+ [submission]: {},+ },+ primaryAccounts: { [mail]: 'a' },+ state: '1',+}+const raw = (id: string) => ({+ id,+ threadId: 'thread-' + id,+ receivedAt: '2026-09-23T10:00:00Z',+ subject: 'Sample',+ from: [{ email: '[email protected]', name: 'Sender' }],+ mailboxIds: { inbox: true },+ keywords: { $seen: true },+})+function fixture(overrides: Record<string, (args: any) => any> = {}, downloadBody?: string) {+ const calls: { name: string; args: any }[] = []+ const fetch = vi.fn(async (_url: any, init?: RequestInit) => {+ if (String(_url).includes('/download/') && downloadBody !== undefined)+ return new Response(downloadBody)+ if (!init?.body) return Response.json(session)+ const request = JSON.parse(String(init.body))+ return Response.json({+ methodResponses: request.methodCalls.map(([name, args, tag]: any) => {+ calls.push({ name, args })+ const response =+ overrides[name]?.(args) ??+ (+ {+ 'Mailbox/get': {+ list: [+ {+ id: 'inbox',+ name: 'Inbox',+ role: 'inbox',+ myRights: { mayReadItems: true },+ totalEmails: 50_000,+ unreadEmails: 1,+ },+ ],+ },+ 'Email/query': {+ ids: Array.from({ length: args.limit || 0 }, (_, i) =>+ String((args.position || 0) + i),+ ),+ total: 50_000,+ },+ 'Email/get': { list: (args.ids || []).map(raw) },+ 'Thread/get': {+ list: (args.ids || []).map((id: string) => ({+ id,+ emailIds: [id.replace('thread-', '')],+ })),+ },+ 'Email/set': { updated: {}, notUpdated: { bad: { type: 'forbidden' } } },+ } as any+ )[name]+ return [name, response, tag]+ }),+ })+ }) as unknown as typeof globalThis.fetch+ const provider = new JmapProvider({+ serverUrl: 'https://mail.example',+ connectionId: 'test',+ name: 'Test',+ authorization: 'Basic disposable',+ fetch,+ })+ return { provider, fetch, calls }+}+describe('JMAP provider', () => {+ it('loads only one conversation page from a 50k inbox and no bodies', async () => {+ const { provider, calls } = fixture()+ const [account] = await provider.connect()+ const page = await provider.query(account, { view: 'inbox' })+ expect(page.items).toHaveLength(50)+ expect(page.total).toBe(50_000)+ expect(page.next).toBe(50)+ const emailGets = calls.filter((c) => c.name === 'Email/get')+ expect(emailGets.flatMap((c) => c.args.ids)).toHaveLength(50)+ expect(emailGets.every((c) => !c.args.fetchAllBodyValues)).toBe(true)+ expect(calls.find((c) => c.name === 'Email/query')?.args.collapseThreads).toBe(true)+ })+ it('normalizes addresses without display names', async () => {+ const { provider } = fixture({+ 'Email/get': () => ({+ list: [+ {+ ...raw('unnamed'),+ from: [{ email: '[email protected]', name: null }],+ to: [{ email: '[email protected]', name: null }],+ cc: [{ email: '[email protected]' }],+ bcc: [{ email: '[email protected]', name: null }],+ replyTo: [{ email: '[email protected]', name: null }],+ },+ ],+ }),+ })+ const [account] = await provider.connect()+ const [message] = await provider.messages(account, ['unnamed'])+ expect(message.from).toEqual([{ email: '[email protected]', name: '' }])+ expect(message.to).toEqual([{ email: '[email protected]', name: '' }])+ expect(message.cc).toEqual([{ email: '[email protected]', name: '' }])+ expect(message.bcc).toEqual([{ email: '[email protected]', name: '' }])+ expect(message.replyTo).toEqual([{ email: '[email protected]', name: '' }])+ })+ it('omits null optional attachment fields before forwarding through IPC', async () => {+ const { provider } = fixture({+ 'Email/get': () => ({+ list: [+ {+ ...raw('forward'),+ bodyStructure: {+ type: 'multipart/mixed',+ subParts: [+ {+ blobId: 'attachment-blob',+ name: 'report.pdf',+ type: 'application/pdf',+ size: 42,+ cid: null,+ disposition: 'attachment',+ },+ {+ blobId: 'inline-blob',+ name: null,+ type: 'image/png',+ size: 12,+ cid: '[email protected]',+ disposition: null,+ },+ ],+ },+ },+ ],+ }),+ })+ const [account] = await provider.connect()+ const [message] = await provider.messages(account, ['forward'], true)+ expect(message.attachments).toEqual([+ {+ blobId: 'attachment-blob',+ name: 'report.pdf',+ type: 'application/pdf',+ size: 42,+ disposition: 'attachment',+ },+ {+ blobId: 'inline-blob',+ name: 'attachment',+ type: 'image/png',+ size: 12,+ cid: '[email protected]',+ },+ ])+ expect(+ ipcSchemas.stageRemoteAttachments.safeParse([account.id, message.attachments]).success,+ ).toBe(true)+ })+ it('sends with the name chosen in the app, falling back to the server identity name', async () => {+ const { provider } = fixture({+ 'Identity/get': () => ({+ list: [{ id: 'i1', name: 'Server Name', email: '[email protected]' }],+ }),+ })+ const [account] = await provider.connect()+ expect((await provider.identities(account))[0].name).toBe('Server Name')+ const [identity] = await provider.identities({ ...account, senderName: 'Jane Doe' })+ expect(identity).toMatchObject({ name: 'Jane Doe', email: '[email protected]' })+ })+ it('passes full-history filters and page offsets to the server', async () => {+ const { provider, calls } = fixture()+ const [account] = await provider.connect()+ await provider.query(+ account,+ { view: 'all', text: 'invoice', from: '[email protected]', hasAttachment: true },+ 49_950,+ )+ const q = calls.find((c) => c.name === 'Email/query')!.args+ expect(q.position).toBe(49_950)+ expect(JSON.stringify(q.filter)).toContain('[email protected]')+ expect(JSON.stringify(q.filter)).toContain('invoice')+ })+ it('uses the JMAP mailbox exclusion filter for starred mail and search', async () => {+ const mailboxes = [+ { id: 'spam-id', role: 'junk' },+ { id: 'trash-id', role: 'trash' },+ ] as Parameters<typeof jmapFilter>[1]+ expect(jmapFilter({ view: 'starred' }, mailboxes)).toEqual({+ operator: 'AND',+ conditions: [{ inMailboxOtherThan: ['spam-id', 'trash-id'] }, { hasKeyword: '$flagged' }],+ })+ expect(jmapFilter({ view: 'all', text: 'invoice' }, mailboxes)).toEqual({+ operator: 'AND',+ conditions: [{ inMailboxOtherThan: ['spam-id', 'trash-id'] }, { text: 'invoice' }],+ })+ expect(jmapFilter({ view: 'all' }, [])).toEqual({})+ })+ it('recovers an HTML body from nested MIME parts when htmlBody is empty', async () => {+ const { provider } = fixture({+ 'Email/get': () => ({+ list: [+ {+ ...raw('nested'),+ htmlBody: [{ type: 'text/html', partId: 'empty-part' }],+ bodyStructure: {+ type: 'multipart/alternative',+ subParts: [{ type: 'text/html', partId: 'html-part' }],+ },+ bodyValues: {+ 'empty-part': { value: ' ' },+ 'html-part': { value: '<p>Visible body</p>' },+ },+ },+ ],+ }),+ })+ const [account] = await provider.connect()+ expect((await provider.messages(account, ['nested'], true))[0].html).toBe('<p>Visible body</p>')+ })+ it('recovers a missing body value from its JMAP part blob', async () => {+ const { provider, fetch } = fixture(+ {+ 'Email/get': () => ({+ list: [+ {+ ...raw('blob'),+ htmlBody: [{ type: 'text/html', blobId: 'body-blob', size: 21 }],+ bodyValues: {},+ },+ ],+ }),+ },+ '<p>Recovered body</p>',+ )+ const [account] = await provider.connect()+ expect((await provider.messages(account, ['blob'], true))[0].html).toBe('<p>Recovered body</p>')+ expect(fetch.mock.calls.some(([url]) => String(url).includes('/download/'))).toBe(true)+ })+ it('surfaces per-object mutation failures', async () => {+ const { provider } = fixture()+ const [a] = await provider.connect()+ const result = await provider.update(a, { bad: { keywords: { $seen: true } } })+ expect(result.updated).toEqual([])+ expect(result.failures).toEqual(['bad: forbidden'])+ })+ it('accepts same-origin discovery redirects and rejects cross-origin endpoints', async () => {+ const fetch = vi+ .fn()+ .mockResolvedValueOnce(new Response(null, { status: 302, headers: { location: '/session' } }))+ .mockResolvedValueOnce(Response.json(session))+ const p = new JmapProvider({+ serverUrl: 'https://mail.example',+ connectionId: 'c',+ name: '',+ authorization: 'test',+ fetch,+ })+ expect(await p.connect()).toHaveLength(1)+ expect(fetch.mock.calls[1][0]).toBe('https://mail.example/session')+ const foreign = new JmapProvider({+ serverUrl: 'https://mail.example',+ connectionId: 'c',+ name: '',+ authorization: 'test',+ fetch: vi+ .fn()+ .mockResolvedValue(Response.json({ ...session, apiUrl: 'https://elsewhere.example/api' })),+ })+ await expect(foreign.connect()).rejects.toThrow('another origin')+ })+ it('reports rate limits without automatically replaying writes', async () => {+ const fetch = vi+ .fn()+ .mockResolvedValueOnce(Response.json(session))+ .mockResolvedValueOnce(new Response(null, { status: 429, headers: { 'retry-after': '60' } }))+ const p = new JmapProvider({+ serverUrl: 'https://mail.example',+ connectionId: 'c',+ name: '',+ authorization: 'test',+ fetch,+ })+ const [a] = await p.connect()+ await expect(p.update(a, { m: { keywords: { $seen: true } } })).rejects.toMatchObject({+ code: 'rateLimit',+ retryAfter: 60,+ })+ await expect(p.update(a, { m: { keywords: { $seen: true } } })).rejects.toMatchObject({+ code: 'rateLimit',+ })+ expect(fetch).toHaveBeenCalledTimes(2)+ })+ it('uses the operation snapshot state and surfaces stale writes without retrying', async () => {+ const { provider, calls } = fixture({+ 'Email/get': (args) => ({ list: args.ids.map(raw), state: 'snapshot' }),+ })+ const [account] = await provider.connect()+ await provider.messages(account, ['1'])+ const expected = provider.getStateToken(account)+ expect(expected).toBe('snapshot')+ await provider.update(account, { bad: { keywords: { $seen: true } } }, [], expected)+ expect(calls.find((c) => c.name === 'Email/set')!.args.ifInState).toBe('snapshot')+ const fetch = vi+ .fn()+ .mockResolvedValueOnce(Response.json(session))+ .mockResolvedValueOnce(+ Response.json({ methodResponses: [['error', { type: 'stateMismatch' }, 's']] }),+ )+ const stale = new JmapProvider({+ serverUrl: 'https://mail.example',+ connectionId: 'c',+ name: '',+ authorization: 'test',+ fetch,+ })+ const [a] = await stale.connect()+ await expect(+ stale.update(a, { m: { keywords: { $seen: true } } }, [], 'old'),+ ).rejects.toMatchObject({ code: 'stateMismatch' })+ expect(fetch).toHaveBeenCalledTimes(2)+ })+ it('translates typed changes into escaped JMAP patch paths', () => {+ expect(+ jmapPatch({ mailboxes: { inbox: false, 'custom/a~b': true }, keywords: { $seen: true } }),+ ).toEqual({+ 'mailboxIds/inbox': null,+ 'mailboxIds/custom~1a~0b': true,+ 'keywords/$seen': true,+ })+ })+ it('recognizes only supported unsubscribe destinations', () => {+ expect(+ parseUnsubscribe('<https://list.example/unsubscribe>', 'List-Unsubscribe=One-Click'),+ ).toEqual({ url: 'https://list.example/unsubscribe', oneClick: true })+ expect(parseUnsubscribe('<javascript:alert(1)>')).toBeUndefined()+ })+})diff --git a/tests/mail-mutations.test.ts b/tests/mail-mutations.test.tsnew file mode 100644index 0000000..1d325d5--- /dev/null+++ b/tests/mail-mutations.test.ts@@ -0,0 +1,106 @@+import { describe, expect, it } from 'vitest'+import type { Mailbox, Message } from '../packages/core/src'+import {+ planMutation,+ safeUndoUpdates,+ undoForUpdated,+} from '../apps/desktop/src/main/mail-mutations'++const rights: Mailbox['rights'] = {+ mayReadItems: true,+ mayAddItems: true,+ mayRemoveItems: true,+ maySetSeen: true,+ maySetKeywords: true,+ mayCreateChild: true,+ mayRename: true,+ mayDelete: true,+}+const boxes: Mailbox[] = ['inbox', 'archive', 'trash', 'custom/a~b'].map((id) => ({+ id,+ accountId: 'account',+ name: id,+ role: id.startsWith('custom') ? null : id,+ parentId: null,+ totalEmails: 0,+ unreadEmails: 0,+ rights: { ...rights },+}))+const message: Message = {+ id: 'message',+ accountId: 'account',+ threadId: 'thread',+ subject: 'Test',+ from: [],+ to: [],+ cc: [],+ bcc: [],+ replyTo: [],+ receivedAt: '2026-09-24T00:00:00Z',+ preview: '',+ keywords: {},+ mailboxIds: { inbox: true, 'custom/a~b': true },+ size: 0,+ hasAttachment: false,+}++describe('mail mutation planning', () => {+ it('archives only Inbox membership and preserves other folders', () => {+ const plan = planMutation([message, message], boxes, 'archive')+ expect(plan.changes).toEqual({+ message: { mailboxes: { inbox: false, archive: true } },+ })+ expect(plan.inverse).toEqual({+ message: { mailboxes: { inbox: true, archive: false } },+ })+ expect(plan.destroy).toEqual([])+ })++ it('only includes confirmed updates in undo and refuses to undo over later changes', () => {+ const second = { ...message, id: 'second' }+ const plan = planMutation([message, second], boxes, 'move', 'archive')+ expect(plan.changes.message.mailboxes).toMatchObject({ 'custom/a~b': false })+ const undo = undoForUpdated('account', plan, ['message'])+ expect(Object.keys(undo.changes)).toEqual(['message'])+ expect(safeUndoUpdates(undo, [{ ...message, mailboxIds: { archive: true } }])).toEqual({+ message: plan.inverse.message,+ })+ expect(+ safeUndoUpdates(undo, [{ ...message, mailboxIds: { archive: true, 'custom/a~b': true } }]),+ ).toEqual({})+ })++ it('never copies a message into a second folder on single-folder servers', () => {+ const sent: Message = { ...message, id: 'reply', mailboxIds: { sent: true } }+ const withSent = [...boxes, { ...boxes[0], id: 'sent', role: 'sent' }]+ // JMAP keeps every message in the conversation and adds Archive to the reply in Sent.+ expect(planMutation([message, sent], withSent, 'archive').changes.reply).toEqual({+ mailboxes: { archive: true },+ })+ // IMAP would copy it instead, so only the Inbox message moves.+ const exclusive = planMutation([message, sent], withSent, 'archive', undefined, {+ exclusiveMailboxes: true,+ })+ expect(exclusive.changes.reply).toBeUndefined()+ expect(exclusive.changes.message).toEqual({ mailboxes: { inbox: false, archive: true } })+ const trash = planMutation([message, sent], withSent, 'trash', undefined, {+ exclusiveMailboxes: true,+ })+ expect(trash.changes.reply).toEqual({ mailboxes: { sent: false, trash: true } })+ })+ it('keeps keyword changes for messages whose folder does not change', () => {+ const sent: Message = { ...message, id: 'reply', mailboxIds: { sent: true } }+ const plan = planMutation([sent], boxes, 'star', undefined, { exclusiveMailboxes: true })+ expect(plan.changes.reply).toEqual({ keywords: { $flagged: true } })+ expect(plan.inverse.reply).toEqual({ keywords: { $flagged: false } })+ })+ it('rejects moves without rights and deletion outside Trash', () => {+ const readOnly = boxes.map((box) =>+ box.id === 'inbox' ? { ...box, rights: { ...box.rights, mayRemoveItems: false } } : box,+ )+ expect(() => planMutation([message], readOnly, 'archive')).toThrow('cannot be moved')+ expect(() => planMutation([message], boxes, 'destroy')).toThrow(+ 'Only messages already in Trash',+ )+ })+})diff --git a/tests/mime.test.ts b/tests/mime.test.tsnew file mode 100644index 0000000..69e0d70--- /dev/null+++ b/tests/mime.test.ts@@ -0,0 +1,141 @@+import { describe, it, expect } from 'vitest'+import { composeMime, parseMime, type ComposeInput } from '../packages/imap/src/mime'++const png = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 1, 2, 3])+const binary = new Uint8Array(4096).map((_, i) => (i * 37 + 11) % 256)+const input = (overrides: Partial<ComposeInput> = {}): ComposeInput => ({+ from: { name: 'Jürgen Müller', email: '[email protected]' },+ to: [{ name: 'Zoë 山田', email: '[email protected]' }],+ cc: [{ name: '', email: '[email protected]' }],+ bcc: [{ name: 'Hidden Person', email: '[email protected]' }],+ subject: 'Grüße aus Köln 🌷 — a subject long enough to need folding across several header lines',+ html: '<p>Hallo <b>Zoë</b>, ein Bild: <img src="cid:logo@inlark"></p>',+ text: 'Hallo Zoë, schöne Grüße ✨\n.leading dot line\n',+ messageId: '[email protected]',+ inReplyTo: ['[email protected]'],+ references: ['[email protected]', '[email protected]'],+ date: new Date('2026-09-01T10:00:00Z'),+ attachments: [+ { name: 'logo.png', type: 'image/png', cid: 'logo@inlark', content: png },+ { name: 'Übersicht März.bin', type: 'application/octet-stream', content: binary },+ ],+ ...overrides,+})+const decode = (bytes: Uint8Array) => Buffer.from(bytes).toString('latin1')+const headers = (bytes: Uint8Array) => decode(bytes).split(/\r\n\r\n/)[0]++describe('MIME', () => {+ it('round trips Unicode, threading headers, inline images and binary attachments', async () => {+ const mime = await composeMime(input())+ expect(mime).toBeInstanceOf(Uint8Array)+ expect(Buffer.isBuffer(mime)).toBe(false)+ const head = headers(mime)+ expect(head).toMatch(/^Message-ID: <abc\.123@example\.test>$/m)+ expect(head).toMatch(/^In-Reply-To: <parent@example\.test>$/m)+ expect(head).toMatch(/^References: <root@example\.test> <parent@example\.test>$/m)+ expect(head).not.toMatch(/^(X-Mailer|User-Agent|X-Originating|Bcc):/im)+ expect(decode(mime)).toContain('multipart/related')+ expect(decode(mime)).toContain('multipart/alternative')+ // Every header line is 7-bit; Unicode is encoded.+ expect(/[^\x00-\x7f]/.test(head)).toBe(false)++ const parsed = await parseMime(mime)+ expect(parsed.subject).toBe(input().subject)+ expect(parsed.from).toEqual([{ name: 'Jürgen Müller', email: '[email protected]' }])+ expect(parsed.to).toEqual([{ name: 'Zoë 山田', email: '[email protected]' }])+ expect(parsed.cc).toEqual([{ name: '', email: '[email protected]' }])+ expect(parsed.bcc).toEqual([])+ expect(parsed.messageId).toBe('[email protected]')+ expect(parsed.inReplyTo).toEqual(['[email protected]'])+ expect(parsed.references).toEqual(['[email protected]', '[email protected]'])+ expect(parsed.date).toBe('2026-09-01T10:00:00.000Z')+ expect(parsed.text.trim()).toBe(input().text.trim())+ // cid links are kept, not rewritten to data URLs.+ expect(parsed.html).toContain('cid:logo@inlark')+ expect(parsed.html).toContain('<b>Zoë</b>')+ const [logo, file] = parsed.attachments+ expect(logo).toMatchObject({ name: 'logo.png', type: 'image/png', cid: 'logo@inlark' })+ expect(logo.disposition).toBe('inline')+ expect(logo.content).toEqual(png)+ expect(file).toMatchObject({+ name: 'Übersicht März.bin',+ type: 'application/octet-stream',+ disposition: 'attachment',+ size: binary.byteLength,+ })+ expect(file.cid).toBeUndefined()+ expect(Buffer.isBuffer(file.content)).toBe(false)+ expect(file.content).toEqual(binary)+ })++ it('keeps Bcc only for drafts', async () => {+ const sent = await composeMime(input())+ expect(decode(sent)).not.toContain('[email protected]')+ const draft = await composeMime(input({ keepBcc: true }))+ expect(headers(draft)).toMatch(/^Bcc: .*hidden@example\.test/m)+ expect((await parseMime(draft)).bcc).toEqual([+ { name: 'Hidden Person', email: '[email protected]' },+ ])+ })++ it('composes a text-only message and never invents HTML when parsing it', async () => {+ const mime = await composeMime(+ input({ html: '', attachments: [], bcc: [], inReplyTo: [], references: [] }),+ )+ expect(decode(mime)).not.toContain('multipart')+ expect(headers(mime)).not.toMatch(/^(In-Reply-To|References):/m)+ const parsed = await parseMime(mime)+ expect(parsed.html).toBe('')+ expect(parsed.text.trim()).toBe(input().text.trim())+ expect(parsed.inReplyTo).toEqual([])+ expect(parsed.references).toEqual([])+ expect(parsed.attachments).toEqual([])+ })++ it('parses List-Unsubscribe safely', async () => {+ const message = (unsubscribe: string, post = '') =>+ new TextEncoder().encode(+ [+ 'From: News <[email protected]>',+ 'To: [email protected]',+ 'Subject: Weekly',+ 'Message-ID: <[email protected]>',+ `List-Unsubscribe: ${unsubscribe}`,+ ...(post ? [`List-Unsubscribe-Post: ${post}`] : []),+ '',+ 'Hello',+ '',+ ].join('\r\n'),+ )+ expect(+ (+ await parseMime(+ message(+ '<mailto:[email protected]?subject=unsubscribe>,\r\n <https://example.test/u/1>',+ 'List-Unsubscribe=One-Click',+ ),+ )+ ).unsubscribe,+ ).toEqual({ url: 'https://example.test/u/1', oneClick: true })+ expect((await parseMime(message('<mailto:[email protected]>'))).unsubscribe).toEqual({+ url: 'mailto:[email protected]',+ oneClick: false,+ })+ expect((await parseMime(message('<javascript:alert(1)>'))).unsubscribe).toBeUndefined()+ expect(+ (await parseMime(message('<https://user:[email protected]/u>'))).unsubscribe,+ ).toBeUndefined()+ expect((await parseMime(message('<http://example.test/u>'))).unsubscribe).toBeUndefined()+ const plain = await parseMime(message('<https://example.test/u>'))+ expect(plain.html).toBe('')+ expect(plain.text.trim()).toBe('Hello')+ })++ it('enforces a size bound', async () => {+ const mime = await composeMime(input())+ await expect(parseMime(mime, { maxBytes: mime.byteLength - 1 })).rejects.toMatchObject({+ code: 'tooLarge',+ })+ await expect(parseMime(mime, { maxBytes: mime.byteLength })).resolves.toBeTruthy()+ })+})diff --git a/tests/public-fetch.test.ts b/tests/public-fetch.test.tsnew file mode 100644index 0000000..d260d4d--- /dev/null+++ b/tests/public-fetch.test.ts@@ -0,0 +1,67 @@+import { EventEmitter } from 'node:events'+import { describe, expect, it, vi } from 'vitest'++const { request } = vi.hoisted(() => ({ request: vi.fn() }))++vi.mock('node:dns/promises', () => ({+ lookup: async () => [{ address: '8.8.8.8', family: 4 }],+}))+vi.mock('node:https', () => ({ request }))++import { publicFetch } from '../apps/desktop/src/main/public-fetch'++describe('public resource requests', () => {+ it('accepts response headers without downloading a large unsubscribe confirmation page', async () => {+ const response = Object.assign(new EventEmitter(), {+ statusCode: 200,+ headers: { 'content-type': 'text/html; charset=utf-8' },+ destroy: vi.fn(),+ })+ const outgoing = Object.assign(new EventEmitter(), { end: vi.fn() })+ request.mockImplementation((_url, _options, onResponse) => {+ queueMicrotask(() => {+ onResponse(response)+ response.emit('data', Buffer.alloc(200_000))+ response.emit('end')+ })+ return outgoing+ })++ const result = await publicFetch('https://list.example/unsubscribe', {+ method: 'POST',+ body: 'List-Unsubscribe=One-Click',+ headersOnly: true,+ })++ expect(result).toMatchObject({ status: 200, type: 'text/html', bytes: Buffer.alloc(0) })+ expect(outgoing.end).toHaveBeenCalledWith('List-Unsubscribe=One-Click')+ expect(response.destroy).toHaveBeenCalledOnce()+ })++ it('returns a bounded prefix when fetching icon metadata from a large page', async () => {+ const response = Object.assign(new EventEmitter(), {+ statusCode: 200,+ headers: { 'content-type': 'text/html; charset=utf-8' },+ destroy: vi.fn(),+ })+ const outgoing = Object.assign(new EventEmitter(), { end: vi.fn() })+ request.mockImplementation((_url, _options, onResponse) => {+ queueMicrotask(() => {+ onResponse(response)+ response.emit('data', Buffer.from('icon'))+ response.emit('data', Buffer.from(' and the rest of a large page'))+ })+ return outgoing+ })++ const result = await publicFetch('https://large.example/', {+ maxBytes: 8,+ allowPartial: true,+ userAgent: 'Mozilla/5.0',+ })++ expect(result.bytes.toString()).toBe('icon and')+ expect(response.destroy).toHaveBeenCalledOnce()+ expect(request.mock.calls.at(-1)?.[1].headers).toMatchObject({ 'User-Agent': 'Mozilla/5.0' })+ })+})diff --git a/tests/reader-body.test.ts b/tests/reader-body.test.tsnew file mode 100644index 0000000..ed6af25--- /dev/null+++ b/tests/reader-body.test.ts@@ -0,0 +1,27 @@+import { createElement } from '../apps/desktop/node_modules/react'+import { renderToStaticMarkup } from '../apps/desktop/node_modules/react-dom/server'+import { describe, expect, it, vi } from 'vitest'+import type { Message } from '../packages/core/src'++describe('email body fallback', () => {+ it('shows plain text outside the HTML frame until the frame has readable content', async () => {+ vi.stubGlobal('location', { search: '', protocol: 'file:' })+ vi.stubGlobal('window', {})+ try {+ const { EmailBody } = await import('../apps/desktop/src/renderer/src/Reader')+ const message = {+ id: 'message',+ accountId: 'account',+ from: [],+ text: 'The message body remains readable.',+ } as Message+ const markup = renderToStaticMarkup(+ createElement(EmailBody, { message, remoteImages: false }),+ )+ expect(markup).toContain('class="email-fallback"')+ expect(markup).toContain('The message body remains readable.')+ } finally {+ vi.unstubAllGlobals()+ }+ })+})diff --git a/tests/remote-image.test.ts b/tests/remote-image.test.tsnew file mode 100644index 0000000..6604467--- /dev/null+++ b/tests/remote-image.test.ts@@ -0,0 +1,44 @@+import { describe, expect, it, vi } from 'vitest'+import { remoteImageData } from '../apps/desktop/src/main/remote-image'+import { publicFetch } from '../apps/desktop/src/main/public-fetch'++type FetchResource = typeof publicFetch+const png = Buffer.from('89504e470d0a1a0a', 'hex')++describe('remote message images', () => {+ it('follows public image redirects and identifies raster bytes despite a generic MIME type', async () => {+ const fetch = vi+ .fn<FetchResource>()+ .mockResolvedValueOnce({+ status: 302,+ type: 'text/html',+ bytes: Buffer.alloc(0),+ location: '/images/logo',+ })+ .mockResolvedValueOnce({ status: 200, type: 'application/octet-stream', bytes: png })+ expect(await remoteImageData('https://images.example/redirect', fetch)).toBe(+ `data:image/png;base64,${png.toString('base64')}`,+ )+ expect(fetch.mock.calls.map(([url]) => url)).toEqual([+ 'https://images.example/redirect',+ 'https://images.example/images/logo',+ ])+ })++ it('returns no image for unavailable content or unsafe redirect URLs', async () => {+ const failed = vi.fn<FetchResource>().mockRejectedValue(new Error('Network failure'))+ expect(await remoteImageData('https://images.example/missing', failed)).toBeNull()+ const html = vi+ .fn<FetchResource>()+ .mockResolvedValue({ status: 200, type: 'text/html', bytes: Buffer.from('<html>') })+ expect(await remoteImageData('https://images.example/not-image', html)).toBeNull()+ const redirect = vi.fn<FetchResource>().mockResolvedValue({+ status: 302,+ type: 'text/html',+ bytes: Buffer.alloc(0),+ location: 'file:///etc/passwd',+ })+ expect(await remoteImageData('https://images.example/redirect', redirect)).toBeNull()+ expect(redirect).toHaveBeenCalledTimes(1)+ })+})diff --git a/tests/selection.test.ts b/tests/selection.test.tsnew file mode 100644index 0000000..434c935--- /dev/null+++ b/tests/selection.test.ts@@ -0,0 +1,34 @@+import { describe, expect, it } from 'vitest'+import { selectConversation } from '../apps/desktop/src/renderer/src/selection'++describe('conversation selection', () => {+ const keys = ['personal:1', 'studio:1', 'personal:2', 'studio:2', 'personal:3']++ it('selects and deselects a single conversation without mutating existing selection', () => {+ const selected = new Set(['personal:1'])+ expect(selectConversation(keys, selected, 'studio:1')).toEqual(new Set(keys.slice(0, 2)))+ expect(selectConversation(keys, selected, 'personal:1')).toEqual(new Set())+ expect(selected).toEqual(new Set(['personal:1']))+ })++ it.each([+ ['studio:1', 'studio:2'],+ ['studio:2', 'studio:1'],+ ])('selects the range from %s to %s, preserving selections outside it', (anchor, target) => {+ expect(selectConversation(keys, new Set(['personal:3']), target, anchor)).toEqual(+ new Set(keys.slice(1)),+ )+ })++ it('falls back to single selection when an anchor is no longer in the list', () => {+ expect(selectConversation(keys, new Set(), 'studio:1', 'removed')).toEqual(+ new Set(['studio:1']),+ )+ })++ it('ignores a target that is no longer in the list', () => {+ expect(selectConversation(keys, new Set(['personal:1']), 'removed', 'studio:1')).toEqual(+ new Set(['personal:1']),+ )+ })+})diff --git a/tests/sender-avatar.test.ts b/tests/sender-avatar.test.tsnew file mode 100644index 0000000..4732092--- /dev/null+++ b/tests/sender-avatar.test.ts@@ -0,0 +1,243 @@+import { describe, expect, it, vi } from 'vitest'+import {+ advertisedIcons,+ parentBrandDomain,+ SenderAvatarResolver,+} from '../apps/desktop/src/main/sender-avatar'++const pixels = Buffer.from(+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQIHWP4z8DwHwAFgAI/ScL/nwAAAABJRU5ErkJggg==',+ 'base64',+)+const image = (label: string, type = 'image/png') => ({+ status: 200,+ type,+ bytes: pixels,+ label,+})+const missing = { status: 404, type: 'text/plain', bytes: Buffer.alloc(0) }++describe('sender avatars', () => {+ it('uses a personal picture before a brand mark', async () => {+ const fetch = vi.fn(async () => image('portrait'))+ const resolver = new SenderAvatarResolver(fetch)+ expect(await resolver.get(' [email protected] ')).toBe(+ `data:image/png;base64,${pixels.toString('base64')}`,+ )+ expect(fetch).toHaveBeenCalledOnce()+ expect(fetch.mock.calls[0][0]).toMatch(+ /^https:\/\/gravatar\.com\/avatar\/[a-f0-9]{64}\?s=96&d=404$/,+ )+ })++ it('uses an advertised brand icon and shares it across senders on the same domain', async () => {+ const requested: string[] = []+ const fetch = vi.fn(async (url: string) => {+ requested.push(url)+ if (url === 'https://brand.com/')+ return {+ status: 200,+ type: 'text/html',+ bytes: Buffer.from(+ '<link rel="icon" href="/small.ico"><link href="/brand.png" rel="apple-touch-icon">',+ ),+ }+ if (url === 'https://brand.com/brand.png') return image('brand')+ return missing+ })+ const resolver = new SenderAvatarResolver(fetch)+ const result = await Promise.all([resolver.get('[email protected]'), resolver.get('[email protected]')])+ expect(result).toEqual([+ `data:image/png;base64,${pixels.toString('base64')}`,+ `data:image/png;base64,${pixels.toString('base64')}`,+ ])+ expect(requested.filter((url) => url === 'https://brand.com/')).toHaveLength(1)+ expect(requested).not.toContain('https://brand.com/small.ico')+ })++ it('falls back to the conventional favicon and then initials when no image exists', async () => {+ const resolver = new SenderAvatarResolver(async (url) =>+ url === 'https://brand.com/favicon.ico' ? image('icon', 'image/x-icon') : missing,+ )+ expect(await resolver.get('[email protected]')).toBe(+ `data:image/png;base64,${pixels.toString('base64')}`,+ )+ const absent = new SenderAvatarResolver(async () => missing)+ expect(await absent.get('[email protected]')).toBeNull()+ expect(await absent.get('[email protected]')).toBeNull()+ expect(await absent.get('hello@localhost')).toBeNull()+ })++ it('accepts HTTPS icons from a site CDN and ignores insecure icons', () => {+ expect(+ advertisedIcons(+ '<link rel="icon" href="https://cdn.brand.com/icon.png"><link rel="icon" href="http://brand.com/insecure.png"><link rel="apple-touch-icon" href="/logo.png">',+ 'https://brand.com',+ ),+ ).toEqual(['https://brand.com/logo.png', 'https://cdn.brand.com/icon.png'])+ })++ it('follows bounded HTTPS redirects for homepages and icon assets', async () => {+ const requested: string[] = []+ const fetch = vi.fn(async (url: string) => {+ requested.push(url)+ if (url === 'https://brand.com/')+ return { ...missing, status: 301, location: 'https://www.brand.com/' }+ if (url === 'https://www.brand.com/')+ return {+ status: 200,+ type: 'text/html',+ bytes: Buffer.from('<link rel="icon" href="/icon.png">'),+ }+ if (url === 'https://www.brand.com/icon.png')+ return { ...missing, status: 302, location: 'https://cdn.brand.com/icon.png' }+ if (url === 'https://cdn.brand.com/icon.png') return image('icon', 'application/octet-stream')+ return missing+ })+ const resolver = new SenderAvatarResolver(fetch)+ expect(await resolver.get('[email protected]')).toBe(+ `data:image/png;base64,${pixels.toString('base64')}`,+ )+ expect(requested).toContain('https://cdn.brand.com/icon.png')+ })++ it('tries the parent domain for mail subdomains without requesting public suffixes', async () => {+ const requested: string[] = []+ const resolver = new SenderAvatarResolver(async (url) => {+ requested.push(url)+ return url === 'https://openai.com/favicon.ico' ? image('icon') : missing+ })+ expect(await resolver.get('[email protected]')).toBe(+ `data:image/png;base64,${pixels.toString('base64')}`,+ )+ expect(requested).toContain('https://openai.com/favicon.ico')+ expect(parentBrandDomain('mail.google.co.uk')).toBe('google.co.uk')+ expect(parentBrandDomain('mail.co.uk')).toBeNull()+ })++ it('reaches the root domain through deeper mail subdomains', async () => {+ const requested: string[] = []+ const resolver = new SenderAvatarResolver(async (url) => {+ requested.push(url)+ return url === 'https://openai.com/favicon.ico' ? image('icon') : missing+ })+ expect(await resolver.get('[email protected]')).toBe(+ `data:image/png;base64,${pixels.toString('base64')}`,+ )+ expect(requested).toContain('https://tm.openai.com/favicon.ico')+ expect(requested).toContain('https://openai.com/favicon.ico')+ expect(requested).not.toContain('https://icons.duckduckgo.com/ip3/openai.com.ico')+ })++ it('uses a cached favicon lookup when the root site refuses direct requests', async () => {+ const requested: string[] = []+ const resolver = new SenderAvatarResolver(async (url) => {+ requested.push(url)+ return url === 'https://icons.duckduckgo.com/ip3/openai.com.ico' ? image('icon') : missing+ })+ expect(await resolver.get('[email protected]')).toBe(+ `data:image/png;base64,${pixels.toString('base64')}`,+ )+ expect(requested).toContain('https://openai.com/favicon.ico')+ expect(requested).toContain('https://twenty-icons.com/openai.com')+ expect(requested.at(-1)).toBe('https://icons.duckduckgo.com/ip3/openai.com.ico')+ })++ it('uses Twenty Icons before DuckDuckGo and shares the result across senders', async () => {+ const requested: string[] = []+ const fetch = vi.fn(async (url: string) => {+ requested.push(url)+ return url === 'https://twenty-icons.com/company.com' ? image('icon') : missing+ })+ const resolver = new SenderAvatarResolver(fetch)+ const results = await Promise.all([+ resolver.get('[email protected]'),+ resolver.get('[email protected]'),+ ])++ expect(results).toEqual([+ `data:image/png;base64,${pixels.toString('base64')}`,+ `data:image/png;base64,${pixels.toString('base64')}`,+ ])+ expect(requested.filter((url) => url === 'https://twenty-icons.com/company.com')).toHaveLength(+ 1,+ )+ expect(requested).not.toContain('https://twenty-icons.com/mail.company.com')+ expect(requested).not.toContain('https://icons.duckduckgo.com/ip3/company.com.ico')+ })++ it('rejects redirects that downgrade to HTTP', async () => {+ const requested: string[] = []+ const resolver = new SenderAvatarResolver(async (url) => {+ requested.push(url)+ if (url === 'https://brand.com/apple-touch-icon.png')+ return { ...missing, status: 301, location: 'http://brand.com/icon.png' }+ return missing+ })+ await resolver.get('[email protected]')+ expect(requested).not.toContain('http://brand.com/icon.png')+ })++ it('finds a Snocks-style icon in the prefix of a large homepage', async () => {+ const page = Buffer.from(+ `<head><link rel="icon" href="/cdn/shop/files/brand.png?width=128"></head>${'x'.repeat(600_000)}`,+ )+ const fetch = vi.fn(+ async (url: string, options?: { maxBytes?: number; allowPartial?: boolean }) => {+ if (url === 'https://snocks.com/') {+ if (!options?.allowPartial) throw new Error('Resource is too large.')+ return { status: 200, type: 'text/html', bytes: page.subarray(0, options.maxBytes) }+ }+ if (url === 'https://snocks.com/cdn/shop/files/brand.png?width=128') return image('brand')+ return missing+ },+ )+ const resolver = new SenderAvatarResolver(fetch)+ expect(await resolver.get('[email protected]')).toBe(+ `data:image/png;base64,${pixels.toString('base64')}`,+ )+ expect(fetch).toHaveBeenCalledWith('https://snocks.com/', {+ maxBytes: 512_000,+ timeoutMs: 5000,+ allowPartial: true,+ userAgent: 'Mozilla/5.0',+ })+ })++ it('follows DPD-style four redirects to an advertised favicon', async () => {+ const redirects = new Map([+ ['https://dpd.at/', 'https://www.dpd.com/at'],+ ['https://www.dpd.com/at', 'https://www.dpd.com/at/'],+ ['https://www.dpd.com/at/', 'https://www.dpd.com/at/de'],+ ['https://www.dpd.com/at/de', 'https://www.dpd.com/at/de/'],+ ])+ const fetch = vi.fn(async (url: string) => {+ const location = redirects.get(url)+ if (location) return { ...missing, status: 301, location }+ if (url === 'https://www.dpd.com/at/de/')+ return {+ status: 200,+ type: 'text/html',+ bytes: Buffer.from('<link rel="icon" href="/wp-content/favicon.png">'),+ }+ if (url === 'https://www.dpd.com/wp-content/favicon.png') return image('dpd')+ return missing+ })+ expect(await new SenderAvatarResolver(fetch).get('[email protected]')).toBe(+ `data:image/png;base64,${pixels.toString('base64')}`,+ )+ })++ it('accepts a Trade Republic-style favicon larger than 128 KB', async () => {+ const favicon = Buffer.concat([Buffer.from('00000100', 'hex'), Buffer.alloc(285_474)])+ const fetch = vi.fn(async (url: string, options?: { maxBytes?: number }) => {+ if (url === 'https://traderepublic.com/favicon.ico') {+ if ((options?.maxBytes ?? 0) < favicon.length) throw new Error('Resource is too large.')+ return { status: 200, type: 'image/vnd.microsoft.icon', bytes: favicon }+ }+ return missing+ })+ const result = await new SenderAvatarResolver(fetch).get('[email protected]')+ expect(result).toBe(`data:image/x-icon;base64,${favicon.toString('base64')}`)+ })+})diff --git a/tests/service-imap.test.ts b/tests/service-imap.test.tsnew file mode 100644index 0000000..c1e2cd6--- /dev/null+++ b/tests/service-imap.test.ts@@ -0,0 +1,418 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+vi.mock('electron', () => ({+ app: { getVersion: () => 'test' },+ safeStorage: {+ isEncryptionAvailable: () => false,+ getSelectedStorageBackend: () => 'basic_text',+ },+ dialog: {},+ shell: {},+ Notification: { isSupported: () => false },+}))+import { MailService, type ProviderFactory } from '../apps/desktop/src/main/service'+import { JsonStore } from '../apps/desktop/src/main/storage'+import { openInProcessIndex } from '../apps/desktop/src/main/imap-index/sqlite-index'+import { ImapProvider } from '../packages/imap/src'+import { JmapProvider } from '../packages/jmap/src'+import {+ ProviderError,+ type ConnectInput,+ type Draft,+ type SubmissionOutcome,+} from '../packages/core/src'+import { FakeImapServer } from './support/fake-imap'++const input: ConnectInput = {+ config: {+ protocol: 'imap',+ email: '[email protected]',+ incoming: { host: 'imap.example.com', port: 993, security: 'tls', username: 'me' },+ outgoing: { host: 'smtp.example.com', port: 587, security: 'starttls', username: 'me' },+ outgoingSameCredentials: true,+ },+ password: 'disposable',+ name: 'Work',+ remember: true,+ connectionId: 'imap-connection',+}+const draftId = 'fb4c0a00-254f-4fb1-965e-96d56ca9ef17'+const accountId = JSON.stringify(['imap-connection', 'imap'])+const draft: Draft = {+ id: draftId,+ accountId,+ identityId: 'default',+ to: [{ name: 'Alex', email: '[email protected]' }],+ cc: [{ name: 'Sam', email: '[email protected]' }],+ bcc: [],+ subject: 'Plans',+ html: '<p>Hello</p>',+ text: 'Hello',+ attachments: [],+ updatedAt: '2026-09-23T10:00:00.000Z',+ status: 'local',+}+let directory: string+let server: FakeImapServer+let service: MailService+let store: JsonStore+let submit: ReturnType<typeof vi.fn<(...args: any[]) => Promise<SubmissionOutcome>>>+let verify: ReturnType<typeof vi.fn<(...args: any[]) => Promise<void>>>+const factory: ProviderFactory = (options) =>+ new ImapProvider({+ connectionId: options.connectionId,+ name: options.name,+ config: options.config as typeof input.config & { protocol: 'imap' },+ password: options.secrets.password,+ outgoingPassword: options.secrets.outgoingPassword,+ folders: options.folders,+ index: openInProcessIndex(+ options.temporary ? ':memory:' : join(directory, options.connectionId + '.sqlite'),+ ),+ readAttachment: options.readAttachment,+ background: false,+ ports: server.port,+ smtp: { submit, verify },+ timing: { sentCopyGraceMs: 0, previews: 0 },+ })+async function start() {+ store = new JsonStore(directory)+ service = new MailService(store, () => {}, { providers: factory })+ await service.init()+}+beforeEach(async () => {+ directory = await mkdtemp(join(tmpdir(), 'inlark-service-imap-'))+ server = new FakeImapServer()+ submit = vi.fn(async () => ({ accepted: ['[email protected]', '[email protected]'], rejected: [] }))+ verify = vi.fn(async () => {})+ await start()+})+afterEach(async () => {+ service.dispose()+ vi.restoreAllMocks()+ await new Promise((r) => setTimeout(r, 20))+ await rm(directory, { recursive: true, force: true })+})+const journal = async () =>+ (await store.read<any[]>('submissions', [])).find((j) => j.draftId === draftId)+const restart = async () => {+ service.dispose()+ await start()+ await vi.waitFor(() => expect(service.accounts[0]?.status).toBe('connected'))+}++describe('IMAP account setup', () => {+ it('checks incoming and outgoing servers separately and saves nothing', async () => {+ verify.mockRejectedValueOnce(+ new ProviderError('outgoingAuthentication', 'The outgoing server rejected this login.'),+ )+ const test = await service.testConnection({ ...input, connectionId: undefined })+ expect(test.incoming).toEqual({ ok: true })+ expect(test.outgoing).toEqual({ ok: false, error: 'The outgoing server rejected this login.' })+ expect(test.folders?.mappings.sent).toEqual({ path: 'Sent', source: 'server' })+ expect(submit).not.toHaveBeenCalled()+ await expect(stat(join(directory, 'connections.json'))).rejects.toThrow()+ })+ it('requires both servers before completing setup', async () => {+ verify.mockRejectedValueOnce(+ new ProviderError('outgoingNetwork', 'The outgoing server could not be reached.'),+ )+ await expect(service.connect(input)).rejects.toThrow('outgoing server')+ expect(service.accounts).toEqual([])+ await service.connect(input)+ expect(service.accounts[0]).toMatchObject({+ protocol: 'imap',+ email: '[email protected]',+ status: 'connected',+ })+ })+ it('never exposes passwords in connection settings and keeps separate outgoing secrets', async () => {+ await service.connect({+ ...input,+ config: { ...input.config, outgoingSameCredentials: false } as ConnectInput['config'],+ outgoingPassword: 'outgoing-secret',+ })+ const settings = await service.connectionSettings('imap-connection')+ expect(JSON.stringify(settings)).not.toMatch(/disposable|outgoing-secret/)+ expect(settings).toMatchObject({ remember: true, config: { protocol: 'imap' } })+ const saved = JSON.parse(await readFile(join(directory, 'connections.json'), 'utf8')).data[0]+ expect(saved).toMatchObject({+ localSecret: 'disposable',+ outgoingLocalSecret: 'outgoing-secret',+ })+ await restart()+ await service.send(draft)+ expect(submit.mock.calls[0][0]).toMatchObject({ password: 'outgoing-secret' })+ })+ it('creates missing folders chosen during setup and remembers the choice', async () => {+ server.boxes.delete('Archive')+ await service.connect({ ...input, folders: { archive: { path: 'Archive', create: true } } })+ expect(server.boxes.has('Archive')).toBe(true)+ expect((await service.connectionSettings('imap-connection')).folders).toEqual({+ archive: { path: 'Archive' },+ })+ const review = await service.setFolderMappings(accountId, { archive: { path: 'INBOX' } })+ expect(review.mappings.archive).toEqual({ path: 'INBOX', source: 'user' })+ })+})++describe('legacy connection migration', () => {+ it('upgrades version 1 records to JMAP connections atomically and keeps a backup', async () => {+ service.dispose()+ const legacy = [+ {+ id: 'old',+ serverUrl: 'https://mail.example',+ username: 'me',+ name: 'Home',+ localSecret: 'legacy-secret',+ accounts: [+ {+ id: '["old","a"]',+ connectionId: 'old',+ remoteId: 'a',+ name: 'Home',+ email: '[email protected]',+ color: '#a69aef',+ status: 'connected',+ },+ ],+ },+ ]+ await writeFile(+ join(directory, 'connections.json'),+ JSON.stringify({ version: 1, data: legacy }),+ )+ const connect = vi+ .spyOn(JmapProvider.prototype, 'connect')+ .mockRejectedValue(new ProviderError('network', 'Offline'))+ await start()+ const saved = JSON.parse(await readFile(join(directory, 'connections.json'), 'utf8'))+ expect(saved.version).toBe(2)+ expect(saved.data[0]).toMatchObject({+ id: 'old',+ localSecret: 'legacy-secret',+ config: { protocol: 'jmap', serverUrl: 'https://mail.example', username: 'me' },+ accounts: [{ id: '["old","a"]', protocol: 'jmap' }],+ })+ expect(+ JSON.parse(await readFile(join(directory, 'connections.v1.backup.json'), 'utf8')).data,+ ).toEqual(legacy)+ expect(service.accounts.map((a) => a.id)).toEqual(['["old","a"]'])+ await vi.waitFor(() => expect(connect).toHaveBeenCalled())+ })+ it('refuses a malformed legacy file and leaves it untouched', async () => {+ service.dispose()+ const original = JSON.stringify({ version: 1, data: [{ id: 'broken' }] })+ await writeFile(join(directory, 'connections.json'), original)+ await expect(start()).rejects.toThrow('preserved')+ expect(await readFile(join(directory, 'connections.json'), 'utf8')).toBe(original)+ })+ it('refuses data from a newer version without modifying it', async () => {+ service.dispose()+ const original = JSON.stringify({ version: 3, data: [] })+ await writeFile(join(directory, 'connections.json'), original)+ await expect(start()).rejects.toThrow('unsupported')+ expect(await readFile(join(directory, 'connections.json'), 'utf8')).toBe(original)+ })+})++describe('IMAP sending', () => {+ beforeEach(() => service.connect(input))++ it('persists MIME, envelope and journal before submitting, then files the Sent copy', async () => {+ submit.mockImplementationOnce(async (_settings, envelope) => {+ expect((await journal()).state).toBe('submitting')+ expect((await journal()).envelope).toEqual(envelope)+ expect(await readFile(join(directory, 'outgoing', draftId + '.eml'), 'utf8')).toContain(+ 'Subject: Plans',+ )+ return { accepted: envelope.to, rejected: [] }+ })+ const result = await service.send(draft)+ expect(result).toMatchObject({ status: 'sent', sentCopy: 'filed' })+ expect(server.box('Sent').messages).toHaveLength(1)+ expect((await journal()).sentCopy).toBe('filed')+ await expect(stat(join(directory, 'outgoing', draftId + '.eml'))).rejects.toThrow()+ expect(await service.submissions()).toEqual([])+ })+ it('records acceptance before filing, and a filing failure only retries filing', async () => {+ server.hooks.set('APPEND:before', () => {+ throw new ProviderError('command', 'Over quota')+ })+ const result = await service.send(draft)+ expect(result).toMatchObject({ status: 'sent', sentCopy: 'pending' })+ expect(result.message).toContain('Sent copy pending')+ expect((await journal()).state).toBe('sent')+ expect(await service.submissions()).toMatchObject([+ { draftId, state: 'sent', sentCopy: 'failed' },+ ])+ expect((await service.retrySentCopy(draftId)).sentCopy).toBe('filed')+ expect(submit).toHaveBeenCalledTimes(1)+ expect(server.box('Sent').messages).toHaveLength(1)+ })+ it('reconciles an ambiguous Sent append instead of appending twice', async () => {+ server.hooks.set('APPEND:after', () => {+ server.commandPorts.at(-1)!.drop()+ throw new ProviderError('network', 'Connection lost.')+ })+ await service.send(draft)+ expect((await journal()).sentCopy).toBe('uncertain')+ await service.retrySentCopy(draftId)+ expect((await journal()).sentCopy).toBe('server')+ expect(server.box('Sent').messages).toHaveLength(1)+ expect(submit).toHaveBeenCalledTimes(1)+ })+ it('reports partial acceptance and recovers a draft addressed only to refused recipients', async () => {+ submit.mockResolvedValueOnce({+ accepted: ['[email protected]'],+ rejected: [{ email: '[email protected]', reason: '550 No such user' }],+ })+ const result = await service.send(draft)+ expect(result.status).toBe('partial')+ expect(result.rejected).toEqual([{ name: 'Sam', email: '[email protected]' }])+ expect(await service.submissions()).toMatchObject([+ { state: 'partial', rejected: [{ email: '[email protected]' }] },+ ])+ // A partial send is never resent automatically.+ expect((await service.send(draft)).status).toBe('partial')+ const recovery = await service.recoverRejected(draftId)+ expect(recovery).toMatchObject({+ to: [],+ cc: [{ email: '[email protected]' }],+ subject: 'Plans',+ text: 'Hello',+ status: 'local',+ })+ expect(recovery.id).not.toBe(draftId)+ expect(await service.submissions()).toEqual([])+ expect(submit).toHaveBeenCalledTimes(1)+ })+ it('never retries a submission whose final response was lost, even after restart', async () => {+ submit.mockRejectedValueOnce(new ProviderError('submissionUncertain', 'No final reply.'))+ expect((await service.send(draft)).status).toBe('uncertain')+ expect((await service.send(draft)).status).toBe('uncertain')+ expect((await service.reconcile(draftId)).status).toBe('uncertain')+ await restart()+ expect((await service.send(draft)).status).toBe('uncertain')+ expect(submit).toHaveBeenCalledTimes(1)+ // A Sent copy alone is not proof of submission.+ server.deliver('Sent', { messageId: (await journal()).messageId, subject: 'Plans' })+ expect((await service.reconcile(draftId)).status).toBe('uncertain')+ const replacement = await service.replaceUncertain(draftId)+ expect(replacement).toMatchObject({ subject: 'Plans', status: 'local' })+ expect(replacement.id).not.toBe(draftId)+ expect((await service.drafts()).find((d) => d.id === draftId)?.status).toBe('uncertain')+ expect(submit).toHaveBeenCalledTimes(1)+ })+ it('treats a crash while the journal says submitting as unconfirmed, never as unsent', async () => {+ const write = store.write.bind(store)+ let crash = false+ vi.spyOn(store, 'write').mockImplementation((name, data, version) => {+ if (crash && name === 'submissions') return Promise.reject(new Error('Power lost'))+ return write(name, data, version)+ })+ submit.mockImplementationOnce(async (_s, envelope) => {+ crash = true+ return { accepted: envelope.to, rejected: [] }+ })+ expect((await service.send(draft)).message).toContain('reconciled after restart')+ crash = false+ await restart()+ expect((await journal()).state).toBe('uncertain')+ expect((await service.send(draft)).status).toBe('uncertain')+ expect(submit).toHaveBeenCalledTimes(1)+ })+ it('does not submit when the journal cannot be written first', async () => {+ const write = store.write.bind(store)+ vi.spyOn(store, 'write').mockImplementation((name, data, version) => {+ if (name === 'submissions' && (data as any[]).some((j) => j.state === 'submitting'))+ return Promise.reject(new Error('Disk full'))+ return write(name, data, version)+ })+ await expect(service.send(draft)).rejects.toThrow('Disk full')+ expect(submit).not.toHaveBeenCalled()+ expect((await service.drafts())[0]).toMatchObject({ text: 'Hello' })+ })+ it('restores a draft interrupted before submission began without claiming it was sent', async () => {+ await service.saveDraft(draft)+ await store.write('submissions', [+ { draftId, accountId, state: 'preparing', at: draft.updatedAt },+ ])+ await restart()+ expect(await journal()).toBeUndefined()+ // The draft is editable again (and may already be saved to the server), never marked sent.+ expect(['local', 'synced']).toContain((await service.drafts())[0].status)+ expect((await service.drafts())[0].text).toBe('Hello')+ expect(submit).not.toHaveBeenCalled()+ })+ it('distinguishes an outgoing login failure from incoming problems', async () => {+ submit.mockRejectedValueOnce(+ new ProviderError('outgoingAuthentication', 'The outgoing server rejected your login.'),+ )+ await expect(service.send(draft)).rejects.toThrow('outgoing server')+ expect(service.accounts[0]).toMatchObject({+ status: 'connected',+ outgoingError: 'The outgoing server rejected your login.',+ })+ expect((await service.drafts())[0]).toMatchObject({+ status: 'error',+ errorKind: 'outgoingAuthentication',+ })+ expect((await journal()).state).toBe('rejected')+ expect((await service.send(draft)).status).toBe('sent')+ expect(service.accounts[0].outgoingError).toBeUndefined()+ })+})++describe('IMAP drafts', () => {+ beforeEach(() => service.connect(input))++ it('replaces the server draft only after the new copy is confirmed', async () => {+ const first = await service.syncDraft(draft)+ expect(first.status).toBe('synced')+ const second = await service.syncDraft({+ ...first,+ text: 'Hello again',+ updatedAt: '2026-09-23T10:01:00.000Z',+ })+ expect(second.status).toBe('synced')+ expect(second.serverId).not.toBe(first.serverId)+ expect(server.box('Drafts').messages.map((m) => m.input.text?.trim())).toEqual(['Hello again'])+ })+ it('keeps both copies when another client changed the server draft', async () => {+ const first = await service.syncDraft(draft)+ // Another client saves its own edit: it appends a new draft and removes the old one.+ server.remove('Drafts', server.box('Drafts').messages[0].uid)+ server.deliver('Drafts', {+ messageId: 'theirs@x',+ subject: 'Plans',+ text: 'Their edit',+ flags: ['\\Draft'],+ })+ const second = await service.syncDraft({+ ...first,+ text: 'Mine',+ updatedAt: '2026-09-23T10:01:00.000Z',+ })+ expect(second).toMatchObject({ status: 'error', errorKind: 'conflict', text: 'Mine' })+ expect(server.box('Drafts').messages.map((m) => m.input.text)).toEqual(['Their edit'])+ })+ it('keeps the previous server draft when the replacement cannot be confirmed', async () => {+ const first = await service.syncDraft(draft)+ server.hooks.set('APPEND:before', () => {+ throw new ProviderError('command', 'Over quota')+ })+ const failed = await service.syncDraft({+ ...first,+ text: 'Newer',+ updatedAt: '2026-09-23T10:01:00.000Z',+ })+ expect(failed.status).toBe('error')+ expect(failed.text).toBe('Newer')+ expect(server.box('Drafts').messages).toHaveLength(1)+ expect(server.box('Drafts').messages[0].input.text?.trim()).toBe('Hello')+ })+})diff --git a/tests/service.test.ts b/tests/service.test.tsnew file mode 100644index 0000000..e90b7dc--- /dev/null+++ b/tests/service.test.ts@@ -0,0 +1,436 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { mkdtemp, readFile, stat, rm } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { safeStorage } from 'electron'+vi.mock('electron', () => ({+ app: { getVersion: () => 'test' },+ safeStorage: {+ isEncryptionAvailable: () => false,+ getSelectedStorageBackend: () => 'basic_text',+ encryptString: (value: string) => Buffer.from('encrypted:' + value),+ decryptString: (value: Buffer) => value.toString().replace(/^encrypted:/, ''),+ },+ dialog: {},+ shell: {},+ Notification: { isSupported: () => false },+}))+import { MailService } from '../apps/desktop/src/main/service'+import { JsonStore, encryptSecret } from '../apps/desktop/src/main/storage'+import { JmapProvider, JmapError, draftFingerprint } from '../packages/jmap/src'+import { type Account, type Draft, type Mailbox, type Message } from '../packages/core/src'+import { publicAddress, publicFetch } from '../apps/desktop/src/main/public-fetch'+const account: Account = {+ id: 'account',+ connectionId: 'connection',+ remoteId: 'remote',+ name: 'Test',+ email: '[email protected]',+ color: '#aaa',+ status: 'connected',+}+const draft: Draft = {+ id: 'fb4c0a00-254f-4fb1-965e-96d56ca9ef17',+ accountId: account.id,+ identityId: 'identity',+ to: [{ name: 'Recipient', email: '[email protected]' }],+ cc: [],+ bcc: [],+ subject: 'Test',+ html: '<p>Hello</p>',+ text: 'Hello',+ attachments: [],+ updatedAt: '2026-09-23T10:00:00.000Z',+ status: 'local',+}+const mail: Message = {+ id: 'message',+ threadId: 'thread',+ accountId: account.id,+ subject: 'Test',+ from: [],+ to: [],+ cc: [],+ bcc: [],+ replyTo: [],+ receivedAt: '2026-09-23T10:00:00Z',+ preview: '',+ keywords: { $seen: true },+ mailboxIds: { inbox: true, custom: true },+ size: 1,+ hasAttachment: false,+}+const boxes = ['inbox', 'archive', 'drafts', 'sent', 'trash', 'custom'].map((id) => ({+ id,+ accountId: account.id,+ name: id,+ role: id === 'custom' ? null : id,+ parentId: null,+ totalEmails: 1,+ unreadEmails: 0,+ rights: {+ mayReadItems: true,+ mayAddItems: true,+ mayRemoveItems: true,+ maySetSeen: true,+ maySetKeywords: true,+ mayCreateChild: true,+ mayRename: true,+ mayDelete: true,+ },+})) satisfies Mailbox[]+let directory: string, service: MailService, store: JsonStore+beforeEach(async () => {+ directory = await mkdtemp(join(tmpdir(), 'inlark-test-'))+ store = new JsonStore(directory)+ service = new MailService(store, () => {})+ await service.init()+ vi.spyOn(JmapProvider.prototype, 'connect').mockResolvedValue([account])+ vi.spyOn(JmapProvider.prototype, 'identities').mockResolvedValue([+ { id: 'identity', accountId: account.id, name: 'Me', email: account.email },+ ])+ vi.spyOn(JmapProvider.prototype, 'subscribe').mockReturnValue(() => {})+ vi.spyOn(JmapProvider.prototype, 'mailboxes').mockResolvedValue(boxes)+ vi.spyOn(JmapProvider.prototype, 'query').mockResolvedValue({ items: [], total: 0 })+ vi.spyOn(JmapProvider.prototype, 'conversationMetadata').mockResolvedValue([mail])+ vi.spyOn(JmapProvider.prototype, 'messages').mockResolvedValue([mail])+ vi.spyOn(JmapProvider.prototype, 'createDraft').mockResolvedValue('created')+ vi.spyOn(JmapProvider.prototype, 'update').mockImplementation(async (_a, updates) => ({+ updated: Object.keys(updates),+ failures: [],+ }))+ await service.connect({+ config: { protocol: 'jmap', serverUrl: 'https://mail.example', username: 'test' },+ password: 'disposable',+ name: 'Test',+ remember: false,+ connectionId: 'connection',+ })+})+afterEach(async () => {+ service.dispose()+ vi.restoreAllMocks()+ await rm(directory, { recursive: true, force: true })+})+describe('durable mail operations', () => {+ it('archives without removing unrelated folder memberships', async () => {+ const result = await service.mutate({+ targets: [{ accountId: account.id, threadId: 'thread' }],+ action: 'archive',+ })+ const update = vi.mocked(JmapProvider.prototype.update).mock.calls.at(-1)![1]+ expect(update.message).toEqual({ mailboxes: { inbox: false, archive: true } })+ expect(result.undoId).toBeTruthy()+ })+ it('serializes overlapping changes to one account so neither sees stale state', async () => {+ let state = 's0'+ vi.spyOn(JmapProvider.prototype, 'getStateToken').mockImplementation(() => state)+ vi.mocked(JmapProvider.prototype.update).mockImplementation(+ async (_account, updates, _destroy, expected) => {+ await new Promise((resolve) => setTimeout(resolve, 10))+ if (expected !== state) return { updated: [], failures: ['stateMismatch'] }+ state = 's' + (Number(state.slice(1)) + 1)+ return { updated: Object.keys(updates), failures: [] }+ },+ )+ const target = [{ accountId: account.id, threadId: 'thread' }]+ // Archiving in the reader opens the next conversation, which is marked read at once.+ const [archive, read] = await Promise.all([+ service.mutate({ targets: target, action: 'archive' }),+ service.mutate({ targets: target, action: 'unread' }),+ ])+ expect(archive.failures).toEqual([])+ expect(read.failures).toEqual([])+ expect(state).toBe('s2')+ })+ it('preserves drafts across service restart with private permissions', async () => {+ await service.saveDraft(draft)+ expect((await stat(join(directory, 'drafts.json'))).mode & 0o777).toBe(0o600)+ service.dispose()+ service = new MailService(new JsonStore(directory), () => {})+ await service.init()+ expect((await service.drafts())[0].text).toBe('Hello')+ })+ it('reconnects after restart with an explicitly remembered local password', async () => {+ await service.connect({+ config: { protocol: 'jmap', serverUrl: 'https://mail.example', username: 'test' },+ password: 'disposable',+ name: 'Test',+ remember: true,+ connectionId: 'connection',+ })+ const path = join(directory, 'connections.json')+ expect((await stat(directory)).mode & 0o777).toBe(0o700)+ expect((await stat(path)).mode & 0o777).toBe(0o600)+ expect(JSON.parse(await readFile(path, 'utf8'))).toMatchObject({+ version: 2,+ data: [+ {+ localSecret: 'disposable',+ config: { protocol: 'jmap', serverUrl: 'https://mail.example' },+ },+ ],+ })+ service.dispose()+ service = new MailService(new JsonStore(directory), () => {})+ await service.init()+ await vi.waitFor(() => expect(service.accounts[0].status).toBe('connected'))+ expect(service.accounts[0].sessionOnly).toBe(false)+ })+ it('keeps the chosen avatar across reconnects and restarts', async () => {+ await service.connect({+ config: { protocol: 'jmap', serverUrl: 'https://mail.example', username: 'test' },+ password: 'disposable',+ name: 'Test',+ remember: true,+ connectionId: 'connection',+ })+ const appearance = { seed: 'a1b2c3d4', image: 'data:image/png;base64,iVBORw0KGgo=' }+ await service.updateAccount(account.id, appearance)+ await service.reconnect('connection')+ expect(service.accounts[0]).toMatchObject(appearance)+ service.dispose()+ service = new MailService(new JsonStore(directory), () => {})+ await service.init()+ await vi.waitFor(() => expect(service.accounts[0].status).toBe('connected'))+ expect(service.accounts[0]).toMatchObject(appearance)+ })+ it('refuses a picture whose contents do not match its type', async () => {+ const html = 'data:image/png;base64,' + Buffer.from('<svg onload=alert(1)>').toString('base64')+ await expect(service.updateAccount(account.id, { image: html })).rejects.toThrow(+ 'could not be read',+ )+ expect(service.accounts[0].image).toBeUndefined()+ })+ it('does not save the password for session-only login', async () => {+ const connection = JSON.parse(await readFile(join(directory, 'connections.json'), 'utf8'))+ .data[0]+ expect(connection.secret).toBeUndefined()+ expect(connection.localSecret).toBeUndefined()+ })+ it('moves a local password to secure storage when a keyring becomes available', async () => {+ const input = {+ config: { protocol: 'jmap', serverUrl: 'https://mail.example', username: 'test' },+ password: 'disposable',+ name: 'Test',+ remember: true,+ connectionId: 'connection',+ }+ await service.connect(input)+ vi.spyOn(safeStorage, 'isEncryptionAvailable').mockReturnValue(true)+ vi.spyOn(safeStorage, 'getSelectedStorageBackend').mockReturnValue('gnome_libsecret')+ await service.reconnect('connection')+ const connection = JSON.parse(await readFile(join(directory, 'connections.json'), 'utf8'))+ .data[0]+ expect(connection.localSecret).toBeUndefined()+ expect(connection.secret).toBe(Buffer.from('encrypted:disposable').toString('base64'))+ })+ it('never resubmits an ambiguous send, including after restart', async () => {+ const submit = vi+ .spyOn(JmapProvider.prototype, 'submit')+ .mockRejectedValue(new JmapError('network', 'Response lost'))+ vi.spyOn(JmapProvider.prototype, 'submissionExists').mockResolvedValue(false)+ expect((await service.send(draft)).status).toBe('uncertain')+ expect((await service.send(draft)).status).toBe('uncertain')+ expect(submit).toHaveBeenCalledTimes(1)+ const persisted = await store.read<any[]>('submissions', [])+ expect(persisted[0].state).toBe('uncertain')+ await service.saveDraft({ ...draft, text: 'Newer UI autosave' })+ expect((await service.drafts())[0].status).toBe('uncertain')+ })+ it('reconciles a lost send response using server submission records', async () => {+ vi.spyOn(JmapProvider.prototype, 'submit').mockRejectedValue(+ new JmapError('network', 'Response lost'),+ )+ vi.spyOn(JmapProvider.prototype, 'submissionExists').mockResolvedValue(true)+ await service.send(draft)+ expect((await service.reconcile(draft.id)).status).toBe('sent')+ expect((await service.drafts())[0].status).toBe('sent')+ })+ it('retains the draft after an explicit server rejection and allows a deliberate retry', async () => {+ const submit = vi+ .spyOn(JmapProvider.prototype, 'submit')+ .mockRejectedValueOnce(new JmapError('submissionRejected', 'Recipient rejected'))+ .mockResolvedValue({ accepted: ['[email protected]'], rejected: [] })+ await expect(service.send(draft)).rejects.toThrow('Recipient rejected')+ expect((await service.drafts())[0].text).toBe('Hello')+ expect((await service.send(draft)).status).toBe('sent')+ expect(submit).toHaveBeenCalledTimes(2)+ })+ it('keeps the local copy when another client edits the server draft', async () => {+ const saved = await service.syncDraft({+ ...draft,+ serverId: 'original',+ serverFingerprint: 'different',+ })+ expect(saved.status).toBe('error')+ expect(saved.text).toBe('Hello')+ expect(JmapProvider.prototype.createDraft).not.toHaveBeenCalled()+ })++ it('does not undo over a subsequent change from another client', async () => {+ const result = await service.mutate({+ targets: [{ accountId: account.id, threadId: 'thread' }],+ action: 'archive',+ })+ vi.mocked(JmapProvider.prototype.messages).mockResolvedValue([+ { ...mail, mailboxIds: { custom: true, trash: true } },+ ])+ vi.mocked(JmapProvider.prototype.update).mockClear()+ const undone = await service.undo(result.undoId!)+ expect(undone.changed).toBe(0)+ expect(undone.failures.join()).toContain('changed since')+ expect(vi.mocked(JmapProvider.prototype.update).mock.calls[0][1]).toEqual({})+ })+ it('recovers a crash during submission and preserves the immutable attempted content', async () => {+ await service.saveDraft({ ...draft, status: 'sending' })+ await store.write('submissions', [+ {+ draftId: draft.id,+ accountId: account.id,+ emailId: 'created',+ state: 'submitting',+ at: draft.updatedAt,+ },+ ])+ service.dispose()+ service = new MailService(new JsonStore(directory), () => {})+ await service.init()+ expect((await service.drafts())[0].status).toBe('uncertain')+ await service.saveDraft({+ ...draft,+ text: 'stale renderer write',+ updatedAt: new Date().toISOString(),+ })+ expect((await service.drafts())[0].text).toBe('Hello')+ })+ it('does not send or delete a server draft changed by another client', async () => {+ const submit = vi+ .spyOn(JmapProvider.prototype, 'submit')+ .mockResolvedValue({ accepted: ['[email protected]'], rejected: [] })+ await expect(+ service.send({ ...draft, serverId: 'original', serverFingerprint: 'different' }),+ ).rejects.toThrow('another client')+ expect(submit).not.toHaveBeenCalled()+ expect(JmapProvider.prototype.update).not.toHaveBeenCalled()+ expect((await service.drafts())[0].text).toBe('Hello')+ })+ it('returns successful accounts and explicitly identifies an unavailable account', async () => {+ const second = { ...account, id: 'second', connectionId: 'other', remoteId: 'other' }+ vi.mocked(JmapProvider.prototype.connect).mockResolvedValue([second])+ await service.connect({+ config: { protocol: 'jmap', serverUrl: 'https://mail.example', username: 'second' },+ password: 'disposable',+ name: 'Second',+ remember: false,+ connectionId: 'other',+ })+ vi.mocked(JmapProvider.prototype.query).mockImplementation(async (a) => {+ if (a.id === account.id) throw new JmapError('network', 'Offline')+ return { items: [], total: 12 }+ })+ const result = await service.query({ view: 'inbox' })+ expect(result.total).toBe(12)+ expect(result.failedAccounts).toEqual([account.id])+ })+ it('synchronizes a closed offline draft on the next connected refresh', async () => {+ await service.saveDraft(draft)+ await service.refresh()+ expect((await service.drafts())[0].status).toBe('synced')+ expect(JmapProvider.prototype.createDraft).toHaveBeenCalledTimes(1)+ })+ it('recovers a completed submission when its final local draft write failed', async () => {+ const submit = vi+ .spyOn(JmapProvider.prototype, 'submit')+ .mockResolvedValue({ accepted: ['[email protected]'], rejected: [] })+ const write = store.write.bind(store)+ const failingWrite = vi.spyOn(store, 'write').mockImplementation((name, data) => {+ if (name === 'drafts' && (data as Draft[]).some((d) => d.status === 'sent'))+ return Promise.reject(new Error('Disk full'))+ return write(name, data)+ })+ expect((await service.send(draft)).status).toBe('sent')+ failingWrite.mockRestore()+ service.dispose()+ service = new MailService(new JsonStore(directory), () => {})+ await service.init()+ expect((await service.drafts())[0]).toMatchObject({+ status: 'sent',+ text: '',+ html: '',+ attachments: [],+ })+ expect((await service.reconcile(draft.id)).status).toBe('sent')+ expect(submit).toHaveBeenCalledTimes(1)+ })+ it('preserves a message sent by another client when discarding the stale local draft', async () => {+ const remote = { ...mail, keywords: { $seen: true }, text: 'Hello' }+ vi.mocked(JmapProvider.prototype.messages).mockResolvedValue([remote])+ await service.saveDraft({+ ...draft,+ serverId: remote.id,+ serverFingerprint: draftFingerprint(remote),+ })+ await service.deleteDraft(draft.id)+ expect(JmapProvider.prototype.update).not.toHaveBeenCalled()+ expect(await service.drafts()).toEqual([])+ })+ it('deletes a server-only draft but never a message sent meanwhile', async () => {+ vi.mocked(JmapProvider.prototype.messages).mockResolvedValue([+ { ...mail, keywords: { $draft: true } },+ ])+ await service.deleteServerDraft(account.id, mail.id)+ expect(vi.mocked(JmapProvider.prototype.update).mock.calls.at(-1)!.slice(1, 3)).toEqual([+ {},+ [mail.id],+ ])+ vi.mocked(JmapProvider.prototype.update).mockClear()+ vi.mocked(JmapProvider.prototype.messages).mockResolvedValue([mail])+ await expect(service.deleteServerDraft(account.id, mail.id)).rejects.toThrow(+ 'no longer a draft',+ )+ expect(JmapProvider.prototype.update).not.toHaveBeenCalled()+ })+ it('does not recreate a draft deleted or sent in another client without a decision', async () => {+ for (const remote of [[], [{ ...mail, keywords: { $seen: true } }]]) {+ vi.mocked(JmapProvider.prototype.messages).mockResolvedValue(remote)+ const result = await service.syncDraft({+ ...draft,+ serverId: 'original',+ serverFingerprint: 'previous',+ })+ expect(result.status).toBe('error')+ expect(result.error).toContain('another client')+ expect(result.text).toBe('Hello')+ }+ expect(JmapProvider.prototype.createDraft).not.toHaveBeenCalled()+ })+ it('never silently stores weakly encrypted credentials', () => {+ expect(() => encryptSecret('secret')).toThrow('Secure credential storage is unavailable')+ })+ it('excludes mail contents and login details from diagnostics', async () => {+ await service.saveDraft(draft)+ const log = await service.diagnostics()+ expect(log).not.toContain('[email protected]')+ expect(log).not.toContain('disposable')+ expect(log).not.toContain('Hello')+ })+})+describe('untrusted message resource boundaries', () => {+ it('rejects local and reserved IP ranges, including mapped IPv6', async () => {+ for (const address of [+ '127.0.0.1',+ '10.0.0.1',+ '172.16.0.1',+ '192.168.1.1',+ '169.254.169.254',+ '::1',+ '::ffff:127.0.0.1',+ 'fc00::1',+ '2001:db8::1',+ ])+ expect(publicAddress(address)).toBe(false)+ expect(publicAddress('8.8.8.8')).toBe(true)+ await expect(publicFetch('http://127.0.0.1/image')).rejects.toThrow('Private network')+ })+})diff --git a/tests/smtp.test.ts b/tests/smtp.test.tsnew file mode 100644index 0000000..7ef0766--- /dev/null+++ b/tests/smtp.test.ts@@ -0,0 +1,312 @@+import { describe, it, expect, afterEach } from 'vitest'+import { readFileSync } from 'node:fs'+import { createServer, type AddressInfo, type Socket } from 'node:net'+import { SMTPServer, type SMTPServerOptions } from 'smtp-server'+import { composeMime } from '../packages/imap/src/mime'+import { smtpOptions, submitSmtp, verifySmtp, type SmtpSettings } from '../packages/imap/src/smtp'++const fixture = (name: string) => readFileSync(new URL(`./fixtures/tls/${name}`, import.meta.url))+const ca = fixture('ca.crt')+const trusted = { key: fixture('server.key'), cert: fixture('server.crt') }+const untrusted = { key: fixture('untrusted.key'), cert: fixture('untrusted.crt') }+const password = 'correct horse battery'++type Handlers = Pick<SMTPServerOptions, 'onRcptTo' | 'onData' | 'onMailFrom'>+const servers: (() => Promise<void>)[] = []+afterEach(async () => {+ await Promise.all(servers.splice(0).map((close) => close()))+})++async function start(options: Partial<SMTPServerOptions> = {}) {+ const log = {+ auth: [] as string[],+ names: [] as string[],+ mailFrom: [] as string[],+ rcptTo: [] as string[],+ data: [] as Buffer[],+ }+ const sockets = new Set<Socket>()+ const server = new SMTPServer({+ logger: false,+ disableReverseLookup: true,+ ...trusted,+ onAuth(auth, session, callback) {+ log.auth.push(auth.username ?? '')+ log.names.push(session.hostNameAppearsAs)+ if (auth.username === 'user' && auth.password === password) callback(null, { user: 'user' })+ else callback(new Error('Invalid username or password'))+ },+ onMailFrom(address, _session, callback) {+ log.mailFrom.push(address.address)+ callback()+ },+ onRcptTo(address, _session, callback) {+ log.rcptTo.push(address.address)+ if (address.address.startsWith('nobody@'))+ callback(Object.assign(new Error('No such user here'), { responseCode: 550 }))+ else callback()+ },+ onData(stream, _session, callback) {+ const chunks: Buffer[] = []+ stream.on('data', (chunk: Buffer) => chunks.push(chunk))+ stream.on('end', () => {+ log.data.push(Buffer.concat(chunks))+ callback(null, 'Queued as 1234')+ })+ },+ ...options,+ })+ // Clients that abort a TLS handshake surface as server errors; they are expected here.+ server.on('error', () => undefined)+ server.server.on('connection', (socket: Socket) => sockets.add(socket))+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))+ const port = (server.server.address() as AddressInfo).port+ servers.push(async () => {+ sockets.forEach((s) => s.destroy())+ await new Promise<void>((resolve) => server.close(() => resolve()))+ })+ return { port, log, sockets }+}++const settings = (port: number, overrides: Partial<SmtpSettings> = {}): SmtpSettings => ({+ host: '127.0.0.1',+ port,+ security: 'tls',+ username: 'user',+ password,+ timeoutMs: 3000,+ tls: { ca },+ ...overrides,+})+const message = (bcc: string[] = []) =>+ composeMime({+ from: { name: 'Me', email: '[email protected]' },+ to: [{ name: 'You', email: '[email protected]' }],+ cc: [],+ bcc: bcc.map((email) => ({ name: '', email })),+ subject: 'Hello',+ html: '<p>Hi</p>',+ text: 'Hi\n.a line starting with a dot\n',+ messageId: '[email protected]',+ attachments: [],+ })+const envelope = (to: string[] = ['[email protected]']) => ({ from: '[email protected]', to })+const failure = async (promise: Promise<unknown>) => {+ const error = await promise.then(+ () => undefined,+ (e: unknown) => e as { code: string; message: string },+ )+ expect(error, 'expected a failure').toBeDefined()+ expect(error!.message).not.toContain(password)+ return error!+}+const finalReply = (responseCode: number): Handlers['onData'] =>+ function (stream, _session, callback) {+ stream.on('data', () => undefined)+ stream.on('end', () => callback(Object.assign(new Error('Not now'), { responseCode })))+ }++describe('SMTP submission', () => {+ it('submits over implicit TLS, transmitting exactly the given bytes', async () => {+ const { port, log } = await start({ secure: true })+ const mime = await message()+ const outcome = await submitSmtp(settings(port), envelope(), mime)+ expect(outcome).toEqual({ accepted: ['[email protected]'], rejected: [] })+ expect(log.mailFrom).toEqual(['[email protected]'])+ expect(log.data).toHaveLength(1)+ expect(new Uint8Array(log.data[0])).toEqual(mime)+ expect(log.names).toEqual(['[127.0.0.1]'])+ })++ it('submits over STARTTLS', async () => {+ const { port, log } = await start()+ const outcome = await submitSmtp(+ settings(port, { security: 'starttls' }),+ envelope(),+ await message(),+ )+ expect(outcome.accepted).toEqual(['[email protected]'])+ expect(log.auth).toEqual(['user'])+ await verifySmtp(settings(port, { security: 'starttls', host: 'localhost' }))+ })++ it('never signs in when STARTTLS is required but not offered', async () => {+ const { port, log } = await start({ hideSTARTTLS: true })+ const error = await failure(verifySmtp(settings(port, { security: 'starttls' })))+ expect(error.code).toBe('outgoingNetwork')+ expect(error.message).toMatch(/STARTTLS/)+ expect(log.auth).toEqual([])+ await failure(submitSmtp(settings(port, { security: 'starttls' }), envelope(), await message()))+ expect(log.auth).toEqual([])+ expect(log.mailFrom).toEqual([])+ })++ it('rejects an untrusted certificate before signing in', async () => {+ const tls = await start({ secure: true, ...untrusted })+ const error = await failure(verifySmtp(settings(tls.port)))+ expect(error).toMatchObject({ code: 'outgoingNetwork' })+ expect(error.message).toMatch(/certificate/)+ const starttls = await start({ ...untrusted })+ const upgrade = await failure(verifySmtp(settings(starttls.port, { security: 'starttls' })))+ expect(upgrade).toMatchObject({ code: 'outgoingNetwork' })+ expect(upgrade.message).toMatch(/certificate/)+ expect([...tls.log.auth, ...starttls.log.auth]).toEqual([])+ })++ it('reports a wrong password as an authentication failure', async () => {+ const { port, log } = await start({ secure: true })+ const error = await failure(verifySmtp(settings(port, { password: 'wrong' })))+ expect(error.code).toBe('outgoingAuthentication')+ const send = await failure(+ submitSmtp(settings(port, { password: 'wrong' }), envelope(), await message()),+ )+ expect(send.code).toBe('outgoingAuthentication')+ expect(log.mailFrom).toEqual([])+ })++ it('fails rather than sending unauthenticated when AUTH is not offered', async () => {+ const { port, log } = await start({+ secure: true,+ authOptional: true,+ disabledCommands: ['AUTH'],+ })+ const error = await failure(submitSmtp(settings(port), envelope(), await message()))+ expect(error.code).toBe('outgoingNetwork')+ expect(log.mailFrom).toEqual([])+ })++ it('reports an unreachable server as a network failure', async () => {+ const closed = createServer()+ await new Promise<void>((resolve) => closed.listen(0, '127.0.0.1', resolve))+ const port = (closed.address() as AddressInfo).port+ await new Promise<void>((resolve) => closed.close(() => resolve()))+ const error = await failure(verifySmtp(settings(port)))+ expect(error.code).toBe('outgoingNetwork')+ })++ it('verifies without ever starting a message', async () => {+ const { port, log } = await start({ secure: true })+ await verifySmtp(settings(port))+ expect(log.auth).toEqual(['user'])+ expect(log.mailFrom).toEqual([])+ expect(log.rcptTo).toEqual([])+ expect(log.data).toEqual([])+ })++ it('treats a refused sender or every refused recipient as a definite rejection', async () => {+ const { port, log } = await start({ secure: true })+ const error = await failure(+ submitSmtp(+ settings(port),+ envelope(['[email protected]', '[email protected]']),+ await message(),+ ),+ )+ expect(error.code).toBe('submissionRejected')+ expect(error.message).toMatch(/every recipient/)+ expect(log.data).toEqual([])++ const sender = await start({+ secure: true,+ onMailFrom: (_address, _session, callback) =>+ callback(Object.assign(new Error('Not your address'), { responseCode: 553 })),+ })+ const refused = await failure(submitSmtp(settings(sender.port), envelope(), await message()))+ expect(refused.code).toBe('submissionRejected')+ expect(refused.message).toMatch(/sender/)+ expect(sender.log.rcptTo).toEqual([])+ })++ it('reports partial acceptance with the rejected recipients and reasons', async () => {+ const { port, log } = await start({ secure: true })+ const outcome = await submitSmtp(+ settings(port),+ envelope(['[email protected]', '[email protected]']),+ await message(),+ )+ expect(outcome.accepted).toEqual(['[email protected]'])+ expect(outcome.rejected).toEqual([+ { email: '[email protected]', reason: expect.stringMatching(/550.*No such user/) },+ ])+ expect(log.data).toHaveLength(1)+ })++ it('delivers Bcc through the envelope only', async () => {+ const { port, log } = await start({ secure: true })+ const mime = await message(['[email protected]'])+ await submitSmtp(settings(port), envelope(['[email protected]', '[email protected]']), mime)+ expect(log.rcptTo).toEqual(['[email protected]', '[email protected]'])+ const received = log.data[0].toString('latin1')+ expect(received).not.toMatch(/^Bcc:/im)+ expect(received).not.toContain('[email protected]')+ })++ it('treats a lost final response as uncertain', async () => {+ const { port, log, sockets } = await start({+ secure: true,+ onData(stream) {+ const chunks: Buffer[] = []+ stream.on('data', (chunk: Buffer) => chunks.push(chunk))+ stream.on('end', () => {+ log.data.push(Buffer.concat(chunks))+ sockets.forEach((s) => s.destroy())+ })+ },+ })+ const error = await failure(submitSmtp(settings(port), envelope(), await message()))+ expect(error.code).toBe('submissionUncertain')+ expect(log.data).toHaveLength(1)+ })++ it('treats a missing final response as uncertain after the timeout', async () => {+ const { port } = await start({+ secure: true,+ onData: (stream) => stream.on('data', () => undefined),+ })+ const error = await failure(+ submitSmtp(settings(port, { timeoutMs: 500 }), envelope(), await message()),+ )+ expect(error.code).toBe('submissionUncertain')+ })++ it('treats 4xx and 5xx final responses as definite rejections', async () => {+ const temporary = await start({ secure: true, onData: finalReply(451) })+ const soft = await failure(submitSmtp(settings(temporary.port), envelope(), await message()))+ expect(soft.code).toBe('submissionRejected')+ expect(soft.message).toMatch(/temporarily/)+ const permanent = await start({ secure: true, onData: finalReply(554) })+ const hard = await failure(submitSmtp(settings(permanent.port), envelope(), await message()))+ expect(hard.code).toBe('submissionRejected')+ expect(hard.message).not.toMatch(/temporarily/)+ expect(hard.message).toMatch(/554/)+ })++ it('rejects an unusable envelope without connecting', async () => {+ const { port, log } = await start({ secure: true })+ for (const to of [[], ['bad [email protected]'], ['<[email protected]>']]) {+ const error = await failure(submitSmtp(settings(port), envelope(to), await message()))+ expect(error.code).toBe('submissionRejected')+ }+ expect(log.auth).toEqual([])+ })++ it('enforces the TLS policy in the connection options', () => {+ const tls = smtpOptions(settings(465, { host: 'mail.example.test' }))+ expect(tls).toMatchObject({ secure: true, ignoreTLS: false, name: '[127.0.0.1]' })+ expect(tls.tls).toMatchObject({+ rejectUnauthorized: true,+ minVersion: 'TLSv1.2',+ servername: 'mail.example.test',+ })+ const starttls = smtpOptions(settings(587, { security: 'starttls', tls: undefined }))+ expect(starttls).toMatchObject({+ secure: false,+ requireTLS: true,+ ignoreTLS: false,+ opportunisticTLS: false,+ })+ expect(starttls.tls).toEqual({ rejectUnauthorized: true, minVersion: 'TLSv1.2' })+ expect(starttls.logger).toBe(false)+ expect(starttls.debug).toBe(false)+ })+})diff --git a/tests/stalwart-imap.integration.test.ts b/tests/stalwart-imap.integration.test.tsnew file mode 100644index 0000000..13656bb--- /dev/null+++ b/tests/stalwart-imap.integration.test.ts@@ -0,0 +1,245 @@+import { describe, it, expect } from 'vitest'+import { randomUUID } from 'node:crypto'+import { readFileSync } from 'node:fs'+import { JmapProvider } from '../packages/jmap/src'+import { ImapProvider, submitSmtp, verifySmtp } from '../packages/imap/src'+import { openInProcessIndex } from '../apps/desktop/src/main/imap-index/sqlite-index'+import type { Draft, ImapConnectionConfig } from '../packages/core/src'++const env = process.env+const ready =+ env.STALWART_TEST_URL &&+ env.STALWART_TEST_USERNAME &&+ env.STALWART_TEST_PASSWORD &&+ env.STALWART_TEST_IMAPS_PORT &&+ env.STALWART_TEST_CA+// Explicit opt-in. Only ever point this at a disposable server: creates and deletes test mail.+describe.skipIf(!ready)('disposable Stalwart IMAP/SMTP integration', () => {+ const username = env.STALWART_TEST_USERNAME!+ const password = env.STALWART_TEST_PASSWORD!+ const ca = ready ? readFileSync(env.STALWART_TEST_CA!, 'utf8') : ''+ const config = (security: 'tls' | 'starttls'): ImapConnectionConfig => ({+ protocol: 'imap',+ email: username,+ incoming: {+ host: '127.0.0.1',+ port: Number(security === 'tls' ? env.STALWART_TEST_IMAPS_PORT : env.STALWART_TEST_IMAP_PORT),+ security,+ username,+ },+ outgoing: {+ host: '127.0.0.1',+ port: Number(+ security === 'tls' ? env.STALWART_TEST_SUBMISSIONS_PORT : env.STALWART_TEST_SUBMISSION_PORT,+ ),+ security,+ username,+ },+ outgoingSameCredentials: true,+ })+ const imap = (+ security: 'tls' | 'starttls' = 'tls',+ overrides: Partial<ConstructorParameters<typeof ImapProvider>[0]> = {},+ ) =>+ new ImapProvider({+ connectionId: 'integration-' + security,+ name: 'Integration',+ config: config(security),+ password,+ index: openInProcessIndex(':memory:'),+ readAttachment: async () => new TextEncoder().encode('Attachment fixture'),+ background: false,+ tls: { ca },+ timing: { sentCopyGraceMs: 3000 },+ ...overrides,+ })+ const sync = (p: ImapProvider) => (p as any).syncPass('all') as Promise<void>++ it('enforces TLS verification, credentials and both security modes', async () => {+ const untrusted = imap('tls', { tls: undefined })+ await expect(untrusted.connect()).rejects.toMatchObject({ code: 'tls' })+ await untrusted.close()+ const wrong = imap('tls', { password: 'wrong-' + randomUUID() })+ await expect(wrong.connect()).rejects.toMatchObject({ code: 'authentication' })+ await wrong.close()+ for (const security of ['tls', 'starttls'] as const) {+ const p = imap(security)+ expect(await p.connect()).toHaveLength(1)+ await p.verifyOutgoing()+ await p.close()+ }+ await expect(+ verifySmtp({ ...config('tls').outgoing, password: 'wrong', tls: { ca } }),+ ).rejects.toMatchObject({ code: 'outgoingAuthentication' })+ }, 60000)++ it('indexes, searches, organizes, drafts and sends, with changes visible over JMAP', async () => {+ const jmap = new JmapProvider({+ serverUrl: env.STALWART_TEST_URL!,+ authorization: 'Basic ' + Buffer.from(username + ':' + password).toString('base64'),+ connectionId: 'integration-jmap',+ name: 'Integration',+ })+ const [jmapAccount] = await jmap.connect()+ const p = imap()+ const [account] = await p.connect()+ const tag = 'Inlark-imap-' + randomUUID()+ let folderId = ''+ try {+ await p.folder(account, 'create', undefined, tag)+ const jmapFolder = (await jmap.mailboxes(jmapAccount)).find((b) => b.name === tag)!+ const [set] = await jmap.call([+ [+ 'Email/set',+ {+ accountId: jmapAccount.remoteId,+ create: Object.fromEntries(+ Array.from({ length: 61 }, (_, i) => [+ 'e' + i,+ {+ mailboxIds: { [jmapFolder.id]: true },+ from: [{ name: 'Fixture', email: username }],+ to: [{ name: 'Test', email: username }],+ subject: tag + ' ' + i,+ messageId: [tag + '-' + i + '@inlark.test'],+ ...(i > 0+ ? {+ references: [tag + '[email protected]'],+ inReplyTo: [tag + '[email protected]'],+ }+ : {}),+ receivedAt: new Date(Date.UTC(2026, 8, 20, 0, i)).toISOString(),+ textBody: [{ partId: 'text', type: 'text/plain' }],+ bodyValues: { text: { value: 'Unicode: Grüße aus Wien. Needle ' + i } },+ },+ ]),+ ),+ },+ 'seed',+ ],+ ])+ expect(set.notCreated).toBeUndefined()+ await sync(p)+ folderId = (await p.mailboxes(account)).find((b) => b.name === tag)!.id+ // All 61 share References, so they are one conversation of 61 messages.+ const page = await p.query(account, { view: 'all', mailboxId: folderId })+ expect(page.items).toHaveLength(1)+ expect(page.items[0].count).toBe(61)+ const messages = await p.conversation(account, page.items[0].id)+ expect(messages).toHaveLength(61)+ expect(messages[0].text).toContain('Grüße')+ // Server search, polled because indexing happens asynchronously on the server.+ await expect+ .poll(+ async () =>+ (await p.query(account, { view: 'all', mailboxId: folderId, subject: tag + ' 60' }))+ .items.length,+ {+ timeout: 15000,+ interval: 500,+ },+ )+ .toBe(1)+ // Flag over IMAP, observe over JMAP.+ const first = messages[0]+ expect(+ (await p.update(account, { [first.id]: { keywords: { $flagged: true } } })).failures,+ ).toEqual([])+ const jmapFirst = (+ await jmap.query(jmapAccount, {+ view: 'all',+ mailboxId: jmapFolder.id,+ subject: tag + ' 0',+ })+ ).items[0].messages.find((m) => m.subject === tag + ' 0')!+ expect((await jmap.messages(jmapAccount, [jmapFirst.id]))[0].keywords.$flagged).toBe(true)+ // Move over IMAP; the message keeps its ID and JMAP sees the new folder.+ const boxes = await p.mailboxes(account)+ const trash = boxes.find((b) => b.role === 'trash')!+ const moved = await p.update(account, {+ [first.id]: { mailboxes: { [folderId]: false, [trash.id]: true } },+ })+ expect(moved).toEqual({ updated: [first.id], failures: [] })+ expect((await p.messages(account, [first.id]))[0].mailboxIds).toEqual({ [trash.id]: true })+ const jmapTrash = (await jmap.mailboxes(jmapAccount)).find((b) => b.role === 'trash')!+ expect((await jmap.messages(jmapAccount, [jmapFirst.id]))[0].mailboxIds).toEqual({+ [jmapTrash.id]: true,+ })+ // Permanent deletion removes exactly that message.+ expect(await p.update(account, {}, [first.id])).toEqual({ updated: [first.id], failures: [] })+ expect(await jmap.messages(jmapAccount, [jmapFirst.id])).toEqual([])++ // Drafts are appended with $draft and visible to JMAP clients.+ const draft: Draft = {+ id: randomUUID(),+ accountId: account.id,+ identityId: 'default',+ to: [{ name: 'Self', email: username }],+ cc: [],+ bcc: [{ name: 'Nobody', email: 'nobody-' + randomUUID().slice(0, 8) + '@inlark.test' }],+ subject: tag + ' submission',+ html: '<p>Grüße per SMTP</p>',+ text: 'Grüße per SMTP',+ attachments: [{ id: randomUUID(), name: 'fixture.txt', type: 'text/plain', size: 18 }],+ updatedAt: new Date().toISOString(),+ status: 'local',+ }+ const draftId = await p.createDraft(account, draft)+ const [savedDraft] = await p.messages(account, [draftId], true)+ expect(savedDraft).toMatchObject({ subject: tag + ' submission', keywords: { $draft: true } })+ expect(savedDraft.attachments).toHaveLength(1)++ // Send: the unknown Bcc recipient is refused while the real one accepts (partial).+ const messageId = randomUUID() + '@inlark.test'+ const outgoing = await p.prepareSubmission(account, draft, messageId)+ const outcome = await submitSmtp(+ { ...config('tls').outgoing, password, tls: { ca } },+ outgoing.envelope,+ outgoing.mime!,+ )+ expect(outcome.accepted).toEqual([username])+ expect(['server', 'filed']).toContain(await p.fileSentCopy(account, outgoing))+ // Filing again finds the copy by Message-ID and never appends a duplicate.+ expect(await p.fileSentCopy(account, outgoing)).toBe('server')+ await expect+ .poll(+ async () => {+ await sync(p)+ return (await p.query(account, { view: 'inbox', subject: tag + ' submission' })).items+ .length+ },+ { timeout: 20000, interval: 1000 },+ )+ .toBe(1)+ const [delivered] = (await p.query(account, { view: 'inbox', subject: tag + ' submission' }))+ .items+ const [received] = await p+ .conversation(account, delivered.id)+ .then((m) => m.filter((x) => x.messageId?.includes(messageId)))+ expect(received.text).toContain('Grüße per SMTP')+ expect(received.bcc).toEqual([])+ } finally {+ // Refresh the JMAP state before each attempt: the IMAP side changed the mailbox meanwhile.+ for (let attempt = 0; attempt < 5; attempt++) {+ const [found] = await jmap.call([+ [+ 'Email/query',+ { accountId: jmapAccount.remoteId, filter: { subject: tag }, limit: 500 },+ 'q',+ ],+ ])+ if (!found.ids.length) break+ await jmap.messages(jmapAccount, found.ids)+ try {+ await jmap.update(jmapAccount, {}, found.ids)+ break+ } catch (error) {+ if (attempt === 4) throw error+ }+ }+ if (folderId) await p.folder(account, 'delete', folderId).catch(() => {})+ await p.close()+ jmap.dispose()+ }+ }, 120000)+})diff --git a/tests/stalwart.integration.test.ts b/tests/stalwart.integration.test.tsnew file mode 100644index 0000000..52e8b4e--- /dev/null+++ b/tests/stalwart.integration.test.ts@@ -0,0 +1,159 @@+import { describe, it, expect } from 'vitest'+import { JmapProvider } from '../packages/jmap/src'+import { randomUUID } from 'node:crypto'+import { spawnSync } from 'node:child_process'+import type { Draft } from '../packages/core/src'+const serverUrl = process.env.STALWART_TEST_URL,+ username = process.env.STALWART_TEST_USERNAME,+ password = process.env.STALWART_TEST_PASSWORD+// Explicit opt-in. Only ever point this at a disposable server: creates and deletes test mail.+describe.skipIf(!serverUrl || !username || !password)('disposable Stalwart integration', () => {+ it('discovers, paginates, searches, renders, uploads, organizes, submits, and cleans up', async () => {+ const provider = new JmapProvider({+ serverUrl: serverUrl!,+ authorization: 'Basic ' + Buffer.from(username + ':' + password).toString('base64'),+ connectionId: 'integration',+ name: 'Integration',+ })+ const [account] = await provider.connect()+ expect(account).toBeTruthy()+ const identities = await provider.identities(account)+ expect(identities.length).toBeGreaterThan(0)+ const tag = 'Inlark-test-' + randomUUID()+ let folderId = ''+ const created: string[] = []+ try {+ await provider.folder(account, 'create', undefined, tag)+ folderId = (await provider.mailboxes(account)).find((b) => b.name === tag)!.id+ const create = Object.fromEntries(+ Array.from({ length: 61 }, (_, i) => [+ 'e' + i,+ {+ mailboxIds: { [folderId]: true },+ keywords: { $seen: true },+ from: [{ name: 'Fixture', email: identities[0].email }],+ to: [{ name: 'Test', email: identities[0].email }],+ subject: tag + ' ' + i,+ receivedAt: new Date(Date.UTC(2026, 8, 20, 0, i)).toISOString(),+ textBody: [{ partId: 'text', type: 'text/plain' }],+ bodyValues: { text: { value: 'Unicode: Grüße aus Wien. Search needle ' + i } },+ },+ ]),+ )+ const [set] = await provider.call([+ ['Email/set', { accountId: account.remoteId, create }, 'seed'],+ ])+ expect(set.notCreated).toBeUndefined()+ created.push(...Object.values<{ id: string }>(set.created).map((v) => v.id))+ // Stalwart updates search/sort indexes asynchronously after bulk Email/set.+ await expect+ .poll(+ async () =>+ (await provider.query(account, { view: 'all', mailboxId: folderId }, 0, 100)).items.map(+ (c) => c.messages[0].id,+ ),+ { timeout: 10000, interval: 100 },+ )+ .toEqual(Array.from({ length: 61 }, (_, i) => set.created['e' + (60 - i)].id))+ const first = await provider.query(account, { view: 'all', mailboxId: folderId }, 0, 50)+ const second = await provider.query(+ account,+ { view: 'all', mailboxId: folderId },+ first.next,+ 50,+ )+ expect(first.items).toHaveLength(50)+ expect(second.items).toHaveLength(11)+ expect(new Set([...first.items, ...second.items].map((c) => c.key)).size).toBe(61)+ const body = await provider.conversation(account, first.items[0].id)+ expect(body[0].text).toContain('Grüße')+ const result = await provider.update(account, {+ [body[0].id]: { keywords: { $flagged: true, $seen: false } },+ })+ expect(result.failures).toEqual([])+ const flagged = await provider.query(account, { view: 'starred', mailboxId: folderId })+ expect(flagged.items).toHaveLength(1)+ expect(flagged.items[0].unread).toBe(true)+ const searched = await provider.query(account, {+ view: 'all',+ mailboxId: folderId,+ subject: tag + ' 60',+ })+ expect(searched.items).toHaveLength(1)+ const blobId = await provider.upload(+ account,+ new TextEncoder().encode('Attachment fixture'),+ 'text/plain',+ )+ const bytes = await provider.download(account, {+ blobId,+ name: 'fixture.txt',+ type: 'text/plain',+ size: 18,+ })+ expect(new TextDecoder().decode(bytes)).toBe('Attachment fixture')+ const draft: Draft = {+ id: randomUUID(),+ accountId: account.id,+ identityId: identities[0].id,+ to: [{ name: 'Self', email: identities[0].email }],+ cc: [],+ bcc: [],+ subject: tag + ' submission',+ html: '<p>Local delivery test</p>',+ text: 'Local delivery test',+ attachments: [+ { id: randomUUID(), blobId, name: 'fixture.txt', size: 18, type: 'text/plain' },+ ],+ updatedAt: new Date().toISOString(),+ status: 'local',+ }+ const emailId = await provider.createDraft(account, draft, draft.id + '@inlark.test')+ created.push(emailId)+ expect((await provider.messages(account, [emailId], true))[0].attachments).toHaveLength(1)+ const outgoing = {+ messageId: draft.id + '@inlark.test',+ emailId,+ envelope: { from: '', to: [] },+ }+ expect((await provider.submit(account, outgoing, draft.identityId)).rejected).toEqual([])+ expect(await provider.submissionExists(account, outgoing)).toBe(true)+ await provider.folder(account, 'rename', folderId, tag + ' renamed')+ if (process.env.STALWART_TEST_CONTAINER) {+ const restart = spawnSync(+ process.env.STALWART_TEST_RUNTIME || 'podman',+ ['restart', process.env.STALWART_TEST_CONTAINER],+ { encoding: 'utf8' },+ )+ expect(restart.status).toBe(0)+ await expect+ .poll(+ async () => {+ try {+ return (await provider.connect())[0].id+ } catch {+ return undefined+ }+ },+ { timeout: 15000, interval: 250 },+ )+ .toBe(account.id)+ expect((await provider.query(account, { view: 'all', mailboxId: folderId })).total).toBe(61)+ }+ } finally {+ if (created.length) {+ for (let attempt = 0; attempt < 5; attempt++) {+ await provider.messages(account, created)+ try {+ await provider.update(account, {}, created)+ break+ } catch (e) {+ if (attempt === 4) throw e+ }+ }+ }+ if (folderId) await provider.folder(account, 'delete', folderId)+ provider.dispose()+ }+ }, 60000)+})diff --git a/tests/support/fake-imap.ts b/tests/support/fake-imap.tsnew file mode 100644index 0000000..36e1905--- /dev/null+++ b/tests/support/fake-imap.ts@@ -0,0 +1,504 @@+import { ProviderError, type Address } from '../../packages/core/src'+import { parseMime } from '../../packages/imap/src/mime'+import type { BodyPart, FolderListing } from '../../packages/imap/src/metadata-index'+import type {+ CopyResult,+ FetchQuery,+ FetchedMessage,+ ImapPort,+ ImapServerOptions,+ SearchCriteria,+} from '../../packages/imap/src/port'++export interface FakeMessageInput {+ messageId?: string+ inReplyTo?: string+ references?: string[]+ subject?: string+ from?: Address[]+ to?: Address[]+ bcc?: Address[]+ date?: string+ text?: string+ html?: string+ attachments?: { name: string; type: string; content: string; cid?: string }[]+ flags?: string[]+}+interface FakeMessage {+ uid: number+ modseq: number+ flags: Set<string>+ internalDate: string+ input: FakeMessageInput+ raw?: Uint8Array+}+interface FakeBox {+ path: string+ specialUse: string | null+ guessed: string | null+ uidValidity: number+ uidNext: number+ messages: FakeMessage[]+}++/** Builds a small but real RFC 5322 message so the MIME parser sees what a server would send. */+function rfc822(input: FakeMessageInput): Uint8Array {+ const header = (name: string, value?: string) => (value ? name + ': ' + value + '\r\n' : '')+ const list = (a?: Address[]) =>+ a?.map((x) => (x.name ? `"${x.name}" <${x.email}>` : x.email)).join(', ')+ const boundary = 'fake-boundary'+ const parts = [+ ['text/plain; charset=utf-8', input.text ?? ''],+ ...(input.html ? [['text/html; charset=utf-8', input.html]] : []),+ ]+ let body: string+ let type: string+ if (!input.attachments?.length && parts.length === 1) {+ type = 'text/plain; charset=utf-8'+ body = input.text ?? ''+ } else {+ type = 'multipart/mixed; boundary="' + boundary + '"'+ body =+ [+ ...parts.map(([t, v]) => '--' + boundary + '\r\nContent-Type: ' + t + '\r\n\r\n' + v),+ ...(input.attachments || []).map(+ (a) =>+ '--' ++ boundary ++ '\r\nContent-Type: ' ++ a.type ++ '\r\nContent-Disposition: ' ++ (a.cid ? 'inline' : 'attachment') ++ '; filename="' ++ a.name ++ '"\r\n' ++ (a.cid ? 'Content-ID: <' + a.cid + '>\r\n' : '') ++ 'Content-Transfer-Encoding: base64\r\n\r\n' ++ Buffer.from(a.content).toString('base64'),+ ),+ ].join('\r\n') ++ '\r\n--' ++ boundary ++ '--\r\n'+ }+ return new TextEncoder().encode(+ header('Message-ID', input.messageId && '<' + input.messageId + '>') ++ header('In-Reply-To', input.inReplyTo && '<' + input.inReplyTo + '>') ++ header('References', input.references?.map((r) => '<' + r + '>').join(' ')) ++ header('Subject', input.subject) ++ header('From', list(input.from)) ++ header('To', list(input.to)) ++ header('Date', input.date && new Date(input.date).toUTCString()) ++ 'MIME-Version: 1.0\r\nContent-Type: ' ++ type ++ '\r\n\r\n' ++ body,+ )+}+function structure(input: FakeMessageInput): BodyPart {+ const text: BodyPart[] = [+ {+ part: '1',+ type: 'text/plain',+ parameters: { charset: 'utf-8' },+ size: (input.text ?? '').length,+ },+ ...(input.html+ ? [+ {+ part: '2',+ type: 'text/html',+ parameters: { charset: 'utf-8' },+ size: input.html.length,+ },+ ]+ : []),+ ]+ if (!input.attachments?.length && text.length === 1) return { ...text[0], part: undefined }+ return {+ type: 'multipart/mixed',+ childNodes: [+ ...text,+ ...(input.attachments || []).map((a, i) => ({+ part: String(text.length + i + 1),+ type: a.type,+ size: a.content.length,+ disposition: a.cid ? 'inline' : 'attachment',+ dispositionParameters: { filename: a.name },+ ...(a.cid ? { id: '<' + a.cid + '>' } : {}),+ })),+ ],+ }+}++export class FakeImapServer {+ capabilities = new Set(['IMAP4REV1', 'IDLE', 'MOVE', 'UIDPLUS', 'CONDSTORE'])+ boxes = new Map<string, FakeBox>()+ password = 'disposable'+ down = false+ /** Like servers whose search index lags behind APPEND: header searches find nothing. */+ laggingSearch = false+ modseq = 1+ ports: FakePort[] = []+ commands: string[] = []+ /** Runs once before the named command; may throw to simulate a failure. */+ hooks = new Map<string, (stage: 'before' | 'after') => void>()+ private validity = 100+ constructor() {+ this.addMailbox('INBOX')+ this.addMailbox('Sent', '\\Sent')+ this.addMailbox('Drafts', '\\Drafts')+ this.addMailbox('Trash', '\\Trash')+ this.addMailbox('Archive', '\\Archive')+ this.addMailbox('Junk', '\\Junk')+ }+ addMailbox(path: string, specialUse: string | null = null, guessed: string | null = null) {+ this.boxes.set(path, {+ path,+ specialUse,+ guessed,+ uidValidity: this.validity++,+ uidNext: 1,+ messages: [],+ })+ }+ box(path: string) {+ const box = this.boxes.get(path)+ if (!box) throw new Error('No mailbox ' + path)+ return box+ }+ /** Delivers a message as another client or the MTA would, and notifies idling connections. */+ deliver(path: string, input: FakeMessageInput): number {+ const box = this.box(path)+ const uid = box.uidNext+++ box.messages.push({+ uid,+ modseq: ++this.modseq,+ flags: new Set(input.flags || []),+ internalDate: new Date(input.date || Date.now()).toISOString(),+ input,+ })+ this.notify(path, 'exists')+ return uid+ }+ /** Another client changes flags directly. */+ setFlags(path: string, uid: number, flags: string[]) {+ const message = this.box(path).messages.find((m) => m.uid === uid)!+ message.flags = new Set(flags)+ message.modseq = ++this.modseq+ this.notify(path, 'flags')+ }+ /** Another client expunges. */+ remove(path: string, uid: number) {+ const box = this.box(path)+ box.messages = box.messages.filter((m) => m.uid !== uid)+ this.notify(path, 'expunge')+ }+ /** The server rebuilt the folder: every UID changes. */+ resetUidValidity(path: string) {+ const box = this.box(path)+ box.uidValidity = this.validity+++ box.uidNext = 1+ for (const m of box.messages) m.uid = box.uidNext+++ }+ notify(path: string, event: 'exists' | 'expunge' | 'flags') {+ for (const port of this.ports) port.emitEvent(event, path)+ }+ hook(command: string, stage: 'before' | 'after') {+ const fn = this.hooks.get(command + ':' + stage)+ if (fn) {+ this.hooks.delete(command + ':' + stage)+ fn(stage)+ }+ }+ port = (options: ImapServerOptions, purpose: 'command' | 'idle') => {+ const port = new FakePort(this, options, purpose)+ this.ports.push(port)+ return port+ }+ get commandPorts() {+ return this.ports.filter((p) => p.purpose === 'command')+ }+}++export class FakePort implements ImapPort {+ private selected?: string+ private open = false+ private handlers = new Map<string, ((path: string) => void)[]>()+ constructor(+ private server: FakeImapServer,+ private options: ImapServerOptions,+ readonly purpose: 'command' | 'idle',+ ) {}+ get capabilities() {+ return this.server.capabilities+ }+ get condstore() {+ return this.server.capabilities.has('CONDSTORE')+ }+ private check(command: string) {+ this.server.commands.push(command)+ if (!this.open) throw new ProviderError('network', 'Connection closed.')+ this.server.hook(command, 'before')+ }+ private selectedBox() {+ if (!this.selected) throw new ProviderError('command', 'No mailbox selected.')+ return this.server.box(this.selected)+ }+ emitEvent(event: string, path: string) {+ if (this.open && this.selected === path)+ for (const fn of this.handlers.get(event) || []) fn(path)+ }+ /** Simulates a dropped connection. */+ drop() {+ if (!this.open) return+ this.open = false+ for (const fn of this.handlers.get('close') || []) fn('')+ }+ async connect() {+ if (this.server.down)+ throw new ProviderError('network', 'The incoming server could not be reached.')+ if (this.options.password !== this.server.password)+ throw new ProviderError('authentication', 'The incoming server rejected this login.')+ this.open = true+ }+ async close() {+ this.drop()+ }+ on(event: string, listener: (path: string) => void) {+ this.handlers.set(event, [...(this.handlers.get(event) || []), listener])+ }+ async list(): Promise<FolderListing[]> {+ this.check('LIST')+ return [...this.server.boxes.values()].map((b) => ({+ path: b.path,+ name: b.path.split('/').at(-1)!,+ delimiter: '/',+ parentPath: b.path.includes('/') ? b.path.slice(0, b.path.lastIndexOf('/')) : null,+ specialUse: b.specialUse,+ guessedSpecialUse: b.guessed,+ noSelect: false,+ }))+ }+ async status(path: string) {+ this.check('STATUS')+ const box = this.server.box(path)+ return {+ messages: box.messages.length,+ unseen: box.messages.filter((m) => !m.flags.has('\\Seen')).length,+ uidNext: box.uidNext,+ uidValidity: String(box.uidValidity),+ highestModseq: this.condstore+ ? String(Math.max(1, ...box.messages.map((m) => m.modseq)))+ : undefined,+ }+ }+ async select(path: string) {+ this.check('SELECT')+ const box = this.server.box(path)+ this.selected = path+ return {+ path,+ uidValidity: String(box.uidValidity),+ uidNext: box.uidNext,+ exists: box.messages.length,+ highestModseq: this.condstore+ ? String(Math.max(1, ...box.messages.map((m) => m.modseq)))+ : undefined,+ }+ }+ private inRange(range: string, uid: number, max: number) {+ return range.split(',').some((part) => {+ const [a, b] = part.split(':')+ const low = a === '*' ? max : Number(a)+ const high = b === undefined ? low : b === '*' ? max : Number(b)+ return uid >= Math.min(low, high) && uid <= Math.max(low, high)+ })+ }+ async search(criteria: SearchCriteria) {+ this.check('SEARCH')+ const box = this.selectedBox()+ const max = Math.max(0, ...box.messages.map((m) => m.uid))+ const has = (value: string | undefined, needle?: string) =>+ !needle || (value || '').toLowerCase().includes(needle.toLowerCase())+ return box.messages+ .filter((m) => {+ const i = m.input+ const addresses = (a?: Address[]) => a?.map((x) => x.name + ' ' + x.email).join(' ')+ if (criteria.uid && !this.inRange(criteria.uid, m.uid, max)) return false+ if (+ criteria.text &&+ !has([i.subject, i.text, i.html, addresses(i.from)].join(' '), criteria.text)+ )+ return false+ if (!has(addresses(i.from), criteria.from) || !has(addresses(i.to), criteria.to))+ return false+ if (!has(i.subject, criteria.subject)) return false+ if (criteria.seen !== undefined && m.flags.has('\\Seen') !== criteria.seen) return false+ if (criteria.flagged !== undefined && m.flags.has('\\Flagged') !== criteria.flagged)+ return false+ if (+ criteria.header?.['message-id'] &&+ (this.server.laggingSearch || '<' + i.messageId + '>' !== criteria.header['message-id'])+ )+ return false+ if (criteria.since && m.internalDate < criteria.since.toISOString().slice(0, 10))+ return false+ return true+ })+ .map((m) => m.uid)+ }+ async fetch(range: string, query: FetchQuery, changedSince?: string): Promise<FetchedMessage[]> {+ this.check('FETCH')+ const box = this.selectedBox()+ const max = Math.max(0, ...box.messages.map((m) => m.uid))+ return box.messages+ .filter((m) => this.inRange(range, m.uid, max))+ .filter((m) => !changedSince || m.modseq > Number(changedSince))+ .map((m) => {+ const i = m.input+ const raw = (m.raw ??= rfc822(i))+ return {+ uid: m.uid,+ modseq: this.condstore ? String(m.modseq) : undefined,+ ...(query.flags ? { flags: [...m.flags] } : {}),+ ...(query.envelope+ ? {+ envelope: {+ date: i.date,+ subject: i.subject,+ messageId: i.messageId && '<' + i.messageId + '>',+ inReplyTo: i.inReplyTo && '<' + i.inReplyTo + '>',+ from: i.from || [],+ to: i.to || [],+ cc: [],+ bcc: i.bcc || [],+ replyTo: [],+ },+ }+ : {}),+ ...(query.bodyStructure ? { bodyStructure: structure(i) } : {}),+ ...(query.internalDate ? { internalDate: m.internalDate } : {}),+ ...(query.size ? { size: raw.length } : {}),+ ...(query.headers+ ? {+ headers: i.references+ ? 'References: ' + i.references.map((r) => '<' + r + '>').join(' ') + '\r\n'+ : '',+ }+ : {}),+ }+ })+ }+ async source(uid: number, maxBytes: number) {+ this.check('FETCH')+ const m = this.selectedBox().messages.find((x) => x.uid === uid)+ if (!m) return undefined+ const raw = (m.raw ??= rfc822(m.input))+ return raw.length > maxBytes ? undefined : raw+ }+ async download(uid: number, part: string, maxBytes: number, truncate = false) {+ this.check('FETCH')+ const m = this.selectedBox().messages.find((x) => x.uid === uid)+ if (!m) throw new ProviderError('notFound', 'Gone.')+ const i = m.input+ const texts = [i.text ?? '', ...(i.html ? [i.html] : [])]+ const index = Number(part === 'TEXT' ? 1 : part) - 1+ const value =+ index < texts.length+ ? texts[index]+ : ((i.attachments || [])[index - texts.length]?.content ?? '')+ const bytes = new TextEncoder().encode(value)+ if (bytes.length > maxBytes && !truncate) throw new ProviderError('tooLarge', 'Too large.')+ return bytes.subarray(0, maxBytes)+ }+ async store(+ uids: number[],+ operation: 'add' | 'remove',+ flags: string[],+ unchangedSince?: string,+ ) {+ this.check('STORE')+ for (const m of this.selectedBox().messages.filter((x) => uids.includes(x.uid))) {+ // CONDSTORE: a message changed after the given modseq is left alone ([MODIFIED]).+ if (unchangedSince && this.condstore && m.modseq > Number(unchangedSince)) continue+ for (const flag of flags) operation === 'add' ? m.flags.add(flag) : m.flags.delete(flag)+ m.modseq = ++this.server.modseq+ }+ this.server.hook('STORE', 'after')+ return true+ }+ private transfer(uids: number[], destination: string, remove: boolean): CopyResult {+ const source = this.selectedBox()+ const target = this.server.box(destination)+ const uidMap = new Map<number, number>()+ for (const m of source.messages.filter((x) => uids.includes(x.uid))) {+ const uid = target.uidNext+++ uidMap.set(m.uid, uid)+ target.messages.push({ ...m, uid, flags: new Set(m.flags), modseq: ++this.server.modseq })+ }+ if (remove) source.messages = source.messages.filter((x) => !uids.includes(x.uid))+ this.server.notify(destination, 'exists')+ return this.capabilities.has('UIDPLUS')+ ? { uidValidity: String(target.uidValidity), uidMap }+ : {}+ }+ async move(uids: number[], destination: string) {+ if (!this.capabilities.has('MOVE')) throw new ProviderError('unsupported', 'No MOVE.')+ this.check('MOVE')+ return this.transfer(uids, destination, true)+ }+ async copy(uids: number[], destination: string) {+ this.check('COPY')+ return this.transfer(uids, destination, false)+ }+ async expunge(uids: number[]) {+ if (!this.capabilities.has('UIDPLUS')) throw new ProviderError('unsupported', 'No UIDPLUS.')+ this.check('UID EXPUNGE')+ const box = this.selectedBox()+ for (const m of box.messages) if (uids.includes(m.uid)) m.flags.add('\\Deleted')+ box.messages = box.messages.filter((m) => !(uids.includes(m.uid) && m.flags.has('\\Deleted')))+ return true+ }+ async append(path: string, content: Uint8Array, flags: string[], date?: Date) {+ this.check('APPEND')+ const box = this.server.box(path)+ // A real server parses the appended message for its envelope.+ const parsed = await parseMime(content)+ const uid = box.uidNext+++ box.messages.push({+ uid,+ modseq: ++this.server.modseq,+ flags: new Set(flags),+ internalDate: (date || new Date()).toISOString(),+ input: {+ messageId: parsed.messageId,+ inReplyTo: parsed.inReplyTo[0],+ references: parsed.references,+ subject: parsed.subject,+ from: parsed.from,+ to: parsed.to,+ bcc: parsed.bcc,+ text: parsed.text,+ html: parsed.html || undefined,+ },+ raw: content,+ })+ this.server.hook('APPEND', 'after')+ return this.capabilities.has('UIDPLUS') ? { uid, uidValidity: String(box.uidValidity) } : {}+ }+ async createMailbox(path: string) {+ this.check('CREATE')+ this.server.addMailbox(path)+ }+ async renameMailbox(path: string, newPath: string) {+ this.check('RENAME')+ const box = this.server.box(path)+ this.server.boxes.delete(path)+ this.server.boxes.set(newPath, { ...box, path: newPath })+ }+ async deleteMailbox(path: string) {+ this.check('DELETE')+ this.server.boxes.delete(path)+ }+}diff --git a/tsconfig.json b/tsconfig.jsonnew file mode 100644index 0000000..eb6122c--- /dev/null+++ b/tsconfig.json@@ -0,0 +1,17 @@+{+ "compilerOptions": {+ "target": "ES2022",+ "module": "ESNext",+ "moduleResolution": "Bundler",+ "lib": ["ES2022", "DOM", "DOM.Iterable"],+ "jsx": "react-jsx",+ "strict": true,+ "noUnusedLocals": true,+ "noUnusedParameters": true,+ "noEmit": true,+ "esModuleInterop": true,+ "resolveJsonModule": true,+ "skipLibCheck": true,+ "forceConsistentCasingInFileNames": true+ }+}diff --git a/turbo.json b/turbo.jsonnew file mode 100644index 0000000..36ab6fd--- /dev/null+++ b/turbo.json@@ -0,0 +1,8 @@+{+ "$schema": "https://turbo.build/schema.json",+ "tasks": {+ "build": { "dependsOn": ["^build"], "outputs": ["out/**", "dist/**"] },+ "typecheck": { "dependsOn": ["^typecheck"] },+ "dev": { "cache": false, "persistent": true }+ }+}diff --git a/vitest.config.ts b/vitest.config.tsnew file mode 100644index 0000000..af7c9cf--- /dev/null+++ b/vitest.config.ts@@ -0,0 +1,13 @@+import { defineConfig } from 'vitest/config'+import { fileURLToPath } from 'node:url'+export default defineConfig({+ resolve: {+ alias: {+ electron: fileURLToPath(new URL('./tests/electron.stub.ts', import.meta.url)),+ '@inlark/core': fileURLToPath(new URL('./packages/core/src/index.ts', import.meta.url)),+ '@inlark/jmap': fileURLToPath(new URL('./packages/jmap/src/index.ts', import.meta.url)),+ '@inlark/imap': fileURLToPath(new URL('./packages/imap/src/index.ts', import.meta.url)),+ },+ },+ test: { include: ['tests/**/*.test.ts'], testTimeout: 15000, environment: 'node' },+})