From f2721373889df07898dca97622d58e49c4b8e047 Mon Sep 17 00:00:00 2001 From: Simon Blackwell Date: Sun, 10 Feb 2019 21:24:32 -0500 Subject: [PATCH] Initial public reference implementation subsequent to deprecation of JOQULAR as an in memory datastore. --- .gitignore | 58 + LICENSE | 686 +---------- README.md | 229 ++-- examples/index.html | 69 -- examples/patterns.html | 83 -- index.js | 883 ++++++++++++++ joqular.js | 2238 ----------------------------------- package.json | 71 +- test/benchmark.html | 297 ----- test/es6-collections.min.js | 5 - test/es6-promise.min.js | 9 - test/fdb-all.min.js | 6 - test/index.html | 752 +----------- test/index.js | 372 ++++++ test/object-observe.js | 739 ------------ test/pouchdb.find.min.js | 3 - 16 files changed, 1536 insertions(+), 4964 deletions(-) create mode 100644 .gitignore delete mode 100644 examples/index.html delete mode 100644 examples/patterns.html create mode 100644 index.js delete mode 100644 joqular.js delete mode 100644 test/benchmark.html delete mode 100644 test/es6-collections.min.js delete mode 100644 test/es6-promise.min.js delete mode 100644 test/fdb-all.min.js create mode 100644 test/index.js delete mode 100644 test/object-observe.js delete mode 100644 test/pouchdb.find.min.js diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..621038f --- /dev/null +++ b/.gitignore @@ -0,0 +1,58 @@ +# Logs +logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* + +# Runtime data +pids +*.pid +*.seed +*.pid.lock + +# Directory for instrumented libs generated by jscoverage/JSCover +lib-cov + +# Coverage directory used by tools like istanbul +coverage + +# nyc test coverage +.nyc_output + +# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) +.grunt + +# Bower dependency directory (https://bower.io/) +bower_components + +# node-waf configuration +.lock-wscript + +# Compiled binary addons (http://nodejs.org/api/addons.html) +build/Release + +# Dependency directories +node_modules/ +jspm_packages/ + +# Typescript v1 declaration files +typings/ + +# Optional npm cache directory +.npm + +# Optional eslint cache +.eslintcache + +# Optional REPL history +.node_repl_history + +# Output of 'npm pack' +*.tgz + +# Yarn Integrity file +.yarn-integrity + +# dotenv environment variables file +.env diff --git a/LICENSE b/LICENSE index 733c072..48e9f9b 100644 --- a/LICENSE +++ b/LICENSE @@ -1,675 +1,23 @@ - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 + MIT License - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. +Copyright (c) 2019 Simon Y. Blackwell - Preamble +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: - The GNU General Public License is a free, copyleft license for -software and other kinds of works. +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Use with the GNU Affero General Public License. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - {one line to give the program's name and a brief idea of what it does.} - Copyright (C) {year} {name of author} - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - {project} Copyright (C) {year} {fullname} - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. diff --git a/README.md b/README.md index ce49534..887a0a6 100644 --- a/README.md +++ b/README.md @@ -1,161 +1,224 @@ # joqular -NOTE: +JavaScript Object Query Language Representation - Funny it's mostly JSON. -2016-10-25: JOQULAR has now been replaced by ReasonDB: https://github.com/anywhichway/reasondb. There were extensive delays due to differences in behavior of Promises in the broweser and nodejs. Many of these were resolved by moving to asycn/await programming and the use of Babel. Although the pattern matching language is not fully implemented, SQL like functionality and joins are now supported as is persistence in both the browser and on the server. Some of the other feratures in the ALPHA have also be dropped for now. The code base is half the size. +JOQULAR is a query language specification. Although there is a reference implementation with this site others are free to write their own drivers. -2016-04-28: With the release of Node v6.0 on April 26th, 2016 we are able to re-start development of JOQULAR 2.0 and move from Alpha to Beta in the next month or so. +# Installation Of Reference Implementation +npm install joqular -An ALPHA of Version 2 of JOQULAR was released on January 10th, 2016. It is available at this branch https://github.com/anywhichway/joqular/tree/v2. It is recommended you not start using Version 1 for anything other than exploratory investigation and you may simply be better off with the ALPHA. The new version of JOQULAR has the following: +# Usage -1) A far cleaner code-base. +``` +const = await JOQULAR.match(,); +``` -2) A more modular code-base. +``` +const pattern = {name:{$eq:"joe"}}, + matched1 = await JOQULAR.match(pattern,{name:"joe",age:27}), // will resolve to the object with name "joe" + matched2 = await JOQULAR.match(pattern,{name:"jane",age:27}); // will resolve to undefined +``` -3) Movement of temporal code into its own library https://github.com/anywhichway/about-time. +For now see the [Medium article](https://medium.com/@anywhichway/joqular-high-powered-javascript-pattern-matching-273a0d77eab5) for more information. -4) All predicates and key words now start with $. +# API -5) Path references now use the key word $self, e.g. {"/": "name"} becomes {$self:"/name"}. +## Predicates and Functions -6) Native object polyfills are now optional, although not using them will limit database predicate tests against these objects. +All 92 predicates and functions or their aliases could actually be defined inline; however, functiona that are difficult to implement or used frequently are defined as part of JOQULAR. -7) The calling interface is now almost exclusively Promise based. +Below is an alphabetical list with minimal documentation. Future documentation will have far more detail and group functions by type. In the meantime, see the the `index.js` in the test directory and review the unit tests. -8) Schema based validation on a continuous basis per property change or a per Object invocation has been added using https://github.com/anywhichway/jovial. +$ -9) Both client and server storage have been added. Transfer of data to the server id accomplished using Faye +$and -10) A Node Express starter framework is provided. +$as +$avg -JavaScript Object Query Language Representation - Funny, it's mostly JSON. +$avga -- Serializable pattern and SQL like object matching for JavaScript, including joins! -- Use Insert, Update, Delete to modify objects and indexes, or configure indexes to update automatically with zero configuration indexing. -- More built-in predicates/operators than most other other data query mechanisms, currently 44. Includes built in random and statistical sampling capability. -- Extensible with just one line of code per predicate/query operator. Puts the intelligence in your data, not the database engine. -- Just-in-time, fully indexed in-memory database, 2x to 10x faster than linear search, faster than Forerunner, IndexedDB and PouchDB for insert and search. -- Indexes represent the live state of JavaScript objects. Query results are also live objects or POJO projections, your choice. POJO key value formatting using a built-in or developer specified format function. -- Extensive Date and Time comparisons with precision at the year, month, day, hour, second, millisecond -- 3-Way Single Function You Choose API ... callbacks, Promises, return values. +$between -See the Wiki for detailed documentation: https://github.com/anywhichway/joqular/wiki +$compute -Issues log and milestones when available: https://github.com/anywhichway/joqular/issues +$count -Let us know what features you would like us to work on by commenting on any enhancement issues. (Obviously, we will work on bugs.) https://github.com/anywhichway/joqular/issues?utf8=%E2%9C%93&q=label%3Aenhancement+ +$counta -npm install joqular +$date + +$day + +$default + +$define + +$descendant + +$disjoint + +$echoes + +$eeq + +$eq + +$every + +$excludes + +$extract + +$false + +$filter + +$forDescendant + +$freeze + +$fullYear + +$gt + +$gte + +$hours + +$in + +$includes + +$instanceof + +$intersects + +$isAny + +$isArray + +$isCreditCard + +$isEmail + +$isEven + +$isFrozen + +$isIPAddress + +$isNaN + +$isOdd + +$isSSN + +$length -# examples +$lt -// everyone named Joe +$lte -{name: {$eq: 'Joe'}} +$map -// everyone born in January +$matches -{birthday: {month: 1}} +$max -// events longer than 1 hour +$maxa -{event: {hours: {$gt: 1}}} +$milliseconds -// all adult women +$min -{age: {$gte: 18}, gender: 'female'}} +$mina -// adult women Bainbridge Island and downtown Seattle +$minutes -{age: {$gte: 18}, gender: 'female', address: {zipcode: {$in: [98110,98101]}}}} +$month -// all grandsons named the same as their grandfather +$ne -{father: {father: {name: {'/': 'name'}}}} +$neeq -// all partners who are partnered with the same gender +$neq -{partner1: {gender: {'..partner2': 'gender'}}} +$nin -// all partners who are not partnered with the same gender +$not -{partner1: {gender: {$neq: {'..partner2': 'gender'}}}} +$or -// Joe's children, if any are sick +$outside -{name: 'Joe', {children: {$some: function(child) { return child.isSick; }}}} +$readonly -// Joe's children, if all are sick +$redact -{name: 'Joe', {children: {$every: function(child) { return child.isSick; }}}} +$reduce -// [], unless all females are named Jo +$regexp -{gender: 'female', {$forall: function(object) { return object.name==='Jo'; }}} +$return -// all females if any are named Jo +$sample -{gender: 'female', {$exists: function(object) { return object.name==='Jo'; }}} +$search -// anyone named Joe or Jo +$seconds -{name: {$soundex: 'Joe'}} +$some -// anyone with a name starting in Jo +$sort -{name: {$match: /Jo*/}} +$sum -// anyone who is female and authorized based on the value, i.e. 21 or over +$suma -function authorized(value) { return value>=21; }.predicate=true; -{gender: 'female', {age: {$: authorized}}} +$text -// anyone who is female and authorized based on the object, i.e. a volunteer +$time -function authorized() { return this.volunteer }.predicate=true; -{gender: 'female', $$: authorized} +$true -// general query +$type -select().from({p1: Person}).where(``); +$typeof -// all Person's ordered by zipcode, then name +$UTCDate -select().from({p1: Person}).orderBy({'p1.address.zipcode': 'asc', 'p1.name':'asc'}); +$UTCDay - // all combinations of people - -select().from({p1: Person,p2: Person}).where({p2: {$neq: p1}}); +$UTCFullYear -// first 10 Person's matching a query +$UTCHours -select().first(10).from({p1: Person}).where(``); +$UTCMilliseconds -// last 10 Person's matching a query +$UTCMinutes -select().last(10).from({p1: Person}).where(``); +$UTCMonth -// random sample at 95% confidence +/- 3 +$UTCSeconds -select().sample(.95,.03).from({p1: Person}); +$valid -# updates +$value -2015-06-01 v1.02.01 Added SQL like Insert, Update, Delete. Further optimized indexing and search. Formatting capability added for POJO projections using Select. Dates fully indexed by year, month, dayofMonth, hours, seconds, milliseconds. Durations fully indexed by years, months, weeks, days, hours, minutes, seconds, milliseconds. Added weeks (W) to Duration. Three "breaking" changes. 1) Index format changed in a manner that is not compatible with current persisted indexes. No automated migration currently available. 2) Modified syntax to require a $ sign before any function references in patterns and queries in order to provide hints to query optimizer. Simple global replace on an existing function references to address the change. 3) Modified Date, Time, Duration match behavior such they they will no longer match just a number. Dates must be matched using the entire object or their subfields, 'year', 'month', 'dayofMonth', 'hours', 'minutes', 'seconds', 'milliseconds'. Times must be matched using the entire object or their subfield 'milliseconds'. Durations must be matched using the entire object or their subfields 'length' (which is expressed in milliseconds), 'years', 'months', 'weeks', 'days', 'hours', 'seconds', 'milliseconds'. The function 'valueOf()' continues to return a number of milliseconds for all these objects. +$where -2015-05-11 v1.01.02 Extended ability to reference data across patterns when using providers. Reversed ordering of update info and reformatted examples in README. (1,193 Unit tests and growing ...) +$xor -2015-05-04 v1.01.01 Added 'between' and 'outside' for primitive types, added SQL like queries with joins, adopted NPM semantic versioning, no breaking changes going from v0.x.xx to v1.xx.xx (1,163 Unit tests and growing ...) +$year -2015-04-26 v0.0.95 Added missing predicate declaration for String.prototype.match (632 Unit tests and growing ...) -2015-04-26 v0.0.94 Added patterns example, fixed recursion matching issue, added the $$ operator (628 Unit tests and growing ...) +## Updates -2015-04-25 v0.0.93 corrected typos in npm package (626 Unit tests and growing ...) +2019-02-10 v2.0.0b - Initial public reference implementation subsequent to deprecation of JOQULAR as an in memory datastore. -2015-04-25 v0.0.92 Initial public release (626 Unit tests and growing ...) diff --git a/examples/index.html b/examples/index.html deleted file mode 100644 index 71ec5e7..0000000 --- a/examples/index.html +++ /dev/null @@ -1,69 +0,0 @@ - - - - - - - - - -Open the developer tools in your browser to see this sample in action. - - - \ No newline at end of file diff --git a/examples/patterns.html b/examples/patterns.html deleted file mode 100644 index e45d12b..0000000 --- a/examples/patterns.html +++ /dev/null @@ -1,83 +0,0 @@ - - - - - - - - - -Open the developer tools in your browser to see this sample in action. - - - - - - \ No newline at end of file diff --git a/index.js b/index.js new file mode 100644 index 0000000..cb496ac --- /dev/null +++ b/index.js @@ -0,0 +1,883 @@ +(function() { + "use strict"; + +//soundex from https://gist.github.com/shawndumas/1262659 + function soundex(a) {a=(a+"").toLowerCase().split("");var c=a.shift(),b="",d={a:"",e:"",i:"",o:"",u:"",b:1,f:1,p:1,v:1,c:2,g:2,j:2,k:2,q:2,s:2,x:2,z:2,d:3,t:3,l:4,m:5,n:5,r:6},b=c+a.map(function(a){return d[a]}).filter(function(a,b,e){return 0===b?a!==d[c]:a!==e[b-1]}).join("");return(b+"000").slice(0,4).toUpperCase()}; + +//from https://gist.github.com/lovasoa/3361645 + length==1 mod by AnyWhichWay + function intersection(){ + if(arguments.length===0) return []; + if(arguments.length===1) return arguments[0].slice(); + var a,b,c,d,e,f,g=[],h={},i; + i=arguments.length-1; + d=arguments[0].length; + c=0; + for(a=0;a<=i;a++){ + e=arguments[a].length; + if(e { + if(!name || name==="anonymous") { + throw new Error("JOQULAR.function: A function name must be provided"); + } + if(typeof(f)!=="function") { + throw new Error(`JOQULAR.function: ${f} is not a function`); + } + if(!name[0]==="$") { + name = "$" + name; + } + FUNCTIONS[name] = f; + }, + deepCopy = data => { + const type = typeof(data); + if(data && type==="object") { + if(data instanceof Date) { + return new Date(data.getTime()); + } + const descriptors = Object.getOwnPropertyDescriptors(data); + return Object.keys(descriptors).reduce((accum,key) => { + const {enumerable,configurable,writable,get,set} = descriptors[key]; + if(!get && !set) { + const value = deepCopy(data[key]); + Object.defineProperty(accum,key,{enumerable,configurable,writable,value}); + } + return accum; + },Array.isArray(data) ? [] : Object.create(Object.getPrototypeOf(data))); + } + return data; + }, + deleteFunction = (name) => { + if(!name || name==="anonymous") { + throw new Error("JOQULAR.function: A function name must be provided"); + } + if(FUNCTIONS[name]) { + delete FUNCTIONS[name]; + return true; + } + return false; + }, + register = (f,name=f.name) => { + if(!name || name==="anonymous") { + throw new Error("JOQULAR.register: A function name must be provided"); + } + if(typeof(f)!=="function") { + throw new Error(`JOQULAR.register: ${f} is not a function`); + } + CTORS[name] = f; + }, + unregister = (name) => { + if(!name || name==="anonymous") { + throw new Error("JOQULAR.unregister: A function name must be provided"); + } + if(CTORS[name]) { + delete CTORS[name]; + return true; + } + return false; + }, + match = async (pattern,value,extracted={}) => { + const copy = deepCopy(value); + return matchaux(pattern,copy,extracted) + }, + matchaux = async (pattern,value,extracted={},objectKey,object) => { + if(pattern===null || pattern===value) return value; + const ptype=typeof(pattern), + vtype = typeof(value); + if(pattern && ptype=="object") { + for(const key in pattern) { + let pkey = key; + if(key==="$_") { + pkey = () => true; + } else if(key.includes("=>")) { + try { + pkey = new Function("return " + key)(); + if(value==null || vtype!=="object") return; + } catch(e) { + ; // ignore + } + } else if(key[0]==="/") { + const i = key.lastIndexOf("/"); + if(i>0) { + try { + const regexp = new RegExp(key.substring(1,i),key.substring(i+1)); + pkey = (key) => { + return regexp.test(key); + }; + } catch(e) { + ; + } + } + } + const pkeytype = typeof(pkey), + predicate = FUNCTIONS[key] ? FUNCTIONS[key] : typeof(pattern[key])==="function" ? pattern[key] : undefined; + if(pkeytype!=="function" && predicate) { + if(typeof(pattern[key])==="function" && !FUNCTIONS[key]) { + if(!(await predicate.call(value,value[key],predicate,key))) { + return; + } + extracted[key] = value[key]; + } else { + if(!(await predicate.call(object,value,pattern[key],objectKey))) { + return; + } + if(value===undefined) { + value = object[objectKey]; // predicate may have added value + } + if(objectKey) extracted[objectKey] = value; + } + continue; + } + if((!predicate || predicate.recurse) && value && typeof(value)==="object") { + if(pkeytype==="function") { + const keys = Object.keys(value).filter(key => pkey(key)); + if(keys.length===0) { + return; + } + for(const vkey of keys) { + if((await matchaux(pattern[key],value[vkey],extracted,vkey,value)===undefined)) { + return; + } + } + } else if((await matchaux(pattern[key],value[key],extracted,key,value)===undefined)) { + return; + } + } + } + return value; + } + }, + functions = { + $(value,f,key) { + return f(value,key,this); + }, + async $and(a,tests,key) { + const resolve = (a,pname,value) => FUNCTIONS[pname] ? FUNCTIONS[pname].call(this,a,value,key) : false; + if(Array.isArray(tests)) { + for(const test of tests) { + for(const pname of Object.keys(test)) { + if(!(await resolve(a,pname,test[pname]))) { + return false; + } + } + } + return true; + } else { + for(const pname of Object.keys(tests)) { + if(!(await resolve(a,pname,tests[pname]))) { + return false; + } + } + return true; + } + }, + $as(value,as,key) { + delete this[key]; + this[as] = value; + return true; + }, + $avg(iterable,as) { + if(Symbol.iterator in Object(iterable)) { + let sum = 0, + count = 0; + for(let value of iterable) { + if(!Array.isArray(iterable)) { + value = value[1]; + } + if(typeof(value)==="number") { + sum += value; + count++; + } + } + this[as] = sum/count; + return true; + } + }, + $avga(iterable,as) { + if(Symbol.iterator in Object(iterable)) { + let sum = 0, + count = 0; + for(let value of iterable) { + if(!Array.isArray(iterable)) { + value = value[1]; + } + if(value==true) { + value = 1; + } else if(value==false) { + value = 0; + } else { + value = parseFloat(value) + } + if(typeof(value)==="number" && !isNaN(value)) { + sum += value; + count++; + } + } + this[as] = sum/count; + return true; + } + }, + $between(value,[lo,hi,inclusive=true]) { + if(value && typeof(value.between)==="function") { + return value.between(lo,hi,inclusive); + } + if(inclusive) { + return (value>=lo && value<=hi) || (value>=hi && value<=lo); + } + return (value>lo && valuehi && value f(item)); + } else { + result = []; + } + if(as) { + this[as] = result; + } else { + this[key] = result; + } + return true; + }, + async $forDescendant(target,{pattern,$,depth=Infinity},key) { + JOQULAR.match(pattern,target,{},key,this); + if(!target || typeof(target)!=="object" || depth===0) return true; + for(const key of Object.keys(target)) { + await FUNCTIONS.$forDescendant.call(target,target[key],{pattern,$,depth:depth-1},key); + } + return true; + }, + $freeze(value,property,key) { + const type = typeof(value); + if(value && type==="object") { + Object.freeze(value); + } + if(property) { + try { + Object.defineProperty(this,key,{enumerable:true,value}); + } catch(e) { + ; + } + } + return true; + }, + $gt(a,b) { + return a > b; + }, + $gte(a,b) { + return a >= b; + }, + $gt(a,b) { + return a > b; + }, + $in(value,includer) { + if(value && typeof(value.in)==="function") { + return value.in(includer); + } + if(includer && typeof(includer.includes)==="function") { + return includer.includes(value); + } + }, + $includes(includer,value) { + if(includer) { + if(typeof(includer.includes)==="function") { + return includer.includes(value); + } + if(typeof(includer.excludes)==="function") { + return !includer.excludes(value); + } + } + }, + $instanceof(a,b) { + b = typeof(b)==="string" ? CTORS[b] : b; + return a && typeof(a)==="object" && b && typeof(b)==="function" && a instanceof b; + }, + $intersects(a,b) { + return Array.isArray(a) && Array.isArray(b) && intersection(a,b).length>0; + }, + $isAny() { + return true; + }, + async $isArray(value) { + return Array.isArray(value); + }, + $isCreditCard(value) { + // Visa || Mastercard || American Express || Diners Club || Discover || JCB + return (/^(?:4[0-9]{12}(?:[0-9]{3})?|(?:5[1-5][0-9]{2}|222[1-9]|22[3-9][0-9]|2[3-6][0-9]{2}|27[01][0-9]|2720)[0-9]{12}|3[47][0-9]{13}| 3(?:0[0-5]|[68][0-9])[0-9]{11}|6(?:011|5[0-9]{2})[0-9]{12}|(?:2131|1800|35\d{3})\d{11})$/m).test(value) && validateLuhn(value); + }, + $isEmail(value) { + return !/(\.{2}|-{2}|_{2})/.test(value) && /^[a-z0-9][a-z0-9-_\.]+@[a-z0-9][a-z0-9-]+[a-z0-9]\.[a-z]{2,10}(?:\.[a-z]{2,10})?$/i.test(value); + }, + $isEven(value) { + return value % 2 === 0; + }, + $isFrozen(value) { + const type = typeof(value); + if(value && type==="object") { + return Object.isFrozen(value); + } + return true; + }, + $isIPAddress(value) { + return (/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/m).test(value); + }, + $isNaN(value) { + return isNaN(value); + }, + $isOdd(value) { + return value % 2 !== 0; + }, + $isSSN(value) { + return /^\d{3}-?\d{2}-?\d{4}$/.test(value); + }, + $length(value,length) { + return a && a.length===length; + }, + $lt(a,b) { + return a < b; + }, + $lte(a,b) { + return a <= b; + }, + async $map(iterable,f,key) { + const results = []; + let as; + if(Array.isArray(f)) { + as = f[1]; + f = f[0]; + } + if(Symbol.iterator in Object(iterable)) { + let key = 0; + for(let value of iterable) { + if(Array.isArray(iterable)) { + results.push(await f(value,key,iterable)); + } else { + results.push(await f(value[1],value[0],iterable)); + } + key++; + } + } + if(as) { + this[as] = results; + } else { + this[key] = results; + } + return true; + }, + $matches(value,regexp) { + if(value) { + const match = value.matches||value.match; + if(typeof(match)==="function") { + let as; + if(Array.isArray(regexp)) { + as = regexp[2]; + try { + regexp = new RegExp(...regexp.slice(0,2)); + } catch(e) { + ; + } + } + const matches = match(regexp); + if(matches) { + if(as) { + this[as] = matches; + } + return true; + } + } + } + }, + $max(iterable,as) { + if(Symbol.iterator in Object(iterable)) { + let max; + for(let value of iterable) { + if(!Array.isArray(iterable)) { + value = value[1]; + } + max = max===undefined || value > max ? value : max; + } + this[as] = max; + return true; + } + }, + $maxa(iterable,as) { + if(Symbol.iterator in Object(iterable)) { + let max = -Infinity; + for(let value of iterable) { + if(!Array.isArray(iterable)) { + value = value[1]; + } + if(value==true) { + value = 1; + } else if(value==false) { + value = 0; + } else { + value = parseFloat(value) + } + if(typeof(value)==="number" && !isNaN(value)) { + max = value > max ? value : max; + } + } + this[as] = max; + return true; + } + }, + $min(iterable,as) { + if(Symbol.iterator in Object(iterable)) { + let min; + for(let value of iterable) { + if(!Array.isArray(iterable)) { + value = value[1]; + } + min = min===undefined || value < min ? value : min; + } + this[as] = min; + return true; + } + }, + $mina(iterable,as) { + if(Symbol.iterator in Object(iterable)) { + let min = Infinity; + for(let value of iterable) { + if(!Array.isArray(iterable)) { + value = value[1]; + } + if(value==true) { + value = 1; + } else if(value==false) { + value = 0; + } else { + value = parseFloat(value) + } + if(typeof(value)==="number" && !isNaN(value)) { + min = value < min ? value : min; + } + } + this[as] = min; + return true; + } + }, + $neq(a,b) { + return a != b; + }, + $neeq(a,b) { + return a !== b; + }, + $nin(value,includer) { + if(value && typeof(value.in)==="function") { + return !value.in(includer); + } + if(includer && typeof(includer.includes)==="function") { + return !includer.includes(value); + } + }, + async $not(a,tests,key) { + const resolve = (a,pname,value) => FUNCTIONS[pname] ? FUNCTIONS[pname].call(this,a,value,key) : false, + pnames = Object.keys(tests); + for(const pname of pname) { + if(!(await resolve(a,pname,tests[pname]))) { + return false; + } + } + return true; + }, + async $or(a,tests,key) { + const resolve = (a,pname,value) => FUNCTIONS[pname] ? FUNCTIONS[pname].call(this,a,value,key) : false; + if(Array.isArray(tests)) { + for(const test of tests) { + for(const pname of Object.keys(test)) { + if((await resolve(a,pname,test[pname]))) { + return true; + } + } + } + } else { + for(const pname of Object.keys(tests)) { + if((await resolve(a,pname,tests[pname]))) { + return true; + } + } + } + }, + $outside(value,[lo,hi]) { + if(value) { + if(typeof(value.outside)==="function") { + return value.outside(lo,hi); + } + return !FUNCTIONS.$between(value,[lo,hi,true]); + } + }, + $readonly(value,_,key) { + try { + this[key] = value; + return false; + } catch(e) { + return true; + } + }, + $redact(_1,_2,key) { + delete this[key]; + return true; + }, + async $reduce(iterable,f,key) { + let accum, + as; + if(Array.isArray(f)) { + as = f[2]; + accum = f[1]; + f = f[0]; + } + if(Symbol.iterator in Object(iterable)) { + let key = 0; + for(let value of iterable) { + if(Array.isArray(iterable)) { + accum = await f(accum,value,key,iterable); + } else { + accum = await f(accum,value[1],value[0],iterable); + } + key++; + } + } + if(as) { + this[as] = accum; + } else { + this[key] = accum; + } + return true; + }, + $return(_,value,key) { + if(value===undefined) { + delete this[key]; + } else { + this[key] = value; + } + return true; + }, + $sample(iterable,[pct,max=Infinity],key) { + const sample = [], + indexes = []; + let i = 0; + // get count random items from an iterable + if(Symbol.iterator in Object(iterable)) { + for(const item of iterable) { + const rand = Math.random(); + if(rand<=pct) { + if(Array.isArray(iterable)) { + sample.push(item); + } else { + sample.push(item.value) + } + if(sample.length===max) break; + } + } + } + this[key] = sample; + return true; + }, + async $search(text,phrase) { + if(text) { + if(typeof(text.search)==="function") { + return text.search(phrase); + } + const tokens = tokenize(phrase), + stems = stems(tokens); + if(stems.some(stem => text.includes(stem))) { + return true; + } + const tris = trigrams(phrase.replace(/\s/g,"")), + count = tris.reduce((accum,tri) => { return text.includes(tri) ? accum++ : accum },0); + if((count/tris.length)>.8) { + return true; + } + } + }, + async $some(iterable,f) { + if(Symbol.iterator in Object(iterable)) { + let key = 0; + for(let value of iterable) { + if(Array.isArray(iterable)) { + if(await f(value,key,iterable)) { + return true; + } + } else { + if(await f(value[1],value[0],iterable)) { + return true; + } + } + key++; + } + } + return false; + }, + $sort(sortable,f,key) { + let as, result; + if(Array.isArray(f)) { + as = f[1]; + f = f[0]; + } + if(sortable && typeof(sortable.sort)==="function") { + result = sortable.sort((a,b) => f(a,b)); + } else { + result = []; + } + if(as) { + this[as] = result + } else { + this[key] = result; + } + return true; + }, + $sum(iterable,as) { + if(Symbol.iterator in Object(iterable)) { + let sum = 0; + for(let value of iterable) { + if(!Array.isArray(iterable)) { + value = value[1]; + } + if(typeof(value)==="number") { + sum =+ value; + } + } + this[as] = sum; + return true; + } + }, + $suma(iterable,as) { + if(Symbol.iterator in Object(iterable)) { + let sum = 0; + for(let value of iterable) { + if(!Array.isArray(iterable)) { + value = value[1]; + } + if(value==true) { + value = 1; + } else if(value==false) { + value = 0; + } else { + value = parseFloat(value); + } + if(typeof(value)==="number" && !isNaN(value)) { + sum =+ value; + } + } + this[as] = sum; + return true; + } + }, + $true() { + return true; + }, + $typeof(a,b) { + return typeof(a)===b; + }, + $valid(value,validations,key) { + if(typeof(validations)==="function") { + return validations(value,key,this); + } + for(const validationKey in Object.keys(validations)) { + const validator = FUNCTIONS[validationKey]; + if(typeof(validator)==="function") { + const valid = validator(this,validations[validationKey]); + if(!valid) { + const error = new TypeError(`failed validation ${validationKey} for ${this}`); + if(validations.onError) { + validations.onError(error,value,key,this); + } else { + throw(error); + } + } + } + } + return true; + }, + $xor(a,tests,key) { + let found = 0; + const resolve = (a,pname,value) => FUNCTIONS[pname] ? FUNCTIONS[pname].call(this,a,value,key) : false; + if(Array.isArray(tests)) { + for(const test of tests) { + for(const pname in test) { + if(resolve(a,pname,test[pname])) found++; + if(found>1) return false; + } + } + } else { + for(const pname in tests) { + if(resolve(a,pname,tests[pname])) found++; + if(found>1) return false; + } + } + return found===1; + } + }; + functions.$value = functions.$compute; + functions.$type = functions.$typeof; + functions.$text = functions.$search; + functions.$regexp = functions.$matches; + functions.$ne = functions.$neq; + functions.$where = functions.$; + + for(const key of ["date","day","fullYear","hours","milliseconds","minutes","month","seconds","time","UTCDate","UTCDay","UTCFullYear","UTCHours","UTCSeconds","UTCMilliseconds","UTCMinutes","UTCMonth","year"]) { + const fname = `get${key[0].toUpperCase()}${key.substring(1)}`; + functions["$"+key] = + Function(`return function ${"$"+key}(a,b) { + const atype = typeof(a), + btype = typeof(b); + if((atype==="number" && Math.abs(a)<8640000000000000) || atype==="string") { + try { a = new Date(a); } catch(e) { return false; } + } + if((btype==="number" && Math.abs(b)<8640000000000000) || btype==="string") { + try { b = new Date(a); } catch(e) { return false; } + } + if(typeof(a)==="object" && a instanceof Date && typeof(b)==="object" && b instanceof Date) return a.${fname}()===b.${fname}(); }`)(); + } + + Object.defineProperty(JOQULAR,"function",{value:addFunction}); + Object.defineProperty(JOQULAR,"undefine",{value:deleteFunction}); + Object.defineProperty(JOQULAR,"register",{value:register}); + Object.defineProperty(JOQULAR,"unregister",{value:unregister}); + Object.defineProperty(JOQULAR,"match",{value:match}); + Object.assign(FUNCTIONS,functions); + + if(typeof(module)!=="undefined") module.exports = JOQULAR; + if(typeof(window)!=="undefined") window.JOQULAR = JOQULAR; + +}).call(this); \ No newline at end of file diff --git a/joqular.js b/joqular.js deleted file mode 100644 index aab2cbd..0000000 --- a/joqular.js +++ /dev/null @@ -1,2238 +0,0 @@ -/* - * GNU GENERAL PUBLIC LICENSE - * Version 3, 29 June 2007 - * Copyright 2015 (and left) AnyWhichWay, LLC and Simon Y. Blackwell - * - * The software is provided as is without any guarantee of quality or applicability for any specific use. - * - * Attribution for the work of others is in the source code, although none came with a license stipulation. - */ -(function(exports) { - "use strict"; - function toPredicate(f) { - var predicate = function() { - if(arguments[0] instanceof Array && f.length>1) { - return f.apply(this,arguments[0]); - } - return f.apply(this,arguments); - }; - predicate.predicate = true; - return predicate; - } - function toProvider(f) { - f.provider = true; - return f; - } - function Null() { - - } - (Null.prototype.eq = function(value) { return value===null || value.valueOf()===null; }).predicate = true; - (Null.prototype.neq = function(value) { return value!==null && value.valueOf()!==null; }).predicate = true; - (Null.prototype["in"] = function(value) { - return value && value.contains && value.contains(this); - }).predicate=true; - (Null.prototype.nin = function(value) { - return !value || !value.contains || !value.contains(this); - }).predicate=true; - Null.prototype.valueOf = function() { return null; } - var NULL = new Null(); - function toObject(value) { - if(value===undefined) { - return undefined; - } - if(value===null) { - return NULL; - } - if(typeof(value)==="object" || typeof(value)==="function") { - return value; - } - var type = typeof(value); - switch(type) { - case "string": return new String(value); - case "number": return new Number(value); - case "boolean": return new Boolean(value); - } - return undefined; // should this actually throw an error? - } - // soundex from https://gist.github.com/shawndumas/1262659 - function soundex(s) { - var a = s.toLowerCase().split(''), - f = a.shift(), - r = '', - codes = { - a: '', e: '', i: '', o: '', u: '', - b: 1, f: 1, p: 1, v: 1, - c: 2, g: 2, j: 2, k: 2, q: 2, s: 2, x: 2, z: 2, - d: 3, t: 3, - l: 4, - m: 5, n: 5, - r: 6 - }; - - r = f + - a - .map(function (v, i, a) { return codes[v] }) - .filter(function (v, i, a) { - return ((i === 0) ? v !== codes[f] : v !== a[i - 1]); - }) - .join(''); - - return (r + '000').slice(0, 4).toUpperCase(); - } - /* - * http://www.anujgakhar.com/2014/03/01/binary-search-in-javascript/ - * Improvements 2015 by AnyWhichWay - */ - function binarySearch(array, key) { - var lo = 0, - hi = array.length - 1, - mid, - element, - results = []; - while (lo <= hi) { - mid = ((lo + hi) >> 1); - element = array[mid]; - if (element < key) { - lo = mid + 1; - } else if (element > key) { - hi = mid - 1; - } else { - if(array[mid]===key || (key && array[mid]===key.valueOf())) { - results.push(mid); - while(array[mid]===key || (key && array[mid]===key.valueOf())) { - mid++; - } - results.push(mid-1); - } - return results; - } - } - return results; - } - /* - * https://github.com/Benvie - * improvements 2015 by AnyWhichWay - */ - function intersection(array) { - var arrays = arguments.length; - // fast path when we have nothing to intersect - if (arrays === 0) { - return []; - } - if (arrays === 1) { - return array.slice(); - } - - var arg = 0, // current arg index - bits = 0, // bits to compare at the end - count = 0, // unique item count - items = [], // unique items - match = [], // item bits - seen = new Map(); // item -> index map - - do { - var arr = arguments[arg], - len = arr.length, - bit = 1 << arg, // each array is assigned a bit - i = 0; - - if (!len) { - return []; // bail out if empty array - } - - bits |= bit; // add the bit to the collected bits - do { - var value = arr[i], - index = seen.get(value); // find existing item index - - if (index === undefined) { // new item - count++; - index = match.length; - seen.set(value, index); - items[index] = value; - match[index] = bit; - } else { // update existing item - match[index] |= bit; - } - } while (++i < len); - } while (++arg < arrays); - - var result = [], - i = 0; - - do { // filter out items that don't have the full bitfield - if (match[i] === bits) { - result[result.length] = items[i]; - } - } while (++i < count); - - return result; - } - function getRandomInt(min, max) { - return Math.floor(Math.random() * (max - min + 1)) + min; - } - //Please cite as - //Shanti R Rao and Potluri M Rao, "Sample Size Calculator", - //Raosoft Inc., 2009, http://www.raosoft.com/samplesize.html - - //probCriticalNormal function is adapted from an algorithm published - //in Numerical Recipes in Fortran. - function probCriticalNormal(P) - { -// input p is confidence level convert it to -// cumulative probability before computing critical - - var Y, Pr, Real1, Real2, HOLD; - var I; - var PN = [0, // ARRAY[1..5] OF REAL - -0.322232431088 , - -1.0 , - -0.342242088547 , - -0.0204231210245 , - -0.453642210148E-4 ]; - - var QN = [0, // ARRAY[1..5] OF REAL - 0.0993484626060 , - 0.588581570495 , - 0.531103462366 , - 0.103537752850 , - 0.38560700634E-2 ]; - - Pr = 0.5 - P/2; // one side significance - - - if ( Pr <=1.0E-8) HOLD = 6; - else { - if (Pr == 0.5) HOLD = 0; - else{ - Y = Math.sqrt ( Math.log( 1.0 / (Pr * Pr) ) ); - Real1 = PN[5]; Real2 = QN[5]; - - for ( I=4; I >= 1; I--) - { - Real1 = Real1 * Y + PN[I]; - Real2 = Real2 * Y + QN[I]; - } - - HOLD = Y + Real1/Real2; - } // end of else pr = 0.5 - } // end of else Pr <= 1.0E-8 - - return HOLD; - } // end of CriticalNormal - - function sampleSize(confidence, margin, population) - { - var response = 50, pcn = probCriticalNormal(confidence / 100.0), - d1 = pcn * pcn * response * (100.0 - response), - d2 = (population - 1.0) * (margin * margin) + d1; - if (d2 > 0.0) - return Math.ceil(population * d1 / d2); - return 0.0; - } - function crossProduct(args,test) { - var end = args.length - 1; - var result = [] - function addTo(curr, start) { - var first = args[start] - , last = (start === end) - for (var i = 0; i < first.length; ++i) { - var copy = curr.slice(); - copy.push(first[i]) - if (last) { - if(!test || test(copy,result.length)) { - result.push(copy); - } - } else { - addTo(copy, start + 1) - } - } - } - if (args.length) { - addTo([], 0) - } else { - result.push([]) - } - return result - } - function Sorter() { - this.sorts = []; - } - Sorter.prototype.by = function(path,direction) { - this.sorts.push({path:path.split("."),direction:direction}); - } - Sorter.prototype.sort = function(rows) { - var me = this; - rows.sort(function(rowa,rowb) { - var result; - me.sorts.some(function(spec) { - var alias = spec.path[0]; - var valuea = rowa[alias]; - var valueb = rowb[alias]; - for(var i = 1;i < spec.path.length; i++) { - valuea = (valuea ? valuea[spec.path[i]] : valuea); - valueb = (valueb ? valueb[spec.path[i]] : valueb); - } - if(valuea===valueb) return result = 0; - if(spec.direction==="asc") { - if(valuea < valueb) return result = -1; - return result = 1; - } - if(valuea < valueb) return result = 1; - return result = -1; - }); - return result; - }); - } - // returns null or undefined if possibleReference is either of those values - // returns possibleReference as value if no aliases provided - // returns dereference.ignore if possibleReference is a reference and can be skipped - // otherwise returns an object representing the reference value, even if a primitive - function dereference(possibleReference,aliases,scope) { - if(possibleReference===null || possibleReference===undefined) { - return {value: toObject(possibleReference)}; - } - var value, type = typeof(possibleReference); - if(type==="function") { - if(possibleReference.deferred) { - return dereference(possibleReference(),aliases,scope) - } - return {value: possibleReference}; - } - if(type==="object") { - var key = Object.keys(possibleReference)[0]; - if(aliases && aliases.indexOf) { - if(aliases.indexOf(key)>=0) { - return {value: dereference.ignore}; - } - } else if(aliases!=null && typeof(aliases)==="object") { - var path; - if(aliases[key] && typeof(aliases[key])==="object") { - path = possibleReference[key].split("."); - value = aliases[key]; - for(var i=0;i=0 && possibleReference[possiblepath]!==undefined) { - test = possiblepath; - value = possibleReference[test]; - if(value instanceof Array) { - return {test: test, value: value}; - } - if(possibleReference[test] && typeof(possibleReference[test])!=="string") { - possiblepath = Object.keys(possibleReference[test])[0]; - } - } - if(possiblepath && scope) { - if(possiblepath.indexOf("/")===0) { - value = scope[0]; - path = possiblepath.substring(1).split("."); - if(path[0]==="") { - path.shift(); - } - } else if(possiblepath.indexOf("..")===0) { - if(scope.length-1<0) { return false; } - value = scope[scope.length-1]; - path = possiblepath.substring(2).split("."); - if(path[0]==="") { - path.shift(); - } - } else if(possiblepath.indexOf(".")===0) { - if(scope.length===0) { return false; } - value = scope[scope.length-1]; - path = possiblepath.substring(1).split("."); - if(path[0]==="") { - path.shift(); - } - } else if(aliases && aliases[possiblepath] && typeof(aliases[possiblepath])!=="function") { - if(possibleReference[test]) { - return {test: test, value: toObject(aliases[possiblepath][possibleReference[test][possiblepath]])}; - } - } else if(test) { - return {test: test, value: toObject(value)}; - } - if(value) { - if(test) { - path.push(possibleReference[test][possiblepath]); - } else { - path.push(possibleReference[possiblepath]); - test = possibleReference.test; - } - for(var i=0;i= value.valueOf(); - case "gt": return providerValue > value.valueOf(); - default: return providerValue === value.valueOf(); - } - return false; - } - function joqularMatch(pattern,aliases,scope) { - scope || (scope = [this]); - var me = this, keys, aliased = false; - if(typeof(pattern)==="function" && pattern.deferred) { - pattern = pattern.call(this,this.valueOf()); - } - if(pattern===undefined || pattern.valueOf()===undefined) { - return null; - } - if(pattern===me || pattern===me.valueOf() || (pattern!=null && pattern.valueOf()===me.valueOf())) { - return me; - } - if(pattern!=null && getIntrinsicType(pattern)==="object") { - keys = Object.keys(pattern); - if(keys.length===0) { - return me; - } - if(keys.every(function(key) { - if(key==='$$') { - return pattern.$$.call(scope[0]); - } - if(key==='$') { - return pattern.$(me.valueOf()); - } - if(key==="forall" || key==="exists") { - return pattern[key](me); - } - var value1 = toObject(me[key]), type1 = getIntrinsicType(value1), value2s = [], value2; - if(value1===undefined) { - return false; - } - - var deref = dereference(pattern[key],aliases,scope); - value2 = deref.value; - if(value2===dereference.ignore) { - return true; - } - if(value2===undefined) { - return false; - } - var type2 = getIntrinsicType(value2); - return (!deref.test && value1===value2 || - (!deref.test && value1.valueOf()===value2.valueOf()) || - (typeof(value1[deref.test])==="function" && value1[deref.test].call(value1,value2)) || - (type2==="function" && value2(value1)) || - (type1==="function" && value1.predicate && value1.call(me,(value2!=null ? value2.valueOf() : value2))) || - (type1==="function" && value1.provider && providerTest(value1.call(me),value2,deref.test,aliases)) || - (type1!=="function" && typeof(value1[deref.test])!=="function" && (type1!==type2 || type2==="object") && value1.joqularMatch && joqularMatch.call(value1,value2,aliases,scope.concat([me])))); - })) { - return this; - } - return null; - } - return null; - }; - // {name: "Simon"} - // {name: {String: "Simon", ids: {}}} - // pattern: {name: "Simon"} - // {name: "Simon", address: {zipcode: 98110}} - // {name: {String: "Simon"}, address: {Object: {zipcode: {Number: 98110}}}} - function Ids() { - - } - function Key() { - - } - function Kind() { - this.joqularIdMap = new Ids(); - this.forgeinIds = {}; - } - Kind.prototype.getValues = function(kind) { - var me = this; - if(!me.joqularValues) { - var values = [], keys = Object.keys(me); - keys.forEach(function(key) { - if(key==="Functions" || key==="joqularIdMap" || key==="joqularId" || key==="forgeinIds") { - return; - } - var value; - switch(kind) { - case "Boolean": value = (key==="true" ? true : false); values.push(value); break; - case "Number": value = parseFloat(key); values.push(value); break; - case "String": value = key; values.push(value); break; - case "Null": value = null; values.push(value); break; - // index find will assume any other types must be tested during instance match cycle - }; - }); - if(kind==="Number") { - values.sort(function(a,b) { return a - b; }); - } else { - values.sort(); - } - me.joqularValues = values; - } - return me.joqularValues; - } - Kind.prototype.getIds = function() { - if(!this.joqularIds) { - Object.defineProperty(this,"joqularIds",{enumerable:false,configurable:true,writable:true,value:Object.keys(this.joqularIdMap)}); - } - return this.joqularIds; - } - Kind.prototype.find = function(index,value,results,scopes,scopekey,scopekind) { - var me = this, testvalue = value.valueOf(), kindname = value.constructor.name, pass = [], instancevalues, instancevalue; - if(!me[scopekey]) { - results.splice(0,results.length); - return false; - } - if(kindname==="Function") { - var kindnames = Object.keys(me[scopekey]); - kindnames.forEach(function(kindname) { - if(value===FindPattern.prototype.defined) { - pass = pass.concat(me[scopekey][kindname].getIds()); - } else { - instancevalues = me[scopekey][kindname].getValues(kindname); - if(value.test==="every") { - if(["Boolean","Number","String","Null"].indexOf(kindname)===-1) { - pass = pass.concat(me[scopekey][kindname].getIds()); - } else { - instancevalues.every(function(instancevalue) { - instancevalue = new Object.joqularIndexes[kindname](instancevalue).valueOf(); - if(value(instancevalue)) { - pass = pass.concat(me[scopekey][kindname][instancevalue].getIds()); - return true; - } - return false; - }); - } - } else if(value.test==="some") { - if(["Boolean","Number","String","Null"].indexOf(kindname)===-1) { - pass = pass.concat(me[scopekey][kindname].getIds()); - } else { - instancevalues.some(function(instancevalue) { - instancevalue = new Object.joqularIndexes[kindname](instancevalue).valueOf(); - if(value(instancevalue)) { - pass = pass.concat(me[scopekey][kindname][instancevalue].getIds()); - return true; - } - return false; - }); - } - } else { - if(["Boolean","Number","String","Null"].indexOf(kindname)===-1) { - pass = pass.concat(me[scopekey][kindname].getIds()); - } else { - instancevalues.forEach(function(instancevalue) { - (kindname==="Number" && isNaN(instancevalue)) || (instancevalue = new Object.joqularIndexes[kindname](instancevalue).valueOf()); - if(value(instancevalue)) { - pass = pass.concat(me[scopekey][kindname][instancevalue].getIds()); - } - }); - } - } - } - }); - } else if(["Boolean","Number","String","Null"].indexOf(kindname)>=0) { - if(value.test) { - if(!me[scopekey][kindname] && value.test==="neq") { - var kindnames = Object.keys(me[scopekey]); - kindnames.forEach(function(kindname) { - pass = pass.concat(me[scopekey][kindname].getIds()); - }); - } else if(me[scopekey][kindname]) { - instancevalues = me[scopekey][kindname].getValues(kindname); - switch(value.test) { - // do optimized tests against sorted values from index - case "lt": - for(var i=0;i=0) { - pass = pass.concat(me[scopekey][kindname][testvalue].getIds()); - }; - break; - case "neq": - instancevalues.forEach(function(instancevalue) { - if(instancevalue !== testvalue) { - pass = pass.concat(me[scopekey][kindname][instancevalue].getIds()); - } - }); - break; - case "gte": - for(var i=instancevalues.length-1;i>=0;i--) { - instancevalue = new value.constructor(instancevalues[i]==="false" ? false : instancevalues[i]).valueOf() - if(instancevalue >= testvalue) { - pass = pass.concat(me[scopekey][kindname][instancevalue].getIds()); - continue; - } - break; - }; - break; - case "gt": - for(var i=instancevalues.length-1;i>=0;i--) { - instancevalue = new value.constructor(instancevalues[i]==="false" ? false : instancevalues[i]).valueOf() - if(instancevalue > testvalue) { - pass = pass.concat(me[scopekey][kindname][instancevalue].getIds()); - continue; - } - break; - }; - break; - // do un-optimized tests - default: - if(Object.joqularIndexes[kindname] && Object.joqularIndexes[kindname].index.keys[value.test] && Object.joqularIndexes[kindname].index.keys[value.test].Function) { - instancevalues.forEach(function(instancevalue) { - instancevalue = new Object.joqularIndexes[kindname](instancevalue); - if(instancevalue[value.test](value)) { - pass = pass.concat(me[scopekey][kindname][instancevalue].getIds()); - } - }); - } - } - } else { // get the objects that support the type of test requested - var kindnames = Object.keys(me[scopekey]); - kindnames.forEach(function(kindname) { - if(["Boolean","Number","String","Null"].indexOf(kindname)>=0) { - return; - } - if(Object.joqularIndexes[kindname] && Object.joqularIndexes[kindname].index.keys[value.test] && Object.joqularIndexes[kindname].index.keys[value.test].Function) { - pass = pass.concat(me[scopekey][kindname].getIds()); - } - }); - } - } else if(me[scopekey] && me[scopekey][kindname] && me[scopekey][kindname][testvalue]) { // test for direct matches - pass = me[scopekey][kindname][testvalue].getIds(); - } - // collect everything that supports the test being requested - } else if(value.test) { - var kindnames = Object.keys(me[scopekey]); - kindnames.forEach(function(kindname) { - if(Object.joqularIndexes[kindname] && Object.joqularIndexes[kindname].index.keys[value.test] && Object.joqularIndexes[kindname].index.keys[value.test].Function) { - pass = pass.concat(me[scopekey][kindname].getIds()); - } - }); - // walk other object - } else if(me[scopekey][kindname] && me[scopekey][kindname].forgeinIds && Object.joqularIndexes[kindname]) { - var fids = Object.keys(me[scopekey][kindname].forgeinIds); - var subresults = Object.joqularIndexes[kindname].index.find(value,fids,scopes,scopekey); - if(subresults.length>0) { - pass = pass.concat(me[scopekey][kindname].getIds()); - } - // walk keys and sub-objects - } else if(kindname==="Pattern") { - var keys = Object.keys(value); - if(keys.every(function(key) { - if(me[key] instanceof Key) { - return me.find(index,value[key],pass,scopes,key,value[key].constructor.name); - } - return true; - })) { - // look in child objects in case key was not present - var kindnames = Object.keys(me[scopekey]); - kindnames.forEach(function(kindname) { - if(me[scopekey][kindname].forgeinIds && Object.joqularIndexes[kindname]) { - var fids = Object.keys(me[scopekey][kindname].forgeinIds); - var subresults = Object.joqularIndexes[kindname].index.find(value,fids,scopes,scopekey); - if(subresults.length>0) { - pass = pass.concat(me[scopekey][kindname].getIds()); - } - } - }); - } - } - if(pass.length===0) { - results.splice(0,results.length); - return false; - } - results.index = true; - var tmp = (results.length>0 ? intersection(results,pass) : pass); - results.splice.apply(results,[0,results.length].concat(tmp)); - return results.length>0; - } - function Value() { - this.joqularIdMap = new Ids(); - } - Value.prototype.getIds = function() { - if(!this.joqularIds) { - this.joqularIds = Object.keys(this.joqularIdMap); - } - return this.joqularIds; - } - function Method() { - this.joqularIdMap = new Ids(); - } - Method.prototype.getIds = function() { - if(!this.joqularIds) { - this.joqularIds = Object.keys(this.joqularIdMap); - } - return this.joqularIds; - } - function Pattern(init) { - for(var key in init) { - this[key] = init[key]; - } - } - function FindPattern(pattern,aliases) { - this.compile(pattern,aliases); - } - FindPattern.prototype = new Pattern(); - FindPattern.prototype.defined = function(value) { - return value!==undefined - } - FindPattern.prototype.compile = function(pattern,aliases,scope) { - scope || (scope = this); - var me = this, keys = Object.keys(pattern); - keys.forEach(function(key) { - if(key==="$forall" || key==="$exists") { - return; // should only exist at top level, perhaps alias with every and exists and ih=gnore at top level? - } - if(key.indexOf("$$")===0) { - return; - } - var value = pattern[key], type = typeof(value); - value = toObject(value); - if(value.valueOf()!=null && type==="object") { - if(value instanceof Array) { - scope[key] = value; - } else { - var possibletest = Object.keys(value)[0]; - if(possibletest && (["$$"].indexOf(possibletest)>=0 || possibletest.indexOf("/")===0 || possibletest.indexOf(".")===0)) { - value = me.defined; - scope[key] = value; // just ensure key defined, leave resolution until final match, i.e. don't do in the index find, do against preliminary results - } else if(possibletest && possibletest.indexOf("$")===0) { - value = toObject(value[possibletest]); - Object.defineProperty(value,"test",{enumerable:false,configurable:true,writable:true,value:possibletest.substring(1)}); - scope[key] = value; - } else if(!(value instanceof Date) && Object.keys(value).length===0) { // handle keyless objects like Sets - value = me.defined; - scope[key] = value; // handle outside of index - } else if(typeof(me[possibletest])==="function") { - var f = value[possibletest]; - value = function() { - return me[possibletest](f,index,results,scope,scopekey,scopekind); - } - scope[key] = value; - } else { - scope[key] = new Pattern(); - me.compile(value,aliases,scope[key]); - } - } - } else { - Object.defineProperty(value,"test",{enumerable:false,configurable:true,writable:true,value:"eq"}); - scope[key] = value; - } - }); - } - function MatchPattern(pattern,literals,aliases) { - this.compile(pattern,literals,aliases); - } - MatchPattern.prototype = new Pattern(); - MatchPattern.prototype.compile = function(pattern,literals,aliases,scope) { - scope || (scope = this); - var me = this, keys = Object.keys(pattern), isfunction = false; - keys.forEach(function(key) { - if(key==="$forall" || key==="$exists") { - return; // not relevant for object matching - } - var value = pattern[key], type = typeof(value); - if(key!=="$$" && key.indexOf("$")===0 && key.length>1) { - key = key.substring(1); - isfunction = true; - } - if(type==="function" || key.indexOf("..")===0 || key.indexOf("/")===0) { - scope[key] = value; - } else if(value!=null && type==="object") { - var possibletest = Object.keys(value)[0]; - if(value[possibletest] && typeof(value[possibletest])==="object" && aliases) { - var possiblealias = Object.keys(value[possibletest])[0]; - // arrays can't be tests and may actually exist to contain function arguments - if(!(value[possibletest] instanceof Array) && aliases[possiblealias] || (aliases.indexOf && aliases.indexOf(possiblealias)>=0)) { - return; - } - } - if(["$lt","$lte","$eq","$neq","$gte","$gt"].indexOf(possibletest)>=0) { - // ignore tests on primtives which were handled by index - if(["Boolean","Number","String","Null"].indexOf(value.constructor.name)===-1) { - var v = {}; - v[possibletest.substring(1)] = value[possibletest]; - scope[key] = v; - } - } else if(value.constructor.name!=="Object") { - scope[key] = value; - } else { - scope[key] = {}; - me.compile(value,literals,aliases,scope[key]); - } - } else if(isfunction || literals){ - scope[key] = (value ? value.valueOf() : value); - } - }); - } - function Index(kindName) { - this.joqularIdMap = new Ids(); - this.keys = new Kind(); - this.nextId = 0; - this.kindName = kindName; - } - Index.prototype.getIds = function() { - if(!this.joqularIds) { - this.joqularIds = Object.keys(this.keys.joqularIdMap); - } - return this.joqularIds; - } - Index.prototype.index = function(instance) { - var me = this, id, kind = me.keys, value, type, kindname = instance.constructor.name; - if(["Boolean","Number","String","Null"].indexOf(kindname)===-1) { - if(instance.joqularId==null) { - id = me.nextId++; - instance.joqularId = id; - } else { - id = instance.joqularId; - } - me.keys.joqularIdMap[id] = instance; - Object.observe(instance,function(changes) { - me.update(instance.joqularId,changes); - }); - } - for(var key in instance) { - if(kindname==="String" && typeof(instance[key])==="string") continue; - value = instance[key]; - value = toObject(value); - if(value===undefined) continue; - kindname = value.constructor.name, type = typeof(value.valueOf()); - if(instance[key]===null) type = "undefined"; - Object.joqularIndexes[kindname] || (Object.joqularIndexes[kindname] = value.constructor); - Object.joqularIndexes[kindname].index || (Object.joqularIndexes[kindname].index = new Index(kindname)); - kind[key] || (kind[key] = new Key()); - kind[key][kindname] || (kind[key][kindname] = new Kind()); - if(id!=null) { - kind[key][kindname].joqularIdMap[id] = 1; - } - if(["Boolean","Number","String","Null"].indexOf(kindname)>=0) { - kind[key][kindname][value.valueOf()] || (kind[key][kindname][value.valueOf()] = new Value()); - kind[key][kindname][value.valueOf()].joqularIdMap[id] = 1; - (kindname==="Number" && isNaN(value)) || Object.joqularIndexes[kindname].index.index(value); - } else if(kindname!==me.kindName || value.joqularId!==id){ - if(value.joqularId==null) { - Object.joqularIndexes[kindname].index.index(value); - } - kind[key][kindname].forgeinIds[value.joqularId] = id; - } - } - if(instance instanceof Array) { - kind.length!=null || (kind.length = new Key()); - kind.length.Number || (kind.length.Number = new Kind()); - kind.length.Number[instance.length] || (kind.length.Number[instance.length] = new Value()); - kind.length.Number[instance.length].joqularIdMap[id] = 1; - kind.length.Number.joqularIdMap[id] = 1; - } - } - Index.prototype.update = function(id,changes) { - var me = this, kind = this.keys; - changes.forEach(function(change) { - var key = change.name, value = toObject(change.object[key]), kindname = value.constructor.name, type = typeof(change.object[key]); - if(change.type==="update" || change.type==="delete") { - var oldvalue = toObject(change.oldValue), oldkindname = oldvalue.constructor.name, oldtype = typeof(change.oldValue); - if(change.oldValue!==null && oldtype==="object") { - delete kind[key][oldkindname].forgeinIds[oldvalue.joqularId]; - } else if(kind[key][oldkindname][change.oldValue].joqularIdMap[id]) { - delete kind[key][oldkindname][change.oldValue].joqularIdMap[id]; // delete reference from index - delete kind[key][oldkindname][change.oldValue].joqularIds; // delete cached id list - } - } - kind[key] || (kind[key] = new Key()); - kind[key][kindname] || (kind[key][kindname] = new Kind()); - if(change.type==="update" || change.type==="add") { - if(type==="object" && value!=null) { - if(value.joqularId===null) { - Object.joqularIndexes[kindname] || (Object.joqularIndexes[kindname] = value.constructor); - Object.joqularIndexes[kindname].index || (Object.joqularIndexes[kindname].index = new Index(kindname)); - Object.joqularIndexes[kindname].index.index(value); - } - kind[key][kindname].forgeinIds[value.joqularId] - } else { - kind[key][kindname][value.valueOf()] || (kind[key][kindname][value.valueOf()] = new Value()); - kind[key][kindname][value.valueOf()].joqularIdMap[id] = 1; - } - } - return; - }); - } - Index.prototype.find = function(pattern,aliases,scopes,scopekey) { - var me = this, findpattern = (pattern instanceof Pattern ? pattern : new FindPattern(pattern,aliases)), - matchpattern = (pattern instanceof Pattern ? pattern : new MatchPattern(pattern,false,aliases)), - keys = Object.keys(findpattern), found = [], results = []; - if(scopes) { - scopes = [me.keys].concat(scopes); - } else { - scopes = [me.keys]; - } - if(keys.every(function(key) { - return me.keys.find(me,findpattern[key],found,scopes,key,findpattern[key].constructor.name); - })) { - if(keys.length===0) { - found = me.getIds(); - found.index = true; - } - results.index = found.index; - if(pattern.$forall && !found.every(function(id) {return pattern.$forall(me.keys.joqularIdMap[id]); })) { - return results; - } - if(pattern.$exists && !found.some(function(id) {return pattern.$exists(me.keys.joqularIdMap[id]); })) { - return results; - } - var matchlength = Object.keys(matchpattern).length; - found.forEach(function(id) { - var matchscopeid, matchscope; - if(scopekey && scopes[scopes.length-1][scopekey]) { - matchscopeid = scopes[scopes.length-1][scopekey][me.kindName].forgeinIds[id]; - matchscope = [scopes[scopes.length-1].joqularIdMap[matchscopeid]]; - } - if(matchlength===0 || joqularMatch.call(me.keys.joqularIdMap[id],matchpattern,aliases,matchscope)) { - results.push(me.keys.joqularIdMap[id]); - } - }); - } - return results; - } - Index.prototype.clear = function(indexOnly,asynch) { - this.joqularIdMap = new Ids(); - this.keys = new Kind(); - this.nextId = 0; - var promise; - if(!indexOnly) { - promise = this.save(); // writes empty index since values reset above - } else { - promise = new Promise(function(resolve,reject) { resolve(); }); - } - if(typeof(asynch)==="function") { - promise.then(function(count) { - asynch(null,count); - })["catch"](function(e) { - asynch(e); - }); - return null; - } - return promise; - } - Index.prototype.flush = function(id) { - var me = this, ids; - if(id!=null) { - ids = [id]; - } else { - ids = me.getIds(); - } - ids.forEach(function(id) { - me.joqularIdMap[id] = 1; - }); - } - Index.prototype.restore = function(id) { - var me = this, cons = Object.joqularIndexes[me.kindName], ids, results = {}; - if(id!=null) { - ids = [id]; - } else { - ids = me.getIds(); - } - ids.forEach(function(id) { - var object = me.joqularIdMap[id]; - if(!object) { - return; - } - if(object===1) { - object = Object.create(cons.prototype); - Object.defineProperty(object,"constructor",{enumerable:false,configurable:true,writable:true,value:cons}); - object.__proto__ = cons.prototype; - var keys = Object.keys(me.keys); - keys.forEach(function(key) { - var kindnames = Object.keys(me.keys[key]); - kindnames.forEach(function(kindname) { - if(["Boolean","Number","String","Null"].indexOf(kindname)>=0) { // FUnction?? - var values = me.keys[key][kindname].getValues(kindname); - values.forEach(function(value) { - if(me.keys[key][kindname][value].joqularIdMap[id]) { - switch(kindname) { - case "Boolean": object[key] = (value==="true" ? true : false); break; - case "Number": object[key] = parseFloat(value); break; - case "String" : object[key] = value; break; - case "Null" : object[key] = null; - } - } - }); - } else { - // joqularRestore(object,cons.index[key][type]); - } - }); - }); - me.joqularIdMap[id] = object; - results[id] = object; - } - }); - return results; - } - function QueryPattern(pattern) { - this.value = pattern; - } - QueryPattern.prototype.toJSON = function() { - return this.value; - } - function Statement(projection) { - - } - function Insert() { - - } - Insert.prototype = new Statement(); - Insert.prototype.into = function(constructor) { - this.impacts = [constructor]; // an array so it is consistent with other statements - return this; - } - Insert.prototype.keys = function(keys) { - this.keyNames = keys; - this.insert = null; - return this; - } - Insert.prototype.values = function(values) { - this.keyValues = values; - this.insert = null; - return this; - } - Insert.prototype.object = function(object) { - this.insert = object; - this.keyNames = null; - this.keyValues = null; - return this; - } - Insert.prototype.exec = function(wait,persist) { - persist = (persist || persist==null ? true : false); - var me = this, constructor = me.impacts[0], object; - if(me.keyNames && me.keyValues) { - object = Object.create(constructor.prototype); - Object.defineProperty(object,"constructor",{enumerable:false,value:me.impacts[0]}); - object.__proto__ = constructor.prototype; - me.keyNames.forEach(function(key,i) { - object[key] = me.keyValues[i]; - }); - constructor.joqularIndex(object); - if(persist) { - constructor.joqularSave(); - } - } else if(me.insert) { - object = me.insert; - if(!(object instanceof me.impacts[0])) { - var object = Object.create(constructor.prototype); - Object.defineProperty(object,"constructor",{enumerable:false,value:me.impacts[0]}); - //object.constructor = constructor; - object.__proto__ = constructor.prototype; - var keys = Object.keys(me.insert); - keys.forEach(function(key) { - object[key] = me.insert[key]; - }); - } - constructor.joqularIndex(object); - if(persist) { - constructor.joqularSave(); - } - } - return object; - } - Insert.prototype.toJSON = function() { - var json = {}; - json.into = this.impacts[0].name; - if(this.keyNames) { - json.keys = this.keyNames; - } - if(this.values) { - json.value = this.values; - } - if(this.object) { - json.object = this.object; - } - return {insert: json}; - } - function Select(projection) { - this.projection = projection; - } - Select.prototype = new Statement(); - Select.prototype.exec = function(wait) { - var me = this; - function doit() { - var aliasnames = Object.keys(me.aliases), selfs = [], compare = {}; - if(!aliasnames.every(function(aliasname) { - var pattern = {}; - if(me.patterns && me.patterns[aliasname]) { - var keys = Object.keys(me.patterns[aliasname].value); - keys.forEach(function(key) { - if(key=="eq" || key=="neq") { // collect object comparisons - compare[aliasname] || (compare[aliasname] = {}); - compare[aliasname][key] = me.patterns[aliasname].value[key]; - // reflexive test - compare[me.patterns[aliasname].value[key]] || (compare[me.patterns[aliasname].value[key]] = {}); - compare[me.patterns[aliasname].value[key]][key] = aliasname; - } else { - pattern[key] = me.patterns[aliasname].value[key]; - } - }); - } - var matches = me.aliases[aliasname].joqularFind(pattern,false,aliasnames); - if(matches.length===0) { - if(!matches.index) { - matches = []; - var ids = me.aliases[aliasname].index.getIds(); - ids.forEach(function(id) { - matches.push(me.aliases[aliasname].index.keys.joqularIdMap[id]); - }); - } - if(matches.length===0) { - return false; - } - } - selfs.push(matches); - return true; - })) { - return []; - }; - if(selfs.length>0) { - var rows = crossProduct(selfs,function(row,i) { - if(me.firstCount!=null && i>=me.firstCount && !me.ordering && me.confidenceLevel==null && me.sampleSize==null) { - return false; - } - var aliases = {}; - row.forEach(function(object,i) { - aliases[aliasnames[i]] = object; - }); - return row.every(function(object,i) { - var aliasname = aliasnames[i], pattern = {}; - // compare objects if required - if(compare[aliasname]) { - var tests = Object.keys(compare[aliasname]); - if(!tests.every(function(test) { - var otheraliasnames = compare[aliasname][test]; - if(typeof(otheraliasnames)==="string") { - otheraliasnames = [otheraliasnames]; - } - return otheraliasnames.every(function(otheraliasname) { - var j = aliasnames.indexOf(otheraliasname), otherobject = row[j]; - if(test==="eq") { - return object===otherobject; - } else { // neq - return object!==otherobject; - } - }); - })) { - return false; - } - } - // get pattern for current object type - if(me.patterns && me.patterns[aliasname]) { - pattern = me.patterns[aliasname].value; - } - // match object to pattern, passing in aliases so that cross-references can be resolved - if(object.joqularMatch(pattern,aliases)) { - row[aliasname] = object; - return true; - } - return false; - }); - }); - if(me.sampleSize!=null || (me.confidenceLevel!=null && me.marginOfError!=null)) { - if(me.randomize) { - rows.sort(function(a,b) { - return getRandomInt(-1,1); - }); - } - var size, samples = []; - if(me.confidenceLevel!=null && me.marginOfError!=null) { - size = sampleSize(me.confidenceLevel, me.marginOfError, rows.length) - } else if(me.sampleSize>=1) { - size = Math.floor(me.sampleSize); - } else { - size = Math.max(1,Math.round(me.sampleSize * rows.length)); - } - if(sizeme.firstCount) { - rows = rows.slice(0,me.firstCount); - } - } else if(me.lastCount!=null) { - if(rows.length>=me.lastCount) { - rows = rows.slice(-me.lastCount); - } - } - if(me.projection) { - rows.forEach(function(row,i) { - var projection = {}, columns = Object.keys(me.projection); - var aliasnames = Object.keys(me.aliases); - columns.forEach(function(column) { - var reference = me.projection[column]; - aliasnames.some(function(aliasname) { - if(reference[aliasname]) { - var path = reference[aliasname].split("."); - var value = row[aliasname]; - for(var i=0;i=2 && typeof(randomizeOrMarginOfError)==="number") { - this.confidenceLevel = sizeOrConfidenceLevel; - this.marginOfError = randomizeOrMarginOfError; - this.randomize = randomize; - } else if(arguments.length===1 || typeof(randomizeOrMarginOfError)==="boolean") { - this.sampleSize = sizeOrConfidenceLevel; - this.randomize = randomizeOrMarginOfError; - } - return this; - } - Select.prototype.from = function(aliases) { - this.aliases = aliases; - return this; - } - Select.prototype.where = function(patterns) { - var me = this; - me.patterns = {}; - var aliases = Object.keys(me.aliases), patternaliases = Object.keys(patterns); - patternaliases.forEach(function(alias) { - if(aliases.indexOf(alias)>=0) { - me.patterns[alias] = new QueryPattern(patterns[alias]); - return true; - } - throw new Error("The top level pattern " + JSON.stringify(new QueryPattern(patterns[alias])) + " does not refer to a class"); - }); - return me; - } - Select.prototype.orderBy = function(ordering) { - this.ordering = ordering; - return this; - } - var JOQULAR = { - enhance: function(constructor,config) { - Object.joqularIndexes = {}; - function createIndex(cons,auto,async,name) { - auto = (auto===undefined ? true : auto); - name || (name = cons.name); - var newcons = Function("root","cons","auto","async","return function " + name + "() {var me = this;if(!(me instanceof " + name + ")) { me = new " + name + "(); } cons.apply(me,arguments); Object.defineProperty(me,'constructor',{enumerable:false,value:" + name + "}); return (auto ? " + name + ".joqularIndex(me,async) : me); }")(constructor,cons,auto,async); - Object.joqularIndexes[name] = newcons; - var keys = Object.getOwnPropertyNames(constructor); - keys.forEach(function(key) { - try { - newcons[key] = constructor[key]; - } catch(e) { - - } - }); - keys = Object.getOwnPropertyNames(cons); - keys.forEach(function(key) { - try { - newcons[key] = cons[key]; - } catch(e) { - - } - }); - newcons.prototype = Object.create(cons.prototype); - newcons.index = new Index(name); - newcons.indexing = {}; - if(config.datastore && config.datastore.name && config.datastore.type==="IndexedDB") { - Object.defineProperty(newcons,"joqularSave",{enumerable:false,value:function(aysnch) { - var me = this, tid; - var promise = new Promise(function(resolve,reject) { - me.dbVersion || (me.dbVersion = 1); - var dbrequest = indexedDB.open(config.datastore.name,me.dbVersion); - dbrequest.onupgradeneeded = function(event) { - var db = event.target.result; - if(!db.objectStoreNames.contains(name)) { - db.createObjectStore(name, { autoIncrement : true }); - } - }; - dbrequest.onblocked = function(event) { - reject(event); - }; - dbrequest.onerror = function(event) { - if(event.target.error.name==="VersionError" && event.target.error.message.indexOf(" less ")>=0) { - event.cancelBubble = true; - me.dbVersion++; - me.joqularSave(); - } else { - reject(event); - } - }; - dbrequest.onsuccess = function(event) { - var db = event.target.result, objectstore; - if(!db.objectStoreNames.contains(name)) { - db.close(); - me.dbVersion++; - me.joqularSave(); - } else { - objectstore = db.transaction(name, "readwrite").objectStore(name); - var request = objectstore.get("root"); - request.onsuccess = function(event) { - var object = request.result; - if(!object) { - objectstore.add({ids:me.ids,index:me.index},"root"); - } else { - object.ids = me.ids; - object.index = me.index; - objectstore.put(object,"root"); - } - db.close(); - var count = me.index.getIds().length - 1; // -1 for nextId key - resolve(count); - }; - request.onerror = function(event) { - reject(event); - } - } - }; - }); - if(typeof(asynch)==="function") { - promise.then(function(count) { - asynch(null,count); - })["catch"](function(e) { - asynch(e); - }); - return null; - } - /*else if(typeof(asynch)==="number") { - tid = setTimeout(function() { tid = null; }); - - }*/ - return promise; - }}); - Object.defineProperty(newcons,"joqularLoad",{enumerable:false,value:function(aysnch) { - var me = this; - var promise = new Promise(function(resolve,reject) { - me.dbVersion || (me.dbVersion = 1); - var dbrequest = indexedDB.open(config.datastore.name,me.dbVersion); - dbrequest.onupgradeneeded = function(event) { - var db = event.target.result; - if(!db.objectStoreNames.contains(name)) { - db.createObjectStore(name, { autoIncrement : true }); - } - }; - dbrequest.onblocked = function(event) { - console.log(event); - reject(event) - }; - dbrequest.onerror = function(event) { - if(event.target.error.name==="VersionError" && event.target.error.message.indexOf(" less ")>=0) { - event.cancelBubble = true; - me.dbVersion++; - me.joqularLoad(); - } else { - reject(event) - } - }; - dbrequest.onsuccess = function(event) { - var db = event.target.result, objectstore; - if(!db.objectStoreNames.contains(name)) { - db.close(); - me.dbVersion++; - me.joqularLoad(); - } else { - objectstore = db.transaction(name).objectStore(name); - // look for checkpoints from failed transaction, - // if found, restore the checkpoint - - // else ... - var request = objectstore.get("root"); - request.onsuccess = function(event) { - var object = request.result; - if(object) { - me.ids = {}; - var keys = Object.keys(object.ids); - keys.forEach(function(id) { - if(id!=="nextId") { - me.ids[id] = Object.create(me.prototype); - for(var property in object.ids[id]) { - me.ids[id][property] = object.ids[id][property]; - } - Object.defineProperty(me.ids[id],"constructor",{enumerable:false,value:me}); - me.ids.nextId = parseInt(id)+1; - } - }); - me.index = object.index; - } else { - me.ids = {}; - me.ids.nextId = 0; - me.index = {}; - } - db.close(); - var count = Object.keys(me.ids).length - 1; // -1 for nextId key - resolve(count); - }; - } - }; - }); - if(typeof(asynch)==="function") { - promise.then(function(count) { - asynch(null,count); - })["catch"](function(e) { - asynch(e); - }); - return null; - } - return promise; - }}); - } - return newcons; - } - if(config.index===true) { - config.enhancePrimitives = true; - config.enhanceArray = true; - config.ehhanceDate = true; - Object.defineProperty(constructor,"joqularFind",{enumarable:false,value:function(pattern,wait,aliasnames) { - var me = this; - function dowait(f) { - if(Object.keys(me.indexing).length===0) { - f(); - } else { - setTimeout(function() { dowait(f) },100); - } - } - var me = this; - if(wait) { - if(typeof(wait)==="function") { - dowait(function() { - wait(null,me.index.find(pattern,aliasnames)); - }); - } else { - return new Promise(function(resolve,reject) { - dowait(function() { resolve(me.index.find(pattern,aliasnames)); }); - }); - } - } - return me.index.find(pattern,aliasnames) - }}); - Object.defineProperty(constructor,"joqularIndex",{enumarable:false,value:function(instance,async) { - var me = this; - if(async) { - var tid; - if(typeof(async)==="function") { - tid = setTimeout(function() { me.index.index(instance); delete me.indexing[tid]; async(instance); },0); - me.indexing[tid] = true; - return tid; - } else { - var promise = new Promise(function(resolve,reject) { - tid = setTimeout(function() { me.index.index(instance); delete me.indexing[tid]; resolve(instance); },0); - }); - me.indexing[tid] = promise; - return promise; - } - } - me.index.index(instance); - return instance; - }}); - }; - function Time(value,precision) { - if(value==null) { - value = new Date().getTime() - } else if(value.constructor===Time || value instanceof Time) { - value = value.valueOf(); - } else if(value instanceof Date) { - value = value.getTime(); - } else if(value instanceof TimeSpan) { - value = value.starts.valueOf(); - } else if(typeof(value)==="string") { - value = Date.parse(value); - } - this.milliseconds = value; - this.toPrecision(precision,true); - Object.defineProperty(this,"constructor",{enumerable:false,configurable:true,writable:true,value:Time}); - }; - Time.prototype = Object.create(constructor.prototype); - Time.prototype.valueOf = function() { - return this.milliseconds; - }; - Time.prototype.withPrecision = function(precision) { - return this.toPrecision(precision,false); - }; - Time.prototype.toPrecision = function(precision,modify) { - modify = (modify || modify==null ? true : false); - if(!precision || this.milliseconds===Infinity || this.milliseconds===-Infinity || isNaN(this.milliseconds)) { - if(modify) { - return this; - } - return new Time(this.milliseconds); - } - var Y1 = this.getFullYear(); - var M1 = (["M","D","h","m","s","ms"].indexOf(precision)!==-1 ? this.getMonth() : null); - var D1 = (["D","h","m","s","ms"].indexOf(precision)!==-1 ? this.getDate() : null); - var h1 = (["h","m","s","ms"].indexOf(precision)!==-1 ? this.getHours() : null); - var m1 = (["m","s","ms"].indexOf(precision)!==-1 ? this.getMinutes() : null); - var s1 = (["s","ms"].indexOf(precision)!==-1 ? this.getSeconds() : null); - var ms1 = (["ms"].indexOf(precision)!==-1 ? this.getMilliseconds() : null); - var date = new Date(Y1,M1,D1,h1,m1,s1,ms1); - if(modify) { - this.setTime(date.getTime()); - return this; - } - return new Time(date); - }; - Time.prototype.lt = toPredicate(function(value,precision) { - return new Time(this).withPrecision(precision).valueOf() < new Time(value,precision).valueOf(); - }); - Time.prototype.lte = toPredicate(function(value,precision) { - if(value===this) { - return true; - } - return new Time(this).withPrecision(precision).valueOf() <= new Time(value,precision).valueOf(); - }); - Time.prototype.eq = toPredicate(function(value,precision) { - if(value===this) { - return true; - } - return new Time(this).withPrecision(precision).valueOf() === new Time(value,precision).valueOf(); - }); - Time.prototype.neq = toPredicate(function(value,precision) { - return new Time(this).withPrecision(precision).valueOf() !== new Time(value,precision).valueOf(); - }); - Time.prototype.gte = toPredicate(function(value,precision) { - if(value===this) { - return true; - } - return new Time(this).withPrecision(precision).valueOf() >= new Time(value,precision).valueOf(); - }); - Time.prototype.gt = toPredicate(function(value,precision) { - return new Time(this).withPrecision(precision).valueOf() > new Time(value,precision).valueOf(); - }); - Time.prototype["in"] = toPredicate(function(value,precision) { - if(value instanceof TimeSpan) { - return value.contains(this); - } - return new Time(this,precision).valueOf() === new Time(value,precision).valueOf(); - }); - var dateProperties = { - getDate: null, - getDay: null, - getFullYear: null, - getHours: null, - getMilliseconds: null, - getMinutes: null, - getMonth: null, - getSeconds: null, - getTime: null, - getTimezoneOffset: null, - getUTCDate: null, - getUTCDay: null, - getUTCFullYear: null, - getUTCHours: null, - getUTCMilliseconds: null, - getUTCMinutes: null, - getUTCMonth: null, - getUTCSeconds: null, - getYear: null, - parse: null, - setDate: null, - setFullYear: null, - setHours: null, - setMilliseconds: null, - setMinutes: null, - setMonth: null, - setSeconds: null, - setTime: null, - setUTCDate: null, - setUTCFullYear: null, - setUTCHours: null, - setUTCMilliseconds: null, - setUTCMinutes: null, - setUTCMonth: null, - setUTCSeconds: null, - setYear: null, - toDateString: null, - toGMTString: null, - toISOString: null, - toLocaleDateString: null, - toLocaleTimeString: null, - toLocaleString: null, - toString: null, - toTimeString: null, - toUTCString: null, - UTC: null - } - Object.keys(dateProperties).forEach(function(key) { - if(!Time.prototype[key]) { - Time.prototype[key] = function() { - var dt = new Date(this.milliseconds); - var result = dt[key].apply(dt,arguments); - this.milliseconds = dt.getTime(); - return result; - } - } - }); - function Duration(value,period) { - period || (period = "ms"); - if(value.constructor===Duration || value instanceof Duration) { - period = "ms"; - value = value.valueOf(); - } - this.length = value * Duration.factors[period]; - this.range = 0; - Object.defineProperty(this,"constructor",{enumerable:false,configurable:true,writable:true,value:Duration}); - }; - Duration.factors = { - Y: 31557600*1000, - M: (31557600*1000)/12, // psuedo-month - W: 7 * 24 * 60 * 60 * 1000, - D: 24 * 60 * 60 * 1000, - h: 60 * 60 * 1000, - m: 60 * 1000, - s: 1000, - ms: 1 - } - Duration.prototype = Object.create(constructor.prototype); - Object.defineProperty(Duration.prototype,"years",{enumerable:true,configurable:false,set:function() { return;},get:function() { return this.length/Duration.factors["Y"]; }}); - Object.defineProperty(Duration.prototype,"months",{enumerable:true,configurable:false,set:function() { return;},get:function() { return this.length/Duration.factors["M"]; }}); - Object.defineProperty(Duration.prototype,"weeks",{enumerable:true,configurable:false,set:function() { return;},get:function() { return this.length/Duration.factors["W"]; }}); - Object.defineProperty(Duration.prototype,"days",{enumerable:true,configurable:false,set:function() { return;},get:function() { return this.length/Duration.factors["D"]; }}); - Object.defineProperty(Duration.prototype,"hours",{enumerable:true,configurable:false,set:function() { return;},get:function() { return this.length/Duration.factors["h"]; }}); - Object.defineProperty(Duration.prototype,"minutes",{enumerable:true,configurable:false,set:function() { return;},get:function() { return this.length/Duration.factors["m"]; }}); - Object.defineProperty(Duration.prototype,"seconds",{enumerable:true,configurable:false,set:function() { return;},get:function() { return this.length/Duration.factors["s"]; }}); - Object.defineProperty(Duration.prototype,"milliseconds",{enumerable:true,configurable:false,set:function() { return;},get:function() { return this.length; }}); - Duration.prototype.valueOf = function() { - return this.length; - }; - Duration.prototype.lt = toPredicate(function(value,period) { - period || (period = "s"); - return this.valueOf() / Duration.factors[period] < new Duration(value).valueOf() / Duration.factors[period]; - }); - Duration.prototype.lte = toPredicate(function(value,period) { - if(value===this) { - return true; - } - period || (period = "s"); - return this.valueOf() / Duration.factors[period] <= new Duration(value).valueOf() / Duration.factors[period]; - }); - Duration.prototype.eq = toPredicate(function(value,period) { - if(value===this) { - return true; - } - period || (period = "s"); - return this.valueOf() / Duration.factors[period] === new Duration(value).valueOf() / Duration.factors[period]; - }); - Duration.prototype.neq = toPredicate(function(value,period) { - period || (period = "s"); - return this.valueOf() / Duration.factors[period] !== new Duration(value).valueOf() / Duration.factors[period]; - }); - Duration.prototype.gte = toPredicate(function(value,period) { - if(value===this) { - return true; - } - period || (period = "s"); - return this.valueOf() / Duration.factors[period] >= new Duration(value).valueOf() / Duration.factors[period]; - }); - Duration.prototype.gt = toPredicate(function(value,period) { - period || (period = "s"); - return this.valueOf() / Duration.factors[period] > new Duration(value).valueOf() / Duration.factors[period]; - }); - Duration.prototype.atLeast = function() { - this.range = -1; - }; - Duration.prototype.atMost = function() { - this.range = 1; - }; - Duration.prototype.exact = function() { - this.range = 0; - }; - // need to define gt, lt etc. in context of range - function TimeSpan(starts,ends) { - if((starts && starts.constructor===TimeSpan) || starts instanceof TimeSpan) { - return new TimeSpan(starts.starts,starts.ends); - } - this.starts = (starts!=null ? new Time(starts).valueOf() : new Time(-Infinity).valueOf()); - this.ends = (ends!=null ? new Time(ends).valueOf() : new Time(Infinity).valueOf()); - Object.defineProperty(this,"duration",{enumerable:true,configurable:false,get:function() { return this.ends - this.starts}, set: function() {}}); - Object.defineProperty(this,"constructor",{enumerable:false,configurable:true,writable:true,value:TimeSpan}); - }; - TimeSpan.prototype = Object.create(constructor.prototype); - TimeSpan.prototype.contains = toPredicate(function(value,precision) { - var starts, ends, time; - if(value instanceof TimeSpan) { - starts = time = new Time(value.starts,precision).valueOf(); - ends = new Time(value.ends,precision).valueOf(); - } else { - starts = time = ends = new Time(value.valueOf(),precision); - } - return this.starts <= starts <= time <= ends <= this.ends; - }); - TimeSpan.prototype.intersects = toPredicate(function(value,precision) { - var starts, ends; - if(value instanceof TimeSpan) { - starts = new Time(value.starts,precision).valueOf(); - ends = new Time(value.ends,precision).valueOf(); - } else { - starts = ends = new Time(value.valueOf(),precision); - } - if(this.starts>=starts && this.starts<=ends) { - return true; - } - if(this.ends<=value.ends && this.ends>=starts) { - return true; - } - return false; - }); - TimeSpan.prototype.disjoint = toPredicate(function(value,precision) { - return !this.intersects(value,precision); - }); - TimeSpan.prototype.coincident = toPredicate(function(value,precision) { - var starts, ends; - if(value instanceof TimeSpan) { - starts = new Time(value.starts,precision).valueOf(); - ends = new Time(value.ends,precision).valueOf(); - } else { - starts = ends = new Time(value.valueOf(),precision); - } - return this.starts==starts && this.ends==ends; - }) - TimeSpan.prototype.eq = toPredicate(function(value,precision) { - if(this===value) { - return true; - } - if(!(value instanceof TimeSpan)) { - return false; - } - return new Time(this.starts,precision).valueOf() === new Time(value.starts,precision).valueOf() && - new Time(this.ends,precision).valueOf() === new Time(value.ends,precision).valueOf(); - }); - TimeSpan.prototype.adjacentOrBefore = toPredicate(function(value,precision) { - return new Time(this.ends+new Duration(1,precision),precision).valueOf() <= new Time(value,precision).valueOf(); - }); - TimeSpan.prototype.before = toPredicate(function(value,precision) { - return new Time(this.ends+new Duration(1,precision),precision).valueOf() < new Time(value,precision).valueOf(); - }); - TimeSpan.prototype.adjacentBefore = toPredicate(function(value,precision) { - return new Time(this.ends+new Duration(1,precision),precision).valueOf() === new Time(value,precision).valueOf(); - }); - TimeSpan.prototype.adjacentOrAfter = toPredicate(function(value,precision) { - var ends; - if(value.constructor===TimeSpan || value instanceof TimeSpan) { - ends = new Time(value.ends,precision); - } else { - ends = new Time(value,precision); - } - return new Time(this.starts-new Duration(1,precision),precision).valueOf() >= ends.valueOf(); - }); - TimeSpan.prototype.after = toPredicate(function(value,precision) { - var ends; - if(value.constructor===TimeSpan || value instanceof TimeSpan) { - ends = new Time(value.ends,precision); - } else { - ends = new Time(value,precision); - } - return new Time(this.starts-new Duration(1,precision),precision).valueOf() > ends.valueOf(); - }); - TimeSpan.prototype.adjacentAfter = toPredicate(function(value,precision) { - var ends; - if(value.constructor===TimeSpan || value instanceof TimeSpan) { - ends = new Time(value.ends,precision); - } else { - ends = new Time(value,precision); - } - return new Time(this.starts-new Duration(1,precision),precision).valueOf() == ends.valueOf(); - }); - TimeSpan.prototype.adjacent = toPredicate(function(value,precision) { - if(this.adjacentBefore(value,precision)) { - return -1; - } - if(this.adjacentAfter(value,precision)) { - return 1; - } - return 0; - }); - Object.defineProperty(constructor.prototype,"joqularMatch",{enumerable:false,value:function(pattern,aliases,scope) { - return joqularMatch.call(this,new MatchPattern(pattern,true),aliases,scope); - }}); - Object.defineProperty(constructor.prototype,"instanceof",{enumerable:false,configurable:true,writable:true,value:toPredicate(function(constructor) { - return this instanceof constructor; - })}); - Object.defineProperty(constructor.prototype,"eq",{enumerable:false,configurable:true,writable:true,value:toPredicate(function(value) { - // first clause handles an object or primitve and value===null or value===undefined - // second clause handles everything else because primitives and Objects will return themselves with .valueOf() - // array and other types of objects may need to override eq - return this.valueOf() === value || - (value!=null && this.valueOf() === value.valueOf()); - })}); - Object.defineProperty(constructor.prototype,"neq",{enumerable:false,configurable:true,writable:true,value:toPredicate(function(value) { - return !this.eq(value); - })}); - if(config.enhancePrimitives) { - [Number,String,Boolean].forEach(function(primitive) { - primitive.prototype.joqularMatch || (primitive.prototype.joqularMatch = constructor.prototype.joqularMatch); - (primitive.prototype.lt = function(value) { - return this.valueOf() < value || this.valueOf() < value.valueOf(); - }).predicate=true; - (primitive.prototype.lte = function(value) { - return this.valueOf() <= value || this.valueOf() <= value.valueOf(); - }).predicate=true; - (primitive.prototype.eq = function(value) { - value = toObject(value); - return this === value || (value!==undefined && this.valueOf() === value.valueOf()); - }).predicate=true; - (primitive.prototype.neq = function(value) { - return !this.eq(value); - }).predicate=true; - (primitive.prototype.gte = function(value) { - return this.valueOf() >= value || this.valueOf() >= value.valueOf(); - }).predicate=true; - (primitive.prototype.gt = function(value) { - return this.valueOf() > value || this.valueOf() > value.valueOf(); - }).predicate=true; - (primitive.prototype["in"] = function(value) { - return value && value.contains && value.contains(this); - }).predicate=true; - (primitive.prototype.nin = function(value) { - return !value || !value.contains || !value.contains(this); - }).predicate=true; - primitive.prototype.between = toPredicate(function(bound1,bound2) { - return (this.valueOf() >= bound1 && this.valueOf() <= bound2) || (this.valueOf() >= bound2 && this.valueOf() <= bound1); - }); - primitive.prototype.outside = toPredicate(function(bound1,bound2) { - return !this.between(bound1,bound2); - }); - }); - } - String.prototype.echoes = toPredicate(function(value) { - return soundex(this)===soundex(value); - }); - String.prototype.soundex = String.prototype.echoes; - Object.defineProperty(String.prototype,"match",{enumerable:true,configurable:true,writable:true,value:String.prototype.match}); - String.prototype.match.predicate = true; - if(config.enhanceDate) { - Date.prototype.joqularMatch || (Date.prototype.joqularMatch = constructor.prototype.joqularMatch); - Object.defineProperty(Date.prototype,"time",{enumerable:true,configurable:false,set:function(time) { this.setTime(time); },get:function() { return this.getTime(); }}); - Object.defineProperty(Date.prototype,"year",{enumerable:true,configurable:false,set:function() { return;},get:function() { return this.getFullYear(); }}); - Object.defineProperty(Date.prototype,"month",{enumerable:true,configurable:false,set:function() { return;},get:function() { return this.getMonth()+1; }}); - Object.defineProperty(Date.prototype,"dayOfMonth",{enumerable:true,configurable:false,set:function() { return;},get:function() { return this.getDate(); }}); - Object.defineProperty(Date.prototype,"hours",{enumerable:true,configurable:false,set:function() { return;},get:function() { return this.getHours(); }}); - Object.defineProperty(Date.prototype,"minutes",{enumerable:true,configurable:false,set:function() { return;},get:function() { return this.getMinutes(); }}); - Object.defineProperty(Date.prototype,"seconds",{enumerable:true,configurable:false,set:function() { return;},get:function() { return this.getSeconds(); }}); - Object.defineProperty(Date.prototype,"milliseconds",{enumerable:true,configurable:false,set:function() { return;},get:function() { return this.getMilliseconds(); }}); - Object.defineProperty(Date.prototype,"dayOfWeek",{enumerable:true,configurable:false,set:function() { return;},get:function() { return this.getDay()+1; }}); - - Date.prototype.lt = toPredicate(function(value,precision) { - if(value instanceof TimeSpan) { - return value.after(this,precision); - } - return new Time(this,precision) < new Time(value,precision); - }); - Date.prototype.lte = toPredicate(function(value,precision) { - if(value instanceof TimeSpan) { - return value.adjacentOrAfter(this,precision); - } - return new Time(this,precision) <= new Time(value,precision); - }); - Date.prototype.eq = toPredicate(function(value,precision) { - if(value===this) { - return true; - } - if(value instanceof Date && this.time===value.time) { - return true; - } - if(value instanceof TimeSpan) { - return value.coincident(this,precision); - } - return new Time(this,precision).valueOf() == new Time(value,precision).valueOf(); - }); - Date.prototype.neq = toPredicate(function(value,precision) { - return new Time(this,precision).valueOf() !== new Time(value,precision).valueOf(); - }); - Date.prototype.gte = toPredicate(function(value,precision) { - if(value instanceof TimeSpan) { - return value.adjacentOrBefore(this,precision); - } - return new Time(this,precision).valueOf() >= new Time(value,precision).valueOf(); - }); - Date.prototype.gt = toPredicate(function(value,precision) { - if(value instanceof TimeSpan) { - return value.adjacentOrBefore(this,precision); - } - return new Time(this,precision).valueOf() >= new Time(value,precision).valueOf(); - }); - Date.prototype.before = Date.prototype.lt; - Date.prototype.adjacentOrBefore = Date.prototype.lte; - Date.prototype.after = Date.prototype.gt; - Date.prototype.adjacentOrAfter = Date.prototype.gte; - Date.prototype.coincident = toPredicate(function(value,precision) { - if(value instanceof TimeSpan) { - var d = new TimeSpan(this,this); - return d.coincident(value,precision); - } - return this.eq(value,precision); - }); - Date.prototype.disjoint = toPredicate(function(value,precision) { - if(value instanceof TimeSpan) { - var d = new TimeSpan(this,this); - return d.disjoint(value,precision); - } - return this.neq(value,precision); - }); - Date.prototype.intersects = toPredicate(function(value,precision) { - if(value instanceof TimeSpan) { - var d = new TimeSpan(this,this); - return d.intersects(value,precision); - } - return this.eq(value,precision); - }); - } - if(config.enhanceArray) { - Array.prototype.joqularMatch || (Array.prototype.joqularMatch = constructor.prototype.joqularMatch); - Array.prototype.count = toProvider(function(type) { - return (!type ? this.length : this.filter(function(item) { return item && typeof(item.valueOf())===type; }).length); - }); - Array.prototype.avg = toProvider(function(ignoreEnds) { - var sum = 0; - var copy = this.filter(function(item) { return item!=null && typeof(item.valueOf())==="number" && !isNaN(item.valueOf()); }).sort(function(a,b) { return a - b;}); - if(ignoreEnds && copy.length>2) { - copy.shift(); - copy.pop(); - } - for(var i=0;i2) { - arr.shift(); - arr.pop(); - } - for(var i=0;i 1) - { - var mean = sum / len; - for(var i=0;i2) { - copy.shift(); - copy.pop(); - } - for(var i=0;i2) i++; - return copy[i]; - }); - Array.prototype.max = toProvider(function(type,ignoreEnds) { - type || (type="number"); - var copy = this.filter(function(item) { return item!=null && typeof(item.valueOf())===type && (!type==="number" || !isNaN(item.valueOf())); }); - if(type==="number") { - copy.sort(function(a,b) { return a.valueOf() - b.valueOf();}); - } else { - copy.sort(); - } - var i = copy.length-1; - if(ignoreEnds && copy.length>2) i--; - return copy[i]; - }); - Array.prototype.bsearch = function(value,sorter) { - var me = this; - if(sorter) { - me = this.slice(0).sort(sorter); - } - return binarySearch(me,value); - }; - Array.prototype.eq = toPredicate(function(value) { - if(this===value) { return true; } - if(!(value instanceof Array) || this.length!==value.length) { - return false; - } - return this.every(function(item,i) { - var v = value[i]; - if(item===v) { - return true; - } - if(item instanceof constructor) { - return item.eq(v); - } - }); - }); - Array.prototype.neq = toPredicate(function(value) { - return !this.eq(value); - }); - Array.prototype.intersects = toPredicate(function(value) { - if(value instanceof Set) { - value = Set.toArray() - } - var result = intersection(this,value); - return result && result.length>0; - }); - Array.prototype.disjoint = toPredicate(function(value) { - return !this.intersects(value); - }); - Array.prototype.coincident = toPredicate(function(value) { - return this.count() === value.count() && - this.every(function(item) { - return value.contains(item); - }); - }); - Array.prototype.contains = toPredicate(function(value) { - return this.some(function(item) { - if(item===value || - (item!=null && item.valueOf()===value) || - (value!=null && item===value.valueOf()) || - (item!=null && value!=null && item.valueOf()===value.valueOf())) { - return true; - } - if(typeof(item.eq)==="function") { - return item.eq(value); - } - return false; - }); - }); - Array.prototype.includes = Array.prototype.contains; - Array.prototype.excludes = toPredicate(function(value) { - return !this.includes(value); - }); - } - if(config.enhanceSet) { - Set.prototype.joqularMatch || (Set.prototype.joqularMatch = constructor.prototype.joqularMatch); - Set.prototype.count = function() { - return this.size; - }; - Set.prototype.toArray = function() { - var array = []; - this.forEach(function(item) { - array.push(item); - }) - return array; - }; - Set.prototype.every = toPredicate(function(f) { - var array = this.toArray(); - return array.every(f) - }); - Set.prototype.some = toPredicate(function(f) { - var array = this.toArray(); - return array.some(f) - }); - Set.prototype.indexOf = function(value) { - var array = this.toArray(); - return array.indexOf(value); - }; - Set.prototype.contains = toPredicate(function(value) { - return (!value && this.has(value)) || this.has(value.valueOf()); - }); - Set.prototype.eq = toPredicate(function(value) { - var me = this; - if(this===value) { return true; } - if(!(value instanceof Set) || this.size!==value.size) { - return false; - } - return me.every(function(item) { - return value.has(item); - }); - }); - Set.prototype.neq = toPredicate(function(value) { - return !this.eq(value); - }); - Set.prototype.intersects = toPredicate(function(value) { - if(!value || typeof(value.contains)!=="function") { - return false; - } - return this.some(function(item) { - return value.contains(item); - }); - }); - Set.prototype.disjoint = toPredicate(function(value) { - return !this.intersects(value); - }); - Set.prototype.coincident = toPredicate(function(value) { - return typeof(value.count)==="function" && - this.count() === value.count() && - this.every(function(item) { - return value.contains(item); - }); - }); - Set.prototype.includes = Set.prototype.contains; - Set.prototype.excludes = toPredicate(function(value) { - return !this.includes(value); - }); - } - JOQULAR.createIndex = createIndex; - JOQULAR.insert = function() { - return new Insert(); - } - JOQULAR.select = function(projection) { - return new Select(projection); - } - JOQULAR.TimeSpan = TimeSpan; - JOQULAR.Time = Time; - JOQULAR.Duration = Duration; - return constructor; - } - } - exports.JOQULAR = JOQULAR; -})("undefined"!=typeof exports&&"undefined"!=typeof global?global:window); \ No newline at end of file diff --git a/package.json b/package.json index 50a6c61..650884c 100644 --- a/package.json +++ b/package.json @@ -1,37 +1,34 @@ -{ - "name": "joqular", - "version":"1.02.01", - "description": "(JOQULAR - JavaScript Object Query Language Representation) A high speed in-memory, isomorphic, JavaScript database wih serializable queries.", - "main": "joqular.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "repository": { - "type": "git", - "url": "https://github.com/anywhichway/joqular.git" - }, - "keywords": [ - "node.js", - "NodeJS", - "Pouch", - "Mongo", - "Taffy", - "Datastore", - "Forerunner", - "Indexed", - "WebDB", - "WebSQL", - "database", - "SQL", - "NoSQL" - ], - "author": "Simon Y. Blackwell (http://www.github.com/anywhichway)", - "license": "GPL3", - "bugs": { - "url": "https://github.com/anywhichway/joqular/issues" - }, - "dependencies": { - - }, - "homepage": "https://github.com/anywhichway/joqular" -} +{ + "name": "joqular", + "version": "2.0.0b", + "description": "(JOQULAR - JavaScript Object Query Language Representation) For JSON data matching, transformation, and extraction", + "main": "index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "repository": { + "type": "git", + "url": "https://github.com/anywhichway/joqular.git" + }, + "keywords": [ + "database", + "SQL", + "NoSQL" + ], + "author": "Simon Y. Blackwell (http://www.github.com/anywhichway)", + "license": "MIT", + "bugs": { + "url": "https://github.com/anywhichway/joqular/issues" + }, + "devDependencies": { + "benchmark": "^2.1.3", + "blanket": "^1.2.3", + "chai": "^3.4.1", + "codacy-coverage": "^2.0.0", + "codeclimate-test-reporter": "^0.2.0", + "istanbul": "^0.4.2", + "mocha": "^2.3.4" + }, + "dependencies": {}, + "homepage": "https://github.com/anywhichway/joqular" +} diff --git a/test/benchmark.html b/test/benchmark.html deleted file mode 100644 index e867e22..0000000 --- a/test/benchmark.html +++ /dev/null @@ -1,297 +0,0 @@ - - - - - - - - - - - - -Open the Developer Console and Reload Page To See Benchmark Results - - - - \ No newline at end of file diff --git a/test/es6-collections.min.js b/test/es6-collections.min.js deleted file mode 100644 index 08c2667..0000000 --- a/test/es6-collections.min.js +++ /dev/null @@ -1,5 +0,0 @@ -(function(e){function f(a,c){function b(a){if(!this||this.constructor!==b)return new b(a);this._keys=[];this._values=[];this._itp=[];this.objectOnly=c;a&&v.call(this,a)}c||w(a,"size",{get:x});a.constructor=b;b.prototype=a;return b}function v(a){this.add?a.forEach(this.add,this):a.forEach(function(a){this.set(a[0],a[1])},this)}function d(a){this.has(a)&&(this._keys.splice(b,1),this._values.splice(b,1),this._itp.forEach(function(a){b=i&&(e=Math.floor((i+j)/2),h!==e);)f=b[e],void 0!==f&&(g=d(this,a,c,f),g>0&&(i=e+1),0>g&&(j=e-1)),h=e;return g>0?e+1:e},e.prototype._sortFunc=function(a,b,c,d){var e,f,g,h=c.split(".:."),i=d.split(".:."),j=a._keyArr,k=j.length;for(e=0;k>e;e++)if(f=j[e],g=typeof b[f.key],"number"===g&&(h[e]=Number(h[e]),i[e]=Number(i[e])),h[e]!==i[e]){if(1===f.dir)return a.sortAsc(h[e],i[e]);if(-1===f.dir)return a.sortDesc(h[e],i[e])}},e.prototype.insert=function(a){var b,c;return b=this.documentKey(a),c=this._data.indexOf(b),-1===c?(c=this.qs(a,this._data,b,this._sortFunc),this._data.splice(c,0,b)):this._data.splice(c,0,b),this._objLookup[a[this._primaryKey]]=b,this._count++,c},e.prototype.remove=function(a){var b,c;return b=this._objLookup[a[this._primaryKey]],b?(c=this._data.indexOf(b),c>-1?(this._data.splice(c,1),delete this._objLookup[a[this._primaryKey]],this._count--,!0):!1):!1},e.prototype.index=function(a){var b,c;return b=this.documentKey(a),c=this._data.indexOf(b),-1===c&&(c=this.qs(a,this._data,b,this._sortFunc)),c},e.prototype.documentKey=function(a){var b,c,d="",e=this._keyArr,f=e.length;for(b=0;f>b;b++)c=e[b],d&&(d+=".:."),d+=a[c.key];return d+=".:."+a[this._primaryKey]},e.prototype.count=function(){return this._count},d.finishModule("ActiveBucket"),b.exports=e},{"./Path":26,"./Shared":30}],4:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k;d=a("./Shared");var l=function(a){this.init.apply(this,arguments)};l.prototype.init=function(a){this._primaryKey="_id",this._primaryIndex=new g("primary"),this._primaryCrc=new g("primaryCrc"),this._crcLookup=new g("crcLookup"),this._name=a,this._data=[],this._groups=[],this._metrics=new f,this._deferQueue={insert:[],update:[],remove:[],upsert:[]},this._deferThreshold={insert:100,update:100,remove:100,upsert:100},this._deferTime={insert:1,update:1,remove:1,upsert:1},this._subsetOf(this)},d.addModule("Collection",l),d.mixin(l.prototype,"Mixin.Common"),d.mixin(l.prototype,"Mixin.Events"),d.mixin(l.prototype,"Mixin.ChainReactor"),d.mixin(l.prototype,"Mixin.CRUD"),d.mixin(l.prototype,"Mixin.Constants"),d.mixin(l.prototype,"Mixin.Triggers"),d.mixin(l.prototype,"Mixin.Sorting"),d.mixin(l.prototype,"Mixin.Matching"),f=a("./Metrics"),g=a("./KeyValueStore"),h=a("./Path"),i=a("./IndexHashMap"),j=a("./IndexBinaryTree"),k=a("./Crc"),e=d.modules.Core,l.prototype.crc=k,d.synthesize(l.prototype,"state"),d.synthesize(l.prototype,"name"),l.prototype.data=function(){return this._data},l.prototype.drop=function(){if("dropped"===this._state)return!0;if(this._db&&this._db._collection&&this._name){if(this.debug()&&console.log("Dropping collection "+this._name),this._state="dropped",this.emit("drop",this),delete this._db._collection[this._name],this._groups&&this._groups.length){var a,b=[];for(a=0;af)return this._deferQueue.upsert=e.concat(a),this.processQueue("upsert",b),{};for(g=[],d=0;dj;j++)this._updateSplicePush(a[o],A+j,b[o].$each[j]);else if(b[o].$each instanceof Array)for(k=b[o].$each.length,j=0;k>j;j++)this._updatePush(a[o],b[o].$each[j]);else this._updatePush(a[o],b[o]);q=!0;break;case"$pull":if(a[o]instanceof Array){for(i=[],j=0;j0)for(;k--;){for(A=0;Ak)break}}break;case"$addToSet":if(void 0===a[o]&&this._updateProperty(a,o,[]),!(a[o]instanceof Array))throw'ForerunnerDB.Collection "'+this.name()+'": Cannot addToSet on a key that is not an array! ('+p+")";var s,t,u,v,w=a[o],x=w.length,y=!0,z=d&&d.$addToSet;for(b[o].$key?(u=!1,v=new h(b[o].$key),t=v.value(b[o])[0],delete b[o].$key):z&&z.key?(u=!1,v=new h(z.key),t=v.value(b[o])[0]):(t=JSON.stringify(b[o]),u=!0),s=0;x>s;s++)if(u){if(JSON.stringify(w[s])===t){y=!1;break}}else if(t===v.value(w[s])[0]){y=!1;break}y&&(this._updatePush(a[o],b[o]),q=!0);break;case"$splicePush":if(void 0===a[o]&&this._updateProperty(a,o,[]),!(a[o]instanceof Array))throw'ForerunnerDB.Collection "'+this.name()+'": Cannot splicePush with a key that is not an array! ('+o+")";var A=b.$index;if(void 0===A)throw'ForerunnerDB.Collection "'+this.name()+'": Cannot splicePush without a $index integer value!';delete b.$index,A>a[o].length&&(A=a[o].length),this._updateSplicePush(a[o],A,b[o]),q=!0;break;case"$move":if(!(a[o]instanceof Array))throw'ForerunnerDB.Collection "'+this.name()+'": Cannot move on a key that is not an array! ('+o+")";for(j=0;jb?a.splice(b,0,c):a.push(c)},l.prototype._updatePush=function(a,b){a.push(b)},l.prototype._updatePull=function(a,b){a.splice(b,1)},l.prototype._updateMultiply=function(a,b,c){a[b]*=c},l.prototype._updateRename=function(a,b,c){a[c]=a[b],delete a[b]},l.prototype._updateUnset=function(a,b){delete a[b]},l.prototype._updatePop=function(a,b){var c=!1;return a.length>0&&(1===b?(a.pop(),c=!0):-1===b&&(a.shift(),c=!0)),c},l.prototype.remove=function(a,b,c){var d,e,f,g,h,i,j,k,l=this;if(a instanceof Array){for(g=[],f=0;fd?c.splice(0,d):c.splice(0,c.length),this[a](f)),setTimeout(function(){g.processQueue(a,b)},e)}else b&&b()},l.prototype.insert=function(a,b,c){return"function"==typeof b?(c=b,b=this._data.length):void 0===b&&(b=this._data.length),a=this.transformIn(a),this._insertHandle(a,b,c)},l.prototype._insertHandle=function(a,b,c){var d,e,f=this._deferQueue.insert,g=this._deferThreshold.insert,h=(this._deferTime.insert,[]),i=[];if(a instanceof Array){if(a.length>g)return this._deferQueue.insert=f.concat(a),void this.processQueue("insert",c);for(e=0;eg._data.length&&(b=g._data.length),g._dataInsertAtIndex(b,a)},c)return"Index violation in index: "+c;if(g.willTrigger(g.TYPE_INSERT,g.PHASE_BEFORE)||g.willTrigger(g.TYPE_INSERT,g.PHASE_AFTER)){if(d={type:"insert"},g.processTrigger(d,g.TYPE_INSERT,g.PHASE_BEFORE,{},a)===!1)return!1;e(a),g.willTrigger(g.TYPE_INSERT,g.PHASE_AFTER)&&(f=g.decouple(a),g.processTrigger(d,g.TYPE_INSERT,g.PHASE_AFTER,{},f))}else e(a);return!0}return"No document passed to insert"},l.prototype._dataInsertAtIndex=function(a,b){this._data.splice(a,0,b)},l.prototype._dataRemoveAtIndex=function(a){this._data.splice(a,1)},l.prototype._dataReplace=function(a){for(;this._data.length;)this._data.pop();this._data=this._data.concat(a)},l.prototype._insertIntoIndexes=function(a){var b,c,d=this._indexByName,e=JSON.stringify(a);c=this._primaryIndex.uniqueSet(a[this._primaryKey],a),this._primaryCrc.uniqueSet(a[this._primaryKey],e),this._crcLookup.uniqueSet(e,a);for(b in d)d.hasOwnProperty(b)&&d[b].insert(a);return c},l.prototype._removeFromIndexes=function(a){var b,c=this._indexByName,d=JSON.stringify(a);this._primaryIndex.unSet(a[this._primaryKey]),this._primaryCrc.unSet(a[this._primaryKey]),this._crcLookup.unSet(d);for(b in c)c.hasOwnProperty(b)&&c[b].remove(a)},l.prototype._rebuildIndexes=function(){var a,b=this._indexByName;for(a in b)b.hasOwnProperty(a)&&b[a].rebuild()},l.prototype.indexOfDocById=function(a){return this._data.indexOf(this._primaryIndex.get(a[this._primaryKey]))},l.prototype.subset=function(a,b){var c=this.find(a,b);return(new l)._subsetOf(this).primaryKey(this._primaryKey).setData(c)},l.prototype.subsetOf=function(){return this.__subsetOf},l.prototype._subsetOf=function(a){return this.__subsetOf=a,this},l.prototype.distinct=function(a,b,c){var d,e,f=this.find(b,c),g=new h(a),i={},j=[];for(e=0;ec;c++)d=JSON.stringify(e[c]),d.indexOf(a)>-1&&g.insert(e[c]);return g.find({},b)}return this.find(a,b)},l.prototype.explain=function(a,b){var c=this.find(a,b);return c.__fdbOp._data},l.prototype.options=function(a){return a=a||{},a.$decouple=void 0!==a.$decouple?a.$decouple:!0,a.$explain=void 0!==a.$explain?a.$explain:!1,a},l.prototype.find=function(a,b){a=a||{},b=this.options(b);var c,d,e,f,g,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w=this._metrics.create("find"),x=this,y=!0,z={},A=[],B={},C=function(b){return x._match(b,a,"and",B)};if(w.start(),a){if(w.time("analyseQuery"),c=this._analyseQuery(a,b,w),w.time("analyseQuery"),w.data("analysis",c),c.hasJoin&&c.queriesJoin){for(w.time("joinReferences"),g=0;gb.limit&&(e.length=b.limit,w.data("limit",b.limit)),b.$decouple&&(w.time("decouple"),e=this.decouple(e),w.time("decouple"),w.data("flag.decouple",!0)),b.$join){for(f=0;f-1&&e.splice(u,1);w.time("removalQueue")}if(b.transform){for(w.time("transform"),v=0;v0){b=this._sort(f,b),d=this.bucket(f.___fdbKey,b);for(e in d)d.hasOwnProperty(e)&&(c=[].concat(a),g=g.concat(this._bucketSort(c,d[e])));return g}return this._sort(f,b)},l.prototype._sort=function(a,b){var c,d=this,e=new h,f=e.parse(a,!0)[0];if(e.path(f.path),1===f.value)c=function(a,b){var c=e.value(a)[0],f=e.value(b)[0];return d.sortAsc(c,f)};else{if(-1!==f.value)throw'ForerunnerDB.Collection "'+this.name()+'": $orderBy clause has invalid direction: '+f.value+", accepted values are 1 or -1 for ascending or descending!";c=function(a,b){var c=e.value(a)[0],f=e.value(b)[0];return d.sortDesc(c,f)}}return b.sort(c)},l.prototype.bucket=function(a,b){var c,d={};for(c=0;c0&&(l=j.lookup(a,b),p.indexMatch.push({lookup:l,keyData:i,index:j})),c.time("checkIndexMatch: "+k),i.score===n))break;c.time("checkIndexes"),p.indexMatch.length>1&&(c.time("findOptimalIndex"),p.indexMatch.sort(function(a,b){return a.keyData.score>b.keyData.score?-1:a.keyData.scoree;e++)if(f=i.value(j[e])[0]){if(l.setData(f),g=l.find(c,d),d.returnFirst&&g.length)return g[0];m.subDocs.push(g),m.subDocTotal+=g.length,m.pathFound=!0}return l.drop(),d.noStats?m.subDocs:(m.pathFound||(m.err="No objects found in the parent documents with a matching path of: "+b),m)},l.prototype.insertIndexViolation=function(a){var b,c,d,e=this._indexByName;if(this._primaryIndex.get(a[this._primaryKey]))b=this._primaryIndex;else for(c in e)if(e.hasOwnProperty(c)&&(d=e[c],d.unique()&&d.violation(a))){b=d;break}return b?b.name():!1},l.prototype.ensureIndex=function(a,b){this._indexByName=this._indexByName||{},this._indexById=this._indexById||{};var c,d={start:(new Date).getTime()};if(b)switch(b.type){case"hashed":c=new i(a,b,this);break;case"btree":c=new j(a,b,this);break;default:c=new i(a,b,this)}else c=new i(a,b,this);return this._indexByName[c.name()]?{err:"Index with that name already exists"}:this._indexById[c.id()]?{err:"Index with those keys already exists"}:(c.rebuild(),this._indexByName[c.name()]=c,this._indexById[c.id()]=c,d.end=(new Date).getTime(),d.total=d.end-d.start,this._lastOp={type:"ensureIndex",stats:{time:d}},{index:c,id:c.id(),name:c.name(),state:c.state()})},l.prototype.index=function(a){return this._indexByName?this._indexByName[a]:void 0},l.prototype.lastOp=function(){return this._metrics.list()},l.prototype.diff=function(a){var b,c,d,e,f={insert:[],update:[],remove:[]},g=this.primaryKey();if(g!==a.primaryKey())throw'ForerunnerDB.Collection "'+this.name()+'": Collection diffing requires that both collections have the same primary key!';for(b=a._data;b&&!(b instanceof Array);)a=b,b=a._data;for(e=b.length,c=0;e>c;c++)d=b[c],this._primaryIndex.get(d[g])?this._primaryCrc.get(d[g])!==a._primaryCrc.get(d[g])&&f.update.push(d):f.insert.push(d);for(b=this._data,e=b.length,c=0;e>c;c++)d=b[c],a._primaryIndex.get(d[g])||f.remove.push(d);return f},e.prototype.collection=function(a,b){if(a)return this._collection[a]||this.debug()&&console.log("Creating collection "+a),this._collection[a]=this._collection[a]||new l(a).db(this),void 0!==b&&this._collection[a].primaryKey(b),this._collection[a];throw'ForerunnerDB.Core "'+this.name()+'": Cannot get collection with undefined name!'},e.prototype.collectionExists=function(a){return Boolean(this._collection[a])},e.prototype.collections=function(a){var b,c=[];a&&(a instanceof RegExp||(a=new RegExp(a)));for(b in this._collection)this._collection.hasOwnProperty(b)&&(a?a.exec(b)&&c.push({name:b,count:this._collection[b].count()}):c.push({name:b,count:this._collection[b].count()}));return c},d.finishModule("Collection"),b.exports=l},{"./Crc":7,"./IndexBinaryTree":11,"./IndexHashMap":12,"./KeyValueStore":13,"./Metrics":14,"./Path":26,"./Shared":30}],5:[function(a,b,c){"use strict";var d,e,f,g;d=a("./Shared");var h=function(){this.init.apply(this,arguments)};h.prototype.init=function(a){this._name=a,this._data=new g("__FDB__cg_data_"+this._name),this._collections=[],this._view=[]},d.addModule("CollectionGroup",h),d.mixin(h.prototype,"Mixin.Common"),d.mixin(h.prototype,"Mixin.ChainReactor"),d.mixin(h.prototype,"Mixin.Constants"),d.mixin(h.prototype,"Mixin.Triggers"),g=a("./Collection"),e=d.modules.Core,f=d.modules.Core.prototype.init,h.prototype.on=function(){this._data.on.apply(this._data,arguments)},h.prototype.off=function(){this._data.off.apply(this._data,arguments)},h.prototype.emit=function(){this._data.emit.apply(this._data,arguments)},h.prototype.primaryKey=function(a){return void 0!==a?(this._primaryKey=a,this):this._primaryKey},d.synthesize(h.prototype,"state"),d.synthesize(h.prototype,"db"),h.prototype.addCollection=function(a){if(a&&-1===this._collections.indexOf(a)){if(this._collections.length){if(this._primaryKey!==a.primaryKey())throw'ForerunnerDB.CollectionGroup "'+this.name()+'": All collections in a collection group must have the same primary key!'}else this.primaryKey(a.primaryKey());this._collections.push(a),a._groups.push(this),a.chain(this),this._data.insert(a.find())}return this},h.prototype.removeCollection=function(a){if(a){var b,c=this._collections.indexOf(a);-1!==c&&(a.unChain(this),this._collections.splice(c,1),b=a._groups.indexOf(this),-1!==b&&a._groups.splice(b,1)),0===this._collections.length&&delete this._primaryKey}return this},h.prototype._chainHandler=function(a){switch(a.type){case"setData":a.data=this.decouple(a.data),this._data.remove(a.options.oldData),this._data.insert(a.data);break;case"insert":a.data=this.decouple(a.data),this._data.insert(a.data);break;case"update":this._data.update(a.data.query,a.data.update,a.options);break;case"remove":this._data.remove(a.data.query,a.options)}},h.prototype.insert=function(){this._collectionsRun("insert",arguments)},h.prototype.update=function(){this._collectionsRun("update",arguments)},h.prototype.updateById=function(){this._collectionsRun("updateById",arguments)},h.prototype.remove=function(){this._collectionsRun("remove",arguments)},h.prototype._collectionsRun=function(a,b){for(var c=0;c-1&&c.splice(d,1)}return this},i.prototype.emit=function(a,b){if(this._listeners=this._listeners||{},a in this._listeners){var c,d=this._listeners[a],e=d.length;for(c=0;e>c;c++)d[c].apply(this,Array.prototype.slice.call(arguments,1))}return this},i.prototype.peek=function(a){var b,c,d=[],e=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],d=d.concat("string"===e?c.peek(a):c.find(a)));return d},i.prototype.peekCat=function(a){var b,c,d,e={},f=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],"string"===f?(d=c.peek(a),d&&d.length&&(e[c.name()]=d)):(d=c.find(a),d&&d.length&&(e[c.name()]=d)));return e},i.prototype.drop=function(a){if("dropped"!==this._state){var b,c=this.collections(),d=c.length,e=0,f=function(){e++,e===d&&a&&a()};for(this._state="dropped",b=0;d>b;b++)this.collection(c[b].name).drop(f),delete this._collection[c[b].name];this.emit("drop",this)}return!0},b.exports=i},{"./Collection.js":4,"./Crc.js":7,"./Metrics.js":14,"./Overload":24,"./Shared":30}],7:[function(a,b,c){"use strict";var d=function(){var a,b,c,d=[];for(b=0;256>b;b++){for(a=b,c=0;8>c;c++)a=1&a?3988292384^a>>>1:a>>>1;d[b]=a}return d}();b.exports=function(a){var b,c=-1;for(b=0;b>>8^d[255&(c^a.charCodeAt(b))];return(-1^c)>>>0}},{}],8:[function(a,b,c){"use strict";var d,e,f,g;d=a("./Shared"),function(){var c=function(){this.init.apply(this,arguments)};c.prototype.init=function(a){this._name=a,this._data={}},d.addModule("Document",c),d.mixin(c.prototype,"Mixin.Common"),d.mixin(c.prototype,"Mixin.Events"),d.mixin(c.prototype,"Mixin.ChainReactor"),d.mixin(c.prototype,"Mixin.Constants"),d.mixin(c.prototype,"Mixin.Triggers"),e=a("./Collection"),f=d.modules.Core,g=d.modules.Core.prototype.init,d.synthesize(c.prototype,"state"),d.synthesize(c.prototype,"db"),d.synthesize(c.prototype,"name"),c.prototype.setData=function(a){var b,c;if(a)if(a=this.decouple(a),this._linked){c={};for(b in this._data)"jQuery"!==b.substr(0,6)&&this._data.hasOwnProperty(b)&&void 0===a[b]&&(c[b]=1);a.$unset=c,this.updateObject(this._data,a,{})}else this._data=a;return this},c.prototype.update=function(a,b,c){this.updateObject(this._data,b,a,c)},c.prototype.updateObject=e.prototype.updateObject,c.prototype._isPositionalKey=function(a){return".$"===a.substr(a.length-2,2)},c.prototype._updateProperty=function(a,b,c){this._linked?(window.jQuery.observable(a).setProperty(b,c),this.debug()&&console.log('ForerunnerDB.Document: Setting data-bound document property "'+b+'" for collection "'+this.name()+'"')):(a[b]=c,this.debug()&&console.log('ForerunnerDB.Document: Setting non-data-bound document property "'+b+'" for collection "'+this.name()+'"'))},c.prototype._updateIncrement=function(a,b,c){this._linked?window.jQuery.observable(a).setProperty(b,a[b]+c):a[b]+=c},c.prototype._updateSpliceMove=function(a,b,c){this._linked?(window.jQuery.observable(a).move(b,c),this.debug()&&console.log('ForerunnerDB.Document: Moving data-bound document array index from "'+b+'" to "'+c+'" for collection "'+this.name()+'"')):(a.splice(c,0,a.splice(b,1)[0]),this.debug()&&console.log('ForerunnerDB.Document: Moving non-data-bound document array index from "'+b+'" to "'+c+'" for collection "'+this.name()+'"'))},c.prototype._updateSplicePush=function(a,b,c){a.length>b?this._linked?window.jQuery.observable(a).insert(b,c):a.splice(b,0,c):this._linked?window.jQuery.observable(a).insert(c):a.push(c)},c.prototype._updatePush=function(a,b){this._linked?window.jQuery.observable(a).insert(b):a.push(b)},c.prototype._updatePull=function(a,b){this._linked?window.jQuery.observable(a).remove(b):a.splice(b,1)},c.prototype._updateMultiply=function(a,b,c){this._linked?window.jQuery.observable(a).setProperty(b,a[b]*c):a[b]*=c},c.prototype._updateRename=function(a,b,c){var d=a[b];this._linked?(window.jQuery.observable(a).setProperty(c,d),window.jQuery.observable(a).removeProperty(b)):(a[c]=d,delete a[b])},c.prototype._updateUnset=function(a,b){this._linked?window.jQuery.observable(a).removeProperty(b):delete a[b]},c.prototype._updatePop=function(a,b){var c,d=!1;return a.length>0&&(this._linked?(1===b?c=a.length-1:-1===b&&(c=0),c>-1&&(window.jQuery.observable(a).remove(c),d=!0)):1===b?(a.pop(),d=!0):-1===b&&(a.shift(),d=!0)),d},c.prototype.drop=function(){return"dropped"===this._state?!0:this._db&&this._name&&this._db&&this._db._document&&this._db._document[this._name]?(this._state="dropped",delete this._db._document[this._name],delete this._data,this.emit("drop",this),!0):!1},f.prototype.init=function(){g.apply(this,arguments)},f.prototype.document=function(a){return a?(this._document=this._document||{},this._document[a]=this._document[a]||new c(a).db(this),this._document[a]):this._document},f.prototype.documents=function(){var a,b=[];for(a in this._document)this._document.hasOwnProperty(a)&&b.push({name:a});return b},d.finishModule("Document"),b.exports=c}()},{"./Collection":4,"./Shared":30}],9:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k;d=a("./Shared");var l=function(a,b){this.init.apply(this,arguments)};l.prototype.init=function(a,b,c){var d=this;this._selector=a,this._template=b,this._options=c,this._debug={},this._id=this.objectId(),this._collectionDroppedWrap=function(){d._collectionDropped.apply(d,arguments)}},d.addModule("Grid",l),d.mixin(l.prototype,"Mixin.Common"),d.mixin(l.prototype,"Mixin.ChainReactor"),d.mixin(l.prototype,"Mixin.Constants"),d.mixin(l.prototype,"Mixin.Triggers"),d.mixin(l.prototype,"Mixin.Events"),f=a("./Collection"),g=a("./CollectionGroup"),h=a("./View"),k=a("./ReactorIO"),i=f.prototype.init,e=d.modules.Core,j=e.prototype.init,d.synthesize(l.prototype,"state"),d.synthesize(l.prototype,"name"),l.prototype.insert=function(){this._from.insert.apply(this._from,arguments)},l.prototype.update=function(){this._from.update.apply(this._from,arguments)},l.prototype.updateById=function(){this._from.updateById.apply(this._from,arguments)},l.prototype.remove=function(){this._from.remove.apply(this._from,arguments)},l.prototype.from=function(a){return void 0!==a&&(this._from&&(this._from.off("drop",this._collectionDroppedWrap),this._from._removeGrid(this)),"string"==typeof a&&(a=this._db.collection(a)),this._from=a,this.refresh()),this},l.prototype.db=function(a){return void 0!==a?(this._db=a,this):this._db},l.prototype._collectionDropped=function(a){a&&delete this._from},l.prototype.drop=function(){return"dropped"===this._state?!0:this._from?(this._from.unlink(this._selector,this.template()),this._from.off("drop",this._collectionDroppedWrap),this._from._removeGrid(this),(this.debug()||this._db&&this._db.debug())&&console.log("ForerunnerDB.Grid: Dropping grid "+this._selector),this._state="dropped",this._db&&this._selector&&delete this._db._grid[this._selector],this.emit("drop",this),delete this._selector,delete this._template,delete this._from,delete this._db,!0):!1},l.prototype.template=function(a){return void 0!==a?(this._template=a,this):this._template},l.prototype._sortGridClick=function(a){var b,c=window.jQuery(a.currentTarget).attr("data-grid-sort")||"",d=c.split(","),e={};for(b=0;b','",'",""],e=window.jQuery(f.join("")),d.html(e),j.link(e.find("ul"),{template:'{^{for options}}
  • {^{if active}} {{/if}}{{:'+g+"}}
  • {{/for}}"},{wrap:"options"}),b.on("click","#"+a._id+"_"+g+" ul.dropdown-menu li>a",function(b){b.preventDefault();var c={};c[g]=window.jQuery(this).attr("data-val"),a._from.queryAdd(c)})})}return this},f.prototype.grid=h.prototype.grid=function(a,b,c){if(this._db&&this._db._grid){if(this._db._grid[a])throw'ForerunnerDB.Collection/View "'+this.name()+'": Cannot create a grid using this collection/view because a grid with this name already exists: '+name;var d=new l(a,b,c).db(this._db).from(this);return this._grid=this._grid||[],this._grid.push(d),this._db._grid[a]=d,d}},f.prototype.unGrid=h.prototype.unGrid=function(a,b,c){if(this._db&&this._db._grid){if(this._db._grid[a]){var d=this._db._grid[a];return delete this._db._grid[a],d.drop()}throw'ForerunnerDB.Collection/View "'+this.name()+'": Cannot remove a grid using this collection/view because a grid with this name does not exist: '+name}},f.prototype._addGrid=g.prototype._addGrid=h.prototype._addGrid=function(a){return void 0!==a&&(this._grid=this._grid||[],this._grid.push(a)),this},f.prototype._removeGrid=g.prototype._removeGrid=h.prototype._removeGrid=function(a){if(void 0!==a&&this._grid){var b=this._grid.indexOf(a);b>-1&&this._grid.splice(b,1)}return this},e.prototype.init=function(){this._grid={},j.apply(this,arguments)},e.prototype.grid=function(a,b,c){return this._grid[a]||(this.debug()||this._db&&this._db.debug())&&console.log("Core.Grid: Creating grid "+a),this._grid[a]=this._grid[a]||new l(a,b,c).db(this),this._grid[a]},e.prototype.unGrid=function(a,b,c){return this._grid[a]||(this.debug()||this._db&&this._db.debug())&&console.log("Core.Grid: Creating grid "+a),this._grid[a]=this._grid[a]||new l(a,b,c).db(this),this._grid[a]},e.prototype.gridExists=function(a){return Boolean(this._grid[a])},e.prototype.grids=function(){var a,b=[];for(a in this._grid)this._grid.hasOwnProperty(a)&&b.push({name:a,count:this._grid[a].count()});return b},d.finishModule("Grid"),b.exports=l},{"./Collection":4,"./CollectionGroup":5,"./ReactorIO":28,"./Shared":30,"./View":32}],10:[function(a,b,c){"use strict";var d,e,f,g;d=a("./Shared"),g=a("./Overload");var h=function(a,b){this.init.apply(this,arguments)};h.prototype.init=function(a,b){if(this._options=b,this._selector=window.jQuery(this._options.selector),!this._selector[0])throw'ForerunnerDB.Highchart "'+a.name()+'": Chart target element does not exist via selector: '+this._options.selector;this._listeners={},this._collection=a,this._options.series=[],b.chartOptions=b.chartOptions||{},b.chartOptions.credits=!1;var c,d,e;switch(this._options.type){case"pie":this._selector.highcharts(this._options.chartOptions),this._chart=this._selector.highcharts(),c=this._collection.find(),d={allowPointSelect:!0,cursor:"pointer",dataLabels:{enabled:!0,format:"{point.name}: {y} ({point.percentage:.0f}%)",style:{color:window.Highcharts.theme&&window.Highcharts.theme.contrastTextColor||"black"}}},e=this.pieDataFromCollectionData(c,this._options.keyField,this._options.valField),window.jQuery.extend(d,this._options.seriesOptions),window.jQuery.extend(d,{name:this._options.seriesName,data:e}),this._chart.addSeries(d,!0,!0);break;case"line":case"area":case"column":case"bar":e=this.seriesDataFromCollectionData(this._options.seriesField,this._options.keyField,this._options.valField,this._options.orderBy),this._options.chartOptions.xAxis=e.xAxis,this._options.chartOptions.series=e.series,this._selector.highcharts(this._options.chartOptions),this._chart=this._selector.highcharts();break;default:throw'ForerunnerDB.Highchart "'+a.name()+'": Chart type specified is not currently supported by ForerunnerDB: '+this._options.type}this._hookEvents()},d.addModule("Highchart",h),e=d.modules.Collection,f=e.prototype.init,d.mixin(h.prototype,"Mixin.Events"),d.synthesize(h.prototype,"state"),h.prototype.pieDataFromCollectionData=function(a,b,c){var d,e=[];for(d=0;da;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},g.prototype.insert=function(a,b){var c,d,e=this._unique,f=this._itemKeyHash(a,this._keys);e&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a),d=this._btree.get(f),void 0===d&&(d=[],this._btree.put(f,d)),d.push(a),this._size++},g.prototype.remove=function(a,b){var c,d,e,f=this._unique,g=this._itemKeyHash(a,this._keys);f&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),d=this._btree.get(g),void 0!==d&&(e=d.indexOf(a),e>-1&&(1===d.length?this._btree.del(g):d.splice(e,1),this._size--))},g.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},g.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},g.prototype.lookup=function(a){return this._data[this._itemHash(a,this._keys)]||[]},g.prototype.match=function(a,b){var c,d=new e,f=d.parseArr(this._keys),g=d.parseArr(a),h=[],i=0;for(c=0;ca;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},f.prototype.insert=function(a,b){var c,d,e,f=this._unique;for(f&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a),d=this._itemHashArr(a,this._keys),e=0;e-1&&(d.splice(c,1),this._size--,this.pullFromCrossRef(b,d)),d.length||delete this._data[a]},f.prototype.pull=function(a){var b,c,d=a[this._collection.primaryKey()],e=this._crossRef[d],f=e.length;for(b=0;f>b;b++)c=e[b],this._pullFromArray(c,a);this._size--,delete this._crossRef[d]},f.prototype._pullFromArray=function(a,b){for(var c=a.length;c--;)a[c]===b&&a.splice(c,1)},f.prototype.pushToCrossRef=function(a,b){var c,d=a[this._collection.primaryKey()];this._crossRef[d]=this._crossRef[d]||[],c=this._crossRef[d],-1===c.indexOf(b)&&c.push(b)},f.prototype.pullFromCrossRef=function(a,b){var c=a[this._collection.primaryKey()];delete this._crossRef[c]},f.prototype.lookup=function(a){return this._data[this._itemHash(a,this._keys)]||[]},f.prototype.match=function(a,b){var c,d=new e,f=d.parseArr(this._keys),g=d.parseArr(a),h=[],i=0;for(c=0;cb;b++)d=this._data[f[b]],d&&e.push(d);return e}if(f instanceof RegExp){e=[];for(b in this._data)this._data.hasOwnProperty(b)&&f.test(b)&&e.push(this._data[b]);return e}if("object"!=typeof f)return d=this._data[f],void 0!==d?[d]:[];if(f.$ne){e=[];for(b in this._data)this._data.hasOwnProperty(b)&&b!==f.$ne&&e.push(this._data[b]);return e}if(f.$in&&f.$in instanceof Array){e=[];for(b in this._data)this._data.hasOwnProperty(b)&&f.$in.indexOf(b)>-1&&e.push(this._data[b]);return e}if(f.$nin&&f.$nin instanceof Array){e=[];for(b in this._data)this._data.hasOwnProperty(b)&&-1===f.$nin.indexOf(b)&&e.push(this._data[b]);return e}if(f.$or&&f.$or instanceof Array){for(e=[],b=0;b-1&&this._chain.splice(b,1)}},chainSend:function(a,b,c){if(this._chain){var d,e=this._chain,f=e.length;for(d=0;f>d;d++)e[d].chainReceive(this,a,b,c)}},chainReceive:function(a,b,c,d){var e={sender:a,type:b,data:c,options:d};(!this._chainHandler||this._chainHandler&&!this._chainHandler(e))&&this.chainSend(e.type,e.data,e.options)}};b.exports=d},{}],17:[function(a,b,c){"use strict";var d,e=0,f=a("./Overload");d={decouple:function(a,b){if(void 0!==a){if(b){var c,d=JSON.stringify(a),e=[];for(c=0;b>c;c++)e.push(JSON.parse(d));return e}return JSON.parse(JSON.stringify(a))}return void 0},objectId:function(a){var b,c=Math.pow(10,17);if(a){var d,f=0,g=a.length;for(d=0;g>d;d++)f+=a.charCodeAt(d)*c;b=f.toString(16)}else e++,b=(e+(Math.random()*c+Math.random()*c+Math.random()*c+Math.random()*c)).toString(16);return b},debug:new f([function(){return this._debug&&this._debug.all},function(a){return void 0!==a?"boolean"==typeof a?(this._debug=this._debug||{},this._debug.all=a,this.chainSend("debug",this._debug),this):this._debug&&this._debug[a]||this._db&&this._db._debug&&this._db._debug[a]||this._debug&&this._debug.all:this._debug&&this._debug.all},function(a,b){return void 0!==a?void 0!==b?(this._debug=this._debug||{},this._debug[a]=b,this.chainSend("debug",this._debug),this):this._debug&&this._debug[b]||this._db&&this._db._debug&&this._db._debug[a]:this._debug&&this._debug.all}])},b.exports=d},{"./Overload":24}],18:[function(a,b,c){"use strict";var d={TYPE_INSERT:0,TYPE_UPDATE:1,TYPE_REMOVE:2,PHASE_BEFORE:0,PHASE_AFTER:1};b.exports=d},{}],19:[function(a,b,c){"use strict";var d=a("./Overload"),e={on:new d({"string, function":function(a,b){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||{},this._listeners[a]["*"]=this._listeners[a]["*"]||[],this._listeners[a]["*"].push(b),this},"string, *, function":function(a,b,c){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||{},this._listeners[a][b]=this._listeners[a][b]||[],this._listeners[a][b].push(c),this}}),off:new d({string:function(a){return this._listeners&&this._listeners[a]&&a in this._listeners&&delete this._listeners[a],this},"string, function":function(a,b){var c,d;return"string"==typeof b?this._listeners&&this._listeners[a]&&this._listeners[a][b]&&delete this._listeners[a][b]:a in this._listeners&&(c=this._listeners[a]["*"],d=c.indexOf(b),d>-1&&c.splice(d,1)),this},"string, *, function":function(a,b,c){if(this._listeners&&a in this._listeners&&b in this.listeners[a]){var d=this._listeners[a][b],e=d.indexOf(c);e>-1&&d.splice(e,1)}},"string, *":function(a,b){this._listeners&&a in this._listeners&&b in this._listeners[a]&&delete this._listeners[a][b]}}),emit:function(a,b){if(this._listeners=this._listeners||{},a in this._listeners){var c,d;if(this._listeners[a]["*"]){var e=this._listeners[a]["*"];for(d=e.length,c=0;d>c;c++)e[c].apply(this,Array.prototype.slice.call(arguments,1))}if(b instanceof Array&&b[0]&&b[0][this._primaryKey]){var f,g,h=this._listeners[a];for(d=b.length,c=0;d>c;c++)if(h[b[c][this._primaryKey]])for(f=h[b[c][this._primaryKey]].length,g=0;f>g;g++)h[b[c][this._primaryKey]][g].apply(this,Array.prototype.slice.call(arguments,1))}}return this}};b.exports=e},{"./Overload":24}],20:[function(a,b,c){"use strict";var d={_match:function(a,b,c,d){var e,f,g,h,i,j,k,l=typeof a,m=typeof b,n=!0;if(d=d||{},d.$rootQuery||(d.$rootQuery=b),"string"!==l&&"number"!==l||"string"!==m&&"number"!==m){for(k in b)if(b.hasOwnProperty(k)){if(e=!1,j=k.substr(0,2),"//"===j)continue;if(0===j.indexOf("$")&&(i=this._matchOp(k,a,b[k],d),i>-1)){if(i){if("or"===c)return!0}else n=i;e=!0}if(!e&&b[k]instanceof RegExp)if(e=!0,"object"==typeof a&&void 0!==a[k]&&b[k].test(a[k])){if("or"===c)return!0}else n=!1;if(!e)if("object"==typeof b[k])if(void 0!==a[k])if(a[k]instanceof Array&&!(b[k]instanceof Array)){for(g=!1,h=0;hc;case"$gte":return b>=c;case"$lt":return c>b;case"$lte":return c>=b;case"$exists":return void 0===b!==c;case"$ne":return b!=c;case"$or":for(var e=0;eg;g++)if(h[g]===b)return!0;return!1}throw'ForerunnerDB.Mixin.Matching "'+this.name()+'": Cannot use an $in operator on a non-array key: '+a;case"$nin":if(c instanceof Array){var j,k=c,l=k.length;for(j=0;l>j;j++)if(k[j]===b)return!1;return!0}throw'ForerunnerDB.Mixin.Matching "'+this.name()+'": Cannot use a $nin operator on a non-array key: '+a;case"$distinct":d.$rootQuery["//distinctLookup"]=d.$rootQuery["//distinctLookup"]||{};for(var m in c)if(c.hasOwnProperty(m))return d.$rootQuery["//distinctLookup"][m]=d.$rootQuery["//distinctLookup"][m]||{}, -d.$rootQuery["//distinctLookup"][m][b[m]]?!1:(d.$rootQuery["//distinctLookup"][m][b[m]]=!0,!0)}return-1}};b.exports=d},{}],21:[function(a,b,c){"use strict";var d={sortAsc:function(a,b){return"string"==typeof a&&"string"==typeof b?a.localeCompare(b):a>b?1:b>a?-1:0},sortDesc:function(a,b){return"string"==typeof a&&"string"==typeof b?b.localeCompare(a):a>b?-1:b>a?1:0}};b.exports=d},{}],22:[function(a,b,c){"use strict";var d={addTrigger:function(a,b,c,d){var e,f=this;return e=f._triggerIndexOf(a,b,c),-1===e?(f._trigger=f._trigger||{},f._trigger[b]=f._trigger[b]||{},f._trigger[b][c]=f._trigger[b][c]||[],f._trigger[b][c].push({id:a,method:d}),!0):!1},removeTrigger:function(a,b,c){var d,e=this;return d=e._triggerIndexOf(a,b,c),d>-1&&e._trigger[b][c].splice(d,1),!1},willTrigger:function(a,b){return this._trigger&&this._trigger[a]&&this._trigger[a][b]&&this._trigger[a][b].length},processTrigger:function(a,b,c,d,e){var f,g,h,i,j,k=this;if(k._trigger&&k._trigger[b]&&k._trigger[b][c]){for(f=k._trigger[b][c],h=f.length,g=0;h>g;g++){if(i=f[g],this.debug()){var l,m;switch(b){case this.TYPE_INSERT:l="insert";break;case this.TYPE_UPDATE:l="update";break;case this.TYPE_REMOVE:l="remove";break;default:l=""}switch(c){case this.PHASE_BEFORE:m="before";break;case this.PHASE_AFTER:m="after";break;default:m=""}}if(j=i.method.call(k,a,d,e),j===!1)return!1;if(void 0!==j&&j!==!0&&j!==!1)throw"ForerunnerDB.Mixin.Triggers: Trigger error: "+j}return!0}},_triggerIndexOf:function(a,b,c){var d,e,f,g=this;if(g._trigger&&g._trigger[b]&&g._trigger[b][c])for(d=g._trigger[b][c],e=d.length,f=0;e>f;f++)if(d[f].id===a)return f;return-1}};b.exports=d},{}],23:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=function(a){this.pathSolver=new e,this.counter=0,this.init.apply(this,arguments)};f.prototype.init=function(a){this._data={operation:a,index:{potential:[],used:!1},steps:[],time:{startMs:0,stopMs:0,totalMs:0,process:{}},flag:{},log:[]}},d.addModule("Operation",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.start=function(){this._data.time.startMs=(new Date).getTime()},f.prototype.log=function(a){if(a){var b=this._log.length>0?this._data.log[this._data.log.length-1].time:0,c={event:a,time:(new Date).getTime(),delta:0};return this._data.log.push(c),b&&(c.delta=c.time-b),this}return this._data.log},f.prototype.time=function(a){if(void 0!==a){var b=this._data.time.process,c=b[a]=b[a]||{};return c.startMs?(c.stopMs=(new Date).getTime(),c.totalMs=c.stopMs-c.startMs,c.stepObj.totalMs=c.totalMs,delete c.stepObj):(c.startMs=(new Date).getTime(),c.stepObj={name:a},this._data.steps.push(c.stepObj)),this}return this._data.time},f.prototype.flag=function(a,b){return void 0===a||void 0===b?void 0!==a?this._data.flag[a]:this._data.flag:void(this._data.flag[a]=b)},f.prototype.data=function(a,b,c){return void 0!==b?(this.pathSolver.set(this._data,a,b),this):this.pathSolver.get(this._data,a)},f.prototype.pushData=function(a,b,c){this.pathSolver.push(this._data,a,b)},f.prototype.stop=function(){this._data.time.stopMs=(new Date).getTime(),this._data.time.totalMs=this._data.time.stopMs-this._data.time.startMs},d.finishModule("Operation"),b.exports=f},{"./Path":26,"./Shared":30}],24:[function(a,b,c){"use strict";var d=function(a){if(a){var b,c,d,f,g,h;if(!(a instanceof Array)){d={};for(b in a)if(a.hasOwnProperty(b))if(f=b.replace(/ /g,""),-1===f.indexOf("*"))d[f]=a[b];else for(h=e(f),g=0;gb;b++)if(a[b].length===arguments.length)return a[b].apply(this,arguments)}else{for(b=0;b=0;b--)if(d=f.slice(0,b).join(","),a[d+",..."])return a[d+",..."].apply(this,arguments)}throw'ForerunnerDB.Overload "'+this.name()+'": Overloaded method does not have a matching signature for the passed arguments: '+JSON.stringify(f)}}return function(){}},e=function(a){var b,c,d=[],f=["string","object","number","function","undefined"];if(a.indexOf("*")>-1)for(c=0;c-1&&(this._collections.splice(a,1),a.unChain(this),a.off("drop",this._collectionDroppedWrap),this._refresh()),this},i.prototype._collectionDropped=function(a){a&&this._removeCollection(a)},i.prototype._refresh=function(){if("dropped"!==this._state){if(this._collections&&this._collections[0]){this._collData.primaryKey(this._collections[0].primaryKey());var a,b=[];for(a=0;ah;h++){if(f=f[d[h]],g instanceof Array){for(i=0;ii;i++){if(f=f[d[i]],!f||"object"!=typeof f){h=d[i]+":"+f;break}g=f}return h},e.prototype.clean=function(a){return"."===a.substr(0,1)&&(a=a.substr(1,a.length-1)),a},d.finishModule("Path"),b.exports=e},{"./Shared":30}],27:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k,l=a("./Shared"),m=a("localforage");j=function(){this.init.apply(this,arguments)},j.prototype.init=function(a){a.isClient()&&void 0!==window.Storage&&(this.mode("localforage"),m.config({driver:[m.INDEXEDDB,m.WEBSQL,m.LOCALSTORAGE],name:"ForerunnerDB",storeName:"FDB"}))},l.addModule("Persist",j),l.mixin(j.prototype,"Mixin.ChainReactor"),d=l.modules.Core,e=a("./Collection"),f=e.prototype.drop,g=a("./CollectionGroup"),h=e.prototype.init,i=d.prototype.init,k=l.overload,j.prototype.mode=function(a){return void 0!==a?(this._mode=a,this):this._mode},j.prototype.driver=function(a){if(void 0!==a){switch(a.toUpperCase()){case"LOCALSTORAGE":m.setDriver(m.LOCALSTORAGE);break;case"WEBSQL":m.setDriver(m.WEBSQL);break;case"INDEXEDDB":m.setDriver(m.INDEXEDDB);break;default:throw"ForerunnerDB.Persist: The persistence driver you have specified is not found. Please use either IndexedDB, WebSQL or LocalStorage!"}return this}return m.driver()},j.prototype.save=function(a,b,c){var d;switch(d=function(a,b){a="object"==typeof a?"json::fdb::"+JSON.stringify(a):"raw::fdb::"+a,b&&b(!1,a)},this.mode()){case"localforage":d(b,function(b,d){m.setItem(a,d).then(function(a){c(!1,a)},function(a){c(a)})});break;default:c&&c("No data handler.")}},j.prototype.load=function(a,b){var c,d,e;switch(e=function(a,b){if(a){switch(c=a.split("::fdb::"),c[0]){case"json":d=JSON.parse(c[1]);break;case"raw":d=c[1]}b&&b(!1,d)}else b(!1,a)},this.mode()){case"localforage":m.getItem(a).then(function(a){e(a,b)},function(a){b(a)});break;default:b&&b("No data handler or unrecognised data type.")}},j.prototype.drop=function(a,b){switch(this.mode()){case"localforage":m.removeItem(a).then(function(){b(!1)},function(a){b(a)});break;default:b&&b("No data handler or unrecognised data type.")}},e.prototype.drop=new k({"":function(){"dropped"!==this._state&&this.drop(!0)},"function":function(a){"dropped"!==this._state&&this.drop(!0,a)},"boolean":function(a){if("dropped"!==this._state){if(a){if(!this._name)throw"ForerunnerDB.Persist: Cannot drop a collection's persistent storage when no name assigned to collection!";if(!this._db)throw"ForerunnerDB.Persist: Cannot drop a collection's persistent storage when the collection is not attached to a database!";this._db.persist.drop(this._name)}f.apply(this,arguments)}},"boolean, function":function(a,b){"dropped"!==this._state&&(a&&(this._name?this._db?this._db.persist.drop(this._name,b):b&&b("Cannot drop a collection's persistent storage when the collection is not attached to a database!"):b&&b("Cannot drop a collection's persistent storage when no name assigned to collection!")),f.apply(this,arguments))}}),e.prototype.save=function(a){this._name?this._db?this._db.persist.save(this._name,this._data,a):a&&a("Cannot save a collection that is not attached to a database!"):a&&a("Cannot save a collection with no assigned name!")},e.prototype.load=function(a){var b=this;this._name?this._db?this._db.persist.load(this._name,function(c,d){c?a&&a(c):(d&&b.setData(d),a&&a(!1))}):a&&a("Cannot load a collection that is not attached to a database!"):a&&a("Cannot load a collection with no assigned name!")},d.prototype.init=function(){this.persist=new j(this),i.apply(this,arguments)},d.prototype.load=function(a){var b,c,d=this._collection,e=d.keys(),f=e.length;b=function(b){b?a(b):(f--,0===f&&a(!1))};for(c in d)d.hasOwnProperty(c)&&d[c].load(b)},d.prototype.save=function(a){var b,c,d=this._collection,e=d.keys(),f=e.length;b=function(b){b?a(b):(f--,0===f&&a(!1))};for(c in d)d.hasOwnProperty(c)&&d[c].save(b)},l.finishModule("Persist"),b.exports=j},{"./Collection":4,"./CollectionGroup":5,"./Shared":30,localforage:40}],28:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a,b,c){if(!(a&&b&&c))throw"ForerunnerDB.ReactorIO: ReactorIO requires an in, out and process argument to instantiate!";if(this._reactorIn=a,this._reactorOut=b,this._chainHandler=c,!a.chain||!b.chainReceive)throw"ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!";a.chain(this),this.chain(b)};d.addModule("ReactorIO",e),e.prototype.drop=function(){return"dropped"!==this._state&&(this._state="dropped",this._reactorIn&&this._reactorIn.unChain(this),this._reactorOut&&this.unChain(this._reactorOut),delete this._reactorIn,delete this._reactorOut,delete this._chainHandler,this.emit("drop",this)),!0},d.synthesize(e.prototype,"state"),d.mixin(e.prototype,"Mixin.ChainReactor"),d.mixin(e.prototype,"Mixin.Events"),d.finishModule("ReactorIO"),b.exports=e},{"./Shared":30}],29:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k=a("./Shared"),l=a("rest"),m=a("rest/interceptor/mime"),n=function(){this.init.apply(this,arguments)};n.prototype.init=function(a){this._endPoint="",this._client=l.wrap(m)},n.prototype._params=function(a){var b=[];for(var c in a)a.hasOwnProperty(c)&&b.push(encodeURIComponent(c)+"="+encodeURIComponent(a[c]));return b.join("&")},n.prototype.get=function(a,b,c){var d,e=this;a=void 0!==a?a:"",console.log("Getting: ",this.endPoint()+a+"?"+this._params(b)),this._client({method:"get",path:this.endPoint()+a,params:b}).then(function(a){a.entity&&a.entity.error?c(a.entity.error,a.entity,a):(d=e.collection(),d&&d.upsert(a.entity),c(!1,a.entity,a))},function(a){c(!0,a.entity,a)})},n.prototype.post=function(a,b,c){this._client({method:"post",path:this.endPoint()+a,entity:b,headers:{"Content-Type":"application/json"}}).then(function(a){a.entity&&a.entity.error?c(a.entity.error,a.entity,a):c(!1,a.entity,a)},function(a){c(!0,a)})},k.synthesize(n.prototype,"sessionData"),k.synthesize(n.prototype,"endPoint"),k.synthesize(n.prototype,"collection"),k.addModule("Rest",n),k.mixin(n.prototype,"Mixin.ChainReactor"),d=k.modules.Core,e=a("./Collection"),f=e.prototype.drop,g=a("./CollectionGroup"),h=e.prototype.init,i=d.prototype.init,j=k.overload,e.prototype.init=function(){this.rest=new n,this.rest.collection(this),h.apply(this,arguments)},d.prototype.init=function(){this.rest=new n,i.apply(this,arguments)},k.finishModule("Rest"),b.exports=n},{"./Collection":4,"./CollectionGroup":5,"./Shared":30,rest:43,"rest/interceptor/mime":48}],30:[function(a,b,c){"use strict";var d={version:"1.3.17",modules:{},_synth:{},addModule:function(a,b){this.modules[a]=b,this.emit("moduleLoad",[a,b])},finishModule:function(a){if(!this.modules[a])throw"ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): "+a;this.modules[a]._fdbFinished=!0,this.emit("moduleFinished",[a,this.modules[a]])},moduleFinished:function(a,b){this.modules[a]&&this.modules[a]._fdbFinished?b(a,this.modules[a]):this.on("moduleFinished",b)},moduleExists:function(a){return Boolean(this.modules[a])},mixin:function(a,b){var c=this.mixins[b];if(!c)throw"ForerunnerDB.Shared: Cannot find mixin named: "+b;for(var d in c)c.hasOwnProperty(d)&&(a[d]=c[d])},synthesize:function(a,b,c){if(this._synth[b]=this._synth[b]||function(a){return void 0!==a?(this["_"+b]=a,this):this["_"+b]},c){var d=this;a[b]=function(){var a,e=this.$super;return this.$super=d._synth[b],a=c.apply(this,arguments),this.$super=e,a}}else a[b]=this._synth[b]},overload:a("./Overload"),mixins:{"Mixin.Common":a("./Mixin.Common"),"Mixin.Events":a("./Mixin.Events"),"Mixin.ChainReactor":a("./Mixin.ChainReactor"),"Mixin.CRUD":a("./Mixin.CRUD"),"Mixin.Constants":a("./Mixin.Constants"),"Mixin.Triggers":a("./Mixin.Triggers"),"Mixin.Sorting":a("./Mixin.Sorting"),"Mixin.Matching":a("./Mixin.Matching")}};d.mixin(d,"Mixin.Events"),b.exports=d},{"./Mixin.CRUD":15,"./Mixin.ChainReactor":16,"./Mixin.Common":17,"./Mixin.Constants":18,"./Mixin.Events":19,"./Mixin.Matching":20,"./Mixin.Sorting":21,"./Mixin.Triggers":22,"./Overload":24}],31:[function(a,b,c){Array.prototype.filter||(Array.prototype.filter=function(a){if(void 0===this||null===this)throw new TypeError;var b=Object(this),c=b.length>>>0;if("function"!=typeof a)throw new TypeError;for(var d=[],e=arguments.length>=2?arguments[1]:void 0,f=0;c>f;f++)if(f in b){var g=b[f];a.call(e,g,f,b)&&d.push(g)}return d}),"function"!=typeof Object.create&&(Object.create=function(){var a=function(){};return function(b){if(arguments.length>1)throw Error("Second argument not supported");if("object"!=typeof b)throw TypeError("Argument must be an object");a.prototype=b;var c=new a;return a.prototype=null,c}}()),Array.prototype.indexOf||(Array.prototype.indexOf=function(a,b){var c;if(null===this)throw new TypeError('"this" is null or not defined');var d=Object(this),e=d.length>>>0;if(0===e)return-1;var f=+b||0;if(Math.abs(f)===1/0&&(f=0),f>=e)return-1;for(c=Math.max(f>=0?f:e-Math.abs(f),0);e>c;){if(c in d&&d[c]===a)return c;c++}return-1}),b.exports={}},{}],32:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k;d=a("./Shared");var l=function(a,b,c){this.init.apply(this,arguments)};l.prototype.init=function(a,b,c){var d=this;this._name=a,this._groups=[],this._listeners={},this._querySettings={},this._debug={},this.query(b,!1),this.queryOptions(c,!1),this._collectionDroppedWrap=function(){d._collectionDropped.apply(d,arguments)},this._privateData=new f("__FDB__view_privateData_"+this._name)},d.addModule("View",l),d.mixin(l.prototype,"Mixin.Common"),d.mixin(l.prototype,"Mixin.ChainReactor"),d.mixin(l.prototype,"Mixin.Constants"),d.mixin(l.prototype,"Mixin.Triggers"),f=a("./Collection"),g=a("./CollectionGroup"),k=a("./ActiveBucket"),j=a("./ReactorIO"),h=f.prototype.init,e=d.modules.Core,i=e.prototype.init,d.synthesize(l.prototype,"state"),d.synthesize(l.prototype,"name"),l.prototype.insert=function(){this._from.insert.apply(this._from,arguments)},l.prototype.update=function(){this._from.update.apply(this._from,arguments)},l.prototype.updateById=function(){this._from.updateById.apply(this._from,arguments)},l.prototype.remove=function(){this._from.remove.apply(this._from,arguments)},l.prototype.find=function(a,b){return this.publicData().find(a,b)},l.prototype.data=function(){return this._privateData},l.prototype.from=function(a){var b=this;if(void 0!==a){this._from&&(this._from.off("drop",this._collectionDroppedWrap),delete this._from),"string"==typeof a&&(a=this._db.collection(a)),this._from=a,this._io=new j(a,this,function(a){var c,d,e,f,g,h,i;if(b._querySettings.query){if("insert"===a.type){if(c=a.data,c instanceof Array)for(f=[],i=0;id;d++)e=this._activeBucket.insert(b[d]),this._transformInsert(a.data,e),this._privateData._insertHandle(a.data,e);else e=this._privateData._data.length,this._transformInsert(a.data,e),this._privateData._insertHandle(a.data,e);break;case"update":if(this.debug()&&console.log('ForerunnerDB.View: Updating some data on view "'+this.name()+'" in underlying (internal) view collection "'+this._privateData.name()+'"'),g=this._privateData.primaryKey(),f=this._privateData.update(a.data.query,a.data.update,a.data.options),this._querySettings.options&&this._querySettings.options.$orderBy)for(c=f.length,d=0;c>d;d++)i=f[d],this._activeBucket.remove(i),j=this._privateData._data.indexOf(i),e=this._activeBucket.insert(i),j!==e&&this._privateData._updateSpliceMove(this._privateData._data,j,e);if(this._transformEnabled&&this._transformIn)for(g=this._publicData.primaryKey(),k=0;kd;d++)this._activeBucket.insert(b[d])}else delete this._activeBucket},l.prototype.refresh=function(){if(this._from){var a=this.publicData();this._privateData.remove(),a.remove(),this._privateData.insert(this._from.find(this._querySettings.query,this._querySettings.options))}return this._querySettings.options&&this._querySettings.options.$orderBy?this.rebuildActiveBucket(this._querySettings.options.$orderBy):this.rebuildActiveBucket(),this},l.prototype.count=function(){return this._privateData&&this._privateData._data?this._privateData._data.length:0},l.prototype.subset=function(){return this.publicData().subset.apply(this._privateData,arguments)},l.prototype.transform=function(a){return void 0!==a?("object"==typeof a?(void 0!==a.enabled&&(this._transformEnabled=a.enabled),void 0!==a.dataIn&&(this._transformIn=a.dataIn),void 0!==a.dataOut&&(this._transformOut=a.dataOut)):this._transformEnabled=a!==!1,this._transformPrimaryKey(this.privateData().primaryKey()),this._transformSetData(this.privateData().find()),this):{enabled:this._transformEnabled,dataIn:this._transformIn,dataOut:this._transformOut}},l.prototype.privateData=function(){return this._privateData},l.prototype.publicData=function(){return this._transformEnabled?this._publicData:this._privateData},l.prototype._transformSetData=function(a){this._transformEnabled&&(this._publicData=new f("__FDB__view_publicData_"+this._name),this._publicData.db(this._privateData._db),this._publicData.transform({enabled:!0,dataIn:this._transformIn,dataOut:this._transformOut}),this._publicData.setData(a))},l.prototype._transformInsert=function(a,b){this._transformEnabled&&this._publicData&&this._publicData.insert(a,b)},l.prototype._transformUpdate=function(a,b,c){this._transformEnabled&&this._publicData&&this._publicData.update(a,b,c)},l.prototype._transformRemove=function(a,b){this._transformEnabled&&this._publicData&&this._publicData.remove(a,b)},l.prototype._transformPrimaryKey=function(a){this._transformEnabled&&this._publicData&&this._publicData.primaryKey(a)},f.prototype.init=function(){this._view=[],h.apply(this,arguments)},f.prototype.view=function(a,b,c){if(this._db&&this._db._view){if(this._db._view[a])throw'ForerunnerDB.Collection "'+this.name()+'": Cannot create a view using this collection because a view with this name already exists: '+a;var d=new l(a,b,c).db(this._db).from(this);return this._view=this._view||[],this._view.push(d),d}},f.prototype._addView=g.prototype._addView=function(a){return void 0!==a&&this._view.push(a),this},f.prototype._removeView=g.prototype._removeView=function(a){if(void 0!==a){var b=this._view.indexOf(a);b>-1&&this._view.splice(b,1)}return this},e.prototype.init=function(){this._view={},i.apply(this,arguments)},e.prototype.view=function(a){return this._view[a]||(this.debug()||this._db&&this._db.debug())&&console.log("Core.View: Creating view "+a),this._view[a]=this._view[a]||new l(a).db(this),this._view[a]},e.prototype.viewExists=function(a){return Boolean(this._view[a])},e.prototype.views=function(){var a,b=[];for(a in this._view)this._view.hasOwnProperty(a)&&b.push({name:a,count:this._view[a].count()});return b},d.finishModule("View"),b.exports=l},{"./ActiveBucket":3,"./Collection":4,"./CollectionGroup":5,"./ReactorIO":28,"./Shared":30}],33:[function(a,b,c){function d(){if(!h){h=!0;for(var a,b=g.length;b;){a=g,g=[];for(var c=-1;++ca;a++)b(l[a]);l=null}if("object"!=typeof this)throw new TypeError("Promises must be constructed via new");if("function"!=typeof a)throw new TypeError("not a function");var j=null,k=null,l=[],m=this;this.then=function(a,c){return new d(function(d,f){b(new e(a,c,d,f))})},f(a,c,h)}function e(a,b,c,d){this.onFulfilled="function"==typeof a?a:null,this.onRejected="function"==typeof b?b:null,this.resolve=c,this.reject=d}function f(a,b,c){var d=!1;try{a(function(a){d||(d=!0,b(a))},function(a){d||(d=!0,c(a))})}catch(e){if(d)return;d=!0,c(e)}}var g=a("asap");b.exports=d},{asap:36}],35:[function(a,b,c){"use strict";function d(a){this.then=function(b){return"function"!=typeof b?this:new e(function(c,d){f(function(){try{c(b(a))}catch(e){d(e)}})})}}var e=a("./core.js"),f=a("asap");b.exports=e,d.prototype=Object.create(e.prototype);var g=new d(!0),h=new d(!1),i=new d(null),j=new d(void 0),k=new d(0),l=new d("");e.resolve=function(a){if(a instanceof e)return a;if(null===a)return i;if(void 0===a)return j;if(a===!0)return g;if(a===!1)return h;if(0===a)return k;if(""===a)return l;if("object"==typeof a||"function"==typeof a)try{var b=a.then;if("function"==typeof b)return new e(b.bind(a))}catch(c){return new e(function(a,b){b(c)})}return new d(a); - -},e.from=e.cast=function(a){var b=new Error("Promise.from and Promise.cast are deprecated, use Promise.resolve instead");return b.name="Warning",console.warn(b.stack),e.resolve(a)},e.denodeify=function(a,b){return b=b||1/0,function(){var c=this,d=Array.prototype.slice.call(arguments);return new e(function(e,f){for(;d.length&&d.length>b;)d.pop();d.push(function(a,b){a?f(a):e(b)}),a.apply(c,d)})}},e.nodeify=function(a){return function(){var b=Array.prototype.slice.call(arguments),c="function"==typeof b[b.length-1]?b.pop():null;try{return a.apply(this,arguments).nodeify(c)}catch(d){if(null===c||"undefined"==typeof c)return new e(function(a,b){b(d)});f(function(){c(d)})}}},e.all=function(){var a=1===arguments.length&&Array.isArray(arguments[0]),b=Array.prototype.slice.call(a?arguments[0]:arguments);if(!a){var c=new Error("Promise.all should be called with a single array, calling it with multiple arguments is deprecated");c.name="Warning",console.warn(c.stack)}return new e(function(a,c){function d(f,g){try{if(g&&("object"==typeof g||"function"==typeof g)){var h=g.then;if("function"==typeof h)return void h.call(g,function(a){d(f,a)},c)}b[f]=g,0===--e&&a(b)}catch(i){c(i)}}if(0===b.length)return a([]);for(var e=b.length,f=0;fa?void b(null):void c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readonly").objectStore(e.storeName),g=!1,h=f.openCursor();h.onsuccess=function(){var c=h.result;return c?void(0===a?b(c.key):g?b(c.key):(g=!0,c.advance(a))):void b(null)},h.onerror=function(){d(h.error)}})["catch"](d)});return l(d,b),d}function k(a){var b=this,c=new o(function(a,c){b.ready().then(function(){var d=b._dbInfo,e=d.db.transaction(d.storeName,"readonly").objectStore(d.storeName),f=e.openCursor(),g=[];f.onsuccess=function(){var b=f.result;return b?(g.push(b.key),void b["continue"]()):void a(g)},f.onerror=function(){c(f.error)}})["catch"](c)});return l(c,a),c}function l(a,b){b&&a.then(function(a){b(null,a)},function(a){b(a)})}function m(a,b){b&&a.then(function(a){n(b,a)},function(a){b(a)})}function n(a,b){return a?setTimeout(function(){return a(null,b)},0):void 0}var o="undefined"!=typeof b&&b.exports?a("promise"):this.Promise,p=p||this.indexedDB||this.webkitIndexedDB||this.mozIndexedDB||this.OIndexedDB||this.msIndexedDB;if(p){var q={_driver:"asyncStorage",_initStorage:c,iterate:e,getItem:d,setItem:f,removeItem:g,clear:h,length:i,key:j,keys:k};"undefined"!=typeof b&&b.exports?b.exports=q:"function"==typeof define&&define.amd?define("asyncStorage",function(){return q}):this.asyncStorage=q}}).call(window)},{promise:35}],38:[function(a,b,c){(function(){"use strict";function c(b){var c=this,d={};if(b)for(var e in b)d[e]=b[e];d.keyPrefix=d.name+"/",c._dbInfo=d;var f=new m(function(b){s===r.DEFINE?a(["localforageSerializer"],b):b(s===r.EXPORT?a("./../utils/serializer"):n.localforageSerializer)});return f.then(function(a){return o=a,m.resolve()})}function d(a){var b=this,c=b.ready().then(function(){for(var a=b._dbInfo.keyPrefix,c=p.length-1;c>=0;c--){var d=p.key(c);0===d.indexOf(a)&&p.removeItem(d)}});return l(c,a),c}function e(a,b){var c=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=c.ready().then(function(){var b=c._dbInfo,d=p.getItem(b.keyPrefix+a);return d&&(d=o.deserialize(d)),d});return l(d,b),d}function f(a,b){var c=this,d=c.ready().then(function(){for(var b=c._dbInfo.keyPrefix,d=b.length,e=p.length,f=0;e>f;f++){var g=p.key(f),h=p.getItem(g);if(h&&(h=o.deserialize(h)),h=a(h,g.substring(d),f+1),void 0!==h)return h}});return l(d,b),d}function g(a,b){var c=this,d=c.ready().then(function(){var b,d=c._dbInfo;try{b=p.key(a)}catch(e){b=null}return b&&(b=b.substring(d.keyPrefix.length)),b});return l(d,b),d}function h(a){var b=this,c=b.ready().then(function(){for(var a=b._dbInfo,c=p.length,d=[],e=0;c>e;e++)0===p.key(e).indexOf(a.keyPrefix)&&d.push(p.key(e).substring(a.keyPrefix.length));return d});return l(c,a),c}function i(a){var b=this,c=b.keys().then(function(a){return a.length});return l(c,a),c}function j(a,b){var c=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=c.ready().then(function(){var b=c._dbInfo;p.removeItem(b.keyPrefix+a)});return l(d,b),d}function k(a,b,c){var d=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var e=d.ready().then(function(){void 0===b&&(b=null);var c=b;return new m(function(e,f){o.serialize(b,function(b,g){if(g)f(g);else try{var h=d._dbInfo;p.setItem(h.keyPrefix+a,b),e(c)}catch(i){("QuotaExceededError"===i.name||"NS_ERROR_DOM_QUOTA_REACHED"===i.name)&&f(i),f(i)}})})});return l(e,c),e}function l(a,b){b&&a.then(function(a){b(null,a)},function(a){b(a)})}var m="undefined"!=typeof b&&b.exports?a("promise"):this.Promise,n=this,o=null,p=null;try{if(!(this.localStorage&&"setItem"in this.localStorage))return;p=this.localStorage}catch(q){return}var r={DEFINE:1,EXPORT:2,WINDOW:3},s=r.WINDOW;"undefined"!=typeof b&&b.exports?s=r.EXPORT:"function"==typeof define&&define.amd&&(s=r.DEFINE);var t={_driver:"localStorageWrapper",_initStorage:c,iterate:f,getItem:e,setItem:k,removeItem:j,clear:d,length:i,key:g,keys:h};s===r.EXPORT?b.exports=t:s===r.DEFINE?define("localStorageWrapper",function(){return t}):this.localStorageWrapper=t}).call(window)},{"./../utils/serializer":41,promise:35}],39:[function(a,b,c){(function(){"use strict";function c(b){var c=this,d={db:null};if(b)for(var e in b)d[e]="string"!=typeof b[e]?b[e].toString():b[e];var f=new m(function(b){r===q.DEFINE?a(["localforageSerializer"],b):b(r===q.EXPORT?a("./../utils/serializer"):n.localforageSerializer)}),g=new m(function(a,e){try{d.db=p(d.name,String(d.version),d.description,d.size)}catch(f){return c.setDriver(c.LOCALSTORAGE).then(function(){return c._initStorage(b)}).then(a)["catch"](e)}d.db.transaction(function(b){b.executeSql("CREATE TABLE IF NOT EXISTS "+d.storeName+" (id INTEGER PRIMARY KEY, key unique, value)",[],function(){c._dbInfo=d,a()},function(a,b){e(b)})})});return f.then(function(a){return o=a,g})}function d(a,b){var c=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new m(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("SELECT * FROM "+e.storeName+" WHERE key = ? LIMIT 1",[a],function(a,c){var d=c.rows.length?c.rows.item(0).value:null;d&&(d=o.deserialize(d)),b(d)},function(a,b){d(b)})})})["catch"](d)});return l(d,b),d}function e(a,b){var c=this,d=new m(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("SELECT * FROM "+e.storeName,[],function(c,d){for(var e=d.rows,f=e.length,g=0;f>g;g++){var h=e.item(g),i=h.value;if(i&&(i=o.deserialize(i)),i=a(i,h.key,g+1),void 0!==i)return void b(i)}b()},function(a,b){d(b)})})})["catch"](d)});return l(d,b),d}function f(a,b,c){var d=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var e=new m(function(c,e){d.ready().then(function(){void 0===b&&(b=null);var f=b;o.serialize(b,function(b,g){if(g)e(g);else{var h=d._dbInfo;h.db.transaction(function(d){d.executeSql("INSERT OR REPLACE INTO "+h.storeName+" (key, value) VALUES (?, ?)",[a,b],function(){c(f)},function(a,b){e(b)})},function(a){a.code===a.QUOTA_ERR&&e(a)})}})})["catch"](e)});return l(e,c),e}function g(a,b){var c=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new m(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("DELETE FROM "+e.storeName+" WHERE key = ?",[a],function(){b()},function(a,b){d(b)})})})["catch"](d)});return l(d,b),d}function h(a){var b=this,c=new m(function(a,c){b.ready().then(function(){var d=b._dbInfo;d.db.transaction(function(b){b.executeSql("DELETE FROM "+d.storeName,[],function(){a()},function(a,b){c(b)})})})["catch"](c)});return l(c,a),c}function i(a){var b=this,c=new m(function(a,c){b.ready().then(function(){var d=b._dbInfo;d.db.transaction(function(b){b.executeSql("SELECT COUNT(key) as c FROM "+d.storeName,[],function(b,c){var d=c.rows.item(0).c;a(d)},function(a,b){c(b)})})})["catch"](c)});return l(c,a),c}function j(a,b){var c=this,d=new m(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("SELECT key FROM "+e.storeName+" WHERE id = ? LIMIT 1",[a+1],function(a,c){var d=c.rows.length?c.rows.item(0).key:null;b(d)},function(a,b){d(b)})})})["catch"](d)});return l(d,b),d}function k(a){var b=this,c=new m(function(a,c){b.ready().then(function(){var d=b._dbInfo;d.db.transaction(function(b){b.executeSql("SELECT key FROM "+d.storeName,[],function(b,c){for(var d=[],e=0;eb;b+=4)c=f.indexOf(a[b]),d=f.indexOf(a[b+1]),e=f.indexOf(a[b+2]),g=f.indexOf(a[b+3]),l[j++]=c<<2|d>>4,l[j++]=(15&d)<<4|e>>2,l[j++]=(3&e)<<6|63&g;return k}function e(a){var b,c=new Uint8Array(a),d="";for(b=0;b>2],d+=f[(3&c[b])<<4|c[b+1]>>4],d+=f[(15&c[b+1])<<2|c[b+2]>>6],d+=f[63&c[b+2]];return c.length%3===2?d=d.substring(0,d.length-1)+"=":c.length%3===1&&(d=d.substring(0,d.length-2)+"=="),d}var f="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",g="__lfsc__:",h=g.length,i="arbf",j="blob",k="si08",l="ui08",m="uic8",n="si16",o="si32",p="ur16",q="ui32",r="fl32",s="fl64",t=h+i.length,u={serialize:a,deserialize:c,stringToBuffer:d,bufferToString:e};"undefined"!=typeof b&&b.exports?b.exports=u:"function"==typeof define&&define.amd?define("localforageSerializer",function(){return u}):this.localforageSerializer=u}).call(window)},{}],42:[function(a,b,c){!function(a,b){"use strict";var c;a(function(a){function d(a,b){var c,d,e,f;if(c=a,e={},b){for(d in b)f=new RegExp("\\{"+d+"\\}"),f.test(c)?c=c.replace(f,encodeURIComponent(b[d]),"g"):e[d]=b[d];for(d in e)c+=-1===c.indexOf("?")?"?":"&",c+=encodeURIComponent(d),null!==e[d]&&void 0!==e[d]&&(c+="=",c+=encodeURIComponent(e[d]))}return c}function e(a,b){return 0===a.indexOf(b)}function f(a,b){return this instanceof f?void(a instanceof f?(this._template=a.template,this._params=g({},this._params,b)):(this._template=(a||"").toString(),this._params=b||{})):new f(a,b)}var g,h,i,j,k;return g=a("./util/mixin"),i=/([a-z][a-z0-9\+\-\.]*:)\/\/([^@]+@)?(([^:\/]+)(:([0-9]+))?)?(\/[^?#]*)?(\?[^#]*)?(#\S*)?/i,j=/^([a-z][a-z0-9\-\+\.]*:\/\/|\/)/i,k=/([a-z][a-z0-9\+\-\.]*:)\/\/([^@]+@)?(([^:\/]+)(:([0-9]+))?)?\//i,f.prototype={append:function(a,b){return new f(this._template+a,g({},this._params,b))},fullyQualify:function(){if(!b)return this;if(this.isFullyQualified())return this;var a=this._template;return e(a,"//")?a=h.protocol+a:e(a,"/")?a=h.origin+a:this.isAbsolute()||(a=h.origin+h.pathname.substring(0,h.pathname.lastIndexOf("/")+1)),-1===a.indexOf("/",8)&&(a+="/"),new f(a,this._params)},isAbsolute:function(){return j.test(this.build())},isFullyQualified:function(){return k.test(this.build())},isCrossOrigin:function(){if(!h)return!0;var a=this.parts();return a.protocol!==h.protocol||a.hostname!==h.hostname||a.port!==h.port},parts:function(){var a,b;return a=this.fullyQualify().build().match(i),b={href:a[0],protocol:a[1],host:a[3]||"",hostname:a[4]||"",port:a[6],pathname:a[7]||"",search:a[8]||"",hash:a[9]||""},b.origin=b.protocol+"//"+b.host,b.port=b.port||("https:"===b.protocol?"443":"http:"===b.protocol?"80":""),b},build:function(a){return d(this._template,g({},this._params,a))},toString:function(){return this.build()}},h=b?new f(b.href).parts():c,f})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)},"undefined"!=typeof window?window.location:void 0)},{"./util/mixin":78}],43:[function(a,b,c){!function(a){"use strict";a(function(a){var b=a("./client/default"),c=a("./client/xhr");return b.setPlatformDefaultClient(c),b})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{"./client/default":45,"./client/xhr":46}],44:[function(a,b,c){!function(a){"use strict";a(function(){return function(a,b){return b&&(a.skip=function(){return b}),a.wrap=function(b,c){return b(a,c)},a.chain=function(){return"undefined"!=typeof console&&console.log("rest.js: client.chain() is deprecated, use client.wrap() instead"),a.wrap.apply(this,arguments)},a}})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{}],45:[function(a,b,c){!function(a){"use strict";var b;a(function(a){function c(){return e.apply(b,arguments)}var d,e,f;return d=a("../client"),c.setDefaultClient=function(a){e=a},c.getDefaultClient=function(){return e},c.resetDefaultClient=function(){e=f},c.setPlatformDefaultClient=function(a){if(f)throw new Error("Unable to redefine platformDefaultClient");e=f=a},d(c)})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{"../client":44}],46:[function(a,b,c){!function(a,b){"use strict";a(function(a){function c(a){var b={};return a?(a.trim().split(j).forEach(function(a){var c,d,e;c=a.indexOf(":"),d=g(a.substring(0,c).trim()),e=a.substring(c+1).trim(),b[d]?Array.isArray(b[d])?b[d].push(e):b[d]=[b[d],e]:b[d]=e}),b):b}function d(a,b){return Object.keys(b||{}).forEach(function(c){if(b.hasOwnProperty(c)&&c in a)try{a[c]=b[c]}catch(d){}}),a}var e,f,g,h,i,j;return e=a("when"),f=a("../UrlBuilder"),g=a("../util/normalizeHeaderName"),h=a("../util/responsePromise"),i=a("../client"),j=/[\r|\n]+/,i(function(a){return h.promise(function(e,g){var h,i,j,k,l,m,n,o;if(a="string"==typeof a?{path:a}:a||{},n={request:a},a.canceled)return n.error="precanceled",void g(n);if(o=a.engine||b.XMLHttpRequest,!o)return void g({request:a,error:"xhr-not-available"});l=a.entity,a.method=a.method||(l?"POST":"GET"),i=a.method,j=new f(a.path||"",a.params).build();try{h=n.raw=new o,d(h,a.mixin),h.open(i,j,!0),d(h,a.mixin),k=a.headers;for(m in k)("Content-Type"!==m||"multipart/form-data"!==k[m])&&h.setRequestHeader(m,k[m]);a.canceled=!1,a.cancel=function(){a.canceled=!0,h.abort(),g(n)},h.onreadystatechange=function(){a.canceled||h.readyState===(o.DONE||4)&&(n.status={code:h.status,text:h.statusText},n.headers=c(h.getAllResponseHeaders()),n.entity=h.responseText,n.status.code>0?e(n):setTimeout(function(){e(n)},0))};try{h.onerror=function(){n.error="loaderror",g(n)}}catch(p){}h.send(l)}catch(p){n.error="loaderror",g(n)}})})})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)},"undefined"!=typeof window?window:void 0)},{"../UrlBuilder":42,"../client":44,"../util/normalizeHeaderName":79,"../util/responsePromise":80,when:75}],47:[function(a,b,c){!function(a){"use strict";a(function(a){function b(a){return a}function c(a){return a}function d(a){return a}function e(a){return l.promise(function(b,c){a.forEach(function(a){l(a,b,c)})})}function f(a){return this instanceof f?void i(this,a):new f(a)}function g(a){var g,i,m,n;return a=a||{},g=a.init||b,i=a.request||c,m=a.success||a.response||d,n=a.error||function(){return l((a.response||d).apply(this,arguments),l.reject,l.reject)},function(b,c){function d(a){var g,h;return g={},h={arguments:Array.prototype.slice.call(arguments),client:d},a="string"==typeof a?{path:a}:a||{},a.originator=a.originator||d,j(i.call(g,a,c,h),function(a){var d,i,j;return j=b,a instanceof f&&(i=a.abort,j=a.client||j,d=a.response,a=a.request),d=d||l(a,function(a){return l(j(a),function(a){return m.call(g,a,c,h)},function(a){return n.call(g,a,c,h)})}),i?e([d,i]):d},function(b){return l.reject({request:a,error:b})})}return"object"==typeof b&&(c=b),"function"!=typeof b&&(b=a.client||h),c=g(c||{}),k(d,b)}}var h,i,j,k,l;return h=a("./client/default"),i=a("./util/mixin"),j=a("./util/responsePromise"),k=a("./client"),l=a("when"),g.ComplexRequest=f,g})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{"./client":44,"./client/default":45,"./util/mixin":78,"./util/responsePromise":80,when:75}],48:[function(a,b,c){!function(a){"use strict";a(function(a){var b,c,d,e,f;return b=a("../interceptor"),c=a("../mime"),d=a("../mime/registry"),f=a("when"),e={read:function(a){return a},write:function(a){return a}},b({init:function(a){return a.registry=a.registry||d,a},request:function(a,b){var d,g;return g=a.headers||(a.headers={}),d=c.parse(g["Content-Type"]=g["Content-Type"]||b.mime||"text/plain"),g.Accept=g.Accept||b.accept||d.raw+", application/json;q=0.8, text/plain;q=0.5, */*;q=0.2","entity"in a?b.registry.lookup(d).otherwise(function(){if(b.permissive)return e;throw"mime-unknown"}).then(function(c){var e=b.client||a.originator;return f.attempt(c.write,a.entity,{client:e,request:a,mime:d,registry:b.registry}).otherwise(function(){throw"mime-serialization"}).then(function(b){return a.entity=b,a})}):a},response:function(a,b){if(!(a.headers&&a.headers["Content-Type"]&&a.entity))return a;var d=c.parse(a.headers["Content-Type"]);return b.registry.lookup(d).otherwise(function(){return e}).then(function(c){var e=b.client||a.request&&a.request.originator;return f.attempt(c.read,a.entity,{client:e,response:a,mime:d,registry:b.registry}).otherwise(function(b){throw a.error="mime-deserialization",a.cause=b,a}).then(function(b){return a.entity=b,a})})}})})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{"../interceptor":47,"../mime":51,"../mime/registry":52,when:75}],49:[function(a,b,c){!function(a){"use strict";a(function(a){function b(a,b){return 0===a.indexOf(b)}function c(a,b){return a.lastIndexOf(b)+b.length===a.length}var d,e;return d=a("../interceptor"),e=a("../UrlBuilder"),d({request:function(a,d){var f;return d.prefix&&!new e(a.path).isFullyQualified()&&(f=d.prefix,a.path&&(c(f,"/")||b(a.path,"/")||(f+="/"),f+=a.path),a.path=f),a}})})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{"../UrlBuilder":42,"../interceptor":47}],50:[function(a,b,c){!function(a){"use strict";a(function(a){var b,c,d;return b=a("../interceptor"),c=a("../util/uriTemplate"),d=a("../util/mixin"),b({init:function(a){return a.params=a.params||{},a.template=a.template||"",a},request:function(a,b){var e,f;return e=a.path||b.template,f=d({},a.params,b.params),a.path=c.expand(e,f),delete a.params,a}})})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{"../interceptor":47,"../util/mixin":78,"../util/uriTemplate":82}],51:[function(a,b,c){!function(a){"use strict";var b;a(function(){function a(a){var c,d;return c=a.split(";"),d=c[0].trim().split("+"),{raw:a,type:d[0],suffix:d[1]?"+"+d[1]:"",params:c.slice(1).reduce(function(a,c){return c=c.split("="),a[c[0].trim()]=c[1]?c[1].trim():b,a},{})}}return{parse:a}})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{}],52:[function(a,b,c){!function(a){"use strict";a(function(a){function b(a){this.lookup=function(b){var e;return e="string"==typeof b?c.parse(b):b,a[e.raw]?a[e.raw]:a[e.type+e.suffix]?a[e.type+e.suffix]:a[e.type]?a[e.type]:a[e.suffix]?a[e.suffix]:d.reject(new Error('Unable to locate converter for mime "'+e.raw+'"'))},this.delegate=function(a){return{read:function(){var b=arguments;return this.lookup(a).then(function(a){return a.read.apply(this,b)}.bind(this))}.bind(this),write:function(){var b=arguments;return this.lookup(a).then(function(a){return a.write.apply(this,b)}.bind(this))}.bind(this)}},this.register=function(b,c){return a[b]=d(c),a[b]},this.child=function(){return new b(Object.create(a))}}var c,d,e;return c=a("../mime"),d=a("when"),e=new b({}),e.register("application/hal",a("./type/application/hal")),e.register("application/json",a("./type/application/json")),e.register("application/x-www-form-urlencoded",a("./type/application/x-www-form-urlencoded")),e.register("multipart/form-data",a("./type/multipart/form-data")),e.register("text/plain",a("./type/text/plain")),e.register("+json",e.delegate("application/json")),e})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{"../mime":51,"./type/application/hal":53,"./type/application/json":54,"./type/application/x-www-form-urlencoded":55,"./type/multipart/form-data":56,"./type/text/plain":57,when:75}],53:[function(a,b,c){!function(a){"use strict";a(function(a){function b(a,b,c){Object.defineProperty(a,b,{value:c,configurable:!0,enumerable:!1,writeable:!0})}var c,d,e,f,g,h;return c=a("../../../interceptor/pathPrefix"),d=a("../../../interceptor/template"),e=a("../../../util/find"),f=a("../../../util/lazyPromise"),g=a("../../../util/responsePromise"),h=a("when"),{read:function(a,i){function j(a,b){(b&&l&&l.warn||l.log)&&(l.warn||l.log).call(l,"Relationship '"+a+"' is deprecated, see "+b)}var k,l;return i=i||{},k=i.client,l=i.console||l,i.registry.lookup(i.mime.suffix).then(function(l){return h(l.read(a,i)).then(function(a){return e.findProperties(a,"_embedded",function(a,c,d){Object.keys(a).forEach(function(d){if(!(d in c)){var e=g({entity:a[d]});b(c,d,e)}}),b(c,d,a)}),e.findProperties(a,"_links",function(a,e,h){Object.keys(a).forEach(function(c){var h=a[c];c in e||b(e,c,g.make(f(function(){return h.deprecation&&j(c,h.deprecation),h.templated===!0?d(k)({path:h.href}):k({path:h.href})})))}),b(e,h,a),b(e,"clientFor",function(b,e){var f=a[b];if(!f)throw new Error("Unknown relationship: "+b);return f.deprecation&&j(b,f.deprecation),f.templated===!0?d(e||k,{template:f.href}):c(e||k,{prefix:f.href})}),b(e,"requestFor",function(a,b,c){var d=this.clientFor(a,c);return d(b)})}),a})})},write:function(a,b){return b.registry.lookup(b.mime.suffix).then(function(c){return c.write(a,b)})}}})}("function"==typeof define&&define.amd?define:function(c){ -b.exports=c(a)})},{"../../../interceptor/pathPrefix":49,"../../../interceptor/template":50,"../../../util/find":76,"../../../util/lazyPromise":77,"../../../util/responsePromise":80,when:75}],54:[function(a,b,c){!function(a){"use strict";a(function(){function a(b,c){return{read:function(a){return JSON.parse(a,b)},write:function(a){return JSON.stringify(a,c)},extend:a}}return a()})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{}],55:[function(a,b,c){!function(a){"use strict";a(function(){function a(a){return a=encodeURIComponent(a),a.replace(d,"+")}function b(a){return a=a.replace(e," "),decodeURIComponent(a)}function c(b,d,e){return Array.isArray(e)?e.forEach(function(a){b=c(b,d,a)}):(b.length>0&&(b+="&"),b+=a(d),void 0!==e&&null!==e&&(b+="="+a(e))),b}var d,e;return d=/%20/g,e=/\+/g,{read:function(a){var c={};return a.split("&").forEach(function(a){var d,e,f;d=a.split("="),e=b(d[0]),f=2===d.length?b(d[1]):null,e in c?(Array.isArray(c[e])||(c[e]=[c[e]]),c[e].push(f)):c[e]=f}),c},write:function(a){var b="";return Object.keys(a).forEach(function(d){b=c(b,d,a[d])}),b}}})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{}],56:[function(a,b,c){!function(a){"use strict";a(function(){function a(a){return a&&1===a.nodeType&&"FORM"===a.tagName}function b(a){var b,c=new FormData;for(var d in a)a.hasOwnProperty(d)&&(b=a[d],b instanceof File?c.append(d,b,b.name):b instanceof Blob?c.append(d,b):c.append(d,String(b)));return c}return{write:function(c){if("undefined"==typeof FormData)throw new Error("The multipart/form-data mime serializer requires FormData support");if(c instanceof FormData)return c;if(a(c))return new FormData(c);if("object"==typeof c&&null!==c)return b(c);throw new Error("Unable to create FormData from object "+c)}}})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{}],57:[function(a,b,c){!function(a){"use strict";a(function(){return{read:function(a){return a},write:function(a){return a.toString()}}})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{}],58:[function(a,b,c){!function(a){"use strict";a(function(a){var b=a("./makePromise"),c=a("./Scheduler"),d=a("./env").asap;return b({scheduler:new c(d)})})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{"./Scheduler":59,"./env":71,"./makePromise":73}],59:[function(a,b,c){!function(a){"use strict";a(function(){function a(a){this._async=a,this._running=!1,this._queue=this,this._queueLen=0,this._afterQueue={},this._afterQueueLen=0;var b=this;this.drain=function(){b._drain()}}return a.prototype.enqueue=function(a){this._queue[this._queueLen++]=a,this.run()},a.prototype.afterQueue=function(a){this._afterQueue[this._afterQueueLen++]=a,this.run()},a.prototype.run=function(){this._running||(this._running=!0,this._async(this.drain))},a.prototype._drain=function(){for(var a=0;a>>0,j=i,k=[],l=0;i>l;++l)if(f=b[l],void 0!==f||l in b){if(e=a._handler(f),e.state()>0){h.become(e),a._visitRemaining(b,l,e);break}e.visit(h,c,d)}else--j;return 0===j&&h.reject(new RangeError("any(): array must not be empty")),g}function e(b,c){function d(a){this.resolved||(k.push(a),0===--n&&(l=null,this.resolve(k)))}function e(a){this.resolved||(l.push(a),0===--f&&(k=null,this.reject(l)))}var f,g,h,i=a._defer(),j=i._handler,k=[],l=[],m=b.length>>>0,n=0;for(h=0;m>h;++h)g=b[h],(void 0!==g||h in b)&&++n;for(c=Math.max(c,0),f=n-c+1,n=Math.min(c,n),c>n?j.reject(new RangeError("some(): array must contain at least "+c+" item(s), but had "+n)):0===n&&j.resolve(k),h=0;m>h;++h)g=b[h],(void 0!==g||h in b)&&a._handler(g).visit(j,d,e,j.notify);return i}function f(b,c){return a._traverse(c,b)}function g(b,c){var d=s.call(b);return a._traverse(c,d).then(function(a){return h(d,a)})}function h(b,c){for(var d=c.length,e=new Array(d),f=0,g=0;d>f;++f)c[f]&&(e[g++]=a._handler(b[f]).value);return e.length=g,e}function i(a){return p(a.map(j))}function j(c){var d=a._handler(c);return 0===d.state()?o(c).then(b.fulfilled,b.rejected):(d._unreport(),b.inspect(d))}function k(a,b){return arguments.length>2?q.call(a,m(b),arguments[2]):q.call(a,m(b))}function l(a,b){return arguments.length>2?r.call(a,m(b),arguments[2]):r.call(a,m(b))}function m(a){return function(b,c,d){return n(a,void 0,[b,c,d])}}var n=c(a),o=a.resolve,p=a.all,q=Array.prototype.reduce,r=Array.prototype.reduceRight,s=Array.prototype.slice;return a.any=d,a.some=e,a.settle=i,a.map=f,a.filter=g,a.reduce=k,a.reduceRight=l,a.prototype.spread=function(a){return this.then(p).then(function(b){return a.apply(this,b)})},a}})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{"../apply":61,"../state":74}],63:[function(a,b,c){!function(a){"use strict";a(function(){function a(){throw new TypeError("catch predicate must be a function")}function b(a,b){return c(b)?a instanceof b:b(a)}function c(a){return a===Error||null!=a&&a.prototype instanceof Error}function d(a){return("object"==typeof a||"function"==typeof a)&&null!==a}function e(a){return a}return function(c){function f(a,c){return function(d){return b(d,c)?a.call(this,d):j(d)}}function g(a,b,c,e){var f=a.call(b);return d(f)?h(f,c,e):c(e)}function h(a,b,c){return i(a).then(function(){return b(c)})}var i=c.resolve,j=c.reject,k=c.prototype["catch"];return c.prototype.done=function(a,b){this._handler.visit(this._handler.receiver,a,b)},c.prototype["catch"]=c.prototype.otherwise=function(b){return arguments.length<2?k.call(this,b):"function"!=typeof b?this.ensure(a):k.call(this,f(arguments[1],b))},c.prototype["finally"]=c.prototype.ensure=function(a){return"function"!=typeof a?this:this.then(function(b){return g(a,this,e,b)},function(b){return g(a,this,j,b)})},c.prototype["else"]=c.prototype.orElse=function(a){return this.then(void 0,function(){return a})},c.prototype["yield"]=function(a){return this.then(function(){return a})},c.prototype.tap=function(a){return this.then(a)["yield"](this)},c}})}("function"==typeof define&&define.amd?define:function(a){b.exports=a()})},{}],64:[function(a,b,c){!function(a){"use strict";a(function(){return function(a){return a.prototype.fold=function(b,c){var d=this._beget();return this._handler.fold(function(c,d,e){a._handler(c).fold(function(a,c,d){d.resolve(b.call(this,c,a))},d,this,e)},c,d._handler.receiver,d._handler),d},a}})}("function"==typeof define&&define.amd?define:function(a){b.exports=a()})},{}],65:[function(a,b,c){!function(a){"use strict";a(function(a){var b=a("../state").inspect;return function(a){return a.prototype.inspect=function(){return b(a._handler(this))},a}})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{"../state":74}],66:[function(a,b,c){!function(a){"use strict";a(function(){return function(a){function b(a,b,d,e){return c(function(b){return[b,a(b)]},b,d,e)}function c(a,b,e,f){function g(f,g){return d(e(f)).then(function(){return c(a,b,e,g)})}return d(f).then(function(c){return d(b(c)).then(function(b){return b?c:d(a(c)).spread(g)})})}var d=a.resolve;return a.iterate=b,a.unfold=c,a}})}("function"==typeof define&&define.amd?define:function(a){b.exports=a()})},{}],67:[function(a,b,c){!function(a){"use strict";a(function(){return function(a){return a.prototype.progress=function(a){return this.then(void 0,void 0,a)},a}})}("function"==typeof define&&define.amd?define:function(a){b.exports=a()})},{}],68:[function(a,b,c){!function(a){"use strict";a(function(a){function b(a,b,d,e){return c.setTimer(function(){a(d,e,b)},b)}var c=a("../env"),d=a("../TimeoutError");return function(a){function e(a,c,d){b(f,a,c,d)}function f(a,b){b.resolve(a)}function g(a,b,c){var e="undefined"==typeof a?new d("timed out after "+c+"ms"):a;b.reject(e)}return a.prototype.delay=function(a){var b=this._beget();return this._handler.fold(e,a,void 0,b._handler),b},a.prototype.timeout=function(a,d){var e=this._beget(),f=e._handler,h=b(g,a,d,e._handler);return this._handler.visit(f,function(a){c.clearTimer(h),this.resolve(a)},function(a){c.clearTimer(h),this.reject(a)},f.notify),e},a}})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{"../TimeoutError":60,"../env":71}],69:[function(a,b,c){!function(a){"use strict";a(function(a){function b(a){throw a}function c(){}var d=a("../env").setTimer,e=a("../format");return function(a){function f(a){a.handled||(n.push(a),k("Potentially unhandled rejection ["+a.id+"] "+e.formatError(a.value)))}function g(a){var b=n.indexOf(a);b>=0&&(n.splice(b,1),l("Handled previous rejection ["+a.id+"] "+e.formatObject(a.value)))}function h(a,b){m.push(a,b),null===o&&(o=d(i,0))}function i(){for(o=null;m.length>0;)m.shift()(m.shift())}var j,k=c,l=c;"undefined"!=typeof console&&(j=console,k="undefined"!=typeof j.error?function(a){j.error(a)}:function(a){j.log(a)},l="undefined"!=typeof j.info?function(a){j.info(a)}:function(a){j.log(a)}),a.onPotentiallyUnhandledRejection=function(a){h(f,a)},a.onPotentiallyUnhandledRejectionHandled=function(a){h(g,a)},a.onFatalRejection=function(a){h(b,a.value)};var m=[],n=[],o=null;return a}})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{"../env":71,"../format":72}],70:[function(a,b,c){!function(a){"use strict";a(function(){return function(a){return a.prototype["with"]=a.prototype.withThis=function(a){var b=this._beget(),c=b._handler;return c.receiver=a,this._handler.chain(c,a),b},a}})}("function"==typeof define&&define.amd?define:function(a){b.exports=a()})},{}],71:[function(a,b,c){(function(c){!function(a){"use strict";a(function(a){function b(){return"undefined"!=typeof c&&null!==c&&"function"==typeof c.nextTick}function d(){return"function"==typeof MutationObserver&&MutationObserver||"function"==typeof WebKitMutationObserver&&WebKitMutationObserver}function e(a){function b(){var a=c;c=void 0,a()}var c,d=document.createTextNode(""),e=new a(b);e.observe(d,{characterData:!0});var f=0;return function(a){c=a,d.data=f^=1}}var f,g="undefined"!=typeof setTimeout&&setTimeout,h=function(a,b){return setTimeout(a,b)},i=function(a){return clearTimeout(a)},j=function(a){return g(a,0)};if(b())j=function(a){return c.nextTick(a)};else if(f=d())j=e(f);else if(!g){var k=a,l=k("vertx");h=function(a,b){return l.setTimer(b,a)},i=l.cancelTimer,j=l.runOnLoop||l.runOnContext}return{setTimer:h,clearTimer:i,asap:j}})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})}).call(this,a("_process"))},{_process:33}],72:[function(a,b,c){!function(a){"use strict";a(function(){function a(a){var c="object"==typeof a&&null!==a&&a.stack?a.stack:b(a);return a instanceof Error?c:c+" (WARNING: non-Error used)"}function b(a){var b=String(a);return"[object Object]"===b&&"undefined"!=typeof JSON&&(b=c(a,b)),b}function c(a,b){try{return JSON.stringify(a)}catch(c){return b}}return{formatError:a,formatObject:b,tryStringify:c}})}("function"==typeof define&&define.amd?define:function(a){b.exports=a()})},{}],73:[function(a,b,c){(function(a){!function(b){"use strict";b(function(){return function(b){function c(a,b){this._handler=a===u?b:d(a)}function d(a){function b(a){e.resolve(a)}function c(a){e.reject(a)}function d(a){e.notify(a)}var e=new w;try{a(b,c,d)}catch(f){c(f)}return e}function e(a){return J(a)?a:new c(u,new x(r(a)))}function f(a){return new c(u,new x(new A(a)))}function g(){return aa}function h(){return new c(u,new w)}function i(a,b){var c=new w(a.receiver,a.join().context);return new b(u,c)}function j(a){return l(T,null,a)}function k(a,b){return l(O,a,b)}function l(a,b,d){function e(c,e,g){g.resolved||m(d,f,c,a(b,e,c),g)}function f(a,b,c){k[a]=b,0===--j&&c.become(new z(k))}for(var g,h="function"==typeof b?e:f,i=new w,j=d.length>>>0,k=new Array(j),l=0;l0?b(c,f.value,e):(e.become(f),n(a,c+1,f))}else b(c,d,e)}function n(a,b,c){for(var d=b;dc&&a._unreport()}}function p(a){return"object"!=typeof a||null===a?f(new TypeError("non-iterable passed to race()")):0===a.length?g():1===a.length?e(a[0]):q(a)}function q(a){var b,d,e,f=new w;for(b=0;b0||"function"!=typeof b&&0>e)return new this.constructor(u,d);var f=this._beget(),g=f._handler;return d.chain(g,d.receiver,a,b,c),f},c.prototype["catch"]=function(a){return this.then(void 0,a)},c.prototype._beget=function(){return i(this._handler,this.constructor)},c.all=j,c.race=p,c._traverse=k,c._visitRemaining=n,u.prototype.when=u.prototype.become=u.prototype.notify=u.prototype.fail=u.prototype._unreport=u.prototype._report=U,u.prototype._state=0,u.prototype.state=function(){return this._state},u.prototype.join=function(){for(var a=this;void 0!==a.handler;)a=a.handler;return a},u.prototype.chain=function(a,b,c,d,e){this.when({resolver:a,receiver:b,fulfilled:c,rejected:d,progress:e})},u.prototype.visit=function(a,b,c,d){this.chain(Z,a,b,c,d)},u.prototype.fold=function(a,b,c,d){this.when(new I(a,b,c,d))},S(u,v),v.prototype.become=function(a){a.fail()};var Z=new v;S(u,w),w.prototype._state=0,w.prototype.resolve=function(a){this.become(r(a))},w.prototype.reject=function(a){this.resolved||this.become(new A(a))},w.prototype.join=function(){if(!this.resolved)return this;for(var a=this;void 0!==a.handler;)if(a=a.handler,a===this)return this.handler=D();return a},w.prototype.run=function(){var a=this.consumers,b=this.handler;this.handler=this.handler.join(),this.consumers=void 0;for(var c=0;c0?c(d.value):b(d.value)}return{pending:a,fulfilled:c,rejected:b,inspect:d}})}("function"==typeof define&&define.amd?define:function(a){b.exports=a()})},{}],75:[function(a,b,c){!function(a){"use strict";a(function(a){function b(a,b,c,d){var e=x.resolve(a);return arguments.length<2?e:e.then(b,c,d)}function c(a){return new x(a)}function d(a){return function(){for(var b=0,c=arguments.length,d=new Array(c);c>b;++b)d[b]=arguments[b];return y(a,this,d)}}function e(a){for(var b=0,c=arguments.length-1,d=new Array(c);c>b;++b)d[b]=arguments[b+1];return y(a,this,d)}function f(){return new g}function g(){function a(a){d._handler.resolve(a)}function b(a){d._handler.reject(a)}function c(a){d._handler.notify(a)}var d=x._defer();this.promise=d,this.resolve=a,this.reject=b,this.notify=c,this.resolver={resolve:a,reject:b,notify:c}}function h(a){return a&&"function"==typeof a.then}function i(){return x.all(arguments)}function j(a){return b(a,x.all)}function k(a){return b(a,x.settle)}function l(a,c){return b(a,function(a){return x.map(a,c)})}function m(a,c){return b(a,function(a){return x.filter(a,c)})}var n=a("./lib/decorators/timed"),o=a("./lib/decorators/array"),p=a("./lib/decorators/flow"),q=a("./lib/decorators/fold"),r=a("./lib/decorators/inspect"),s=a("./lib/decorators/iterate"),t=a("./lib/decorators/progress"),u=a("./lib/decorators/with"),v=a("./lib/decorators/unhandledRejection"),w=a("./lib/TimeoutError"),x=[o,p,q,s,t,r,u,n,v].reduce(function(a,b){return b(a)},a("./lib/Promise")),y=a("./lib/apply")(x);return b.promise=c,b.resolve=x.resolve,b.reject=x.reject,b.lift=d,b["try"]=e,b.attempt=e,b.iterate=x.iterate,b.unfold=x.unfold,b.join=i,b.all=j,b.settle=k,b.any=d(x.any),b.some=d(x.some),b.race=d(x.race),b.map=l,b.filter=m,b.reduce=d(x.reduce),b.reduceRight=d(x.reduceRight),b.isPromiseLike=h,b.Promise=x,b.defer=f,b.TimeoutError=w,b})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{"./lib/Promise":58,"./lib/TimeoutError":60,"./lib/apply":61,"./lib/decorators/array":62,"./lib/decorators/flow":63,"./lib/decorators/fold":64,"./lib/decorators/inspect":65,"./lib/decorators/iterate":66,"./lib/decorators/progress":67,"./lib/decorators/timed":68,"./lib/decorators/unhandledRejection":69,"./lib/decorators/with":70}],76:[function(a,b,c){!function(a){"use strict";a(function(){return{findProperties:function a(b,c,d){"object"==typeof b&&null!==b&&(c in b&&d(b[c],b,c),Object.keys(b).forEach(function(e){a(b[e],c,d)}))}}})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{}],77:[function(a,b,c){!function(a){"use strict";a(function(a){function b(a){var b,d,e,f,g;return b=c.defer(),d=!1,e=b.resolver,f=b.promise,g=f.then,f.then=function(){return d||(d=!0,c.attempt(a).then(e.resolve,e.reject)),g.apply(f,arguments)},f}var c;return c=a("when"),b})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{when:75}],78:[function(a,b,c){!function(a){"use strict";a(function(){function a(a){var c,d,e,f;for(a||(a={}),c=1,d=arguments.length;d>c;c+=1){e=arguments[c];for(f in e)f in a&&(a[f]===e[f]||f in b&&b[f]===e[f])||(a[f]=e[f])}return a}var b={};return a})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{}],79:[function(a,b,c){!function(a){"use strict";a(function(){function a(a){return a.toLowerCase().split("-").map(function(a){return a.charAt(0).toUpperCase()+a.slice(1)}).join("-")}return a})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{}],80:[function(a,b,c){!function(a){"use strict";a(function(a){function b(a,b){return a.then(function(a){return a&&a[b]},function(a){return j.reject(a&&a[b])})}function c(){return b(this,"entity")}function d(){return b(b(this,"status"),"code")}function e(){return b(this,"headers")}function f(a){return a=k(a),b(this.headers(),a)}function g(a){return a=[].concat(a),h(j.reduce(a,function(a,b){if("string"==typeof b&&(b={rel:b}),"function"!=typeof a.entity.clientFor)throw new Error("Hypermedia response expected");var c=a.entity.clientFor(b.rel);return c({params:b.params})},this))}function h(a){return a.status=d,a.headers=e,a.header=f,a.entity=c,a.follow=g,a}function i(){return h(j.apply(j,arguments))}var j=a("when"),k=a("./normalizeHeaderName");return i.make=h,i.reject=function(a){return h(j.reject(a))},i.promise=function(a){return h(j.promise(a))},i})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{"./normalizeHeaderName":79,when:75}],81:[function(a,b,c){!function(a){"use strict";a(function(){function a(a,b){if("string"!=typeof a)throw new Error("String required for URL encoding");return a.split("").map(function(a){if(b.hasOwnProperty(a))return a;var c=a.charCodeAt(0);return 127>=c?"%"+c.toString(16).toUpperCase():encodeURIComponent(a).toUpperCase()}).join("")}function b(b){return b=b||d.unreserved,function(c){return a(c,b)}}function c(a){return decodeURIComponent(a)}var d;return d=function(){var a={alpha:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",digit:"0123456789"};return a.genDelims=":/?#[]@",a.subDelims="!$&'()*+,;=",a.reserved=a.genDelims+a.subDelims,a.unreserved=a.alpha+a.digit+"-._~",a.url=a.reserved+a.unreserved,a.scheme=a.alpha+a.digit+"+-.",a.userinfo=a.unreserved+a.subDelims+":",a.host=a.unreserved+a.subDelims,a.port=a.digit,a.pchar=a.unreserved+a.subDelims+":@",a.segment=a.pchar,a.path=a.segment+"/",a.query=a.pchar+"/?",a.fragment=a.pchar+"/?",Object.keys(a).reduce(function(b,c){return b[c]=a[c].split("").reduce(function(a,b){return a[b]=!0,a},{}),b},{})}(),{decode:c,encode:b(),encodeURL:b(d.url),encodeScheme:b(d.scheme),encodeUserInfo:b(d.userinfo),encodeHost:b(d.host),encodePort:b(d.port),encodePathSegment:b(d.segment),encodePath:b(d.path),encodeQuery:b(d.query),encodeFragment:b(d.fragment)}})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{}],82:[function(a,b,c){!function(a){"use strict";var b;a(function(a){function c(a,c,d){return c.split(",").reduce(function(c,e){var g,i;if(g={},"*"===e.slice(-1)&&(e=e.slice(0,-1),g.explode=!0),h.test(e)){var j=h.exec(e);e=j[1],g.maxLength=parseInt(j[2])}return e=f.decode(e),i=d[e],i===b||null===i?c:("string"==typeof i?(g.maxLength&&(i=i.slice(0,g.maxLength)),c+=c.length?a.separator:a.first,a.named&&(c+=a.encoder(e),c+=i.length?"=":a.empty),c+=a.encoder(i)):c+=Array.isArray(i)?i.reduce(function(b,c){return b.length?(b+=g.explode?a.separator:",",a.named&&g.explode&&(b+=a.encoder(e),b+=c.length?"=":a.empty)):(b+=a.first,a.named&&(b+=a.encoder(e),b+=c.length?"=":a.empty)),b+=a.encoder(c)},""):Object.keys(i).reduce(function(b,c){return b.length?b+=g.explode?a.separator:",":(b+=a.first,a.named&&!g.explode&&(b+=a.encoder(e),b+=i[c].length?"=":a.empty)),b+=a.encoder(c),b+=g.explode?"=":",",b+=a.encoder(i[c])},""),c)},"")}function d(a,b){var d;if(d=g[a.slice(0,1)],d?a=a.slice(1):d=g[""],d.reserved)throw new Error("Reserved expression operations are not supported");return c(d,a,b)}function e(a,b){var c,e,f;for(f="",e=0;;){if(c=a.indexOf("{",e),-1===c){f+=a.slice(e);break}f+=a.slice(e,c),e=a.indexOf("}",c)+1,f+=d(a.slice(c+1,e-1),b)}return f}var f,g,h;return f=a("./uriEncoder"),h=/^([^:]*):([0-9]+)$/,g={"":{first:"",separator:",",named:!1,empty:"",encoder:f.encode},"+":{first:"",separator:",",named:!1,empty:"",encoder:f.encodeURL},"#":{first:"#",separator:",",named:!1,empty:"",encoder:f.encodeURL},".":{first:".",separator:".",named:!1,empty:"",encoder:f.encode},"/":{first:"/",separator:"/",named:!1,empty:"",encoder:f.encode},";":{first:";",separator:";",named:!0,empty:"",encoder:f.encode},"?":{first:"?",separator:"&",named:!0,empty:"=",encoder:f.encode},"&":{first:"&",separator:"&",named:!0,empty:"=",encoder:f.encode},"=":{reserved:!0},",":{reserved:!0},"!":{reserved:!0},"@":{reserved:!0},"|":{reserved:!0}},{expand:e}})}("function"==typeof define&&define.amd?define:function(c){b.exports=c(a)})},{"./uriEncoder":81}]},{},[1]); \ No newline at end of file diff --git a/test/index.html b/test/index.html index 2b2740f..3b8bed9 100644 --- a/test/index.html +++ b/test/index.html @@ -1,726 +1,26 @@ - - - - - - - - -Open browser development tools to see results of tests. - - - - \ No newline at end of file + + + + + + + + + + +
    +
    +
    +
    + + + + + + + diff --git a/test/index.js b/test/index.js new file mode 100644 index 0000000..fc427a3 --- /dev/null +++ b/test/index.js @@ -0,0 +1,372 @@ +var chai, + expect, + JOQULAR; +if(typeof(window)==="undefined") { + chai = require("chai"); + expect = chai.expect; + JOQULAR = require("../index.js"); +} + +const now = new Date(), + notnow = new Date(); + testobject = { + name:"joe", + age:27, + size: 10, + ip: "127.0.0.0", + ssn: "555-55-5555", + race:"caucasian", + favoriteNumbers:[1,7,13], + mixedArray:[1,1,true,undefined], + email:"someone@somewhere.com", + data: [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20], + unneeded: "redact me", + now: now + }, + testvalidator = (object) => { + chai.expect(object.name).equal("joe"); + chai.expect(object.age).equal(27); + chai.expect(object.race).equal("caucasian"); + }; + +const ms = now.getMilliseconds(); +notnow.setMilliseconds(ms===999 ? 0 : ms+1); +const seconds = now.getUTCSeconds(); +notnow.setUTCSeconds(seconds===59 ? 0 : seconds+1); +const minutes = now.getUTCMinutes(); +notnow.setUTCMinutes(minutes===59 ? 0 : minutes+1); +const hours = now.getUTCHours(); +notnow.setUTCHours(hours===23 ? 0 : hours+1); +const mo = now.getUTCMonth(); +notnow.setUTCMonth(mo===11 ? 0 : mo+1); +const date = now.getUTCDate(); +notnow.setUTCDate(date>28 ? 0 : date+1); +const yr = now.getUTCFullYear(); +notnow.setUTCFullYear(yr+1); + + +describe("Test",function() { + it("double property",function() { + return JOQULAR.match({name:"joe",age:27},testobject) + .then(object => testvalidator(object)) + }); + it("inline property",function() { + return JOQULAR.match({[key => key==="age"]:{$lt:28}},testobject) + .then(object => testvalidator(object)) + }); + it("inline value true",function() { + return JOQULAR.match({age:value => value < 28},testobject) + .then(object => testvalidator(object)) + }); + it("inline value false",function() { + return JOQULAR.match({age:value => value < 27},testobject) + .then(object => testvalidator(object)).catch(() => true); + }); + it("functional key",function() { + return JOQULAR.match({[key => key==="name"]:{$typeof:"string"}},testobject) + .then(object => testvalidator(object)) + }); + it("RegExp key",function() { + return JOQULAR.match({[/.*name/]:{$eq: "joe"}},{name:"joe",age:27,race:"caucasian"}) + .then(object => testvalidator(object)) + }); + xit("$",function() { + return JOQULAR.match({name:{$:value=>value==="joe"}},testobject).then(object => { testvalidator(object); }) + }); + it("$lt",function() { + return JOQULAR.match({age:{$lt:28}},testobject).then(object => testvalidator(object)) + }); + it("$lt fail",function(done) { + JOQULAR.match({age:{$lt:27}},testobject).then(object => testvalidator(object)).catch(()=>done()) + }); + it("$lte",function() { + return JOQULAR.match({age:{$lte:27}},testobject).then(object => testvalidator(object)) + }); + it("$lte fail",function(done) { + JOQULAR.match({age:{$lte:26}},testobject).then(object => testvalidator(object)).catch(()=>done()) + }); + it("$eq",function() { + return JOQULAR.match({age:{$eq:27}},testobject).then(object => testvalidator(object)) + }); + it("$eq fail",function(done) { + JOQULAR.match({age:{$eq:26}},testobject).then(object => testvalidator(object)).catch(()=>done()) + }); + it("$eq string",function() { + return JOQULAR.match({age:{$eq:"27"}},testobject).then(object => testvalidator(object)) + }); + it("$eq string fail",function(done) { + JOQULAR.match({age:{$eq:"26"}},testobject).then(object => testvalidator(object)).catch(()=>done()) + }); + it("$eeq",function() { + return JOQULAR.match({age:{$eeq:27}},testobject).then(object => testvalidator(object)) + }); + it("$eeq fail",function(done) { + JOQULAR.match({age:{$eeq:28}},testobject).then(object => testvalidator(object)).catch(()=>done()) + }); + it("$neq string",function() { + return JOQULAR.match({age:{$neq:"5"}},testobject).then(object => testvalidator(object)) + }); + it("$neq string fail",function(done) { + JOQULAR.match({age:{$neq:"27"}},testobject).then(object => testvalidator(object)).catch(()=>done()) + }); + it("$neeq",function() { + return JOQULAR.match({age:{$neeq:5}},testobject).then(object => testvalidator(object)) + }); + it("$neeq fail",function(done) { + JOQULAR.match({age:{$neeq:27}},testobject).then(object => testvalidator(object)).catch(() =>done()) + }); + it("$between",function() { + return JOQULAR.match({age:{$between:[26,28]}},testobject).then(object => testvalidator(object)) + }); + it("$between fail",function(done) { + JOQULAR.match({age:{$between:[30,31]}},testobject).then(object => testvalidator(object)).catch(() =>done()) + }); + it("$between inclusive",function() { + return JOQULAR.match({age:{$between:[27,28,true]}},testobject).then(object => testvalidator(object)) + }); + it("$between inclusive fail",function(done) { + JOQULAR.match({age:{$between:[30,318,true]}},testobject).then(object => testvalidator(object)).catch(() =>done()) + }); + it("$outside higher",function() { + return JOQULAR.match({age:{$outside:[25,26]}},testobject).then(object => testvalidator(object)) + }); + it("$outside higher fail",function(done) { + JOQULAR.match({age:{$outside:[25,28]}},testobject).then(object => testvalidator(object)).catch(() =>done()) + }); + it("$outside lower",function() { + return JOQULAR.match({age:{$outside:[28,29]}},testobject).then(object => testvalidator(object)) + }); + it("$outside lower fail",function(done) { + JOQULAR.match({age:{$outside:[26,29]}},testobject).then(object => testvalidator(object)).catch(() =>done()) + }); + it("$gte",function() { + return JOQULAR.match({age:{$gte:27}},testobject).then(object => testvalidator(object)) + }); + it("$gte fail",function(done) { + JOQULAR.match({age:{$gte:28}},testobject).then(object => testvalidator(object)).catch(() =>done()) + }); + it("$gt",function() { + return JOQULAR.match({age:{$gt:26}},testobject).then(object => testvalidator(object)) + }); + it("$gt fail",function(done) { + JOQULAR.match({age:{$gt:28}},testobject).then(object => testvalidator(object)).catch(() =>done()) + }); + it("$instanceof by string",function() { + return JOQULAR.match({favoriteNumbers:{$instanceof:"Array"}},testobject).then(object => testvalidator(object)) + }); + it("$instanceof by string fail",function(done) { + JOQULAR.match({favoriteNumbers:{$instanceof:"Function"}},testobject).then(object => testvalidator(object)).catch(() =>done()) + }); + it("$instanceof by constructor",function() { + return JOQULAR.match({favoriteNumbers:{$instanceof:Array}},testobject).then(object => testvalidator(object)) + }); + it("$instanceof by constructor fail",function(done) { + JOQULAR.match({favoriteNumbers:{$instanceof:Function}},testobject).then(object => testvalidator(object)).catch(() =>done()) + }); + it("$isArray",function() { + return JOQULAR.match({favoriteNumbers:{$isArray:null}},testobject).then(object => testvalidator(object)) + }); + it("$isArray fail",function(done) { + JOQULAR.match({age:{$isArray:null}},testobject).then(object => testvalidator(object)).catch(() =>done()) + }); + it("$isEmail",function() { + return JOQULAR.match({email:{$isEmail:null}},testobject).then(object => testvalidator(object)) + }); + it("$isEmail fail",function(done) { + JOQULAR.match({name:{$isEmail:null}},testobject).then(object => testvalidator(object)).catch(() =>done()) + }); + it("$isEven",function() { + return JOQULAR.match({size:{$isEven:null}},testobject).then(object => testvalidator(object)) + }); + it("$isEven fail",function(done) { + JOQULAR.match({age:{$isEven:null}},testobject).then(object => testvalidator(object)).catch(() =>done()) + }); + it("$isIPAddress",function() { + return JOQULAR.match({ip:{$isIPAddress:null}},testobject).then(object => testvalidator(object)) + }); + it("$isIPAddress fail",function(done) { + JOQULAR.match({age:{$isIPAddress:null}},testobject).then(object => testvalidator(object)).catch(() =>done()) + }); + it("$isOdd",function() { + return JOQULAR.match({age:{$isOdd:null}},testobject).then(object => testvalidator(object)) + }); + it("$isOdd fail",function(done) { + JOQULAR.match({size:{$isOdd:null}},testobject).then(object => testvalidator(object)).catch(() =>done()) + }); + it("$isSSN",function() { + return JOQULAR.match({ssn:{$isSSN:null}},testobject).then(object => testvalidator(object)) + }); + it("$isSSN fail",function(done) { + JOQULAR.match({name:{$isSSN:null}},testobject).then(object => testvalidator(object)).catch(() =>done()) + }); + for(const key of ["date","day","fullYear","hours","milliseconds","minutes","month","seconds","time","UTCDate","UTCDay","UTCFullYear","UTCHours","UTCSeconds","UTCMilliseconds","UTCMinutes","UTCMonth","year"]) { + it(`\$${key}`,function() { + return JOQULAR.match({now:{["$"+key]:now}},testobject).then(object => testvalidator(object)) + }); + if(key.startsWith("UTC")) { + it(`\$${key} fail`,function(done) { + JOQULAR.match({now:{["$"+key]:notnow}},testobject).then(object => testvalidator(object)).catch(() =>done()) + }); + } + } + it("$min",function() { + return JOQULAR.match({favoriteNumbers:{$min:"minFavorite"}},testobject) + .then(object => { testvalidator(object); chai.expect(object.minFavorite).equal(1); }) + }); + it("$min fail",function(done) { + JOQULAR.match({favoriteNumbers:{$min:"minFavorite"}},testobject) + .then(object => { testvalidator(object); chai.expect(object.minFavorite).equal(2); }).catch(() =>done()) + }); + it("$avg",function() { + return JOQULAR.match({favoriteNumbers:{$avg:"avgFavorite"}},testobject) + .then(object => { testvalidator(object); chai.expect(object.avgFavorite).equal(7); }) + }); + it("$avg fail",function(done) { + JOQULAR.match({favoriteNumbers:{$avg:"avgFavorite"}},testobject) + .then(object => { testvalidator(object); chai.expect(object.avgFavorite).equal(6); }).catch(() =>done()) + }); + it("$max",function() { + return JOQULAR.match({favoriteNumbers:{$max:"maxFavorite"}},testobject) + .then(object => { testvalidator(object); chai.expect(object.maxFavorite).equal(13); }) + }); + it("$max fail",function(done) { + JOQULAR.match({favoriteNumbers:{$max:"maxFavorite"}},testobject) + .then(object => { testvalidator(object); chai.expect(object.maxFavorite).equal(7); }).catch(() =>done()) + }); + it("$count",function() { + return JOQULAR.match({favoriteNumbers:{$count:"countFavorite"}},testobject) + .then(object => { testvalidator(object); chai.expect(object.countFavorite).equal(3); }) + }); + it("$count fail",function(done) { + JOQULAR.match({favoriteNumbers:{$count:"countFavorite"}},testobject) + .then(object => { testvalidator(object); chai.expect(object.countFavorite).equal(4); }).catch(() =>done()) + }); + it("$mina",function() { + return JOQULAR.match({mixedArray:{$min:"minFavorite"}},testobject) + .then(object => { testvalidator(object); chai.expect(object.minFavorite).equal(1); }) + }); + it("$mina fail",function(done) { + JOQULAR.match({mixedArray:{$min:"minFavorite"}},testobject) + .then(object => { testvalidator(object); chai.expect(object.minFavorite).equal(2); }).catch(() =>done()) + }); + it("$avga",function() { + return JOQULAR.match({mixedArray:{$avga:"avg"}},testobject) + .then(object => { testvalidator(object); chai.expect(object.avg).equal(1); }) + }); + it("$avga fail",function(done) { + JOQULAR.match({mixedArray:{$avga:"avg"}},testobject) + .then(object => { testvalidator(object); chai.expect(object.avg).equal(2); }).catch(() =>done()) + }); + it("$maxa",function() { + return JOQULAR.match({mixedArray:{$maxa:"max"}},testobject) + .then(object => { testvalidator(object); chai.expect(object.max).equal(1); }) + }); + it("$maxa fail",function(done) { + JOQULAR.match({mixedArray:{$maxa:"max"}},testobject) + .then(object => { testvalidator(object); chai.expect(object.max).equal(2); }).catch(() =>done()) + }); + it("$counta",function() { + return JOQULAR.match({mixedArray:{$counta:"count"}},testobject) + .then(object => { testvalidator(object); chai.expect(object.count).equal(4); }) + }); + it("$counta fail",function(done) { + JOQULAR.match({mixedArray:{$counta:"count"}},testobject) + .then(object => { testvalidator(object); chai.expect(object.count).equal(5); }).catch(() =>done()) + }); + it("$count mixed",function() { + return JOQULAR.match({mixedArray:{$count:"count"}},testobject) + .then(object => { testvalidator(object); chai.expect(object.count).equal(3); }) + }); + it("$as",function() { + return JOQULAR.match({size:{$as:"Size"}},testobject) + .then(object => { chai.expect(object.Size).equal(10); }) + }); + it("$compute",function() { + return JOQULAR.match({computed:{$compute:()=>1}},testobject) + .then(object => { testvalidator(object); chai.expect(object.computed).equal(1); }) + }); + it("$filter",function() { + return JOQULAR.match({mixedArray:{$filter:(item)=>item!==undefined}},testobject) + .then(object => { testvalidator(object); chai.expect(object.mixedArray.length).equal(3); }) + }); + it("$sort",function() { + return JOQULAR.match({favoriteNumbers:{$sort:(a,b)=> b - a}},testobject) + .then(object => { testvalidator(object); chai.expect(object.favoriteNumbers[0]).equal(13); }) + }); + it("$sample",function() { + return JOQULAR.match({data:{$sample:[.5,5]}},testobject) + .then(object => { + testvalidator(object); + chai.expect(object.data.length).equal(5); + }) + }); + it("$echoes",function() { + return JOQULAR.match({name:{$echoes:"jo"}},testobject) + .then(object => { testvalidator(object); }) + }); + it("$echoes fail",function(done) { + JOQULAR.match({name:{$echoes:"bill"}},testobject) + .then(object => { testvalidator(object); }).catch(() =>done()) + }); + it("$typeof",function() { + return JOQULAR.match({name:{$typeof:"string"}},testobject) + .then(object => { testvalidator(object); }) + }); + it("$typeof fail",function(done) { + JOQULAR.match({name:{$typeof:"number"}},testobject) + .then(object => { testvalidator(object); }).catch(() =>done()) + }); + it("$and",function() { + return JOQULAR.match({name:{$and:{$typeof:"string",$:(value) => value.length===3}}},testobject) + .then(object => { testvalidator(object); }) + }); + it("$or",function() { + return JOQULAR.match({name:{$or:{$typeof:"string",$:(value) => value.length===3}}},testobject) + .then(object => { testvalidator(object); }) + }); + it("$xor",function(done) { + JOQULAR.match({name:{$xor:{$typeof:"string",$and:{$typeof:"number"}}}},testobject) + .then(object => { testvalidator(object); }) + .catch(() =>done()) + }); + it("$xor fail direct",function(done) { + JOQULAR.match({name:{$xor:{$typeof:"string",$:(value) => value.length===3}}},testobject) + .then(object => { testvalidator(object); }) + .catch(() =>done()) + }); + it("$xor fail indirect",function(done) { + JOQULAR.match({name:{$xor:{$typeof:"string",$and:{$typeof:"string"}}}},testobject) + .then(object => { testvalidator(object); }) + .catch(() =>done()) + }); + it("$redact",function() { + return JOQULAR.match({unneeded:{$redact:null}},testobject) + .then(object => { testvalidator(object); chai.expect(object.unneeded).equal(undefined); }) + }); + it("$some",function() { + return JOQULAR.match({favoriteNumbers:{$some:(value) => value===13}},testobject) + .then(object => { testvalidator(object); }) + }); + it("$some fail",function(done) { + JOQULAR.match({favoriteNumbers:{$some:(value) => value===20}},testobject) + .then(object => { testvalidator(object); }) + .catch(() =>done()) + }); + it("$every",function() { + return JOQULAR.match({favoriteNumbers:{$every:(value) => value>0}},testobject) + .then(object => { testvalidator(object); }) + }); + it("$every fail",function(done) { + JOQULAR.match({favoriteNumbers:{$every:(value) => value>13}},testobject) + .then(object => { testvalidator(object); }) + .catch(() =>done()) + }); + it("$reduce",function() { + return JOQULAR.match({favoriteNumbers:{$reduce:[(accum,value) => accum += value,0,"sum"]}},testobject) + .then(object => { testvalidator(object); chai.expect(object.sum).equal(21); }) + }); + it("$map",function() { + return JOQULAR.match({favoriteNumbers:{$map:[(value) => value,"mapped"]}},testobject) + .then(object => { testvalidator(object); chai.expect(object.mapped.length).equal(3); }) + }); +}); \ No newline at end of file diff --git a/test/object-observe.js b/test/object-observe.js deleted file mode 100644 index cc07c22..0000000 --- a/test/object-observe.js +++ /dev/null @@ -1,739 +0,0 @@ -/*! - * Object.observe polyfill - v0.2.4 - * by Massimo Artizzu (MaxArt2501) - * - * https://github.com/MaxArt2501/object-observe - * - * Licensed under the MIT License - * See LICENSE for details - */ - -// Some type definitions -/** - * This represents the data relative to an observed object - * @typedef {Object} ObjectData - * @property {Map} handlers - * @property {String[]} properties - * @property {*[]} values - * @property {Descriptor[]} descriptors - * @property {Notifier} notifier - * @property {Boolean} frozen - * @property {Boolean} extensible - * @property {Object} proto - */ -/** - * Function definition of a handler - * @callback Handler - * @param {ChangeRecord[]} changes -*/ -/** - * This represents the data relative to an observed object and one of its - * handlers - * @typedef {Object} HandlerData - * @property {Map} observed - * @property {ChangeRecord[]} changeRecords - */ -/** - * @typedef {Object} ObservedData - * @property {String[]} acceptList - * @property {ObjectData} data -*/ -/** - * Type definition for a change. Any other property can be added using - * the notify() or performChange() methods of the notifier. - * @typedef {Object} ChangeRecord - * @property {String} type - * @property {Object} object - * @property {String} [name] - * @property {*} [oldValue] - * @property {Number} [index] - */ -/** - * Type definition for a notifier (what Object.getNotifier returns) - * @typedef {Object} Notifier - * @property {Function} notify - * @property {Function} performChange - */ -/** - * Function called with Notifier.performChange. It may optionally return a - * ChangeRecord that gets automatically notified, but `type` and `object` - * properties are overridden. - * @callback Performer - * @returns {ChangeRecord|undefined} - */ - -Object.observe || (function(O, A, root) { - "use strict"; - - /** - * Relates observed objects and their data - * @type {Map>} - */ - handlers, - - defaultAcceptList = [ "add", "update", "delete", "reconfigure", "setPrototype", "preventExtensions" ]; - - // Functions for internal usage - - /** - * Checks if the argument is an Array object. Polyfills Array.isArray. - * @function isArray - * @param {?*} object - * @returns {Boolean} - */ - var isArray = A.isArray || (function(toString) { - return function (object) { return toString.call(object) === "[object Array]"; }; - })(O.prototype.toString), - - /** - * Returns the index of an item in a collection, or -1 if not found. - * Uses the generic Array.indexOf or Array.prototype.indexOf if available. - * @function inArray - * @param {Array} array - * @param {*} pivot Item to look for - * @param {Number} [start=0] Index to start from - * @returns {Number} - */ - inArray = A.prototype.indexOf ? A.indexOf || function(array, pivot, start) { - return A.prototype.indexOf.call(array, pivot, start); - } : function(array, pivot, start) { - for (var i = start || 0; i < array.length; i++) - if (array[i] === pivot) - return i; - return -1; - }, - - /** - * Returns an instance of Map, or a Map-like object is Map is not - * supported or doesn't support forEach() - * @function createMap - * @returns {Map} - */ - createMap = typeof root.Map === "undefined" || !Map.prototype.forEach ? function() { - // Lightweight shim of Map. Lacks clear(), entries(), keys() and - // values() (the last 3 not supported by IE11, so can't use them), - // it doesn't handle the constructor's argument (like IE11) and of - // course it doesn't support for...of. - // Chrome 31-35 and Firefox 13-24 have a basic support of Map, but - // they lack forEach(), so their native implementation is bad for - // this polyfill. (Chrome 36+ supports Object.observe.) - var keys = [], values = []; - - return { - size: 0, - has: function(key) { return inArray(keys, key) > -1; }, - get: function(key) { return values[inArray(keys, key)]; }, - set: function(key, value) { - var i = inArray(keys, key); - if (i === -1) { - keys.push(key); - values.push(value); - this.size++; - } else values[i] = value; - }, - "delete": function(key) { - var i = inArray(keys, key); - if (i > -1) { - keys.splice(i, 1); - values.splice(i, 1); - this.size--; - } - }, - forEach: function(callback/*, thisObj*/) { - for (var i = 0; i < keys.length; i++) - callback.call(arguments[1], values[i], keys[i], this); - } - }; - } : function() { return new Map(); }, - - /** - * Simple shim for Object.getOwnPropertyNames when is not available - * Misses checks on object, don't use as a replacement of Object.keys/getOwnPropertyNames - * @function getProps - * @param {Object} object - * @returns {String[]} - */ - getProps = O.getOwnPropertyNames ? (function() { - var func = O.getOwnPropertyNames; - try { - arguments.callee; - } catch (e) { - // Strict mode is supported - - // In strict mode, we can't access to "arguments", "caller" and - // "callee" properties of functions. Object.getOwnPropertyNames - // returns [ "prototype", "length", "name" ] in Firefox; it returns - // "caller" and "arguments" too in Chrome and in Internet - // Explorer, so those values must be filtered. - var avoid = (func(inArray).join(" ") + " ").replace(/prototype |length |name /g, "").slice(0, -1).split(" "); - if (avoid.length) func = function(object) { - var props = O.getOwnPropertyNames(object); - if (typeof object === "function") - for (var i = 0, j; i < avoid.length;) - if ((j = inArray(props, avoid[i++])) > -1) - props.splice(j, 1); - - return props; - }; - } - return func; - })() : function(object) { - // Poor-mouth version with for...in (IE8-) - var props = [], prop, hop; - if ("hasOwnProperty" in object) { - for (prop in object) - if (object.hasOwnProperty(prop)) - props.push(prop); - } else { - hop = O.hasOwnProperty; - for (prop in object) - if (hop.call(object, prop)) - props.push(prop); - } - - // Inserting a common non-enumerable property of arrays - if (isArray(object)) - props.push("length"); - - return props; - }, - - /** - * Return the prototype of the object... if defined. - * @function getPrototype - * @param {Object} object - * @returns {Object} - */ - getPrototype = O.getPrototypeOf, - - /** - * Return the descriptor of the object... if defined. - * IE8 supports a (useless) Object.getOwnPropertyDescriptor for DOM - * nodes only, so defineProperties is checked instead. - * @function getDescriptor - * @param {Object} object - * @param {String} property - * @returns {Descriptor} - */ - getDescriptor = O.defineProperties && O.getOwnPropertyDescriptor, - - /** - * Sets up the next check and delivering iteration, using - * requestAnimationFrame or a (close) polyfill. - * @function nextFrame - * @param {function} func - * @returns {number} - */ - nextFrame = root.requestAnimationFrame || root.webkitRequestAnimationFrame || (function() { - var initial = +new Date, - last = initial; - return function(func) { - return setTimeout(function() { - func((last = +new Date) - initial); - }, 17); - }; - })(), - - /** - * Sets up the observation of an object - * @function doObserve - * @param {Object} object - * @param {Handler} handler - * @param {String[]} [acceptList] - */ - doObserve = function(object, handler, acceptList) { - - var data = observed.get(object); - - if (data) - setHandler(object, data, handler, acceptList); - else { - data = createObjectData(object); - setHandler(object, data, handler, acceptList); - - if (observed.size === 1) - // Let the observation begin! - nextFrame(runGlobalLoop); - } - }, - - /** - * Creates the initial data for an observed object - * @function createObjectData - * @param {Object} object - */ - createObjectData = function(object, data) { - var props = getProps(object), - values = [], descs, i = 0, - data = { - handlers: createMap(), - frozen: O.isFrozen ? O.isFrozen(object) : false, - extensible: O.isExtensible ? O.isExtensible(object) : true, - proto: getPrototype && getPrototype(object), - properties: props, - values: values, - notifier: retrieveNotifier(object, data) - }; - - if (getDescriptor) { - descs = data.descriptors = []; - while (i < props.length) { - descs[i] = getDescriptor(object, props[i]); - values[i] = object[props[i++]]; - } - } else while (i < props.length) - values[i] = object[props[i++]]; - - observed.set(object, data); - - return data; - }, - - /** - * Performs basic property value change checks on an observed object - * @function performPropertyChecks - * @param {ObjectData} data - * @param {Object} object - * @param {String} [except] Doesn't deliver the changes to the - * handlers that accept this type - */ - performPropertyChecks = (function() { - var updateCheck = getDescriptor ? function(object, data, idx, except, descr) { - var key = data.properties[idx], - value = object[key], - ovalue = data.values[idx], - odesc = data.descriptors[idx]; - - if ("value" in descr && (ovalue === value - ? ovalue === 0 && 1/ovalue !== 1/value - : ovalue === ovalue || value === value)) { - addChangeRecord(object, data, { - name: key, - type: "update", - object: object, - oldValue: ovalue - }, except); - data.values[idx] = value; - } - if (odesc.configurable && (!descr.configurable - || descr.writable !== odesc.writable - || descr.enumerable !== odesc.enumerable - || descr.get !== odesc.get - || descr.set !== odesc.set)) { - addChangeRecord(object, data, { - name: key, - type: "reconfigure", - object: object, - oldValue: ovalue - }, except); - data.descriptors[idx] = descr; - } - } : function(object, data, idx, except) { - var key = data.properties[idx], - value = object[key], - ovalue = data.values[idx]; - - if (ovalue === value ? ovalue === 0 && 1/ovalue !== 1/value - : ovalue === ovalue || value === value) { - addChangeRecord(object, data, { - name: key, - type: "update", - object: object, - oldValue: ovalue - }, except); - data.values[idx] = value; - } - }; - - // Checks if some property has been deleted - var deletionCheck = getDescriptor ? function(object, props, proplen, data, except) { - var i = props.length, descr; - while (proplen && i--) { - if (props[i] !== null) { - descr = getDescriptor(object, props[i]); - proplen--; - - // If there's no descriptor, the property has really - // been deleted; otherwise, it's been reconfigured so - // that's not enumerable anymore - if (descr) updateCheck(object, data, i, except, descr); - else { - addChangeRecord(object, data, { - name: props[i], - type: "delete", - object: object, - oldValue: data.values[i] - }, except); - data.properties.splice(i, 1); - data.values.splice(i, 1); - data.descriptors.splice(i, 1); - } - } - } - } : function(object, props, proplen, data, except) { - var i = props.length; - while (proplen && i--) - if (props[i] !== null) { - addChangeRecord(object, data, { - name: props[i], - type: "delete", - object: object, - oldValue: data.values[i] - }, except); - data.properties.splice(i, 1); - data.values.splice(i, 1); - proplen--; - } - }; - - return function(data, object, except) { - if (!data.handlers.size || data.frozen) return; - - var props, proplen, keys, - values = data.values, - descs = data.descriptors, - i = 0, idx, - key, value, - proto, descr; - - // If the object isn't extensible, we don't need to check for new - // or deleted properties - if (data.extensible) { - - props = data.properties.slice(); - proplen = props.length; - keys = getProps(object); - - if (descs) { - while (i < keys.length) { - key = keys[i++]; - idx = inArray(props, key); - descr = getDescriptor(object, key); - - if (idx === -1) { - addChangeRecord(object, data, { - name: key, - type: "add", - object: object - }, except); - data.properties.push(key); - values.push(object[key]); - descs.push(descr); - } else { - props[idx] = null; - proplen--; - updateCheck(object, data, idx, except, descr); - } - } - deletionCheck(object, props, proplen, data, except); - - if (!O.isExtensible(object)) { - data.extensible = false; - addChangeRecord(object, data, { - type: "preventExtensions", - object: object - }, except); - - data.frozen = O.isFrozen(object); - } - } else { - while (i < keys.length) { - key = keys[i++]; - idx = inArray(props, key); - value = object[key]; - - if (idx === -1) { - addChangeRecord(object, data, { - name: key, - type: "add", - object: object - }, except); - data.properties.push(key); - values.push(value); - } else { - props[idx] = null; - proplen--; - updateCheck(object, data, idx, except); - } - } - deletionCheck(object, props, proplen, data, except); - } - - } else if (!data.frozen) { - - // If the object is not extensible, but not frozen, we just have - // to check for value changes - for (; i < props.length; i++) { - key = props[i]; - updateCheck(object, data, i, except, getDescriptor(object, key)); - } - - if (O.isFrozen(object)) - data.frozen = true; - } - - if (getPrototype) { - proto = getPrototype(object); - if (proto !== data.proto) { - addChangeRecord(object, data, { - type: "setPrototype", - name: "__proto__", - object: object, - oldValue: data.proto - }); - data.proto = proto; - } - } - }; - })(), - - /** - * Sets up the main loop for object observation and change notification - * It stops if no object is observed. - * @function runGlobalLoop - */ - runGlobalLoop = function() { - if (observed.size) { - observed.forEach(performPropertyChecks); - handlers.forEach(deliverHandlerRecords); - nextFrame(runGlobalLoop); - } - }, - - /** - * Deliver the change records relative to a certain handler, and resets - * the record list. - * @param {HandlerData} hdata - * @param {Handler} handler - */ - deliverHandlerRecords = function(hdata, handler) { - if (hdata.changeRecords.length) { - handler(hdata.changeRecords); - hdata.changeRecords = []; - } - }, - - /** - * Returns the notifier for an object - whether it's observed or not - * @function retrieveNotifier - * @param {Object} object - * @param {ObjectData} [data] - * @returns {Notifier} - */ - retrieveNotifier = function(object, data) { - if (arguments.length < 2) - data = observed.get(object); - - /** @type {Notifier} */ - return data && data.notifier || { - /** - * @method notify - * @see http://arv.github.io/ecmascript-object-observe/#notifierprototype._notify - * @memberof Notifier - * @param {ChangeRecord} changeRecord - */ - notify: function(changeRecord) { - changeRecord.type; // Just to check the property is there... - - // If there's no data, the object has been unobserved - var data = observed.get(object); - if (data) { - var recordCopy = { object: object }, prop; - for (prop in changeRecord) - if (prop !== "object") - recordCopy[prop] = changeRecord[prop]; - addChangeRecord(object, data, recordCopy); - } - }, - - /** - * @method performChange - * @see http://arv.github.io/ecmascript-object-observe/#notifierprototype_.performchange - * @memberof Notifier - * @param {String} changeType - * @param {Performer} func The task performer - * @param {*} [thisObj] Used to set `this` when calling func - */ - performChange: function(changeType, func/*, thisObj*/) { - if (typeof changeType !== "string") - throw new TypeError("Invalid non-string changeType"); - - if (typeof func !== "function") - throw new TypeError("Cannot perform non-function"); - - // If there's no data, the object has been unobserved - var data = observed.get(object), - prop, changeRecord, - result = func.call(arguments[2]); - - data && performPropertyChecks(data, object, changeType); - - // If there's no data, the object has been unobserved - if (data && result && typeof result === "object") { - changeRecord = { object: object, type: changeType }; - for (prop in result) - if (prop !== "object" && prop !== "type") - changeRecord[prop] = result[prop]; - addChangeRecord(object, data, changeRecord); - } - } - }; - }, - - /** - * Register (or redefines) an handler in the collection for a given - * object and a given type accept list. - * @function setHandler - * @param {Object} object - * @param {ObjectData} data - * @param {Handler} handler - * @param {String[]} acceptList - */ - setHandler = function(object, data, handler, acceptList) { - var hdata = handlers.get(handler); - if (!hdata) - handlers.set(handler, hdata = { - observed: createMap(), - changeRecords: [] - }); - hdata.observed.set(object, { - acceptList: acceptList.slice(), - data: data - }); - data.handlers.set(handler, hdata); - }, - - /** - * Adds a change record in a given ObjectData - * @function addChangeRecord - * @param {Object} object - * @param {ObjectData} data - * @param {ChangeRecord} changeRecord - * @param {String} [except] - */ - addChangeRecord = function(object, data, changeRecord, except) { - data.handlers.forEach(function(hdata) { - var acceptList = hdata.observed.get(object).acceptList; - // If except is defined, Notifier.performChange has been - // called, with except as the type. - // All the handlers that accepts that type are skipped. - if ((typeof except !== "string" - || inArray(acceptList, except) === -1) - && inArray(acceptList, changeRecord.type) > -1) - hdata.changeRecords.push(changeRecord); - }); - }; - - observed = createMap(); - handlers = createMap(); - - /** - * @function Object.observe - * @see http://arv.github.io/ecmascript-object-observe/#Object.observe - * @param {Object} object - * @param {Handler} handler - * @param {String[]} [acceptList] - * @throws {TypeError} - * @returns {Object} The observed object - */ - O.observe = function observe(object, handler, acceptList) { - if (!object || typeof object !== "object" && typeof object !== "function") - throw new TypeError("Object.observe cannot observe non-object"); - - if (typeof handler !== "function") - throw new TypeError("Object.observe cannot deliver to non-function"); - - if (O.isFrozen && O.isFrozen(handler)) - throw new TypeError("Object.observe cannot deliver to a frozen function object"); - - if (typeof acceptList === "undefined") - acceptList = defaultAcceptList; - else if (!acceptList || typeof acceptList !== "object") - throw new TypeError("Third argument to Object.observe must be an array of strings."); - - doObserve(object, handler, acceptList); - - return object; - }; - - /** - * @function Object.unobserve - * @see http://arv.github.io/ecmascript-object-observe/#Object.unobserve - * @param {Object} object - * @param {Handler} handler - * @throws {TypeError} - * @returns {Object} The given object - */ - O.unobserve = function unobserve(object, handler) { - if (object === null || typeof object !== "object" && typeof object !== "function") - throw new TypeError("Object.unobserve cannot unobserve non-object"); - - if (typeof handler !== "function") - throw new TypeError("Object.unobserve cannot deliver to non-function"); - - var hdata = handlers.get(handler), odata; - - if (hdata && (odata = hdata.observed.get(object))) { - hdata.observed.forEach(function(odata, object) { - performPropertyChecks(odata.data, object); - }); - nextFrame(function() { - deliverHandlerRecords(hdata, handler); - }); - - // In Firefox 13-18, size is a function, but createMap should fall - // back to the shim for those versions - if (hdata.observed.size === 1 && hdata.observed.has(object)) - handlers["delete"](handler); - else hdata.observed["delete"](object); - - if (odata.data.handlers.size === 1) - observed["delete"](object); - else odata.data.handlers["delete"](handler); - } - - return object; - }; - - /** - * @function Object.getNotifier - * @see http://arv.github.io/ecmascript-object-observe/#GetNotifier - * @param {Object} object - * @throws {TypeError} - * @returns {Notifier} - */ - O.getNotifier = function getNotifier(object) { - if (object === null || typeof object !== "object" && typeof object !== "function") - throw new TypeError("Object.getNotifier cannot getNotifier non-object"); - - if (O.isFrozen && O.isFrozen(object)) return null; - - return retrieveNotifier(object); - }; - - /** - * @function Object.deliverChangeRecords - * @see http://arv.github.io/ecmascript-object-observe/#Object.deliverChangeRecords - * @see http://arv.github.io/ecmascript-object-observe/#DeliverChangeRecords - * @param {Handler} handler - * @throws {TypeError} - */ - O.deliverChangeRecords = function deliverChangeRecords(handler) { - if (typeof handler !== "function") - throw new TypeError("Object.deliverChangeRecords cannot deliver to non-function"); - - var hdata = handlers.get(handler); - if (hdata) { - hdata.observed.forEach(function(odata, object) { - performPropertyChecks(odata.data, object); - }); - deliverHandlerRecords(hdata, handler); - } - }; - -})(Object, Array, this); \ No newline at end of file diff --git a/test/pouchdb.find.min.js b/test/pouchdb.find.min.js deleted file mode 100644 index d0c4464..0000000 --- a/test/pouchdb.find.min.js +++ /dev/null @@ -1,3 +0,0 @@ -!function e(t,n,r){function o(u,s){if(!n[u]){if(!t[u]){var a="function"==typeof require&&require;if(!s&&a)return a(u,!0);if(i)return i(u,!0);throw new Error("Cannot find module '"+u+"'")}var c=n[u]={exports:{}};t[u][0].call(c.exports,function(e){var n=t[u][1][e];return o(n?n:e)},c,c.exports,e,t,n,r)}return n[u].exports}for(var i="function"==typeof require&&require,u=0;uo;o++){for(var u=f(e[o]),s=n,a=0,c=u.length;c>a;a++){var l=u[a];if(s=s[l],!s)break}r.push(s)}t(r)}}function r(e,t){var n=f(e);return function(e){for(var r=e,o=0,i=n.length;i>o;o++){var u=n[o];if(r=r[u],!r)return}t(r)}}function o(e,t){return function(n){t(n[e])}}function i(e,t){return function(n){for(var r=[],o=0,i=e.length;i>o;o++)r.push(n[e[o]]);t(r)}}function u(e){for(var t=0,n=e.length;n>t;t++){var r=e[t];if(-1!==r.indexOf("."))return!1}return!0}function s(e,t){var s=u(e),a=1===e.length;return s?a?o(e[0],t):i(e,t):a?r(e[0],t):n(e,t)}var a=e("./utils"),c=e("pouchdb-abstract-mapreduce"),f=a.parseField,l=c({name:"indexes",mapper:function(e,t){var n=Object.keys(e.fields);return s(n,t)},reducer:function(){throw new Error("reduce not supported")},ddocValidator:function(e,t){var n=e.views[t];if(!n.map||!n.map.fields)throw new Error("ddoc "+e._id+" with view "+t+" doesn't have map.fields defined. maybe it wasn't created by this plugin?")}});t.exports=l},{"./utils":10,"pouchdb-abstract-mapreduce":40}],3:[function(e,t){"use strict";function n(e,t,n){return u.upsert.call(e,t,n)}function r(e,t){function r(e){return e._rev&&"query"!==e.language&&(h=!0),e.language="query",e.views=e.views||{},y=!!e.views[l],e.views[l]={map:{fields:o.mergeObjects(t.index.fields)},reduce:"_count",options:{def:u}},e}var u=o.clone(t.index);t.index=f(t.index),c(t.index);var a=o.MD5(JSON.stringify(t)),l=t.name||"idx-"+a,d=t.ddoc||"idx-"+a,p="_design/"+d,h=!1,y=!1;return i("creating index",p),n(e,p,r).then(function(){if(h)throw new Error('invalid language for ddoc with id "'+p+'" (should be "query")')}).then(function(){var t=d+"/"+l;return s.query.call(e,t,{limit:0,reduce:!1}).then(function(){return{result:y?"exists":"created"}})})}var o=e("../../../utils"),i=o.log,u=e("pouchdb-upsert"),s=e("../abstract-mapper"),a=e("../utils"),c=a.validateIndex,f=a.massageIndexDef;t.exports=r},{"../../../utils":12,"../abstract-mapper":2,"../utils":10,"pouchdb-upsert":47}],4:[function(e,t){"use strict";function n(e,t){var n=t.ddoc;return e.get(n).then(function(t){return e.remove(t)}).then(function(){return r.viewCleanup.apply(e)}).then(function(){return{ok:!0}})}var r=e("../abstract-mapper");t.exports=n},{"../abstract-mapper":2}],5:[function(e,t){"use strict";function n(e,t){for(var n=e,r=0,o=t.length;o>r;r++){var i=t[r];if(n=n[i],!n)break}return n}function r(e,t,r){function o(e){return s(n(e,r),t)}function i(e){var t=n(e,r);return"undefined"!=typeof t&&null!==t}switch(e){case"$eq":return function(e){return i(e)&&0===o(e)};case"$lte":return function(e){return i(e)&&o(e)<=0};case"$gte":return function(e){return i(e)&&o(e)>=0};case"$lt":return function(e){return i(e)&&o(e)<0};case"$gt":return function(e){return i(e)&&o(e)>0};case"$exists":return function(e){return i(e)};case"$ne":return function(e){var o=n(e,r);return t.every(function(e){return 0!==s(o,e)})}}}function o(e,t){var n=[];return t.forEach(function(t){var o=e.selector[t],i=l(t);o&&Object.keys(o).forEach(function(e){var t=o[e],u=r(e,t,i);n.push(u)})}),function(e){for(var t=0,r=n.length;r>t;t++){var o=n[t];if(!o(e.doc))return!1}return!0}}function i(e){function t(t){return e.map(function(e){var r="string"==typeof e?e:c(e),o=l(r),i=n(t,o);return i})}return function(e,n){var r=t(e.doc),o=t(n.doc),i=s(r,o);return 0!==i?i:d.compare(e.doc._id,n.doc._id)}}function u(e,t,n){var r=o(t,n);if(e=e.filter(r),t.sort){var u=i(t.sort);e=e.sort(u),"string"!=typeof t.sort[0]&&"desc"===f(t.sort[0])&&(e=e.reverse())}if("limit"in t||"skip"in t){var s=t.skip||0,a=("limit"in t?t.limit:e.length)+s;e=e.slice(s,a)}return e}var s=e("pouchdb-collate").collate,a=e("../utils"),c=a.getKey,f=a.getValue,l=a.parseField,d=e("../../../utils");t.exports=u},{"../../../utils":12,"../utils":10,"pouchdb-collate":44}],6:[function(e,t){"use strict";function n(e){return e.ddoc.substring(8)+"/"+e.name}function r(e,t){return t.selector&&(t.selector=l(t.selector)),t.sort&&(t.sort=d(t.sort)),h(t),i(e).then(function(r){var i=a(t,r.indexes),c=i.index,l=o.extend(!0,{include_docs:!0,reduce:!1},i.queryOpts);if("startkey"in l&&"endkey"in l&&u(l.startkey,l.endkey)>0)return{docs:[]};var d=t.sort&&"string"!=typeof t.sort[0]&&"desc"===p(t.sort[0]);return d&&(l.descending=!0,l=y(l)),i.inMemoryFields.length||("limit"in t&&(l.limit=t.limit),"skip"in t&&(l.skip=t.skip)),v.resolve().then(function(){if("_all_docs"===c.name)return e.allDocs(l);var t=n(c);return s.query.call(e,t,l)}).then(function(e){return l.inclusive_start===!1&&(e.rows=g(e.rows,l.startkey,c)),i.inMemoryFields.length&&(e.rows=f(e.rows,t,i.inMemoryFields)),{docs:e.rows.map(function(e){var n=e.doc;return t.fields?o.pick(n,t.fields):n})}})})}var o=e("../../../utils"),i=e("../get-indexes"),u=e("pouchdb-collate").collate,s=e("../abstract-mapper"),a=e("./query-planner"),c=e("../utils"),f=e("./in-memory-filter"),l=c.massageSelector,d=c.massageSort,p=c.getValue,h=c.validateFindRequest,y=c.reverseOptions,g=c.filterInclusiveStart,v=o.Promise;t.exports=r},{"../../../utils":12,"../abstract-mapper":2,"../get-indexes":8,"../utils":10,"./in-memory-filter":5,"./query-planner":7,"pouchdb-collate":44}],7:[function(e,t){"use strict";function n(e,t){for(var n=e.def.fields.map(E),r=0,o=n.length;o>r;r++){var i=n[r];if(t===i)return!0}return!1}function r(e,t){var n=e[t],r=E(n);return"$eq"!==r}function o(e,t){var n=t.def.fields.map(E);return e.slice().sort(function(e,t){var r=n.indexOf(e),o=n.indexOf(t);return-1===r&&(r=Number.MAX_VALUE),-1===o&&(o=Number.MAX_VALUE),w.compare(r,o)})}function i(e,t,i){i=o(i,e);for(var u=!1,s=0,a=i.length;a>s;s++){var c=i[s];if(u||!n(e,c))return i.slice(s);a-1>s&&r(t,c)&&(u=!0)}return[]}function u(e){var t=[];return Object.keys(e).forEach(function(n){var r=e[n];Object.keys(r).forEach(function(e){"$ne"===e&&t.push(n)})}),t}function s(e,t,n,r){var s=w.flatten(e,i(t,n,r),u(n));return o(w.uniq(s),t)}function a(e,t,n){if(t){var r=w.oneArrayIsStrictSubArrayOfOther(t,e),o=w.oneArrayIsSubArrayOfOther(n,e);return r&&o}return w.oneSetIsSubArrayOfOther(n,e)}function c(e,t){var n=e[0],r=t[n],o=1===Object.keys(r).length&&"$ne"===E(r);return!o}function f(e,t,n,r){var o=e.def.fields.map(E),i=a(o,t,n);if(!i)return!1;var u=c(o,r);return u}function l(e,t,n,r){for(var o=[],i=0,u=r.length;u>i;i++){var s=r[i],a=f(s,n,t,e);a&&o.push(s)}return o}function d(e,t,n,r){function o(e){for(var t=e.def.fields.map(E),n=0,r=0,o=t.length;o>r;r++){var i=t[r];u[i]&&n++}return n}var i=l(e,t,n,r);if(0===i.length)return null;if(1===i.length)return i[0];var u=w.arrayToObject(t);return w.max(i,o)}function p(e,t){switch(e){case"$eq":return{key:t};case"$lte":return{endkey:t};case"$gte":return{startkey:t};case"$lt":return{endkey:t,inclusive_end:!1};case"$gt":return{startkey:t,inclusive_start:!1};case"$exists":return t?{startkey:I}:{endkey:j};case"$type":switch(t){case"null":return{startkey:S,endkey:$};case"boolean":return{startkey:q,endkey:N};case"number":return{startkey:C,endkey:D};case"string":return{startkey:T,endkey:F};case"array":return{startkey:M,endkey:L};case"object":return{startkey:P,endkey:B}}}}function h(e,t){for(var n,r=E(t.def.fields[0]),o=e[r],i=Object.keys(o),u=0;uc;c++){var l=i[c],d=e[l];if(!d){n(c);break}if(c>0){if("$ne"in d){n(c);break}var p="$gt"in d||"$gte"in d||"$lt"in d||"$lte"in d,h=Object.keys(e[i[c-1]]),g=w.arrayEquals(h,["$eq"]),v=w.arrayEquals(h,Object.keys(d)),m=p&&!g&&!v;if(m){n(c);break}}for(var b=Object.keys(d),k=null,x=0;x=e.length?t:e;return new Error("couldn't find a usable index. try creating an index on: "+r.join(", "))}function b(e,t){k("planning query",e);var n=e.selector,r=e.sort,o=O(n,r),i=o.fields,u=o.sortOrder,a=d(n,i,u,t);if(!a)throw m(i,u,n);var c=a.def.fields[0],f=n[E(c)];if(1===Object.keys(f).length&&"$ne"===E(f))throw new Error("$ne can't be used here. try $gt/$lt instead");var l=v(n,a),p=l.queryOpts,h=l.inMemoryFields,y=s(h,a,n,i),g={queryOpts:p,index:a,inMemoryFields:y};return k("query plan",g),g}var w=e("../../../utils"),k=w.log,x=e("../utils"),E=x.getKey,_=x.getValue,O=x.getUserFields,j=null,A={"ï¿¿":{}},I=!1,S=null,$=null,q=!1,N=!0,C=0,D=Number.MAX_VALUE,T="",F="ï¿¿ï¿¿ï¿¿",M=[],L=[{"ï¿¿":{}}],P={},B={"ï¿¿":{}};t.exports=b},{"../../../utils":12,"../utils":10}],8:[function(e,t){"use strict";function n(e){return e.allDocs({startkey:"_design/",endkey:"_design/ï¿¿",include_docs:!0}).then(function(e){var t={indexes:[{ddoc:null,name:"_all_docs",type:"special",def:{fields:[{_id:"asc"}]}}]};return t.indexes=r.flatten(t.indexes,e.rows.filter(function(e){return"query"===e.doc.language}).map(function(e){var t=Object.keys(e.doc.views);return t.map(function(t){var n=e.doc.views[t];return{ddoc:e.id,name:t,type:"json",def:i(n.options.def)}})})),t.indexes.sort(function(e,t){return r.compare(e.name,t.name)}),t})}var r=e("../../../utils"),o=e("../utils"),i=o.massageIndexDef;t.exports=n},{"../../../utils":12,"../utils":10}],9:[function(e,t,n){"use strict";var r=e("../../utils"),o=r.callbackify;n.createIndex=o(e("./create-index")),n.find=o(e("./find")),n.getIndexes=o(e("./get-indexes")),n.deleteIndex=o(e("./delete-index"))},{"../../utils":12,"./create-index":3,"./delete-index":4,"./find":6,"./get-indexes":8}],10:[function(e,t){"use strict";function n(e){return Object.keys(e)[0]}function r(e){return e[n(e)]}function o(e){return Object.keys(e).length}function i(e,t){var n={};return n[e]=t,n}function u(e){return e&&e.map(function(e){if("string"==typeof e){var t={};return t[e]="asc",t}return e})}function s(e,t,n){"undefined"==typeof n.$eq&&("undefined"!=typeof n.$gte?"$gte"===e?t>n.$gte&&(n.$gte=t):t>=n.$gte&&(delete n.$gte,n.$gt=t):"undefined"!=typeof n.$gt?"$gte"===e?t>n.$gt&&(delete n.$gt,n.$gte=t):t>n.$gt&&(n.$gt=t):n[e]=t)}function a(e,t,n){"undefined"==typeof n.$eq&&("undefined"!=typeof n.$lte?"$lte"===e?to;o++){var u=e[o],s=u.key,a=t;if(r.length>1&&(s=s[0],a=a[0]),k.collate(s,a)>0)break}return o>0?e.slice(o):e}function y(e){var t=w.clone(e);return delete t.startkey,delete t.endkey,delete t.inclusive_start,delete t.inclusive_end,"endkey"in e&&(t.startkey=e.endkey),"startkey"in e&&(t.endkey=e.startkey),"inclusive_start"in e&&(t.inclusive_end=e.inclusive_start),"inclusive_end"in e&&(t.inclusive_start=e.inclusive_end),t}function g(e){var t=e.fields.filter(function(e){return"asc"===r(e)});if(0!==t.length&&t.length!==e.fields.length)throw new Error("unsupported mixed sorting")}function v(e){if("object"!=typeof e.selector)throw new Error("you must provide a selector when you find()");if("sort"in e&&(!e.sort||!Array.isArray(e.sort)))throw new Error("invalid sort json - should be an array");var t=Object.keys(e.selector),r=e.sort?u(e.sort).map(n):[];if(!w.oneSetIsSubArrayOfOther(t,r))throw new Error("conflicting sort and selector fields");for(var o=e.selector.$and||[e.selector],i=0;ir;r++){var i=e[r];"."===i?r>0&&"\\"===e[r-1]?n=n.substring(0,n.length-1)+".":(t.push(n),n=""):n+=i}return n&&t.push(n),t}function b(e,t){var r,o=Object.keys(e),i=t?t.map(n):[];return r=o.length>i.length?o:i,0===i.length?{fields:r}:(r=r.sort(function(e,t){var n=i.indexOf(e);-1===n&&(n=Number.MAX_VALUE);var r=i.indexOf(t);return-1===r&&(r=Number.MAX_VALUE),r>n?-1:n>r?1:0}),{fields:r,sortOrder:t.map(n)})}var w=e("../../utils"),k=e("pouchdb-collate");t.exports={getKey:n,getValue:r,getSize:o,massageSort:u,massageSelector:d,validateIndex:g,validateFindRequest:v,reverseOptions:y,filterInclusiveStart:h,massageIndexDef:p,parseField:m,objectFrom:i,getUserFields:b}},{"../../utils":12,"pouchdb-collate":44}],11:[function(e,t,n){"use strict";var r=e("./utils"),o=e("./adapters/http"),i=e("./adapters/local");n.createIndex=r.toPromise(function(e,t){if("undefined"==typeof t&&(t=e,e=void 0),"object"!=typeof e)return t(new Error("you must provide an index to create"));var n="http"===this.type()?o:i;n.createIndex(this,e,t)}),n.find=r.toPromise(function(e,t){if("undefined"==typeof t&&(t=e,e=void 0),"object"!=typeof e)return t(new Error("you must provide search parameters to find()"));var n="http"===this.type()?o:i;n.find(this,e,t)}),n.getIndexes=r.toPromise(function(e){var t="http"===this.type()?o:i;t.getIndexes(this,e)}),n.deleteIndex=r.toPromise(function(e,t){if("undefined"==typeof t&&(t=e,e=void 0),"object"!=typeof e)return t(new Error("you must provide an index to delete"));var n="http"===this.type()?o:i;n.deleteIndex(this,e,t)}),"undefined"!=typeof window&&window.PouchDB&&window.PouchDB.plugin(n)},{"./adapters/http":1,"./adapters/local":9,"./utils":12}],12:[function(e,t,n){var r,o=e("__browserify_process"),i="undefined"!=typeof self?self:"undefined"!=typeof window?window:{},u=e("__browserify_Buffer").Buffer;r="undefined"!=typeof window&&window.PouchDB?window.PouchDB.utils.Promise:"function"==typeof i.Promise?i.Promise:e("lie"),n.once=function(e){var t=!1;return n.getArguments(function(n){if(t)throw console.trace(),new Error("once called more than once");t=!0,e.apply(this,n)})},n.getArguments=function(e){return function(){for(var t=arguments.length,n=new Array(t),r=-1;++rr;r++){var i=e[r];Array.isArray(i)?t=t.concat(n.flatten.apply(null,i)):t.push(i)}return t}),n.mergeObjects=function(e){for(var t={},r=0,o=e.length;o>r;r++)t=n.extend(!0,t,e[r]);return t},n.pick=function(e,t){for(var n={},r=0,o=t.length;o>r;r++){var i=t[r];n[i]=e[i]}return n},n.oneArrayIsSubArrayOfOther=function(e,t){for(var n=0,r=Math.min(e.length,t.length);r>n;n++)if(e[n]!==t[n])return!1;return!0},n.oneArrayIsStrictSubArrayOfOther=function(e,t){return e.length>t.length?!1:n.oneArrayIsSubArrayOfOther(e,t)},n.oneSetIsSubArrayOfOther=function(e,t){e=e.slice();for(var n=0,r=t.length;r>n;n++){var o=t[n];if(!e.length)break;var i=e.indexOf(o);if(-1===i)return!1;e.splice(i,1)}return!0},n.compare=function(e,t){return t>e?-1:e>t?1:0},n.arrayToObject=function(e){for(var t={},n=0,r=e.length;r>n;n++)t[e[n]]=!0;return t},n.max=function(e,t){for(var n=null,r=-1,o=0,i=e.length;i>o;o++){var u=e[o],s=t(u);s>r&&(r=s,n=u)}return n},n.arrayEquals=function(e,t){if(e.length!==t.length)return!1;for(var n=0,r=e.length;r>n;n++)if(e[n]!==t[n])return!1;return!0},n.uniq=function(e){for(var t={},n=0;n>1,f=-7,l=n?0:o-1,d=n?1:-1,p=e[t+l];for(l+=d,i=p&(1<<-f)-1,p>>=-f,f+=s;f>0;i=256*i+e[t+l],l+=d,f-=8);for(u=i&(1<<-f)-1,i>>=-f,f+=r;f>0;u=256*u+e[t+l],l+=d,f-=8);if(0===i)i=1-c;else{if(i===a)return u?0/0:1/0*(p?-1:1);u+=Math.pow(2,r),i-=c}return(p?-1:1)*u*Math.pow(2,i-r)},n.writeIEEE754=function(e,t,n,r,o,i){var u,s,a,c=8*i-o-1,f=(1<>1,d=23===o?Math.pow(2,-24)-Math.pow(2,-77):0,p=r?i-1:0,h=r?-1:1,y=0>t||0===t&&0>1/t?1:0;for(t=Math.abs(t),isNaN(t)||1/0===t?(s=isNaN(t)?1:0,u=f):(u=Math.floor(Math.log(t)/Math.LN2),t*(a=Math.pow(2,-u))<1&&(u--,a*=2),t+=u+l>=1?d/a:d*Math.pow(2,1-l),t*a>=2&&(u++,a/=2),u+l>=f?(s=0,u=f):u+l>=1?(s=(t*a-1)*Math.pow(2,o),u+=l):(s=t*Math.pow(2,l-1)*Math.pow(2,o),u=0));o>=8;e[n+p]=255&s,p+=h,s/=256,o-=8);for(u=u<0;e[n+p]=255&u,p+=h,u/=256,c-=8);e[n+p-h]|=128*y}},{}],q9TxCC:[function(e,t,n){function r(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}function o(t,n,i){if($||($=e("assert")),!(this instanceof o))return new o(t,n,i);if(this.parent=this,this.offset=0,"base64"==n&&"string"==typeof t)for(t=r(t);t.length%4!=0;)t+="=";var s;if("number"==typeof i){this.length=u(n);for(var c=0;c=t?t:e>=0?e:(e+=t,e>=0?e:0))}function u(e){return e=~~Math.ceil(+e),0>e?0:e}function s(e){return(Array.isArray||function(e){return"[object Array]"=={}.toString.apply(e)})(e)}function a(e){return s(e)||o.isBuffer(e)||e&&"object"==typeof e&&"number"==typeof e.length}function c(e){return 16>e?"0"+e.toString(16):e.toString(16)}function f(e){for(var t=[],n=0;no&&!(o+n>=t.length||o>=e.length);)t[o+n]=e[o],o++;return o}function h(e){try{return decodeURIComponent(e)}catch(t){return String.fromCharCode(65533)}}function y(e,t,n,r){var o=0;return r||($.ok("boolean"==typeof n,"missing or invalid endian"),$.ok(void 0!==t&&null!==t,"missing offset"),$.ok(t+1=e.length?0:(n?(o=e[t]<<8,t+1=e.length?0:(n?(t+1>>0):(t+2>>0)),o)}function v(e,t,n,r){var o,i;return r||($.ok("boolean"==typeof n,"missing or invalid endian"),$.ok(void 0!==t&&null!==t,"missing offset"),$.ok(t+1=0,"specified a negative value for writing an unsigned value"),$.ok(t>=e,"value is larger than maximum value for type"),$.ok(Math.floor(e)===e,"value has a fractional component")}function x(e,t,n,r,o){o||($.ok(void 0!==t&&null!==t,"missing value"),$.ok("boolean"==typeof r,"missing or invalid endian"),$.ok(void 0!==n&&null!==n,"missing offset"),$.ok(n+1>>8*(r?1-i:i)}function E(e,t,n,r,o){o||($.ok(void 0!==t&&null!==t,"missing value"),$.ok("boolean"==typeof r,"missing or invalid endian"),$.ok(void 0!==n&&null!==n,"missing offset"),$.ok(n+3>>8*(r?3-i:i)&255}function _(e,t,n){$.ok("number"==typeof e,"cannot write a non-number as a number"),$.ok(t>=e,"value larger than maximum allowed value"),$.ok(e>=n,"value smaller than minimum allowed value"),$.ok(Math.floor(e)===e,"value has a fractional component")}function O(e,t,n){$.ok("number"==typeof e,"cannot write a non-number as a number"),$.ok(t>=e,"value larger than maximum allowed value"),$.ok(e>=n,"value smaller than minimum allowed value")}function j(e,t,n,r,o){o||($.ok(void 0!==t&&null!==t,"missing value"),$.ok("boolean"==typeof r,"missing or invalid endian"),$.ok(void 0!==n&&null!==n,"missing offset"),$.ok(n+1=0?x(e,t,n,r,o):x(e,65535+t+1,n,r,o)}function A(e,t,n,r,o){o||($.ok(void 0!==t&&null!==t,"missing value"),$.ok("boolean"==typeof r,"missing or invalid endian"),$.ok(void 0!==n&&null!==n,"missing offset"),$.ok(n+3=0?E(e,t,n,r,o):E(e,4294967295+t+1,n,r,o)}function I(t,n,r,o,i){i||($.ok(void 0!==n&&null!==n,"missing value"),$.ok("boolean"==typeof o,"missing or invalid endian"),$.ok(void 0!==r&&null!==r,"missing offset"),$.ok(r+3e||e>=this.length)throw new Error("oob");return this[e]},o.prototype.set=function(e,t){if(0>e||e>=this.length)throw new Error("oob");return this[e]=t},o.byteLength=function(e,t){switch(t||"utf8"){case"hex":return e.length/2;case"utf8":case"utf-8":return f(e).length;case"ascii":case"binary":return e.length;case"base64":return d(e).length;default:throw new Error("Unknown encoding")}},o.prototype.utf8Write=function(e,t,n){return o._charsWritten=p(f(e),this,t,n)},o.prototype.asciiWrite=function(e,t,n){return o._charsWritten=p(l(e),this,t,n)},o.prototype.binaryWrite=o.prototype.asciiWrite,o.prototype.base64Write=function(e,t,n){return o._charsWritten=p(d(e),this,t,n)},o.prototype.base64Slice=function(){var t=Array.prototype.slice.apply(this,arguments);return e("base64-js").fromByteArray(t)},o.prototype.utf8Slice=function(){for(var e=Array.prototype.slice.apply(this,arguments),t="",n="",r=0;rr;r++)if(e[r]=c(this[r]),r==n.INSPECT_MAX_BYTES){e[r+1]="...";break}return""},o.prototype.hexSlice=function(e,t){var n=this.length;(!e||0>e)&&(e=0),(!t||0>t||t>n)&&(t=n);for(var r="",o=e;t>o;o++)r+=c(this[o]);return r},o.prototype.toString=function(e,t,n){if(e=String(e||"utf8").toLowerCase(),t=+t||0,"undefined"==typeof n&&(n=this.length),+n==t)return"";switch(e){case"hex":return this.hexSlice(t,n);case"utf8":case"utf-8":return this.utf8Slice(t,n);case"ascii":return this.asciiSlice(t,n);case"binary":return this.binarySlice(t,n);case"base64":return this.base64Slice(t,n);case"ucs2":case"ucs-2":return this.ucs2Slice(t,n);default:throw new Error("Unknown encoding")}},o.prototype.hexWrite=function(e,t,n){t=+t||0;var r=this.length-t;n?(n=+n,n>r&&(n=r)):n=r;var i=e.length;if(i%2)throw new Error("Invalid hex string");n>i/2&&(n=i/2);for(var u=0;n>u;u++){var s=parseInt(e.substr(2*u,2),16);if(isNaN(s))throw new Error("Invalid hex string");this[t+u]=s}return o._charsWritten=2*u,u},o.prototype.write=function(e,t,n,r){if(isFinite(t))isFinite(n)||(r=n,n=void 0);else{var o=r;r=t,t=n,n=o}t=+t||0;var i=this.length-t;switch(n?(n=+n,n>i&&(n=i)):n=i,r=String(r||"utf8").toLowerCase()){case"hex":return this.hexWrite(e,t,n);case"utf8":case"utf-8":return this.utf8Write(e,t,n);case"ascii":return this.asciiWrite(e,t,n);case"binary":return this.binaryWrite(e,t,n);case"base64":return this.base64Write(e,t,n);case"ucs2":case"ucs-2":return this.ucs2Write(e,t,n);default:throw new Error("Unknown encoding")}},o.prototype.slice=function(e,t){var n=this.length;return e=i(e,n,0),t=i(t,n,n),new o(this,t-e,+e)},o.prototype.copy=function(e,t,n,r){var o=this;if(n||(n=0),(void 0===r||isNaN(r))&&(r=this.length),t||(t=0),n>r)throw new Error("sourceEnd < sourceStart");if(r===n)return 0;if(0==e.length||0==o.length)return 0;if(0>t||t>=e.length)throw new Error("targetStart out of bounds");if(0>n||n>=o.length)throw new Error("sourceStart out of bounds");if(0>r||r>o.length)throw new Error("sourceEnd out of bounds");r>this.length&&(r=this.length),e.length-tu;u++)$.ok("undefined"!=typeof this[u],"copying undefined buffer bytes!"),i.push(this[u]);for(var u=t;un)throw new Error("end < start");if(n===t)return 0;if(0==this.length)return 0;if(0>t||t>=this.length)throw new Error("start out of bounds");if(0>n||n>this.length)throw new Error("end out of bounds");for(var r=t;n>r;r++)this[r]=e},o.isBuffer=function(e){return e instanceof o||e instanceof o},o.concat=function(e,t){if(!s(e))throw new Error("Usage: Buffer.concat(list, [totalLength])\n list should be an Array.");if(0===e.length)return new o(0);if(1===e.length)return e[0];if("number"!=typeof t){t=0;for(var n=0;n=n.length?void 0:n[e]},o.prototype.readUInt16LE=function(e,t){return y(this,e,!1,t)},o.prototype.readUInt16BE=function(e,t){return y(this,e,!0,t)},o.prototype.readUInt32LE=function(e,t){return g(this,e,!1,t)},o.prototype.readUInt32BE=function(e,t){return g(this,e,!0,t)},o.prototype.readInt8=function(e,t){var n,r=this;return t||($.ok(void 0!==e&&null!==e,"missing offset"),$.ok(e=r.length?void 0:(n=128&r[e],n?-1*(255-r[e]+1):r[e])},o.prototype.readInt16LE=function(e,t){return v(this,e,!1,t)},o.prototype.readInt16BE=function(e,t){return v(this,e,!0,t)},o.prototype.readInt32LE=function(e,t){return m(this,e,!1,t)},o.prototype.readInt32BE=function(e,t){return m(this,e,!0,t)},o.prototype.readFloatLE=function(e,t){return b(this,e,!1,t)},o.prototype.readFloatBE=function(e,t){return b(this,e,!0,t)},o.prototype.readDoubleLE=function(e,t){return w(this,e,!1,t)},o.prototype.readDoubleBE=function(e,t){return w(this,e,!0,t) -},o.prototype.writeUInt8=function(e,t,n){var r=this;n||($.ok(void 0!==e&&null!==e,"missing value"),$.ok(void 0!==t&&null!==t,"missing offset"),$.ok(t=0?r.writeUInt8(e,t,n):r.writeUInt8(255+e+1,t,n)},o.prototype.writeInt16LE=function(e,t,n){j(this,e,t,!1,n)},o.prototype.writeInt16BE=function(e,t,n){j(this,e,t,!0,n)},o.prototype.writeInt32LE=function(e,t,n){A(this,e,t,!1,n)},o.prototype.writeInt32BE=function(e,t,n){A(this,e,t,!0,n)},o.prototype.writeFloatLE=function(e,t,n){I(this,e,t,!1,n)},o.prototype.writeFloatBE=function(e,t,n){I(this,e,t,!0,n)},o.prototype.writeDoubleLE=function(e,t,n){S(this,e,t,!1,n)},o.prototype.writeDoubleBE=function(e,t,n){S(this,e,t,!0,n)}},{"./buffer_ieee754":1,assert:6,"base64-js":4}],"buffer-browserify":[function(e,t){t.exports=e("q9TxCC")},{}],4:[function(e,t){!function(){"use strict";function e(e){var t,n,o,i,u,s;if(e.length%4>0)throw"Invalid string. Length must be a multiple of 4";for(u=e.indexOf("="),u=u>0?e.length-u:0,s=[],o=u>0?e.length-4:e.length,t=0,n=0;o>t;t+=4,n+=3)i=r.indexOf(e[t])<<18|r.indexOf(e[t+1])<<12|r.indexOf(e[t+2])<<6|r.indexOf(e[t+3]),s.push((16711680&i)>>16),s.push((65280&i)>>8),s.push(255&i);return 2===u?(i=r.indexOf(e[t])<<2|r.indexOf(e[t+1])>>4,s.push(255&i)):1===u&&(i=r.indexOf(e[t])<<10|r.indexOf(e[t+1])<<4|r.indexOf(e[t+2])>>2,s.push(i>>8&255),s.push(255&i)),s}function n(e){function t(e){return r[e>>18&63]+r[e>>12&63]+r[e>>6&63]+r[63&e]}var n,o,i,u=e.length%3,s="";for(n=0,i=e.length-u;i>n;n+=3)o=(e[n]<<16)+(e[n+1]<<8)+e[n+2],s+=t(o);switch(u){case 1:o=e[e.length-1],s+=r[o>>2],s+=r[o<<4&63],s+="==";break;case 2:o=(e[e.length-2]<<8)+e[e.length-1],s+=r[o>>10],s+=r[o>>4&63],s+=r[o<<2&63],s+="="}return s}var r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";t.exports.toByteArray=e,t.exports.fromByteArray=n}()},{}],5:[function(e,t,n){function r(e){return"[object Array]"===c.call(e)}function o(e,t){var n;if(null===e)n={__proto__:null};else{if("object"!=typeof e)throw new TypeError("typeof prototype["+typeof e+"] != 'object'");var r=function(){};r.prototype=e,n=new r,n.__proto__=e}return"undefined"!=typeof t&&Object.defineProperties&&Object.defineProperties(n,t),n}function i(e){return"object"!=typeof e&&"function"!=typeof e||null===e}function u(e){if(i(e))throw new TypeError("Object.keys called on a non-object");var t=[];for(var n in e)f.call(e,n)&&t.push(n);return t}function s(e){if(i(e))throw new TypeError("Object.getOwnPropertyNames called on a non-object");var t=u(e);return n.isArray(e)&&-1===n.indexOf(e,"length")&&t.push("length"),t}function a(e,t){return{value:e[t]}}var c=Object.prototype.toString,f=Object.prototype.hasOwnProperty;n.isArray="function"==typeof Array.isArray?Array.isArray:r,n.indexOf=function(e,t){if(e.indexOf)return e.indexOf(t);for(var n=0;ni;++i)e.hasOwnProperty(i)&&(o?r=t(r,e[i],i,e):(r=e[i],o=!0));return r},n.substr="b"!=="ab".substr(-1)?function(e,t,n){return 0>t&&(t=e.length+t),e.substr(t,n)}:function(e,t,n){return e.substr(t,n)},n.trim=function(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")},n.bind=function(){var e=Array.prototype.slice.call(arguments),t=e.shift();if(t.bind)return t.bind.apply(t,e);var n=e.shift();return function(){t.apply(n,e.concat([Array.prototype.slice.call(arguments)]))}},n.create="function"==typeof Object.create?Object.create:o;var l="function"==typeof Object.keys?Object.keys:u,d="function"==typeof Object.getOwnPropertyNames?Object.getOwnPropertyNames:s;if((new Error).hasOwnProperty("description")){var p=function(e,t){return"[object Error]"===c.call(e)&&(t=n.filter(t,function(e){return"description"!==e&&"number"!==e&&"message"!==e})),t};n.keys=function(e){return p(e,l(e))},n.getOwnPropertyNames=function(e){return p(e,d(e))}}else n.keys=l,n.getOwnPropertyNames=d;if("function"==typeof Object.getOwnPropertyDescriptor)try{Object.getOwnPropertyDescriptor({a:1},"a"),n.getOwnPropertyDescriptor=Object.getOwnPropertyDescriptor}catch(h){n.getOwnPropertyDescriptor=function(e,t){try{return Object.getOwnPropertyDescriptor(e,t)}catch(n){return a(e,t)}}}else n.getOwnPropertyDescriptor=a},{}],6:[function(e,t){function n(e,t){return d.isUndefined(t)?""+t:!d.isNumber(t)||!isNaN(t)&&isFinite(t)?d.isFunction(t)||d.isRegExp(t)?t.toString():t:t.toString()}function r(e,t){return d.isString(e)?e.length=0;r--)if(o[r]!=i[r])return!1;for(r=o.length-1;r>=0;r--)if(n=o[r],!s(e[n],t[n]))return!1;return!0}function f(e,t){return e&&t?"[object RegExp]"==Object.prototype.toString.call(t)?t.test(e):e instanceof t?!0:t.call({},e)===!0?!0:!1:!1}function l(e,t,n,r){var o;d.isString(n)&&(r=n,n=null);try{t()}catch(u){o=u}if(r=(n&&n.name?" ("+n.name+").":".")+(r?" "+r:"."),e&&!o&&i(o,n,"Missing expected exception"+r),!e&&f(o,n)&&i(o,n,"Got unwanted exception"+r),e&&o&&n&&!f(o,n)||!e&&o)throw o}var d=e("util"),p=e("_shims"),h=Array.prototype.slice,y=t.exports=u;y.AssertionError=function(e){this.name="AssertionError",this.actual=e.actual,this.expected=e.expected,this.operator=e.operator,this.message=e.message||o(this)},d.inherits(y.AssertionError,Error),y.fail=i,y.ok=u,y.equal=function(e,t,n){e!=t&&i(e,t,n,"==",y.equal)},y.notEqual=function(e,t,n){e==t&&i(e,t,n,"!=",y.notEqual)},y.deepEqual=function(e,t,n){s(e,t)||i(e,t,n,"deepEqual",y.deepEqual)},y.notDeepEqual=function(e,t,n){s(e,t)&&i(e,t,n,"notDeepEqual",y.notDeepEqual)},y.strictEqual=function(e,t,n){e!==t&&i(e,t,n,"===",y.strictEqual)},y.notStrictEqual=function(e,t,n){e===t&&i(e,t,n,"!==",y.notStrictEqual)},y["throws"]=function(){l.apply(this,[!0].concat(h.call(arguments)))},y.doesNotThrow=function(){l.apply(this,[!1].concat(h.call(arguments)))},y.ifError=function(e){if(e)throw e}},{_shims:5,util:7}],7:[function(e,t,n){function r(e,t){var r={seen:[],stylize:i};return arguments.length>=3&&(r.depth=arguments[2]),arguments.length>=4&&(r.colors=arguments[3]),h(t)?r.showHidden=t:t&&n._extend(r,t),w(r.showHidden)&&(r.showHidden=!1),w(r.depth)&&(r.depth=2),w(r.colors)&&(r.colors=!1),w(r.customInspect)&&(r.customInspect=!0),r.colors&&(r.stylize=o),s(r,e,r.depth)}function o(e,t){var n=r.styles[t];return n?"["+r.colors[n][0]+"m"+e+"["+r.colors[n][1]+"m":e}function i(e){return e}function u(e){var t={};return N.forEach(e,function(e){t[e]=!0}),t}function s(e,t,r){if(e.customInspect&&t&&O(t.inspect)&&t.inspect!==n.inspect&&(!t.constructor||t.constructor.prototype!==t)){var o=t.inspect(r);return m(o)||(o=s(e,o,r)),o}var i=a(e,t);if(i)return i;var h=N.keys(t),y=u(h);if(e.showHidden&&(h=N.getOwnPropertyNames(t)),0===h.length){if(O(t)){var g=t.name?": "+t.name:"";return e.stylize("[Function"+g+"]","special")}if(k(t))return e.stylize(RegExp.prototype.toString.call(t),"regexp");if(E(t))return e.stylize(Date.prototype.toString.call(t),"date");if(_(t))return c(t)}var v="",b=!1,w=["{","}"];if(p(t)&&(b=!0,w=["[","]"]),O(t)){var x=t.name?": "+t.name:"";v=" [Function"+x+"]"}if(k(t)&&(v=" "+RegExp.prototype.toString.call(t)),E(t)&&(v=" "+Date.prototype.toUTCString.call(t)),_(t)&&(v=" "+c(t)),0===h.length&&(!b||0==t.length))return w[0]+v+w[1];if(0>r)return k(t)?e.stylize(RegExp.prototype.toString.call(t),"regexp"):e.stylize("[Object]","special");e.seen.push(t);var j;return j=b?f(e,t,r,y,h):h.map(function(n){return l(e,t,r,y,n,b)}),e.seen.pop(),d(j,v,w)}function a(e,t){if(w(t))return e.stylize("undefined","undefined");if(m(t)){var n="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(n,"string")}return v(t)?e.stylize(""+t,"number"):h(t)?e.stylize(""+t,"boolean"):y(t)?e.stylize("null","null"):void 0}function c(e){return"["+Error.prototype.toString.call(e)+"]"}function f(e,t,n,r,o){for(var i=[],u=0,s=t.length;s>u;++u)i.push(q(t,String(u))?l(e,t,n,r,String(u),!0):"");return N.forEach(o,function(o){o.match(/^\d+$/)||i.push(l(e,t,n,r,o,!0))}),i}function l(e,t,n,r,o,i){var u,a,c;if(c=N.getOwnPropertyDescriptor(t,o)||{value:t[o]},c.get?a=c.set?e.stylize("[Getter/Setter]","special"):e.stylize("[Getter]","special"):c.set&&(a=e.stylize("[Setter]","special")),q(r,o)||(u="["+o+"]"),a||(N.indexOf(e.seen,c.value)<0?(a=y(n)?s(e,c.value,null):s(e,c.value,n-1),a.indexOf("\n")>-1&&(a=i?a.split("\n").map(function(e){return" "+e}).join("\n").substr(2):"\n"+a.split("\n").map(function(e){return" "+e}).join("\n"))):a=e.stylize("[Circular]","special")),w(u)){if(i&&o.match(/^\d+$/))return a;u=JSON.stringify(""+o),u.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(u=u.substr(1,u.length-2),u=e.stylize(u,"name")):(u=u.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),u=e.stylize(u,"string"))}return u+": "+a}function d(e,t,n){var r=0,o=N.reduce(e,function(e,t){return r++,t.indexOf("\n")>=0&&r++,e+t.replace(/\u001b\[\d\d?m/g,"").length+1},0);return o>60?n[0]+(""===t?"":t+"\n ")+" "+e.join(",\n ")+" "+n[1]:n[0]+t+" "+e.join(", ")+" "+n[1]}function p(e){return N.isArray(e)}function h(e){return"boolean"==typeof e}function y(e){return null===e}function g(e){return null==e}function v(e){return"number"==typeof e}function m(e){return"string"==typeof e}function b(e){return"symbol"==typeof e}function w(e){return void 0===e}function k(e){return x(e)&&"[object RegExp]"===I(e)}function x(e){return"object"==typeof e&&e}function E(e){return x(e)&&"[object Date]"===I(e)}function _(e){return x(e)&&"[object Error]"===I(e)}function O(e){return"function"==typeof e}function j(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||"symbol"==typeof e||"undefined"==typeof e}function A(e){return e instanceof Buffer}function I(e){return Object.prototype.toString.call(e)}function S(e){return 10>e?"0"+e.toString(10):e.toString(10)}function $(){var e=new Date,t=[S(e.getHours()),S(e.getMinutes()),S(e.getSeconds())].join(":");return[e.getDate(),D[e.getMonth()],t].join(" ")}function q(e,t){return Object.prototype.hasOwnProperty.call(e,t)}var N=e("_shims"),C=/%[sdj%]/g;n.format=function(e){if(!m(e)){for(var t=[],n=0;n=i)return e;switch(e){case"%s":return String(o[n++]);case"%d":return Number(o[n++]);case"%j":try{return JSON.stringify(o[n++])}catch(t){return"[Circular]"}default:return e}}),s=o[n];i>n;s=o[++n])u+=y(s)||!x(s)?" "+s:" "+r(s);return u},n.inspect=r,r.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},r.styles={special:"cyan",number:"yellow","boolean":"yellow",undefined:"grey","null":"bold",string:"green",date:"magenta",regexp:"red"},n.isArray=p,n.isBoolean=h,n.isNull=y,n.isNullOrUndefined=g,n.isNumber=v,n.isString=m,n.isSymbol=b,n.isUndefined=w,n.isRegExp=k,n.isObject=x,n.isDate=E,n.isError=_,n.isFunction=O,n.isPrimitive=j,n.isBuffer=A;var D=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];n.log=function(){console.log("%s - %s",$(),n.format.apply(n,arguments))},n.inherits=function(e,t){e.super_=t,e.prototype=N.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}})},n._extend=function(e,t){if(!t||!x(t))return e;for(var n=N.keys(t),r=n.length;r--;)e[n[r]]=t[n[r]];return e}},{_shims:5}]},{},[]),t.exports=e("buffer-browserify")},{}],16:[function(e,t){var n=t.exports={};n.nextTick=function(){var e="undefined"!=typeof window&&window.setImmediate,t="undefined"!=typeof window&&window.postMessage&&window.addEventListener;if(e)return function(e){return window.setImmediate(e)};if(t){var n=[];return window.addEventListener("message",function(e){var t=e.source;if((t===window||null===t)&&"process-tick"===e.data&&(e.stopPropagation(),n.length>0)){var r=n.shift();r()}},!0),function(e){n.push(e),window.postMessage("process-tick","*")}}return function(e){setTimeout(e,0)}}(),n.title="browser",n.browser=!0,n.env={},n.argv=[],n.binding=function(){throw new Error("process.binding is not supported")},n.cwd=function(){return"/"},n.chdir=function(){throw new Error("process.chdir is not supported")}},{}],17:[function(e,t,n){function r(){return"WebkitAppearance"in document.documentElement.style||window.console&&(console.firebug||console.exception&&console.table)||navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31}function o(){var e=arguments,t=this.useColors;if(e[0]=(t?"%c":"")+this.namespace+(t?" %c":" ")+e[0]+(t?"%c ":" ")+"+"+n.humanize(this.diff),!t)return e;var r="color: "+this.color;e=[e[0],r,"color: inherit"].concat(Array.prototype.slice.call(e,1));var o=0,i=0;return e[0].replace(/%[a-z%]/g,function(e){"%%"!==e&&(o++,"%c"===e&&(i=o))}),e.splice(i,0,r),e}function i(){return"object"==typeof console&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}function u(e){try{null==e?a.removeItem("debug"):a.debug=e}catch(t){}}function s(){var e;try{e=a.debug}catch(t){}return e}n=t.exports=e("./debug"),n.log=i,n.formatArgs=o,n.save=u,n.load=s,n.useColors=r;var a;a="undefined"!=typeof chrome&&"undefined"!=typeof chrome.storage?chrome.storage.local:window.localStorage,n.colors=["lightseagreen","forestgreen","goldenrod","dodgerblue","darkorchid","crimson"],n.formatters.j=function(e){return JSON.stringify(e)},n.enable(s())},{"./debug":18}],18:[function(e,t,n){function r(){return n.colors[f++%n.colors.length]}function o(e){function t(){}function o(){var e=o,t=+new Date,i=t-(c||t);e.diff=i,e.prev=c,e.curr=t,c=t,null==e.useColors&&(e.useColors=n.useColors()),null==e.color&&e.useColors&&(e.color=r());var u=Array.prototype.slice.call(arguments);u[0]=n.coerce(u[0]),"string"!=typeof u[0]&&(u=["%o"].concat(u));var s=0;u[0]=u[0].replace(/%([a-z%])/g,function(t,r){if("%%"===t)return t;s++;var o=n.formatters[r];if("function"==typeof o){var i=u[s];t=o.call(e,i),u.splice(s,1),s--}return t}),"function"==typeof n.formatArgs&&(u=n.formatArgs.apply(e,u));var a=o.log||n.log||console.log.bind(console);a.apply(e,u)}t.enabled=!1,o.enabled=!0;var i=n.enabled(e)?o:t;return i.namespace=e,i}function i(e){n.save(e);for(var t=(e||"").split(/[\s,]+/),r=t.length,o=0;r>o;o++)t[o]&&(e=t[o].replace(/\*/g,".*?"),"-"===e[0]?n.skips.push(new RegExp("^"+e.substr(1)+"$")):n.names.push(new RegExp("^"+e+"$")))}function u(){n.enable("")}function s(e){var t,r;for(t=0,r=n.skips.length;r>t;t++)if(n.skips[t].test(e))return!1;for(t=0,r=n.names.length;r>t;t++)if(n.names[t].test(e))return!0;return!1}function a(e){return e instanceof Error?e.stack||e.message:e}n=t.exports=o,n.coerce=a,n.disable=u,n.enable=i,n.enabled=s,n.humanize=e("ms"),n.names=[],n.skips=[],n.formatters={};var c,f=0},{ms:19}],19:[function(e,t){function n(e){var t=/^((?:\d+)?\.?\d+) *(ms|seconds?|s|minutes?|m|hours?|h|days?|d|years?|y)?$/i.exec(e);if(t){var n=parseFloat(t[1]),r=(t[2]||"ms").toLowerCase();switch(r){case"years":case"year":case"y":return n*f;case"days":case"day":case"d":return n*c;case"hours":case"hour":case"h":return n*a;case"minutes":case"minute":case"m":return n*s;case"seconds":case"second":case"s":return n*u;case"ms":return n}}}function r(e){return e>=c?Math.round(e/c)+"d":e>=a?Math.round(e/a)+"h":e>=s?Math.round(e/s)+"m":e>=u?Math.round(e/u)+"s":e+"ms"}function o(e){return i(e,c,"day")||i(e,a,"hour")||i(e,s,"minute")||i(e,u,"second")||e+" ms"}function i(e,t,n){return t>e?void 0:1.5*t>e?Math.floor(e/t)+" "+n:Math.ceil(e/t)+" "+n+"s"}var u=1e3,s=60*u,a=60*s,c=24*a,f=365.25*c;t.exports=function(e,t){return t=t||{},"string"==typeof e?n(e):t["long"]?o(e):r(e)}},{}],20:[function(e,t){t.exports="function"==typeof Object.create?function(e,t){e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}})}:function(e,t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}},{}],21:[function(e,t){"use strict";function n(){}t.exports=n},{}],22:[function(e,t){"use strict";function n(e){function t(e,t){function r(e){c[t]=e,++f===n&!a&&(a=!0,s.resolve(d,c))}i(e).then(r,function(e){a||(a=!0,s.reject(d,e))})}if("[object Array]"!==Object.prototype.toString.call(e))return o(new TypeError("must be an array"));var n=e.length,a=!1;if(!n)return i([]);for(var c=new Array(n),f=0,l=-1,d=new r(u);++l0?e.slice(n):e}function a(e){var t=e.value,n=t&&"object"==typeof t&&t._id||e.id;return n}function c(e,t,n){try{return{output:t.apply(null,n)}}catch(r){return e.emit("error",r),{error:r}}}function f(e,t){var r=e.descending?"endkey":"startkey",o=e.descending?"startkey":"endkey";if("undefined"!=typeof e[r]&&"undefined"!=typeof e[o]&&v(e[r],e[o])>0)throw new n("No rows can match your key range, reverse your start_key and end_key or set {descending : true}");if(t.reduce&&e.reduce!==!1){if(e.include_docs)throw new n("{include_docs:true} is invalid for reduce");if(e.keys&&e.keys.length>1&&!e.group&&!e.group_level)throw new n("Multi-key fetches for reduce views must use {group: true}")}if(e.group_level){if("number"!=typeof e.group_level)throw new n('Invalid value for integer: "'+e.group_level+'"');if(e.group_level<0)throw new n('Invalid value for positive integer: "'+e.group_level+'"')}}function l(e){return function(t){if(404===t.status)return e;throw t}}function d(e){function t(e,t,n){function r(){return i(d)?x.resolve(a):t.db.get(s)["catch"](l(a))}function o(e){return e.keys.length?t.db.allDocs({keys:e.keys,include_docs:!0}):x.resolve({rows:[]})}function u(e,t){for(var n=[],r={},o=0,i=t.rows.length;i>o;o++){var u=t.rows[o],s=u.doc;if(s&&(n.push(s),r[s._id]=!0,s._deleted=!f[s._id],!s._deleted)){var a=f[s._id];"value"in a&&(s.value=a.value)}}var c=Object.keys(f);return c.forEach(function(e){if(!r[e]){var t={_id:e},o=f[e];"value"in o&&(t.value=o.value),n.push(t)}}),e.keys=k.uniq(c.concat(e.keys)),n.push(e),n}var s="_local/doc_"+e,a={_id:s,keys:[]},c=n[e],f=c.indexableKeysToKeyValues,d=c.changes;return r().then(function(e){return o(e).then(function(t){return u(e,t)})})}function n(e,n,r){var o="_local/lastSeq";return e.db.get(o)["catch"](l({_id:o,seq:0})).then(function(o){var i=Object.keys(n);return x.all(i.map(function(r){return t(r,e,n)})).then(function(t){var n=k.flatten(t);return o.seq=r,n.push(o),e.db.bulkDocs({docs:n})})})}function d(e){var t="string"==typeof e?e:e.name,n=E[t];return n||(n=E[t]=new g),n}function p(e){return k.sequentialize(d(e),function(){return j(e)})()}function j(e){function t(e,t){var n={id:i._id,key:b(e)};"undefined"!=typeof t&&null!==t&&(n.value=b(t)),o.push(n)}function r(t,r){return function(){return n(e,t,r)}}var o,i,s=C(e.mapFun,t),a=e.seq||0,f=new g;return new x(function(t,n){function l(){f.finish().then(function(){e.seq=a,t()})}function d(){function t(e){n(e)}e.sourceDB.changes({conflicts:!0,include_docs:!0,style:"all_docs",since:a,limit:O}).on("complete",function(t){var n=t.results;if(!n.length)return l();for(var p={},h=0,y=n.length;y>h;h++){var g=n[h];if("_"!==g.doc._id[0]){o=[],i=g.doc,i._deleted||c(e.sourceDB,s,[i]),o.sort(u);for(var v,b={},w=0,k=o.length;k>w;w++){var x=o[w],E=[x.key,x.id];x.key===v&&E.push(w);var _=m(E);b[_]=x,v=x.key}p[g.doc._id]={indexableKeysToKeyValues:b,changes:g.changes}}a=g.seq}return f.add(r(p,a)),n.lengthu?n.slice(0,u):n),t&&0===v(t.key[0][0],n)?(t.key.push([n,e.id]),void t.value.push(e.value)):void i.push({key:[[n,e.id]],value:[e.value]})});for(var a=0,f=i.length;f>a;a++){var l=i[a],d=c(e.sourceDB,o,[l.key,l.value,!1]);l.value=d.error?null:d.output,l.key=l.key[0][0]}return{rows:s(i,n.limit,n.skip)}}function I(e,t){return k.sequentialize(d(e),function(){return S(e,t)})()}function S(e,t){function n(t){return t.include_docs=!0,e.db.allDocs(t).then(function(e){return o=e.total_rows,e.rows.map(function(e){if("value"in e.doc&&"object"==typeof e.doc.value&&null!==e.doc.value){var t=Object.keys(e.doc.value).sort(),n=["id","key","value"];if(!(n>t||t>n))return e.doc.value}var r=y.parseIndexableString(e.doc._id);return{key:r[0],id:r[1],value:"value"in e.doc?e.doc.value:null}})})}function r(n){var r;if(r=i?A(e,n,t):{total_rows:o,offset:u,rows:n},t.include_docs){var s=k.uniq(n.map(a));return e.sourceDB.allDocs({keys:s,include_docs:!0,conflicts:t.conflicts,attachments:t.attachments}).then(function(e){var t={};return e.rows.forEach(function(e){e.doc&&(t["$"+e.id]=e.doc)}),n.forEach(function(e){var n=a(e),r=t["$"+n];r&&(e.doc=r)}),r})}return r}var o,i=e.reduceFun&&t.reduce!==!1,u=t.skip||0;"undefined"==typeof t.keys||t.keys.length||(t.limit=0,delete t.keys);var s=function(e){return e.reduce(function(e,t){return e.concat(t)})};if("undefined"!=typeof t.keys){var c=t.keys,f=c.map(function(e){var t={startkey:m([e]),endkey:m([e,{}])};return n(t)});return x.all(f).then(s).then(r)}var l={descending:t.descending};if("undefined"!=typeof t.startkey&&(l.startkey=m(t.descending?[t.startkey,{}]:[t.startkey])),"undefined"!=typeof t.endkey){var d=t.inclusive_end!==!1;t.descending&&(d=!d),l.endkey=m(d?[t.endkey,{}]:[t.endkey])}if("undefined"!=typeof t.key){var p=m([t.key]),h=m([t.key,{}]);l.descending?(l.endkey=p,l.startkey=h):(l.startkey=p,l.endkey=h)}return i||("number"==typeof t.limit&&(l.limit=t.limit),l.skip=u),n(l).then(r)}function $(e){return e.get("_local/"+N).then(function(t){var n={};Object.keys(t.views).forEach(function(e){var t=o(e),r="_design/"+t[0],i=t[1];n[r]=n[r]||{},n[r][i]=!0});var r={keys:Object.keys(n),include_docs:!0};return e.allDocs(r).then(function(r){var o={};r.rows.forEach(function(e){var r=e.key.substring(8);Object.keys(n[e.key]).forEach(function(n){var i=r+"/"+n;t.views[i]||(i=n);var u=Object.keys(t.views[i]),s=e.doc&&e.doc.views&&e.doc.views[n];u.forEach(function(e){o[e]=o[e]||s})})});var i=Object.keys(o).filter(function(e){return!o[e]}),u=i.map(function(t){return k.sequentialize(d(t),function(){return e.constructor.destroy(t,e.__opts)})()});return x.all(u).then(function(){return{ok:!0}})})},l({ok:!0}))}function q(e,t,n){if("string"!=typeof t){f(n,t);var i={db:e,viewName:"temp_view/temp_view",map:t.map,reduce:t.reduce,temporary:!0,pluginName:N};return _.add(function(){return w(i).then(function(e){function t(){return e.db.destroy() -}return k.fin(p(e).then(function(){return I(e,n)}),t)})}),_.finish()}var u=t,s=o(u),a=s[0],c=s[1];return e.get("_design/"+a).then(function(t){var o=t.views&&t.views[c];if(!o)throw new r("ddoc "+t._id+" has no view named "+c);T(t,c),f(n,o);var i={db:e,viewName:u,map:o.map,reduce:o.reduce,pluginName:N};return w(i).then(function(e){return"ok"===n.stale||"update_after"===n.stale?("update_after"===n.stale&&h.nextTick(function(){p(e)}),I(e,n)):p(e).then(function(){return I(e,n)})})})}var N=e.name,C=e.mapper,D=e.reducer,T=e.ddocValidator,F=function(e,t,n){var r=this;"function"==typeof t&&(n=t,t={}),t=k.extend(!0,{},t),"function"==typeof e&&(e={map:e});var o=x.resolve().then(function(){return q(r,e,t)});return k.promisedCallback(o,n),o},M=k.callbackify(function(){var e=this;return $(e)});return{query:F,viewCleanup:M}}var p,h=e("__browserify_process"),y=e("pouchdb-collate"),g=e("./taskqueue"),v=y.collate,m=y.toIndexableString,b=y.normalizeKey,w=e("./create-view");p="undefined"!=typeof console&&"function"==typeof console.log?Function.prototype.bind.call(console.log,console):function(){};var k=e("./utils"),x=k.Promise,E={},_=new g,O=50;k.inherits(n,Error),k.inherits(r,Error),t.exports=d},{"./create-view":39,"./taskqueue":41,"./utils":43,__browserify_process:16,"pouchdb-collate":44}],41:[function(e,t){"use strict";function n(){this.promise=new r(function(e){e()})}var r=e("./utils").Promise;n.prototype.add=function(e){return this.promise=this.promise["catch"](function(){}).then(function(){return e()}),this.promise},n.prototype.finish=function(){return this.promise},t.exports=n},{"./utils":43}],42:[function(e,t){"use strict";var n=e("pouchdb-upsert").upsert;t.exports=function(e,t,r){return n.apply(e,[t,r])}},{"pouchdb-upsert":47}],43:[function(e,t,n){var r=e("__browserify_process"),o="undefined"!=typeof self?self:"undefined"!=typeof window?window:{};n.Promise="function"==typeof o.Promise?o.Promise:e("lie"),n.inherits=e("inherits"),n.extend=e("pouchdb-extend");var i=e("argsarray");n.promisedCallback=function(e,t){return t&&e.then(function(e){r.nextTick(function(){t(null,e)})},function(e){r.nextTick(function(){t(e)})}),e},n.callbackify=function(e){return i(function(t){var r=t.pop(),o=e.apply(this,t);return"function"==typeof r&&n.promisedCallback(o,r),o})},n.fin=function(e,t){return e.then(function(e){var n=t();return"function"==typeof n.then?n.then(function(){return e}):e},function(e){var n=t();if("function"==typeof n.then)return n.then(function(){throw e});throw e})},n.sequentialize=function(e,t){return function(){var n=arguments,r=this;return e.add(function(){return t.apply(r,n)})}},n.flatten=function(e){for(var t=[],n=0,r=e.length;r>n;n++)t=t.concat(e[n]);return t},n.uniq=function(e){for(var t={},n=0,r=e.length;r>n;n++)t["$"+e[n]]=!0;var o=Object.keys(t),i=new Array(o.length);for(n=0,r=o.length;r>n;n++)i[n]=o[n].substring(1);return i};var u=e("crypto"),s=e("spark-md5");n.MD5=function(e){return r.browser?s.hash(e):u.createHash("md5").update(e).digest("hex")}},{__browserify_process:16,argsarray:13,crypto:14,inherits:20,lie:24,"pouchdb-extend":46,"spark-md5":48}],44:[function(e,t,n){"use strict";function r(e){if(null!==e)switch(typeof e){case"boolean":return e?1:0;case"number":return f(e);case"string":return e.replace(/\u0002/g,"").replace(/\u0001/g,"").replace(/\u0000/g,"");case"object":var t=Array.isArray(e),r=t?e:Object.keys(e),o=-1,i=r.length,u="";if(t)for(;++oo;o++){var i=n.collate(e[o],t[o]);if(0!==i)return i}return e.length===t.length?0:e.length>t.length?1:-1}function s(e,t){return e===t?0:e>t?1:-1}function a(e,t){for(var r=Object.keys(e),o=Object.keys(t),i=Math.min(r.length,o.length),u=0;i>u;u++){var s=n.collate(r[u],o[u]);if(0!==s)return s;if(s=n.collate(e[r[u]],t[o[u]]),0!==s)return s}return r.length===o.length?0:r.length>o.length?1:-1}function c(e){var t=["boolean","number","string","object"],n=t.indexOf(typeof e);return~n?null===e?1:Array.isArray(e)?5:3>n?n+2:n+3:Array.isArray(e)?5:void 0}function f(e){if(0===e)return"1";var t=e.toExponential().split(/e\+?/),n=parseInt(t[1],10),r=0>e,o=r?"0":"2",i=(r?-n:n)-l,u=h.padLeft(i.toString(),"0",d);o+=p+u;var s=Math.abs(parseFloat(t[0]));r&&(s=10-s);var a=s.toFixed(20);return a=a.replace(/\.?0+$/,""),o+=p+a}var l=-324,d=3,p="",h=e("./utils");n.collate=function(e,t){if(e===t)return 0;e=n.normalizeKey(e),t=n.normalizeKey(t);var r=c(e),o=c(t);if(r-o!==0)return r-o;if(null===e)return 0;switch(typeof e){case"number":return e-t;case"boolean":return e===t?0:t>e?-1:1;case"string":return s(e,t)}return Array.isArray(e)?u(e,t):a(e,t)},n.normalizeKey=function(e){switch(typeof e){case"undefined":return null;case"number":return 1/0===e||e===-1/0||isNaN(e)?null:e;case"object":var t=e;if(Array.isArray(e)){var r=e.length;e=new Array(r);for(var o=0;r>o;o++)e[o]=n.normalizeKey(t[o])}else{if(e instanceof Date)return e.toJSON();if(null!==e){e={};for(var i in t)if(t.hasOwnProperty(i)){var u=t[i];"undefined"!=typeof u&&(e[i]=n.normalizeKey(u))}}}}return e},n.toIndexableString=function(e){var t="\x00";return e=n.normalizeKey(e),c(e)+p+r(e)+t},n.parseIndexableString=function(e){for(var t=[],n=[],r=0;;){var u=e[r++];if("\x00"!==u)switch(u){case"1":t.push(null);break;case"2":t.push("1"===e[r]),r++;break;case"3":var s=o(e,r);t.push(s.num),r+=s.length;break;case"4":for(var a="";;){var c=e[r];if("\x00"===c)break;a+=c,r++}a=a.replace(/\u0001\u0001/g,"\x00").replace(/\u0001\u0002/g,"").replace(/\u0002\u0002/g,""),t.push(a);break;case"5":var f={element:[],index:t.length};t.push(f.element),n.push(f);break;case"6":var l={element:{},index:t.length};t.push(l.element),n.push(l);break;default:throw new Error("bad collationIndex or unexpectedly reached end of input: "+u)}else{if(1===t.length)return t.pop();i(t,n)}}}},{"./utils":45}],45:[function(e,t,n){"use strict";function r(e,t,n){for(var r="",o=n-e.length;r.lengthn;n++){if(n===o)return 1;var i=e.charAt(n),u=t.charAt(n);if(i!==u)return u>i?-1:1}return o>r?-1:0},n.intToDecimalForm=function(e){var t=0>e,n="";do{var r=t?-Math.ceil(e%10):Math.floor(e%10);n=r+n,e=t?Math.ceil(e/10):Math.floor(e/10)}while(e);return t&&"0"!==n&&(n="-"+n),n}},{}],46:[function(e,t){"use strict";function n(e){return null===e?String(e):"object"==typeof e||"function"==typeof e?a[d.call(e)]||"object":typeof e}function r(e){return null!==e&&e===e.window}function o(e){if(!e||"object"!==n(e)||e.nodeType||r(e))return!1;try{if(e.constructor&&!p.call(e,"constructor")&&!p.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(t){return!1}var o;for(o in e);return void 0===o||p.call(e,o)}function i(e){return"function"===n(e)}function u(){for(var e=[],t=-1,n=arguments.length,r=new Array(n);++tp;p++)if(null!=(r=t[p])){l=h(r);for(u in r)if(!(u in Object.prototype)){if(l&&!v.test(u))continue;if(s=d[u],a=r[u],d===a)continue;g&&a&&(o(a)||(c=h(a)))?(c?(c=!1,f=s&&h(s)?s:[]):f=s&&o(s)?s:{},e.push({args:[g,f,a],result:{container:d,key:u}})):void 0!==a&&(h(r)&&i(a)||(d[u]=a))}}n.container[n.key]=d}for(var a={},c=["Boolean","Number","String","Function","Array","Date","RegExp","Object","Error"],f=0;f>>32-i,r)},n=function(e,n,r,o,i,u,s){return t(n&r|~n&o,e,n,i,u,s)},r=function(e,n,r,o,i,u,s){return t(n&o|r&~o,e,n,i,u,s)},o=function(e,n,r,o,i,u,s){return t(n^r^o,e,n,i,u,s)},i=function(e,n,r,o,i,u,s){return t(r^(n|~o),e,n,i,u,s)},u=function(t,u){var s=t[0],a=t[1],c=t[2],f=t[3];s=n(s,a,c,f,u[0],7,-680876936),f=n(f,s,a,c,u[1],12,-389564586),c=n(c,f,s,a,u[2],17,606105819),a=n(a,c,f,s,u[3],22,-1044525330),s=n(s,a,c,f,u[4],7,-176418897),f=n(f,s,a,c,u[5],12,1200080426),c=n(c,f,s,a,u[6],17,-1473231341),a=n(a,c,f,s,u[7],22,-45705983),s=n(s,a,c,f,u[8],7,1770035416),f=n(f,s,a,c,u[9],12,-1958414417),c=n(c,f,s,a,u[10],17,-42063),a=n(a,c,f,s,u[11],22,-1990404162),s=n(s,a,c,f,u[12],7,1804603682),f=n(f,s,a,c,u[13],12,-40341101),c=n(c,f,s,a,u[14],17,-1502002290),a=n(a,c,f,s,u[15],22,1236535329),s=r(s,a,c,f,u[1],5,-165796510),f=r(f,s,a,c,u[6],9,-1069501632),c=r(c,f,s,a,u[11],14,643717713),a=r(a,c,f,s,u[0],20,-373897302),s=r(s,a,c,f,u[5],5,-701558691),f=r(f,s,a,c,u[10],9,38016083),c=r(c,f,s,a,u[15],14,-660478335),a=r(a,c,f,s,u[4],20,-405537848),s=r(s,a,c,f,u[9],5,568446438),f=r(f,s,a,c,u[14],9,-1019803690),c=r(c,f,s,a,u[3],14,-187363961),a=r(a,c,f,s,u[8],20,1163531501),s=r(s,a,c,f,u[13],5,-1444681467),f=r(f,s,a,c,u[2],9,-51403784),c=r(c,f,s,a,u[7],14,1735328473),a=r(a,c,f,s,u[12],20,-1926607734),s=o(s,a,c,f,u[5],4,-378558),f=o(f,s,a,c,u[8],11,-2022574463),c=o(c,f,s,a,u[11],16,1839030562),a=o(a,c,f,s,u[14],23,-35309556),s=o(s,a,c,f,u[1],4,-1530992060),f=o(f,s,a,c,u[4],11,1272893353),c=o(c,f,s,a,u[7],16,-155497632),a=o(a,c,f,s,u[10],23,-1094730640),s=o(s,a,c,f,u[13],4,681279174),f=o(f,s,a,c,u[0],11,-358537222),c=o(c,f,s,a,u[3],16,-722521979),a=o(a,c,f,s,u[6],23,76029189),s=o(s,a,c,f,u[9],4,-640364487),f=o(f,s,a,c,u[12],11,-421815835),c=o(c,f,s,a,u[15],16,530742520),a=o(a,c,f,s,u[2],23,-995338651),s=i(s,a,c,f,u[0],6,-198630844),f=i(f,s,a,c,u[7],10,1126891415),c=i(c,f,s,a,u[14],15,-1416354905),a=i(a,c,f,s,u[5],21,-57434055),s=i(s,a,c,f,u[12],6,1700485571),f=i(f,s,a,c,u[3],10,-1894986606),c=i(c,f,s,a,u[10],15,-1051523),a=i(a,c,f,s,u[1],21,-2054922799),s=i(s,a,c,f,u[8],6,1873313359),f=i(f,s,a,c,u[15],10,-30611744),c=i(c,f,s,a,u[6],15,-1560198380),a=i(a,c,f,s,u[13],21,1309151649),s=i(s,a,c,f,u[4],6,-145523070),f=i(f,s,a,c,u[11],10,-1120210379),c=i(c,f,s,a,u[2],15,718787259),a=i(a,c,f,s,u[9],21,-343485551),t[0]=e(s,t[0]),t[1]=e(a,t[1]),t[2]=e(c,t[2]),t[3]=e(f,t[3])},s=function(e){var t,n=[];for(t=0;64>t;t+=4)n[t>>2]=e.charCodeAt(t)+(e.charCodeAt(t+1)<<8)+(e.charCodeAt(t+2)<<16)+(e.charCodeAt(t+3)<<24);return n},a=function(e){var t,n=[];for(t=0;64>t;t+=4)n[t>>2]=e[t]+(e[t+1]<<8)+(e[t+2]<<16)+(e[t+3]<<24);return n},c=function(e){var t,n,r,o,i,a,c=e.length,f=[1732584193,-271733879,-1732584194,271733878];for(t=64;c>=t;t+=64)u(f,s(e.substring(t-64,t)));for(e=e.substring(t-64),n=e.length,r=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],t=0;n>t;t+=1)r[t>>2]|=e.charCodeAt(t)<<(t%4<<3);if(r[t>>2]|=128<<(t%4<<3),t>55)for(u(f,r),t=0;16>t;t+=1)r[t]=0;return o=8*c,o=o.toString(16).match(/(.*?)(.{0,8})$/),i=parseInt(o[2],16),a=parseInt(o[1],16)||0,r[14]=i,r[15]=a,u(f,r),f},f=function(e){var t,n,r,o,i,s,c=e.length,f=[1732584193,-271733879,-1732584194,271733878];for(t=64;c>=t;t+=64)u(f,a(e.subarray(t-64,t)));for(e=c>t-64?e.subarray(t-64):new Uint8Array(0),n=e.length,r=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],t=0;n>t;t+=1)r[t>>2]|=e[t]<<(t%4<<3);if(r[t>>2]|=128<<(t%4<<3),t>55)for(u(f,r),t=0;16>t;t+=1)r[t]=0;return o=8*c,o=o.toString(16).match(/(.*?)(.{0,8})$/),i=parseInt(o[2],16),s=parseInt(o[1],16)||0,r[14]=i,r[15]=s,u(f,r),f},l=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"],d=function(e){var t,n="";for(t=0;4>t;t+=1)n+=l[e>>8*t+4&15]+l[e>>8*t&15];return n},p=function(e){var t;for(t=0;t>16)+(t>>16)+(n>>16);return r<<16|65535&n}),y.prototype.append=function(e){return/[\u0080-\uFFFF]/.test(e)&&(e=unescape(encodeURIComponent(e))),this.appendBinary(e),this},y.prototype.appendBinary=function(e){this._buff+=e,this._length+=e.length;var t,n=this._buff.length;for(t=64;n>=t;t+=64)u(this._state,s(this._buff.substring(t-64,t)));return this._buff=this._buff.substr(t-64),this},y.prototype.end=function(e){var t,n,r=this._buff,o=r.length,i=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];for(t=0;o>t;t+=1)i[t>>2]|=r.charCodeAt(t)<<(t%4<<3);return this._finish(i,o),n=e?this._state:p(this._state),this.reset(),n},y.prototype._finish=function(e,t){var n,r,o,i=t;if(e[i>>2]|=128<<(i%4<<3),i>55)for(u(this._state,e),i=0;16>i;i+=1)e[i]=0;n=8*this._length,n=n.toString(16).match(/(.*?)(.{0,8})$/),r=parseInt(n[2],16),o=parseInt(n[1],16)||0,e[14]=r,e[15]=o,u(this._state,e)},y.prototype.reset=function(){return this._buff="",this._length=0,this._state=[1732584193,-271733879,-1732584194,271733878],this},y.prototype.destroy=function(){delete this._state,delete this._buff,delete this._length},y.hash=function(e,t){/[\u0080-\uFFFF]/.test(e)&&(e=unescape(encodeURIComponent(e)));var n=c(e);return t?n:p(n)},y.hashBinary=function(e,t){var n=c(e);return t?n:p(n)},y.ArrayBuffer=function(){this.reset()},y.ArrayBuffer.prototype.append=function(e){var t,n=this._concatArrayBuffer(this._buff,e),r=n.length;for(this._length+=e.byteLength,t=64;r>=t;t+=64)u(this._state,a(n.subarray(t-64,t)));return this._buff=r>t-64?n.subarray(t-64):new Uint8Array(0),this},y.ArrayBuffer.prototype.end=function(e){var t,n,r=this._buff,o=r.length,i=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];for(t=0;o>t;t+=1)i[t>>2]|=r[t]<<(t%4<<3);return this._finish(i,o),n=e?this._state:p(this._state),this.reset(),n},y.ArrayBuffer.prototype._finish=y.prototype._finish,y.ArrayBuffer.prototype.reset=function(){return this._buff=new Uint8Array(0),this._length=0,this._state=[1732584193,-271733879,-1732584194,271733878],this},y.ArrayBuffer.prototype.destroy=y.prototype.destroy,y.ArrayBuffer.prototype._concatArrayBuffer=function(e,t){var n=e.length,r=new Uint8Array(n+t.byteLength);return r.set(e),r.set(new Uint8Array(t),n),r},y.ArrayBuffer.hash=function(e,t){var n=f(new Uint8Array(e));return t?n:p(n)},y})},{}]},{},[11]); \ No newline at end of file