[
  {
    "path": ".github/ISSUE_TEMPLATE/config.yml",
    "content": "blank_issues_enabled: true\ncontact_links:\n  - name: 命令标签分享\n    url: https://github.com/MuiseDestiny/zotero-gpt/discussions/3\n    about: 如果你制作了一个命令标签，欢迎在这里分享给大家"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/report_bug_cn.yml",
    "content": "name: 插件问题反馈\ndescription: \"报告本插件存在的问题，且您确信这是插件问题而不是您的问题\"\n#title: \"\"\n#labels: [\"bug\"]\nbody:\n  - type: markdown\n    attributes:\n      value: |\n        感谢提交反馈！请尽可能完整填写以下信息，帮助我们更好地定位问题和快速解决问题\n        **在一切开始之前，请确保您已经阅读过 [wiki](https://github.com/MuiseDestiny/zotero-gpt/wiki) 页面**\n        即使**重启**您的`Zotero`之后，该问题依然存在\n        ------\n  - type: checkboxes\n    attributes:\n      label: 这个问题是否已有issue\n      description: 请搜索全部 issue 和 [wiki](https://github.com/MuiseDestiny/zotero-gpt/wiki) 以查看您想反馈的问题是否已存在或已解决\n      options:\n      - label: 我确认没有已有issue，且已阅读**常见问题**\n        required: true\n  - type: textarea\n    attributes:\n      label: 运行环境\n      description: |\n        请详细填写您的运行环境，以下是一个例子：\n        - **OS**: Windows11 22H2\n        - **Zotero version**: 6.0.23\n        - **Plugin version**: 0.2.3\n      value: |\n        - **OS**: \n        - **Zotero version**: \n        - **Plugin version**: \n    validations:\n      required: true\n  - type: textarea\n    attributes:\n      label: 当前配置信息\n      description: 如果能打开插件，请执行 `/report` 命令，将输出的信息**左键双击**复制粘贴到这里\n      placeholder: |\n        `api` https://api.openai.com\n        `secretKey` sk-...D6vr\n        `model` gpt-3.5-turbo\n        `temperature` 1.0\n    validations:\n      required: false\n  - type: textarea\n    id: what-happened\n    attributes:\n      label: 问题详情\n      description: 请详细描述您遇到的问题。提示：如果可以，也请提供错误的截图\n      placeholder: |\n        描述您遇到的问题\n        说明您的预期结果和实际结果之间的差异\n    validations:\n      required: true\n  - type: textarea\n    attributes:\n      label: 补充说明\n      description: 链接？参考资料？任何更多背景信息！\n      placeholder: |\n        该问题是偶然发生的还是可以稳定复现？\n        是否与不同的Paper或PDF文件有关？"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/report_bug_en.yml",
    "content": "name: Plugin Issue Report\ndescription: \"Report issues with this plugin, and you believe that it is a plugin issue rather than your own issue\"\nbody:\n  - type: markdown\n    attributes:\n      value: |\n        Thank you for submitting feedback! Please fill in the information below as completely as possible to help us better locate the issue and resolve it quickly.\n        **Before everything starts, make sure you have read the [wiki](https://github.com/MuiseDestiny/zotero-gpt/wiki) page**\n        Even after **restarting** your `Zotero`, the issue still persists\n        ------\n  - type: checkboxes\n    attributes:\n      label: Has this issue been reported before?\n      description: Please search all issues and the [wiki](https://github.com/MuiseDestiny/zotero-gpt/wiki) to see if the issue you want to report already exists or has been resolved\n      options:\n      - label: I confirm that there is no existing issue, and I have read the **FAQ**\n        required: true\n  - type: textarea\n    attributes:\n      label: Operating Environment\n      description: |\n        Please provide detailed information about your environment, here is an example:\n        - **OS**: Windows11 22H2\n        - **Zotero version**: 6.0.23\n        - **Plugin version**: 0.2.3\n      value: |\n        - **OS**: \n        - **Zotero version**: \n        - **Plugin version**: \n    validations:\n      required: true\n  - type: textarea\n    attributes:\n      label: Current Configuration Information\n      description: If you can open the plugin, please run the `/report` command, and **double-click** to copy and paste the output here\n      placeholder: |\n        `api` https://api.openai.com\n        `secretKey` sk-...D6vr\n        `model` gpt-3.5-turbo\n        `temperature` 1.0\n    validations:\n      required: false\n  - type: textarea\n    id: what-happened\n    attributes:\n      label: Issue Details\n      description: Please provide a detailed description of the issue you encountered. If possible, please also provide a screenshot of the error\n      placeholder: |\n        Describe the issue you encountered\n        Explain the difference between your expected results and the actual results\n    validations:\n      required: true\n  - type: textarea\n    attributes:\n      label: Additional Information\n      description: Links? References? Any more background information!\n      placeholder: |\n        Is the issue occurring randomly or can it be reproduced?\n        Is it related to different Papers or PDF files?"
  },
  {
    "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://docs.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: \"weekly\"\n"
  },
  {
    "path": ".github/workflows/manual.yml",
    "content": "name: Manual Trigger\n\npermissions: write-all\n\non:\n  # 手动触发\n  workflow_dispatch:\n    # inputs:\n    #   logLevel:\n    #     description: 'Log level'\n    #     required: true\n    #     default: 'warning'\n    #     type: choice\n    #     options:\n    #     - info\n    #     - warning\n    #     - debug\n\n\njobs:\n  release:\n    runs-on: ubuntu-latest\n    steps:\n      - name: Checkout\n        uses: actions/checkout@v3\n        with:\n          repository: ${{github.repository}}.wiki\n          path: wiki\n      - name: Update wiki\n        run: |\n          cd wiki\n          mkdir -p versions\n          export releases=$(curl -L \\\n            -H \"Authorization: Bearer ${{ secrets.GITHUB_TOKEN }}\" \\\n            -H \"Accept: application/vnd.github+json\" \\\n            -H \"X-GitHub-Api-Version: 2022-11-28\" \\\n            \"https://api.github.com/repos/${GITHUB_REPOSITORY}/releases?per_page=100\" \\\n          )\n          result=$(echo \"${releases}\" \\\n            | awk -vRS='\"' '!(NR%2){gsub(/\\n/, \"\\\\\\\\n\"); gsub(/\\r/, \"\\\\\\\\r\")} {printf(\"%s%s\", $0, RT)}' \\\n          )\n          echo \"$result\" | jq -c '.[]' | while read -r release; do \n            draft=$(echo \"$release\" | jq -r '.draft')\n            prerelease=$(echo \"$release\" | jq -r '.prerelease')\n            if [ \"$draft\" == 'false' ] && [ \"$prerelease\" == 'false' ]; then\n              tag_name=$(echo \"$release\" | jq -r '.tag_name')\n              MAJOR_VERSION=$(echo ${tag_name} | cut -d. -f1)\n              MINOR_VERSION=$(echo ${tag_name} | cut -d. -f2)\n              dir_name=versions/${MAJOR_VERSION}.${MINOR_VERSION}\n              mkdir -p ${dir_name}\n              name=${dir_name}/${tag_name}.bk\n              if [ ! -f \"${name}\" ]; then\n                title=$(echo \"$release\" | jq -r '.name')\n                body=$(echo \"$release\" | jq -r '.body')\n                echo -e \"## ${title}  \\n${body}\" > ${name}\n                echo \"file created: ${name}\"\n              else\n                echo \"file exists: ${name}\"\n              fi\n            else\n              echo \"draft: $draft, prerelease: $prerelease\"\n            fi\n          done\n          # generate CHANGELOG.md\n          # get all files start with v recrusive, and sort by version\n          echo -e \"\" > CHANGELOG.md\n          export files=$(find versions -name \"*\" -type f | sort -r)\n          for file in ${files}; do\n            t=$(basename ${file})\n            echo -e \"# ${t%.*}  \\n\" >> CHANGELOG.md\n            cat ${file} >> CHANGELOG.md\n            echo -e \"\\n\\n\\n  \" >> CHANGELOG.md\n          done\n          cat CHANGELOG.md\n          ls -alhR -I .git\n          # commit and push\n          # check if there is any change\n          if [ -z \"$(git status --porcelain)\" ]; then\n            echo \"No changes to commit\"\n            exit 0\n          fi\n          git config user.name github-actions\n          git config user.email github-actions@github.com\n          git add .\n          git commit -m \"Update wiki for ${tag_name}\"\n          git push"
  },
  {
    "path": ".github/workflows/publish_wiki_tags.yml",
    "content": "name: Publish wiki tags\n\npermissions: write-all\n\non:\n  push:\n    branches:\n      - bootstrap\n    paths:\n      - 'tags/*.txt'\n\njobs:\n  release:\n    runs-on: ubuntu-latest\n    steps:\n      - name: Checkout repo\n        uses: actions/checkout@v3\n        with:\n          repository: ${{github.repository}}\n          path: repo\n      - name: Checkout wiki\n        uses: actions/checkout@v3\n        with:\n          repository: ${{github.repository}}.wiki\n          path: wiki\n      - name: Update wiki\n        run: |\n          rm -rf wiki/labels\n          mkdir -p wiki/labels\n          cp -r repo/tags/*.txt wiki/labels/\n          cd wiki/labels\n          export files=$(find . -name \"*.txt\" -type f | sort -r)\n          for file in ${files}; do\n            t=$(basename ${file})\n            # echo \"<pre>\" > ${t%.*}.md\n            cat ${file} > ${t%.*}.md\n            # echo \"</pre>\" >> ${t%.*}.md\n          done\n          rm -rf *.txt\n          cd ../\n          ls -alhR -I .git\n          if [ -z \"$(git status --porcelain)\" ]; then\n            echo \"No changes to commit\"\n            exit 0\n          fi\n          git config user.name github-actions\n          git config user.email github-actions@github.com\n          git add .\n          git commit -m \"Update wiki from ${{github.repository}}\"\n          git push\n"
  },
  {
    "path": ".github/workflows/wiki.yml",
    "content": "name: Release Trigger\n\n# https://docs.github.com/en/actions/using-jobs/assigning-permissions-to-jobs#overview\npermissions: write-all\n\non:\n  # 通过Event API触发\n  release:\n    types: [released, edited]\n\n\njobs:\n  release:\n    runs-on: ubuntu-latest\n    steps:\n      - name: Checkout\n        uses: actions/checkout@v3\n        with:\n          repository: ${{github.repository}}.wiki\n          path: wiki\n      - name: Dump GitHub context\n        env:\n          GITHUB_CONTEXT: ${{ toJson(github) }}\n        run: |\n          echo \"$GITHUB_CONTEXT\"\n      - name: Check release\n        id: check_release\n        run: |\n          if [ ${{ github.event.release.draft }} == 'false' ] && [ ${{ github.event.release.prerelease }} == 'false' ]; then\n            echo \"next=true\" >> $GITHUB_ENV\n          else\n            echo \"next=false\" >> $GITHUB_ENV\n          fi\n      - name: Update wiki\n        if: ${{ env.next }}\n        run: |\n          cd wiki\n          mkdir -p versions\n          export tag_name=${{ github.event.release.tag_name }}\n          export body=\"${{ github.event.release.body }}\"\n          export title=\"${{ github.event.release.name }}\"\n          export MAJOR_VERSION=$(echo ${tag_name} | cut -d. -f1)\n          export MINOR_VERSION=$(echo ${tag_name} | cut -d. -f2)\n          export dir_name=versions/${MAJOR_VERSION}.${MINOR_VERSION}\n          # generate certain version wiki\n          mkdir -p ${dir_name}\n          export name=${dir_name}/${tag_name}.bk\n          echo -e \"## ${title}  \\n${body}\" > ${name}\n          # generate CHANGELOG.md\n          # get all files start with v recrusive, and sort by version\n          echo -e \"\" > CHANGELOG.md\n          export files=$(find versions -name \"*\" -type f | sort -r)\n          for file in ${files}; do\n            t=$(basename ${file})\n            echo -e \"# ${t%.*}  \\n\" >> CHANGELOG.md\n            cat ${file} >> CHANGELOG.md\n            echo -e \"\\n\\n\\n  \" >> CHANGELOG.md\n          done\n          ls -alhR -I .git\n          # commit and push\n          # check if there is any change\n          if [ -z \"$(git status --porcelain)\" ]; then\n            echo \"No changes to commit\"\n            exit 0\n          fi\n          git config user.name github-actions\n          git config user.email github-actions@github.com\n          git add .\n          git commit -m \"Update wiki for ${tag_name}\"\n          git push"
  },
  {
    "path": ".gitignore",
    "content": "**/builds\nnode_modules\npackage-lock.json\nzotero-cmd.json\nREADME.md\n.env\n**/test"
  },
  {
    "path": ".release-it.json",
    "content": "{\n  \"npm\": {\n    \"publish\": false\n  },\n  \"github\": {\n    \"release\": true,\n    \"assets\": [\"builds/*.xpi\"]\n  },\n  \"hooks\": {\n    \"after:bump\": \"npm run build\",\n    \"after:release\": \"echo Successfully released ${name} v${version} to ${repo.repository}.\"\n  }\n}\n"
  },
  {
    "path": ".vscode/launch.json",
    "content": "{\n    // 使用 IntelliSense 了解相关属性。 \n    // 悬停以查看现有属性的描述。\n    // 欲了解更多信息，请访问: https://go.microsoft.com/fwlink/?linkid=830387\n    \"version\": \"0.2.0\",\n    \"configurations\": [\n        {\n            \"type\": \"node\",\n            \"request\": \"launch\",\n            \"name\": \"Restart\",\n            \"runtimeExecutable\": \"npm\",\n            \"runtimeArgs\": [\n                \"run\",\n                \"restart\"\n            ],\n        },\n        {\n            \"type\": \"node\",\n            \"request\": \"launch\",\n            \"name\": \"Restart in Prod Mode\",\n            \"runtimeExecutable\": \"npm\",\n            \"runtimeArgs\": [\n                \"run\",\n                \"restart-prod\"\n            ],\n        }\n    ]\n}"
  },
  {
    "path": ".vscode/toolkit.code-snippets",
    "content": "{\n    \"appendElement - full\": {\n        \"scope\": \"javascript,typescript\",\n        \"prefix\": \"appendElement\",\n        \"body\": [\n            \"appendElement({\",\n            \"\\ttag: '${1:div}',\",\n            \"\\tid: '${2:id}',\",\n            \"\\tnamespace: '${3:html}',\",\n            \"\\tclassList: ['${4:class}'],\",\n            \"\\tstyles: {${5:style}: '$6'},\",\n            \"\\tproperties: {},\",\n            \"\\tattributes: {},\",\n            \"\\t[{ '${7:onload}', (e: Event) => $8, ${9:false} }],\",\n            \"\\tcheckExistanceParent: ${10:HTMLElement},\",\n            \"\\tignoreIfExists: ${11:true},\",\n            \"\\tskipIfExists: ${12:true},\",\n            \"\\tremoveIfExists: ${13:true},\",\n            \"\\tcustomCheck: (doc: Document, options: ElementOptions) => ${14:true},\",\n            \"\\tchildren: [$15]\",\n            \"}, ${16:container});\"\n        ]\n    },\n    \"appendElement - minimum\": {\n        \"scope\": \"javascript,typescript\",\n        \"prefix\": \"appendElement\",\n        \"body\": \"appendElement({ tag: '$1' }, $2);\"\n    },\n    \"register Notifier\": {\n        \"scope\": \"javascript,typescript\",\n        \"prefix\": \"registerObserver\",\n        \"body\": [\n            \"registerObserver({\",\n            \"\\t notify: (\",\n            \"\\t\\tevent: _ZoteroTypes.Notifier.Event,\",\n            \"\\t\\ttype: _ZoteroTypes.Notifier.Type,\",\n            \"\\t\\tids: string[],\",\n            \"\\t\\textraData: _ZoteroTypes.anyObj\",\n            \"\\t) => {\",\n            \"\\t\\t$0\",\n            \"\\t}\",\n            \"});\"\n        ]\n    }\n}\n"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU AFFERO GENERAL PUBLIC LICENSE\n                       Version 3, 19 November 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU Affero General Public License is a free, copyleft license for\nsoftware and other kinds of works, specifically designed to ensure\ncooperation with the community in the case of network server software.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nour General Public Licenses are intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  Developers that use our General Public Licenses protect your rights\nwith two steps: (1) assert copyright on the software, and (2) offer\nyou this License which gives you legal permission to copy, distribute\nand/or modify the software.\n\n  A secondary benefit of defending all users' freedom is that\nimprovements made in alternate versions of the program, if they\nreceive widespread use, become available for other developers to\nincorporate.  Many developers of free software are heartened and\nencouraged by the resulting cooperation.  However, in the case of\nsoftware used on network servers, this result may fail to come about.\nThe GNU General Public License permits making a modified version and\nletting the public access it on a server without ever releasing its\nsource code to the public.\n\n  The GNU Affero General Public License is designed specifically to\nensure that, in such cases, the modified source code becomes available\nto the community.  It requires the operator of a network server to\nprovide the source code of the modified version running there to the\nusers of that server.  Therefore, public use of a modified version, on\na publicly accessible server, gives the public access to the source\ncode of the modified version.\n\n  An older license, called the Affero General Public License and\npublished by Affero, was designed to accomplish similar goals.  This is\na different license, not a version of the Affero GPL, but Affero has\nreleased a new version of the Affero GPL which permits relicensing under\nthis license.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU Affero General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Remote Network Interaction; Use with the GNU General Public License.\n\n  Notwithstanding any other provision of this License, if you modify the\nProgram, your modified version must prominently offer all users\ninteracting with it remotely through a computer network (if your version\nsupports such interaction) an opportunity to receive the Corresponding\nSource of your version by providing access to the Corresponding Source\nfrom a network server at no charge, through some standard or customary\nmeans of facilitating copying of software.  This Corresponding Source\nshall include the Corresponding Source for any work covered by version 3\nof the GNU General Public License that is incorporated pursuant to the\nfollowing paragraph.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the work with which it is combined will remain governed by version\n3 of the GNU General Public License.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU Affero General Public License from time to time.  Such new versions\nwill be similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU Affero General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU Affero General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU Affero General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU Affero General Public License as published\n    by the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU Affero General Public License for more details.\n\n    You should have received a copy of the GNU Affero General Public License\n    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If your software can interact with users remotely through a computer\nnetwork, you should also make sure that it provides a way for users to\nget its source.  For example, if your program is a web application, its\ninterface could display a \"Source\" link that leads users to an archive\nof the code.  There are many ways you could offer source, and different\nsolutions will be better for different programs; see section 13 for the\nspecific requirements.\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU AGPL, see\n<http://www.gnu.org/licenses/>.\n"
  },
  {
    "path": "addon/bootstrap.js",
    "content": "/**\n * Most of this code is from Zotero team's official Make It Red example[1]\n * or the Zotero 7 documentation[2].\n * [1] https://github.com/zotero/make-it-red\n * [2] https://www.zotero.org/support/dev/zotero_7_for_developers\n */\n\nif (typeof Zotero == \"undefined\") {\n  var Zotero;\n}\n\nvar chromeHandle;\n\n// In Zotero 6, bootstrap methods are called before Zotero is initialized, and using include.js\n// to get the Zotero XPCOM service would risk breaking Zotero startup. Instead, wait for the main\n// Zotero window to open and get the Zotero object from there.\n//\n// In Zotero 7, bootstrap methods are not called until Zotero is initialized, and the 'Zotero' is\n// automatically made available.\nasync function waitForZotero() {\n  if (typeof Zotero != \"undefined\") {\n    await Zotero.initializationPromise;\n  }\n\n  var { Services } = ChromeUtils.import(\"resource://gre/modules/Services.jsm\");\n  var windows = Services.wm.getEnumerator(\"navigator:browser\");\n  var found = false;\n  while (windows.hasMoreElements()) {\n    let win = windows.getNext();\n    if (win.Zotero) {\n      Zotero = win.Zotero;\n      found = true;\n      break;\n    }\n  }\n  if (!found) {\n    await new Promise((resolve) => {\n      var listener = {\n        onOpenWindow: function (aWindow) {\n          // Wait for the window to finish loading\n          let domWindow = aWindow\n            .QueryInterface(Ci.nsIInterfaceRequestor)\n            .getInterface(Ci.nsIDOMWindowInternal || Ci.nsIDOMWindow);\n          domWindow.addEventListener(\n            \"load\",\n            function () {\n              domWindow.removeEventListener(\"load\", arguments.callee, false);\n              if (domWindow.Zotero) {\n                Services.wm.removeListener(listener);\n                Zotero = domWindow.Zotero;\n                resolve();\n              }\n            },\n            false\n          );\n        },\n      };\n      Services.wm.addListener(listener);\n    });\n  }\n  await Zotero.initializationPromise;\n}\n\nfunction install(data, reason) {}\n\nasync function startup({ id, version, resourceURI, rootURI }, reason) {\n  await waitForZotero();\n\n  // String 'rootURI' introduced in Zotero 7\n  if (!rootURI) {\n    rootURI = resourceURI.spec;\n  }\n\n  if (Zotero.platformMajorVersion >= 102) {\n    var aomStartup = Components.classes[\n      \"@mozilla.org/addons/addon-manager-startup;1\"\n    ].getService(Components.interfaces.amIAddonManagerStartup);\n    var manifestURI = Services.io.newURI(rootURI + \"manifest.json\");\n    chromeHandle = aomStartup.registerChrome(manifestURI, [\n      [\"content\", \"__addonRef__\", rootURI + \"chrome/content/\"],\n      [\"locale\", \"__addonRef__\", \"en-US\", rootURI + \"chrome/locale/en-US/\"],\n      [\"locale\", \"__addonRef__\", \"zh-CN\", rootURI + \"chrome/locale/zh-CN/\"],\n    ]);\n  } else {\n    setDefaultPrefs(rootURI);\n  }\n\n  /**\n   * Global variables for plugin code.\n   * The `_globalThis` is the global root variable of the plugin sandbox environment\n   * and all child variables assigned to it is globally accessible.\n   * See `src/index.ts` for details.\n   */\n  const ctx = {\n    rootURI,\n  };\n  ctx._globalThis = ctx;\n\n  Services.scriptloader.loadSubScript(\n    `${rootURI}/chrome/content/scripts/index.js`,\n    ctx\n  );\n}\n\nfunction shutdown({ id, version, resourceURI, rootURI }, reason) {\n  if (reason === APP_SHUTDOWN) {\n    return;\n  }\n  if (typeof Zotero === \"undefined\") {\n    Zotero = Components.classes[\"@zotero.org/Zotero;1\"].getService(\n      Components.interfaces.nsISupports\n    ).wrappedJSObject;\n  }\n  Zotero.__addonInstance__.hooks.onShutdown();\n\n  Cc[\"@mozilla.org/intl/stringbundle;1\"]\n    .getService(Components.interfaces.nsIStringBundleService)\n    .flushBundles();\n\n  Cu.unload(`${rootURI}/chrome/content/scripts/index.js`);\n\n  if (chromeHandle) {\n    chromeHandle.destruct();\n    chromeHandle = null;\n  }\n}\n\nfunction uninstall(data, reason) {}\n\n// Loads default preferences from defaults/preferences/prefs.js in Zotero 6\nfunction setDefaultPrefs(rootURI) {\n  var branch = Services.prefs.getDefaultBranch(\"\");\n  var obj = {\n    pref(pref, value) {\n      switch (typeof value) {\n        case \"boolean\":\n          branch.setBoolPref(pref, value);\n          break;\n        case \"string\":\n          branch.setStringPref(pref, value);\n          break;\n        case \"number\":\n          branch.setIntPref(pref, value);\n          break;\n        default:\n          Zotero.logError(`Invalid type '${typeof value}' for pref '${pref}'`);\n      }\n    },\n  };\n  Zotero.getMainWindow().console.log(rootURI + \"prefs.js\");\n  Services.scriptloader.loadSubScript(rootURI + \"prefs.js\", obj);\n}\n"
  },
  {
    "path": "addon/chrome/content/md.css",
    "content": ".markdown-body {\n    --color-prettylights-syntax-comment: #6e7781;\n    --color-prettylights-syntax-constant: #0550ae;\n    --color-prettylights-syntax-entity: #8250df;\n    --color-prettylights-syntax-storage-modifier-import: #24292f;\n    --color-prettylights-syntax-entity-tag: #116329;\n    --color-prettylights-syntax-keyword: #cf222e;\n    --color-prettylights-syntax-string: #0a3069;\n    --color-prettylights-syntax-variable: #953800;\n    --color-prettylights-syntax-brackethighlighter-unmatched: #82071e;\n    --color-prettylights-syntax-invalid-illegal-text: #f6f8fa;\n    --color-prettylights-syntax-invalid-illegal-bg: #82071e;\n    --color-prettylights-syntax-carriage-return-text: #f6f8fa;\n    --color-prettylights-syntax-carriage-return-bg: #cf222e;\n    --color-prettylights-syntax-string-regexp: #116329;\n    --color-prettylights-syntax-markup-list: #3b2300;\n    --color-prettylights-syntax-markup-heading: #0550ae;\n    --color-prettylights-syntax-markup-italic: #24292f;\n    --color-prettylights-syntax-markup-bold: #24292f;\n    --color-prettylights-syntax-markup-deleted-text: #82071e;\n    --color-prettylights-syntax-markup-deleted-bg: #ffebe9;\n    --color-prettylights-syntax-markup-inserted-text: #116329;\n    --color-prettylights-syntax-markup-inserted-bg: #dafbe1;\n    --color-prettylights-syntax-markup-changed-text: #953800;\n    --color-prettylights-syntax-markup-changed-bg: #ffd8b5;\n    --color-prettylights-syntax-markup-ignored-text: #eaeef2;\n    --color-prettylights-syntax-markup-ignored-bg: #0550ae;\n    --color-prettylights-syntax-meta-diff-range: #8250df;\n    --color-prettylights-syntax-brackethighlighter-angle: #57606a;\n    --color-prettylights-syntax-sublimelinter-gutter-mark: #8c959f;\n    --color-prettylights-syntax-constant-other-reference-link: #0a3069;\n    --color-fg-default: #24292f;\n    --color-fg-muted: #57606a;\n    --color-fg-subtle: #6e7781;\n    --color-canvas-default: transparent;\n    --color-canvas-subtle: rgba(89, 192, 188, .1);\n    --color-border-default: #d0d7de;\n    --color-border-muted: rgba(89, 192, 188, .2);\n    --color-neutral-muted: rgba(89, 192, 188, .2);\n    --color-accent-fg: #0969da;\n    --color-accent-emphasis: #0969da;\n    --color-attention-subtle: #fff8c5;\n    --color-danger-fg: #cf222e\n}\n\n.markdown-body {\n    -ms-text-size-adjust: 100%;\n    -webkit-text-size-adjust: 100%;\n    margin: 0;\n    color: var(--color-fg-default);\n    background-color: var(--color-canvas-default);\n    font-family: -apple-system, BlinkMacSystemFont, segoe ui, noto sans, Helvetica, Arial, sans-serif, apple color emoji, segoe ui emoji;\n    font-size: 16px;\n    line-height: 1.5;\n    word-wrap: break-word\n}\n\n.markdown-body .octicon {\n    display: inline-block;\n    fill: currentColor;\n    vertical-align: text-bottom\n}\n\n.markdown-body h1:hover .anchor .octicon-link:before,\n.markdown-body h2:hover .anchor .octicon-link:before,\n.markdown-body h3:hover .anchor .octicon-link:before,\n.markdown-body h4:hover .anchor .octicon-link:before,\n.markdown-body h5:hover .anchor .octicon-link:before,\n.markdown-body h6:hover .anchor .octicon-link:before {\n    width: 16px;\n    height: 16px;\n    content: ' ';\n    display: inline-block;\n    background-color: currentColor;\n    -webkit-mask-image: url(data:image/svg+xml;base64,PHN2ZyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHZpZXdCb3g9JzAgMCAxNiAxNicgdmVyc2lvbj0nMS4xJyBhcmlhLWhpZGRlbj0ndHJ1ZSc+PHBhdGggZmlsbC1ydWxlPSdldmVub2RkJyBkPSdNNy43NzUgMy4yNzVhLjc1Ljc1IDAgMDAxLjA2IDEuMDZsMS4yNS0xLjI1YTIgMiAwIDExMi44MyAyLjgzbC0yLjUgMi41YTIgMiAwIDAxLTIuODMgMCAuNzUuNzUgMCAwMC0xLjA2IDEuMDYgMy41IDMuNSAwIDAwNC45NSAwbDIuNS0yLjVhMy41IDMuNSAwIDAwLTQuOTUtNC45NWwtMS4yNSAxLjI1em0tNC42OSA5LjY0YTIgMiAwIDAxMC0yLjgzbDIuNS0yLjVhMiAyIDAgMDEyLjgzIDAgLjc1Ljc1IDAgMDAxLjA2LTEuMDYgMy41IDMuNSAwIDAwLTQuOTUgMGwtMi41IDIuNWEzLjUgMy41IDAgMDA0Ljk1IDQuOTVsMS4yNS0xLjI1YS43NS43NSAwIDAwLTEuMDYtMS4wNmwtMS4yNSAxLjI1YTIgMiAwIDAxLTIuODMgMHonPjwvcGF0aD48L3N2Zz4=);\n    mask-image: url(data:image/svg+xml;base64,PHN2ZyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHZpZXdCb3g9JzAgMCAxNiAxNicgdmVyc2lvbj0nMS4xJyBhcmlhLWhpZGRlbj0ndHJ1ZSc+PHBhdGggZmlsbC1ydWxlPSdldmVub2RkJyBkPSdNNy43NzUgMy4yNzVhLjc1Ljc1IDAgMDAxLjA2IDEuMDZsMS4yNS0xLjI1YTIgMiAwIDExMi44MyAyLjgzbC0yLjUgMi41YTIgMiAwIDAxLTIuODMgMCAuNzUuNzUgMCAwMC0xLjA2IDEuMDYgMy41IDMuNSAwIDAwNC45NSAwbDIuNS0yLjVhMy41IDMuNSAwIDAwLTQuOTUtNC45NWwtMS4yNSAxLjI1em0tNC42OSA5LjY0YTIgMiAwIDAxMC0yLjgzbDIuNS0yLjVhMiAyIDAgMDEyLjgzIDAgLjc1Ljc1IDAgMDAxLjA2LTEuMDYgMy41IDMuNSAwIDAwLTQuOTUgMGwtMi41IDIuNWEzLjUgMy41IDAgMDA0Ljk1IDQuOTVsMS4yNS0xLjI1YS43NS43NSAwIDAwLTEuMDYtMS4wNmwtMS4yNSAxLjI1YTIgMiAwIDAxLTIuODMgMHonPjwvcGF0aD48L3N2Zz4=)\n}\n\n.markdown-body details,\n.markdown-body figcaption,\n.markdown-body figure {\n    display: block\n}\n\n.markdown-body summary {\n    display: list-item\n}\n\n.markdown-body [hidden] {\n    display: none !important\n}\n\n.markdown-body a {\n    background-color: transparent;\n    color: var(--color-accent-fg);\n    text-decoration: none\n}\n\n.markdown-body abbr[title] {\n    border-bottom: none;\n    text-decoration: underline dotted\n}\n\n.markdown-body b,\n.markdown-body strong {\n    font-weight: var(--base-text-weight-semibold, 600)\n}\n\n.markdown-body dfn {\n    font-style: italic\n}\n\n.markdown-body h1 {\n    margin: .67em 0;\n    font-weight: var(--base-text-weight-semibold, 600);\n    padding-bottom: .3em;\n    font-size: 2em;\n    border-bottom: 1px solid var(--color-border-muted)\n}\n\n.markdown-body mark {\n    background-color: var(--color-attention-subtle);\n    color: var(--color-fg-default)\n}\n\n.markdown-body small {\n    font-size: 90%\n}\n\n.markdown-body sub,\n.markdown-body sup {\n    font-size: 75%;\n    line-height: 0;\n    position: relative;\n    vertical-align: baseline\n}\n\n.markdown-body sub {\n    bottom: -.25em\n}\n\n.markdown-body sup {\n    top: -.5em\n}\n\n.markdown-body img {\n    border-style: none;\n    max-width: 100%;\n    box-sizing: content-box;\n    background-color: var(--color-canvas-default)\n}\n\n.markdown-body code,\n.markdown-body kbd,\n.markdown-body pre,\n.markdown-body samp {\n    font-family: monospace;\n    font-size: 1em\n}\n\n.markdown-body figure {\n    margin: 1em 40px\n}\n\n.markdown-body hr {\n    box-sizing: content-box;\n    overflow: hidden;\n    background: 0 0;\n    border-bottom: 1px solid var(--color-border-muted);\n    height: .25em;\n    padding: 0;\n    margin: 24px 0;\n    background-color: var(--color-border-default);\n    border: 0\n}\n\n.markdown-body input {\n    font: inherit;\n    margin: 0;\n    overflow: visible;\n    font-family: inherit;\n    font-size: inherit;\n    line-height: inherit\n}\n\n.markdown-body [type=button],\n.markdown-body [type=reset],\n.markdown-body [type=submit] {\n    -webkit-appearance: button\n}\n\n.markdown-body [type=checkbox],\n.markdown-body [type=radio] {\n    box-sizing: border-box;\n    padding: 0\n}\n\n.markdown-body [type=number]::-webkit-inner-spin-button,\n.markdown-body [type=number]::-webkit-outer-spin-button {\n    height: auto\n}\n\n.markdown-body [type=search]::-webkit-search-cancel-button,\n.markdown-body [type=search]::-webkit-search-decoration {\n    -webkit-appearance: none\n}\n\n.markdown-body ::-webkit-input-placeholder {\n    color: inherit;\n    opacity: .54\n}\n\n.markdown-body ::-webkit-file-upload-button {\n    -webkit-appearance: button;\n    font: inherit\n}\n\n.markdown-body a:hover {\n    text-decoration: underline\n}\n\n.markdown-body ::placeholder {\n    color: var(--color-fg-subtle);\n    opacity: 1\n}\n\n.markdown-body hr::before {\n    display: table;\n    content: \"\"\n}\n\n.markdown-body hr::after {\n    display: table;\n    clear: both;\n    content: \"\"\n}\n\n.markdown-body table {\n    border-spacing: 0;\n    border-collapse: collapse;\n    display: block;\n    width: max-content;\n    max-width: 100%;\n    overflow: auto;\n}\n\n.markdown-body td,\n.markdown-body th {\n    padding: 0\n}\n\n.markdown-body details summary {\n    cursor: pointer\n}\n\n.markdown-body details:not([open])>*:not(summary) {\n    display: none !important\n}\n\n.markdown-body a:focus,\n.markdown-body [role=button]:focus,\n.markdown-body input[type=radio]:focus,\n.markdown-body input[type=checkbox]:focus {\n    outline: 2px solid var(--color-accent-fg);\n    outline-offset: -2px;\n    box-shadow: none\n}\n\n.markdown-body a:focus:not(:focus-visible),\n.markdown-body [role=button]:focus:not(:focus-visible),\n.markdown-body input[type=radio]:focus:not(:focus-visible),\n.markdown-body input[type=checkbox]:focus:not(:focus-visible) {\n    outline: solid 1px transparent\n}\n\n.markdown-body a:focus-visible,\n.markdown-body [role=button]:focus-visible,\n.markdown-body input[type=radio]:focus-visible,\n.markdown-body input[type=checkbox]:focus-visible {\n    outline: 2px solid var(--color-accent-fg);\n    outline-offset: -2px;\n    box-shadow: none\n}\n\n.markdown-body a:not([class]):focus,\n.markdown-body a:not([class]):focus-visible,\n.markdown-body input[type=radio]:focus,\n.markdown-body input[type=radio]:focus-visible,\n.markdown-body input[type=checkbox]:focus,\n.markdown-body input[type=checkbox]:focus-visible {\n    outline-offset: 0\n}\n\n.markdown-body kbd {\n    display: inline-block;\n    padding: 3px 5px;\n    font: 11px ui-monospace, SFMono-Regular, SF Mono, Menlo, Consolas, Liberation Mono, monospace;\n    line-height: 10px;\n    color: var(--color-fg-default);\n    vertical-align: middle;\n    background-color: var(--color-canvas-subtle);\n    border: solid 1px var(--color-neutral-muted);\n    border-bottom-color: var(--color-neutral-muted);\n    border-radius: 6px;\n    box-shadow: inset 0 -1px 0 var(--color-neutral-muted)\n}\n\n.markdown-body h1,\n.markdown-body h2,\n.markdown-body h3,\n.markdown-body h4,\n.markdown-body h5,\n.markdown-body h6 {\n    margin-top: 24px;\n    margin-bottom: 16px;\n    font-weight: var(--base-text-weight-semibold, 600);\n    line-height: 1.25\n}\n\n.markdown-body h2 {\n    font-weight: var(--base-text-weight-semibold, 600);\n    padding-bottom: .3em;\n    font-size: 1.5em;\n    border-bottom: 1px solid var(--color-border-muted)\n}\n\n.markdown-body h3 {\n    font-weight: var(--base-text-weight-semibold, 600);\n    font-size: 1.25em\n}\n\n.markdown-body h4 {\n    font-weight: var(--base-text-weight-semibold, 600);\n    font-size: 1em\n}\n\n.markdown-body h5 {\n    font-weight: var(--base-text-weight-semibold, 600);\n    font-size: .875em\n}\n\n.markdown-body h6 {\n    font-weight: var(--base-text-weight-semibold, 600);\n    font-size: .85em;\n    color: var(--color-fg-muted)\n}\n\n.markdown-body p {\n    margin-top: 0;\n    margin-bottom: 10px\n}\n\n.markdown-body blockquote {\n    margin: 0;\n    padding: 0 1em;\n    color: var(--color-fg-muted);\n    border-left: .25em solid var(--color-border-default)\n}\n\n.markdown-body ul,\n.markdown-body ol {\n    margin-top: 0;\n    margin-bottom: 0;\n    padding-left: 2em\n}\n\n.markdown-body ol ol,\n.markdown-body ul ol {\n    list-style-type: lower-roman\n}\n\n.markdown-body ul ul ol,\n.markdown-body ul ol ol,\n.markdown-body ol ul ol,\n.markdown-body ol ol ol {\n    list-style-type: lower-alpha\n}\n\n.markdown-body dd {\n    margin-left: 0\n}\n\n.markdown-body tt,\n.markdown-body code,\n.markdown-body samp {\n    font-family: ui-monospace, SFMono-Regular, SF Mono, Menlo, Consolas, Liberation Mono, monospace;\n    font-size: 12px\n}\n\n.markdown-body pre {\n    margin-top: 0;\n    margin-bottom: 0;\n    font-family: ui-monospace, SFMono-Regular, SF Mono, Menlo, Consolas, Liberation Mono, monospace;\n    font-size: 12px;\n    word-wrap: normal\n}\n\n.markdown-body .octicon {\n    display: inline-block;\n    overflow: visible !important;\n    vertical-align: text-bottom;\n    fill: currentColor\n}\n\n.markdown-body input::-webkit-outer-spin-button,\n.markdown-body input::-webkit-inner-spin-button {\n    margin: 0;\n    -webkit-appearance: none;\n    appearance: none\n}\n\n.markdown-body::before {\n    display: table;\n    content: \"\"\n}\n\n.markdown-body::after {\n    display: table;\n    clear: both;\n    content: \"\"\n}\n\n.markdown-body>*:first-child {\n    margin-top: 0.25em !important\n}\n\n.markdown-body>*:last-child {\n    margin-bottom: 0.25em !important\n}\n\n.markdown-body a:not([href]) {\n    color: inherit;\n    text-decoration: none\n}\n\n.markdown-body .absent {\n    color: var(--color-danger-fg)\n}\n\n.markdown-body .anchor {\n    float: left;\n    padding-right: 4px;\n    margin-left: -20px;\n    line-height: 1\n}\n\n.markdown-body .anchor:focus {\n    outline: none\n}\n\n.markdown-body p,\n.markdown-body blockquote,\n.markdown-body ul,\n.markdown-body ol,\n.markdown-body dl,\n.markdown-body table,\n.markdown-body pre,\n.markdown-body details {\n    margin-top: 0;\n    margin-bottom: 16px\n}\n\n.markdown-body blockquote>:first-child {\n    margin-top: 0\n}\n\n.markdown-body blockquote>:last-child {\n    margin-bottom: 0\n}\n\n.markdown-body h1 .octicon-link,\n.markdown-body h2 .octicon-link,\n.markdown-body h3 .octicon-link,\n.markdown-body h4 .octicon-link,\n.markdown-body h5 .octicon-link,\n.markdown-body h6 .octicon-link {\n    color: var(--color-fg-default);\n    vertical-align: middle;\n    visibility: hidden\n}\n\n.markdown-body h1:hover .anchor,\n.markdown-body h2:hover .anchor,\n.markdown-body h3:hover .anchor,\n.markdown-body h4:hover .anchor,\n.markdown-body h5:hover .anchor,\n.markdown-body h6:hover .anchor {\n    text-decoration: none\n}\n\n.markdown-body h1:hover .anchor .octicon-link,\n.markdown-body h2:hover .anchor .octicon-link,\n.markdown-body h3:hover .anchor .octicon-link,\n.markdown-body h4:hover .anchor .octicon-link,\n.markdown-body h5:hover .anchor .octicon-link,\n.markdown-body h6:hover .anchor .octicon-link {\n    visibility: visible\n}\n\n.markdown-body h1 tt,\n.markdown-body h1 code,\n.markdown-body h2 tt,\n.markdown-body h2 code,\n.markdown-body h3 tt,\n.markdown-body h3 code,\n.markdown-body h4 tt,\n.markdown-body h4 code,\n.markdown-body h5 tt,\n.markdown-body h5 code,\n.markdown-body h6 tt,\n.markdown-body h6 code {\n    padding: 0 .2em;\n    font-size: inherit\n}\n\n.markdown-body summary h1,\n.markdown-body summary h2,\n.markdown-body summary h3,\n.markdown-body summary h4,\n.markdown-body summary h5,\n.markdown-body summary h6 {\n    display: inline-block\n}\n\n.markdown-body summary h1 .anchor,\n.markdown-body summary h2 .anchor,\n.markdown-body summary h3 .anchor,\n.markdown-body summary h4 .anchor,\n.markdown-body summary h5 .anchor,\n.markdown-body summary h6 .anchor {\n    margin-left: -40px\n}\n\n.markdown-body summary h1,\n.markdown-body summary h2 {\n    padding-bottom: 0;\n    border-bottom: 0\n}\n\n.markdown-body ul.no-list,\n.markdown-body ol.no-list {\n    padding: 0;\n    list-style-type: none\n}\n\n.markdown-body ol[type=a] {\n    list-style-type: lower-alpha\n}\n\n.markdown-body ol[type=A] {\n    list-style-type: upper-alpha\n}\n\n.markdown-body ol[type=i] {\n    list-style-type: lower-roman\n}\n\n.markdown-body ol[type=I] {\n    list-style-type: upper-roman\n}\n\n.markdown-body ol[type=\"1\"] {\n    list-style-type: decimal\n}\n\n.markdown-body div>ol:not([type]) {\n    list-style-type: decimal\n}\n\n.markdown-body ul ul,\n.markdown-body ul ol,\n.markdown-body ol ol,\n.markdown-body ol ul {\n    margin-top: 0;\n    margin-bottom: 0\n}\n\n.markdown-body li>p {\n    margin-top: 16px\n}\n\n.markdown-body li+li {\n    margin-top: .25em\n}\n\n.markdown-body dl {\n    padding: 0\n}\n\n.markdown-body dl dt {\n    padding: 0;\n    margin-top: 16px;\n    font-size: 1em;\n    font-style: italic;\n    font-weight: var(--base-text-weight-semibold, 600)\n}\n\n.markdown-body dl dd {\n    padding: 0 16px;\n    margin-bottom: 16px\n}\n\n.markdown-body table th {\n    font-weight: var(--base-text-weight-semibold, 600)\n}\n\n.markdown-body table th,\n.markdown-body table td {\n    padding: 6px 13px;\n    border: 1px solid var(--color-border-default)\n}\n\n.markdown-body table tr {\n    background-color: var(--color-canvas-default);\n    border-top: 1px solid var(--color-border-muted)\n}\n\n.markdown-body table tr:nth-child(2n) {\n    background-color: var(--color-canvas-subtle)\n}\n\n.markdown-body table img {\n    background-color: transparent\n}\n\n.markdown-body img[align=right] {\n    padding-left: 20px\n}\n\n.markdown-body img[align=left] {\n    padding-right: 20px\n}\n\n.markdown-body .emoji {\n    max-width: none;\n    vertical-align: text-top;\n    background-color: transparent\n}\n\n.markdown-body span.frame {\n    display: block;\n    overflow: hidden\n}\n\n.markdown-body span.frame>span {\n    display: block;\n    float: left;\n    width: auto;\n    padding: 7px;\n    margin: 13px 0 0;\n    overflow: hidden;\n    border: 1px solid var(--color-border-default)\n}\n\n.markdown-body span.frame span img {\n    display: block;\n    float: left\n}\n\n.markdown-body span.frame span span {\n    display: block;\n    padding: 5px 0 0;\n    clear: both;\n    color: var(--color-fg-default)\n}\n\n.markdown-body span.align-center {\n    display: block;\n    overflow: hidden;\n    clear: both\n}\n\n.markdown-body span.align-center>span {\n    display: block;\n    margin: 13px auto 0;\n    overflow: hidden;\n    text-align: center\n}\n\n.markdown-body span.align-center span img {\n    margin: 0 auto;\n    text-align: center\n}\n\n.markdown-body span.align-right {\n    display: block;\n    overflow: hidden;\n    clear: both\n}\n\n.markdown-body span.align-right>span {\n    display: block;\n    margin: 13px 0 0;\n    overflow: hidden;\n    text-align: right\n}\n\n.markdown-body span.align-right span img {\n    margin: 0;\n    text-align: right\n}\n\n.markdown-body span.float-left {\n    display: block;\n    float: left;\n    margin-right: 13px;\n    overflow: hidden\n}\n\n.markdown-body span.float-left span {\n    margin: 13px 0 0\n}\n\n.markdown-body span.float-right {\n    display: block;\n    float: right;\n    margin-left: 13px;\n    overflow: hidden\n}\n\n.markdown-body span.float-right>span {\n    display: block;\n    margin: 13px auto 0;\n    overflow: hidden;\n    text-align: right\n}\n\n.markdown-body code,\n.markdown-body tt {\n    padding: .2em .4em;\n    margin: 0;\n    font-size: 85%;\n    white-space: break-spaces;\n    background-color: var(--color-neutral-muted);\n    border-radius: 6px\n}\n\n.markdown-body code br,\n.markdown-body tt br {\n    display: none\n}\n\n.markdown-body del code {\n    text-decoration: inherit\n}\n\n.markdown-body samp {\n    font-size: 85%\n}\n\n.markdown-body pre code {\n    font-size: 100%\n}\n\n.markdown-body pre>code {\n    padding: 0;\n    margin: 0;\n    word-break: normal;\n    white-space: pre;\n    background: 0 0;\n    border: 0\n}\n\n.markdown-body .highlight {\n    margin-bottom: 16px\n}\n\n.markdown-body .highlight pre {\n    margin-bottom: 0;\n    word-break: normal\n}\n\n.markdown-body .highlight pre,\n.markdown-body pre {\n    padding: 16px;\n    overflow: auto;\n    font-size: 85%;\n    line-height: 1.45;\n    background-color: var(--color-canvas-subtle);\n    border-radius: 6px\n}\n\n.markdown-body pre code,\n.markdown-body pre tt {\n    display: inline;\n    max-width: auto;\n    padding: 0;\n    margin: 0;\n    overflow: visible;\n    line-height: inherit;\n    word-wrap: normal;\n    background-color: transparent;\n    border: 0\n}\n\n.markdown-body .csv-data td,\n.markdown-body .csv-data th {\n    padding: 5px;\n    overflow: hidden;\n    font-size: 12px;\n    line-height: 1;\n    text-align: left;\n    white-space: nowrap\n}\n\n.markdown-body .csv-data .blob-num {\n    padding: 10px 8px 9px;\n    text-align: right;\n    background: var(--color-canvas-default);\n    border: 0\n}\n\n.markdown-body .csv-data tr {\n    border-top: 0\n}\n\n.markdown-body .csv-data th {\n    font-weight: var(--base-text-weight-semibold, 600);\n    background: var(--color-canvas-subtle);\n    border-top: 0\n}\n\n.markdown-body [data-footnote-ref]::before {\n    content: \"[\"\n}\n@-webkit-keyframes blink {\n    to {\n        visibility: hidden;\n    }\n}\n@keyframes blink {\n    to {\n        visibility: hidden;\n    }\n}\n\n.markdown-body math {\n    display: none;\n}\n.markdown-body svg {\n    margin-left: 0.25em;\n    margin-right: 0.25em;\n}\n\n.streaming>span:after,\n.streaming>ul:last-child li:last-child:after,\n.streaming>pre:last-child code:after,\n.streaming>ol:last-child li:last-child:after,\n.streaming>:not(ol):not(ul):not(pre):last-child:after {\n    -webkit-animation: blink 1s steps(5, start) infinite !important;\n    animation: blink 1s steps(5, start) infinite !important;\n    content: \"▋\";\n    margin-left: .25rem;\n    vertical-align: baseline\n}\n\n.markdown-body [data-footnote-ref]::after {\n    content: \"]\"\n}\n\n.markdown-body .footnotes {\n    font-size: 12px;\n    color: var(--color-fg-muted);\n    border-top: 1px solid var(--color-border-default)\n}\n\n.markdown-body .footnotes ol {\n    padding-left: 16px\n}\n\n.markdown-body .footnotes ol ul {\n    display: inline-block;\n    padding-left: 16px;\n    margin-top: 16px\n}\n\n.markdown-body .footnotes li {\n    position: relative\n}\n\n.markdown-body .footnotes li:target::before {\n    position: absolute;\n    top: -8px;\n    right: -8px;\n    bottom: -8px;\n    left: -24px;\n    pointer-events: none;\n    content: \"\";\n    border: 2px solid var(--color-accent-emphasis);\n    border-radius: 6px\n}\n\n.markdown-body .footnotes li:target {\n    color: var(--color-fg-default)\n}\n\n.markdown-body .footnotes .data-footnote-backref g-emoji {\n    font-family: monospace\n}\n\n.markdown-body .pl-c {\n    color: var(--color-prettylights-syntax-comment)\n}\n\n.markdown-body .pl-c1,\n.markdown-body .pl-s .pl-v {\n    color: var(--color-prettylights-syntax-constant)\n}\n\n.markdown-body .pl-e,\n.markdown-body .pl-en {\n    color: var(--color-prettylights-syntax-entity)\n}\n\n.markdown-body .pl-smi,\n.markdown-body .pl-s .pl-s1 {\n    color: var(--color-prettylights-syntax-storage-modifier-import)\n}\n\n.markdown-body .pl-ent {\n    color: var(--color-prettylights-syntax-entity-tag)\n}\n\n.markdown-body .pl-k {\n    color: var(--color-prettylights-syntax-keyword)\n}\n\n.markdown-body .pl-s,\n.markdown-body .pl-pds,\n.markdown-body .pl-s .pl-pse .pl-s1,\n.markdown-body .pl-sr,\n.markdown-body .pl-sr .pl-cce,\n.markdown-body .pl-sr .pl-sre,\n.markdown-body .pl-sr .pl-sra {\n    color: var(--color-prettylights-syntax-string)\n}\n\n.markdown-body .pl-v,\n.markdown-body .pl-smw {\n    color: var(--color-prettylights-syntax-variable)\n}\n\n.markdown-body .pl-bu {\n    color: var(--color-prettylights-syntax-brackethighlighter-unmatched)\n}\n\n.markdown-body .pl-ii {\n    color: var(--color-prettylights-syntax-invalid-illegal-text);\n    background-color: var(--color-prettylights-syntax-invalid-illegal-bg)\n}\n\n.markdown-body .pl-c2 {\n    color: var(--color-prettylights-syntax-carriage-return-text);\n    background-color: var(--color-prettylights-syntax-carriage-return-bg)\n}\n\n.markdown-body .pl-sr .pl-cce {\n    font-weight: 700;\n    color: var(--color-prettylights-syntax-string-regexp)\n}\n\n.markdown-body .pl-ml {\n    color: var(--color-prettylights-syntax-markup-list)\n}\n\n.markdown-body .pl-mh,\n.markdown-body .pl-mh .pl-en,\n.markdown-body .pl-ms {\n    font-weight: 700;\n    color: var(--color-prettylights-syntax-markup-heading)\n}\n\n.markdown-body .pl-mi {\n    font-style: italic;\n    color: var(--color-prettylights-syntax-markup-italic)\n}\n\n.markdown-body .pl-mb {\n    font-weight: 700;\n    color: var(--color-prettylights-syntax-markup-bold)\n}\n\n.markdown-body .pl-md {\n    color: var(--color-prettylights-syntax-markup-deleted-text);\n    background-color: var(--color-prettylights-syntax-markup-deleted-bg)\n}\n\n.markdown-body .pl-mi1 {\n    color: var(--color-prettylights-syntax-markup-inserted-text);\n    background-color: var(--color-prettylights-syntax-markup-inserted-bg)\n}\n\n.markdown-body .pl-mc {\n    color: var(--color-prettylights-syntax-markup-changed-text);\n    background-color: var(--color-prettylights-syntax-markup-changed-bg)\n}\n\n.markdown-body .pl-mi2 {\n    color: var(--color-prettylights-syntax-markup-ignored-text);\n    background-color: var(--color-prettylights-syntax-markup-ignored-bg)\n}\n\n.markdown-body .pl-mdr {\n    font-weight: 700;\n    color: var(--color-prettylights-syntax-meta-diff-range)\n}\n\n.markdown-body .pl-ba {\n    color: var(--color-prettylights-syntax-brackethighlighter-angle)\n}\n\n.markdown-body .pl-sg {\n    color: var(--color-prettylights-syntax-sublimelinter-gutter-mark)\n}\n\n.markdown-body .pl-corl {\n    text-decoration: underline;\n    color: var(--color-prettylights-syntax-constant-other-reference-link)\n}\n\n.markdown-body g-emoji {\n    display: inline-block;\n    min-width: 1ch;\n    font-family: apple color emoji, segoe ui emoji, segoe ui symbol;\n    font-size: 1em;\n    font-style: normal !important;\n    font-weight: var(--base-text-weight-normal, 400);\n    line-height: 1;\n    vertical-align: -.075em\n}\n\n.markdown-body g-emoji img {\n    width: 1em;\n    height: 1em\n}\n\n.markdown-body .task-list-item {\n    list-style-type: none\n}\n\n.markdown-body .task-list-item label {\n    font-weight: var(--base-text-weight-normal, 400)\n}\n\n.markdown-body .task-list-item.enabled label {\n    cursor: pointer\n}\n\n.markdown-body .task-list-item+.task-list-item {\n    margin-top: 4px\n}\n\n.markdown-body .task-list-item .handle {\n    display: none\n}\n\n.markdown-body .task-list-item-checkbox {\n    margin: 0 .2em .25em -1.4em;\n    vertical-align: middle\n}\n\n.markdown-body .contains-task-list:dir(rtl) .task-list-item-checkbox {\n    margin: 0 -1.6em .25em .2em\n}\n\n.markdown-body .contains-task-list {\n    position: relative\n}\n\n.markdown-body .contains-task-list:hover .task-list-item-convert-container,\n.markdown-body .contains-task-list:focus-within .task-list-item-convert-container {\n    display: block;\n    width: auto;\n    height: 24px;\n    overflow: visible;\n    clip: auto\n}\n\n.markdown-body ::-webkit-calendar-picker-indicator {\n    filter: invert(50%)\n}"
  },
  {
    "path": "addon/chrome/locale/en-US/addon.properties",
    "content": "startup.begin=Addon is loading\nstartup.finish=Addon is ready\nmenuitem.label=Addon Template: Helper Examples\nmenupopup.label=Addon Template: Menupopup\nmenuitem.submenulabel=Addon Template\nmenuitem.filemenulabel=Addon Template: File Menuitem\nprefs.title=Template\nprefs.table.title=Title\nprefs.table.detail=Detail\ntabpanel.lib.tab.label=Lib Tab\ntabpanel.reader.tab.label=Reader Tab"
  },
  {
    "path": "addon/chrome/locale/en-US/overlay.dtd",
    "content": "<!ENTITY zotero.__addonRef__.pref.title \"Addon Template Example\">\n<!ENTITY zotero.__addonRef__.itemmenu.test.label \"addon template\">\n<!ENTITY zotero.__addonRef__.pref.enable.label \"Enable\">\n<!ENTITY zotero.__addonRef__.pref.input.label \"Input\">\n\n<!ENTITY zotero.__addonRef__.help.version.label \"__addonName__ VERSION __buildVersion__\">\n<!ENTITY zotero.__addonRef__.help.releasetime.label \"Build __buildTime__\">"
  },
  {
    "path": "addon/chrome/locale/zh-CN/addon.properties",
    "content": "startup.begin=插件加载中\nstartup.finish=插件已就绪\nmenuitem.label=插件模板: 帮助工具样例\nmenupopup.label=插件模板: 弹出菜单\nmenuitem.submenulabel=插件模板：子菜单\nmenuitem.filemenulabel=插件模板: 文件菜单\nprefs.title=插件模板\nprefs.table.title=标题\nprefs.table.detail=详情\ntabpanel.lib.tab.label=库标签\ntabpanel.reader.tab.label=阅读器标签"
  },
  {
    "path": "addon/chrome/locale/zh-CN/overlay.dtd",
    "content": "<!ENTITY zotero.__addonRef__.pref.title \"插件模板设置示例\">\n<!ENTITY zotero.__addonRef__.itemmenu.test.label \"插件模板\">\n<!ENTITY zotero.__addonRef__.pref.enable.label \"开启\">\n<!ENTITY zotero.__addonRef__.pref.input.label \"输入\">\n\n<!ENTITY zotero.__addonRef__.help.version.label \"__addonName__ 版本 __buildVersion__\">\n<!ENTITY zotero.__addonRef__.help.releasetime.label \"Build __buildTime__\">"
  },
  {
    "path": "addon/chrome.manifest",
    "content": "content __addonRef__ chrome/content/\nlocale __addonRef__ en-US chrome/locale/en-US/\nlocale __addonRef__ zh-CN chrome/locale/zh-CN/\n"
  },
  {
    "path": "addon/install.rdf",
    "content": "<?xml version=\"1.0\"?>\n<RDF:RDF\n    xmlns:em=\"http://www.mozilla.org/2004/em-rdf#\"\n    xmlns:NC=\"http://home.netscape.com/NC-rdf#\"\n    xmlns:RDF=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\n    <RDF:Description\n        RDF:about=\"urn:mozilla:install-manifest\"\n        em:id=\"__addonID__\"\n        em:name=\"__addonName__\"\n        em:version=\"__buildVersion__\"\n        em:type=\"2\"\n        em:creator=\"__author__\"\n        em:description=\"__description__\"\n        em:homepageURL=\"__homepage__\"\n        em:iconURL=\"chrome://__addonRef__/content/icons/favicon.png\"\n        em:optionsURL=\"chrome://__addonRef__/content/preferences.xul\"\n        em:updateURL=\"__updaterdf__\"\n        em:multiprocessCompatible=\"true\"\n        em:bootstrap=\"true\">\n        <em:targetApplication>\n            <Description>\n                <em:id>zotero@chnm.gmu.edu</em:id>\n                <em:minVersion>5.0</em:minVersion>\n                <em:maxVersion>*</em:maxVersion>\n            </Description>\n        </em:targetApplication>\n        <em:targetApplication>\n            <Description>\n                <em:id>juris-m@juris-m.github.io</em:id>\n                <em:minVersion>5.0</em:minVersion>\n                <em:maxVersion>*</em:maxVersion>\n            </Description>\n        </em:targetApplication>\n  </RDF:Description>\n</RDF:RDF>\n"
  },
  {
    "path": "addon/manifest.json",
    "content": "{\n  \"manifest_version\": 2,\n  \"name\": \"__addonName__\",\n  \"version\": \"__buildVersion__\",\n  \"description\": \"__description__\",\n  \"author\": \"__author__\",\n  \"icons\": {\n    \"48\": \"chrome/content/icons/favicon@0.5x.png\",\n    \"96\": \"chrome/content/icons/favicon.png\"\n  },\n  \"applications\": {\n    \"zotero\": {\n      \"id\": \"__addonID__\",\n      \"update_url\": \"__updaterdf__\",\n      \"strict_min_version\": \"6.999\",\n      \"strict_max_version\": \"7.0.*\"\n    }\n  }\n}\n"
  },
  {
    "path": "addon/prefs.js",
    "content": "pref(\"extensions.zotero.__addonRef__.enable\", true);\npref(\"extensions.zotero.__addonRef__.tags\", \"[]\");\npref(\"extensions.zotero.__addonRef__.secretKey\", \"\");\npref(\"extensions.zotero.__addonRef__.model\", \"gpt-3.5-turbo\");\npref(\"extensions.zotero.__addonRef__.api\", \"https://api.openai.com\");\npref(\"extensions.zotero.__addonRef__.temperature\", \"1.0\");\npref(\"extensions.zotero.__addonRef__.deltaTime\", 100);\npref(\"extensions.zotero.__addonRef__.width\", \"32%\");\npref(\"extensions.zotero.__addonRef__.tagsMore\", \"expand\");\npref(\"extensions.zotero.__addonRef__.chatNumber\", 3);\npref(\"extensions.zotero.__addonRef__.relatedNumber\", 5);\npref(\"extensions.zotero.__addonRef__.embeddingBatchNum\", 10);\n\n\n\n\n\n\n\n\n"
  },
  {
    "path": "package.json",
    "content": "{\n  \"name\": \"zotero-gpt\",\n  \"version\": \"0.2.8\",\n  \"description\": \"GPT Meet Zotero\",\n  \"config\": {\n    \"addonName\": \"Zotero GPT\",\n    \"addonID\": \"zoterogpt@polygon.org\",\n    \"addonRef\": \"zoterogpt\",\n    \"addonInstance\": \"ZoteroGPT\",\n    \"releasepage\": \"\",\n    \"updaterdf\": \"\"\n  },\n  \"main\": \"src/index.ts\",\n  \"scripts\": {\n    \"build-dev\": \"cross-env NODE_ENV=development node scripts/build.js\",\n    \"build-prod\": \"cross-env NODE_ENV=production node scripts/build.js\",\n    \"build\": \"concurrently -c auto npm:build-prod npm:tsc\",\n    \"tsc\": \"tsc --noEmit\",\n    \"start-z6\": \"node scripts/start.js --z 6\",\n    \"start-z7\": \"node scripts/start.js --z 7\",\n    \"start\": \"node scripts/start.js\",\n    \"stop\": \"node scripts/stop.js\",\n    \"restart-dev\": \"npm run build-dev && npm run stop && npm run start\",\n    \"restart-prod\": \"npm run build-prod && npm run stop && npm run start\",\n    \"restart\": \"npm run restart-dev\",\n    \"release\": \"release-it\",\n    \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\"\n  },\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"git+https://github.com/MuiseDestiny/zotero-gpt.git\"\n  },\n  \"author\": \"Polygon\",\n  \"license\": \"AGPL-3.0-or-later\",\n  \"bugs\": {\n    \"url\": \"https://github.com/MuiseDestiny/zotero-gpt/issues\"\n  },\n  \"homepage\": \"\",\n  \"dependencies\": {\n    \"@dqbd/tiktoken\": \"^1.0.6\",\n    \"@iktakahiro/markdown-it-katex\": \"^4.0.1\",\n    \"@pinecone-database/pinecone\": \"^0.0.14\",\n    \"blueimp-md5\": \"^2.19.0\",\n    \"chromadb\": \"^1.3.1\",\n    \"compute-cosine-similarity\": \"^1.0.0\",\n    \"crypto\": \"^1.0.1\",\n    \"crypto-js\": \"^4.1.1\",\n    \"dotenv\": \"^16.0.3\",\n    \"gpt-3-encoder\": \"^1.1.4\",\n    \"highlight\": \"^0.2.4\",\n    \"highlight.js\": \"^11.7.0\",\n    \"htmldiff-js\": \"^1.0.5\",\n    \"langchain\": \"^0.0.66\",\n    \"lighten-darken-color\": \"^1.0.0\",\n    \"markdown-it\": \"^13.0.1\",\n    \"markdown-it-mathjax3\": \"^4.3.2\",\n    \"node-fetch\": \"^3.3.1\",\n    \"pdf-parse\": \"^1.1.1\",\n    \"pdfreader\": \"^3.0.0\",\n    \"proxy-agent\": \"^5.0.0\",\n    \"react-markdown\": \"^8.0.6\",\n    \"showdown\": \"^2.1.0\",\n    \"terser\": \"^5.17.1\",\n    \"zotero-adv-installer\": \"file:..\",\n    \"zotero-plugin-toolkit\": \"^2.0.1\"\n  },\n  \"devDependencies\": {\n    \"@types/crypto-js\": \"^4.1.1\",\n    \"@types/markdown-it\": \"^12.2.3\",\n    \"@types/node\": \"^18.11.17\",\n    \"compressing\": \"^1.6.3\",\n    \"concurrently\": \"^8.0.1\",\n    \"cross-env\": \"^7.0.3\",\n    \"esbuild\": \"^0.17.4\",\n    \"esbuild-plugin-wasm\": \"^1.0.0\",\n    \"minimist\": \"^1.2.7\",\n    \"punycode\": \"^2.3.0\",\n    \"release-it\": \"^15.6.0\",\n    \"replace-in-file\": \"^6.3.5\",\n    \"typescript\": \"^5.0.4\",\n    \"uglify-js\": \"^3.17.4\",\n    \"zotero-types\": \"^1.0.12\"\n  }\n}\n"
  },
  {
    "path": "scripts/build.js",
    "content": "const esbuild = require(\"esbuild\");\nconst compressing = require(\"compressing\");\nconst path = require(\"path\");\nconst fs = require(\"fs\");\nconst process = require(\"process\");\nconst replace = require(\"replace-in-file\");\nconst UglifyJS = require(\"terser\");\nconst {\n  name,\n  author,\n  description,\n  homepage,\n  version,\n  config,\n} = require(\"../package.json\");\n\nfunction copyFileSync(source, target) {\n  var targetFile = target;\n\n  // If target is a directory, a new file with the same name will be created\n  if (fs.existsSync(target)) {\n    if (fs.lstatSync(target).isDirectory()) {\n      targetFile = path.join(target, path.basename(source));\n    }\n  }\n\n  fs.writeFileSync(targetFile, fs.readFileSync(source));\n}\n\nfunction copyFolderRecursiveSync(source, target) {\n  var files = [];\n\n  // Check if folder needs to be created or integrated\n  var targetFolder = path.join(target, path.basename(source));\n  if (!fs.existsSync(targetFolder)) {\n    fs.mkdirSync(targetFolder);\n  }\n\n  // Copy\n  if (fs.lstatSync(source).isDirectory()) {\n    files = fs.readdirSync(source);\n    files.forEach(function (file) {\n      var curSource = path.join(source, file);\n      if (fs.lstatSync(curSource).isDirectory()) {\n        copyFolderRecursiveSync(curSource, targetFolder);\n      } else {\n        copyFileSync(curSource, targetFolder);\n      }\n    });\n  }\n}\n\nfunction clearFolder(target) {\n  if (fs.existsSync(target)) {\n    fs.rmSync(target, { recursive: true, force: true });\n  }\n\n  fs.mkdirSync(target, { recursive: true });\n}\n\nfunction dateFormat(fmt, date) {\n  let ret;\n  const opt = {\n    \"Y+\": date.getFullYear().toString(),\n    \"m+\": (date.getMonth() + 1).toString(),\n    \"d+\": date.getDate().toString(),\n    \"H+\": date.getHours().toString(),\n    \"M+\": date.getMinutes().toString(),\n    \"S+\": date.getSeconds().toString(),\n  };\n  for (let k in opt) {\n    ret = new RegExp(\"(\" + k + \")\").exec(fmt);\n    if (ret) {\n      fmt = fmt.replace(\n        ret[1],\n        ret[1].length == 1 ? opt[k] : opt[k].padStart(ret[1].length, \"0\")\n      );\n    }\n  }\n  return fmt;\n}\n\nasync function main() {\n  const t = new Date();\n  const buildTime = dateFormat(\"YYYY-mm-dd HH:MM:SS\", t);\n  const buildDir = \"builds\";\n\n  console.log(\n    `[Build] BUILD_DIR=${buildDir}, VERSION=${version}, BUILD_TIME=${buildTime}, ENV=${[\n      process.env.NODE_ENV,\n    ]}`\n  );\n\n  clearFolder(buildDir);\n\n  copyFolderRecursiveSync(\"addon\", buildDir);\n\n  copyFileSync(\"update-template.json\", \"update.json\");\n  copyFileSync(\"update-template.rdf\", \"update.rdf\");\n\n  const outfile = path.join(buildDir, \"addon/chrome/content/scripts/index.js\");\n  await esbuild\n    .build({\n      entryPoints: [\"src/index.ts\"],\n      define: {\n        __env__: `\"${process.env.NODE_ENV}\"`,\n      },\n      bundle: true,\n      outfile,\n      // Don't turn minify on\n      // minify: true,\n      target: \"firefox60\",\n    })\n    .catch(() => process.exit(1));\n\n  console.log(\"[Build] Run esbuild OK\");\n\n  const indexJsContent = fs.readFileSync(outfile, \"utf-8\");\n  const result = await UglifyJS.minify(indexJsContent, {\n    output: { ascii_only: true },\n  });\n  if (result.error) {\n    console.log(\"UglifyJS error\", result.error);\n    process.exit(1);\n  }\n  fs.writeFileSync(outfile, result.code, \"utf-8\");\n\n  const replaceFrom = [\n    /__author__/g,\n    /__description__/g,\n    /__homepage__/g,\n    /__buildVersion__/g,\n    /__buildTime__/g,\n  ];\n\n  const replaceTo = [author, description, homepage, version, buildTime];\n\n  replaceFrom.push(\n    ...Object.keys(config).map((k) => new RegExp(`__${k}__`, \"g\"))\n  );\n  replaceTo.push(...Object.values(config));\n\n  const optionsAddon = {\n    files: [\n      path.join(buildDir, \"**/*.rdf\"),\n      path.join(buildDir, \"**/*.dtd\"),\n      path.join(buildDir, \"**/*.xul\"),\n      path.join(buildDir, \"**/*.xhtml\"),\n      path.join(buildDir, \"**/*.json\"),\n      path.join(buildDir, \"addon/prefs.js\"),\n      path.join(buildDir, \"addon/chrome.manifest\"),\n      path.join(buildDir, \"addon/manifest.json\"),\n      path.join(buildDir, \"addon/bootstrap.js\"),\n      \"update.json\",\n      \"update.rdf\",\n    ],\n    from: replaceFrom,\n    to: replaceTo,\n    countMatches: true,\n  };\n\n  _ = replace.sync(optionsAddon);\n  console.log(\n    \"[Build] Run replace in \",\n    _.filter((f) => f.hasChanged).map(\n      (f) => `${f.file} : ${f.numReplacements} / ${f.numMatches}`\n    )\n  );\n\n  console.log(\"[Build] Replace OK\");\n\n  console.log(\"[Build] Addon prepare OK\");\n\n  await compressing.zip.compressDir(\n    path.join(buildDir, \"addon\"),\n    path.join(buildDir, `${name}.xpi`),\n    {\n      ignoreBase: true,\n    }\n  );\n\n  console.log(\"[Build] Addon pack OK\");\n  console.log(\n    `[Build] Finished in ${(new Date().getTime() - t.getTime()) / 1000} s.`\n  );\n}\n\nmain().catch((err) => {\n  console.log(err);\n  process.exit(1);\n});\n"
  },
  {
    "path": "scripts/start.js",
    "content": "const { execSync } = require(\"child_process\");\nconst { exit } = require(\"process\");\nconst { exec } = require(\"./zotero-cmd.json\");\n\n// Run node start.js -h for help\nconst args = require(\"minimist\")(process.argv.slice(2));\n\nif (args.help || args.h) {\n  console.log(\"Start Zotero Args:\");\n  console.log(\n    \"--zotero(-z): Zotero exec key in zotero-cmd.json. Default the first one.\"\n  );\n  console.log(\"--profile(-p): Zotero profile name.\");\n  exit(0);\n}\n\nconst zoteroPath = exec[args.zotero || args.z || Object.keys(exec)[0]];\nconst profile = args.profile || args.p;\n\nconst startZotero = `${zoteroPath} --debugger --purgecaches ${\n  profile ? `-p ${profile}` : \"\"\n}`;\n\nexecSync(startZotero);\nexit(0);\n"
  },
  {
    "path": "scripts/stop.js",
    "content": "const { execSync } = require(\"child_process\");\nconst { killZoteroWindows, killZoteroUnix } = require(\"./zotero-cmd.json\");\n\ntry {\n  if (process.platform === \"win32\") {\n    execSync(killZoteroWindows);\n  } else {\n    execSync(killZoteroUnix);\n  }\n} catch (e) {}\n"
  },
  {
    "path": "scripts/zotero-cmd-default.json",
    "content": "{\n  \"usage\": \"Copy and rename this file to zotero-cmd.json. Edit the cmd.\",\n  \"killZoteroWindows\": \"taskkill /f /im zotero.exe\",\n  \"killZoteroUnix\": \"kill -9 $(ps -x | grep zotero)\",\n  \"exec\": {\n    \"6\": \"/path/to/zotero6.exe\",\n    \"7\": \"/path/to/zotero7.exe\"\n  }\n}"
  },
  {
    "path": "src/addon.ts",
    "content": "import ZoteroToolkit from \"zotero-plugin-toolkit/dist/index\";\nimport { ColumnOptions } from \"zotero-plugin-toolkit/dist/helpers/virtualizedTable\";\nimport hooks from \"./hooks\";\n\nclass Addon {\n  public data: {\n    alive: boolean;\n    // Env type, see build.js\n    env: \"development\" | \"production\";\n    // ztoolkit: MyToolkit;\n    ztoolkit: ZoteroToolkit;\n    locale?: {\n      stringBundle: any;\n    };\n    prefs?: {\n      window: Window;\n      columns: Array<ColumnOptions>;\n      rows: Array<{ [dataKey: string]: string }>;\n    };\n  };\n  // Lifecycle hooks\n  public hooks: typeof hooks;\n  // APIs\n  public api: {};\n\n  constructor() {\n    this.data = {\n      alive: true,\n      env: __env__,\n      // ztoolkit: new MyToolkit(),\n      ztoolkit: new ZoteroToolkit(),\n    };\n    this.hooks = hooks;\n    this.api = {};\n  }\n}\n\nexport default Addon;\n"
  },
  {
    "path": "src/hooks.ts",
    "content": "import { config } from \"../package.json\";\nimport { getString, initLocale } from \"./modules/locale\";\nimport Views from \"./modules/views\";\nimport Utils from \"./modules/utils\";\nimport { initValidation } from \"../../validation/core\";\n\nasync function onStartup() {\n  initValidation(config.addonRef); \n  await Promise.all([\n    Zotero.initializationPromise,\n    Zotero.unlockPromise,\n    Zotero.uiReadyPromise,\n  ]);\n  initLocale();\n  ztoolkit.ProgressWindow.setIconURI(\n    \"default\",\n    `chrome://${config.addonRef}/content/icons/favicon.png`\n  );\n\n  Zotero[config.addonInstance].views = new Views();\n\n  Zotero[config.addonInstance].utils = new Utils();\n}\n\nfunction onShutdown(): void {\n  ztoolkit.unregisterAll();\n  // Remove addon object\n  addon.data.alive = false;\n  delete Zotero[config.addonInstance];\n}\n\nexport default {\n  onStartup,\n  onShutdown,\n};\n"
  },
  {
    "path": "src/index.ts",
    "content": "import { BasicTool } from \"zotero-plugin-toolkit/dist/basic\";\nimport Addon from \"./addon\";\nimport { config } from \"../package.json\";\n\nconst basicTool = new BasicTool();\n\nif (!basicTool.getGlobal(\"Zotero\")[config.addonInstance]) {\n  // Set global variables\n  let window: Window\n  _globalThis.Zotero = basicTool.getGlobal(\"Zotero\");\n  _globalThis.ZoteroPane = basicTool.getGlobal(\"ZoteroPane\");\n  _globalThis.Zotero_Tabs = basicTool.getGlobal(\"Zotero_Tabs\");\n  _globalThis.window = window = basicTool.getGlobal(\"window\");\n  _globalThis.URL = basicTool.getGlobal(\"window\").URL;\n  _globalThis.setTimeout = basicTool.getGlobal(\"window\").setTimeout;\n  _globalThis.URLSearchParams = basicTool.getGlobal(\"window\").URLSearchParams;\n  _globalThis.Headers = basicTool.getGlobal(\"window\").Headers;\n  _globalThis.AbortSignal = basicTool.getGlobal(\"window\").AbortSignal;\n  _globalThis.Request = basicTool.getGlobal(\"window\").Request;\n  _globalThis.AbortSignal.timeout = (ms: number) => {\n    // @ts-ignore\n    const controller = new window.AbortController();\n    const timer = window.setTimeout(() => controller.abort(), ms);\n    controller.signal.addEventListener(\"abort\", () => {\n      window.clearTimeout(timer);\n    });\n    return controller.signal;\n  }\n\n  _globalThis.document = basicTool.getGlobal(\"document\");\n  _globalThis.addon = new Addon();\n  _globalThis.ztoolkit = addon.data.ztoolkit;\n  ztoolkit.basicOptions.log.prefix = `[${config.addonName}]`;\n  ztoolkit.basicOptions.log.disableConsole = addon.data.env === \"production\";\n  ztoolkit.UI.basicOptions.ui.enableElementJSONLog = false\n  ztoolkit.UI.basicOptions.ui.enableElementDOMLog = false\n  ztoolkit.basicOptions.debug.disableDebugBridgePassword =\n    addon.data.env === \"development\";\n  Zotero[config.addonInstance] = addon;\n  // Trigger addon hook for initialization\n  addon.hooks.onStartup();\n}\n"
  },
  {
    "path": "src/modules/Meet/BetterNotes.ts",
    "content": "import Views from \"../views\";\nimport Meet from \"./api\";\n\n/**\n * 优先返回选中文本，再返回所在span前所有文字MD\n * @param span 光标所在行，HTMLSpanElement\n * @returns \n */\nexport async function getEditorText(span: HTMLSpanElement) {\n  const BNEditorApi = Zotero.BetterNotes.api.editor\n  const editor = BNEditorApi.getEditorInstance(Zotero.BetterNotes.data.workspace.mainId);\n  let lines = [...editor._iframeWindow.document.querySelector(\".primary-editor\").childNodes]\n  lines = lines.slice(0, lines.indexOf(span))\n  const context = await Zotero.BetterNotes.api.convert.html2md(lines.map(e => e.outerHTML).join(\"\\n\"))\n  let range = Zotero.BetterNotes.api.editor.getRangeAtCursor(editor)\n  let selection = Zotero.BetterNotes.api.editor.getTextBetween(editor, range.from, range.to)\n  ztoolkit.log(selection, range)\n  if (selection.trim().length > 0) {\n    ztoolkit.log(\"selection\", selection)\n    return selection\n  } else {\n    ztoolkit.log(\"context\", context)\n    return context\n  }\n}\n\nexport function reFocus(editor?: any) {\n  if (!editor) {\n    const BNEditorApi = Zotero.BetterNotes.api.editor\n    editor = BNEditorApi.getEditorInstance(Zotero.BetterNotes.data.workspace.mainId);\n  }\n  editor && editor._iframeWindow.focus()\n}\n\n\n\nexport function replaceEditorText(htmlString: string) {\n  const BNEditorApi = Zotero.BetterNotes.api.editor\n  const editor = BNEditorApi.getEditorInstance(Zotero.BetterNotes.data.workspace.mainId);\n  const range = BNEditorApi.getRangeAtCursor(editor)\n  // 删除原来\n  window.setTimeout(async () => {\n    await Meet.Global.lock\n    Meet.Global.lock = Zotero.Promise.defer() as _ZoteroTypes.PromiseObject\n    BNEditorApi.del(editor, range.from, range.to)\n    insertEditorText(htmlString)\n    Meet.Global.lock.resolve()\n  })\n}\n\n/**\n * 在编辑器光标处插入文本\n * @param htmlString \n */\nexport function insertEditorText(htmlString: string, editor?: any) {\n  const BNEditorApi = Zotero.BetterNotes.api.editor\n  if (!editor) {\n    editor = BNEditorApi.getEditorInstance(Zotero.BetterNotes.data.workspace.mainId);\n  }\n  const to = BNEditorApi.getRangeAtCursor(editor).to\n  reFocus(editor)\n  BNEditorApi.insert(\n    editor,\n    htmlString,\n    to,\n    true\n  )\n  reFocus(editor)\n}\n\n/**\n * 让GPT UI跟随此行\n */\nexport function follow() {\n  const views = Zotero.ZoteroGPT.views as Views\n  const BNEditorApi = Zotero.BetterNotes.api.editor\n  const editor = BNEditorApi.getEditorInstance(Zotero.BetterNotes.data.workspace.mainId);\n  let getLine: any = (index: number) => {\n    return editor._iframeWindow.document.querySelector(`.primary-editor>*:nth-child(${index})`)\n  }\n  let place = (reBuild: boolean = false) => {\n    const lineIndex = BNEditorApi.getLineAtCursor(editor) + 1\n    let line = getLine(lineIndex)\n    // 光标有文字就下一行\n    if (line.innerText.replace(\"\\n\", \"\").trim().length != 0) {\n      line = getLine(lineIndex+1)\n    }\n    let { x, y } = line.getBoundingClientRect();\n    const leftPanel = document.querySelector(\"#betternotes-workspace-outline-container\")!\n    x = leftPanel.getAttribute(\"collapsed\") ?\n      0\n      :\n      leftPanel.getBoundingClientRect().width\n    views.show(x + 30, y + 38, reBuild)\n  }\n  // 第一次重建UI\n  place(true)\n  let id = window.setInterval(async () => {\n    // await Meet.Global.lock;\n    // Meet.Global.lock = Zotero.Promise.defer() as _ZoteroTypes.PromiseObject\n    place()\n    // Meet.Global.lock.resolve()\n  }, 10)\n  views._ids.push({\n    type: \"follow\",\n    id: id\n  })\n}"
  },
  {
    "path": "src/modules/Meet/OpenAI.ts",
    "content": "import { config } from \"../../../package.json\";\nimport { MD5 } from \"crypto-js\"\nimport { Document } from \"langchain/document\";\nimport LocalStorage from \"../localStorage\";\nimport Views from \"../views\";\nimport Meet from \"./api\";\nconst similarity = require('compute-cosine-similarity');\ndeclare type RequestArg = { headers: any, api: string, body: Function, remove?: string | RegExp, process?: Function }\nlet chatID: string\nconst requestArgs: RequestArg[] = [\n  {\n    api: \"https://aigpt.one/api/chat-stream\",\n    headers: {\n      \"path\": \"v1/chat/completions\"\n    },\n    body: (requestText: string, messages: any) => { \n      return {\n        \"model\": \"gpt-3.5-turbo\",\n        messages: messages,\n        stream: true,\n        \"max_tokens\": 2000,\n        \"presence_penalty\": 0\n      }\n    } \n  },\n  {\n    api: \"https://chatbot.theb.ai/api/chat-process\",\n    headers: {\n    },\n    body: (requestText: string, messages: any) => {\n      return { \"prompt\": requestText, \"options\": { \"parentMessageId\": chatID }}\n    },\n    process: (text: string) => {\n      const res = JSON.parse(text.split(\"\\n\").slice(-1)[0])\n      chatID = res.id\n      return res.text\n    }\n  }\n]\n\n/**\n * 给定文本和文档，返回文档列表，返回最相似的几个\n * @param queryText \n * @param docs \n * @param obj \n * @returns \n */\nexport async function similaritySearch(queryText: string, docs: Document[], obj: { key: string }) {\n  const storage = Meet.Global.storage = Meet.Global.storage || new LocalStorage(config.addonRef)\n  await storage.lock.promise;\n  const embeddings = new OpenAIEmbeddings() as any\n  // 查找本地，为节省空间，只储存向量\n  // 因为随着插件更新，解析出的PDF可能会有优化，因此再此进行提取MD5值作为验证\n  // 但可以预测，本地JSON文件可能会越来越大\n  const id = MD5(docs.map((i: any) => i.pageContent).join(\"\\n\\n\")).toString()\n  await storage.lock\n  const _vv = storage.get(obj, id)\n  ztoolkit.log(_vv)\n  let vv: any\n  if (_vv) {\n    Meet.Global.popupWin.createLine({ text: \"Reading embeddings...\", type: \"default\" })\n    vv = _vv\n  } else {\n    Meet.Global.popupWin.createLine({ text: \"Generating embeddings...\", type: \"default\" })\n    vv = await embeddings.embedDocuments(docs.map((i: any) => i.pageContent))\n    window.setTimeout(async () => {\n      await storage.set(obj, id, vv)\n    })\n  }\n\n  const v0 = await embeddings.embedQuery(queryText)\n  // 从20个里面找出文本最长的几个，防止出现较短但相似度高的段落影响回答准确度\n  const relatedNumber = Zotero.Prefs.get(`${config.addonRef}.relatedNumber`) as number\n  Meet.Global.popupWin.createLine({ text: `Searching ${relatedNumber} related content...`, type: \"default\" })\n  const k = relatedNumber * 5\n  const pp = vv.map((v: any) => similarity(v0, v));\n  docs = [...pp].sort((a, b) => b - a).slice(0, k).map((p: number) => {\n    return docs[pp.indexOf(p)]\n  })\n  // return docs.slice(0, relatedNumber)\n  return docs.sort((a, b) => b.pageContent.length - a.pageContent.length).slice(0, relatedNumber)\n}\n\n\nclass OpenAIEmbeddings {\n  constructor() {\n  }\n  private async request(input: string[]) {\n    const views = Zotero.ZoteroGPT.views as Views\n    let api = Zotero.Prefs.get(`${config.addonRef}.api`) as string\n    api = api.replace(/\\/(?:v1)?\\/?$/, \"\")\n    const secretKey = Zotero.Prefs.get(`${config.addonRef}.secretKey`)\n    const split_len = Zotero.Prefs.get(`${config.addonRef}.embeddingBatchNum`)\n    let res\n    const url = `${api}/v1/embeddings`\n    if (!secretKey) {\n      new ztoolkit.ProgressWindow(url, { closeOtherProgressWindows: true })\n        .createLine({ text: \"Your secretKey is not configured.\", type: \"default\" })\n        .show()\n      return\n    }\n    var final_embeddings=[]\n    for (let i = 0; i < input.length; i += split_len) {\n\n      const chunk = input.slice(i, i + split_len)\n      ztoolkit.log(\"input\", chunk)\n      try {\n        res = await Zotero.HTTP.request(\n          \"POST\",\n          url,\n          {\n            responseType: \"json\",\n            headers: {\n              \"Content-Type\": \"application/json\",\n              \"Authorization\": `Bearer ${secretKey}`,\n            },\n            body: JSON.stringify({\n              model: \"text-embedding-ada-002\",\n              input: chunk\n            }),\n          }\n        )\n      } catch (error: any) {\n        try {\n          error = error.xmlhttp.response?.error\n          views.setText(`# ${error.code}\\n> ${url}\\n\\n**${error.type}**\\n${error.message}`, true)\n          new ztoolkit.ProgressWindow(error.code, { closeOtherProgressWindows: true })\n            .createLine({ text: error.message, type: \"default\" })\n            .show()\n        } catch {\n          new ztoolkit.ProgressWindow(\"Error\", { closeOtherProgressWindows: true })\n            .createLine({ text: error.message, type: \"default\" })\n            .show()\n        }\n      }\n      if (res?.response?.data) {\n        final_embeddings = final_embeddings.concat(res.response.data.map((i: any) => i.embedding))\n      }\n    }\n    return final_embeddings\n  }\n\n  public async embedDocuments(texts: string[]) {\n    return await this.request(texts)\n  }\n\n  public async embedQuery(text: string) {\n    return (await this.request([text]))?.[0]\n  }\n}\n\n\nexport async function getGPTResponse(requestText: string) {\n  const secretKey = Zotero.Prefs.get(`${config.addonRef}.secretKey`)\n  // 这里可以补充很多免费API，然后用户设置用哪个\n  if (!secretKey) { return await getGPTResponseBy(requestArgs[1], requestText) }\n  else { return await getGPTResponseByOpenAI(requestText) }\n}\n\n/**\n * 所有getGPTResponseTextByXXX参照此函数实现\n * gpt-3.5-turbo / gpt-4\n * @param requestText \n * @returns \n */\nexport async function getGPTResponseByOpenAI(requestText: string) {\n  const views = Zotero.ZoteroGPT.views as Views\n  const secretKey = Zotero.Prefs.get(`${config.addonRef}.secretKey`)\n  const temperature = Zotero.Prefs.get(`${config.addonRef}.temperature`)\n  let api = Zotero.Prefs.get(`${config.addonRef}.api`) as string\n  api = api.replace(/\\/(?:v1)?\\/?$/, \"\")\n  const model = Zotero.Prefs.get(`${config.addonRef}.model`)\n  views.messages.push({\n    role: \"user\",\n    content: requestText\n  })\n  // outputSpan.innerText = responseText;\n  const deltaTime = Zotero.Prefs.get(`${config.addonRef}.deltaTime`) as number\n  // 储存上一次的结果\n  let _textArr: string[] = []\n  // 随着请求返回实时变化\n  let textArr: string[] = []\n  // 激活输出\n  views.stopAlloutput()\n  views.setText(\"\")\n  let responseText: string | undefined\n  const id: number = window.setInterval(async () => {\n    if (!responseText && _textArr.length == textArr.length) { return}\n    _textArr = textArr.slice(0, _textArr.length + 1)\n    let text = _textArr.join(\"\")\n    text.length > 0 && views.setText(text)\n    if (responseText && responseText == text) {\n      views.setText(text, true)\n      window.clearInterval(id)\n    }\n  }, deltaTime)\n  views._ids.push({\n    type: \"output\",\n    id: id\n  })\n  const chatNumber = Zotero.Prefs.get(`${config.addonRef}.chatNumber`) as number\n  const url = `${api}/v1/chat/completions`\n  try {\n    await Zotero.HTTP.request(\n      \"POST\",\n      url,\n      {\n        headers: {\n          \"Content-Type\": \"application/json\",\n          \"Authorization\": `Bearer ${secretKey}`,\n        },\n        body: JSON.stringify({\n          model: model,\n          messages: views.messages.slice(-chatNumber),\n          stream: true,\n          temperature: Number(temperature)\n        }),\n        responseType: \"text\",\n        requestObserver: (xmlhttp: XMLHttpRequest) => {\n          xmlhttp.onprogress = (e: any) => {\n            try {\n              textArr = e.target.response.match(/data: (.+)/g).filter((s: string) => s.indexOf(\"content\") >= 0).map((s: string) => {\n                try {\n                  return JSON.parse(s.replace(\"data: \", \"\")).choices[0].delta.content.replace(/\\n+/g, \"\\n\")\n                } catch {\n                  return false\n                }\n              }).filter(Boolean)\n            } catch {\n              // 出错一般是token超出限制\n              ztoolkit.log(e.target.response)\n            }\n            if (e.target.timeout) {\n              e.target.timeout = 0;\n            }\n          };\n        },\n      }\n    );\n  } catch (error: any) {\n    try {\n      error = JSON.parse(error?.xmlhttp?.response).error\n      textArr = [`# ${error.code}\\n> ${url}\\n\\n**${error.type}**\\n${error.message}`]\n      new ztoolkit.ProgressWindow(error.code, { closeOtherProgressWindows: true })\n        .createLine({ text: error.message, type: \"default\" })\n        .show()\n    } catch {\n      new ztoolkit.ProgressWindow(\"Error\", { closeOtherProgressWindows: true })\n        .createLine({ text: error.message, type: \"default\" })\n        .show()\n    }\n  }\n  responseText = textArr.join(\"\")\n  ztoolkit.log(\"responseText\", responseText)\n  // if (views._ids.map(i=>i.id).indexOf(id) >= 0 ) {\n  //   views.setText(responseText, true)\n  // }\n  // window.clearInterval(id)\n  views.messages.push({\n    role: \"assistant\",\n    content: responseText\n  })\n  return responseText\n}\n\n/**\n * 返回值要是纯文本\n * @param requestArg\n * @param requestText \n * @param views \n * @returns \n */\nexport async function getGPTResponseBy(\n  requestArg: RequestArg,\n  requestText: string,\n) {\n  const views = Zotero.ZoteroGPT.views as Views\n  const deltaTime = Zotero.Prefs.get(`${config.addonRef}.deltaTime`) as number\n  let responseText: string | undefined\n  let _responseText = \"\"\n  views.messages.push({\n    role: \"user\",\n    content: requestText\n  })\n  // 储存上一次的结果\n  // 激活输出\n  views.stopAlloutput()\n  views.setText(\"\")\n  const id = window.setInterval(() => {\n    _responseText.trim().length > 0 && views.setText(_responseText)\n    if (responseText && responseText == _responseText) {\n      views.setText(_responseText, true)\n      window.clearInterval(id)\n    }\n  }, deltaTime)\n  views._ids.push({ type: \"output\", id: id })\n  const chatNumber = Zotero.Prefs.get(`${config.addonRef}.chatNumber`) as number\n  const body = JSON.stringify(requestArg.body(requestText, views.messages.slice(-chatNumber)))\n  await Zotero.HTTP.request(\n    \"POST\",\n    requestArg.api,\n    {\n      headers: {\n        \"Content-Type\": \"application/json\",\n        ...requestArg.headers\n      }, \n      body,\n      responseType: \"text\",\n      requestObserver: (xmlhttp: XMLHttpRequest) => {\n        xmlhttp.onprogress = (e: any) => {\n          _responseText = e.target.response.replace(requestArg.remove, \"\")\n          if (requestArg.process) {\n            _responseText = requestArg.process(_responseText)\n          }\n          if (e.target.timeout) {\n            e.target.timeout = 0;\n          }\n        };\n      },\n    }\n  );\n  // if (views._ids.map(i => i.id).indexOf(id) >= 0) {\n  //   views.setText(responseText, true)\n  // }\n  // window.clearInterval(id)\n  // if (views.isInNote) {\n  //   window.setTimeout(async () => {\n  //     Meet.BetterNotes.replaceEditorText(\n  //       // await Zotero.BetterNotes.api.convert.md2html(responseText)\n  //       views.container.querySelector(\".markdown-body\")!.innerHTML\n  //     )\n  //   })\n  // }\n  responseText = _responseText\n  views.messages.push({\n    role: \"assistant\",\n    content: responseText\n  })\n  return responseText\n}\n"
  },
  {
    "path": "src/modules/Meet/Zotero.ts",
    "content": "import { config } from \"../../../package.json\";\nimport { MD5 } from \"crypto-js\"\nimport { Document } from \"langchain/document\";\nimport { similaritySearch } from \"./OpenAI\";\nimport Meet from \"./api\";\nimport ZoteroToolkit from \"zotero-plugin-toolkit\";\n\n/**\n * 读取剪贴板\n * @returns string\n */\nexport function getClipboardText(): string {\n  // @ts-ignore\n  const clipboardService = window.Cc['@mozilla.org/widget/clipboard;1'].getService(Ci.nsIClipboard);\n  // @ts-ignore\n  const transferable = window.Cc['@mozilla.org/widget/transferable;1'].createInstance(Ci.nsITransferable);\n  if (!transferable) {\n    window.alert('剪贴板服务错误：无法创建可传输的实例');\n  }\n  transferable.addDataFlavor('text/unicode');\n  clipboardService.getData(transferable, clipboardService.kGlobalClipboard);\n  let clipboardData = {};\n  let clipboardLength = {};\n  try {\n    transferable.getTransferData('text/unicode', clipboardData, clipboardLength);\n  } catch (err: any) {\n    window.console.error('剪贴板服务获取失败：', err.message);\n  }\n  // @ts-ignore\n  clipboardData = clipboardData.value.QueryInterface(Ci.nsISupportsString);\n  // @ts-ignore\n  return clipboardData.data\n}\n\n/**\n * 将选中条目处理成全文\n * 注意：这里目前是不储存得到向量的，因为条目一直在更新\n * @param key \n * @returns \n */\nasync function selectedItems2documents(key: string) {\n  const docs = ZoteroPane.getSelectedItems().map((item: Zotero.Item) => {\n    const text = JSON.stringify(item.toJSON());\n    return new Document({\n      pageContent: text.slice(0, 500),\n      metadata: {\n        type: \"id\",\n        id: item.id,\n        key\n      }\n    })\n  })\n  return docs\n}\n\n/**\n * https://github.com/MuiseDestiny/zotero-reference/blob/743bef7ac59d644675d8ab33a0b6c138d47fdb2f/src/modules/pdf.ts#L75\n * @param items \n * @returns \n */\nfunction mergeSameLine(items: PDFItem[]) {\n  let toLine = (item: PDFItem) => {\n    let line: PDFLine = {\n      x: parseFloat(item.transform[4].toFixed(1)),\n      y: parseFloat(item.transform[5].toFixed(1)),\n      text: item.str || \"\",\n      height: item.height,\n      width: item.width,\n      url: item?.url,\n      _height: [item.height]\n    }\n    if (line.width < 0) {\n      line.x += line.width\n      line.width = -line.width\n    }\n    return line\n  }\n\n  let j = 0\n  let lines: PDFLine[] = [toLine(items[j])]\n  for (j = 1; j < items.length; j++) {\n    let line = toLine(items[j])\n    let lastLine = lines.slice(-1)[0]\n    // 考虑上标下标\n    if (\n      line.y == lastLine.y ||\n      (line.y >= lastLine.y && line.y < lastLine.y + lastLine.height) ||\n      (line.y + line.height > lastLine.y && line.y + line.height <= lastLine.y + lastLine.height)\n    ) {\n      lastLine.text += (\" \" + line.text)\n      lastLine.width += line.width\n      lastLine.url = lastLine.url || line.url\n      // 记录所有高度\n      lastLine._height.push(line.height)\n    } else {\n      // 处理已完成的行，用众数赋值高度\n      let hh = lastLine._height\n      // lastLine.height = hh.sort((a, b) => a - b)[parseInt(String(hh.length / 2))]\n      // 用最大值\n      // lastLine.height = hh.sort((a, b) => b-a)[0]\n      // 众数\n      const num: any = {}\n      for (let i = 0; i < hh.length; i++) {\n        num[String(hh[i])] ??= 0\n        num[String(hh[i])] += 1\n      }\n      lastLine.height = Number(\n        Object.keys(num).sort((h1: string, h2: string) => {\n          return num[h2] - num[h1]\n        })[0]\n      )\n      // 新的一行\n      lines.push(line)\n    }\n  }\n  return lines\n}\n\ndeclare type Box = {\n  left: number;\n  right: number;\n  top: number;\n  bottom: number;\n}\n\n/**\n * 判断A和B两个矩形是否几何相交\n * @param A \n * @param B \n * @returns \n */\nfunction isIntersect(A: Box, B: Box): boolean {\n  if (\n    B.right < A.left ||\n    B.left > A.right ||\n    B.bottom > A.top ||\n    B.top < A.bottom\n  ) {\n    return false\n  } else {\n    return true\n  }\n}\n\n/**\n * 判断两行是否是跨页同位置行\n * @param lineA \n * @param lineB \n * @param maxWidth \n * @param maxHeight \n * @returns \n */\nfunction isIntersectLines(lineA: any, lineB: any, maxWidth: number, maxHeight: number) {\n  let rectA = {\n    left: lineA.x / maxWidth,\n    right: (lineA.x + lineA.width) / maxWidth,\n    bottom: lineA.y / maxHeight,\n    top: (lineA.y + lineA.height) / maxHeight\n  }\n  let rectB = {\n    left: lineB.x / maxWidth,\n    right: (lineB.x + lineB.width) / maxWidth,\n    bottom: lineB.y / maxHeight,\n    top: (lineB.y + lineB.height) / maxHeight\n  }\n  return isIntersect(rectA, rectB)\n}\n\n/**\n * 读取PDF全文，因为读取速度一般较快，所以不储存\n * 当然排除学位论文，书籍等\n * 此函数遇到reference关键词会停止读取，因为参考文献太影响最后计算相似度了\n */\nasync function pdf2documents(itemkey: string) {\n  const reader = await ztoolkit.Reader.getReader() as _ZoteroTypes.ReaderInstance\n  const PDFViewerApplication = (reader._iframeWindow as any).wrappedJSObject.PDFViewerApplication;\n  await PDFViewerApplication.pdfLoadingTask.promise;\n  await PDFViewerApplication.pdfViewer.pagesPromise;\n  let pages = PDFViewerApplication.pdfViewer._pages;\n  let totalPageNum = pages.length\n  // const popupWin = new ztoolkit.ProgressWindow(\"[Pending] PDF\", { closeTime: -1 })\n  //   .createLine({ text: `[1/${totalPageNum}] Reading`, progress: 1, type: \"success\" })\n  //   .show()\n  const popupWin = Meet.Global.popupWin.createLine({ text: `[1/${totalPageNum}] Reading PDF`, progress: 1, type: \"success\" })\n    .show()\n  // 读取所有页面lines\n  const pageLines: any = {}\n  let docs: Document[] = []\n  for (let pageNum = 0; pageNum < totalPageNum; pageNum++) {\n    let pdfPage = pages[pageNum].pdfPage\n    let textContent = await pdfPage.getTextContent()\n    let items: PDFItem[] = textContent.items.filter((item: PDFItem) => item.str.trim().length)\n    let lines = mergeSameLine(items)\n    let index = lines.findIndex(line => /(r?eferences?|acknowledgements)$/i.test(line.text.trim()))\n    if (index != -1) {\n      lines = lines.slice(0, index)\n    }\n    pageLines[pageNum] = lines\n    popupWin.changeLine({ idx: popupWin.lines.length - 1, text: `[${pageNum + 1}/${totalPageNum}] Reading PDF`, progress: (pageNum + 1) / totalPageNum * 100})\n    // 防止误杀\n    if (index != -1 && pageNum / totalPageNum >= .9) {\n      break\n    }\n  }\n  popupWin.changeLine({ idx: popupWin.lines.length - 1, text: \"Reading PDF\", progress: 100 })\n  popupWin.changeLine({ progress: 100 });\n  totalPageNum = Object.keys(pageLines).length\n  for (let pageNum = 0; pageNum < totalPageNum; pageNum++) {\n    let pdfPage = pages[pageNum].pdfPage\n    const maxWidth = pdfPage._pageInfo.view[2];\n    const maxHeight = pdfPage._pageInfo.view[3];\n    let lines = [...pageLines[pageNum]]\n    // 去除页眉页脚信息\n    let removeLines = new Set()\n    let removeNumber = (text: string) => {\n      // 英文页码\n      if (/^[A-Z]{1,3}$/.test(text)) {\n        text = \"\"\n      }\n      // 正常页码1,2,3\n      text = text.replace(/\\x20+/g, \"\").replace(/\\d+/g, \"\")\n      return text\n    }\n    // 是否为重复\n    let isRepeat = (line: PDFLine, _line: PDFLine) => {\n      let text = removeNumber(line.text)\n      let _text = removeNumber(_line.text)\n      return text == _text && isIntersectLines(line, _line, maxWidth, maxHeight)\n    }\n    // 存在于数据起始结尾的无效行\n    for (let i of Object.keys(pageLines)) {\n      if (Number(i) == pageNum) { continue }\n      // 两个不同页，开始对比\n      let _lines = pageLines[i]\n      let directions = {\n        forward: {\n          factor: 1,\n          done: false\n        },\n        backward: {\n          factor: -1,\n          done: false\n        }\n      }\n      for (let offset = 0; offset < lines.length && offset < _lines.length; offset++) {\n        [\"forward\", \"backward\"].forEach((direction: string) => {\n          if (directions[direction as keyof typeof directions].done) { return }\n          let factor = directions[direction as keyof typeof directions].factor\n          let index = factor * offset + (factor > 0 ? 0 : -1)\n          let line = lines.slice(index)[0]\n          let _line = _lines.slice(index)[0]\n          if (isRepeat(line, _line)) {\n            // 认为是相同的\n            line[direction] = true\n            removeLines.add(line)\n          } else {\n            directions[direction as keyof typeof directions].done = true\n          }\n        })\n      }\n      // 内部的\n      // 设定一个百分百正文区域防止误杀\n      const content = { x: 0.2 * maxWidth, width: .6 * maxWidth, y: .2 * maxHeight, height: .6 * maxHeight }\n      for (let j = 0; j < lines.length; j++) {\n        let line = lines[j]\n        if (isIntersectLines(content, line, maxWidth, maxHeight)) { continue }\n        for (let k = 0; k < _lines.length; k++) {\n          let _line = _lines[k]\n          if (isRepeat(line, _line)) {\n            line.repeat = line.repeat == undefined ? 1 : (line.repeat + 1)\n            line.repateWith = _line\n            removeLines.add(line)\n          }\n        }\n      }\n    }\n    lines = lines.filter((e: any) => !(e.forward || e.backward || (e.repeat && e.repeat > 3)));\n    // 段落聚类\n    // 原则：字体从大到小，合并；从小变大，断开\n    let abs = (x: number) => x > 0 ? x : -x\n    const paragraphs = [[lines[0]]]\n    for (let i = 1; i < lines.length; i++) {\n      let lastLine = paragraphs.slice(-1)[0].slice(-1)[0]\n      let currentLine = lines[i]\n      let nextLine = lines[i + 1]\n      const isNewParagraph =\n        // 达到一定行数阈值\n        paragraphs.slice(-1)[0].length >= 5 && \n        (\n          // 当前行存在一个非常大的字体的文字\n          currentLine._height.some((h2: number) => lastLine._height.every((h1: number) => h2 > h1)) ||\n          // 是摘要自动为一段\n          /abstract/i.test(currentLine.text) ||\n          // 与上一行间距过大\n          abs(lastLine.y - currentLine.y) > currentLine.height * 2 ||\n          // 首行缩进分段\n          (currentLine.x > lastLine.x && nextLine && nextLine.x < currentLine.x)\n        )\n      // 开新段落\n      if (isNewParagraph) {\n        paragraphs.push([currentLine])\n      }\n      // 否则纳入当前段落\n      else {\n        paragraphs.slice(-1)[0].push(currentLine)\n      }\n    }\n    ztoolkit.log(paragraphs)\n    // 段落合并\n    for (let i = 0; i < paragraphs.length; i++) {\n      let box: { page: number, left: number; top: number; right: number; bottom: number }\n      /**\n       * 所有line是属于一个段落的\n       * 合并同时计算它的边界\n       */\n      let _pageText = \"\"\n      let line, nextLine\n      for (let j = 0; j < paragraphs[i].length; j++) {\n        line = paragraphs[i][j]\n        if (!line) { continue }\n        nextLine = paragraphs[i]?.[j + 1]\n        // 更新边界\n        box ??= { page: pageNum, left: line.x, right: line.x + line.width, top: line.y + line.height, bottom: line.y }\n        if (line.x < box.left) {\n          box.left = line.x\n        }\n        if (line.x + line.width > box.right) {\n          box.right = line.x + line.width\n        }\n        if (line.y < box.bottom) {\n          line.y = box.bottom\n        }\n        if (line.y + line.height > box.top) {\n          box.top = line.y + line.height\n        }\n        _pageText += line.text\n        if (\n          nextLine &&\n          line.height > nextLine.height\n        ) {\n          _pageText = \"\\n\"\n        } else if (j < paragraphs[i].length - 1) {\n          if (!line.text.endsWith(\"-\")) {\n            _pageText += \" \"\n          }\n        }\n      }\n      _pageText = _pageText.replace(/\\x20+/g, \" \").replace(/^\\x20*\\n+/g, \"\").replace(/\\x20*\\n+/g, \"\");\n      if (_pageText.length > 0) {\n        docs.push(\n          new Document({\n            pageContent: _pageText,\n            metadata: { type: \"box\", box: box!, key: itemkey },\n          })\n        )\n      }\n    }\n  }\n  // popupWin.changeHeadline(\"[Done] PDF\")\n  // popupWin.startCloseTimer(1000)\n  console.log(\"pdf2documents\", docs)\n  return docs\n}\n\n/**\n * 如果当前在主面板，根据选中条目生成文本，查找相关 - 用于搜索条目\n * 如果在PDF阅读界面，阅读PDF原文，查找返回相应段落 - 用于总结问题\n * @param queryText \n * @returns \n */\nexport async function getRelatedText(queryText: string) {\n  // @ts-ignore\n  const cache = (window._GPTGlobal ??= {cache: []}).cache\n  let docs: Document[], key: string\n  switch (Zotero_Tabs.selectedIndex) {\n    case 0:\n      // 只有再次选中相同条目，且条目没有更新变化，才会复用，不然会一直重复建立索引\n      // TODO - 优化\n      key = MD5(ZoteroPane.getSelectedItems().map(i => i.key).join(\"\")).toString()\n      docs = cache[key] || await selectedItems2documents(key)\n      break;\n    default:\n      let pdfItem = Zotero.Items.get(\n        Zotero.Reader.getByTabID(Zotero_Tabs.selectedID)!.itemID as number\n      )\n      key = pdfItem.key\n      docs = cache[key] || await pdf2documents(key)\n      break\n  }\n  cache[key] = docs\n  docs = await similaritySearch(queryText, docs, { key }) as Document[]\n  ztoolkit.log(\"docs\", docs)\n  Zotero[config.addonInstance].views.insertAuxiliary(docs)\n  return docs.map((doc: Document, index: number) => `[${index + 1}]${doc.pageContent}`).join(\"\\n\\n\")\n}\n\n/**\n * 获取选中条目某个字段\n * @param fieldName \n * @returns \n */\nexport function getItemField(fieldName: any) {\n  return ZoteroPane.getSelectedItems()[0].getField(fieldName)\n}\n\n/**\n * 获取PDF页面文字\n * @returns \n */\nexport function getPDFSelection() {\n  try {\n    return ztoolkit.Reader.getSelectedText(\n      Zotero.Reader.getByTabID(Zotero_Tabs.selectedID)\n    );\n  } catch {\n    return \"\"\n  }\n}\n\nexport async function getPDFAnnotations(select: boolean = false) {\n  let keys: string[]\n  if (select) {\n    // try {\n      const reader = await ztoolkit.Reader.getReader() as _ZoteroTypes.ReaderInstance\n      const nodes = reader._iframeWindow?.document.querySelectorAll(\"[id^=annotation-].selected\") as any\n      ztoolkit.log(nodes)\n      keys = [...nodes].map(i => i.id.split(\"-\")[1])\n      ztoolkit.log(keys)\n    // } catch {}\n  }\n  const pdfItem = Zotero.Items.get(\n    Zotero.Reader.getByTabID(Zotero_Tabs.selectedID)!.itemID as number\n  )\n  const docs: Document[] = [] \n  pdfItem.getAnnotations().forEach((anno: any) => {\n    if (select && keys.indexOf(anno.key) == -1) { return }\n    const pos = JSON.parse(anno.annotationPosition)\n    const rect = pos.rects[0]\n    docs.push(\n      new Document({\n        pageContent: anno.annotationText,\n        metadata: {\n          type: \"box\",\n          box: { page: pos.pageIndex, left: rect[0], right: rect[2], top: rect[3], bottom: rect[1] },\n          key: pdfItem.key\n        }\n      })\n    )\n  })\n  Zotero[config.addonInstance].views.insertAuxiliary(docs)\n  return docs.map((doc: Document, index: number) => `[${index + 1}]${doc.pageContent}`).join(\"\\n\\n\")\n}\n"
  },
  {
    "path": "src/modules/Meet/api.ts",
    "content": "import {\n  getClipboardText,\n  getItemField,\n  getPDFSelection,\n  getRelatedText,\n  getPDFAnnotations\n} from \"./Zotero\"\n\nimport {\n  getEditorText,\n  insertEditorText,\n  replaceEditorText,\n  follow,\n  reFocus\n} from \"./BetterNotes\"\n\nimport {\n  getGPTResponse\n} from \"./OpenAI\"\nimport Views from \"../views\";\n\nconst Meet: {\n  [key: string]: any;\n  Global: {\n    [key: string]: any;\n    views: Views | undefined\n  }\n} = {\n  /**\n   * 开放给用户\n   * 示例：Meet.Zotero.xxx()\n   */\n  Zotero: {\n    /**\n     * 返回系统剪贴板复制的内容\n     */\n    getClipboardText,\n    /**\n     * 返回选中条目的某个字段值，多个选中返回第一个选中的某个字段值\n     * @fieldName 接收字段的名称\n     * 比如摘要，Meet.Zotero.getItemField(\"abstractNote\")\n     */\n    getItemField, \n    /**\n     * 返回阅读PDF时选中的文字\n     */\n    getPDFSelection,\n    /**\n     * 返回相关段落，如你选中多条条目，则返回与问题最相关的5个条目\n     * 如果你在PDF中则会读取整个PDF，返回与问题最相关的5个段落\n     * @queryText 接收一个查询字符串\n     * Meet.Zotero.getItemField(\"本文提到的XXX是什么意思？\")\n     */\n    getRelatedText,\n    /**\n     * 获取PDF注释内容\n     * @select 接收一个boolean，是否返回选中的标注\n     * getPDFAnnotations(true) 会返回选中的标注\n     * getPDFAnnotations() 默认返回所有标注\n     */\n    getPDFAnnotations,\n  },\n  /**\n   * 部分开放\n   * 下列函数只针对主笔记\n   */\n  BetterNotes: {\n    getEditorText,\n    insertEditorText,\n    replaceEditorText,\n    follow,\n    reFocus\n  },\n  OpenAI: {\n    getGPTResponse\n  },\n  Global: {\n    lock: undefined,\n    input: undefined,\n    views: undefined,\n    popupWin: undefined,\n    storage: undefined\n  }\n}\n\nexport default Meet"
  },
  {
    "path": "src/modules/base.ts",
    "content": "import { config } from \"../../package.json\";\n\n\nconst help = `\n### Quick Commands\n\n\\`/help\\` Show all commands.\n\\`/clear\\` Clear history conversation.\n\\`/report\\` Run this and copy the output content to give feedback to the developer.\n\\`/secretKey sk-xxx\\` Set GPT secret key. Generate it in https://platform.openai.com/account/api-keys.\n\\`/api https://api.openai.com\\` Set API. \n\\`/model gpt-4/gpt-3.5-turbo\\` Set GPT model. For example, \\`/model gpt-3.5-turbo\\`.\n\\`/temperature 1.0\\` Set GPT temperature. Controls the randomness and diversity of generated text, specified within a range of 0 to 1.\n\\`/chatNumber 3\\` Set the number of saved historical conversations.\n\\`/relatedNumber 5\\` Set the number of most relevant text. For example, the number of paragraphs referenced while using askPDF.\n\\`/deltaTime 100\\` Control GPT smoothness (ms).\n\\`/width 32%\\` Control GPT UI width (pct).\n\\`/tagsMore expand/scroll\\` Set mode to display more tags.\n\\`/key default\\` Restore the variable values above to their default values (if have).\n\n### About UI\n\nYou can hold down \\`Ctrl\\` and scroll the mouse wheel to zoom the entire UI.\nAnd when your mouse is in the output box, the size of any content in the output box will be adjusted.\n\n### About Tag\n\nYou can \\`long click\\` on the tag below to see its internal pseudo-code.\nYou can type \\`#xxx\\` and press \\`Enter\\` to create a tag. And save it with \\`Ctrl + S\\`, during which you can execute it with \\`Ctrl + R\\`.\nYou can \\`right-long-click\\` a tag to delete it.\n\n### About Output Text\n\nYou can \\`double click\\` on this text to copy GPT's answer.\nYou can \\`long press\\` me without releasing, then move me to a suitable position before releasing.\n\n### About Input Text\n\nYou can exit me by pressing \\`Esc\\` above my head and wake me up by pressing \\`Shift + /\\` or \\`Shift + ?\\` in the Zotero main window.\nYou can type the question in my header, then press \\`Enter\\` to ask me.\nYou can press \\`Ctrl + Enter\\` to execute last executed command tag again.\nYou can press \\`Shift + Enter\\` to enter long text editing mode and press \\`Ctrl + R\\` to execute long text.\n`\n// 这是 OpenAI ChatGPT 的字体\nconst fontFamily = `Söhne,ui-sans-serif,system-ui,-apple-system,Segoe UI,Roboto,Ubuntu,Cantarell,Noto Sans,sans-serif,Helvetica Neue,Arial,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji`\n\nfunction parseTag(text: string) {\n  text = text.replace(/^\\n/, \"\").replace(/\\n$/, \"\")\n  let tagString = text.match(/^#(.+)\\n/) as any\n  function randomColor() {\n    var letters = '0123456789ABCDEF';\n    var color = '#';\n    for (var i = 0; i < 6; i++) {\n      color += letters[Math.floor(Math.random() * 16)];\n    }\n    return color;\n  }\n  let tag: Tag = {\n    tag: config.addonName,\n    color: randomColor(),\n    position: 9,\n    text: text,\n    trigger: \"\",\n  }\n  if (tagString) {\n    tagString = tagString[0]\n    tag.tag = tagString.match(/^#([^\\[\\n]+)/)[1]\n    // 解析颜色\n    let color = tagString.match(/\\[c(?:olor)?=\"?(#.+?)\"?\\]/)\n    tag.color = color?.[1] || tag.color\n    // 解析位置\n    let position = tagString.match(/\\[pos(?:ition)?=\"?(\\d+?)\"?\\]/)\n    tag.position = Number(position?.[1] || tag.position)\n    // 解析关键词\n    let trigger = tagString.match(/\\[tr(?:igger)?=\"?(.+)\"?\\]/)\n    tag.trigger = trigger?.[1] || tag.trigger\n    tag.text = `#${tag.tag}[position=${tag.position}][color=${tag.color}][trigger=${tag.trigger}]` + \"\\n\" + text.replace(/^#.+\\n/, \"\")\n  }\n  return tag\n}\n\n/**\n * 这里默认标签无法删除，但可以更改里面的内容，比如颜色位置，内部prompt\n */\nlet defaultTags: any = [\n`\n#🪐AskPDF[color=#0EA293][position=10][trigger=/^(本文|这篇文章|论文)/]\nYou are a helpful assistant. Context information is below.\n$\\{\nMeet.Global.views.messages = [];\nMeet.Zotero.getRelatedText(Meet.Global.input)\n\\}\nUsing the provided context information, write a comprehensive reply to the given query. Make sure to cite results using [number] notation after the reference. If the provided context information refer to multiple subjects with the same name, write separate answers for each subject. Use prior knowledge only if the given context didn't provide enough information.\n\nAnswer the question: $\\{Meet.Global.input\\}\n\nReply in ${Zotero.locale}\n`,\n`\n#🌟Translate[c=#D14D72][pos=11][trigger=/^翻译/]\nTranslate these content to 简体中文:\n$\\{\nMeet.Global.input.replace(\"翻译\", \"\") ||\nMeet.Zotero.getPDFSelection() ||\nMeet.Global.views.messages[0].content\n\\}\n\n`,\n`\n#✨Improve writing[color=#8e44ad][pos=12][trigger=/^润色/]\nBelow is a paragraph from an academic paper. Polish the writing to meet the academic style, improve the spelling, grammar, clarity, concision and overall readability. When necessary, rewrite the whole sentence. Furthermore, list all modification and explain the reasons to do so in markdown table. Paragraph: \"$\\{\nMeet.Global.input.replace(\"润色\", \"\") ||\nMeet.Global.views.messages[0].content\n\\}\"\n`,\n`\n#Clipboard[c=#576CBC][pos=13][trigger=/(剪贴板|复制内容)/]\nThis is the content in my clipboard:\n$\\{Meet.Zotero.getClipboardText()\\}\n---\n$\\{Meet.Global.input\\}\n`,\n`\n#Annotations[c=#F49D1A][pos=14][trigger=/(选中|选择的|选择|所选)?(注释|高亮|标注)/]\nThese are PDF Annotation contents:\n$\\{\nMeet.Zotero.getPDFAnnotations(Meet.Global.input.match(/(选中|选择的|选择|所选)/))\n\\}\n\nPlease answer me in the language of my question. Make sure to cite results using [number] notation after the reference. \nMy question is: $\\{Meet.Global.input\\}\n`,\n`\n#Selection[c=#D14D72][pos=15][trigger=/^(这段|选中)(文本|话|文字|描述)/]\nRead these content:\n$\\{\nMeet.Zotero.getPDFSelection() ||\nMeet.Global.views.messages[0].content\n\\}\n---\nAnswer me in the language of my question. This is my question: $\\{Meet.Global.input\\}\n`,\n  `\n#Item[c=#159895][pos=16][trigger=/这篇(文献|论文|文章)/]\nThis is a Zotero item presented in JSON format:\n$\\{\nJSON.stringify(ZoteroPane.getSelectedItems()[0].toJSON())\n\\}\n\nBase on this JSON: $\\{Meet.Global.input\\}\n`,\n  `\n#Items[c=#159895][pos=17][trigger=/这些(文献|论文)/]\nThese are Zotero items presented in JSON format:\n$\\{\nMeet.Zotero.getRelatedText(Meet.Global.input)\n\\}\n\nPlease answer me using the lanaguage as same as my question. Make sure to cite results using [number] notation after the reference. \nMy question is: $\\{Meet.Global.input\\}\n`,\n]\ndefaultTags = defaultTags.map(parseTag)\n\n\nexport { help, fontFamily, defaultTags, parseTag }"
  },
  {
    "path": "src/modules/localStorage.ts",
    "content": "import { config } from \"../../package.json\";\n\nclass LocalStorage {\n  public filename!: string;\n  public cache: any;\n  public lock: any;\n  constructor(filename: string) {\n    this.lock = Zotero.Promise.defer()\n    this.init(filename)\n  }\n\n  async init(filename: string) {\n    const window = Zotero.getMainWindow();\n    // @ts-ignore\n    const OS = window.OS;\n    if (!(await OS.File.exists(filename))) {\n      const temp = Zotero.getTempDirectory();\n      this.filename = OS.Path.join(temp.path.replace(temp.leafName, \"\"), `${filename}.json`);\n    } else {\n      this.filename = filename\n    }\n    try {\n      const rawString = await Zotero.File.getContentsAsync(this.filename) as string\n      this.cache = JSON.parse(rawString)\n    } catch {\n      this.cache = {}\n    }\n    this.lock.resolve()\n  }\n\n  get(item: Zotero.Item | { key: string }, key: string) {\n    if (this.cache == undefined) { return }\n    return (this.cache[item.key] ??= {})[key]\n  }\n\n  async set(item: Zotero.Item | { key: string }, key: string, value: any) {\n    await this.lock.promise;\n    (this.cache[item.key] ??= {})[key] = value\n    window.setTimeout(async () => {\n      await Zotero.File.putContentsAsync(this.filename, JSON.stringify(this.cache));\n    })\n  }\n}\n\nexport default LocalStorage\n\n"
  },
  {
    "path": "src/modules/locale.ts",
    "content": "import { config } from \"../../package.json\";\n\nexport function initLocale() {\n  addon.data.locale = {\n    stringBundle: Components.classes[\"@mozilla.org/intl/stringbundle;1\"]\n      .getService(Components.interfaces.nsIStringBundleService)\n      .createBundle(`chrome://${config.addonRef}/locale/addon.properties`),\n  };\n}\n\nexport function getString(\n  localString: string,\n  noReload: boolean = false\n): string {\n  try {\n    return addon.data.locale?.stringBundle.GetStringFromName(localString);\n  } catch (e) {\n    if (!noReload) {\n      initLocale();\n      return getString(localString, true);\n    }\n    return localString;\n  }\n}\n"
  },
  {
    "path": "src/modules/utils.ts",
    "content": "import Meet from \"./Meet/api\";\n\nexport default class Utils {\n  constructor() {\n  }\n  public getRGB(color: string) {\n    var sColor = color.toLowerCase();\n    // 十六进制颜色值的正则表达式\n    var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;\n    // 如果是16进制颜色\n    if (sColor && reg.test(sColor)) {\n      if (sColor.length === 4) {\n        var sColorNew = \"#\";\n        for (var i = 1; i < 4; i += 1) {\n          sColorNew += sColor.slice(i, i + 1).concat(sColor.slice(i, i + 1));\n        }\n        sColor = sColorNew;\n      }\n      //处理六位的颜色值\n      var sColorChange = [];\n      for (var i = 1; i < 7; i += 2) {\n        sColorChange.push(parseInt(\"0x\" + sColor.slice(i, i + 2)));\n      }\n      return sColorChange;\n    }\n    return sColor;\n  }\n\n  /**\n   * 兼容旧版\n   * @deprecated\n   * @param queryText \n   * @returns \n   */\n  public async getRelatedText(queryText: string) {\n    return await Meet.Zotero.getRelatedText(queryText)\n  }\n}\n"
  },
  {
    "path": "src/modules/views.ts",
    "content": "import { config } from \"../../package.json\";\nimport Meet from \"./Meet/api\"\nimport Utils from \"./utils\";\nimport { Document } from \"langchain/document\";\nimport { help, fontFamily, defaultTags, parseTag } from \"./base\"\nconst markdown = require(\"markdown-it\")({\n  breaks: true, // 将行结束符\\n转换为 <br> 标签\n  xhtmlOut: true, // 使用 /> 关闭标签，而不是 >\n  typographer: true,\n  html: true,\n});\nconst mathjax3 = require('markdown-it-mathjax3');\nmarkdown.use(mathjax3);\n\nexport default class Views {\n  private id = \"zotero-GPT-container\";\n  /**\n   * OpenAI接口历史消息记录，需要暴露给GPT响应函数\n   */\n  public messages: { role: \"user\" | \"assistant\"; content: string }[] = [];\n  /**\n   * 用于储存历史执行的输入，配合方向上下键来快速回退\n   */\n  private _history: { input: string; output: string }[] = []\n  /**\n   * 用于储存上一个执行的标签，配合 Ctrl + Enter 快速再次执行\n   */\n  private _tag: Tag | undefined;\n  /**\n   * 记录当前GPT输出流setInterval的id，防止终止后仍有输出，需要暴露给GPT响应函数\n   */\n  public _ids: {type: \"follow\"| \"output\", id: number}[] = []\n  /**\n   * 是否在笔记环境下\n   */\n  public isInNote: boolean = true\n  public container!: HTMLDivElement;\n  private inputContainer!: HTMLDivElement;\n  private outputContainer!: HTMLDivElement;\n  private dotsContainer!: HTMLDivElement;\n  private tagsContainer!: HTMLDivElement;\n  private utils: Utils;\n  constructor() {\n    this.utils = new Utils()\n    this.registerKey()\n    this.addStyle()\n    // @ts-ignore\n    window.Meet = Meet\n    Meet.Global.views = this\n  }\n\n  private addStyle() {\n    ztoolkit.UI.appendElement({\n      tag: \"style\",\n      id: `${config.addonRef}-style`,\n      namespace: \"html\",\n      properties: {\n        innerHTML: `\n          @keyframes loading {\n            0%, 100%\n            {\n              opacity: 0.25;\n            }\n            50%\n            {\n              opacity: 0.8;\n            }\n          }\n          #${this.id} .three-dots:hover {\n            opacity: 0.8 !important;\n          }\n          #${this.id} .three-dots.loading .dot:nth-child(1) {\n            animation-delay: 0s;\n          }\n          #${this.id} .three-dots.loading .dot:nth-child(2) {\n            animation-delay: 0.5s;\n          }\n          #${this.id} .three-dots.loading .dot:nth-child(3) {\n            animation-delay: 1s;\n          }\n          #${this.id} .three-dots.loading .dot {\n            animation: loading 1.5s ease-in-out infinite;\n          }\n          #${this.id} ::-moz-selection {\n            background: rgba(89, 192, 188, .8); \n            color: #fff;\n          }\n          #output-container * {\n            font-family: ${fontFamily} !important;\n          }\n          #output-container div p, #output-container div span {\n            marigin: 0;\n            padding: 0;\n            text-align: justify;\n          }\n          .gpt-menu-box .menu-item:hover, .gpt-menu-box .menu-item.selected{\n            background-color: rgba(89, 192, 188, .23) !important;\n          }\n          #${this.id} .tag {\n            position: relative;\n            overflow: hidden;\n          }\n          #${this.id} .ripple {\n            left: 0;\n            top: 50%;\n            position: absolute;\n            background: #fff;\n            transform: translate(-50%, -50%);\n            pointer-events: none;\n            border-radius: 50%;\n            animation: ripple 1.5s linear;\n          }\n          @keyframes ripple {\n            from {\n              width: 0px;\n              height: 0px;\n              opacity: 0.5;\n            }\n            to {\n              width: 500px;\n              height: 500px;\n              opacity: 0;\n            }\n          }\n        `\n      },\n      // #output-container div.streaming span:after,  \n    }, document.documentElement);\n\n    ztoolkit.UI.appendElement({\n      tag: \"link\",\n      id: `${config.addonRef}-link`,\n      properties: {\n        type: \"text/css\",\n        rel: \"stylesheet\",\n        href: `chrome://${config.addonRef}/content/md.css`\n      }\n    }, document.documentElement)\n  }\n\n  /**\n   * 设置GPT回答区域文字\n   * @param text \n   * @param isDone \n   */\n  public setText(text: string, isDone: boolean = false, scrollToNewLine: boolean = true, isRecord: boolean = true,) {\n    this.outputContainer.style.display = \"\"\n    const outputDiv = this.outputContainer.querySelector(\".markdown-body\")! as HTMLDivElement\n    outputDiv.setAttribute(\"pureText\", text);\n    outputDiv.classList.add(\"streaming\");\n    let ready = () => {\n      if (outputDiv.innerHTML.trim() == \"\") {\n        outputDiv.innerHTML = `<p></p>`\n      }\n    }\n    ready()\n    /**\n     * 根据差异渲染，只为保全光标闪烁\n     */\n    let md2html = () => {\n      let result = markdown.render(text)\n        // .replace(/<mjx-assistive-mml[^>]*>.*?<\\/mjx-assistive-mml>/g, \"\")\n      /**\n       * 监测差异，替换节点或文字\n       * @param oldNode \n       * @param newNode \n       * @returns \n       */\n      let diffRender = (oldNode: any, newNode: any) => {\n        if (newNode.nodeName == \"svg\") {\n          oldNode.parentNode.replaceChild(newNode, oldNode)\n          return\n        }\n        if (oldNode.nodeName == \"#text\" && newNode.nodeName == \"#text\") { \n          oldNode.data = newNode.data\n          return\n        } else {\n          if (\n            oldNode.outerHTML == newNode.outerHTML &&\n            oldNode.innerHTML == newNode.innerHTML\n          ) {\n            return\n          }\n        }\n        // 老的比新的多要去除\n        [...oldNode.childNodes].slice(newNode.childNodes.length).forEach((e: any)=>e.remove())\n        for (let i = 0; i < newNode.childNodes.length; i++) {\n          if (i < oldNode.childNodes.length) {\n            if (oldNode.childNodes[i].tagName != newNode.childNodes[i].tagName) {\n              if (oldNode.childNodes[i].tagName == \"#text\") {\n                oldNode.childNodes[i].remove()\n                oldNode.appendChild(newNode.childNodes[i])\n              } else {\n                oldNode.replaceChild(newNode.childNodes[i], oldNode.childNodes[i])\n              }\n              continue\n            } else {\n              diffRender(oldNode.childNodes[i], newNode.childNodes[i])\n            }\n          } else {\n            oldNode.appendChild(newNode.childNodes[i])\n          }\n        }\n      }\n      // 纯文本本身不需要MD渲染，防止样式不一致出现变形\n      let _outputDiv = outputDiv.cloneNode(true) as HTMLDivElement\n      try {\n        _outputDiv.innerHTML = result\n        if (outputDiv.childNodes.length == 0) {\n          outputDiv.innerHTML = result\n        } else {\n          diffRender(outputDiv, _outputDiv)\n        }\n      } catch {\n        outputDiv.innerText = result\n      }\n    }\n    md2html()\n    ready()\n    // @ts-ignore\n    scrollToNewLine && this.outputContainer.scrollBy(0, this.outputContainer.scrollTopMax)\n    if (isDone) {\n      // 任何实时预览的错误到最后，应该因为下面这句消失\n      outputDiv.innerHTML = markdown.render(text)\n      if (isRecord) {\n        this._history.push({ input: Meet.Global.input, output: text })\n      }\n      outputDiv.classList.remove(\"streaming\")\n      if (this.isInNote) {\n        this.hide()\n        // 下面是完成回答后写入 Better Notes 主笔记的两种方案\n        Meet.BetterNotes.insertEditorText(outputDiv.innerHTML)\n        // window.setTimeout(async () => {\n        //   Meet.BetterNotes.insertEditorText(await Zotero.BetterNotes.api.convert.md2html(text))\n        // })\n      }\n    }\n  }\n\n  /**\n   * GPT写的\n   * @param node \n   */\n  private addDragEvent(node: HTMLDivElement) {\n    let posX: number, posY: number\n    let currentX: number, currentY: number\n    let isDragging: boolean = false\n\n    function handleMouseDown(event: MouseEvent) {\n      // 如果是input或textarea元素，跳过拖拽逻辑\n      if (\n        event.target instanceof window.HTMLInputElement ||\n        event.target instanceof window.HTMLTextAreaElement ||\n        (event.target as HTMLDivElement).classList.contains(\"tag\")\n      ) {\n        return\n      }\n      posX = node.offsetLeft - event.clientX\n      posY = node.offsetTop - event.clientY\n      isDragging = true\n    }\n\n    function handleMouseUp(event: MouseEvent) {\n      isDragging = false\n    }\n\n    function handleMouseMove(event: MouseEvent) {\n      if (isDragging) {\n        currentX = event.clientX + posX\n        currentY = event.clientY + posY\n        node.style.left = currentX + \"px\"\n        node.style.top = currentY + \"px\"\n      }\n    }\n\n    // Add event listeners\n    node.addEventListener(\"mousedown\", handleMouseDown)\n    node.addEventListener(\"mouseup\", handleMouseUp)\n    node.addEventListener(\"mousemove\", handleMouseMove)\n  }\n\n\n  /**\n   * GPT写的\n   * @param inputNode \n   */\n  private bindUpDownKeys(inputNode: HTMLInputElement) {\n    // let currentIdx = this._history.length;\n    inputNode.addEventListener(\"keydown\", (e) => {\n      this._history = this._history.filter(i=>i.input)\n      let currentIdx = this._history.map(i=>i.input).indexOf(this.inputContainer!.querySelector(\"input\")!.value)\n      currentIdx = currentIdx == -1 ? this._history.length : currentIdx\n      if (e.key === \"ArrowUp\") {\n        currentIdx--;\n        if (currentIdx < 0) {\n          currentIdx = 0;\n        }\n        inputNode.value = this._history[currentIdx].input || \"\";\n        this.setText(this._history[currentIdx].output, true, false, false)\n      } else if (e.key === \"ArrowDown\") {\n        currentIdx++;\n        if (currentIdx >= this._history.length) {\n          currentIdx = this._history.length;\n          inputNode.value = \"\";\n          this.outputContainer.style.display = \"none\"\n        } else {\n          inputNode.value = this._history[currentIdx].input || \"\";\n          this.setText(this._history[currentIdx].output, true, false, false)\n        }\n      }\n      if ([\"ArrowDown\", \"ArrowUp\"].indexOf(e.key) >= 0) {\n        e.stopPropagation();\n        e.preventDefault();\n        inputNode.setSelectionRange(inputNode.value.length, inputNode.value.length);\n      }\n    });\n  }\n\n  /**\n   * 绑定ctrl+滚轮放大缩小\n   * @param div \n   */\n  private bindCtrlScrollZoom(div: HTMLDivElement) {\n      // 为指定的div绑定wheel事件\n    div.addEventListener('DOMMouseScroll', (event: any) => {\n      // 检查是否按下了ctrl键\n      if (event.ctrlKey || event.metaKey) {\n        let _scale = div.style.transform.match(/scale\\((.+)\\)/)\n        let scale = _scale ? parseFloat(_scale[1]) : 1\n        let minScale = 0.5, maxScale = 2, step = 0.05\n        if (div.style.bottom == \"0px\") {\n          div.style.transformOrigin = \"center bottom\"\n        } else {\n          div.style.transformOrigin = \"center center\"\n        }\n        if (event.detail > 0) {\n          // 缩小\n          scale = scale - step\n          div.style.transform = `scale(${scale < minScale ? minScale : scale})`;\n        } else {\n          // 放大\n          scale = scale + step\n          div.style.transform = `scale(${scale > maxScale ? maxScale : scale})`;\n        }\n      }\n    })\n  }\n\n  /**\n   * 绑定ctrl+滚轮放大缩小控件内的所有元素\n   * @param div\n   */\n  private bindCtrlScrollZoomOutput(div: HTMLDivElement) {\n    const styleAttributes = {\n      fontSize: 'font-size',\n      lineHeight: 'line-height',\n      marginBottom: 'margin-bottom',\n      marginTop: 'margin-top',\n      paddingBottom: 'padding-bottom',\n      paddingTop: 'padding-top',\n    } as const;\n    type StyleAttributeKeys = keyof typeof styleAttributes;\n    type StyleAttributes = {\n      [K in StyleAttributeKeys]: string;\n    };\n    // 获取子元素的初始样式\n    const getChildStyles = (child: Element): StyleAttributes => {\n      const style = window.getComputedStyle(child);\n      const result: Partial<StyleAttributes> = {};\n      for (const key in styleAttributes) {\n        const typedKey = key as StyleAttributeKeys;\n        result[typedKey] = style.getPropertyValue(styleAttributes[typedKey]);\n      }\n      return result as StyleAttributes;\n    };\n  \n    // 更新并应用子元素的样式\n    const applyNewStyles = (child: HTMLElement, style: StyleAttributes, scale: number) => {\n      const newStyle = (value: string) => parseFloat(value) * scale + 'px';\n  \n      for (const key in styleAttributes) {\n        child.style && (child.style[key as StyleAttributeKeys] = newStyle(style[key as StyleAttributeKeys]))\n      }\n    };\n    // 为指定的div绑定wheel事件\n    div.addEventListener('DOMMouseScroll', (event: any) => {\n      const children = div.children[0].children;\n      if (event.ctrlKey || event.metaKey) {\n        const step = 0.05;\n        event.preventDefault();\n        // 阻止事件冒泡\n        event.stopPropagation();\n        const scale = event.detail > 0 ? 1 - step : 1 + step;\n        Array.from(children).forEach((child) => {\n          const childElement = child as HTMLElement;\n          const currentStyle = getChildStyles(child);\n          applyNewStyles(childElement, currentStyle, scale);\n        });\n      }\n    });\n  }\n\n  private buildContainer() {\n    // 顶层容器\n    const container = ztoolkit.UI.createElement(document, \"div\", {\n      id: this.id,\n      styles: {\n        display: \"none\",\n        flexDirection: \"column\",\n        justifyContent: \"flex-start\",\n        alignItems: \"center\",\n        position: \"fixed\",\n        width: Zotero.Prefs.get(`${config.addonRef}.width`) as string,\n        // height: \"4em\",\n        fontSize: \"18px\",\n        borderRadius: \"10px\",\n        backgroundColor: \"#fff\",\n        boxShadow: `0px 1.8px 7.3px rgba(0, 0, 0, 0.071),\n                    0px 6.3px 24.7px rgba(0, 0, 0, 0.112),\n                    0px 30px 90px rgba(0, 0, 0, 0.2)`,\n        fontFamily: fontFamily,\n      }\n    })\n    this.addDragEvent(container)\n    this.bindCtrlScrollZoom(container)\n    // 输入\n    const inputContainer = this.inputContainer = ztoolkit.UI.appendElement({\n      tag: \"div\",\n      id: \"input-container\",\n      styles: {\n        borderBottom: \"1px solid #f6f6f6\",\n        width: \"100%\",\n        display: \"flex\",\n        justifyContent: \"center\",\n        flexDirection: \"column\",\n        alignItems: \"center\",\n      },\n      children: [\n        {\n          tag: \"input\",\n          styles: {\n            width: \"calc(100% - 1.5em)\",\n            height: \"2.5em\",\n            borderRadius: \"10px\",\n            border: \"none\",\n            outline: \"none\",\n            fontFamily: \"Consolas\",\n            fontSize: \".8em\",\n          }\n        },\n        {\n          tag: \"textarea\",\n          styles: {\n            display: \"none\",\n            width: \"calc(100% - 1.5em)\",\n            maxHeight: \"20em\",\n            minHeight: \"2em\",\n            borderRadius: \"10px\",\n            border: \"none\",\n            outline: \"none\",\n            resize: \"vertical\",\n            marginTop: \"0.55em\",\n            fontFamily: \"Consolas\",\n            fontSize: \".8em\"\n\n          }\n        }\n      ]\n\n    }, container) as HTMLDivElement\n    const inputNode = inputContainer.querySelector(\"input\")!\n    this.bindUpDownKeys(inputNode)\n    const textareaNode = inputContainer.querySelector(\"textarea\")!\n    const that = this;\n    let lastInputText = \"\"\n    let inputListener = function (event: KeyboardEvent) {\n      // @ts-ignore\n      if(this.style.display == \"none\") { return }\n      // @ts-ignore\n      let text = Meet.Global.input = this.value\n      if ((event.ctrlKey || event.metaKey) && [\"s\", \"r\"].indexOf(event.key) >= 0 && textareaNode.style.display != \"none\") {\n        // 必定保存，但未必运行\n        const tag = parseTag(text)\n        if (tag) {\n          // @ts-ignore\n          this.value = tag.text\n          let tags = that.getTags()\n          // 如果tags存在，可能是更新，先从tags里将其移除\n          tags = tags.filter((_tag: Tag) => {\n            return _tag.tag != tag.tag\n          })\n          tags.push(tag)\n          that.setTags(tags)\n          that.renderTags();\n          if (event.key == \"s\") {\n            new ztoolkit.ProgressWindow(\"Save Tag\")\n              .createLine({ text: tag.tag, type: \"success\" })\n              .show()\n            return\n          }\n          // 运行代码，并保存标签\n          if (event.key == \"r\") {\n            return that.execTag(tag)\n          }\n        }\n        // 普通文本\n        else {\n          // 运行文本呢\n          if (event.key == \"r\") {\n            // 长文本当作未保存的命令标签执行，长文本里可以写js\n            return that.execTag({tag: \"Untitled\", position: -1, color: \"\", trigger: \"\", text})\n          }\n        }\n      }\n      if (event.key == \"Enter\") { \n        ztoolkit.log(event)\n        \n        outputContainer.querySelector(\".auxiliary\")?.remove()\n\n        // 同时按Ctrl，会点击第一个标签\n        if (event.ctrlKey || event.metaKey) {\n          // 查找第一个点击\n          ztoolkit.log(\"Ctrl + Enter\")\n          let tag = that._tag || that.getTags()[0]\n          return that.execTag(tag)\n        }\n        // 按住Shift，进入长文本编辑模式，此时应该通过Ctrl+R来运行\n        if (event.shiftKey) {\n          if (inputNode.style.display != \"none\") {\n            inputNode.style.display = \"none\"\n            textareaNode.style.display = \"\"\n            textareaNode.focus()\n            textareaNode.value = text + \"\\n\"\n          }\n          return\n        }\n        // 优先级最高，防止中文输入法回车转化成英文\n        if (text.length != lastInputText.length) {\n          lastInputText = text\n          return\n        }\n        if (text.startsWith(\"#\")) {\n          if (inputNode.style.display != \"none\") {\n            inputNode.style.display = \"none\"\n            textareaNode.style.display = \"\"\n            textareaNode.focus()\n            // 判断本地是否存在这个标签\n            const tags = that.getTags();\n            const tag = tags.find((tag: any) => tag.text.startsWith(text.split(\"\\n\")[0]))\n            if (tag) {\n              textareaNode.value = tag.text\n            } else {\n              textareaNode.value = text + \"\\n\"\n            }\n          }\n        } else if (text.startsWith(\"/\")) {\n          that._history.push(text)\n          // 尝试结束其它stream的生命\n          // that._id = undefined\n          that.stopAlloutput()\n          text = text.slice(1)\n          let [key, value] = text.split(\" \")\n          if (key == \"clear\") {\n            that.messages = []\n            // @ts-ignore\n            this.value = \"\"\n            that.setText(\"success\", true, false)\n          } else if (key == \"help\"){ \n            that.setText(help, true, false)\n          } else if (key == \"report\") { \n            const secretKey = Zotero.Prefs.get(`${config.addonRef}.secretKey`) as string\n            // window.setTimeout(() => {\n            //   Zotero.launchURL(\"https://platform.openai.com/account/usage\")\n            // }, 1000)\n            return that.setText(`\\`api\\` ${Zotero.Prefs.get(`${config.addonRef}.api`)}\\n\\`secretKey\\` ${secretKey.slice(0, 3) + \"...\" + secretKey.slice(-4)}\\n\\`model\\` ${Zotero.Prefs.get(`${config.addonRef}.model`)}\\n\\`temperature\\` ${Zotero.Prefs.get(`${config.addonRef}.temperature`)}`, true, false)\n          } else if ([\"secretKey\", \"model\", \"api\", \"temperature\", \"deltaTime\", \"width\", \"tagsMore\", \"chatNumber\", \"relatedNumber\"].indexOf(key) >= 0) {  \n            if (value?.length > 0) {\n              if (value == \"default\") {\n                Zotero.Prefs.clear(`${config.addonRef}.${key}`)\n                value = Zotero.Prefs.get(`${config.addonRef}.${key}`)\n                that.setText(`${key} = ${value}`, true, false)\n                return \n              }\n              switch (key) {\n                case \"deltaTime\":\n                case \"relatedNumber\":\n                case \"chatNumber\":\n                  Zotero.Prefs.set(`${config.addonRef}.${key}`, Number(value))\n                  break;\n                case \"width\":\n                  ztoolkit.log(\"width\", value.match(/^[\\d\\.]+%$/))\n                  if (value.match(/^[\\d\\.]+%$/)) {\n                    that.container.style.width = value\n                    Zotero.Prefs.set(`${config.addonRef}.${key}`, value)\n                    break;\n                  } else {\n                    ztoolkit.log(\"width Error\")\n                    return that.setText(`Invalid value, ${value}, please enter a percentage, for example \\`32 %\\`.`, true, false)\n                  }\n                case \"tagsMore\":\n                  if ([\"scroll\", \"expand\"].indexOf(value) >= 0) {\n                    Zotero.Prefs.set(`${config.addonRef}.${key}`, value)\n                    break;\n                  } else {\n                    ztoolkit.log(\"tagsMore Error\")\n                    return that.setText(`Invalid value, ${value}, please enter \\`expand\\` or \\`scroll\\`.`, true, false)\n                  }\n                default: \n                  Zotero.Prefs.set(`${config.addonRef}.${key}`, value)\n                  break\n              }\n            } else {\n              value = Zotero.Prefs.get(`${config.addonRef}.${key}`)\n            }\n            that.setText(`${key} = ${value}`, true, false)\n            // @ts-ignore\n            this.value = \"\"\n          } else {\n            that.setText(help, true, false)\n            const mdbody = that.outputContainer.querySelector(\".markdown-body\") as HTMLDivElement\n            mdbody.innerHTML = `<center><span style=\"color: #D14D72;font-weight:bold;font-size:20px;\">Invalid Command, Please Read this.</span></center>` + mdbody.innerHTML\n          }\n        } else {\n          that.execText(text)\n          that._history.push(text)\n        }\n      } else if (event.key == \"Escape\") {\n        outputContainer.style.display = \"none\"\n        // 退出长文编辑模式\n        if (textareaNode.style.display != \"none\") {\n          textareaNode.style.display = \"none\"\n          inputNode.value = \"\"\n          inputNode.style.display = \"\"\n          inputNode.focus()\n          return\n        }\n        if (inputNode.value.length) {\n          inputNode.value = \"\"\n          return\n        }\n        // 退出container\n        that.hide()\n        that.container!.remove()\n        that.isInNote && Meet.BetterNotes.reFocus()\n      } else if (event.key == \"/\" && text == \"/\" && that.container.querySelector(\"input\")?.style.display != \"none\") {\n        const rect = that.container.querySelector(\"input\")!.getBoundingClientRect()\n        const commands = [\"clear\", \"help\", \"report\", \"secretKey\", \"model\", \"api\", \"temperature\", \"chatNumber\", \"relatedNumber\" , \"deltaTime\", \"tagsMore\", \"width\"]\n        that.createMenuNode(\n          { x: rect.left, y: rect.top + rect.height, width: 200, height: 350 / 12 * commands.length  },\n          commands.map(name => {\n            return {\n              name,\n              listener: () => {\n                // @ts-ignore\n                this.value = `/${name}`\n              }\n            }\n          }), [2, 6, 8]\n        )\n      }\n      lastInputText = text\n    }\n    inputNode.addEventListener(\"keyup\", inputListener)\n    textareaNode.addEventListener(\"keyup\", inputListener)\n    // 输出\n    const outputContainer = this.outputContainer = ztoolkit.UI.appendElement({\n      tag: \"div\",\n      id: \"output-container\",\n      styles: {\n        width: \"calc(100% - 1em)\",\n        backgroundColor: \"rgba(89, 192, 188, .08)\",\n        color: \"#374151\",\n        maxHeight: document.documentElement.getBoundingClientRect().height * .5 + \"px\",\n        overflowY: \"auto\",\n        overflowX: \"hidden\",\n        padding: \"0.25em 0.5em\",\n        display: \"none\",\n        // resize: \"vertical\"\n      },\n      children: [\n        {\n          tag: \"div\", // Change this to 'div'\n          classList: [\"markdown-body\"],\n          styles: {\n            fontSize: \"0.8em\",\n            lineHeight: \"2em\",\n            // margin: \".5em 0\"\n          },\n          properties: {\n            // 用于复制\n            pureText: \"\"\n          }\n        }\n      ],\n      listeners: [\n        {\n          /**\n           * 双击是插件的输出，可能是插入笔记\n           */\n          type: \"dblclick\",\n          listener: () => {\n            // 无论后面发生什么错误，都确保先复制下来\n            // 目前可能用户的Better Notes版本低，不支持API\n            const text = outputContainer.querySelector(\"[pureText]\")!.getAttribute(\"pureText\") || \"\"\n            new ztoolkit.Clipboard()\n              .addText(text, \"text/unicode\")\n              .copy()\n            const div = outputContainer.cloneNode(true) as HTMLDivElement\n            div.querySelector(\".auxiliary\")?.remove()\n            const htmlString = div.innerHTML\n            if (Zotero_Tabs.selectedIndex == 1 && Zotero.BetterNotes) {\n              Meet.BetterNotes.insertEditorText(htmlString)\n              this.hide()\n              new ztoolkit.ProgressWindow(config.addonName)\n                .createLine({ text: \"Insert To Main Note\", type: \"success\" })\n                .show()\n              return\n            }\n            if (Zotero_Tabs.selectedIndex > 0) {\n              const parentID = Zotero.Items.get(\n                Zotero.Reader.getByTabID(Zotero_Tabs.selectedID)!.itemID as number\n              ).parentID\n              \n              const editor = Zotero.Notes._editorInstances.find(\n                (e) =>\n                  e._item.parentID === parentID && !Components.utils.isDeadWrapper(e._iframeWindow)\n              );\n              ztoolkit.log(editor)\n              // 笔记被打开，且打开笔记视图，才触发向当前条目笔记插入\n              if (editor && document.querySelector(\"#zotero-tb-toggle-notes-pane.toggled\")) {\n                Meet.BetterNotes.insertEditorText(htmlString, editor)\n                new ztoolkit.ProgressWindow(config.addonName)\n                  .createLine({ text: \"Insert To Note\", type: \"success\" })\n                  .show()\n                return\n              }\n            }\n            new ztoolkit.ProgressWindow(config.addonName)\n              .createLine({ text: \"Copy Plain Text\", type: \"success\" })\n              .show()\n          }\n        }\n      ]\n    }, container) as HTMLDivElement\n    this.bindCtrlScrollZoomOutput(outputContainer)\n    // 命令标签\n    const tagsMore = Zotero.Prefs.get(`${config.addonRef}.tagsMore`) as string\n    const tagsContainer = this.tagsContainer = ztoolkit.UI.appendElement({\n      tag: \"div\",\n      classList: [\"tags-container\"],\n      styles: {\n        width: \"calc(100% - .5em)\",\n        display: \"flex\",\n        flexDirection: \"row\",\n        justifyContent: \"flex-start\",\n        alignItems: \"center\",\n        margin: \".25em 0\",\n        flexWrap: tagsMore == \"expand\" ? \"wrap\" : \"nowrap\",\n        overflow: \"hidden\",\n        height: \"1.7em\"\n      },\n      listeners: [\n        {\n          type: \"DOMMouseScroll\",\n          listener: (event: any) => {\n            if (tagsMore == \"expand\") { return }\n            const scrollSpeed = 80\n            // @ts-ignore\n            if (event.detail > 0) {\n              tagsContainer.scrollLeft += scrollSpeed\n            } else {\n              tagsContainer.scrollLeft -= scrollSpeed\n            }\n            event.preventDefault()\n            event.stopPropagation()\n          }\n        }\n      ]\n    }, container) as HTMLDivElement\n    this.dotsContainer = ztoolkit.UI.appendElement({\n      tag: \"div\",\n      classList: [\"three-dots\"],\n      styles: {\n        // width: \"100%\",\n        display: \"flex\",\n        height: \"1em\",\n        justifyContent: \"center\",\n        alignItems: \"center\",\n        marginBottom: \"0.25em\",\n        cursor: \"pointer\",\n        opacity: \".5\",\n        transition: \"opacity .25s linear\"\n      },\n      children: (() => {\n          let arr = []\n          for (let i = 0; i < 3; i++) {\n            arr.push({\n              tag: \"div\",\n              classList: [\"dot\"],\n              styles: {\n                width: \"6px\",\n                height: \"6px\",\n                margin: \"0 .25em\",\n                backgroundColor: \"#ff7675\",\n                borderRadius: \"6px\",\n              },\n            })\n          }\n          return arr\n        })() as any,\n      listeners: [\n        {\n          type: \"click\",\n          listener: () => {\n            if (tagsMore == \"scroll\") { return }\n            tagsContainer.style.height = tagsContainer.style.height == \"auto\" ? \"1.7em\" : \"auto\"\n          }\n        }\n      ]\n    }, container) as HTMLDivElement\n    document.documentElement.append(container)\n    this.renderTags()\n    // 聚焦\n    window.setTimeout(() => {\n      container.focus()\n      inputContainer.focus()\n      inputNode.focus()\n    })\n    return container\n  }\n\n  /**\n   * 渲染标签，要根据position排序\n   */\n  private renderTags() {\n    this.tagsContainer!?.querySelectorAll(\"div\").forEach(e=>e.remove())\n    let tags = this.getTags() as Tag[]\n    tags.forEach((tag: Tag, index: number) => {\n      this.addTag(tag, index)\n    })\n  }\n\n  /**\n   * 添加一个标签\n   */\n  private addTag(tag: Tag, index: number) {\n    let [red, green, blue] = this.utils.getRGB(tag.color)\n    let timer: undefined | number;\n    ztoolkit.UI.appendElement({\n      tag: \"div\",\n      id: `tag-${index}`,\n      classList: [\"tag\"],\n      styles: {\n        display: \"inline-block\",\n        flexShrink: \"0\",\n        fontSize: \"0.8em\",\n        height: \"1.5em\",\n        color: `rgba(${red}, ${green}, ${blue}, 1)`,\n        backgroundColor: `rgba(${red}, ${green}, ${blue}, 0.15)`,\n        borderRadius: \"1em\",\n        border: \"1px solid #fff\",\n        margin: \".25em\",\n        padding: \"0 .8em\",\n        cursor: \"pointer\",\n        whiteSpace: \"nowrap\"\n      },\n      properties: {\n        innerHTML: tag.tag\n      },\n      listeners: [\n        {\n          type: \"mousedown\",\n          listener: (event: any) => {\n            timer = window.setTimeout(() => {\n              timer = undefined\n              if (event.buttons == 1) {                \n                // 进入编辑模式\n                const textareaNode = this.inputContainer?.querySelector(\"textarea\")!\n                const inputNode = this.inputContainer?.querySelector(\"input\")!\n                inputNode.style.display = \"none\";\n                textareaNode.style.display = \"\"\n                textareaNode.value = tag.text\n                this.outputContainer.style!.display = \"none\"\n              } else if (event.buttons == 2) {\n                let tags = this.getTags()\n                tags = tags.filter((_tag: Tag) => _tag.tag != tag.tag)\n                this.setTags(tags)\n                this.renderTags();\n              }\n            }, 1000)\n          }\n        },\n        {\n          type: \"mouseup\",\n          listener: async () => {\n            if (timer) {\n              window.clearTimeout(timer)\n              timer = undefined\n              this.outputContainer.querySelector(\".auxiliary\")?.remove()\n              await this.execTag(tag)\n            }\n          }\n        }\n      ]\n    }, this.tagsContainer!) as HTMLDivElement\n  }\n\n  private rippleEffect(div: HTMLDivElement, color: string) {\n    let [red, green, blue] = this.utils.getRGB(color)\n    ztoolkit.UI.appendElement({\n      tag: \"div\",\n      styles: {\n        backgroundColor: `rgba(${red}, ${green}, ${blue}, 0.5)`\n      },\n      classList: [\"ripple\"]\n    }, div)\n  }\n  /**\n   * 执行标签\n   */\n  private async execTag(tag: Tag) {\n    Meet.Global.input = this.inputContainer.querySelector(\"input\")?.value as string\n    this._tag = tag\n    const popunWin = new ztoolkit.ProgressWindow(tag.tag, { closeTime: -1, closeOtherProgressWindows: true })\n      .show()\n    Meet.Global.popupWin = popunWin\n    popunWin\n      .createLine({ text: \"Generating input content...\", type: \"default\" })\n    this.dotsContainer?.classList.add(\"loading\")\n    this.outputContainer.style.display = \"none\"\n    ztoolkit.log(tag, this.getTags())\n    const tagIndex = this.getTags().map(JSON.stringify).indexOf(JSON.stringify(tag)) as number\n    this.rippleEffect(\n      this.container.querySelector(`#tag-${tagIndex}`)!,\n      tag.color\n    )\n    const outputDiv = this.outputContainer.querySelector(\"div\")!\n    outputDiv.innerHTML = \"\"\n    outputDiv.setAttribute(\"pureText\", \"\");\n    let text = tag.text.replace(/^#.+\\n/, \"\")\n    // 旧版语法不宜传播，MD语法会被转义\n    for (let rawString of text.match(/```j(?:ava)?s(?:cript)?\\n([\\s\\S]+?)\\n```/g)! || []) {\n      let codeString = rawString.match(/```j(?:ava)?s(?:cript)?\\n([\\s\\S]+?)\\n```/)![1]\n      try {\n        text = text.replace(rawString, await window.eval(`${codeString}`))\n      } catch { }\n    }\n    // 新版语法容易分享传播\n    for (let rawString of text.match(/\\$\\{[\\s\\S]+?\\}/g)! || []) {\n      let codeString = rawString.match(/\\$\\{([\\s\\S]+?)\\}/)![1]\n      try {\n        text = text.replace(rawString, await window.eval(`${codeString}`))\n      } catch {  }\n    }\n    popunWin.createLine({ text: `Characters ${text.length}`, type: \"success\" })\n    popunWin.createLine({ text: \"Answering...\", type: \"default\" })\n    // 运行替换其中js代码\n    text = await Meet.OpenAI.getGPTResponse(text) as string\n    this.dotsContainer?.classList.remove(\"loading\")\n    if (text.trim().length) {\n      try {\n        window.eval(`\n          setTimeout(async () => {\n            ${text}\n          })\n        `)\n        popunWin.createLine({ text: \"Code is executed\", type: \"success\" })\n      } catch { }\n      popunWin.createLine({ text: \"Done\", type: \"success\" })\n    } else {\n      popunWin.createLine({ text: \"Done\", type: \"fail\" })\n    }\n    popunWin.startCloseTimer(3000)\n  }\n\n  /**\n   * 执行输入框文本\n   * @param text \n   * @returns \n   */\n  private async execText(text: string) {\n    // 如果文本中存在某一标签预设的关键词|正则表达式，则转为执行该标签\n    const tag = this.getTags()\n      .filter((tag: Tag) => tag.trigger?.length > 0)\n      .find((tag: Tag) => {\n      const trigger = tag.trigger\n      if (trigger.startsWith(\"/\") && trigger.endsWith(\"/\")) {\n        return (window.eval(trigger) as RegExp).test(text)\n      } else {\n        return text.indexOf(trigger as string) >= 0\n      }\n    })\n    if (tag) { return this.execTag(tag) }\n\n    // 没有匹配执行文本\n    this.outputContainer.style.display = \"none\"\n    const outputDiv = this.outputContainer.querySelector(\"div\")!\n    outputDiv.innerHTML = \"\"\n    outputDiv.setAttribute(\"pureText\", \"\");\n    if (text.trim().length == 0) { return }\n    this.dotsContainer?.classList.add(\"loading\")\n    await Meet.OpenAI.getGPTResponse(text)\n    this.dotsContainer?.classList.remove(\"loading\")\n  }\n\n  /**\n   * 从Zotero.Prefs获取所有已保存标签\n   * 按照position顺序排序后返回\n   */\n  private getTags() {\n    // 进行一个简单的处理，应该是中文/表情写入prefs.js导致的bug\n    let tagsJson\n    try {\n      tagsJson = Zotero.Prefs.get(`${config.addonRef}.tags`) as string\n    } catch {}\n    if (!tagsJson) {\n      tagsJson = \"[]\"\n      Zotero.Prefs.set(`${config.addonRef}.tags`, tagsJson)\n    }\n    let tags = JSON.parse(tagsJson)\n    for (let defaultTag of defaultTags) {\n      if (!tags.find((tag: Tag) => tag.tag == defaultTag.tag)) {\n        tags.push(defaultTag)\n      }\n    }\n    return (tags.length > 0 ? tags : defaultTags).sort((a: Tag, b: Tag) => a.position - b.position)\n  }\n\n  private setTags(tags: any[]) {\n    Zotero.Prefs.set(`${config.addonRef}.tags`, JSON.stringify(tags))\n  }\n\n  /**\n   * 下面代码是GPT写的\n   * @param x \n   * @param y \n   */\n  public show(x: number = -1, y: number = -1, reBuild: boolean = true) {\n    reBuild = reBuild || !this.container\n    if (reBuild) {\n      document.querySelectorAll(`#${this.id}`).forEach(e=>e.remove())\n      this.container = this.buildContainer()\n      this.container.style.display = \"flex\"\n    }\n    this.container.setAttribute(\"follow\", \"\")\n    if (x + y < 0) {\n      const rect = document.documentElement.getBoundingClientRect()\n      x = rect.width / 2 - this.container.offsetWidth / 2;\n      y = rect.height / 2 - this.container.offsetHeight / 2;\n    }\n\n    // ensure container doesn't go off the right side of the screen\n    if (x + this.container.offsetWidth > window.innerWidth) {\n      x = window.innerWidth - this.container.offsetWidth\n    }\n\n    // ensure container doesn't go off the bottom of the screen\n    if (y + this.container.offsetHeight > window.innerHeight) {\n      y = window.innerHeight - this.container.offsetHeight\n    }\n\n    // ensure container doesn't go off the left side of the screen\n    if (x < 0) {\n      x = 0\n    }\n\n    // ensure container doesn't go off the top of the screen\n    if (y < 0) {\n      y = 0\n    }\n    // this.container.style.display = \"flex\"\n    this.container.style.left = `${x}px`\n    this.container.style.top = `${y}px`\n    // reBuild && (this.container.style.display = \"flex\")\n  }\n\n  /**\n   * 关闭界面清除所有setInterval\n   */\n  public hide() {\n    this.container.style.display = \"none\"\n    ztoolkit.log(this._ids)\n    this._ids.map(id=>id.id).forEach(window.clearInterval)\n  }\n\n  public stopAlloutput() {\n    this._ids.filter(id => id.type == \"output\").map(i => i.id).forEach(window.clearInterval)\n  }\n\n  /**\n   * 在输出界面插入辅助按钮\n   * 这是一个极具扩展性的函数\n   * 帮助定位，比如定位条目，PDF段落，PDF注释\n   */\n  public insertAuxiliary(docs: Document[]) {\n    this.outputContainer.querySelector(\".auxiliary\")?.remove()\n    const auxDiv = ztoolkit.UI.appendElement({\n      namespace: \"html\",\n      classList: [\"auxiliary\"],\n      tag: \"div\",\n      styles: {\n        display: \"flex\",\n        alignItems: \"center\",\n        justifyContent: \"center\",\n      }\n    }, this.outputContainer)\n    docs.forEach((doc: Document, index: number) => {\n      ztoolkit.UI.appendElement({\n        namespace: \"html\",\n        tag: \"a\",\n        styles: {\n          margin: \".3em\",\n          fontSize: \"0.8em\",\n          cursor: \"pointer\",\n          borderRadius: \"3px\",\n          backgroundColor: \"rgba(89, 192, 188, .43)\",\n          width: \"1.5em\",\n          height: \"1.5em\",\n          textAlign: \"center\",\n          color: \"white\",\n          fontWeight: \"bold\"\n        },\n        properties: {\n          innerText: index + 1\n        },\n        listeners: [\n          {\n            type: \"click\",\n            listener: async () => {\n              if (doc.metadata.type == \"box\") {\n                const reader = await ztoolkit.Reader.getReader();\n                (reader!._iframeWindow as any).wrappedJSObject.eval(`\n                  PDFViewerApplication.pdfViewer.scrollPageIntoView({\n                    pageNumber: ${doc.metadata.box.page + 1},\n                    destArray: ${JSON.stringify([null, { name: \"XYZ\" }, doc.metadata.box.left, doc.metadata.box.top, 3.5])},\n                    allowNegativeOffset: false,\n                    ignoreDestinationZoom: false\n                  })\n                `)\n              } else if (doc.metadata.type == \"id\") {\n                await ZoteroPane.selectItem(doc.metadata.id as number)\n              }\n            }\n          }\n        ]\n      }, auxDiv)\n    })\n  }\n\n  /**\n   * 创建选项\n   */\n  public createMenuNode(\n    rect: { x: number, y: number, width: number, height: number },\n    items: { name: string, listener: Function }[],\n    separators: number[]\n  ) {\n    document.querySelector(\".gpt-menu-box\")?.remove()\n    const removeNode = () => {\n      document.removeEventListener(\"mousedown\", removeNode)\n      document.removeEventListener(\"keydown\", keyDownHandler)\n      window.setTimeout(() => {\n        menuNode.remove()\n      }, 0)\n      this.inputContainer.querySelector(\"input\")?.focus()\n    }\n    document.addEventListener(\"mousedown\", removeNode)\n    let menuNode = ztoolkit.UI.appendElement({\n      tag: \"div\",\n      classList: [\"gpt-menu-box\"],\n      styles: {\n        position: \"fixed\",\n        left: `${rect.x}px`,\n        top: `${rect.y}px`,\n        width: `${rect.width}px`,\n        display: \"flex\",\n        height: `${rect.height}px`,\n        justifyContent: \"space-around\",\n        flexDirection: \"column\",\n        padding: \"6px\",\n        border: \"1px solid #d4d4d4\",\n        backgroundColor: \"#ffffff\",\n        borderRadius: \"8px\",\n        boxShadow: `0px 1px 2px rgba(0, 0, 0, 0.028),\n                                0px 3.4px 6.7px rgba(0, 0, 0, .042),\n                                0px 15px 30px rgba(0, 0, 0, .07)`,\n        overflow: \"hidden\",\n        userSelect: \"none\",\n      },\n      children: (() => {\n        let arr = [];\n        for (let i = 0; i < items.length; i++) {\n          arr.push({\n            tag: \"div\",\n            classList: [\"menu-item\"],\n            styles: {\n              display: \"flex\",\n              alignItems: \"center\",\n              gap: \"8px\",\n              padding: \"4px 8px\",\n              cursor: \"default\",\n              fontSize: \"13px\",\n              borderRadius: \"4px\",\n              whiteSpace: \"nowrap\",\n            },\n            listeners: [\n              {\n                type: \"mousedown\",\n                listener: async (event: any) => {\n                  await items[i].listener()\n                }\n              },\n              {\n                type: \"mouseenter\",\n                listener: function () {\n                  nodes.forEach(e => e.classList.remove(\"selected\"))\n                  // @ts-ignore\n                  this.classList.add(\"selected\")\n                  currentIndex = i\n                }\n              },\n            ],\n            children: [\n              {\n                tag: \"div\",\n                classList: [\"menu-item-name\"],\n                styles: {\n                  paddingLeft: \"0.5em\",\n                },\n                properties: {\n                  innerText: items[i].name\n                }\n              }\n            ]\n          })\n          if (separators.indexOf(i) != -1) {\n            arr.push({\n              tag: \"div\",\n              styles: {\n                height: \"0\",\n                margin: \"6px -6px\",\n                borderTop: \".5px solid #e0e0e0\",\n                borderBottom: \".5px solid #e0e0e0\",\n              }\n            })\n          }\n\n        }\n        return arr\n      })() as any\n    }, document.documentElement)\n    \n    const winRect = document.documentElement.getBoundingClientRect()\n    const nodeRect = menuNode.getBoundingClientRect()\n    // 避免溢出\n    if (nodeRect.bottom > winRect.bottom) {\n      menuNode.style.top = \"\"\n      menuNode.style.bottom = \"0px\"\n    }\n    // menuNode.querySelector(\".menu-item:first-child\")?.classList.add(\"selected\")\n    const nodes = menuNode.querySelectorAll(\".menu-item\")\n    nodes[0].classList.add(\"selected\")\n    let currentIndex = 0\n    this.inputContainer.querySelector(\"input\")?.blur()\n    let keyDownHandler = (event: any) => {\n      ztoolkit.log(event)\n      if (event.code == \"ArrowDown\") {\n        currentIndex += 1\n        if (currentIndex >= nodes.length) {\n          currentIndex = 0\n        }\n      } else if (event.code == \"ArrowUp\") {\n        currentIndex -= 1\n        if (currentIndex < 0) {\n          currentIndex = nodes.length - 1\n        }\n      } else if (event.code == \"Enter\") {\n        items[currentIndex].listener()\n        \n        removeNode()\n      } else if (event.code == \"Escape\") {\n        removeNode()\n      }\n      nodes.forEach(e => e.classList.remove(\"selected\"))\n      nodes[currentIndex].classList.add(\"selected\")\n    }\n    document.addEventListener(\"keydown\", keyDownHandler)\n    return menuNode\n  }\n\n  /**\n   * 绑定快捷键\n   */\n  private registerKey() {\n    const callback = async () => {\n      this.isInNote = false\n      if (Zotero_Tabs.selectedIndex == 0) {\n        const div = document.querySelector(\"#item-tree-main-default .row.selected\")!\n        if (div) {\n          const rect = div.getBoundingClientRect()\n          this.show(rect.x, rect.y + rect.height)\n        } else {\n          this.show()\n        }\n      } else {\n        const reader = await ztoolkit.Reader.getReader()\n        // const div = reader?._iframeWindow?.document.querySelector(\"#selection-menu\")!\n        const div = reader?._iframeWindow?.document.querySelector(\".selection-popup\")!\n        if (div) {\n          window.setTimeout(() => {\n            this.messages = this.messages.concat(\n              [\n                {\n                  role: \"user\",\n                  content: `I am reading a PDF, and the following text is a part of the PDF. Please read it first, and I will ask you some question later: \\n${Meet.Zotero.getPDFSelection()}`\n                },\n                {\n                  role: \"assistant\",\n                  content: \"OK.\"\n                }\n              ]\n            )\n            const rect = div?.getBoundingClientRect()\n            const windRect = document.documentElement.getBoundingClientRect()\n            const ww = windRect.width *\n              0.01 * Number((Zotero.Prefs.get(`${config.addonRef}.width`) as string).slice(0, -1))\n            ww\n            this.show(rect.left + rect.width * .5 - ww * .5, rect.bottom)\n          }, 233)\n        } else {\n          this.show()\n        }\n      }\n    }\n    if (Zotero.isMac) {\n      ztoolkit.Shortcut.register(\"event\", {\n        id: config.addonRef,\n        modifiers: \"meta\",\n        key: \"/\",\n        callback: callback\n      })\n    } else {\n      ztoolkit.Shortcut.register(\"event\", {\n        id: config.addonRef,\n        modifiers: \"control\",\n        key: \"/\",\n        callback: callback\n      })\n    }\n    \n    document.addEventListener(\n      \"keydown\",\n      async (event: any) => {\n        // 笔记内按空格\n        if (\n          Zotero_Tabs.selectedIndex == 1 &&\n          event.explicitOriginalTarget.baseURI.indexOf(\"note-editor\") >= 0 &&\n          event.code == \"Space\" &&\n          Zotero.BetterNotes.api.editor\n        ) {\n          this.isInNote = true\n          const doc = event.explicitOriginalTarget.ownerDocument\n          let selection = doc.getSelection()\n          let range = selection.getRangeAt(0);\n          const span = range.endContainer\n          let text = await Meet.BetterNotes.getEditorText(span)\n          ztoolkit.log(text)\n          this.messages = [{\n            role: \"user\",\n            content: text\n          }]\n          if (/[\\n ]+/.test(span.innerText)) {\n            Meet.BetterNotes.follow(span)\n            event.preventDefault();\n          }\n          return \n        }\n        if (\n          (event.shiftKey && event.key.toLowerCase() == \"?\") ||\n          (event.key == \"/\" && Zotero.isMac)) {\n          if (\n            event.originalTarget.isContentEditable ||\n            \"value\" in event.originalTarget\n          ) {\n            return;\n          }\n          \n        }\n      },\n      true\n    );\n  }\n}\n\n"
  },
  {
    "path": "tags/Abstract2Introduction.txt",
    "content": "#摘要转综述[pos=1]\n\n下面是一篇论文的摘要：\n\n```js\nconst ztoolkit = Zotero.ZoteroGPT.data.ztoolkit\nlet getSelection = () => {\n    return ztoolkit.Reader.getSelectedText(\n Zotero.Reader.getByTabID(Zotero_Tabs.selectedID)\n    );\n}\ngetSelection()\n```\n\n\n现在我想引用它写一篇文献综述，请你帮我写几句话总结这篇论文的工作，作者没有告诉你，你可以用XX代替。我要中文的。要求50字左右。\n\n---\n\n使用场景: 选中PDF的摘要的时候"
  },
  {
    "path": "tags/Add-Controlled-Tagger",
    "content": "@Zotero GPT Tag\n#Tags[color=#0EA253][trigger=/^生成标签/]\n${\n(async () => {\n  // =========================\n  // 0) 受控词表 + 与 zotero-gpt 对接的小工具\n  // =========================\n  const CONTROLLED = new Set([\n    \"#Field/BuildingEnergyConsumption\",\n    \"#Field/IndoorThermalComfort\",\n    \"#Field/IndoorAirQuality\",\n    \"#Object/RuralResidence\",\n    \"#Method/MachineLearning\",\n    \"#Method/CFD\",\n    \"#Method/Experiment\",\n    \"#Type/Review\"\n  ]);\n\n  // ========== 新增：ProgressWindow 通知封装（最小侵入） ==========\n  const PW = (() => {\n    let pw = null;\n    let lines = [];\n\n    const iconMap = {\n      info:    \"chrome://zotero/skin/information.png\",\n      success: \"chrome://zotero/skin/tick.png\",\n      warning: \"chrome://zotero/skin/warning.png\",\n      error:   \"chrome://zotero/skin/cross.png\",\n    };\n\n    function ensure() {\n      try {\n        if (!Zotero?.ProgressWindow) return null;\n        if (!pw) {\n          pw = new Zotero.ProgressWindow();\n          pw.changeHeadline(\"智能标签生成\");\n          pw.setProgress(100);\n        }\n        return pw;\n      } catch { return null; }\n    }\n\n    function showLine(msg, type = \"info\") {\n      const _pw = ensure();\n      if (_pw) {\n        _pw.addDescription(String(msg), iconMap[type] || iconMap.info);\n        _pw.show();\n      } else {\n        console.log(`[Tags][${type}] ${msg}`);\n      }\n    }\n\n    function startStep(msg) {\n      lines.push(String(msg));\n      const _pw = ensure();\n      if (_pw) {\n        _pw.addDescription(String(msg));\n        _pw.show();\n      } else {\n        console.log(`[Tags][STEP] ${msg}`);\n      }\n    }\n\n    function update(msgOrArray) {\n      const _pw = ensure();\n      if (!_pw) {\n        if (Array.isArray(msgOrArray)) msgOrArray.forEach(m => console.log(`[Tags] ${m}`));\n        else console.log(`[Tags] ${msgOrArray}`);\n        return;\n      }\n      // 简单策略：每次追加一行（避免复杂 diff）\n      const arr = Array.isArray(msgOrArray) ? msgOrArray : [msgOrArray];\n      arr.forEach(m => _pw.addDescription(String(m)));\n      _pw.show();\n    }\n\n    function close(afterMs = 1200) {\n      const _pw = ensure();\n      if (_pw) _pw.startCloseTimer(afterMs);\n    }\n\n    return { showLine, startStep, update, close };\n  })();\n\n  // ---------- 新增：格式规则 ----------\n  const TAXON_PREFIXES = [\"#Field/\",\"#Object/\",\"#Method/\",\"#Type/\"];\n  const isFormattedTag = (s) => {\n    if (!s) return false;\n    const t = String(s).replace(/\\u00A0/g,\" \").trim();\n    return /^#(Field|Object|Method|Type)\\/[A-Za-z0-9_\\-\\/.]+$/.test(t);\n  };\n  const normalizeTag = (s) => String(s ?? \"\")\n    .replace(/\\u00A0/g,\" \")\n    .replace(/[“”]/g,'\"')\n    .trim();\n\n  // ---------- 更稳健：从任意文本中抽 JSON 数组 ----------\n  const extractJsonArray = (txt) => {\n    if (!txt) return null;\n    let s = String(txt)\n      .replace(/^[\\s\\S]*?(\\[)/, \"$1\")\n      .replace(/(\\])[\\s\\S]*$/, \"$1\")\n      .replace(/[“”]/g, '\"');\n    const m = s.match(/\\[[\\s\\S]*\\]/);\n    if (!m) return null;\n    try {\n      const arr = JSON.parse(m[0]);\n      if (!Array.isArray(arr)) return null;\n      return arr.map(x => normalizeTag(x)).filter(Boolean);\n    } catch(_) { return null; }\n  };\n\n  // ---------- 新增：获取 Zotero 库里“已存在的格式化标签” ----------\n  const getAllFormattedTagsInLibrary = async () => {\n    const out = new Set();\n    const lower2canon = new Map();\n    try {\n      if (Zotero?.Tags?.getAll) {\n        const all = await Zotero.Tags.getAll();\n        for (const t of (all || [])) {\n          const name = normalizeTag(typeof t === \"string\" ? t : (t?.name || t?.tag || \"\"));\n          if (isFormattedTag(name)) {\n            out.add(name);\n            lower2canon.set(name.toLowerCase(), name);\n          }\n        }\n      }\n    } catch (_) {}\n\n    try {\n      const ts = ZoteroPane?.tagSelector;\n      const list = (ts?.getTags && ts.getTags()) || ts?._tags || [];\n      for (const t of list) {\n        const name = normalizeTag(typeof t === \"string\" ? t : (t?.name || t?.tag || \"\"));\n        if (isFormattedTag(name)) {\n          out.add(name);\n          lower2canon.set(name.toLowerCase(), name);\n        }\n      }\n    } catch (_) {}\n\n    return { formattedSet: out, lower2canon };\n  };\n\n  // ---------- LLM 提示词 ----------\n  const askLLMForTags = async (controlledListString, paperText) => {\n    const prompt = `\nRead the abstract/fulltext below and output 3–5 tags ONLY as a JSON array.\n\nRules:\n- Each tag MUST strictly follow these namespaces and format:\n  \"#Field/<Name>\" or \"#Object/<Name>\" or \"#Method/<Name>\" or \"#Type/<Name>\"\n- Use \"/\" to separate the top-level namespace and the name (e.g., \"#Field/IndoorThermalComfort\").\n- Prefer concepts in the controlled list when applicable; otherwise generate appropriate custom tags that still follow the format above.\n- Output ONLY the JSON array (no prose, no code fence, no comments).\n\nControlled list (for reference):\n${controlledListString}\n\nAbstract / Text:\n${paperText}\n\nExample of the ONLY acceptable output format:\n[\"#Field/IndoorThermalComfort\",\"#Method/CFD\",\"#Object/Furniture\"]\n    `.trim();\n\n    PW.startStep(\"调用 LLM 生成标签…\");\n    const res = await Meet?.Global?.views?.ask?.(prompt);\n    const parsed = extractJsonArray(res);\n    if (!parsed) PW.showLine(\"LLM 未返回有效 JSON 数组，尝试兜底策略\", \"warning\");\n    return parsed;\n  };\n\n  // =========================\n  // 1) 必要的保留函数\n  // =========================\n  const safe = (v, f=\"\") => {\n    if (v===undefined || v===null) return f;\n    return String(v).replace(/\\u00A0/g,\" \").trim();\n  };\n\n  const getTagsSafe = (top) => {\n    try {\n      if (typeof top?.getTags === \"function\") {\n        const tags = top.getTags() || [];\n        return tags.map(t => safe(t?.tag || t?.name, \"\")).filter(Boolean);\n      }\n    } catch(e) {}\n    return [];\n  };\n\n  // ---------- 新增：对 LLM 输出做“库中已存在标签优先匹配”的映射 ----------\n  const mapToExistingOrAcceptCustom = (llmTags, existingSet, lower2canon) => {\n    const chosen = [];\n    const seen = new Set();\n    for (const raw of (llmTags || [])) {\n      const t = normalizeTag(raw);\n      if (!isFormattedTag(t)) continue;\n      const lower = t.toLowerCase();\n      const canon = lower2canon.get(lower);\n      const finalTag = canon || t;\n      if (!seen.has(finalTag)) {\n        chosen.push(finalTag);\n        seen.add(finalTag);\n      }\n    }\n    return chosen.slice(0, 5);\n  };\n\n  // ---------- 修改：applyTags 增加进度提示 ----------\n  const applyTagsToZotero = async (topItem, tagList) => {\n    if (!topItem || !Array.isArray(tagList) || !tagList.length) return;\n    try {\n      const existingTags = getTagsSafe(topItem);\n      const existingTagNames = new Set(existingTags.map(normalizeTag));\n\n      const wanted = Array.from(new Set(\n        tagList\n          .map(normalizeTag)\n          .filter(t => isFormattedTag(t) && !existingTagNames.has(t))\n      ));\n\n      if (!wanted.length) {\n        PW.showLine(\"推荐标签已存在，无需添加\", \"info\");\n        return;\n      }\n\n      PW.startStep(`添加 ${wanted.length} 个标签…`);\n      for (const tagName of wanted) {\n        if (typeof topItem.addTag === \"function\") topItem.addTag(tagName);\n      }\n\n      if (typeof topItem.saveTx === \"function\")           await topItem.saveTx();\n      else if (typeof topItem.save === \"function\")        await topItem.save();\n      else if (typeof topItem.saveChanges === \"function\") await topItem.saveChanges();\n\n      PW.showLine(`成功添加：${wanted.join(\", \")}`, \"success\");\n    } catch (e) {\n      PW.showLine(`添加标签失败：${e.message}`, \"error\");\n      console.error(\"[Tags] Failed to add tags to Zotero:\", e);\n    }\n  };\n\n  const stripReferences = (raw) => {\n    if (!raw) return raw;\n    const lines = raw.split(/\\r?\\n/);\n    const lower = lines.map(l => l.trim().toLowerCase());\n    const refHeadings = [\"references\",\"参考文献\",\"bibliography\",\"works cited\",\"literature cited\"];\n    const tailHeadings = [\"declaration of competing interest\",\"conflict of interest\",\"credit authorship contribution statement\",\"acknowledgements\",\"acknowledgments\",\"作者贡献\",\"致谢\",\"资金支持\",\"funding\",\"appendix\",\"附录\"];\n    let cutIdx = -1;\n    for (let i = lines.length - 1; i >= 0; i--) {\n      const s = lower[i];\n      if (!s) continue;\n      if (refHeadings.some(h => s === h || s.startsWith(h))) { cutIdx = i; break; }\n    }\n    if (cutIdx < 0) {\n      const startTail = Math.floor(lines.length * 0.6);\n      for (let i = startTail; i < lines.length; i++) {\n        const s = lower[i];\n        if (tailHeadings.some(h => s === h || s.startsWith(h))) { cutIdx = i; break; }\n      }\n    }\n    const isRefLine = (s) => /^\\s*(\\[\\d+\\]|\\d+\\.)\\s+/.test(s) || (/^[A-Z][A-Za-z\\-']+(,\\s*[A-Z]\\.){1,3}.*\\(\\d{4}\\)/.test(s));\n    if (cutIdx < 0) {\n      const start = Math.floor(lines.length * 0.6);\n      let consec = 0, startIdx = -1;\n      for (let i = start; i < lines.length; i++) {\n        if (isRefLine(lines[i])) { if (startIdx < 0) startIdx = i; consec++; }\n        else if (consec > 0) { if (consec >= 5) { cutIdx = startIdx; break; } consec = 0; startIdx = -1; }\n      }\n      if (cutIdx < 0 && consec >= 5) cutIdx = startIdx;\n    }\n    return (cutIdx >= 0) ? lines.slice(0, cutIdx).join(\"\\n\").trim() : raw;\n  };\n\n  // ========== 若无法提取文本，则上传 PDF 给 LLM ==========\n  const uploadPdfIfNoText = async (pdfItem, extractedTxt) => {\n    try {\n      if (!pdfItem) return false;\n      const empty = !extractedTxt || String(extractedTxt).trim() === \"\";\n      if (!empty) return false;\n      const up = window?.Meet?.OpenAI?.uploadFile;\n      if (typeof up !== \"function\") return false;\n      PW.startStep(\"未提取到文本，上传 PDF 给 LLM…\");\n      await up([pdfItem]);\n      PW.showLine(\"PDF 已上传至 LLM\", \"success\");\n      return true;\n    } catch (e) {\n      PW.showLine(`PDF 上传失败：${e.message}`, \"error\");\n      return false;\n    }\n  };\n\n  // =========================\n  // 2) 选取单一 PDF 目标\n  // =========================\n  PW.showLine(\"开始生成智能标签…\", \"info\");\n\n  const isLibEnv = (typeof Zotero_Tabs !== \"undefined\");\n  const isLibrary = isLibEnv && (Zotero_Tabs.selectedType === \"library\");\n  const isReader  = isLibEnv && (Zotero_Tabs.selectedType === \"reader\");\n\n  let pdfItem = null;\n\n  if (isReader && typeof Zotero?.Reader?.getByTabID === \"function\") {\n    const reader = Zotero.Reader.getByTabID(Zotero_Tabs.selectedID);\n    pdfItem = reader?._item || reader?.item || null;\n  } else if (isLibrary && typeof ZoteroPane !== \"undefined\" && typeof ZoteroPane.getSelectedItems === \"function\") {\n    const items = ZoteroPane.getSelectedItems() || [];\n    if (items.length) {\n      const first = items[0];\n      const isPdf = (() => {\n        try { return first?.isPDFAttachment && first.isPDFAttachment(); } catch (_) { return false; }\n      })();\n\n      if (isPdf) {\n        pdfItem = first;\n      } else {\n        try {\n          if (typeof first?.getBestAttachmentState === \"function\" && typeof first?.getBestAttachment === \"function\") {\n            const st = await first.getBestAttachmentState();\n            if (st?.exists) {\n              const best = await first.getBestAttachment();\n              if (best?.isPDFAttachment && best.isPDFAttachment()) {\n                pdfItem = best;\n              }\n            }\n          }\n        } catch (_) {}\n        if (!pdfItem && typeof first?.getAttachments === \"function\") {\n          try {\n            const childIds = first.getAttachments() || [];\n            for (const cid of childIds) {\n              const ch = Zotero.Items.get(cid);\n              if (ch?.isPDFAttachment && ch.isPDFAttachment()) { pdfItem = ch; break; }\n            }\n          } catch (_) {}\n        }\n      }\n    }\n  }\n\n  if (!pdfItem) {\n    PW.showLine(\"未找到 PDF 附件，请选择包含 PDF 的文献项\", \"error\");\n    PW.close(3000);\n    return \"\";\n  }\n\n  const targets = [{ item: pdfItem, number: 1 }];\n  const CONTROLLED_LIST_STRING = Array.from(CONTROLLED).join(\"\\n\");\n\n  // 预抓库中格式化标签\n  PW.startStep(\"读取库内已存在的格式化标签…\");\n  const { formattedSet: LIB_FORMATTED_SET, lower2canon: LIB_LC2CANON } = await getAllFormattedTagsInLibrary();\n\n  for (const { item: pdfItem, number } of targets) {\n    try {\n      const top = pdfItem?.topLevelItem || pdfItem;\n\n      // 提取文本\n      PW.startStep(\"提取 PDF 文本…\");\n      let textRaw = \"\";\n      try {\n        if (typeof Zotero?.PDFWorker?.getFullText === \"function\") {\n          const ft = await Zotero.PDFWorker.getFullText(pdfItem.id, null);\n          textRaw = safe(ft?.text, \"\");\n        }\n      } catch (_) { textRaw = \"\"; }\n\n      await uploadPdfIfNoText(pdfItem, textRaw);\n\n      const text = stripReferences(textRaw);\n      const payload = text || \"(no fulltext extracted)\";\n\n      // 调 LLM\n      const arr = await askLLMForTags(CONTROLLED_LIST_STRING, payload);\n\n      // 匹配/接受\n      let candidateTags = mapToExistingOrAcceptCustom(arr, LIB_FORMATTED_SET, LIB_LC2CANON);\n\n      if (!candidateTags.length) {\n        candidateTags = [\"#Field/BuildingEnergyConsumption\",\"#Method/MachineLearning\",\"#Object/Furniture\"]\n          .filter(t => CONTROLLED.has(t))\n          .slice(0, 3);\n        PW.showLine(\"LLM 未返回有效标签，使用兜底标签\", \"warning\");\n      } else {\n        PW.showLine(`LLM 返回标签：${candidateTags.join(\", \")}`, \"info\");\n      }\n\n      // 写入\n      if (candidateTags.length) {\n        await applyTagsToZotero(top, candidateTags);\n      }\n    } catch (e) {\n      PW.showLine(`处理失败：${e.message}`, \"error\");\n      console.error(\"(处理失败)\", e);\n    }\n  }\n\n  PW.showLine(\"标签生成流程完成\", \"success\");\n  PW.close(1800);\n\n  return \"\";\n})();  // IIFE 结束\n}$\n"
  },
  {
    "path": "tags/AddTags.txt",
    "content": "#🔭AddTags[position=9][color=#B7A7DB]\n\n下面是我在Zotero里创建的一些嵌套标签，它们以#开头，中间用/连接：\n```js\nZotero.ZoteroGPT.views.messages = [];\nJSON.stringify(Zotero.ZoteroStyle.data.views.tagsUI.plainTags.slice(0, 20))\n```\n---\n这是一篇文献的摘要：\n```js\nZoteroPane.getSelectedItems()[0].getField(\"abstractNote\")\n```\n---\n\n请你帮我根据我已有的嵌套标签，分析出我该给这篇文献添加什么嵌套标签，请你推荐三个，并给我一段代码，这段代码将在Zotero里执行，下面是示例代码：  \n```js\nconst tags = [\"#tag1/tag2/tag3\", \"#tag1/tag2/tag3\", \"#tag1/tag2/tag3\"]\nitem = ZoteroPane.getSelectedItems()[0]\ntags.forEach(tag=>{\n  item.addTag(tag)\n})\nawait item.saveTx()\n```\n---\n你只需要回答我代码，除了代码你不需要进行任何文字描述，你给出代码是："
  },
  {
    "path": "tags/AskAbstract.txt",
    "content": "#摘要提问[pos=0]\n\n下面是一篇论文的摘要：\n\n```js\nconst ztoolkit = Zotero.ZoteroGPT.data.ztoolkit\nlet getSelection = () => {\n    return ztoolkit.Reader.getSelectedText(\n Zotero.Reader.getByTabID(Zotero_Tabs.selectedID)\n    );\n}\ngetSelection()\n```"
  },
  {
    "path": "tags/AskClipboard.txt",
    "content": "#📄AskClipboard[position=9][color=#dc4334]\n\nRead this:\n\n```js\n\nZotero.ZoteroGPT.utils.getClipboardText()\n\n```\n\n---\n\nplease answer this question based on above content (use 简体中文)：  \n```js\nZotero.ZoteroGPT.views.inputContainer.querySelector(\"input\").value\n```"
  },
  {
    "path": "tags/AskExperimentDetails.txt",
    "content": "#总结实验方法[pos=9]\n\n请用子弹列表的形式提取该段落的信息，包括，被试数量，实验设计(如, 2(Gender: male vs female) X 2(Matching Condition: matching or mismatching))，实验流程(如，被试首先观看刺激，然后进行反应，最后呈现反馈给被试)。务必使用中文回答。  \n下面是论文的方法部分：  \n```js\nconst ztoolkit = Zotero.ZoteroGPT.data.ztoolkit\nlet getSelection = () => {\n    return ztoolkit.Reader.getSelectedText(\n Zotero.Reader.getByTabID(Zotero_Tabs.selectedID)\n    );\n}\nztoolkit.log(getSelection())\ngetSelection()\n```\n\n---\n\n选中PDF文字时候"
  },
  {
    "path": "tags/AskJournal.txt",
    "content": "#期刊介绍[pos=9]\n\n介绍一下下面这个期刊：  \n```js\nZoteroPane.getSelectedItems()[0].getField(\"publicationTitle\")\n```\n\n---\n\n应用场景: 选中主界面条目时候\n"
  },
  {
    "path": "tags/AskPDF.txt",
    "content": "#🪐AskPDF[pos=0][color=#009FBD]\n\nYou are a helpful assistant. Context information is below.\n\n---\n```js\nwindow.gptInputString = Zotero.ZoteroGPT.views.inputContainer.querySelector(\"input\").value\nZotero.ZoteroGPT.views.messages = [];\n\nZotero.ZoteroGPT.utils.getRelatedText(\nwindow.gptInputString \n)\n\n```\n---\n\nCurrent date:   \n```js\nString(new Date())\n```\nUsing the provided context information, write a comprehensive reply to the given query. Make sure to cite results using [number] notation after the reference. If the provided context information refer to multiple subjects with the same name, write separate answers for each subject. Use prior knowledge only if the given context didn't provide enough information. \n\nAnswer the question:\n```js\nwindow.gptInputString \n```\n\nReply in 简体中文\n"
  },
  {
    "path": "tags/Readme.md",
    "content": "## About Tag\n\nYou can long click on the tag below to see its internal pseudo-code.\nYou can type #xxx and enter to create a tag and save it with Ctrl + S, during which you can execute it with Ctrl + R.\nYou can right-click and long-click a tag to delete it.\n\n## About Output Text\nYou can double click on this text to copy GPT's answer.\nYou can long press me without releasing, then move me to a suitable position before releasing.\n\n## About Input Text\nYou can type the question in my header, enter and ask me a question.\nYou can exit me by pressing Esc above my head and wake me up by pressing Shift + / in the Zotero window."
  },
  {
    "path": "tags/SearchItems.txt",
    "content": "#🔍SearchItems[position=9][color=#ED5629]\n\n现在你是一个数据库系统，下面是一些JSON信息，每个JSON对应Zotero一篇文献：\n\n---\n\n```js\nwindow.gptInputString = Zotero.ZoteroGPT.views.inputContainer.querySelector(\"input\").value\nZotero.ZoteroGPT.views.messages = [];\n\nZotero.ZoteroGPT.utils.getRelatedText(\nwindow.gptInputString \n)\n\n```\n\n---\n\n我现在在寻找一篇文献，它很可能就在我上面给你的文献之中。下面是对我想找的文献的描述：\n```js\nwindow.gptInputString \n```\n\n请你回答最有可能是哪几篇文献，请同时给出最可能的一篇。\n\nReply in 简体中文"
  },
  {
    "path": "tags/Translate.txt",
    "content": "#🎈Translate[pos=1][c=#21a2f1]\n\ntranslate these from english to 简体中文:\n```js\nZotero.ZoteroGPT.utils.getPDFSelection()\n```"
  },
  {
    "path": "tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"experimentalDecorators\": true,\n    \"module\": \"commonjs\",\n    \"target\": \"ES2016\",\n    \"resolveJsonModule\": true,\n    \"skipLibCheck\": true,\n    \"strict\": true\n  },\n  \"include\": [\"src\", \"typing\", \"node_modules/zotero-types\"],\n  \"exclude\": [\"builds\", \"addon\"]\n}\n"
  },
  {
    "path": "typing/global.d.ts",
    "content": "declare const _globalThis: {\n  [key: string]: any;\n  Zotero: _ZoteroTypes.Zotero;\n  ZoteroPane: _ZoteroTypes.ZoteroPane;\n  Zotero_Tabs: typeof Zotero_Tabs;\n  window: Window;\n  document: Document;\n  ztoolkit: typeof ztoolkit;\n  addon: typeof addon;\n};\n\ndeclare const ztoolkit: import(\"zotero-plugin-toolkit\").ZoteroToolkit;\n\ndeclare const rootURI: string;\n\ndeclare const addon: import(\"../src/addon\").default;\n\ndeclare const __env__: \"production\" | \"development\";\n\n\ndeclare type PDFLine = {\n  x: number,\n  _x?: number,\n  y: number,\n  text: string,\n  height: number,\n  _height: number[],\n  width: number,\n  url?: string,\n}\n\ndeclare type PDFItem = {\n  chars: {\n    baseline: number;\n    c: string;\n    fontName: string;\n    fontSize: number;\n    rect: number[];\n    rotation: number;\n  }[];\n  dir: string;\n  fontName: string;\n  height: number;\n  str: string;\n  transform: number[];\n  width: number;\n  url?: string;\n}\n\ndeclare type PDFAnnotation = {\n  rect: number[];\n  url?: string;\n  unsafeUrl?: string;\n}\n\ninterface Rect {\n  bottom: number;\n  height: number;\n  left: number;\n  right: number;\n  top: number;\n  width: number;\n  x: number;\n  y: number;\n}\ninterface Tag { tag: string; color: string; position: number, trigger: string, text: string }"
  },
  {
    "path": "update-template.json",
    "content": "{\n  \"addons\": {\n    \"__addonID__\": {\n      \"updates\": [\n        {\n          \"version\": \"__buildVersion__\",\n          \"update_link\": \"__releasepage__\",\n          \"applications\": {\n            \"gecko\": {\n              \"strict_min_version\": \"60.0\"\n            }\n          }\n        },\n        {\n          \"version\": \"__buildVersion__\",\n          \"update_link\": \"__releasepage__\",\n          \"applications\": {\n            \"zotero\": {\n              \"strict_min_version\": \"6.999\"\n            }\n          }\n        }\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "update-template.rdf",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" xmlns:em=\"http://www.mozilla.org/2004/em-rdf#\">\n  <rdf:Description rdf:about=\"urn:mozilla:extension:__addonID__\">\n    <em:updates>\n      <rdf:Seq>\n        <rdf:li>\n          <rdf:Description>\n            <em:version>__buildVersion__</em:version>\n            <em:targetApplication>\n              <rdf:Description>\n                <em:id>zotero@chnm.gmu.edu</em:id>\n                <em:minVersion>6.999</em:minVersion>\n                <em:maxVersion>*</em:maxVersion>\n                <em:updateLink>__releasepage__</em:updateLink>\n              </rdf:Description>\n            </em:targetApplication>\n            <em:targetApplication>\n              <rdf:Description>\n                <em:id>juris-m@juris-m.github.io</em:id>\n                <em:minVersion>6.999</em:minVersion>\n                <em:maxVersion>*</em:maxVersion>\n                <em:updateLink>__releasepage__</em:updateLink>\n              </rdf:Description>\n            </em:targetApplication>\n          </rdf:Description>\n        </rdf:li>\n      </rdf:Seq>\n    </em:updates>\n  </rdf:Description>\n</rdf:RDF>"
  },
  {
    "path": "update.json",
    "content": "{\n  \"addons\": {\n    \"zoterogpt@polygon.org\": {\n      \"updates\": [\n        {\n          \"version\": \"0.2.9\",\n          \"update_link\": \"\",\n          \"applications\": {\n            \"gecko\": {\n              \"strict_min_version\": \"60.0\"\n            }\n          }\n        },\n        {\n          \"version\": \"0.2.8\",\n          \"update_link\": \"\",\n          \"applications\": {\n            \"zotero\": {\n              \"strict_min_version\": \"6.999\"\n            }\n          }\n        }\n      ]\n    }\n  }\n}\n"
  },
  {
    "path": "update.rdf",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" xmlns:em=\"http://www.mozilla.org/2004/em-rdf#\">\n  <rdf:Description rdf:about=\"urn:mozilla:extension:zoterogpt@polygon.org\">\n    <em:updates>\n      <rdf:Seq>\n        <rdf:li>\n          <rdf:Description>\n            <em:version>0.2.9</em:version>\n            <em:targetApplication>\n              <rdf:Description>\n                <em:id>zotero@chnm.gmu.edu</em:id>\n                <em:minVersion>6.999</em:minVersion>\n                <em:maxVersion>*</em:maxVersion>\n                <em:updateLink></em:updateLink>\n              </rdf:Description>\n            </em:targetApplication>\n            <em:targetApplication>\n              <rdf:Description>\n                <em:id>juris-m@juris-m.github.io</em:id>\n                <em:minVersion>6.999</em:minVersion>\n                <em:maxVersion>*</em:maxVersion>\n                <em:updateLink></em:updateLink>\n              </rdf:Description>\n            </em:targetApplication>\n          </rdf:Description>\n        </rdf:li>\n      </rdf:Seq>\n    </em:updates>\n  </rdf:Description>\n</rdf:RDF>\n"
  }
]