[
  {
    "path": ".github/ISSUE_TEMPLATE/bug_report.md",
    "content": "---\n\nname: 🐞 Bug report\nabout: Create a report to help us improve\ntitle: \"[Bug] the title of bug report\"\nlabels: bug\nassignees: ''\n\n---\n\n#### Describe the bug\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/help_wanted.md",
    "content": "---\nname: 🥺 Help wanted\nabout: Confuse about the use of electron-vue-vite\ntitle: \"[Help] the title of help wanted report\"\nlabels: help wanted\nassignees: ''\n\n---\n\n#### Describe the problem you confuse\n"
  },
  {
    "path": ".github/PULL_REQUEST_TEMPLATE.md",
    "content": "<!-- Thank you for contributing! -->\n\n### Description\n\n<!-- Please insert your description here and provide especially info about the \"what\" this PR is solving -->\n\n### What is the purpose of this pull request? <!-- (put an \"X\" next to an item) -->\n\n- [ ] Bug fix\n- [ ] New Feature\n- [ ] Documentation update\n- [ ] Other\n"
  },
  {
    "path": ".github/dependabot.yml",
    "content": "# To get started with Dependabot version updates, you'll need to specify which\n# package ecosystems to update and where the package manifests are located.\n# Please see the documentation for all configuration options:\n# https://help.github.com/github/administering-a-repository/configuration-options-for-dependency-updates\n\nversion: 2\nupdates:\n  - package-ecosystem: \"npm\" # See documentation for possible values\n    directory: \"/\" # Location of package manifests\n    schedule:\n      interval: \"monthly\"\n"
  },
  {
    "path": ".github/workflows/build.yml",
    "content": "name: Build\n\non:\n  push:\n    branches: [main]\n    paths-ignore:\n      - \"**.md\"\n      - \"**.spec.js\"\n      - \".idea\"\n      - \".vscode\"\n      - \".dockerignore\"\n      - \"Dockerfile\"\n      - \".gitignore\"\n      - \".github/**\"\n      - \"!.github/workflows/build.yml\"\n\njobs:\n  build:\n    runs-on: ${{ matrix.os }}\n\n    strategy:\n      matrix:\n        os: [macos-latest, ubuntu-latest, windows-latest]\n\n    steps:\n      - name: Checkout Code\n        uses: actions/checkout@v3\n\n      - name: Setup Node.js\n        uses: actions/setup-node@v3\n        with:\n          node-version: 18\n\n      - name: Install Dependencies\n        run: npm install\n\n      - name: Build Release Files\n        run: npm run build\n        env:\n          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n\n      - name: Upload Artifact\n        uses: actions/upload-artifact@v3\n        with:\n          name: release_on_${{ matrix. os }}\n          path: release/\n          retention-days: 5"
  },
  {
    "path": ".github/workflows/ci.yml",
    "content": "name: CI\n\non:\n  pull_request_target:\n    branches:\n      - main\n\npermissions:\n  pull-requests: write\n\njobs:\n  job1:\n    name: Check Not Allowed File Changes\n    runs-on: ubuntu-latest\n    outputs:\n      markdown_change: ${{ steps.filter_markdown.outputs.change }}\n      markdown_files: ${{ steps.filter_markdown.outputs.change_files }}\n    steps:\n\n      - name: Check Not Allowed File Changes\n        uses: dorny/paths-filter@v2\n        id: filter_not_allowed\n        with:\n          list-files: json\n          filters: |\n            change:\n              - 'package-lock.json'\n              - 'yarn.lock'\n              - 'pnpm-lock.yaml'\n\n      # ref: https://github.com/github/docs/blob/main/.github/workflows/triage-unallowed-contributions.yml\n      - name: Comment About Changes We Can't Accept\n        if: ${{ steps.filter_not_allowed.outputs.change == 'true' }}\n        uses: actions/github-script@v6\n        with:\n          script: |\n            let workflowFailMessage = \"It looks like you've modified some files that we can't accept as contributions.\"\n            try {\n              const badFilesArr = [\n                'package-lock.json',\n                'yarn.lock',\n                'pnpm-lock.yaml',\n              ]\n              const badFiles = badFilesArr.join('\\n- ')\n              const reviewMessage = `👋 Hey there spelunker. It looks like you've modified some files that we can't accept as contributions. The complete list of files we can't accept are:\\n- ${badFiles}\\n\\nYou'll need to revert all of the files you changed in that list using [GitHub Desktop](https://docs.github.com/en/free-pro-team@latest/desktop/contributing-and-collaborating-using-github-desktop/managing-commits/reverting-a-commit) or \\`git checkout origin/main <file name>\\`. Once you get those files reverted, we can continue with the review process. :octocat:\\n\\nMore discussion:\\n- https://github.com/electron-vite/electron-vite-vue/issues/192`\n              createdComment = await github.rest.issues.createComment({\n                owner: context.repo.owner,\n                repo: context.repo.repo,\n                issue_number: context.payload.number,\n                body: reviewMessage,\n              })\n              workflowFailMessage = `${workflowFailMessage} Please see ${createdComment.data.html_url} for details.`\n            } catch(err) {\n              console.log(\"Error creating comment.\", err)\n            }\n            core.setFailed(workflowFailMessage)\n\n      - name: Check Not Linted Markdown\n        if: ${{ always() }}\n        uses: dorny/paths-filter@v2\n        id: filter_markdown\n        with:\n          list-files: shell\n          filters: |\n            change:\n              - added|modified: '*.md'\n\n\n  job2:\n    name: Lint Markdown\n    runs-on: ubuntu-latest\n    needs: job1\n    if: ${{ always() && needs.job1.outputs.markdown_change == 'true' }}\n    steps:\n      - name: Checkout Code\n        uses: actions/checkout@v3\n        with:\n          ref: ${{ github.event.pull_request.head.sha }}\n\n      - name: Lint markdown\n        run: npx markdownlint-cli ${{ needs.job1.outputs.markdown_files }} --ignore node_modules"
  },
  {
    "path": ".gitignore",
    "content": "# Logs\nlogs\n*.log\nnpm-debug.log*\nyarn-debug.log*\nyarn-error.log*\npnpm-debug.log*\nlerna-debug.log*\n\nnode_modules\ndist\ndist-ssr\ndist-electron\nrelease\n*.local\n\n# Editor directories and files\n.vscode/.debug.env\n.idea\n.DS_Store\n*.suo\n*.ntvs*\n*.njsproj\n*.sln\n*.sw?\n\n#lockfile\npackage-lock.json\npnpm-lock.yaml\nyarn.lock\n/test-results/\n/playwright-report/\n/playwright/.cache/\n"
  },
  {
    "path": ".npmrc",
    "content": "# For electron-builder\n# https://github.com/electron-userland/electron-builder/issues/6289#issuecomment-1042620422\nshamefully-hoist=true\n\n# For China 🇨🇳 developers\n# electron_mirror=https://npmmirror.com/mirrors/electron/\n"
  },
  {
    "path": ".playwright.config.txt",
    "content": "import type { PlaywrightTestConfig } from \"@playwright/test\";\n\n/**\n * Read environment variables from file.\n * https://github.com/motdotla/dotenv\n */\n// require('dotenv').config();\n\n/**\n * See https://playwright.dev/docs/test-configuration.\n */\nconst config: PlaywrightTestConfig = {\n  testDir: \"./e2e\",\n  /* Maximum time one test can run for. */\n  timeout: 30 * 1000,\n  expect: {\n    /**\n     * Maximum time expect() should wait for the condition to be met.\n     * For example in `await expect(locator).toHaveText();`\n     */\n    timeout: 5000,\n  },\n  /* Run tests in files in parallel */\n  fullyParallel: true,\n  /* Fail the build on CI if you accidentally left test.only in the source code. */\n  forbidOnly: !!process.env.CI,\n  /* Retry on CI only */\n  retries: process.env.CI ? 2 : 0,\n  /* Opt out of parallel tests on CI. */\n  workers: process.env.CI ? 1 : undefined,\n  /* Reporter to use. See https://playwright.dev/docs/test-reporters */\n  reporter: \"html\",\n  /* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */\n  use: {\n    /* Maximum time each action such as `click()` can take. Defaults to 0 (no limit). */\n    actionTimeout: 0,\n    /* Base URL to use in actions like `await page.goto('/')`. */\n    // baseURL: 'http://localhost:3000',\n\n    /* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */\n    trace: \"on-first-retry\",\n  },\n\n  /* Folder for test artifacts such as screenshots, videos, traces, etc. */\n  // outputDir: 'test-results/',\n\n  /* Run your local dev server before starting the tests */\n  // webServer: {\n  //   command: 'npm run start',\n  //   port: 3000,\n  // },\n};\n\nexport default config;\n"
  },
  {
    "path": ".vite.config.flat.txt",
    "content": "import { rmSync } from 'node:fs'\nimport path from 'node:path'\nimport { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react'\nimport electron from 'vite-plugin-electron'\nimport renderer from 'vite-plugin-electron-renderer'\nimport pkg from './package.json'\n\n// https://vitejs.dev/config/\nexport default defineConfig(({ command }) => {\n  rmSync('dist-electron', { recursive: true, force: true })\n\n  const isServe = command === 'serve'\n  const isBuild = command === 'build'\n  const sourcemap = isServe || !!process.env.VSCODE_DEBUG\n\n  return {\n    resolve: {\n      alias: {\n        '@': path.join(__dirname, 'src')\n      },\n    },\n    plugins: [\n      react(),\n      electron([\n        {\n          // Main-Process entry file of the Electron App.\n          entry: 'electron/main/index.ts',\n          onstart(options) {\n            if (process.env.VSCODE_DEBUG) {\n              console.log(/* For `.vscode/.debug.script.mjs` */'[startup] Electron App')\n            } else {\n              options.startup()\n            }\n          },\n          vite: {\n            build: {\n              sourcemap,\n              minify: isBuild,\n              outDir: 'dist-electron/main',\n              rollupOptions: {\n                external: Object.keys('dependencies' in pkg ? pkg.dependencies : {}),\n              },\n            },\n          },\n        },\n        {\n          entry: 'electron/preload/index.ts',\n          onstart(options) {\n            // Notify the Renderer-Process to reload the page when the Preload-Scripts build is complete, \n            // instead of restarting the entire Electron App.\n            options.reload()\n          },\n          vite: {\n            build: {\n              sourcemap: sourcemap ? 'inline' : undefined, // #332\n              minify: isBuild,\n              outDir: 'dist-electron/preload',\n              rollupOptions: {\n                external: Object.keys('dependencies' in pkg ? pkg.dependencies : {}),\n              },\n            },\n          },\n        }\n      ]),\n      // Use Node.js API in the Renderer-process\n      renderer(),\n    ],\n    server: process.env.VSCODE_DEBUG && (() => {\n      const url = new URL(pkg.debug.env.VITE_DEV_SERVER_URL)\n      return {\n        host: url.hostname,\n        port: +url.port,\n      }\n    })(),\n    clearScreen: false,\n  }\n})\n"
  },
  {
    "path": ".vscode/.debug.script.mjs",
    "content": "import fs from 'node:fs'\nimport path from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport { createRequire } from 'node:module'\nimport { spawn } from 'node:child_process'\n\nconst pkg = createRequire(import.meta.url)('../package.json')\nconst __dirname = path.dirname(fileURLToPath(import.meta.url))\n\n// write .debug.env\nconst envContent = Object.entries(pkg.debug.env).map(([key, val]) => `${key}=${val}`)\nfs.writeFileSync(path.join(__dirname, '.debug.env'), envContent.join('\\n'))\n\n// bootstrap\nspawn(\n  // TODO: terminate `npm run dev` when Debug exits.\n  process.platform === 'win32' ? 'npm.cmd' : 'npm',\n  ['run', 'dev'],\n  {\n    stdio: 'inherit',\n    env: Object.assign(process.env, { VSCODE_DEBUG: 'true' }),\n  },\n)"
  },
  {
    "path": ".vscode/extensions.json",
    "content": "{\n  // See http://go.microsoft.com/fwlink/?LinkId=827846\n  // for the documentation about the extensions.json format\n  \"recommendations\": [\n    \"mrmlnc.vscode-json5\"\n  ]\n}\n"
  },
  {
    "path": ".vscode/launch.json",
    "content": "{\n  // Use IntelliSense to learn about possible attributes.\n  // Hover to view descriptions of existing attributes.\n  // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387\n  \"version\": \"0.2.0\",\n  \"compounds\": [\n    {\n      \"name\": \"Debug App\",\n      \"preLaunchTask\": \"Before Debug\",\n      \"configurations\": [\n        \"Debug Main Process\",\n        \"Debug Renderer Process\"\n      ],\n      \"presentation\": {\n        \"hidden\": false,\n        \"group\": \"\",\n        \"order\": 1\n      },\n      \"stopAll\": true\n    }\n  ],\n  \"configurations\": [\n    {\n      \"name\": \"Debug Main Process\",\n      \"type\": \"node\",\n      \"request\": \"launch\",\n      \"runtimeExecutable\": \"${workspaceRoot}/node_modules/.bin/electron\",\n      \"windows\": {\n        \"runtimeExecutable\": \"${workspaceRoot}/node_modules/.bin/electron.cmd\"\n      },\n      \"runtimeArgs\": [\n        \"--no-sandbox\",\n        \"--remote-debugging-port=9229\",\n        \".\"\n      ],\n      \"envFile\": \"${workspaceFolder}/.vscode/.debug.env\",\n      \"console\": \"integratedTerminal\"\n    },\n    {\n      \"name\": \"Debug Renderer Process\",\n      \"port\": 9229,\n      \"request\": \"attach\",\n      \"type\": \"chrome\",\n      \"timeout\": 60000,\n      \"skipFiles\": [\n        \"<node_internals>/**\",\n        \"${workspaceRoot}/node_modules/**\",\n        \"${workspaceRoot}/dist-electron/**\",\n        // Skip files in host(VITE_DEV_SERVER_URL)\n        \"http://127.0.0.1:7777/**\"\n      ]\n    },\n  ]\n}"
  },
  {
    "path": ".vscode/settings.json",
    "content": "{\n  \"typescript.tsdk\": \"node_modules/typescript/lib\",\n  \"typescript.tsc.autoDetect\": \"off\",\n  \"json.schemas\": [\n    {\n      \"fileMatch\": [\n        \"/*electron-builder.json5\",\n        \"/*electron-builder.json\"\n      ],\n      \"url\": \"https://json.schemastore.org/electron-builder\"\n    }\n  ]\n}\n"
  },
  {
    "path": ".vscode/tasks.json",
    "content": "{\n  // See https://go.microsoft.com/fwlink/?LinkId=733558 \n  // for the documentation about the tasks.json format\n  \"version\": \"2.0.0\",\n  \"tasks\": [\n    {\n      \"label\": \"Before Debug\",\n      \"type\": \"shell\",\n      \"command\": \"node .vscode/.debug.script.mjs\",\n      \"isBackground\": true,\n      \"problemMatcher\": {\n        \"owner\": \"typescript\",\n        \"fileLocation\": \"relative\",\n        \"pattern\": {\n          // TODO: correct \"regexp\"\n          \"regexp\": \"^([a-zA-Z]\\\\:\\/?([\\\\w\\\\-]\\/?)+\\\\.\\\\w+):(\\\\d+):(\\\\d+): (ERROR|WARNING)\\\\: (.*)$\",\n          \"file\": 1,\n          \"line\": 3,\n          \"column\": 4,\n          \"code\": 5,\n          \"message\": 6\n        },\n        \"background\": {\n          \"activeOnStart\": true,\n          \"beginsPattern\": \"^.*VITE v.*  ready in \\\\d* ms.*$\",\n          \"endsPattern\": \"^.*\\\\[startup\\\\] Electron App.*$\"\n        }\n      }\n    }\n  ]\n}"
  },
  {
    "path": "LICENSE",
    "content": "MIT License\n\nCopyright (c) 2023 草鞋没号\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "README.md",
    "content": "# electron-vite-react\n\n[![awesome-vite](https://awesome.re/mentioned-badge.svg)](https://github.com/vitejs/awesome-vite)\n![GitHub stars](https://img.shields.io/github/stars/caoxiemeihao/vite-react-electron?color=fa6470)\n![GitHub issues](https://img.shields.io/github/issues/caoxiemeihao/vite-react-electron?color=d8b22d)\n![GitHub license](https://img.shields.io/github/license/caoxiemeihao/vite-react-electron)\n[![Required Node.JS >= 14.18.0 || >=16.0.0](https://img.shields.io/static/v1?label=node&message=14.18.0%20||%20%3E=16.0.0&logo=node.js&color=3f893e)](https://nodejs.org/about/releases)\n\nEnglish | [简体中文](README.zh-CN.md)\n\n## 👀 Overview\n\n📦 Ready out of the box  \n🎯 Based on the official [template-react-ts](https://github.com/vitejs/vite/tree/main/packages/create-vite/template-react-ts), project structure will be familiar to you  \n🌱 Easily extendable and customizable  \n💪 Supports Node.js API in the renderer process  \n🔩 Supports C/C++ native addons  \n🐞 Debugger configuration included  \n🖥 Easy to implement multiple windows  \n\n## 🛫 Quick Setup\n\n```sh\n# clone the project\ngit clone https://github.com/electron-vite/electron-vite-react.git\n\n# enter the project directory\ncd electron-vite-react\n\n# install dependency\nnpm install\n\n# develop\nnpm run dev\n```\n\n## 🐞 Debug\n\n![electron-vite-react-debug.gif](/electron-vite-react-debug.gif)\n\n## 📂 Directory structure\n\nFamiliar React application structure, just with `electron` folder on the top :wink:  \n*Files in this folder will be separated from your React application and built into `dist-electron`*  \n\n```tree\n├── electron                                 Electron-related code\n│   ├── main                                 Main-process source code\n│   └── preload                              Preload-scripts source code\n│\n├── release                                  Generated after production build, contains executables\n│   └── {version}\n│       ├── {os}-{os_arch}                   Contains unpacked application executable\n│       └── {app_name}_{version}.{ext}       Installer for the application\n│\n├── public                                   Static assets\n└── src                                      Renderer source code, your React application\n```\n\n<!--\n## 🚨 Be aware\n\nThis template integrates Node.js API to the renderer process by default. If you want to follow **Electron Security Concerns** you might want to disable this feature. You will have to expose needed API by yourself.  \n\nTo get started, remove the option as shown below. This will [modify the Vite configuration and disable this feature](https://github.com/electron-vite/vite-plugin-electron-renderer#config-presets-opinionated).\n\n```diff\n# vite.config.ts\n\nexport default {\n  plugins: [\n    ...\n-   // Use Node.js API in the Renderer-process\n-   renderer({\n-     nodeIntegration: true,\n-   }),\n    ...\n  ],\n}\n```\n-->\n\n## 🔧 Additional features\n\n1. electron-updater 👉 [see docs](src/components/update/README.md)\n1. playwright\n\n## ❔ FAQ\n\n- [C/C++ addons, Node.js modules - Pre-Bundling](https://github.com/electron-vite/vite-plugin-electron-renderer#dependency-pre-bundling)\n- [dependencies vs devDependencies](https://github.com/electron-vite/vite-plugin-electron-renderer#dependencies-vs-devdependencies)\n"
  },
  {
    "path": "README.zh-CN.md",
    "content": "# vite-react-electron\n\n[![awesome-vite](https://awesome.re/mentioned-badge.svg)](https://github.com/vitejs/awesome-vite)\n![GitHub stars](https://img.shields.io/github/stars/caoxiemeihao/vite-react-electron?color=fa6470)\n![GitHub issues](https://img.shields.io/github/issues/caoxiemeihao/vite-react-electron?color=d8b22d)\n![GitHub license](https://img.shields.io/github/license/caoxiemeihao/vite-react-electron)\n[![Required Node.JS >= 14.18.0 || >=16.0.0](https://img.shields.io/static/v1?label=node&message=14.18.0%20||%20%3E=16.0.0&logo=node.js&color=3f893e)](https://nodejs.org/about/releases)\n\n[English](README.md) | 简体中文\n\n## 概述\n\n📦 开箱即用  \n🎯 基于官方的 [template-react-ts](https://github.com/vitejs/vite/tree/main/packages/create-vite/template-react-ts), 低侵入性  \n🌱 结构清晰，可塑性强  \n💪 支持在渲染进程中使用 Electron、Node.js API  \n🔩 支持 C/C++ 模块  \n🖥 很容易实现多窗口  \n\n## 快速开始\n\n```sh\n# clone the project\ngit clone https://github.com/electron-vite/electron-vite-react.git\n\n# enter the project directory\ncd electron-vite-react\n\n# install dependency\nnpm install\n\n# develop\nnpm run dev\n```\n\n## 调试\n\n![electron-vite-react-debug.gif](/electron-vite-react-debug.gif)\n\n## 目录\n\n*🚨 默认情况下, `electron` 文件夹下的文件将会被构建到 `dist-electron`*\n\n```tree\n├── electron                                 Electron 源码文件夹\n│   ├── main                                 Main-process 源码\n│   └── preload                              Preload-scripts 源码\n│\n├── release                                  构建后生成程序目录\n│   └── {version}\n│       ├── {os}-{os_arch}                   未打包的程序(绿色运行版)\n│       └── {app_name}_{version}.{ext}       应用安装文件\n│\n├── public                                   同 Vite 模板的 public\n└── src                                      渲染进程源码、React代码\n```\n\n<!--\n## 🚨 这需要留神\n\n默认情况下，该模板在渲染进程中集成了 Node.js，如果你不需要它，你只需要删除下面的选项. [因为它会修改 Vite 默认的配置](https://github.com/electron-vite/vite-plugin-electron-renderer#config-presets-opinionated).\n\n```diff\n# vite.config.ts\n\nexport default {\n  plugins: [\n    ...\n-   // Use Node.js API in the Renderer-process\n-   renderer({\n-     nodeIntegration: true,\n-   }),\n    ...\n  ],\n}\n```\n-->\n\n## 🔧 额外的功能\n\n1. Electron 自动更新 👉 [阅读文档](src/components/update/README.zh-CN.md)\n2. Playwright 测试\n\n## ❔ FAQ\n\n- [C/C++ addons, Node.js modules - Pre-Bundling](https://github.com/electron-vite/vite-plugin-electron-renderer#dependency-pre-bundling)\n- [dependencies vs devDependencies](https://github.com/electron-vite/vite-plugin-electron-renderer#dependencies-vs-devdependencies)\n\n## 🍵 🍰 🍣 🍟\n\n<img width=\"270\" src=\"https://github.com/caoxiemeihao/blog/blob/main/assets/$qrcode/$.png?raw=true\">\n"
  },
  {
    "path": "electron/electron-env.d.ts",
    "content": "/// <reference types=\"vite-electron-plugin/electron-env\" />\n\ndeclare namespace NodeJS {\n  interface ProcessEnv {\n    VSCODE_DEBUG?: 'true'\n    /**\n     * The built directory structure\n     *\n     * ```tree\n     * ├─┬ dist-electron\n     * │ ├─┬ main\n     * │ │ └── index.js    > Electron-Main\n     * │ └─┬ preload\n     * │   └── index.mjs   > Preload-Scripts\n     * ├─┬ dist\n     * │ └── index.html    > Electron-Renderer\n     * ```\n     */\n    APP_ROOT: string\n    /** /dist/ or /public/ */\n    VITE_PUBLIC: string\n  }\n}\n"
  },
  {
    "path": "electron/main/index.ts",
    "content": "import { app, BrowserWindow, shell, ipcMain } from 'electron'\nimport { createRequire } from 'node:module'\nimport { fileURLToPath } from 'node:url'\nimport path from 'node:path'\nimport os from 'node:os'\nimport { update } from './update'\n\nconst require = createRequire(import.meta.url)\nconst __dirname = path.dirname(fileURLToPath(import.meta.url))\n\n// The built directory structure\n//\n// ├─┬ dist-electron\n// │ ├─┬ main\n// │ │ └── index.js    > Electron-Main\n// │ └─┬ preload\n// │   └── index.mjs   > Preload-Scripts\n// ├─┬ dist\n// │ └── index.html    > Electron-Renderer\n//\nprocess.env.APP_ROOT = path.join(__dirname, '../..')\n\nexport const MAIN_DIST = path.join(process.env.APP_ROOT, 'dist-electron')\nexport const RENDERER_DIST = path.join(process.env.APP_ROOT, 'dist')\nexport const VITE_DEV_SERVER_URL = process.env.VITE_DEV_SERVER_URL\n\nprocess.env.VITE_PUBLIC = VITE_DEV_SERVER_URL\n  ? path.join(process.env.APP_ROOT, 'public')\n  : RENDERER_DIST\n\n// Disable GPU Acceleration for Windows 7\nif (os.release().startsWith('6.1')) app.disableHardwareAcceleration()\n\n// Set application name for Windows 10+ notifications\nif (process.platform === 'win32') app.setAppUserModelId(app.getName())\n\nif (!app.requestSingleInstanceLock()) {\n  app.quit()\n  process.exit(0)\n}\n\nlet win: BrowserWindow | null = null\nconst preload = path.join(__dirname, '../preload/index.mjs')\nconst indexHtml = path.join(RENDERER_DIST, 'index.html')\n\nasync function createWindow() {\n  win = new BrowserWindow({\n    title: 'Main window',\n    icon: path.join(process.env.VITE_PUBLIC, 'favicon.ico'),\n    webPreferences: {\n      preload,\n      // Warning: Enable nodeIntegration and disable contextIsolation is not secure in production\n      // nodeIntegration: true,\n\n      // Consider using contextBridge.exposeInMainWorld\n      // Read more on https://www.electronjs.org/docs/latest/tutorial/context-isolation\n      // contextIsolation: false,\n    },\n  })\n\n  if (VITE_DEV_SERVER_URL) { // #298\n    win.loadURL(VITE_DEV_SERVER_URL)\n    // Open devTool if the app is not packaged\n    win.webContents.openDevTools()\n  } else {\n    win.loadFile(indexHtml)\n  }\n\n  // Test actively push message to the Electron-Renderer\n  win.webContents.on('did-finish-load', () => {\n    win?.webContents.send('main-process-message', new Date().toLocaleString())\n  })\n\n  // Make all links open with the browser, not with the application\n  win.webContents.setWindowOpenHandler(({ url }) => {\n    if (url.startsWith('https:')) shell.openExternal(url)\n    return { action: 'deny' }\n  })\n\n  // Auto update\n  update(win)\n}\n\napp.whenReady().then(createWindow)\n\napp.on('window-all-closed', () => {\n  win = null\n  if (process.platform !== 'darwin') app.quit()\n})\n\napp.on('second-instance', () => {\n  if (win) {\n    // Focus on the main window if the user tried to open another\n    if (win.isMinimized()) win.restore()\n    win.focus()\n  }\n})\n\napp.on('activate', () => {\n  const allWindows = BrowserWindow.getAllWindows()\n  if (allWindows.length) {\n    allWindows[0].focus()\n  } else {\n    createWindow()\n  }\n})\n\n// New window example arg: new windows url\nipcMain.handle('open-win', (_, arg) => {\n  const childWindow = new BrowserWindow({\n    webPreferences: {\n      preload,\n      nodeIntegration: true,\n      contextIsolation: false,\n    },\n  })\n\n  if (VITE_DEV_SERVER_URL) {\n    childWindow.loadURL(`${VITE_DEV_SERVER_URL}#${arg}`)\n  } else {\n    childWindow.loadFile(indexHtml, { hash: arg })\n  }\n})\n"
  },
  {
    "path": "electron/main/update.ts",
    "content": "import { app, ipcMain } from 'electron'\nimport { createRequire } from 'node:module'\nimport type {\n  ProgressInfo,\n  UpdateDownloadedEvent,\n  UpdateInfo,\n} from 'electron-updater'\n\nconst { autoUpdater } = createRequire(import.meta.url)('electron-updater');\n\nexport function update(win: Electron.BrowserWindow) {\n\n  // When set to false, the update download will be triggered through the API\n  autoUpdater.autoDownload = false\n  autoUpdater.disableWebInstaller = false\n  autoUpdater.allowDowngrade = false\n\n  // start check\n  autoUpdater.on('checking-for-update', function () { })\n  // update available\n  autoUpdater.on('update-available', (arg: UpdateInfo) => {\n    win.webContents.send('update-can-available', { update: true, version: app.getVersion(), newVersion: arg?.version })\n  })\n  // update not available\n  autoUpdater.on('update-not-available', (arg: UpdateInfo) => {\n    win.webContents.send('update-can-available', { update: false, version: app.getVersion(), newVersion: arg?.version })\n  })\n\n  // Checking for updates\n  ipcMain.handle('check-update', async () => {\n    if (!app.isPackaged) {\n      const error = new Error('The update feature is only available after the package.')\n      return { message: error.message, error }\n    }\n\n    try {\n      return await autoUpdater.checkForUpdatesAndNotify()\n    } catch (error) {\n      return { message: 'Network error', error }\n    }\n  })\n\n  // Start downloading and feedback on progress\n  ipcMain.handle('start-download', (event: Electron.IpcMainInvokeEvent) => {\n    startDownload(\n      (error, progressInfo) => {\n        if (error) {\n          // feedback download error message\n          event.sender.send('update-error', { message: error.message, error })\n        } else {\n          // feedback update progress message\n          event.sender.send('download-progress', progressInfo)\n        }\n      },\n      () => {\n        // feedback update downloaded message\n        event.sender.send('update-downloaded')\n      }\n    )\n  })\n\n  // Install now\n  ipcMain.handle('quit-and-install', () => {\n    autoUpdater.quitAndInstall(false, true)\n  })\n}\n\nfunction startDownload(\n  callback: (error: Error | null, info: ProgressInfo | null) => void,\n  complete: (event: UpdateDownloadedEvent) => void,\n) {\n  autoUpdater.on('download-progress', (info: ProgressInfo) => callback(null, info))\n  autoUpdater.on('error', (error: Error) => callback(error, null))\n  autoUpdater.on('update-downloaded', complete)\n  autoUpdater.downloadUpdate()\n}\n"
  },
  {
    "path": "electron/preload/index.ts",
    "content": "import { ipcRenderer, contextBridge } from 'electron'\n\n// --------- Expose some API to the Renderer process ---------\ncontextBridge.exposeInMainWorld('ipcRenderer', {\n  on(...args: Parameters<typeof ipcRenderer.on>) {\n    const [channel, listener] = args\n    return ipcRenderer.on(channel, (event, ...args) => listener(event, ...args))\n  },\n  off(...args: Parameters<typeof ipcRenderer.off>) {\n    const [channel, ...omit] = args\n    return ipcRenderer.off(channel, ...omit)\n  },\n  send(...args: Parameters<typeof ipcRenderer.send>) {\n    const [channel, ...omit] = args\n    return ipcRenderer.send(channel, ...omit)\n  },\n  invoke(...args: Parameters<typeof ipcRenderer.invoke>) {\n    const [channel, ...omit] = args\n    return ipcRenderer.invoke(channel, ...omit)\n  },\n\n  // You can expose other APTs you need here.\n  // ...\n})\n\n// --------- Preload scripts loading ---------\nfunction domReady(condition: DocumentReadyState[] = ['complete', 'interactive']) {\n  return new Promise(resolve => {\n    if (condition.includes(document.readyState)) {\n      resolve(true)\n    } else {\n      document.addEventListener('readystatechange', () => {\n        if (condition.includes(document.readyState)) {\n          resolve(true)\n        }\n      })\n    }\n  })\n}\n\nconst safeDOM = {\n  append(parent: HTMLElement, child: HTMLElement) {\n    if (!Array.from(parent.children).find(e => e === child)) {\n      return parent.appendChild(child)\n    }\n  },\n  remove(parent: HTMLElement, child: HTMLElement) {\n    if (Array.from(parent.children).find(e => e === child)) {\n      return parent.removeChild(child)\n    }\n  },\n}\n\n/**\n * https://tobiasahlin.com/spinkit\n * https://connoratherton.com/loaders\n * https://projects.lukehaas.me/css-loaders\n * https://matejkustec.github.io/SpinThatShit\n */\nfunction useLoading() {\n  const className = `loaders-css__square-spin`\n  const styleContent = `\n@keyframes square-spin {\n  25% { transform: perspective(100px) rotateX(180deg) rotateY(0); }\n  50% { transform: perspective(100px) rotateX(180deg) rotateY(180deg); }\n  75% { transform: perspective(100px) rotateX(0) rotateY(180deg); }\n  100% { transform: perspective(100px) rotateX(0) rotateY(0); }\n}\n.${className} > div {\n  animation-fill-mode: both;\n  width: 50px;\n  height: 50px;\n  background: #fff;\n  animation: square-spin 3s 0s cubic-bezier(0.09, 0.57, 0.49, 0.9) infinite;\n}\n.app-loading-wrap {\n  position: fixed;\n  top: 0;\n  left: 0;\n  width: 100vw;\n  height: 100vh;\n  display: flex;\n  align-items: center;\n  justify-content: center;\n  background: #282c34;\n  z-index: 9;\n}\n    `\n  const oStyle = document.createElement('style')\n  const oDiv = document.createElement('div')\n\n  oStyle.id = 'app-loading-style'\n  oStyle.innerHTML = styleContent\n  oDiv.className = 'app-loading-wrap'\n  oDiv.innerHTML = `<div class=\"${className}\"><div></div></div>`\n\n  return {\n    appendLoading() {\n      safeDOM.append(document.head, oStyle)\n      safeDOM.append(document.body, oDiv)\n    },\n    removeLoading() {\n      safeDOM.remove(document.head, oStyle)\n      safeDOM.remove(document.body, oDiv)\n    },\n  }\n}\n\n// ----------------------------------------------------------------------\n\nconst { appendLoading, removeLoading } = useLoading()\ndomReady().then(appendLoading)\n\nwindow.onmessage = (ev) => {\n  ev.data.payload === 'removeLoading' && removeLoading()\n}\n\nsetTimeout(removeLoading, 4999)"
  },
  {
    "path": "electron-builder.json",
    "content": "{\n  \"$schema\": \"https://raw.githubusercontent.com/electron-userland/electron-builder/master/packages/app-builder-lib/scheme.json\",\n  \"appId\": \"YourAppID\",\n  \"asar\": true,\n  \"directories\": {\n    \"output\": \"release/${version}\"\n  },\n  \"files\": [\n    \"dist-electron\",\n    \"dist\"\n  ],\n  \"mac\": {\n    \"artifactName\": \"${productName}_${version}.${ext}\",\n    \"target\": [\n      \"dmg\",\n      \"zip\"\n    ]\n  },\n  \"win\": {\n    \"target\": [\n      {\n        \"target\": \"nsis\",\n        \"arch\": [\n          \"x64\"\n        ]\n      }\n    ],\n    \"artifactName\": \"${productName}_${version}.${ext}\"\n  },\n  \"nsis\": {\n    \"oneClick\": false,\n    \"perMachine\": false,\n    \"allowToChangeInstallationDirectory\": true,\n    \"deleteAppDataOnUninstall\": false\n  },\n  \"publish\": {\n    \"provider\": \"generic\",\n    \"channel\": \"latest\",\n    \"url\": \"https://github.com/electron-vite/electron-vite-react/releases/download/v0.9.9/\"\n  }\n}\n"
  },
  {
    "path": "index.html",
    "content": "<!DOCTYPE html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"UTF-8\" />\n    <link rel=\"icon\" type=\"image/x-icon\" href=\"/favicon.ico\" />\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n    <meta http-equiv=\"Content-Security-Policy\" content=\"script-src 'self' 'unsafe-inline';\" />\n    <title>Electron + Vite + React</title>\n  </head>\n  <body>\n    <div id=\"root\"></div>\n    <script type=\"module\" src=\"/src/main.tsx\"></script>\n  </body>\n</html>\n"
  },
  {
    "path": "package.json",
    "content": "{\n  \"name\": \"electron-vite-react\",\n  \"version\": \"2.2.0\",\n  \"main\": \"dist-electron/main/index.js\",\n  \"description\": \"Electron Vite React boilerplate.\",\n  \"author\": \"草鞋没号 <308487730@qq.com>\",\n  \"license\": \"MIT\",\n  \"private\": true,\n  \"debug\": {\n    \"env\": {\n      \"VITE_DEV_SERVER_URL\": \"http://127.0.0.1:7777/\"\n    }\n  },\n  \"type\": \"module\",\n  \"scripts\": {\n    \"dev\": \"vite\",\n    \"build\": \"tsc && vite build && electron-builder\",\n    \"preview\": \"vite preview\",\n    \"pretest\": \"vite build --mode=test\",\n    \"test\": \"vitest run\"\n  },\n  \"dependencies\": {\n    \"electron-updater\": \"^6.3.9\"\n  },\n  \"devDependencies\": {\n    \"@playwright/test\": \"^1.48.2\",\n    \"@types/react\": \"^18.3.12\",\n    \"@types/react-dom\": \"^18.3.1\",\n    \"@vitejs/plugin-react\": \"^4.3.3\",\n    \"autoprefixer\": \"^10.4.20\",\n    \"electron\": \"^33.2.0\",\n    \"electron-builder\": \"^24.13.3\",\n    \"postcss\": \"^8.4.49\",\n    \"postcss-import\": \"^16.1.0\",\n    \"react\": \"^18.3.1\",\n    \"react-dom\": \"^18.3.1\",\n    \"tailwindcss\": \"^3.4.15\",\n    \"typescript\": \"^5.4.2\",\n    \"vite\": \"^5.4.11\",\n    \"vite-plugin-electron\": \"^0.29.0\",\n    \"vite-plugin-electron-renderer\": \"^0.14.6\",\n    \"vitest\": \"^2.1.5\"\n  }\n}\n"
  },
  {
    "path": "postcss.config.cjs",
    "content": "module.exports = {\n  plugins: {\n    'postcss-import': {},\n    'tailwindcss/nesting': {},\n    tailwindcss: {},\n    autoprefixer: {},\n  },\n}\n"
  },
  {
    "path": "src/App.css",
    "content": "#root {\n  max-width: 1280px;\n  margin: 0 auto;\n  padding: 2rem;\n  text-align: center;\n}\n\n.logo-box {\n  position: relative;\n  height: 9em;\n}\n\n.logo {\n  position: absolute;\n  left: calc(50% - 4.5em);\n  height: 6em;\n  padding: 1.5em;\n  will-change: filter;\n  transition: filter 300ms;\n}\n.logo:hover {\n  filter: drop-shadow(0 0 2em #646cffaa);\n}\n\n@keyframes logo-spin {\n  from {\n    transform: rotate(0deg);\n  }\n  to {\n    transform: rotate(360deg);\n  }\n}\n\n@media (prefers-reduced-motion: no-preference) {\n  .logo.electron {\n    animation: logo-spin infinite 20s linear;\n  }\n}\n\n.card {\n  padding: 2em;\n}\n\n.read-the-docs {\n  color: #888;\n}\n\n.flex-center {\n  display: flex;\n  align-items: center;\n  justify-content: center;\n}\n"
  },
  {
    "path": "src/App.tsx",
    "content": "import { useState } from 'react'\nimport UpdateElectron from '@/components/update'\nimport logoVite from './assets/logo-vite.svg'\nimport logoElectron from './assets/logo-electron.svg'\nimport './App.css'\n\nfunction App() {\n  const [count, setCount] = useState(0)\n  return (\n    <div className='App'>\n      <div className='logo-box'>\n        <a href='https://github.com/electron-vite/electron-vite-react' target='_blank'>\n          <img src={logoVite} className='logo vite' alt='Electron + Vite logo' />\n          <img src={logoElectron} className='logo electron' alt='Electron + Vite logo' />\n        </a>\n      </div>\n      <h1>Electron + Vite + React</h1>\n      <div className='card'>\n        <button onClick={() => setCount((count) => count + 1)}>\n          count is {count}\n        </button>\n        <p>\n          Edit <code>src/App.tsx</code> and save to test HMR\n        </p>\n      </div>\n      <p className='read-the-docs'>\n        Click on the Electron + Vite logo to learn more\n      </p>\n      <div className='flex-center'>\n        Place static files into the<code>/public</code> folder <img style={{ width: '5em' }} src='./node.svg' alt='Node logo' />\n      </div>\n\n      <UpdateElectron />\n    </div>\n  )\n}\n\nexport default App"
  },
  {
    "path": "src/components/update/Modal/index.tsx",
    "content": "import React, { ReactNode } from 'react'\nimport { createPortal } from 'react-dom'\nimport './modal.css'\n\nconst ModalTemplate: React.FC<React.PropsWithChildren<{\n  title?: ReactNode\n  footer?: ReactNode\n  cancelText?: string\n  okText?: string\n  onCancel?: () => void\n  onOk?: () => void\n  width?: number\n}>> = props => {\n  const {\n    title,\n    children,\n    footer,\n    cancelText = 'Cancel',\n    okText = 'OK',\n    onCancel,\n    onOk,\n    width = 530,\n  } = props\n\n  return (\n    <div className='update-modal'>\n      <div className='update-modal__mask' />\n      <div className='update-modal__warp'>\n        <div className='update-modal__content' style={{ width }}>\n          <div className='content__header'>\n            <div className='content__header-text'>{title}</div>\n            <span\n              className='update-modal--close'\n              onClick={onCancel}\n            >\n              <svg\n                viewBox=\"0 0 1024 1024\"\n                version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\"\n              >\n                <path d=\"M557.312 513.248l265.28-263.904c12.544-12.48 12.608-32.704 0.128-45.248-12.512-12.576-32.704-12.608-45.248-0.128l-265.344 263.936-263.04-263.84C236.64 191.584 216.384 191.52 203.84 204 191.328 216.48 191.296 236.736 203.776 249.28l262.976 263.776L201.6 776.8c-12.544 12.48-12.608 32.704-0.128 45.248 6.24 6.272 14.464 9.44 22.688 9.44 8.16 0 16.32-3.104 22.56-9.312l265.216-263.808 265.44 266.24c6.24 6.272 14.432 9.408 22.656 9.408 8.192 0 16.352-3.136 22.592-9.344 12.512-12.48 12.544-32.704 0.064-45.248L557.312 513.248z\" p-id=\"2764\" fill=\"currentColor\">\n                </path>\n              </svg>\n            </span>\n          </div>\n          <div className='content__body'>{children}</div>\n          {typeof footer !== 'undefined' ? (\n            <div className='content__footer'>\n              <button onClick={onCancel}>{cancelText}</button>\n              <button onClick={onOk}>{okText}</button>\n            </div>\n          ) : footer}\n        </div>\n      </div>\n    </div>\n  )\n}\n\nconst Modal = (props: Parameters<typeof ModalTemplate>[0] & { open: boolean }) => {\n  const { open, ...omit } = props\n\n  return createPortal(\n    open ? ModalTemplate(omit) : null,\n    document.body,\n  )\n}\n\nexport default Modal\n"
  },
  {
    "path": "src/components/update/Modal/modal.css",
    "content": ".update-modal {\n  --primary-color: rgb(224, 30, 90);\n\n  .update-modal__mask {\n    width: 100vw;\n    height: 100vh;\n    position: fixed;\n    left: 0;\n    top: 0;\n    z-index: 9;\n    background: rgba(0, 0, 0, 0.45);\n  }\n\n  .update-modal__warp {\n    position: fixed;\n    top: 50%;\n    left: 50%;\n    transform: translate(-50%, -50%);\n    z-index: 19;\n  }\n\n  .update-modal__content {\n    box-shadow: 0 0 10px -4px rgb(130, 86, 208);\n    overflow: hidden;\n    border-radius: 4px;\n\n    .content__header {\n      display: flex;\n      line-height: 38px;\n      background-color: var(--primary-color);\n\n      .content__header-text {\n        font-weight: bold;\n        width: 0;\n        flex-grow: 1;\n      }\n    }\n\n    .update-modal--close {\n      width: 30px;\n      height: 30px;\n      margin: 4px;\n      line-height: 34px;\n      text-align: center;\n      cursor: pointer;\n\n      svg {\n        width: 17px;\n        height: 17px;\n      }\n    }\n\n    .content__body {\n      padding: 10px;\n      background-color: #fff;\n      color: #333;\n    }\n\n    .content__footer {\n      padding: 10px;\n      background-color: #fff;\n      display: flex;\n      justify-content: flex-end;\n\n      button {\n        padding: 7px 11px;\n        background-color: var(--primary-color);\n        font-size: 14px;\n        margin-left: 10px;\n\n        &:first-child {\n          margin-left: 0;\n        }\n      }\n    }\n  }\n\n  .icon {\n    padding: 0 15px;\n    width: 20px;\n    fill: currentColor;\n\n    &:hover {\n      color: rgba(0, 0, 0, 0.4);\n    }\n  }\n}"
  },
  {
    "path": "src/components/update/Progress/index.tsx",
    "content": "import React from 'react'\nimport './progress.css'\n\nconst Progress: React.FC<React.PropsWithChildren<{\n  percent?: number\n}>> = props => {\n  const { percent = 0 } = props\n\n  return (\n    <div className='update-progress'>\n      <div className='update-progress-pr'>\n        <div\n          className='update-progress-rate'\n          style={{ width: `${3 * percent}px` }}\n        />\n      </div>\n      <span className='update-progress-num'>{(percent ?? 0).toString().substring(0, 4)}%</span>\n    </div>\n  )\n}\n\nexport default Progress\n"
  },
  {
    "path": "src/components/update/Progress/progress.css",
    "content": ".update-progress {\n  display: flex;\n  align-items: center;\n\n  .update-progress-pr {\n    border: 1px solid #000;\n    border-radius: 3px;\n    height: 6px;\n    width: 300px;\n  }\n\n  .update-progress-rate {\n    height: 6px;\n    border-radius: 3px;\n    background-image: linear-gradient(to right, rgb(130, 86, 208) 0%, var(--primary-color) 100%)\n  }\n\n  .update-progress-num {\n    margin: 0 10px;\n  }\n}"
  },
  {
    "path": "src/components/update/README.md",
    "content": "# electron-updater\n\nEnglish | [简体中文](README.zh-CN.md)\n\n> Use `electron-updater` to realize the update detection, download and installation of the electric program.\n\n```sh\nnpm i electron-updater\n```\n\n### Main logic\n\n1. ##### Configuration of the update the service address and update information script:\n\n   Add a `publish` field to `electron-builder.json5` for configuring the update address and which strategy to use as the update service.\n\n   ``` json5\n   {\n      \"publish\": {\n         \"provider\": \"generic\",\n         \"channel\": \"latest\",\n         \"url\": \"https://foo.com/\"\n      }\n   }\n   ```\n\n   For more information, please refer to : [electron-builder.json5...](https://github.com/electron-vite/electron-vite-react/blob/2f2880a9f19de50ff14a0785b32a4d5427477e55/electron-builder.json5#L38)\n\n2. ##### The update logic of Electron:\n\n   - Checking if an update is available;\n   - Checking the version of the software on the server;\n   - Checking if an update is available;\n   - Downloading the new version of the software from the server (when an update is available);\n   - Installation method;\n\n   For more information, please refer to  : [update...](https://github.com/electron-vite/electron-vite-react/blob/main/electron/main/update.ts)\n\n3. ##### Updating UI pages in Electron:\n\n   The main function is to provide a UI page for users to trigger the update logic mentioned in (2.) above. Users can click on the page to trigger different update functions in Electron.\n   \n   For more information, please refer to : [components/update...](https://github.com/electron-vite/electron-vite-react/blob/main/src/components/update/index.tsx)\n\n---\n\nHere it is recommended to trigger updates through user actions (in this project, Electron update function is triggered after the user clicks on the \"Check for updates\" button).\n\nFor more information on using `electron-updater` for Electron updates, please refer to the documentation : [auto-update](https://www.electron.build/.html)\n"
  },
  {
    "path": "src/components/update/README.zh-CN.md",
    "content": "# electron-auto-update\n\n[English](README.md) | 简体中文\n\n使用`electron-updater`实现electron程序的更新检测、下载和安装等功能。\n\n```sh\nnpm i electron-updater\n```\n\n### 主要逻辑\n\n1. ##### 更新地址、更新信息脚本的配置\n\n   在`electron-builder.json5`添加`publish`字段,用来配置更新地址和使用哪种策略作为更新服务\n\n    ``` json5\n    {\n      \"publish\": {\n        \"provider\": \"generic\",    // 提供者、提供商\n        \"channel\": \"latest\",      // 生成yml文件的名称\n        \"url\": \"https://foo.com/\" //更新地址\n      }\n    }\n    ```\n\n更多见 : [electron-builder.json5...](xxx)\n\n2. ##### Electron更新逻辑\n\n   - 检测更新是否可用；\n\n   - 检测服务端的软件版本；\n\n   - 检测更新是否可用；\n\n   - 下载服务端新版软件（当更新可用）；\n   - 安装方式；\n\n  更多见 : [update...](https://github.com/electron-vite/electron-vite-react/blob/main/electron/main/update.ts)\n\n3. ##### Electron更新UI页面\n\n    主要功能是：用户触发上述(2.)更新逻辑的UI页面。用户可以通过点击页面触发electron更新的不同功能。\n    更多见 : [components/update.ts...](https://github.com/electron-vite/electron-vite-react/tree/main/src/components/update/index.tsx)\n\n---\n\n这里建议更新触发以用户操作触发（本项目的以用户点击 **更新检测** 后触发electron更新功能）\n\n关于更多使用`electron-updater`进行electron更新，见文档：[auto-update](https://www.electron.build/.html)\n"
  },
  {
    "path": "src/components/update/index.tsx",
    "content": "import type { ProgressInfo } from 'electron-updater'\nimport { useCallback, useEffect, useState } from 'react'\nimport Modal from '@/components/update/Modal'\nimport Progress from '@/components/update/Progress'\nimport './update.css'\n\nconst Update = () => {\n  const [checking, setChecking] = useState(false)\n  const [updateAvailable, setUpdateAvailable] = useState(false)\n  const [versionInfo, setVersionInfo] = useState<VersionInfo>()\n  const [updateError, setUpdateError] = useState<ErrorType>()\n  const [progressInfo, setProgressInfo] = useState<Partial<ProgressInfo>>()\n  const [modalOpen, setModalOpen] = useState<boolean>(false)\n  const [modalBtn, setModalBtn] = useState<{\n    cancelText?: string\n    okText?: string\n    onCancel?: () => void\n    onOk?: () => void\n  }>({\n    onCancel: () => setModalOpen(false),\n    onOk: () => window.ipcRenderer.invoke('start-download'),\n  })\n\n  const checkUpdate = async () => {\n    setChecking(true)\n    /**\n     * @type {import('electron-updater').UpdateCheckResult | null | { message: string, error: Error }}\n     */\n    const result = await window.ipcRenderer.invoke('check-update')\n    setProgressInfo({ percent: 0 })\n    setChecking(false)\n    setModalOpen(true)\n    if (result?.error) {\n      setUpdateAvailable(false)\n      setUpdateError(result?.error)\n    }\n  }\n\n  const onUpdateCanAvailable = useCallback((_event: Electron.IpcRendererEvent, arg1: VersionInfo) => {\n    setVersionInfo(arg1)\n    setUpdateError(undefined)\n    // Can be update\n    if (arg1.update) {\n      setModalBtn(state => ({\n        ...state,\n        cancelText: 'Cancel',\n        okText: 'Update',\n        onOk: () => window.ipcRenderer.invoke('start-download'),\n      }))\n      setUpdateAvailable(true)\n    } else {\n      setUpdateAvailable(false)\n    }\n  }, [])\n\n  const onUpdateError = useCallback((_event: Electron.IpcRendererEvent, arg1: ErrorType) => {\n    setUpdateAvailable(false)\n    setUpdateError(arg1)\n  }, [])\n\n  const onDownloadProgress = useCallback((_event: Electron.IpcRendererEvent, arg1: ProgressInfo) => {\n    setProgressInfo(arg1)\n  }, [])\n\n  const onUpdateDownloaded = useCallback((_event: Electron.IpcRendererEvent, ...args: any[]) => {\n    setProgressInfo({ percent: 100 })\n    setModalBtn(state => ({\n      ...state,\n      cancelText: 'Later',\n      okText: 'Install now',\n      onOk: () => window.ipcRenderer.invoke('quit-and-install'),\n    }))\n  }, [])\n\n  useEffect(() => {\n    // Get version information and whether to update\n    window.ipcRenderer.on('update-can-available', onUpdateCanAvailable)\n    window.ipcRenderer.on('update-error', onUpdateError)\n    window.ipcRenderer.on('download-progress', onDownloadProgress)\n    window.ipcRenderer.on('update-downloaded', onUpdateDownloaded)\n\n    return () => {\n      window.ipcRenderer.off('update-can-available', onUpdateCanAvailable)\n      window.ipcRenderer.off('update-error', onUpdateError)\n      window.ipcRenderer.off('download-progress', onDownloadProgress)\n      window.ipcRenderer.off('update-downloaded', onUpdateDownloaded)\n    }\n  }, [])\n\n  return (\n    <>\n      <Modal\n        open={modalOpen}\n        cancelText={modalBtn?.cancelText}\n        okText={modalBtn?.okText}\n        onCancel={modalBtn?.onCancel}\n        onOk={modalBtn?.onOk}\n        footer={updateAvailable ? /* hide footer */null : undefined}\n      >\n        <div className='modal-slot'>\n          {updateError\n            ? (\n              <div>\n                <p>Error downloading the latest version.</p>\n                <p>{updateError.message}</p>\n              </div>\n            ) : updateAvailable\n              ? (\n                <div>\n                  <div>The last version is: v{versionInfo?.newVersion}</div>\n                  <div className='new-version__target'>v{versionInfo?.version} -&gt; v{versionInfo?.newVersion}</div>\n                  <div className='update__progress'>\n                    <div className='progress__title'>Update progress:</div>\n                    <div className='progress__bar'>\n                      <Progress percent={progressInfo?.percent} ></Progress>\n                    </div>\n                  </div>\n                </div>\n              )\n              : (\n                <div className='can-not-available'>{JSON.stringify(versionInfo ?? {}, null, 2)}</div>\n              )}\n        </div>\n      </Modal>\n      <button disabled={checking} onClick={checkUpdate}>\n        {checking ? 'Checking...' : 'Check update'}\n      </button>\n    </>\n  )\n}\n\nexport default Update\n"
  },
  {
    "path": "src/components/update/update.css",
    "content": ".modal-slot {\n  .update-progress {\n    display: flex;\n  }\n\n  .new-version__target,\n  .update__progress {\n    margin-left: 40px;\n  }\n\n  .progress__title {\n    margin-right: 10px;\n  }\n\n  .progress__bar {\n    width: 0;\n    flex-grow: 1;\n  }\n\n  .can-not-available {\n    padding: 20px;\n    text-align: center;\n  }\n}"
  },
  {
    "path": "src/demos/ipc.ts",
    "content": "\nwindow.ipcRenderer.on('main-process-message', (_event, ...args) => {\n  console.log('[Receive Main-process message]:', ...args)\n})\n"
  },
  {
    "path": "src/demos/node.ts",
    "content": "import { lstat } from 'node:fs/promises'\nimport { cwd } from 'node:process'\n\nlstat(cwd()).then(stats => {\n  console.log('[fs.lstat]', stats)\n}).catch(err => {\n  console.error(err)\n})\n"
  },
  {
    "path": "src/index.css",
    "content": "@tailwind base;\n@tailwind components;\n@tailwind utilities;\n\n:root {\n  font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif;\n  line-height: 1.5;\n  font-weight: 400;\n\n  color-scheme: light dark;\n  color: rgba(255, 255, 255, 0.87);\n  background-color: #242424;\n\n  font-synthesis: none;\n  text-rendering: optimizeLegibility;\n  -webkit-font-smoothing: antialiased;\n  -moz-osx-font-smoothing: grayscale;\n  -webkit-text-size-adjust: 100%;\n}\n\na {\n  font-weight: 500;\n  color: #646cff;\n  text-decoration: inherit;\n}\na:hover {\n  color: #535bf2;\n}\n\nbody {\n  margin: 0;\n  display: flex;\n  place-items: center;\n  min-width: 320px;\n  min-height: 100vh;\n}\n\nh1 {\n  font-size: 3.2em;\n  line-height: 1.1;\n}\n\nbutton {\n  border-radius: 8px;\n  border: 1px solid transparent;\n  padding: 0.6em 1.2em;\n  font-size: 1em;\n  font-weight: 500;\n  font-family: inherit;\n  background-color: #1a1a1a;\n  cursor: pointer;\n  transition: border-color 0.25s;\n}\nbutton:hover {\n  border-color: #646cff;\n}\nbutton:focus,\nbutton:focus-visible {\n  outline: 4px auto -webkit-focus-ring-color;\n}\n\ncode {\n  background-color: #1a1a1a;\n  padding: 2px 4px;\n  margin: 0 4px;\n  border-radius: 4px;\n}\n\n.card {\n  padding: 2em;\n}\n\n#app {\n  max-width: 1280px;\n  margin: 0 auto;\n  padding: 2rem;\n  text-align: center;\n}\n\n@media (prefers-color-scheme: light) {\n  :root {\n    color: #213547;\n    background-color: #ffffff;\n  }\n  a:hover {\n    color: #747bff;\n  }\n  button {\n    background-color: #f9f9f9;\n  }\n  code {\n    background-color: #f9f9f9;\n  }\n}\n"
  },
  {
    "path": "src/main.tsx",
    "content": "import React from 'react'\nimport ReactDOM from 'react-dom/client'\nimport App from './App'\n\nimport './index.css'\n\nimport './demos/ipc'\n// If you want use Node.js, the`nodeIntegration` needs to be enabled in the Main process.\n// import './demos/node'\n\nReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(\n  <React.StrictMode>\n    <App />\n  </React.StrictMode>,\n)\n\npostMessage({ payload: 'removeLoading' }, '*')\n"
  },
  {
    "path": "src/type/electron-updater.d.ts",
    "content": "interface VersionInfo {\n  update: boolean\n  version: string\n  newVersion?: string\n}\n\ninterface ErrorType {\n  message: string\n  error: Error\n}\n"
  },
  {
    "path": "src/vite-env.d.ts",
    "content": "/// <reference types=\"vite/client\" />\n\ninterface Window {\n  // expose in the `electron/preload/index.ts`\n  ipcRenderer: import('electron').IpcRenderer\n}\n"
  },
  {
    "path": "tailwind.config.js",
    "content": "/** @type {import('tailwindcss').Config} */\nexport default {\n  content: [\n    './index.html',\n    './src/**/*.{js,ts,jsx,tsx}',\n  ],\n  theme: {\n    extend: {},\n  },\n  corePlugins: {\n    preflight: false,\n  },\n  plugins: [],\n}\n"
  },
  {
    "path": "test/e2e.spec.ts",
    "content": "import path from 'node:path'\nimport {\n  type ElectronApplication,\n  type Page,\n  type JSHandle,\n  _electron as electron,\n} from 'playwright'\nimport type { BrowserWindow } from 'electron'\nimport {\n  beforeAll,\n  afterAll,\n  describe,\n  expect,\n  test,\n} from 'vitest'\n\nconst root = path.join(__dirname, '..')\nlet electronApp: ElectronApplication\nlet page: Page\n\nif (process.platform === 'linux') {\n  // pass ubuntu\n  test(() => expect(true).true)\n} else {\n  beforeAll(async () => {\n    electronApp = await electron.launch({\n      args: ['.', '--no-sandbox'],\n      cwd: root,\n      env: { ...process.env, NODE_ENV: 'development' },\n    })\n    page = await electronApp.firstWindow()\n\n    const mainWin: JSHandle<BrowserWindow> = await electronApp.browserWindow(page)\n    await mainWin.evaluate(async (win) => {\n      win.webContents.executeJavaScript('console.log(\"Execute JavaScript with e2e testing.\")')\n    })\n  })\n\n  afterAll(async () => {\n    await page.screenshot({ path: 'test/screenshots/e2e.png' })\n    await page.close()\n    await electronApp.close()\n  })\n\n  describe('[electron-vite-react] e2e tests', async () => {\n    test('startup', async () => {\n      const title = await page.title()\n      expect(title).eq('Electron + Vite + React')\n    })\n\n    test('should be home page is load correctly', async () => {\n      const h1 = await page.$('h1')\n      const title = await h1?.textContent()\n      expect(title).eq('Electron + Vite + React')\n    })\n\n    test('should be count button can click', async () => {\n      const countButton = await page.$('button')\n      await countButton?.click()\n      const countValue = await countButton?.textContent()\n      expect(countValue).eq('count is 1')\n    })\n  })\n}\n"
  },
  {
    "path": "tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"target\": \"ESNext\",\n    \"useDefineForClassFields\": true,\n    \"lib\": [\"DOM\", \"DOM.Iterable\", \"ESNext\"],\n    \"allowJs\": false,\n    \"skipLibCheck\": true,\n    \"esModuleInterop\": false,\n    \"allowSyntheticDefaultImports\": true,\n    \"strict\": true,\n    \"forceConsistentCasingInFileNames\": true,\n    \"module\": \"ESNext\",\n    \"moduleResolution\": \"Node\",\n    \"resolveJsonModule\": true,\n    \"isolatedModules\": true,\n    \"noEmit\": true,\n    \"jsx\": \"react-jsx\",\n    \"baseUrl\": \"./\",\n    \"paths\": {\n      \"@/*\": [\n        \"src/*\"\n      ]\n    },\n  },\n  \"include\": [\"src\", \"electron\"],\n  \"references\": [{ \"path\": \"./tsconfig.node.json\" }]\n}\n"
  },
  {
    "path": "tsconfig.node.json",
    "content": "{\n  \"compilerOptions\": {\n    \"composite\": true,\n    \"module\": \"ESNext\",\n    \"moduleResolution\": \"Node\",\n    \"resolveJsonModule\": true,\n    \"allowSyntheticDefaultImports\": true\n  },\n  \"include\": [\"vite.config.ts\", \"package.json\"]\n}\n"
  },
  {
    "path": "vite.config.ts",
    "content": "import { rmSync } from 'node:fs'\nimport path from 'node:path'\nimport { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react'\nimport electron from 'vite-plugin-electron/simple'\nimport pkg from './package.json'\n\n// https://vitejs.dev/config/\nexport default defineConfig(({ command }) => {\n  rmSync('dist-electron', { recursive: true, force: true })\n\n  const isServe = command === 'serve'\n  const isBuild = command === 'build'\n  const sourcemap = isServe || !!process.env.VSCODE_DEBUG\n\n  return {\n    resolve: {\n      alias: {\n        '@': path.join(__dirname, 'src')\n      },\n    },\n    plugins: [\n      react(),\n      electron({\n        main: {\n          // Shortcut of `build.lib.entry`\n          entry: 'electron/main/index.ts',\n          onstart(args) {\n            if (process.env.VSCODE_DEBUG) {\n              console.log(/* For `.vscode/.debug.script.mjs` */'[startup] Electron App')\n            } else {\n              args.startup()\n            }\n          },\n          vite: {\n            build: {\n              sourcemap,\n              minify: isBuild,\n              outDir: 'dist-electron/main',\n              rollupOptions: {\n                external: Object.keys('dependencies' in pkg ? pkg.dependencies : {}),\n              },\n            },\n          },\n        },\n        preload: {\n          // Shortcut of `build.rollupOptions.input`.\n          // Preload scripts may contain Web assets, so use the `build.rollupOptions.input` instead `build.lib.entry`.\n          input: 'electron/preload/index.ts',\n          vite: {\n            build: {\n              sourcemap: sourcemap ? 'inline' : undefined, // #332\n              minify: isBuild,\n              outDir: 'dist-electron/preload',\n              rollupOptions: {\n                external: Object.keys('dependencies' in pkg ? pkg.dependencies : {}),\n              },\n            },\n          },\n        },\n        // Ployfill the Electron and Node.js API for Renderer process.\n        // If you want use Node.js in Renderer process, the `nodeIntegration` needs to be enabled in the Main process.\n        // See 👉 https://github.com/electron-vite/vite-plugin-electron-renderer\n        renderer: {},\n      }),\n    ],\n    server: process.env.VSCODE_DEBUG && (() => {\n      const url = new URL(pkg.debug.env.VITE_DEV_SERVER_URL)\n      return {\n        host: url.hostname,\n        port: +url.port,\n      }\n    })(),\n    clearScreen: false,\n  }\n})\n"
  },
  {
    "path": "vitest.config.ts",
    "content": "import { defineConfig } from 'vitest/config'\n\nexport default defineConfig({\n  test: {\n    root: __dirname,\n    include: ['test/**/*.{test,spec}.?(c|m)[jt]s?(x)'],\n    testTimeout: 1000 * 29,\n  },\n})\n"
  }
]