[
  {
    "path": ".dockerignore",
    "content": ".git/\nmodules/translators/\nDockerfile\ndocker-compose.*\nnpm-debug.log\nnode_modules/\n"
  },
  {
    "path": ".eslintignore",
    "content": "connectorTypeSchemaData.js\nmodules\nsrc/rdf/*\n"
  },
  {
    "path": ".eslintrc",
    "content": "{\n\t\"env\": {\n\t\t\"es6\": true,\n\t\t\"node\": true,\n\t\t\"mocha\": true\n\t},\n\t\"globals\": {\n\t\t\"Zotero\": false\n\t},\n\t\"extends\": [\n\t\t\"@zotero\"\n\t],\n\t\"parserOptions\": {\n\t\t\"ecmaVersion\": 2018\n\t},\n\t\"rules\": {}\n}\n"
  },
  {
    "path": ".github/workflows/ci.yml",
    "content": "name: CI\non: [push, pull_request]\njobs:\n  build:\n    name: Test\n    runs-on: ubuntu-latest\n    timeout-minutes: 5\n    strategy:\n      matrix:\n        node-version: [20, 22, 24, 25]\n    \n    steps:\n      - uses: actions/checkout@v2\n      \n      - run: git submodule update --init --depth=1 modules/translate\n      - run: git submodule update --init --depth=1 modules/utilities\n      - run: git submodule update --init --depth=1 modules/zotero-schema\n      - run: git submodule update --init --depth=1 modules/translators\n      \n      - name: Install Node ${{ matrix.node-version }}\n        uses: actions/setup-node@v2\n        with:\n          node-version: ${{ matrix.node-version }}\n      \n      - run: npm ci\n      - run: npm test\n"
  },
  {
    "path": ".gitignore",
    "content": "node_modules\nconfig/production.json\nconfig/dev.json\nconfig/local.json\nlambda_config*.env\n\n"
  },
  {
    "path": ".gitmodules",
    "content": "[submodule \"modules/translators\"]\n\tpath = modules/translators\n\turl = https://github.com/zotero/translators\n[submodule \"modules/utilities\"]\n\tpath = modules/utilities\n\turl = https://github.com/zotero/utilities.git\n[submodule \"modules/translate\"]\n\tpath = modules/translate\n\turl = https://github.com/zotero/translate.git\n[submodule \"modules/zotero-schema\"]\n\tpath = modules/zotero-schema\n\turl = https://github.com/zotero/zotero-schema.git\n"
  },
  {
    "path": "COPYING",
    "content": "Zotero is Copyright © 2018-2021 Corporation for Digital Scholarship,\nVienna, Virginia, USA http://digitalscholar.org\n\nCopyright © 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017\nRoy Rosenzweig Center for History and New Media, George Mason University,\nFairfax, Virginia, USA  http://zotero.org\n\nThe Corporation for Digital Scholarship distributes the Zotero source code\nunder the GNU Affero General Public License, version 3 (AGPLv3). The full text\nof this license is given below.\n\nThe Zotero name is a registered trademark of the Corporation for Digital Scholarship.\nSee http://zotero.org/trademark for more information.\n\nThird-party copyright in this distribution is noted where applicable.\n\nAll rights not expressly granted are reserved.\n\n=========================================================================\n\n                    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 by\n    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": "Dockerfile",
    "content": "FROM node:lts\n\n# install npm dependencies\nWORKDIR /app\nCOPY ./package.json /app/package.json\nRUN npm install\n\n# copy the code\n# (after dependencies installation)\nCOPY . /app\n\n# Cloning zotero translators repository\nRUN git clone --depth=1 https://github.com/zotero/translators.git /app/modules/translators/\n\n# run the application\nEXPOSE 1969\nENTRYPOINT [ \"./docker-entrypoint.sh\" ]\n"
  },
  {
    "path": "README.md",
    "content": "# Zotero Translation Server\n\n[![Build Status](https://img.shields.io/github/actions/workflow/status/zotero/translation-server/ci.yml?branch=master)](https://github.com/zotero/translation-server/actions)\n\n\nThe Zotero translation server lets you use [Zotero translators](https://www.zotero.org/support/translators) without the Zotero client.\n\n## Installation\n\n### Running via Docker\n\nThe easiest way to run a local instance of translation-server is via Docker.\n\n```\ndocker pull zotero/translation-server\ndocker run -d -p 1969:1969 --rm --name translation-server zotero/translation-server\n```\n\nThis will pull the latest image [from Docker Hub](https://registry.hub.docker.com/r/zotero/translation-server)\nand run it as a background process on port 1969. Use `docker kill translation-server` to stop it.\n\n### Running from source\n\nFirst, fetch the source code and install Node dependencies:\n\n1. `git clone --recurse-submodules https://github.com/zotero/translation-server`\n\n1. `cd translation-server`\n\n1. `npm install`\n\nOnce you've set up a local copy of the repo, you can run the server in various ways:\n\n#### Node.js\n\n`npm start`\n\n#### Docker (development)\n\nBuild from the local repo and run in foreground:\n\n```\ndocker build -t translation-server .\ndocker run -ti -p 1969:1969 --rm translation-server\n```\n\n#### AWS Lambda\n\ntranslation-server can also run on AWS Lambda and be accessed through API Gateway. You will need the [AWS SAM CLI](https://docs.aws.amazon.com/lambda/latest/dg/sam-cli-requirements.html) to deploy the server.\n\nCopy and configure config file:\n```\ncp lambda_config.env-sample lambda_config.env\n```\n\nTest locally:\n```\n./lambda_local_test lambda_config.env\n```\n\nDeploy:\n```\n./lambda_deploy lambda_config.env\n```\n\nYou can view the API Gateway endpoint in the Outputs section of the console output.\n\n## User-Agent\n\nBy default, translation-server uses a standard Chrome `User-Agent` string to maximize compatibility. This is fine for personal usage, but for a deployed service, it’s polite to customize `User-Agent` so that sites can identify requests and contact you in case of abuse.\n\nYou can do this by setting the `USER_AGENT` environment variable:\n\n`USER_AGENT='my-custom-translation-server/2.0 (me@example.com)' npm start`\n\nIf you find that regular requests are being blocked with a fully custom user-agent string, you can also add an identifier and contact information to the end of a standard browser UA string:\n\n```\nexport USER_AGENT='Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36 my-custom-translation-server/2.0 (me@example.com)'\nnpm start\n```\n\n## Proxy Support\n\nYou can configure translation-server to use a proxy server by setting the `HTTP_PROXY` and `HTTPS_PROXY` environment variables:\n\n`HTTP_PROXY=http://proxy.example.com:8080 HTTPS_PROXY=http://proxy.example.com:8080 npm start`\n\nIf your proxy server uses a self-signed certificate, you can set `NODE_TLS_REJECT_UNAUTHORIZED=0` to force Node to ignore certificate errors.\n\nIt’s also possible to opt out of proxying for specific hosts by using the `NO_PROXY` variable. See the [Node `request` library documentation](https://github.com/request/request#controlling-proxy-behaviour-using-environment-variables) for more details.\n\n## Running tests\n\n`npm test`\n\n## Endpoints\n\n### Web Translation\n\n#### Retrieve metadata for a webpage:\n\n```\n$ curl -d 'https://www.nytimes.com/2018/06/11/technology/net-neutrality-repeal.html' \\\n   -H 'Content-Type: text/plain' http://127.0.0.1:1969/web\n```\n\nReturns an array of translated items in Zotero API JSON format\n\n#### Retrieve metadata for a webpage with multiple results:\n\n```\n$ curl -d 'https://www.ncbi.nlm.nih.gov/pubmed/?term=crispr' \\\n   -H 'Content-Type: text/plain' http://127.0.0.1:1969/web\n```\n\nReturns `300 Multiple Choices` with a JSON object:\n\n```\n{\n\t\"url\": \"https://www.ncbi.nlm.nih.gov/pubmed/?term=crispr\",\n\t\"session\": \"9y5s0EW6m5GgLm0\",\n\t\"items\": {\n\t\t\"u30044970\": {\n\t\t\t\"title\": \"RNA Binding and HEPN-Nuclease Activation Are Decoupled in CRISPR-Cas13a.\"\n\t\t},\n\t\t\"u30044923\": {\n\t\t\t\"title\": \"Knockout of tnni1b in zebrafish causes defects in atrioventricular valve development via the inhibition of the myocardial wnt signaling pathway.\"\n\t\t},\n\t\t// more results\n\t}\n}\n```\n\nTo make a selection, delete unwanted results from the items object and POST the returned data back to the server as `application/json`.\n\n\n### Search Translation\n\nRetrieve metadata from an identifier (DOI, ISBN, PMID, arXiv ID):\n\n```\n$ curl -d 10.2307/4486062 -H 'Content-Type: text/plain' http://127.0.0.1:1969/search\n```\n\n### Export Translation\n\nConvert items in Zotero API JSON format to a [supported export format](https://github.com/zotero/translation-server/blob/master/src/formats.js) (RIS, BibTeX, etc.):\n\n```\n$ curl -d @items.json -H 'Content-Type: application/json' 'http://127.0.0.1:1969/export?format=bibtex'\n```\n\n### Import Translation\n\nConvert items in any [import format](https://www.zotero.org/support/kb/importing_standardized_formats)\nto the Zotero API JSON format:\n\n```\n$ curl --data-binary @data.bib -H 'Content-Type: text/plain' http://127.0.0.1:1969/import\n"
  },
  {
    "path": "config/custom-environment-variables.json",
    "content": "{\n\t\"translatorsDirectory\": \"TRANSLATORS_DIR\"\n}\n"
  },
  {
    "path": "config/default.json5",
    "content": "{\n\t\"allowedOrigins\": [], // CORS\n\t\"blacklistedDomains\": [],\n\t\"deproxifyURLs\": false, // Automatically try deproxified versions of URLs\n\t\"identifierSearchLambda\": \"\", // Identifier search Lambda function for text search\n\t\"port\": 1969,\n\t\"host\": \"0.0.0.0\", // host to listen on\n\t\"httpMaxResponseSize\": 10, // Max size of requested response to load; triggers 400 ResponseSize error when exceeded\n\t\"textSearchTimeout\": 5,\n\t\"translators\": {\n\t\t\"CrossrefREST.email\": \"\" // Pass an email to Crossref REST API to utilize the faster servers pool\n\t},\n\t\"trustProxyHeaders\": false, // Trust X-Forwarded-For when logging requests\n\t\"userAgent\": \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36\",\n\t\"translatorsDirectory\": \"./modules/translators\"\n}\n"
  },
  {
    "path": "config/test.json",
    "content": "{\n\t\"testPort\": 3456,\n\t\"identifierSearchURL\": \"http://identifier-search/search?q=\"\n}\n"
  },
  {
    "path": "docker-entrypoint.sh",
    "content": "#!/bin/bash\n\n# will be deprecated when https://github.com/zotero/translation-server/issues/1 will be released\necho \"-> Updating zotero translators\"\ncd /app/modules/translators/\ngit pull --ff-only origin master\n\ncd /app/\nexec npm start\n"
  },
  {
    "path": "lambda_config.env-sample",
    "content": "node_env=production\n\ndeployment_bucket_name=deployment\nstack_name=TranslationServer\nmain_function_name=translation-server\nidentifier_search_function_name=identifier-search\n"
  },
  {
    "path": "lambda_deploy",
    "content": "#!/bin/bash -e\ndir=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\n\nif [ -z $1 ]; then\n\techo \"Usage: $0 config.env\" >&2\n\texit 1\nfi\n\nset -a\n. \"$dir/$1\"\nset +a\n\n./lambda_package\n\nj2 \"$dir/lambda_template.yaml.j2\" > \"$dir/package/template.yaml\"\n\nsam package --template-file \"$dir/package/template.yaml\" --s3-bucket $deployment_bucket_name --output-template-file \"$dir/package/package.yaml\"\naws cloudformation deploy --template-file \"$dir/package/package.yaml\" --stack-name $stack_name --capabilities CAPABILITY_IAM\naws cloudformation describe-stacks --stack-name $stack_name\nrm -rf \"$dir/package\"\n"
  },
  {
    "path": "lambda_local_test",
    "content": "#!/bin/bash -e\ndir=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\n\nif [ -z $1 ]; then\n\techo \"Usage: $0 config.env\" >&2\n\texit 1\nfi\n\nset -a\n. \"$dir/$1\"\nset +a\n\nj2 \"$dir/lambda_template.yaml.j2\" > \"$dir/lambda_template.yaml\"\n\nsam local invoke Lambda --template \"$dir/lambda_template.yaml\" -e lambda_local_test_event.json\n\nrm \"$dir/lambda_template.yaml\"\n"
  },
  {
    "path": "lambda_local_test_event.json",
    "content": "{\n\t\"body\": \"https://www.nytimes.com/2018/06/11/technology/net-neutrality-repeal.html\",\n\t\"resource\": \"/{proxy+}\",\n\t\"requestContext\": {\n\t\t\"resourceId\": \"123456\",\n\t\t\"apiId\": \"1234567890\",\n\t\t\"resourcePath\": \"/{proxy+}\",\n\t\t\"httpMethod\": \"POST\",\n\t\t\"requestId\": \"c6af9ac6-7b61-11e6-9a41-93e8deadbeef\",\n\t\t\"accountId\": \"123456789012\",\n\t\t\"identity\": {\n\t\t\t\"apiKey\": null,\n\t\t\t\"userArn\": null,\n\t\t\t\"cognitoAuthenticationType\": null,\n\t\t\t\"caller\": null,\n\t\t\t\"userAgent\": \"Custom User Agent String\",\n\t\t\t\"user\": null,\n\t\t\t\"cognitoIdentityPoolId\": null,\n\t\t\t\"cognitoIdentityId\": null,\n\t\t\t\"cognitoAuthenticationProvider\": null,\n\t\t\t\"sourceIp\": \"127.0.0.1\",\n\t\t\t\"accountId\": null\n\t\t},\n\t\t\"stage\": \"prod\"\n\t},\n\t\"queryStringParameters\": {\n\n\t},\n\t\"headers\": {\n\t\t\"Via\": \"1.1 08f323deadbeefa7af34d5feb414ce27.cloudfront.net (CloudFront)\",\n\t\t\"Accept-Language\": \"en-US,en;q=0.8\",\n\t\t\"CloudFront-Is-Desktop-Viewer\": \"true\",\n\t\t\"CloudFront-Is-SmartTV-Viewer\": \"false\",\n\t\t\"CloudFront-Is-Mobile-Viewer\": \"false\",\n\t\t\"X-Forwarded-For\": \"127.0.0.1, 127.0.0.2\",\n\t\t\"CloudFront-Viewer-Country\": \"US\",\n\t\t\"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\",\n\t\t\"Upgrade-Insecure-Requests\": \"1\",\n\t\t\"X-Forwarded-Port\": \"443\",\n\t\t\"Host\": \"1234567890.execute-api.us-east-1.amazonaws.com\",\n\t\t\"X-Forwarded-Proto\": \"https\",\n\t\t\"X-Amz-Cf-Id\": \"cDehVQoZnx43VYQb9j2-nvCh-9z396Uhbp027Y2JvkCPNLmGJHqlaA==\",\n\t\t\"CloudFront-Is-Tablet-Viewer\": \"false\",\n\t\t\"Cache-Control\": \"max-age=0\",\n\t\t\"User-Agent\": \"Custom User Agent String\",\n\t\t\"CloudFront-Forwarded-Proto\": \"https\",\n\t\t\"Accept-Encoding\": \"gzip, deflate, sdch\",\n\t\t\"Content-Type\": \"text/plain\"\n\t},\n\t\"pathParameters\": {\n\t\t\"proxy\": \"web\"\n\t},\n\t\"httpMethod\": \"POST\",\n\t\"stageVariables\": {\n\t\t\"baz\": \"qux\"\n\t},\n\t\"path\": \"/web\"\n}\n"
  },
  {
    "path": "lambda_package",
    "content": "rm -rf package\nmkdir package\n\n# Skip files that aren't required i.e. \".git\"\ncp -R config package/\ncp -R modules package/\ncp -R node_modules package/\ncp -R src package/\n\n# Remove broken symlinks because \"sam package\" complains\nfind -L package/ -maxdepth 10 -type l -delete\n"
  },
  {
    "path": "lambda_template.yaml.j2",
    "content": "AWSTemplateFormatVersion: '2010-09-09'\nTransform: 'AWS::Serverless-2016-10-31'\nDescription: >-\n  Lambda-based translation-server to run Zotero translators ({{ node_env }})\nResources:\n  # Lambda function\n  Lambda:\n    Type: 'AWS::Serverless::Function'\n    Properties:\n      FunctionName: {{ main_function_name }}\n      CodeUri: ./\n      Handler: src/lambda.handler\n      Runtime: nodejs14.x\n      MemorySize: 2048\n      Timeout: 30\n      Policies:\n        - LambdaInvokePolicy:\n           FunctionName: {{ identifier_search_function_name }}\n      Events:\n        # API Gateway\n        PostAPI:\n          Type: Api\n          Properties:\n            # Proxy all POST requests to Lambda function\n            Path: /{proxy+}\n            Method: post\n        OptionsAPI:\n          Type: Api\n          Properties:\n            # Proxy all OPTIONS requests to Lambda function\n            Path: /{proxy+}\n            Method: options\n      Environment:\n        Variables:\n          NODE_ENV: {{ node_env }}\nOutputs:\n  API:\n    Value: !Sub \"https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/\"\n\n"
  },
  {
    "path": "package.json",
    "content": "{\n\t\"name\": \"translation-server\",\n\t\"version\": \"2.0.5\",\n\t\"description\": \"Zotero translation server\",\n\t\"license\": \"AGPL-3.0-only\",\n\t\"main\": \"index.js\",\n\t\"repository\": {\n\t\t\"type\": \"git\",\n\t\t\"url\": \"git+https://github.com/zotero/translation-server-v2\"\n\t},\n\t\"dependencies\": {\n\t\t\"aws-sdk\": \"^2.1692.0\",\n\t\t\"config\": \"^4.1.1\",\n\t\t\"iconv-lite\": \"^0.4.24\",\n\t\t\"jsdom\": \"^29.0.1\",\n\t\t\"koa\": \"^2.15.3\",\n\t\t\"koa-bodyparser\": \"^4.4.1\",\n\t\t\"koa-route\": \"^3.2.0\",\n\t\t\"md5\": \"^2.3.0\",\n\t\t\"request\": \"^2.88.2\",\n\t\t\"request-promise-native\": \"^1.0.9\",\n\t\t\"serverless-http\": \"^2.7.0\",\n\t\t\"w3c-xmlserializer\": \"^5.0.0\",\n\t\t\"whatwg-encoding\": \"^3.1.1\",\n\t\t\"wicked-good-xpath\": \"git+https://git@github.com/zotero/wicked-good-xpath.git#1b88459\",\n\t\t\"xregexp\": \"^5.1.2\",\n\t\t\"yargs\": \"^12.0.2\"\n\t},\n\t\"devDependencies\": {\n\t\t\"@zotero/eslint-config\": \"^1.0.8\",\n\t\t\"chai\": \"^4.1.2\",\n\t\t\"eslint\": \"^5.16.0\",\n\t\t\"mocha\": \"^5.2.0\",\n\t\t\"sinon\": \"^6.1.4\",\n\t\t\"supertest\": \"^3.1.0\"\n\t},\n\t\"scripts\": {\n\t\t\"start\": \"node src/server.js\",\n\t\t\"start:debug\": \"node --inspect src/server.js\",\n\t\t\"test\": \"NODE_ENV=test ALLOW_CONFIG_MUTATIONS=1 node_modules/.bin/mocha test/*_test.js\",\n\t\t\"test:import\": \"DEBUG_LEVEL=0 NODE_ENV=test ALLOW_CONFIG_MUTATIONS=1 node_modules/.bin/mocha test/import_test.js\"\n\t}\n}\n"
  },
  {
    "path": "src/args.js",
    "content": "/*\n\t***** BEGIN LICENSE BLOCK *****\n\t\n\tCopyright © 2018 Center for History and New Media\n\t\t\t\t\tGeorge Mason University, Fairfax, Virginia, USA\n\t\t\t\t\thttp://zotero.org\n\t\n\tThis file is part of Zotero.\n\t\n\tZotero is free software: you can redistribute it and/or modify\n\tit under the terms of the GNU Affero General Public License as published by\n\tthe Free Software Foundation, either version 3 of the License, or\n\t(at your option) any later version.\n\t\n\tZotero is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n\tGNU Affero General Public License for more details.\n\n\tYou should have received a copy of the GNU Affero General Public License\n\talong with Zotero.  If not, see <http://www.gnu.org/licenses/>.\n\t\n\t***** END LICENSE BLOCK *****\n*/\n\n'use strict';\n\nconst { basename } = require('path');\nconst yargs = require('yargs');\n\nmodule.exports = yargs\n\t.usage(`Usage: ${basename(process.argv[0])} [options]`)\n\t.wrap(78)\n\t.env('ZOTERO')\n\n\t.option('translator-tester', {\n\t\talias: 't',\n\t\ttype: 'boolean',\n\t\tdefault: false,\n\t\tdescribe: 'Serve the translator tester at /translatorTester'\n\t})\n\n\t.help('help');\n"
  },
  {
    "path": "src/cors.js",
    "content": "const config = require('config');\n\nmodule.exports = async (ctx, next) => {\n\theadersSet = {};\n\tfunction set(key, value) {\n\t\tctx.set(key, value);\n\t\theadersSet[key] = value;\n\t}\n\tif (ctx.headers.origin) {\n\t\tlet allowedOrigins = config.get('allowedOrigins').filter(x => x);\n\t\tlet allAllowed = allowedOrigins.includes('*');\n\t\tif (allAllowed || allowedOrigins.includes(ctx.headers.origin)) {\n\t\t\tset(\"Access-Control-Allow-Origin\", allAllowed ? '*' : ctx.headers.origin);\n\t\t\tset(\"Access-Control-Allow-Methods\", \"POST, GET, OPTIONS\");\n\t\t\tset(\"Access-Control-Allow-Headers\", \"Content-Type\");\n\t\t\tset(\"Access-Control-Expose-Headers\", \"Link\");\n\t\t}\n\t\t// Force a 200 on API Gateway\n\t\tctx.body = '';\n\t}\n\ttry {\n\t\tawait next();\n\t}\n\tcatch (e) {\n        e.headers = Object.assign({}, e.headers, headersSet);\n        throw e;\n    }\n};"
  },
  {
    "path": "src/debug.js",
    "content": "/*\n    ***** BEGIN LICENSE BLOCK *****\n    \n    Copyright © 2009 Center for History and New Media\n                     George Mason University, Fairfax, Virginia, USA\n                     http://zotero.org\n    \n    This file is part of Zotero.\n    \n    Zotero is free software: you can redistribute it and/or modify\n    it under the terms of the GNU Affero General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n    \n    Zotero 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 Zotero.  If not, see <http://www.gnu.org/licenses/>.\n    \n    ***** END LICENSE BLOCK *****\n*/\n\nZotero.Utilities = require('./utilities');\n\nZotero.Debug = new function () {\n\tvar _console, _stackTrace, _store, _level, _lastTime, _output = [];\n\tvar _slowTime = false;\n\tvar _colorOutput = false;\n\tvar _consoleViewer = false;\n\tvar _consoleViewerQueue = [];\n\tvar _consoleViewerListener;\n\t\n\t/**\n\t * Initialize debug logging\n\t */\n\tthis.init = function (enabled=true) {\n\t\tthis.enabled = enabled;\n\t}\n\t\n\tthis.log = function (message, level, maxDepth, stack) {\n\t\tif (!this.enabled) {\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tif (typeof message != 'string') {\n\t\t\tmessage = Zotero.Utilities.varDump(message, 0, maxDepth);\n\t\t}\n\t\t\n\t\tif (!level) {\n\t\t\tlevel = 3;\n\t\t}\n\t\t\n\t\t// If level above debug.level value, don't display\n\t\tif (level > _level) {\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tvar deltaStr = '';\n\t\tvar deltaStrStore = '';\n\t\tvar delta = 0;\n\t\tvar d = new Date();\n\t\tif (_lastTime) {\n\t\t\tdelta = d - _lastTime;\n\t\t}\n\t\t_lastTime = d;\n\t\tvar slowPrefix = \"\";\n\t\tvar slowSuffix = \"\";\n\t\tif (_slowTime && delta > _slowTime) {\n\t\t\tslowPrefix = \"\\x1b[31;40m\";\n\t\t\tslowSuffix = \"\\x1b[0m\";\n\t\t}\n\t\t\n\t\tdelta = (\"\" + delta).padStart(7, \"0\");\n\t\t\n\t\tdeltaStr = \"(\" + slowPrefix + \"+\" + delta + slowSuffix + \")\";\n\t\tif (_store) {\n\t\t\tdeltaStrStore = \"(+\" + delta + \")\";\n\t\t}\n\t\t\n\t\tif (stack === true) {\n\t\t\tstack = new Error().stack.substr('Error'.length);\n\t\t}\n\t\t\n\t\tif (stack) {\n\t\t\tmessage += '\\n' + this.stackToString(stack);\n\t\t}\n\t\t\n\t\tvar output = '(' + level + ')' + deltaStr + ': ' + message;\n\t\tconsole.log(output+\"\\n\");\n\t\t\n\t\tif (_store) {\n\t\t\tif (Math.random() < 1/1000) {\n\t\t\t\t// Remove initial lines if over limit\n\t\t\t\tvar overage = this.count() - Zotero.Prefs.get('debug.store.limit');\n\t\t\t\tif (overage > 0) {\n\t\t\t\t\t_output.splice(0, Math.abs(overage));\n\t\t\t\t}\n\t\t\t}\n\t\t\t_output.push('(' + level + ')' + deltaStrStore + ': ' + message);\n\t\t}\n\t}\n\t\n\t\n\tthis.get = Zotero.Promise.method(function(maxChars, maxLineLength) {\n\t\tvar output = _output;\n\t\tvar total = output.length;\n\t\t\n\t\tif (total == 0) {\n\t\t\treturn \"\";\n\t\t}\n\t\t\n\t\tif (maxLineLength) {\n\t\t\tfor (var i=0, len=output.length; i<len; i++) {\n\t\t\t\tif (output[i].length > maxLineLength) {\n\t\t\t\t\toutput[i] = Zotero.Utilities.ellipsize(output[i], maxLineLength, false, true);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\toutput = output.join('\\n\\n');\n\t\t\n\t\tif (maxChars) {\n\t\t\toutput = output.substr(maxChars * -1);\n\t\t\t// Cut at two newlines\n\t\t\tlet matches = output.match(/^[\\n]*\\n\\n/);\n\t\t\tif (matches) {\n\t\t\t\toutput = output.substr(matches[0].length);\n\t\t\t}\n\t\t}\n\n\t\treturn output;\n\t});\n\t\n\t\n\tthis.setStore = function (enable) {\n\t\tif (enable) {\n\t\t\tthis.clear();\n\t\t}\n\t\t_store = enable;\n\t\tthis.updateEnabled();\n\t\tthis.storing = _store;\n\t}\n\t\n\t\n\tthis.updateEnabled = function () {\n\t\tthis.enabled = _console || _consoleViewer || _store;\n\t};\n\t\n\t\n\tthis.count = function () {\n\t\treturn _output.length;\n\t}\n\t\n\t\n\tthis.clear = function () {\n\t\t_output = [];\n\t}\n\t\n\t/**\n\t * Format a stack trace for output in the same way that Error.stack does\n\t * @param {Components.stack} stack\n\t * @param {Integer} [lines=5] Number of lines to format\n\t */\n\tthis.stackToString = function (stack, lines) {\n\t\tif (!lines) lines = 5;\n\t\tvar str = '';\n\t\twhile(stack && lines--) {\n\t\t\tstr += '\\n  ' + (stack.name || '') + '@' + stack.filename\n\t\t\t\t+ ':' + stack.lineNumber;\n\t\t\tstack = stack.caller;\n\t\t}\n\t\treturn this.filterStack(str).substr(1);\n\t};\n\t\n\t\n\t/**\n\t * Strip Bluebird lines from a stack trace\n\t *\n\t * @param {String} stack\n\t */\n\tthis.filterStack = function (stack) {\n\t\treturn stack.split(/\\n/).filter(line => line.indexOf('zotero/bluebird') == -1).join('\\n');\n\t}\n}\n\nmodule.exports = Zotero.Debug;\n"
  },
  {
    "path": "src/exportEndpoint.js",
    "content": "/*\n    ***** BEGIN LICENSE BLOCK *****\n    \n    Copyright © 2018 Corporation for Digital Scholarship\n                     Vienna, Virginia, USA\n                     https://www.zotero.org\n    \n    This file is part of Zotero.\n    \n    Zotero is free software: you can redistribute it and/or modify\n    it under the terms of the GNU Affero General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n    \n    Zotero 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 Zotero.  If not, see <http://www.gnu.org/licenses/>.\n    \n    ***** END LICENSE BLOCK *****\n*/\n\nconst config = require('config');\nconst { FORMATS, CONTENT_TYPES } = require('./formats');\nconst Translate = require('./translation/translate');\n\nvar ExportEndpoint = module.exports = {\n\thandle: async function (ctx, next) {\n\t\tctx.assert(ctx.is('json'), 415);\n\t\t\n\t\tvar items = ctx.request.body;\n\t\t\n\t\tif (!items) {\n\t\t\tctx.throw(400, \"POST data not provided\");\n\t\t}\n\t\t\n\t\tvar query = ctx.request.query;\n\t\t\n\t\tvar translatorID;\n\t\t\n\t\tif (!query.format || !(translatorID = FORMATS[query.format])) {\n\t\t\tctx.throw(400, \"Invalid format specified\");\n\t\t}\n\t\t\n\t\tif (!items.length || !items[0].itemType) {\n\t\t\tctx.throw(400, \"Input must be an array of items as JSON\");\n\t\t}\n\t\t\n\t\tvar translator = Zotero.Translators.get(translatorID);\n\t\tvar legacy = Zotero.Utilities.semverCompare('4.0.27', translator.metadata.minVersion) > 0;\n\t\t\n\t\t// Emulate itemsToExportFormat as best as we can\n\t\tfor (let item of items) {\n\t\t\t// There's no library, so all we have is a key\n\t\t\tif (!item.uri) {\n\t\t\t\titem.uri = item.key;\n\t\t\t\tdelete item.key;\n\t\t\t}\n\t\t\t\n\t\t\tif (legacy) {\n\t\t\t\t// SQL instead of ISO 8601\n\t\t\t\tif (item.dateAdded) item.dateAdded = Zotero.Date.isoToSQL(item.dateAdded);\n\t\t\t\tif (item.dateModified) item.dateAdded = Zotero.Date.isoToSQL(item.dateModified);\n\t\t\t\tif (item.accessDate) item.accessDate = Zotero.Date.isoToSQL(item.accessDate);\n\t\t\t}\n\t\t}\n\t\t\n\t\tvar translate = new Translate.Export();\n\t\ttranslate.setTranslator(translatorID);\n\t\ttranslate.setItems(items);\n\t\ttry {\n\t\t\tawait new Promise(function (resolve, reject) {\n\t\t\t\ttranslate.setHandler(\"done\", function (obj, status) {\n\t\t\t\t\tif (!status) {\n\t\t\t\t\t\treject();\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tctx.set('Content-Type', CONTENT_TYPES[query.format]);\n\t\t\t\t\t\tctx.response.body = translate.string;\n\t\t\t\t\t\tresolve();\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\ttranslate.translate();\n\t\t\t});\n\t\t}\n\t\tcatch (e) {\n\t\t\tctx.throw(\n\t\t\t\t500,\n\t\t\t\t\"An error occurred during translation. Please check translation with the Zotero client.\",\n\t\t\t\t{ expose: true }\n\t\t\t);\n\t\t}\n\t}\n};\n"
  },
  {
    "path": "src/formats.js",
    "content": "/* eslint camelcase: \"off\" */\n\nconst FORMATS = {\n\tbibtex: \"9cb70025-a888-4a29-a210-93ec52da40d4\",\n\tbiblatex: \"b6e39b57-8942-4d11-8259-342c46ce395f\",\n\tbookmarks: \"4e7119e0-02be-4848-86ef-79a64185aad8\",\n\tcoins: \"05d07af9-105a-4572-99f6-a8e231c0daef\",\n\tcsljson: \"bc03b4fe-436d-4a1f-ba59-de4d2d7a63f7\",\n\tcsv: \"25f4c5e2-d790-4daa-a667-797619c7e2f2\",\n\tendnote_xml: \"eb7059a4-35ec-4961-a915-3cf58eb9784b\",\n\tevernote: \"18dd188a-9afc-4cd6-8775-1980c3ce0fbf\",\n\tmods: \"0e2235e7-babf-413c-9acf-f27cce5f059c\",\n\trdf_bibliontology: \"14763d25-8ba0-45df-8f52-b8d1108e7ac9\",\n\trdf_dc: \"6e372642-ed9d-4934-b5d1-c11ac758ebb7\",\n\trdf_zotero: \"14763d24-8ba0-45df-8f52-b8d1108e7ac9\",\n\trefer: \"881f60f2-0802-411a-9228-ce5f47b64c7d\",\n\trefworks_tagged: \"1a3506da-a303-4b0a-a1cd-f216e6138d86\",\n\tris: \"32d59d2d-b65a-4da4-b0a3-bdd3cfb979e7\",\n\ttei: \"032ae9b7-ab90-9205-a479-baf81f49184a\",\n\twikipedia: \"3f50aaac-7acc-4350-acd0-59cb77faf620\"\n};\n\nconst CONTENT_TYPES = {\n\tbibtex: \"application/x-bibtex\",\n\tbiblatex: \"application/x-bibtex\",\n\tbookmarks: \"text/html\",\n\tcoins: \"text/html\",\n\tcsljson: \"application/json\",\n\tcsv: \"text/csv\",\n\tendnote_xml: \"text/xml\",\n\tevernote: \"text/xml\",\n\tmods: \"application/mods+xml\",\n\trdf_bibliontology: \"application/rdf+xml\",\n\trdf_dc: \"application/rdf+xml\",\n\trdf_zotero: \"application/rdf+xml\",\n\trefer: \"application/x-research-info-systems\",\n\trefworks_tagged: \"text/plain\",\n\tris: \"application/x-research-info-systems\",\n\ttei: \"text/xml\",\n\twikipedia: \"text/x-wiki\"\n};\n\nmodule.exports = { FORMATS, CONTENT_TYPES };\n"
  },
  {
    "path": "src/http.js",
    "content": "/*\n    ***** BEGIN LICENSE BLOCK *****\n    \n    Copyright © 2011 Center for History and New Media\n                     George Mason University, Fairfax, Virginia, USA\n                     http://zotero.org\n    \n    This file is part of Zotero.\n    \n    Zotero is free software: you can redistribute it and/or modify\n    it under the terms of the GNU Affero General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n    \n    Zotero 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 Zotero.  If not, see <http://www.gnu.org/licenses/>.\n    \n    ***** END LICENSE BLOCK *****\n*/\n\nvar config = require('config');\nvar request = require('request');\nvar iconv = require('iconv-lite');\nvar url = require('url');\nvar jsdom = require('jsdom');\nvar { JSDOM } = jsdom;\nvar wgxpath = require('wicked-good-xpath');\nvar { MIMEType } = require(\"whatwg-mimetype\"); // Use the same MIME type library as JSDOM\n\n/**\n * Functions for performing HTTP requests\n * @namespace\n */\nZotero.HTTP = new function() {\n\tthis.StatusError = function(url, status, body) {\n\t\tthis.message = `HTTP request to ${url} rejected with status ${status}`;\n\t\tthis.status = status;\n\t\tthis.responseText = body;\n\t};\n\tthis.StatusError.prototype = Object.create(Error.prototype);\n\n\tthis.TimeoutError = function(ms) {\n\t\tthis.message = `HTTP request has timed out after ${ms}ms`;\n\t};\n\tthis.TimeoutError.prototype = Object.create(Error.prototype);\n\t\n\t// Max size of requested response to load; triggers 400 ResponseSizeError when exceeded\n\tthis.httpMaxResponseSize = ( config.has('httpMaxResponseSize') ? config.get('httpMaxResponseSize') : 10 ) * 1024 * 1024;\n\n\tthis.ResponseSizeError = function(url) {\n\t\tthis.message = `${url} response exceeds max size`;\n\t};\n\tthis.ResponseSizeError.prototype = Object.create(Error.prototype);\n\t\n\tthis.UnsupportedFormatError = function (url, msg) {\n\t\tthis.message = msg;\n\t};\n\tthis.UnsupportedFormatError.prototype = Object.create(Error.prototype);\n\t\n\t/**\n\t * Get a promise for a HTTP request\n\t *\n\t * @param {String} method The method of the request (\"GET\", \"POST\", \"HEAD\", or \"OPTIONS\")\n\t * @param {String}\turl\t\t\t\tURL to request\n\t * @param {Object} [options] Options for HTTP request:<ul>\n\t *         <li>body - The body of a POST request</li>\n\t *         <li>headers - Object of HTTP headers to send with the request</li>\n\t *         <li>cookieSandbox - The sandbox from which cookies should be taken</li>\n\t *         <li>debug - Log response text and status code</li>\n\t *         <li>logBodyLength - Length of request body to log</li>\n\t *         <li>timeout - Request timeout specified in milliseconds [default 15000]</li>\n\t *         <li>responseType - The response type of the request from the XHR spec</li>\n\t *         <li>responseTypeMap - A Map of remote content type ('application/x-bibtex') to\n\t *              XHR response type ('text'). 'html' and 'xml' imply isHTML() and isXML() from\n\t *              whatwg-mimetype. Use an empty string for the key to set a fallback response type;\n\t *              otherwise unspecified content types are rejected.</li>\n\t *         <li>successCodes - HTTP status codes that are considered successful, or FALSE to allow all</li>\n\t *     </ul>\n\t * @return {Promise<Object>} A promise resolved with an object containing the following XMLHttpRequest properties:\n\t * \t\t- responseText {String}\n\t * \t\t- getAllResponseHeaders {Function}\n\t * \t\t- getResponseHeader {Function}\n\t * \t\t- statusCode {Number}\n\t */\n\tthis.request = async function(method, requestURL, options = {}) {\n\t\t// Default options\n\t\toptions = Object.assign({\n\t\t\tbody: null,\n\t\t\theaders: {},\n\t\t\tcookieSandbox: request.jar(),\n\t\t\tdebug: false,\n\t\t\tlogBodyLength: 1024,\n\t\t\ttimeout: 15000,\n\t\t\tresponseType: '',\n\t\t\tsuccessCodes: null,\n\t\t\tmaxResponseSize: this.httpMaxResponseSize\n\t\t}, options);\n\t\t\n\t\toptions.headers = Object.assign({\n\t\t\t'User-Agent': process.env.USER_AGENT || config.get('userAgent'),\n\t\t\t'Accept': '*/*'\n\t\t}, options.headers);\n\t\n\t\tlet logBody = '';\n\t\tif (['GET', 'HEAD'].includes(method)) {\n\t\t\tif (options.body != null) {\n\t\t\t\tthrow new Error(`HTTP ${method} cannot have a request body (${options.body})`)\n\t\t\t}\n\t\t} else if(options.body) {\n\t\t\toptions.body = typeof options.body == 'string' ? options.body : JSON.stringify(options.body);\n\t\t\t\n\t\t\tif (!options.headers) options.headers = {};\n\t\t\tif (!options.headers[\"Content-Type\"]) {\n\t\t\t\toptions.headers[\"Content-Type\"] = \"application/x-www-form-urlencoded\";\n\t\t\t}\n\t\t\telse if (options.headers[\"Content-Type\"] == 'multipart/form-data') {\n\t\t\t\t// Allow XHR to set Content-Type with boundary for multipart/form-data\n\t\t\t\tdelete options.headers[\"Content-Type\"];\n\t\t\t}\n\t\t\t\n\t\t\tlogBody = `: ${options.body.substr(0, options.logBodyLength)}` +\n\t\t\t\t\toptions.body.length > options.logBodyLength ? '...' : '';\n\t\t\t// TODO: make sure below does its job in every API call instance\n\t\t\t// Don't display password or session id in console\n\t\t\tlogBody = logBody.replace(/password\":\"[^\"]+/, 'password\":\"********');\n\t\t\tlogBody = logBody.replace(/password=[^&]+/, 'password=********');\n\t\t}\n\t\tZotero.debug(`HTTP ${method} ${requestURL}${logBody}`);\n\t\t\n\t\t// Parse URL to escape it (e.g., Unicode characters)\n\t\tvar parsedURL = new url.URL(requestURL);\n\t\t\n\t\tlet {response, body} = await customRequest(method, parsedURL, options);\n\t\t\n\t\tif (options.debug) {\n\t\t\tZotero.debug(`HTTP ${response.statusCode} response: ${body}`);\n\t\t}\n\t\t\n\t\tvar result = {\n\t\t\tresponseURL: response.request.uri.href,\n\t\t\tstatus: response.statusCode,\n\t\t\tgetAllResponseHeaders: () => {\n\t\t\t\treturn [...Object.entries(response.headers)].map(([k, v]) => `${k}: ${v}\\r\\n`).join('');\n\t\t\t},\n\t\t\tgetResponseHeader: (header) => {\n\t\t\t\treturn response.headers[header.toLowerCase()] || null;\n\t\t\t}\n\t\t};\n\t\t\n\t\tvar mimeType = new MIMEType(response.headers['content-type']);\n\t\tvar responseType = getResponseType(response.headers['content-type'], options);\n\t\tresult.type = responseType;\n\t\t\n\t\tif (responseType == 'document') {\n\t\t\tbody = decodeContent(body, response.headers['content-type']);\n\t\t\tlet dom = new JSDOM(body, {\n\t\t\t\turl: result.responseURL,\n\t\t\t\t// Inform JSDOM what content type it's parsing,\n\t\t\t\t// so it could reject unsupported content types\n\t\t\t\tcontentType: response.headers['content-type']\n\t\t\t});\n\t\t\t\n\t\t\twgxpath.install(dom.window, true);\n\t\t\tresult.response = dom.window.document;\n\t\t\t\n\t\t\t// Follow meta redirects in HTML files\n\t\t\tif (mimeType.isHTML() || mimeType.essence == 'application/xhtml+xml') {\n\t\t\t\tlet meta = result.response.querySelector('meta[http-equiv=refresh]');\n\t\t\t\tif (meta && meta.getAttribute('content')) {\n\t\t\t\t\tlet parts = meta.getAttribute('content').split(/;\\s*url=/);\n\t\t\t\t\t// If there's a redirect to another URL in less than 15 seconds,\n\t\t\t\t\t// follow it\n\t\t\t\t\tif (parts.length == 2 && parseInt(parts[0]) <= 15) {\n\t\t\t\t\t\tlet newURL = parts[1].trim().replace(/^'(.+)'/, '$1');\n\t\t\t\t\t\tnewURL = url.resolve(requestURL, newURL);\n\t\t\t\t\t\t\n\t\t\t\t\t\tZotero.debug(\"Meta refresh to \" + newURL);\n\t\t\t\t\t\tresult = Zotero.HTTP.request(method, newURL, options);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\telse if (responseType == 'json') {\n\t\t\tresult.response = JSON.parse(body.toString());\n\t\t}\n\t\telse if (responseType == 'text') {\n\t\t\tlet charset = mimeType.parameters.get('charset');\n\t\t\t// Treat unknown charset as utf-8\n\t\t\tif (!charset) {\n\t\t\t\tcharset = 'utf8';\n\t\t\t}\n\t\t\telse if (!iconv.encodingExists(charset)) {\n\t\t\t\tZotero.debug(`Unknown charset ${charset} -- decoding as UTF-8`);\n\t\t\t\tcharset = 'utf8';\n\t\t\t}\n\t\t\tbody = iconv.decode(body, charset);\n\t\t\tresult.response = body;\n\t\t\tresult.responseText = body;\n\t\t}\n\t\telse {\n\t\t\tthrow new Error(\"Invalid responseType\");\n\t\t}\n\t\t\n\t\treturn result;\n\t};\n\t\n\t/**\n\t * Load one or more documents\n\t *\n\t * This should stay in sync with the equivalent function in the client\n\t *\n\t * @param {String|String[]} urls - URL(s) of documents to load\n\t * @param {Function} processor - Callback to be executed for each document loaded\n\t * @param {CookieJar} [cookieSandbox] Cookie sandbox object\n\t * @return {Promise<Array>} - A promise for an array of results from the processor runs\n\t */\n\tthis.processDocuments = async function (urls, processor, options = {}) {\n\t\t// Handle old signature: urls, processor, onDone, onError\n\t\tif (arguments.length > 3) {\n\t\t\tZotero.debug(\"Zotero.HTTP.processDocuments() now takes only 2 arguments -- update your code\");\n\t\t\tvar onDone = arguments[3];\n\t\t\tvar onError = arguments[4];\n\t\t}\n\t\t\n\t\tvar cookieSandbox = options.cookieSandbox;\n\t\tvar headers = options.headers;\n\t\t\n\t\tif (typeof urls == \"string\") urls = [urls];\n\t\tvar funcs = urls.map(url => () => {\n\t\t\treturn Zotero.HTTP.request(\n\t\t\t\t\"GET\",\n\t\t\t\turl,\n\t\t\t\t{\n\t\t\t\t\tresponseType: 'document',\n\t\t\t\t\tcookieSandbox,\n\t\t\t\t\theaders\n\t\t\t\t}\n\t\t\t)\n\t\t\t.then((req) => {\n\t\t\t\treturn processor(req.response, req.responseURL);\n\t\t\t});\n\t\t});\n\t\t\n\t\t// Run processes serially\n\t\t// TODO: Add some concurrency?\n\t\tvar f;\n\t\tvar results = [];\n\t\twhile (f = funcs.shift()) {\n\t\t\ttry {\n\t\t\t\tresults.push(await f());\n\t\t\t}\n\t\t\tcatch (e) {\n\t\t\t\tif (onError) {\n\t\t\t\t\tonError(e);\n\t\t\t\t}\n\t\t\t\tthrow e;\n\t\t\t}\n\t\t}\n\t\t\n\t\t// Deprecated\n\t\tif (onDone) {\n\t\t\tonDone();\n\t\t}\n\t\t\n\t\treturn results;\n\t}\n\t\n\t/**\n\t* Send an HTTP GET request\n\t*\n\t* @deprecated Use {@link Zotero.HTTP.request}\n\t* @param {String}\t\t\turl\t\t\t\tURL to request\n\t* @param {Function} \t\tonDone\t\t\tCallback to be executed upon request completion\n\t* @param {String}\t\t\tresponseCharset\n\t* @param {CookieJar}\t\tcookieSandbox\n\t* @param {Object}\t\t\theaders\t\t\tHTTP headers to include with the request\n\t* @return {Boolean} True if the request was sent, or false if the browser is offline\n\t*/\n\tthis.doGet = function(url, onDone, responseCharset, cookieSandbox, headers) {\n\t\tZotero.debug('Zotero.HTTP.doGet is deprecated. Use Zotero.HTTP.request');\n\t\tthis.request('GET', url, {responseCharset, headers, cookieSandbox})\n\t\t.then(onDone, function(e) {\n\t\t\tonDone({status: e.status, responseText: e.responseText});\n\t\t});\n\t\treturn true;\n\t};\n\t\n\t/**\n\t* Send an HTTP POST request\n\t*\n\t* @deprecated Use {@link Zotero.HTTP.request}\n\t* @param {String}\t\t\turl URL to request\n\t* @param {String|Object[]}\tbody Request body\n\t* @param {Function}\t\t\tonDone Callback to be executed upon request completion\n\t* @param {String}\t\t\theaders Request HTTP headers\n\t* @param {String}\t\t\tresponseCharset\n\t* @param {CookieJar}\t\tcookieSandbox\n\t* @return {Boolean} True if the request was sent, or false if the browser is offline\n\t*/\n\tthis.doPost = function(url, body, onDone, headers, responseCharset, cookieSandbox) {\n\t\tZotero.debug('Zotero.HTTP.doPost is deprecated. Use Zotero.HTTP.request');\n\t\tthis.request('POST', url, {body, responseCharset, headers, cookieSandbox})\n\t\t.then(onDone, function(e) {\n\t\t\tonDone({status: e.status, responseText: e.responseText});\n\t\t});\n\t\treturn true;\n\t};\n}\n\n/**\n * A temporary workaround for JSDOM content decoding issues.\n * The code is adapted from jsdom/lib/api.js. All dependencies\n * are already used internally in JSDOM\n *\n * TODO: Remove this code when https://github.com/jsdom/jsdom/issues/2495 will be solved\n */\nconst sniffHTMLEncoding = require(\"html-encoding-sniffer\");\nconst whatwgEncoding = require(\"whatwg-encoding\");\n\nfunction decodeContent(html, contentType) {\n\tlet transportLayerEncodingLabel;\n\tif (contentType) {\n\t\tconst mimeType = new MIMEType(contentType);\n\t\ttransportLayerEncodingLabel = mimeType.parameters.get(\"charset\");\n\t}\n\t\n\thtml = Buffer.from(html.buffer, html.byteOffset, html.byteLength);\n\t\n\tlet encoding = sniffHTMLEncoding(html, {defaultEncoding: \"UTF-8\", transportLayerEncodingLabel});\n\thtml = whatwgEncoding.decode(html, encoding);\n\t\n\treturn html;\n}\n\n/**\n * request.js doesn't support response size limitation, therefore\n * we have to do it manually\n *\n * @param {String} method\n * @param {String} requestURL\n * @param {Object} options\n * @return {Promise<Object>} response, body\n */\nfunction customRequest(method, requestURL, options) {\n\treturn new Promise(function (resolve, reject) {\n\t\tlet response;\n\t\t\n\t\t// Make sure resolve/reject is called only once even if request.js\n\t\t// is emitting events when it shouldn't\n\t\tlet returned = false;\n\t\t\n\t\t// Store buffers in array, because concatenation operation is is unbelievably slow\n\t\tlet buffers = [];\n\t\tlet bufferLength = 0;\n\t\t\n\t\tlet req = request({\n\t\t\turi: requestURL,\n\t\t\tmethod,\n\t\t\theaders: options.headers,\n\t\t\ttimeout: options.timeout,\n\t\t\tbody: options.body,\n\t\t\tgzip: true,\n\t\t\tfollowAllRedirects: true,\n\t\t\tjar: options.cookieSandbox,\n\t\t\tencoding: null // Get body in a buffer\n\t\t})\n\t\t\t.on('error', function (err) {\n\t\t\t\tif (returned) return;\n\t\t\t\treject(err);\n\t\t\t})\n\t\t\t.on('data', function (chunk) {\n\t\t\t\tif (returned) return;\n\t\t\t\t\n\t\t\t\tbufferLength += chunk.length;\n\t\t\t\tbuffers.push(chunk);\n\t\t\t\t\n\t\t\t\tif (bufferLength > options.maxResponseSize) {\n\t\t\t\t\treq.abort();\n\t\t\t\t\treturned = true;\n\t\t\t\t\treject(new Zotero.HTTP.ResponseSizeError(requestURL));\n\t\t\t\t}\n\t\t\t})\n\t\t\t.on('response', function (res) {\n\t\t\t\tif (returned) return;\n\t\t\t\tresponse = res;\n\t\t\t\t\n\t\t\t\tif (!response.headers['content-type']) {\n\t\t\t\t\treturned = true;\n\t\t\t\t\treturn reject(new Zotero.HTTP.UnsupportedFormatError(requestURL, 'Missing Content-Type header'));\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t// Check if the status code is allowed\n\t\t\t\t// Array of success codes given\n\t\t\t\tif (options.successCodes) {\n\t\t\t\t\tvar success = options.successCodes.includes(response.statusCode);\n\t\t\t\t}\n\t\t\t\t// Explicit FALSE means allow any status code\n\t\t\t\telse if (options.successCodes === false) {\n\t\t\t\t\tvar success = true;\n\t\t\t\t}\n\t\t\t\t// Otherwise, 2xx is success\n\t\t\t\telse {\n\t\t\t\t\tvar success = response.statusCode >= 200 && response.statusCode < 300;\n\t\t\t\t}\n\t\t\t\tif (!success) {\n\t\t\t\t\treturned = true;\n\t\t\t\t\treturn reject(new Zotero.HTTP.StatusError(requestURL, response.statusCode, response.body));\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t// Check Content-Type before starting the download\n\t\t\t\tlet supported = true;\n\t\t\t\tlet mimeType = new MIMEType(response.headers['content-type']);\n\t\t\t\tif (options.responseType == 'document') {\n\t\t\t\t\tsupported = mimeType.isHTML() || mimeType.isXML();\n\t\t\t\t}\n\t\t\t\telse if (options.responseTypeMap) {\n\t\t\t\t\tlet map = options.responseTypeMap;\n\t\t\t\t\tsupported = (map.has('html') && mimeType.isHTML())\n\t\t\t\t\t\t|| (map.has('xml') && mimeType.isXML())\n\t\t\t\t\t\t|| map.has(mimeType.essence)\n\t\t\t\t\t\t// An empty string for a key allows unspecified types as text\n\t\t\t\t\t\t|| map.has('');\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (!supported) {\n\t\t\t\t\treq.abort();\n\t\t\t\t\treturned = true;\n\t\t\t\t\treturn reject(new Zotero.HTTP.UnsupportedFormatError(\n\t\t\t\t\t\trequestURL,\n\t\t\t\t\t\tresponse.headers['content-type'] + ' is not supported'\n\t\t\t\t\t));\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t// Content-length doesn't always exists or it can be a length of a gzipped content,\n\t\t\t\t// but it's still worth to do the initial size check\n\t\t\t\tif (\n\t\t\t\t\tresponse.headers['content-length'] !== undefined &&\n\t\t\t\t\tresponse.headers['content-length'] > options.maxResponseSize\n\t\t\t\t) {\n\t\t\t\t\treq.abort();\n\t\t\t\t\treturned = true;\n\t\t\t\t\treject(new Zotero.HTTP.ResponseSizeError(requestURL));\n\t\t\t\t}\n\t\t\t})\n\t\t\t.on('end', function () {\n\t\t\t\tif (returned) return;\n\t\t\t\treturned = true;\n\t\t\t\tresolve({response, body: Buffer.concat(buffers, bufferLength)});\n\t\t\t});\n\t});\n};\n\nfunction getResponseType(contentType, options) {\n\tvar mimeType = new MIMEType(contentType);\n\tif (options.responseType) {\n\t\treturn options.responseType;\n\t}\n\tif (options.responseTypeMap) {\n\t\tlet map = options.responseTypeMap;\n\t\tif (map.has('html') && mimeType.isHTML()) {\n\t\t\treturn map.get('html');\n\t\t}\n\t\tif (map.has('xml') && mimeType.isXML()) {\n\t\t\treturn map.get('xml');\n\t\t}\n\t\tif (map.has(mimeType.essence)) {\n\t\t\treturn map.get(mimeType.essence);\n\t\t}\n\t}\n\treturn 'text';\n}\n\nmodule.exports = Zotero.HTTP;\n"
  },
  {
    "path": "src/importEndpoint.js",
    "content": "'use strict';\n\n/*\n\t\t***** BEGIN LICENSE BLOCK *****\n\t\t\n\t\tCopyright © 2018 Corporation for Digital Scholarship\n\t\t\t\t\t\t\t\t\t\t Vienna, Virginia, USA\n\t\t\t\t\t\t\t\t\t\t https://www.zotero.org\n\t\t\n\t\tThis file is part of Zotero.\n\t\t\n\t\tZotero is free software: you can redistribute it and/or modify\n\t\tit under the terms of the GNU Affero General Public License as published by\n\t\tthe Free Software Foundation, either version 3 of the License, or\n\t\t(at your option) any later version.\n\t\t\n\t\tZotero is distributed in the hope that it will be useful,\n\t\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\t\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\tSee the\n\t\tGNU Affero General Public License for more details.\n\t\t\n\t\tYou should have received a copy of the GNU Affero General Public License\n\t\talong with Zotero.\tIf not, see <http://www.gnu.org/licenses/>.\n\t\t\n\t\t***** END LICENSE BLOCK *****\n*/\n\nconst Translate = require('./translation/translate');\n\nmodule.exports = {\n\thandle: async function (ctx, _next) {\n\t\tconst translate = new Translate.Import();\n\t\ttranslate.setString(ctx.request.body || '');\n\n\t\tconst translators = await translate.getTranslators();\n\t\tif (translators.length === 0) {\n\t\t\tctx.throw(500, 'No suitable translators found', { expose: true });\n\t\t\treturn;\n\t\t}\n\t\ttranslate.setTranslator(translators[0]);\n\t\tvar items = await translate.translate({ libraryID: 1 });\n\t\t\n\t\tctx.set('Content-Type', 'application/json');\n\t\tctx.set('Zotero-Translator-ID', translators[0].translatorID);\n\t\t\n\t\t// Convert translator JSON to API JSON\n\t\tvar newItems = [];\n\t\titems.forEach((item) => {\n\t\t\tnewItems.push(...Zotero.Utilities.Item.itemToAPIJSON(item));\n\t\t});\n\t\t\n\t\tctx.response.body = JSON.stringify(newItems, null, 2);\n\t}\n};\n"
  },
  {
    "path": "src/lambda.js",
    "content": "/*\n    ***** BEGIN LICENSE BLOCK *****\n    \n    Copyright © 2018 Center for History and New Media\n                     George Mason University, Fairfax, Virginia, USA\n                     https://www.zotero.org\n    \n    This file is part of Zotero.\n    \n    Zotero is free software: you can redistribute it and/or modify\n    it under the terms of the GNU Affero General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n    \n    Zotero 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 Zotero.  If not, see <http://www.gnu.org/licenses/>.\n    \n    ***** END LICENSE BLOCK *****\n*/\n\nconst Koa = require('koa');\nconst _ = require('koa-route');\nconst bodyParser = require('koa-bodyparser');\nconst cors = require('./cors');\nconst serverless = require('serverless-http');\n\nrequire('./zotero');\nconst Debug = require('./debug');\nvar Translators; // Translators module is cashed\nconst SearchEndpoint = require('./searchEndpoint');\nconst WebEndpoint = require('./webEndpoint');\nconst ExportEndpoint = require('./exportEndpoint');\nconst ImportEndpoint = require('./importEndpoint');\n\nconst app = module.exports = new Koa();\napp.use(function (ctx, next) {\n\tvar msg = `${ctx.method} ${ctx.url} from ${ctx.request.ip} \"${ctx.headers['user-agent']}\"`;\n\tif (ctx.headers.origin) {\n\t\tmsg += ` (${ctx.headers.origin})`;\n\t}\n\tZotero.debug(msg);\n\treturn next();\n});\napp.use(cors);\napp.use(\n\tbodyParser({\n\t\tenableTypes: ['text', 'json'],\n\t\tjsonLimit: '5mb',\n\t\ttextLimit: '3mb',\n\t})\n);\napp.use(_.post('/web', WebEndpoint.handle.bind(WebEndpoint)));\napp.use(_.post('/search', SearchEndpoint.handle.bind(SearchEndpoint)));\napp.use(_.post('/export', ExportEndpoint.handle.bind(ExportEndpoint)));\napp.use(_.post('/import', ImportEndpoint.handle.bind(ImportEndpoint)));\n\nDebug.init(1);\n\nconst handler = serverless(app);\nmodule.exports.handler = async function (event, context) {\n\tif (!Translators) {\n\t\tTranslators = require('./translators');\n\t\tawait Translators.init();\n\t}\n\t\n\tvar result = await handler(event, context);\n\treturn result;\n};\n"
  },
  {
    "path": "src/proxy.js",
    "content": "/*\n\t***** BEGIN LICENSE BLOCK *****\n\t\n\tCopyright © 2016 Center for History and New Media\n\t\t\t\t\tGeorge Mason University, Fairfax, Virginia, USA\n\t\t\t\t\thttp://zotero.org\n\t\n\tThis file is part of Zotero.\n\t\n\tZotero is free software: you can redistribute it and/or modify\n\tit under the terms of the GNU Affero General Public License as published by\n\tthe Free Software Foundation, either version 3 of the License, or\n\t(at your option) any later version.\n\t\n\tZotero is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n\tGNU Affero General Public License for more details.\n\n\tYou should have received a copy of the GNU Affero General Public License\n\talong with Zotero.  If not, see <http://www.gnu.org/licenses/>.\n\t\n\t***** END LICENSE BLOCK *****\n*/\n\n/**\n * Intercepts web requests to detect and redirect proxies. Loosely based on Zotero for Firefox proxy code.\n *\n * Zotero.Proxies.Detectors specifies detector functions/objects, which run asynchronously for every\n * request and add new proxies based on proxy specific rule match\n *\n * Zotero.Proxies.proxies defines a list of already known proxies (Zotero.Proxy), based on an URL match scheme.\n *\n * Each Zotero.Proxy holds a list of already recognized hosts (previously accessed via the proxy\n * by the user) and automatically redirects the requests to these hosts via the proxy.\n */\n\n(function() {\n\n\"use strict\";\n\nvar url = require('url');\nvar TLDS = Zotero.requireTranslate('./tlds');\n\nZotero.Proxies = new function() {\n\n\t/**\n\t * Check the url for potential proxies and deproxify, providing a schema to build\n\t * a proxy object.\n\t * \n\t * @param URL\n\t * @returns {Object} Unproxied url to proxy object\n\t */\n\tthis.getPotentialProxies = function(URL) {\n\t\tvar urlToProxy = {};\n\t\t// If it's a known proxied URL just return it\n\t\tif (Zotero.Proxies.transparent) {\n\t\t\tfor (var proxy of Zotero.Proxies.proxies) {\n\t\t\t\tif (proxy.regexp) {\n\t\t\t\t\tvar m = proxy.regexp.exec(URL);\n\t\t\t\t\tif (m) {\n\t\t\t\t\t\tlet proper = proxy.toProper(m);\n\t\t\t\t\t\turlToProxy[proper] = proxy.toJSON();\n\t\t\t\t\t\treturn urlToProxy;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\turlToProxy[URL] = null;\n\t\t\n\t\t// if there is a subdomain that is also a TLD, also test against URI with the domain\n\t\t// dropped after the TLD\n\t\t// (i.e., www.nature.com.mutex.gmu.edu => www.nature.com)\n\t\tvar m = /^(https?:\\/\\/)([^\\/]+)/i.exec(URL);\n\t\tif (m) {\n\t\t\t// First, drop the 0- if it exists (this is an III invention)\n\t\t\tvar host = m[2];\n\t\t\tif (host.substr(0, 2) === \"0-\") host = host.substr(2);\n\t\t\tvar hostnameParts = [host.split(\".\")];\n\t\t\tif (m[1] == 'https://') {\n\t\t\t\t// try replacing hyphens with dots for https protocol\n\t\t\t\t// to account for EZProxy HttpsHypens mode\n\t\t\t\thostnameParts.push(host.split('.'));\n\t\t\t\thostnameParts[1].splice(0, 1, ...(hostnameParts[1][0].replace(/-/g, '.').split('.')));\n\t\t\t}\n\t\t\t\n\t\t\tfor (let i=0; i < hostnameParts.length; i++) {\n\t\t\t\tlet parts = hostnameParts[i];\n\t\t\t\t// If hostnameParts has two entries, then the second one is with replaced hyphens\n\t\t\t\tlet dotsToHyphens = i == 1;\n\t\t\t\t// skip the lowest level subdomain, domain and TLD\n\t\t\t\tfor (let j=1; j<parts.length-2; j++) {\n\t\t\t\t\t// if a part matches a TLD, everything up to it is probably the true URL\n\t\t\t\t\tif (TLDS[parts[j].toLowerCase()]) {\n\t\t\t\t\t\tvar properHost = parts.slice(0, j+1).join(\".\");\n\t\t\t\t\t\t// protocol + properHost + /path\n\t\t\t\t\t\tvar properURL = m[1]+properHost+URL.substr(m[0].length);\n\t\t\t\t\t\tvar proxyHost = parts.slice(j+1).join('.');\n\t\t\t\t\t\turlToProxy[properURL] = {scheme: '%h.' + proxyHost + '/%p', dotsToHyphens};\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn urlToProxy;\n\t};\n\n\t/**\n\t * Determines whether a host is blacklisted, i.e., whether we should refuse to save transparent\n\t * proxy entries for this host. This is necessary because EZProxy offers to proxy all Google and\n\t * Wikipedia subdomains, but in practice, this would get really annoying.\n\t *\n\t * @type Boolean\n\t * @private\n\t */\n\tthis._isBlacklisted = function(host) {\n\t\t/**\n\t\t * Regular expression patterns of hosts never to proxy\n\t\t * @const\n\t\t */\n\t\tconst hostBlacklist = [\n\t\t\t/edu$/,\n\t\t\t/google\\.com$/,\n\t\t\t/wikipedia\\.org$/,\n\t\t\t/^[^.]*$/,\n\t\t\t/doubleclick\\.net$/,\n\t\t\t/^eutils.ncbi.nlm.nih.gov$/\n\t\t];\n\t\t/**\n\t\t * Regular expression patterns of hosts that should always be proxied, regardless of whether\n\t\t * they're on the blacklist\n\t\t * @const\n\t\t */\n\t\tconst hostWhitelist = [\n\t\t\t/^scholar\\.google\\.com$/,\n\t\t\t/^muse\\.jhu\\.edu$/,\n\t\t\t/^(www\\.)?journals\\.uchicago\\.edu$/\n\t\t]\n\n\t\tfor (var blackPattern of hostBlacklist) {\n\t\t\tif (blackPattern.test(host)) {\n\t\t\t\tfor (var whitePattern of hostWhitelist) {\n\t\t\t\t\tif (whitePattern.test(host)) {\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n};\n\n/**\n * Creates a Zotero.Proxy object from a DB row\n *\n * @constructor\n * @class A model for a http proxy server\n */\nZotero.Proxy = function (json={}) {\n\tthis.id = json.id || Date.now();\n\tthis.autoAssociate = json.autoAssociate == undefined ? true : !!json.autoAssociate;\n\tthis.scheme = json.scheme;\n\tthis.hosts = json.hosts || [];\n\tthis.dotsToHyphens = !!json.dotsToHyphens;\n\tif (this.scheme) {\n\t\t// Loading from storage or new\n\t\tthis.compileRegexp();\n\t}\n};\n\n/**\n * Convert the proxy to JSON compatible object\n * @returns {Object}\n */\nZotero.Proxy.prototype.toJSON = function() {\n\tif (!this.scheme) {\n\t\tthrow Error('Cannot convert proxy to JSON - no scheme');\n\t}\n\treturn {id: this.id, scheme: this.scheme, dotsToHyphens: this.dotsToHyphens};\n};\n\n\n/**\n * Regexps to match the URL contents corresponding to proxy scheme parameters\n * @const\n */\nconst Zotero_Proxy_schemeParameters = {\n\t\"%p\": \"(.*?)\",\t// path\n\t\"%d\": \"(.*?)\",\t// directory\n\t\"%f\": \"(.*?)\",\t// filename\n\t\"%a\": \"(.*?)\",\t// anything\n\t\"%h\": \"([a-zA-Z0-9]+[.\\\\-][a-zA-Z0-9.\\\\-]+)\"\t// hostname\n};\n\n/**\n * Regexps to match proxy scheme parameters in the proxy scheme URL\n * @const\n */\nconst Zotero_Proxy_schemeParameterRegexps = {\n\t\"%p\": /([^%])%p/,\n\t\"%d\": /([^%])%d/,\n\t\"%f\": /([^%])%f/,\n\t\"%h\": /([^%])%h/,\n\t\"%a\": /([^%])%a/\n};\n\n\n/**\n * Compiles the regular expression against which we match URLs to determine if this proxy is in use\n * and saves it in this.regexp\n */\nZotero.Proxy.prototype.compileRegexp = function() {\n\tvar indices = this.indices = {};\n\tthis.parameters = [];\n\tfor (var param in Zotero_Proxy_schemeParameters) {\n\t\tvar index = this.scheme.indexOf(param);\n\n\t\t// avoid escaped matches\n\t\twhile (this.scheme[index-1] && (this.scheme[index-1] == \"%\")) {\n\t\t\tthis.scheme = this.scheme.substr(0, index-1)+this.scheme.substr(index);\n\t\t\tindex = this.scheme.indexOf(param, index+1);\n\t\t}\n\n\t\tif (index != -1) {\n\t\t\tthis.indices[param] = index;\n\t\t\tthis.parameters.push(param);\n\t\t}\n\t}\n\n\t// sort params by index\n\tthis.parameters = this.parameters.sort(function(a, b) {\n\t\treturn indices[a]-indices[b];\n\t});\n\n\t// now replace with regexp fragment in reverse order\n\tvar re;\n\tif (this.scheme.includes('://')) {\n\t\tre = \"^\"+Zotero.Utilities.quotemeta(this.scheme)+\"$\";\n\t} else {\n\t\tre = \"^https?\"+Zotero.Utilities.quotemeta('://'+this.scheme)+\"$\";\n\t}\n\tfor(var i=this.parameters.length-1; i>=0; i--) {\n\t\tvar param = this.parameters[i];\n\t\tre = re.replace(Zotero_Proxy_schemeParameterRegexps[param], \"$1\"+Zotero_Proxy_schemeParameters[param]);\n\t}\n\n\tthis.regexp = new RegExp(re);\n}\n\n/**\n * Converts a proxied URL to an unproxied URL using this proxy\n *\n * @param m {Array} The match from running this proxy's regexp against a URL spec\n * @type String\n */\nZotero.Proxy.prototype.toProper = function(m) {\n\tif (!Array.isArray(m)) {\n\t\tlet match = this.regexp.exec(m);\n\t\tif (!match) {\n\t\t\treturn m\n\t\t} else {\n\t\t\tm = match;\n\t\t}\n\t}\n\tlet hostIdx = this.parameters.indexOf(\"%h\");\n\tlet scheme = m[0].indexOf('https') == 0 ? 'https://' : 'http://';\n\tif (hostIdx != -1) {\n\t\tvar properURL = scheme+m[hostIdx+1]+\"/\";\n\t} else {\n\t\tvar properURL = scheme+this.hosts[0]+\"/\";\n\t}\n\t\n\t// Replace `-` with `.` in https to support EZProxy HttpsHyphens.\n\t// Potentially troublesome with domains that contain dashes\n\tif (this.dotsToHyphens ||\n\t\t(this.dotsToHyphens == undefined && scheme == \"https://\") ||\n\t\t!properURL.includes('.')) {\n\t\tproperURL = properURL.replace(/-/g, '.');\n\t}\n\n\tif (this.indices[\"%p\"]) {\n\t\tproperURL += m[this.parameters.indexOf(\"%p\")+1];\n\t} else {\n\t\tvar dir = m[this.parameters.indexOf(\"%d\")+1];\n\t\tvar file = m[this.parameters.indexOf(\"%f\")+1];\n\t\tif (dir !== \"\") properURL += dir+\"/\";\n\t\tproperURL += file;\n\t}\n\n\treturn properURL;\n}\n\n/**\n * Converts an unproxied URL to a proxied URL using this proxy\n *\n * @param {Object|String} uri The URI corresponding to the unproxied URL\n * @type String\n */\nZotero.Proxy.prototype.toProxy = function(uri) {\n\tif (typeof uri == \"string\") {\n\t\turi = url.parse(uri);\n\t\t// If there's no path it is set to null, but we need\n\t\t// at least an empty string to avoid doing many checks\n\t\turi.path = uri.path || '';\n\t}\n\tif (this.regexp.exec(uri.href) || Zotero.Proxies._isBlacklisted(uri.host)) {\n\t\treturn uri.href;\n\t}\n\tvar proxyURL = this.scheme;\n\n\tfor(var i=this.parameters.length-1; i>=0; i--) {\n\t\tvar param = this.parameters[i];\n\t\tvar value = \"\";\n\t\tif (param == \"%h\") {\n\t\t\tvalue = (this.dotsToHyphens && uri.protocol == 'https:') ? uri.host.replace(/\\./g, '-') : uri.host;\n\t\t} else if (param == \"%p\") {\n\t\t\tvalue = uri.path.substr(1);\n\t\t} else if (param == \"%d\") {\n\t\t\tvalue = uri.path.substr(0, uri.path.lastIndexOf(\"/\"));\n\t\t} else if (param == \"%f\") {\n\t\t\tvalue = uri.path.substr(uri.path.lastIndexOf(\"/\")+1)\n\t\t}\n\n\t\tproxyURL = proxyURL.substr(0, this.indices[param])+value+proxyURL.substr(this.indices[param]+2);\n\t}\n\n\tif (proxyURL.includes('://')) {\n\t\treturn proxyURL;\n\t}\n\treturn uri.protocol + '//' + proxyURL;\n}\n\n/**\n * Generate a display name for the proxy (e.g., \"proxy.example.edu (HTTPS)\")\n *\n * @return {String}\n */\nZotero.Proxy.prototype.toDisplayName = function () {\n\ttry {\n\t\tvar parts = this.scheme.match(/^(?:(?:[^:]+):\\/\\/)?([^\\/]+)/);\n\t\tvar domain = parts[1]\n\t\t\t// Include part after %h, if it's present\n\t\t\t.split('%h').pop()\n\t\t\t// Trim leading punctuation after the %h\n\t\t\t.match(/\\W(.+)/)[1];\n\t\treturn domain;\n\t}\n\tcatch (e) {\n\t\tZotero.logError(`Invalid proxy ${this.scheme}: ${e}`);\n\t\treturn this.scheme;\n\t}\n}\n\nmodule.exports = {Proxies: Zotero.Proxies, Proxy: Zotero.Proxy};\n\n})();\n"
  },
  {
    "path": "src/searchEndpoint.js",
    "content": "/*\n    ***** BEGIN LICENSE BLOCK *****\n    \n    Copyright © 2018 Corporation for Digital Scholarship\n                     Vienna, Virginia, USA\n                     https://www.zotero.org\n    \n    This file is part of Zotero.\n    \n    Zotero is free software: you can redistribute it and/or modify\n    it under the terms of the GNU Affero General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n    \n    Zotero 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 Zotero.  If not, see <http://www.gnu.org/licenses/>.\n    \n    ***** END LICENSE BLOCK *****\n*/\n\nconst config = require('config');\nconst Translate = require('./translation/translate');\nconst TextSearch = require('./textSearch');\n\nvar SearchEndpoint = module.exports = {\n\thandle: async function (ctx, next) {\n\t\tctx.assert(ctx.is('text'), 415);\n\t\t\n\t\tvar data = ctx.request.body;\n\t\t\n\t\tif (!data) {\n\t\t\tctx.throw(400, \"POST data not provided\\n\");\n\t\t}\n\t\t\n\t\t// Look for DOI, ISBN, etc.\n\t\tvar identifiers = Zotero.Utilities.extractIdentifiers(data);\n\t\t\n\t\t// Use PMID only if it's the only text in the query, with or without a pmid: prefix\n\t\tif (identifiers.length && identifiers[0].PMID\n\t\t\t\t&& identifiers[0].PMID !== data.replace(/^\\s*(?:pmid:)?([0-9]+)\\s*$/, '$1')) {\n\t\t\tidentifiers = [];\n\t\t}\n\t\t\n\t\t// Text search\n\t\tif (!identifiers.length) {\n\t\t\tawait TextSearch.handle(ctx, next);\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tawait this.handleIdentifier(ctx, identifiers[0]);\n\t},\n\t\n\t\n\thandleIdentifier: async function (ctx, identifier) {\n\t\t// Identifier\n\t\ttry {\n\t\t\tvar translate = new Translate.Search();\n\t\t\ttranslate.setIdentifier(identifier);\n\t\t\tlet translators = await translate.getTranslators();\n\t\t\tif (!translators.length) {\n\t\t\t\tctx.throw(501, \"No translators available\", { expose: true });\n\t\t\t}\n\t\t\ttranslate.setTranslator(translators);\n\t\t\t\n\t\t\tvar items = await translate.translate({\n\t\t\t\tlibraryID: false\n\t\t\t});\n\t\t}\n\t\tcatch (e) {\n\t\t\tif (e == translate.ERROR_NO_RESULTS) {\n\t\t\t\tctx.throw(501, e, { expose: true });\n\t\t\t}\n\t\t\t\n\t\t\tZotero.debug(e, 1);\n\t\t\tctx.throw(\n\t\t\t\t500,\n\t\t\t\t\"An error occurred during translation. \"\n\t\t\t\t\t+ \"Please check translation with the Zotero client.\",\n\t\t\t\t{ expose: true }\n\t\t\t);\n\t\t}\n\t\t\n\t\t// Translation can return multiple items (e.g., a parent item and notes pointing to it),\n\t\t// so we have to return an array with keyed items\n\t\tvar newItems = [];\n\t\titems.forEach(item => {\n\t\t\tnewItems.push(...Zotero.Utilities.Item.itemToAPIJSON(item));\n\t\t});\n\t\t\n\t\tctx.response.body = newItems;\n\t}\n};\n"
  },
  {
    "path": "src/server.js",
    "content": "/* eslint no-process-env: \"off\" */\n\n/*\n    ***** BEGIN LICENSE BLOCK *****\n    \n    Copyright © 2018 Center for History and New Media\n                     George Mason University, Fairfax, Virginia, USA\n                     https://www.zotero.org\n    \n    This file is part of Zotero.\n    \n    Zotero is free software: you can redistribute it and/or modify\n    it under the terms of the GNU Affero General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n    \n    Zotero 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 Zotero.  If not, see <http://www.gnu.org/licenses/>.\n    \n    ***** END LICENSE BLOCK *****\n*/\n\nconst process = require('process');\nconst config = require('config');\nconst Koa = require('koa');\nconst _ = require('koa-route');\nconst bodyParser = require('koa-bodyparser');\nconst cors = require('./cors');\n\n// Prevent UnhandledPromiseRejection crash in Node 15, though this shouldn't be necessary\nprocess.on('unhandledRejection', (reason, promise) => {\n\tZotero.debug('Unhandled rejection: ' + (reason.stack || reason), 1)\n});\n\nrequire('./zotero');\nconst Debug = require('./debug');\nconst Translators = require('./translators');\nconst SearchEndpoint = require('./searchEndpoint');\nconst WebEndpoint = require('./webEndpoint');\nconst ExportEndpoint = require('./exportEndpoint');\nconst ImportEndpoint = require('./importEndpoint');\n\nconst app = module.exports = new Koa();\nif (config.get('trustProxyHeaders')) {\n\tapp.proxy = true;\n}\napp.use(function (ctx, next) {\n\tvar msg = `${ctx.method} ${ctx.url} from ${ctx.request.ip} \"${ctx.headers['user-agent']}\"`;\n\tif (ctx.headers.origin) {\n\t\tmsg += ` (${ctx.headers.origin})`;\n\t}\n\tZotero.debug(msg);\n\treturn next();\n});\napp.use(cors);\napp.use(\n\tbodyParser({\n\t\tenableTypes: ['text', 'json'],\n\t\tjsonLimit: '5mb',\n\t\ttextLimit: '5mb',\n\t})\n);\napp.use(_.post('/web', WebEndpoint.handle.bind(WebEndpoint)));\napp.use(_.post('/search', SearchEndpoint.handle.bind(SearchEndpoint)));\napp.use(_.post('/export', ExportEndpoint.handle.bind(ExportEndpoint)));\napp.use(_.post('/import', ImportEndpoint.handle.bind(ImportEndpoint)));\n\nDebug.init(process.env.DEBUG_LEVEL ? parseInt(process.env.DEBUG_LEVEL) : 1);\nTranslators.init()\n.then(function () {\n\t// Don't start server in test mode, since it's handled by supertest\n\tif (process.env.NODE_ENV == 'test') return;\n\t\n\tvar port = config.get('port');\n\tvar host = config.get('host');\n\tapp.listen(port, host);\n\tDebug.log(`Listening on ${host}:${port}`);\n});\n"
  },
  {
    "path": "src/testEndpoint.js",
    "content": "var fs = require('fs');\nvar path = require('path');\n\nvar TestEndpoint = {\n\thandlePlain: async function (ctx, _next) {\n\t\tctx.response.body = '<html><head><title>Test</title></head><body>Hello</body></html>';\n\t},\n\t\n\thandleSingle: async function (ctx, _next) {\n\t\tvar title = ctx.headers['accept-language'] == 'fr' ? 'Titre' : 'Title';\n\t\tctx.response.body = `<html>\n\t\t\t<head>\n\t\t\t\t<title>${title}</title>\n\t\t\t\t<link rel=\"schema.DC\" href=\"http://purl.org/dc/elements/1.1/\" />\n\t\t\t\t<meta name=\"citation_title\" content=\"${title}\"/>\n\t\t\t</head>\n\t\t\t<body>Body</body>\n\t\t</html>`;\n\t},\n\t\n\thandleMultiple: async function (ctx, _next) {\n\t\tctx.response.body = '<html><body>'\n\t\t\t+ '<span class=\"Z3988\" title=\"url_ver=Z39.88-2004&amp;ctx_ver=Z39.88-2004&amp;rfr_id=info%3Asid%2Fzotero.org%3A2&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Abook&amp;rft.genre=book&amp;rft.btitle=A\"></span>'\n\t\t\t+ '<span class=\"Z3988\" title=\"url_ver=Z39.88-2004&amp;ctx_ver=Z39.88-2004&amp;rfr_id=info%3Asid%2Fzotero.org%3A2&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Abook&amp;rft.genre=book&amp;rft.btitle=B\"></span>'\n\t\t\t+ '<span class=\"Z3988\" title=\"url_ver=Z39.88-2004&amp;ctx_ver=Z39.88-2004&amp;rfr_id=info%3Asid%2Fzotero.org%3A2&amp;rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Abook&amp;rft.genre=book&amp;rft.btitle=C\"></span>'\n\t\t\t+ '</body></html>';\n\t},\n\t\n\thandleRedirect: async function (ctx, _next) {\n\t\tctx.redirect('/test/single');\n\t},\n\t\n\thandleBibTeX: async function (ctx, _next) {\n\t\tctx.set('Content-Type', 'application/x-bibtex');\n\t\tctx.response.body = fs\n\t\t\t.readFileSync(path.join(__dirname, '../test/data/bibtex_response.xml'))\n\t\t\t.toString();\n\t},\n\t\n\tinvalidContentType: async function (ctx, _next) {\n\t\tctx.set('Content-Type', 'image/jpeg');\n\t\tctx.response.body = '';\n\t},\n\t\n\tmissingContentType: async function (ctx, _next) {\n\t\tctx.response.body = null;\n\t}\n};\n\nmodule.exports = TestEndpoint;\n"
  },
  {
    "path": "src/textSearch.js",
    "content": "/*\n    ***** BEGIN LICENSE BLOCK *****\n    \n    Copyright © 2018 Center for History and New Media\n                     George Mason University, Fairfax, Virginia, USA\n                     https://www.zotero.org\n    \n    This file is part of Zotero.\n    \n    Zotero is free software: you can redistribute it and/or modify\n    it under the terms of the GNU Affero General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n    \n    Zotero 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 Zotero.  If not, see <http://www.gnu.org/licenses/>.\n    \n    ***** END LICENSE BLOCK *****\n*/\n\nconst config = require('config');\nconst XRegExp = require('xregexp');\nconst md5 = require('md5');\nconst AWS = require('aws-sdk');\nconst Lambda = new AWS.Lambda({apiVersion: '2015-03-31'});\n\nmodule.exports = {\n\t/**\n\t * Handle text search\n\t *\n\t * @return {Promise<undefined>}\n\t */\n\thandle: async function (ctx, next) {\n\t\t// If identifier-search is disabled in the request or unavailable, return 501\n\t\tif (ctx.request.query.text === '0'\n\t\t\t\t|| !config.has('identifierSearchLambda')\n\t\t\t\t|| !config.get(\"identifierSearchLambda\")) {\n\t\t\tctx.throw(501, \"No identifiers found\", { expose: true });\n\t\t}\n\t\t\n\t\tvar data = ctx.request.body;\n\t\t\n\t\tvar result = await search(\n\t\t\tdata,\n\t\t\tctx.query && ctx.query.start\n\t\t);\n\t\t\n\t\t// Throw selection if two or more items are found, or the selection flag is marked\n\t\tif (result.items.length >= 2 || result.items.length >= 1 && result.select) {\n\t\t\tlet newItems = {};\n\t\t\t\n\t\t\tfor (let item of result.items) {\n\t\t\t\tlet DOI = item.DOI;\n\t\t\t\tlet ISBN = item.ISBN;\n\t\t\t\t\n\t\t\t\tif (!DOI && item.extra) {\n\t\t\t\t\tlet m = item.extra.match(/DOI: (.*)/);\n\t\t\t\t\tif (m) DOI = m[1];\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (!ISBN && item.extra) {\n\t\t\t\t\tlet m = item.extra.match(/ISBN: (.*)/);\n\t\t\t\t\tif (m) ISBN = m[1];\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tlet identifier;\n\t\t\t\t// DOI has a priority over ISBN for items that have both\n\t\t\t\tif (DOI) {\n\t\t\t\t\tidentifier = DOI;\n\t\t\t\t}\n\t\t\t\telse if (item.ISBN) {\n\t\t\t\t\tidentifier = ISBN.split(' ')[0];\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tnewItems[identifier] = {\n\t\t\t\t\titemType: item.itemType,\n\t\t\t\t\ttitle: item.title,\n\t\t\t\t\tdescription: formatDescription(item),\n\t\t\t\t};\n\t\t\t}\n\t\t\t\n\t\t\t// If there were more results, include a link to the next result set\n\t\t\tif (result.next) {\n\t\t\t\tctx.set('Link', `</search?start=${result.next}>; rel=\"next\"`);\n\t\t\t}\n\t\t\tctx.response.status = 300;\n\t\t\t\n\t\t\t\n\t\t\t//\n\t\t\t// TODO: Differentiate from web request 300\n\t\t\t//\n\t\t\t\n\t\t\t\n\t\t\tctx.response.body = newItems;\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tif (result.items.length === 1) {\n\t\t\tctx.response.body = Zotero.Utilities.Item.itemToAPIJSON(result.items[0]);\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tctx.response.body = [];\n\t},\n\t\n\t// Expose for stubbing in tests\n\tqueryLambda: async function (query) {\n\t\tlet params = {\n\t\t\tFunctionName: config.get('identifierSearchLambda'),\n\t\t\tInvocationType: 'RequestResponse',\n\t\t\tPayload: JSON.stringify({query})\n\t\t};\n\t\t\n\t\tlet result = await Lambda.invoke(params).promise();\n\t\t\n\t\tif (result.FunctionError) {\n\t\t\tthrow new Error('Lambda error: ' + result.Payload);\n\t\t}\n\t\t\n\t\tidentifiers = JSON.parse(result.Payload);\n\t\treturn identifiers;\n\t}\n};\n\n\nasync function search(query, start) {\n\tconst timeout = config.get('textSearchTimeout') * 1000;\n\tconst startTime = new Date();\n\tconst numResults = 3;\n\tlet identifiers;\n\tlet moreResults = false;\n\ttry {\n\t\tidentifiers = await module.exports.queryLambda(query);\n\t\t\n\t\t// If passed a start= parameter, skip ahead\n\t\tlet startPos = 0;\n\t\tif (start) {\n\t\t\tfor (let i = 0; i < identifiers.length; i++) {\n\t\t\t\tif (identifierToToken(identifiers[i]) == start) {\n\t\t\t\t\tstartPos = i + 1;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tif (identifiers.length > startPos + numResults + 1) {\n\t\t\tmoreResults = true;\n\t\t}\n\t\t\n\t\tidentifiers = identifiers.slice(startPos);\n\t} catch(e) {\n\t\tZotero.debug(e, 1);\n\t\treturn {select: false, items: []};\n\t}\n\t\n\tlet items = [];\n\tlet nextLastIdentifier = null;\n\tfor (let identifier of identifiers) {\n\t\tlet translate = new Zotero.Translate.Search();\n\t\ttry {\n\t\t\ttranslate.setIdentifier(identifier);\n\t\t\tlet translators = await translate.getTranslators();\n\t\t\tif (!translators.length) {\n\t\t\t\tif (new Date() > startTime.getTime() + timeout) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\ttranslate.setTranslator(translators);\n\t\t\t\n\t\t\tlet newItems = await translate.translate({\n\t\t\t\tlibraryID: false\n\t\t\t});\n\n\t\t\tif (newItems.length) {\n\t\t\t\tlet seq = getLongestCommonSequence(newItems[0].title, query);\n\t\t\t\tif (seq.length >= 6 && seq.split(' ').length >= 2) {\n\t\t\t\t\titems.push(newItems[0]);\n\t\t\t\t\t// Keep track of last identifier if we're limiting results\n\t\t\t\t\tif (moreResults) {\n\t\t\t\t\t\tnextLastIdentifier = identifier;\n\t\t\t\t\t}\n\t\t\t\t\tif (items.length == numResults) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tcatch (e) {\n\t\t\tif (e !== translate.ERROR_NO_RESULTS) {\n\t\t\t\tZotero.debug(e, 1);\n\t\t\t}\n\t\t}\n\t\tif (new Date() > startTime.getTime() + timeout) {\n\t\t\tbreak;\n\t\t}\n\t}\n\t\n\treturn {\n\t\t// Force item selection, even for a single item\n\t\tselect: true,\n\t\titems,\n\t\tnext: nextLastIdentifier ? identifierToToken(nextLastIdentifier) : null\n\t};\n\t\n\t// // Query Crossref and LoC/GBV in parallel to respond faster to the client\n\t// let [crossrefItems, libraryItems] = await Promise.all([queryCrossref(query), queryLibraries(query)]);\n\t//\n\t// // Subtract book reviews from Crossref\n\t// crossrefItems = subtractCrossrefItems(crossrefItems, libraryItems);\n\t//\n\t// let items = crossrefItems.concat(libraryItems);\n\t//\n\t// // Filter out too fuzzy items, by comparing item title (and other metadata) against query\n\t// return await filterResults(items, query);\n}\n\n\nfunction formatDescription(item) {\n\tlet parts = [];\n\t\n\tlet authors = [];\n\tfor (let creator of item.creators) {\n\t\tif (creator.creatorType === 'author' && creator.lastName) {\n\t\t\tauthors.push(creator.lastName);\n\t\t\tif (authors.length === 3) break;\n\t\t}\n\t}\n\t\n\tif(authors.length) parts.push(authors.join(', '));\n\t\n\tif (item.date) {\n\t\tlet m = item.date.toString().match(/[0-9]{4}/);\n\t\tif (m) parts.push(m[0]);\n\t}\n\t\n\tif(item.publicationTitle) {\n\t\tparts.push(item.publicationTitle);\n\t} else if(item.publisher) {\n\t\tparts.push(item.publisher);\n\t}\n\t\n\treturn parts.join(' \\u2013 ');\n}\n\n\nfunction subtractCrossrefItems(crossrefItems, libraryItems) {\n\tlet items = [];\n\tfor(let crossrefItem of crossrefItems) {\n\t\t// Keep books and book sections\n\t\tif(['book', 'bookSection'].includes(crossrefItem.itemType)) {\n\t\t\titems.push(crossrefItem);\n\t\t\tcontinue;\n\t\t}\n\t\t\n\t\tlet crossrefTitle = crossrefItem.title;\n\t\t// Remove all tags\n\t\tcrossrefTitle = crossrefTitle.replace(/<\\/?\\w+[^<>]*>/gi, '');\n\t\tcrossrefTitle = crossrefTitle.replace(/:/g, ' ');\n\t\t\n\t\t// Normalize title, split to words, filter out empty array elements\n\t\tcrossrefTitle = normalize(crossrefTitle).split(' ').filter(x => x).join(' ');\n\t\t\n\t\tlet found = false;\n\t\tfor(let libraryItem of libraryItems) {\n\t\t\tlet libraryTitle = libraryItem.title;\n\t\t\t// Remove all tags\n\t\t\tlibraryTitle = libraryTitle.replace(/<\\/?\\w+[^<>]*>/gi, '');\n\t\t\tlibraryTitle = libraryTitle.replace(/:/g, ' ');\n\t\t\t\n\t\t\t// Normalize title, split to words, filter out empty array elements\n\t\t\tlibraryTitle = normalize(libraryTitle).split(' ').filter(x => x).join(' ');\n\t\t\t\n\t\t\tif(crossrefTitle.includes(libraryTitle)) {\n\t\t\t\tfound = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t\n\t\tif(!found) {\n\t\t\titems.push(crossrefItem);\n\t\t}\n\t}\n\t\n\treturn items;\n}\n\nasync function queryCrossref(query) {\n\tlet items = [];\n\ttry {\n\t\tlet translate = new Zotero.Translate.Search();\n\t\t// Crossref REST\n\t\ttranslate.setTranslator(\"0a61e167-de9a-4f93-a68a-628b48855909\");\n\t\ttranslate.setSearch({query});\n\t\titems = await translate.translate({libraryID: false});\n\t}\n\tcatch (e) {\n\t\tZotero.debug(e, 2);\n\t}\n\treturn items;\n}\n\n/**\n * Queries LoC and if that fails, queries GBV\n */\nasync function queryLibraries(query) {\n\tlet items = [];\n\ttry {\n\t\tlet translate = new Zotero.Translate.Search();\n\t\t// Library of Congress ISBN\n\t\ttranslate.setTranslator(\"c070e5a2-4bfd-44bb-9b3c-4be20c50d0d9\");\n\t\ttranslate.setSearch({query});\n\t\titems = await translate.translate({libraryID: false});\n\t}\n\tcatch (e) {\n\t\tZotero.debug(e, 2);\n\t\ttry {\n\t\t\tlet translate = new Zotero.Translate.Search();\n\t\t\t// Gemeinsamer Bibliotheksverbund ISBN\n\t\t\ttranslate.setTranslator(\"de0eef58-cb39-4410-ada0-6b39f43383f9\");\n\t\t\ttranslate.setSearch({query});\n\t\t\titems = await translate.translate({libraryID: false});\n\t\t}\n\t\tcatch (e) {\n\t\t\tZotero.debug(e, 2);\n\t\t}\n\t}\n\treturn items;\n}\n\n/**\n * Decomposes all accents and ligatures,\n * filters out symbols that aren't space or alphanumeric,\n * and lowercases alphabetic symbols.\n */\nfunction normalize(text) {\n\tlet rx = XRegExp('[^\\\\pL 0-9]', 'g');\n\ttext = XRegExp.replace(text, rx, '');\n\ttext = text.normalize('NFKD');\n\ttext = XRegExp.replace(text, rx, '');\n\ttext = text.toLowerCase();\n\treturn text;\n}\n\n/**\n * Checks if a given word equals to any of the authors' names\n */\nfunction hasAuthor(authors, word) {\n\treturn authors.some(author => {\n\t\treturn (author.firstName && normalize(author.firstName).split(' ').includes(word))\n\t\t\t|| (author.lastName && normalize(author.lastName).split(' ').includes(word));\n\t});\n}\n\n/**\n * Tries to find the longest common words sequence between\n * item title and query text. Query text must include title (or part of it)\n * from the beginning. If there are leftover query words, it tries to\n * validate them against item metadata (currently only authors and year)\n */\nasync function filterResults(items, query) {\n\tlet filteredItems = [];\n\tlet select = false;\n\n\t// Normalize query, split to words, filter out empty array elements\n\tlet queryWords = normalize(query).split(' ').filter(x => x);\n\t\n\tfor (let item of items) {\n\t\tlet DOI = item.DOI;\n\t\tlet ISBN = item.ISBN;\n\t\t\n\t\tif (!DOI && item.extra) {\n\t\t\tlet m = item.extra.match(/DOI: (.*)/);\n\t\t\tif (m) DOI = m[1];\n\t\t}\n\t\t\n\t\tif (!ISBN && item.extra) {\n\t\t\tlet m = item.extra.match(/ISBN: (.*)/);\n\t\t\tif (m) ISBN = m[1];\n\t\t}\n\t\t\n\t\tif (!DOI && !ISBN) continue;\n\t\tlet title = item.title;\n\t\t// Remove all tags\n\t\ttitle = title.replace(/<\\/?\\w+[^<>]*>/gi, '');\n\t\ttitle = title.replace(/:/g, ' ');\n\t\t\n\t\t// Normalize title, split to words, filter out empty array elements\n\t\tlet titleWords = normalize(title).split(' ').filter(x => x);\n\t\t\n\t\tlet longestFrom = 0;\n\t\tlet longestLen = 0;\n\t\t\n\t\t// Finds the longest common words sequence between query text and item.title\n\t\tfor (let i = 0; i < queryWords.length; i++) {\n\t\t\tfor (let j = queryWords.length; j > 0; j--) {\n\t\t\t\tlet a = queryWords.slice(i, j);\n\t\t\t\tfor (let k = 0; k < titleWords.length - a.length + 1; k++) {\n\t\t\t\t\tlet b = titleWords.slice(k, a.length + k);\n\t\t\t\t\tif (a.length && b.length && a.join(' ') === b.join(' ')) {\n\t\t\t\t\t\tif (a.length > longestLen) {\n\t\t\t\t\t\t\tlongestFrom = i;\n\t\t\t\t\t\t\tlongestLen = b.length;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\t// At least two common words sequence must be found between query and title\n\t\tif (longestLen < 1) continue;\n\t\t\n\t\t// Longest common sequence of words\n\t\tlet foundPart = queryWords.slice(longestFrom, longestLen);\n\t\t\n\t\t// Remaining words\n\t\tlet rems = queryWords.slice(0, longestFrom);\n\t\trems = rems.concat(queryWords.slice(longestLen));\n\t\t\n\t\t// If at least one remaining word is left, it tries to compare it against item metadata.\n\t\t// Otherwise the whole query text is found in the title, and we have a full match\n\t\tif (rems.length) {\n\t\t\tlet foundAuthor = false;\n\t\t\tlet needYear = false;\n\t\t\tlet foundYear = false;\n\t\t\t\n\t\t\t// Still remaining words\n\t\t\tlet rems2 = [];\n\t\t\t\n\t\t\tfor (let rem of rems) {\n\t\t\t\t// Ignore words\n\t\t\t\tif (['the', 'a', 'an'].indexOf(rem) >= 0) continue;\n\t\t\t\t\n\t\t\t\t// If the remaining word has at least 2 chars and exists in metadata authors\n\t\t\t\tif (rem.length >= 2 && hasAuthor(item.creators, rem)) {\n\t\t\t\t\tfoundAuthor = true;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t// If the remaining word is a 4 digit number (year)\n\t\t\t\tif (/^[0-9]{4}$/.test(rem)) {\n\t\t\t\t\tneedYear = true;\n\t\t\t\t\t\n\t\t\t\t\tif (item.date) {\n\t\t\t\t\t\t// If the remaining word exists in the item date\n\t\t\t\t\t\tlet m = item.date.toString().match(/[0-9]{4}/);\n\t\t\t\t\t\tif (m && m[0] === rem) {\n\t\t\t\t\t\t\tfoundYear = true;\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t// Push the word that is still remaining\n\t\t\t\trems2.push(rem);\n\t\t\t}\n\t\t\t\n\t\t\t// If a year exists in the query, but is not matched to the item date\n\t\t\tif (needYear && !foundYear) continue;\n\t\t\t\n\t\t\t// If there are still remaining words and none of authors are found\n\t\t\tif (rems2.length && !foundAuthor) continue;\n\t\t}\n\t\t\n\t\t// If the query part that was found in title is shorter than 30 symbols\n\t\tif (foundPart.join(' ').length < 30) select = true;\n\t\t\n\t\tfilteredItems.push({\n\t\t\tmatchedLen: foundPart.join(' ').length,\n\t\t\ttitleLen: titleWords.join(' ').length,\n\t\t\titem\n\t\t});\n\t}\n\t\n\t// Sort results by matched text length\n\t// and how close the matched text length is to title length\n\tfilteredItems.sort(function (a, b) {\n\t\tif (b.matchedLen < a.matchedLen) return -1;\n\t\tif (b.matchedLen > a.matchedLen) return 1;\n\t\treturn Math.abs(a.matchedLen - a.titleLen) - Math.abs(b.matchedLen - b.titleLen);\n\t});\n\t\n\tfilteredItems = filteredItems.map(item => item.item);\n\t\n\treturn {select, items: filteredItems};\n}\n\nfunction getLongestCommonSequence(title, query) {\n\ttitle = title.replace(/<\\/?\\w+[^<>]*>/gi, '');\n\ttitle = title.replace(/:/g, ' ');\n\t\n\tquery = query.replace(/:/g, ' ');\n\t\n\t// Normalize, split to words and filter out empty array elements\n\tlet titleWords = normalize(title).split(' ').filter(x => x);\n\tlet queryWords = normalize(query).split(' ').filter(x => x);\n\t\n\tlet longestFrom = 0;\n\tlet longestLen = 0;\n\t\n\t// Finds the longest common words sequence between query text and item.title\n\tfor (let i = 0; i < queryWords.length; i++) {\n\t\tfor (let j = queryWords.length; j > 0; j--) {\n\t\t\tlet a = queryWords.slice(i, j);\n\t\t\tfor (let k = 0; k < titleWords.length - a.length + 1; k++) {\n\t\t\t\tlet b = titleWords.slice(k, a.length + k);\n\t\t\t\tif (a.length && b.length && a.join(' ') === b.join(' ')) {\n\t\t\t\t\tif (a.length > longestLen) {\n\t\t\t\t\t\tlongestFrom = i;\n\t\t\t\t\t\tlongestLen = b.length;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\treturn queryWords.slice(longestFrom, longestFrom + longestLen).join(' ');\n}\n\nfunction identifierToToken(identifier) {\n\treturn md5(JSON.stringify(identifier));\n}\n"
  },
  {
    "path": "src/translation/sandboxManager.js",
    "content": "/*\n    ***** BEGIN LICENSE BLOCK *****\n    \n    Copyright © 2009 Center for History and New Media\n                     George Mason University, Fairfax, Virginia, USA\n                     http://zotero.org\n    \n    This file is part of Zotero.\n    \n    Zotero is free software: you can redistribute it and/or modify\n    it under the terms of the GNU Affero General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n    \n    Zotero 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 Zotero.  If not, see <http://www.gnu.org/licenses/>.\n    \n    ***** END LICENSE BLOCK *****\n*/\n\n\n/**\n * @class Manages the translator sandbox\n * @param {Translate} translate\n * @param {String|window} sandboxLocation\n */\nvar SandboxManager = function(sandboxLocation) {\n\tthis.sandbox = {\n\t\t\"Zotero\":{},\n\t\tPromise,\n\t};\n};\n\nSandboxManager.prototype = {\n\t/**\n\t * Evaluates code in the sandbox\n\t * @param {String} code Code to evaluate\n\t * @param {String[]} functions Functions to import into the sandbox (rather than leaving\n\t *                                 as inner functions)\n\t */\n\teval: function(code, functions) {\n\t\t// delete functions to import\n\t\tfor (var i in functions) {\n\t\t\tdelete this.sandbox[functions[i]];\n\t\t}\n\n\t\t// Prepend sandbox properties within eval environment (what a mess (1))\n\t\tfor (var prop in this.sandbox) {\n\t\t\tcode = 'var ' + prop + ' = this.sandbox.' + prop + ';' + code;\n\t\t}\n\n\t\t// Import inner functions back into the sandbox\n\t\tfor (var i in functions) {\n\t\t\t// TODO: Omit in translate.js?\n\t\t\tif (functions[i] == 'detectExport') continue;\n\t\t\t\n\t\t\ttry {\n\t\t\t\tcode += 'this.sandbox.' + functions[i] + ' = ' + functions[i] + ';';\n\t\t\t} catch (e) {\n\t\t\t}\n\t\t}\n\n\t\t// Eval in a closure\n\t\t(function() {\n\t\t\teval(code);\n\t\t}).call(this);\n\t},\n\t\n\t/**\n\t * Imports an object into the sandbox\n\t *\n\t * @param {Object} object Object to be imported (under Zotero)\n\t * @param {Boolean} passTranslateAsFirstArgument Whether the translate instance should be passed\n\t *     as the first argument to the function.\n\t */\n\timportObject: function(object, passAsFirstArgument, attachTo) {\n\t\tif(!attachTo) attachTo = this.sandbox.Zotero;\n\t\t\n\t\tfor(var key in (object.__exposedProps__ ? object.__exposedProps__ : object)) {\n\t\t\tif(Function.prototype[key]) continue;\n\t\t\tif(typeof object[key] === \"function\" || typeof object[key] === \"object\") {\n\t\t\t\t// magic closures\n\t\t\t\tattachTo[key] = new function() {\n\t\t\t\t\tvar fn = object[key];\n\t\t\t\t\treturn function() {\n\t\t\t\t\t\tvar args = (passAsFirstArgument ? [passAsFirstArgument] : []);\n\t\t\t\t\t\tfor(var i=0; i<arguments.length; i++) {\n\t\t\t\t\t\t\targs.push(arguments[i]);\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\treturn fn.apply(object, args);\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t// attach members\n\t\t\t\tthis.importObject(object[key], passAsFirstArgument ? passAsFirstArgument : null, attachTo[key]);\n\t\t\t} else {\n\t\t\t\tattachTo[key] = object[key];\n\t\t\t}\n\t\t}\n\t}\n}\n\nmodule.exports = SandboxManager;\n"
  },
  {
    "path": "src/translation/translate.js",
    "content": "/*\n\t***** BEGIN LICENSE BLOCK *****\n\t\n\tCopyright © 2018 Center for History and New Media\n\t\t\t\t\tGeorge Mason University, Fairfax, Virginia, USA\n\t\t\t\t\thttp://zotero.org\n\t\n\tThis file is part of Zotero.\n\t\n\tZotero is free software: you can redistribute it and/or modify\n\tit under the terms of the GNU Affero General Public License as published by\n\tthe Free Software Foundation, either version 3 of the License, or\n\t(at your option) any later version.\n\t\n\tZotero is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n\tGNU Affero General Public License for more details.\n\n\tYou should have received a copy of the GNU Affero General Public License\n\talong with Zotero.  If not, see <http://www.gnu.org/licenses/>.\n\t\n\t***** END LICENSE BLOCK *****\n*/\n\nZotero.Translate = Zotero.requireTranslate('./translation/translate');\n\nZotero.Translate = {...Zotero.Translate,\n\tSandboxManager: require('./sandboxManager'),\n\t...require('./translate_item')\n};\nZotero.Translate.ItemSaver.prototype.saveItems = async function (jsonItems, attachmentCallback, itemsDoneCallback) {\n\tthis.items = (this.items || []).concat(jsonItems)\n\treturn jsonItems\n}\n\n// Translation architecture shims and monkey-patches\nvar wgxpath = require('wicked-good-xpath');\nglobal.XPathResult = wgxpath.XPathResultType;\nvar jsdom = require('jsdom');\nvar { JSDOM } = jsdom;\nvar serializeNode = require(\"w3c-xmlserializer\");\n\n// Shim innerText for JSDOM, see https://github.com/jsdom/jsdom/issues/1245\n// JSDOM interfaces are recreated per instance, so we use the beforeParse hook\n// to apply shims once per instance (not on every window access).\nfunction shimInnerText(window) {\n\tObject.defineProperty(window.Attr.prototype, 'innerText', {\n\t\tget() {\n\t\t\treturn this.textContent;\n\t\t},\n\t\tset(value) {\n\t\t\tthis.textContent = value;\n\t\t},\n\t\tconfigurable: true,\n\t});\n\tObject.defineProperty(window.Node.prototype, 'innerText', {\n\t\tget() {\n\t\t\t// innerText in the browser is more sophisticated, but this removes most unwanted content\n\t\t\t// https://github.com/jsdom/jsdom/issues/1245#issuecomment-584677454\n\t\t\tlet el = this.cloneNode(true);\n\t\t\tel.querySelectorAll('script, style').forEach(s => s.remove());\n\t\t\treturn el.textContent;\n\t\t},\n\t\tset(value) {\n\t\t\tthis.textContent = value;\n\t\t},\n\t\tconfigurable: true,\n\t});\n}\n\n// Wrap JSDOM constructor to inject innerText shim via beforeParse for all instances\njsdom.JSDOM = class extends JSDOM {\n\tconstructor(input, options = {}) {\n\t\tvar originalBeforeParse = options.beforeParse;\n\t\toptions.beforeParse = function (window) {\n\t\t\tshimInnerText(window);\n\t\t\tif (originalBeforeParse) {\n\t\t\t\toriginalBeforeParse(window);\n\t\t\t}\n\t\t};\n\t\tsuper(input, options);\n\t}\n};\nJSDOM = jsdom.JSDOM;\n\nvar dom = new JSDOM('<html></html>');\nwgxpath.install(dom.window, true);\nglobal.DOMParser = dom.window.DOMParser;\nglobal.XMLSerializer = class XMLSerializer {\n\tserializeToString(node) {\n\t\treturn serializeNode(node);\n\t}\n};\n\nmodule.exports = Zotero.Translate;\n"
  },
  {
    "path": "src/translation/translate_item.js",
    "content": "/*\n    ***** BEGIN LICENSE BLOCK *****\n    \n    Copyright © 2011 Center for History and New Media\n                     George Mason University, Fairfax, Virginia, USA\n                     http://zotero.org\n    \n    This file is part of Zotero.\n    \n    Zotero is free software: you can redistribute it and/or modify\n    it under the terms of the GNU Affero General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n    \n    Zotero 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 Zotero.  If not, see <http://www.gnu.org/licenses/>.\n    \n    ***** END LICENSE BLOCK *****\n*/\n\nItemSaver = function(libraryID, attachmentMode, forceTagType) {};\nItemSaver.ATTACHMENT_MODE_IGNORE = 0;\nItemSaver.ATTACHMENT_MODE_DOWNLOAD = 1;\nItemSaver.ATTACHMENT_MODE_FILE = 2;\n\n// We don't define a real itemSaver here because Zotero.Translate will always be run in object-only\n// mode, but we do define a saveCollection no-op.\nItemSaver.prototype.saveCollection = function() {};\n\nItemGetter = function() {\n\tthis._itemsLeft = null;\n\tthis._collectionsLeft = null;\n\tthis._itemID = 1;\n};\n\nItemGetter.prototype = {\n\t\"setItems\":function(items) {\n\t\tthis._itemsLeft = items;\n\t\tthis.numItems = this._itemsLeft.length;\n\t},\n\t\n\t/**\n\t * Retrieves the next available item\n\t */\n\t\"nextItem\":function() {\n\t\tif(!this._itemsLeft.length) return false;\n\t\tvar item = this._itemsLeft.shift();\n\t\tif (this.legacy) {\n\t\t\titem = Zotero.Utilities.Item.itemToLegacyExportFormat(item);\n\t\t}\n\t\tif (!item.attachments) {\n\t\t\titem.attachments = [];\n\t\t}\n\t\tif (!item.notes) {\n\t\t\titem.notes = [];\n\t\t}\n\n\t\t// convert single field creators to format expected by export\n\t\tif(item.creators) {\n\t\t\tfor(var i=0; i<item.creators.length; i++) {\n\t\t\t\tvar creator = item.creators[i];\n\t\t\t\tif(creator.name) {\n\t\t\t\t\tcreator.lastName = creator.name;\n\t\t\t\t\tcreator.firstName = \"\";\n\t\t\t\t\tdelete creator.name;\n\t\t\t\t\tcreator.fieldMode = 1;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\titem.itemID = this._itemID++;\n\t\treturn item;\n\t},\n\t\n\t\"nextCollection\":function() {\n\t\treturn false;\n\t},\n\t\n\texportFiles: function () {}\n}\nItemGetter.prototype.__defineGetter__(\"numItemsRemaining\", function() { return this._itemsLeft.length });\n\nmodule.exports = {ItemSaver, ItemGetter}"
  },
  {
    "path": "src/translators.js",
    "content": "/*\n    ***** BEGIN LICENSE BLOCK *****\n    \n    Copyright © 2009 Center for History and New Media\n                     George Mason University, Fairfax, Virginia, USA\n                     http://zotero.org\n    \n    This file is part of Zotero.\n    \n    Zotero is free software: you can redistribute it and/or modify\n    it under the terms of the GNU Affero General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n    \n    Zotero 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 Zotero.  If not, see <http://www.gnu.org/licenses/>.\n    \n    ***** END LICENSE BLOCK *****\n*/\n\n// Enumeration of types of translators\nvar TRANSLATOR_TYPES = {\"import\":1, \"export\":2, \"web\":4, \"search\":8};\n\nconst fs = require('fs');\nconst path = require('path');\n\nvar Translators = Zotero.requireTranslate('./translators');\n\n/**\n * Singleton to handle loading and caching of translators\n * @namespace\n */\nTranslators = Object.assign(Translators, new function() {\n\tvar _cache, _translators;\n\tvar _initialized = false;\n\tconst infoRe = /^\\s*{[\\S\\s]*?}\\s*?[\\r\\n]/;\n\t\n\t/**\n\t * Initializes translator cache, loading all translators into memory\n\t * @param {Zotero.Translators[]} [translators] List of translators. If not specified, they will be\n     * retrieved from storage.\n\t */\n\tthis.init = async function(translators) {\n\t\tif(!translators) {\n\t\t\ttranslators = await this.load();\n\t\t}\n\t\t\n\t\t_cache = {\"import\":[], \"export\":[], \"web\":[], \"search\":[]};\n\t\t_translators = {};\n\t\t_initialized = true;\n\t\t\n\t\t// Build caches\n\t\tfor(var i=0; i<translators.length; i++) {\n\t\t\ttry {\n\t\t\t\tvar translator = new Zotero.Translator(translators[i]);\n\t\t\t\t_translators[translator.translatorID] = translator;\n\t\t\t\t\n\t\t\t\tfor(var type in TRANSLATOR_TYPES) {\n\t\t\t\t\tif(translator.translatorType & TRANSLATOR_TYPES[type]) {\n\t\t\t\t\t\t_cache[type].push(translator);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} catch(e) {\n\t\t\t\tZotero.logError(e);\n\t\t\t\ttry {\n\t\t\t\t\tZotero.logError(\"Could not load translator \"+JSON.stringify(translators[i]));\n\t\t\t\t} catch(e) {}\n\t\t\t}\n\t\t}\n\t\t\n\t\t// Sort by priority\n\t\tvar cmp = function (a, b) {\n\t\t\tif (a.priority > b.priority) {\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\telse if (a.priority < b.priority) {\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t}\n\t\tfor(var type in _cache) {\n\t\t\t_cache[type].sort(cmp);\n\t\t}\n\t\tZotero.debug(`Translators initialized with ${translators.length} loaded`);\n\t};\n\t\n\tthis.load = async function() {\n\t\tvar translatorsDirPath = path.resolve(path.resolve(__dirname, '..'), Zotero.Prefs.get(\"translatorsDirectory\"));\n\t\t\n\t\tif(!await new Promise(resolve => fs.access(translatorsDirPath, (err) => resolve(!err)))) {\n\t\t\tthrow new Error(\"Translators directory \"+translatorsDirPath+\" is not \"+\n\t\t\t\t\"accessible. Please set this correctly in config.js.\\n\")\n\t\t}\n\n\t\tvar translatorFilePaths = await new Promise((resolve, reject) => \n\t\t\tfs.readdir(translatorsDirPath, (err, files) => err ? reject(err) : resolve(files)));\n\t\tvar translators = [];\n\t\tfor (let filePath of translatorFilePaths)  {\n\t\t\tif (filePath[0] === '.' || filePath.substr(filePath.length-3) !== \".js\") continue;\n\t\t\tfilePath = path.resolve(translatorsDirPath, filePath);\n\t\t\tvar data = await new Promise((resolve, reject) => \n\t\t\t\tfs.readFile(filePath, \"utf8\", (err, data) => err ? reject(err) : resolve(data)));\n\t\t\t\n\t\t\t// Strip off byte order mark, if one exists\n\t\t\tif(data[0] === \"\\uFEFF\") data = data.substr(1);\n\t\t\t\n\t\t\t// We assume lastUpdated is at the end to avoid running the regexp on more than necessary\n\t\t\tvar lastUpdatedIndex = data.indexOf('\"lastUpdated\"');\n\t\t\tif (lastUpdatedIndex == -1) {\n\t\t\t\tZotero.debug(\"Invalid or missing translator metadata JSON object in \" + filename);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t\n\t\t\t// Add 50 characters to clear lastUpdated timestamp and final \"}\"\n\t\t\tvar header = data.substr(0, lastUpdatedIndex + 50);\n\t\t\tvar m = infoRe.exec(header);\n\t\t\tif (!m) {\n\t\t\t\tZotero.debug(\"Invalid or missing translator metadata JSON object in \" + filename);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t\n\t\t\tvar metadataString = m[0];\n\t\t\t\n\t\t\ttry {\n\t\t\t\tvar info = JSON.parse(metadataString);\n\t\t\t} catch(e) {\n\t\t\t\tZotero.debug(\"Invalid or missing translator metadata JSON object in \" + filename);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tinfo.code = data;\n\t\t\t// We don't ever want to reload from disk again (and don't have the code to do that either)\n\t\t\tinfo.cacheCode = true;\n\t\t\t\n\t\t\ttranslators.push(info);\n\t\t}\n\t\treturn translators;\n\t};\n\t\n\t/**\n\t * Gets the translator that corresponds to a given ID\n\t *\n\t * @param {String} id The ID of the translator\n\t */\n\tthis.get = function (id) {\n\t\tif (!_initialized) {\n\t\t\tthrow new Error(\"Trying to retrieve a translator without initalizing translator store\");\n\t\t}\n\t\tvar translator = _translators[id];\n\t\tif (!translator) {\n\t\t\treturn false;\n\t\t}\n\t\treturn translator;\n\t};\n\t\n\t/**\n\t * Gets all translators for a specific type of translation\n\t * @param {String} type The type of translators to get (import, export, web, or search)\n\t * @param {Boolean} [debugMode] Whether to assume debugging mode. If true, code is included for \n\t *                              unsupported translators, and code originally retrieved from the\n\t *                              repo is re-retrieved from Zotero Standalone.\n\t */\n\tthis.getAllForType = async function (type, debugMode) {\n\t\tif(!_initialized) Zotero.Translators.init()\n\t\tvar translators = _cache[type].slice(0);\n\t\tvar codeGetter = new Zotero.Translators.CodeGetter(translators, debugMode);\n\t\treturn codeGetter.getAll().then(function() {\n\t\t\treturn translators;\n\t\t});\n\t};\n\n\tthis.getCodeForTranslator = Zotero.Promise.method(function (translator) {\n\t\tif (translator.code) {\n\t\t\treturn translator.code;\n\t\t} else {\n\t\t\tthrow new Error(`Code for translator ${translator.translatorID} is missing`);\n\t\t}\n\t});\n\t\n\t/**\n\t * Gets web translators for a specific location\n\t * @param {String} uri The URI for which to look for translators\n\t * @return {Promise<Array[]>} - A promise for a 2-item array containing an array of translators and\n\t *     an array of functions for converting URLs from proper to proxied forms\n\t */\n\tthis.getWebTranslatorsForLocation = async function (URI, rootURI) {\n\t\tvar isFrame = URI !== rootURI;\n\t\tif(!_initialized) Zotero.Translators.init();\n\t\tvar allTranslators = _cache[\"web\"];\n\t\tvar potentialTranslators = [];\n\t\tvar proxies = [];\n\t\t\n\t\tvar rootSearchURIs = Zotero.Proxies.getPotentialProxies(rootURI);\n\t\tvar frameSearchURIs = isFrame ? Zotero.Proxies.getPotentialProxies(URI) : rootSearchURIs;\n\n\t\tZotero.debug(\"Translators: Looking for translators for \"+Object.keys(frameSearchURIs).join(', '));\n\n\t\tfor(var i=0; i<allTranslators.length; i++) {\n\t\t\tvar translator = allTranslators[i];\n\t\t\tif (isFrame && !translator.webRegexp.all) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\trootURIsLoop:\n\t\t\tfor(var rootSearchURI in rootSearchURIs) {\n\t\t\t\tvar isGeneric = !allTranslators[i].webRegexp.root;\n\t\t\t\t// don't attempt to use generic translators that can't be run in this browser\n\t\t\t\t// since that would require transmitting every page to Zotero host\n\t\t\t\tif(isGeneric && allTranslators[i].runMode !== Zotero.Translator.RUN_MODE_IN_BROWSER) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tvar rootURIMatches = isGeneric || rootSearchURI.length < 8192 && translator.webRegexp.root.test(rootSearchURI);\n\t\t\t\tif (translator.webRegexp.all && rootURIMatches) {\n\t\t\t\t\tfor (var frameSearchURI in frameSearchURIs) {\n\t\t\t\t\t\tvar frameURIMatches = frameSearchURI.length < 8192 && translator.webRegexp.all.test(frameSearchURI);\n\t\t\t\t\t\t\t\n\t\t\t\t\t\tif (frameURIMatches) {\n\t\t\t\t\t\t\tpotentialTranslators.push(translator);\n\t\t\t\t\t\t\tproxies.push(frameSearchURIs[frameSearchURI]);\n\t\t\t\t\t\t\t// prevent adding the translator multiple times\n\t\t\t\t\t\t\tbreak rootURIsLoop;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else if(!isFrame && (isGeneric || rootURIMatches)) {\n\t\t\t\t\tpotentialTranslators.push(translator);\n\t\t\t\t\tproxies.push(rootSearchURIs[rootSearchURI]);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tvar codeGetter = new Zotero.Translators.CodeGetter(potentialTranslators);\n\t\treturn codeGetter.getAll().then(function () {\n\t\t\treturn [potentialTranslators, proxies];\n\t\t});\n\t};\n\n\t/**\n\t * Converts translators to JSON-serializable objects\n\t */\n\tthis.serialize = function(translator, properties) {\n\t\t// handle translator arrays\n\t\tif(translator.length !== undefined) {\n\t\t\tvar newTranslators = new Array(translator.length);\n\t\t\tfor(var i in translator) {\n\t\t\t\tnewTranslators[i] = Zotero.Translators.serialize(translator[i], properties);\n\t\t\t}\n\t\t\treturn newTranslators;\n\t\t}\n\t\t\n\t\t// handle individual translator\n\t\tvar newTranslator = {};\n\t\tfor(var i in properties) {\n\t\t\tvar property = properties[i];\n\t\t\tnewTranslator[property] = translator[property];\n\t\t}\n\t\treturn newTranslator;\n\t}\n});\n\nmodule.exports = Translators;"
  },
  {
    "path": "src/utilities.js",
    "content": "/*\n    ***** BEGIN LICENSE BLOCK *****\n    \n    Copyright © 2009 Center for History and New Media\n                     George Mason University, Fairfax, Virginia, USA\n                     http://zotero.org\n    \n    This file is part of Zotero.\n    \n    Zotero is free software: you can redistribute it and/or modify\n    it under the terms of the GNU Affero General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n    \n    Zotero 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 Zotero.  If not, see <http://www.gnu.org/licenses/>.\n    \n\t\n\tUtilities based in part on code taken from Piggy Bank 2.1.1 (BSD-licensed)\n\t\n    ***** END LICENSE BLOCK *****\n*/\n\nvar Zotero = require('./zotero');\n\nZotero.OpenURL = Zotero.requireUtilities('./openurl');\nZotero.Date = Zotero.requireUtilities('./date');\n\nZotero.Utilities = Zotero.requireUtilities('./utilities');\nZotero.Utilities = {...Zotero.Utilities,\n\tXRegExp: Zotero.requireUtilities('xregexp-all'),\n\tItem: Zotero.requireUtilities('./utilities_item')\n};\n// Due to how Utilities.Translate is constructed from the of\n// Utilities, we cannot define it above in the object with the rest\nZotero.Utilities.Translate = Zotero.requireTranslate('./utilities_translate');\nvar addZoteroUnicodeData = Zotero.requireUtilities('xregexp-unicode-zotero');\naddZoteroUnicodeData(Zotero.Utilities.XRegExp);\n\nZotero.Schema = Zotero.requireUtilities('./schema.js');\nZotero.Schema.init(require('../modules/zotero-schema/schema.json'));\n\nmodule.exports = Zotero.Utilities;\n\n"
  },
  {
    "path": "src/webEndpoint.js",
    "content": "/*\n    ***** BEGIN LICENSE BLOCK *****\n    \n    Copyright © 2018 Corporation for Digital Scholarship\n                     Vienna, Virginia, USA\n                     https://www.zotero.org\n    \n    This file is part of Zotero.\n    \n    Zotero is free software: you can redistribute it and/or modify\n    it under the terms of the GNU Affero General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n    \n    Zotero 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 Zotero.  If not, see <http://www.gnu.org/licenses/>.\n    \n    ***** END LICENSE BLOCK *****\n*/\n\nconst WebSession = require('./webSession');\n\n// Timeout for select requests, in seconds\nconst SELECT_TIMEOUT = 60;\nconst sessionsWaitingForSelection = {};\n\nvar requestsSinceGC = 0;\n\n\nvar WebEndpoint = module.exports = {\n\thandle: async function (ctx, next) {\n\t\tctx.assert(ctx.is('text/plain') || ctx.is('json'), 415);\n\t\t\n\t\tsetTimeout(() => {\n\t\t\tgc();\n\t\t});\n\t\t\n\t\tvar data = ctx.request.body;\n\t\t\n\t\tif (!data) {\n\t\t\tctx.throw(400, \"POST data not provided\\n\");\n\t\t}\n\t\t\n\t\t// If follow-up URL request, retrieve session and update context\n\t\tvar query;\n\t\tvar session;\n\t\tif (typeof data == 'object') {\n\t\t\tlet sessionID = data.session;\n\t\t\tif (!sessionID) {\n\t\t\t\tctx.throw(400, \"'session' not provided\");\n\t\t\t}\n\t\t\tsession = sessionsWaitingForSelection[sessionID];\n\t\t\tif (session) {\n\t\t\t\tdelete sessionsWaitingForSelection[sessionID];\n\t\t\t\tsession.ctx = ctx;\n\t\t\t\tsession.next = next;\n\t\t\t\tsession.data = data;\n\t\t\t} else {\n\t\t\t\tlet single = !!ctx.request.query.single;\n\t\t\t\tsession = new WebSession(ctx, next, data.url, { single });\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\t// From https://stackoverflow.com/a/3809435, modified to allow up to 9-char TLDs and IP addresses\n\t\t\tlet urlRE = /^(https?:\\/\\/)?([-a-zA-Z0-9@:%._+~#=]{2,256}\\.[a-z]{2,9}\\b|((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\\.|\\b)){4})(\\S*)$/i;\n\t\t\t\n\t\t\tif (!data.match(urlRE)) {\n\t\t\t\tctx.throw(400, \"URL not provided\");\n\t\t\t}\n\t\t\t\n\t\t\t// Prepend 'http://' if not provided\n\t\t\tif (!data.startsWith('http')) {\n\t\t\t\tdata = 'http://' + data;\n\t\t\t}\n\t\t\t\n\t\t\tlet single = !!ctx.request.query.single;\n\t\t\tsession = new WebSession(ctx, next, data, { single });\n\t\t}\n\t\t\n\t\tawait session.handleURL();\n\t\t\n\t\tif (ctx.response.status == 300) {\n\t\t\tif(typeof data == 'object') {\n\t\t\t\t// Select item if this was an item selection query\n\t\t\t\tsession.data = data;\n\t\t\t\tawait session.handleURL();\n\t\t\t} else {\n\t\t\t\t// Store session if returning multiple choices\n\t\t\t\tsessionsWaitingForSelection[session.id] = session;\n\t\t\t}\n\t\t}\n\t}\n};\n\n/**\n * Perform garbage collection every 10 requests\n */\nfunction gc() {\n\tif ((++requestsSinceGC) == 10) {\n\t\tfor (let i in sessionsWaitingForSelection) {\n\t\t\tlet session = sessionsWaitingForSelection[i];\n\t\t\tif (session.started && Date.now() >= session.started + SELECT_TIMEOUT * 1000) {\n\t\t\t\tdelete sessionsWaitingForSelection[i];\n\t\t\t}\n\t\t}\n\t\trequestsSinceGC = 0;\n\t}\n}\n"
  },
  {
    "path": "src/webSession.js",
    "content": "/*\n    ***** BEGIN LICENSE BLOCK *****\n    \n    Copyright © 2018 Corporation for Digital Scholarship\n                     Vienna, Virginia, USA\n                     https://www.zotero.org\n    \n    This file is part of Zotero.\n    \n    Zotero is free software: you can redistribute it and/or modify\n    it under the terms of the GNU Affero General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n    \n    Zotero 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 Zotero.  If not, see <http://www.gnu.org/licenses/>.\n    \n    ***** END LICENSE BLOCK *****\n*/\n\nconst config = require('config');\nconst urlLib = require('url');\nconst { CONTENT_TYPES } = require('./formats');\nconst Translate = require('./translation/translate');\nconst TLDS = Zotero.requireTranslate('./tlds');\nconst HTTP = require('./http');\nconst Translators = require('./translators');\nconst ImportEndpoint = require('./importEndpoint');\nconst SearchEndpoint = require('./searchEndpoint');\nconst { jar: cookieJar } = require('request');\n\nconst SERVER_TRANSLATION_TIMEOUT = 30;\nconst FORWARDED_HEADERS = ['Accept-Language'];\n\nvar WebSession = module.exports = function (ctx, next, data, options) {\n\tthis.ctx = ctx;\n\tthis.next = next;\n\tthis.data = data;\n\tthis.options = options;\n};\n\n/**\n * @return {Promise<undefined>}\n */\nWebSession.prototype.handleURL = async function () {\n\tif (typeof this.data == 'object') {\n\t\tawait this.selectDone();\n\t\treturn;\n\t}\n\t\n\tvar url = this.data;\n\t\n\t// Forward supported headers\n\tvar headers = {};\n\tfor (let header of FORWARDED_HEADERS) {\n\t\tlet lc = header.toLowerCase();\n\t\tif (this.ctx.headers[lc]) {\n\t\t\theaders[header] = this.ctx.headers[lc];\n\t\t}\n\t}\n\t\n\ttry {\n\t\tvar parsedURL = urlLib.parse(url);\n\t}\n\tcatch (e) {\n\t\tthis.ctx.throw(400, \"Invalid URL provided\\n\");\n\t}\n\t\n\t// Check domain\n\tvar m = url.match(/https?:\\/\\/([^/]+)/);\n\tif (m) {\n\t\tlet domain = m[1];\n\t\tlet blacklisted = config.get(\"blacklistedDomains\")\n\t\t\t.some(x => x && new RegExp(x).test(domain));\n\t\tif (blacklisted) {\n\t\t\tlet doi = this.cleanDOIFromURL(url);\n\t\t\tif (!doi) {\n\t\t\t\tthis.ctx.throw(500, \"An error occurred retrieving the document\\n\");\n\t\t\t}\n\t\t\tawait SearchEndpoint.handleIdentifier(this.ctx, { DOI: doi });\n\t\t\treturn;\n\t\t}\n\t}\n\t\n\tvar responseTypeMap = new Map([\n\t\t['html', 'document'],\n\t\t['application/xhtml+xml', 'document'],\n\t\t['text/plain', 'text']\n\t]);\n\t// Force all import content types to text\n\tfor (let type in CONTENT_TYPES) {\n\t\tlet contentType = CONTENT_TYPES[type];\n\t\tif (contentType == 'text/html') continue;\n\t\tif (responseTypeMap.has(contentType)) continue;\n\t\tresponseTypeMap.set(contentType, 'text');\n\t}\n\t\n\tvar urlsToTry = config.get('deproxifyURLs') ? this.deproxifyURL(url) : [url];\n\tfor (let i = 0; i < urlsToTry.length; i++) {\n\t\tlet url = urlsToTry[i];\n\t\tif (urlsToTry.length > 1) {\n\t\t\tZotero.debug(\"Trying \" + url);\n\t\t}\n\t\t\n\t\t/*let runningInstance;\n\t\tif ((runningInstance = Zotero.Server.Translation.waitingForSelection[data.sessionid])\n\t\t\t\t&& data.items) {\n\t\t\t// Already waiting for a items response, so just pass this there\n\t\t\trunningInstance._cookieSandbox.setTimeout(SERVER_TRANSLATION_TIMEOUT*1000,\n\t\t\t\trunningInstance.timeout.bind(runningInstance));\n\t\t\trunningInstance.sendResponse = sendResponseCallback;\n\t\t\trunningInstance.selectDone(data.items);\n\t\t\tbreak;\n\t\t}*/\n\t\t\n\t\t// New request\n\t\tthis._cookieSandbox = cookieJar();\n\t\t\n\t\tlet resolve;\n\t\tlet reject;\n\t\tlet promise = new Promise(function () {\n\t\t\tresolve = arguments[0];\n\t\t\treject = arguments[1];\n\t\t});\n\t\t\n\t\tlet translate = new Translate.Web();\n\t\tlet translatePromise;\n\t\ttranslate.setHandler(\"translators\", async function (translate, translators) {\n\t\t\t// Force single-page saving\n\t\t\tif (this.options.single) {\n\t\t\t\ttranslators = translators.filter(t => t.itemType != 'multiple');\n\t\t\t}\n\t\t\t\n\t\t\ttry {\n\t\t\t\ttranslatePromise = this.translate(translate, translators);\n\t\t\t\tawait translatePromise;\n\t\t\t\tresolve();\n\t\t\t}\n\t\t\tcatch (e) {\n\t\t\t\treject(e);\n\t\t\t}\n\t\t}.bind(this));\n\t\ttranslate.setHandler(\"select\", (translate, items, callback) => {\n\t\t\ttry {\n\t\t\t\tthis.select(\n\t\t\t\t\turl,\n\t\t\t\t\ttranslate,\n\t\t\t\t\titems,\n\t\t\t\t\tcallback,\n\t\t\t\t\ttranslatePromise\n\t\t\t\t);\n\t\t\t}\n\t\t\tcatch (e) {\n\t\t\t\tZotero.debug(e, 1);\n\t\t\t\treject(e);\n\t\t\t\t// Resolve the translate promise\n\t\t\t\tcallback([]);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tresolve();\n\t\t});\n\t\ttranslate.setCookieSandbox(this._cookieSandbox);\n\t\ttranslate.setRequestHeaders(headers);\n\t\t\n\t\ttry {\n\t\t\tlet req = await Zotero.HTTP.request(\n\t\t\t\t\"GET\",\n\t\t\t\turl,\n\t\t\t\t{\n\t\t\t\t\tresponseTypeMap,\n\t\t\t\t\tcookieSandbox: this._cookieSandbox,\n\t\t\t\t\theaders\n\t\t\t\t}\n\t\t\t);\n\t\t\tif (req.type === 'document') {\n\t\t\t\ttranslate.setDocument(req.response);\n\t\t\t\t// This could be optimized by only running detect on secondary translators\n\t\t\t\t// if the first fails, but for now just run detect on all\n\t\t\t\ttranslate.getTranslators(true);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tZotero.debug(`Handling ${req.getResponseHeader('content-type')} as import`);\n\t\t\t\tthis.ctx.request.body = req.response;\n\t\t\t\tawait ImportEndpoint.handle(this.ctx);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t\n\t\t\treturn promise;\n\t\t}\n\t\tcatch (e) {\n\t\t\tZotero.debug(e, 1);\n\t\t\t\n\t\t\tif (e instanceof Zotero.HTTP.StatusError && e.status == 404) {\n\t\t\t\tthis.ctx.throw(400, \"Remote page not found\");\n\t\t\t}\n\t\t\t\n\t\t\tlet doi = this.cleanDOIFromURL(url);\n\t\t\tif (doi) {\n\t\t\t\tZotero.debug(`Error translating page -- continuing with DOI ${doi} from URL`);\n\t\t\t\tawait SearchEndpoint.handleIdentifier(this.ctx, { DOI: doi });\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t\n\t\t\tif (e instanceof Zotero.HTTP.ResponseSizeError) {\n\t\t\t\tthis.ctx.throw(400, \"Response exceeds max size\");\n\t\t\t}\n\t\t\t\n\t\t\tif (e instanceof Zotero.HTTP.UnsupportedFormatError) {\n\t\t\t\tthis.ctx.throw(400, \"The remote document is not in a supported format\");\n\t\t\t}\n\t\t\t\n\t\t\t// No more URLs to try\n\t\t\tif (i == urlsToTry.length - 1) {\n\t\t\t\tthis.ctx.throw(500, \"An error occurred retrieving the document\");\n\t\t\t}\n\t\t}\n\t}\n};\n\n\n/**\n * Called when translators are available to perform translation\n *\n * @return {Promise<undefined>}\n */\nWebSession.prototype.translate = async function (translate, translators) {\n\t// No matching translators\n\tif (!translators.length) {\n\t\tZotero.debug(\"No translators found -- saving as a webpage\");\n\t\tthis.saveWebpage(translate);\n\t\treturn;\n\t}\n\t\n\tvar translator;\n\tvar items;\n\twhile (translator = translators.shift()) {\n\t\ttranslate.setTranslator(translator);\n\t\ttry {\n\t\t\titems = await translate.translate({\n\t\t\t\tlibraryID: false\n\t\t\t});\n\t\t\tbreak;\n\t\t}\n\t\tcatch (e) {\n\t\t\tZotero.debug(\"Translation using \" + translator.label + \" failed\", 1);\n\t\t\tZotero.debug(e, 1);\n\t\t\t\n\t\t\t// If no more translators, save as webpage\n\t\t\tif (!translators.length) {\n\t\t\t\tthis.saveWebpage(translate);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t\n\t\t\t// Try next translator\n\t\t}\n\t}\n\t\n\t//this._cookieSandbox.clearTimeout();\n\t\n\t// Check for DOI in URL if no results\n\tif (!items.length) {\n\t\tlet doi = this.cleanDOIFromURL(translate.location);\n\t\tif (doi) {\n\t\t\tZotero.debug(`No results -- continuing with DOI ${doi} from URL`);\n\t\t\tawait SearchEndpoint.handleIdentifier(this.ctx, { DOI: doi });\n\t\t\treturn;\n\t\t}\n\t}\n\t\n\tvar json = [];\n\tfor (let item of items) {\n\t\tjson.push(...Zotero.Utilities.Item.itemToAPIJSON(item));\n\t}\n\tthis.ctx.response.status = 200;\n\tthis.ctx.response.body = json;\n};\n\n/**\n * TEMP: Remove once there's a generic webpage translator\n *\n * @return {undefined}\n */\nWebSession.prototype.saveWebpage = function (translate) {\n\tlet head = translate.document.documentElement.querySelector('head');\n\tif (!head) {\n\t\t// XXX better status code?\n\t\tthis.ctx.throw(501, \"No translators available\\n\");\n\t}\n\t\n\t// TEMP: Return basic webpage item for HTML\n\tlet description = head.querySelector('meta[name=description]');\n\tif (description) {\n\t\tdescription = description.getAttribute('content');\n\t}\n\tlet data = {\n\t\titemType: \"webpage\",\n\t\turl: translate.document.location.href,\n\t\ttitle: translate.document.title,\n\t\tabstractNote: description,\n\t\taccessDate: Zotero.Date.dateToISO(new Date())\n\t};\n\tthis.ctx.response.body = Zotero.Utilities.Item.itemToAPIJSON(data);\n};\n\n\n/**\n * Called if multiple items are available for selection from the translator\n */\nWebSession.prototype.select = function (url, translate, items, callback, promise) {\n\t// Fix for translators that return item list as array rather than object\n\tif (Array.isArray(items)) {\n\t\tlet newItems = {};\n\t\tfor (let i = 0; i < items.length; i++) {\n\t\t\tnewItems[i] = items[i];\n\t\t}\n\t\titems = newItems;\n\t}\n\t\n\t// If translator returns objects with 'title' and 'checked' properties (e.g., PubMed),\n\t// extract title\n\tfor (let i in items) {\n\t\tif (items[i].title) {\n\t\t\titems[i] = items[i].title;\n\t\t}\n\t}\n\t\n\tthis.id = Zotero.Utilities.randomString(15);\n\tthis.started = Date.now();\n\tthis.url = url;\n\tthis.translate = translate;\n\tthis.items = items;\n\tthis.selectCallback = callback;\n\tthis.translatePromise = promise;\n\t\n\t// Send \"Multiple Choices\" HTTP response\n\t//this._cookieSandbox.clearTimeout();\n\tthis.ctx.response.status = 300;\n\tthis.ctx.response.body = {\n\t\turl,\n\t\tsession: this.id,\n\t\titems\n\t};\n};\n\n/**\n * Called when items have been selected by the client\n */\nWebSession.prototype.selectDone = function () {\n\tvar url = this.data.url;\n\tvar selectedItems = this.data.items;\n\t\n\tif (this.url != url) {\n\t\tthis.ctx.throw(409, \"'url' does not match URL in session\");\n\t}\n\t\n\tif (!selectedItems) {\n\t\tthis.ctx.throw(400, \"'items' not provided\");\n\t}\n\t\n\t// Make sure items are actually available\n\tvar haveItems = false;\n\tfor (let i in selectedItems) {\n\t\tif (this.items[i] === undefined || this.items[i] !== selectedItems[i]) {\n\t\t\tthis.selectCallback([]);\n\t\t\tthis.ctx.throw(409, \"Items specified do not match items available\");\n\t\t}\n\t\thaveItems = true;\n\t}\n\t\n\t// Make sure at least one item was specified\n\tif (!haveItems) {\n\t\tthis.selectCallback([]);\n\t\tthis.ctx.throw(400, \"No items specified\");\n\t}\n\t\n\t// Run select callback\n\tthis.selectCallback(selectedItems);\n\t\n\t// The original translate promise in this.translate() from the first request is stalled while\n\t// waiting for item select from the client. When the follow-up request comes in, the new ctx\n\t// object is swapped in by the endpoint code, and the select callback above allows the\n\t// translate promise to complete and the translated items to be assigned to the new ctx\n\t// response body.\n\treturn this.translatePromise;\n};\n\n\n/**\n * Called if the request timed out before it could complete\n */\n/*WebSession.prototype.timeout = function() {\n\tthis.sendResponse(504, \"text/plain\", \"Translation timed out.\\n\");\n};*/\n\n\n\n\n\n/**\n * Try to determine whether the passed URL looks like a proxied URL based on TLDs in the\n * middle of the domain and return a list of likely URLs, starting with the longest domain\n * and ending with the original one\n *\n * E.g., https://www-example-co-uk.mutex.gmu.edu ->\n *\n * [\n *   'https://www.example.co.uk',\n *   'https://www.example.co',\n *   'https://www-example-co-uk.mutex.gmu.edu',\n * ]\n *\n * Based on Zotero.Proxies.getPotentialProxies()\n */\nWebSession.prototype.deproxifyURL = function (url) {\n\tvar urlToProxy = {\n\t\t[url]: null\n\t};\n\t\n\t// if there is a subdomain that is also a TLD, also test against URI with the domain\n\t// dropped after the TLD\n\t// (i.e., www.nature.com.mutex.gmu.edu => www.nature.com)\n\tvar m = /^(https?:\\/\\/)([^\\/]+)/i.exec(url);\n\tif (m) {\n\t\t// First, drop the 0- if it exists (this is an III invention)\n\t\tvar host = m[2];\n\t\tif (host.substr(0, 2) === \"0-\") host = host.substr(2);\n\t\tvar hostnameParts = [host.split(\".\")];\n\t\tif (m[1] == 'https://') {\n\t\t\t// try replacing hyphens with dots for https protocol\n\t\t\t// to account for EZProxy HttpsHypens mode\n\t\t\thostnameParts.push(host.split('.'));\n\t\t\thostnameParts[1].splice(0, 1, ...(hostnameParts[1][0].replace(/-/g, '.').split('.')));\n\t\t}\n\t\t\n\t\tfor (let i=0; i < hostnameParts.length; i++) {\n\t\t\tlet parts = hostnameParts[i];\n\t\t\t// If hostnameParts has two entries, then the second one is with replaced hyphens\n\t\t\tlet dotsToHyphens = i == 1;\n\t\t\t// skip the lowest level subdomain, domain and TLD\n\t\t\tfor (let j=1; j<parts.length-2; j++) {\n\t\t\t\t// if a part matches a TLD, everything up to it is probably the true URL\n\t\t\t\tif (TLDS[parts[j].toLowerCase()]) {\n\t\t\t\t\tvar properHost = parts.slice(0, j+1).join(\".\");\n\t\t\t\t\t// protocol + properHost + /path\n\t\t\t\t\tvar properURL = m[1]+properHost + url.substr(m[0].length);\n\t\t\t\t\tvar proxyHost = parts.slice(j + 1).join('.');\n\t\t\t\t\turlToProxy[properURL] = {scheme: '%h.' + proxyHost + '/%p', dotsToHyphens};\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tvar urls = Object.keys(urlToProxy);\n\turls.sort((a, b) => b.length - a.length);\n\turls.push(urls.shift());\n\treturn urls;\n};\n\n\nWebSession.prototype.cleanDOIFromURL = function (url) {\n\tlet doi = Zotero.Utilities.cleanDOI(decodeURIComponent(url));\n\tif (doi) {\n\t\t// Stop at query string, ampersand, or hash\n\t\tdoi = doi.replace(/[?&#].*/, '');\n\t}\n\treturn doi || null;\n};\n"
  },
  {
    "path": "src/zotero.js",
    "content": "/*\n    ***** BEGIN LICENSE BLOCK *****\n    \n    Copyright © 2009 Center for History and New Media\n                     George Mason University, Fairfax, Virginia, USA\n                     http://zotero.org\n    \n    This file is part of Zotero.\n    \n    Zotero is free software: you can redistribute it and/or modify\n    it under the terms of the GNU Affero General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n    \n    Zotero 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 Zotero.  If not, see <http://www.gnu.org/licenses/>.\n    \n    ***** END LICENSE BLOCK *****\n*/\n\nconst path = require('path');\nconst config = require('config');\nconst fs = require('fs');\n\nvar Zotero = global.Zotero = module.exports = new function() {\n\tthis.isNode = true;\n\tthis.isServer = true;\n\tthis.locale = 'en-US';\n\t\n\tthis.version = \"5.0.97\";\n\t\n\t/**\n\t * Debug logging function\n\t *\n\t * Uses prefs e.z.debug.log and e.z.debug.level (restart required)\n\t *\n\t * Defaults to log level 3 if level not provided\n\t */\n\tthis.debug = function(message, level) {\n\t\tZotero.Debug.log(message, level);\n\t}\n\t\n\t/**\n\t * Log a JS error to the Mozilla JS error console.\n\t * @param {Exception} err\n\t */\n\tthis.logError = function(err) {\n\t\t// Firefox uses this\n\t\tZotero.debug(err);\n\t}\n\t\n\tthis.setTimeout = setTimeout;\n}\n\n// TODO: Pref store\nZotero.Prefs = new function(){\n\tvar tempStore = {};\n\t\n\tthis.get = function(pref) {\n\t\tif (tempStore.hasOwnProperty(pref)) return tempStore[pref];\n\t\tif (config.has(pref)) return config.get(pref);\n\t};\n\n\t/**\n\t * @param pref\n\t * @param value\n\t */\n\tthis.set = function(pref, value) {\n\t\ttempStore[pref] = value;\n\t};\n\n\t/**\n\t * @param pref\n\t */\n\tthis.clear = function(pref) {\n\t\tdelete tempStore[pref];\n\t}\n}\n\n/**\n * A custom require function to import modules from the translate submodule\n * @param {String} modulePath\n * @returns {*}\n */\nZotero.requireTranslate = function(modulePath) {\n\treturn require(path.resolve(__dirname, '../modules/translate/src/', modulePath));\n}\n\nZotero.requireUtilities = function(modulePath) {\n\treturn require(path.resolve(__dirname, '../modules/utilities/', modulePath));\n}\n\nZotero.Promise = Zotero.requireTranslate('./promise');\nZotero.Debug = Zotero.requireTranslate('./debug');\nZotero.Translators = require('./translators');\nZotero.Utilities = require('./utilities');\nZotero.Date = Zotero.requireUtilities('./date');\nZotero.Date.init(Zotero.requireUtilities('./resource/dateFormats.json'))\nZotero.OpenURL = Zotero.requireUtilities('./openurl');\nZotero.Translator = Zotero.requireTranslate('./translator');\nZotero.Translate = require('./translation/translate');\nZotero.Proxies = require('./proxy').Proxies;\nZotero.Proxy = require('./proxy').Proxy;\n\nvar $rdf = Zotero.requireTranslate('./rdf/init');\nif(Zotero.RDF) {\n\tZotero.RDF.AJAW = $rdf;\n} else {\n\tZotero.RDF = {AJAW:$rdf};\n}\nZotero = Object.assign(Zotero, Zotero.requireUtilities('./cachedTypes'));\nZotero.setTypeSchema(Zotero.requireUtilities('./resource/zoteroTypeSchemaData'));"
  },
  {
    "path": "test/data/bibtex_response.xml",
    "content": "@article{Bar19,\n  author = \"Foo Bar\",\n   title = \"Title\",\n journal = \"Journal\",\n  volume = 123,\n    year = 2019,\n   pages = \"123--125\"}"
  },
  {
    "path": "test/data/loc_book1_response.xml",
    "content": "<?xml version=\"1.0\"?>\n<zs:searchRetrieveResponse xmlns:zs=\"http://www.loc.gov/zing/srw/\"><zs:version>1.1</zs:version><zs:numberOfRecords>1</zs:numberOfRecords><zs:records><zs:record><zs:recordSchema/><zs:recordPacking>xml</zs:recordPacking><zs:recordData><record xmlns=\"http://www.loc.gov/MARC21/slim\">\n  <leader>01691cam a2200361 a 4500</leader>\n  <controlfield tag=\"001\">16725802</controlfield>\n  <controlfield tag=\"005\">20120514113518.0</controlfield>\n  <controlfield tag=\"008\">110407s2011    mdua     b    001 0 eng  </controlfield>\n  <datafield tag=\"906\" ind1=\" \" ind2=\" \">\n    <subfield code=\"a\">7</subfield>\n    <subfield code=\"b\">cbc</subfield>\n    <subfield code=\"c\">orignew</subfield>\n    <subfield code=\"d\">1</subfield>\n    <subfield code=\"e\">ecip</subfield>\n    <subfield code=\"f\">20</subfield>\n    <subfield code=\"g\">y-gencatlg</subfield>\n  </datafield>\n  <datafield tag=\"925\" ind1=\"0\" ind2=\" \">\n    <subfield code=\"a\">acquire</subfield>\n    <subfield code=\"b\">2 shelf copies</subfield>\n    <subfield code=\"x\">policy default</subfield>\n  </datafield>\n  <datafield tag=\"955\" ind1=\" \" ind2=\" \">\n    <subfield code=\"b\">xh09 2011-04-07</subfield>\n    <subfield code=\"i\">xh09 2011-04-07 to Dewey</subfield>\n    <subfield code=\"w\">rd14 2011-04-07</subfield>\n    <subfield code=\"a\">xn02 2011-12-13 1 copy rec'd., to CIP ver.</subfield>\n    <subfield code=\"f\">rf10 2012-02-27 Z-CipVer. telework to BCDD</subfield>\n    <subfield code=\"t\">xn05 2012-05-14 copy 2 added</subfield>\n  </datafield>\n  <datafield tag=\"010\" ind1=\" \" ind2=\" \">\n    <subfield code=\"a\">  2011009234</subfield>\n  </datafield>\n  <datafield tag=\"016\" ind1=\"7\" ind2=\" \">\n    <subfield code=\"a\">015994368</subfield>\n    <subfield code=\"2\">Uk</subfield>\n  </datafield>\n  <datafield tag=\"020\" ind1=\" \" ind2=\" \">\n    <subfield code=\"a\">1421402831 (hardcover : alk. paper)</subfield>\n  </datafield>\n  <datafield tag=\"020\" ind1=\" \" ind2=\" \">\n    <subfield code=\"a\">9781421402833 (hardcover : alk. paper)</subfield>\n  </datafield>\n  <datafield tag=\"035\" ind1=\" \" ind2=\" \">\n    <subfield code=\"a\">(OCoLC)ocn711959730</subfield>\n  </datafield>\n  <datafield tag=\"040\" ind1=\" \" ind2=\" \">\n    <subfield code=\"a\">DLC</subfield>\n    <subfield code=\"c\">DLC</subfield>\n    <subfield code=\"d\">YDX</subfield>\n    <subfield code=\"d\">YDXCP</subfield>\n    <subfield code=\"d\">BWX</subfield>\n    <subfield code=\"d\">CDX</subfield>\n    <subfield code=\"d\">IXA</subfield>\n    <subfield code=\"d\">UKMGB</subfield>\n    <subfield code=\"d\">ZCU</subfield>\n    <subfield code=\"d\">DLC</subfield>\n  </datafield>\n  <datafield tag=\"042\" ind1=\" \" ind2=\" \">\n    <subfield code=\"a\">pcc</subfield>\n  </datafield>\n  <datafield tag=\"043\" ind1=\" \" ind2=\" \">\n    <subfield code=\"a\">e-fr---</subfield>\n  </datafield>\n  <datafield tag=\"050\" ind1=\"0\" ind2=\"0\">\n    <subfield code=\"a\">TX719</subfield>\n    <subfield code=\"b\">.T253 2011</subfield>\n  </datafield>\n  <datafield tag=\"082\" ind1=\"0\" ind2=\"0\">\n    <subfield code=\"a\">641.5944</subfield>\n    <subfield code=\"2\">22</subfield>\n  </datafield>\n  <datafield tag=\"100\" ind1=\"1\" ind2=\" \">\n    <subfield code=\"a\">Takats, Sean,</subfield>\n    <subfield code=\"d\">1974-</subfield>\n  </datafield>\n  <datafield tag=\"245\" ind1=\"1\" ind2=\"4\">\n    <subfield code=\"a\">The expert cook in enlightenment France /</subfield>\n    <subfield code=\"c\">Sean Takats.</subfield>\n  </datafield>\n  <datafield tag=\"260\" ind1=\" \" ind2=\" \">\n    <subfield code=\"a\">Baltimore :</subfield>\n    <subfield code=\"b\">Johns Hopkins University Press,</subfield>\n    <subfield code=\"c\">2011.</subfield>\n  </datafield>\n  <datafield tag=\"300\" ind1=\" \" ind2=\" \">\n    <subfield code=\"a\">x, 203 p. :</subfield>\n    <subfield code=\"b\">ill. ;</subfield>\n    <subfield code=\"c\">24 cm.</subfield>\n  </datafield>\n  <datafield tag=\"490\" ind1=\"1\" ind2=\" \">\n    <subfield code=\"a\">The Johns Hopkins University studies in historical and political science, 129th series ;</subfield>\n    <subfield code=\"v\">2</subfield>\n  </datafield>\n  <datafield tag=\"504\" ind1=\" \" ind2=\" \">\n    <subfield code=\"a\">Includes bibliographical references (p.[179]-196) and index.</subfield>\n  </datafield>\n  <datafield tag=\"505\" ind1=\"0\" ind2=\" \">\n    <subfield code=\"a\">Defining the cook -- Corrupting spaces -- Pots and pens -- Theorizing the kitchen -- The servant of medicine -- Conclusion.</subfield>\n  </datafield>\n  <datafield tag=\"650\" ind1=\" \" ind2=\"0\">\n    <subfield code=\"a\">Cooking, French</subfield>\n    <subfield code=\"x\">History</subfield>\n    <subfield code=\"y\">18th century.</subfield>\n  </datafield>\n  <datafield tag=\"650\" ind1=\" \" ind2=\"0\">\n    <subfield code=\"a\">Cooking</subfield>\n    <subfield code=\"z\">France</subfield>\n    <subfield code=\"x\">History</subfield>\n    <subfield code=\"y\">18th century.</subfield>\n  </datafield>\n  <datafield tag=\"650\" ind1=\" \" ind2=\"0\">\n    <subfield code=\"a\">Cooks</subfield>\n    <subfield code=\"z\">France</subfield>\n    <subfield code=\"x\">History</subfield>\n    <subfield code=\"y\">18th century.</subfield>\n  </datafield>\n  <datafield tag=\"651\" ind1=\" \" ind2=\"0\">\n    <subfield code=\"a\">France</subfield>\n    <subfield code=\"x\">Social life and customs</subfield>\n    <subfield code=\"y\">18th century.</subfield>\n  </datafield>\n  <datafield tag=\"830\" ind1=\" \" ind2=\"0\">\n    <subfield code=\"a\">Johns Hopkins University studies in historical and political science ;</subfield>\n    <subfield code=\"v\">129th ser., 2.</subfield>\n  </datafield>\n</record></zs:recordData><zs:recordPosition>1</zs:recordPosition></zs:record></zs:records><zs:echoedSearchRetrieveRequest><zs:version>1.1</zs:version><zs:query>bath.ISBN=^9781421402833</zs:query><zs:maximumRecords>1</zs:maximumRecords><zs:recordPacking>xml</zs:recordPacking></zs:echoedSearchRetrieveRequest></zs:searchRetrieveResponse>\n"
  },
  {
    "path": "test/data/pubmed_article1_response.xml",
    "content": "<?xml version=\"1.0\" ?>\n<!DOCTYPE PubmedArticleSet PUBLIC \"-//NLM//DTD PubMedArticle, 1st January 2019//EN\" \"https://dtd.nlm.nih.gov/ncbi/pubmed/out/pubmed_190101.dtd\">\n<PubmedArticleSet>\n<PubmedArticle>\n    <MedlineCitation Status=\"In-Data-Review\" Owner=\"NLM\">\n        <PMID Version=\"1\">30571677</PMID>\n        <DateRevised>\n            <Year>2018</Year>\n            <Month>12</Month>\n            <Day>20</Day>\n        </DateRevised>\n        <Article PubModel=\"Electronic-eCollection\">\n            <Journal>\n                <ISSN IssnType=\"Electronic\">1553-7358</ISSN>\n                <JournalIssue CitedMedium=\"Internet\">\n                    <Volume>14</Volume>\n                    <Issue>12</Issue>\n                    <PubDate>\n                        <Year>2018</Year>\n                        <Month>Dec</Month>\n                    </PubDate>\n                </JournalIssue>\n                <Title>PLoS computational biology</Title>\n                <ISOAbbreviation>PLoS Comput. Biol.</ISOAbbreviation>\n            </Journal>\n            <ArticleTitle>Ten simple rules for documenting scientific software.</ArticleTitle>\n            <Pagination>\n                <MedlinePgn>e1006561</MedlinePgn>\n            </Pagination>\n            <ELocationID EIdType=\"doi\" ValidYN=\"Y\">10.1371/journal.pcbi.1006561</ELocationID>\n            <AuthorList CompleteYN=\"Y\">\n                <Author ValidYN=\"Y\">\n                    <LastName>Lee</LastName>\n                    <ForeName>Benjamin D</ForeName>\n                    <Initials>BD</Initials>\n                    <Identifier Source=\"ORCID\">http://orcid.org/0000-0002-7133-8397</Identifier>\n                    <AffiliationInfo>\n                        <Affiliation>School of Engineering and Applied Sciences, Harvard University, Cambridge, Massachusetts, United States of America.</Affiliation>\n                    </AffiliationInfo>\n                </Author>\n            </AuthorList>\n            <Language>eng</Language>\n            <PublicationTypeList>\n                <PublicationType UI=\"D016421\">Editorial</PublicationType>\n            </PublicationTypeList>\n            <ArticleDate DateType=\"Electronic\">\n                <Year>2018</Year>\n                <Month>12</Month>\n                <Day>20</Day>\n            </ArticleDate>\n        </Article>\n        <MedlineJournalInfo>\n            <Country>United States</Country>\n            <MedlineTA>PLoS Comput Biol</MedlineTA>\n            <NlmUniqueID>101238922</NlmUniqueID>\n            <ISSNLinking>1553-734X</ISSNLinking>\n        </MedlineJournalInfo>\n        <CoiStatement>The author has declared that no competing interests exist.</CoiStatement>\n    </MedlineCitation>\n    <PubmedData>\n        <History>\n            <PubMedPubDate PubStatus=\"entrez\">\n                <Year>2018</Year>\n                <Month>12</Month>\n                <Day>21</Day>\n                <Hour>6</Hour>\n                <Minute>0</Minute>\n            </PubMedPubDate>\n            <PubMedPubDate PubStatus=\"pubmed\">\n                <Year>2018</Year>\n                <Month>12</Month>\n                <Day>21</Day>\n                <Hour>6</Hour>\n                <Minute>0</Minute>\n            </PubMedPubDate>\n            <PubMedPubDate PubStatus=\"medline\">\n                <Year>2018</Year>\n                <Month>12</Month>\n                <Day>21</Day>\n                <Hour>6</Hour>\n                <Minute>0</Minute>\n            </PubMedPubDate>\n        </History>\n        <PublicationStatus>epublish</PublicationStatus>\n        <ArticleIdList>\n            <ArticleId IdType=\"pubmed\">30571677</ArticleId>\n            <ArticleId IdType=\"doi\">10.1371/journal.pcbi.1006561</ArticleId>\n            <ArticleId IdType=\"pii\">PCOMPBIOL-D-18-01117</ArticleId>\n        </ArticleIdList>\n    </PubmedData>\n</PubmedArticle>\n\n</PubmedArticleSet>"
  },
  {
    "path": "test/export_test.js",
    "content": "/* global assert:false, request:false */\n\nvar { JSDOM } = require('jsdom');\nconst dom = new JSDOM('<html></html>');\nconst DOMParser = dom.window.DOMParser;\n\ndescribe(\"/export\", function () {\n\tvar json = [{\"key\":\"Q5VYZIG2\",\"version\":0,\"itemType\":\"newspaperArticle\",\"creators\":[{\"firstName\":\"Keith\",\"lastName\":\"Collins\",\"creatorType\":\"author\"}],\"tags\":[{\"tag\":\"Net Neutrality\",\"type\":1},{\"tag\":\"Pai, Ajit\",\"type\":1},{\"tag\":\"Federal Communications Commission\",\"type\":1},{\"tag\":\"Regulation and Deregulation of Industry\",\"type\":1},{\"tag\":\"Computers and the Internet\",\"type\":1}],\"title\":\"Net Neutrality Has Officially Been Repealed. Here’s How That Could Affect You.\",\"section\":\"Technology\",\"url\":\"https://www.nytimes.com/2018/06/11/technology/net-neutrality-repeal.html\",\"abstractNote\":\"Net Neutrality rules that required internet service providers to offer equal access to all web content are no longer in effect as of Monday.\",\"language\":\"en-US\",\"libraryCatalog\":\"NYTimes.com\",\"accessDate\":\"2018-08-21T08:23:37Z\",\"date\":\"2018-06-11\",\"publicationTitle\":\"The New York Times\",\"ISSN\":\"0362-4331\"}];\n\tvar jsonMinimal = [{ key: \"JZMIXKUW\", version: 0, itemType: \"webpage\", url: \"http://example.com/\", title: \"Example\", accessDate: \"2019-01-14T20:18:11Z\"}]\n\t\n\tit(\"should export to BibTeX (full)\", async function () {\n\t\tvar response = await request()\n\t\t\t.post('/export?format=bibtex')\n\t\t\t.send(json)\n\t\t\t.expect(200);\n\t\tassert.isTrue(response.text.trim().startsWith('@article'));\n\t});\n\t\n\tit(\"should export to BibTeX (minimal)\", async function () {\n\t\tvar response = await request()\n\t\t\t.post('/export?format=bibtex')\n\t\t\t.send(jsonMinimal)\n\t\t\t.expect(200);\n\t\tassert.isTrue(response.text.trim().startsWith('@misc'));\n\t});\n\t\n\tit(\"should set BibTeX access date\", async function () {\n\t\tvar response = await request()\n\t\t\t.post('/export?format=bibtex')\n\t\t\t.send(jsonMinimal)\n\t\t\t.expect(200);\n\t\tassert.match(response.text, /urldate = {2019-01-14}/);\n\t});\n\t\n\tit(\"should export to RIS (full)\", async function () {\n\t\tvar response = await request()\n\t\t\t.post('/export?format=ris')\n\t\t\t.send(json)\n\t\t\t.expect(200);\n\t\tassert.isTrue(response.text.startsWith('TY  - NEWS'));\n\t});\n\t\n\tit(\"should export to RIS (minimal)\", async function () {\n\t\tvar response = await request()\n\t\t\t.post('/export?format=ris')\n\t\t\t.send(jsonMinimal)\n\t\t\t.expect(200);\n\t\tconsole.log(response.text);\n\t\tassert.isTrue(response.text.startsWith('TY  - ELEC'));\n\t});\n\t\n\tit(\"should export COinS (full)\", async function () {\n\t\tvar response = await request()\n\t\t\t.post('/export?format=coins')\n\t\t\t.send(json)\n\t\t\t.expect(200)\n\t\t\t.expect('Content-Type', 'text/html');\n\t\tassert.isTrue(response.text.startsWith(\"<span class='Z3988'\"));\n\t});\n\t\n\tit(\"should export COinS (minimal)\", async function () {\n\t\tvar response = await request()\n\t\t\t.post('/export?format=coins')\n\t\t\t.send(jsonMinimal)\n\t\t\t.expect(200)\n\t\t\t.expect('Content-Type', 'text/html');\n\t\tconsole.log(response.text);\n\t\tassert.isTrue(response.text.startsWith(\"<span class='Z3988'\"));\n\t});\n\t\n\tit(\"should export CSL JSON\", async function () {\n\t\tvar date = \"2017-06-29T15:02:20Z\";\n\t\tvar json = [{\n\t\t\titemType: \"journalArticle\",\n\t\t\tcreators: [\n\t\t\t\t{\n\t\t\t\t\tfirstName: \"First\",\n\t\t\t\t\tlastName: \"Last\",\n\t\t\t\t\tcreatorType: \"Author\"\n\t\t\t\t}\n\t\t\t],\n\t\t\textra: `original-date: ${date}`\n\t\t}];\n\t\tvar response = await request()\n\t\t\t.post('/export?format=csljson')\n\t\t\t.send(json)\n\t\t\t.expect(200)\n\t\t\t.expect('Content-Type', 'application/json');\n\t\tassert.equal(response.body[0].type, 'article-journal');\n\t\t// TODO: Put in 'original-date' property\n\t\tassert.equal(response.body[0].note, `original-date: ${date}`);\n\t});\n\t\n\tit(\"should export computer program as CSL JSON\", async function () {\n\t\tvar date = \"2017-06-29T15:02:20Z\";\n\t\tvar json = [{\n\t\t\titemType: \"computerProgram\"\n\t\t}];\n\t\tvar response = await request()\n\t\t\t.post('/export?format=csljson')\n\t\t\t.send(json)\n\t\t\t.expect(200)\n\t\t\t.expect('Content-Type', 'application/json');\n\t\tassert.equal(response.body[0].type, 'software');\n\t});\n\t\n\tit(\"should export note as CSL JSON\", async function () {\n\t\tvar json = [\n\t\t\t{\n\t\t\t\titemType: \"note\",\n\t\t\t\tnote: \"Note\"\n\t\t\t}\n\t\t];\n\t\tvar response = await request()\n\t\t\t.post('/export?format=csljson')\n\t\t\t.send(json)\n\t\t\t.expect(200)\n\t\t\t.expect('Content-Type', 'application/json');\n\t\tassert.equal(response.body[0].type, 'document');\n\t\tassert.equal(response.body[0].title, 'Note');\n\t});\n\t\n\tit(\"should export Bibliontology RDF\", async function () {\n\t\tvar response = await request()\n\t\t\t.post('/export?format=rdf_bibliontology')\n\t\t\t.send(json)\n\t\t\t.expect(200)\n\t\t\t.expect('Content-Type', 'application/rdf+xml');\n\t\tvar dp = new DOMParser();\n\t\tvar doc = dp.parseFromString(response.text, 'text/xml');\n\t\tassert.equal(doc.documentElement.localName, 'RDF');\n\t\tassert.equal(\n\t\t\tdoc.querySelector('Issue isPartOf Newspaper title').textContent,\n\t\t\t'The New York Times'\n\t\t);\n\t});\n\t\n\tit(\"should export Bibliontology RDF (minimal)\", async function () {\n\t\tvar response = await request()\n\t\t\t.post('/export?format=rdf_bibliontology')\n\t\t\t.send(jsonMinimal)\n\t\t\t.expect(200)\n\t\t\t.expect('Content-Type', 'application/rdf+xml');\n\t\tvar dp = new DOMParser();\n\t\tvar doc = dp.parseFromString(response.text, 'text/xml');\n\t\tassert.equal(doc.documentElement.localName, 'RDF');\n\t\tassert.equal(doc.querySelector('Webpage title').textContent, 'Example');\n\t});\n\t\n\tit(\"should export to RefWorks Tagged\", async function () {\n\t\tvar response = await request()\n\t\t\t.post('/export?format=refworks_tagged')\n\t\t\t.send(json)\n\t\t\t.expect(200)\n\t\t\t.expect('Content-Type', 'text/plain');\n\t\tassert.include(response.text, 'RT Newspaper Article');\n\t});\n\t\n\tit(\"should export to TEI\", async function () {\n\t\tvar response = await request()\n\t\t\t.post('/export?format=tei')\n\t\t\t.send(json)\n\t\t\t.expect(200)\n\t\t\t.expect('Content-Type', 'text/xml');\n\t\tvar dp = new DOMParser();\n\t\tvar doc = dp.parseFromString(response.text, 'text/xml');\n\t\tassert.equal(doc.documentElement.localName, 'listBibl');\n\t\tassert.equal(doc.querySelector('monogr title').textContent, 'The New York Times');\n\t});\n\t\n\tit(\"should export Zotero RDF (full)\", async function () {\n\t\tvar response = await request()\n\t\t\t.post('/export?format=rdf_zotero')\n\t\t\t.send(json)\n\t\t\t.expect(200)\n\t\t\t.expect('Content-Type', 'application/rdf+xml');\n\t\tvar dp = new DOMParser();\n\t\tvar doc = dp.parseFromString(response.text, 'text/xml');\n\t\tassert.equal(doc.documentElement.localName, 'RDF');\n\t});\n\t\n\tit(\"should export Zotero RDF (minimal)\", async function () {\n\t\tvar response = await request()\n\t\t\t.post('/export?format=rdf_zotero')\n\t\t\t.send(jsonMinimal)\n\t\t\t.expect(200)\n\t\t\t.expect('Content-Type', 'application/rdf+xml');\n\t\tvar dp = new DOMParser();\n\t\tvar doc = dp.parseFromString(response.text, 'text/xml');\n\t\tassert.equal(doc.documentElement.localName, 'RDF');\n\t});\n});\n"
  },
  {
    "path": "test/import_test.js",
    "content": "/* global assert:false, request:false */\n\n'use strict';\n\nconst fs = require('fs');\nconst path = require('path');\n\nfunction flatten(array) {\n\treturn [].concat.apply([], array);\n}\n\nfunction addTest(name, translatorID, input, expected) {\n\tit(`should import ${name}`, async function () {\n\t\tconst response = await request()\n\t\t\t.post('/import')\n\t\t\t.send(input)\n\t\t\t.set('Content-Type', 'text/plain')\n\t\t\t.expect(200);\n\n\t\tassert.equal(response.headers['zotero-translator-id'], translatorID);\n\n\t\tconst items = {\n\t\t\texpected: flatten(expected.map(item => Zotero.Utilities.Item.itemToAPIJSON(item))), // normalize and flatten results\n\t\t\tfound: response.body,\n\t\t};\n\n\t\tfor (const ef of ['expected', 'found']) {\n\t\t\tfor (const item of items[ef]) {\n\t\t\t\t// inline attached notes -- notes are exported as separate items with a parentItem, but the parentItem is going to be different every time the test is ran\n\t\t\t\tif (!item.notes) {\n\t\t\t\t\titem.notes = items[ef]\n\t\t\t\t\t\t.filter(note => (note.itemType === 'note' && note.parentItem === item.key))\n\t\t\t\t\t\t.map(note => ({ note: note.note, itemType: note.itemType}));\n\t\t\t\t}\n\t\t\t}\n\t\t\t// remove notes now inlined\n\t\t\titems[ef] = items[ef].filter(item => (item.itemType !== 'note' || !item.parentItem));\n\n\t\t\tfor (const item of items[ef]) {\n\t\t\t\t// remove purely administrative fields -- must be done in 2nd run because the key/parentItem are required in the 1st run for inlining notes\n\t\t\t\tdelete item.key;\n\t\t\t\tdelete item.version;\n\t\t\t\tdelete item.parentItem;\n\n\t\t\t\t// remove empty array to simplify comparison\n\t\t\t\tif (Array.isArray(item.tags) && !item.tags.length) {\n\t\t\t\t\tdelete item.tags;\n\t\t\t\t}\n\n\t\t\t\t// sort tags for stable comparison\n\t\t\t\tif (item.tags) {\n\t\t\t\t\titem.tags.sort((a, b) => `${a.type}::${a.tag}`.localeCompare(`${b.type}::${b.tag}`));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tassert.deepEqual(items.expected, items.found);\n\t});\n}\n\nfunction parseJSON(name, json, source) {\n\ttry {\n\t\treturn JSON.parse(json);\n\t}\n\tcatch (err) {\n\t\tit(`should import ${name}`, function () {\n\t\t\tconst m = err.message.match(/(.*) at position ([0-9]+)$/);\n\t\t\tif (m) {\n\t\t\t\tconst pos = parseInt(m[2]);\n\t\t\t\tconst line = source.substring(0, source.indexOf(json) + pos).split('\\n').length;\n\t\t\t\tconst column = pos - json.lastIndexOf('\\n', pos);\n\t\t\t\tthrow new Error(`${m[1]} around line ${line}, column ${column}`);\n\t\t\t}\n\t\t\tthrow err;\n\t\t});\n\t}\n\treturn null;\n}\n\n(process.env.IMPORT_TESTS ? describe : describe.skip)(\"/import\", function () {\n\tconst translators = path.join(__dirname, '../modules/translators');\n\tfor (const translator of fs.readdirSync(translators)) {\n\t\tif (!translator.endsWith('.js')) continue;\n\n\t\tconst name = translator.replace(/\\.js$/, '');\n\t\tconst code = fs.readFileSync(path.join(translators, translator), 'utf-8');\n\n\t\tconst marker = code.indexOf('/** BEGIN TEST CASES **/');\n\t\tif (marker === -1) continue;\n\n\t\tconst header = parseJSON(name, code.replace(/\\n}\\n[\\s\\S]*/, '}'), code);\n\t\tif (!header) continue;\n\t\tconst start = code.indexOf('[', marker);\n\t\tconst end = code.lastIndexOf(']') + 1;\n\n\t\tconst cases = parseJSON(name, code.substring(Math.max(start, marker), Math.max(end, start, marker)), code);\n\t\tif (!cases) continue;\n\n\t\tlet caseNo = 0;\n\t\tfor (const test of cases) {\n\t\t\tcaseNo += 1;\n\t\t\tif (test.type !== 'import') continue;\n\t\t\taddTest(`${name} # ${caseNo}`, header.translatorID, test.input, test.items);\n\t\t}\n\t}\n});\n"
  },
  {
    "path": "test/mocha.opts",
    "content": "--file test/setup.js\n"
  },
  {
    "path": "test/search_test.js",
    "content": "/* global assert:false, request:false, sinon:false */\n\nconst config = require('config');\nconst HTTP = require('../src/http');\nconst TextSearch = require('../src/textSearch');\nconst path = require('path');\nconst fs = require('fs');\nconst urlParse = require('url');\n\ndescribe(\"/search\", function () {\n\tvar bookISBN1 = '9781421402833';\n\tvar bookTitle1 = 'The expert cook in enlightenment France';\n\t\n\tvar articlePMID1 = '30571677';\n\tvar articleTitle1 = 'Ten simple rules for documenting scientific software';\n\t\n\tbeforeEach(() => {\n\t\tvar origHTTPRequest = HTTP.request.bind(HTTP);\n\t\tsinon.stub(HTTP, 'request').callsFake(async function (method, url, options) {\n\t\t\tif (url.startsWith('http://127.0.0.1')) {\n\t\t\t\treturn origHTTPRequest(method, url, options);\n\t\t\t}\n\t\t\t\n\t\t\tZotero.debug(\"Mocking request\");\n\t\t\t\n\t\t\tif (url.startsWith('https://www.crossref.org')) {\n\t\t\t\treturn {\n\t\t\t\t\tstatus: 200,\n\t\t\t\t\tresponseText: '<?xml version=\"1.0\" encoding=\"UTF-8\"?>'\n\t\t\t\t\t\t+ '<doi_records><doi_record key=\"555-555\"><crossref>'\n\t\t\t\t\t\t+ '<error>Either ISSN or Journal title or Proceedings title must be supplied.</error>'\n\t\t\t\t\t\t+ '</crossref></doi_record></doi_records>'\n\t\t\t\t};\n\t\t\t}\n\t\t\t\n\t\t\t// Mock Library of Congress ISBN lookup\n\t\t\tif (url.startsWith('https://lx2.loc.gov')) {\n\t\t\t\tvar xml = fs.readFileSync(\n\t\t\t\t\tpath.join(__dirname, 'data', 'loc_book1_response.xml'),\n\t\t\t\t\t{\n\t\t\t\t\t\tencoding: 'utf-8'\n\t\t\t\t\t}\n\t\t\t\t);\n\t\t\t\treturn {\n\t\t\t\t\tstatus: 200,\n\t\t\t\t\tresponseText: xml\n\t\t\t\t};\n\t\t\t}\n\t\t\t\n\t\t\tif (url.startsWith('https://eutils.ncbi.nlm.nih.gov')) {\n\t\t\t\tlet xml = fs.readFileSync(\n\t\t\t\t\tpath.join(__dirname, 'data', 'pubmed_article1_response.xml'),\n\t\t\t\t\t{\n\t\t\t\t\t\tencoding: 'utf-8'\n\t\t\t\t\t}\n\t\t\t\t);\n\t\t\t\treturn {\n\t\t\t\t\tstatus: 200,\n\t\t\t\t\tresponseText: xml\n\t\t\t\t};\n\t\t\t}\n\t\t\t\n\t\t\tZotero.debug(\"Unhandled request\");\n\t\t\tthrow new Error(\"Unhandled request\");\n\t\t});\n\t\t\n\t\t// Mock identifier-search Lambda call\n\t\tvar origQueryLambda = TextSearch.queryLambda.bind(TextSearch);\n\t\tsinon.stub(TextSearch, 'queryLambda').callsFake(function (query) {\n\t\t\tif (query == bookTitle1.toLowerCase()) {\n\t\t\t\treturn Promise.resolve([{\"ISBN\":bookISBN1}]);\n\t\t\t}\n\t\t\treturn origQueryLambda(query);\n\t\t});\n\t});\n\t\n\tafterEach(() => {\n\t\tHTTP.request.restore();\n\t\tTextSearch.queryLambda.restore();\n\t});\n\t\n\t\n\tit(\"should perform a text search\", async function () {\n\t\tconfig.identifierSearchLambda = 'IdentifierSearch';\n\t\t\n\t\tvar response = await request()\n\t\t\t.post('/search')\n\t\t\t.set('Content-Type', 'text/plain')\n\t\t\t.send(bookTitle1.toLowerCase());\n\t\tassert.equal(response.statusCode, 300);\n\t\tvar json = response.body;\n\t\tassert.lengthOf(Object.keys(json), 1);\n\t\tassert.equal(json[bookISBN1].itemType, 'book');\n\t\tassert.equal(json[bookISBN1].title, bookTitle1);\n\t});\n\t\n\t\n\tit(\"should translate an ISBN\", async function () {\n\t\tvar response = await request()\n\t\t\t.post('/search')\n\t\t\t.set('Content-Type', 'text/plain')\n\t\t\t.send(bookISBN1);\n\t\tassert.equal(response.statusCode, 200);\n\t\tvar json = response.body;\n\t\t\n\t\tassert.lengthOf(json, 2);\n\t\tassert.equal(json[0].itemType, 'book');\n\t\tassert.equal(json[0].title, bookTitle1);\n\t\t// This note contains keywords that should probably be tags\n\t\tassert.equal(json[1].itemType, 'note');\n\t\tassert.equal(json[1].parentItem, json[0].key);\n\t});\n\t\n\t\n\tit(\"should translate a PMID\", async function () {\n\t\tvar response = await request()\n\t\t\t.post('/search')\n\t\t\t.set('Content-Type', 'text/plain')\n\t\t\t.send(articlePMID1);\n\t\tassert.equal(response.statusCode, 200);\n\t\tvar json = response.body;\n\t\t\n\t\tassert.lengthOf(json, 1);\n\t\tassert.equal(json[0].itemType, 'journalArticle');\n\t\tassert.equal(json[0].title, articleTitle1);\n\t});\n\t\n\tit(\"should translate a PMID with 'pmid:' prefix\", async function () {\n\t\tvar response = await request()\n\t\t\t.post('/search')\n\t\t\t.set('Content-Type', 'text/plain')\n\t\t\t.send('pmid:' + articlePMID1);\n\t\tassert.equal(response.statusCode, 200);\n\t\tvar json = response.body;\n\t\t\n\t\tassert.lengthOf(json, 1);\n\t\tassert.equal(json[0].itemType, 'journalArticle');\n\t\tassert.equal(json[0].title, articleTitle1);\n\t});\n});\n"
  },
  {
    "path": "test/setup.js",
    "content": "/* eslint no-unused-vars: [\"error\", { \"varsIgnorePattern\": \"bodyParser\" }] */\n\nconst config = require('config');\nconst request = require('supertest');\nconst chai = require('chai');\nglobal.sinon = require('sinon');\nconst app = require('../src/server');\nconst Koa = require('koa');\nconst _ = require('koa-route');\nconst bodyParser = require('koa-bodyparser');\nconst TestEndpoint = require('../src/testEndpoint');\n\n// Globals that are available to every test\nglobal.assert = chai.assert;\nglobal.request = function () {\n\treturn request(app.callback())\n};\nglobal.testURL = `http://127.0.0.1:${config.get('testPort')}/test/`;\n\n// Serve sample pages for tests\nconst testApp = new Koa();\ntestApp.use(_.get('/test/plain', TestEndpoint.handlePlain));\ntestApp.use(_.get('/test/single', TestEndpoint.handleSingle));\ntestApp.use(_.get('/test/multiple', TestEndpoint.handleMultiple));\ntestApp.use(_.get('/test/redirect', TestEndpoint.handleRedirect));\ntestApp.use(_.get('/test/bibtex', TestEndpoint.handleBibTeX));\ntestApp.use(_.get('/test/invalidContentType', TestEndpoint.invalidContentType));\ntestApp.use(_.get('/test/missingContentType', TestEndpoint.missingContentType));\nvar testServer = testApp.listen(config.get('testPort'));\n\nbefore(async function () {\n\t// Wait for translator initialization\n\tawait Promise.delay(500);\n});\n\nafter(function () {\n\ttestServer.close();\n});\n"
  },
  {
    "path": "test/testTranslators/testTranslators.js",
    "content": "/*\n\t***** BEGIN LICENSE BLOCK *****\n\t\n\tCopyright © 2018 Center for History and New Media\n\t\t\t\t\tGeorge Mason University, Fairfax, Virginia, USA\n\t\t\t\t\thttp://zotero.org\n\t\n\tThis file is part of Zotero.\n\t\n\tZotero is free software: you can redistribute it and/or modify\n\tit under the terms of the GNU Affero General Public License as published by\n\tthe Free Software Foundation, either version 3 of the License, or\n\t(at your option) any later version.\n\t\n\tZotero is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n\tGNU Affero General Public License for more details.\n\n\tYou should have received a copy of the GNU Affero General Public License\n\talong with Zotero.  If not, see <http://www.gnu.org/licenses/>.\n\t\n\t***** END LICENSE BLOCK *****\n*/\n\n'use strict';\n\nprocess.on('unhandledRejection', (err, p) => { \n\tconsole.error(err);\n});\n\nrequire('../../src/zotero');\nrequire('../../src/translation/translate');\nrequire('../../src/http');\n\nconst { basename } = require('path');\nconst yargs = require('yargs');\nconst fs = require('fs').promises;\nconst { jar: cookieJar } = require('request');\nconst {TranslatorTester} = require('../../modules/translate/testTranslators/translatorTester.js');\n\nlet options = yargs\n\t.usage(`Usage: ${basename(process.argv[0])} [options]`)\n\t.wrap(78)\n\t.option('output', {\n\t\ttype: 'string',\n\t\talias: 'o',\n\t\tdescribe: 'Path to the output file for translation results'\n\t})\n\t.option('cross-origin', {\n\t\ttype: 'boolean',\n\t\tdefault: true,\n\t\tdescribe: 'Enable cross-origin HTTP requests in translators'\n\t})\n\t.option('num-concurrent-tests', {\n\t\ttype: 'number',\n\t\tdefault: 10\n\t})\n\t.option('grep', {\n\t\ttype: 'string',\n\t\talias: 'g',\n\t\tdescribe: 'Only test translators with matching labels or ids'\n\t})\n\t.option('browser', {\n\t\ttype: 'string',\n\t\talias: 'b',\n\t\tdefault: 'v',\n\t\tdescribe: \"The browser flag\"\n\t})\n\t.argv;\n\n// For debugging specific translators by label\nlet regexp = options.g && new RegExp(options.g);\n\nconst TEST_TYPES = [\"web\", \"import\", \"export\", \"search\"];\nvar results = [];\n\n// NOTE: We need to attach a cookie sandbox to the translate instances to make websites with\n// cookie forgetting browser/scrapper protection happy when calling HTTP.processDocuments().\n// Thus we're overriding the translate instance constructing method and attaching a cookie jar\nZotero.Translate.newInstance = function(type) {\n\tlet translate = new Zotero.Translate[type.substr(0, 1).toUpperCase()+type.substr(1).toLowerCase()];\n\tif (translate.setCookieSandbox) {\n\t\ttranslate.setCookieSandbox(cookieJar());\n\t}\n\treturn translate;\n}\n\nif (!options.crossOrigin) {\n\t// Monkey patching translator http methods to disallow cross-origin requests\n\tlet throwIfDifferentOrigins = function(origin, url) {\n\t\tlet a = new URL(origin), b = new URL(url);\n\t\tif (a.origin != b.origin) {\n\t\t\tthrow new Error(`Cross origin request from ${origin} to ${url} not allowed`);\n\t\t}\n\t}\n\tlet doGet = Zotero.Utilities.Translate.prototype.doGet;\n\tlet doPost = Zotero.Utilities.Translate.prototype.doPost;\n\tZotero.Utilities.Translate.prototype.doGet = function(urls) {\n\t\tif (!this._translate.location) return;\n\t\tif(typeof(urls) == \"string\") {\n\t\t\tvar url = urls;\n\t\t} else {\n\t\t\tvar url = arguments[0].shift();\n\t\t}\n\t\tthrowIfDifferentOrigins(this._translate.location, url);\n\t\treturn doGet.apply(this, arguments);\n\t}\n\tZotero.Utilities.Translate.prototype.doPost = function() {\n\t\tif (!this._translate.location) return;\n\t\tthrowIfDifferentOrigins(this._translate.location, arguments[0]);\n\t\treturn doPost.apply(this, arguments);\n\t}\n}\n\t\n/**\n * Runs a specific set of tests\n */\nasync function runTesters(translators, type) {\n\tfor (let translator of translators) {\n\t\tlet tester = new TranslatorTester(translator, type, (_, t)=> console.log(t + '\\n'));\n\t\tawait new Promise(resolve => {\n\t\t\ttester.runTests(function() {\n\t\t\t\ttry {\n\t\t\t\t\tif(tester.pending.length) return;\n\n\t\t\t\t\t// Done translating, so serialize test results\n\t\t\t\t\tlet result = tester.serialize();\n\t\t\t\t\tresults.push(result);\n\t\t\t\t\tresolve(result);\n\t\t\t\t} catch(e) {\n\t\t\t\t\tZotero.debug(e);\n\t\t\t\t\tZotero.logError(e);\n\t\t\t\t\tresolve();\n\t\t\t\t}\n\t\t\t})\n\t\t});\n\t}\n\treturn;\n}\n\n\n(async function() {\n\nZotero.Debug.init(0);\nawait Zotero.Translators.init();\n\nfor (let type of TEST_TYPES) {\n\tlet translators = await Zotero.Translators.getAllForType(type, true);\n\t\n\ttry {\n\t\t// Concurrent async via iterators magic\n\t\t// https://stackoverflow.com/a/51020535\n\t\tif (regexp) {\n\t\t\ttranslators = translators.filter(t => regexp.test(t.label) || regexp.test(t.translatorID));\n\t\t}\n\t\tlet iterator = translators.values();\n\t\tlet promises = new Array(options.numConcurrentTests).fill(iterator).map(t => runTesters(t, type));\n\t\tawait Promise.all(promises);\n\t} catch(e) {\n\t\tZotero.debug(e);\n\t\tZotero.logError(e);\n\t}\n}\n\nresults.sort(function(a, b) {\n\tvar atype = TEST_TYPES.indexOf(a.type);\n\tvar btype = TEST_TYPES.indexOf(b.type);\n\tif (atype != btype) return atype-btype;\n\telse return a.label.localeCompare(b.label);\n})\n\nlet result = {\n\tbrowser: options.browser,\n\tversion: Zotero.version,\n\tresults: results\n};\nif (options.o) {\n\tawait fs.writeFile(options.o, JSON.stringify(result, null, '\\t'));\n}\n// If any tests failed, return non-0 exit code\nlet retVal = 0;\nif (results.some(r => r.failed.length || r.unknown.length)) {\n\tretVal = 1;\n}\nprocess.exit(retVal);\n})();\n"
  },
  {
    "path": "test/web_test.js",
    "content": "/* global assert:false, request:false, testURL:false */\n\ndescribe(\"/web\", function () {\n\tit(\"should translate a generic webpage\", async function () {\n\t\tvar url = testURL + 'plain';\n\t\tvar response = await request()\n\t\t\t.post('/web')\n\t\t\t.set('Content-Type', 'text/plain')\n\t\t\t.send(url);\n\t\tassert.equal(response.statusCode, 200);\n\t\tvar json = response.body;\n\t\t\n\t\tassert.lengthOf(json, 1);\n\t\tassert.equal(json[0].itemType, 'webpage');\n\t\tassert.equal(json[0].title, 'Test');\n\t});\n\t\n\t\n\tit(\"should translate a webpage with embedded metadata\", async function () {\n\t\tvar url = testURL + 'single';\n\t\tvar response = await request()\n\t\t\t.post('/web')\n\t\t\t.set('Content-Type', 'text/plain')\n\t\t\t.send(url);\n\t\tassert.equal(response.statusCode, 200);\n\t\tvar json = response.body;\n\t\t\n\t\tassert.lengthOf(json, 1);\n\t\tassert.equal(json[0].itemType, 'journalArticle');\n\t\tassert.equal(json[0].title, 'Title');\n\t});\n\t\n\t\n\tit(\"should return multiple results and perform follow-up translation\", async function () {\n\t\tvar url = testURL + 'multiple';\n\t\tvar response = await request()\n\t\t\t.post('/web')\n\t\t\t.set('Content-Type', 'text/plain')\n\t\t\t.send(url);\n\t\tassert.equal(response.statusCode, 300);\n\t\tvar json = response.body;\n\t\tassert.equal(json.url, url);\n\t\tassert.property(json, 'session');\n\t\tassert.deepEqual(json.items, { 0: 'A', 1: 'B', 2: 'C' });\n\t\t\n\t\tdelete json.items[1];\n\t\t\n\t\tresponse = await request()\n\t\t\t.post('/web')\n\t\t\t.send(json);\n\t\tassert.equal(response.statusCode, 200);\n\t\tjson = response.body;\n\t\tassert.lengthOf(json, 2);\n\t\tassert.equal(json[0].title, 'A');\n\t\tassert.equal(json[1].title, 'C');\n\t});\n\t\n\t\n\t// Simulate a request to a different server without the cached session id\n\tit(\"should return multiple results and perform follow-up translation with unknown session id\", async function () {\n\t\tvar url = testURL + 'multiple';\n\t\tvar response = await request()\n\t\t\t.post('/web')\n\t\t\t.set('Content-Type', 'text/plain')\n\t\t\t.send(url);\n\t\tassert.equal(response.statusCode, 300);\n\t\tvar json = response.body;\n\t\tassert.equal(json.url, url);\n\t\tassert.property(json, 'session');\n\t\tassert.deepEqual(json.items, { 0: 'A', 1: 'B', 2: 'C' });\n\t\t\n\t\tdelete json.items[1];\n\t\t// Change the session id\n\t\tjson.session[0] = json.session[0] == 'a' ? 'b' : 'a';\n\t\t\n\t\tresponse = await request()\n\t\t\t.post('/web')\n\t\t\t.send(json);\n\t\tassert.equal(response.statusCode, 200);\n\t\tjson = response.body;\n\t\tassert.lengthOf(json, 2);\n\t\tassert.equal(json[0].title, 'A');\n\t\tassert.equal(json[1].title, 'C');\n\t});\n\t\n\t\n\tit(\"should follow a redirect and use the final URL for translation\", async function () {\n\t\tvar url = testURL + 'redirect';\n\t\tvar finalURL = testURL + 'single';\n\t\tvar response = await request()\n\t\t\t.post('/web')\n\t\t\t.set('Content-Type', 'text/plain')\n\t\t\t.send(url);\n\t\tassert.equal(response.statusCode, 200);\n\t\tvar json = response.body;\n\t\t\n\t\tassert.lengthOf(json, 1);\n\t\tassert.equal(json[0].itemType, 'journalArticle');\n\t\tassert.equal(json[0].title, 'Title');\n\t\tassert.equal(json[0].url, finalURL);\n\t});\n\t\n\t\n\tit(\"should translate a remote BibTeX file\", async function () {\n\t\tvar url = testURL + 'bibtex';\n\t\tvar response = await request()\n\t\t\t.post('/web')\n\t\t\t.set('Content-Type', 'text/plain')\n\t\t\t.send(url);\n\t\tassert.equal(response.statusCode, 200);\n\t\tvar json = response.body;\n\t\t\n\t\tassert.lengthOf(json, 1);\n\t\tassert.equal(json[0].itemType, 'journalArticle');\n\t\tassert.equal(json[0].title, 'Title');\n\t});\n\t\n\t\n\tit(\"should return 400 if a page returns a 404\", async function () {\n\t\tvar url = testURL + '404';\n\t\tvar response = await request()\n\t\t\t.post('/web')\n\t\t\t.set('Content-Type', 'text/plain')\n\t\t\t.send(url);\n\t\tassert.equal(response.statusCode, 400);\n\t\tassert.equal(response.text, 'Remote page not found');\n\t});\n\t\n\t\n\t// Note: This doesn't test subsequent requests during translation\n\tit(\"should forward the Accept-Language header in the initial request\", async function () {\n\t\tvar url = testURL + 'single';\n\t\tvar response = await request()\n\t\t\t.post('/web')\n\t\t\t.set('Content-Type', 'text/plain')\n\t\t\t.set('Accept-Language', 'fr')\n\t\t\t.send(url);\n\t\tassert.equal(response.statusCode, 200);\n\t\tvar json = response.body;\n\t\t\n\t\tassert.lengthOf(json, 1);\n\t\tassert.equal(json[0].itemType, 'journalArticle');\n\t\tassert.equal(json[0].title, 'Titre');\n\t});\n\t\n\tit(\"should reject non-HTML/XML upstream content types\", async function () {\n\t\tvar url = testURL + 'invalidContentType';\n\t\tvar response = await request()\n\t\t\t.post('/web')\n\t\t\t.set('Content-Type', 'text/plain')\n\t\t\t.send(url);\n\t\tassert.equal(response.statusCode, 400);\n\t\tassert.equal(response.text, \"The remote document is not in a supported format\");\n\t});\n\t\n\tit(\"should reject missing upstream Content-Type header\", async function () {\n\t\tvar url = testURL + 'missingContentType';\n\t\tvar response = await request()\n\t\t\t.post('/web')\n\t\t\t.set('Content-Type', 'text/plain')\n\t\t\t.send(url);\n\t\tassert.equal(response.statusCode, 400);\n\t\tassert.equal(response.text, \"The remote document is not in a supported format\");\n\t});\n});\n"
  },
  {
    "path": "translate_export",
    "content": "#!/bin/bash\n\nformat=\"$1\"\nif [ -z \"$1\" ]; then\n\techo \"Usage: $0 format\"\n\texit 1\nfi\n\njson='[{\"key\":\"Q5VYZIG2\",\"version\":0,\"itemType\":\"newspaperArticle\",\"creators\":[{\"firstName\":\"Keith\",\"lastName\":\"Collins\",\"creatorType\":\"author\"}],\"tags\":[{\"tag\":\"Net Neutrality\",\"type\":1},{\"tag\":\"Pai, Ajit\",\"type\":1},{\"tag\":\"Federal Communications Commission\",\"type\":1},{\"tag\":\"Regulation and Deregulation of Industry\",\"type\":1},{\"tag\":\"Computers and the Internet\",\"type\":1}],\"title\":\"Net Neutrality Has Officially Been Repealed. Here’s How That Could Affect You.\",\"section\":\"Technology\",\"url\":\"https://www.nytimes.com/2018/06/11/technology/net-neutrality-repeal.html\",\"abstractNote\":\"Net Neutrality rules that required internet service providers to offer equal access to all web content are no longer in effect as of Monday.\",\"language\":\"en-US\",\"libraryCatalog\":\"NYTimes.com\",\"accessDate\":\"2018-08-21T08:23:37Z\",\"date\":\"2018-06-11\",\"publicationTitle\":\"The New York Times\",\"ISSN\":\"0362-4331\"}]'\ncurl -v -d \"$json\" -H \"Content-Type: application/json\" \"127.0.0.1:1969/export?format=$format\"\n"
  },
  {
    "path": "translate_search",
    "content": "#!/bin/bash\n\nURL=\"$1\"\nif [ -z \"$1\" ]; then\n\techo \"Usage: $0 identifier-or-phrase\"\n\texit 1\nfi\n\ncurl -v -d \"$URL\" -H \"Content-Type: text/plain\" 127.0.0.1:1969/search\n"
  },
  {
    "path": "translate_url",
    "content": "#!/bin/bash\n\nURL=\"$1\"\nif [ -z \"$1\" ]; then\n\techo \"Usage: $0 URL\"\n\texit 1\nfi\n\ncurl -v -d \"$URL\" -H \"Content-Type: text/plain\" 127.0.0.1:1969/web\n"
  },
  {
    "path": "translate_url_multiple",
    "content": "#!/bin/bash\n\nURL=\"$1\"\nif [ -z \"$1\" ]; then\n\techo \"Usage: $0 URL\"\n\texit 1\nfi\n\ncurl -v -d \"$URL\" -H \"Content-Type: text/plain\" 127.0.0.1:1969/web | jq '{ url: .url, session: .session, items: .items | to_entries | [.[0]] | from_entries }' | curl -v -d @- -H \"Content-Type: application/json\" 127.0.0.1:1969/web\n"
  },
  {
    "path": "translate_url_single",
    "content": "#!/bin/bash\n\nURL=\"$1\"\nif [ -z \"$1\" ]; then\n\techo \"Usage: $0 URL\"\n\texit 1\nfi\n\ncurl -v -d \"$URL\" -H 'Content-Type: text/plain' '127.0.0.1:1969/web?single=1'\n"
  }
]